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)