fix(#4906): migrate the ROADMAP.md Plans: line onto the PlanningDoc seam — Phase 2 (#4933)

* feat(#4906): migrate the ROADMAP.md **Plans:** line onto the PlanningDoc seam

Phase 2 of epic #4906. Migrates the two writers of ROADMAP.md's Plans field onto
the seam ADR-4910 locks, and deletes both bespoke regexes per Decision 2 — a
correct copy of a rule the seam now owns is the same divergence risk as an
incorrect one.

src/phase.cts's mutateMilestonePhase carried planCountBodyPattern, one capture
group, replace-to-end-of-line: this is #4852, still live before this change.
src/roadmap.cts's cmdRoadmapUpdatePlanProgress carried the correct three-arm
sibling (the #2853/#3584 correction) that phase.cts never adopted. Both now call
findField/setFieldValue/serialize against a PlanningDoc parsed from the same
milestone/phase-confined substring their existing withPhaseSection /
replaceInCurrentMilestone wrappers already compute — those confinement
wrappers are unchanged, only the field-write mechanism inside them moved.

Verified end-to-end through the real commands against real fixtures, not
against an isolated reimplementation of the classification logic:
cmdRoadmapUpdatePlanProgress and cmdPhaseComplete both preserve a trailing
human annotation across a real count rewrite, and both leave a bracketed
human annotation (the #3584 Finding A discriminator) untouched.

Found and fixed inline, in the already-merged src/planning-document.cts,
rather than deferred: BOLD_FIELD_RE recognized only **Label:** (colon inside
the closing bold). gsd-core/templates/roadmap.md ships every field, Plans
included, as **Label**: (colon outside) -- migrating roadmap.cts onto the
seam as it stood would have silently regressed real generated ROADMAP.md
files back to the bug this migration exists to remove. Widened to recognize
both spellings; deliberately NOT widened to a bare unbolded Label: form,
which would register ordinary prose as a spurious field.

roadmap.cts's writer also recognizes a bare singular/plural count (1 plan /
3 plans, no fraction) as an existing count token to overwrite, not template-
placeholder or freeform prose -- the template's own single-plan-phase shape
and #3584 Finding B's fix. Preserved exactly; this shape is easy to drop by
only porting the more common fraction form.

Two of Phase 2's three originally-cited defects turned out to be already
fixed on next, independent of this epic, and are struck via a dated ADR
amendment rather than silently narrowed: #4862 (stateReplaceField's own
anchoring hardening already preserves sibling fields) and #4499
(spliceFrontmatter's per-key preservation already keeps block sequences
byte-identical). Both reproduced against the built module before being
struck, not assumed. STATE.md's field-write engine is re-scoped out of this
phase entirely -- not because of its get_impact rating alone (measured the
same way, the two sites THIS phase keeps are also CRITICAL, and an earlier
draft of the amendment claimed otherwise without checking; corrected) but
because updateCore is a multi-field transaction with frontmatter sync and
preservation reconciliation that does not map onto PlanningDoc's node model,
where migrating it would mean designing that model, not calling an existing
seam function.

Refs #4852
Refs #4906

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(#4906): preserve a trailing annotation with no em-dash separator

Test authoring surfaced a real regression against an existing #3584 fixture:
`**Plans**: 0/1 plans executed (11-16 are gap closure from VERIFICATION)` -- a
parenthetical annotation glued on with a bare space, no em-dash -- was left
completely untouched by the migrated code instead of being rewritten with the
count updated and the parenthetical preserved.

Root cause: planning-document.cts's parseBoldFieldLine splits a field's value
from its trailing annotation only on the literal " -- " separator. An
em-dash-separated annotation already lives outside `value` in `trailingSpan`,
untouched by setFieldValue regardless -- that path was never broken. A
parenthetical with no em-dash has nowhere to go but inside `value`, and the
migrated classification required the WHOLE value to match a count-token shape
exactly, so this case fell into "leave untouched."

Fixed in the migrated call sites, not in the seam: prefix-match the count
token against the field's current value, then re-glue whatever textual suffix
follows WITHIN that value onto the new count text before writing. Correct for
both shapes with no special-casing -- the em-dash case's suffix-within-value
is empty by construction (the annotation already lives outside value), the
parenthetical case's suffix is exactly the glued content, preserved verbatim.

Deliberately not fixed by widening planning-document.cts's separator grammar
to also recognize a bare-space-then-parenthesis: that seam is already-merged
and already-tested, and guessing at an open-ended set of annotation shapes at
the seam level is exactly what isTemplatePlaceholder already avoids by
staying caller-side. "What counts as a Plans-field count token" is domain
knowledge about this one field.

phase.cts's writePlansField had no arm-2/arm-3 classification before this
migration -- its original regex unconditionally overwrote whatever value was
present. That unconditional-overwrite behavior is preserved exactly for
values with no recognizable count-token prefix; only the recognized-count
case gained suffix preservation, matching what phase.cts actually did before.

Verified end-to-end via the real cmdRoadmapUpdatePlanProgress and
cmdPhaseComplete commands against real fixtures for both the parenthetical
and em-dash shapes at both sites.

Refs #4906

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(#4906): cover the migrated Plans-line writers at both sites

15 cases across tests/phase.test.cjs and tests/roadmap.test.cjs, one per row
of the phase test matrix, extending the existing describe blocks and helper
functions those files already use for these two commands rather than
building parallel fixtures.

Covers: trailing-prose preservation on a real count rewrite at both sites
(the #4852 regression, and the #2853/#3584 non-regression); zero-trailing-
content boundary; the bracketed-template-placeholder vs bracketed-human-
annotation discriminator (#3584 Finding A); a missing Plans field not
crashing either command; an unrelated unreadable sibling node in the same
confined section surfacing rather than corrupting the field; confinement
holding across sibling phases and milestones; a round trip through the
command's own read path; CRLF safety; and a parity assertion that both sites
now produce identical Plans-line text for identical inputs, proving one
shared mechanism rather than source-grepping for the deleted regex literals.

Authoring caught a real regression before it could land silently: an
existing #3584 fixture using a parenthetical annotation with no em-dash
separator failed against the first version of the migration. Reported rather
than edited to match the broken behavior -- see the paired fix commit. That
existing test needed no changes once the fix landed; its assertion was
verified independently against the real CLI before this commit.

Refs #4906

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(#4906): give phase.cts's Plans writer the same arm-2/arm-3 classification as roadmap.cts

Isolated adversarial review (mandatory orthogonal review pass) executed
writePlansField against `[Deferred pending re-scope]` and the fresh-template
placeholder wording and found the first version of this migration kept
phase.cts's OLD unconditional-overwrite behavior for the no-count-prefix
case instead of adopting the same isTemplatePlaceholder / arm-3-untouched
classification roadmap.cts's sibling site already uses. A bracketed human
annotation was being silently rewritten to a new count -- a real
content-destroying regression against this phase's own design-doc behavior
table, not an accepted trade-off, and exactly the kind of divergence between
the two sites Decision 2's parity requirement exists to eliminate.

writePlansField now runs the same template-placeholder check and "no count
prefix and not a placeholder => leave untouched" branch before ever calling
setFieldValue. Added two site-1 tests (rows 4 and 6 of the phase test
matrix) mirroring the existing site-2 coverage for this exact discriminator.

Refs #4906

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(#4906): restore plain (non-bold) Plans: line support and fix a test helper mismatch

gsd-test (mandatory verification, run before every push) surfaced two real
defects the migration's manual CLI checks had not caught:

1. #1163 regression: a hand-edited/pre-template ROADMAP.md can carry a PLAIN
   (non-bold) `Plans:` line rather than the canonical `**Plans**:`/
   `**Plans:**` bold field. The old deleted regexes tolerated this shape;
   the seam's BOLD_FIELD_RE is deliberately bold-only (widening it would
   register ordinary prose like "Note: see below" as a spurious field
   seam-wide), so the migrated writers silently no-op'd on it instead of
   updating the count -- a real, previously-tested behavior lost.

   Fixed with a caller-side fallback in both src/roadmap.cts (where the
   failing #1163 test lives) and src/phase.cts (added for parity, per
   Decision 2 -- the two sites should not diverge on which legacy shapes
   they tolerate): when findField finds no boldField Plans node, look for a
   plain `Plans:` line directly and apply the same arm-1/2/3 classification
   against it. This is domain knowledge about one field's legacy tolerated
   shape, the same class of thing isTemplatePlaceholder already keeps
   caller-side rather than seam grammar.

2. tests/roadmap.test.cjs's new rows 4/5 (site 2) seeded the colon-outside
   spelling (`**Plans**: ...`) but their plansLineIn() helper only matched
   colon-inside (`**Plans:**`), so both assertions compared against
   `undefined` regardless of whether the write logic was correct -- a
   test-authoring bug, not a source defect. Fixed the helper to recognize
   both BOLD_FIELD_RE spellings, matching what the production code actually
   supports.

Verified via a real gsd-test run before this fix (outcome: failed, 5
failures, all in tests/roadmap.test.cjs) and will be re-verified via a real
gsd-test run on this commit before push, per this repo's non-rationalization
rule: a red gate is fixed, never explained away.

Refs #4906

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(#4906): backfill the Phase 2 changeset fragment's PR number

pr:0 -> pr:4933, now that gh api POST /pulls has returned the real number.

Refs #4906

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-09-23 19:25:39 -04:00
committed by GitHub
parent 1e3e1f7cd8
commit d7b5b2c2b6
7 changed files with 723 additions and 26 deletions

View File

@@ -11697,6 +11697,228 @@ describe('issue #1159 (Defect B): deferred/future requirement IDs must not trigg
},
);
});
// ─────────────────────────────────────────────────────────────────────────────
// #4906 Phase 2 (.gsd/phase/feat-4906-phase2-field-writes/50-test-matrix.md):
// cmdPhaseComplete's `**Plans:**` write migrated onto the PlanningDoc
// parse -> setFieldValue -> serialize seam (src/planning-document.cjs). Reuses
// createFixture/capturePhaseComplete (site-1 helpers, defined earlier in this
// same folded scope) rather than hand-rolling a new invocation path. Row
// numbers refer to the locked matrix; row 6 (bracketed human annotation vs
// template placeholder) is a site-2-only row and is already covered at
// tests/phase.test.cjs's "case 11" test (bug #3584 describe block above,
// "a bracketed human annotation is preserved verbatim, not mistaken for the
// template placeholder") — not duplicated here.
// ─────────────────────────────────────────────────────────────────────────────
describe('#4906 Phase 2: cmdPhaseComplete Plans-line seam migration (site 1)', () => {
function fixtureWithPlansLines(phase1PlansLine, phase2PlansLine = '**Plans:** 0/1 plans') {
const tmpDir = createFixture('gsd-4906-phase-');
const roadmapPath = path.join(tmpDir, '.planning', 'ROADMAP.md');
const before = fs.readFileSync(roadmapPath, 'utf-8');
const after = before
.replace('**Plans:** 1 plans', phase1PlansLine)
.replace('**Goal:** Build the API', `**Goal:** Build the API\n${phase2PlansLine}`);
fs.writeFileSync(roadmapPath, after);
return { tmpDir, roadmapPath };
}
function plansLines(content) {
return content.split(/\r?\n/).filter((l) => l.trim().startsWith('**Plans:**'));
}
test('row 1 (#4852 regression): trailing prose on the Plans line survives a count bump', (t) => {
const annotation = '— replanned per review';
const { tmpDir, roadmapPath } = fixtureWithPlansLines(`**Plans:** 1 plans ${annotation}`);
t.after(() => cleanup(tmpDir));
capturePhaseComplete(t, tmpDir, '1');
const [line] = plansLines(fs.readFileSync(roadmapPath, 'utf-8'));
assert.equal(line, `**Plans:** 1/1 plans complete ${annotation}`,
'annotation must survive byte-for-byte after the count bump');
});
test('row 3: a Plans line with a real count and no trailing content updates cleanly', (t) => {
const { tmpDir, roadmapPath } = fixtureWithPlansLines('**Plans:** 1 plans');
t.after(() => cleanup(tmpDir));
capturePhaseComplete(t, tmpDir, '1');
const [line] = plansLines(fs.readFileSync(roadmapPath, 'utf-8'));
assert.equal(line, '**Plans:** 1/1 plans complete');
});
test('row 7: a missing Plans field does not crash phase.complete', (t) => {
const tmpDir = createFixture('gsd-4906-row7-');
const roadmapPath = path.join(tmpDir, '.planning', 'ROADMAP.md');
const before = fs.readFileSync(roadmapPath, 'utf-8');
// Drop the `**Plans:**` line from Phase 01's own section entirely.
const after = before.replace('**Plans:** 1 plans\n', '');
fs.writeFileSync(roadmapPath, after);
t.after(() => cleanup(tmpDir));
// Must not throw — capturePhaseComplete throws on a non-zero exit.
assert.doesNotThrow(() => capturePhaseComplete(t, tmpDir, '1'));
});
test('row 8: an unreadable sibling node in the confined window is surfaced, not silently dropped', (t) => {
// Ragged table shape reused verbatim from tests/planning-document.test.cjs's
// raggedTableSource() (row 8 there): a data row with fewer cells than the
// header and no valid delimiter row for that mismatch — parsePlanningDoc
// accepts it as a table NODE but marks it unreadable, so `serialize`
// refuses the whole section splice (ADR-4910 amendment).
const { tmpDir, roadmapPath } = fixtureWithPlansLines('**Plans:** 1 plans');
const before = fs.readFileSync(roadmapPath, 'utf-8');
const ragged = ['', '| A | B |', '|---|---|', '| onlyone |', ''].join('\n');
fs.writeFileSync(roadmapPath, before.replace('**Plans:** 1 plans\n', `**Plans:** 1 plans\n${ragged}`));
t.after(() => cleanup(tmpDir));
const stdout = capturePhaseComplete(t, tmpDir, '1');
const result = JSON.parse(stdout);
assert.deepEqual(result.preservation_warnings, [{ field: 'Plans', reason: 'unreadable-nodes' }],
'the refusal must be surfaced via preservation_warnings, not silently swallowed');
const [line] = plansLines(fs.readFileSync(roadmapPath, 'utf-8'));
assert.equal(line, '**Plans:** 1 plans', 'the Plans field itself must stay unchanged, not corrupted');
});
test('row 9: the write does not escape its confinement window into a sibling phase', (t) => {
const annotation = '— do not touch';
const { tmpDir, roadmapPath } = fixtureWithPlansLines('**Plans:** 1 plans', `**Plans:** 0/1 plans ${annotation}`);
t.after(() => cleanup(tmpDir));
capturePhaseComplete(t, tmpDir, '1');
const [phase1Line, phase2Line] = plansLines(fs.readFileSync(roadmapPath, 'utf-8'));
assert.equal(phase1Line, '**Plans:** 1/1 plans complete', 'phase 1 (the target) is rewritten');
assert.equal(phase2Line, `**Plans:** 0/1 plans ${annotation}`,
"phase 2's own Plans line must stay untouched by phase 1's write");
});
test('row 10: a migrated Plans write round-trips identically through the seam\'s own read path', (t) => {
const { tmpDir, roadmapPath } = fixtureWithPlansLines('**Plans:** 1 plans');
t.after(() => cleanup(tmpDir));
capturePhaseComplete(t, tmpDir, '1');
const written = fs.readFileSync(roadmapPath, 'utf-8');
const { parsePlanningDoc, findField, readNode } = require('../gsd-core/bin/lib/planning-document.cjs');
const parsed = parsePlanningDoc(written, 'ROADMAP.md');
assert.ok(parsed.ok, 'the written ROADMAP.md must remain parseable by the same seam');
const fieldId = findField(parsed.value, 'Plans');
assert.ok(fieldId, 'the Plans field must still be locatable');
const read = readNode(parsed.value, fieldId);
assert.ok(read.ok, 'the Plans field must remain readable');
assert.equal(read.value, '1/1 plans complete', 'round-tripped value matches exactly what was computed');
});
test('row 12: the Plans-line migration is CRLF-safe', (t) => {
const { splitLines } = require('../gsd-core/bin/lib/text-lines.cjs');
const annotation = '— crlf annotation';
const { tmpDir, roadmapPath } = fixtureWithPlansLines(`**Plans:** 1 plans ${annotation}`);
const lf = fs.readFileSync(roadmapPath, 'utf-8');
fs.writeFileSync(roadmapPath, splitLines(lf).join('\r\n'));
t.after(() => cleanup(tmpDir));
capturePhaseComplete(t, tmpDir, '1');
const written = fs.readFileSync(roadmapPath, 'utf-8');
const [line] = splitLines(written).filter((l) => l.trim().startsWith('**Plans:**'));
assert.equal(line, `**Plans:** 1/1 plans complete ${annotation}`,
'CRLF source must not corrupt the offset or strand/duplicate the annotation');
});
test('row 13: phase.cts and roadmap.cts write identical Plans-line text for the same inputs', (t) => {
// Parity proof (Decision 2): both sites route through the same
// planning-document seam and must produce byte-identical text for the
// same summaryCount/planCount/isComplete inputs — never asserted by
// grepping for the deleted regex literals.
const { tmpDir, roadmapPath } = fixtureWithPlansLines('**Plans:** 1 plans');
t.after(() => cleanup(tmpDir));
capturePhaseComplete(t, tmpDir, '1');
const [phaseSiteLine] = plansLines(fs.readFileSync(roadmapPath, 'utf-8'));
const roadmapMod = require('../gsd-core/bin/lib/roadmap.cjs');
const rmTmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4906-row13-roadmap-'));
t.after(() => cleanup(rmTmp));
const planningDir = path.join(rmTmp, '.planning');
fs.mkdirSync(planningDir, { recursive: true });
fs.writeFileSync(path.join(planningDir, 'config.json'), JSON.stringify({ project_code: 'TEST' }));
fs.writeFileSync(
path.join(planningDir, 'ROADMAP.md'),
[
'# Roadmap', '',
'- [ ] **Phase 10: Test Phase**', '',
'### Phase 10: Test Phase',
'**Goal:** goal',
'**Plans:** 1 plans', '',
'## Progress', '',
'| Phase | Plans Complete | Status | Completed |',
'|-------|----------------|--------|-----------|',
'| 10 Test Phase | 0/1 | Not started | - |', '',
].join('\n'),
);
const rmPhaseDir = path.join(planningDir, 'phases', '10-test-phase');
fs.mkdirSync(rmPhaseDir, { recursive: true });
fs.writeFileSync(path.join(rmPhaseDir, '10-01-PLAN.md'), '# Plan\n');
fs.writeFileSync(path.join(rmPhaseDir, '10-01-SUMMARY.md'), '# Summary\n');
fs.writeFileSync(path.join(rmPhaseDir, '10-VERIFICATION.md'), '---\nstatus: passed\n---\n\n# Verification\n');
let captured = '';
const origWriteSync = fs.writeSync;
t.mock.method(fs, 'writeSync', (fd, ...args) => {
if (fd === 1) {
const buf = args[0];
captured += Buffer.isBuffer(buf) ? buf.toString('utf-8') : String(buf);
return Buffer.isBuffer(buf) ? buf.length : Buffer.byteLength(String(buf));
}
if (fd === 2) return Buffer.isBuffer(args[0]) ? args[0].length : Buffer.byteLength(String(args[0]));
return origWriteSync.call(fs, fd, ...args);
});
roadmapMod.cmdRoadmapUpdatePlanProgress(rmTmp, '10', false);
void captured;
const [roadmapSiteLine] = fs.readFileSync(path.join(planningDir, 'ROADMAP.md'), 'utf-8')
.split(/\r?\n/)
.filter((l) => l.trim().startsWith('**Plans:**'));
assert.equal(phaseSiteLine, '**Plans:** 1/1 plans complete');
assert.equal(roadmapSiteLine, '**Plans:** 1/1 plans complete',
'both sites must produce byte-identical Plans-line text for the same 1/1-complete inputs');
assert.equal(phaseSiteLine, roadmapSiteLine);
});
test('row 6 (site-1 arm 3, review finding): a bracketed human annotation is left untouched, not overwritten', (t) => {
// Isolated adversarial review (#4906 Phase 2) caught that this site's
// migration preserved its OLD unconditional-overwrite behavior instead
// of adopting arm 3 from roadmap.cts's sibling classification — a
// freeform/bracketed annotation with no count-token prefix must stay
// untouched, exactly as the design doc's Behavior table row 4 requires
// and exactly as roadmap.cts's own "case 11" (#3584 Finding A) already
// proves for site 2.
const { tmpDir, roadmapPath } = fixtureWithPlansLines('**Plans:** [Deferred pending re-scope]');
t.after(() => cleanup(tmpDir));
capturePhaseComplete(t, tmpDir, '1');
const [line] = plansLines(fs.readFileSync(roadmapPath, 'utf-8'));
assert.equal(line, '**Plans:** [Deferred pending re-scope]',
'a bracketed human annotation is arm 3 (freeform), never a template placeholder or a count token, and must not be overwritten');
});
test('row 6 (site-1 arm 2): the fresh-template placeholder wording is still replaced with the computed count', (t) => {
const { tmpDir, roadmapPath } = fixtureWithPlansLines('**Plans:** [Number of plans, e.g., "3 plans" or "TBD"]');
t.after(() => cleanup(tmpDir));
capturePhaseComplete(t, tmpDir, '1');
const [line] = plansLines(fs.readFileSync(roadmapPath, 'utf-8'));
assert.equal(line, '**Plans:** 1/1 plans complete',
'the template placeholder is arm 2 and must still be replaced with the real count');
});
test('#1163 parity: a plain (non-bold) Plans: line still gets its count updated', (t) => {
// roadmap.cts's sibling site has a real, pre-existing regression test
// for this exact legacy shape (tests/roadmap.test.cjs, "regressions:
// insert missing plan rows (#1163)") — caught missing here by gsd-test,
// since this migration's first version only handled the BOLD_FIELD_RE
// grammar and silently no-op'd on a plain `Plans:` line. Fixed in
// src/phase.cts's writePlansField with the same caller-side fallback
// roadmap.cts uses, kept in parity per Decision 2.
const tmpDir = createFixture('gsd-4906-plain-plans-');
const roadmapPath = path.join(tmpDir, '.planning', 'ROADMAP.md');
const before = fs.readFileSync(roadmapPath, 'utf-8');
const after = before.replace('**Plans:** 1 plans', 'Plans: 0/1 plans executed');
fs.writeFileSync(roadmapPath, after);
t.after(() => cleanup(tmpDir));
capturePhaseComplete(t, tmpDir, '1');
const written = fs.readFileSync(roadmapPath, 'utf-8');
const line = written.split(/\r?\n/).find((l) => l.trim().startsWith('Plans:'));
assert.equal(line, 'Plans: 1/1 plans complete',
'a plain (non-bold) Plans: line must still be updated, not silently skipped');
});
});
});
}
@@ -16083,3 +16305,4 @@ describe('phase complete skips already-complete phases as next_phase (#4699)', (
'without the fix scope change: an unchecked phase 3 stays a valid candidate (disk spelling wins)');
});
});

