diff --git a/.github/test-suite-registry.json b/.github/test-suite-registry.json index 64362da9ed..0932f9c144 100644 --- a/.github/test-suite-registry.json +++ b/.github/test-suite-registry.json @@ -682,6 +682,21 @@ "status": "mapped", "related_issues": [9860] }, + { + "id": "pm-service.tenant-store", + "paths": [ + "pm-stack/pm-service/test/tenant-store.test.ts" + ], + "invocation": "cd pm-stack/pm-service && bun test", + "venue": { + "workflow": ".github/workflows/pm-stack-tests.yml", + "job_step": "Test pm-service tenant-store suite", + "state": "active", + "dispatchable": true + }, + "status": "mapped", + "related_issues": [12825] + }, { "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 4c799e4751..e0d5805bb2 100644 --- a/.github/workflows/pm-stack-tests.yml +++ b/.github/workflows/pm-stack-tests.yml @@ -321,3 +321,17 @@ jobs: exit 1 fi bun test + + # Bun suite for #12825: pm-stack/pm-service/test/ + # (tenant-store.test.ts, the component A PM tenant store + # schema + migrations conformance suite) must not be a + # silently skipped suite either. It needs only bun + # (bun:sqlite is built in), no install step. + - name: Test pm-service tenant-store suite + working-directory: pm-stack/pm-service + run: | + if [ ! -d test ] || ! ls test/*.test.ts >/dev/null 2>&1; then + echo "::error::Missing pm-service test suite — pm-stack/pm-service/test has no *.test.ts files; the suite was not run." + exit 1 + fi + bun test diff --git a/pm-stack/pm-service/README.md b/pm-stack/pm-service/README.md new file mode 100644 index 0000000000..9fc76a77e4 --- /dev/null +++ b/pm-stack/pm-service/README.md @@ -0,0 +1,53 @@ +# PM service, Workers edition (component A) + +The hosted edition of the PM service: the laptop aggregator's +capabilities re-implemented in TypeScript as one hosted service on +Cloudflare Workers, consuming the **same data model** as the laptop +edition (#9060), so both editions read the same world. + +Design: `doc/2026-11-23T03-22-03Z_design_pm-service-workers-edition/` +(component A of epic #9078, under #9079). Implementation slices are +§8 of that design; this package grows one slice at a time. + +## Slice 1 — PM tenant store: schema + migrations (#12825) + +`src/tenant-store/` is the store the rest of the service builds on: + +- `migrations/0001_pm_tenant_store.sql` — the DDL of record. One + schema in the tenant's Turso DB (component E tenant plane, #9083 + §2.2) holding the whole PM store: board registry rows (#9060 §1 + `BoardDef`, stored as data), collector snapshots, the merged item + pool, hierarchy/link records (#9060 §11), Metadata copies (#9060 + §12), roadmap rows, milestones + release-milestone close-out + snapshots (#9060 §4), reconcile findings, and the writer-of-record + lease row (design §5). +- `migrate.ts` — the migration runner: applies pending migrations in + version order, each in a transaction, and records them in + `pm_schema_migrations` (the schema-version record). Runtime-agnostic + over a minimal `SqlDb` surface. +- `load.ts` — loads the `NNNN_name.sql` files as migrations. +- `schema.ts` — the wire shapes the store holds (`BoardDef`, + `LinkRecord`, `PmMetadataBlock`, `WriterLease`) and their + validators; the conformance contract against #9060 and the laptop + collector's output types. +- `sqlite.ts` — a bun:sqlite `SqlDb` adapter for tests/local tooling + (a tenant DB is SQLite-shaped wherever it lives; Turso/libSQL + speaks the same dialect). + +Invariants carried by the schema and pinned by the test suite: + +- **Tenant plane only.** These migrations are never applied to the + central tenancy DB — no PM content is central (E §2.3). +- **No tokens or keys in any table.** The suite fails if any column + name in the schema names a token, secret, password, credential, or + key value. +- **Shapes match #9060 exactly.** Registry / pool / link-record / + Metadata fixtures in the suite are the collector's landed output + shapes (`pm-stack/aggregator/src/model.ts`, `board-registry.ts`). + +Run the suite: + +```sh +bun test # from this directory +bun run typecheck +``` diff --git a/pm-stack/pm-service/bun.lock b/pm-stack/pm-service/bun.lock new file mode 100644 index 0000000000..4ac4ab65f3 --- /dev/null +++ b/pm-stack/pm-service/bun.lock @@ -0,0 +1,18 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "pm-service", + "devDependencies": { + "@cloudflare/workers-types": "^4.20251011.0", + "typescript": "^5.6.0", + }, + }, + }, + "packages": { + "@cloudflare/workers-types": ["@cloudflare/workers-types@4.20260702.1", "", {}, "sha512-mOhf5TUEB1m2vPrxtqoIGfz0fUC9xyxRDx5gWHy5s+OCo6dcV+g7wI1R7gYCMFohhqF/2y2xeKVwMwCJjfn/WA=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + } +} diff --git a/pm-stack/pm-service/package.json b/pm-stack/pm-service/package.json new file mode 100644 index 0000000000..f009e1b4c9 --- /dev/null +++ b/pm-stack/pm-service/package.json @@ -0,0 +1 @@ +{"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.","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 diff --git a/pm-stack/pm-service/src/bun.d.ts b/pm-stack/pm-service/src/bun.d.ts new file mode 100644 index 0000000000..7864fd200e --- /dev/null +++ b/pm-stack/pm-service/src/bun.d.ts @@ -0,0 +1,35 @@ +/** + * Minimal ambient declarations for the Bun runtime surface this + * package uses, so `tsc --noEmit` stays dependency-light (the + * package's only devDependencies are the Workers types + TypeScript, + * mirroring pm-stack/decision-events-worker). These declare only + * what src/ calls; they are not a general Bun type library. + */ + +declare module "bun:sqlite" { + export class Database { + constructor(path?: string); + exec(sql: string): void; + query(sql: string): { + run(...params: (string | number | null)[]): unknown; + all(...params: (string | number | null)[]): unknown[]; + get(...params: (string | number | null)[]): unknown; + }; + transaction(fn: () => T): () => T; + } +} + +declare const Bun: { + file(path: string): { text(): Promise }; + Glob: new ( + pattern: string, + ) => { + scan(options: { cwd: string }): AsyncIterable; + }; +}; + +/** Bun extends ImportMeta with the module's URL and directory. */ +interface ImportMeta { + url: string; + dir: string; +} diff --git a/pm-stack/pm-service/src/tenant-store/load.ts b/pm-stack/pm-service/src/tenant-store/load.ts new file mode 100644 index 0000000000..7187f5dd0f --- /dev/null +++ b/pm-stack/pm-service/src/tenant-store/load.ts @@ -0,0 +1,30 @@ +/** + * Loads the tenant store's SQL migrations from a directory of + * `NNNN_name.sql` files (the DDL of record lives in those files, per + * the pm-stack migration convention — see pm-stack/external-comms). + * Files are returned in version order; a filename that does not parse + * or a duplicated version is an error, never a silent skip. + */ +import type { Migration } from "./migrate.ts"; + +export async function loadMigrations(dir: string): Promise { + const files: string[] = []; + for await (const file of new Bun.Glob("*.sql").scan({ cwd: dir })) files.push(file); + files.sort(); + const migrations: Migration[] = []; + const seen = new Set(); + for (const file of files) { + const match = /^(\d+)_([a-z0-9_]+)\.sql$/.exec(file); + if (!match) throw new Error(`migration filename must be NNNN_name.sql: ${file}`); + const version = Number(match[1]); + if (seen.has(version)) throw new Error(`duplicate migration version ${version}: ${file}`); + seen.add(version); + migrations.push({ version, name: match[2] as string, sql: await Bun.file(`${dir}/${file}`).text() }); + } + return migrations.sort((a, b) => a.version - b.version); +} + +/** The migrations shipped with this package, from ./migrations. */ +export function tenantStoreMigrations(): Promise { + return loadMigrations(new URL("./migrations", import.meta.url).pathname); +} diff --git a/pm-stack/pm-service/src/tenant-store/migrate.ts b/pm-stack/pm-service/src/tenant-store/migrate.ts new file mode 100644 index 0000000000..ef6e694df7 --- /dev/null +++ b/pm-stack/pm-service/src/tenant-store/migrate.ts @@ -0,0 +1,93 @@ +/** + * Migration runner for the PM tenant store (#12825). + * + * Applies numbered SQL migrations to ONE tenant's Turso DB (component + * E tenant plane) in version order, each in its own transaction, and + * records every applied migration in `pm_schema_migrations` — that + * table is the store's schema-version record. Re-running is a no-op + * for already-applied versions; a version recorded with a different + * name than the migration on disk is drift and fails loudly. + * + * The runner is runtime-agnostic: it talks to the minimal SqlDb + * surface below. `sqlite.ts` adapts bun:sqlite for tests and local + * tooling; the hosted service will adapt its libSQL client the same + * way. This module never sees a database URL or token (E §2.3: no + * tokens in any DB, and none in this code path either). + */ + +export interface SqlDb { + exec(sql: string): void; + run(sql: string, params?: readonly (string | number | null)[]): void; + all(sql: string, params?: readonly (string | number | null)[]): T[]; + transaction(fn: () => T): T; +} + +export interface Migration { + version: number; + name: string; + sql: string; +} + +interface AppliedRow { + version: number; + name: string; +} + +const BOOKKEEPING_DDL = `CREATE TABLE IF NOT EXISTS pm_schema_migrations ( + version INTEGER PRIMARY KEY, + name TEXT NOT NULL, + applied_at TEXT NOT NULL +)`; + +export function applyMigrations( + db: SqlDb, + migrations: readonly Migration[], + now: () => string = () => new Date().toISOString(), +): { applied: number[]; current: number[] } { + const ordered = [...migrations].sort((a, b) => a.version - b.version); + const seen = new Set(); + for (const migration of ordered) { + if (!Number.isInteger(migration.version) || migration.version < 1) + throw new Error(`invalid migration version: ${migration.version}`); + if (seen.has(migration.version)) throw new Error(`duplicate migration version: ${migration.version}`); + seen.add(migration.version); + } + + db.exec(BOOKKEEPING_DDL); + const recorded = new Map( + db.all("SELECT version, name FROM pm_schema_migrations ORDER BY version").map((row) => [ + row.version, + row.name, + ]), + ); + + const applied: number[] = []; + for (const migration of ordered) { + const recordedName = recorded.get(migration.version); + if (recordedName !== undefined) { + if (recordedName !== migration.name) + throw new Error( + `migration drift: version ${migration.version} is recorded as "${recordedName}" but the file on disk is "${migration.name}"`, + ); + continue; + } + db.transaction(() => { + db.exec(migration.sql); + db.run("INSERT INTO pm_schema_migrations (version, name, applied_at) VALUES (?, ?, ?)", [ + migration.version, + migration.name, + now(), + ]); + }); + applied.push(migration.version); + } + return { applied, current: currentSchemaVersion(db) }; +} + +/** Recorded schema version of a tenant DB: the highest applied migration, or [] when none has run. */ +export function currentSchemaVersion(db: SqlDb): number[] { + db.exec(BOOKKEEPING_DDL); + return db + .all<{ version: number }>("SELECT version FROM pm_schema_migrations ORDER BY version") + .map((row) => row.version); +} diff --git a/pm-stack/pm-service/src/tenant-store/migrations/0001_pm_tenant_store.sql b/pm-stack/pm-service/src/tenant-store/migrations/0001_pm_tenant_store.sql new file mode 100644 index 0000000000..a2061bb576 --- /dev/null +++ b/pm-stack/pm-service/src/tenant-store/migrations/0001_pm_tenant_store.sql @@ -0,0 +1,276 @@ +-- PM tenant store — schema + migrations (component A slice 1, #12825). +-- +-- Design: doc/2026-11-23T03-22-03Z_design_pm-service-workers-edition +-- §3 (data homes) and §5 (writer-of-record lease); shapes pinned to +-- #9060 (doc/2026-11-12T22-50-00Z_design_pm-board-hierarchy-genealogy) +-- and to the laptop collector's output types +-- (pm-stack/aggregator/src/model.ts, board-registry.ts, projects.ts). +-- +-- This schema lives in ONE tenant's Turso DB (component E tenant +-- plane, #9083 §2.2). It is never applied to the central tenancy DB: +-- no PM content is central (E §2.3), and no table here holds a token, +-- key, secret, or credential value — the tenant-store test suite +-- asserts that by column name. Timestamps are TEXT (ISO-8601) and +-- JSON documents are TEXT, per the pm-stack Turso type mapping +-- (pm-stack/external-comms/migration-0002). +-- +-- Applied by src/tenant-store/migrate.ts, which records each applied +-- migration in pm_schema_migrations (the schema-version record). + +-- --------------------------------------------------------------------- +-- Board registry (#9060 §1: BoardDef, stored as data exactly as on +-- the laptop; the collector's landed registry is the seed shape). +-- --------------------------------------------------------------------- +CREATE TABLE pm_boards ( + board_id TEXT PRIMARY KEY CHECK (trim(board_id) <> ''), + org TEXT NOT NULL CHECK (trim(org) <> ''), + number INTEGER NOT NULL CHECK (number >= 1), + node_id TEXT NOT NULL CHECK (trim(node_id) <> ''), -- PVT_… + url TEXT NOT NULL, + role TEXT NOT NULL CHECK (role IN ('overall', 'project', 'wip', 'register', 'ideas')), + parent_board_id TEXT REFERENCES pm_boards (board_id), + sibling_order INTEGER NOT NULL, + title TEXT NOT NULL, + recorded_at TEXT NOT NULL, + UNIQUE (org, number) +); + +-- --------------------------------------------------------------------- +-- Collector snapshots: one header row per landed per-board snapshot +-- (the collector's ProjectSnapshot/ProjectAudit pair). Pool rows and +-- the audit document hang off this header; writer + epoch are the +-- write provenance (component A design §7 invariant 2). +-- --------------------------------------------------------------------- +CREATE TABLE pm_snapshots ( + snapshot_id TEXT PRIMARY KEY CHECK (trim(snapshot_id) <> ''), + board_id TEXT NOT NULL REFERENCES pm_boards (board_id), + generated_at TEXT NOT NULL, + reported_total INTEGER NOT NULL CHECK (reported_total >= 0), + emitted_entries INTEGER NOT NULL CHECK (emitted_entries >= 0), + writer TEXT NOT NULL CHECK (writer IN ('laptop', 'hosted')), + epoch INTEGER NOT NULL CHECK (epoch >= 0), + audit_json TEXT NOT NULL, -- full ProjectAudit for this board's snapshot + recorded_at TEXT NOT NULL +); + +CREATE INDEX pm_snapshots_board_idx ON pm_snapshots (board_id, generated_at); + +-- --------------------------------------------------------------------- +-- The merged item pool: one row per board item per snapshot, in the +-- collector's ProjectPoolItem shape. item_json is the full emitted +-- item, byte-faithful; the typed columns are the extracted keys the +-- read API and genealogy walker query (the #9060 §15 pattern: full +-- document as JSON plus extracted key fields). +-- --------------------------------------------------------------------- +CREATE TABLE pm_items ( + board_id TEXT NOT NULL REFERENCES pm_boards (board_id), + item_id TEXT NOT NULL, -- PVTI_… project item node id + snapshot_id TEXT NOT NULL REFERENCES pm_snapshots (snapshot_id), + ref TEXT NOT NULL, -- "owner/repo#123", the canonical item key + repo TEXT NOT NULL, + number INTEGER NOT NULL CHECK (number >= 1), + content_kind TEXT NOT NULL CHECK (content_kind IN ('issue', 'pr')), + state TEXT NOT NULL CHECK (state IN ('open', 'closed', 'merged')), + draft INTEGER NOT NULL DEFAULT 0 CHECK (draft IN (0, 1)), + title TEXT NOT NULL, + url TEXT NOT NULL, + project_url TEXT NOT NULL, + issue_url TEXT NOT NULL, + database_id INTEGER, + author TEXT, + labels_json TEXT NOT NULL DEFAULT '[]', + status TEXT, -- Project "Status" field; NULL when unset on the item + area TEXT, -- Project "Area" field + horizon TEXT, -- Project "Horizon" field + kind TEXT, -- Project "Kind" field (Task | Epic), not the content kind + milestone_title TEXT, + milestone_due_on TEXT, -- release date for release milestones (#9060 §4) + milestone_closed_at TEXT, + sub_issues_total INTEGER CHECK (sub_issues_total IS NULL OR sub_issues_total >= 0), + sub_issues_completed INTEGER CHECK (sub_issues_completed IS NULL OR sub_issues_completed >= 0), + parent_ref TEXT, + epic_ref TEXT, + blocked_by_json TEXT NOT NULL DEFAULT '[]', + blocks_json TEXT NOT NULL DEFAULT '[]', + historical_parent_refs_json TEXT NOT NULL DEFAULT '[]', + spawn_rollup_json TEXT, + edge_diagnostics_json TEXT NOT NULL DEFAULT '[]', + item_updated_at TEXT, + closed_at TEXT, + merged_at TEXT, + item_json TEXT NOT NULL, -- full ProjectPoolItem as emitted + recorded_at TEXT NOT NULL, + PRIMARY KEY (board_id, item_id) +); + +CREATE INDEX pm_items_ref_idx ON pm_items (ref); +CREATE INDEX pm_items_snapshot_idx ON pm_items (snapshot_id); + +-- --------------------------------------------------------------------- +-- Hierarchy / link records (#9060 §11): every link is a record with +-- relation, status, and provenance — never a bare pointer. Board → +-- board links use the same shape with kind 'board' (the registry +-- stores board links as link records, §11). A historical link must +-- carry until + reason; a removed link must carry its reason +-- (misclassification) so the removal stays auditable. +-- --------------------------------------------------------------------- +CREATE TABLE pm_links ( + link_id TEXT PRIMARY KEY CHECK (trim(link_id) <> ''), + source_kind TEXT NOT NULL CHECK (source_kind IN ('item', 'board')), + source_ref TEXT NOT NULL, -- item ref "owner/repo#123", or board_id + target_kind TEXT NOT NULL CHECK (target_kind IN ('item', 'board')), + target_ref TEXT NOT NULL, -- item ref, or board_id + target_repo TEXT, -- #9060 §12 target.repo (item targets only) + target_number INTEGER, -- #9060 §12 target.number (item targets only) + relation TEXT NOT NULL CHECK (trim(relation) <> ''), -- parent | spawned-by | blocks | blocked-by | relates | board-parent | primary-parent | … + status TEXT NOT NULL CHECK (status IN ('active', 'historical', 'removed')), + since TEXT, + until TEXT, + reason TEXT, -- split | carryover | reparent-on-close | misclassification | … + provenance_json TEXT NOT NULL DEFAULT '{}', -- writer / epoch / session provenance + recorded_at TEXT NOT NULL, + CHECK (status <> 'historical' OR (until IS NOT NULL AND reason IS NOT NULL)), + CHECK (status <> 'removed' OR reason IS NOT NULL), + CHECK ( + (target_kind = 'item' AND target_repo IS NOT NULL AND target_number IS NOT NULL) + OR (target_kind = 'board' AND target_repo IS NULL AND target_number IS NULL) + ) +); + +CREATE INDEX pm_links_source_idx ON pm_links (source_ref, relation, status); +CREATE INDEX pm_links_target_idx ON pm_links (target_ref, relation, status); + +-- --------------------------------------------------------------------- +-- Metadata copies (#9060 §12): the tenant DB's copy of each item's +-- canonical Metadata block. metadata_json is the full block, +-- byte-faithful; extracted columns serve the §13/§15 query surface +-- (by direct parent, session, lane, queue). +-- --------------------------------------------------------------------- +CREATE TABLE pm_item_metadata ( + ref TEXT PRIMARY KEY, -- "owner/repo#123" + repo TEXT NOT NULL, + number INTEGER NOT NULL CHECK (number >= 1), + kind TEXT NOT NULL CHECK (kind IN ('issue', 'pr')), + pm_meta INTEGER NOT NULL CHECK (pm_meta >= 1), -- block format version + direct_parent_ref TEXT, + direct_parent_kind TEXT, + lineage_design_ref TEXT, + lineage_roadmap_item_ref TEXT, + lineage_priority_ref TEXT, + provenance_session_id TEXT, + provenance_lane TEXT, + provenance_queue_id TEXT, + provenance_json TEXT NOT NULL, -- the §12 provenance object + metadata_json TEXT NOT NULL, -- the full canonical block + recorded_at TEXT NOT NULL +); + +CREATE INDEX pm_item_metadata_parent_idx ON pm_item_metadata (direct_parent_ref); +CREATE INDEX pm_item_metadata_session_idx ON pm_item_metadata (provenance_session_id); + +-- --------------------------------------------------------------------- +-- Roadmap rows: the "Program roadmap" row (aggregator RoadmapRow) +-- plus the genealogy overlay the hosted read API serves +-- (priority / afterRefs / releaseRef, #9060 §6). +-- --------------------------------------------------------------------- +CREATE TABLE pm_roadmap_rows ( + row_id INTEGER PRIMARY KEY, -- Grist row id (RoadmapRow.id) + subject TEXT NOT NULL UNIQUE, -- "grist://" + title TEXT NOT NULL, + area TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT '', + horizon TEXT NOT NULL DEFAULT '', + horizon_error TEXT, + source TEXT NOT NULL DEFAULT '', + notes TEXT NOT NULL DEFAULT '', + links_json TEXT NOT NULL DEFAULT '[]', + priority_ref TEXT, -- overlay: overall-priority item ref + after_refs_json TEXT NOT NULL DEFAULT '[]', -- overlay: sequencing refs + release_ref TEXT, -- overlay: release item ref + grist_url TEXT, + file_url TEXT, + recorded_at TEXT NOT NULL +); + +-- --------------------------------------------------------------------- +-- Milestones, two kinds (#9060 §4): program milestones are rolling +-- standing homes (due_on NULL, never close); release milestones are +-- bounded containers whose due_on is the release date. +-- --------------------------------------------------------------------- +CREATE TABLE pm_milestones ( + repo TEXT NOT NULL, + number INTEGER NOT NULL CHECK (number >= 1), -- GitHub milestone number + title TEXT NOT NULL, + kind TEXT NOT NULL CHECK (kind IN ('program', 'release')), + due_on TEXT, + closed_at TEXT, + state TEXT NOT NULL CHECK (state IN ('open', 'closed')), + recorded_at TEXT NOT NULL, + PRIMARY KEY (repo, number), + CHECK (kind <> 'release' OR due_on IS NOT NULL) +); + +-- --------------------------------------------------------------------- +-- Release-milestone close-out snapshots (#9060 §4): counts of issues, +-- designs, and epics covered, each split closed / carried-over, plus +-- the release date — the accounting /api/releases.json serves. +-- --------------------------------------------------------------------- +CREATE TABLE pm_release_snapshots ( + repo TEXT NOT NULL, + milestone_number INTEGER NOT NULL, + release_date TEXT NOT NULL, + issues_covered INTEGER NOT NULL CHECK (issues_covered >= 0), + issues_closed INTEGER NOT NULL CHECK (issues_closed >= 0), + issues_carried_over INTEGER NOT NULL CHECK (issues_carried_over >= 0), + designs_covered INTEGER NOT NULL CHECK (designs_covered >= 0), + designs_closed INTEGER NOT NULL CHECK (designs_closed >= 0), + designs_carried_over INTEGER NOT NULL CHECK (designs_carried_over >= 0), + epics_covered INTEGER NOT NULL CHECK (epics_covered >= 0), + epics_closed INTEGER NOT NULL CHECK (epics_closed >= 0), + epics_carried_over INTEGER NOT NULL CHECK (epics_carried_over >= 0), + carried_over_epics_json TEXT NOT NULL DEFAULT '[]', -- refs of epics carried over (§4 carryover) + computed_at TEXT NOT NULL, + snapshot_json TEXT NOT NULL, -- full accounting document + PRIMARY KEY (repo, milestone_number), + FOREIGN KEY (repo, milestone_number) REFERENCES pm_milestones (repo, number), + CHECK (issues_closed <= issues_covered AND issues_carried_over <= issues_covered), + CHECK (designs_closed <= designs_covered AND designs_carried_over <= designs_covered), + CHECK (epics_closed <= epics_covered AND epics_carried_over <= epics_covered) +); + +-- --------------------------------------------------------------------- +-- Reconcile findings: the drift / invariant report rows both +-- editions produce (primary-parent divergence, non-record-writer +-- writes, lease violations, Grist drift, …). Findings are the +-- enforcement surface where GitHub cannot hard-block (#9060 §7). +-- --------------------------------------------------------------------- +CREATE TABLE pm_reconcile_findings ( + finding_id TEXT PRIMARY KEY CHECK (trim(finding_id) <> ''), + board_id TEXT REFERENCES pm_boards (board_id), + kind TEXT NOT NULL CHECK (trim(kind) <> ''), + severity TEXT NOT NULL DEFAULT 'warning' CHECK (severity IN ('info', 'warning', 'error')), + subject_ref TEXT, -- item ref or board id the finding is about + summary TEXT NOT NULL, + detail_json TEXT NOT NULL DEFAULT '{}', + writer TEXT CHECK (writer IS NULL OR writer IN ('laptop', 'hosted')), + epoch INTEGER CHECK (epoch IS NULL OR epoch >= 0), + recorded_at TEXT NOT NULL, + resolved_at TEXT +); + +CREATE INDEX pm_reconcile_findings_board_idx ON pm_reconcile_findings (board_id, recorded_at); + +-- --------------------------------------------------------------------- +-- Writer-of-record lease (component A design §5): one row per board +-- — {board_id, writer, epoch, heartbeat_at}. The epoch is a fencing +-- counter: it increments on every flip, and every reconcile run +-- reads this row before its first mutation and aborts if it is not +-- the recorded writer at the current epoch. +-- --------------------------------------------------------------------- +CREATE TABLE pm_writer_leases ( + board_id TEXT PRIMARY KEY REFERENCES pm_boards (board_id), + writer TEXT NOT NULL CHECK (writer IN ('laptop', 'hosted')), + epoch INTEGER NOT NULL CHECK (epoch >= 1), + heartbeat_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); diff --git a/pm-stack/pm-service/src/tenant-store/schema.ts b/pm-stack/pm-service/src/tenant-store/schema.ts new file mode 100644 index 0000000000..bc71a62c72 --- /dev/null +++ b/pm-stack/pm-service/src/tenant-store/schema.ts @@ -0,0 +1,209 @@ +/** + * Wire shapes the PM tenant store holds, and their validators. + * + * These types are the conformance contract for #12825: they mirror + * #9060's design shapes and the laptop collector's landed output + * types field for field, so a row the store accepts is a row the + * collector can emit and the hosted read API can serve. + * + * - BoardDef — #9060 §1; pm-stack/aggregator/src/board-registry.ts + * - LinkRecord — #9060 §11 (relation / status / provenance records) + * - PmMetadataBlock — #9060 §12 (the canonical Metadata block) + * - WriterLease — component A design §5 (writer-of-record lease) + * + * Validators return a list of problems (empty = valid), mirroring + * validateBoardRegistry in the aggregator: callers decide whether a + * problem is fatal; nothing here throws on shape. + */ + +export type BoardRole = "overall" | "project" | "wip" | "register" | "ideas"; + +/** #9060 §1 board registry entry, stored as a pm_boards row. */ +export interface BoardDef { + id: string; + org: string; + number: number; + nodeId: string; + url: string; + role: BoardRole; + parentBoardId?: string; + siblingOrder: number; + title: string; +} + +const BOARD_ROLES: readonly string[] = ["overall", "project", "wip", "register", "ideas"]; + +export function validateBoardDef(value: unknown): string[] { + if (!isRecord(value)) return ["board def must be an object"]; + const problems: string[] = []; + if (typeof value.id !== "string" || !value.id.trim()) problems.push("board id must not be empty"); + if (typeof value.org !== "string" || !value.org.trim()) problems.push("board org must not be empty"); + if (!Number.isInteger(value.number) || (value.number as number) < 1) + problems.push(`invalid project number: ${String(value.id)}`); + if (typeof value.nodeId !== "string" || !value.nodeId.startsWith("PVT_")) + problems.push(`invalid project node id: ${String(value.id)}`); + if (typeof value.role !== "string" || !BOARD_ROLES.includes(value.role)) + problems.push(`invalid board role: ${String(value.role)}`); + if (value.parentBoardId !== undefined && (typeof value.parentBoardId !== "string" || !value.parentBoardId.trim())) + problems.push(`invalid parent board id: ${String(value.id)}`); + if (!Number.isInteger(value.siblingOrder)) problems.push(`invalid sibling order: ${String(value.id)}`); + if (typeof value.title !== "string" || !value.title.trim()) problems.push("board title must not be empty"); + if (typeof value.url === "string" && typeof value.org === "string" && Number.isInteger(value.number)) { + try { + if (new URL(value.url).pathname !== `/orgs/${value.org}/projects/${value.number as number}`) + problems.push(`project URL does not match org/number: ${String(value.id)}`); + } catch { + problems.push(`invalid project URL: ${String(value.id)}`); + } + } else { + problems.push(`invalid project URL: ${String(value.id)}`); + } + return problems; +} + +export type LinkStatus = "active" | "historical" | "removed"; + +/** #9060 §12 link target for item links: {repo, number}. */ +export interface LinkTarget { + repo: string; + number: number; +} + +/** + * #9060 §11 link record, as stored in pm_links. The source is an item + * ref ("owner/repo#123") or a board id; the target is an item + * ({repo, number}) or a board ({boardId}) — links are level-agnostic. + */ +export interface LinkRecord { + sourceKind: "item" | "board"; + sourceRef: string; + target: LinkTarget | { boardId: string }; + relation: string; + status: LinkStatus; + since?: string | null; + until?: string | null; + reason?: string | null; +} + +const LINK_STATUSES: readonly string[] = ["active", "historical", "removed"]; + +/** "owner/repo#123" — the registry's canonical key for an issue or PR. */ +export function isRefKey(value: unknown): value is string { + return typeof value === "string" && /^[^/\s#]+\/[^/\s#]+#\d+$/.test(value); +} + +/** Target / relation / status / until / reason checks shared by pm_links rows and §12 block links. */ +function validateLinkFields(value: Record): string[] { + const problems: string[] = []; + const target = value.target; + const targetIsItem = isRecord(target) && typeof target.repo === "string" && Number.isInteger(target.number); + const targetIsBoard = isRecord(target) && typeof target.boardId === "string" && target.boardId.trim().length > 0; + if (!targetIsItem && !targetIsBoard) problems.push("link target must be {repo, number} or {boardId}"); + if (typeof value.relation !== "string" || !value.relation.trim()) problems.push("link relation must not be empty"); + if (typeof value.status !== "string" || !LINK_STATUSES.includes(value.status)) + problems.push(`invalid link status: ${String(value.status)}`); + // #9060 §11: historical links carry until + reason; removed links + // carry their reason so the removal stays auditable. + if (value.status === "historical") { + if (typeof value.until !== "string" || !value.until) problems.push("historical link must carry until"); + if (typeof value.reason !== "string" || !value.reason) problems.push("historical link must carry a reason"); + } + if (value.status === "removed" && (typeof value.reason !== "string" || !value.reason)) + problems.push("removed link must carry a reason"); + return problems; +} + +export function validateLinkRecord(value: unknown): string[] { + if (!isRecord(value)) return ["link record must be an object"]; + const problems: string[] = []; + if (value.sourceKind === "item") { + if (!isRefKey(value.sourceRef)) problems.push(`link source is not an item ref: ${String(value.sourceRef)}`); + } else if (value.sourceKind === "board") { + if (typeof value.sourceRef !== "string" || !value.sourceRef.trim()) + problems.push("link source board id must not be empty"); + } else { + problems.push(`invalid link source kind: ${String(value.sourceKind)}`); + } + return [...problems, ...validateLinkFields(value)]; +} + +/** #9060 §12: the canonical Metadata block every issue and PR carries. */ +export interface PmMetadataBlock { + pm_meta: 1; + direct_parent: { repo: string; number: number; kind: string } | null; + links: Array<{ + target: LinkTarget; + relation: string; + status: LinkStatus; + since?: string | null; + until?: string | null; + reason?: string | null; + }>; + lineage: { + design: string | null; + roadmap_item: string | null; + priority: string | null; + }; + provenance: Record; +} + +export function validateMetadataBlock(value: unknown): string[] { + if (!isRecord(value)) return ["metadata block must be an object"]; + const problems: string[] = []; + if (value.pm_meta !== 1) problems.push(`unsupported pm_meta version: ${String(value.pm_meta)}`); + const parent = value.direct_parent; + if (parent !== null) { + if (!isRecord(parent) || typeof parent.repo !== "string" || !Number.isInteger(parent.number) || typeof parent.kind !== "string") + problems.push("direct_parent must be null or {repo, number, kind}"); + } + if (!Array.isArray(value.links)) { + problems.push("links must be an array"); + } else { + value.links.forEach((link, index) => { + if (!isRecord(link)) { + problems.push(`links[${index}] must be an object`); + return; + } + // §12 block links are item → item by construction (the block's + // own item is the source), so only the shared fields apply. + for (const problem of validateLinkFields(link)) problems.push(`links[${index}]: ${problem}`); + }); + } + if (!isRecord(value.lineage)) { + problems.push("lineage must be an object"); + } else { + for (const key of ["design", "roadmap_item", "priority"] as const) { + const entry = value.lineage[key]; + if (entry !== null && typeof entry !== "string") problems.push(`lineage.${key} must be a string or null`); + } + } + if (!isRecord(value.provenance)) problems.push("provenance must be an object"); + return problems; +} + +export type WriterKind = "laptop" | "hosted"; + +/** Component A design §5: the writer-of-record lease row. */ +export interface WriterLease { + boardId: string; + writer: WriterKind; + epoch: number; + heartbeatAt: string; +} + +export function validateWriterLease(value: unknown): string[] { + if (!isRecord(value)) return ["writer lease must be an object"]; + const problems: string[] = []; + if (typeof value.boardId !== "string" || !value.boardId.trim()) problems.push("lease board id must not be empty"); + if (value.writer !== "laptop" && value.writer !== "hosted") + problems.push(`invalid lease writer: ${String(value.writer)}`); + if (!Number.isInteger(value.epoch) || (value.epoch as number) < 1) + problems.push(`invalid lease epoch: ${String(value.epoch)}`); + if (typeof value.heartbeatAt !== "string" || Number.isNaN(Date.parse(value.heartbeatAt))) + problems.push("lease heartbeat must be an ISO-8601 timestamp"); + return problems; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/pm-stack/pm-service/src/tenant-store/sqlite.ts b/pm-stack/pm-service/src/tenant-store/sqlite.ts new file mode 100644 index 0000000000..a147faf0b4 --- /dev/null +++ b/pm-stack/pm-service/src/tenant-store/sqlite.ts @@ -0,0 +1,28 @@ +/** + * bun:sqlite adapter for the tenant store's SqlDb surface — the + * test/local-tooling backend. A tenant DB is SQLite-shaped wherever + * it lives (Turso/libSQL speaks the same dialect), so the migration + * suite runs against this adapter unchanged. Foreign keys are ON: + * the schema's references are part of the contract, not decoration. + */ +import { Database } from "bun:sqlite"; +import type { SqlDb } from "./migrate.ts"; + +export function bunSqliteDb(db: Database): SqlDb { + return { + exec: (sql) => db.exec(sql), + run: (sql, params = []) => { + db.query(sql).run(...(params as (string | number | null)[])); + }, + all: (sql: string, params: readonly (string | number | null)[] = []) => + db.query(sql).all(...(params as (string | number | null)[])) as T[], + transaction: (fn: () => T): T => db.transaction(fn)(), + }; +} + +/** Open a tenant DB at `path` (":memory:" for tests) with its SqlDb adapter. */ +export function openTenantDb(path = ":memory:"): { db: Database; sql: SqlDb } { + const db = new Database(path); + db.exec("PRAGMA foreign_keys = ON"); + return { db, sql: bunSqliteDb(db) }; +} diff --git a/pm-stack/pm-service/test/tenant-store.test.ts b/pm-stack/pm-service/test/tenant-store.test.ts new file mode 100644 index 0000000000..d7a05f4655 --- /dev/null +++ b/pm-stack/pm-service/test/tenant-store.test.ts @@ -0,0 +1,464 @@ +/** + * PM tenant store conformance suite (#12825). + * + * Oracle: the merged component A design (§3 data homes, §5 lease), + * #9060's design shapes (§1 BoardDef, §4 milestones, §11 link + * records, §12 Metadata), and the laptop collector's landed output + * types (pm-stack/aggregator/src/model.ts ProjectPoolItem, + * board-registry.ts PROJECT_BOARDS). Fixtures below are those shapes; + * the suite fails if the schema or the validators drift from them. + */ +import { describe, expect, test } from "bun:test"; +import { tenantStoreMigrations } from "../src/tenant-store/load.ts"; +import { applyMigrations, currentSchemaVersion, type Migration } from "../src/tenant-store/migrate.ts"; +import { + validateBoardDef, + validateLinkRecord, + validateMetadataBlock, + validateWriterLease, + type BoardDef, +} from "../src/tenant-store/schema.ts"; +import { openTenantDb } from "../src/tenant-store/sqlite.ts"; + +const NOW = "2026-11-23T06:00:00.000Z"; +const now = () => NOW; + +async function migratedDb() { + const { db, sql } = openTenantDb(); + const migrations = await tenantStoreMigrations(); + const result = applyMigrations(sql, migrations, now); + return { db, sql, migrations, result }; +} + +/** The laptop collector's landed registry (board-registry.ts PROJECT_BOARDS). */ +const LANDED_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", + }, + { + id: "lab-cluster", + org: "Clustered-Computing", + number: 1, + nodeId: "PVT_kwDOAlO1HM4BrYAm", + url: "https://github.com/orgs/Clustered-Computing/projects/1", + role: "project", + parentBoardId: "devtoday-main", + siblingOrder: 2, + title: "Lab Cluster", + }, +]; + +function insertBoard(sql: ReturnType["sql"], board: BoardDef) { + 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, NOW], + ); +} + +describe("migrations", () => { + test("apply to an empty tenant DB, record the schema version, and are idempotent", async () => { + const { sql, result } = await migratedDb(); + expect(result.applied).toEqual([1]); + expect(currentSchemaVersion(sql)).toEqual([1]); + const rows = sql.all<{ version: number; name: string; applied_at: string }>( + "SELECT version, name, applied_at FROM pm_schema_migrations", + ); + expect(rows).toEqual([{ version: 1, name: "pm_tenant_store", applied_at: NOW }]); + + const migrations = await tenantStoreMigrations(); + expect(applyMigrations(sql, migrations, now).applied).toEqual([]); + expect(currentSchemaVersion(sql)).toEqual([1]); + }); + + test("create the full PM store schema (design §3 + §5)", async () => { + const { sql } = await migratedDb(); + const tables = sql + .all<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name") + .map((row) => row.name); + expect(tables).toEqual([ + "pm_boards", + "pm_item_metadata", + "pm_items", + "pm_links", + "pm_milestones", + "pm_reconcile_findings", + "pm_release_snapshots", + "pm_roadmap_rows", + "pm_schema_migrations", + "pm_snapshots", + "pm_writer_leases", + ]); + }); + + test("fail loudly when a recorded migration's name drifts from the file on disk", async () => { + const { sql, migrations } = await migratedDb(); + sql.run("UPDATE pm_schema_migrations SET name = 'renamed_elsewhere' WHERE version = 1"); + expect(() => applyMigrations(sql, migrations, now)).toThrow(/migration drift/); + }); + + test("no table holds a token, key, secret, password, or credential column (E §2.3)", async () => { + const { sql } = await migratedDb(); + const tables = sql + .all<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'table'") + .map((row) => row.name); + const offenders: string[] = []; + for (const table of tables) { + for (const column of sql.all<{ name: string }>(`PRAGMA table_info(${table})`)) { + if (/(token|secret|password|credential|key)/i.test(column.name)) offenders.push(`${table}.${column.name}`); + } + } + expect(offenders).toEqual([]); + }); + + test("the shipped migration files load in order with parsed versions", async () => { + const migrations: Migration[] = await tenantStoreMigrations(); + expect(migrations.map((m) => [m.version, m.name])).toEqual([[1, "pm_tenant_store"]]); + expect(migrations[0]?.sql).toContain("CREATE TABLE pm_writer_leases"); + }); +}); + +describe("board registry (#9060 §1)", () => { + test("the collector's landed registry validates and round-trips as rows", async () => { + const { sql } = await migratedDb(); + for (const board of LANDED_BOARDS) { + expect(validateBoardDef(board)).toEqual([]); + insertBoard(sql, board); + } + const rows = sql.all<{ board_id: string; role: string; parent_board_id: string | null }>( + "SELECT board_id, role, parent_board_id FROM pm_boards ORDER BY sibling_order", + ); + expect(rows).toEqual([ + { board_id: "devtoday-main", role: "overall", parent_board_id: null }, + { board_id: "forks-main", role: "project", parent_board_id: "devtoday-main" }, + { board_id: "lab-cluster", role: "project", parent_board_id: "devtoday-main" }, + ]); + }); + + test("role is a closed vocabulary and (org, number) is unique", async () => { + const { sql } = await migratedDb(); + insertBoard(sql, LANDED_BOARDS[0] as BoardDef); + expect(() => insertBoard(sql, { ...(LANDED_BOARDS[0] as BoardDef), id: "other", role: "bogus" as BoardDef["role"] })).toThrow(); + expect(() => insertBoard(sql, { ...(LANDED_BOARDS[0] as BoardDef), id: "dupe" })).toThrow(); + expect(validateBoardDef({ ...(LANDED_BOARDS[0] as BoardDef), role: "bogus" }).length).toBeGreaterThan(0); + }); +}); + +/** A collector ProjectPoolItem (aggregator model.ts), as emitted for the crate-split epic. */ +const POOL_ITEM = { + boardId: "devtoday-main", + id: "PVTI_lADOAZNvF84Bouayzg12345", + databaseId: 12345, + url: "https://github.com/orgs/developing-today/projects/4/views/1?pane=issue&itemId=12345", + projectUrl: "https://github.com/orgs/developing-today/projects/4", + ref: "developing-today/code#3447", + repo: "developing-today/code", + number: 3447, + issueUrl: "https://github.com/developing-today/code/issues/3447", + title: "epic: id crate split", + state: "open", + contentKind: "issue", + labels: ["epic", "epic/id-crate-split"], + author: "dezren39", + updatedAt: "2026-11-12T10:00:00.000Z", + milestone: { title: "ID platform — release 2026-12-01", dueOn: "2026-12-01", closedAt: null }, + subIssuesSummary: { total: 9, completed: 4 }, + status: "In Progress", + area: "ID", + horizon: "Now", + kind: "Epic", + parentRef: "developing-today/code#3195", + epicRef: "developing-today/code#2056", + blockedBy: [], + blocks: ["developing-today/code#4403"], +}; + +describe("merged item pool (collector ProjectPoolItem shape)", () => { + test("a snapshot header + pool item store byte-faithful JSON with extracted keys", async () => { + const { sql } = await migratedDb(); + insertBoard(sql, LANDED_BOARDS[0] as BoardDef); + sql.run( + `INSERT INTO pm_snapshots (snapshot_id, board_id, generated_at, reported_total, emitted_entries, writer, epoch, audit_json, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ["snap-1", "devtoday-main", NOW, 1229, 1200, "laptop", 1, "{}", NOW], + ); + sql.run( + `INSERT INTO pm_items (board_id, item_id, snapshot_id, ref, repo, number, content_kind, state, draft, title, + url, project_url, issue_url, database_id, author, labels_json, status, area, horizon, kind, + milestone_title, milestone_due_on, milestone_closed_at, sub_issues_total, sub_issues_completed, + parent_ref, epic_ref, blocked_by_json, blocks_json, item_updated_at, item_json, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [ + POOL_ITEM.boardId, POOL_ITEM.id, "snap-1", POOL_ITEM.ref, POOL_ITEM.repo, POOL_ITEM.number, + POOL_ITEM.contentKind, POOL_ITEM.state, 0, POOL_ITEM.title, POOL_ITEM.url, POOL_ITEM.projectUrl, + POOL_ITEM.issueUrl, POOL_ITEM.databaseId, POOL_ITEM.author, JSON.stringify(POOL_ITEM.labels), + POOL_ITEM.status, POOL_ITEM.area, POOL_ITEM.horizon, POOL_ITEM.kind, POOL_ITEM.milestone.title, + POOL_ITEM.milestone.dueOn, POOL_ITEM.milestone.closedAt, POOL_ITEM.subIssuesSummary.total, + POOL_ITEM.subIssuesSummary.completed, POOL_ITEM.parentRef, POOL_ITEM.epicRef, + JSON.stringify(POOL_ITEM.blockedBy), JSON.stringify(POOL_ITEM.blocks), POOL_ITEM.updatedAt, + JSON.stringify(POOL_ITEM), NOW, + ], + ); + const row = sql.all<{ ref: string; status: string; kind: string; epic_ref: string; item_json: string }>( + "SELECT ref, status, kind, epic_ref, item_json FROM pm_items WHERE board_id = 'devtoday-main'", + )[0]; + expect(row?.ref).toBe("developing-today/code#3447"); + expect(row?.status).toBe("In Progress"); + expect(row?.kind).toBe("Epic"); + expect(row?.epic_ref).toBe("developing-today/code#2056"); + expect(JSON.parse(row?.item_json as string)).toEqual(POOL_ITEM); + }); + + test("pool rows require a known board (foreign keys enforced)", async () => { + const { sql } = await migratedDb(); + expect(() => + sql.run( + `INSERT INTO pm_snapshots (snapshot_id, board_id, generated_at, reported_total, emitted_entries, writer, epoch, audit_json, recorded_at) + VALUES ('snap-x', 'no-such-board', ?, 0, 0, 'laptop', 0, '{}', ?)`, + [NOW, NOW], + ), + ).toThrow(); + }); +}); + +describe("link records (#9060 §11)", () => { + const insertLink = (sql: ReturnType["sql"], row: (string | number | null)[]) => + sql.run( + `INSERT INTO pm_links (link_id, source_kind, source_ref, target_kind, target_ref, target_repo, target_number, + relation, status, since, until, reason, provenance_json, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + row, + ); + + test("active, historical, removed, and board-parent records validate and store", async () => { + const { sql } = await migratedDb(); + const records = [ + { + sourceKind: "item", sourceRef: "developing-today/code#4403", + target: { repo: "developing-today/code", number: 3447 }, + relation: "parent", status: "active", since: "2026-11-02", + }, + { + sourceKind: "item", sourceRef: "developing-today/code#4403", + target: { repo: "developing-today/code", number: 123 }, + relation: "parent", status: "historical", since: "2026-11-02", until: "2026-11-12", reason: "split", + }, + { + sourceKind: "item", sourceRef: "developing-today/code#4403", + target: { repo: "developing-today/code", number: 999 }, + relation: "parent", status: "removed", since: "2026-11-02", reason: "misclassification", + }, + { + sourceKind: "board", sourceRef: "forks-main", + target: { boardId: "devtoday-main" }, + relation: "board-parent", status: "active", + }, + ] as const; + for (const [index, record] of records.entries()) { + expect(validateLinkRecord(record)).toEqual([]); + const target = record.target; + insertLink(sql, [ + `link-${index}`, record.sourceKind, record.sourceRef, + "boardId" in target ? "board" : "item", + "boardId" in target ? target.boardId : `${target.repo}#${target.number}`, + "boardId" in target ? null : target.repo, + "boardId" in target ? null : target.number, + record.relation, record.status, + "since" in record ? record.since : null, + "until" in record ? record.until : null, + "reason" in record ? record.reason : null, + "{}", NOW, + ]); + } + expect(sql.all<{ n: number }>("SELECT COUNT(*) AS n FROM pm_links")[0]?.n).toBe(4); + const historical = sql.all<{ n: number }>( + "SELECT COUNT(*) AS n FROM pm_links WHERE status = 'historical' AND until IS NOT NULL AND reason = 'split'", + )[0]?.n; + expect(historical).toBe(1); + }); + + test("historical without until/reason and removed without reason are rejected by validator and schema", async () => { + const { sql } = await migratedDb(); + const bad = { + sourceKind: "item", sourceRef: "developing-today/code#4403", + target: { repo: "developing-today/code", number: 123 }, + relation: "parent", status: "historical", since: "2026-11-02", + } as const; + expect(validateLinkRecord(bad).length).toBeGreaterThan(0); + expect(() => + insertLink(sql, ["bad-1", "item", bad.sourceRef, "item", "developing-today/code#123", "developing-today/code", 123, "parent", "historical", "2026-11-02", null, null, "{}", NOW]), + ).toThrow(); + expect(() => + insertLink(sql, ["bad-2", "item", bad.sourceRef, "item", "developing-today/code#123", "developing-today/code", 123, "parent", "removed", "2026-11-02", null, null, "{}", NOW]), + ).toThrow(); + }); +}); + +/** The #9060 §12 worked example block, verbatim shape. */ +const METADATA_BLOCK = { + pm_meta: 1, + direct_parent: { repo: "developing-today/code", number: 3447, kind: "epic" }, + links: [ + { + target: { repo: "developing-today/code", number: 123 }, + relation: "parent", + status: "historical", + since: "2026-11-02", + until: "2026-11-12", + reason: "split", + }, + ], + lineage: { design: null, roadmap_item: null, priority: null }, + provenance: { + queue_id: null, session_id: null, lane: null, host: null, worktree: null, + picked_up_at: null, work_started_at: null, created_at: null, model: null, lane_start_issues: [], + }, +}; + +describe("Metadata copies (#9060 §12)", () => { + test("the §12 example block validates, stores byte-faithful, and extracts its direct parent", async () => { + const { sql } = await migratedDb(); + expect(validateMetadataBlock(METADATA_BLOCK)).toEqual([]); + expect(validateMetadataBlock({ ...METADATA_BLOCK, pm_meta: 2 }).length).toBeGreaterThan(0); + sql.run( + `INSERT INTO pm_item_metadata (ref, repo, number, kind, pm_meta, direct_parent_ref, direct_parent_kind, + lineage_design_ref, lineage_roadmap_item_ref, lineage_priority_ref, + provenance_session_id, provenance_lane, provenance_queue_id, provenance_json, metadata_json, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [ + "developing-today/code#4403", "developing-today/code", 4403, "issue", 1, + "developing-today/code#3447", "epic", null, null, null, null, null, null, + JSON.stringify(METADATA_BLOCK.provenance), JSON.stringify(METADATA_BLOCK), NOW, + ], + ); + const row = sql.all<{ direct_parent_ref: string; metadata_json: string }>( + "SELECT direct_parent_ref, metadata_json FROM pm_item_metadata", + )[0]; + expect(row?.direct_parent_ref).toBe("developing-today/code#3447"); + expect(JSON.parse(row?.metadata_json as string)).toEqual(METADATA_BLOCK); + }); +}); + +describe("writer-of-record lease (component A design §5)", () => { + test("one lease row per board; writer and epoch are fenced by the schema", async () => { + const { sql } = await migratedDb(); + insertBoard(sql, LANDED_BOARDS[0] as BoardDef); + const lease = { boardId: "devtoday-main", writer: "laptop", epoch: 1, heartbeatAt: NOW } as const; + expect(validateWriterLease(lease)).toEqual([]); + expect(validateWriterLease({ ...lease, writer: "third-party" }).length).toBeGreaterThan(0); + sql.run( + "INSERT INTO pm_writer_leases (board_id, writer, epoch, heartbeat_at, updated_at) VALUES (?, ?, ?, ?, ?)", + [lease.boardId, lease.writer, lease.epoch, lease.heartbeatAt, NOW], + ); + expect(() => + sql.run( + "INSERT INTO pm_writer_leases (board_id, writer, epoch, heartbeat_at, updated_at) VALUES (?, ?, ?, ?, ?)", + ["devtoday-main", "hosted", 2, NOW, NOW], + ), + ).toThrow(); // second row for the same board: flips update the row and bump the epoch + sql.run("UPDATE pm_writer_leases SET writer = 'hosted', epoch = epoch + 1, heartbeat_at = ? WHERE board_id = ?", [NOW, "devtoday-main"]); + const row = sql.all<{ writer: string; epoch: number }>("SELECT writer, epoch FROM pm_writer_leases")[0]; + expect(row).toEqual({ writer: "hosted", epoch: 2 }); + }); +}); + +describe("milestones + release snapshots (#9060 §4)", () => { + test("program milestones carry no date; release milestones require one; close-out accounting is consistent", async () => { + const { sql } = await migratedDb(); + sql.run( + `INSERT INTO pm_milestones (repo, number, title, kind, due_on, closed_at, state, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + ["developing-today/code", 3, "ID program (ROLLING)", "program", null, null, "open", NOW], + ); + expect(() => + sql.run( + `INSERT INTO pm_milestones (repo, number, title, kind, due_on, closed_at, state, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + ["developing-today/code", 16, "ID platform — release 2026-12-01", "release", null, null, "open", NOW], + ), + ).toThrow(); + sql.run( + `INSERT INTO pm_milestones (repo, number, title, kind, due_on, closed_at, state, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + ["developing-today/code", 16, "ID platform — release 2026-12-01", "release", "2026-12-01", "2026-12-01T18:00:00.000Z", "closed", NOW], + ); + // §4's worked example: "closed with the release covering 123 issues, 23 designs, 4 epics". + 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [ + "developing-today/code", 16, "2026-12-01", + 123, 100, 23, 23, 20, 3, 4, 3, 1, + JSON.stringify(["developing-today/code#2056"]), NOW, "{}", + ], + ); + expect(() => + 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ["developing-today/code", 3, "2026-12-01", 10, 11, 0, 0, 0, 0, 0, 0, 0, "[]", NOW, "{}"], + ), + ).toThrow(); // closed (11) cannot exceed covered (10) + }); +}); + +describe("roadmap rows + reconcile findings", () => { + test("a roadmap row stores its genealogy overlay; findings fence severity", async () => { + const { sql } = await migratedDb(); + insertBoard(sql, LANDED_BOARDS[0] as BoardDef); + sql.run( + `INSERT INTO pm_roadmap_rows (row_id, subject, title, area, status, horizon, source, notes, + links_json, priority_ref, after_refs_json, release_ref, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [ + 28, "grist:doc1/Roadmap/28", "ID platform v1", "ID", "In Progress", "Now", "grist", "", + "[]", "developing-today/code#2056", JSON.stringify(["developing-today/code#3195"]), + "developing-today/code#2056", NOW, + ], + ); + const row = sql.all<{ priority_ref: string; after_refs_json: string }>( + "SELECT priority_ref, after_refs_json FROM pm_roadmap_rows", + )[0]; + expect(row?.priority_ref).toBe("developing-today/code#2056"); + expect(JSON.parse(row?.after_refs_json as string)).toEqual(["developing-today/code#3195"]); + + sql.run( + `INSERT INTO pm_reconcile_findings (finding_id, board_id, kind, severity, subject_ref, summary, detail_json, writer, epoch, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ["f-1", "devtoday-main", "non-record-writer", "error", "developing-today/code#4403", "write arrived from a non-record writer", "{}", "laptop", 2, NOW], + ); + expect(() => + sql.run( + `INSERT INTO pm_reconcile_findings (finding_id, board_id, kind, severity, summary, recorded_at) + VALUES ('f-2', 'devtoday-main', 'drift', 'fatal', 'x', ?)`, + [NOW], + ), + ).toThrow(); + }); +}); diff --git a/pm-stack/pm-service/tsconfig.json b/pm-stack/pm-service/tsconfig.json new file mode 100644 index 0000000000..4f66fb71bf --- /dev/null +++ b/pm-stack/pm-service/tsconfig.json @@ -0,0 +1 @@ +{"compilerOptions":{"allowImportingTsExtensions":true,"lib":["ES2022"],"module":"ESNext","moduleResolution":"bundler","noEmit":true,"skipLibCheck":true,"strict":true,"target":"ES2022","types":["@cloudflare/workers-types"]},"include":["src"]} \ No newline at end of file