Files
msd-core/tests/state-rebuild.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

513 lines
23 KiB
JavaScript

'use strict';
// Phase 1 tests for the `rebuild` transition (ADR-1817).
//
// Covers the four drift classes from epic #1817:
// #1 ## Current Position prose contradicts frontmatter
// #2 ## Performance Metrics → **By Phase:** table has orphaned rows
// #3 Template-placeholder field values ([X], [date], etc.) left in place
// #4 Duplicate ## Session Continuity archived-session H3 blocks
//
// Plus the cross-cutting contracts:
// #6 Idempotency: rebuild twice on a clean file = byte-identical
// #7 Regression guard: sync/prune unchanged when rebuild is not invoked
//
// Discipline (CONTRIBUTING.md): tests assert on typed structured values via
// the public `transitionCore` API, never on rendered text via raw grep.
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
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',
localToday: () => '2026-06-29',
nowIso: () => '2026-06-29T12:00:00.000Z',
});
const noProgress = () => 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,
clock: fixedClock,
phaseInventoryProvider: noPhases,
});
// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------
/**
* A clean, fully-reconciled STATE.md body — the canonical post-rebuild shape.
* Used as the starting point for drift fixtures and as the idempotency
* baseline (running rebuild on this must produce no mutation).
*/
function cleanState() {
return [
'---',
'gsd_state_version: \'1.0\'',
'status: executing',
'milestone: 1.0.0',
'milestone_name: Test Milestone',
'current_phase: 3',
'current_phase_name: Test Phase',
'current_plan: 2',
'progress:',
' total_phases: 5',
' completed_phases: 2',
' total_plans: 10',
' completed_plans: 4',
' percent: 40',
'---',
'',
'# Project State',
'',
'## Project Reference',
'',
'See: .planning/PROJECT.md (updated 2026-06-01)',
'',
'**Core value:** A test project',
'**Current focus:** Test Phase',
'',
'## Current Position',
'',
'**Current Phase:** 3',
'**Current Phase Name:** Test Phase',
'**Current Plan:** 2',
'**Total Plans in Phase:** 5',
'**Status:** executing',
'**Last Activity:** 2026-06-29',
'**Last Activity Description:** mid-flight context from plan 3-02',
'',
'Phase: 3 of 5 (Test Phase)',
'Plan: 2 of 5',
'Status: Executing Phase 3',
'Last activity: 2026-06-29 — mid-flight context',
'',
'**Progress:** [████░░░░░░] 40%',
'',
'## Performance Metrics',
'',
'**By Phase:**',
'',
'| Phase | Plans | Total | Avg/Plan |',
'|-------|-------|-------|----------|',
'| 1 | 2 | - | - |',
'| 2 | 3 | - | - |',
'| 3 | 5 | - | - |',
'',
'## Accumulated Context',
'',
'### Decisions',
'',
'- Phase 1: chose option A',
'- Phase 2: chose option B',
'',
'### Pending Todos',
'',
'None yet.',
'',
'## Deferred Items',
'',
'| Category | Item | Status | Deferred At |',
'|----------|------|--------|-------------|',
'| *(none)* | | | |',
'',
'## Session Continuity',
'',
'Last session: 2026-06-29 12:00',
'Stopped at: mid-flight context',
'Resume file: None',
'',
].join('\n');
}
/** Drift fixture #1: body `**Current Phase:**` and `**Current Phase Name:**`
* contradict frontmatter (e.g. after a milestone switch). */
function driftedCurrentPosition() {
// Take the clean state and inject stale body prose.
const c = cleanState();
return c
.replace('**Current Phase:** 3', '**Current Phase:** 2')
.replace('**Current Phase Name:** Test Phase', '**Current Phase Name:** Old Phase Name');
}
/** Drift fixture #3: template placeholder values left in body fields. */
function driftedPlaceholders() {
const c = cleanState();
// Inject placeholders into a couple of fields. Don't touch the fields
// syncCore actively maintains (Last Activity) — those would be reconciled
// by sync, not rebuild.
return c
.replace('**Current focus:** Test Phase', '**Current focus:** [Current phase name]')
.replace('See: .planning/PROJECT.md (updated 2026-06-01)', 'See: .planning/PROJECT.md (updated [date])');
}
/** Count LIVE `### Session —` headings, excluding any occurrences inside the
* `## Rebuild Log` audit section (the log's `before:` field captures dropped
* content verbatim, which would otherwise inflate the count). */
function countLiveSessionHeadings(content) {
// Strip everything from `## Rebuild Log` to EOF, then count.
const stripped = content.replace(/^## Rebuild Log[\s\S]*$/m, '');
return (stripped.match(/^###\s+Session\s+—/gm) || []).length;
}
/** Drift fixture #4: six duplicate `### Session —` archived blocks under
* `## Session Continuity` (more than the default 3-most-recent retention). */
function driftedSessionArchiveDuplicates() {
// Replace the canonical short Session Continuity block with one that has
// six archived sub-blocks.
const c = cleanState();
const archiveBlock = [
'## Session Continuity',
'',
'Last session: 2026-06-29 12:00',
'Stopped at: mid-flight context',
'Resume file: None',
'',
'### Session — 2026-06-20',
'',
'oldest session — should be dropped',
'',
'### Session — 2026-06-22',
'',
'second-oldest — should be dropped',
'',
'### Session — 2026-06-25',
'',
'third — kept',
'',
'### Session — 2026-06-27',
'',
'fourth — kept',
'',
'### Session — 2026-06-28',
'',
'fifth — kept',
'',
'### Session — 2026-06-29',
'',
'sixth — kept',
'',
].join('\n');
return c.replace(/## Session Continuity[\s\S]*$/, archiveBlock);
}
// ---------------------------------------------------------------------------
// Tests — dispatch + idempotency contract
// ---------------------------------------------------------------------------
describe('ADR-1817 `rebuild` intent: dispatch + idempotency (§1, §4)', () => {
test('transitionCore dispatches `rebuild` without throwing', () => {
const result = transitionCore(cleanState(), { kind: 'rebuild' }, baseDeps);
assert.ok(result, 'rebuild must return a result');
assert.ok(Array.isArray(result.updated), 'updated must be an array');
assert.ok(result.data && typeof result.data === 'object', 'data must be an object');
});
test('rebuild on a clean file is a no-op: content byte-identical, no log, no `updated`', () => {
const clean = cleanState();
const result = transitionCore(clean, { kind: 'rebuild' }, baseDeps);
assert.strictEqual(result.content, clean, 'content must be byte-identical on a clean file');
assert.deepStrictEqual(result.updated, [], 'no fields should be marked updated on a clean file');
assert.strictEqual(result.data && result.data.mutated, false, 'mutated flag must be false');
assert.strictEqual(result.content.includes('## Rebuild Log'), false,
'a no-op rebuild must NOT append a ## Rebuild Log section (idempotency)');
});
test('running rebuild twice on a drifted file converges: second run is a no-op', () => {
const drifted = driftedCurrentPosition();
const first = transitionCore(drifted, { kind: 'rebuild' }, baseDeps);
assert.notStrictEqual(first.content, drifted, 'first run must mutate drifted content');
const second = transitionCore(first.content, { kind: 'rebuild' }, baseDeps);
assert.strictEqual(second.content, first.content,
'second run on the just-rebuilt content must be byte-identical (idempotency)');
assert.deepStrictEqual(second.updated, [], 'second run must mark nothing updated');
assert.strictEqual(second.data && second.data.mutated, false,
'second run must report mutated=false');
});
});
// ---------------------------------------------------------------------------
// Tests — drift class #1: Current Position prose reconciliation
// ---------------------------------------------------------------------------
describe('ADR-1817 §2: rebuild reconciles ## Current Position prose with frontmatter (#1817 criterion #1)', () => {
test('body `**Current Phase:**` is re-derived from frontmatter.current_phase when drifted', () => {
const drifted = driftedCurrentPosition();
assert.strictEqual(stateExtractField(drifted, 'Current Phase'), '2',
'fixture sanity: drifted body must have stale phase 2');
const result = transitionCore(drifted, { kind: 'rebuild' }, baseDeps);
assert.strictEqual(
stateExtractField(result.content, 'Current Phase'),
'3',
'body Current Phase must be reconciled to frontmatter value 3',
);
});
test('body `**Current Phase Name:**` is re-derived from frontmatter.current_phase_name when drifted', () => {
const drifted = driftedCurrentPosition();
assert.strictEqual(stateExtractField(drifted, 'Current Phase Name'), 'Old Phase Name',
'fixture sanity: drifted body must have stale name');
const result = transitionCore(drifted, { kind: 'rebuild' }, baseDeps);
assert.strictEqual(
stateExtractField(result.content, 'Current Phase Name'),
'Test Phase',
'body Current Phase Name must be reconciled to frontmatter value',
);
});
test('each reconciliation produces an audit-log entry in ## Rebuild Log', () => {
const result = transitionCore(driftedCurrentPosition(), { kind: 'rebuild' }, baseDeps);
assert.ok(result.content.includes('## Rebuild Log'),
'rebuild that mutated must create ## Rebuild Log section');
assert.ok(result.content.includes('kind: current-position-reconciled'),
'log must contain a current-position-reconciled entry');
assert.ok(result.content.includes('reason:'),
'every log entry must carry a reason field (ADR-1411 provenance)');
});
});
// ---------------------------------------------------------------------------
// Tests — drift class #3: template-placeholder removal
// ---------------------------------------------------------------------------
describe('ADR-1817 §2: rebuild strips template-placeholder field values (#1817 criterion #3)', () => {
test('`**Field:** [placeholder]` lines are replaced with `**Field:** (pending)`', () => {
const drifted = driftedPlaceholders();
const result = transitionCore(drifted, { kind: 'rebuild' }, baseDeps);
assert.ok(result.content.includes('**Current focus:** (pending)'),
'placeholder Current focus must be replaced with (pending)');
assert.ok(result.content.includes('**Last Activity:** 2026-06-29'),
'fixture sanity: syncCore-maintained fields are untouched by rebuild');
});
test('a placeholder-removed audit-log entry is recorded', () => {
const result = transitionCore(driftedPlaceholders(), { kind: 'rebuild' }, baseDeps);
assert.ok(result.content.includes('kind: placeholder-removed'),
'log must contain a placeholder-removed entry');
});
test('a clean body with no placeholders produces no placeholder-removed log entry', () => {
const result = transitionCore(cleanState(), { kind: 'rebuild' }, baseDeps);
assert.ok(!result.content.includes('kind: placeholder-removed'),
'clean file must not log placeholder removal');
});
});
// ---------------------------------------------------------------------------
// Tests — drift class #4: Session Continuity Archive de-duplication
// ---------------------------------------------------------------------------
describe('ADR-1817 §2: rebuild de-duplicates ## Session Continuity archive blocks (#1817 criterion #4)', () => {
test('when > 3 archived sessions, the oldest are dropped down to the 3 most-recent', () => {
const drifted = driftedSessionArchiveDuplicates();
// Fixture sanity: six archived H3 blocks
const before = countLiveSessionHeadings(drifted);
assert.strictEqual(before, 6, 'fixture must have 6 archived sessions');
const result = transitionCore(drifted, { kind: 'rebuild' }, baseDeps);
const after = countLiveSessionHeadings(result.content);
assert.strictEqual(after, 3, 'rebuild must keep exactly 3 most-recent archived sessions');
});
test('each dropped session produces a session-archive-deduplicated log entry', () => {
const result = transitionCore(driftedSessionArchiveDuplicates(), { kind: 'rebuild' }, baseDeps);
const dropEntries = (result.content.match(/kind: session-archive-deduplicated/g) || []).length;
assert.strictEqual(dropEntries, 3, 'three dropped sessions → three log entries');
});
test('the kept sessions are the most-recent three (by document order — template convention)', () => {
const result = transitionCore(driftedSessionArchiveDuplicates(), { kind: 'rebuild' }, baseDeps);
// Strip the audit log so we only inspect LIVE content (the log's `before:`
// field legitimately preserves dropped text per ADR-1817 §3).
const live = result.content.replace(/^## Rebuild Log[\s\S]*$/m, '');
// DEFAULT_MAX_SESSION_ARCHIVES = 3 → drop the 3 oldest, keep 06-27/28/29.
assert.ok(!live.includes('### Session — 2026-06-20'), 'dropped: 06-20 (oldest)');
assert.ok(!live.includes('### Session — 2026-06-22'), 'dropped: 06-22 (2nd oldest)');
assert.ok(!live.includes('### Session — 2026-06-25'), 'dropped: 06-25 (3rd oldest)');
assert.ok(live.includes('### Session — 2026-06-27'), 'kept: 06-27');
assert.ok(live.includes('### Session — 2026-06-28'), 'kept: 06-28');
assert.ok(live.includes('### Session — 2026-06-29'), 'kept: 06-29 (newest)');
assert.ok(!live.includes('oldest session — should be dropped'),
'oldest session content must be gone from the live section');
assert.ok(!live.includes('second-oldest — should be dropped'),
'second-oldest session content must be gone from the live section');
});
test('when <= 3 archived sessions, rebuild is a no-op on the archive', () => {
const clean = cleanState(); // has zero archived H3 sessions
const result = transitionCore(clean, { kind: 'rebuild' }, baseDeps);
assert.ok(!result.content.includes('kind: session-archive-deduplicated'),
'no dedup log entry when archive is within retention');
});
});
// ---------------------------------------------------------------------------
// Tests — drift class #2: By Phase table reconciliation (via dep)
// ---------------------------------------------------------------------------
describe('ADR-1817 §2: rebuild reconciles **By Phase:** table via phaseInventoryProvider (#1817 criterion #2)', () => {
test('orphaned rows for phases missing from the inventory are dropped', () => {
// Inventory: only phases 1, 2, 3 exist on disk. Drifted body has rows for
// 1, 2, 3, AND an orphan row for phase 99 (prior milestone).
const drifted = cleanState().replace(
/\| 3 \| 5 \| - \| - \|\n/,
'| 3 | 5 | - | - |\n| 99 | 1 | - | - |\n',
);
const deps = {
...baseDeps,
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:
const result2 = transitionCore(drifted, { kind: 'rebuild' }, deps);
// Strip the audit log so we only inspect LIVE table rows (the log's
// `before:` field legitimately preserves the pre-rebuild table per
// ADR-1817 §3).
const live = result2.content.replace(/^## Rebuild Log[\s\S]*$/m, '');
assert.ok(!live.includes('| 99 |'),
'orphan row for phase 99 (not on disk) must be dropped when phaseInventoryProvider is wired');
assert.ok(live.includes('| 1 |'), 'kept: phase 1');
assert.ok(live.includes('| 2 |'), 'kept: phase 2');
assert.ok(live.includes('| 3 |'), 'kept: phase 3');
});
test('rebuild logs a by-phase-table-reconciled entry when the table changes', () => {
const drifted = cleanState().replace(
/\| 3 \| 5 \| - \| - \|\n/,
'| 3 | 5 | - | - |\n| 99 | 1 | - | - |\n',
);
const deps = {
...baseDeps,
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'),
'rebuild that mutated the table must log a by-phase-table-reconciled entry');
});
test('Leaky-Abstractions guard: when phaseInventoryProvider is absent, table is preserved verbatim', () => {
const drifted = cleanState().replace(
/\| 3 \| 5 \| - \| - \|\n/,
'| 3 | 5 | - | - |\n| 99 | 1 | - | - |\n',
);
// 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');
assert.ok(!result.content.includes('kind: by-phase-table-reconciled'),
'no log entry when step is a no-op');
});
});
// ---------------------------------------------------------------------------
// 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)
// ---------------------------------------------------------------------------
describe('ADR-1817 §5/§6: rebuild does not affect sync or prune (regression guard, criterion #7)', () => {
test('sync still patches its three frontmatter fields when rebuild is also available', () => {
const state = cleanState();
const result = transitionCore(
state,
{ kind: 'sync', totalPlansInPhase: 7, percent: 50 },
baseDeps,
);
// sync should have updated Total Plans in Phase and Progress and Last Activity.
assert.strictEqual(stateExtractField(result.content, 'Total Plans in Phase'), '7',
'sync must still patch Total Plans in Phase');
assert.ok(stateExtractField(result.content, 'Progress').includes('50%'),
'sync must still patch Progress percent');
});
test('prune still archives by cutoff when rebuild is also available', () => {
// Smoke: prune on a body with at least one Decisions row at phase 1 should
// archive that row when cutoff=0. The exact byte shape is covered by the
// dedicated state-transition tests; this test only asserts prune is NOT
// broken by adding the rebuild case to the switch.
const state = cleanState();
const result = transitionCore(state, { kind: 'prune', cutoff: 0 }, baseDeps);
assert.ok(result, 'prune must still return a result');
assert.ok(result.updated !== undefined, 'prune must still return an updated array');
});
});