Skip to content

Commit 433d75f

Browse files
committed
dx(doctor): flag a worktree whose node_modules lags the lockfile
Add a doctor probe and a check:affected preflight that compare node_modules/.pnpm/lock.yaml (the exact lockfile snapshot pnpm installed from) against pnpm-lock.yaml via a content hash — no subprocess. On mismatch both surfaces report the same one-liner: "node_modules was installed from a different lockfile; run pnpm install", so a stale install names its own cause instead of surfacing as bogus format diffs on files a change never touched (the #1956 incident). Closes #1963
1 parent 03c3984 commit 433d75f

7 files changed

Lines changed: 373 additions & 1 deletion

File tree

‎scripts/check-affected/run.test.ts‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import os from 'node:os';
99
import path from 'node:path';
1010
import { test } from 'node:test';
1111
import { runCmdSync } from '../../src/utils/exec.ts';
12+
import { STALE_NODE_MODULES_MESSAGE } from '../../src/utils/lockfile-install-sync.ts';
1213
import { CHECK_CATALOG } from './checks.ts';
1314
import { DEFAULT_VITEST_MAX_WORKERS } from '../lib/vitest-concurrency.ts';
1415
import { selectChecks } from './model.ts';
@@ -247,3 +248,107 @@ test('runChecks leaves coverage to CI and runs capped related tests once', async
247248
'the coverage gate is GitHub-authoritative and must not run locally',
248249
);
249250
});
251+
252+
test('runChecks fails fast on a stale install before running format or any other check', async () => {
253+
const executed: string[][] = [];
254+
const execute: CommandExecutor = async (command) => {
255+
executed.push(command);
256+
return 0;
257+
};
258+
const plan = selectChecks({
259+
changedFiles: ['packages/selectors/src/index.ts'],
260+
packageEntryFiles: [],
261+
});
262+
const code = await runChecks(plan, { scripts: ALL_SCRIPTS }, ARGS, {
263+
execute,
264+
cwd: '.',
265+
checkLockfileSync: () => ({ inSync: false, reason: 'stale' }),
266+
});
267+
assert.equal(code, 1);
268+
assert.deepEqual(executed, [], 'no check — including format — may run against a stale install');
269+
});
270+
271+
test('runChecks fails fast when node_modules was never installed in this checkout', async () => {
272+
const executed: string[][] = [];
273+
const execute: CommandExecutor = async (command) => {
274+
executed.push(command);
275+
return 0;
276+
};
277+
const plan = selectChecks({
278+
changedFiles: ['packages/selectors/src/index.ts'],
279+
packageEntryFiles: [],
280+
});
281+
const code = await runChecks(plan, { scripts: ALL_SCRIPTS }, ARGS, {
282+
execute,
283+
cwd: '.',
284+
checkLockfileSync: () => ({ inSync: false, reason: 'install-missing' }),
285+
});
286+
assert.equal(code, 1);
287+
assert.deepEqual(executed, []);
288+
});
289+
290+
test('runChecks does not block on a missing lockfile — that is a different failure than a stale install', async () => {
291+
const executed: string[][] = [];
292+
const execute: CommandExecutor = async (command) => {
293+
executed.push(command);
294+
return 0;
295+
};
296+
const plan = selectChecks({
297+
changedFiles: ['packages/selectors/src/index.ts'],
298+
packageEntryFiles: [],
299+
});
300+
const code = await runChecks(plan, { scripts: ALL_SCRIPTS }, ARGS, {
301+
execute,
302+
cwd: '.',
303+
checkLockfileSync: () => ({ inSync: false, reason: 'lockfile-missing' }),
304+
});
305+
assert.equal(code, 0);
306+
assert.ok(executed.length > 0, 'checks still run when there is nothing to compare against');
307+
});
308+
309+
test('runChecks proceeds normally when the install is in sync', async () => {
310+
const executed: string[][] = [];
311+
const execute: CommandExecutor = async (command) => {
312+
executed.push(command);
313+
return 0;
314+
};
315+
const plan = selectChecks({
316+
changedFiles: ['packages/selectors/src/index.ts'],
317+
packageEntryFiles: [],
318+
});
319+
const code = await runChecks(plan, { scripts: ALL_SCRIPTS }, ARGS, {
320+
execute,
321+
cwd: '.',
322+
checkLockfileSync: () => ({ inSync: true }),
323+
});
324+
assert.equal(code, 0);
325+
assert.ok(executed.some((command) => command.includes('format:check')));
326+
});
327+
328+
test('runChecks names the real cause on stderr instead of surfacing as an unrelated failure', async () => {
329+
const stderrChunks: string[] = [];
330+
const originalWrite = process.stderr.write.bind(process.stderr);
331+
process.stderr.write = ((chunk: string | Uint8Array) => {
332+
stderrChunks.push(chunk.toString());
333+
return true;
334+
}) as typeof process.stderr.write;
335+
336+
try {
337+
const plan = selectChecks({
338+
changedFiles: ['packages/selectors/src/index.ts'],
339+
packageEntryFiles: [],
340+
});
341+
const code = await runChecks(plan, { scripts: ALL_SCRIPTS }, ARGS, {
342+
execute: async () => 0,
343+
cwd: '.',
344+
checkLockfileSync: () => ({ inSync: false, reason: 'stale' }),
345+
});
346+
assert.equal(code, 1);
347+
assert.ok(
348+
stderrChunks.some((chunk) => chunk.includes(STALE_NODE_MODULES_MESSAGE)),
349+
`expected stderr to name the stale-install cause, got: ${stderrChunks.join('')}`,
350+
);
351+
} finally {
352+
process.stderr.write = originalWrite;
353+
}
354+
});

