@gtrabanco/agentic-workflow 0.4.0 → 4.10.0-canary.20261102.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,12 +21,20 @@
21
21
  * that blocks the caller (feature 66, AC2).
22
22
  */
23
23
 
24
- import { readFileSync } from "node:fs";
25
- import { join, resolve, basename } from "node:path";
24
+ import { readFileSync, existsSync } from "node:fs";
25
+ import { join, resolve, basename, dirname } from "node:path";
26
26
 
27
27
  // Import SDK modules
28
28
  import { create, setSection, evidence_addRow, progress_logEntry, validate } from "../src/edit/UnitDoc.mjs";
29
- import { rowUpsert, annotate as roadmapAnnotate } from "../src/edit/Roadmap.mjs";
29
+ import { rowUpsert, annotate as roadmapAnnotate, checkUnitDoc, ROADMAP_CHECK_CODES } from "../src/edit/Roadmap.mjs";
30
+ import {
31
+ FIX_INDEX_DOCUMENT,
32
+ ROADMAP_DOCUMENT,
33
+ ROADMAP_FIXES_HEADING,
34
+ RoadmapMovedError,
35
+ resolveRoadmapSource,
36
+ roadmapSection,
37
+ } from "../src/index-document.mjs";
30
38
  import { rowAdd } from "../src/edit/Changelog.mjs";
31
39
  import { ceilingRebase } from "../src/edit/Budgets.mjs";
32
40
  import { skillAdd, skillRemove } from "../src/edit/Manifest.mjs";
@@ -68,6 +76,43 @@ function refuse(reason) {
68
76
  process.exit(2);
69
77
  }
70
78
 
