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.

Flight School (Phase C3): per-class tiers that can only add cards

Lin (kwant bot)04b3758c49b2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5c19edbb..46b79615 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
### Added
+- **Flight School: give each bot only as much freedom as it has earned.** With the new `flight_school`
+ setting on (off by default), you can set a bot's tier per kind of task: Observe (every change asks),
+ Sandbox (it may change files in its task folder when kwant took a checkpoint it can undo; every command
+ asks) or Act (its normal approvals). A tier only adds approval cards, even with approvals off, and
+ payments still always ask. Lowering a tier applies from the bot's next action. Bots already there keep
+ Act; bots hired after you switch it on start at Sandbox. A bot on Codex or a custom engine that is below
+ Act doesn't run its task, because kwant can't see its own tools.
- **kwant can tell when an app finished connecting through Composio.** A new person-only
`GET /api/connections/composio/apps/:slug/status` answers whether you've signed in to the app, so the
connection card can show "Connected" once you have.
diff --git a/docs/mcp-api.md b/docs/mcp-api.md
index 03599f8c..ea93421b 100644
--- a/docs/mcp-api.md
+++ b/docs/mcp-api.md
@@ -287,6 +287,9 @@ bot's approvals are `off`, or `smart` and the server marks the tool `readOnlyHin
2. The UI resolves it with the existing `POST /api/approvals/:id/resolve`
`{"decision": "allow_once" | "always_allow" | "deny"}`.
`always_allow` allows that tool for that kwant until kwnt restarts.
+ With Flight School on (`flight_school`), a bot below `act` for the task it works gets a card for calls
+ its tier doesn't allow even with approvals `off` or a smart Allow, with `details.tier_reason`; see
+ [mission-control.md](mission-control.md) §14.
3. Unanswered tickets are denied after 300 s, or when the turn ends or is cancelled; kwnt then
emits `{"type":"ApprovalWithdrawn","data":{"id":"<ticket>"}}` so the UI can drop the card.
Resolving a withdrawn (or unknown) ticket returns `409` and changes nothing: its tool never
diff --git a/docs/mission-control.md b/docs/mission-control.md
index 70ae4613..0e5c7067 100644
--- a/docs/mission-control.md
+++ b/docs/mission-control.md
@@ -490,3 +490,77 @@ acceptance, a routine) is only ever proposed; it applies when the person approve
- `task_json` gains `recovery_spent_tokens`, `recovery_budget_tokens`, `last_failure: {class, summary, created_at}|null` and `autofix: attempt|null` and `autofix_attempts` (retries AutoFix started: running, succeeded or failed). Needs-you kinds: `autofix_suggested`, `fix_needed`, `workflow_change`.
- Insights gain `autofix_7d: {attempts, succeeded, tokens}` and `failures_by_class_7d`, for the space.
- Task events: `failure`, `autofix_scheduled`, `autofix_started`, `autofix_finished`, `workflow_change_proposed`, `workflow_change_decided`, `workflow_change_applied`.
+
+## 14. Flight School (Phase C3)
+
+Design and decisions: `/home/maus/shared/ship-software-safely/mission-control/phase-c/contract.md` §3
+and §9 (D4, D7, D8, D9, D10). A bot's tier for a class of tasks is a **ceiling** on top of its approval
+mode: it can add a card, never remove one. Scorecards and tier proposals are C4, not here.
+
+### Settings
+
+- `flight_school` (bool, default `false`). Off, nothing is gated, whatever tiers are saved: every call
+ takes exactly today's path. On, tiers apply to turns that work a task (a chat turn of a bot with no open
+ claim is never gated).
+- `flight_school_new_bot_tier` (`observe`, `sandbox` or `act`, default `sandbox`): the `'*'` tier a bot hired
+ while Flight School is on starts at (a trigger on `kwants`). Bots that were there before have no row,
+ which is `act` (D4), so switching the feature on changes nothing until the person lowers a bot.
+
+### Tables
+
+- `tasks.task_class` (`TEXT NOT NULL DEFAULT 'general'`, slug `[a-z0-9-]{1,40}`). Set by the person
+ (`POST /api/tasks`, `PATCH /api/tasks/:id`, `POST /api/missions`) or a lead's `mission_plan`, never for a
+ task the planning bot would run itself (owner, or no owner and it leads). Forks inherit it. A change
+ writes a `class_changed` task event.
+- `capability_policies`: `id`, `kwant_id`, `task_class` (a class or `'*'`), `tier`, `granted_by`
+ (`CHECK = 'person'`), `granted_at`, `revoked_at`, `note`. One live row per bot and class
+ (`capability_live`). Rows are never deleted or edited; the only update sets `revoked_at` once (triggers).
+- `capability_events` (append-only): `kwant_id`, `task_class`, `kind` (`granted`, `revoked`,
+ `new_bot_default`), `tier`, `actor`, `detail`, `created_at`.
+- Rollback: `kwnt::db::flight_school::FLIGHT_SCHOOL_DOWN` drops the tables and triggers and the column
+ (tested).
+
+### The gate
+
+`flight_school::tier_gate(db, data_dir, req)` is the one function, asked at four points:
+`BrokerApprover::classified` (MCP tools and claude's tools that ask), the built-in Allow of claude's
+permission prompt (an allowed in-folder write falls through to the approver instead), `SelfToolsApprover`
+(kwant's own tools) and `approve_local_shell_in` (the API drivers' `execute_shell`). It reads the policy on
+every call. In order:
+
+1. The payment floor (`payment_floor::reason`). No tier skips it; at `act` a payment still cards.
+2. Flight School off, or the turn works no task → no gate.
+3. The tier for the task's class: the bot's row for that class, else its `'*'` row, else `act`. A policy
+ that can't be read counts as `observe` (fails closed).
+4. The call's effect: `checkpoints::effect` (the ledger's), with kwant's `memory_*`, `fact_*`, `task_*`,
+ `mission_plan`, `tier_status`, `ask_user` and read-only self tools as `none`.
+
+| effect | `observe` | `sandbox` | `act` |
+|---|---|---|---|
+| `none` | today's path | today's path | today's path |
+| `workspace` (file tool in the task folder) | card | runs if this run has a `before_run` checkpoint, else card | today's path |
+| `external` (`Bash`, MCP tools, outside files, other self tools) | card | card | today's path |
+
+A forced card carries `details.tier_reason` ("Sandbox: commands always ask", "Observe: every change
+asks", …). Approvals `off`, smart Allow and `always_ask` don't skip it; a session "always allow" for that
+tool in that chat does (D9), except on a payment.
+
+### Revoke and engines
+
+- `POST /api/capabilities/:kwant_id/revoke` writes the lower tier in one transaction; the running turn's
+ next call is gated by it. A call already allowed and running finishes.
+- The engine guard (D7): a task whose bot is below `act` on Codex or a custom engine (whose own tools kwant
+ can't see) is moved to `blocked` with the reason "This engine can't be held to its tier…" and the
+ Needs-you item `engine_cant_sandbox`: in the runner before the claim (pinned engines), and at turn start
+ once the route is known (an `auto` bot routed there). Claude and Grok run.
+
+### Routes
+
+- `GET /api/capabilities?kwant_id=&space=` (open): `{flight_school, kwant_id, default_tier, policies,
+ effective: [{task_class, tier, from: class|any_class|default|unreadable}], events}`.
+- `POST /api/capabilities` `{kwant_id, task_class, tier, note?}` (person only): sets the tier; the same tier
+ again returns `unchanged: true`.
+- `POST /api/capabilities/:kwant_id/revoke` `{task_class, to_tier: observe|sandbox, note?}` (person only):
+ lowers it; a tier that isn't lower returns `unchanged: true`.
+- Bot tool `tier_status {task_class?}` (read-only, offered with the task board).
+- `task_json` gains `task_class` and `owner_tier` (`null` while Flight School is off).
diff --git a/src/db/autofix.rs b/src/db/autofix.rs
index c0561b04..c0211ff7 100644
--- a/src/db/autofix.rs
+++ b/src/db/autofix.rs
@@ -337,13 +337,18 @@ impl Database {
/// used one), and its claim is the attempt's, so its spend is recovery.
pub async fn link_retry_task(&self, task_id: &str, failed: &Task, attempt_id: &str) -> Result<(), DbError> {
let mut tx = self.pool.begin().await?;
- sqlx::query("UPDATE tasks SET forked_from = ?, attempts = ?, max_attempts = ? WHERE id = ? AND forked_from IS NULL")
- .bind(&failed.id)
- .bind(failed.attempts + 1)
- .bind(failed.max_attempts)
- .bind(task_id)
- .execute(&mut *tx)
- .await?;
+ // It keeps the failed task's Flight School class (and so its tier)
+ sqlx::query(
+ "UPDATE tasks SET forked_from = ?, attempts = ?, max_attempts = ?, task_class = (SELECT task_class FROM tasks WHERE id = ?) \
+ WHERE id = ? AND forked_from IS NULL",
+ )
+ .bind(&failed.id)
+ .bind(failed.attempts + 1)
+ .bind(failed.max_attempts)
+ .bind(&failed.id)
+ .bind(task_id)
+ .execute(&mut *tx)
+ .await?;
sqlx::query("UPDATE agent_claims SET autofix_id = ? WHERE task_id = ? AND released_at IS NULL").bind(attempt_id).bind(task_id).execute(&mut *tx).await?;
tx.commit().await?;
Ok(())
diff --git a/src/db/flight_school.rs b/src/db/flight_school.rs
new file mode 100644
index 00000000..9ff8fba4
--- /dev/null
+++ b/src/db/flight_school.rs
@@ -0,0 +1,336 @@
+//! Mission Control Phase C3: Flight School's bookkeeping. A task's class (`tasks.task_class`), the
+//! tier the person gave a bot for a class (`capability_policies`, one live row per bot and class,
+//! `'*'` for every class without its own) and what happened to those tiers (`capability_events`,
+//! append-only). Only person-only routes write policies; the gate reads them on every call.
+//! Contract: docs/mission-control.md §14.
+
+use super::{Database, DbError};
+use chrono::Utc;
+use serde::Serialize;
+use sqlx::FromRow;
+use uuid::Uuid;
+
+pub const TIERS: [&str; 3] = ["observe", "sandbox", "act"];
+/// The class of every task nobody gave one.
+pub const DEFAULT_CLASS: &str = "general";
+/// The policy row that covers every class without its own.
+pub const ANY_CLASS: &str = "*";
+
+/// Undoes [`Database::migrate_flight_school`]: the tables go and `tasks` gets back the shape older
+/// releases read. Kept for rollbacks and tested.
+pub const FLIGHT_SCHOOL_DOWN: &str = "DROP TRIGGER IF EXISTS kwants_flight_school_default; \
+ DROP TRIGGER IF EXISTS capability_policies_no_delete; \
+ DROP TRIGGER IF EXISTS capability_policies_only_revoke; \
+ DROP TRIGGER IF EXISTS capability_events_no_update; \
+ DROP TRIGGER IF EXISTS capability_events_no_delete; \
+ DROP TABLE IF EXISTS capability_events; \
+ DROP INDEX IF EXISTS capability_live; \
+ DROP TABLE IF EXISTS capability_policies; \
+ ALTER TABLE tasks DROP COLUMN task_class";
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct Policy {
+ pub id: String,
+ pub kwant_id: String,
+ pub task_class: String,
+ pub tier: String,
+ pub granted_by: String,
+ pub granted_at: String,
+ pub revoked_at: Option<String>,
+ pub note: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct CapabilityEvent {
+ pub id: i64,
+ pub kwant_id: String,
+ pub task_class: String,
+ pub kind: String,
+ pub tier: Option<String>,
+ pub actor: String,
+ pub detail: Option<String>,
+ pub created_at: String,
+}
+
+/// `observe` < `sandbox` < `act`; an unknown tier is the lowest.
+pub fn rank(tier: &str) -> usize {
+ TIERS.iter().position(|t| *t == tier).unwrap_or(0)
+}
+
+/// A class slug: `[a-z0-9-]{1,40}` (D10).
+pub fn valid_class(class: &str) -> bool {
+ (1..=40).contains(&class.len()) && class.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
+}
+
+const TRIGGERS: [&str; 5] = [
+ // A tier row is never deleted or rewritten: revoking sets `revoked_at` once, and a new row
+ // carries the new tier
+ "CREATE TRIGGER IF NOT EXISTS capability_policies_no_delete BEFORE DELETE ON capability_policies \
+ BEGIN SELECT RAISE(ABORT, 'tier history is kept'); END",
+ "CREATE TRIGGER IF NOT EXISTS capability_policies_only_revoke BEFORE UPDATE ON capability_policies \
+ WHEN OLD.revoked_at IS NOT NULL OR NEW.revoked_at IS NULL OR NEW.id IS NOT OLD.id OR NEW.kwant_id IS NOT OLD.kwant_id \
+ OR NEW.task_class IS NOT OLD.task_class OR NEW.tier IS NOT OLD.tier OR NEW.granted_by IS NOT OLD.granted_by \
+ OR NEW.granted_at IS NOT OLD.granted_at \
+ BEGIN SELECT RAISE(ABORT, 'a tier can only be revoked'); END",
+ "CREATE TRIGGER IF NOT EXISTS capability_events_no_update BEFORE UPDATE ON capability_events \
+ BEGIN SELECT RAISE(ABORT, 'capability events are append-only'); END",
+ "CREATE TRIGGER IF NOT EXISTS capability_events_no_delete BEFORE DELETE ON capability_events \
+ BEGIN SELECT RAISE(ABORT, 'capability events are append-only'); END",
+ // A bot hired while Flight School is on starts at the person's default for new bots (§3.6, D4).
+ // Existing bots have no row, which is `act`: switching the feature on changes nothing for them.
+ "CREATE TRIGGER IF NOT EXISTS kwants_flight_school_default AFTER INSERT ON kwants \
+ WHEN (SELECT value FROM settings WHERE key = 'flight_school') = 'true' \
+ BEGIN \
+ INSERT INTO capability_policies (id, kwant_id, task_class, tier, granted_by, granted_at, note) \
+ VALUES (lower(hex(randomblob(16))), NEW.id, '*', \
+ COALESCE((SELECT value FROM settings WHERE key = 'flight_school_new_bot_tier' AND value IN ('observe', 'sandbox', 'act')), 'sandbox'), \
+ 'person', strftime('%Y-%m-%dT%H:%M:%fZ', 'now'), 'new bot default'); \
+ INSERT INTO capability_events (kwant_id, task_class, kind, tier, actor, detail, created_at) \
+ SELECT NEW.id, '*', 'new_bot_default', tier, 'person', NULL, granted_at FROM capability_policies \
+ WHERE kwant_id = NEW.id AND task_class = '*' AND revoked_at IS NULL; \
+ END",
+];
+
+impl Database {
+ pub(super) async fn migrate_flight_school(&self) -> Result<(), DbError> {
+ // Additive only: one new column with a default, new tables, new triggers
+ let has_class: Option<(String,)> =
+ sqlx::query_as("SELECT name FROM pragma_table_info('tasks') WHERE name = 'task_class'").fetch_optional(&self.pool).await?;
+ if has_class.is_none() {
+ sqlx::query("ALTER TABLE tasks ADD COLUMN task_class TEXT NOT NULL DEFAULT 'general'").execute(&self.pool).await?;
+ }
+ for stmt in [
+ "CREATE TABLE IF NOT EXISTS capability_policies (
+ id TEXT PRIMARY KEY,
+ kwant_id TEXT NOT NULL,
+ task_class TEXT NOT NULL,
+ tier TEXT NOT NULL CHECK (tier IN ('observe', 'sandbox', 'act')),
+ granted_by TEXT NOT NULL CHECK (granted_by = 'person'),
+ granted_at TEXT NOT NULL,
+ revoked_at TEXT,
+ note TEXT
+ )",
+ "CREATE UNIQUE INDEX IF NOT EXISTS capability_live ON capability_policies (kwant_id, task_class) WHERE revoked_at IS NULL",
+ "CREATE TABLE IF NOT EXISTS capability_events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ kwant_id TEXT NOT NULL,
+ task_class TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ tier TEXT,
+ actor TEXT NOT NULL,
+ detail TEXT,
+ created_at TEXT NOT NULL
+ )",
+ "CREATE INDEX IF NOT EXISTS capability_events_kwant ON capability_events (kwant_id, id)",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ for t in TRIGGERS {
+ sqlx::query(t).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ /// The task's class; `general` for a task that isn't there.
+ pub async fn task_class(&self, task_id: &str) -> Result<String, DbError> {
+ let row: Option<(String,)> = sqlx::query_as("SELECT task_class FROM tasks WHERE id = ?").bind(task_id).fetch_optional(&self.pool).await?;
+ Ok(row.map_or_else(|| DEFAULT_CLASS.to_string(), |r| r.0))
+ }
+
+ /// Sets a task's class and records a `class_changed` task event. Callers validate the slug and
+ /// who may set it (the lead or the person, never the task's own bot).
+ pub async fn set_task_class(&self, task_id: &str, class: &str, actor: &str) -> Result<bool, DbError> {
+ let mut tx = self.pool.begin().await?;
+ let row: Option<(String, Option<String>)> =
+ sqlx::query_as("SELECT task_class, mission_id FROM tasks WHERE id = ?").bind(task_id).fetch_optional(&mut *tx).await?;
+ let Some((old, mission)) = row else { return Ok(false) };
+ if old == class {
+ return Ok(true);
+ }
+ sqlx::query("UPDATE tasks SET task_class = ?, updated_at = ? WHERE id = ?").bind(class).bind(Utc::now()).bind(task_id).execute(&mut *tx).await?;
+ super::missions::insert_event(&mut tx, task_id, mission.as_deref(), "class_changed", actor, None, None, &serde_json::json!({"from": old, "to": class}))
+ .await?;
+ tx.commit().await?;
+ Ok(true)
+ }
+
+ /// The live policy for `kwant_id` on `class`: its own row, else the `'*'` row. `None`: no row,
+ /// which means `act`.
+ pub async fn live_policy(&self, kwant_id: &str, class: &str) -> Result<Option<Policy>, DbError> {
+ Ok(sqlx::query_as::<_, Policy>(
+ "SELECT * FROM capability_policies WHERE kwant_id = ? AND revoked_at IS NULL AND task_class IN (?, '*') \
+ ORDER BY task_class = '*' LIMIT 1",
+ )
+ .bind(kwant_id)
+ .bind(class)
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ /// Every live policy of a bot, by class.
+ pub async fn policies_of(&self, kwant_id: &str) -> Result<Vec<Policy>, DbError> {
+ Ok(sqlx::query_as::<_, Policy>("SELECT * FROM capability_policies WHERE kwant_id = ? AND revoked_at IS NULL ORDER BY task_class")
+ .bind(kwant_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// The classes a bot's tasks have, for the capabilities view.
+ pub async fn classes_of(&self, kwant_id: &str) -> Result<Vec<String>, DbError> {
+ let rows: Vec<(String,)> = sqlx::query_as(
+ "SELECT DISTINCT task_class FROM tasks WHERE owner_kwant_id = ?1 OR suggested_kwant_id = ?1 ORDER BY task_class",
+ )
+ .bind(kwant_id)
+ .fetch_all(&self.pool)
+ .await?;
+ Ok(rows.into_iter().map(|r| r.0).collect())
+ }
+
+ pub async fn capability_events(&self, kwant_id: &str, limit: i64) -> Result<Vec<CapabilityEvent>, DbError> {
+ Ok(sqlx::query_as::<_, CapabilityEvent>("SELECT * FROM capability_events WHERE kwant_id = ? ORDER BY id DESC LIMIT ?")
+ .bind(kwant_id)
+ .bind(limit)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// The person sets `tier` for a bot on `class` (`'*'` for every class without its own): the live
+ /// row, if any, is revoked and the new one written in one transaction, with an event of `kind`
+ /// (`granted` or `revoked`). The unique index keeps one live row per bot and class.
+ pub async fn set_policy(&self, kwant_id: &str, class: &str, tier: &str, kind: &str, note: Option<&str>) -> Result<Policy, DbError> {
+ let now = Utc::now().to_rfc3339();
+ let mut tx = self.pool.begin().await?;
+ sqlx::query("UPDATE capability_policies SET revoked_at = ? WHERE kwant_id = ? AND task_class = ? AND revoked_at IS NULL")
+ .bind(&now)
+ .bind(kwant_id)
+ .bind(class)
+ .execute(&mut *tx)
+ .await?;
+ let policy = sqlx::query_as::<_, Policy>(
+ "INSERT INTO capability_policies (id, kwant_id, task_class, tier, granted_by, granted_at, note) VALUES (?, ?, ?, ?, 'person', ?, ?) RETURNING *",
+ )
+ .bind(Uuid::new_v4().to_string())
+ .bind(kwant_id)
+ .bind(class)
+ .bind(tier)
+ .bind(&now)
+ .bind(note)
+ .fetch_one(&mut *tx)
+ .await?;
+ sqlx::query("INSERT INTO capability_events (kwant_id, task_class, kind, tier, actor, detail, created_at) VALUES (?, ?, ?, ?, 'person', ?, ?)")
+ .bind(kwant_id)
+ .bind(class)
+ .bind(kind)
+ .bind(tier)
+ .bind(note)
+ .bind(&now)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(policy)
+ }
+
+ /// Whether the task's open claim (the run going on now) has a usable `before_run` checkpoint:
+ /// what lets a sandboxed bot write in its task folder.
+ pub async fn run_has_checkpoint(&self, task_id: &str) -> Result<bool, DbError> {
+ let row: Option<(i64,)> = sqlx::query_as(
+ "SELECT 1 FROM task_checkpoints cp JOIN agent_claims c ON c.id = cp.claim_id \
+ WHERE cp.task_id = ? AND cp.kind = 'before_run' AND cp.error IS NULL AND c.released_at IS NULL LIMIT 1",
+ )
+ .bind(task_id)
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(row.is_some())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ async fn db() -> (tempfile::TempDir, Database) {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ (tmp, db)
+ }
+
+ #[test]
+ fn class_slugs() {
+ for ok in ["general", "seo-audit", "a", "x1", &"a".repeat(40)] {
+ assert!(valid_class(ok), "{ok}");
+ }
+ for bad in ["", "*", "Upper", "a b", "a_b", "é", &"a".repeat(41)] {
+ assert!(!valid_class(bad), "{bad}");
+ }
+ assert!(rank("observe") < rank("sandbox") && rank("sandbox") < rank("act"));
+ }
+
+ #[tokio::test]
+ async fn policies_are_revoked_never_rewritten_and_events_are_append_only() {
+ let (_tmp, db) = db().await;
+ db.set_policy("k1", "*", "sandbox", "granted", None).await.unwrap();
+ let p = db.set_policy("k1", "*", "observe", "revoked", Some("too many denials")).await.unwrap();
+ assert_eq!(db.live_policy("k1", "general").await.unwrap().unwrap().id, p.id);
+ let rows: Vec<(String, Option<String>)> =
+ sqlx::query_as("SELECT tier, revoked_at FROM capability_policies WHERE kwant_id = 'k1' ORDER BY granted_at").fetch_all(&db.pool).await.unwrap();
+ assert_eq!(rows.len(), 2);
+ assert!(rows.iter().filter(|r| r.1.is_none()).count() == 1);
+ assert!(sqlx::query("UPDATE capability_policies SET tier = 'act' WHERE id = ?").bind(&p.id).execute(&db.pool).await.is_err());
+ assert!(sqlx::query("DELETE FROM capability_policies").execute(&db.pool).await.is_err());
+ assert!(sqlx::query("INSERT INTO capability_policies (id, kwant_id, task_class, tier, granted_by, granted_at) VALUES ('x', 'k1', 'a', 'act', 'k1', 'now')")
+ .execute(&db.pool)
+ .await
+ .is_err());
+ assert!(sqlx::query("UPDATE capability_events SET tier = 'act'").execute(&db.pool).await.is_err());
+ assert!(sqlx::query("DELETE FROM capability_events").execute(&db.pool).await.is_err());
+ assert_eq!(db.capability_events("k1", 10).await.unwrap().len(), 2);
+ }
+
+ #[tokio::test]
+ async fn a_class_row_beats_the_star_row() {
+ let (_tmp, db) = db().await;
+ db.set_policy("k1", "*", "observe", "granted", None).await.unwrap();
+ db.set_policy("k1", "seo", "act", "granted", None).await.unwrap();
+ assert_eq!(db.live_policy("k1", "seo").await.unwrap().unwrap().tier, "act");
+ assert_eq!(db.live_policy("k1", "general").await.unwrap().unwrap().tier, "observe");
+ assert!(db.live_policy("k2", "general").await.unwrap().is_none());
+ }
+
+ #[tokio::test]
+ async fn a_bot_hired_with_flight_school_on_starts_at_the_new_bot_tier() {
+ let (_tmp, db) = db().await;
+ let space = crate::db::spaces::SpaceId::new(crate::db::spaces::DEFAULT_SPACE_ID);
+ let new = |name: &str| crate::db::models::NewKwant {
+ name: name.into(),
+ title: String::new(),
+ persona_prompt: String::new(),
+ soul: String::new(),
+ avatar_sprite: String::new(),
+ driver_type: "api".into(),
+ preferred_model: "auto".into(),
+ };
+ let before = db.create_kwant(&space, &new("Before")).await.unwrap();
+ assert!(db.policies_of(&before.id).await.unwrap().is_empty());
+ db.set_setting("flight_school", "true").await.unwrap();
+ let after = db.create_kwant(&space, &new("After")).await.unwrap();
+ let p = db.policies_of(&after.id).await.unwrap();
+ assert_eq!((p.len(), p[0].task_class.as_str(), p[0].tier.as_str()), (1, "*", "sandbox"));
+ db.set_setting("flight_school_new_bot_tier", "observe").await.unwrap();
+ let third = db.create_kwant(&space, &new("Third")).await.unwrap();
+ assert_eq!(db.policies_of(&third.id).await.unwrap()[0].tier, "observe");
+ assert!(db.policies_of(&before.id).await.unwrap().is_empty(), "existing bots stay at act");
+ }
+
+ #[tokio::test]
+ async fn the_down_migration_restores_the_old_shape_and_up_runs_again() {
+ let (_tmp, db) = db().await;
+ sqlx::raw_sql(FLIGHT_SCHOOL_DOWN).execute(&db.pool).await.unwrap();
+ let col: Option<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info('tasks') WHERE name = 'task_class'").fetch_optional(&db.pool).await.unwrap();
+ assert!(col.is_none());
+ let t: Option<(String,)> = sqlx::query_as("SELECT name FROM sqlite_master WHERE name = 'capability_policies'").fetch_optional(&db.pool).await.unwrap();
+ assert!(t.is_none());
+ db.migrate_flight_school().await.unwrap();
+ db.migrate_flight_school().await.unwrap();
+ assert_eq!(db.task_class("missing").await.unwrap(), "general");
+ }
+}
diff --git a/src/db/mission_graph.rs b/src/db/mission_graph.rs
index 204311e8..db1c7184 100644
--- a/src/db/mission_graph.rs
+++ b/src/db/mission_graph.rs
@@ -272,8 +272,8 @@ impl Database {
}
let fork = sqlx::query_as::<_, Task>(
"INSERT INTO tasks (id, space_id, mission_id, title, acceptance, state, priority, suggested_kwant_id, budget_tokens, max_attempts, \
- source_kind, source_id, channel_id, direct_kwant_id, thread_id, created_by, created_at, updated_at, forked_from) \
- VALUES (?, ?, ?, ?, ?, 'backlog', ?, ?, ?, ?, ?, NULL, ?, ?, ?, 'person', ?, ?, ?) RETURNING *",
+ source_kind, source_id, channel_id, direct_kwant_id, thread_id, created_by, created_at, updated_at, forked_from, task_class) \
+ VALUES (?, ?, ?, ?, ?, 'backlog', ?, ?, ?, ?, ?, NULL, ?, ?, ?, 'person', ?, ?, ?, (SELECT task_class FROM tasks WHERE id = ?)) RETURNING *",
)
.bind(&fork_id)
.bind(&orig.space_id)
@@ -291,6 +291,7 @@ impl Database {
.bind(now)
.bind(now)
.bind(&orig.id)
+ .bind(&orig.id)
.fetch_one(&mut *tx)
.await?;
sqlx::query("INSERT INTO task_dependencies (task_id, depends_on_id) SELECT ?, depends_on_id FROM task_dependencies WHERE task_id = ?")
diff --git a/src/db/mod.rs b/src/db/mod.rs
index eb04f77a..b450b194 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -28,6 +28,7 @@ pub mod missions;
pub mod mission_graph;
pub mod checkpoints;
pub mod autofix;
+pub mod flight_school;
/// What a space's #general says about itself.
pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
@@ -178,6 +179,8 @@ impl Database {
db.repair_team_channels().await?;
db.migrate_approval_modes(fresh, data_dir).await?;
}
+ // After the spaces migration, which can rebuild `kwants` (and drop its triggers)
+ db.migrate_flight_school().await?;
db.pool.close().await;
let pool = SqlitePoolOptions::new()
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index 19df03e5..a0e065c2 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -320,6 +320,12 @@ pub trait ToolApprover: Send + Sync {
/// `auto_allowed`, `approved` or `denied`. Called for the calls the permission hook lets
/// through on its own too. Default: nothing is recorded.
async fn note(&self, _request: &ToolApprovalRequest, _decision: &'static str, _approval_id: Option<&str>) {}
+
+ /// Flight School's gate (C3): `Some(reason)` when this call must get a card even where the
+ /// permission hook would let it through on its own. Default: no gate.
+ async fn tier_gate(&self, _request: &ToolApprovalRequest) -> Option<String> {
+ None
+ }
}
/// What became of a call that may have needed a card.
diff --git a/src/server/auth.rs b/src/server/auth.rs
index af664032..677539cd 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -340,6 +340,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {
// AutoFix's proposed changes to routines, checks and tasks: only the person reads, approves
// or rejects them; bots only propose (the `workflow_propose` tool)
["", "api", "workflow-changes", ..] => true,
+ // Flight School: only the person gives or takes a bot's freedom (C3); reads stay open
+ ["", "api", "capabilities", ..] => *method != Method::GET && *method != Method::HEAD,
// App-wide settings, including where notifications go (`notify_webhook_url`), and the
// sub-routes such as `/computer` (which machine the bots run on) and `/computer/window`:
// bots change the allowed ones through their `settings_update` action, never these routes
diff --git a/src/server/computer.rs b/src/server/computer.rs
index 21f402ab..b2d0d286 100644
--- a/src/server/computer.rs
+++ b/src/server/computer.rs
@@ -201,6 +201,14 @@ pub async fn approve_local_shell_in(
if let Some(why) = &payment {
details["payment_reason"] = json!(why);
}
+ // Flight School (C3): below act, a command always asks, approvals off or not
+ let tier = match payment {
+ Some(_) => None,
+ None => super::missions::flight_school::shell_gate(&state.db, target_id).await,
+ };
+ if let Some(why) = tier {
+ details["tier_reason"] = json!(why);
+ }
// "Always this session" under smart: per bot and conversation, like claude's tools
let remembered = conversation.filter(|_| mode == SMART && payment.is_none());
if crate::sandbox::credentials::call_touches_kwnt_secrets(&details["arguments"], Some(cwd)) {
@@ -221,7 +229,7 @@ pub async fn approve_local_shell_in(
return true;
}
}
- if payment.is_none() && (mode == OFF || verdict.as_ref().is_some_and(|v| v.is_allowed())) {
+ if payment.is_none() && tier.is_none() && (mode == OFF || verdict.as_ref().is_some_and(|v| v.is_allowed())) {
if verdict.is_some() {
tracing::info!(target = %target_id, "ran a local command without a card: not risky");
}
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index e0e04b3b..61714a85 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -342,7 +342,7 @@ pub struct SelfToolsApprover {
}
/// The agents' own tools that only read: free even in an always-ask turn.
-const READ_ONLY_SELF_TOOLS: &[&str] = &[
+pub(crate) const READ_ONLY_SELF_TOOLS: &[&str] = &[
"search_history",
"memory_search",
"delegation_status",
@@ -359,6 +359,7 @@ const READ_ONLY_SELF_TOOLS: &[&str] = &[
super::page_source::TOOL,
"skill_get",
"task_list",
+ "tier_status",
];
#[async_trait]
@@ -381,6 +382,10 @@ impl ToolApprover for SelfToolsApprover {
}
}
if req.server == SELF_SERVER_NAME && (!self.always_ask || READ_ONLY_SELF_TOOLS.contains(&req.tool.as_str())) {
+ // Flight School: a tier below act cards kwant's own tools that change things
+ if self.inner.tier_gate(&req).await.is_some() {
+ return self.inner.decide(req).await;
+ }
self.inner.note(&req, "allowed", None).await;
return crate::mcp::ApprovalOutcome::Allowed;
}
@@ -390,6 +395,10 @@ impl ToolApprover for SelfToolsApprover {
async fn note(&self, req: &ToolApprovalRequest, decision: &'static str, approval_id: Option<&str>) {
self.inner.note(req, decision, approval_id).await
}
+
+ async fn tier_gate(&self, req: &ToolApprovalRequest) -> Option<String> {
+ self.inner.tier_gate(req).await
+ }
}
/// The address the turn's browser shows now, without starting a browser.
@@ -404,6 +413,7 @@ fn tool_list(scope: &SelfScope, board: bool) -> Value {
if let Some(list) = tools.as_array_mut() {
if board {
list.extend(super::missions::tools::tools());
+ list.push(super::missions::flight_school::tool());
}
list.extend(super::skills::tools());
list.extend(super::mcp_suggest::tools());
@@ -873,6 +883,7 @@ async fn call_tool(
n if super::bot_actions::handles(n) => super::bot_actions::call(state, scope, n, args).await,
n if super::hires::handles(n) => super::hires::call(state, scope, n, args).await,
n if super::missions::tools::handles(n) => super::missions::tools::call(state, scope, n, args).await,
+ "tier_status" => super::missions::flight_school::call_tool(state, &scope.kwant_id, args).await,
"list_attachments" if scope.origin.is_some() => super::attachments::tool_list(state, scope).await,
"share_file" if scope.origin.is_some() => super::attachments::tool_share(state, scope, args).await,
"delegate" => super::delegation::tool_delegate(state, scope, args).await,
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 0f76657b..b6671cfe 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -172,6 +172,11 @@ impl ToolApprover for BrokerApprover {
async fn note(&self, req: &ToolApprovalRequest, decision: &'static str, approval_id: Option<&str>) {
super::missions::checkpoints::log_call(&self.db, &self.data_dir, req, decision, approval_id).await;
}
+
+ async fn tier_gate(&self, req: &ToolApprovalRequest) -> Option<String> {
+ // Boxed: keeps this future (and every caller's) small
+ Box::pin(super::missions::flight_school::tier_gate(&self.db, &self.data_dir, req)).await
+ }
}
impl BrokerApprover {
@@ -183,7 +188,14 @@ impl BrokerApprover {
// The payment floor (D8): a call that pays always gets a card, whatever the approvals,
// "Ask only when risky" or "always allow" say. Allowing it covers this one call.
let payment = req.payment.clone().or_else(|| mcp::payment_floor::reason(&req, None));
- let off = payment.is_none() && !self.always_ask && mode.as_ref().is_some_and(|m| m.is_off());
+ // Flight School (C3): the bot's tier for this task can add a card, never remove one. It
+ // skips approvals off and smart Allow; a session "always allow" still counts (D9).
+ let tier = match payment {
+ Some(_) => None,
+ None => self.tier_gate(&req).await,
+ };
+ let forced = payment.is_some() || tier.is_some();
+ let off = !forced && !self.always_ask && mode.as_ref().is_some_and(|m| m.is_off());
// "Ask only when risky": what the caller made of this call; nothing known asks. A turn that
// always asks (it read outside text) still lets claude's plain read tools through.
let smart = mode
@@ -192,7 +204,7 @@ impl BrokerApprover {
.then(|| req.smart.clone())
.flatten()
.filter(|_| !self.always_ask || (req.builtin.is_some() && matches!(req.tool.as_str(), "Read" | "Glob" | "Grep")))
- .filter(|_| payment.is_none());
+ .filter(|_| !forced);
let mut details = match &req.builtin {
Some(b) => json!({
"source": "claude_builtin",
@@ -218,6 +230,9 @@ impl BrokerApprover {
if let Some(why) = &payment {
details["payment_reason"] = json!(why);
}
+ if let Some(why) = &tier {
+ details["tier_reason"] = json!(why);
+ }
let record = NewApproval {
turn_id: req.turn_id.clone(),
kwant_id: req.kwant_id.clone(),
@@ -620,11 +635,17 @@ async fn decide(session: &PermissionSession, args: &Value, smart: bool) -> Value
};
match decision {
mcp::builtin_tools::BuiltinDecision::Allow => {
- // No card and no approval record, but the task's ledger still gets it
let cwd = folder.or_else(|| session.cwd.clone()).map(|f| f.display().to_string());
- let req = noted_request(session, tool_name, "", tool_name, &input, Some(mcp::BuiltinCall { cwd, outside_folder: false }));
- session.ctx.approver.note(&req, "allowed", None).await;
- return json!({"behavior": "allow", "updatedInput": input});
+ let call = mcp::BuiltinCall { cwd, outside_folder: false };
+ let req = noted_request(session, tool_name, "", tool_name, &input, Some(call.clone()));
+ // Flight School: a tier below act sends even an in-folder write to the approver
+ if session.ctx.approver.tier_gate(&req).await.is_some() {
+ ("", tool_name, Some(call))
+ } else {
+ // No card and no approval record, but the task's ledger still gets it
+ session.ctx.approver.note(&req, "allowed", None).await;
+ return json!({"behavior": "allow", "updatedInput": input});
+ }
}
mcp::builtin_tools::BuiltinDecision::Ask { outside_folder } => {
if smart {
diff --git a/src/server/missions/flight_school.rs b/src/server/missions/flight_school.rs
new file mode 100644
index 00000000..7ad8a0e7
--- /dev/null
+++ b/src/server/missions/flight_school.rs
@@ -0,0 +1,386 @@
+//! Mission Control Phase C3: Flight School. A bot's tier for a class of tasks (`observe`,
+//! `sandbox`, `act`) is a ceiling on top of its approval mode: it can add a card, never remove one.
+//! [`tier_gate`] is the one function every permission path asks (`BrokerApprover::classified`,
+//! claude's built-in Allow, kwant's own tools, and the API drivers' shell); it reads the policy on
+//! every call, so a revoke holds from the next call on. Off (the default) gates nothing.
+//! Contract: docs/mission-control.md §14.
+
+use super::routes::{bad, conflict, internal, not_found};
+use super::{bot_in_space, task_folder_in, transition, Actor};
+use crate::db::flight_school::{rank, valid_class, ANY_CLASS, DEFAULT_CLASS, TIERS};
+use crate::db::missions::{Task, TaskChange};
+use crate::db::Database;
+use crate::mcp::ToolApprovalRequest;
+use crate::server::spaces::Scope;
+use crate::server::AppState;
+use axum::{
+ extract::{Path, Query, State},
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+pub const SETTING: &str = "flight_school";
+pub const NEW_BOT_SETTING: &str = "flight_school_new_bot_tier";
+pub const DEFAULT_NEW_BOT_TIER: &str = "sandbox";
+/// A task's blocked reason when its bot's engine runs tools kwant can't see (D7).
+pub const ENGINE_CANT_SANDBOX: &str = "This engine can't be held to its tier: switch the bot to Claude or grant Act";
+
+pub async fn enabled(db: &Database) -> bool {
+ matches!(db.get_setting(SETTING).await.ok().flatten().as_deref().map(str::trim), Some("true" | "1" | "on"))
+}
+
+pub async fn new_bot_tier(db: &Database) -> &'static str {
+ let v = db.get_setting(NEW_BOT_SETTING).await.ok().flatten();
+ TIERS.iter().copied().find(|t| Some(*t) == v.as_deref().map(str::trim)).unwrap_or(DEFAULT_NEW_BOT_TIER)
+}
+
+pub fn settings_error(new_bot_tier: Option<&str>) -> Option<String> {
+ new_bot_tier.filter(|t| !TIERS.contains(t)).map(|t| format!("flight_school_new_bot_tier must be observe, sandbox or act (got {t})"))
+}
+
+/// The bot's tier for `class`: its row for the class, else its `'*'` row, else `act` (D4: bots
+/// that were there before Flight School keep today's freedom). A policy that can't be read is
+/// `observe`: the gate fails closed.
+pub async fn tier_of(db: &Database, kwant_id: &str, class: &str) -> (&'static str, &'static str) {
+ match db.live_policy(kwant_id, class).await {
+ Ok(Some(p)) => (TIERS[rank(&p.tier)], if p.task_class == ANY_CLASS { "any_class" } else { "class" }),
+ Ok(None) => ("act", "default"),
+ Err(e) => {
+ tracing::warn!(error = %e, kwant = %kwant_id, "could not read a Flight School tier; treating it as observe");
+ ("observe", "unreadable")
+ }
+ }
+}
+
+/// kwant's own tools that change nothing outside the chat or the board: free at every tier. The
+/// rest of the self tools are `external`, as the side-effect ledger counts them.
+fn self_tool_is_free(tool: &str) -> bool {
+ tool.starts_with("memory_")
+ || tool.starts_with("fact_")
+ || tool.starts_with("task_")
+ || matches!(tool, "mission_plan" | "tier_status" | "ask_user")
+ || crate::server::continuity::READ_ONLY_SELF_TOOLS.contains(&tool)
+}
+
+/// The call's effect for the gate: the ledger's [`super::checkpoints::effect`], with kwant's free
+/// self tools as `none`.
+pub fn gate_effect(req: &ToolApprovalRequest, task_folder: Option<&std::path::Path>) -> &'static str {
+ if req.server == crate::mcp::SELF_SERVER_NAME && self_tool_is_free(&req.tool) {
+ return "none";
+ }
+ super::checkpoints::effect(req, task_folder)
+}
+
+/// What `tier` says about a call of `effect`: `None` leaves it to today's path, `Some(reason)`
+/// forces a card. `checkpoint` is whether this run has a usable `before_run` checkpoint.
+pub fn decide(tier: &str, effect: &str, bash: bool, checkpoint: bool) -> Option<&'static str> {
+ match (tier, effect) {
+ ("act", _) | (_, "none") => None,
+ ("sandbox", "workspace") if checkpoint => None,
+ ("sandbox", "workspace") => Some("Sandbox: this run has no checkpoint to undo file changes, so they ask"),
+ ("sandbox", _) if bash => Some("Sandbox: commands always ask"),
+ ("sandbox", _) => Some("Sandbox: only files in the task folder change without asking"),
+ _ => Some("Observe: every change asks"),
+ }
+}
+
+/// The one Flight School gate (§3.3). The payment floor comes first and no tier skips it; then,
+/// only with `flight_school` on and only for a turn that works a task, the bot's live tier for the
+/// task's class against the call's effect. `Some(reason)`: the call gets a card whatever the
+/// approval mode, smart Allow or `always_ask` say (a session "always allow" still counts, D9).
+pub async fn tier_gate(db: &Database, data_dir: &std::path::Path, req: &ToolApprovalRequest) -> Option<String> {
+ if let Some(why) = req.payment.clone().or_else(|| crate::mcp::payment_floor::reason(req, None)) {
+ return Some(why);
+ }
+ if !enabled(db).await {
+ return None;
+ }
+ let task = task_of(db, &req.kwant_id, &req.turn_id).await?;
+ let class = db.task_class(&task.id).await.unwrap_or_else(|_| DEFAULT_CLASS.into());
+ let (tier, _) = tier_of(db, &req.kwant_id, &class).await;
+ if tier == "act" {
+ return None;
+ }
+ let folder = task_folder_in(db, data_dir, &task).await;
+ let effect = gate_effect(req, folder.as_deref());
+ let checkpoint = effect == "workspace" && db.run_has_checkpoint(&task.id).await.unwrap_or(false);
+ decide(tier, effect, req.builtin.is_some() && req.tool_name == "Bash", checkpoint).map(str::to_string)
+}
+
+/// The gate for a shell command an API driver runs (`execute_shell`): always `external`.
+pub async fn shell_gate(db: &Database, kwant_id: &str) -> Option<&'static str> {
+ if !enabled(db).await {
+ return None;
+ }
+ let task = task_of(db, kwant_id, "").await?;
+ let class = db.task_class(&task.id).await.unwrap_or_else(|_| DEFAULT_CLASS.into());
+ let (tier, _) = tier_of(db, kwant_id, &class).await;
+ decide(tier, "external", true, false)
+}
+
+async fn task_of(db: &Database, kwant_id: &str, turn_id: &str) -> Option<Task> {
+ let id = db.task_of_turn(kwant_id, turn_id).await.ok().flatten()?;
+ db.get_task(&id).await.ok().flatten()
+}
+
+/// Whether kwant sees every tool call of a bot on this engine (§3.5): Claude (permission prompt)
+/// and Grok (only MCP tools) do. Codex runs its shell and file tools in its own sandbox, and a
+/// custom engine outside kwant's gateway, so neither can be held below `act`.
+pub fn engine_can_be_gated(model_or_family: &str) -> bool {
+ let m = model_or_family.trim().to_ascii_lowercase();
+ !matches!(m.as_str(), "codex" | "custom")
+ && !matches!(crate::profiles::Engine::from_model(&m), Some(crate::profiles::Engine::Codex | crate::profiles::Engine::Custom))
+}
+
+/// The engine guard (D7) before a runner turn: a task whose bot is below `act` and pinned to an
+/// engine kwant can't gate is blocked with [`ENGINE_CANT_SANDBOX`] instead of running unguarded.
+/// `true` when it was blocked.
+pub async fn block_if_ungated(state: &AppState, task: &Task, bot: &crate::db::models::Kwant, model: Option<&str>) -> bool {
+ if !enabled(&state.db).await {
+ return false;
+ }
+ let pinned = crate::router::parse_pin(&bot.preferred_model).family;
+ let Some(engine) = model.map(str::to_string).or(pinned) else { return false };
+ if engine_can_be_gated(&engine) {
+ return false;
+ }
+ let class = state.db.task_class(&task.id).await.unwrap_or_else(|_| DEFAULT_CLASS.into());
+ if tier_of(&state.db, &bot.id, &class).await.0 == "act" {
+ return false;
+ }
+ let Ok(Some(t)) = state.db.get_task(&task.id).await else { return false };
+ let change = TaskChange { reason: Some(ENGINE_CANT_SANDBOX.into()), ..Default::default() };
+ match transition(state, &t.id, &t.state, "blocked", Actor::Kwant, "kwant", change).await {
+ Ok(_) => {
+ tracing::info!(task_id = %t.id, kwant = %bot.id, engine = %engine, "Flight School: blocked a task its engine can't be held to");
+ true
+ }
+ Err(_) => false,
+ }
+}
+
+/// The same guard once a turn knows its engine: an `auto` bot routed to Codex or a custom engine
+/// while it works a task below `act`. The task is blocked and the turn doesn't start.
+pub async fn refuse_turn(state: &AppState, bot: &crate::db::models::Kwant, model: &str) -> Option<String> {
+ if engine_can_be_gated(model) || !enabled(&state.db).await {
+ return None;
+ }
+ let task = task_of(&state.db, &bot.id, "").await?;
+ block_if_ungated(state, &task, bot, Some(model)).await.then(|| format!("{}: {ENGINE_CANT_SANDBOX}.", bot.name))
+}
+
+/// The task's Needs-you item when the engine guard blocked it.
+pub fn needs_you(task: &Task) -> Option<Value> {
+ (task.state == "blocked" && task.blocked_reason.as_deref() == Some(ENGINE_CANT_SANDBOX))
+ .then(|| json!({"kind": "engine_cant_sandbox", "id": task.id, "text": ENGINE_CANT_SANDBOX}))
+}
+
+/// `owner_tier` on task JSON: the tier of the bot that runs (or would run) the task, with Flight
+/// School on; `null` when it is off.
+pub async fn owner_tier(state: &AppState, task: &Task) -> Value {
+ if !enabled(&state.db).await {
+ return Value::Null;
+ }
+ let Some(bot) = task.owner_kwant_id.as_deref().or(task.suggested_kwant_id.as_deref()) else { return Value::Null };
+ let class = state.db.task_class(&task.id).await.unwrap_or_else(|_| DEFAULT_CLASS.into());
+ json!(tier_of(&state.db, bot, &class).await.0)
+}
+
+/// A bot's tiers: its live rows and, per class its tasks have, the tier that applies and why.
+pub async fn status_json(state: &AppState, kwant_id: &str) -> Value {
+ let policies = state.db.policies_of(kwant_id).await.unwrap_or_default();
+ let mut classes = state.db.classes_of(kwant_id).await.unwrap_or_default();
+ for p in &policies {
+ if p.task_class != ANY_CLASS && !classes.contains(&p.task_class) {
+ classes.push(p.task_class.clone());
+ }
+ }
+ if !classes.iter().any(|c| c == DEFAULT_CLASS) {
+ classes.insert(0, DEFAULT_CLASS.into());
+ }
+ let mut effective = Vec::new();
+ for c in &classes {
+ let (tier, from) = tier_of(&state.db, kwant_id, c).await;
+ effective.push(json!({"task_class": c, "tier": tier, "from": from}));
+ }
+ let any = policies.iter().find(|p| p.task_class == ANY_CLASS).map(|p| p.tier.clone());
+ json!({
+ "flight_school": enabled(&state.db).await,
+ "kwant_id": kwant_id,
+ "default_tier": any.unwrap_or_else(|| "act".into()),
+ "policies": policies,
+ "effective": effective,
+ "events": state.db.capability_events(kwant_id, 50).await.unwrap_or_default(),
+ })
+}
+
+// Routes: reads are open like the rest of the app API, writes are person-only (`auth.rs`)
+
+#[derive(Deserialize)]
+pub struct CapQuery {
+ kwant_id: String,
+}
+
+/// `GET /api/capabilities?kwant_id=`.
+pub async fn get_capabilities(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<CapQuery>) -> Response {
+ let Some(bot) = bot_in_space(&state, &space, &q.kwant_id).await else { return not_found("bot") };
+ Json(status_json(&state, &bot.id).await).into_response()
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct SetTier {
+ kwant_id: String,
+ task_class: String,
+ tier: String,
+ note: Option<String>,
+}
+
+fn class_ok(class: &str) -> bool {
+ class == ANY_CLASS || valid_class(class)
+}
+
+/// `POST /api/capabilities` (person-only): sets a bot's tier for a class, or `'*'` for every class
+/// without its own row. Setting the tier it already has changes nothing (safe to repeat).
+pub async fn set_capability(State(state): State<AppState>, Scope(space): Scope, Json(p): Json<SetTier>) -> Response {
+ if !class_ok(&p.task_class) {
+ return bad("task_class must be * or 1–40 of a-z, 0-9 and -");
+ }
+ if !TIERS.contains(&p.tier.as_str()) {
+ return bad("tier must be observe, sandbox or act");
+ }
+ let note = p.note.as_deref().map(str::trim).filter(|n| !n.is_empty()).map(|n| n.chars().take(500).collect::<String>());
+ let Some(bot) = bot_in_space(&state, &space, &p.kwant_id).await else { return not_found("bot") };
+ let own = state.db.policies_of(&bot.id).await.unwrap_or_default();
+ if own.iter().any(|x| x.task_class == p.task_class && x.tier == p.tier) {
+ return Json(json!({"unchanged": true, "capabilities": status_json(&state, &bot.id).await})).into_response();
+ }
+ match state.db.set_policy(&bot.id, &p.task_class, &p.tier, "granted", note.as_deref()).await {
+ Ok(_) => Json(json!({"unchanged": false, "capabilities": status_json(&state, &bot.id).await})).into_response(),
+ Err(crate::db::DbError::Sqlx(e)) if e.to_string().contains("UNIQUE") => conflict("another change to this tier landed first; reload"),
+ Err(e) => internal(e),
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Revoke {
+ task_class: String,
+ to_tier: String,
+ note: Option<String>,
+}
+
+/// `POST /api/capabilities/:kwant_id/revoke` (person-only): lowers a bot's tier for a class at
+/// once. The next tool call of a running turn is gated by the new tier; a call already running
+/// finishes. Revoking to the tier it already has (or a higher one) changes nothing.
+pub async fn revoke_capability(State(state): State<AppState>, Scope(space): Scope, Path(kwant_id): Path<String>, Json(p): Json<Revoke>) -> Response {
+ if !class_ok(&p.task_class) {
+ return bad("task_class must be * or 1–40 of a-z, 0-9 and -");
+ }
+ if !matches!(p.to_tier.as_str(), "observe" | "sandbox") {
+ return bad("to_tier must be observe or sandbox");
+ }
+ let Some(bot) = bot_in_space(&state, &space, &kwant_id).await else { return not_found("bot") };
+ let class = if p.task_class == ANY_CLASS { DEFAULT_CLASS } else { p.task_class.as_str() };
+ let now = if p.task_class == ANY_CLASS {
+ state.db.policies_of(&bot.id).await.unwrap_or_default().into_iter().find(|x| x.task_class == ANY_CLASS).map_or("act", |x| TIERS[rank(&x.tier)])
+ } else {
+ tier_of(&state.db, &bot.id, class).await.0
+ };
+ if rank(&p.to_tier) >= rank(now) {
+ return Json(json!({"unchanged": true, "capabilities": status_json(&state, &bot.id).await})).into_response();
+ }
+ let note = p.note.as_deref().map(str::trim).filter(|n| !n.is_empty()).map(|n| n.chars().take(500).collect::<String>());
+ match state.db.set_policy(&bot.id, &p.task_class, &p.to_tier, "revoked", note.as_deref()).await {
+ Ok(_) => Json(json!({"unchanged": false, "capabilities": status_json(&state, &bot.id).await})).into_response(),
+ Err(crate::db::DbError::Sqlx(e)) if e.to_string().contains("UNIQUE") => conflict("another change to this tier landed first; reload"),
+ Err(e) => internal(e),
+ }
+}
+
+// The `tier_status` bot tool (read-only)
+
+pub fn tool() -> Value {
+ json!({
+ "name": "tier_status",
+ "description": "Your Flight School tier: how much you may do on your own per class of task (observe: every change asks; sandbox: only files in the task folder, with a checkpoint; act: your normal approvals). Only the person changes it.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {"task_class": {"type": "string", "description": "One class; leave out for all."}},
+ },
+ })
+}
+
+pub async fn call_tool(state: &AppState, kwant_id: &str, args: &Value) -> (String, bool) {
+ let mut v = status_json(state, kwant_id).await;
+ if let Some(class) = args["task_class"].as_str().map(str::trim).filter(|c| !c.is_empty()) {
+ if !valid_class(class) {
+ return ("task_class must be 1–40 of a-z, 0-9 and -".into(), true);
+ }
+ let (tier, from) = tier_of(&state.db, kwant_id, class).await;
+ v["effective"] = json!([{"task_class": class, "tier": tier, "from": from}]);
+ }
+ if let Some(obj) = v.as_object_mut() {
+ obj.remove("events");
+ }
+ (serde_json::to_string_pretty(&v).unwrap_or_default(), false)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_tier_table() {
+ // (tier, effect, bash, checkpoint) → card?
+ for (tier, effect, bash, cp, card) in [
+ ("act", "workspace", false, false, false),
+ ("act", "external", true, false, false),
+ ("sandbox", "none", false, false, false),
+ ("sandbox", "workspace", false, true, false),
+ ("sandbox", "workspace", false, false, true),
+ ("sandbox", "external", true, true, true),
+ ("sandbox", "external", false, true, true),
+ ("observe", "none", false, false, false),
+ ("observe", "workspace", false, true, true),
+ ("observe", "external", true, true, true),
+ ] {
+ assert_eq!(decide(tier, effect, bash, cp).is_some(), card, "{tier} {effect} bash={bash} cp={cp}");
+ }
+ assert_eq!(decide("sandbox", "external", true, true), Some("Sandbox: commands always ask"));
+ }
+
+ #[test]
+ fn engines_kwant_can_hold() {
+ for ok in ["claude", "claude-sonnet-4-6", "grok", "grok-4", "anthropic/claude-opus"] {
+ assert!(engine_can_be_gated(ok), "{ok}");
+ }
+ for no in ["codex", "gpt-5-codex", "gpt-5", "custom", "custom:claude-sonnet-4.6"] {
+ assert!(!engine_can_be_gated(no), "{no}");
+ }
+ }
+
+ #[test]
+ fn free_self_tools() {
+ let req = |tool: &str| ToolApprovalRequest {
+ kwant_id: "k".into(),
+ kwant_name: "K".into(),
+ turn_id: "t".into(),
+ tool_name: format!("mcp__{}__{tool}", crate::mcp::SELF_SERVER_NAME),
+ server: crate::mcp::SELF_SERVER_NAME.into(),
+ tool: tool.into(),
+ arguments: json!({}),
+ builtin: None,
+ smart: None,
+ payment: None,
+ };
+ for free in ["memory_add", "task_update", "mission_plan", "tier_status", "ask_user", "search_history"] {
+ assert_eq!(gate_effect(&req(free), None), "none", "{free}");
+ }
+ for ext in ["browser_act", "bot_update", "channel_update", "settings_update", "delegate"] {
+ assert_eq!(gate_effect(&req(ext), None), "external", "{ext}");
+ }
+ }
+}
diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rs
index c37c9923..fe1739a2 100644
--- a/src/server/missions/mod.rs
+++ b/src/server/missions/mod.rs
@@ -15,6 +15,7 @@
pub mod autofix;
pub mod checkpoints;
pub mod checks;
+pub mod flight_school;
pub mod graph;
pub mod listener;
pub mod routes;
@@ -491,6 +492,7 @@ pub async fn needs_you(state: &AppState, task: &Task) -> Vec<Value> {
let mut items = owner_needs_you(state, task).await;
items.extend(autofix::needs_you(state, task).await);
items.extend(graph::flag_items(state, task).await);
+ items.extend(flight_school::needs_you(task));
items
}
@@ -555,6 +557,8 @@ pub async fn task_json(state: &AppState, task: &Task) -> Value {
obj.insert("checkpoint_count".into(), json!(count));
obj.insert("last_checkpoint_at".into(), json!(last));
autofix::extend_task_json(state, task, obj).await;
+ obj.insert("task_class".into(), json!(state.db.task_class(&task.id).await.unwrap_or_else(|_| crate::db::flight_school::DEFAULT_CLASS.into())));
+ obj.insert("owner_tier".into(), flight_school::owner_tier(state, task).await);
}
v
}
@@ -675,6 +679,8 @@ pub struct PlanTask {
pub budget_tokens: Option<i64>,
#[serde(default)]
pub checks: Vec<PlanCheck>,
+ /// Flight School's class (D10); `general` when left out.
+ pub task_class: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
@@ -802,6 +808,16 @@ pub async fn create_plan(
Some(o) => Some(bot_in_space(state, space, o).await.ok_or_else(|| format!("task {key}: no bot {o} in this space"))?.id),
None => None,
};
+ if let Some(class) = &t.task_class {
+ if !crate::db::flight_school::valid_class(class) {
+ return Err(format!("task {key}: task_class must be 1–40 of a-z, 0-9 and -"));
+ }
+ // A bot never picks the class (and so the tier) of a task it would run itself
+ let runner = owner.as_deref().unwrap_or(lead.id.as_str());
+ if by.created_by != "person" && runner == by.created_by {
+ return Err(format!("task {key}: you can't set the class of a task you'd run yourself; leave task_class out"));
+ }
+ }
owners.push(owner);
let mut ok = Vec::new();
for c in &t.checks {
@@ -868,6 +884,9 @@ pub async fn create_plan(
)
.await
.map_err(|e| e.to_string())?;
+ if let Some(class) = t.task_class.as_deref().filter(|c| *c != crate::db::flight_school::DEFAULT_CLASS) {
+ state.db.set_task_class(&row.id, class, by.created_by).await.map_err(|e| e.to_string())?;
+ }
for (c, approved) in t.checks.iter().zip(&approvals[i]) {
state
.db
diff --git a/src/server/missions/routes.rs b/src/server/missions/routes.rs
index 8f78aea8..e56c0475 100644
--- a/src/server/missions/routes.rs
+++ b/src/server/missions/routes.rs
@@ -427,6 +427,8 @@ pub struct CreateTask {
checks: Vec<PlanCheck>,
source_kind: Option<String>,
source_id: Option<String>,
+ /// Flight School's class (D10); `general` when left out.
+ task_class: Option<String>,
}
pub async fn create_task(State(state): State<AppState>, Scope(space): Scope, Json(p): Json<CreateTask>) -> Response {
@@ -451,6 +453,9 @@ pub async fn create_task(State(state): State<AppState>, Scope(space): Scope, Jso
if p.priority.is_some_and(|x| !(0..=3).contains(&x)) {
return bad("priority must be 0–3");
}
+ if p.task_class.as_deref().is_some_and(|c| !crate::db::flight_school::valid_class(c)) {
+ return bad("task_class must be 1–40 of a-z, 0-9 and -");
+ }
let mission = match &p.mission_id {
Some(id) => match state.db.get_mission(id).await {
Ok(Some(m)) if m.space_id == space.as_str() => {
@@ -517,6 +522,11 @@ pub async fn create_task(State(state): State<AppState>, Scope(space): Scope, Jso
Ok(t) => t,
Err(e) => return internal(e),
};
+ if let Some(class) = p.task_class.as_deref().filter(|c| *c != crate::db::flight_school::DEFAULT_CLASS) {
+ if let Err(e) = state.db.set_task_class(&task.id, class, "person").await {
+ return internal(e);
+ }
+ }
for (c, approved) in p.checks.iter().zip(approvals) {
let nc = NewCheck {
task_id: task.id.clone(),
@@ -583,6 +593,8 @@ pub struct PatchTask {
priority: Option<i64>,
owner_kwant_id: Option<String>,
budget_tokens: Option<i64>,
+ /// Only the person changes a class (this route is person-only for bot tokens).
+ task_class: Option<String>,
}
pub async fn patch_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, Json(p): Json<PatchTask>) -> Response {
@@ -603,6 +615,9 @@ pub async fn patch_task(State(state): State<AppState>, RawQuery(q): RawQuery, Pa
if p.budget_tokens.is_some_and(|b| !(1..=super::BUDGET_RANGE.1).contains(&b)) {
return bad(format!("budget_tokens must be 1–{}", super::BUDGET_RANGE.1));
}
+ if p.task_class.as_deref().is_some_and(|c| !crate::db::flight_school::valid_class(c)) {
+ return bad("task_class must be 1–40 of a-z, 0-9 and -");
+ }
let owner = match &p.owner_kwant_id {
Some(o) => match super::bot_in_space(&state, &SpaceId::new(&t.space_id), o).await {
Some(k) => Some(k.id),
@@ -613,6 +628,11 @@ pub async fn patch_task(State(state): State<AppState>, RawQuery(q): RawQuery, Pa
if let Err(e) = state.db.edit_task(&id, title, p.acceptance.as_deref().map(str::trim), p.priority, owner.as_deref(), p.budget_tokens, "person").await {
return internal(e);
}
+ if let Some(class) = &p.task_class {
+ if let Err(e) = state.db.set_task_class(&id, class, "person").await {
+ return internal(e);
+ }
+ }
match state.db.get_task(&id).await {
Ok(Some(t)) => {
emit_task(&state, &t).await;
diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rs
index 2b1da25c..1e77f7d0 100644
--- a/src/server/missions/runner.rs
+++ b/src/server/missions/runner.rs
@@ -84,6 +84,11 @@ pub async fn run_mission(state: &AppState, mission: &Mission, max: usize) -> (Ve
if picked.iter().any(|(_, k)| k.id == bot.id) {
continue;
}
+ // Flight School (D7): a bot below act on an engine kwant can't gate doesn't run the task
+ if super::flight_school::block_if_ungated(state, t, &bot, None).await {
+ reason = Some(super::flight_school::ENGINE_CANT_SANDBOX.into());
+ continue;
+ }
let context = mission_context(mission, &bot);
match state.db.claim_task(&t.id, &bot.id, None, Some(&context), lease_ms(state).await, false, "kwant").await {
Ok(Ok(task)) => {
diff --git a/src/server/missions/tools.rs b/src/server/missions/tools.rs
index 9f523c44..ac1ed460 100644
--- a/src/server/missions/tools.rs
+++ b/src/server/missions/tools.rs
@@ -64,6 +64,7 @@ pub fn tools() -> Vec<Value> {
"depends_on": {"type": "array", "items": {"type": "string"}},
"budget_tokens": {"type": "integer"},
"checks": {"type": "array", "items": check_schema()},
+ "task_class": {"type": "string", "description": "Kind of work, as a short slug (seo-audit, release…); sets how much freedom its bot gets. Leave it out for tasks you'd run yourself."},
},
"required": ["title", "acceptance"],
},
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 5e5a39c9..faa2c105 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -386,6 +386,8 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/tasks/:id/autofix", post(missions::autofix::run_autofix))
.route("/api/tasks/:id/autofix/:aid/cancel", post(missions::autofix::cancel_autofix))
.route("/api/workflow-changes", get(missions::autofix::list_changes))
+ .route("/api/capabilities", get(missions::flight_school::get_capabilities).post(missions::flight_school::set_capability))
+ .route("/api/capabilities/:kwant_id/revoke", post(missions::flight_school::revoke_capability))
.route("/api/workflow-changes/:id/approve", post(missions::autofix::approve_change))
.route("/api/workflow-changes/:id/reject", post(missions::autofix::reject_change))
.route("/api/tasks/:id/flags/:flag_id/resolve", post(missions::graph::resolve_flag))
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 15b5fdf3..d6ccad33 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1863,6 +1863,12 @@ async fn run_kwant_turn_inner(
let route = crate::router::apply_preferred_model(route, &target_kwant.preferred_model);
let target_model = route.selected_model.clone();
+ // Flight School (D7): a task below act never runs on an engine kwant can't gate
+ if let Some(text) = Box::pin(super::missions::flight_school::refuse_turn(state, target_kwant, &target_model)).await {
+ event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));
+ event_broadcast.send(RuntimeEvent::TurnComplete { tokens: 0, duration_ms: 0, kwant_id: Some(target_kwant.id.clone()), profile_id: None });
+ return Err(text);
+ }
let effort_level = route.effort_level.clone();
let tier = route.tier.unwrap_or(crate::drivers::engines::Tier::Balanced);
let pinned_model = route.model.clone();
@@ -3277,6 +3283,10 @@ pub struct SettingsResponse {
pub autofix: String,
/// Share of a task's budget its AutoFix retries may spend (0–100).
pub recovery_budget_pct: i64,
+ /// Flight School: tiers are enforced for task turns (see `super::missions::flight_school`).
+ pub flight_school: bool,
+ /// The tier a bot hired while Flight School is on starts at, for every class.
+ pub flight_school_new_bot_tier: String,
}
/// Unknown keys are refused, so a typo or a key from another version fails loudly instead of
@@ -3317,6 +3327,8 @@ pub struct SaveSettingsPayload {
pub checkpoint_keep: Option<i64>,
pub autofix: Option<String>,
pub recovery_budget_pct: Option<i64>,
+ pub flight_school: Option<bool>,
+ pub flight_school_new_bot_tier: Option<String>,
}
pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {
@@ -3366,6 +3378,8 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settings
checkpoint_keep: super::missions::checkpoints::keep(&state).await,
autofix: super::missions::autofix::mode(&state).await.into(),
recovery_budget_pct: super::missions::autofix::recovery_pct(&state).await,
+ flight_school: super::missions::flight_school::enabled(&state.db).await,
+ flight_school_new_bot_tier: super::missions::flight_school::new_bot_tier(&state.db).await.into(),
}))
}
@@ -3421,6 +3435,9 @@ pub async fn save_settings(
if let Some(e) = super::missions::autofix::settings_error(payload.autofix.as_deref(), payload.recovery_budget_pct) {
return bad(e);
}
+ if let Some(e) = super::missions::flight_school::settings_error(payload.flight_school_new_bot_tier.as_deref()) {
+ return bad(e);
+ }
if payload.chain_token_budget.is_some_and(|n| n > super::budget::MAX) {
return bad(format!("chain_token_budget must be 0–{}", super::budget::MAX));
}
@@ -3534,6 +3551,12 @@ pub async fn save_settings(
if let Some(n) = payload.recovery_budget_pct {
let _ = state.db.set_setting(super::missions::autofix::PCT_SETTING, &n.to_string()).await;
}
+ if let Some(on) = payload.flight_school {
+ let _ = state.db.set_setting(super::missions::flight_school::SETTING, if on { "true" } else { "false" }).await;
+ }
+ if let Some(t) = &payload.flight_school_new_bot_tier {
+ let _ = state.db.set_setting(super::missions::flight_school::NEW_BOT_SETTING, t).await;
+ }
if let Some(on) = payload.agent_tools {
let _ = state.db.set_setting("agent_tools", if on { "on" } else { "off" }).await;
}
diff --git a/tests/flight_school_test.rs b/tests/flight_school_test.rs
new file mode 100644
index 00000000..a493686a
--- /dev/null
+++ b/tests/flight_school_test.rs
@@ -0,0 +1,471 @@
+//! Mission Control Phase C3: Flight School. A bot's tier for a class of tasks is a ceiling on top
+//! of its approval mode: it can add a card, never remove one, and the payment floor stays first.
+//! The contract's acceptance tests (docs/mission-control.md §14): the tier × effect table through
+//! claude's real permission endpoint, approvals off and smart Allow still carding in sandbox,
+//! observe carding an in-folder write, revoke gating the very next call, act and "off" being
+//! today's path, the person-only routes, the task class a bot can't pick, and the engine guard.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrono::Utc;
+use kwnt::{
+ broker::{ApprovalDecision, PermissionBroker},
+ config::Config,
+ db::{models::Kwant, spaces::SpaceId, Database},
+ drivers::events::RuntimeEvent,
+ mcp::{ApprovalOutcome, SmartVerdict, ToolApprovalRequest, ToolApprover, SELF_SERVER_NAME},
+ router::LayaRouter,
+ server::{
+ continuity::{SelfScope, SelfToolsApprover, TurnOrigin},
+ create_router, mcp_runtime,
+ turns::ActiveTurn,
+ AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::path::{Path, PathBuf};
+use std::{sync::Arc, time::Duration};
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+const STRIPE_POST: &str = "curl -X POST https://api.stripe.com/v1/charges -u sk_test_x: -d amount=100 -d currency=usd";
+
+struct Env {
+ app: Router,
+ state: AppState,
+ bot: Kwant,
+ general: String,
+ _tmp: TempDir,
+}
+
+async fn setup() -> Env {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let space = SpaceId::default_space();
+ let bot = state.db.list_kwants(&space).await.unwrap()[0].clone();
+ let general = state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap().id;
+ let e = Env { app: create_router(state.clone()), bot, general, state, _tmp: tmp };
+ person(&e, "POST", "/api/settings", json!({"mission_board": true})).await;
+ e
+}
+
+async fn call(app: &Router, method: &str, uri: &str, auth: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ if let Some(token) = auth {
+ req = req.header("authorization", format!("Bearer {token}"));
+ }
+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+async fn person(e: &Env, method: &str, uri: &str, body: Value) -> Value {
+ let body = (method != "GET").then_some(body);
+ let (status, v) = call(&e.app, method, uri, Some(e.state.api_token.reveal()), body).await;
+ assert!(status.is_success(), "{method} {uri}: {status} {v}");
+ v
+}
+
+async fn set_approvals(e: &Env, mode: &str) {
+ person(e, "PUT", &format!("/api/kwants/{}/approvals", e.bot.id), json!({"approvals": mode})).await;
+}
+
+async fn set_tier(e: &Env, class: &str, tier: &str) {
+ person(e, "POST", "/api/capabilities", json!({"kwant_id": e.bot.id, "task_class": class, "tier": tier})).await;
+}
+
+async fn flight_school(e: &Env, on: bool) {
+ person(e, "POST", "/api/settings", json!({"flight_school": on})).await;
+}
+
+fn id(v: &Value) -> String {
+ v["id"].as_str().unwrap().to_string()
+}
+
+/// A live turn of the bot in #general with its own tools, working in `folder`; returns (turn id, token).
+async fn turn(e: &Env, folder: &Path) -> (String, String) {
+ let turn_id = uuid::Uuid::new_v4().to_string();
+ let scope = SelfScope {
+ kwant_id: e.bot.id.clone(),
+ kwant_name: e.bot.name.clone(),
+ origin: Some(TurnOrigin { channel_id: Some(e.general.clone()), ..Default::default() }),
+ turn_id: Some(turn_id.clone()),
+ ..Default::default()
+ };
+ let (_, token) =
+ mcp_runtime::prepare_turn_with_opts(&e.state, &e.bot, Some(turn_id.clone()), Some(folder.to_path_buf()), Some(scope), Default::default())
+ .await
+ .unwrap();
+ e.state.turns.set_turn(ActiveTurn {
+ turn_id: turn_id.clone(),
+ kwant_id: e.bot.id.clone(),
+ context_id: e.general.clone(),
+ thread_id: None,
+ state: "running".into(),
+ since: Utc::now(),
+ purpose: None,
+ });
+ (turn_id, token)
+}
+
+async fn end(e: &Env, turn_id: &str, token: &str) {
+ mcp_runtime::finish_turn(&e.state, token).await;
+ e.state.turns.end_turn(turn_id);
+}
+
+async fn self_tool(e: &Env, token: &str, name: &str, args: Value) -> (bool, String) {
+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});
+ let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc)).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ (v["result"]["isError"].as_bool().unwrap_or(false), v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string())
+}
+
+/// A person's mission with one task the bot owns, of `class`, claimed by the bot (with a
+/// `before_run` checkpoint when `checkpoint`). Returns (task id, the task's folder).
+async fn claimed_task(e: &Env, class: &str, checkpoint: bool) -> (String, PathBuf) {
+ person(e, "POST", "/api/settings", json!({"checkpoints": checkpoint})).await;
+ let body = json!({"title": "Ship it", "goal": "a release", "lead_kwant_id": e.bot.id, "budget_tokens": 900_000,
+ "channel_id": e.general, "tasks": [{"title": "A", "owner": e.bot.id, "task_class": class}]});
+ let m = person(e, "POST", "/api/missions", body).await;
+ let detail = person(e, "GET", &format!("/api/missions/{}", id(&m)), json!(null)).await;
+ let tid = id(&detail["tasks"][0]);
+ let mission = e.state.db.get_mission(&id(&m)).await.unwrap().unwrap();
+ let dir = PathBuf::from(mission.workspace_path);
+ std::fs::create_dir_all(&dir).unwrap();
+ let (turn_id, token) = turn(e, &dir).await;
+ let (err, text) = self_tool(e, &token, "task_claim", json!({"task_id": tid})).await;
+ assert!(!err, "{text}");
+ end(e, &turn_id, &token).await;
+ assert_eq!(e.state.db.run_has_checkpoint(&tid).await.unwrap(), checkpoint);
+ (tid, dir)
+}
+
+/// What claude's permission prompt gets for `tool {input}` in a turn working in `folder`:
+/// `Ok(behavior)` when kwnt answers without a card, `Err(card details)` when it shows one (denied).
+async fn claude_asks(e: &Env, folder: &Path, tool: &str, input: Value) -> Result<String, Value> {
+ let (turn_id, token) = turn(e, folder).await;
+ let out = ask_in(e, &token, tool, input).await;
+ end(e, &turn_id, &token).await;
+ out
+}
+
+async fn ask_in(e: &Env, token: &str, tool: &str, input: Value) -> Result<String, Value> {
+ let mut events = e.state.event_sender.subscribe();
+ let ask = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "approve",
+ "arguments": {"tool_name": tool, "input": input, "tool_use_id": "tu_1"}}});
+ let app = e.app.clone();
+ let path = format!("/api/mcp/permission/{token}");
+ let mut prompt = tokio::spawn(async move { call(&app, "POST", &path, None, Some(ask)).await });
+ let behavior = |v: &Value| {
+ let text = v["result"]["content"][0]["text"].as_str().unwrap();
+ serde_json::from_str::<Value>(text).unwrap()["behavior"].as_str().unwrap().to_string()
+ };
+ let answered = tokio::time::timeout(Duration::from_millis(1500), &mut prompt).await;
+ let card = loop {
+ match events.try_recv() {
+ Ok(RuntimeEvent::ApprovalRequired { id, details, .. }) => break Some((id, details)),
+ Ok(_) => continue,
+ Err(_) => break None,
+ }
+ };
+ match (answered, card) {
+ (Ok(done), None) => Ok(behavior(&done.unwrap().1)),
+ (Err(_), Some((id, details))) => {
+ assert!(e.state.broker.resolve(&id, ApprovalDecision::Deny).await);
+ let (_, v) = prompt.await.unwrap();
+ assert_eq!(behavior(&v), "deny");
+ Err(details)
+ }
+ (answered, card) => panic!("answered {} with card {card:?}", answered.is_ok()),
+ }
+}
+
+fn approver(e: &Env) -> mcp_runtime::BrokerApprover {
+ mcp_runtime::BrokerApprover {
+ db: e.state.db.clone(),
+ data_dir: e.state.config.data_dir.clone(),
+ broker: e.state.broker.clone(),
+ events: e.state.event_sender.clone(),
+ timeout: Duration::from_millis(200),
+ conversation: e.general.clone(),
+ chat: None,
+ always_ask: false,
+ }
+}
+
+fn request(e: &Env, server: &str, tool: &str, arguments: Value) -> ToolApprovalRequest {
+ ToolApprovalRequest {
+ kwant_id: e.bot.id.clone(),
+ kwant_name: e.bot.name.clone(),
+ turn_id: "t-fs".into(),
+ tool_name: if server.is_empty() { tool.to_string() } else { format!("mcp__{server}__{tool}") },
+ server: server.into(),
+ tool: tool.into(),
+ arguments,
+ builtin: None,
+ smart: None,
+ payment: None,
+ }
+}
+
+fn bash(e: &Env, command: &str) -> ToolApprovalRequest {
+ let mut req = request(e, "", "Bash", json!({"command": command}));
+ req.builtin = Some(kwnt::mcp::BuiltinCall { cwd: None, outside_folder: false });
+ req
+}
+
+fn write_in(dir: &Path) -> Value {
+ json!({"file_path": dir.join("notes.md").display().to_string(), "content": "hi"})
+}
+
+fn reason(details: &Value) -> &str {
+ details["tier_reason"].as_str().unwrap_or("")
+}
+
+/// The calls the tier tests make, and what claude's permission prompt answered for each.
+async fn outcomes(e: &Env, dir: &Path) -> Vec<Result<String, Value>> {
+ let mut out = Vec::new();
+ for (tool, input) in [
+ ("Write", write_in(dir)),
+ ("Read", json!({"file_path": dir.join("notes.md").display().to_string()})),
+ ("Bash", json!({"command": "touch x"})),
+ ("Write", json!({"file_path": "/tmp/flight-school-outside.txt", "content": "x"})),
+ ] {
+ out.push(claude_asks(e, dir, tool, input).await);
+ }
+ out
+}
+
+#[tokio::test]
+async fn flight_school_off_gates_nothing_even_with_a_lower_tier_saved() {
+ let e = setup().await;
+ set_approvals(&e, "off").await;
+ let (_tid, dir) = claimed_task(&e, "general", false).await;
+ let before = outcomes(&e, &dir).await;
+ // The person saved observe for every class, but Flight School is off
+ set_tier(&e, "*", "observe").await;
+ let after = outcomes(&e, &dir).await;
+ assert_eq!(before, after);
+ assert!(after.iter().all(|o| o == &Ok("allow".to_string())), "{after:?}");
+ // Kwant's own tools and the API drivers' shell too
+ let a = SelfToolsApprover { inner: Arc::new(approver(&e)), always_ask: false, browser: None };
+ assert_eq!(a.decide(request(&e, SELF_SERVER_NAME, "bot_update", json!({}))).await, ApprovalOutcome::Allowed);
+ assert!(kwnt::server::computer::approve_local_shell(&e.state, &e.bot.id, "touch x", &dir).await);
+ // The task says nothing about tiers while it is off
+ let t = person(&e, "GET", &format!("/api/tasks/{_tid}"), json!(null)).await;
+ assert_eq!(t["task"]["owner_tier"], Value::Null);
+ assert_eq!(t["task"]["task_class"], "general");
+ // Under ask, cards are today's: no tier_reason
+ set_approvals(&e, "ask").await;
+ let Err(details) = claude_asks(&e, &dir, "Bash", json!({"command": "touch x"})).await else { panic!("ask mode cards Bash") };
+ assert!(details.get("tier_reason").is_none(), "{details}");
+}
+
+#[tokio::test]
+async fn sandbox_cards_every_command_and_outside_write_and_needs_a_checkpoint_for_folder_writes() {
+ let e = setup().await;
+ set_approvals(&e, "off").await;
+ flight_school(&e, true).await;
+ set_tier(&e, "release", "sandbox").await;
+
+ // Without a before_run checkpoint, even a folder write asks
+ let (tid, dir) = claimed_task(&e, "release", false).await;
+ let Err(d) = claude_asks(&e, &dir, "Write", write_in(&dir)).await else { panic!("no checkpoint: a write asks") };
+ assert!(reason(&d).contains("no checkpoint"), "{d}");
+ person(&e, "POST", &format!("/api/tasks/{tid}/cancel"), json!({})).await;
+
+ // With one, folder writes and edits run; every command and every outside write asks
+ let (_tid, dir) = claimed_task(&e, "release", true).await;
+ assert_eq!(claude_asks(&e, &dir, "Write", write_in(&dir)).await, Ok("allow".into()));
+ std::fs::write(dir.join("notes.md"), "hi").unwrap();
+ let edit = json!({"file_path": dir.join("notes.md").display().to_string(), "old_string": "hi", "new_string": "ho"});
+ assert_eq!(claude_asks(&e, &dir, "Edit", edit).await, Ok("allow".into()));
+ assert_eq!(claude_asks(&e, &dir, "Read", json!({"file_path": dir.join("notes.md").display().to_string()})).await, Ok("allow".into()));
+ for command in ["touch x", "ls", "echo hi"] {
+ let Err(d) = claude_asks(&e, &dir, "Bash", json!({"command": command})).await else { panic!("sandbox: {command} must ask") };
+ assert_eq!(reason(&d), "Sandbox: commands always ask");
+ }
+ let Err(d) = claude_asks(&e, &dir, "Write", json!({"file_path": "/tmp/fs-outside.txt", "content": "x"})).await else { panic!("outside write") };
+ assert!(reason(&d).starts_with("Sandbox"), "{d}");
+ // Kwant's own tools that change things ask; memory and task tools don't
+ let a = SelfToolsApprover { inner: Arc::new(approver(&e)), always_ask: false, browser: None };
+ assert_eq!(a.decide(request(&e, SELF_SERVER_NAME, "bot_update", json!({}))).await, ApprovalOutcome::Unanswered);
+ assert_eq!(a.decide(request(&e, SELF_SERVER_NAME, "memory_add", json!({"text": "x"}))).await, ApprovalOutcome::Allowed);
+ assert_eq!(a.decide(request(&e, SELF_SERVER_NAME, "task_update", json!({}))).await, ApprovalOutcome::Allowed);
+ // The API drivers' shell asks too
+ let waited = tokio::time::timeout(Duration::from_millis(300), kwnt::server::computer::approve_local_shell(&e.state, &e.bot.id, "touch x", &dir)).await;
+ assert!(waited.is_err(), "a sandboxed command waits for the person");
+ // Every call above is in the ledger
+ let calls = e.state.db.tool_calls_of(&_tid).await.unwrap();
+ assert!(calls.iter().filter(|c| c.tool_name == "Bash").count() >= 3, "{calls:?}");
+}
+
+#[tokio::test]
+async fn approvals_off_and_smart_allow_still_card_in_sandbox_but_always_allow_counts() {
+ let e = setup().await;
+ flight_school(&e, true).await;
+ set_tier(&e, "*", "sandbox").await;
+ let (_tid, _dir) = claimed_task(&e, "general", true).await;
+ let a = approver(&e);
+ for mode in ["off", "smart"] {
+ set_approvals(&e, mode).await;
+ let mut req = bash(&e, "ls");
+ req.smart = Some(SmartVerdict::Allow("only reads".into()));
+ assert_eq!(a.decide(req).await, ApprovalOutcome::Unanswered, "{mode}");
+ assert_eq!(a.decide(request(&e, "github", "create_issue", json!({}))).await, ApprovalOutcome::Unanswered, "{mode}");
+ }
+ // D9: the person's own "always allow" for that tool in that chat still counts
+ set_approvals(&e, "off").await;
+ e.state.broker.allow_for_session(&e.bot.id, &e.general, "Bash").await;
+ assert_eq!(a.decide(bash(&e, "ls")).await, ApprovalOutcome::Allowed);
+ // …but never for a payment
+ assert_eq!(a.decide(bash(&e, STRIPE_POST)).await, ApprovalOutcome::Unanswered);
+ // An always-ask turn still cards
+ let strict = mcp_runtime::BrokerApprover { always_ask: true, ..approver(&e) };
+ assert_eq!(strict.decide(request(&e, "github", "create_issue", json!({}))).await, ApprovalOutcome::Unanswered);
+}
+
+#[tokio::test]
+async fn observe_cards_an_in_folder_write_that_ask_mode_lets_through() {
+ let e = setup().await;
+ set_approvals(&e, "ask").await;
+ let (_tid, dir) = claimed_task(&e, "research", true).await;
+ // Today, in ask mode, a write in the folder runs without a card
+ assert_eq!(claude_asks(&e, &dir, "Write", write_in(&dir)).await, Ok("allow".into()));
+ flight_school(&e, true).await;
+ set_tier(&e, "research", "observe").await;
+ let Err(d) = claude_asks(&e, &dir, "Write", write_in(&dir)).await else { panic!("observe: a folder write asks") };
+ assert_eq!(reason(&d), "Observe: every change asks");
+ // Reading still doesn't
+ assert_eq!(claude_asks(&e, &dir, "Read", json!({"file_path": dir.join("notes.md").display().to_string()})).await, Ok("allow".into()));
+ let t = person(&e, "GET", &format!("/api/tasks/{_tid}"), json!(null)).await;
+ assert_eq!((t["task"]["task_class"].as_str(), t["task"]["owner_tier"].as_str()), (Some("research"), Some("observe")));
+}
+
+#[tokio::test]
+async fn act_is_todays_path_and_a_payment_still_cards_at_act() {
+ let e = setup().await;
+ set_approvals(&e, "off").await;
+ let (_tid, dir) = claimed_task(&e, "general", true).await;
+ let today = outcomes(&e, &dir).await;
+ flight_school(&e, true).await;
+ let no_row = outcomes(&e, &dir).await;
+ set_tier(&e, "general", "act").await;
+ let act = outcomes(&e, &dir).await;
+ assert_eq!(today, no_row, "no policy row is act");
+ assert_eq!(today, act, "act is today's path");
+ // The payment floor sits first in the gate: it cards at act too
+ let Err(d) = claude_asks(&e, &dir, "Bash", json!({"command": STRIPE_POST})).await else { panic!("a payment asks at act") };
+ assert!(d["payment_reason"].as_str().unwrap().contains("stripe.com"), "{d}");
+ assert!(d.get("tier_reason").is_none(), "{d}");
+}
+
+#[tokio::test]
+async fn revoke_mid_turn_gates_the_very_next_call() {
+ let e = setup().await;
+ set_approvals(&e, "off").await;
+ flight_school(&e, true).await;
+ let (_tid, dir) = claimed_task(&e, "general", true).await;
+ let (turn_id, token) = turn(&e, &dir).await;
+ assert_eq!(ask_in(&e, &token, "Bash", json!({"command": "touch a"})).await, Ok("allow".into()));
+ let r = person(&e, "POST", &format!("/api/capabilities/{}/revoke", e.bot.id), json!({"task_class": "*", "to_tier": "sandbox"})).await;
+ assert_eq!(r["unchanged"], false, "{r}");
+ // Same turn, next call
+ let Err(d) = ask_in(&e, &token, "Bash", json!({"command": "touch b"})).await else { panic!("revoked: the next call asks") };
+ assert_eq!(reason(&d), "Sandbox: commands always ask");
+ // Revoking again (or to a higher tier) changes nothing
+ let again = person(&e, "POST", &format!("/api/capabilities/{}/revoke", e.bot.id), json!({"task_class": "*", "to_tier": "sandbox"})).await;
+ assert_eq!(again["unchanged"], true);
+ end(&e, &turn_id, &token).await;
+ let caps = person(&e, "GET", &format!("/api/capabilities?kwant_id={}", e.bot.id), json!(null)).await;
+ assert_eq!(caps["default_tier"], "sandbox", "{caps}");
+ assert_eq!(caps["events"][0]["kind"], "revoked", "{caps}");
+}
+
+#[tokio::test]
+async fn only_the_person_changes_tiers_and_task_classes() {
+ let e = setup().await;
+ let (tid, dir) = claimed_task(&e, "general", true).await;
+ let (turn_id, token) = turn(&e, &dir).await;
+ let body = json!({"kwant_id": e.bot.id, "task_class": "*", "tier": "act"});
+ for (method, uri, body) in [
+ ("POST", "/api/capabilities".to_string(), body.clone()),
+ ("POST", format!("/api/capabilities/{}/revoke", e.bot.id), json!({"task_class": "*", "to_tier": "observe"})),
+ ("PATCH", format!("/api/tasks/{tid}"), json!({"task_class": "anything"})),
+ ] {
+ let (s, v) = call(&e.app, method, &uri, Some(&token), Some(body)).await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "{method} {uri}: {v}");
+ }
+ let (s, _) = call(&e.app, "GET", &format!("/api/capabilities?kwant_id={}", e.bot.id), Some(&token), None).await;
+ assert_eq!(s, StatusCode::OK, "reads stay open");
+ // tier_status reads; it can't write
+ let (err, text) = self_tool(&e, &token, "tier_status", json!({})).await;
+ assert!(!err, "{text}");
+ assert!(text.contains("\"act\""), "{text}");
+ // A bot's plan can't pick the class of a task it would run itself
+ let plan = |owner: Option<&str>| {
+ let mut t = json!({"title": "B", "acceptance": "done", "task_class": "anything"});
+ if let Some(o) = owner {
+ t["owner"] = json!(o);
+ }
+ json!({"title": "Plan", "goal": "g", "tasks": [t]})
+ };
+ let (err, text) = self_tool(&e, &token, "mission_plan", plan(None)).await;
+ assert!(err && text.contains("task_class"), "{text}");
+ let (err, text) = self_tool(&e, &token, "mission_plan", plan(Some(&e.bot.id))).await;
+ assert!(err && text.contains("task_class"), "{text}");
+ let other = e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap().into_iter().find(|k| k.id != e.bot.id).unwrap();
+ let (err, text) = self_tool(&e, &token, "mission_plan", plan(Some(&other.id))).await;
+ assert!(!err, "a lead sets a teammate's class: {text}");
+ end(&e, &turn_id, &token).await;
+ // The person can; a bad slug is refused
+ person(&e, "PATCH", &format!("/api/tasks/{tid}"), json!({"task_class": "release"})).await;
+ assert_eq!(e.state.db.task_class(&tid).await.unwrap(), "release");
+ // A redo keeps the class (and so the tier)
+ let fork = person(&e, "POST", &format!("/api/tasks/{tid}/fork"), json!({"reason": "redo"})).await;
+ let fork_id = fork["task"]["id"].as_str().or(fork["id"].as_str()).unwrap().to_string();
+ assert_eq!(e.state.db.task_class(&fork_id).await.unwrap(), "release", "{fork}");
+ let (s, _) = call(&e.app, "PATCH", &format!("/api/tasks/{tid}"), Some(e.state.api_token.reveal()), Some(json!({"task_class": "Not OK"}))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+ let (s, _) = call(&e.app, "POST", "/api/capabilities", Some(e.state.api_token.reveal()), Some(json!({"kwant_id": e.bot.id, "task_class": "*", "tier": "root"}))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+}
+
+#[tokio::test]
+async fn a_codex_bot_below_act_blocks_its_task_instead_of_running_it() {
+ let e = setup().await;
+ flight_school(&e, true).await;
+ let bot = json!({"name": "Cody", "title": "Codex bot", "persona_prompt": "p", "avatar_sprite": "s",
+ "driver_type": "cli", "preferred_model": "codex"});
+ let cody = id(&person(&e, "POST", "/api/kwants", bot).await);
+ // Hired while Flight School is on: starts at sandbox
+ let caps = person(&e, "GET", &format!("/api/capabilities?kwant_id={cody}"), json!(null)).await;
+ assert_eq!(caps["default_tier"], "sandbox", "{caps}");
+ let body = json!({"title": "Ship it", "goal": "g", "lead_kwant_id": cody, "budget_tokens": 900_000,
+ "channel_id": e.general, "tasks": [{"title": "A", "owner": cody}]});
+ let m = person(&e, "POST", "/api/missions", body).await;
+ let r = person(&e, "POST", &format!("/api/missions/{}/run", id(&m)), json!({"max_tasks": 1})).await;
+ assert_eq!(r["started"].as_array().map_or(0, Vec::len), 0, "{r}");
+ let detail = person(&e, "GET", &format!("/api/missions/{}", id(&m)), json!(null)).await;
+ let t = &detail["tasks"][0];
+ assert_eq!(t["state"], "blocked", "{t}");
+ assert_eq!(t["needs_you"][0]["kind"], "engine_cant_sandbox", "{t}");
+ // Granting act lets it run again (the person unblocks it)
+ person(&e, "POST", "/api/capabilities", json!({"kwant_id": cody, "task_class": "*", "tier": "act"})).await;
+ let caps = person(&e, "GET", &format!("/api/capabilities?kwant_id={cody}"), json!(null)).await;
+ assert_eq!(caps["default_tier"], "act", "{caps}");
+}