Files
msd-core/tests/worktree-base-ref.test.cjs
Tom Boucher 53ea8e0664 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>
2026-08-05 16:00:52 -04:00

1040 lines
44 KiB
JavaScript

'use strict';
/**
* Worktree Base-Ref Module — unit tests
*
* Seam: gsd-core/bin/lib/worktree-base-ref.cjs
* Interface: shortSha, readBaseRefFromSettings, applyWorktreeBaseRef,
* resolveEffectiveBaseRef, evaluateWorktreeBaseDegrade
*
* Issue #683: worktree base-mismatch detection and degradation logic.
* All tests use dependency injection (inline stubs) — no real filesystem
* or real git is exercised.
*/
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'
);
const {
shortSha,
readBaseRefFromSettings,
applyWorktreeBaseRef,
resolveEffectiveBaseRef,
evaluateWorktreeBaseDegrade,
cmdWorktreeBaseCheck,
cmdWorktreeSetBaseRef,
} = require(MODULE_PATH);
// ─── shortSha ────────────────────────────────────────────────────────────────
describe('shortSha', () => {
test('returns first 8 chars of a full sha', () => {
assert.strictEqual(shortSha('abc123def456789'), 'abc123de');
});
test('returns the string itself when shorter than 8 chars', () => {
assert.strictEqual(shortSha('abc12'), 'abc12');
});
test('returns empty string for null', () => {
assert.strictEqual(shortSha(null), '');
});
test('returns empty string for empty string', () => {
assert.strictEqual(shortSha(''), '');
});
test('returns exactly 8 chars when sha is exactly 8 chars', () => {
assert.strictEqual(shortSha('12345678'), '12345678');
});
});
// ─── readBaseRefFromSettings ─────────────────────────────────────────────────
describe('readBaseRefFromSettings', () => {
test('returns baseRef when present as a string', () => {
assert.strictEqual(readBaseRefFromSettings({ worktree: { baseRef: 'head' } }), 'head');
});
test('returns baseRef value "fresh"', () => {
assert.strictEqual(readBaseRefFromSettings({ worktree: { baseRef: 'fresh' } }), 'fresh');
});
test('returns null when worktree is missing', () => {
assert.strictEqual(readBaseRefFromSettings({}), null);
});
test('returns null when settings is null', () => {
assert.strictEqual(readBaseRefFromSettings(null), null);
});
test('returns null when settings is undefined', () => {
assert.strictEqual(readBaseRefFromSettings(undefined), null);
});
test('returns null when worktree is not an object (string)', () => {
assert.strictEqual(readBaseRefFromSettings({ worktree: 'not-an-object' }), null);
});
test('returns null when baseRef is a number (non-string)', () => {
assert.strictEqual(readBaseRefFromSettings({ worktree: { baseRef: 42 } }), null);
});
test('returns null when baseRef is null', () => {
assert.strictEqual(readBaseRefFromSettings({ worktree: { baseRef: null } }), null);
});
test('returns null when baseRef is undefined', () => {
assert.strictEqual(readBaseRefFromSettings({ worktree: { baseRef: undefined } }), null);
});
});
// ─── applyWorktreeBaseRef ─────────────────────────────────────────────────────
describe('applyWorktreeBaseRef', () => {
test('sets baseRef to "head" when absent, returns changed:true', () => {
const settings = {};
const result = applyWorktreeBaseRef(settings);
assert.strictEqual(result.changed, true);
assert.strictEqual(result.skipped, null);
assert.strictEqual(result.previous, null);
assert.strictEqual(result.settings.worktree.baseRef, 'head');
});
test('sets baseRef to "head" when worktree key is missing entirely', () => {
const settings = { other: 'value' };
const result = applyWorktreeBaseRef(settings);
assert.strictEqual(result.changed, true);
assert.strictEqual(settings.worktree.baseRef, 'head');
});
test('sets baseRef to "head" when worktree.baseRef is null', () => {
const settings = { worktree: { baseRef: null, otherKey: 'keep' } };
const result = applyWorktreeBaseRef(settings);
assert.strictEqual(result.changed, true);
assert.strictEqual(settings.worktree.baseRef, 'head');
});
test('sets baseRef to "head" when worktree.baseRef is undefined', () => {
const settings = { worktree: { baseRef: undefined } };
const result = applyWorktreeBaseRef(settings);
assert.strictEqual(result.changed, true);
assert.strictEqual(settings.worktree.baseRef, 'head');
});
test('preserves other worktree.* keys when setting baseRef', () => {
const settings = { worktree: { otherKey: 'preserved', anotherKey: 123 } };
applyWorktreeBaseRef(settings);
assert.strictEqual(settings.worktree.otherKey, 'preserved');
assert.strictEqual(settings.worktree.anotherKey, 123);
assert.strictEqual(settings.worktree.baseRef, 'head');
});
test('mutates settings in place and returns the same object reference', () => {
const settings = {};
const result = applyWorktreeBaseRef(settings);
assert.strictEqual(result.settings, settings);
});
test('returns already-head skip when baseRef is already "head"', () => {
const settings = { worktree: { baseRef: 'head' } };
const result = applyWorktreeBaseRef(settings);
assert.strictEqual(result.changed, false);
assert.strictEqual(result.skipped, 'already-head');
assert.strictEqual(result.previous, 'head');
assert.strictEqual(settings.worktree.baseRef, 'head');
});
test('returns explicit-other skip when baseRef is "fresh", does NOT overwrite', () => {
const settings = { worktree: { baseRef: 'fresh' } };
const result = applyWorktreeBaseRef(settings);
assert.strictEqual(result.changed, false);
assert.strictEqual(result.skipped, 'explicit-other');
assert.strictEqual(result.previous, 'fresh');
assert.strictEqual(settings.worktree.baseRef, 'fresh');
});
test('returns explicit-other skip for any other string value', () => {
const settings = { worktree: { baseRef: 'some-branch' } };
const result = applyWorktreeBaseRef(settings);
assert.strictEqual(result.changed, false);
assert.strictEqual(result.skipped, 'explicit-other');
assert.strictEqual(result.previous, 'some-branch');
});
});
// ─── resolveEffectiveBaseRef ──────────────────────────────────────────────────
describe('resolveEffectiveBaseRef', () => {
// Helper to build a path-keyed readFile stub
function makeReadFile(files) {
return (p) => (Object.prototype.hasOwnProperty.call(files, p) ? files[p] : null);
}
test('returns baseRef from settings.local.json when present', () => {
const claudeDir = '/repo/.claude';
const deps = {
readFile: makeReadFile({
[path.join(claudeDir, 'settings.local.json')]: JSON.stringify({ worktree: { baseRef: 'head' } }),
[path.join(claudeDir, 'settings.json')]: JSON.stringify({ worktree: { baseRef: 'fresh' } }),
}),
};
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps), 'head');
});
test('falls back to settings.json when settings.local.json has no baseRef', () => {
const claudeDir = '/repo/.claude';
const deps = {
readFile: makeReadFile({
[path.join(claudeDir, 'settings.local.json')]: JSON.stringify({ other: 'value' }),
[path.join(claudeDir, 'settings.json')]: JSON.stringify({ worktree: { baseRef: 'fresh' } }),
}),
};
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps), 'fresh');
});
test('returns null when both files are missing', () => {
const claudeDir = '/repo/.claude';
const deps = { readFile: () => null };
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps), null);
});
test('returns null when both files exist but have no baseRef', () => {
const claudeDir = '/repo/.claude';
const deps = {
readFile: makeReadFile({
[path.join(claudeDir, 'settings.local.json')]: JSON.stringify({ other: 'value' }),
[path.join(claudeDir, 'settings.json')]: JSON.stringify({ other: 'value2' }),
}),
};
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps), null);
});
test('ignores malformed JSON in settings.local.json and falls back', () => {
const claudeDir = '/repo/.claude';
const deps = {
readFile: makeReadFile({
[path.join(claudeDir, 'settings.local.json')]: 'not valid json {{{',
[path.join(claudeDir, 'settings.json')]: JSON.stringify({ worktree: { baseRef: 'head' } }),
}),
};
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps), 'head');
});
test('ignores malformed JSON in settings.json', () => {
const claudeDir = '/repo/.claude';
const deps = {
readFile: makeReadFile({
[path.join(claudeDir, 'settings.local.json')]: null,
[path.join(claudeDir, 'settings.json')]: 'not valid json',
}),
};
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps), null);
});
test('settings.local.json null baseRef falls back to settings.json', () => {
const claudeDir = '/repo/.claude';
const deps = {
readFile: makeReadFile({
[path.join(claudeDir, 'settings.local.json')]: JSON.stringify({ worktree: { baseRef: null } }),
[path.join(claudeDir, 'settings.json')]: JSON.stringify({ worktree: { baseRef: 'fresh' } }),
}),
};
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps), 'fresh');
});
});
// ─── evaluateWorktreeBaseDegrade ──────────────────────────────────────────────
describe('evaluateWorktreeBaseDegrade', () => {
// Stub helper: matches on args.join(' ') and returns canned results
function makeExecGit(responses) {
return function stubExecGit(args, _opts) {
const key = args.join(' ');
if (Object.prototype.hasOwnProperty.call(responses, key)) {
return responses[key];
}
// Default: fail with a helpful error to surface unexpected calls
throw new Error(`Unexpected execGit call: ${JSON.stringify(args)}`);
};
}
test('effectiveBaseRef="head" → no degrade, reason baseref-head, execGit never called', () => {
let called = false;
const result = evaluateWorktreeBaseDegrade({
execGit: () => { called = true; return { exitCode: 0, stdout: '', stderr: '', signal: null, error: null }; },
effectiveBaseRef: 'head',
});
assert.strictEqual(result.shouldDegrade, false);
assert.strictEqual(result.reason, 'baseref-head');
assert.strictEqual(result.message, null);
assert.strictEqual(result.headSha, null);
assert.strictEqual(result.forkRef, null);
assert.strictEqual(result.forkSha, null);
assert.strictEqual(called, false, 'execGit must not be called when effectiveBaseRef is head');
});
test('git rev-parse HEAD fails → no degrade, reason no-head', () => {
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 128, stdout: '', stderr: 'fatal: not a git repo', signal: null, error: null },
}),
});
assert.strictEqual(result.shouldDegrade, false);
assert.strictEqual(result.reason, 'no-head');
assert.strictEqual(result.headSha, null);
});
test('git rev-parse HEAD returns empty stdout → no degrade, reason no-head', () => {
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 0, stdout: '', stderr: '', signal: null, error: null },
}),
});
assert.strictEqual(result.shouldDegrade, false);
assert.strictEqual(result.reason, 'no-head');
});
// ─── #3050: fail-closed matrix for git rev-parse HEAD outcomes ─────────────
// DECIDED RULE: degrade UNLESS git completed and gave a definitive answer.
// - timeout → degrade, reason 'head-unresolvable'
// - exitCode === 128 → NO degrade, reason 'no-head' (unchanged)
// - exit 0 with non-empty sha → proceed (unchanged)
// - anything else (127, other → degrade, reason 'head-unresolvable'
// non-zero, exit 0 empty stdout
// is pinned separately above)
test('git rev-parse HEAD TIMES OUT → shouldDegrade:true, reason "head-unresolvable" (#3050)', () => {
const timedOutErr = new Error('spawnSync git ETIMEDOUT');
timedOutErr.code = 'ETIMEDOUT';
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: null, stdout: '', stderr: '', signal: 'SIGTERM', error: timedOutErr },
}),
});
assert.strictEqual(result.shouldDegrade, true);
assert.strictEqual(result.reason, 'head-unresolvable');
assert.ok(result.message, 'a fail-closed degrade must carry a non-null explanatory message');
assert.strictEqual(result.headSha, null);
});
test('cross-platform: timeout WITHOUT signal set (Windows shape) still degrades (#3050)', () => {
// Node.js guarantees error.code === 'ETIMEDOUT' cross-platform when the
// spawnSync `timeout` option fires; `signal` reporting is the
// platform-fragile half and must not be required to detect a timeout.
const timedOutErr = new Error('spawnSync git ETIMEDOUT');
timedOutErr.code = 'ETIMEDOUT';
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: null, stdout: '', stderr: '', signal: null, error: timedOutErr },
}),
});
assert.strictEqual(result.shouldDegrade, true);
assert.strictEqual(result.reason, 'head-unresolvable');
});
test('git missing (exitCode 127) → degrade, reason "head-unresolvable" (#3050)', () => {
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 127, stdout: '', stderr: 'git: not found', signal: null, error: null },
}),
});
assert.strictEqual(result.shouldDegrade, true);
assert.strictEqual(result.reason, 'head-unresolvable');
});
// Boundary coverage: 128 is the ONLY benign non-zero exit (definitive "not a
// git repository"). 129 (limit+1) must NOT be swept into that carve-out.
test('exitCode 129 (limit+1 boundary, just past the 128 carve-out) → degrade, reason "head-unresolvable" (#3050)', () => {
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 129, stdout: '', stderr: 'fatal: something else', signal: null, error: null },
}),
});
assert.strictEqual(result.shouldDegrade, true);
assert.strictEqual(result.reason, 'head-unresolvable');
});
test('other non-zero, non-128 exit → degrade, reason "head-unresolvable" (#3050)', () => {
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 1, stdout: '', stderr: 'fatal: something else', signal: null, error: null },
}),
});
assert.strictEqual(result.shouldDegrade, true);
assert.strictEqual(result.reason, 'head-unresolvable');
});
test('exitCode 128 ("not a git repository") still does NOT degrade (#3050 regression guard)', () => {
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 128, stdout: '', stderr: 'fatal: not a git repository', signal: null, error: null },
}),
});
assert.strictEqual(result.shouldDegrade, false);
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({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 0, stdout: HEAD_SHA, stderr: '', signal: null, error: null },
'rev-parse --verify --quiet origin/HEAD': { exitCode: 0, stdout: HEAD_SHA, stderr: '', signal: null, error: null },
}),
});
assert.strictEqual(result.shouldDegrade, false);
assert.strictEqual(result.reason, 'head-matches-fork');
assert.strictEqual(result.headSha, HEAD_SHA);
assert.strictEqual(result.forkRef, 'origin/HEAD');
assert.strictEqual(result.forkSha, HEAD_SHA);
assert.strictEqual(result.message, null);
});
test('HEAD != origin/HEAD → degrade, reason head-diverged-from-fork, MSG_DIVERGED', () => {
const HEAD_SHA = 'deadbeef11223344deadbeef11223344deadbeef';
const FORK_SHA = 'cafebabe11223344cafebabe11223344cafebabe';
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 0, stdout: HEAD_SHA, stderr: '', signal: null, error: null },
'rev-parse --verify --quiet origin/HEAD': { exitCode: 0, stdout: FORK_SHA, stderr: '', signal: null, error: null },
}),
});
assert.strictEqual(result.shouldDegrade, true);
assert.strictEqual(result.reason, 'head-diverged-from-fork');
assert.strictEqual(result.headSha, HEAD_SHA);
assert.strictEqual(result.forkRef, 'origin/HEAD');
assert.strictEqual(result.forkSha, FORK_SHA);
// Verify message contains the short SHAs and the issue reference
const expectedMsg = `⚠ Worktree base mismatch: HEAD (${HEAD_SHA.slice(0, 8)}) differs from origin/HEAD (${FORK_SHA.slice(0, 8)}). Running this phase sequentially on the main working tree. To keep parallel worktrees, set worktree.baseRef:"head" in .claude/settings.local.json (or run: gsd-tools worktree set-baseref). See #683.`;
assert.strictEqual(result.message, expectedMsg);
});
test('origin/HEAD fails but symbolic-ref resolves to refs/remotes/origin/next', () => {
const HEAD_SHA = 'aaaa1111bbbb2222aaaa1111bbbb2222aaaa1111';
const FORK_SHA = 'cccc3333dddd4444cccc3333dddd4444cccc3333';
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 0, stdout: HEAD_SHA, stderr: '', signal: null, error: null },
'rev-parse --verify --quiet origin/HEAD': { exitCode: 1, stdout: '', stderr: '', signal: null, error: null },
'symbolic-ref --quiet refs/remotes/origin/HEAD': { exitCode: 0, stdout: 'refs/remotes/origin/next', stderr: '', signal: null, error: null },
'rev-parse --verify --quiet refs/remotes/origin/next': { exitCode: 0, stdout: FORK_SHA, stderr: '', signal: null, error: null },
}),
});
assert.strictEqual(result.forkRef, 'origin/next');
assert.strictEqual(result.forkSha, FORK_SHA);
// HEAD != FORK_SHA in this fixture → degrade
assert.strictEqual(result.shouldDegrade, true);
assert.strictEqual(result.reason, 'head-diverged-from-fork');
assert.ok(result.message !== null);
assert.ok(result.message.includes('origin/next'));
});
test('origin/HEAD fails AND symbolic-ref fails → degrade, reason fork-ref-unknown, MSG_UNKNOWN', () => {
const HEAD_SHA = 'eeee5555ffff6666eeee5555ffff6666eeee5555';
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 0, stdout: HEAD_SHA, stderr: '', signal: null, error: null },
'rev-parse --verify --quiet origin/HEAD': { exitCode: 1, stdout: '', stderr: '', signal: null, error: null },
'symbolic-ref --quiet refs/remotes/origin/HEAD': { exitCode: 1, stdout: '', stderr: '', signal: null, error: null },
}),
});
assert.strictEqual(result.shouldDegrade, true);
assert.strictEqual(result.reason, 'fork-ref-unknown');
assert.strictEqual(result.forkRef, null);
assert.strictEqual(result.forkSha, null);
const expectedMsg = `⚠ Cannot determine the worktree fork base (origin/HEAD unresolved). Running this phase sequentially on the main working tree to avoid a base mismatch. To keep parallel worktrees, set worktree.baseRef:"head" in .claude/settings.local.json (or run: gsd-tools worktree set-baseref). See #683.`;
assert.strictEqual(result.message, expectedMsg);
});
test('cwd is passed through to execGit calls', () => {
const HEAD_SHA = '1234567890abcdef1234567890abcdef12345678';
const capturedOpts = [];
const result = evaluateWorktreeBaseDegrade({
cwd: '/some/worktree',
execGit: (args, opts) => {
capturedOpts.push(opts);
const key = args.join(' ');
if (key === 'rev-parse HEAD') return { exitCode: 0, stdout: HEAD_SHA, stderr: '', signal: null, error: null };
if (key === 'rev-parse --verify --quiet origin/HEAD') return { exitCode: 0, stdout: HEAD_SHA, stderr: '', signal: null, error: null };
throw new Error(`Unexpected: ${key}`);
},
});
assert.strictEqual(result.shouldDegrade, false);
assert.ok(capturedOpts.length > 0);
for (const opts of capturedOpts) {
assert.strictEqual(opts && opts.cwd, '/some/worktree');
}
});
test('symbolic-ref resolves but subsequent rev-parse fails → falls through to fork-ref-unknown', () => {
const HEAD_SHA = 'abcd1234abcd1234abcd1234abcd1234abcd1234';
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 0, stdout: HEAD_SHA, stderr: '', signal: null, error: null },
'rev-parse --verify --quiet origin/HEAD': { exitCode: 1, stdout: '', stderr: '', signal: null, error: null },
'symbolic-ref --quiet refs/remotes/origin/HEAD': { exitCode: 0, stdout: 'refs/remotes/origin/main', stderr: '', signal: null, error: null },
'rev-parse --verify --quiet refs/remotes/origin/main': { exitCode: 1, stdout: '', stderr: '', signal: null, error: null },
}),
});
assert.strictEqual(result.shouldDegrade, true);
assert.strictEqual(result.reason, 'fork-ref-unknown');
assert.strictEqual(result.forkRef, null);
assert.strictEqual(result.forkSha, null);
});
});
// ─── cmdWorktreeBaseCheck ─────────────────────────────────────────────────────
describe('cmdWorktreeBaseCheck', () => {
function makeExecGitCheck(responses) {
return function stubExecGit(args, _opts) {
const key = args.join(' ');
if (Object.prototype.hasOwnProperty.call(responses, key)) {
return responses[key];
}
throw new Error(`Unexpected execGit call: ${JSON.stringify(args)}`);
};
}
test('baseRef=head in settings → shouldDegrade false, reason baseref-head; write emits valid JSON', () => {
const cwd = '/repo';
const claudeDir = '/repo/.claude';
let written = '';
const deps = {
readFile: (p) => {
if (p === path.join(claudeDir, 'settings.local.json')) return JSON.stringify({ worktree: { baseRef: 'head' } });
return null;
},
execGit: makeExecGitCheck({}),
write: (s) => { written += s; },
// Hermetic: point userClaudeDir at a non-existent path so real ~/.claude is never read
userClaudeDir: '/nonexistent-hermetic-user-dir',
};
const result = cmdWorktreeBaseCheck(cwd, [], deps);
assert.strictEqual(result.shouldDegrade, false);
assert.strictEqual(result.reason, 'baseref-head');
const parsed = JSON.parse(written);
assert.deepStrictEqual(parsed, result);
});
test('diverged shas → shouldDegrade true; captured JSON parses correctly', () => {
const cwd = '/repo';
const HEAD_SHA = 'deadbeef11223344deadbeef11223344deadbeef';
const FORK_SHA = 'cafebabe11223344cafebabe11223344cafebabe';
let written = '';
const deps = {
readFile: () => null,
execGit: makeExecGitCheck({
'rev-parse HEAD': { exitCode: 0, stdout: HEAD_SHA, stderr: '', signal: null, error: null },
'rev-parse --verify --quiet origin/HEAD': { exitCode: 0, stdout: FORK_SHA, stderr: '', signal: null, error: null },
}),
write: (s) => { written += s; },
// Hermetic: point userClaudeDir at a non-existent path so real ~/.claude is never read
userClaudeDir: '/nonexistent-hermetic-user-dir',
};
const result = cmdWorktreeBaseCheck(cwd, [], deps);
assert.strictEqual(result.shouldDegrade, true);
const parsed = JSON.parse(written);
assert.strictEqual(parsed.shouldDegrade, true);
assert.strictEqual(parsed.reason, 'head-diverged-from-fork');
});
});
// ─── cmdWorktreeSetBaseRef ────────────────────────────────────────────────────
describe('cmdWorktreeSetBaseRef', () => {
test('readFile returns {} → changed true, writeFile called with worktree.baseRef "head"', () => {
const cwd = '/repo';
const file = path.join(cwd, '.claude', 'settings.local.json');
let writtenPath = null;
let writtenContent = null;
let written = '';
const deps = {
readFile: () => '{}',
existsSync: () => true,
mkdir: () => {},
writeFile: (p, content) => { writtenPath = p; writtenContent = content; },
write: (s) => { written += s; },
};
const result = cmdWorktreeSetBaseRef(cwd, [], deps);
assert.strictEqual(result.changed, true);
assert.strictEqual(result.file, file);
assert.strictEqual(result.baseRef, 'head');
assert.strictEqual(writtenPath, file);
const parsedWritten = JSON.parse(writtenContent);
assert.strictEqual(parsedWritten.worktree.baseRef, 'head');
const parsedOutput = JSON.parse(written);
assert.strictEqual(parsedOutput.changed, true);
});
test('readFile returns explicit-other → changed false, skipped explicit-other, writeFile NOT called', () => {
const cwd = '/repo';
let writeFileCalled = false;
let written = '';
const deps = {
readFile: () => JSON.stringify({ worktree: { baseRef: 'fresh' } }),
existsSync: () => true,
mkdir: () => {},
writeFile: () => { writeFileCalled = true; },
write: (s) => { written += s; },
};
const result = cmdWorktreeSetBaseRef(cwd, [], deps);
assert.strictEqual(result.changed, false);
assert.strictEqual(result.skipped, 'explicit-other');
assert.strictEqual(result.previous, 'fresh');
assert.strictEqual(writeFileCalled, false, 'writeFile must NOT be called for explicit-other');
const parsedOutput = JSON.parse(written);
assert.strictEqual(parsedOutput.changed, false);
assert.strictEqual(parsedOutput.skipped, 'explicit-other');
});
test('readFile returns malformed JSON → throws refusing-to-modify error', () => {
const cwd = '/repo';
const file = path.join(cwd, '.claude', 'settings.local.json');
const deps = {
readFile: () => '{',
existsSync: () => true,
mkdir: () => {},
writeFile: () => {},
write: () => {},
};
assert.throws(
() => cmdWorktreeSetBaseRef(cwd, [], deps),
(err) => {
assert.ok(err instanceof Error, 'must throw an Error');
assert.ok(err.message.includes('Refusing to modify'), `message should contain "Refusing to modify", got: ${err.message}`);
assert.ok(err.message.includes(file), `message should contain file path, got: ${err.message}`);
return true;
}
);
});
test('readFile returns null (missing file) → treated as {} → changed true', () => {
const cwd = '/repo';
let writeFileCalled = false;
const deps = {
readFile: () => null,
existsSync: () => false,
mkdir: () => {},
writeFile: () => { writeFileCalled = true; },
write: () => {},
};
const result = cmdWorktreeSetBaseRef(cwd, [], deps);
assert.strictEqual(result.changed, true);
assert.strictEqual(writeFileCalled, true);
});
// FIX 2: non-object top-level JSON must be rejected with a clear error
test('readFile returns "[]" (array) → throws /expected a JSON object/', () => {
const cwd = '/repo';
const deps = {
readFile: () => '[]',
existsSync: () => true,
mkdir: () => {},
writeFile: () => {},
write: () => {},
};
assert.throws(
() => cmdWorktreeSetBaseRef(cwd, [], deps),
/expected a JSON object/
);
});
test('readFile returns "42" (primitive) → throws /expected a JSON object/', () => {
const cwd = '/repo';
const deps = {
readFile: () => '42',
existsSync: () => true,
mkdir: () => {},
writeFile: () => {},
write: () => {},
};
assert.throws(
() => cmdWorktreeSetBaseRef(cwd, [], deps),
/expected a JSON object/
);
});
});
// FIX 2: applyWorktreeBaseRef must reject non-object/array/null inputs
describe('applyWorktreeBaseRef — non-object inputs (FIX 2)', () => {
test('applyWorktreeBaseRef(null) → throws TypeError', () => {
assert.throws(
() => applyWorktreeBaseRef(null),
TypeError
);
});
test('applyWorktreeBaseRef([]) → throws TypeError', () => {
assert.throws(
() => applyWorktreeBaseRef([]),
TypeError
);
});
});
// ─── FIX 2: JSONC support ─────────────────────────────────────────────────────
describe('resolveEffectiveBaseRef — JSONC (FIX 2)', () => {
function makeReadFile(files) {
return (p) => (Object.prototype.hasOwnProperty.call(files, p) ? files[p] : null);
}
test('returns baseRef from settings.local.json with // line comments', () => {
const claudeDir = '/repo/.claude';
const jsonc = [
'// this is a comment',
'{',
' // another comment',
' "worktree": {',
' "baseRef": "head" // inline comment',
' }',
'}',
].join('\n');
const deps = {
readFile: makeReadFile({
[path.join(claudeDir, 'settings.local.json')]: jsonc,
}),
};
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps), 'head');
});
test('returns baseRef from settings.local.json with /* */ block comments', () => {
const claudeDir = '/repo/.claude';
const jsonc = [
'/* block comment */',
'{',
' "worktree": { /* inline block */ "baseRef": "fresh" }',
'}',
'/* trailing block */',
].join('\n');
const deps = {
readFile: makeReadFile({
[path.join(claudeDir, 'settings.local.json')]: jsonc,
}),
};
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps), 'fresh');
});
});
describe('cmdWorktreeSetBaseRef — JSONC (FIX 2)', () => {
test('commented-but-valid settings.local.json → updates it (changed true) rather than throwing', () => {
const cwd = '/repo';
const jsonc = [
'// user comment',
'{',
' // another comment',
' "other": "value"',
'}',
].join('\n');
let writtenContent = null;
const deps = {
readFile: () => jsonc,
existsSync: () => true,
mkdir: () => {},
writeFile: (_p, content) => { writtenContent = content; },
write: () => {},
};
const result = cmdWorktreeSetBaseRef(cwd, [], deps);
assert.strictEqual(result.changed, true, 'must set baseRef when absent (even in JSONC file)');
assert.ok(writtenContent !== null, 'must write the updated file');
const parsed = JSON.parse(writtenContent);
assert.strictEqual(parsed.worktree.baseRef, 'head');
});
test('JSONC with explicit baseRef="fresh" → skipped explicit-other, does not throw', () => {
const cwd = '/repo';
const jsonc = [
'// user comment',
'{',
' "worktree": {',
' // keeps the fork base fixed',
' "baseRef": "fresh"',
' }',
'}',
].join('\n');
let writeFileCalled = false;
const deps = {
readFile: () => jsonc,
existsSync: () => true,
mkdir: () => {},
writeFile: () => { writeFileCalled = true; },
write: () => {},
};
const result = cmdWorktreeSetBaseRef(cwd, [], deps);
assert.strictEqual(result.changed, false);
assert.strictEqual(result.skipped, 'explicit-other');
assert.strictEqual(writeFileCalled, false);
});
test('genuinely malformed JSON (after stripping comments) still throws refusing-to-modify', () => {
const cwd = '/repo';
const file = path.join(cwd, '.claude', 'settings.local.json');
// This is malformed even after comment stripping
const malformed = '// comment\n{ "key": }';
const deps = {
readFile: () => malformed,
existsSync: () => true,
mkdir: () => {},
writeFile: () => {},
write: () => {},
};
assert.throws(
() => cmdWorktreeSetBaseRef(cwd, [], deps),
(err) => {
assert.ok(err instanceof Error);
assert.ok(err.message.includes('Refusing to modify'), `got: ${err.message}`);
assert.ok(err.message.includes(file), `got: ${err.message}`);
return true;
}
);
});
});
// ─── FIX 3: defensive trim on git SHAs ────────────────────────────────────────
describe('evaluateWorktreeBaseDegrade — defensive trim on SHAs (FIX 3)', () => {
function makeExecGit(responses) {
return function stubExecGit(args, _opts) {
const key = args.join(' ');
if (Object.prototype.hasOwnProperty.call(responses, key)) {
return responses[key];
}
throw new Error(`Unexpected execGit call: ${JSON.stringify(args)}`);
};
}
test('HEAD with trailing newline still matches origin/HEAD — no degrade', () => {
const SHA = 'aabbccdd11223344aabbccdd11223344aabbccdd';
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 0, stdout: SHA + '\n', stderr: '', signal: null, error: null },
'rev-parse --verify --quiet origin/HEAD': { exitCode: 0, stdout: SHA + '\n', stderr: '', signal: null, error: null },
}),
});
assert.strictEqual(result.shouldDegrade, false);
assert.strictEqual(result.reason, 'head-matches-fork');
});
test('HEAD with trailing whitespace still diverges correctly from different origin/HEAD', () => {
const HEAD_SHA = 'deadbeef11223344deadbeef11223344deadbeef';
const FORK_SHA = 'cafebabe11223344cafebabe11223344cafebabe';
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 0, stdout: HEAD_SHA + '\n', stderr: '', signal: null, error: null },
'rev-parse --verify --quiet origin/HEAD': { exitCode: 0, stdout: FORK_SHA + '\r\n', stderr: '', signal: null, error: null },
}),
});
assert.strictEqual(result.shouldDegrade, true);
assert.strictEqual(result.reason, 'head-diverged-from-fork');
// After trimming, headSha and forkSha should be clean
assert.strictEqual(result.headSha, HEAD_SHA);
assert.strictEqual(result.forkSha, FORK_SHA);
});
test('symbolic-ref stdout with trailing newline resolves correctly', () => {
const HEAD_SHA = 'aaaa1111bbbb2222aaaa1111bbbb2222aaaa1111';
const FORK_SHA = 'cccc3333dddd4444cccc3333dddd4444cccc3333';
const result = evaluateWorktreeBaseDegrade({
execGit: makeExecGit({
'rev-parse HEAD': { exitCode: 0, stdout: HEAD_SHA + '\n', stderr: '', signal: null, error: null },
'rev-parse --verify --quiet origin/HEAD': { exitCode: 1, stdout: '', stderr: '', signal: null, error: null },
'symbolic-ref --quiet refs/remotes/origin/HEAD': { exitCode: 0, stdout: 'refs/remotes/origin/next\n', stderr: '', signal: null, error: null },
'rev-parse --verify --quiet refs/remotes/origin/next': { exitCode: 0, stdout: FORK_SHA + '\n', stderr: '', signal: null, error: null },
}),
});
assert.strictEqual(result.forkRef, 'origin/next');
assert.strictEqual(result.forkSha, FORK_SHA);
assert.strictEqual(result.shouldDegrade, true);
});
});
// ─── resolveEffectiveBaseRef — user/global layer (#1013) ─────────────────────
describe('resolveEffectiveBaseRef — user/global layer (#1013)', () => {
function makeReadFile(files) {
return (p) => (Object.prototype.hasOwnProperty.call(files, p) ? files[p] : null);
}
const USER_CLAUDE_DIR = '/home/user/.claude';
const claudeDir = '/repo/.claude';
test('(a) user/global settings.json provides baseRef:"head" when both project files absent', () => {
const deps = {
readFile: makeReadFile({
[path.join(USER_CLAUDE_DIR, 'settings.json')]: JSON.stringify({ worktree: { baseRef: 'head' } }),
}),
};
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps, USER_CLAUDE_DIR), 'head');
});
test('(b) project local "fresh" OVERRIDES user/global "head" → returns "fresh"', () => {
const deps = {
readFile: makeReadFile({
[path.join(claudeDir, 'settings.local.json')]: JSON.stringify({ worktree: { baseRef: 'fresh' } }),
[path.join(USER_CLAUDE_DIR, 'settings.json')]: JSON.stringify({ worktree: { baseRef: 'head' } }),
}),
};
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps, USER_CLAUDE_DIR), 'fresh');
});
test('(c) project shared "fresh" (no local) OVERRIDES user/global "head" → returns "fresh"', () => {
const deps = {
readFile: makeReadFile({
[path.join(claudeDir, 'settings.json')]: JSON.stringify({ worktree: { baseRef: 'fresh' } }),
[path.join(USER_CLAUDE_DIR, 'settings.json')]: JSON.stringify({ worktree: { baseRef: 'head' } }),
}),
};
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps, USER_CLAUDE_DIR), 'fresh');
});
test('(d) userClaudeDir undefined → behaves as before, returns null when both project files absent', () => {
const deps = { readFile: () => null };
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps, undefined), null);
});
test('(d) userClaudeDir null → behaves as before, returns null when both project files absent', () => {
const deps = { readFile: () => null };
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps, null), null);
});
test('user/global settings.json absent → returns null (no fallback beyond user layer)', () => {
const deps = {
readFile: makeReadFile({
// user settings.json present but has no baseRef
[path.join(USER_CLAUDE_DIR, 'settings.json')]: JSON.stringify({ other: 'value' }),
}),
};
assert.strictEqual(resolveEffectiveBaseRef(claudeDir, deps, USER_CLAUDE_DIR), null);
});
test('userClaudeDir === claudeDir → does not double-read (avoids re-reading shared settings.json)', () => {
// When project dir IS the user dir (cwd is home), the user layer should be skipped
// to avoid reading settings.json twice. This is enforced by the path.resolve comparison.
const sameDir = '/home/.claude';
let readCount = 0;
const deps = {
readFile: (p) => {
readCount++;
if (p === path.join(sameDir, 'settings.local.json')) return null;
if (p === path.join(sameDir, 'settings.json')) return JSON.stringify({ worktree: { baseRef: 'head' } });
return null;
},
};
// resolveEffectiveBaseRef(sameDir, deps, sameDir) — userClaudeDir === claudeDir
const result = resolveEffectiveBaseRef(sameDir, deps, sameDir);
assert.strictEqual(result, 'head'); // still reads shared settings.json (the project layer)
// The shared settings.json should have been read exactly once (project layer), not twice
assert.strictEqual(readCount, 2, 'only local + shared should be read; user layer skipped when same dir');
});
});
// ─── cmdWorktreeBaseCheck — user/global cascade (#1013 KEY REGRESSION) ───────
describe('cmdWorktreeBaseCheck — user/global cascade (#1013)', () => {
// Phase-lane execGit: origin/HEAD probe fails (no symref either) → fork-ref-unknown → degrade
function makePhaseLaneExecGit(HEAD_SHA) {
return function stubExecGit(args, _opts) {
const key = args.join(' ');
if (key === 'rev-parse HEAD') {
return { exitCode: 0, stdout: HEAD_SHA, stderr: '', signal: null, error: null };
}
if (key === 'rev-parse --verify --quiet origin/HEAD') {
return { exitCode: 1, stdout: '', stderr: '', signal: null, error: null };
}
if (key === 'symbolic-ref --quiet refs/remotes/origin/HEAD') {
return { exitCode: 1, stdout: '', stderr: '', signal: null, error: null };
}
throw new Error(`Unexpected execGit call: ${JSON.stringify(args)}`);
};
}
const HEAD_SHA = 'phase1lane11223344phase1lane11223344phase';
const USER_CLAUDE_DIR = '/home/user/.claude';
const cwd = '/repo';
const claudeDir = '/repo/.claude';
test('(e positive) user/global head + phase lane → shouldDegrade:false (KEY REGRESSION)', () => {
// This is the exact bug: user set worktree.baseRef:"head" in their global settings,
// but without the fix that setting was invisible and the phase lane triggered degrade.
const deps = {
execGit: makePhaseLaneExecGit(HEAD_SHA),
readFile: (p) => {
// Project files: no baseRef
if (p === path.join(claudeDir, 'settings.local.json')) return null;
if (p === path.join(claudeDir, 'settings.json')) return null;
// User/global file: baseRef = "head"
if (p === path.join(USER_CLAUDE_DIR, 'settings.json')) {
return JSON.stringify({ worktree: { baseRef: 'head' } });
}
return null;
},
write: () => {},
userClaudeDir: USER_CLAUDE_DIR,
};
const result = cmdWorktreeBaseCheck(cwd, [], deps);
assert.strictEqual(result.shouldDegrade, false,
'user/global worktree.baseRef:"head" must suppress degrade on a phase lane');
assert.strictEqual(result.reason, 'baseref-head');
});
test('(e negative) NO user/global head + same phase lane → shouldDegrade:true (proves lane degrades)', () => {
// Without a user/global head, the phase lane must still degrade (proves the positive test is real)
const deps = {
execGit: makePhaseLaneExecGit(HEAD_SHA),
readFile: () => null, // no project or user settings
write: () => {},
userClaudeDir: '/nonexistent-hermetic-dir-no-global',
};
const result = cmdWorktreeBaseCheck(cwd, [], deps);
assert.strictEqual(result.shouldDegrade, true,
'without user/global head, a phase lane must degrade');
assert.strictEqual(result.reason, 'fork-ref-unknown');
});
});