Skip to content

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

fix: detect stale dependencies before pregate (#12248)

Adam Eivyd37fe1d3c0e5
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md
index 46c14081c8..7fb7f2999a 100644
--- a/docs/CONTRIBUTING.md
+++ b/docs/CONTRIBUTING.md
@@ -87,6 +87,8 @@ See [VERSIONING.md](./VERSIONING.md) for full details.
3. Push `main` to `release` branch to trigger GitHub Release workflow
4. Before pushing, follow [Regular Development](./VERSIONING.md#regular-development): verify your branch/upstream and working-tree state, preserve unrelated work, and explicitly fetch the intended base for comparison (the tracking branch may differ); integrate it only for conflicts, enforced branch policy, or evidenced integration risk. Run `npm run pregate` after any rebase and before every push. See [AGENTS.md's Git Workflow](../AGENTS.md#git-workflow) for the full contract.
+Pregate first checks installed package versions against all four workspace lockfiles without modifying dependency trees. Stale, missing, or unreadable evidence stops lint/tests with a reconciliation diagnostic. Ordinary worktree links must be repaired only in their owning source checkout; a separate clone with its own locked installs is also suitable for validation. `--plan-only` prints the plan without checking installed dependencies.
+
Pregate proves only the stages it runs; it does not replace required CI or resource-dependent checks. A full-suite plan runs only the always-run guards unless `--full` is supplied; DB suites, Windows, client build, and boot smoke are reported but not run by pregate.
PRs run the browser suites' smoke profile; the `[fidelity]` cases run nightly
diff --git a/scripts/ensure-deps.js b/scripts/ensure-deps.js
index d7014ac2be..11c7a6304d 100644
--- a/scripts/ensure-deps.js
+++ b/scripts/ensure-deps.js
@@ -3,13 +3,14 @@
* Repairs missing or stale dependencies only in workspaces that own their tree.
* Handles ENOTEMPTY npm bug by retrying with clean node_modules.
*/
-import { existsSync, rmSync, readFileSync, writeFileSync, mkdirSync, statSync, lstatSync } from 'fs';
+import { existsSync, rmSync, readFileSync, writeFileSync, mkdirSync, statSync } from 'fs';
import { execFileSync } from 'child_process';
import { createHash } from 'crypto';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { rebuildTrusted, patchInstalledDependencies } from './trusted-rebuilds.js';
import { isDirectlyInvoked } from './lib/directInvocation.js';
+import { dependencyWorkspaces, hasLinkedDependencies } from './lib/workspaceDependencies.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.
@@ -33,12 +34,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');
-export const WORKSPACES = [
- { dir: ROOT, label: 'root' },
- { dir: join(ROOT, 'client'), label: 'client' },
- { dir: join(ROOT, 'server'), label: 'server' },
- { dir: join(ROOT, 'autofixer'), label: 'autofixer' }
-];
+export const WORKSPACES = dependencyWorkspaces(ROOT);
function dependencyHash(dir) {
const pkgPath = join(dir, 'package.json');
@@ -143,7 +139,7 @@ function main() {
// checking inside the repair loop could already mutate an earlier workspace.
// lstat also catches dangling links and Windows directory junctions.
for (const { dir, label } of WORKSPACES) {
- if (lstatSync(join(dir, 'node_modules'), { throwIfNoEntry: false })?.isSymbolicLink()) {
+ if (hasLinkedDependencies(dir)) {
console.error(`⛔ Refusing dependency repair: ${label}/node_modules is linked. Run startup in the source checkout; use its workspace binaries for worktree tests.`);
process.exitCode = 1;
return;
diff --git a/scripts/ensure-deps.test.js b/scripts/ensure-deps.test.js
index f3c8477f43..5ce590f412 100644
--- a/scripts/ensure-deps.test.js
+++ b/scripts/ensure-deps.test.js
@@ -97,6 +97,7 @@ describe('startup dependency reconciliation', () => {
writeFileSync(join(root, 'package.json'), '{"type":"module"}');
copyFileSync(join(REPO_ROOT, 'scripts', 'ensure-deps.js'), join(root, 'scripts', 'ensure-deps.js'));
copyFileSync(join(REPO_ROOT, 'scripts', 'lib', 'directInvocation.js'), join(root, 'scripts', 'lib', 'directInvocation.js'));
+ copyFileSync(join(REPO_ROOT, 'scripts', 'lib', 'workspaceDependencies.js'), join(root, 'scripts', 'lib', 'workspaceDependencies.js'));
writeFileSync(join(root, 'scripts', 'trusted-rebuilds.js'), `
import { writeFileSync } from 'fs';
import { join } from 'path';
diff --git a/scripts/lib/workspaceDependencies.js b/scripts/lib/workspaceDependencies.js
new file mode 100644
index 0000000000..101ff64ca7
--- /dev/null
+++ b/scripts/lib/workspaceDependencies.js
@@ -0,0 +1,69 @@
+/** Read-only workspace/dependency ownership shared by startup and pregate. */
+import { lstatSync, readFileSync, realpathSync } from 'fs';
+import { join } from 'path';
+
+export function dependencyWorkspaces(root) {
+ return ['root', 'client', 'server', 'autofixer'].map(label => ({
+ label, dir: label === 'root' ? root : join(root, label),
+ }));
+}
+
+export function hasLinkedDependencies(dir) {
+ return lstatSync(join(dir, 'node_modules'), { throwIfNoEntry: false })?.isSymbolicLink() ?? false;
+}
+
+function readJson(path) {
+ try {
+ return { value: JSON.parse(readFileSync(path, 'utf8')) };
+ } catch (error) {
+ return { error: error.code === 'ENOENT' ? 'missing' : 'unreadable', code: error.code ?? 'invalid JSON' };
+ }
+}
+
+/**
+ * Compare actual manifests, not install receipts: old receipts and npm's hidden
+ * lockfile cannot establish which package versions are currently on disk.
+ * Absent optional dependencies are valid npm installs (platform / --omit=optional).
+ */
+export function inspectWorkspaceDependencies({ dir, label }) {
+ const issues = [];
+ let linked = false;
+ let owner = dir;
+ try {
+ linked = hasLinkedDependencies(dir);
+ owner = join(realpathSync(join(dir, 'node_modules')), '..');
+ } catch (error) {
+ issues.push(`node_modules ${error.code === 'ENOENT' ? 'missing' : 'unreadable'} (${error.code})${linked ? ' — linked target unavailable' : ''}`);
+ }
+ const lock = readJson(join(dir, 'package-lock.json'));
+ if (lock.error) {
+ issues.push(`package-lock.json ${lock.error} (${lock.code})`);
+ } else if (!lock.value?.packages || !lock.value.packages['']) {
+ issues.push('package-lock.json unreadable (requires a packages map with a root entry)');
+ } else if (issues.length === 0) {
+ for (const [path, expected] of Object.entries(lock.value.packages)) {
+ if (path === '') continue;
+ if (!/^(?:node_modules\/)(?:[^/]+\/)*[^/]+$/.test(path)
+ || path.split('/').some(part => part === '..' || part === '.')
+ || typeof expected?.version !== 'string' || expected.link) {
+ issues.push(`${path}: unreadable lock entry (expected a locked package version)`);
+ continue;
+ }
+ const installed = readJson(join(dir, path, 'package.json'));
+ if (installed.error) {
+ if (installed.error === 'missing' && expected.optional) continue;
+ issues.push(`${path}: ${installed.error} package.json (${installed.code}); expected ${expected.version}`);
+ } else if (typeof installed.value?.version !== 'string') {
+ issues.push(`${path}: unreadable package version; expected ${expected.version}`);
+ } else if (installed.value.version !== expected.version) {
+ issues.push(`${path}: expected ${expected.version}, installed ${installed.value.version}`);
+ }
+ }
+ }
+ return { label, linked, owner, issues };
+}
+
+/** Returns diagnostics only; never installs, patches, deletes or writes receipts. */
+export function dependencyConsistencyProblems(root) {
+ return dependencyWorkspaces(root).map(inspectWorkspaceDependencies).filter(result => result.issues.length > 0);
+}
diff --git a/scripts/pregate.js b/scripts/pregate.js
index 2ebd4a476f..a9c0673937 100644
--- a/scripts/pregate.js
+++ b/scripts/pregate.js
@@ -41,6 +41,7 @@ import { ALWAYS_RUN_TESTS, structuralTestsFor } from './ci-test-plan.js';
import { assertNodeVersion } from './checkNodeVersion.js';
import { isDirectlyInvoked } from './lib/directInvocation.js';
import { needsBrowserFidelity } from './lib/browserFidelity.js';
+import { dependencyConsistencyProblems } from './lib/workspaceDependencies.js';
const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
@@ -386,6 +387,19 @@ async function main() {
process.exit(0);
}
+ const dependencyProblems = dependencyConsistencyProblems(REPO_ROOT);
+ if (dependencyProblems.length > 0) {
+ console.error('❌ Dependency consistency preflight failed; lint/tests have not run.');
+ for (const { label, linked, owner, issues } of dependencyProblems) {
+ console.error(` ${label} (${linked ? 'linked' : 'owned'} node_modules):\n${issues.map(issue => ` ${issue}`).join('\n')}`);
+ console.error(linked
+ ? ` Reconcile dependencies in the owning source checkout (${owner}), or validate in a separate clone with its own locked installs. Never run npm install/ci through worktree links.`
+ : ` Reconcile this checkout's dependencies from its committed lockfiles (npm ci in the owning workspace), then rerun pregate.`);
+ }
+ process.exit(1);
+ }
+ console.log('✅ Dependency consistency preflight passed (installed package versions match workspace locks).');
+
for (const stage of stages) {
console.log(`▶️ ${stage.name}`);
const result = await runStage(stage);
diff --git a/scripts/pregate.test.js b/scripts/pregate.test.js
index 520f1cff41..4634c669e8 100644
--- a/scripts/pregate.test.js
+++ b/scripts/pregate.test.js
@@ -9,10 +9,10 @@
*/
import { afterAll, afterEach, beforeAll, beforeEach, describe, it, expect } from 'vitest';
import { execFileSync, spawn, spawnSync } from 'child_process';
-import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, symlinkSync, existsSync, lstatSync, readdirSync } from 'fs';
import { tmpdir } from 'os';
import { cp } from 'fs/promises';
-import { dirname, join } from 'path';
+import { delimiter, dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { destroyGitSandbox, makeGitSandbox } from '../server/lib/gitTestRepo.js';
import {
@@ -108,6 +108,7 @@ describe('pregate hidden-content invocation', () => {
const write = (path, content) => writeFileSync(join(root, path), content);
const run = (...args) => spawnSync(process.execPath, ['scripts/pregate.js', '--base', base, ...args], {
cwd: root, encoding: 'utf8',
+ env: { ...process.env, PATH: `${join(scratch, 'fake-bin')}${delimiter}${process.env.PATH}` },
});
const snapshot = () => ({
status: git('--no-optional-locks', 'status', '--porcelain=v1', '-z', '--untracked-files=all'),
@@ -125,7 +126,7 @@ describe('pregate hidden-content invocation', () => {
'scripts/pregate.js', 'scripts/checkNodeVersion.js', 'scripts/scan-diff-hidden-content.js',
'scripts/ci-test-plan.js', 'scripts/ci-base-sha.js', 'server/lib/staticImportGraph.js',
'scripts/lib/directInvocation.js', 'scripts/lib/browserFidelity.js', 'scripts/lib/browserTestProfiles.js', 'scripts/lib/githubOutput.js', 'scripts/lib/dbTestFiles.js',
- 'scripts/lib/browserSuites.js',
+ 'scripts/lib/browserSuites.js', 'scripts/lib/workspaceDependencies.js',
'server/lib/diffHiddenContentScan.js', 'server/lib/modelAbuseGuard.js',
'server/lib/textUtils.js',
]) {
@@ -133,6 +134,10 @@ describe('pregate hidden-content invocation', () => {
copyFileSync(join(REPO_ROOT, path), join(root, path));
}
write('package.json', '{"type":"module"}\n');
+ for (const workspace of ['', 'client', 'server', 'autofixer']) {
+ mkdirSync(join(root, workspace, 'node_modules'), { recursive: true });
+ write(join(workspace, 'package-lock.json'), JSON.stringify({ packages: { '': {} } }));
+ }
mkdirSync(join(root, 'docs'));
write(trackedPath, clean);
git('add', '--all');
@@ -160,6 +165,77 @@ describe('pregate hidden-content invocation', () => {
if (template?.scratch) await destroyGitSandbox(template.scratch);
});
+ // This regression catches stale inherited packages before any lint/test child
+ // can produce a misleading product failure or repair the shared source tree.
+ it.each(['matching', 'stale', 'missing-package', 'unreadable-package', 'dangling'])(
+ 'checks %s linked dependencies read-only before executing stages', (state) => {
+ const shared = join(scratch, 'source', 'server', 'node_modules');
+ const installed = join(shared, 'express', 'package.json');
+ const modules = join(root, 'server', 'node_modules');
+ mkdirSync(dirname(installed), { recursive: true });
+ writeFileSync(installed, state === 'unreadable-package' ? '{broken' : JSON.stringify({ version: state === 'stale' ? '5.2.1' : '5.3.0' }));
+ if (state === 'missing-package') rmSync(installed);
+ const sourceReceipt = join(scratch, 'source', 'deps-hashes.json');
+ writeFileSync(sourceReceipt, '{"server":"legacy"}');
+ writeFileSync(join(shared, '.package-lock.json'), '{"packages":{"node_modules/express":{"version":"5.3.0"}}}');
+ const sourceSnapshot = () => Object.fromEntries(readdirSync(join(scratch, 'source'), { recursive: true })
+ .filter(path => lstatSync(join(scratch, 'source', path)).isFile())
+ .map(path => [path, readFileSync(join(scratch, 'source', path), 'utf8')]));
+ const before = sourceSnapshot();
+ const fakeBin = join(scratch, 'fake-bin');
+ mkdirSync(fakeBin);
+ writeFileSync(join(fakeBin, 'npm'), '#!/usr/bin/env node\nrequire("fs").writeFileSync("unexpected-npm", "called");', { mode: 0o755 });
+ writeFileSync(join(fakeBin, 'npm.cmd'), '@node "%~dp0npm" %*\r\n');
+ rmSync(modules, { recursive: true });
+ const target = state === 'dangling' ? join(scratch, 'absent-deps') : shared;
+ symlinkSync(target, modules, process.platform === 'win32' ? 'junction' : 'dir');
+ write('server/package-lock.json', JSON.stringify({ packages: {
+ '': {}, 'node_modules/express': { version: '5.3.0' },
+ 'node_modules/optional-platform-package': { version: '1.0.0', optional: true },
+ } }));
+ // Changing scripts selects full lint; any accidental stage run leaves a
+ // durable marker. Startup/package-manager repair is a separate trap.
+ for (const name of ['run-ci-lint.js', 'run-ci-tests.js', 'ensure-deps.js']) {
+ write(`scripts/${name}`, `import { writeFileSync } from 'fs'; writeFileSync('unexpected-stage', '${name}');`);
+ }
+ const result = run();
+ if (state === 'matching') {
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).toContain('Dependency consistency preflight passed');
+ expect(existsSync(join(root, 'unexpected-stage'))).toBe(true);
+ } else {
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('server (linked node_modules)');
+ expect(result.stderr).toContain('owning source checkout');
+ expect(result.stderr).toContain('Never run npm install/ci through worktree links');
+ const diagnostic = {
+ stale: 'expected 5.3.0, installed 5.2.1',
+ 'missing-package': 'missing package.json (ENOENT)',
+ 'unreadable-package': 'unreadable package.json (invalid JSON)',
+ dangling: 'linked target unavailable',
+ }[state];
+ expect(result.stderr).toContain(diagnostic);
+ expect(existsSync(join(root, 'unexpected-stage'))).toBe(false);
+ }
+ expect(lstatSync(modules).isSymbolicLink()).toBe(true);
+ expect(sourceSnapshot()).toEqual(before);
+ expect(existsSync(join(root, 'unexpected-npm'))).toBe(false);
+ expect(readFileSync(sourceReceipt, 'utf8')).toBe('{"server":"legacy"}');
+ if (state === 'dangling') expect(existsSync(target)).toBe(false);
+ },
+ );
+
+ it('refuses missing and unreadable lock evidence rather than calling it a match', () => {
+ rmSync(join(root, 'client', 'package-lock.json'));
+ write('autofixer/package-lock.json', '{invalid');
+ const result = run();
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('client (owned node_modules)');
+ expect(result.stderr).toContain('package-lock.json missing (ENOENT)');
+ expect(result.stderr).toContain('autofixer (owned node_modules)');
+ expect(result.stderr).toContain('package-lock.json unreadable (invalid JSON)');
+ });
+
it.each(['committed', 'staged', 'unstaged', 'untracked'])(
'rejects %s hidden content without changing files or staging state', (state) => {
const path = state === 'untracked' ? 'docs/untracked note.md' : trackedPath;
@@ -526,7 +602,7 @@ describe('the gate end to end', () => {
'scripts/pregate.js', 'scripts/checkNodeVersion.js', 'scripts/scan-diff-hidden-content.js',
'scripts/ci-test-plan.js', 'scripts/ci-base-sha.js', 'server/lib/staticImportGraph.js',
'scripts/lib/directInvocation.js', 'scripts/lib/browserFidelity.js', 'scripts/lib/browserTestProfiles.js', 'scripts/lib/githubOutput.js', 'scripts/lib/dbTestFiles.js',
- 'scripts/lib/browserSuites.js',
+ 'scripts/lib/browserSuites.js', 'scripts/lib/workspaceDependencies.js',
'server/lib/diffHiddenContentScan.js', 'server/lib/modelAbuseGuard.js',
'server/lib/textUtils.js',
]) {