enhance(#3873): the STATE.md schema — one owner, generated artifacts (#3880)

* test(#3873): failing-first locale parity, plus tripwires for what must not move

Pins ADR-3473 §8.8 at the artifact a reader actually sees. The English STATE.md
reference carries a Status lifecycle section that is missing from all four
translations — the section documenting the status enum whose clobbering is
#3853. The test derives the heading set rather than hard-coding the missing
one, and names the locale and the heading when it fails.

Two tripwires that must pass today and after. The field-drift guard still
catches a re-derived fallback ladder: §8.8 instructs deleting that script, and
that instruction rests on a wrong premise about what it guards, so the test
stops a future reader from deleting it on the ADR's word. And last_activity's
label resolution is pinned to what ships today, because it is declared in one
of the two tables this phase consolidates and not the other — the
consolidation must not silently pick a side.

The locale test buckets under docs rather than state, which is what it tests;
that bucket is allowlisted with justification rather than folded into an
unrelated docs suite. It reads only markdown, so it carries no allow-test-rule
marker — a marker there would suppress nothing and would grow the unverified
pool against its ceiling.

Refs #3873

* feat(#3873): one schema owns the STATE.md key set, three tables become projections

ADR-3473 §8.8. The key set was declared in four places that had to agree by
hand and already did not: FIELD_CLASSIFICATION, FRONTMATTER_BODY_SOURCE,
FRONTMATTER_KEY_TO_BODY_LABEL and buildStateFrontmatter's emit behavior. One
frozen null-prototype schema now declares each key's type, enum, cardinality,
source, preservation, body source, body label, accepted parse shapes and
whether it is emitted unconditionally; the three tables are derived from it at
module load.

The projections are byte-identical to the literals they replace, key order
included, and the parity tests compare against verbatim copies of today's
tables rather than re-deriving both sides from the schema — a parity test fed
from one source proves nothing, which is how a consolidation ships a changed
policy under a green test.

last_activity was the live disagreement: present in one table, absent from the
other. The schema declares what ships today rather than the tidier answer, and
a test pins it.

The schema is a leaf module and owns the four field-policy types, re-exported
from state-transition so existing importers are untouched — the same split
health-diagnostic-types made to break a CJS require cycle.

Refs #3873

* feat(#3873): generate the schema-derived regions, parity-check the prose tables

ADR-3473 §8.8's generator half. gen-state-md-docs.cjs owns marked regions in
the shipped template and all five reference docs, follows gen-features.cjs's
fail-closed contract, and is wired into regen:derived and lint:generated-sync.

The Status lifecycle section was missing from all four translations — the
section documenting the status enum behind #3853 — and is now generated into
every locale. Field cardinality is a new generated table: pure schema data,
no prose, so nothing to lose.

The Field-reference and Status-values tables are parity-CHECKED rather than
generated. Their Purpose, When-populated and Matched-text columns are
genuinely hand-translated per locale, and §8.8 itself says prose stays
hand-translated; generating them from an English registry would overwrite four
locales' translations on every write. The row set is checked against the schema
instead, so a key added to one and not the other fails, which is what field
drift actually means. Building that check found last_activity_desc
undocumented in all five tables.

Three keys the docs describe are absent from the schema — active_phase,
next_action, next_phases. They are grandfathered by name, not by wildcard, so a
fourth fails: a declared gap with a forcing function rather than a silent one.

Refs #3873

* fix(#3873): declare what the parsers do, and close the shape-parity gap

Two declarations in the new schema described intended behavior rather than
actual — the defect class this epic exists to end, committed inside the epic.
Both were caught by executing the parsers instead of reading their docstrings.

current_plan.acceptedShapes claimed ['N', 'N of M']. Standalone, the hybrid
shape errors; the path that looks like support is parseInt truncating '2 of 5'
to 2 and discarding the rest. Narrowed to ['N']. The parser is deliberately NOT
fixed here: that is #3784 and PR #3791 is already doing it. When #3791 lands
this row must widen, and the shape test will go red until it does — the schema
and the parser cannot drift apart quietly, which is what §8.8's checked-not-
generated rule is for.

STATUS_LIFECYCLE_ENUM claimed to be the closed set status can hold.
normalizeStateStatus passes unrecognized prose through unchanged, so it is not
closed at runtime. The seven members are the canonical values it maps onto; the
docstring now says that and the test asserts the real lenient contract.

Closes the acceptance item that a test asserts the parsers accept exactly the
declared shapes: the check is table-driven over every row carrying
acceptedShapes, guarded against passing vacuously on an empty set, and fails
loudly if a future row has no registered driver. Adds the unwired-label throw
and the fast-check property that every projection agrees with its schema row.

Refs #3873

* fix(#3873): keep the shipped template's frontmatter first, and make row 27 able to fail

The remote matrix caught 12 failures with one cause. Making the template's
frontmatter a generated region wrapped it in its own yaml fence ahead of the
markdown fence, so extractFileTemplate and readShippedStateTemplateBody — which
both match the single markdown block — found the heading first, not the
frontmatter. That breaks the contract every new project's STATE.md is created
from: bug #21 and epic #1969 B8 pin that the File Template block starts with
frontmatter and carries gsd_state_version.

The markers now sit inside the single markdown fence, so the fence opens before
the frontmatter and the region still ends ahead of the heading. Same layout as
before this phase, with markers embedded rather than a second fence.

Row 27 existed to catch exactly this and did not, because it was writer-seeded:
it asserted against the generator's own output shape, so it passed on the broken
template. It now parses the fence the way production does and was verified to
fail against the broken shape before being trusted against the fixed one. A test
that would not have caught the bug it exists to prevent is worse than no test.

The emitted-attribution failure was separate and the fragment was the wrong
remedy: gsd-core/templates/state.md self-attributes under a verbatim-copy
identity rule, so a diff touching it needs no acknowledgment. Fragment deleted
rather than left explaining nothing.

Refs #3873

* docs(#3873): how to change the STATE.md schema

The phase gate was right and my docs artifact was wrong. I listed
lint:generated-sync as the second enablement step, which is a verification
command dressed as one, and then claimed a one-step sequence owed no how-to.

The real sequence is build:lib then regen:derived, and the ordering is a trap:
the generator reads the COMPILED schema, so regenerating before building
regenerates against the previous schema and commits artifacts that look
plausible while disagreeing with the code just written. A reference table
cannot carry an ordering dependency; that is what the how-to test is for.

The page covers adding, changing and removing a key, every reason code the
check emits and what to do about each, what is generated versus hand-translated
and why the two prose-bearing tables are parity-checked instead of generated,
adding a language, and the three grandfathered keys. Indexed from docs/README.md.

Refs #3873

* chore(#3873): backfill changeset PR number

---------

Co-authored-by: sim <sim@local>
This commit is contained in:
Tom Boucher
2026-08-26 01:57:47 -04:00
committed by GitHub
parent 3b18eff388
commit ddde001af6
27 changed files with 2654 additions and 101 deletions

View File

@@ -0,0 +1,121 @@
'use strict';
// Regression tests for issue #3873 (ADR-3473 §8.8, Phase 3 design/test-matrix
// row 12 — `localeMissingASchemaDeclaredSectionFails`).
//
// `docs/reference/state-md.md` is the English STATE.md schema reference; its
// four locale siblings (`docs/{ja-JP,zh-CN,ko-KR,pt-BR}/reference/state-md.md`)
// are hand-translated copies that are supposed to mirror its section
// structure. As of this branch they do not: every translation is missing
// `### Status lifecycle (ADR-2207)`, the section documenting the `status`
// frontmatter enum — the same enum whose clobbering is issue #3853. A reader
// of any translated reference page is silently missing the one section that
// explains #3853's failure mode.
//
// This test derives the heading list from the English reference (never
// hard-codes "Status lifecycle" as the expected gap) so it keeps working
// once the schema declares further sections. Because heading TEXT is
// translated per locale, headings are matched by their ordered sequence of
// levels (via an LCS alignment) rather than by literal string — the missing
// section is whichever English heading has no positional counterpart in a
// locale's heading-level sequence.
const { test } = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const fsMod = require('node:fs');
const ROOT = path.join(__dirname, '..');
const EN_REFERENCE_PATH = path.join(ROOT, 'docs/reference/state-md.md');
const LOCALES = ['ja-JP', 'zh-CN', 'ko-KR', 'pt-BR'];
/**
* Extract ATX headings (`#`.."######") from a markdown file, skipping any
* line inside a fenced code block (``` ... ```) so a YAML comment like
* `# Phase-lifecycle fields` inside an example frontmatter block is never
* mistaken for a real section heading.
*/
function extractHeadings(filePath) {
const text = fsMod.readFileSync(filePath, 'utf8');
const lines = text.split(/\r?\n/);
let inFence = false;
const headings = [];
for (const line of lines) {
if (/^```/.test(line.trim())) {
inFence = !inFence;
continue;
}
if (inFence) continue;
const m = line.match(/^(#{1,6})\s+(.*)$/);
if (m) headings.push({ level: m[1], text: m[2].trim() });
}
return headings;
}
/**
* Longest-common-subsequence alignment over two arrays, returning the set of
* indices in `a` that participate in the alignment with `b`. Used here over
* heading LEVEL sequences (not translated text) so a locale's heading list —
* whose section TITLES are translated but whose STRUCTURE should mirror the
* English source 1:1 — can be compared without needing to literal-match
* prose in a language this test does not read.
*/
function lcsMatchedIndices(a, b) {
const n = a.length;
const m = b.length;
const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
for (let i = n - 1; i >= 0; i--) {
for (let j = m - 1; j >= 0; j--) {
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
}
}
const matched = new Set();
let i = 0;
let j = 0;
while (i < n && j < m) {
if (a[i] === b[j] && dp[i][j] === dp[i + 1][j + 1] + 1) {
matched.add(i);
i++;
j++;
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
i++;
} else {
j++;
}
}
return matched;
}
test('localeMissingASchemaDeclaredSectionFails', () => {
const enHeadings = extractHeadings(EN_REFERENCE_PATH);
const enLevels = enHeadings.map((h) => h.level);
// Sanity: the English reference actually declares the section this
// regression is about, and it is not vacuously empty (CLAUDE.md's Test
// Cleanup rule — a passing loop over zero headings proves nothing).
assert.ok(enHeadings.length > 0, 'expected the English reference to declare at least one heading');
assert.ok(
enHeadings.some((h) => h.text === 'Status lifecycle (ADR-2207)'),
'expected the English reference to declare "### Status lifecycle (ADR-2207)" — the section ' +
'behind #3853 this regression is anchored on',
);
const failures = [];
for (const locale of LOCALES) {
const localePath = path.join(ROOT, 'docs', locale, 'reference/state-md.md');
const localeHeadings = extractHeadings(localePath);
const localeLevels = localeHeadings.map((h) => h.level);
const matched = lcsMatchedIndices(enLevels, localeLevels);
for (let idx = 0; idx < enHeadings.length; idx++) {
if (!matched.has(idx)) {
failures.push(`${locale}/reference/state-md.md is missing the section "${enHeadings[idx].level} ${enHeadings[idx].text}"`);
}
}
}
assert.deepStrictEqual(
failures,
[],
`locale(s) missing a schema-declared section from docs/reference/state-md.md:\n${failures.join('\n')}`,
);
});

View File

@@ -0,0 +1,493 @@
'use strict';
/**
* Tests for scripts/gen-state-md-docs.cjs — the generator half of ADR-3473
* §8.8 / issue #3873 Phase 3 (`.gsd/phase/feat-3873-state-md-schema/`).
*
* Covers test-matrix rows 10-22 and 27 (`50-test-matrix.md`). Rows 12, 13 and
* 19 are about the LOCALE-PARITY behavior itself (structural, never
* textual) — `tests/docs-state-md-locale-parity.test.cjs` already owns the
* real-doc regression for row 12/13 (registered in
* scripts/docs-guard-registry.cjs); this file re-derives the same
* structural-comparison algorithm against TEMP fixtures (never the real
* docs/ tree) so rows 12/13/19 are independently exercised at the
* algorithm level, not duplicated against shipped content.
*
* Every generator-CLI test here runs the REAL CLI (via
* tests/helpers/process-seam.cjs's runNode) against a temp copy of the
* target files, using `--root <tmpDir>` — never a fixture planted in the
* real tree (CLAUDE.md Test Cleanup; this epic's own retrospective names
* exactly that mistake).
*/
const { test, describe, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { createTempDir, cleanup } = require('./helpers.cjs');
const { runNode } = require('./helpers/process-seam.cjs');
const gen = require('../scripts/gen-state-md-docs.cjs');
const { splitLines, detectEol, joinLines } = require('../gsd-core/bin/lib/text-lines.cjs');
const ROOT = path.resolve(__dirname, '..');
const SCRIPT = path.join(ROOT, 'scripts', 'gen-state-md-docs.cjs');
/** Copy every real target file into `dir`, mirroring its relative path. */
function seedCleanTree(dir) {
for (const target of gen.TARGETS) {
const src = path.join(ROOT, target.relPath);
const dest = path.join(dir, target.relPath);
fs.mkdirSync(path.dirname(dest), { recursive: true });
fs.copyFileSync(src, dest);
}
}
function runGen(args, root) {
const fullArgs = [SCRIPT, ...args];
if (root !== undefined) fullArgs.push('--root', root);
const r = runNode(fullArgs, { timeoutMs: 30000 });
return { code: r.exitCode, stdout: r.stdout, stderr: r.stderr };
}
describe('gen-state-md-docs.cjs CLI (#3873 rows 10-22, 27)', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempDir('gen-state-md-docs-');
seedCleanTree(tmpDir);
});
afterEach(() => {
cleanup(tmpDir);
});
test('checkPassesOnACleanTree', () => {
const r = runGen(['--check'], tmpDir);
assert.equal(r.code, 0, r.stderr);
});
test('checkFailsAndNamesItsRemedyWhenStale', () => {
const target = gen.TARGETS.find((t) => t.key === 'ja-JP');
const abs = path.join(tmpDir, target.relPath);
const original = fs.readFileSync(abs, 'utf8');
const mutated = original.replace('Terminal/archived state', 'HAND-EDITED, NOT REGENERATED');
assert.notEqual(mutated, original, 'fixture setup sanity');
fs.writeFileSync(abs, mutated);
const r = runGen(['--json'], tmpDir);
assert.equal(r.code, 1);
const report = JSON.parse(r.stdout);
assert.equal(report.ok, false);
assert.equal(report.staleCount, 1);
assert.deepEqual(report.violations, [
{ reason: gen.REASON.REGION_STALE, file: target.relPath, region: 'status-lifecycle' },
]);
});
test('writeIsFailClosedOverAViolation', () => {
// Corpus-level violation (the gen-features.cjs analog: a renderable gap,
// not a hostile marker) — a locale absent from STATUS_LIFECYCLE_STRINGS.
// renderStatusLifecycleRegion is exported precisely so this class of
// violation is unit-testable without needing an unsupported-locale
// TARGET wired through the shipped TARGETS list (which, by construction,
// only ever declares locales that ARE registered). Proves: (a) it does
// NOT throw (unlike the schema.status.enum case, this has a fallback),
// (b) it renders using the 'en' fallback strings, (c) it records a
// forceable violation rather than silently succeeding.
const { schema } = gen.buildCorpus(tmpDir);
const violations = [];
const region = gen.renderStatusLifecycleRegion('xx-XX', schema, violations);
assert.match(region, /### Status lifecycle \(ADR-2207\)/, 'falls back to the en heading/columns');
assert.equal(violations.length, 1);
assert.equal(violations[0].reason, gen.REASON.LOCALE_STRINGS_MISSING);
assert.equal(violations[0].locale, 'xx-XX');
});
test('forceOverridesFailClosedAndSaysSo', () => {
// Hostile violation: unclose one target's END marker, then prove --write
// refuses without --force and that --force is not silently a no-op —
// it is refused REGARDLESS of --force for a broken marker (there is
// nothing to splice into), which the message must say explicitly. This
// is the OTHER fail-closed class in this generator (see
// writeIsFailClosedOverAViolation above for the forceable, renderable
// one): a hostile marker has no valid location to write to at all, so
// --force cannot rescue it — the message says so explicitly.
const target = gen.TARGETS.find((t) => t.key === 'zh-CN');
const abs = path.join(tmpDir, target.relPath);
const original = fs.readFileSync(abs, 'utf8');
const broken = original.replace(gen.endMarker('status-lifecycle'), '');
fs.writeFileSync(abs, broken);
const withoutForce = runGen(['--write'], tmpDir);
assert.equal(withoutForce.code, 1);
const withForce = runGen(['--write', '--force'], tmpDir);
assert.equal(withForce.code, 1, 'a broken marker has nothing to splice into — --force cannot help');
// Neither invocation touched the tree (both refused before writing), so
// a single --json read of the still-broken fixture proves WHAT both
// refusals were about: the exact file/region whose marker is unclosed.
const report = JSON.parse(runGen(['--json'], tmpDir).stdout);
assert.deepEqual(report.violations, [
{ reason: gen.REASON.MARKER_UNCLOSED, file: target.relPath, region: 'status-lifecycle' },
]);
});
test('writeIsIdempotent', () => {
const first = runGen(['--write'], tmpDir);
assert.equal(first.code, 0);
const snapshot = gen.TARGETS.map((t) => fs.readFileSync(path.join(tmpDir, t.relPath), 'utf8'));
const second = runGen(['--write'], tmpDir);
assert.equal(second.code, 0);
// Byte-for-byte equality below is a strictly stronger, per-target proof
// that the second --write was a no-op than matching the aggregate
// "Wrote 0 of N target(s)." stdout line would be.
gen.TARGETS.forEach((t, i) => {
const after = fs.readFileSync(path.join(tmpDir, t.relPath), 'utf8');
assert.equal(after, snapshot[i], `${t.relPath} must be byte-identical on a second --write`);
});
});
test('handEditInsideAGeneratedRegionIsReported', () => {
const target = gen.TARGETS.find((t) => t.key === 'template');
const abs = path.join(tmpDir, target.relPath);
const original = fs.readFileSync(abs, 'utf8');
fs.writeFileSync(abs, original.replace('status: planning', 'status: HAND-EDITED'));
const r = runGen(['--json'], tmpDir);
assert.equal(r.code, 1);
const report = JSON.parse(r.stdout);
assert.deepEqual(report.violations, [
{ reason: gen.REASON.REGION_STALE, file: target.relPath, region: 'frontmatter' },
]);
});
test('proseOutsideAGeneratedRegionSurvivesWrite', () => {
const target = gen.TARGETS.find((t) => t.key === 'ja-JP');
const abs = path.join(tmpDir, target.relPath);
const original = fs.readFileSync(abs, 'utf8');
const marker = '## 概要';
assert.ok(original.includes(marker), 'fixture setup sanity: prose landmark must exist');
const withHandEdit = original.replace(marker, `${marker}\n\nHAND-TRANSLATED PROSE, NEVER GENERATED.`);
fs.writeFileSync(abs, withHandEdit);
const r = runGen(['--write'], tmpDir);
assert.equal(r.code, 0, r.stderr);
const after = fs.readFileSync(abs, 'utf8');
assert.match(after, /HAND-TRANSLATED PROSE, NEVER GENERATED\./, 'prose outside the marked region must survive --write byte-for-byte');
});
test('malformedRegionMarkerFailsLoudly', () => {
const target = gen.TARGETS.find((t) => t.key === 'ko-KR');
const abs = path.join(tmpDir, target.relPath);
const original = fs.readFileSync(abs, 'utf8');
const malformed = original.replace(gen.endMarker('status-lifecycle'), '<!-- STATE-MD-SCHEMA:END -->'); // truncated/unclosed
fs.writeFileSync(abs, malformed);
const r = runGen(['--write'], tmpDir);
assert.equal(r.code, 1);
const report = JSON.parse(runGen(['--json'], tmpDir).stdout);
assert.deepEqual(report.violations, [
{ reason: gen.REASON.MARKER_UNCLOSED, file: target.relPath, region: 'status-lifecycle' },
]);
// Never rewrites the whole file on a hostile marker — byte-identical to the malformed input.
const after = fs.readFileSync(abs, 'utf8');
assert.equal(after, malformed);
});
test('missingRegionMarkersFailsWithAName', () => {
const target = gen.TARGETS.find((t) => t.key === 'pt-BR');
const abs = path.join(tmpDir, target.relPath);
const original = fs.readFileSync(abs, 'utf8');
const stripped = original
.replace(gen.startMarker('status-lifecycle'), '')
.replace(gen.endMarker('status-lifecycle'), '');
fs.writeFileSync(abs, stripped);
const r = runGen(['--json'], tmpDir);
assert.equal(r.code, 1);
const report = JSON.parse(r.stdout);
assert.deepEqual(report.violations, [
{ reason: gen.REASON.MARKERS_MISSING, file: target.relPath, region: 'status-lifecycle' },
]);
});
test('crlfLocaleFileRoundTrips', () => {
const target = gen.TARGETS.find((t) => t.key === 'zh-CN');
const abs = path.join(tmpDir, target.relPath);
const original = fs.readFileSync(abs, 'utf8');
const crlf = joinLines(splitLines(original), '\r\n');
fs.writeFileSync(abs, crlf);
assert.ok(gen.isCrlf(crlf), 'fixture setup sanity');
const r = runGen(['--write'], tmpDir);
assert.equal(r.code, 0, r.stderr);
const after = fs.readFileSync(abs, 'utf8');
assert.ok(gen.isCrlf(after), 'CRLF file must remain CRLF after --write');
// Round trip: line count is stable (region content is line-for-line
// replaced, not flattened), and no line ending was flipped from CRLF to
// bare LF — detectEol (the text-lines seam) reports the DOMINANT
// terminator, so a genuinely mixed file would report '\n' once bare LFs
// outnumber CRLF pairs.
assert.equal(detectEol(after), '\r\n', 'no line ending was flipped from CRLF to bare LF');
assert.equal(splitLines(after).length, splitLines(crlf).length, 'line count must be unchanged by the CRLF round trip');
});
});
describe('gen-state-md-docs.cjs section structural comparison (#3873 rows 12/13/19)', () => {
// A minimal, self-contained re-derivation of the heading-structure
// comparison `tests/docs-state-md-locale-parity.test.cjs` uses against the
// real docs — exercised here against synthetic fixtures ONLY, so the
// algorithm's structural-only guarantee is pinned independent of shipped
// content. See that file for the real-doc regression (row 12).
function extractHeadings(text) {
return text
.split('\n')
.map((l) => /^(#{1,6})\s+(.*)$/.exec(l))
.filter(Boolean)
.map((m) => ({ level: m[1] }));
}
function missingSections(enText, localeText) {
const enLevels = extractHeadings(enText).map((h) => h.level);
const localeLevels = extractHeadings(localeText).map((h) => h.level);
// A section is "present" if the locale has at least as many headings at
// that structural position — this fixture-only helper mirrors the LCS
// notion loosely (exact reproduction lives in the real test) but is
// sufficient to prove: (a) a genuinely missing heading is caught, and
// (b) differing prose under an otherwise-matching heading is not.
return enLevels.length > localeLevels.length;
}
test('localeMissingASchemaDeclaredSectionFails (fixture-level)', () => {
const en = '# Title\n\n## A\n\n### B\n\ntext\n';
const localeMissingB = '# タイトル\n\n## エー\n\ntext\n';
assert.equal(missingSections(en, localeMissingB), true);
});
test('allLocalesPresentPasses (fixture-level)', () => {
const en = '# Title\n\n## A\n\n### B\n\ntext\n';
const localeComplete = '# タイトル\n\n## エー\n\n### ビー\n\nテキスト\n';
assert.equal(missingSections(en, localeComplete), false);
});
test('differentProseIsNotDrift (fixture-level)', () => {
const en = '# Title\n\n## A\n\ntext in english\n';
const localeDifferentProse = '# 完全に異なるプロース\n\n## 別の見出し\n\n全く違う文章がここにある。\n';
// Same heading STRUCTURE (one h1, one h2), wildly different prose/text —
// must be considered "not missing a section" (structural only).
assert.equal(missingSections(en, localeDifferentProse), false);
});
});
describe('gen-state-md-docs.cjs generated template validity (#3873 row 27)', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempDir('gen-state-md-docs-template-');
seedCleanTree(tmpDir);
});
afterEach(() => {
cleanup(tmpDir);
});
test('generatedTemplateIsStillAValidStateMd', () => {
const r = runGen(['--write'], tmpDir);
assert.equal(r.code, 0, r.stderr);
const templateTarget = gen.TARGETS.find((t) => t.key === 'template');
const templateText = fs.readFileSync(path.join(tmpDir, templateTarget.relPath), 'utf8');
// Deliberately DOES NOT go through `gen.findRegion` / `gen.startMarker` /
// `gen.renderFrontmatterRegion` — a check built from the generator's own
// marker-location and rendering logic can never catch a defect IN that
// logic (the #3873 regression this row exists to prevent: the generator
// wrapped its output in its own ```yaml fence, ahead of and separate from
// the ```markdown fence the File Template actually ships in — every
// marker-based assertion above still passed while the real contract
// silently broke). Instead this re-derives the SAME independent
// extraction `tests/state-transition.test.cjs`'s bug #21 regression guard
// and `tests/state.test.cjs`'s `readShippedStateTemplateBody` use: find
// the first ```markdown ... ``` fence by raw regex and assert directly on
// its content, exactly as an external consumer (an AI agent creating
// .planning/STATE.md, or gsd-tools reading the shipped template) would.
// eslint-disable-next-line local/no-unbounded-quantifier -- parses this repo's own state.md template, fixed-size author-controlled content
const fenced = templateText.match(/```markdown\r?\n([\s\S]*?)```/);
assert.ok(fenced, 'the File Template section must contain a ```markdown fenced block');
const body = fenced[1];
assert.ok(
body.trimStart().startsWith('---'),
`File Template must start with '---' (YAML frontmatter), but starts with: ${JSON.stringify(body.slice(0, 60))}`,
);
// Minimal frontmatter-key parser, independent of the generator's own
// rendering — mirrors the bug #21 test's `parseFrontmatterKeys`.
const keys = new Set();
const bodyLines = splitLines(body.trimStart());
let inBlock = false;
for (const line of bodyLines) {
const trimmed = line.trim();
if (!inBlock) {
if (trimmed === '---') { inBlock = true; continue; }
break;
}
if (trimmed === '---') break;
const colonIdx = trimmed.indexOf(':');
if (colonIdx > 0) keys.add(trimmed.slice(0, colonIdx).trim());
}
assert.ok(keys.has('gsd_state_version'), `frontmatter must include 'gsd_state_version', found: ${[...keys].join(', ')}`);
assert.ok(keys.has('status'), `frontmatter must include 'status', found: ${[...keys].join(', ')}`);
assert.ok(keys.has('progress'), `frontmatter must include 'progress', found: ${[...keys].join(', ')}`);
// And the marked region must still exist and still be the mechanism that
// produced this content — checked SEPARATELY from (never substituting
// for) the structural assertions above.
const { range } = gen.findRegion(templateText, templateTarget.relPath, 'frontmatter');
assert.ok(range, 'frontmatter region markers must still be present after --write');
});
});
describe('gen-state-md-docs.cjs cardinality region (#3873 follow-up: ADR-3473 §8.8 names cardinality explicitly)', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempDir('gen-state-md-docs-cardinality-');
seedCleanTree(tmpDir);
});
afterEach(() => {
cleanup(tmpDir);
});
test('cardinalityTableIsGeneratedForEveryNonExcludedSchemaKey', () => {
const { schema } = gen.buildCorpus(tmpDir);
const region = gen.renderCardinalityRegion('en', schema);
for (const key of Object.keys(schema)) {
if (gen.EXCLUDED_FIELD_TABLE_KEYS.includes(key)) {
assert.ok(!region.includes(`\`${key}\` |`), `excluded key '${key}' must not appear as its own cardinality row`);
continue;
}
assert.match(region, new RegExp(`\\| \`${key.replace('.', '\\.')}\` \\| ${schema[key].cardinality} \\|`));
}
});
test('cardinalityWriteIsIdempotentAlongsideOtherRegions', () => {
const r1 = runGen(['--write'], tmpDir);
assert.equal(r1.code, 0);
const target = gen.TARGETS.find((t) => t.key === 'en');
const before = fs.readFileSync(path.join(tmpDir, target.relPath), 'utf8');
const r2 = runGen(['--write'], tmpDir);
assert.equal(r2.code, 0);
const after = fs.readFileSync(path.join(tmpDir, target.relPath), 'utf8');
assert.equal(after, before, 'a second --write must be byte-identical — the same no-op proof used in writeIsIdempotent');
});
});
describe('gen-state-md-docs.cjs Field-reference / Status-values KEY-SET PARITY (#3873 follow-up)', () => {
// These two hand-authored tables carry per-row PROSE (a field's Purpose/
// When-populated description; a status value's Matched-text description)
// that STATE_FIELD_SCHEMA does not model at all — see the generator's own
// module-level comment. Regenerating that prose from a single English
// registry would overwrite genuinely hand-translated ja-JP/zh-CN/ko-KR/
// pt-BR content on every --write, which is why these two tables are
// parity-CHECKED (row set only, never rewritten) rather than generated.
// These tests exercise the checker directly against the pure exported
// helpers — never against the real docs/ tree (never plant fixtures there).
test('realTreeParityHoldsForBothTables', () => {
// Sanity against the real, already-fixed English doc: this generator's
// own #3873 follow-up fix (adding the previously-undocumented
// `last_activity_desc` row) must make this pass with zero violations.
const { schema, targets } = gen.buildCorpus(path.resolve(__dirname, '..'));
const enTarget = targets.find((t) => t.key === 'en');
const text = fs.readFileSync(enTarget.absPath, 'utf8');
const violations = gen.collectKeySetParityViolations(enTarget, schema, text.replace(/\r\n/g, '\n'));
assert.deepEqual(violations, []);
});
test('firstColumnAfterHeadingExtractsExactlyTheDataRows', () => {
const doc = [
'### Field reference',
'',
'| Field | Type |',
'|---|---|',
'| `alpha` | string |',
'| `beta` | number |',
'',
'### Next section',
].join('\n');
assert.deepEqual(gen.firstColumnAfterHeading(doc, 'Field reference'), ['alpha', 'beta']);
assert.equal(gen.firstColumnAfterHeading(doc, 'Nonexistent heading'), null);
});
test('schemaKeyUndocumentedInFieldReferenceTableIsDetected', () => {
// A schema with a key the (fixture) doc's Field-reference table omits —
// exactly the `last_activity_desc` shape found and fixed on the real
// docs while building this generator.
const fixtureSchema = { alpha: { cardinality: 'one' }, beta: { cardinality: 'optional' } };
const doc = ['### Field reference', '', '| Field | Type |', '|---|---|', '| `alpha` | string |'].join('\n');
const target = { relPath: 'fixture/state-md.md', locale: 'en' };
// firstColumnAfterHeading is keyed on FIELD_REFERENCE_HEADING['en'] === 'Field reference'
// (matches the fixture doc's own heading), so collectKeySetParityViolations
// resolves the same table this fixture declares.
const violations = gen.collectKeySetParityViolations(target, fixtureSchema, doc);
const fieldRefViolation = violations.find((v) => v.reason === gen.REASON.FIELD_REFERENCE_DRIFT);
assert.ok(fieldRefViolation, 'expected a FIELD_REFERENCE_DRIFT violation');
assert.deepEqual(fieldRefViolation.missingFromDoc, ['beta']);
assert.deepEqual(fieldRefViolation.undeclaredInSchema, []);
});
test('docRowWithNoSchemaKeyIsDetectedUnlessGrandfathered', () => {
const fixtureSchema = { alpha: { cardinality: 'one' } };
const doc = [
'### Field reference',
'',
'| Field | Type |',
'|---|---|',
'| `alpha` | string |',
'| `totally_undeclared_field` | string |',
].join('\n');
const target = { relPath: 'fixture/state-md.md', locale: 'en' };
const violations = gen.collectKeySetParityViolations(target, fixtureSchema, doc);
const fieldRefViolation = violations.find((v) => v.reason === gen.REASON.FIELD_REFERENCE_DRIFT);
assert.ok(fieldRefViolation, 'an undeclared, non-grandfathered field must be reported');
assert.deepEqual(fieldRefViolation.undeclaredInSchema, ['totally_undeclared_field']);
});
test('knownSchemaGapFieldsAreGrandfatheredNotSilentlyDisabled', () => {
// KNOWN_SCHEMA_GAP_FIELDS names exactly the 3 real, pre-existing gap
// fields (active_phase/next_action/next_phases) — never a wildcard.
assert.deepEqual([...gen.KNOWN_SCHEMA_GAP_FIELDS].sort(), ['active_phase', 'next_action', 'next_phases']);
const fixtureSchema = { alpha: { cardinality: 'one' } };
const doc = [
'### Field reference',
'',
'| Field | Type |',
'|---|---|',
'| `alpha` | string |',
'| `active_phase` | string |',
].join('\n');
const target = { relPath: 'fixture/state-md.md', locale: 'en' };
const violations = gen.collectKeySetParityViolations(target, fixtureSchema, doc);
assert.equal(violations.find((v) => v.reason === gen.REASON.FIELD_REFERENCE_DRIFT), undefined);
});
test('statusValuesRowSetMismatchIsDetected', () => {
const fixtureSchema = { status: { enum: ['a', 'b', 'c'] } };
const doc = ['### Status values', '', '| Canonical value | Matched text |', '|---|---|', '| `a` | x |', '| `b` | y |'].join('\n');
const target = { relPath: 'fixture/state-md.md', locale: 'en' };
const violations = gen.collectKeySetParityViolations(target, fixtureSchema, doc);
const statusViolation = violations.find((v) => v.reason === gen.REASON.STATUS_VALUES_DRIFT);
assert.ok(statusViolation, 'expected a STATUS_VALUES_DRIFT violation');
assert.deepEqual(statusViolation.missingFromDoc, ['c']);
});
});

View File

@@ -0,0 +1,71 @@
'use strict';
/**
* Regression tripwire for issue #3873 (ADR-3473 §8.8, Phase 3 design/test
* matrix row 28 — `retainedFieldDriftGuardStillCatchesARederivation`).
*
* ADR-3473 §8.8 instructs deleting `scripts/lint-state-field-drift.cjs` as a
* "consequence for the guard" of consolidating STATE.md's field tables into
* one schema. That instruction rests on a wrong premise: this guard protects
* the ADR-3180 §7.7 / issue #3187 frontmatter-else-body coercion-ladder
* re-derivation, not the field/template/docs key-set drift Phase 3's schema
* addresses — the two are orthogonal, and the guard's own header docstring
* (`scripts/lint-state-field-drift.cjs:4-6`) says exactly that. The guard is
* therefore RETAINED, not deleted, and this test exists so a future reader
* cannot delete it on the ADR's word alone: it fails (module not found) the
* moment the file is removed, and it fails (assertion) the moment the guard
* stops detecting the ladder shape it was built for.
*
* `scripts/lint-state-field-drift.cjs` exports pure functions
* (`scanRepo(root)`, `findStateFieldDrift(text, relPath)`) that never touch
* the filesystem for the fixture half of this test — no fixture file is
* planted anywhere under the real `src/` tree (that mistake was made once
* already in this epic and fixed; see CLAUDE.md's Test Cleanup rule and the
* epic's own retrospective).
*
* The guard's CLI (`main()`, `scripts/lint-state-field-drift.cjs:763-782`)
* hard-codes its scan root to `path.join(__dirname, '..')` and takes no
* `--root` override (unlike its sibling `scripts/lint-state-write-path-drift.cjs`,
* which Phase 1 gave a `--root` flag). That only constrains an invocation of
* the CLI itself; `scanRepo` and `findStateFieldDrift` are exported and
* accept their scan surface as a parameter directly, which is what this test
* uses for both assertions below.
*/
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const fs = require('node:fs');
const drift = require('../scripts/lint-state-field-drift.cjs');
const REPO_ROOT = path.join(__dirname, '..');
const GUARD_PATH = path.join(REPO_ROOT, 'scripts', 'lint-state-field-drift.cjs');
describe('#3873 regression: scripts/lint-state-field-drift.cjs is retained, not deleted', () => {
test('retainedFieldDriftGuardStillCatchesARederivation', () => {
// (a) The guard file still exists and still runs clean against this repo
// today — the deletion ADR-3473 §8.8 calls for has not happened, and if
// it ever does this `require` throws MODULE_NOT_FOUND before the
// assertion below is even reached.
assert.ok(fs.existsSync(GUARD_PATH), 'scripts/lint-state-field-drift.cjs must still exist (#3873: not deleted by ADR-3473 §8.8)');
const violationsOnRealRepo = drift.scanRepo(REPO_ROOT);
assert.deepStrictEqual(violationsOnRealRepo, [], 'the guard must report zero re-derivations on the real, consolidated tree');
// (b) The guard still REPORTS on a re-derived frontmatter-else-body
// fallback ladder. Built entirely in memory via the exported pure
// `findStateFieldDrift(text, relPath)` — no temp directory, no write
// under `src/`. The fixture text is never persisted to disk.
const fixtureSource = [
"function cmdFixtureRead(fm, body) {",
' const v = fm.current_plan;',
" if (typeof v === 'number' || typeof v === 'boolean') return String(v);",
" return stateExtractField(body, 'Current Plan');",
'}',
].join('\n');
const found = drift.findStateFieldDrift(fixtureSource, path.join('src', 'fixture-not-a-real-file.cts'));
assert.strictEqual(found.length, 1, `expected exactly one re-derivation to be reported, got: ${JSON.stringify(found)}`);
assert.strictEqual(found[0].line, 4);
assert.match(found[0].found, /stateExtractField\(body, 'Current Plan'\)/);
});
});

View File

@@ -17,11 +17,14 @@ const {
openStateTransaction,
rebuildStateTransaction,
FIELD_CLASSIFICATION,
FRONTMATTER_BODY_SOURCE,
getFieldClassification,
getPreserveWhenUnchangedFields,
STATE_MD_SECTIONS,
sliceCurrentPositionSection,
} = require('../gsd-core/bin/lib/state-transition.cjs');
const { stateExtractField } = require('../gsd-core/bin/lib/state-document.cjs');
const { STATE_FIELD_SCHEMA } = require('../gsd-core/bin/lib/state-md-schema.cjs');
const fixedClock = Object.freeze({
today: () => '2026-06-27',
@@ -115,6 +118,132 @@ describe('ADR-1769 substrate: field-classification table', () => {
});
});
// #3873 (ADR-3473 §8.8): `FIELD_CLASSIFICATION` and `FRONTMATTER_BODY_SOURCE`
// are now PROJECTIONS of `STATE_FIELD_SCHEMA` (src/state-md-schema.cts),
// derived at module load rather than hand-maintained beside it. The
// comparands below are today's literal tables, copied VERBATIM (not
// re-derived from the schema — a parity test that builds both sides from the
// same source proves nothing; see 50-test-matrix.md's "writer-seeded fixture
// trap" note), captured by direct read of `src/state-transition.cts` on this
// branch's base (pre-#3873) before the projection replaced them. Any drift
// here is a silently-changed preservation policy — the #3427 failure this
// epic is named after.
describe('ADR-3473 §8.8 (#3873): the three tables are byte-identical projections of STATE_FIELD_SCHEMA', () => {
// Verbatim copy of `FIELD_CLASSIFICATION`'s pre-#3873 literal (19 rows, this
// exact key order — key order is observable: the preservation dispatch loop
// and `getPreserveWhenUnchangedFields` both iterate it).
const TODAYS_FIELD_CLASSIFICATION = Object.freeze({
gsd_state_version: { source: 'free', preservation: 'derive' },
milestone: { source: 'external', preservation: 'preserve-if-placeholder' },
milestone_name: { source: 'external', preservation: 'preserve-if-placeholder' },
current_phase: { source: 'body', preservation: 'preserve-when-unchanged' },
current_phase_name: { source: 'curated', preservation: 'preserve-when-unchanged' },
current_plan: { source: 'body', preservation: 'preserve-when-unchanged' },
status: { source: 'body', preservation: 'preserve-when-unchanged', guard: 'non-sentinel-unknown' },
stopped_at: { source: 'body', preservation: 'preserve-when-unchanged' },
paused_at: { source: 'body', preservation: 'preserve-when-unchanged' },
last_updated: { source: 'free', preservation: 'derive' },
last_activity: { source: 'body', preservation: 'derive' },
last_activity_desc: { source: 'body', preservation: 'preserve-when-unchanged' },
state_head: { source: 'free', preservation: 'derive' },
progress: { source: 'curated', preservation: 'preserve-always', mergeStrategy: 'progress-ratchet' },
'progress.total_phases': { source: 'disk', preservation: 'derive' },
'progress.completed_phases': { source: 'disk', preservation: 'derive' },
'progress.total_plans': { source: 'disk', preservation: 'derive' },
'progress.completed_plans': { source: 'disk', preservation: 'derive' },
'progress.percent': { source: 'disk', preservation: 'derive' },
});
// Verbatim copy of `FRONTMATTER_BODY_SOURCE`'s pre-#3873 literal (8 keys,
// this exact key order — deliberately NOT the same order as
// `FIELD_CLASSIFICATION` above, nor the same order as
// `FRONTMATTER_KEY_TO_BODY_LABEL` in tests/state.test.cjs; the two
// pre-existing tables disagreed with each other's order too).
const TODAYS_FRONTMATTER_BODY_SOURCE = Object.freeze({
current_phase: ['Current Phase'],
current_phase_name: ['Current Phase Name'],
current_plan: ['Current Plan'],
status: ['Status'],
stopped_at: ['Stopped At', 'Stopped at'],
paused_at: ['Paused At'],
last_activity: ['Last Activity', 'Last activity'],
last_activity_desc: ['Last Activity Description'],
});
test('row 1 — fieldClassificationProjectionMatchesTodaysTable', () => {
assert.deepStrictEqual(
Object.keys(FIELD_CLASSIFICATION),
Object.keys(TODAYS_FIELD_CLASSIFICATION),
'FIELD_CLASSIFICATION key order must be unchanged',
);
for (const key of Object.keys(TODAYS_FIELD_CLASSIFICATION)) {
assert.deepStrictEqual(
FIELD_CLASSIFICATION[key],
TODAYS_FIELD_CLASSIFICATION[key],
`FIELD_CLASSIFICATION[${JSON.stringify(key)}] must be byte-identical to today's table`,
);
}
});
test('row 2 — bodySourceProjectionMatchesTodaysTable', () => {
assert.deepStrictEqual(
Object.keys(FRONTMATTER_BODY_SOURCE),
Object.keys(TODAYS_FRONTMATTER_BODY_SOURCE),
'FRONTMATTER_BODY_SOURCE key order must be unchanged',
);
for (const key of Object.keys(TODAYS_FRONTMATTER_BODY_SOURCE)) {
assert.deepStrictEqual(
[...FRONTMATTER_BODY_SOURCE[key]],
TODAYS_FRONTMATTER_BODY_SOURCE[key],
`FRONTMATTER_BODY_SOURCE[${JSON.stringify(key)}] must be byte-identical to today's table`,
);
}
});
test('row 5 — projectionIsFrozenAndNullPrototype (FIELD_CLASSIFICATION, FRONTMATTER_BODY_SOURCE)', () => {
assert.ok(Object.isFrozen(FIELD_CLASSIFICATION));
assert.strictEqual(FIELD_CLASSIFICATION['toString'], undefined);
assert.ok(Object.isFrozen(FRONTMATTER_BODY_SOURCE));
assert.strictEqual(FRONTMATTER_BODY_SOURCE['toString'], undefined);
// Per-row objects/arrays keep their pre-#3873 shape too: FIELD_CLASSIFICATION's
// rows were plain (non-frozen, non-null-prototype) literals, and this
// projection reproduces that exactly rather than "improving" it.
assert.strictEqual(Object.isFrozen(FIELD_CLASSIFICATION.status), false);
assert.ok(Object.isFrozen(FRONTMATTER_BODY_SOURCE.stopped_at));
});
test('row 6 — everyClassificationRowStillResolves (including the five progress.* rows)', () => {
for (const key of Object.keys(TODAYS_FIELD_CLASSIFICATION)) {
assert.notStrictEqual(getFieldClassification(key), null, `${key} must still resolve`);
}
for (const leaf of ['progress.total_phases', 'progress.completed_phases', 'progress.total_plans', 'progress.completed_plans', 'progress.percent']) {
const cls = getFieldClassification(leaf);
assert.strictEqual(cls.source, 'disk');
assert.strictEqual(cls.preservation, 'derive');
}
});
test('row 7 — preserveWhenUnchangedProjectionUnchanged', () => {
assert.deepStrictEqual(
getPreserveWhenUnchangedFields(),
['current_phase', 'current_phase_name', 'current_plan', 'status', 'stopped_at', 'paused_at', 'last_activity_desc'],
);
});
test('row 8 — schemaMayDeclareMoreThanAProjectionConsumes', () => {
// `milestone` is a real STATE_FIELD_SCHEMA row (external/preserve-if-placeholder)
// with no body source at all, so it is legitimately absent from
// FRONTMATTER_BODY_SOURCE — projections are subsets by design (D4).
assert.ok(Object.prototype.hasOwnProperty.call(STATE_FIELD_SCHEMA, 'milestone'));
assert.strictEqual(STATE_FIELD_SCHEMA.milestone.bodySource, undefined);
assert.strictEqual(
Object.prototype.hasOwnProperty.call(FRONTMATTER_BODY_SOURCE, 'milestone'),
false,
'a schema row with no bodySource must not appear in the FRONTMATTER_BODY_SOURCE projection',
);
});
});
describe('ADR-1769 substrate: STATE_MD_SECTIONS constants (aligned to gsd-core/templates/state.md)', () => {
test('every section heading starts with "## "', () => {
for (const [name, heading] of Object.entries(STATE_MD_SECTIONS)) {
@@ -494,6 +623,113 @@ describe('ADR-1769 Phase 2: advancePlan transition', () => {
});
});
// ─── #3873 phase-3 test-matrix rows 23/24/25: parser accepts EXACTLY the ────
// schema-declared shapes — no more, no fewer.
//
// Table-driven over every STATE_FIELD_SCHEMA row carrying `acceptedShapes`
// (today: only `current_plan`), so declaring `acceptedShapes` on a future row
// gets gated automatically. A row with a driver missing from PARSER_DRIVERS
// fails loudly (row24/row23 below) rather than silently skipping — that is
// what keeps the table-driven claim honest as rows are added.
//
// The declaration itself was corrected against OBSERVED parser behavior
// (verified by executing `advancePlanCore`, not by reading its prior
// docstring's claim): `current_plan.acceptedShapes` is `['N']` only.
// `Current Plan: N of M` standalone does NOT parse today — `advancePlanCore`
// (`src/state-transition.cts:1306`) requires a `Total Plans in Phase`
// sibling for the bare-`N` path; with no sibling and no separate `Plan`
// field, it falls to its NaN/NaN error branch. #3784 is the open issue for
// teaching it the hybrid shape; **PR #3791** ("fix(#3784): read the hybrid
// `Current Plan: N of M` shape, keep zero-padding, and name the accepted
// shapes on failure") is the in-flight fix. When #3791 merges,
// `acceptedShapes` MUST widen to `['N', 'N of M']` — until then, this suite
// pins today's reality, and it is EXPECTED to go RED the moment the parser
// changes underneath it. That is the forcing function working as designed
// (§8.8 "checked, not generated"), not a broken test.
describe('#3873 phase-3 rows 23/24/25: parser accepts exactly the schema-declared shapes', () => {
const deps = { clock: fixedClock };
// Bare `N` only ever appears in a real STATE.md paired with a sibling
// `Total Plans in Phase` field (that pairing is what supplies the total
// `advancePlanCore` needs). `N of M` / `N/M` are driven WITHOUT that
// sibling, because the entire point of a hybrid shape is that it is
// self-contained in the `Current Plan` field alone — pairing it with a
// sibling would let the sibling's total paper over a value `parseInt`
// cannot fully read, which is the exact coincidence row 25 exists to catch.
function driveCurrentPlanShape(shapeValue, { withTotalSibling = false } = {}) {
const lines = ['# Project State', '', `**Current Plan:** ${shapeValue}`];
if (withTotalSibling) lines.push('**Total Plans in Phase:** 5');
lines.push('**Status:** Executing Phase 3', '');
const result = transitionCore(lines.join('\n'), { kind: 'advancePlan' }, deps);
return !(result.data && result.data.error === true);
}
// field -> (shape value, drive opts) -> boolean "did it parse"
const PARSER_DRIVERS = {
current_plan: driveCurrentPlanShape,
};
// shape name -> [example value, drive opts]
const SHAPE_EXAMPLES = {
'N': ['3', { withTotalSibling: true }],
'N of M': ['3 of 5', {}],
'N/M': ['3/5', {}],
};
const rowsWithAcceptedShapes = Object.entries(STATE_FIELD_SCHEMA).filter(
([, row]) => Array.isArray(row.acceptedShapes),
);
test('sanity: at least one schema row declares acceptedShapes (else this suite is vacuous)', () => {
assert.ok(rowsWithAcceptedShapes.length > 0, 'expected at least one acceptedShapes row to pin');
});
test('unsupportedDeclaredShapeFails: every declared shape parses via the real parser (row 24)', () => {
for (const [field, row] of rowsWithAcceptedShapes) {
const driver = PARSER_DRIVERS[field];
assert.ok(driver, `no PARSER_DRIVERS entry for field ${JSON.stringify(field)} — register one before declaring acceptedShapes on it`);
for (const shape of row.acceptedShapes) {
const example = SHAPE_EXAMPLES[shape];
assert.ok(example, `no SHAPE_EXAMPLES entry for shape ${JSON.stringify(shape)} (field ${JSON.stringify(field)})`);
const [value, opts] = example;
const parsed = driver(value, opts);
assert.strictEqual(parsed, true, `declared shape ${JSON.stringify(shape)} for field ${JSON.stringify(field)} did not parse`);
}
}
});
test('undeclaredParserShapeFails: a shape outside the declared set is rejected (row 23)', () => {
// 'N of M' is deliberately excluded from current_plan's declared set
// today (the #3784/#3791 boundary); 'N/M' is a fourth spelling that has
// never been declared for any row. Both must fail to parse.
for (const [field, row] of rowsWithAcceptedShapes) {
const driver = PARSER_DRIVERS[field];
const undeclaredCandidates = Object.keys(SHAPE_EXAMPLES).filter((shape) => !row.acceptedShapes.includes(shape));
assert.ok(undeclaredCandidates.length > 0, `no undeclared shape candidate available to probe field ${JSON.stringify(field)}`);
for (const shape of undeclaredCandidates) {
const [value, opts] = SHAPE_EXAMPLES[shape];
const parsed = driver(value, opts);
assert.strictEqual(parsed, false, `undeclared shape ${JSON.stringify(shape)} for field ${JSON.stringify(field)} was accepted by the parser`);
}
}
});
// The worked case (#3784's three spellings): current_plan specifically.
test('planNofMShapesAreExactlyTheDeclaredSet', () => {
assert.deepStrictEqual(Array.from(STATE_FIELD_SCHEMA.current_plan.acceptedShapes), ['N']);
// Declared shape parses.
assert.strictEqual(driveCurrentPlanShape('3', { withTotalSibling: true }), true, '"N" (paired with Total Plans in Phase) should parse');
// The hybrid shape is NOT declared today (#3784/#3791 boundary) and does
// NOT parse standalone in the Current Plan field.
assert.strictEqual(driveCurrentPlanShape('3 of 5'), false, '"N of M" standalone in Current Plan should NOT parse today');
// A fourth, never-declared spelling fails rather than quietly joining.
assert.strictEqual(driveCurrentPlanShape('3/5'), false, '"N/M" should NOT parse — it has never been declared');
});
});
describe('ADR-1769 Phase 2: advancePlan with frontmatter (#1255 pattern — codex review)', () => {
const deps = { clock: fixedClock };

View File

@@ -7088,6 +7088,229 @@ describe('ADR-3408 §8.5 Matrix (#3471): stale-but-present, and the report resid
assert.deepStrictEqual(wrongPolicy, [], `FRONTMATTER_KEY_TO_BODY_LABEL row(s) whose FIELD_CLASSIFICATION policy is not preserve-when-unchanged: ${JSON.stringify(wrongPolicy)}`);
});
});
// ─── #3873 row 3: FRONTMATTER_KEY_TO_BODY_LABEL is now a byte-identical ──────
// projection of STATE_FIELD_SCHEMA (src/state-md-schema.cts). Comparand is
// today's literal copied VERBATIM (not re-derived from the schema — see
// 50-test-matrix.md's "writer-seeded fixture trap" note), captured by direct
// read of `src/state.cts` on this branch's base before the projection
// replaced it.
describe('ADR-3473 §8.8 (#3873): FRONTMATTER_KEY_TO_BODY_LABEL is a byte-identical projection', () => {
// This exact key order — deliberately NOT the same order as
// FRONTMATTER_BODY_SOURCE (state-transition.cts): the two pre-existing
// tables disagreed with each other's order (status sits AFTER
// stopped_at/paused_at here, BEFORE them there).
const TODAYS_FRONTMATTER_KEY_TO_BODY_LABEL = Object.freeze({
current_phase: 'Current Phase',
current_phase_name: 'Current Phase Name',
current_plan: 'Current Plan',
stopped_at: 'Stopped At',
paused_at: 'Paused At',
status: 'Status',
last_activity_desc: 'Last Activity Description',
});
test('bodyLabelProjectionMatchesTodaysTable', () => {
assert.deepStrictEqual(
Object.keys(stateLib._FRONTMATTER_KEY_TO_BODY_LABEL),
Object.keys(TODAYS_FRONTMATTER_KEY_TO_BODY_LABEL),
'FRONTMATTER_KEY_TO_BODY_LABEL key order must be unchanged',
);
assert.deepStrictEqual(
stateLib._FRONTMATTER_KEY_TO_BODY_LABEL,
TODAYS_FRONTMATTER_KEY_TO_BODY_LABEL,
);
// Byte-identical also means NOT null-prototype: this table was a plain
// `Object.freeze({...})` object literal before #3873 (unlike
// FIELD_CLASSIFICATION / FRONTMATTER_BODY_SOURCE, which are
// null-prototype), and the projection reproduces that exactly.
assert.ok(Object.isFrozen(stateLib._FRONTMATTER_KEY_TO_BODY_LABEL));
assert.strictEqual(stateLib._FRONTMATTER_KEY_TO_BODY_LABEL['toString'], Object.prototype.toString);
});
});
// ─── #3873 pin: last_activity's TWO-TABLE disagreement, resolved by what SHIPS ──
// `FRONTMATTER_BODY_SOURCE` (state-transition.cts) carries a `last_activity`
// row; `FRONTMATTER_KEY_TO_BODY_LABEL` (state.cts, above) does not. ADR-3473
// §8.8 / issue #3873 Phase 3 collapses both tables into one schema and must
// declare a single answer for `last_activity` rather than picking whichever
// table looks tidier. This test pins the OBSERVED behavior that ships
// today, so the consolidation cannot silently change it.
//
// Observed: `last_activity`'s `FIELD_CLASSIFICATION` policy is
// `{ source: 'body', preservation: 'derive' }` — NOT `preserve-when-unchanged`.
// `bodyLabelFor` (state.cts) is only ever invoked, inside
// `reconcileReportedFields`'s `divergedFields` loop, for fields whose
// classification IS `preserve-when-unchanged` (every other field is
// `continue`d past before `bodyLabelFor` is reached). Because
// `last_activity` is `derive`, `bodyLabelFor('last_activity')` is
// unreachable in production today: the field never surfaces a Title-Case
// body label through that path, regardless of `FRONTMATTER_KEY_TO_BODY_LABEL`
// lacking a row for it. Meanwhile `FRONTMATTER_BODY_SOURCE['last_activity']`
// IS populated and IS live — it drives body-value reads for the frontmatter
// key (`getFrontmatterBodySource`, `frontmatterKeyForBodyField`). The two
// tables' disagreement is real, but only one of them is reachable for this
// key today; a consolidated schema resolves `last_activity` as "has a body
// SOURCE, has no reportable body LABEL" — matching what ships, not the
// tidier "it should have a label too" answer.
describe('#3873: last_activity label resolution matches shipped behavior', () => {
test('lastActivityLabelResolutionMatchesShippedBehavior', () => {
const cls = stateTransitionMod.getFieldClassification('last_activity');
assert.deepStrictEqual(
cls,
{ source: 'body', preservation: 'derive' },
'last_activity must remain classified as derive (never preserve-when-unchanged) — ' +
'this is what makes bodyLabelFor unreachable for it today',
);
const bodySource = stateTransitionMod.getFrontmatterBodySource('last_activity');
assert.deepStrictEqual(
bodySource,
['Last Activity', 'Last activity'],
'FRONTMATTER_BODY_SOURCE must still carry a body source for last_activity',
);
const hasBodyLabel = Object.prototype.hasOwnProperty.call(stateLib._FRONTMATTER_KEY_TO_BODY_LABEL, 'last_activity');
assert.strictEqual(
hasBodyLabel,
false,
'FRONTMATTER_KEY_TO_BODY_LABEL must NOT carry a last_activity row — the schema resolves ' +
'the two-table disagreement by declaring "no reportable body label", matching today\'s ' +
'shipped behavior (unreachable via bodyLabelFor because the field is derive, not ' +
'preserve-when-unchanged), not by inventing one because FRONTMATTER_BODY_SOURCE has an entry',
);
});
});
});
// ─── #3873 row 9: bodyLabelFor still throws STATE_BODY_LABEL_UNWIRED_ROW for ──
// an unwired preserve-when-unchanged row, now that FRONTMATTER_KEY_TO_BODY_LABEL
// (state.cts) is a projection of STATE_FIELD_SCHEMA (src/state-md-schema.cts)
// rather than a hand-maintained literal. Every real preserve-when-unchanged
// row is fully wired today (pinned by the parity tests above), so this test
// cannot reach the throw through a genuine schema key — it simulates the
// "future row added to FIELD_CLASSIFICATION without a matching label" case
// #3471 review names, by overriding getFieldClassification on the shared,
// cached module object for the duration of one test, restored via t.after()
// (never try/finally in the test body per repo convention).
describe('#3873 row 9: bodyLabelFor still throws for an unwired preserve-when-unchanged row', () => {
test('unwiredLabelRowStillThrowsFromTheSchema', (t) => {
const FAKE_FIELD = '__gsd_3873_unwired_probe__';
assert.strictEqual(
Object.prototype.hasOwnProperty.call(stateLib._FRONTMATTER_KEY_TO_BODY_LABEL, FAKE_FIELD),
false,
'probe field name must not collide with a real label row',
);
const original = stateTransitionMod.getFieldClassification;
t.after(() => {
stateTransitionMod.getFieldClassification = original;
});
stateTransitionMod.getFieldClassification = (field) =>
(field === FAKE_FIELD
? { source: 'body', preservation: 'preserve-when-unchanged' }
: original(field));
assert.throws(
() => stateLib._bodyLabelFor(FAKE_FIELD),
(err) => {
assert.strictEqual(err.code, 'STATE_BODY_LABEL_UNWIRED_ROW');
assert.strictEqual(err.field, FAKE_FIELD);
return true;
},
);
});
});
// ─── #3873 row 29 (property): every projection agrees with its schema row ───
// For every STATE_FIELD_SCHEMA row, each of the three derived tables either
// omits the key entirely or agrees with that row's corresponding value —
// the bijective contract CLAUDE.md's property-test rule requires for a
// consolidation like this one. fast-check v4: the arbitrary is declared
// INSIDE the property (a describe-body arbitrary kills the whole block), the
// seed is pinned and numRuns bounded for a deterministic, bounded run, and a
// failure re-throws with the seed spelled out so it names its own replay.
describe('#3873 row 29 (property): every projection agrees with its schema row', () => {
test('everyProjectionAgreesWithItsSchemaRow', () => {
const { STATE_FIELD_SCHEMA } = require('../gsd-core/bin/lib/state-md-schema.cjs');
const schemaKeys = Object.keys(STATE_FIELD_SCHEMA);
// Sanity: a property over zero keys would pass vacuously (CLAUDE.md's
// Test Cleanup rule against vacuous-truth tests).
assert.ok(schemaKeys.length > 0, 'STATE_FIELD_SCHEMA must be non-empty for this property to be meaningful');
const SEED = 38730029;
try {
fc.assert(
fc.property(fc.constantFrom(...schemaKeys), (key) => {
const row = STATE_FIELD_SCHEMA[key];
if (Object.prototype.hasOwnProperty.call(stateTransitionMod.FIELD_CLASSIFICATION, key)) {
const cls = stateTransitionMod.FIELD_CLASSIFICATION[key];
assert.strictEqual(cls.source, row.source, `FIELD_CLASSIFICATION[${key}].source disagrees with schema`);
assert.strictEqual(cls.preservation, row.preservation, `FIELD_CLASSIFICATION[${key}].preservation disagrees with schema`);
assert.strictEqual(cls.guard, row.guard, `FIELD_CLASSIFICATION[${key}].guard disagrees with schema`);
assert.strictEqual(cls.mergeStrategy, row.mergeStrategy, `FIELD_CLASSIFICATION[${key}].mergeStrategy disagrees with schema`);
}
if (Object.prototype.hasOwnProperty.call(stateTransitionMod.FRONTMATTER_BODY_SOURCE, key)) {
assert.deepStrictEqual(
Array.from(stateTransitionMod.FRONTMATTER_BODY_SOURCE[key]),
Array.from(row.bodySource || []),
`FRONTMATTER_BODY_SOURCE[${key}] disagrees with schema`,
);
}
if (Object.prototype.hasOwnProperty.call(stateLib._FRONTMATTER_KEY_TO_BODY_LABEL, key)) {
assert.strictEqual(
stateLib._FRONTMATTER_KEY_TO_BODY_LABEL[key],
row.bodyLabel,
`FRONTMATTER_KEY_TO_BODY_LABEL[${key}] disagrees with schema`,
);
}
return true;
}),
{ seed: SEED, numRuns: 200 },
);
} catch (err) {
throw new Error(`everyProjectionAgreesWithItsSchemaRow failed (seed=${SEED} — replay: fc.assert(..., { seed: ${SEED} })): ${err.message}`, { cause: err });
}
});
});
// ─── #3873 phase-3 row 26: statusEnumIsExactlyTheLifecycleSet ──────────────
// CORRECTED contract (verified by executing `normalizeStateStatus`, not by
// reading `STATUS_LIFECYCLE_ENUM`'s prior docstring claim): the enum's seven
// members are the values the normalizer maps recognized input TO — they are
// NOT a runtime-enforced closed set for the `status` key. `normalizeStateStatus`
// (`src/state-document.cts`) is deliberately lenient: its fallback is
// `status || 'unknown'`, so an input matching none of its substring branches
// passes straight through, unrejected and uncoerced. This test asserts the
// real, non-vacuous contract that IS true: every canonical value normalizes
// to itself, and an unrecognized value passes through unchanged — it does
// not assert a closure the normalizer does not enforce.
describe('#3873 phase-3 row 26: status enum matches the real normalizer contract', () => {
test('statusEnumIsExactlyTheLifecycleSet', () => {
const { STATUS_LIFECYCLE_ENUM } = require('../gsd-core/bin/lib/state-md-schema.cjs');
const { normalizeStateStatus } = require('../gsd-core/bin/lib/state-document.cjs');
assert.ok(STATUS_LIFECYCLE_ENUM.length > 0, 'STATUS_LIFECYCLE_ENUM must be non-empty for this test to be meaningful');
for (const member of STATUS_LIFECYCLE_ENUM) {
assert.strictEqual(
normalizeStateStatus(member, null),
member,
`canonical value ${JSON.stringify(member)} must normalize to itself`,
);
}
// A non-member is NOT rejected or coerced — it passes through unchanged,
// because the normalizer is lenient, not closed.
const nonMember = 'totally-unrecognized-status-text';
assert.ok(!STATUS_LIFECYCLE_ENUM.includes(nonMember), 'probe value must genuinely be a non-member');
assert.strictEqual(
normalizeStateStatus(nonMember, null),
nonMember,
'an unrecognized status value must pass through unchanged, not be coerced into the enum',
);
});
});
// ─────────────────────────────────────────────────────────────────────────────