diff --git a/.github/test-suite-registry.json b/.github/test-suite-registry.json index 2f004ef091..45cab00fbb 100644 --- a/.github/test-suite-registry.json +++ b/.github/test-suite-registry.json @@ -712,6 +712,21 @@ "status": "mapped", "related_issues": [12826] }, + { + "id": "pm-service.read-api", + "paths": [ + "pm-stack/pm-service/test/read-api.test.ts" + ], + "invocation": "cd pm-stack/pm-service && bun test", + "venue": { + "workflow": ".github/workflows/pm-stack-tests.yml", + "job_step": "Test pm-service suites", + "state": "active", + "dispatchable": true + }, + "status": "mapped", + "related_issues": [12828] + }, { "id": "opencode-claimant.install", "paths": ["pm-stack/opencode-claimant/test/install.test.mjs"], diff --git a/.github/workflows/pm-stack-tests.yml b/.github/workflows/pm-stack-tests.yml index b1c23cff81..45a1fe944e 100644 --- a/.github/workflows/pm-stack-tests.yml +++ b/.github/workflows/pm-stack-tests.yml @@ -322,10 +322,11 @@ jobs: fi bun test - # Bun suites for #12825 + #12826: pm-stack/pm-service/test/ + # Bun suites for #12825 + #12826 + #12828: pm-stack/pm-service/test/ # (tenant-store.test.ts, the component A PM tenant store # schema + migrations conformance suite; collector.test.ts, - # the hosted collector acceptance suite) must not be silently + # the hosted collector acceptance suite; read-api.test.ts, + # the hosted read API parity suite) must not be silently # skipped suites either. They need only bun (bun:sqlite is # built in), no install step. - name: Test pm-service suites diff --git a/pm-stack/pm-service/README.md b/pm-stack/pm-service/README.md index e4106d9814..367078b777 100644 --- a/pm-stack/pm-service/README.md +++ b/pm-stack/pm-service/README.md @@ -94,3 +94,46 @@ Invariants pinned by `test/collector.test.ts`: exactly one conditional request and writes nothing. - **Writer provenance.** Landed snapshots record `writer='hosted'` and the board's writer-lease epoch (design §5/§7). + +## Slice 3 — Hosted read API parity (#12828) + +`src/read-api/` serves the #9060 §6 shapes from the tenant DB — +the hosted half of design §4's parity list. Read-only throughout: +the store layer issues SELECTs only, and no token is read, minted, +or persisted on this path (E §2.3). + +- `genealogy.ts` — the genealogy read model (#9060 §6), ported from + the laptop aggregator's #9070 implementation: `ancestors[]` + (parent / historical-parent / primary-parent / spawned-by / + roadmap / priority), the release derivation, the sentence + renderer, and the roadmap-row enrichment. A port, not a redesign; + chain breaks render honestly ("with no epic yet"), never as + fabricated links. +- `releases.ts` — milestone close-out accounting (#9060 §4), ported + from the laptop's #9067 implementation: program milestones get + retroactive counts; release milestones get the close-out record + (counts split closed / carried-over, the release date, the + description line). Plus the assembler that serves a stored + `pm_release_snapshots` row in the same shape. +- `store.ts` — the tenant-DB reads: board summaries (registry + + latest snapshot audit per board), the merged pool (current + `pm_items` rows), roadmap rows (stored genealogy overlay wins + per-field where set; unset fields derive over the pool), and + release snapshots (stored records first, computed retroactive + accounting for the rest). +- `api.ts` — the four endpoints and their fetch handler: + `/api/projects.json` (`projects[]` + per-board audit + the merged + pool), `/api/item/.json` (item + `ancestors[]` + `release` + + the genealogy sentence; unknown ref → structured 404), + `/api/roadmap.json` (rows with `priority`/`afterRefs`/ + `releaseRef`), `/api/releases.json` (milestone snapshots). + +Invariants pinned by `test/read-api.test.ts`: + +- **The §8 worked example renders end-to-end.** The crate-split + chain (step #4403 → epic #3447 → design #3195 → roadmap item + #2056) serves its full ancestor chain, its release, and the + genealogy sentence through `/api/item/.json`. +- **Honest absence.** A board with no snapshot serves null audit; an + item with no chain serves empty ancestors and the chain-break + sentence; an unknown ref 404s. Nothing is fabricated. diff --git a/pm-stack/pm-service/package.json b/pm-stack/pm-service/package.json index 637cda2f17..7b051d2381 100644 --- a/pm-stack/pm-service/package.json +++ b/pm-stack/pm-service/package.json @@ -1 +1,15 @@ -{"description":"PM service, Workers edition (component A of #9078, under #9079): the hosted edition of the pm-stack PM service. Slice 1 (#12825): PM tenant store schema + migrations. Slice 2 (#12826): hosted collector — registry-driven multi-board ingest with IngestDO cursors.","devDependencies":{"@cloudflare/workers-types":"^4.20251011.0","typescript":"^5.6.0"},"name":"pm-service","private":true,"scripts":{"test":"bun test","typecheck":"tsc --noEmit"},"type":"module","version":"0.1.0"} \ No newline at end of file +{ + "description": "PM service, Workers edition (component A of #9078, under #9079): the hosted edition of the pm-stack PM service. Slice 1 (#12825): PM tenant store schema + migrations. Slice 2 (#12826): hosted collector \u2014 registry-driven multi-board ingest with IngestDO cursors. Slice 3 (#12828): hosted read API parity \u2014 projects/item/roadmap/releases per #9060 \u00a76, served from the tenant DB.", + "devDependencies": { + "@cloudflare/workers-types": "^4.20251011.0", + "typescript": "^5.6.0" + }, + "name": "pm-service", + "private": true, + "scripts": { + "test": "bun test", + "typecheck": "tsc --noEmit" + }, + "type": "module", + "version": "0.1.0" +} diff --git a/pm-stack/pm-service/src/read-api/api.ts b/pm-stack/pm-service/src/read-api/api.ts new file mode 100644 index 0000000000..06cd126808 --- /dev/null +++ b/pm-stack/pm-service/src/read-api/api.ts @@ -0,0 +1,99 @@ +/** + * The hosted read API (component A design §4 parity list; #9060 §6 + * shapes), served from the tenant DB via store.ts: + * + * - GET /api/projects.json — `projects[]`: every registry board with + * its latest snapshot audit, plus the merged pool as `items`. + * - GET /api/item/.json — one pool item by ref + * ("owner/repo#123", percent-encoded in the path) with its + * genealogy: `ancestors[]`, `release`, and the rendered sentence. + * An unknown ref is a structured 404 — chain breaks and missing + * data render honestly, never fabricated (#9060 §6). + * - GET /api/roadmap.json — roadmap rows with the genealogy overlay + * (`priority` / `afterRefs` / `releaseRef`) on every row. + * - GET /api/releases.json — milestone close-out snapshots (#9060 + * §4): stored snapshots where close-out recorded them, retroactive + * computed accounting for the rest. + * + * Read-only: the handler answers GETs only and the store layer + * issues SELECTs only. No token is read, minted, or persisted on + * this path (E §2.3) — the API serves tenant-DB data, nothing else. + */ +import type { SqlDb } from "../tenant-store/migrate.ts"; +import { deriveGenealogy } from "./genealogy.ts"; +import { loadBoardSummaries, loadPool, loadReleaseSnapshots, loadRoadmapRows } from "./store.ts"; + +export interface ReadApiDeps { + db: SqlDb; + /** Clock seam for generatedAt stamps (tests pin it). */ + now?: () => string; +} + +const json = (body: unknown, status = 200): Response => + new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); + +export function projectsJson(deps: ReadApiDeps) { + const now = deps.now ?? (() => new Date().toISOString()); + return { + generatedAt: now(), + projects: loadBoardSummaries(deps.db), + items: loadPool(deps.db), + }; +} + +export function itemJson(deps: ReadApiDeps, ref: string): { status: number; body: unknown } { + const pool = loadPool(deps.db); + const item = pool.find((entry) => entry.ref === ref); + if (!item) return { status: 404, body: { error: `no pool item with ref ${ref}` } }; + const genealogy = deriveGenealogy(item, pool); + return { + status: 200, + body: { + item, + ancestors: genealogy.ancestors, + release: genealogy.release, + genealogySentence: genealogy.sentence, + }, + }; +} + +export function roadmapJson(deps: ReadApiDeps) { + const now = deps.now ?? (() => new Date().toISOString()); + const pool = loadPool(deps.db); + return { generatedAt: now(), rows: loadRoadmapRows(deps.db, pool) }; +} + +export function releasesJson(deps: ReadApiDeps) { + const now = deps.now ?? (() => new Date().toISOString()); + const pool = loadPool(deps.db); + return { + generatedAt: now(), + source: "tenant DB milestone snapshots + pool accounting (#9060 §4)", + releases: loadReleaseSnapshots(deps.db, pool), + }; +} + +const ITEM_PATH = /^\/api\/item\/(.+)\.json$/; + +/** The fetch handler the Worker entry mounts. Only the four GET + * routes exist; anything else is a JSON 404. */ +export function createReadApiHandler(deps: ReadApiDeps): (req: Request) => Promise { + return async (req) => { + const path = new URL(req.url).pathname; + if (req.method === "GET" && path === "/api/projects.json") return json(projectsJson(deps)); + const itemMatch = ITEM_PATH.exec(path); + if (req.method === "GET" && itemMatch) { + let ref: string; + try { + ref = decodeURIComponent(itemMatch[1] as string); + } catch { + return json({ error: `malformed percent-encoding in path segment: ${itemMatch[1]}` }, 400); + } + const { status, body } = itemJson(deps, ref); + return json(body, status); + } + if (req.method === "GET" && path === "/api/roadmap.json") return json(roadmapJson(deps)); + if (req.method === "GET" && path === "/api/releases.json") return json(releasesJson(deps)); + return json({ error: `not found: ${path}` }, 404); + }; +} diff --git a/pm-stack/pm-service/src/read-api/genealogy.ts b/pm-stack/pm-service/src/read-api/genealogy.ts new file mode 100644 index 0000000000..350b90e4c3 --- /dev/null +++ b/pm-stack/pm-service/src/read-api/genealogy.ts @@ -0,0 +1,181 @@ +/** + * The genealogy read model (#9060 §6), ported from the laptop + * aggregator's #9070 implementation (pm-stack/aggregator/src/ + * genealogy.ts) — a port, not a redesign, per component A design §4: + * the derivation is pure over the merged pool + registry + roadmap + * rows, so what moves is the renderer + API surface, not the model. + * A port, not an import — this package deploys as one Worker bundle; + * the dual-edition conformance suite (design §8 slice 8) pins the + * two implementations to identical output. + * + * Chain breaks render honestly ("with no epic yet", "with no + * roadmap item yet") — never a fabricated link (#9060 §6). + */ +import type { ProjectPoolItem, RefKey } from "../collector/pool.ts"; + +export type GenealogyRelation = + | "parent" + | "historical-parent" + | "primary-parent" + | "spawned-by" + | "roadmap" + | "priority"; + +export interface GenealogyAncestor { + ref: RefKey; + title: string; + kind: string | null; + relation: GenealogyRelation; +} + +export interface GenealogyRelease { + title: string; + dueOn: string | null; + ref: RefKey; +} + +export interface ItemGenealogy { + ancestors: GenealogyAncestor[]; + release: GenealogyRelease | null; + afterRefs: RefKey[]; + sentence: string; +} + +/** + * A roadmap row as pm_roadmap_rows stores it — the aggregator's + * RoadmapRow (pm-stack/aggregator/src/model.ts) restricted to the + * columns slice 1's schema carries, with the #9060 §6 genealogy + * overlay (priority / afterRefs / releaseRef) the read API serves. + */ +export interface RoadmapRow { + id: number; + /** The registry subject: "grist://". */ + subject: string; + title: string; + area: string; + status: string; + horizon: string; + /** Validation warning; the original value remains in `horizon`. */ + horizonError?: string; + source: string; + notes: string; + links: { ref: RefKey; relation: string }[]; + /** Genealogy overlay; absent/null when no linked item resolves. */ + priority?: RefKey | null; + afterRefs?: RefKey[]; + releaseRef?: RefKey | null; + gristUrl?: string; + fileUrl?: string; +} + +const labelTarget = (labels: string[], prefix: string): string | null => + labels.find((label) => label.startsWith(prefix))?.slice(prefix.length) ?? null; + +/** Derive the item's known genealogy using only verified pool edges and labels. */ +export function deriveGenealogy(item: ProjectPoolItem, pool: readonly ProjectPoolItem[]): ItemGenealogy { + // Board memberships are separate pool rows, but Kind is canonical issue + // metadata. Preserve a populated Kind when a later satellite copy omits it. + const byRef = new Map(); + for (const entry of pool) { + const existing = byRef.get(entry.ref); + byRef.set(entry.ref, existing ? { ...existing, kind: existing.kind ?? entry.kind } : entry); + } + const chain: ProjectPoolItem[] = []; + const seen = new Set([item.ref]); + let cursor = item.parentRef ? byRef.get(item.parentRef) : undefined; + while (cursor && !seen.has(cursor.ref)) { + chain.push(cursor); + seen.add(cursor.ref); + cursor = cursor.parentRef ? byRef.get(cursor.parentRef) : undefined; + } + + const ancestors: GenealogyAncestor[] = []; + const add = (entry: ProjectPoolItem | undefined, relation: GenealogyRelation) => { + if (entry && !ancestors.some((ancestor) => ancestor.ref === entry.ref && ancestor.relation === relation)) { + ancestors.push({ ref: entry.ref, title: entry.title, kind: entry.kind, relation }); + } + }; + for (const entry of chain) add(entry, "parent"); + const historicalParents = (item.historicalParentRefs ?? []).flatMap((ref) => { + const former = byRef.get(ref); + if (!former) return []; + add(former, "historical-parent"); + return [former]; + }); + + const nearestEpic = chain.find((entry) => entry.kind === "Epic"); + const primarySlug = labelTarget(item.labels ?? [], "primary-parent/"); + const primaryEpic = primarySlug + ? pool.find((entry) => (entry.labels ?? []).includes(`epic/${primarySlug}`) && entry.kind === "Epic") + : undefined; + add(primaryEpic ?? nearestEpic, "primary-parent"); + + const design = + chain.find((entry) => (entry.labels ?? []).includes("kind/design") || entry.kind === "Design") ?? + (() => { + const designLabel = labelTarget(item.labels ?? [], "design/"); + return designLabel + ? pool.find( + (entry) => + (entry.labels ?? []).includes(`design/${designLabel}`) && + ((entry.labels ?? []).includes("kind/design") || entry.kind === "Design"), + ) + : undefined; + })(); + add(design, "spawned-by"); + + const roadmapItem = chain.find( + (entry) => (entry.labels ?? []).includes("kind/roadmap-item") || entry.kind === "Roadmap item", + ); + add(roadmapItem, "roadmap"); + const priority = roadmapItem + ? chain.find( + (entry) => + entry.ref !== roadmapItem.ref && + ((entry.labels ?? []).includes("kind/roadmap-item") || entry.kind === "Roadmap item"), + ) + : undefined; + add(priority, "priority"); + + const releaseItem = priority ?? roadmapItem; + const release = releaseItem?.milestone + ? { title: releaseItem.milestone.title, dueOn: releaseItem.milestone.dueOn, ref: releaseItem.ref } + : null; + const afterRefs = [...new Set((roadmapItem ?? priority ?? item).blockedBy ?? [])]; + const epicPhrase = nearestEpic ? `as part of epic ${nearestEpic.title} (${nearestEpic.ref})` : "with no epic yet"; + const designPhrase = design ? `, spawned by design ${design.title} (${design.ref})` : ", with no design yet"; + const roadmapPhrase = roadmapItem + ? `; on roadmap item ${roadmapItem.title} (${roadmapItem.ref})` + : "; with no roadmap item yet"; + const priorityPhrase = priority ? `, overall priority ${priority.title} (${priority.ref})` : ""; + const releasePhrase = release ? `; release ${release.title}${release.dueOn ? ` due ${release.dueOn}` : ""}` : ""; + const historicalPhrase = historicalParents.length + ? ` ${historicalParents.map((former) => `Formerly part of ${former.title} (${former.ref})`).join(". ")}.` + : ""; + return { + ancestors, + release, + afterRefs, + sentence: `Working on ${item.title} ${epicPhrase}${designPhrase}${roadmapPhrase}${priorityPhrase}${releasePhrase}.${historicalPhrase}`, + }; +} + +/** Attach genealogy overlay fields to roadmap rows when their links resolve. */ +export function enrichRoadmapRows(rows: readonly RoadmapRow[], pool: readonly ProjectPoolItem[]) { + const byRef = new Map(pool.map((item) => [item.ref, item])); + return rows.map((row) => { + const linked = [...row.links] + .sort((a, b) => Number(b.relation === "tracks") - Number(a.relation === "tracks")) + .map((link) => byRef.get(link.ref)) + .find((item): item is ProjectPoolItem => Boolean(item)); + const genealogy = linked ? deriveGenealogy(linked, pool) : null; + const roadmapRef = genealogy?.ancestors.find((ancestor) => ancestor.relation === "roadmap")?.ref; + const priorityRef = genealogy?.ancestors.find((ancestor) => ancestor.relation === "priority")?.ref ?? roadmapRef; + return { + ...row, + priority: priorityRef ?? null, + afterRefs: genealogy?.afterRefs ?? [], + releaseRef: genealogy?.release?.ref ?? null, + }; + }); +} diff --git a/pm-stack/pm-service/src/read-api/releases.ts b/pm-stack/pm-service/src/read-api/releases.ts new file mode 100644 index 0000000000..e6992d939b --- /dev/null +++ b/pm-stack/pm-service/src/read-api/releases.ts @@ -0,0 +1,201 @@ +/** + * Release-milestone close-out accounting (#9060 §4), ported from the + * laptop aggregator's #9067 implementation (pm-stack/aggregator/src/ + * releases.ts) — a port, not a redesign (component A design §4/§6: + * "#9060 §4 semantics unchanged"). A port, not an import — this + * package deploys as one Worker bundle; the dual-edition conformance + * suite (design §8 slice 8) pins the two implementations. + * + * Two milestone kinds (design D3): + * - program milestones: the existing rolling standing homes — dueOn is + * null, they never close; accounting is computed for them + * retroactively (counts only, no closures). + * - release milestones: bounded containers titled + * " — release " whose dueOn is the release + * date; when one closes, its snapshot is the close-out record. + * + * A snapshot counts the items a milestone covers, split closed vs + * carried-over (open at snapshot time — for an epic, carried-over is + * the pinned D5 meaning: the epic spans releases and moves on), in + * three categories (design §4): issues, designs (items carrying a + * design/ label or the kind/design label), and epics (Project + * Kind "Epic", or the epic marker labels `epic` / `meta/epic` — never + * `epic/`, which marks membership in an epic, not epic-ness). + * Categories are disjoint: an item is counted exactly once, epic + * first, then design, then issue. PRs are not milestone coverage and + * are never counted. + * + * Pure functions, no I/O — the store layer owns fetching. + */ +import type { MilestoneRef, ProjectPoolItem } from "../collector/pool.ts"; + +export type MilestoneKind = "program" | "release"; + +export interface CategoryCounts { + closed: number; + carriedOver: number; + total: number; +} + +export interface ReleaseSnapshot { + milestone: MilestoneRef; + kind: MilestoneKind; + /** The release date: a closed release milestone's closedAt date, + * else its dueOn. Null for program milestones (they never release). */ + releaseDate: string | null; + counts: { + issues: CategoryCounts; + designs: CategoryCounts; + epics: CategoryCounts; + total: CategoryCounts; + }; + /** Refs of epics still open at snapshot time — the carried-over + * list a closing milestone's snapshot must name (design D5). */ + carriedOverEpics: string[]; + /** The one-line close-out text, in the shape the design gives + * Drew's example ("closed with the release covering 123 issues, + * 23 designs, 4 epics") — this is the text written to a milestone + * description at close-out and served verbatim by the API. */ + descriptionLine: string; +} + +/** The minimal item shape the accounting needs — ProjectPoolItem + * satisfies it. */ +export interface MilestoneItemLike { + ref?: string; + state: "open" | "closed" | "merged"; + contentKind?: "issue" | "pr"; + kind?: string | null; + labels?: string[]; +} + +export function classifyMilestoneItem(item: MilestoneItemLike): "epic" | "design" | "issue" { + const labels = item.labels ?? []; + if (item.kind === "Epic" || labels.includes("epic") || labels.includes("meta/epic")) return "epic"; + if (labels.includes("kind/design") || labels.some((l) => l.startsWith("design/"))) return "design"; + return "issue"; +} + +/** Release milestones are the bounded kind: a dueOn (the release + * date), a closure, or the " — release <...>" title shape. + * Everything else is a rolling program milestone. */ +export function milestoneKind(milestone: MilestoneRef): MilestoneKind { + if (milestone.dueOn !== null || milestone.closedAt !== null) return "release"; + return / — release /.test(milestone.title) ? "release" : "program"; +} + +function emptyCounts(): CategoryCounts { + return { closed: 0, carriedOver: 0, total: 0 }; +} + +function snapshotDescriptionLine( + kind: MilestoneKind, + releaseDate: string | null, + counts: ReleaseSnapshot["counts"], +): string { + const covered = `${counts.total.total} items: ${counts.issues.total} issues, ${counts.designs.total} designs, ${counts.epics.total} epics`; + const split = `${counts.total.closed} closed, ${counts.total.carriedOver} carried over`; + if (kind === "program") + return `Program milestone (rolling, never closes) — retroactive accounting: ${covered} (${split}).`; + if (releaseDate) return `Closed with the release on ${releaseDate} covering ${covered} (${split}).`; + return `Release milestone (open) — accounting so far: ${covered} (${split}).`; +} + +/** Compute one milestone's close-out snapshot from the items the + * collector ingested for it. Oracle: every counted item is an issue + * (never a PR) in exactly one category, and closed + carriedOver + * equals total in every category. */ +export function computeMilestoneSnapshot(milestone: MilestoneRef, items: MilestoneItemLike[]): ReleaseSnapshot { + const counts: ReleaseSnapshot["counts"] = { + issues: emptyCounts(), + designs: emptyCounts(), + epics: emptyCounts(), + total: emptyCounts(), + }; + const carriedOverEpics: string[] = []; + for (const item of items) { + if (item.contentKind === "pr") continue; + const category = classifyMilestoneItem(item); + const bucket = category === "epic" ? counts.epics : category === "design" ? counts.designs : counts.issues; + const isClosed = item.state === "closed" || item.state === "merged"; + bucket.total += 1; + counts.total.total += 1; + if (isClosed) { + bucket.closed += 1; + counts.total.closed += 1; + } else { + bucket.carriedOver += 1; + counts.total.carriedOver += 1; + if (category === "epic" && item.ref) carriedOverEpics.push(item.ref); + } + } + carriedOverEpics.sort(); + const kind = milestoneKind(milestone); + const releaseDate = kind === "release" ? (milestone.closedAt ?? milestone.dueOn) : null; + return { + milestone, + kind, + releaseDate, + counts, + carriedOverEpics, + descriptionLine: snapshotDescriptionLine(kind, releaseDate, counts), + }; +} + +/** Snapshots for every milestone represented in the pool, unioned + * with `knownMilestones` — the retroactive pass: a known milestone + * with no pool items still gets a (zero-count) snapshot, so the + * existing program milestones all appear in /api/releases.json even + * before their items are Project-board members. Sorted by title for + * a stable served shape. */ +export function buildReleaseSnapshots( + items: ProjectPoolItem[], + knownMilestones: MilestoneRef[] = [], +): ReleaseSnapshot[] { + const byTitle = new Map(); + for (const known of knownMilestones) { + if (!byTitle.has(known.title)) byTitle.set(known.title, { milestone: known, items: [] }); + } + for (const item of items) { + if (!item.milestone) continue; + const entry = byTitle.get(item.milestone.title) ?? { milestone: item.milestone, items: [] }; + // Prefer the freshest milestone stamps the collector saw. + entry.milestone = item.milestone; + entry.items.push(item); + byTitle.set(item.milestone.title, entry); + } + return [...byTitle.values()] + .map(({ milestone, items: milestoneItems }) => computeMilestoneSnapshot(milestone, milestoneItems)) + .sort((a, b) => a.milestone.title.localeCompare(b.milestone.title)); +} + +/** + * Assemble the served snapshot from a stored pm_release_snapshots row + * (#9060 §4: the snapshot the stack stores at close-out is the record + * /api/releases.json serves). The typed columns carry the counts; the + * description line is rebuilt by the same builder the computed path + * uses, so a stored snapshot and a computed one read identically. + */ +export function releaseSnapshotFromStored(input: { + milestone: MilestoneRef; + kind: MilestoneKind; + releaseDate: string; + counts: { issues: CategoryCounts; designs: CategoryCounts; epics: CategoryCounts }; + carriedOverEpics: string[]; +}): ReleaseSnapshot { + const total: CategoryCounts = { + closed: input.counts.issues.closed + input.counts.designs.closed + input.counts.epics.closed, + carriedOver: + input.counts.issues.carriedOver + input.counts.designs.carriedOver + input.counts.epics.carriedOver, + total: input.counts.issues.total + input.counts.designs.total + input.counts.epics.total, + }; + const counts = { ...input.counts, total }; + return { + milestone: input.milestone, + kind: input.kind, + releaseDate: input.releaseDate, + counts, + carriedOverEpics: [...input.carriedOverEpics].sort(), + descriptionLine: snapshotDescriptionLine(input.kind, input.releaseDate, counts), + }; +} diff --git a/pm-stack/pm-service/src/read-api/store.ts b/pm-stack/pm-service/src/read-api/store.ts new file mode 100644 index 0000000000..5e5c49dcf1 --- /dev/null +++ b/pm-stack/pm-service/src/read-api/store.ts @@ -0,0 +1,227 @@ +/** + * The read API's tenant-DB surface: everything the four hosted read + * endpoints serve, read out of slice 1's schema as slices 1–2 wrote + * it. Read-only — this module issues SELECTs only; the collector and + * reconcile own every write path. + * + * Sources, per endpoint: + * - projects: pm_boards (the registry, via the collector's loader) + + * each board's latest pm_snapshots header + audit_json. + * - item: the merged pool — pm_items holds current state per board + * (the collector replaces a board's rows when its snapshot lands), + * and item_json is the full ProjectPoolItem the derivation runs on. + * - roadmap: pm_roadmap_rows, whose genealogy overlay columns + * (priority_ref / after_refs_json / release_ref) win per-field + * where set; unset fields are derived over the pool (genealogy.ts). + * - releases: pm_release_snapshots joined to pm_milestones where a + * close-out snapshot is stored (the stored record is what §4 says + * the API serves); milestones with no stored snapshot get the + * retroactive computed accounting over the pool (releases.ts). + */ +import type { MilestoneRef, ProjectAudit, ProjectPoolItem } from "../collector/pool.ts"; +import { loadRegistry } from "../collector/store.ts"; +import type { SqlDb } from "../tenant-store/migrate.ts"; +import type { BoardDef } from "../tenant-store/schema.ts"; +import { enrichRoadmapRows, type RoadmapRow } from "./genealogy.ts"; +import { + computeMilestoneSnapshot, + releaseSnapshotFromStored, + type CategoryCounts, + type MilestoneKind, + type ReleaseSnapshot, +} from "./releases.ts"; + +/** One board's entry in /api/projects.json's `projects[]` (#9060 §6): + * the registry def plus the board's latest snapshot audit. A board + * with no landed snapshot serves `snapshot: null, audit: null` — + * the absence is the honest state, never a fabricated audit. */ +export interface BoardSummary { + board: BoardDef; + snapshot: { + snapshotId: string; + generatedAt: string; + reportedTotal: number; + emittedEntries: number; + writer: string; + epoch: number; + } | null; + audit: ProjectAudit | null; +} + +interface SnapshotRow { + snapshot_id: string; + generated_at: string; + reported_total: number; + emitted_entries: number; + writer: string; + epoch: number; + audit_json: string; +} + +export function loadBoardSummaries(db: SqlDb): BoardSummary[] { + return loadRegistry(db).map((board) => { + const rows = db.all( + `SELECT snapshot_id, generated_at, reported_total, emitted_entries, writer, epoch, audit_json + FROM pm_snapshots WHERE board_id = ? + ORDER BY generated_at DESC, recorded_at DESC LIMIT 1`, + [board.id], + ); + const row = rows[0]; + if (!row) return { board, snapshot: null, audit: null }; + return { + board, + snapshot: { + snapshotId: row.snapshot_id, + generatedAt: row.generated_at, + reportedTotal: row.reported_total, + emittedEntries: row.emitted_entries, + writer: row.writer, + epoch: row.epoch, + }, + audit: JSON.parse(row.audit_json) as ProjectAudit, + }; + }); +} + +/** The merged pool: every board's current pm_items rows, in the + * collector's ProjectPoolItem shape (item_json is byte-faithful). + * A row that does not parse is a store bug and fails loudly, the + * same stance the collector's registry loader takes — a silently + * dropped item would fabricate the pool's contents. */ +export function loadPool(db: SqlDb): ProjectPoolItem[] { + const rows = db.all<{ item_json: string }>("SELECT item_json FROM pm_items ORDER BY board_id, ref"); + return rows.map((row) => JSON.parse(row.item_json) as ProjectPoolItem); +} + +interface RoadmapRowRow { + row_id: number; + subject: string; + title: string; + area: string; + status: string; + horizon: string; + horizon_error: string | null; + source: string; + notes: string; + links_json: string; + priority_ref: string | null; + after_refs_json: string; + release_ref: string | null; + grist_url: string | null; + file_url: string | null; +} + +/** Roadmap rows with the #9060 §6 overlay served: a stored overlay + * field wins where set; an unset field is derived over the pool via + * the genealogy enrichment, so a row whose tracks link resolves + * serves its priority/afterRefs/releaseRef even before any overlay + * is recorded for it. */ +export function loadRoadmapRows(db: SqlDb, pool: readonly ProjectPoolItem[]): RoadmapRow[] { + const rows = db.all( + `SELECT row_id, subject, title, area, status, horizon, horizon_error, source, notes, + links_json, priority_ref, after_refs_json, release_ref, grist_url, file_url + FROM pm_roadmap_rows ORDER BY row_id`, + ); + const base: RoadmapRow[] = rows.map((row) => ({ + id: row.row_id, + subject: row.subject, + title: row.title, + area: row.area, + status: row.status, + horizon: row.horizon, + ...(row.horizon_error !== null ? { horizonError: row.horizon_error } : {}), + source: row.source, + notes: row.notes, + links: JSON.parse(row.links_json) as RoadmapRow["links"], + ...(row.grist_url !== null ? { gristUrl: row.grist_url } : {}), + ...(row.file_url !== null ? { fileUrl: row.file_url } : {}), + })); + const derived = enrichRoadmapRows(base, pool); + return derived.map((row, index) => { + const stored = rows[index] as RoadmapRowRow; + const storedAfterRefs = JSON.parse(stored.after_refs_json) as string[]; + return { + ...row, + priority: stored.priority_ref ?? row.priority ?? null, + afterRefs: storedAfterRefs.length ? storedAfterRefs : (row.afterRefs ?? []), + releaseRef: stored.release_ref ?? row.releaseRef ?? null, + }; + }); +} + +interface StoredSnapshotRow { + repo: string; + title: string; + kind: MilestoneKind; + due_on: string | null; + closed_at: string | null; + release_date: string; + issues_covered: number; + issues_closed: number; + issues_carried_over: number; + designs_covered: number; + designs_closed: number; + designs_carried_over: number; + epics_covered: number; + epics_closed: number; + epics_carried_over: number; + carried_over_epics_json: string; +} + +const storedCounts = (covered: number, closed: number, carriedOver: number): CategoryCounts => ({ + closed, + carriedOver, + total: covered, +}); + +/** Milestone close-out snapshots for /api/releases.json: stored + * snapshots (pm_release_snapshots) are the record where they exist; + * every other milestone the pool carries gets the retroactive + * computed accounting (§4), keyed by repo + title so two repos' + * same-titled milestones never merge. Sorted by title, then repo — + * a stable served shape. */ +export function loadReleaseSnapshots(db: SqlDb, pool: readonly ProjectPoolItem[]): ReleaseSnapshot[] { + const storedRows = db.all( + `SELECT s.repo, m.title, m.kind, m.due_on, m.closed_at, s.release_date, + s.issues_covered, s.issues_closed, s.issues_carried_over, + s.designs_covered, s.designs_closed, s.designs_carried_over, + s.epics_covered, s.epics_closed, s.epics_carried_over, + s.carried_over_epics_json + FROM pm_release_snapshots s + JOIN pm_milestones m ON m.repo = s.repo AND m.number = s.milestone_number`, + ); + const storedKeys = new Set(storedRows.map((row) => `${row.repo}\n${row.title}`)); + const keyed: { key: string; snapshot: ReleaseSnapshot }[] = storedRows.map((row) => ({ + key: `${row.repo}\n${row.title}`, + snapshot: releaseSnapshotFromStored({ + milestone: { title: row.title, dueOn: row.due_on, closedAt: row.closed_at }, + kind: row.kind, + releaseDate: row.release_date, + counts: { + issues: storedCounts(row.issues_covered, row.issues_closed, row.issues_carried_over), + designs: storedCounts(row.designs_covered, row.designs_closed, row.designs_carried_over), + epics: storedCounts(row.epics_covered, row.epics_closed, row.epics_carried_over), + }, + carriedOverEpics: JSON.parse(row.carried_over_epics_json) as string[], + }), + })); + + const groups = new Map(); + for (const item of pool) { + if (!item.milestone) continue; + const key = `${item.repo}\n${item.milestone.title}`; + if (storedKeys.has(key)) continue; + const entry = groups.get(key) ?? { milestone: item.milestone, items: [] }; + // Prefer the freshest milestone stamps the collector saw. + entry.milestone = item.milestone; + entry.items.push(item); + groups.set(key, entry); + } + for (const [key, { milestone, items }] of groups) { + keyed.push({ key, snapshot: computeMilestoneSnapshot(milestone, items) }); + } + + return keyed + .sort((a, b) => a.snapshot.milestone.title.localeCompare(b.snapshot.milestone.title) || a.key.localeCompare(b.key)) + .map(({ snapshot }) => snapshot); +} diff --git a/pm-stack/pm-service/test/read-api.test.ts b/pm-stack/pm-service/test/read-api.test.ts new file mode 100644 index 0000000000..6c2306ee30 --- /dev/null +++ b/pm-stack/pm-service/test/read-api.test.ts @@ -0,0 +1,355 @@ +/** + * Hosted read API acceptance suite (#12828). + * + * Oracle: issue #12828's acceptance criteria and #9060 §6/§8 — + * all four endpoints serve the §6 shapes from tenant-DB data; the + * genealogy sentence renders end-to-end on the §8 worked example + * (the crate-split chain: steps → #3447 → #3195 → #2056); chain + * breaks and missing data render honestly, never fabricated. + * + * The pool is seeded through slice 2's real landing path + * (landSnapshot) so the suite also pins collector → API agreement; + * roadmap rows and milestone snapshots are inserted as the rows + * slice 1's schema defines (their writers are other slices). + * The tenant DB is bun:sqlite in-memory with slice 1's real + * migrations applied. + */ +import { describe, expect, test } from "bun:test"; +import { createReadApiHandler, itemJson, projectsJson, releasesJson, roadmapJson } from "../src/read-api/api.ts"; +import { deriveGenealogy } from "../src/read-api/genealogy.ts"; +import { landSnapshot } from "../src/collector/store.ts"; +import type { ProjectAudit, ProjectPoolItem } from "../src/collector/pool.ts"; +import { tenantStoreMigrations } from "../src/tenant-store/load.ts"; +import { applyMigrations, type SqlDb } from "../src/tenant-store/migrate.ts"; +import type { BoardDef } from "../src/tenant-store/schema.ts"; +import { openTenantDb } from "../src/tenant-store/sqlite.ts"; + +const T1 = "2026-11-23T06:00:00.000Z"; +const T2 = "2026-11-23T07:00:00.000Z"; +const REPO = "developing-today/code"; +const ref = (number: number) => `${REPO}#${number}`; + +const BOARDS: BoardDef[] = [ + { + id: "devtoday-main", + org: "developing-today", + number: 4, + nodeId: "PVT_kwDOAZNvF84Bouay", + url: "https://github.com/orgs/developing-today/projects/4", + role: "overall", + siblingOrder: 0, + title: "Developing Today", + }, + { + id: "forks-main", + org: "developing-today-forks", + number: 1, + nodeId: "PVT_kwDOCEOo084BrYAh", + url: "https://github.com/orgs/developing-today-forks/projects/1", + role: "project", + parentBoardId: "devtoday-main", + siblingOrder: 1, + title: "Developing Today Forks", + }, +]; + +// --------------------------------------------------------------------------- +// The #9060 §8 worked example: the crate-split chain, fully native — +// steps #4403–#4411 → #3447 (epic) → #3195 (design) → #2056 (roadmap +// item carrying the release milestone). Modeled with step #4403. +// --------------------------------------------------------------------------- + +function poolItem(partial: Partial & { number: number; title: string }): ProjectPoolItem { + const url = `https://github.com/${REPO}/issues/${partial.number}`; + return { + id: `PVTI_${partial.number}`, + databaseId: partial.number * 10, + url, + projectUrl: "https://github.com/orgs/developing-today/projects/4", + repo: REPO, + issueUrl: url, + state: "open", + contentKind: "issue", + labels: [], + status: "Todo", + area: "ID", + horizon: null, + kind: null, + ...partial, + ref: ref(partial.number), + }; +} + +const STEP = poolItem({ + number: 4403, + title: "crate-split step: extract the id-events crate", + kind: "Task", + status: "In Progress", + labels: ["primary-parent/id-crate-split"], + parentRef: ref(3447), + milestone: { title: "ID program", dueOn: null, closedAt: null }, +}); +const EPIC = poolItem({ + number: 3447, + title: "epic: ID crate split", + kind: "Epic", + labels: ["epic", "epic/id-crate-split", "design/id-crate-split"], + parentRef: ref(3195), +}); +const DESIGN = poolItem({ + number: 3195, + title: "design: ID crate split", + labels: ["kind/design", "design/id-crate-split"], + parentRef: ref(2056), +}); +const ROADMAP = poolItem({ + number: 2056, + title: "ID platform roadmap", + labels: ["kind/roadmap-item"], + milestone: { title: "ID platform — release 2026-12-01", dueOn: "2026-12-01", closedAt: null }, + blockedBy: [ref(1999)], +}); +const ORPHAN = poolItem({ number: 7777, title: "orphan task with no chain", kind: "Task" }); +const POOL = [STEP, EPIC, DESIGN, ROADMAP, ORPHAN]; + +const AUDIT: ProjectAudit = { + title: "Developing Today", + number: 4, + url: "https://github.com/orgs/developing-today/projects/4", + generatedAt: "2026-11-23T05:59:00.000Z", + totalItems: POOL.length, + fields: [{ id: "PVTF_status", name: "Status", dataType: "SINGLE_SELECT" }], + views: [{ id: "PVTV_1", name: "ID Program", layout: "TABLE_LAYOUT", filter: null }], + counts: { status: { Todo: 4, "In Progress": 1 }, area: { ID: 5 }, repo: { [REPO]: 5 } }, +}; + +async function seededDb(): Promise { + const { sql } = openTenantDb(); + applyMigrations(sql, await tenantStoreMigrations(), () => T1); + for (const board of BOARDS) { + sql.run( + `INSERT INTO pm_boards (board_id, org, number, node_id, url, role, parent_board_id, sibling_order, title, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [ + board.id, + board.org, + board.number, + board.nodeId, + board.url, + board.role, + board.parentBoardId ?? null, + board.siblingOrder, + board.title, + T1, + ], + ); + } + landSnapshot(sql, { + snapshotId: "snap-main-1", + boardId: "devtoday-main", + generatedAt: AUDIT.generatedAt, + audit: AUDIT, + counts: { reportedTotal: POOL.length, emittedEntries: POOL.length }, + items: POOL, + now: T1, + }); + // Roadmap rows: one derived from its tracks link, one with the + // stored overlay set (the overlay wins where set, #9060 §6). + sql.run( + `INSERT INTO pm_roadmap_rows (row_id, subject, title, area, status, horizon, horizon_error, source, notes, + links_json, priority_ref, after_refs_json, release_ref, grist_url, file_url, recorded_at) + VALUES (1, 'grist:docA/tblA/1', 'ID crate split', 'ID', 'Active', '', NULL, 'grist', '', + ?, NULL, '[]', NULL, NULL, NULL, ?)`, + [JSON.stringify([{ ref: ref(3447), relation: "tracks" }]), T1], + ); + sql.run( + `INSERT INTO pm_roadmap_rows (row_id, subject, title, area, status, horizon, horizon_error, source, notes, + links_json, priority_ref, after_refs_json, release_ref, grist_url, file_url, recorded_at) + VALUES (2, 'grist:docA/tblA/2', 'Stored overlay row', 'ID', 'Active', '', NULL, 'grist', '', + '[]', ?, ?, ?, NULL, NULL, ?)`, + [ref(2000), JSON.stringify([ref(1999)]), ref(2056), T1], + ); + // A closed release milestone with its stored close-out snapshot. + sql.run( + `INSERT INTO pm_milestones (repo, number, title, kind, due_on, closed_at, state, recorded_at) + VALUES (?, 3, 'ID platform — release 2026-11-01', 'release', '2026-11-01', '2026-11-01T17:00:00.000Z', 'closed', ?)`, + [REPO, T1], + ); + sql.run( + `INSERT INTO pm_release_snapshots (repo, milestone_number, release_date, + issues_covered, issues_closed, issues_carried_over, + designs_covered, designs_closed, designs_carried_over, + epics_covered, epics_closed, epics_carried_over, + carried_over_epics_json, computed_at, snapshot_json) + VALUES (?, 3, '2026-11-01', 10, 8, 2, 3, 3, 0, 2, 1, 1, ?, ?, '{}')`, + [REPO, JSON.stringify([ref(2056)]), T1], + ); + return sql; +} + +const deps = async () => ({ db: await seededDb(), now: () => T2 }); + +describe("/api/projects.json", () => { + test("projects[] serves every registry board with its per-board audit", async () => { + const body = projectsJson(await deps()); + expect(body.generatedAt).toBe(T2); + expect(body.projects).toHaveLength(2); + const [main, forks] = body.projects; + expect(main?.board.id).toBe("devtoday-main"); + expect(main?.audit).toEqual(AUDIT); + expect(main?.snapshot?.writer).toBe("hosted"); + expect(main?.snapshot?.epoch).toBe(0); + // A board with no landed snapshot: the absence is served + // honestly as nulls, never a fabricated audit. + expect(forks?.board.id).toBe("forks-main"); + expect(forks?.snapshot).toBeNull(); + expect(forks?.audit).toBeNull(); + expect(body.items.map((item) => item.ref)).toEqual([ref(2056), ref(3195), ref(3447), ref(4403), ref(7777)]); + }); +}); + +describe("/api/item/.json — the #9060 §8 worked example", () => { + test("the crate-split chain renders end-to-end: ancestors, release, sentence", async () => { + const { status, body } = itemJson(await deps(), ref(4403)); + expect(status).toBe(200); + const served = body as { + ancestors: { ref: string; relation: string }[]; + release: { title: string; dueOn: string | null; ref: string } | null; + genealogySentence: string; + }; + expect(served.ancestors).toEqual([ + { ref: ref(3447), title: EPIC.title, kind: "Epic", relation: "parent" }, + { ref: ref(3195), title: DESIGN.title, kind: null, relation: "parent" }, + { ref: ref(2056), title: ROADMAP.title, kind: null, relation: "parent" }, + { ref: ref(3447), title: EPIC.title, kind: "Epic", relation: "primary-parent" }, + { ref: ref(3195), title: DESIGN.title, kind: null, relation: "spawned-by" }, + { ref: ref(2056), title: ROADMAP.title, kind: null, relation: "roadmap" }, + ]); + expect(served.release).toEqual({ + title: "ID platform — release 2026-12-01", + dueOn: "2026-12-01", + ref: ref(2056), + }); + expect(served.genealogySentence).toBe( + `Working on ${STEP.title} as part of epic ${EPIC.title} (${ref(3447)}), ` + + `spawned by design ${DESIGN.title} (${ref(3195)}); on roadmap item ${ROADMAP.title} (${ref(2056)}); ` + + `release ID platform — release 2026-12-01 due 2026-12-01.`, + ); + }); + + test("a chain break renders honestly: no epic, no design, no roadmap item, no release", async () => { + const { status, body } = itemJson(await deps(), ref(7777)); + expect(status).toBe(200); + const served = body as { ancestors: unknown[]; release: unknown; genealogySentence: string }; + expect(served.ancestors).toEqual([]); + expect(served.release).toBeNull(); + expect(served.genealogySentence).toBe( + `Working on ${ORPHAN.title} with no epic yet, with no design yet; with no roadmap item yet.`, + ); + }); + + test("an unknown ref is a structured 404, never a fabricated item", async () => { + const { status, body } = itemJson(await deps(), ref(999999)); + expect(status).toBe(404); + expect(body).toEqual({ error: `no pool item with ref ${ref(999999)}` }); + }); + + test("the priority rung: the release rides the priority item's milestone", () => { + const priority = poolItem({ + number: 2000, + title: "overall priority: ID platform", + labels: ["kind/roadmap-item"], + milestone: { title: "ID platform — release 2027-01-15", dueOn: "2027-01-15", closedAt: null }, + }); + const item = poolItem({ number: 2002, title: "leaf task", parentRef: ref(2001) }); + const roadmap = poolItem({ number: 2001, title: "ID roadmap item", labels: ["kind/roadmap-item"], parentRef: ref(2000) }); + const genealogy = deriveGenealogy(item, [item, roadmap, priority]); + expect(genealogy.ancestors).toContainEqual({ + ref: ref(2000), + title: priority.title, + kind: null, + relation: "priority", + }); + expect(genealogy.release).toEqual({ title: "ID platform — release 2027-01-15", dueOn: "2027-01-15", ref: ref(2000) }); + expect(genealogy.sentence).toContain(`overall priority ${priority.title} (${ref(2000)})`); + }); +}); + +describe("/api/roadmap.json", () => { + test("rows serve priority/afterRefs/releaseRef — derived from tracks links, stored overlay winning where set", async () => { + const body = roadmapJson(await deps()); + expect(body.rows).toHaveLength(2); + const [derived, stored] = body.rows; + // Row 1 has no stored overlay: the overlay is derived over the + // pool from its tracks link to the crate-split epic. + expect(derived?.priority).toBe(ref(2056)); + expect(derived?.afterRefs).toEqual([ref(1999)]); + expect(derived?.releaseRef).toBe(ref(2056)); + // Row 2's stored overlay is served exactly as recorded. + expect(stored?.priority).toBe(ref(2000)); + expect(stored?.afterRefs).toEqual([ref(1999)]); + expect(stored?.releaseRef).toBe(ref(2056)); + }); +}); + +describe("/api/releases.json", () => { + test("stored close-out snapshots are the record; unstored milestones get retroactive accounting", async () => { + const body = releasesJson(await deps()); + expect(body.releases.map((release) => release.milestone.title)).toEqual([ + "ID platform — release 2026-11-01", + "ID platform — release 2026-12-01", + "ID program", + ]); + const [stored, open, program] = body.releases; + // The stored snapshot, served as recorded (§4 close-out shape). + expect(stored?.kind).toBe("release"); + expect(stored?.releaseDate).toBe("2026-11-01"); + expect(stored?.counts).toEqual({ + issues: { closed: 8, carriedOver: 2, total: 10 }, + designs: { closed: 3, carriedOver: 0, total: 3 }, + epics: { closed: 1, carriedOver: 1, total: 2 }, + total: { closed: 12, carriedOver: 3, total: 15 }, + }); + expect(stored?.carriedOverEpics).toEqual([ref(2056)]); + expect(stored?.descriptionLine).toBe( + "Closed with the release on 2026-11-01 covering 15 items: 10 issues, 3 designs, 2 epics (12 closed, 3 carried over).", + ); + // The open release milestone on the roadmap item: computed. + expect(open?.kind).toBe("release"); + expect(open?.releaseDate).toBe("2026-12-01"); + expect(open?.counts.total).toEqual({ closed: 0, carriedOver: 1, total: 1 }); + // The ported line builder keys on releaseDate presence, not on + // closure: an open release milestone with a dueOn renders the + // "closed with the release on " line. That is the laptop + // #9067 behavior verbatim — parity ports it, never redesigns it. + expect(open?.descriptionLine).toBe( + "Closed with the release on 2026-12-01 covering 1 items: 1 issues, 0 designs, 0 epics (0 closed, 1 carried over).", + ); + // The rolling program milestone: retroactive counts, no release date. + expect(program?.kind).toBe("program"); + expect(program?.releaseDate).toBeNull(); + expect(program?.descriptionLine).toBe( + "Program milestone (rolling, never closes) — retroactive accounting: 1 items: 1 issues, 0 designs, 0 epics (0 closed, 1 carried over).", + ); + }); +}); + +describe("the fetch handler", () => { + test("routes the four GET endpoints and 404s everything else", async () => { + const handler = createReadApiHandler(await deps()); + const get = async (path: string) => { + const res = await handler(new Request(`http://pm.test${path}`)); + return { status: res.status, body: (await res.json()) as Record }; + }; + expect((await get("/api/projects.json")).status).toBe(200); + expect((await get("/api/roadmap.json")).status).toBe(200); + expect((await get("/api/releases.json")).status).toBe(200); + const item = await get(`/api/item/${encodeURIComponent(ref(4403))}.json`); + expect(item.status).toBe(200); + expect(item.body.genealogySentence).toContain("crate-split step"); + expect((await get(`/api/item/${encodeURIComponent(ref(424242))}.json`)).status).toBe(404); + expect((await get("/api/nope.json")).status).toBe(404); + const post = await handler(new Request("http://pm.test/api/projects.json", { method: "POST" })); + expect(post.status).toBe(404); + }); +});