Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .github/test-suite-registry.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
5 changes: 3 additions & 2 deletions .github/workflows/pm-stack-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
43 changes: 43 additions & 0 deletions pm-stack/pm-service/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<id>.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/<id>.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.
16 changes: 15 additions & 1 deletion pm-stack/pm-service/package.json
Original file line number Diff line number Diff line change
@@ -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"}
{
"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"
}
99 changes: 99 additions & 0 deletions pm-stack/pm-service/src/read-api/api.ts
Original file line number Diff line number Diff line change
@@ -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/<id>.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<Response> {
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);
};
}
181 changes: 181 additions & 0 deletions pm-stack/pm-service/src/read-api/genealogy.ts
Original file line number Diff line number Diff line change
@@ -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:<docId>/<tableId>/<rowId>". */
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<RefKey, ProjectPoolItem>();
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<RefKey>([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,
};
});
}
Loading