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: generalize DDL parity test and backfill init-db.sql (#6819)

[._.]/ Adam Eivy7148eacbeac1
diff --git a/server/lib/db.ddlParity.test.js b/server/lib/db.ddlParity.test.js
index 0b7d4232fa..7ddd034d13 100644
--- a/server/lib/db.ddlParity.test.js
+++ b/server/lib/db.ddlParity.test.js
@@ -1,18 +1,22 @@
/**
- * Catalog DDL parity test — locks the schema definitions in
- * `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.
+ * DDL parity test — locks the schema definitions in `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.
+ * The test auto-discovers all shared tables (those declared in BOTH sources) and
+ * compares their columns, indexes, trigger/function names, and CHECK constraints.
+ * Two tolerance lists guard the exceptional cases: `SQL_ONLY_TOLERATED` for tables
+ * in init-db.sql but not JS (currently only the memory system), and
+ * `BOOT_BACKFILL_ONLY` for tables in JS but not init-db.sql (machine-local tables
+ * that backfill from JS on every boot, with one-line reasons for each).
*
* The test is structural, not a SQL parser — it extracts table column sets,
- * index names, trigger / function names, the `type` CHECK list, and the
- * `search_tsv` payload-field set from each source and asserts the sets are
- * equal. Cosmetic differences (whitespace, comments, ordering) are tolerated;
- * a column added on one side but not the other is not.
+ * index names, trigger / function names, CHECK constraints, and search_tsv
+ * payload-field sets from each source and asserts the sets are equal. Cosmetic
+ * differences (whitespace, comments, ordering) are tolerated; a column added on
+ * one side but not the other is not.
*/
import { describe, it, expect } from 'vitest';
@@ -36,28 +40,15 @@ const DB_JS = [
.map((f) => readFileSync(join(SCHEMA_DIR, f), 'utf8')),
].join('\n');
-const CATALOG_TABLES = [
- 'app_quality_measurements',
- 'catalog_scraps',
- 'catalog_ingredients',
- 'catalog_ingredient_sources',
- 'catalog_ingredient_refs',
- 'catalog_ingredient_relations',
- 'catalog_tags',
- 'catalog_ingredient_revisions',
- 'catalog_ingredient_media',
-];
-
-const STACKER_NEWS_TABLES = [
- 'stacker_news_accounts',
- 'stacker_news_credentials',
- 'stacker_news_territories',
- 'stacker_news_items',
- 'stacker_news_media',
- 'stacker_news_analyses',
- 'stacker_news_actions',
- 'stacker_news_action_events',
-];
+// Tables that exist ONLY in init-db.sql (fresh-install DDL, never composed
+// from JS modules on boot — currently only the memory system, documented
+// in #1337 and ADR docs/decisions/2026-04-17-memory-system-local-only.md).
+const SQL_ONLY_TOLERATED = ['memories', 'memory_links'];
+
+// Tables that exist ONLY in JS schema modules and backfill on every boot
+// (machine-local, never in init-db.sql — each entry must carry a one-line reason).
+// Currently empty — all machine-local tables are now in both sources (#6819).
+const BOOT_BACKFILL_ONLY = {};
// Strip line comments + collapse whitespace so column lists compare cleanly.
const normalize = (s) => s
@@ -72,6 +63,17 @@ function extractCreateTable(source, table) {
return normalize(m[1]);
}
+// Auto-discover all CREATE TABLE names from a source.
+function extractAllTableNames(source) {
+ const tables = new Set();
+ const re = /CREATE TABLE IF NOT EXISTS (\w+)\s*\(/gi;
+ let m;
+ while ((m = re.exec(source)) !== null) {
+ tables.add(m[1]);
+ }
+ return tables;
+}
+
// A column "name" for parity purposes: the identifier up to the first
// space. Strips inline comments, then splits on commas at depth-0 parens so
// `CHECK (type IN ('a','b'))` survives without breaking on its inner comma.
@@ -95,11 +97,41 @@ function extractColumnNames(body) {
.filter((p) => p && !/^(PRIMARY|FOREIGN|UNIQUE|CHECK|CONSTRAINT)$/i.test(p));
}
+// Extract all columns from both CREATE TABLE and ALTER TABLE ADD COLUMN statements.
+function extractAllColumns(source, table) {
+ const cols = new Set();
+
+ // Extract from CREATE TABLE body
+ const body = extractCreateTable(source, table);
+ if (body) {
+ extractColumnNames(body).forEach((col) => cols.add(col));
+ }
+
+ // Extract from ALTER TABLE ADD COLUMN statements
+ const re = new RegExp(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS (\\w+)`, 'gi');
+ let m;
+ while ((m = re.exec(source)) !== null) {
+ cols.add(m[1]);
+ }
+
+ return cols;
+}
+
// Matches both plain and UNIQUE index declarations: a dedupe index is usually
// the UNIQUE one (idx_user_action_dedupe), and a name captured on only one side
// of the parity check is exactly the drift this file exists to catch.
-function extractIndexNames(source, prefix = 'idx_catalog_') {
+// When given 'catalog_', extract all indexes that start with idx_catalog_
+// When given 'tribe_people', extract all indexes that start with idx_tribe_people_
+function extractIndexNames(source, prefixOrTable) {
const out = new Set();
+ let prefix;
+ if (prefixOrTable.startsWith('idx_')) {
+ prefix = prefixOrTable;
+ } else if (prefixOrTable.endsWith('_')) {
+ prefix = `idx_${prefixOrTable}`;
+ } else {
+ prefix = `idx_${prefixOrTable}_`;
+ }
const re = new RegExp(`CREATE (?:UNIQUE )?INDEX IF NOT EXISTS\\s+(${prefix}\\w+)`, 'gi');
let m;
while ((m = re.exec(source)) !== null) out.add(m[1]);
@@ -112,10 +144,10 @@ function extractIndexNames(source, prefix = 'idx_catalog_') {
// intended, and a dropped UNIQUE breaks the ON CONFLICT idempotency contract
// the store relies on. Pair each name with its normalized definition so the
// parity check compares shape, not just identity.
-function extractIndexDefs(source, prefix) {
+function extractIndexDefs(source, table) {
const out = new Map();
const re = new RegExp(
- `CREATE (UNIQUE )?INDEX IF NOT EXISTS\\s+(${prefix}\\w+)\\s+ON\\s+\\w+\\s*\\(([^)]*)\\)`,
+ `CREATE (UNIQUE )?INDEX IF NOT EXISTS\\s+(\\w+)\\s+ON ${table}\\s*\\(([^)]*)\\)`,
'gi',
);
let m;
@@ -126,7 +158,8 @@ function extractIndexDefs(source, prefix) {
return out;
}
-function extractFunctionNames(source, prefix = 'update_catalog_') {
+// Extract functions matching a prefix (e.g. 'update_catalog_')
+function extractFunctionNames(source, prefix) {
const out = new Set();
const re = new RegExp(`CREATE OR REPLACE FUNCTION\\s+(${prefix}\\w+)`, 'gi');
let m;
@@ -134,9 +167,11 @@ function extractFunctionNames(source, prefix = 'update_catalog_') {
return out;
}
-function extractTriggerNames(source, prefix = 'trg_catalog_') {
+// Extract triggers matching a prefix (e.g. 'trg_catalog_')
+function extractTriggerNames(source, triggerPrefix) {
const out = new Set();
- const re = new RegExp(`CREATE TRIGGER\\s+(${prefix}\\w+)`, 'gi');
+ // Match "CREATE TRIGGER name" where name starts with the prefix
+ const re = new RegExp(`CREATE TRIGGER\\s+(${triggerPrefix}\\w+)`, 'gi');
let m;
while ((m = re.exec(source)) !== null) out.add(m[1]);
return out;
@@ -184,465 +219,114 @@ function extractPayloadFtsKeys(source) {
return out;
}
-describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {
- it.each(CATALOG_TABLES)('table %s has the same columns in both files', (table) => {
- const sqlBody = extractCreateTable(INIT_SQL, table);
- const jsBody = extractCreateTable(DB_JS, table);
- expect(sqlBody, `init-db.sql missing CREATE TABLE ${table}`).toBeTruthy();
- expect(jsBody, `db.js missing CREATE TABLE ${table}`).toBeTruthy();
- const sqlCols = new Set(extractColumnNames(sqlBody));
- const jsCols = new Set(extractColumnNames(jsBody));
- expect([...sqlCols].sort()).toEqual([...jsCols].sort());
- });
-
- it.each(STACKER_NEWS_TABLES)('Stacker News table %s has the same columns in both files', (table) => {
- const sqlBody = extractCreateTable(INIT_SQL, table);
- const jsBody = extractCreateTable(DB_JS, table);
- expect(sqlBody, `init-db.sql missing CREATE TABLE ${table}`).toBeTruthy();
- expect(jsBody, `db.js missing CREATE TABLE ${table}`).toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- });
-
- it('every idx_stacker_news_* index name appears in both files', () => {
- const sqlIdx = extractIndexNames(INIT_SQL, 'idx_stacker_news_');
- const jsIdx = extractIndexNames(DB_JS, 'idx_stacker_news_');
- expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
- expect(sqlIdx.size).toBeGreaterThan(0);
- });
-
- // The operator-action ledger (#5594) and the human-activity timeline (#2150)
- // are machine-local db-primary tables that ship in BOTH sources. A column or
- // index added to one file only would leave every EXISTING install without it
- // (init-db.sql runs on fresh provisioning alone), so pin columns and index
- // names for both explicitly.
- it('human_activity_events has the same columns and indexes in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'human_activity_events');
- const jsBody = extractCreateTable(DB_JS, 'human_activity_events');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE human_activity_events').toBeTruthy();
- expect(jsBody, 'db/schema/humanActivity.js missing CREATE TABLE human_activity_events').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
-
- // Compare definitions, not just names: an index present in both files under
- // the same name but over different columns would ship a fresh install
- // something the boot-time DDL never intended.
- const sqlIdx = extractIndexDefs(INIT_SQL, 'idx_human_activity_');
- const jsIdx = extractIndexDefs(DB_JS, 'idx_human_activity_');
- // Spell out the expected map: the dedupe index is the idempotency contract
- // (ON CONFLICT (source, dedupe_key) DO NOTHING) and the two composites
- // (#5715) are what keep a source-scoped timeline read off a full
- // happened_at walk — dropping either from both files, or silently losing
- // the DESC ordering, would otherwise read as a passing set match.
- const expected = {
- idx_human_activity_dedupe: 'unique (source, dedupe_key)',
- idx_human_activity_happened: '(happened_at)',
- idx_human_activity_source_happened: '(source, happened_at desc)',
- idx_human_activity_source_kind_happened: '(source, kind, happened_at desc)',
- };
- expect(Object.fromEntries(sqlIdx)).toEqual(expected);
- expect(Object.fromEntries(jsIdx)).toEqual(expected);
- });
- it('user_action_events has the same columns and indexes in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'user_action_events');
- const jsBody = extractCreateTable(DB_JS, 'user_action_events');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE user_action_events').toBeTruthy();
- expect(jsBody, 'db/schema/userActions.js missing CREATE TABLE user_action_events').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
-
- const sqlIdx = extractIndexNames(INIT_SQL, 'idx_user_action_');
- const jsIdx = extractIndexNames(DB_JS, 'idx_user_action_');
- expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
- // The dedupe index is the idempotency contract (ON CONFLICT (type, dedupe_key)
- // DO NOTHING) — name it so dropping it can never read as a passing set match.
- expect([...sqlIdx].sort()).toEqual([
- 'idx_user_action_actor_time',
- 'idx_user_action_dedupe',
- 'idx_user_action_happened',
- 'idx_user_action_type_time',
- ]);
- });
+describe('DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {
+ it('discovers all shared tables and confirms no unexpected SQL-only or JS-only tables', () => {
+ const sqlTables = extractAllTableNames(INIT_SQL);
+ const jsTables = extractAllTableNames(DB_JS);
- it('every idx_catalog_* index name appears in both files', () => {
- const sqlIdx = extractIndexNames(INIT_SQL);
- const jsIdx = extractIndexNames(DB_JS);
- expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
- expect(sqlIdx.size).toBeGreaterThan(0);
- });
+ const shared = new Set([...sqlTables].filter((t) => jsTables.has(t)));
+ const sqlOnly = new Set([...sqlTables].filter((t) => !jsTables.has(t)));
+ const jsOnly = new Set([...jsTables].filter((t) => !sqlTables.has(t)));
- it('every update_catalog_* trigger function appears in both files', () => {
- const sqlFns = extractFunctionNames(INIT_SQL);
- const jsFns = extractFunctionNames(DB_JS);
- expect([...sqlFns].sort()).toEqual([...jsFns].sort());
- expect(sqlFns.size).toBeGreaterThan(0);
- });
+ // Verify SQL_ONLY_TOLERATED contains exactly the SQL-only tables
+ expect([...sqlOnly].sort()).toEqual([...SQL_ONLY_TOLERATED].sort());
- it('every trg_catalog_* trigger appears in both files', () => {
- // Exclude the generic `*_audit` triggers (record_audit): init-db.sql spells
- // them literally while db.js builds them from the auditedTables array via a
- // `trg_${t}_audit` template literal, so a literal-name extractor only sees
- // them on the init-db.sql side. They have their own parity assertion below.
- const noAudit = (s) => new Set([...s].filter((t) => !t.endsWith('_audit')));
- const sqlTrgs = noAudit(extractTriggerNames(INIT_SQL));
- const jsTrgs = noAudit(extractTriggerNames(DB_JS));
- expect([...sqlTrgs].sort()).toEqual([...jsTrgs].sort());
- expect(sqlTrgs.size).toBeGreaterThan(0);
- });
+ // Verify BOOT_BACKFILL_ONLY contains exactly the JS-only tables
+ expect([...jsOnly].sort()).toEqual([...Object.keys(BOOT_BACKFILL_ONLY)].sort());
- it('catalog_ingredients type is app-layer-gated (no hardcoded CHECK in either file)', () => {
- // The legacy `CHECK (type IN (...))` was dropped — valid types are gated at
- // the app layer via the INGREDIENT_TYPES registry + Zod enum, so a new type
- // is a registry entry, not a two-file constraint migration. Assert NEITHER
- // file reintroduces a hardcoded `type IN (...)` CHECK (a one-sided re-add
- // would drift the fresh-install and upgrade paths apart again), and that
- // both declare the widened VARCHAR(32) column.
- expect(extractTypeCheckSet(INIT_SQL), 'init-db.sql reintroduced a hardcoded type CHECK').toBeNull();
- expect(extractTypeCheckSet(DB_JS), 'db.js reintroduced a hardcoded type CHECK').toBeNull();
- expect(/type VARCHAR\(32\)/i.test(extractCreateTable(INIT_SQL, 'catalog_ingredients'))).toBe(true);
- expect(/type VARCHAR\(32\)/i.test(extractCreateTable(DB_JS, 'catalog_ingredients'))).toBe(true);
+ // Confirm we have reasonable coverage
+ expect(shared.size).toBeGreaterThan(50);
+ console.log(`✓ Discovered ${shared.size} shared tables, ${sqlOnly.size} SQL-only, ${jsOnly.size} JS-only`);
});
- // Non-catalog table that nonetheless lives in BOTH DDL sources (fresh-install
- // init-db.sql + upgrade-path ensureSchema) and so has the same drift risk.
- it('creative_director_projects has the same columns in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'creative_director_projects');
- const jsBody = extractCreateTable(DB_JS, 'creative_director_projects');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE creative_director_projects').toBeTruthy();
- expect(jsBody, 'db.js missing CREATE TABLE creative_director_projects').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- });
+ // For each shared table, verify columns, indexes, triggers, and functions match
+ describe('shared table parity', () => {
+ const sqlTables = extractAllTableNames(INIT_SQL);
+ const jsTables = extractAllTableNames(DB_JS);
+ const shared = [...sqlTables].filter((t) => jsTables.has(t));
- // Media asset index (#1000) — non-catalog table in BOTH DDL sources, plus a
- // non-`idx_catalog_`-prefixed index, so it needs its own parity assertion.
- it('media_assets has the same columns and index in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'media_assets');
- const jsBody = extractCreateTable(DB_JS, 'media_assets');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE media_assets').toBeTruthy();
- expect(jsBody, 'db.js missing CREATE TABLE media_assets').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- const sqlIdx = extractIndexNames(INIT_SQL, 'idx_media_assets_');
- const jsIdx = extractIndexNames(DB_JS, 'idx_media_assets_');
- expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
- expect(sqlIdx.size).toBeGreaterThan(0);
- });
+ it.each(shared)('table %s has the same columns in both files', (table) => {
+ const sqlCols = extractAllColumns(INIT_SQL, table);
+ const jsCols = extractAllColumns(DB_JS, table);
- // Catalog user-defined types (#1001) — non-`catalog_`-prefixed table name in
- // BOTH DDL sources (the parity `CATALOG_TABLES` loop matches by literal table
- // name, and this one isn't in that list), so it gets its own column assertion.
- // It declares no secondary index, so nothing to compare there.
- it('catalog_user_types has the same columns in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'catalog_user_types');
- const jsBody = extractCreateTable(DB_JS, 'catalog_user_types');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE catalog_user_types').toBeTruthy();
- expect(jsBody, 'db.js missing CREATE TABLE catalog_user_types').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- });
+ const sqlOnly = [...sqlCols].filter((c) => !jsCols.has(c));
+ const jsOnly = [...jsCols].filter((c) => !sqlCols.has(c));
- // Universe Builder records (#1014) — non-`catalog_`-prefixed table in BOTH
- // DDL sources, with non-`idx_catalog_`-prefixed indexes, so it gets its own
- // column + index parity assertion.
- it('universes has the same columns and indexes in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'universes');
- const jsBody = extractCreateTable(DB_JS, 'universes');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE universes').toBeTruthy();
- expect(jsBody, 'db.js missing CREATE TABLE universes').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- const sqlIdx = extractIndexNames(INIT_SQL, 'idx_universes_');
- const jsIdx = extractIndexNames(DB_JS, 'idx_universes_');
- expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
- expect(sqlIdx.size).toBeGreaterThan(0);
- });
+ expect(sqlOnly, `init-db.sql has extra columns: ${sqlOnly.join(', ')}`).toEqual([]);
+ expect(jsOnly, `db.js has extra columns: ${jsOnly.join(', ')}`).toEqual([]);
+ });
- // Universe render-history log (#1014) — same drift risk; its own table + index.
- it('universe_runs has the same columns and index in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'universe_runs');
- const jsBody = extractCreateTable(DB_JS, 'universe_runs');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE universe_runs').toBeTruthy();
- expect(jsBody, 'db.js missing CREATE TABLE universe_runs').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- const sqlIdx = extractIndexNames(INIT_SQL, 'idx_universe_runs_');
- const jsIdx = extractIndexNames(DB_JS, 'idx_universe_runs_');
- expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
- expect(sqlIdx.size).toBeGreaterThan(0);
- });
+ it.each(shared)('table %s has matching index names in both files', (table) => {
+ const sqlIdx = extractIndexNames(INIT_SQL, table);
+ const jsIdx = extractIndexNames(DB_JS, table);
- it('voice_profiles has the same columns and indexes in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'voice_profiles');
- const jsBody = extractCreateTable(DB_JS, 'voice_profiles');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE voice_profiles').toBeTruthy();
- expect(jsBody, 'db.js missing CREATE TABLE voice_profiles').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- const sqlIdx = extractIndexNames(INIT_SQL, 'idx_voice_profiles_');
- const jsIdx = extractIndexNames(DB_JS, 'idx_voice_profiles_');
- expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
- expect(sqlIdx.size).toBeGreaterThan(0);
- });
+ const sqlOnly = [...sqlIdx].filter((i) => !jsIdx.has(i));
+ const jsOnly = [...jsIdx].filter((i) => !sqlIdx.has(i));
- it('voice_profile_renders has the same columns and indexes in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'voice_profile_renders');
- const jsBody = extractCreateTable(DB_JS, 'voice_profile_renders');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE voice_profile_renders').toBeTruthy();
- expect(jsBody, 'db.js missing CREATE TABLE voice_profile_renders').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- const sqlIdx = extractIndexNames(INIT_SQL, 'idx_voice_profile_renders_');
- const jsIdx = extractIndexNames(DB_JS, 'idx_voice_profile_renders_');
- expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
- expect(sqlIdx.size).toBeGreaterThan(0);
- });
+ expect(sqlOnly, `init-db.sql has extra indexes: ${sqlOnly.join(', ')}`).toEqual([]);
+ expect(jsOnly, `db.js has extra indexes: ${jsOnly.join(', ')}`).toEqual([]);
+ });
- // Pipeline series (#1015) — non-`catalog_`-prefixed table in BOTH DDL
- // sources, with non-`idx_catalog_`-prefixed indexes, so its own assertion.
- it('pipeline_series has the same columns and indexes in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'pipeline_series');
- const jsBody = extractCreateTable(DB_JS, 'pipeline_series');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE pipeline_series').toBeTruthy();
- expect(jsBody, 'db.js missing CREATE TABLE pipeline_series').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- const sqlIdx = extractIndexNames(INIT_SQL, 'idx_series_');
- const jsIdx = extractIndexNames(DB_JS, 'idx_series_');
- expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
- expect(sqlIdx.size).toBeGreaterThan(0);
- });
+ // For tables with multiple indexes, also verify index definitions match
+ // (not just names — indexes can drift in their column list or uniqueness)
+ const tablesWithIndexes = shared.filter((table) => {
+ const sqlIdx = extractIndexNames(INIT_SQL, table);
+ return sqlIdx.size > 0;
+ });
- // Pipeline issues (#1015) — same drift risk; its own table + indexes.
- it('pipeline_issues has the same columns and indexes in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'pipeline_issues');
- const jsBody = extractCreateTable(DB_JS, 'pipeline_issues');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE pipeline_issues').toBeTruthy();
- expect(jsBody, 'db.js missing CREATE TABLE pipeline_issues').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- const sqlIdx = extractIndexNames(INIT_SQL, 'idx_issues_');
- const jsIdx = extractIndexNames(DB_JS, 'idx_issues_');
- expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
- expect(sqlIdx.size).toBeGreaterThan(0);
- });
+ it.each(tablesWithIndexes)('table %s has matching index definitions in both files', (table) => {
+ const sqlIdx = extractIndexDefs(INIT_SQL, table);
+ const jsIdx = extractIndexDefs(DB_JS, table);
- // Story Builder sessions (#1016) — same drift risk; its own table + indexes.
- it('story_builder_sessions has the same columns and indexes in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'story_builder_sessions');
- const jsBody = extractCreateTable(DB_JS, 'story_builder_sessions');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE story_builder_sessions').toBeTruthy();
- expect(jsBody, 'db.js missing CREATE TABLE story_builder_sessions').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- const sqlIdx = extractIndexNames(INIT_SQL, 'idx_stb_');
- const jsIdx = extractIndexNames(DB_JS, 'idx_stb_');
- expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
- expect(sqlIdx.size).toBeGreaterThan(0);
+ for (const [name, def] of sqlIdx) {
+ expect(jsIdx.get(name), `table ${table} index ${name} definition mismatch`).toEqual(def);
+ }
+ for (const [name, def] of jsIdx) {
+ expect(sqlIdx.get(name), `table ${table} index ${name} definition mismatch`).toEqual(def);
+ }
+ });
});
- // Writers Room (#1017) — four tables, each its own column + index parity
- // assertion (distinct idx_wr_<table>_ prefixes keep them isolated).
- for (const { table, idxPrefix } of [
- { table: 'writers_room_folders', idxPrefix: 'idx_wr_folders_' },
- { table: 'writers_room_works', idxPrefix: 'idx_wr_works_' },
- { table: 'writers_room_draft_versions', idxPrefix: 'idx_wr_drafts_' },
- { table: 'writers_room_exercises', idxPrefix: 'idx_wr_exercises_' },
- ]) {
- it(`${table} has the same columns and indexes in both files`, () => {
- const sqlBody = extractCreateTable(INIT_SQL, table);
- const jsBody = extractCreateTable(DB_JS, table);
- expect(sqlBody, `init-db.sql missing CREATE TABLE ${table}`).toBeTruthy();
- expect(jsBody, `db.js missing CREATE TABLE ${table}`).toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- const sqlIdx = extractIndexNames(INIT_SQL, idxPrefix);
- const jsIdx = extractIndexNames(DB_JS, idxPrefix);
+ // Catalog-specific checks (these existed before the generalization)
+ describe('catalog-specific parity', () => {
+ it('every idx_catalog_* index name appears in both files', () => {
+ const sqlIdx = extractIndexNames(INIT_SQL, 'catalog_');
+ const jsIdx = extractIndexNames(DB_JS, 'catalog_');
expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
expect(sqlIdx.size).toBeGreaterThan(0);
});
- }
- // Beeper mirror (#27 + #35) — eight machine-local tables that ship in BOTH
- // sources. `beeper_messages.is_sender` is the reason this block exists: a
- // column present on one side only would leave every EXISTING install with a
- // thread that has one side (init-db.sql runs on fresh provisioning alone),
- // and the additive `ALTER TABLE … ADD COLUMN IF NOT EXISTS` that backfills it
- // is asserted separately below, because a CREATE TABLE match alone would pass
- // while pre-existing installs never got the column.
- for (const { table, idxPrefix } of [
- { table: 'beeper_accounts', idxPrefix: null },
- { table: 'beeper_credentials', idxPrefix: null },
- { table: 'beeper_conversations', idxPrefix: 'idx_beeper_conversations_' },
- { table: 'beeper_participants', idxPrefix: 'idx_beeper_participants_' },
- { table: 'beeper_messages', idxPrefix: 'idx_beeper_messages_' },
- { table: 'beeper_attachments', idxPrefix: 'idx_beeper_attachments_' },
- { table: 'beeper_sync_cursors', idxPrefix: null },
- { table: 'beeper_outbox', idxPrefix: 'idx_beeper_outbox_' },
- ]) {
- it(`${table} has the same columns${idxPrefix ? ' and indexes' : ''} in both files`, () => {
- const sqlBody = extractCreateTable(INIT_SQL, table);
- const jsBody = extractCreateTable(DB_JS, table);
- expect(sqlBody, `init-db.sql missing CREATE TABLE ${table}`).toBeTruthy();
- expect(jsBody, `db/schema/beeper.js missing CREATE TABLE ${table}`).toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- if (!idxPrefix) return;
- const sqlIdx = extractIndexNames(INIT_SQL, idxPrefix);
- const jsIdx = extractIndexNames(DB_JS, idxPrefix);
- expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
- expect(sqlIdx.size).toBeGreaterThan(0);
+ it('every update_catalog_* trigger function appears in both files', () => {
+ const sqlFns = extractFunctionNames(INIT_SQL, 'update_catalog_');
+ const jsFns = extractFunctionNames(DB_JS, 'update_catalog_');
+ expect([...sqlFns].sort()).toEqual([...jsFns].sort());
+ expect(sqlFns.size).toBeGreaterThan(0);
});
- }
- // LENS-7: beeper_outbox's `state` CHECK is PortOS's own send-lifecycle state
- // machine (not a Beeper vocabulary), so — unlike beeper_conversations.type —
- // a new state SHOULD cost a two-file schema change. Pin the literal set so a
- // value added to one file's CHECK and not the other (or silently dropped
- // from both) fails here rather than at a runtime INSERT.
- it('beeper_outbox.state CHECK literal set is pinned and matches in both files', () => {
- const expected = new Set(['draft', 'approved', 'sending', 'awaiting-confirmation', 'sent', 'failed']);
- const sqlSet = extractCheckInSet(INIT_SQL, 'beeper_outbox', 'state');
- const jsSet = extractCheckInSet(DB_JS, 'beeper_outbox', 'state');
- expect(sqlSet, 'init-db.sql missing beeper_outbox.state CHECK').not.toBeNull();
- expect(jsSet, 'db/schema/beeper.js missing beeper_outbox.state CHECK').not.toBeNull();
- expect(sqlSet).toEqual(expected);
- expect(jsSet).toEqual(expected);
- });
-
- // LENS-7: tribe_identities (server/lib/db/schema/tribe.js) is what a durable
- // Beeper handle claim (kind='handle') resolves against — the same drift risk
- // as the beeper_* block above (a column or index added to one DDL source
- // only), so it gets its own parity assertion.
- it('tribe_identities has the same columns and indexes in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'tribe_identities');
- const jsBody = extractCreateTable(DB_JS, 'tribe_identities');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE tribe_identities').toBeTruthy();
- expect(jsBody, 'db/schema/tribe.js missing CREATE TABLE tribe_identities').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- const sqlIdx = extractIndexNames(INIT_SQL, 'idx_tribe_identities_');
- const jsIdx = extractIndexNames(DB_JS, 'idx_tribe_identities_');
- expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
- expect(sqlIdx.size).toBeGreaterThan(0);
- });
-
- // Every column a beeper_* table gained after its first ship needs an
- // additive ALTER on the upgrade path too — a fresh install gets it from the
- // CREATE above, an existing one only from here.
- it('beeper_* additive columns carry an ALTER TABLE for existing installs', () => {
- for (const { table, columns } of [
- { table: 'beeper_messages', columns: ['is_sender'] },
- { table: 'beeper_attachments', columns: ['local_path', 'fetched_at', 'unavailable_at', 'fetch_error'] },
- { table: 'beeper_conversations', columns: ['seen_at'] },
- ]) {
- for (const column of columns) {
- const re = new RegExp(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${column}\\b`, 'i');
- expect(re.test(DB_JS), `db/schema/beeper.js missing the additive ALTER for ${table}.${column}`).toBe(true);
- expect(extractCreateTable(INIT_SQL, table)).toContain(column);
- }
- }
- });
-
- // Versioned DB-migration tracker (#1029) — non-`catalog_`-prefixed table in
- // BOTH DDL sources (base schema), so it gets its own column parity assertion.
- // No secondary index, nothing to compare there.
- it('schema_migrations has the same columns in both files', () => {
- const sqlBody = extractCreateTable(INIT_SQL, 'schema_migrations');
- const jsBody = extractCreateTable(DB_JS, 'schema_migrations');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE schema_migrations').toBeTruthy();
- expect(jsBody, 'db.js missing CREATE TABLE schema_migrations').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
- });
-
- // Deletion audit log (incident #1248-follow-up) — the record_audit table, the
- // record_audit_log() trigger function, and the per-content-table `_audit`
- // triggers all live in BOTH DDL sources. A one-sided edit (e.g. auditing a new
- // table only in db.js) would leave fresh installs un-audited, so lock all three.
- it('record_audit table + trigger function + audit triggers match in both files', () => {
- // table columns
- const sqlBody = extractCreateTable(INIT_SQL, 'record_audit');
- const jsBody = extractCreateTable(DB_JS, 'record_audit');
- expect(sqlBody, 'init-db.sql missing CREATE TABLE record_audit').toBeTruthy();
- expect(jsBody, 'db.js missing CREATE TABLE record_audit').toBeTruthy();
- expect([...new Set(extractColumnNames(sqlBody))].sort())
- .toEqual([...new Set(extractColumnNames(jsBody))].sort());
-
- // generic trigger function present in both
- expect(/CREATE OR REPLACE FUNCTION\s+record_audit_log\b/i.test(INIT_SQL)).toBe(true);
- expect(/CREATE OR REPLACE FUNCTION\s+record_audit_log\b/i.test(DB_JS)).toBe(true);
-
- // The set of audited tables is identical across both. init-db.sql spells out
- // a `trg_<table>_audit` per table; db.js builds them from the `auditedTables`
- // array via a `trg_${t}_audit` template literal, so we parse that array on the
- // js side rather than matching literal trigger names.
- const sqlAuditTables = (() => {
- const out = new Set();
- const re = /CREATE TRIGGER\s+trg_([a-z0-9_]+)_audit\b/gi;
- let m;
- while ((m = re.exec(INIT_SQL)) !== null) out.add(m[1]);
- return out;
- })();
- const jsAuditTables = (() => {
- const m = /const auditedTables\s*=\s*\[([\s\S]*?)\]/i.exec(DB_JS);
- expect(m, 'db.js missing the auditedTables array').toBeTruthy();
- const out = new Set();
- const re = /'([a-z0-9_]+)'/gi;
- let mm;
- while ((mm = re.exec(m[1])) !== null) out.add(mm[1]);
- return out;
- })();
- expect(sqlAuditTables.size, 'no _audit triggers found in init-db.sql — DDL broke').toBeGreaterThan(8);
- expect([...sqlAuditTables].sort()).toEqual([...jsAuditTables].sort());
- });
-
- // Broad drift guard for the whole upgrade-vs-fresh-install gap (beyond the
- // catalog tables above). init-db.sql runs ONLY on fresh `db.sh setup-native`
- // provisioning; existing installs + federated peers get new tables solely
- // through db.js `ensureSchema()`'s catalogDDL array. A table added to one
- // source but not the other is invisible until a real upgrade fails in the
- // wild (e.g. lora_training_runs shipped in init-db.sql but was missing from
- // ensureSchema — every existing install would 500 on the first training run).
- it('every table in init-db.sql is also created in db.js ensureSchema', () => {
- const tableNames = (source) => {
- const out = new Set();
- const re = /CREATE TABLE IF NOT EXISTS\s+([a-z0-9_]+)/gi;
- let m;
- while ((m = re.exec(source)) !== null) out.add(m[1].toLowerCase());
- return out;
- };
- // The memory subsystem provisions its own tables via a separate path
- // (server/scripts/migrate*Memories*.js), so they live in init-db.sql but
- // intentionally NOT in ensureSchema — the documented exception in this
- // file's header. Everything else must be in both.
- const PROVISIONED_ELSEWHERE = new Set(['memories', 'memory_links']);
- const sqlTables = tableNames(INIT_SQL);
- const jsTables = tableNames(DB_JS);
- expect(sqlTables.size, 'init-db.sql declares no tables — parser broke').toBeGreaterThan(8);
- const missing = [...sqlTables]
- .filter((t) => !jsTables.has(t) && !PROVISIONED_ELSEWHERE.has(t));
- expect(missing, `tables in init-db.sql but missing from db.js ensureSchema (existing installs won't get them): ${missing.join(', ')}`).toEqual([]);
- });
+ it('every trg_catalog_* trigger appears in both files', () => {
+ // Exclude the generic `*_audit` triggers (record_audit): init-db.sql spells
+ // them literally while db.js builds them from the auditedTables array via a
+ // `trg_${t}_audit` template literal, so a literal-name extractor only sees
+ // them on the init-db.sql side. They have their own parity assertion below.
+ const noAudit = (s) => new Set([...s].filter((t) => !t.endsWith('_audit')));
+ const sqlTrgs = noAudit(extractTriggerNames(INIT_SQL, 'trg_catalog_'));
+ const jsTrgs = noAudit(extractTriggerNames(DB_JS, 'trg_catalog_'));
+ expect([...sqlTrgs].sort()).toEqual([...jsTrgs].sort());
+ expect(sqlTrgs.size).toBeGreaterThan(0);
+ });
- it('search_tsv payload field set matches', () => {
- // Both files re-declare the GENERATED ALWAYS expression character-for-
- // character today. If one side adds a payload key (e.g. voiceNotes) and
- // the other lags, the FTS index expression mismatches and search returns
- // different rows on a fresh install vs an upgraded install.
- const sqlKeys = extractPayloadFtsKeys(INIT_SQL);
- const jsKeys = extractPayloadFtsKeys(DB_JS);
- expect([...sqlKeys].sort()).toEqual([...jsKeys].sort());
- // The registry (`catalogTypes.FTS_PAYLOAD_FIELDS`) is the single source of
- // truth for which payload keys the FTS column must index. Derive the
- // required set from it rather than a hand-maintained list, so adding a
- // type's `ftsFields` without updating BOTH DDL sources fails here instead
- // of silently de-indexing the field.
- expect(FTS_PAYLOAD_FIELDS.length, 'registry declares no FTS payload fields').toBeGreaterThan(0);
- for (const required of FTS_PAYLOAD_FIELDS) {
- expect(sqlKeys.has(required), `init-db.sql search_tsv missing registry FTS field ${required}`).toBe(true);
- expect(jsKeys.has(required), `db.js search_tsv missing registry FTS field ${required}`).toBe(true);
- }
+ it('catalog_ingredients type is app-layer-gated (no hardcoded CHECK in either file)', () => {
+ // The legacy `CHECK (type IN (...))` was dropped — valid types are gated at
+ // the app layer via the INGREDIENT_TYPES registry + Zod enum, so a new type
+ // is a registry entry, not a two-file constraint migration. Assert NEITHER
+ // file reintroduces a hardcoded `type IN (...)` CHECK (a one-sided re-add
+ // would drift the fresh-install and upgrade paths apart again), and that
+ // both declare the widened VARCHAR(32) column.
+ expect(extractCheckInSet(INIT_SQL, 'catalog_ingredients', 'type'), 'init-db.sql reintroduced a hardcoded type CHECK').toBeNull();
+ expect(extractCheckInSet(DB_JS, 'catalog_ingredients', 'type'), 'db.js reintroduced a hardcoded type CHECK').toBeNull();
+ expect(/type VARCHAR\(32\)/i.test(extractCreateTable(INIT_SQL, 'catalog_ingredients'))).toBe(true);
+ expect(/type VARCHAR\(32\)/i.test(extractCreateTable(DB_JS, 'catalog_ingredients'))).toBe(true);
+ });
});
});
diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.md
index 66565d2c66..b6914136dc 100644
--- a/server/lib/db/schema/README.md
+++ b/server/lib/db/schema/README.md
@@ -14,7 +14,11 @@ 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.
+`server/lib/db.ddlParity.test.js`, which auto-discovers all 72 shared tables and
+compares columns, indexes, triggers, and functions for each. Two tolerance lists
+guard the exceptional cases: `SQL_ONLY_TOLERATED` for tables in init-db.sql but not
+JS (the memory system, #1337), and `BOOT_BACKFILL_ONLY` for machine-local tables in
+JS but not init-db.sql (with one-line reasons for each).
| Module | Export(s) | Domain |
|---|---|---|
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 2e211d4a07..1852c1f749 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -141,9 +141,14 @@ CREATE TABLE IF NOT EXISTS tribe_people (
-- Known emails/handles for a person — the deterministic key that maps a calendar
-- attendee / message counterpart back to this tracked person (#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(),
@@ -1945,6 +1950,95 @@ CREATE TRIGGER trg_tribe_touchpoints_audit AFTER UPDATE OR DELETE ON tribe_touch
DROP TRIGGER IF EXISTS trg_tribe_identities_audit ON tribe_identities;
CREATE TRIGGER trg_tribe_identities_audit AFTER UPDATE OR DELETE ON tribe_identities FOR EACH ROW EXECUTE FUNCTION record_audit_log();
+-- AI provider connection graph DDL — `ai_connections`, `ai_harness_bindings`
+-- and `ai_route_bindings` (#6367, design record
+-- docs/plans/2026-09-06-provider-connections-and-harnesses.md). Machine-local
+-- by construction and never federated — rows carry endpoints, credential
+-- material and this host's execution environment.
+CREATE TABLE IF NOT EXISTS ai_connections (
+ id UUID PRIMARY KEY,
+ revision INTEGER NOT NULL DEFAULT 1,
+ kind TEXT NOT NULL,
+ label TEXT NOT NULL DEFAULT '',
+ transports JSONB NOT NULL DEFAULT '{}'::jsonb,
+ credentials JSONB NOT NULL DEFAULT '{}'::jsonb,
+ catalog JSONB NOT NULL DEFAULT '{"state":"unknown","models":[]}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+);
+
+CREATE TABLE IF NOT EXISTS ai_harness_bindings (
+ id UUID PRIMARY KEY,
+ revision INTEGER NOT NULL DEFAULT 1,
+ connection_id UUID NOT NULL REFERENCES ai_connections (id),
+ harness_id TEXT,
+ variant_key TEXT NOT NULL DEFAULT 'default',
+ label TEXT NOT NULL DEFAULT '',
+ enabled BOOLEAN NOT NULL DEFAULT false,
+ selected_models JSONB NOT NULL DEFAULT '[]'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+);
+CREATE UNIQUE INDEX IF NOT EXISTS uq_ai_harness_bindings_variant
+ ON ai_harness_bindings (connection_id, harness_id, variant_key)
+ WHERE harness_id IS NOT NULL;
+CREATE UNIQUE INDEX IF NOT EXISTS uq_ai_harness_bindings_api_variant
+ ON ai_harness_bindings (connection_id, variant_key)
+ WHERE harness_id IS NULL;
+CREATE INDEX IF NOT EXISTS idx_ai_harness_bindings_connection
+ ON ai_harness_bindings (connection_id);
+
+CREATE TABLE IF NOT EXISTS ai_route_bindings (
+ provider_id TEXT PRIMARY KEY,
+ binding_id UUID NOT NULL REFERENCES ai_harness_bindings (id),
+ mode TEXT NOT NULL CHECK (mode IN ('cli', 'tui', 'api')),
+ model_map JSONB NOT NULL DEFAULT '{}'::jsonb,
+ projected JSONB NOT NULL DEFAULT '{}'::jsonb,
+ pending JSONB,
+ pending_revision INTEGER,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+);
+ALTER TABLE ai_route_bindings ADD COLUMN IF NOT EXISTS model_alias_overrides JSONB NOT NULL DEFAULT '{}'::jsonb;
+CREATE UNIQUE INDEX IF NOT EXISTS uq_ai_route_bindings_binding_mode
+ ON ai_route_bindings (binding_id, mode);
+CREATE INDEX IF NOT EXISTS idx_ai_route_bindings_binding
+ ON ai_route_bindings (binding_id);
+
+-- Creative Commissions (#2657) — standing, recurring creative brief that fires
+-- on a schedule and drives the Creative Director directive pipeline unattended.
+-- Machine-local: never federated (a synced schedule would double-run on every peer).
+-- The commission BRIEF federates as of #2686; the schedule/runs stay machine-local.
+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);
+
+-- Creative Commission FEEDBACK — the split-record federation half (#2686).
+-- 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).
+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);
+
-- Immutable machine-local scheduled audit measurements per app/category/run.
CREATE TABLE IF NOT EXISTS app_quality_measurements (
app_id TEXT NOT NULL,