use anyhow::Context;
use futures_util::future::BoxFuture;
use std::collections::HashSet;
use crate::db::{Connection, params};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TargetDb {
Core,
Logs,
}
type RustFn = for<'a> fn(&'a Connection) -> BoxFuture<'a, anyhow::Result<()>>;
#[derive(Debug, Clone, Copy)]
pub(crate) enum MigrationBody {
Sql(&'static str),
Rust(RustFn),
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Migration {
pub(crate) id: &'static str,
pub(crate) target: TargetDb,
pub(crate) body: MigrationBody,
}
const BASELINE_CORE_SCHEMA: &str = "\
-- ── Board (tickets, comments, counters) ────────────────────────────────
CREATE TABLE IF NOT EXISTS tickets (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
description TEXT NOT NULL,
phase TEXT NOT NULL DEFAULT 'backlog',
workspace_name TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
prerequisites TEXT NOT NULL DEFAULT '[]',
supersedes TEXT,
superseded_by TEXT,
commit_hash TEXT,
lines_added INTEGER,
lines_removed INTEGER,
reporter TEXT NOT NULL DEFAULT '',
is_archived INTEGER NOT NULL DEFAULT 0,
priority INTEGER NOT NULL DEFAULT 1,
label TEXT NOT NULL DEFAULT 'feat',
reviewed_head TEXT,
reviewed_tree TEXT,
done_at TEXT,
bounce_count INTEGER NOT NULL DEFAULT 0,
last_transition_actor TEXT
);
CREATE TABLE IF NOT EXISTS ticket_comments (
id TEXT PRIMARY KEY,
ticket_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
created_at TEXT NOT NULL,
FOREIGN KEY (ticket_id) REFERENCES tickets(id)
);
CREATE TABLE IF NOT EXISTS ticket_counters (
workspace_name TEXT PRIMARY KEY,
next_id INTEGER NOT NULL DEFAULT 1
);
-- ── Sessions / jobs / agents ───────────────────────────────────────────
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
agent_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_metadata (
agent_id TEXT PRIMARY KEY,
last_activity TEXT NOT NULL,
channel TEXT,
user_name TEXT,
workspace_name TEXT,
role TEXT,
active_models TEXT,
token_length INTEGER,
message_count INTEGER NOT NULL DEFAULT 0,
created_at TEXT,
sleep_ended TEXT,
custom_role TEXT,
custom_identifier TEXT,
launch_stopped TEXT,
reply_to TEXT,
context_block_len INTEGER,
user_activity TEXT,
image_count INTEGER,
provider TEXT,
provider_model TEXT,
chain TEXT,
extract TEXT
);
CREATE TABLE IF NOT EXISTS session_personal_changes (
agent_id TEXT PRIMARY KEY REFERENCES session_metadata(agent_id) ON DELETE CASCADE,
baseline TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY,
kind TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'launched',
task TEXT NOT NULL DEFAULT '',
workspace_name TEXT NOT NULL,
user_name TEXT NOT NULL DEFAULT '',
channel TEXT NOT NULL DEFAULT '',
role TEXT NOT NULL,
retry_count INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
ticket_id TEXT REFERENCES tickets(id),
caller_agent_id TEXT,
mode TEXT,
exec_dir TEXT,
custom_launch TEXT,
chain TEXT,
extract TEXT
);
CREATE TABLE IF NOT EXISTS agents (
job_id TEXT REFERENCES jobs(id) ON DELETE CASCADE,
agent_id TEXT NOT NULL,
kind TEXT NOT NULL,
idx INTEGER,
status TEXT NOT NULL DEFAULT 'launched',
outcome TEXT,
task TEXT NOT NULL,
PRIMARY KEY (job_id, agent_id)
);
CREATE TABLE IF NOT EXISTS pending_jobs (
id TEXT PRIMARY KEY,
target_agent_id TEXT NOT NULL,
envelope TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS research_jobs (
id TEXT PRIMARY KEY REFERENCES jobs(id) ON DELETE CASCADE,
state TEXT NOT NULL
);
-- ── Workspaces / editor ───────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS workspaces (
name TEXT PRIMARY KEY,
path TEXT NOT NULL UNIQUE,
status TEXT NOT NULL DEFAULT 'pending',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
maintenance INTEGER NOT NULL DEFAULT 0,
paused INTEGER NOT NULL DEFAULT 1,
maintainer_debounce_mins INTEGER NOT NULL DEFAULT 5,
maintainer_last_run_at TEXT,
maintainer_recommendations TEXT,
diagnostics TEXT,
diagnostics_generation INTEGER NOT NULL DEFAULT 0,
notes TEXT NOT NULL DEFAULT '',
last_analyzed_commit TEXT,
discovery_generation INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS workspace_contexts (
workspace_name TEXT NOT NULL REFERENCES workspaces(name) ON DELETE CASCADE,
role TEXT,
content TEXT NOT NULL,
created_at TEXT NOT NULL,
UNIQUE(workspace_name, role)
);
CREATE TABLE IF NOT EXISTS editor_tabs (
workspace_name TEXT NOT NULL REFERENCES workspaces(name) ON DELETE CASCADE,
file_path TEXT NOT NULL,
tab_order INTEGER NOT NULL DEFAULT 0,
is_active INTEGER NOT NULL DEFAULT 0,
is_dirty INTEGER NOT NULL DEFAULT 0,
dirty_content TEXT,
PRIMARY KEY (workspace_name, file_path)
);
-- ── Users / channels ───────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS users (
name TEXT PRIMARY KEY,
selected_workspace TEXT,
image_gen_model TEXT,
video_model TEXT,
granted_tools TEXT,
memory_inventory_day TEXT
);
CREATE TABLE IF NOT EXISTS user_channels (
user_name TEXT NOT NULL REFERENCES users(name),
channel TEXT NOT NULL,
identifier TEXT NOT NULL,
reply_target TEXT,
UNIQUE(channel, identifier)
);
CREATE TABLE IF NOT EXISTS guest_reports (
user_name TEXT NOT NULL,
day TEXT NOT NULL,
digest TEXT NOT NULL,
PRIMARY KEY (user_name, day, digest)
);
-- ── Config ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS config_kv (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS config_model_routing (
model TEXT PRIMARY KEY,
provider_order TEXT,
allow_fallbacks INTEGER
);
-- ── Chat history ───────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS chat_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
message_id TEXT NOT NULL UNIQUE,
user_name TEXT NOT NULL,
direction TEXT NOT NULL,
content TEXT NOT NULL,
agent_role TEXT,
broadcast_id TEXT,
workspace TEXT NOT NULL,
timestamp TEXT,
reply_author TEXT,
reply_snippet TEXT
);
-- ── Telegram intake ────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS telegram_intake (
account_id TEXT NOT NULL,
update_id INTEGER NOT NULL,
state TEXT NOT NULL,
payload TEXT,
created_at TEXT NOT NULL,
decided_at TEXT,
claimed_by TEXT,
PRIMARY KEY (account_id, update_id)
);
CREATE TABLE IF NOT EXISTS telegram_bursts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account_id TEXT NOT NULL,
user_name TEXT NOT NULL,
reply_target TEXT NOT NULL,
parts INTEGER NOT NULL,
released_by TEXT NOT NULL,
released_at TEXT NOT NULL,
part_times TEXT NOT NULL
);
-- ── Ticket chronicle / automations ─────────────────────────────────────
CREATE TABLE IF NOT EXISTS ticket_chronicle (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ticket_id TEXT NOT NULL,
workspace_name TEXT NOT NULL,
source_phase TEXT NOT NULL,
target_phase TEXT NOT NULL,
at TEXT NOT NULL,
actor TEXT
);
CREATE TABLE IF NOT EXISTS automations (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
user_name TEXT NOT NULL,
kind TEXT NOT NULL,
text TEXT NOT NULL,
fire_at TEXT,
interval_seconds INTEGER,
next_fire_at TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
created_at TEXT NOT NULL,
trigger TEXT,
role TEXT,
identifier TEXT,
workspace TEXT,
retry_at TEXT,
unfinished_attempts INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS send_outcomes (
id TEXT PRIMARY KEY,
state TEXT NOT NULL,
answer TEXT,
reason TEXT,
shape TEXT,
chain_steps INTEGER,
created_at TEXT NOT NULL,
finished_at TEXT
);
CREATE TABLE IF NOT EXISTS custom_roles (
name TEXT PRIMARY KEY,
prompt TEXT NOT NULL,
tools TEXT NOT NULL,
behavior TEXT NOT NULL,
created_at TEXT NOT NULL
);
-- ── Indexes ────────────────────────────────────────────────────────────
-- Only the indexes a product query's plan reaches, plus the uniqueness ones.
-- The audit of what is kept and what is deliberately absent is this
-- constant's doc comment.
CREATE INDEX IF NOT EXISTS idx_ticket_comments_ticket_id ON ticket_comments(ticket_id);
CREATE INDEX IF NOT EXISTS idx_sessions_agent_id ON sessions(agent_id, id);
CREATE INDEX IF NOT EXISTS idx_jobs_kind_status ON jobs(kind, status);
CREATE UNIQUE INDEX IF NOT EXISTS idx_agents_anchor ON agents(agent_id) WHERE job_id IS NULL;
CREATE INDEX IF NOT EXISTS idx_pending_jobs_agent_created ON pending_jobs(target_agent_id, created_at);
CREATE UNIQUE INDEX IF NOT EXISTS workspace_contexts_null_role ON workspace_contexts(workspace_name) WHERE role IS NULL;
CREATE INDEX IF NOT EXISTS idx_chat_history_user_ws_id ON chat_history(user_name, workspace, id);
CREATE INDEX IF NOT EXISTS idx_tickets_title_fts ON tickets USING fts (title) WITH (tokenizer = 'ngram');
CREATE INDEX IF NOT EXISTS idx_tickets_board_active ON tickets (is_archived, priority ASC, created_at DESC);
CREATE UNIQUE INDEX IF NOT EXISTS idx_jobs_phase_ticket ON jobs(kind, ticket_id) WHERE ticket_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_ticket_chronicle_ws_id ON ticket_chronicle(workspace_name, id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_ticket_chronicle_dedup ON ticket_chronicle(ticket_id, workspace_name, source_phase, target_phase, at);
CREATE INDEX IF NOT EXISTS idx_automations_due ON automations(status, next_fire_at);
CREATE INDEX IF NOT EXISTS idx_tickets_workspace_phase ON tickets (workspace_name, phase, is_archived, priority ASC, created_at DESC);";
const BASELINE_LOGS_SCHEMA: &str = "\
-- ── Logs / tool calls / LLM requests ───────────────────────────────────
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
level TEXT NOT NULL,
target TEXT NOT NULL,
message TEXT NOT NULL,
fields TEXT NOT NULL DEFAULT '{}',
agent_id TEXT NOT NULL DEFAULT '',
agent_role TEXT NOT NULL DEFAULT '',
workspace TEXT NOT NULL DEFAULT '',
ticket TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS tool_calls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
agent_id TEXT NOT NULL,
role TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'agent',
tool_name TEXT NOT NULL,
arguments TEXT NOT NULL DEFAULT '{}',
duration_ms INTEGER NOT NULL DEFAULT 0,
success INTEGER NOT NULL DEFAULT 1,
error_message TEXT,
workspace TEXT NOT NULL DEFAULT '',
recorded_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS llm_requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
recorded_at TEXT NOT NULL,
purpose TEXT NOT NULL,
agent_id TEXT NOT NULL DEFAULT '',
role TEXT NOT NULL DEFAULT '',
workspace TEXT NOT NULL DEFAULT '',
ticket_id TEXT,
model TEXT NOT NULL,
routing TEXT NOT NULL DEFAULT '',
input_tokens INTEGER,
output_tokens INTEGER,
cached_input_tokens INTEGER,
cache_miss_tokens INTEGER,
duration_ms INTEGER NOT NULL,
retry_attempts INTEGER NOT NULL,
finish_reason TEXT,
failure_class TEXT,
success INTEGER NOT NULL DEFAULT 1,
cost REAL,
cost_details TEXT,
upstream_provider TEXT,
system_fingerprint TEXT
);
-- ── Grep telemetry ─────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS grep_telemetry (
id INTEGER PRIMARY KEY AUTOINCREMENT,
recorded_at TEXT NOT NULL,
command TEXT NOT NULL,
served INTEGER NOT NULL DEFAULT 0,
reason TEXT NOT NULL DEFAULT '',
recursive INTEGER NOT NULL DEFAULT 0,
piped INTEGER NOT NULL DEFAULT 0,
operand_count INTEGER NOT NULL DEFAULT 0,
flags TEXT NOT NULL DEFAULT '',
mode TEXT NOT NULL DEFAULT '',
workspace TEXT NOT NULL DEFAULT '',
grep_count INTEGER NOT NULL DEFAULT 0,
served_count INTEGER NOT NULL DEFAULT 0,
skipped_count INTEGER NOT NULL DEFAULT 0,
duration_ms INTEGER,
exit_code INTEGER
);
-- ── Indexes ────────────────────────────────────────────────────────────
-- Only the indexes a product query's plan reaches; the audit of what is
-- kept and what is deliberately absent is this constant's doc comment.
CREATE INDEX IF NOT EXISTS idx_logs_level ON logs(level);
CREATE INDEX IF NOT EXISTS idx_tool_calls_recorded_at ON tool_calls(recorded_at);
CREATE INDEX IF NOT EXISTS idx_tool_calls_error_message ON tool_calls(error_message);
CREATE INDEX IF NOT EXISTS idx_llm_requests_recorded_at ON llm_requests(recorded_at);
CREATE INDEX IF NOT EXISTS idx_grep_telemetry_recorded_at ON grep_telemetry(recorded_at);
-- ── Per-attempt LLM failure trail ──────────────────────────────────────
CREATE TABLE IF NOT EXISTS llm_failures (
id INTEGER PRIMARY KEY AUTOINCREMENT,
operation_id TEXT NOT NULL,
recorded_at TEXT NOT NULL,
purpose TEXT NOT NULL,
agent_id TEXT NOT NULL DEFAULT '',
role TEXT NOT NULL DEFAULT '',
workspace TEXT NOT NULL DEFAULT '',
ticket_id TEXT,
model TEXT NOT NULL,
routing TEXT NOT NULL DEFAULT '',
attempt INTEGER NOT NULL,
attempt_duration_ms INTEGER,
failure_class TEXT NOT NULL,
finish_reason TEXT,
retry_after_ms INTEGER,
error_chain TEXT NOT NULL DEFAULT ''
);";
const DROP_DEEPSEEK_V41_FLASH_1017_ROUTING: &str =
"DELETE FROM config_model_routing WHERE model = 'deepseek/deepseek-v4.1-flash-1017';";
const GUEST_REPORTS_TABLE: &str = "CREATE TABLE IF NOT EXISTS guest_reports (
user_name TEXT NOT NULL,
day TEXT NOT NULL,
digest TEXT NOT NULL,
PRIMARY KEY (user_name, day, digest)
);";
const SEND_OUTCOMES_TABLE: &str = "CREATE TABLE IF NOT EXISTS send_outcomes (
id TEXT PRIMARY KEY,
state TEXT NOT NULL,
answer TEXT,
reason TEXT,
shape TEXT,
chain_steps INTEGER,
created_at TEXT NOT NULL,
finished_at TEXT
);";
pub(crate) const MIGRATIONS: &[Migration] = &[
Migration {
id: "24",
target: TargetDb::Core,
body: MigrationBody::Sql(BASELINE_CORE_SCHEMA),
},
Migration {
id: "26",
target: TargetDb::Logs,
body: MigrationBody::Sql(BASELINE_LOGS_SCHEMA),
},
Migration {
id: "69",
target: TargetDb::Core,
body: MigrationBody::Rust(seed_audio_transcription_disabled),
},
Migration {
id: "79",
target: TargetDb::Core,
body: MigrationBody::Sql(GUEST_REPORTS_TABLE),
},
Migration {
id: "80",
target: TargetDb::Core,
body: MigrationBody::Rust(add_session_metadata_provider),
},
Migration {
id: "81",
target: TargetDb::Core,
body: MigrationBody::Sql(DROP_DEEPSEEK_V41_FLASH_1017_ROUTING),
},
Migration {
id: "82",
target: TargetDb::Core,
body: MigrationBody::Rust(set_media_model_lists),
},
Migration {
id: "83",
target: TargetDb::Core,
body: MigrationBody::Rust(set_media_model_lists),
},
Migration {
id: "84",
target: TargetDb::Core,
body: MigrationBody::Rust(add_chain_columns),
},
Migration {
id: "85",
target: TargetDb::Core,
body: MigrationBody::Rust(add_extract_columns),
},
Migration {
id: "86",
target: TargetDb::Core,
body: MigrationBody::Sql(SEND_OUTCOMES_TABLE),
},
];
pub(crate) async fn run_migrations(conn: &Connection, db: TargetDb) -> anyhow::Result<()> {
run_catalog(conn, db, MIGRATIONS).await
}
pub(crate) const MIGRATIONS_TABLE: &str = "schema_migrations";
pub(crate) async fn has_pending(conn: &Connection, db: TargetDb) -> anyhow::Result<bool> {
let applied = applied_ids(conn).await?;
Ok(MIGRATIONS
.iter()
.any(|migration| migration.target == db && !applied.contains(migration.id)))
}
async fn applied_ids(conn: &Connection) -> anyhow::Result<HashSet<String>> {
Ok(conn
.query(&format!("SELECT id FROM {MIGRATIONS_TABLE}"), ())
.await
.context("Failed to read applied migrations")?
.into_iter()
.filter_map(|row| row.get::<String>(0).ok())
.collect())
}
async fn run_catalog(conn: &Connection, db: TargetDb, catalog: &[Migration]) -> anyhow::Result<()> {
conn.execute(
&format!(
"CREATE TABLE IF NOT EXISTS {MIGRATIONS_TABLE} (\
id TEXT PRIMARY KEY,\
applied_at TEXT NOT NULL\
)"
),
(),
)
.await
.context("Failed to create schema_migrations tracking table")?;
let applied = applied_ids(conn).await?;
for migration in catalog {
if migration.target != db {
continue;
}
if applied.contains(migration.id) {
continue;
}
match migration.body {
MigrationBody::Sql(sql) => {
let tx = conn.begin_tx().await.with_context(|| {
format!("Migration '{}': failed to begin transaction", migration.id)
})?;
tx.execute_batch(sql)
.await
.with_context(|| format!("Migration '{}' failed", migration.id))?;
tx.execute(
&format!("INSERT INTO {MIGRATIONS_TABLE} (id, applied_at) VALUES (?1, ?2)"),
params![migration.id, crate::db::now()],
)
.await
.with_context(|| {
format!("Migration '{}': failed to record as applied", migration.id)
})?;
tx.commit()
.await
.with_context(|| format!("Migration '{}': failed to commit", migration.id))?;
}
MigrationBody::Rust(run) => {
run(conn)
.await
.with_context(|| format!("Migration '{}' failed", migration.id))?;
conn.execute(
&format!("INSERT INTO {MIGRATIONS_TABLE} (id, applied_at) VALUES (?1, ?2)"),
params![migration.id, crate::db::now()],
)
.await
.with_context(|| {
format!("Migration '{}': failed to record as applied", migration.id)
})?;
}
}
}
Ok(())
}
async fn column_exists(conn: &Connection, table: &str, column: &str) -> anyhow::Result<bool> {
let found = conn
.query(&format!("PRAGMA table_info({table})"), ())
.await
.with_context(|| format!("Failed to probe {table}.{column}"))?
.into_iter()
.any(|row| row.get::<String>(1).ok().as_deref() == Some(column));
Ok(found)
}
async fn add_column_if_missing(
conn: &Connection,
table: &str,
column: &str,
ty: &str,
) -> anyhow::Result<()> {
if !column_exists(conn, table, column).await? {
conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column} {ty}"), ())
.await
.with_context(|| format!("Failed to add {table}.{column}"))?;
}
Ok(())
}
fn add_chain_columns(conn: &Connection) -> BoxFuture<'_, anyhow::Result<()>> {
Box::pin(run_add_chain_columns(conn))
}
async fn run_add_chain_columns(conn: &Connection) -> anyhow::Result<()> {
add_column_if_missing(conn, "jobs", "chain", "TEXT").await?;
add_column_if_missing(conn, "session_metadata", "chain", "TEXT").await
}
fn add_extract_columns(conn: &Connection) -> BoxFuture<'_, anyhow::Result<()>> {
Box::pin(run_add_extract_columns(conn))
}
async fn run_add_extract_columns(conn: &Connection) -> anyhow::Result<()> {
add_column_if_missing(conn, "jobs", "extract", "TEXT").await?;
add_column_if_missing(conn, "session_metadata", "extract", "TEXT").await
}
fn add_session_metadata_provider(conn: &Connection) -> BoxFuture<'_, anyhow::Result<()>> {
Box::pin(run_add_session_metadata_provider(conn))
}
async fn run_add_session_metadata_provider(conn: &Connection) -> anyhow::Result<()> {
add_column_if_missing(conn, "session_metadata", "provider", "TEXT").await?;
add_column_if_missing(conn, "session_metadata", "provider_model", "TEXT").await
}
fn seed_audio_transcription_disabled(conn: &Connection) -> BoxFuture<'_, anyhow::Result<()>> {
Box::pin(run_seed_audio_transcription_disabled(conn))
}
async fn run_seed_audio_transcription_disabled(conn: &Connection) -> anyhow::Result<()> {
conn.execute(
"INSERT INTO config_kv (key, value) VALUES (?1, 'false') ON CONFLICT (key) DO NOTHING",
params![crate::config::CONFIG_KEY_AUDIO_TRANSCRIPTION_USE_LOCAL],
)
.await?;
Ok(())
}
async fn run_set_media_model_lists(conn: &Connection) -> anyhow::Result<()> {
for (key, list) in [
(
crate::config::CONFIG_KEY_IMAGE_GEN_MODELS,
crate::config::SHIPPED_IMAGE_GEN_MODELS,
),
(
crate::config::CONFIG_KEY_VIDEO_MODELS,
crate::config::SHIPPED_VIDEO_MODELS,
),
] {
conn.execute(
"INSERT INTO config_kv (key, value) VALUES (?1, ?2) \
ON CONFLICT (key) DO UPDATE SET value = excluded.value",
params![key, list],
)
.await?;
}
Ok(())
}
fn set_media_model_lists(conn: &Connection) -> BoxFuture<'_, anyhow::Result<()>> {
Box::pin(run_set_media_model_lists(conn))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::db::Connection;
async fn recorded_ids(conn: &Connection) -> Vec<String> {
conn.query("SELECT id FROM schema_migrations", ())
.await
.expect("read schema_migrations")
.into_iter()
.map(|row| row.get::<String>(0).expect("id"))
.collect()
}
async fn config_kv_rows(conn: &Connection) -> Vec<(String, String)> {
let mut rows: Vec<(String, String)> = conn
.query("SELECT key, value FROM config_kv", ())
.await
.expect("read config_kv")
.into_iter()
.map(|row| {
(
row.get::<String>(0).expect("key"),
row.get::<String>(1).expect("value"),
)
})
.collect();
rows.sort();
rows
}
fn normalize_ddl(sql: &str) -> String {
let mut out = String::new();
let mut in_string = false;
let mut chars = sql.chars().peekable();
while let Some(c) = chars.next() {
if in_string {
if c == '\'' {
in_string = false;
}
out.push(c);
} else if c == '\'' {
in_string = true;
out.push(c);
} else if c == '-' && chars.peek() == Some(&'-') {
for c2 in chars.by_ref() {
if c2 == '\n' {
break;
}
}
} else if !c.is_whitespace() {
out.push(c);
}
}
out
}
async fn index_defs(conn: &Connection) -> std::collections::BTreeMap<String, String> {
conn.query(
"SELECT name, sql FROM sqlite_master \
WHERE type = 'index' AND name NOT LIKE 'sqlite_autoindex_%' \
AND name NOT LIKE '__turso_internal_%' AND name NOT LIKE 'turso_cdc%'",
(),
)
.await
.expect("read index definitions")
.into_iter()
.map(|row| {
let name = row.get::<String>(0).expect("index name");
let sql = row
.get::<Option<String>>(1)
.expect("index sql")
.unwrap_or_default();
(name, normalize_ddl(&sql))
})
.collect()
}
async fn table_names(conn: &Connection) -> Vec<String> {
conn.query(
"SELECT name FROM sqlite_master \
WHERE type = 'table' AND name NOT LIKE 'sqlite_%' \
AND name NOT LIKE '__turso_internal_%' AND name NOT LIKE 'turso_cdc%'",
(),
)
.await
.expect("read tables")
.into_iter()
.map(|row| row.get::<String>(0).expect("table name"))
.collect()
}
const EXPECTED_CORE_TABLE_COLUMNS: &[(&str, &[&str])] = &[
(
"agents",
&[
"job_id", "agent_id", "kind", "idx", "status", "outcome", "task",
],
),
(
"automations",
&[
"id",
"session_id",
"user_name",
"kind",
"text",
"fire_at",
"interval_seconds",
"next_fire_at",
"status",
"created_at",
"trigger",
"role",
"identifier",
"workspace",
"retry_at",
"unfinished_attempts",
],
),
(
"chat_history",
&[
"id",
"message_id",
"user_name",
"direction",
"content",
"agent_role",
"broadcast_id",
"workspace",
"timestamp",
"reply_author",
"reply_snippet",
],
),
("config_kv", &["key", "value"]),
(
"config_model_routing",
&["model", "provider_order", "allow_fallbacks"],
),
(
"custom_roles",
&["name", "prompt", "tools", "behavior", "created_at"],
),
(
"editor_tabs",
&[
"workspace_name",
"file_path",
"tab_order",
"is_active",
"is_dirty",
"dirty_content",
],
),
("guest_reports", &["user_name", "day", "digest"]),
(
"jobs",
&[
"id",
"kind",
"status",
"task",
"workspace_name",
"user_name",
"channel",
"role",
"retry_count",
"created_at",
"updated_at",
"ticket_id",
"caller_agent_id",
"mode",
"exec_dir",
"custom_launch",
"chain",
"extract",
],
),
(
"pending_jobs",
&["id", "target_agent_id", "envelope", "created_at"],
),
("research_jobs", &["id", "state"]),
("schema_migrations", &["id", "applied_at"]),
(
"send_outcomes",
&[
"id",
"state",
"answer",
"reason",
"shape",
"chain_steps",
"created_at",
"finished_at",
],
),
(
"session_metadata",
&[
"agent_id",
"last_activity",
"channel",
"user_name",
"workspace_name",
"role",
"active_models",
"token_length",
"message_count",
"created_at",
"sleep_ended",
"custom_role",
"custom_identifier",
"launch_stopped",
"reply_to",
"chain",
"context_block_len",
"user_activity",
"image_count",
"provider",
"provider_model",
"extract",
],
),
("session_personal_changes", &["agent_id", "baseline"]),
(
"sessions",
&["id", "agent_id", "role", "content", "created_at"],
),
(
"telegram_bursts",
&[
"id",
"account_id",
"user_name",
"reply_target",
"parts",
"released_by",
"released_at",
"part_times",
],
),
(
"telegram_intake",
&[
"account_id",
"update_id",
"state",
"payload",
"created_at",
"decided_at",
"claimed_by",
],
),
(
"ticket_chronicle",
&[
"id",
"ticket_id",
"workspace_name",
"source_phase",
"target_phase",
"at",
"actor",
],
),
(
"ticket_comments",
&["id", "ticket_id", "role", "content", "created_at"],
),
("ticket_counters", &["workspace_name", "next_id"]),
(
"tickets",
&[
"id",
"title",
"description",
"phase",
"workspace_name",
"created_at",
"updated_at",
"prerequisites",
"supersedes",
"superseded_by",
"commit_hash",
"lines_added",
"lines_removed",
"reporter",
"is_archived",
"priority",
"label",
"reviewed_head",
"reviewed_tree",
"done_at",
"bounce_count",
"last_transition_actor",
],
),
(
"user_channels",
&["user_name", "channel", "identifier", "reply_target"],
),
(
"users",
&[
"name",
"selected_workspace",
"image_gen_model",
"video_model",
"granted_tools",
"memory_inventory_day",
],
),
(
"workspace_contexts",
&["workspace_name", "role", "content", "created_at"],
),
(
"workspaces",
&[
"name",
"path",
"status",
"created_at",
"updated_at",
"maintenance",
"paused",
"maintainer_debounce_mins",
"maintainer_last_run_at",
"maintainer_recommendations",
"diagnostics",
"diagnostics_generation",
"notes",
"last_analyzed_commit",
"discovery_generation",
],
),
];
const EXPECTED_CORE_INDEXES: &[&str] = &[
"idx_ticket_comments_ticket_id",
"idx_sessions_agent_id",
"idx_jobs_kind_status",
"idx_agents_anchor",
"idx_pending_jobs_agent_created",
"workspace_contexts_null_role",
"idx_chat_history_user_ws_id",
"idx_tickets_title_fts",
"idx_tickets_board_active",
"idx_jobs_phase_ticket",
"idx_ticket_chronicle_ws_id",
"idx_ticket_chronicle_dedup",
"idx_automations_due",
"idx_tickets_workspace_phase",
];
const EXPECTED_LOGS_TABLE_COLUMNS: &[(&str, &[&str])] = &[
(
"grep_telemetry",
&[
"id",
"recorded_at",
"command",
"served",
"reason",
"recursive",
"piped",
"operand_count",
"flags",
"mode",
"workspace",
"grep_count",
"served_count",
"skipped_count",
"duration_ms",
"exit_code",
],
),
(
"llm_failures",
&[
"id",
"operation_id",
"recorded_at",
"purpose",
"agent_id",
"role",
"workspace",
"ticket_id",
"model",
"routing",
"attempt",
"attempt_duration_ms",
"failure_class",
"finish_reason",
"retry_after_ms",
"error_chain",
],
),
(
"llm_requests",
&[
"id",
"recorded_at",
"purpose",
"agent_id",
"role",
"workspace",
"ticket_id",
"model",
"routing",
"input_tokens",
"output_tokens",
"cached_input_tokens",
"cache_miss_tokens",
"duration_ms",
"retry_attempts",
"finish_reason",
"failure_class",
"success",
"cost",
"cost_details",
"upstream_provider",
"system_fingerprint",
],
),
(
"logs",
&[
"id",
"timestamp",
"level",
"target",
"message",
"fields",
"agent_id",
"agent_role",
"workspace",
"ticket",
],
),
("schema_migrations", &["id", "applied_at"]),
(
"tool_calls",
&[
"id",
"agent_id",
"role",
"source",
"tool_name",
"arguments",
"duration_ms",
"success",
"error_message",
"workspace",
"recorded_at",
],
),
];
const EXPECTED_LOGS_INDEXES: &[&str] = &[
"idx_logs_level",
"idx_tool_calls_recorded_at",
"idx_tool_calls_error_message",
"idx_llm_requests_recorded_at",
"idx_grep_telemetry_recorded_at",
];
async fn assert_schema_matches(
conn: &Connection,
expected_tables: &[(&str, &[&str])],
expected_indexes: &[&str],
context: &str,
) {
let actual_names: Vec<String> = table_names(conn).await;
let actual_set: std::collections::HashSet<&str> =
actual_names.iter().map(String::as_str).collect();
let expected_set: std::collections::HashSet<&str> =
expected_tables.iter().map(|(n, _)| *n).collect();
let missing: Vec<&str> = expected_set.difference(&actual_set).copied().collect();
let extra: Vec<&str> = actual_set.difference(&expected_set).copied().collect();
assert!(missing.is_empty(), "{context}: missing tables {missing:?}");
assert!(extra.is_empty(), "{context}: unexpected tables {extra:?}");
for (table, expected_cols) in expected_tables {
let actual = column_shapes(conn, table).await;
let actual_set: std::collections::HashSet<&str> =
actual.keys().map(String::as_str).collect();
let expected_set: std::collections::HashSet<&str> =
expected_cols.iter().copied().collect();
let miss: Vec<&str> = expected_set.difference(&actual_set).copied().collect();
let ex: Vec<&str> = actual_set.difference(&expected_set).copied().collect();
assert!(
miss.is_empty(),
"{context}: table '{table}' missing columns {miss:?}"
);
assert!(
ex.is_empty(),
"{context}: table '{table}' has extra columns {ex:?}"
);
}
assert_index_set(conn, expected_indexes, context).await;
}
async fn assert_index_set(conn: &Connection, expected: &[&str], context: &str) {
let names: Vec<String> = index_defs(conn).await.into_keys().collect();
let actual: std::collections::HashSet<&str> = names.iter().map(String::as_str).collect();
let expected: std::collections::HashSet<&str> = expected.iter().copied().collect();
let missing: Vec<&str> = expected.difference(&actual).copied().collect();
let extra: Vec<&str> = actual.difference(&expected).copied().collect();
assert!(missing.is_empty(), "{context}: missing indexes {missing:?}");
assert!(extra.is_empty(), "{context}: unexpected indexes {extra:?}");
}
#[tokio::test]
async fn fresh_install_converges_to_expected_shape() {
let tmp = tempfile::TempDir::new().unwrap();
let conn = crate::db::open_consolidated_store(tmp.path())
.await
.expect("fresh consolidated store");
assert_schema_matches(
&conn,
EXPECTED_CORE_TABLE_COLUMNS,
EXPECTED_CORE_INDEXES,
"fresh core",
)
.await;
let mut applied = recorded_ids(&conn).await;
applied.sort();
assert_eq!(
applied,
["24", "69", "79", "80", "81", "82", "83", "84", "85", "86"].map(String::from),
"fresh core applies the baseline, the 69 seed and the eight upgrade entries exactly"
);
}
#[tokio::test]
async fn fresh_logs_install_converges_to_expected_shape() {
let tmp = tempfile::TempDir::new().unwrap();
let root = tmp.path();
let conn = crate::db::open_with_schema(
&crate::db::store_db_path(root, crate::db::LOG_DB_NAME),
"",
)
.await
.expect("open logs");
run_migrations(&conn, TargetDb::Logs)
.await
.expect("run logs catalog");
assert_schema_matches(
&conn,
EXPECTED_LOGS_TABLE_COLUMNS,
EXPECTED_LOGS_INDEXES,
"fresh logs",
)
.await;
let mut applied = recorded_ids(&conn).await;
applied.sort();
assert_eq!(
applied,
vec!["26".to_string()],
"fresh logs applies the baseline exactly"
);
}
async fn model_routing_orders(conn: &Connection) -> Vec<(String, String)> {
conn.query(
"SELECT model, provider_order FROM config_model_routing ORDER BY model",
(),
)
.await
.expect("read config_model_routing")
.into_iter()
.map(|row| {
(
row.get::<String>(0).expect("model"),
row.get::<String>(1).expect("provider_order"),
)
})
.collect()
}
#[tokio::test]
async fn drop_deepseek_v41_flash_1017_routing_deletes_only_that_model() {
let tmp = tempfile::TempDir::new().unwrap();
let conn = crate::db::open_with_schema(
&crate::db::store_db_path(tmp.path(), crate::db::CONSOLIDATED_DB_NAME),
"",
)
.await
.expect("open core");
run_catalog(&conn, TargetDb::Core, &MIGRATIONS[..1])
.await
.expect("baseline catalog");
for (model, order) in [
("deepseek/deepseek-v4.1-flash-1017", "deepinfra/fp8/flex"),
("deepseek/deepseek-v4.1-flash", "deepseek"),
("deepseek/deepseek-v4.1-flash-1017-preview", "deepseek"),
("qwen/qwen3.8-flash", "GMICloud"),
] {
conn.execute(
"INSERT INTO config_model_routing (model, provider_order) VALUES (?1, ?2)",
params![model, order],
)
.await
.unwrap();
}
let entry = MIGRATIONS
.iter()
.find(|m| m.id == "81")
.expect("entry 81 in the catalog");
run_catalog(&conn, TargetDb::Core, std::slice::from_ref(entry))
.await
.expect("apply entry 81");
let remaining = model_routing_orders(&conn).await;
assert_eq!(
remaining,
vec![
(
"deepseek/deepseek-v4.1-flash".to_string(),
"deepseek".to_string()
),
(
"deepseek/deepseek-v4.1-flash-1017-preview".to_string(),
"deepseek".to_string()
),
("qwen/qwen3.8-flash".to_string(), "GMICloud".to_string()),
],
"only the exact model id may be dropped — prefix and family neighbours keep their row"
);
conn.execute(DROP_DEEPSEEK_V41_FLASH_1017_ROUTING, ())
.await
.expect("re-run entry 81 body");
assert_eq!(model_routing_orders(&conn).await, remaining);
}
#[tokio::test]
async fn has_pending_reads_the_catalog_against_the_ledger() {
let tmp = tempfile::TempDir::new().unwrap();
let conn = crate::db::open_with_schema(
&crate::db::store_db_path(tmp.path(), crate::db::CONSOLIDATED_DB_NAME),
"",
)
.await
.expect("open core");
run_migrations(&conn, TargetDb::Core).await.unwrap();
assert!(
!has_pending(&conn, TargetDb::Core).await.unwrap(),
"a store at the catalog's head has nothing pending"
);
let newest = MIGRATIONS
.iter()
.rev()
.find(|migration| migration.target == TargetDb::Core)
.expect("the core catalog has entries")
.id;
conn.execute(
&format!("DELETE FROM schema_migrations WHERE id = '{newest}'"),
(),
)
.await
.unwrap();
assert!(
has_pending(&conn, TargetDb::Core).await.unwrap(),
"an entry the ledger no longer records is pending again"
);
}
const V0_10_0_CORE_SCHEMA: &str = "\
-- ── Board (tickets, comments, counters) ────────────────────────────────
CREATE TABLE IF NOT EXISTS tickets (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
description TEXT NOT NULL,
phase TEXT NOT NULL DEFAULT 'backlog',
workspace_name TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
prerequisites TEXT NOT NULL DEFAULT '[]',
supersedes TEXT,
superseded_by TEXT,
commit_hash TEXT,
lines_added INTEGER,
lines_removed INTEGER,
reporter TEXT NOT NULL DEFAULT '',
is_archived INTEGER NOT NULL DEFAULT 0,
priority INTEGER NOT NULL DEFAULT 1,
label TEXT NOT NULL DEFAULT 'feat',
reviewed_head TEXT,
reviewed_tree TEXT,
done_at TEXT,
bounce_count INTEGER NOT NULL DEFAULT 0,
last_transition_actor TEXT
);
CREATE TABLE IF NOT EXISTS ticket_comments (
id TEXT PRIMARY KEY,
ticket_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
created_at TEXT NOT NULL,
FOREIGN KEY (ticket_id) REFERENCES tickets(id)
);
CREATE TABLE IF NOT EXISTS ticket_counters (
workspace_name TEXT PRIMARY KEY,
next_id INTEGER NOT NULL DEFAULT 1
);
-- ── Sessions / jobs / agents ───────────────────────────────────────────
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
agent_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_metadata (
agent_id TEXT PRIMARY KEY,
last_activity TEXT NOT NULL,
channel TEXT,
user_name TEXT,
workspace_name TEXT,
role TEXT,
active_models TEXT,
token_length INTEGER,
message_count INTEGER NOT NULL DEFAULT 0,
created_at TEXT,
sleep_ended TEXT,
custom_role TEXT,
custom_identifier TEXT,
launch_stopped TEXT,
reply_to TEXT,
context_block_len INTEGER,
user_activity TEXT,
image_count INTEGER
);
CREATE TABLE IF NOT EXISTS session_personal_changes (
agent_id TEXT PRIMARY KEY REFERENCES session_metadata(agent_id) ON DELETE CASCADE,
baseline TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY,
kind TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'launched',
task TEXT NOT NULL DEFAULT '',
workspace_name TEXT NOT NULL,
user_name TEXT NOT NULL DEFAULT '',
channel TEXT NOT NULL DEFAULT '',
role TEXT NOT NULL,
retry_count INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
ticket_id TEXT REFERENCES tickets(id),
caller_agent_id TEXT,
mode TEXT,
exec_dir TEXT,
custom_launch TEXT
);
CREATE TABLE IF NOT EXISTS agents (
job_id TEXT REFERENCES jobs(id) ON DELETE CASCADE,
agent_id TEXT NOT NULL,
kind TEXT NOT NULL,
idx INTEGER,
status TEXT NOT NULL DEFAULT 'launched',
outcome TEXT,
task TEXT NOT NULL,
PRIMARY KEY (job_id, agent_id)
);
CREATE TABLE IF NOT EXISTS pending_jobs (
id TEXT PRIMARY KEY,
target_agent_id TEXT NOT NULL,
envelope TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS research_jobs (
id TEXT PRIMARY KEY REFERENCES jobs(id) ON DELETE CASCADE,
state TEXT NOT NULL
);
-- ── Workspaces / editor ───────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS workspaces (
name TEXT PRIMARY KEY,
path TEXT NOT NULL UNIQUE,
status TEXT NOT NULL DEFAULT 'pending',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
maintenance INTEGER NOT NULL DEFAULT 0,
paused INTEGER NOT NULL DEFAULT 1,
maintainer_debounce_mins INTEGER NOT NULL DEFAULT 5,
maintainer_last_run_at TEXT,
maintainer_recommendations TEXT,
diagnostics TEXT,
diagnostics_generation INTEGER NOT NULL DEFAULT 0,
notes TEXT NOT NULL DEFAULT '',
last_analyzed_commit TEXT,
discovery_generation INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS workspace_contexts (
workspace_name TEXT NOT NULL REFERENCES workspaces(name) ON DELETE CASCADE,
role TEXT,
content TEXT NOT NULL,
created_at TEXT NOT NULL,
UNIQUE(workspace_name, role)
);
CREATE TABLE IF NOT EXISTS editor_tabs (
workspace_name TEXT NOT NULL REFERENCES workspaces(name) ON DELETE CASCADE,
file_path TEXT NOT NULL,
tab_order INTEGER NOT NULL DEFAULT 0,
is_active INTEGER NOT NULL DEFAULT 0,
is_dirty INTEGER NOT NULL DEFAULT 0,
dirty_content TEXT,
PRIMARY KEY (workspace_name, file_path)
);
-- ── Users / channels ───────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS users (
name TEXT PRIMARY KEY,
selected_workspace TEXT,
image_gen_model TEXT,
video_model TEXT,
granted_tools TEXT,
memory_inventory_day TEXT
);
CREATE TABLE IF NOT EXISTS user_channels (
user_name TEXT NOT NULL REFERENCES users(name),
channel TEXT NOT NULL,
identifier TEXT NOT NULL,
reply_target TEXT,
UNIQUE(channel, identifier)
);
-- ── Config ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS config_kv (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS config_model_routing (
model TEXT PRIMARY KEY,
provider_order TEXT,
allow_fallbacks INTEGER
);
-- ── Chat history ───────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS chat_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
message_id TEXT NOT NULL UNIQUE,
user_name TEXT NOT NULL,
direction TEXT NOT NULL,
content TEXT NOT NULL,
agent_role TEXT,
broadcast_id TEXT,
workspace TEXT NOT NULL,
timestamp TEXT,
reply_author TEXT,
reply_snippet TEXT
);
-- ── Telegram intake ────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS telegram_intake (
account_id TEXT NOT NULL,
update_id INTEGER NOT NULL,
state TEXT NOT NULL,
payload TEXT,
created_at TEXT NOT NULL,
decided_at TEXT,
claimed_by TEXT,
PRIMARY KEY (account_id, update_id)
);
CREATE TABLE IF NOT EXISTS telegram_bursts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account_id TEXT NOT NULL,
user_name TEXT NOT NULL,
reply_target TEXT NOT NULL,
parts INTEGER NOT NULL,
released_by TEXT NOT NULL,
released_at TEXT NOT NULL,
part_times TEXT NOT NULL
);
-- ── Ticket chronicle / automations ─────────────────────────────────────
CREATE TABLE IF NOT EXISTS ticket_chronicle (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ticket_id TEXT NOT NULL,
workspace_name TEXT NOT NULL,
source_phase TEXT NOT NULL,
target_phase TEXT NOT NULL,
at TEXT NOT NULL,
actor TEXT
);
CREATE TABLE IF NOT EXISTS automations (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
user_name TEXT NOT NULL,
kind TEXT NOT NULL,
text TEXT NOT NULL,
fire_at TEXT,
interval_seconds INTEGER,
next_fire_at TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
created_at TEXT NOT NULL,
trigger TEXT,
role TEXT,
identifier TEXT,
workspace TEXT,
retry_at TEXT,
unfinished_attempts INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS custom_roles (
name TEXT PRIMARY KEY,
prompt TEXT NOT NULL,
tools TEXT NOT NULL,
behavior TEXT NOT NULL,
created_at TEXT NOT NULL
);
-- ── Indexes ────────────────────────────────────────────────────────────
-- Only the indexes a product query's plan reaches, plus the uniqueness ones.
-- The unreached rest are dropped by [`DROP_UNUSED_CORE_INDEXES`], which
-- carries the audit.
CREATE INDEX IF NOT EXISTS idx_ticket_comments_ticket_id ON ticket_comments(ticket_id);
CREATE INDEX IF NOT EXISTS idx_sessions_agent_id ON sessions(agent_id, id);
CREATE INDEX IF NOT EXISTS idx_jobs_kind_status ON jobs(kind, status);
CREATE UNIQUE INDEX IF NOT EXISTS idx_agents_anchor ON agents(agent_id) WHERE job_id IS NULL;
CREATE INDEX IF NOT EXISTS idx_pending_jobs_agent_created ON pending_jobs(target_agent_id, created_at);
CREATE UNIQUE INDEX IF NOT EXISTS workspace_contexts_null_role ON workspace_contexts(workspace_name) WHERE role IS NULL;
CREATE INDEX IF NOT EXISTS idx_chat_history_user_ws_id ON chat_history(user_name, workspace, id);
CREATE INDEX IF NOT EXISTS idx_tickets_title_fts ON tickets USING fts (title) WITH (tokenizer = 'ngram');
CREATE INDEX IF NOT EXISTS idx_tickets_board_active ON tickets (is_archived, priority ASC, created_at DESC);
CREATE UNIQUE INDEX IF NOT EXISTS idx_jobs_phase_ticket ON jobs(kind, ticket_id) WHERE ticket_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_ticket_chronicle_ws_id ON ticket_chronicle(workspace_name, id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_ticket_chronicle_dedup ON ticket_chronicle(ticket_id, workspace_name, source_phase, target_phase, at);
CREATE INDEX IF NOT EXISTS idx_automations_due ON automations(status, next_fire_at);
CREATE INDEX IF NOT EXISTS idx_tickets_workspace_phase ON tickets (workspace_name, phase, is_archived, priority ASC, created_at DESC);";
const V0_10_0_LOGS_SCHEMA: &str = "\
-- ── Logs / tool calls / LLM requests ───────────────────────────────────
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
level TEXT NOT NULL,
target TEXT NOT NULL,
message TEXT NOT NULL,
fields TEXT NOT NULL DEFAULT '{}',
agent_id TEXT NOT NULL DEFAULT '',
agent_role TEXT NOT NULL DEFAULT '',
workspace TEXT NOT NULL DEFAULT '',
ticket TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS tool_calls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
agent_id TEXT NOT NULL,
role TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'agent',
tool_name TEXT NOT NULL,
arguments TEXT NOT NULL DEFAULT '{}',
duration_ms INTEGER NOT NULL DEFAULT 0,
success INTEGER NOT NULL DEFAULT 1,
error_message TEXT,
workspace TEXT NOT NULL DEFAULT '',
recorded_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS llm_requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
recorded_at TEXT NOT NULL,
purpose TEXT NOT NULL,
agent_id TEXT NOT NULL DEFAULT '',
role TEXT NOT NULL DEFAULT '',
workspace TEXT NOT NULL DEFAULT '',
ticket_id TEXT,
model TEXT NOT NULL,
routing TEXT NOT NULL DEFAULT '',
input_tokens INTEGER,
output_tokens INTEGER,
cached_input_tokens INTEGER,
cache_miss_tokens INTEGER,
duration_ms INTEGER NOT NULL,
retry_attempts INTEGER NOT NULL,
finish_reason TEXT,
failure_class TEXT,
success INTEGER NOT NULL DEFAULT 1,
cost REAL,
cost_details TEXT,
upstream_provider TEXT,
system_fingerprint TEXT
);
-- ── Grep telemetry ─────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS grep_telemetry (
id INTEGER PRIMARY KEY AUTOINCREMENT,
recorded_at TEXT NOT NULL,
command TEXT NOT NULL,
served INTEGER NOT NULL DEFAULT 0,
reason TEXT NOT NULL DEFAULT '',
recursive INTEGER NOT NULL DEFAULT 0,
piped INTEGER NOT NULL DEFAULT 0,
operand_count INTEGER NOT NULL DEFAULT 0,
flags TEXT NOT NULL DEFAULT '',
mode TEXT NOT NULL DEFAULT '',
workspace TEXT NOT NULL DEFAULT '',
grep_count INTEGER NOT NULL DEFAULT 0,
served_count INTEGER NOT NULL DEFAULT 0,
skipped_count INTEGER NOT NULL DEFAULT 0,
duration_ms INTEGER,
exit_code INTEGER
);
-- ── Indexes ────────────────────────────────────────────────────────────
-- Only the indexes a product query's plan reaches. The write-only rest are
-- dropped by [`DROP_UNUSED_LOGS_INDEXES`], which carries the audit.
CREATE INDEX IF NOT EXISTS idx_logs_level ON logs(level);
CREATE INDEX IF NOT EXISTS idx_tool_calls_recorded_at ON tool_calls(recorded_at);
CREATE INDEX IF NOT EXISTS idx_tool_calls_error_message ON tool_calls(error_message);
CREATE INDEX IF NOT EXISTS idx_llm_requests_recorded_at ON llm_requests(recorded_at);
CREATE INDEX IF NOT EXISTS idx_grep_telemetry_recorded_at ON grep_telemetry(recorded_at);
-- ── Per-attempt LLM failure trail ──────────────────────────────────────
CREATE TABLE IF NOT EXISTS llm_failures (
id INTEGER PRIMARY KEY AUTOINCREMENT,
operation_id TEXT NOT NULL,
recorded_at TEXT NOT NULL,
purpose TEXT NOT NULL,
agent_id TEXT NOT NULL DEFAULT '',
role TEXT NOT NULL DEFAULT '',
workspace TEXT NOT NULL DEFAULT '',
ticket_id TEXT,
model TEXT NOT NULL,
routing TEXT NOT NULL DEFAULT '',
attempt INTEGER NOT NULL,
attempt_duration_ms INTEGER,
failure_class TEXT NOT NULL,
finish_reason TEXT,
retry_after_ms INTEGER,
error_chain TEXT NOT NULL DEFAULT ''
);";
const V0_10_0_CORE_IDS: &[&str] = &[
"24", "25", "27", "28", "29", "30", "31", "32", "33", "34", "36", "37", "38", "39", "40",
"41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55",
"56", "57", "59", "60", "61", "62", "63", "65", "66", "67", "68", "69", "70", "72", "73",
"74", "75", "76", "77", "78",
];
const V0_10_0_LOGS_IDS: &[&str] = &["26", "35", "58", "64", "71"];
#[derive(Debug, PartialEq, Eq)]
struct ColumnShape {
declared: String,
not_null: i64,
default: Option<String>,
pk: i64,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct ForeignKey {
referenced_table: String,
from: String,
to: Option<String>,
on_update: String,
on_delete: String,
}
async fn column_shapes(
conn: &Connection,
table: &str,
) -> std::collections::BTreeMap<String, ColumnShape> {
conn.query(&format!("PRAGMA table_info({table})"), ())
.await
.expect("read table_info")
.into_iter()
.map(|row| {
(
row.get::<String>(1).expect("column name"),
ColumnShape {
declared: row.get::<String>(2).expect("declared type"),
not_null: row.get::<i64>(3).expect("notnull"),
default: row.get::<Option<String>>(4).expect("default"),
pk: row.get::<i64>(5).expect("pk"),
},
)
})
.collect()
}
async fn foreign_keys(conn: &Connection, table: &str) -> Vec<ForeignKey> {
let mut keys: Vec<ForeignKey> = conn
.query(&format!("PRAGMA foreign_key_list({table})"), ())
.await
.expect("read foreign_key_list")
.into_iter()
.map(|row| ForeignKey {
referenced_table: row.get::<String>(2).expect("referenced table"),
from: row.get::<String>(3).expect("from"),
to: row.get::<Option<String>>(4).expect("to"),
on_update: row.get::<String>(5).expect("on update"),
on_delete: row.get::<String>(6).expect("on delete"),
})
.collect();
keys.sort();
keys
}
async fn assert_same_schema(upgraded: &Connection, fresh: &Connection, context: &str) {
let mut upgraded_tables = table_names(upgraded).await;
let mut fresh_tables = table_names(fresh).await;
upgraded_tables.sort();
fresh_tables.sort();
assert_eq!(
upgraded_tables, fresh_tables,
"{context}: table sets differ"
);
for table in &fresh_tables {
assert_eq!(
column_shapes(upgraded, table).await,
column_shapes(fresh, table).await,
"{context}: table '{table}' column shapes differ"
);
assert_eq!(
foreign_keys(upgraded, table).await,
foreign_keys(fresh, table).await,
"{context}: table '{table}' foreign keys differ"
);
}
assert_eq!(
index_defs(upgraded).await,
index_defs(fresh).await,
"{context}: index definitions differ"
);
}
async fn v0_10_0_store(db_path: &std::path::Path, schema: &str, ids: &[&str]) -> Connection {
let conn = crate::db::open_with_schema(db_path, "")
.await
.expect("open the v0.10.0 fixture store");
conn.execute_batch(schema).await.expect("v0.10.0 baseline");
conn.execute(
"CREATE TABLE IF NOT EXISTS schema_migrations (\
id TEXT PRIMARY KEY, applied_at TEXT NOT NULL)",
(),
)
.await
.expect("create the fixture ledger");
for id in ids {
conn.execute(
"INSERT INTO schema_migrations (id, applied_at) VALUES (?1, ?2)",
params![*id, crate::db::now()],
)
.await
.expect("record a v0.10.0 id");
}
conn
}
#[tokio::test]
async fn v0_10_0_store_upgrades_to_the_fresh_shape() {
let tmp = tempfile::TempDir::new().unwrap();
let conn = v0_10_0_store(
&crate::db::store_db_path(&tmp.path().join("upgrade"), crate::db::CONSOLIDATED_DB_NAME),
V0_10_0_CORE_SCHEMA,
V0_10_0_CORE_IDS,
)
.await;
conn.execute(
"INSERT INTO config_kv (key, value) VALUES (?1, 'false')",
params![crate::config::CONFIG_KEY_AUDIO_TRANSCRIPTION_USE_LOCAL],
)
.await
.expect("seed entry 69's row as 0.10.0 left it");
conn.execute(
"INSERT INTO config_model_routing (model, provider_order) \
VALUES ('deepseek/deepseek-v4.1-flash-1017', 'deepinfra/fp8/flex')",
(),
)
.await
.expect("seed the routing row entry 81 deletes");
run_migrations(&conn, TargetDb::Core)
.await
.expect("upgrade the v0.10.0 store");
let fresh = crate::db::open_consolidated_store(&tmp.path().join("fresh"))
.await
.expect("fresh store");
assert_same_schema(&conn, &fresh, "v0.10.0 upgrade vs fresh core").await;
assert_eq!(
config_kv_rows(&conn).await,
config_kv_rows(&fresh).await,
"the catalog-written config rows must match a fresh install"
);
assert_eq!(
model_routing_orders(&conn).await,
model_routing_orders(&fresh).await,
"entry 81 must delete the routing row a v0.10.0 store carries"
);
}
#[tokio::test]
async fn v0_10_0_logs_store_matches_the_fresh_shape() {
let tmp = tempfile::TempDir::new().unwrap();
let conn = v0_10_0_store(
&crate::db::store_db_path(&tmp.path().join("upgrade"), crate::db::LOG_DB_NAME),
V0_10_0_LOGS_SCHEMA,
V0_10_0_LOGS_IDS,
)
.await;
run_migrations(&conn, TargetDb::Logs)
.await
.expect("upgrade the v0.10.0 logs store");
let fresh = crate::db::open_with_schema(
&crate::db::store_db_path(&tmp.path().join("fresh"), crate::db::LOG_DB_NAME),
"",
)
.await
.expect("fresh logs store");
run_migrations(&fresh, TargetDb::Logs)
.await
.expect("fresh logs catalog");
assert_same_schema(&conn, &fresh, "v0.10.0 logs upgrade vs fresh logs").await;
}
#[tokio::test]
async fn seed_audio_transcription_disabled_writes_the_off_default_once() {
let key = crate::config::CONFIG_KEY_AUDIO_TRANSCRIPTION_USE_LOCAL;
let tmp = tempfile::TempDir::new().unwrap();
let conn = crate::db::open_consolidated_store(tmp.path())
.await
.expect("fresh store");
let transcription = |rows: Vec<(String, String)>| {
rows.into_iter()
.filter(|(stored, _)| stored == key)
.collect::<Vec<_>>()
};
assert_eq!(
transcription(config_kv_rows(&conn).await),
vec![(key.to_string(), "false".to_string())],
"a fresh install ships transcription off"
);
conn.execute(
"UPDATE config_kv SET value = 'true' WHERE key = ?1",
params![key],
)
.await
.unwrap();
run_seed_audio_transcription_disabled(&conn)
.await
.expect("re-run entry 69");
assert_eq!(
transcription(config_kv_rows(&conn).await),
vec![(key.to_string(), "true".to_string())],
"an owner's value is never overwritten"
);
}
#[tokio::test]
async fn set_media_model_lists_overwrites_hand_edited_lists() {
let image_key = crate::config::CONFIG_KEY_IMAGE_GEN_MODELS;
let video_key = crate::config::CONFIG_KEY_VIDEO_MODELS;
let shipped = vec![
(
image_key.to_string(),
crate::config::SHIPPED_IMAGE_GEN_MODELS.to_string(),
),
(
video_key.to_string(),
crate::config::SHIPPED_VIDEO_MODELS.to_string(),
),
];
let lists = |rows: Vec<(String, String)>| {
rows.into_iter()
.filter(|(key, _)| key == image_key || key == video_key)
.collect::<Vec<_>>()
};
let tmp = tempfile::TempDir::new().unwrap();
let conn = crate::db::open_consolidated_store(tmp.path())
.await
.expect("fresh store");
assert_eq!(
lists(config_kv_rows(&conn).await),
shipped,
"a fresh store must run the catalog onto the shipped lists"
);
conn.execute(
"UPDATE config_kv SET value = 'hand/pick' WHERE key IN (?1, ?2)",
params![image_key, video_key],
)
.await
.unwrap();
run_set_media_model_lists(&conn)
.await
.expect("re-run entry 82");
assert_eq!(
lists(config_kv_rows(&conn).await),
shipped,
"a hand-edited list is replaced, otherwise the new defaults never reach the install"
);
conn.execute(
"DELETE FROM config_kv WHERE key IN (?1, ?2)",
params![image_key, video_key],
)
.await
.unwrap();
run_set_media_model_lists(&conn)
.await
.expect("re-run entry 82 with no rows");
assert_eq!(
lists(config_kv_rows(&conn).await),
shipped,
"an install predating the rows must receive them too"
);
}
#[tokio::test]
async fn a_store_that_recorded_the_media_list_step_still_arrives_at_the_new_list() {
let video_key = crate::config::CONFIG_KEY_VIDEO_MODELS;
let tmp = tempfile::TempDir::new().unwrap();
let conn = crate::db::open_consolidated_store(tmp.path())
.await
.expect("fresh store");
conn.execute(
"UPDATE config_kv SET value = 'minimax/hailuo-3' WHERE key = ?1",
params![video_key],
)
.await
.unwrap();
conn.execute("DELETE FROM schema_migrations WHERE id = '83'", ())
.await
.unwrap();
run_migrations(&conn, TargetDb::Core)
.await
.expect("re-run the core catalog");
let video = config_kv_rows(&conn)
.await
.into_iter()
.find(|(key, _)| key == video_key)
.map(|(_, value)| value);
assert_eq!(
video.as_deref(),
Some(crate::config::SHIPPED_VIDEO_MODELS),
"a store that already recorded 82 must still reach the shipped video list"
);
assert!(
recorded_ids(&conn).await.iter().any(|id| id == "83"),
"entry 83 must be recorded again"
);
}
}