// --------------------------------------------------------------------------- // Schema definitions and migrations for SQLite / PostgreSQL engines. // --------------------------------------------------------------------------- export interface Migration { version: number; name: string; up: (d: DialectTag) => string[]; } /** Tag used by migrations to branch on backend. */ export type DialectTag = "sqlite" | "postgresql"; // --------------------------------------------------------------------------- // Migration list // --------------------------------------------------------------------------- export const migrations: Migration[] = [ { version: 1, name: "initial_schema", up: (d) => { const jsonType = d === "sqlite" ? "TEXT" : "JSONB"; const blobType = d === "sqlite" ? "BLOB" : "BYTEA"; const tsDefault = d === "sqlite" ? "datetime('now')" : "NOW()"; const autoTs = `DEFAULT (${tsDefault})`; return [ // _migrations (self-bootstrap — created by runner, but listed for clarity) `CREATE TABLE IF NOT EXISTS _migrations ( version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TIMESTAMP ${autoTs} )`, // conversations `CREATE TABLE IF NOT EXISTS conversations ( id TEXT PRIMARY KEY, agent_id TEXT NOT NULL, tenant_id TEXT NOT NULL DEFAULT '__default__', owner_id TEXT NOT NULL DEFAULT 'local-owner', title TEXT NOT NULL DEFAULT 'New conversation', data ${jsonType} NOT NULL, message_count INTEGER NOT NULL DEFAULT 0, created_at TIMESTAMP ${autoTs}, updated_at TIMESTAMP ${autoTs} )`, `CREATE INDEX IF NOT EXISTS idx_conversations_lookup ON conversations (agent_id, tenant_id, owner_id, updated_at DESC)`, // memory `CREATE TABLE IF NOT EXISTS memory ( agent_id TEXT NOT NULL, tenant_id TEXT NOT NULL DEFAULT '__default__', content TEXT NOT NULL DEFAULT '', updated_at TIMESTAMP ${autoTs}, PRIMARY KEY (agent_id, tenant_id) )`, // todos `CREATE TABLE IF NOT EXISTS todos ( agent_id TEXT NOT NULL, conversation_id TEXT NOT NULL, data ${jsonType} NOT NULL, PRIMARY KEY (agent_id, conversation_id) )`, // reminders `CREATE TABLE IF NOT EXISTS reminders ( id TEXT PRIMARY KEY, agent_id TEXT NOT NULL, tenant_id TEXT NOT NULL DEFAULT '__default__', owner_id TEXT, conversation_id TEXT NOT NULL, task TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', scheduled_at REAL NOT NULL, timezone TEXT, created_at TIMESTAMP ${autoTs} )`, `CREATE INDEX IF NOT EXISTS idx_reminders_lookup ON reminders (agent_id, tenant_id, status, scheduled_at)`, // vfs_entries `CREATE TABLE IF NOT EXISTS vfs_entries ( agent_id TEXT NOT NULL, tenant_id TEXT NOT NULL DEFAULT '__default__', path TEXT NOT NULL, parent_path TEXT NOT NULL, type TEXT NOT NULL DEFAULT 'file', content ${blobType}, symlink_target TEXT, mime_type TEXT, size INTEGER NOT NULL DEFAULT 0, mode INTEGER NOT NULL DEFAULT 438, created_at TIMESTAMP ${autoTs}, updated_at TIMESTAMP ${autoTs}, PRIMARY KEY (agent_id, tenant_id, path) )`, `CREATE INDEX IF NOT EXISTS idx_vfs_parent ON vfs_entries (agent_id, tenant_id, parent_path)`, ]; }, }, { version: 2, name: "separate_tool_result_archive", up: (d) => { const jsonType = d === "sqlite" ? "TEXT" : "JSONB"; return [ `ALTER TABLE conversations ADD COLUMN tool_result_archive ${jsonType}`, ]; }, }, { version: 3, name: "extract_heavy_fields_from_data_blob", up: (d) => { const jsonType = d === "sqlite" ? "TEXT" : "JSONB"; return [ `ALTER TABLE conversations ADD COLUMN harness_messages ${jsonType}`, `ALTER TABLE conversations ADD COLUMN continuation_messages ${jsonType}`, ...(d === "sqlite" ? [ `UPDATE conversations SET tool_result_archive = json_extract(data, '$._toolResultArchive'), harness_messages = json_extract(data, '$._harnessMessages'), continuation_messages = json_extract(data, '$._continuationMessages') WHERE json_extract(data, '$._toolResultArchive') IS NOT NULL OR json_extract(data, '$._harnessMessages') IS NOT NULL`, `UPDATE conversations SET data = json_remove(data, '$._toolResultArchive', '$._harnessMessages', '$._continuationMessages')`, ] : [ `UPDATE conversations SET tool_result_archive = data->'_toolResultArchive', harness_messages = data->'_harnessMessages', continuation_messages = data->'_continuationMessages' WHERE data->'_toolResultArchive' IS NOT NULL OR data->'_harnessMessages' IS NOT NULL`, `UPDATE conversations SET data = data - '_toolResultArchive' - '_harnessMessages' - '_continuationMessages'`, ]), ]; }, }, { version: 4, name: "promote_summary_fields_to_columns", up: (d) => { const jsonType = d === "sqlite" ? "TEXT" : "JSONB"; return [ `ALTER TABLE conversations ADD COLUMN parent_conversation_id TEXT`, `ALTER TABLE conversations ADD COLUMN has_pending_approvals INTEGER NOT NULL DEFAULT 0`, `ALTER TABLE conversations ADD COLUMN channel_meta ${jsonType}`, // Backfill from data blob ...(d === "sqlite" ? [ `UPDATE conversations SET parent_conversation_id = json_extract(data, '$.parentConversationId'), has_pending_approvals = CASE WHEN json_array_length(COALESCE(json_extract(data, '$.pendingApprovals'), '[]')) > 0 THEN 1 ELSE 0 END, channel_meta = json_extract(data, '$.channelMeta')`, ] : [ `UPDATE conversations SET parent_conversation_id = data->>'parentConversationId', has_pending_approvals = CASE WHEN jsonb_array_length(COALESCE(data->'pendingApprovals', '[]'::jsonb)) > 0 THEN 1 ELSE 0 END, channel_meta = data->'channelMeta'`, ]), ]; }, }, { version: 5, name: "add_reminder_recurrence", up: (d) => { const jsonType = d === "sqlite" ? "TEXT" : "JSONB"; return [ `ALTER TABLE reminders ADD COLUMN recurrence ${jsonType}`, `ALTER TABLE reminders ADD COLUMN occurrence_count INTEGER NOT NULL DEFAULT 0`, ]; }, }, { version: 6, name: "add_thread_anchor", up: () => [ `ALTER TABLE conversations ADD COLUMN parent_message_id TEXT`, `CREATE INDEX IF NOT EXISTS idx_conversations_thread_anchor ON conversations (parent_conversation_id, parent_message_id) WHERE parent_message_id IS NOT NULL`, ], }, { version: 7, name: "fix_reminder_scheduled_at_precision", // Postgres maps `REAL` to float4 (4 bytes, ~7 digit precision), // which silently rounds millisecond epochs (13 digits) — every // reminder write+read on Postgres returned a different value than // it stored. SQLite's REAL is float8 (15+ digit precision) so it // was always fine there. // // Convert the Postgres column to BIGINT so future writes are exact // (already-stored rounded values aren't recoverable but they were // never correct in the first place). up: (d) => { if (d === "sqlite") return []; return [ `ALTER TABLE reminders ALTER COLUMN scheduled_at TYPE BIGINT USING scheduled_at::bigint`, ]; }, }, { version: 8, name: "conversation_entries", // Append-only conversation log (Phase 3 substrate). Additive: no // existing table or behavior changes. `seq` is a per-conversation // monotonic order assigned by the application (NOT an autoincrement // serial), so the same seq space restarts at 1 for every conversation. // The UNIQUE (conversation_id, seq) constraint backstops the // app-assigned ordering against concurrent writers. up: (d) => { const jsonType = d === "sqlite" ? "TEXT" : "JSONB"; const tsDefault = d === "sqlite" ? "datetime('now')" : "NOW()"; const autoTs = `DEFAULT (${tsDefault})`; return [ `CREATE TABLE IF NOT EXISTS conversation_entries ( seq INTEGER NOT NULL, id TEXT NOT NULL UNIQUE, agent_id TEXT NOT NULL, tenant_id TEXT NOT NULL DEFAULT '__default__', conversation_id TEXT NOT NULL, type TEXT NOT NULL, payload ${jsonType} NOT NULL, created_at TIMESTAMP ${autoTs}, UNIQUE (conversation_id, seq) )`, `CREATE INDEX IF NOT EXISTS idx_conversation_entries_seq ON conversation_entries (conversation_id, seq)`, ]; }, }, ];