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 S1: enforce space isolation in the db layer

Lin (kwant bot)181f3d547a2b
diff --git a/src/db/continuity.rs b/src/db/continuity.rs
index 6799b7ca..336f9564 100644
--- a/src/db/continuity.rs
+++ b/src/db/continuity.rs
@@ -1,6 +1,7 @@
//! Agent continuity: pinned team/channel instructions, full-text search over messages, per-kwant
//! memory, and routines with their run history.
+use super::spaces::SpaceId;
use super::{Database, DbError};
use chrono::{DateTime, Utc};
use serde::Serialize;
@@ -129,6 +130,8 @@ pub struct RoutineRow {
pub last_run_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
pub last_status: Option<String>,
+ /// Its kwant's space; the channel, when set, is in the same one.
+ pub space_id: String,
}
#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
@@ -156,7 +159,7 @@ pub struct NewRoutine {
}
const ROUTINE_SELECT: &str = "SELECT r.id, r.kwant_id, r.channel_id, r.name, r.instructions, r.schedule, r.enabled, \
- r.next_run_at, r.last_run_at, r.created_at, \
+ r.next_run_at, r.last_run_at, r.created_at, r.space_id, \
(SELECT status FROM routine_runs x WHERE x.routine_id = r.id ORDER BY x.started_at DESC, x.rowid DESC LIMIT 1) AS last_status \
FROM routines r";
@@ -248,9 +251,11 @@ impl Database {
// Search
- /// Best matches first (bm25), newer first among equals. An empty result for a query with no words.
+ /// Best matches first (bm25), newer first among equals, from the space's channels, direct chats
+ /// and threads only. An empty result for a query with no words.
pub async fn search_messages(
&self,
+ space: &SpaceId,
q: &str,
filter: &SearchFilter,
) -> Result<Vec<SearchHit>, DbError> {
@@ -263,10 +268,16 @@ impl Database {
snippet(messages_fts, 0, '<mark>', '</mark>', '…', 16) AS snippet, m.created_at \
FROM messages_fts JOIN messages m ON m.rowid = messages_fts.rowid \
LEFT JOIN channels c ON c.id = m.channel_id \
+ LEFT JOIN kwants dk ON dk.id = m.direct_kwant_id \
+ LEFT JOIN threads t ON t.id = m.thread_id \
+ LEFT JOIN kwants tk ON tk.id = t.kwant_id \
LEFT JOIN kwants k ON m.sender_role = 'kwant' AND k.name = m.sender_id \
+ AND k.space_id = COALESCE(c.space_id, dk.space_id, tk.space_id) \
WHERE messages_fts MATCH ",
);
qb.push_bind(query);
+ qb.push(" AND COALESCE(c.space_id, dk.space_id, tk.space_id) = ")
+ .push_bind(space.as_str().to_string());
if let Some(channel) = &filter.channel_id {
qb.push(" AND m.channel_id = ").push_bind(channel.clone());
}
@@ -391,10 +402,11 @@ impl Database {
// Routines
- pub async fn list_routines(&self) -> Result<Vec<RoutineRow>, DbError> {
+ pub async fn list_routines(&self, space: &SpaceId) -> Result<Vec<RoutineRow>, DbError> {
Ok(sqlx::query_as::<_, RoutineRow>(&format!(
- "{ROUTINE_SELECT} ORDER BY r.created_at, r.rowid"
+ "{ROUTINE_SELECT} WHERE r.space_id = ? ORDER BY r.created_at, r.rowid"
))
+ .bind(space.as_str())
.fetch_all(&self.pool)
.await?)
}
@@ -408,11 +420,14 @@ impl Database {
)
}
+ /// The routine's space is its kwant's. Fails with [`DbError::OtherSpace`] for a channel in
+ /// another space.
pub async fn create_routine(&self, input: &NewRoutine) -> Result<RoutineRow, DbError> {
+ let space = self.routine_space(input).await?;
let id = Uuid::new_v4().to_string();
sqlx::query(
- "INSERT INTO routines (id, kwant_id, channel_id, name, instructions, schedule, enabled, next_run_at, created_at) \
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ "INSERT INTO routines (id, kwant_id, channel_id, name, instructions, schedule, enabled, next_run_at, created_at, space_id) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(&id)
.bind(&input.kwant_id)
@@ -423,6 +438,7 @@ impl Database {
.bind(input.enabled)
.bind(input.next_run_at)
.bind(Utc::now())
+ .bind(space.as_str())
.execute(&self.pool)
.await?;
self.get_routine(&id)
@@ -430,15 +446,28 @@ impl Database {
.ok_or(DbError::Sqlx(sqlx::Error::RowNotFound))
}
- /// Replaces every editable field.
+ /// The kwant (and channel, when set) a routine runs as must share a space.
+ async fn routine_space(&self, input: &NewRoutine) -> Result<SpaceId, DbError> {
+ let other = || DbError::OtherSpace("the agent and channel must be in the same space".into());
+ let space = self.space_of_kwant(&input.kwant_id).await?.ok_or_else(other)?;
+ if let Some(channel) = &input.channel_id {
+ if self.space_of_channel(channel).await?.as_ref() != Some(&space) {
+ return Err(other());
+ }
+ }
+ Ok(space)
+ }
+
+ /// Replaces every editable field. The routine may move with its kwant to that kwant's space.
pub async fn update_routine(
&self,
id: &str,
input: &NewRoutine,
) -> Result<Option<RoutineRow>, DbError> {
+ let space = self.routine_space(input).await?;
let res = sqlx::query(
"UPDATE routines SET kwant_id = ?, channel_id = ?, name = ?, instructions = ?, schedule = ?, enabled = ?, \
- next_run_at = ? WHERE id = ?",
+ next_run_at = ?, space_id = ? WHERE id = ?",
)
.bind(&input.kwant_id)
.bind(&input.channel_id)
@@ -447,6 +476,7 @@ impl Database {
.bind(&input.schedule)
.bind(input.enabled)
.bind(input.next_run_at)
+ .bind(space.as_str())
.bind(id)
.execute(&self.pool)
.await?;
@@ -487,7 +517,7 @@ impl Database {
Ok(res.rows_affected())
}
- /// Enabled routines due at `now`.
+ /// Enabled routines due at `now`, in every space: each one runs in its own space.
pub async fn due_routines(&self, now: DateTime<Utc>) -> Result<Vec<RoutineRow>, DbError> {
Ok(sqlx::query_as::<_, RoutineRow>(&format!(
"{ROUTINE_SELECT} WHERE r.enabled = 1 AND r.next_run_at IS NOT NULL AND r.next_run_at <= ? ORDER BY r.next_run_at"
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 21f04d06..60db3e52 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -10,6 +10,7 @@ pub mod away;
pub mod spaces;
use models::*;
+use spaces::SpaceId;
use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite};
use std::path::Path;
use thiserror::Error;
@@ -28,6 +29,13 @@ pub enum DbError {
#[error("Migration error: {0}")]
Migration(String),
+
+ /// A write would link rows from two spaces.
+ #[error("{0}")]
+ OtherSpace(String),
+
+ #[error("{0}")]
+ Conflict(String),
}
#[derive(Clone, Debug)]
@@ -110,9 +118,11 @@ impl Database {
db.migrate_history().await?;
db.migrate_away().await?;
if spaces {
- db.migrate_spaces(data_dir, fresh).await?;
+ let migration = db.migrate_spaces(data_dir, fresh).await?;
+ db.require_spaces_schema(&migration).await?;
+ db.ensure_one_general().await?;
+ db.seed_defaults().await?;
}
- db.seed_defaults().await?;
Ok(db)
}
@@ -128,7 +138,10 @@ impl Database {
.await?;
}
- let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM kwants")
+ // Only the Default space is seeded; other spaces start empty
+ let space = SpaceId::default_space();
+ let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM kwants WHERE space_id = ?")
+ .bind(space.as_str())
.fetch_one(&self.pool)
.await?;
@@ -147,11 +160,11 @@ impl Database {
.collect();
for starter in starters {
- self.create_kwant(&starter).await?;
+ self.create_kwant(&space, &starter).await?;
}
// Create initial general channel
- let kwants = self.list_kwants().await?;
+ let kwants = self.list_kwants(&space).await?;
if let Some(lead) = kwants.first() {
let chan = NewChannel {
name: "general".into(),
@@ -160,7 +173,7 @@ impl Database {
member_kwants: kwants.iter().map(|k| k.id.clone()).collect(),
routing_mode: "auto".into(),
};
- self.create_channel(&chan).await?;
+ self.create_channel(&space, &chan).await?;
}
} else {
// Smoothly migrate any legacy starter names and prompts
@@ -170,13 +183,14 @@ impl Database {
}
// Seed default team if none exists
- let team_count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM teams")
+ let team_count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM teams WHERE space_id = ?")
+ .bind(space.as_str())
.fetch_one(&self.pool)
.await
.unwrap_or((0,));
if team_count.0 == 0 {
- let kwants = self.list_kwants().await?;
+ let kwants = self.list_kwants(&space).await?;
if let Some(lead) = kwants.iter().find(|k| k.name == "Architect").or_else(|| kwants.first()) {
let member_ids: Vec<String> = kwants.iter().map(|k| k.id.clone()).collect();
let default_team = NewTeam {
@@ -188,7 +202,7 @@ impl Database {
workspace_path: None,
repo_url: None,
};
- self.create_team(&default_team).await?;
+ self.create_team(&space, &default_team).await?;
}
}
@@ -197,12 +211,12 @@ impl Database {
// Kwants CRUD
- pub async fn create_kwant(&self, input: &NewKwant) -> Result<Kwant, DbError> {
+ pub async fn create_kwant(&self, space: &SpaceId, input: &NewKwant) -> Result<Kwant, DbError> {
let id = Uuid::new_v4().to_string();
sqlx::query(
r#"
- INSERT INTO kwants (id, name, title, persona_prompt, soul, avatar_sprite, driver_type, preferred_model)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ INSERT INTO kwants (id, name, title, persona_prompt, soul, avatar_sprite, driver_type, preferred_model, space_id)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
"#,
)
.bind(&id)
@@ -213,6 +227,7 @@ impl Database {
.bind(&input.avatar_sprite)
.bind(&input.driver_type)
.bind(&input.preferred_model)
+ .bind(space.as_str())
.execute(&self.pool)
.await?;
@@ -221,8 +236,10 @@ impl Database {
.ok_or_else(|| DbError::Sqlx(sqlx::Error::RowNotFound))
}
- pub async fn list_kwants(&self) -> Result<Vec<Kwant>, DbError> {
- let rows = sqlx::query_as::<_, Kwant>("SELECT * FROM kwants ORDER BY created_at ASC")
+ /// The space's kwants, oldest first.
+ pub async fn list_kwants(&self, space: &SpaceId) -> Result<Vec<Kwant>, DbError> {
+ let rows = sqlx::query_as::<_, Kwant>("SELECT * FROM kwants WHERE space_id = ? ORDER BY created_at ASC")
+ .bind(space.as_str())
.fetch_all(&self.pool)
.await?;
Ok(rows)
@@ -266,14 +283,20 @@ impl Database {
}
// Channels CRUD
- pub async fn create_channel(&self, input: &NewChannel) -> Result<Channel, DbError> {
+ /// Fails with [`DbError::OtherSpace`] when the lead or a member is another space's kwant,
+ /// and [`DbError::Conflict`] for a second #general in the space.
+ pub async fn create_channel(&self, space: &SpaceId, input: &NewChannel) -> Result<Channel, DbError> {
let id = Uuid::new_v4().to_string();
let members_json = serde_json::to_string(&input.member_kwants)?;
+ self.check_members(space, &input.lead_kwant_id, &input.member_kwants).await?;
+ if input.name == "general" && self.general_channel(space).await?.is_some() {
+ return Err(DbError::Conflict("this space already has a #general".into()));
+ }
sqlx::query(
r#"
- INSERT INTO channels (id, name, description, lead_kwant_id, member_kwants, routing_mode)
- VALUES (?, ?, ?, ?, ?, ?)
+ INSERT INTO channels (id, name, description, lead_kwant_id, member_kwants, routing_mode, space_id)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
"#,
)
.bind(&id)
@@ -282,6 +305,7 @@ impl Database {
.bind(&input.lead_kwant_id)
.bind(&members_json)
.bind(&input.routing_mode)
+ .bind(space.as_str())
.execute(&self.pool)
.await?;
@@ -290,13 +314,34 @@ impl Database {
.ok_or_else(|| DbError::Sqlx(sqlx::Error::RowNotFound))
}
- pub async fn list_channels(&self) -> Result<Vec<Channel>, DbError> {
- let rows = sqlx::query_as::<_, Channel>("SELECT * FROM channels ORDER BY created_at ASC")
+ pub async fn list_channels(&self, space: &SpaceId) -> Result<Vec<Channel>, DbError> {
+ let rows = sqlx::query_as::<_, Channel>("SELECT * FROM channels WHERE space_id = ? ORDER BY created_at ASC")
+ .bind(space.as_str())
.fetch_all(&self.pool)
.await?;
Ok(rows)
}
+ /// The space's #general (the oldest, if an old database has several).
+ pub async fn general_channel(&self, space: &SpaceId) -> Result<Option<Channel>, DbError> {
+ Ok(sqlx::query_as::<_, Channel>(
+ "SELECT * FROM channels WHERE space_id = ? AND name = 'general' ORDER BY created_at ASC, rowid ASC LIMIT 1",
+ )
+ .bind(space.as_str())
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ /// Refuses a lead or member list that names another space's kwant (or no kwant at all).
+ async fn check_members(&self, space: &SpaceId, lead: &str, members: &[String]) -> Result<(), DbError> {
+ let ids: Vec<&str> = std::iter::once(lead).chain(members.iter().map(String::as_str)).collect();
+ if self.kwants_in_space(space, &ids).await? {
+ Ok(())
+ } else {
+ Err(DbError::OtherSpace("every lead and member must be a kwant in this space".into()))
+ }
+ }
+
pub async fn get_channel(&self, id: &str) -> Result<Option<Channel>, DbError> {
let row = sqlx::query_as::<_, Channel>("SELECT * FROM channels WHERE id = ?")
.bind(id)
@@ -432,15 +477,17 @@ impl Database {
}
// Teams CRUD
- pub async fn create_team(&self, input: &NewTeam) -> Result<Team, DbError> {
+ /// Fails with [`DbError::OtherSpace`] when the lead or a member is another space's kwant.
+ pub async fn create_team(&self, space: &SpaceId, input: &NewTeam) -> Result<Team, DbError> {
let id = Uuid::new_v4().to_string();
let icon = input.icon.as_deref().unwrap_or("users");
let members_json = serde_json::to_string(&input.member_kwants)?;
+ self.check_members(space, &input.lead_kwant_id, &input.member_kwants).await?;
sqlx::query(
r#"
- INSERT INTO teams (id, name, description, icon, lead_kwant_id, member_kwants, workspace_path, repo_url)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ INSERT INTO teams (id, name, description, icon, lead_kwant_id, member_kwants, workspace_path, repo_url, space_id)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
"#,
)
.bind(&id)
@@ -451,12 +498,13 @@ impl Database {
.bind(&members_json)
.bind(&input.workspace_path)
.bind(&input.repo_url)
+ .bind(space.as_str())
.execute(&self.pool)
.await?;
// Auto-create a team channel team-{name} if it doesn't already exist
let channel_name = format!("team-{}", input.name);
- let channels = self.list_channels().await?;
+ let channels = self.list_channels(space).await?;
if !channels.iter().any(|c| c.name == channel_name) {
let chan = NewChannel {
name: channel_name,
@@ -465,7 +513,7 @@ impl Database {
member_kwants: input.member_kwants.clone(),
routing_mode: "auto".into(),
};
- self.create_channel(&chan).await?;
+ self.create_channel(space, &chan).await?;
}
self.get_team(&id)
@@ -473,8 +521,9 @@ impl Database {
.ok_or_else(|| DbError::Sqlx(sqlx::Error::RowNotFound))
}
- pub async fn list_teams(&self) -> Result<Vec<Team>, DbError> {
- let rows = sqlx::query_as::<_, Team>("SELECT * FROM teams ORDER BY created_at ASC")
+ pub async fn list_teams(&self, space: &SpaceId) -> Result<Vec<Team>, DbError> {
+ let rows = sqlx::query_as::<_, Team>("SELECT * FROM teams WHERE space_id = ? ORDER BY created_at ASC")
+ .bind(space.as_str())
.fetch_all(&self.pool)
.await?;
Ok(rows)
@@ -488,17 +537,23 @@ impl Database {
Ok(row)
}
- pub async fn get_team_by_name(&self, name: &str) -> Result<Option<Team>, DbError> {
- let row = sqlx::query_as::<_, Team>("SELECT * FROM teams WHERE name = ?")
+ pub async fn get_team_by_name(&self, space: &SpaceId, name: &str) -> Result<Option<Team>, DbError> {
+ let row = sqlx::query_as::<_, Team>("SELECT * FROM teams WHERE space_id = ? AND name = ?")
+ .bind(space.as_str())
.bind(name)
.fetch_optional(&self.pool)
.await?;
Ok(row)
}
+ /// Fails with [`DbError::OtherSpace`] when the lead or a member is another space's kwant.
pub async fn update_team(&self, id: &str, input: &NewTeam) -> Result<Option<Team>, DbError> {
let icon = input.icon.as_deref().unwrap_or("users");
let members_json = serde_json::to_string(&input.member_kwants)?;
+ let Some(space) = self.space_of_team(id).await? else {
+ return Ok(None);
+ };
+ self.check_members(&space, &input.lead_kwant_id, &input.member_kwants).await?;
let res = sqlx::query(
r#"
@@ -524,11 +579,12 @@ impl Database {
// Also update corresponding team channel if it exists
let channel_name = format!("team-{}", input.name);
- let _ = sqlx::query("UPDATE channels SET description = ?, lead_kwant_id = ?, member_kwants = ? WHERE name = ?")
+ let _ = sqlx::query("UPDATE channels SET description = ?, lead_kwant_id = ?, member_kwants = ? WHERE name = ? AND space_id = ?")
.bind(&input.description)
.bind(&input.lead_kwant_id)
.bind(&members_json)
.bind(&channel_name)
+ .bind(space.as_str())
.execute(&self.pool)
.await;
@@ -544,8 +600,9 @@ impl Database {
}
// MCP servers
- pub async fn list_mcp_servers(&self) -> Result<Vec<McpServer>, DbError> {
- let rows = sqlx::query_as::<_, McpServerRow>("SELECT * FROM mcp_servers ORDER BY name ASC")
+ pub async fn list_mcp_servers(&self, space: &SpaceId) -> Result<Vec<McpServer>, DbError> {
+ let rows = sqlx::query_as::<_, McpServerRow>("SELECT * FROM mcp_servers WHERE space_id = ? ORDER BY name ASC")
+ .bind(space.as_str())
.fetch_all(&self.pool)
.await?;
Ok(rows.into_iter().map(McpServer::from_row).collect())
@@ -560,11 +617,11 @@ impl Database {
}
/// Inserts `server` with a fresh id (any id passed in is ignored).
- pub async fn create_mcp_server(&self, server: &McpServer) -> Result<McpServer, DbError> {
+ pub async fn create_mcp_server(&self, space: &SpaceId, server: &McpServer) -> Result<McpServer, DbError> {
let id = Uuid::new_v4().to_string();
sqlx::query(
- "INSERT INTO mcp_servers (id, name, transport, command, args, url, env, headers, enabled, timeout_secs) \
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ "INSERT INTO mcp_servers (id, name, transport, command, args, url, env, headers, enabled, timeout_secs, space_id) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(&id)
.bind(&server.name)
@@ -576,6 +633,7 @@ impl Database {
.bind(serde_json::to_string(&server.headers)?)
.bind(server.enabled)
.bind(server.timeout_secs)
+ .bind(space.as_str())
.execute(&self.pool)
.await?;
self.get_mcp_server(&id)
@@ -624,11 +682,11 @@ impl Database {
Ok(res.rows_affected() > 0)
}
- /// The servers a kwant may use, enabled or not: every server it hasn't opted out of.
+ /// The servers a kwant may use, enabled or not: every server in its space it hasn't opted out of.
pub async fn get_kwant_mcp_server_ids(&self, kwant_id: &str) -> Result<Vec<String>, DbError> {
let rows: Vec<(String,)> = sqlx::query_as(
- "SELECT s.id FROM mcp_servers s WHERE NOT EXISTS \
- (SELECT 1 FROM kwant_mcp_disabled d WHERE d.kwant_id = ? AND d.server_id = s.id) ORDER BY s.name ASC",
+ "SELECT s.id FROM mcp_servers s WHERE s.space_id = (SELECT space_id FROM kwants WHERE id = ?1) AND NOT EXISTS \
+ (SELECT 1 FROM kwant_mcp_disabled d WHERE d.kwant_id = ?1 AND d.server_id = s.id) ORDER BY s.name ASC",
)
.bind(kwant_id)
.fetch_all(&self.pool)
@@ -636,15 +694,19 @@ impl Database {
Ok(rows.into_iter().map(|r| r.0).collect())
}
- /// Makes `server_ids` the kwant's servers: every other server is opted out, so ones added later
- /// start on. Callers validate that every id exists.
+ /// Makes `server_ids` the kwant's servers: every other server in its space is opted out, so
+ /// ones added later start on. Callers validate that every id is a server in the kwant's space.
pub async fn set_kwant_mcp_servers(&self, kwant_id: &str, server_ids: &[String]) -> Result<(), DbError> {
let mut tx = self.pool.begin().await?;
sqlx::query("DELETE FROM kwant_mcp_disabled WHERE kwant_id = ?")
.bind(kwant_id)
.execute(&mut *tx)
.await?;
- let all: Vec<(String,)> = sqlx::query_as("SELECT id FROM mcp_servers").fetch_all(&mut *tx).await?;
+ let all: Vec<(String,)> =
+ sqlx::query_as("SELECT id FROM mcp_servers WHERE space_id = (SELECT space_id FROM kwants WHERE id = ?)")
+ .bind(kwant_id)
+ .fetch_all(&mut *tx)
+ .await?;
for (server_id,) in all.into_iter().filter(|(id,)| !server_ids.contains(id)) {
sqlx::query("INSERT OR IGNORE INTO kwant_mcp_disabled (kwant_id, server_id) VALUES (?, ?)")
.bind(kwant_id)
@@ -656,11 +718,11 @@ impl Database {
Ok(())
}
- /// The enabled servers the kwant hasn't opted out of: what it may use on its next turn.
+ /// The enabled servers in the kwant's space it hasn't opted out of: what it may use on its next turn.
pub async fn list_active_mcp_servers_for_kwant(&self, kwant_id: &str) -> Result<Vec<McpServer>, DbError> {
let rows = sqlx::query_as::<_, McpServerRow>(
- "SELECT s.* FROM mcp_servers s WHERE s.enabled = 1 AND NOT EXISTS \
- (SELECT 1 FROM kwant_mcp_disabled d WHERE d.kwant_id = ? AND d.server_id = s.id) ORDER BY s.name ASC",
+ "SELECT s.* FROM mcp_servers s WHERE s.enabled = 1 AND s.space_id = (SELECT space_id FROM kwants WHERE id = ?1) \
+ AND NOT EXISTS (SELECT 1 FROM kwant_mcp_disabled d WHERE d.kwant_id = ?1 AND d.server_id = s.id) ORDER BY s.name ASC",
)
.bind(kwant_id)
.fetch_all(&self.pool)
@@ -668,14 +730,16 @@ impl Database {
Ok(rows.into_iter().map(McpServer::from_row).collect())
}
- /// Opt-outs by server: `server_id -> kwant ids that have it off`. Only existing kwants are listed.
+ /// Opt-outs by server: `server_id -> kwant ids that have it off`. Only the space's kwants are listed.
pub async fn list_mcp_kwant_opt_outs(
&self,
+ space: &SpaceId,
) -> Result<std::collections::HashMap<String, Vec<String>>, DbError> {
let rows: Vec<(String, String)> = sqlx::query_as(
"SELECT d.server_id, d.kwant_id FROM kwant_mcp_disabled d JOIN kwants k ON k.id = d.kwant_id \
- ORDER BY k.name ASC",
+ WHERE k.space_id = ? ORDER BY k.name ASC",
)
+ .bind(space.as_str())
.fetch_all(&self.pool)
.await?;
let mut map = std::collections::HashMap::<String, Vec<String>>::new();
diff --git a/src/db/models.rs b/src/db/models.rs
index 65cd0952..8e2b1bf4 100644
--- a/src/db/models.rs
+++ b/src/db/models.rs
@@ -20,6 +20,9 @@ pub struct Kwant {
pub level: i64,
pub turns_completed: i64,
pub created_at: Option<DateTime<Utc>>,
+ /// The space this row belongs to.
+ #[serde(default = "crate::db::spaces::default_space_id")]
+ pub space_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -59,6 +62,9 @@ pub struct Channel {
#[serde(default)]
#[sqlx(default)]
pub instructions: Option<String>,
+ /// The space this row belongs to.
+ #[serde(default = "crate::db::spaces::default_space_id")]
+ pub space_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -146,6 +152,9 @@ pub struct Team {
#[serde(default)]
#[sqlx(default)]
pub instructions: Option<String>,
+ /// The space this row belongs to.
+ #[serde(default = "crate::db::spaces::default_space_id")]
+ pub space_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -327,6 +336,9 @@ pub struct LlmProfile {
pub enabled: bool,
pub is_default: bool,
pub created_at: Option<DateTime<Utc>>,
+ /// The space this row belongs to.
+ #[serde(default = "crate::db::spaces::default_space_id")]
+ pub space_id: String,
}
#[derive(Debug, Clone)]
diff --git a/src/db/profiles.rs b/src/db/profiles.rs
index 1970a383..aaba6655 100644
--- a/src/db/profiles.rs
+++ b/src/db/profiles.rs
@@ -1,6 +1,7 @@
//! LLM profiles: several accounts per engine, which kwants are bound to and fail over between.
use super::models::*;
+use super::spaces::SpaceId;
use super::{Database, DbError};
use chrono::{DateTime, Utc};
use std::collections::{HashMap, HashSet};
@@ -14,8 +15,17 @@ pub fn system_profile_id(engine: &str) -> String {
format!("prf_system_{engine}")
}
+/// Id of an engine's This machine profile in a space. The Default space keeps the old ids.
+pub fn system_profile_id_in(space: &SpaceId, engine: &str) -> String {
+ if space.is_default() {
+ system_profile_id(engine)
+ } else {
+ format!("prf_system_{engine}_{space}")
+ }
+}
+
const PROFILE_COLUMNS: &str =
- "id, engine, name, kind, home_dir, priority, enabled, is_default, created_at";
+ "id, engine, name, kind, home_dir, priority, enabled, is_default, created_at, space_id";
impl Database {
/// Adds the kwant binding columns and one system profile per engine. Existing setups end up
@@ -44,11 +54,12 @@ impl Database {
Ok(())
}
- /// All profiles, an engine's default first and then by priority.
- pub async fn list_profiles(&self) -> Result<Vec<LlmProfile>, DbError> {
+ /// The space's profiles, an engine's default first and then by priority.
+ pub async fn list_profiles(&self, space: &SpaceId) -> Result<Vec<LlmProfile>, DbError> {
let rows = sqlx::query_as::<_, LlmProfile>(&format!(
- "SELECT {PROFILE_COLUMNS} FROM llm_profiles ORDER BY engine, is_default DESC, priority, created_at, id"
+ "SELECT {PROFILE_COLUMNS} FROM llm_profiles WHERE space_id = ? ORDER BY engine, is_default DESC, priority, created_at, id"
))
+ .bind(space.as_str())
.fetch_all(&self.pool)
.await?;
Ok(rows)
@@ -65,18 +76,19 @@ impl Database {
}
/// Fails with a unique-constraint error on a duplicate name or home dir.
- pub async fn create_profile(&self, input: &NewLlmProfile) -> Result<LlmProfile, DbError> {
+ pub async fn create_profile(&self, space: &SpaceId, input: &NewLlmProfile) -> Result<LlmProfile, DbError> {
let id = format!("prf_{}", Uuid::new_v4().simple());
let mut tx = self.pool.begin().await?;
if input.is_default {
- sqlx::query("UPDATE llm_profiles SET is_default = 0 WHERE engine = ?")
+ sqlx::query("UPDATE llm_profiles SET is_default = 0 WHERE engine = ? AND space_id = ?")
.bind(&input.engine)
+ .bind(space.as_str())
.execute(&mut *tx)
.await?;
}
sqlx::query(
- "INSERT INTO llm_profiles (id, engine, name, kind, home_dir, priority, enabled, is_default)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+ "INSERT INTO llm_profiles (id, engine, name, kind, home_dir, priority, enabled, is_default, space_id)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(&id)
.bind(&input.engine)
@@ -86,6 +98,7 @@ impl Database {
.bind(input.priority)
.bind(input.enabled)
.bind(input.is_default)
+ .bind(space.as_str())
.execute(&mut *tx)
.await?;
tx.commit().await?;
@@ -104,8 +117,9 @@ impl Database {
};
let mut tx = self.pool.begin().await?;
if patch.is_default == Some(true) && !existing.is_default {
- sqlx::query("UPDATE llm_profiles SET is_default = 0 WHERE engine = ?")
+ sqlx::query("UPDATE llm_profiles SET is_default = 0 WHERE engine = ? AND space_id = ?")
.bind(&existing.engine)
+ .bind(&existing.space_id)
.execute(&mut *tx)
.await?;
sqlx::query("UPDATE llm_profiles SET is_default = 1 WHERE id = ?")
@@ -125,7 +139,7 @@ impl Database {
}
/// Deletes a profile, its key and state. Kwants bound to it go back to the engine default,
- /// and a deleted default hands that role to the system profile. Never touches the home dir.
+ /// and a deleted default hands that role to the space's system profile. Never touches the home dir.
pub async fn delete_profile(&self, id: &str) -> Result<bool, DbError> {
let Some(existing) = self.get_profile(id).await? else {
return Ok(false);
@@ -141,7 +155,7 @@ impl Database {
}
if existing.is_default {
sqlx::query("UPDATE llm_profiles SET is_default = 1 WHERE id = ?")
- .bind(system_profile_id(&existing.engine))
+ .bind(system_profile_id_in(&SpaceId::new(&existing.space_id), &existing.engine))
.execute(&mut *tx)
.await?;
}
@@ -243,21 +257,30 @@ impl Database {
pub async fn list_kwant_bindings(
&self,
+ space: &SpaceId,
) -> Result<HashMap<String, (Option<String>, bool)>, DbError> {
let rows: Vec<(String, Option<String>, bool)> =
- sqlx::query_as("SELECT id, profile_id, profile_failover FROM kwants")
+ sqlx::query_as("SELECT id, profile_id, profile_failover FROM kwants WHERE space_id = ?")
+ .bind(space.as_str())
.fetch_all(&self.pool)
.await?;
Ok(rows.into_iter().map(|(id, p, f)| (id, (p, f))).collect())
}
/// `profile_id`: `None` leaves it, `Some(None)` clears it. `failover`: `None` leaves it.
+ /// Fails with [`DbError::OtherSpace`] for a profile outside the kwant's space.
pub async fn set_kwant_binding(
&self,
kwant_id: &str,
profile_id: Option<Option<&str>>,
failover: Option<bool>,
) -> Result<(), DbError> {
+ if let Some(Some(profile)) = profile_id {
+ let kwant_space = self.space_of_kwant(kwant_id).await?;
+ if kwant_space.is_none() || self.space_of_profile(profile).await? != kwant_space {
+ return Err(DbError::OtherSpace("that account belongs to another space".into()));
+ }
+ }
if let Some(profile_id) = profile_id {
sqlx::query("UPDATE kwants SET profile_id = ? WHERE id = ?")
.bind(profile_id)
@@ -275,9 +298,9 @@ impl Database {
Ok(())
}
- pub async fn kwant_views(&self) -> Result<Vec<KwantView>, DbError> {
- let kwants = self.list_kwants().await?;
- let mut bindings = self.list_kwant_bindings().await?;
+ pub async fn kwant_views(&self, space: &SpaceId) -> Result<Vec<KwantView>, DbError> {
+ let kwants = self.list_kwants(space).await?;
+ let mut bindings = self.list_kwant_bindings(space).await?;
Ok(kwants
.into_iter()
.map(|kwant| {
diff --git a/src/db/skills.rs b/src/db/skills.rs
index 28747944..9918a000 100644
--- a/src/db/skills.rs
+++ b/src/db/skills.rs
@@ -2,6 +2,7 @@
//! from something that worked (it is stored `pending`), the user reviews and enables it, and only
//! enabled skills ever reach a prompt. A skill is text only: it has no tool list and grants nothing.
+use super::spaces::SpaceId;
use super::{Database, DbError};
use chrono::{DateTime, Utc};
use serde::Serialize;
@@ -39,6 +40,8 @@ pub struct Skill {
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub reviewed_at: Option<DateTime<Utc>>,
+ /// Shared skills (`kwant_id` = `None`) are shared within this space only.
+ pub space_id: String,
}
#[derive(Debug, PartialEq)]
@@ -194,23 +197,30 @@ impl Database {
.await?)
}
- /// Skills, newest first; `kwant_id` also matches the shared ones.
- pub async fn list_skills(&self, kwant_id: Option<&str>, status: Option<&str>) -> Result<Vec<Skill>, DbError> {
+ /// The space's skills, newest first; `kwant_id` also matches the shared ones.
+ pub async fn list_skills(
+ &self,
+ space: &SpaceId,
+ kwant_id: Option<&str>,
+ status: Option<&str>,
+ ) -> Result<Vec<Skill>, DbError> {
Ok(sqlx::query_as::<_, Skill>(
"SELECT * FROM skills
- WHERE (?1 IS NULL OR kwant_id = ?1 OR kwant_id IS NULL) AND (?2 IS NULL OR status = ?2)
+ WHERE space_id = ?3 AND (?1 IS NULL OR kwant_id = ?1 OR kwant_id IS NULL) AND (?2 IS NULL OR status = ?2)
ORDER BY updated_at DESC LIMIT 500",
)
.bind(kwant_id)
.bind(status)
+ .bind(space.as_str())
.fetch_all(&self.pool)
.await?)
}
- /// The enabled skills `kwant_id` may use: its own and the shared ones, by name.
+ /// The enabled skills `kwant_id` may use: its own and the ones shared in its space, by name.
pub async fn enabled_skills_for(&self, kwant_id: &str) -> Result<Vec<Skill>, DbError> {
Ok(sqlx::query_as::<_, Skill>(
- "SELECT * FROM skills WHERE status = 'enabled' AND (kwant_id = ? OR kwant_id IS NULL) ORDER BY name",
+ "SELECT * FROM skills WHERE status = 'enabled' AND (kwant_id = ?1 OR kwant_id IS NULL)
+ AND space_id = (SELECT space_id FROM kwants WHERE id = ?1) ORDER BY name",
)
.bind(kwant_id)
.fetch_all(&self.pool)
@@ -218,10 +228,11 @@ impl Database {
}
/// The live (enabled or disabled) skill called `name` for this agent, if any.
- async fn live_skill(&self, kwant_id: Option<&str>, name: &str) -> Result<Option<Skill>, DbError> {
+ async fn live_skill(&self, space: &SpaceId, kwant_id: Option<&str>, name: &str) -> Result<Option<Skill>, DbError> {
Ok(sqlx::query_as::<_, Skill>(
- "SELECT * FROM skills WHERE IFNULL(kwant_id, '') = IFNULL(?, '') AND name = ? AND status IN ('enabled', 'disabled')",
+ "SELECT * FROM skills WHERE space_id = ? AND IFNULL(kwant_id, '') = IFNULL(?, '') AND name = ? AND status IN ('enabled', 'disabled')",
)
+ .bind(space.as_str())
.bind(kwant_id)
.bind(name)
.fetch_optional(&self.pool)
@@ -232,7 +243,8 @@ impl Database {
/// revision of that skill; proposing again before review rewrites the waiting proposal.
pub async fn propose_skill(&self, kwant_id: &str, text: SkillText) -> Result<Skill, SkillError> {
let now = Utc::now();
- let replaces = self.live_skill(Some(kwant_id), &text.name).await?.map(|s| s.id);
+ let space = self.space_of_kwant(kwant_id).await?.ok_or(SkillError::NotFound)?;
+ let replaces = self.live_skill(&space, Some(kwant_id), &text.name).await?.map(|s| s.id);
let waiting = sqlx::query_as::<_, Skill>(
"SELECT * FROM skills WHERE status = 'pending' AND kwant_id = ? AND name = ? ORDER BY created_at DESC LIMIT 1",
)
@@ -260,8 +272,8 @@ impl Database {
}
let id = Uuid::new_v4().to_string();
sqlx::query(
- "INSERT INTO skills (id, kwant_id, name, description, body, status, source, proposed_by, replaces_id, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, 'pending', 'agent', ?, ?, ?, ?)",
+ "INSERT INTO skills (id, kwant_id, name, description, body, status, source, proposed_by, replaces_id, created_at, updated_at, space_id)
+ VALUES (?, ?, ?, ?, ?, 'pending', 'agent', ?, ?, ?, ?, ?)",
)
.bind(&id)
.bind(kwant_id)
@@ -272,21 +284,29 @@ impl Database {
.bind(&replaces)
.bind(now)
.bind(now)
+ .bind(space.as_str())
.execute(&self.pool)
.await?;
self.get_skill(&id).await?.ok_or(SkillError::NotFound)
}
- /// A skill the user wrote; it is enabled at once (the user is the reviewer).
- pub async fn create_user_skill(&self, kwant_id: Option<&str>, text: SkillText) -> Result<Skill, SkillError> {
- if self.live_skill(kwant_id, &text.name).await?.is_some() {
+ /// A skill the user wrote; it is enabled at once (the user is the reviewer). `kwant_id` must
+ /// be one of the space's kwants.
+ pub async fn create_user_skill(
+ &self,
+ space: &SpaceId,
+ kwant_id: Option<&str>,
+ text: SkillText,
+ ) -> Result<Skill, SkillError> {
+ self.check_skill_owner(space, kwant_id).await?;
+ if self.live_skill(space, kwant_id, &text.name).await?.is_some() {
return Err(SkillError::Conflict(format!("a skill called {} already exists", text.name)));
}
let id = Uuid::new_v4().to_string();
let now = Utc::now();
sqlx::query(
- "INSERT INTO skills (id, kwant_id, name, description, body, status, source, created_at, updated_at, reviewed_at)
- VALUES (?, ?, ?, ?, ?, 'enabled', 'user', ?, ?, ?)",
+ "INSERT INTO skills (id, kwant_id, name, description, body, status, source, created_at, updated_at, reviewed_at, space_id)
+ VALUES (?, ?, ?, ?, ?, 'enabled', 'user', ?, ?, ?, ?)",
)
.bind(&id)
.bind(kwant_id)
@@ -296,11 +316,22 @@ impl Database {
.bind(now)
.bind(now)
.bind(now)
+ .bind(space.as_str())
.execute(&self.pool)
.await?;
self.get_skill(&id).await?.ok_or(SkillError::NotFound)
}
+ /// A skill's owner, when it has one, must be a kwant in the skill's space.
+ async fn check_skill_owner(&self, space: &SpaceId, kwant_id: Option<&str>) -> Result<(), SkillError> {
+ match kwant_id {
+ Some(id) if !self.kwants_in_space(space, &[id]).await? => {
+ Err(SkillError::Invalid("that agent is in another space".into()))
+ }
+ _ => Ok(()),
+ }
+ }
+
/// Enables a pending skill (with the user's edits, if any); the skill it revises is superseded.
pub async fn approve_skill(&self, id: &str, edit: &SkillEdit) -> Result<Skill, SkillError> {
let skill = self.get_skill(id).await?.ok_or(SkillError::NotFound)?;
@@ -309,6 +340,7 @@ impl Database {
}
let text = merged_text(&skill, edit)?;
let kwant_id = edit.kwant_id.clone().unwrap_or(skill.kwant_id.clone());
+ self.check_skill_owner(&SpaceId::new(&skill.space_id), kwant_id.as_deref()).await?;
let now = Utc::now();
let mut tx = self.pool.begin().await?;
// The revised skill steps aside; any other live skill with the target name blocks approval
@@ -320,8 +352,9 @@ impl Database {
.await?;
}
let clash: Option<(String,)> = sqlx::query_as(
- "SELECT id FROM skills WHERE IFNULL(kwant_id, '') = IFNULL(?, '') AND name = ? AND status IN ('enabled', 'disabled') AND id != ?",
+ "SELECT id FROM skills WHERE space_id = ? AND IFNULL(kwant_id, '') = IFNULL(?, '') AND name = ? AND status IN ('enabled', 'disabled') AND id != ?",
)
+ .bind(&skill.space_id)
.bind(&kwant_id)
.bind(&text.name)
.bind(id)
@@ -376,6 +409,7 @@ impl Database {
}
let text = merged_text(&skill, edit)?;
let kwant_id = edit.kwant_id.clone().unwrap_or(skill.kwant_id.clone());
+ self.check_skill_owner(&SpaceId::new(&skill.space_id), kwant_id.as_deref()).await?;
let res = sqlx::query("UPDATE skills SET kwant_id = ?, name = ?, description = ?, body = ?, updated_at = ? WHERE id = ?")
.bind(&kwant_id)
.bind(&text.name)
diff --git a/src/db/spaces.rs b/src/db/spaces.rs
index 9120cbb9..ba1cada3 100644
--- a/src/db/spaces.rs
+++ b/src/db/spaces.rs
@@ -1,5 +1,6 @@
-//! 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.
+//! Spaces: the `spaces` table and a `space_id` on every top-level row (S0), and the lookups that
+//! keep each space to itself (S1). Lists and lookups that could reach into another space take a
+//! required [`SpaceId`], so a caller that hasn't decided its space doesn't compile.
//!
//! 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
@@ -9,13 +10,77 @@
//! Default space exists: its inserts get the column default and its queries ignore the column.
use super::{Database, DbError};
-use sqlx::{Connection, SqliteConnection};
+use serde::{Deserialize, Serialize};
+use sqlx::{Connection, FromRow, 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";
+/// Where a space keeps its files (team work folders, sandboxes). The Default space keeps the
+/// data dir itself, so existing folders stay where they are; others get `spaces/<id>`, with
+/// anything but ASCII letters, digits, `_` and `-` in the id replaced.
+pub fn space_data_dir(data_dir: &std::path::Path, space: &SpaceId) -> std::path::PathBuf {
+ if space.is_default() {
+ return data_dir.to_path_buf();
+ }
+ let safe: String = space
+ .as_str()
+ .chars()
+ .map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' })
+ .collect();
+ data_dir.join("spaces").join(safe)
+}
+
+/// The id of a space. Required by every list or lookup that could otherwise return rows from
+/// another space; build one from a row you already have (`kwant.space_id`, …) or, for requests
+/// that don't name a space yet, with [`SpaceId::default_space`].
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct SpaceId(String);
+
+impl SpaceId {
+ pub fn new(id: impl Into<String>) -> Self {
+ Self(id.into())
+ }
+
+ /// The Default space, which holds everything from before spaces.
+ pub fn default_space() -> Self {
+ Self(DEFAULT_SPACE_ID.to_string())
+ }
+
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+
+ pub fn is_default(&self) -> bool {
+ self.0 == DEFAULT_SPACE_ID
+ }
+}
+
+impl std::fmt::Display for SpaceId {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+/// Serde default for the `space_id` field of rows read from older JSON.
+pub fn default_space_id() -> String {
+ DEFAULT_SPACE_ID.to_string()
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, FromRow, PartialEq)]
+pub struct Space {
+ pub id: String,
+ pub name: String,
+ pub icon: String,
+ pub color: Option<String>,
+ pub sort: i64,
+ pub archived_at: Option<chrono::DateTime<chrono::Utc>>,
+ pub created_at: Option<chrono::DateTime<chrono::Utc>>,
+}
+
/// `PRAGMA user_version` once the spaces schema is in place.
pub const SPACES_SCHEMA_VERSION: i64 = 1;
@@ -307,3 +372,146 @@ async fn foreign_key_violations(conn: &mut SqliteConnection) -> Result<HashMap<(
}
Ok(counts)
}
+
+/// What [`Database::create_space`] needs. There's no API for it before S2; tests and the
+/// later `/api/spaces` call it.
+#[derive(Debug, Clone)]
+pub struct NewSpace {
+ pub name: String,
+ pub icon: String,
+ pub color: Option<String>,
+ /// This machine's switch in the new space, for every engine.
+ pub this_machine_enabled: bool,
+}
+
+impl Database {
+ /// Fails startup when the spaces migration hasn't run: S1 queries need `space_id`.
+ pub(super) async fn require_spaces_schema(&self, migration: &SpacesMigration) -> Result<(), DbError> {
+ if self.schema_version().await? >= SPACES_SCHEMA_VERSION {
+ return Ok(());
+ }
+ let why = match migration {
+ SpacesMigration::Skipped { reason } => reason.clone(),
+ _ => "unknown".into(),
+ };
+ Err(DbError::Migration(format!(
+ "kwnt can't start: the database is still on the schema from before spaces, and this \
+ version needs spaces ({why}). Nothing was changed. Fix the cause and start kwnt again, \
+ or run the previous kwnt release, which still works on this database."
+ )))
+ }
+
+ /// One #general per space, as a unique index. A database that already has two channels called
+ /// "general" in one space keeps working without the index (the old app never stopped a user
+ /// creating a second one); [`Database::create_channel_in`] still refuses new duplicates.
+ /// Returns whether the index is in place.
+ pub(super) async fn ensure_one_general(&self) -> Result<bool, DbError> {
+ let dupes: Vec<(String, i64)> = sqlx::query_as(
+ "SELECT space_id, COUNT(*) FROM channels WHERE name = 'general' GROUP BY space_id HAVING COUNT(*) > 1",
+ )
+ .fetch_all(&self.pool)
+ .await?;
+ if !dupes.is_empty() {
+ tracing::warn!(
+ spaces = ?dupes,
+ "Several #general channels in one space; not adding the one-#general rule until they're renamed"
+ );
+ return Ok(false);
+ }
+ sqlx::query("CREATE UNIQUE INDEX IF NOT EXISTS channels_one_general ON channels (space_id) WHERE name = 'general'")
+ .execute(&self.pool)
+ .await?;
+ Ok(true)
+ }
+
+ /// A new, empty space with its own This machine row per engine (the space's default for
+ /// each engine). Its #general and bots come with S2's create flow.
+ pub async fn create_space(&self, input: &NewSpace) -> Result<Space, DbError> {
+ let id = SpaceId::new(format!("spc_{}", uuid::Uuid::new_v4().simple()));
+ let mut tx = self.pool.begin().await?;
+ sqlx::query("INSERT INTO spaces (id, name, icon, color, sort) VALUES (?, ?, ?, ?, (SELECT IFNULL(MAX(sort), 0) + 1 FROM spaces))")
+ .bind(id.as_str())
+ .bind(input.name.trim())
+ .bind(&input.icon)
+ .bind(&input.color)
+ .execute(&mut *tx)
+ .await?;
+ for engine in super::profiles::PROFILE_ENGINES {
+ sqlx::query(
+ "INSERT INTO llm_profiles (id, engine, name, kind, home_dir, priority, enabled, is_default, space_id)
+ VALUES (?, ?, 'This machine', 'system', NULL, 0, ?, 1, ?)",
+ )
+ .bind(super::profiles::system_profile_id_in(&id, engine))
+ .bind(engine)
+ .bind(input.this_machine_enabled)
+ .bind(id.as_str())
+ .execute(&mut *tx)
+ .await?;
+ }
+ tx.commit().await?;
+ self.get_space(&id).await?.ok_or(DbError::Sqlx(sqlx::Error::RowNotFound))
+ }
+
+ pub async fn get_space(&self, id: &SpaceId) -> Result<Option<Space>, DbError> {
+ Ok(sqlx::query_as::<_, Space>("SELECT * FROM spaces WHERE id = ?")
+ .bind(id.as_str())
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ pub async fn list_spaces(&self) -> Result<Vec<Space>, DbError> {
+ Ok(sqlx::query_as::<_, Space>("SELECT * FROM spaces ORDER BY sort, created_at, id")
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ async fn space_of(&self, sql: &str, id: &str) -> Result<Option<SpaceId>, DbError> {
+ let row: Option<(String,)> = sqlx::query_as(sql).bind(id).fetch_optional(&self.pool).await?;
+ Ok(row.map(|(s,)| SpaceId(s)))
+ }
+
+ pub async fn space_of_kwant(&self, id: &str) -> Result<Option<SpaceId>, DbError> {
+ self.space_of("SELECT space_id FROM kwants WHERE id = ?", id).await
+ }
+
+ pub async fn space_of_channel(&self, id: &str) -> Result<Option<SpaceId>, DbError> {
+ self.space_of("SELECT space_id FROM channels WHERE id = ?", id).await
+ }
+
+ pub async fn space_of_team(&self, id: &str) -> Result<Option<SpaceId>, DbError> {
+ self.space_of("SELECT space_id FROM teams WHERE id = ?", id).await
+ }
+
+ pub async fn space_of_profile(&self, id: &str) -> Result<Option<SpaceId>, DbError> {
+ self.space_of("SELECT space_id FROM llm_profiles WHERE id = ?", id).await
+ }
+
+ pub async fn space_of_mcp_server(&self, id: &str) -> Result<Option<SpaceId>, DbError> {
+ self.space_of("SELECT space_id FROM mcp_servers WHERE id = ?", id).await
+ }
+
+ /// The space of whatever an event or chat id names: a channel, a kwant (its direct chat),
+ /// a thread (its kwant's space) or a team.
+ pub async fn space_of_context(&self, id: &str) -> Result<Option<SpaceId>, DbError> {
+ self.space_of(
+ "SELECT space_id FROM channels WHERE id = ?1
+ UNION ALL SELECT space_id FROM kwants WHERE id = ?1
+ UNION ALL SELECT k.space_id FROM threads t JOIN kwants k ON k.id = t.kwant_id WHERE t.id = ?1
+ UNION ALL SELECT space_id FROM teams WHERE id = ?1
+ LIMIT 1",
+ id,
+ )
+ .await
+ }
+
+ /// Whether every one of `kwant_ids` is a kwant in `space`. Used before a write links kwants
+ /// to a channel, team or routine, so nothing ever mixes two spaces.
+ pub async fn kwants_in_space(&self, space: &SpaceId, kwant_ids: &[&str]) -> Result<bool, DbError> {
+ for id in kwant_ids {
+ if self.space_of_kwant(id).await?.as_ref() != Some(space) {
+ return Ok(false);
+ }
+ }
+ Ok(true)
+ }
+}
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index 040927dc..62d6c3b6 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -992,6 +992,7 @@ mod tests {
#[test]
fn test_build_cli_prompt_with_history() {
let kwant = Kwant {
+ space_id: crate::db::spaces::DEFAULT_SPACE_ID.into(),
id: "k1".into(),
name: "Architect".into(),
title: "Lead".into(),
@@ -1062,6 +1063,7 @@ mod tests {
#[test]
fn test_build_cli_prompt_without_history() {
let kwant = Kwant {
+ space_id: crate::db::spaces::DEFAULT_SPACE_ID.into(),
id: "k1".into(),
name: "Architect".into(),
title: "Lead".into(),
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index c33cf210..5e53830f 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -207,11 +207,13 @@ pub async fn first_ollama_model(root: &str) -> Option<String> {
/// The model families a turn can run on right now, for routing: a family counts when its API key
/// or CLI passed its check (see [`engines`]), or when `profile_engines` has a usable profile for
-/// it. Empty when nothing can run; there is no made-up fallback.
+/// it. `host_off` families (This machine off in the space) only count through `profile_engines`.
+/// Empty when nothing can run; there is no made-up fallback.
pub async fn detect_available_models(
db: &crate::db::Database,
engines: &engines::EngineRegistry,
profile_engines: &std::collections::HashSet<crate::profiles::Engine>,
+ host_off: &std::collections::HashSet<crate::profiles::Engine>,
) -> Vec<ModelDescriptor> {
use crate::profiles::Engine;
use engines::{EngineId, SystemRoute};
@@ -237,7 +239,9 @@ pub async fn detect_available_models(
let key = db.get_setting(family.key_setting()).await.ok().flatten();
let route = engines::system_route(engines, family.as_str(), key, find_cli_binary);
let engine = match &route {
- Ok(SystemRoute::Api { engine, .. }) | Ok(SystemRoute::Cli { engine, .. }) => Some(*engine),
+ Ok(SystemRoute::Api { engine, .. }) | Ok(SystemRoute::Cli { engine, .. }) if !host_off.contains(&family) => {
+ Some(*engine)
+ }
_ => None,
};
if engine.is_none() && !profile_engines.contains(&family) {
diff --git a/src/main.rs b/src/main.rs
index 5534cfd7..86a47c95 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -260,7 +260,7 @@ fn print_status(config: &Config) {
async fn print_agents(config: &Config) -> Result<(), Box<dyn std::error::Error>> {
let db = Database::init(&config.data_dir).await?;
- let kwants = db.list_kwants().await?;
+ let kwants = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await?;
println!(
"{:<16} {:<32} {:<8} MODEL",
"NAME", "TITLE", "DRIVER"
@@ -280,7 +280,7 @@ async fn print_agents(config: &Config) -> Result<(), Box<dyn std::error::Error>>
async fn print_teams(config: &Config) -> Result<(), Box<dyn std::error::Error>> {
let db = Database::init(&config.data_dir).await?;
- let teams = db.list_teams().await?;
+ let teams = db.list_teams(&kwnt::db::spaces::SpaceId::default_space()).await?;
println!("{:<24} {:<8} WORKSPACE", "TEAM", "MEMBERS");
if teams.is_empty() {
println!("(no teams)");
@@ -298,7 +298,7 @@ async fn print_teams(config: &Config) -> Result<(), Box<dyn std::error::Error>>
async fn print_channels(config: &Config) -> Result<(), Box<dyn std::error::Error>> {
let db = Database::init(&config.data_dir).await?;
- let channels = db.list_channels().await?;
+ let channels = db.list_channels(&kwnt::db::spaces::SpaceId::default_space()).await?;
println!("{:<24} {:<10} DESCRIPTION", "CHANNEL", "ROUTING");
if channels.is_empty() {
println!("(no channels)");
diff --git a/src/profiles/mod.rs b/src/profiles/mod.rs
index 2e751a2d..72073c0d 100644
--- a/src/profiles/mod.rs
+++ b/src/profiles/mod.rs
@@ -446,6 +446,7 @@ mod tests {
fn profile(id: &str, engine: &str, kind: &str, priority: i64, default: bool) -> LlmProfile {
LlmProfile {
+ space_id: crate::db::spaces::DEFAULT_SPACE_ID.into(),
id: id.into(),
engine: engine.into(),
name: id.into(),
diff --git a/src/router/team.rs b/src/router/team.rs
index 0ffe914f..b1d4134d 100644
--- a/src/router/team.rs
+++ b/src/router/team.rs
@@ -506,6 +506,7 @@ mod tests {
fn make_test_fixture() -> (Team, Vec<Kwant>) {
let team = Team {
+ space_id: crate::db::spaces::DEFAULT_SPACE_ID.into(),
id: "team-1".into(),
name: "core-engineering".into(),
description: Some("Architecture & DevOps".into()),
@@ -519,6 +520,7 @@ mod tests {
};
let members = vec![
Kwant {
+ space_id: crate::db::spaces::DEFAULT_SPACE_ID.into(),
id: "kwant-1".into(),
name: "Architect".into(),
title: "Systems Architect".into(),
@@ -534,6 +536,7 @@ mod tests {
created_at: None,
},
Kwant {
+ space_id: crate::db::spaces::DEFAULT_SPACE_ID.into(),
id: "kwant-2".into(),
name: "DevOps".into(),
title: "DevOps Engineer".into(),
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 0a7e2f4a..f3a27cf1 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -413,7 +413,11 @@ async fn call_tool(
let Some(query) = str_arg("query") else {
return ("query is required".into(), true);
};
- let channels = db.list_channels().await.unwrap_or_default();
+ // Only the agent's own space, #general included
+ let Ok(Some(space)) = db.space_of_kwant(&scope.kwant_id).await else {
+ return ("Search failed.".into(), true);
+ };
+ let channels = db.list_channels(&space).await.unwrap_or_default();
let visible = visible_channels(&channels, &scope.kwant_id);
let channel_id = str_arg("channel_id").map(str::to_string);
if let Some(c) = &channel_id {
@@ -431,7 +435,7 @@ async fn call_tool(
.unwrap_or(10)
.clamp(1, AGENT_SEARCH_LIMIT),
};
- match db.search_messages(query, &filter).await {
+ match db.search_messages(&space, query, &filter).await {
Ok(hits) => (hits_as_text(&hits), false),
Err(e) => {
tracing::warn!(error = %e, "agent search failed");
@@ -567,12 +571,22 @@ pub struct SearchQuery {
pub limit: Option<i64>,
}
-/// `GET /api/search?q=&channel_id=&kwant_id=&limit=`.
+/// `GET /api/search?q=&channel_id=&kwant_id=&limit=`, in the channel's or kwant's space, else
+/// the Default space.
pub async fn search(State(state): State<AppState>, Query(q): Query<SearchQuery>) -> Response {
let text = q.q.unwrap_or_default();
if store::fts_query(&text).is_none() {
return error(StatusCode::BAD_REQUEST, "q needs at least one word");
}
+ let space = match (q.channel_id.as_deref().filter(|s| !s.is_empty()), q.kwant_id.as_deref().filter(|s| !s.is_empty())) {
+ (Some(c), _) => state.db.space_of_channel(c).await,
+ (None, Some(k)) => state.db.space_of_kwant(k).await,
+ (None, None) => Ok(None),
+ };
+ let space = match space {
+ Ok(s) => s.unwrap_or_else(super::routes::request_space),
+ Err(_) => return internal(),
+ };
let filter = SearchFilter {
channel_id: q.channel_id.filter(|s| !s.is_empty()),
kwant_id: q.kwant_id.filter(|s| !s.is_empty()),
@@ -580,7 +594,7 @@ pub async fn search(State(state): State<AppState>, Query(q): Query<SearchQuery>)
allowed_direct: None,
limit: q.limit.unwrap_or(20).clamp(1, MAX_SEARCH_LIMIT),
};
- match state.db.search_messages(&text, &filter).await {
+ match state.db.search_messages(&space, &text, &filter).await {
Ok(hits) => Json(hits).into_response(),
Err(e) => {
tracing::warn!(error = %e, "search failed");
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 911754da..1e7bf849 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -5,6 +5,7 @@
use super::routes::{scope_for, try_kwant_turn, TurnOpts};
use super::AppState;
use crate::db::models::{Kwant, MessageExtra, NewMessage};
+use crate::db::spaces::SpaceId;
use crate::db::threads::{Delegation, NewDelegation, Thread, MAX_TASK_CHARS};
use crate::drivers::RuntimeEvent;
use axum::{
@@ -152,6 +153,11 @@ pub async fn start(state: &AppState, req: StartRequest) -> Result<Delegation, (S
if req.origin_depth + 1 > MAX_DEPTH {
return bad("This task was already delegated; it can't be delegated further.");
}
+ // Never across spaces, with or without a member list
+ if req.specialist.space_id != req.lead.space_id {
+ return Err((StatusCode::FORBIDDEN, format!("{} isn't in this space.", req.specialist.name)));
+ }
+ let space = SpaceId::new(&req.lead.space_id);
if let Some(allowed) = &req.allowed {
if !allowed.iter().any(|id| id == &req.specialist.id) {
return Err((StatusCode::FORBIDDEN, format!("{} isn't in this chat.", req.specialist.name)));
@@ -165,8 +171,11 @@ pub async fn start(state: &AppState, req: StartRequest) -> Result<Delegation, (S
// The origin must exist, and a direct chat or thread origin must be the lead's own
let team_id = if let Some(cid) = &o.channel_id {
let channel = state.db.get_channel(cid).await.ok().flatten().ok_or((StatusCode::NOT_FOUND, "channel not found".into()))?;
+ if channel.space_id != space.as_str() {
+ return Err((StatusCode::NOT_FOUND, "channel not found".into()));
+ }
match channel.name.strip_prefix("team-") {
- Some(name) => state.db.list_teams().await.unwrap_or_default().into_iter().find(|t| t.name.eq_ignore_ascii_case(name)).map(|t| t.id),
+ Some(name) => state.db.list_teams(&space).await.unwrap_or_default().into_iter().find(|t| t.name.eq_ignore_ascii_case(name)).map(|t| t.id),
None => None,
}
} else if let Some(kid) = &o.kwant_id {
@@ -625,10 +634,11 @@ pub async fn tool_delegate(state: &AppState, scope: &super::continuity::SelfScop
};
let to = args["to"].as_str().map(str::trim).unwrap_or("").trim_start_matches('@');
let task = args["task"].as_str().unwrap_or("").to_string();
- let kwants = state.db.list_kwants().await.unwrap_or_default();
- let Some(lead) = kwants.iter().find(|k| k.id == scope.kwant_id).cloned() else {
+ let Some(lead) = state.db.get_kwant(&scope.kwant_id).await.ok().flatten() else {
return ("Unknown agent.".into(), true);
};
+ // Only the lead's own space, even when the chat has no member list
+ let kwants = state.db.list_kwants(&SpaceId::new(&lead.space_id)).await.unwrap_or_default();
let pool: Vec<&Kwant> = if origin.member_ids.is_empty() {
kwants.iter().filter(|k| k.id != lead.id).collect()
} else {
diff --git a/src/server/engine_routes.rs b/src/server/engine_routes.rs
index 3737dcbc..5e87cead 100644
--- a/src/server/engine_routes.rs
+++ b/src/server/engine_routes.rs
@@ -19,7 +19,7 @@ pub struct EnginesResponse {
/// The cached checks; never waits on one. Engines not checked yet show as "checking". Stale
/// profile sign-in checks run in the background for the next call.
pub async fn list(State(state): State<AppState>) -> Json<EnginesResponse> {
- let engines = with_accounts(&state, state.engines.snapshot()).await;
+ let engines = with_accounts(&state, &super::routes::request_space(), state.engines.snapshot()).await;
let bg = state.clone();
tokio::spawn(async move { profile_turn::refresh_sign_ins(&bg).await });
Json(EnginesResponse { engines })
@@ -35,7 +35,7 @@ pub async fn recheck_all(state: &AppState) -> Vec<EngineReport> {
load_disabled(state).await;
let env = probe_env(state).await;
let (engines, ()) = tokio::join!(state.engines.recheck(&env), profile_turn::refresh_sign_ins(state));
- with_accounts(state, engines).await
+ with_accounts(state, &super::routes::request_space(), engines).await
}
/// What the checks run with: Settings and the env, and Claude's sign-in config dir.
@@ -81,7 +81,7 @@ pub async fn set_enabled(
let env = probe_env(&state).await;
state.engines.recheck_one(id, &env).await;
}
- Ok(Json(EnginesResponse { engines: with_accounts(&state, state.engines.snapshot()).await }))
+ Ok(Json(EnginesResponse { engines: with_accounts(&state, &super::routes::request_space(), state.engines.snapshot()).await }))
}
/// Checks every engine in the background, so the first turns after startup see real status.
diff --git a/src/server/mcp_routes.rs b/src/server/mcp_routes.rs
index 64932717..0905fd01 100644
--- a/src/server/mcp_routes.rs
+++ b/src/server/mcp_routes.rs
@@ -31,7 +31,7 @@ fn db_err(e: DbError) -> ApiError {
/// Which kwants have each server off. A read failure shows no opt-outs rather than failing the list.
async fn opt_outs(state: &AppState) -> std::collections::HashMap<String, Vec<String>> {
- state.db.list_mcp_kwant_opt_outs().await.unwrap_or_else(|e| {
+ state.db.list_mcp_kwant_opt_outs(&super::routes::request_space()).await.unwrap_or_else(|e| {
tracing::warn!(error = %e, "could not read MCP kwant opt-outs");
Default::default()
})
@@ -46,7 +46,7 @@ async fn view(state: &AppState, server: &McpServer) -> McpServerView {
}
pub async fn list_servers(State(state): State<AppState>) -> ApiResult<Vec<McpServerView>> {
- let servers = state.db.list_mcp_servers().await.map_err(db_err)?;
+ let servers = state.db.list_mcp_servers(&super::routes::request_space()).await.map_err(db_err)?;
let mut statuses = mcp_oauth::statuses(&state).await;
let mut opt_outs = opt_outs(&state).await;
Ok(Json(
@@ -70,7 +70,7 @@ pub async fn get_server(State(state): State<AppState>, Path(id): Path<String>) -
pub async fn create_server(State(state): State<AppState>, Json(input): Json<McpServerInput>) -> ApiResult<McpServerView> {
let server = mcp::build_server(input, None).map_err(|m| err(StatusCode::BAD_REQUEST, m))?;
- let created = state.db.create_mcp_server(&server).await.map_err(db_err)?;
+ let created = state.db.create_mcp_server(&super::routes::request_space(), &server).await.map_err(db_err)?;
Ok(Json(McpServerView::from(&created)))
}
@@ -182,10 +182,11 @@ pub async fn set_kwant_servers(
Path(kwant_id): Path<String>,
Json(body): Json<AssignServers>,
) -> ApiResult<Value> {
- if state.db.get_kwant(&kwant_id).await.map_err(db_err)?.is_none() {
+ let Some(space) = state.db.space_of_kwant(&kwant_id).await.map_err(db_err)? else {
return Err(err(StatusCode::NOT_FOUND, "kwant not found"));
- }
- let known: Vec<String> = state.db.list_mcp_servers().await.map_err(db_err)?.into_iter().map(|s| s.id).collect();
+ };
+ // Only servers in the kwant's own space can be assigned to it
+ let known: Vec<String> = state.db.list_mcp_servers(&space).await.map_err(db_err)?.into_iter().map(|s| s.id).collect();
if let Some(unknown) = body.server_ids.iter().find(|id| !known.contains(id)) {
return Err(err(StatusCode::BAD_REQUEST, format!("unknown MCP server id '{unknown}'")));
}
diff --git a/src/server/profile_routes.rs b/src/server/profile_routes.rs
index 5e0a49df..185a1fe7 100644
--- a/src/server/profile_routes.rs
+++ b/src/server/profile_routes.rs
@@ -3,6 +3,7 @@
use super::AppState;
use crate::db::models::{LlmProfile, LlmProfilePatch, NewLlmProfile};
+use crate::db::spaces::SpaceId;
use crate::profiles::login::LoginView;
use crate::profiles::{
clean_key, clean_name, create_private_dir, managed_home, validate_user_home, Engine,
@@ -137,7 +138,7 @@ async fn load(state: &AppState, id: &str) -> Result<LlmProfile, Response> {
/// `GET /api/profiles`
pub async fn list(State(state): State<AppState>) -> Response {
- match state.db.list_profiles().await {
+ match state.db.list_profiles(&super::routes::request_space()).await {
Ok(profiles) => Json(views(&state, profiles).await).into_response(),
Err(e) => db_err(e),
}
@@ -183,16 +184,22 @@ pub async fn create(State(state): State<AppState>, Json(body): Json<CreateBody>)
("cli_home", None) => None,
_ => return err(StatusCode::BAD_REQUEST, "kind must be cli_home or api_key"),
};
- let all = match state.db.list_profiles().await {
+ let space = super::routes::request_space();
+ let all = match state.db.list_profiles(&space).await {
Ok(a) => a,
Err(e) => return db_err(e),
};
+ // Home folders stay unique across every space, so two spaces never share a sign-in
+ let mut everyone = Vec::new();
+ for s in state.db.list_spaces().await.unwrap_or_default() {
+ everyone.extend(state.db.list_profiles(&SpaceId::new(&s.id)).await.unwrap_or_default());
+ }
if all.iter().filter(|p| p.engine == engine.as_str()).count() >= MAX_PER_ENGINE {
return err(StatusCode::BAD_REQUEST, "too many profiles for this engine");
}
let home_dir = match (body.kind.as_str(), body.home_dir.as_deref()) {
("cli_home", Some(raw)) => {
- let others: Vec<String> = all
+ let others: Vec<String> = everyone
.iter()
.filter_map(|p| state.profiles.home_of(p))
.map(|h| h.to_string_lossy().into_owned())
@@ -219,7 +226,7 @@ pub async fn create(State(state): State<AppState>, Json(body): Json<CreateBody>)
enabled: body.enabled.unwrap_or(true),
is_default: body.is_default.unwrap_or(false),
};
- let profile = match state.db.create_profile(&input).await {
+ let profile = match state.db.create_profile(&space, &input).await {
Ok(p) => p,
Err(e) => return db_err(e),
};
diff --git a/src/server/profile_turn.rs b/src/server/profile_turn.rs
index 81519a0e..9164e14c 100644
--- a/src/server/profile_turn.rs
+++ b/src/server/profile_turn.rs
@@ -3,6 +3,7 @@
use super::AppState;
use crate::db::models::LlmProfile;
+use crate::db::spaces::SpaceId;
use crate::drivers::engines::{EngineAccount, EngineId, EngineReport, EngineStatus};
use crate::drivers::{find_cli_binary, resolve_driver_for_model, ApiDriver, CliDriver, Driver};
use std::collections::HashSet;
@@ -12,12 +13,12 @@ use crate::profiles::{
ProviderFailure, SignInBar,
};
-/// Every profile and what decides whether each can take a turn now, from the db and the
+/// The space's profiles and what decides whether each can take a turn now, from the db and the
/// cached sign-in checks (never waits on a check). `None` when the db can't be read.
-async fn accounts(state: &AppState) -> Option<(Vec<LlmProfile>, Availability)> {
+async fn accounts(state: &AppState, space: &SpaceId) -> Option<(Vec<LlmProfile>, Availability)> {
let db = &state.db;
let (Ok(profiles), Ok(states), Ok(with_key)) = (
- db.list_profiles().await,
+ db.list_profiles(space).await,
db.list_profile_states().await,
db.profile_ids_with_key().await,
) else {
@@ -32,14 +33,18 @@ async fn accounts(state: &AppState) -> Option<(Vec<LlmProfile>, Availability)> {
Some((profiles, avail))
}
-/// Profiles to try for a turn on `engine`, in order. Empty when the model has no profiles
-/// (e.g. Ollama) or the engine has none enabled: the turn then runs as before profiles.
+/// Profiles of the kwant's space to try for a turn on `engine`, in order. Empty when the model
+/// has no profiles (e.g. Ollama) or the engine has none enabled: the turn then runs on the
+/// host, unless [`host_off`] says This machine is off in that space.
pub async fn plan(state: &AppState, engine: Option<Engine>, kwant_id: &str) -> Vec<LlmProfile> {
let Some(engine) = engine else {
return Vec::new();
};
+ let Ok(Some(space)) = state.db.space_of_kwant(kwant_id).await else {
+ return Vec::new();
+ };
let (Some((profiles, avail)), Ok(binding)) =
- (accounts(state).await, state.db.get_kwant_binding(kwant_id).await)
+ (accounts(state, &space).await, state.db.get_kwant_binding(kwant_id).await)
else {
return Vec::new();
};
@@ -57,6 +62,19 @@ pub async fn plan(state: &AppState, engine: Option<Engine>, kwant_id: &str) -> V
.collect()
}
+/// Engines whose This machine profile is off in `space`. A turn on one of them never falls back
+/// to the host's own login or Settings key there; it needs one of the space's own accounts.
+pub async fn host_off(state: &AppState, space: &SpaceId) -> HashSet<Engine> {
+ let Ok(profiles) = state.db.list_profiles(space).await else {
+ return HashSet::new();
+ };
+ profiles
+ .iter()
+ .filter(|p| p.kind == "system" && !p.enabled)
+ .filter_map(|p| Engine::parse(&p.engine))
+ .collect()
+}
+
/// The engine a profile's turns run on: its family's API for a key, else its CLI. The system
/// profile runs on whichever host engine routing picks, so it has none of its own.
pub fn profile_engine(p: &LlmProfile) -> Option<EngineId> {
@@ -142,8 +160,8 @@ fn own_accounts<'a>(
/// would use: these engines can run even when the host's own CLI or key can't. Routing keeps
/// the lenient bar (an unchecked profile counts) so turns right after startup, before any
/// sign-in check, still reach a profile that is in fact signed in.
-pub async fn profile_engines(state: &AppState) -> HashSet<Engine> {
- let Some((profiles, avail)) = accounts(state).await else {
+pub async fn profile_engines(state: &AppState, space: &SpaceId) -> HashSet<Engine> {
+ let Some((profiles, avail)) = accounts(state, space).await else {
return HashSet::new();
};
[Engine::Claude, Engine::Codex, Engine::Grok]
@@ -154,7 +172,8 @@ pub async fn profile_engines(state: &AppState) -> HashSet<Engine> {
/// Whether `report`'s engine is ready and the account a kwant on it uses: the first of the
/// engine's accounts in failover order (the default first) that can take a turn, the system
-/// profile ("This machine") counting when the engine's own login is ready. Off ⇒ not ready.
+/// profile ("This machine") counting when the engine's own login is ready. Off ⇒ not ready, and
+/// This machine turned off means the host's own login doesn't count either.
pub fn readiness(
report: &EngineReport,
profiles: &[LlmProfile],
@@ -169,6 +188,8 @@ pub fn readiness(
return (host, None);
};
let system = |p: &&LlmProfile| p.kind == "system";
+ let host_off = profiles.iter().any(|p| system(&p) && p.engine == family.as_str() && !p.enabled);
+ let host = host && !host_off;
let picked = preference_order(profiles, family, None)
.into_iter()
.filter(|p| system(p) || profile_engine(p) == Some(report.id))
@@ -178,19 +199,14 @@ pub fn readiness(
} else {
avail.admits(p, now, SignInBar::SignedIn)
}
- })
- .or_else(|| {
- // This machine turned off as a profile still runs turns when nothing else does
- host.then(|| profiles.iter().find(|p| p.engine == family.as_str() && system(p)))
- .flatten()
});
let uses = picked.map(|p| EngineAccount { profile_id: p.id.clone(), label: p.name.clone() });
(host || uses.is_some(), uses)
}
-/// Fills in `ready` and `uses` on every report.
-pub async fn with_accounts(state: &AppState, mut reports: Vec<EngineReport>) -> Vec<EngineReport> {
- let accounts = accounts(state).await;
+/// Fills in `ready` and `uses` on every report, for `space`'s accounts.
+pub async fn with_accounts(state: &AppState, space: &SpaceId, mut reports: Vec<EngineReport>) -> Vec<EngineReport> {
+ let accounts = accounts(state, space).await;
let now = chrono::Utc::now();
for r in &mut reports {
let (ready, uses) = match &accounts {
@@ -212,9 +228,11 @@ pub async fn refresh_sign_ins(state: &AppState) {
if REFRESHING.swap(true, Ordering::AcqRel) {
return;
}
- if let Ok(profiles) = state.db.list_profiles().await {
- let keyed = super::profile_routes::keyed_ids(state, &profiles).await;
- state.profiles.statuses(&profiles, &keyed).await;
+ for space in state.db.list_spaces().await.unwrap_or_default() {
+ if let Ok(profiles) = state.db.list_profiles(&SpaceId::new(&space.id)).await {
+ let keyed = super::profile_routes::keyed_ids(state, &profiles).await;
+ state.profiles.statuses(&profiles, &keyed).await;
+ }
}
REFRESHING.store(false, Ordering::Release);
}
@@ -303,6 +321,7 @@ mod tests {
enabled: true,
is_default: default,
created_at: None,
+ space_id: "spc_default".into(),
}
}
@@ -435,13 +454,15 @@ mod tests {
}
#[test]
- fn host_ready_uses_this_machine_even_when_its_profile_is_off() {
+ fn this_machine_off_is_never_a_fallback_even_when_the_host_is_ready() {
let r = report(EngineId::Claude, true, EngineStatus::Ready);
let mut profiles = oleks();
profiles[0].enabled = false;
+ assert_eq!(readiness(&r, &profiles, &Availability::default(), now()), (false, None));
+ // Another account of the space still makes it ready
assert_eq!(
- uses(readiness(&r, &profiles, &Availability::default(), now())),
- (true, Some("This machine".into()))
+ uses(readiness(&r, &profiles, &signed_in(&["p_personal"]), now())),
+ (true, Some("Personal".into()))
);
// Ollama has no accounts: ready from its own check alone
let o = report(EngineId::Ollama, true, EngineStatus::Ready);
diff --git a/src/server/routes.rs b/src/server/routes.rs
index e92cffdd..b4618dc7 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2,6 +2,8 @@ use super::discussion;
use super::AppState;
use crate::broker::ApprovalDecision;
use crate::db::models::*;
+use crate::db::spaces::SpaceId;
+use crate::db::DbError;
use crate::drivers::{find_cli_binary, RoutingCandidate, RuntimeEvent, TurnInput};
use crate::router::{parse_mentions_with_lookup, TagMention, TeamDecision};
use axum::{
@@ -39,24 +41,44 @@ pub async fn laya_status(State(state): State<AppState>) -> impl IntoResponse {
Json(state.router.status())
}
+/// 400 for a write that would mix spaces, 409 for a clash, 500 otherwise.
+pub(crate) fn db_status(e: &DbError) -> StatusCode {
+ match e {
+ DbError::OtherSpace(_) => StatusCode::BAD_REQUEST,
+ DbError::Conflict(_) => StatusCode::CONFLICT,
+ _ => StatusCode::INTERNAL_SERVER_ERROR,
+ }
+}
+
+/// The space of a request that doesn't name one: Default, until `?space=` arrives (S2).
+pub(crate) fn request_space() -> SpaceId {
+ SpaceId::default_space()
+}
+
pub async fn list_kwants(
State(state): State<AppState>,
) -> Result<Json<Vec<KwantView>>, StatusCode> {
state
.db
- .kwant_views()
+ .kwant_views(&request_space())
.await
.map(Json)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
-/// Trims the name and rejects names that can't be @mentioned or clash with another kwant.
-async fn validate_kwant_name(state: &AppState, name: &mut String, own_id: Option<&str>) -> Result<(), StatusCode> {
+/// Trims the name and rejects names that can't be @mentioned or clash with another kwant in the
+/// space. Other spaces may use the same name.
+async fn validate_kwant_name(
+ state: &AppState,
+ space: &SpaceId,
+ name: &mut String,
+ own_id: Option<&str>,
+) -> Result<(), StatusCode> {
*name = name.trim().to_string();
if name.is_empty() || name.contains(char::is_whitespace) || name.contains('@') {
return Err(StatusCode::BAD_REQUEST);
}
- let kwants = state.db.list_kwants().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ let kwants = state.db.list_kwants(space).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if kwants.iter().any(|k| Some(k.id.as_str()) != own_id && k.name.eq_ignore_ascii_case(name)) {
return Err(StatusCode::CONFLICT);
}
@@ -97,9 +119,10 @@ pub struct UpdateKwantRequest {
binding: ProfileBinding,
}
-/// The pinned profile must exist and be for the engine of the kwant's model.
+/// The pinned profile must exist, be in the kwant's space and be for the engine of its model.
async fn check_binding(
state: &AppState,
+ space: &SpaceId,
binding: &ProfileBinding,
preferred_model: &str,
) -> Result<(), StatusCode> {
@@ -112,6 +135,9 @@ async fn check_binding(
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::BAD_REQUEST)?;
+ if profile.space_id != space.as_str() {
+ return Err(StatusCode::BAD_REQUEST);
+ }
let family = crate::router::parse_pin(preferred_model).family;
match family.as_deref().and_then(crate::profiles::Engine::parse) {
Some(engine) if engine.as_str() != profile.engine => Err(StatusCode::BAD_REQUEST),
@@ -132,7 +158,7 @@ async fn save_binding(
.db
.set_kwant_binding(kwant_id, profile_id, binding.profile_failover)
.await
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
+ .map_err(|e| db_status(&e))
}
async fn kwant_view_json(state: &AppState, id: &str) -> Result<Json<KwantView>, StatusCode> {
@@ -147,11 +173,12 @@ pub async fn create_kwant(
State(state): State<AppState>,
Json(mut payload): Json<CreateKwantRequest>,
) -> Result<Json<KwantView>, StatusCode> {
- validate_kwant_name(&state, &mut payload.base.name, None).await?;
- check_binding(&state, &payload.binding, &payload.base.preferred_model).await?;
+ let space = request_space();
+ validate_kwant_name(&state, &space, &mut payload.base.name, None).await?;
+ check_binding(&state, &space, &payload.binding, &payload.base.preferred_model).await?;
let kwant = state
.db
- .create_kwant(&payload.base)
+ .create_kwant(&space, &payload.base)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
save_binding(&state, &kwant.id, &payload.binding).await?;
@@ -163,8 +190,14 @@ pub async fn update_kwant(
Path(id): Path<String>,
Json(mut payload): Json<UpdateKwantRequest>,
) -> Result<Json<KwantView>, StatusCode> {
- validate_kwant_name(&state, &mut payload.base.name, Some(&id)).await?;
- check_binding(&state, &payload.binding, &payload.base.preferred_model).await?;
+ let space = state
+ .db
+ .space_of_kwant(&id)
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
+ .ok_or(StatusCode::NOT_FOUND)?;
+ validate_kwant_name(&state, &space, &mut payload.base.name, Some(&id)).await?;
+ check_binding(&state, &space, &payload.binding, &payload.base.preferred_model).await?;
match state.db.update_kwant(&id, &payload.base).await {
Ok(Some(_)) => {}
Ok(None) => return Err(StatusCode::NOT_FOUND),
@@ -177,7 +210,7 @@ pub async fn update_kwant(
pub async fn list_channels(State(state): State<AppState>) -> Result<Json<Vec<Channel>>, StatusCode> {
state
.db
- .list_channels()
+ .list_channels(&request_space())
.await
.map(Json)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
@@ -189,10 +222,10 @@ pub async fn create_channel(
) -> Result<Json<Channel>, StatusCode> {
state
.db
- .create_channel(&payload)
+ .create_channel(&request_space(), &payload)
.await
.map(Json)
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
+ .map_err(|e| db_status(&e))
}
#[derive(Debug, Deserialize)]
@@ -236,7 +269,7 @@ pub async fn list_messages(
pub async fn list_teams(State(state): State<AppState>) -> Result<Json<Vec<Team>>, StatusCode> {
state
.db
- .list_teams()
+ .list_teams(&request_space())
.await
.map(Json)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
@@ -248,10 +281,10 @@ pub async fn create_team(
) -> Result<Json<Team>, StatusCode> {
state
.db
- .create_team(&payload)
+ .create_team(&request_space(), &payload)
.await
.map(Json)
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
+ .map_err(|e| db_status(&e))
}
pub async fn get_team(
@@ -292,7 +325,7 @@ pub async fn update_team(
Ok(Json(team))
}
Ok(None) => Err(StatusCode::NOT_FOUND),
- Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
+ Err(e) => Err(db_status(&e)),
}
}
@@ -462,7 +495,9 @@ pub(super) async fn scope_for(
job: &super::turns::JobGuard,
delegation_depth: i64,
) -> Result<TurnScope, String> {
- let all_kwants = state.db.list_kwants().await.map_err(|_| "could not load agents".to_string())?;
+ // Teammates, the team and its folder all come from the kwant's own space
+ let space = SpaceId::new(&kwant.space_id);
+ let all_kwants = state.db.list_kwants(&space).await.map_err(|_| "could not load agents".to_string())?;
let channel = match &channel_id {
Some(id) => Some(
state.db.get_channel(id).await.ok().flatten().ok_or_else(|| "the chat's channel no longer exists".to_string())?,
@@ -473,7 +508,7 @@ pub(super) async fn scope_for(
Some(id) => Some(state.db.get_thread(id).await.ok().flatten().ok_or_else(|| "the thread no longer exists".to_string())?),
None => None,
};
- let teams = state.db.list_teams().await.unwrap_or_default();
+ let teams = state.db.list_teams(&space).await.unwrap_or_default();
let team = match (&thread, channel.as_ref().and_then(|c| c.name.strip_prefix("team-"))) {
(Some(t), _) => t.team_id.as_ref().and_then(|id| teams.iter().find(|x| &x.id == id).cloned()),
(None, Some(name)) => teams.iter().find(|t| t.name.eq_ignore_ascii_case(name)).cloned(),
@@ -490,8 +525,13 @@ pub(super) async fn scope_for(
let teammates: Vec<Kwant> = member_ids.iter().filter_map(|id| all_kwants.iter().find(|k| &k.id == id).cloned()).collect();
let workspace_dir = match &team {
Some(t) => Some(
- crate::tools::resolve_or_prepare_workspace(&state.config.data_dir, &t.name, t.workspace_path.as_deref(), t.repo_url.as_deref())
- .await,
+ crate::tools::resolve_or_prepare_workspace(
+ &crate::db::spaces::space_data_dir(&state.config.data_dir, &space),
+ &t.name,
+ t.workspace_path.as_deref(),
+ t.repo_url.as_deref(),
+ )
+ .await,
),
None => None,
};
@@ -963,11 +1003,21 @@ async fn run_kwant_turn_inner(
let cancel_token = &scope.cancel_token;
{
- let profile_engines = super::profile_turn::profile_engines(state).await;
+ let space = SpaceId::new(&target_kwant.space_id);
+ let profile_engines = super::profile_turn::profile_engines(state, &space).await;
+ let host_off = super::profile_turn::host_off(state, &space).await;
let available_models =
- crate::drivers::detect_available_models(&db, &state.engines, &profile_engines).await;
+ crate::drivers::detect_available_models(&db, &state.engines, &profile_engines, &host_off).await;
if available_models.is_empty() {
- let text = format!("⚠️ [{}] {}", target_kwant.name, crate::drivers::engines::NO_ENGINE_MESSAGE);
+ // Say why when it's this space's own switch, so nobody hunts for a broken engine
+ let text = if host_off.is_empty() {
+ format!("⚠️ [{}] {}", target_kwant.name, crate::drivers::engines::NO_ENGINE_MESSAGE)
+ } else {
+ format!(
+ "⚠️ [{}] This machine is off in this space and no other account is on. Turn one on in Settings → Engines.",
+ target_kwant.name
+ )
+ };
event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));
event_broadcast.send(RuntimeEvent::TurnComplete {
tokens: 0,
@@ -1115,7 +1165,14 @@ async fn run_kwant_turn_inner(
let engine = crate::profiles::Engine::parse(&target_model)
.or_else(|| crate::profiles::Engine::from_model(&target_model));
let candidates = super::profile_turn::plan(state, engine, &target_kwant.id).await;
- let attempts: Vec<Option<LlmProfile>> = if candidates.is_empty() {
+ // This machine turned off in the kwant's space: no host fallback, so nothing to try
+ let host_off = match engine {
+ Some(e) => super::profile_turn::host_off(state, &SpaceId::new(&target_kwant.space_id)).await.contains(&e),
+ None => false,
+ };
+ let attempts: Vec<Option<LlmProfile>> = if candidates.is_empty() && host_off {
+ Vec::new()
+ } else if candidates.is_empty() {
vec![None]
} else {
candidates.into_iter().map(Some).collect()
@@ -1192,6 +1249,21 @@ async fn run_kwant_turn_inner(
let mut driver_result = None;
let mut gave_up: Option<String> = None;
let mut ran_on: Option<RanOn> = None;
+ if attempts.is_empty() {
+ let text = format!(
+ "⚠️ [{}] This machine is off in this space and no other {} account is on.",
+ target_kwant.name,
+ engine.map(|e| e.as_str()).unwrap_or("model")
+ );
+ event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));
+ event_broadcast.send(RuntimeEvent::TurnComplete {
+ tokens: 0,
+ duration_ms: turn_start.elapsed().as_millis() as u64,
+ kwant_id: Some(target_kwant.id.clone()),
+ profile_id: None,
+ });
+ gave_up = Some(text);
+ }
for (i, profile) in attempts.iter().enumerate() {
let (driver, host_engine) = match super::profile_turn::driver_for(
state,
@@ -1468,6 +1540,28 @@ async fn run_kwant_turn_inner(
}
}
+/// The space a chat message belongs to: its channel's, else its direct kwant's, else its team's,
+/// else Default.
+async fn chat_space(state: &AppState, payload: &SendChatPayload) -> Result<SpaceId, DbError> {
+ let db = &state.db;
+ if let Some(id) = &payload.channel_id {
+ if let Some(space) = db.space_of_channel(id).await? {
+ return Ok(space);
+ }
+ }
+ if let Some(id) = &payload.kwant_id {
+ if let Some(space) = db.space_of_kwant(id).await? {
+ return Ok(space);
+ }
+ }
+ if let Some(id) = &payload.team_id {
+ if let Some(space) = db.space_of_team(id).await? {
+ return Ok(space);
+ }
+ }
+ Ok(request_space())
+}
+
pub async fn send_chat(
State(state): State<AppState>,
Json(mut payload): Json<SendChatPayload>,
@@ -1476,15 +1570,17 @@ pub async fn send_chat(
if let Some(thread_id) = payload.thread_id.clone() {
return send_to_thread(state, thread_id, payload, uploads).await;
}
+ // Everything this message can reach (mentions, teams, Laya's candidates) is in its space
+ let space = chat_space(&state, &payload).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let all_kwants = state
.db
- .list_kwants()
+ .list_kwants(&space)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let all_teams = state
.db
- .list_teams()
+ .list_teams(&space)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
@@ -1602,7 +1698,7 @@ pub async fn send_chat(
let workspace_dir = if let Some(ref team) = active_team {
Some(
crate::tools::resolve_or_prepare_workspace(
- &state.config.data_dir,
+ &crate::db::spaces::space_data_dir(&state.config.data_dir, &space),
&team.name,
team.workspace_path.as_deref(),
team.repo_url.as_deref(),
@@ -2309,30 +2405,32 @@ pub struct NavigatePayload {
pub url: String,
}
+/// A sandbox target by team, channel or kwant id, or by team name in the Default space. Folders
+/// are under the target's own space, so same-named teams in two spaces never share one.
pub async fn resolve_sandbox_target_info(state: &AppState, target_id: &str) -> Option<(String, PathBuf)> {
- if let Ok(Some(team)) = state.db.get_team(target_id).await {
+ let workspaces = |space: &str| {
+ crate::db::spaces::space_data_dir(&state.config.data_dir, &SpaceId::new(space)).join("workspaces")
+ };
+ let team_folder = |team: Team| {
let ws = team
.workspace_path
.as_deref()
.filter(|s| !s.trim().is_empty())
.map(PathBuf::from)
- .unwrap_or_else(|| state.config.data_dir.join("workspaces").join(&team.name));
- Some((team.name, ws))
+ .unwrap_or_else(|| workspaces(&team.space_id).join(&team.name));
+ (team.name, ws)
+ };
+ if let Ok(Some(team)) = state.db.get_team(target_id).await {
+ Some(team_folder(team))
} else if let Ok(Some(channel)) = state.db.get_channel(target_id).await {
let safe_cname = channel.name.to_lowercase().replace(|c: char| !c.is_alphanumeric(), "-");
- let ws = state.config.data_dir.join("workspaces").join(format!("chan-{}", safe_cname));
+ let ws = workspaces(&channel.space_id).join(format!("chan-{}", safe_cname));
Some((format!("chan-{}", safe_cname), ws))
} else if let Ok(Some(kwant)) = state.db.get_kwant(target_id).await {
let safe_kname = kwant.name.to_lowercase().replace(|c: char| !c.is_alphanumeric(), "-");
- Some((format!("bot-{}", safe_kname), state.config.data_dir.join("workspaces").join(format!("bot-{}", safe_kname))))
- } else if let Ok(Some(team)) = state.db.get_team_by_name(target_id).await {
- let ws = team
- .workspace_path
- .as_deref()
- .filter(|s| !s.trim().is_empty())
- .map(PathBuf::from)
- .unwrap_or_else(|| state.config.data_dir.join("workspaces").join(&team.name));
- Some((team.name, ws))
+ Some((format!("bot-{}", safe_kname), workspaces(&kwant.space_id).join(format!("bot-{}", safe_kname))))
+ } else if let Ok(Some(team)) = state.db.get_team_by_name(&request_space(), target_id).await {
+ Some(team_folder(team))
} else {
None
}
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index 4a9444e3..516e831e 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -31,6 +31,14 @@ fn error(status: StatusCode, message: impl Into<String>) -> Response {
(status, Json(json!({ "error": message.into() }))).into_response()
}
+/// A routine whose agent and channel are in different spaces is a 400; anything else is a 500.
+fn db_error(e: crate::db::DbError) -> Response {
+ match e {
+ crate::db::DbError::OtherSpace(m) => (StatusCode::BAD_REQUEST, m).into_response(),
+ _ => internal(),
+ }
+}
+
fn internal() -> Response {
StatusCode::INTERNAL_SERVER_ERROR.into_response()
}
@@ -164,7 +172,7 @@ async fn build(
}
pub async fn list(State(state): State<AppState>) -> Response {
- match state.db.list_routines().await {
+ match state.db.list_routines(&super::routes::request_space()).await {
Ok(list) => {
Json(list.into_iter().map(RoutineView::from).collect::<Vec<_>>()).into_response()
}
@@ -190,7 +198,7 @@ pub async fn create(State(state): State<AppState>, Json(p): Json<RoutinePayload>
state.scheduler_wake.notify_one();
(StatusCode::CREATED, Json(RoutineView::from(r))).into_response()
}
- Err(_) => internal(),
+ Err(e) => db_error(e),
}
}
@@ -214,7 +222,7 @@ pub async fn update(
Json(RoutineView::from(r)).into_response()
}
Ok(None) => StatusCode::NOT_FOUND.into_response(),
- Err(_) => internal(),
+ Err(e) => db_error(e),
}
}
@@ -405,7 +413,11 @@ async fn execute(state: &AppState, routine: &RoutineRow) -> Result<Option<String
/// Moves every missed or unset next run to its first slot after `now`: runs missed while kwnt was
/// down are dropped, and a `once` routine whose time has passed is switched off.
pub async fn reschedule_all(state: &AppState, now: DateTime<Utc>) {
- let routines = state.db.list_routines().await.unwrap_or_default();
+ let mut routines = Vec::new();
+ for space in state.db.list_spaces().await.unwrap_or_default() {
+ let space = crate::db::spaces::SpaceId::new(&space.id);
+ routines.extend(state.db.list_routines(&space).await.unwrap_or_default());
+ }
// A slot still ahead is kept: recomputing it would push interval routines back on every restart
for r in routines
.into_iter()
diff --git a/src/server/skills.rs b/src/server/skills.rs
index e6a7be1b..d0329456 100644
--- a/src/server/skills.rs
+++ b/src/server/skills.rs
@@ -221,6 +221,17 @@ fn unified(lines: &[DiffLine]) -> String {
// Routes
+/// The space a skill request is about: the kwant's, or the request's when it names none.
+async fn skill_space(state: &AppState, kwant_id: Option<&str>) -> crate::db::spaces::SpaceId {
+ match kwant_id {
+ Some(id) => match state.db.space_of_kwant(id).await {
+ Ok(Some(space)) => space,
+ _ => super::routes::request_space(),
+ },
+ None => super::routes::request_space(),
+ }
+}
+
#[derive(Deserialize)]
pub struct SkillsQuery {
pub kwant_id: Option<String>,
@@ -235,7 +246,9 @@ pub async fn list(State(state): State<AppState>, Query(q): Query<SkillsQuery>) -
return error(StatusCode::BAD_REQUEST, format!("unknown status '{s}'"));
}
}
- match state.db.list_skills(q.kwant_id.as_deref().filter(|s| !s.is_empty()), status.as_deref()).await {
+ let kwant_id = q.kwant_id.as_deref().filter(|s| !s.is_empty());
+ let space = skill_space(&state, kwant_id).await;
+ match state.db.list_skills(&space, kwant_id, status.as_deref()).await {
Ok(list) => Json(list).into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
@@ -327,7 +340,9 @@ pub async fn create(State(state): State<AppState>, Json(p): Json<SkillPayload>)
Ok(t) => t,
Err(e) => return skill_error(e),
};
- match state.db.create_user_skill(p.kwant_id.flatten().as_deref(), text).await {
+ let kwant_id = p.kwant_id.flatten();
+ let space = skill_space(&state, kwant_id.as_deref()).await;
+ match state.db.create_user_skill(&space, kwant_id.as_deref(), text).await {
Ok(s) => {
changed(&state, &s);
(StatusCode::CREATED, Json(s)).into_response()
@@ -519,6 +534,7 @@ mod tests {
created_at: now,
updated_at: now,
reviewed_at: None,
+ space_id: "spc_default".into(),
}
}
diff --git a/src/server/sse.rs b/src/server/sse.rs
index ab74e94b..c7ef2130 100644
--- a/src/server/sse.rs
+++ b/src/server/sse.rs
@@ -3,22 +3,69 @@ use axum::{
response::sse::{Event, KeepAlive, Sse},
};
use futures::stream::Stream;
+use futures::StreamExt;
+use serde_json::Value;
+use std::collections::HashMap;
use std::convert::Infallible;
+use std::sync::Arc;
+use tokio::sync::Mutex;
use tokio_stream::wrappers::BroadcastStream;
-use tokio_stream::StreamExt;
use super::AppState;
+use crate::db::Database;
+use crate::drivers::events::RuntimeEvent;
+
+/// Fields that name the chat, agent or team an event belongs to, most specific first.
+const SPACE_KEYS: [&str; 5] = ["context_id", "channel_id", "thread_id", "kwant_id", "team_id"];
+
+/// The event's wire JSON with the `space_id` it belongs to, or `null` for global events
+/// (accounts, models, …). `cache` maps ids already looked up to their space for one connection.
+pub async fn wire_event(db: &Database, cache: &mut HashMap<String, Option<String>>, event: &RuntimeEvent) -> Value {
+ let mut v = event.to_wire();
+ let Value::Object(map) = &mut v else {
+ return v;
+ };
+ // Turn tags sit at the top; an event's own ids are in its `data`
+ let ids: Vec<String> = SPACE_KEYS
+ .iter()
+ .flat_map(|key| [map.get(*key), map.get("data").and_then(|d| d.get(*key))])
+ .flatten()
+ .filter_map(|v| v.as_str().filter(|s| !s.is_empty()).map(str::to_string))
+ .collect();
+ let mut space = None;
+ for id in &ids {
+ let id = id.as_str();
+ if !cache.contains_key(id) {
+ // A long-lived connection sees ids come and go; start over rather than grow forever
+ if cache.len() >= 10_000 {
+ cache.clear();
+ }
+ let found = db.space_of_context(id).await.ok().flatten().map(|s| s.as_str().to_string());
+ cache.insert(id.to_string(), found);
+ }
+ if let Some(s) = cache.get(id).cloned().flatten() {
+ space = Some(s);
+ break;
+ }
+ }
+ map.insert("space_id".into(), space.map(Value::String).unwrap_or(Value::Null));
+ v
+}
pub async fn sse_handler(
State(state): State<AppState>,
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let rx = state.event_sender.subscribe();
- let stream = BroadcastStream::new(rx).filter_map(|msg| match msg {
- Ok(event) => {
- let json_str = event.to_wire().to_string();
- Some(Ok(Event::default().data(json_str)))
- }
- Err(_) => None,
- });
+ let cache = Arc::new(Mutex::new(HashMap::new()));
+ let stream = BroadcastStream::new(rx)
+ .filter_map(|msg| async move { msg.ok() })
+ .then(move |event| {
+ let db = state.db.clone();
+ let cache = cache.clone();
+ async move {
+ let wire = wire_event(&db, &mut *cache.lock().await, &event).await;
+ Ok(Event::default().data(wire.to_string()))
+ }
+ });
Sse::new(stream).keep_alive(KeepAlive::default())
}
diff --git a/tests/away_test.rs b/tests/away_test.rs
index 7fc9700d..2c8bf2ab 100644
--- a/tests/away_test.rs
+++ b/tests/away_test.rs
@@ -142,11 +142,11 @@ fn rfc(t: DateTime<Utc>) -> String {
#[tokio::test]
async fn away_lists_every_kind_filters_caps_and_marks_seen() {
let (app, state, _tmp) = setup().await;
- let kwants = state.db.list_kwants().await.unwrap();
+ let kwants = state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let (lead, spec) = (kwants[0].clone(), kwants[1].clone());
let chan = state
.db
- .create_channel(&NewChannel {
+ .create_channel(&kwnt::db::spaces::SpaceId::default_space(), &NewChannel {
name: "ops".into(),
description: None,
lead_kwant_id: lead.id.clone(),
@@ -345,7 +345,7 @@ async fn away_lists_every_kind_filters_caps_and_marks_seen() {
#[tokio::test]
async fn away_lists_are_capped_at_50_newest_first() {
let (app, state, _tmp) = setup().await;
- let kwants = state.db.list_kwants().await.unwrap();
+ let kwants = state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let (lead, spec) = (&kwants[0].id, &kwants[1].id);
let now = Utc::now();
let mut done = Vec::new();
@@ -412,11 +412,11 @@ async fn live_approval_link(app: &Router, state: &AppState, kwant: &kwnt::db::mo
#[tokio::test]
async fn live_approvals_link_to_the_chat_their_turn_runs_in() {
let (app, state, _tmp) = setup().await;
- let kwants = state.db.list_kwants().await.unwrap();
+ let kwants = state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let (lead, spec) = (kwants[0].clone(), kwants[1].clone());
let echo = state
.db
- .create_mcp_server(&McpServer {
+ .create_mcp_server(&kwnt::db::spaces::SpaceId::default_space(), &McpServer {
id: String::new(),
name: "echo".into(),
transport: "stdio".into(),
@@ -434,7 +434,7 @@ async fn live_approvals_link_to_the_chat_their_turn_runs_in() {
state.db.set_kwant_mcp_servers(&lead.id, std::slice::from_ref(&echo.id)).await.unwrap();
let chan = state
.db
- .create_channel(&NewChannel {
+ .create_channel(&kwnt::db::spaces::SpaceId::default_space(), &NewChannel {
name: "ops".into(),
description: None,
lead_kwant_id: lead.id.clone(),
diff --git a/tests/browser_stream_test.rs b/tests/browser_stream_test.rs
index d6732c08..d7affb79 100644
--- a/tests/browser_stream_test.rs
+++ b/tests/browser_stream_test.rs
@@ -103,7 +103,7 @@ async fn stream_input_control_lease_and_origin_protection() {
let tmp = tempfile::tempdir().unwrap();
let config = Config {data_dir:tmp.path().into(),browser_cdp_url:Some(format!("http://127.0.0.1:{}",mock.port)),..Config::default()};
let db = Database::init(tmp.path()).await.unwrap();
- let id=db.list_kwants().await.unwrap()[0].id.clone();
+ let id=db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap()[0].id.clone();
let state=AppState::new(config.clone(),db,ToolRunner::new(tmp.path().join("workspace")),PermissionBroker::new(),LayaRouter::new(config.laya_url));
let ctrl=kwnt::server::routes::get_or_create_browser_controller(&state,&id).await.unwrap();
assert!(state.sandbox_manager.get_sandbox(&id).await.is_none(),"browser must not start an execution container");
@@ -159,7 +159,7 @@ async fn live_chromium_stream_and_isolated_sessions() {
let tmp = tempfile::tempdir().unwrap();
let config = Config { data_dir: tmp.path().into(), ..Config::default() };
let db = Database::init(tmp.path()).await.unwrap();
- let bots = db.list_kwants().await.unwrap();
+ let bots = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let id = bots[0].id.clone();
let state = AppState::new(config.clone(), db, ToolRunner::new(tmp.path().join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url));
let ctrl = kwnt::server::routes::get_or_create_browser_controller(&state, &id).await.expect("real Chromium session");
diff --git a/tests/continuity_test.rs b/tests/continuity_test.rs
index 47780787..af714123 100644
--- a/tests/continuity_test.rs
+++ b/tests/continuity_test.rs
@@ -139,7 +139,7 @@ async fn upgrade_from(schema: &str) {
let db = Database::init(tmp.path()).await.unwrap();
// Existing messages were indexed; old rows load with the new optional columns
let hits = db
- .search_messages(
+ .search_messages(&kwnt::db::spaces::SpaceId::default_space(),
"zebra",
&SearchFilter {
limit: 10,
@@ -182,7 +182,7 @@ async fn upgrade_from(schema: &str) {
Database::init(tmp.path()).await.unwrap();
let db = Database::init(tmp.path()).await.unwrap();
let ids: Vec<String> = db
- .search_messages(
+ .search_messages(&kwnt::db::spaces::SpaceId::default_space(),
"zebra",
&SearchFilter {
limit: 10,
@@ -196,7 +196,7 @@ async fn upgrade_from(schema: &str) {
.collect();
assert_eq!(ids, vec!["m3".to_string()]);
assert_eq!(
- db.search_messages(
+ db.search_messages(&kwnt::db::spaces::SpaceId::default_space(),
"giraffe",
&SearchFilter {
limit: 10,
@@ -230,17 +230,17 @@ async fn upgrades_a_c1e8b3a_era_database() {
async fn search_ranks_filters_and_marks() {
let (app, state, _tmp) = setup().await;
let db = &state.db;
- let kwants = db.list_kwants().await.unwrap();
+ let kwants = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let (k1, k2) = (&kwants[0], &kwants[1]);
let general = db
- .list_channels()
+ .list_channels(&kwnt::db::spaces::SpaceId::default_space())
.await
.unwrap()
.into_iter()
.find(|c| c.name == "general")
.unwrap();
let other = db
- .create_channel(&NewChannel {
+ .create_channel(&kwnt::db::spaces::SpaceId::default_space(), &NewChannel {
name: "ops".into(),
description: None,
lead_kwant_id: k2.id.clone(),
@@ -368,7 +368,7 @@ async fn search_ranks_filters_and_marks() {
#[tokio::test]
async fn memory_api_caps_and_ownership() {
let (app, state, _tmp) = setup().await;
- let kwants = state.db.list_kwants().await.unwrap();
+ let kwants = state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let (k1, k2) = (&kwants[0].id, &kwants[1].id);
let mut rx = state.event_sender.subscribe();
@@ -485,10 +485,10 @@ async fn memory_api_caps_and_ownership() {
async fn instructions_and_memory_reach_the_prompt() {
let (app, state, _tmp) = setup().await;
let db = &state.db;
- let kwants = db.list_kwants().await.unwrap();
+ let kwants = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let k = &kwants[0];
let team = db
- .create_team(&NewTeam {
+ .create_team(&kwnt::db::spaces::SpaceId::default_space(), &NewTeam {
name: "core".into(),
description: None,
icon: None,
@@ -500,7 +500,7 @@ async fn instructions_and_memory_reach_the_prompt() {
.await
.unwrap();
let channel = db
- .list_channels()
+ .list_channels(&kwnt::db::spaces::SpaceId::default_space())
.await
.unwrap()
.into_iter()
@@ -617,10 +617,10 @@ async fn instructions_and_memory_reach_the_prompt() {
async fn self_tools_are_scoped_to_the_turn_and_kwant() {
let (app, state, _tmp) = setup().await;
let db = &state.db;
- let kwants = db.list_kwants().await.unwrap();
+ let kwants = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let (k1, k2) = (&kwants[0], &kwants[1]);
let private = db
- .create_channel(&NewChannel {
+ .create_channel(&kwnt::db::spaces::SpaceId::default_space(), &NewChannel {
name: "secret-ops".into(),
description: None,
lead_kwant_id: k2.id.clone(),
@@ -865,7 +865,7 @@ fn routine(kwant_id: &str, schedule: Value) -> Value {
#[tokio::test]
async fn routines_api_validates_and_reports() {
let (app, state, _tmp) = setup().await;
- let k = state.db.list_kwants().await.unwrap()[0].id.clone();
+ let k = state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap()[0].id.clone();
for bad in [
json!({"type": "daily", "time": "09:00"}),
@@ -971,7 +971,7 @@ async fn add_routine(
#[tokio::test]
async fn scheduler_skips_overlaps_and_never_replays() {
let (_app, state, _tmp) = setup().await;
- let k = state.db.list_kwants().await.unwrap()[0].id.clone();
+ let k = state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap()[0].id.clone();
let now = Utc::now();
// kwnt was down for a day: an interval routine due long ago runs at most once, then moves a full step past now
@@ -1074,7 +1074,7 @@ async fn scheduler_skips_overlaps_and_never_replays() {
// Routines of a deleted kwant go away
sqlx_delete_kwant(&state, &k).await;
scheduler::tick(&state, t).await;
- assert!(state.db.list_routines().await.unwrap().is_empty());
+ assert!(state.db.list_routines(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap().is_empty());
}
async fn sqlx_delete_kwant(state: &AppState, id: &str) {
@@ -1088,7 +1088,7 @@ async fn sqlx_delete_kwant(state: &AppState, id: &str) {
#[tokio::test]
async fn interrupted_runs_are_failed_on_start() {
let (_app, state, _tmp) = setup().await;
- let k = state.db.list_kwants().await.unwrap()[0].id.clone();
+ let k = state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap()[0].id.clone();
let id = add_routine(
&state,
&k,
@@ -1113,7 +1113,7 @@ async fn interrupted_runs_are_failed_on_start() {
#[tokio::test]
async fn messages_load_around_and_before_a_message() {
let (app, state, _tmp) = setup().await;
- let kwant = state.db.list_kwants().await.unwrap().remove(0);
+ let kwant = state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap().remove(0);
let channel = |name: &str| NewChannel {
name: name.into(),
description: None,
@@ -1121,8 +1121,8 @@ async fn messages_load_around_and_before_a_message() {
member_kwants: vec![kwant.id.clone()],
routing_mode: "auto".into(),
};
- let chan = state.db.create_channel(&channel("history")).await.unwrap();
- let other = state.db.create_channel(&channel("other")).await.unwrap();
+ let chan = state.db.create_channel(&kwnt::db::spaces::SpaceId::default_space(), &channel("history")).await.unwrap();
+ let other = state.db.create_channel(&kwnt::db::spaces::SpaceId::default_space(), &channel("other")).await.unwrap();
let mut ids = Vec::new();
for i in 0..250 {
let m = state.db.insert_message(&msg(Some(&chan.id), None, "user", "me", &format!("m{i}"))).await.unwrap();
@@ -1306,11 +1306,11 @@ async fn settings_refuse_unknown_keys_and_save_agent_tools() {
#[tokio::test]
async fn notifications_are_filtered_and_content_free() {
let (_app, state, _tmp) = setup().await;
- let kwants = state.db.list_kwants().await.unwrap();
+ let kwants = state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let k = &kwants[0];
let general = state
.db
- .list_channels()
+ .list_channels(&kwnt::db::spaces::SpaceId::default_space())
.await
.unwrap()
.into_iter()
diff --git a/tests/db_test.rs b/tests/db_test.rs
index 0fb3fc65..ebd6ea4f 100644
--- a/tests/db_test.rs
+++ b/tests/db_test.rs
@@ -16,10 +16,10 @@ async fn test_db_init_and_crud() {
preferred_model: "auto".into(),
};
- let kwant = db.create_kwant(&new_kwant).await.unwrap();
+ let kwant = db.create_kwant(&kwnt::db::spaces::SpaceId::default_space(), &new_kwant).await.unwrap();
assert_eq!(kwant.name, "PixelMage");
- let list = db.list_kwants().await.unwrap();
+ let list = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
// Default seeded kwants (3) + 1 newly created = 4
assert!(list.iter().any(|k| k.name == "PixelMage"));
assert!(list.len() >= 4);
@@ -30,16 +30,16 @@ async fn test_db_init_and_crud() {
// Channels
let new_chan = NewChannel {
- name: "general".into(),
+ name: "tavern".into(),
description: Some("Guild Tavern".into()),
lead_kwant_id: kwant.id.clone(),
member_kwants: vec![kwant.id.clone()],
routing_mode: "auto".into(),
};
- let chan = db.create_channel(&new_chan).await.unwrap();
- assert_eq!(chan.name, "general");
+ let chan = db.create_channel(&kwnt::db::spaces::SpaceId::default_space(), &new_chan).await.unwrap();
+ assert_eq!(chan.name, "tavern");
- let channels = db.list_channels().await.unwrap();
+ let channels = db.list_channels(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
assert!(!channels.is_empty());
// Messages
@@ -119,11 +119,11 @@ async fn test_team_crud_and_seed() {
let temp_dir = tempfile::tempdir().unwrap();
let db = Database::init(temp_dir.path()).await.unwrap();
- let teams = db.list_teams().await.unwrap();
+ let teams = db.list_teams(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
assert!(!teams.is_empty(), "Default seed team should exist");
assert_eq!(teams[0].name, "core-engineering");
- let kwants = db.list_kwants().await.unwrap();
+ let kwants = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let new_team = NewTeam {
name: "infra-sec".into(),
description: Some("Security and cloud infrastructure".into()),
@@ -133,10 +133,10 @@ async fn test_team_crud_and_seed() {
workspace_path: None,
repo_url: None,
};
- let created = db.create_team(&new_team).await.unwrap();
+ let created = db.create_team(&kwnt::db::spaces::SpaceId::default_space(), &new_team).await.unwrap();
assert_eq!(created.name, "infra-sec");
- let fetched = db.get_team_by_name("infra-sec").await.unwrap();
+ let fetched = db.get_team_by_name(&kwnt::db::spaces::SpaceId::default_space(), "infra-sec").await.unwrap();
assert!(fetched.is_some());
assert_eq!(fetched.unwrap().id, created.id);
@@ -144,7 +144,7 @@ async fn test_team_crud_and_seed() {
assert!(by_id.is_some());
assert_eq!(by_id.unwrap().name, "infra-sec");
- let channels = db.list_channels().await.unwrap();
+ let channels = db.list_channels(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
assert!(channels.iter().any(|c| c.name == "team-infra-sec"));
assert!(channels.iter().any(|c| c.name == "team-core-engineering"));
@@ -159,7 +159,7 @@ async fn test_team_with_workspace_and_repo() {
let temp_dir = tempfile::tempdir().unwrap();
let db = Database::init(temp_dir.path()).await.unwrap();
- let kwants = db.list_kwants().await.unwrap();
+ let kwants = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let new_team = NewTeam {
name: "dev-squad".into(),
description: Some("Frontend and backend app development".into()),
@@ -169,7 +169,7 @@ async fn test_team_with_workspace_and_repo() {
workspace_path: Some("/Users/dev/my-project".into()),
repo_url: Some("https://github.com/my-org/my-project.git".into()),
};
- let created = db.create_team(&new_team).await.unwrap();
+ let created = db.create_team(&kwnt::db::spaces::SpaceId::default_space(), &new_team).await.unwrap();
assert_eq!(created.workspace_path.as_deref(), Some("/Users/dev/my-project"));
assert_eq!(created.repo_url.as_deref(), Some("https://github.com/my-org/my-project.git"));
@@ -194,7 +194,7 @@ async fn test_team_with_workspace_and_repo() {
async fn test_starter_souls_seeded_and_user_edits_survive_restart() {
let tmp = tempdir().unwrap();
let db = Database::init(tmp.path()).await.unwrap();
- let starters = db.list_kwants().await.unwrap();
+ let starters = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
assert_eq!(starters.len(), 3);
assert!(starters.iter().all(|k| !k.soul.trim().is_empty()), "every starter has a soul");
@@ -219,7 +219,7 @@ async fn test_starter_souls_seeded_and_user_edits_survive_restart() {
drop(db);
let db = Database::init(tmp.path()).await.unwrap();
- let after = db.list_kwants().await.unwrap();
+ let after = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
// An untouched starter without a soul (as in pre-soul databases) gets one back
assert!(!after.iter().find(|k| k.name == "Architect").unwrap().soul.is_empty());
// A starter whose persona the user rewrote is left alone
diff --git a/tests/delegation_test.rs b/tests/delegation_test.rs
index 853f4a1a..144e17e1 100644
--- a/tests/delegation_test.rs
+++ b/tests/delegation_test.rs
@@ -443,7 +443,7 @@ async fn delegation_tools_enforce_their_rules() {
(v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string(), v["result"]["isError"] == true)
}
};
- let names: Vec<String> = env.state.db.list_kwants().await.unwrap().into_iter().map(|k| k.name).collect();
+ let names: Vec<String> = env.state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap().into_iter().map(|k| k.name).collect();
{
let mut tools = env.state.self_tools.lock().await;
tools.insert(
diff --git a/tests/driver_test.rs b/tests/driver_test.rs
index f0fce8ff..0e01ae0d 100644
--- a/tests/driver_test.rs
+++ b/tests/driver_test.rs
@@ -65,6 +65,7 @@ async fn test_mock_driver_streaming() {
let (tx, mut rx) = mpsc::channel(16);
let dummy_kwant = Kwant {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
id: "k-1".into(),
name: "CyberMage".into(),
title: "Arcane".into(),
@@ -125,6 +126,7 @@ fn test_turn_input_format_system_prompt_with_and_without_team_context() {
use kwnt::drivers::TeamContext;
let kwant = Kwant {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
id: "k-1".into(),
name: "Architect".into(),
title: "Systems Architect".into(),
diff --git a/tests/engine_model_test.rs b/tests/engine_model_test.rs
index 8318f2b5..f3d64d8f 100644
--- a/tests/engine_model_test.rs
+++ b/tests/engine_model_test.rs
@@ -217,7 +217,7 @@ async fn laya_picks_model_tier_pins_and_engine_switches() {
// Laya is offered only engines that are on
let offered: Vec<String> =
- detect_available_models(&state.db, &state.engines, &HashSet::new()).await.into_iter().map(|m| m.id).collect();
+ detect_available_models(&state.db, &state.engines, &HashSet::new(), &HashSet::new()).await.into_iter().map(|m| m.id).collect();
assert!(offered.contains(&"claude".to_string()), "{offered:?}");
assert!(!offered.iter().any(|m| m == "codex" || m == "grok"), "{offered:?}");
diff --git a/tests/grok_driver_test.rs b/tests/grok_driver_test.rs
index f2d71ff1..a47e6383 100644
--- a/tests/grok_driver_test.rs
+++ b/tests/grok_driver_test.rs
@@ -36,6 +36,7 @@ fn turn(mcp: Option<McpTurnContext>) -> TurnInput {
browser_api_url: None,
thread_id: "t1".into(),
kwant: Kwant {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
id: "k1".into(),
name: "Ada".into(),
title: "Lead".into(),
diff --git a/tests/mcp_api_loop_test.rs b/tests/mcp_api_loop_test.rs
index 1c0b17c9..5e800cc5 100644
--- a/tests/mcp_api_loop_test.rs
+++ b/tests/mcp_api_loop_test.rs
@@ -82,6 +82,7 @@ fn input(mcp: Option<McpTurnContext>) -> TurnInput {
browser_api_url: None,
thread_id: "t1".into(),
kwant: Kwant {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
id: "k1".into(),
name: "Ada".into(),
title: "Lead".into(),
diff --git a/tests/mcp_default_on_test.rs b/tests/mcp_default_on_test.rs
index 50d78fbb..83ca0297 100644
--- a/tests/mcp_default_on_test.rs
+++ b/tests/mcp_default_on_test.rs
@@ -77,18 +77,18 @@ async fn turn_servers(state: &AppState, kwant_id: &str) -> Vec<String> {
async fn servers_are_on_for_every_kwant_until_opted_out() {
let (state, app, _tmp) = env().await;
let db = &state.db;
- let kwants = db.list_kwants().await.unwrap();
+ let kwants = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let (a, b) = (kwants[0].id.clone(), kwants[1].id.clone());
// A server added after the kwants exist is on for all of them, with nothing assigned
- let notion_id = db.create_mcp_server(&server("notion", true)).await.unwrap().id;
- let off_id = db.create_mcp_server(&server("off", false)).await.unwrap().id;
+ let notion_id = db.create_mcp_server(&kwnt::db::spaces::SpaceId::default_space(), &server("notion", true)).await.unwrap().id;
+ let off_id = db.create_mcp_server(&kwnt::db::spaces::SpaceId::default_space(), &server("off", false)).await.unwrap().id;
for k in [&a, &b] {
assert_eq!(turn_servers(&state, k).await, vec!["notion"], "globally disabled servers stay out");
}
// ...and for a kwant created later
let late = db
- .create_kwant(&NewKwant {
+ .create_kwant(&kwnt::db::spaces::SpaceId::default_space(), &NewKwant {
name: "Late".into(),
title: "t".into(),
persona_prompt: "p".into(),
@@ -125,7 +125,7 @@ async fn servers_are_on_for_every_kwant_until_opted_out() {
assert!(turn_servers(&state, &a).await.is_empty());
// A server added after the opt-out is on for a too
- let github_id = db.create_mcp_server(&server("github", true)).await.unwrap().id;
+ let github_id = db.create_mcp_server(&kwnt::db::spaces::SpaceId::default_space(), &server("github", true)).await.unwrap().id;
assert_eq!(turn_servers(&state, &a).await, vec!["github"]);
// The server list says who has each server off
@@ -139,7 +139,7 @@ async fn servers_are_on_for_every_kwant_until_opted_out() {
// Turning it back on clears the opt-out
call(&app, "PUT", &uri, Some(json!({"server_ids": [notion_id, off_id, github_id]}))).await;
assert_eq!(turn_servers(&state, &a).await, vec!["github", "notion"]);
- assert!(db.list_mcp_kwant_opt_outs().await.unwrap().is_empty());
+ assert!(db.list_mcp_kwant_opt_outs(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap().is_empty());
// Validation is unchanged
let (status, _) = call(&app, "PUT", &uri, Some(json!({"server_ids": ["nope"]}))).await;
@@ -152,19 +152,19 @@ async fn servers_are_on_for_every_kwant_until_opted_out() {
async fn deleting_a_server_removes_its_opt_outs() {
let (state, app, _tmp) = env().await;
let db = &state.db;
- let kwants = db.list_kwants().await.unwrap();
- let notion_id = db.create_mcp_server(&server("notion", true)).await.unwrap().id;
+ let kwants = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
+ let notion_id = db.create_mcp_server(&kwnt::db::spaces::SpaceId::default_space(), &server("notion", true)).await.unwrap().id;
for k in &kwants {
db.set_kwant_mcp_servers(&k.id, &[]).await.unwrap();
}
- assert_eq!(db.list_mcp_kwant_opt_outs().await.unwrap()[&notion_id].len(), kwants.len());
+ assert_eq!(db.list_mcp_kwant_opt_outs(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap()[&notion_id].len(), kwants.len());
let (status, _) = call(&app, "DELETE", &format!("/api/mcp/servers/{notion_id}"), None).await;
assert_eq!(status, StatusCode::OK);
- assert!(db.list_mcp_kwant_opt_outs().await.unwrap().is_empty(), "no orphaned opt-out rows");
+ assert!(db.list_mcp_kwant_opt_outs(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap().is_empty(), "no orphaned opt-out rows");
// A server added again starts on for everyone
- db.create_mcp_server(&server("notion", true)).await.unwrap();
+ db.create_mcp_server(&kwnt::db::spaces::SpaceId::default_space(), &server("notion", true)).await.unwrap();
for k in &kwants {
assert_eq!(turn_servers(&state, &k.id).await, vec!["notion"]);
}
diff --git a/tests/mcp_oauth_test.rs b/tests/mcp_oauth_test.rs
index 14699e1f..25547a27 100644
--- a/tests/mcp_oauth_test.rs
+++ b/tests/mcp_oauth_test.rs
@@ -188,7 +188,7 @@ async fn sign_in_flow_end_to_end() {
assert!(!format!("{token:?}").contains(&token.access_token));
// Turns get the Bearer header; the claude CLI config carries it in its private file
- let kwant = e.state.db.list_kwants().await.unwrap().into_iter().next().unwrap();
+ let kwant = e.state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap().into_iter().next().unwrap();
e.state.db.set_kwant_mcp_servers(&kwant.id, std::slice::from_ref(&id)).await.unwrap();
let (ctx, turn) = mcp_runtime::prepare_turn(&e.state, &kwant, None).await.unwrap();
let bearer = format!("Bearer {}", token.access_token);
@@ -232,7 +232,7 @@ async fn short_lived_tokens_are_refreshed_before_use() {
assert_ne!(first.refresh_token, second.refresh_token, "rotated refresh token is stored");
// Concurrent turns refresh once each in turn, never with a spent refresh token
- let kwant = e.state.db.list_kwants().await.unwrap().into_iter().next().unwrap();
+ let kwant = e.state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap().into_iter().next().unwrap();
e.state.db.set_kwant_mcp_servers(&kwant.id, std::slice::from_ref(&id)).await.unwrap();
let (a, b) = tokio::join!(mcp_runtime::prepare_turn(&e.state, &kwant, None), mcp_runtime::prepare_turn(&e.state, &kwant, None));
for (ctx, _) in [a.unwrap(), b.unwrap()] {
diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rs
index 86c1ed8b..3f6d5eaf 100644
--- a/tests/mcp_runtime_test.rs
+++ b/tests/mcp_runtime_test.rs
@@ -265,6 +265,7 @@ fn turn(mcp: Option<McpTurnContext>) -> TurnInput {
browser_api_url: None,
thread_id: "t1".into(),
kwant: Kwant {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
id: "k1".into(),
name: "Ada".into(),
title: "Lead".into(),
diff --git a/tests/mcp_test.rs b/tests/mcp_test.rs
index 74963897..7e31ac41 100644
--- a/tests/mcp_test.rs
+++ b/tests/mcp_test.rs
@@ -158,7 +158,7 @@ async fn registry_crud_masks_secrets() {
assert_eq!(status, StatusCode::NOT_FOUND);
// Assignment: only enabled servers are active for the kwant
- let kwant_id = db.list_kwants().await.unwrap()[0].id.clone();
+ let kwant_id = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap()[0].id.clone();
let uri = format!("/api/kwants/{kwant_id}/mcp-servers");
let (status, _) = call(&app, "PUT", &uri, Some(json!({"server_ids": ["nope"]}))).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
diff --git a/tests/router_test.rs b/tests/router_test.rs
index 56b403e7..4fbb8291 100644
--- a/tests/router_test.rs
+++ b/tests/router_test.rs
@@ -106,6 +106,7 @@ fn test_parse_mentions_kwant_and_team() {
async fn test_team_orchestration_heuristic_fallback() {
let router = LayaRouter::new("http://127.0.0.1:9999/unreachable".into());
let team = Team {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
id: "team-1".into(),
name: "core-engineering".into(),
description: Some("Architecture & DevOps".into()),
@@ -119,6 +120,7 @@ async fn test_team_orchestration_heuristic_fallback() {
};
let members = vec![
Kwant {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
id: "kwant-1".into(),
name: "Architect".into(),
title: "Systems Architect".into(),
@@ -134,6 +136,7 @@ async fn test_team_orchestration_heuristic_fallback() {
created_at: None,
},
Kwant {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
id: "kwant-2".into(),
name: "DevOps".into(),
title: "DevOps Engineer".into(),
@@ -286,6 +289,7 @@ async fn laya_status_starts_unknown_and_updates() {
fn agent(id: &str, name: &str, title: &str) -> Kwant {
Kwant {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
id: id.into(),
name: name.into(),
title: title.into(),
@@ -332,6 +336,7 @@ fn test_laya_team_discussion_uses_runner_up_as_second_speaker() {
agent("c", "DevOps", "Systems & Security Engineer"),
];
let team = Team {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
id: "t".into(),
name: "core".into(),
description: None,
diff --git a/tests/server_test.rs b/tests/server_test.rs
index b0471dbc..818b3146 100644
--- a/tests/server_test.rs
+++ b/tests/server_test.rs
@@ -93,7 +93,7 @@ async fn test_teams_api_endpoints() {
assert_eq!(resp.status(), StatusCode::OK);
// 3. POST /api/teams
- let kwants = db.list_kwants().await.unwrap();
+ let kwants = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let new_team_payload = json!({
"name": "qa-squad",
"description": "Quality assurance squad",
@@ -370,9 +370,9 @@ async fn test_sandbox_password_vault_api() {
let tools = ToolRunner::new(tmp.path().join("workspace"));
let broker = PermissionBroker::new();
let router = LayaRouter::new(config.laya_url.clone());
- let kwants = db.list_kwants().await.unwrap();
+ let kwants = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let team = db
- .create_team(&kwnt::db::models::NewTeam {
+ .create_team(&kwnt::db::spaces::SpaceId::default_space(), &kwnt::db::models::NewTeam {
name: "test-team-vault".into(),
description: Some("Team for vault testing".into()),
icon: None,
@@ -706,7 +706,7 @@ async fn test_channel_sandbox_target_resolution() {
let router = LayaRouter::new(config.laya_url.clone());
let state = AppState::new(config, db.clone(), tools, broker, router);
- let channels = db.list_channels().await.unwrap();
+ let channels = db.list_channels(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
let general_channel = channels.iter().find(|c| c.name == "general").expect("Seeded general channel");
let resolved = resolve_sandbox_target_info(&state, &general_channel.id).await;
diff --git a/tests/skills_test.rs b/tests/skills_test.rs
index a3754510..678afebd 100644
--- a/tests/skills_test.rs
+++ b/tests/skills_test.rs
@@ -288,8 +288,8 @@ async fn skills_never_grant_tools_and_stay_with_their_agent() {
async fn skills_migration_is_idempotent_and_additive() {
let tmp = tempfile::tempdir().unwrap();
let db = kwnt::db::Database::init(tmp.path()).await.unwrap();
- db.create_user_skill(None, kwnt::db::skills::clean_skill_text("keep-me", "d", "b").unwrap()).await.unwrap();
+ db.create_user_skill(&kwnt::db::spaces::SpaceId::default_space(), None, kwnt::db::skills::clean_skill_text("keep-me", "d", "b").unwrap()).await.unwrap();
drop(db);
let db = kwnt::db::Database::init(tmp.path()).await.unwrap();
- assert_eq!(db.list_skills(None, Some("enabled")).await.unwrap().len(), 1);
+ assert_eq!(db.list_skills(&kwnt::db::spaces::SpaceId::default_space(), None, Some("enabled")).await.unwrap().len(), 1);
}
diff --git a/tests/spaces_isolation_test.rs b/tests/spaces_isolation_test.rs
new file mode 100644
index 00000000..0c50adab
--- /dev/null
+++ b/tests/spaces_isolation_test.rs
@@ -0,0 +1,692 @@
+//! Spaces S1: nothing in one space reaches another. Each test makes a second space B straight in
+//! the db next to the Default space A, with the same names in both where that is the risk (a bot
+//! "Ada", a team "web"), and checks one path that used to look across every space. A fake claude
+//! CLI on PATH records the folder it ran in and the prompt, so no real engine is ever called.
+//! Its own test binary: it changes PATH.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use futures::StreamExt;
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{
+ models::{Kwant, ProfileKey, NewChannel, NewKwant, NewLlmProfile, NewMessage, NewTeam},
+ spaces::{NewSpace, SpaceId},
+ Database,
+ },
+ profiles::Engine,
+ router::LayaRouter,
+ server::{continuity::SelfScope, continuity::TurnOrigin, create_router, delegation, profile_turn, AppState},
+ tools::ToolRunner,
+ RuntimeEvent,
+};
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::sync::OnceLock;
+use std::time::Duration;
+use tower::ServiceExt;
+
+/// Answers "answer <tag>" for a prompt with "REPLYTAG:<tag>", or "answer @Ada" for one with
+/// "SAYADA". Every call is saved under `$KWNT_TEST_PROMPTS` as its folder, a "---" line and the prompt.
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1" in
+ auth) echo '{"loggedIn":true}'; exit 0 ;;
+esac
+for a; do last="$a"; done
+printf '%s\n---\n%s' "$PWD" "$last" > "$KWNT_TEST_PROMPTS/$$-$(date +%s%N)"
+tag=$(printf '%s\n' "$last" | sed -n 's/.*REPLYTAG:\([A-Za-z0-9_]*\).*/\1/p' | tail -n 1)
+reply="answer ${tag:-none}"
+case "$last" in *SAYADA*) reply="answer @Ada" ;; esac
+echo "{\"type\":\"result\",\"is_error\":false,\"num_turns\":1,\"result\":\"$reply\"}"
+"#;
+
+fn prompts_dir() -> &'static PathBuf {
+ static DIR: OnceLock<PathBuf> = OnceLock::new();
+ DIR.get_or_init(|| {
+ let root = tempfile::tempdir().unwrap().keep();
+ let bin = root.join("bin");
+ let prompts = root.join("prompts");
+ std::fs::create_dir_all(&bin).unwrap();
+ std::fs::create_dir_all(&prompts).unwrap();
+ let fake = bin.join("claude");
+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ std::env::set_var("KWNT_TEST_PROMPTS", &prompts);
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ prompts
+ })
+}
+
+/// (folder, prompt) of every fake CLI call whose prompt contains `marker`.
+fn calls_with(marker: &str) -> Vec<(String, String)> {
+ std::fs::read_dir(prompts_dir())
+ .unwrap()
+ .filter_map(|e| std::fs::read_to_string(e.unwrap().path()).ok())
+ .filter(|p| p.contains(marker))
+ .map(|p| {
+ let (dir, prompt) = p.split_once("\n---\n").unwrap_or(("", &p));
+ (dir.to_string(), prompt.to_string())
+ })
+ .collect()
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let resp = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("content-type", "application/json")
+ .body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let s = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (s, serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())))
+}
+
+async fn wait_for<F, Fut>(what: &str, mut check: F)
+where
+ F: FnMut() -> Fut,
+ Fut: std::future::Future<Output = bool>,
+{
+ for _ in 0..200 {
+ if check().await {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ panic!("timed out waiting for {what}");
+}
+
+/// The Default space A and a second space B, each with a bot "Ada" and a second bot, a #general
+/// and a team "web" (Ada leads, both are members).
+struct Env {
+ app: Router,
+ state: AppState,
+ data: PathBuf,
+ a: SpaceId,
+ b: SpaceId,
+ ada_a: Kwant,
+ ada_b: Kwant,
+ other_b: Kwant,
+ _tmp: tempfile::TempDir,
+}
+
+async fn kwant(db: &Database, space: &SpaceId, name: &str) -> Kwant {
+ db.create_kwant(
+ space,
+ &NewKwant {
+ name: name.into(),
+ title: format!("{name} the tester"),
+ persona_prompt: "Test persona".into(),
+ soul: String::new(),
+ avatar_sprite: "s".into(),
+ driver_type: "api".into(),
+ preferred_model: "claude".into(),
+ },
+ )
+ .await
+ .unwrap()
+}
+
+async fn setup(b_this_machine_on: bool) -> Env {
+ prompts_dir();
+ let tmp = tempfile::tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ let a = SpaceId::default_space();
+ let b = SpaceId::new(
+ &db.create_space(&NewSpace {
+ name: "Side project".into(),
+ icon: "🧪".into(),
+ color: None,
+ this_machine_enabled: b_this_machine_on,
+ })
+ .await
+ .unwrap()
+ .id,
+ );
+ let ada_a = kwant(&db, &a, "Ada").await;
+ let other_a = kwant(&db, &a, "Remy").await;
+ let ada_b = kwant(&db, &b, "Ada").await;
+ let other_b = kwant(&db, &b, "Bea").await;
+ for (space, ada, other) in [(&a, &ada_a, &other_a), (&b, &ada_b, &other_b)] {
+ let members = vec![ada.id.clone(), other.id.clone()];
+ if space != &a {
+ // Default got its #general from the seed
+ db.create_channel(space, &NewChannel {
+ name: "general".into(),
+ description: None,
+ lead_kwant_id: ada.id.clone(),
+ member_kwants: members.clone(),
+ routing_mode: "auto".into(),
+ })
+ .await
+ .unwrap();
+ }
+ db.create_team(space, &NewTeam {
+ name: "web".into(),
+ description: None,
+ icon: None,
+ lead_kwant_id: ada.id.clone(),
+ member_kwants: members,
+ workspace_path: None,
+ repo_url: None,
+ })
+ .await
+ .unwrap();
+ }
+ let config = Config {
+ data_dir: data.clone(),
+ laya_url: "http://127.0.0.1:9".into(),
+ browser_cdp_url: Some("http://127.0.0.1:9".into()),
+ ..Config::default()
+ };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(data.join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let app = create_router(state.clone());
+ Env { app, state, data, a, b, ada_a, ada_b, other_b, _tmp: tmp }
+}
+
+impl Env {
+ async fn general(&self, space: &SpaceId) -> String {
+ self.state.db.general_channel(space).await.unwrap().expect("a #general").id
+ }
+
+ async fn team(&self, space: &SpaceId) -> String {
+ self.state.db.get_team_by_name(space, "web").await.unwrap().expect("team web").id
+ }
+
+ async fn send(&self, body: Value) {
+ let (s, v) = call(&self.app, "POST", "/api/chat/send", Some(body)).await;
+ assert!(s.is_success(), "{s} {v}");
+ }
+
+ /// Messages in a channel or direct chat.
+ async fn messages(&self, chat: &str) -> Vec<kwnt::db::models::Message> {
+ self.state.db.list_messages(chat, 200).await.unwrap()
+ }
+
+ async fn say(&self, chat_channel: Option<&str>, direct: Option<&str>, sender: &str, text: &str) {
+ self.state
+ .db
+ .insert_message(&NewMessage {
+ channel_id: chat_channel.map(str::to_string),
+ direct_kwant_id: direct.map(str::to_string),
+ sender_role: "user".into(),
+ sender_id: sender.into(),
+ text: text.into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 1,
+ })
+ .await
+ .unwrap();
+ }
+}
+
+// 1. Laya's #general candidates
+
+#[tokio::test]
+async fn general_routing_candidates_come_only_from_the_channels_space() {
+ let env = setup(true).await;
+ let mut events = env.state.event_sender.subscribe();
+ let general_b = env.general(&env.b).await;
+ env.send(json!({"channel_id": general_b, "prompt": "who is around? REPLYTAG:laya1", "sender_id": "user"})).await;
+
+ let candidates = tokio::time::timeout(Duration::from_secs(10), async {
+ loop {
+ if let Ok(RuntimeEvent::RoutingStarted { candidates, .. }) = events.recv().await.map(|e| e.unscoped().clone()) {
+ return candidates;
+ }
+ }
+ })
+ .await
+ .expect("routing started");
+ let ids: Vec<&str> = candidates.iter().map(|c| c.id.as_str()).collect();
+ assert_eq!(ids.len(), 2, "only B's two bots: {ids:?}");
+ assert!(ids.contains(&env.ada_b.id.as_str()) && ids.contains(&env.other_b.id.as_str()));
+ assert!(!ids.contains(&env.ada_a.id.as_str()));
+}
+
+// 2. @mentions
+
+#[tokio::test]
+async fn a_mention_reaches_the_bot_of_that_name_in_the_chats_space() {
+ let env = setup(true).await;
+ let mut events = env.state.event_sender.subscribe();
+ // In B's #general, "@Ada" is B's Ada even though A has a bot of the same name
+ let general_b = env.general(&env.b).await;
+ env.send(json!({"channel_id": general_b, "prompt": "@Ada hello REPLYTAG:mention1", "sender_id": "user"})).await;
+ wait_for("Ada's reply in B", || async {
+ env.messages(&general_b).await.iter().any(|m| m.text.contains("answer mention1"))
+ })
+ .await;
+ // Replies are saved under the bot's name, so tell the two Adas apart by the turns' kwant ids
+ let speakers = turn_kwants(&mut events);
+ assert!(speakers.contains(&env.ada_b.id), "{speakers:?}");
+ assert!(!speakers.contains(&env.ada_a.id), "{speakers:?}");
+ assert!(env.messages(&env.ada_a.id).await.is_empty());
+}
+
+/// Kwant ids of the turns in the events received so far.
+fn turn_kwants(events: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>) -> Vec<String> {
+ let mut ids = Vec::new();
+ loop {
+ let e = match events.try_recv() {
+ Ok(e) => e,
+ Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) => continue,
+ Err(_) => break,
+ };
+ if let RuntimeEvent::Scoped { tag, .. } = &e {
+ ids.push(tag.kwant_id.clone());
+ }
+ if let RuntimeEvent::TurnComplete { kwant_id: Some(k), .. } = e.unscoped() {
+ ids.push(k.clone());
+ }
+ }
+ ids
+}
+
+// 3. Delegation without a member list
+
+#[tokio::test]
+async fn delegation_without_a_member_list_stays_in_the_leads_space() {
+ let env = setup(true).await;
+ // The agent tool in a direct chat, which has no member list: A's bots aren't offered or reachable
+ let scope = SelfScope {
+ kwant_id: env.other_b.id.clone(),
+ kwant_name: env.other_b.name.clone(),
+ origin: Some(TurnOrigin {
+ channel_id: None,
+ direct_kwant_id: Some(env.other_b.id.clone()),
+ thread_id: None,
+ team_id: None,
+ member_ids: Vec::new(),
+ depth: 0,
+ }),
+ cancel: None,
+ turn_id: None,
+ workspace: None,
+ };
+ let (text, is_error) = delegation::tool_delegate(&env.state, &scope, &json!({"to": "Remy", "task": "help"})).await;
+ assert!(is_error, "{text}");
+ assert!(text.contains("No agent named 'Remy'"), "{text}");
+ assert!(text.contains("Ada") && !text.contains("Remy."), "only B's bots are offered: {text}");
+
+ // The HTTP API, which takes ids: a specialist from another space is refused
+ let (s, v) = call(
+ &env.app,
+ "POST",
+ "/api/delegations",
+ Some(json!({"lead_kwant_id": env.other_b.id, "specialist_kwant_id": env.ada_a.id, "task": "help", "kwant_id": env.other_b.id})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "{v}");
+ assert!(env.state.db.list_delegations(None, None, 50).await.unwrap().is_empty());
+}
+
+// 4. Account failover and default selection
+
+#[tokio::test]
+async fn failover_only_tries_accounts_in_the_kwants_space() {
+ let env = setup(true).await;
+ // A has a Claude API key account first in line; B has only its own This machine
+ let in_a = env
+ .state
+ .db
+ .create_profile(&env.a, &NewLlmProfile {
+ engine: "claude".into(),
+ name: "Work key".into(),
+ kind: "api_key".into(),
+ home_dir: None,
+ priority: 1,
+ enabled: true,
+ is_default: true,
+ })
+ .await
+ .unwrap();
+ env.state.db.set_profile_key(&in_a.id, &ProfileKey("sk-ant-test-a".into())).await.unwrap();
+ let plan_a = profile_turn::plan(&env.state, Some(Engine::Claude), &env.ada_a.id).await;
+ assert!(plan_a.iter().any(|p| p.id == in_a.id), "A uses its own account");
+ let plan_b = profile_turn::plan(&env.state, Some(Engine::Claude), &env.ada_b.id).await;
+ assert!(!plan_b.is_empty(), "B has its own This machine");
+ assert!(plan_b.iter().all(|p| p.space_id == env.b.as_str()), "{:?}", plan_b.iter().map(|p| &p.id).collect::<Vec<_>>());
+ // Binding B's bot to A's account is refused
+ assert!(matches!(
+ env.state.db.set_kwant_binding(&env.ada_b.id, Some(Some(&in_a.id)), None).await,
+ Err(kwnt::db::DbError::OtherSpace(_))
+ ));
+}
+
+// 5. This machine off is never a fallback
+
+#[tokio::test]
+async fn this_machine_off_in_a_space_is_never_used_even_with_accounts_elsewhere() {
+ let env = setup(false).await;
+ let in_a = env
+ .state
+ .db
+ .create_profile(&env.a, &NewLlmProfile {
+ engine: "claude".into(),
+ name: "Work key".into(),
+ kind: "api_key".into(),
+ home_dir: None,
+ priority: 1,
+ enabled: true,
+ is_default: false,
+ })
+ .await
+ .unwrap();
+ // A ready account in A, which B must not borrow
+ env.state.db.set_profile_key(&in_a.id, &ProfileKey("sk-ant-test-a".into())).await.unwrap();
+ assert!(profile_turn::host_off(&env.state, &env.b).await.contains(&Engine::Claude));
+ assert!(!profile_turn::host_off(&env.state, &env.a).await.contains(&Engine::Claude));
+ assert!(profile_turn::plan(&env.state, Some(Engine::Claude), &env.ada_b.id).await.is_empty());
+
+ env.send(json!({"kwant_id": env.ada_b.id, "prompt": "hi REPLYTAG:hostoff1", "sender_id": "user"})).await;
+ for _ in 0..100 {
+ if env.messages(&env.ada_b.id).await.iter().any(|m| m.text.contains("This machine is off in this space")) {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ let texts: Vec<String> = env.messages(&env.ada_b.id).await.into_iter().map(|m| m.text).collect();
+ assert!(texts.iter().any(|t| t.contains("This machine is off in this space")), "{texts:?}");
+ assert!(calls_with("hostoff1").is_empty(), "the CLI on this machine was not run");
+ assert!(!env.messages(&env.ada_b.id).await.iter().any(|m| m.text.contains("answer hostoff1")));
+}
+
+// 6. MCP servers
+
+#[tokio::test]
+async fn mcp_servers_never_reach_bots_in_another_space() {
+ let env = setup(true).await;
+ // Created through the API, which is the Default space until S2
+ let (s, server) = call(
+ &env.app,
+ "POST",
+ "/api/mcp/servers",
+ Some(json!({"name": "files", "transport": "http", "url": "http://127.0.0.1:9/mcp"})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK, "{server}");
+ let id = server["id"].as_str().unwrap().to_string();
+ let ids = |list: Vec<kwnt::db::models::McpServer>| list.into_iter().map(|s| s.id).collect::<Vec<_>>();
+
+ assert!(ids(env.state.db.list_active_mcp_servers_for_kwant(&env.ada_a.id).await.unwrap()).contains(&id), "on by default in A");
+ assert!(ids(env.state.db.list_active_mcp_servers_for_kwant(&env.ada_b.id).await.unwrap()).is_empty());
+ assert!(env.state.db.list_mcp_servers(&env.b).await.unwrap().is_empty());
+
+ let (s, v) = call(&env.app, "PUT", &format!("/api/kwants/{}/mcp-servers", env.ada_b.id), Some(json!({"server_ids": [id]}))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");
+ // Even written straight to the db, the assignment doesn't cross
+ let _ = env.state.db.set_kwant_mcp_servers(&env.ada_b.id, std::slice::from_ref(&id)).await;
+ assert!(ids(env.state.db.list_active_mcp_servers_for_kwant(&env.ada_b.id).await.unwrap()).is_empty());
+ assert!(env.state.db.get_kwant_mcp_server_ids(&env.ada_b.id).await.unwrap().is_empty());
+}
+
+// 7. Skills
+
+#[tokio::test]
+async fn shared_skills_stay_in_their_space() {
+ let env = setup(true).await;
+ let (s, skill) = call(
+ &env.app,
+ "POST",
+ "/api/skills",
+ Some(json!({"name": "release-notes", "description": "Write release notes", "body": "Steps for release notes."})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::CREATED, "{skill}");
+ let id = skill["id"].as_str().unwrap();
+ let names = |list: Vec<kwnt::db::skills::Skill>| list.into_iter().map(|s| s.id).collect::<Vec<_>>();
+ assert!(names(env.state.db.enabled_skills_for(&env.ada_a.id).await.unwrap()).contains(&id.to_string()));
+ assert!(env.state.db.enabled_skills_for(&env.ada_b.id).await.unwrap().is_empty());
+ let (_, list) = call(&env.app, "GET", &format!("/api/skills?kwant_id={}", env.ada_b.id), None).await;
+ assert_eq!(list.as_array().map(Vec::len), Some(0), "{list}");
+ assert!(env.state.db.list_skills(&env.b, None, None).await.unwrap().is_empty());
+
+ // A skill for B's bot lives in B, and A's list doesn't show it
+ let (s, own) = call(
+ &env.app,
+ "POST",
+ "/api/skills",
+ Some(json!({"name": "triage", "description": "Triage bugs", "body": "Steps.", "kwant_id": env.ada_b.id})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::CREATED, "{own}");
+ assert_eq!(own["space_id"], env.b.as_str());
+ let (_, list_a) = call(&env.app, "GET", "/api/skills", None).await;
+ assert!(!list_a.to_string().contains("triage"));
+}
+
+// 8. The search tool
+
+#[tokio::test]
+async fn the_search_tool_only_finds_messages_in_the_agents_space() {
+ let env = setup(true).await;
+ let general_a = env.general(&env.a).await;
+ let general_b = env.general(&env.b).await;
+ env.say(Some(&general_a), None, "user", "the zebra launch plan for A").await;
+ env.say(None, Some(&env.ada_a.id), "user", "secret zebra numbers in A's direct chat").await;
+ env.say(Some(&general_b), None, "user", "a zebra sketch for B").await;
+
+ let token = "tok-search-b";
+ env.state.self_tools.lock().await.insert(
+ token.into(),
+ SelfScope {
+ kwant_id: env.ada_b.id.clone(),
+ kwant_name: env.ada_b.name.clone(),
+ origin: None,
+ cancel: None,
+ turn_id: None,
+ workspace: None,
+ },
+ );
+ let resp = env
+ .app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/api/mcp/self")
+ .header("content-type", "application/json")
+ .header("authorization", format!("Bearer {token}"))
+ .body(Body::from(
+ json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "search_history", "arguments": {"query": "zebra"}}})
+ .to_string(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = String::from_utf8_lossy(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).to_string();
+ assert!(body.contains("sketch for B"), "B's own message is found: {body}");
+ assert!(!body.contains("launch plan") && !body.contains("secret zebra"), "{body}");
+
+ // The HTTP search, scoped by the bot it names
+ let (_, hits) = call(&env.app, "GET", &format!("/api/search?q=zebra&kwant_id={}", env.ada_b.id), None).await;
+ assert!(!hits.to_string().contains("launch plan") && !hits.to_string().contains("secret zebra"), "{hits}");
+ let all_b = env.state.db.search_messages(&env.b, "zebra", &kwnt::db::continuity::SearchFilter {
+ channel_id: None,
+ kwant_id: None,
+ allowed_channels: None,
+ allowed_direct: None,
+ limit: 50,
+ })
+ .await
+ .unwrap();
+ assert_eq!(all_b.len(), 1);
+}
+
+// 9. Routines and the scheduler
+
+#[tokio::test]
+async fn a_routine_cannot_join_a_bot_and_a_channel_from_different_spaces() {
+ let env = setup(true).await;
+ let general_a = env.general(&env.a).await;
+ let schedule = json!({"type": "interval", "every_minutes": 60});
+ let (s, v) = call(
+ &env.app,
+ "POST",
+ "/api/routines",
+ Some(json!({"kwant_id": env.ada_b.id, "channel_id": general_a, "name": "Digest", "instructions": "Summarise", "schedule": schedule})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");
+
+ // A routine in B's own direct chat works, and lands in B, not in A's list
+ let (s, r) = call(
+ &env.app,
+ "POST",
+ "/api/routines",
+ Some(json!({"kwant_id": env.ada_b.id, "channel_id": null, "name": "Digest", "instructions": "Summarise", "schedule": schedule})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::CREATED, "{r}");
+ let (_, list_a) = call(&env.app, "GET", "/api/routines", None).await;
+ assert_eq!(list_a.as_array().map(Vec::len), Some(0), "{list_a}");
+ let in_b = env.state.db.list_routines(&env.b).await.unwrap();
+ assert_eq!(in_b.len(), 1);
+ assert_eq!(in_b[0].space_id, env.b.as_str());
+ assert!(env.state.db.list_routines(&env.a).await.unwrap().is_empty());
+
+ // Moving it onto A's channel is refused as well
+ let id = r["id"].as_str().unwrap();
+ let (s, v) = call(&env.app, "PATCH", &format!("/api/routines/{id}"), Some(json!({"channel_id": general_a}))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");
+}
+
+// 10. Work folders
+
+#[tokio::test]
+async fn teams_with_the_same_name_work_in_different_folders() {
+ let env = setup(true).await;
+ let team_a = env.team(&env.a).await;
+ let team_b = env.team(&env.b).await;
+ env.send(json!({"team_id": team_a, "prompt": "@Ada build it REPLYTAG:folderA", "sender_id": "user"})).await;
+ env.send(json!({"team_id": team_b, "prompt": "@Ada build it REPLYTAG:folderB", "sender_id": "user"})).await;
+ wait_for("both teams' turns", || async { !calls_with("folderA").is_empty() && !calls_with("folderB").is_empty() }).await;
+
+ let dir_a = PathBuf::from(&calls_with("folderA")[0].0);
+ let dir_b = PathBuf::from(&calls_with("folderB")[0].0);
+ assert_ne!(dir_a, dir_b);
+ let space_root = env.data.join("spaces");
+ assert!(!dir_a.starts_with(&space_root), "A keeps its folder: {}", dir_a.display());
+ assert!(dir_b.starts_with(&space_root), "B works under its own space folder: {}", dir_b.display());
+ assert!(!dir_b.starts_with(&dir_a) && !dir_a.starts_with(&dir_b));
+}
+
+// 11. SSE events carry their space
+
+/// The next SSE event's JSON.
+async fn next_event<S, E>(stream: &mut S) -> Value
+where
+ S: futures::Stream<Item = Result<axum::body::Bytes, E>> + Unpin,
+ E: std::fmt::Debug,
+{
+ let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next()).await.expect("an event").unwrap().unwrap();
+ let text = String::from_utf8_lossy(&chunk).to_string();
+ let data = text.lines().find_map(|l| l.strip_prefix("data:")).expect("a data line").trim().to_string();
+ serde_json::from_str(&data).unwrap()
+}
+
+#[tokio::test]
+async fn sse_events_carry_the_space_they_belong_to() {
+ let env = setup(true).await;
+ let resp = env.app.clone().oneshot(Request::builder().uri("/api/events").body(Body::empty()).unwrap()).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let mut stream = resp.into_body().into_data_stream();
+ let general_b = env.general(&env.b).await;
+ let send = |e: RuntimeEvent| {
+ let _ = env.state.event_sender.send(e);
+ };
+ send(RuntimeEvent::MemoryChanged { kwant_id: env.ada_b.id.clone() });
+ assert_eq!(next_event(&mut stream).await["space_id"], env.b.as_str());
+ send(RuntimeEvent::MemoryChanged { kwant_id: env.ada_a.id.clone() });
+ assert_eq!(next_event(&mut stream).await["space_id"], env.a.as_str());
+ send(RuntimeEvent::RoutingStarted { context_id: Some(general_b), candidates: Vec::new() });
+ assert_eq!(next_event(&mut stream).await["space_id"], env.b.as_str());
+ send(RuntimeEvent::DiscussionCompleted { total_turns: 1 });
+ assert_eq!(next_event(&mut stream).await["space_id"], Value::Null, "an event with no chat is global");
+}
+
+// Handoffs (bonus)
+
+#[tokio::test]
+async fn a_handoff_mention_never_reaches_a_bot_in_another_space() {
+ let env = setup(true).await;
+ let mut events = env.state.event_sender.subscribe();
+ // Bea in B answers "@Ada": both spaces have an Ada, and only B's may take the handoff
+ let general_b = env.general(&env.b).await;
+ env.send(json!({"channel_id": general_b, "prompt": "@Bea REPLYTAG:handoff1 SAYADA", "sender_id": "user"})).await;
+ wait_for("Bea's reply", || async {
+ env.messages(&general_b).await.iter().any(|m| m.text.contains("answer @Ada"))
+ })
+ .await;
+ // Bea's "@Ada" hands off to B's Ada, never to A's
+ wait_for("the handoff turn", || async {
+ calls_with("handed this conversation to you").iter().any(|(_, p)| p.contains("Bea handed"))
+ })
+ .await;
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ let a_msgs = env.messages(&env.general(&env.a).await).await;
+ assert!(!a_msgs.iter().any(|m| m.sender_id == env.ada_a.id), "A's Ada never spoke");
+ let handoff_replies: Vec<_> = env.messages(&general_b).await.into_iter().filter(|m| m.sender_id == env.ada_a.id).collect();
+ assert!(handoff_replies.is_empty());
+ let speakers = turn_kwants(&mut events);
+ assert!(speakers.contains(&env.ada_b.id), "B's Ada took the handoff: {speakers:?}");
+ assert!(!speakers.contains(&env.ada_a.id), "{speakers:?}");
+}
+
+// Startup and #general
+
+#[tokio::test]
+async fn a_second_general_in_a_space_is_refused_but_each_space_has_its_own() {
+ let env = setup(true).await;
+ let again = env
+ .state
+ .db
+ .create_channel(&env.b, &NewChannel {
+ name: "general".into(),
+ description: None,
+ lead_kwant_id: env.ada_b.id.clone(),
+ member_kwants: vec![env.ada_b.id.clone()],
+ routing_mode: "auto".into(),
+ })
+ .await;
+ assert!(matches!(again, Err(kwnt::db::DbError::Conflict(_))));
+ assert_ne!(env.general(&env.a).await, env.general(&env.b).await);
+ // A channel can't take members from another space
+ let mixed = env
+ .state
+ .db
+ .create_channel(&env.b, &NewChannel {
+ name: "mixed".into(),
+ description: None,
+ lead_kwant_id: env.ada_b.id.clone(),
+ member_kwants: vec![env.ada_b.id.clone(), env.ada_a.id.clone()],
+ routing_mode: "auto".into(),
+ })
+ .await;
+ assert!(matches!(mixed, Err(kwnt::db::DbError::OtherSpace(_))));
+}
diff --git a/tests/spaces_migration_test.rs b/tests/spaces_migration_test.rs
index 4db1985c..7cf2ff37 100644
--- a/tests/spaces_migration_test.rs
+++ b/tests/spaces_migration_test.rs
@@ -141,7 +141,7 @@ async fn migration_keeps_every_row_and_id_and_backs_up_first() {
("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);
+ let claude_default = db.list_profiles(&kwnt::db::spaces::SpaceId::default_space()).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();
@@ -195,25 +195,31 @@ async fn migration_runs_once() {
assert_eq!(backups(tmp.path()).len(), 1, "no second backup");
}
+/// Starts kwnt on `dir`, expecting it to refuse; returns the reason it gave.
+async fn refused_start(dir: &std::path::Path) -> String {
+ match Database::init(dir).await {
+ Ok(_) => panic!("startup should refuse a database below schema version 1"),
+ Err(e) => e.to_string(),
+ }
+}
+
#[tokio::test]
-async fn backup_failure_leaves_the_old_schema_and_retries_next_start() {
+async fn backup_failure_refuses_startup_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);
+ // Startup refuses rather than run without spaces, and leaves the old schema as it was
+ let refused = refused_start(tmp.path()).await;
+ assert!(refused.contains("can't start"), "{refused}");
+ assert!(refused.contains("Nothing was changed"), "{refused}");
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();
@@ -222,7 +228,7 @@ async fn backup_failure_leaves_the_old_schema_and_retries_next_start() {
}
#[tokio::test]
-async fn failed_schema_change_rolls_back_everything() {
+async fn failed_schema_change_rolls_back_everything_and_refuses_startup() {
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
@@ -230,8 +236,8 @@ async fn failed_schema_change_rolls_back_everything() {
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);
+ let refused = refused_start(tmp.path()).await;
+ assert!(refused.contains("rolled back"), "{refused}");
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
@@ -300,11 +306,11 @@ async fn fresh_database_starts_with_spaces_and_no_backup() {
}
// The existing DB layer writes through unchanged and lands in Default
let team = db
- .create_team(&kwnt::db::models::NewTeam {
+ .create_team(&kwnt::db::spaces::SpaceId::default_space(), &kwnt::db::models::NewTeam {
name: "web".into(),
description: None,
icon: None,
- lead_kwant_id: db.list_kwants().await.unwrap()[0].id.clone(),
+ lead_kwant_id: db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap()[0].id.clone(),
member_kwants: vec![],
workspace_path: None,
repo_url: None,