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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Make token budgets opt-in: 0 means no limit, and it is the default
Lin (kwant bot)8fc752628c4e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8842c75c..3e32866b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).- **kwant.si covers 0.2.0.** The home page has a "New in 0.2.0" strip, the features page has sectionsfor the Mission board, Flight School and connecting apps with new screenshots and three short clips(Sandbox, AutoFix, Connect), and there are new docs pages for the Mission board and Flight School.+- **No token limit by default.** New tasks and missions no longer get a hidden 50k (task) or 200k+ (mission) token budget, so ordinary work stops landing in Needs you as "Out of budget". A budget of+ 0 means no limit; you can still set one on a task or mission, or as a default in Settings+ (`mission_default_task_budget_tokens`, `mission_default_budget_tokens`). Existing tasks and missions+ still on the old automatic limit have it removed; limits you set yourself stay. A task already+ blocked for its budget stays in Needs you until you remove its limit and unblock it.## [Mac 0.2.0] - 2026-10-28diff --git a/docs/mission-control.md b/docs/mission-control.mdindex c00a97d3..e9ec53c4 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -16,7 +16,8 @@ with `?space=<id>` (default space when omitted), like the rest of the API.|---|---|---|---|| `mission_board` | bool | `false` | Shows the board, gives bots the mission tools, auto-creates tasks from hand-offs, routine runs, Loose Ends and work-ahead runs, and runs active missions. Off: routes still answer (read and person actions), bots get no task tools, nothing is auto-created, the runner is idle. || `mission_lease_minutes` | int 5–240 | `30` | How long a claim lives without activity. |-| `mission_default_budget_tokens` | int 1 000–5 000 000 | `200000` | A mission's budget when none is given. |+| `mission_default_budget_tokens` | int 0 or 1 000–5 000 000 | `0` | A new mission's budget when none is given. 0 = no limit. |+| `mission_default_task_budget_tokens` | int 0–5 000 000 | `0` | A new task's budget when none is given (capped at a limited mission's budget). 0 = no limit. |Changing settings is person-only (as today). Bots can't change these through `settings_update`.@@ -272,8 +273,11 @@ claimed or let go of during that turn (`task_update review` releases the claim band the turn still pays for itself). When the turn ends and the task is still `working`, thelease is released (`ready`, attempt +1).-Budget: a claim needs `spent + reserved + task budget ≤ mission budget`, where `reserved` is what-working tasks may still spend. After every turn the tokens are added. A task over its own budget is+Budget: `budget_tokens` 0 means no limit, on missions and tasks alike, and is what new ones get+unless a budget or a Settings default is given (§15). A mission with no limit never refuses a claim.+In a limited mission a claim needs `spent + reserved + task budget ≤ mission budget`, where `reserved`+is what working tasks with a limit may still spend; a task with no limit reserves nothing and needs+only one token left. After every turn the tokens are added. A task over its own budget isblocked (`budget`). A mission at or over its budget gets `over_budget: true`, and no new claims startuntil the person raises the budget. One turn already running can overshoot by what that turn uses,because kwant counts tokens when a model call returns.@@ -579,3 +583,27 @@ the turn ended, and the next tick put the task back in `working` with no turn rulowers 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).++## 15. Opt-in budgets++Token budgets are opt-in. `budget_tokens` 0 means no limit, for tasks and missions.++- New tasks (person, hand-off, routine, chat, work-ahead) and missions get 0 unless a budget is+ given or the person set a default (`mission_default_task_budget_tokens`,+ `mission_default_budget_tokens`, both 0 by default). A plan task gets the task default, capped at a+ limited mission's budget; a task's own budget must be 0 or at most its mission's.+- No limit is never enforced: no `budget` block, `over_budget` stays false, nothing reserved, and+ AutoFix has no recovery cap (`recovery_budget_tokens` is 0, meaning none). The prompt a bot gets for+ a task leaves out the "Budget: N tokens" line.+- `PATCH /api/tasks/:id` and `PATCH /api/missions/:id` take `budget_tokens` 0 to remove a limit, or a+ positive number (tasks 1–5 000 000, missions 1 000–5 000 000). Anything else is 400.+- **Unblocking a task blocked for its budget** (`state` `blocked`, `blocked_reason` `budget`):+ `PATCH /api/tasks/:id {"budget_tokens": 0}` (or a higher limit), then `POST /api/tasks/:id/unblock`.+ The task goes `blocked → backlog → ready` when its dependencies are verified and its mission is+ active. (Hand-off tasks are not restarted by the board; that is a separate fix.)+- Migration (once, when the stored table still has `CHECK (budget_tokens > 0)`): `tasks` and+ `missions` are rebuilt with `CHECK (budget_tokens >= 0)`, keeping every column, index and trigger,+ and in the same transaction rows still at the old silent defaults lose them:+ `UPDATE tasks SET budget_tokens = 0 WHERE budget_tokens = 50000` and+ `UPDATE missions SET budget_tokens = 0 WHERE budget_tokens = 200000`. Task states are not changed.+- The hand-off loop guard (`chain_token_budget`) is separate and unchanged.diff --git a/src/db/missions.rs b/src/db/missions.rsindex ad28f8f0..68ab84fa 100644--- a/src/db/missions.rs+++ b/src/db/missions.rs@@ -13,6 +13,13 @@ use serde_json::Value;use sqlx::FromRow;use uuid::Uuid;+/// The silent budgets every task and mission got before budgets became opt-in+/// ([`Database::migrate_opt_in_budgets`]).+pub const OLD_DEFAULT_TASK_BUDGET: i64 = 50_000;+pub const OLD_DEFAULT_MISSION_BUDGET: i64 = 200_000;+const OLD_BUDGET_CHECK: &str = "CHECK (budget_tokens > 0)";+const NEW_BUDGET_CHECK: &str = "CHECK (budget_tokens >= 0)";+pub const TASK_STATES: [&str; 9] = ["backlog", "ready", "working", "needs_you", "review", "verified", "blocked", "failed", "cancelled"];pub const MISSION_STATUSES: [&str; 4] = ["draft", "active", "done", "cancelled"];pub const SOURCE_KINDS: [&str; 7] = ["mission", "person", "delegation", "routine", "zombie", "work_ahead", "chat"];@@ -316,7 +323,7 @@ impl Database {direct_kwant_id TEXT,thread_id TEXT,workspace_path TEXT NOT NULL DEFAULT '',- budget_tokens INTEGER NOT NULL CHECK (budget_tokens > 0),+ budget_tokens INTEGER NOT NULL CHECK (budget_tokens >= 0),spent_tokens INTEGER NOT NULL DEFAULT 0,created_by TEXT NOT NULL,approved_at TIMESTAMP,@@ -336,7 +343,7 @@ impl Database {priority INTEGER NOT NULL DEFAULT 1 CHECK (priority BETWEEN 0 AND 3),owner_kwant_id TEXT,suggested_kwant_id TEXT,- budget_tokens INTEGER NOT NULL CHECK (budget_tokens > 0),+ budget_tokens INTEGER NOT NULL CHECK (budget_tokens >= 0),spent_tokens INTEGER NOT NULL DEFAULT 0,attempts INTEGER NOT NULL DEFAULT 0,max_attempts INTEGER NOT NULL DEFAULT 3,@@ -434,6 +441,33 @@ impl Database {Ok(())}+ /// Budgets became opt-in: `budget_tokens` 0 means no limit. Tables made before that only+ /// allow `> 0`, so they are rebuilt once with `>= 0`, keeping every column, index and trigger,+ /// and in the same transaction rows still at the old silent defaults ([`OLD_DEFAULT_TASK_BUDGET`]+ /// on tasks, [`OLD_DEFAULT_MISSION_BUDGET`] on missions) lose them. Budgets anyone set stay.+ /// Runs last, after every migration that adds a column or trigger to these tables.+ pub(super) async fn migrate_opt_in_budgets(&self) -> Result<(), DbError> {+ let mut conn = self.pool.acquire().await?;+ let mut old = Vec::new();+ for table in ["missions", "tasks"] {+ let sql: Option<(String,)> = sqlx::query_as("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?")+ .bind(table)+ .fetch_optional(&mut *conn)+ .await?;+ if let Some((sql,)) = sql.filter(|(sql,)| sql.contains(OLD_BUDGET_CHECK)) {+ old.push((table, sql));+ }+ }+ if old.is_empty() {+ return Ok(());+ }+ // Table rebuilds need foreign keys off, and SQLite ignores this pragma inside a transaction+ sqlx::query("PRAGMA foreign_keys = OFF").execute(&mut *conn).await?;+ let result = rebuild_budgets(&mut conn, &old).await;+ sqlx::query("PRAGMA foreign_keys = ON").execute(&mut *conn).await?;+ result+ }+// Missionspub async fn create_mission(&self, space: &SpaceId, m: &NewMission) -> Result<Mission, DbError> {@@ -530,7 +564,7 @@ impl Database {pub async fn mission_reserved(&self, mission_id: &str) -> Result<i64, DbError> {let (n,): (i64,) = sqlx::query_as("SELECT COALESCE(SUM(MAX(budget_tokens - spent_tokens, 0)), 0) FROM tasks \- WHERE mission_id = ? AND state IN ('working', 'needs_you')",+ WHERE mission_id = ? AND state IN ('working', 'needs_you') AND budget_tokens > 0",).bind(mission_id).fetch_one(&self.pool)@@ -755,16 +789,21 @@ impl Database {if m.status != "active" {return Ok(Err(ClaimRefused::MissionNotActive));}- let (reserved,): (i64,) = sqlx::query_as(- "SELECT COALESCE(SUM(MAX(budget_tokens - spent_tokens, 0)), 0) FROM tasks WHERE mission_id = ? AND state IN ('working', 'needs_you')",- )- .bind(mid)- .fetch_one(&mut *tx)- .await?;- let needed = (task.budget_tokens - task.spent_tokens).max(1);- let remaining = m.budget_tokens - m.spent_tokens - reserved;- if needed > remaining {- return Ok(Err(ClaimRefused::Budget { remaining: remaining.max(0), needed }));+ // A mission with no limit never refuses; tasks with no limit reserve nothing and need+ // only that the mission has tokens left+ if m.budget_tokens > 0 {+ let (reserved,): (i64,) = sqlx::query_as(+ "SELECT COALESCE(SUM(MAX(budget_tokens - spent_tokens, 0)), 0) FROM tasks \+ WHERE mission_id = ? AND state IN ('working', 'needs_you') AND budget_tokens > 0",+ )+ .bind(mid)+ .fetch_one(&mut *tx)+ .await?;+ let needed = if task.budget_tokens > 0 { (task.budget_tokens - task.spent_tokens).max(1) } else { 1 };+ let remaining = m.budget_tokens - m.spent_tokens - reserved;+ if needed > remaining {+ return Ok(Err(ClaimRefused::Budget { remaining: remaining.max(0), needed }));+ }}}// Expired claims of this task (or the bot's own) are let go before the new one@@ -1198,3 +1237,154 @@ pub(super) async fn insert_event(.await?;Ok(())}++/// [`Database::migrate_opt_in_budgets`]'s rebuild, in one transaction: SQLite's documented+/// create-copy-drop-rename, from the table's own stored SQL so columns added by later migrations+/// come along, then its indexes and triggers (dropped with the old table) are made again.+async fn rebuild_budgets(conn: &mut sqlx::SqliteConnection, old: &[(&str, String)]) -> Result<(), DbError> {+ let mut tx = sqlx::Connection::begin(&mut *conn).await?;+ // Rows that were already dangling don't stop the rebuild; only new ones would+ let before = fk_violations(&mut tx).await?;+ // Triggers on any table can name tasks or missions, and SQLite re-checks them all on a+ // rename, so they come off first and go back once both tables are rebuilt+ let triggers: Vec<(String, String)> =+ sqlx::query_as("SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND sql IS NOT NULL ORDER BY name").fetch_all(&mut *tx).await?;+ for (name, _) in &triggers {+ sqlx::query(&format!("DROP TRIGGER \"{name}\"")).execute(&mut *tx).await?;+ }+ for (table, sql) in old {+ let new_table = format!("{table}__budget_new");+ let head = format!("CREATE TABLE {table} ");+ let quoted = format!("CREATE TABLE \"{table}\" ");+ let body = sql+ .strip_prefix(&head)+ .or_else(|| sql.strip_prefix("ed))+ .ok_or_else(|| DbError::Migration(format!("{table}: unexpected table SQL")))?;+ let create = format!("CREATE TABLE {new_table} {}", body.replace(OLD_BUDGET_CHECK, NEW_BUDGET_CHECK));+ let indexes: Vec<(String,)> =+ sqlx::query_as("SELECT sql FROM sqlite_master WHERE tbl_name = ? AND type = 'index' AND sql IS NOT NULL ORDER BY name")+ .bind(table)+ .fetch_all(&mut *tx)+ .await?;+ sqlx::query(&create).execute(&mut *tx).await?;+ let cols: Vec<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info(?) ORDER BY cid").bind(table).fetch_all(&mut *tx).await?;+ let list = cols.iter().map(|(c,)| format!("\"{c}\"")).collect::<Vec<_>>().join(", ");+ // rowid too, so listings without an ORDER BY keep their order+ let copied = sqlx::query(&format!("INSERT INTO {new_table} (rowid, {list}) SELECT rowid, {list} FROM {table}"))+ .execute(&mut *tx)+ .await?+ .rows_affected();+ let (count,): (i64,) = sqlx::query_as(&format!("SELECT COUNT(*) FROM {table}")).fetch_one(&mut *tx).await?;+ if copied != count as u64 {+ return Err(DbError::Migration(format!("{table}: copied {copied} of {count} rows")));+ }+ sqlx::query(&format!("DROP TABLE {table}")).execute(&mut *tx).await?;+ sqlx::query(&format!("ALTER TABLE {new_table} RENAME TO {table}")).execute(&mut *tx).await?;+ for (stmt,) in &indexes {+ sqlx::query(stmt).execute(&mut *tx).await?;+ }+ }+ for (_, stmt) in &triggers {+ sqlx::query(stmt).execute(&mut *tx).await?;+ }+ sqlx::query("UPDATE tasks SET budget_tokens = 0 WHERE budget_tokens = ?").bind(OLD_DEFAULT_TASK_BUDGET).execute(&mut *tx).await?;+ sqlx::query("UPDATE missions SET budget_tokens = 0 WHERE budget_tokens = ?").bind(OLD_DEFAULT_MISSION_BUDGET).execute(&mut *tx).await?;+ if fk_violations(&mut tx).await? > before {+ return Err(DbError::Migration("foreign key check failed after the budget rebuild".into()));+ }+ tx.commit().await?;+ Ok(())+}++async fn fk_violations(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>) -> Result<usize, DbError> {+ let rows: Vec<(String, Option<i64>, String, i64)> = sqlx::query_as("PRAGMA foreign_key_check").fetch_all(&mut **tx).await?;+ Ok(rows.len())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn mission(budget: i64) -> NewMission {+ NewMission { title: "M".into(), status: "active".into(), lead_kwant_id: "lead".into(), budget_tokens: budget, created_by: "person".into(), ..Default::default() }+ }++ fn task(mission_id: Option<&str>, budget: i64, state: &str) -> NewTask {+ NewTask {+ mission_id: mission_id.map(Into::into),+ title: format!("T {budget}"),+ state: state.into(),+ priority: 1,+ budget_tokens: budget,+ max_attempts: 3,+ source_kind: "person".into(),+ created_by: "person".into(),+ ..Default::default()+ }+ }++ async fn schema_of(db: &Database, kind: &str) -> Vec<(String, String)> {+ sqlx::query_as("SELECT name, sql FROM sqlite_master WHERE tbl_name IN ('tasks', 'missions') AND type = ? AND sql IS NOT NULL ORDER BY name")+ .bind(kind)+ .fetch_all(&db.pool)+ .await+ .unwrap()+ }++ /// A database as a release before opt-in budgets leaves it: same tables, the old `> 0` check.+ async fn old_shape(db: &Database) {+ let mut conn = db.pool.acquire().await.unwrap();+ sqlx::query("PRAGMA writable_schema = ON").execute(&mut *conn).await.unwrap();+ sqlx::query("UPDATE sqlite_master SET sql = replace(sql, ?, ?) WHERE type = 'table' AND name IN ('tasks', 'missions')")+ .bind(NEW_BUDGET_CHECK)+ .bind(OLD_BUDGET_CHECK)+ .execute(&mut *conn)+ .await+ .unwrap();+ sqlx::query("PRAGMA writable_schema = OFF").execute(&mut *conn).await.unwrap();+ }++ #[tokio::test]+ async fn the_migration_takes_off_only_the_old_silent_defaults_and_keeps_the_tables_whole() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let space = SpaceId::default_space();+ let old_m = db.create_mission(&space, &mission(OLD_DEFAULT_MISSION_BUDGET)).await.unwrap();+ let set_m = db.create_mission(&space, &mission(300_000)).await.unwrap();+ let old_t = db.create_task(&space, &task(Some(&old_m.id), OLD_DEFAULT_TASK_BUDGET, "ready")).await.unwrap();+ let set_t = db.create_task(&space, &task(Some(&old_m.id), 60_000, "ready")).await.unwrap();+ let blocked = db.create_task(&space, &task(None, OLD_DEFAULT_TASK_BUDGET, "blocked")).await.unwrap();+ let (indexes, triggers) = (schema_of(&db, "index").await, schema_of(&db, "trigger").await);+ assert!(!triggers.is_empty());+ old_shape(&db).await;+ db.pool.close().await;++ let db = Database::init(tmp.path()).await.unwrap();+ for table in ["tasks", "missions"] {+ let (sql,): (String,) = sqlx::query_as("SELECT sql FROM sqlite_master WHERE name = ?").bind(table).fetch_one(&db.pool).await.unwrap();+ assert!(sql.contains(NEW_BUDGET_CHECK) && !sql.contains(OLD_BUDGET_CHECK), "{sql}");+ }+ assert_eq!(db.get_mission(&old_m.id).await.unwrap().unwrap().budget_tokens, 0);+ assert_eq!(db.get_mission(&set_m.id).await.unwrap().unwrap().budget_tokens, 300_000);+ assert_eq!(db.get_task(&old_t.id).await.unwrap().unwrap().budget_tokens, 0);+ assert_eq!(db.get_task(&set_t.id).await.unwrap().unwrap().budget_tokens, 60_000);+ // States aren't touched: a task blocked for its budget stays for the person to unblock+ let b = db.get_task(&blocked.id).await.unwrap().unwrap();+ assert_eq!((b.budget_tokens, b.state.as_str()), (0, "blocked"));+ assert_eq!(schema_of(&db, "index").await, indexes, "indexes survive the rebuild");+ assert_eq!(schema_of(&db, "trigger").await, triggers, "triggers survive the rebuild");+ // ...and still bite+ let raw = db.exec_raw_for_test(&format!("UPDATE tasks SET state = 'verified' WHERE id = '{}'", set_t.id)).await;+ assert!(raw.is_err());+ let fk: Vec<(String, Option<i64>, String, i64)> = sqlx::query_as("PRAGMA foreign_key_check").fetch_all(&db.pool).await.unwrap();+ assert!(fk.is_empty(), "{fk:?}");++ // Once only: a 50k budget the person sets after the migration stays+ db.edit_task(&set_t.id, None, None, None, None, Some(OLD_DEFAULT_TASK_BUDGET), "person").await.unwrap();+ db.pool.close().await;+ let db = Database::init(tmp.path()).await.unwrap();+ assert_eq!(db.get_task(&set_t.id).await.unwrap().unwrap().budget_tokens, OLD_DEFAULT_TASK_BUDGET);+ assert!(db.create_task(&space, &task(None, 0, "ready")).await.is_ok(), "0 is allowed now");+ assert!(db.create_task(&space, &task(None, -1, "ready")).await.is_err(), "negatives still aren't");+ }+}diff --git a/src/db/mod.rs b/src/db/mod.rsindex b450b194..c0634887 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -181,6 +181,8 @@ impl Database {}// After the spaces migration, which can rebuild `kwants` (and drop its triggers)db.migrate_flight_school().await?;+ // Last: it rebuilds `tasks` and `missions` from their stored SQL, columns and triggers included+ db.migrate_opt_in_budgets().await?;db.pool.close().await;let pool = SqlitePoolOptions::new()diff --git a/src/server/missions/autofix.rs b/src/server/missions/autofix.rsindex 124faf19..308aa3ef 100644--- a/src/server/missions/autofix.rs+++ b/src/server/missions/autofix.rs@@ -406,7 +406,8 @@ fn used(task: &Task) -> i64 {}}-/// The recovery budget: `recovery_budget_pct` of the task's budget.+/// The recovery budget: `recovery_budget_pct` of the task's budget. 0 for a task with no limit,+/// which means no recovery cap either (see [`limit`]).pub fn recovery_budget(task: &Task, pct: i64) -> i64 {task.budget_tokens.saturating_mul(pct) / 100}@@ -422,7 +423,7 @@ async fn limit(state: &AppState, task: &Task) -> Option<&'static str> {}let estimate = task.spent_tokens / task.attempts.max(1);let recovery = recovery_budget(task, recovery_pct(state).await);- if task.recovery_spent_tokens + estimate > recovery {+ if task.budget_tokens > super::NO_LIMIT && task.recovery_spent_tokens + estimate > recovery {return Some("over_recovery_budget");}Nonediff --git a/src/server/missions/listener.rs b/src/server/missions/listener.rsindex 03e5be0d..1cd82c97 100644--- a/src/server/missions/listener.rs+++ b/src/server/missions/listener.rs@@ -99,6 +99,7 @@ async fn start_held(place: (Option<String>, Option<String>, Option<String>),context_id: &str,) -> Option<Task> {+ let budget_tokens = super::default_task_budget(state).await;let new = |mission_id: Option<String>| NewTask {mission_id,title: title.chars().take(200).collect(),@@ -107,7 +108,7 @@ async fn start_held(priority: 1,owner_kwant_id: None,suggested_kwant_id: Some(owner.into()),- budget_tokens: super::DEFAULT_TASK_BUDGET,+ budget_tokens,max_attempts: super::DEFAULT_MAX_ATTEMPTS,source_kind: source_kind.into(),source_id: Some(source_id.into()),@@ -303,7 +304,7 @@ pub async fn on_work_ahead_posted(state: &AppState, lead: &crate::db::models::Kwpriority: 1,owner_kwant_id: Some(lead.id.clone()),suggested_kwant_id: Some(lead.id.clone()),- budget_tokens: super::DEFAULT_TASK_BUDGET,+ budget_tokens: super::default_task_budget(state).await,max_attempts: 1,source_kind: "work_ahead".into(),source_id: Some(run_id.into()),diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rsindex fe1739a2..ec9673da 100644--- a/src/server/missions/mod.rs+++ b/src/server/missions/mod.rs@@ -34,12 +34,17 @@ use serde_json::{json, Value};pub const SETTING: &str = "mission_board";pub const LEASE_SETTING: &str = "mission_lease_minutes";pub const BUDGET_SETTING: &str = "mission_default_budget_tokens";+pub const TASK_BUDGET_SETTING: &str = "mission_default_task_budget_tokens";pub const DEFAULT_LEASE_MINUTES: i64 = 30;pub const LEASE_RANGE: (i64, i64) = (5, 240);-pub const DEFAULT_BUDGET: i64 = 200_000;+/// `budget_tokens` 0 means no limit, for missions and tasks alike. New ones get none unless the+/// person sets a default in Settings or a budget on the mission or task.+pub const NO_LIMIT: i64 = 0;+pub const DEFAULT_BUDGET: i64 = NO_LIMIT;+/// A positive mission budget (or a default for new missions) lies in this range.pub const BUDGET_RANGE: (i64, i64) = (1_000, 5_000_000);/// A task's budget when none is given (capped at its mission's budget).-pub const DEFAULT_TASK_BUDGET: i64 = 50_000;+pub const DEFAULT_TASK_BUDGET: i64 = NO_LIMIT;pub const MAX_PLAN_TASKS: usize = 30;pub const DEFAULT_MAX_ATTEMPTS: i64 = 3;/// Longest stored check output.@@ -69,17 +74,53 @@ pub async fn lease_ms(state: &AppState) -> i64 {lease_minutes(state).await * 60_000}+/// A mission budget is 0 (no limit) or within [`BUDGET_RANGE`].+pub fn valid_mission_budget(n: i64) -> bool {+ n == NO_LIMIT || (BUDGET_RANGE.0..=BUDGET_RANGE.1).contains(&n)+}++/// A task budget is 0 (no limit) or 1 up to the top of [`BUDGET_RANGE`].+pub fn valid_task_budget(n: i64) -> bool {+ (0..=BUDGET_RANGE.1).contains(&n)+}++/// Whether `spent` tokens went past `budget`; never with no limit.+pub fn over(spent: i64, budget: i64) -> bool {+ budget > NO_LIMIT && spent > budget+}++async fn budget_setting(state: &AppState, key: &str, valid: fn(i64) -> bool, default: i64) -> i64 {+ state+ .db+ .get_setting(key)+ .await+ .ok()+ .flatten()+ .and_then(|v| v.trim().parse::<i64>().ok())+ .filter(|n| valid(*n))+ .unwrap_or(default)+}++/// A new mission's budget when none is given: 0 (no limit) unless the person set one.pub async fn default_budget(state: &AppState) -> i64 {- int_setting(state, BUDGET_SETTING, BUDGET_RANGE, DEFAULT_BUDGET).await+ budget_setting(state, BUDGET_SETTING, valid_mission_budget, DEFAULT_BUDGET).await+}++/// A new task's budget when none is given: 0 (no limit) unless the person set one.+pub async fn default_task_budget(state: &AppState) -> i64 {+ budget_setting(state, TASK_BUDGET_SETTING, valid_task_budget, DEFAULT_TASK_BUDGET).await}/// Why the mission settings in a `POST /api/settings` are refused, if they are.-pub fn settings_error(lease: Option<i64>, budget: Option<i64>) -> Option<String> {+pub fn settings_error(lease: Option<i64>, budget: Option<i64>, task_budget: Option<i64>) -> Option<String> {if lease.is_some_and(|m| !(LEASE_RANGE.0..=LEASE_RANGE.1).contains(&m)) {return Some(format!("mission_lease_minutes must be {}–{}", LEASE_RANGE.0, LEASE_RANGE.1));}- if budget.is_some_and(|n| !(BUDGET_RANGE.0..=BUDGET_RANGE.1).contains(&n)) {- return Some(format!("mission_default_budget_tokens must be {}–{}", BUDGET_RANGE.0, BUDGET_RANGE.1));+ if budget.is_some_and(|n| !valid_mission_budget(n)) {+ return Some(format!("mission_default_budget_tokens must be 0 (no limit) or {}–{}", BUDGET_RANGE.0, BUDGET_RANGE.1));+ }+ if task_budget.is_some_and(|n| !valid_task_budget(n)) {+ return Some(format!("mission_default_task_budget_tokens must be 0 (no limit) or 1–{}", BUDGET_RANGE.1));}None}@@ -419,7 +460,7 @@ pub async fn spend(state: &AppState, kwant_id: &str, context_id: &str, turn_id:autofix::spend_on_claim(state, &claim.task_id, Some(&claim.id), due).await;let _ = state.db.renew_claim(&claim.task_id, lease_ms(state).await).await;let Ok(Some(task)) = state.db.get_task(&claim.task_id).await else { return };- if task.spent_tokens > task.budget_tokens && matches!(task.state.as_str(), "working" | "needs_you") {+ if over(task.spent_tokens, task.budget_tokens) && matches!(task.state.as_str(), "working" | "needs_you") {let change = TaskChange {kind: "budget".into(),reason: Some("budget".into()),@@ -577,7 +618,7 @@ pub async fn mission_json(state: &AppState, m: &Mission) -> Value {obj.remove("workspace_path");obj.insert("lead_name".into(), json!(name_of(state, Some(&m.lead_kwant_id)).await));obj.insert("reserved_tokens".into(), json!(reserved));- obj.insert("over_budget".into(), json!(m.spent_tokens >= m.budget_tokens));+ obj.insert("over_budget".into(), json!(m.budget_tokens > NO_LIMIT && m.spent_tokens >= m.budget_tokens));obj.insert("counts".into(), Value::Object(counts));}v@@ -780,12 +821,18 @@ pub async fn create_plan(return Err(format!("a mission has at most {MAX_PLAN_TASKS} tasks"));}let budget = match budget {- Some(b) if !(BUDGET_RANGE.0..=BUDGET_RANGE.1).contains(&b) => {- return Err(format!("budget_tokens must be {}–{}", BUDGET_RANGE.0, BUDGET_RANGE.1))+ Some(b) if !valid_mission_budget(b) => {+ return Err(format!("budget_tokens must be 0 (no limit) or {}–{}", BUDGET_RANGE.0, BUDGET_RANGE.1))}Some(b) => b,None => default_budget(state).await,};+ // A task's own limit fits inside a limited mission's+ let task_max = if budget > NO_LIMIT { budget } else { BUDGET_RANGE.1 };+ let task_default = match default_task_budget(state).await {+ d if budget > NO_LIMIT && d > budget => budget,+ d => d,+ };// Everything is checked before anything is writtenlet mut keys = std::collections::HashMap::new();let mut owners = Vec::new();@@ -801,8 +848,8 @@ pub async fn create_plan(if t.priority.is_some_and(|p| !(0..=3).contains(&p)) {return Err(format!("task {key}: priority must be 0–3"));}- if t.budget_tokens.is_some_and(|b| b < 1 || b > budget) {- return Err(format!("task {key}: budget_tokens must be 1–{budget}"));+ if t.budget_tokens.is_some_and(|b| !(0..=task_max).contains(&b)) {+ return Err(format!("task {key}: budget_tokens must be 0 (no limit) or 1–{task_max}"));}let owner = match &t.owner {Some(o) => Some(bot_in_space(state, space, o).await.ok_or_else(|| format!("task {key}: no bot {o} in this space"))?.id),@@ -872,7 +919,7 @@ pub async fn create_plan(priority: t.priority.unwrap_or(1),owner_kwant_id: None,suggested_kwant_id: owners[i].clone(),- budget_tokens: t.budget_tokens.unwrap_or(DEFAULT_TASK_BUDGET.min(budget)),+ budget_tokens: t.budget_tokens.unwrap_or(task_default),max_attempts: DEFAULT_MAX_ATTEMPTS,source_kind: "mission".into(),source_id: Some(mission.id.clone()),@@ -1137,8 +1184,15 @@ mod tests {#[test]fn settings_ranges() {- assert!(settings_error(Some(4), None).is_some());- assert!(settings_error(Some(30), Some(200_000)).is_none());- assert!(settings_error(None, Some(999)).is_some());+ assert!(settings_error(Some(4), None, None).is_some());+ assert!(settings_error(Some(30), Some(200_000), None).is_none());+ assert!(settings_error(None, Some(999), None).is_some());+ // 0 is "no limit" for both defaults; negatives and too-large values are refused+ assert!(settings_error(None, Some(0), Some(0)).is_none());+ assert!(settings_error(None, None, Some(50_000)).is_none());+ assert!(settings_error(None, Some(-1), None).is_some());+ assert!(settings_error(None, None, Some(-1)).is_some());+ assert!(settings_error(None, None, Some(5_000_001)).is_some());+ assert!(settings_error(None, Some(5_000_001), None).is_some());}}diff --git a/src/server/missions/routes.rs b/src/server/missions/routes.rsindex a2695957..790d2307 100644--- a/src/server/missions/routes.rs+++ b/src/server/missions/routes.rs@@ -190,8 +190,8 @@ pub async fn patch_mission(State(state): State<AppState>, RawQuery(q): RawQuery,return bad("title must be 1–200 characters");}let (lo, hi) = super::BUDGET_RANGE;- if p.budget_tokens.is_some_and(|b| !(lo..=hi).contains(&b)) {- return bad(format!("budget_tokens must be {lo}–{hi}"));+ if p.budget_tokens.is_some_and(|b| !super::valid_mission_budget(b)) {+ return bad(format!("budget_tokens must be 0 (no limit) or {lo}–{hi}"));}if let Err(e) = state.db.edit_mission(&id, title, p.goal.as_deref().map(str::trim), p.budget_tokens).await {return internal(e);@@ -478,9 +478,12 @@ pub async fn create_task(State(state): State<AppState>, Scope(space): Scope, Jso},None => None,};- let budget = p.budget_tokens.unwrap_or(super::DEFAULT_TASK_BUDGET);- if !(1..=super::BUDGET_RANGE.1).contains(&budget) {- return bad(format!("budget_tokens must be 1–{}", super::BUDGET_RANGE.1));+ let budget = match p.budget_tokens {+ Some(b) => b,+ None => super::default_task_budget(&state).await,+ };+ if !super::valid_task_budget(budget) {+ return bad(format!("budget_tokens must be 0 (no limit) or 1–{}", super::BUDGET_RANGE.1));}let mut approvals = Vec::new();for c in &p.checks {@@ -614,8 +617,8 @@ pub async fn patch_task(State(state): State<AppState>, RawQuery(q): RawQuery, Paif p.priority.is_some_and(|x| !(0..=3).contains(&x)) {return bad("priority must be 0–3");}- 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.budget_tokens.is_some_and(|b| !super::valid_task_budget(b)) {+ return bad(format!("budget_tokens must be 0 (no limit) or 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 -");diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rsindex 4af36901..57c7ac02 100644--- a/src/server/missions/runner.rs+++ b/src/server/missions/runner.rs@@ -150,7 +150,7 @@ async fn prompt(state: &AppState, m: &Mission, t: &Task) -> String {Work on it now. Attach what you produced with task_attach_evidence, then call task_update with \task_id {id} and status \"review\": kwant runs the checks and only they (or a teammate's review, \or the person) can verify it. If you can't finish, call task_update with status \"blocked\" and a \- reason, or \"ready\" to let it go. Never say it is verified yourself. Budget: {budget} tokens.",+ reason, or \"ready\" to let it go. Never say it is verified yourself.{budget}",id = t.id,mt = m.title,goal = m.goal,@@ -158,7 +158,7 @@ async fn prompt(state: &AppState, m: &Mission, t: &Task) -> String {acc = if t.acceptance.is_empty() { "(none given)" } else { &t.acceptance },checks = if list.is_empty() { "- none: a teammate or the person reviews it".into() } else { list.join("\n") },deps = if deps.is_empty() { String::new() } else { format!("It builds on tasks {} (verified).\n", deps.iter().map(|d| d.0.as_str()).collect::<Vec<_>>().join(", ")) },- budget = t.budget_tokens - t.spent_tokens,+ budget = if t.budget_tokens > super::NO_LIMIT { format!(" Budget: {} tokens.", t.budget_tokens - t.spent_tokens) } else { String::new() },)}diff --git a/src/server/missions/tools.rs b/src/server/missions/tools.rsindex f23a684c..d1c470b7 100644--- a/src/server/missions/tools.rs+++ b/src/server/missions/tools.rs@@ -49,7 +49,7 @@ pub fn tools() -> Vec<Value> {"properties": {"title": {"type": "string"},"goal": {"type": "string", "description": "The outcome, in a sentence or two."},- "budget_tokens": {"type": "integer", "description": "Token budget for the whole mission (optional)."},+ "budget_tokens": {"type": "integer", "description": "Token budget for the whole mission (optional; leave out or 0 for no limit)."},"tasks": {"type": "array","maxItems": super::MAX_PLAN_TASKS,diff --git a/src/server/routes.rs b/src/server/routes.rsindex 0fbe609b..c4af1499 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -3273,8 +3273,10 @@ pub struct SettingsResponse {pub mission_board: bool,/// Minutes a task claim lives without activity (5–240).pub mission_lease_minutes: i64,- /// A new mission's token budget when none is given.+ /// A new mission's token budget when none is given; 0 = no limit (the default).pub mission_default_budget_tokens: i64,+ /// A new task's token budget when none is given; 0 = no limit (the default).+ pub mission_default_task_budget_tokens: i64,/// Time Machine: checkpoints before and after each task run (see `super::missions::checkpoints`).pub checkpoints: bool,/// Largest checkpoint, in MB (10–2000).@@ -3324,6 +3326,7 @@ pub struct SaveSettingsPayload {pub mission_board: Option<bool>,pub mission_lease_minutes: Option<i64>,pub mission_default_budget_tokens: Option<i64>,+ pub mission_default_task_budget_tokens: Option<i64>,pub checkpoints: Option<bool>,pub checkpoint_max_mb: Option<i64>,pub checkpoint_keep: Option<i64>,@@ -3375,6 +3378,7 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settingsmission_board: super::missions::enabled(&state).await,mission_lease_minutes: super::missions::lease_minutes(&state).await,mission_default_budget_tokens: super::missions::default_budget(&state).await,+ mission_default_task_budget_tokens: super::missions::default_task_budget(&state).await,checkpoints: super::missions::checkpoints::enabled(&state).await,checkpoint_max_mb: super::missions::checkpoints::max_mb(&state).await,checkpoint_keep: super::missions::checkpoints::keep(&state).await,@@ -3428,7 +3432,7 @@ pub async fn save_settings(if payload.work_ahead_daily_cap.is_some_and(|n| !(1..=super::decide::MAX_WORK_AHEAD_CAP).contains(&n)) {return bad(format!("work_ahead_daily_cap must be 1–{}", super::decide::MAX_WORK_AHEAD_CAP));}- if let Some(e) = super::missions::settings_error(payload.mission_lease_minutes, payload.mission_default_budget_tokens) {+ if let Some(e) = super::missions::settings_error(payload.mission_lease_minutes, payload.mission_default_budget_tokens, payload.mission_default_task_budget_tokens) {return bad(e);}if let Some(e) = super::missions::checkpoints::settings_error(payload.checkpoint_max_mb, payload.checkpoint_keep) {@@ -3538,6 +3542,9 @@ pub async fn save_settings(if let Some(n) = payload.mission_default_budget_tokens {let _ = state.db.set_setting(super::missions::BUDGET_SETTING, &n.to_string()).await;}+ if let Some(n) = payload.mission_default_task_budget_tokens {+ let _ = state.db.set_setting(super::missions::TASK_BUDGET_SETTING, &n.to_string()).await;+ }if let Some(on) = payload.checkpoints {let _ = state.db.set_setting(super::missions::checkpoints::SETTING, if on { "true" } else { "false" }).await;}diff --git a/tests/opt_in_budget_test.rs b/tests/opt_in_budget_test.rsnew file mode 100644index 00000000..3d2d0d18--- /dev/null+++ b/tests/opt_in_budget_test.rs@@ -0,0 +1,259 @@+//! Token budgets are opt-in: `budget_tokens` 0 means no limit, which new tasks and missions get+//! unless the person sets one (on the item, or as a default in Settings). No limit is never+//! enforced; a positive one still blocks. Contract: docs/mission-control.md §15.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{models::Kwant, spaces::SpaceId, Database},+ router::LayaRouter,+ server::{+ continuity::{SelfScope, TurnOrigin},+ create_router, mcp_runtime, missions, AppState,+ },+ tools::ToolRunner,+};+use serde_json::{json, Value};+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++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 kwants = state.db.list_kwants(&space).await.unwrap();+ 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: kwants[0].clone(), general, state, _tmp: tmp };+ let (status, v) = call(&e.app, "POST", "/api/settings", None, Some(json!({"mission_board": true}))).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ 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: Option<Value>) -> Value {+ let (status, v) = call(&e.app, method, uri, None, body).await;+ assert!(status.is_success(), "{method} {uri}: {status} {v}");+ v+}++fn rpc(method: &str, params: Value) -> Value {+ json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})+}++async fn tool(e: &Env, token: &str, name: &str, args: Value) -> (Value, bool, String) {+ let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc("tools/call", json!({"name": name, "arguments": args})))).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ let text = v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string();+ let parsed = serde_json::from_str(&text).unwrap_or(Value::Null);+ (parsed, v["result"]["isError"].as_bool().unwrap_or(false), text)+}++++/// A turn of `bot` in #general with its own tools; returns the turn token.+async fn turn(e: &Env, bot: &Kwant, turn_id: &str) -> String {+ let origin = TurnOrigin { channel_id: Some(e.general.clone()), ..Default::default() };+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ origin: Some(origin),+ turn_id: Some(turn_id.into()),+ ..Default::default()+ };+ mcp_runtime::prepare_turn_with_self(&e.state, bot, Some(turn_id.into()), None, Some(scope)).await.unwrap().1+}++async fn task(e: &Env, id: &str) -> Value {+ person(e, "GET", &format!("/api/tasks/{id}"), None).await+}++fn id(v: &Value) -> String {+ v["id"].as_str().unwrap().to_string()+}++/// A mission the person creates (active at once), led by `e.bot`; returns `(mission, tasks)`.+async fn mission_with(e: &Env, budget: Option<i64>, tasks: Value) -> (Value, Vec<Value>) {+ let mut body = json!({"title": "Ship it", "goal": "a release", "lead_kwant_id": e.bot.id, "channel_id": e.general, "tasks": tasks});+ if let Some(b) = budget {+ body["budget_tokens"] = json!(b);+ }+ let m = person(e, "POST", "/api/missions", Some(body)).await;+ let detail = person(e, "GET", &format!("/api/missions/{}", id(&m)), None).await;+ let mut tasks = detail["tasks"].as_array().unwrap().clone();+ tasks.sort_by_key(|t| t["title"].as_str().unwrap().to_string());+ (detail["mission"].clone(), tasks)+}++async fn claim(e: &Env, tid: &str) -> String {+ let turn_id = format!("t-{}", uuid::Uuid::new_v4());+ let token = turn(e, &e.bot, &turn_id).await;+ let (v, err, text) = tool(e, &token, "task_claim", json!({"task_id": tid})).await;+ assert!(!err, "claim failed: {text} {v}");+ turn_id+}++async fn spend(e: &Env, turn_id: &str, tokens: u64) {+ let started_ms = chrono::Utc::now().timestamp_millis() - 1000;+ missions::spend(&e.state, &e.bot.id, &e.general, Some(turn_id), started_ms, tokens, 0).await;+}++#[tokio::test]+async fn new_tasks_and_missions_have_no_limit_unless_one_is_given() {+ let e = setup().await;+ let s = person(&e, "GET", "/api/settings", None).await;+ assert_eq!((s["mission_default_budget_tokens"].as_i64(), s["mission_default_task_budget_tokens"].as_i64()), (Some(0), Some(0)), "{s}");++ let t = person(&e, "POST", "/api/tasks", Some(json!({"title": "Plain"}))).await;+ assert_eq!(t["budget_tokens"], 0, "{t}");+ let t = person(&e, "POST", "/api/tasks", Some(json!({"title": "Capped", "budget_tokens": 5_000}))).await;+ assert_eq!(t["budget_tokens"], 5_000, "{t}");++ let (m, tasks) = mission_with(&e, None, json!([{"title": "A"}, {"title": "B", "budget_tokens": 7_000}])).await;+ assert_eq!((m["budget_tokens"].as_i64(), m["over_budget"].as_bool()), (Some(0), Some(false)), "{m}");+ assert_eq!((tasks[0]["budget_tokens"].as_i64(), tasks[1]["budget_tokens"].as_i64()), (Some(0), Some(7_000)));+ // Inside a limited mission a plan task still gets no cap of its own unless given+ let (m, tasks) = mission_with(&e, Some(10_000), json!([{"title": "A"}])).await;+ assert_eq!((m["budget_tokens"].as_i64(), tasks[0]["budget_tokens"].as_i64()), (Some(10_000), Some(0)));+ let (status, v) = call(&e.app, "POST", "/api/missions", None, Some(json!({"title": "Too big", "goal": "g", "lead_kwant_id": e.bot.id,+ "channel_id": e.general, "budget_tokens": 10_000, "tasks": [{"title": "A", "budget_tokens": 20_000}]}))).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{v}");++ // Defaults the person sets apply to new items (a task default never exceeds its mission)+ person(&e, "POST", "/api/settings", Some(json!({"mission_default_budget_tokens": 300_000, "mission_default_task_budget_tokens": 50_000}))).await;+ assert_eq!(person(&e, "POST", "/api/tasks", Some(json!({"title": "D"}))).await["budget_tokens"], 50_000);+ let (m, tasks) = mission_with(&e, None, json!([{"title": "A"}])).await;+ assert_eq!((m["budget_tokens"].as_i64(), tasks[0]["budget_tokens"].as_i64()), (Some(300_000), Some(50_000)));+ let (_, tasks) = mission_with(&e, Some(20_000), json!([{"title": "A"}])).await;+ assert_eq!(tasks[0]["budget_tokens"], 20_000);+}++#[tokio::test]+async fn settings_take_zero_as_no_limit_and_refuse_bad_values() {+ let e = setup().await;+ for bad in [+ json!({"mission_default_budget_tokens": -1}),+ json!({"mission_default_budget_tokens": 999}),+ json!({"mission_default_budget_tokens": 5_000_001}),+ json!({"mission_default_task_budget_tokens": -1}),+ json!({"mission_default_task_budget_tokens": 5_000_001}),+ ] {+ let (status, v) = call(&e.app, "POST", "/api/settings", None, Some(bad.clone())).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{bad} → {v}");+ }+ person(&e, "POST", "/api/settings", Some(json!({"mission_default_budget_tokens": 200_000, "mission_default_task_budget_tokens": 1}))).await;+ let s = person(&e, "GET", "/api/settings", None).await;+ assert_eq!((s["mission_default_budget_tokens"].as_i64(), s["mission_default_task_budget_tokens"].as_i64()), (Some(200_000), Some(1)));+ person(&e, "POST", "/api/settings", Some(json!({"mission_default_budget_tokens": 0, "mission_default_task_budget_tokens": 0}))).await;+ let s = person(&e, "GET", "/api/settings", None).await;+ assert_eq!((s["mission_default_budget_tokens"].as_i64(), s["mission_default_task_budget_tokens"].as_i64()), (Some(0), Some(0)));+}++#[tokio::test]+async fn no_limit_never_blocks_a_positive_limit_still_does_and_removing_it_unblocks() {+ let e = setup().await;+ let free = id(&person(&e, "POST", "/api/tasks", Some(json!({"title": "Free", "owner_kwant_id": e.bot.id}))).await);+ let turn_id = claim(&e, &free).await;+ spend(&e, &turn_id, 5_000_000).await;+ let t = task(&e, &free).await["task"].clone();+ assert_eq!((t["state"].as_str(), t["spent_tokens"].as_i64()), (Some("working"), Some(5_000_000)), "{t}");+ person(&e, "POST", &format!("/api/tasks/{free}/cancel"), None).await;++ let capped = id(&person(&e, "POST", "/api/tasks", Some(json!({"title": "Capped", "owner_kwant_id": e.bot.id, "budget_tokens": 100}))).await);+ let turn_id = claim(&e, &capped).await;+ spend(&e, &turn_id, 150).await;+ let t = task(&e, &capped).await["task"].clone();+ assert_eq!((t["state"].as_str(), t["blocked_reason"].as_str()), (Some("blocked"), Some("budget")), "{t}");++ // The unblock the UI's "Remove limit and continue" makes: PATCH the limit off, then unblock+ let (status, v) = call(&e.app, "PATCH", &format!("/api/tasks/{capped}"), None, Some(json!({"budget_tokens": -1}))).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{v}");+ let t = person(&e, "PATCH", &format!("/api/tasks/{capped}"), Some(json!({"budget_tokens": 0}))).await;+ assert_eq!((t["budget_tokens"].as_i64(), t["state"].as_str()), (Some(0), Some("blocked")), "{t}");+ let t = person(&e, "POST", &format!("/api/tasks/{capped}/unblock"), None).await;+ assert_eq!(t["state"], "ready", "{t}");+ let turn_id = claim(&e, &capped).await;+ spend(&e, &turn_id, 1_000_000).await;+ assert_eq!(task(&e, &capped).await["task"]["state"], "working");+}++/// A claim kwant takes (as the mission runner does), so one bot can hold several.+async fn system_claim(e: &Env, t: &Value) -> Result<Result<kwnt::db::missions::Task, kwnt::db::missions::ClaimRefused>, kwnt::db::DbError> {+ e.state.db.claim_task(t["id"].as_str().unwrap(), &e.bot.id, None, None, 60_000, true, "kwant").await+}++#[tokio::test]+async fn reserve_math_counts_only_limited_tasks_and_a_mission_with_no_limit_never_refuses() {+ let e = setup().await;+ let db = &e.state.db;+ // A limited mission: unlimited tasks reserve nothing, limited ones reserve what they have left+ let (m, tasks) = mission_with(&e, Some(10_000), json!([+ {"title": "A"}, {"title": "B", "budget_tokens": 6_000}, {"title": "C", "budget_tokens": 6_000}, {"title": "D"}+ ])).await;+ assert!(system_claim(&e, &tasks[0]).await.unwrap().is_ok());+ assert!(system_claim(&e, &tasks[1]).await.unwrap().is_ok());+ let detail = person(&e, "GET", &format!("/api/missions/{}", id(&m)), None).await;+ assert_eq!(detail["mission"]["reserved_tokens"], 6_000, "{detail}");+ let third = system_claim(&e, &tasks[2]).await.unwrap();+ assert!(matches!(third, Err(kwnt::db::missions::ClaimRefused::Budget { remaining: 4_000, needed: 6_000 })), "{third:?}");+ // Once the mission's tokens are gone, even an unlimited task can't start+ db.exec_raw_for_test(&format!("UPDATE missions SET spent_tokens = 4000 WHERE id = '{}'", id(&m))).await.unwrap();+ let fourth = system_claim(&e, &tasks[3]).await.unwrap();+ assert!(matches!(fourth, Err(kwnt::db::missions::ClaimRefused::Budget { remaining: 0, needed: 1 })), "{fourth:?}");+ // Spent plus reserved fills it, but only spending at or past the limit is "over budget"+ let detail = person(&e, "GET", &format!("/api/missions/{}", id(&m)), None).await;+ assert_eq!(detail["mission"]["over_budget"], false);+ db.exec_raw_for_test(&format!("UPDATE missions SET spent_tokens = 10000 WHERE id = '{}'", id(&m))).await.unwrap();+ let detail = person(&e, "GET", &format!("/api/missions/{}", id(&m)), None).await;+ assert_eq!(detail["mission"]["over_budget"], true);++ // A mission with no limit: everything starts, nothing is "over budget"+ let (m, tasks) = mission_with(&e, None, json!([+ {"title": "A", "budget_tokens": 3_000_000}, {"title": "B", "budget_tokens": 3_000_000}, {"title": "C"}+ ])).await;+ for t in &tasks {+ assert!(system_claim(&e, t).await.unwrap().is_ok(), "{t}");+ }+ db.exec_raw_for_test(&format!("UPDATE missions SET spent_tokens = 9000000 WHERE id = '{}'", id(&m))).await.unwrap();+ let detail = person(&e, "GET", &format!("/api/missions/{}", id(&m)), None).await;+ assert_eq!((detail["mission"]["over_budget"].as_bool(), detail["mission"]["reserved_tokens"].as_i64()), (Some(false), Some(6_000_000)), "{detail}");++ // PATCH takes 0 off a mission's limit and refuses what isn't 0 or in range+ let (status, _) = call(&e.app, "PATCH", &format!("/api/missions/{}", id(&m)), None, Some(json!({"budget_tokens": 500}))).await;+ assert_eq!(status, StatusCode::BAD_REQUEST);+ let m2 = person(&e, "PATCH", &format!("/api/missions/{}", id(&m)), Some(json!({"budget_tokens": 50_000}))).await;+ assert_eq!(m2["budget_tokens"].as_i64(), Some(50_000), "{m2}");+ let m2 = person(&e, "PATCH", &format!("/api/missions/{}", id(&m)), Some(json!({"budget_tokens": 0}))).await;+ assert_eq!(m2["budget_tokens"].as_i64(), Some(0), "{m2}");+}