View File

@@ -5486,3 +5486,193 @@ describe('#4801: init.manager resolves archived phase directories', () => {
`live plan-less phase stays incomplete; got ${row.disk_status}`);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// #4906 Phase 2 (.gsd/phase/feat-4906-phase2-field-writes/50-test-matrix.md):
// cmdRoadmapUpdatePlanProgress's `**Plans:**` write migrated onto the
// PlanningDoc parse -> setFieldValue -> serialize seam (src/planning-document.
// cjs). Row numbers refer to the locked matrix.
//
// Row 6 (a bracketed HUMAN annotation, e.g. `[Deferred pending re-scope]`,
// must not be mistaken for the fresh-template placeholder) is #3584 Finding
// A's own regression fixture and is already covered — see tests/phase.test.
// cjs's "case 11 — a bracketed human annotation is preserved verbatim, not
// mistaken for the template placeholder" in the `bug #3584` describe block —
// not duplicated here per the fixture-provenance rule.
//
// Row 13 (parity between phase.cts and roadmap.cts for identical numeric
// inputs) is asserted once, at tests/phase.test.cjs's "row 13" test above;
// not duplicated here.
// ─────────────────────────────────────────────────────────────────────────────
describe('#4906 Phase 2: cmdRoadmapUpdatePlanProgress Plans-line seam migration (site 2)', () => {
let tmpDir;
let roadmapPath;
beforeEach(() => {
tmpDir = createTempProject('gsd-4906-roadmap-');
roadmapPath = path.join(tmpDir, '.planning', 'ROADMAP.md');
});
afterEach(() => {
cleanup(tmpDir);
});
function seedPhase10(plansLine, { verified = true } = {}) {
fs.writeFileSync(
roadmapPath,
[
'# Roadmap', '',
'- [ ] **Phase 10: Test Phase**', '',
'### Phase 10: Test Phase',
'**Goal:** goal',
plansLine, '',
'## Progress', '',
'| Phase | Plans Complete | Status | Completed |',
'|-------|----------------|--------|-----------|',
'| 10 Test Phase | 0/1 | Not started | - |', '',
].join('\n'),
);
const phaseDir = path.join(tmpDir, '.planning', 'phases', '10-test-phase');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '10-01-PLAN.md'), '# Plan\n');
fs.writeFileSync(path.join(phaseDir, '10-01-SUMMARY.md'), '# Summary\n');
if (verified) {
fs.writeFileSync(path.join(phaseDir, '10-VERIFICATION.md'), '---\nstatus: passed\n---\n\n# Verification\n');
}
return phaseDir;
}
function plansLineIn(content) {
// Recognizes both BOLD_FIELD_RE spellings (colon inside `**Plans:**` and
// colon outside `**Plans**:`, the canonical templates/roadmap.md shape) —
// rows 4/5 below seed the colon-outside spelling, and a finder anchored
// to only one spelling silently reports "field not found" (`undefined`)
// rather than a real assertion failure, masking whichever bug is actually
// present. Caught by gsd-test (#4906 Phase 2 verification run).
return content.split(/\r?\n/).find((l) => /^\*\*Plans(?::\*\*|\*\*:)/.test(l.trim()));
}
test('row 2 (non-regression of #2853/#3584): trailing prose survives migration', () => {
const annotation = '— replanned per review';
seedPhase10(`**Plans:** 1 plans ${annotation}`);
const result = runGsdTools('roadmap update-plan-progress 10', tmpDir);
assert.ok(result.success, `command failed: ${result.error}`);
const line = plansLineIn(fs.readFileSync(roadmapPath, 'utf-8'));
assert.equal(line, `**Plans:** 1/1 plans complete ${annotation}`,
'annotation must survive byte-for-byte after the count bump');
});
test('row 3: a Plans line with a real count and no trailing content updates cleanly', () => {
seedPhase10('**Plans:** 1 plans');
const result = runGsdTools('roadmap update-plan-progress 10', tmpDir);
assert.ok(result.success, `command failed: ${result.error}`);
const line = plansLineIn(fs.readFileSync(roadmapPath, 'utf-8'));
assert.equal(line, '**Plans:** 1/1 plans complete');
});
test('row 4: the fresh-template placeholder is replaced with the real count', () => {
seedPhase10('**Plans**: [Number of plans, e.g., "3 plans" or "TBD"]');
const result = runGsdTools('roadmap update-plan-progress 10', tmpDir);
assert.ok(result.success, `command failed: ${result.error}`);
const line = plansLineIn(fs.readFileSync(roadmapPath, 'utf-8'));
assert.equal(line, '**Plans**: 1/1 plans complete');
});
test('row 5: freeform prose (not the template placeholder, not a real count) is left untouched', () => {
seedPhase10('**Plans**: TBD — annotation');
const result = runGsdTools('roadmap update-plan-progress 10', tmpDir);
assert.ok(result.success, `command failed: ${result.error}`);
const line = plansLineIn(fs.readFileSync(roadmapPath, 'utf-8'));
assert.equal(line, '**Plans**: TBD — annotation', 'freeform prose must never be classified as a writable count');
});
test('row 7: a missing Plans field does not crash roadmap.update-plan-progress', () => {
fs.writeFileSync(
roadmapPath,
[
'# Roadmap', '',
'- [ ] **Phase 10: Test Phase**', '',
'### Phase 10: Test Phase',
'**Goal:** goal', '',
'## Progress', '',
'| Phase | Plans Complete | Status | Completed |',
'|-------|----------------|--------|-----------|',
'| 10 Test Phase | 0/1 | Not started | - |', '',
].join('\n'),
);
const phaseDir = path.join(tmpDir, '.planning', 'phases', '10-test-phase');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '10-01-PLAN.md'), '# Plan\n');
fs.writeFileSync(path.join(phaseDir, '10-01-SUMMARY.md'), '# Summary\n');
fs.writeFileSync(path.join(phaseDir, '10-VERIFICATION.md'), '---\nstatus: passed\n---\n\n# Verification\n');
const result = runGsdTools('roadmap update-plan-progress 10', tmpDir);
assert.ok(result.success, `must not crash on a missing Plans field: ${result.error}`);
});
test('row 9: the write does not escape its confinement window into a sibling phase', () => {
const annotation = '— do not touch';
fs.writeFileSync(
roadmapPath,
[
'# Roadmap', '',
'- [ ] **Phase 10: Test Phase**',
'- [ ] **Phase 11: Sibling Phase**', '',
'### Phase 10: Test Phase',
'**Goal:** goal',
'**Plans:** 1 plans', '',
'### Phase 11: Sibling Phase',
'**Goal:** sibling goal',
`**Plans:** 0/1 plans ${annotation}`, '',
'## Progress', '',
'| Phase | Plans Complete | Status | Completed |',
'|-------|----------------|--------|-----------|',
'| 10 Test Phase | 0/1 | Not started | - |',
'| 11 Sibling Phase | 0/1 | Not started | - |', '',
].join('\n'),
);
const phaseDir = path.join(tmpDir, '.planning', 'phases', '10-test-phase');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '10-01-PLAN.md'), '# Plan\n');
fs.writeFileSync(path.join(phaseDir, '10-01-SUMMARY.md'), '# Summary\n');
fs.writeFileSync(path.join(phaseDir, '10-VERIFICATION.md'), '---\nstatus: passed\n---\n\n# Verification\n');
const result = runGsdTools('roadmap update-plan-progress 10', tmpDir);
assert.ok(result.success, `command failed: ${result.error}`);
const lines = fs.readFileSync(roadmapPath, 'utf-8')
.split(/\r?\n/)
.filter((l) => l.trim().startsWith('**Plans:**'));
assert.equal(lines[0], '**Plans:** 1/1 plans complete', 'phase 10 (the target) is rewritten');
assert.equal(lines[1], `**Plans:** 0/1 plans ${annotation}`,
"phase 11's own Plans line must stay untouched by phase 10's write");
});
test('row 10: a migrated Plans write round-trips identically through the seam\'s own read path', () => {
seedPhase10('**Plans:** 1 plans');
const result = runGsdTools('roadmap update-plan-progress 10', tmpDir);
assert.ok(result.success, `command failed: ${result.error}`);
const written = fs.readFileSync(roadmapPath, 'utf-8');
const { parsePlanningDoc, findField, readNode } = require('../gsd-core/bin/lib/planning-document.cjs');
const parsed = parsePlanningDoc(written, 'ROADMAP.md');
assert.ok(parsed.ok, 'the written ROADMAP.md must remain parseable by the same seam');
const fieldId = findField(parsed.value, 'Plans');
assert.ok(fieldId, 'the Plans field must still be locatable');
const read = readNode(parsed.value, fieldId);
assert.ok(read.ok, 'the Plans field must remain readable');
assert.equal(read.value, '1/1 plans complete', 'round-tripped value matches exactly what was computed');
});
test('row 12: the Plans-line migration is CRLF-safe', () => {
const { splitLines } = require('../gsd-core/bin/lib/text-lines.cjs');
const annotation = '— crlf annotation';
seedPhase10(`**Plans:** 1 plans ${annotation}`);
const lf = fs.readFileSync(roadmapPath, 'utf-8');
fs.writeFileSync(roadmapPath, splitLines(lf).join('\r\n'));
const result = runGsdTools('roadmap update-plan-progress 10', tmpDir);
assert.ok(result.success, `command failed: ${result.error}`);
const written = fs.readFileSync(roadmapPath, 'utf-8');
const line = splitLines(written).find((l) => l.trim().startsWith('**Plans:**'));
assert.equal(line, `**Plans:** 1/1 plans complete ${annotation}`,
'CRLF source must not corrupt the offset or strand/duplicate the annotation');
});
});