Skip to content
Merged
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 @@ -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"],
Expand Down
14 changes: 14 additions & 0 deletions .github/workflows/pm-stack-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
53 changes: 53 additions & 0 deletions pm-stack/pm-service/README.md
Original file line number Diff line number Diff line change
@@ -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
```
18 changes: 18 additions & 0 deletions pm-stack/pm-service/bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pm-stack/pm-service/package.json
Original file line number Diff line number Diff line change
@@ -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"}
35 changes: 35 additions & 0 deletions pm-stack/pm-service/src/bun.d.ts
Original file line number Diff line number Diff line change
@@ -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<T>(fn: () => T): () => T;
}
}

declare const Bun: {
file(path: string): { text(): Promise<string> };
Glob: new (
pattern: string,
) => {
scan(options: { cwd: string }): AsyncIterable<string>;
};
};

/** Bun extends ImportMeta with the module's URL and directory. */
interface ImportMeta {
url: string;
dir: string;
}
30 changes: 30 additions & 0 deletions pm-stack/pm-service/src/tenant-store/load.ts
Original file line number Diff line number Diff line change
@@ -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<Migration[]> {
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<number>();
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<Migration[]> {
return loadMigrations(new URL("./migrations", import.meta.url).pathname);
}
93 changes: 93 additions & 0 deletions pm-stack/pm-service/src/tenant-store/migrate.ts
Original file line number Diff line number Diff line change
@@ -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<T>(sql: string, params?: readonly (string | number | null)[]): T[];
transaction<T>(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<number>();
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<AppliedRow>("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);
}
Loading