Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Spaces S0: spaces table and space_id columns, everything in the Default space

Lin (kwant bot)8d339eb50de2
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 35eed9aa..21f04d06 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -7,6 +7,7 @@ pub mod attachments;
pub mod questions;
pub mod skills;
pub mod away;
+pub mod spaces;
use models::*;
use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite};
@@ -24,6 +25,9 @@ pub enum DbError {
#[error("JSON serialization error: {0}")]
Json(#[from] serde_json::Error),
+
+ #[error("Migration error: {0}")]
+ Migration(String),
}
#[derive(Clone, Debug)]
@@ -58,8 +62,19 @@ const STARTERS: [(&str, &str, &str, &str, &str); 3] = [
impl Database {
pub async fn init(data_dir: &Path) -> Result<Self, DbError> {
+ Self::open(data_dir, true).await
+ }
+
+ /// The database as a release from before spaces leaves it, for migration tests.
+ #[doc(hidden)]
+ pub async fn init_without_spaces(data_dir: &Path) -> Result<Self, DbError> {
+ Self::open(data_dir, false).await
+ }
+
+ async fn open(data_dir: &Path, spaces: bool) -> Result<Self, DbError> {
std::fs::create_dir_all(data_dir)?;
let db_path = data_dir.join("kwnt.db");
+ let fresh = !db_path.exists();
let conn_str = format!("sqlite://{}?mode=rwc", db_path.to_string_lossy());
let pool = SqlitePoolOptions::new()
@@ -94,6 +109,9 @@ impl Database {
db.migrate_attachments().await?;
db.migrate_history().await?;
db.migrate_away().await?;
+ if spaces {
+ db.migrate_spaces(data_dir, fresh).await?;
+ }
db.seed_defaults().await?;
Ok(db)
diff --git a/src/db/spaces.rs b/src/db/spaces.rs
new file mode 100644
index 00000000..1b6fe815
--- /dev/null
+++ b/src/db/spaces.rs
@@ -0,0 +1,304 @@
+//! Spaces, step S0: the `spaces` table and a `space_id` on every top-level row, with everything
+//! that exists today in the Default space. Nothing reads `space_id` yet, so behaviour is unchanged.
+//!
+//! The migration runs once, gated on `PRAGMA user_version`. It first writes a full copy of the
+//! database to `<data_dir>/backups/` and does nothing else if that fails. The schema change then
+//! runs in one transaction that rolls back on any error or on a new foreign-key violation, so a
+//! failed migration leaves the old schema, which this release still runs on, and retries at the
+//! next start. A binary from before spaces still runs on the migrated database while only the
+//! Default space exists: its inserts get the column default and its queries ignore the column.
+
+use super::{Database, DbError};
+use sqlx::{Connection, SqliteConnection};
+use std::collections::{HashMap, HashSet};
+use std::path::{Path, PathBuf};
+
+/// The space every row created before spaces belongs to.
+pub const DEFAULT_SPACE_ID: &str = "spc_default";
+
+/// `PRAGMA user_version` once the spaces schema is in place.
+pub const SPACES_SCHEMA_VERSION: i64 = 1;
+
+/// Tables that only gain a column. Their uniqueness rules don't involve names.
+const ADD_COLUMN_TABLES: [&str; 4] = ["kwants", "channels", "routines", "skills"];
+
+/// Tables with a name that was unique app-wide and becomes unique per space. SQLite can't drop a
+/// table-level UNIQUE, so these are rebuilt (create new, copy, drop old, rename). Each statement
+/// keeps every column and rule of the old table, plus `space_id`; the old case sensitivity is kept.
+const REBUILDS: [(&str, &str, &[&str]); 3] = [
+ (
+ "teams",
+ "CREATE TABLE teams__spaces_new (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ description TEXT,
+ icon TEXT NOT NULL DEFAULT 'users',
+ lead_kwant_id TEXT NOT NULL,
+ member_kwants TEXT NOT NULL,
+ workspace_path TEXT,
+ repo_url TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ instructions TEXT,
+ space_id TEXT NOT NULL DEFAULT 'spc_default',
+ UNIQUE (space_id, name),
+ FOREIGN KEY(lead_kwant_id) REFERENCES kwants(id)
+ )",
+ &[],
+ ),
+ (
+ "mcp_servers",
+ "CREATE TABLE mcp_servers__spaces_new (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ transport TEXT NOT NULL,
+ command TEXT,
+ args TEXT NOT NULL DEFAULT '[]',
+ url TEXT,
+ env TEXT NOT NULL DEFAULT '{}',
+ headers TEXT NOT NULL DEFAULT '{}',
+ enabled INTEGER NOT NULL DEFAULT 1,
+ timeout_secs INTEGER NOT NULL DEFAULT 30,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ space_id TEXT NOT NULL DEFAULT 'spc_default',
+ UNIQUE (space_id, name)
+ )",
+ &[],
+ ),
+ (
+ "llm_profiles",
+ "CREATE TABLE llm_profiles__spaces_new (
+ id TEXT PRIMARY KEY,
+ engine TEXT NOT NULL CHECK (engine IN ('claude', 'codex', 'grok')),
+ name TEXT NOT NULL,
+ kind TEXT NOT NULL CHECK (kind IN ('system', 'cli_home', 'api_key')),
+ home_dir TEXT UNIQUE,
+ priority INTEGER NOT NULL DEFAULT 100,
+ enabled INTEGER NOT NULL DEFAULT 1,
+ is_default INTEGER NOT NULL DEFAULT 0,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ space_id TEXT NOT NULL DEFAULT 'spc_default',
+ UNIQUE (space_id, engine, name COLLATE NOCASE)
+ )",
+ // Dropping the old table dropped its one-default index; it comes back per space
+ &["CREATE UNIQUE INDEX llm_profiles_one_default ON llm_profiles (space_id, engine) WHERE is_default = 1"],
+ ),
+];
+
+const INDEXES: [&str; 7] = [
+ "DROP INDEX IF EXISTS skills_live_name",
+ "CREATE UNIQUE INDEX skills_live_name ON skills (space_id, IFNULL(kwant_id, ''), name)
+ WHERE status IN ('enabled', 'disabled')",
+ "CREATE INDEX kwants_by_space ON kwants (space_id)",
+ "CREATE INDEX channels_by_space ON channels (space_id)",
+ "CREATE INDEX teams_by_space ON teams (space_id)",
+ "CREATE INDEX llm_profiles_by_space ON llm_profiles (space_id, engine)",
+ "CREATE INDEX routines_by_space ON routines (space_id)",
+];
+
+/// What happened to the spaces migration at startup.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum SpacesMigration {
+ /// The schema was already at [`SPACES_SCHEMA_VERSION`].
+ AlreadyDone,
+ /// Migrated; `backup` is `None` only for a database created by this start.
+ Migrated { backup: Option<PathBuf> },
+ /// Nothing changed: the backup couldn't be written, or the schema change failed and was
+ /// rolled back. Retried at the next start.
+ Skipped { reason: String },
+}
+
+impl Database {
+ /// `PRAGMA user_version`: 0 before spaces, [`SPACES_SCHEMA_VERSION`] after.
+ pub async fn schema_version(&self) -> Result<i64, DbError> {
+ let (v,): (i64,) = sqlx::query_as("PRAGMA user_version").fetch_one(&self.pool).await?;
+ Ok(v)
+ }
+
+ /// Never fails startup: an error leaves the old schema in place and is logged.
+ pub(super) async fn migrate_spaces(&self, data_dir: &Path, fresh: bool) -> Result<SpacesMigration, DbError> {
+ if self.schema_version().await? >= SPACES_SCHEMA_VERSION {
+ return Ok(SpacesMigration::AlreadyDone);
+ }
+
+ // A database this start created holds nothing worth a copy
+ let backup = if fresh {
+ None
+ } else {
+ match self.backup_before_spaces(data_dir).await {
+ Ok(path) => Some(path),
+ Err(e) => {
+ let reason = format!("couldn't write the pre-spaces backup: {e}");
+ tracing::error!("Spaces migration not run, the database is unchanged: {reason}");
+ return Ok(SpacesMigration::Skipped { reason });
+ }
+ }
+ };
+
+ let mut conn = self.pool.acquire().await?;
+ // Table rebuilds need foreign keys off, and SQLite ignores this pragma inside a transaction
+ sqlx::query("PRAGMA foreign_keys = OFF").execute(&mut *conn).await?;
+ let result = migrate_in_transaction(&mut conn).await;
+ sqlx::query("PRAGMA foreign_keys = ON").execute(&mut *conn).await?;
+
+ match result {
+ Ok(()) => {
+ match &backup {
+ Some(path) => tracing::info!(backup = %path.display(), "Migrated the database to spaces"),
+ None => tracing::info!("Created the database with spaces"),
+ }
+ Ok(SpacesMigration::Migrated { backup })
+ }
+ Err(e) => {
+ let reason = format!("schema change failed and was rolled back: {e}");
+ tracing::error!("Spaces migration not run, the database is unchanged: {reason}");
+ Ok(SpacesMigration::Skipped { reason })
+ }
+ }
+ }
+
+ /// `VACUUM INTO` gives a consistent copy under WAL. The copy holds API keys and OAuth
+ /// tokens, so the folder and file are owner-only.
+ async fn backup_before_spaces(&self, data_dir: &Path) -> Result<PathBuf, DbError> {
+ let dir = data_dir.join("backups");
+ std::fs::create_dir_all(&dir)?;
+ restrict(&dir, 0o700)?;
+ let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ");
+ let mut path = dir.join(format!("kwnt-pre-spaces-{stamp}.db"));
+ let mut n = 1;
+ while path.exists() {
+ path = dir.join(format!("kwnt-pre-spaces-{stamp}-{n}.db"));
+ n += 1;
+ }
+ sqlx::query("VACUUM INTO ?")
+ .bind(path.to_string_lossy().into_owned())
+ .execute(&self.pool)
+ .await?;
+ restrict(&path, 0o600)?;
+ Ok(path)
+ }
+}
+
+#[cfg(unix)]
+fn restrict(path: &Path, mode: u32) -> std::io::Result<()> {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
+}
+
+#[cfg(not(unix))]
+fn restrict(_path: &Path, _mode: u32) -> std::io::Result<()> {
+ Ok(())
+}
+
+async fn migrate_in_transaction(conn: &mut SqliteConnection) -> Result<(), DbError> {
+ // Violations already in the data aren't ours to fix; only new ones abort the migration
+ let violations_before = foreign_key_violations(conn).await?;
+
+ let mut tx = conn.begin().await?;
+ sqlx::query(
+ "CREATE TABLE spaces (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL UNIQUE COLLATE NOCASE,
+ icon TEXT NOT NULL DEFAULT 'box',
+ color TEXT,
+ sort INTEGER NOT NULL DEFAULT 0,
+ archived_at TIMESTAMP,
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
+ )",
+ )
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("INSERT INTO spaces (id, name, icon, color, sort) VALUES (?, 'Default', '💼', 'amber', 0)")
+ .bind(DEFAULT_SPACE_ID)
+ .execute(&mut *tx)
+ .await?;
+
+ // No REFERENCES spaces(id): SQLite refuses ADD COLUMN with a foreign key and a non-NULL
+ // default. Space membership is enforced in code
+ for table in ADD_COLUMN_TABLES {
+ sqlx::query(&format!(
+ "ALTER TABLE {table} ADD COLUMN space_id TEXT NOT NULL DEFAULT '{DEFAULT_SPACE_ID}'"
+ ))
+ .execute(&mut *tx)
+ .await?;
+ }
+
+ for (table, create, after) in REBUILDS {
+ rebuild(&mut tx, table, create, after).await?;
+ }
+
+ for stmt in INDEXES {
+ sqlx::query(stmt).execute(&mut *tx).await?;
+ }
+
+ let violations_after = foreign_key_violations(&mut tx).await?;
+ let new: Vec<_> = violations_after
+ .iter()
+ .filter(|(key, n)| **n > violations_before.get(*key).copied().unwrap_or(0))
+ .collect();
+ if !new.is_empty() {
+ return Err(DbError::Migration(format!("foreign key check failed: {new:?}")));
+ }
+
+ sqlx::query(&format!("PRAGMA user_version = {SPACES_SCHEMA_VERSION}"))
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(())
+}
+
+/// SQLite's documented rebuild: create the new table, copy every row, drop the old one and
+/// rename. Child tables refer to the parent by name, so their foreign keys follow the rename.
+/// Refuses to drop a column the new table doesn't have, rather than lose data.
+async fn rebuild(conn: &mut SqliteConnection, table: &str, create: &str, after: &[&str]) -> Result<(), DbError> {
+ let new_table = format!("{table}__spaces_new");
+ sqlx::query(create).execute(&mut *conn).await?;
+
+ let old_cols = columns(conn, table).await?;
+ let new_cols: HashSet<String> = columns(conn, &new_table).await?.into_iter().collect();
+ if let Some(missing) = old_cols.iter().find(|c| !new_cols.contains(*c)) {
+ return Err(DbError::Migration(format!("{table}.{missing} has no place in the new table")));
+ }
+
+ // rowid too, so listings without an ORDER BY keep their order
+ let list = old_cols.iter().map(|c| format!("\"{c}\"")).collect::<Vec<_>>().join(", ");
+ let copied = sqlx::query(&format!(
+ "INSERT INTO {new_table} (rowid, {list}) SELECT rowid, {list} FROM {table}"
+ ))
+ .execute(&mut *conn)
+ .await?
+ .rows_affected();
+ let (old_count,): (i64,) = sqlx::query_as(&format!("SELECT COUNT(*) FROM {table}"))
+ .fetch_one(&mut *conn)
+ .await?;
+ if copied != old_count as u64 {
+ return Err(DbError::Migration(format!("{table}: copied {copied} of {old_count} rows")));
+ }
+
+ sqlx::query(&format!("DROP TABLE {table}")).execute(&mut *conn).await?;
+ sqlx::query(&format!("ALTER TABLE {new_table} RENAME TO {table}"))
+ .execute(&mut *conn)
+ .await?;
+ for stmt in after {
+ sqlx::query(stmt).execute(&mut *conn).await?;
+ }
+ Ok(())
+}
+
+async fn columns(conn: &mut SqliteConnection, table: &str) -> Result<Vec<String>, DbError> {
+ let rows: Vec<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info(?) ORDER BY cid")
+ .bind(table)
+ .fetch_all(&mut *conn)
+ .await?;
+ Ok(rows.into_iter().map(|(name,)| name).collect())
+}
+
+/// `PRAGMA foreign_key_check` counted per (table, parent). Not per rowid: a rebuild renumbers them.
+async fn foreign_key_violations(conn: &mut SqliteConnection) -> Result<HashMap<(String, String), usize>, DbError> {
+ let rows: Vec<(String, Option<i64>, String, i64)> =
+ sqlx::query_as("PRAGMA foreign_key_check").fetch_all(&mut *conn).await?;
+ let mut counts = HashMap::new();
+ for (table, _, parent, _) in rows {
+ *counts.entry((table, parent)).or_insert(0) += 1;
+ }
+ Ok(counts)
+}
diff --git a/tests/spaces_migration_test.rs b/tests/spaces_migration_test.rs
new file mode 100644
index 00000000..4db1985c
--- /dev/null
+++ b/tests/spaces_migration_test.rs
@@ -0,0 +1,316 @@
+//! Spaces S0: the migration keeps every row, backs up first, runs once and leaves the old schema
+//! when it can't finish.
+
+use kwnt::db::spaces::{DEFAULT_SPACE_ID, SPACES_SCHEMA_VERSION};
+use kwnt::db::Database;
+use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions};
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+use std::str::FromStr;
+
+async fn raw(path: &Path) -> SqlitePool {
+ let opts = SqliteConnectOptions::from_str(&format!("sqlite://{}", path.display()))
+ .unwrap()
+ .foreign_keys(false);
+ SqlitePoolOptions::new().max_connections(1).connect_with(opts).await.unwrap()
+}
+
+async fn exec(pool: &SqlitePool, sql: &str) {
+ sqlx::query(sql).execute(pool).await.unwrap_or_else(|e| panic!("{sql}: {e}"));
+}
+
+/// A database as the release before spaces leaves it, with some of everything in it.
+async fn legacy(dir: &Path) -> SqlitePool {
+ Database::init_without_spaces(dir).await.unwrap();
+ let pool = raw(&dir.join("kwnt.db")).await;
+ for sql in [
+ "INSERT INTO kwants (id, name, title, persona_prompt, avatar_sprite, profile_id) VALUES
+ ('k_ada', 'Ada', 'Lead', 'p', 'architect', 'prf_personal'),
+ ('k_lin', 'Lin', 'Backend', 'p', 'devops', NULL)",
+ "INSERT INTO channels (id, name, lead_kwant_id, member_kwants) VALUES ('c_eng', 'eng', 'k_ada', '[\"k_ada\",\"k_lin\"]')",
+ "INSERT INTO teams (id, name, lead_kwant_id, member_kwants, workspace_path, instructions) VALUES
+ ('t_web', 'web', 'k_ada', '[\"k_ada\"]', '/w/web', 'ship it'),
+ ('t_Web', 'Web', 'k_lin', '[\"k_lin\"]', NULL, NULL)",
+ "UPDATE llm_profiles SET is_default = 0 WHERE id = 'prf_system_claude'",
+ "UPDATE llm_profiles SET enabled = 0, priority = 7 WHERE id = 'prf_system_codex'",
+ "INSERT INTO llm_profiles (id, engine, name, kind, home_dir, priority, enabled, is_default) VALUES
+ ('prf_personal', 'claude', 'Personal', 'cli_home', '/h/personal', 1, 1, 1),
+ ('prf_work', 'claude', 'Work', 'cli_home', '/h/work', 2, 0, 0),
+ ('prf_grok_key', 'grok', 'Key', 'api_key', NULL, 5, 1, 0)",
+ "INSERT INTO llm_profile_secrets (profile_id, api_key) VALUES ('prf_grok_key', 'xai-secret')",
+ "INSERT INTO llm_profile_state (profile_id, limited_until, last_error) VALUES ('prf_work', '2030-01-01T00:00:00Z', 'auth')",
+ "INSERT INTO mcp_servers (id, name, transport, command, url, env) VALUES
+ ('m_fs', 'fs', 'stdio', 'mcp-fs', NULL, '{\"A\":\"1\"}'),
+ ('m_gh', 'github', 'http', NULL, 'https://mcp.example', '{}')",
+ "INSERT INTO kwant_mcp_disabled (kwant_id, server_id) VALUES ('k_lin', 'm_fs')",
+ "INSERT INTO mcp_oauth_tokens (server_id, access_token, token_endpoint, client_id, resource) VALUES ('m_gh', 'tok', 'https://t', 'cid', 'r')",
+ "INSERT INTO mcp_oauth_clients (server_id, redirect_uri, issuer, client_id) VALUES ('m_gh', 'http://cb', 'https://iss', 'cid')",
+ "INSERT INTO routines (id, kwant_id, channel_id, name, instructions, schedule) VALUES ('r_1', 'k_lin', 'c_eng', 'daily', 'do', '{}')",
+ "INSERT INTO routine_runs (id, routine_id, trigger, started_at, status) VALUES ('rr_1', 'r_1', 'manual', '2026-01-01', 'ok')",
+ "INSERT INTO skills (id, kwant_id, name, description, body, status, source, created_at, updated_at) VALUES
+ ('s_shared', NULL, 'deploy', 'd', 'b', 'enabled', 'user', '2026-01-01', '2026-01-01'),
+ ('s_lin', 'k_lin', 'deploy', 'd', 'b', 'enabled', 'agent', '2026-01-01', '2026-01-01')",
+ "INSERT INTO messages (id, channel_id, direct_kwant_id, sender_role, sender_id, text) VALUES
+ ('msg_1', 'c_eng', NULL, 'user', 'u', 'hello migration'),
+ ('msg_2', NULL, 'k_ada', 'kwant', 'k_ada', 'direct reply')",
+ "INSERT INTO kwant_memories (id, kwant_id, text) VALUES ('mem_1', 'k_ada', 'likes sqlite')",
+ "INSERT INTO settings (key, value) VALUES ('laya_url', 'http://laya')",
+ ] {
+ exec(&pool, sql).await;
+ }
+ pool
+}
+
+/// Every row of every table except `spaces`, without `space_id`, as quoted text.
+async fn snapshot(pool: &SqlitePool) -> BTreeMap<String, Vec<String>> {
+ let tables: Vec<(String,)> = sqlx::query_as(
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name != 'spaces' ORDER BY name",
+ )
+ .fetch_all(pool)
+ .await
+ .unwrap();
+ let mut out = BTreeMap::new();
+ for (table,) in tables {
+ let cols: Vec<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info(?) WHERE name != 'space_id' ORDER BY cid")
+ .bind(&table)
+ .fetch_all(pool)
+ .await
+ .unwrap();
+ let expr = cols.iter().map(|(c,)| format!("quote(\"{c}\")")).collect::<Vec<_>>().join(" || '|' || ");
+ let mut rows: Vec<String> = sqlx::query_scalar(&format!("SELECT {expr} FROM \"{table}\""))
+ .fetch_all(pool)
+ .await
+ .unwrap();
+ rows.sort();
+ out.insert(table, rows);
+ }
+ out
+}
+
+async fn scalar_i64(pool: &SqlitePool, sql: &str) -> i64 {
+ sqlx::query_scalar(sql).fetch_one(pool).await.unwrap()
+}
+
+async fn has_column(pool: &SqlitePool, table: &str, col: &str) -> bool {
+ scalar_i64(pool, &format!("SELECT COUNT(*) FROM pragma_table_info('{table}') WHERE name = '{col}'")).await == 1
+}
+
+fn backups(dir: &Path) -> Vec<PathBuf> {
+ match std::fs::read_dir(dir.join("backups")) {
+ Ok(entries) => entries.map(|e| e.unwrap().path()).collect(),
+ Err(_) => vec![],
+ }
+}
+
+const SPACE_TABLES: [&str; 7] = ["kwants", "channels", "teams", "llm_profiles", "mcp_servers", "routines", "skills"];
+
+#[tokio::test]
+async fn migration_keeps_every_row_and_id_and_backs_up_first() {
+ let tmp = tempfile::tempdir().unwrap();
+ let pool = legacy(tmp.path()).await;
+ let before = snapshot(&pool).await;
+ assert_eq!(scalar_i64(&pool, "PRAGMA user_version").await, 0);
+
+ let db = Database::init(tmp.path()).await.unwrap();
+ assert_eq!(db.schema_version().await.unwrap(), SPACES_SCHEMA_VERSION);
+
+ let after = snapshot(&pool).await;
+ assert_eq!(before, after, "every row and id survives, nothing added or lost");
+
+ assert_eq!(
+ sqlx::query_as::<_, (String, String)>("SELECT id, name FROM spaces").fetch_all(&pool).await.unwrap(),
+ vec![(DEFAULT_SPACE_ID.to_string(), "Default".to_string())]
+ );
+ for table in SPACE_TABLES {
+ let elsewhere = scalar_i64(&pool, &format!("SELECT COUNT(*) FROM {table} WHERE space_id != '{DEFAULT_SPACE_ID}'")).await;
+ assert_eq!(elsewhere, 0, "{table} rows all in the Default space");
+ assert!(scalar_i64(&pool, &format!("SELECT COUNT(*) FROM {table}")).await > 0, "{table} has rows to check");
+ }
+
+ // This machine keeps its fixed ids and settings; Personal stays the Claude default
+ let profiles: Vec<(String, i64, i64, i64)> =
+ sqlx::query_as("SELECT id, priority, enabled, is_default FROM llm_profiles WHERE kind = 'system' ORDER BY id")
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ profiles,
+ vec![
+ ("prf_system_claude".into(), 0, 1, 0),
+ ("prf_system_codex".into(), 7, 0, 1),
+ ("prf_system_grok".into(), 0, 1, 1),
+ ]
+ );
+ let claude_default = db.list_profiles().await.unwrap().into_iter().find(|p| p.engine == "claude" && p.is_default);
+ assert_eq!(claude_default.map(|p| p.id), Some("prf_personal".into()));
+
+ let fk: Vec<(String, Option<i64>, String, i64)> = sqlx::query_as("PRAGMA foreign_key_check").fetch_all(&pool).await.unwrap();
+ assert!(fk.is_empty(), "{fk:?}");
+ let integrity: String = sqlx::query_scalar("PRAGMA integrity_check").fetch_one(&pool).await.unwrap();
+ assert_eq!(integrity, "ok");
+
+ // Child foreign keys still follow the rebuilt parents
+ exec(&pool, "PRAGMA foreign_keys = ON").await;
+ exec(&pool, "DELETE FROM mcp_servers WHERE id = 'm_gh'").await;
+ exec(&pool, "DELETE FROM llm_profiles WHERE id = 'prf_grok_key'").await;
+ assert_eq!(scalar_i64(&pool, "SELECT COUNT(*) FROM mcp_oauth_tokens").await, 0);
+ assert_eq!(scalar_i64(&pool, "SELECT COUNT(*) FROM llm_profile_secrets").await, 0);
+ assert!(sqlx::query("INSERT INTO kwant_mcp_disabled (kwant_id, server_id) VALUES ('k_ada', 'nope')")
+ .execute(&pool)
+ .await
+ .is_err());
+
+ // The backup is the database as it was before the migration touched it
+ let files = backups(tmp.path());
+ assert_eq!(files.len(), 1, "{files:?}");
+ let backup = raw(&files[0]).await;
+ assert_eq!(scalar_i64(&backup, "PRAGMA user_version").await, 0);
+ assert!(!has_column(&backup, "teams", "space_id").await);
+ assert_eq!(snapshot(&backup).await, before);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode(&files[0]), 0o600, "the copy holds API keys");
+ assert_eq!(mode(&tmp.path().join("backups")), 0o700);
+ }
+}
+
+#[tokio::test]
+async fn migration_runs_once() {
+ let tmp = tempfile::tempdir().unwrap();
+ let pool = legacy(tmp.path()).await;
+ Database::init(tmp.path()).await.unwrap();
+ let first = snapshot(&pool).await;
+ let schema: Vec<(String,)> = sqlx::query_as("SELECT sql FROM sqlite_master WHERE sql IS NOT NULL ORDER BY name").fetch_all(&pool).await.unwrap();
+
+ for _ in 0..2 {
+ let db = Database::init(tmp.path()).await.unwrap();
+ assert_eq!(db.schema_version().await.unwrap(), SPACES_SCHEMA_VERSION);
+ }
+ assert_eq!(snapshot(&pool).await, first);
+ let again: Vec<(String,)> = sqlx::query_as("SELECT sql FROM sqlite_master WHERE sql IS NOT NULL ORDER BY name").fetch_all(&pool).await.unwrap();
+ assert_eq!(schema, again);
+ assert_eq!(scalar_i64(&pool, "SELECT COUNT(*) FROM spaces").await, 1);
+ assert_eq!(backups(tmp.path()).len(), 1, "no second backup");
+}
+
+#[tokio::test]
+async fn backup_failure_leaves_the_old_schema_and_retries_next_start() {
+ let tmp = tempfile::tempdir().unwrap();
+ let pool = legacy(tmp.path()).await;
+ let before = snapshot(&pool).await;
+ // A file where the backups folder should go makes the backup fail
+ std::fs::write(tmp.path().join("backups"), "not a folder").unwrap();
+
+ let db = Database::init(tmp.path()).await.expect("startup still succeeds");
+ assert_eq!(db.schema_version().await.unwrap(), 0);
+ assert_eq!(scalar_i64(&pool, "SELECT COUNT(*) FROM sqlite_master WHERE name = 'spaces'").await, 0);
+ for table in SPACE_TABLES {
+ assert!(!has_column(&pool, table, "space_id").await, "{table} untouched");
+ }
+ assert_eq!(snapshot(&pool).await, before);
+ // Still a working database on the old schema
+ assert!(db.list_kwants().await.unwrap().iter().any(|k| k.id == "k_ada"));
+ assert!(db.list_teams().await.unwrap().iter().any(|t| t.name == "web"));
+ drop(db);
+
+ std::fs::remove_file(tmp.path().join("backups")).unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ assert_eq!(db.schema_version().await.unwrap(), SPACES_SCHEMA_VERSION);
+ assert_eq!(backups(tmp.path()).len(), 1);
+}
+
+#[tokio::test]
+async fn failed_schema_change_rolls_back_everything() {
+ let tmp = tempfile::tempdir().unwrap();
+ let pool = legacy(tmp.path()).await;
+ // A column the rebuilt table doesn't know: the migration must refuse rather than drop it
+ exec(&pool, "ALTER TABLE mcp_servers ADD COLUMN local_note TEXT").await;
+ exec(&pool, "UPDATE mcp_servers SET local_note = 'keep me'").await;
+ let before = snapshot(&pool).await;
+
+ let db = Database::init(tmp.path()).await.expect("startup still succeeds");
+ assert_eq!(db.schema_version().await.unwrap(), 0);
+ assert_eq!(snapshot(&pool).await, before);
+ assert_eq!(scalar_i64(&pool, "SELECT COUNT(*) FROM sqlite_master WHERE name = 'spaces'").await, 0);
+ // Steps before the failing one were rolled back too
+ assert!(!has_column(&pool, "kwants", "space_id").await);
+ assert!(!has_column(&pool, "teams", "space_id").await);
+ assert_eq!(scalar_i64(&pool, "SELECT COUNT(*) FROM sqlite_master WHERE name LIKE '%__spaces_new'").await, 0);
+ // The backup was written before the attempt
+ assert_eq!(backups(tmp.path()).len(), 1);
+}
+
+#[tokio::test]
+async fn foreign_key_problems_already_in_the_data_do_not_block_it() {
+ let tmp = tempfile::tempdir().unwrap();
+ let pool = legacy(tmp.path()).await;
+ exec(&pool, "INSERT INTO teams (id, name, lead_kwant_id, member_kwants) VALUES ('t_orphan', 'orphan', 'k_gone', '[]')").await;
+ exec(&pool, "INSERT INTO llm_profile_state (profile_id, last_error) VALUES ('prf_gone', 'auth')").await;
+ let count = |pool: SqlitePool| async move {
+ sqlx::query_as::<_, (String, Option<i64>, String, i64)>("PRAGMA foreign_key_check").fetch_all(&pool).await.unwrap().len()
+ };
+ assert_eq!(count(pool.clone()).await, 2);
+
+ let db = Database::init(tmp.path()).await.unwrap();
+ assert_eq!(db.schema_version().await.unwrap(), SPACES_SCHEMA_VERSION);
+ assert_eq!(count(pool.clone()).await, 2, "the same two, none new");
+}
+
+#[tokio::test]
+async fn names_are_unique_per_space() {
+ let tmp = tempfile::tempdir().unwrap();
+ let pool = legacy(tmp.path()).await;
+ Database::init(tmp.path()).await.unwrap();
+ exec(&pool, "INSERT INTO spaces (id, name) VALUES ('spc_two', 'Personal')").await;
+
+ let ok = |sql: &'static str| {
+ let pool = pool.clone();
+ async move { sqlx::query(sql).execute(&pool).await.map(|_| ()) }
+ };
+ // The same names are fine in another space
+ ok("INSERT INTO teams (id, name, lead_kwant_id, member_kwants, space_id) VALUES ('t2', 'web', 'k_ada', '[]', 'spc_two')").await.unwrap();
+ ok("INSERT INTO mcp_servers (id, name, transport, space_id) VALUES ('m2', 'fs', 'stdio', 'spc_two')").await.unwrap();
+ ok("INSERT INTO llm_profiles (id, engine, name, kind, is_default, space_id) VALUES ('p2', 'claude', 'personal', 'cli_home', 1, 'spc_two')").await.unwrap();
+ ok("INSERT INTO skills (id, name, description, body, status, source, created_at, updated_at, space_id) VALUES ('s2', 'deploy', 'd', 'b', 'enabled', 'user', 'x', 'x', 'spc_two')").await.unwrap();
+
+ // ...and still refused within one, with the old case rules
+ ok("INSERT INTO teams (id, name, lead_kwant_id, member_kwants) VALUES ('t3', 'web', 'k_ada', '[]')").await.unwrap_err();
+ ok("INSERT INTO teams (id, name, lead_kwant_id, member_kwants, space_id) VALUES ('t4', 'web', 'k_ada', '[]', 'spc_two')").await.unwrap_err();
+ ok("INSERT INTO mcp_servers (id, name, transport) VALUES ('m3', 'fs', 'stdio')").await.unwrap_err();
+ ok("INSERT INTO llm_profiles (id, engine, name, kind) VALUES ('p3', 'claude', 'PERSONAL', 'cli_home')").await.unwrap_err();
+ ok("INSERT INTO llm_profiles (id, engine, name, kind, is_default, space_id) VALUES ('p4', 'claude', 'Other', 'cli_home', 1, 'spc_two')").await.unwrap_err();
+ ok("INSERT INTO skills (id, name, description, body, status, source, created_at, updated_at) VALUES ('s3', 'deploy', 'd', 'b', 'enabled', 'user', 'x', 'x')").await.unwrap_err();
+ // home_dir stays unique across spaces: two accounts can't share one login folder
+ ok("INSERT INTO llm_profiles (id, engine, name, kind, home_dir, space_id) VALUES ('p5', 'claude', 'Dup', 'cli_home', '/h/personal', 'spc_two')").await.unwrap_err();
+}
+
+#[tokio::test]
+async fn fresh_database_starts_with_spaces_and_no_backup() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ assert_eq!(db.schema_version().await.unwrap(), SPACES_SCHEMA_VERSION);
+ assert!(backups(tmp.path()).is_empty());
+
+ let pool = raw(&tmp.path().join("kwnt.db")).await;
+ assert!(scalar_i64(&pool, "SELECT COUNT(*) FROM kwants").await >= 3, "starters seeded");
+ for table in ["kwants", "channels", "teams", "llm_profiles"] {
+ assert_eq!(scalar_i64(&pool, &format!("SELECT COUNT(*) FROM {table} WHERE space_id != '{DEFAULT_SPACE_ID}'")).await, 0);
+ }
+ // The existing DB layer writes through unchanged and lands in Default
+ let team = db
+ .create_team(&kwnt::db::models::NewTeam {
+ name: "web".into(),
+ description: None,
+ icon: None,
+ lead_kwant_id: db.list_kwants().await.unwrap()[0].id.clone(),
+ member_kwants: vec![],
+ workspace_path: None,
+ repo_url: None,
+ })
+ .await
+ .unwrap();
+ let space: String = sqlx::query_scalar("SELECT space_id FROM teams WHERE id = ?").bind(&team.id).fetch_one(&pool).await.unwrap();
+ assert_eq!(space, DEFAULT_SPACE_ID);
+}