Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
chore: drop the dead gitignored-lockfile delete path from the reinstall helpers (#5691)
Adam Eivy80b04f28aa15
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex a816ecae62..090f942801 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -135,6 +135,7 @@ export const WINDOWS_CONTRACT_TESTS = [export const ALWAYS_RUN_TESTS = ['scripts/agent-instructions-files.test.js','scripts/direct-invocation-drift.test.js',+ 'scripts/ensure-deps.test.js','scripts/node-version-drift.test.js','scripts/repo-scan-guards.test.js','scripts/tailnet-identity-leak.test.js',diff --git a/scripts/ensure-deps.js b/scripts/ensure-deps.jsindex 3bd5a5ac04..37168924a4 100644--- a/scripts/ensure-deps.js+++ b/scripts/ensure-deps.js@@ -9,6 +9,7 @@ import { createHash } from 'crypto';import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { rebuildTrusted } from './trusted-rebuilds.js';+import { isDirectlyInvoked } from './lib/directInvocation.js';// Node refuses to spawn npm's `.cmd` shim under `shell:false` (CVE-2024-27980),// so every npm spawn goes through this wrap. Safe to import before `npm install`// has ever run — bufferedSpawn's whole import graph is Node builtins only.@@ -31,7 +32,7 @@ const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');// `git pull` + `npm start` path, which has no pull context to diff against.const HASH_FILE = join(ROOT, 'data', 'deps-hashes.json');-const WORKSPACES = [+export const WORKSPACES = [{ dir: ROOT, label: 'root' },{ dir: join(ROOT, 'client'), label: 'client' },{ dir: join(ROOT, 'server'), label: 'server' },@@ -62,21 +63,6 @@ function saveHashes(hashes) {}}-// True only when the lockfile is gitignored (the per-install client/server-// locks). A tracked root lockfile is kept — it's consistent with package.json.-function lockfileIsGitignored(dir) {- try {- execFileSync('git', ['check-ignore', '-q', join(dir, 'package-lock.json')], {- cwd: ROOT,- stdio: 'ignore',- windowsHide: true- });- return true;- } catch {- return false;- }-}-// Filesystem fallback for the no-baseline case (first run after this feature// lands, or a fresh manual checkout): npm writes node_modules/.package-lock.json// at the end of every install, so its mtime is the last-install time. If@@ -95,15 +81,14 @@ function manifestNewerThanInstall(dir) {}}-function cleanWorkspaceDeps(dir) {+// Wipe `node_modules` ONLY. Every workspace lockfile ensure-deps touches (root,+// client, server, autofixer) is tracked, so `npm install` re-resolves from the+// committed lock — which is the state we want. Deleting it would let a clean+// reinstall silently float transitive versions past the `overrides` pins.+export function cleanWorkspaceDeps(dir) {try {rmSync(join(dir, 'node_modules'), { recursive: true, force: true });} catch { /* best effort */ }- if (lockfileIsGitignored(dir)) {- try {- rmSync(join(dir, 'package-lock.json'), { force: true });- } catch { /* best effort */ }- }}// The trusted install-script allowlist lives in scripts/trusted-rebuilds.js —@@ -140,73 +125,79 @@ function install(dir, label) {}}-const storedHashes = loadHashes();-let hashesDirty = false;-let needed = false;--for (const { dir, label } of WORKSPACES) {- const currentHash = pkgHash(dir);- const nodeModulesMissing = !existsSync(join(dir, 'node_modules'));- const storedHash = storedHashes[label];- // With a stored baseline, a differing hash means the manifest moved since the- // last install. Without one (first run after this feature lands, or a fresh- // manual checkout), fall back to the install-marker mtime so a `git pull` +- // `npm start` that changed package.json over a present node_modules is still- // caught — instead of silently seeding the stale tree.- const depsChanged = storedHash != null- ? currentHash != null && storedHash !== currentHash- : !nodeModulesMissing && manifestNewerThanInstall(dir);-- if (nodeModulesMissing || depsChanged) {- if (depsChanged) {- // Clean whenever the manifest changed — even if node_modules is already- // gone — so the stale gitignored lockfile is removed and npm resolves the- // tree from scratch instead of reusing the old per-install lock.- console.log(`🧹 ${label} package.json changed since last install — clean reinstall...`);- cleanWorkspaceDeps(dir);- } else {- console.log(`📦 Missing node_modules for ${label} — installing...`);+// Import-safe driver: the module exposes its helpers to scripts/ensure-deps.test.js,+// and only performs installs when run as `node scripts/ensure-deps.js`.+function main() {+ const storedHashes = loadHashes();+ let hashesDirty = false;+ let needed = false;++ for (const { dir, label } of WORKSPACES) {+ const currentHash = pkgHash(dir);+ const nodeModulesMissing = !existsSync(join(dir, 'node_modules'));+ const storedHash = storedHashes[label];+ // With a stored baseline, a differing hash means the manifest moved since the+ // last install. Without one (first run after this feature lands, or a fresh+ // manual checkout), fall back to the install-marker mtime so a `git pull` ++ // `npm start` that changed package.json over a present node_modules is still+ // caught — instead of silently seeding the stale tree.+ const depsChanged = storedHash != null+ ? currentHash != null && storedHash !== currentHash+ : !nodeModulesMissing && manifestNewerThanInstall(dir);++ if (nodeModulesMissing || depsChanged) {+ if (depsChanged) {+ // Clean whenever the manifest changed — even if node_modules is already+ // gone — so npm rebuilds the tree from the committed lockfile instead of+ // layering onto a tree resolved against the previous manifest.+ console.log(`🧹 ${label} package.json changed since last install — clean reinstall...`);+ cleanWorkspaceDeps(dir);+ } else {+ console.log(`📦 Missing node_modules for ${label} — installing...`);+ }+ if (!install(dir, label)) process.exit(1);+ needed = true;+ }++ if (currentHash != null && storedHashes[label] !== currentHash) {+ storedHashes[label] = currentHash;+ hashesDirty = true;}- if (!install(dir, label)) process.exit(1);- needed = true;}- if (currentHash != null && storedHashes[label] !== currentHash) {- storedHashes[label] = currentHash;- hashesDirty = true;+ // Verify critical packages exist even if node_modules dirs were present+ // Grouped by workspace to avoid redundant installs+ const criticalPackages = [+ { dir: ROOT, label: 'root', pkg: 'pm2/package.json' },+ { dir: join(ROOT, 'client'), label: 'client', pkg: 'vite/bin/vite.js' },+ { dir: join(ROOT, 'server'), label: 'server', pkg: 'express/package.json' },+ { dir: join(ROOT, 'server'), label: 'server', pkg: 'pg/package.json' },+ ];++ const criticalByDir = new Map();+ for (const { dir, label, pkg } of criticalPackages) {+ if (!criticalByDir.has(dir)) criticalByDir.set(dir, { label, pkgs: [] });+ criticalByDir.get(dir).pkgs.push(pkg);}-}-// Verify critical packages exist even if node_modules dirs were present-// Grouped by workspace to avoid redundant installs-const criticalPackages = [- { dir: ROOT, label: 'root', pkg: 'pm2/package.json' },- { dir: join(ROOT, 'client'), label: 'client', pkg: 'vite/bin/vite.js' },- { dir: join(ROOT, 'server'), label: 'server', pkg: 'express/package.json' },- { dir: join(ROOT, 'server'), label: 'server', pkg: 'pg/package.json' },-];+ for (const [dir, { label, pkgs }] of criticalByDir) {+ const missing = pkgs.filter(pkg => !existsSync(join(dir, 'node_modules', ...pkg.split('/'))));+ if (!missing.length) continue;-const criticalByDir = new Map();-for (const { dir, label, pkg } of criticalPackages) {- if (!criticalByDir.has(dir)) criticalByDir.set(dir, { label, pkgs: [] });- criticalByDir.get(dir).pkgs.push(pkg);-}+ console.log(`📦 Missing ${missing.map(p => p.split('/')[0]).join(', ')} in ${label} — reinstalling deps...`);+ if (!install(dir, label)) process.exit(1);+ needed = true;-for (const [dir, { label, pkgs }] of criticalByDir) {- const missing = pkgs.filter(pkg => !existsSync(join(dir, 'node_modules', ...pkg.split('/'))));- if (!missing.length) continue;+ const stillMissing = pkgs.filter(pkg => !existsSync(join(dir, 'node_modules', ...pkg.split('/'))));+ if (stillMissing.length) {+ console.error(`❌ Still missing in ${label} after reinstall: ${stillMissing.map(p => p.split('/')[0]).join(', ')}`);+ process.exit(1);+ }+ }- console.log(`📦 Missing ${missing.map(p => p.split('/')[0]).join(', ')} in ${label} — reinstalling deps...`);- if (!install(dir, label)) process.exit(1);- needed = true;+ if (hashesDirty) saveHashes(storedHashes);- const stillMissing = pkgs.filter(pkg => !existsSync(join(dir, 'node_modules', ...pkg.split('/'))));- if (stillMissing.length) {- console.error(`❌ Still missing in ${label} after reinstall: ${stillMissing.map(p => p.split('/')[0]).join(', ')}`);- process.exit(1);- }+ if (needed) console.log('✅ Dependencies verified');}-if (hashesDirty) saveHashes(storedHashes);--if (needed) console.log('✅ Dependencies verified');+if (isDirectlyInvoked(import.meta.url)) main();diff --git a/scripts/ensure-deps.test.js b/scripts/ensure-deps.test.jsnew file mode 100644index 0000000000..a01610fd0d--- /dev/null+++ b/scripts/ensure-deps.test.js@@ -0,0 +1,86 @@+/**+ * Destructive-action guard for the clean-reinstall path (issue #5691).+ *+ * `cleanWorkspaceDeps` (and its `update.sh` / `update.ps1` twins) used to delete+ * `package-lock.json` whenever `git check-ignore` said the lockfile was ignored+ * — correct while the client and server locks were gitignored, dead since all+ * four workspace lockfiles became tracked. Restoring that delete would be silent+ * and dangerous: a `git pull` that changes a `package.json` would wipe the+ * committed lock and let `npm install` re-resolve transitive versions past the+ * `overrides` pins (which is how the node-tar / engine.io advisories are held+ * down), with no other detector in the suite.+ *+ * The behavioural test alone cannot catch that regression — the old code ran+ * `git check-ignore` with `cwd` pinned to the repo root, so it always answered+ * "not ignored" for a temp directory outside the checkout. So the premise (every+ * workspace lockfile is tracked) and the absence of the delete are asserted too.+ */+import { describe, expect, it } from 'vitest';+import { execFileSync } from 'child_process';+import { mkdtempSync, mkdirSync, writeFileSync, existsSync, rmSync, readFileSync } from 'fs';+import { tmpdir } from 'os';+import { dirname, join, relative } from 'path';+import { fileURLToPath } from 'url';+import { cleanWorkspaceDeps, WORKSPACES } from './ensure-deps.js';++const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++/** Every helper that wipes a workspace's installed deps before a reinstall. */+const REINSTALL_HELPERS = ['scripts/ensure-deps.js', 'update.sh', 'update.ps1'];++/** True when `source` can delete a workspace lockfile, or asks git whether it may. */+const deletesLockfile = (source) => (+ /check-ignore/.test(source)+ || /(rmSync|rm -f|rm -rf|Remove-Item)[^\n]*package-lock\.json/.test(source)+);++describe('clean reinstall keeps the committed lockfile (#5691)', () => {+ it('wipes node_modules and keeps the lockfile', () => {+ const dir = mkdtempSync(join(tmpdir(), 'portos-ensure-deps-'));+ try {+ mkdirSync(join(dir, 'node_modules', 'left-over'), { recursive: true });+ writeFileSync(join(dir, 'package-lock.json'), '{"lockfileVersion":3}');++ cleanWorkspaceDeps(dir);++ expect(existsSync(join(dir, 'node_modules'))).toBe(false);+ expect(existsSync(join(dir, 'package-lock.json'))).toBe(true);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ // The premise the deletion removal rests on. If a workspace lockfile is ever+ // untracked again, this fails first and says so — rather than the reinstall+ // path quietly reverting to a per-install lock nobody can reproduce.+ it('tracks a lockfile for every workspace ensure-deps cleans', () => {+ const tracked = new Set(+ execFileSync('git', ['ls-files', '*package-lock.json'], { cwd: REPO_ROOT, encoding: 'utf8' })+ .split('\n')+ .filter(Boolean)+ );++ expect(WORKSPACES.length).toBeGreaterThan(0);+ for (const { dir, label } of WORKSPACES) {+ const lockPath = [relative(REPO_ROOT, dir), 'package-lock.json'].filter(Boolean).join('/');+ expect(tracked, `${label} lockfile must stay tracked`).toContain(lockPath);+ }+ });++ // The detector decides whether the scan below means anything, so it is+ // verified against both spellings of the removed path rather than trusted.+ it('deletesLockfile flags the removed delete path in every helper language', () => {+ expect(deletesLockfile("if (lockfileIsGitignored(dir)) rmSync(join(dir, 'package-lock.json'), { force: true });")).toBe(true);+ expect(deletesLockfile('if git check-ignore -q "$dir/package-lock.json"; then rm -f "$dir/package-lock.json"; fi')).toBe(true);+ expect(deletesLockfile('Remove-Item -Force "$Dir/package-lock.json" -ErrorAction SilentlyContinue')).toBe(true);+ expect(deletesLockfile("rmSync(join(dir, 'node_modules'), { recursive: true, force: true });")).toBe(false);+ });++ it('no reinstall helper deletes a workspace lockfile', () => {+ const offenders = REINSTALL_HELPERS.filter(+ (relativePath) => deletesLockfile(readFileSync(join(REPO_ROOT, relativePath), 'utf8'))+ );++ expect(offenders).toEqual([]);+ });+});diff --git a/update.ps1 b/update.ps1index ff22de7eb3..a296b56ba3 100644--- a/update.ps1+++ b/update.ps1@@ -106,19 +106,16 @@ function Test-WorkspaceDepsChanged {}# Wipe a workspace's installed deps so the next `npm install` resolves the tree-# from scratch. node_modules is always removed; the lockfile is removed ONLY-# when it's gitignored (the per-install client/server locks) — a tracked root-# or autofixer lock was just pulled and is already consistent with the new-# package.json, so keep it for reproducible resolution.+# from scratch. node_modules ONLY — every workspace lockfile this script touches+# (root, client, server, autofixer) is tracked, so the pull just brought one that+# is already consistent with the new package.json. Keep it: reinstalling from the+# committed lock is reproducible, while deleting it would let transitive versions+# float past the `overrides` pins.function Clear-WorkspaceDeps {param([string]$Dir)if (Test-Path "$Dir/node_modules") {Remove-Item -Recurse -Force "$Dir/node_modules" -ErrorAction SilentlyContinue}- git check-ignore -q "$Dir/package-lock.json" 2>$null- if ($LASTEXITCODE -eq 0 -and (Test-Path "$Dir/package-lock.json")) {- Remove-Item -Force "$Dir/package-lock.json" -ErrorAction SilentlyContinue- }}# Resilient npm install — retries once after cleaning node_modules on failure@@ -140,7 +137,7 @@ function Safe-Install {Invoke-Logged npm install --no-saveif ($LASTEXITCODE -eq 0) { Pop-Location; return }- Write-SafeHost "⚠️ npm install failed for $Label — cleaning node_modules + package-lock.json and retrying..." -ForegroundColor Yellow+ Write-SafeHost "⚠️ npm install failed for $Label — cleaning node_modules and retrying..." -ForegroundColor YellowPop-LocationClear-WorkspaceDeps -Dir $DirPush-Location $Dirdiff --git a/update.sh b/update.shindex 58a53a4cad..f4873d8d15 100755--- a/update.sh+++ b/update.sh@@ -38,16 +38,14 @@ log "==================================="log ""# Wipe a workspace's installed deps so the next `npm install` resolves the tree-# from scratch. node_modules is always removed; the lockfile is removed ONLY-# when it's gitignored (the per-install client/server locks) — a tracked root-# or autofixer lock was just pulled and is already consistent with the new-# package.json, so keep it for reproducible resolution.+# from scratch. node_modules ONLY — every workspace lockfile this script touches+# (root, client, server, autofixer) is tracked, so the pull just brought one that+# is already consistent with the new package.json. Keep it: reinstalling from the+# committed lock is reproducible, while deleting it would let transitive versions+# float past the `overrides` pins.clean_workspace_deps() {local dir="$1"rm -rf "$dir/node_modules"- if git check-ignore -q "$dir/package-lock.json" 2>/dev/null; then- rm -f "$dir/package-lock.json"- fi}# Whether the pulled update changed this workspace's package.json. When it did,@@ -99,7 +97,7 @@ safe_install() {return 0fi- log "⚠️ npm install failed for $label — cleaning node_modules + package-lock.json and retrying..."+ log "⚠️ npm install failed for $label — cleaning node_modules and retrying..."clean_workspace_deps "$dir"if (cd "$dir" && run npm install --no-save); thenreturn 0