enhance(#3871): the state transaction — mandatory snapshot, open()/rebuild() (#3874)

* test(#3871): failing-first regressions for the dropped curated progress block

Pins ADR-3473 §8.6 / #3756 at the consumer's output: state record-session and
state add-decision on an archived-milestone project drop the curated progress
frontmatter entirely, exit 0, and report nothing. Reproduced against the real
CLI before writing the tests, not inferred from the issue text.

Also adds the unit-level probe that applyStatePreservation's preserve-always
row is inert on a resyncing write, and an over-preservation guard that an
empty project is never inflated.

Refs #3871

* feat(#3871): make the STATE.md pre-write snapshot mandatory via open()/rebuild()

ADR-3473 §8.6. StatePreservationInput's nullable preFm and the always-present
preFmSnapshot were the same extractFrontmatter call, one of them nulled on
resync — a policy flag baked into a snapshot. Both collapse into a single
StateTransaction whose snapshot cannot be absent: openStateTransaction()
applies preservation, rebuildStateTransaction() does not, and both carry the
snapshot because the reporting phase needs it either way. An absent snapshot
is now a construction failure; an empty one stays legal, because that is what
a document with no parseable frontmatter honestly has.

writeStateMd requires a rebuild transaction, which types ADR-3408 §8.3's
closed exception list at both call sites (state sync, health --repair) instead
of matching them as strings in a ratcheted baseline.

Fixes the dropped curated progress block: an all-zero or absent derived total
set is an unmeasured scan, not a measurement, so the curated block stands.
Also fixes two defects surfaced while building — preserve-always reported a
mutation even when it restored an identical value, and it re-entered the
curated object by reference, which would alias the snapshot the next phase
diffs against.

Refs #3871

* fix(#3871): close the three remaining subsumed defects and restore the arm the type does not replace

Review of the first two commits found four things.

The guard shrink deleted the seam-bypass axis whole, but only its
writeStateMd( arm became redundant. Its other arm catches a call site
re-assembling syncStateFrontmatter + applyPostSyncPreservation instead of the
owned composition, which the transaction type does not make unrepresentable
and which #3469 found live. Restored as findCompositionBypasses, terminal
rather than ratcheted.

Three of the four issues this phase claims were untouched. All three are the
epic's own shape and are fixed at the seam: current_phase_name is reasserted
from the curated value when the caller names none, and cmdStateJson stops
carrying a hand-maintained list parallel to FIELD_CLASSIFICATION and projects
it instead.

The construction failure that is the point of this phase had no test. Every
enumerated matrix row now has one, including the measured-versus-unmeasured
coercion boundary and a seeded property that no curated key is ever dropped.

ADR-3473 §8.6 said the guard 'keeps only its raw-write check'. Verified
against next: there was no raw-write check, and four other checks it does not
name. Amended in place with the evidence. ARCHITECTURE.md separately
advertised a preservation policy the code had deleted.

Refs #3871

* fix(#3871): do not let the unmeasured-scan rule block an explicitly-requested resync

The remote matrix caught over-preservation, the failure this phase's own
negative space says must not happen. state update Progress re-derives the
block from the body the caller just rewrote; on a project with no phase dirs
the derivation yields zero totals, the unmeasured rule read that as 'the scan
measured nothing', and the stale curated percent was restored over the resync
the user asked for.

preserve-always already said what the missing condition was: never overwrite
unless the caller explicitly names this field. explicitProgressField carries
it and is derived from shouldResyncStateProgress, not set by hand at a call
site, so it cannot drift from what the caller asked for.

Two defects found in the same mechanism and fixed with it. readModifyWriteStateMd
enumerates its option keys, so a new option was silently dropped rather than
rejected. And the raw-write axis captured its first argument up to the first
comma, which lands inside a nested path.join, so a write to a STATE.md literal
was invisible to it — the prove-it-can-fail test caught that one immediately.

No test assertion was weakened; all three frontmatter rows encode #3242, #1969
B3 and #1972 and stand unchanged.

Refs #3871

* docs(#3871): record why the raw-write check is kept, not why it was named

The amendment justified findRawStateWrites as 'written because §8.6 requires
it to exist', which is cargo-culting the contract and would have been the
wrong reason to keep anything. The real reason is that writeStateMd acquires
the STATE.md lockfile and a raw fs.writeFileSync acquires nothing, so this is
a lock bypass and lost-update is the #500/#905/#1230 family — and after this
phase it is the one reachable path into the file that nothing else covers.

Also records why ADR-3408 §8.6's deletion of the 'clear' policy is not the
precedent it looks like: 'clear' was dead vocabulary in a closed enum, this is
coverage of a reachable path.

Refs #3871

* chore(#3871): backfill changeset PR number

---------

Co-authored-by: sim <sim@local>
This commit is contained in:
Tom Boucher
2026-08-25 20:38:12 -04:00
committed by GitHub
parent 382bf7c423
commit 1863f5569c
15 changed files with 2429 additions and 1174 deletions

View File

@@ -37,8 +37,19 @@ const os = require('node:os');
const stateMod = require('../gsd-core/bin/lib/state.cjs');
const { writeStateMd } = stateMod;
const { rebuildStateTransaction } = require('../gsd-core/bin/lib/state-transition.cjs');
const { extractFrontmatter } = require('../gsd-core/bin/lib/frontmatter.cjs');
const { cleanup } = require('./helpers.cjs');
// ADR-3473 §8.6: writeStateMd's third argument is now a transaction. Both
// tests below mirror MINIMAL_STATE_MD's own pre-write content back to itself
// (no frontmatter on disk yet, so the snapshot is legitimately {}) — this is
// the M8 concurrency invariant under test, not a preservation scenario, so
// a `rebuild()` transaction (no preservation applied) is correct here.
function rebuildTransactionFor(content) {
return rebuildStateTransaction({ snapshot: extractFrontmatter(content) });
}
// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────
@@ -99,7 +110,7 @@ describe('M8: writeStateMd scans disk AFTER acquiring the lock (scan-in-lock)',
},
});
writeStateMd(statePath, MINIMAL_STATE_MD, tmpDir);
writeStateMd(statePath, MINIMAL_STATE_MD, rebuildTransactionFor(MINIMAL_STATE_MD), tmpDir);
assert.equal(fired, 1, 'afterAcquire hook must fire exactly once inside writeStateMd');
@@ -116,7 +127,7 @@ describe('M8: writeStateMd scans disk AFTER acquiring the lock (scan-in-lock)',
test('single-threaded callers (no hook) are byte-for-behaviour unchanged: count = 1', () => {
// Regression guard: with no concurrent writer (hook unset), the count must be
// exactly the on-disk truth — the fix must NOT change the uncontended result.
writeStateMd(statePath, MINIMAL_STATE_MD, tmpDir);
writeStateMd(statePath, MINIMAL_STATE_MD, rebuildTransactionFor(MINIMAL_STATE_MD), tmpDir);
assert.equal(
readTotalPlans(statePath), 1,
'uncontended writeStateMd must stamp the real on-disk plan count (1)'

View File

@@ -41,6 +41,15 @@ const { cleanup } = require('./helpers.cjs');
const STATE_CJS_PATH = path.join(
__dirname, '..', 'gsd-core', 'bin', 'lib', 'state.cjs'
);
// ADR-3473 §8.6: the writer worker's writeStateMd call now needs a
// rebuildStateTransaction() — resolved as a separate require path since the
// worker script runs in its own isolated module scope.
const STATE_TRANSITION_CJS_PATH = path.join(
__dirname, '..', 'gsd-core', 'bin', 'lib', 'state-transition.cjs'
);
const FRONTMATTER_CJS_PATH = path.join(
__dirname, '..', 'gsd-core', 'bin', 'lib', 'frontmatter.cjs'
);
const MINIMAL_STATE_MD = [
'# Project State',
@@ -123,10 +132,21 @@ fs.openSync = function(filePath, flags, mode) {
// any module-level SAB allocations from a prior require contaminating sabCount.)
delete require.cache[workerData.stateCjsPath];
const { writeStateMd } = require(workerData.stateCjsPath);
const { rebuildStateTransaction } = require(workerData.stateTransitionCjsPath);
const { extractFrontmatter } = require(workerData.frontmatterCjsPath);
let callErr = null;
try {
writeStateMd(workerData.statePath, workerData.content, workerData.tmpDir);
// ADR-3473 §8.6: writeStateMd now requires a rebuild() transaction — this
// worker's write mirrors REGENERATE_STATE's shape (a fresh, no-frontmatter
// MINIMAL_STATE_MD body), so the snapshot is of whatever (if anything)
// already exists on disk at statePath before this write.
const priorContent = fs.existsSync(workerData.statePath)
? fs.readFileSync(workerData.statePath, 'utf8')
: '';
writeStateMd(workerData.statePath, workerData.content, rebuildStateTransaction({
snapshot: extractFrontmatter(priorContent, workerData.statePath),
}), workerData.tmpDir);
} catch (e) {
callErr = (e && e.message) ? e.message : String(e);
}
@@ -244,6 +264,8 @@ describe('perf #316: acquireStateLock hoists sleep buffer — exactly one SAB pe
eval: true,
workerData: {
stateCjsPath: STATE_CJS_PATH,
stateTransitionCjsPath: STATE_TRANSITION_CJS_PATH,
frontmatterCjsPath: FRONTMATTER_CJS_PATH,
statePath,
content: MINIMAL_STATE_MD,
tmpDir,

File diff suppressed because it is too large Load Diff

View File

@@ -2,33 +2,46 @@
/**
* Tests for the STATE.md write-path anti-divergence drift guard
* (epic #3408, issue #3468, ADR-3408 Decision 5) —
* `scripts/lint-state-write-path-drift.cjs`.
* (epic #3408, issue #3468, ADR-3408 Decision 5; SHRUNK per ADR-3473 §8.6,
* issue #3871) — `scripts/lint-state-write-path-drift.cjs`.
*
* Design contract: docs/adr/3408-state-write-path-preservation.md (§8.1/§8.2/§8.3)
* Test matrix: .gsd/phase/refactor-3468-table-driven-preservation/50-test-matrix.md
* (section D, rows D1-D13 — this file covers section D only)
* docs/adr/3473-enforcement-by-construction.md (§8.6)
*
* Every row except D1 and D13 drives the guard's exported PURE functions
* (`findSeamBypasses`, `findPromptSeamUses`, `applyRatchet`, `loadBaseline`)
* directly with in-memory fixtures — no temp tree is needed, mirroring
* tests/state-field-drift.test.cjs's own house pattern for this class of
* guard. `REPO_ROOT` inside the guard module is a constant resolved from
* `__dirname` at require time, so it cannot be pointed at a synthetic tree
* without changing the guard's own interface — D1 (the real-tree contract)
* is therefore driven through the CLI's `--json` output instead, and D13
* (an unreadable file) through an `fs.readFileSync` monkeypatch rather than
* a real synthetic tree.
* The guard covers five axes, each backed by its own exported pure function
* and each terminal (every finding carries its own `reason` — there is no
* ratchet and nothing here reads a baseline file): `findPolicyDispatchDrift`/
* `findUnimplementedPolicies` (Axis 1, policy dispatch), `findRawStateWrites`
* (Axis 2, a raw `fs.writeFileSync` against the state path),
* `findUnstrippedContentWrites` (Axis 3, a frontmatter-shaped body write),
* `findPromptSeamUses` (Axis 4, prompt-layer prose shelling out to a
* write-side command), and `findCompositionBypasses` (Axis 5, a direct
* `syncStateFrontmatter`/`applyPostSyncPreservation` call outside their
* owner). ADR-3473 §8.6 retired one prior axis's `writeStateMd(` arm and the
* ratchet/retired-baseline machinery that backed it, once `writeStateMd`'s
* third parameter started requiring a `StateTransaction` the type system
* names; issue #3871 review kept that axis's OTHER arm (now
* `findCompositionBypasses`) because the type system gates only
* `writeStateMd`'s parameter, not a call site that never goes through
* `writeStateMd` at all — that arm was made terminal too.
*
* Sections D and E drive each pure function directly with in-memory
* fixtures — no temp tree needed, mirroring
* tests/state-field-drift.test.cjs's own house pattern. Section F instead
* drives the real CLI entry point, via the guard's `--root <dir>` flag
* (`collect(root)` takes a matching parameter, default `REPO_ROOT`, so every
* existing invocation — `npm run lint:ci` included — is unaffected): this is
* what lets a real-tree fixture run inside a disposable `createTempDir()`
* tree instead of ever mutating this repository's own `src/`, where a
* planted fixture would be visible to any concurrent `tsc`/`npm run
* build:lib`/`npm run lint`/another guard invocation, and would survive as
* build-breaking debris if the process were killed before `t.after` ran. D1
* is the one exception among the fixture-driven rows: it asserts the real
* repo's own `src/` and prompt layer are clean, so it runs through the CLI's
* `--json` output against the real `REPO_ROOT` with no `--root` override.
*
* Fixtures use array `.join('\n')`, never an indented template literal —
* indentation bleed would shift every asserted line number. Per D2/D5/D7's
* matrix note ("guard fixtures come from outside the guard's own writer"),
* the write-seam call lines reused below are copied VERBATIM from real,
* pre-existing production call sites (the guard's own current baseline
* entries) rather than invented by this test file:
* - `writeStateMd(statePath, modified, cwd);` src/state.cts:3682
* - `writeStateMd(statePath, result.content, cwd);` src/milestone.cts:865
* - `writeStateMd(statePath, stateContent, cwd);` src/health-diagnostic.cts:337
* indentation bleed would shift every asserted line number.
*
* Assertions compare the frozen `REASON` enum values and the `--json`/pure
* function return shapes only — never a substring/regex match on the human
@@ -43,46 +56,33 @@ const path = require('node:path');
const { runNode } = require('./helpers/process-seam.cjs');
const { PROBE_TIMEOUT_MS } = require('./helpers/timeouts.cjs');
const { createTempDir, cleanup } = require('./helpers.cjs');
const guard = require('../scripts/lint-state-write-path-drift.cjs');
const {
REASON,
findSeamBypasses,
findPromptSeamUses,
findPolicyDispatchDrift,
findUnstrippedContentWrites,
applyRatchet,
loadBaseline,
buildBaselineEntries,
collect,
findRawStateWrites,
findCompositionBypasses,
targetsStatePath,
EXECUTOR_FILE,
SEAM_OWNER_FILE,
SEAM_OWNER_EXEMPT_FUNCTIONS,
EXECUTOR_FILE,
REPO_ROOT,
BASELINE_PATH,
} = guard;
const GUARD_PATH = path.join(REPO_ROOT, 'scripts', 'lint-state-write-path-drift.cjs');
// A synthetic, non-owner, non-executor consumer file — never a real repo
// path — used as the `rel` argument wherever a row does not specifically
// need EXECUTOR_FILE or SEAM_OWNER_FILE behavior.
// A synthetic, non-executor consumer file — never a real repo path — used
// wherever a row does not specifically need EXECUTOR_FILE behavior.
const OTHER_FILE = 'src/example-consumer.cts';
const OTHER_FILE_2 = 'src/example-consumer-2.cts';
const OTHER_FILE_3 = 'src/example-consumer-3.cts';
// ─── D1: the real tree, through the CLI's --json contract ─────────────────
describe('D1 — the real tree', () => {
test('guard: clean tree passes', () => {
// Expected RED until the sibling refactor of src/state-transition.cts
// (issue #3468 Phase 1, concurrent with this test file's own authorship)
// lands: at write time the executor still dispatches five fields by
// literal name and leaves `derive`/`clear` unimplemented, which this
// guard's policy-dispatch axis correctly reports as 7 findings. Mirrors
// tests/milestone-window-drift-guard.test.cjs's own precedent of an
// explicitly-documented real-tree row that is red until its companion
// consolidation lands.
const result = runNode([GUARD_PATH, '--json'], { cwd: REPO_ROOT, timeoutMs: PROBE_TIMEOUT_MS });
assert.strictEqual(result.outcome, 'exited');
const body = JSON.parse(result.stdout);
@@ -92,155 +92,14 @@ describe('D1 — the real tree', () => {
});
});
// ─── D2: the guard MUST be able to fail ────────────────────────────────────
describe('D2 — an unrecorded bypass fails', () => {
test('guard: an unrecorded bypass fails', () => {
const text = [
'function cmdSomethingElse(cwd) {',
' const modified = deriveModifiedContent();',
' writeStateMd(statePath, modified, cwd);',
'}',
].join('\n');
const observed = findSeamBypasses(OTHER_FILE, text);
assert.strictEqual(observed.length, 1);
assert.strictEqual(observed[0].line, 3);
const findings = applyRatchet(observed, { entries: [] });
// A guard that cannot fail is worse than no guard: an unacknowledged
// bypass against an empty baseline MUST produce exactly one finding,
// reasoned, at the exact file and line — not merely "an array".
assert.strictEqual(findings.length, 1);
assert.strictEqual(findings[0].reason, REASON.SEAM_BYPASS_UNRECORDED);
assert.strictEqual(findings[0].file, OTHER_FILE);
assert.strictEqual(findings[0].line, 3);
assert.strictEqual(findings[0].source, 'writeStateMd(statePath, modified, cwd);');
});
});
// ─── D3: a recorded bypass is acknowledged ─────────────────────────────────
describe('D3 — a recorded bypass is acknowledged', () => {
test('guard: a recorded bypass is acknowledged', () => {
const text = [
'function cmdSomethingElse(cwd) {',
' const modified = deriveModifiedContent();',
' writeStateMd(statePath, modified, cwd);',
'}',
].join('\n');
const observed = findSeamBypasses(OTHER_FILE, text);
const baseline = {
entries: [{ file: OTHER_FILE, source: 'writeStateMd(statePath, modified, cwd);', symbol: 'writeStateMd', count: 1, owner: null }],
};
assert.deepStrictEqual(applyRatchet(observed, baseline), []);
});
});
// ─── D4: a stale acknowledgment fails ──────────────────────────────────────
describe('D4 — a stale acknowledgment fails', () => {
test('guard: a stale acknowledgment fails', () => {
// The call site the baseline acknowledges no longer fires at all this
// scan — the acknowledgment has outlived what it describes.
const baseline = {
entries: [{ file: OTHER_FILE, source: 'writeStateMd(statePath, modified, cwd);', symbol: 'writeStateMd', count: 1, owner: null }],
};
const findings = applyRatchet([], baseline);
assert.strictEqual(findings.length, 1);
assert.strictEqual(findings[0].reason, REASON.BASELINE_ENTRY_STALE);
assert.strictEqual(findings[0].file, OTHER_FILE);
assert.strictEqual(findings[0].observed, 0);
assert.strictEqual(findings[0].acknowledged, 1);
});
});
// ─── D5/D6/D7: the occurrence-count boundary triple (limit-1/limit/limit+1) ─
// The baseline acknowledges 2 occurrences throughout ("the limit"); only the
// OBSERVED count in the fixture source varies. This is why the ratchet keys
// entries on (file, trimmed source) instead of line number: two
// byte-identical call sites in one file are otherwise indistinguishable.
describe('D5 — occurrence count catches partial migration (limit-1)', () => {
test('guard: occurrence count catches partial migration', () => {
const text = [
'function cmdSomethingElse(cwd) {',
' writeStateMd(statePath, result.content, cwd);',
'}',
].join('\n');
const observed = findSeamBypasses(OTHER_FILE_2, text);
assert.strictEqual(observed.length, 1);
const baseline = {
entries: [{ file: OTHER_FILE_2, source: 'writeStateMd(statePath, result.content, cwd);', symbol: 'writeStateMd', count: 2, owner: null }],
};
const findings = applyRatchet(observed, baseline);
// Only 1 of the 2 acknowledged call sites still fires — a genuine
// partial migration, not a clean removal — must fail, not silently pass.
assert.strictEqual(findings.length, 1);
assert.strictEqual(findings[0].reason, REASON.SEAM_BYPASS_COUNT_SHRANK);
assert.strictEqual(findings[0].observed, 1);
assert.strictEqual(findings[0].acknowledged, 2);
});
});
describe('D6 — matching occurrence count passes (limit)', () => {
test('guard: matching occurrence count passes', () => {
const text = [
'function cmdSomethingElse(cwd) {',
' writeStateMd(statePath, result.content, cwd);',
' writeStateMd(statePath, result.content, cwd);',
'}',
].join('\n');
const observed = findSeamBypasses(OTHER_FILE_2, text);
assert.strictEqual(observed.length, 2);
const baseline = {
entries: [{ file: OTHER_FILE_2, source: 'writeStateMd(statePath, result.content, cwd);', symbol: 'writeStateMd', count: 2, owner: null }],
};
assert.deepStrictEqual(applyRatchet(observed, baseline), []);
});
});
describe('D7 — a new copy beside an acknowledged one fails (limit+1)', () => {
test('guard: a new copy beside an acknowledged one fails', () => {
const text = [
'function cmdA(cwd) {',
' writeStateMd(statePath, stateContent, cwd);',
'}',
'function cmdB(cwd) {',
' writeStateMd(statePath, stateContent, cwd);',
'}',
'function cmdC(cwd) {',
' writeStateMd(statePath, stateContent, cwd);',
'}',
].join('\n');
const observed = findSeamBypasses(OTHER_FILE_3, text);
assert.strictEqual(observed.length, 3);
const baseline = {
entries: [{ file: OTHER_FILE_3, source: 'writeStateMd(statePath, stateContent, cwd);', symbol: 'writeStateMd', count: 2, owner: null }],
};
const findings = applyRatchet(observed, baseline);
assert.strictEqual(findings.length, 1);
assert.strictEqual(findings[0].reason, REASON.SEAM_BYPASS_COUNT_GREW);
assert.strictEqual(findings[0].observed, 3);
assert.strictEqual(findings[0].acknowledged, 2);
});
});
// ─── D8: comments are not drift ────────────────────────────────────────────
// ─── D8: comments are not drift (composition-bypass shape) ────────────────
describe('D8 — comments are not drift', () => {
test('guard: comments are not drift', () => {
const text = [
'// writeStateMd(statePath, modified, cwd);',
'// syncStateFrontmatter(content, cwd);',
'/**',
' * writeStateMd(statePath, modified, cwd);',
' * applyPostSyncPreservation(originalContent, content, synced, statePath, options);',
' */',
'function noop() {}',
].join('\n');
@@ -249,7 +108,7 @@ describe('D8 — comments are not drift', () => {
// and a `/* */` block comment both carrying the exact call text must
// stay silent — both are blanked by `stripComments` before the seam-call
// regex ever runs.
assert.deepStrictEqual(findSeamBypasses(OTHER_FILE, text), []);
assert.deepStrictEqual(findCompositionBypasses(OTHER_FILE, text), []);
});
});
@@ -257,24 +116,34 @@ describe('D8 — comments are not drift', () => {
describe('D9 — owner functions are exempt', () => {
test('guard: owner functions are exempt', () => {
// #3469: `readModifyWriteStateMd` now calls the single
// `syncAndPreserveStateMd` symbol rather than assembling the two seam
// calls itself, so it needs no exemption — `syncAndPreserveStateMd` is
// the sole legitimate place `syncStateFrontmatter(` and
// `applyPostSyncPreservation(` appear together (the composition every
// OTHER caller, including `readModifyWriteStateMd`, now routes through).
// `syncAndPreserveStateMd` is the sole legitimate place
// `syncStateFrontmatter(` and `applyPostSyncPreservation(` appear
// together (the composition every OTHER caller routes through).
assert.ok(SEAM_OWNER_EXEMPT_FUNCTIONS.includes('syncAndPreserveStateMd'));
const text = [
'function syncAndPreserveStateMd(originalContent, transformedContent, statePath, cwd, resync) {',
' const synced = syncStateFrontmatter(transformedContent, cwd);',
' return applyPostSyncPreservation(originalContent, transformedContent, synced, statePath, resync);',
'function syncAndPreserveStateMd(originalContent, transformedContent, statePath, cwd, options) {',
' const synced = syncStateFrontmatter(transformedContent, cwd, options.authoritativeFm);',
' return applyPostSyncPreservation(originalContent, transformedContent, synced, statePath, options);',
'}',
].join('\n');
// The seam's own internal plumbing (the one owned composition —
// sync then post-sync preservation) is not a bypass.
assert.deepStrictEqual(findSeamBypasses(SEAM_OWNER_FILE, text), []);
assert.deepStrictEqual(findCompositionBypasses(SEAM_OWNER_FILE, text), []);
});
test('guard: writeStateMd is also exempt — its own sanctioned direct syncStateFrontmatter call is not a bypass', () => {
assert.ok(SEAM_OWNER_EXEMPT_FUNCTIONS.includes('writeStateMd'));
const text = [
'function writeStateMd(statePath, content, transaction, cwd, clock) {',
" const synced = syncStateFrontmatter(content, cwd, undefined, transaction.kind === 'rebuild');",
' platformWriteSync(statePath, synced);',
'}',
].join('\n');
assert.deepStrictEqual(findCompositionBypasses(SEAM_OWNER_FILE, text), []);
});
});
@@ -287,17 +156,90 @@ describe('D10 — the owner file is not exempt', () => {
const text = [
'function patchCore(cwd) {',
' const modified = compute();',
' writeStateMd(statePath, modified, cwd);',
' return modified;',
' const synced = syncStateFrontmatter(modified, cwd);',
' return synced;',
'}',
].join('\n');
const out = findSeamBypasses(SEAM_OWNER_FILE, text);
const out = findCompositionBypasses(SEAM_OWNER_FILE, text);
assert.strictEqual(out.length, 1);
assert.strictEqual(out[0].reason, REASON.COMPOSITION_BYPASS);
assert.strictEqual(out[0].line, 3);
});
});
// ─── D12: CRLF is scanned identically to LF ────────────────────────────────
describe('D12 — CRLF is scanned identically', () => {
test('guard: CRLF is scanned identically', () => {
const lfText = [
'function cmdSomethingElse(cwd) {',
' const synced = syncStateFrontmatter(modified, cwd);',
'}',
].join('\n');
const crlfText = lfText.split('\n').join('\r\n');
const lfOut = findCompositionBypasses(OTHER_FILE, lfText);
const crlfOut = findCompositionBypasses(OTHER_FILE, crlfText);
assert.strictEqual(crlfOut.length, 1);
const strip = (arr) => arr.map(({ line, symbol, source }) => ({ line, symbol, source }));
assert.deepStrictEqual(strip(crlfOut), strip(lfOut));
// A stray trailing \r surviving into the reported source (the repo's
// documented \n-only-regex bug class) would show up here as a
// sanitized `\x0d` escape — it must not.
assert.strictEqual(crlfOut[0].source, 'const synced = syncStateFrontmatter(modified, cwd);');
});
});
// ─── E1/E2 (Phase 2 / #3469, RETAINED per issue #3871): the composition-pair
// re-assembly shape itself, and the legitimate single-call composition ─────
describe('E1 — a re-assembled composition at a new call site is detected', () => {
test('guard: a call site invoking syncStateFrontmatter and applyPostSyncPreservation directly (bypassing syncAndPreserveStateMd) is caught on BOTH calls', () => {
// Finding 3's exact shape (ADR-3408 Amendment 2): every step calls an
// owner, so neither call alone is undeclared — but assembling the PAIR
// at a call site outside the seam composition is the re-derivation §8.3
// forbids by name. Synthetic: the real instance of this shape
// (cmdPhaseComplete's pre-#3469 adapter) was fixed by that phase.
const text = [
'function cmdReassembledAdapter(cwd, statePath, stateContent) {',
' let synced = syncStateFrontmatter(stateContent, cwd, authoritativeFm);',
' synced = applyPostSyncPreservation(originalStateContent, stateContent, synced, statePath, options);',
' return synced;',
'}',
].join('\n');
const out = findCompositionBypasses(OTHER_FILE, text);
assert.strictEqual(out.length, 2, 'both re-assembled stages must be caught, not just one');
assert.deepStrictEqual(out.map((f) => f.symbol).sort(), ['applyPostSyncPreservation', 'syncStateFrontmatter']);
assert.ok(out.every((f) => f.reason === REASON.COMPOSITION_BYPASS));
});
});
describe('E2 — a legitimate single call to the composition is not detected', () => {
test('guard: calling syncAndPreserveStateMd (the ONE write-seam composition) is not a bypass', () => {
// Verbatim shape from a real caller of the composition (e.g.
// milestone.cts's cmdMilestoneComplete) — a single call to the owned
// composition function, never to its two internal stages directly.
const text = [
' const finalContent = syncAndPreserveStateMd(',
' originalStateContent,',
' result.content,',
' statePath,',
' cwd,',
' {',
' resync: true,',
' authoritativeFm: Object.keys(authoritativeFm).length > 0 ? authoritativeFm : undefined,',
' divergedFields,',
' },',
' );',
].join('\n');
assert.deepStrictEqual(findCompositionBypasses(OTHER_FILE, text), []);
});
});
// ─── D11: the prompt layer is in the scan surface ──────────────────────────
describe('D11 — the prompt layer is in the scan surface', () => {
@@ -313,6 +255,7 @@ describe('D11 — the prompt layer is in the scan surface', () => {
const out = findPromptSeamUses(PROMPT_FILE, text);
assert.strictEqual(out.length, 1);
assert.strictEqual(out[0].line, 3);
assert.strictEqual(out[0].reason, REASON.PROMPT_LAYER_STATE_WRITE);
assert.strictEqual(out[0].symbol, 'prompt-layer-state-write');
});
@@ -324,104 +267,6 @@ describe('D11 — the prompt layer is in the scan surface', () => {
});
});
// ─── D12: CRLF is scanned identically to LF ────────────────────────────────
describe('D12 — CRLF is scanned identically', () => {
test('guard: CRLF is scanned identically', () => {
const lfText = [
'function cmdSomethingElse(cwd) {',
' writeStateMd(statePath, modified, cwd);',
'}',
].join('\n');
const crlfText = lfText.split('\n').join('\r\n');
const lfOut = findSeamBypasses(OTHER_FILE, lfText);
const crlfOut = findSeamBypasses(OTHER_FILE, crlfText);
assert.strictEqual(crlfOut.length, 1);
const strip = (arr) => arr.map(({ line, symbol, source }) => ({ line, symbol, source }));
assert.deepStrictEqual(strip(crlfOut), strip(lfOut));
// A stray trailing \r surviving into the reported source (the repo's
// documented \n-only-regex bug class) would show up here as a
// sanitized `\x0d` escape — it must not.
assert.strictEqual(crlfOut[0].source, 'writeStateMd(statePath, modified, cwd);');
});
});
// ─── D13: an unreadable file degrades, never crashes ───────────────────────
describe('D13 — an unreadable file is reported, not fatal', () => {
test('guard: an unreadable file is reported, not fatal', (t) => {
const originalReadFileSync = fs.readFileSync;
t.after(() => {
fs.readFileSync = originalReadFileSync;
});
// Monkeypatch (never chmod 0o000, which root bypasses under Docker/CI
// and would leave this assertion covering nothing). Scoped to
// BASELINE_PATH only, so no other read in this process is disturbed.
fs.readFileSync = function patchedReadFileSync(target, ...rest) {
if (target === BASELINE_PATH) {
const err = new Error('simulated unreadable baseline file');
err.code = 'EACCES';
throw err;
}
return originalReadFileSync.call(fs, target, ...rest);
};
// loadBaseline() must not throw — it degrades to a returned value.
assert.doesNotThrow(() => loadBaseline());
const result = loadBaseline();
// An unreadable file (EACCES) is NOT the same state as an absent one
// (ENOENT) and must not degrade to the same "no baseline yet" shape —
// collapsing the two is the exact ADR-3180/ADR-3408 failure mode this
// guard exists to catch. loadBaseline() must surface a distinguishable
// `entries: null` result carrying the underlying fs error code.
assert.deepStrictEqual(result, { entries: null, code: 'EACCES' });
});
test('CLI: an unreadable baseline reaches REASON.BASELINE_UNREADABLE with its error code, not the first-run shape', (t) => {
const originalReadFileSync = fs.readFileSync;
t.after(() => {
fs.readFileSync = originalReadFileSync;
});
fs.readFileSync = function patchedReadFileSync(target, ...rest) {
if (target === BASELINE_PATH) {
const err = new Error('simulated unreadable baseline file');
err.code = 'EACCES';
throw err;
}
return originalReadFileSync.call(fs, target, ...rest);
};
// Drive main() in-process (not via the CLI subprocess helper) so the
// monkeypatched fs.readFileSync is actually in effect for the call.
const originalArgv = process.argv;
const originalWrite = process.stdout.write;
t.after(() => {
process.stdout.write = originalWrite;
process.argv = originalArgv;
process.exitCode = 0;
});
let captured = '';
process.stdout.write = function patchedWrite(chunk) {
captured += chunk;
return true;
};
process.argv = [originalArgv[0], GUARD_PATH, '--json'];
guard.main(['--json']);
const exitCode = process.exitCode;
assert.strictEqual(exitCode, 1);
const parsed = JSON.parse(captured);
assert.strictEqual(parsed.ok, false);
assert.strictEqual(parsed.findings.length, 1);
assert.strictEqual(parsed.findings[0].reason, REASON.BASELINE_UNREADABLE);
assert.strictEqual(parsed.findings[0].code, 'EACCES');
});
});
// ─── D14: field-name-keyed BRANCH comparisons (not just CALLS) ────────────
// #3468: `applyPreserveIfPlaceholder` shipped a `field !== 'milestone_name'`
// branch — a field-name-keyed dispatch that routed around
@@ -510,11 +355,10 @@ describe('D14 — field-name-keyed branch comparisons are caught', () => {
// Security review finding: a repo can legally track a filename containing C1
// control bytes or bidi-override codepoints — exactly as attacker-controlled
// on a fork PR as the `source` fragment this guard already sanitized before
// this fix. Before this fix `file` reached `--json` stdout and the committed
// baseline (`scripts/state-write-path-drift-baseline.json`) unsanitized —
// this fix. Before this fix `file` reached `--json` stdout unsanitized —
// only the human formatter wrapped it. A finding's `file` (and any other
// attacker-derived field, like `field`) must come back escaped from the
// FINDER itself, so every consumer (human, `--json`, baseline) inherits the
// FINDER itself, so every consumer (human, `--json`) inherits the
// sanitization uniformly.
//
// The two attack codepoints are built via `String.fromCharCode` rather than
@@ -527,10 +371,10 @@ describe('D15 — file (and field) values are sanitized at construction', () =>
const ATTACK_FILE = `src/evil${RLO}${C1_CSI}name.cts`;
const ESCAPED_FILE = 'src/evil\\u202e\\x9bname.cts';
test('findSeamBypasses: an attacker-controlled filename comes back escaped', () => {
const text = ['function cmdSomethingElse(cwd) {', ' writeStateMd(statePath, modified, cwd);', '}'].join('\n');
test('findRawStateWrites: an attacker-controlled filename comes back escaped', () => {
const text = ['function cmdSomethingElse(cwd) {', ' fs.writeFileSync(statePath, modified);', '}'].join('\n');
const out = findSeamBypasses(ATTACK_FILE, text);
const out = findRawStateWrites(ATTACK_FILE, text);
assert.strictEqual(out.length, 1);
assert.strictEqual(out[0].file, ESCAPED_FILE);
// Neither raw attack codepoint survives in the finding at all — this is
@@ -539,15 +383,6 @@ describe('D15 — file (and field) values are sanitized at construction', () =>
// construction-time escaping — not JSON.stringify — is load-bearing).
assert.ok(!out[0].file.includes(RLO));
assert.ok(!out[0].file.includes(C1_CSI));
// The SAME escaped value is what a regenerated baseline entry persists —
// proving the fix reaches the committed
// scripts/state-write-path-drift-baseline.json, not just the finding.
const entries = buildBaselineEntries(out, null);
assert.strictEqual(entries.length, 1);
assert.strictEqual(entries[0].file, ESCAPED_FILE);
assert.ok(!entries[0].file.includes(RLO));
assert.ok(!entries[0].file.includes(C1_CSI));
});
test('findPromptSeamUses: an attacker-controlled filename comes back escaped', () => {
@@ -573,66 +408,13 @@ describe('D15 — file (and field) values are sanitized at construction', () =>
});
// ─────────────────────────────────────────────────────────────────────────
// Phase 2 (#3469) — ADR-3408 §8.3 Matrix section E: guard rows closing
// Phase 1's declared known gap (Axis 3, §8.3(b)) and pinning the ratchet's
// new 2-permanent-entry shape (Amendment 2). Test matrix:
// .gsd/phase/refactor-3469-one-write-seam/50-test-matrix.md
//
// E4/E5 are the false-positive guards — the exact shape that measured 29
// false positives to 1 true positive in Phase 1's naive co-occurrence
// approximation (see this guard's own header, Axis 3). E7 is the inverse: a
// sanctioned-permanent entry vanishing from the observed tree must FAIL, not
// silently reach zero — a guard reaching zero here would only do so by
// having stopped looking at a real writer.
// Section E (Phase 2 / #3469) — ADR-3408 §8.3 Matrix section E: guard rows
// closing Phase 1's declared known gap (Axis 3, §8.3(b)). E1/E2/E6/E7/E8
// (all of which drove the retired `findSeamBypasses`/ratchet machinery) are
// REMOVED along with it, per ADR-3473 §8.6. E3/E4/E5 (the frontmatter-write
// axis ADR-3473 §8.6 did NOT name for removal) are retained.
// ─────────────────────────────────────────────────────────────────────────
describe('E1 — a re-assembled composition at a new call site is detected', () => {
test('guard: a call site invoking syncStateFrontmatter and applyPostSyncPreservation directly (bypassing syncAndPreserveStateMd) is caught on BOTH calls', () => {
// Finding 3's exact shape (ADR-3408 Amendment 2): every step calls an
// owner, so neither call alone is undeclared — but assembling the PAIR
// at a call site outside the seam composition is the re-derivation §8.3
// forbids by name. Synthetic: the real instance of this shape
// (cmdPhaseComplete's pre-#3469 adapter) was fixed by this same phase.
const text = [
'function cmdReassembledAdapter(cwd, statePath, stateContent) {',
' let synced = syncStateFrontmatter(stateContent, cwd, authoritativeFm);',
' synced = applyPostSyncPreservation(originalStateContent, stateContent, synced, statePath, true, authoritativeFm);',
' return synced;',
'}',
].join('\n');
const observed = findSeamBypasses(OTHER_FILE, text);
assert.strictEqual(observed.length, 2, 'both re-assembled stages must be caught, not just one');
assert.deepStrictEqual(observed.map((f) => f.symbol).sort(), ['applyPostSyncPreservation', 'syncStateFrontmatter']);
const findings = applyRatchet(observed, { entries: [] });
assert.strictEqual(findings.length, 2);
assert.ok(findings.every((f) => f.reason === REASON.SEAM_BYPASS_UNRECORDED));
});
});
describe('E2 — a legitimate single call to the composition is not detected', () => {
test('guard: calling syncAndPreserveStateMd (the ONE write-seam composition) is not a bypass', () => {
// Verbatim from src/milestone.cts's real cmdMilestoneComplete call site
// (ADR-3408 Amendment 2's third caller).
const text = [
' const finalContent = syncAndPreserveStateMd(',
' originalStateContent,',
' result.content,',
' statePath,',
' cwd,',
' {',
' resync: true,',
' authoritativeFm: Object.keys(authoritativeFm).length > 0 ? authoritativeFm : undefined,',
' divergedFields,',
' },',
' );',
].join('\n');
assert.deepStrictEqual(findSeamBypasses(OTHER_FILE, text), []);
});
});
describe('E3 — a patchCore-style frontmatter write is detected (closes the Phase 1 declared gap)', () => {
test('guard: stateReplaceField over unstripped content with a variable field name is caught', () => {
// The pre-Phase-2 shape #3469 fixed: patchCore ran stateReplaceField
@@ -705,57 +487,150 @@ describe('E5 — sectionBody-scoped stateReplaceField calls are NOT detected', (
});
});
describe('E6 — ratchet: exactly 2 sanctioned-permanent entries remain (limit)', () => {
test('guard: the real baseline has exactly 2 permanent entries, and the real tree matches it with zero findings', () => {
const baseline = loadBaseline();
assert.strictEqual(
baseline.entries.length,
2,
'ADR-3408 Amendment 2: the ratchet holds exactly 2 sanctioned-permanent entries, not 0 — ' +
'Phase 4 does not drive this baseline to empty',
// ─────────────────────────────────────────────────────────────────────────
// F — ADR-3473 §8.6: the raw-write axis (`findRawStateWrites`), and the
// guard's own real CLI entry point proving the shrunk guard can still fail.
// ─────────────────────────────────────────────────────────────────────────
describe('F1 — the raw-write axis: pure function coverage', () => {
test('guard: fs.writeFileSync against statePath is reported', () => {
const text = [
'function bogusRawWrite(statePath, content) {',
' fs.writeFileSync(statePath, content);',
'}',
].join('\n');
const out = findRawStateWrites(OTHER_FILE, text);
assert.strictEqual(out.length, 1);
assert.strictEqual(out[0].reason, REASON.RAW_STATE_WRITE);
assert.strictEqual(out[0].line, 2);
assert.strictEqual(out[0].source, 'fs.writeFileSync(statePath, content);');
});
test('guard: fs.writeFileSync against a STATE.md literal is reported', () => {
const text = [
'function bogusRawWrite(cwd, content) {',
" fs.writeFileSync(path.join(cwd, 'STATE.md'), content);",
'}',
].join('\n');
const out = findRawStateWrites(OTHER_FILE, text);
assert.strictEqual(out.length, 1);
assert.strictEqual(out[0].reason, REASON.RAW_STATE_WRITE);
});
test('control: fs.writeFileSync against an unrelated target is NOT reported', () => {
const text = ['function writeSomethingElse(otherPath, content) {', ' fs.writeFileSync(otherPath, content);', '}'].join(
'\n',
);
for (const entry of baseline.entries) {
assert.strictEqual(entry.owner, 'sanctioned-permanent');
}
const { seamFindings } = collect();
const findings = applyRatchet(seamFindings, baseline);
assert.deepStrictEqual(findings, [], 'the real tree must match the 2-entry baseline exactly');
assert.deepStrictEqual(findRawStateWrites(OTHER_FILE, text), []);
});
test('control: platformWriteSync (the sanctioned seam) against statePath is NOT reported — a different call, by name', () => {
// The type/seam this axis exists BESIDE, not instead of: every real
// STATE.md writer in this codebase calls `platformWriteSync`, never raw
// `fs.writeFileSync`, against `statePath`. This axis only matches the
// literal `fs.writeFileSync` call shape.
const text = ['function realWriter(statePath, content) {', ' platformWriteSync(statePath, content);', '}'].join(
'\n',
);
assert.deepStrictEqual(findRawStateWrites(OTHER_FILE, text), []);
});
test('guard: comments are not drift', () => {
const text = [
'// fs.writeFileSync(statePath, modified);',
'/**',
' * fs.writeFileSync(statePath, modified);',
' */',
'function noop() {}',
].join('\n');
assert.deepStrictEqual(findRawStateWrites(OTHER_FILE, text), []);
});
test('targetsStatePath: bare identifier and STATE.md-literal both match; an unrelated identifier does not', () => {
assert.ok(targetsStatePath('statePath'));
assert.ok(targetsStatePath("path.join(cwd, 'STATE.md')"));
assert.ok(!targetsStatePath('otherPath'));
});
});
describe('E7 — ratchet: a sanctioned-permanent entry disappearing fails (limit-1)', () => {
test('guard: removing one of the two permanent entries from the observed tree is reported STALE, not silently accepted', () => {
const baseline = loadBaseline();
assert.strictEqual(baseline.entries.length, 2);
// Simulate one sanctioned entry (cmdStateSync's writeStateMd call)
// vanishing from the observed tree — exactly the shape §8.3's closed
// exception list forbids: a sanctioned exception may not silently
// disappear (a guard reaching zero here would only do so by having
// stopped looking at a real writer).
const vanished = baseline.entries[0];
const stillPresent = baseline.entries[1];
const observed = [{ file: stillPresent.file, source: stillPresent.source, symbol: stillPresent.symbol, line: 1 }];
describe('F2 — a guard that cannot fail is not a guard: the real CLI entry point catches a raw write', () => {
test('CLI: --root <synthetic tree> with fs.writeFileSync(statePath, ...) is reported, without touching the real src/ tree', (t) => {
// A throwaway tree in an OS temp dir, never inside this repository — the
// guard's own `--root` flag (default REPO_ROOT, so every OTHER caller of
// this CLI is unaffected) is what makes this possible without mutating
// the repo under test. See this file's header for why a real-src/
// fixture was rejected.
const tmpRoot = createTempDir('state-write-path-drift-guard-');
t.after(() => cleanup(tmpRoot));
const findings = applyRatchet(observed, baseline);
assert.strictEqual(findings.length, 1);
assert.strictEqual(findings[0].reason, REASON.BASELINE_ENTRY_STALE);
assert.strictEqual(findings[0].file, vanished.file);
assert.strictEqual(findings[0].observed, 0);
assert.strictEqual(findings[0].acknowledged, 1);
const srcDir = path.join(tmpRoot, 'src');
fs.mkdirSync(srcDir, { recursive: true });
const fixtureContent = [
"import * as fs from 'node:fs';",
'',
'function bogusRawWrite(statePath: string, content: string): void {',
' fs.writeFileSync(statePath, content);',
'}',
].join('\n');
fs.writeFileSync(path.join(srcDir, 'bogus.cts'), fixtureContent, 'utf8');
const result = runNode([GUARD_PATH, '--root', tmpRoot, '--json'], { cwd: REPO_ROOT, timeoutMs: PROBE_TIMEOUT_MS });
assert.strictEqual(result.outcome, 'exited');
assert.strictEqual(result.exitCode, 1, 'a real raw write against statePath must fail the CLI, not pass it');
const body = JSON.parse(result.stdout);
assert.strictEqual(body.ok, false);
const finding = body.findings.find((f) => f.file === 'src/bogus.cts');
assert.ok(finding, 'the planted fixture must appear in --json findings');
assert.strictEqual(finding.reason, REASON.RAW_STATE_WRITE);
assert.strictEqual(finding.line, 4);
});
test('CLI: --root <a clean synthetic tree> passes, proving --root does not silently widen scope back to REPO_ROOT', (t) => {
const tmpRoot = createTempDir('state-write-path-drift-guard-clean-');
t.after(() => cleanup(tmpRoot));
const srcDir = path.join(tmpRoot, 'src');
fs.mkdirSync(srcDir, { recursive: true });
fs.writeFileSync(path.join(srcDir, 'clean.cts'), "export const noop = () => 'noop';\n", 'utf8');
const result = runNode([GUARD_PATH, '--root', tmpRoot, '--json'], { cwd: REPO_ROOT, timeoutMs: PROBE_TIMEOUT_MS });
assert.strictEqual(result.outcome, 'exited');
assert.strictEqual(result.exitCode, 0);
const body = JSON.parse(result.stdout);
assert.strictEqual(body.ok, true);
assert.deepStrictEqual(body.findings, []);
});
});
describe('E8 — ratchet: a 3rd bypass beside the 2 sanctioned entries fails as unrecorded (limit+1)', () => {
test('guard: a new, unacknowledged writeStateMd call alongside the 2 sanctioned entries fails', () => {
const baseline = loadBaseline();
assert.strictEqual(baseline.entries.length, 2);
const matchingObserved = baseline.entries.map((e) => ({ file: e.file, source: e.source, symbol: e.symbol, line: 1 }));
const newBypass = { file: OTHER_FILE, source: 'writeStateMd(statePath, modified, cwd);', symbol: 'writeStateMd', line: 42 };
const observed = [...matchingObserved, newBypass];
describe('F3 — a guard that cannot fail is not a guard: the real CLI entry point catches a composition bypass', () => {
test('CLI: --root <synthetic tree> with a re-assembled syncStateFrontmatter + applyPostSyncPreservation pair is reported, without touching the real src/ tree', (t) => {
const tmpRoot = createTempDir('state-write-path-drift-guard-composition-');
t.after(() => cleanup(tmpRoot));
const findings = applyRatchet(observed, baseline);
assert.strictEqual(findings.length, 1);
assert.strictEqual(findings[0].reason, REASON.SEAM_BYPASS_UNRECORDED);
assert.strictEqual(findings[0].file, OTHER_FILE);
const srcDir = path.join(tmpRoot, 'src');
fs.mkdirSync(srcDir, { recursive: true });
const fixtureContent = [
'function cmdReassembledAdapter(cwd: string, statePath: string, stateContent: string): string {',
' let synced = syncStateFrontmatter(stateContent, cwd, authoritativeFm);',
' synced = applyPostSyncPreservation(originalStateContent, stateContent, synced, statePath, options);',
' return synced;',
'}',
].join('\n');
fs.writeFileSync(path.join(srcDir, 'bogus-composition.cts'), fixtureContent, 'utf8');
const result = runNode([GUARD_PATH, '--root', tmpRoot, '--json'], { cwd: REPO_ROOT, timeoutMs: PROBE_TIMEOUT_MS });
assert.strictEqual(result.outcome, 'exited');
assert.strictEqual(result.exitCode, 1, 'a re-assembled write-seam composition must fail the CLI, not pass it');
const body = JSON.parse(result.stdout);
assert.strictEqual(body.ok, false);
const findings = body.findings.filter((f) => f.file === 'src/bogus-composition.cts');
assert.strictEqual(findings.length, 2, 'both re-assembled stages must appear in --json findings');
assert.ok(findings.every((f) => f.reason === REASON.COMPOSITION_BYPASS));
});
});

View File

@@ -6624,7 +6624,9 @@ describe('ADR-3408 §8.5 Matrix (#3471): stale-but-present, and the report resid
].join('\n');
fs.writeFileSync(statePath, original);
stateLib.writeStateMd(statePath, original, tmp);
stateLib.writeStateMd(statePath, original, stateTransitionMod.rebuildStateTransaction({
snapshot: frontmatterLib.extractFrontmatter(original),
}), tmp);
const onDisk = fs.readFileSync(statePath, 'utf8');
const fm = frontmatterLib.extractFrontmatter(onDisk);
@@ -6657,7 +6659,9 @@ describe('ADR-3408 §8.5 Matrix (#3471): stale-but-present, and the report resid
].join('\n');
fs.writeFileSync(statePath, original);
stateLib.writeStateMd(statePath, original, tmp);
stateLib.writeStateMd(statePath, original, stateTransitionMod.rebuildStateTransaction({
snapshot: frontmatterLib.extractFrontmatter(original),
}), tmp);
const expected = [
'---', 'gsd_state_version: 1.0', 'status: unknown', 'last_updated: "2023-11-14T22:13:20.000Z"',
@@ -6693,7 +6697,9 @@ describe('ADR-3408 §8.5 Matrix (#3471): stale-but-present, and the report resid
'**Current phase:** (determining...)', '**Status:** Resuming', '',
].join('\n');
stateLib.writeStateMd(statePath, regenerated, tmp);
stateLib.writeStateMd(statePath, regenerated, stateTransitionMod.rebuildStateTransaction({
snapshot: frontmatterLib.extractFrontmatter(oldCurated),
}), tmp);
const onDisk = fs.readFileSync(statePath, 'utf8');
const fm = frontmatterLib.extractFrontmatter(onDisk);
@@ -14385,7 +14391,9 @@ describe('buildStateFrontmatter cache invalidation (#1967)', () => {
test('writeStateMd invalidates cache so subsequent reads see new disk state', () => {
// First write — populates cache via buildStateFrontmatter
const content1 = fs.readFileSync(statePath, 'utf-8');
state.writeStateMd(statePath, content1, tmpDir);
state.writeStateMd(statePath, content1, stateTransitionMod.rebuildStateTransaction({
snapshot: frontmatterLib.extractFrontmatter(content1),
}), tmpDir);
// Create a NEW phase directory AFTER the first write
// Without cache invalidation, the second write would still see only 1 phase
@@ -14400,7 +14408,9 @@ describe('buildStateFrontmatter cache invalidation (#1967)', () => {
// Second write in the SAME process — must see the new phase
const content2 = fs.readFileSync(statePath, 'utf-8');
state.writeStateMd(statePath, content2, tmpDir);
state.writeStateMd(statePath, content2, stateTransitionMod.rebuildStateTransaction({
snapshot: frontmatterLib.extractFrontmatter(content2),
}), tmpDir);
// Read back and parse frontmatter to verify it reflects 2 phases, not 1
const result = fs.readFileSync(statePath, 'utf-8');
@@ -16895,3 +16905,613 @@ describe('#3699 state update — derived frontmatter keys explain themselves', (
}
});
});
// ═════════════════════════════════════════════════════════════════════════
// #3871 / #3756 (ADR-3473 §8.6): a curated `progress:` frontmatter block is
// LOST on a write by verbs that have nothing to do with progress (state
// record-session, state add-decision) once the CURRENT milestone's phase
// dirs have been archived to `.planning/milestones/<version>-phases/` while
// STATE.md/ROADMAP.md still identify that milestone as the current one
// (ROADMAP heading "Current", Phase entries still listed in the ROADMAP
// text — only the on-disk phase directories moved). The milestone-scoped
// disk scan then finds none of the current milestone's phase directories
// under `.planning/phases/` and derives an empty/zero progress projection —
// verified empirically (see repro3756.js, run against the built lib): the
// persisted frontmatter's `progress` key is dropped ENTIRELY after the
// write (not merely zeroed-with-percent-omitted). Root cause is unchanged:
// `applyPostSyncPreservation` (src/state.cts) computes
// `const preFm = resync ? null : extractFrontmatter(...)` while
// `readModifyWriteStateMd` defaults `resync` to `true`, so the declared
// `preserve-always` policy row for `progress` never runs on this write path
// and has no chance to restore the curated block before it is discarded.
//
// Fixture pattern mirrors `tests/health-validation.test.cjs`'s
// `mkArchivePhases` (`.planning/milestones/<version>-phases/<NN>-phase-N/`)
// and `tests/completion-ratio-scope-withholding.test.cjs`'s ROADMAP-heading
// fixture builders — a "Current" milestone heading (so scope classifies as
// SCOPE.COMPLETE / windowed rather than UNSCOPED — a "Shipped" heading gets
// stripped by `stripShippedMilestones` and reproduces rule-4 withholding
// instead, a different and pre-existing intentional behavior, NOT this
// defect), phase dirs that exist ONLY under the archive path, and nothing
// at all under `.planning/phases/` for the current milestone.
// ═════════════════════════════════════════════════════════════════════════
describe('#3871 / #3756: curated progress must survive a write on an archived milestone', () => {
// Builds an archived-milestone fixture: STATE.md asserts milestone v1.0
// and carries the curated progress block (5/5/32/32/100%) plus the body
// sections `record-session` and `add-decision` each need (Session
// Continuity, Decisions). ROADMAP.md shows v1.0 as the CURRENT milestone
// ("Current 🚧" heading, with all 5 Phase entries still listed in the
// ROADMAP text) with 5 phases. The phase dirs themselves live ONLY under
// `.planning/milestones/v1.0-phases/` — `.planning/phases/` has nothing
// for the current milestone, exactly as it is right after `milestone
// complete --archive-phases` runs while STATE.md has not yet been
// advanced to a new milestone.
function buildArchivedMilestoneFixture(cwd) {
const planningDir = path.join(cwd, '.planning');
fs.mkdirSync(planningDir, { recursive: true });
fs.writeFileSync(
path.join(planningDir, 'ROADMAP.md'),
[
'## v1.0 Current 🚧',
'',
'### Phase 1: Foo',
'### Phase 2: Bar',
'### Phase 3: Baz',
'### Phase 4: Qux',
'### Phase 5: Quux',
'',
].join('\n'),
);
// 5 archived phases totalling 32 plans, every plan paired with a
// SUMMARY (all complete) — mirrors mkArchivePhases in
// tests/health-validation.test.cjs, but with real PLAN/SUMMARY files
// rather than empty dirs, since this fixture is about the DISK SCAN
// finding zero CURRENT-milestone phases, not about archive discovery.
const archiveDir = path.join(planningDir, 'milestones', 'v1.0-phases');
const plansPerPhase = [7, 7, 6, 6, 6]; // sums to 32
plansPerPhase.forEach((count, i) => {
const phaseNum = String(i + 1).padStart(2, '0');
const phaseDir = path.join(archiveDir, `${phaseNum}-phase-${i + 1}`);
fs.mkdirSync(phaseDir, { recursive: true });
for (let p = 1; p <= count; p += 1) {
const planNum = String(p).padStart(2, '0');
fs.writeFileSync(path.join(phaseDir, `${phaseNum}-${planNum}-PLAN.md`), '# Plan\n');
fs.writeFileSync(path.join(phaseDir, `${phaseNum}-${planNum}-SUMMARY.md`), '# Summary\n');
}
});
// Deliberately NO .planning/phases/ directory at all for the current
// milestone — the archived-milestone shape this issue is about.
fs.writeFileSync(
path.join(planningDir, 'STATE.md'),
[
'---',
'gsd_state_version: 1.0',
'milestone: v1.0',
'status: executing',
'progress:',
' total_phases: 5',
' completed_phases: 5',
' total_plans: 32',
' completed_plans: 32',
' percent: 100',
'---',
'',
'# Project State',
'',
'## Session Continuity',
'',
'**Last session:** 2024-01-10',
'**Stopped at:** Phase 5, Plan 32',
'**Resume file:** None',
'',
'## Decisions',
'No decisions yet.',
'',
'## Blockers',
'None',
'',
].join('\n'),
);
}
function assertCuratedProgressSurvived(cwd) {
const statePath = path.join(cwd, '.planning', 'STATE.md');
const content = fs.readFileSync(statePath, 'utf-8');
const fm = frontmatterLib.extractFrontmatter(content);
assert.ok(fm && fm.progress, 'STATE.md frontmatter must still carry a progress block');
assert.strictEqual(Number(fm.progress.total_phases), 5, 'total_phases must remain the curated 5, not zeroed by the archived-milestone disk scan');
assert.strictEqual(Number(fm.progress.completed_phases), 5, 'completed_phases must remain the curated 5');
assert.strictEqual(Number(fm.progress.total_plans), 32, 'total_plans must remain the curated 32');
assert.strictEqual(Number(fm.progress.completed_plans), 32, 'completed_plans must remain the curated 32');
assert.strictEqual(Number(fm.progress.percent), 100, 'percent must remain the curated 100, not go missing');
}
// THIS TEST MUST FAIL TODAY (#3756): `state record-session` resyncs
// (readModifyWriteStateMd defaults resync:true), which forces `preFm` to
// null in applyPostSyncPreservation, which starves the preserve-always
// executor for `progress` of the one input (`ctx.preFm`) it actually
// reads — so the curated block is never restored and the persisted
// frontmatter's `progress` key is dropped entirely (verified via
// repro3756.js against the built lib, not merely inferred).
test('recordSessionOnArchivedMilestoneDoesNotZeroProgress', (t) => {
const cwd = createTempDir('gsd-3871-record-session-');
t.after(() => cleanup(cwd));
buildArchivedMilestoneFixture(cwd);
const result = runGsdTools(['state', 'record-session', '--stopped-at', 'Phase 5 complete'], cwd);
assert.ok(result.success, `Command failed: ${result.error}`);
assertCuratedProgressSurvived(cwd);
});
// Same fixture, same failure mode, via `state add-decision` instead —
// pins that the defect is in the shared write seam (readModifyWriteStateMd
// / applyPostSyncPreservation), not something specific to record-session.
// THIS TEST MUST FAIL TODAY (#3756) for the same reason as above.
test('addDecisionOnArchivedMilestoneDoesNotZeroProgress', (t) => {
const cwd = createTempDir('gsd-3871-add-decision-');
t.after(() => cleanup(cwd));
buildArchivedMilestoneFixture(cwd);
const result = runGsdTools(
['state', 'add-decision', '--phase', '05-01', '--summary', 'Ship v1.0', '--rationale', 'milestone complete'],
cwd,
);
assert.ok(result.success, `Command failed: ${result.error}`);
assertCuratedProgressSurvived(cwd);
});
// The over-preservation guard: a genuinely empty project (no phases
// anywhere, no curated progress block at all) must still report zeros
// after the same verb — the fix for #3756 must not make
// applyStatePreservation invent a nonzero progress block out of nothing.
// This test MUST PASS both today and after the fix.
test('newProjectWithNoPhasesKeepsZeroProgress', (t) => {
const cwd = createTempProject('gsd-3871-empty-');
t.after(() => cleanup(cwd));
fs.writeFileSync(
path.join(cwd, '.planning', 'STATE.md'),
[
'# Project State',
'',
'## Session Continuity',
'',
'**Last session:** 2024-01-10',
'**Stopped at:** None',
'**Resume file:** None',
'',
].join('\n'),
);
const result = runGsdTools(['state', 'record-session', '--stopped-at', 'Nothing started yet'], cwd);
assert.ok(result.success, `Command failed: ${result.error}`);
const statePath = path.join(cwd, '.planning', 'STATE.md');
const written = fs.readFileSync(statePath, 'utf-8');
const fm = frontmatterLib.extractFrontmatter(written);
const progress = fm && fm.progress;
// No curated progress ever existed, so exactly one deterministic outcome
// is acceptable — the block is entirely absent, or every count in it is
// a genuine, well-formed 0. Some assertion MUST run either way (no `if`
// guard around the assertion itself); which branch it took is stated in
// the failure message so a silent pass-through cannot hide which case
// fired. `Number.isFinite` (not `Number(x) || 0`) so a garbage/NaN value
// is caught rather than laundered into a false 0.
if (!progress) {
assert.strictEqual(progress, undefined, 'case: no progress block at all — this is the accepted degraded outcome for a project with no curated progress');
} else {
const counters = {
total_phases: Number(progress.total_phases),
completed_phases: Number(progress.completed_phases),
total_plans: Number(progress.total_plans),
completed_plans: Number(progress.completed_plans),
};
for (const [key, value] of Object.entries(counters)) {
assert.ok(Number.isFinite(value), `case: progress block present — ${key} must coerce to a finite number, got ${JSON.stringify(progress[key])}`);
assert.strictEqual(value, 0, `case: progress block present — ${key} must be exactly 0 on an empty project, not inflated`);
}
}
});
});
// ─────────────────────────────────────────────────────────────────────────────
// ADR-3473 §8.6 test matrix rows 31-33 (.gsd/phase/feat-3871-state-transaction-
// snapshot/50-test-matrix.md): consumer-output identity for the two
// sanctioned `rebuild()` exceptions (`state sync`, `/gsd-health --repair`'s
// REGENERATE_STATE) and the second producer of the same composition
// (`phase complete`'s atomic-commit adapter in src/phase.cts).
// ─────────────────────────────────────────────────────────────────────────────
describe('ADR-3473 §8.6 matrix row 31: state sync still lets the body win (#905, rebuild() did not invert the command)', () => {
let tmpDir;
beforeEach(() => { tmpDir = createFixture(); });
afterEach(() => { cleanup(tmpDir); });
test('stateSyncStillLetsTheBodyWin', () => {
const content = [
'---',
'gsd_state_version: 1.0',
'stopped_at: "curated stale value — must NOT survive"',
'---',
'',
'# Project State',
'',
'## Session',
'',
'**Stopped at:** fresh body value from a contradicting body — must win',
'',
].join('\n');
fs.writeFileSync(path.join(tmpDir, '.planning', 'STATE.md'), content);
const result = runGsdTools('state sync', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const state = fs.readFileSync(path.join(tmpDir, '.planning', 'STATE.md'), 'utf-8');
const fm = frontmatterLib.extractFrontmatter(state);
assert.strictEqual(
fm.stopped_at,
'fresh body value from a contradicting body — must win',
'the body must win over the frontmatter it contradicts — proves routing cmdStateSync through rebuild() did not invert the command',
);
});
});
describe('ADR-3473 §8.6 matrix row 32: REGENERATE_STATE still factory-resets and tolerates NO frontmatter at all', () => {
// NOTE — discrepancy from the brief's literal instruction, verified
// empirically (not assumed): driving this through the real CLI
// (`runGsdTools('validate health --repair', ...)`) cannot exercise this
// row. Two independent reasons, both confirmed against the built lib:
// 1. `REMEDY_ACTION.REGENERATE_STATE`'s risk is DESTRUCTIVE
// (health-diagnostic-rules/root-existence.cjs's E004 rule), and
// `applyRepairs`'s dispatch gate refuses every DESTRUCTIVE remedy
// unconditionally — `--repair` NEVER actually calls
// `rebuildStateTransaction` for it (see
// tests/verify-health.test.cjs "refuses to regenerate STATE.md when
// missing" and tests/health-diagnostic.test.cjs row 15, both pinning
// the refusal-only contract).
// 2. Independently, E004 itself only fires when
// `snapshot.currentPhaseLabel.scope === SCOPE.UNREADABLE` — a STATE.md
// that exists, is readable, and simply has NO frontmatter block does
// NOT trip that scope. Verified live: `validate health --repair` json
// against exactly this fixture returns `"errors": []` and never
// surfaces a `regenerateState` action at all.
// So the CLI can never reach this code path for this row, by policy (1)
// and by detection (2) independently. The invocation shape that DOES
// reach it is the one `runRepairAction`'s REGENERATE_STATE case (and the
// existing "D3" test in this same file, ADR-3408 §8.5 Matrix, Section A)
// already use: `stateLib.writeStateMd` + `stateTransitionMod
// .rebuildStateTransaction({ snapshot: extractFrontmatter(priorState) })`
// directly — the exact call `runRepairAction`'s REGENERATE_STATE case
// makes. This test drives that shape with a prior STATE.md carrying
// literally NO frontmatter block (not merely a missing file).
test('regenerateStateStillFactoryResetsAndToleratesNoFrontmatter', (t) => {
const tmp = createTempDir('gsd-3871-row32-');
t.after(() => cleanup(tmp));
const statePath = path.join(tmp, 'STATE.md');
const noFrontmatterContent = [
'# Session State',
'',
'No frontmatter here at all — a broken document, the usual reason',
'REGENERATE_STATE fires in the first place.',
'',
].join('\n');
fs.writeFileSync(statePath, noFrontmatterContent);
const priorSnapshot = frontmatterLib.extractFrontmatter(noFrontmatterContent, statePath);
assert.deepStrictEqual(priorSnapshot, {}, 'precondition: extractFrontmatter must return {} (never throw/null) for a document with no frontmatter');
let tx;
assert.doesNotThrow(() => {
tx = stateTransitionMod.rebuildStateTransaction({ snapshot: priorSnapshot });
}, 'rebuildStateTransaction must NOT raise a construction failure for the {} snapshot of a frontmatter-less document');
const regenerated = [
'# Session State', '', '## Position', '',
'**Current phase:** (determining...)', '**Status:** Resuming', '',
].join('\n');
stateLib.writeStateMd(statePath, regenerated, tx, tmp);
const onDisk = fs.readFileSync(statePath, 'utf8');
const fm = frontmatterLib.extractFrontmatter(onDisk);
assert.ok(fm && fm.gsd_state_version, 'the factory reset must produce a fresh, well-formed frontmatter block');
assert.strictEqual(fm.status, 'Resuming', 'the regenerated content must be what was written, not the old (nonexistent) curated content');
assert.match(onDisk, /## Position/, 'the regenerated body must be the fresh factory-reset content, not the old prose');
});
});
describe('ADR-3473 §8.6 matrix row 33: phase complete\'s adapter uses the identical transaction/preservation composition (#3374 Variant A stays fixed)', () => {
let tmpDir;
beforeEach(() => { tmpDir = createTempProject(); });
afterEach(() => { cleanup(tmpDir); });
test('phaseCompleteAdapterUsesTheSameTransaction', () => {
const planningDir = path.join(tmpDir, '.planning');
const phase1Dir = path.join(planningDir, 'phases', '01-foundation');
const phase2Dir = path.join(planningDir, 'phases', '02-api');
fs.mkdirSync(phase1Dir, { recursive: true });
fs.mkdirSync(phase2Dir, { recursive: true });
fs.writeFileSync(
path.join(planningDir, 'ROADMAP.md'),
[
'# Roadmap',
'',
'- [ ] Phase 1: Foundation',
'- [ ] Phase 2: API',
'',
'### Phase 1: Foundation',
'**Goal:** Setup',
'**Plans:** 1 plans',
'',
'### Phase 2: API',
'**Goal:** Build API',
'',
'## Progress',
'',
'| Phase | Plans Complete | Status | Completed |',
'|-------|----------------|--------|-----------|',
'| 01. Foundation | 0/1 | Not started | - |',
'| 02. API | 0/1 | Not started | - |',
'',
].join('\n'),
);
// A curated `paused_at` frontmatter value with NO corresponding body
// source line — its body delta compares as unchanged (nothing to
// disagree with), so a stale/absent derived value would clobber it if
// cmdPhaseComplete's adapter did NOT route through the identical
// applyStatePreservation dispatch a `state` verb uses.
fs.writeFileSync(
path.join(planningDir, 'STATE.md'),
[
'---',
'gsd_state_version: 1.0',
'paused_at: "curated pause note — must survive phase complete"',
'---',
'',
'# State',
'',
'**Current Phase:** 01',
'**Current Phase Name:** Foundation',
'**Status:** In progress',
'**Current Plan:** 01-01',
'**Last Activity:** 2025-01-01',
'**Last Activity Description:** Working on phase 1',
'',
].join('\n'),
);
fs.writeFileSync(path.join(phase1Dir, '01-01-PLAN.md'), '# Plan\n');
fs.writeFileSync(path.join(phase1Dir, '01-01-SUMMARY.md'), '# Summary\n');
fs.writeFileSync(
path.join(phase1Dir, '01-VERIFICATION.md'),
['---', 'status: passed', '---', '', '# Verification', ''].join('\n'),
);
const result = runGsdTools(['phase', 'complete', '1'], tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.ok(
Array.isArray(output.preservation_warnings) && output.preservation_warnings.some((w) => w.field === 'paused_at'),
`expected paused_at named in preservation_warnings — same policy a state verb reports; got ${JSON.stringify(output.preservation_warnings)}`,
);
const state = fs.readFileSync(path.join(planningDir, 'STATE.md'), 'utf-8');
const fm = frontmatterLib.extractFrontmatter(state);
assert.strictEqual(
fm.paused_at,
'curated pause note — must survive phase complete',
'the curated field must survive phase complete via the SAME composition (syncAndPreserveStateMd -> applyStatePreservation) a state verb uses',
);
});
});
// #3834/#3835/#3836 share the epic #3473 thesis: FIELD_CLASSIFICATION declares
// a field's preservation policy once (src/state-transition.cts), and each of
// these three is a call site that either defeats the delta heuristic by
// rewriting the exact body source it compares against in the same write
// (#3834, #3835), or maintains a hand-typed field list parallel to the table
// that had already drifted from it (#3836).
describe('#3834/#3835/#3836: current_phase_name / last_activity_desc preservation call-site gaps', () => {
function buildCuratedNameFixture(cwd) {
const planningDir = path.join(cwd, '.planning');
fs.mkdirSync(planningDir, { recursive: true });
fs.writeFileSync(
path.join(planningDir, 'ROADMAP.md'),
[
'# Roadmap',
'',
'## v1.0 Demo Milestone',
'',
'### Phase 1: First Phase',
'**Goal:** demo',
'',
'### Phase 2: Second Phase Real Name',
'**Goal:** demo',
'',
'### Phase 3: Third Phase',
'**Goal:** demo',
'',
].join('\n'),
);
fs.writeFileSync(
path.join(planningDir, 'STATE.md'),
[
'---',
'gsd_state_version: 1.0',
'milestone: v1.0',
'milestone_name: Demo Milestone',
'current_phase: 1',
'current_phase_name: Real Curated Name',
'current_plan: 0',
'status: executing',
'stopped_at: "Phase 1 done"',
'last_updated: "2026-08-25T00:00:00.000Z"',
'last_activity: "2026-08-25"',
'last_activity_desc: "Fresh curated description"',
'progress:',
' total_phases: 3',
' completed_phases: 1',
' total_plans: 6',
' completed_plans: 2',
' percent: 33',
'---',
'',
'# Project State',
'',
'## Current Position',
'',
'**Phase:** 1 — Real Curated Name',
'**Current Plan:** 0',
'**Status:** executing',
'',
'## Session',
'',
'**Stopped At:** Phase 1 done',
'**Last Activity:** 2026-08-25',
'**Last Activity Description:** Fresh curated description',
'',
].join('\n'),
);
}
// THIS TEST MUST FAIL BEFORE THE #3834 FIX: `state planned-phase` without
// `--name` rewrites the body `Phase:` source line to `N — READY TO EXECUTE`
// in the same write the preserve-when-unchanged delta rule compares
// against, so the rule cannot fire and the post-sync re-derivation harvests
// the status fragment as if it were the curated name.
test('plannedPhaseWithoutNameDoesNotClobberCuratedPhaseName', (t) => {
const cwd = createTempDir('gsd-3834-planned-phase-');
t.after(() => cleanup(cwd));
buildCuratedNameFixture(cwd);
const result = runGsdTools(['state', 'planned-phase', '--phase', '2', '--plans', '3'], cwd);
assert.ok(result.success, `Command failed: ${result.error}`);
const statePath = path.join(cwd, '.planning', 'STATE.md');
const written = fs.readFileSync(statePath, 'utf-8');
const fm = frontmatterLib.extractFrontmatter(written);
assert.strictEqual(
fm.current_phase_name,
'Real Curated Name',
`current_phase_name must keep the curated value, not the status fragment "READY TO EXECUTE" — got ${JSON.stringify(fm.current_phase_name)}`,
);
});
// THIS TEST MUST FAIL BEFORE THE #3835 FIX: `state complete-phase` rewrites
// the body `Phase:` source line to `N — COMPLETE` unconditionally, which
// defeats the same delta rule and DROPS the current_phase_name key from
// persisted frontmatter entirely (not merely blanks it).
test('completePhaseDoesNotDropCuratedPhaseName', (t) => {
const cwd = createTempDir('gsd-3835-complete-phase-');
t.after(() => cleanup(cwd));
buildCuratedNameFixture(cwd);
// Phase directories so `progress` is legitimately re-derived from disk
// and does not confound the current_phase_name assertion below.
const phasesDir = path.join(cwd, '.planning', 'phases');
fs.mkdirSync(path.join(phasesDir, '01-first-phase'), { recursive: true });
fs.mkdirSync(path.join(phasesDir, '02-second-phase'), { recursive: true });
fs.mkdirSync(path.join(phasesDir, '03-third-phase'), { recursive: true });
fs.writeFileSync(path.join(phasesDir, '01-first-phase', '1-01-SUMMARY.md'), '---\nphase: 1\nplan: 01\nstatus: complete\n---\n# s\n');
fs.writeFileSync(path.join(phasesDir, '01-first-phase', '1-01-PLAN.md'), '---\nphase: 1\nplan: 01\n---\n# p\n');
fs.writeFileSync(path.join(phasesDir, '02-second-phase', '2-01-PLAN.md'), '---\nphase: 2\nplan: 01\n---\n# p\n');
fs.writeFileSync(path.join(phasesDir, '03-third-phase', '3-01-PLAN.md'), '---\nphase: 3\nplan: 01\n---\n# p\n');
const result = runGsdTools(['state', 'complete-phase', '1'], cwd);
assert.ok(result.success, `Command failed: ${result.error}`);
const statePath = path.join(cwd, '.planning', 'STATE.md');
const written = fs.readFileSync(statePath, 'utf-8');
const fm = frontmatterLib.extractFrontmatter(written);
assert.strictEqual(
fm.current_phase_name,
'Real Curated Name',
`current_phase_name must survive complete-phase, not be deleted from frontmatter entirely — got ${JSON.stringify(fm.current_phase_name)}`,
);
});
// THIS TEST MUST FAIL BEFORE THE #3836 FIX: `cmdStateJson`'s hand-maintained
// preserve-when-unchanged field list omits `last_activity_desc` (declared
// preserve-when-unchanged in FIELD_CLASSIFICATION and wired on the write
// path per #3258), so a stale body-prose "Last Activity Description:" line
// beats a fresher curated frontmatter value on every `state json` read.
test('stateJsonPreservesCuratedLastActivityDescOverStaleBodyProse', (t) => {
const cwd = createTempDir('gsd-3836-state-json-');
t.after(() => cleanup(cwd));
const planningDir = path.join(cwd, '.planning');
fs.mkdirSync(planningDir, { recursive: true });
fs.writeFileSync(
path.join(planningDir, 'ROADMAP.md'),
[
'# Roadmap',
'',
'## v1.0 Demo Milestone',
'',
'### Phase 1: First Phase',
'**Goal:** demo',
'',
'### Phase 2: Second Phase Real Name',
'**Goal:** demo',
'',
].join('\n'),
);
fs.writeFileSync(
path.join(planningDir, 'STATE.md'),
[
'---',
'gsd_state_version: 1.0',
'milestone: v1.0',
'milestone_name: Demo Milestone',
'current_phase: 2',
'current_phase_name: Second Phase Real Name',
'current_plan: 1',
'status: executing',
'stopped_at: "Phase 2 plan 1 in flight"',
'last_updated: "2026-08-25T00:00:00.000Z"',
'last_activity: "2026-08-25"',
'last_activity_desc: "FRESH CURATED DESCRIPTION"',
'---',
'',
'# Project State',
'',
'## Current Position',
'',
'**Phase:** 2 — Second Phase Real Name',
'**Current Plan:** 1',
'**Status:** executing',
'',
'## Session',
'',
'**Stopped At:** Phase 2 plan 1 in flight',
'**Last Activity:** 2026-08-25',
'',
'## Session Continuity Archive',
'',
'**Last Activity Description:** STALE ARCHIVED DESCRIPTION FROM 2025',
'',
].join('\n'),
);
const before = fs.readFileSync(path.join(planningDir, 'STATE.md'), 'utf-8');
const result = runGsdTools(['state', 'json'], cwd);
assert.ok(result.success, `Command failed: ${result.error}`);
const after = fs.readFileSync(path.join(planningDir, 'STATE.md'), 'utf-8');
assert.strictEqual(after, before, '`state json` is read-only and must not mutate STATE.md');
const parsed = JSON.parse(result.output);
assert.strictEqual(
parsed.last_activity_desc,
'FRESH CURATED DESCRIPTION',
`last_activity_desc must report the curated frontmatter value, not the stale archived body prose — got ${JSON.stringify(parsed.last_activity_desc)}`,
);
});
});