chore(#2143): fail-loud Result + per-surface write-set contract — Phase 3 (#2251)

* chore(#2143): fail-loud Result + per-surface write-set contract — Phase 3

Phase 3 of epic #2143 (ADR-2143 §5/§6). The three target bugs (#2140, #2112,
#2118) were already fixed tactically on next; this introduces the reusable
structural contracts and rewires the primary #2140 site onto them.

- src/write-set.cts (new): the parse `Result<T> = {ok,value|reason}` (§5) and the
  per-surface write-set (`WriteOutcome {surface, applied, requirement?}`,
  `WriteSet`, `writeSetComplete`) (§6). markdown-table.cts now imports + re-exports
  `Result` from here (single source; distinct from command-routing-hub's Result).
- requirements mark-complete (src/milestone.cts): returns a PER-REQUIREMENT,
  per-surface write-set; `write_set_complete` is true only if every surface of
  every requirement applied — structurally forbidding the #2140 OR-into-one-flag
  masking, including across a multi-ID batch (adversarial-review regression).
  Pre-existing output fields unchanged (behaviour-preserving; #2140 already fixed).
- deriveProgressFromRoadmap (src/phase-lifecycle.cts): removed the vestigial
  null-swallowing try/catch (findTableWithColumns never throws) — ADR §5 no-swallow;
  RoadmapProgress return contract unchanged.
- commit --files (#2112) and milestone complete --dry-run (#2118) left as-is
  (single-surface commit / pre-mutation preview — not genuine multi-surface writes).

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

* chore(#2244): backfill changeset PR number (#2251)

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-07-13 20:39:58 -04:00
committed by GitHub
parent efd04716da
commit 2cbf186420
12 changed files with 381 additions and 43 deletions

View File

@@ -3,17 +3,19 @@
* (ADR-2143, epic #2143). Pure functions, Node built-ins only, string-in/value-out,
* no I/O. Compiled by tsc to gsd-core/bin/lib/markdown-table.cjs.
*
* NOTE: the `Result<T>` here is the ADR-2143 parse-result shape {ok,value|reason} —
* deliberately distinct from command-routing-hub's dispatch `Result` {ok,data|kind};
* the two never mix (different modules).
* NOTE: the `Result<T>` here is the ADR-2143 §5 parse-result shape {ok,value|reason},
* now defined once in `./write-set.cjs` (the shared fail-loud + write-set seam) and
* re-exported here so existing importers of `Result` from this module keep working
* unchanged — deliberately distinct from command-routing-hub's dispatch `Result`
* {ok,data|kind}; the two never mix (different modules).
*/
import { collectSection, replaceSection } from './markdown-sectionizer.cjs';
import type { Result } from './write-set.cjs';
export type { Result } from './write-set.cjs';
// ─── Types ────────────────────────────────────────────────────────────────────
export type Result<T> = { ok: true; value: T } | { ok: false; reason: string };
/** A parsed GFM pipe table: header column names + rows addressed by column name. */
export interface MarkdownTable {
columns: string[];

View File

@@ -18,6 +18,8 @@ import { platformWriteSync, platformEnsureDir, execGit, retryRenameSync } from '
import { formatGsdSlash, resolveRuntime } from './runtime-slash.cjs';
import { realClock } from './clock.cjs';
import { transitionCore } from './state-transition.cjs';
import { writeSetComplete } from './write-set.cjs';
import type { WriteSet } from './write-set.cjs';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import ioMod = require('./io.cjs');
const { output, error } = ioMod;
@@ -79,6 +81,18 @@ function cmdRequirementsMarkComplete(cwd: string, reqIdsRaw: string[], raw: bool
// a missing row only counts as drift when a table actually exists.
const hasTable = /^\|\s*Requirement\s*\|/im.test(reqContent);
// ADR-2143 §6 per-surface write-set, tracked PER requirement ID: a
// multi-ID batch must not OR one ID's surface outcome into another's —
// that is the exact #2140 class one level up (an ID whose traceability
// row is absent/unmatched must not have its partial write masked by a
// different ID in the same invocation that fully reconciled). Reported
// additively as `write_set` below — it does not change the existing
// marked_complete/already_complete/not_found/table_unmatched/updated
// computation, which stays byte-for-behaviour identical (#2140's tactical
// fix already surfaces the checkbox-only-partial-write case via
// table_unmatched; this only adds the structured ADR-2143 shape on top).
const writeSet: WriteSet = [];
for (const reqId of reqIds) {
const reqEscaped = escapeRegex(reqId);
@@ -96,6 +110,16 @@ function cmdRequirementsMarkComplete(cwd: string, reqIdsRaw: string[], raw: bool
const tableHit = afterTable !== reqContent;
if (tableHit) reqContent = afterTable;
// ADR-2143 §6 per-ID write-set entries: this ID's checkbox surface is
// always tracked; the traceability surface is tracked only when the file
// has a traceability table at all (same `hasTable` gate the existing
// required-surface logic below uses) — omitted entirely, not a false
// `applied:false`, when no table is required of this file.
writeSet.push({ requirement: reqId, surface: 'checkbox', applied: checkboxHit });
if (hasTable) {
writeSet.push({ requirement: reqId, surface: 'traceability', applied: tableHit });
}
// Coverage of the traceability surface for this ID (computed after any flip).
// hasRow keys on the ID + a second cell (`| ID | <phase> |`) so a bare mention
// of the ID in a non-traceability table does not masquerade as a real row.
@@ -129,6 +153,17 @@ function cmdRequirementsMarkComplete(cwd: string, reqIdsRaw: string[], raw: bool
platformWriteSync(reqPath, reqContent);
}
// ADR-2143 §6: `writeSet` above already carries one WriteOutcome per
// (requirement, surface) this invocation could have written to — per ID,
// not ORed across the batch. `write_set` and `write_set_complete` are
// additive: they do not replace or gate `updated` / `marked_complete` /
// `already_complete` / `not_found` / `table_unmatched`, which remain
// computed exactly as before (see #2140 note above — that fix already
// surfaces a checkbox-only partial write via `table_unmatched`;
// `write_set_complete` is a structured, ADR-2143-shaped read of the SAME
// per-surface, per-ID facts, `false` if ANY id's ANY required surface did
// not apply, since `writeSetComplete` requires EVERY entry to have
// applied, never an OR across surfaces OR across IDs).
output(
{
updated: updated.length > 0,
@@ -137,6 +172,8 @@ function cmdRequirementsMarkComplete(cwd: string, reqIdsRaw: string[], raw: bool
not_found: notFound,
table_unmatched: tableUnmatched,
total: reqIds.length,
write_set: writeSet,
write_set_complete: writeSetComplete(writeSet),
},
raw,
`${updated.length}/${reqIds.length} requirements marked complete`,

View File

@@ -62,43 +62,49 @@ export function deriveProgressFromRoadmap(roadmapContent: string): RoadmapProgre
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;
// ADR-2143 §5 (fail-loud, no null-swallow): this used to be wrapped in a
// try/catch that silently fell through to the existing (null) values on any
// thrown error. `findTableWithColumns`/`parseMarkdownTable` never throw —
// an unparseable or absent table resolves to `null` /
// `{ ok: false, reason }`, not an exception — so the catch was masking
// nothing but dead code paths. Removed per ADR-2143 §5; the public
// `RoadmapProgress` contract (nulls = absent) is unchanged.
//
// 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);
}
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 */ }
totalPlans = totalPlansSum > 0 ? totalPlansSum : null;
}
return { completedPhases, totalPhases, totalPlans };
}

55
src/write-set.cts Normal file
View File

@@ -0,0 +1,55 @@
/**
* Write-Set — shared fail-loud parse `Result` and per-surface write-set
* contracts (ADR-2143, epic #2143). Pure, Node built-ins only, no I/O.
* Compiled by tsc to gsd-core/bin/lib/write-set.cjs.
*
* ADR-2143 §5 (fail-loud parsing, no null-swallow): seam parse operations
* and document-model accessors return a typed `Result<T>` — never a bare
* `null` a caller can mistake for "empty but fine." This is the same
* `{ ok: true; value: T } | { ok: false; reason: string }` shape
* `markdown-table.cts` already defined for `parseMarkdownTable` /
* `appendQuickTaskRow`; this module is now the single source of truth for
* it and `markdown-table.cjs` re-exports the type so existing importers of
* `Result` from that module keep working unchanged.
*
* NOTE: deliberately distinct from command-routing-hub's dispatch `Result`
* (`{ok,data}|{ok:false,kind}`) — the two never mix (different modules,
* different shapes, different purposes).
*
* ADR-2143 §6 (write-set results for multi-surface commands, no
* OR-into-one-flag): a command that mutates more than one surface returns
* an explicit per-surface write-set — `{ surface, applied }` outcomes — and
* its top-level "did this fully succeed" signal is true only if EVERY
* surface in the set applied. ORing independent surfaces into a single
* boolean is the direct anti-pattern that let a checkbox-only partial
* write (#2140) report full success.
*/
export type Result<T> = { ok: true; value: T } | { ok: false; reason: string };
/**
* One surface's outcome within a multi-surface write (ADR-2143 §6).
*
* `requirement` identifies which entity/ID this surface outcome belongs to,
* so a multi-entity command's write-set does not collapse independent
* entities into one aggregate — the §6 "no OR into one flag" rule applies
* per entity too, not just per surface.
*/
export interface WriteOutcome {
surface: string;
applied: boolean;
requirement?: string;
}
/** The full set of per-surface outcomes for one multi-surface write. */
export type WriteSet = WriteOutcome[];
/**
* True only if the write-set is non-empty AND every surface in it applied.
* An empty write-set is never "complete" — there is nothing to be complete
* about, so treating it as vacuously true would let a no-op masquerade as
* a full success (the same OR-into-one-flag class ADR-2143 §6 prohibits).
*/
export function writeSetComplete(ws: WriteSet): boolean {
return ws.length > 0 && ws.every((o) => o.applied);
}