Files
msd-core/src/phase-lifecycle.cts
Tom Boucher d49ac81306 chore(#2143): markdown table model + schema registry + fail-loud pilot — Phase 1 (#2248)
* chore(#2143): markdown table model + schema registry + fail-loud pilot — Phase 1

Phase 1 of epic #2143 (ADR-2143): consolidate markdown table parsing onto a
canonical seam and migrate the pilot reader.

- Add src/markdown-table.cts: parseMarkdownTable (GFM tables -> typed
  {columns, rows} addressed by column NAME; ragged rows are typed parse
  errors, not silent), a single-source TABLE_SCHEMAS registry
  (RoadmapProgress / RequirementsTraceability / QuickTasks / Security, with
  variants under one id), matchTableSchema, and findTableBySchema. Result<T>
  is scoped to this seam (distinct from the dispatch Result).
- Migrate deriveProgressFromRoadmap (src/phase-lifecycle.cts) off the
  position-anchored regex to name-based resolution via the seam — fixes #2137
  (the 5-column milestone-grouped Progress table previously returned all-null).
- Add a schema-backed `gsd-tools quick-tasks-append` subcommand and route
  fast.md's log_to_state through it, retiring the inline `awk NF-2` column
  arithmetic — fixes #2133 (addresses #2012, #2119). Cell values are escaped
  (| and newlines) and the STATE.md read-modify-write is atomic under
  readModifyWriteStateMd (lost-update race, cf. #500/#905/#1230).
- Writer/reader/template parity test guards TABLE_SCHEMAS against drift
  (ADR-2143 §3 Generative-Fix-Divergence).

Registration: .gitignore, eslint.config.mjs, docs/INVENTORY.md +
INVENTORY-MANIFEST.json, CONTEXT.md glossary, docs/CLI-TOOLS.md.

Behaviour-preserving for the canonical 4-column Progress table; the named
bugs are driven fail-first. Extend-never-mutate (ADR-2143 §2).

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

* chore(#2242): backfill changeset PR number (#2248)

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

* fix(#2242): escape backslash before pipe in markdown-table cell escaping

CodeQL js/incomplete-sanitization (high): escapeCell escaped | -> \| but not
the backslash itself. Now escapes \ -> \\ before | -> \|, and splitTableRow
unescapes both \\ -> \ and \| -> | symmetrically so cell values (incl.
literal backslashes) round-trip exactly. Added backslash round-trip tests.

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

* fix(#2242): read ROADMAP Progress table by column name — supersede #2168 ad-hoc scan

Rebase reconciliation with #2168 (the tactical #2137 fix that marked itself
"pending #2143"). deriveProgressFromRoadmap now resolves the Progress table via
a new seam helper findTableWithColumns (first table whose header is a superset of
Phase/Plans Complete/Status/Completed, any order, extra columns ignored) and reads
cells by NAME — order/injection-invariant per ADR-2143 §3 — instead of the exact
TABLE_SCHEMAS match. This satisfies #2168's column-invariance property test while
staying seam-based and preserving its `## Progress` scoping (#2012/#1445).
Ragged Progress tables now resolve to null (ADR-2143 fail-loud); updated the stale
state.test.cjs assertion that predated the Phase-1 migration.

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 20:36:14 -04:00

114 lines
5.0 KiB
TypeScript

/**
* Phase Lifecycle Pure Helpers — pure-computation functions extracted from
* the phase-lifecycle SDK handler (ADR-457 build-at-publish: the hand-written
* bin/lib/phase-lifecycle.cjs collapsed to a TypeScript source of truth).
* Behaviour is preserved byte-for-behaviour from the prior hand-written .cjs;
* only types are added.
*
* I/O adapter pattern (ADR-3524 Section 4): each side supplies its own I/O
* (sync readFileSync for CJS, async readFile for SDK); the pure computation
* logic is shared via this generated artifact.
*
* Scope:
* - deriveProgressFromRoadmap(roadmapContent): count Complete rows => idempotent
* - clampPercent(completed, total): percent with 100 ceiling
*
* These two functions are the root-cause fix for issue #4.
*
* References:
* - ADR-3524 (docs/adr/3524-cjs-sdk-hard-seam.md)
* - Issue #4 (open-gsd/gsd-core)
*/
import { findTableWithColumns } from './markdown-table.cjs';
/** Result of deriveProgressFromRoadmap. */
export interface RoadmapProgress {
completedPhases: number | null;
totalPhases: number | null;
totalPlans: number | null;
}
/**
* Derive completed_phases, total_phases, and total_plans from ROADMAP content.
* Root cause fix for issue #4 — see gen-phase-lifecycle.mjs for full documentation.
*
* ADR-2143 §3 ("addressed by NAME, never ordinal"): the Progress table is
* located via the markdown-table seam's `findTableWithColumns`, which is
* column-NAME/order/count-invariant — it matches the first table whose header
* is a SUPERSET of the canonical `Phase` / `Plans Complete` / `Status` /
* `Completed` names, in any order, tolerating extra/injected unrelated
* columns (#2137's fast-check property test shuffles headers and injects
* columns and asserts the derived counts never change). This supersedes the
* earlier `findTableBySchema` exact-schema lookup, which required an exact
* canonical column SET+ORDER and returned all-null on any reordering or
* injection.
*
* Scoped to the `## Progress` section when the document has one (#2012 decoy
* avoidance — a differently-headed table sharing the same column names must
* not be picked up instead); a headingless milestone slice (#1445) falls back
* to scanning the whole input, preserving the "Progress table not under a
* `## Progress` heading, or not the first table in the document, still
* resolves" behaviour.
*
* Cells are read by column NAME (`r['Status']`, `r['Plans Complete']`,
* `r['Phase']`), fixing #2137 (the old position-based regex assumed "Status"
* was always the 3rd cell and "Plans Complete" the 2nd, which broke for the
* 5-column milestone-grouped variant that inserts a `Milestone` column ahead
* of them).
*/
export function deriveProgressFromRoadmap(roadmapContent: string): RoadmapProgress {
let completedPhases: number | null = null;
let totalPhases: number | null = null;
let totalPlans: number | null = null;
try {
// ADR-2143 §3: read the Progress table by column NAME (order/injection-invariant),
// via the markdown-table seam. Scope to the `## Progress` section when present
// (#2012 decoy avoidance); a headingless milestone slice (#1445) falls back to the
// whole input. Requires the canonical Phase/Plans Complete/Status/Completed columns
// in any order (extra columns ignored) — supersedes findTableBySchema's exact-schema lookup.
const progressMatch = roadmapContent.match(/^##[ \t]+Progress\b/im);
let scoped = roadmapContent;
if (progressMatch && progressMatch.index !== undefined) {
const afterHeading = roadmapContent.slice(progressMatch.index);
const nextHeading = afterHeading.search(/\n#{1,2}[ \t]/);
scoped = nextHeading >= 0 ? afterHeading.slice(0, nextHeading) : afterHeading;
}
const table = findTableWithColumns(scoped, ['Phase', 'Plans Complete', 'Status', 'Completed']);
if (table) {
const allRows = table.rows;
const completed = allRows.filter((r) => /^complete$/i.test((r['Status'] ?? '').trim())).length;
completedPhases = completed > 0 ? completed : null;
// Data rows only (exclude 999.x backlog phases). Mirrors init.cts /^999(?:\.|$)/ filter.
const dataRows = allRows.filter((r) => {
const phase = (r['Phase'] ?? '').trim();
return /^\d/.test(phase) && !/^999\b/.test(phase);
});
totalPhases = dataRows.length > 0 ? dataRows.length : null;
let totalPlansSum = 0;
for (const r of allRows) {
const cell = (r['Plans Complete'] ?? '').trim();
const m = /(\d+)\s*\/\s*(\d+)/.exec(cell);
if (m) totalPlansSum += parseInt(m[2], 10);
}
totalPlans = totalPlansSum > 0 ? totalPlansSum : null;
}
} catch { /* intentionally empty — fall through to existing values */ }
return { completedPhases, totalPhases, totalPlans };
}
/**
* Compute progress percent clamped to 100.
* Root cause fix for issue #4 — see gen-phase-lifecycle.mjs for full documentation.
*/
export function clampPercent(completed: number, total: number): number {
if (!total || total <= 0) return 0;
return Math.min(100, Math.round((completed / total) * 100));
}