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
AutoFix: kwant's own auth texts, network errors are transient, budget card, masked check specs, idempotent run
Lin (kwant bot)61565e4caefe
diff --git a/docs/mission-control.md b/docs/mission-control.mdindex 2a704226..cfc11465 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -441,7 +441,7 @@ it is listed as "not undone".- `POST /api/tasks/:id/checkpoints/:cid/restore` (person only, `Idempotency-Key` required): body `{preview_sha256, force_paths?: [path], rerun?: bool}`. Returns `{restored, deleted, failed: [{path, why}], before_restore_checkpoint_id, external_not_undone, not_undone_note, effects_known, task}`.- 409 `fork_instead` for a verified task, `running` while a claim is live, `stale_preview` when the folder or task changed since the preview.- The task moves review/failed → ready and blocked → backlog; other states stay. A `restored` task event records the counts.- - A restore never re-runs a task by itself (D10). When the task ends up ready or backlog it is held (`held_at` set, `held` task event): neither the runner nor a bot's `task_claim` takes it until the person calls `POST /api/tasks/:id/run` (person only; 409 `not_held` when it isn't held; `released` task event). `rerun: true` ("restore and run again") leaves it unheld, or lets go of an earlier hold.+ - A restore never re-runs a task by itself (D10). When the task ends up ready or backlog it is held (`held_at` set, `held` task event): neither the runner nor a bot's `task_claim` takes it until the person calls `POST /api/tasks/:id/run` (person only; `Idempotency-Key` accepted, and the same key replays the first 200; 409 `not_held` when it isn't held; `released` task event). `rerun: true` ("restore and run again") leaves it unheld, or lets go of an earlier hold.- 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).@@ -461,16 +461,16 @@ acceptance, a routine) is only ever proposed; it applies when the person approve### 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.+- `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 (an `http` check whose connection was refused, dropped or timed out says "network error" by reqwest's error kind, not its wording), 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, and kwant's own "signed out or its key was rejected" / "No account can run bots" / no other account on), 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. A check's spec is masked the same way wherever it is shown (task JSON, Needs-you text, failure excerpt, retry prompt, workflow changes); the stored spec keeps the real values, and a `workflow_propose` whose spec still holds `[redacted]` is refused. 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.+- 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; a skip for `over_recovery_budget` also gives the failed task a `fix_needed` Needs-you item ("Retry budget used up: raise it or retry by hand.").- 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.+- 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. Token budgets (the task's and the recovery budget) count fresh input, cache writes and output, as Phase A spend does; cached input that is read again (`cache_read`) is left out. `model_usage.cost_usd` is the real-money figure.- 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.@@ -485,7 +485,7 @@ acceptance, a routine) is only ever proposed; it applies when the person approve- `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`.+- `GET /api/workflow-changes?status=&task_id=` (both filters optional), `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` and `autofix_attempts` (retries AutoFix started: running, succeeded or failed). Needs-you kinds: `autofix_suggested`, `fix_needed`, `workflow_change`.- Insights gain `autofix_7d: {attempts, succeeded, tokens}` and `failures_by_class_7d`, for the space.- Task events: `failure`, `autofix_scheduled`, `autofix_started`, `autofix_finished`, `workflow_change_proposed`, `workflow_change_decided`, `workflow_change_applied`.diff --git a/frontend/src/missions.ts b/frontend/src/missions.tsindex de6985c2..1fb434a5 100644--- a/frontend/src/missions.ts+++ b/frontend/src/missions.ts@@ -116,6 +116,8 @@ export interface Task {recovery_budget_tokens?: number;last_failure?: { class: FailureClass; summary: string; created_at: string } | null;autofix?: AutofixAttempt | null;+ /** Retries AutoFix started for this task (running, succeeded or failed). */+ autofix_attempts?: number;}// AutoFix (Phase B3, docs/mission-control.md §13)@@ -164,7 +166,7 @@ export interface AutofixError {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). */+/** GET /api/workflow-changes?status=…&task_id=… (person only; both filters optional). */export interface WorkflowChange {id: string;task_id: string | null;diff --git a/src/server/missions/autofix.rs b/src/server/missions/autofix.rsindex c1159ab0..60ff42df 100644--- a/src/server/missions/autofix.rs+++ b/src/server/missions/autofix.rs@@ -58,7 +58,7 @@ pub fn settings_error(mode: Option<&str>, pct: Option<i64>) -> Option<String> {// Classification-const AUTH: [&str; 12] = [+const AUTH: [&str; 17] = ["not logged in","not signed in","/login",@@ -71,6 +71,12 @@ const AUTH: [&str; 12] = ["token has expired","login has expired","credit balance is too low",+ // kwant's own messages when no account can take the turn (profile_turn.rs, drivers/engines.rs)+ "signed out",+ "key was rejected",+ "no account can run bots",+ "no other account is on",+ "no custom api account is on",];const TRANSIENT: [&str; 18] = [@@ -146,6 +152,9 @@ fn strategy_for(class: &str) -> &'static str {}}+/// What the person must do when AutoFix stopped short of the retry budget.+pub const RECOVERY_BUDGET_FIX: &str = "Retry budget used up: raise it or retry by hand.";+/// What the person must do for a failure AutoFix never retries.fn fix_text(class: &str, summary: &str) -> Option<String> {match class {@@ -158,33 +167,45 @@ fn fix_text(class: &str, summary: &str) -> Option<String> {// Redaction-/// Masks anything that looks like a key, token or password, line by line.+/// Masks anything that looks like a key, token or password, line by line. Words are runs of+/// key-like characters, so a key inside quotes, JSON or after a `:` is found too.pub fn redact(text: &str) -> String {+ let word = |c: char| c.is_ascii_alphanumeric() || "-_.=/+".contains(c);text.lines().map(|line| {let line = crate::profiles::classify::mask_credentials(line);- line.split(' ')- .map(|w| {- let bare = w.trim_matches(|c: char| "\"'`,;()[]{}<>".contains(c));- let looks_secret = bare.len() >= 20- && bare.chars().all(|c| c.is_ascii_alphanumeric() || "-_.=/+".contains(c))- && bare.chars().any(|c| c.is_ascii_digit())- && !bare.starts_with("http")- && !bare.starts_with('/');- let prefixed = ["sk-", "xai-", "sess-", "ghp_", "gho_", "github_pat_", "xox", "AKIA"].iter().any(|p| bare.starts_with(p)) && bare.len() > 8;- if looks_secret || prefixed {- w.replace(bare, "[redacted]")- } else {- w.to_string()- }- })- .collect::<Vec<_>>()- .join(" ")+ let mut out = String::with_capacity(line.len());+ let mut rest = line.as_str();+ while let Some(start) = rest.find(word) {+ out.push_str(&rest[..start]);+ let tail = &rest[start..];+ let end = tail.find(|c: char| !word(c)).unwrap_or(tail.len());+ let w = &tail[..end];+ let looks_secret = w.len() >= 20+ && w.chars().any(|c| c.is_ascii_digit())+ && !w.starts_with('/')+ && !w.starts_with("http");+ let prefixed = ["sk-", "xai-", "sess-", "ghp_", "gho_", "github_pat_", "xox", "AKIA"].iter().any(|p| w.starts_with(p)) && w.len() > 8;+ out.push_str(if looks_secret || prefixed { "[redacted]" } else { w });+ rest = &tail[end..];+ }+ out.push_str(rest);+ out}).collect::<Vec<_>>().join("\n")}+/// [`redact`] over every string in `v` (a check's spec, a change's before/after).+pub fn redact_value(v: &Value) -> Value {+ match v {+ Value::String(s) => Value::String(redact(s)),+ Value::Array(a) => Value::Array(a.iter().map(redact_value).collect()),+ Value::Object(o) => Value::Object(o.iter().map(|(k, v)| (k.clone(), redact_value(v))).collect()),+ other => other.clone(),+ }+}+fn cut(text: &str, max: usize) -> String {if text.chars().count() <= max {return text.to_string();@@ -558,7 +579,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, redact(&c.spec_value().to_string())));+ out.push_str(&format!("The check that failed: {} {}\n", c.kind, redact_value(&c.spec_value())));}if let Some(x) = &failure.excerpt {out.push_str(&format!("Its output (secrets masked):\n{x}\n"));@@ -617,6 +638,9 @@ pub async fn extend_task_json(state: &AppState, task: &Task, obj: &mut serde_jso);let current = state.db.current_attempt(&task.id).await.ok().flatten();obj.insert("autofix".into(), current.as_ref().map_or(Value::Null, attempt_json));+ // Retries AutoFix actually started (planned, suggested or skipped ones don't count)+ let ran = state.db.attempts_of(&task.id).await.unwrap_or_default().iter().filter(|a| matches!(a.status.as_str(), "running" | "succeeded" | "failed")).count();+ obj.insert("autofix_attempts".into(), json!(ran));}/// AutoFix's Needs-you items, for a task that isn't running: a suggested retry, a proposed@@ -639,8 +663,14 @@ pub async fn needs_you(state: &AppState, task: &Task) -> Vec<Value> {items.push(json!({"kind": "autofix_suggested", "id": a.id, "text": cut(&text, 200)}));}if let Some(f) = last {+ let over_budget = || async {+ let attempts = state.db.attempts_of(&task.id).await.unwrap_or_default();+ attempts.iter().rev().find(|a| a.failure_id == f.id).is_some_and(|a| a.status == "skipped" && a.reason.starts_with("over_recovery_budget"))+ };if let Some(text) = fix_text(&f.class, &f.summary) {items.push(json!({"kind": "fix_needed", "id": f.id, "text": cut(&text, 200)}));+ } else if task.state == "failed" && over_budget().await {+ items.push(json!({"kind": "fix_needed", "id": f.id, "text": RECOVERY_BUDGET_FIX}));}}}@@ -797,8 +827,8 @@ async fn change_json(state: &AppState, c: &WorkflowChange) -> Value {"task_id": c.task_id,"routine_id": c.routine_id,"target": c.target,- "before": parse(&c.before),- "after": parse(&c.after),+ "before": redact_value(&parse(&c.before)),+ "after": redact_value(&parse(&c.after)),"reason": c.reason,"proposed_by": c.proposed_by,"proposed_by_name": super::name_of(state, Some(&c.proposed_by)).await,@@ -808,13 +838,15 @@ async fn change_json(state: &AppState, c: &WorkflowChange) -> Value {})}-/// `GET /api/workflow-changes?status=proposed` (person-only).+/// `GET /api/workflow-changes?status=proposed&task_id=…` (person-only; both filters optional).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);+ let param = |name: &str| q.as_deref().unwrap_or("").split('&').find_map(|p| p.strip_prefix(name)).map(str::to_string);+ let status = param("status=");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})"));}- match state.db.list_changes(status.as_deref(), None).await {+ let task_id = param("task_id=").filter(|t| !t.is_empty());+ match state.db.list_changes(status.as_deref(), task_id.as_deref()).await {Ok(list) => {let mut out = Vec::new();for c in &list {@@ -958,6 +990,9 @@ pub async fn propose(state: &AppState, bot_id: &str, args: &Value) -> Result<Vallet cid = after["check_id"].as_str().ok_or("after.check_id is required")?;let c = state.db.get_check(cid).await.map_err(|e| e.to_string())?.filter(|c| c.task_id == t.id).ok_or("no such check on this task")?;let spec = after.get("spec").cloned().unwrap_or_else(|| c.spec_value());+ if spec.to_string().contains("[redacted]") {+ return Err("after.spec has masked values ([redacted]); ask the person for the real ones".into());+ }super::validate_check(&c.kind, &spec, true)?;let required = after["required"].as_bool().unwrap_or(c.required);(None, json!({"check_id": c.id, "kind": c.kind, "spec": c.spec_value(), "required": c.required}), json!({"check_id": c.id, "kind": c.kind, "spec": spec, "required": required}))@@ -986,3 +1021,77 @@ pub async fn insights(state: &AppState, space_id: &str, since: DateTime<Utc>) ->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))}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn kwants_own_no_account_messages_are_auth() {+ use crate::db::models::LlmProfile;+ use crate::profiles::classify::{FailClass, ProviderFailure};+ use crate::server::profile_turn::{give_up_notice, switch_notice};+ let p = |name: &str| LlmProfile {+ id: name.into(),+ engine: "claude".into(),+ name: name.into(),+ kind: "subscription".into(),+ home_dir: None,+ priority: 0,+ enabled: true,+ is_default: true,+ created_at: None,+ space_id: "spc_default".into(),+ };+ let auth = ProviderFailure { class: FailClass::Auth, retry_at: None, detail: "401".into() };+ // The exact texts a turn ends with, built by the code that writes them: a rewording breaks this+ let texts = [+ give_up_notice("Ann", &p("This machine"), &auth, 1),+ give_up_notice("Ann", &p("Work"), &auth, 2),+ switch_notice(&p("Work"), &p("Personal"), &auth),+ crate::drivers::engines::no_engine_notice("Ann", false).0,+ crate::drivers::engines::no_engine_notice("Ann", true).0,+ crate::drivers::engines::NO_CUSTOM_ACCOUNT.to_string(),+ ];+ for t in &texts {+ assert_eq!(classify("turn", "error", t), "auth", "{t}");+ assert_eq!(strategy_for(classify("turn", "error", t)), "none", "{t}");+ }+ // The give-up text has no "401" of its own: the words alone must carry it+ assert!(!texts[0].contains("401"), "{}", texts[0]);+ }++ #[tokio::test]+ async fn an_http_check_on_a_closed_port_is_transient_and_waits() {+ let port = {+ let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ l.local_addr().unwrap().port()+ };+ let spec = json!({"url": format!("http://127.0.0.1:{port}/health")});+ let (status, out) = super::super::checks::run_spec("http", &spec, None, true).await;+ assert_eq!(status, "error", "{out}");+ assert!(out.contains("network error"), "{out}");+ assert_eq!(classify("check", &status, &out), "transient", "{out}");+ assert_eq!(strategy_for("transient"), "wait_and_retry");+ // The text fallback still holds for words the engines print+ assert_eq!(classify("check", "error", "connection refused"), "transient");+ }++ #[test]+ fn a_bare_key_inside_a_spec_is_masked() {+ // Glued to other characters, as typed into a command: no space on either side of the key+ let spec = json!({"command": "test \"$(cat t)\" = \"Zq8VwK3mT9pL2rX7nB4c\">/dev/null && curl https://example.com/v1/items", "timeout_secs": 30});+ let out = redact_value(&spec);+ let s = out.to_string();+ assert!(!s.contains("Zq8VwK3mT9pL2rX7nB4c"), "{s}");+ assert!(s.contains("= \\\"[redacted]\\\">/dev/null"), "{s}");+ assert!(s.contains("https://example.com/v1/items"), "{s}");+ // As text (the failure excerpt) too+ assert!(!redact(&spec.to_string()).contains("Zq8VwK3mT9pL2rX7nB4c"));+ assert_eq!(out["timeout_secs"], 30);+ // Quotes and brackets around a key are kept as they were+ assert_eq!(redact("key [sk-ant-api03abcdef]"), "key [[redacted]]");+ assert_eq!(redact("'ghp_abcdefghij0123456789'"), "'[redacted]'");+ assert_eq!(redact("exit code 1\nexpected 42 got 41"), "exit code 1\nexpected 42 got 41");+ }+}diff --git a/src/server/missions/checkpoints.rs b/src/server/missions/checkpoints.rsindex a381c68b..62e6d6b7 100644--- a/src/server/missions/checkpoints.rs+++ b/src/server/missions/checkpoints.rs@@ -1098,22 +1098,24 @@ pub async fn restore(.await}-/// `POST /api/tasks/:id/run` (person-only): lets a task a restore held be claimed again (D10).-pub async fn run_held(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {- let task = match load_task(&state, q.as_deref(), &id).await {- Ok(t) => t,- Err(r) => return r,- };- match state.db.set_task_hold(&task.id, false).await {- Ok(true) => {- let _ = state.db.task_event(&task.id, task.mission_id.as_deref(), "released", "person", &json!({})).await;+/// `POST /api/tasks/:id/run` (person-only; `Idempotency-Key` optional): lets a task a restore+/// held be claimed again (D10). The same key again replays the first 200 instead of `not_held`.+pub async fn run_held(State(state): State<AppState>, RawQuery(q): RawQuery, headers: HeaderMap, Path(id): Path<String>) -> Response {+ let route = format!("POST /api/tasks/{id}/run");+ super::graph::idempotent(&state, &headers, route, || async {+ let task = load_task(&state, q.as_deref(), &id).await?;+ match state.db.set_task_hold(&task.id, false).await {+ Ok(true) => {+ let _ = state.db.task_event(&task.id, task.mission_id.as_deref(), "released", "person", &json!({})).await;+ }+ Ok(false) => return Err(coded(StatusCode::CONFLICT, "not_held", "the task isn't on hold")),+ Err(e) => return Err(internal(e)),}- Ok(false) => return coded(StatusCode::CONFLICT, "not_held", "the task isn't on hold"),- Err(e) => return internal(e),- }- let t = state.db.get_task(&task.id).await.ok().flatten().unwrap_or(task);- emit_task(&state, &t).await;- Json(json!({"task": task_json(&state, &t).await})).into_response()+ let t = state.db.get_task(&task.id).await.ok().flatten().unwrap_or(task);+ emit_task(&state, &t).await;+ Ok(json!({"task": task_json(&state, &t).await}))+ })+ .await}/// Fork `from_checkpoint` (B1 `POST /api/tasks/:id/fork`): writes the original's task-owneddiff --git a/src/server/missions/checks.rs b/src/server/missions/checks.rsindex 3cb6afb8..be9d573e 100644--- a/src/server/missions/checks.rs+++ b/src/server/missions/checks.rs@@ -122,7 +122,7 @@ async fn http(url: &str, spec: &Value, person_ok: bool) -> Result<(bool, String).redirect(reqwest::redirect::Policy::none()).build().map_err(|e| e.to_string())?;- let resp = client.get(url).send().await.map_err(|e| format!("GET {url} failed: {e}"))?;+ let resp = client.get(url).send().await.map_err(|e| send_error(url, &e))?;let status = resp.status().as_u16();let ok_status = match spec["expect_status"].as_u64() {Some(want) => u64::from(status) == want,@@ -146,6 +146,19 @@ async fn http(url: &str, spec: &Value, person_ok: bool) -> Result<(bool, String)Ok((ok_status && has, out))}+/// Why a GET didn't get a response. A refused or dropped connection and a timeout say so in+/// words AutoFix classes as temporary; reqwest's own text ("error sending request") doesn't.+fn send_error(url: &str, e: &reqwest::Error) -> String {+ let why = if e.is_timeout() {+ "timed out"+ } else if e.is_connect() {+ "connection refused or unreachable"+ } else {+ return format!("GET {url} failed: {e}");+ };+ format!("GET {url} failed: network error, {why} ({e})")+}+async fn file(kind: &str, rel: &str, spec: &Value, dir: &Path) -> Result<(bool, String), String> {let path = inside(dir, rel)?;let meta = tokio::fs::metadata(&path).await;diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rsindex ac39b760..c37c9923 100644--- a/src/server/missions/mod.rs+++ b/src/server/missions/mod.rs@@ -348,7 +348,7 @@ pub async fn evaluate(state: &AppState, task_id: &str) -> Option<Task> {if moved.is_some() {let bad = checks.iter().filter(|c| matches!(c.status.as_str(), "failed" | "error")).find(|c| c.required).or_else(|| checks.iter().find(|c| matches!(c.status.as_str(), "failed" | "error")));if let Some(c) = bad {- let text = format!("{} {}\n{}", c.kind, c.spec_value(), c.output_excerpt.as_deref().unwrap_or(""));+ let text = format!("{} {}\n{}", c.kind, autofix::redact_value(&c.spec_value()), c.output_excerpt.as_deref().unwrap_or(""));autofix::record(state, task_id, "check", &c.status, &text, &why).await;}}@@ -522,7 +522,7 @@ pub async fn check_approvals(state: &AppState, task: &Task) -> Vec<Value> {.iter().filter(|c| c.required && !c.approved).map(|c| {- let text = format!("Allow this check: {} {}", c.kind, c.spec_value());+ let text = format!("Allow this check: {} {}", c.kind, autofix::redact_value(&c.spec_value()));json!({"kind": "check_approval", "id": c.id, "text": text.chars().take(200).collect::<String>()})}).collect()@@ -582,7 +582,8 @@ pub async fn mission_json(state: &AppState, m: &Mission) -> Value {pub fn check_json(task: &Task, c: &OutcomeCheck, checked_by_name: Option<String>) -> Value {let mut v = serde_json::to_value(c).unwrap_or(Value::Null);if let Some(obj) = v.as_object_mut() {- obj.insert("spec".into(), c.spec_value());+ // The spec reaches the API and bots: a key typed into it is masked like check output+ obj.insert("spec".into(), autofix::redact_value(&c.spec_value()));obj.insert("checked_by_name".into(), json!(checked_by_name));obj.insert("counts".into(), json!(counts(task, c)));}diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rsindex d40a2b89..2b1da25c 100644--- a/src/server/missions/runner.rs+++ b/src/server/missions/runner.rs@@ -136,7 +136,7 @@ async fn prompt(state: &AppState, m: &Mission, t: &Task) -> String {let list: Vec<String> = checks.iter().filter(|c| c.approved)- .map(|c| format!("- {} {}{}", c.kind, c.spec_value(), if c.required { "" } else { " (optional)" }))+ .map(|c| format!("- {} {}{}", c.kind, super::autofix::redact_value(&c.spec_value()), if c.required { "" } else { " (optional)" })).collect();let deps = state.db.dependencies_of(&t.id).await.unwrap_or_default();format!(diff --git a/src/server/missions/tools.rs b/src/server/missions/tools.rsindex 758fbd34..9f523c44 100644--- a/src/server/missions/tools.rs+++ b/src/server/missions/tools.rs@@ -292,7 +292,7 @@ async fn claim(state: &AppState, scope: &SelfScope, task: &Task) -> ToolResult {let mut out = json!({"task": brief(&t),"lease_minutes": lease / 60_000,- "checks": checks.iter().map(|c| json!({"id": c.id, "kind": c.kind, "spec": c.spec_value(), "approved": c.approved})).collect::<Vec<_>>(),+ "checks": checks.iter().map(|c| json!({"id": c.id, "kind": c.kind, "spec": super::autofix::redact_value(&c.spec_value()), "approved": c.approved})).collect::<Vec<_>>(),"next": "Do the work, attach evidence with task_attach_evidence, then task_update status=review.",});if let Some(note) = super::autofix::retry_note(state, &t).await {diff --git a/tests/mission_autofix_test.rs b/tests/mission_autofix_test.rsindex b6ddcd0a..d4da0557 100644--- a/tests/mission_autofix_test.rs+++ b/tests/mission_autofix_test.rs@@ -99,6 +99,8 @@ struct Env {/// kwant on a real port (the stand-in CLI calls back), with the mission board on.async fn setup() -> Env {+ // The CLI lookup is cached per process: put the stand-in first before any test can resolve `claude`+ fake_cli();let tmp = tempdir().unwrap();let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let port = listener.local_addr().unwrap().port();@@ -343,6 +345,7 @@ async fn a_failing_check_is_retried_with_its_diagnostics_until_the_attempts_run_"{a:?}");assert!(a[2].reason.starts_with("no_attempts_left"), "{a:?}");+ assert_eq!(t["autofix_attempts"], 2, "two retries ran; the skipped one doesn't count: {t}");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}");@@ -433,6 +436,10 @@ async fn a_retry_over_the_recovery_budget_is_skipped_and_only_autofix_turns_counassert!(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}");+ // The person is told, not just shown a failed task+ let fix: Vec<&Value> = t["needs_you"].as_array().unwrap().iter().filter(|i| i["kind"] == "fix_needed").collect();+ assert_eq!(fix.len(), 1, "{t}");+ assert_eq!(fix[0]["text"], kwnt::server::missions::autofix::RECOVERY_BUDGET_FIX, "{t}");// At 10% the person can't push one through eitherautofix(&e, "on", 10).await;let (status, v) = send(&e.app, "POST", &format!("/api/tasks/{tid}/autofix"), None, None).await;@@ -641,6 +648,11 @@ async fn a_bad_check_spec_only_proposes_a_change() {assert_eq!(changes[0]["target"], "check_spec");assert_eq!(changes[0]["task_id"], tid.as_str());assert_eq!(changes[0]["after"]["required"], false, "{changes:?}");+ // The board asks for one task's changes only+ let mine = person(&e, "GET", &format!("/api/workflow-changes?status=proposed&task_id={tid}"), None).await;+ assert_eq!(mine.as_array().unwrap().len(), 1, "{mine}");+ let other = person(&e, "GET", "/api/workflow-changes?task_id=no-such-task", None).await;+ assert_eq!(other.as_array().unwrap().len(), 0, "{other}");assert!(kinds(&t["needs_you"]).contains(&"workflow_change".to_string()), "{t}");// Unchanged until approved, and AutoFix doesn't rerun a check that can't runlet checks = e.state.db.list_checks(&tid).await.unwrap();@@ -695,3 +707,80 @@ async fn diagnostics_are_redacted_and_their_path_never_reaches_the_api() {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}");}++// Eval 9 follow-ups++#[tokio::test]+async fn a_key_typed_into_a_check_spec_is_masked_wherever_the_spec_is_shown() {+ let e = setup().await;+ autofix(&e, "suggest", 25).await;+ let secret = "Zq8VwK3mT9pL2rX7nB4c";+ // The key is glued to quotes and a redirect, as people type it; the output never prints it+ let cmd = format!("test \"$(echo nope)\" = \"{secret}\">/dev/null; echo checked; 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;+ // It still ran with the real value: the stored spec is untouched+ let checks = e.state.db.list_checks(&tid).await.unwrap();+ assert!(checks[0].spec_value()["command"].as_str().unwrap().contains(secret));+ let mut seen = Vec::new();+ for uri in [format!("/api/tasks/{tid}"), format!("/api/tasks/{tid}/failures"), "/api/tasks".into()] {+ let (status, v) = send(&e.app, "GET", &uri, None, None).await;+ if status == StatusCode::OK {+ seen.push((uri, v.to_string()));+ }+ }+ assert_eq!(seen.len(), 3, "{seen:?}");+ let t = person(&e, "GET", &format!("/api/tasks/{tid}"), None).await;+ assert!(t["checks"][0]["spec"]["command"].as_str().unwrap().contains("[redacted]"), "{t}");+ for (uri, body) in &seen {+ assert!(!body.contains(secret), "{uri}: {body}");+ }+ for ev in e.state.db.task_events(&tid, 500).await.unwrap() {+ assert!(!ev.detail.contains(secret), "{ev:?}");+ }+ let dir = e.state.config.data_dir.join("autofix").join(&tid);+ for f in std::fs::read_dir(&dir).unwrap() {+ let body = std::fs::read_to_string(f.unwrap().path()).unwrap();+ assert!(body.contains("checked") && !body.contains(secret), "{body}");+ }+ let note = kwnt::server::missions::autofix::retry_note(&e.state, &e.state.db.get_task(&tid).await.unwrap().unwrap()).await;+ assert!(note.is_none_or(|n| !n.contains(secret)));+ // A bot can't copy the masked spec back as a "change"+ let token = turn(&e, &e.bot, &format!("t-{}", uuid::Uuid::new_v4())).await;+ let args = json!({"target": "check_spec", "task_id": tid, "reason": "fix it",+ "after": {"check_id": checks[0].id, "spec": t["checks"][0]["spec"].clone()}});+ let (status, v) = send(&e.app, "POST", "/api/mcp/self", Some(&token), Some(json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "workflow_propose", "arguments": args}}))).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ assert!(v.to_string().contains("masked values"), "{v}");+}++#[tokio::test]+async fn running_a_held_task_twice_with_one_key_replays_the_first_200() {+ let e = setup().await;+ let tid = person_task(&e, json!([])).await;+ assert!(e.state.db.set_task_hold(&tid, true).await.unwrap());+ let run = |key: Option<&'static str>| {+ let mut req = Request::builder().method("POST").uri(format!("/api/tasks/{tid}/run")).header("content-type", "application/json");+ if let Some(k) = key {+ req = req.header("idempotency-key", k);+ }+ e.app.clone().oneshot(req.body(Body::from("{}")).unwrap())+ };+ let first = run(Some("run-1")).await.unwrap();+ assert_eq!(first.status(), StatusCode::OK);+ let first: Value = serde_json::from_slice(&to_bytes(first.into_body(), usize::MAX).await.unwrap()).unwrap();+ assert!(first["task"]["held_at"].is_null(), "{first}");+ let again = run(Some("run-1")).await.unwrap();+ assert_eq!(again.status(), StatusCode::OK);+ assert_eq!(again.headers().get("idempotent-replayed").map(|v| v.to_str().unwrap()), Some("true"));+ let again: Value = serde_json::from_slice(&to_bytes(again.into_body(), usize::MAX).await.unwrap()).unwrap();+ assert_eq!(again, first);+ // A new key (or none) on a task that isn't held is still a 409+ for key in [Some("run-2"), None] {+ let r = run(key).await.unwrap();+ assert_eq!(r.status(), StatusCode::CONFLICT, "{key:?}");+ }+ let released = e.state.db.task_events(&tid, 500).await.unwrap().iter().filter(|ev| ev.kind == "released").count();+ assert_eq!(released, 1);+}