refactor(#3468): dispatch state preservation on the declared policy, not the field (#3495)

* test(#3468): add write-path drift guard, ratcheted at its measured baseline

Guard-first, per ADR-3180 Amendment 3's standing rule that a phase builds
and runs its guard BEFORE its scope is fixed, and states its copy count as
'N found by the guard', never 'N per the epic'.

Measured, not assumed:

  Axis 1 (policy dispatch, ADR-3408 section 8.1) — 7 violations, RED by
  design. 5 field-name-keyed getFieldClassification('literal') branches
  plus 2 declared FieldPreservation members with no executor at all
  (derive, clear). This is the fail-first evidence for the refactor.

  Axis 2 (write seam, section 8.3) — 4 bypasses, ratcheted. Epic #3408
  scoped this at two writers; the whole-repo scan found four, and one the
  epic named (patchCore) is not among them because it bypasses via
  stateReplaceField rather than the seam calls. Fourth consecutive time an
  epic's copy count proved a lower bound.

Two detectors were written and removed again before this commit, both
recorded in the file header rather than silently dropped:

  - A prompt-layer detector that reported 5 backticked prose mentions as
    drift. That is ADR-3180 Amendment 3's recorded false-positive class,
    and CONTRIBUTING.md already settles it: a backticked command reference
    is a mention. Now gated on inline-code spans.

  - A stateReplaceField co-occurrence detector for section 8.3(b). Measured
    at 29 false positives to 1 true positive — it matched the function's own
    definition and ~20 calls on frontmatter-free body slices. Banking 29
    non-defects to catch one is the 'ratchet as a parking lot' gaming route
    Decision 5 names, so it is a DECLARED KNOWN GAP owned by Phase 2
    (#3469), which both fixes it and makes its detection tractable.

* test(#3468): failing-first coverage for policy dispatch and the loud failure

Matrix sections A, B and C from 50-test-matrix.md.

Expected RED against this tree, confirmed by static trace rather than
assumed:

  B1, B2, B3 — an unwired declared preserve-when-unchanged row must throw
  with code STATE_PRESERVATION_UNWIRED_ROW and a structured .field. Today
  src/state-transition.cts:314 silently continues.

  A4 — a whitespace-only snapshot is restored today, because the guard is
  .length > 0. Required behavior is skip.

Everything else is characterization, locking in behavior the refactor must
preserve. C1 is table-driven over every FIELD_CLASSIFICATION key; C2 pins
current_phase_name's exact outputs as literals, because its row is being
reclassified preserve-always to preserve-when-unchanged as a
behavior-preserving change and nothing else would catch a drift. C3 is a
seeded fast-check property (seed 3468, 200 runs, replay data on failure).

A22 is deliberately NOT a behavioral test. Whether 'derive' has an explicit
executor is not observable through applyStatePreservation's public API — it
is a structural property, and the drift guard's unimplemented_policy axis is
what enforces it. That split is ADR-3408 Decision 5's own pairing: the lint
is the structural metric, the test is the outcome metric, and neither is
reported alone.

* refactor(#3468): dispatch preservation on the declared policy, not the field

Implements ADR-3408 sections 8.1, 8.2 and 8.6.

applyStatePreservation is now one loop over FIELD_CLASSIFICATION dispatching
on the row's preservation value, with four small executors — one per
FieldPreservation member. No branch is selected by field name. Zero
literal-argument getFieldClassification calls remain.

Behavior-preserving for 16 of 20 input classes. The four that change:

  - An unwired declared preserve-when-unchanged row now THROWS
    (code STATE_PRESERVATION_UNWIRED_ROW, structured .field) instead of
    silently continuing. This fires only on an internal invariant violation
    with both ends in our own source; a drifted, malformed or unparseable
    user STATE.md must never reach it, which is section 8.2's bright line
    and what test B8 proves through the real CLI.
  - derive gained an explicit no-op executor. That is what makes the throw
    decidable: 'policy says do nothing' is now distinguishable from 'nobody
    wired this'.
  - current_phase_name's row is corrected from preserve-always to
    preserve-when-unchanged. The row was wrong, not the code — it has always
    been delta-gated on the body Phase line, so preserve-always had two
    divergent implementations. Behavior is unchanged and test C2 pins it.
  - A whitespace-only snapshot is no longer restored; the check is trimmed.

clear is deleted from the FieldPreservation union — no row used it and no
executor existed. Speculative Generality: a policy invented for a need that
never arrived. Verified zero dependents.

The caller folds six dedicated pre/post parameters into one bodyDeltas map
keyed by field, so all seven preserve-when-unchanged rows travel one channel
instead of two. Two shapes for one kind of data is why the executor needed
per-field branches at all.

Also fixed, found while reviewing the refactor rather than deferred:

  - applyPreserveIfPlaceholder opened with a field-name literal test, which
    section 8.1 forbids outright. The executor is idempotent, so the test
    bought nothing. The drift guard could not see it, so Axis 1 is widened
    to catch field-variable comparisons against literals — the guard
    reported zero while a violation sat in the file it polices, which is
    Goodhart's gaming-by-indirection.
  - loadBaseline conflated an unreadable baseline with an absent one. A
    guard whose own diagnostic collapses two states into one identical
    result reproduces the exact failure shape this epic exists to remove.

* docs(#3468): record Phase 1 validation as ADR-3408 Amendment 1

Amendment 1 records what Phase 1 found, per ADR-3408 section 8's rule that a
behavior it does not state is not decided:

- preserve-always had TWO divergent implementations; current_phase_name's
  row was wrong and is reclassified, behavior unchanged.
- section 8.6 resolved: clear is deleted, zero dependents.
- the closed guard vocabulary is real and has exactly one true member,
  because stopped_at's scoping turned out to be caller-side extraction.
- copy count found by the guard: 4 write-seam bypasses where the epic
  scoped 2, and patchCore — one of the two it named — is not among them.
- two detectors built and removed again, with their measured false-positive
  rates, so nobody re-attempts them.
- a DECLARED KNOWN GAP for section 8.3(b), owned by Phase 2.
- Decision 5's anti-gaming list earned itself twice in one phase.

Also adds the changeset fragment.

* test(#3468): fix review findings — try/finally, stale clear allowlist, ratchet owners

Standards axis, both hard violations:

  - tests/state-write-path-drift-guard.test.cjs wrapped stdout/argv/exitCode
    restoration in try/finally inside the test body. CONTRIBUTING.md:356
    forbids it outright, and the correct t.after() pattern was already in
    use two lines up in the same test.

  - tests/state-transition.test.cjs still listed 'clear' as an allowed
    FieldPreservation value in the row-enumeration test AND the
    getFieldClassification property test, after this PR deleted it. A stale
    allowlist weakens the property's negative space — it would accept a
    resurrected clear row as valid.

Contract tension, resolved rather than left:

  ADR-3408 section 8.3 requires each ratchet entry carry the issue owning
  its removal. All four shipped with owner: null. The guard was right not to
  INVENT one, but the owners are known from the phase plan, so recording
  them is not inventing: phase.cts -> #3469, state.cts and milestone.cts ->
  #3471, health-diagnostic.cts -> sanctioned-permanent.

  Rather than a JSDoc caveat, --baseline now MERGES prior owner values on
  the (file, source) key, so a mechanical regeneration can no longer
  silently discard curated provenance. Verified by regenerating twice.

* fix(#3468): sanitize attacker-controlled fields on every guard output path

Isolated security review, MEDIUM, confidence 8/10.

findSeamBypasses and findPromptSeamUses built findings with an UNSANITIZED
`file`, while the co-located `source` on the same object was correctly
wrapped in sanitizeForReport. On a fork PR a filename is exactly as
attacker-controlled as a source fragment — a repo can legally track a
filename carrying C1 control bytes or bidi overrides.

The raw value reached two paths: --json stdout, and the COMMITTED baseline
JSON via buildBaselineEntries. JSON.stringify neutralizes C0 controls but
does NOT escape C1 (0x7f-0x9f) nor the bidi/zero-width range
sanitizeForReport exists to strip — which is the precise threat the guard's
own header names. Only the human formatter was safe.

Sanitization now happens at CONSTRUCTION, so every consumer inherits it
rather than each output path having to remember. The same defect was present
on `field` and `policy` and is fixed alongside. Double-sanitization in the
formatter is left in place, verified idempotent: escaped output is ASCII and
cannot re-match the control/bidi classes.

Also: the guard was not referenced anywhere in package.json, so nothing ran
it. A drift guard nobody runs is not a guard, and ADR-3408 Decision 5 assumes
it runs. Wired into lint:ci beside its sibling drift guards; it was already
green on this tree, so the chain stays green.

* chore(#3468): re-curate ratchet after an upstream rewording of a tracked bypass

The rebase onto origin/next turned the guard red on its first real day, which
is the ratchet working rather than a defect.

c90ae479f fix(#3350) reworded cmdPhaseComplete's syncStateFrontmatter call
onto one line and changed its third argument. Because entries are keyed on
(file, trimmed source text) rather than a line number, that single upstream
edit registered as BOTH a stale acknowledgment and an unrecorded site — the
two-sided signal the design intends, forcing a human to look rather than
letting a tracked bypass drift out of view.

The owner-preserving merge behaved exactly as designed: three owners survived
because their keys were unchanged, and phase.cts's dropped to null because its
source text is genuinely a different key. Re-curated to #3469, the phase that
owns its removal.

Note for Phase 2: c90ae479f is #3350's fix landing independently on next —
one of the two instances Phase 2 was scoped to drive fail-first. Surfaced to
the epic rather than absorbed silently.

* test(#3468): derive B1's fixture from the table so it cannot go stale

Checkpoint 2 came back with 2 failures of 33803, both B1:

  actual   'current_phase_name'
  expected 'current_plan'

The implementation was right and the test was stale. B1 hand-built a
bodyDeltas literal intending current_plan to be the ONLY unwired row, but it
also omitted status, stopped_at and current_phase_name — all three of which
became preserve-when-unchanged rows in THIS PR. Table order puts
current_phase_name first, so the throw correctly named it.

B1 now builds from neutralBodyDeltas() and deletes exactly one key, which is
what its own comment always claimed it did. A future table change can no
longer silently make it assert the wrong field.

Audited every other bodyDeltas literal in the file: four exist, all correct —
two enumerate all seven rows explicitly, two pass {} where the emptiness is
the point of the test. Roughly thirty other sites already derive from the
helper.

Also renames the local unchchangedChanged to lastActivityDescChangedDeltas.
A typo'd identifier that happens to work is still a Mysterious Name; noted
during research and fixed now that this change touches the file.

* chore(#3468): re-curate ratchet and fold the seam channel into the shared helper

The rebase onto be9329b10 fix(#3374) was a true semantic conflict, resolved
rather than handed back, because the resolution was determinable:

That PR extracted the post-sync preservation pass into a shared
applyPostSyncPreservation helper — which is ADR-3408 section 8.3, i.e. a
piece of Phase 2's own deliverable, landing upstream. Its structure is kept
wholesale; this branch's contribution is applied INSIDE it.

That combination had to be checked rather than assumed. Upstream's helper
wires only FOUR bodyDeltas keys and still passes status / stopped_at /
current_phase_name through six dedicated parameters. This branch reclassifies
current_phase_name to preserve-when-unchanged, deletes those six parameters
from StatePreservationInput, and makes an unwired declared row THROW. Taking
upstream's file as-is would therefore have thrown on EVERY STATE.md write.

The helper now wires all seven rows through the single channel. Verified
7-to-7 against FIELD_CLASSIFICATION, with a clean tsc — which is the real
proof the dedicated parameters are gone, since they no longer exist on the
input type.

The ratchet also caught the same phase.cts call being reworded a second time,
reporting it as both a stale acknowledgment and an unrecorded site. Re-curated
to #3469. Recording the tradeoff plainly: keying on (file, source text) means
an upstream reword of a tracked line needs re-curation, where keying on line
numbers would churn on every unrelated edit. ADR-3180 Decision 4(e) chose
source text deliberately, and the owner-preserving merge added earlier covers
the common case where the text is unchanged.

* chore(#3468): backfill pr number in changeset fragment

---------

Co-authored-by: sim <sim@local>
This commit is contained in:
Tom Boucher
2026-08-14 13:25:30 -04:00
committed by GitHub
parent 5b5d473e13
commit 1218d76d62
11 changed files with 2665 additions and 269 deletions

View File

@@ -34,7 +34,6 @@ describe('ADR-1769 substrate: field-classification table', () => {
'preserve-when-unchanged',
'preserve-always',
'preserve-if-placeholder',
'clear',
]);
test('every classified field has a { source, preservation } row with known enum values', () => {
@@ -50,10 +49,10 @@ describe('ADR-1769 substrate: field-classification table', () => {
}
});
test('current_phase_name is curated / preserve-always (ADR-1769 §4 — kills #1743/#1695 by construction)', () => {
test('current_phase_name is curated / preserve-when-unchanged (ADR-1769 §4 — kills #1743/#1695 by construction; ADR-3408 #3468 reclassified from preserve-always to match its long-standing delta-gated behavior)', () => {
const cls = getFieldClassification('current_phase_name');
assert.strictEqual(cls && cls.source, 'curated');
assert.strictEqual(cls && cls.preservation, 'preserve-always');
assert.strictEqual(cls && cls.preservation, 'preserve-when-unchanged');
});
test('progress is curated / preserve-always (ADR-1769 §4 — curated-progress ratchet)', () => {
@@ -417,7 +416,6 @@ describe('ADR-1769 Phase 1: property tests (RULESET.TESTS.property-based-testing
'preserve-when-unchanged',
'preserve-always',
'preserve-if-placeholder',
'clear',
]);
fc.assert(
fc.property(fc.string(), (s) => {
@@ -1295,12 +1293,13 @@ describe('ADR-1769 Phase 7: sync transition — body writes + #1761', () => {
// ─────────────────────────────────────────────────────────────────────────────
describe('ADR-1769 #1796: applyStatePreservation — table-driven post-sync consolidation', () => {
// Shared no-op deltas for tests that only exercise one field.
const untouched = {
preBodyStatus: null, postBodyStatus: null,
preBodyStoppedAt: null, postBodyStoppedAt: null,
preBodyPhaseSource: null, postBodyPhaseSource: null,
};
// Shared no-op deltas for tests that only exercise one field. #3468 folded
// the three dedicated status/stopped_at/current_phase_name parameter pairs
// into the single bodyDeltas channel every preserve-when-unchanged row now
// uses — `neutralBodyDeltas()` (defined below, hoisted) wires every such
// row to an "unchanged this write" delta so a test exercising ONE field
// (e.g. progress) never trips the §8.2 unwired-row throw for another.
const untouched = { bodyDeltas: neutralBodyDeltas() };
test('progress: restores curated block when table=preserve-always and transition is not re-deriving (!resync)', () => {
// Default behavior: wholesale curated restore. #3242 Bug A protection.
@@ -1426,9 +1425,7 @@ describe('ADR-1769 #1796: applyStatePreservation — table-driven post-sync cons
preFmSnapshot: { status: 'completed' },
postFm: { status: 'verifying' },
resync: true,
preBodyStatus: 'Executing Phase 3', postBodyStatus: 'Executing Phase 3',
preBodyStoppedAt: null, postBodyStoppedAt: null,
preBodyPhaseSource: null, postBodyPhaseSource: null,
bodyDeltas: { ...neutralBodyDeltas(), status: { pre: 'Executing Phase 3', post: 'Executing Phase 3' } },
});
assert.equal(r.postFm.status, 'completed');
assert.equal(r.mutated, true);
@@ -1440,23 +1437,19 @@ describe('ADR-1769 #1796: applyStatePreservation — table-driven post-sync cons
preFmSnapshot: { status: 'completed' },
postFm: { status: 'verifying' },
resync: true,
preBodyStatus: 'Executing Phase 3', postBodyStatus: 'Completed Phase 3', // changed
preBodyStoppedAt: null, postBodyStoppedAt: null,
preBodyPhaseSource: null, postBodyPhaseSource: null,
bodyDeltas: { ...neutralBodyDeltas(), status: { pre: 'Executing Phase 3', post: 'Completed Phase 3' } }, // changed
});
assert.equal(r.postFm.status, 'verifying');
assert.equal(r.mutated, false);
});
test('current_phase_name: preserves curated value when body Phase source unchanged (preserve-always)', () => {
test('current_phase_name: preserves curated value when body Phase source unchanged (preserve-when-unchanged, #3468 reclassified)', () => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { current_phase_name: 'curated-name' },
postFm: { current_phase_name: 'wrong-parenthetical-harvest' },
resync: true,
preBodyStatus: null, postBodyStatus: null,
preBodyStoppedAt: null, postBodyStoppedAt: null,
preBodyPhaseSource: '3', postBodyPhaseSource: '3',
bodyDeltas: { ...neutralBodyDeltas(), current_phase_name: { pre: '3', post: '3' } },
});
assert.equal(r.postFm.current_phase_name, 'curated-name');
assert.equal(r.mutated, true);
@@ -1480,7 +1473,7 @@ describe('ADR-1769 #1796: applyStatePreservation — table-driven post-sync cons
// #3258: every FIELD_CLASSIFICATION row declaring a preservation policy must be
// honored by applyStatePreservation (the table-consuming pass). The table's own
// docstring promises "a policy change is a one-row table edit" — this invariant
// proves it: for every non-`derive`/non-`clear` row, a minimal input where the
// proves it: for every non-`derive` row, a minimal input where the
// declared policy would restore the snapshot value DOES restore it. Adding a
// new preservation row without an implementation branch makes this fail.
//
@@ -1492,23 +1485,23 @@ describe('ADR-1769 #1796: applyStatePreservation — table-driven post-sync cons
// ─────────────────────────────────────────────────────────────────────────────
describe('#3258: applyStatePreservation honors every declared preservation row', () => {
const GOOD_PLACEHOLDER = 'preserved-by-table';
// Universal "body source unchanged this write" deltas. Every
// preserve-when-unchanged probe reuses these so the delta condition (pre ===
// post) is satisfied and the only variable is whether the branch exists.
// #3468: current_phase_name folded into this same bodyDeltas channel
// (reclassified from preserve-always to preserve-when-unchanged) — every
// preserve-when-unchanged row must be present here or the §8.2 throw fires
// for whichever row a probe does not itself supply.
const SAME = { pre: 'unchanged-source', post: 'unchanged-source' };
const unchangedBodyDeltas = {
status: SAME,
stopped_at: SAME,
current_phase_name: SAME,
paused_at: SAME,
current_phase: SAME,
current_plan: SAME,
last_activity_desc: SAME,
};
// Dedicated-channel deltas (the four pre-#3258 rows use these, unchanged).
const sameStatus = { preBodyStatus: 'x', postBodyStatus: 'x' };
const sameStoppedAt = { preBodyStoppedAt: 'x', postBodyStoppedAt: 'x' };
const samePhaseSource = { preBodyPhaseSource: 'x', postBodyPhaseSource: 'x' };
// Per-policy probe. Returns whether applyStatePreservation restored the
// field's snapshot value under an input crafted so the declared policy fires.
@@ -1516,36 +1509,27 @@ describe('#3258: applyStatePreservation honors every declared preservation row',
const cls = getFieldClassification(field);
if (!cls) return false;
const policy = cls.preservation;
if (policy === 'derive' || policy === 'clear') return true; // not a preservation policy
if (policy === 'derive') return true; // not a preservation policy
const GOOD = 'preserved-by-table';
const BAD = 'clobbered-by-derive';
if (policy === 'preserve-always') {
if (field === 'progress') {
const curated = { progress: { total_phases: 4, completed_phases: 3, percent: 75 } };
const r = applyStatePreservation({
preFm: curated, preFmSnapshot: curated,
postFm: { progress: { total_phases: 5, completed_phases: 0, percent: 0 } },
resync: false, bodyDeltas: unchangedBodyDeltas,
...sameStatus, ...sameStoppedAt, ...samePhaseSource,
});
return JSON.stringify(r.postFm.progress) === JSON.stringify(curated.progress);
}
// current_phase_name: preserve-always, restored when body Phase source unchanged.
// Only `progress` carries this policy today (current_phase_name was
// reclassified to preserve-when-unchanged in #3468 — ADR-3408 §8.1).
const curated = { progress: { total_phases: 4, completed_phases: 3, percent: 75 } };
const r = applyStatePreservation({
preFm: null, preFmSnapshot: { [field]: GOOD },
postFm: { [field]: BAD }, resync: false, bodyDeltas: unchangedBodyDeltas,
...sameStatus, ...sameStoppedAt, preBodyPhaseSource: '3', postBodyPhaseSource: '3',
preFm: curated, preFmSnapshot: curated,
postFm: { progress: { total_phases: 5, completed_phases: 0, percent: 0 } },
resync: false, bodyDeltas: unchangedBodyDeltas,
});
return r.postFm[field] === GOOD;
return JSON.stringify(r.postFm.progress) === JSON.stringify(curated.progress);
}
if (policy === 'preserve-when-unchanged') {
const r = applyStatePreservation({
preFm: null, preFmSnapshot: { [field]: GOOD },
postFm: { [field]: BAD }, resync: true, bodyDeltas: unchangedBodyDeltas,
...sameStatus, ...sameStoppedAt, ...samePhaseSource,
});
return r.postFm[field] === GOOD;
}
@@ -1559,7 +1543,6 @@ describe('#3258: applyStatePreservation honors every declared preservation row',
preFmSnapshot: { milestone: GOOD, milestone_name: GOOD },
postFm: { milestone: 'derived-version', milestone_name: 'milestone' },
resync: true, bodyDeltas: unchangedBodyDeltas,
...sameStatus, ...sameStoppedAt, ...samePhaseSource,
});
return r.postFm[field] === GOOD;
}
@@ -1567,10 +1550,10 @@ describe('#3258: applyStatePreservation honors every declared preservation row',
return false;
}
test('every non-derive/non-clear preservation row is honored (the one-row-table-edit contract)', () => {
test('every non-derive preservation row is honored (the one-row-table-edit contract)', () => {
const expected = [];
for (const [field, cls] of Object.entries(FIELD_CLASSIFICATION)) {
if (cls.preservation !== 'derive' && cls.preservation !== 'clear') {
if (cls.preservation !== 'derive') {
expected.push(field);
}
}
@@ -1579,36 +1562,43 @@ describe('#3258: applyStatePreservation honors every declared preservation row',
missing,
[],
`applyStatePreservation does not honor these declared preservation rows (expected every ` +
`non-derive/non-clear row to restore its snapshot value): ${JSON.stringify(missing)}. ` +
`non-derive row to restore its snapshot value): ${JSON.stringify(missing)}. ` +
`Add a branch per ADR-1769 §4 so the table is the single policy source (#3258).`,
);
});
const unchchangedChanged = {
const lastActivityDescChangedDeltas = {
status: { pre: 'x', post: 'x' },
stopped_at: { pre: 'x', post: 'x' },
current_phase_name: { pre: 'x', post: 'x' },
paused_at: { pre: 'x', post: 'x' },
current_phase: { pre: 'x', post: 'x' },
current_plan: { pre: 'x', post: 'x' },
last_activity_desc: { pre: 'old description', post: 'new description from transition' }, // changed
};
test('a row declaring a preservation policy with no implementation would be caught (sentinel)', () => {
// Proves the invariant above actually catches a missing implementation: a
// field with a preservation policy but no body-delta wiring / branch does
// not get restored. We simulate this by probing a field whose body-source
// delta the caller forgot to supply (the realistic regression shape).
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { current_plan: GOOD_PLACEHOLDER },
postFm: { current_plan: 'derived' },
resync: true,
bodyDeltas: {}, // caller forgot to wire current_plan's body-source delta
...sameStatus, ...sameStoppedAt, ...samePhaseSource,
});
assert.notEqual(r.postFm.current_plan, GOOD_PLACEHOLDER,
'a preserve-when-unchanged row with no body-source delta wiring must NOT be restored ' +
'(proves the invariant would catch a new unimplemented row)');
test('a preserve-when-unchanged row with no wired bodyDeltas entry THROWS (ADR-3408 §8.2 — #3468 tightened from the pre-#3468 silent skip)', () => {
// Pre-#3468 this row was a "sentinel" proving a missing implementation was
// merely NOT restored (a silent `continue`). ADR-3408 §8.2 requires the
// stronger invariant: an internal invariant violation — a declared row
// the caller forgot to wire via bodyDeltas — THROWS with a structured
// error, never a silent no-op indistinguishable from a correct skip.
assert.throws(
() => applyStatePreservation({
preFm: null,
preFmSnapshot: { current_plan: 'preserved-by-table' },
postFm: { current_plan: 'derived' },
resync: true,
bodyDeltas: {}, // caller forgot to wire current_plan's body-source delta
}),
(err) => {
assert.strictEqual(err.code, 'STATE_PRESERVATION_UNWIRED_ROW');
assert.strictEqual(err.field, 'current_phase',
'current_phase is the first preserve-when-unchanged field in FIELD_CLASSIFICATION\'s ' +
'iteration order, so it is the field named by the throw when bodyDeltas is empty');
return true;
},
);
});
// Per-field restore tests (clearer failure messages than the set-equality
@@ -1621,7 +1611,6 @@ describe('#3258: applyStatePreservation honors every declared preservation row',
postFm: { last_activity_desc: 'stale derived description' },
resync: true,
bodyDeltas: { ...unchangedBodyDeltas },
...sameStatus, ...sameStoppedAt, ...samePhaseSource,
});
assert.equal(r.postFm.last_activity_desc, 'authoritative description');
assert.equal(r.mutated, true);
@@ -1633,8 +1622,7 @@ describe('#3258: applyStatePreservation honors every declared preservation row',
preFmSnapshot: { last_activity_desc: 'old description' },
postFm: { last_activity_desc: 'new description from transition' },
resync: true,
bodyDeltas: { ...unchchangedChanged }, // body 'Last Activity Description' moved
...sameStatus, ...sameStoppedAt, ...samePhaseSource,
bodyDeltas: { ...lastActivityDescChangedDeltas }, // body 'Last Activity Description' moved
});
assert.equal(r.postFm.last_activity_desc, 'new description from transition');
assert.equal(r.mutated, false);
@@ -1650,7 +1638,6 @@ describe('#3258: applyStatePreservation honors every declared preservation row',
postFm: { paused_at: '2026-01-01' },
resync: true,
bodyDeltas: { ...unchangedBodyDeltas },
...sameStatus, ...sameStoppedAt, ...samePhaseSource,
});
assert.equal(r.postFm.paused_at, '2026-02-02');
assert.equal(r.mutated, true);
@@ -1663,7 +1650,6 @@ describe('#3258: applyStatePreservation honors every declared preservation row',
postFm: { current_phase: '2' },
resync: true,
bodyDeltas: { ...unchangedBodyDeltas },
...sameStatus, ...sameStoppedAt, ...samePhaseSource,
});
assert.equal(r.postFm.current_phase, '4');
assert.equal(r.mutated, true);
@@ -1676,7 +1662,6 @@ describe('#3258: applyStatePreservation honors every declared preservation row',
postFm: { current_plan: '3' },
resync: true,
bodyDeltas: { ...unchangedBodyDeltas },
...sameStatus, ...sameStoppedAt, ...samePhaseSource,
});
assert.equal(r.postFm.current_plan, '5');
assert.equal(r.mutated, true);
@@ -1689,7 +1674,6 @@ describe('#3258: applyStatePreservation honors every declared preservation row',
postFm: { milestone: '0.x', milestone_name: 'milestone' }, // placeholder derive
resync: true,
bodyDeltas: { ...unchangedBodyDeltas },
...sameStatus, ...sameStoppedAt, ...samePhaseSource,
});
assert.equal(r.postFm.milestone_name, 'Real Curated Name',
'placeholder-derived milestone_name must yield to the curated snapshot (#948/#2135 contract)');
@@ -1698,6 +1682,612 @@ describe('#3258: applyStatePreservation honors every declared preservation row',
});
});
// ─────────────────────────────────────────────────────────────────────────────
// #3468 (ADR-3408, Phase 1 test matrix 50-test-matrix.md, sections A/B/C):
// policy dispatch, the §8.2 unenforced-row invariant, and behavior identity
// across the refactor. Failing-first: several rows below are EXPECTED to
// fail against the current tree until the refactor lands (see each test's
// comment for which). Everything else characterizes behavior the refactor
// must preserve byte-for-byte.
// ─────────────────────────────────────────────────────────────────────────────
// Wires every currently-declared preserve-when-unchanged field with a neutral
// "unchanged this write" delta, so a test probing ONE field never trips over
// another field being unwired — forward-compatible with both today's tree
// (where an unwired row silently `continue`s) and the post-refactor tree
// (where an unwired row throws per §8.2 / matrix row B1).
function neutralBodyDeltas() {
const deltas = {};
for (const [field, cls] of Object.entries(FIELD_CLASSIFICATION)) {
if (cls.preservation === 'preserve-when-unchanged') {
deltas[field] = { pre: 'unchanged-source', post: 'unchanged-source' };
}
}
return deltas;
}
// #3468 folded status/stopped_at/current_phase_name's three dedicated
// pre/post parameter pairs into the single bodyDeltas channel and deleted
// them from StatePreservationInput — applyStatePreservation no longer reads
// these properties at all. Kept (rather than stripped from every call site
// below) as an inert, harmless spread: StatePreservationInput is a TypeScript
// type these plain-JS tests are not checked against, so an extra own
// property is silently ignored at runtime, and removing it from ~20 call
// sites would be pure churn with no behavior change. neutralBodyDeltas()
// already supplies the real (bodyDeltas-based) no-op deltas these fields
// need post-refactor.
const dedicatedNoop = {
preBodyStatus: 'x', postBodyStatus: 'x',
preBodyStoppedAt: 'x', postBodyStoppedAt: 'x',
preBodyPhaseSource: 'x', postBodyPhaseSource: 'x',
};
describe('#3468 matrix A: executor policy dispatch (ADR-3408 §8.1) — new/boundary/hostile rows', () => {
test('A3: preserve-when-unchanged — an empty-string snapshot is not restored', () => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { current_plan: '' },
postFm: { current_plan: 'derived' },
resync: true,
bodyDeltas: neutralBodyDeltas(),
...dedicatedNoop,
});
assert.equal(r.postFm.current_plan, 'derived');
assert.equal(r.mutated, false);
});
// A4 (matrix: "likely gap today"): a whitespace-only snapshot passes the
// current `.length > 0` check (3 > 0) and DOES get restored today. The
// required behavior is skip. This is expected to FAIL against the current
// tree until the refactor tightens the guard.
test('A4: preserve-when-unchanged — a whitespace-only snapshot is not restored (".length > 0" is not enough)', () => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { current_plan: ' ' },
postFm: { current_plan: 'derived' },
resync: true,
bodyDeltas: neutralBodyDeltas(),
...dedicatedNoop,
});
assert.equal(r.postFm.current_plan, 'derived',
'a whitespace-only snapshot must not be treated as a real curated value');
assert.equal(r.mutated, false);
});
test('A5: preserve-when-unchanged — a non-string snapshot is ignored (no throw)', () => {
for (const snapshot of [42, true, null, { nested: 1 }, undefined]) {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { current_plan: snapshot },
postFm: { current_plan: 'derived' },
resync: true,
bodyDeltas: neutralBodyDeltas(),
...dedicatedNoop,
});
assert.equal(r.postFm.current_plan, 'derived', `snapshot=${JSON.stringify(snapshot)} must not be restored`);
}
});
test('A6: preserve-when-unchanged — no-op when postFm already equals the snapshot', () => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { current_plan: 'same-value' },
postFm: { current_plan: 'same-value' },
resync: true,
bodyDeltas: neutralBodyDeltas(),
...dedicatedNoop,
});
assert.equal(r.postFm.current_plan, 'same-value');
assert.equal(r.mutated, false);
});
test('A7: preserve-when-unchanged — a postFm missing the key entirely is restored (undefined !== snapshot)', () => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { current_plan: 'curated' },
postFm: {}, // key absent entirely
resync: true,
bodyDeltas: neutralBodyDeltas(),
...dedicatedNoop,
});
assert.equal(r.postFm.current_plan, 'curated');
assert.equal(r.mutated, true);
});
test('A8: status — the "unknown" sentinel snapshot is never restored', () => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { status: 'unknown' },
postFm: { status: 'verifying' },
resync: true,
preBodyStatus: 'x', postBodyStatus: 'x',
preBodyStoppedAt: 'x', postBodyStoppedAt: 'x',
preBodyPhaseSource: 'x', postBodyPhaseSource: 'x',
bodyDeltas: neutralBodyDeltas(),
});
assert.equal(r.postFm.status, 'verifying');
assert.equal(r.mutated, false);
});
test('A9: status — the "unknown" sentinel guard is case-sensitive ("Unknown" is a real value, restored)', () => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { status: 'Unknown' },
postFm: { status: 'verifying' },
resync: true,
preBodyStatus: 'x', postBodyStatus: 'x',
preBodyStoppedAt: 'x', postBodyStoppedAt: 'x',
preBodyPhaseSource: 'x', postBodyPhaseSource: 'x',
bodyDeltas: neutralBodyDeltas(),
});
assert.equal(r.postFm.status, 'Unknown',
'the sentinel is an exact-match on the lowercase literal "unknown" — a case variant is a real value');
assert.equal(r.mutated, true);
});
test('A12: preserve-always progress — preFm===null under !resync does not throw (skip)', () => {
assert.doesNotThrow(() => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: {},
postFm: { progress: { total_phases: 5, completed_phases: 1, percent: 20 } },
resync: false,
bodyDeltas: neutralBodyDeltas(),
...dedicatedNoop,
});
assert.deepEqual(r.postFm.progress, { total_phases: 5, completed_phases: 1, percent: 20 });
assert.equal(r.mutated, false);
});
});
test('A14: deriveProgressKeys — derived completed_plans === curated keeps curated (limit: ">" not ">=", #2969)', () => {
const curated = { progress: { total_plans: 10, completed_plans: 7, percent: 70 } };
const r = applyStatePreservation({
preFm: curated,
preFmSnapshot: curated,
postFm: { progress: { total_plans: 10, completed_plans: 7, percent: 70 } }, // derived === curated
resync: false,
deriveProgressKeys: true,
bodyDeltas: neutralBodyDeltas(),
...dedicatedNoop,
});
assert.equal(r.postFm.progress.completed_plans, 7,
'equal counts (derived === curated) must keep curated — the ratchet is ">" not ">="');
});
test('A18: preserve-if-placeholder — punctuation-led derived names are rejected for every delimiter', () => {
for (const derived of ['— Foo', ': Foo', '-Foo']) {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { milestone: '1.0', milestone_name: 'Real Curated Name' },
postFm: { milestone: '1.1', milestone_name: derived },
resync: true,
bodyDeltas: neutralBodyDeltas(),
...dedicatedNoop,
});
assert.equal(r.postFm.milestone_name, 'Real Curated Name',
`punctuation-led derived name ${JSON.stringify(derived)} must be rejected`);
}
});
test('A19: preserve-if-placeholder — an empty-string derived name is rejected (restored)', () => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { milestone: '1.0', milestone_name: 'Real Curated Name' },
postFm: { milestone: '1.1', milestone_name: '' },
resync: true,
bodyDeltas: neutralBodyDeltas(),
...dedicatedNoop,
});
assert.equal(r.postFm.milestone_name, 'Real Curated Name');
});
test('A20: preserve-if-placeholder — a placeholder snapshot is not restored over a placeholder derived value', () => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { milestone: '1.0', milestone_name: 'milestone' }, // snapshot IS the placeholder
postFm: { milestone: '1.1', milestone_name: 'milestone' }, // derived is also the placeholder
resync: true,
bodyDeltas: neutralBodyDeltas(),
...dedicatedNoop,
});
assert.equal(r.postFm.milestone_name, 'milestone', 'nothing better to restore — value passes through unchanged');
assert.equal(r.postFm.milestone, '1.1', 'milestone version passes through unchanged alongside it');
});
test('A21: preserve-if-placeholder — a real, different derived name wins over the curated snapshot', () => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { milestone: '1.0', milestone_name: 'Old Curated Name' },
postFm: { milestone: '2.0', milestone_name: 'New Real Milestone Name' },
resync: true,
bodyDeltas: neutralBodyDeltas(),
...dedicatedNoop,
});
assert.equal(r.postFm.milestone_name, 'New Real Milestone Name');
assert.equal(r.postFm.milestone, '2.0');
});
// A22 (design 40-design.md row 17 / matrix "new — row 17"): a `derive` row
// must be an explicit no-op — untouched, no throw, mutated unaffected.
// NOTE: as a black-box behavioral probe against the public
// applyStatePreservation API (the only seam this test file can drive),
// this currently ALREADY PASSES — today's loop filters every field to
// `cls.preservation === 'preserve-when-unchanged'` before doing anything,
// so a `derive` row is skipped by omission rather than by an explicit
// branch. The matrix's "no branch exists" is a source-structure claim
// (§8.1's "exactly one executor per policy") that this black-box test
// cannot distinguish from "skipped by omission" — see report.
test('A22: derive rows (last_updated, state_head, gsd_state_version, last_activity) are an explicit no-op', () => {
for (const field of ['last_updated', 'state_head', 'gsd_state_version', 'last_activity']) {
assert.doesNotThrow(() => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { [field]: 'curated-value' },
postFm: { [field]: 'freshly-derived-value' },
resync: true,
bodyDeltas: { ...neutralBodyDeltas(), [field]: { pre: 'old', post: 'new' } },
...dedicatedNoop,
});
assert.equal(r.postFm[field], 'freshly-derived-value',
`${field}: a derive row always takes the freshly-derived (postFm) value`);
});
}
});
test('A23: a field with no FIELD_CLASSIFICATION row passes through untouched', () => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { totally_unclassified_field: 'curated' },
postFm: { totally_unclassified_field: 'derived' },
resync: true,
bodyDeltas: { ...neutralBodyDeltas(), totally_unclassified_field: { pre: 'x', post: 'y' } },
...dedicatedNoop,
});
assert.equal(r.postFm.totally_unclassified_field, 'derived');
assert.equal(r.mutated, false);
});
test('A24: prototype-pollution — __proto__ / constructor / toString never resolve to inherited classifications', () => {
for (const hostileKey of ['__proto__', 'constructor', 'toString']) {
assert.strictEqual(getFieldClassification(hostileKey), null,
`${hostileKey} must not resolve to an inherited Object member`);
}
// applyStatePreservation itself must not crash or misbehave when a
// hostile field name rides along in postFm/preFmSnapshot/bodyDeltas.
// Computed keys (not literal `__proto__:`) create genuine OWN properties
// instead of mutating the object's prototype.
assert.doesNotThrow(() => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { ['__proto__']: 'x', ['constructor']: 'y', ['toString']: 'z' },
postFm: { ['__proto__']: 'a', ['constructor']: 'b', ['toString']: 'c' },
resync: true,
bodyDeltas: {
...neutralBodyDeltas(),
['__proto__']: { pre: 'x', post: 'y' },
['constructor']: { pre: 'x', post: 'y' },
['toString']: { pre: 'x', post: 'y' },
},
...dedicatedNoop,
});
assert.equal(typeof r.postFm, 'object');
assert.equal(typeof r.mutated, 'boolean');
});
});
});
// ─────────────────────────────────────────────────────────────────────────────
// #3468 matrix B: the §8.2 unenforced-row invariant.
//
// Structured error shape THIS TASK REQUIRES THE IMPLEMENTATION TO PROVIDE
// (CONTRIBUTING.md § Prohibited: Raw Text Matching — the thrown error must
// carry typed properties, never asserted via message-prose matching):
// err.code === 'STATE_PRESERVATION_UNWIRED_ROW'
// err.field === '<the FIELD_CLASSIFICATION key that was not wired>'
//
// B1-B3 are EXPECTED TO FAIL against the current tree: today's loop at
// src/state-transition.cts:314 does `if (!delta) continue;` — a silent skip,
// not a throw. This is the exact defect §8.2 requires fixing.
// ─────────────────────────────────────────────────────────────────────────────
describe('#3468 matrix B: an unenforced preserve-when-unchanged row (ADR-3408 §8.2)', () => {
test('B1: a declared preserve-when-unchanged row missing from bodyDeltas throws, naming the field', () => {
const bodyDeltas = neutralBodyDeltas();
delete bodyDeltas.current_plan; // the ONLY unwired row
assert.throws(
() => applyStatePreservation({
preFm: null,
preFmSnapshot: { current_plan: 'curated' },
postFm: { current_plan: 'derived' },
resync: true,
bodyDeltas,
...dedicatedNoop,
}),
(err) => {
assert.strictEqual(err.code, 'STATE_PRESERVATION_UNWIRED_ROW');
assert.strictEqual(err.field, 'current_plan');
return true;
},
);
});
test('B2: bodyDeltas entirely absent throws, naming the first unwired row', () => {
assert.throws(
() => applyStatePreservation({
preFm: null,
preFmSnapshot: {},
postFm: {},
resync: true,
// bodyDeltas omitted entirely
...dedicatedNoop,
}),
(err) => {
assert.strictEqual(err.code, 'STATE_PRESERVATION_UNWIRED_ROW');
// current_phase is the first preserve-when-unchanged field in
// FIELD_CLASSIFICATION's insertion order — before current_phase_name,
// current_plan, status, stopped_at, paused_at, last_activity_desc,
// all of which share the same loop post-#3468 (no field stays on a
// dedicated channel any more).
assert.strictEqual(err.field, 'current_phase');
return true;
},
);
});
test('B3: bodyDeltas present but {} throws, naming the first unwired row', () => {
assert.throws(
() => applyStatePreservation({
preFm: null,
preFmSnapshot: {},
postFm: {},
resync: true,
bodyDeltas: {},
...dedicatedNoop,
}),
(err) => {
assert.strictEqual(err.code, 'STATE_PRESERVATION_UNWIRED_ROW');
assert.strictEqual(err.field, 'current_phase');
return true;
},
);
});
test('B4: a delta shaped {pre:null,post:null} is treated as WIRED, not missing (the boundary that separates B1 from A1)', () => {
const bodyDeltas = {
...neutralBodyDeltas(),
current_phase: { pre: null, post: null },
};
assert.doesNotThrow(() => {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: {}, // no snapshot — skip is a legitimate, non-throwing outcome
postFm: { current_phase: 'derived' },
resync: true,
bodyDeltas,
...dedicatedNoop,
});
assert.equal(r.postFm.current_phase, 'derived');
});
});
test('B5: a partially-shaped delta ({post} with no pre key) does not throw — treated as wired', () => {
const bodyDeltas = {
...neutralBodyDeltas(),
current_phase: { post: 'x' }, // `pre` key entirely absent
};
assert.doesNotThrow(() => {
applyStatePreservation({
preFm: null,
preFmSnapshot: { current_phase: 'curated' },
postFm: { current_phase: 'derived' },
resync: true,
bodyDeltas,
...dedicatedNoop,
});
});
});
test('B6: only preserve-when-unchanged rows require wiring — derive/preserve-always/preserve-if-placeholder do not', () => {
// Every preserve-when-unchanged row IS wired here; last_updated (derive),
// progress (preserve-always), and milestone_name (preserve-if-placeholder)
// are deliberately absent from bodyDeltas and must not trigger the throw.
assert.doesNotThrow(() => {
applyStatePreservation({
preFm: null,
preFmSnapshot: {},
postFm: {},
resync: true,
bodyDeltas: neutralBodyDeltas(),
...dedicatedNoop,
});
});
});
});
// ─────────────────────────────────────────────────────────────────────────────
// #3468 matrix C: behavior identity across the refactor (ADR-3408 §8.1).
//
// Literal, pinned expected values — not derived from a shared helper — per
// 40-design.md's "Known limits": the reclassification of current_phase_name
// is behavior-preserving by design, so the existing suite staying green
// proves nothing; only a pinned before/after comparison catches a silent
// drift (CONTRIBUTING.md § Fixture provenance #2371).
// ─────────────────────────────────────────────────────────────────────────────
describe('#3468 matrix C1/C2: identity across the refactor — pinned literal outputs', () => {
const GOOD = 'preserved-by-table';
const BAD = 'clobbered-by-derive';
// Four of the seven preserve-when-unchanged rows, pinned generically here;
// status/stopped_at get their own pinned test above (their 'unknown'
// sentinel guard has no analogue in these four), and current_phase_name
// gets its own dedicated C2 test below (it needs BOTH an unchanged AND a
// changed delta for the same field, which this generic loop cannot express).
const LOOP_PWU_FIELDS = ['current_phase', 'current_plan', 'paused_at', 'last_activity_desc'];
test('C1: shared preserve-when-unchanged loop — delta unchanged restores the snapshot (pinned)', () => {
for (const field of LOOP_PWU_FIELDS) {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { [field]: GOOD },
postFm: { [field]: BAD },
resync: true,
bodyDeltas: neutralBodyDeltas(),
...dedicatedNoop,
});
assert.equal(r.postFm[field], GOOD, `${field}: pinned identity — restore-when-unchanged`);
}
});
test('C1: shared preserve-when-unchanged loop — delta changed lets derived win (pinned)', () => {
for (const field of LOOP_PWU_FIELDS) {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { [field]: GOOD },
postFm: { [field]: BAD },
resync: true,
bodyDeltas: { ...neutralBodyDeltas(), [field]: { pre: 'old', post: 'new' } },
...dedicatedNoop,
});
assert.equal(r.postFm[field], BAD, `${field}: pinned identity — derived wins when body source changed`);
}
});
test('C1: status / stopped_at (pinned)', () => {
const rStatus = applyStatePreservation({
preFm: null, preFmSnapshot: { status: GOOD }, postFm: { status: BAD }, resync: true,
bodyDeltas: neutralBodyDeltas(),
});
assert.equal(rStatus.postFm.status, GOOD);
const rStopped = applyStatePreservation({
preFm: null, preFmSnapshot: { stopped_at: GOOD }, postFm: { stopped_at: BAD }, resync: true,
bodyDeltas: neutralBodyDeltas(),
});
assert.equal(rStopped.postFm.stopped_at, GOOD);
});
test('C1: preserve-always progress and preserve-if-placeholder milestone/milestone_name (pinned)', () => {
const curated = { progress: { total_phases: 4, completed_phases: 3, percent: 75 } };
const rProgress = applyStatePreservation({
preFm: curated, preFmSnapshot: curated,
postFm: { progress: { total_phases: 5, completed_phases: 0, percent: 0 } },
resync: false, bodyDeltas: neutralBodyDeltas(), ...dedicatedNoop,
});
assert.deepEqual(rProgress.postFm.progress, curated.progress);
const rMilestone = applyStatePreservation({
preFm: null,
preFmSnapshot: { milestone: '1.0', milestone_name: GOOD },
postFm: { milestone: '1.1', milestone_name: 'milestone' },
resync: true, bodyDeltas: neutralBodyDeltas(), ...dedicatedNoop,
});
assert.equal(rMilestone.postFm.milestone_name, GOOD);
});
test('C1: derive-classified fields pass through untouched regardless of snapshot (pinned)', () => {
for (const field of ['gsd_state_version', 'last_updated', 'last_activity', 'state_head']) {
const r = applyStatePreservation({
preFm: null,
preFmSnapshot: { [field]: GOOD },
postFm: { [field]: BAD },
resync: true,
bodyDeltas: { ...neutralBodyDeltas(), [field]: { pre: 'old', post: 'new' } },
...dedicatedNoop,
});
assert.equal(r.postFm[field], BAD, `${field}: derive rows always take the derived (postFm) value`);
}
});
// C2: current_phase_name's row is reclassified preserve-always →
// preserve-when-unchanged (#3468, ADR-3408 §8.1 amendment) as a
// BEHAVIOR-PRESERVING change (40-design.md). Both outcomes are pinned
// literally so a post-refactor drift is caught even though the existing
// suite staying green would prove nothing. The delta now travels through
// bodyDeltas.current_phase_name (folded from the pre-#3468 dedicated
// preBodyPhaseSource/postBodyPhaseSource parameter pair, which #3468
// deleted from StatePreservationInput) rather than through
// neutralBodyDeltas()'s generic "unchanged" default, since this test needs
// to drive both an unchanged AND a changed delta for the SAME field.
test('C2: current_phase_name (reclassified preserve-always → preserve-when-unchanged) — pinned outputs', () => {
const rEqual = applyStatePreservation({
preFm: null,
preFmSnapshot: { current_phase_name: GOOD },
postFm: { current_phase_name: BAD },
resync: true,
bodyDeltas: { ...neutralBodyDeltas(), current_phase_name: { pre: '3', post: '3' } }, // body Phase: source unchanged this write
});
assert.equal(rEqual.postFm.current_phase_name, GOOD,
'reclassification must not change this: unchanged body Phase source still restores the curated name');
assert.equal(rEqual.mutated, true);
const rDiffer = applyStatePreservation({
preFm: null,
preFmSnapshot: { current_phase_name: GOOD },
postFm: { current_phase_name: BAD },
resync: true,
bodyDeltas: { ...neutralBodyDeltas(), current_phase_name: { pre: '3', post: '4' } }, // body Phase: source changed this write
});
assert.equal(rDiffer.postFm.current_phase_name, BAD,
'reclassification must not change this: changed body Phase source still lets derived win');
assert.equal(rDiffer.mutated, false);
});
});
describe('#3468 matrix C3: executor dispatch is a pure function of the row policy (property)', () => {
// Every preserve-when-unchanged field EXCEPT status/stopped_at — excluded
// because status carries the 'unknown' sentinel guard (a field-specific
// exception this generic property does not model) and stopped_at is its
// paired dedicated-channel sibling in the pre-#3468 design this comment
// originally described; both get their own pinned coverage in C1 above.
const LOOP_PWU_FIELDS = Object.keys(FIELD_CLASSIFICATION).filter((f) => {
const cls = getFieldClassification(f);
return cls !== null && cls.preservation === 'preserve-when-unchanged' && f !== 'status' && f !== 'stopped_at';
});
test('property: restore fires iff (wired AND non-empty snapshot AND unchanged delta AND postFm differs)', () => {
fc.assert(
fc.property(
fc.constantFrom(...LOOP_PWU_FIELDS),
fc.string({ maxLength: 20 }),
fc.boolean(),
fc.string({ maxLength: 20 }),
fc.boolean(),
fc.boolean(),
(field, snapshotValue, snapshotPresent, postFmValue, deltaChanged, resync) => {
const preFmSnapshot = snapshotPresent ? { [field]: snapshotValue } : {};
const postFm = { [field]: postFmValue };
const delta = { pre: 'source', post: deltaChanged ? 'source-changed' : 'source' };
const r = applyStatePreservation({
preFm: null,
preFmSnapshot,
postFm,
resync,
bodyDeltas: { ...neutralBodyDeltas(), [field]: delta },
...dedicatedNoop,
});
const snapshotUsable = snapshotPresent && snapshotValue.length > 0;
const alreadyCorrect = postFmValue === snapshotValue;
const expectRestore = snapshotUsable && !deltaChanged && !alreadyCorrect;
const expectedValue = expectRestore ? snapshotValue : postFmValue;
if (r.postFm[field] !== expectedValue || r.mutated !== expectRestore) {
throw new Error(
`dispatch mismatch: field=${field} snapshotPresent=${snapshotPresent} ` +
`snapshotValue=${JSON.stringify(snapshotValue)} postFmValue=${JSON.stringify(postFmValue)} ` +
`deltaChanged=${deltaChanged} resync=${resync} expectRestore=${expectRestore} ` +
`got postFm[field]=${JSON.stringify(r.postFm[field])} mutated=${r.mutated}`,
);
}
return true;
},
),
{ seed: 3468, numRuns: 200 },
);
});
});
// ────────────────────────────────────────────────────────────────────────
// Folded from tests/bug-21-state-md-template-frontmatter.test.cjs — consolidation epic #1969 (B8 #1977)

