Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Migrate pipeline series + issues to PostgreSQL (#1015)

Adam Eivy700783d43696
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1c66be649c..aad619ce48 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -18,6 +18,7 @@
## Changed
- **Universe Builder now stores universes in PostgreSQL** — your universes (canon bibles, categories, composite sheets, locks, influences, and the per-universe render-run history) moved out of the per-record `data/universes/{id}/index.json` files into dedicated `universes` and `universe_runs` tables, one row per universe. Existing installs are migrated automatically and losslessly on first boot — the legacy `data/universes/` directory is renamed aside (`data/universes.imported`) as a one-release recovery source. Nothing changes in how you create, edit, delete, render, or sync universes: the Universe Builder UI and the cross-machine federation wire format are unchanged (no schema-version bump — the sync payload is storage-independent, so a machine on this version syncs universes cleanly with a peer still on the old file storage). This is the first implementation slice (#1014) of the Create relational-schema migration designed in #999. Universes still persist to the per-record file store under the `MEMORY_BACKEND=file` dev/test escape hatch.
+- **Pipeline series & issues now store in PostgreSQL** — your comic/TV series and their issues (the 8-stage production pipeline state: idea, prose, comic script, teleplay, comic pages, storyboards, episode video, audio) moved out of the per-record `data/pipeline-series/{id}/index.json` and `data/pipeline-issues/{id}/index.json` files into dedicated `pipeline_series` and `pipeline_issues` tables, one row per record. The hot relationships are promoted to indexed columns — `pipeline_issues (series_id, number)` directly serves the issue-renumber pass (the most common cross-record pipeline query), and `pipeline_series (universe_id)` serves the universe delete-guard and "series in this universe" lists. Existing installs are migrated automatically and losslessly on first boot. Each issue's full stage map (including its `lastRunId` transcript pointers) stays in the row's `data` payload, and the "Finish the draft" manuscript-review sibling document stays a file alongside the series — only the series/issue records themselves moved. Nothing changes in how you create, edit, delete, renumber, run, or sync the pipeline: the UI and the cross-machine federation wire format are unchanged (no schema-version bump — the sync payload is storage-independent, so a machine on this version syncs the pipeline cleanly with a peer still on the old file storage). This is the second implementation slice (#1015) of the Create relational-schema migration designed in #999, building on the Universes slice (#1014). The pipeline still persists to the per-record file store under the `MEMORY_BACKEND=file` dev/test escape hatch.
- **Create relational schema design (Postgres-first plan, #999)** — a design doc ([`docs/plans/2026-06-07-create-relational-schema-design.md`](../docs/plans/2026-06-07-create-relational-schema-design.md)) now specifies the PostgreSQL data model for the remaining file-backed Create domains: universes, pipeline series/issues, Story Builder sessions, and Writers Room metadata, plus how `catalog_ingredient_refs` will resolve to DB-native targets. It's design-only (no behavior change): one row per record with the record body in a `data` JSONB column and only queryable fields promoted to columns (mirroring the Creative Director #997 and catalog-user-types #1001 swaps), zero hard FKs (so a federated ref can still arrive before its target), Writers Room draft `.md` bodies staying file-backed with only their metadata indexed, and — crucially — no change to the existing snapshot/push federation model, so each store's file→DB move stays invisible to peers with no schema-version bump. Five implementation slices are tracked as #1014–#1018.
- **Catalog user-defined types now live in PostgreSQL** — the user-defined ingredient types you create in Settings → Catalog (the registry that defines what fields a custom catalog type has) moved out of the `data/settings.json` blob into a dedicated `catalog_user_types` table, one row per type, so type definitions version and federate alongside the catalog data they govern instead of riding the unrelated settings file. Existing installs are migrated automatically and losslessly on first boot — the legacy `catalogUserTypes` slice is renamed aside (`catalogUserTypes_imported`) as a one-release recovery source. Nothing changes in how you create, edit, delete, or sync types: the `/api/catalog/types` UI and the cross-machine federation wire format are unchanged (no schema-version bump — the sync payload is storage-independent), so a machine on this version syncs types cleanly with a peer still on the old one. This is the Phase 4 lead-in of the Postgres-first plan (#1001), unblocking typed catalog references. Types still persist to the settings slice under the `MEMORY_BACKEND=file` dev/test escape hatch.
- **Generated images & videos now have a PostgreSQL index** — every generated image and video is mirrored into a new `media_assets` table (one row per asset), so media metadata — prompt, model, dimensions, lineage, timestamps — becomes queryable from the database instead of only by scanning `data/images/*` sidecars and `data/video-history.json`. The bytes and those files stay exactly where they are and remain authoritative; the table is a *derived* index, rebuilt from disk on boot (and pruned of any asset whose file has been removed) and kept current as new media finishes rendering. Nothing about the gallery, history, or generation flows changes for you — this is the foundation (Phase 3.2 of the Postgres-first plan, #1000) that later lets media collections and catalog attachments resolve through one queryable asset index. The index is simply not maintained under the `MEMORY_BACKEND=file` dev/test escape hatch (media still serves from disk).
diff --git a/server/index.js b/server/index.js
index f83526225d..6b43fb6275 100644
--- a/server/index.js
+++ b/server/index.js
@@ -851,6 +851,13 @@ ensureSelf()
// a half-applied import racing a request. listIds() is the cheapest call
// that forces backend selection. Idempotent (marker-gated import).
await universeStore().listIds();
+ // Pipeline series + issues PG warm (#1015): same contract as the universe
+ // warm — touch each store so it selects Postgres and runs its one-time
+ // file→DB import (migrateSeriesToDB / migrateIssuesToDB) BEFORE
+ // httpServer.listen, so the first request/sync sees migrated records.
+ // Series first (issues soft-ref it for universe resolution / lists).
+ await seriesStore().listIds();
+ await issueStore().listIds();
// Authoritative catalog user-type warm (#1001): with the DB confirmed +
// schema ensured, load the registry from the catalog_user_types store
// (running the one-time settings→DB import on first access). This runs
diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.js
index c1c2450357..4dfad31096 100644
--- a/server/lib/db.catalogDdlParity.test.js
+++ b/server/lib/db.catalogDdlParity.test.js
@@ -232,6 +232,35 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {
expect(sqlIdx.size).toBeGreaterThan(0);
});
+ // Pipeline series (#1015) — non-`catalog_`-prefixed table in BOTH DDL
+ // sources, with non-`idx_catalog_`-prefixed indexes, so its own assertion.
+ it('pipeline_series has the same columns and indexes in both files', () => {
+ const sqlBody = extractCreateTable(INIT_SQL, 'pipeline_series');
+ const jsBody = extractCreateTable(DB_JS, 'pipeline_series');
+ expect(sqlBody, 'init-db.sql missing CREATE TABLE pipeline_series').toBeTruthy();
+ expect(jsBody, 'db.js missing CREATE TABLE pipeline_series').toBeTruthy();
+ expect([...new Set(extractColumnNames(sqlBody))].sort())
+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());
+ const sqlIdx = extractIndexNames(INIT_SQL, 'idx_series_');
+ const jsIdx = extractIndexNames(DB_JS, 'idx_series_');
+ expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
+ expect(sqlIdx.size).toBeGreaterThan(0);
+ });
+
+ // Pipeline issues (#1015) — same drift risk; its own table + indexes.
+ it('pipeline_issues has the same columns and indexes in both files', () => {
+ const sqlBody = extractCreateTable(INIT_SQL, 'pipeline_issues');
+ const jsBody = extractCreateTable(DB_JS, 'pipeline_issues');
+ expect(sqlBody, 'init-db.sql missing CREATE TABLE pipeline_issues').toBeTruthy();
+ expect(jsBody, 'db.js missing CREATE TABLE pipeline_issues').toBeTruthy();
+ expect([...new Set(extractColumnNames(sqlBody))].sort())
+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());
+ const sqlIdx = extractIndexNames(INIT_SQL, 'idx_issues_');
+ const jsIdx = extractIndexNames(DB_JS, 'idx_issues_');
+ expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
+ expect(sqlIdx.size).toBeGreaterThan(0);
+ });
+
it('search_tsv payload field set matches', () => {
// Both files re-declare the GENERATED ALWAYS expression character-for-
// character today. If one side adds a payload key (e.g. voiceNotes) and
diff --git a/server/lib/db.js b/server/lib/db.js
index 0e771321cc..3053811c34 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -633,6 +633,62 @@ async function ensureSchemaImpl() {
created_at TIMESTAMPTZ DEFAULT NOW()
)`,
`CREATE INDEX IF NOT EXISTS idx_universe_runs_universe ON universe_runs (universe_id, created_at DESC)`,
+
+ // Pipeline series (Phase 3 Create migration, issue #1015). One row per
+ // series, the full sanitized record (arc/seasons/locks/covers/style) in
+ // `data` JSONB, moved out of data/pipeline-series/{id}/index.json
+ // (collectionStore). Only the fields the service/federation query, join, or
+ // sort on are mirrored into columns: `name` (rename-cascade + list sort),
+ // `universe_id` (the hot relationship — the delete-guard "reject universe
+ // delete when live series link it" + "series in this universe" lists; soft
+ // ref, no FK — a series can sync before its universe arrives), and the
+ // promote back-link `writers_room_work_id`. `ephemeral` + the LWW/tombstone
+ // trio (updated_at/deleted/deleted_at) populated FROM the record body
+ // (mirrorTimestamp), not a DB trigger. NO sync_sequence: pipeline records
+ // federate via the EXISTING dataSync snapshot/push model — the storage swap
+ // is invisible to peers (no schema-version bump). Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS pipeline_series (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ universe_id TEXT,
+ writers_room_work_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ ephemeral BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_series_universe ON pipeline_series (universe_id) WHERE deleted = FALSE`,
+ `CREATE INDEX IF NOT EXISTS idx_series_wr_work ON pipeline_series (writers_room_work_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_series_updated ON pipeline_series (updated_at)`,
+
+ // Pipeline issues (issue #1015). One row per issue; the 8-stage `stages`
+ // map (text/visual/audio, runHistory, canonExtraction, covers) + lastRunId
+ // pointers stay entirely in `data` JSONB (document-shaped, sanitizer-owned).
+ // `series_id` (parent, soft ref), `season_id` (arc grouping), and `number`
+ // (renumber-recomputed ordinal) are promoted — the renumber pass reads all
+ // issues of a series ordered by number, the single most common cross-record
+ // pipeline query, served directly by idx_issues_series (series_id, number).
+ // `status` promoted for "issues needing review" dashboards. `ephemeral` +
+ // LWW/tombstone trio mirror the body. NO sync_sequence (see pipeline_series).
+ // Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS pipeline_issues (
+ id TEXT PRIMARY KEY,
+ series_id TEXT NOT NULL,
+ season_id TEXT,
+ number INTEGER,
+ status VARCHAR(32),
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ ephemeral BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_issues_series ON pipeline_issues (series_id, number) WHERE deleted = FALSE`,
+ `CREATE INDEX IF NOT EXISTS idx_issues_season ON pipeline_issues (season_id) WHERE season_id IS NOT NULL`,
+ `CREATE INDEX IF NOT EXISTS idx_issues_updated ON pipeline_issues (updated_at)`,
];
for (const sql of catalogDDL) {
await pool.query(sql);
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 2ec141fd5c..c666bd713a 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -680,3 +680,58 @@ CREATE TABLE IF NOT EXISTS universe_runs (
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_universe_runs_universe ON universe_runs (universe_id, created_at DESC);
+
+-- Pipeline series (Phase 3 Create migration, issue #1015). One row per series,
+-- the full sanitized record (arc/seasons/locks/covers/style) in `data` JSONB,
+-- moved out of data/pipeline-series/{id}/index.json (collectionStore). Only the
+-- fields the service/federation query, join, or sort on are mirrored into
+-- columns: `name` (rename-cascade + list sort), `universe_id` (the hot
+-- relationship — delete-guard + "series in this universe" lists; soft ref, no
+-- FK — a series can sync before its universe arrives), and the promote
+-- back-link `writers_room_work_id`. `ephemeral` + the LWW/tombstone trio
+-- (updated_at/deleted/deleted_at) populated FROM the record body, not a DB
+-- trigger. NO sync_sequence: pipeline records federate via the EXISTING
+-- dataSync snapshot/push model — the storage swap is invisible to peers (no
+-- schema-version bump). Mirrors the pipeline_series block in db.js ensureSchema().
+CREATE TABLE IF NOT EXISTS pipeline_series (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ universe_id TEXT,
+ writers_room_work_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ ephemeral BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+);
+CREATE INDEX IF NOT EXISTS idx_series_universe ON pipeline_series (universe_id) WHERE deleted = FALSE;
+CREATE INDEX IF NOT EXISTS idx_series_wr_work ON pipeline_series (writers_room_work_id);
+CREATE INDEX IF NOT EXISTS idx_series_updated ON pipeline_series (updated_at);
+
+-- Pipeline issues (issue #1015). One row per issue; the 8-stage `stages` map
+-- (text/visual/audio, runHistory, canonExtraction, covers) + lastRunId pointers
+-- stay entirely in `data` JSONB (document-shaped, sanitizer-owned). `series_id`
+-- (parent, soft ref), `season_id` (arc grouping), and `number`
+-- (renumber-recomputed ordinal) are promoted — the renumber pass reads all
+-- issues of a series ordered by number, the single most common cross-record
+-- pipeline query, served directly by idx_issues_series (series_id, number).
+-- `status` promoted for "issues needing review" dashboards. `ephemeral` +
+-- LWW/tombstone trio mirror the body. NO sync_sequence (see pipeline_series).
+-- Mirrors the pipeline_issues block in db.js ensureSchema().
+CREATE TABLE IF NOT EXISTS pipeline_issues (
+ id TEXT PRIMARY KEY,
+ series_id TEXT NOT NULL,
+ season_id TEXT,
+ number INTEGER,
+ status VARCHAR(32),
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ ephemeral BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+);
+CREATE INDEX IF NOT EXISTS idx_issues_series ON pipeline_issues (series_id, number) WHERE deleted = FALSE;
+CREATE INDEX IF NOT EXISTS idx_issues_season ON pipeline_issues (season_id) WHERE season_id IS NOT NULL;
+CREATE INDEX IF NOT EXISTS idx_issues_updated ON pipeline_issues (updated_at);
diff --git a/server/scripts/migrateIssuesToDB.js b/server/scripts/migrateIssuesToDB.js
new file mode 100644
index 0000000000..3f11492555
--- /dev/null
+++ b/server/scripts/migrateIssuesToDB.js
@@ -0,0 +1,98 @@
+/**
+ * One-time importer: data/pipeline-issues/{id}/index.json (collectionStore) →
+ * PostgreSQL (`pipeline_issues`), for Phase 3 Create / issue #1015.
+ *
+ * Issues used to live one-record-per-dir. As of #1015 they live one-row-per-
+ * issue in Postgres. On the first PG-backed access (from
+ * services/pipeline/issuesStore/store.js, BEFORE the boot warm reads any issue),
+ * this importer copies each legacy record into `pipeline_issues`. Issue dirs
+ * hold ONLY index.json (no file-primary siblings), so — like the universe
+ * importer — the whole legacy dir is renamed aside after all rows land.
+ *
+ * Idempotency / safety (mirrors migrateUniversesToDB):
+ * - Marker-gated in data/pipeline-issues.migrated.json so the walk runs once.
+ * - INSERT … ON CONFLICT (id) DO NOTHING — never clobbers an existing row.
+ * - LOSSLESS: each record copied verbatim into `data`.
+ * - The legacy dir is RENAMED to data/pipeline-issues.imported (not deleted)
+ * so it remains a recovery source for ≥1 release. Renamed ONLY after all
+ * rows land AND only then is the marker written — a crash mid-import leaves
+ * the dir → next boot retries (ON CONFLICT DO NOTHING makes the retry safe).
+ */
+
+import { readFile, writeFile, rename, readdir, stat } from 'fs/promises';
+import { join } from 'path';
+import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { query } from '../lib/db.js';
+import { mirrorTimestamp } from '../lib/pgTimestamp.js';
+
+const LEGACY_DIRNAME = 'pipeline-issues';
+const IMPORTED_DIRNAME = 'pipeline-issues.imported';
+const MARKER_FILENAME = 'pipeline-issues.migrated.json';
+const RECORD_RE = /^iss-[A-Za-z0-9-]+$/;
+
+async function markerExists() {
+ const raw = await readFile(join(PATHS.data, MARKER_FILENAME), 'utf-8').catch(() => null);
+ return raw != null;
+}
+
+async function writeMarker(payload) {
+ await writeFile(join(PATHS.data, MARKER_FILENAME), JSON.stringify(payload, null, 2) + '\n', 'utf-8');
+}
+
+async function importRecord(record) {
+ if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !record.id) return false;
+ if (typeof record.seriesId !== 'string' || !record.seriesId) return false;
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(record.createdAt, now);
+ const result = await query(
+ `INSERT INTO pipeline_issues (id, series_id, season_id, number, status, data, ephemeral, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8, $9, $10, $11)
+ ON CONFLICT (id) DO NOTHING`,
+ [
+ record.id,
+ record.seriesId,
+ typeof record.seasonId === 'string' && record.seasonId ? record.seasonId : null,
+ Number.isFinite(record.number) ? Math.floor(record.number) : null,
+ typeof record.status === 'string' && record.status ? record.status.slice(0, 32) : null,
+ JSON.stringify(record),
+ record.ephemeral === true,
+ createdAt,
+ mirrorTimestamp(record.updatedAt, createdAt),
+ record.deleted === true,
+ mirrorTimestamp(record.deletedAt, null),
+ ],
+ );
+ return result.rowCount > 0;
+}
+
+export async function migrateIssuesToDB() {
+ if (await markerExists()) return { ok: true, reason: 'already-applied', imported: 0 };
+
+ const legacyDir = join(PATHS.data, LEGACY_DIRNAME);
+ const dirStat = await stat(legacyDir).catch(() => null);
+
+ if (!dirStat || !dirStat.isDirectory()) {
+ return { ok: true, reason: 'fresh-install', imported: 0 };
+ }
+
+ const entries = await readdir(legacyDir).catch(() => []);
+ let imported = 0;
+ let skipped = 0;
+ for (const name of entries) {
+ if (!RECORD_RE.test(name)) continue;
+ const record = await readJSONFile(join(legacyDir, name, 'index.json'), null, { allowArray: false, logError: false });
+ if (!record) { skipped += 1; continue; }
+ if (await importRecord(record)) imported += 1;
+ else skipped += 1;
+ }
+
+ try {
+ await rename(legacyDir, join(PATHS.data, IMPORTED_DIRNAME));
+ } catch (err) {
+ console.warn(`⚠️ pipeline-issues→DB import: imported ${imported} issue(s) but renaming ${LEGACY_DIRNAME} aside failed (${err.message}) — leaving dir, will retry marker next boot`);
+ return { ok: true, reason: 'imported-rename-failed', imported, skipped };
+ }
+ await writeMarker({ migratedAt: new Date().toISOString(), imported, skipped, reason: 'imported' });
+ console.log(`📚 pipeline-issues→DB import: imported ${imported} issue(s) (${skipped} skipped); data/${LEGACY_DIRNAME} renamed to ${IMPORTED_DIRNAME}`);
+ return { ok: true, reason: 'imported', imported, skipped };
+}
diff --git a/server/scripts/migrateIssuesToDB.test.js b/server/scripts/migrateIssuesToDB.test.js
new file mode 100644
index 0000000000..4fea3dcbf3
--- /dev/null
+++ b/server/scripts/migrateIssuesToDB.test.js
@@ -0,0 +1,118 @@
+/**
+ * Tests for the legacy data/pipeline-issues/{id}/index.json → Postgres importer
+ * (#1015). Issue dirs hold only index.json (no siblings), so the whole legacy
+ * dir is renamed aside after rows land — like the universe importer. Disk + PG
+ * are mocked.
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+let files = {};
+let dirEntries = null;
+let recordsByDir = {};
+let renameShouldFail = false;
+let renamed = [];
+
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { data: '/fake/data' },
+ readJSONFile: vi.fn(async (path) => recordsByDir[path] ?? null),
+}));
+
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn(async (path) => {
+ if (!(path in files)) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
+ return files[path];
+ }),
+ writeFile: vi.fn(async (path, content) => { files[path] = content; }),
+ rename: vi.fn(async (from, to) => {
+ if (renameShouldFail) throw new Error('EACCES');
+ renamed.push([from, to]);
+ }),
+ readdir: vi.fn(async () => (dirEntries === null ? [] : dirEntries)),
+ stat: vi.fn(async (path) => {
+ if (path === '/fake/data/pipeline-issues') {
+ if (dirEntries === null) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
+ return { isDirectory: () => true };
+ }
+ const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e;
+ }),
+}));
+
+let table;
+const query = vi.fn(async (sql, params) => {
+ if (/INSERT INTO pipeline_issues/.test(sql)) {
+ const id = params[0];
+ if (table.has(id)) return { rowCount: 0, rows: [] };
+ table.set(id, { id, seriesId: params[1], number: params[3], data: JSON.parse(params[5]) });
+ return { rowCount: 1, rows: [] };
+ }
+ return { rowCount: 0, rows: [] };
+});
+vi.mock('../lib/db.js', () => ({ query: (...a) => query(...a) }));
+
+const MARKER = '/fake/data/pipeline-issues.migrated.json';
+const rec = (id, extra = {}) => ({ id, seriesId: 'ser-1', number: 1, title: id, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-02T00:00:00.000Z', ...extra });
+
+async function importer() {
+ const { migrateIssuesToDB } = await import('./migrateIssuesToDB.js');
+ return migrateIssuesToDB();
+}
+
+beforeEach(() => {
+ files = {};
+ dirEntries = null;
+ recordsByDir = {};
+ renameShouldFail = false;
+ renamed = [];
+ table = new Map();
+ query.mockClear();
+});
+
+describe('migrateIssuesToDB', () => {
+ it('fresh install (no legacy dir): no-op WITHOUT a marker', async () => {
+ const result = await importer();
+ expect(result).toMatchObject({ ok: true, reason: 'fresh-install', imported: 0 });
+ expect(MARKER in files).toBe(false);
+ });
+
+ it('marker already present: no-op', async () => {
+ files[MARKER] = JSON.stringify({ reason: 'imported' });
+ dirEntries = ['iss-1'];
+ recordsByDir['/fake/data/pipeline-issues/iss-1/index.json'] = rec('iss-1');
+ const result = await importer();
+ expect(result).toMatchObject({ reason: 'already-applied' });
+ expect(table.size).toBe(0);
+ });
+
+ it('imports records verbatim, renames the dir aside, stamps marker', async () => {
+ dirEntries = ['iss-1', 'iss-2', 'index.json', '.DS_Store'];
+ recordsByDir['/fake/data/pipeline-issues/iss-1/index.json'] = rec('iss-1', { number: 2, stages: { idea: { output: 'x' } } });
+ recordsByDir['/fake/data/pipeline-issues/iss-2/index.json'] = rec('iss-2');
+ const result = await importer();
+ expect(result).toMatchObject({ ok: true, reason: 'imported', imported: 2 });
+ expect(table.get('iss-1').data.stages.idea.output).toBe('x'); // verbatim
+ expect(table.get('iss-1').number).toBe(2); // mirror column
+ expect(renamed).toEqual([['/fake/data/pipeline-issues', '/fake/data/pipeline-issues.imported']]);
+ expect(MARKER in files).toBe(true);
+ });
+
+ it('skips a record missing seriesId', async () => {
+ dirEntries = ['iss-1', 'iss-bad'];
+ recordsByDir['/fake/data/pipeline-issues/iss-1/index.json'] = rec('iss-1');
+ recordsByDir['/fake/data/pipeline-issues/iss-bad/index.json'] = { id: 'iss-bad', title: 'orphan' };
+ const result = await importer();
+ expect(result.imported).toBe(1);
+ expect(table.has('iss-1')).toBe(true);
+ expect(table.has('iss-bad')).toBe(false);
+ });
+
+ it('rename failure leaves the marker UNwritten so next boot retries', async () => {
+ dirEntries = ['iss-1'];
+ recordsByDir['/fake/data/pipeline-issues/iss-1/index.json'] = rec('iss-1');
+ renameShouldFail = true;
+ const result = await importer();
+ expect(result).toMatchObject({ ok: true, reason: 'imported-rename-failed', imported: 1 });
+ expect(MARKER in files).toBe(false);
+ expect(table.has('iss-1')).toBe(true);
+ });
+});
diff --git a/server/scripts/migrateSeriesToDB.js b/server/scripts/migrateSeriesToDB.js
new file mode 100644
index 0000000000..f96620e9bf
--- /dev/null
+++ b/server/scripts/migrateSeriesToDB.js
@@ -0,0 +1,112 @@
+/**
+ * One-time importer: data/pipeline-series/{id}/index.json (collectionStore) →
+ * PostgreSQL (`pipeline_series`), for Phase 3 Create / issue #1015.
+ *
+ * Series used to live one-record-per-dir. As of #1015 the series RECORD lives
+ * one-row-per-series in Postgres. On the first PG-backed access (from
+ * services/pipeline/seriesStore/store.js, BEFORE the boot warm reads any
+ * series), this importer copies each legacy `index.json` into `pipeline_series`.
+ *
+ * The series dir ALSO holds a `manuscript-review.json` sibling doc that is
+ * `file-primary` (manuscriptReview.js reads/writes it at
+ * data/pipeline-series/{id}/manuscript-review.json). So — UNLIKE the universe
+ * importer, which renames the whole legacy dir aside — this importer must NOT
+ * move the dirs: it would orphan the review siblings the live code still reads
+ * from that path. Instead it renames each migrated record's `index.json` to
+ * `index.json.imported` IN PLACE, leaving the dir + its review sibling intact,
+ * and stamps a type-level marker.
+ *
+ * Idempotency / safety (mirrors migrateUniversesToDB):
+ * - Marker-gated in data/pipeline-series.migrated.json so the walk runs once.
+ * - INSERT … ON CONFLICT (id) DO NOTHING — a row already in the table is never
+ * clobbered. The DB row is authoritative once it exists.
+ * - LOSSLESS: each record copied verbatim into `data` (the live store's
+ * sanitizer runs on read).
+ * - Each `index.json` is RENAMED to `index.json.imported` (not deleted) so it
+ * remains a recovery source for ≥1 release and a re-run can't re-import
+ * stale rows over fresher DB state. Renamed ONLY after the row lands.
+ * - Marker stamped only after the full walk; a crash mid-import leaves some
+ * index.json in place → next boot retries (ON CONFLICT DO NOTHING makes the
+ * retry safe; an already-renamed record is simply skipped on re-read).
+ */
+
+import { readFile, writeFile, rename, readdir, stat } from 'fs/promises';
+import { join } from 'path';
+import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { query } from '../lib/db.js';
+import { mirrorTimestamp } from '../lib/pgTimestamp.js';
+
+const LEGACY_DIRNAME = 'pipeline-series';
+const MARKER_FILENAME = 'pipeline-series.migrated.json';
+const RECORD_RE = /^ser-[A-Za-z0-9-]+$/;
+
+async function markerExists() {
+ const raw = await readFile(join(PATHS.data, MARKER_FILENAME), 'utf-8').catch(() => null);
+ return raw != null;
+}
+
+async function writeMarker(payload) {
+ await writeFile(join(PATHS.data, MARKER_FILENAME), JSON.stringify(payload, null, 2) + '\n', 'utf-8');
+}
+
+// One legacy series record → `pipeline_series` row. Verbatim into `data`; the
+// typed mirror columns are bind-sanitized so a hand-edited/legacy value can't
+// make the INSERT throw and abort the whole import.
+async function importRecord(record) {
+ if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !record.id) return false;
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(record.createdAt, now);
+ const result = await query(
+ `INSERT INTO pipeline_series (id, name, universe_id, writers_room_work_id, data, ephemeral, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10)
+ ON CONFLICT (id) DO NOTHING`,
+ [
+ record.id,
+ typeof record.name === 'string' ? record.name : '',
+ typeof record.universeId === 'string' && record.universeId ? record.universeId : null,
+ typeof record.writersRoomWorkId === 'string' && record.writersRoomWorkId ? record.writersRoomWorkId : null,
+ JSON.stringify(record),
+ record.ephemeral === true,
+ createdAt,
+ mirrorTimestamp(record.updatedAt, createdAt),
+ record.deleted === true,
+ mirrorTimestamp(record.deletedAt, null),
+ ],
+ );
+ return result.rowCount > 0;
+}
+
+export async function migrateSeriesToDB() {
+ if (await markerExists()) return { ok: true, reason: 'already-applied', imported: 0 };
+
+ const legacyDir = join(PATHS.data, LEGACY_DIRNAME);
+ const dirStat = await stat(legacyDir).catch(() => null);
+
+ // Fresh install (no legacy dir): no-op WITHOUT stamping the marker (keeps the
+ // recovery escape hatch open — see migrateUniversesToDB).
+ if (!dirStat || !dirStat.isDirectory()) {
+ return { ok: true, reason: 'fresh-install', imported: 0 };
+ }
+
+ const entries = await readdir(legacyDir).catch(() => []);
+ let imported = 0;
+ let skipped = 0;
+ for (const name of entries) {
+ if (!RECORD_RE.test(name)) continue; // skip index.json, hidden, non-record dirs
+ const recordPath = join(legacyDir, name, 'index.json');
+ const record = await readJSONFile(recordPath, null, { allowArray: false, logError: false });
+ // Already-renamed (index.json absent) on a retried run, or unreadable.
+ if (!record) { skipped += 1; continue; }
+ if (await importRecord(record)) imported += 1;
+ else skipped += 1;
+ // Rename the record's index.json aside IN PLACE — leaves the dir + its
+ // manuscript-review.json sibling untouched, so the file-primary review doc
+ // stays readable at its canonical path. Best-effort: a rename failure leaves
+ // the index.json (next boot retries; ON CONFLICT DO NOTHING is safe).
+ await rename(recordPath, `${recordPath}.imported`).catch(() => {});
+ }
+
+ await writeMarker({ migratedAt: new Date().toISOString(), imported, skipped, reason: 'imported' });
+ console.log(`🎬 pipeline-series→DB import: imported ${imported} series (${skipped} skipped); index.json renamed aside in place (review siblings kept)`);
+ return { ok: true, reason: 'imported', imported, skipped };
+}
diff --git a/server/scripts/migrateSeriesToDB.test.js b/server/scripts/migrateSeriesToDB.test.js
new file mode 100644
index 0000000000..97ad7bbd54
--- /dev/null
+++ b/server/scripts/migrateSeriesToDB.test.js
@@ -0,0 +1,117 @@
+/**
+ * Tests for the legacy data/pipeline-series/{id}/index.json → Postgres importer
+ * (#1015). Unlike the universe importer, this renames each record's index.json
+ * aside IN PLACE (not the whole dir) so the file-primary manuscript-review.json
+ * siblings stay readable at their canonical path. Disk + PG are mocked.
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+let files = {}; // path → string (markers)
+let dirEntries = null; // readdir(legacyDir) result, or null = ENOENT
+let recordsByDir = {}; // `${legacyDir}/${id}/index.json` → record object
+let renamed = [];
+
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { data: '/fake/data' },
+ readJSONFile: vi.fn(async (path) => recordsByDir[path] ?? null),
+}));
+
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn(async (path) => {
+ if (!(path in files)) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
+ return files[path];
+ }),
+ writeFile: vi.fn(async (path, content) => { files[path] = content; }),
+ rename: vi.fn(async (from, to) => { renamed.push([from, to]); }),
+ readdir: vi.fn(async () => (dirEntries === null ? [] : dirEntries)),
+ stat: vi.fn(async (path) => {
+ if (path === '/fake/data/pipeline-series') {
+ if (dirEntries === null) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
+ return { isDirectory: () => true };
+ }
+ const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e;
+ }),
+}));
+
+let table;
+const query = vi.fn(async (sql, params) => {
+ if (/INSERT INTO pipeline_series/.test(sql)) {
+ const id = params[0];
+ if (table.has(id)) return { rowCount: 0, rows: [] };
+ table.set(id, { id, name: params[1], universeId: params[2], data: JSON.parse(params[4]) });
+ return { rowCount: 1, rows: [] };
+ }
+ return { rowCount: 0, rows: [] };
+});
+vi.mock('../lib/db.js', () => ({ query: (...a) => query(...a) }));
+
+const MARKER = '/fake/data/pipeline-series.migrated.json';
+const rec = (id, extra = {}) => ({ id, name: id, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-02T00:00:00.000Z', ...extra });
+
+async function importer() {
+ const { migrateSeriesToDB } = await import('./migrateSeriesToDB.js');
+ return migrateSeriesToDB();
+}
+
+beforeEach(() => {
+ files = {};
+ dirEntries = null;
+ recordsByDir = {};
+ renamed = [];
+ table = new Map();
+ query.mockClear();
+});
+
+describe('migrateSeriesToDB', () => {
+ it('fresh install (no legacy dir): no-op WITHOUT a marker', async () => {
+ const result = await importer();
+ expect(result).toMatchObject({ ok: true, reason: 'fresh-install', imported: 0 });
+ expect(MARKER in files).toBe(false);
+ expect(table.size).toBe(0);
+ });
+
+ it('marker already present: no-op (does not re-walk)', async () => {
+ files[MARKER] = JSON.stringify({ reason: 'imported' });
+ dirEntries = ['ser-1'];
+ recordsByDir['/fake/data/pipeline-series/ser-1/index.json'] = rec('ser-1');
+ const result = await importer();
+ expect(result).toMatchObject({ reason: 'already-applied' });
+ expect(table.size).toBe(0);
+ });
+
+ it('imports records verbatim, renames each index.json aside IN PLACE, stamps marker', async () => {
+ dirEntries = ['ser-1', 'ser-2', 'index.json', '.DS_Store'];
+ recordsByDir['/fake/data/pipeline-series/ser-1/index.json'] = rec('ser-1', { universeId: 'u-1', logline: 'a' });
+ recordsByDir['/fake/data/pipeline-series/ser-2/index.json'] = rec('ser-2');
+ const result = await importer();
+ expect(result).toMatchObject({ ok: true, reason: 'imported', imported: 2 });
+ expect(table.get('ser-1').data.logline).toBe('a'); // verbatim
+ expect(table.get('ser-1').universeId).toBe('u-1'); // mirror column
+ // Per-record index.json renamed aside — dir itself NOT renamed (siblings stay).
+ expect(renamed).toContainEqual(['/fake/data/pipeline-series/ser-1/index.json', '/fake/data/pipeline-series/ser-1/index.json.imported']);
+ expect(renamed).toContainEqual(['/fake/data/pipeline-series/ser-2/index.json', '/fake/data/pipeline-series/ser-2/index.json.imported']);
+ // The whole-dir rename the universe importer does must NOT happen here.
+ expect(renamed.some(([from]) => from === '/fake/data/pipeline-series')).toBe(false);
+ expect(MARKER in files).toBe(true);
+ });
+
+ it('is idempotent: a re-run over the same rows imports 0 (ON CONFLICT DO NOTHING)', async () => {
+ dirEntries = ['ser-1'];
+ recordsByDir['/fake/data/pipeline-series/ser-1/index.json'] = rec('ser-1');
+ table.set('ser-1', { id: 'ser-1' });
+ const result = await importer();
+ expect(result.imported).toBe(0);
+ expect(MARKER in files).toBe(true);
+ });
+
+ it('skips non-record entries and unreadable records', async () => {
+ dirEntries = ['ser-1', 'ser-bad', 'index.json'];
+ recordsByDir['/fake/data/pipeline-series/ser-1/index.json'] = rec('ser-1');
+ recordsByDir['/fake/data/pipeline-series/ser-bad/index.json'] = null;
+ const result = await importer();
+ expect(result.imported).toBe(1);
+ expect(table.has('ser-1')).toBe(true);
+ expect(table.has('ser-bad')).toBe(false);
+ });
+});
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index 1c8765ec2d..19e2714d9c 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -21,6 +21,7 @@ import {
} from '../lib/schemaVersions.js';
import { mergeUniversesFromSync, listUniverses } from './universeBuilder.js';
import { getUniverseMutationEpoch } from './universeBuilder/store.js';
+import { getPipelineMutationEpoch } from './pipeline/syncEpoch.js';
import { mergeSeriesFromSync, listSeries } from './pipeline/series.js';
import { mergeIssuesFromSync, listIssues } from './pipeline/issues.js';
import { mergeMediaCollectionsFromSync, listCollections, itemKey } from './mediaCollections.js';
@@ -36,8 +37,22 @@ const CHRONOTYPE_FILE = join(PATHS.digitalTwin, 'chronotype.json');
const LONGEVITY_FILE = join(PATHS.digitalTwin, 'longevity.json');
const FEEDBACK_FILE = join(PATHS.digitalTwin, 'feedback.json');
const MEATSPACE_DIR = PATHS.meatspace;
+// Pipeline series + issues used to live under data/pipeline-series/<id> and
+// data/pipeline-issues/<id>; #1015 moved the RECORDS into PostgreSQL
+// (`pipeline_series` / `pipeline_issues`). Same federation-invisibility problem
+// as universes (#1014): a PG-backed pipeline edit no longer touches these
+// directories, so the dir fingerprint alone would go stale and peers would stop
+// receiving pipeline edits. The pipeline store exports a monotonic mutation
+// epoch (bumped on every series/issue record write/delete) folded into this
+// path's fingerprint via PIPELINE_EPOCH_KEY below. The series dir is still
+// stat'd because its `manuscript-review.json` siblings remain file-primary —
+// a review-only edit must still invalidate the pipeline checksum.
const PIPELINE_SERIES_DIR = join(PATHS.data, 'pipeline-series');
const PIPELINE_ISSUES_DIR = join(PATHS.data, 'pipeline-issues');
+// Sentinel fingerprint-map key (not a real path — readFingerprintMap special-
+// cases it) carrying the pipeline mutation epoch into the pipeline +
+// mediaCollections checksum caches.
+const PIPELINE_EPOCH_KEY = '__pipelineEpoch';
// Universes used to live in a single `universe-builder.json`; migration 034
// split them into `data/universes/<id>/index.json`, and #1014 moved them again
// into PostgreSQL (`universes` + `universe_runs`). Sync reads them through the
@@ -749,13 +764,17 @@ const CHECKSUM_PATHS = {
// the cache — see UNIVERSE_BUILDER_DIR's note. PEER_SUBSCRIPTIONS_FILE so a
// subscribe/unsubscribe re-checksums the per-peer scoped snapshot.
universe: [UNIVERSE_BUILDER_DIR, UNIVERSE_EPOCH_KEY, PEER_SUBSCRIPTIONS_FILE],
- pipeline: [PIPELINE_SERIES_DIR, PIPELINE_ISSUES_DIR, PEER_SUBSCRIPTIONS_FILE],
+ // PIPELINE_EPOCH_KEY folds in the pipeline store's mutation epoch so a
+ // PG-backed series/issue edit (which doesn't touch these dirs) still
+ // invalidates the cache — see PIPELINE_SERIES_DIR's note. The series dir is
+ // still stat'd for the file-primary manuscript-review.json siblings.
+ pipeline: [PIPELINE_SERIES_DIR, PIPELINE_ISSUES_DIR, PIPELINE_EPOCH_KEY, PEER_SUBSCRIPTIONS_FILE],
// mediaCollections invalidates on its own record dir AND on the parent
// record files — `getMediaCollectionsSnapshot` filters collections whose
// linked universe/series is ephemeral, so a "mark ephemeral" PATCH on a
// universe must re-checksum the collections snapshot even though no
// media-collections record file moved. Same goes for un-ephemeral.
- mediaCollections: [MEDIA_COLLECTIONS_DIR, UNIVERSE_BUILDER_DIR, UNIVERSE_EPOCH_KEY, PIPELINE_SERIES_DIR, PEER_SUBSCRIPTIONS_FILE],
+ mediaCollections: [MEDIA_COLLECTIONS_DIR, UNIVERSE_BUILDER_DIR, UNIVERSE_EPOCH_KEY, PIPELINE_SERIES_DIR, PIPELINE_EPOCH_KEY, PEER_SUBSCRIPTIONS_FILE],
// videoHistory is a flat history file with no parent-record dependency —
// its checksum invalidates only when video-history.json itself moves.
videoHistory: [VIDEO_HISTORY_FILE],
@@ -878,6 +897,7 @@ async function readFingerprintMap(paths) {
// a file stat, so a PG-backed universe edit invalidates the cache even
// though no file moved. fingerprintsEqual compares these like any value.
if (p === UNIVERSE_EPOCH_KEY) { out[p] = `epoch:${getUniverseMutationEpoch()}`; return; }
+ if (p === PIPELINE_EPOCH_KEY) { out[p] = `epoch:${getPipelineMutationEpoch()}`; return; }
const s = await stat(p).catch(() => null);
if (!s) { out[p] = null; return; }
if (s.isDirectory()) {
diff --git a/server/services/dataSync.pipelineEpoch.test.js b/server/services/dataSync.pipelineEpoch.test.js
new file mode 100644
index 0000000000..21e2321acc
--- /dev/null
+++ b/server/services/dataSync.pipelineEpoch.test.js
@@ -0,0 +1,86 @@
+/**
+ * dataSync pipeline mutation-epoch fingerprint (#1015).
+ *
+ * When pipeline series + issues move to PostgreSQL, a pipeline edit no longer
+ * touches data/pipeline-series/ or data/pipeline-issues/, so the directory
+ * file-fingerprint that gates dataSync's pipeline snapshot cache goes stale —
+ * peers would silently stop receiving pipeline edits. The fix folds the pipeline
+ * store's monotonic mutation epoch into the pipeline checksum fingerprint.
+ *
+ * This test isolates that mechanism: listSeries/listIssues are mocked so the
+ * snapshot CONTENT can change with NO file change, and getPipelineMutationEpoch
+ * is mocked so we control the epoch. It proves (a) a content change WITHOUT an
+ * epoch bump is masked by the cache, and (b) bumping the epoch invalidates the
+ * cache and surfaces the new content.
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
+
+const { makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-datasync-pipeline-epoch-' });
+
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return makeProxy(actual);
+});
+
+let seriesContent = [];
+let issuesContent = [];
+let epoch = 0;
+
+vi.mock('./pipeline/series.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ listSeries: vi.fn(async () => seriesContent),
+ mergeSeriesFromSync: vi.fn(async () => ({ applied: false, count: 0 })),
+ };
+});
+vi.mock('./pipeline/issues.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ listIssues: vi.fn(async () => issuesContent),
+ mergeIssuesFromSync: vi.fn(async () => ({ applied: false, count: 0 })),
+ };
+});
+vi.mock('./pipeline/syncEpoch.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, getPipelineMutationEpoch: vi.fn(() => epoch) };
+});
+
+const dataSync = await import('./dataSync.js');
+
+afterAll(cleanup);
+
+beforeEach(() => {
+ seriesContent = [{ id: 'ser-1', name: 'A', createdAt: '2026-05-17T09:00:00Z', updatedAt: '2026-05-17T10:00:00Z' }];
+ issuesContent = [];
+ epoch = 0;
+});
+
+describe('dataSync — pipeline mutation-epoch fingerprint', () => {
+ it('a content change WITHOUT an epoch bump or file change is masked by the cache', async () => {
+ const before = await dataSync.getChecksum('pipeline');
+ seriesContent = [{ id: 'ser-1', name: 'CHANGED', updatedAt: '2026-05-17T11:00:00Z' }];
+ const after = await dataSync.getChecksum('pipeline');
+ expect(after.checksum).toBe(before.checksum); // masked — fingerprint identical
+ });
+
+ it('bumping the epoch invalidates the cache and surfaces the new content', async () => {
+ const before = await dataSync.getChecksum('pipeline');
+ seriesContent = [{ id: 'ser-1', name: 'CHANGED', updatedAt: '2026-05-17T11:00:00Z' }];
+ epoch += 1; // the store bumps this on every record write/delete
+ const after = await dataSync.getChecksum('pipeline');
+ expect(after.checksum).not.toBe(before.checksum);
+ expect(after.checksum).toBe((await dataSync.getSnapshot('pipeline')).checksum);
+ });
+
+ it('an issue content change also surfaces once the epoch bumps', async () => {
+ const before = await dataSync.getChecksum('pipeline');
+ issuesContent = [{ id: 'iss-1', seriesId: 'ser-1', number: 1, title: 'New', updatedAt: '2026-05-17T11:00:00Z' }];
+ epoch += 1;
+ const after = await dataSync.getChecksum('pipeline');
+ expect(after.checksum).not.toBe(before.checksum);
+ });
+});
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index d79121d2fb..049b8e25c3 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -18,10 +18,8 @@
* Persisted to data/pipeline-issues/{id}/index.json.
*/
-import { join } from 'path';
import { randomUUID } from 'crypto';
-import { PATHS } from '../../lib/fileUtils.js';
-import { createCollectionStore } from '../../lib/collectionStore.js';
+import { getIssuesStore } from './issuesStore/store.js';
import { isPlainObject } from '../../lib/objects.js';
import { IMAGE_GEN_MODE } from '../imageGen/modes.js';
import {
@@ -39,24 +37,12 @@ import { applyVolumeOrderedNumbers, UNSCOPED_ANCHOR } from '../../lib/pipelineIs
import { maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash } from '../../lib/conflictJournal.js';
import * as seriesSvc from './series.js';
-// TYPE-level (storage layout) schema version stamped on
-// `data/pipeline-issues/index.json`.
-// v1 — issues split out of monolithic `data/pipeline-issues.json` into
-// per-record `data/pipeline-issues/{id}/index.json`. See migration 035.
-const TYPE_SCHEMA_VERSION = 1;
-
-let _store = null;
-const store = () => {
- if (_store && _store.dir === join(PATHS.data, 'pipeline-issues')) return _store;
- _store = createCollectionStore({
- dir: join(PATHS.data, 'pipeline-issues'),
- type: 'pipelineIssues',
- schemaVersion: TYPE_SCHEMA_VERSION,
- sanitizeRecord: sanitizeIssue,
- idPattern: /^iss-[A-Za-z0-9-]+$/,
- });
- return _store;
-};
+// Storage backend dispatcher (#1015). Issue records moved from per-record
+// `data/pipeline-issues/{id}/index.json` (collectionStore) to one-row-per-issue
+// in PostgreSQL (`pipeline_issues`); the facade is a drop-in for the
+// collectionStore surface this service calls (loadAll/loadOne/saveOneNow/
+// deleteOne/queueTypeIndexWrite), so only this factory changed.
+const store = () => getIssuesStore(sanitizeIssue);
export const issueStore = () => store();
diff --git a/server/services/pipeline/issuesStore/db.js b/server/services/pipeline/issuesStore/db.js
new file mode 100644
index 0000000000..2d4da45549
--- /dev/null
+++ b/server/services/pipeline/issuesStore/db.js
@@ -0,0 +1,79 @@
+/**
+ * Pipeline issues — PostgreSQL leaf I/O (#1015).
+ *
+ * One row per issue in `pipeline_issues`: the full sanitized record in `data`
+ * JSONB, including the entire 8-stage `stages` map (text/visual/audio,
+ * runHistory, canonExtraction, covers) and the stage `lastRunId` string
+ * pointers into data/runs/<runId>/ (NOT migrating — file-backed transcripts).
+ * series_id / season_id / number / status / ephemeral / updated_at / deleted /
+ * deleted_at are mirrored into columns for the renumber pass (the hot
+ * `idx_issues_series (series_id, number)` query), review dashboards, the
+ * snapshot ephemeral-filter, and LWW staleness.
+ *
+ * PURE leaf I/O — the store facade owns serialization + sanitize; reads return
+ * `data` verbatim (the columns are a queryable mirror, never read back).
+ */
+
+import { query } from '../../../lib/db.js';
+import { mirrorTimestamp } from '../../../lib/pgTimestamp.js';
+
+/** Raw on-disk-equivalent record (the `data` JSONB), or null. No sanitize. */
+export async function readRaw(id) {
+ const { rows } = await query(`SELECT data FROM pipeline_issues WHERE id = $1`, [id]);
+ return rows[0]?.data ?? null;
+}
+
+/** Every issue id (live, ephemeral, AND tombstones) — the service filters. */
+export async function listIds() {
+ const { rows } = await query(`SELECT id FROM pipeline_issues`);
+ return rows.map((r) => r.id);
+}
+
+/** Every record's raw `data` JSONB in one query (live/ephemeral/tombstones). */
+export async function listRaw() {
+ const { rows } = await query(`SELECT data FROM pipeline_issues`);
+ return rows.map((r) => r.data);
+}
+
+/**
+ * Upsert one record. `data` is written verbatim (lossless); the typed mirror
+ * columns are bind-sanitized so a hand-edited/legacy record can't make the
+ * write throw. `created_at` preserved on conflict.
+ */
+export async function writeRaw(id, record) {
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(record?.createdAt, now);
+ await query(
+ `INSERT INTO pipeline_issues (id, series_id, season_id, number, status, data, ephemeral, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8, $9, $10, $11)
+ ON CONFLICT (id) DO UPDATE SET
+ series_id = EXCLUDED.series_id,
+ season_id = EXCLUDED.season_id,
+ number = EXCLUDED.number,
+ status = EXCLUDED.status,
+ data = EXCLUDED.data,
+ ephemeral = EXCLUDED.ephemeral,
+ updated_at = EXCLUDED.updated_at,
+ deleted = EXCLUDED.deleted,
+ deleted_at = EXCLUDED.deleted_at`,
+ [
+ id,
+ typeof record?.seriesId === 'string' ? record.seriesId : '',
+ typeof record?.seasonId === 'string' && record.seasonId ? record.seasonId : null,
+ Number.isFinite(record?.number) ? Math.floor(record.number) : null,
+ typeof record?.status === 'string' && record.status ? record.status.slice(0, 32) : null,
+ JSON.stringify(record),
+ record?.ephemeral === true,
+ createdAt,
+ mirrorTimestamp(record?.updatedAt, createdAt),
+ record?.deleted === true,
+ mirrorTimestamp(record?.deletedAt, null),
+ ],
+ );
+ return record;
+}
+
+/** Hard-delete a record (tombstone GC). Idempotent — missing row is a no-op. */
+export async function deleteRaw(id) {
+ await query(`DELETE FROM pipeline_issues WHERE id = $1`, [id]);
+}
diff --git a/server/services/pipeline/issuesStore/db.test.js b/server/services/pipeline/issuesStore/db.test.js
new file mode 100644
index 0000000000..ebecfe4df3
--- /dev/null
+++ b/server/services/pipeline/issuesStore/db.test.js
@@ -0,0 +1,100 @@
+/**
+ * Postgres-backed round-trip for the pipeline issues DB adapter (#1015).
+ * SKIPS cleanly when no DB is reachable. Snapshots + restores the table.
+ */
+
+import { describe, it, expect, afterAll, beforeAll, beforeEach } from 'vitest';
+import { checkHealth, ensureSchema, query, close } from '../../../lib/db.js';
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ const probe = await query(
+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'pipeline_issues') AS ok`,
+ ).catch(() => ({ rows: [{ ok: false }] }));
+ if (probe.rows?.[0]?.ok) dbReady = true;
+ else skipReason = 'pipeline_issues table not present';
+ }
+}
+
+if (!dbReady) console.log(`⏭️ pipeline/issuesStore/db.test.js skipped: ${skipReason}`);
+
+const I = (id, extra = {}) => ({
+ id, seriesId: 'ser-1', seasonId: null, number: 1, status: 'draft', title: id,
+ stages: {}, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-02T00:00:00.000Z',
+ deleted: false, deletedAt: null, ...extra,
+});
+
+describe.skipIf(!dbReady)('pipeline issues DB adapter round-trip', () => {
+ let db;
+ let snap = [];
+ beforeAll(async () => {
+ db = await import('./db.js');
+ snap = (await query(`SELECT * FROM pipeline_issues`)).rows;
+ });
+
+ beforeEach(async () => { await query(`DELETE FROM pipeline_issues`); });
+
+ afterAll(async () => {
+ await query(`DELETE FROM pipeline_issues`).catch(() => {});
+ for (const r of snap) {
+ await query(
+ `INSERT INTO pipeline_issues (id, series_id, season_id, number, status, data, ephemeral, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7,$8,$9,$10,$11) ON CONFLICT (id) DO NOTHING`,
+ [r.id, r.series_id, r.season_id, r.number, r.status, JSON.stringify(r.data), r.ephemeral, r.created_at, r.updated_at, r.deleted, r.deleted_at],
+ ).catch(() => {});
+ }
+ await close();
+ });
+
+ it('writes a record and reads it back verbatim (full stages map preserved)', async () => {
+ const rec = I('iss-1', { stages: { idea: { status: 'ready', output: 'beats', lastRunId: 'run-7' } } });
+ await db.writeRaw('iss-1', rec);
+ expect(await db.readRaw('iss-1')).toEqual(rec);
+ });
+
+ it('upsert updates the record and the mirror columns (series_id/number/status)', async () => {
+ await db.writeRaw('iss-1', I('iss-1', { number: 1, status: 'draft' }));
+ await db.writeRaw('iss-1', I('iss-1', { number: 3, status: 'shipped', updatedAt: '2026-03-03T00:00:00.000Z' }));
+ const col = (await query(`SELECT series_id, number, status, updated_at FROM pipeline_issues WHERE id = 'iss-1'`)).rows[0];
+ expect(col.number).toBe(3);
+ expect(col.status).toBe('shipped');
+ expect(new Date(col.updated_at).toISOString()).toBe('2026-03-03T00:00:00.000Z');
+ });
+
+ it('idx_issues_series serves the renumber query (series ordered by number)', async () => {
+ await db.writeRaw('iss-b', I('iss-b', { number: 2 }));
+ await db.writeRaw('iss-a', I('iss-a', { number: 1 }));
+ await db.writeRaw('iss-d', I('iss-d', { number: 9, deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' }));
+ const ordered = (await query(
+ `SELECT id FROM pipeline_issues WHERE series_id = 'ser-1' AND deleted = FALSE ORDER BY number`,
+ )).rows;
+ expect(ordered.map((r) => r.id)).toEqual(['iss-a', 'iss-b']);
+ });
+
+ it('listIds returns live, tombstoned, and ephemeral ids alike', async () => {
+ await db.writeRaw('iss-live', I('iss-live'));
+ await db.writeRaw('iss-dead', I('iss-dead', { deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' }));
+ await db.writeRaw('iss-ghost', I('iss-ghost', { ephemeral: true }));
+ expect((await db.listIds()).sort()).toEqual(['iss-dead', 'iss-ghost', 'iss-live']);
+ });
+
+ it('tolerates a malformed timestamp without throwing', async () => {
+ await db.writeRaw('iss-bad', I('iss-bad', { updatedAt: 'not-a-date', createdAt: 'nope' }));
+ const col = (await query(`SELECT created_at, updated_at FROM pipeline_issues WHERE id = 'iss-bad'`)).rows[0];
+ expect(col.created_at).toBeInstanceOf(Date);
+ expect(col.updated_at).toBeInstanceOf(Date);
+ });
+
+ it('deleteRaw removes the row (idempotent)', async () => {
+ await db.writeRaw('iss-1', I('iss-1'));
+ await db.deleteRaw('iss-1');
+ expect(await db.readRaw('iss-1')).toBeNull();
+ await db.deleteRaw('iss-1');
+ });
+});
diff --git a/server/services/pipeline/issuesStore/store.js b/server/services/pipeline/issuesStore/store.js
new file mode 100644
index 0000000000..f9b405230e
--- /dev/null
+++ b/server/services/pipeline/issuesStore/store.js
@@ -0,0 +1,188 @@
+/**
+ * Pipeline issues — storage backend dispatcher (#1015).
+ *
+ * Issues used to live one-record-per-dir under
+ * data/pipeline-issues/{id}/index.json (collectionStore). As of #1015 they live
+ * one-row-per-issue in PostgreSQL (`pipeline_issues`). This facade is a DROP-IN
+ * for the `createCollectionStore` surface issues.js already calls (loadAll /
+ * loadOne / saveOneNow / deleteOne / queueTypeIndexWrite / verifySchemaVersion),
+ * so the service keeps its public API and only its `store()` factory changes. It
+ * owns the in-process serialization + the sanitizer and delegates leaf I/O to a
+ * memoized backend (PostgreSQL ./db.js, or collectionStore file backend under
+ * MEMORY_BACKEND=file / NODE_ENV=test).
+ *
+ * Federation invisibility: every record write/delete bumps the shared pipeline
+ * MUTATION EPOCH (../syncEpoch.js) — see seriesStore/store.js for the rationale.
+ *
+ * `queueTypeIndexWrite` keeps the single-tail "one consistent merge snapshot"
+ * semantics issues.js relies on for mergeIssuesFromSync / pruneTombstonedIssues
+ * (those read the whole issue set, mutate, and write back; they must serialize
+ * against themselves). It's a process-local promise tail — backend-agnostic.
+ *
+ * The first PG-backed call runs a one-time, marker-gated import of the legacy
+ * data/pipeline-issues file store into the table (migrateIssuesToDB).
+ */
+
+import { join } from 'path';
+import { PATHS } from '../../../lib/fileUtils.js';
+import { createCollectionStore } from '../../../lib/collectionStore.js';
+import { checkHealth, ensureSchema } from '../../../lib/db.js';
+import { bumpPipelineMutationEpoch } from '../syncEpoch.js';
+
+const TYPE_SCHEMA_VERSION = 1;
+const ID_PATTERN = /^iss-[A-Za-z0-9-]+$/;
+
+function isFileBackend() {
+ return process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test';
+}
+
+function assertValidId(id) {
+ if (typeof id !== 'string' || !ID_PATTERN.test(id)) {
+ throw new Error(`pipelineIssuesStore: invalid record id "${id}" — must match ${ID_PATTERN}`);
+ }
+}
+
+function makeFileBackend(dir, sanitizeRecord) {
+ const cs = createCollectionStore({
+ dir,
+ type: 'pipelineIssues',
+ schemaVersion: TYPE_SCHEMA_VERSION,
+ sanitizeRecord,
+ idPattern: ID_PATTERN,
+ });
+ return {
+ name: 'file',
+ readOne: (id) => cs.loadOne(id),
+ listIds: () => cs.listIds(),
+ listRaw: async () => {
+ const ids = await cs.listIds();
+ const records = await Promise.all(ids.map((id) => cs.loadOneRaw(id)));
+ return records.filter((r) => r != null);
+ },
+ writeRaw: (id, record) => cs.saveOneNow(id, record),
+ deleteRaw: (id) => cs.deleteOneNow(id),
+ verify: () => cs.verifySchemaVersion(),
+ };
+}
+
+function makePgBackend(db, sanitizeRecord) {
+ return {
+ name: 'postgres',
+ readOne: async (id) => {
+ const raw = await db.readRaw(id);
+ return raw ? sanitizeRecord(raw) : null;
+ },
+ listIds: db.listIds,
+ listRaw: db.listRaw,
+ writeRaw: db.writeRaw,
+ deleteRaw: db.deleteRaw,
+ verify: async () => ({ ok: true, type: 'pipelineIssues', onDisk: null, expected: null,
+ message: 'collection "pipelineIssues" @ postgres (#1015)' }),
+ };
+}
+
+async function pgBackend(sanitizeRecord) {
+ const health = await checkHealth();
+ if (!health.connected) {
+ throw new Error('Pipeline issues require PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)');
+ }
+ await ensureSchema();
+ const { migrateIssuesToDB } = await import('../../../scripts/migrateIssuesToDB.js');
+ await migrateIssuesToDB();
+ const db = await import('./db.js');
+ return makePgBackend(db, sanitizeRecord);
+}
+
+function createFacade({ dir, sanitizeRecord }) {
+ const sanitizer = typeof sanitizeRecord === 'function' ? sanitizeRecord : (r) => r;
+
+ let backend = null;
+ let selecting = null;
+ const getBackend = () => {
+ if (backend) return Promise.resolve(backend);
+ if (!selecting) {
+ selecting = (isFileBackend() ? Promise.resolve(makeFileBackend(dir, sanitizer)) : pgBackend(sanitizer))
+ .then((b) => { backend = b; return b; })
+ .finally(() => { selecting = null; });
+ }
+ return selecting;
+ };
+
+ // Single-tail type-index queue — mirrors collectionStore.queueTypeIndexWrite.
+ // mergeIssuesFromSync / pruneTombstonedIssues load the whole issue set, mutate,
+ // and write back; they must serialize against themselves for one consistent
+ // merge snapshot.
+ let typeIndexTail = Promise.resolve();
+ function queueTypeIndexWrite(fn) {
+ const next = typeIndexTail.then(fn, fn);
+ const silenced = next.catch(() => {});
+ typeIndexTail = silenced;
+ silenced.finally(() => { if (typeIndexTail === silenced) typeIndexTail = Promise.resolve(); });
+ return next;
+ }
+
+ const saveOneNow = async (id, record) => {
+ assertValidId(id);
+ const out = await (await getBackend()).writeRaw(id, record);
+ bumpPipelineMutationEpoch();
+ return out ?? record;
+ };
+
+ const deleteOneNow = async (id) => {
+ assertValidId(id);
+ await (await getBackend()).deleteRaw(id);
+ bumpPipelineMutationEpoch();
+ };
+
+ return {
+ dir,
+ type: 'pipelineIssues',
+ getBackendName: () => backend?.name ?? null,
+
+ listIds: async () => (await getBackend()).listIds(),
+ loadOne: async (id) => {
+ if (typeof id !== 'string' || !ID_PATTERN.test(id)) return null;
+ return (await getBackend()).readOne(id);
+ },
+ loadAll: async () => {
+ const raw = await (await getBackend()).listRaw();
+ return raw.map((r) => sanitizer(r)).filter((r) => r != null);
+ },
+
+ saveOneNow,
+ deleteOneNow,
+ deleteOne: deleteOneNow, // issues delete from inside queueTypeIndexWrite / Promise.all batches
+
+ queueTypeIndexWrite,
+
+ verifySchemaVersion: async () => {
+ if (!isFileBackend()) {
+ return { ok: true, type: 'pipelineIssues', onDisk: null, expected: null,
+ message: 'collection "pipelineIssues" @ postgres (#1015)' };
+ }
+ return (await getBackend()).verify();
+ },
+ };
+}
+
+let _facade = null;
+let _facadeDir = null;
+
+/**
+ * Get the issues store facade. Pass the record sanitizer (sanitizeIssue) so
+ * loadOne/loadAll return sanitized records. Synchronous — backend selection is
+ * deferred into each method.
+ */
+export function getIssuesStore(sanitizeRecord) {
+ const dir = join(PATHS.data, 'pipeline-issues');
+ if (_facade && _facadeDir === dir) return _facade;
+ _facade = createFacade({ dir, sanitizeRecord });
+ _facadeDir = dir;
+ return _facade;
+}
+
+/** Reset the memoized facade — test seam only (does NOT reset the epoch). */
+export function _resetIssuesStore() {
+ _facade = null;
+ _facadeDir = null;
+}
diff --git a/server/services/pipeline/issuesStore/store.test.js b/server/services/pipeline/issuesStore/store.test.js
new file mode 100644
index 0000000000..df066fc720
--- /dev/null
+++ b/server/services/pipeline/issuesStore/store.test.js
@@ -0,0 +1,92 @@
+/**
+ * Pipeline issues store facade — file-backend dispatcher behavior (#1015).
+ *
+ * NODE_ENV=test selects the file backend (collectionStore over a real tmpdir),
+ * so this exercises the facade WITHOUT a database: the collectionStore-compatible
+ * surface issues.js uses (loadAll / loadOne / saveOneNow / deleteOne /
+ * queueTypeIndexWrite), and the shared pipeline mutation epoch that record
+ * writes/deletes bump (and reads do not).
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'issues-store-test-'));
+
+vi.mock('../../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+});
+
+const { getIssuesStore, _resetIssuesStore } = await import('./store.js');
+const { getPipelineMutationEpoch } = await import('../syncEpoch.js');
+
+const passthroughSanitize = (r) => (r ? { ...r, _sanitized: true } : r);
+
+describe('pipeline issues store facade — file backend', () => {
+ beforeEach(() => {
+ rmSync(join(TEST_DATA_ROOT, 'pipeline-issues'), { recursive: true, force: true });
+ _resetIssuesStore();
+ });
+ afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+ it('selects the file backend under NODE_ENV=test', async () => {
+ const s = getIssuesStore(passthroughSanitize);
+ await s.listIds();
+ expect(s.getBackendName()).toBe('file');
+ });
+
+ it('saveOneNow persists, loadOne sanitizes, loadAll lists', async () => {
+ const s = getIssuesStore(passthroughSanitize);
+ await s.saveOneNow('iss-1', { id: 'iss-1', seriesId: 'ser-1', title: 'One' });
+ expect(await s.loadOne('iss-1')).toEqual({ id: 'iss-1', seriesId: 'ser-1', title: 'One', _sanitized: true });
+ await s.saveOneNow('iss-2', { id: 'iss-2', seriesId: 'ser-1', title: 'Two' });
+ expect((await s.loadAll()).map((r) => r.id).sort()).toEqual(['iss-1', 'iss-2']);
+ });
+
+ it('deleteOne removes the record', async () => {
+ const s = getIssuesStore(passthroughSanitize);
+ await s.saveOneNow('iss-1', { id: 'iss-1', seriesId: 'ser-1', title: 'X' });
+ await s.deleteOne('iss-1');
+ expect(await s.loadOne('iss-1')).toBeNull();
+ expect(await s.listIds()).toEqual([]);
+ });
+
+ it('record writes AND deletes bump the pipeline mutation epoch; reads do not', async () => {
+ const s = getIssuesStore(passthroughSanitize);
+ const e0 = getPipelineMutationEpoch();
+ await s.saveOneNow('iss-1', { id: 'iss-1', seriesId: 'ser-1', title: 'X' });
+ const e1 = getPipelineMutationEpoch();
+ expect(e1).toBeGreaterThan(e0);
+ await s.loadOne('iss-1');
+ await s.loadAll();
+ expect(getPipelineMutationEpoch()).toBe(e1);
+ await s.deleteOne('iss-1');
+ expect(getPipelineMutationEpoch()).toBeGreaterThan(e1);
+ });
+
+ it('queueTypeIndexWrite single-tail serializes against itself', async () => {
+ const s = getIssuesStore(passthroughSanitize);
+ const order = [];
+ await Promise.all([
+ s.queueTypeIndexWrite(async () => { order.push('a-start'); await Promise.resolve(); order.push('a-end'); }),
+ s.queueTypeIndexWrite(async () => { order.push('b'); }),
+ ]);
+ expect(order).toEqual(['a-start', 'a-end', 'b']);
+ });
+
+ it('saveOneNow rejects ids outside the iss- allowlist', async () => {
+ const s = getIssuesStore(passthroughSanitize);
+ await expect(s.saveOneNow('ser-1', { id: 'ser-1', seriesId: 'ser-1', title: 'X' })).rejects.toThrow(/invalid record id/);
+ });
+
+ it('verifySchemaVersion reports the file collection version', async () => {
+ const s = getIssuesStore(passthroughSanitize);
+ await s.saveOneNow('iss-1', { id: 'iss-1', seriesId: 'ser-1', title: 'X' });
+ const status = await s.verifySchemaVersion();
+ expect(status.ok).toBe(true);
+ expect(status.type).toBe('pipelineIssues');
+ });
+});
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 7b246f87ab..e2f0d97e37 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -11,10 +11,8 @@
* collection (server/services/pipeline/issues.js) and reference a series by id.
*/
-import { join } from 'path';
import { randomUUID } from 'crypto';
-import { PATHS } from '../../lib/fileUtils.js';
-import { createCollectionStore } from '../../lib/collectionStore.js';
+import { getSeriesStore } from './seriesStore/store.js';
import { isStr, trimTo } from '../../lib/storyBible.js';
import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';
import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
@@ -26,26 +24,13 @@ import {
import { emitRecordUpdated, emitRecordDeleted } from '../sharing/recordEvents.js';
import { renameCollectionForSeries, unlinkCollectionsForSeries } from '../mediaCollections.js';
-// TYPE-level (storage layout) schema version stamped on
-// `data/pipeline-series/index.json`.
-// v1 — series split out of monolithic `data/pipeline-series.json` into
-// per-record `data/pipeline-series/{id}/index.json`. See migration 036.
-const TYPE_SCHEMA_VERSION = 1;
-
-// Lazy store factory so tests that swap PATHS.data per-test still see the
-// right temp root — the store captures PATHS.data once at first call.
-let _store = null;
-const store = () => {
- if (_store && _store.dir === join(PATHS.data, 'pipeline-series')) return _store;
- _store = createCollectionStore({
- dir: join(PATHS.data, 'pipeline-series'),
- type: 'pipelineSeries',
- schemaVersion: TYPE_SCHEMA_VERSION,
- sanitizeRecord: sanitizeSeries,
- idPattern: /^ser-[A-Za-z0-9-]+$/,
- });
- return _store;
-};
+// Storage backend dispatcher (#1015). Series records moved from per-record
+// `data/pipeline-series/{id}/index.json` (collectionStore) to one-row-per-series
+// in PostgreSQL (`pipeline_series`); the facade is a drop-in for the
+// collectionStore surface this service calls, so only this factory changed. The
+// `manuscript-review.json` sibling doc stays file-primary — the facade's
+// `recordDir(id)` still resolves to the on-disk path manuscriptReview.js reads.
+const store = () => getSeriesStore(sanitizeSeries);
export const seriesStore = () => store();
diff --git a/server/services/pipeline/seriesStore/db.js b/server/services/pipeline/seriesStore/db.js
new file mode 100644
index 0000000000..a5166f9b4f
--- /dev/null
+++ b/server/services/pipeline/seriesStore/db.js
@@ -0,0 +1,84 @@
+/**
+ * Pipeline series — PostgreSQL leaf I/O (#1015).
+ *
+ * One row per series in `pipeline_series`: the full sanitized record
+ * (arc, seasons[], locks, covers, style notes) in `data` JSONB, with
+ * name / universe_id / writers_room_work_id / ephemeral / updated_at /
+ * deleted / deleted_at mirrored into columns for the queries the service +
+ * federation actually run (rename cascade, universe delete-guard, "series in
+ * this universe" lists, snapshot ephemeral-filter, LWW staleness, the
+ * writers-room promote back-link).
+ *
+ * PURE leaf I/O — no in-process serialization, no sanitizing. The store facade
+ * (store.js) owns the per-id write queue + the mutation epoch and applies
+ * `sanitizeSeries` on read, so reads here return `data` verbatim (the columns
+ * are a queryable mirror, never read back).
+ *
+ * The series' `manuscript-review.json` sibling doc is `file-primary` and does
+ * NOT live here — it stays on disk under data/pipeline-series/{id}/ (see
+ * manuscriptReview.js); only the series record itself moved to PG.
+ */
+
+import { query } from '../../../lib/db.js';
+import { mirrorTimestamp } from '../../../lib/pgTimestamp.js';
+
+/** Raw on-disk-equivalent record (the `data` JSONB), or null. No sanitize. */
+export async function readRaw(id) {
+ const { rows } = await query(`SELECT data FROM pipeline_series WHERE id = $1`, [id]);
+ return rows[0]?.data ?? null;
+}
+
+/** Every series id (live, ephemeral, AND tombstones) — the service filters. */
+export async function listIds() {
+ const { rows } = await query(`SELECT id FROM pipeline_series`);
+ return rows.map((r) => r.id);
+}
+
+/** Every record's raw `data` JSONB in one query (live/ephemeral/tombstones). */
+export async function listRaw() {
+ const { rows } = await query(`SELECT data FROM pipeline_series`);
+ return rows.map((r) => r.data);
+}
+
+/**
+ * Upsert one record. `data` is written verbatim (lossless); the typed mirror
+ * columns are bind-sanitized so a hand-edited/legacy record with a malformed
+ * timestamp or missing field can't make the write throw (which, during the boot
+ * warm/import, would block the whole backend). `created_at` is preserved on
+ * conflict — only the first INSERT sets it.
+ */
+export async function writeRaw(id, record) {
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(record?.createdAt, now);
+ await query(
+ `INSERT INTO pipeline_series (id, name, universe_id, writers_room_work_id, data, ephemeral, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10)
+ ON CONFLICT (id) DO UPDATE SET
+ name = EXCLUDED.name,
+ universe_id = EXCLUDED.universe_id,
+ writers_room_work_id = EXCLUDED.writers_room_work_id,
+ data = EXCLUDED.data,
+ ephemeral = EXCLUDED.ephemeral,
+ updated_at = EXCLUDED.updated_at,
+ deleted = EXCLUDED.deleted,
+ deleted_at = EXCLUDED.deleted_at`,
+ [
+ id,
+ typeof record?.name === 'string' ? record.name : '',
+ typeof record?.universeId === 'string' && record.universeId ? record.universeId : null,
+ typeof record?.writersRoomWorkId === 'string' && record.writersRoomWorkId ? record.writersRoomWorkId : null,
+ JSON.stringify(record),
+ record?.ephemeral === true,
+ createdAt,
+ mirrorTimestamp(record?.updatedAt, createdAt),
+ record?.deleted === true,
+ mirrorTimestamp(record?.deletedAt, null),
+ ],
+ );
+ return record;
+}
+
+/** Hard-delete a record (tombstone GC). Idempotent — missing row is a no-op. */
+export async function deleteRaw(id) {
+ await query(`DELETE FROM pipeline_series WHERE id = $1`, [id]);
+}
diff --git a/server/services/pipeline/seriesStore/db.test.js b/server/services/pipeline/seriesStore/db.test.js
new file mode 100644
index 0000000000..299d39a600
--- /dev/null
+++ b/server/services/pipeline/seriesStore/db.test.js
@@ -0,0 +1,101 @@
+/**
+ * Postgres-backed round-trip for the pipeline series DB adapter (#1015).
+ *
+ * Like universeBuilder/db.test.js, needs a live PostgreSQL with the schema
+ * applied; SKIPS cleanly when no DB is reachable. Snapshots + restores the table
+ * so a developer's real series survive the run.
+ */
+
+import { describe, it, expect, afterAll, beforeAll, beforeEach } from 'vitest';
+import { checkHealth, ensureSchema, query, close } from '../../../lib/db.js';
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ const probe = await query(
+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'pipeline_series') AS ok`,
+ ).catch(() => ({ rows: [{ ok: false }] }));
+ if (probe.rows?.[0]?.ok) dbReady = true;
+ else skipReason = 'pipeline_series table not present';
+ }
+}
+
+if (!dbReady) console.log(`⏭️ pipeline/seriesStore/db.test.js skipped: ${skipReason}`);
+
+const S = (id, extra = {}) => ({
+ id, name: id, universeId: null, writersRoomWorkId: null,
+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-02T00:00:00.000Z',
+ deleted: false, deletedAt: null, ...extra,
+});
+
+describe.skipIf(!dbReady)('pipeline series DB adapter round-trip', () => {
+ let db;
+ let snap = [];
+ beforeAll(async () => {
+ db = await import('./db.js');
+ snap = (await query(`SELECT * FROM pipeline_series`)).rows;
+ });
+
+ beforeEach(async () => { await query(`DELETE FROM pipeline_series`); });
+
+ afterAll(async () => {
+ await query(`DELETE FROM pipeline_series`).catch(() => {});
+ for (const r of snap) {
+ await query(
+ `INSERT INTO pipeline_series (id, name, universe_id, writers_room_work_id, data, ephemeral, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1,$2,$3,$4,$5::jsonb,$6,$7,$8,$9,$10) ON CONFLICT (id) DO NOTHING`,
+ [r.id, r.name, r.universe_id, r.writers_room_work_id, JSON.stringify(r.data), r.ephemeral, r.created_at, r.updated_at, r.deleted, r.deleted_at],
+ ).catch(() => {});
+ }
+ await close();
+ });
+
+ it('writes a record and reads it back verbatim', async () => {
+ const rec = S('ser-1', { universeId: 'u-1', seasons: [{ id: 'sea-1', number: 1 }], arc: { logline: 'x' } });
+ await db.writeRaw('ser-1', rec);
+ expect(await db.readRaw('ser-1')).toEqual(rec);
+ });
+
+ it('upsert updates the record and the mirror columns', async () => {
+ await db.writeRaw('ser-1', S('ser-1', { name: 'First', universeId: 'u-1' }));
+ await db.writeRaw('ser-1', S('ser-1', { name: 'Renamed', universeId: 'u-2', updatedAt: '2026-03-03T00:00:00.000Z' }));
+ const col = (await query(`SELECT name, universe_id, updated_at FROM pipeline_series WHERE id = 'ser-1'`)).rows[0];
+ expect(col.name).toBe('Renamed');
+ expect(col.universe_id).toBe('u-2');
+ expect(new Date(col.updated_at).toISOString()).toBe('2026-03-03T00:00:00.000Z');
+ });
+
+ it('idx_series_universe serves "live series in a universe" (the delete-guard query)', async () => {
+ await db.writeRaw('ser-1', S('ser-1', { universeId: 'u-1' }));
+ await db.writeRaw('ser-2', S('ser-2', { universeId: 'u-1', deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' }));
+ await db.writeRaw('ser-3', S('ser-3', { universeId: 'u-2' }));
+ const live = (await query(`SELECT id FROM pipeline_series WHERE universe_id = 'u-1' AND deleted = FALSE`)).rows;
+ expect(live.map((r) => r.id)).toEqual(['ser-1']);
+ });
+
+ it('listIds returns live, tombstoned, and ephemeral ids alike', async () => {
+ await db.writeRaw('ser-live', S('ser-live'));
+ await db.writeRaw('ser-dead', S('ser-dead', { deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' }));
+ await db.writeRaw('ser-ghost', S('ser-ghost', { ephemeral: true }));
+ expect((await db.listIds()).sort()).toEqual(['ser-dead', 'ser-ghost', 'ser-live']);
+ });
+
+ it('tolerates a malformed timestamp without throwing (falls back)', async () => {
+ await db.writeRaw('ser-bad', S('ser-bad', { updatedAt: 'not-a-date', createdAt: 'nope' }));
+ const col = (await query(`SELECT created_at, updated_at FROM pipeline_series WHERE id = 'ser-bad'`)).rows[0];
+ expect(col.created_at).toBeInstanceOf(Date);
+ expect(col.updated_at).toBeInstanceOf(Date);
+ });
+
+ it('deleteRaw removes the row (idempotent)', async () => {
+ await db.writeRaw('ser-1', S('ser-1'));
+ await db.deleteRaw('ser-1');
+ expect(await db.readRaw('ser-1')).toBeNull();
+ await db.deleteRaw('ser-1');
+ });
+});
diff --git a/server/services/pipeline/seriesStore/store.js b/server/services/pipeline/seriesStore/store.js
new file mode 100644
index 0000000000..866627f370
--- /dev/null
+++ b/server/services/pipeline/seriesStore/store.js
@@ -0,0 +1,221 @@
+/**
+ * Pipeline series — storage backend dispatcher (#1015).
+ *
+ * Series used to live one-record-per-dir under
+ * data/pipeline-series/{id}/index.json (collectionStore). As of #1015 they live
+ * one-row-per-series in PostgreSQL (`pipeline_series`). This facade is a
+ * DROP-IN for the `createCollectionStore` surface series.js already calls
+ * (loadAll / loadOne / queueRecordWrite / saveOne / saveOneNow / deleteOneNow /
+ * recordDir / verifySchemaVersion), so the service keeps its public API and only
+ * its `store()` factory changes. It owns the in-process serialization (per-id
+ * write queue) + the sanitizer, and delegates only leaf I/O to a memoized
+ * backend:
+ *
+ * - PostgreSQL (./db.js) for normal installs.
+ * - File (collectionStore) only under MEMORY_BACKEND=file or NODE_ENV=test —
+ * both UNSUPPORTED for production. Tests boot without a DB, so they keep
+ * exercising the per-record file store exactly as before.
+ *
+ * Federation invisibility (D2 of the schema-design doc): dataSync decides WHEN to
+ * re-send the pipeline snapshot by fingerprinting the data/pipeline-series +
+ * data/pipeline-issues directories. A PG-backed series edit no longer touches
+ * those directories, so the shared pipeline MUTATION EPOCH (./syncEpoch.js) is
+ * bumped on every record write/delete; dataSync folds it into the pipeline +
+ * mediaCollections fingerprints, keeping the storage swap invisible to peers.
+ *
+ * `recordDir(id)` ALWAYS returns the on-disk path
+ * data/pipeline-series/{id} regardless of backend — the series'
+ * `manuscript-review.json` sibling doc is `file-primary` and stays on disk
+ * (manuscriptReview.js reads/writes it there). Only the series record itself
+ * (index.json) moved to PG.
+ *
+ * The first PG-backed call runs a one-time, marker-gated import of the legacy
+ * data/pipeline-series file store into the table (migrateSeriesToDB), leaving
+ * the manuscript-review.json siblings in place.
+ */
+
+import { join } from 'path';
+import { PATHS } from '../../../lib/fileUtils.js';
+import { createCollectionStore } from '../../../lib/collectionStore.js';
+import { checkHealth, ensureSchema } from '../../../lib/db.js';
+import { bumpPipelineMutationEpoch } from '../syncEpoch.js';
+
+// TYPE-level (storage layout) schema version stamped on the file backend's
+// data/pipeline-series/index.json — preserved so an install on the file escape
+// hatch still passes the boot verifier. (PG has no type-index file.)
+const TYPE_SCHEMA_VERSION = 1;
+const ID_PATTERN = /^ser-[A-Za-z0-9-]+$/;
+
+function isFileBackend() {
+ return process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test';
+}
+
+function assertValidId(id) {
+ if (typeof id !== 'string' || !ID_PATTERN.test(id)) {
+ throw new Error(`pipelineSeriesStore: invalid record id "${id}" — must match ${ID_PATTERN}`);
+ }
+}
+
+// --- File backend (escape hatch / tests): wraps collectionStore ---
+function makeFileBackend(dir, sanitizeRecord) {
+ const cs = createCollectionStore({
+ dir,
+ type: 'pipelineSeries',
+ schemaVersion: TYPE_SCHEMA_VERSION,
+ sanitizeRecord,
+ idPattern: ID_PATTERN,
+ });
+ return {
+ name: 'file',
+ readRaw: (id) => cs.loadOneRaw(id),
+ readOne: (id) => cs.loadOne(id),
+ listIds: () => cs.listIds(),
+ listRaw: async () => {
+ const ids = await cs.listIds();
+ const records = await Promise.all(ids.map((id) => cs.loadOneRaw(id)));
+ return records.filter((r) => r != null);
+ },
+ writeRaw: (id, record) => cs.saveOneNow(id, record),
+ deleteRaw: (id) => cs.deleteOneNow(id),
+ verify: () => cs.verifySchemaVersion(),
+ };
+}
+
+// --- PostgreSQL backend: pure leaf I/O from ./db.js ---
+function makePgBackend(db, sanitizeRecord) {
+ return {
+ name: 'postgres',
+ readRaw: db.readRaw,
+ readOne: async (id) => {
+ const raw = await db.readRaw(id);
+ return raw ? sanitizeRecord(raw) : null;
+ },
+ listIds: db.listIds,
+ listRaw: db.listRaw,
+ writeRaw: db.writeRaw,
+ deleteRaw: db.deleteRaw,
+ verify: async () => ({ ok: true, type: 'pipelineSeries', onDisk: null, expected: null,
+ message: 'collection "pipelineSeries" @ postgres (#1015)' }),
+ };
+}
+
+async function pgBackend(sanitizeRecord) {
+ const health = await checkHealth();
+ if (!health.connected) {
+ throw new Error('Pipeline series require PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)');
+ }
+ await ensureSchema();
+ const { migrateSeriesToDB } = await import('../../../scripts/migrateSeriesToDB.js');
+ await migrateSeriesToDB();
+ const db = await import('./db.js');
+ return makePgBackend(db, sanitizeRecord);
+}
+
+// --- Facade: collectionStore-compatible, queues + epoch + sanitize ---
+function createFacade({ dir, sanitizeRecord }) {
+ const sanitizer = typeof sanitizeRecord === 'function' ? sanitizeRecord : (r) => r;
+
+ let backend = null;
+ let selecting = null;
+ const getBackend = () => {
+ if (backend) return Promise.resolve(backend);
+ if (!selecting) {
+ selecting = (isFileBackend() ? Promise.resolve(makeFileBackend(dir, sanitizer)) : pgBackend(sanitizer))
+ .then((b) => { backend = b; return b; })
+ .finally(() => { selecting = null; });
+ }
+ return selecting;
+ };
+
+ // Per-id write queue — mirrors collectionStore.queueRecordWrite.
+ const recordTails = new Map();
+ function queueRecordWrite(id, fn) {
+ assertValidId(id);
+ const prev = recordTails.get(id) || Promise.resolve();
+ const next = prev.then(fn, fn);
+ const silenced = next.catch(() => {});
+ recordTails.set(id, silenced);
+ silenced.finally(() => { if (recordTails.get(id) === silenced) recordTails.delete(id); });
+ return next;
+ }
+
+ const loadOne = async (id) => {
+ if (typeof id !== 'string' || !ID_PATTERN.test(id)) return null;
+ return (await getBackend()).readOne(id);
+ };
+
+ const saveOneNow = async (id, record) => {
+ assertValidId(id);
+ const out = await (await getBackend()).writeRaw(id, record);
+ bumpPipelineMutationEpoch();
+ return out ?? record;
+ };
+
+ const deleteOneNow = async (id) => {
+ assertValidId(id);
+ await (await getBackend()).deleteRaw(id);
+ bumpPipelineMutationEpoch();
+ };
+
+ return {
+ dir,
+ type: 'pipelineSeries',
+ // recordDir ALWAYS resolves to the on-disk path — the manuscript-review.json
+ // sibling is file-primary and lives there regardless of the record backend.
+ recordDir: (id) => join(dir, id),
+ getBackendName: () => backend?.name ?? null,
+
+ // Reads (sanitized, matching collectionStore.loadOne/loadAll)
+ listIds: async () => (await getBackend()).listIds(),
+ loadOne,
+ loadOneRaw: async (id) => {
+ if (typeof id !== 'string' || !ID_PATTERN.test(id)) return null;
+ return (await getBackend()).readRaw(id);
+ },
+ loadAll: async () => {
+ const raw = await (await getBackend()).listRaw();
+ return raw.map((r) => sanitizer(r)).filter((r) => r != null);
+ },
+
+ // Writes
+ queueRecordWrite,
+ saveOneNow,
+ saveOne: (id, record) => queueRecordWrite(id, () => saveOneNow(id, record)),
+ deleteOneNow,
+ deleteOne: (id) => queueRecordWrite(id, () => deleteOneNow(id)),
+
+ // Boot-time verifier. Under PG return ok WITHOUT forcing backend selection
+ // (the early boot verifier runs before the dbReady gate; the authoritative
+ // warm in index.js selects the backend at the right time).
+ verifySchemaVersion: async () => {
+ if (!isFileBackend()) {
+ return { ok: true, type: 'pipelineSeries', onDisk: null, expected: null,
+ message: 'collection "pipelineSeries" @ postgres (#1015)' };
+ }
+ return (await getBackend()).verify();
+ },
+ };
+}
+
+let _facade = null;
+let _facadeDir = null;
+
+/**
+ * Get the series store facade. Pass the record sanitizer (sanitizeSeries) so
+ * loadOne/loadAll return sanitized records without store.js importing the
+ * service (which would close a cycle). Synchronous — backend selection is
+ * deferred into each method.
+ */
+export function getSeriesStore(sanitizeRecord) {
+ const dir = join(PATHS.data, 'pipeline-series');
+ if (_facade && _facadeDir === dir) return _facade;
+ _facade = createFacade({ dir, sanitizeRecord });
+ _facadeDir = dir;
+ return _facade;
+}
+
+/** Reset the memoized facade — test seam only (does NOT reset the epoch). */
+export function _resetSeriesStore() {
+ _facade = null;
+ _facadeDir = null;
+}
diff --git a/server/services/pipeline/seriesStore/store.test.js b/server/services/pipeline/seriesStore/store.test.js
new file mode 100644
index 0000000000..91c1f7d211
--- /dev/null
+++ b/server/services/pipeline/seriesStore/store.test.js
@@ -0,0 +1,110 @@
+/**
+ * Pipeline series store facade — file-backend dispatcher behavior (#1015).
+ *
+ * NODE_ENV=test selects the file backend (collectionStore over a real tmpdir),
+ * so this exercises the facade WITHOUT a database: the collectionStore-compatible
+ * read/write/delete surface series.js uses, recordDir resolving to the on-disk
+ * path (so manuscript-review.json siblings stay file-backed), and the shared
+ * pipeline mutation epoch that record writes/deletes bump (and reads do not) —
+ * the signal dataSync folds into its fingerprint so the storage swap stays
+ * invisible to federation.
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'series-store-test-'));
+
+vi.mock('../../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+});
+
+const { getSeriesStore, _resetSeriesStore } = await import('./store.js');
+const { getPipelineMutationEpoch } = await import('../syncEpoch.js');
+
+const passthroughSanitize = (r) => (r ? { ...r, _sanitized: true } : r);
+
+describe('pipeline series store facade — file backend', () => {
+ beforeEach(() => {
+ rmSync(join(TEST_DATA_ROOT, 'pipeline-series'), { recursive: true, force: true });
+ _resetSeriesStore();
+ });
+ afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+ it('selects the file backend under NODE_ENV=test', async () => {
+ const s = getSeriesStore(passthroughSanitize);
+ await s.listIds();
+ expect(s.getBackendName()).toBe('file');
+ });
+
+ it('saveOneNow persists, loadOneRaw returns verbatim, loadOne sanitizes', async () => {
+ const s = getSeriesStore(passthroughSanitize);
+ await s.saveOneNow('ser-1', { id: 'ser-1', name: 'Salt Run' });
+ expect(await s.loadOneRaw('ser-1')).toEqual({ id: 'ser-1', name: 'Salt Run' });
+ expect(await s.loadOne('ser-1')).toEqual({ id: 'ser-1', name: 'Salt Run', _sanitized: true });
+ expect(await s.listIds()).toEqual(['ser-1']);
+ });
+
+ it('loadAll returns every record sanitized', async () => {
+ const s = getSeriesStore(passthroughSanitize);
+ await s.saveOneNow('ser-1', { id: 'ser-1', name: 'A' });
+ await s.saveOneNow('ser-2', { id: 'ser-2', name: 'B' });
+ const all = await s.loadAll();
+ expect(all.map((r) => r.id).sort()).toEqual(['ser-1', 'ser-2']);
+ expect(all.every((r) => r._sanitized)).toBe(true);
+ });
+
+ it('deleteOneNow removes the record', async () => {
+ const s = getSeriesStore(passthroughSanitize);
+ await s.saveOneNow('ser-1', { id: 'ser-1', name: 'X' });
+ await s.deleteOneNow('ser-1');
+ expect(await s.loadOneRaw('ser-1')).toBeNull();
+ expect(await s.listIds()).toEqual([]);
+ });
+
+ it('recordDir resolves to the on-disk path regardless of backend (review siblings)', async () => {
+ const s = getSeriesStore(passthroughSanitize);
+ expect(s.recordDir('ser-1')).toBe(join(TEST_DATA_ROOT, 'pipeline-series', 'ser-1'));
+ });
+
+ it('record writes AND deletes bump the pipeline mutation epoch; reads do not', async () => {
+ const s = getSeriesStore(passthroughSanitize);
+ const e0 = getPipelineMutationEpoch();
+ await s.saveOneNow('ser-1', { id: 'ser-1', name: 'X' });
+ const e1 = getPipelineMutationEpoch();
+ expect(e1).toBeGreaterThan(e0);
+ await s.loadOne('ser-1');
+ await s.listIds();
+ expect(getPipelineMutationEpoch()).toBe(e1); // reads don't bump
+ await s.deleteOneNow('ser-1');
+ expect(getPipelineMutationEpoch()).toBeGreaterThan(e1);
+ });
+
+ it('queueRecordWrite serializes same-id RMW and rejects bad ids', async () => {
+ const s = getSeriesStore(passthroughSanitize);
+ expect(() => s.queueRecordWrite('bad-id', async () => 'never')).toThrow(/invalid record id/);
+ const order = [];
+ await Promise.all([
+ s.queueRecordWrite('ser-x', async () => { order.push('a-start'); await Promise.resolve(); order.push('a-end'); }),
+ s.queueRecordWrite('ser-x', async () => { order.push('b'); }),
+ ]);
+ expect(order).toEqual(['a-start', 'a-end', 'b']);
+ });
+
+ it('saveOneNow / deleteOneNow reject ids outside the ser- allowlist (backend parity)', async () => {
+ const s = getSeriesStore(passthroughSanitize);
+ await expect(s.saveOneNow('iss-1', { id: 'iss-1', name: 'X' })).rejects.toThrow(/invalid record id/);
+ await expect(s.deleteOneNow('nope')).rejects.toThrow(/invalid record id/);
+ });
+
+ it('verifySchemaVersion reports the file collection version', async () => {
+ const s = getSeriesStore(passthroughSanitize);
+ await s.saveOneNow('ser-1', { id: 'ser-1', name: 'X' });
+ const status = await s.verifySchemaVersion();
+ expect(status.ok).toBe(true);
+ expect(status.type).toBe('pipelineSeries');
+ });
+});
diff --git a/server/services/pipeline/syncEpoch.js b/server/services/pipeline/syncEpoch.js
new file mode 100644
index 0000000000..5f543b0619
--- /dev/null
+++ b/server/services/pipeline/syncEpoch.js
@@ -0,0 +1,37 @@
+/**
+ * Pipeline mutation epoch — the dataSync federation-invisibility signal (#1015).
+ *
+ * Pipeline series + issues used to live in per-record dirs under
+ * data/pipeline-series/{id} and data/pipeline-issues/{id}. dataSync's `pipeline`
+ * snapshot-cache fingerprint stats those directories to decide WHEN to re-send
+ * the pipeline snapshot to peers. As of #1015 the records live in PostgreSQL
+ * (`pipeline_series` / `pipeline_issues`), so a record edit no longer touches
+ * those directories — without help, the dir fingerprint would never invalidate
+ * and peers would silently stop receiving pipeline edits.
+ *
+ * The fix mirrors the universe store's mutation epoch (#1014): a single
+ * module-level monotonic counter bumped on every series/issue record
+ * write/delete. dataSync folds it into the `pipeline` fingerprint (and the
+ * `mediaCollections` fingerprint, which filters collections by their linked
+ * series' ephemeral state) via a sentinel key, so the checksum cache invalidates
+ * on a DB edit just as it did on a file edit. Under the file backend the dirs
+ * still change too (harmless double-signal).
+ *
+ * Module-level (not per-facade) so dataSync reads ONE monotonic counter
+ * regardless of how many times the series/issues facades are rebuilt (test
+ * PATHS.data swaps). Series AND issues share the one counter because dataSync's
+ * `pipeline` category covers both record kinds together — any pipeline mutation
+ * must invalidate that one checksum.
+ */
+
+let pipelineEpoch = 0;
+
+/** Current pipeline mutation epoch — folded into dataSync's fingerprint. */
+export function getPipelineMutationEpoch() {
+ return pipelineEpoch;
+}
+
+/** Bump the epoch — called by the series/issues stores on every record write/delete. */
+export function bumpPipelineMutationEpoch() {
+ pipelineEpoch += 1;
+}