fix(#3057): make a guard's failure distinguishable from its benign result — Wave 1 (#3088)

* fix(#3057): refuse the write when the duplicate scan cannot complete

writeManifest documents itself as a fail-closed duplicate guard: if any
existing manifest shares plan_id with a different, non-terminal job_id it must
refuse, because dispatching again would duplicate the external job.

It could not honour that. The scan reads every sibling manifest looking for the
duplicate, and an unreadable or unparseable sibling was `continue`d past. If
the corrupt file was the one holding the live duplicate, the scan found nothing
and a duplicate external job dispatched.

The asymmetry is what gives it away: a malformed TARGET refused with
malformed_existing because clobbering is unacceptable, while a malformed
SIBLING was skipped — yet siblings are the only thing the duplicate check
reads.

Adds a scan_incomplete verdict that refuses and names the offending file, so an
operator can quarantine or repair it. Fail-closed alone would let one stale
corrupt manifest wedge every dispatch for that planning dir permanently; naming
the file is what makes refusing survivable. malformed_existing is untouched, so
the target/sibling distinction stays visible. The docstring is updated — it
previously stated a rule the function did not keep.

memFs() gains an optional failReads map so these branches are reachable at all;
they had zero coverage because the fake could not express a per-file read
fault. The signature is additive and every existing caller is unchanged.

The regression is proved by a pair, not a single test. A control writes a
readable sibling holding a genuine non-terminal duplicate and asserts
duplicate_plan_id, establishing the scenario is real; the regression then makes
that same path unreadable and asserts scan_incomplete. A first draft of this
test used a corrupt-JSON fixture containing no plan_id at all while its comment
claimed otherwise — it duplicated the unparseable-sibling case and proved
nothing, which is the defect class this phase exists to remove.

Refs #3051

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(#3057): make a guard's failure distinguishable from its benign result

Wave 1 of the negative-space backfill: the branches where a guard that could
not verify something reported the same value it reports when everything is
fine. That indistinguishability is the defect; every fix here makes the two
states tellable apart, and every test proves it with a pair — one for the
failure, one for the benign case. A single test cannot establish that two
states are distinguishable, which is the whole property being fixed.

state.cts phaseInventoryProvider returned null for both a real disk-scan
failure and a genuinely empty phases dir, so `state rebuild` could report
success while phase-table reconciliation never ran. It now returns a
discriminated result and the CLI surfaces phase_inventory_scan_failed plus a
reason. The reason field turned out never to have been wired into the emitted
JSON at all — it existed only as an internal variable — so a test could only
assert on the operator-facing note. It is a real field now.

state.cts treated an unreadable lock body the same as an empty one, applying
the 1-second stealable floor. A lock we cannot read is not a lock we know is
stale; an unreadable body is now held to the deadman ceiling like a live
holder.

verification.cts findStaleVerificationSummary returned null on any fs, scan or
clock failure — meaning "not stale". It now returns a discriminated
StaleCheckResult and the caller records that the check was indeterminate.

git-base-branch resolveBaseBranch returned 'main' both when no candidate branch
existed and when every git tier timed out. A diagnostics variant now reports
whether the answer was verified, and the CLI writes an unverified-fallback note
to stderr. The stdout contract five workflows parse is untouched.

worktree-safety snapshotWorktreeInventory left exists:true when statSync threw,
so a guard that could not check reported the worktree present; exists is now
tri-state and a stat failure surfaces as an 'unverified' finding.
planWorktreePrune reported 'no_worktrees' for a parse failure, which is not the
same as an empty list — and it drives a prune. It now reports 'parse_failed'.

Fixing the inventory change exposed a second fail-open in verify.cts: the
validate-health consumer silently dropped findings whose kind it did not
recognise, so the new kind would have vanished. That is closed too — worth
noting that the survey enumerated producers of degraded verdicts, not consumers
that discard them.

worktree-base-ref and state-transition gain the distinguishing signal without
changing what they do: headAbsenceVerified, and a phase-inventory scan meta.
Whether those guards should ACT differently is a product question this change
does not answer, and both are flagged rather than quietly settled.

rescueSummaryArtifacts is left alone: rescuing on an uncertain cat-file is
deliberate per #2556. It now has tests proving it, and a recorded negative
finding — git cat-file -e returns 128 for both "absent from HEAD" and a fatal
error, so "uncertain" and "certain-and-fine" are not separable at the git
level.

Refs #3051

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(#3057): assert typed values, not rendered text

Ten assertions in the rebuild CLI suite matched substrings of produced output —
STATE.md body fields, a markdown table row, an audit-log heading, and JSON keys
read as text. CONTRIBUTING prohibits that: if the code under test produces
text, the test asserts on its structured surface instead.

No production surface had to be built. Every one already existed and was
already compiled into bin/lib: stateExtractField for body fields,
parseMarkdownTable for the phase table, collectSection for the audit-log
section, and result.data.log — already a typed RebuildLogEntry[]. The tests
were matching rendered text sitting next to the structured data.

One of those assertions was passing for the wrong reason. `stdout.includes
('rebuilt')` matched the JSON KEY name, not a value: the dry-run path emits
`mutated` and the real path emits `rebuilt`, so it would have passed whether
the value was true or false. It now asserts the value.

external-job's refusal already had to name the offending file — that naming is
why the fail-closed variant is survivable rather than a permanent wedge — but
the tests proved it by substring of a prose message. The failure result now
carries offendingPath as its own field and the tests assert it by value. The
human message is unchanged; operators read it.

Array membership is left alone. `phaseIds.includes('99')` and
`result.updated.includes('Completed Phases')` are membership checks on real
arrays, not text matching, and converting them would weaken nothing and clarify
nothing.

Refs #3051

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(#3057): execute acquireStateLock instead of grepping its source

The non-EEXIST lock test asserted on the TEXT of the built .cjs and never
called acquireStateLock. It carried an allow-test-rule: architectural-invariant
exemption to permit that. A source grep proves a literal is present in a file,
not that the behaviour works — it is weaker than a liveness test, which at
least runs the code, and it was the only coverage the fatal-errno path had.

Replaced with tests that inject the errno through fs and assert what actually
happens: a fatal EACCES propagates out of acquireStateLock with zero backoff
sleeps, while EAGAIN/EINTR/EINVAL/EIO/ENOENT/ESTALE/EPERM/EBUSY retry once and
succeed. The exemption is removed and its allowlist entry with it.

One old assertion is deliberately not carried over: it checked the retryable
errnos were expressed as a Set rather than an inline literal. That is a shape
check with no runtime signature; the behavioural tests fail if the code reverts
to the old inline check, which is the regression it was really guarding.

The #3057 lock-body tests move into that same file rather than a new one, which
is what lint-test-file-count asks for and puts every acquireStateLock test in
one place.

Refs #3051

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(#3057): surface an indeterminate staleness check to its callers

An isolated review caught an inconsistency inside this wave. Two of the three
"add the distinguishing signal" fixes wire through to something a user sees:
git base-branch writes an unverified-fallback diagnostic to stderr, and an
unverifiable worktree surfaces as a W020 finding. The third set
staleCheckIndeterminate on readVerificationStatus's result and nothing read it.

A signal nobody consumes leaves the fail-open exactly as silent as before: the
staleness check could fail and the operator saw precisely what they would see
if the answer were genuinely "not stale". That is the defect this issue exists
to remove, so it is not defensible as scaffolding when its two siblings in the
same change already wire through.

All five callers now surface it, each through the channel it already had rather
than a mechanism imposed uniformly: phase complete adds it to its existing
warnings array and, on the blocked path, as an additive note on the error text;
init and roadmap carry it as a field on output they already emit; the UAT
report carries it without ever gating passed/blockers; workstream inventory
takes an injectable writeDiagnostic mirroring the git base-branch idiom,
because its return shape had nowhere to hang a per-phase field without
rippling the builder's types.

The routing decision is unchanged everywhere. What changes is only that a
caller and an operator can now tell a failed check from a completed one.

That diagnostic carries structured meta rather than being asserted by regex —
the default still writes only the human message to stderr, but tests assert
phaseDir and reason by value. Two earlier assertions in this branch were
converted the same way; this was the last raw-text assertion left.

Also records a scope correction: the completePhaseCore guards now compare
stateReplaceField's result to the body instead of testing truthiness, so a
field whose substitution produced identical text no longer reports as updated.
That is a real behaviour fix, not the signal-only change this file was
described as carrying, and its tests cover both the changed and unchanged
cases.

Refs #3051

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(#3057): bound two heavy subprocesses for a loaded bench, not an idle one

The remote matrix surfaced three failures unrelated to this branch's changes.
All were bad tests, and a re-run would have hidden every one of them.

The reviewer-flags parse block bounded bash -> node -> a full gsd-tools cold
start at 5 seconds. On a bench running thirty thousand tests in parallel that
is not a hang, it is a busy machine. Raised to 30s, matching the convention
sibling suites already use for script invocations, with a comment saying what
the budget covers so nobody tightens it back. Two further copies of the same
5-second spawn in the same file had the identical defect and are raised too —
they were not in the failure report, but they will be next time.

The fragment-propagation test bounded npm run regen:derived — a full build plus
eight generators, the heaviest subprocess in the suite — at five minutes, and
node22 was killed near the end. The captured output proves it: every generator
had written its files and gen:install-tree had emitted all fifteen runtimes
before the kill. Raised to fifteen minutes.

That failure read as `null !== 0`, which says nothing. status null means killed,
not a non-zero exit, and the two want different responses: one is a timeout to
size correctly, the other is a real build break. The assertion now distinguishes
them and names the signal.

Neither test's assertions were weakened and no retry was added. A retry here
would suppress exactly the signal the timeout exists to produce.

Refs #3051

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(#3057): capture fd 1 through the mock tracker, not a raw reassignment

The phase suite reported zero test results on both lanes while running for five
and a half minutes and exiting 1. No assertion text, no stderr, four events for
the whole file: enqueue, start, dequeue, complete. That shape is not a failing
assertion — it is the runner being unable to read the child at all, because it
parses its event stream from the child's stdout.

The cause was the capture helper reassigning fs.writeSync directly. Proven
rather than assumed: a standalone probe patched fs.writeSync and called
process.stdout.write, and the interception fired only when fd 1 resolved to a
FILE, not when it was a pipe. The remote runner captures the event stream to a
file, so a helper that was invisible against a pipe swallowed the reporter's own
output on the bench. That is also why the two sibling suites wired the same way
in this change pass cleanly — they use the mock tracker, the seam io.test.cjs
established for this exact function.

The helper now uses t.mock.method with an explicit restore after each call, so
teardown belongs to node:test rather than a second hand-rolled implementation,
and the interception cannot outlive the one synchronous call it wraps even if
that call throws. Ten call sites thread the test context through; three test
callbacks gained the parameter they lacked.

The three B3 tests are untouched — same assertions, same fault injection. Only
how the context reaches the helper changed.

Refs #3051

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(#3057): capture phase-complete output from a subprocess, not fd 1

Two attempts to make in-process fd-1 interception safe both failed on the
bench. The suite reported zero test results on either lane while exiting 1 —
four events for the whole file — because the runner parses its event stream
from the child's stdout, and process.stdout.write routes through fs.writeSync
whenever fd 1 resolves to a file, which is how the runner captures. Patching
that seam anywhere in a file can therefore destroy the file's own reporting,
and tightening the window only moved the runtime from 326s to 125s without
recovering a single event.

So the interception is gone rather than tuned. The helper now spawns gsd-tools
as a real subprocess and reads stdout the way the OS already gives it to us,
which is what the rest of the suite does. It asserts the command succeeded
before parsing, so a genuine failure can no longer present as a JSON parse
error.

The two fault-injecting tests could not survive that move as written: a
subprocess cannot see a mock installed in the parent. Instead of reinstating
the interception they now produce the fault on disk — the summary artifact is
created as a dangling symlink, so the staleness check's real statSync throws
inside the child. That is a more honest fixture than a mock in any case, since
it is a condition a user's tree can actually be in. Skipped on Windows, matching
the existing symlink precedent in the write-guard suite.

Three further call sites turned out to depend on parent-process writeFileSync
mocks the subprocess could not see. Those call the CJS function directly, which
is what they always wanted — they never needed stdout at all.

Refs #3051

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(#3057): one name for one signal, one encoding for one distinction

Standards review found four things this branch introduced, all of them
inconsistencies with itself rather than with the repo.

One upstream bit reached its consumers under three names —
verification_stale_check_indeterminate in two modules, the same value with
"stale" dropped in a third, and stderr only in the fourth. Standardised on the
long name wherever it is a field. The workstream inventory keeps its stderr
channel, since its return shape has nowhere to hang a per-phase field without
rippling the builder's types, but it now says the same word for the same thing.

worktree-safety encoded one three-way distinction two ways in a single file: a
named union for a finding's kind, and boolean|null for an inventory entry's
existence. The second is now a named union too.

Two assertions matched human prose because the blocked and non-blocked
completion paths carried no typed field for the signal. Both now assert typed
values. The first round of this fix added the field but left the regex beside
it, which is the banned pattern sitting next to its own replacement; the second
removed it and added an assertion on the reason enum so nothing was lost.

The remaining two were reasoned away before being fixed, and both reasons were
bad. "No typed surface exists" is the condition CONTRIBUTING says to fix by
adding one — it took three lines. "The file already does this dozens of times"
is not licence to add instance number thirty-one; a convention that violates a
documented rule is debt, not precedent.

Vocabulary differing across DIFFERENT modules is left alone: CONTEXT.md rejects
a single shared result envelope, so per-module shapes are precedented, and a
baseline smell does not outrank a documented standard.

A census of every line this branch adds to a test file now finds no regex or
substring assertion on produced prose: 87 strictEqual, 25 ok (all non-empty or
shape guards), 12 equal, 3 throws (all typed err.code predicates), 3
deepStrictEqual, 2 notStrictEqual.

Refs #3051

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore(#3057): backfill changeset pr number to 3088

---------

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-08-05 16:00:52 -04:00
committed by GitHub
parent 589a9b29b0
commit 53ea8e0664
32 changed files with 2238 additions and 337 deletions

View File

@@ -185,8 +185,9 @@ test('parseSacctRow parses [jobid, state] columns', () => {
// ─── writeManifest (fail-closed duplicate guard + fs injection) ────────────────
function memFs(files = {}) {
function memFs(files = {}, opts = {}) {
const store = new Map(Object.entries(files));
const failReads = new Map(Object.entries(opts.failReads || {}));
return {
mkdirSync: () => undefined,
readdirSync: (d) => {
@@ -194,6 +195,9 @@ function memFs(files = {}) {
return Array.isArray(set) ? set : [];
},
readFileSync: (p) => {
if (failReads.has(p)) {
throw new Error(failReads.get(p));
}
if (!store.has(p)) { const e = new Error('enoent'); e.code = 'ENOENT'; throw e; }
return store.get(p);
},
@@ -268,6 +272,129 @@ test('writeManifest fails closed on a malformed existing manifest', () => {
assert.strictEqual(res.kind, 'malformed_existing');
});
// ─── writeManifest — negative-space: an incomplete duplicate scan (#3057) ─────
// A corrupt/unreadable SIBLING manifest must not be silently skipped: the
// duplicate scan cannot be trusted to have inspected it, so the write must
// refuse rather than risk dispatching a duplicate external job.
test('an unreadable sibling manifest refuses the write', () => {
// A1
const dir = path.join('.planning', 'async-jobs');
const siblingPath = path.join(dir, '99999.json');
const clock = { nowIso: () => '2020-06-15T12:00:00.000Z' };
const fs = memFs(
{ [dir]: ['99999.json'] },
{ failReads: { [siblingPath]: 'eio: input/output error' } },
);
const manifest = buildManifest(baseInput(), { clock });
const res = writeManifest(manifest, '.planning', { fs, clock });
assert.strictEqual(res.ok, false);
assert.strictEqual(res.kind, 'scan_incomplete');
assert.strictEqual(res.offendingPath, siblingPath, 'offendingPath must name the unreadable file');
});
test('an unparseable sibling manifest refuses the write', () => {
// A2
const dir = path.join('.planning', 'async-jobs');
const siblingPath = path.join(dir, '99999.json');
const clock = { nowIso: () => '2020-06-15T12:00:00.000Z' };
const fs = memFs({ [dir]: ['99999.json'], [siblingPath]: '{not json' });
const manifest = buildManifest(baseInput(), { clock });
const res = writeManifest(manifest, '.planning', { fs, clock });
assert.strictEqual(res.ok, false);
assert.strictEqual(res.kind, 'scan_incomplete');
assert.strictEqual(res.offendingPath, siblingPath, 'offendingPath must name the unparseable file');
});
test('target and sibling failures stay distinct kinds', () => {
// A3
const dir = path.join('.planning', 'async-jobs');
const targetPath = path.join(dir, '12345.json');
const clock = { nowIso: () => '2020-06-15T12:00:00.000Z' };
const fs = memFs({ [dir]: ['12345.json'], [targetPath]: '{not json' });
const manifest = buildManifest(baseInput(), { clock });
const res = writeManifest(manifest, '.planning', { fs, clock });
assert.strictEqual(res.ok, false);
assert.strictEqual(res.kind, 'malformed_existing', 'the TARGET failure must stay malformed_existing, not scan_incomplete');
});
// A4 (paired): prove the sibling really holds a duplicate (control), then
// prove that making that SAME content unreadable still refuses (regression).
test('control: a readable sibling with a non-terminal duplicate plan_id is duplicate_plan_id', () => {
// A4a — control. Same construction as the "FAILS CLOSED on duplicate
// plan_id" test above: valid JSON, same plan_id, different job_id,
// non-terminal status. This establishes the sibling content genuinely
// triggers the duplicate guard when it CAN be read.
const dir = path.join('.planning', 'async-jobs');
const siblingPath = path.join(dir, '99999.json');
const clock = { nowIso: () => '2020-06-15T12:00:00.000Z' };
const duplicate = buildManifest({ ...baseInput(), job_id: '99999' }, { clock });
const fs = memFs({ [dir]: ['99999.json'], [siblingPath]: JSON.stringify(duplicate) });
const manifest = buildManifest(baseInput(), { clock });
const res = writeManifest(manifest, '.planning', { fs, clock });
assert.strictEqual(res.ok, false);
assert.strictEqual(res.kind, 'duplicate_plan_id', 'the sibling content must be a real duplicate trigger when readable');
});
test('a corrupt sibling can no longer hide a duplicate dispatch', () => {
// A4b — the bug, as a test. Same sibling PATH as the control above, which
// that test proves can hold a genuine non-terminal duplicate for this
// plan_id. Here the read itself faults (opts.failReads), so no content is
// reachable at all — and that is the point: the guard now refuses on ANY
// unreadable sibling precisely because it cannot know whether that file
// was the duplicate. The control supplies the "it could have been"; this
// supplies the "and we no longer gamble on it".
//
// Before the fix, an unreadable sibling was `continue`d past, the
// duplicate was never seen, and this returned ok:true — dispatching a
// duplicate external job.
const dir = path.join('.planning', 'async-jobs');
const siblingPath = path.join(dir, '99999.json');
const clock = { nowIso: () => '2020-06-15T12:00:00.000Z' };
const fs = memFs(
{ [dir]: ['99999.json'] },
{ failReads: { [siblingPath]: 'eio: input/output error' } },
);
const manifest = buildManifest(baseInput(), { clock });
const res = writeManifest(manifest, '.planning', { fs, clock });
assert.strictEqual(res.ok, false, 'a corrupt sibling must refuse, not silently permit a possible duplicate dispatch');
assert.strictEqual(res.kind, 'scan_incomplete');
});
test('happy path unaffected', () => {
// A5
const dir = path.join('.planning', 'async-jobs');
const clock = { nowIso: () => '2020-06-15T12:00:00.000Z' };
const fs = memFs({ [dir]: [] });
const manifest = buildManifest(baseInput(), { clock });
const res = writeManifest(manifest, '.planning', { fs, clock });
assert.strictEqual(res.ok, true);
});
test('a terminal prior job is still allowed', () => {
// A6
const dir = path.join('.planning', 'async-jobs');
const otherPath = path.join(dir, '99999.json');
const clock = { nowIso: () => '2020-06-15T12:00:00.000Z' };
const dead = buildManifest({ ...baseInput(), job_id: '99999', status: 'failed', terminal_details: { code: 1 } }, { clock });
const fs = memFs({ [dir]: ['99999.json'], [otherPath]: JSON.stringify(dead) });
const manifest = buildManifest(baseInput(), { clock });
const res = writeManifest(manifest, '.planning', { fs, clock });
assert.strictEqual(res.ok, true, 'the duplicate guard only protects against re-dispatching live work');
});
test('a directory read failure is io_error, not scan_incomplete', () => {
// A7
const clock = { nowIso: () => '2020-06-15T12:00:00.000Z' };
const fs = memFs({}, { failReads: {} });
fs.readdirSync = () => { throw new Error('eio: input/output error'); };
const manifest = buildManifest(baseInput(), { clock });
const res = writeManifest(manifest, '.planning', { fs, clock });
assert.strictEqual(res.ok, false);
assert.strictEqual(res.kind, 'io_error');
});
// ─── Property-based (CLAUDE.md: parsers/contracts need a fast-check test) ─────
test('property: mapSlurmState is total and idempotent over the known alphabet', () => {

View File

@@ -1181,14 +1181,24 @@ test('regenDerivedPropagatesSingleFragmentEditWithNoSecondSourceSurface', (t) =>
cwd: overlay,
encoding: 'utf8',
env: installerEnv(),
timeout: 300000,
// `regen:derived` chains a full `npm run build` plus eight generators —
// the single heaviest subprocess in this suite. 300_000 (5min) was
// observed to be killed (status: null) near the very end of a genuinely
// completed run on a loaded bench (linux-node22), not from a real hang.
// 900_000 (15min) is deliberately generous so this can never again flake
// on load while still catching a true hang.
timeout: 900000,
maxBuffer: 64 * 1024 * 1024,
});
assert.equal(
regen.status,
0,
`npm run regen:derived must succeed inside the copy-mode overlay\n` +
`stdout: ${regen.stdout}\nstderr: ${regen.stderr}`,
regen.status === null
? `npm run regen:derived was KILLED (status: null, signal: ${regen.signal}) inside the copy-mode ` +
`overlay — likely a timeout, not a build failure; the captured output below may show the build ` +
`actually completed\nstdout: ${regen.stdout}\nstderr: ${regen.stderr}`
: `npm run regen:derived must succeed inside the copy-mode overlay (exit ${regen.status})\n` +
`stdout: ${regen.stdout}\nstderr: ${regen.stderr}`,
);
// 3. P2, now non-tautological because real writers ran: compare the

View File

@@ -30,6 +30,7 @@ const path = require('node:path');
const { execSync } = require('node:child_process');
const { runGsdTools, cleanup, readFileNormalized } = require('./helpers.cjs');
const { makeFaultyGit } = require('./helpers/faulty-deps.cjs');
// ─── helpers ──────────────────────────────────────────────────────────────────
@@ -301,6 +302,82 @@ describe('#1268 gitWorktreeInfoInternal: relocation to git-base-branch', () => {
});
});
// ─── #3057 B4: last-resort "main" — verified vs unverified ───────────────────
//
// `resolveBaseBranch` alone collapses two very different situations into the
// same `'main'` string: a repository that genuinely has no candidate branch
// (every git query on tiers 2-4 completed and cleanly answered "nothing"),
// and a total resolution failure (every query timed out). `resolveBaseBranchDiagnostics`
// exposes `verified` so a caller can tell them apart; `cmdGitBaseBranch`
// surfaces the unverified case as a stderr diagnostic without touching its
// stdout contract (five workflows parse that stdout literally).
describe('#3057 B4: resolveBaseBranchDiagnostics — verified vs unverified last-resort default', () => {
test('every tier-2/3/4 git query TIMES OUT → last-resort "main" is UNVERIFIED', (t) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3057-b4-fault-'));
t.after(() => cleanup(dir));
// No .planning/config.json in this dir → the config-override tier is
// skipped naturally (readConfigBaseBranch's real-fs read misses cleanly).
const faultyGit = makeFaultyGit({ faults: [{ kind: 'timeout' }] });
const result = gitBaseBranch.resolveBaseBranchDiagnostics(dir, { execGit: faultyGit });
assert.strictEqual(result.branch, 'main');
assert.strictEqual(result.verified, false);
});
test('every tier-2/3/4 git query cleanly reports no candidate → last-resort "main" is VERIFIED', (t) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3057-b4-clean-'));
t.after(() => cleanup(dir));
// Default passthrough: exitCode 0, empty stdout for every call — a real,
// completed "no answer" from git, not a failure (timedOut:false, error:null).
const faultyGit = makeFaultyGit();
const result = gitBaseBranch.resolveBaseBranchDiagnostics(dir, { execGit: faultyGit });
assert.strictEqual(result.branch, 'main');
assert.strictEqual(result.verified, true);
});
test('resolveBaseBranch (string-returning) is unaffected — both cases still return "main"', (t) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3057-b4-compat-'));
t.after(() => cleanup(dir));
assert.strictEqual(
gitBaseBranch.resolveBaseBranch(dir, { execGit: makeFaultyGit({ faults: [{ kind: 'timeout' }] }) }),
'main',
);
assert.strictEqual(
gitBaseBranch.resolveBaseBranch(dir, { execGit: makeFaultyGit() }),
'main',
);
});
test('cmdGitBaseBranch writes an unverified-fallback diagnostic to stderr ONLY when unverified', (t) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3057-b4-cmd-'));
t.after(() => cleanup(dir));
let stdoutText = '';
let stderrText = '';
gitBaseBranch.cmdGitBaseBranch(dir, [], {
execGit: makeFaultyGit({ faults: [{ kind: 'timeout' }] }),
write: (s) => { stdoutText += s; },
writeDiagnostic: (s) => { stderrText += s; },
});
assert.strictEqual(stdoutText, 'main\n');
assert.ok(stderrText.length > 0, 'the unverified fallback must write a stderr diagnostic');
stdoutText = '';
stderrText = '';
gitBaseBranch.cmdGitBaseBranch(dir, [], {
execGit: makeFaultyGit(),
write: (s) => { stdoutText += s; },
writeDiagnostic: (s) => { stderrText += s; },
});
assert.strictEqual(stdoutText, 'main\n');
assert.strictEqual(stderrText, '', 'a verified fallback must not write any diagnostic');
});
});
// ─── setGsdConfig prototype-pollution guard (#1406) ───────────────────────────
describe('#1406: setGsdConfig prototype-pollution guard', () => {

View File

@@ -2775,6 +2775,112 @@ describe('#2376 — init.* path fields resolve when process cwd differs from --c
});
});
// ─────────────────────────────────────────────────────────────────────────────
// #3057 B3: cmdInitVerifyWork surfaces an indeterminate staleness check
//
// buildPhaseCompletionProjection (init.cts) projects readVerificationStatus's
// result into phase_completion — a workflow step reads phase_completion.*
// fields directly. Pre-#3057 B3 wiring, `staleCheckIndeterminate` was
// computed by readVerificationStatus but dropped here, so a workflow could
// never distinguish "checked; nothing is stale" from "could not check".
// ─────────────────────────────────────────────────────────────────────────────
describe('#3057 B3: cmdInitVerifyWork — verification staleness-check indeterminate is surfaced', () => {
const initMod = require(path.join(__dirname, '..', 'gsd-core', 'bin', 'lib', 'init.cjs'));
let projectDir;
beforeEach(() => {
projectDir = createFixture();
});
afterEach(() => {
cleanup(projectDir);
});
/**
* In-process capture of cmdInitVerifyWork's stdout JSON, stderr discarded.
*
* io.cts's `output()` writes via `writeAllSync` → `fs.writeSync(1, ...)`
* directly (bug #1008's non-blocking-pipe fix), NOT `process.stdout.write`
* — so mocking `process.stdout.write` here silently captures nothing and
* every assertion below saw `JSON.parse('')` ("Unexpected end of JSON
* input") regardless of what cmdInitVerifyWork actually produced. The fix
* is the fd-level seam tests/io.test.cjs already established for exactly
* this function (bug #1008's `t.mock.method(fs, 'writeSync', ...)`
* pattern): intercept fd 1, discard fd 2, and pass every OTHER fd through
* to the real writeSync — any code path that opens its own fd (e.g. a
* lock file) must still actually write, not be silently swallowed as if
* it were stdout.
*/
function captureInitVerifyWork(t, cwd, phase) {
const chunks = [];
const origWriteSync = fs.writeSync.bind(fs);
t.mock.method(fs, 'writeSync', (fd, data, offset, length) => {
if (fd === 2) return Buffer.isBuffer(data) ? data.length : String(data).length;
if (fd !== 1) return origWriteSync(fd, data, offset, length);
const chunk = Buffer.isBuffer(data)
? data.subarray(offset ?? 0, length === undefined ? data.length : (offset ?? 0) + length).toString('utf8')
: String(data);
chunks.push(chunk);
return Buffer.byteLength(chunk, 'utf8');
});
initMod.cmdInitVerifyWork(cwd, phase, false);
const captured = chunks.join('');
assert.ok(captured.length > 0, 'cmdInitVerifyWork produced no stdout output');
return captured;
}
function seedVerifiedPhase() {
seedPhase(projectDir, '03-api', {
'03-01-PLAN.md': '# Plan',
'03-01-SUMMARY.md': '# Summary',
'03-VERIFICATION.md': '---\nstatus: passed\n---\n\n# Verification\n',
});
fs.writeFileSync(path.join(projectDir, '.planning', 'STATE.md'), '# State\n');
fs.writeFileSync(path.join(projectDir, '.planning', 'ROADMAP.md'), '# Roadmap\n');
const phaseDir = path.join(projectDir, '.planning', 'phases', '03-api');
const summaryPath = path.join(phaseDir, '03-01-SUMMARY.md');
const verificationPath = path.join(phaseDir, '03-VERIFICATION.md');
// Deterministic mtime ordering (never rely on write-order clock ties):
// verification strictly newer than the summary → a completed check finds
// nothing stale.
const older = new Date('2026-01-01T00:00:00.000Z');
const newer = new Date('2026-01-01T00:01:00.000Z');
fs.utimesSync(summaryPath, older, older);
fs.utimesSync(verificationPath, newer, newer);
return { summaryPath, verificationPath };
}
test('an fs failure inside the staleness check sets phase_completion.verification_stale_check_indeterminate:true', (t) => {
const { summaryPath, verificationPath } = seedVerifiedPhase();
const origStatSync = fs.statSync;
t.mock.method(fs, 'statSync', function injectedStaleCheckFault(target, ...args) {
const targetPath = String(target);
if (targetPath === verificationPath || targetPath === summaryPath) {
throw new Error('injected stat failure (#3057 B3)');
}
return origStatSync.call(fs, target, ...args);
});
const output = JSON.parse(captureInitVerifyWork(t, projectDir, '03'));
// Pre-existing no-throw fail-open routing is UNCHANGED: status still
// resolves to 'passed' exactly as it would without the injected fault.
assert.strictEqual(output.phase_completion.verification_status, 'passed');
assert.strictEqual(output.phase_completion.verification_stale_check_indeterminate, true);
});
test('a completed staleness check that finds nothing stale reports verification_stale_check_indeterminate:false', (t) => {
seedVerifiedPhase();
const output = JSON.parse(captureInitVerifyWork(t, projectDir, '03'));
assert.strictEqual(output.phase_completion.verification_status, 'passed');
assert.strictEqual(output.phase_completion.verification_stale_check_indeterminate, false);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// roadmap analyze command
// ─────────────────────────────────────────────────────────────────────────────

View File

@@ -8374,23 +8374,46 @@ function extractFrontmatterField(stateContent, fieldName) {
return fieldMatch ? fieldMatch[1].trim() : null;
}
// Capture stdout from cmdPhaseComplete (it calls output() which writes to stdout)
function capturePhaseComplete(cwd, phaseNum) {
// We invoke gsd-tools directly for the full CJS path, but with GSD_DISABLE_SDK_BRIDGE=1
// to force the CJS implementation. Since no env var disables bridge, we call cmdPhaseComplete
// directly and redirect output capture.
const chunks = [];
const origWrite = process.stdout.write.bind(process.stdout);
const origErrWrite = process.stderr.write.bind(process.stderr);
process.stdout.write = (chunk) => { chunks.push(chunk); return true; };
process.stderr.write = () => true;
try {
cmdPhaseComplete(cwd, phaseNum, false);
} finally {
process.stdout.write = origWrite;
process.stderr.write = origErrWrite;
// Capture stdout from `gsd-tools phase complete <N>` via a REAL subprocess.
//
// #3057: this used to call cmdPhaseComplete(...) IN-PROCESS and capture its
// stdout by monkeypatching fs.writeSync (io.cts's output() writes via
// writeAllSync -> fs.writeSync(1, ...), not process.stdout.write — bug #1008's
// non-blocking-pipe fix). That interception shares the exact seam the remote
// matrix's own event-stream capture depends on: when the runner's stdout is
// redirected to a file (the common case for a captured CI child),
// `process.stdout.write` itself resolves through that SAME public
// `fs.writeSync`, so any write racing the patched window — including the
// runner's own test:pass/test:fail events — could be silently swallowed into
// `chunks` or dropped instead of reaching the real fd. Two attempts to make
// that interception safe (manual save/restore, then `t.mock.method`) both
// still left this file reporting zero test:pass/test:fail events on the
// remote matrix. The fix is to stop intercepting fd 1 altogether: run the
// real CLI in a real subprocess, exactly like every other test in this file
// already does via `runGsdTools`, so the OS owns stdout capture and the
// runner's own event stream is never at risk.
//
// The phase family router (phase-command-router.cjs) calls
// `phase.cmdPhaseComplete(cwd, phaseNum, raw)` directly for `phase complete`
// — no SDK delegation on this path — so this reaches the exact same CJS
// function the old in-process call did.
//
// A handful of call sites depend on state a subprocess cannot see (a mock
// installed in THIS process, or the parent's own fs.writeFileSync mock for
// the rollback-failure tests below); those call sites do not use this
// helper — see the inline notes at each one.
function capturePhaseComplete(t, cwd, phaseNum) {
const result = runGsdTools(['phase', 'complete', String(phaseNum)], cwd);
if (!result.success) {
// Surface exitCode/error verbatim so a real failure never presents as a
// downstream `JSON.parse('')` error, and so assert.throws() callers keep
// matching against the real stderr text (e.g. "verification is
// incomplete...").
throw new Error(
result.error || `cmdPhaseComplete failed (exitCode=${result.exitCode})`,
);
}
return chunks.join('');
return result.output;
}
// ── T1: Double invocation must NOT double-increment Completed Phases ─────────
@@ -8406,9 +8429,9 @@ describe('issue #4 (CJS): cmdPhaseComplete — idempotency (blind-increment bug)
cleanup(tmpDir);
});
test('T1: double invocation does NOT double-increment Completed Phases in STATE.md body', () => {
test('T1: double invocation does NOT double-increment Completed Phases in STATE.md body', (t) => {
// First call — legitimate completion
capturePhaseComplete(tmpDir, '1');
capturePhaseComplete(t, tmpDir, '1');
const stateAfter1 = readStateMd(tmpDir);
const completedAfter1Body = extractField(stateAfter1, 'Completed Phases');
@@ -8426,7 +8449,7 @@ describe('issue #4 (CJS): cmdPhaseComplete — idempotency (blind-increment bug)
);
// Second call on the same phase — must be idempotent
capturePhaseComplete(tmpDir, '1');
capturePhaseComplete(t, tmpDir, '1');
const stateAfter2 = readStateMd(tmpDir);
const completedAfter2Body = extractField(stateAfter2, 'Completed Phases');
@@ -8465,8 +8488,15 @@ describe('issue #4 (CJS): cmdPhaseComplete — idempotency (blind-increment bug)
return originalWriteFileSync.call(this, target, ...args);
});
// Calls cmdPhaseComplete directly (bypassing capturePhaseComplete's
// subprocess helper): this test's fault is a `t.mock.method(fs,
// 'writeFileSync', ...)` installed in THIS process, which a subprocess
// cannot see. No stdout capture is needed here — only the thrown
// exception and the resulting on-disk file state — so calling the CJS
// function directly does not touch fd 1 and does not reinstate the
// fs.writeSync interception this file removed.
assert.throws(
() => capturePhaseComplete(tmpDir, '1'),
() => cmdPhaseComplete(tmpDir, '1', false),
/injected STATE\.md write failure/,
);
@@ -8500,8 +8530,11 @@ describe('issue #4 (CJS): cmdPhaseComplete — idempotency (blind-increment bug)
return originalWriteFileSync.call(this, target, ...args);
});
// See the parent-process-mock note in the STATE.md-write-fails test
// above: this must call cmdPhaseComplete directly, not via
// capturePhaseComplete's subprocess helper.
assert.throws(
() => capturePhaseComplete(tmpDir, '1'),
() => cmdPhaseComplete(tmpDir, '1', false),
/injected REQUIREMENTS\.md write failure/,
);
@@ -8535,13 +8568,123 @@ describe('issue #4 (CJS): cmdPhaseComplete — idempotency (blind-increment bug)
return originalWriteFileSync.call(this, target, ...args);
});
// See the parent-process-mock note in the STATE.md-write-fails test
// above: this must call cmdPhaseComplete directly, not via
// capturePhaseComplete's subprocess helper.
assert.throws(
() => capturePhaseComplete(tmpDir, '1'),
() => cmdPhaseComplete(tmpDir, '1', false),
/injected REQUIREMENTS\.md write failure[\s\S]*WARNING: rollback failed while restoring[\s\S]*injected ROADMAP\.md rollback failure/,
);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// #3057 B3: cmdPhaseComplete surfaces an indeterminate staleness check
//
// readVerificationStatus's internal staleness check can itself fail (fs /
// scanPhasePlans / clock error). Pre-#3057 B3, that failure was silently
// identical to a completed check that genuinely found nothing stale — the
// SAME fail-open shape as #3050. B3 flags this on the result
// (`staleCheckIndeterminate`); this test proves phase.cts actually SURFACES
// that flag (into `warnings[]`, the same advisory channel the UAT/VERIFICATION
// pre-scan above already uses) rather than dropping it on the floor.
// ─────────────────────────────────────────────────────────────────────────────
describe('#3057 B3: cmdPhaseComplete — verification staleness-check indeterminate is surfaced', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createFixture('gsd-3057-b3-phase-');
});
afterEach(() => {
cleanup(tmpDir);
});
test(
'an fs failure inside the staleness check adds a warning; completion routing is unchanged',
{ skip: process.platform === 'win32' ? 'symlink creation needs privilege on Windows' : false },
(t) => {
const phase01Dir = path.join(tmpDir, '.planning', 'phases', '01-foundation');
const summaryPath = path.join(phase01Dir, '01-01-SUMMARY.md');
// Real, on-disk fault instead of an in-process fs.statSync mock: this now
// runs cmdPhaseComplete in a subprocess (via capturePhaseComplete), which
// cannot see a mock installed in this process. findStaleVerificationSummary
// (verification.cjs) calls fs.statSync on each summary file to compare
// mtimes, and statSync follows symlinks — so pointing the summary at a
// target that does not exist reproduces a genuine ENOENT there, degrading
// the staleness check to {determined:false} exactly like the removed
// injected statSync throw did. scanPhasePlans only matches summary
// *filenames* (never stats them), so the plan-coverage gate still sees
// the summary as present.
fs.unlinkSync(summaryPath);
fs.symlinkSync(path.join(phase01Dir, '.does-not-exist'), summaryPath);
const output = JSON.parse(capturePhaseComplete(t, tmpDir, '1'));
// Pre-existing no-throw fail-open routing is UNCHANGED: the phase still
// completes exactly as it would have before #3057 B3.
assert.strictEqual(output.completed_phase, '1');
assert.ok(Array.isArray(output.warnings), 'result must carry a warnings array');
assert.strictEqual(
output.verification_stale_check_indeterminate,
true,
`result must surface the indeterminate staleness check as a typed field; got ${JSON.stringify(output.warnings)}`,
);
assert.strictEqual(output.has_warnings, true);
},
);
test('a completed staleness check that finds nothing stale does NOT add an indeterminate warning', (t) => {
const output = JSON.parse(capturePhaseComplete(t, tmpDir, '1'));
assert.strictEqual(output.completed_phase, '1');
assert.strictEqual(
output.verification_stale_check_indeterminate,
false,
`must not report an indeterminate check when the staleness check ran to completion; got ${JSON.stringify(output.warnings)}`,
);
});
test(
'a BLOCKED completion (status=human_needed) with an indeterminate staleness check still blocks, but the error note says so',
{ skip: process.platform === 'win32' ? 'symlink creation needs privilege on Windows' : false },
() => {
const phase02Dir = path.join(tmpDir, '.planning', 'phases', '02-api');
fs.writeFileSync(path.join(phase02Dir, '02-01-PLAN.md'), '# Plan\nDo the work.\n');
fs.writeFileSync(path.join(phase02Dir, '02-VERIFICATION.md'), [
'---',
'status: human_needed',
'---',
'',
'# Verification',
'',
].join('\n'));
// Real, on-disk fault — see the note in the sibling test above. The
// summary is a dangling symlink so fs.statSync (inside
// findStaleVerificationSummary, running in the subprocess) throws ENOENT.
const summaryPath = path.join(phase02Dir, '02-01-SUMMARY.md');
fs.symlinkSync(path.join(phase02Dir, '.does-not-exist'), summaryPath);
// Routing is UNCHANGED — status !== 'passed' already blocked before #3057
// B3; the note is purely additive to the message text. Assert the fact
// structurally (via --json-errors) rather than regexing the human-
// readable note — CONTRIBUTING requires a typed surface alongside any
// text a caller might otherwise only match on, and once that typed
// surface exists the test must assert on IT, not also on the rendered
// prose (src/phase.cts's human message wording is out of scope for this
// test — operators read it, but the test must not lock its exact text).
const result = runGsdTools(['--json-errors', 'phase', 'complete', '2'], tmpDir);
assert.equal(result.success, false, 'phase complete must fail when verification is blocked');
const errorPayload = JSON.parse(result.error);
assert.equal(errorPayload.reason, 'phase_verification_incomplete');
assert.equal(errorPayload.verification_stale_check_indeterminate, true);
},
);
});
// ─────────────────────────────────────────────────────────────────────────────
// Regressions: phase complete preserves completion date (#1161)
// Tests drive the REAL handler (cmdPhaseComplete) via the CLI entry point
@@ -8842,7 +8985,7 @@ describe('issue #4 (CJS): cmdPhaseComplete — progress percent clamp', () => {
cleanup(tmpDir);
});
test('T2: Progress percent never exceeds 100 after double invocation', () => {
test('T2: Progress percent never exceeds 100 after double invocation', (t) => {
tmpDir = createFixture();
// Pre-load STATE.md with Completed Phases: 1, Total Phases: 1 (already 100%)
@@ -8873,9 +9016,9 @@ describe('issue #4 (CJS): cmdPhaseComplete — progress percent clamp', () => {
fs.writeFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), roadmap);
// First call
capturePhaseComplete(tmpDir, '1');
capturePhaseComplete(t, tmpDir, '1');
// Second call — this is the problematic one
capturePhaseComplete(tmpDir, '1');
capturePhaseComplete(t, tmpDir, '1');
const stateAfterBoth = readStateMd(tmpDir);

View File

@@ -73,7 +73,13 @@ function runReviewerFlagsParseBlock(block, args) {
return execFileSync('bash', ['-c', script], {
env: { ...process.env, ARGUMENTS: args, GSD_TOOLS_PATH },
encoding: 'utf8',
timeout: 5000,
// 30s covers the nested bash → node → gsd-tools.cjs cold-start chain this
// helper spawns. 5s was too tight: on a loaded bench (30k tests running
// in parallel) that budget was consumed by process-spawn scheduling
// latency alone, producing a spurious ETIMEDOUT with no genuine hang.
// 30_000 matches the convention other script-invocation tests in this
// repo already use (see e.g. adr-index-gate.test.cjs, check-env.test.cjs).
timeout: 30_000,
}).trim();
}
@@ -393,7 +399,10 @@ describe('plan-review-convergence: #2315 respects review.default_reviewers (no-f
return execFileSync('bash', ['-c', script], {
env: { ...process.env, ARGUMENTS: args, GSD_TEST_DEFAULT_REVIEWERS: defaultReviewers ?? '', GSD_TOOLS_PATH },
encoding: 'utf8',
timeout: 5000,
// 30s covers the same nested bash → node → gsd-tools.cjs cold-start
// chain as runReviewerFlagsParseBlock above; see that helper's
// comment for why 5s flaked under bench load.
timeout: 30_000,
});
};
@@ -447,7 +456,10 @@ describe('plan-review-convergence: #2315 respects review.default_reviewers (no-f
return execFileSync('bash', ['-c', script], {
env: { ...process.env, ARGUMENTS: args, GSD_TEST_DEFAULT_REVIEWERS: defaultReviewers ?? '', GSD_TOOLS_PATH },
encoding: 'utf8',
timeout: 5000,
// 30s covers the same nested bash → node → gsd-tools.cjs cold-start
// chain as runReviewerFlagsParseBlock above; see that helper's
// comment for why 5s flaked under bench load.
timeout: 30_000,
});
};

View File

@@ -1117,6 +1117,128 @@ describe('roadmap update-plan-progress command', () => {
});
});
// ─────────────────────────────────────────────────────────────────────────────
// #3057 B3: cmdRoadmapUpdatePlanProgress surfaces an indeterminate staleness check
//
// readVerificationStatus's internal staleness check can fail (fs /
// scanPhasePlans / clock error). Pre-#3057 B3 wiring, that failure was
// dropped here — `verificationPassed` used only `.status`, never
// `.staleCheckIndeterminate` — so this command's JSON output could never
// distinguish "checked; nothing is stale" from "could not check". These
// tests require roadmap.cjs directly (in-process) so an `fs.statSync` fault
// can be injected via the same deterministic path-scoped seam #3057 B4 uses
// for git-base-branch.cts (see tests/git-base-branch.test.cjs).
// ─────────────────────────────────────────────────────────────────────────────
describe('#3057 B3: roadmap update-plan-progress — verification staleness-check indeterminate is surfaced', () => {
const roadmapMod = require(path.join(__dirname, '..', 'gsd-core', 'bin', 'lib', 'roadmap.cjs'));
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject('gsd-3057-b3-roadmap-');
});
afterEach(() => {
cleanup(tmpDir);
});
/**
* In-process capture of cmdRoadmapUpdatePlanProgress's stdout JSON, stderr
* discarded.
*
* io.cts's `output()` writes via `writeAllSync` → `fs.writeSync(1, ...)`
* directly (bug #1008's non-blocking-pipe fix), NOT `process.stdout.write`
* — so mocking `process.stdout.write` here silently captured nothing and
* every assertion below saw `JSON.parse('')` ("Unexpected end of JSON
* input") regardless of what the command actually produced. The fix is the
* fd-level seam tests/io.test.cjs already established for exactly this
* function (bug #1008's `t.mock.method(fs, 'writeSync', ...)` pattern):
* intercept fd 1, discard fd 2, and pass every OTHER fd through to the
* real writeSync — this command takes the planning lock, which writes its
* own JSON via a separate fd that must not be swallowed as if it were
* stdout (confirmed: without the pass-through, its lock-acquire JSON
* corrupts the captured payload into two concatenated JSON objects).
*/
function captureUpdatePlanProgress(t, cwd, phaseNum) {
const chunks = [];
const origWriteSync = fs.writeSync.bind(fs);
t.mock.method(fs, 'writeSync', (fd, data, offset, length) => {
if (fd === 2) return Buffer.isBuffer(data) ? data.length : String(data).length;
if (fd !== 1) return origWriteSync(fd, data, offset, length);
const chunk = Buffer.isBuffer(data)
? data.subarray(offset ?? 0, length === undefined ? data.length : (offset ?? 0) + length).toString('utf8')
: String(data);
chunks.push(chunk);
return Buffer.byteLength(chunk, 'utf8');
});
roadmapMod.cmdRoadmapUpdatePlanProgress(cwd, phaseNum, false);
const captured = chunks.join('');
assert.ok(captured.length > 0, 'cmdRoadmapUpdatePlanProgress produced no stdout output');
return captured;
}
function seedVerifiedPhase() {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap
### Phase 1: Test
**Goal:** Test goal
**Plans:** TBD
## Progress
| Phase | Milestone | Plans Complete | Status | Completed |
|-------|-----------|----------------|--------|-----------|
| 1. Test | v1.0 | 0/1 | Planned | - |
`
);
const p1 = path.join(tmpDir, '.planning', 'phases', '01-test');
fs.mkdirSync(p1, { recursive: true });
fs.writeFileSync(path.join(p1, '01-01-PLAN.md'), '# Plan 1');
fs.writeFileSync(path.join(p1, '01-01-SUMMARY.md'), '# Summary 1');
fs.writeFileSync(path.join(p1, '01-VERIFICATION.md'), '---\nstatus: passed\n---\n\n# Verification\n');
const summaryPath = path.join(p1, '01-01-SUMMARY.md');
const verificationPath = path.join(p1, '01-VERIFICATION.md');
// Deterministic mtime ordering — never rely on write-order clock ties.
const older = new Date('2026-01-01T00:00:00.000Z');
const newer = new Date('2026-01-01T00:01:00.000Z');
fs.utimesSync(summaryPath, older, older);
fs.utimesSync(verificationPath, newer, newer);
return { summaryPath, verificationPath };
}
test('an fs failure inside the staleness check sets verification_stale_check_indeterminate:true; routing unchanged', (t) => {
const { summaryPath, verificationPath } = seedVerifiedPhase();
const origStatSync = fs.statSync;
t.mock.method(fs, 'statSync', function injectedStaleCheckFault(target, ...args) {
const targetPath = String(target);
if (targetPath === verificationPath || targetPath === summaryPath) {
throw new Error('injected stat failure (#3057 B3)');
}
return origStatSync.call(fs, target, ...args);
});
const output = JSON.parse(captureUpdatePlanProgress(t, tmpDir, '1'));
// Pre-existing no-throw fail-open routing is UNCHANGED: the phase still
// resolves complete, exactly as it would without the injected fault.
assert.strictEqual(output.complete, true, 'routing unchanged — phase still marked complete');
assert.strictEqual(output.verification_stale_check_indeterminate, true);
});
test('a completed staleness check that finds nothing stale reports verification_stale_check_indeterminate:false', (t) => {
seedVerifiedPhase();
const output = JSON.parse(captureUpdatePlanProgress(t, tmpDir, '1'));
assert.strictEqual(output.complete, true);
assert.strictEqual(output.verification_stale_check_indeterminate, false);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// phase add command
// ─────────────────────────────────────────────────────────────────────────────

View File

@@ -1,236 +1,285 @@
// allow-test-rule: architectural-invariant
// acquireStateLock is a private function (not exported). The behavioral contract —
// throw on non-EEXIST errors rather than returning a false-success lockPath — is
// an implementation invariant that cannot be verified through the public CLI API
// without introducing timing-sensitive mocks. Source inspection is the correct
// and authoritative level for this contract.
'use strict';
/**
* Regression tests for #3772 — acquireStateLock silently returns false-success
* Regression tests for #3772 — acquireStateLock silently returned false-success
* on non-EEXIST openSync errors (EMFILE / EINTR / ENOSPC under load).
*
* Extended in #3776 to cover Docker overlay-fs and NFS transient errno codes.
* Extended in #3776 to cover Docker overlay-fs and NFS transient errno codes,
* and in #3057 (B2) to cover the steal-decision fault path for an unreadable
* lock body (merged in from tests/state-lock-body-unreadable.test.cjs, which
* this file absorbed — same acquireStateLock surface, see lint-test-file-count).
*
* Every test in this file actually CALLS acquireStateLock (never regexes the
* built .cjs source) and injects errno faults via `withFaultyFs` on the exact
* fs.openSync call the lock-create path makes (src/state.cts, the
* `fs.openSync(lockPath, O_CREAT|O_EXCL|O_WRONLY)` line inside
* acquireStateLock's retry loop) — never chmod/subprocess tricks.
*
* Contract under test:
* C1. Non-EEXIST error from fs.openSync → must throw, not return lockPath
* C2. Success path (openSync succeeds) → must return lockPath
* C3. EEXIST error → retry / wait semantics unchanged (not impacted by this fix)
* C4. RETRY_ERRNOS set: EAGAIN/EINTR/EINVAL/EIO/ENOENT/ESTALE must be in the retry allowlist
* C5. Fatal codes: EMFILE/ENOSPC/EROFS/EACCES must NOT be in the retry allowlist
* C6. Unknown errno codes must NOT be in the retry allowlist (conservative default)
* C7. EPERM/EBUSY must remain in the retry allowlist (from #3773)
* C1. A fatal non-EEXIST error (EACCES) propagates/throws — not swallowed
* as EEXIST contention and not retried.
* C2. Success path (openSync succeeds) → returns lockPath and writes this
* process's pid into the lock body.
* C4/C7. ACQUIRE_LOCK_RETRY_ERRNOS codes (EAGAIN/EINTR/EINVAL/EIO/ENOENT/
* ESTALE/EPERM/EBUSY) are retried — the open eventually succeeds and
* exactly one contention-style backoff (clock.sleep) occurs first.
* C5/C6. Fatal codes (EMFILE/ENOSPC/EROFS) and unknown codes propagate
* immediately — zero backoff, the error is thrown on the first attempt.
* (C8 — "uses a Set, not an inline literal" — is an implementation-shape
* assertion with no independent runtime signature; it is subsumed by C4c-f
* above, since a regression to the old inline EPERM||EBUSY check would fail
* those newer-errno retry assertions.)
*/
const { test, describe } = require('node:test');
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const STATE_CJS_PATH = path.join(
__dirname, '..', 'gsd-core', 'bin', 'lib', 'state.cjs'
);
const { makeFakeClock } = require('./helpers/clock.cjs');
const { withFaultyFs } = require('./helpers/faulty-deps.cjs');
const { cleanup } = require('./helpers.cjs');
const { acquireStateLock, releaseStateLock } = require('../gsd-core/bin/lib/state.cjs');
// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────
const originalOpenSync = fs.openSync;
const originalReadFileSync = fs.readFileSync;
/** Extract the text of acquireStateLock from the source file. */
function extractAcquireStateLockSource(src) {
const fnStart = src.indexOf('function acquireStateLock(');
assert.ok(fnStart !== -1, 'acquireStateLock function must exist in state.cjs');
// Find the closing brace by counting open/close braces from the function start
let depth = 0;
let i = fnStart;
let foundOpen = false;
while (i < src.length) {
if (src[i] === '{') { depth++; foundOpen = true; }
if (src[i] === '}') { depth--; }
if (foundOpen && depth === 0) { return src.slice(fnStart, i + 1); }
i++;
}
throw new Error('Could not find closing brace of acquireStateLock');
/** Fresh temp project dir with a STATE.md, for a single test. */
function makeTempState() {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-lock-non-eexist-'));
fs.mkdirSync(path.join(tmpDir, '.planning'), { recursive: true });
const statePath = path.join(tmpDir, '.planning', 'STATE.md');
fs.writeFileSync(statePath, '# State\n');
return { tmpDir, statePath };
}
/** Back-date `lockPath`'s mtime by `ageMs` (real fs time, not fake-clock). */
function backdateMtime(lockPath, ageMs) {
const staled = new Date(Date.now() - ageMs);
fs.utimesSync(lockPath, staled, staled);
}
/**
* Build a `t`-taking test body that faults fs.openSync for `lockPath` ONCE
* with `code`, then lets the retried open succeed for real — proving the
* errno is retried (not thrown) and exactly one backoff occurs.
*/
function assertOpenSyncErrorIsRetried(code) {
return (t) => {
const { tmpDir, statePath } = makeTempState();
t.after(() => cleanup(tmpDir));
const lockPath = statePath + '.lock';
const clock = makeFakeClock(0);
let calls = 0;
const acquired = withFaultyFs(
{
openSync: (p, ...rest) => {
if (String(p) === lockPath) {
calls++;
if (calls === 1) {
throw Object.assign(new Error(code + ': injected transient error'), { code });
}
}
return originalOpenSync(p, ...rest);
},
},
() => acquireStateLock(statePath, clock),
);
t.after(() => releaseStateLock(acquired));
assert.equal(
acquired, lockPath,
code + ' must be retried and the retried open must succeed, not be thrown immediately',
);
assert.equal(
clock.sleepCalls.length, 1,
code + ' must trigger exactly one contention-style backoff before the retried open succeeds',
);
};
}
/**
* Build a `t`-taking test body that faults fs.openSync for `lockPath` on
* EVERY call with `code` — proving the errno propagates on the first attempt
* with zero backoff (fatal, not retried).
*/
function assertOpenSyncErrorIsFatal(code) {
return (t) => {
const { tmpDir, statePath } = makeTempState();
t.after(() => cleanup(tmpDir));
const lockPath = statePath + '.lock';
const clock = makeFakeClock(0);
assert.throws(
() => withFaultyFs(
{
openSync: (p, ...rest) => {
if (String(p) === lockPath) {
throw Object.assign(new Error(code + ': injected fatal error'), { code });
}
return originalOpenSync(p, ...rest);
},
},
() => acquireStateLock(statePath, clock),
),
(err) => err.code === code,
code + ' must propagate to the caller rather than being retried or swallowed',
);
assert.equal(
clock.sleepCalls.length, 0,
code + ' must not trigger a contention/backoff retry before throwing',
);
};
}
// ─────────────────────────────────────────────────────────────────────────────
// C1. Non-EEXIST error → must throw, not return lockPath
// C1. Non-EEXIST fatal error → must throw, not be swallowed as contention
// ─────────────────────────────────────────────────────────────────────────────
describe('acquireStateLock: non-EEXIST openSync errors (#3772)', () => {
test('C1: source contains throw-not-return for non-EEXIST errors', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const fnSrc = extractAcquireStateLockSource(src);
// The bug pattern: silently returning the lockPath on non-EEXIST error.
// This branch must NOT appear in the fixed code.
const bugPattern = /if\s*\(\s*err\.code\s*!==\s*['"]EEXIST['"]\s*\)\s*return\s+lockPath/;
assert.ok(
!bugPattern.test(fnSrc),
'acquireStateLock must NOT return lockPath on non-EEXIST errors (silent false-success — #3772)'
);
// The fix: throw the error so callers get the real OS-level failure.
const fixPattern = /if\s*\(\s*err\.code\s*!==\s*['"]EEXIST['"]\s*\)\s*throw\s+err/;
assert.ok(
fixPattern.test(fnSrc),
'acquireStateLock must throw err on non-EEXIST openSync errors (EMFILE/EINTR/ENOSPC — #3772)'
);
});
test(
'C1: a fatal non-EEXIST error (EACCES) propagates — not swallowed as EEXIST contention',
assertOpenSyncErrorIsFatal('EACCES'),
);
});
// ─────────────────────────────────────────────────────────────────────────────
// C2. Success path → returns lockPath (regression guard — fix must not break success)
// C2. Success path → returns lockPath and writes this process's pid
// ─────────────────────────────────────────────────────────────────────────────
describe('acquireStateLock: success path still returns lockPath', () => {
test('C2: source contains return lockPath in the success (try) branch', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const fnSrc = extractAcquireStateLockSource(src);
test('C2: openSync succeeding returns the lock path and writes this process pid', (t) => {
const { tmpDir, statePath } = makeTempState();
t.after(() => cleanup(tmpDir));
// The success path: openSync succeeds → write PID → close → add to held set → return lockPath.
// Verify the return is still present inside the try block (before the catch).
const tryBlock = fnSrc.slice(fnSrc.indexOf('try {'), fnSrc.indexOf('} catch ('));
assert.ok(
tryBlock.includes('return lockPath'),
'acquireStateLock must still return lockPath when fs.openSync succeeds (success path intact)'
const acquired = acquireStateLock(statePath);
t.after(() => releaseStateLock(acquired));
assert.equal(acquired, statePath + '.lock', 'acquireStateLock must return the lock path on success');
assert.ok(fs.existsSync(acquired), 'the lock file must exist on disk after a successful acquire');
assert.equal(
fs.readFileSync(acquired, 'utf8'), String(process.pid),
'the lock body must contain this process pid on the success path',
);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// C4. RETRY_ERRNOS set: new Docker/NFS transient codes must be present (#3776)
// C4 / C7. Transient errno codes are retried (#3776 / #3773 regression guard)
// ─────────────────────────────────────────────────────────────────────────────
/** Extract the ACQUIRE_LOCK_RETRY_ERRNOS Set literal from the source file. */
function extractRetryErrnosSource(src) {
const constStart = src.indexOf('const ACQUIRE_LOCK_RETRY_ERRNOS');
assert.ok(constStart !== -1, 'ACQUIRE_LOCK_RETRY_ERRNOS constant must exist in state.cjs');
// Extract to the end of the Set(...) constructor — find the closing ]);
const setEnd = src.indexOf(']);', constStart);
assert.ok(setEnd !== -1, 'ACQUIRE_LOCK_RETRY_ERRNOS Set must have closing ]);');
return src.slice(constStart, setEnd + 2);
}
describe('acquireStateLock: transient errno codes are retried, not thrown (#3776)', () => {
test('C4a: EAGAIN is retried (resource temporarily unavailable)', assertOpenSyncErrorIsRetried('EAGAIN'));
test('C4b: EINTR is retried (syscall interrupted)', assertOpenSyncErrorIsRetried('EINTR'));
test('C4c: EINVAL is retried (Docker overlay-fs transient)', assertOpenSyncErrorIsRetried('EINVAL'));
test('C4d: EIO is retried (Docker overlay-fs / NFS transient)', assertOpenSyncErrorIsRetried('EIO'));
test('C4e: ENOENT is retried (Docker overlay-fs parent dir transient)', assertOpenSyncErrorIsRetried('ENOENT'));
test('C4f: ESTALE is retried (NFS stale file handle)', assertOpenSyncErrorIsRetried('ESTALE'));
});
describe('acquireStateLock: RETRY_ERRNOS Set contains expected transient codes (#3776)', () => {
test('C4a: EAGAIN is in ACQUIRE_LOCK_RETRY_ERRNOS', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const setBlock = extractRetryErrnosSource(src);
assert.ok(setBlock.includes("'EAGAIN'"), 'ACQUIRE_LOCK_RETRY_ERRNOS must include EAGAIN (resource temporarily unavailable)');
});
test('C4b: EINTR is in ACQUIRE_LOCK_RETRY_ERRNOS', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const setBlock = extractRetryErrnosSource(src);
assert.ok(setBlock.includes("'EINTR'"), 'ACQUIRE_LOCK_RETRY_ERRNOS must include EINTR (syscall interrupted)');
});
test('C4c: EINVAL is in ACQUIRE_LOCK_RETRY_ERRNOS', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const setBlock = extractRetryErrnosSource(src);
assert.ok(setBlock.includes("'EINVAL'"), 'ACQUIRE_LOCK_RETRY_ERRNOS must include EINVAL (Docker overlay-fs transient)');
});
test('C4d: EIO is in ACQUIRE_LOCK_RETRY_ERRNOS', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const setBlock = extractRetryErrnosSource(src);
assert.ok(setBlock.includes("'EIO'"), 'ACQUIRE_LOCK_RETRY_ERRNOS must include EIO (Docker overlay-fs / NFS transient)');
});
test('C4e: ENOENT is in ACQUIRE_LOCK_RETRY_ERRNOS', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const setBlock = extractRetryErrnosSource(src);
assert.ok(setBlock.includes("'ENOENT'"), 'ACQUIRE_LOCK_RETRY_ERRNOS must include ENOENT (Docker overlay-fs parent dir transient)');
});
test('C4f: ESTALE is in ACQUIRE_LOCK_RETRY_ERRNOS', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const setBlock = extractRetryErrnosSource(src);
assert.ok(setBlock.includes("'ESTALE'"), 'ACQUIRE_LOCK_RETRY_ERRNOS must include ESTALE (NFS stale file handle)');
});
describe('acquireStateLock: EPERM/EBUSY still retried (regression guard, #3773)', () => {
test('C7a: EPERM is retried (Windows / macOS AV scanner)', assertOpenSyncErrorIsRetried('EPERM'));
test('C7b: EBUSY is retried (Windows file in use)', assertOpenSyncErrorIsRetried('EBUSY'));
});
// ─────────────────────────────────────────────────────────────────────────────
// C5. Fatal codes: EMFILE/ENOSPC/EROFS/EACCES must NOT be in the retry set
// C5 / C6. Fatal and unknown errno codes propagate immediately, never retried
// ─────────────────────────────────────────────────────────────────────────────
describe('acquireStateLock: fatal errno codes NOT in RETRY_ERRNOS (#3776)', () => {
test('C5a: EMFILE is NOT in ACQUIRE_LOCK_RETRY_ERRNOS (fd limit exhausted — fatal)', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const setBlock = extractRetryErrnosSource(src);
assert.ok(!setBlock.includes("'EMFILE'"), 'ACQUIRE_LOCK_RETRY_ERRNOS must NOT include EMFILE (fatal: fd limit)');
});
test('C5b: ENOSPC is NOT in ACQUIRE_LOCK_RETRY_ERRNOS (disk full — fatal)', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const setBlock = extractRetryErrnosSource(src);
assert.ok(!setBlock.includes("'ENOSPC'"), 'ACQUIRE_LOCK_RETRY_ERRNOS must NOT include ENOSPC (fatal: disk full)');
});
test('C5c: EROFS is NOT in ACQUIRE_LOCK_RETRY_ERRNOS (read-only fs — fatal)', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const setBlock = extractRetryErrnosSource(src);
assert.ok(!setBlock.includes("'EROFS'"), 'ACQUIRE_LOCK_RETRY_ERRNOS must NOT include EROFS (fatal: read-only fs)');
});
test('C5d: EACCES is NOT in ACQUIRE_LOCK_RETRY_ERRNOS (permission denied — fatal)', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const setBlock = extractRetryErrnosSource(src);
assert.ok(!setBlock.includes("'EACCES'"), 'ACQUIRE_LOCK_RETRY_ERRNOS must NOT include EACCES (fatal: no permission)');
});
describe('acquireStateLock: fatal errno codes propagate without retry (#3776)', () => {
test('C5a: EMFILE propagates immediately (fd limit exhausted — fatal)', assertOpenSyncErrorIsFatal('EMFILE'));
test('C5b: ENOSPC propagates immediately (disk full — fatal)', assertOpenSyncErrorIsFatal('ENOSPC'));
test('C5c: EROFS propagates immediately (read-only fs — fatal)', assertOpenSyncErrorIsFatal('EROFS'));
// EACCES is covered by C1 above (the canonical non-EEXIST-fatal case).
});
// ─────────────────────────────────────────────────────────────────────────────
// C6. Unknown errno codes are not in the retry set (conservative default)
// ─────────────────────────────────────────────────────────────────────────────
describe('acquireStateLock: unknown errno codes not retried (conservative default, #3776)', () => {
test('C6: ACQUIRE_LOCK_RETRY_ERRNOS does not include ESOMETHING (unknown code)', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const setBlock = extractRetryErrnosSource(src);
assert.ok(
!setBlock.includes("'ESOMETHING'"),
'ACQUIRE_LOCK_RETRY_ERRNOS must not include unknown errno ESOMETHING (conservative: surface unknowns)'
);
});
test(
'C6: an unrecognized errno (ESOMETHING) propagates rather than being retried',
assertOpenSyncErrorIsFatal('ESOMETHING'),
);
});
// ─────────────────────────────────────────────────────────────────────────────
// C7. EPERM/EBUSY remain in the retry set (regression guard from #3773)
// #3057 B2 — an unreadable STATE.md lock body must not get the same
// fresh-create-floor stealable treatment as a genuinely empty one.
//
// `_stateLockBodyPid` used to collapse two different situations to the same
// `null`: a lock body that reads back empty/garbage (the create→write
// window — expected, benign) and a lock body that could not be READ at all
// (an I/O fault — permission error, transient NFS/overlay-fs hiccup, etc.).
// Both got the SAME 1-second (`freshCreateFloorMs`) steal-eligibility
// window, so a transient read fault could rob an actively-held lock exactly
// as fast as a lock that is merely mid-creation.
//
// The fix (`_stateLockBodyStatus`, state.cts) makes the steal decision
// four-way: an unreadable body is now held to the SAME conservative
// `deadmanCeilingMs` ceiling as a verified-live holder, not the short
// fresh-create floor.
//
// These two tests are a pair by construction: identical lock age (past the
// fresh-create floor, nowhere near the deadman ceiling), identical clock
// rig — the ONLY variable is whether the body read throws (fault-injected
// via `withFaultyFs`, never chmod/subprocess) or genuinely reads back empty.
// ─────────────────────────────────────────────────────────────────────────────
describe('acquireStateLock: EPERM/EBUSY still in RETRY_ERRNOS (regression guard, #3773)', () => {
test('C7a: EPERM is in ACQUIRE_LOCK_RETRY_ERRNOS (Windows / macOS AV scanner)', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const setBlock = extractRetryErrnosSource(src);
assert.ok(setBlock.includes("'EPERM'"), 'ACQUIRE_LOCK_RETRY_ERRNOS must still include EPERM (#3773 regression guard)');
});
describe('#3057 B2: acquireStateLock steal decision — unreadable lock body vs. genuinely empty', () => {
test('FAILURE path: an unreadable lock body is NOT stolen at the fresh-create-floor age — the acquire budget is exhausted instead', (t) => {
const { tmpDir, statePath } = makeTempState();
t.after(() => cleanup(tmpDir));
test('C7b: EBUSY is in ACQUIRE_LOCK_RETRY_ERRNOS (Windows file in use)', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const setBlock = extractRetryErrnosSource(src);
assert.ok(setBlock.includes("'EBUSY'"), 'ACQUIRE_LOCK_RETRY_ERRNOS must still include EBUSY (#3773 regression guard)');
});
});
const lockPath = statePath + '.lock';
// Content is irrelevant — the fault-injected read throws before it is ever parsed.
fs.writeFileSync(lockPath, '12345');
t.after(() => { try { fs.unlinkSync(lockPath); } catch { /* already gone */ } });
// ─────────────────────────────────────────────────────────────────────────────
// C8. acquireStateLock uses Set-based retry check (not inline literal)
// ─────────────────────────────────────────────────────────────────────────────
// Age the lock past freshCreateFloorMs (1000ms) but nowhere near
// deadmanCeilingMs (60000ms) — this is EXACTLY the age at which a
// genuinely-empty body would already be stolen (see the paired test below).
backdateMtime(lockPath, 5000);
describe('acquireStateLock: uses Set-based retry check (grep-able, not inline literal)', () => {
test('C8: retry check uses ACQUIRE_LOCK_RETRY_ERRNOS.has() not hardcoded comparisons', () => {
const src = fs.readFileSync(STATE_CJS_PATH, 'utf-8');
const fnSrc = extractAcquireStateLockSource(src);
const baseClock = makeFakeClock(Date.now() + 100); // ageMs ≈ 5100ms at start
// Jump the virtual clock past the 30 000ms acquire budget on the very
// first retry sleep, so the test proves "never stolen within budget"
// deterministically without hundreds of synchronous retry iterations.
const fastClock = {
now: baseClock.now.bind(baseClock),
sleep(ms) {
baseClock.sleep(ms);
baseClock.advance(31000);
},
};
// Must use the named Set for the check inside the function
assert.ok(
fnSrc.includes('ACQUIRE_LOCK_RETRY_ERRNOS.has('),
'acquireStateLock catch block must use ACQUIRE_LOCK_RETRY_ERRNOS.has() for retry decision'
);
// Must NOT have the old inline EPERM/EBUSY literal check
const oldPattern = /err\.code\s*===\s*['"]EPERM['"]\s*\|\|\s*err\.code\s*===\s*['"]EBUSY['"]/;
assert.ok(
!oldPattern.test(fnSrc),
'acquireStateLock must not use old inline EPERM||EBUSY check (should use ACQUIRE_LOCK_RETRY_ERRNOS.has())'
assert.throws(
() => withFaultyFs(
{
readFileSync: (p, ...rest) => {
if (String(p) === lockPath) {
throw Object.assign(new Error('EIO: i/o error, read'), { code: 'EIO' });
}
return originalReadFileSync(p, ...rest);
},
},
() => acquireStateLock(statePath, fastClock),
),
/acquireStateLock.*exceeded.*30000ms budget/,
'an unreadable lock body past the fresh-create-floor age must NOT be stolen — it must hit the acquire-budget timeout',
);
});
test('BENIGN path: a genuinely empty lock body at the SAME age IS stolen (fresh-create-floor path unaffected by the fix)', (t) => {
const { tmpDir, statePath } = makeTempState();
t.after(() => cleanup(tmpDir));
const lockPath = statePath + '.lock';
fs.writeFileSync(lockPath, ''); // genuinely empty — mid-creation window, not an I/O fault
backdateMtime(lockPath, 5000); // identical age to the FAILURE test above
const clock = makeFakeClock(Date.now() + 100); // ageMs ≈ 5100ms, identical rig to the FAILURE test above
const acquired = acquireStateLock(statePath, clock);
t.after(() => releaseStateLock(acquired));
assert.ok(fs.existsSync(acquired),
'a genuinely empty lock body past the fresh-create-floor age must still be stolen and re-acquired');
});
});

View File

@@ -17,6 +17,11 @@ const {
cleanup,
runGsdTools,
} = require('./helpers.cjs');
const { withFaultyFs } = require('./helpers/faulty-deps.cjs');
const stateMod = require('../gsd-core/bin/lib/state.cjs');
const { stateExtractField } = require('../gsd-core/bin/lib/state-document.cjs');
const { parseMarkdownTable } = require('../gsd-core/bin/lib/markdown-table.cjs');
const { collectSection } = require('../gsd-core/bin/lib/markdown-sectionizer.cjs');
const TOOLS_PATH = path.join(__dirname, '..', 'gsd-core', 'bin', 'gsd-tools.cjs');
@@ -113,6 +118,124 @@ function readLiveState(cwd) {
return content.replace(/^## Rebuild Log[\s\S]*$/m, '');
}
/**
* A project whose ONLY drift is the `**By Phase:**` table (an orphan row for
* phase 99, which isn't on disk). Every other body/frontmatter field is
* already canonical, so `rebuildCore`'s other reconciliation steps are all
* no-ops — the ONLY thing that can add a `## Rebuild Log` entry / flip
* `mutated` is whether the phase-inventory disk scan actually reconciles the
* table. This isolates the phase-inventory-scan outcome for #3057 B1.
*/
function projectWithOnlyPhaseTableDrift() {
const cwd = createTempProject('state-rebuild-cli-scan');
const planningPath = path.join(cwd, '.planning');
fs.mkdirSync(path.join(planningPath, 'phases', '01-phase-one'), { recursive: true });
fs.writeFileSync(path.join(planningPath, 'phases', '01-phase-one', '01-PLAN.md'), '# Plan');
const stateContent = [
'---',
'gsd_state_version: \'1.0\'',
'status: executing',
'milestone: 1.0.0',
'milestone_name: Test',
'current_phase: 1',
'current_phase_name: Phase One',
'current_plan: 1',
'progress:',
' total_phases: 1',
' completed_phases: 0',
' total_plans: 1',
' completed_plans: 0',
' percent: 0',
'---',
'',
'# Project State',
'',
'## Project Reference',
'',
'**Core value:** A test project',
'**Current focus:** Phase One',
'',
'## Current Position',
'',
'**Current Phase:** 1',
'**Current Phase Name:** Phase One',
'**Current Plan:** 1',
'**Total Plans in Phase:** 1',
'**Status:** executing',
'**Last Activity:** 2026-06-29',
'**Last Activity Description:** mid-flight',
'',
'Phase: 1 of 1 (Phase One)',
'Plan: 1 of 1',
'Status: Executing Phase 1',
'Last activity: 2026-06-29 — mid-flight',
'',
'**Progress:** [░░░░░░░░░░] 0%',
'',
'## Performance Metrics',
'',
'**By Phase:**',
'',
'| Phase | Plans | Total | Avg/Plan |',
'|-------|-------|-------|----------|',
'| 1 | 1 | - | - |',
'| 99 | 1 | - | - |',
'',
'## Accumulated Context',
'',
'### Decisions',
'',
'None yet.',
'',
'## Session Continuity',
'',
'Last session: 2026-06-29 12:00',
'Stopped at: mid-flight',
'Resume file: None',
'',
].join('\n');
fs.writeFileSync(path.join(planningPath, 'STATE.md'), stateContent);
return cwd;
}
/**
* Typed presence check for the `## Rebuild Log` audit-log section, shared by
* both call sites that need it (CONTRIBUTING: no raw-text `.includes()` on
* produced STATE.md text). Built on the existing `collectSection` seam
* (markdown-sectionizer.cjs) — a `Section | null`, not string matching.
*/
function hasRebuildLogSection(content) {
return collectSection(content, (h) => h.text.trim() === 'Rebuild Log') !== null;
}
/**
* Run `fn` while capturing every fd-1 write `cmdStateRebuild`'s `output()`
* performs (it writes via a raw `fs.writeSync(1, ...)`, never
* `console.log`/`process.stdout.write` — same seam `tests/io.test.cjs`
* exercises for bug #1008). Standalone helper with no test context, so the
* try/finally restore is CONTRIBUTING-compliant (same shape as
* `withFaultyFs`).
*/
function captureStdout(fn) {
const chunks = [];
const original = fs.writeSync;
fs.writeSync = (fd, data, offset, length) => {
if (fd !== 1) return original(fd, data, offset, length);
const chunk = Buffer.isBuffer(data)
? data.subarray(offset ?? 0, length === undefined ? data.length : (offset ?? 0) + length).toString('utf8')
: String(data);
chunks.push(chunk);
return Buffer.byteLength(chunk, 'utf8');
};
try {
fn();
} finally {
fs.writeSync = original;
}
return chunks.join('');
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
@@ -127,18 +250,21 @@ describe('ADR-1817 Phase 2: `state rebuild` CLI subcommand dispatch (criterion #
// Body fields reconciled with frontmatter.
const live = readLiveState(cwd);
assert.ok(live.includes('**Current Phase:** 2'),
assert.strictEqual(stateExtractField(live, 'Current Phase'), '2',
'body Current Phase must be reconciled to frontmatter value 2');
assert.ok(live.includes('**Current Phase Name:** Phase Two'),
assert.strictEqual(stateExtractField(live, 'Current Phase Name'), 'Phase Two',
'body Current Phase Name must be reconciled to frontmatter value');
// Orphan table row dropped (phase 99 is not on disk).
assert.ok(!live.includes('| 99 |'),
'orphan row for phase 99 must be dropped (phaseInventoryProvider wired to disk scan)');
const byPhaseTable = parseMarkdownTable(live);
assert.ok(byPhaseTable.ok, `By Phase table must parse; reason: ${byPhaseTable.ok ? '' : byPhaseTable.reason}`);
const phaseIds = byPhaseTable.value.rows.map((r) => r.Phase);
assert.ok(!phaseIds.includes('99'),
`orphan row for phase 99 must be dropped (phaseInventoryProvider wired to disk scan); rows: ${JSON.stringify(phaseIds)}`);
// Audit log appended.
const fullState = fs.readFileSync(path.join(cwd, '.planning', 'STATE.md'), 'utf8');
assert.ok(fullState.includes('## Rebuild Log'),
assert.ok(hasRebuildLogSection(fullState),
'audit log section must be appended');
});
@@ -155,9 +281,12 @@ describe('ADR-1817 Phase 2: `state rebuild` CLI subcommand dispatch (criterion #
'--dry-run must NOT modify STATE.md on disk');
// The structured output should signal mutations would occur (the fixture
// has drift, so mutated=true in dry-run preview).
assert.ok(result.output.includes('mutated'),
`dry-run output should report mutated flag; output: ${result.output}`);
// has drift, so mutated=true in dry-run preview). `state rebuild --dry-run`
// emits pure JSON to stdout (src/state.cts:3221 `cmdStateRebuild`'s dry-run
// branch: `emit({ ..., mutated, ... })`).
const parsed = JSON.parse(result.output);
assert.strictEqual(parsed.mutated, true,
`dry-run output should report mutated:true; output: ${result.output}`);
});
test('`state rebuild --verbose` emits audit-log entries to stderr', (t) => {
@@ -177,10 +306,14 @@ describe('ADR-1817 Phase 2: `state rebuild` CLI subcommand dispatch (criterion #
// tees the same entries to stderr. The functional guarantee (audit log
// written) is what matters; the stderr tee is a convenience.
const after = fs.readFileSync(path.join(cwd, '.planning', 'STATE.md'), 'utf8');
assert.ok(after.includes('## Rebuild Log'),
assert.ok(hasRebuildLogSection(after),
'--verbose must still produce the audit log section in STATE.md');
assert.ok(stdout.includes('rebuilt'),
`--verbose stdout must include the rebuild result; got: ${stdout.slice(0, 200)}`);
// The real (non-dry-run) path emits `{ rebuilt: capturedMutated, ... }`
// to stdout as pure JSON (src/state.cts:3254 `cmdStateRebuild`). The
// fixture has drift, so `rebuilt` must be true.
const parsedStdout = JSON.parse(stdout);
assert.strictEqual(parsedStdout.rebuilt, true,
`--verbose stdout must report rebuilt:true; got: ${stdout.slice(0, 200)}`);
});
test('`state rebuild` on a clean STATE.md is a no-op (idempotency, end-to-end)', (t) => {
@@ -207,11 +340,81 @@ describe('ADR-1817 Phase 2: `state rebuild` CLI subcommand dispatch (criterion #
// No STATE.md written.
const result = runGsdTools('state rebuild', cwd);
// The command emits an error result but does not crash the process.
const combined = `${result.output}\n${result.error || ''}`;
assert.ok(combined.includes('STATE.md not found'),
'missing STATE.md should produce a clean "STATE.md not found" message');
assert.ok(!combined.includes('at Object.'),
'no raw stack trace should leak into the output (CONTRIBUTING QA Matrix)');
// The command emits a typed JSON error result and exits 0 — it does not
// crash the process (src/state.cts:3136 `cmdStateRebuild`'s missing-file
// guard: `emit({ error: 'STATE.md not found' }, raw); return;`, no
// `process.exit`). `result.success` proves the clean exit (a crash would
// flip it to false and populate `result.error` with a raw stack trace
// instead); `JSON.parse` proves stdout is exactly the structured payload
// with nothing else — including no leaked stack-trace text — mixed in.
assert.ok(result.success,
`state rebuild on a missing STATE.md should exit cleanly (no crash); stderr: ${result.error || ''}`);
const parsed = JSON.parse(result.output);
assert.strictEqual(parsed.error, 'STATE.md not found',
`missing STATE.md should produce a typed error field; output: ${result.output}`);
});
});
// ---------------------------------------------------------------------------
// #3057 B1: the PRODUCTION `phaseInventoryProvider` closure (state.cts:3106),
// not just the pure `reconcileByPhaseTable` core, must distinguish a real
// disk-scan failure from a genuinely-empty/reconciled scan. In-process fault
// injection via `withFaultyFs` on the real `fs.readdirSync` the closure
// calls — never chmod, never the subprocess seam (both banned per
// tests/helpers/faulty-deps.cjs's module doc).
// ---------------------------------------------------------------------------
describe('#3057 B1: cmdStateRebuild (production adapter) surfaces a real phase-inventory scan failure', () => {
test('FAILURE path: readdirSync(.planning/phases) faulted → phase_inventory_scan_failed:true, table left untouched, mutated:false', (t) => {
const cwd = projectWithOnlyPhaseTableDrift();
t.after(() => cleanup(cwd));
const phasesDir = path.join(cwd, '.planning', 'phases');
const originalReaddirSync = fs.readdirSync;
const stdout = withFaultyFs({
readdirSync: (p, ...rest) => {
if (String(p) === phasesDir) {
throw Object.assign(new Error('EACCES: permission denied, scandir ' + phasesDir), { code: 'EACCES' });
}
return originalReaddirSync(p, ...rest);
},
}, () => captureStdout(() => {
stateMod.cmdStateRebuild(cwd, { dryRun: true }, false);
}));
const parsed = JSON.parse(stdout);
assert.strictEqual(parsed.phase_inventory_scan_failed, true,
`a faulted disk scan must report phase_inventory_scan_failed:true; got: ${stdout}`);
assert.strictEqual(parsed.mutated, false,
'nothing else drifted in this fixture, so mutated must stay false — the failure is carried ONLY by the dedicated field');
assert.strictEqual(parsed.phase_inventory_scan_reason,
'EACCES: permission denied, scandir ' + phasesDir,
`phase_inventory_scan_reason must carry the exact fault message from the injected readdirSync throw; got: ${JSON.stringify(parsed.phase_inventory_scan_reason)}`);
// The orphan row must survive untouched — a failed scan is not a
// trustworthy inventory to reconcile the table against.
const live = readLiveState(cwd);
const byPhaseTable = parseMarkdownTable(live);
assert.ok(byPhaseTable.ok, `By Phase table must parse; reason: ${byPhaseTable.ok ? '' : byPhaseTable.reason}`);
const phaseIds = byPhaseTable.value.rows.map((r) => r.Phase);
assert.ok(phaseIds.includes('99'),
`orphan row for phase 99 must be preserved when the scan failed; rows: ${JSON.stringify(phaseIds)}`);
});
test('BENIGN path: the same fixture with an unfaulted disk scan reconciles the table and reports no failure', (t) => {
const cwd = projectWithOnlyPhaseTableDrift();
t.after(() => cleanup(cwd));
const stdout = captureStdout(() => {
stateMod.cmdStateRebuild(cwd, { dryRun: true }, false);
});
const parsed = JSON.parse(stdout);
assert.strictEqual(parsed.phase_inventory_scan_failed, false,
`an unfaulted disk scan must report phase_inventory_scan_failed:false; got: ${stdout}`);
assert.strictEqual(parsed.mutated, true,
'the real disk scan finds phase 1 only, so the orphan row 99 is real drift the (dry-run) rebuild would fix');
assert.strictEqual(parsed.phase_inventory_scan_reason, undefined,
'a clean scan must leave phase_inventory_scan_reason absent, distinguishing it from a faulted scan');
});
});

View File

@@ -22,6 +22,7 @@ const {
transitionCore,
} = require('../gsd-core/bin/lib/state-transition.cjs');
const { stateExtractField } = require('../gsd-core/bin/lib/state-document.cjs');
const { parseMarkdownTable } = require('../gsd-core/bin/lib/markdown-table.cjs');
const fixedClock = Object.freeze({
today: () => '2026-06-29',
@@ -30,7 +31,12 @@ const fixedClock = Object.freeze({
});
const noProgress = () => null;
const noPhases = () => null;
// #3057 B1: `phaseInventoryProvider` returns a discriminated result, never a
// bare array-or-null — `{ ok: true, phases: [] }` is the genuinely-empty
// benign case ("nothing to reconcile"), distinct from `{ ok: false, reason }`
// (a scan that could not complete). See tests/helpers/faulty-deps.cjs and the
// dedicated describe block below for the failure-path coverage.
const noPhases = () => ({ ok: true, phases: [] });
const baseDeps = Object.freeze({
progressProvider: noProgress,
@@ -362,11 +368,14 @@ describe('ADR-1817 §2: rebuild reconciles **By Phase:** table via phaseInventor
);
const deps = {
...baseDeps,
phaseInventoryProvider: () => [
{ number: '1', name: 'Phase 1', planCount: 2, summaryCount: 2 },
{ number: '2', name: 'Phase 2', planCount: 3, summaryCount: 3 },
{ number: '3', name: 'Test Phase', planCount: 5, summaryCount: 4 },
],
phaseInventoryProvider: () => ({
ok: true,
phases: [
{ number: '1', name: 'Phase 1', planCount: 2, summaryCount: 2 },
{ number: '2', name: 'Phase 2', planCount: 3, summaryCount: 3 },
{ number: '3', name: 'Test Phase', planCount: 5, summaryCount: 4 },
],
}),
};
// First call with no phaseInventoryProvider → no-op (covered by its own test below).
// Re-run with the provider-wired deps:
@@ -389,11 +398,14 @@ describe('ADR-1817 §2: rebuild reconciles **By Phase:** table via phaseInventor
);
const deps = {
...baseDeps,
phaseInventoryProvider: () => [
{ number: '1', name: 'Phase 1', planCount: 2, summaryCount: 2 },
{ number: '2', name: 'Phase 2', planCount: 3, summaryCount: 3 },
{ number: '3', name: 'Test Phase', planCount: 5, summaryCount: 4 },
],
phaseInventoryProvider: () => ({
ok: true,
phases: [
{ number: '1', name: 'Phase 1', planCount: 2, summaryCount: 2 },
{ number: '2', name: 'Phase 2', planCount: 3, summaryCount: 3 },
{ number: '3', name: 'Test Phase', planCount: 5, summaryCount: 4 },
],
}),
};
const result = transitionCore(drifted, { kind: 'rebuild' }, deps);
assert.ok(result.content.includes('kind: by-phase-table-reconciled'),
@@ -405,7 +417,7 @@ describe('ADR-1817 §2: rebuild reconciles **By Phase:** table via phaseInventor
/\| 3 \| 5 \| - \| - \|\n/,
'| 3 | 5 | - | - |\n| 99 | 1 | - | - |\n',
);
// baseDeps.phaseInventoryProvider = noPhases (returns null) → step is no-op.
// baseDeps.phaseInventoryProvider = noPhases ({ ok: true, phases: [] }) → step is no-op.
const result = transitionCore(drifted, { kind: 'rebuild' }, baseDeps);
assert.ok(result.content.includes('| 99 |'),
'orphan row must be preserved when no canonical source is wired');
@@ -414,6 +426,60 @@ describe('ADR-1817 §2: rebuild reconciles **By Phase:** table via phaseInventor
});
});
// ---------------------------------------------------------------------------
// Tests — #3057 B1: a phase-inventory scan FAILURE must be distinguishable
// from a genuinely-empty scan. Before the fix both were `null`, so a real
// disk-scan failure and "no phases on disk" produced the identical result:
// `state rebuild` could report success while by-phase-table reconciliation
// silently never ran.
// ---------------------------------------------------------------------------
describe('#3057 B1: phaseInventoryProvider scan-failure is distinguishable from genuinely-empty', () => {
const drifted = () => cleanState().replace(
/\| 3 \| 5 \| - \| - \|\n/,
'| 3 | 5 | - | - |\n| 99 | 1 | - | - |\n',
);
test('FAILURE path: ok:false surfaces phase_inventory_scan_failed and leaves the table untouched', () => {
const deps = {
...baseDeps,
phaseInventoryProvider: () => ({ ok: false, reason: 'EACCES: permission denied, readdir .planning/phases' }),
};
const result = transitionCore(drifted(), { kind: 'rebuild' }, deps);
assert.strictEqual(result.data.phase_inventory_scan_failed, true,
'a scan failure must set phase_inventory_scan_failed:true on the result data');
assert.strictEqual(result.data.phase_inventory_scan_reason,
'EACCES: permission denied, readdir .planning/phases',
'the failure reason must be threaded through to the caller');
const table = parseMarkdownTable(result.content);
assert.ok(table.ok, `By Phase table must parse; reason: ${table.ok ? '' : table.reason}`);
const phaseIds = table.value.rows.map((r) => r.Phase);
assert.ok(phaseIds.includes('99'),
'orphan row must be preserved — a failed scan is not a trustworthy inventory to reconcile against');
assert.ok(!result.data.log.some((e) => e.kind === 'by-phase-table-reconciled'),
'a failed scan must not log a by-phase-table-reconciled entry (nothing was actually reconciled)');
});
test('BENIGN path: ok:true with an empty phases array reports no failure and no reconciliation', () => {
const deps = {
...baseDeps,
phaseInventoryProvider: () => ({ ok: true, phases: [] }),
};
const result = transitionCore(drifted(), { kind: 'rebuild' }, deps);
assert.strictEqual(result.data.phase_inventory_scan_failed, false,
'a genuinely-empty successful scan must report phase_inventory_scan_failed:false');
assert.strictEqual(result.data.phase_inventory_scan_reason, undefined,
'no reason field when the scan did not fail');
const table = parseMarkdownTable(result.content);
assert.ok(table.ok, `By Phase table must parse; reason: ${table.ok ? '' : table.reason}`);
const phaseIds = table.value.rows.map((r) => r.Phase);
assert.ok(phaseIds.includes('99'),
'orphan row is preserved (same visible outcome as the failure case — the DATA field is what distinguishes them)');
assert.ok(!result.data.log.some((e) => e.kind === 'by-phase-table-reconciled'),
'an empty inventory logs no reconciliation entry, same as the failure case');
});
});
// ---------------------------------------------------------------------------
// Tests — §5 + §6: regression guard (sync/prune unchanged by rebuild presence)
// ---------------------------------------------------------------------------

View File

@@ -676,6 +676,43 @@ describe('ADR-1769 Phase 3: completePhase progress derivation (roadmap)', () =>
assert.strictEqual(stateExtractField(result.content, 'Completed Phases'), '2');
assert.strictEqual(stateExtractField(result.content, 'Progress'), '40%');
});
// #3057 B9: `result.updated` must let a caller tell "recomputed from the
// roadmap" apart from "roadmap unavailable, left as-is". Before the fix,
// `stateReplaceField`'s return was truthy whenever the field pattern
// matched — regardless of whether the substituted text actually differed
// from `body` — so 'Completed Phases' (and 'Progress') were marked
// 'updated' even when nothing changed.
test('FAILURE path (roadmap unavailable): Completed Phases / Progress are NOT marked updated — left-as-is is distinguishable from recomputed', () => {
const nullDeps = { clock: fixedClock, progressProvider: noProgress, roadmapProvider: () => null };
const result = transitionCore(
completePhaseBody(),
{ kind: 'completePhase', phaseNum: '3', nextPhaseNum: '4', nextPhaseName: null, isLastPhase: false, planCount: 3, summaryCount: 3 },
nullDeps,
);
assert.ok(!result.updated.includes('Completed Phases'),
`left-as-is 'Completed Phases' must NOT appear in updated; got ${JSON.stringify(result.updated)}`);
assert.ok(!result.updated.includes('Progress'),
`left-as-is 'Progress' must NOT appear in updated; got ${JSON.stringify(result.updated)}`);
// Values are unchanged (the benign-preservation contract from the test above).
assert.strictEqual(stateExtractField(result.content, 'Completed Phases'), '2');
assert.strictEqual(stateExtractField(result.content, 'Progress'), '40%');
});
test('BENIGN path (roadmap recomputes a different value): Completed Phases / Progress ARE marked updated — recomputed is distinguishable from left-as-is', () => {
const result = transitionCore(
completePhaseBody(),
{ kind: 'completePhase', phaseNum: '3', nextPhaseNum: '4', nextPhaseName: null, isLastPhase: false, planCount: 3, summaryCount: 3 },
deps, // roadmapProvider => ROADMAP_3_OF_5, which recomputes Completed Phases 2 → 3
);
assert.ok(result.updated.includes('Completed Phases'),
`recomputed 'Completed Phases' must appear in updated; got ${JSON.stringify(result.updated)}`);
assert.ok(result.updated.includes('Progress'),
`recomputed 'Progress' must appear in updated; got ${JSON.stringify(result.updated)}`);
assert.strictEqual(stateExtractField(result.content, 'Completed Phases'), '3');
assert.strictEqual(stateExtractField(result.content, 'Progress'), '60%');
});
});
describe('ADR-1769 Phase 3: completePhase edge cases', () => {

View File

@@ -598,6 +598,80 @@ describe('evaluateUatPassed — policy.requireVerification', () => {
});
});
// ─── evaluateUatPassed — #3057 B3: staleness-check indeterminate is surfaced ──
//
// readVerificationStatus's internal staleness check can fail (fs /
// scanPhasePlans / clock error). Pre-#3057 B3 wiring, the requireVerification
// policy check used only `.status`, dropping `.staleCheckIndeterminate` on
// the floor — so cmdPhaseUatPassed's JSON output (which spreads this whole
// report) could never distinguish "checked; nothing is stale" from "could
// not check". `verification_stale_check_indeterminate` must never itself gate
// `passed`/`blockers` — only readVerificationStatus's `.status` may.
describe('#3057 B3: evaluateUatPassed — verification staleness-check indeterminate is surfaced', () => {
let tmpDir;
beforeEach(() => {
tmpDir = makeTmpDir();
});
afterEach(() => {
rmDir(tmpDir);
});
function seedVerifiedPhase() {
writeFile(tmpDir, 'phase-UAT.md', makePassingUat(1));
writeFile(tmpDir, 'phase-VERIFICATION.md', '---\nstatus: passed\n---\n\nOK.');
writeFile(tmpDir, 'phase-SUMMARY.md', '# Summary');
const verificationPath = path.join(tmpDir, 'phase-VERIFICATION.md');
const summaryPath = path.join(tmpDir, 'phase-SUMMARY.md');
// Deterministic mtime ordering — never rely on write-order clock ties.
const older = new Date('2026-01-01T00:00:00.000Z');
const newer = new Date('2026-01-01T00:01:00.000Z');
fs.utimesSync(summaryPath, older, older);
fs.utimesSync(verificationPath, newer, newer);
return { summaryPath, verificationPath };
}
test('an fs failure inside the staleness check sets verification_stale_check_indeterminate:true; passed/blockers unchanged', (t) => {
const { summaryPath, verificationPath } = seedVerifiedPhase();
const origStatSync = fs.statSync;
t.mock.method(fs, 'statSync', function injectedStaleCheckFault(target, ...args) {
const targetPath = String(target);
if (targetPath === verificationPath || targetPath === summaryPath) {
throw new Error('injected stat failure (#3057 B3)');
}
return origStatSync.call(fs, target, ...args);
});
const report = evaluateUatPassed(tmpDir, { policy: { requireVerification: true } });
// Pre-existing no-throw fail-open routing is UNCHANGED — `passed`/
// `blockers` are exactly what they would be without the injected fault.
assert.strictEqual(report.passed, true);
assert.deepStrictEqual(report.blockers, []);
assert.strictEqual(report.verification_stale_check_indeterminate, true);
});
test('a completed staleness check that finds nothing stale reports verification_stale_check_indeterminate:false', () => {
seedVerifiedPhase();
const report = evaluateUatPassed(tmpDir, { policy: { requireVerification: true } });
assert.strictEqual(report.passed, true);
assert.strictEqual(report.verification_stale_check_indeterminate, false);
});
test('requireVerification not set → verification_stale_check_indeterminate is always false (readVerificationStatus never reached)', () => {
seedVerifiedPhase();
const report = evaluateUatPassed(tmpDir, { policy: { requireVerification: false } });
assert.strictEqual(report.verification_stale_check_indeterminate, false);
});
});
// ─── evaluateUatPassed — malformed markdown guard ─────────────────────────────
describe('evaluateUatPassed — malformed markdown blocker', () => {

View File

@@ -802,6 +802,83 @@ describe('verification-status', () => {
});
// ─── #3057 B3: findStaleVerificationSummary — indeterminate vs not-stale ─────
//
// The pre-fix catch-all returned `null` on ANY fs / scanPhasePlans / clock
// failure — identical to a completed check that genuinely found nothing
// stale. `opts.fs` had never been exercised by any test. These two tests
// confirm (a) the `opts.fs` injection seam actually works, and (b) the two
// outcomes are now distinguishable via `staleCheckIndeterminate` on the
// `readVerificationStatus` result.
describe('#3057 B3: staleness check — indeterminate is distinguishable from not-stale', () => {
test('an fs failure inside the staleness check yields staleCheckIndeterminate:true, not a silent "not stale"', (t) => {
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3057-b3-fault-'));
t.after(() => cleanup(baseDir));
const dir = path.join(baseDir, '01-stale-check-fault');
fs.mkdirSync(dir);
const verificationPath = path.join(dir, '01-VERIFICATION.md');
const summaryPath = path.join(dir, '01-01-SUMMARY.md');
writeVerificationMd(dir, '01-VERIFICATION.md', 'passed');
fs.writeFileSync(summaryPath, '# Summary');
// The summary IS newer — if the check ran to completion it would find
// 'stale'. The point of this test is that it never gets to find out.
setMtime(verificationPath, '2026-01-01T00:00:00.000Z');
setMtime(summaryPath, '2026-01-01T00:01:00.000Z');
// Confirms opts.fs is actually threaded through: readdirSync/readFileSync
// delegate to the real fs (so "find the VERIFICATION.md" / "read its
// frontmatter" upstream of the staleness check still succeed normally),
// and ONLY statSync is faulted — driving findStaleVerificationSummary's
// catch branch specifically, via the injected seam, not a global monkeypatch.
const fsLike = {
readdirSync: (d) => fs.readdirSync(d),
readFileSync: (p, enc) => fs.readFileSync(p, enc),
statSync: () => { throw new Error('injected stat failure (#3057 B3)'); },
};
const result = readVerificationStatus(dir, {
fs: fsLike,
phaseCleanCommitTimesMs: () => new Map(),
});
// Pre-existing no-throw fail-open contract is UNCHANGED: routing still
// proceeds as if nothing were stale (status stays 'passed', not 'stale' —
// a genuinely-stale summary sits right there and would have tripped the
// 'stale' route had the check run to completion).
assert.equal(result.status, 'passed');
// But the cause is no longer silently identical to a completed "nothing
// is stale" check — this MUST be flagged as indeterminate.
assert.strictEqual(result.staleCheckIndeterminate, true);
});
test('a completed staleness check that finds nothing stale never reports indeterminate', (t) => {
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3057-b3-ok-'));
t.after(() => cleanup(baseDir));
const dir = path.join(baseDir, '01-stale-check-ok');
fs.mkdirSync(dir);
const verificationPath = path.join(dir, '01-VERIFICATION.md');
const summaryPath = path.join(dir, '01-01-SUMMARY.md');
writeVerificationMd(dir, '01-VERIFICATION.md', 'passed');
fs.writeFileSync(summaryPath, '# Summary');
// Verification NEWER than the summary → the check runs to completion
// (no fault injected) and genuinely finds nothing stale.
setMtime(summaryPath, '2026-01-01T00:00:00.000Z');
setMtime(verificationPath, '2026-01-01T00:01:00.000Z');
const result = readVerificationStatus(dir, { phaseCleanCommitTimesMs: () => new Map() });
assert.equal(result.status, 'passed');
assert.strictEqual(
result.staleCheckIndeterminate,
undefined,
'a completed check that found nothing stale must not be flagged indeterminate',
);
});
});
// ─── #2617: next_command runtime projection ──────────────────────────────────
//
// Regression tests for #2617 — verification-status `next_command` bypassed the

View File

@@ -1762,3 +1762,103 @@ describe('#2645 — deleting a verification report must not raise completeness',
'the in-milestone phase (2-new) must be recorded normally');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// #3057 B3: inspectWorkstream surfaces an indeterminate staleness check
//
// readVerificationStatus's internal staleness check can fail (fs /
// scanPhasePlans / clock error). Pre-#3057 B3 wiring, that failure was
// dropped here — `liveVerificationStatus` used only `.status` — so nothing
// could ever distinguish "checked; nothing is stale" from "could not check".
// `WorkstreamInventory`'s own return shape has no per-phase verification
// detail to carry this on, so it is surfaced via the SAME injectable
// stderr-diagnostic seam #3057 B4 added to cmdGitBaseBranch (see
// tests/git-base-branch.test.cjs), never via a change to `phases[]`/
// `completed_phases` — the rollup routing must stay byte-identical.
// ─────────────────────────────────────────────────────────────────────────────
describe('#3057 B3: inspectWorkstream — verification staleness-check indeterminate is surfaced', () => {
let tmpDir;
before(() => { tmpDir = createFixture(); });
after(() => cleanup(tmpDir));
const V2_STATE = 'milestone: v2.0\nstatus: executing\n';
function roadmapWithRows(rows) {
return [
'# Roadmap', '', '## Progress', '',
'| Phase | Milestone | Plans Complete | Status | Completed |',
'| --- | --- | --- | --- | --- |',
...rows,
'',
].join('\n');
}
/** Writes a verified phase directory with a deterministic (never-stale) mtime ordering. */
function writeVerifiedPhase(wsDir, slug) {
const dir = path.join(wsDir, 'phases', slug);
fs.mkdirSync(dir, { recursive: true });
const summaryPath = path.join(dir, '01-SUMMARY.md');
const verificationPath = path.join(dir, '01-VERIFICATION.md');
fs.writeFileSync(path.join(dir, '01-PLAN.md'), '# plan\n');
fs.writeFileSync(summaryPath, '# summary\n');
fs.writeFileSync(verificationPath, '---\nstatus: passed\n---\n');
// Deterministic mtime ordering — never rely on write-order clock ties.
const older = new Date('2026-01-01T00:00:00.000Z');
const newer = new Date('2026-01-01T00:01:00.000Z');
fs.utimesSync(summaryPath, older, older);
fs.utimesSync(verificationPath, newer, newer);
return { summaryPath, verificationPath };
}
test('an fs failure inside the staleness check writes a stderr diagnostic; the rollup is UNCHANGED', (t) => {
const wsDir = seedWorkstream(tmpDir, { name: 'ws-3057-b3-fault' });
fs.writeFileSync(path.join(wsDir, 'STATE.md'), V2_STATE);
fs.writeFileSync(path.join(wsDir, 'ROADMAP.md'), roadmapWithRows([
'| 1. Alpha | v2.0 | 1/1 | Complete | - |',
]));
const { summaryPath, verificationPath } = writeVerifiedPhase(wsDir, '1-alpha');
const origStatSync = fs.statSync;
t.mock.method(fs, 'statSync', function injectedStaleCheckFault(target, ...args) {
const targetPath = String(target);
if (targetPath === verificationPath || targetPath === summaryPath) {
throw new Error('injected stat failure (#3057 B3)');
}
return origStatSync.call(fs, target, ...args);
});
const calls = [];
const inv = inspectWorkstream(tmpDir, 'ws-3057-b3-fault', {
active: null,
writeDiagnostic: (message, meta) => { calls.push({ message, meta }); },
});
assert.ok(inv);
// Pre-existing no-throw fail-open routing is UNCHANGED: the rollup counts
// exactly what it would without the injected fault.
assert.equal(inv.completed_phases, 1, 'rollup routing unchanged');
assert.strictEqual(calls.length, 1, 'an indeterminate staleness check must write exactly one diagnostic');
assert.strictEqual(calls[0].meta.phaseDir, '1-alpha', 'diagnostic meta should name the affected phase directory');
assert.strictEqual(calls[0].meta.reason, 'staleCheckIndeterminate', 'diagnostic meta should carry a stable reason');
});
test('a completed staleness check that finds nothing stale writes NO diagnostic', () => {
const wsDir = seedWorkstream(tmpDir, { name: 'ws-3057-b3-ok' });
fs.writeFileSync(path.join(wsDir, 'STATE.md'), V2_STATE);
fs.writeFileSync(path.join(wsDir, 'ROADMAP.md'), roadmapWithRows([
'| 1. Alpha | v2.0 | 1/1 | Complete | - |',
]));
writeVerifiedPhase(wsDir, '1-alpha');
const calls = [];
const inv = inspectWorkstream(tmpDir, 'ws-3057-b3-ok', {
active: null,
writeDiagnostic: (message, meta) => { calls.push({ message, meta }); },
});
assert.ok(inv);
assert.equal(inv.completed_phases, 1);
assert.strictEqual(calls.length, 0, 'a completed, non-stale check must not write any diagnostic');
});
});

View File

@@ -16,6 +16,8 @@ const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const { makeFaultyGit } = require('./helpers/faulty-deps.cjs');
const MODULE_PATH = path.join(
__dirname, '..', 'gsd-core', 'bin', 'lib', 'worktree-base-ref.cjs'
);
@@ -380,6 +382,42 @@ describe('evaluateWorktreeBaseDegrade', () => {
assert.strictEqual(result.reason, 'no-head');
});
// ─── #3057 B8: headAbsenceVerified distinguishes the two "no-head" causes ──
//
// Both outcomes below keep `shouldDegrade:false, reason:'no-head'` — that
// product decision is deliberately UNCHANGED (pinned by the regression
// guards above and flagged in the #3050 review as still an open question).
// What changes is that a caller can now tell git's DEFINITIVE "not a git
// repository" answer (exit 128) apart from git completing but returning
// nothing useful (exit 0, empty stdout) — the module's own #380-383 comment
// named this gap; these two paired tests prove it is closed.
test('exit 128 — git\'s definitive "not a git repository" answer → headAbsenceVerified:true', () => {
const faultyGit = makeFaultyGit({
faults: [{ kind: 'exit', exitCode: 128, stderr: 'fatal: not a git repository' }],
});
const result = evaluateWorktreeBaseDegrade({ execGit: faultyGit });
assert.strictEqual(result.shouldDegrade, false);
assert.strictEqual(result.reason, 'no-head');
assert.strictEqual(result.headAbsenceVerified, true);
});
test('exit 0 with empty stdout — git completed but gave no useful answer → headAbsenceVerified:false', () => {
// makeFaultyGit()'s default passthrough IS exit 0 / empty stdout / no
// error / not timed out — a real, completed, but non-substantive answer.
const faultyGit = makeFaultyGit();
const result = evaluateWorktreeBaseDegrade({ execGit: faultyGit });
assert.strictEqual(result.shouldDegrade, false);
assert.strictEqual(result.reason, 'no-head');
assert.strictEqual(result.headAbsenceVerified, false);
});
test('headAbsenceVerified is null (not applicable) for a reason other than no-head', () => {
const result = evaluateWorktreeBaseDegrade({ effectiveBaseRef: 'head' });
assert.strictEqual(result.reason, 'baseref-head');
assert.strictEqual(result.headAbsenceVerified, null);
});
test('HEAD == origin/HEAD → no degrade, reason head-matches-fork', () => {
const HEAD_SHA = 'aabbccdd11223344aabbccdd11223344aabbccdd';
const result = evaluateWorktreeBaseDegrade({

View File

@@ -21,6 +21,7 @@ const path = require('node:path');
const childProcess = require('node:child_process');
const fc = require('fast-check');
const { createTempGitProject, createTempDir, cleanup } = require('./helpers.cjs');
const { makeFaultyGit } = require('./helpers/faulty-deps.cjs');
const WORKTREE_SAFETY_PATH = path.join(
__dirname, '..', 'gsd-core', 'bin', 'lib', 'worktree-safety.cjs'
@@ -405,7 +406,36 @@ describe('planWorktreePrune', () => {
},
});
assert.strictEqual(plan.action, 'metadata_prune_only');
assert.strictEqual(plan.reason, 'no_worktrees');
// #3050/#3057 (B6): a parse failure must NOT collide with the
// genuinely-empty-list verdict below ('no_worktrees') — see the paired
// test 'reason distinguishes a parse failure from a genuinely empty list'.
assert.strictEqual(plan.reason, 'parse_failed');
});
// Counter-test pair (B5/B6 negative-space, #3057): the same 0-worktrees
// shape must yield a DIFFERENT reason depending on WHY the list came back
// empty — a parser that threw vs a porcelain output that genuinely listed
// nothing. Asserting only one of these could not prove they are
// distinguishable; asserting both, side by side, proves it.
test('reason distinguishes a parse failure from a genuinely empty list', () => {
const failurePlan = planWorktreePrune('/repo/main', {}, {
execGit: () => ({ exitCode: 0, stdout: 'not-porcelain', stderr: '' }),
parseWorktreePorcelain: () => {
throw new Error('parse failed');
},
});
assert.strictEqual(failurePlan.action, 'metadata_prune_only');
assert.strictEqual(failurePlan.reason, 'parse_failed');
const benignPlan = planWorktreePrune('/repo/main', {}, {
execGit: () => ({ exitCode: 0, stdout: '', stderr: '' }),
parseWorktreePorcelain: () => [],
});
assert.strictEqual(benignPlan.action, 'metadata_prune_only');
assert.strictEqual(benignPlan.reason, 'no_worktrees');
assert.notStrictEqual(failurePlan.reason, benignPlan.reason,
'a parse failure must not be reported as the same reason as a genuinely empty worktree list');
});
// Counter-test: timeout path (Contract 6)
@@ -629,6 +659,41 @@ describe('inspectWorktreeHealth', () => {
const result = inspectWorktreeHealth('/tmp', {}, { execGit: makeTimeoutStub() });
assert.strictEqual(Array.isArray(result.findings), true, 'findings must be an array even when ok:false');
});
// Counter-test (B5, #3057): a statSync throw must surface as its own
// 'unverified' finding, distinct from 'orphan' (the case above, where
// existsSync itself says the path is absent). Silently producing NO finding
// for an unverifiable worktree would be the fail-open this row exists to close.
test('reports an unverified finding (not silently healthy, not orphan) when statSync throws', () => {
const health = inspectWorktreeHealth(
'/repo/main',
{ staleAfterMs: 60 * 60 * 1000, nowMs: 2 * 60 * 60 * 1000 },
{
execGit: () => ({
exitCode: 0,
stdout: [
'worktree /repo/main',
'HEAD aaa',
'branch refs/heads/main',
'',
'worktree /repo/wt-unverified',
'HEAD bbb',
'branch refs/heads/feat-a',
'',
].join('\n'),
stderr: '',
}),
existsSync: () => true,
statSync: () => {
throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' });
},
}
);
assert.strictEqual(health.ok, true);
assert.deepStrictEqual(health.findings, [
{ kind: 'unverified', path: '/repo/wt-unverified' },
]);
});
});
// ─── snapshotWorktreeInventory ────────────────────────────────────────────────
@@ -663,8 +728,8 @@ describe('snapshotWorktreeInventory', () => {
);
assert.strictEqual(inventory.ok, true);
assert.deepStrictEqual(inventory.entries, [
{ path: '/repo/wt-a', exists: true, isStale: true, ageMinutes: 120 },
{ path: '/repo/wt-b', exists: false, isStale: false, ageMinutes: null },
{ path: '/repo/wt-a', exists: 'present', isStale: true, ageMinutes: 120 },
{ path: '/repo/wt-b', exists: 'absent', isStale: false, ageMinutes: null },
]);
});
@@ -694,6 +759,52 @@ describe('snapshotWorktreeInventory', () => {
'must use reason=git_timed_out when execGit returns timedOut:true'
);
});
// Counter-test pair (B5, #3057): a statSync throw must NOT be reported as
// exists:'present' (unverified presence masquerading as confirmed presence),
// and must be distinguishable from a genuinely-absent worktree (existsSync
// returns false for a different entry in the SAME call). Asserting only one
// side could not prove the two are distinguishable.
test("exists is 'unverified' (not 'present') when statSync throws — distinct from a genuinely absent worktree", () => {
const porcelain = [
'worktree /repo/main',
'HEAD aaa',
'branch refs/heads/main',
'',
'worktree /repo/wt-unverified',
'HEAD bbb',
'branch refs/heads/feat-a',
'',
'worktree /repo/wt-absent',
'HEAD ccc',
'branch refs/heads/feat-b',
'',
].join('\n');
const inventory = snapshotWorktreeInventory(
'/repo/main',
{ staleAfterMs: 60 * 60 * 1000, nowMs: 2 * 60 * 60 * 1000 },
{
execGit: () => ({ exitCode: 0, stdout: porcelain, stderr: '' }),
existsSync: (p) => p !== '/repo/wt-absent',
statSync: (p) => {
if (p === '/repo/wt-unverified') {
throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' });
}
return { mtimeMs: 0 };
},
}
);
assert.strictEqual(inventory.ok, true);
assert.deepStrictEqual(inventory.entries, [
{ path: '/repo/wt-unverified', exists: 'unverified', isStale: false, ageMinutes: null },
{ path: '/repo/wt-absent', exists: 'absent', isStale: false, ageMinutes: null },
]);
assert.notStrictEqual(
inventory.entries[0].exists,
inventory.entries[1].exists,
'an unverifiable statSync failure must not collapse to the same exists value as a genuinely absent worktree'
);
});
});
// ─── Degraded-git prune flow (AC3) ───────────────────────────────────────────
@@ -2922,6 +3033,111 @@ describe('executeWorktreeWaveCleanupPlan', () => {
assert.equal(result.ok, true, 'cleanup can still succeed after rescuing on cat-file timeout');
});
// ─── B7 (#3050/#3057): rescue-anyway on an uncertain cat-file, via the
// Phase 2 fault-injection adapter (makeFaultyGit) rather than a hand-rolled
// key-matching stub. The two tests above already prove the verdict with
// hand-written mocks; these prove it again through the in-process fault
// seam the epic standardized on, for both fault shapes the design calls
// "uncertain": a fatal exit (128) and a timeout.
//
// #3057 finding: `git cat-file -e` returns exit 128 BOTH for the normal
// "absent from HEAD" case (#2556's own comment above, line ~2833) and for a
// genuine fatal git error — there is no third exit code that means
// "confirmed absent, no ambiguity" as opposed to "uncertain". The
// production code's own non-zero-exit check (`catFileResult.exitCode === 0
// ? skip : rescue`) therefore CANNOT distinguish "uncertain" from
// "certain-and-fine" — every non-zero exit, whatever its cause, is uncertain
// by construction, and #2556 rescues all of them uniformly. That is not a
// gap the tests below can paper over: it is the reason "rescue whenever not
// confirmed committed" is the whole rule, rather than a narrower
// uncertain-only carve-out.
function makeWaveCleanupPassthrough() {
return (args) => {
const key = args.join(' ');
if (key === '-C /repo/.claude/worktrees/agent-a1 rev-parse --abbrev-ref HEAD') {
return { exitCode: 0, stdout: 'worktree-agent-a1', stderr: '', signal: null, error: null, timedOut: false };
}
if (key === 'merge-base HEAD worktree-agent-a1') {
return { exitCode: 0, stdout: 'abc123', stderr: '', signal: null, error: null, timedOut: false };
}
if (key === 'diff --diff-filter=D --name-only HEAD...worktree-agent-a1') {
return { exitCode: 0, stdout: '', stderr: '', signal: null, error: null, timedOut: false };
}
if (key === '-C /repo/.claude/worktrees/agent-a1 status --porcelain --untracked-files=all') {
return { exitCode: 0, stdout: '', stderr: '', signal: null, error: null, timedOut: false };
}
if (key.startsWith('merge worktree-agent-a1')) {
return { exitCode: 0, stdout: '', stderr: '', signal: null, error: null, timedOut: false };
}
if (key === 'worktree remove /repo/.claude/worktrees/agent-a1 --force') {
return { exitCode: 0, stdout: '', stderr: '', signal: null, error: null, timedOut: false };
}
if (key === 'branch -D worktree-agent-a1') {
return { exitCode: 0, stdout: '', stderr: '', signal: null, error: null, timedOut: false };
}
return { exitCode: 0, stdout: '', stderr: '', signal: null, error: null, timedOut: false };
};
}
const waveCleanupPlanFixture = {
ok: true,
repoRoot: '/repo/main',
action: 'cleanup_wave',
discovery: 'manifest',
entries: [{
agent_id: 'a1',
worktree_path: '/repo/.claude/worktrees/agent-a1',
branch: 'worktree-agent-a1',
expected_base: 'abc123',
}],
};
test('#3057/B7 (makeFaultyGit): cat-file exit 128 still rescues anyway (deliberate, #2556)', () => {
const rescued = [];
const execGit = makeFaultyGit({
faults: [{ kind: 'exit', exitCode: 128, when: (args) => args.includes('cat-file') }],
passthrough: makeWaveCleanupPassthrough(),
});
const result = executeWorktreeWaveCleanupPlan(waveCleanupPlanFixture, {
execGit,
findSummaryFiles: (worktreePath) => (
worktreePath === '/repo/.claude/worktrees/agent-a1'
? ['/repo/.claude/worktrees/agent-a1/.planning/q1-SUMMARY.md']
: []
),
readFileSync: () => 'summary content',
existsSync: () => false,
mkdirSync: () => {},
copyFileSync: (src, dest) => { rescued.push({ src, dest }); },
});
assert.strictEqual(rescued.length, 1,
'an uncertain cat-file (exit 128) must still rescue — the deliberate #2556 verdict');
assert.strictEqual(result.ok, true);
});
test('#3057/B7 (makeFaultyGit): cat-file timeout still rescues anyway (deliberate, #2556)', () => {
const rescued = [];
const execGit = makeFaultyGit({
faults: [{ kind: 'timeout', when: (args) => args.includes('cat-file') }],
passthrough: makeWaveCleanupPassthrough(),
});
const result = executeWorktreeWaveCleanupPlan(waveCleanupPlanFixture, {
execGit,
findSummaryFiles: (worktreePath) => (
worktreePath === '/repo/.claude/worktrees/agent-a1'
? ['/repo/.claude/worktrees/agent-a1/.planning/q1-SUMMARY.md']
: []
),
readFileSync: () => 'summary content',
existsSync: () => false,
mkdirSync: () => {},
copyFileSync: (src, dest) => { rescued.push({ src, dest }); },
});
assert.strictEqual(rescued.length, 1,
'an uncertain cat-file (timeout) must still rescue — the deliberate #2556 verdict, same as exit 128');
assert.strictEqual(result.ok, true);
});
test('blocks dirty worktrees before merge/remove/delete', () => {
const calls = [];
const plan = {