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

address review (claude+codex): lossless import, marker-on-rename, ensureSchema race

Adam Eivy3a76eb225f01
diff --git a/server/lib/db.js b/server/lib/db.js
index ed073556a4..469cb2fc85 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -87,12 +87,30 @@ export async function checkHealth() {
}
}
+// In-flight dedup for ensureSchema(). At boot, two independent fire-and-forget
+// callers can race: the Creative Director recovery scan (which lazily selects
+// the PG backend and calls ensureSchema) and the boot DB gate. Running the
+// idempotent DDL list concurrently can intermittently error or deadlock on
+// Postgres system catalogs (concurrent CREATE TABLE/INDEX IF NOT EXISTS contend
+// on pg_type / pg_class). Sharing one in-flight promise serializes them; it's
+// cleared on settle so a deliberate later call (the gate runs it twice) still
+// re-applies (cheap — ~30 no-op parses on an up-to-date DB).
+let ensureSchemaInFlight = null;
+
/**
* Apply idempotent schema upgrades to an existing database.
* Each statement uses IF NOT EXISTS so it's safe to run on every startup.
* Add new ALTER TABLE statements here when the schema evolves.
+ *
+ * Concurrent calls share a single in-flight execution (see ensureSchemaInFlight).
*/
export async function ensureSchema() {
+ if (ensureSchemaInFlight) return ensureSchemaInFlight;
+ ensureSchemaInFlight = ensureSchemaImpl().finally(() => { ensureSchemaInFlight = null; });
+ return ensureSchemaInFlight;
+}
+
+async function ensureSchemaImpl() {
const upgrades = [
`ALTER TABLE memories ADD COLUMN IF NOT EXISTS sync_sequence BIGSERIAL`,
`ALTER TABLE memories ADD COLUMN IF NOT EXISTS origin_instance_id VARCHAR(36)`,
@@ -510,11 +528,14 @@ export async function ensureSchema() {
EXECUTE 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.
+ // the full record lives in `data` JSONB, with status/created_at/updated_at
+ // mirrored into columns (kept in lockstep on every write) for future
+ // queries. `listProjects` sorts by created_at; nothing filters status yet
+ // (the recovery scan filters in JS), so no status/updated_at index — an
+ // unused index is just write amplification. 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',
@@ -522,8 +543,6 @@ export async function ensureSchema() {
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.sql
index 7e6816680e..f0adc24900 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -562,11 +562,15 @@ CREATE TRIGGER trg_catalog_tag_updated_at
-- ===========================================================================
-- 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.
+-- One row per project. The full project record — treatment, scenes, runs[],
+-- and the misc back-pointers (collectionId / timelineProjectId / finalVideoId
+-- / sourceIssueId) — lives in `data` JSONB. `status` / `created_at` /
+-- `updated_at` are mirrored into columns (kept in lockstep with the JSONB on
+-- every write) so future queries CAN filter/sort on them without a JSONB
+-- expression; `listProjects` sorts by `created_at`. No index on status/
+-- updated_at yet — nothing queries them today (the recovery scan filters
+-- p.status in JS over the loaded record), and an unused index is just write
+-- amplification. Add one alongside the query that needs it.
--
-- Why JSONB and not normalized scene/run tables: no code queries INTO scenes
-- or runs relationally (the orchestrator loads the whole project, mutates a
@@ -588,5 +592,3 @@ CREATE TABLE IF NOT EXISTS creative_director_projects (
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.js
index c543d67951..b89dd4ca2d 100644
--- a/server/scripts/migrateCreativeDirectorToDB.js
+++ b/server/scripts/migrateCreativeDirectorToDB.js
@@ -16,8 +16,11 @@
* - 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.
+ * - The import is LOSSLESS: each project is copied verbatim, runs[] included.
+ * Trimming the runs[] cap is the LIVE store's job (projectsDB.persist /
+ * projectsFile.saveAll both call trimRuns on the next write) — doing it here
+ * would silently drop run history the file still holds. A legacy over-cap
+ * array shrinks on the project's first post-import write instead.
*
* 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
@@ -30,7 +33,6 @@ 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';
@@ -85,7 +87,8 @@ export async function migrateCreativeDirectorToDB() {
skipped += 1;
continue;
}
- if (Array.isArray(project.runs)) project.runs = trimRuns(project.runs);
+ // Import verbatim — including the full runs[] history. The cap is enforced
+ // by the live store on the next write, not here, so the migration is lossless.
const result = await query(
`INSERT INTO creative_director_projects (id, status, data, created_at, updated_at)
VALUES ($1, $2, $3::jsonb, $4, $5)
@@ -105,9 +108,20 @@ export async function migrateCreativeDirectorToDB() {
// 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).
+ //
+ // The marker is written ONLY if the rename succeeds. If the rename fails, the
+ // live file is still in place — stamping the marker would leave Postgres
+ // authoritative while data/creative-director-projects.json lingers, so a
+ // rollback or MEMORY_BACKEND=file boot would silently read stale pre-migration
+ // state, and the marker would block any retry. Leaving the marker unwritten
+ // makes the next boot retry the (idempotent) import + rename instead.
+ let renamed = true;
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`);
+ renamed = false;
+ console.warn(`⚠️ CD→DB import: imported ${imported} row(s) but could not rename ${LEGACY_FILENAME} aside (${err.message}) — NOT stamping marker; will retry the rename next boot`);
});
+ if (!renamed) return { ok: false, reason: 'rename-failed', imported, skipped };
+
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.js
index df73896f8f..e85bbded3b 100644
--- a/server/scripts/migrateCreativeDirectorToDB.test.js
+++ b/server/scripts/migrateCreativeDirectorToDB.test.js
@@ -15,6 +15,9 @@ vi.mock('../lib/fileUtils.js', () => ({
PATHS: { data: '/fake/data' },
}));
+// Rename can be made to fail per-test via `renameShouldFail`.
+let renameShouldFail = false;
+
vi.mock('fs/promises', () => ({
readFile: vi.fn(async (path) => {
if (!(path in files)) {
@@ -26,6 +29,7 @@ vi.mock('fs/promises', () => ({
}),
writeFile: vi.fn(async (path, content) => { files[path] = content; }),
rename: vi.fn(async (from, to) => {
+ if (renameShouldFail) throw new Error('EACCES: rename failed');
files[to] = files[from];
delete files[from];
}),
@@ -38,7 +42,7 @@ 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 });
+ table.set(id, { id, status, data: JSON.parse(data) });
return { rowCount: 1, rows: [] };
}
return { rowCount: 0, rows: [] };
@@ -54,6 +58,7 @@ const { migrateCreativeDirectorToDB } = await import('./migrateCreativeDirectorT
beforeEach(() => {
files = {};
table = new Map();
+ renameShouldFail = false;
query.mockClear();
});
@@ -90,12 +95,33 @@ describe('migrateCreativeDirectorToDB', () => {
});
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}' });
+ 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}');
+ expect(table.get('cd-1').data).toEqual({ fresher: true });
+ });
+
+ it('imports run history LOSSLESSLY — does not trim a >200-run project', async () => {
+ // Regression: the importer must NOT apply the live-store runs[] cap, or
+ // existing installs with long CD histories silently lose run rows on migrate.
+ const runs = Array.from({ length: 350 }, (_, i) => ({ runId: `r${i}`, status: 'completed' }));
+ files[LEGACY] = JSON.stringify([{ id: 'cd-1', status: 'complete', runs }]);
+ const result = await migrateCreativeDirectorToDB();
+ expect(result.imported).toBe(1);
+ expect(table.get('cd-1').data.runs).toHaveLength(350);
+ });
+
+ it('does NOT stamp the marker when the legacy rename fails (retries next boot)', async () => {
+ files[LEGACY] = JSON.stringify([{ id: 'cd-1', status: 'draft' }]);
+ renameShouldFail = true;
+ const result = await migrateCreativeDirectorToDB();
+ expect(result).toMatchObject({ ok: false, reason: 'rename-failed', imported: 1 });
+ // Row landed, but legacy file still present and marker NOT written → retry.
+ expect(table.has('cd-1')).toBe(true);
+ expect(files[LEGACY]).toBeTruthy();
+ expect(files[MARKER]).toBeUndefined();
});
it('skips malformed records (missing id) without aborting the import', async () => {
diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.js
index 57ce1ab595..ba0f2a81bc 100644
--- a/server/services/creativeDirector/local.js
+++ b/server/services/creativeDirector/local.js
@@ -50,7 +50,7 @@ async function selectBackend() {
// 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)');
+ throw new Error('Creative Director requires PostgreSQL — run `npm run setup:db` (dev/test only: set PGMODE=file in .env; the launcher maps it to MEMORY_BACKEND=file for the unsupported file backend)');
}
await ensureSchema();
const { migrateCreativeDirectorToDB } = await import('../../scripts/migrateCreativeDirectorToDB.js');
diff --git a/server/services/creativeDirector/projectsDB.js b/server/services/creativeDirector/projectsDB.js
index fa6c5bc5e7..0c7095bf70 100644
--- a/server/services/creativeDirector/projectsDB.js
+++ b/server/services/creativeDirector/projectsDB.js
@@ -31,10 +31,10 @@ import {
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.
+// The `data` JSONB is the whole record. status/created_at/updated_at are
+// mirrored into columns (kept in lockstep with the JSONB on every write) for
+// future queries, but reads always return `data` verbatim so callers see the
+// exact record shape the file backend gave — the columns are never read back.
function rowToProject(row) {
if (!row) return null;
// `data` already holds id/status/createdAt/updatedAt; the columns are a