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([issue-2832]): split ensureSchemaImpl DDL into per-domain db/schema modules

[._.]/ Adam Eivyb9ca9ac4e5da
diff --git a/server/lib/catalogTypes.test.js b/server/lib/catalogTypes.test.js
index 45b6b7c722..189e873d6a 100644
--- a/server/lib/catalogTypes.test.js
+++ b/server/lib/catalogTypes.test.js
@@ -13,7 +13,7 @@
*/
import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'node:fs';
+import { readFileSync, readdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import {
@@ -47,7 +47,17 @@ import { afterEach } from 'vitest';
const HERE = dirname(fileURLToPath(import.meta.url));
const INIT_SQL = readFileSync(join(HERE, '..', 'scripts', 'init-db.sql'), 'utf8');
-const DB_JS = readFileSync(join(HERE, 'db.js'), 'utf8');
+// The ensureSchema() DDL (incl. the catalog search_tsv payload fields and any
+// type CHECK) now lives in per-domain modules under db/schema/ (#2832); db.js is
+// the thin composer. Concatenate the module sources (plus db.js) so this text
+// scan still sees the JS-side DDL literals it asserts against.
+const SCHEMA_DIR = join(HERE, 'db', 'schema');
+const DB_JS = [
+ readFileSync(join(HERE, 'db.js'), 'utf8'),
+ ...readdirSync(SCHEMA_DIR)
+ .filter((f) => f.endsWith('.js') && !f.endsWith('.test.js'))
+ .map((f) => readFileSync(join(SCHEMA_DIR, f), 'utf8')),
+].join('\n');
describe('catalogTypes — registry shape', () => {
it('exposes the six v1 types in order, frozen', () => {
diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.js
index 8b56bbbaf8..1d222365d3 100644
--- a/server/lib/db.catalogDdlParity.test.js
+++ b/server/lib/db.catalogDdlParity.test.js
@@ -1,8 +1,9 @@
/**
* Catalog DDL parity test — locks the schema definitions in
- * `server/scripts/init-db.sql` (fresh-install path) and the `catalogDDL`
- * array inside `server/lib/db.js` `ensureSchema()` (upgrade path) so a future
- * PR that updates one without the other surfaces here instead of in the wild.
+ * `server/scripts/init-db.sql` (fresh-install path) and the per-domain DDL
+ * modules under `server/lib/db/schema/` that `ensureSchema()` composes and runs
+ * (upgrade path — #2832 split them out of `db.js`) so a future PR that updates
+ * one without the other surfaces here instead of in the wild.
*
* Same risk exists for the `memories` / `memory_links` DDL but has been
* tolerated since the memory system landed; this test only covers catalog.
@@ -16,13 +17,24 @@
import { describe, it, expect } from 'vitest';
import { FTS_PAYLOAD_FIELDS } from './catalogTypes.js';
-import { readFileSync } from 'node:fs';
+import { readFileSync, readdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
const HERE = dirname(fileURLToPath(import.meta.url));
const INIT_SQL = readFileSync(join(HERE, '..', 'scripts', 'init-db.sql'), 'utf8');
-const DB_JS = readFileSync(join(HERE, 'db.js'), 'utf8');
+// The ensureSchema() DDL now lives in per-domain modules under db/schema/ (#2832);
+// db.js is the thin composer. Concatenate the module sources (plus db.js itself)
+// so this structural parity check sees every CREATE TABLE / INDEX / trigger the
+// upgrade path runs, exactly as it did when the DDL was inlined in db.js. The
+// variable keeps the DB_JS name because it still represents "the JS-side DDL".
+const SCHEMA_DIR = join(HERE, 'db', 'schema');
+const DB_JS = [
+ readFileSync(join(HERE, 'db.js'), 'utf8'),
+ ...readdirSync(SCHEMA_DIR)
+ .filter((f) => f.endsWith('.js') && !f.endsWith('.test.js'))
+ .map((f) => readFileSync(join(SCHEMA_DIR, f), 'utf8')),
+].join('\n');
const CATALOG_TABLES = [
'catalog_scraps',
diff --git a/server/lib/db.js b/server/lib/db.js
index f5e5adf6fc..8360980374 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -6,6 +6,7 @@
*/
import pg from 'pg';
+import { buildUpgradeDdl, buildCatalogDdl } from './db/schema/index.js';
const { Pool } = pg;
@@ -358,152 +359,7 @@ async function ensureSchemaImpl() {
// either — it must be issued from a dedicated non-transactional path (a
// standalone maintenance script / manual step run outside any transaction).
// See docs/STORAGE.md ("Boot schema upgrades & the CREATE INDEX lock window").
- const upgrades = [
- `ALTER TABLE memories ADD COLUMN IF NOT EXISTS sync_sequence BIGSERIAL`,
- `ALTER TABLE memories ADD COLUMN IF NOT EXISTS origin_instance_id VARCHAR(36)`,
- `CREATE INDEX IF NOT EXISTS idx_memories_origin_instance ON memories (origin_instance_id)`,
- `CREATE INDEX IF NOT EXISTS idx_memories_sync_sequence ON memories (sync_sequence)`,
- // Versioned DB-migration tracker (#1029). Records which ordered migration
- // files in server/scripts/db-migrations/ have been applied on THIS install.
- // It's part of the base schema (created here AND in init-db.sql, parity-
- // locked by db.catalogDdlParity.test.js) so the runner — which executes
- // AFTER ensureSchema() at boot — can always read it. ensureSchema()'s
- // additive CREATE/ADD IF NOT EXISTS gates handle fresh-install schema; the
- // runner handles DELTAS that those gates can't express (renames, type
- // changes, data transforms, embedding-dimension changes).
- `CREATE TABLE IF NOT EXISTS schema_migrations (
- id TEXT PRIMARY KEY,
- applied_at TIMESTAMPTZ DEFAULT NOW()
- )`,
- `CREATE TABLE IF NOT EXISTS tribe_people (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- name TEXT NOT NULL,
- relationship TEXT DEFAULT '',
- ring VARCHAR(32) NOT NULL DEFAULT 'tribe',
- cadence_days INTEGER NOT NULL DEFAULT 45,
- last_contact_on DATE,
- channel TEXT DEFAULT '',
- energy VARCHAR(32) NOT NULL DEFAULT 'steady',
- tags TEXT[] DEFAULT '{}',
- next_move TEXT DEFAULT '',
- notes TEXT DEFAULT '',
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- // Known emails/handles for a person — the deterministic key that maps a
- // calendar attendee / message counterpart back to this tracked person so
- // touchpoints can be auto-logged (#2033).
- `ALTER TABLE tribe_people ADD COLUMN IF NOT EXISTS emails TEXT[] DEFAULT '{}'`,
- // Known phone handles for a person — the deterministic key that maps an
- // iMessage/Signal handle (E.164, e.g. +15551234567) back to this tracked
- // person so touchpoints can be auto-logged (#2151). Mirrors emails[].
- `ALTER TABLE tribe_people ADD COLUMN IF NOT EXISTS phones TEXT[] DEFAULT '{}'`,
- `CREATE INDEX IF NOT EXISTS idx_tribe_people_live ON tribe_people (deleted, ring, updated_at DESC)`,
- `CREATE INDEX IF NOT EXISTS idx_tribe_people_tags ON tribe_people USING gin (tags)`,
- `CREATE INDEX IF NOT EXISTS idx_tribe_people_emails ON tribe_people USING gin (emails)`,
- `CREATE INDEX IF NOT EXISTS idx_tribe_people_phones ON tribe_people USING gin (phones)`,
- `CREATE TABLE IF NOT EXISTS tribe_touchpoints (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- person_id UUID NOT NULL REFERENCES tribe_people(id) ON DELETE CASCADE,
- happened_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
- channel TEXT DEFAULT '',
- summary TEXT DEFAULT '',
- source VARCHAR(32) NOT NULL DEFAULT 'user',
- calendar_account_id TEXT,
- calendar_event_id TEXT,
- dedupe_key TEXT,
- metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW()
- )`,
- // Idempotency key for auto-logged touchpoints (calendar event id / message
- // thread+day). Partial unique index so re-syncs never double-log a person
- // for the same event/thread-day; NULL for hand-logged user touchpoints.
- `ALTER TABLE tribe_touchpoints ADD COLUMN IF NOT EXISTS dedupe_key TEXT`,
- `CREATE INDEX IF NOT EXISTS idx_tribe_touchpoints_person ON tribe_touchpoints (person_id, happened_at DESC)`,
- `CREATE INDEX IF NOT EXISTS idx_tribe_touchpoints_calendar ON tribe_touchpoints (calendar_account_id, calendar_event_id)`,
- `CREATE UNIQUE INDEX IF NOT EXISTS idx_tribe_touchpoints_dedupe ON tribe_touchpoints (person_id, dedupe_key) WHERE dedupe_key IS NOT NULL`,
- `CREATE TABLE IF NOT EXISTS tribe_memory_links (
- person_id UUID NOT NULL REFERENCES tribe_people(id) ON DELETE CASCADE,
- memory_id UUID NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
- note TEXT DEFAULT '',
- created_at TIMESTAMPTZ DEFAULT NOW(),
- PRIMARY KEY (person_id, memory_id)
- )`,
- `CREATE INDEX IF NOT EXISTS idx_tribe_memory_links_memory ON tribe_memory_links (memory_id)`,
- // Human activity timeline (#2150) — unified, machine-local event store fed by
- // message/calendar syncs (later: iMessage, Spotify, YouTube, Signal). Stores
- // metadata + a short summary only; full bodies stay in per-source caches, with
- // metadata pointers (threadId/externalId) back to the source. Idempotent via the
- // unique (source, dedupe_key) index + ON CONFLICT DO NOTHING. Machine-local like
- // Tribe (ADR 2026-06-26) — excluded from peer sync, guarded in peerSync.test.js.
- `CREATE TABLE IF NOT EXISTS human_activity_events (
- id TEXT PRIMARY KEY,
- source TEXT NOT NULL,
- account_id TEXT,
- kind TEXT NOT NULL,
- happened_at TIMESTAMPTZ NOT NULL,
- duration_s INTEGER,
- title TEXT,
- summary TEXT,
- url TEXT,
- participants JSONB DEFAULT '[]'::jsonb,
- metadata JSONB DEFAULT '{}'::jsonb,
- dedupe_key TEXT NOT NULL,
- created_at TIMESTAMPTZ DEFAULT NOW()
- )`,
- `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(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- `CREATE INDEX IF NOT EXISTS idx_creative_commissions_enabled ON creative_commissions (enabled)`,
- // The commission BRIEF federates as of #2686 (record kind `creativeCommission`,
- // schedule/runs/assignment stay machine-local) — a delete must tombstone so it
- // propagates. Idempotent upgrade for installs predating the split.
- `ALTER TABLE creative_commissions ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
- `ALTER TABLE creative_commissions ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
- // Creative Commission FEEDBACK — the split-record federation half (#2686).
- // Unlike the machine-local commission above, taste reactions FEDERATE so a
- // 👍/👎 rated on one machine conditions the same commission's next run on
- // another. One row per reaction; the full sanitized record in `data` JSONB,
- // with commission_id / run_id / created_at / updated_at mirrored for the
- // per-commission hydration query, plus the soft-delete tombstone columns the
- // LWW merge needs (a hard delete never propagates). Record kind
- // `commissionFeedback`, sync category `commissionFeedback`.
- `CREATE TABLE IF NOT EXISTS commission_feedback (
- id TEXT PRIMARY KEY,
- commission_id TEXT,
- run_id TEXT,
- data JSONB NOT NULL,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- `CREATE INDEX IF NOT EXISTS idx_commission_feedback_commission ON commission_feedback (commission_id, created_at)`,
- ];
+ const upgrades = buildUpgradeDdl();
for (const sql of upgrades) {
await pool.query(sql);
}
@@ -517,1082 +373,7 @@ async function ensureSchemaImpl() {
// marked ready while update triggers and HNSW indexes were never installed.
// Cost on a fully-applied install is ~30 Postgres no-op parses (<10ms).
- const catalogDDL = [
- `CREATE TABLE IF NOT EXISTS catalog_scraps (
- id TEXT PRIMARY KEY,
- title TEXT,
- raw_text TEXT NOT NULL,
- source_kind VARCHAR(32) DEFAULT 'paste',
- metadata JSONB DEFAULT '{}'::jsonb,
- embedding vector(768),
- embedding_model VARCHAR(100),
- origin_instance_id VARCHAR(36),
- chunk_index INT NOT NULL DEFAULT 0,
- parent_scrap_id TEXT REFERENCES catalog_scraps(id) ON DELETE CASCADE,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ,
- sync_sequence BIGSERIAL
- )`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_scraps_embedding
- ON catalog_scraps USING hnsw (embedding vector_cosine_ops)
- WITH (m = 16, ef_construction = 64)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_scraps_fts
- ON catalog_scraps USING gin (
- to_tsvector('english', coalesce(title, '') || ' ' || coalesce(raw_text, ''))
- )`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_scraps_sync_seq ON catalog_scraps (sync_sequence)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_scraps_created_at ON catalog_scraps (created_at)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_scraps_origin_instance ON catalog_scraps (origin_instance_id)`,
- // Scrap chunking (catalog v7): a long paste is split into a parent row
- // (chunk_index 0, raw_text = the FULL original text so the FTS index stays
- // populated) plus N child rows (parent_scrap_id → parent, chunk_index 1..N,
- // raw_text = the chunk slice). The extractor processes each child and unions
- // results. The columns are declared inline in the CREATE above (fresh
- // installs) AND re-added idempotently here for EXISTING installs (CREATE IF
- // NOT EXISTS won't add columns to a pre-existing table). Existing rows
- // default to chunk_index 0 / parent_scrap_id NULL — a plain non-chunked
- // scrap, unchanged behavior. We do NOT retro-chunk existing rows.
- `ALTER TABLE catalog_scraps ADD COLUMN IF NOT EXISTS chunk_index INT NOT NULL DEFAULT 0`,
- `ALTER TABLE catalog_scraps ADD COLUMN IF NOT EXISTS parent_scrap_id TEXT REFERENCES catalog_scraps(id) ON DELETE CASCADE`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_scraps_parent ON catalog_scraps (parent_scrap_id)`,
-
- `CREATE TABLE IF NOT EXISTS catalog_ingredients (
- id TEXT PRIMARY KEY,
- -- No DB CHECK on \`type\`: valid types are gated at the app layer via the
- -- INGREDIENT_TYPES registry (catalogTypes.js / catalogValidation.js Zod
- -- enum), so a new system or user-defined type needs no constraint migration.
- -- VARCHAR(32) leaves headroom for longer type ids. The DROP CONSTRAINT +
- -- widen for existing installs runs in the idempotent ALTER block below.
- type VARCHAR(32) NOT NULL,
- name TEXT NOT NULL,
- payload JSONB NOT NULL DEFAULT '{}'::jsonb,
- tags TEXT[] DEFAULT '{}',
- embedding vector(768),
- embedding_model VARCHAR(100),
- origin_instance_id VARCHAR(36),
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ,
- sync_sequence BIGSERIAL
- )`,
- // Relax the legacy `type` CHECK on existing installs: types are now gated at
- // the app layer (INGREDIENT_TYPES registry + Zod enum), so a new system or
- // user-defined type doesn't need a DROP/RE-ADD constraint migration. Postgres
- // auto-named the inline CHECK `catalog_ingredients_type_check`. Both statements
- // are idempotent — DROP IF EXISTS no-ops once gone; the column-type widen
- // no-ops when already VARCHAR(32).
- `ALTER TABLE catalog_ingredients DROP CONSTRAINT IF EXISTS catalog_ingredients_type_check`,
- `ALTER TABLE catalog_ingredients ALTER COLUMN type TYPE VARCHAR(32)`,
- // Postgres can't ALTER the expression of a STORED generated column, so when
- // the v2 expansion needs to land we DROP and re-ADD `search_tsv`. The
- // conditional below (executed after the table CREATE, before the
- // ADD-only fallback) inspects pg_attrdef and rewrites the column ONLY
- // when the current generation expression is missing a v2-only field
- // (`physicalDescription`). That keeps boot O(1) on already-v2 installs —
- // an unconditional DROP+ADD would AccessExclusive-lock the table, rewrite
- // every row, and rebuild the GIN index on every server start.
- // Fresh installs (no column yet) fall through to the ADD IF NOT EXISTS
- // below and skip the DROP entirely.
- `DO $$
- DECLARE
- expr TEXT;
- BEGIN
- SELECT pg_get_expr(d.adbin, d.adrelid)
- INTO expr
- FROM pg_attribute a
- JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
- WHERE a.attrelid = 'catalog_ingredients'::regclass
- AND a.attname = 'search_tsv'
- AND a.attgenerated = 's';
- IF expr IS NOT NULL AND position('physicalDescription' in expr) = 0 THEN
- EXECUTE 'ALTER TABLE catalog_ingredients DROP COLUMN search_tsv';
- END IF;
- END$$`,
- `ALTER TABLE catalog_ingredients ADD COLUMN IF NOT EXISTS search_tsv tsvector
- GENERATED ALWAYS AS (
- setweight(to_tsvector('english', coalesce(name, '')), 'A') ||
- setweight(to_tsvector('english',
- coalesce(payload->>'description', '') || ' ' ||
- coalesce(payload->>'physicalDescription', '') || ' ' ||
- coalesce(payload->>'personality', '') || ' ' ||
- coalesce(payload->>'background', '') || ' ' ||
- coalesce(payload->>'summary', '') || ' ' ||
- coalesce(payload->>'notes', '') || ' ' ||
- coalesce(payload->>'role', '') || ' ' ||
- coalesce(payload->>'motivations', '') || ' ' ||
- coalesce(payload->>'significance', '')
- ), 'B')
- ) STORED`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_embedding
- ON catalog_ingredients USING hnsw (embedding vector_cosine_ops)
- WITH (m = 16, ef_construction = 64)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_fts ON catalog_ingredients USING gin (search_tsv)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_type ON catalog_ingredients (type)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_tags ON catalog_ingredients USING gin (tags)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_sync_seq ON catalog_ingredients (sync_sequence)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_created_at ON catalog_ingredients (created_at)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_origin_instance ON catalog_ingredients (origin_instance_id)`,
-
- `CREATE TABLE IF NOT EXISTS catalog_ingredient_sources (
- ingredient_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
- scrap_id TEXT NOT NULL REFERENCES catalog_scraps(id) ON DELETE CASCADE,
- span JSONB,
- extracted_at TIMESTAMPTZ DEFAULT NOW(),
- sync_sequence BIGSERIAL,
- PRIMARY KEY (ingredient_id, scrap_id)
- )`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_sources_scrap ON catalog_ingredient_sources (scrap_id)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_sources_sync_seq ON catalog_ingredient_sources (sync_sequence)`,
-
- `CREATE TABLE IF NOT EXISTS catalog_ingredient_refs (
- ingredient_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
- ref_kind VARCHAR(32) NOT NULL,
- ref_id TEXT NOT NULL,
- role VARCHAR(64) NOT NULL,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ,
- sync_sequence BIGSERIAL,
- PRIMARY KEY (ingredient_id, ref_kind, ref_id, role)
- )`,
- // Idempotent upgrade path for existing installs predating the soft-delete
- // columns. Without these, an old install boots the new code and silently
- // hard-DELETEs on unlink (no tombstone, no sync_sequence bump) — peers
- // never learn the ref was removed.
- `ALTER TABLE catalog_ingredient_refs ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
- `ALTER TABLE catalog_ingredient_refs ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_refs_target ON catalog_ingredient_refs (ref_kind, ref_id)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_refs_sync_seq ON catalog_ingredient_refs (sync_sequence)`,
-
- // Ingredient↔ingredient edges (the catalog graph seam). `kind` is an
- // app-layer enum (RELATION_KINDS in catalogTypes.js), not a DB CHECK.
- // Both ids CASCADE on ingredient hard-delete; soft-delete columns from day
- // one so unlinks tombstone + propagate to peers.
- `CREATE TABLE IF NOT EXISTS catalog_ingredient_relations (
- from_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
- to_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
- kind VARCHAR(32) NOT NULL,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ,
- sync_sequence BIGSERIAL,
- PRIMARY KEY (from_id, to_id, kind)
- )`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_to ON catalog_ingredient_relations (to_id)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_sync_seq ON catalog_ingredient_relations (sync_sequence)`,
-
- // First-class canonical tag table. Additive index over the freeform
- // `catalog_ingredients.tags TEXT[]` column (which stays as-is). `id` is
- // deterministic (`cat-tag-<canonical-key>`) so the same tag has the same id
- // on every install; `parent_id` self-FK (ON DELETE SET NULL) enables tag
- // hierarchies without cascading a subtree away.
- `CREATE TABLE IF NOT EXISTS catalog_tags (
- id TEXT PRIMARY KEY,
- label TEXT NOT NULL,
- description TEXT,
- color VARCHAR(32),
- parent_id TEXT REFERENCES catalog_tags(id) ON DELETE SET NULL,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- sync_sequence BIGSERIAL
- )`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_tags_label ON catalog_tags (label)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_tags_parent ON catalog_tags (parent_id)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_tags_sync_seq ON catalog_tags (sync_sequence)`,
-
- // Append-only revision history for catalog_ingredients (local audit, not
- // federated). Written by catalogDB.updateIngredient on every content change
- // + a seed row on create; pruned to the last CATALOG_REVISION_RETENTION per
- // ingredient at the app layer. No sync_sequence — revisions stay local; the
- // synced ingredient row already LWW-merges the latest state across peers.
- // Mirrors the catalog_ingredient_revisions block in init-db.sql (parity is
- // asserted by db.catalogDdlParity.test.js).
- `CREATE TABLE IF NOT EXISTS catalog_ingredient_revisions (
- id TEXT PRIMARY KEY,
- ingredient_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
- name TEXT NOT NULL,
- payload JSONB NOT NULL DEFAULT '{}'::jsonb,
- tags TEXT[] DEFAULT '{}',
- source VARCHAR(16) NOT NULL DEFAULT 'user'
- CHECK (source IN ('user', 'extract', 'refine', 'sync')),
- actor VARCHAR(120),
- created_at TIMESTAMPTZ DEFAULT NOW()
- )`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_revisions_ingredient
- ON catalog_ingredient_revisions (ingredient_id, created_at DESC)`,
-
- // Typed media attachments — `media_key` REFERENCES the media library
- // (data/images + history.jsonl sidecar) by key; the bytes are never copied
- // here, so federation ships the key and the receiver matches its own
- // library (missing → metadata-missing integrity surface). `kind` is an
- // app-layer enum (MEDIA_KINDS in catalogTypes.js), not a DB CHECK. Soft-
- // delete from day one so detaches tombstone + propagate. Mirrors the
- // catalog_ingredient_media block in init-db.sql (parity is asserted by
- // db.catalogDdlParity.test.js).
- `CREATE TABLE IF NOT EXISTS catalog_ingredient_media (
- ingredient_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
- media_key TEXT NOT NULL,
- kind VARCHAR(32) NOT NULL,
- role VARCHAR(64),
- caption TEXT,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ,
- sync_sequence BIGSERIAL,
- PRIMARY KEY (ingredient_id, media_key, kind)
- )`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_ingredient ON catalog_ingredient_media (ingredient_id)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_key ON catalog_ingredient_media (media_key)`,
- `CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_sync_seq ON catalog_ingredient_media (sync_sequence)`,
-
- `CREATE OR REPLACE FUNCTION update_catalog_ingredient_timestamp()
- RETURNS TRIGGER AS $$
- DECLARE
- content_changed BOOLEAN;
- BEGIN
- content_changed := (
- NEW.type IS DISTINCT FROM OLD.type OR
- NEW.name IS DISTINCT FROM OLD.name OR
- NEW.payload IS DISTINCT FROM OLD.payload OR
- NEW.tags IS DISTINCT FROM OLD.tags OR
- NEW.embedding IS DISTINCT FROM OLD.embedding OR
- NEW.embedding_model IS DISTINCT FROM OLD.embedding_model OR
- NEW.deleted IS DISTINCT FROM OLD.deleted OR
- NEW.updated_at IS DISTINCT FROM OLD.updated_at
- );
- IF NOT content_changed THEN RETURN NEW; END IF;
- IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
- NEW.updated_at := NOW();
- END IF;
- NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredients', 'sync_sequence'));
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql`,
- `DROP TRIGGER IF EXISTS trg_catalog_ingredient_updated_at ON catalog_ingredients`,
- `CREATE TRIGGER trg_catalog_ingredient_updated_at
- BEFORE UPDATE ON catalog_ingredients
- FOR EACH ROW
- EXECUTE FUNCTION update_catalog_ingredient_timestamp()`,
-
- `CREATE OR REPLACE FUNCTION update_catalog_scrap_timestamp()
- RETURNS TRIGGER AS $$
- DECLARE
- content_changed BOOLEAN;
- BEGIN
- content_changed := (
- NEW.title IS DISTINCT FROM OLD.title OR
- NEW.raw_text IS DISTINCT FROM OLD.raw_text OR
- NEW.source_kind IS DISTINCT FROM OLD.source_kind OR
- NEW.metadata IS DISTINCT FROM OLD.metadata OR
- NEW.embedding IS DISTINCT FROM OLD.embedding OR
- NEW.embedding_model IS DISTINCT FROM OLD.embedding_model OR
- NEW.deleted IS DISTINCT FROM OLD.deleted OR
- NEW.updated_at IS DISTINCT FROM OLD.updated_at
- );
- IF NOT content_changed THEN RETURN NEW; END IF;
- IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
- NEW.updated_at := NOW();
- END IF;
- NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_scraps', 'sync_sequence'));
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql`,
- `DROP TRIGGER IF EXISTS trg_catalog_scrap_updated_at ON catalog_scraps`,
- `CREATE TRIGGER trg_catalog_scrap_updated_at
- BEFORE UPDATE ON catalog_scraps
- FOR EACH ROW
- EXECUTE FUNCTION update_catalog_scrap_timestamp()`,
-
- // Source-link UPDATE bumps sync_sequence so a span change (via
- // `upsertSourceFromPeer` → ON CONFLICT DO UPDATE SET span = ...) doesn't
- // stay invisible to peers (whose cursor would skip past the unchanged seq).
- `CREATE OR REPLACE FUNCTION update_catalog_source_sync_seq()
- RETURNS TRIGGER AS $$
- BEGIN
- IF NEW.span IS DISTINCT FROM OLD.span THEN
- NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_sources', 'sync_sequence'));
- END IF;
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql`,
- `DROP TRIGGER IF EXISTS trg_catalog_source_sync_seq ON catalog_ingredient_sources`,
- `CREATE TRIGGER trg_catalog_source_sync_seq
- BEFORE UPDATE ON catalog_ingredient_sources
- FOR EACH ROW
- EXECUTE FUNCTION update_catalog_source_sync_seq()`,
-
- // Ref-link UPDATE bumps sync_sequence so a soft-delete or revival of a
- // ref row ships as a normal sync event. Without this, the soft-delete
- // path would update `deleted`/`deleted_at` but leave sync_sequence at
- // the original INSERT value — peers past that cursor would never see
- // the tombstone and their "Appears in" panels would stay stale.
- `CREATE OR REPLACE FUNCTION update_catalog_ref_sync_seq()
- RETURNS TRIGGER AS $$
- BEGIN
- IF NEW.deleted IS DISTINCT FROM OLD.deleted
- OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at THEN
- NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_refs', 'sync_sequence'));
- END IF;
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql`,
- `DROP TRIGGER IF EXISTS trg_catalog_ref_sync_seq ON catalog_ingredient_refs`,
- `CREATE TRIGGER trg_catalog_ref_sync_seq
- BEFORE UPDATE ON catalog_ingredient_refs
- FOR EACH ROW
- EXECUTE FUNCTION update_catalog_ref_sync_seq()`,
-
- // Relation UPDATE bumps sync_sequence on soft-delete / revival so a peer
- // sees the tombstone (or un-delete) on its next pull — mirrors the ref
- // trigger above.
- `CREATE OR REPLACE FUNCTION update_catalog_relation_sync_seq()
- RETURNS TRIGGER AS $$
- BEGIN
- IF NEW.deleted IS DISTINCT FROM OLD.deleted
- OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at THEN
- NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_relations', 'sync_sequence'));
- END IF;
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql`,
- `DROP TRIGGER IF EXISTS trg_catalog_relation_sync_seq ON catalog_ingredient_relations`,
- `CREATE TRIGGER trg_catalog_relation_sync_seq
- BEFORE UPDATE ON catalog_ingredient_relations
- FOR EACH ROW
- EXECUTE FUNCTION update_catalog_relation_sync_seq()`,
-
- // Media UPDATE bumps sync_sequence on soft-delete/revival OR a mutable
- // field (role/caption) change so a peer sees the edit/tombstone next pull.
- // Mirrors the relation trigger but also watches the editable metadata.
- `CREATE OR REPLACE FUNCTION update_catalog_media_sync_seq()
- RETURNS TRIGGER AS $$
- BEGIN
- IF NEW.deleted IS DISTINCT FROM OLD.deleted
- OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at
- OR NEW.role IS DISTINCT FROM OLD.role
- OR NEW.caption IS DISTINCT FROM OLD.caption THEN
- NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_media', 'sync_sequence'));
- END IF;
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql`,
- `DROP TRIGGER IF EXISTS trg_catalog_media_sync_seq ON catalog_ingredient_media`,
- `CREATE TRIGGER trg_catalog_media_sync_seq
- BEFORE UPDATE ON catalog_ingredient_media
- FOR EACH ROW
- EXECUTE FUNCTION update_catalog_media_sync_seq()`,
-
- // Tag UPDATE bumps sync_sequence + updated_at on a mutable-field change
- // (label/description/color/parent_id) so a peer sees the edit on its next
- // pull. Mirrors the scrap timestamp trigger.
- `CREATE OR REPLACE FUNCTION update_catalog_tag_timestamp()
- RETURNS TRIGGER AS $$
- DECLARE
- content_changed BOOLEAN;
- BEGIN
- content_changed := (
- NEW.label IS DISTINCT FROM OLD.label OR
- NEW.description IS DISTINCT FROM OLD.description OR
- NEW.color IS DISTINCT FROM OLD.color OR
- NEW.parent_id IS DISTINCT FROM OLD.parent_id OR
- NEW.updated_at IS DISTINCT FROM OLD.updated_at
- );
- IF NOT content_changed THEN RETURN NEW; END IF;
- IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
- NEW.updated_at := NOW();
- END IF;
- NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_tags', 'sync_sequence'));
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql`,
- `DROP TRIGGER IF EXISTS trg_catalog_tag_updated_at ON catalog_tags`,
- `CREATE TRIGGER trg_catalog_tag_updated_at
- BEFORE UPDATE ON catalog_tags
- FOR EACH ROW
- EXECUTE FUNCTION update_catalog_tag_timestamp()`,
-
- // Creative Director projects (Phase 3, issue #997). One row per project;
- // the full record lives in `data` JSONB, with status/created_at/updated_at
- // mirrored into columns (kept in lockstep on every write) for future
- // queries. `listProjects` sorts by created_at. `status` is app-layer gated
- // (PROJECT_STATUSES), no DB CHECK. As of #1564 projects FEDERATE across peers
- // via the per-record peer-sync push pipeline (record kind
- // `creativeDirectorProject`, sync category `creativeDirectorProjects`), so
- // the soft-delete tombstone trio (deleted/deleted_at + LWW updated_at) mirrors
- // the authors table — a delete is a tombstone the merge keeps an out-of-date
- // peer from resurrecting. Mirrors the creative_director_projects block in
- // init-db.sql; the ADD COLUMN upgrades below backfill existing installs.
- `CREATE TABLE IF NOT EXISTS creative_director_projects (
- id TEXT PRIMARY KEY,
- status VARCHAR(32) NOT NULL DEFAULT 'draft',
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- // Backfill the tombstone columns on installs created before #1564 (the
- // CREATE above is a no-op once the table exists). The partial index serves
- // the live-list filter (deleted = FALSE).
- `ALTER TABLE creative_director_projects ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
- `ALTER TABLE creative_director_projects ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
- `CREATE INDEX IF NOT EXISTS idx_creative_director_projects_live ON creative_director_projects (deleted) WHERE deleted = FALSE`,
-
- // Music Video projects (issue #1760). The director scene board's db-primary
- // record: id/status/created_at/updated_at mirrored as columns, the full
- // project (track link, cached audioAnalysis, scenes[]) in `data` JSONB —
- // same shape as creative_director_projects. The soft-delete tombstone trio is
- // present so peer-sync federation (a follow-up) is additive. Mirrors the
- // music_video_projects block in init-db.sql.
- `CREATE TABLE IF NOT EXISTS music_video_projects (
- id TEXT PRIMARY KEY,
- status VARCHAR(32) NOT NULL DEFAULT 'draft',
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- `ALTER TABLE music_video_projects ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
- `ALTER TABLE music_video_projects ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
- `CREATE INDEX IF NOT EXISTS idx_music_video_projects_live ON music_video_projects (deleted) WHERE deleted = FALSE`,
-
- // Mood boards (issue #911). A dedicated inspiration/mood-board canvas,
- // distinct from raw Media History, for collecting visual + textual
- // references that feed the Create suite. One row per board, the full record
- // (name/description/items[]) in `data` JSONB. Items (image-by-media-key or
- // external URL, or a text note + optional caption/source backref) live
- // inline in the board's JSONB rather than a child table — a board is read/
- // written whole, has a small bounded item list, and there are no cross-board
- // item queries. `name` mirrors a column for the live-list sort. As of #1564
- // mood boards FEDERATE across peers via the per-record peer-sync push pipeline
- // (record kind `moodBoard`, sync category `moodBoards`), so the soft-delete
- // tombstone trio (deleted/deleted_at + LWW updated_at) mirrors
- // creative_director_projects — a delete is a tombstone the merge keeps an
- // out-of-date peer from resurrecting. Mirrors the mood_boards block in
- // init-db.sql; the ADD COLUMN upgrades below backfill existing installs.
- `CREATE TABLE IF NOT EXISTS mood_boards (
- id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- // Backfill the tombstone columns on installs created before #1564 (the
- // CREATE above is a no-op once the table exists).
- `ALTER TABLE mood_boards ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
- `ALTER TABLE mood_boards ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
- // updated_at DESC is the board-list "recently touched" sort.
- `CREATE INDEX IF NOT EXISTS idx_mood_boards_updated ON mood_boards (updated_at DESC)`,
- // Partial index for the live-list filter (deleted = FALSE).
- `CREATE INDEX IF NOT EXISTS idx_mood_boards_live ON mood_boards (deleted) WHERE deleted = FALSE`,
-
- // Media asset index (Phase 3.2, issue #1000). One row per generated image
- // or video; the bytes stay on disk (data/images, data/videos) and the
- // sidecar/.json history files remain authoritative — this table is a
- // DERIVED, queryable index, reconciled from disk at boot + kept warm by a
- // generation-completed hook. `media_key` is the shared `<kind>:<ref>`
- // vocabulary (mediaItemKey.js); `kind`/`ref` are mirrored into columns for
- // queries, the full metadata record lives in `data` JSONB. created_at is
- // the asset's own timestamp; indexed_at is when this index row was written.
- // No sync_sequence/tombstone: the index is local-only (rebuilt from disk),
- // not federated — a row vanishes when its file does (prune on reconcile).
- // Mirrors the media_assets block in init-db.sql.
- `CREATE TABLE IF NOT EXISTS media_assets (
- media_key TEXT PRIMARY KEY,
- kind VARCHAR(16) NOT NULL,
- ref TEXT NOT NULL,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- indexed_at TIMESTAMPTZ DEFAULT NOW()
- )`,
- // created_at DESC is the gallery/history sort order; kind narrows
- // images-vs-videos. A composite (kind, created_at DESC) serves both.
- `CREATE INDEX IF NOT EXISTS idx_media_assets_kind_created ON media_assets (kind, created_at DESC)`,
-
- // Catalog user-defined types (Phase 4 lead-in, issue #1001). One row per
- // user-defined ingredient type — the registry that defines catalog row
- // semantics, moved out of data/settings.json (`catalogUserTypes`) so type
- // evolution versions/syncs alongside the catalog data it governs. `id` is
- // the type discriminator (the `type` column on catalog_ingredients + the
- // `cat-<prefix>-<uuid>` mint seed); the full definition lives in `data`
- // JSONB. updated_at / deleted_at mirror the federation LWW clock + tombstone
- // (a soft-deleted type is KEPT as a tombstone row so the deletion federates
- // — setUserCatalogTypes filters tombstones out of the active registry).
- // ≤64 rows, read whole on every warm/sync, so no secondary index (an unused
- // index is just write amplification). Mirrors the catalog_user_types block
- // in init-db.sql.
- `CREATE TABLE IF NOT EXISTS catalog_user_types (
- id TEXT PRIMARY KEY,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted_at TIMESTAMPTZ,
- created_at TIMESTAMPTZ DEFAULT NOW()
- )`,
-
- // Universe Builder records (Phase 3 Create migration, issue #1014). One row
- // per universe, the full sanitized record (canon bibles, categories,
- // compositeSheets, locks, influences) in `data` JSONB, moved out of
- // data/universes/{id}/index.json (collectionStore). Only the fields the
- // service/federation query, join, or sort on are mirrored into columns:
- // `name` (rename-cascade + delete-guard + list sort), `schema_version` (the
- // RECORD-shape version sanitizeTemplate stamps — a column so a future
- // migration can find unmigrated rows without parsing JSONB), `ephemeral`
- // (the snapshot loop filters local-only records), and the LWW/tombstone
- // trio (updated_at/deleted/deleted_at). NO sync_sequence: universes
- // federate via the EXISTING dataSync snapshot/push model (LWW on the body's
- // updatedAt), NOT catalog-style pull cursors — the storage swap is invisible
- // to peers (no schema-version bump). The mirror columns are populated FROM
- // the record body (mirrorTimestamp), not a DB trigger. Mirrors the universes
- // block in init-db.sql.
- `CREATE TABLE IF NOT EXISTS universes (
- id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- schema_version INTEGER NOT NULL DEFAULT 4,
- ephemeral BOOLEAN DEFAULT FALSE,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- // Partial index on the live set — the common list/scan path is "non-deleted
- // universes". updated_at supports LWW-staleness scans.
- `CREATE INDEX IF NOT EXISTS idx_universes_live ON universes (deleted) WHERE deleted = FALSE`,
- `CREATE INDEX IF NOT EXISTS idx_universes_updated ON universes (updated_at)`,
-
- // Universe render-history log (issue #1014). The type-level `config.runs[]`
- // array collectionStore kept in data/universes/index.json (capped 200,
- // NEVER federated — per-peer local) becomes its own table. `universe_id` is
- // a soft ref (no FK): the cascade-clean on universe delete is handled in the
- // service exactly as the file backend did, and a soft ref keeps the table
- // independent of universe-row insert ordering during the one-time import.
- // `data` holds jobIds[]/promptCount/collectionId. Mirrors init-db.sql.
- `CREATE TABLE IF NOT EXISTS universe_runs (
- id TEXT PRIMARY KEY,
- universe_id TEXT NOT NULL,
- collection_id TEXT,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW()
- )`,
- `CREATE INDEX IF NOT EXISTS idx_universe_runs_universe ON universe_runs (universe_id, created_at DESC)`,
-
- // Author personas. One row per reusable author/byline persona, the full
- // sanitized record (name, writingStyle, bio, physicalDescription,
- // headshotStyle, headshotImageUrl) in `data` JSONB. `name` mirrors a column
- // for the live-list sort; the LWW/tombstone trio (updated_at/deleted/
- // deleted_at) is populated FROM the record body. Authors are db-primary AND
- // federated via the per-record peer-sync push pipeline (record kind `author`,
- // sync category `authors`); a federated series also keeps its denormalized
- // `author` byline so a peer that hasn't synced the persona still renders the
- // cover correctly. Mirrors the authors block in init-db.sql.
- `CREATE TABLE IF NOT EXISTS authors (
- id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- `CREATE INDEX IF NOT EXISTS idx_authors_live ON authors (deleted) WHERE deleted = FALSE`,
-
- // Music artists (the Music studio's persona store — analogue of authors).
- // One row per artist, the full sanitized record (name, genre, bio,
- // musicalStyle, physicalDescription, portraitStyle, portraitImageUrl) in
- // `data` JSONB. `name` mirrors a column for the live-list sort; the LWW/
- // tombstone trio is populated FROM the record body. Artists are db-primary
- // and federation-ready (LWW merge mirrors authors), but the artist record
- // kind is not yet registered in peerSync — local-only for now (see issue #1502).
- // Mirrors the artists block in init-db.sql.
- `CREATE TABLE IF NOT EXISTS artists (
- id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- `CREATE INDEX IF NOT EXISTS idx_artists_live ON artists (deleted) WHERE deleted = FALSE`,
-
- // Music albums (the Music studio). One row per album, the full sanitized
- // record (title, artistId+denormalized artist, description, genre,
- // releaseYear, coverImageUrl, ordered trackIds) in `data` JSONB. `title`
- // mirrors a column for the live-list sort. db-primary + federation-ready
- // (LWW merge mirrors artists), not yet registered in peerSync — local-only
- // for now (see issue #1502). Mirrors the albums block in init-db.sql.
- `CREATE TABLE IF NOT EXISTS albums (
- id TEXT PRIMARY KEY,
- title TEXT NOT NULL,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- `CREATE INDEX IF NOT EXISTS idx_albums_live ON albums (deleted) WHERE deleted = FALSE`,
-
- // Music tracks (the Music studio). One row per track, the full sanitized
- // record (title, albumId/artistId FKs + denormalized artist, lyrics, prompt,
- // engine/modelId/durationSec gen metadata, audioFilename pointing into the
- // shared music library at data/music/) in `data` JSONB. `title` mirrors a
- // column for queries. db-primary + federation-ready, not yet registered in
- // peerSync — local-only for now (see issue #1502). Mirrors init-db.sql.
- `CREATE TABLE IF NOT EXISTS tracks (
- id TEXT PRIMARY KEY,
- title TEXT NOT NULL,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- `CREATE INDEX IF NOT EXISTS idx_tracks_live ON tracks (deleted) WHERE deleted = FALSE`,
-
- // Pipeline series (Phase 3 Create migration, issue #1015). One row per
- // series, the full sanitized record (arc/seasons/locks/covers/style) in
- // `data` JSONB, moved out of data/pipeline-series/{id}/index.json
- // (collectionStore). Only the fields the service/federation query, join, or
- // sort on are mirrored into columns: `name` (rename-cascade + list sort),
- // `universe_id` (the hot relationship — the delete-guard "reject universe
- // delete when live series link it" + "series in this universe" lists; soft
- // ref, no FK — a series can sync before its universe arrives), and the
- // promote back-link `writers_room_work_id`. `ephemeral` + the LWW/tombstone
- // trio (updated_at/deleted/deleted_at) populated FROM the record body
- // (mirrorTimestamp), not a DB trigger. NO sync_sequence: pipeline records
- // federate via the EXISTING dataSync snapshot/push model — the storage swap
- // is invisible to peers (no schema-version bump). Mirrors init-db.sql.
- `CREATE TABLE IF NOT EXISTS pipeline_series (
- id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- universe_id TEXT,
- writers_room_work_id TEXT,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- ephemeral BOOLEAN DEFAULT FALSE,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- `CREATE INDEX IF NOT EXISTS idx_series_universe ON pipeline_series (universe_id) WHERE deleted = FALSE`,
- `CREATE INDEX IF NOT EXISTS idx_series_wr_work ON pipeline_series (writers_room_work_id)`,
- `CREATE INDEX IF NOT EXISTS idx_series_updated ON pipeline_series (updated_at)`,
-
- // Pipeline issues (issue #1015). One row per issue; the 8-stage `stages`
- // map (text/visual/audio, runHistory, canonExtraction, covers) + lastRunId
- // pointers stay entirely in `data` JSONB (document-shaped, sanitizer-owned).
- // `series_id` (parent, soft ref), `season_id` (arc grouping), and `number`
- // (renumber-recomputed ordinal) are promoted — the renumber pass reads all
- // issues of a series ordered by number, the single most common cross-record
- // pipeline query, served directly by idx_issues_series (series_id, number).
- // `status` promoted for "issues needing review" dashboards. `ephemeral` +
- // LWW/tombstone trio mirror the body. NO sync_sequence (see pipeline_series).
- // Mirrors init-db.sql.
- `CREATE TABLE IF NOT EXISTS pipeline_issues (
- id TEXT PRIMARY KEY,
- series_id TEXT NOT NULL,
- season_id TEXT,
- number INTEGER,
- status VARCHAR(32),
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- ephemeral BOOLEAN DEFAULT FALSE,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- `CREATE INDEX IF NOT EXISTS idx_issues_series ON pipeline_issues (series_id, number) WHERE deleted = FALSE`,
- `CREATE INDEX IF NOT EXISTS idx_issues_season ON pipeline_issues (season_id) WHERE season_id IS NOT NULL`,
- `CREATE INDEX IF NOT EXISTS idx_issues_updated ON pipeline_issues (updated_at)`,
-
- // Story Builder sessions (issue #1016). One row per session; the conductor
- // bookkeeping (`steps` lock/integrity map, `syncedHashes` baseline,
- // `currentStep`, `llm` picker choice) stays entirely in `data` JSONB. The two
- // FKs `universe_id` / `series_id` are promoted for "sessions linked to this
- // record" lookups. `sync` is promoted because Story Builder is the one store
- // whose federation is OPT-IN — the snapshot loop filters WHERE sync = TRUE to
- // decide what to even consider pushing, so promoting it avoids deserializing
- // every session's `data` per snapshot tick. `ephemeral` + the LWW/tombstone
- // trio mirror the body. NO sync_sequence (sessions ride the existing dataSync
- // snapshot/LWW model, not the per-record push pipeline). Mirrors init-db.sql.
- `CREATE TABLE IF NOT EXISTS story_builder_sessions (
- id TEXT PRIMARY KEY,
- universe_id TEXT,
- series_id TEXT,
- sync BOOLEAN DEFAULT FALSE,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- ephemeral BOOLEAN DEFAULT FALSE,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- `CREATE INDEX IF NOT EXISTS idx_stb_universe ON story_builder_sessions (universe_id)`,
- `CREATE INDEX IF NOT EXISTS idx_stb_series ON story_builder_sessions (series_id)`,
- `CREATE INDEX IF NOT EXISTS idx_stb_updated ON story_builder_sessions (updated_at)`,
-
- // Writers Room (Phase 3 Create migration, issue #1017). FOUR tables replace
- // the bespoke file layout (folders.json, exercises.json, per-work
- // manifest.json). Writers Room is NOT federated — it has no dataSync category
- // and no schema-version gate — so unlike the universe/pipeline/story-builder
- // tables these carry NO `ephemeral`/`sync`/sync_sequence columns and need no
- // mutation epoch. The only thing that stays on disk is the draft prose body
- // (drafts/<draftId>.md, file-primary); its metadata is the draft_versions row.
-
- // Folder tree. Self-ref parent_id (soft, no FK — nested tree). sort_order +
- // name promoted (the library renders the tree ordered by them). Mirrors
- // init-db.sql.
- `CREATE TABLE IF NOT EXISTS writers_room_folders (
- id TEXT PRIMARY KEY,
- parent_id TEXT,
- name TEXT NOT NULL,
- sort_order INTEGER DEFAULT 0,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- `CREATE INDEX IF NOT EXISTS idx_wr_folders_parent ON writers_room_folders (parent_id, sort_order)`,
- // Idempotent upgrade for installs predating folder federation (#1645): without
- // the soft-delete columns an old install boots the new code and hard-DELETEs a
- // folder (no tombstone) — peers never learn it was removed and resurrect it.
- `ALTER TABLE writers_room_folders ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
- `ALTER TABLE writers_room_folders ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
-
- // Work manifests. The drafts[] array moves OUT of `data` into
- // writers_room_draft_versions (the one decomposition — draft versions are a
- // genuine 1-to-many the library + Phase-5 staleness analysis query). imageStyle
- // / liveMode / usage counters stay in `data`. `folder_id`, `title`, `kind`,
- // `status`, the promote/bridge links, and `active_draft_version_id` are
- // promoted for the library list + the resolver (#1018) + the bridge CTAs.
- // SOFT-DELETE added here (`deleted`/`deleted_at`): the file backend hard-deletes
- // via rm -rf; the DB backend aligns with the other stores (import sets
- // deleted = FALSE for all existing works). Soft ref everywhere — no FK.
- // Mirrors init-db.sql.
- `CREATE TABLE IF NOT EXISTS writers_room_works (
- id TEXT PRIMARY KEY,
- folder_id TEXT,
- title TEXT NOT NULL,
- kind VARCHAR(32),
- status VARCHAR(32),
- active_draft_version_id TEXT,
- pipeline_series_id TEXT,
- pipeline_issue_id TEXT,
- cd_project_id TEXT,
- media_collection_id TEXT,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- `CREATE INDEX IF NOT EXISTS idx_wr_works_folder ON writers_room_works (folder_id) WHERE deleted = FALSE`,
- `CREATE INDEX IF NOT EXISTS idx_wr_works_series ON writers_room_works (pipeline_series_id) WHERE pipeline_series_id IS NOT NULL`,
-
- // Draft-version metadata index (file-primary bodies). The .md body stays on
- // disk at data/writers-room/works/<workId>/drafts/<draftId>.md; this row is
- // the queryable index over it: `content_file` (relative path), `content_hash`
- // (sha256 for staleness), `word_count`, `segment_index` (outline), version
- // lineage. asset-file-db-indexed pattern applied to prose. Mirrors init-db.sql.
- `CREATE TABLE IF NOT EXISTS writers_room_draft_versions (
- id TEXT PRIMARY KEY,
- work_id TEXT NOT NULL,
- label TEXT,
- content_file TEXT NOT NULL,
- content_hash TEXT,
- word_count INTEGER DEFAULT 0,
- segment_index JSONB NOT NULL DEFAULT '[]'::jsonb,
- created_from_version_id TEXT,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW()
- )`,
- `CREATE INDEX IF NOT EXISTS idx_wr_drafts_work ON writers_room_draft_versions (work_id, created_at)`,
-
- // Exercise sessions (sprint timer). Monolithic exercises.json → flat table.
- // `work_id`, `status`, started_at promoted for the per-work list (ordered by
- // started_at DESC). prompt/durations/word counts/appendedText stay in `data`.
- // Mirrors init-db.sql.
- `CREATE TABLE IF NOT EXISTS writers_room_exercises (
- id TEXT PRIMARY KEY,
- work_id TEXT,
- status VARCHAR(16),
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- started_at TIMESTAMPTZ,
- finished_at TIMESTAMPTZ,
- deleted BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMPTZ
- )`,
- `CREATE INDEX IF NOT EXISTS idx_wr_exercises_work ON writers_room_exercises (work_id, started_at DESC)`,
- // Idempotent upgrade for installs predating exercise federation (#1645). The
- // tombstone columns let a peer's deletion propagate (LWW never propagates a
- // hard delete); no current path deletes an exercise but a future peer might.
- `ALTER TABLE writers_room_exercises ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
- `ALTER TABLE writers_room_exercises ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
-
- // LoRA training runs (character LoRA training). MUST live here, not only
- // in init-db.sql — init-db.sql runs only on fresh `db.sh setup-native`
- // provisioning, so existing installs + federated peers get new tables
- // exclusively through this boot-time upgrade path. Mirrors init-db.sql.
- `CREATE TABLE IF NOT EXISTS lora_training_runs (
- id TEXT PRIMARY KEY,
- status TEXT NOT NULL,
- character_id TEXT,
- data JSONB NOT NULL DEFAULT '{}'::jsonb,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW()
- )`,
- `CREATE INDEX IF NOT EXISTS idx_lora_training_runs_status ON lora_training_runs (status)`,
- `CREATE INDEX IF NOT EXISTS idx_lora_training_runs_character ON lora_training_runs (character_id)`,
-
- // ─── Privacy Center: PII Vault (issue #2140, epic #2138) ─────────────────
- // Encrypted-at-rest identity facts. `value_enc` is AES-256-GCM ciphertext
- // (`v1:<iv>:<tag>:<ct>`, key from PRIVACY_VAULT_KEY — lib/vaultCrypto.js);
- // plaintext is NEVER stored, `masked_value` is the display form. Machine-
- // local: no federation, no tombstones (deferred, #2148) — a delete is a
- // hard DELETE. `use_for_scans` gates which facts the broker scan engine
- // may disclose (hard-false for ssn/passport/drivers_license/
- // financial_account — enforced app-side). Mirrors the privacy blocks in
- // init-db.sql.
- `CREATE TABLE IF NOT EXISTS privacy_vault_records (
- id UUID PRIMARY KEY,
- type TEXT NOT NULL,
- label TEXT NOT NULL DEFAULT '',
- value_enc TEXT NOT NULL,
- masked_value TEXT NOT NULL DEFAULT '',
- status TEXT NOT NULL DEFAULT 'current',
- valid_from DATE,
- valid_to DATE,
- share_with_twin BOOLEAN NOT NULL DEFAULT FALSE,
- use_for_scans BOOLEAN NOT NULL DEFAULT FALSE,
- notes TEXT NOT NULL DEFAULT '',
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW()
- )`,
- // Type is the primary list filter (all addresses, all emails, ...).
- `CREATE INDEX IF NOT EXISTS idx_privacy_vault_records_type ON privacy_vault_records (type)`,
- // Explicit consent audit rows (v1 subject is always 'self'); the broker
- // opt-out engine builds on this trail. Append-only.
- `CREATE TABLE IF NOT EXISTS privacy_consents (
- id UUID PRIMARY KEY,
- subject TEXT NOT NULL DEFAULT 'self',
- scope TEXT NOT NULL,
- method TEXT NOT NULL,
- granted_at TIMESTAMPTZ DEFAULT NOW()
- )`,
-
- // ─── Privacy Center: Trusted Organizations registry (issue #2141, epic
- // #2138) ──────────────────────────────────────────────────────────────
- // Every organization that has (or had) the user's PII, with a trust
- // stance and per-org holdings linking to the exact vault records each org
- // holds. Data backbone for the change-of-address inventory (Phase 4) and
- // the "who has my PII" view. Machine-local: no federation, no tombstones
- // (same deferred scope as the vault, #2148). Mirrors the privacy blocks
- // in init-db.sql.
- `CREATE TABLE IF NOT EXISTS privacy_orgs (
- id UUID PRIMARY KEY,
- name TEXT NOT NULL,
- category TEXT NOT NULL DEFAULT 'other',
- website TEXT NOT NULL DEFAULT '',
- trust TEXT NOT NULL DEFAULT 'trusted',
- status TEXT NOT NULL DEFAULT 'active',
- contact JSONB NOT NULL DEFAULT '{}'::jsonb,
- social_account_id TEXT,
- notes TEXT NOT NULL DEFAULT '',
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW()
- )`,
- `CREATE INDEX IF NOT EXISTS idx_privacy_orgs_trust ON privacy_orgs (trust)`,
- `CREATE INDEX IF NOT EXISTS idx_privacy_orgs_status ON privacy_orgs (status)`,
- // Which vault records each org holds. Composite PK (no surrogate id) — an
- // org either holds a given vault record or it doesn't, so the pair IS the
- // identity. Cascade both ways: deleting the org or the vault record drops
- // its holdings rows.
- `CREATE TABLE IF NOT EXISTS privacy_org_holdings (
- org_id UUID NOT NULL REFERENCES privacy_orgs (id) ON DELETE CASCADE,
- vault_record_id UUID NOT NULL REFERENCES privacy_vault_records (id) ON DELETE CASCADE,
- status TEXT NOT NULL DEFAULT 'current',
- noted_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- PRIMARY KEY (org_id, vault_record_id)
- )`,
- // Reverse lookup: "which orgs hold vault record X" (getOrgsHoldingRecord).
- `CREATE INDEX IF NOT EXISTS idx_privacy_org_holdings_vault_record ON privacy_org_holdings (vault_record_id)`,
-
- // ─── Privacy Center: data-broker database + case ledger (issue #2144,
- // epic #2138) ──────────────────────────────────────────────────────────
- // `privacy_brokers` is the curated (+ later BADBOOL / CA-registry) database
- // of people-search brokers the exposure-scan/opt-out engine works. Seeded
- // idempotently from data.reference/privacy/brokers.json on first use (NO
- // network at boot). `source`/`confidence` gate the refresh: curated rows
- // (field_verified/documented) are never clobbered by an auto refresh.
- // `cluster_parent` groups sibling brands under one suppression;
- // `disclosure_fields` caps what the engine may ever submit to that broker.
- // Machine-local — no federation, no tombstones (same deferred scope as the
- // vault, #2148). Mirrors the privacy blocks in init-db.sql.
- `CREATE TABLE IF NOT EXISTS privacy_brokers (
- id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- urls JSONB NOT NULL DEFAULT '{}'::jsonb,
- optout JSONB NOT NULL DEFAULT '{}'::jsonb,
- tier SMALLINT NOT NULL DEFAULT 2,
- disclosure_fields TEXT[] NOT NULL DEFAULT '{}',
- cluster_parent TEXT REFERENCES privacy_brokers (id) ON DELETE SET NULL,
- prefer_suppression BOOLEAN NOT NULL DEFAULT FALSE,
- antibot BOOLEAN NOT NULL DEFAULT FALSE,
- source TEXT NOT NULL DEFAULT 'curated',
- confidence TEXT NOT NULL DEFAULT 'documented',
- last_verified DATE,
- enabled BOOLEAN NOT NULL DEFAULT TRUE,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW()
- )`,
- // Planner walks enabled brokers, cluster-parents first.
- `CREATE INDEX IF NOT EXISTS idx_privacy_brokers_enabled ON privacy_brokers (enabled)`,
- `CREATE INDEX IF NOT EXISTS idx_privacy_brokers_cluster_parent ON privacy_brokers (cluster_parent)`,
- // Per-broker exposure/opt-out case ledger with a service-enforced state
- // machine. `state` is validated app-side (privacyBrokers.js); every write
- // stamps `next_recheck_at` (state-dependent backoff). `evidence` holds
- // listing URLs / match basis / screenshot refs — NOT plaintext PII (the
- // engine records only least-disclosure identifiers). A broker delete
- // cascades its cases.
- `CREATE TABLE IF NOT EXISTS privacy_broker_cases (
- id UUID PRIMARY KEY,
- broker_id TEXT NOT NULL REFERENCES privacy_brokers (id) ON DELETE CASCADE,
- state TEXT NOT NULL DEFAULT 'unscanned',
- found BOOLEAN,
- evidence JSONB NOT NULL DEFAULT '{}'::jsonb,
- disclosed_fields TEXT[] NOT NULL DEFAULT '{}',
- channel TEXT,
- reason TEXT,
- next_recheck_at TIMESTAMPTZ,
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW()
- )`,
- // One live case per broker in v1 (self-only subject) — unique so the
- // scan-pass upsert can ON CONFLICT the broker id.
- `CREATE UNIQUE INDEX IF NOT EXISTS idx_privacy_broker_cases_broker ON privacy_broker_cases (broker_id)`,
- // "Which cases are due for a recheck" — the run-loop's primary query.
- `CREATE INDEX IF NOT EXISTS idx_privacy_broker_cases_recheck ON privacy_broker_cases (next_recheck_at)`,
-
- // ─── Privacy Center: change-of-address events (issue #2143, epic #2138) ──
- // One row per "field X changed from A to B" declaration. `vault_record_id`
- // is the OLD record (marked `previous` on declare); `replacement_record_id`
- // is the NEW one (nullable for a removal-only change). Declaring an event
- // flips every `current` holding of the old record to `update_pending` (see
- // privacyChanges.js). Both FKs cascade so removing a vault record cleans up
- // its change events. Machine-local — no federation, no tombstones (same
- // deferred scope as the vault, #2148). Mirrors the block in init-db.sql.
- `CREATE TABLE IF NOT EXISTS privacy_change_events (
- id UUID PRIMARY KEY,
- vault_record_id UUID NOT NULL REFERENCES privacy_vault_records (id) ON DELETE CASCADE,
- replacement_record_id UUID REFERENCES privacy_vault_records (id) ON DELETE SET NULL,
- kind TEXT NOT NULL DEFAULT 'other',
- declared_at TIMESTAMPTZ DEFAULT NOW(),
- note TEXT NOT NULL DEFAULT ''
- )`,
- // "Changes touching this record" — the inventory groups by the old record.
- `CREATE INDEX IF NOT EXISTS idx_privacy_change_events_vault_record ON privacy_change_events (vault_record_id)`,
-
- // ─── Deletion audit log (incident #1248-follow-up) ──────────────────────
- // Append-only forensic trail of EVERY tombstone (soft-delete), un-tombstone
- // (recovery), and hard-delete of user-authored records — written by a DB
- // trigger so it captures deletions from ANY source: the app, a test suite
- // doing raw `DELETE FROM`, or a manual `psql` session. (On 2026-06-13 a CoS
- // agent's test run wiped every universe/series with no trace of who/when;
- // this table closes that gap.) `row_snapshot` keeps the OLD row JSON so a
- // wrongful delete is recoverable from the log alone. Local-only, never
- // federated (no sync_sequence) — each install audits its own mutations.
- // Mirrors the record_audit block in init-db.sql (parity-locked by
- // db.catalogDdlParity.test.js).
- `CREATE TABLE IF NOT EXISTS record_audit (
- id BIGSERIAL PRIMARY KEY,
- table_name TEXT NOT NULL,
- record_id TEXT,
- record_name TEXT,
- action VARCHAR(16) NOT NULL,
- actor TEXT,
- source_query TEXT,
- application_name TEXT,
- backend_pid INTEGER,
- row_snapshot JSONB,
- occurred_at TIMESTAMPTZ DEFAULT NOW()
- )`,
- `CREATE INDEX IF NOT EXISTS idx_record_audit_record ON record_audit (table_name, record_id, occurred_at DESC)`,
- `CREATE INDEX IF NOT EXISTS idx_record_audit_occurred ON record_audit (occurred_at DESC)`,
- `CREATE INDEX IF NOT EXISTS idx_record_audit_action ON record_audit (action, occurred_at DESC)`,
-
- // Generic audit trigger. Works on any table via to_jsonb(OLD/NEW) so it needs
- // no per-table column knowledge: `id`/`name`/`title`/`deleted`/`deleted_at`
- // are read out of the row JSON (absent keys → NULL). A row is "deleted" when
- // its `deleted` boolean is true OR its `deleted_at` is non-null (covers both
- // the bool-trio tables and catalog_user_types' deleted_at-only shape).
- // `actor` reads the optional `portos.actor` GUC the app MAY set per session;
- // `source_query` captures current_query() so even an un-attributed raw DELETE
- // is traceable. AFTER trigger: only committed-path rows are logged.
- `CREATE OR REPLACE FUNCTION record_audit_log()
- RETURNS TRIGGER AS $$
- DECLARE
- oldj JSONB := to_jsonb(OLD);
- newj JSONB;
- was_deleted BOOLEAN;
- now_deleted BOOLEAN;
- v_action TEXT;
- BEGIN
- IF TG_OP = 'DELETE' THEN
- v_action := 'hard_delete';
- INSERT INTO record_audit
- (table_name, record_id, record_name, action, actor, source_query, application_name, backend_pid, row_snapshot)
- VALUES
- (TG_TABLE_NAME, oldj->>'id', COALESCE(oldj->>'name', oldj->>'title'), v_action,
- current_setting('portos.actor', true), current_query(),
- current_setting('application_name', true), pg_backend_pid(), oldj);
- RETURN OLD;
- END IF;
-
- newj := to_jsonb(NEW);
- was_deleted := COALESCE((oldj->>'deleted')::boolean, oldj->>'deleted_at' IS NOT NULL, false);
- now_deleted := COALESCE((newj->>'deleted')::boolean, newj->>'deleted_at' IS NOT NULL, false);
- IF now_deleted AND NOT was_deleted THEN
- v_action := 'tombstone';
- ELSIF was_deleted AND NOT now_deleted THEN
- v_action := 'untombstone';
- ELSE
- RETURN NEW;
- END IF;
- INSERT INTO record_audit
- (table_name, record_id, record_name, action, actor, source_query, application_name, backend_pid, row_snapshot)
- VALUES
- (TG_TABLE_NAME, newj->>'id', COALESCE(newj->>'name', newj->>'title'), v_action,
- current_setting('portos.actor', true), current_query(),
- current_setting('application_name', true), pg_backend_pid(), newj);
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql`,
- ];
-
- // Attach the audit trigger to every user-authored-content table. Adding a
- // table here is all it takes to audit its deletions. (Keep in sync with the
- // AUDITED_RECORD_TABLES list in init-db.sql.)
- const auditedTables = [
- 'universes', 'universe_runs', 'pipeline_series', 'pipeline_issues',
- 'story_builder_sessions', 'writers_room_works', 'writers_room_folders',
- 'writers_room_draft_versions', 'catalog_ingredients', 'catalog_scraps',
- 'catalog_user_types', 'creative_director_projects', 'mood_boards',
- 'lora_training_runs', 'authors', 'artists', 'albums', 'tracks', 'tribe_people', 'tribe_touchpoints',
- ];
- for (const t of auditedTables) {
- catalogDDL.push(`DROP TRIGGER IF EXISTS trg_${t}_audit ON ${t}`);
- catalogDDL.push(
- `CREATE TRIGGER trg_${t}_audit AFTER UPDATE OR DELETE ON ${t} FOR EACH ROW EXECUTE FUNCTION record_audit_log()`,
- );
- }
+ const catalogDDL = buildCatalogDdl();
for (const sql of catalogDDL) {
await pool.query(sql);
diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.md
new file mode 100644
index 0000000000..bfe52eaff7
--- /dev/null
+++ b/server/lib/db/schema/README.md
@@ -0,0 +1,43 @@
+# `server/lib/db/schema/` — per-domain boot DDL
+
+The idempotent `CREATE TABLE` / `CREATE INDEX` / trigger DDL that
+`ensureSchemaImpl()` (in `server/lib/db.js`) runs on every boot, split out of
+that formerly ~1265-line function into one module per domain (#2832). Each
+module exports a plain **statement array**; `index.js` re-exports them and
+composes the two ordered lists the composer runs.
+
+**Byte-identical, order-preserving.** These modules were extracted verbatim —
+statement text and ordering are unchanged, so the composed schema is identical
+to the pre-split inline version. **Order is load-bearing** (FK references, the
+`record_audit_log()` function preceding its triggers, and `catalog_user_types`'
+original post-media position), so if you add a table, append it in the domain
+module and keep the composer order in `index.js` intact.
+
+Parity with `server/scripts/init-db.sql` (the fresh-install path) is locked by
+`server/lib/db.catalogDdlParity.test.js`, which reads these module sources.
+
+| Module | Export(s) | Domain |
+|---|---|---|
+| `core.js` | `coreDdl` | Memory sync columns + the `schema_migrations` version tracker |
+| `tribe.js` | `tribeDdl` | Tribe CRM — people, touchpoints, memory links (machine-local) |
+| `humanActivity.js` | `humanActivityDdl` | Human-activity timeline event store (machine-local) |
+| `commissions.js` | `commissionsDdl` | Creative Commissions + feedback (machine-local) |
+| `catalog.js` | `catalogDdl`, `catalogUserTypesDdl` | Catalog scraps/ingredients/tags/media + user-defined types |
+| `media.js` | `mediaDdl` | Creative-director / music-video projects, mood boards, media assets |
+| `universes.js` | `universesDdl` | Universes + universe run history |
+| `library.js` | `libraryDdl` | Authors, artists, albums, tracks |
+| `pipeline.js` | `pipelineDdl` | Pipeline series, issues, story-builder sessions |
+| `writersRoom.js` | `writersRoomDdl` | Writers-Room folders, works, draft versions, exercises |
+| `lora.js` | `loraDdl` | LoRA training runs |
+| `privacy.js` | `privacyDdl` | Privacy suite — vault, consents, orgs, brokers, change events |
+| `audit.js` | `auditDdl`, `auditedTables`, `buildAuditTriggers()` | `record_audit` table/function + per-table audit triggers |
+
+### Composer (`index.js`)
+
+- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `commissions`).
+- `buildCatalogDdl()` → phase-2 list (`catalog` → `media` → `catalogUserTypes` →
+ `universes` → `library` → `pipeline` → `writersRoom` → `lora` → `privacy` →
+ `audit` DDL → audit triggers).
+
+`ensureSchemaImpl()` calls these two builders and runs each list through
+`pool.query` in order.
diff --git a/server/lib/db/schema/audit.js b/server/lib/db/schema/audit.js
new file mode 100644
index 0000000000..302fbba337
--- /dev/null
+++ b/server/lib/db/schema/audit.js
@@ -0,0 +1,108 @@
+// Record-audit DDL — the audit-log table + the generic record_audit_log()
+// trigger function, the list of audited tables, and the trigger builder.
+// Extracted verbatim from ensureSchemaImpl() in server/lib/db.js (#2832) with
+// zero behavior change. Parity-locked against server/scripts/init-db.sql by
+// db.catalogDdlParity.test.js — keep auditedTables in sync with the
+// AUDITED_RECORD_TABLES list there.
+export const auditDdl = [
+ // ─── Deletion audit log (incident #1248-follow-up) ──────────────────────
+ // Append-only forensic trail of EVERY tombstone (soft-delete), un-tombstone
+ // (recovery), and hard-delete of user-authored records — written by a DB
+ // trigger so it captures deletions from ANY source: the app, a test suite
+ // doing raw `DELETE FROM`, or a manual `psql` session. (On 2026-06-13 a CoS
+ // agent's test run wiped every universe/series with no trace of who/when;
+ // this table closes that gap.) `row_snapshot` keeps the OLD row JSON so a
+ // wrongful delete is recoverable from the log alone. Local-only, never
+ // federated (no sync_sequence) — each install audits its own mutations.
+ // Mirrors the record_audit block in init-db.sql (parity-locked by
+ // db.catalogDdlParity.test.js).
+ `CREATE TABLE IF NOT EXISTS record_audit (
+ id BIGSERIAL PRIMARY KEY,
+ table_name TEXT NOT NULL,
+ record_id TEXT,
+ record_name TEXT,
+ action VARCHAR(16) NOT NULL,
+ actor TEXT,
+ source_query TEXT,
+ application_name TEXT,
+ backend_pid INTEGER,
+ row_snapshot JSONB,
+ occurred_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_record_audit_record ON record_audit (table_name, record_id, occurred_at DESC)`,
+ `CREATE INDEX IF NOT EXISTS idx_record_audit_occurred ON record_audit (occurred_at DESC)`,
+ `CREATE INDEX IF NOT EXISTS idx_record_audit_action ON record_audit (action, occurred_at DESC)`,
+
+ // Generic audit trigger. Works on any table via to_jsonb(OLD/NEW) so it needs
+ // no per-table column knowledge: `id`/`name`/`title`/`deleted`/`deleted_at`
+ // are read out of the row JSON (absent keys → NULL). A row is "deleted" when
+ // its `deleted` boolean is true OR its `deleted_at` is non-null (covers both
+ // the bool-trio tables and catalog_user_types' deleted_at-only shape).
+ // `actor` reads the optional `portos.actor` GUC the app MAY set per session;
+ // `source_query` captures current_query() so even an un-attributed raw DELETE
+ // is traceable. AFTER trigger: only committed-path rows are logged.
+ `CREATE OR REPLACE FUNCTION record_audit_log()
+ RETURNS TRIGGER AS $$
+ DECLARE
+ oldj JSONB := to_jsonb(OLD);
+ newj JSONB;
+ was_deleted BOOLEAN;
+ now_deleted BOOLEAN;
+ v_action TEXT;
+ BEGIN
+ IF TG_OP = 'DELETE' THEN
+ v_action := 'hard_delete';
+ INSERT INTO record_audit
+ (table_name, record_id, record_name, action, actor, source_query, application_name, backend_pid, row_snapshot)
+ VALUES
+ (TG_TABLE_NAME, oldj->>'id', COALESCE(oldj->>'name', oldj->>'title'), v_action,
+ current_setting('portos.actor', true), current_query(),
+ current_setting('application_name', true), pg_backend_pid(), oldj);
+ RETURN OLD;
+ END IF;
+
+ newj := to_jsonb(NEW);
+ was_deleted := COALESCE((oldj->>'deleted')::boolean, oldj->>'deleted_at' IS NOT NULL, false);
+ now_deleted := COALESCE((newj->>'deleted')::boolean, newj->>'deleted_at' IS NOT NULL, false);
+ IF now_deleted AND NOT was_deleted THEN
+ v_action := 'tombstone';
+ ELSIF was_deleted AND NOT now_deleted THEN
+ v_action := 'untombstone';
+ ELSE
+ RETURN NEW;
+ END IF;
+ INSERT INTO record_audit
+ (table_name, record_id, record_name, action, actor, source_query, application_name, backend_pid, row_snapshot)
+ VALUES
+ (TG_TABLE_NAME, newj->>'id', COALESCE(newj->>'name', newj->>'title'), v_action,
+ current_setting('portos.actor', true), current_query(),
+ current_setting('application_name', true), pg_backend_pid(), newj);
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql`,
+];
+
+// Attach the audit trigger to every user-authored-content table. Adding a
+// table here is all it takes to audit its deletions. (Keep in sync with the
+// AUDITED_RECORD_TABLES list in init-db.sql.)
+export const auditedTables = [
+ 'universes', 'universe_runs', 'pipeline_series', 'pipeline_issues',
+ 'story_builder_sessions', 'writers_room_works', 'writers_room_folders',
+ 'writers_room_draft_versions', 'catalog_ingredients', 'catalog_scraps',
+ 'catalog_user_types', 'creative_director_projects', 'mood_boards',
+ 'lora_training_runs', 'authors', 'artists', 'albums', 'tracks', 'tribe_people', 'tribe_touchpoints',
+];
+
+// Build the per-table DROP/CREATE audit-trigger statements in the original
+// order (two statements per table). Appended after auditDdl by the composer so
+// the executed DDL is byte-identical to the pre-split inline loop.
+export function buildAuditTriggers() {
+ const stmts = [];
+ for (const t of auditedTables) {
+ stmts.push(`DROP TRIGGER IF EXISTS trg_${t}_audit ON ${t}`);
+ stmts.push(
+ `CREATE TRIGGER trg_${t}_audit AFTER UPDATE OR DELETE ON ${t} FOR EACH ROW EXECUTE FUNCTION record_audit_log()`,
+ );
+ }
+ return stmts;
+}
diff --git a/server/lib/db/schema/catalog.js b/server/lib/db/schema/catalog.js
new file mode 100644
index 0000000000..367439bc49
--- /dev/null
+++ b/server/lib/db/schema/catalog.js
@@ -0,0 +1,429 @@
+// Catalog DDL — scraps, ingredients, sources/refs/relations, tags, revisions,
+// ingredient media, and the user-defined ingredient types. Extracted verbatim
+// from ensureSchemaImpl() in server/lib/db.js (#2832) with zero behavior change.
+// Parity-locked against server/scripts/init-db.sql by db.catalogDdlParity.test.js.
+//
+// catalog_user_types is a separate export because in the original array it sits
+// AFTER the media block, not adjacent to the other catalog tables — the composer
+// (index.js) inserts it at that same position so the DDL order is byte-identical.
+export const catalogDdl = [
+ `CREATE TABLE IF NOT EXISTS catalog_scraps (
+ id TEXT PRIMARY KEY,
+ title TEXT,
+ raw_text TEXT NOT NULL,
+ source_kind VARCHAR(32) DEFAULT 'paste',
+ metadata JSONB DEFAULT '{}'::jsonb,
+ embedding vector(768),
+ embedding_model VARCHAR(100),
+ origin_instance_id VARCHAR(36),
+ chunk_index INT NOT NULL DEFAULT 0,
+ parent_scrap_id TEXT REFERENCES catalog_scraps(id) ON DELETE CASCADE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ,
+ sync_sequence BIGSERIAL
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_scraps_embedding
+ ON catalog_scraps USING hnsw (embedding vector_cosine_ops)
+ WITH (m = 16, ef_construction = 64)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_scraps_fts
+ ON catalog_scraps USING gin (
+ to_tsvector('english', coalesce(title, '') || ' ' || coalesce(raw_text, ''))
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_scraps_sync_seq ON catalog_scraps (sync_sequence)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_scraps_created_at ON catalog_scraps (created_at)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_scraps_origin_instance ON catalog_scraps (origin_instance_id)`,
+ // Scrap chunking (catalog v7): a long paste is split into a parent row
+ // (chunk_index 0, raw_text = the FULL original text so the FTS index stays
+ // populated) plus N child rows (parent_scrap_id → parent, chunk_index 1..N,
+ // raw_text = the chunk slice). The extractor processes each child and unions
+ // results. The columns are declared inline in the CREATE above (fresh
+ // installs) AND re-added idempotently here for EXISTING installs (CREATE IF
+ // NOT EXISTS won't add columns to a pre-existing table). Existing rows
+ // default to chunk_index 0 / parent_scrap_id NULL — a plain non-chunked
+ // scrap, unchanged behavior. We do NOT retro-chunk existing rows.
+ `ALTER TABLE catalog_scraps ADD COLUMN IF NOT EXISTS chunk_index INT NOT NULL DEFAULT 0`,
+ `ALTER TABLE catalog_scraps ADD COLUMN IF NOT EXISTS parent_scrap_id TEXT REFERENCES catalog_scraps(id) ON DELETE CASCADE`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_scraps_parent ON catalog_scraps (parent_scrap_id)`,
+
+ `CREATE TABLE IF NOT EXISTS catalog_ingredients (
+ id TEXT PRIMARY KEY,
+ -- No DB CHECK on \`type\`: valid types are gated at the app layer via the
+ -- INGREDIENT_TYPES registry (catalogTypes.js / catalogValidation.js Zod
+ -- enum), so a new system or user-defined type needs no constraint migration.
+ -- VARCHAR(32) leaves headroom for longer type ids. The DROP CONSTRAINT +
+ -- widen for existing installs runs in the idempotent ALTER block below.
+ type VARCHAR(32) NOT NULL,
+ name TEXT NOT NULL,
+ payload JSONB NOT NULL DEFAULT '{}'::jsonb,
+ tags TEXT[] DEFAULT '{}',
+ embedding vector(768),
+ embedding_model VARCHAR(100),
+ origin_instance_id VARCHAR(36),
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ,
+ sync_sequence BIGSERIAL
+ )`,
+ // Relax the legacy `type` CHECK on existing installs: types are now gated at
+ // the app layer (INGREDIENT_TYPES registry + Zod enum), so a new system or
+ // user-defined type doesn't need a DROP/RE-ADD constraint migration. Postgres
+ // auto-named the inline CHECK `catalog_ingredients_type_check`. Both statements
+ // are idempotent — DROP IF EXISTS no-ops once gone; the column-type widen
+ // no-ops when already VARCHAR(32).
+ `ALTER TABLE catalog_ingredients DROP CONSTRAINT IF EXISTS catalog_ingredients_type_check`,
+ `ALTER TABLE catalog_ingredients ALTER COLUMN type TYPE VARCHAR(32)`,
+ // Postgres can't ALTER the expression of a STORED generated column, so when
+ // the v2 expansion needs to land we DROP and re-ADD `search_tsv`. The
+ // conditional below (executed after the table CREATE, before the
+ // ADD-only fallback) inspects pg_attrdef and rewrites the column ONLY
+ // when the current generation expression is missing a v2-only field
+ // (`physicalDescription`). That keeps boot O(1) on already-v2 installs —
+ // an unconditional DROP+ADD would AccessExclusive-lock the table, rewrite
+ // every row, and rebuild the GIN index on every server start.
+ // Fresh installs (no column yet) fall through to the ADD IF NOT EXISTS
+ // below and skip the DROP entirely.
+ `DO $$
+ DECLARE
+ expr TEXT;
+ BEGIN
+ SELECT pg_get_expr(d.adbin, d.adrelid)
+ INTO expr
+ FROM pg_attribute a
+ JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
+ WHERE a.attrelid = 'catalog_ingredients'::regclass
+ AND a.attname = 'search_tsv'
+ AND a.attgenerated = 's';
+ IF expr IS NOT NULL AND position('physicalDescription' in expr) = 0 THEN
+ EXECUTE 'ALTER TABLE catalog_ingredients DROP COLUMN search_tsv';
+ END IF;
+ END$$`,
+ `ALTER TABLE catalog_ingredients ADD COLUMN IF NOT EXISTS search_tsv tsvector
+ GENERATED ALWAYS AS (
+ setweight(to_tsvector('english', coalesce(name, '')), 'A') ||
+ setweight(to_tsvector('english',
+ coalesce(payload->>'description', '') || ' ' ||
+ coalesce(payload->>'physicalDescription', '') || ' ' ||
+ coalesce(payload->>'personality', '') || ' ' ||
+ coalesce(payload->>'background', '') || ' ' ||
+ coalesce(payload->>'summary', '') || ' ' ||
+ coalesce(payload->>'notes', '') || ' ' ||
+ coalesce(payload->>'role', '') || ' ' ||
+ coalesce(payload->>'motivations', '') || ' ' ||
+ coalesce(payload->>'significance', '')
+ ), 'B')
+ ) STORED`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_embedding
+ ON catalog_ingredients USING hnsw (embedding vector_cosine_ops)
+ WITH (m = 16, ef_construction = 64)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_fts ON catalog_ingredients USING gin (search_tsv)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_type ON catalog_ingredients (type)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_tags ON catalog_ingredients USING gin (tags)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_sync_seq ON catalog_ingredients (sync_sequence)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_created_at ON catalog_ingredients (created_at)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_origin_instance ON catalog_ingredients (origin_instance_id)`,
+
+ `CREATE TABLE IF NOT EXISTS catalog_ingredient_sources (
+ ingredient_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
+ scrap_id TEXT NOT NULL REFERENCES catalog_scraps(id) ON DELETE CASCADE,
+ span JSONB,
+ extracted_at TIMESTAMPTZ DEFAULT NOW(),
+ sync_sequence BIGSERIAL,
+ PRIMARY KEY (ingredient_id, scrap_id)
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_sources_scrap ON catalog_ingredient_sources (scrap_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_sources_sync_seq ON catalog_ingredient_sources (sync_sequence)`,
+
+ `CREATE TABLE IF NOT EXISTS catalog_ingredient_refs (
+ ingredient_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
+ ref_kind VARCHAR(32) NOT NULL,
+ ref_id TEXT NOT NULL,
+ role VARCHAR(64) NOT NULL,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ,
+ sync_sequence BIGSERIAL,
+ PRIMARY KEY (ingredient_id, ref_kind, ref_id, role)
+ )`,
+ // Idempotent upgrade path for existing installs predating the soft-delete
+ // columns. Without these, an old install boots the new code and silently
+ // hard-DELETEs on unlink (no tombstone, no sync_sequence bump) — peers
+ // never learn the ref was removed.
+ `ALTER TABLE catalog_ingredient_refs ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
+ `ALTER TABLE catalog_ingredient_refs ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_refs_target ON catalog_ingredient_refs (ref_kind, ref_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_refs_sync_seq ON catalog_ingredient_refs (sync_sequence)`,
+
+ // Ingredient↔ingredient edges (the catalog graph seam). `kind` is an
+ // app-layer enum (RELATION_KINDS in catalogTypes.js), not a DB CHECK.
+ // Both ids CASCADE on ingredient hard-delete; soft-delete columns from day
+ // one so unlinks tombstone + propagate to peers.
+ `CREATE TABLE IF NOT EXISTS catalog_ingredient_relations (
+ from_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
+ to_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
+ kind VARCHAR(32) NOT NULL,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ,
+ sync_sequence BIGSERIAL,
+ PRIMARY KEY (from_id, to_id, kind)
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_to ON catalog_ingredient_relations (to_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_sync_seq ON catalog_ingredient_relations (sync_sequence)`,
+
+ // First-class canonical tag table. Additive index over the freeform
+ // `catalog_ingredients.tags TEXT[]` column (which stays as-is). `id` is
+ // deterministic (`cat-tag-<canonical-key>`) so the same tag has the same id
+ // on every install; `parent_id` self-FK (ON DELETE SET NULL) enables tag
+ // hierarchies without cascading a subtree away.
+ `CREATE TABLE IF NOT EXISTS catalog_tags (
+ id TEXT PRIMARY KEY,
+ label TEXT NOT NULL,
+ description TEXT,
+ color VARCHAR(32),
+ parent_id TEXT REFERENCES catalog_tags(id) ON DELETE SET NULL,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ sync_sequence BIGSERIAL
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_tags_label ON catalog_tags (label)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_tags_parent ON catalog_tags (parent_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_tags_sync_seq ON catalog_tags (sync_sequence)`,
+
+ // Append-only revision history for catalog_ingredients (local audit, not
+ // federated). Written by catalogDB.updateIngredient on every content change
+ // + a seed row on create; pruned to the last CATALOG_REVISION_RETENTION per
+ // ingredient at the app layer. No sync_sequence — revisions stay local; the
+ // synced ingredient row already LWW-merges the latest state across peers.
+ // Mirrors the catalog_ingredient_revisions block in init-db.sql (parity is
+ // asserted by db.catalogDdlParity.test.js).
+ `CREATE TABLE IF NOT EXISTS catalog_ingredient_revisions (
+ id TEXT PRIMARY KEY,
+ ingredient_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ payload JSONB NOT NULL DEFAULT '{}'::jsonb,
+ tags TEXT[] DEFAULT '{}',
+ source VARCHAR(16) NOT NULL DEFAULT 'user'
+ CHECK (source IN ('user', 'extract', 'refine', 'sync')),
+ actor VARCHAR(120),
+ created_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_revisions_ingredient
+ ON catalog_ingredient_revisions (ingredient_id, created_at DESC)`,
+
+ // Typed media attachments — `media_key` REFERENCES the media library
+ // (data/images + history.jsonl sidecar) by key; the bytes are never copied
+ // here, so federation ships the key and the receiver matches its own
+ // library (missing → metadata-missing integrity surface). `kind` is an
+ // app-layer enum (MEDIA_KINDS in catalogTypes.js), not a DB CHECK. Soft-
+ // delete from day one so detaches tombstone + propagate. Mirrors the
+ // catalog_ingredient_media block in init-db.sql (parity is asserted by
+ // db.catalogDdlParity.test.js).
+ `CREATE TABLE IF NOT EXISTS catalog_ingredient_media (
+ ingredient_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
+ media_key TEXT NOT NULL,
+ kind VARCHAR(32) NOT NULL,
+ role VARCHAR(64),
+ caption TEXT,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ,
+ sync_sequence BIGSERIAL,
+ PRIMARY KEY (ingredient_id, media_key, kind)
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_ingredient ON catalog_ingredient_media (ingredient_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_key ON catalog_ingredient_media (media_key)`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_sync_seq ON catalog_ingredient_media (sync_sequence)`,
+
+ `CREATE OR REPLACE FUNCTION update_catalog_ingredient_timestamp()
+ RETURNS TRIGGER AS $$
+ DECLARE
+ content_changed BOOLEAN;
+ BEGIN
+ content_changed := (
+ NEW.type IS DISTINCT FROM OLD.type OR
+ NEW.name IS DISTINCT FROM OLD.name OR
+ NEW.payload IS DISTINCT FROM OLD.payload OR
+ NEW.tags IS DISTINCT FROM OLD.tags OR
+ NEW.embedding IS DISTINCT FROM OLD.embedding OR
+ NEW.embedding_model IS DISTINCT FROM OLD.embedding_model OR
+ NEW.deleted IS DISTINCT FROM OLD.deleted OR
+ NEW.updated_at IS DISTINCT FROM OLD.updated_at
+ );
+ IF NOT content_changed THEN RETURN NEW; END IF;
+ IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
+ NEW.updated_at := NOW();
+ END IF;
+ NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredients', 'sync_sequence'));
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql`,
+ `DROP TRIGGER IF EXISTS trg_catalog_ingredient_updated_at ON catalog_ingredients`,
+ `CREATE TRIGGER trg_catalog_ingredient_updated_at
+ BEFORE UPDATE ON catalog_ingredients
+ FOR EACH ROW
+ EXECUTE FUNCTION update_catalog_ingredient_timestamp()`,
+
+ `CREATE OR REPLACE FUNCTION update_catalog_scrap_timestamp()
+ RETURNS TRIGGER AS $$
+ DECLARE
+ content_changed BOOLEAN;
+ BEGIN
+ content_changed := (
+ NEW.title IS DISTINCT FROM OLD.title OR
+ NEW.raw_text IS DISTINCT FROM OLD.raw_text OR
+ NEW.source_kind IS DISTINCT FROM OLD.source_kind OR
+ NEW.metadata IS DISTINCT FROM OLD.metadata OR
+ NEW.embedding IS DISTINCT FROM OLD.embedding OR
+ NEW.embedding_model IS DISTINCT FROM OLD.embedding_model OR
+ NEW.deleted IS DISTINCT FROM OLD.deleted OR
+ NEW.updated_at IS DISTINCT FROM OLD.updated_at
+ );
+ IF NOT content_changed THEN RETURN NEW; END IF;
+ IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
+ NEW.updated_at := NOW();
+ END IF;
+ NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_scraps', 'sync_sequence'));
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql`,
+ `DROP TRIGGER IF EXISTS trg_catalog_scrap_updated_at ON catalog_scraps`,
+ `CREATE TRIGGER trg_catalog_scrap_updated_at
+ BEFORE UPDATE ON catalog_scraps
+ FOR EACH ROW
+ EXECUTE FUNCTION update_catalog_scrap_timestamp()`,
+
+ // Source-link UPDATE bumps sync_sequence so a span change (via
+ // `upsertSourceFromPeer` → ON CONFLICT DO UPDATE SET span = ...) doesn't
+ // stay invisible to peers (whose cursor would skip past the unchanged seq).
+ `CREATE OR REPLACE FUNCTION update_catalog_source_sync_seq()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ IF NEW.span IS DISTINCT FROM OLD.span THEN
+ NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_sources', 'sync_sequence'));
+ END IF;
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql`,
+ `DROP TRIGGER IF EXISTS trg_catalog_source_sync_seq ON catalog_ingredient_sources`,
+ `CREATE TRIGGER trg_catalog_source_sync_seq
+ BEFORE UPDATE ON catalog_ingredient_sources
+ FOR EACH ROW
+ EXECUTE FUNCTION update_catalog_source_sync_seq()`,
+
+ // Ref-link UPDATE bumps sync_sequence so a soft-delete or revival of a
+ // ref row ships as a normal sync event. Without this, the soft-delete
+ // path would update `deleted`/`deleted_at` but leave sync_sequence at
+ // the original INSERT value — peers past that cursor would never see
+ // the tombstone and their "Appears in" panels would stay stale.
+ `CREATE OR REPLACE FUNCTION update_catalog_ref_sync_seq()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ IF NEW.deleted IS DISTINCT FROM OLD.deleted
+ OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at THEN
+ NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_refs', 'sync_sequence'));
+ END IF;
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql`,
+ `DROP TRIGGER IF EXISTS trg_catalog_ref_sync_seq ON catalog_ingredient_refs`,
+ `CREATE TRIGGER trg_catalog_ref_sync_seq
+ BEFORE UPDATE ON catalog_ingredient_refs
+ FOR EACH ROW
+ EXECUTE FUNCTION update_catalog_ref_sync_seq()`,
+
+ // Relation UPDATE bumps sync_sequence on soft-delete / revival so a peer
+ // sees the tombstone (or un-delete) on its next pull — mirrors the ref
+ // trigger above.
+ `CREATE OR REPLACE FUNCTION update_catalog_relation_sync_seq()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ IF NEW.deleted IS DISTINCT FROM OLD.deleted
+ OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at THEN
+ NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_relations', 'sync_sequence'));
+ END IF;
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql`,
+ `DROP TRIGGER IF EXISTS trg_catalog_relation_sync_seq ON catalog_ingredient_relations`,
+ `CREATE TRIGGER trg_catalog_relation_sync_seq
+ BEFORE UPDATE ON catalog_ingredient_relations
+ FOR EACH ROW
+ EXECUTE FUNCTION update_catalog_relation_sync_seq()`,
+
+ // Media UPDATE bumps sync_sequence on soft-delete/revival OR a mutable
+ // field (role/caption) change so a peer sees the edit/tombstone next pull.
+ // Mirrors the relation trigger but also watches the editable metadata.
+ `CREATE OR REPLACE FUNCTION update_catalog_media_sync_seq()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ IF NEW.deleted IS DISTINCT FROM OLD.deleted
+ OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at
+ OR NEW.role IS DISTINCT FROM OLD.role
+ OR NEW.caption IS DISTINCT FROM OLD.caption THEN
+ NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_media', 'sync_sequence'));
+ END IF;
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql`,
+ `DROP TRIGGER IF EXISTS trg_catalog_media_sync_seq ON catalog_ingredient_media`,
+ `CREATE TRIGGER trg_catalog_media_sync_seq
+ BEFORE UPDATE ON catalog_ingredient_media
+ FOR EACH ROW
+ EXECUTE FUNCTION update_catalog_media_sync_seq()`,
+
+ // Tag UPDATE bumps sync_sequence + updated_at on a mutable-field change
+ // (label/description/color/parent_id) so a peer sees the edit on its next
+ // pull. Mirrors the scrap timestamp trigger.
+ `CREATE OR REPLACE FUNCTION update_catalog_tag_timestamp()
+ RETURNS TRIGGER AS $$
+ DECLARE
+ content_changed BOOLEAN;
+ BEGIN
+ content_changed := (
+ NEW.label IS DISTINCT FROM OLD.label OR
+ NEW.description IS DISTINCT FROM OLD.description OR
+ NEW.color IS DISTINCT FROM OLD.color OR
+ NEW.parent_id IS DISTINCT FROM OLD.parent_id OR
+ NEW.updated_at IS DISTINCT FROM OLD.updated_at
+ );
+ IF NOT content_changed THEN RETURN NEW; END IF;
+ IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
+ NEW.updated_at := NOW();
+ END IF;
+ NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_tags', 'sync_sequence'));
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql`,
+ `DROP TRIGGER IF EXISTS trg_catalog_tag_updated_at ON catalog_tags`,
+ `CREATE TRIGGER trg_catalog_tag_updated_at
+ BEFORE UPDATE ON catalog_tags
+ FOR EACH ROW
+ EXECUTE FUNCTION update_catalog_tag_timestamp()`,
+
+];
+
+export const catalogUserTypesDdl = [
+ // Catalog user-defined types (Phase 4 lead-in, issue #1001). One row per
+ // user-defined ingredient type — the registry that defines catalog row
+ // semantics, moved out of data/settings.json (`catalogUserTypes`) so type
+ // evolution versions/syncs alongside the catalog data it governs. `id` is
+ // the type discriminator (the `type` column on catalog_ingredients + the
+ // `cat-<prefix>-<uuid>` mint seed); the full definition lives in `data`
+ // JSONB. updated_at / deleted_at mirror the federation LWW clock + tombstone
+ // (a soft-deleted type is KEPT as a tombstone row so the deletion federates
+ // — setUserCatalogTypes filters tombstones out of the active registry).
+ // ≤64 rows, read whole on every warm/sync, so no secondary index (an unused
+ // index is just write amplification). Mirrors the catalog_user_types block
+ // in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS catalog_user_types (
+ id TEXT PRIMARY KEY,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+
+];
diff --git a/server/lib/db/schema/commissions.js b/server/lib/db/schema/commissions.js
new file mode 100644
index 0000000000..bd42744f89
--- /dev/null
+++ b/server/lib/db/schema/commissions.js
@@ -0,0 +1,53 @@
+// Creative Commissions DDL — machine-local commission records + feedback.
+// Extracted verbatim from ensureSchemaImpl() in server/lib/db.js (#2832);
+// idempotent, runs on every boot.
+export const commissionsDdl = [
+ // 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(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_creative_commissions_enabled ON creative_commissions (enabled)`,
+ // The commission BRIEF federates as of #2686 (record kind `creativeCommission`,
+ // schedule/runs/assignment stay machine-local) — a delete must tombstone so it
+ // propagates. Idempotent upgrade for installs predating the split.
+ `ALTER TABLE creative_commissions ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
+ `ALTER TABLE creative_commissions ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
+ // Creative Commission FEEDBACK — the split-record federation half (#2686).
+ // Unlike the machine-local commission above, taste reactions FEDERATE so a
+ // 👍/👎 rated on one machine conditions the same commission's next run on
+ // another. One row per reaction; the full sanitized record in `data` JSONB,
+ // with commission_id / run_id / created_at / updated_at mirrored for the
+ // per-commission hydration query, plus the soft-delete tombstone columns the
+ // LWW merge needs (a hard delete never propagates). Record kind
+ // `commissionFeedback`, sync category `commissionFeedback`.
+ `CREATE TABLE IF NOT EXISTS commission_feedback (
+ id TEXT PRIMARY KEY,
+ commission_id TEXT,
+ run_id TEXT,
+ data JSONB NOT NULL,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_commission_feedback_commission ON commission_feedback (commission_id, created_at)`,
+];
diff --git a/server/lib/db/schema/core.js b/server/lib/db/schema/core.js
new file mode 100644
index 0000000000..742cb2dc4f
--- /dev/null
+++ b/server/lib/db/schema/core.js
@@ -0,0 +1,22 @@
+// Core base-schema DDL — memory sync columns + the versioned db-migration
+// tracker. Extracted from ensureSchemaImpl() in server/lib/db.js (#2832) with
+// zero behavior change; every statement is idempotent and runs on every boot.
+// Parity-locked against server/scripts/init-db.sql by db.catalogDdlParity.test.js.
+export const coreDdl = [
+ `ALTER TABLE memories ADD COLUMN IF NOT EXISTS sync_sequence BIGSERIAL`,
+ `ALTER TABLE memories ADD COLUMN IF NOT EXISTS origin_instance_id VARCHAR(36)`,
+ `CREATE INDEX IF NOT EXISTS idx_memories_origin_instance ON memories (origin_instance_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_memories_sync_sequence ON memories (sync_sequence)`,
+ // Versioned DB-migration tracker (#1029). Records which ordered migration
+ // files in server/scripts/db-migrations/ have been applied on THIS install.
+ // It's part of the base schema (created here AND in init-db.sql, parity-
+ // locked by db.catalogDdlParity.test.js) so the runner — which executes
+ // AFTER ensureSchema() at boot — can always read it. ensureSchema()'s
+ // additive CREATE/ADD IF NOT EXISTS gates handle fresh-install schema; the
+ // runner handles DELTAS that those gates can't express (renames, type
+ // changes, data transforms, embedding-dimension changes).
+ `CREATE TABLE IF NOT EXISTS schema_migrations (
+ id TEXT PRIMARY KEY,
+ applied_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+];
diff --git a/server/lib/db/schema/humanActivity.js b/server/lib/db/schema/humanActivity.js
new file mode 100644
index 0000000000..9b93400350
--- /dev/null
+++ b/server/lib/db/schema/humanActivity.js
@@ -0,0 +1,28 @@
+// Human activity timeline DDL (#2150) — unified machine-local event store fed
+// by message/calendar syncs. Extracted verbatim from ensureSchemaImpl() in
+// server/lib/db.js (#2832); idempotent, runs on every boot.
+export const humanActivityDdl = [
+ // Human activity timeline (#2150) — unified, machine-local event store fed by
+ // message/calendar syncs (later: iMessage, Spotify, YouTube, Signal). Stores
+ // metadata + a short summary only; full bodies stay in per-source caches, with
+ // metadata pointers (threadId/externalId) back to the source. Idempotent via the
+ // unique (source, dedupe_key) index + ON CONFLICT DO NOTHING. Machine-local like
+ // Tribe (ADR 2026-06-26) — excluded from peer sync, guarded in peerSync.test.js.
+ `CREATE TABLE IF NOT EXISTS human_activity_events (
+ id TEXT PRIMARY KEY,
+ source TEXT NOT NULL,
+ account_id TEXT,
+ kind TEXT NOT NULL,
+ happened_at TIMESTAMPTZ NOT NULL,
+ duration_s INTEGER,
+ title TEXT,
+ summary TEXT,
+ url TEXT,
+ participants JSONB DEFAULT '[]'::jsonb,
+ metadata JSONB DEFAULT '{}'::jsonb,
+ dedupe_key TEXT NOT NULL,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `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)`,
+];
diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.js
new file mode 100644
index 0000000000..b18298881d
--- /dev/null
+++ b/server/lib/db/schema/index.js
@@ -0,0 +1,78 @@
+// Barrel + composer for the per-domain schema DDL modules (#2832).
+//
+// ensureSchemaImpl() in server/lib/db.js used to inline ~1265 lines of
+// CREATE TABLE / CREATE INDEX / trigger DDL for every domain. That DDL now
+// lives in per-domain modules here, each exporting a plain statement array;
+// this file re-exports them and composes the two ordered lists that
+// ensureSchemaImpl runs on every boot.
+//
+// ORDER IS LOAD-BEARING. The composed lists reproduce the pre-split statement
+// order EXACTLY (foreign-key references, the trigger function preceding its
+// triggers, and catalog_user_types' original post-media position all depend on
+// it), so the executed schema is byte-identical to the inline version.
+//
+// See README.md for the module catalog.
+
+import { coreDdl } from './core.js';
+import { tribeDdl } from './tribe.js';
+import { humanActivityDdl } from './humanActivity.js';
+import { commissionsDdl } from './commissions.js';
+import { catalogDdl, catalogUserTypesDdl } from './catalog.js';
+import { mediaDdl } from './media.js';
+import { universesDdl } from './universes.js';
+import { libraryDdl } from './library.js';
+import { pipelineDdl } from './pipeline.js';
+import { writersRoomDdl } from './writersRoom.js';
+import { loraDdl } from './lora.js';
+import { privacyDdl } from './privacy.js';
+import { auditDdl, auditedTables, buildAuditTriggers } from './audit.js';
+
+export {
+ coreDdl,
+ tribeDdl,
+ humanActivityDdl,
+ commissionsDdl,
+ catalogDdl,
+ catalogUserTypesDdl,
+ mediaDdl,
+ universesDdl,
+ libraryDdl,
+ pipelineDdl,
+ writersRoomDdl,
+ loraDdl,
+ privacyDdl,
+ auditDdl,
+ auditedTables,
+ buildAuditTriggers,
+};
+
+// Phase 1 — the `upgrades` list: memory-sync columns + migration tracker, then
+// the machine-local Tribe / human-activity / commission tables. Run first,
+// before the catalog block.
+export function buildUpgradeDdl() {
+ return [
+ ...coreDdl,
+ ...tribeDdl,
+ ...humanActivityDdl,
+ ...commissionsDdl,
+ ];
+}
+
+// Phase 2 — the `catalogDDL` list: catalog + all creative-app tables, then the
+// record_audit table/function, then the per-table audit triggers. catalog_user_types
+// is threaded in AFTER the media block to match its original position (see catalog.js).
+export function buildCatalogDdl() {
+ return [
+ ...catalogDdl,
+ ...mediaDdl,
+ ...catalogUserTypesDdl,
+ ...universesDdl,
+ ...libraryDdl,
+ ...pipelineDdl,
+ ...writersRoomDdl,
+ ...loraDdl,
+ ...privacyDdl,
+ ...auditDdl,
+ ...buildAuditTriggers(),
+ ];
+}
diff --git a/server/lib/db/schema/library.js b/server/lib/db/schema/library.js
new file mode 100644
index 0000000000..39cf45f136
--- /dev/null
+++ b/server/lib/db/schema/library.js
@@ -0,0 +1,78 @@
+// Creative-library DDL — authors, artists, albums, and tracks. Extracted
+// verbatim from ensureSchemaImpl() in server/lib/db.js (#2832); idempotent,
+// runs on every boot.
+export const libraryDdl = [
+ // Author personas. One row per reusable author/byline persona, the full
+ // sanitized record (name, writingStyle, bio, physicalDescription,
+ // headshotStyle, headshotImageUrl) in `data` JSONB. `name` mirrors a column
+ // for the live-list sort; the LWW/tombstone trio (updated_at/deleted/
+ // deleted_at) is populated FROM the record body. Authors are db-primary AND
+ // federated via the per-record peer-sync push pipeline (record kind `author`,
+ // sync category `authors`); a federated series also keeps its denormalized
+ // `author` byline so a peer that hasn't synced the persona still renders the
+ // cover correctly. Mirrors the authors block in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS authors (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_authors_live ON authors (deleted) WHERE deleted = FALSE`,
+
+ // Music artists (the Music studio's persona store — analogue of authors).
+ // One row per artist, the full sanitized record (name, genre, bio,
+ // musicalStyle, physicalDescription, portraitStyle, portraitImageUrl) in
+ // `data` JSONB. `name` mirrors a column for the live-list sort; the LWW/
+ // tombstone trio is populated FROM the record body. Artists are db-primary
+ // and federation-ready (LWW merge mirrors authors), but the artist record
+ // kind is not yet registered in peerSync — local-only for now (see issue #1502).
+ // Mirrors the artists block in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS artists (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_artists_live ON artists (deleted) WHERE deleted = FALSE`,
+
+ // Music albums (the Music studio). One row per album, the full sanitized
+ // record (title, artistId+denormalized artist, description, genre,
+ // releaseYear, coverImageUrl, ordered trackIds) in `data` JSONB. `title`
+ // mirrors a column for the live-list sort. db-primary + federation-ready
+ // (LWW merge mirrors artists), not yet registered in peerSync — local-only
+ // for now (see issue #1502). Mirrors the albums block in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS albums (
+ id TEXT PRIMARY KEY,
+ title TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_albums_live ON albums (deleted) WHERE deleted = FALSE`,
+
+ // Music tracks (the Music studio). One row per track, the full sanitized
+ // record (title, albumId/artistId FKs + denormalized artist, lyrics, prompt,
+ // engine/modelId/durationSec gen metadata, audioFilename pointing into the
+ // shared music library at data/music/) in `data` JSONB. `title` mirrors a
+ // column for queries. db-primary + federation-ready, not yet registered in
+ // peerSync — local-only for now (see issue #1502). Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS tracks (
+ id TEXT PRIMARY KEY,
+ title TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_tracks_live ON tracks (deleted) WHERE deleted = FALSE`,
+
+];
diff --git a/server/lib/db/schema/lora.js b/server/lib/db/schema/lora.js
new file mode 100644
index 0000000000..c4c6f90b85
--- /dev/null
+++ b/server/lib/db/schema/lora.js
@@ -0,0 +1,19 @@
+// LoRA training-run DDL. Extracted verbatim from ensureSchemaImpl() in
+// server/lib/db.js (#2832); idempotent, runs on every boot.
+export const loraDdl = [
+ // LoRA training runs (character LoRA training). MUST live here, not only
+ // in init-db.sql — init-db.sql runs only on fresh `db.sh setup-native`
+ // provisioning, so existing installs + federated peers get new tables
+ // exclusively through this boot-time upgrade path. Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS lora_training_runs (
+ id TEXT PRIMARY KEY,
+ status TEXT NOT NULL,
+ character_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_lora_training_runs_status ON lora_training_runs (status)`,
+ `CREATE INDEX IF NOT EXISTS idx_lora_training_runs_character ON lora_training_runs (character_id)`,
+
+];
diff --git a/server/lib/db/schema/media.js b/server/lib/db/schema/media.js
new file mode 100644
index 0000000000..bf1340f759
--- /dev/null
+++ b/server/lib/db/schema/media.js
@@ -0,0 +1,106 @@
+// Media-project DDL — creative-director projects, music-video projects, mood
+// boards, and media assets. Extracted verbatim from ensureSchemaImpl() in
+// server/lib/db.js (#2832); idempotent, runs on every boot.
+export const mediaDdl = [
+ // Creative Director projects (Phase 3, issue #997). One row per project;
+ // the full record lives in `data` JSONB, with status/created_at/updated_at
+ // mirrored into columns (kept in lockstep on every write) for future
+ // queries. `listProjects` sorts by created_at. `status` is app-layer gated
+ // (PROJECT_STATUSES), no DB CHECK. As of #1564 projects FEDERATE across peers
+ // via the per-record peer-sync push pipeline (record kind
+ // `creativeDirectorProject`, sync category `creativeDirectorProjects`), so
+ // the soft-delete tombstone trio (deleted/deleted_at + LWW updated_at) mirrors
+ // the authors table — a delete is a tombstone the merge keeps an out-of-date
+ // peer from resurrecting. Mirrors the creative_director_projects block in
+ // init-db.sql; the ADD COLUMN upgrades below backfill existing installs.
+ `CREATE TABLE IF NOT EXISTS creative_director_projects (
+ id TEXT PRIMARY KEY,
+ status VARCHAR(32) NOT NULL DEFAULT 'draft',
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ // Backfill the tombstone columns on installs created before #1564 (the
+ // CREATE above is a no-op once the table exists). The partial index serves
+ // the live-list filter (deleted = FALSE).
+ `ALTER TABLE creative_director_projects ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
+ `ALTER TABLE creative_director_projects ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
+ `CREATE INDEX IF NOT EXISTS idx_creative_director_projects_live ON creative_director_projects (deleted) WHERE deleted = FALSE`,
+
+ // Music Video projects (issue #1760). The director scene board's db-primary
+ // record: id/status/created_at/updated_at mirrored as columns, the full
+ // project (track link, cached audioAnalysis, scenes[]) in `data` JSONB —
+ // same shape as creative_director_projects. The soft-delete tombstone trio is
+ // present so peer-sync federation (a follow-up) is additive. Mirrors the
+ // music_video_projects block in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS music_video_projects (
+ id TEXT PRIMARY KEY,
+ status VARCHAR(32) NOT NULL DEFAULT 'draft',
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `ALTER TABLE music_video_projects ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
+ `ALTER TABLE music_video_projects ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
+ `CREATE INDEX IF NOT EXISTS idx_music_video_projects_live ON music_video_projects (deleted) WHERE deleted = FALSE`,
+
+ // Mood boards (issue #911). A dedicated inspiration/mood-board canvas,
+ // distinct from raw Media History, for collecting visual + textual
+ // references that feed the Create suite. One row per board, the full record
+ // (name/description/items[]) in `data` JSONB. Items (image-by-media-key or
+ // external URL, or a text note + optional caption/source backref) live
+ // inline in the board's JSONB rather than a child table — a board is read/
+ // written whole, has a small bounded item list, and there are no cross-board
+ // item queries. `name` mirrors a column for the live-list sort. As of #1564
+ // mood boards FEDERATE across peers via the per-record peer-sync push pipeline
+ // (record kind `moodBoard`, sync category `moodBoards`), so the soft-delete
+ // tombstone trio (deleted/deleted_at + LWW updated_at) mirrors
+ // creative_director_projects — a delete is a tombstone the merge keeps an
+ // out-of-date peer from resurrecting. Mirrors the mood_boards block in
+ // init-db.sql; the ADD COLUMN upgrades below backfill existing installs.
+ `CREATE TABLE IF NOT EXISTS mood_boards (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ // Backfill the tombstone columns on installs created before #1564 (the
+ // CREATE above is a no-op once the table exists).
+ `ALTER TABLE mood_boards ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
+ `ALTER TABLE mood_boards ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
+ // updated_at DESC is the board-list "recently touched" sort.
+ `CREATE INDEX IF NOT EXISTS idx_mood_boards_updated ON mood_boards (updated_at DESC)`,
+ // Partial index for the live-list filter (deleted = FALSE).
+ `CREATE INDEX IF NOT EXISTS idx_mood_boards_live ON mood_boards (deleted) WHERE deleted = FALSE`,
+
+ // Media asset index (Phase 3.2, issue #1000). One row per generated image
+ // or video; the bytes stay on disk (data/images, data/videos) and the
+ // sidecar/.json history files remain authoritative — this table is a
+ // DERIVED, queryable index, reconciled from disk at boot + kept warm by a
+ // generation-completed hook. `media_key` is the shared `<kind>:<ref>`
+ // vocabulary (mediaItemKey.js); `kind`/`ref` are mirrored into columns for
+ // queries, the full metadata record lives in `data` JSONB. created_at is
+ // the asset's own timestamp; indexed_at is when this index row was written.
+ // No sync_sequence/tombstone: the index is local-only (rebuilt from disk),
+ // not federated — a row vanishes when its file does (prune on reconcile).
+ // Mirrors the media_assets block in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS media_assets (
+ media_key TEXT PRIMARY KEY,
+ kind VARCHAR(16) NOT NULL,
+ ref TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ indexed_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ // created_at DESC is the gallery/history sort order; kind narrows
+ // images-vs-videos. A composite (kind, created_at DESC) serves both.
+ `CREATE INDEX IF NOT EXISTS idx_media_assets_kind_created ON media_assets (kind, created_at DESC)`,
+
+];
diff --git a/server/lib/db/schema/pipeline.js b/server/lib/db/schema/pipeline.js
new file mode 100644
index 0000000000..13acfada23
--- /dev/null
+++ b/server/lib/db/schema/pipeline.js
@@ -0,0 +1,95 @@
+// Pipeline DDL — comic/prose pipeline series, issues, and story-builder
+// sessions. Extracted verbatim from ensureSchemaImpl() in server/lib/db.js
+// (#2832); idempotent, runs on every boot.
+export const pipelineDdl = [
+ // Pipeline series (Phase 3 Create migration, issue #1015). One row per
+ // series, the full sanitized record (arc/seasons/locks/covers/style) in
+ // `data` JSONB, moved out of data/pipeline-series/{id}/index.json
+ // (collectionStore). Only the fields the service/federation query, join, or
+ // sort on are mirrored into columns: `name` (rename-cascade + list sort),
+ // `universe_id` (the hot relationship — the delete-guard "reject universe
+ // delete when live series link it" + "series in this universe" lists; soft
+ // ref, no FK — a series can sync before its universe arrives), and the
+ // promote back-link `writers_room_work_id`. `ephemeral` + the LWW/tombstone
+ // trio (updated_at/deleted/deleted_at) populated FROM the record body
+ // (mirrorTimestamp), not a DB trigger. NO sync_sequence: pipeline records
+ // federate via the EXISTING dataSync snapshot/push model — the storage swap
+ // is invisible to peers (no schema-version bump). Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS pipeline_series (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ universe_id TEXT,
+ writers_room_work_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ ephemeral BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_series_universe ON pipeline_series (universe_id) WHERE deleted = FALSE`,
+ `CREATE INDEX IF NOT EXISTS idx_series_wr_work ON pipeline_series (writers_room_work_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_series_updated ON pipeline_series (updated_at)`,
+
+ // Pipeline issues (issue #1015). One row per issue; the 8-stage `stages`
+ // map (text/visual/audio, runHistory, canonExtraction, covers) + lastRunId
+ // pointers stay entirely in `data` JSONB (document-shaped, sanitizer-owned).
+ // `series_id` (parent, soft ref), `season_id` (arc grouping), and `number`
+ // (renumber-recomputed ordinal) are promoted — the renumber pass reads all
+ // issues of a series ordered by number, the single most common cross-record
+ // pipeline query, served directly by idx_issues_series (series_id, number).
+ // `status` promoted for "issues needing review" dashboards. `ephemeral` +
+ // LWW/tombstone trio mirror the body. NO sync_sequence (see pipeline_series).
+ // Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS pipeline_issues (
+ id TEXT PRIMARY KEY,
+ series_id TEXT NOT NULL,
+ season_id TEXT,
+ number INTEGER,
+ status VARCHAR(32),
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ ephemeral BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_issues_series ON pipeline_issues (series_id, number) WHERE deleted = FALSE`,
+ `CREATE INDEX IF NOT EXISTS idx_issues_season ON pipeline_issues (season_id) WHERE season_id IS NOT NULL`,
+ `CREATE INDEX IF NOT EXISTS idx_issues_updated ON pipeline_issues (updated_at)`,
+
+ // Story Builder sessions (issue #1016). One row per session; the conductor
+ // bookkeeping (`steps` lock/integrity map, `syncedHashes` baseline,
+ // `currentStep`, `llm` picker choice) stays entirely in `data` JSONB. The two
+ // FKs `universe_id` / `series_id` are promoted for "sessions linked to this
+ // record" lookups. `sync` is promoted because Story Builder is the one store
+ // whose federation is OPT-IN — the snapshot loop filters WHERE sync = TRUE to
+ // decide what to even consider pushing, so promoting it avoids deserializing
+ // every session's `data` per snapshot tick. `ephemeral` + the LWW/tombstone
+ // trio mirror the body. NO sync_sequence (sessions ride the existing dataSync
+ // snapshot/LWW model, not the per-record push pipeline). Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS story_builder_sessions (
+ id TEXT PRIMARY KEY,
+ universe_id TEXT,
+ series_id TEXT,
+ sync BOOLEAN DEFAULT FALSE,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ ephemeral BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_stb_universe ON story_builder_sessions (universe_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_stb_series ON story_builder_sessions (series_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_stb_updated ON story_builder_sessions (updated_at)`,
+
+ // Writers Room (Phase 3 Create migration, issue #1017). FOUR tables replace
+ // the bespoke file layout (folders.json, exercises.json, per-work
+ // manifest.json). Writers Room is NOT federated — it has no dataSync category
+ // and no schema-version gate — so unlike the universe/pipeline/story-builder
+ // tables these carry NO `ephemeral`/`sync`/sync_sequence columns and need no
+ // mutation epoch. The only thing that stays on disk is the draft prose body
+ // (drafts/<draftId>.md, file-primary); its metadata is the draft_versions row.
+
+];
diff --git a/server/lib/db/schema/privacy.js b/server/lib/db/schema/privacy.js
new file mode 100644
index 0000000000..796210875c
--- /dev/null
+++ b/server/lib/db/schema/privacy.js
@@ -0,0 +1,154 @@
+// Privacy-suite DDL — vault records, consents, orgs, org holdings, brokers,
+// broker cases, and change events. Extracted verbatim from ensureSchemaImpl()
+// in server/lib/db.js (#2832); idempotent, runs on every boot.
+export const privacyDdl = [
+ // ─── Privacy Center: PII Vault (issue #2140, epic #2138) ─────────────────
+ // Encrypted-at-rest identity facts. `value_enc` is AES-256-GCM ciphertext
+ // (`v1:<iv>:<tag>:<ct>`, key from PRIVACY_VAULT_KEY — lib/vaultCrypto.js);
+ // plaintext is NEVER stored, `masked_value` is the display form. Machine-
+ // local: no federation, no tombstones (deferred, #2148) — a delete is a
+ // hard DELETE. `use_for_scans` gates which facts the broker scan engine
+ // may disclose (hard-false for ssn/passport/drivers_license/
+ // financial_account — enforced app-side). Mirrors the privacy blocks in
+ // init-db.sql.
+ `CREATE TABLE IF NOT EXISTS privacy_vault_records (
+ id UUID PRIMARY KEY,
+ type TEXT NOT NULL,
+ label TEXT NOT NULL DEFAULT '',
+ value_enc TEXT NOT NULL,
+ masked_value TEXT NOT NULL DEFAULT '',
+ status TEXT NOT NULL DEFAULT 'current',
+ valid_from DATE,
+ valid_to DATE,
+ share_with_twin BOOLEAN NOT NULL DEFAULT FALSE,
+ use_for_scans BOOLEAN NOT NULL DEFAULT FALSE,
+ notes TEXT NOT NULL DEFAULT '',
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ // Type is the primary list filter (all addresses, all emails, ...).
+ `CREATE INDEX IF NOT EXISTS idx_privacy_vault_records_type ON privacy_vault_records (type)`,
+ // Explicit consent audit rows (v1 subject is always 'self'); the broker
+ // opt-out engine builds on this trail. Append-only.
+ `CREATE TABLE IF NOT EXISTS privacy_consents (
+ id UUID PRIMARY KEY,
+ subject TEXT NOT NULL DEFAULT 'self',
+ scope TEXT NOT NULL,
+ method TEXT NOT NULL,
+ granted_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+
+ // ─── Privacy Center: Trusted Organizations registry (issue #2141, epic
+ // #2138) ──────────────────────────────────────────────────────────────
+ // Every organization that has (or had) the user's PII, with a trust
+ // stance and per-org holdings linking to the exact vault records each org
+ // holds. Data backbone for the change-of-address inventory (Phase 4) and
+ // the "who has my PII" view. Machine-local: no federation, no tombstones
+ // (same deferred scope as the vault, #2148). Mirrors the privacy blocks
+ // in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS privacy_orgs (
+ id UUID PRIMARY KEY,
+ name TEXT NOT NULL,
+ category TEXT NOT NULL DEFAULT 'other',
+ website TEXT NOT NULL DEFAULT '',
+ trust TEXT NOT NULL DEFAULT 'trusted',
+ status TEXT NOT NULL DEFAULT 'active',
+ contact JSONB NOT NULL DEFAULT '{}'::jsonb,
+ social_account_id TEXT,
+ notes TEXT NOT NULL DEFAULT '',
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_privacy_orgs_trust ON privacy_orgs (trust)`,
+ `CREATE INDEX IF NOT EXISTS idx_privacy_orgs_status ON privacy_orgs (status)`,
+ // Which vault records each org holds. Composite PK (no surrogate id) — an
+ // org either holds a given vault record or it doesn't, so the pair IS the
+ // identity. Cascade both ways: deleting the org or the vault record drops
+ // its holdings rows.
+ `CREATE TABLE IF NOT EXISTS privacy_org_holdings (
+ org_id UUID NOT NULL REFERENCES privacy_orgs (id) ON DELETE CASCADE,
+ vault_record_id UUID NOT NULL REFERENCES privacy_vault_records (id) ON DELETE CASCADE,
+ status TEXT NOT NULL DEFAULT 'current',
+ noted_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ PRIMARY KEY (org_id, vault_record_id)
+ )`,
+ // Reverse lookup: "which orgs hold vault record X" (getOrgsHoldingRecord).
+ `CREATE INDEX IF NOT EXISTS idx_privacy_org_holdings_vault_record ON privacy_org_holdings (vault_record_id)`,
+
+ // ─── Privacy Center: data-broker database + case ledger (issue #2144,
+ // epic #2138) ──────────────────────────────────────────────────────────
+ // `privacy_brokers` is the curated (+ later BADBOOL / CA-registry) database
+ // of people-search brokers the exposure-scan/opt-out engine works. Seeded
+ // idempotently from data.reference/privacy/brokers.json on first use (NO
+ // network at boot). `source`/`confidence` gate the refresh: curated rows
+ // (field_verified/documented) are never clobbered by an auto refresh.
+ // `cluster_parent` groups sibling brands under one suppression;
+ // `disclosure_fields` caps what the engine may ever submit to that broker.
+ // Machine-local — no federation, no tombstones (same deferred scope as the
+ // vault, #2148). Mirrors the privacy blocks in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS privacy_brokers (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ urls JSONB NOT NULL DEFAULT '{}'::jsonb,
+ optout JSONB NOT NULL DEFAULT '{}'::jsonb,
+ tier SMALLINT NOT NULL DEFAULT 2,
+ disclosure_fields TEXT[] NOT NULL DEFAULT '{}',
+ cluster_parent TEXT REFERENCES privacy_brokers (id) ON DELETE SET NULL,
+ prefer_suppression BOOLEAN NOT NULL DEFAULT FALSE,
+ antibot BOOLEAN NOT NULL DEFAULT FALSE,
+ source TEXT NOT NULL DEFAULT 'curated',
+ confidence TEXT NOT NULL DEFAULT 'documented',
+ last_verified DATE,
+ enabled BOOLEAN NOT NULL DEFAULT TRUE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ // Planner walks enabled brokers, cluster-parents first.
+ `CREATE INDEX IF NOT EXISTS idx_privacy_brokers_enabled ON privacy_brokers (enabled)`,
+ `CREATE INDEX IF NOT EXISTS idx_privacy_brokers_cluster_parent ON privacy_brokers (cluster_parent)`,
+ // Per-broker exposure/opt-out case ledger with a service-enforced state
+ // machine. `state` is validated app-side (privacyBrokers.js); every write
+ // stamps `next_recheck_at` (state-dependent backoff). `evidence` holds
+ // listing URLs / match basis / screenshot refs — NOT plaintext PII (the
+ // engine records only least-disclosure identifiers). A broker delete
+ // cascades its cases.
+ `CREATE TABLE IF NOT EXISTS privacy_broker_cases (
+ id UUID PRIMARY KEY,
+ broker_id TEXT NOT NULL REFERENCES privacy_brokers (id) ON DELETE CASCADE,
+ state TEXT NOT NULL DEFAULT 'unscanned',
+ found BOOLEAN,
+ evidence JSONB NOT NULL DEFAULT '{}'::jsonb,
+ disclosed_fields TEXT[] NOT NULL DEFAULT '{}',
+ channel TEXT,
+ reason TEXT,
+ next_recheck_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ // One live case per broker in v1 (self-only subject) — unique so the
+ // scan-pass upsert can ON CONFLICT the broker id.
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_privacy_broker_cases_broker ON privacy_broker_cases (broker_id)`,
+ // "Which cases are due for a recheck" — the run-loop's primary query.
+ `CREATE INDEX IF NOT EXISTS idx_privacy_broker_cases_recheck ON privacy_broker_cases (next_recheck_at)`,
+
+ // ─── Privacy Center: change-of-address events (issue #2143, epic #2138) ──
+ // One row per "field X changed from A to B" declaration. `vault_record_id`
+ // is the OLD record (marked `previous` on declare); `replacement_record_id`
+ // is the NEW one (nullable for a removal-only change). Declaring an event
+ // flips every `current` holding of the old record to `update_pending` (see
+ // privacyChanges.js). Both FKs cascade so removing a vault record cleans up
+ // its change events. Machine-local — no federation, no tombstones (same
+ // deferred scope as the vault, #2148). Mirrors the block in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS privacy_change_events (
+ id UUID PRIMARY KEY,
+ vault_record_id UUID NOT NULL REFERENCES privacy_vault_records (id) ON DELETE CASCADE,
+ replacement_record_id UUID REFERENCES privacy_vault_records (id) ON DELETE SET NULL,
+ kind TEXT NOT NULL DEFAULT 'other',
+ declared_at TIMESTAMPTZ DEFAULT NOW(),
+ note TEXT NOT NULL DEFAULT ''
+ )`,
+ // "Changes touching this record" — the inventory groups by the old record.
+ `CREATE INDEX IF NOT EXISTS idx_privacy_change_events_vault_record ON privacy_change_events (vault_record_id)`,
+
+];
diff --git a/server/lib/db/schema/schema.test.js b/server/lib/db/schema/schema.test.js
new file mode 100644
index 0000000000..406099c185
--- /dev/null
+++ b/server/lib/db/schema/schema.test.js
@@ -0,0 +1,108 @@
+/**
+ * Compose/barrel test for the per-domain schema DDL modules (#2832).
+ *
+ * Issue #2832 split the ~1265-line inline DDL in ensureSchemaImpl()
+ * (server/lib/db.js) into per-domain modules here, each exporting a plain
+ * statement array, with index.js composing the two ordered lists the composer
+ * runs. This pins that contract:
+ * - every domain module exports an array of SQL strings,
+ * - the composer includes each module's statements,
+ * - ORDER is preserved (FK references + trigger-function-before-triggers),
+ * - the audit-trigger builder emits two statements per audited table.
+ *
+ * Byte-for-byte equivalence with the pre-split inline arrays was verified at
+ * extraction time; catalog↔init-db.sql parity is locked separately by
+ * db.catalogDdlParity.test.js.
+ */
+
+import { describe, it, expect } from 'vitest';
+import * as schema from './index.js';
+import {
+ buildUpgradeDdl,
+ buildCatalogDdl,
+ auditedTables,
+ buildAuditTriggers,
+} from './index.js';
+
+const DOMAIN_ARRAYS = [
+ 'coreDdl', 'tribeDdl', 'humanActivityDdl', 'commissionsDdl',
+ 'catalogDdl', 'catalogUserTypesDdl', 'mediaDdl', 'universesDdl',
+ 'libraryDdl', 'pipelineDdl', 'writersRoomDdl', 'loraDdl', 'privacyDdl',
+ 'auditDdl',
+];
+
+describe('db/schema barrel + composer (#2832)', () => {
+ it.each(DOMAIN_ARRAYS)('%s is a non-empty array of SQL strings', (name) => {
+ const arr = schema[name];
+ expect(Array.isArray(arr), `${name} should be an array`).toBe(true);
+ expect(arr.length).toBeGreaterThan(0);
+ for (const stmt of arr) expect(typeof stmt).toBe('string');
+ });
+
+ it('buildUpgradeDdl composes the phase-1 modules in order', () => {
+ const expected = [
+ ...schema.coreDdl,
+ ...schema.tribeDdl,
+ ...schema.humanActivityDdl,
+ ...schema.commissionsDdl,
+ ];
+ expect(buildUpgradeDdl()).toEqual(expected);
+ });
+
+ it('buildCatalogDdl composes the phase-2 modules in order, with catalog_user_types after media', () => {
+ const expected = [
+ ...schema.catalogDdl,
+ ...schema.mediaDdl,
+ ...schema.catalogUserTypesDdl,
+ ...schema.universesDdl,
+ ...schema.libraryDdl,
+ ...schema.pipelineDdl,
+ ...schema.writersRoomDdl,
+ ...schema.loraDdl,
+ ...schema.privacyDdl,
+ ...schema.auditDdl,
+ ...buildAuditTriggers(),
+ ];
+ expect(buildCatalogDdl()).toEqual(expected);
+ });
+
+ it('every FK target created within these lists precedes the statement referencing it', () => {
+ // Structural safety net for the extraction: for each `REFERENCES <table>`
+ // whose target is created WITHIN these two lists, that CREATE must appear at
+ // or before the referencing statement — catches an intra-list reorder. Some
+ // FK targets (e.g. `memories`) are created by a separate schema path and the
+ // `upgrades` list only ALTERs them, so a target absent here is not a failure.
+ const all = [...buildUpgradeDdl(), ...buildCatalogDdl()];
+ const createdAt = new Map();
+ all.forEach((sql, i) => {
+ const m = /CREATE TABLE IF NOT EXISTS (\w+)/.exec(sql);
+ if (m && !createdAt.has(m[1])) createdAt.set(m[1], i);
+ });
+ all.forEach((sql, i) => {
+ const re = /REFERENCES\s+(\w+)\s*\(/gi;
+ let m;
+ while ((m = re.exec(sql)) !== null) {
+ const target = m[1];
+ if (!createdAt.has(target)) continue; // created by another schema path
+ expect(createdAt.get(target), `FK target ${target} created after its reference`).toBeLessThanOrEqual(i);
+ }
+ });
+ });
+
+ it('the record_audit_log() function is defined before any trigger that calls it', () => {
+ const catalog = buildCatalogDdl();
+ const fnIdx = catalog.findIndex((s) => /CREATE OR REPLACE FUNCTION record_audit_log/.test(s));
+ const firstTrigIdx = catalog.findIndex((s) => /EXECUTE FUNCTION record_audit_log/.test(s));
+ expect(fnIdx).toBeGreaterThanOrEqual(0);
+ expect(firstTrigIdx).toBeGreaterThan(fnIdx);
+ });
+
+ it('buildAuditTriggers emits a DROP + CREATE pair per audited table', () => {
+ const triggers = buildAuditTriggers();
+ expect(triggers.length).toBe(auditedTables.length * 2);
+ for (const t of auditedTables) {
+ expect(triggers).toContain(`DROP TRIGGER IF EXISTS trg_${t}_audit ON ${t}`);
+ expect(triggers.some((s) => s.startsWith(`CREATE TRIGGER trg_${t}_audit `))).toBe(true);
+ }
+ });
+});
diff --git a/server/lib/db/schema/tribe.js b/server/lib/db/schema/tribe.js
new file mode 100644
index 0000000000..63bbe0dbbd
--- /dev/null
+++ b/server/lib/db/schema/tribe.js
@@ -0,0 +1,62 @@
+// Tribe / relationship-CRM DDL (#2033, #2150, #2151) — people, touchpoints,
+// and memory links. Machine-local (never federated). Extracted verbatim from
+// ensureSchemaImpl() in server/lib/db.js (#2832); idempotent, runs on every boot.
+export const tribeDdl = [
+ `CREATE TABLE IF NOT EXISTS tribe_people (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ name TEXT NOT NULL,
+ relationship TEXT DEFAULT '',
+ ring VARCHAR(32) NOT NULL DEFAULT 'tribe',
+ cadence_days INTEGER NOT NULL DEFAULT 45,
+ last_contact_on DATE,
+ channel TEXT DEFAULT '',
+ energy VARCHAR(32) NOT NULL DEFAULT 'steady',
+ tags TEXT[] DEFAULT '{}',
+ next_move TEXT DEFAULT '',
+ notes TEXT DEFAULT '',
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ // Known emails/handles for a person — the deterministic key that maps a
+ // calendar attendee / message counterpart back to this tracked person so
+ // touchpoints can be auto-logged (#2033).
+ `ALTER TABLE tribe_people ADD COLUMN IF NOT EXISTS emails TEXT[] DEFAULT '{}'`,
+ // Known phone handles for a person — the deterministic key that maps an
+ // iMessage/Signal handle (E.164, e.g. +15551234567) back to this tracked
+ // person so touchpoints can be auto-logged (#2151). Mirrors emails[].
+ `ALTER TABLE tribe_people ADD COLUMN IF NOT EXISTS phones TEXT[] DEFAULT '{}'`,
+ `CREATE INDEX IF NOT EXISTS idx_tribe_people_live ON tribe_people (deleted, ring, updated_at DESC)`,
+ `CREATE INDEX IF NOT EXISTS idx_tribe_people_tags ON tribe_people USING gin (tags)`,
+ `CREATE INDEX IF NOT EXISTS idx_tribe_people_emails ON tribe_people USING gin (emails)`,
+ `CREATE INDEX IF NOT EXISTS idx_tribe_people_phones ON tribe_people USING gin (phones)`,
+ `CREATE TABLE IF NOT EXISTS tribe_touchpoints (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ person_id UUID NOT NULL REFERENCES tribe_people(id) ON DELETE CASCADE,
+ happened_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ channel TEXT DEFAULT '',
+ summary TEXT DEFAULT '',
+ source VARCHAR(32) NOT NULL DEFAULT 'user',
+ calendar_account_id TEXT,
+ calendar_event_id TEXT,
+ dedupe_key TEXT,
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ // Idempotency key for auto-logged touchpoints (calendar event id / message
+ // thread+day). Partial unique index so re-syncs never double-log a person
+ // for the same event/thread-day; NULL for hand-logged user touchpoints.
+ `ALTER TABLE tribe_touchpoints ADD COLUMN IF NOT EXISTS dedupe_key TEXT`,
+ `CREATE INDEX IF NOT EXISTS idx_tribe_touchpoints_person ON tribe_touchpoints (person_id, happened_at DESC)`,
+ `CREATE INDEX IF NOT EXISTS idx_tribe_touchpoints_calendar ON tribe_touchpoints (calendar_account_id, calendar_event_id)`,
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_tribe_touchpoints_dedupe ON tribe_touchpoints (person_id, dedupe_key) WHERE dedupe_key IS NOT NULL`,
+ `CREATE TABLE IF NOT EXISTS tribe_memory_links (
+ person_id UUID NOT NULL REFERENCES tribe_people(id) ON DELETE CASCADE,
+ memory_id UUID NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
+ note TEXT DEFAULT '',
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ PRIMARY KEY (person_id, memory_id)
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_tribe_memory_links_memory ON tribe_memory_links (memory_id)`,
+];
diff --git a/server/lib/db/schema/universes.js b/server/lib/db/schema/universes.js
new file mode 100644
index 0000000000..38ec7db320
--- /dev/null
+++ b/server/lib/db/schema/universes.js
@@ -0,0 +1,51 @@
+// Universe DDL — universes + universe run history. Extracted verbatim from
+// ensureSchemaImpl() in server/lib/db.js (#2832); idempotent, runs on every boot.
+export const universesDdl = [
+ // Universe Builder records (Phase 3 Create migration, issue #1014). One row
+ // per universe, the full sanitized record (canon bibles, categories,
+ // compositeSheets, locks, influences) in `data` JSONB, moved out of
+ // data/universes/{id}/index.json (collectionStore). Only the fields the
+ // service/federation query, join, or sort on are mirrored into columns:
+ // `name` (rename-cascade + delete-guard + list sort), `schema_version` (the
+ // RECORD-shape version sanitizeTemplate stamps — a column so a future
+ // migration can find unmigrated rows without parsing JSONB), `ephemeral`
+ // (the snapshot loop filters local-only records), and the LWW/tombstone
+ // trio (updated_at/deleted/deleted_at). NO sync_sequence: universes
+ // federate via the EXISTING dataSync snapshot/push model (LWW on the body's
+ // updatedAt), NOT catalog-style pull cursors — the storage swap is invisible
+ // to peers (no schema-version bump). The mirror columns are populated FROM
+ // the record body (mirrorTimestamp), not a DB trigger. Mirrors the universes
+ // block in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS universes (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ schema_version INTEGER NOT NULL DEFAULT 4,
+ ephemeral BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ // Partial index on the live set — the common list/scan path is "non-deleted
+ // universes". updated_at supports LWW-staleness scans.
+ `CREATE INDEX IF NOT EXISTS idx_universes_live ON universes (deleted) WHERE deleted = FALSE`,
+ `CREATE INDEX IF NOT EXISTS idx_universes_updated ON universes (updated_at)`,
+
+ // Universe render-history log (issue #1014). The type-level `config.runs[]`
+ // array collectionStore kept in data/universes/index.json (capped 200,
+ // NEVER federated — per-peer local) becomes its own table. `universe_id` is
+ // a soft ref (no FK): the cascade-clean on universe delete is handled in the
+ // service exactly as the file backend did, and a soft ref keeps the table
+ // independent of universe-row insert ordering during the one-time import.
+ // `data` holds jobIds[]/promptCount/collectionId. Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS universe_runs (
+ id TEXT PRIMARY KEY,
+ universe_id TEXT NOT NULL,
+ collection_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_universe_runs_universe ON universe_runs (universe_id, created_at DESC)`,
+
+];
diff --git a/server/lib/db/schema/writersRoom.js b/server/lib/db/schema/writersRoom.js
new file mode 100644
index 0000000000..cf0eeb1164
--- /dev/null
+++ b/server/lib/db/schema/writersRoom.js
@@ -0,0 +1,96 @@
+// Writers-Room DDL — folders, works, draft versions, and exercises. Extracted
+// verbatim from ensureSchemaImpl() in server/lib/db.js (#2832); idempotent,
+// runs on every boot.
+export const writersRoomDdl = [
+ // Folder tree. Self-ref parent_id (soft, no FK — nested tree). sort_order +
+ // name promoted (the library renders the tree ordered by them). Mirrors
+ // init-db.sql.
+ `CREATE TABLE IF NOT EXISTS writers_room_folders (
+ id TEXT PRIMARY KEY,
+ parent_id TEXT,
+ name TEXT NOT NULL,
+ sort_order INTEGER DEFAULT 0,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_wr_folders_parent ON writers_room_folders (parent_id, sort_order)`,
+ // Idempotent upgrade for installs predating folder federation (#1645): without
+ // the soft-delete columns an old install boots the new code and hard-DELETEs a
+ // folder (no tombstone) — peers never learn it was removed and resurrect it.
+ `ALTER TABLE writers_room_folders ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
+ `ALTER TABLE writers_room_folders ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
+
+ // Work manifests. The drafts[] array moves OUT of `data` into
+ // writers_room_draft_versions (the one decomposition — draft versions are a
+ // genuine 1-to-many the library + Phase-5 staleness analysis query). imageStyle
+ // / liveMode / usage counters stay in `data`. `folder_id`, `title`, `kind`,
+ // `status`, the promote/bridge links, and `active_draft_version_id` are
+ // promoted for the library list + the resolver (#1018) + the bridge CTAs.
+ // SOFT-DELETE added here (`deleted`/`deleted_at`): the file backend hard-deletes
+ // via rm -rf; the DB backend aligns with the other stores (import sets
+ // deleted = FALSE for all existing works). Soft ref everywhere — no FK.
+ // Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS writers_room_works (
+ id TEXT PRIMARY KEY,
+ folder_id TEXT,
+ title TEXT NOT NULL,
+ kind VARCHAR(32),
+ status VARCHAR(32),
+ active_draft_version_id TEXT,
+ pipeline_series_id TEXT,
+ pipeline_issue_id TEXT,
+ cd_project_id TEXT,
+ media_collection_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_wr_works_folder ON writers_room_works (folder_id) WHERE deleted = FALSE`,
+ `CREATE INDEX IF NOT EXISTS idx_wr_works_series ON writers_room_works (pipeline_series_id) WHERE pipeline_series_id IS NOT NULL`,
+
+ // Draft-version metadata index (file-primary bodies). The .md body stays on
+ // disk at data/writers-room/works/<workId>/drafts/<draftId>.md; this row is
+ // the queryable index over it: `content_file` (relative path), `content_hash`
+ // (sha256 for staleness), `word_count`, `segment_index` (outline), version
+ // lineage. asset-file-db-indexed pattern applied to prose. Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS writers_room_draft_versions (
+ id TEXT PRIMARY KEY,
+ work_id TEXT NOT NULL,
+ label TEXT,
+ content_file TEXT NOT NULL,
+ content_hash TEXT,
+ word_count INTEGER DEFAULT 0,
+ segment_index JSONB NOT NULL DEFAULT '[]'::jsonb,
+ created_from_version_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_wr_drafts_work ON writers_room_draft_versions (work_id, created_at)`,
+
+ // Exercise sessions (sprint timer). Monolithic exercises.json → flat table.
+ // `work_id`, `status`, started_at promoted for the per-work list (ordered by
+ // started_at DESC). prompt/durations/word counts/appendedText stay in `data`.
+ // Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS writers_room_exercises (
+ id TEXT PRIMARY KEY,
+ work_id TEXT,
+ status VARCHAR(16),
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ started_at TIMESTAMPTZ,
+ finished_at TIMESTAMPTZ,
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_wr_exercises_work ON writers_room_exercises (work_id, started_at DESC)`,
+ // Idempotent upgrade for installs predating exercise federation (#1645). The
+ // tombstone columns let a peer's deletion propagate (LWW never propagates a
+ // hard delete); no current path deletes an exercise but a future peer might.
+ `ALTER TABLE writers_room_exercises ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
+ `ALTER TABLE writers_room_exercises ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
+
+];