Files
msd-core/src/markdown-table.cts
Tom Boucher c1885df9e5 chore(#2143): prohibition-with-teeth + migrate remaining ad-hoc table sites — Phase 4 (final) (#2253)
* chore(#2143): prohibition-with-teeth + migrate remaining table sites — Phase 4

Phase 4 of epic #2143 (ADR-2143 §7). Completes the markdown table/mutation
consolidation by (a) giving the ad-hoc-parsing prohibition teeth and (b)
migrating the last ad-hoc table sites onto the shared seam.

- src/markdown-table.cts: new formatting-preserving `updateTableCell` primitive
  (self-contained, ragged-row-tolerant header/delimiter/cell-range scan; splices
  only the target cell's raw span, preserving all other bytes incl. padding/CRLF;
  no-op-preserves-padding when a transformer returns the current value). Exports
  splitTableRow/isDelimiterRow/findTableStartOffset for tolerant reuse.
- eslint-rules/no-adhoc-markdown-parsing.cjs: TABLE-REGEX detector extended to
  `new RegExp(<literal|static-template>)`; new `.replace()`-mutation detector for
  roadmap/state/content receivers with a table/section-shaped pattern.
- scripts/lint-table-schema-drift.cjs (wired into lint:ci): fails if a TABLE_SCHEMA
  header drifts from its authored table; tests import its logic (single source).
- Migrated onto the seam (behaviour-preserving vs pre-Phase-4 HEAD, verified
  byte-diff old-vs-new): roadmap.cts cmdRoadmapUpdatePlanProgress, phase.cts
  cmdPhaseComplete + traceability, milestone.cts cmdRequirementsMarkComplete,
  uat.cts read path, state.cts metrics/decisions/By-Phase.
- Incidental correctness gains from the migration: a decoy table can no longer
  swallow a phase-progress update (## Progress scoping); a ragged neighbouring
  row no longer silently aborts an edit; completing integer phase N no longer
  touches a decimal sub-phase N.x row; record-metric no longer drops trailing
  section content or duplicates the ## Performance Metrics section.
- Kept justified allow-adhoc-markdown markers only where genuinely not a table
  (security.cts <|role|> token) or a loose non-GFM section (uat human-verify).

Two orthogonal isolated reviews (correctness/adversarial + security) passed;
correctness found 4 behaviour regressions in the first migration pass, all fixed
and re-verified byte-identical-or-better vs OLD.

Surfaced for maintainer (pre-existing, ambiguous domain logic, NOT changed here):
templates/state.md places a By-Phase table under ## Performance Metrics while
cmdStateRecordMetric assumes a Plan|Duration|Tasks|Files table.

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

* fix(#2143): match traceability row by first-cell value, not Requirement header

Phase 4's migration matched the REQUIREMENTS.md traceability row by a column
literally named `Requirement` (`row['Requirement']`), but real tables head that
column `REQ-ID`. The by-name lookup found nothing, so `phase complete` and
`requirements mark-complete` left the Status cell `Pending` (regressed #2769 /
#2203, caught by gsd-test — 8 failures, both node 22/24).

- src/phase.cts, src/milestone.cts: match the row by its FIRST cell's value
  (the requirement-ID column) regardless of that column's HEADER name, via
  `Object.values(row)[0]` (updateTableCell builds the record in header order).
  This mirrors OLD's first-cell `\|\s*<id>\s*\|` anchor, restoring header-name
  independence while keeping the seam.
- src/milestone.cts hasTable: broadened from `Requirement`-only to also
  recognize `Requirement ID` / `REQ-ID` / `REQ ID` headers, kept in sync with
  the now-positional rowMatch/hasRow so a REQ-ID-headed table participates in
  the ADR-2143 §6 write-set and the #2140 table_unmatched drift check (it was
  silently omitted before — a checkbox-only partial reconcile against a REQ-ID
  table could report as fully reconciled). The `Requirement`-headed path is
  byte-identical to OLD.

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

* test(#2143): replace stale structural milestone guards with behavioural suite

The `milestone.cjs regex global state fix` block was a source-structure guard
(allow-test-rule: structural-regression-guard) — it readFileSync'd the compiled
milestone.cjs and asserted removed regex idioms (`tablePattern.test`,
`afterTable !== reqContent`, `doneTable = new RegExp(...)`). Phase 4's migration
deleted those regexes (table update is now updateTableCell), making the
assertions obsolete. Per the Test Cleanup rule, replace them in-PR with a
behavioural suite driving the compiled CLI:

- multi-ID mark-complete flips all IDs (guards the lastIndex/global-state class),
- Pending->Complete flip under both `REQ-ID` and `Requirement` headers (#2769),
- idempotent already_complete detection with no corruption,
- REQ-ID-headed table participates in write_set (traceability entry, applied),
- REQ-ID-headed table trips #2140 table_unmatched drift on a missing row.

Pruned the now-nonexistent structural-regression-guard entry from the
lint-allow-test-rule-refs allowlist (the source-text-is-the-product entry for
the same file remains valid).

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

* chore(changeset): backfill PR number 2253

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

* fix(#2143): record-metric targets its own metrics table, not By-Phase velocity

`state record-metric` appended its per-plan row (`| Phase 1 P1 | 5min | 3 tasks |
4 files |`) into the FIRST table under `## Performance Metrics` — which on a real
template-derived STATE.md is the By-Phase velocity table `| Phase | Plans | Total
| Avg/Plan |`, polluting it on EVERY plan completion (execute-plan.md:414 is a
per-plan call). The command's own metrics table is `| Plan | Duration | Tasks |
Files |`, which the template does not ship, so the row never reached it; the
scaffold branch also emitted a wrong `| Phase | Plan | Duration | Notes |` header
matching neither the row nor the canonical table.

Pre-existing (predates Phase 4); surfaced while migrating this site and fixed here
per no-defer, on the user's explicit go-ahead.

- src/state.cts cmdStateRecordMetric: locate the metrics table by its own header
  shape (`Plan|Duration|Tasks|Files`, via splitTableRow/isDelimiterRow) rather
  than "first table in the section". When the section exists but has no metrics
  table (only the By-Phase table), self-heal by appending a fresh **Per-Plan
  Metrics:** table to the END of the section body — By-Phase table, Recent Trend
  and footer preserved verbatim, no duplicate `## Performance Metrics` heading,
  created stays false. Absent-section scaffold header corrected to the canonical
  `| Plan | Duration | Tasks | Files |`. Ragged-tolerance + None-yet preserved.
- Not touching templates/state.md (golden-install-parity hashed) — record-metric
  self-creates the table on first use instead.

Failing-first regression test (tests/state.test.cjs) demonstrates the By-Phase
pollution on the pre-fix build, then green after. Verified: no pollution, self-
heal idempotency, both-tables isolation, content/heading preservation, flags,
None-yet, corrected scaffold header (23-check adversarial harness + all existing
record-metric scenarios).

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

* feat(#2143): deleteSection seam primitive (level-bounded whole-section removal)

ADR-2143 §4 shipped withSection/collectSection (replace a section BODY) but no
way to DELETE a section (heading + body). Phase 4 suppressed the phase-remove
section delete instead of building it. deleteSection(content, predicate, opts)
locates the section via the collectSection machinery and splices out from the
heading's start offset to the next same-or-higher-level heading — so a level-3
`### Phase N` delete stops at a following level-2 `## Progress`, never past it.

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

* fix(#2143): phase remove no longer deletes ## Progress on last-phase removal

updateRoadmapAfterPhaseRemoval deleted a `### Phase N` detail section with a
greedy raw regex whose lazy scan, on the LAST phase, ran to EOF and destroyed
the following `## Progress` heading and its entire tracking table — silent data
loss, uncovered by tests (removal tests only exercised a middle phase). Migrated
onto the new deleteSection seam (level-bounded, stops at `## Progress`); dropped
the allow-adhoc-markdown SECTION-DELETION suppression. Failing-first regression
(tests/phase.test.cjs) removes the LAST phase and asserts the ## Progress heading
+ table survive; middle-phase removal is byte-identical.

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

* feat(#2143): deleteTableRow seam primitive (row removal, ragged-tolerant)

Sibling of updateTableCell: locates the first GFM table, matches a DATA row by
predicate (ragged-tolerant record build, header order), and splices out that
row's whole line preserving every other byte. Returns {ok:false,reason} on no
table / no match. Enables migrating the phase-remove Progress-table row delete
off its ad-hoc regex (ADR-2143 §7 — the "future row-delete seam" Phase 4 punted).

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

* fix(#2143): phase remove deletes the Progress row via deleteTableRow

The Progress-table row delete used a whole-document regex with two defects:
(a) `\.?\s` required whitespace after the phase number, so a COMPACT row
`|2|Beta|` was never deleted (stale row left behind); (b) unscoped — it could
strike a row in a different table (e.g. an earlier `| Phase | Requirements |`
table). Migrated onto deleteTableRow, scoped to the `## Progress` section
(mirrors deriveProgressFromRoadmap), matching the row by first-cell phase number
(integer zero-pad-insensitive; decimal exact; removing `2` never touches `2.5`).
Both allow-adhoc-markdown suppressions removed. New behavioural tests: compact
unpadded row deleted; padded byte-parity on the surviving rows (their ordinal
correctly renumbers via the pre-existing renumber block).

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

* fix(#2143): deleteTableRow leaves no dangling newline on last EOL-less row

Deleting the final row of a table with no trailing EOL sliced from the row's
start to end-of-string, stranding the newline that terminated the previous line.
Back rowStart over the preceding \r?\n in that branch so the table ends cleanly.
(Caught by the primitive's own unit test on gsd-test; local scenario checks
missed the no-trailing-EOL edge.)

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

* fix(#2143): migrate read-only section-collects onto collectSection

Six hand-rolled `## Section` read-extract regexes replaced by the collectSection
seam (behaviour-preserving; extracted bodies feed the same downstream parsers):
state.cts matchSessionSection (## Session / ## Session Continuity) + ## Blockers,
smart-entry.cts ## Blockers, audit.cts ## Current Focus + ## Open Questions.
Removes 6 allow-adhoc-markdown "pending #1372" suppressions. Incidental fix: the
old Session regex `## Session[ \t]*\n` silently failed on a CRLF `## Session\r\n`
heading (Windows STATE.md), nulling all session fields; collectSection is
CRLF-safe, so session state now resolves on Windows.

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

* fix(#2143): fence-safe state-transition section writes + dedup stripFrontmatter

- milestoneCompleteCore's `## Current Position` and `## Operator Next Steps`
  section resets used fence-blind raw regexes that a fenced `##` inside the body
  could truncate/mis-target (#2130/#2067/#2080 class). Migrated onto a
  fence-aware tokenizeHeadings-based helper (resetSectionVerbatim) that is
  byte-identical to the old output on the canonical path (9/9 fixtures) and
  correctly ignores a fenced fake heading (proven robustness gain).
- mutateCurrentPositionFirstTime: hand-rolled locate+splice → collectSection +
  replaceSection (byte-parity).
- stripFrontmatter was inlined byte-identically in state.cts AND
  state-transition.cts; hoisted the single canonical copy into frontmatter.cts
  (both call sites now import it) + unit tests — eliminates the divergence risk
  per CLAUDE.md "Generative Fix Divergence". Removes 3 allow-adhoc-markdown /
  #1372 markers.

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

* fix(#2143): name-address By-Phase sum + uat parse, eslint recall hole, catches

- state.cts By-Phase "Total plans completed" sum: positional 2nd-cell regex →
  name-addressed splitTableRow read (correct on a reordered header, where the
  old code silently summed the wrong column). Marker removed.
- uat.cts parseVerificationItems: loose pipe regex → splitTableRow within the
  existing table/numbered/bullet union scan (item list byte-identical; does NOT
  reintroduce the reverted strict-parseMarkdownTable item-drop). Marker removed.
- eslint no-adhoc-markdown-parsing: close the `new RegExp(identifier)` recall
  hole — resolve a const-declared table-shaped regex identifier (mirrors the
  .replace() detector) + RuleTester cases; param/call args stay out (boundary).
- commands.cts: delete a lying comment that claimed the scaffold date "stays on
  raw UTC / deferred" — #2136 already moved it to realClock.localToday().
- Empty catches (classified, not blind-swept): removed 4 dead try/catch;
  fixed 3 error-hiding (phase-insert decimal-dir I/O collision now fails loud;
  phase-remove rename partial-failure surfaced; milestone-archive true count via
  finally); left best-effort swallows with justification comments.

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

* fix(#2143): extractFencedBlock seam + migrate api-coverage named fence

parseCoverageMatrix extracted its ```coverage fenced block with an ad-hoc regex
(the last real allow-adhoc-markdown suppression). Added extractFencedBlock to the
markdown-sectionizer seam (reuses stripFencedCode's CommonMark fence engine —
info-string match, ~~~/backtick, nesting, indent) and migrated onto it; byte-
parity on the parsed CoverageMatrix across 8 fixtures. Only security.cts:367
(a genuine `<|role|>` protocol-token false-positive, not a GFM table) remains
marked in src/ — the "prohibition with teeth" goal (nothing grandfathered but a
true FP) is met.

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

* fix(#2143): By-Phase row insert is name-addressed (insertTableRow seam)

updatePerformanceMetricsSection's INSERT-new-row branch located the By-Phase
table with a canonical-column-order-only regex + a hardcoded positional row
literal, so on a reordered header it silently inserted nothing — inconsistent
with the now name-addressed UPDATE and SUM halves of the same function. Added
insertTableRow (markdown-table seam sibling of updateTableCell/deleteTableRow:
name-addressed, header-order-agnostic, EOL-preserving) and migrated the branch
onto it, mapping By-Phase values by column NAME. Canonical-order output is
byte-identical; a reordered header now inserts a correctly-mapped row; a
pre-existing CRLF mixed-EOL splice glitch is incidentally fixed. Retired the
now-dead byPhaseTablePattern const.

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

* fix(#2143): phase-list checkbox flip via updateBullet seam

Added updateBullet (markdown-sectionizer): a fence-aware, offset-tracked
single-bullet write primitive (GFM 1–4-space marker tolerance) — the write
counterpart to read-only iterateBullets. Migrated mutateMilestonePhase's
phase-list checkbox flip (`- [ ] Phase N …` → `- [x] … (completed <date>)`)
off its whole-slice regex onto it, same milestone-slice scope + clock seam.
Byte-identical across simple / idempotent / metachar-title / double-space /
CRLF scenarios.

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

* fix(#2143): scope the Progress-ordinal renumber to ## Progress via seam

phase remove's integer-renumber decremented Progress-table phase ordinals with a
whole-document `content.replace(/(\|\s*)(\d+)(\.\s)/g, …)` — unscoped, so it also
rewrote any `| N. …` cell in an unrelated/decoy table (same class as the batch-2
row-delete scoping bug). Migrated onto updateTableCell, scoped to the ## Progress
section, decrementing each affected row's leading phase ordinal by column name.
Byte-identical on canonical Progress tables + multi-row + decimal-sibling cases;
a decoy `| 3. … |` row before ## Progress is now correctly left untouched. The
sibling heading / checkbox-bullet / PLAN.md-filename / Depends-on-prose renumbers
are not GFM-table mutations (outside ADR-2143's table/section mandate) — left as-is.

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

* fix(#2143): review fixes — scope traceability write, restore Current Position H3-stop

Adversarial review of the remediation (BLOCK verdict) — all 9 findings fixed:
- F1 (BLOCKER): requirements mark-complete / phase complete flipped the checkbox
  but NOT the traceability row on the shipped template, because updateTableCell
  bound to the FIRST table (## Out of Scope, no Status column) instead of the
  ## Traceability table — the #2140 silent-divergence class, re-introduced by the
  seam migration and missed by tests (fixtures had Traceability first). Scoped
  the write + hasRow probe to the ## Traceability section slice (updateTraceability
  Cell helper) in milestone.cts + phase.cts. Failing-first tests on the
  Out-of-Scope-before-Traceability layout; the #2769 first-cell match preserved.
- F2 (MAJOR): mutateCurrentPositionFirstTime restored to locateCurrentPosition
  (STOP_H2_PLUS) — collectSection's default H2-stop swallowed a level-3 subsection
  and the field regexes clobbered it (#2130 class).
- F3/F8: Progress-ordinal renumber re-escapes via escapeCell + keys padding
  recovery by row index (was de-escaping `\|` and losing padding on dup values).
- F4: insertTableRow escapes cell values internally.
- F5: updateBullet accepts a tab after the marker (`[ \t]{1,4}`).
- F7: resetSectionVerbatim consumes CRLF blank lines (byte-parity on CRLF).
- F6/F9: corrected two misleading comments.

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

* chore(changeset): data-loss + CRLF-session user-facing fixes (#2253)

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

* test(#2143): de-flake the G10 windsurf ReDoS-guard wall-clock assertion

The G10 test asserted `elapsedMs < 1000` for a 200k-char payload — a wall-clock
assertion (CLAUDE.md: never assert on wall-clock time) that flaked on a loaded
node24 bench at ~1.1s. It was redundant: runHook's spawnSync `timeout: 10000`
already SIGKILLs a catastrophic-backtracking hook, so the exit-0 assertion is the
real ReDoS guard. Removed the timing assertion; kept exit-0 + documented the
subprocess-timeout mechanism. Surfaced (not caused) by this branch's gsd-test
runs loading the bench; unrelated to the markdown-parsing changes but fixed in
place per the no-flaky-tests rule.

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

---------

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

801 lines
33 KiB
TypeScript

/**
* Markdown Table Model — canonical GFM table parsing + schema registry seam
* (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 §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 ────────────────────────────────────────────────────────────────────
/** A parsed GFM pipe table: header column names + rows addressed by column name. */
export interface MarkdownTable {
columns: string[];
rows: Record<string, string>[];
}
/** One recognised header-shape variant of a canonical table kind. */
export interface CanonicalTableVariant {
label: string;
columns: string[];
}
// ─── Schema registry ──────────────────────────────────────────────────────────
/**
* Canonical column-header shapes for every GFM table GSD parses or generates.
* Each entry in `TABLE_SCHEMAS[id]` is one accepted variant (exact column names,
* in order); `matchTableSchema` resolves a parsed header back to `{id, label}`.
*
* This registry is the single source of truth — a parity test
* (tests/markdown-table.test.cjs) asserts every variant's header appears
* verbatim in the template/workflow file that generates it, so the registry
* and the templates can never silently drift (ADR-2143 §3 Generative-Fix-
* Divergence guard).
*/
export const TABLE_SCHEMAS: Record<string, CanonicalTableVariant[]> = {
RoadmapProgress: [
{ label: 'flat', columns: ['Phase', 'Plans Complete', 'Status', 'Completed'] },
{
label: 'milestone-grouped',
columns: ['Phase', 'Milestone', 'Plans Complete', 'Status', 'Completed'],
},
],
RequirementsTraceability: [
{ label: 'default', columns: ['Requirement', 'Phase', 'Status'] },
],
QuickTasks: [
{ label: 'no-status', columns: ['#', 'Description', 'Date', 'Commit', 'Directory'] },
{
label: 'with-status',
columns: ['#', 'Description', 'Date', 'Commit', 'Status', 'Directory'],
},
],
Security: [
{ label: 'trust-boundaries', columns: ['Boundary', 'Description', 'Data Crossing'] },
{
label: 'threat-register',
columns: [
'Threat ID',
'Category',
'Component',
'Severity',
'Disposition',
'Mitigation',
'Status',
],
},
{
label: 'accepted-risks',
columns: ['Risk ID', 'Threat Ref', 'Rationale', 'Accepted By', 'Date'],
},
{
label: 'audit-trail',
columns: ['Audit Date', 'Threats Total', 'Closed', 'Open', 'Run By'],
},
],
};
/**
* Resolve a parsed table's header columns to the canonical schema it matches
* (exact column names, same length, same order), else `null`.
*/
export function matchTableSchema(columns: string[]): { id: string; label: string } | null {
for (const [id, variants] of Object.entries(TABLE_SCHEMAS)) {
for (const variant of variants) {
if (
variant.columns.length === columns.length
&& variant.columns.every((col, idx) => col === columns[idx])
) {
return { id, label: variant.label };
}
}
}
return null;
}
// ─── Parsing ──────────────────────────────────────────────────────────────────
/**
* Split one GFM table row line into trimmed cell strings.
* Strips one leading and one trailing `|`, splits on unescaped `|`, trims
* each cell, and unescapes `\\` back to `\` and `\|` back to `|` (the exact
* reverse of `escapeCell`'s `\`->`\\` then `|`->`\|` order below), so cell
* values round-trip exactly — including literal backslashes.
*/
export function splitTableRow(line: string): string[] {
let stripped = line.trim();
if (stripped.startsWith('|')) stripped = stripped.slice(1);
if (stripped.endsWith('|')) stripped = stripped.slice(0, -1);
return stripped.split(/(?<!\\)\|/).map((cell) => cell.trim().replace(/\\([\\|])/g, '$1'));
}
/**
* True when every delimiter cell matches GFM's `:?-{1,}:?` shape (spaces
* removed). Exported (alongside `splitTableRow`) so callers that need their
* own ragged-tolerant header/delimiter detection — e.g. state.cts's
* `cmdStateRecordMetric` row-append, which must recognize an existing table
* without requiring every DATA row to also parse cleanly (#2245 Blocker 2) —
* reuse the exact same header/delimiter-shape check `parseMarkdownTable` uses,
* instead of re-deriving it and risking divergence.
*/
export function isDelimiterRow(cells: string[]): boolean {
return cells.every((cell) => /^:?-{1,}:?$/.test(cell.replace(/\s+/g, '')));
}
/**
* Parse the FIRST GFM pipe table found in `sectionText`.
*
* Defensive by design: never throws — every malformed shape (no table,
* missing/misaligned delimiter row, ragged data row) returns a typed
* `{ok:false, reason}` instead of silently coercing or dropping data
* (ADR-2143 §3 — ragged rows are errors, not silent).
*
* Scope note: GSD planning tables (STATE.md/ROADMAP.md/requirements.md/
* SECURITY.md) are always fully-piped (leading + trailing `|` on every row)
* and non-indented — this parser targets THAT shape, not arbitrary
* CommonMark (which also allows non-piped rows and up to 3 leading spaces).
*/
export function parseMarkdownTable(sectionText: string): Result<MarkdownTable> {
if (typeof sectionText !== 'string' || sectionText.trim() === '') {
return { ok: false, reason: 'empty or non-string input' };
}
const lines = sectionText.split(/\r?\n/);
let headerIdx = -1;
for (let i = 0; i < lines.length; i++) {
const trimmed = lines[i].trim();
if (trimmed.startsWith('|') && trimmed.indexOf('|', 1) !== -1) {
headerIdx = i;
break;
}
}
if (headerIdx === -1) {
return { ok: false, reason: 'no table found' };
}
const columns = splitTableRow(lines[headerIdx]);
const delimiterLine = lines[headerIdx + 1];
if (delimiterLine === undefined || !delimiterLine.trim().startsWith('|')) {
return { ok: false, reason: 'missing delimiter row' };
}
const delimiterCells = splitTableRow(delimiterLine);
if (!isDelimiterRow(delimiterCells)) {
return { ok: false, reason: 'missing delimiter row' };
}
if (delimiterCells.length !== columns.length) {
return { ok: false, reason: 'delimiter/header column count mismatch' };
}
const rows: Record<string, string>[] = [];
let rowNum = 0;
for (let i = headerIdx + 2; i < lines.length; i++) {
const trimmed = lines[i].trim();
if (!trimmed.startsWith('|')) break;
rowNum += 1;
const cells = splitTableRow(lines[i]);
if (cells.length !== columns.length) {
return {
ok: false,
reason: `row ${rowNum} has ${cells.length} cells, expected ${columns.length}`,
};
}
const row: Record<string, string> = {};
columns.forEach((col, idx) => {
row[col] = cells[idx];
});
rows.push(row);
}
return { ok: true, value: { columns, rows } };
}
// ─── updateTableCell (ADR-2143 §7 formatting-preserving cell write) ──────────
/** One line of `text`, with its absolute start offset and original EOL length. */
interface LineOffset {
line: string;
start: number;
}
/**
* Split `text` into lines exactly like `.split(/\r?\n/)` (bare `\r` is NOT a
* line break, matching `parseMarkdownTable`), tracking each line's absolute
* start offset in `text` so cell ranges can be computed relative to the
* ORIGINAL string, not the trimmed/relative line.
*/
function splitLinesWithOffsets(text: string): LineOffset[] {
const result: LineOffset[] = [];
let start = 0;
const re = /\r\n|\n/g;
let m: RegExpExecArray | null;
while ((m = re.exec(text)) !== null) {
result.push({ line: text.slice(start, m.index), start });
start = m.index + m[0].length;
}
result.push({ line: text.slice(start), start });
return result;
}
/**
* Cell range within one row: `text.slice(start, end)` is the RAW cell text
* (untrimmed, still `\`-escaped) between its two delimiting `|` characters.
*/
interface CellRange {
start: number;
end: number;
}
/**
* Split one GFM table row LINE into raw cell ranges, absolute to the original
* `text` the line was sliced from (`lineStart` = that line's start offset).
* Mirrors `splitTableRow`'s trim + strip-leading/trailing-pipe + unescaped-pipe
* split EXACTLY, but returns character ranges instead of trimmed values, so a
* caller can splice a replacement into the original string byte-for-byte.
*/
function splitTableRowRanges(line: string, lineStart: number): CellRange[] {
const leftTrim = /^\s*/.exec(line)![0].length;
const rightTrim = /\s*$/.exec(line)![0].length;
let stripped = line.slice(leftTrim, line.length - rightTrim);
let strippedStart = lineStart + leftTrim;
if (stripped.startsWith('|')) {
stripped = stripped.slice(1);
strippedStart += 1;
}
if (stripped.endsWith('|')) {
stripped = stripped.slice(0, -1);
}
const cells: CellRange[] = [];
const re = /(?<!\\)\|/g;
let cellStartRel = 0;
let m: RegExpExecArray | null;
while ((m = re.exec(stripped)) !== null) {
cells.push({ start: strippedStart + cellStartRel, end: strippedStart + m.index });
cellStartRel = m.index + 1;
}
cells.push({ start: strippedStart + cellStartRel, end: strippedStart + stripped.length });
return cells;
}
/** Unescape one raw (still-`\`-escaped) cell/column-name span exactly like
* `splitTableRow`: trim, then reverse `\\` -> `\` and `\|` -> `|`. */
function unescapeCellText(raw: string): string {
return raw.trim().replace(/\\([\\|])/g, '$1');
}
/**
* Surgically edit ONE table cell while preserving the table's exact byte
* formatting (ADR-2143 §7). Locates the first GFM table's header + delimiter
* row in `tableText` (own header/delimiter detection — deliberately does NOT
* gate on `parseMarkdownTable(tableText).ok`), finds the first DATA row where
* `match(row, index)` is true, and replaces ONLY that row's `column` cell's
* raw inner text (the span between its two delimiting `|` characters) — every
* other byte of `tableText` (other cells, padding, alignment, EOL style) is
* left BYTE-IDENTICAL. This is deliberately NOT a parse-then-render: a
* render pass would reformat padding/alignment/dates that mutation sites
* (e.g. `status.padEnd(11)`) depend on staying pinned.
*
* Ragged-tolerant by design (#2245 review Fix 2): each data row's
* `{colName:cellText}` record is built ONLY from the columns physically
* present in THAT row — a short row simply omits its trailing column names;
* an over-long row's extra trailing cells are ignored — so `match` is called
* with whatever partial record a ragged row yields. A single sibling row
* whose cell count doesn't match the header must never silently no-op the
* whole write (the prior `parseMarkdownTable(tableText).ok` gate failed the
* ENTIRE table — including an otherwise-well-formed target row — the moment
* ANY other row in the same table was ragged). A row that matches on content
* but is too short to physically contain `column` has no cell to splice
* into, so it cannot be selected; the scan continues past it.
*
* `newValue` is spliced in VERBATIM as the new raw cell span — it is the
* caller's responsibility to supply the fully-formatted text (including any
* leading/trailing padding needed to reproduce the table's existing column
* alignment, and to escape a literal `|` or `\` the value might contain via
* the same convention `splitTableRow`/`escapeCell` use elsewhere in this
* module). When `newValue` is a function, it receives the CURRENT (trimmed,
* unescaped) cell value — the same value that appears in `match`'s `row`
* argument — and must return the full literal replacement text. Returning
* the current value unchanged is a supported no-op-probe pattern for callers
* that need to know whether (and to what current value) a row matched
* without necessarily writing a new value.
*
* Returns `{ok:false, reason}` only for a genuinely absent/malformed table
* (no header line, or no valid delimiter row immediately below it), an
* unknown `column`, or zero rows satisfying `match` while physically
* containing `column` — never for a ragged sibling row.
*/
export function updateTableCell(
tableText: string,
match: (row: Record<string, string>, index: number) => boolean,
column: string,
newValue: string | ((current: string) => string),
): Result<string> {
const lines = splitLinesWithOffsets(tableText);
let headerIdx = -1;
for (let i = 0; i < lines.length; i++) {
const trimmed = lines[i].line.trim();
if (trimmed.startsWith('|') && trimmed.indexOf('|', 1) !== -1) {
headerIdx = i;
break;
}
}
if (headerIdx === -1) {
return { ok: false, reason: 'no table found' };
}
const delimiterLine = lines[headerIdx + 1]?.line;
if (delimiterLine === undefined || !delimiterLine.trim().startsWith('|')) {
return { ok: false, reason: 'missing delimiter row' };
}
const headerRanges = splitTableRowRanges(lines[headerIdx].line, lines[headerIdx].start);
const columns = headerRanges.map((r) => unescapeCellText(tableText.slice(r.start, r.end)));
const delimiterCells = splitTableRow(delimiterLine);
if (!isDelimiterRow(delimiterCells)) {
return { ok: false, reason: 'missing delimiter row' };
}
if (delimiterCells.length !== columns.length) {
return { ok: false, reason: 'delimiter/header column count mismatch' };
}
if (!columns.includes(column)) {
return { ok: false, reason: `unknown column: ${column}` };
}
const targetColIdx = columns.indexOf(column);
let selectedRange: CellRange | undefined;
let dataRowIndex = 0;
for (let i = headerIdx + 2; i < lines.length; i++) {
const trimmed = lines[i].line.trim();
if (!trimmed.startsWith('|')) break;
const cellRanges = splitTableRowRanges(lines[i].line, lines[i].start);
const record: Record<string, string> = {};
const presentCount = Math.min(cellRanges.length, columns.length);
for (let c = 0; c < presentCount; c++) {
record[columns[c]] = unescapeCellText(tableText.slice(cellRanges[c].start, cellRanges[c].end));
}
if (targetColIdx < cellRanges.length && match(record, dataRowIndex)) {
selectedRange = cellRanges[targetColIdx];
break;
}
dataRowIndex += 1;
}
if (!selectedRange) {
return { ok: false, reason: 'no matching row' };
}
const currentValue = unescapeCellText(tableText.slice(selectedRange.start, selectedRange.end));
const replacement = typeof newValue === 'function' ? newValue(currentValue) : newValue;
// True no-op guard: a function `newValue` that returns `current` UNCHANGED
// (the documented no-op-probe pattern) must leave `tableText` genuinely
// byte-identical, padding included. `current` is already trimmed/unescaped,
// so naively splicing it back in would strip the raw cell's original
// leading/trailing padding — this returns the ORIGINAL text untouched
// instead whenever the callback's answer is "no change".
if (typeof newValue === 'function' && replacement === currentValue) {
return { ok: true, value: tableText };
}
return {
ok: true,
value: tableText.slice(0, selectedRange.start) + replacement + tableText.slice(selectedRange.end),
};
}
// ─── deleteTableRow (ADR-2143 §7 row-removal sibling of updateTableCell) ─────
/**
* Surgically delete ONE whole table row while preserving every other byte of
* `tableText` (ADR-2143 §7, row-removal sibling of `updateTableCell`). Locates
* the first GFM table's header + delimiter row in `tableText` using the exact
* same self-contained, ragged-tolerant scan `updateTableCell` uses (own
* header/delimiter detection — does NOT gate on `parseMarkdownTable(tableText).ok`),
* finds the FIRST data row where `match(row, index)` is true, and splices out
* that row's entire LINE — including its trailing newline (`\r\n` or `\n`,
* whichever terminates it) — from `tableText`. Every other byte (header,
* delimiter, other rows, surrounding prose before/after the table, EOL style)
* is left BYTE-IDENTICAL.
*
* Ragged-tolerant by design, mirroring `updateTableCell` (#2245 review Fix 2):
* each data row's `{colName:cellText}` record is built ONLY from the columns
* physically present in THAT row — a sibling row whose cell count doesn't
* match the header must never abort the whole scan; `match` is simply called
* with whatever partial record a ragged row yields.
*
* Returns `{ok:false, reason}` for a genuinely absent/malformed table (no
* header line, or no valid delimiter row immediately below it) or zero rows
* satisfying `match` — never for a ragged sibling row.
*/
export function deleteTableRow(
tableText: string,
match: (row: Record<string, string>, index: number) => boolean,
): Result<string> {
const lines = splitLinesWithOffsets(tableText);
let headerIdx = -1;
for (let i = 0; i < lines.length; i++) {
const trimmed = lines[i].line.trim();
if (trimmed.startsWith('|') && trimmed.indexOf('|', 1) !== -1) {
headerIdx = i;
break;
}
}
if (headerIdx === -1) {
return { ok: false, reason: 'no table found' };
}
const delimiterLine = lines[headerIdx + 1]?.line;
if (delimiterLine === undefined || !delimiterLine.trim().startsWith('|')) {
return { ok: false, reason: 'missing delimiter row' };
}
const headerRanges = splitTableRowRanges(lines[headerIdx].line, lines[headerIdx].start);
const columns = headerRanges.map((r) => unescapeCellText(tableText.slice(r.start, r.end)));
const delimiterCells = splitTableRow(delimiterLine);
if (!isDelimiterRow(delimiterCells)) {
return { ok: false, reason: 'missing delimiter row' };
}
if (delimiterCells.length !== columns.length) {
return { ok: false, reason: 'delimiter/header column count mismatch' };
}
let selectedLineIdx = -1;
let dataRowIndex = 0;
for (let i = headerIdx + 2; i < lines.length; i++) {
const trimmed = lines[i].line.trim();
if (!trimmed.startsWith('|')) break;
const cellRanges = splitTableRowRanges(lines[i].line, lines[i].start);
const record: Record<string, string> = {};
const presentCount = Math.min(cellRanges.length, columns.length);
for (let c = 0; c < presentCount; c++) {
record[columns[c]] = unescapeCellText(tableText.slice(cellRanges[c].start, cellRanges[c].end));
}
if (match(record, dataRowIndex)) {
selectedLineIdx = i;
break;
}
dataRowIndex += 1;
}
if (selectedLineIdx === -1) {
return { ok: false, reason: 'no matching row' };
}
// Splice out the whole LINE including its trailing EOL: the next line's
// recorded `start` offset is already positioned right after whatever EOL
// (`\r\n` or `\n`) terminated the selected line (see `splitLinesWithOffsets`
// above) — when the selected row is the LAST line in `tableText` (no
// trailing EOL to preserve), fall back to the end of the string.
let rowStart = lines[selectedLineIdx].start;
let rowEnd: number;
if (selectedLineIdx + 1 < lines.length) {
rowEnd = lines[selectedLineIdx + 1].start;
} else {
// The selected row is the LAST line and has no trailing EOL: deleting from
// its `start` to end-of-string would strand the EOL that terminated the
// PREVIOUS line as a dangling newline. Back `rowStart` up over that
// preceding `\n` (and its `\r`, if any) so the table ends cleanly after the
// new last row.
rowEnd = tableText.length;
if (rowStart > 0 && tableText[rowStart - 1] === '\n') {
rowStart -= 1;
if (rowStart > 0 && tableText[rowStart - 1] === '\r') rowStart -= 1;
}
}
return {
ok: true,
value: tableText.slice(0, rowStart) + tableText.slice(rowEnd),
};
}
// ─── insertTableRow (ADR-2143 §7 row-insertion sibling of updateTableCell) ───
/**
* Insert ONE new row into a GFM table while preserving every other byte of
* `tableText` (ADR-2143 §7, row-insertion sibling of `updateTableCell` /
* `deleteTableRow`). Locates the first table's header + delimiter row using
* the exact same self-contained, ragged-tolerant scan the other two use (own
* header/delimiter detection — does NOT gate on `parseMarkdownTable(tableText).ok`),
* builds the new row's cells in the table's ACTUAL header order — each column
* name is passed through `valueFor(column)`; a column for which `valueFor`
* returns `undefined` gets `fallback` (default `'-'`) — and splices it in
* immediately after the table's LAST existing data row (or immediately after
* the delimiter row when the table has zero data rows).
*
* Name-addressed and header-order-agnostic by construction: unlike a
* hardcoded positional literal (`| ${a} | ${b} | - | - |`), this never
* silently no-ops or mis-maps a value onto the wrong column when the header
* is reordered or a superset of the columns `valueFor` knows about (#2245
* audit sibling finding — the bug this helper replaces).
*
* EOL-preserving: the new row reuses whatever exact EOL bytes (`\r\n` or
* `\n`) already terminate the line it's inserted after, so a CRLF document
* stays CRLF and an LF document stays LF — never guessed or hardcoded. When
* the insertion point is at the very end of `tableText` with no following
* line (the table's last row has no trailing EOL of its own), the existing
* last row is terminated with the header/delimiter boundary's own EOL (so it
* gains a terminator, since it is no longer the last line) and the new row
* becomes the new EOL-less tail — mirroring `tableText`'s own convention of
* not forcing a trailing newline that wasn't already there.
*
* Escaping (F4 #2245 review): unlike `updateTableCell`, whose `newValue` is
* spliced in VERBATIM (caller-must-escape — see its doc comment above), every
* value returned by `valueFor` (and `fallback`) IS escaped internally here via
* `escapeCell` before being joined into the new row, exactly like
* `appendQuickTaskRow` below — a caller-supplied name containing a literal
* `|` or `\` cannot silently split the new row into extra columns. Callers do
* NOT need to pre-escape their values.
*
* Returns `{ok:false, reason}` only for a genuinely absent/malformed table
* (no header line, or no valid delimiter row immediately below it) — never
* for a ragged data row (mirrors `updateTableCell`/`deleteTableRow`).
*/
export function insertTableRow(
tableText: string,
valueFor: (column: string) => string | undefined,
fallback = '-',
): Result<string> {
const lines = splitLinesWithOffsets(tableText);
let headerIdx = -1;
for (let i = 0; i < lines.length; i++) {
const trimmed = lines[i].line.trim();
if (trimmed.startsWith('|') && trimmed.indexOf('|', 1) !== -1) {
headerIdx = i;
break;
}
}
if (headerIdx === -1) {
return { ok: false, reason: 'no table found' };
}
const delimiterLine = lines[headerIdx + 1]?.line;
if (delimiterLine === undefined || !delimiterLine.trim().startsWith('|')) {
return { ok: false, reason: 'missing delimiter row' };
}
const delimiterCells = splitTableRow(delimiterLine);
if (!isDelimiterRow(delimiterCells)) {
return { ok: false, reason: 'missing delimiter row' };
}
const headerRanges = splitTableRowRanges(lines[headerIdx].line, lines[headerIdx].start);
const columns = headerRanges.map((r) => unescapeCellText(tableText.slice(r.start, r.end)));
// Header -> delimiter EOL, reused as the fallback terminator for the "insert
// point is at the absolute end of tableText" edge case below.
const headerToDelimiterEol = tableText.slice(
lines[headerIdx].start + lines[headerIdx].line.length,
lines[headerIdx + 1].start,
) || '\n';
let lastLineIdx = headerIdx + 1; // delimiter row, when the table has zero data rows
for (let i = headerIdx + 2; i < lines.length; i++) {
if (!lines[i].line.trim().startsWith('|')) break;
lastLineIdx = i;
}
const newRow = `| ${columns.map((col) => escapeCell(valueFor(col) ?? fallback)).join(' | ')} |`;
if (lastLineIdx + 1 < lines.length) {
// A following line exists — insert the new row, reusing the EXACT EOL
// that already terminates the current last table line, so every other
// byte (including everything after the table) stays untouched.
const insertAt = lines[lastLineIdx + 1].start;
const eol = tableText.slice(lines[lastLineIdx].start + lines[lastLineIdx].line.length, insertAt);
return { ok: true, value: tableText.slice(0, insertAt) + newRow + eol + tableText.slice(insertAt) };
}
// The table's last row is also the last line of `tableText` (no trailing
// EOL). Terminate it now — it needs one, since it is no longer last — and
// append the new row as the new EOL-less tail.
return { ok: true, value: tableText + headerToDelimiterEol + newRow };
}
/**
* Find the first table in `text` whose header matches `TABLE_SCHEMAS[schemaId]`,
* scanning the WHOLE document (not just a named section). Returns `null` when
* no table with that schema is found.
*
* Fixes the regression where callers first located a named heading (e.g.
* `## Progress`) via `collectSection` and only then parsed a table inside it —
* a schema-matching table that lives under a differently-named heading (or no
* heading at all), or that isn't the first table in the document, was
* invisible to that approach. Scanning the whole document by schema restores
* the old "find the progress table anywhere" behaviour while staying
* seam-based (ADR-2143).
*/
export function findTableBySchema(text: string, schemaId: string): MarkdownTable | null {
if (typeof text !== 'string') return null;
const lines = text.split(/\r?\n/);
for (let i = 0; i < lines.length; i++) {
const t = lines[i].trim();
if (!t.startsWith('|') || t.indexOf('|', 1) === -1) continue;
const cols = splitTableRow(lines[i]);
const m = matchTableSchema(cols);
if (m && m.id === schemaId) {
const parsed = parseMarkdownTable(lines.slice(i).join('\n'));
if (parsed.ok) return parsed.value;
}
}
return null;
}
/**
* Find the first GFM table in `text` whose header contains ALL of `required`
* column names (order-independent; extra/injected columns allowed). Returns
* the parsed `MarkdownTable`, or `null` when no table's header is a superset
* of `required`.
*
* Column-NAME/order/count-invariant counterpart to `findTableBySchema` (ADR-2143
* §3 "addressed by NAME, never ordinal"): where `findTableBySchema` requires an
* EXACT canonical column set+order registered in `TABLE_SCHEMAS`, this scans
* for any header that names the required columns, in any order, tolerating
* extra/unrelated injected columns. Cells remain addressable by column NAME
* via the returned `MarkdownTable`.
*/
export function findTableWithColumns(text: string, required: string[]): MarkdownTable | null {
if (typeof text !== 'string') return null;
const lines = text.split(/\r?\n/);
for (let i = 0; i < lines.length; i++) {
const t = lines[i].trim();
if (!t.startsWith('|') || t.indexOf('|', 1) === -1) continue;
const cols = splitTableRow(lines[i]);
if (required.every((rq) => cols.includes(rq))) {
const parsed = parseMarkdownTable(lines.slice(i).join('\n'));
if (parsed.ok) return parsed.value;
}
}
return null;
}
// ─── Quick Tasks row append (#2133) ────────────────────────────────────────────
/**
* Escape one dynamic cell value for insertion into a GFM pipe-table row.
*
* Escapes `\` -> `\\` FIRST, then `|` -> `\|` (in that order, so a literal
* backslash already in the value is never mistaken for part of an escape
* sequence introduced by this function — CodeQL js/incomplete-sanitization).
* `splitTableRow` reverses both in the opposite order (`\\` -> `\` then
* `\|` -> `|`, see line ~114 above), so escaping/unescaping round-trips
* exactly, including literal backslashes. Newlines are collapsed to a
* single space — a raw `|` or embedded newline in a cell value (e.g. a task
* `description`) would otherwise corrupt the table (extra column / a fake
* extra row) and get rejected by the now-fail-loud `parseMarkdownTable` as a
* ragged row.
*
* Exported (F3/#2245 review) so callers of `updateTableCell` that build a
* replacement value by transforming the CURRENT (already-unescaped) cell
* text — e.g. phase.cts's Progress-ordinal renumber, which decrements the
* leading digit of a `Phase` cell like `3. Parser | Lexer` and splices the
* rest of the cell text back verbatim — can re-escape that value before
* returning it from the `newValue` callback, honoring `updateTableCell`'s
* caller-must-re-escape contract (see its doc comment above) instead of
* spliceing a raw, unescaped `|` back into the table and silently splitting
* the cell.
*/
export function escapeCell(value: string): string {
return String(value)
.replace(/\r?\n+/g, ' ')
.replace(/\\/g, '\\\\') // escape the escape char FIRST (CodeQL js/incomplete-sanitization)
.replace(/\|/g, '\\|')
.trim();
}
/** Fields needed to render one "Quick Tasks Completed" row (schema-driven). */
export interface QuickTaskFields {
description: string;
date: string;
commit: string;
status?: string;
directory?: string;
}
/**
* Append one row to STATE.md's "Quick Tasks Completed" table.
*
* Pure, schema-driven replacement for fast.md's inline `awk NF-2` column-count
* guess (#2133, ADR-2143 §3 schema registry / §7 fail-loud unrecognized-schema
* guard). Never touches disk, git, or the clock — callers (the `gsd-tools
* quick-tasks-append` subcommand) compute `date`/`commit` and pass them in.
*
* Fails loud (`{ok:false, reason}`, never a silent skip) when:
* - no "Quick Tasks Completed" heading exists in `stateContent`
* - the section's body doesn't parse as a GFM table (parseMarkdownTable failure)
* - the table's header doesn't match a known `TABLE_SCHEMAS.QuickTasks` variant
* (the old awk arithmetic silently skipped here instead — that silent-skip
* branch is the bug this replaces).
*
* The new row is inserted immediately after the LAST existing table row line
* (or immediately after the header/delimiter when the table has zero data
* rows), preserving any surrounding blank lines/trailing content in the section.
*/
export function appendQuickTaskRow(
stateContent: string,
fields: QuickTaskFields,
): Result<{ content: string; row: string; variant: string }> {
const section = collectSection(stateContent, (h) => /^quick tasks completed$/i.test(h.text.trim()));
if (!section) {
return { ok: false, reason: 'no Quick Tasks Completed section' };
}
const parsed = parseMarkdownTable(section.body);
if (!parsed.ok) {
return { ok: false, reason: `quick-tasks table: ${parsed.reason}` };
}
const match = matchTableSchema(parsed.value.columns);
if (!match || match.id !== 'QuickTasks') {
return {
ok: false,
reason: `unrecognized Quick Tasks schema (columns: ${parsed.value.columns.join(' | ')})`,
};
}
const variant = TABLE_SCHEMAS.QuickTasks.find((v) => v.label === match.label);
const columns = variant ? variant.columns : parsed.value.columns;
const rowNumber = parsed.value.rows.length + 1;
const cellFor = (col: string): string => {
switch (col) {
case '#': return escapeCell(String(rowNumber));
case 'Description': return escapeCell(fields.description);
case 'Date': return escapeCell(fields.date);
case 'Commit': return escapeCell(fields.commit);
case 'Status': return escapeCell(fields.status ?? '—');
case 'Directory': return escapeCell(fields.directory ?? '—');
default: return '—';
}
};
const row = `| ${columns.map(cellFor).join(' | ')} |`;
// Detect the section's EOL BEFORE splitting on /\r?\n/ (which discards it) so
// the rejoin below preserves CRLF instead of downgrading a CRLF section to
// mixed EOL (the inserted `row` itself never contains a newline).
const eol = /\r\n/.test(section.body) ? '\r\n' : '\n';
const lines = section.body.split(/\r?\n/);
let lastTableLineIdx = -1;
for (let i = 0; i < lines.length; i++) {
if (lines[i].trim().startsWith('|')) lastTableLineIdx = i;
}
// lastTableLineIdx is always >= 0 here — parseMarkdownTable already
// confirmed a header + delimiter row exist in this same `section.body`.
const newLines = [
...lines.slice(0, lastTableLineIdx + 1),
row,
...lines.slice(lastTableLineIdx + 1),
];
const newBody = newLines.join(eol);
const content = replaceSection(stateContent, section, newBody);
return { ok: true, value: { content, row, variant: match.label } };
}
// Consumers: require('../gsd-core/bin/lib/markdown-table.cjs')
// Named CJS exports are the canonical surface (ADR-457 .cts → .cjs build-at-publish).