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.

AutoFix: acceptance tests, docs §13, Insights per space, redacted check output

Lin (kwant bot)189fa168d9aa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d304f2ec..1dc40f8a 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
+- **Mission Control: AutoFix (backend).** Every failed task now records why it failed, with secrets
+ masked. Turn on the new `autofix` setting (off by default, or "suggest" to approve each retry) and
+ kwant retries what is safe to retry: after a temporary error it waits 1, 5, then 25 minutes; after a
+ failed check it runs again with the check's output. Retries stay within the task's attempts and a
+ recovery budget (25% of the task's budget by default). Sign-in problems, budget overruns and denied
+ actions are never retried; they ask you instead. Bots can propose changes to a check, the acceptance
+ or a routine, and nothing changes until you approve. The board UI follows separately.
- **Mission Control: checkpoints and restore (backend).** kwant snapshots a task's folder before and
after each run, and on demand. You can preview and restore a checkpoint: only the files that task's
runs changed are written back, after a safety checkpoint you can restore in turn. What the bot did
diff --git a/docs/mission-control.md b/docs/mission-control.md
index d3ff3745..2a704226 100644
--- a/docs/mission-control.md
+++ b/docs/mission-control.md
@@ -445,3 +445,47 @@ it is listed as "not undone".
- Never writes through a symlink or outside the folder.
- `POST /api/tasks/:id/fork` accepts `from_checkpoint`: the original's task-owned paths are restored to that checkpoint first (after a `before_restore`), then the fork is made. The response adds `restore`.
- `task_json` gains `checkpoint_count`, `last_checkpoint_at` and `held_at` (null unless a restore holds the task).
+
+## 13. AutoFix (Phase B3)
+
+Design and decisions: `/home/maus/shared/ship-software-safely/mission-control/phase-b/contract.md` §4–§5
+and `decisions.md` (D5, D7, D12). Every failure of a task is recorded with a class. With the setting
+`autofix` on, AutoFix may retry it a bounded number of times. A permanent change (a check, the
+acceptance, a routine) is only ever proposed; it applies when the person approves it.
+
+### Settings
+
+- `autofix`: `off` (default), `suggest` or `on`. `off` records failures only (Phase A behaviour: a failed check sends the task back to `ready`). `suggest` plans one attempt and waits for the person (`autofix_suggested` Needs-you item). `on` runs the attempt.
+- `recovery_budget_pct` (0–100, default 25): the share of the task's budget that AutoFix retries may spend.
+
+### Failures
+
+- `task_failures` (append-only): `id`, `task_id`, `attempt`, `source` (`check`, `turn`, `lease`, `budget`, `routine`, `handoff`), `class`, `summary`, `excerpt`, `checkpoint_id` (the last good `after_run`), `created_at`, and server-only `diagnostics_path`.
+- `classify(source, status, text)` is deterministic. A check that failed is `check_failed`, or `bad_spec` when its command can't run (exit 127, "command not found"). A check that errored is `transient` for a timeout or 429/5xx, else `bad_spec`. A lease that ran out or a turn that ended without a review is `stalled`; over budget is `budget`; a denied action is `denied`; a task waiting on the person is `needs_input`. Other errors are `auth` (not logged in, 401, expired token, credit too low), then `transient` (rate limit, overloaded, timeouts, connection errors, 429/500/502/503/504/529 as whole numbers), else `unknown`.
+- The text is redacted (credentials in URLs, `sk-`/`xai-`/`ghp_`… prefixes, long digit-bearing tokens) before it is stored. The excerpt is at most 2,000 characters. The full redacted output goes to `<data_dir>/autofix/<task_id>/<uuid>.log` (folder 0700, file 0600, 256 KB). No route returns that path.
+
+### Attempts
+
+- `autofix_attempts`: `id`, `task_id`, `failure_id`, `strategy`, `status` (`suggested`, `scheduled`, `running`, `succeeded`, `failed`, `skipped`), `not_before`, `reason`, `retry_task_id`, `tokens_spent`, `created_at`, `finished_at`, and server-only `idempotency_key` (unique: sha256 of task, failure and strategy, so a failure is never planned twice). At most one `scheduled`/`running` attempt per task (`autofix_one_live`), and a trigger refuses one past the task's `max_attempts`.
+- Strategies: `transient` → `wait_and_retry` after 1, 5, then 25 minutes; `stalled` → `retry_from_checkpoint` (the folder is as the run left it) or `retry_same`; `check_failed` → `retry_with_diagnostics`; `bad_spec` → `propose_change` (a `check_spec` proposal making the check optional; the attempt stays `suggested` and never runs); `unknown` → `retry_same`, once per task. `auth`, `budget` and `denied` are never retried: a `skipped` attempt with what to do and a `fix_needed` Needs-you item. `needs_input` and hand-off tasks get no attempt.
+- Limits, checked when planning and again when starting: a `blocked` task is never moved (`not_retryable`); no attempts left (`no_attempts_left`); `recovery_spent_tokens` plus the average spend per attempt over the recovery budget (`over_recovery_budget`). A limit makes the attempt `skipped` with that reason.
+- While attempts are left and AutoFix isn't off, a failure parks the task in `failed` instead of `ready` (no "failed" chat line). The retry moves it `failed → ready` as `Actor::AutoFix`, the only move that actor may make, with a task event of kind `autofix`. A routine run is retried as a new routine run; its task gets `forked_from` = the failed task and counts on from its attempts, and the failed task stays `failed`.
+- Recovery spend: a claim taken while an attempt runs carries its `autofix_id`, and that claim's spend (at hand-in and at turn end) also adds to `tasks.recovery_spent_tokens` and the attempt's `tokens_spent`. Plain runs never count as recovery.
+- The retry prompt (runner and `task_claim`) says which attempt it is and why, the failing check and its redacted output, `KWANT_IDEMPOTENCY_KEY=<key>`, and the external tool calls earlier attempts already made. Calls in an attempt's turns record the key in `turn_tool_calls.idempotency_key`.
+- An attempt ends `succeeded` when its task is verified, `skipped` when it is cancelled, `failed` at the next failure.
+- Scheduled attempts live in the table; the scheduler tick runs the due ones, so a restart loses nothing.
+
+### Workflow changes (person only)
+
+- `workflow_changes`: `id`, `task_id`, `routine_id`, `target` (`check_spec`, `task_acceptance`, `max_attempts`, `routine_instructions`, `routine_schedule`), `before`, `after`, `reason`, `proposed_by`, `status` (`proposed`, `approved`, `rejected`, `applied`, `stale`), `decided_by`, `decided_at`, `created_at`. Triggers: only the person decides; `applied` only after `approved`.
+- Bots propose with the `workflow_propose` tool; kwant reads `before` itself. Approving applies the change once, only while the target still holds `before`; otherwise it goes `stale` and nothing is written.
+
+### Routes
+
+- `GET /api/tasks/:id/failures`: oldest first, each `{id, attempt, source, class, summary, excerpt, checkpoint_id, created_at, autofix: attempt|null}`.
+- `POST /api/tasks/:id/autofix` (person only, `Idempotency-Key` accepted), body `{failure_id?}`: runs the suggested or scheduled attempt now, or plans one. 409 with `code` `not_retryable`, `no_attempts_left` or `over_recovery_budget`.
+- `POST /api/tasks/:id/autofix/:aid/cancel` (person only): a `suggested`/`scheduled` attempt becomes `skipped`.
+- `GET /api/workflow-changes?status=`, `POST /api/workflow-changes/:id/approve`, `POST /api/workflow-changes/:id/reject`: all person only (`/api/workflow-changes` is a person-only segment).
+- `task_json` gains `recovery_spent_tokens`, `recovery_budget_tokens`, `last_failure: {class, summary, created_at}|null` and `autofix: attempt|null`. 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`.
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index e15dd37a..de6985c2 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -44,8 +44,11 @@ export interface NeedsYouItem {
/** check_approval: a required check waits for the person's OK (id = the check's id); only on tasks in review.
* Optional checks never appear here.
* may_be_invalid: an open flag (id = the flag's id), in any state, verified included; resolve it with
- * `POST /api/tasks/:id/flags/:flag_id/resolve`. */
- kind: 'question' | 'approval' | 'human_step' | 'check_approval' | 'may_be_invalid';
+ * `POST /api/tasks/:id/flags/:flag_id/resolve`.
+ * autofix_suggested: a retry waits for the person (id = the attempt's id); run it with `POST /api/tasks/:id/autofix`.
+ * fix_needed: a failure AutoFix never retries (id = the failure's id). workflow_change: a proposed change
+ * (id = the change's id); approve or reject it under /api/workflow-changes. */
+ kind: 'question' | 'approval' | 'human_step' | 'check_approval' | 'may_be_invalid' | 'autofix_suggested' | 'fix_needed' | 'workflow_change';
id: string;
text: string;
}
@@ -108,6 +111,73 @@ export interface Task {
/** Time Machine checkpoints of this task; older servers leave these out. */
checkpoint_count?: number;
last_checkpoint_at?: string | null;
+ /** AutoFix (Phase B3); older servers leave these out. Recovery spend is part of `spent_tokens`. */
+ recovery_spent_tokens?: number;
+ recovery_budget_tokens?: number;
+ last_failure?: { class: FailureClass; summary: string; created_at: string } | null;
+ autofix?: AutofixAttempt | null;
+}
+
+// AutoFix (Phase B3, docs/mission-control.md §13)
+
+export type AutofixMode = 'off' | 'suggest' | 'on';
+export type FailureClass =
+ | 'transient' | 'stalled' | 'check_failed' | 'bad_spec' | 'auth' | 'budget' | 'denied' | 'needs_input' | 'unknown';
+export type FailureSource = 'check' | 'turn' | 'lease' | 'budget' | 'routine' | 'handoff';
+export type AutofixStrategy =
+ | 'wait_and_retry' | 'retry_from_checkpoint' | 'retry_with_diagnostics' | 'retry_same' | 'propose_change' | 'none';
+export type AutofixStatus = 'suggested' | 'scheduled' | 'running' | 'succeeded' | 'failed' | 'skipped';
+
+export interface AutofixAttempt {
+ id: string;
+ strategy: AutofixStrategy;
+ status: AutofixStatus;
+ /** When a scheduled retry may start (backoff); null to start as soon as possible. */
+ not_before: string | null;
+ /** Why; for a skipped attempt it starts with `no_attempts_left`, `over_recovery_budget` or `not_retryable`. */
+ reason: string;
+ tokens_spent: number;
+ /** A routine retry's new task. */
+ retry_task_id: string | null;
+}
+
+/** GET /api/tasks/:id/failures, oldest first. */
+export interface TaskFailure {
+ id: string;
+ attempt: number;
+ source: FailureSource;
+ class: FailureClass;
+ summary: string;
+ /** Redacted output, at most 2,000 characters. */
+ excerpt: string | null;
+ checkpoint_id: string | null;
+ created_at: string;
+ autofix: AutofixAttempt | null;
+}
+
+/** 409 from POST /api/tasks/:id/autofix. */
+export interface AutofixError {
+ error: string;
+ code: 'not_retryable' | 'no_attempts_left' | 'over_recovery_budget';
+}
+
+export type WorkflowTarget = 'check_spec' | 'task_acceptance' | 'max_attempts' | 'routine_instructions' | 'routine_schedule';
+export type WorkflowChangeStatus = 'proposed' | 'approved' | 'rejected' | 'applied' | 'stale';
+
+/** GET /api/workflow-changes (person only). */
+export interface WorkflowChange {
+ id: string;
+ task_id: string | null;
+ routine_id: string | null;
+ target: WorkflowTarget;
+ before: unknown;
+ after: unknown;
+ reason: string;
+ proposed_by: string;
+ proposed_by_name: string | null;
+ status: WorkflowChangeStatus;
+ decided_at: string | null;
+ created_at: string;
}
// Time Machine (Phase B2, docs/mission-control.md §12)
@@ -327,6 +397,9 @@ export interface Insights {
interventions_7d: number;
tokens_7d: number;
tokens_per_verified_7d: number | null;
+ /** AutoFix over the last 7 days (older servers leave these out). */
+ autofix_7d?: { attempts: number; succeeded: number; tokens: number };
+ failures_by_class_7d?: Partial<Record<FailureClass, number>>;
}
// ---------------------------------------------------------------------------
diff --git a/src/db/autofix.rs b/src/db/autofix.rs
index 1ea72cab..235aa6ca 100644
--- a/src/db/autofix.rs
+++ b/src/db/autofix.rs
@@ -3,7 +3,7 @@
//! strategy, at most one live per task) and the permanent changes it or a bot proposes
//! (`workflow_changes`, applied once and only after the person approves). The diagnostics files
//! live under `<data_dir>/autofix/`; no path stored here ever reaches the API. Contract:
-//! docs/mission-control.md §16.
+//! docs/mission-control.md §13.
use super::missions::{insert_event, Task};
use super::{Database, DbError};
@@ -233,8 +233,8 @@ impl Database {
let id = Uuid::new_v4().to_string();
let mut tx = self.pool.begin().await?;
let r = sqlx::query(
- "INSERT OR IGNORE INTO autofix_attempts (id, task_id, failure_id, strategy, idempotency_key, status, not_before, reason, created_at, finished_at) \
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ "INSERT INTO autofix_attempts (id, task_id, failure_id, strategy, idempotency_key, status, not_before, reason, created_at, finished_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(idempotency_key) DO NOTHING",
)
.bind(&id)
.bind(&a.task.id)
@@ -543,18 +543,23 @@ impl Database {
}
/// Insights: AutoFix attempts that ran, succeeded, and their tokens; failures by class.
- pub async fn autofix_stats(&self, since: DateTime<Utc>) -> Result<(i64, i64, i64, Vec<(String, i64)>), DbError> {
+ pub async fn autofix_stats(&self, space_id: &str, since: DateTime<Utc>) -> Result<(i64, i64, i64, Vec<(String, i64)>), DbError> {
let (attempts, succeeded, tokens): (i64, i64, i64) = sqlx::query_as(
- "SELECT COUNT(*), COALESCE(SUM(status = 'succeeded'), 0), COALESCE(SUM(tokens_spent), 0) FROM autofix_attempts \
- WHERE created_at >= ? AND status IN ('running', 'succeeded', 'failed')",
+ "SELECT COUNT(*), COALESCE(SUM(a.status = 'succeeded'), 0), COALESCE(SUM(a.tokens_spent), 0) FROM autofix_attempts a \
+ JOIN tasks t ON t.id = a.task_id WHERE t.space_id = ? AND a.created_at >= ? AND a.status IN ('running', 'succeeded', 'failed')",
)
+ .bind(space_id)
.bind(since)
.fetch_one(&self.pool)
.await?;
- let classes: Vec<(String, i64)> = sqlx::query_as("SELECT class, COUNT(*) FROM task_failures WHERE created_at >= ? GROUP BY class ORDER BY class")
- .bind(since)
- .fetch_all(&self.pool)
- .await?;
+ let classes: Vec<(String, i64)> = sqlx::query_as(
+ "SELECT f.class, COUNT(*) FROM task_failures f JOIN tasks t ON t.id = f.task_id \
+ WHERE t.space_id = ? AND f.created_at >= ? GROUP BY f.class ORDER BY f.class",
+ )
+ .bind(space_id)
+ .bind(since)
+ .fetch_all(&self.pool)
+ .await?;
Ok((attempts, succeeded, tokens, classes))
}
}
diff --git a/src/server/missions/autofix.rs b/src/server/missions/autofix.rs
index e1f8b86b..c1159ab0 100644
--- a/src/server/missions/autofix.rs
+++ b/src/server/missions/autofix.rs
@@ -6,7 +6,7 @@
//! task's own attempts and recovery budget allow. `suggest` plans the same retry but waits for the
//! person. Permanent changes (a routine's instructions or schedule, a check's spec, a task's
//! acceptance or max attempts) are only ever proposed; the person approves them, and they are
-//! applied once. Contract: docs/mission-control.md §16.
+//! applied once. Contract: docs/mission-control.md §13.
use super::routes::{bad, conflict, internal, load_task, not_found};
use super::{emit_task, transition, Actor};
@@ -558,7 +558,7 @@ pub async fn retry_note(state: &AppState, task: &Task) -> Option<String> {
"retry_with_diagnostics" => {
let checks = state.db.list_checks(&task.id).await.unwrap_or_default();
if let Some(c) = checks.iter().find(|c| matches!(c.status.as_str(), "failed" | "error")) {
- out.push_str(&format!("The check that failed: {} {}\n", c.kind, c.spec_value()));
+ out.push_str(&format!("The check that failed: {} {}\n", c.kind, redact(&c.spec_value().to_string())));
}
if let Some(x) = &failure.excerpt {
out.push_str(&format!("Its output (secrets masked):\n{x}\n"));
@@ -812,7 +812,7 @@ async fn change_json(state: &AppState, c: &WorkflowChange) -> Value {
pub async fn list_changes(State(state): State<AppState>, RawQuery(q): RawQuery) -> Response {
let status = q.as_deref().unwrap_or("").split('&').find_map(|p| p.strip_prefix("status=")).map(str::to_string);
if let Some(s) = status.as_deref().filter(|s| !["proposed", "approved", "rejected", "applied", "stale"].contains(s)) {
- return bad(&format!("status must be proposed, approved, rejected, applied or stale (got {s})"));
+ return bad(format!("status must be proposed, approved, rejected, applied or stale (got {s})"));
}
match state.db.list_changes(status.as_deref(), None).await {
Ok(list) => {
@@ -980,9 +980,9 @@ pub async fn propose(state: &AppState, bot_id: &str, args: &Value) -> Result<Val
Ok(json!({"id": c.id, "status": c.status, "note": "Proposed. Only the person can approve it; nothing changes until then."}))
}
-/// Insights: `autofix_7d` and `failures_by_class_7d`.
-pub async fn insights(state: &AppState, since: DateTime<Utc>) -> (Value, Value) {
- let (attempts, succeeded, tokens, classes) = state.db.autofix_stats(since).await.unwrap_or_default();
+/// Insights for a space: `autofix_7d` and `failures_by_class_7d`.
+pub async fn insights(state: &AppState, space_id: &str, since: DateTime<Utc>) -> (Value, Value) {
+ let (attempts, succeeded, tokens, classes) = state.db.autofix_stats(space_id, since).await.unwrap_or_default();
let by_class: serde_json::Map<String, Value> = classes.into_iter().map(|(c, n)| (c, json!(n))).collect();
(json!({"attempts": attempts, "succeeded": succeeded, "tokens": tokens}), Value::Object(by_class))
}
diff --git a/src/server/missions/checks.rs b/src/server/missions/checks.rs
index 42ca28e6..3cb6afb8 100644
--- a/src/server/missions/checks.rs
+++ b/src/server/missions/checks.rs
@@ -194,6 +194,8 @@ pub async fn run_check(state: &AppState, task: &Task, check: &OutcomeCheck) -> O
// didn't add or approve is held to public addresses again now, pinned against DNS rebinding.
let person_ok = check.requested_by == "person" || approved_by_person(state, check).await;
let (status, output) = run_spec(&check.kind, &spec, folder.as_deref(), person_ok).await;
+ // The excerpt reaches bots and the API: credentials in the output never get stored
+ let output = super::autofix::redact(&output);
let ev = state
.db
.add_evidence(&NewEvidence {
diff --git a/src/server/missions/listener.rs b/src/server/missions/listener.rs
index ab0afe7a..418d9c02 100644
--- a/src/server/missions/listener.rs
+++ b/src/server/missions/listener.rs
@@ -234,7 +234,8 @@ pub async fn on_routine_run(state: &AppState, routine_id: &str, run_id: &str, st
finish(state, &t, "review", "the routine run finished").await;
}
(Some(t), "error") => {
- if finish(state, &t, "failed", "the routine run failed").await {
+ let failed = finish(state, &t, "failed", "the routine run failed").await;
+ if failed {
let err = state.db.routine_run_error(run_id).await.ok().flatten().unwrap_or_else(|| "the routine run failed".into());
super::autofix::record(state, &t.id, "routine", "error", &err, err.lines().next().unwrap_or("the routine run failed")).await;
}
diff --git a/src/server/missions/routes.rs b/src/server/missions/routes.rs
index 2183ebf9..a88887aa 100644
--- a/src/server/missions/routes.rs
+++ b/src/server/missions/routes.rs
@@ -324,7 +324,7 @@ pub async fn insights(State(state): State<AppState>, Scope(space): Scope) -> Res
let still_blocked: Vec<&str> = all.iter().filter(|t| t.state == "blocked").map(|t| t.id.as_str()).collect();
let blocked_minutes = blocked_minutes(&events, &still_blocked, since, chrono::Utc::now());
let per = if verified.is_empty() { Value::Null } else { json!(tokens / verified.len() as i64) };
- let (autofix_7d, failures_by_class_7d) = super::autofix::insights(&state, since).await;
+ let (autofix_7d, failures_by_class_7d) = super::autofix::insights(&state, space.as_str(), since).await;
Json(json!({
"verified_7d": verified.len(),
"false_success_7d": false_success,
diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rs
index 22ba7490..d40a2b89 100644
--- a/src/server/missions/runner.rs
+++ b/src/server/missions/runner.rs
@@ -183,7 +183,7 @@ async fn run_one(state: &AppState, m: &Mission, task: &Task, bot: &crate::db::mo
/// After a runner turn of `task_id`: still `working` means the bot didn't finish or let go, so the
/// lease is released (one attempt used). With AutoFix on, a task with attempts left parks in
-/// `failed` for it (§16), and the failure is recorded: the turn's error, a denied action since
+/// `failed` for it (§13), and the failure is recorded: the turn's error, a denied action since
/// `started`, or a stall; a task left waiting on the person records `needs_input`.
pub async fn after_turn(state: &AppState, task_id: &str, err: Option<&str>, started: chrono::DateTime<chrono::Utc>) {
let Ok(Some(t)) = state.db.get_task(task_id).await else { return };
diff --git a/tests/mission_autofix_test.rs b/tests/mission_autofix_test.rs
new file mode 100644
index 00000000..b6ddcd0a
--- /dev/null
+++ b/tests/mission_autofix_test.rs
@@ -0,0 +1,697 @@
+//! Mission Control Phase B3: AutoFix. A failure is recorded with a class and redacted
+//! diagnostics; with `autofix` on, a retryable one gets a bounded attempt (its own strategy, the
+//! task's attempts, a recovery budget), and a permanent change is only ever proposed until the
+//! person approves it. These are the contract's 10 acceptance tests (docs/mission-control.md §13),
+//! numbered as there. Its own test binary: it changes PATH and listens on a real port the
+//! stand-in CLI calls back on.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrono::{DateTime, Utc};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{autofix::NewAttempt, continuity::NewRoutine, models::Kwant, spaces::SpaceId, Database},
+ router::LayaRouter,
+ server::{
+ continuity::{SelfScope, TurnOrigin},
+ create_router, mcp_runtime,
+ missions::{autofix::classify, listener, runner},
+ AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::os::unix::fs::PermissionsExt;
+use std::path::PathBuf;
+use std::sync::OnceLock;
+use std::time::Duration;
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+/// On a Mission Control prompt: logs the prompt (with the task it holds) to prompts.log next to
+/// itself, streams its usage so far (10 input, 10 output), moves the task to review through its
+/// kwant tools, then reports the same final usage: 20 fresh tokens a turn, all known at hand-in.
+const FAKE_CLAUDE: &str = r#"#!/usr/bin/env python3
+import json, os, re, sys, urllib.request
+args = sys.argv[1:]
+if args[:1] == ["auth"]:
+ print('{"loggedIn":true}')
+ sys.exit(0)
+prompt = args[-1] if args else ""
+held = re.search(r"You hold task (\S+) of", prompt)
+if held and "--mcp-config" in args:
+ with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "prompts.log"), "a") as f:
+ f.write(json.dumps({"task": held.group(1), "prompt": prompt}) + "\n")
+ start = {"type": "message_start", "message": {"id": "msg_1", "usage": {"input_tokens": 10, "output_tokens": 1}}}
+ print(json.dumps({"type": "stream_event", "event": start}), flush=True)
+ print(json.dumps({"type": "stream_event", "event": {"type": "message_delta", "usage": {"output_tokens": 10}}}), flush=True)
+ with open(args[args.index("--mcp-config") + 1]) as f:
+ servers = json.load(f).get("mcpServers", {})
+ for s in servers.values():
+ if s.get("url", "").endswith("/api/mcp/self"):
+ call = {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": {"name": "task_update", "arguments": {"task_id": held.group(1), "status": "review"}}}
+ headers = dict(s.get("headers", {}), **{"content-type": "application/json"})
+ req = urllib.request.Request(s["url"], data=json.dumps(call).encode(), headers=headers)
+ urllib.request.urlopen(req, timeout=30).read()
+print(json.dumps({"type": "result", "is_error": False, "num_turns": 1, "result": "done, sent for review",
+ "usage": {"input_tokens": 10, "output_tokens": 10}}))
+"#;
+
+/// Fresh tokens of one stand-in CLI turn.
+const PER_TURN: i64 = 20;
+
+fn fake_cli() -> PathBuf {
+ static DONE: OnceLock<PathBuf> = OnceLock::new();
+ DONE.get_or_init(|| {
+ let bin = tempfile::tempdir().unwrap().keep().join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ let fake = bin.join("claude");
+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();
+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ bin
+ })
+ .clone()
+}
+
+/// The prompts the stand-in CLI got for `tid`, in order.
+fn prompts(tid: &str) -> Vec<String> {
+ let log = std::fs::read_to_string(fake_cli().join("prompts.log")).unwrap_or_default();
+ log.lines()
+ .filter_map(|l| serde_json::from_str::<Value>(l).ok())
+ .filter(|v| v["task"] == tid)
+ .map(|v| v["prompt"].as_str().unwrap_or("").to_string())
+ .collect()
+}
+
+struct Env {
+ app: Router,
+ state: AppState,
+ bot: Kwant,
+ general: String,
+ tmp: TempDir,
+}
+
+/// kwant on a real port (the stand-in CLI calls back), with the mission board on.
+async fn setup() -> Env {
+ let tmp = tempdir().unwrap();
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let state = state_on(&tmp, port, db);
+ let app = create_router(state.clone());
+ let served = app.clone();
+ tokio::spawn(async move { axum::serve(listener, served).await.unwrap() });
+ 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, state, bot, general, tmp };
+ person(&e, "POST", "/api/settings", Some(json!({"mission_board": true}))).await;
+ e
+}
+
+fn state_on(tmp: &TempDir, port: u16, db: Database) -> AppState {
+ let config = Config {
+ data_dir: tmp.path().to_path_buf(),
+ host: "127.0.0.1".into(),
+ port,
+ laya_url: "http://127.0.0.1:9".into(),
+ browser_cdp_url: Some("http://127.0.0.1:9".into()),
+ ..Config::default()
+ };
+ AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ )
+}
+
+async fn send(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) = send(&e.app, method, uri, None, body).await;
+ assert!(status.is_success(), "{method} {uri}: {status} {v}");
+ v
+}
+
+async fn ok(e: &Env, token: &str, name: &str, args: Value) -> Value {
+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});
+ let (status, v) = send(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc)).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ let text = v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string();
+ assert!(!v["result"]["isError"].as_bool().unwrap_or(false), "{name} {args} failed: {text}");
+ serde_json::from_str(&text).unwrap_or(Value::Null)
+}
+
+/// 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
+}
+
+fn id(v: &Value) -> String {
+ v["id"].as_str().unwrap().to_string()
+}
+
+async fn task(e: &Env, id: &str) -> Value {
+ person(e, "GET", &format!("/api/tasks/{id}"), None).await["task"].clone()
+}
+
+async fn failures(e: &Env, tid: &str) -> Vec<Value> {
+ person(e, "GET", &format!("/api/tasks/{tid}/failures"), None).await.as_array().unwrap().clone()
+}
+
+async fn autofix(e: &Env, mode: &str, pct: i64) {
+ person(e, "POST", "/api/settings", Some(json!({"autofix": mode, "recovery_budget_pct": pct}))).await;
+}
+
+/// Waits until `tid` is in `want` (up to ~15 s).
+async fn wait_state(e: &Env, tid: &str, want: &str) -> Value {
+ for _ in 0..300 {
+ let t = task(e, tid).await;
+ if t["state"] == want {
+ return t;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ panic!("{tid} never got to {want}: {}", task(e, tid).await);
+}
+
+/// A person task of the default bot with `checks`, outside any mission (no runner turns start),
+/// and its folder.
+async fn person_task(e: &Env, checks: Value) -> String {
+ let body = json!({"title": "Fix it", "acceptance": "works", "owner_kwant_id": e.bot.id, "checks": checks});
+ let t = person(e, "POST", "/api/tasks", Some(body)).await;
+ let tid = id(&t);
+ let row = e.state.db.get_task(&tid).await.unwrap().unwrap();
+ std::fs::create_dir_all(kwnt::server::missions::task_folder(&e.state, &row).await.unwrap()).unwrap();
+ tid
+}
+
+/// The default bot claims `tid` in a new turn; returns the turn id and its token.
+async fn claim(e: &Env, tid: &str) -> (String, String) {
+ let turn_id = format!("t-{}", uuid::Uuid::new_v4());
+ let token = turn(e, &e.bot, &turn_id).await;
+ ok(e, &token, "task_claim", json!({"task_id": tid})).await;
+ (turn_id, token)
+}
+
+/// Claims `tid` and hands it in; its checks run.
+async fn hand_in(e: &Env, tid: &str) {
+ let (_, token) = claim(e, tid).await;
+ ok(e, &token, "task_update", json!({"task_id": tid, "status": "review"})).await;
+}
+
+/// A failing command check whose output says what went wrong.
+fn failing_check() -> Value {
+ json!([{"kind": "command", "spec": {"command": "echo expected 42 got 41; exit 1"}}])
+}
+
+/// A bot that runs on the stand-in claude CLI, with approvals off for the space.
+async fn cli_bot(e: &Env) -> String {
+ fake_cli();
+ e.state.db.set_space_approvals(&SpaceId::default_space(), "off").await.unwrap();
+ let bot = json!({"name": "Ann", "title": "Ann the tester", "persona_prompt": "Test persona",
+ "avatar_sprite": "s", "driver_type": "cli", "preferred_model": "claude"});
+ id(&person(e, "POST", "/api/kwants", Some(bot)).await)
+}
+
+/// A mission of one task for the stand-in CLI bot with the failing check; returns its ids.
+async fn cli_mission(e: &Env, budget: i64) -> (String, String) {
+ let ann = cli_bot(e).await;
+ let body = json!({"title": "Ship it", "goal": "a release", "lead_kwant_id": ann, "budget_tokens": 900_000,
+ "channel_id": e.general, "tasks": [{"title": "A", "owner": ann, "budget_tokens": budget, "checks": failing_check()}]});
+ let m = person(e, "POST", "/api/missions", Some(body)).await;
+ let mid = id(&m);
+ let detail = person(e, "GET", &format!("/api/missions/{mid}"), None).await;
+ let tid = id(&detail["tasks"][0]);
+ let row = e.state.db.get_mission(&mid).await.unwrap().unwrap();
+ std::fs::create_dir_all(&row.workspace_path).unwrap();
+ (mid, tid)
+}
+
+/// Waits until the mission's runner turn is over and its spend has landed.
+async fn runner_idle(mid: &str) {
+ for _ in 0..300 {
+ if !runner::is_running(mid) {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ tokio::time::sleep(Duration::from_millis(200)).await;
+}
+
+async fn attempts(e: &Env, tid: &str) -> Vec<kwnt::db::autofix::Attempt> {
+ e.state.db.attempts_of(tid).await.unwrap()
+}
+
+fn kinds(items: &Value) -> Vec<String> {
+ items.as_array().unwrap().iter().map(|i| i["kind"].as_str().unwrap().to_string()).collect()
+}
+
+fn at(v: &Value) -> DateTime<Utc> {
+ v.as_str().unwrap().parse().unwrap()
+}
+
+// 1
+#[test]
+fn classify_maps_every_signal_to_its_class() {
+ let rows = [
+ // engine drivers (claude CLI, codex, grok, the API driver) and routine runs
+ ("turn", "error", "Not logged in · Please run /login", "auth"),
+ ("turn", "error", "Not signed in: run `claude auth login` and try again", "auth"),
+ ("turn", "error", "OAuth token has expired. Please obtain a new token or refresh your existing token.", "auth"),
+ ("turn", "error", "API key rejected (401)", "auth"),
+ ("turn", "error", "unexpected status 401 Unauthorized: Reconnecting… timed out", "auth"),
+ ("turn", "error", "Credit balance is too low", "auth"),
+ ("turn", "error", "API Error: 529 {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\"}}", "transient"),
+ ("turn", "error", "stream error: rate-limiting (HTTP 429)", "transient"),
+ ("routine", "error", "Quota exceeded (429)", "transient"),
+ ("handoff", "error", "error sending request: connection refused", "transient"),
+ ("turn", "error", "upstream 503 Service Unavailable", "transient"),
+ ("turn", "error", "the model said something odd", "unknown"),
+ ("turn", "error", "ran 4290 steps", "unknown"),
+ // checks
+ ("check", "failed", "command echo\nexit code 1\nexpected 42 got 41", "check_failed"),
+ ("check", "failed", "command nosuchcmd\nexit code 127\nsh: 1: nosuchcmd: not found", "bad_spec"),
+ ("check", "failed", "command x\nexit code 1\nbash: x: command not found", "bad_spec"),
+ ("check", "error", "Check timed out after 30s", "transient"),
+ ("check", "error", "file out.csv: path escapes the task folder", "bad_spec"),
+ // what the board itself saw
+ ("lease", "stalled", "", "stalled"),
+ ("budget", "error", "over budget: 120 of 100 tokens", "budget"),
+ ("turn", "stalled", "", "stalled"),
+ ("turn", "denied", "mcp__gmail__send: send to bob", "denied"),
+ ("turn", "needs_input", "", "needs_input"),
+ ];
+ for (source, status, text, want) in rows {
+ assert_eq!(classify(source, status, text), want, "{source}/{status}: {text}");
+ }
+}
+
+// 2
+#[tokio::test]
+async fn a_failing_check_is_retried_with_its_diagnostics_until_the_attempts_run_out() {
+ let e = setup().await;
+ autofix(&e, "on", 25).await;
+ let (mid, tid) = cli_mission(&e, 50_000).await;
+ person(&e, "POST", &format!("/api/missions/{mid}/run"), Some(json!({"max_tasks": 1}))).await;
+ // Three runs: the first, then two AutoFix retries; the last failure has no attempt left
+ for _ in 0..600 {
+ let t = task(&e, &tid).await;
+ if t["state"] == "failed" && t["attempts"] == 3 && failures(&e, &tid).await.len() == 3 {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ runner_idle(&mid).await;
+ let t = task(&e, &tid).await;
+ assert_eq!((t["state"].as_str(), t["attempts"].as_i64()), (Some("failed"), Some(3)), "{t}");
+ let fs = failures(&e, &tid).await;
+ assert_eq!(fs.len(), 3, "{fs:?}");
+ assert!(fs.iter().all(|f| f["class"] == "check_failed" && f["source"] == "check"), "{fs:?}");
+ assert!(fs[0]["excerpt"].as_str().unwrap().contains("expected 42 got 41"), "{fs:?}");
+ let a = attempts(&e, &tid).await;
+ let got: Vec<(&str, &str)> = a.iter().map(|a| (a.strategy.as_str(), a.status.as_str())).collect();
+ assert_eq!(
+ got,
+ [("retry_with_diagnostics", "failed"), ("retry_with_diagnostics", "failed"), ("retry_with_diagnostics", "skipped")],
+ "{a:?}"
+ );
+ assert!(a[2].reason.starts_with("no_attempts_left"), "{a:?}");
+ let ins = person(&e, "GET", "/api/missions/insights", None).await;
+ assert_eq!(ins["failures_by_class_7d"]["check_failed"], 3, "{ins}");
+ assert_eq!(ins["autofix_7d"]["attempts"], 2, "{ins}");
+ // The retries' prompts carry the check's output and the attempt's idempotency key
+ let p = prompts(&tid);
+ assert_eq!(p.len(), 3, "{p:?}");
+ assert!(!p[0].contains("[AutoFix]"), "{}", p[0]);
+ for (n, prompt) in p.iter().enumerate().skip(1) {
+ assert!(prompt.contains(&format!("[AutoFix] This is attempt {} of 3", n + 1)), "{prompt}");
+ assert!(prompt.contains("expected 42 got 41"), "{prompt}");
+ assert!(prompt.contains("KWANT_IDEMPOTENCY_KEY="), "{prompt}");
+ }
+ assert!(t["needs_you"].as_array().unwrap().iter().all(|i| i["kind"] != "autofix_suggested"), "{t}");
+ // No attempt can be scheduled past max_attempts, even in SQL
+ let sql = format!(
+ "INSERT INTO autofix_attempts (id, task_id, failure_id, strategy, idempotency_key, status, reason, created_at) \
+ VALUES ('extra', '{tid}', '{}', 'retry_same', 'extra-key', 'scheduled', 'more', '2026-10-27T00:00:00Z')",
+ fs[2]["id"].as_str().unwrap()
+ );
+ let err = e.state.db.exec_raw_for_test(&sql).await.unwrap_err().to_string();
+ assert!(err.contains("within the task's attempts"), "{err}");
+}
+
+// 3
+#[tokio::test]
+async fn off_records_only_and_suggest_waits_for_the_person() {
+ let e = setup().await;
+ // off (the default): Phase A behaviour, the failure is only recorded
+ let off = person_task(&e, failing_check()).await;
+ hand_in(&e, &off).await;
+ let t = wait_state(&e, &off, "ready").await;
+ assert_eq!(t["attempts"], 1, "{t}");
+ let fs = failures(&e, &off).await;
+ assert_eq!(fs.len(), 1, "{fs:?}");
+ assert_eq!(fs[0]["class"], "check_failed");
+ assert!(attempts(&e, &off).await.is_empty(), "off plans nothing");
+ assert_eq!(t["last_failure"]["class"], "check_failed", "{t}");
+ // suggest: one suggested attempt and a Needs-you item; nothing runs until the person asks
+ autofix(&e, "suggest", 25).await;
+ let sug = person_task(&e, failing_check()).await;
+ hand_in(&e, &sug).await;
+ wait_state(&e, &sug, "failed").await;
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ kwnt::server::missions::autofix::run_due(&e.state).await;
+ let t = task(&e, &sug).await;
+ assert_eq!(t["state"], "failed", "nothing runs on its own: {t}");
+ let a = attempts(&e, &sug).await;
+ assert_eq!(a.len(), 1, "{a:?}");
+ assert_eq!((a[0].strategy.as_str(), a[0].status.as_str()), ("retry_with_diagnostics", "suggested"));
+ assert_eq!(t["autofix"]["status"], "suggested", "{t}");
+ assert!(kinds(&t["needs_you"]).contains(&"autofix_suggested".to_string()), "{t}");
+ let r = person(&e, "POST", &format!("/api/tasks/{sug}/autofix"), None).await;
+ assert_eq!(r["status"], "running", "{r}");
+ let t = task(&e, &sug).await;
+ assert_eq!(t["state"], "ready", "{t}");
+ assert!(!kinds(&t["needs_you"]).contains(&"autofix_suggested".to_string()), "{t}");
+ // The bot's next claim is the attempt's: the claim note says so
+ claim(&e, &sug).await;
+ let note = kwnt::server::missions::autofix::retry_note(&e.state, &e.state.db.get_task(&sug).await.unwrap().unwrap()).await.unwrap();
+ assert!(note.contains("expected 42 got 41") && note.contains("KWANT_IDEMPOTENCY_KEY="), "{note}");
+}
+
+// 4
+#[tokio::test]
+async fn a_retry_over_the_recovery_budget_is_skipped_and_only_autofix_turns_count_as_recovery() {
+ let e = setup().await;
+ autofix(&e, "on", 25).await;
+ // A budget of 100: 25 for recovery, and each turn spends 20
+ let (mid, tid) = cli_mission(&e, 100).await;
+ person(&e, "POST", &format!("/api/missions/{mid}/run"), Some(json!({"max_tasks": 1}))).await;
+ for _ in 0..600 {
+ let a = attempts(&e, &tid).await;
+ if a.len() == 2 && a[1].status == "skipped" {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ runner_idle(&mid).await;
+ let t = task(&e, &tid).await;
+ // The first turn was a plain run: none of it is recovery; the AutoFix retry's turn is
+ assert_eq!(t["spent_tokens"], 2 * PER_TURN, "{t}");
+ assert_eq!(t["recovery_spent_tokens"], PER_TURN, "{t}");
+ assert_eq!(t["recovery_budget_tokens"], 25, "{t}");
+ let a = attempts(&e, &tid).await;
+ assert_eq!(a.len(), 2, "{a:?}");
+ assert_eq!((a[0].status.as_str(), a[0].tokens_spent), ("failed", PER_TURN), "{a:?}");
+ assert_eq!(a[1].status, "skipped", "{a:?}");
+ assert!(a[1].reason.starts_with("over_recovery_budget"), "{a:?}");
+ assert_eq!(t["state"], "failed", "{t}");
+ assert_eq!(t["attempts"], 2, "an attempt is left, but no recovery budget: {t}");
+ // At 10% the person can't push one through either
+ autofix(&e, "on", 10).await;
+ let (status, v) = send(&e.app, "POST", &format!("/api/tasks/{tid}/autofix"), None, None).await;
+ assert_eq!(status, StatusCode::CONFLICT, "{v}");
+ assert_eq!(v["code"], "over_recovery_budget", "{v}");
+ assert_eq!(task(&e, &tid).await["state"], "failed");
+}
+
+// 5
+#[tokio::test]
+async fn transient_failures_back_off_1_5_25_minutes_and_survive_a_restart() {
+ let e = setup().await;
+ autofix(&e, "on", 25).await;
+ let tid = person_task(&e, json!([])).await;
+ e.state.db.exec_raw_for_test(&format!("UPDATE tasks SET max_attempts = 5 WHERE id = '{tid}'")).await.unwrap();
+ let mut waits = Vec::new();
+ for n in 0..3 {
+ let started = Utc::now();
+ claim(&e, &tid).await;
+ runner::after_turn(&e.state, &tid, Some("API Error: 429 rate_limit_error: This request would exceed your rate limit"), started).await;
+ assert_eq!(task(&e, &tid).await["state"], "failed");
+ let fs = failures(&e, &tid).await;
+ let f = fs.last().unwrap();
+ assert_eq!(f["class"], "transient", "{fs:?}");
+ let a = &f["autofix"];
+ assert_eq!((a["strategy"].as_str(), a["status"].as_str()), (Some("wait_and_retry"), Some("scheduled")), "{a}");
+ waits.push((at(&a["not_before"]) - at(&f["created_at"])).num_minutes());
+ let aid = a["id"].as_str().unwrap().to_string();
+ if n == 0 {
+ // A restart: a new pool on the same database. The attempt is still there, once
+ let db2 = Database::init(e.tmp.path()).await.unwrap();
+ let state2 = state_on(&e.tmp, 9, db2);
+ let row = state2.db.get_task(&tid).await.unwrap().unwrap();
+ let again = state2.db.attempts_of(&tid).await.unwrap();
+ assert_eq!(again.len(), 1, "{again:?}");
+ let same_key = NewAttempt {
+ task: &row,
+ failure_id: &again[0].failure_id,
+ strategy: "wait_and_retry",
+ idempotency_key: again[0].idempotency_key.clone(),
+ status: "scheduled",
+ not_before: None,
+ reason: "again".into(),
+ };
+ assert!(state2.db.insert_attempt(&same_key).await.unwrap().is_none(), "the same key plans nothing twice");
+ let other = NewAttempt { idempotency_key: "another".into(), ..same_key };
+ assert!(state2.db.insert_attempt(&other).await.is_err(), "one live attempt per task");
+ // Not due yet: the tick leaves it; once due, the reloaded app runs it
+ kwnt::server::missions::autofix::run_due(&state2).await;
+ assert_eq!(state2.db.get_attempt(&aid).await.unwrap().unwrap().status, "scheduled");
+ state2.db.exec_raw_for_test(&format!("UPDATE autofix_attempts SET not_before = '2026-01-01T00:00:00Z' WHERE id = '{aid}'")).await.unwrap();
+ kwnt::server::missions::autofix::run_due(&state2).await;
+ assert_eq!(state2.db.get_attempt(&aid).await.unwrap().unwrap().status, "running");
+ } else {
+ // The person asks now: no waiting
+ let r = person(&e, "POST", &format!("/api/tasks/{tid}/autofix"), None).await;
+ assert_eq!((r["id"].as_str(), r["status"].as_str()), (Some(aid.as_str()), Some("running")), "{r}");
+ }
+ assert_eq!(task(&e, &tid).await["state"], "ready");
+ }
+ assert_eq!(waits, [1, 5, 25]);
+}
+
+// 6
+#[tokio::test]
+async fn auth_budget_and_denied_are_never_retried_and_ask_the_person() {
+ let e = setup().await;
+ autofix(&e, "on", 25).await;
+ // auth
+ let auth = person_task(&e, json!([])).await;
+ let started = Utc::now();
+ claim(&e, &auth).await;
+ runner::after_turn(&e.state, &auth, Some("Not logged in · Please run /login"), started).await;
+ // denied
+ let denied = person_task(&e, json!([])).await;
+ let started = Utc::now();
+ let (turn_id, _) = claim(&e, &denied).await;
+ e.state
+ .db
+ .log_tool_call(&turn_id, &e.bot.id, &denied, "mcp__gmail__send", "external", "send to [email protected]", "denied", None, None)
+ .await
+ .unwrap();
+ runner::after_turn(&e.state, &denied, None, started).await;
+ for (tid, class) in [(&auth, "auth"), (&denied, "denied")] {
+ let t = task(&e, tid).await;
+ assert_eq!(t["state"], "failed", "{t}");
+ assert_eq!(t["last_failure"]["class"], class, "{t}");
+ let a = attempts(&e, tid).await;
+ assert_eq!(a.len(), 1, "{a:?}");
+ assert_eq!((a[0].strategy.as_str(), a[0].status.as_str()), ("none", "skipped"), "{a:?}");
+ assert!(kinds(&t["needs_you"]).contains(&"fix_needed".to_string()), "{t}");
+ let (status, v) = send(&e.app, "POST", &format!("/api/tasks/{tid}/autofix"), None, None).await;
+ assert_eq!((status, v["code"].as_str()), (StatusCode::CONFLICT, Some("not_retryable")), "{v}");
+ }
+ // budget: over its budget, the task is blocked, and AutoFix never moves a blocked task
+ let body = json!({"title": "Small", "owner_kwant_id": e.bot.id, "budget_tokens": 100});
+ let budget = id(&person(&e, "POST", "/api/tasks", Some(body)).await);
+ let started_ms = Utc::now().timestamp_millis() - 1000;
+ let (turn_id, _) = claim(&e, &budget).await;
+ kwnt::server::missions::spend(&e.state, &e.bot.id, &e.general, Some(&turn_id), started_ms, 150, 0).await;
+ let t = task(&e, &budget).await;
+ assert_eq!(t["state"], "blocked", "{t}");
+ assert_eq!(t["last_failure"]["class"], "budget", "{t}");
+ assert!(kinds(&t["needs_you"]).contains(&"fix_needed".to_string()), "{t}");
+ assert!(attempts(&e, &budget).await.iter().all(|a| a.status == "skipped"));
+ let (status, v) = send(&e.app, "POST", &format!("/api/tasks/{budget}/autofix"), None, None).await;
+ assert_eq!((status, v["code"].as_str()), (StatusCode::CONFLICT, Some("not_retryable")), "{v}");
+ kwnt::server::missions::autofix::run_due(&e.state).await;
+ assert_eq!(task(&e, &budget).await["state"], "blocked");
+}
+
+// 7
+#[tokio::test]
+async fn a_failed_routine_run_is_retried_as_a_new_linked_run() {
+ let e = setup().await;
+ autofix(&e, "on", 25).await;
+ let routine = e
+ .state
+ .db
+ .create_routine(&NewRoutine {
+ kwant_id: e.bot.id.clone(),
+ channel_id: Some(e.general.clone()),
+ name: "Morning digest".into(),
+ instructions: "Post the digest".into(),
+ schedule: json!({"type": "interval", "every_minutes": 60}).to_string(),
+ enabled: false,
+ next_run_at: None,
+ thread_id: None,
+ context_message_id: None,
+ })
+ .await
+ .unwrap();
+ let run = e.state.db.start_routine_run(&routine.id, "schedule", "running", None).await.unwrap();
+ listener::on_routine_run(&e.state, &routine.id, &run.id, "running").await;
+ let failed = e.state.db.task_by_source("routine", &run.id).await.unwrap().unwrap();
+ e.state.db.finish_routine_run(&run.id, "error", Some("stream error: rate-limiting (HTTP 429)"), None).await.unwrap();
+ listener::on_routine_run(&e.state, &routine.id, &run.id, "error").await;
+ let t = task(&e, &failed.id).await;
+ assert_eq!(t["state"], "failed", "{t}");
+ assert_eq!(t["last_failure"]["class"], "transient", "{t}");
+ let r = person(&e, "POST", &format!("/api/tasks/{}/autofix", failed.id), None).await;
+ assert_eq!(r["status"], "running", "{r}");
+ let new_id = r["retry_task_id"].as_str().expect("the retry is a new run's task").to_string();
+ assert_ne!(new_id, failed.id);
+ let new = e.state.db.get_task(&new_id).await.unwrap().unwrap();
+ assert_eq!(new.forked_from.as_deref(), Some(failed.id.as_str()));
+ assert_eq!(new.source_kind, "routine");
+ assert_ne!(new.source_id, failed.source_id, "a new routine run");
+ assert_eq!(new.attempts, 1, "the failed run used one attempt");
+ assert_eq!(e.state.db.latest_claim_autofix(&new_id).await.unwrap().as_deref(), Some(r["id"].as_str().unwrap()), "its spend is recovery");
+ assert_eq!(task(&e, &failed.id).await["state"], "failed", "the failed task stays failed");
+}
+
+// 8
+#[tokio::test]
+async fn workflow_changes_are_applied_once_and_only_by_the_person() {
+ let e = setup().await;
+ let tid = person_task(&e, json!([])).await;
+ let (_, token) = claim(&e, &tid).await;
+ let p = ok(&e, &token, "workflow_propose", json!({"target": "task_acceptance", "task_id": tid, "after": "works, with tests", "reason": "the acceptance is vague"})).await;
+ let cid = id(&p);
+ assert_eq!(p["status"], "proposed");
+ // Not even SQL applies a change nobody approved
+ let err = e.state.db.exec_raw_for_test(&format!("UPDATE workflow_changes SET status = 'applied' WHERE id = '{cid}'")).await.unwrap_err().to_string();
+ assert!(err.contains("only the person decides") || err.contains("only after the person approves"), "{err}");
+ let listed = person(&e, "GET", "/api/workflow-changes?status=proposed", None).await;
+ assert_eq!(listed[0]["before"], json!({"acceptance": "works"}), "before is read by kwant: {listed}");
+ let (status, _) = send(&e.app, "POST", &format!("/api/workflow-changes/{cid}/approve"), Some(&token), None).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ let (status, _) = send(&e.app, "GET", "/api/workflow-changes", Some(&token), None).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ let c = person(&e, "POST", &format!("/api/workflow-changes/{cid}/approve"), None).await;
+ assert_eq!(c["status"], "applied", "{c}");
+ assert_eq!(e.state.db.get_task(&tid).await.unwrap().unwrap().acceptance, "works, with tests");
+ let (status, _) = send(&e.app, "POST", &format!("/api/workflow-changes/{cid}/approve"), None, None).await;
+ assert_eq!(status, StatusCode::CONFLICT, "applied once");
+ // The target changed after the proposal: stale, nothing written
+ let p = ok(&e, &token, "workflow_propose", json!({"target": "max_attempts", "task_id": tid, "after": 5, "reason": "flaky"})).await;
+ e.state.db.exec_raw_for_test(&format!("UPDATE tasks SET max_attempts = 4 WHERE id = '{tid}'")).await.unwrap();
+ let c = person(&e, "POST", &format!("/api/workflow-changes/{}/approve", id(&p)), None).await;
+ assert_eq!(c["status"], "stale", "{c}");
+ assert_eq!(e.state.db.get_task(&tid).await.unwrap().unwrap().max_attempts, 4);
+ // A rejected one is never applied
+ let p = ok(&e, &token, "workflow_propose", json!({"target": "max_attempts", "task_id": tid, "after": 6, "reason": "flaky"})).await;
+ let c = person(&e, "POST", &format!("/api/workflow-changes/{}/reject", id(&p)), None).await;
+ assert_eq!(c["status"], "rejected", "{c}");
+ assert_eq!(e.state.db.get_task(&tid).await.unwrap().unwrap().max_attempts, 4);
+}
+
+// 9
+#[tokio::test]
+async fn a_bad_check_spec_only_proposes_a_change() {
+ let e = setup().await;
+ autofix(&e, "on", 25).await;
+ let spec = json!({"command": "nosuchcmd_kwant_autofix"});
+ let tid = person_task(&e, json!([{"kind": "command", "spec": spec}])).await;
+ hand_in(&e, &tid).await;
+ let t = wait_state(&e, &tid, "failed").await;
+ assert_eq!(t["last_failure"]["class"], "bad_spec", "{t}");
+ let a = attempts(&e, &tid).await;
+ assert_eq!(a.len(), 1, "{a:?}");
+ assert_eq!((a[0].strategy.as_str(), a[0].status.as_str()), ("propose_change", "suggested"), "{a:?}");
+ let changes = person(&e, "GET", "/api/workflow-changes?status=proposed", None).await;
+ let changes = changes.as_array().unwrap();
+ assert_eq!(changes.len(), 1, "{changes:?}");
+ assert_eq!(changes[0]["target"], "check_spec");
+ assert_eq!(changes[0]["task_id"], tid.as_str());
+ assert_eq!(changes[0]["after"]["required"], false, "{changes:?}");
+ assert!(kinds(&t["needs_you"]).contains(&"workflow_change".to_string()), "{t}");
+ // Unchanged until approved, and AutoFix doesn't rerun a check that can't run
+ let checks = e.state.db.list_checks(&tid).await.unwrap();
+ assert_eq!((checks[0].spec_value(), checks[0].required), (spec.clone(), true));
+ let (status, v) = send(&e.app, "POST", &format!("/api/tasks/{tid}/autofix"), None, None).await;
+ assert_eq!((status, v["code"].as_str()), (StatusCode::CONFLICT, Some("not_retryable")), "{v}");
+ let c = person(&e, "POST", &format!("/api/workflow-changes/{}/approve", id(&changes[0])), None).await;
+ assert_eq!(c["status"], "applied", "{c}");
+ let checks = e.state.db.list_checks(&tid).await.unwrap();
+ assert_eq!((checks[0].spec_value(), checks[0].required), (spec, false));
+}
+
+// 10
+#[tokio::test]
+async fn diagnostics_are_redacted_and_their_path_never_reaches_the_api() {
+ let e = setup().await;
+ // Suggest: the failure stays put for the person to look at
+ autofix(&e, "suggest", 25).await;
+ // The secrets are only in the output, never in the spec
+ let cmd = "printf 'key sk-ant-%s%s\\n' api03abcdefghij 0123456789 >&2; printf 'GET https://bob:%s%[email protected]/x\\n' hunter2 secretpw >&2; exit 1";
+ let tid = person_task(&e, json!([{"kind": "command", "spec": {"command": cmd}}])).await;
+ hand_in(&e, &tid).await;
+ wait_state(&e, &tid, "failed").await;
+ let fs = failures(&e, &tid).await;
+ assert_eq!(fs.len(), 1, "{fs:?}");
+ let excerpt = fs[0]["excerpt"].as_str().unwrap();
+ assert!(excerpt.contains("exit code 1"), "{excerpt}");
+ for secret in ["api03abcdefghij0123456789", "hunter2secretpw"] {
+ assert!(!excerpt.contains(secret), "{excerpt}");
+ }
+ // The full diagnostics are on disk only, redacted, 0600 in a 0700 folder
+ let dir = e.state.config.data_dir.join("autofix").join(&tid);
+ assert_eq!(std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700);
+ let files: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|f| f.unwrap().path()).collect();
+ assert_eq!(files.len(), 1, "{files:?}");
+ assert_eq!(std::fs::metadata(&files[0]).unwrap().permissions().mode() & 0o777, 0o600);
+ let body = std::fs::read_to_string(&files[0]).unwrap();
+ assert!(body.contains("exit code 1") && !body.contains("api03abcdefghij0123456789") && !body.contains("hunter2secretpw"), "{body}");
+ // No API response carries the path
+ let root = e.state.config.data_dir.join("autofix").to_string_lossy().into_owned();
+ let mut seen = Vec::new();
+ for uri in [format!("/api/tasks/{tid}"), format!("/api/tasks/{tid}/failures"), "/api/tasks".into(), "/api/missions/insights".into()] {
+ let (_, v) = send(&e.app, "GET", &uri, None, None).await;
+ seen.push(v.to_string());
+ }
+ let r = person(&e, "POST", &format!("/api/tasks/{tid}/autofix"), None).await;
+ seen.push(r.to_string());
+ for s in &seen {
+ assert!(!s.contains("diagnostics_path") && !s.contains(&root), "{s}");
+ assert!(!s.contains("hunter2secretpw"), "{s}");
+ }
+ let note = kwnt::server::missions::autofix::retry_note(&e.state, &e.state.db.get_task(&tid).await.unwrap().unwrap()).await.unwrap();
+ assert!(!note.contains("api03abcdefghij0123456789") && !note.contains("hunter2secretpw"), "{note}");
+}