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

make Creative Commissions db-primary (Postgres), not a file collection

[._.]/ Adam Eivyeadebf6f9dec
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 57371c7dfc..12e0e0cb2e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -124,4 +124,4 @@
- **[issue-2654] Lift the CoS actionable-insights fetch into `ChiefOfStaff.fetchData` so the banner refreshes for the whole staleness class.** `ActionableInsightsBanner` owned its own `/cos/actionable-insights` fetch on a 60s `useAutoRefetch` poll, decoupled from the parent's 30s task poll, so its server-derived counts (blocked, approvals, "N health issues") lagged any parent-owned data change until that poll. A prior fix bridged only the TasksTab mutation path via an `insightsRefreshKey` counter; socket-driven task changes, agent spawn/completion, and health checks stayed stale. Insights are now fetched inside `ChiefOfStaff.fetchData`'s `Promise.all` and passed down as an `insights` prop, making the banner presentational (it keeps only dismiss/expand/unblock UI state); its unblock path calls `onRefresh` up instead of owning a `refetch()`. The banner's counts refresh **only** through `fetchData`: the 30s poll, task mutations (TasksTab `onRefresh`), the unblock-up path, and agent spawn/completion (which already call `fetchData`). There is deliberately no on-demand "refresh just the insights" path, because `/cos/actionable-insights` runs a health check that **auto-restarts errored PM2 processes** (`server/services/cosHealthMonitor.js`) and re-emits `cos:health:check` — so refreshing from the `cos:health:check` socket handler would loop, and refreshing from the manual "Run Check" button would fire a second process-restart ~1s after the button's own check. Daemon/manual health changes therefore refresh the banner on the next `fetchData` poll (a 2× improvement over the retired 60s self-poll, and the cadence skew is gone). A failed/transient insights fetch (`null`) preserves the last-good array; a legitimately-empty `[]` clears the banner. Because that same insights call triggers a fresh server health check whose `cos:health:check` socket emit can land before `fetchData`'s own (pre-check) `getCosHealth` read resolves, `fetchData` keeps whichever health check is newer by `lastCheck` (`Date.parse`-normalized), and preserves the last-good health when its own read fails — instead of blanking a fresher socket-delivered result. Retires `insightsRefreshKey`, `refreshTasks`'s signal bump, the banner's `refreshKey` prop, its `didMountRef` skip-mount effect, and its `useAutoRefetch` self-poll. Tests cover the prop-driven render, null/empty gating, the unblock-up path, guards asserting neither the `cos:health:check` socket handler nor the manual button re-fetches insights (no loop, no second restart), and the stale/failed-read health-overwrite guards.
- **Fix Element Flash: pressing Enter/Return after answering now advances to the next question.** In the Element Flash recall test (`ElementsSong.jsx`), the Enter-to-submit handler lived only on the answer `<input>`, which unmounts once the result is shown — so a second Enter did nothing and the user had to click "Next" to continue. `ElementFlashMode` now binds a window `keydown` listener while a result is showing (input unmounted) that advances on Enter/Return, mirroring the "Next" button; the `next()` handler was hoisted above the completion early-return so the effect can reference it without breaking hook order. The listener ignores auto-repeat (`e.repeat`) and any Enter that a focused control or open overlay already owns (`e.target.closest('button, a, input, textarea, select, [role="dialog"], [role="menu"], [contenteditable]')`) — so a keyboard user tabbed to the Back/Next button doesn't double-advance, and an Enter meant for the command palette doesn't leak through to the quiz. Tests drive answer → Enter (submit) → Enter (advance) asserting the counter increments, and pin that an Enter fired from the focused Next button is not hijacked by the window listener.
-- **[issue-2657] Autonomous Creation Engine (Phase 1) — schedule the Creative Director with a recurring, feedback-ready creative brief.** New first-class `CreativeCommission` entity: a standing brief (`{ name, enabled, targetAbility, brief, schedule, generation }`) that fires on a cron cadence and drives the existing Creative Director *directive* pipeline unattended — "every night at 2am, make me something surreal." Commissions persist in a machine-local `createCollectionStore` collection at `data/creative-commissions/` (schemaVersion 1, stamped by migration 191 + a `data.reference/` seed); they are deliberately **not** federated in Phase 1 — the same rationale as `seriesAutopilotScheduler`'s settings-based schedules, since a schedule that synced across peers would double-run on every machine (federation with a per-peer "home" gate is Phase 2). A new `commissionScheduler.js` (modeled on `seriesAutopilotScheduler`) arms one `eventScheduler` cron per enabled commission; on fire it re-reads the commission + creative-autonomy config, builds a CD directive from the brief via the pure `buildCommissionDirective` (which already folds a last-N feedback digest so Phase 2 only needs the rate surface), mints a directive-driven CD video project, and nudges `advanceAfterPlanStepSettled` so each plan step runs through the gated `dispatchCreativeTool`. Cold-bootstrap compliant per the AI Provider Usage Policy: boot only *arms* crons (nothing fires until a cadence elapses), and every fire gates on creative autonomy `execute` **and** the daily `cos` budget before spawning anything — an `off`/`dry-run` or over-budget install records a `skipped` run and generates nothing. Full REST CRUD at `/api/creative-commission` (Zod-validated create/update, DAILY/WEEKLY/CUSTOM schedules composed to cron with an authoritative `isValidCron` check in the service, `generation` schema with no object-level default so an empty PATCH still 400s the "at least one field" refine), a scheduler re-sync after every mutation, and a new `/creative-commission` Create-suite page: list + deep-linked create/edit Drawer (`/creative-commission/:id`, `/new`) with pause/resume, inline-confirm delete, and per-run history — registered in `NAV_COMMANDS` (⌘K + voice) and the sidebar. Phase 1 restricts `targetAbility` to `video` (the enum widens with the ability adapter in Phase 3/4) so a user can't create a commission that silently never runs. Refs #2657 — Phases 2–5 (feedback loop, all-ability adapter, music tool, genre taxonomy) remain. New unit + route + migration tests cover cron composition, the feedback digest, the store CRUD/sanitizer, the autonomy/budget gates, the no-boot-generation guarantee, and the route contract.
+- **[issue-2657] Autonomous Creation Engine (Phase 1) — schedule the Creative Director with a recurring, feedback-ready creative brief.** New first-class `CreativeCommission` entity: a standing brief (`{ name, enabled, targetAbility, brief, schedule, generation }`) that fires on a cron cadence and drives the existing Creative Director *directive* pipeline unattended — "every night at 2am, make me something surreal." Commissions are `db-primary` (per `docs/STORAGE.md`): one row per commission in the machine-local `creative_commissions` PostgreSQL table (full record in `data` JSONB, adapter `server/services/creativeCommissions/db.js`, selected pg-vs-file exactly like universeBuilder so a `NODE_ENV=test`/`MEMORY_BACKEND=file` install keeps a file escape hatch). No `sync_sequence`/tombstone — deletes are hard deletes, mirroring `tribe`. They are deliberately **not** federated in Phase 1 — the same rationale as `seriesAutopilotScheduler`'s settings-based schedules, since a schedule that synced across peers would double-run on every machine (federation with a per-peer "home" gate is Phase 2). A new `commissionScheduler.js` (modeled on `seriesAutopilotScheduler`) arms one `eventScheduler` cron per enabled commission; on fire it re-reads the commission + creative-autonomy config, builds a CD directive from the brief via the pure `buildCommissionDirective` (which already folds a last-N feedback digest so Phase 2 only needs the rate surface), mints a directive-driven CD video project, and nudges `advanceAfterPlanStepSettled` so each plan step runs through the gated `dispatchCreativeTool`. Cold-bootstrap compliant per the AI Provider Usage Policy: boot only *arms* crons (nothing fires until a cadence elapses), and every fire gates on creative autonomy `execute` **and** the daily `cos` budget before spawning anything — an `off`/`dry-run` or over-budget install records a `skipped` run and generates nothing. Full REST CRUD at `/api/creative-commission` (Zod-validated create/update, DAILY/WEEKLY/CUSTOM schedules composed to cron with an authoritative `isValidCron` check in the service, `generation` schema with no object-level default so an empty PATCH still 400s the "at least one field" refine), a scheduler re-sync after every mutation, and a new `/creative-commission` Create-suite page: list + deep-linked create/edit Drawer (`/creative-commission/:id`, `/new`) with pause/resume, inline-confirm delete, and per-run history — registered in `NAV_COMMANDS` (⌘K + voice) and the sidebar. Phase 1 restricts `targetAbility` to `video` (the enum widens with the ability adapter in Phase 3/4) so a user can't create a commission that silently never runs. Refs #2657 — Phases 2–5 (feedback loop, all-ability adapter, music tool, genre taxonomy) remain. New unit + route + PG-adapter tests cover cron composition, the feedback digest, the store CRUD/sanitizer, the autonomy/budget gates, the no-boot-generation guarantee, the route contract, and the `creative_commissions` row round-trip (verbatim readback / upsert with created_at preserved / list order / hard delete). Scheduler-vs-request writes serialize on the facade's shared per-id write queue (`createRecordWriteQueue`), identical to universeBuilder/storyBuilder.
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 6b222c859e..8707c0196f 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -35,6 +35,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.
- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`.
- `tribe_people` / `tribe_touchpoints` / `tribe_memory_links` — the Tribe relationship/CRM graph (people + their care cadence, contact touchpoints, and cross-links into brain `memories`). **Intentionally machine-local — never federated** (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724): it is relationship-graph data, mirroring the deliberate "memory_links are instance-local" boundary in `memorySync.js` (memory *nodes* federate, the link graph does not), and is coupled to machine-local domains — `tribe_memory_links` extends the non-federated `memory_links` layer and `tribe_touchpoints` carry per-machine calendar-account refs. NO `sync_sequence`, no peer-sync record kind, no `dataSync` category. Adapter: `server/services/tribe.js`.
+- `creative_commissions` — Creative Commissions (Autonomous Creation Engine Phase 1, #2657): standing recurring creative briefs that fire on a cron cadence and drive the Creative Director directive pipeline unattended. One row per commission, the full sanitized record (brief / schedule / generation / feedback / capped `runs[]`) in `data` JSONB with `name`/`enabled`/`created_at`/`updated_at` mirrored into columns for the scheduler's "arm every enabled commission" query. **Intentionally machine-local — never federated** (a synced schedule would double-run on every peer, same rationale as `seriesAutopilotScheduler`): NO `sync_sequence` and NO `deleted`/`deleted_at` tombstone — deletes are hard deletes, mirroring `tribe`. Phase 2 will split the machine-local *schedule* from a federatable *brief/feedback* record before adding any sync hook. Adapter: `server/services/creativeCommissions/db.js`, selected pg-vs-file by `server/services/creativeCommissions/store.js` (file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only).
**Postgres-First target.** Pipeline series/issues, Story Builder sessions, and searchable media metadata are still `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. The schema for the Create domains is designed in [`docs/plans/2026-06-07-create-relational-schema-design.md`](./plans/2026-06-07-create-relational-schema-design.md) (#999), with implementation tracked as #1014–#1018. (Creative Director project/scene/run state moved to Postgres in Phase 3 / #997; catalog user-defined types moved in Phase 4 lead-in / #1001; **universes moved in Phase 3 Create slice 1 / #1014** — see the `universes` entry above. Pipeline series/issues #1015, Story Builder #1016, Writers Room #1017, and the catalog ref resolver #1018 are the remaining slices.)
diff --git a/scripts/migrations/191-creative-commissions.js b/scripts/migrations/191-creative-commissions.js
deleted file mode 100644
index d5292958fc..0000000000
--- a/scripts/migrations/191-creative-commissions.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * Stamp the Creative Commission collection's type-level index at schemaVersion 1
- * (issue #2657, Autonomous Creation Engine — Phase 1).
- *
- * The commissions live in a `createCollectionStore` collection at
- * `data/creative-commissions/`. A fresh collection has no records and no
- * `index.json`; the boot verifier tolerates a missing index (treats it as a
- * fresh install), and the store stamps the index on its first write. But to keep
- * the on-disk shape explicit and let a future schemaVersion bump detect existing
- * v1 data, this migration creates the type index up front if it's absent.
- *
- * There is NO legacy monolith to split — commissions are a brand-new record kind
- * — so this is a pure stamp, not a data transform.
- *
- * Idempotent: a second run finds an index at version ≥ 1 and writes nothing.
- * Forward-only: never downgrades an index the code already advanced past 1.
- */
-
-import { readFile, writeFile, mkdir } from 'fs/promises';
-import { join } from 'path';
-
-const TYPE = 'creative-commissions';
-const SCHEMA_VERSION = 1;
-
-const readJson = async (path) => {
- const raw = await readFile(path, 'utf-8').catch((err) => {
- if (err.code === 'ENOENT') return null;
- throw err;
- });
- if (raw == null) return null;
- try { return JSON.parse(raw); } catch { return null; }
-};
-
-export async function up({ rootDir }) {
- const dir = join(rootDir, 'data', TYPE);
- const indexPath = join(dir, 'index.json');
- const existing = await readJson(indexPath);
-
- if (existing && typeof existing.schemaVersion === 'number' && existing.schemaVersion >= SCHEMA_VERSION) {
- console.log(`✅ creative-commissions: type index already at v${existing.schemaVersion} — no changes`);
- return { migrated: false };
- }
-
- await mkdir(dir, { recursive: true });
- const index = {
- schemaVersion: SCHEMA_VERSION,
- type: TYPE,
- updatedAt: new Date().toISOString(),
- config: {},
- };
- await writeFile(indexPath, JSON.stringify(index, null, 2) + '\n');
- console.log(`🎬 creative-commissions: stamped type index → v${SCHEMA_VERSION}`);
- return { migrated: true };
-}
-
-export default { up };
diff --git a/scripts/migrations/191-creative-commissions.test.js b/scripts/migrations/191-creative-commissions.test.js
deleted file mode 100644
index 12531c53be..0000000000
--- a/scripts/migrations/191-creative-commissions.test.js
+++ /dev/null
@@ -1,41 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach } from 'vitest';
-import { mkdtemp, rm, readFile, mkdir, writeFile } from 'fs/promises';
-import { tmpdir } from 'os';
-import { join } from 'path';
-import { up } from './191-creative-commissions.js';
-
-let rootDir;
-
-beforeEach(async () => { rootDir = await mkdtemp(join(tmpdir(), 'portos-mig191-')); });
-afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });
-
-const indexPath = () => join(rootDir, 'data', 'creative-commissions', 'index.json');
-
-describe('migration 191 — creative-commissions type index stamp', () => {
- it('creates the type index at schemaVersion 1 on a fresh install', async () => {
- const res = await up({ rootDir });
- expect(res.migrated).toBe(true);
- const idx = JSON.parse(await readFile(indexPath(), 'utf-8'));
- expect(idx.schemaVersion).toBe(1);
- expect(idx.type).toBe('creative-commissions');
- expect(idx.config).toEqual({});
- });
-
- it('is idempotent — a second run writes nothing', async () => {
- await up({ rootDir });
- const first = await readFile(indexPath(), 'utf-8');
- const res = await up({ rootDir });
- expect(res.migrated).toBe(false);
- expect(await readFile(indexPath(), 'utf-8')).toBe(first);
- });
-
- it('does not downgrade an index already past v1', async () => {
- await mkdir(join(rootDir, 'data', 'creative-commissions'), { recursive: true });
- await writeFile(indexPath(), JSON.stringify({ schemaVersion: 3, type: 'creative-commissions', config: { x: 1 } }));
- const res = await up({ rootDir });
- expect(res.migrated).toBe(false);
- const idx = JSON.parse(await readFile(indexPath(), 'utf-8'));
- expect(idx.schemaVersion).toBe(3);
- expect(idx.config).toEqual({ x: 1 });
- });
-});
diff --git a/server/lib/db.js b/server/lib/db.js
index 4fb6f0a74b..0226044cbd 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -455,6 +455,28 @@ async function ensureSchemaImpl() {
)`,
`CREATE UNIQUE INDEX IF NOT EXISTS idx_human_activity_dedupe ON human_activity_events (source, dedupe_key)`,
`CREATE INDEX IF NOT EXISTS idx_human_activity_happened ON human_activity_events (happened_at)`,
+ // Creative Commissions (#2657, Autonomous Creation Engine — Phase 1). A
+ // standing, recurring creative brief that fires on a schedule and drives the
+ // Creative Director directive pipeline unattended. One row per commission:
+ // the full sanitized record (brief / schedule / generation / feedback /
+ // runs[]) in `data` JSONB, with id / name / enabled / created_at / updated_at
+ // mirrored into columns for the scheduler's "arm every enabled commission"
+ // query. INTENTIONALLY MACHINE-LOCAL — never federated (a synced schedule
+ // would double-run on every peer, same rationale as seriesAutopilotScheduler),
+ // so there is NO sync_sequence and NO deleted/deleted_at tombstone: deletes
+ // are hard deletes, mirroring tribe_people (ADR
+ // docs/decisions/2026-06-26-tribe-and-universe-runs-local.md). Adding a sync
+ // hook here is a conscious act — Phase 2 must split the machine-local schedule
+ // from the federatable brief/feedback first.
+ `CREATE TABLE IF NOT EXISTS creative_commissions (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL DEFAULT '',
+ enabled BOOLEAN NOT NULL DEFAULT TRUE,
+ data JSONB NOT NULL,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_creative_commissions_enabled ON creative_commissions (enabled)`,
];
for (const sql of upgrades) {
await pool.query(sql);
diff --git a/server/services/creativeCommissions/db.js b/server/services/creativeCommissions/db.js
new file mode 100644
index 0000000000..e6f85e6f24
--- /dev/null
+++ b/server/services/creativeCommissions/db.js
@@ -0,0 +1,71 @@
+/**
+ * Creative Commission — PostgreSQL leaf I/O (#2657, Autonomous Creation Engine).
+ *
+ * One row per commission in `creative_commissions`: the full sanitized record
+ * (brief / schedule / generation / feedback / runs[]) in `data` JSONB, with
+ * id / name / enabled / created_at / updated_at mirrored into columns for the
+ * scheduler's "arm every enabled commission" query. This is the DEFAULT backend
+ * for real installs; the file backend (collectionStore) is a dev/test escape
+ * hatch only (see store.js).
+ *
+ * INTENTIONALLY MACHINE-LOCAL — never federated (a synced schedule would
+ * double-run on every peer). So there is NO sync_sequence and NO
+ * deleted/deleted_at tombstone: `deleteRaw` is a hard delete, mirroring
+ * tribe_people (ADR docs/decisions/2026-06-26-tribe-and-universe-runs-local.md).
+ *
+ * This module is PURE leaf I/O — no sanitizing, no serialization. The store
+ * facade (store.js) owns the sanitizer + merge semantics AND serializes the
+ * scheduler-vs-request read-modify-write on a shared per-id write queue
+ * (`createRecordWriteQueue`, identical to universeBuilder/storyBuilder), so reads
+ * here return `data` verbatim (the columns are a queryable mirror, never read
+ * back) and writes are plain upserts.
+ */
+
+import { query } from '../../lib/db.js';
+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
+
+/** Raw stored record (the `data` JSONB), or null. No sanitize. */
+export async function readRaw(id) {
+ const { rows } = await query(`SELECT data FROM creative_commissions WHERE id = $1`, [id]);
+ return rows[0]?.data ?? null;
+}
+
+/** Every commission's raw `data` JSONB, oldest first (stable create order). */
+export async function listRaw() {
+ const { rows } = await query(`SELECT data FROM creative_commissions ORDER BY created_at ASC, id ASC`);
+ return rows.map((r) => r.data);
+}
+
+/**
+ * Upsert one record. `data` is written verbatim (lossless); the typed mirror
+ * columns are bind-sanitized so a hand-edited/legacy record with a malformed
+ * timestamp can't make the write throw. `created_at` is preserved on conflict
+ * (only the first INSERT sets it).
+ */
+export async function writeRaw(id, record) {
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(record?.createdAt, now);
+ await query(
+ `INSERT INTO creative_commissions (id, name, enabled, data, created_at, updated_at)
+ VALUES ($1, $2, $3, $4::jsonb, $5, $6)
+ ON CONFLICT (id) DO UPDATE SET
+ name = EXCLUDED.name,
+ enabled = EXCLUDED.enabled,
+ data = EXCLUDED.data,
+ updated_at = EXCLUDED.updated_at`,
+ [
+ id,
+ typeof record?.name === 'string' ? record.name : '',
+ record?.enabled !== false,
+ JSON.stringify(record),
+ createdAt,
+ mirrorTimestamp(record?.updatedAt, createdAt),
+ ],
+ );
+ return record;
+}
+
+/** Hard-delete a record. Idempotent — a missing row is a no-op. */
+export async function deleteRaw(id) {
+ await query(`DELETE FROM creative_commissions WHERE id = $1`, [id]);
+}
diff --git a/server/services/creativeCommissions/db.test.js b/server/services/creativeCommissions/db.test.js
new file mode 100644
index 0000000000..efd40077c7
--- /dev/null
+++ b/server/services/creativeCommissions/db.test.js
@@ -0,0 +1,103 @@
+/**
+ * Postgres-backed round-trip for the Creative Commission DB adapter (#2657).
+ *
+ * `*.db.test.js` → runs ONLY via `npm run test:db` against `portos_test`, never
+ * the real `portos` DB (the db.js runner guard + the health-gate skip below
+ * enforce this). If no test DB is reachable it SKIPS cleanly rather than failing
+ * red. Every row uses a per-run nonce id prefix and is torn down in afterAll, so
+ * the suite never touches unrelated rows and is safe on a shared test DB.
+ *
+ * Exercises the pure leaf I/O: verbatim record readback, list order, upsert
+ * (created_at preserved on conflict), and hard delete (no tombstone — commissions
+ * are machine-local). The scheduler-vs-request read-modify-write serialization
+ * lives in the store facade's shared per-id write queue, not here, so it's
+ * covered by the store tests + the shared fileWriteQueue suite.
+ */
+
+import { describe, it, expect, afterAll } from 'vitest';
+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
+import { readRaw, listRaw, writeRaw, deleteRaw } from './db.js';
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ const probe = await query(
+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'creative_commissions') AS ok`,
+ ).catch(() => ({ rows: [{ ok: false }] }));
+ if (probe.rows?.[0]?.ok) dbReady = true;
+ else skipReason = 'creative_commissions table not present';
+ }
+}
+
+if (!dbReady) console.log(`⏭️ creativeCommissions/db.test.js skipped: ${skipReason}`);
+
+const nonce = `cc${Date.now()}`;
+const cid = (n) => `${nonce}-${n}`;
+
+const rec = (id, over = {}) => ({
+ id,
+ name: `Commission ${id}`,
+ enabled: true,
+ targetAbility: 'video',
+ brief: { intent: 'surreal', constraints: {} },
+ schedule: { kind: 'DAILY', atLocalTime: '02:00' },
+ generation: { quality: 'standard' },
+ feedback: [],
+ runs: [],
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ ...over,
+});
+
+afterAll(async () => {
+ if (dbReady) {
+ await query(`DELETE FROM creative_commissions WHERE id LIKE $1`, [`${nonce}-%`]).catch(() => {});
+ await close();
+ }
+});
+
+describe.skipIf(!dbReady)('creativeCommissions DB adapter round-trip', () => {
+ it('writes and reads a record back verbatim', async () => {
+ const r = rec(cid('rw'), { brief: { intent: 'noir', constraints: { universeId: 'u-1' } } });
+ await writeRaw(r.id, r);
+ expect(await readRaw(r.id)).toEqual(r);
+ });
+
+ it('returns null for a missing id', async () => {
+ expect(await readRaw(cid('nope'))).toBeNull();
+ });
+
+ it('upserts on conflict — preserves created_at, updates data + mirror columns', async () => {
+ const id = cid('upsert');
+ await writeRaw(id, rec(id, { name: 'first' }));
+ await writeRaw(id, rec(id, { name: 'second', enabled: false, createdAt: '2099-01-01T00:00:00.000Z' }));
+ const back = await readRaw(id);
+ expect(back.name).toBe('second');
+ // created_at column is preserved on conflict (only the first INSERT sets it);
+ // name/enabled mirror the new data.
+ const col = await query(`SELECT created_at, name, enabled FROM creative_commissions WHERE id = $1`, [id]);
+ expect(col.rows[0].created_at.toISOString()).toBe('2026-01-01T00:00:00.000Z');
+ expect(col.rows[0].name).toBe('second');
+ expect(col.rows[0].enabled).toBe(false);
+ });
+
+ it('lists commissions oldest-first (created_at ASC)', async () => {
+ await writeRaw(cid('old'), rec(cid('old'), { createdAt: '2026-01-01T00:00:00.000Z' }));
+ await writeRaw(cid('new'), rec(cid('new'), { createdAt: '2026-06-01T00:00:00.000Z' }));
+ const ids = (await listRaw()).map((r) => r.id).filter((x) => x.startsWith(nonce));
+ expect(ids.indexOf(cid('old'))).toBeLessThan(ids.indexOf(cid('new')));
+ });
+
+ it('hard-deletes a record (idempotent — no tombstone)', async () => {
+ const id = cid('del');
+ await writeRaw(id, rec(id));
+ await deleteRaw(id);
+ expect(await readRaw(id)).toBeNull();
+ await expect(deleteRaw(id)).resolves.not.toThrow(); // idempotent
+ });
+});
diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.js
index ff457a15c5..de57b44542 100644
--- a/server/services/creativeCommissions/store.js
+++ b/server/services/creativeCommissions/store.js
@@ -4,15 +4,25 @@
* A CreativeCommission is a standing, recurring creative brief that fires on a
* schedule and drives the Creative Director's directive pipeline unattended.
*
- * Storage: a `createCollectionStore` collection at `data/creative-commissions/`,
- * one record per commission. Commissions are MACHINE-LOCAL and NOT federated in
- * Phase 1 — the same rationale as `seriesAutopilotScheduler`'s settings-based
- * schedules: a schedule that federated across sync peers would double-run on
- * every machine. Federation is Phase 2 work, and it must split this record: the
- * brief/feedback CAN federate, but the `schedule` field (+ a future "home peer"
- * pointer) MUST stay machine-local, or the whole double-run avoidance breaks.
- * seriesAutopilot already proved this shape out (local schedule → federated
- * series); Phase 2 will decompose the monolithic local record accordingly.
+ * Storage: `db-primary` (docs/STORAGE.md). Real installs store one row per
+ * commission in the `creative_commissions` PostgreSQL table (the full sanitized
+ * record in `data` JSONB — see ./db.js). A file backend (collectionStore at
+ * `data/creative-commissions/`) is retained ONLY as the dev/test escape hatch
+ * (`MEMORY_BACKEND=file` or `NODE_ENV=test`), exactly like universeBuilder — so
+ * the unit tests keep exercising a real store without a database. This facade
+ * owns the sanitizer + merge semantics uniformly (applied on the service side,
+ * not inside a backend) so the two backends can't drift, serializes the
+ * scheduler-vs-request read-modify-write on a shared per-id write queue
+ * (`createRecordWriteQueue`, identical to universeBuilder), and delegates only
+ * plain leaf I/O to the selected backend.
+ *
+ * Commissions are MACHINE-LOCAL and NOT federated in Phase 1 — the same rationale
+ * as `seriesAutopilotScheduler`'s settings-based schedules: a schedule that
+ * federated across sync peers would double-run on every machine. The DB row
+ * carries no sync cursor/tombstone (deletes are hard deletes, mirroring tribe).
+ * Federation is Phase 2 work, and it must split this record: the brief/feedback
+ * CAN federate, but the `schedule` field (+ a future "home peer" pointer) MUST
+ * stay machine-local, or the whole double-run avoidance breaks.
*
* The record shape is stable/forward-looking: `feedback[]` + `feedbackWindow`
* exist now (Phase 1 leaves feedback empty) so Phase 2 only needs the rate
@@ -30,6 +40,8 @@ import { randomUUID } from 'crypto';
import { EventEmitter } from 'events';
import { PATHS } from '../../lib/fileUtils.js';
import { createCollectionStore } from '../../lib/collectionStore.js';
+import { createPgFileFacade, resolvePgBackend, isFileBackend } from '../../lib/pgFileFacade.js';
+import { createRecordWriteQueue } from '../../lib/fileWriteQueue.js';
import { isValidCron } from '../eventScheduler.js';
import { commissionToCron } from './directive.js';
@@ -51,8 +63,9 @@ const isStr = (v) => typeof v === 'string';
/**
* Normalize a raw record into the canonical stored shape. Returns null for a
- * non-object / id-less record (collectionStore drops nulls), so a malformed
- * on-disk file can't surface. Passed to every `loadOne`.
+ * non-object / id-less record (so a malformed on-disk / on-row record can't
+ * surface). Applied by the service on every read and before every write, so both
+ * backends return an identical shape.
*/
export function sanitizeCommission(raw) {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
@@ -97,28 +110,110 @@ export function sanitizeCommission(raw) {
};
}
-let _store = null;
-/** Lazily construct the singleton commission store (avoids touching PATHS at import). */
+// --- File backend (dev/test escape hatch): wraps collectionStore ---
+// No sanitizer on the collectionStore — the facade sanitizes uniformly on the
+// service side so file and PG return an identical shape. The type-level index is
+// stamped on the first write so the boot verifier reports the real version.
+function makeFileBackend(dir) {
+ const cs = createCollectionStore({
+ dir,
+ type: TYPE,
+ schemaVersion: COMMISSIONS_SCHEMA_VERSION,
+ });
+ let stamped = false;
+ const ensureTypeIndex = async () => {
+ if (stamped) return;
+ stamped = true;
+ await cs.saveTypeIndex({}).catch(() => { stamped = false; });
+ };
+ return {
+ name: 'file',
+ listRaw: () => cs.loadAll(),
+ readRaw: (id) => cs.loadOne(id),
+ writeRaw: async (id, record) => { await ensureTypeIndex(); await cs.saveOneNow(id, record); return record; },
+ deleteRaw: (id) => cs.deleteOneNow(id),
+ verify: () => cs.verifySchemaVersion(),
+ };
+}
+
+// --- PostgreSQL backend: pure leaf I/O from ./db.js ---
+// No `verify` — the facade's verifySchemaVersion short-circuits the PG case
+// without touching the backend (see below), so PG has no type-index to check.
+function makePgBackend(db) {
+ return {
+ name: 'postgres',
+ listRaw: db.listRaw,
+ readRaw: db.readRaw,
+ writeRaw: db.writeRaw,
+ deleteRaw: db.deleteRaw,
+ };
+}
+
+// Self-sufficient PG bring-up: the boot DB gate fail-fasts a required-but-missing
+// DB, but an early scheduler warm can call in BEFORE that gate's ensureSchema()
+// runs — so resolvePgBackend health-checks + brings the (idempotent) schema up.
+// No file→DB migration: commissions are a brand-new record kind that never
+// shipped on the file backend.
+const pgBackend = () => resolvePgBackend({
+ requirement: 'Creative Commissions require PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)',
+ loadDb: () => import('./db.js'),
+ makePg: makePgBackend,
+});
+
+// --- Facade: memoized backend selection + per-id write queue + verify ---
+// Keyed by data dir so a test harness that swaps PATHS.data per-test still sees
+// the right root. commissionStore() is the accessor the boot verifier calls.
+// The facade owns the scheduler-vs-request serialization via a shared per-id
+// write queue (identical to universeBuilder/storyBuilder) rather than a backend
+// row lock — commissions are machine-local and written only by the single main
+// server process (the scheduler fire + the REST route), so in-process per-id
+// serialization is sufficient and keeps both backends serializing identically.
+let _facade = null;
+let _facadeDir = null;
+
+function createFacade(dir) {
+ const { getBackend, getBackendName } = createPgFileFacade({
+ makeFile: () => makeFileBackend(dir),
+ makePg: () => pgBackend(),
+ });
+ // Tail-chained per id: two RMW cycles on the SAME id serialize while different
+ // ids fan out. Backend-agnostic, so file and PG serialize the same way.
+ const queueRecordWrite = createRecordWriteQueue();
+ return {
+ dir,
+ type: TYPE,
+ getBackendName,
+ listRaw: async () => (await getBackend()).listRaw(),
+ readRaw: async (id) => (await getBackend()).readRaw(id),
+ writeRaw: async (id, record) => (await getBackend()).writeRaw(id, record),
+ deleteRaw: async (id) => (await getBackend()).deleteRaw(id),
+ queueRecordWrite,
+ // Under PG, report ok WITHOUT forcing backend selection (the early boot
+ // verifier runs before the dbReady gate); under the file escape hatch, read
+ // the on-disk type index. The env check matches the selection predicate.
+ verifySchemaVersion: async () => {
+ if (!isFileBackend()) {
+ return { ok: true, type: TYPE, onDisk: null, expected: null,
+ message: `collection "${TYPE}" @ postgres (#2657)` };
+ }
+ return (await getBackend()).verify();
+ },
+ };
+}
+
+/** Get the memoized commission store facade (the boot verifier calls this). */
export function commissionStore() {
- if (!_store) {
- _store = createCollectionStore({
- dir: join(PATHS.data, TYPE),
- type: TYPE,
- schemaVersion: COMMISSIONS_SCHEMA_VERSION,
- sanitizeRecord: sanitizeCommission,
- });
- }
- return _store;
+ const dir = join(PATHS.data, TYPE);
+ if (_facade && _facadeDir === dir) return _facade;
+ _facade = createFacade(dir);
+ _facadeDir = dir;
+ return _facade;
}
-// `saveOne` writes only the per-record file, never the type-level index.json
-// (which stamps schemaVersion). Stamp it once per process on first write so the
-// boot verifier reports the real version and a future bump can detect v1 data.
-const _stamped = new WeakSet();
-async function ensureTypeIndex(store) {
- if (_stamped.has(store)) return;
- _stamped.add(store);
- await store.saveTypeIndex({}).catch(() => { _stamped.delete(store); });
+/** Reset the memoized facade — test seam only. */
+export function _resetCommissionStore() {
+ _facade = null;
+ _facadeDir = null;
}
/**
@@ -135,39 +230,40 @@ export function assertValidSchedule(schedule) {
}
export async function listCommissions() {
- return commissionStore().loadAll();
+ const raw = await commissionStore().listRaw();
+ return raw.map(sanitizeCommission).filter(Boolean);
}
export async function getCommission(id) {
- const rec = await commissionStore().loadOne(id);
+ const raw = await commissionStore().readRaw(id);
+ const rec = raw ? sanitizeCommission(raw) : null;
if (!rec) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);
return rec;
}
export async function createCommission(input) {
assertValidSchedule(input.schedule);
- const store = commissionStore();
const now = new Date().toISOString();
const id = `commission-${randomUUID()}`;
// sanitizeCommission defaults runs/feedback to [] and the create schema carries
// neither key, so no explicit empties are needed here.
const record = sanitizeCommission({ ...input, id, createdAt: now, updatedAt: now });
- await ensureTypeIndex(store);
- await store.saveOne(id, record);
+ await commissionStore().writeRaw(id, record);
commissionEvents.emit('commission:changed', { id, action: 'create' });
return record;
}
export async function updateCommission(id, patch) {
- const store = commissionStore();
if (patch.schedule) assertValidSchedule(patch.schedule);
- // Serialize the load→merge→save inside the per-id write queue so a concurrent
+ const store = commissionStore();
+ // Serialize the load→merge→save on the per-id write queue so a concurrent
// scheduler fire (recordCommissionRun, also queued) can't have its run-history
// append clobbered by a stale pre-read here — the scheduler-vs-request race
- // CLAUDE.md requires serializing at the file level.
+ // CLAUDE.md requires serializing at the record level.
const merged = await store.queueRecordWrite(id, async () => {
- const current = await store.loadOne(id);
- if (!current) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);
+ const currentRaw = await store.readRaw(id);
+ if (!currentRaw) return null;
+ const current = sanitizeCommission(currentRaw);
const next = sanitizeCommission({
...current,
...patch,
@@ -190,33 +286,34 @@ export async function updateCommission(id, patch) {
createdAt: current.createdAt,
updatedAt: new Date().toISOString(),
});
- await store.saveOneNow(id, next);
+ await store.writeRaw(id, next);
return next;
});
+ if (!merged) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);
commissionEvents.emit('commission:changed', { id, action: 'update' });
return merged;
}
export async function deleteCommission(id) {
- const store = commissionStore();
- const current = await store.loadOne(id);
+ const current = await commissionStore().readRaw(id);
if (!current) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);
- await store.deleteOne(id);
+ await commissionStore().deleteRaw(id);
commissionEvents.emit('commission:changed', { id, action: 'delete' });
return { id, deleted: true };
}
/**
* Append a run entry to a commission (fire history). Runs are capped to the last
- * MAX_PERSISTED_RUNS. Serialized per-id by the collectionStore write queue.
- * Best-effort: called from the scheduler's fire handler (outside the request
- * lifecycle) — the caller wraps errors.
+ * MAX_PERSISTED_RUNS. Serialized per-record on the write queue. Best-effort:
+ * called from the scheduler's fire handler (outside the request lifecycle) — the
+ * caller wraps errors. Returns the appended run, or null if the commission is gone.
*/
export async function recordCommissionRun(id, runEntry) {
const store = commissionStore();
return store.queueRecordWrite(id, async () => {
- const current = await store.loadOne(id);
- if (!current) return null;
+ const currentRaw = await store.readRaw(id);
+ if (!currentRaw) return null;
+ const current = sanitizeCommission(currentRaw);
const run = {
id: runEntry.id || `run-${randomUUID()}`,
ranAt: runEntry.ranAt || new Date().toISOString(),
@@ -227,7 +324,7 @@ export async function recordCommissionRun(id, runEntry) {
error: isStr(runEntry.error) ? runEntry.error : null,
};
const runs = [...(current.runs || []), run].slice(-MAX_PERSISTED_RUNS);
- await store.saveOneNow(id, { ...current, runs, updatedAt: new Date().toISOString() });
+ await store.writeRaw(id, { ...current, runs, updatedAt: new Date().toISOString() });
return run;
});
}
diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.js
index 9e4ea5a6dc..d88e710c17 100644
--- a/server/services/creativeCommissions/store.test.js
+++ b/server/services/creativeCommissions/store.test.js
@@ -9,8 +9,9 @@ const makeMemStore = () => ({
saveOne: async (id, rec) => { records.set(id, rec); },
saveOneNow: async (id, rec) => { records.set(id, rec); },
deleteOne: async (id) => { records.delete(id); },
+ deleteOneNow: async (id) => { records.delete(id); },
saveTypeIndex: async () => {},
- queueRecordWrite: async (_id, fn) => fn(),
+ verifySchemaVersion: async () => ({ ok: true }),
});
vi.mock('../../lib/collectionStore.js', () => ({ createCollectionStore: () => makeMemStore() }));
vi.mock('../../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-test-data' } }));