‎scripts/check-affected/run.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,11 @@ import fs from 'node:fs';
99
import path from 'node:path';
1010
import { pathToFileURL } from 'node:url';
1111
import { runCmdStreaming, runCmdSync } from '../../src/utils/exec.ts';
12+
import {
13+
checkLockfileInstallSync,
14+
STALE_NODE_MODULES_MESSAGE,
15+
type LockfileInstallSyncResult,
16+
} from '../../src/utils/lockfile-install-sync.ts';
1217
import { parseScriptArgs } from '../lib/cli-args.ts';
1318
import { runEntrypoint } from '../lib/cli-entrypoint.ts';
1419
import {
@@ -184,9 +189,24 @@ export async function runChecks(
184189
plan: CheckPlan,
185190
pkg: PackageJson,
186191
args: Args,
187-
options: { cwd?: string; execute?: CommandExecutor; changedFiles?: readonly string[] } = {},
192+
options: {
193+
cwd?: string;
194+
execute?: CommandExecutor;
195+
changedFiles?: readonly string[];
196+
checkLockfileSync?: (cwd: string) => LockfileInstallSyncResult;
197+
} = {},
188198
): Promise<number> {
189199
const cwd = options.cwd ?? repoRoot;
200+
const checkLockfileSync = options.checkLockfileSync ?? checkLockfileInstallSync;
201+
// Fast preflight, before format (first in the catalog) or any other check gets a
202+
// chance to run: a stale install (#1956) makes oxfmt/oxlint/tsc misbehave in ways
203+
// that look like real diffs/failures on files the change never touched. Naming the
204+
// real cause here means an agent never "fixes" formatting that was never wrong.
205+
const lockfileSync = checkLockfileSync(cwd);
206+
if (!lockfileSync.inSync && lockfileSync.reason !== 'lockfile-missing') {
207+
reportStaleInstall(lockfileSync.reason);
208+
return 1;
209+
}
190210
const execute = options.execute ?? streamingExecutor;
191211
const runnable = plan.checks.map(getCheckSpec).filter((spec: CheckSpec) => spec.localRunnable);
192212
const skipped = plan.checks.map(getCheckSpec).filter((spec: CheckSpec) => !spec.localRunnable);
@@ -212,6 +232,16 @@ export async function runChecks(
212232
return 0;
213233
}
214234

235+
function reportStaleInstall(reason: 'install-missing' | 'stale'): void {
236+
process.stderr.write(`\ncheck:affected: ${STALE_NODE_MODULES_MESSAGE}\n`);
237+
process.stderr.write(
238+
reason === 'install-missing'
239+
? '(no node_modules/.pnpm/lock.yaml found — this checkout was never installed)\n'
240+
: '(node_modules/.pnpm/lock.yaml disagrees with pnpm-lock.yaml)\n',
241+
);
242+
process.stderr.write('Run `agent-device doctor` for more detail.\n');
243+
}
244+
215245
// Where a check the local run skips is authoritative. A parked check has no automatic
216246
// lane; say so instead of printing an empty job list.
217247
function describeOwner(id: CheckId, ciJobs: ReadonlyMap<CheckId, string[]>): string {
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import assert from 'node:assert/strict';
2+
import fs from 'node:fs';
3+
import path from 'node:path';
4+
import { test } from 'vitest';
5+
import { mkdtempForTestSync } from '../../../__tests__/test-utils/tmp-dir.ts';
6+
import { STALE_NODE_MODULES_MESSAGE } from '../../../utils/lockfile-install-sync.ts';
7+
import { nodeModulesLockfileCheck } from '../session-doctor-node-modules.ts';
8+
9+
function writeLockfile(root: string, content: string): void {
10+
fs.writeFileSync(path.join(root, 'pnpm-lock.yaml'), content);
11+
}
12+
13+
function writeInstalledSnapshot(root: string, content: string): void {
14+
const dir = path.join(root, 'node_modules', '.pnpm');
15+
fs.mkdirSync(dir, { recursive: true });
16+
fs.writeFileSync(path.join(dir, 'lock.yaml'), content);
17+
}
18+
19+
test('node-modules doctor check passes when the installed snapshot matches the checked-out lockfile', () => {
20+
const root = mkdtempForTestSync('agent-device-doctor-node-modules-sync-');
21+
writeLockfile(root, 'lockfileVersion: 9.0\n');
22+
writeInstalledSnapshot(root, 'lockfileVersion: 9.0\n');
23+
24+
const check = nodeModulesLockfileCheck(root);
25+
assert.equal(check.id, 'node-modules');
26+
assert.equal(check.status, 'pass');
27+
assert.match(check.summary, /matches pnpm-lock\.yaml/);
28+
});
29+
30+
test('node-modules doctor check fails with the stale-install message when hashes disagree', () => {
31+
const root = mkdtempForTestSync('agent-device-doctor-node-modules-stale-');
32+
writeLockfile(root, 'lockfileVersion: 9.0\nfoo: bar\n');
33+
writeInstalledSnapshot(root, 'lockfileVersion: 9.0\n');
34+
35+
const check = nodeModulesLockfileCheck(root);
36+
assert.equal(check.status, 'fail');
37+
assert.equal(check.summary, STALE_NODE_MODULES_MESSAGE);
38+
assert.equal(check.command, 'pnpm install');
39+
assert.deepEqual(check.evidence, { repoRoot: root, reason: 'stale' });
40+
});
41+
42+
test('node-modules doctor check fails with the stale-install message when node_modules was never installed here', () => {
43+
const root = mkdtempForTestSync('agent-device-doctor-node-modules-missing-install-');
44+
writeLockfile(root, 'lockfileVersion: 9.0\n');
45+
46+
const check = nodeModulesLockfileCheck(root);
47+
assert.equal(check.status, 'fail');
48+
assert.equal(check.summary, STALE_NODE_MODULES_MESSAGE);
49+
assert.deepEqual(check.evidence, { repoRoot: root, reason: 'install-missing' });
50+
});
51+
52+
test('node-modules doctor check stays informational when the checkout has no lockfile at all', () => {
53+
const root = mkdtempForTestSync('agent-device-doctor-node-modules-missing-lockfile-');
54+
55+
const check = nodeModulesLockfileCheck(root);
56+
assert.equal(check.status, 'warn');
57+
assert.match(check.summary, /pnpm-lock\.yaml not found/);
58+
});
59+
60+
test("node-modules doctor check defaults to this checkout's own root, matching real doctor wiring", () => {
61+
// session-doctor.ts calls nodeModulesLockfileCheck() with no argument; this repo's own
62+
// install is expected to be in sync while the suite runs (pnpm install was run for it).
63+
const check = nodeModulesLockfileCheck();
64+
assert.equal(check.id, 'node-modules');
65+
assert.equal(check.status, 'pass');
66+
});
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import {
2+
checkLockfileInstallSync,
3+
STALE_NODE_MODULES_MESSAGE,
4+
} from '../../utils/lockfile-install-sync.ts';
5+
import { findProjectRoot } from '../../utils/version.ts';
6+
import type { DoctorCheck } from '@agent-device/contracts/observability';
7+
8+
export function nodeModulesLockfileCheck(repoRoot: string = findProjectRoot()): DoctorCheck {
9+
const result = checkLockfileInstallSync(repoRoot);
10+
if (result.inSync) {
11+
return {
12+
id: 'node-modules',
13+
status: 'pass',
14+
summary: 'node_modules matches pnpm-lock.yaml.',
15+
};
16+
}
17+
if (result.reason === 'lockfile-missing') {
18+
return {
19+
id: 'node-modules',
20+
status: 'warn',
21+
summary: 'pnpm-lock.yaml not found; cannot verify node_modules is in sync.',
22+
evidence: { repoRoot, reason: result.reason },
23+
};
24+
}
25+
return {
26+
id: 'node-modules',
27+
status: 'fail',
28+
summary: STALE_NODE_MODULES_MESSAGE,
29+
hint: 'Run this from every worktree whose node_modules might have drifted, not just the main checkout.',
30+
command: 'pnpm install',
31+
evidence: { repoRoot, reason: result.reason },
32+
};
33+
}

‎src/daemon/handlers/session-doctor.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
resolveDoctorDeviceForAppCheck,
1616
} from './session-doctor-device.ts';
1717
import { probeMetro } from './session-doctor-metro.ts';
18+
import { nodeModulesLockfileCheck } from './session-doctor-node-modules.ts';
1819
import {
1920
readDoctorOptions,
2021
remoteConnectionChecks,
@@ -65,6 +66,7 @@ export async function handleDoctorCommand(params: {
6566
summary: `agent-device ${readVersion()} using ${stateDir}`,
6667
evidence: { version: readVersion(), stateDir },
6768
},
69+
nodeModulesLockfileCheck(),
6870
...remoteConnectionChecks(req, { required: options.remote }),
6971
...sessionChecks(sessionStore, sessionName, session, { remote: options.remote }),
7072
);
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import assert from 'node:assert/strict';
2+
import fs from 'node:fs';
3+
import path from 'node:path';
4+
import { test } from 'vitest';
5+
import { mkdtempForTestSync } from '../__tests__/test-utils/tmp-dir.ts';
6+
import { checkLockfileInstallSync } from './lockfile-install-sync.ts';
7+
8+
function writeLockfile(root: string, content: string): void {
9+
fs.writeFileSync(path.join(root, 'pnpm-lock.yaml'), content);
10+
}
11+
12+
function writeInstalledSnapshot(root: string, content: string): void {
13+
const dir = path.join(root, 'node_modules', '.pnpm');
14+
fs.mkdirSync(dir, { recursive: true });
15+
fs.writeFileSync(path.join(dir, 'lock.yaml'), content);
16+
}
17+
18+
test('reports in sync when the installed snapshot byte-matches the checked-out lockfile', () => {
19+
const root = mkdtempForTestSync('agent-device-lockfile-sync-match-');
20+
writeLockfile(root, 'lockfileVersion: 9.0\nimporters:\n .: {}\n');
21+
writeInstalledSnapshot(root, 'lockfileVersion: 9.0\nimporters:\n .: {}\n');
22+
23+
assert.deepEqual(checkLockfileInstallSync(root), { inSync: true });
24+
});
25+
26+
test('reports stale when the installed snapshot content differs from the checked-out lockfile', () => {
27+
const root = mkdtempForTestSync('agent-device-lockfile-sync-stale-');
28+
writeLockfile(
29+
root,
30+
'lockfileVersion: 9.0\nimporters:\n .:\n dependencies:\n newDep: 1.0.0\n',
31+
);
32+
writeInstalledSnapshot(root, 'lockfileVersion: 9.0\nimporters:\n .: {}\n');
33+
34+
assert.deepEqual(checkLockfileInstallSync(root), { inSync: false, reason: 'stale' });
35+
});
36+
37+
test('reports install-missing when node_modules/.pnpm/lock.yaml does not exist', () => {
38+
const root = mkdtempForTestSync('agent-device-lockfile-sync-no-install-');
39+
writeLockfile(root, 'lockfileVersion: 9.0\n');
40+
41+
assert.deepEqual(checkLockfileInstallSync(root), { inSync: false, reason: 'install-missing' });
42+
});
43+
44+
test('reports install-missing for a fresh worktree that has no node_modules directory at all', () => {
45+
const root = mkdtempForTestSync('agent-device-lockfile-sync-fresh-worktree-');
46+
writeLockfile(root, 'lockfileVersion: 9.0\n');
47+
// Deliberately no node_modules directory — the exact state of a brand new
48+
// `git worktree add`, before its first `pnpm install`.
49+
assert.equal(fs.existsSync(path.join(root, 'node_modules')), false);
50+
51+
assert.deepEqual(checkLockfileInstallSync(root), { inSync: false, reason: 'install-missing' });
52+
});
53+
54+
test('reports lockfile-missing when the checkout has no pnpm-lock.yaml', () => {
55+
const root = mkdtempForTestSync('agent-device-lockfile-sync-no-lockfile-');
56+
writeInstalledSnapshot(root, 'lockfileVersion: 9.0\n');
57+
58+
assert.deepEqual(checkLockfileInstallSync(root), { inSync: false, reason: 'lockfile-missing' });
59+
});
60+
61+
test('is not fooled by two worktrees sharing the same repo but different lockfile states', () => {
62+
// The failure mode from #1963: a worktree's own node_modules must be compared against
63+
// that same worktree's own pnpm-lock.yaml, never another checkout's.
64+
const worktreeA = mkdtempForTestSync('agent-device-lockfile-sync-worktree-a-');
65+
const worktreeB = mkdtempForTestSync('agent-device-lockfile-sync-worktree-b-');
66+
writeLockfile(worktreeA, 'lockfileVersion: 9.0\nimporters:\n .: {}\n');
67+
writeInstalledSnapshot(worktreeA, 'lockfileVersion: 9.0\nimporters:\n .: {}\n');
68+
writeLockfile(
69+
worktreeB,
70+
'lockfileVersion: 9.0\nimporters:\n .:\n dependencies:\n newDep: 1.0.0\n',
71+
);
72+
writeInstalledSnapshot(worktreeB, 'lockfileVersion: 9.0\nimporters:\n .: {}\n');
73+
74+
assert.deepEqual(checkLockfileInstallSync(worktreeA), { inSync: true });
75+
assert.deepEqual(checkLockfileInstallSync(worktreeB), { inSync: false, reason: 'stale' });
76+
});

0 commit comments

Comments
 (0)