79
+ /**
80
+ * Walk up from a unit doc to the repo root until the default index exists; null
81
+ * when no ancestor carries it.
82
+ */
83
+ /** Strip the docs root from a published index path (`docs/X/Y.md` → `X/Y.md`). */
84
+ function relativeToDocs(index) {
85
+ return index.replace(/^docs\//, "");
86
+ }
87
+
88
+ /**
89
+ * The index this tree carries, resolved by the shared reader so the documented
90
+ * rollback lever applies here exactly as it does everywhere else: the reader
91
+ * decides which path is readable, and a tree that carries only the pre-move
92
+ * path while the window is closed is refused with its pointer at the new home.
93
+ * Returns `{ direct, index }`: the path a caller passed explicitly (never
94
+ * resolved through the tree) and the walked-up index path.
95
+ *
96
+ * @param {string} docPath — the unit doc the walk starts from
97
+ * @param {string|undefined} direct — `--roadmap`/`--index`, already read
98
+ */
99
+ function resolveIndex(docPath, direct) {
100
+ if (direct !== undefined) return { direct: resolve(direct), index: null };
101
+ const source = resolveRoadmapSource({ exists: (relative) => findUpIndex(docPath, relative) !== null });
102
+ return { direct: null, index: source === null ? null : findUpIndex(docPath, source.path) };
103
+ }
104
+
105
+ function findUpIndex(docPath, relativeIndex) {
106
+ let dir = dirname(docPath);
107
+ for (;;) {
108
+ const candidate = join(dir, relativeIndex);
109
+ if (existsSync(candidate)) return candidate;
110
+ const parent = dirname(dir);
111
+ if (parent === dir) return null;
112
+ dir = parent;
113
+ }
114
+ }
115
+
71
116
  // ── Router ───────────────────────────────────────────────────────────────
72
117
 
73
118
  const command = process.argv[2];
@@ -210,6 +255,14 @@ switch (command) {
210
255
 
211
256
  // ── roadmap ──────────────────────────────────────────────────────────
212
257
  case "roadmap": {
258
+ // `rowUpsert`/`annotate` take a table path first: a bare first positional is
259
+ // a missing path, never a filename. Resolving the subcommand word would make
260
+ // `roadmap rowUpsert …` open a file literally named `rowUpsert` and refuse
261
+ // with ENOENT, which reads as a missing table instead of a usage error.
262
+ if (rawArgs[0] === "rowUpsert" || rawArgs[0] === "annotate") {
263
+ process.stderr.write(`usage: agentic-workflow roadmap <table-path> ${rawArgs[0]} <json>\n`);
264
+ process.exit(2);
265
+ }
213
266
  const filePath = rawArgs[0] ? resolve(rawArgs[0]) : join(process.cwd(), "ROADMAP.md");
214
267
 
215
268
  if (rawArgs[0] === "rowUpsert" || (rawArgs[0] && rawArgs[1] === "rowUpsert")) {
@@ -232,6 +285,85 @@ switch (command) {
232
285
  } catch (e) {
233
286
  refuse(e.message);
234
287
  }
288
+ } else if (rawArgs[0] === "check" || (rawArgs[0] && rawArgs[1] === "check")) {
289
+ // roadmap check <unit-doc-path> [--roadmap <file>] [--index <file>] [--json]
290
+ // Cross-document check (issue #316): the unit doc's own facts (NN,
291
+ // slug, PR URL) against its index row. Exit contract: 0 consistent,
292
+ // 1 violations (named codes), 2 usage.
293
+ const docArg = rawArgs[1] === "check" ? rawArgs[2] : rawArgs[1];
294
+ if (!docArg) {
295
+ process.stderr.write("usage: agentic-workflow roadmap check <unit-doc-path> [--roadmap <file>] [--index <file>] [--json]\n");
296
+ process.exit(2);
297
+ }
298
+ const flag = (name) => {
299
+ const i = restArgs.indexOf(name);
300
+ return i !== -1 ? restArgs[i + 1] : undefined;
301
+ };
302
+ try {
303
+ const docPath = resolve(docArg);
304
+ const docText = readFileSync(docPath, "utf8");
305
+ // Kind and index defaults follow the doc's own tree position:
306
+ // docs/features → the roadmap, docs/fix → the fix index (its rows are
307
+ // removed once merged, so a missing row there is convention, not
308
+ // contradiction).
309
+ const parts = docPath.split("/");
310
+ const isFix = parts.includes("docs") && parts[parts.indexOf("docs") + 1] === "fix";
311
+ // One index (issue #319): a feature row and a fix row are two tables of
312
+ // the same document, so both kinds default to it and `checkUnitDoc`
313
+ // reads its own table there. A pre-319 tree still has the pre-move
314
+ // roadmap and the standalone fix index under the alias.
315
+ const indexArg = flag("--roadmap") ?? flag("--index");
316
+ // The index is resolved through the shared reader, so the documented
317
+ // rollback lever (`ROADMAP_LEGACY_READ`) governs this consumer too: with
318
+ // the window closed a pre-move-only tree is refused with the pointer at
319
+ // its new home, and with the lever on the same tree reads as before.
320
+ const resolved = resolveIndex(docPath, indexArg);
321
+ const indexPath = resolved.direct ?? resolved.index;
322
+ if (!indexPath) {
323
+ refuse(`index not found for ${docArg} — pass --roadmap <file>`);
324
+ }
325
+ const dirName = basename(dirname(docPath));
326
+ const nn = /^(\d+)/.exec(dirName)?.[1] ?? "";
327
+ const slug = dirName.replace(/^\d+-/, "");
328
+ // A half-migrated tree (issue #319): the consolidated index exists but
329
+ // carries no `## Fixes` table, so the active fix rows are still in the
330
+ // standalone fix index. `MIGRATION.md` and `init-workspace`'s upgrade
331
+ // reference promise that state is readable, so a fix doc falls back to
332
+ // it exactly as the sensor, router, settle validator and ceremony CLI
333
+ // do — never a feature row read as a fix row, never a vacuous pass.
334
+ const indexText = readFileSync(indexPath, "utf8");
335
+ const fixIndexText = isFix && !indexArg && roadmapSection(indexText, ROADMAP_FIXES_HEADING) === null
336
+ ? (() => {
337
+ const standalone = findUpIndex(docPath, relativeToDocs(FIX_INDEX_DOCUMENT));
338
+ return standalone === null ? null : readFileSync(standalone, "utf8");
339
+ })()
340
+ : null;
341
+ const result = checkUnitDoc({
342
+ nn,
343
+ slug,
344
+ kind: isFix ? "fix" : "feature",
345
+ docText,
346
+ indexText: fixIndexText ?? indexText,
347
+ });
348
+ if (parsed.json) {
349
+ console.log(
350
+ JSON.stringify(
351
+ { service: "roadmap", op: "check", path: docPath, schema: "roadmap-table@1", codes: ROADMAP_CHECK_CODES, ok: result.ok, violations: result.violations },
352
+ null,
353
+ 2,
354
+ ),
355
+ );
356
+ } else {
357
+ for (const v of result.violations) {
358
+ console.log(`roadmap-check: ${docPath}:${v.line} ${v.code} — ${v.detail}`);
359
+ }
360
+ console.log(`verdict: ${result.ok ? "PASS" : "FAIL"}`);
361
+ console.log(`violations: ${result.violations.length}`);
362
+ }
363
+ process.exit(result.ok ? 0 : 1);
364
+ } catch (e) {
365
+ refuse(e.message);
366
+ }
235
367
  } else {
236
368
  refuse(`Unknown roadmap operation`);
237
369
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gtrabanco/agentic-workflow",
3
- "version": "0.4.0",
3
+ "version": "4.10.0-canary.20261102.1",
4
4
  "description": "Deterministic runner for the agentic-workflow lane: file services (agwo edit), sensors, guards and receipts. One pinned pure-JS dependency, no native deps, no build step.",
5
5
  "license": "MIT",
6
6
  "author": "Gabriel Trabanco <1969593+gtrabanco@users.noreply.github.com>",
@@ -9,6 +9,18 @@
9
9
 
10
10
  import { readFileSync, writeFileSync } from "node:fs";
11
11
  import { createHash } from "node:crypto";
12
+ import { roadmapTableRows } from "../index-document.mjs";
13
+
14
+ /**
15
+ * The separator rule matches the table that exists in this repository
16
+ * (`|----|------|…`), not only the literal `|---|` — issue #316 found the
17
+ * writer refusing the repo's own roadmap on the old literal match.
18
+ */
19
+ const SEPARATOR_RE = /^\s*\|[-: |]+\|?\s*$/;
20
+
21
+ function isSeparatorLine(line) {
22
+ return SEPARATOR_RE.test(line) && (line.match(/-/g) || []).length >= 3;
23
+ }
12
24
 
13
25
  // ── Helpers ──────────────────────────────────────────────────────────────
14
26
 
@@ -54,8 +66,8 @@ export function rowUpsert(table, { nn, slug, status, dependsOn, description }) {
54
66
  throw new Error("Roadmap table header not found (expected line with | NN |)");
55
67
  }
56
68
 
57
- // Find the separator line (contains "|---|")
58
- const separatorLine = content.split("\n").find((l) => l.includes("|---|"));
69
+ // Find the separator line (a rule of pipes, dashes, colons and spaces)
70
+ const separatorLine = content.split("\n").find(isSeparatorLine);
59
71
  if (!separatorLine) {
60
72
  throw new Error("Roadmap table separator not found (expected line with |---|)");
61
73
  }
@@ -101,6 +113,132 @@ export function rowUpsert(table, { nn, slug, status, dependsOn, description }) {
101
113
  );
102
114
  }
103
115
 
116
+ /**
117
+ * findRow(table, nn) — the full cell parse of one row, for callers that need
118
+ * to re-emit the row through rowUpsert without clobbering the cells they do
119
+ * not touch (the settle write: status changes, everything else preserved).
120
+ *
121
+ * Returns { nn, slug, status, dependsOn, description, line } or null when the
122
+ * row is absent. slug keeps the raw cell (backticks included); callers that
123
+ * compare slugs strip them.
124
+ */
125
+ export function findRow(table, nn) {
126
+ const content = readFileSync(table, "utf8");
127
+ const line = content.split("\n").find((l) => l.trim().startsWith(`| ${nn} |`) && /^\| (\d+) \|/.test(l.trim()));
128
+ if (!line) return null;
129
+ const cells = line.split("|").map((c) => c.trim());
130
+ return {
131
+ nn: cells[1] ?? "",
132
+ slug: cells[2] ?? "",
133
+ status: cells[3] ?? "",
134
+ dependsOn: cells[4] ?? "",
135
+ description: cells[5] ?? "",
136
+ line,
137
+ };
138
+ }
139
+
140
+ /**
141
+ * The closed vocabulary of `roadmap check`. Adding a code is a change to this
142
+ * constant and its tests, never a new string somewhere else.
143
+ */
144
+ export const ROADMAP_CHECK_CODES = Object.freeze(["row-missing", "slug-mismatch", "pr-url-unsettled"]);
145
+
146
+ /** First cell's unit number: roadmap rows carry it bare, fix-index rows link it. */
147
+ function rowNumber(cell) {
148
+ if (/^\d+$/.test(cell)) return cell;
149
+ const m = /issues\/(\d+)|#(\d+)/.exec(cell);
150
+ return m ? m[1] ?? m[2] : null;
151
+ }
152
+
153
+ /**
154
+ * The index rows of one kind, keyed by unit number. Scoped through
155
+ * `roadmapTableRows` so a consolidated document (issue #319) never answers a
156
+ * fix check with a feature row of the same number, while a pre-319 document or
157
+ * a caller-supplied fragment keeps its single-table meaning.
158
+ */
159
+ function parseIndexRows(indexText, kind) {
160
+ const rows = new Map();
161
+ for (const cells of roadmapTableRows(indexText, kind === "fix" ? "fix" : "feature")) {
162
+ if (cells.length < 3) continue;
163
+ const nn = rowNumber(cells[0] ?? "");
164
+ if (!nn) continue;
165
+ rows.set(nn, { status: cells[2] ?? "", slug: (cells[1] ?? "").replace(/`/g, "") });
166
+ }
167
+ return rows;
168
+ }
169
+
170
+ /** The status cell's bare token: the decoration (` · [#N](url)`) never carries it. */
171
+ function statusToken(cell) {
172
+ return cell.replace(/[`*]/g, "").split("·")[0].trim();
173
+ }
174
+
175
+ /**
176
+ * PR URLs on the doc's own lifecycle surfaces: the `## Next`, `## Log` and
177
+ * `## Evidence` sections and the References `- PR:` line the release step
178
+ * writes. URLs quoted elsewhere (cross-references in References prose) are
179
+ * other units' PRs and are never treated as this doc's own.
180
+ */
181
+ function ownPrUrls(docText) {
182
+ const urls = [];
183
+ let section = null;
184
+ docText.split("\n").forEach((line, i) => {
185
+ const heading = /^##\s+(.*)/.exec(line);
186
+ if (heading) section = heading[1].trim();
187
+ const isReferencePr = /^-\s*PR:/.test(line);
188
+ const own = (section && /^(Next|Log|Evidence)\b/i.test(section)) || isReferencePr;
189
+ if (!own) return;
190
+ for (const m of line.matchAll(/https?:\/\/\S*\/pull\/(\d+)/g)) {
191
+ urls.push({
192
+ pr: Number(m[1]),
193
+ url: m[0].replace(/[`),.]+$/, ""),
194
+ line: i + 1,
195
+ where: isReferencePr ? "References" : section,
196
+ });
197
+ }
198
+ });
199
+ return urls;
200
+ }
201
+
202
+ /**
203
+ * checkUnitDoc({ nn, slug, kind, docText, indexText }) — the cross-document
204
+ * comparison between a unit doc's own facts and its index row (issue #316).
205
+ *
206
+ * kind is "feature" (roadmap-indexed) or "fix" (fix-index rows are removed
207
+ * once merged, so an absent row is that index's own convention, not a
208
+ * contradiction). Returns { ok, violations } where every violation carries a
209
+ * code from ROADMAP_CHECK_CODES, the doc line it was detected on and a detail
210
+ * naming the expected settle form `done · [#N](<same url>)`.
211
+ */
212
+ export function checkUnitDoc({ nn, slug, kind, docText, indexText }) {
213
+ const violations = [];
214
+ const row = parseIndexRows(indexText, kind).get(String(nn));
215
+ if (!row) {
216
+ if (kind !== "fix") {
217
+ violations.push({ code: "row-missing", line: 1, detail: `no roadmap row for NN ${nn}` });
218
+ }
219
+ return { ok: violations.length === 0, violations };
220
+ }
221
+ if (slug && row.slug && row.slug !== slug) {
222
+ violations.push({ code: "slug-mismatch", line: 1, detail: `doc folder says '${slug}', row says '${row.slug}'` });
223
+ }
224
+ for (const { pr, url, line, where } of ownPrUrls(docText)) {
225
+ const token = statusToken(row.status);
226
+ // The settle link is backtick-tolerant: the fix index decorates rows as
227
+ // `done` · [`#302`](…), the roadmap as done · [#212](…). Both are the same
228
+ // settle; only the exact URL is compared, never the decoration.
229
+ const settled =
230
+ token === "done" &&
231
+ new RegExp(`\\[\`?#${pr}\`?\\]\\(${url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\)`).test(row.status);
232
+ if (settled) continue;
233
+ violations.push({
234
+ code: "pr-url-unsettled",
235
+ line,
236
+ detail: `doc carries its PR URL (${where}); row status is '${row.status}' — expected 'done · [#${pr}](${url})'`,
237
+ });
238
+ }
239
+ return { ok: violations.length === 0, violations };
240
+ }
241
+
104
242
  /**
105
243
  * annotate(nn, note) — appends a note to the description cell of the row
106
244
  * identified by nn. The note is appended with a newline and "—" prefix.
@@ -0,0 +1,304 @@
1
+ /**
2
+ * The location indexes — one document, two tables (issue #319).
3
+ *
4
+ * `docs/ROADMAP.md` is the single index: `## Features` orders feature units,
5
+ * `## Fixes` carries the active fixes that used to live in `docs/fix/README.md`.
6
+ * The path is published here so a consumer never hardcodes it again — the
7
+ * 15-file recurrence the move was made to end.
8
+ *
9
+ * The same constants are mirrored by `@gtrabanco/agentic-workflow-schema`
10
+ * (`src/paths.ts`), the package the orchestration layer imports; the mirror is
11
+ * held in step by `scripts/index-document.test.mjs`, which reads both sources.
12
+ * The pre-move path is spelled exactly once in the tree, in this file: the
13
+ * alias below.
14
+ *
15
+ * The migration window is CLOSED (owner decision D4, 2026-10-30; it supersedes
16
+ * unit 319's D2): every reader resolves {@link ROADMAP_DOCUMENT} only. A
17
+ * repository that still carries the pre-move path is refused with a
18
+ * `roadmap-moved` pointer at its new home — never a silent empty parse, and
19
+ * never an empty index. `ROADMAP_LEGACY_READ` stays as the documented
20
+ * rollback lever: flipping it back to `true` re-opens the alias for an
21
+ * emergency, it is not a normal operating mode.
22
+ */
23
+
24
+ import fs from "node:fs";
25
+ import path from "node:path";
26
+
27
+ /** The consolidated index. */
28
+ export const ROADMAP_DOCUMENT = "docs/ROADMAP.md";
29
+ /** The pre-move path: detected only, so the refusal can name it. Never read. */
30
+ export const ROADMAP_LEGACY_DOCUMENT = "docs/features/ROADMAP.md";
31
+ /** The fix index file. Before unit 319 it was the index itself; now it is a stub. */
32
+ export const FIX_INDEX_DOCUMENT = "docs/fix/README.md";
33
+ /** The features table's heading in the consolidated index. */
34
+ export const ROADMAP_FEATURES_HEADING = "Features";
35
+ /** The fixes table's heading in the consolidated index. */
36
+ export const ROADMAP_FIXES_HEADING = "Fixes";
37
+ /**
38
+ * D4: the read alias is closed. Kept as an explicit, tested rollback lever:
39
+ * `true` re-opens the pre-move path for an emergency, and every consumer reads
40
+ * it through this one value.
41
+ *
42
+ * An operator rolling back cannot edit an installed package, so
43
+ * `AGENTIC_WORKFLOW_ROADMAP_LEGACY_READ=1` re-opens it at run time — the same
44
+ * value, one channel wider. It never re-opens by accident: only the exact `1`.
45
+ */
46
+ export const ROADMAP_LEGACY_READ = process.env.AGENTIC_WORKFLOW_ROADMAP_LEGACY_READ === "1";
47
+ /** The closed code a closed window refuses the pre-move path with. */
48
+ export const ROADMAP_MOVED_CODE = "roadmap-moved";
49
+
50
+ /**
51
+ * The pre-move path was read after the window closed. The error names the file
52
+ * that moved and where it moved to, so a consumer reconciles instead of parsing
53
+ * an empty document.
54
+ */
55
+ export class RoadmapMovedError extends Error {
56
+ constructor(from = ROADMAP_LEGACY_DOCUMENT, to = ROADMAP_DOCUMENT) {
57
+ super(`${ROADMAP_MOVED_CODE}: ${from} has moved to ${to} — read ${to}`);
58
+ this.name = "RoadmapMovedError";
59
+ this.code = ROADMAP_MOVED_CODE;
60
+ this.from = from;
61
+ this.to = to;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Which index a repository carries, without reading it: `{ path, source }`
67
+ * where `source` is `"canonical"`, or `"legacy"` only while the rollback lever
68
+ * is on; `null` when neither exists. A repository that carries only the
69
+ * pre-move path and no rollback is refused here, before any read.
70
+ *
71
+ * `exists` is the caller's own existence check, so a consumer that confines
72
+ * reads to its project root (the sensor) keeps its confinement instead of
73
+ * bypassing it with a second filesystem call.
74
+ *
75
+ * @param {object} options
76
+ * @param {(relative: string) => boolean} options.exists
77
+ * @param {boolean} [options.legacy] — defaults to the window flag.
78
+ * @returns {{path: string, source: "canonical"|"legacy"} | null}
79
+ */
80
+ export function resolveRoadmapSource({ exists, legacy = ROADMAP_LEGACY_READ }) {
81
+ if (exists(ROADMAP_DOCUMENT)) return { path: ROADMAP_DOCUMENT, source: "canonical" };
82
+ if (!exists(ROADMAP_LEGACY_DOCUMENT)) return null;
83
+ if (!legacy) throw new RoadmapMovedError();
84
+ return { path: ROADMAP_LEGACY_DOCUMENT, source: "legacy" };
85
+ }
86
+
87
+ /**
88
+ * Read the index a repository carries: `{ path, source, text }` or `null`.
89
+ * Throws `RoadmapMovedError` when only the pre-move path exists and the window
90
+ * is closed.
91
+ *
92
+ * @param {string} rootDir
93
+ * @param {{legacy?: boolean}} [options]
94
+ */
95
+ export function readRoadmapIndex(rootDir, { legacy = ROADMAP_LEGACY_READ } = {}) {
96
+ const exists = (relative) => {
97
+ try {
98
+ return fs.lstatSync(path.join(rootDir, relative)).isFile();
99
+ } catch {
100
+ return false;
101
+ }
102
+ };
103
+ const source = resolveRoadmapSource({ exists, legacy });
104
+ if (source === null) return null;
105
+ return { ...source, text: fs.readFileSync(path.join(rootDir, source.path), "utf8") };
106
+ }
107
+
108
+ /**
109
+ * A fence-looking line: up to three spaces, then three-or-more backticks or
110
+ * tildes. `marker` is the character that opened the run, `length` how long it is.
111
+ * (CommonMark's shape, which the schema package's `advanceFence` shares.)
112
+ */
113
+ const FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
114
+
115
+ /**
116
+ * Advance the fence state over one line, returning the block still open after it
117
+ * — the one grammar for every reader of the index.
118
+ *
119
+ * A block closes only on a run of the character that OPENED it, at least as long,
120
+ * with nothing but spaces after it. A block that is not open ignores input
121
+ * indented four columns or more: that is an indented code block, not a fence.
122
+ * Every consumer decides through this one function, so the heading scan and the
123
+ * row scan can never track differently — a fenced example row is document text,
124
+ * never a live row of a table.
125
+ *
126
+ * @param {string} line
127
+ * @param {{marker: string, length: number} | null} open
128
+ * @returns {{marker: string, length: number} | null}
129
+ */
130
+ export function fenceRun(line, open) {
131
+ const run = FENCE_LINE.exec(line);
132
+ if (run === null) {
133
+ if (open === null && /^ {4,}/.test(line) && line.trimStart().startsWith("|")) return open;
134
+ return open;
135
+ }
136
+ const marker = run[1][0];
137
+ const length = run[1].length;
138
+ if (open === null) {
139
+ if (/^ {4,}/.test(line)) return null;
140
+ return { marker, length };
141
+ }
142
+ return marker === open.marker && length >= open.length && run[2].trim() === "" ? null : open;
143
+ }
144
+
145
+ /**
146
+ * Whether a line is a live table row: a table row that no open fence owns. Rows
147
+ * indented four columns or more are an indented code block's lines, not rows.
148
+ *
149
+ * @param {string} line
150
+ * @param {{marker: string, length: number} | null} open — the block open before this line
151
+ * @returns {boolean}
152
+ */
153
+ export function isLiveTableRow(line, open) {
154
+ if (open !== null) return false;
155
+ if (/^ {4,}/.test(line)) return false;
156
+ return line.trimStart().startsWith("|");
157
+ }
158
+
159
+ /**
160
+ * The body of one `## <heading>` section, or `null` when the document has no
161
+ * such heading. Fenced code blocks are respected: a `##` line inside a fence is
162
+ * document text, not a heading.
163
+ *
164
+ * @param {string} text
165
+ * @param {string} heading
166
+ * @returns {string | null}
167
+ */
168
+ export function roadmapSection(text, heading) {
169
+ if (typeof text !== "string") return null;
170
+ const wanted = heading.trim().toLowerCase();
171
+ const out = [];
172
+ let fence = null;
173
+ let level = 0;
174
+ for (const line of text.split("\n")) {
175
+ fence = fenceRun(line, fence);
176
+ const match = fence === null ? /^(#{1,6})\s+(.*)$/.exec(line) : null;
177
+ if (match) {
178
+ if (level !== 0 && match[1].length <= level) break; // the section ended
179
+ if (level === 0 && match[2].trim().toLowerCase() === wanted) {
180
+ level = match[1].length;
181
+ continue;
182
+ }
183
+ if (level === 0) continue;
184
+ }
185
+ if (level !== 0) out.push(line);
186
+ }
187
+ return level === 0 ? null : out.join("\n");
188
+ }
189
+
190
+ /**
191
+ * The cells of one Markdown table row, splitting only on unescaped pipes and
192
+ * dropping only the boundary cells the pipes actually delimit — the same
193
+ * contract the schema package's mirror holds, so a row reads identically on
194
+ * both published sides whether or not it carries a trailing pipe (issue #319,
195
+ * F15).
196
+ */
197
+ export function tableCells(line) {
198
+ const cells = [];
199
+ let current = "";
200
+ for (let index = 0; index < line.length; index += 1) {
201
+ const char = line[index];
202
+ if (char === "\\" && line[index + 1] === "|") {
203
+ current += "|";
204
+ index += 1;
205
+ } else if (char === "|") {
206
+ cells.push(current.trim());
207
+ current = "";
208
+ } else {
209
+ current += char;
210
+ }
211
+ }
212
+ cells.push(current.trim());
213
+ if (cells.length < 2) return [];
214
+ const body = cells[0] === "" ? cells.slice(1) : cells;
215
+ return body[body.length - 1] === "" ? body.slice(0, -1) : body;
216
+ }
217
+
218
+ const isSeparatorRow = (cells) => cells.length > 0 && cells.every((cell) => /^[-:\s]*$/.test(cell));
219
+
220
+ /**
221
+ * Whether a document declares its tables by heading — the consolidated index,
222
+ * and any document that has begun migrating to it. A pre-319 roadmap puts one
223
+ * table straight under its title and is not one.
224
+ *
225
+ * @param {string} text
226
+ * @returns {boolean}
227
+ */
228
+ function declaresTablesByHeading(text) {
229
+ return roadmapSection(text, ROADMAP_FEATURES_HEADING) !== null || roadmapSection(text, ROADMAP_FIXES_HEADING) !== null;
230
+ }
231
+
232
+ /**
233
+ * The data rows of the table that belongs to `kind` — `"feature"` reads
234
+ * `## Features`, `"fix"` reads `## Fixes`.
235
+ *
236
+ * Scoping is what keeps the two tables apart: in a consolidated document a
237
+ * feature row numbered `N` and a fix row for issue `N` are different rows, and a
238
+ * parser handed the whole file must never mix them. A document without the
239
+ * heading (a pre-319 roadmap, a standalone fix index, a caller-supplied
240
+ * fragment) keeps its single-table meaning: every row is the caller's kind.
241
+ *
242
+ * A document that declares its tables by heading is the exception: when its
243
+ * `## Fixes` heading is absent, the fix table is empty rather than inherited
244
+ * from `## Features`. Reading the features table as fixes there is the
245
+ * half-migrated defect (issue #319, F1) — feature row `N` would answer for fix
246
+ * row `N` and report a slug mismatch against another kind.
247
+ *
248
+ * The inverse is not symmetric: a pre-319 roadmap keeps its features table under
249
+ * its title, so a feature read that finds no `## Features` heading but does find
250
+ * `## Fixes` is a half-migrated roadmap, never an empty feature table.
251
+ *
252
+ * Only live rows are returned: a fenced code block (a writer's example of the
253
+ * row format) and an indented code block are content, never data — the same
254
+ * `fenceRun` grammar the heading scan uses, so no reader can track differently.
255
+ *
256
+ * @param {string} text
257
+ * @param {"feature"|"fix"} kind
258
+ * @returns {string[][]}
259
+ */
260
+ export function roadmapTableRows(text, kind) {
261
+ if (typeof text !== "string") return [];
262
+ const heading = kind === "fix" ? ROADMAP_FIXES_HEADING : ROADMAP_FEATURES_HEADING;
263
+ const section = roadmapSection(text, heading);
264
+ const emptyFixTable = section === null && kind === "fix" && declaresTablesByHeading(text);
265
+ const body = emptyFixTable ? "" : (section ?? text);
266
+ const rows = [];
267
+ let fence = null;
268
+ for (const line of body.split("\n")) {
269
+ if (isLiveTableRow(line, fence)) {
270
+ const cells = tableCells(line);
271
+ if (cells.length > 0 && !isSeparatorRow(cells)) rows.push(cells);
272
+ }
273
+ fence = fenceRun(line, fence);
274
+ }
275
+ return rows;
276
+ }
277
+
278
+ /**
279
+ * The fix index's rows for this repository: the `## Fixes` table of the
280
+ * consolidated index when it has one, else the standalone `docs/fix/README.md`
281
+ * of a pre-319 tree. `{ path, text }` or `null`.
282
+ *
283
+ * @param {string} rootDir
284
+ * @param {{legacy?: boolean}} [options]
285
+ */
286
+ export function readFixIndexTable(rootDir, { legacy = ROADMAP_LEGACY_READ } = {}) {
287
+ const index = readRoadmapIndex(rootDir, { legacy });
288
+ if (index !== null) {
289
+ const section = roadmapSection(index.text, ROADMAP_FIXES_HEADING);
290
+ if (section !== null) return { path: index.path, text: section };
291
+ }
292
+ const standalone = path.join(rootDir, FIX_INDEX_DOCUMENT);
293
+ try {
294
+ if (!fs.lstatSync(standalone).isFile()) return null;
295
+ return { path: FIX_INDEX_DOCUMENT, text: fs.readFileSync(standalone, "utf8") };
296
+ } catch {
297
+ return null;
298
+ }
299
+ }
300
+
301
+ /** Whether a caller-supplied document path is the consolidated index. */
302
+ export function isRoadmapDocument(documentPath) {
303
+ return typeof documentPath === "string" && (documentPath === ROADMAP_DOCUMENT || documentPath.endsWith(`/${ROADMAP_DOCUMENT}`));
304
+ }