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

@@ -75,6 +75,7 @@ import frontmatterMod = require('./frontmatter.cjs');
// eslint-disable-next-line @typescript-eslint/no-require-imports -- state.cjs is an export= CommonJS module
import stateMod = require('./state.cjs');
import { platformWriteSync, platformReadSync, platformEnsureDir, retryRenameSync, contentChangedAfterNormalize } from './shell-command-projection.cjs';
import { parsePlanningDoc, findField, readNode, setFieldValue, serialize } from './planning-document.cjs';
import { formatGsdSlash, resolveRuntime } from './runtime-slash.cjs';
import { realClock } from './clock.cjs';
import { transitionCore } from './state-transition.cjs';
@@ -3728,7 +3729,7 @@ function cmdPhaseComplete(cwd: string, phaseNum: string, raw: boolean): void {
// whole-slice `.replace()` onto the seam. Applied per single physical
// line by updateBullet, so the pattern no longer needs the `m` flag
// (it never sees more than one line at a time); see
// planCountBodyPattern below for the sites that were migrated onto
// writePlansField below for the sites that were migrated onto
// withPhaseSection instead.
//
// #2245 review Fix 6: this is behaviour-preserving for GSD-GENERATED
@@ -3787,12 +3788,109 @@ function cmdPhaseComplete(cwd: string, phaseNum: string, raw: boolean): void {
// ADR-2143 §4: the plan-count write is now routed through
// withPhaseSection (see mutateMilestonePhase below), which hands this
// pattern ONLY phase N's own detail-section body — so the pattern no
// longer needs its own `#{2,4}\s*Phase\s+N` anchor + skip-ahead-past-
// interior-headings lookahead; the section boundary itself confines
// the match (the #2067/#2200 boundary-crossing class is now
// structurally impossible for this site rather than regex-enforced).
const planCountBodyPattern = /(\*\*Plans:\*\*\s*)[^\n]+/i;
// seam call ONLY phase N's own detail-section body — the section
// boundary itself confines the write (the #2067/#2200 boundary-
// crossing class is structurally impossible for this site).
//
// #4906 Phase 2 (#4917/ADR-4910): migrated off the one-capture-group
// regex that replaced to end of line, dropping any hand-written
// trailing prose after the count (#4852) — onto the PlanningDoc
// `boldField` write seam, whose `valueSpan`/`trailingSpan` split
// never touches the trailing annotation.
const writePlansField = (body: string): string => {
const parsed = parsePlanningDoc(body, 'ROADMAP.md');
if (!parsed.ok) {
preservationWarnings.push({ field: 'Plans', reason: parsed.reason });
return body;
}
const fieldId = findField(parsed.value, 'Plans');
if (!fieldId) {
// #4906 regression (#1163 parity, caught by gsd-test against
// roadmap.cts's sibling site): a hand-edited or pre-template
// ROADMAP.md may carry a PLAIN (non-bold) `Plans:` line rather
// than the canonical `**Plans**:`/`**Plans:**` bold field.
// BOLD_FIELD_RE stays bold-only (widening it would register
// ordinary prose as a spurious field seam-wide) — this fallback
// mirrors roadmap.cts's identical one, kept in parity per
// Decision 2 rather than letting the two sites diverge on which
// legacy shapes they tolerate.
const plainMatch = body.match(/^([ \t]*)Plans:([ \t]*)([^\r\n]*)$/m);
if (!plainMatch) {
// No `**Plans:**`/`**Plans**:`/plain `Plans:` line in this
// phase's section — nothing to write; not a failure (mirrors
// the old regex's silent no-match no-op).
return body;
}
const [whole, indent, spacing, plainValue] = plainMatch;
const plainCountPrefixMatch = plainValue.match(
/^(?:\d+\s*\/\s*\d+\s+plans(?:\s+(?:complete|executed))?|\d+\s+plans?)/i,
);
const plainIsTemplatePlaceholder = /^\[\s*Number of plans\b[\s\S]*\]$/i.test(plainValue.trim());
if (!plainCountPrefixMatch && !plainIsTemplatePlaceholder) {
// Arm 3: freeform prose, TBD, a bracketed human annotation, or
// an empty value — leave the field exactly as it was.
return body;
}
const plainNewCountText = `${summaryCount}/${planCount} plans complete`;
const plainSuffix = plainCountPrefixMatch ? plainValue.slice(plainCountPrefixMatch[0].length) : '';
const newPlainLine = `${indent}Plans:${spacing}${plainNewCountText}${plainSuffix}`;
const start = plainMatch.index ?? body.indexOf(whole);
return body.slice(0, start) + newPlainLine + body.slice(start + whole.length);
}
// #4906 regression fix: PREFIX-match the existing value's count
// token and re-glue whatever follows it VERBATIM — a glued-on
// annotation with no ` — ` separator (e.g. a parenthetical like
// `0/1 plans executed (11-16 are gap closure from VERIFICATION)`)
// lives entirely inside `value` (`TRAILING_SEPARATOR_RE` in
// planning-document.cts only splits on ` — `, unchanged/correct),
// so overwriting `value` outright previously destroyed it.
//
// #4906 review finding (isolated adversarial pass): the prior
// version of this migration preserved this site's OLD
// unconditional-overwrite behavior for the no-count-prefix case,
// which clobbers arm 3 (freeform prose / TBD / a bracketed human
// annotation like `[Deferred pending re-scope]`) — a real
// regression against the design doc's own Behavior table row 4,
// not an accepted trade-off. Fixed here by adopting the SAME
// template-placeholder / arm-3-untouched classification
// roadmap.cts's sibling site already uses (isTemplatePlaceholder +
// "no count prefix and not a placeholder => leave untouched"),
// rather than letting the two migrated sites diverge on this.
const newCountText = `${summaryCount}/${planCount} plans complete`;
const current = readNode(parsed.value, fieldId);
if (!current.ok) {
return body;
}
const currentValue = current.value;
const countPrefixMatch = currentValue.match(
/^(?:\d+\s*\/\s*\d+\s+plans(?:\s+(?:complete|executed))?|\d+\s+plans?)/i,
);
const isTemplatePlaceholder = /^\[\s*Number of plans\b[\s\S]*\]$/i.test(currentValue.trim());
if (!countPrefixMatch && !isTemplatePlaceholder) {
// Arm 3: freeform prose, TBD, a bracketed human annotation, or an
// empty value — leave the field exactly as it was.
return body;
}
const newValueToWrite = countPrefixMatch
? newCountText + currentValue.slice(countPrefixMatch[0].length)
: newCountText;
const staged = setFieldValue(parsed.value, fieldId, newValueToWrite);
if (!staged.ok) {
preservationWarnings.push({ field: 'Plans', reason: staged.reason });
return body;
}
const out = serialize(staged.value);
if (!out.ok) {
// `hasUnreadableNodes` refusal (ADR-4910 amendment) — a ragged
// SIBLING node elsewhere in this same section refuses the whole
// splice. Never throw / crash the phase-complete transaction over
// a node unrelated to this write; surface it and leave `body`
// unchanged, same as any other preservation warning.
preservationWarnings.push({ field: 'Plans', reason: out.reason });
return body;
}
return out.value;
};
const phaseInfoSummaries = phaseInfo['summaries'] as string[];
@@ -3839,7 +3937,7 @@ function cmdPhaseComplete(cwd: string, phaseNum: string, raw: boolean): void {
// section's body, so neither regex can escape into a sibling
// phase's section, a shipped milestone, or a Backlog entry.
s = withPhaseSection(s, phaseNum, (body) => {
let b = body.replace(planCountBodyPattern, `$1${summaryCount}/${planCount} plans complete`);
let b = writePlansField(body);
for (const summaryFile of phaseInfoSummaries) {
const planId = summaryFile.replace('-SUMMARY.md', '').replace('SUMMARY.md', '');
if (!planId) continue;

View File

@@ -229,7 +229,15 @@ function fencedLineIndices(lines: LineInfo[]): Set<number> {
return set;
}
const BOLD_FIELD_RE = /^(\s*)(\*\*[^*\r\n]+:\*\*)([ \t]*)([^\r\n]*)$/;
/** Matches both shipped bold-field spellings: colon-inside (`**Label:**`,
* the original grammar) and colon-outside (`**Label**:`, the canonical form
* used throughout `templates/roadmap.md`). Each alternative's trailing
* marker is exactly 3 characters (`:**` or `**:`), so `token.slice(2, -3)`
* in `parseBoldFieldLine` strips the leading `**` and the spelling-specific
* trailing marker identically for both, yielding the same `label` either
* way. Deliberately excludes a bare unbolded `Label:` form — see Phase 1's
* prose-vs-field disambiguation design. */
const BOLD_FIELD_RE = /^(\s*)(\*\*[^*\r\n]+(?::\*\*|\*\*:))([ \t]*)([^\r\n]*)$/;
/** Boundary marking a hand-written trailing annotation on a field line —
* the token owner must never destroy prose past this separator. */
const TRAILING_SEPARATOR_RE = / — /;

View File

@@ -50,6 +50,9 @@ const { extractFrontmatter, parseMustHavesBlock } = frontmatter;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import verificationMod = require('./verification.cjs');
const { isPhaseComplete } = verificationMod;
// #4906 Phase 2 (#4917/ADR-4910): the PlanningDoc parse -> mutate -> serialize
// seam, mirroring phase.cts's already-migrated `writePlansField` site.
import { parsePlanningDoc, findField, readNode, setFieldValue, serialize } from './planning-document.cjs';
// ─── Types ────────────────────────────────────────────────────────────────────
@@ -1082,7 +1085,7 @@ function cmdRoadmapUpdatePlanProgress(cwd: string, phaseNum: string | null | und
let roadmapContent = originalContent;
const phasePattern = phaseMarkdownRegexSource(phaseNum);
// #4247: ONE local source for the ATX phase-heading anchor that every
// section-scoped writer below (`planCountPattern`,
// section-scoped writer below (`planSectionPattern`,
// `insertRowsPatternA|B`) starts with — extracted so the target-detection
// gate below reads the SAME grammar the writers anchor on, and a future
// edit to one cannot drift from the other three copies.
@@ -1095,7 +1098,7 @@ function cmdRoadmapUpdatePlanProgress(cwd: string, phaseNum: string | null | und
const gateActiveRegion = gateDetailsClose === -1
? originalContent
: originalContent.slice(gateDetailsClose + '</details>'.length);
// Heading target: the exact grammar `planCountPattern` /
// Heading target: the exact grammar `planSectionPattern` /
// `insertRowsPatternA|B` anchor on (an ATX phase heading for this phase).
const headingTargetFound = new RegExp(phaseHeadingAnchor, 'i').test(gateActiveRegion);
// Checklist target: when the phase is complete, its own checklist bullet
@@ -1193,9 +1196,16 @@ function cmdRoadmapUpdatePlanProgress(cwd: string, phaseNum: string | null | und
// `_match` unchanged. An untouched first line cannot orphan its own
// continuation on the next line, since the pattern never spans past
// `\n` in the first place.
const planCountPattern = new RegExp(
`(${phaseHeadingAnchor}(?:(?!\\n#{1,4}\\s)[\\s\\S])*?(?:\\*\\*Plans\\*\\*:|\\*\\*Plans:\\*\\*|(?:^|\\n)Plans:)\\s*)(\\d+\\s*\\/\\s*\\d+\\s+plans(?:\\s+(?:complete|executed))?|\\d+\\s+plans?)?([^\\r\\n]*)`,
'i'
// #4906 Phase 2 (#4917/ADR-4910): migrated off the one-capture-group
// regex that replaced to end of line onto the PlanningDoc `boldField`
// write seam. `planSectionPattern` scopes the match to phase N's OWN
// detail section (heading + body up to the next heading) — the same
// window `phaseHeadingAnchor`'s siblings anchor on — and the callback
// below runs parse -> classify -> (maybe) mutate -> serialize entirely
// within that section text, mirroring phase.cts's `writePlansField`.
const planSectionPattern = new RegExp(
`${phaseHeadingAnchor}(?:(?!\\n#{1,4}\\s)[\\s\\S])*`,
'i',
);
const planCountText = isComplete
? `${summaryCount}/${planCount} plans complete`
@@ -1205,24 +1215,107 @@ function cmdRoadmapUpdatePlanProgress(cwd: string, phaseNum: string | null | und
// gsd-core/templates/roadmap.md actually ships, not to "anything in
// brackets" — a bracketed human annotation like `[Deferred pending
// re-scope]` is structurally bracketed too but carries none of this
// wording, so it correctly falls through to arm 3 untouched.
// wording, so it correctly falls through to arm 3 untouched. Kept as a
// caller-side classifier (NOT seam grammar) reused below against the
// `boldField` node's own parsed `value`.
const isTemplatePlaceholder = (value: string): boolean => {
const trimmed = value.trim();
return /^\[\s*Number of plans\b[\s\S]*\]$/i.test(trimmed);
};
roadmapContent = replaceInCurrentMilestone(roadmapContent, planCountPattern, (_match, label, existingCount, trailing) => {
if (existingCount) {
// Arm 1: real count token — rewrite it, preserve the trailing annotation.
return `${label}${planCountText}${trailing}`;
// Positive detectors for the two "real count token" shapes (#2853 /
// #3584 Finding B): a fraction count (`N/M plans complete|executed`) or a
// bare singular/plural count (`N plan`/`N plans`, the fresh single-plan
// template shape at gsd-core/templates/roadmap.md:62). Either one is an
// existing count token to overwrite (arm 1), never template placeholder
// (arm 2) or freeform prose (arm 3).
// #4906 regression fix: PREFIX match (not full-string) — a real count
// token may have a glued-on annotation with no ` — ` separator (e.g.
// `0/1 plans executed (11-16 are gap closure from VERIFICATION)`), which
// `parseBoldFieldLine`'s em-dash-only trailing-content split leaves
// entirely inside `value` (TRAILING_SEPARATOR_RE in planning-document.cts
// is unchanged and correct — this is a caller-side classification fix,
// not a seam fix). Returns the matched prefix length, or -1 if no match.
const fractionCountPrefixLength = (value: string): number => {
const m = value.match(/^\d+\s*\/\s*\d+\s+plans(?:\s+(?:complete|executed))?/i);
return m ? m[0].length : -1;
};
const bareCountPrefixLength = (value: string): number => {
const m = value.match(/^\d+\s+plans?/i);
return m ? m[0].length : -1;
};
roadmapContent = replaceInCurrentMilestone(roadmapContent, planSectionPattern, (sectionText: string): string => {
const parsed = parsePlanningDoc(sectionText, 'ROADMAP.md');
if (!parsed.ok) {
// Unreadable section (e.g. an unterminated frontmatter fence) —
// leave it byte-identical rather than throwing.
return sectionText;
}
if (isTemplatePlaceholder(trailing)) {
// Arm 2: fresh-template placeholder — replace with the count.
return `${label}${planCountText}`;
const fieldId = findField(parsed.value, 'Plans');
if (!fieldId) {
// #4906 regression (#1163, caught by gsd-test): a hand-edited or
// pre-template ROADMAP.md may carry a PLAIN (non-bold) `Plans:` line
// rather than the canonical `**Plans**:`/`**Plans:**` bold field.
// BOLD_FIELD_RE is deliberately bold-only (widening it to any bare
// `Label:` would register ordinary prose like "Note: see below" as a
// spurious field seam-wide) — this is domain knowledge about ONE
// field's legacy tolerated shape, the same class of thing
// `isTemplatePlaceholder` above already keeps caller-side rather
// than seam grammar, so the fallback lives here, not in
// planning-document.cts.
const plainMatch = sectionText.match(/^([ \t]*)Plans:([ \t]*)([^\r\n]*)$/m);
if (!plainMatch) {
// No `**Plans:**`/`**Plans**:`/plain `Plans:` line in this phase's
// own section — nothing to write; not a failure (mirrors the old
// regex's silent no-match no-op).
return sectionText;
}
const [whole, indent, spacing, plainValue] = plainMatch;
const plainFractionLen = fractionCountPrefixLength(plainValue);
const plainBareLen = bareCountPrefixLength(plainValue);
const plainCountPrefixLen = plainFractionLen >= 0 ? plainFractionLen : plainBareLen;
if (plainCountPrefixLen < 0 && !isTemplatePlaceholder(plainValue)) {
// Arm 3: freeform prose, TBD, a bracketed human annotation, or an
// empty value — leave the section exactly as it was.
return sectionText;
}
const plainSuffix = plainCountPrefixLen >= 0 ? plainValue.slice(plainCountPrefixLen) : '';
const newPlainLine = `${indent}Plans:${spacing}${planCountText}${plainSuffix}`;
const start = plainMatch.index ?? sectionText.indexOf(whole);
return sectionText.slice(0, start) + newPlainLine + sectionText.slice(start + whole.length);
}
// Arm 3: freeform prose, TBD, a bracketed human annotation, a wrapped
// sentence's first line, or an empty value — leave the line exactly as
// it was.
return _match;
const current = readNode(parsed.value, fieldId);
if (!current.ok) {
return sectionText;
}
const currentValue = current.value;
const fractionPrefixLen = fractionCountPrefixLength(currentValue);
const barePrefixLen = bareCountPrefixLength(currentValue);
const countPrefixLen = fractionPrefixLen >= 0 ? fractionPrefixLen : barePrefixLen;
if (countPrefixLen < 0 && !isTemplatePlaceholder(currentValue)) {
// Arm 3: freeform prose, TBD, a bracketed human annotation, or an
// empty value — leave the section exactly as it was.
return sectionText;
}
// Arm 1 (real count token, possibly with a glued-on no-separator
// annotation re-attached verbatim as `suffix`) or arm 2 (fresh-template
// placeholder, whole value replaced): write the computed count.
// `setFieldValue`'s valueSpan/trailingSpan split additionally preserves
// any EM-DASH-separated trailing annotation (#2853) automatically — no
// separate "preserve trailing" branch needed for that shape.
const suffix = countPrefixLen >= 0 ? currentValue.slice(countPrefixLen) : '';
const newValueToWrite = planCountText + suffix;
const staged = setFieldValue(parsed.value, fieldId, newValueToWrite);
if (!staged.ok) {
return sectionText;
}
const out = serialize(staged.value);
if (!out.ok) {
// `hasUnreadableNodes` refusal (ADR-4910 amendment) — a ragged
// SIBLING node elsewhere in this same section refuses the whole
// splice. Never throw; leave the section unchanged.
return sectionText;
}
return out.value;
});
// If complete: check checkbox