diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index b6d4158d8c..f036779f73 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -42,6 +42,12 @@ export interface Config { commentsFile: string; /** Append-only roadmap annotation store (#1284), separate from comments. */ roadmapAnnotationsFile: string; + /** Checkout of developing-today/code on the aggregator host; the + * repo-file roadmap source (#1738) reads planning/roadmaps/*.md here. */ + codeCheckout: string; + /** Checkout of dezren39/darwin-nix on the aggregator host; the + * repo-file roadmap source (#1738) reads ROADMAP.md here. */ + nixCheckout: string; /** Dashboard actions store (#1152/#1154/#1156) — triage write path. */ actionsFile: string; /** Saved-views store (#1276) — named per-person filter sets. */ @@ -169,6 +175,8 @@ export function loadConfig(env: Record = process.env feedFile: s(env.PM_AGG_FEED_FILE, join(process.cwd(), "fleet-feed.json")), commentsFile: s(env.PM_AGG_COMMENTS_FILE, join(process.cwd(), "comments.json")), roadmapAnnotationsFile: s(env.PM_AGG_ROADMAP_ANNOTATIONS_FILE, join(process.cwd(), "roadmap-annotations.json")), + codeCheckout: s(env.PM_AGG_CODE_CHECKOUT, join(homedir(), "git", "code")), + nixCheckout: s(env.PM_AGG_NIX_CHECKOUT, join(homedir(), "code", "dezren39-nix")), actionsFile: s(env.PM_AGG_ACTIONS_FILE, join(process.cwd(), "actions.json")), viewsFile: s(env.PM_AGG_VIEWS_FILE, join(process.cwd(), "views.json")), eventsFile: s(env.PM_AGG_EVENTS_FILE, join(process.cwd(), "events.json")), diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index c8abe669f5..4dab892906 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -219,6 +219,9 @@ export interface RoadmapRow { links: Link[]; /** Grist UI link for this row's document (#1136), when known. */ gristUrl?: string; + /** Repo-file link for this row's source file + heading (#1738), when + * the row was parsed from a repo roadmap file rather than Grist. */ + fileUrl?: string; } /** Where each facet's data came from, shown in the UI footer. */ diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 22d588bcd5..ae09154633 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -1787,6 +1787,7 @@ function roadmapCard( .join(" "); const cmt = counts ? commentBadge(row.subject, counts) : ""; const grist = row.gristUrl ? ` Grist ↗` : ""; + const repoFile = row.fileUrl ? ` Repo file ↗` : ""; const expansion = drill ? roadmapDrilldown(drill, row, forecasts, spend) : ""; const notes = annotations?.get(row.subject) ?? []; const annotationHtml = notes.length @@ -1813,7 +1814,7 @@ function roadmapCard( } } } - return `
${esc(row.title)}${cmt}
${esc(row.status)} ${esc(row.area)} · ${esc(row.horizon)}${horizonWarning}${statusClash}${refBadges}${grist}${annotationHtml}${expansion}${briefPanels}
`; + return `
${esc(row.title)}${cmt}
${esc(row.status)} ${esc(row.area)} · ${esc(row.horizon)}${horizonWarning}${statusClash}${refBadges}${grist}${repoFile}${annotationHtml}${expansion}${briefPanels}
`; } function roadmapAnnotationHtml(annotation: RoadmapAnnotation): string { diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index 616827f0cf..ad89317c78 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -39,6 +39,7 @@ import { import { isRecord } from "../validate.ts"; import { buildAttentionFlags, buildQuotaActions, quotaActionFlags } from "../derive.ts"; import { validateRoadmapHorizon } from "../roadmap-horizon.ts"; +import { describeRepoRoadmapSection, mergeRoadmapRows, readRepoRoadmaps } from "./repo-roadmap.ts"; import { summarizeDns } from "../dns.ts"; import { applyCloudflareExport, @@ -1329,13 +1330,28 @@ export function liveSource( try { const rows = await gristRoadmap(cfg); if (rows.length > 0) { - provenance.roadmap = "live (Grist)"; + let merged = rows; + let label = "live (Grist)"; if (cfg.projector.baseUrl) { - const enriched = await enrichWithRegistryLinks(cfg.projector.baseUrl, rows, (r) => r.subject); - provenance.roadmap = "live (Grist + projector links)"; - return enriched; + merged = await enrichWithRegistryLinks(cfg.projector.baseUrl, rows, (r) => r.subject); + label = "live (Grist + projector links)"; } - return rows; + // #1738: merge the repos' own roadmap files in alongside the + // Grist rows. The repo-file read never throws (its failures + // are section states), but guard anyway: a broken repo source + // must never take the Grist roadmap down with it. Empty + // sections name their state + reason in the label (#1500). + try { + const repo = await readRepoRoadmaps(cfg); + const out = mergeRoadmapRows(merged, repo.rows); + merged = out.rows; + const sections = repo.sections.map(describeRepoRoadmapSection).join("; "); + label += ` + repo files (${sections}${out.collapsedCount ? `; ${out.collapsedCount} grist duplicate(s) collapsed` : ""})`; + } catch (err) { + label += ` + repo files (unreadable: ${err instanceof Error ? err.message : err})`; + } + provenance.roadmap = label; + return merged; } } catch (err) { provenance.roadmap = `fixtures (grist unreachable: ${err instanceof Error ? err.message : err})`; diff --git a/pm-stack/aggregator/src/sources/repo-roadmap.test.ts b/pm-stack/aggregator/src/sources/repo-roadmap.test.ts new file mode 100644 index 0000000000..dfc53fb2f0 --- /dev/null +++ b/pm-stack/aggregator/src/sources/repo-roadmap.test.ts @@ -0,0 +1,176 @@ +import { describe, expect, test } from "bun:test"; +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + mergeRoadmapRows, + parseRepoRoadmapFile, + readRepoRoadmaps, +} from "./repo-roadmap.ts"; +import type { RoadmapRow } from "../model.ts"; + +// An id.md-shaped code roadmap file: horizon lives in the ## heading, +// refs are bare #n against the file's own repo. +const CODE_FILE = `# Roadmap: id + +The id program record. + +## Now — the path to Phase 12 + +| Title | Status | Intent | Links | +| ------------------ | ----------- | ---------------------- | ----- | +| Many worlds per node | planned | 1,000 idle / 100 active worlds. | F12.12 #557 | +| Trusted CI signal | in-progress | A red check must mean something. | #241, [plan](https://github.com/developing-today/code/issues/999) | + +## Ideas + +| Title | Status | Intent | Links | +| --------------- | ------ | ------------- | ----- | +| Worlds on Workers | idea | A pkarr option. | #793 | +`; + +const CODE_META = { repo: "developing-today/code", path: "planning/roadmaps/id.md" }; + +// A nix ROADMAP.md-shaped file: an "Areas" summary table (no Title +// column — must be skipped), then per-area sections whose tables carry +// the Horizon column; area comes from the section heading. +const NIX_FILE = `# Roadmap + +Grouped by area. + +## Areas + +| Area | Current focus | +| ---------- | ------------- | +| [Widgets](#widgets) | All the widgets | + +## Widgets + +| Title | Horizon | Status | Intent | Links | +| ---------------- | ------- | -------- | ------------------- | ----- | +| Widget takeover | Now | planned | Take over widgets. | \`developing-today/code#237\` | +| Widget hygiene | Next | proposed | Sweep the widgets. | #376 | +`; + +const NIX_META = { + repo: "dezren39/darwin-nix", + path: "ROADMAP.md", + program: "darwin-nix", + areaFromSections: true, +}; + +describe("parseRepoRoadmapFile — code planning/roadmaps shape", () => { + const rows = parseRepoRoadmapFile(CODE_FILE, CODE_META); + + test("the id program appears with zero Grist rows", () => { + expect(rows.length).toBe(3); + expect(rows.every((r) => r.area === "id")).toBe(true); + expect(rows.every((r) => r.subject.startsWith("repo-file:developing-today/code/planning/roadmaps/id.md/"))).toBe(true); + }); + + test("horizon comes from the section heading; Ideas is its own bucket, not an error", () => { + expect(rows[0].horizon).toBe("Now"); + expect(rows[2].horizon).toBe("Ideas"); + expect(rows[2].horizonError).toBeUndefined(); + }); + + test("bare and URL refs resolve against the file's repo; file link points at the heading", () => { + expect(rows[0].links).toEqual([{ ref: "developing-today/code#557", relation: "tracks" }]); + expect(rows[1].links.map((l) => l.ref).sort()).toEqual(["developing-today/code#241", "developing-today/code#999"]); + expect(rows[0].fileUrl).toBe( + "https://github.com/developing-today/code/blob/main/planning/roadmaps/id.md#now--the-path-to-phase-12", + ); + expect(rows[0].source).toContain("repo file"); + expect(rows[0].notes).toContain("1,000 idle"); + }); +}); + +describe("parseRepoRoadmapFile — nix ROADMAP.md shape", () => { + const rows = parseRepoRoadmapFile(NIX_FILE, NIX_META); + + test("the Areas summary table is skipped; section tables parse with their Horizon column", () => { + expect(rows.length).toBe(2); + expect(rows.map((r) => r.title)).toEqual(["Widget takeover", "Widget hygiene"]); + expect(rows[0].area).toBe("Widgets"); + expect(rows[0].horizon).toBe("Now"); + expect(rows[1].horizon).toBe("Next"); + }); + + test("qualified refs keep their repo; bare refs take the file's repo", () => { + expect(rows[0].links).toEqual([{ ref: "developing-today/code#237", relation: "tracks" }]); + expect(rows[1].links).toEqual([{ ref: "dezren39/darwin-nix#376", relation: "tracks" }]); + }); + + test("a file with no Title table parses empty", () => { + expect(parseRepoRoadmapFile("# Roadmap\n\nJust prose, no tables.\n", NIX_META)).toEqual([]); + }); +}); + +const gristRow = (title: string, subject: string): RoadmapRow => ({ + id: 7, + subject, + title, + area: "id", + status: "planned", + horizon: "Now", + source: "", + notes: "", + links: [{ ref: "developing-today/code#557", relation: "tracks" }], +}); + +describe("mergeRoadmapRows — dedupe prefers the repo row", () => { + test("a Grist duplicate collapses into the repo row with provenance noted", () => { + const repo = parseRepoRoadmapFile(CODE_FILE, CODE_META).map((r, i) => ({ ...r, id: -1 - i })); + const grist = [gristRow("Many Worlds Per Node!", "grist:doc/Roadmap/7"), gristRow("Only in Grist", "grist:doc/Roadmap/8")]; + const { rows, collapsedCount } = mergeRoadmapRows(grist, repo); + expect(collapsedCount).toBe(1); + expect(rows.some((r) => r.subject === "grist:doc/Roadmap/7")).toBe(false); + expect(rows.some((r) => r.subject === "grist:doc/Roadmap/8")).toBe(true); + const twin = rows.find((r) => r.title === "Many worlds per node"); + expect(twin?.notes).toContain("grist:doc/Roadmap/7"); + expect(twin?.links).toEqual([{ ref: "developing-today/code#557", relation: "tracks" }]); + }); +}); + +describe("readRepoRoadmaps — section states say why (#1500)", () => { + test("ok: both sources read, ids are unique negatives", async () => { + const root = await mkdtemp(join(tmpdir(), "repo-roadmap-")); + await mkdir(join(root, "code", "planning", "roadmaps"), { recursive: true }); + await writeFile(join(root, "code", "planning", "roadmaps", "id.md"), CODE_FILE); + await mkdir(join(root, "nix"), { recursive: true }); + await writeFile(join(root, "nix", "ROADMAP.md"), NIX_FILE); + const { rows, sections } = await readRepoRoadmaps({ codeCheckout: join(root, "code"), nixCheckout: join(root, "nix") }); + expect(rows.length).toBe(5); + expect(new Set(rows.map((r) => r.id)).size).toBe(5); + expect(rows.every((r) => r.id < 0)).toBe(true); + expect(sections.map((s) => s.state)).toEqual(["ok", "ok"]); + }); + + test("missing: neither checkout carries the files", async () => { + const root = await mkdtemp(join(tmpdir(), "repo-roadmap-")); + const { rows, sections } = await readRepoRoadmaps({ codeCheckout: join(root, "code"), nixCheckout: join(root, "nix") }); + expect(rows).toEqual([]); + expect(sections.map((s) => s.state)).toEqual(["missing", "missing"]); + expect(sections[0].reason).toContain("PM_AGG_CODE_CHECKOUT"); + expect(sections[1].reason).toContain("PM_AGG_NIX_CHECKOUT"); + }); + + test("parse-empty: files exist but carry no Title-table rows", async () => { + const root = await mkdtemp(join(tmpdir(), "repo-roadmap-")); + await mkdir(join(root, "code", "planning", "roadmaps"), { recursive: true }); + await writeFile(join(root, "code", "planning", "roadmaps", "empty.md"), "# Roadmap: empty\n\nNo tables yet.\n"); + await mkdir(join(root, "nix"), { recursive: true }); + await writeFile(join(root, "nix", "ROADMAP.md"), "# Roadmap\n\nNothing parsed.\n"); + const { sections } = await readRepoRoadmaps({ codeCheckout: join(root, "code"), nixCheckout: join(root, "nix") }); + expect(sections.map((s) => s.state)).toEqual(["parse-empty", "parse-empty"]); + }); + + test("unreadable: a file where a directory is expected (and vice versa)", async () => { + const root = await mkdtemp(join(tmpdir(), "repo-roadmap-")); + await mkdir(join(root, "code", "planning"), { recursive: true }); + await writeFile(join(root, "code", "planning", "roadmaps"), "not a directory"); + await mkdir(join(root, "nix", "ROADMAP.md"), { recursive: true }); + const { sections } = await readRepoRoadmaps({ codeCheckout: join(root, "code"), nixCheckout: join(root, "nix") }); + expect(sections.map((s) => s.state)).toEqual(["unreadable", "unreadable"]); + }); +}); diff --git a/pm-stack/aggregator/src/sources/repo-roadmap.ts b/pm-stack/aggregator/src/sources/repo-roadmap.ts new file mode 100644 index 0000000000..9647e04eeb --- /dev/null +++ b/pm-stack/aggregator/src/sources/repo-roadmap.ts @@ -0,0 +1,338 @@ +// Repo-file roadmap source (#1738): parse the repos' own roadmap +// records — developing-today/code planning/roadmaps/*.md and +// dezren39/darwin-nix ROADMAP.md — into RoadmapRow records, so /roadmap +// and /api/roadmap.json show them alongside the Grist table rows +// instead of drifting from them (the id program had a full repo record +// and no Grist presence at all). +// +// Both file families carry the same table shape: a "Title" column, +// optional Status / Horizon / Intent / Links columns, grouped under +// ## headings. Code files put the horizon in the heading ("## Now — +// the path to Phase 12") and the area in the file ("# Roadmap: id"); +// the nix ROADMAP.md puts the horizon in the table and the area in +// each ## heading. The parser handles both. +// +// Merge rule (acceptance on #1738): a title present in both sources +// collapses to the repo-file row; the Grist duplicate is noted in that +// row's notes (provenance) and its links are unioned in. +// +// Empty sources say why (#1500): every source section reports one of +// ok | missing | parse-empty | unreadable with a reason, instead of +// silently contributing zero rows. + +import { readdir, readFile } from "node:fs/promises"; +import { join } from "node:path"; +import { isValidRef, refsInText, type Link, type RoadmapRow } from "../model.ts"; +import { validateRoadmapHorizon } from "../roadmap-horizon.ts"; +import { normalizeTitle } from "../roadmap-reconcile.ts"; + +export type RepoRoadmapSectionState = "ok" | "missing" | "parse-empty" | "unreadable"; + +export interface RepoRoadmapSection { + /** Human label of the source: "code planning/roadmaps" / "nix ROADMAP.md". */ + source: string; + state: RepoRoadmapSectionState; + /** Why the section is empty (or what it read, when ok). */ + reason: string; + rowCount: number; +} + +export interface RepoRoadmaps { + rows: RoadmapRow[]; + sections: RepoRoadmapSection[]; +} + +export interface RepoRoadmapFileMeta { + /** Repo the file lives in ("developing-today/code") — the target for + * bare #n refs and the blob link's repo. */ + repo: string; + /** Repo-relative path ("planning/roadmaps/id.md"). */ + path: string; + /** Area for rows when the file's own H1 does not name one. */ + program?: string; + /** Nix style: the area is each ## section heading, not the file. */ + areaFromSections?: boolean; +} + +type ParsedRow = Omit; + +const HORIZON_BUCKETS = ["Now", "Next", "Later", "Ideas", "Ongoing"]; + +/** GitHub's heading-anchor slug: lowercase, drop punctuation, spaces to hyphens. */ +export function githubSlug(heading: string): string { + return heading + .toLowerCase() + .replace(/[^\p{L}\p{N} _-]/gu, "") + .replace(/ /g, "-"); +} + +/** Split a markdown table row into cells on unescaped pipes. */ +function splitCells(line: string): string[] { + const parts = line.split(/(? c.replace(/\\\|/g, "|").trim()); +} + +/** Plain-text form of a table cell: links collapse to their text. */ +function cellText(cell: string): string { + return cell + .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/[*_`]/g, "") + .trim(); +} + +const SHORTHAND_REPOS = new Map([ + ["nix", "dezren39/darwin-nix"], + ["code", "developing-today/code"], + ["opencode", "developing-today-forks/opencode"], + ["openchamber", "developing-today-forks/openchamber"], +]); + +/** Refs named by a roadmap table cell: full GitHub URLs (via + * refsInText), qualified owner/repo#n tokens, the repos' own shorthand + * (nix#203, code#1500), and bare #n refs against the file's repo. */ +export function roadmapRefsInText(text: string, ownRepo: string): Link[] { + const refs = new Set(refsInText(text)); + for (const m of text.matchAll(/(?:^|[\s,;(\[`])((?:[\w.-]+)\/(?:[\w.-]+))#(\d+)/g)) { + refs.add(`${m[1]}#${m[2]}`); + } + for (const m of text.matchAll(/(?:^|[\s,;(\[`])(nix|code|opencode|openchamber)#(\d+)/g)) { + refs.add(`${SHORTHAND_REPOS.get(m[1])}#${m[2]}`); + } + for (const m of text.matchAll(/(?:^|[\s,;(\[`])#(\d+)/g)) { + refs.add(`${ownRepo}#${m[1]}`); + } + return [...refs].filter((r) => isValidRef(r)).map((ref) => ({ ref, relation: "tracks" as const })); +} + +function horizonOfHeading(heading: string): string | null { + const first = heading.trim().split(/[\s—–:(-]/)[0]; + return HORIZON_BUCKETS.find((b) => b.toLowerCase() === first.toLowerCase()) ?? null; +} + +/** Parse one roadmap markdown file into rows (ids assigned by the reader). */ +export function parseRepoRoadmapFile(content: string, meta: RepoRoadmapFileMeta): ParsedRow[] { + const lines = content.split(/\r?\n/); + let program = meta.program ?? meta.path.split("/").pop()?.replace(/\.md$/i, "") ?? ""; + let section = ""; + let sectionHorizon: string | null = null; + const rows: ParsedRow[] = []; + const subjectCounts = new Map(); + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const h1 = /^#\s+Roadmap:\s*(.+?)\s*$/.exec(line); + if (h1) { + program = h1[1]; + continue; + } + const h2 = /^##\s+(.+?)\s*$/.exec(line); + if (h2) { + section = h2[1]; + sectionHorizon = horizonOfHeading(section); + continue; + } + if (!line.trimStart().startsWith("|")) continue; + const header = splitCells(line).map((c) => c.toLowerCase()); + const titleCol = header.indexOf("title"); + if (titleCol === -1) continue; // e.g. the nix "Areas" summary table + const col = (name: string) => header.indexOf(name); + const horizonCol = col("horizon"); + const statusCol = col("status"); + const intentCol = col("intent") !== -1 ? col("intent") : col("notes"); + const linksCol = col("links"); + // Consume the separator line plus every following table row. + let j = i + 1; + if (j < lines.length && /^\s*\|?[\s:|-]+\|?\s*$/.test(lines[j]) && lines[j].includes("-")) j++; + for (; j < lines.length && lines[j].trimStart().startsWith("|"); j++) { + const cells = splitCells(lines[j]); + const title = cellText(cells[titleCol] ?? ""); + if (!title) continue; + const horizon = (horizonCol !== -1 ? cellText(cells[horizonCol] ?? "") : "") || sectionHorizon || "Unscheduled"; + const anchor = section ? githubSlug(section) : ""; + const base = `repo-file:${meta.repo}/${meta.path}/${githubSlug(title)}`; + const seen = (subjectCounts.get(base) ?? 0) + 1; + subjectCounts.set(base, seen); + const validation = validateRoadmapHorizon(horizon); + rows.push({ + subject: seen > 1 ? `${base}-${seen}` : base, + title, + area: meta.areaFromSections ? section || program : program, + status: statusCol !== -1 ? cellText(cells[statusCol] ?? "") : "", + horizon, + // "Ideas" is a real bucket in the repo files' own grammar + // (it earns its own timeline lane); the Grist grammar does not + // know it, so flagging it "invalid" would lie about the file. + ...(!validation.valid && horizon !== "Ideas" ? { horizonError: validation.error } : {}), + source: `repo file (${meta.repo}/${meta.path})`, + notes: intentCol !== -1 ? cellText(cells[intentCol] ?? "") : "", + links: roadmapRefsInText(linksCol !== -1 ? (cells[linksCol] ?? "") : lines[j], meta.repo), + fileUrl: `https://github.com/${meta.repo}/blob/main/${meta.path}${anchor ? `#${anchor}` : ""}`, + }); + } + i = j - 1; + } + return rows; +} + +const errCode = (err: unknown): string => + err instanceof Error ? ((err as NodeJS.ErrnoException).code ?? err.message) : String(err); + +/** Read both repo roadmap sources from the aggregator host's checkouts. + * Never throws: every failure lands in the section's state + reason. */ +export async function readRepoRoadmaps(checkouts: { + codeCheckout: string; + nixCheckout: string; +}): Promise { + const rows: RoadmapRow[] = []; + const sections: RepoRoadmapSection[] = []; + let nextId = -1; + const take = (parsed: ParsedRow[]) => { + for (const row of parsed) rows.push({ ...row, id: nextId-- }); + return parsed.length; + }; + + // developing-today/code — planning/roadmaps/*.md, one program per file. + { + const source = "code planning/roadmaps"; + const dir = join(checkouts.codeCheckout, "planning", "roadmaps"); + let names: string[] | null = null; + try { + names = (await readdir(dir)).filter((n) => n.toLowerCase().endsWith(".md")).sort(); + } catch (err) { + const code = errCode(err); + sections.push({ + source, + state: code === "ENOENT" ? "missing" : "unreadable", + reason: + code === "ENOENT" + ? `planning/roadmaps not found under ${checkouts.codeCheckout} (PM_AGG_CODE_CHECKOUT)` + : `planning/roadmaps under ${checkouts.codeCheckout} could not be listed: ${code}`, + rowCount: 0, + }); + } + if (names) { + let count = 0; + const failures: string[] = []; + for (const name of names) { + try { + const content = await readFile(join(dir, name), "utf8"); + count += take( + parseRepoRoadmapFile(content, { + repo: "developing-today/code", + path: `planning/roadmaps/${name}`, + }), + ); + } catch (err) { + failures.push(`${name}: ${errCode(err)}`); + } + } + if (count === 0 && failures.length === names.length && names.length > 0) { + sections.push({ + source, + state: "unreadable", + reason: `no roadmap file could be read (${failures.join("; ")})`, + rowCount: 0, + }); + } else if (count === 0) { + sections.push({ + source, + state: "parse-empty", + reason: `${names.length} roadmap file(s) read under planning/roadmaps, but no Title-table rows parsed`, + rowCount: 0, + }); + } else { + sections.push({ + source, + state: "ok", + reason: `${names.length} roadmap file(s), ${count} rows${failures.length ? `; unreadable: ${failures.join("; ")}` : ""}`, + rowCount: count, + }); + } + } + } + + // dezren39/darwin-nix — the single ROADMAP.md, areas per ## section. + { + const source = "nix ROADMAP.md"; + const file = join(checkouts.nixCheckout, "ROADMAP.md"); + try { + const content = await readFile(file, "utf8"); + const count = take( + parseRepoRoadmapFile(content, { + repo: "dezren39/darwin-nix", + path: "ROADMAP.md", + program: "darwin-nix", + areaFromSections: true, + }), + ); + sections.push( + count === 0 + ? { + source, + state: "parse-empty", + reason: `ROADMAP.md read under ${checkouts.nixCheckout}, but no Title-table rows parsed`, + rowCount: 0, + } + : { source, state: "ok", reason: `ROADMAP.md, ${count} rows`, rowCount: count }, + ); + } catch (err) { + const code = errCode(err); + sections.push({ + source, + state: code === "ENOENT" ? "missing" : "unreadable", + reason: + code === "ENOENT" + ? `ROADMAP.md not found under ${checkouts.nixCheckout} (PM_AGG_NIX_CHECKOUT)` + : `ROADMAP.md under ${checkouts.nixCheckout} could not be read: ${code}`, + rowCount: 0, + }); + } + } + + return { rows, sections }; +} + +/** One-line section summary for the provenance footer: ok sections give + * their row count; empty sections give their state and reason (#1500). */ +export function describeRepoRoadmapSection(section: RepoRoadmapSection): string { + return section.state === "ok" + ? `${section.source}: ${section.rowCount} rows` + : `${section.source}: ${section.state} — ${section.reason}`; +} + +export interface RoadmapMerge { + rows: RoadmapRow[]; + collapsedCount: number; +} + +/** Merge repo-file rows with Grist rows: duplicates (same normalized + * title) collapse in favour of the repo-file row, with the Grist + * duplicate noted in that row's notes and its links unioned in. */ +export function mergeRoadmapRows(gristRows: RoadmapRow[], repoRows: RoadmapRow[]): RoadmapMerge { + const repoByTitle = new Map(); + for (const row of repoRows) { + const key = normalizeTitle(row.title); + if (key && !repoByTitle.has(key)) repoByTitle.set(key, row); + } + const kept: RoadmapRow[] = []; + let collapsedCount = 0; + for (const grist of gristRows) { + const twin = repoByTitle.get(normalizeTitle(grist.title)); + if (!twin) { + kept.push(grist); + continue; + } + collapsedCount++; + const seenLinks = new Set(twin.links.map((l) => `${l.ref}|${l.relation}`)); + for (const link of grist.links) { + if (!seenLinks.has(`${link.ref}|${link.relation}`)) twin.links.push(link); + } + twin.notes = [twin.notes, `Also tracked in the Grist roadmap (${grist.subject}); collapsed in favour of this repo-file row (#1738).`] + .filter(Boolean) + .join("\n"); + } + return { rows: [...repoRows, ...kept], collapsedCount }; +} diff --git a/pm-stack/aggregator/test/grist-live.test.ts b/pm-stack/aggregator/test/grist-live.test.ts index 332206660b..f0552870f8 100644 --- a/pm-stack/aggregator/test/grist-live.test.ts +++ b/pm-stack/aggregator/test/grist-live.test.ts @@ -25,6 +25,8 @@ async function testConfig() { PM_PROJECTOR_URL: "off", GRIST_URL: "http://grist.test", GRIST_ROADMAP_DOC: "test-roadmap-doc", + PM_AGG_CODE_CHECKOUT: join(dir, "code"), + PM_AGG_NIX_CHECKOUT: join(dir, "nix"), GRIST_API_KEY: "test-grist-api-key", }); } @@ -86,7 +88,10 @@ describe("live Grist roadmap reader (#1213)", () => { gristUrl: "http://amd-6.raptor-pumpkinseed.ts.net:8484/doc/test-roadmap-doc", }, ]); - expect(src.provenance().roadmap).toBe("live (Grist)"); + // #1738: the live label now carries the repo-file sections; + // with hermetic (absent) checkouts both report missing (#1500). + expect(src.provenance().roadmap).toContain("live (Grist) + repo files (code planning/roadmaps: missing"); + expect(src.provenance().roadmap).toContain("nix ROADMAP.md: missing"); } finally { globalThis.fetch = realFetch; }