View File

@@ -0,0 +1,566 @@
'use strict';
/**
* 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`.
*
* 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)
*
* 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.
*
* 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
*
* Assertions compare the frozen `REASON` enum values and the `--json`/pure
* function return shapes only — never a substring/regex match on the human
* formatter's prose (CONTRIBUTING.md, "Prohibited: Raw Text Matching on Test
* Outputs").
*/
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { runNode } = require('./helpers/process-seam.cjs');
const { PROBE_TIMEOUT_MS } = require('./helpers/timeouts.cjs');
const guard = require('../scripts/lint-state-write-path-drift.cjs');
const {
REASON,
findSeamBypasses,
findPromptSeamUses,
findPolicyDispatchDrift,
applyRatchet,
loadBaseline,
buildBaselineEntries,
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.
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);
assert.strictEqual(body.ok, true);
assert.deepStrictEqual(body.findings, []);
assert.strictEqual(result.exitCode, 0);
});
});
// ─── 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 ────────────────────────────────────────────
describe('D8 — comments are not drift', () => {
test('guard: comments are not drift', () => {
const text = [
'// writeStateMd(statePath, modified, cwd);',
'/**',
' * writeStateMd(statePath, modified, cwd);',
' */',
'function noop() {}',
].join('\n');
// ADR-3180 Amendment 3's recorded false positive: a `//` line comment
// 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), []);
});
});
// ─── D9/D10: the owner-file exemption is function-scoped, not file-scoped ──
describe('D9 — owner functions are exempt', () => {
test('guard: owner functions are exempt', () => {
assert.ok(SEAM_OWNER_EXEMPT_FUNCTIONS.includes('readModifyWriteStateMd'));
const text = [
'function readModifyWriteStateMd(cwd) {',
' const modified = compute();',
' writeStateMd(statePath, modified, cwd);',
' return modified;',
'}',
].join('\n');
// The seam's own internal plumbing (the I/O wrapper calling the pure
// sync stage) is not a bypass.
assert.deepStrictEqual(findSeamBypasses(SEAM_OWNER_FILE, text), []);
});
});
describe('D10 — the owner file is not exempt', () => {
test('guard: the owner file is not exempt', () => {
// ADR-3408 Decision 5's named gaming route: a whole-FILE exemption on
// the owner is exactly how getMilestoneInfo stayed invisible to an
// earlier drift guard. A call inside any OTHER function in state.cts —
// not one of SEAM_OWNER_EXEMPT_FUNCTIONS — must still be caught.
const text = [
'function patchCore(cwd) {',
' const modified = compute();',
' writeStateMd(statePath, modified, cwd);',
' return modified;',
'}',
].join('\n');
const out = findSeamBypasses(SEAM_OWNER_FILE, text);
assert.strictEqual(out.length, 1);
assert.strictEqual(out[0].line, 3);
});
});
// ─── D11: the prompt layer is in the scan surface ──────────────────────────
describe('D11 — the prompt layer is in the scan surface', () => {
const PROMPT_FILE = 'gsd-core/workflows/example-workflow.md';
test('guard: the prompt layer is in the scan surface', () => {
const text = [
'# Example workflow',
'',
'Run gsd-tools state.patch --field status --value done to record completion directly.',
].join('\n');
const out = findPromptSeamUses(PROMPT_FILE, text);
assert.strictEqual(out.length, 1);
assert.strictEqual(out[0].line, 3);
assert.strictEqual(out[0].symbol, 'prompt-layer-state-write');
});
test('control: the same candidate wrapped in backticks is a mention, not an invocation, and is not reported', () => {
// Proves the detection above is genuinely exercising the code-span
// exclusion, not merely that the fixture happens to score zero.
const text = 'Documentation only: `gsd-tools state.patch --field status --value done`.';
assert.deepStrictEqual(findPromptSeamUses(PROMPT_FILE, text), []);
});
});
// ─── 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
// `getFieldClassification` entirely, so `FIELD_NAME_DISPATCH_RE` (which only
// matches the CALL shape) reported zero violations while the branch shape
// sat in the executor undetected. This section drives the widened detector
// directly against in-memory fixtures, mirroring D2's own "guard: does the
// pure function itself report" pattern.
describe('D14 — field-name-keyed branch comparisons are caught', () => {
test('guard: field !== literal is reported as FIELD_NAME_DISPATCH', () => {
const text = [
'function applyPreserveIfPlaceholder(field, cls, ctx) {',
" if (field !== 'milestone_name') return;",
'}',
].join('\n');
const out = findPolicyDispatchDrift(EXECUTOR_FILE, text);
assert.strictEqual(out.length, 1);
assert.strictEqual(out[0].reason, REASON.FIELD_NAME_DISPATCH);
assert.strictEqual(out[0].line, 2);
assert.strictEqual(out[0].field, 'milestone_name');
});
test('guard: field === literal is reported as FIELD_NAME_DISPATCH', () => {
const text = [
'function applyPreserveWhenUnchanged(field, cls, ctx) {',
" if (field === 'status') return;",
'}',
].join('\n');
const out = findPolicyDispatchDrift(EXECUTOR_FILE, text);
assert.strictEqual(out.length, 1);
assert.strictEqual(out[0].reason, REASON.FIELD_NAME_DISPATCH);
assert.strictEqual(out[0].line, 2);
assert.strictEqual(out[0].field, 'status');
});
test('guard: the reversed literal === field is reported as FIELD_NAME_DISPATCH', () => {
const text = [
'function applyPreserveIfPlaceholder(field, cls, ctx) {',
" if ('milestone' === field) return;",
'}',
].join('\n');
const out = findPolicyDispatchDrift(EXECUTOR_FILE, text);
assert.strictEqual(out.length, 1);
assert.strictEqual(out[0].reason, REASON.FIELD_NAME_DISPATCH);
assert.strictEqual(out[0].line, 2);
assert.strictEqual(out[0].field, 'milestone');
});
test('control: preservation === literal (the CORRECT policy-dispatch shape) is NOT reported', () => {
const text = [
'function applyPreserveAlways(field, cls, ctx) {',
" if (cls.preservation === 'preserve-always') return;",
'}',
].join('\n');
assert.deepStrictEqual(findPolicyDispatchDrift(EXECUTOR_FILE, text), []);
});
test('control: an unrelated variable compared to a literal is NOT reported', () => {
const text = [
'function helper(status, cls, ctx) {',
" if (status !== 'unknown') return;",
'}',
].join('\n');
assert.deepStrictEqual(findPolicyDispatchDrift(EXECUTOR_FILE, text), []);
});
test('control: bracket-indexed field access (ctx.postFm[field]) compared to a non-literal is NOT reported', () => {
const text = [
'function applyPreserveWhenUnchanged(field, cls, ctx) {',
' if (ctx.postFm[field] === snapshot) return;',
'}',
].join('\n');
assert.deepStrictEqual(findPolicyDispatchDrift(EXECUTOR_FILE, text), []);
});
});
// ─── D15: `file` (and other attacker-derived fields) are sanitized AT
// CONSTRUCTION, not just by the human formatter ─────────────────────────────
// 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 —
// 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
// sanitization uniformly.
//
// The two attack codepoints are built via `String.fromCharCode` rather than
// embedded as literal bytes, so this test file's own source never carries a
// live control/bidi codepoint on disk.
describe('D15 — file (and field) values are sanitized at construction', () => {
const RLO = String.fromCharCode(0x202e); // RIGHT-TO-LEFT OVERRIDE (bidi)
const C1_CSI = String.fromCharCode(0x9b); // C1 CONTROL: CSI
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');
const out = findSeamBypasses(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
// exactly what reaches `--json` stdout verbatim (JSON.stringify
// neutralizes C0 but NOT C1 or bidi codepoints, which is why
// 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', () => {
const text = 'Run gsd-tools state.patch --field status --value done to record completion directly.';
const out = findPromptSeamUses(ATTACK_FILE, text);
assert.strictEqual(out.length, 1);
assert.strictEqual(out[0].file, ESCAPED_FILE);
assert.ok(!out[0].file.includes(RLO));
assert.ok(!out[0].file.includes(C1_CSI));
});
test('findPolicyDispatchDrift: filename AND the field literal are both escaped', () => {
const text = [" if (field === 'status" + RLO + C1_CSI + "') return;"].join('\n');
const out = findPolicyDispatchDrift(ATTACK_FILE, text);
assert.strictEqual(out.length, 1);
assert.strictEqual(out[0].file, ESCAPED_FILE);
assert.strictEqual(out[0].field, 'status\\u202e\\x9b');
assert.ok(!out[0].field.includes(RLO));
assert.ok(!out[0].field.includes(C1_CSI));
});
});

