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 Writers Room metadata to PostgreSQL (#1017)

Adam Eivy89228b1ab9b7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 949d90bf49..2f901c6002 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,6 +24,7 @@
- **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.
- **Story Builder sessions now store in PostgreSQL** — the guided Story Builder's session records (the per-step lock/integrity state, the cross-machine staleness baseline, your current step, and the saved provider/model picker choice) moved out of the per-record `data/story-builder/{id}/index.json` files into a dedicated `story_builder_sessions` table, one row per session. The two links every session carries — its universe and its series — are promoted to indexed columns, and the OPT-IN cross-machine resume flag (`sync`) is promoted too so the federation snapshot loop can find the sync-enabled sessions without deserializing every session's body. Existing installs are migrated automatically and losslessly on first boot — the legacy `data/story-builder/` directory is renamed aside (`data/story-builder.imported`) as a one-release recovery source. Nothing changes in how you create, run, lock, reconcile, or sync sessions: the Story Builder UI and the opt-in cross-machine resume wire format are unchanged (no schema-version bump — the sync payload is storage-independent, so a machine on this version syncs sessions cleanly with a peer still on the old file storage). This is the third implementation slice (#1016) of the Create relational-schema migration designed in #999, building on the Universes (#1014) and Pipeline (#1015) slices. Sessions still persist to the per-record file store under the `MEMORY_BACKEND=file` dev/test escape hatch.
+- **Writers Room metadata now stores in PostgreSQL** — the Writers Room library's metadata — folders, work manifests, draft-version history, and writing-sprint exercises — moved out of the bespoke `data/writers-room/` file layout (`folders.json`, `exercises.json`, per-work `manifest.json`) into dedicated `writers_room_folders`, `writers_room_works`, `writers_room_draft_versions`, and `writers_room_exercises` tables. Each work's draft *versions* are decomposed into their own rows (one per version) so the library and future staleness analysis can query word counts, hashes, and lineage directly, while the **draft prose bodies stay on disk** as `.md` files (`data/writers-room/works/<id>/drafts/<draftId>.md`) — only their metadata is indexed in the database. Existing installs are migrated automatically and losslessly on first boot: the JSON metadata files are renamed aside (`*.imported.json`) as a one-release recovery source, and the `.md` bodies are left exactly where they are. Nothing changes in how you create, edit, version, delete, or run exercises on your works — the Writers Room UI is unchanged. (Writers Room is single-machine and not federated, so there's no wire-format or schema-version change.) This is the fourth implementation slice (#1017) of the Create relational-schema migration designed in #999, building on the Universes (#1014), Pipeline (#1015), and Story Builder (#1016) slices. The library still persists to the legacy file layout 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 9ba1ebf06d..69d61dc485 100644
--- a/server/index.js
+++ b/server/index.js
@@ -163,6 +163,7 @@ import { universeStore } from './services/universeBuilder.js';
import { seriesStore } from './services/pipeline/series.js';
import { issueStore } from './services/pipeline/issues.js';
import { storyBuilderStore } from './services/storyBuilder.js';
+import { writersRoomStore } from './services/writersRoom/store.js';
import { mediaCollectionStore } from './services/mediaCollections.js';
import { createPortOSProviderRoutes } from './routes/providers.js';
import { createPortOSRunsRoutes } from './routes/runs.js';
@@ -864,6 +865,12 @@ ensureSelf()
// request/sync sees migrated sessions. Universe + series warmed first
// (sessions soft-ref both for the staleness recompute / linked-record view).
await storyBuilderStore().listIds();
+ // Writers Room PG warm (#1017): same contract — touch the store so it
+ // selects Postgres and runs its one-time file→DB import
+ // (migrateWritersRoomToDB) BEFORE httpServer.listen. listWorkIds() is the
+ // cheapest call that forces backend selection. The draft .md bodies stay on
+ // disk (file-primary); only the metadata migrates. Idempotent (marker-gated).
+ await writersRoomStore().listWorkIds();
// 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 e1f9f6b87f..c270b63f87 100644
--- a/server/lib/db.catalogDdlParity.test.js
+++ b/server/lib/db.catalogDdlParity.test.js
@@ -275,6 +275,28 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {
expect(sqlIdx.size).toBeGreaterThan(0);
});
+ // Writers Room (#1017) — four tables, each its own column + index parity
+ // assertion (distinct idx_wr_<table>_ prefixes keep them isolated).
+ for (const { table, idxPrefix } of [
+ { table: 'writers_room_folders', idxPrefix: 'idx_wr_folders_' },
+ { table: 'writers_room_works', idxPrefix: 'idx_wr_works_' },
+ { table: 'writers_room_draft_versions', idxPrefix: 'idx_wr_drafts_' },
+ { table: 'writers_room_exercises', idxPrefix: 'idx_wr_exercises_' },
+ ]) {
+ it(`${table} has the same columns and indexes in both files`, () => {
+ const sqlBody = extractCreateTable(INIT_SQL, table);
+ const jsBody = extractCreateTable(DB_JS, table);
+ expect(sqlBody, `init-db.sql missing CREATE TABLE ${table}`).toBeTruthy();
+ expect(jsBody, `db.js missing CREATE TABLE ${table}`).toBeTruthy();
+ expect([...new Set(extractColumnNames(sqlBody))].sort())
+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());
+ const sqlIdx = extractIndexNames(INIT_SQL, idxPrefix);
+ const jsIdx = extractIndexNames(DB_JS, idxPrefix);
+ 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 6ee7163935..426e6aa217 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -715,6 +715,91 @@ async function ensureSchemaImpl() {
`CREATE INDEX IF NOT EXISTS idx_stb_universe ON story_builder_sessions (universe_id)`,
`CREATE INDEX IF NOT EXISTS idx_stb_series ON story_builder_sessions (series_id)`,
`CREATE INDEX IF NOT EXISTS idx_stb_updated ON story_builder_sessions (updated_at)`,
+
+ // Writers Room (Phase 3 Create migration, issue #1017). FOUR tables replace
+ // the bespoke file layout (folders.json, exercises.json, per-work
+ // manifest.json). Writers Room is NOT federated — it has no dataSync category
+ // and no schema-version gate — so unlike the universe/pipeline/story-builder
+ // tables these carry NO `ephemeral`/`sync`/sync_sequence columns and need no
+ // mutation epoch. The only thing that stays on disk is the draft prose body
+ // (drafts/<draftId>.md, file-primary); its metadata is the draft_versions row.
+
+ // Folder tree. Self-ref parent_id (soft, no FK — nested tree). sort_order +
+ // name promoted (the library renders the tree ordered by them). Mirrors
+ // init-db.sql.
+ `CREATE TABLE IF NOT EXISTS writers_room_folders (
+ id TEXT PRIMARY KEY,
+ parent_id TEXT,
+ name TEXT NOT NULL,
+ sort_order INTEGER DEFAULT 0,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_wr_folders_parent ON writers_room_folders (parent_id, sort_order)`,
+
+ // Work manifests. The drafts[] array moves OUT of `data` into
+ // writers_room_draft_versions (the one decomposition — draft versions are a
+ // genuine 1-to-many the library + Phase-5 staleness analysis query). imageStyle
+ // / liveMode / usage counters stay in `data`. `folder_id`, `title`, `kind`,
+ // `status`, the promote/bridge links, and `active_draft_version_id` are
+ // promoted for the library list + the resolver (#1018) + the bridge CTAs.
+ // SOFT-DELETE added here (`deleted`/`deleted_at`): the file backend hard-deletes
+ // via rm -rf; the DB backend aligns with the other stores (import sets
+ // deleted = FALSE for all existing works). Soft ref everywhere — no FK.
+ // Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS writers_room_works (
+ id TEXT PRIMARY KEY,
+ folder_id TEXT,
+ title TEXT NOT NULL,
+ kind VARCHAR(32),
+ status VARCHAR(32),
+ active_draft_version_id TEXT,
+ pipeline_series_id TEXT,
+ pipeline_issue_id TEXT,
+ cd_project_id TEXT,
+ media_collection_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_wr_works_folder ON writers_room_works (folder_id) WHERE deleted = FALSE`,
+ `CREATE INDEX IF NOT EXISTS idx_wr_works_series ON writers_room_works (pipeline_series_id) WHERE pipeline_series_id IS NOT NULL`,
+
+ // Draft-version metadata index (file-primary bodies). The .md body stays on
+ // disk at data/writers-room/works/<workId>/drafts/<draftId>.md; this row is
+ // the queryable index over it: `content_file` (relative path), `content_hash`
+ // (sha256 for staleness), `word_count`, `segment_index` (outline), version
+ // lineage. asset-file-db-indexed pattern applied to prose. Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS writers_room_draft_versions (
+ id TEXT PRIMARY KEY,
+ work_id TEXT NOT NULL,
+ label TEXT,
+ content_file TEXT NOT NULL,
+ content_hash TEXT,
+ word_count INTEGER DEFAULT 0,
+ segment_index JSONB NOT NULL DEFAULT '[]'::jsonb,
+ created_from_version_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_wr_drafts_work ON writers_room_draft_versions (work_id, created_at)`,
+
+ // Exercise sessions (sprint timer). Monolithic exercises.json → flat table.
+ // `work_id`, `status`, started_at promoted for the per-work list (ordered by
+ // started_at DESC). prompt/durations/word counts/appendedText stay in `data`.
+ // Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS writers_room_exercises (
+ id TEXT PRIMARY KEY,
+ work_id TEXT,
+ status VARCHAR(16),
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ started_at TIMESTAMPTZ,
+ finished_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_wr_exercises_work ON writers_room_exercises (work_id, started_at DESC)`,
];
for (const sql of catalogDDL) {
await pool.query(sql);
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index c182f6798f..7b3b7ca4c5 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -762,3 +762,66 @@ CREATE TABLE IF NOT EXISTS story_builder_sessions (
CREATE INDEX IF NOT EXISTS idx_stb_universe ON story_builder_sessions (universe_id);
CREATE INDEX IF NOT EXISTS idx_stb_series ON story_builder_sessions (series_id);
CREATE INDEX IF NOT EXISTS idx_stb_updated ON story_builder_sessions (updated_at);
+
+-- Writers Room (Phase 3 Create migration, issue #1017). FOUR tables replace the
+-- bespoke file layout (folders.json, exercises.json, per-work manifest.json).
+-- Writers Room is NOT federated (no dataSync category, no schema-version gate),
+-- so unlike the universe/pipeline/story-builder tables these carry NO
+-- `ephemeral`/`sync`/sync_sequence columns. The only thing that stays on disk is
+-- the draft prose body (drafts/<draftId>.md, file-primary); its metadata is the
+-- draft_versions row.
+-- Mirrors the writers_room_* blocks in db.js ensureSchema().
+CREATE TABLE IF NOT EXISTS writers_room_folders (
+ id TEXT PRIMARY KEY,
+ parent_id TEXT,
+ name TEXT NOT NULL,
+ sort_order INTEGER DEFAULT 0,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+);
+CREATE INDEX IF NOT EXISTS idx_wr_folders_parent ON writers_room_folders (parent_id, sort_order);
+
+CREATE TABLE IF NOT EXISTS writers_room_works (
+ id TEXT PRIMARY KEY,
+ folder_id TEXT,
+ title TEXT NOT NULL,
+ kind VARCHAR(32),
+ status VARCHAR(32),
+ active_draft_version_id TEXT,
+ pipeline_series_id TEXT,
+ pipeline_issue_id TEXT,
+ cd_project_id TEXT,
+ media_collection_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+);
+CREATE INDEX IF NOT EXISTS idx_wr_works_folder ON writers_room_works (folder_id) WHERE deleted = FALSE;
+CREATE INDEX IF NOT EXISTS idx_wr_works_series ON writers_room_works (pipeline_series_id) WHERE pipeline_series_id IS NOT NULL;
+
+CREATE TABLE IF NOT EXISTS writers_room_draft_versions (
+ id TEXT PRIMARY KEY,
+ work_id TEXT NOT NULL,
+ label TEXT,
+ content_file TEXT NOT NULL,
+ content_hash TEXT,
+ word_count INTEGER DEFAULT 0,
+ segment_index JSONB NOT NULL DEFAULT '[]'::jsonb,
+ created_from_version_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+);
+CREATE INDEX IF NOT EXISTS idx_wr_drafts_work ON writers_room_draft_versions (work_id, created_at);
+
+CREATE TABLE IF NOT EXISTS writers_room_exercises (
+ id TEXT PRIMARY KEY,
+ work_id TEXT,
+ status VARCHAR(16),
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ started_at TIMESTAMPTZ,
+ finished_at TIMESTAMPTZ
+);
+CREATE INDEX IF NOT EXISTS idx_wr_exercises_work ON writers_room_exercises (work_id, started_at DESC);
diff --git a/server/scripts/migrateWritersRoomToDB.js b/server/scripts/migrateWritersRoomToDB.js
new file mode 100644
index 0000000000..8be663d7d9
--- /dev/null
+++ b/server/scripts/migrateWritersRoomToDB.js
@@ -0,0 +1,217 @@
+/**
+ * One-time importer: the bespoke data/writers-room file layout → PostgreSQL
+ * (writers_room_folders / writers_room_works / writers_room_draft_versions /
+ * writers_room_exercises), for Phase 3 Create / issue #1017.
+ *
+ * Writers Room metadata used to live in:
+ * folders.json → writers_room_folders rows
+ * exercises.json → writers_room_exercises rows
+ * works/<id>/manifest.json → writers_room_works row + the
+ * manifest's drafts[] decomposed into
+ * writers_room_draft_versions rows
+ *
+ * UNLIKE the universe / story-builder importers, the legacy dir is NOT renamed
+ * aside: the draft PROSE BODIES (works/<id>/drafts/<draftId>.md) are
+ * file-primary and STAY where local.js reads them. So this importer parks aside
+ * only the JSON METADATA files (folders.json → folders.imported.json,
+ * exercises.json → exercises.imported.json, each manifest.json →
+ * manifest.imported.json) as a recovery source, leaving the .md bodies in place.
+ *
+ * Idempotency / safety (mirrors migrateStoryBuilderToDB):
+ * - Marker-gated in data/writers-room.migrated.json so the walk runs once.
+ * - INSERT … ON CONFLICT (id) DO NOTHING — never clobbers an existing row.
+ * - LOSSLESS: folders/exercises copied verbatim into `data`; a work's manifest
+ * (minus drafts[]) into the work row's `data`, each draft entry verbatim
+ * into a draft-version row's `data`.
+ * - The JSON files are renamed aside only AFTER all rows land; the marker is
+ * written only after that — a crash mid-import leaves the files → 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, safeJSONParse } from '../lib/fileUtils.js';
+import { query } from '../lib/db.js';
+import { mirrorTimestamp } from '../lib/pgTimestamp.js';
+
+const ROOT_DIRNAME = 'writers-room';
+const MARKER_FILENAME = 'writers-room.migrated.json';
+const WORK_ID_RE = /^wr-work-[0-9a-f-]+$/i;
+
+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');
+}
+
+// Rename a file aside (path → path.replace('.json','.imported.json')) if it
+// exists; a missing file is a no-op. Never overwrites an existing recovery copy.
+async function parkFileAside(path) {
+ const exists = await stat(path).catch(() => null);
+ if (!exists) return;
+ const aside = path.replace(/\.json$/, '.imported.json');
+ const asideExists = await stat(aside).catch(() => null);
+ if (asideExists) return; // recovery copy already present — don't clobber
+ await rename(path, aside).catch((err) => {
+ console.warn(`⚠️ writers-room→DB import: could not park ${path} aside (${err.message})`);
+ });
+}
+
+async function importFolder(folder) {
+ if (!folder || typeof folder.id !== 'string' || !folder.id) return false;
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(folder.createdAt, now);
+ const result = await query(
+ `INSERT INTO writers_room_folders (id, parent_id, name, sort_order, data, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)
+ ON CONFLICT (id) DO NOTHING`,
+ [
+ folder.id,
+ typeof folder.parentId === 'string' && folder.parentId ? folder.parentId : null,
+ String(folder.name ?? ''),
+ Number.isInteger(folder.sortOrder) ? folder.sortOrder : 0,
+ JSON.stringify(folder),
+ createdAt,
+ mirrorTimestamp(folder.updatedAt, createdAt),
+ ],
+ );
+ return result.rowCount > 0;
+}
+
+async function importExercise(exercise) {
+ if (!exercise || typeof exercise.id !== 'string' || !exercise.id) return false;
+ const result = await query(
+ `INSERT INTO writers_room_exercises (id, work_id, status, data, started_at, finished_at)
+ VALUES ($1, $2, $3, $4::jsonb, $5, $6)
+ ON CONFLICT (id) DO NOTHING`,
+ [
+ exercise.id,
+ typeof exercise.workId === 'string' && exercise.workId ? exercise.workId : null,
+ typeof exercise.status === 'string' ? exercise.status.slice(0, 16) : null,
+ JSON.stringify(exercise),
+ mirrorTimestamp(exercise.startedAt, null),
+ mirrorTimestamp(exercise.finishedAt, null),
+ ],
+ );
+ return result.rowCount > 0;
+}
+
+// A work manifest → one work row (manifest minus drafts[]) + one draft-version
+// row per draft entry. All existing works import as deleted = FALSE.
+async function importWork(manifest) {
+ if (!manifest || typeof manifest.id !== 'string' || !manifest.id) return false;
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(manifest.createdAt, now);
+ const { drafts: draftList, ...workData } = manifest;
+ const drafts = Array.isArray(draftList) ? draftList : [];
+ const result = await query(
+ `INSERT INTO writers_room_works
+ (id, folder_id, title, kind, status, active_draft_version_id,
+ pipeline_series_id, pipeline_issue_id, cd_project_id, media_collection_id,
+ data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::jsonb,$12,$13,FALSE,NULL)
+ ON CONFLICT (id) DO NOTHING`,
+ [
+ manifest.id,
+ typeof manifest.folderId === 'string' && manifest.folderId ? manifest.folderId : null,
+ String(manifest.title ?? ''),
+ typeof manifest.kind === 'string' ? manifest.kind.slice(0, 32) : null,
+ typeof manifest.status === 'string' ? manifest.status.slice(0, 32) : null,
+ typeof manifest.activeDraftVersionId === 'string' ? manifest.activeDraftVersionId : null,
+ typeof manifest.pipelineSeriesId === 'string' ? manifest.pipelineSeriesId : null,
+ typeof manifest.pipelineIssueId === 'string' ? manifest.pipelineIssueId : null,
+ typeof manifest.cdProjectId === 'string' ? manifest.cdProjectId : null,
+ typeof manifest.mediaCollectionId === 'string' ? manifest.mediaCollectionId : null,
+ JSON.stringify(workData),
+ createdAt,
+ mirrorTimestamp(manifest.updatedAt, createdAt),
+ ],
+ );
+ for (const draft of drafts) {
+ if (!draft || typeof draft.id !== 'string') continue;
+ await query(
+ `INSERT INTO writers_room_draft_versions
+ (id, work_id, label, content_file, content_hash, word_count,
+ segment_index, created_from_version_id, data, created_at)
+ VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9::jsonb,$10)
+ ON CONFLICT (id) DO NOTHING`,
+ [
+ draft.id,
+ manifest.id,
+ typeof draft.label === 'string' ? draft.label : null,
+ String(draft.contentFile ?? ''),
+ typeof draft.contentHash === 'string' ? draft.contentHash : null,
+ Number.isInteger(draft.wordCount) ? draft.wordCount : 0,
+ JSON.stringify(Array.isArray(draft.segmentIndex) ? draft.segmentIndex : []),
+ typeof draft.createdFromVersionId === 'string' ? draft.createdFromVersionId : null,
+ JSON.stringify(draft),
+ mirrorTimestamp(draft.createdAt, createdAt),
+ ],
+ );
+ }
+ return result.rowCount > 0;
+}
+
+export async function migrateWritersRoomToDB() {
+ if (await markerExists()) return { ok: true, reason: 'already-applied' };
+
+ const root = join(PATHS.data, ROOT_DIRNAME);
+ const rootStat = await stat(root).catch(() => null);
+
+ // Fresh install (no legacy dir): no-op WITHOUT stamping the marker (keeps the
+ // recovery escape hatch open — see migrateStoryBuilderToDB).
+ if (!rootStat || !rootStat.isDirectory()) {
+ return { ok: true, reason: 'fresh-install', folders: 0, works: 0, exercises: 0 };
+ }
+
+ // Folders.
+ const foldersFile = join(root, 'folders.json');
+ const folders = await readJSONFile(foldersFile, []);
+ let folderCount = 0;
+ for (const f of Array.isArray(folders) ? folders : []) {
+ if (await importFolder(f)) folderCount += 1;
+ }
+
+ // Exercises.
+ const exercisesFile = join(root, 'exercises.json');
+ const exercises = await readJSONFile(exercisesFile, []);
+ let exerciseCount = 0;
+ for (const e of Array.isArray(exercises) ? exercises : []) {
+ if (await importExercise(e)) exerciseCount += 1;
+ }
+
+ // Works (manifest.json per work dir; .md bodies stay in place).
+ const worksDir = join(root, 'works');
+ const worksStat = await stat(worksDir).catch(() => null);
+ const workEntries = worksStat?.isDirectory()
+ ? await readdir(worksDir, { withFileTypes: true }).catch(() => [])
+ : [];
+ let workCount = 0;
+ const importedManifestPaths = [];
+ for (const entry of workEntries) {
+ if (!entry.isDirectory() || !WORK_ID_RE.test(entry.name)) continue;
+ const manifestPath = join(worksDir, entry.name, 'manifest.json');
+ const content = await readFile(manifestPath, 'utf-8').catch(() => null);
+ if (content === null) continue;
+ const manifest = safeJSONParse(content, null, { allowArray: false, logError: true, context: manifestPath });
+ if (!manifest) continue; // corrupted manifest — skip, leave on disk untouched
+ if (await importWork(manifest)) workCount += 1;
+ importedManifestPaths.push(manifestPath);
+ }
+
+ // Park the JSON metadata files aside (the .md bodies stay put). Only after all
+ // rows have landed, so a crash before this leaves a clean retry.
+ await parkFileAside(foldersFile);
+ await parkFileAside(exercisesFile);
+ for (const p of importedManifestPaths) await parkFileAside(p);
+
+ await writeMarker({
+ migratedAt: new Date().toISOString(),
+ folders: folderCount, works: workCount, exercises: exerciseCount, reason: 'imported',
+ });
+ console.log(`✍️ writers-room→DB import: ${folderCount} folder(s), ${workCount} work(s), ${exerciseCount} exercise(s); .md bodies left in place`);
+ return { ok: true, reason: 'imported', folders: folderCount, works: workCount, exercises: exerciseCount };
+}
diff --git a/server/scripts/migrateWritersRoomToDB.test.js b/server/scripts/migrateWritersRoomToDB.test.js
new file mode 100644
index 0000000000..e11fad8dca
--- /dev/null
+++ b/server/scripts/migrateWritersRoomToDB.test.js
@@ -0,0 +1,183 @@
+/**
+ * Tests for the legacy data/writers-room file layout → Postgres importer
+ * (#1017). Disk + PG are mocked. The key differences from the other importers:
+ * - The .md draft bodies are file-primary and must NOT be parked aside — only
+ * the JSON metadata files (folders.json, exercises.json, each manifest.json)
+ * are renamed to *.imported.json.
+ * - A work manifest's drafts[] decomposes into draft-version rows.
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const DATA = '/fake/data';
+const ROOT = `${DATA}/writers-room`;
+const WORKS = `${ROOT}/works`;
+const MARKER = `${DATA}/writers-room.migrated.json`;
+
+let files = {}; // path -> string content (for readFile/writeFile)
+let jsonByPath = {}; // path -> parsed value (for readJSONFile)
+let workDirs = []; // entries under works/
+let existingDirs = new Set();
+let renamed = [];
+
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { data: DATA },
+ readJSONFile: vi.fn(async (path, fallback) => (path in jsonByPath ? jsonByPath[path] : fallback)),
+ safeJSONParse: vi.fn((content, fallback) => { try { return JSON.parse(content); } catch { return fallback; } }),
+}));
+
+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]); files[to] = files[from]; delete files[from]; }),
+ readdir: vi.fn(async (path) => {
+ if (path === WORKS) return workDirs;
+ return [];
+ }),
+ stat: vi.fn(async (path) => {
+ if (path === ROOT || path === WORKS) {
+ if (existingDirs.has(path)) return { isDirectory: () => true };
+ const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e;
+ }
+ // For parkFileAside existence checks: the source exists if it's in `files`,
+ // the .imported.json aside does not (unless renamed already).
+ if (path in files) return { isFile: () => true };
+ const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e;
+ }),
+}));
+
+const folders = new Map();
+const works = new Map();
+const drafts = new Map();
+const exercises = new Map();
+
+const query = vi.fn(async (sql, params) => {
+ if (/INSERT INTO writers_room_folders/.test(sql)) {
+ const id = params[0];
+ if (folders.has(id)) return { rowCount: 0, rows: [] };
+ folders.set(id, { id, parentId: params[1], name: params[2], sortOrder: params[3], data: JSON.parse(params[4]) });
+ return { rowCount: 1, rows: [] };
+ }
+ if (/INSERT INTO writers_room_works/.test(sql)) {
+ const id = params[0];
+ if (works.has(id)) return { rowCount: 0, rows: [] };
+ works.set(id, { id, folderId: params[1], title: params[2], pipelineSeriesId: params[6], data: JSON.parse(params[10]) });
+ return { rowCount: 1, rows: [] };
+ }
+ if (/INSERT INTO writers_room_draft_versions/.test(sql)) {
+ const id = params[0];
+ if (drafts.has(id)) return { rowCount: 0, rows: [] };
+ drafts.set(id, { id, workId: params[1], contentFile: params[3], data: JSON.parse(params[8]) });
+ return { rowCount: 1, rows: [] };
+ }
+ if (/INSERT INTO writers_room_exercises/.test(sql)) {
+ const id = params[0];
+ if (exercises.has(id)) return { rowCount: 0, rows: [] };
+ exercises.set(id, { id, workId: params[1], status: params[2], data: JSON.parse(params[3]) });
+ return { rowCount: 1, rows: [] };
+ }
+ return { rowCount: 0, rows: [] };
+});
+vi.mock('../lib/db.js', () => ({ query: (...a) => query(...a) }));
+
+const draft = (id) => ({ id, label: 'D', contentFile: `drafts/${id}.md`, contentHash: 'h', wordCount: 1, segmentIndex: [], createdAt: '2026-01-01T00:00:00.000Z' });
+const manifest = (id, extra = {}) => ({ id, title: id, kind: 'short-story', status: 'drafting', activeDraftVersionId: 'wr-draft-a', drafts: [draft('wr-draft-a')], createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-02T00:00:00.000Z', ...extra });
+
+async function importer() {
+ const { migrateWritersRoomToDB } = await import('./migrateWritersRoomToDB.js');
+ return migrateWritersRoomToDB();
+}
+
+beforeEach(() => {
+ files = {};
+ jsonByPath = {};
+ workDirs = [];
+ existingDirs = new Set();
+ renamed = [];
+ folders.clear(); works.clear(); drafts.clear(); exercises.clear();
+ query.mockClear();
+});
+
+describe('migrateWritersRoomToDB', () => {
+ it('fresh install (no writers-room dir): no-op WITHOUT a marker', async () => {
+ const result = await importer();
+ expect(result).toMatchObject({ ok: true, reason: 'fresh-install' });
+ expect(MARKER in files).toBe(false);
+ });
+
+ it('marker already present: no-op', async () => {
+ files[MARKER] = JSON.stringify({ reason: 'imported' });
+ existingDirs.add(ROOT);
+ jsonByPath[`${ROOT}/folders.json`] = [{ id: 'wr-folder-1', name: 'X' }];
+ const result = await importer();
+ expect(result).toMatchObject({ reason: 'already-applied' });
+ expect(folders.size).toBe(0);
+ });
+
+ it('imports folders, works (+ decomposed drafts), exercises; parks ONLY JSON aside', async () => {
+ existingDirs.add(ROOT);
+ existingDirs.add(WORKS);
+ jsonByPath[`${ROOT}/folders.json`] = [{ id: 'wr-folder-1', name: 'Novels', sortOrder: 1, createdAt: '2026-01-01T00:00:00.000Z' }];
+ jsonByPath[`${ROOT}/exercises.json`] = [{ id: 'wr-ex-1', workId: 'wr-work-1', status: 'finished', startedAt: '2026-01-01T00:00:00.000Z' }];
+ files[`${ROOT}/folders.json`] = '[]';
+ files[`${ROOT}/exercises.json`] = '[]';
+ workDirs = [
+ { name: 'wr-work-1', isDirectory: () => true },
+ { name: '.DS_Store', isDirectory: () => false },
+ ];
+ files[`${WORKS}/wr-work-1/manifest.json`] = JSON.stringify(manifest('wr-work-1', {
+ pipelineSeriesId: 'ser-1',
+ drafts: [draft('wr-draft-a'), draft('wr-draft-b')],
+ }));
+
+ const result = await importer();
+ expect(result).toMatchObject({ ok: true, reason: 'imported', folders: 1, works: 1, exercises: 1 });
+
+ // Rows landed.
+ expect(folders.get('wr-folder-1').name).toBe('Novels');
+ expect(exercises.get('wr-ex-1').status).toBe('finished');
+ expect(works.get('wr-work-1').pipelineSeriesId).toBe('ser-1'); // mirror column
+ expect(works.get('wr-work-1').data.drafts).toBeUndefined(); // drafts[] stripped from work row
+ expect([...drafts.keys()].sort()).toEqual(['wr-draft-a', 'wr-draft-b']); // decomposed
+
+ // ONLY the JSON metadata is parked aside — never the .md bodies.
+ const renamedFrom = renamed.map(([from]) => from);
+ expect(renamedFrom).toContain(`${ROOT}/folders.json`);
+ expect(renamedFrom).toContain(`${ROOT}/exercises.json`);
+ expect(renamedFrom).toContain(`${WORKS}/wr-work-1/manifest.json`);
+ expect(renamed.every(([from]) => from.endsWith('.json'))).toBe(true);
+ expect(renamed.some(([from]) => from.endsWith('.md'))).toBe(false);
+
+ expect(MARKER in files).toBe(true);
+ });
+
+ it('skips a corrupted manifest (leaves it on disk), still imports the rest', async () => {
+ existingDirs.add(ROOT);
+ existingDirs.add(WORKS);
+ workDirs = [
+ { name: 'wr-work-aaa', isDirectory: () => true },
+ { name: 'wr-work-bbb', isDirectory: () => true },
+ ];
+ files[`${WORKS}/wr-work-aaa/manifest.json`] = JSON.stringify(manifest('wr-work-aaa'));
+ files[`${WORKS}/wr-work-bbb/manifest.json`] = '{ not valid json';
+ const result = await importer();
+ expect(result.works).toBe(1);
+ expect(works.has('wr-work-aaa')).toBe(true);
+ expect(works.has('wr-work-bbb')).toBe(false);
+ // The corrupted manifest is NOT parked aside.
+ expect(renamed.some(([from]) => from === `${WORKS}/wr-work-bbb/manifest.json`)).toBe(false);
+ });
+
+ it('re-import is idempotent (ON CONFLICT DO NOTHING)', async () => {
+ works.set('wr-work-1', { id: 'wr-work-1' }); // pretend already imported
+ existingDirs.add(ROOT);
+ existingDirs.add(WORKS);
+ workDirs = [{ name: 'wr-work-1', isDirectory: () => true }];
+ files[`${WORKS}/wr-work-1/manifest.json`] = JSON.stringify(manifest('wr-work-1'));
+ const result = await importer();
+ expect(result.works).toBe(0); // conflict → not counted as newly imported
+ });
+});
diff --git a/server/services/writersRoom/_shared.js b/server/services/writersRoom/_shared.js
index 05c4f37b82..12e10bb14f 100644
--- a/server/services/writersRoom/_shared.js
+++ b/server/services/writersRoom/_shared.js
@@ -3,7 +3,9 @@
// shorthands plus the work-id shape check; duplicating them turned into
// byte-for-byte drift risk.
+import { join } from 'path';
import { ServerError } from '../../lib/errorHandler.js';
+import { PATHS } from '../../lib/fileUtils.js';
export const nowIso = () => new Date().toISOString();
export const badRequest = (message) => new ServerError(message, { status: 400, code: 'VALIDATION_ERROR' });
@@ -19,3 +21,24 @@ export const assertValidWorkId = (workId) => {
throw badRequest('Invalid work id');
}
};
+
+export const DRAFT_ID_RE = /^wr-draft-[0-9a-f-]+$/i;
+
+// On-disk path helpers. Resolved lazily (functions, not consts) so tests can
+// swap PATHS.data via vi.mock without the module-load snapshot freezing them at
+// import time. The DRAFT .md bodies live under works/<id>/drafts/ regardless of
+// storage backend (file-primary) — local.js owns them; the file backend's JSON
+// metadata files (folders.json, exercises.json, manifest.json) live alongside.
+export const wrRoot = () => join(PATHS.data, 'writers-room');
+export const wrFoldersFile = () => join(wrRoot(), 'folders.json');
+export const wrExercisesFile = () => join(wrRoot(), 'exercises.json');
+export const wrWorksDir = () => join(wrRoot(), 'works');
+export const wrWorkDir = (workId) => {
+ assertValidWorkId(workId);
+ return join(wrWorksDir(), workId);
+};
+export const wrManifestPath = (workId) => join(wrWorkDir(workId), 'manifest.json');
+export const wrDraftPath = (workId, draftId) => {
+ if (!DRAFT_ID_RE.test(draftId)) throw badRequest('Invalid draft id');
+ return join(wrWorkDir(workId), 'drafts', `${draftId}.md`);
+};
diff --git a/server/services/writersRoom/db.js b/server/services/writersRoom/db.js
new file mode 100644
index 0000000000..84178b5ec8
--- /dev/null
+++ b/server/services/writersRoom/db.js
@@ -0,0 +1,285 @@
+/**
+ * Writers Room — PostgreSQL leaf I/O (#1017).
+ *
+ * Four tables replace the bespoke file layout:
+ * writers_room_folders ← folders.json
+ * writers_room_works ← works/<id>/manifest.json (minus drafts[])
+ * writers_room_draft_versions ← the manifest's drafts[] array (decomposed)
+ * writers_room_exercises ← exercises.json
+ *
+ * The draft PROSE BODY stays on disk at works/<id>/drafts/<draftId>.md
+ * (file-primary) — only its metadata (hash, word count, segment index, lineage)
+ * becomes a row here. local.js still owns the .md read/write; this module is the
+ * metadata index over them.
+ *
+ * PURE leaf I/O — no sanitizing, no path logic, no .md access. The store facade
+ * (store.js) selects this backend; local.js reassembles a manifest (work row +
+ * its draft rows → the manifest shape with an embedded drafts[]) on read and
+ * splits it on write, so its public API is unchanged.
+ *
+ * The `data` JSONB on every table holds the FULL lossless record; the typed
+ * columns are a queryable mirror (never read back into the record). Writers Room
+ * is NOT federated, so there is no ephemeral/sync column and no mutation epoch.
+ */
+
+import { query, withTransaction } from '../../lib/db.js';
+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
+
+// ---------- folders ----------
+
+/** Every folder row's `data` JSONB, ordered for the library tree. */
+export async function listFolders() {
+ const { rows } = await query(
+ `SELECT data FROM writers_room_folders ORDER BY sort_order, created_at`,
+ );
+ return rows.map((r) => r.data);
+}
+
+/** Upsert one folder. `created_at` is preserved on conflict. */
+export async function writeFolder(folder) {
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(folder?.createdAt, now);
+ await query(
+ `INSERT INTO writers_room_folders (id, parent_id, name, sort_order, data, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)
+ ON CONFLICT (id) DO UPDATE SET
+ parent_id = EXCLUDED.parent_id,
+ name = EXCLUDED.name,
+ sort_order = EXCLUDED.sort_order,
+ data = EXCLUDED.data,
+ updated_at = EXCLUDED.updated_at`,
+ [
+ folder.id,
+ typeof folder?.parentId === 'string' && folder.parentId ? folder.parentId : null,
+ String(folder?.name ?? ''),
+ Number.isInteger(folder?.sortOrder) ? folder.sortOrder : 0,
+ JSON.stringify(folder),
+ createdAt,
+ mirrorTimestamp(folder?.updatedAt, createdAt),
+ ],
+ );
+}
+
+/** Hard-delete a folder. Idempotent — missing row is a no-op. */
+export async function deleteFolder(id) {
+ await query(`DELETE FROM writers_room_folders WHERE id = $1`, [id]);
+}
+
+// ---------- exercises ----------
+
+/** Every exercise row's `data` JSONB, newest sprint first. */
+export async function listExercises() {
+ const { rows } = await query(
+ `SELECT data FROM writers_room_exercises ORDER BY started_at DESC NULLS LAST`,
+ );
+ return rows.map((r) => r.data);
+}
+
+/** Upsert one exercise session. */
+export async function writeExercise(exercise) {
+ await query(
+ `INSERT INTO writers_room_exercises (id, work_id, status, data, started_at, finished_at)
+ VALUES ($1, $2, $3, $4::jsonb, $5, $6)
+ ON CONFLICT (id) DO UPDATE SET
+ work_id = EXCLUDED.work_id,
+ status = EXCLUDED.status,
+ data = EXCLUDED.data,
+ started_at = EXCLUDED.started_at,
+ finished_at = EXCLUDED.finished_at`,
+ [
+ exercise.id,
+ typeof exercise?.workId === 'string' && exercise.workId ? exercise.workId : null,
+ typeof exercise?.status === 'string' ? exercise.status.slice(0, 16) : null,
+ JSON.stringify(exercise),
+ mirrorTimestamp(exercise?.startedAt, null),
+ mirrorTimestamp(exercise?.finishedAt, null),
+ ],
+ );
+}
+
+// ---------- works + draft versions ----------
+
+/**
+ * Map a work row + its draft rows back to the manifest shape local.js expects:
+ * the full work record from `data` with `drafts[]` rebuilt from the
+ * draft-version rows (ordered by created_at to preserve version lineage order).
+ * Returns null for a missing/soft-deleted work.
+ */
+function rowsToManifest(workRow, draftRows) {
+ if (!workRow) return null;
+ const manifest = { ...workRow.data };
+ manifest.drafts = draftRows.map((d) => d.data);
+ return manifest;
+}
+
+/** One work's manifest (rebuilt from its row + draft rows), or null. */
+export async function readWork(id) {
+ const work = await query(
+ `SELECT data FROM writers_room_works WHERE id = $1 AND deleted = FALSE`,
+ [id],
+ );
+ if (!work.rows[0]) return null;
+ const drafts = await query(
+ `SELECT data FROM writers_room_draft_versions WHERE work_id = $1 ORDER BY created_at, id`,
+ [id],
+ );
+ return rowsToManifest(work.rows[0], drafts.rows);
+}
+
+/** Every live work id (non-deleted). */
+export async function listWorkIds() {
+ const { rows } = await query(
+ `SELECT id FROM writers_room_works WHERE deleted = FALSE`,
+ );
+ return rows.map((r) => r.id);
+}
+
+/** Every live work's manifest, rebuilt with its drafts[] — one pair of queries. */
+export async function listWorks() {
+ const works = await query(
+ `SELECT id, data FROM writers_room_works WHERE deleted = FALSE`,
+ );
+ if (works.rows.length === 0) return [];
+ const drafts = await query(
+ `SELECT work_id, data FROM writers_room_draft_versions
+ WHERE work_id = ANY($1::text[]) ORDER BY created_at, id`,
+ [works.rows.map((r) => r.id)],
+ );
+ const draftsByWork = new Map();
+ for (const d of drafts.rows) {
+ if (!draftsByWork.has(d.work_id)) draftsByWork.set(d.work_id, []);
+ draftsByWork.get(d.work_id).push({ data: d.data });
+ }
+ return works.rows.map((w) => rowsToManifest(w, draftsByWork.get(w.id) || []));
+}
+
+// Bind tuple for one draft-version row from a manifest draft entry.
+function draftBinds(workId, draft) {
+ return [
+ draft.id,
+ workId,
+ typeof draft?.label === 'string' ? draft.label : null,
+ String(draft?.contentFile ?? ''),
+ typeof draft?.contentHash === 'string' ? draft.contentHash : null,
+ Number.isInteger(draft?.wordCount) ? draft.wordCount : 0,
+ JSON.stringify(Array.isArray(draft?.segmentIndex) ? draft.segmentIndex : []),
+ typeof draft?.createdFromVersionId === 'string' ? draft.createdFromVersionId : null,
+ JSON.stringify(draft),
+ mirrorTimestamp(draft?.createdAt, new Date().toISOString()),
+ ];
+}
+
+/**
+ * Upsert a work manifest AND its draft versions atomically. The manifest's
+ * `drafts[]` array is the authoritative version set: we upsert each draft row
+ * and DELETE any draft rows for this work no longer in the array (covers a
+ * version delete). `created_at` is preserved on conflict for both the work and
+ * each draft. Runs in a transaction so a half-written work never leaves orphan
+ * draft rows or a draft set out of sync with the manifest.
+ */
+export async function writeWork(manifest) {
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(manifest?.createdAt, now);
+ const drafts = Array.isArray(manifest?.drafts) ? manifest.drafts : [];
+ // The work row's `data` holds the manifest WITHOUT the drafts[] array — the
+ // draft rows are authoritative, so embedding them too would duplicate (and
+ // risk drifting from) the decomposed source of truth.
+ const { drafts: _omit, ...workData } = manifest;
+ await withTransaction(async (client) => {
+ await client.query(
+ `INSERT INTO writers_room_works
+ (id, folder_id, title, kind, status, active_draft_version_id,
+ pipeline_series_id, pipeline_issue_id, cd_project_id, media_collection_id,
+ data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::jsonb,$12,$13,FALSE,NULL)
+ ON CONFLICT (id) DO UPDATE SET
+ folder_id = EXCLUDED.folder_id,
+ title = EXCLUDED.title,
+ kind = EXCLUDED.kind,
+ status = EXCLUDED.status,
+ active_draft_version_id = EXCLUDED.active_draft_version_id,
+ pipeline_series_id = EXCLUDED.pipeline_series_id,
+ pipeline_issue_id = EXCLUDED.pipeline_issue_id,
+ cd_project_id = EXCLUDED.cd_project_id,
+ media_collection_id = EXCLUDED.media_collection_id,
+ data = EXCLUDED.data,
+ updated_at = EXCLUDED.updated_at,
+ deleted = FALSE,
+ deleted_at = NULL`,
+ [
+ manifest.id,
+ typeof manifest?.folderId === 'string' && manifest.folderId ? manifest.folderId : null,
+ String(manifest?.title ?? ''),
+ typeof manifest?.kind === 'string' ? manifest.kind.slice(0, 32) : null,
+ typeof manifest?.status === 'string' ? manifest.status.slice(0, 32) : null,
+ typeof manifest?.activeDraftVersionId === 'string' ? manifest.activeDraftVersionId : null,
+ typeof manifest?.pipelineSeriesId === 'string' ? manifest.pipelineSeriesId : null,
+ typeof manifest?.pipelineIssueId === 'string' ? manifest.pipelineIssueId : null,
+ typeof manifest?.cdProjectId === 'string' ? manifest.cdProjectId : null,
+ typeof manifest?.mediaCollectionId === 'string' ? manifest.mediaCollectionId : null,
+ JSON.stringify(workData),
+ createdAt,
+ mirrorTimestamp(manifest?.updatedAt, createdAt),
+ ],
+ );
+ for (const draft of drafts) {
+ if (!draft || typeof draft.id !== 'string') continue;
+ await client.query(
+ `INSERT INTO writers_room_draft_versions
+ (id, work_id, label, content_file, content_hash, word_count,
+ segment_index, created_from_version_id, data, created_at)
+ VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9::jsonb,$10)
+ ON CONFLICT (id) DO UPDATE SET
+ work_id = EXCLUDED.work_id,
+ label = EXCLUDED.label,
+ content_file = EXCLUDED.content_file,
+ content_hash = EXCLUDED.content_hash,
+ word_count = EXCLUDED.word_count,
+ segment_index = EXCLUDED.segment_index,
+ created_from_version_id = EXCLUDED.created_from_version_id,
+ data = EXCLUDED.data`,
+ draftBinds(manifest.id, draft),
+ );
+ }
+ // Prune draft rows that are no longer part of the manifest (version delete).
+ const keepIds = drafts.map((d) => d?.id).filter((id) => typeof id === 'string');
+ if (keepIds.length > 0) {
+ await client.query(
+ `DELETE FROM writers_room_draft_versions WHERE work_id = $1 AND id <> ALL($2::text[])`,
+ [manifest.id, keepIds],
+ );
+ } else {
+ await client.query(`DELETE FROM writers_room_draft_versions WHERE work_id = $1`, [manifest.id]);
+ }
+ });
+ return manifest;
+}
+
+/**
+ * Hard-delete a work and its draft rows (the file backend rm -rf's the dir; the
+ * DB backend mirrors that destructive delete rather than tombstoning, since
+ * Writers Room is not federated so there are no peers to propagate a tombstone
+ * to). local.js still rm's the on-disk .md bodies. Idempotent.
+ */
+export async function deleteWork(id) {
+ await withTransaction(async (client) => {
+ await client.query(`DELETE FROM writers_room_draft_versions WHERE work_id = $1`, [id]);
+ await client.query(`DELETE FROM writers_room_works WHERE id = $1`, [id]);
+ });
+}
+
+/**
+ * Every live draft-version row (work_id + the metadata) for the restore-coherence
+ * check — every row's content_file must exist on disk + content_hash must match.
+ */
+export async function listDraftVersionsForCoherence() {
+ const { rows } = await query(
+ `SELECT v.id, v.work_id, v.content_file, v.content_hash
+ FROM writers_room_draft_versions v
+ JOIN writers_room_works w ON w.id = v.work_id AND w.deleted = FALSE
+ ORDER BY v.work_id, v.created_at`,
+ );
+ return rows.map((r) => ({
+ id: r.id, workId: r.work_id, contentFile: r.content_file, contentHash: r.content_hash,
+ }));
+}
diff --git a/server/services/writersRoom/db.test.js b/server/services/writersRoom/db.test.js
new file mode 100644
index 0000000000..efefe5eab0
--- /dev/null
+++ b/server/services/writersRoom/db.test.js
@@ -0,0 +1,187 @@
+/**
+ * Postgres-backed round-trip for the Writers Room DB adapter (#1017). SKIPS
+ * cleanly when no DB is reachable. Snapshots + restores all four tables.
+ *
+ * Covers the one decomposition unique to this slice: a work manifest's drafts[]
+ * array is split into writers_room_draft_versions rows on write and reassembled
+ * into the manifest on read; a version removed from the array prunes its row.
+ */
+
+import { describe, it, expect, afterAll, beforeAll, beforeEach } from 'vitest';
+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
+
+const TABLES = [
+ 'writers_room_folders', 'writers_room_works',
+ 'writers_room_draft_versions', 'writers_room_exercises',
+];
+
+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 = 'writers_room_works') AS ok`,
+ ).catch(() => ({ rows: [{ ok: false }] }));
+ if (probe.rows?.[0]?.ok) dbReady = true;
+ else skipReason = 'writers_room_works table not present';
+ }
+}
+
+if (!dbReady) console.log(`⏭️ writersRoom/db.test.js skipped: ${skipReason}`);
+
+const draft = (id, extra = {}) => ({
+ id, label: 'Draft 1', contentFile: `drafts/${id}.md`, contentHash: 'h'.repeat(64),
+ wordCount: 3, segmentIndex: [{ id: 'seg-001', kind: 'paragraph', heading: '(untitled)', start: 0, end: 10, wordCount: 3 }],
+ createdAt: '2026-01-01T00:00:00.000Z', createdFromVersionId: null, ...extra,
+});
+
+const manifest = (id, extra = {}) => ({
+ id, folderId: null, title: id, kind: 'short-story', status: 'drafting',
+ activeDraftVersionId: 'wr-draft-a', drafts: [draft('wr-draft-a')],
+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-02T00:00:00.000Z', ...extra,
+});
+
+describe.skipIf(!dbReady)('Writers Room DB adapter round-trip', () => {
+ let db;
+ const snaps = {};
+ beforeAll(async () => {
+ db = await import('./db.js');
+ for (const t of TABLES) snaps[t] = (await query(`SELECT * FROM ${t}`)).rows;
+ });
+
+ beforeEach(async () => {
+ for (const t of TABLES) await query(`DELETE FROM ${t}`);
+ });
+
+ afterAll(async () => {
+ for (const t of TABLES) await query(`DELETE FROM ${t}`).catch(() => {});
+ // Restore folders + exercises + works + drafts verbatim from the snapshot.
+ for (const r of snaps.writers_room_folders || []) {
+ await query(
+ `INSERT INTO writers_room_folders (id, parent_id, name, sort_order, data, created_at, updated_at)
+ VALUES ($1,$2,$3,$4,$5::jsonb,$6,$7) ON CONFLICT (id) DO NOTHING`,
+ [r.id, r.parent_id, r.name, r.sort_order, JSON.stringify(r.data), r.created_at, r.updated_at],
+ ).catch(() => {});
+ }
+ for (const r of snaps.writers_room_works || []) {
+ await query(
+ `INSERT INTO writers_room_works (id, folder_id, title, kind, status, active_draft_version_id, pipeline_series_id, pipeline_issue_id, cd_project_id, media_collection_id, data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::jsonb,$12,$13,$14,$15) ON CONFLICT (id) DO NOTHING`,
+ [r.id, r.folder_id, r.title, r.kind, r.status, r.active_draft_version_id, r.pipeline_series_id, r.pipeline_issue_id, r.cd_project_id, r.media_collection_id, JSON.stringify(r.data), r.created_at, r.updated_at, r.deleted, r.deleted_at],
+ ).catch(() => {});
+ }
+ for (const r of snaps.writers_room_draft_versions || []) {
+ await query(
+ `INSERT INTO writers_room_draft_versions (id, work_id, label, content_file, content_hash, word_count, segment_index, created_from_version_id, data, created_at)
+ VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9::jsonb,$10) ON CONFLICT (id) DO NOTHING`,
+ [r.id, r.work_id, r.label, r.content_file, r.content_hash, r.word_count, JSON.stringify(r.segment_index), r.created_from_version_id, JSON.stringify(r.data), r.created_at],
+ ).catch(() => {});
+ }
+ for (const r of snaps.writers_room_exercises || []) {
+ await query(
+ `INSERT INTO writers_room_exercises (id, work_id, status, data, started_at, finished_at)
+ VALUES ($1,$2,$3,$4::jsonb,$5,$6) ON CONFLICT (id) DO NOTHING`,
+ [r.id, r.work_id, r.status, JSON.stringify(r.data), r.started_at, r.finished_at],
+ ).catch(() => {});
+ }
+ await close();
+ });
+
+ it('folder upsert round-trips and mirror columns reflect the body', async () => {
+ await db.writeFolder({ id: 'wr-folder-1', parentId: null, name: 'Novels', sortOrder: 2, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z' });
+ const all = await db.listFolders();
+ expect(all).toHaveLength(1);
+ expect(all[0]).toMatchObject({ id: 'wr-folder-1', name: 'Novels', sortOrder: 2 });
+ const col = (await query(`SELECT name, sort_order FROM writers_room_folders WHERE id = 'wr-folder-1'`)).rows[0];
+ expect(col.name).toBe('Novels');
+ expect(col.sort_order).toBe(2);
+ });
+
+ it('writeWork decomposes drafts[] into rows and readWork reassembles them', async () => {
+ const m = manifest('wr-work-1', {
+ activeDraftVersionId: 'wr-draft-b',
+ drafts: [draft('wr-draft-a'), draft('wr-draft-b', { label: 'Draft 2', createdFromVersionId: 'wr-draft-a' })],
+ });
+ await db.writeWork(m);
+ // The work row's `data` must NOT carry drafts[] (the rows are authoritative).
+ const workData = (await query(`SELECT data FROM writers_room_works WHERE id = 'wr-work-1'`)).rows[0].data;
+ expect(workData.drafts).toBeUndefined();
+ const draftRows = (await query(`SELECT id FROM writers_room_draft_versions WHERE work_id = 'wr-work-1' ORDER BY id`)).rows;
+ expect(draftRows.map((r) => r.id)).toEqual(['wr-draft-a', 'wr-draft-b']);
+ // readWork rebuilds the manifest with drafts[] embedded again.
+ const back = await db.readWork('wr-work-1');
+ expect(back.drafts.map((d) => d.id)).toEqual(['wr-draft-a', 'wr-draft-b']);
+ expect(back.drafts[1].label).toBe('Draft 2');
+ expect(back.title).toBe('wr-work-1');
+ });
+
+ it('removing a version from drafts[] prunes its row on the next write', async () => {
+ await db.writeWork(manifest('wr-work-1', {
+ drafts: [draft('wr-draft-a'), draft('wr-draft-b')],
+ }));
+ await db.writeWork(manifest('wr-work-1', { drafts: [draft('wr-draft-a')] }));
+ const rows = (await query(`SELECT id FROM writers_room_draft_versions WHERE work_id = 'wr-work-1'`)).rows;
+ expect(rows.map((r) => r.id)).toEqual(['wr-draft-a']);
+ });
+
+ it('promote/bridge links + draft metadata mirror into columns', async () => {
+ await db.writeWork(manifest('wr-work-1', {
+ pipelineSeriesId: 'ser-9', cdProjectId: 'cd-9', mediaCollectionId: 'col-9',
+ }));
+ const col = (await query(`SELECT pipeline_series_id, cd_project_id, media_collection_id, active_draft_version_id FROM writers_room_works WHERE id = 'wr-work-1'`)).rows[0];
+ expect(col.pipeline_series_id).toBe('ser-9');
+ expect(col.cd_project_id).toBe('cd-9');
+ expect(col.media_collection_id).toBe('col-9');
+ const dcol = (await query(`SELECT content_hash, word_count FROM writers_room_draft_versions WHERE id = 'wr-draft-a'`)).rows[0];
+ expect(dcol.word_count).toBe(3);
+ expect(dcol.content_hash).toBe('h'.repeat(64));
+ });
+
+ it('listWorks excludes soft-deleted works and rebuilds drafts in one pass', async () => {
+ await db.writeWork(manifest('wr-work-1'));
+ await db.writeWork(manifest('wr-work-2', { drafts: [draft('wr-draft-c')], activeDraftVersionId: 'wr-draft-c' }));
+ await db.deleteWork('wr-work-2'); // hard delete (WR not federated)
+ const works = await db.listWorks();
+ expect(works.map((w) => w.id)).toEqual(['wr-work-1']);
+ expect(works[0].drafts.map((d) => d.id)).toEqual(['wr-draft-a']);
+ expect(await db.readWork('wr-work-2')).toBeNull();
+ // Draft rows for the deleted work are gone too.
+ expect((await query(`SELECT 1 FROM writers_room_draft_versions WHERE work_id = 'wr-work-2'`)).rows).toHaveLength(0);
+ });
+
+ it('exercise upsert round-trips and mirror columns reflect work_id/status', async () => {
+ await db.writeExercise({ id: 'wr-ex-1', workId: 'wr-work-1', status: 'running', prompt: 'go', startedAt: '2026-01-03T00:00:00.000Z', finishedAt: null });
+ await db.writeExercise({ id: 'wr-ex-1', workId: 'wr-work-1', status: 'finished', prompt: 'go', wordsAdded: 50, startedAt: '2026-01-03T00:00:00.000Z', finishedAt: '2026-01-03T01:00:00.000Z' });
+ const all = await db.listExercises();
+ expect(all).toHaveLength(1);
+ expect(all[0].status).toBe('finished');
+ expect(all[0].wordsAdded).toBe(50);
+ const col = (await query(`SELECT status, work_id FROM writers_room_exercises WHERE id = 'wr-ex-1'`)).rows[0];
+ expect(col.status).toBe('finished');
+ expect(col.work_id).toBe('wr-work-1');
+ });
+
+ it('a work-less exercise (workId null) is allowed', async () => {
+ await db.writeExercise({ id: 'wr-ex-free', workId: null, status: 'running', startedAt: '2026-01-04T00:00:00.000Z', finishedAt: null });
+ const col = (await query(`SELECT work_id FROM writers_room_exercises WHERE id = 'wr-ex-free'`)).rows[0];
+ expect(col.work_id).toBeNull();
+ });
+
+ it('tolerates malformed timestamps without throwing', async () => {
+ await db.writeWork(manifest('wr-work-1', { createdAt: 'nope', updatedAt: 'not-a-date' }));
+ const col = (await query(`SELECT created_at, updated_at FROM writers_room_works WHERE id = 'wr-work-1'`)).rows[0];
+ expect(col.created_at).toBeInstanceOf(Date);
+ expect(col.updated_at).toBeInstanceOf(Date);
+ });
+
+ it('listDraftVersionsForCoherence returns one entry per live draft row', async () => {
+ await db.writeWork(manifest('wr-work-1', { drafts: [draft('wr-draft-a'), draft('wr-draft-b')] }));
+ const coh = await db.listDraftVersionsForCoherence();
+ expect(coh.map((c) => c.id).sort()).toEqual(['wr-draft-a', 'wr-draft-b']);
+ expect(coh[0]).toMatchObject({ workId: 'wr-work-1', contentFile: expect.stringMatching(/^drafts\//) });
+ });
+});
diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.js
index 6e7a5fb577..5162d7999d 100644
--- a/server/services/writersRoom/local.js
+++ b/server/services/writersRoom/local.js
@@ -1,49 +1,27 @@
/**
- * Writers Room — file-backed storage for folders, works, drafts, and exercises.
+ * Writers Room — storage orchestration for folders, works, drafts, and exercises.
*
- * Layout under data/writers-room/:
- * folders.json
- * exercises.json
- * works/<workId>/manifest.json
+ * Metadata (folders, work manifests, decomposed draft versions, exercises) is
+ * persisted via the storage dispatcher (./store.js): PostgreSQL on a normal
+ * install (#1017), or the legacy on-disk JSON layout under data/writers-room/
+ * on the dev/test file escape hatch. The draft PROSE BODIES always stay on disk
+ * as .md files (file-primary) regardless of backend — this module owns those:
* works/<workId>/drafts/<draftVersionId>.md
*
- * Manifest holds work metadata + the active draft's metadata + the version
- * history; draft bodies live as .md files so long prose stays out of the JSON.
- *
- * This module is the only writer for data/writers-room/. See
- * docs/features/writers-room.md for the full data model.
+ * A work manifest holds work metadata + the active-draft pointer + the version
+ * history (drafts[]); store.js decomposes drafts[] into draft-version rows on
+ * the PG backend and reassembles them on read, so this module's public API and
+ * the manifest shape are unchanged. See docs/features/writers-room.md.
*/
-import { join } from 'path';
import { randomUUID, createHash } from 'crypto';
-import { readFile, rm, readdir } from 'fs/promises';
-import { PATHS, atomicWrite, ensureDir, readJSONFile, safeJSONParse } from '../../lib/fileUtils.js';
-import { ServerError } from '../../lib/errorHandler.js';
+import { readFile, rm } from 'fs/promises';
+import { atomicWrite, ensureDir } from '../../lib/fileUtils.js';
import { WORK_KINDS, WORK_STATUSES } from '../../lib/writersRoomPresets.js';
-import { nowIso, badRequest, notFound, WORK_ID_RE, assertValidWorkId } from './_shared.js';
-
-// Paths are resolved lazily so tests can swap PATHS.data via vi.mock without
-// the module-load snapshot freezing them at import time.
-const root = () => join(PATHS.data, 'writers-room');
-const foldersFile = () => join(root(), 'folders.json');
-const exercisesFile = () => join(root(), 'exercises.json');
-const worksDir = () => join(root(), 'works');
+import { nowIso, badRequest, notFound, wrWorkDir, wrDraftPath } from './_shared.js';
+import { writersRoomStore } from './store.js';
-const DRAFT_ID_RE = /^wr-draft-[0-9a-f-]+$/i;
-
-function workDir(workId) {
- assertValidWorkId(workId);
- return join(worksDir(), workId);
-}
-
-function draftPath(workId, draftId) {
- if (!DRAFT_ID_RE.test(draftId)) throw badRequest('Invalid draft id');
- return join(workDir(workId), 'drafts', `${draftId}.md`);
-}
-
-function manifestPath(workId) {
- return join(workDir(workId), 'manifest.json');
-}
+const store = () => writersRoomStore();
// ---------- text analysis ----------
@@ -111,24 +89,13 @@ export function buildSegmentIndex(text) {
// ---------- folder CRUD ----------
-async function loadFolders() {
- await ensureDir(root());
- const raw = await readJSONFile(foldersFile(), []);
- return Array.isArray(raw) ? raw : [];
-}
-
-async function saveFolders(folders) {
- await ensureDir(root());
- await atomicWrite(foldersFile(), folders);
-}
-
export async function listFolders() {
- return loadFolders();
+ return store().listFolders();
}
export async function createFolder({ name, parentId = null, sortOrder = 0 }) {
if (!name || !name.trim()) throw badRequest('Folder name required');
- const folders = await loadFolders();
+ const folders = await store().listFolders();
if (parentId && !folders.find((f) => f.id === parentId)) throw notFound('Parent folder');
const folder = {
id: `wr-folder-${randomUUID()}`,
@@ -138,13 +105,12 @@ export async function createFolder({ name, parentId = null, sortOrder = 0 }) {
createdAt: nowIso(),
updatedAt: nowIso(),
};
- folders.push(folder);
- await saveFolders(folders);
+ await store().writeFolder(folder);
return folder;
}
export async function deleteFolder(id) {
- const folders = await loadFolders();
+ const folders = await store().listFolders();
if (!folders.find((f) => f.id === id)) throw notFound('Folder');
const works = await listWorks();
if (works.some((w) => w.folderId === id)) {
@@ -153,41 +119,26 @@ export async function deleteFolder(id) {
if (folders.some((f) => f.parentId === id)) {
throw badRequest('Folder has subfolders — delete or reparent them first');
}
- await saveFolders(folders.filter((f) => f.id !== id));
+ await store().deleteFolder(id);
return { ok: true };
}
// ---------- work CRUD ----------
+// Manifest read/write go through the storage dispatcher (PG metadata, or the
+// legacy on-disk JSON on the file escape hatch). The drafts dir is ensured on
+// every save because the draft .md bodies are written there independently (the
+// file backend also persists manifest.json into the work dir, and ensureDir is
+// idempotent + cheap).
async function loadManifest(workId) {
- const path = manifestPath(workId);
- const content = await readFile(path, 'utf-8').catch((err) => {
- if (err.code === 'ENOENT') return null;
- throw err;
- });
- if (content === null) return null;
- // Surface corrupted manifests as a deterministic 500 with a clear code so
- // listWorks can drop the work without masking the underlying issue, and
- // direct callers (getWork) get an actionable error instead of a raw
- // SyntaxError bubbling out of JSON.parse.
- const parsed = safeJSONParse(content, null, { allowArray: false, logError: true, context: path });
- if (parsed === null) {
- // Log the absolute path server-side for debugging, but keep it OUT of
- // the ServerError — errorHandler ships both message AND context to the
- // client response body, so anything in context leaks to the UI.
- console.warn(`⚠️ wr: corrupted manifest at ${path} (work ${workId})`);
- throw new ServerError(`Corrupted writers-room manifest for ${workId}`, {
- status: 500,
- code: 'CORRUPTED_MANIFEST',
- context: { workId },
- });
- }
- return parsed;
+ // Validate the work id (path-traversal guard) before it reaches the backend.
+ wrWorkDir(workId);
+ return store().readWork(workId);
}
async function saveManifest(workId, manifest) {
- await ensureDir(join(workDir(workId), 'drafts'));
- await atomicWrite(manifestPath(workId), manifest);
+ await ensureDir(`${wrWorkDir(workId)}/drafts`);
+ await store().writeWork(manifest);
}
// Lazy-import to break a circular dep (mediaCollections doesn't import us, but
@@ -212,26 +163,11 @@ export async function ensureWorkMediaCollection(workId) {
return collection;
}
-async function listWorkIds() {
- await ensureDir(worksDir());
- const entries = await readdir(worksDir(), { withFileTypes: true });
- return entries.filter((e) => e.isDirectory() && WORK_ID_RE.test(e.name)).map((e) => e.name);
-}
-
export async function listWorks() {
- const ids = await listWorkIds();
- // Tolerate KNOWN failure modes per work (corrupted JSON, missing file) so
- // one bad work doesn't 500 the whole library. Re-throw anything else
- // (permission errors, EIO, programming bugs) — silently swallowing those
- // would mask real outages. ENOENT bubbles as null from loadManifest itself,
- // not as a thrown error, so we only need to special-case CORRUPTED_MANIFEST.
- const manifests = await Promise.all(ids.map((id) => loadManifest(id).catch((err) => {
- if (err?.code === 'CORRUPTED_MANIFEST') {
- console.warn(`⚠️ wr: dropped work ${id} from listing — corrupted manifest`);
- return null;
- }
- throw err;
- })));
+ // The store returns full manifests (rebuilt with drafts[] on the PG backend),
+ // dropping any work with a corrupted manifest on the file backend so one bad
+ // work doesn't 500 the whole library.
+ const manifests = await store().listWorks();
return manifests
.filter(Boolean)
.map((manifest) => {
@@ -261,7 +197,7 @@ export async function getWork(id) {
}
async function readDraftFile(workId, draftId) {
- return readFile(draftPath(workId, draftId), 'utf-8').catch((err) => {
+ return readFile(wrDraftPath(workId, draftId), 'utf-8').catch((err) => {
if (err.code === 'ENOENT') return '';
throw err;
});
@@ -278,14 +214,14 @@ export async function createWork({ folderId = null, title, kind = 'short-story'
if (!title || !title.trim()) throw badRequest('Work title required');
if (!WORK_KINDS.includes(kind)) throw badRequest(`Invalid kind: ${kind}`);
if (folderId) {
- const folders = await loadFolders();
+ const folders = await store().listFolders();
if (!folders.find((f) => f.id === folderId)) throw notFound('Folder');
}
const id = `wr-work-${randomUUID()}`;
const draftId = `wr-draft-${randomUUID()}`;
const now = nowIso();
- await ensureDir(join(workDir(id), 'drafts'));
- await atomicWrite(draftPath(id, draftId), '');
+ await ensureDir(`${wrWorkDir(id)}/drafts`);
+ await atomicWrite(wrDraftPath(id, draftId), '');
const manifest = {
id,
folderId,
@@ -383,7 +319,7 @@ export async function updateWork(id, patch) {
// folderId can be set to a real folder id or to null (unfile the work).
// Anything else would orphan it from the library tree.
if (patch.folderId !== undefined && patch.folderId !== null) {
- const folders = await loadFolders();
+ const folders = await store().listFolders();
if (!folders.find((f) => f.id === patch.folderId)) throw notFound('Folder');
}
await saveManifest(id, next);
@@ -482,7 +418,11 @@ export async function deleteWork(id) {
}
throw err;
});
- await rm(workDir(id), { recursive: true, force: true });
+ // Drop the metadata rows (no-op on the file backend, where the manifest lives
+ // in the work dir the rm below removes) AND rm the on-disk dir holding the
+ // file-primary draft .md bodies.
+ await store().deleteWork(id);
+ await rm(wrWorkDir(id), { recursive: true, force: true });
return { ok: true };
}
@@ -502,7 +442,7 @@ export async function saveDraftBody(workId, body, { referencedIngredientIds } =
const activeId = manifest.activeDraftVersionId;
if (!activeId) throw badRequest('Work has no active draft');
const text = String(body ?? '');
- await atomicWrite(draftPath(workId, activeId), text);
+ await atomicWrite(wrDraftPath(workId, activeId), text);
const draftIdx = manifest.drafts.findIndex((d) => d.id === activeId);
if (draftIdx < 0) throw notFound('Active draft');
const meta = buildDraftMeta(text, manifest.drafts[draftIdx]);
@@ -526,7 +466,7 @@ export async function snapshotDraft(workId, { label } = {}) {
const fromId = manifest.activeDraftVersionId;
const fromDraft = manifest.drafts.find((d) => d.id === fromId);
const draftLabel = label || `Draft ${manifest.drafts.length + 1}`;
- await atomicWrite(draftPath(workId, newDraftId), body);
+ await atomicWrite(wrDraftPath(workId, newDraftId), body);
// The new draft copies the source's body verbatim, so carry its referenced
// ingredient ids forward — otherwise the freshly-snapshotted version would
// render no chips (despite identical prose) until the next save re-scans.
@@ -564,19 +504,8 @@ export async function getDraftBody(workId, draftId) {
// ---------- exercise sessions ----------
-async function loadExercises() {
- await ensureDir(root());
- const raw = await readJSONFile(exercisesFile(), []);
- return Array.isArray(raw) ? raw : [];
-}
-
-async function saveExercises(exercises) {
- await ensureDir(root());
- await atomicWrite(exercisesFile(), exercises);
-}
-
export async function listExercises({ workId } = {}) {
- const all = await loadExercises();
+ const all = await store().listExercises();
const filtered = workId ? all.filter((e) => e.workId === workId) : all;
return filtered.sort((a, b) => (b.startedAt || '').localeCompare(a.startedAt || ''));
}
@@ -600,42 +529,39 @@ export async function createExercise({ workId = null, prompt = '', durationSecon
startedAt: nowIso(),
finishedAt: null,
};
- const all = await loadExercises();
- all.push(exercise);
- await saveExercises(all);
+ await store().writeExercise(exercise);
return exercise;
}
export async function finishExercise(id, { endingWords, appendedText = null } = {}) {
- const all = await loadExercises();
- const idx = all.findIndex((e) => e.id === id);
- if (idx < 0) throw notFound('Exercise');
- if (settled(all[idx])) throw badRequest('Exercise is already settled');
+ const all = await store().listExercises();
+ const existing = all.find((e) => e.id === id);
+ if (!existing) throw notFound('Exercise');
+ if (settled(existing)) throw badRequest('Exercise is already settled');
// Default missing endingWords to startingWords so wordsAdded never goes
// negative when the caller forgets to send it; clamp the delta as a final
// backstop for the case where the user backspaces past their starting count.
- const startingWords = all[idx].startingWords || 0;
+ const startingWords = existing.startingWords || 0;
const resolvedEnding = endingWords ?? startingWords;
const wordsAdded = Math.max(0, resolvedEnding - startingWords);
const finished = {
- ...all[idx],
+ ...existing,
endingWords: resolvedEnding,
wordsAdded,
appendedText: appendedText ?? null,
status: 'finished',
finishedAt: nowIso(),
};
- all[idx] = finished;
- await saveExercises(all);
+ await store().writeExercise(finished);
return finished;
}
export async function discardExercise(id) {
- const all = await loadExercises();
- const idx = all.findIndex((e) => e.id === id);
- if (idx < 0) throw notFound('Exercise');
- if (settled(all[idx])) throw badRequest('Exercise is already settled');
- all[idx] = { ...all[idx], status: 'discarded', finishedAt: nowIso() };
- await saveExercises(all);
- return all[idx];
+ const all = await store().listExercises();
+ const existing = all.find((e) => e.id === id);
+ if (!existing) throw notFound('Exercise');
+ if (settled(existing)) throw badRequest('Exercise is already settled');
+ const discarded = { ...existing, status: 'discarded', finishedAt: nowIso() };
+ await store().writeExercise(discarded);
+ return discarded;
}
diff --git a/server/services/writersRoom/store.js b/server/services/writersRoom/store.js
new file mode 100644
index 0000000000..cabe0f7dde
--- /dev/null
+++ b/server/services/writersRoom/store.js
@@ -0,0 +1,198 @@
+/**
+ * Writers Room — storage backend dispatcher (#1017).
+ *
+ * Folders, works (+ decomposed draft versions), and exercises used to live in a
+ * bespoke file layout (folders.json, exercises.json, per-work manifest.json). As
+ * of #1017 their METADATA lives in PostgreSQL (writers_room_folders /
+ * writers_room_works / writers_room_draft_versions / writers_room_exercises).
+ * The draft PROSE BODIES stay on disk (file-primary) — local.js still owns the
+ * .md read/write; this dispatcher only routes the metadata.
+ *
+ * The public surface (folders/works/exercises CRUD) is identical across both
+ * backends, so local.js calls `store()` and keeps its API unchanged:
+ *
+ * - PostgreSQL (./db.js) for normal installs.
+ * - File backend only under MEMORY_BACKEND=file or NODE_ENV=test (both
+ * UNSUPPORTED for production). The file backend reproduces the legacy
+ * on-disk JSON format so tests boot without a DB exactly as before.
+ *
+ * Writers Room is NOT federated (no dataSync category, no schema-version gate),
+ * so — unlike the universe/pipeline/story-builder stores — there is NO mutation
+ * epoch here: a storage swap has no peer-visible effect to invalidate.
+ *
+ * The first PG-backed call runs a one-time, marker-gated import of the legacy
+ * data/writers-room file store into the tables (migrateWritersRoomToDB).
+ */
+
+import { readFile, readdir } from 'fs/promises';
+import { atomicWrite, ensureDir, readJSONFile, safeJSONParse } from '../../lib/fileUtils.js';
+import { checkHealth, ensureSchema } from '../../lib/db.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import {
+ WORK_ID_RE, wrRoot, wrFoldersFile, wrExercisesFile, wrWorksDir, wrManifestPath,
+} from './_shared.js';
+
+function isFileBackend() {
+ return process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test';
+}
+
+// --- File backend (escape hatch / tests): the legacy on-disk JSON format ---
+// Reproduces local.js's original storage primitives verbatim so an install on
+// the file escape hatch (and every test that boots without a DB) behaves
+// identically to the pre-#1017 file layout.
+function makeFileBackend() {
+ const loadFolders = async () => {
+ await ensureDir(wrRoot());
+ const raw = await readJSONFile(wrFoldersFile(), []);
+ return Array.isArray(raw) ? raw : [];
+ };
+ const saveFolders = async (folders) => {
+ await ensureDir(wrRoot());
+ await atomicWrite(wrFoldersFile(), folders);
+ };
+ const loadExercises = async () => {
+ await ensureDir(wrRoot());
+ const raw = await readJSONFile(wrExercisesFile(), []);
+ return Array.isArray(raw) ? raw : [];
+ };
+ const saveExercises = async (exercises) => {
+ await ensureDir(wrRoot());
+ await atomicWrite(wrExercisesFile(), exercises);
+ };
+ const loadManifest = async (workId) => {
+ const path = wrManifestPath(workId);
+ const content = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (content === null) return null;
+ // Surface corrupted manifests as a deterministic CORRUPTED_MANIFEST 500 (the
+ // pre-#1017 file behavior) so listWorks can drop the work without masking
+ // the issue and direct callers get an actionable error, not a raw SyntaxError.
+ const parsed = safeJSONParse(content, null, { allowArray: false, logError: true, context: path });
+ if (parsed === null) {
+ console.warn(`⚠️ wr: corrupted manifest at ${path} (work ${workId})`);
+ throw new ServerError(`Corrupted writers-room manifest for ${workId}`, {
+ status: 500, code: 'CORRUPTED_MANIFEST', context: { workId },
+ });
+ }
+ return parsed;
+ };
+ const saveManifest = async (workId, manifest) => {
+ await ensureDir(`${wrWorksDir()}/${workId}/drafts`);
+ await atomicWrite(wrManifestPath(workId), manifest);
+ };
+ const listWorkIds = async () => {
+ await ensureDir(wrWorksDir());
+ const entries = await readdir(wrWorksDir(), { withFileTypes: true });
+ return entries.filter((e) => e.isDirectory() && WORK_ID_RE.test(e.name)).map((e) => e.name);
+ };
+
+ return {
+ name: 'file',
+ // folders
+ listFolders: loadFolders,
+ writeFolder: async (folder) => {
+ const folders = await loadFolders();
+ const idx = folders.findIndex((f) => f.id === folder.id);
+ if (idx >= 0) folders[idx] = folder; else folders.push(folder);
+ await saveFolders(folders);
+ },
+ deleteFolder: async (id) => saveFolders((await loadFolders()).filter((f) => f.id !== id)),
+ // exercises
+ listExercises: loadExercises,
+ writeExercise: async (exercise) => {
+ const all = await loadExercises();
+ const idx = all.findIndex((e) => e.id === exercise.id);
+ if (idx >= 0) all[idx] = exercise; else all.push(exercise);
+ await saveExercises(all);
+ },
+ // works (manifest carries its own drafts[] in the file format)
+ readWork: loadManifest,
+ listWorkIds,
+ listWorks: async () => {
+ const ids = await listWorkIds();
+ // Tolerate a corrupted manifest per work (drop it from the listing) so one
+ // bad work doesn't 500 the whole library — the pre-#1017 file behavior.
+ // Re-throw anything else (permission errors, EIO) — masking those would
+ // hide a real outage.
+ const manifests = await Promise.all(ids.map((id) => loadManifest(id).catch((err) => {
+ if (err?.code === 'CORRUPTED_MANIFEST') {
+ console.warn(`⚠️ wr: dropped work ${id} from listing — corrupted manifest`);
+ return null;
+ }
+ throw err;
+ })));
+ return manifests.filter((m) => m != null);
+ },
+ writeWork: async (manifest) => { await saveManifest(manifest.id, manifest); return manifest; },
+ deleteWork: async () => {}, // local.js rm -rf's the dir directly on the file backend
+ listDraftVersionsForCoherence: async () => {
+ const ids = await listWorkIds();
+ const out = [];
+ for (const id of ids) {
+ const m = await loadManifest(id).catch(() => null);
+ for (const d of m?.drafts || []) {
+ out.push({ id: d.id, workId: id, contentFile: d.contentFile, contentHash: d.contentHash });
+ }
+ }
+ return out;
+ },
+ };
+}
+
+// --- PostgreSQL backend: pure leaf I/O from ./db.js ---
+function makePgBackend(db) {
+ return { name: 'postgres', ...db };
+}
+
+async function pgBackend() {
+ const health = await checkHealth();
+ if (!health.connected) {
+ throw new Error('Writers Room requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)');
+ }
+ await ensureSchema();
+ const { migrateWritersRoomToDB } = await import('../../scripts/migrateWritersRoomToDB.js');
+ await migrateWritersRoomToDB();
+ const db = await import('./db.js');
+ return makePgBackend(db);
+}
+
+// Memoize the backend-selection PROMISE (not just the result) so two concurrent
+// first calls — e.g. the boot warm racing a request — don't both import the PG
+// module and run the migration twice.
+let backend = null;
+let selecting = null;
+
+export function _resetWritersRoomStore() {
+ backend = null;
+ selecting = null;
+}
+
+function getBackend() {
+ if (backend) return Promise.resolve(backend);
+ if (!selecting) {
+ selecting = (isFileBackend() ? Promise.resolve(makeFileBackend()) : pgBackend())
+ .then((b) => { backend = b; return b; })
+ .finally(() => { selecting = null; });
+ }
+ return selecting;
+}
+
+/** The Writers Room metadata store — backend resolved lazily per call. */
+export function writersRoomStore() {
+ return {
+ getBackendName: () => backend?.name ?? null,
+ listFolders: async () => (await getBackend()).listFolders(),
+ writeFolder: async (folder) => (await getBackend()).writeFolder(folder),
+ deleteFolder: async (id) => (await getBackend()).deleteFolder(id),
+ listExercises: async () => (await getBackend()).listExercises(),
+ writeExercise: async (exercise) => (await getBackend()).writeExercise(exercise),
+ readWork: async (id) => (await getBackend()).readWork(id),
+ listWorkIds: async () => (await getBackend()).listWorkIds(),
+ listWorks: async () => (await getBackend()).listWorks(),
+ writeWork: async (manifest) => (await getBackend()).writeWork(manifest),
+ deleteWork: async (id) => (await getBackend()).deleteWork(id),
+ listDraftVersionsForCoherence: async () => (await getBackend()).listDraftVersionsForCoherence(),
+ };
+}
diff --git a/server/services/writersRoom/store.test.js b/server/services/writersRoom/store.test.js
new file mode 100644
index 0000000000..54798f3241
--- /dev/null
+++ b/server/services/writersRoom/store.test.js
@@ -0,0 +1,100 @@
+/**
+ * Writers Room store dispatcher — file-backend behavior (#1017).
+ *
+ * NODE_ENV=test selects the file backend (the legacy on-disk JSON layout over a
+ * real tmpdir), so this exercises the dispatcher WITHOUT a database: the uniform
+ * folders/works/exercises surface local.js calls, the manifest-with-drafts[]
+ * shape the file backend persists verbatim (no decomposition on this backend),
+ * and the corrupted-manifest tolerance the library depends on.
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'wr-store-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+});
+
+const { writersRoomStore, _resetWritersRoomStore } = await import('./store.js');
+
+const WR = join(TEST_DATA_ROOT, 'writers-room');
+
+const manifest = (id, extra = {}) => ({
+ id, title: id, kind: 'short-story', status: 'drafting',
+ activeDraftVersionId: 'wr-draft-a',
+ drafts: [{ id: 'wr-draft-a', label: 'Draft 1', contentFile: 'drafts/wr-draft-a.md', contentHash: 'h', wordCount: 0, segmentIndex: [], createdAt: '2026-01-01T00:00:00.000Z' }],
+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-02T00:00:00.000Z', ...extra,
+});
+
+describe('Writers Room store dispatcher — file backend', () => {
+ beforeEach(() => {
+ rmSync(WR, { recursive: true, force: true });
+ _resetWritersRoomStore();
+ });
+ afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+ it('selects the file backend under NODE_ENV=test', async () => {
+ const s = writersRoomStore();
+ await s.listFolders();
+ expect(s.getBackendName()).toBe('file');
+ });
+
+ it('folders round-trip through write/list/delete', async () => {
+ const s = writersRoomStore();
+ await s.writeFolder({ id: 'wr-folder-1', name: 'A', parentId: null, sortOrder: 0 });
+ await s.writeFolder({ id: 'wr-folder-2', name: 'B', parentId: null, sortOrder: 1 });
+ expect((await s.listFolders()).map((f) => f.id).sort()).toEqual(['wr-folder-1', 'wr-folder-2']);
+ await s.deleteFolder('wr-folder-1');
+ expect((await s.listFolders()).map((f) => f.id)).toEqual(['wr-folder-2']);
+ });
+
+ it('works persist with their embedded drafts[] (no decomposition on file backend)', async () => {
+ const s = writersRoomStore();
+ await s.writeWork(manifest('wr-work-1'));
+ const back = await s.readWork('wr-work-1');
+ expect(back.title).toBe('wr-work-1');
+ expect(back.drafts.map((d) => d.id)).toEqual(['wr-draft-a']);
+ expect(await s.listWorkIds()).toEqual(['wr-work-1']);
+ expect((await s.listWorks()).map((w) => w.id)).toEqual(['wr-work-1']);
+ });
+
+ it('readWork returns null for a missing work', async () => {
+ const s = writersRoomStore();
+ expect(await s.readWork('wr-work-deadbeef')).toBeNull();
+ });
+
+ it('listWorks drops a work with a corrupted manifest but keeps the rest', async () => {
+ const s = writersRoomStore();
+ await s.writeWork(manifest('wr-work-aaa'));
+ // Hand-corrupt a second work's manifest on disk.
+ const badDir = join(WR, 'works', 'wr-work-bbb');
+ mkdirSync(join(badDir, 'drafts'), { recursive: true });
+ writeFileSync(join(badDir, 'manifest.json'), '{ not valid json');
+ const list = await s.listWorks();
+ expect(list.map((w) => w.id)).toEqual(['wr-work-aaa']);
+ // A direct read of the corrupted work surfaces CORRUPTED_MANIFEST.
+ await expect(s.readWork('wr-work-bbb')).rejects.toMatchObject({ code: 'CORRUPTED_MANIFEST' });
+ });
+
+ it('exercises round-trip through write/list', async () => {
+ const s = writersRoomStore();
+ await s.writeExercise({ id: 'wr-ex-1', workId: 'wr-work-1', status: 'running', startedAt: '2026-01-03T00:00:00.000Z' });
+ await s.writeExercise({ id: 'wr-ex-1', workId: 'wr-work-1', status: 'finished', startedAt: '2026-01-03T00:00:00.000Z', finishedAt: '2026-01-03T01:00:00.000Z' });
+ const all = await s.listExercises();
+ expect(all).toHaveLength(1);
+ expect(all[0].status).toBe('finished');
+ });
+
+ it('listDraftVersionsForCoherence enumerates every draft across works', async () => {
+ const s = writersRoomStore();
+ await s.writeWork(manifest('wr-work-1'));
+ const coh = await s.listDraftVersionsForCoherence();
+ expect(coh.map((c) => c.id)).toEqual(['wr-draft-a']);
+ expect(coh[0]).toMatchObject({ workId: 'wr-work-1', contentFile: 'drafts/wr-draft-a.md' });
+ });
+});