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

refactor: share project store scaffolding (#5700)

Adam Eivyfc416797602b
diff --git a/server/lib/README.md b/server/lib/README.md
index 92523bf207..7f89638e7f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -107,6 +107,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `storyBuilderSteps.js` | Unified Story Builder ordered step definitions + helpers (`STEPS`, `STEP_IDS`, `STEP_STATUSES`, `isValidStepId`, `stepIndex`). |
| `streamLines.js` | `createLineReader(onLine, {splitRe?, maxCarry?})` + `createOutputTail({budget?})` — buffered chunk→line splitter for child-process stdout/stderr. Carries the partial trailing line across `data` chunks and `flush()`es the final unterminated line on `close`; carry clamp guards a newline-less runaway stream. One reader per stream (a shared buffer corrupts marker lines). `splitRe: /[\r\n]+/` handles torch/tqdm bare-`\r` progress redraws. `createOutputTail` is the sibling rolling buffer of recent lines (char-budgeted, decoration-only lines skipped so an ASCII-art banner cannot push the real error out) that turns "exited with code 1" into what the tool actually printed — used by `streamingSpawn.js`. |
| `storyBuilderIntegrity.js` | Pure staleness hashing for the Story Builder (`hashUpstream`, `computeStaleSteps`, `computeSyncDrift`). |
+| `projectStoreKit.js` | Shared project-store sync normalization, LWW batch decisions, and tombstone selection for file and PostgreSQL adapters. |
| `canonPrompt.js` | Per-kind field-precedence rules; SHORT/RICH/PREVIEW spec tables; `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` / `descriptorForCanonEntry`. |
| `scenePrompt.js` | Scene-prompt composer + bible matchers (chars/places/objects in text). |
| `proseExportSettings.js` | Per-series prose-export settings (#2181): `sanitizeProseExportSettings` + `resolveExportSettings` + `TRIM_SIZES`/`INTERIOR_FONTS` for the manuscript/ePub/PDF exports. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 0d4d6bd05a..42f6a93a28 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -199,6 +199,7 @@ export * from './borderKey.js';
export * from './boundedStateMap.js';
export * from './collectionStore.js';
export * from './conflictJournal.js';
+export * from './projectStoreKit.js';
export * from './createKeyCachedQueue.js';
export * from './createNewestWinsGuard.js';
export * from './dataRoot.js';
diff --git a/server/lib/projectStoreKit.js b/server/lib/projectStoreKit.js
new file mode 100644
index 0000000000..2c03058689
--- /dev/null
+++ b/server/lib/projectStoreKit.js
@@ -0,0 +1,57 @@
+import { sanitizeSoftDeleteFields } from './syncWire.js';
+
+/**
+ * Field-shape-agnostic project normalization shared by every project domain.
+ */
+export function sanitizeProjectForSync(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ if (typeof raw.id !== 'string' || !raw.id) return null;
+ const createdAt = typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString();
+ const updatedAt = typeof raw.updatedAt === 'string' ? raw.updatedAt : createdAt;
+ const { deleted, deletedAt } = sanitizeSoftDeleteFields(raw);
+ return { ...raw, createdAt, updatedAt, deleted, deletedAt };
+}
+
+/**
+ * Apply a sync batch without performing persistence or conflict-journal I/O.
+ * The returned change records tell a backend exactly which side effects to run.
+ */
+export function applySyncMerge({ byId, remoteProjects, source, kind, mergeProjectRecord: mergeRecord }) {
+ const mergedById = new Map(byId);
+ const changes = [];
+ if (!Array.isArray(remoteProjects)) return { byId: mergedById, changes };
+
+ for (const remote of remoteProjects) {
+ const local = mergedById.get(remote?.id) || null;
+ const { next, inserted, remoteWins, changed } = mergeRecord(local, remote);
+ if (!next || (!inserted && (!remoteWins || !changed))) continue;
+ mergedById.set(next.id, next);
+ changes.push({ kind, id: next.id, local, remote: next, source, inserted });
+ }
+
+ return { byId: mergedById, changes };
+}
+
+/** Select expired tombstones without mutating the supplied project array. */
+export function selectExpiredTombstones(all, olderThanMs) {
+ if (!Number.isFinite(olderThanMs)) return { survivors: [...all], prunedIds: [] };
+ const survivors = [];
+ const prunedIds = [];
+ for (const project of all) {
+ const deletedAtMs = project?.deleted ? Date.parse(project.deletedAt || '') : NaN;
+ if (project?.deleted && Number.isFinite(deletedAtMs) && deletedAtMs < olderThanMs) {
+ prunedIds.push(project.id);
+ } else {
+ survivors.push(project);
+ }
+ }
+ return { survivors, prunedIds };
+}
+
+/** Bind the record kind once for a project store factory. */
+export function makeSyncKind(kind) {
+ return {
+ applySyncMerge: (options) => applySyncMerge({ ...options, kind }),
+ selectExpiredTombstones,
+ };
+}
diff --git a/server/services/creativeDirector/projectsDB.js b/server/services/creativeDirector/projectsDB.js
index 1ea65288fd..50773c7781 100644
--- a/server/services/creativeDirector/projectsDB.js
+++ b/server/services/creativeDirector/projectsDB.js
@@ -1,139 +1,26 @@
-/**
- * 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.
- */
+/** Creative Director PostgreSQL project store. */
-import { randomUUID } from 'crypto';
-import { query, withTransaction } from '../../lib/db.js';
-import { ServerError } from '../../lib/errorHandler.js';
+import { query } from '../../lib/db.js';
import { createCollection } from '../mediaCollections.js';
-import {
- trimRuns,
- mirrorStatus,
- mirrorTimestamp,
- buildProjectRecord,
- applyProjectPatch,
- applyTreatment,
- applyPlan,
- applyPlanStepUpdate,
- applySceneUpdate,
- appendRun,
- applyRunUpdate,
- mergeProjectRecord,
-} from './projectsLogic.js';
-import {
- maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
- withBaseHashFlushBatch,
-} from '../../lib/conflictJournal.js';
+import { createProjectDbStore } from '../projectDbStore.js';
+import * as logic from './projectsLogic.js';
-// 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 and are never read back; reads return `data` verbatim so
-// callers see the exact record shape the file backend gave. The lone exception
-// is the `id` primary key — see rowToProject.
-function rowToProject(row) {
- if (!row) return null;
- // Verbatim, EXCEPT `id`: a legacy row can carry a `data` blob with no id
- // while the PK column — what every lookup here already matches on — has one.
- // An id-less record is unaddressable downstream (the UI keys its grid on it,
- // and sanitizeProjectForSync drops it from peer pushes), so backfill from the
- // authoritative column. Repairing on read rather than by migration is
- // deliberate: no current write path can produce the shape (persist() now
- // asserts the invariant), so this only heals blobs left by older code, and it
- // does so on every install without one having to run a backfill. The stored
- // blob catches up on the record's next write. Healthy rows short-circuit on
- // the first check and are still returned verbatim, without copying.
- if (row.data && !row.data.id) return { ...row.data, id: row.id };
- return row.data;
-}
-
-async function persist(exec, project) {
- // The id lives in BOTH the PK column and the `data` blob, and rowToProject
- // has to repair blobs that lost it. Assert the invariant at the one write
- // chokepoint so a future refactor that drops `id` from the record fails
- // loudly here instead of being silently healed on every subsequent read.
- if (!project?.id) throw new ServerError('Cannot persist a Creative Director project without an id', { status: 500, code: 'PROJECT_ID_MISSING' });
- // 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);
- // `data` is written verbatim (lossless); the typed mirror columns are
- // sanitized so a malformed status/timestamp on a legacy record can't make
- // the INSERT throw (which, during boot init, would block the whole backend).
- const now = new Date().toISOString();
- const createdAt = mirrorTimestamp(project.createdAt, now);
- await exec(
- `INSERT INTO creative_director_projects (id, status, data, created_at, updated_at, deleted, deleted_at)
- VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7)
- ON CONFLICT (id) DO UPDATE SET
- status = EXCLUDED.status,
- data = EXCLUDED.data,
- updated_at = EXCLUDED.updated_at,
- deleted = EXCLUDED.deleted,
- deleted_at = EXCLUDED.deleted_at`,
- [
- project.id,
- mirrorStatus(project.status),
- JSON.stringify(project),
- createdAt,
- mirrorTimestamp(project.updatedAt, createdAt),
- project.deleted === true,
- mirrorTimestamp(project.deletedAt, null),
- ],
- );
- return project;
-}
-
-export async function listProjects({ includeDeleted = false } = {}) {
- // 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 = includeDeleted
- ? await query(`SELECT id, data FROM creative_director_projects ORDER BY created_at ASC`)
- : await query(`SELECT id, data FROM creative_director_projects WHERE deleted = FALSE ORDER BY created_at ASC`);
- return result.rows.map(rowToProject);
-}
+const store = createProjectDbStore({
+ table: 'creative_director_projects',
+ kind: 'creativeDirectorProject',
+ idPrefix: 'cd',
+ logEmoji: '🎬',
+ logLabel: 'Creative Director',
+ logic,
+});
-export async function getProject(id, { includeDeleted = false } = {}) {
- const result = await query(`SELECT id, data FROM creative_director_projects WHERE id = $1`, [id]);
- const project = rowToProject(result.rows[0]);
- if (!project) return null;
- return includeDeleted || !project.deleted ? project : null;
-}
+const { withLockedProject, rowToProject } = store;
-/**
- * Batch fetch by id (#4148) — one round trip for a known id set, so a caller
- * that only needs a handful of projects (the Creative Commission detail page
- * resolving its runs' renders) doesn't pull the whole table. Unknown ids are
- * simply absent from the result; order matches listProjects (created_at ASC).
- */
-export async function getProjectsByIds(ids, { includeDeleted = false } = {}) {
- const wanted = [...new Set((ids || []).filter(Boolean))];
- if (wanted.length === 0) return [];
- const result = includeDeleted
- ? await query(`SELECT id, data FROM creative_director_projects WHERE id = ANY($1) ORDER BY created_at ASC`, [wanted])
- : await query(`SELECT id, data FROM creative_director_projects WHERE id = ANY($1) AND deleted = FALSE ORDER BY created_at ASC`, [wanted]);
- return result.rows.map(rowToProject);
-}
+export const {
+ persist, listProjects, getProject, getProjectsByIds, listProjectIds,
+ updateProject, deleteProject, mergeProjectsFromSync, pruneTombstonedProjects,
+} = store;
-/**
- * Every LIVE project a given Creative Commission spawned, oldest first. The
- * commission↔project link the stop/re-pin paths run on: the commission's own run
- * ledger is capped (MAX_PERSISTED_RUNS) and never sees a project a plan step
- * spawned indirectly, so a wedged project can fall out of it entirely.
- */
export async function listProjectsByCommissionId(commissionId) {
if (!commissionId) return [];
const result = await query(
@@ -144,178 +31,55 @@ export async function listProjectsByCommissionId(commissionId) {
return result.rows.map(rowToProject);
}
-/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
-export async function listProjectIds({ includeDeleted = false } = {}) {
- const result = includeDeleted
- ? await query(`SELECT id FROM creative_director_projects`)
- : await query(`SELECT id FROM creative_director_projects WHERE deleted = FALSE`);
- return result.rows.map((r) => r.id);
-}
-
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}`, source: 'auto' });
- 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 id, data FROM creative_director_projects WHERE id = $1 FOR UPDATE`,
- [id],
- );
- const project = rowToProject(sel.rows[0]);
- // A tombstoned project (#1564 soft-delete) is treated as gone for every
- // user-facing mutator — without this, a PATCH / scene / treatment update
- // after deletion would resurrect the row, bump updatedAt, and re-push a
- // modified tombstone to peers while getProject/deleteProject 404 the same id.
- // mergeProjectsFromSync (peer tombstone apply) bypasses this path via its own
- // persist, so receiving a tombstone still works.
- if (!project || project.deleted) {
- 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) {
- // Soft-delete tombstone (#1564) so the deletion federates and an out-of-date
- // peer can't resurrect the project via the LWW merge. The row stays; `deleted`
- // flips and `updatedAt`/`deletedAt` stamp now so the tombstone wins on merge.
- return withTransaction(async (client) => {
- const sel = await client.query(
- `SELECT id, data FROM creative_director_projects WHERE id = $1 FOR UPDATE`,
- [id],
- );
- const current = rowToProject(sel.rows[0]);
- if (!current || current.deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- const now = new Date().toISOString();
- const next = { ...current, deleted: true, deletedAt: now, updatedAt: now };
- await persist(client.query.bind(client), next);
- return { ok: true };
- });
-}
-
-/**
- * Merge an incoming batch of project records from a peer (per-record push). Each
- * record's read-modify-write runs inside `withTransaction` + `SELECT … FOR
- * UPDATE` so a concurrent local edit can't lose to (or clobber) the merge. LWW
- * on `updatedAt` (tombstone-aware) via the shared `mergeProjectRecord` decision
- * — identical to the file backend so the two can't drift. Mirrors
- * `mergeAuthorsFromSync`: seeds/advances the conflict-journal base hash and
- * journals the about-to-be-overwritten local version when remote wins
- * (best-effort, never throws into the merge). Returns `{ applied, count }`.
- */
-export async function mergeProjectsFromSync(remoteProjects, { source = { via: 'sync', peerId: null } } = {}) {
- if (!Array.isArray(remoteProjects)) return { applied: false, count: 0 };
- let changed = 0;
- for (const remote of remoteProjects) {
- const applied = await withTransaction(async (client) => {
- const sel = await client.query(`SELECT id, data FROM creative_director_projects WHERE id = $1 FOR UPDATE`, [remote?.id]);
- const local = rowToProject(sel.rows[0]);
- const { next, inserted, remoteWins, changed: didChange } = mergeProjectRecord(local, remote);
- if (!next) return false; // malformed remote → dropped
- if (inserted) {
- await persist(client.query.bind(client), next);
- await setSyncBaseHash('creativeDirectorProject', next.id, contentHashForRecord('creativeDirectorProject', next));
- return true;
- }
- // local wins, OR remote won but is byte-identical to local (already agree).
- if (!remoteWins || !didChange) return false;
- await maybeJournalBeforeOverwrite({ kind: 'creativeDirectorProject', id: next.id, local, remote: next, source });
- await persist(client.query.bind(client), next);
- await setSyncBaseHash('creativeDirectorProject', next.id, contentHashForRecord('creativeDirectorProject', next));
- return true;
+ return store.createProject(input, async ({ id }) => {
+ const collection = await createCollection({
+ name: `Creative Director: ${input.name}`,
+ description: `Auto-created for project ${id}`,
+ source: 'auto',
});
- if (applied) changed += 1;
- }
- await flushBaseHashes();
- if (changed === 0) return { applied: false, count: 0 };
- return { applied: true, count: changed };
-}
-
-/**
- * Hard-remove tombstoned projects whose deletedAt is older than the cutoff.
- * Called by tombstoneGc once every subscribed peer has acked the deletion.
- * Evicts each pruned project's conflict-journal base hash (mirrors
- * pruneTombstonedAuthors).
- */
-export async function pruneTombstonedProjects(olderThanMs) {
- if (!Number.isFinite(olderThanMs)) return { pruned: 0 };
- const cutoffIso = new Date(olderThanMs).toISOString();
- const { rows } = await query(
- `DELETE FROM creative_director_projects
- WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1
- RETURNING id`,
- [cutoffIso],
- );
- // Coalesce the per-project base-hash evictions into ONE disk write.
- await withBaseHashFlushBatch(async () => {
- for (const r of rows) await deleteSyncBaseHash('creativeDirectorProject', r.id);
+ return { collectionId: collection.id };
});
- return { pruned: rows.length };
}
export async function setTreatment(id, treatmentInput) {
- const { project } = await withLockedProject(id, (p) => ({ project: applyTreatment(p, treatmentInput) }));
+ const { project } = await withLockedProject(id, (current) => ({ project: logic.applyTreatment(current, treatmentInput) }));
return project;
}
export async function setPlan(id, planInput) {
- const { project } = await withLockedProject(id, (p) => ({ project: applyPlan(p, planInput) }));
+ const { project } = await withLockedProject(id, (current) => ({ project: logic.applyPlan(current, planInput) }));
return project;
}
export async function updatePlanStep(id, stepId, patch) {
- const { result } = await withLockedProject(id, (p) => {
- const { project, updated } = applyPlanStepUpdate(p, stepId, patch);
+ const { result } = await withLockedProject(id, (current) => {
+ const { project, updated } = logic.applyPlanStepUpdate(current, stepId, patch);
return { project, result: updated };
});
return result;
}
export async function updateScene(id, sceneId, patch) {
- const { result } = await withLockedProject(id, (p) => {
- const { project, updated } = applySceneUpdate(p, sceneId, patch);
+ const { result } = await withLockedProject(id, (current) => {
+ const { project, updated } = logic.applySceneUpdate(current, 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);
+ const { result } = await withLockedProject(id, (current) => {
+ const { project, run } = logic.appendRun(current, 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).
+ const outcome = await withLockedProject(id, (current) => {
+ const { project, updated } = logic.applyRunUpdate(current, runId, patch);
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;
+ return outcome.__missing ? null : outcome.result;
}
diff --git a/server/services/creativeDirector/projectsDB.test.js b/server/services/creativeDirector/projectsDB.test.js
index 4350fe37ac..1ce151258a 100644
--- a/server/services/creativeDirector/projectsDB.test.js
+++ b/server/services/creativeDirector/projectsDB.test.js
@@ -19,6 +19,17 @@ vi.mock('../mediaCollections.js', () => ({
createCollection: vi.fn(async () => ({ id: 'col-test' })),
}));
+const syncCounter = vi.hoisted(() => ({ baseHash: 0 }));
+vi.mock('../../lib/conflictJournal.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ maybeJournalBeforeOverwrite: vi.fn(async () => {}),
+ setSyncBaseHash: vi.fn(async () => { syncCounter.baseHash += 1; }),
+ flushBaseHashes: vi.fn(async () => {}),
+ };
+});
+
let dbReady = false;
let skipReason = '';
{
@@ -98,6 +109,27 @@ describe.skipIf(!dbReady)('projectsDB round-trip', () => {
expect(all.find((p) => p.name === 'Legacy row')?.id).toBe(id);
});
+ it('rejects persistence when the project id is missing', async () => {
+ await expect(db.persist(query, { name: 'Missing id' })).rejects.toMatchObject({ code: 'PROJECT_ID_MISSING' });
+ });
+
+ it('same-updatedAt re-push does not persist or rewrite the base hash', async () => {
+ const remote = {
+ id: 'cd-same-timestamp', name: 'Same', status: 'draft', runs: [],
+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
+ deleted: false, deletedAt: null,
+ };
+ created.push(remote.id);
+ await db.mergeProjectsFromSync([remote]);
+ const before = await query(`SELECT xmin::text AS version FROM creative_director_projects WHERE id = $1`, [remote.id]);
+ syncCounter.baseHash = 0;
+
+ expect(await db.mergeProjectsFromSync([remote])).toEqual({ applied: false, count: 0 });
+ const after = await query(`SELECT xmin::text AS version FROM creative_director_projects WHERE id = $1`, [remote.id]);
+ expect(after.rows[0].version).toBe(before.rows[0].version);
+ expect(syncCounter.baseHash).toBe(0);
+ });
+
// #4148 — the batch-by-id read the Creative Commission detail page uses so it
// doesn't list every project on the install.
it('batch-fetches by id, skipping unknown ids and tombstoned projects', async () => {
@@ -147,6 +179,7 @@ describe.skipIf(!dbReady)('projectsDB round-trip', () => {
const res = await db.deleteProject(p.id);
expect(res).toEqual({ ok: true });
expect(await db.getProject(p.id)).toBeNull();
+ await expect(db.updateProject(p.id, { name: 'Zombie' })).rejects.toMatchObject({ code: 'NOT_FOUND' });
await expect(db.deleteProject(p.id)).rejects.toThrow(/not found/);
});
diff --git a/server/services/creativeDirector/projectsFile.js b/server/services/creativeDirector/projectsFile.js
index eec4a2fde4..be6957d03b 100644
--- a/server/services/creativeDirector/projectsFile.js
+++ b/server/services/creativeDirector/projectsFile.js
@@ -1,249 +1,84 @@
-/**
- * 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.
- */
+/** Creative Director file-backed project store (test/development escape hatch). */
import { join } from 'path';
-import { randomUUID } from 'crypto';
-import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils.js';
-import { ServerError } from '../../lib/errorHandler.js';
+import { PATHS } from '../../lib/fileUtils.js';
import { createCollection } from '../mediaCollections.js';
-import {
- trimRuns,
- buildProjectRecord,
- applyProjectPatch,
- applyTreatment,
- applyPlan,
- applyPlanStepUpdate,
- applySceneUpdate,
- appendRun,
- applyRunUpdate,
- mergeProjectRecord,
-} from './projectsLogic.js';
-import {
- maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
- withBaseHashFlushBatch,
-} from '../../lib/conflictJournal.js';
+import { createProjectFileStore } from '../projectFileStore.js';
+import * as logic from './projectsLogic.js';
+
+const store = createProjectFileStore({
+ file: join(PATHS.data, 'creative-director-projects.json'),
+ kind: 'creativeDirectorProject',
+ idPrefix: 'cd',
+ logEmoji: '🎬',
+ logLabel: 'Creative Director',
+ logic,
+});
+
+export const {
+ loadAll, saveAll, loadAllAndIndex, listProjects, getProject,
+ getProjectsByIds, listProjectIds, updateProject, deleteProject,
+ mergeProjectsFromSync, pruneTombstonedProjects,
+} = store;
-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({ includeDeleted = false } = {}) {
- const all = await loadAll();
- return includeDeleted ? all : all.filter((p) => !p.deleted);
-}
-
-export async function getProject(id, { includeDeleted = false } = {}) {
- const all = await loadAll();
- const found = all.find((p) => p.id === id);
- if (!found) return null;
- return includeDeleted || !found.deleted ? found : null;
-}
-
-/**
- * Batch fetch by id (#4148) — mirrors the PG backend's single-round-trip lookup
- * so a caller with a known id set doesn't have to list every project. Unknown
- * ids are simply absent from the result; order follows the stored append order.
- */
-export async function getProjectsByIds(ids, { includeDeleted = false } = {}) {
- const wanted = new Set((ids || []).filter(Boolean));
- if (wanted.size === 0) return [];
- const all = await loadAll();
- return all.filter((p) => wanted.has(p.id) && (includeDeleted || !p.deleted));
-}
-
-/** Every LIVE project a given Creative Commission spawned — mirrors the PG backend. */
export async function listProjectsByCommissionId(commissionId) {
if (!commissionId) return [];
const all = await loadAll();
- return all.filter((p) => !p.deleted && p.commissionId === commissionId);
-}
-
-/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
-export async function listProjectIds({ includeDeleted = false } = {}) {
- const all = await loadAll();
- return (includeDeleted ? all : all.filter((p) => !p.deleted)).map((p) => p.id);
+ return all.filter((project) => !project.deleted && project.commissionId === commissionId);
}
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}`, source: 'auto' });
- 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);
- // Missing OR tombstoned (#1564 soft-delete) → gone for user-facing mutators, so a
- // post-delete write can't resurrect + re-push a modified tombstone.
- if (idx < 0 || all[idx].deleted) 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) {
- // Soft-delete tombstone (#1564) — mirrors projectsDB.deleteProject so the two
- // backends can't drift. The record stays so the deletion can federate.
- const all = await loadAll();
- const idx = all.findIndex((p) => p.id === id);
- if (idx < 0 || all[idx].deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- const now = new Date().toISOString();
- all[idx] = { ...all[idx], deleted: true, deletedAt: now, updatedAt: now };
- await saveAll(all);
- return { ok: true };
-}
-
-/**
- * File-backend mirror of projectsDB.js `mergeProjectsFromSync` — LWW-per-id
- * (tombstone-aware) via the shared `mergeProjectRecord` decision so the two
- * backends can't drift. Single load → per-record merge → single save.
- */
-export async function mergeProjectsFromSync(remoteProjects, { source = { via: 'sync', peerId: null } } = {}) {
- if (!Array.isArray(remoteProjects)) return { applied: false, count: 0 };
- const all = await loadAll();
- const byId = new Map(all.map((p) => [p.id, p]));
- let changed = 0;
- for (const remote of remoteProjects) {
- const local = byId.get(remote?.id) || null;
- const { next, inserted, remoteWins, changed: didChange } = mergeProjectRecord(local, remote);
- if (!next) continue;
- if (inserted) {
- byId.set(next.id, next);
- await setSyncBaseHash('creativeDirectorProject', next.id, contentHashForRecord('creativeDirectorProject', next));
- changed += 1;
- continue;
- }
- if (!remoteWins || !didChange) continue;
- await maybeJournalBeforeOverwrite({ kind: 'creativeDirectorProject', id: next.id, local, remote: next, source });
- byId.set(next.id, next);
- await setSyncBaseHash('creativeDirectorProject', next.id, contentHashForRecord('creativeDirectorProject', next));
- changed += 1;
- }
- if (changed > 0) await saveAll([...byId.values()]);
- await flushBaseHashes();
- if (changed === 0) return { applied: false, count: 0 };
- return { applied: true, count: changed };
-}
-
-/**
- * Hard-remove tombstoned projects whose deletedAt is older than the cutoff.
- * Mirrors projectsDB.js `pruneTombstonedProjects`; evicts each pruned project's
- * base hash.
- */
-export async function pruneTombstonedProjects(olderThanMs) {
- if (!Number.isFinite(olderThanMs)) return { pruned: 0 };
- const all = await loadAll();
- const survivors = [];
- const pruned = [];
- for (const p of all) {
- const ms = p.deleted ? Date.parse(p.deletedAt || '') : NaN;
- if (p.deleted && Number.isFinite(ms) && ms < olderThanMs) pruned.push(p.id);
- else survivors.push(p);
- }
- if (pruned.length === 0) return { pruned: 0 };
- await saveAll(survivors);
- // Coalesce the per-project base-hash evictions into ONE disk write.
- await withBaseHashFlushBatch(async () => {
- for (const id of pruned) await deleteSyncBaseHash('creativeDirectorProject', id);
+ return store.createProject(input, async ({ id }) => {
+ const collection = await createCollection({
+ name: `Creative Director: ${input.name}`,
+ description: `Auto-created for project ${id}`,
+ source: 'auto',
+ });
+ return { collectionId: collection.id };
});
- return { pruned: pruned.length };
}
export async function setTreatment(id, treatmentInput) {
- const all = await loadAll();
- const idx = all.findIndex((p) => p.id === id);
- // Missing OR tombstoned (#1564 soft-delete) → gone for user-facing mutators, so a
- // post-delete write can't resurrect + re-push a modified tombstone.
- if (idx < 0 || all[idx].deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- all[idx] = applyTreatment(all[idx], treatmentInput);
+ const { all, idx } = await loadAllAndIndex(id);
+ all[idx] = logic.applyTreatment(all[idx], treatmentInput);
await saveAll(all);
return all[idx];
}
export async function setPlan(id, planInput) {
- const all = await loadAll();
- const idx = all.findIndex((p) => p.id === id);
- // Missing OR tombstoned (#1564 soft-delete) → gone for user-facing mutators, so a
- // post-delete write can't resurrect + re-push a modified tombstone.
- if (idx < 0 || all[idx].deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- all[idx] = applyPlan(all[idx], planInput);
+ const { all, idx } = await loadAllAndIndex(id);
+ all[idx] = logic.applyPlan(all[idx], planInput);
await saveAll(all);
return all[idx];
}
export async function updatePlanStep(id, stepId, patch) {
- const all = await loadAll();
- const idx = all.findIndex((p) => p.id === id);
- if (idx < 0 || all[idx].deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- const { project, updated } = applyPlanStepUpdate(all[idx], stepId, patch);
+ const { all, idx } = await loadAllAndIndex(id);
+ const { project, updated } = logic.applyPlanStepUpdate(all[idx], stepId, patch);
all[idx] = project;
await saveAll(all);
return updated;
}
export async function updateScene(id, sceneId, patch) {
- const all = await loadAll();
- const idx = all.findIndex((p) => p.id === id);
- // Missing OR tombstoned (#1564 soft-delete) → gone for user-facing mutators, so a
- // post-delete write can't resurrect + re-push a modified tombstone.
- if (idx < 0 || all[idx].deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- const { project, updated } = applySceneUpdate(all[idx], sceneId, patch);
+ const { all, idx } = await loadAllAndIndex(id);
+ const { project, updated } = logic.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);
- // Missing OR tombstoned (#1564 soft-delete) → gone for user-facing mutators, so a
- // post-delete write can't resurrect + re-push a modified tombstone.
- if (idx < 0 || all[idx].deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- const { project, run } = appendRun(all[idx], runEntry);
+ const { all, idx } = await loadAllAndIndex(id);
+ const { project, run } = logic.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);
- // Missing OR tombstoned (#1564 soft-delete) → gone for user-facing mutators, so a
- // post-delete write can't resurrect + re-push a modified tombstone.
- if (idx < 0 || all[idx].deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- const { project, updated } = applyRunUpdate(all[idx], runId, patch);
+ const { all, idx } = await loadAllAndIndex(id);
+ const { project, updated } = logic.applyRunUpdate(all[idx], runId, patch);
if (updated === null) return null;
all[idx] = project;
await saveAll(all);
diff --git a/server/services/creativeDirector/projectsFile.test.js b/server/services/creativeDirector/projectsFile.test.js
index b425143475..d9ea7df554 100644
--- a/server/services/creativeDirector/projectsFile.test.js
+++ b/server/services/creativeDirector/projectsFile.test.js
@@ -17,10 +17,19 @@ import { tmpdir } from 'os';
import { join } from 'path';
const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'cd-projects-file-test-'));
+const writeCounter = vi.hoisted(() => ({ project: 0, baseHash: 0 }));
vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
const actual = await importOriginal();
- return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT },
+ atomicWrite: async (path, data) => {
+ if (typeof path === 'string' && path.endsWith('creative-director-projects.json')) writeCounter.project += 1;
+ if (typeof path === 'string' && path.endsWith('sync_base_hashes.json')) writeCounter.baseHash += 1;
+ return actual.atomicWrite(path, data);
+ },
+ };
});
// createProject would otherwise spin up the full media stack; we only test the
// federation paths here, none of which create a collection.
@@ -36,6 +45,8 @@ function reset() {
rmSync(join(TEST_DATA_ROOT, 'sharing'), { recursive: true, force: true });
rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });
cj.__resetBaseHashCacheForTests();
+ writeCounter.project = 0;
+ writeCounter.baseHash = 0;
}
beforeEach(reset);
afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
@@ -92,6 +103,16 @@ describe('projectsFile federation merge', () => {
expect((await file.getProject('cd-1')).styleSpec).toBe('keep');
});
+ it('same-updatedAt re-push is a no-op without project or base-hash writes', async () => {
+ const remote = project('cd-1');
+ await file.mergeProjectsFromSync([remote]);
+ writeCounter.project = 0;
+ writeCounter.baseHash = 0;
+
+ expect(await file.mergeProjectsFromSync([remote])).toEqual({ applied: false, count: 0 });
+ expect(writeCounter).toEqual({ project: 0, baseHash: 0 });
+ });
+
it('soft-delete tombstones the project (excluded from live reads, present with includeDeleted)', async () => {
await file.mergeProjectsFromSync([project('cd-1')]);
await file.deleteProject('cd-1');
diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.js
index d4a1986a8a..d018b636e1 100644
--- a/server/services/creativeDirector/projectsLogic.js
+++ b/server/services/creativeDirector/projectsLogic.js
@@ -16,8 +16,10 @@ import { creativeDirectorTreatmentSchema, creativeDirectorPlanSchema } from '../
import { PROJECT_STATUSES, PLAN_STEP_TERMINAL_SUCCESS } from '../../lib/creativeDirectorPresets.js';
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
import { pickLlmRoutePinLayer } from '../../lib/llmRoutePin.js';
-import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
import { localImageFilename } from '../../lib/localImageFilename.js';
+import { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';
+
+export { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';
const isStr = (v) => typeof v === 'string';
@@ -140,6 +142,12 @@ export function trimRuns(runs) {
return kept.reverse();
}
+/** Normalize a project at either storage backend's write chokepoint. */
+export function beforeSave(project) {
+ if (!Array.isArray(project?.runs)) return project;
+ return { ...project, runs: trimRuns(project.runs) };
+}
+
// Postgres `status` column is VARCHAR(32) and created_at/updated_at are
// TIMESTAMPTZ. A legacy/hand-edited project with an over-long status or a
// malformed timestamp would make the INSERT throw — and because the PG backend
@@ -280,15 +288,6 @@ export function startingImageFilename(startingImageFile) {
* (`updatedAt`) and the soft-delete trio are normalized so the wire/hash shape
* is stable regardless of on-disk key position.
*/
-export function sanitizeProjectForSync(raw) {
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
- if (!isStr(raw.id) || !raw.id) return null;
- const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();
- const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;
- const { deleted, deletedAt } = sanitizeSoftDeleteFields(raw);
- return { ...raw, createdAt, updatedAt, deleted, deletedAt };
-}
-
/**
* LWW merge decision for one incoming project record against the local copy —
* mirrors `mergeAuthorRecord` (services/authors/logic.js):
diff --git a/server/services/musicVideo/projectsDB.js b/server/services/musicVideo/projectsDB.js
index f865ee23d1..65387764dc 100644
--- a/server/services/musicVideo/projectsDB.js
+++ b/server/services/musicVideo/projectsDB.js
@@ -1,108 +1,38 @@
-/**
- * Music Video — PostgreSQL-backed project store (default backend, #1760).
- *
- * One row per project in `music_video_projects`: id / status / created_at /
- * updated_at mirrored as columns, the full record in `data` JSONB. Mirrors the
- * Creative Director store (#997): every mutator runs inside withTransaction +
- * `SELECT … FOR UPDATE` so a blur-save and an explicit action against the same
- * project serialize instead of losing an update. Mutation semantics live in
- * projectsLogic.js (shared with projectsFile.js) so the two can't drift.
- */
+/** Music Video PostgreSQL project store. */
import { randomUUID } from 'crypto';
-import { query, withTransaction } from '../../lib/db.js';
+import { withTransaction } from '../../lib/db.js';
import { ServerError } from '../../lib/errorHandler.js';
-import {
- mirrorStatus,
- mirrorTimestamp,
- buildProjectRecord,
- cloneProjectRecord,
- applyProjectPatch,
- setAudioAnalysis,
- setMidiTranscription,
- addScene,
- addScenes,
- applySceneUpdate,
- removeScene,
- reorderScenes,
- mergeProjectRecord,
-} from './projectsLogic.js';
-import {
- maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
- withBaseHashFlushBatch,
-} from '../../lib/conflictJournal.js';
+import { createProjectDbStore } from '../projectDbStore.js';
+import * as logic from './projectsLogic.js';
-// `data` JSONB is the whole record; status/created_at/updated_at are a queryable
-// mirror kept in lockstep but never read back — reads return `data` verbatim so
-// callers see the exact shape the file backend gives.
-function rowToProject(row) {
- return row ? row.data : null;
-}
-
-async function persist(exec, project) {
- const now = new Date().toISOString();
- const createdAt = mirrorTimestamp(project.createdAt, now);
- await exec(
- `INSERT INTO music_video_projects (id, status, data, created_at, updated_at, deleted, deleted_at)
- VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7)
- ON CONFLICT (id) DO UPDATE SET
- status = EXCLUDED.status,
- data = EXCLUDED.data,
- updated_at = EXCLUDED.updated_at,
- deleted = EXCLUDED.deleted,
- deleted_at = EXCLUDED.deleted_at`,
- [
- project.id,
- mirrorStatus(project.status),
- JSON.stringify(project),
- createdAt,
- mirrorTimestamp(project.updatedAt, createdAt),
- project.deleted === true,
- mirrorTimestamp(project.deletedAt, null),
- ],
- );
- return project;
-}
+const store = createProjectDbStore({
+ table: 'music_video_projects',
+ kind: 'musicVideoProject',
+ idPrefix: 'mv',
+ logEmoji: '🎞️',
+ logLabel: 'Music Video',
+ logic,
+});
-export async function listProjects({ includeDeleted = false } = {}) {
- const result = includeDeleted
- ? await query(`SELECT data FROM music_video_projects ORDER BY created_at ASC`)
- : await query(`SELECT data FROM music_video_projects WHERE deleted = FALSE ORDER BY created_at ASC`);
- return result.rows.map(rowToProject);
-}
-
-export async function getProject(id, { includeDeleted = false } = {}) {
- const result = await query(`SELECT data FROM music_video_projects WHERE id = $1`, [id]);
- const project = rowToProject(result.rows[0]);
- if (!project) return null;
- return includeDeleted || !project.deleted ? project : null;
-}
+const { withLockedProject, rowToProject } = store;
-/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
-export async function listProjectIds({ includeDeleted = false } = {}) {
- const result = includeDeleted
- ? await query(`SELECT id FROM music_video_projects`)
- : await query(`SELECT id FROM music_video_projects WHERE deleted = FALSE`);
- return result.rows.map((r) => r.id);
-}
-
-export async function createProject(input) {
- const id = `mv-${randomUUID()}`;
- const now = new Date().toISOString();
- const project = buildProjectRecord(input, { id, now });
- await persist(query, project);
- console.log(`🎞️ Created Music Video project: ${id} (${input.name})`);
- return project;
-}
+export const {
+ persist, listProjects, getProject, getProjectsByIds, listProjectIds, createProject,
+ updateProject, deleteProject, mergeProjectsFromSync, pruneTombstonedProjects,
+} = store;
export async function cloneProject(id, options = {}) {
return withTransaction(async (client) => {
- const sel = await client.query(`SELECT data FROM music_video_projects WHERE id = $1 FOR SHARE`, [id]);
- const source = rowToProject(sel.rows[0]);
+ const selected = await client.query(
+ `SELECT id, data FROM music_video_projects WHERE id = $1 FOR SHARE`,
+ [id],
+ );
+ const source = rowToProject(selected.rows[0]);
if (!source || source.deleted) {
throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
}
- const clone = cloneProjectRecord(source, {
+ const clone = logic.cloneProjectRecord(source, {
...options,
id: `mv-${randomUUID()}`,
now: new Date().toISOString(),
@@ -112,145 +42,46 @@ export async function cloneProject(id, options = {}) {
});
}
-// Lock the row, apply `mutate(project)`, persist, return the mutator's result.
-// Throws NOT_FOUND when the row is absent or tombstoned (a post-delete write
-// must not resurrect the row).
-async function withLockedProject(id, mutate) {
- return withTransaction(async (client) => {
- const sel = await client.query(`SELECT data FROM music_video_projects WHERE id = $1 FOR UPDATE`, [id]);
- const project = rowToProject(sel.rows[0]);
- if (!project || project.deleted) {
- throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- }
- const { project: next, result } = mutate(project);
- 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) {
- return withTransaction(async (client) => {
- const sel = await client.query(`SELECT data FROM music_video_projects WHERE id = $1 FOR UPDATE`, [id]);
- const current = rowToProject(sel.rows[0]);
- if (!current || current.deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- const now = new Date().toISOString();
- const next = { ...current, deleted: true, deletedAt: now, updatedAt: now };
- await persist(client.query.bind(client), next);
- return { ok: true };
- });
-}
-
-/**
- * Merge an incoming batch of project records from a peer (per-record push). Each
- * record's read-modify-write runs inside `withTransaction` + `SELECT … FOR
- * UPDATE` so a concurrent local edit can't lose to (or clobber) the merge. LWW
- * on `updatedAt` (tombstone-aware) via the shared `mergeProjectRecord` decision —
- * identical to the file backend so the two can't drift. Seeds/advances the
- * conflict-journal base hash and journals the about-to-be-overwritten local
- * version when remote wins (best-effort). Mirrors creativeDirector/projectsDB.js.
- * Returns `{ applied, count }`.
- */
-export async function mergeProjectsFromSync(remoteProjects, { source = { via: 'sync', peerId: null } } = {}) {
- if (!Array.isArray(remoteProjects)) return { applied: false, count: 0 };
- let changed = 0;
- for (const remote of remoteProjects) {
- const applied = await withTransaction(async (client) => {
- const sel = await client.query(`SELECT data FROM music_video_projects WHERE id = $1 FOR UPDATE`, [remote?.id]);
- const local = rowToProject(sel.rows[0]);
- const { next, inserted, remoteWins, changed: didChange } = mergeProjectRecord(local, remote);
- if (!next) return false; // malformed remote → dropped
- if (inserted) {
- await persist(client.query.bind(client), next);
- await setSyncBaseHash('musicVideoProject', next.id, contentHashForRecord('musicVideoProject', next));
- return true;
- }
- // local wins, OR remote won but is byte-identical to local (already agree).
- if (!remoteWins || !didChange) return false;
- await maybeJournalBeforeOverwrite({ kind: 'musicVideoProject', id: next.id, local, remote: next, source });
- await persist(client.query.bind(client), next);
- await setSyncBaseHash('musicVideoProject', next.id, contentHashForRecord('musicVideoProject', next));
- return true;
- });
- if (applied) changed += 1;
- }
- await flushBaseHashes();
- if (changed === 0) return { applied: false, count: 0 };
- return { applied: true, count: changed };
-}
-
-/**
- * Hard-remove tombstoned projects whose deletedAt is older than the cutoff.
- * Called by tombstoneGc once every subscribed peer has acked the deletion.
- * Evicts each pruned project's conflict-journal base hash. Mirrors
- * creativeDirector/projectsDB.js `pruneTombstonedProjects`.
- */
-export async function pruneTombstonedProjects(olderThanMs) {
- if (!Number.isFinite(olderThanMs)) return { pruned: 0 };
- const cutoffIso = new Date(olderThanMs).toISOString();
- const { rows } = await query(
- `DELETE FROM music_video_projects
- WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1
- RETURNING id`,
- [cutoffIso],
- );
- await withBaseHashFlushBatch(async () => {
- for (const r of rows) await deleteSyncBaseHash('musicVideoProject', r.id);
- });
- return { pruned: rows.length };
-}
-
export async function setProjectAnalysis(id, analysis) {
- const { project } = await withLockedProject(id, (p) => ({ project: setAudioAnalysis(p, analysis) }));
+ const { project } = await withLockedProject(id, (current) => ({ project: logic.setAudioAnalysis(current, analysis) }));
return project;
}
export async function setProjectMidiTranscription(id, midi) {
- const { project } = await withLockedProject(id, (p) => ({ project: setMidiTranscription(p, midi) }));
+ const { project } = await withLockedProject(id, (current) => ({ project: logic.setMidiTranscription(current, midi) }));
return project;
}
export async function addProjectScene(id, sceneInput) {
- const { result } = await withLockedProject(id, (p) => {
- const { project, scene } = addScene(p, sceneInput);
+ const { result } = await withLockedProject(id, (current) => {
+ const { project, scene } = logic.addScene(current, sceneInput);
return { project, result: scene };
});
return result;
}
-/**
- * Bulk-append scenes (the autonomous planner, #1855) — one locked read/write.
- * Returns `{ project, scenes }` (the freshly-persisted project, read under
- * the same `SELECT ... FOR UPDATE` that wrote it — not a pre-mutation
- * snapshot) so a caller composing a response never has to re-fetch or risk
- * overwriting a concurrent edit with stale state.
- */
export async function addProjectScenes(id, sceneInputs) {
- const { project, result: scenes } = await withLockedProject(id, (p) => {
- const { project, scenes } = addScenes(p, sceneInputs);
- return { project, result: scenes };
+ const { project, result: scenes } = await withLockedProject(id, (current) => {
+ const outcome = logic.addScenes(current, sceneInputs);
+ return { project: outcome.project, result: outcome.scenes };
});
return { project, scenes };
}
export async function updateScene(id, sceneId, patch) {
- const { result } = await withLockedProject(id, (p) => {
- const { project, updated } = applySceneUpdate(p, sceneId, patch);
+ const { result } = await withLockedProject(id, (current) => {
+ const { project, updated } = logic.applySceneUpdate(current, sceneId, patch);
return { project, result: updated };
});
return result;
}
export async function deleteScene(id, sceneId) {
- const { project } = await withLockedProject(id, (p) => ({ project: removeScene(p, sceneId) }));
+ const { project } = await withLockedProject(id, (current) => ({ project: logic.removeScene(current, sceneId) }));
return project;
}
export async function reorderProjectScenes(id, orderedIds) {
- const { project } = await withLockedProject(id, (p) => ({ project: reorderScenes(p, orderedIds) }));
+ const { project } = await withLockedProject(id, (current) => ({ project: logic.reorderScenes(current, orderedIds) }));
return project;
}
diff --git a/server/services/musicVideo/projectsDB.test.js b/server/services/musicVideo/projectsDB.test.js
index cd93353445..b1ba707a0a 100644
--- a/server/services/musicVideo/projectsDB.test.js
+++ b/server/services/musicVideo/projectsDB.test.js
@@ -80,6 +80,44 @@ describe.skipIf(!dbReady)('music video projects DB adapter', () => {
await close();
});
+ it('backfills a missing JSONB id from the primary-key column', async () => {
+ const id = `${PRUNE_PREFIX}legacy-no-json-id`;
+ await query(
+ `INSERT INTO music_video_projects (id, status, data, created_at, updated_at, deleted)
+ VALUES ($1, 'draft', $2::jsonb, now(), now(), FALSE)`,
+ [id, JSON.stringify({ name: 'Legacy row', status: 'draft', scenes: [] })],
+ );
+
+ expect(await db.getProject(id)).toMatchObject({ id, name: 'Legacy row' });
+ expect((await db.listProjects()).find((item) => item.name === 'Legacy row')?.id).toBe(id);
+ });
+
+ it('rejects persistence when the project id is missing', async () => {
+ await expect(db.persist(query, { name: 'Missing id' })).rejects.toMatchObject({ code: 'PROJECT_ID_MISSING' });
+ });
+
+ it('rejects a mutator against a tombstoned project', async () => {
+ const created = await db.createProject({ name: 'Doomed' });
+ await db.deleteProject(created.id);
+ await expect(db.updateProject(created.id, { name: 'Zombie' })).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('same-updatedAt re-push does not persist or rewrite the base hash', async () => {
+ const remote = {
+ id: `${PRUNE_PREFIX}same-timestamp`, name: 'Same', status: 'draft', scenes: [],
+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
+ deleted: false, deletedAt: null,
+ };
+ await db.mergeProjectsFromSync([remote]);
+ const before = await query(`SELECT xmin::text AS version FROM music_video_projects WHERE id = $1`, [remote.id]);
+ testState.writeCounter.baseHash = 0;
+
+ expect(await db.mergeProjectsFromSync([remote])).toEqual({ applied: false, count: 0 });
+ const after = await query(`SELECT xmin::text AS version FROM music_video_projects WHERE id = $1`, [remote.id]);
+ expect(after.rows[0].version).toBe(before.rows[0].version);
+ expect(testState.writeCounter.baseHash).toBe(0);
+ });
+
it('pruneTombstonedProjects batches base-hash eviction for multiple tombstones', async () => {
const oldOne = project(`${PRUNE_PREFIX}old-1`, '2000-01-01T00:00:00.000Z');
const oldTwo = project(`${PRUNE_PREFIX}old-2`, '2000-01-02T00:00:00.000Z');
diff --git a/server/services/musicVideo/projectsFile.js b/server/services/musicVideo/projectsFile.js
index 279216d085..aaa923cdf6 100644
--- a/server/services/musicVideo/projectsFile.js
+++ b/server/services/musicVideo/projectsFile.js
@@ -1,80 +1,32 @@
-/**
- * Music Video — file-backed project store (escape-hatch / test backend).
- *
- * Persists to data/music-video-projects.json (array, atomicWrite). Reachable
- * only via MEMORY_BACKEND=file or NODE_ENV=test — PostgreSQL (projectsDB.js) is
- * the default. All mutation semantics live in projectsLogic.js so this backend
- * and the PG backend can't drift; this module only does load/find/persist.
- */
+/** Music Video file-backed project store (test/development escape hatch). */
import { join } from 'path';
import { randomUUID } from 'crypto';
-import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils.js';
+import { PATHS } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
-import {
- buildProjectRecord,
- cloneProjectRecord,
- applyProjectPatch,
- setAudioAnalysis,
- setMidiTranscription,
- addScene,
- addScenes,
- applySceneUpdate,
- removeScene,
- reorderScenes,
- mergeProjectRecord,
-} from './projectsLogic.js';
-import {
- maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
- withBaseHashFlushBatch,
-} from '../../lib/conflictJournal.js';
-
-const PROJECTS_FILE = join(PATHS.data, 'music-video-projects.json');
-
-async function loadAll() {
- const raw = await readJSONFile(PROJECTS_FILE, []);
- return Array.isArray(raw) ? raw : [];
-}
-
-async function saveAll(projects) {
- await ensureDir(PATHS.data);
- await atomicWrite(PROJECTS_FILE, projects);
-}
-
-export async function listProjects({ includeDeleted = false } = {}) {
- const all = await loadAll();
- return includeDeleted ? all : all.filter((p) => !p.deleted);
-}
-
-export async function getProject(id, { includeDeleted = false } = {}) {
- const all = await loadAll();
- const found = all.find((p) => p.id === id);
- if (!found) return null;
- return includeDeleted || !found.deleted ? found : null;
-}
-
-/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
-export async function listProjectIds({ includeDeleted = false } = {}) {
- const all = await loadAll();
- return (includeDeleted ? all : all.filter((p) => !p.deleted)).map((p) => p.id);
-}
-
-export async function createProject(input) {
- const id = `mv-${randomUUID()}`;
- const now = new Date().toISOString();
- const project = buildProjectRecord(input, { id, now });
- const all = await loadAll();
- all.push(project);
- await saveAll(all);
- console.log(`🎞️ Created Music Video project: ${id} (${input.name})`);
- return project;
-}
+import { createProjectFileStore } from '../projectFileStore.js';
+import * as logic from './projectsLogic.js';
+
+const store = createProjectFileStore({
+ file: join(PATHS.data, 'music-video-projects.json'),
+ kind: 'musicVideoProject',
+ idPrefix: 'mv',
+ logEmoji: '🎞️',
+ logLabel: 'Music Video',
+ logic,
+});
+
+export const {
+ loadAll, saveAll, loadAllAndIndex, listProjects, getProject, getProjectsByIds,
+ listProjectIds, createProject, updateProject, deleteProject, mergeProjectsFromSync,
+ pruneTombstonedProjects,
+} = store;
export async function cloneProject(id, options = {}) {
const all = await loadAll();
const source = all.find((project) => project.id === id && !project.deleted);
if (!source) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- const clone = cloneProjectRecord(source, {
+ const clone = logic.cloneProjectRecord(source, {
...options,
id: `mv-${randomUUID()}`,
now: new Date().toISOString(),
@@ -84,115 +36,31 @@ export async function cloneProject(id, options = {}) {
return clone;
}
-// Locate a live (non-tombstoned) project for a user-facing mutator, or throw 404.
-async function loadAllAndIndex(id) {
- const all = await loadAll();
- const idx = all.findIndex((p) => p.id === id);
- if (idx < 0 || all[idx].deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- return { all, idx };
-}
-
-export async function updateProject(id, patch) {
- const { all, idx } = await loadAllAndIndex(id);
- all[idx] = applyProjectPatch(all[idx], patch);
- await saveAll(all);
- return all[idx];
-}
-
-export async function deleteProject(id) {
- const { all, idx } = await loadAllAndIndex(id);
- const now = new Date().toISOString();
- all[idx] = { ...all[idx], deleted: true, deletedAt: now, updatedAt: now };
- await saveAll(all);
- return { ok: true };
-}
-
-/**
- * File-backend mirror of projectsDB.js `mergeProjectsFromSync` — LWW-per-id
- * (tombstone-aware) via the shared `mergeProjectRecord` decision so the two
- * backends can't drift. Single load → per-record merge → single save.
- */
-export async function mergeProjectsFromSync(remoteProjects, { source = { via: 'sync', peerId: null } } = {}) {
- if (!Array.isArray(remoteProjects)) return { applied: false, count: 0 };
- const all = await loadAll();
- const byId = new Map(all.map((p) => [p.id, p]));
- let changed = 0;
- for (const remote of remoteProjects) {
- const local = byId.get(remote?.id) || null;
- const { next, inserted, remoteWins, changed: didChange } = mergeProjectRecord(local, remote);
- if (!next) continue;
- if (inserted) {
- byId.set(next.id, next);
- await setSyncBaseHash('musicVideoProject', next.id, contentHashForRecord('musicVideoProject', next));
- changed += 1;
- continue;
- }
- if (!remoteWins || !didChange) continue;
- await maybeJournalBeforeOverwrite({ kind: 'musicVideoProject', id: next.id, local, remote: next, source });
- byId.set(next.id, next);
- await setSyncBaseHash('musicVideoProject', next.id, contentHashForRecord('musicVideoProject', next));
- changed += 1;
- }
- if (changed > 0) await saveAll([...byId.values()]);
- await flushBaseHashes();
- if (changed === 0) return { applied: false, count: 0 };
- return { applied: true, count: changed };
-}
-
-/**
- * Hard-remove tombstoned projects whose deletedAt is older than the cutoff.
- * Mirrors projectsDB.js `pruneTombstonedProjects`; evicts each pruned project's
- * base hash.
- */
-export async function pruneTombstonedProjects(olderThanMs) {
- if (!Number.isFinite(olderThanMs)) return { pruned: 0 };
- const all = await loadAll();
- const survivors = [];
- const pruned = [];
- for (const p of all) {
- const ms = p.deleted ? Date.parse(p.deletedAt || '') : NaN;
- if (p.deleted && Number.isFinite(ms) && ms < olderThanMs) pruned.push(p.id);
- else survivors.push(p);
- }
- if (pruned.length === 0) return { pruned: 0 };
- await saveAll(survivors);
- await withBaseHashFlushBatch(async () => {
- for (const id of pruned) await deleteSyncBaseHash('musicVideoProject', id);
- });
- return { pruned: pruned.length };
-}
-
export async function setProjectAnalysis(id, analysis) {
const { all, idx } = await loadAllAndIndex(id);
- all[idx] = setAudioAnalysis(all[idx], analysis);
+ all[idx] = logic.setAudioAnalysis(all[idx], analysis);
await saveAll(all);
return all[idx];
}
export async function setProjectMidiTranscription(id, midi) {
const { all, idx } = await loadAllAndIndex(id);
- all[idx] = setMidiTranscription(all[idx], midi);
+ all[idx] = logic.setMidiTranscription(all[idx], midi);
await saveAll(all);
return all[idx];
}
export async function addProjectScene(id, sceneInput) {
const { all, idx } = await loadAllAndIndex(id);
- const { project, scene } = addScene(all[idx], sceneInput);
+ const { project, scene } = logic.addScene(all[idx], sceneInput);
all[idx] = project;
await saveAll(all);
return scene;
}
-/**
- * Bulk-append scenes (the autonomous planner, #1855) — one load/save round
- * trip. Returns `{ project, scenes }` (the freshly-persisted project, not a
- * pre-mutation snapshot) so a caller composing a response never has to
- * re-fetch or risk overwriting a concurrent edit with stale state.
- */
export async function addProjectScenes(id, sceneInputs) {
const { all, idx } = await loadAllAndIndex(id);
- const { project, scenes } = addScenes(all[idx], sceneInputs);
+ const { project, scenes } = logic.addScenes(all[idx], sceneInputs);
all[idx] = project;
await saveAll(all);
return { project, scenes };
@@ -200,7 +68,7 @@ export async function addProjectScenes(id, sceneInputs) {
export async function updateScene(id, sceneId, patch) {
const { all, idx } = await loadAllAndIndex(id);
- const { project, updated } = applySceneUpdate(all[idx], sceneId, patch);
+ const { project, updated } = logic.applySceneUpdate(all[idx], sceneId, patch);
all[idx] = project;
await saveAll(all);
return updated;
@@ -208,14 +76,14 @@ export async function updateScene(id, sceneId, patch) {
export async function deleteScene(id, sceneId) {
const { all, idx } = await loadAllAndIndex(id);
- all[idx] = removeScene(all[idx], sceneId);
+ all[idx] = logic.removeScene(all[idx], sceneId);
await saveAll(all);
return all[idx];
}
export async function reorderProjectScenes(id, orderedIds) {
const { all, idx } = await loadAllAndIndex(id);
- all[idx] = reorderScenes(all[idx], orderedIds);
+ all[idx] = logic.reorderScenes(all[idx], orderedIds);
await saveAll(all);
return all[idx];
}
diff --git a/server/services/musicVideo/projectsFile.test.js b/server/services/musicVideo/projectsFile.test.js
index df5bcacf46..f16e799532 100644
--- a/server/services/musicVideo/projectsFile.test.js
+++ b/server/services/musicVideo/projectsFile.test.js
@@ -12,7 +12,7 @@ import { tmpdir } from 'os';
import { join } from 'path';
const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'mv-projects-file-test-'));
-const writeCounter = vi.hoisted(() => ({ baseHash: 0 }));
+const writeCounter = vi.hoisted(() => ({ project: 0, baseHash: 0 }));
vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
const actual = await importOriginal();
@@ -20,6 +20,7 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
...actual,
PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT },
atomicWrite: async (path, data) => {
+ if (typeof path === 'string' && path.endsWith('music-video-projects.json')) writeCounter.project += 1;
if (typeof path === 'string' && path.endsWith('sync_base_hashes.json')) writeCounter.baseHash += 1;
return actual.atomicWrite(path, data);
},
@@ -35,6 +36,7 @@ function reset() {
rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });
cj.__resetBaseHashCacheForTests();
writeCounter.baseHash = 0;
+ writeCounter.project = 0;
}
beforeEach(reset);
afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
@@ -124,6 +126,16 @@ describe('projectsFile federation (#1770)', () => {
expect((await file.getProject(p.id)).name).toBe('RemoteNewer');
});
+ it('same-updatedAt re-push is a no-op without project or base-hash writes', async () => {
+ const remote = { id: 'mv-peer-1', name: 'Peer', status: 'draft', updatedAt: '2026-02-01T00:00:00Z', createdAt: '2026-02-01T00:00:00Z', scenes: [] };
+ await file.mergeProjectsFromSync([remote]);
+ writeCounter.project = 0;
+ writeCounter.baseHash = 0;
+
+ expect(await file.mergeProjectsFromSync([remote])).toEqual({ applied: false, count: 0 });
+ expect(writeCounter).toEqual({ project: 0, baseHash: 0 });
+ });
+
it('mergeProjectsFromSync applies a remote tombstone (delete federates)', async () => {
const p = await file.createProject({ name: 'Doomed' });
const tombstone = { ...p, deleted: true, deletedAt: '2099-01-01T00:00:00Z', updatedAt: '2099-01-01T00:00:00Z' };
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index 81be178ea0..cd0a1c64b2 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -24,8 +24,11 @@ import {
musicVideoSceneUpdateSchema,
} from '../../lib/validation.js';
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
-import { sanitizeSoftDeleteFields, stripMusicVideoLocalRenderPins } from '../../lib/syncWire.js';
+import { stripMusicVideoLocalRenderPins } from '../../lib/syncWire.js';
import { persistedRenderPinFields } from '../../lib/renderTargets.js';
+import { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';
+
+export { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';
// Re-exported for the PG backend's typed mirror columns (mirrors the CD store).
export { mirrorTimestamp } from '../../lib/pgTimestamp.js';
@@ -331,15 +334,6 @@ export function reorderScenes(project, orderedIds) {
* normalizes the timestamps + soft-delete pair so a legacy/hand-edited payload
* converges byte-for-byte with a freshly-written one. Returns null when unusable.
*/
-export function sanitizeProjectForSync(raw) {
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
- if (!isStr(raw.id) || !raw.id) return null;
- const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();
- const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;
- const { deleted, deletedAt } = sanitizeSoftDeleteFields(raw);
- return { ...raw, createdAt, updatedAt, deleted, deletedAt };
-}
-
/**
* LWW merge decision for one incoming peer record against the local copy.
* Returns `{ next, inserted, remoteWins, changed }`:
diff --git a/server/services/projectDbStore.js b/server/services/projectDbStore.js
new file mode 100644
index 0000000000..1a088f3148
--- /dev/null
+++ b/server/services/projectDbStore.js
@@ -0,0 +1,183 @@
+import { randomUUID } from 'crypto';
+import { query, withTransaction } from '../lib/db.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { makeSyncKind } from '../lib/projectStoreKit.js';
+import {
+ maybeJournalBeforeOverwrite,
+ setSyncBaseHash,
+ contentHashForRecord,
+ flushBaseHashes,
+ deleteSyncBaseHash,
+ withBaseHashFlushBatch,
+} from '../lib/conflictJournal.js';
+
+export function createProjectDbStore({ table, kind, idPrefix, logEmoji, logLabel, logic }) {
+ if (!/^[a-z][a-z0-9_]*$/.test(table)) throw new Error(`Invalid project table: ${table}`);
+ const sync = makeSyncKind(kind);
+
+ function rowToProject(row) {
+ if (!row) return null;
+ if (row.data && !row.data.id) return { ...row.data, id: row.id };
+ return row.data;
+ }
+
+ async function persist(exec, project) {
+ if (!project?.id) {
+ throw new ServerError(`Cannot persist a ${logLabel} project without an id`, {
+ status: 500,
+ code: 'PROJECT_ID_MISSING',
+ });
+ }
+ const prepared = logic.beforeSave ? logic.beforeSave(project) : project;
+ const now = new Date().toISOString();
+ const createdAt = logic.mirrorTimestamp(prepared.createdAt, now);
+ await exec(
+ `INSERT INTO ${table} (id, status, data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7)
+ ON CONFLICT (id) DO UPDATE SET
+ status = EXCLUDED.status,
+ data = EXCLUDED.data,
+ updated_at = EXCLUDED.updated_at,
+ deleted = EXCLUDED.deleted,
+ deleted_at = EXCLUDED.deleted_at`,
+ [
+ prepared.id,
+ logic.mirrorStatus(prepared.status),
+ JSON.stringify(prepared),
+ createdAt,
+ logic.mirrorTimestamp(prepared.updatedAt, createdAt),
+ prepared.deleted === true,
+ logic.mirrorTimestamp(prepared.deletedAt, null),
+ ],
+ );
+ return prepared;
+ }
+
+ async function listProjects({ includeDeleted = false } = {}) {
+ const where = includeDeleted ? '' : ' WHERE deleted = FALSE';
+ const result = await query(`SELECT id, data FROM ${table}${where} ORDER BY created_at ASC`);
+ return result.rows.map(rowToProject);
+ }
+
+ async function getProject(id, { includeDeleted = false } = {}) {
+ const result = await query(`SELECT id, data FROM ${table} WHERE id = $1`, [id]);
+ const project = rowToProject(result.rows[0]);
+ if (!project) return null;
+ return includeDeleted || !project.deleted ? project : null;
+ }
+
+ async function getProjectsByIds(ids, { includeDeleted = false } = {}) {
+ const wanted = [...new Set((ids || []).filter(Boolean))];
+ if (wanted.length === 0) return [];
+ const live = includeDeleted ? '' : ' AND deleted = FALSE';
+ const result = await query(
+ `SELECT id, data FROM ${table} WHERE id = ANY($1)${live} ORDER BY created_at ASC`,
+ [wanted],
+ );
+ return result.rows.map(rowToProject);
+ }
+
+ async function listProjectIds({ includeDeleted = false } = {}) {
+ const where = includeDeleted ? '' : ' WHERE deleted = FALSE';
+ const result = await query(`SELECT id FROM ${table}${where}`);
+ return result.rows.map((row) => row.id);
+ }
+
+ async function createProject(input, buildOptions = {}) {
+ const id = `${idPrefix}-${randomUUID()}`;
+ const extra = typeof buildOptions === 'function'
+ ? await buildOptions({ id, input })
+ : buildOptions;
+ const project = logic.buildProjectRecord(input, { id, now: new Date().toISOString(), ...extra });
+ const persisted = await persist(query, project);
+ console.log(`${logEmoji} Created ${logLabel} project: ${id} (${input.name})`);
+ return persisted;
+ }
+
+ async function withLockedProject(id, mutate, { allowMissing = false } = {}) {
+ return withTransaction(async (client) => {
+ const selected = await client.query(`SELECT id, data FROM ${table} WHERE id = $1 FOR UPDATE`, [id]);
+ const project = rowToProject(selected.rows[0]);
+ if (!project || project.deleted) {
+ if (allowMissing) return { __missing: true };
+ throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const { project: next, result, skipPersist } = mutate(project);
+ const persisted = skipPersist ? next : await persist(client.query.bind(client), next);
+ return { project: persisted, result };
+ });
+ }
+
+ async function updateProject(id, patch) {
+ const { project } = await withLockedProject(id, (current) => ({
+ project: logic.applyProjectPatch(current, patch),
+ }));
+ return project;
+ }
+
+ async function deleteProject(id) {
+ const { result } = await withLockedProject(id, (current) => {
+ const now = new Date().toISOString();
+ return {
+ project: { ...current, deleted: true, deletedAt: now, updatedAt: now },
+ result: { ok: true },
+ };
+ });
+ return result;
+ }
+
+ async function mergeProjectsFromSync(remoteProjects, { source = { via: 'sync', peerId: null } } = {}) {
+ if (!Array.isArray(remoteProjects)) return { applied: false, count: 0 };
+ let count = 0;
+ for (const remote of remoteProjects) {
+ const applied = await withTransaction(async (client) => {
+ const selected = await client.query(`SELECT id, data FROM ${table} WHERE id = $1 FOR UPDATE`, [remote?.id]);
+ const local = rowToProject(selected.rows[0]);
+ const { changes } = sync.applySyncMerge({
+ byId: new Map(local ? [[local.id, local]] : []),
+ remoteProjects: [remote],
+ source,
+ mergeProjectRecord: logic.mergeProjectRecord,
+ });
+ const [change] = changes;
+ if (!change) return false;
+ if (!change.inserted) await maybeJournalBeforeOverwrite(change);
+ await persist(client.query.bind(client), change.remote);
+ await setSyncBaseHash(kind, change.id, contentHashForRecord(kind, change.remote));
+ return true;
+ });
+ if (applied) count += 1;
+ }
+ await flushBaseHashes();
+ return { applied: count > 0, count };
+ }
+
+ async function pruneTombstonedProjects(olderThanMs) {
+ if (!Number.isFinite(olderThanMs)) return { pruned: 0 };
+ const { rows } = await query(
+ `DELETE FROM ${table}
+ WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1
+ RETURNING id`,
+ [new Date(olderThanMs).toISOString()],
+ );
+ await withBaseHashFlushBatch(async () => {
+ for (const row of rows) await deleteSyncBaseHash(kind, row.id);
+ });
+ return { pruned: rows.length };
+ }
+
+ return {
+ rowToProject,
+ persist,
+ listProjects,
+ getProject,
+ getProjectsByIds,
+ listProjectIds,
+ createProject,
+ withLockedProject,
+ updateProject,
+ deleteProject,
+ mergeProjectsFromSync,
+ pruneTombstonedProjects,
+ };
+}
diff --git a/server/services/projectFileStore.js b/server/services/projectFileStore.js
new file mode 100644
index 0000000000..88ef3e4d0a
--- /dev/null
+++ b/server/services/projectFileStore.js
@@ -0,0 +1,134 @@
+import { randomUUID } from 'crypto';
+import { dirname } from 'path';
+import { readJSONFile, atomicWrite, ensureDir } from '../lib/fileUtils.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { makeSyncKind } from '../lib/projectStoreKit.js';
+import {
+ maybeJournalBeforeOverwrite,
+ setSyncBaseHash,
+ contentHashForRecord,
+ flushBaseHashes,
+ deleteSyncBaseHash,
+ withBaseHashFlushBatch,
+} from '../lib/conflictJournal.js';
+
+export function createProjectFileStore({ file, kind, idPrefix, logEmoji, logLabel, logic }) {
+ const sync = makeSyncKind(kind);
+
+ async function loadAll() {
+ const raw = await readJSONFile(file, []);
+ return Array.isArray(raw) ? raw : [];
+ }
+
+ async function saveAll(projects) {
+ await ensureDir(dirname(file));
+ const prepared = logic.beforeSave ? projects.map((project) => logic.beforeSave(project)) : projects;
+ await atomicWrite(file, prepared);
+ return prepared;
+ }
+
+ async function loadAllAndIndex(id) {
+ const all = await loadAll();
+ const idx = all.findIndex((project) => project.id === id);
+ if (idx < 0 || all[idx].deleted) {
+ throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ return { all, idx };
+ }
+
+ async function listProjects({ includeDeleted = false } = {}) {
+ const all = await loadAll();
+ return includeDeleted ? all : all.filter((project) => !project.deleted);
+ }
+
+ async function getProject(id, { includeDeleted = false } = {}) {
+ const all = await loadAll();
+ const found = all.find((project) => project.id === id);
+ if (!found) return null;
+ return includeDeleted || !found.deleted ? found : null;
+ }
+
+ async function getProjectsByIds(ids, { includeDeleted = false } = {}) {
+ const wanted = new Set((ids || []).filter(Boolean));
+ if (wanted.size === 0) return [];
+ const all = await loadAll();
+ return all.filter((project) => wanted.has(project.id) && (includeDeleted || !project.deleted));
+ }
+
+ async function listProjectIds({ includeDeleted = false } = {}) {
+ const all = await loadAll();
+ return (includeDeleted ? all : all.filter((project) => !project.deleted)).map((project) => project.id);
+ }
+
+ async function createProject(input, buildOptions = {}) {
+ const id = `${idPrefix}-${randomUUID()}`;
+ const extra = typeof buildOptions === 'function'
+ ? await buildOptions({ id, input })
+ : buildOptions;
+ const project = logic.buildProjectRecord(input, { id, now: new Date().toISOString(), ...extra });
+ const all = await loadAll();
+ all.push(project);
+ const persisted = await saveAll(all);
+ console.log(`${logEmoji} Created ${logLabel} project: ${id} (${input.name})`);
+ return persisted[persisted.length - 1];
+ }
+
+ async function updateProject(id, patch) {
+ const { all, idx } = await loadAllAndIndex(id);
+ all[idx] = logic.applyProjectPatch(all[idx], patch);
+ const persisted = await saveAll(all);
+ return persisted[idx];
+ }
+
+ async function deleteProject(id) {
+ const { all, idx } = await loadAllAndIndex(id);
+ const now = new Date().toISOString();
+ all[idx] = { ...all[idx], deleted: true, deletedAt: now, updatedAt: now };
+ await saveAll(all);
+ return { ok: true };
+ }
+
+ async function mergeProjectsFromSync(remoteProjects, { source = { via: 'sync', peerId: null } } = {}) {
+ if (!Array.isArray(remoteProjects)) return { applied: false, count: 0 };
+ const all = await loadAll();
+ const { byId, changes } = sync.applySyncMerge({
+ byId: new Map(all.map((project) => [project.id, project])),
+ remoteProjects,
+ source,
+ mergeProjectRecord: logic.mergeProjectRecord,
+ });
+ for (const change of changes) {
+ if (!change.inserted) await maybeJournalBeforeOverwrite(change);
+ await setSyncBaseHash(kind, change.id, contentHashForRecord(kind, change.remote));
+ }
+ if (changes.length > 0) await saveAll([...byId.values()]);
+ await flushBaseHashes();
+ return { applied: changes.length > 0, count: changes.length };
+ }
+
+ async function pruneTombstonedProjects(olderThanMs) {
+ const all = await loadAll();
+ const { survivors, prunedIds } = sync.selectExpiredTombstones(all, olderThanMs);
+ if (prunedIds.length === 0) return { pruned: 0 };
+ await saveAll(survivors);
+ await withBaseHashFlushBatch(async () => {
+ for (const id of prunedIds) await deleteSyncBaseHash(kind, id);
+ });
+ return { pruned: prunedIds.length };
+ }
+
+ return {
+ loadAll,
+ saveAll,
+ loadAllAndIndex,
+ listProjects,
+ getProject,
+ getProjectsByIds,
+ listProjectIds,
+ createProject,
+ updateProject,
+ deleteProject,
+ mergeProjectsFromSync,
+ pruneTombstonedProjects,
+ };
+}