fix(#1156): support table-format STATE.md and insert missing roadmap plan rows (#1172)

* fix(#1162): support table-format STATE.md in state field read/replace

Extend stateExtractField and stateReplaceField in state-document.cts to
detect and operate on pipe-table rows (| Field | value |).  The separator
row | --- | --- | is excluded from matching.  updateCurrentPositionFields
in state.cts now falls through to stateReplaceField for table-format
Current Position sections when the inline Status:/Last activity: patterns
do not match.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#1163): insert missing plan checklist rows in roadmap update-plan-progress

cmdRoadmapUpdatePlanProgress now inserts `- [ ] NN-XX-PLAN.md` checkbox
rows under the phase Plans: line when no per-plan checkbox rows exist yet
(fresh template).  Rows are sorted ascending and any already-summarised
plans are immediately marked [x].  The planCountPattern is extended to
also match plain `Plans:` (in addition to bold `**Plans:**`) so plan
counts are updated in both template variants.  The existing-rows check
covers both top-level and indented checkbox forms to preserve idempotency.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#1163): fill partial plan-row gaps and scope insertion to active milestone

- Finding 1 (HIGH): replace all-or-nothing rowsAlreadyPresent guard with per-file
  set-difference so missing rows are inserted even when SOME plan rows already exist
- Finding 2 (MEDIUM): extend planCountPattern to recognise **Plans**: (canonical
  template form — bold word + outer colon) alongside **Plans:** and plain Plans:;
  use two-pattern fallback for row insertion to anchor under Plans: checklist header
  rather than the **Plans**: summary line
- Finding 3 (MEDIUM): scope row insertion to the active (post-</details>) milestone
  region so duplicate phase headings in archived sections never receive new rows
- Finding 4 (LOW): rename misleading "pipe-like content" test to honestly describe
  what it tests (multi-row table isolation); add out-of-scope escaped-pipe comment
- Remove now-unused anyCheckboxMatched variable (lint clean)
- Add 5 adversarial regression tests (pre-fix failures confirmed)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#1163): scope missing-plan detection to active milestone; preserve authored state fields in table format

- roadmap.cts: compute activeRegion (post-</details> slice) once and use it
  for BOTH missingPlans detection and row insertion, so archived <details>
  rows no longer suppress active-section inserts (Finding 1 code-review)
- roadmap.cts: change (Plans:) inner capture to non-capturing (?:Plans:)
  in insertRowsPatternA to prevent group-numbering shift (Finding 3)
- state.cts: mirror inline-branch preserve-authored guards onto table-format
  branches in updateCurrentPositionFields — Status table branch checks
  isInList/matchesPattern before replacing; Last Activity table branch
  checks isDateShape/inList, preserving executor-authored narrative prose
  (Finding 2 code-review)
- tests: add three failing-first regression tests confirming each finding

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(#1162,#1163): fold table-format + plan-row regressions into owning module tests

Move bug-1162 cases into tests/state.test.cjs and bug-1163 cases into
tests/roadmap.test.cjs under named regression describe blocks; delete the
standalone bug-NNNN files and prune their allowlist entries.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* docs(#1156): add changeset fragment for table-format state + roadmap insert fix

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-06-13 21:56:18 -04:00
committed by GitHub
parent 4db185da74
commit 3827054954
6 changed files with 1185 additions and 28 deletions

View File

@@ -10,7 +10,7 @@ const { test, describe, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const { runGsdTools, cleanup } = require('./helpers.cjs');
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
const { createFixture } = require('./fixtures/index.cjs');
describe('state-snapshot command', () => {
@@ -3230,3 +3230,428 @@ describe('state add-roadmap-evolution (bug #1140)', () => {
assert.ok(!/\bat .*\(.*:\d+:\d+\)/.test(result.error || ''), 'no stack trace');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// regressions: table-format STATE.md (#1162)
// ─────────────────────────────────────────────────────────────────────────────
/**
* Minimal STATE.md that uses a pipe-table for the Current Position section.
* This is the format that triggered the "Field not found" silent failure.
*/
function buildTableFormatState(opts) {
const {
status = 'Ready to plan',
phase = '3',
planCount = '4',
lastActivity = '2026-01-01',
} = opts || {};
return [
'---',
'gsd_state_version: 1.0',
'status: planning',
'---',
'',
'# GSD State',
'',
'## Current Position',
'',
'| Field | Value |',
'| --- | --- |',
`| Status | ${status} |`,
`| Phase | ${phase} |`,
`| Total Plans in Phase | ${planCount} |`,
`| Last Activity | ${lastActivity} |`,
'',
'## Accumulated Context',
'',
'Some context here.',
'',
].join('\n');
}
/**
* STATE.md that uses bold inline format (the existing working format).
* Included as a control case to confirm we did not break bold-field support.
*/
function buildBoldFormatState(opts) {
const {
status = 'Ready to plan',
phase = '3',
} = opts || {};
return [
'---',
'gsd_state_version: 1.0',
'status: planning',
'---',
'',
'# GSD State',
'',
'## Current Position',
'',
`**Status:** ${status}`,
`**Phase:** ${phase}`,
'',
].join('\n');
}
describe('regressions: table-format STATE.md (#1162)', () => {
let tmpDir;
let statePath;
beforeEach(() => {
tmpDir = createTempProject('gsd-1162-');
statePath = path.join(tmpDir, '.planning', 'STATE.md');
});
afterEach(() => {
cleanup(tmpDir);
});
// ── Happy path: table-format field replacement ──────────────────────────
test('state update rewrites table-cell Status value', () => {
fs.writeFileSync(statePath, buildTableFormatState({ status: 'Ready to plan' }));
const result = runGsdTools(['state', 'update', 'Status', 'Ready to execute'], tmpDir);
// Command must report success
assert.ok(result.success, `Command failed: ${result.error}`);
const parsed = JSON.parse(result.output);
assert.equal(parsed.updated, true, 'expected updated:true but got: ' + JSON.stringify(parsed));
// The table cell must be rewritten on disk
const written = fs.readFileSync(statePath, 'utf-8');
assert.ok(
written.includes('| Status | Ready to execute |'),
'Table cell not rewritten. STATE.md content:\n' + written,
);
// Original value must be gone
assert.ok(
!written.includes('| Status | Ready to plan |'),
'Old table cell value still present in STATE.md',
);
});
test('state update rewrites table-cell value for arbitrary field', () => {
fs.writeFileSync(statePath, buildTableFormatState({ lastActivity: '2026-01-01' }));
const result = runGsdTools(['state', 'update', 'Last Activity', '2026-06-13'], tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const parsed = JSON.parse(result.output);
assert.equal(parsed.updated, true, 'expected updated:true');
const written = fs.readFileSync(statePath, 'utf-8');
assert.ok(
written.includes('| Last Activity | 2026-06-13 |'),
'Last Activity table cell not rewritten. Content:\n' + written,
);
});
test('state update is case-insensitive for table field names', () => {
// Table may have lowercase "status" in the first cell
const content = [
'---',
'gsd_state_version: 1.0',
'---',
'',
'## Current Position',
'',
'| Field | Value |',
'| --- | --- |',
'| status | Ready to plan |',
'',
].join('\n');
fs.writeFileSync(statePath, content);
const result = runGsdTools(['state', 'update', 'status', 'Ready to execute'], tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const parsed = JSON.parse(result.output);
assert.equal(parsed.updated, true, 'case-insensitive table match failed');
});
// ── Negative: separator row must NOT be treated as a field ───────────────
test('separator row | --- | --- | is not matched as a field', () => {
// The field name "---" is rejected by the field-name validator before
// stateReplaceField is even called. The command exits with a non-zero
// status and a plain-text error, NOT a JSON { updated: false } result.
// The key invariant is that the file is never corrupted.
const originalContent = buildTableFormatState();
fs.writeFileSync(statePath, originalContent);
const result = runGsdTools(['state', 'update', '---', 'injected'], tmpDir);
// The validator rejects '---' as an invalid field name — command must fail
// OR, if somehow the command succeeds, updated must be false.
if (result.success) {
// Unlikely path — if the validator is relaxed in future, still must not update.
let parsed;
try { parsed = JSON.parse(result.output); } catch { parsed = null; }
if (parsed) {
assert.equal(parsed.updated, false, 'separator row incorrectly matched as a field');
}
}
// Either way: the file must be untouched (no 'injected' value written)
const written = fs.readFileSync(statePath, 'utf-8');
assert.ok(!written.includes('injected'), 'separator row replacement leaked into file');
});
// ── Regression: bold-format still works after the fix ────────────────────
test('state update bold-format still works after table support added', () => {
fs.writeFileSync(statePath, buildBoldFormatState({ status: 'Ready to plan' }));
const result = runGsdTools(['state', 'update', 'Status', 'Ready to execute'], tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const parsed = JSON.parse(result.output);
assert.equal(parsed.updated, true, 'bold-format update broken after fix');
const written = fs.readFileSync(statePath, 'utf-8');
assert.ok(
written.includes('**Status:** Ready to execute'),
'Bold-format field not rewritten. Content:\n' + written,
);
});
// ── updateCurrentPositionFields table support ─────────────────────────────
test('state planned-phase updates table-cell Status via updateCurrentPositionFields', () => {
// cmdStatePlannedPhase uses updateCurrentPositionFields internally;
// verify it also handles the table format.
const content = [
'---',
'gsd_state_version: 1.0',
'status: planning',
'---',
'',
'# GSD State',
'',
'**Status:** Ready to plan',
'**Total Plans in Phase:** 0',
'**Last Activity:** 2026-01-01',
'**Last Activity Description:** initial',
'',
'## Current Position',
'',
'| Field | Value |',
'| --- | --- |',
'| Status | Ready to plan |',
'| Last Activity | 2026-01-01 |',
'',
].join('\n');
fs.writeFileSync(statePath, content);
// Create a minimal phase dir so planned-phase can count plans
const phaseDir = path.join(tmpDir, '.planning', 'phases', '1-test-phase');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '1-01-PLAN.md'), '# Plan 1');
const result = runGsdTools(['state', 'planned-phase', '1', '--plan-count', '1'], tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const written = fs.readFileSync(statePath, 'utf-8');
// The Current Position table cell should now be "Ready to execute"
assert.ok(
written.includes('| Status | Ready to execute |'),
'planned-phase did not update table-cell Status. Content:\n' + written,
);
});
// ── Adversarial / edge cases ──────────────────────────────────────────────
test('table field with extra whitespace in cells is handled', () => {
const content = [
'---',
'gsd_state_version: 1.0',
'---',
'',
'## Current Position',
'',
'| Status | Ready to plan |',
'',
].join('\n');
fs.writeFileSync(statePath, content);
const result = runGsdTools(['state', 'update', 'Status', 'Ready to execute'], tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const parsed = JSON.parse(result.output);
assert.equal(parsed.updated, true, 'extra-whitespace table cell not matched');
});
test('updating one row in a multi-row table does not corrupt adjacent rows', () => {
// Regression: updating `Status` must leave the `Phase` row untouched.
// NOTE: values containing literal '|' (e.g., "blocked | waiting") are NOT
// supported — the current value regex [^|\n]*? stops at the first pipe.
// Escaped-pipe values are out of scope for single-token status fields.
const content = [
'---',
'gsd_state_version: 1.0',
'---',
'',
'## Current Position',
'',
'| Status | Ready to plan |',
'| Phase | 3 |',
'',
].join('\n');
fs.writeFileSync(statePath, content);
// Normal replacement — verify Phase row is untouched
const result = runGsdTools(['state', 'update', 'Status', 'Ready to execute'], tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const written = fs.readFileSync(statePath, 'utf-8');
assert.ok(written.includes('| Phase | 3 |'), 'Phase row was corrupted during Status update');
});
test('CRLF line endings in table format are handled', () => {
const content = buildTableFormatState({ status: 'Ready to plan' }).replace(/\n/g, '\r\n');
fs.writeFileSync(statePath, content);
const result = runGsdTools(['state', 'update', 'Status', 'Ready to execute'], tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const parsed = JSON.parse(result.output);
assert.equal(parsed.updated, true, 'CRLF table format not handled');
});
test('missing STATE.md returns updated:false gracefully', () => {
// No STATE.md written — verify the command does not throw
const missingDir = createTempProject('gsd-1162-missing-');
try {
const result = runGsdTools(['state', 'update', 'Status', 'Ready to execute'], missingDir);
const parsed = JSON.parse(result.output);
assert.equal(parsed.updated, false, 'missing STATE.md should return updated:false');
} finally {
cleanup(missingDir);
}
});
});
describe('regressions: table-format STATE.md (#1162) — updateCurrentPositionFields preserve-authored invariants', () => {
let tmpDir;
let statePath;
beforeEach(() => {
tmpDir = createTempProject('gsd-1162-f2-');
statePath = path.join(tmpDir, '.planning', 'STATE.md');
});
afterEach(() => {
cleanup(tmpDir);
});
// Helper: a STATE.md with table-format Current Position section.
// We use planned-phase to exercise updateCurrentPositionFields indirectly,
// because that is the call-site that writes Status/Last Activity.
function buildMixedFormatState(opts) {
const {
status = 'Ready to plan',
lastActivity = '2026-01-01',
} = opts || {};
return [
'---',
'gsd_state_version: 1.0',
'status: planning',
'---',
'',
'# GSD State',
'',
'**Status:** Ready to plan',
'**Total Plans in Phase:** 0',
`**Last Activity:** ${lastActivity}`,
'**Last Activity Description:** initial',
'',
'## Current Position',
'',
'| Field | Value |',
'| --- | --- |',
`| Status | ${status} |`,
`| Last Activity | ${lastActivity} |`,
'',
].join('\n');
}
// (a) Custom Status in table format must NOT be overwritten by planned-phase.
test('(Finding 2a) custom Status in table format is preserved by updateCurrentPositionFields', () => {
// "Blocked: waiting on infra" is executor-authored — not in KNOWN_TEMPLATE_DEFAULTS.
// planned-phase calls updateCurrentPositionFields with status="Ready to execute".
// The table-format branch must honour the same guard as the inline branch:
// only overwrite when the existing value is a known template default.
const content = buildMixedFormatState({ status: 'Blocked: waiting on infra', lastActivity: '2026-01-01' });
fs.writeFileSync(statePath, content);
const phaseDir = path.join(tmpDir, '.planning', 'phases', '2-test-phase');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '2-01-PLAN.md'), '# Plan\n');
const result = runGsdTools(['state', 'planned-phase', '2', '--plan-count', '1'], tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const written = fs.readFileSync(statePath, 'utf-8');
assert.ok(
written.includes('| Status | Blocked: waiting on infra |'),
'Custom Status was overwritten by updateCurrentPositionFields table branch.\nContent:\n' + written,
);
assert.ok(
!written.includes('| Status | Ready to execute |'),
'Custom Status replaced with Ready to execute in table branch.\nContent:\n' + written,
);
});
// (b) Narrative Last Activity in table format must NOT be overwritten.
test('(Finding 2b) narrative Last Activity in table format is preserved', () => {
// "2026-02-15 -- blocked" has trailing prose — executor-authored.
// planned-phase calls updateCurrentPositionFields with today's ISO date.
// Must be preserved.
const content = buildMixedFormatState({ status: 'Ready to plan', lastActivity: '2026-02-15 -- blocked' });
fs.writeFileSync(statePath, content);
const phaseDir = path.join(tmpDir, '.planning', 'phases', '2-test-phase');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '2-01-PLAN.md'), '# Plan\n');
const result = runGsdTools(['state', 'planned-phase', '2', '--plan-count', '1'], tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const written = fs.readFileSync(statePath, 'utf-8');
assert.ok(
written.includes('| Last Activity | 2026-02-15 -- blocked |'),
'Narrative Last Activity was overwritten in table branch.\nContent:\n' + written,
);
});
// (c) Known-default Status and bare-date Last Activity ARE updated.
test('(Finding 2c) known-default Status and bare-date Last Activity ARE updated in table format', () => {
// "Ready to plan" is a known default; "2026-01-01" is a bare ISO date.
// Both should be replaced by planned-phase.
const content = buildMixedFormatState({ status: 'Ready to plan', lastActivity: '2026-01-01' });
fs.writeFileSync(statePath, content);
const phaseDir = path.join(tmpDir, '.planning', 'phases', '2-test-phase');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '2-01-PLAN.md'), '# Plan\n');
const result = runGsdTools(['state', 'planned-phase', '2', '--plan-count', '1'], tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const written = fs.readFileSync(statePath, 'utf-8');
assert.ok(
written.includes('| Status | Ready to execute |'),
'Known-default Status not updated in table branch.\nContent:\n' + written,
);
// Last Activity should be today's date (not 2026-01-01)
assert.ok(
!written.includes('| Last Activity | 2026-01-01 |'),
'Bare-date Last Activity was NOT updated in table branch.\nContent:\n' + written,
);
});
});