View File

@@ -25,6 +25,14 @@ const workstreamInventory = require('../gsd-core/bin/lib/workstream-inventory.cj
// Phase 12 (#3310, ADR-3180 §8.4 rule 3): `cmdStateValidate`'s `warnings` are
// now `Diagnostic[]` (S0NN codes), not bare strings, and `drift` is gone.
const { SEVERITY } = require('../gsd-core/bin/lib/health-diagnostic-types.cjs');
// #3468 matrix B8: distinguishes a controlled, structured CLI failure (an
// `error()` call, which always emits plain text even under --json-errors —
// see `#2979` in tests/cli-exit.test.cjs) from an uncaught internal crash
// (any non-ExitError throw, which under --json-errors emits a JSON envelope
// carrying `reason: ERROR_REASON.SDK_FAIL_FAST`). The §8.2 invariant throw is
// exactly the latter shape, so this is the structured, non-prose signal B8
// asserts against.
const { ERROR_REASON } = require('../gsd-core/bin/lib/io.cjs');
/** First `Diagnostic` in `output.warnings` carrying the given S0NN code, or `undefined`. */
function findWarning(output, code) {
@@ -13541,3 +13549,165 @@ const HEX_RE = /^[0-9a-f]{4,40}$/i;
assert.strictEqual(r.commits_behind, 0);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// #3468 matrix section B, rows B7/B8 — ADR-3408 §8.2's bright line, exercised
// through the REAL production write path rather than a hand-built
// applyStatePreservation input (CONTRIBUTING.md § Fixture provenance #2371:
// a test constructing its own convenient input proves a property no shipping
// caller exercises).
// ─────────────────────────────────────────────────────────────────────────────
describe('#3468 B7: the production caller wires every declared preserve-when-unchanged row', () => {
let tmpDir;
let statePath;
beforeEach(() => {
tmpDir = createTempProject('gsd-3468-b7-');
statePath = path.join(tmpDir, '.planning', 'STATE.md');
});
afterEach(() => {
cleanup(tmpDir);
});
test('B7: readModifyWriteStateMd never throws the §8.2 invariant on a normal write', () => {
// The real caller (state.cts:2744-2795, the ONLY call site of
// applyStatePreservation) computes and wires bodyDeltas for every
// declared preserve-when-unchanged row. Driving a normal transform
// through the real function — not a hand-built applyStatePreservation
// call — is what proves B1's throw can never fire in production.
assert.doesNotThrow(() => {
stateLib.readModifyWriteStateMd(
statePath,
(content) => `${content}\n<!-- #3468 B7 probe -->\n`,
tmpDir,
);
});
// Also exercise the resync:false (body-only) branch — a second,
// independently-reachable call shape into the same pipeline.
assert.doesNotThrow(() => {
stateLib.readModifyWriteStateMd(
statePath,
(content) => `${content}\n<!-- #3468 B7 probe 2 -->\n`,
tmpDir,
{ resync: false },
);
});
});
});
describe('#3468 B8: a drifted / malformed / unparseable STATE.md never reaches the invariant throw (§8.2 bright line)', () => {
let tmpDir;
let statePath;
beforeEach(() => {
tmpDir = createTempProject('gsd-3468-b8-');
statePath = path.join(tmpDir, '.planning', 'STATE.md');
});
afterEach(() => {
cleanup(tmpDir);
});
// Each fixture replaces the fixture-generated STATE.md with a document that
// is drifted, malformed, or unparseable in a distinct way. None of these
// are internal invariant violations — they are exactly the "ordinary,
// expected user-document state" ADR-3408 §8.5 names, so the command must
// never surface the §8.2 invariant (an uncaught internal Error).
const fixtures = [
{
name: 'drifted: frontmatter current_phase disagrees with the body Phase: line',
content: [
'---',
'gsd_state_version: 1.0',
'current_phase: "7"',
'status: executing',
'---',
'',
'# Project State',
'',
'## Current Position',
'',
'Phase: 2 (Stale Name) — EXECUTING',
'Plan: 1 of 3',
'Status: Executing Phase 2',
'',
].join('\n'),
},
{
name: 'malformed: frontmatter fields carry the wrong YAML type',
content: [
'---',
'gsd_state_version: 1.0',
'status: 42',
'progress: "not-an-object"',
'current_phase_name: [Unexpected, Array]',
'---',
'',
'# Project State',
'',
'## Current Position',
'',
'Phase: 2 (Some Phase) — EXECUTING',
'Plan: 1 of 3',
'Status: Executing Phase 2',
'',
].join('\n'),
},
{
name: 'unparseable: frontmatter fence opens but never closes',
content: [
'---',
'gsd_state_version: 1.0',
'status: executing',
'',
'# Project State (frontmatter never terminated above)',
'',
'## Current Position',
'',
'Phase: 2 (Some Phase) — EXECUTING',
'Plan: 1 of 3',
'Status: Executing Phase 2',
'',
].join('\n'),
},
];
for (const fixture of fixtures) {
test(`B8: ${fixture.name}`, () => {
fs.writeFileSync(statePath, fixture.content);
const result = runGsdTools(['state', 'sync', '--json-errors'], tmpDir);
if (result.success) {
assert.doesNotThrow(
() => JSON.parse(result.output),
`${fixture.name}: success output must be well-formed JSON; got: ${result.output}`,
);
return;
}
// A non-zero exit is allowed (a drifted document may be a legitimate
// domain-level failure) — but it must be a CONTROLLED failure. Under
// --json-errors, an ExitError (a deliberate error() call) always
// writes PLAIN TEXT to stderr (never JSON — see tests/cli-exit.test.cjs
// #2979), while an uncaught internal Error (what the §8.2 invariant
// throw would be, since it is deliberately never caught by a discriminator
// per ADR-3408 §8.2's "Rejected: Return a ScopedResult") is the ONLY
// path that emits the JSON envelope with reason: SDK_FAIL_FAST. So: if
// stderr parses as that envelope, the command crashed on an uncaught
// internal error — the exact bright line B8 forbids.
let structured = null;
try { structured = JSON.parse(result.error); } catch { /* plain text — a controlled ExitError, expected */ }
if (structured) {
assert.notStrictEqual(
structured.reason,
ERROR_REASON.SDK_FAIL_FAST,
`${fixture.name}: command crashed on an uncaught internal error instead of a controlled failure — ` +
`this is the §8.2 invariant bright line: a user document must never trigger it. stderr: ${result.error}`,
);
}
});
}
});