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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(creative-director): migrate project state from JSON to PostgreSQL (#997)
Adam Eivy36b79dc2a255
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7d1560e2c1..18d64c0b9d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -13,6 +13,7 @@## Changed+- **Creative Director state now lives in PostgreSQL** — Creative Director projects (treatment, scenes, and run history) moved out of the single monolithic `data/creative-director-projects.json` file into a `creative_director_projects` table, one row per project. The orchestrator rewrote that whole file ≈10 times per scene render, so a long session turned every project list/read into an O(N²) reserialize; per-project rows remove that contention, and concurrent writes to the same project (render-progress + agent-run updates) are now serialized with a row lock so they can't lose each other's updates. Existing installs are migrated automatically and losslessly on first boot — the legacy file is kept (renamed `…json.imported`) as a recovery source. Behavior is unchanged; this is a storage move (Phase 3 of the Postgres-first plan, #997). The file backend remains reachable under the `MEMORY_BACKEND=file` dev/test escape hatch.- **PostgreSQL is now a required dependency** — file-based JSON storage is no longer offered as a normal setup choice. `npm run setup:db` presents only Docker and Native PostgreSQL hosting modes (and auto-selects native when a healthy local PostgreSQL is already reachable). On boot, PortOS now verifies the database is reachable with the required schema and refuses to start with an actionable message if it isn't — instead of silently falling back to file-backed memory and serving a half-broken install (the creative catalog has no file-backed equivalent). `MEMORY_BACKEND=file` survives only as an explicit, unsupported development/test escape hatch. New docs: [`docs/STORAGE.md`](../docs/STORAGE.md) (the storage-classification contract — `db-primary` / `file-primary` / `asset-file-db-indexed` / `ephemeral-file` — plus a "new data store?" review checklist) and [`docs/BACKUP.md`](../docs/BACKUP.md) (backup/restore now that the Postgres dump is required system state).- **Local model pickers now show what's actually installed** — the Fallback Model dropdown in the AI Provider editor and the provider/model selector in the manuscript editorial review previously only listed the models stored on the provider record, so models you'd pulled in Ollama later (e.g. Command R+, Gemma) never appeared. Both pickers now fold in the live list of installed Ollama / LM Studio models. Embedding-only models (e.g. `nomic-embed-text`) are filtered out of these generation pickers since they can't run a prompt.- **Editorial model recommendation** — the manuscript editorial review now suggests the best installed local model for editing/feedback (a one-tap "Recommended for editing" chip), ranking models that follow instructions tightly (Qwen/Llama/Gemma) ahead of chatty/RAG-tuned ones (Command R+) and skipping embedding/code/vision models. The pick is always among your *installed* models, so it auto-adapts as you pull newer versions.diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 25e185ade5..bc0690a271 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -31,8 +31,9 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `catalog_ingredients` — typed creative records with JSONB payload, tags, embeddings, generated `search_tsv`, soft delete, sync sequence.- `catalog_ingredient_relations` — directed ingredient→ingredient graph edges (the strongest argument for Postgres as the catalog graph store).- `memories` / `memory_links` — long-term memory + pgvector similarity.+- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.-**Postgres-First target.** Universes, pipeline series/issues, Story Builder sessions, Creative Director project/scene/run state, and searchable media metadata are all `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. Catalog user-defined types should also move from `settings.json` into catalog DB tables.+**Postgres-First target.** Universes, pipeline series/issues, Story Builder sessions, and searchable media metadata are still `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. Catalog user-defined types should also move from `settings.json` into catalog DB tables. (Creative Director project/scene/run state moved to Postgres in Phase 3 / #997.)---@@ -91,7 +92,7 @@ The contract draws a single line:- **Files own** large binary payloads, long externally-editable prose bodies, model weights, temporary uploads, and iCloud-backed health/life stores.- **File assets referenced from the DB** get a stable `asset_key` / `media_key` row plus integrity metadata. The DB points to files; it does not absorb the bytes.-Defaulting a new Create feature to a fresh `data/*.json` file is the anti-pattern this contract exists to stop. Monolithic JSON in hot paths (`creative-director-projects.json`, `media-jobs.json`, `video-history.json`) already causes write contention and growth risk; string-id cross-references across separate JSON stores drift with no integrity check. New relational surfaces should be `db-primary` from the start.+Defaulting a new Create feature to a fresh `data/*.json` file is the anti-pattern this contract exists to stop. Monolithic JSON in hot paths (`media-jobs.json`, `video-history.json` — and `creative-director-projects.json` before #997 moved it to Postgres) causes write contention and growth risk; string-id cross-references across separate JSON stores drift with no integrity check. New relational surfaces should be `db-primary` from the start.---diff --git a/server/lib/db.js b/server/lib/db.jsindex 9c32db8fae..ed073556a4 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -508,6 +508,22 @@ export async function ensureSchema() {BEFORE UPDATE ON catalog_tagsFOR EACH ROWEXECUTE FUNCTION update_catalog_tag_timestamp()`,++ // Creative Director projects (Phase 3, issue #997). One row per project;+ // `id`/`status`/`created_at`/`updated_at` are columns (recovery filters on+ // status, list sorts by updatedAt) and the full record lives in `data`+ // JSONB. CD is local-only (not federated) so no sync_sequence/tombstone.+ // `status` is app-layer gated (PROJECT_STATUSES), no DB CHECK. Mirrors the+ // creative_director_projects block in init-db.sql.+ `CREATE TABLE IF NOT EXISTS creative_director_projects (+ id TEXT PRIMARY KEY,+ status VARCHAR(32) NOT NULL DEFAULT 'draft',+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+ )`,+ `CREATE INDEX IF NOT EXISTS idx_cd_projects_status ON creative_director_projects (status)`,+ `CREATE INDEX IF NOT EXISTS idx_cd_projects_updated_at ON creative_director_projects (updated_at)`,];for (const sql of catalogDDL) {await pool.query(sql);diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 2bb054ba11..7e6816680e 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -558,3 +558,35 @@ CREATE TRIGGER trg_catalog_tag_updated_atBEFORE UPDATE ON catalog_tagsFOR EACH ROWEXECUTE FUNCTION update_catalog_tag_timestamp();++-- ===========================================================================+-- Creative Director projects (Phase 3, issue #997)+-- ===========================================================================+-- One row per project. `id` / `status` / `created_at` / `updated_at` are+-- promoted to real columns (the recovery scan and the project list filter on+-- status + sort by updatedAt); the full project record — treatment, scenes,+-- runs[], and the misc back-pointers (collectionId / timelineProjectId /+-- finalVideoId / sourceIssueId) — lives in `data` JSONB.+--+-- Why JSONB and not normalized scene/run tables: no code queries INTO scenes+-- or runs relationally (the orchestrator loads the whole project, mutates a+-- scene or appends a run, writes it back), and scenes carry ad-hoc fields+-- outside the Zod schema (evaluationFrames). Per-PROJECT rows already remove+-- the monolithic-file write contention + O(N²) reserialize the old single+-- creative-director-projects.json caused. Normalizing scenes/runs is deferred+-- to a later phase if a cross-project scene/run query ever materializes.+--+-- CD is local-only (NOT federated — see plan §"Peer sync"), so there is no+-- sync_sequence / soft-delete-tombstone column: a delete is a hard DELETE.+-- `status` has no DB CHECK; valid values are gated at the app layer via+-- PROJECT_STATUSES (creativeDirectorPresets.js), matching the catalog+-- ingredients convention so a new status needs no constraint migration.+CREATE TABLE IF NOT EXISTS creative_director_projects (+ id TEXT PRIMARY KEY,+ status VARCHAR(32) NOT NULL DEFAULT 'draft',+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+);+CREATE INDEX IF NOT EXISTS idx_cd_projects_status ON creative_director_projects (status);+CREATE INDEX IF NOT EXISTS idx_cd_projects_updated_at ON creative_director_projects (updated_at);diff --git a/server/scripts/migrateCreativeDirectorToDB.js b/server/scripts/migrateCreativeDirectorToDB.jsnew file mode 100644index 0000000000..c543d67951--- /dev/null+++ b/server/scripts/migrateCreativeDirectorToDB.js@@ -0,0 +1,114 @@+/**+ * One-time importer: data/creative-director-projects.json → PostgreSQL+ * (creative_director_projects), for Phase 3 / issue #997.+ *+ * Creative Director projects used to live in a single JSON array. As of #997+ * they live one-row-per-project in Postgres. On the first PG-backed init (from+ * services/creativeDirector/local.js, BEFORE the boot recovery scan reads any+ * project), this importer copies each legacy project into the table.+ *+ * Idempotency / safety:+ * - Marker-gated in data/creative-director-projects.migrated.json (mirrors+ * the migrateBibleToCatalog marker convention) so the walk runs once.+ * - INSERT … ON CONFLICT (id) DO NOTHING — a project already in the table+ * (e.g. a partial prior run, or a row created after the JSON was written)+ * is never clobbered. The DB row is authoritative once it exists.+ * - The legacy JSON is RENAMED to .imported (not deleted) so it remains a+ * recovery source for at least one release (per the plan's Phase 5 note),+ * and so a re-run can't re-import stale rows over fresher DB state.+ * - Runs[] is trimmed to the same cap the live store enforces, so a legacy+ * over-cap array doesn't bloat the row on import.+ *+ * NOT marker-gated via data/migrations.applied.json: that list is driven by the+ * prompt-replace runner under scripts/migrations/ and runs at a different boot+ * phase (before the DB gate). This import must run only when Postgres is the+ * confirmed-healthy backend, so it's gated on its own marker and invoked from+ * the backend selector instead.+ */++import { readFile, writeFile, rename } from 'fs/promises';+import { join } from 'path';+import { PATHS } from '../lib/fileUtils.js';+import { query } from '../lib/db.js';+import { trimRuns } from '../services/creativeDirector/projectsLogic.js';++const LEGACY_FILENAME = 'creative-director-projects.json';+const IMPORTED_SUFFIX = '.imported';+const MARKER_FILENAME = 'creative-director-projects.migrated.json';++async function markerExists() {+ const path = join(PATHS.data, MARKER_FILENAME);+ const raw = await readFile(path, 'utf-8').catch(() => null);+ return raw != null;+}++async function writeMarker(payload) {+ const path = join(PATHS.data, MARKER_FILENAME);+ await writeFile(path, JSON.stringify(payload, null, 2) + '\n', 'utf-8');+}++export async function migrateCreativeDirectorToDB() {+ // Already imported on a prior boot → no-op.+ if (await markerExists()) return { ok: true, reason: 'already-applied' };++ const legacyPath = join(PATHS.data, LEGACY_FILENAME);+ const raw = await readFile(legacyPath, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });++ // Fresh install (no legacy file): stamp the marker so we don't re-probe every+ // boot, and return.+ if (raw == null) {+ await writeMarker({ migratedAt: new Date().toISOString(), imported: 0, reason: 'fresh-install' });+ return { ok: true, reason: 'fresh-install', imported: 0 };+ }++ let projects;+ try {+ projects = JSON.parse(raw);+ } catch (err) {+ // A corrupt legacy file shouldn't block boot — leave it in place (un-renamed,+ // no marker) so the user can repair it and the next boot retries.+ console.warn(`⚠️ CD→DB import: ${LEGACY_FILENAME} is invalid JSON (${err.message}) — leaving it for manual repair, will retry next boot`);+ return { ok: false, reason: 'unreadable' };+ }+ if (!Array.isArray(projects)) {+ console.warn(`⚠️ CD→DB import: ${LEGACY_FILENAME} is not an array — skipping, will retry next boot`);+ return { ok: false, reason: 'not-an-array' };+ }++ let imported = 0;+ let skipped = 0;+ for (const project of projects) {+ if (!project || typeof project !== 'object' || typeof project.id !== 'string') {+ skipped += 1;+ continue;+ }+ if (Array.isArray(project.runs)) project.runs = trimRuns(project.runs);+ const result = await query(+ `INSERT INTO creative_director_projects (id, status, data, created_at, updated_at)+ VALUES ($1, $2, $3::jsonb, $4, $5)+ ON CONFLICT (id) DO NOTHING`,+ [+ project.id,+ project.status || 'draft',+ JSON.stringify(project),+ project.createdAt || new Date().toISOString(),+ project.updatedAt || project.createdAt || new Date().toISOString(),+ ],+ );+ if (result.rowCount > 0) imported += 1;+ else skipped += 1;+ }++ // Rename the legacy file aside AFTER all rows land, so a crash mid-import+ // leaves the marker unwritten and the file in place → next boot retries+ // (ON CONFLICT DO NOTHING makes the retry safe for already-imported rows).+ await rename(legacyPath, legacyPath + IMPORTED_SUFFIX).catch((err) => {+ console.warn(`⚠️ CD→DB import: could not rename ${LEGACY_FILENAME} aside (${err.message}); rows imported, marker still written`);+ });+ await writeMarker({ migratedAt: new Date().toISOString(), imported, skipped });+ console.log(`🎬 CD→DB import: imported ${imported} project(s) into creative_director_projects (${skipped} skipped); legacy file renamed to ${LEGACY_FILENAME}${IMPORTED_SUFFIX}`);+ return { ok: true, reason: 'imported', imported, skipped };+}diff --git a/server/scripts/migrateCreativeDirectorToDB.test.js b/server/scripts/migrateCreativeDirectorToDB.test.jsnew file mode 100644index 0000000000..df73896f8f--- /dev/null+++ b/server/scripts/migrateCreativeDirectorToDB.test.js@@ -0,0 +1,115 @@+/**+ * Tests for the legacy creative-director-projects.json → Postgres importer.+ *+ * Marker file I/O + the legacy file read/rename are mocked to an in-memory+ * blob; `db.query` is a fake that records INSERTs and honors ON CONFLICT DO+ * NOTHING. No disk, no Postgres.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';++// In-memory filesystem keyed by absolute path.+let files = {};++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { data: '/fake/data' },+}));++vi.mock('fs/promises', () => ({+ readFile: vi.fn(async (path) => {+ if (!(path in files)) {+ const err = new Error('ENOENT');+ err.code = 'ENOENT';+ throw err;+ }+ return files[path];+ }),+ writeFile: vi.fn(async (path, content) => { files[path] = content; }),+ rename: vi.fn(async (from, to) => {+ files[to] = files[from];+ delete files[from];+ }),+}));++// Fake DB: a Map standing in for creative_director_projects, with ON CONFLICT+// DO NOTHING semantics.+let table;+const query = vi.fn(async (sql, params) => {+ if (/INSERT INTO creative_director_projects/.test(sql)) {+ const [id, status, data] = params;+ if (table.has(id)) return { rowCount: 0, rows: [] };+ table.set(id, { id, status, data });+ return { rowCount: 1, rows: [] };+ }+ return { rowCount: 0, rows: [] };+});+vi.mock('../lib/db.js', () => ({ query: (...a) => query(...a) }));++const LEGACY = '/fake/data/creative-director-projects.json';+const MARKER = '/fake/data/creative-director-projects.migrated.json';+const IMPORTED = LEGACY + '.imported';++const { migrateCreativeDirectorToDB } = await import('./migrateCreativeDirectorToDB.js');++beforeEach(() => {+ files = {};+ table = new Map();+ query.mockClear();+});++describe('migrateCreativeDirectorToDB', () => {+ it('fresh install (no legacy file): stamps marker, imports nothing', async () => {+ const result = await migrateCreativeDirectorToDB();+ expect(result).toMatchObject({ ok: true, reason: 'fresh-install', imported: 0 });+ expect(files[MARKER]).toBeTruthy();+ expect(query).not.toHaveBeenCalled();+ });++ it('imports legacy projects into the table and renames the file aside', async () => {+ files[LEGACY] = JSON.stringify([+ { id: 'cd-1', status: 'complete', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-02T00:00:00.000Z' },+ { id: 'cd-2', status: 'draft', createdAt: '2026-01-03T00:00:00.000Z' },+ ]);+ const result = await migrateCreativeDirectorToDB();+ expect(result).toMatchObject({ ok: true, reason: 'imported', imported: 2 });+ expect(table.has('cd-1')).toBe(true);+ expect(table.has('cd-2')).toBe(true);+ // Legacy renamed aside (recovery source), marker written.+ expect(files[LEGACY]).toBeUndefined();+ expect(files[IMPORTED]).toBeTruthy();+ expect(files[MARKER]).toBeTruthy();+ });++ it('is a no-op on the second run (marker present)', async () => {+ files[LEGACY] = JSON.stringify([{ id: 'cd-1', status: 'draft' }]);+ await migrateCreativeDirectorToDB();+ query.mockClear();+ const result = await migrateCreativeDirectorToDB();+ expect(result).toMatchObject({ ok: true, reason: 'already-applied' });+ expect(query).not.toHaveBeenCalled();+ });++ it('does not clobber a row already in the table (ON CONFLICT DO NOTHING)', async () => {+ table.set('cd-1', { id: 'cd-1', status: 'rendering', data: '{"fresher":true}' });+ files[LEGACY] = JSON.stringify([{ id: 'cd-1', status: 'draft' }]);+ const result = await migrateCreativeDirectorToDB();+ expect(result.imported).toBe(0);+ expect(result.skipped).toBe(1);+ expect(table.get('cd-1').data).toBe('{"fresher":true}');+ });++ it('skips malformed records (missing id) without aborting the import', async () => {+ files[LEGACY] = JSON.stringify([{ id: 'cd-1', status: 'draft' }, { noId: true }, null]);+ const result = await migrateCreativeDirectorToDB();+ expect(result.imported).toBe(1);+ expect(result.skipped).toBe(2);+ });++ it('leaves a corrupt legacy file in place for repair (no marker, no rename)', async () => {+ files[LEGACY] = '{ not valid json';+ const result = await migrateCreativeDirectorToDB();+ expect(result).toMatchObject({ ok: false, reason: 'unreadable' });+ expect(files[LEGACY]).toBeTruthy(); // untouched+ expect(files[MARKER]).toBeUndefined(); // not stamped → retries next boot+ });+});diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.jsindex 087721e5bd..57ce1ab595 100644--- a/server/services/creativeDirector/local.js+++ b/server/services/creativeDirector/local.js@@ -1,227 +1,102 @@/**- * Creative Director — project state CRUD.+ * Creative Director — project state CRUD (backend dispatcher).*- * Persists to data/creative-director-projects.json (array, atomicWrite).- * Mirrors the shape of services/videoTimeline/local.js but stores a richer- * model — every project has a treatment (logline + scene list) the agent- * fills in during the planning task.+ * Historically this module was the file-backed store directly. As of Phase 3+ * (#997) Creative Director projects live in PostgreSQL (creative_director_projects),+ * and this module became a thin dispatcher — mirroring memoryBackend.js — so+ * the 8 import sites and every test mock that targets `./local.js` keep working+ * unchanged.*- * The treatment + scene + run fields are mutated by the agent via the- * /api/creative-director/:id/* routes. This module is the only writer to- * the JSON file; the orchestrator and routes call into here.+ * Backend selection (same posture as the memory backend):+ * - PostgreSQL (projectsDB.js) for normal installs.+ * - File (projectsFile.js) only via MEMORY_BACKEND=file (escape hatch) or+ * NODE_ENV=test — both UNSUPPORTED for production. Tests boot without a DB,+ * so they exercise the file backend and need no Postgres.+ *+ * The first PG init runs a one-time, marker-gated import of any legacy+ * data/creative-director-projects.json rows into the table (see+ * scripts/migrateCreativeDirectorToDB.js), so the boot recovery scan — the first+ * caller — sees migrated projects.+ *+ * `trimRuns` is re-exported from projectsLogic.js for the migration + any caller+ * that imported it from here historically.*/-import { join } from 'path';-import { randomUUID } from 'crypto';-import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils.js';-import { ServerError } from '../../lib/errorHandler.js';-import { creativeDirectorTreatmentSchema } from '../../lib/validation.js';-import { PROJECT_STATUSES } from '../../lib/creativeDirectorPresets.js';-import { createCollection } from '../mediaCollections.js';--const PROJECTS_FILE = join(PATHS.data, 'creative-director-projects.json');--// Without a cap, runs[] grows unbounded and every loadAll/saveAll (≈10 per-// scene render) parses + serializes a file whose size scales with cumulative-// renders — turning per-scene orchestration into O(N²) wall-clock. In-flight-// runs are load-bearing for orphan/dedup detection in completionHook and the-// boot recovery scan, so trim only preserves the most-recent terminal entries.-const MAX_PERSISTED_RUNS = 200;-const TERMINAL_RUN_STATUSES = new Set(['completed', 'failed']);--export function trimRuns(runs) {- if (!Array.isArray(runs)) return [];- if (runs.length <= MAX_PERSISTED_RUNS) return runs;- let inflightCount = 0;- for (const r of runs) {- if (!(r && TERMINAL_RUN_STATUSES.has(r.status))) inflightCount += 1;- }- const terminalBudget = Math.max(0, MAX_PERSISTED_RUNS - inflightCount);- // Walk backwards keeping every in-flight run + the most-recent `terminalBudget`- // terminal runs, then reverse the result so original chronological order is- // preserved (RunsTab sorts by startedAt, but recovery scans + completionHook- // predicates iterate runs[] directly and stay readable when it reads chronologically).- const kept = [];- let terminalsKept = 0;- for (let i = runs.length - 1; i >= 0; i -= 1) {- const r = runs[i];- const isTerminal = r && TERMINAL_RUN_STATUSES.has(r.status);- if (!isTerminal) {- kept.push(r);- } else if (terminalsKept < terminalBudget) {- kept.push(r);- terminalsKept += 1;- }+import { checkHealth, ensureSchema } from '../../lib/db.js';++export { trimRuns } from './projectsLogic.js';++let backend = null;+let backendName = null;++async function selectBackend() {+ if (backend) return backend;++ const envBackend = process.env.MEMORY_BACKEND;++ // Explicit file escape hatch, or test mode (no DB) → file backend.+ if (envBackend === 'file' || process.env.NODE_ENV === 'test') {+ backend = await import('./projectsFile.js');+ backendName = 'file';+ return backend;}- return kept.reverse();-}-async function loadAll() {- const raw = await readJSONFile(PROJECTS_FILE, []);- return Array.isArray(raw) ? raw : [];+ // Default + explicit postgres → PostgreSQL. The boot DB gate in+ // server/index.js fail-fasts when Postgres is required but missing, but the+ // boot RECOVERY scan (recoverInFlightProjects) calls in here BEFORE that gate+ // runs ensureSchema() — so an upgrade install may not have the+ // creative_director_projects table yet at first call. Mirror memoryBackend.js+ // and run ensureSchema() here ourselves (idempotent) so the backend is+ // self-sufficient regardless of boot ordering.+ const health = await checkHealth();+ if (!health.connected) {+ throw new Error('Creative Director requires PostgreSQL — run `npm run setup:db` (or set PGMODE=file for the unsupported file backend)');+ }+ await ensureSchema();+ const { migrateCreativeDirectorToDB } = await import('../../scripts/migrateCreativeDirectorToDB.js');+ await migrateCreativeDirectorToDB();+ backend = await import('./projectsDB.js');+ backendName = 'postgres';+ return backend;}-async function saveAll(projects) {- // Defense for first-run on a fresh checkout where data/ may not exist yet.- // Mirrors videoTimeline/local.js#saveProjects.- await ensureDir(PATHS.data);- // Enforce the runs[] cap at the single write chokepoint so every mutator- // (recordRun, updateRun, updateProject, setTreatment, updateScene) shrinks- // legacy over-cap arrays on first save without each having to remember.- for (const p of projects) {- if (Array.isArray(p?.runs)) p.runs = trimRuns(p.runs);- }- await atomicWrite(PROJECTS_FILE, projects);+/** Name of the active backend, or null before first call (for diagnostics/tests). */+export function getProjectsBackendName() {+ return backendName;}export async function listProjects() {- return loadAll();+ return (await selectBackend()).listProjects();}export async function getProject(id) {- const all = await loadAll();- return all.find((p) => p.id === id) || null;+ return (await selectBackend()).getProject(id);}-export async function createProject({ name, aspectRatio, quality, modelId, targetDurationSeconds, styleSpec = '', startingImageFile = null, userStory = null, disableAudio = true, autoAcceptScenes = false, sourceIssueId = null }) {- const id = `cd-${randomUUID()}`;- const now = new Date().toISOString();-- // Auto-create a media collection scoped to this project. All segment- // renders + the final stitched output land in here.- const collection = await createCollection({ name: `Creative Director: ${name}`, description: `Auto-created for project ${id}` });-- const project = {- id,- name,- status: 'draft',- createdAt: now,- updatedAt: now,- aspectRatio,- quality,- modelId,- targetDurationSeconds,- styleSpec,- startingImageFile,- userStory,- disableAudio,- autoAcceptScenes,- // Optional back-pointer to the pipeline issue that spawned this project.- // The stitch step uses it to look up `stages.audio.music` and mix it- // into the final cut. Bare CD projects (no pipeline origin) leave this- // null and skip the audio-mux pass.- sourceIssueId,- collectionId: collection.id,- timelineProjectId: null,- finalVideoId: null,- treatment: null,- runs: [],- };- const all = await loadAll();- all.push(project);- await saveAll(all);- console.log(`🎬 Created Creative Director project: ${id} (${name})`);- return project;+export async function createProject(input) {+ return (await selectBackend()).createProject(input);}export async function updateProject(id, patch) {- const all = await loadAll();- const idx = all.findIndex((p) => p.id === id);- if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- if (patch.status && !PROJECT_STATUSES.includes(patch.status)) {- throw new ServerError(`Invalid status: ${patch.status}`, { status: 400, code: 'VALIDATION_ERROR' });- }- const updated = { ...all[idx], ...patch, updatedAt: new Date().toISOString() };- all[idx] = updated;- await saveAll(all);- return updated;+ return (await selectBackend()).updateProject(id, patch);}export async function deleteProject(id) {- const all = await loadAll();- const next = all.filter((p) => p.id !== id);- if (next.length === all.length) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- await saveAll(next);- return { ok: true };+ return (await selectBackend()).deleteProject(id);}export async function setTreatment(id, treatmentInput) {- const parsed = creativeDirectorTreatmentSchema.safeParse(treatmentInput);- if (!parsed.success) {- throw new ServerError(- `Treatment validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`,- { status: 400, code: 'VALIDATION_ERROR' },- );- }- const all = await loadAll();- const idx = all.findIndex((p) => p.id === id);- if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- // Initialize each scene's runtime fields if the agent didn't supply them.- const scenes = parsed.data.scenes.map((s) => ({- ...s,- status: s.status || 'pending',- retryCount: s.retryCount ?? 0,- renderedJobId: s.renderedJobId ?? null,- evaluation: s.evaluation ?? null,- }));- const nextStatus = (all[idx].status === 'paused' || all[idx].status === 'failed')- ? all[idx].status- : 'rendering';- all[idx] = {- ...all[idx],- treatment: { logline: parsed.data.logline, synopsis: parsed.data.synopsis, scenes },- status: nextStatus,- updatedAt: new Date().toISOString(),- };- await saveAll(all);- return all[idx];+ return (await selectBackend()).setTreatment(id, treatmentInput);}export async function updateScene(id, sceneId, patch) {- const all = await loadAll();- const idx = all.findIndex((p) => p.id === id);- if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- const project = all[idx];- if (!project.treatment?.scenes?.length) {- throw new ServerError('Project has no treatment yet', { status: 400, code: 'NO_TREATMENT' });- }- const sceneIdx = project.treatment.scenes.findIndex((s) => s.sceneId === sceneId);- if (sceneIdx < 0) throw new ServerError('Scene not found', { status: 404, code: 'NOT_FOUND' });- const updated = { ...project.treatment.scenes[sceneIdx], ...patch };- project.treatment.scenes[sceneIdx] = updated;- project.updatedAt = new Date().toISOString();- all[idx] = project;- await saveAll(all);- return updated;+ return (await selectBackend()).updateScene(id, sceneId, patch);}export async function recordRun(id, runEntry) {- const all = await loadAll();- const idx = all.findIndex((p) => p.id === id);- if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- const project = all[idx];- const run = { startedAt: new Date().toISOString(), ...runEntry, runId: runEntry.runId || randomUUID() };- project.runs = [...(project.runs || []), run];- project.updatedAt = new Date().toISOString();- all[idx] = project;- await saveAll(all);- return run;+ return (await selectBackend()).recordRun(id, runEntry);}export async function updateRun(id, runId, patch) {- const all = await loadAll();- const idx = all.findIndex((p) => p.id === id);- if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- const project = all[idx];- const runIdx = (project.runs || []).findIndex((r) => r.runId === runId);- if (runIdx < 0) return null;- const updated = { ...project.runs[runIdx], ...patch };- project.runs[runIdx] = updated;- project.updatedAt = new Date().toISOString();- all[idx] = project;- // saveAll rewrites project.runs in place via trimRuns when over-cap, so- // runIdx may not point at the patched run afterwards — return the local- // reference captured pre-save instead.- await saveAll(all);- return updated;+ return (await selectBackend()).updateRun(id, runId, patch);}diff --git a/server/services/creativeDirector/localBackend.test.js b/server/services/creativeDirector/localBackend.test.jsnew file mode 100644index 0000000000..5bb3cd94f1--- /dev/null+++ b/server/services/creativeDirector/localBackend.test.js@@ -0,0 +1,86 @@+/**+ * Backend-selection tests for the Creative Director dispatcher (local.js).+ *+ * Mirrors memoryBackend's contract: file backend under MEMORY_BACKEND=file or+ * NODE_ENV=test; Postgres otherwise (gated on a healthy DB). We assert the+ * SELECTION, not the storage round-trip — the file/PG round-trips are covered+ * by local.test.js (file) and projectsDB.test.js (PG, skip-if-no-DB).+ *+ * vi.resetModules() + dynamic re-import isolates the module-level backend cache+ * between cases (same approach as memoryBackend.test.js).+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const fileBackend = { __name: 'file', listProjects: vi.fn(async () => ['file']) };+const dbBackend = { __name: 'db', listProjects: vi.fn(async () => ['db']) };+const checkHealth = vi.fn();+const ensureSchema = vi.fn(async () => {});+const migrateCreativeDirectorToDB = vi.fn(async () => ({ ok: true }));++vi.mock('./projectsFile.js', () => fileBackend);+vi.mock('./projectsDB.js', () => dbBackend);+vi.mock('../../lib/db.js', () => ({ checkHealth: (...a) => checkHealth(...a), ensureSchema: (...a) => ensureSchema(...a) }));+vi.mock('../../scripts/migrateCreativeDirectorToDB.js', () => ({ migrateCreativeDirectorToDB: (...a) => migrateCreativeDirectorToDB(...a) }));++const ORIG_ENV = { ...process.env };++beforeEach(() => {+ vi.resetModules();+ checkHealth.mockReset();+ ensureSchema.mockClear();+ migrateCreativeDirectorToDB.mockClear();+ process.env = { ...ORIG_ENV };+});++afterEach(() => { process.env = { ...ORIG_ENV }; });++describe('local.js backend selection', () => {+ it('uses the file backend under NODE_ENV=test', async () => {+ process.env.NODE_ENV = 'test';+ delete process.env.MEMORY_BACKEND;+ const local = await import('./local.js');+ expect(await local.listProjects()).toEqual(['file']);+ expect(local.getProjectsBackendName()).toBe('file');+ expect(checkHealth).not.toHaveBeenCalled();+ });++ it('uses the file backend under MEMORY_BACKEND=file even when not in test mode', async () => {+ process.env.NODE_ENV = 'production';+ process.env.MEMORY_BACKEND = 'file';+ const local = await import('./local.js');+ expect(await local.listProjects()).toEqual(['file']);+ expect(local.getProjectsBackendName()).toBe('file');+ });++ it('uses Postgres (ensureSchema + import) when DB is healthy and not in test/file mode', async () => {+ process.env.NODE_ENV = 'production';+ delete process.env.MEMORY_BACKEND;+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });+ const local = await import('./local.js');+ expect(await local.listProjects()).toEqual(['db']);+ expect(local.getProjectsBackendName()).toBe('postgres');+ expect(ensureSchema).toHaveBeenCalledOnce();+ expect(migrateCreativeDirectorToDB).toHaveBeenCalledOnce();+ });++ it('throws when Postgres is required but unreachable', async () => {+ process.env.NODE_ENV = 'production';+ delete process.env.MEMORY_BACKEND;+ checkHealth.mockResolvedValue({ connected: false, error: 'ECONNREFUSED' });+ const local = await import('./local.js');+ await expect(local.listProjects()).rejects.toThrow(/requires PostgreSQL/);+ expect(ensureSchema).not.toHaveBeenCalled();+ });++ it('caches the backend after first selection (one health check)', async () => {+ process.env.NODE_ENV = 'production';+ delete process.env.MEMORY_BACKEND;+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });+ const local = await import('./local.js');+ await local.listProjects();+ await local.getProject('cd-1').catch(() => {});+ expect(checkHealth).toHaveBeenCalledOnce();+ expect(ensureSchema).toHaveBeenCalledOnce();+ });+});diff --git a/server/services/creativeDirector/projectsDB.js b/server/services/creativeDirector/projectsDB.jsnew file mode 100644index 0000000000..fa6c5bc5e7--- /dev/null+++ b/server/services/creativeDirector/projectsDB.js@@ -0,0 +1,151 @@+/**+ * Creative Director — PostgreSQL-backed project store (default backend, #997).+ *+ * One row per project in `creative_director_projects`: id / status / created_at+ * / updated_at as columns, the full record in `data` JSONB. This replaces the+ * monolithic data/creative-director-projects.json (per-project rows remove the+ * whole-file reserialize the orchestrator triggered ≈10× per scene render).+ *+ * Concurrency: the orchestrator has two writers that can touch the SAME project+ * concurrently (sceneRunner's render-progress writes + completionHook's run+ * updates). A read-modify-write spanning two pool round-trips would lose+ * updates, so every mutator runs inside withTransaction + `SELECT … FOR UPDATE`+ * — the row lock serializes concurrent writes to one project without blocking+ * writes to other projects (the per-file queue the JSON backend never had).+ *+ * All mutation semantics live in projectsLogic.js (shared with projectsFile.js)+ * so the two backends can't drift; this module only does row I/O + locking.+ */++import { randomUUID } from 'crypto';+import { query, withTransaction } from '../../lib/db.js';+import { ServerError } from '../../lib/errorHandler.js';+import { createCollection } from '../mediaCollections.js';+import {+ trimRuns,+ buildProjectRecord,+ applyProjectPatch,+ applyTreatment,+ applySceneUpdate,+ appendRun,+ applyRunUpdate,+} from './projectsLogic.js';++// The `data` JSONB is the whole record. `id`/`status`/`createdAt`/`updatedAt`+// are mirrored into columns for indexed reads; on the way out we trust the+// columns (status/updated_at are bumped together with data on every write) but+// return the JSONB so callers see the exact record shape the file backend gave.+function rowToProject(row) {+ if (!row) return null;+ // `data` already holds id/status/createdAt/updatedAt; the columns are a+ // queryable mirror. Return the JSONB verbatim so consumers (and the route+ // slim projection) see an identical shape to the file backend.+ return row.data;+}++async function persist(exec, project) {+ // Cap runs[] at the single write chokepoint (mirrors the file backend's+ // saveAll) so legacy over-cap rows shrink on first write.+ if (Array.isArray(project.runs)) project.runs = trimRuns(project.runs);+ await exec(+ `INSERT INTO creative_director_projects (id, status, data, created_at, updated_at)+ VALUES ($1, $2, $3::jsonb, $4, $5)+ ON CONFLICT (id) DO UPDATE SET+ status = EXCLUDED.status,+ data = EXCLUDED.data,+ updated_at = EXCLUDED.updated_at`,+ [project.id, project.status, JSON.stringify(project), project.createdAt, project.updatedAt],+ );+ return project;+}++export async function listProjects() {+ // created_at ASC preserves the file backend's append order (the UI sorts+ // client-side; recovery + tests don't depend on order, but stable beats random).+ const result = await query(+ `SELECT data FROM creative_director_projects ORDER BY created_at ASC`,+ );+ return result.rows.map(rowToProject);+}++export async function getProject(id) {+ const result = await query(`SELECT data FROM creative_director_projects WHERE id = $1`, [id]);+ return rowToProject(result.rows[0]);+}++export async function createProject(input) {+ const id = `cd-${randomUUID()}`;+ const now = new Date().toISOString();+ const collection = await createCollection({ name: `Creative Director: ${input.name}`, description: `Auto-created for project ${id}` });+ const project = buildProjectRecord(input, { id, now, collectionId: collection.id });+ await persist(query, project);+ console.log(`🎬 Created Creative Director project: ${id} (${input.name})`);+ return project;+}++// Lock the row, apply `mutate(project)`, persist, and return whatever the+// mutator's continuation produces. `mutate` returns `{ project, result, skipPersist? }`.+// `skipPersist` lets a no-op mutation (unknown runId) avoid a wasted row rewrite,+// matching the file backend's "return null without writing". Throws NOT_FOUND+// when the row is absent unless `allowMissing` is set (updateRun's path).+async function withLockedProject(id, mutate, { allowMissing = false } = {}) {+ return withTransaction(async (client) => {+ const sel = await client.query(+ `SELECT data FROM creative_director_projects WHERE id = $1 FOR UPDATE`,+ [id],+ );+ const project = rowToProject(sel.rows[0]);+ if (!project) {+ if (allowMissing) return { __missing: true };+ throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ }+ const { project: next, result, skipPersist } = mutate(project);+ if (!skipPersist) await persist(client.query.bind(client), next);+ return { project: next, result };+ });+}++export async function updateProject(id, patch) {+ const { project } = await withLockedProject(id, (p) => ({ project: applyProjectPatch(p, patch) }));+ return project;+}++export async function deleteProject(id) {+ const result = await query(`DELETE FROM creative_director_projects WHERE id = $1`, [id]);+ if (result.rowCount === 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ return { ok: true };+}++export async function setTreatment(id, treatmentInput) {+ const { project } = await withLockedProject(id, (p) => ({ project: applyTreatment(p, treatmentInput) }));+ return project;+}++export async function updateScene(id, sceneId, patch) {+ const { result } = await withLockedProject(id, (p) => {+ const { project, updated } = applySceneUpdate(p, sceneId, patch);+ return { project, result: updated };+ });+ return result;+}++export async function recordRun(id, runEntry) {+ const { result } = await withLockedProject(id, (p) => {+ const { project, run } = appendRun(p, runEntry);+ return { project, result: run };+ });+ return result;+}++export async function updateRun(id, runId, patch) {+ const outcome = await withLockedProject(id, (p) => {+ const { project, updated } = applyRunUpdate(p, runId, patch);+ // Unknown runId: skip the write entirely so we don't bump updated_at or+ // rewrite the row for a no-op (mirrors the file backend's return null).+ return { project, result: updated, skipPersist: updated === null };+ }, { allowMissing: true });+ // Project row absent → mirror the file backend's "return null" (updateRun is+ // best-effort; callers .catch or null-guard it).+ if (outcome.__missing) return null;+ return outcome.result;+}diff --git a/server/services/creativeDirector/projectsDB.test.js b/server/services/creativeDirector/projectsDB.test.jsnew file mode 100644index 0000000000..8c089e056f--- /dev/null+++ b/server/services/creativeDirector/projectsDB.test.js@@ -0,0 +1,124 @@+/**+ * Postgres-backed round-trip for the Creative Director DB store.+ *+ * Like catalogDB.test.js, this needs a live PostgreSQL with the schema applied.+ * If no DB is reachable (CI, fresh checkout), it SKIPS cleanly rather than+ * failing red. When a DB IS reachable it exercises the full project lifecycle+ * (create → treatment → scene patch → run append/update → delete) and a+ * concurrent-write race (the reason the DB backend uses SELECT … FOR UPDATE),+ * tearing its rows back out so the suite is repeatable.+ *+ * mediaCollections.createCollection is mocked so createProject doesn't need the+ * full media stack — we only care about the project row here.+ */++import { describe, it, expect, afterAll, beforeAll, vi } from 'vitest';+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';++vi.mock('../mediaCollections.js', () => ({+ createCollection: vi.fn(async () => ({ id: 'col-test' })),+}));++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 recheck = await checkHealth().catch(() => ({}));+ // hasSchema is the memory-schema flag; ensureSchema also creates our table.+ // Probe the table directly so we don't couple to the memory schema state.+ const probe = await query(+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'creative_director_projects') AS ok`,+ ).catch(() => ({ rows: [{ ok: false }] }));+ if (probe.rows?.[0]?.ok) dbReady = true;+ else skipReason = 'creative_director_projects table not present';+ }+}++if (!dbReady) console.log(`⏭️ projectsDB.test.js skipped: ${skipReason}`);++const CREATE_INPUT = {+ name: 'DB round-trip', aspectRatio: '1:1', quality: 'draft', modelId: 'm', targetDurationSeconds: 9,+};+const TREATMENT = {+ logline: 'A ball bounces.', synopsis: 'It bounces a lot.',+ scenes: [{ sceneId: 'scene-1', order: 0, intent: 'bounce', prompt: 'a bouncing ball', durationSeconds: 3 }],+};++describe.skipIf(!dbReady)('projectsDB round-trip', () => {+ const created = [];+ let db;+ // Import AFTER the skip gate so a no-DB run never touches the pool.+ beforeAll(async () => { db = await import('./projectsDB.js'); });++ afterAll(async () => {+ for (const id of created) {+ await query(`DELETE FROM creative_director_projects WHERE id = $1`, [id]).catch(() => {});+ }+ await close();+ });++ it('creates, reads back, and lists a project (lossless shape)', async () => {+ const p = await db.createProject(CREATE_INPUT);+ created.push(p.id);+ expect(p.id).toMatch(/^cd-/);+ expect(p.status).toBe('draft');+ expect(p.collectionId).toBe('col-test');++ const fetched = await db.getProject(p.id);+ expect(fetched).toEqual(p);++ const list = await db.listProjects();+ expect(list.some((x) => x.id === p.id)).toBe(true);+ });++ it('applies a treatment and patches a scene', async () => {+ const p = await db.createProject(CREATE_INPUT);+ created.push(p.id);+ const withTreatment = await db.setTreatment(p.id, TREATMENT);+ expect(withTreatment.status).toBe('rendering');+ expect(withTreatment.treatment.scenes[0].status).toBe('pending');++ const updatedScene = await db.updateScene(p.id, 'scene-1', { status: 'rendering', renderedJobId: 'job-1' });+ expect(updatedScene).toMatchObject({ status: 'rendering', renderedJobId: 'job-1' });+ const reread = await db.getProject(p.id);+ expect(reread.treatment.scenes[0].renderedJobId).toBe('job-1');+ });++ it('appends and updates runs; unknown runId returns null', async () => {+ const p = await db.createProject(CREATE_INPUT);+ created.push(p.id);+ const run = await db.recordRun(p.id, { kind: 'treatment', status: 'running' });+ expect(run.runId).toBeTruthy();++ const done = await db.updateRun(p.id, run.runId, { status: 'completed' });+ expect(done.status).toBe('completed');++ const missing = await db.updateRun(p.id, 'no-such-run', { status: 'completed' });+ expect(missing).toBeNull();+ });++ it('deletes a project (and 404s on a missing one)', async () => {+ const p = await db.createProject(CREATE_INPUT);+ const res = await db.deleteProject(p.id);+ expect(res).toEqual({ ok: true });+ expect(await db.getProject(p.id)).toBeNull();+ await expect(db.deleteProject(p.id)).rejects.toThrow(/not found/);+ });++ it('serializes concurrent run appends to the same project (no lost update)', async () => {+ const p = await db.createProject(CREATE_INPUT);+ created.push(p.id);+ // Fire 10 concurrent recordRun calls. With SELECT … FOR UPDATE each one+ // sees the prior append, so all 10 survive; a naive read-modify-write would+ // lose most of them.+ await Promise.all(Array.from({ length: 10 }, (_, i) =>+ db.recordRun(p.id, { runId: `r${i}`, kind: 'evaluate', status: 'running' })));+ const reread = await db.getProject(p.id);+ expect(reread.runs).toHaveLength(10);+ expect(new Set(reread.runs.map((r) => r.runId)).size).toBe(10);+ });+});diff --git a/server/services/creativeDirector/projectsFile.js b/server/services/creativeDirector/projectsFile.jsnew file mode 100644index 0000000000..e393c6ace5--- /dev/null+++ b/server/services/creativeDirector/projectsFile.js@@ -0,0 +1,125 @@+/**+ * Creative Director — file-backed project store (escape-hatch / test backend).+ *+ * Persists to data/creative-director-projects.json (array, atomicWrite). This+ * is the ORIGINAL storage; as of Phase 3 (#997) PostgreSQL is the default and+ * this backend is reachable only via the MEMORY_BACKEND=file escape hatch or+ * NODE_ENV=test — same posture as the memory backend (see memoryBackend.js).+ * The dispatcher in local.js picks between this and projectsDB.js.+ *+ * All mutation semantics live in projectsLogic.js so this backend and the PG+ * backend can't drift; this module only does load/find/persist.+ */++import { join } from 'path';+import { randomUUID } from 'crypto';+import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { createCollection } from '../mediaCollections.js';+import {+ trimRuns,+ buildProjectRecord,+ applyProjectPatch,+ applyTreatment,+ applySceneUpdate,+ appendRun,+ applyRunUpdate,+} from './projectsLogic.js';++const PROJECTS_FILE = join(PATHS.data, 'creative-director-projects.json');++async function loadAll() {+ const raw = await readJSONFile(PROJECTS_FILE, []);+ return Array.isArray(raw) ? raw : [];+}++async function saveAll(projects) {+ // Defense for first-run on a fresh checkout where data/ may not exist yet.+ await ensureDir(PATHS.data);+ // Enforce the runs[] cap at the single write chokepoint so every mutator+ // shrinks legacy over-cap arrays on first save without each having to remember.+ for (const p of projects) {+ if (Array.isArray(p?.runs)) p.runs = trimRuns(p.runs);+ }+ await atomicWrite(PROJECTS_FILE, projects);+}++export async function listProjects() {+ return loadAll();+}++export async function getProject(id) {+ const all = await loadAll();+ return all.find((p) => p.id === id) || null;+}++export async function createProject(input) {+ const id = `cd-${randomUUID()}`;+ const now = new Date().toISOString();+ // Auto-create a media collection scoped to this project. All segment renders+ // + the final stitched output land in here.+ const collection = await createCollection({ name: `Creative Director: ${input.name}`, description: `Auto-created for project ${id}` });+ const project = buildProjectRecord(input, { id, now, collectionId: collection.id });+ const all = await loadAll();+ all.push(project);+ await saveAll(all);+ console.log(`🎬 Created Creative Director project: ${id} (${input.name})`);+ return project;+}++export async function updateProject(id, patch) {+ const all = await loadAll();+ const idx = all.findIndex((p) => p.id === id);+ if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ all[idx] = applyProjectPatch(all[idx], patch);+ await saveAll(all);+ return all[idx];+}++export async function deleteProject(id) {+ const all = await loadAll();+ const next = all.filter((p) => p.id !== id);+ if (next.length === all.length) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ await saveAll(next);+ return { ok: true };+}++export async function setTreatment(id, treatmentInput) {+ const all = await loadAll();+ const idx = all.findIndex((p) => p.id === id);+ if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ all[idx] = applyTreatment(all[idx], treatmentInput);+ await saveAll(all);+ return all[idx];+}++export async function updateScene(id, sceneId, patch) {+ const all = await loadAll();+ const idx = all.findIndex((p) => p.id === id);+ if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const { project, updated } = applySceneUpdate(all[idx], sceneId, patch);+ all[idx] = project;+ await saveAll(all);+ return updated;+}++export async function recordRun(id, runEntry) {+ const all = await loadAll();+ const idx = all.findIndex((p) => p.id === id);+ if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const { project, run } = appendRun(all[idx], runEntry);+ all[idx] = project;+ await saveAll(all);+ return run;+}++export async function updateRun(id, runId, patch) {+ const all = await loadAll();+ const idx = all.findIndex((p) => p.id === id);+ if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const { project, updated } = applyRunUpdate(all[idx], runId, patch);+ if (updated === null) return null;+ all[idx] = project;+ await saveAll(all);+ return updated;+}diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.jsnew file mode 100644index 0000000000..7aa047cfa5--- /dev/null+++ b/server/services/creativeDirector/projectsLogic.js@@ -0,0 +1,182 @@+/**+ * Creative Director — pure record transforms.+ *+ * The file backend (projectsFile.js) and the PostgreSQL backend (projectsDB.js)+ * share the SAME mutation semantics — they differ ONLY in how a project record+ * is loaded and persisted. This module holds the storage-agnostic logic so the+ * two backends can never drift in how a treatment is applied, a scene patched,+ * or a run appended. Each function takes a plain project record and returns the+ * next record (or throws a ServerError on a validation failure), leaving the+ * read/write to the caller.+ */++import { randomUUID } from 'crypto';+import { ServerError } from '../../lib/errorHandler.js';+import { creativeDirectorTreatmentSchema } from '../../lib/validation.js';+import { PROJECT_STATUSES } from '../../lib/creativeDirectorPresets.js';++// Without a cap, runs[] grows unbounded and every load/save (≈10 per scene+// render) parses + serializes a payload whose size scales with cumulative+// renders — O(N²) wall-clock. In-flight runs are load-bearing for orphan/dedup+// detection in completionHook and the boot recovery scan, so trim only drops+// the oldest TERMINAL entries. (DB backend stores runs[] inside the project+// row's JSONB, so the same cap keeps that row from bloating too.)+export const MAX_PERSISTED_RUNS = 200;+const TERMINAL_RUN_STATUSES = new Set(['completed', 'failed']);++export function trimRuns(runs) {+ if (!Array.isArray(runs)) return [];+ if (runs.length <= MAX_PERSISTED_RUNS) return runs;+ let inflightCount = 0;+ for (const r of runs) {+ if (!(r && TERMINAL_RUN_STATUSES.has(r.status))) inflightCount += 1;+ }+ const terminalBudget = Math.max(0, MAX_PERSISTED_RUNS - inflightCount);+ // Walk backwards keeping every in-flight run + the most-recent `terminalBudget`+ // terminal runs, then reverse so original chronological order is preserved+ // (recovery scans + completionHook predicates iterate runs[] and stay readable+ // when it reads chronologically).+ const kept = [];+ let terminalsKept = 0;+ for (let i = runs.length - 1; i >= 0; i -= 1) {+ const r = runs[i];+ const isTerminal = r && TERMINAL_RUN_STATUSES.has(r.status);+ if (!isTerminal) {+ kept.push(r);+ } else if (terminalsKept < terminalBudget) {+ kept.push(r);+ terminalsKept += 1;+ }+ }+ return kept.reverse();+}++/**+ * Build a fresh project record. The caller supplies the already-created media+ * collection id (collection creation is a side effect both backends perform+ * the same way before calling this).+ */+export function buildProjectRecord(input, { id, now, collectionId }) {+ const {+ name, aspectRatio, quality, modelId, targetDurationSeconds,+ styleSpec = '', startingImageFile = null, userStory = null,+ disableAudio = true, autoAcceptScenes = false, sourceIssueId = null,+ } = input;+ return {+ id,+ name,+ status: 'draft',+ createdAt: now,+ updatedAt: now,+ aspectRatio,+ quality,+ modelId,+ targetDurationSeconds,+ styleSpec,+ startingImageFile,+ userStory,+ disableAudio,+ autoAcceptScenes,+ // Optional back-pointer to the pipeline issue that spawned this project.+ // The stitch step uses it to look up `stages.audio.music` and mix it into+ // the final cut. Bare CD projects leave this null and skip the audio-mux.+ sourceIssueId,+ collectionId,+ timelineProjectId: null,+ finalVideoId: null,+ treatment: null,+ runs: [],+ };+}++/** Merge a project metadata patch, validating status. Returns the next record. */+export function applyProjectPatch(project, patch) {+ if (patch.status && !PROJECT_STATUSES.includes(patch.status)) {+ throw new ServerError(`Invalid status: ${patch.status}`, { status: 400, code: 'VALIDATION_ERROR' });+ }+ return { ...project, ...patch, updatedAt: new Date().toISOString() };+}++/**+ * Validate + apply a treatment to a project. Returns the next record. Initializes+ * each scene's runtime fields if the agent didn't supply them, and preserves+ * paused/failed status (otherwise flips the project to 'rendering').+ */+export function applyTreatment(project, treatmentInput) {+ const parsed = creativeDirectorTreatmentSchema.safeParse(treatmentInput);+ if (!parsed.success) {+ throw new ServerError(+ `Treatment validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`,+ { status: 400, code: 'VALIDATION_ERROR' },+ );+ }+ const scenes = parsed.data.scenes.map((s) => ({+ ...s,+ status: s.status || 'pending',+ retryCount: s.retryCount ?? 0,+ renderedJobId: s.renderedJobId ?? null,+ evaluation: s.evaluation ?? null,+ }));+ const nextStatus = (project.status === 'paused' || project.status === 'failed')+ ? project.status+ : 'rendering';+ return {+ ...project,+ treatment: { logline: parsed.data.logline, synopsis: parsed.data.synopsis, scenes },+ status: nextStatus,+ updatedAt: new Date().toISOString(),+ };+}++/**+ * Apply a patch to a single scene. Returns `{ project, updated }` (the next+ * record + the updated scene). Throws if the project has no treatment or the+ * scene id is unknown.+ */+export function applySceneUpdate(project, sceneId, patch) {+ if (!project.treatment?.scenes?.length) {+ throw new ServerError('Project has no treatment yet', { status: 400, code: 'NO_TREATMENT' });+ }+ const sceneIdx = project.treatment.scenes.findIndex((s) => s.sceneId === sceneId);+ if (sceneIdx < 0) throw new ServerError('Scene not found', { status: 404, code: 'NOT_FOUND' });+ const updated = { ...project.treatment.scenes[sceneIdx], ...patch };+ const scenes = project.treatment.scenes.slice();+ scenes[sceneIdx] = updated;+ const next = {+ ...project,+ treatment: { ...project.treatment, scenes },+ updatedAt: new Date().toISOString(),+ };+ return { project: next, updated };+}++/** Append a run row. Returns `{ project, run }` (the next record + the new run). */+export function appendRun(project, runEntry) {+ const run = { startedAt: new Date().toISOString(), ...runEntry, runId: runEntry.runId || randomUUID() };+ const next = {+ ...project,+ runs: trimRuns([...(project.runs || []), run]),+ updatedAt: new Date().toISOString(),+ };+ return { project: next, run };+}++/**+ * Patch an existing run by runId. Returns `{ project, updated }`; `updated` is+ * null (and `project` unchanged) when the runId is unknown — mirrors the file+ * backend's "return null, don't throw" contract.+ */+export function applyRunUpdate(project, runId, patch) {+ const runs = project.runs || [];+ const runIdx = runs.findIndex((r) => r.runId === runId);+ if (runIdx < 0) return { project, updated: null };+ const updated = { ...runs[runIdx], ...patch };+ const nextRuns = runs.slice();+ nextRuns[runIdx] = updated;+ const next = {+ ...project,+ runs: trimRuns(nextRuns),+ updatedAt: new Date().toISOString(),+ };+ return { project: next, updated };+}diff --git a/server/services/creativeDirector/projectsLogic.test.js b/server/services/creativeDirector/projectsLogic.test.jsnew file mode 100644index 0000000000..5c71cc277d--- /dev/null+++ b/server/services/creativeDirector/projectsLogic.test.js@@ -0,0 +1,138 @@+/**+ * Pure record-transform tests for the Creative Director storage logic shared by+ * the file + Postgres backends. No I/O — these lock the mutation semantics the+ * two backends MUST agree on (status preservation, scene patching, runs[] cap).+ */++import { describe, it, expect } from 'vitest';+import {+ MAX_PERSISTED_RUNS,+ trimRuns,+ buildProjectRecord,+ applyProjectPatch,+ applyTreatment,+ applySceneUpdate,+ appendRun,+ applyRunUpdate,+} from './projectsLogic.js';++const VALID_TREATMENT = {+ logline: 'A cat finds a hat.',+ synopsis: 'Then puts it on.',+ scenes: [{ sceneId: 'scene-1', order: 0, intent: 'Cat enters', prompt: 'A cat walks in', durationSeconds: 4 }],+};++describe('buildProjectRecord', () => {+ it('produces a draft project with the supplied collection id and null pointers', () => {+ const p = buildProjectRecord(+ { name: 'X', aspectRatio: '1:1', quality: 'draft', modelId: 'm', targetDurationSeconds: 9 },+ { id: 'cd-1', now: '2026-06-07T00:00:00.000Z', collectionId: 'col-1' },+ );+ expect(p).toMatchObject({+ id: 'cd-1', name: 'X', status: 'draft', collectionId: 'col-1',+ timelineProjectId: null, finalVideoId: null, treatment: null, runs: [],+ });+ });+});++describe('applyProjectPatch', () => {+ it('merges the patch and bumps updatedAt', () => {+ const next = applyProjectPatch({ id: 'cd-1', status: 'draft', updatedAt: 'old' }, { status: 'planning' });+ expect(next.status).toBe('planning');+ expect(next.updatedAt).not.toBe('old');+ });+ it('throws on an invalid status', () => {+ expect(() => applyProjectPatch({ id: 'cd-1' }, { status: 'bogus' })).toThrow(/Invalid status/);+ });+});++describe('applyTreatment — status preservation', () => {+ it('preserves paused status', () => {+ const next = applyTreatment({ id: 'cd-1', status: 'paused' }, VALID_TREATMENT);+ expect(next.status).toBe('paused');+ expect(next.treatment.scenes[0].status).toBe('pending');+ });+ it('preserves failed status', () => {+ expect(applyTreatment({ id: 'cd-1', status: 'failed' }, VALID_TREATMENT).status).toBe('failed');+ });+ it('flips planning → rendering', () => {+ expect(applyTreatment({ id: 'cd-1', status: 'planning' }, VALID_TREATMENT).status).toBe('rendering');+ });+ it('initializes scene runtime fields', () => {+ const next = applyTreatment({ id: 'cd-1', status: 'planning' }, VALID_TREATMENT);+ expect(next.treatment.scenes[0]).toMatchObject({ status: 'pending', retryCount: 0, renderedJobId: null, evaluation: null });+ });+ it('throws on an invalid treatment', () => {+ expect(() => applyTreatment({ id: 'cd-1', status: 'planning' }, { logline: '', synopsis: '', scenes: [] })).toThrow(/Treatment validation failed/);+ });+});++describe('applySceneUpdate', () => {+ const base = () => ({ id: 'cd-1', status: 'rendering', treatment: { logline: 'l', synopsis: 's', scenes: [{ sceneId: 'scene-1', order: 0, status: 'pending' }] } });+ it('patches the matching scene and returns it', () => {+ const { project, updated } = applySceneUpdate(base(), 'scene-1', { status: 'rendering', renderedJobId: 'job-1' });+ expect(updated).toMatchObject({ status: 'rendering', renderedJobId: 'job-1' });+ expect(project.treatment.scenes[0].renderedJobId).toBe('job-1');+ });+ it('does not mutate the input project (immutable update)', () => {+ const input = base();+ applySceneUpdate(input, 'scene-1', { status: 'accepted' });+ expect(input.treatment.scenes[0].status).toBe('pending');+ });+ it('throws when the project has no treatment', () => {+ expect(() => applySceneUpdate({ id: 'cd-1' }, 'scene-1', {})).toThrow(/no treatment/);+ });+ it('throws when the scene id is unknown', () => {+ expect(() => applySceneUpdate(base(), 'scene-9', {})).toThrow(/Scene not found/);+ });+});++describe('appendRun / applyRunUpdate', () => {+ it('appends a run with a generated runId + startedAt', () => {+ const { project, run } = appendRun({ id: 'cd-1', runs: [] }, { kind: 'treatment', status: 'running' });+ expect(run.runId).toBeTruthy();+ expect(run.startedAt).toBeTruthy();+ expect(project.runs).toHaveLength(1);+ });+ it('honors a supplied runId', () => {+ const { run } = appendRun({ id: 'cd-1', runs: [] }, { runId: 'fixed', kind: 'evaluate', status: 'running' });+ expect(run.runId).toBe('fixed');+ });+ it('patches an existing run by id', () => {+ const start = appendRun({ id: 'cd-1', runs: [] }, { runId: 'r1', status: 'running' });+ const { project, updated } = applyRunUpdate(start.project, 'r1', { status: 'completed' });+ expect(updated.status).toBe('completed');+ expect(project.runs[0].status).toBe('completed');+ });+ it('returns updated=null and the unchanged project for an unknown runId', () => {+ const input = { id: 'cd-1', runs: [{ runId: 'r1', status: 'running' }] };+ const { project, updated } = applyRunUpdate(input, 'nope', { status: 'completed' });+ expect(updated).toBeNull();+ expect(project).toBe(input);+ });+});++describe('trimRuns', () => {+ it('is a no-op under the cap', () => {+ const runs = [{ runId: 'a', status: 'completed' }];+ expect(trimRuns(runs)).toBe(runs);+ });+ it('caps terminal runs but keeps every in-flight run', () => {+ const terminal = Array.from({ length: MAX_PERSISTED_RUNS + 50 }, (_, i) => ({ runId: `t${i}`, status: 'completed' }));+ const inflight = [{ runId: 'live', status: 'running' }];+ const trimmed = trimRuns([...terminal, ...inflight]);+ expect(trimmed.length).toBe(MAX_PERSISTED_RUNS);+ expect(trimmed.some((r) => r.runId === 'live')).toBe(true);+ });+ it('preserves chronological order after trimming', () => {+ const runs = Array.from({ length: MAX_PERSISTED_RUNS + 10 }, (_, i) => ({ runId: `t${i}`, status: 'completed' }));+ const trimmed = trimRuns(runs);+ // The most-recent MAX runs, still in ascending order.+ expect(trimmed[0].runId).toBe('t10');+ expect(trimmed[trimmed.length - 1].runId).toBe(`t${runs.length - 1}`);+ });+ it('returns [] for non-array input', () => {+ expect(trimRuns(undefined)).toEqual([]);+ expect(trimRuns(null)).toEqual([]);+ });+});