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.

Mission Control B3: AutoFix (failures, classify, strategies, recovery budget, workflow changes)

Lin (kwant bot)72c6b9a06b47
diff --git a/src/db/autofix.rs b/src/db/autofix.rs
new file mode 100644
index 00000000..1ea72cab
--- /dev/null
+++ b/src/db/autofix.rs
@@ -0,0 +1,603 @@
+//! Mission Control Phase B3: AutoFix's bookkeeping. Every failure of a task (`task_failures`,
+//! append-only), the retries AutoFix plans or runs for it (`autofix_attempts`, one per failure and
+//! 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.
+
+use super::missions::{insert_event, Task};
+use super::{Database, DbError};
+use chrono::{DateTime, Utc};
+use serde::Serialize;
+use serde_json::Value;
+use sqlx::FromRow;
+use uuid::Uuid;
+
+pub const SOURCES: [&str; 6] = ["check", "turn", "lease", "budget", "routine", "handoff"];
+pub const CLASSES: [&str; 9] = ["transient", "stalled", "check_failed", "auth", "budget", "denied", "bad_spec", "needs_input", "unknown"];
+pub const STRATEGIES: [&str; 6] = ["retry_same", "retry_with_diagnostics", "retry_from_checkpoint", "wait_and_retry", "propose_change", "none"];
+pub const TARGETS: [&str; 5] = ["routine_instructions", "routine_schedule", "check_spec", "task_acceptance", "max_attempts"];
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct Failure {
+ pub id: String,
+ pub task_id: String,
+ pub attempt: i64,
+ pub source: String,
+ pub class: String,
+ pub summary: String,
+ pub excerpt: Option<String>,
+ /// Server-only.
+ #[serde(skip)]
+ pub diagnostics_path: Option<String>,
+ pub checkpoint_id: Option<String>,
+ pub created_at: DateTime<Utc>,
+}
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct Attempt {
+ pub id: String,
+ pub task_id: String,
+ pub failure_id: String,
+ pub strategy: String,
+ #[serde(skip)]
+ pub idempotency_key: String,
+ pub status: String,
+ pub not_before: Option<DateTime<Utc>>,
+ pub reason: String,
+ pub retry_task_id: Option<String>,
+ pub tokens_spent: i64,
+ pub created_at: DateTime<Utc>,
+ pub finished_at: Option<DateTime<Utc>>,
+}
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct WorkflowChange {
+ pub id: String,
+ pub task_id: Option<String>,
+ pub routine_id: Option<String>,
+ pub target: String,
+ pub before: String,
+ pub after: String,
+ pub reason: String,
+ pub proposed_by: String,
+ pub status: String,
+ pub decided_by: Option<String>,
+ pub decided_at: Option<DateTime<Utc>>,
+ pub created_at: DateTime<Utc>,
+}
+
+pub struct NewFailure<'a> {
+ pub task: &'a Task,
+ pub source: &'a str,
+ pub class: &'a str,
+ pub summary: String,
+ pub excerpt: Option<String>,
+ pub diagnostics_path: Option<String>,
+ pub checkpoint_id: Option<String>,
+}
+
+pub struct NewAttempt<'a> {
+ pub task: &'a Task,
+ pub failure_id: &'a str,
+ pub strategy: &'a str,
+ pub idempotency_key: String,
+ pub status: &'a str,
+ pub not_before: Option<DateTime<Utc>>,
+ pub reason: String,
+}
+
+const TRIGGERS: [&str; 6] = [
+ "CREATE TRIGGER IF NOT EXISTS task_failures_no_update BEFORE UPDATE ON task_failures \
+ BEGIN SELECT RAISE(ABORT, 'task_failures is append-only'); END",
+ "CREATE TRIGGER IF NOT EXISTS task_failures_no_delete BEFORE DELETE ON task_failures \
+ BEGIN SELECT RAISE(ABORT, 'task_failures is append-only'); END",
+ // AutoFix runs are attempts: none is scheduled or started past the task's max_attempts
+ "CREATE TRIGGER IF NOT EXISTS autofix_within_attempts BEFORE INSERT ON autofix_attempts \
+ WHEN NEW.status IN ('scheduled', 'running') \
+ AND (SELECT attempts >= max_attempts FROM tasks WHERE id = NEW.task_id) \
+ BEGIN SELECT RAISE(ABORT, 'autofix runs only within the task''s attempts'); END",
+ "CREATE TRIGGER IF NOT EXISTS autofix_within_attempts_update BEFORE UPDATE OF status ON autofix_attempts \
+ WHEN NEW.status = 'running' AND OLD.status != 'running' \
+ AND (SELECT attempts >= max_attempts FROM tasks WHERE id = NEW.task_id) \
+ BEGIN SELECT RAISE(ABORT, 'autofix runs only within the task''s attempts'); END",
+ // A permanent change is decided by the person, and applied only after approval
+ "CREATE TRIGGER IF NOT EXISTS workflow_change_needs_person BEFORE UPDATE ON workflow_changes \
+ WHEN NEW.status IN ('approved', 'applied', 'rejected') AND COALESCE(NEW.decided_by, '') != 'person' \
+ BEGIN SELECT RAISE(ABORT, 'only the person decides a workflow change'); END",
+ "CREATE TRIGGER IF NOT EXISTS workflow_change_applied_after_approved BEFORE UPDATE ON workflow_changes \
+ WHEN NEW.status = 'applied' AND OLD.status != 'approved' \
+ BEGIN SELECT RAISE(ABORT, 'a workflow change is applied only after the person approves it'); END",
+];
+
+impl Database {
+ pub(super) async fn migrate_autofix(&self) -> Result<(), DbError> {
+ let has: Option<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info('tasks') WHERE name = 'recovery_spent_tokens'").fetch_optional(&self.pool).await?;
+ if has.is_none() {
+ sqlx::query("ALTER TABLE tasks ADD COLUMN recovery_spent_tokens INTEGER NOT NULL DEFAULT 0").execute(&self.pool).await?;
+ }
+ // The AutoFix attempt a claim was taken for: its turns' spend is recovery spend
+ let has: Option<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info('agent_claims') WHERE name = 'autofix_id'").fetch_optional(&self.pool).await?;
+ if has.is_none() {
+ sqlx::query("ALTER TABLE agent_claims ADD COLUMN autofix_id TEXT").execute(&self.pool).await?;
+ }
+ for stmt in [
+ "CREATE TABLE IF NOT EXISTS task_failures (
+ id TEXT PRIMARY KEY,
+ task_id TEXT NOT NULL REFERENCES tasks(id),
+ attempt INTEGER NOT NULL,
+ source TEXT NOT NULL CHECK (source IN ('check', 'turn', 'lease', 'budget', 'routine', 'handoff')),
+ class TEXT NOT NULL CHECK (class IN ('transient', 'stalled', 'check_failed', 'auth', 'budget', 'denied', 'bad_spec', 'needs_input', 'unknown')),
+ summary TEXT NOT NULL,
+ excerpt TEXT,
+ diagnostics_path TEXT,
+ checkpoint_id TEXT,
+ created_at TIMESTAMP NOT NULL
+ )",
+ "CREATE INDEX IF NOT EXISTS task_failures_task ON task_failures (task_id, created_at)",
+ "CREATE TABLE IF NOT EXISTS autofix_attempts (
+ id TEXT PRIMARY KEY,
+ task_id TEXT NOT NULL REFERENCES tasks(id),
+ failure_id TEXT NOT NULL REFERENCES task_failures(id),
+ strategy TEXT NOT NULL CHECK (strategy IN ('retry_same', 'retry_with_diagnostics', 'retry_from_checkpoint', 'wait_and_retry', 'propose_change', 'none')),
+ idempotency_key TEXT NOT NULL UNIQUE,
+ status TEXT NOT NULL CHECK (status IN ('suggested', 'scheduled', 'running', 'succeeded', 'failed', 'skipped')),
+ not_before TIMESTAMP,
+ reason TEXT NOT NULL,
+ retry_task_id TEXT,
+ tokens_spent INTEGER NOT NULL DEFAULT 0,
+ created_at TIMESTAMP NOT NULL,
+ finished_at TIMESTAMP
+ )",
+ "CREATE UNIQUE INDEX IF NOT EXISTS autofix_one_live ON autofix_attempts (task_id) WHERE status IN ('scheduled', 'running')",
+ "CREATE INDEX IF NOT EXISTS autofix_attempts_task ON autofix_attempts (task_id, created_at)",
+ "CREATE TABLE IF NOT EXISTS workflow_changes (
+ id TEXT PRIMARY KEY,
+ task_id TEXT REFERENCES tasks(id),
+ routine_id TEXT,
+ target TEXT NOT NULL CHECK (target IN ('routine_instructions', 'routine_schedule', 'check_spec', 'task_acceptance', 'max_attempts')),
+ before TEXT NOT NULL,
+ after TEXT NOT NULL,
+ reason TEXT NOT NULL,
+ proposed_by TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('proposed', 'approved', 'rejected', 'applied', 'stale')),
+ decided_by TEXT,
+ decided_at TIMESTAMP,
+ created_at TIMESTAMP NOT NULL
+ )",
+ "CREATE INDEX IF NOT EXISTS workflow_changes_status ON workflow_changes (status, created_at)",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ for t in TRIGGERS {
+ sqlx::query(t).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ /// Records a failure and logs a `failure` event, then finishes the task's running AutoFix
+ /// attempt (if any) as failed.
+ pub async fn insert_failure(&self, f: &NewFailure<'_>) -> Result<Failure, DbError> {
+ let id = Uuid::new_v4().to_string();
+ let now = Utc::now();
+ let mut tx = self.pool.begin().await?;
+ sqlx::query(
+ "INSERT INTO task_failures (id, task_id, attempt, source, class, summary, excerpt, diagnostics_path, checkpoint_id, created_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ )
+ .bind(&id)
+ .bind(&f.task.id)
+ .bind(f.task.attempts)
+ .bind(f.source)
+ .bind(f.class)
+ .bind(&f.summary)
+ .bind(&f.excerpt)
+ .bind(&f.diagnostics_path)
+ .bind(&f.checkpoint_id)
+ .bind(now)
+ .execute(&mut *tx)
+ .await?;
+ let detail = serde_json::json!({"failure_id": id, "source": f.source, "class": f.class, "summary": f.summary});
+ insert_event(&mut tx, &f.task.id, f.task.mission_id.as_deref(), "failure", "kwant", None, None, &detail).await?;
+ finish_running(&mut tx, &f.task.id, "failed", now).await?;
+ tx.commit().await?;
+ Ok(sqlx::query_as::<_, Failure>("SELECT * FROM task_failures WHERE id = ?").bind(&id).fetch_one(&self.pool).await?)
+ }
+
+ pub async fn failures_of(&self, task_id: &str) -> Result<Vec<Failure>, DbError> {
+ Ok(sqlx::query_as::<_, Failure>("SELECT * FROM task_failures WHERE task_id = ? ORDER BY created_at, rowid").bind(task_id).fetch_all(&self.pool).await?)
+ }
+
+ pub async fn get_failure(&self, id: &str) -> Result<Option<Failure>, DbError> {
+ Ok(sqlx::query_as::<_, Failure>("SELECT * FROM task_failures WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)
+ }
+
+ /// How many earlier failures of `class` the task had (before `failure_id`).
+ pub async fn count_failures(&self, task_id: &str, class: &str, failure_id: &str) -> Result<i64, DbError> {
+ let (n,): (i64,) = sqlx::query_as(
+ "SELECT COUNT(*) FROM task_failures WHERE task_id = ? AND class = ? AND id != ? \
+ AND rowid < (SELECT rowid FROM task_failures WHERE id = ?)",
+ )
+ .bind(task_id)
+ .bind(class)
+ .bind(failure_id)
+ .bind(failure_id)
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(n)
+ }
+
+ /// Plans an attempt once per key: `Ok(None)` when the key exists already (a repeated tick,
+ /// a restart or a duplicate event). A trigger or the one-live index refusing it is an error.
+ pub async fn insert_attempt(&self, a: &NewAttempt<'_>) -> Result<Option<Attempt>, DbError> {
+ 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ )
+ .bind(&id)
+ .bind(&a.task.id)
+ .bind(a.failure_id)
+ .bind(a.strategy)
+ .bind(&a.idempotency_key)
+ .bind(a.status)
+ .bind(a.not_before)
+ .bind(&a.reason)
+ .bind(Utc::now())
+ .bind(if matches!(a.status, "skipped") { Some(Utc::now()) } else { None })
+ .execute(&mut *tx)
+ .await?;
+ if r.rows_affected() == 0 {
+ return Ok(None);
+ }
+ let kind = if a.status == "skipped" { "autofix_finished" } else { "autofix_scheduled" };
+ let detail = serde_json::json!({"autofix_id": id, "failure_id": a.failure_id, "strategy": a.strategy, "status": a.status, "not_before": a.not_before, "reason": a.reason});
+ insert_event(&mut tx, &a.task.id, a.task.mission_id.as_deref(), kind, "kwant", None, None, &detail).await?;
+ tx.commit().await?;
+ self.get_attempt(&id).await
+ }
+
+ pub async fn get_attempt(&self, id: &str) -> Result<Option<Attempt>, DbError> {
+ Ok(sqlx::query_as::<_, Attempt>("SELECT * FROM autofix_attempts WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)
+ }
+
+ pub async fn attempts_of(&self, task_id: &str) -> Result<Vec<Attempt>, DbError> {
+ Ok(sqlx::query_as::<_, Attempt>("SELECT * FROM autofix_attempts WHERE task_id = ? ORDER BY created_at, rowid").bind(task_id).fetch_all(&self.pool).await?)
+ }
+
+ /// The live attempt of the task, else its most recent one.
+ pub async fn current_attempt(&self, task_id: &str) -> Result<Option<Attempt>, DbError> {
+ Ok(sqlx::query_as::<_, Attempt>(
+ "SELECT * FROM autofix_attempts WHERE task_id = ? \
+ ORDER BY CASE WHEN status IN ('scheduled', 'running') THEN 0 ELSE 1 END, created_at DESC, rowid DESC LIMIT 1",
+ )
+ .bind(task_id)
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ /// Scheduled attempts whose time has come.
+ pub async fn due_attempts(&self, now: DateTime<Utc>) -> Result<Vec<Attempt>, DbError> {
+ Ok(sqlx::query_as::<_, Attempt>(
+ "SELECT * FROM autofix_attempts WHERE status = 'scheduled' AND (not_before IS NULL OR not_before <= ?) ORDER BY created_at",
+ )
+ .bind(now)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Moves an attempt `from` → `to` (compare-and-set) and logs it. `Ok(false)` when it wasn't in
+ /// `from`.
+ pub async fn move_attempt(&self, a: &Attempt, from: &str, to: &str, reason: Option<&str>) -> Result<bool, DbError> {
+ let now = Utc::now();
+ let mut tx = self.pool.begin().await?;
+ let done = matches!(to, "succeeded" | "failed" | "skipped");
+ let r = sqlx::query(
+ "UPDATE autofix_attempts SET status = ?, reason = COALESCE(?, reason), finished_at = CASE WHEN ? THEN ? ELSE finished_at END \
+ WHERE id = ? AND status = ?",
+ )
+ .bind(to)
+ .bind(reason)
+ .bind(done)
+ .bind(now)
+ .bind(&a.id)
+ .bind(from)
+ .execute(&mut *tx)
+ .await?;
+ if r.rows_affected() != 1 {
+ return Ok(false);
+ }
+ let mission: Option<(Option<String>,)> = sqlx::query_as("SELECT mission_id FROM tasks WHERE id = ?").bind(&a.task_id).fetch_optional(&mut *tx).await?;
+ let kind = match to {
+ "running" => "autofix_started",
+ "scheduled" => "autofix_scheduled",
+ _ => "autofix_finished",
+ };
+ let detail = serde_json::json!({"autofix_id": a.id, "strategy": a.strategy, "from": from, "status": to, "reason": reason});
+ insert_event(&mut tx, &a.task_id, mission.and_then(|m| m.0).as_deref(), kind, "kwant", None, None, &detail).await?;
+ tx.commit().await?;
+ Ok(true)
+ }
+
+ /// Finishes the task's running attempt (if any) as `status`.
+ pub async fn finish_running_attempt(&self, task_id: &str, status: &str) -> Result<(), DbError> {
+ let mut tx = self.pool.begin().await?;
+ finish_running(&mut tx, task_id, status, Utc::now()).await?;
+ tx.commit().await?;
+ Ok(())
+ }
+
+ pub async fn set_retry_task(&self, attempt_id: &str, retry_task_id: &str) -> Result<(), DbError> {
+ sqlx::query("UPDATE autofix_attempts SET retry_task_id = ? WHERE id = ?").bind(retry_task_id).bind(attempt_id).execute(&self.pool).await?;
+ Ok(())
+ }
+
+ /// A routine retry's new task: linked to the failed one, counting its attempts (the failed run
+ /// used one), and its claim is the attempt's, so its spend is recovery.
+ pub async fn link_retry_task(&self, task_id: &str, failed: &Task, attempt_id: &str) -> Result<(), DbError> {
+ let mut tx = self.pool.begin().await?;
+ sqlx::query("UPDATE tasks SET forked_from = ?, attempts = ?, max_attempts = ? WHERE id = ? AND forked_from IS NULL")
+ .bind(&failed.id)
+ .bind(failed.attempts + 1)
+ .bind(failed.max_attempts)
+ .bind(task_id)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("UPDATE agent_claims SET autofix_id = ? WHERE task_id = ? AND released_at IS NULL").bind(attempt_id).bind(task_id).execute(&mut *tx).await?;
+ tx.commit().await?;
+ Ok(())
+ }
+
+ /// The AutoFix attempt the task's latest claim was taken for, if it was.
+ pub async fn claim_autofix(&self, claim_id: &str) -> Result<Option<String>, DbError> {
+ let r: Option<(Option<String>,)> = sqlx::query_as("SELECT autofix_id FROM agent_claims WHERE id = ?").bind(claim_id).fetch_optional(&self.pool).await?;
+ Ok(r.and_then(|r| r.0))
+ }
+
+ pub async fn latest_claim_autofix(&self, task_id: &str) -> Result<Option<String>, DbError> {
+ let r: Option<(Option<String>,)> = sqlx::query_as("SELECT autofix_id FROM agent_claims WHERE task_id = ? ORDER BY claimed_at DESC, rowid DESC LIMIT 1")
+ .bind(task_id)
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(r.and_then(|r| r.0))
+ }
+
+ /// Adds recovery spend to the task and to the attempt its claim was taken for.
+ pub async fn spend_recovery(&self, task_id: &str, attempt_id: &str, tokens: i64) -> Result<(), DbError> {
+ let mut tx = self.pool.begin().await?;
+ sqlx::query("UPDATE tasks SET recovery_spent_tokens = MAX(recovery_spent_tokens + ?, 0) WHERE id = ?").bind(tokens).bind(task_id).execute(&mut *tx).await?;
+ sqlx::query("UPDATE autofix_attempts SET tokens_spent = MAX(tokens_spent + ?, 0) WHERE id = ?").bind(tokens).bind(attempt_id).execute(&mut *tx).await?;
+ tx.commit().await?;
+ Ok(())
+ }
+
+ pub async fn recovery_spent(&self, task_id: &str) -> Result<i64, DbError> {
+ let r: Option<(i64,)> = sqlx::query_as("SELECT recovery_spent_tokens FROM tasks WHERE id = ?").bind(task_id).fetch_optional(&self.pool).await?;
+ Ok(r.map_or(0, |r| r.0))
+ }
+
+ /// Whether the task had a `denied` permission decision since `since_ms` (unix ms).
+ /// A routine run's error text, for its task's failure.
+ pub async fn routine_run_error(&self, run_id: &str) -> Result<Option<String>, DbError> {
+ let r: Option<(Option<String>,)> = sqlx::query_as("SELECT error FROM routine_runs WHERE id = ?").bind(run_id).fetch_optional(&self.pool).await?;
+ Ok(r.and_then(|r| r.0))
+ }
+
+ /// The first action denied on `task_id` since `since`, as "tool: summary".
+ pub async fn denied_since(&self, task_id: &str, since: DateTime<Utc>) -> Result<Option<String>, DbError> {
+ let r: Option<(String, String)> = sqlx::query_as(
+ "SELECT tool_name, summary FROM turn_tool_calls WHERE task_id = ? AND decision = 'denied' AND created_at >= ? ORDER BY id LIMIT 1",
+ )
+ .bind(task_id)
+ .bind(since)
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(r.map(|(t, s)| format!("{t}: {s}")))
+ }
+
+ // Workflow changes
+
+ #[allow(clippy::too_many_arguments)]
+ pub async fn propose_change(
+ &self,
+ task: Option<&Task>,
+ routine_id: Option<&str>,
+ target: &str,
+ before: &Value,
+ after: &Value,
+ reason: &str,
+ proposed_by: &str,
+ ) -> Result<WorkflowChange, DbError> {
+ let id = Uuid::new_v4().to_string();
+ let mut tx = self.pool.begin().await?;
+ sqlx::query(
+ "INSERT INTO workflow_changes (id, task_id, routine_id, target, before, after, reason, proposed_by, status, created_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'proposed', ?)",
+ )
+ .bind(&id)
+ .bind(task.map(|t| &t.id))
+ .bind(routine_id)
+ .bind(target)
+ .bind(before.to_string())
+ .bind(after.to_string())
+ .bind(reason)
+ .bind(proposed_by)
+ .bind(Utc::now())
+ .execute(&mut *tx)
+ .await?;
+ if let Some(t) = task {
+ let detail = serde_json::json!({"change_id": id, "target": target, "routine_id": routine_id, "reason": reason});
+ insert_event(&mut tx, &t.id, t.mission_id.as_deref(), "workflow_change_proposed", proposed_by, None, None, &detail).await?;
+ }
+ tx.commit().await?;
+ Ok(sqlx::query_as::<_, WorkflowChange>("SELECT * FROM workflow_changes WHERE id = ?").bind(&id).fetch_one(&self.pool).await?)
+ }
+
+ pub async fn get_change(&self, id: &str) -> Result<Option<WorkflowChange>, DbError> {
+ Ok(sqlx::query_as::<_, WorkflowChange>("SELECT * FROM workflow_changes WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)
+ }
+
+ pub async fn list_changes(&self, status: Option<&str>, task_id: Option<&str>) -> Result<Vec<WorkflowChange>, DbError> {
+ Ok(sqlx::query_as::<_, WorkflowChange>(
+ "SELECT * FROM workflow_changes WHERE (? IS NULL OR status = ?) AND (? IS NULL OR task_id = ?) ORDER BY created_at DESC, rowid DESC LIMIT 200",
+ )
+ .bind(status)
+ .bind(status)
+ .bind(task_id)
+ .bind(task_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// The person decides a proposed change (compare-and-set). `Ok(false)` when it was decided
+ /// already.
+ pub async fn decide_change(&self, c: &WorkflowChange, to: &str) -> Result<bool, DbError> {
+ let mut tx = self.pool.begin().await?;
+ let r = sqlx::query("UPDATE workflow_changes SET status = ?, decided_by = 'person', decided_at = ? WHERE id = ? AND status = 'proposed'")
+ .bind(to)
+ .bind(Utc::now())
+ .bind(&c.id)
+ .execute(&mut *tx)
+ .await?;
+ if r.rows_affected() != 1 {
+ return Ok(false);
+ }
+ change_event(&mut tx, c, "workflow_change_decided", to).await?;
+ tx.commit().await?;
+ Ok(true)
+ }
+
+ /// Applies an approved change once: the target is written only while it still holds `before`
+ /// (else the change goes `stale` and nothing is written). Returns the final status.
+ pub async fn apply_change(&self, c: &WorkflowChange, write: &ChangeWrite) -> Result<String, DbError> {
+ let mut tx = self.pool.begin().await?;
+ let r = match write {
+ ChangeWrite::RoutineInstructions { routine_id, before, after } => {
+ sqlx::query("UPDATE routines SET instructions = ? WHERE id = ? AND instructions = ?").bind(after).bind(routine_id).bind(before).execute(&mut *tx).await?
+ }
+ ChangeWrite::RoutineSchedule { routine_id, before, after, next_run_at } => {
+ sqlx::query("UPDATE routines SET schedule = ?, next_run_at = ? WHERE id = ? AND schedule = ?")
+ .bind(after)
+ .bind(next_run_at)
+ .bind(routine_id)
+ .bind(before)
+ .execute(&mut *tx)
+ .await?
+ }
+ ChangeWrite::CheckSpec { check_id, before_spec, before_required, after_spec, after_required } => {
+ sqlx::query("UPDATE outcome_checks SET spec = ?, required = ? WHERE id = ? AND spec = ? AND required = ?")
+ .bind(after_spec)
+ .bind(after_required)
+ .bind(check_id)
+ .bind(before_spec)
+ .bind(before_required)
+ .execute(&mut *tx)
+ .await?
+ }
+ ChangeWrite::Acceptance { task_id, before, after } => {
+ sqlx::query("UPDATE tasks SET acceptance = ?, updated_at = ? WHERE id = ? AND acceptance = ?")
+ .bind(after)
+ .bind(Utc::now())
+ .bind(task_id)
+ .bind(before)
+ .execute(&mut *tx)
+ .await?
+ }
+ ChangeWrite::MaxAttempts { task_id, before, after } => {
+ sqlx::query("UPDATE tasks SET max_attempts = ?, updated_at = ? WHERE id = ? AND max_attempts = ?")
+ .bind(after)
+ .bind(Utc::now())
+ .bind(task_id)
+ .bind(before)
+ .execute(&mut *tx)
+ .await?
+ }
+ ChangeWrite::Stale => {
+ tx.rollback().await?;
+ return self.mark_stale(c).await;
+ }
+ };
+ if r.rows_affected() != 1 {
+ tx.rollback().await?;
+ return self.mark_stale(c).await;
+ }
+ let r = sqlx::query("UPDATE workflow_changes SET status = 'applied', decided_by = 'person' WHERE id = ? AND status = 'approved'").bind(&c.id).execute(&mut *tx).await?;
+ if r.rows_affected() != 1 {
+ tx.rollback().await?;
+ return Ok(self.get_change(&c.id).await?.map_or_else(|| "missing".into(), |c| c.status));
+ }
+ change_event(&mut tx, c, "workflow_change_applied", "applied").await?;
+ tx.commit().await?;
+ Ok("applied".into())
+ }
+
+ async fn mark_stale(&self, c: &WorkflowChange) -> Result<String, DbError> {
+ let mut tx = self.pool.begin().await?;
+ let r = sqlx::query("UPDATE workflow_changes SET status = 'stale' WHERE id = ? AND status = 'approved'").bind(&c.id).execute(&mut *tx).await?;
+ if r.rows_affected() == 1 {
+ change_event(&mut tx, c, "workflow_change_decided", "stale").await?;
+ }
+ tx.commit().await?;
+ Ok("stale".into())
+ }
+
+ /// 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> {
+ 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')",
+ )
+ .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?;
+ Ok((attempts, succeeded, tokens, classes))
+ }
+}
+
+/// What applying a change writes, with the value it must still find there.
+pub enum ChangeWrite {
+ RoutineInstructions { routine_id: String, before: String, after: String },
+ RoutineSchedule { routine_id: String, before: String, after: String, next_run_at: Option<DateTime<Utc>> },
+ CheckSpec { check_id: String, before_spec: String, before_required: bool, after_spec: String, after_required: bool },
+ Acceptance { task_id: String, before: String, after: String },
+ MaxAttempts { task_id: String, before: i64, after: i64 },
+ /// The target is gone or no longer matches.
+ Stale,
+}
+
+async fn change_event(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, c: &WorkflowChange, kind: &str, status: &str) -> Result<(), DbError> {
+ let Some(task_id) = &c.task_id else { return Ok(()) };
+ let mission: Option<(Option<String>,)> = sqlx::query_as("SELECT mission_id FROM tasks WHERE id = ?").bind(task_id).fetch_optional(&mut **tx).await?;
+ let detail = serde_json::json!({"change_id": c.id, "target": c.target, "status": status});
+ insert_event(tx, task_id, mission.and_then(|m| m.0).as_deref(), kind, "person", None, None, &detail).await
+}
+
+async fn finish_running(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, task_id: &str, status: &str, now: DateTime<Utc>) -> Result<(), DbError> {
+ let running: Vec<(String, String, Option<String>)> = sqlx::query_as(
+ "SELECT a.id, a.strategy, t.mission_id FROM autofix_attempts a JOIN tasks t ON t.id = a.task_id \
+ WHERE a.status = 'running' AND (a.task_id = ? OR a.retry_task_id = ?)",
+ )
+ .bind(task_id)
+ .bind(task_id)
+ .fetch_all(&mut **tx)
+ .await?;
+ for (id, strategy, mission) in running {
+ let r = sqlx::query("UPDATE autofix_attempts SET status = ?, finished_at = ? WHERE id = ? AND status = 'running'")
+ .bind(status)
+ .bind(now)
+ .bind(&id)
+ .execute(&mut **tx)
+ .await?;
+ if r.rows_affected() == 1 {
+ let detail = serde_json::json!({"autofix_id": id, "strategy": strategy, "from": "running", "status": status});
+ let owner: (String,) = sqlx::query_as("SELECT task_id FROM autofix_attempts WHERE id = ?").bind(&id).fetch_one(&mut **tx).await?;
+ insert_event(tx, &owner.0, mission.as_deref(), "autofix_finished", "kwant", None, None, &detail).await?;
+ }
+ }
+ Ok(())
+}
diff --git a/src/db/checkpoints.rs b/src/db/checkpoints.rs
index a00fb98d..6036dfd1 100644
--- a/src/db/checkpoints.rs
+++ b/src/db/checkpoints.rs
@@ -280,8 +280,9 @@ impl Database {
path: Option<&str>,
) -> Result<(), DbError> {
sqlx::query(
- "INSERT INTO turn_tool_calls (turn_id, kwant_id, task_id, tool_name, effect, summary, decision, approval_id, created_at, path) \
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ "INSERT INTO turn_tool_calls (turn_id, kwant_id, task_id, tool_name, effect, summary, decision, approval_id, created_at, path, idempotency_key) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT a.idempotency_key FROM agent_claims c JOIN autofix_attempts a ON a.id = c.autofix_id \
+ WHERE c.task_id = ? AND c.released_at IS NULL ORDER BY c.claimed_at DESC LIMIT 1))",
)
.bind(turn_id)
.bind(kwant_id)
@@ -293,6 +294,7 @@ impl Database {
.bind(approval_id)
.bind(Utc::now())
.bind(path)
+ .bind(task_id)
.execute(&self.pool)
.await?;
Ok(())
diff --git a/src/db/mission_graph.rs b/src/db/mission_graph.rs
index b618338c..204311e8 100644
--- a/src/db/mission_graph.rs
+++ b/src/db/mission_graph.rs
@@ -374,7 +374,7 @@ pub struct FlagClaim<'a> {
/// Resolves the flag inside `tx` if it is still open, and logs `flag_resolved` with `detail`
/// merged in. False when it was already resolved; nothing is written then.
-async fn claim_flag(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, c: &FlagClaim<'_>, detail: Option<&Value>) -> Result<bool, DbError> {
+pub(crate) async fn claim_flag(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, c: &FlagClaim<'_>, detail: Option<&Value>) -> Result<bool, DbError> {
let r = sqlx::query("UPDATE task_flags SET resolved_at = ?, resolved_by = 'person', resolution = ? WHERE id = ? AND resolved_at IS NULL")
.bind(Utc::now())
.bind(c.resolution)
diff --git a/src/db/missions.rs b/src/db/missions.rs
index dc1a8e7c..ad28f8f0 100644
--- a/src/db/missions.rs
+++ b/src/db/missions.rs
@@ -73,6 +73,8 @@ pub struct Task {
pub forked_from: Option<String>,
/// Set by a restore (D10): no claim until the person runs the task (`POST /api/tasks/:id/run`).
pub held_at: Option<DateTime<Utc>>,
+ /// Tokens AutoFix runs spent (Phase B3); part of `spent_tokens`, capped by the recovery budget.
+ pub recovery_spent_tokens: i64,
}
/// A lease on a task. Times are unix milliseconds so the SQLite triggers can compare them.
@@ -657,6 +659,12 @@ impl Database {
pub async fn move_task(&self, id: &str, from: &str, to: &str, actor: &str, change: &TaskChange) -> Result<bool, DbError> {
let now = Utc::now();
let mut tx = self.pool.begin().await?;
+ if let Some((fid, resolution, note)) = &change.flag {
+ let claim = crate::db::mission_graph::FlagClaim { id: fid, resolution, note: note.as_deref() };
+ if !crate::db::mission_graph::claim_flag(&mut tx, &claim, None).await? {
+ return Ok(false);
+ }
+ }
let r = sqlx::query(
"UPDATE tasks SET state = ?, updated_at = ?, \
attempts = attempts + ?, \
@@ -768,7 +776,8 @@ impl Database {
.execute(&mut *tx)
.await?;
sqlx::query(
- "INSERT INTO agent_claims (id, task_id, kwant_id, turn_id, context_id, system, claimed_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+ "INSERT INTO agent_claims (id, task_id, kwant_id, turn_id, context_id, system, claimed_at, expires_at, autofix_id) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, (SELECT id FROM autofix_attempts WHERE task_id = ? AND status = 'running'))",
)
.bind(Uuid::new_v4().to_string())
.bind(task_id)
@@ -778,6 +787,7 @@ impl Database {
.bind(system)
.bind(now)
.bind(now + lease_ms.max(1000))
+ .bind(task_id)
.execute(&mut *tx)
.await?;
sqlx::query("UPDATE tasks SET state = 'working', owner_kwant_id = ?, updated_at = ? WHERE id = ? AND state = 'ready'")
@@ -1145,11 +1155,14 @@ pub struct TaskChange {
/// `Some(x)` sets the owner to `x`.
pub owner: Option<Option<String>>,
pub detail: Option<Value>,
+ /// The person resolving this flag (id, resolution, note) by this move: the flag is claimed
+ /// first in the move's transaction, so of two racing resolves only one moves the task.
+ pub flag: Option<(String, String, Option<String>)>,
}
impl Default for TaskChange {
fn default() -> Self {
- TaskChange { kind: "state".into(), reason: None, attempt: false, owner: None, detail: None }
+ TaskChange { kind: "state".into(), reason: None, attempt: false, owner: None, detail: None, flag: None }
}
}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 45888234..eb04f77a 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -27,6 +27,7 @@ pub mod usage;
pub mod missions;
pub mod mission_graph;
pub mod checkpoints;
+pub mod autofix;
/// What a space's #general says about itself.
pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
@@ -162,6 +163,7 @@ impl Database {
db.migrate_missions().await?;
db.migrate_mission_graph().await?;
db.migrate_checkpoints().await?;
+ db.migrate_autofix().await?;
if spaces {
let migration = db.migrate_spaces(data_dir, fresh).await?;
db.require_spaces_schema(&migration).await?;
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 501c5c48..ba9bb08f 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -337,6 +337,9 @@ pub fn person_only(method: &Method, path: &str) -> bool {
// Mission Control: approving plans, verifying, rejecting, retrying and approving checks are
// the person's calls; bots act on tasks only through their task tools
["", "api", "missions" | "tasks" | "checks", ..] => *method != Method::GET && *method != Method::HEAD,
+ // AutoFix's proposed changes to routines, checks and tasks: only the person reads, approves
+ // or rejects them; bots only propose (the `workflow_propose` tool)
+ ["", "api", "workflow-changes", ..] => true,
// App-wide settings, including where notifications go (`notify_webhook_url`), and the
// sub-routes such as `/computer` (which machine the bots run on) and `/computer/window`:
// bots change the allowed ones through their `settings_update` action, never these routes
@@ -854,6 +857,12 @@ mod tests {
assert!(!person_only(&get, "/api/tasks/t1/checkpoints"));
assert!(!person_only(&get, "/api/tasks/t1/checkpoints/c1/restore-preview"));
assert!(person_only(&post, "/api/tasks/t1/flags/f1/resolve"));
+ assert!(person_only(&get, "/api/workflow-changes"));
+ assert!(person_only(&post, "/api/workflow-changes/w1/approve"));
+ assert!(person_only(&post, "/api/workflow-changes/w1/reject"));
+ assert!(person_only(&post, "/api/tasks/t1/autofix"));
+ assert!(person_only(&post, "/api/tasks/t1/autofix/a1/cancel"));
+ assert!(!person_only(&get, "/api/tasks/t1/failures"));
assert!(person_only(&post, "/api/missions/m1/graph/scan"));
assert!(!person_only(&get, "/api/missions/m1/graph"));
assert!(!person_only(&get, "/api/tasks/t1/flags"));
diff --git a/src/server/missions/autofix.rs b/src/server/missions/autofix.rs
new file mode 100644
index 00000000..e1f8b86b
--- /dev/null
+++ b/src/server/missions/autofix.rs
@@ -0,0 +1,988 @@
+//! Mission Control Phase B3: AutoFix. Every failure of a task is recorded with a class from
+//! [`classify`] (deterministic, no model), its redacted output and a server-only diagnostics file.
+//! With `autofix` on, a failure the task can still recover from parks the task in `failed` and
+//! plans one retry (by class: wait and retry, retry with the diagnostics, continue where it
+//! stopped), which moves it back to `ready` as [`Actor::AutoFix`] once its time has come and the
+//! 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.
+
+use super::routes::{bad, conflict, internal, load_task, not_found};
+use super::{emit_task, transition, Actor};
+use crate::db::autofix::{Attempt, ChangeWrite, Failure, NewAttempt, NewFailure, WorkflowChange, TARGETS};
+use crate::db::missions::{Task, TaskChange};
+use crate::server::AppState;
+use axum::{
+ extract::{Path, RawQuery, State},
+ http::{HeaderMap, StatusCode},
+ response::{IntoResponse, Response},
+ Json,
+};
+use chrono::{DateTime, Duration, Utc};
+use serde::Deserialize;
+use serde_json::{json, Value};
+use sha2::{Digest, Sha256};
+
+pub const SETTING: &str = "autofix";
+pub const MODES: [&str; 3] = ["off", "suggest", "on"];
+pub const PCT_SETTING: &str = "recovery_budget_pct";
+pub const DEFAULT_PCT: i64 = 25;
+pub const PCT_RANGE: (i64, i64) = (0, 100);
+/// Waits before the 1st, 2nd and later retries of a transient failure.
+pub const BACKOFF_MINUTES: [i64; 3] = [1, 5, 25];
+/// Largest diagnostics file kept per failure.
+const DIAGNOSTICS_MAX: usize = 256 * 1024;
+
+pub async fn mode(state: &AppState) -> &'static str {
+ match state.db.get_setting(SETTING).await.ok().flatten().as_deref().map(str::trim) {
+ Some("on") => "on",
+ Some("suggest") => "suggest",
+ _ => "off",
+ }
+}
+
+pub async fn recovery_pct(state: &AppState) -> i64 {
+ super::int_setting(state, PCT_SETTING, PCT_RANGE, DEFAULT_PCT).await
+}
+
+pub fn settings_error(mode: Option<&str>, pct: Option<i64>) -> Option<String> {
+ if let Some(m) = mode.filter(|m| !MODES.contains(m)) {
+ return Some(format!("autofix must be off, suggest or on (got {m})"));
+ }
+ if let Some(n) = pct.filter(|n| !(PCT_RANGE.0..=PCT_RANGE.1).contains(n)) {
+ return Some(format!("recovery_budget_pct must be {}–{} (got {n})", PCT_RANGE.0, PCT_RANGE.1));
+ }
+ None
+}
+
+// Classification
+
+const AUTH: [&str; 12] = [
+ "not logged in",
+ "not signed in",
+ "/login",
+ "auth login",
+ "unauthorized",
+ "invalid api key",
+ "invalid x-api-key",
+ "api key rejected",
+ "authentication_error",
+ "token has expired",
+ "login has expired",
+ "credit balance is too low",
+];
+
+const TRANSIENT: [&str; 18] = [
+ "rate limit",
+ "rate-limit",
+ "rate_limit",
+ "overloaded",
+ "too many requests",
+ "timed out",
+ "timeout",
+ "connection refused",
+ "connection reset",
+ "connection closed",
+ "network",
+ "temporarily unavailable",
+ "service unavailable",
+ "bad gateway",
+ "gateway timeout",
+ "internal server error",
+ "econnreset",
+ "etimedout",
+];
+
+const TRANSIENT_CODES: [&str; 6] = ["429", "500", "502", "503", "504", "529"];
+
+/// Whether `code` appears in `text` as a number of its own (not inside a longer one).
+fn has_code(text: &str, code: &str) -> bool {
+ text.match_indices(code).any(|(i, _)| {
+ let before = text[..i].chars().next_back();
+ let after = text[i + code.len()..].chars().next();
+ !before.is_some_and(|c| c.is_ascii_digit()) && !after.is_some_and(|c| c.is_ascii_digit())
+ })
+}
+
+fn is_auth(t: &str) -> bool {
+ AUTH.iter().any(|p| t.contains(p)) || has_code(t, "401")
+}
+
+fn is_transient(t: &str) -> bool {
+ TRANSIENT.iter().any(|p| t.contains(p)) || TRANSIENT_CODES.iter().any(|c| has_code(t, c))
+}
+
+/// The class of a failure, from where it came (`source`), how it ended (`status`: `failed` or
+/// `error` for a check; `error`, `stalled`, `denied` or `needs_input` for a turn) and its text.
+pub fn classify(source: &str, status: &str, text: &str) -> &'static str {
+ let t = text.to_lowercase();
+ match (source, status) {
+ ("check", "failed") if t.contains("exit code 127") || t.contains("command not found") => "bad_spec",
+ ("check", "failed") => "check_failed",
+ ("check", _) if is_transient(&t) => "transient",
+ ("check", _) => "bad_spec",
+ ("lease", _) => "stalled",
+ ("budget", _) => "budget",
+ ("turn", "stalled") => "stalled",
+ ("turn", "denied") => "denied",
+ ("turn", "needs_input") => "needs_input",
+ // auth before transient: "401" next to "Reconnecting… timed out" is still a login problem
+ (_, _) if is_auth(&t) => "auth",
+ (_, _) if is_transient(&t) => "transient",
+ _ => "unknown",
+ }
+}
+
+/// The strategy for a class (`autofix=on`); `unknown` is retried once per task.
+fn strategy_for(class: &str) -> &'static str {
+ match class {
+ "transient" => "wait_and_retry",
+ "stalled" => "retry_same",
+ "check_failed" => "retry_with_diagnostics",
+ "bad_spec" => "propose_change",
+ "unknown" => "retry_same",
+ _ => "none",
+ }
+}
+
+/// What the person must do for a failure AutoFix never retries.
+fn fix_text(class: &str, summary: &str) -> Option<String> {
+ match class {
+ "auth" => Some(format!("Sign in to the bot's engine again, then retry: {summary}")),
+ "budget" => Some("Raise the task's budget, then retry it.".into()),
+ "denied" => Some("An action was denied during the run. Decide whether it may run, then retry.".into()),
+ _ => None,
+ }
+}
+
+// Redaction
+
+/// Masks anything that looks like a key, token or password, line by line.
+pub fn redact(text: &str) -> String {
+ 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(" ")
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+fn cut(text: &str, max: usize) -> String {
+ if text.chars().count() <= max {
+ return text.to_string();
+ }
+ let s: String = text.chars().take(max.saturating_sub(1)).collect();
+ format!("{s}…")
+}
+
+fn diagnostics_root(state: &AppState) -> std::path::PathBuf {
+ state.config.data_dir.join("autofix")
+}
+
+/// Writes the redacted diagnostics of a failure, 0600 in a 0700 folder. Server-only.
+fn write_diagnostics(state: &AppState, task_id: &str, name: &str, text: &str) -> Option<String> {
+ use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
+ let dir = diagnostics_root(state).join(task_id);
+ std::fs::DirBuilder::new().recursive(true).mode(0o700).create(&dir).ok()?;
+ let path = dir.join(format!("{name}.log"));
+ let mut f = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&path).ok()?;
+ let body: String = text.chars().take(DIAGNOSTICS_MAX).collect();
+ std::io::Write::write_all(&mut f, body.as_bytes()).ok()?;
+ Some(path.to_string_lossy().into_owned())
+}
+
+// Recording and planning
+
+/// Mission and person tasks are retried in place; routine runs as a new run (§4.4).
+fn retried_in_place(task: &Task) -> bool {
+ matches!(task.source_kind.as_str(), "mission" | "person")
+}
+
+/// Whether a failure of `task` with attempts left parks it in `failed` (for AutoFix) instead of
+/// sending it straight back to `ready` (Phase A). `attempt` is whether this failure uses one.
+pub async fn parks(state: &AppState, task: &Task, attempt: bool) -> bool {
+ retried_in_place(task) && mode(state).await != "off" && task.attempts + i64::from(attempt) < task.max_attempts
+}
+
+/// A failed task waiting for AutoFix: the board shows no "failed" chat line for it.
+pub async fn parked(state: &AppState, task: &Task) -> bool {
+ task.state == "failed" && retried_in_place(task) && mode(state).await != "off" && task.attempts < task.max_attempts
+}
+
+/// Attempts the task has used, counting a routine run's own run.
+fn used(task: &Task) -> i64 {
+ if retried_in_place(task) {
+ task.attempts
+ } else {
+ task.attempts + 1
+ }
+}
+
+/// The recovery budget: `recovery_budget_pct` of the task's budget.
+pub fn recovery_budget(task: &Task, pct: i64) -> i64 {
+ task.budget_tokens.saturating_mul(pct) / 100
+}
+
+/// Why another attempt can't start, as an API code: `no_attempts_left`, `over_recovery_budget`,
+/// `not_retryable`.
+async fn limit(state: &AppState, task: &Task) -> Option<&'static str> {
+ if task.state == "blocked" {
+ return Some("not_retryable");
+ }
+ if used(task) >= task.max_attempts {
+ return Some("no_attempts_left");
+ }
+ 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 {
+ return Some("over_recovery_budget");
+ }
+ None
+}
+
+fn limit_reason(code: &str) -> &'static str {
+ match code {
+ "no_attempts_left" => "no_attempts_left: the task used all its attempts",
+ "over_recovery_budget" => "over_recovery_budget: another attempt would go past the recovery budget",
+ _ => "not_retryable: AutoFix never moves this task",
+ }
+}
+
+fn key(task_id: &str, failure_id: &str, strategy: &str) -> String {
+ let d = Sha256::digest(format!("{task_id}:{failure_id}:{strategy}").as_bytes());
+ d.iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// Records a failure of `task` (already moved to where Phase A or [`parks`] put it), then plans
+/// AutoFix's answer. `text` is the raw output; only its redacted form is stored.
+pub async fn record(state: &AppState, task_id: &str, source: &str, status: &str, text: &str, summary: &str) -> Option<Failure> {
+ let task = state.db.get_task(task_id).await.ok().flatten()?;
+ let class = classify(source, status, text);
+ let clean = redact(text);
+ let excerpt = (!clean.trim().is_empty()).then(|| cut(clean.trim(), super::MAX_EXCERPT));
+ let summary = cut(&redact(summary), 200);
+ let name = uuid::Uuid::new_v4().to_string();
+ let diagnostics_path = (!clean.trim().is_empty()).then(|| write_diagnostics(state, &task.id, &name, &clean)).flatten();
+ let checkpoint_id = state
+ .db
+ .checkpoints_of(&task.id)
+ .await
+ .unwrap_or_default()
+ .into_iter()
+ .rev()
+ .find(|c| c.kind == "after_run" && !c.failed())
+ .map(|c| c.id);
+ let new = NewFailure { task: &task, source, class, summary, excerpt, diagnostics_path, checkpoint_id };
+ let failure = match state.db.insert_failure(&new).await {
+ Ok(f) => f,
+ Err(e) => {
+ tracing::warn!(task_id = %task.id, error = %e, "could not record a task failure");
+ return None;
+ }
+ };
+ let task = state.db.get_task(task_id).await.ok().flatten().unwrap_or(task);
+ if mode(state).await != "off" {
+ plan(state, &task, &failure).await;
+ }
+ emit_task(state, &task).await;
+ Some(failure)
+}
+
+/// Plans AutoFix's answer to `failure`: one attempt (keyed, so a repeat plans nothing), a
+/// proposal, or nothing for a class only the person can fix.
+async fn plan(state: &AppState, task: &Task, failure: &Failure) -> Option<Attempt> {
+ if failure.class == "needs_input" || task.source_kind == "delegation" {
+ return None;
+ }
+ let mut strategy = strategy_for(&failure.class);
+ if failure.class == "stalled" && failure.checkpoint_id.is_some() {
+ strategy = "retry_from_checkpoint";
+ }
+ if failure.class == "unknown" {
+ let earlier = state.db.attempts_of(&task.id).await.unwrap_or_default();
+ let fails = state.db.failures_of(&task.id).await.unwrap_or_default();
+ let unknown_retried = earlier.iter().any(|a| a.strategy == "retry_same" && fails.iter().any(|f| f.id == a.failure_id && f.class == "unknown"));
+ if unknown_retried {
+ strategy = "none";
+ }
+ }
+ let k = key(&task.id, &failure.id, strategy);
+ let new = |status, not_before, reason: String| NewAttempt { task, failure_id: &failure.id, strategy, idempotency_key: k.clone(), status, not_before, reason };
+ if strategy == "none" {
+ let why = fix_text(&failure.class, &failure.summary).unwrap_or_else(|| "AutoFix retried this once already".into());
+ return insert(state, &new("skipped", None, why)).await;
+ }
+ if strategy == "propose_change" {
+ propose_check_change(state, task, failure).await;
+ return insert(state, &new("suggested", None, "a check that can't run: allow a change to it first".into())).await;
+ }
+ if let Some(code) = limit(state, task).await {
+ return insert(state, &new("skipped", None, limit_reason(code).into())).await;
+ }
+ let wait = if strategy == "wait_and_retry" {
+ let n = state.db.count_failures(&task.id, "transient", &failure.id).await.unwrap_or(0);
+ Some(failure.created_at + Duration::minutes(BACKOFF_MINUTES[usize::try_from(n).unwrap_or(2).min(2)]))
+ } else {
+ None
+ };
+ let reason = match strategy {
+ "wait_and_retry" => "a temporary error: wait, then run it again".to_string(),
+ "retry_with_diagnostics" => "a check failed: run it again with the check's output".into(),
+ "retry_from_checkpoint" => "the run stopped: continue from where it left off".into(),
+ _ => "run it again".into(),
+ };
+ let status = if mode(state).await == "on" { "scheduled" } else { "suggested" };
+ let a = insert(state, &new(status, wait, reason)).await?;
+ if a.status == "scheduled" {
+ soon(state, &a);
+ }
+ Some(a)
+}
+
+async fn insert(state: &AppState, a: &NewAttempt<'_>) -> Option<Attempt> {
+ match state.db.insert_attempt(a).await {
+ Ok(a) => a,
+ Err(e) => {
+ tracing::info!(task_id = %a.task.id, error = %e, "an autofix attempt wasn't planned");
+ None
+ }
+ }
+}
+
+/// A check that can't run: propose making it optional (the person can edit the spec instead).
+async fn propose_check_change(state: &AppState, task: &Task, failure: &Failure) {
+ let checks = state.db.list_checks(&task.id).await.unwrap_or_default();
+ let Some(c) = checks.iter().find(|c| c.required && matches!(c.status.as_str(), "failed" | "error")).or_else(|| checks.iter().find(|c| matches!(c.status.as_str(), "failed" | "error"))) else {
+ return;
+ };
+ let before = json!({"check_id": c.id, "kind": c.kind, "spec": c.spec_value(), "required": c.required});
+ let after = json!({"check_id": c.id, "kind": c.kind, "spec": c.spec_value(), "required": false});
+ let reason = format!("The {} check can't run ({}). Make it optional, or edit its spec.", c.kind, failure.summary);
+ if let Ok(change) = state.db.propose_change(Some(task), None, "check_spec", &before, &after, &reason, "kwant").await {
+ tracing::info!(change_id = %change.id, task_id = %task.id, "autofix proposed a check change");
+ }
+}
+
+// Running attempts
+
+/// Runs `a` as soon as the task's last turn has ended (its spend has landed) and the mission's
+/// runner slot is free; the scheduler tick ([`run_due`]) catches anything left.
+fn soon(state: &AppState, a: &Attempt) {
+ if a.not_before.is_some_and(|t| t > Utc::now()) {
+ return;
+ }
+ let state = state.clone();
+ let id = a.id.clone();
+ tokio::spawn(async move {
+ for _ in 0..240 {
+ let Ok(Some(a)) = state.db.get_attempt(&id).await else { return };
+ if a.status != "scheduled" {
+ return;
+ }
+ if !busy(&state, &a.task_id).await {
+ execute(&state, &a).await;
+ return;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(250)).await;
+ }
+ });
+}
+
+/// Whether the task's last claim still has a turn going (its spend hasn't landed) or its
+/// mission's runner slot is taken.
+async fn busy(state: &AppState, task_id: &str) -> bool {
+ let Ok(Some(task)) = state.db.get_task(task_id).await else { return false };
+ if task.mission_id.as_deref().is_some_and(super::runner::is_running) {
+ return true;
+ }
+ let claim = match state.db.open_claim(task_id).await.ok().flatten() {
+ Some(c) => Some(c),
+ None => state.db.last_released_claim(task_id).await.ok().flatten(),
+ };
+ let Some(claim) = claim else { return false };
+ state
+ .turns
+ .active_turns()
+ .iter()
+ .any(|t| t.kwant_id == claim.kwant_id && claim.context_id.as_deref().is_none_or(|c| c == t.context_id))
+}
+
+/// Scheduled attempts whose time has come, on each scheduler tick (before the runner picks
+/// tasks). A restart loses nothing: the attempt waits in the table.
+pub async fn run_due(state: &AppState) {
+ if mode(state).await == "off" {
+ return;
+ }
+ for a in state.db.due_attempts(Utc::now()).await.unwrap_or_default() {
+ if !busy(state, &a.task_id).await {
+ execute(state, &a).await;
+ }
+ }
+}
+
+/// Starts a scheduled attempt: limits are checked again (spend has landed by now), then the task
+/// goes back to `ready` as [`Actor::AutoFix`], or a routine gets a new run.
+async fn execute(state: &AppState, a: &Attempt) {
+ let Ok(Some(task)) = state.db.get_task(&a.task_id).await else { return };
+ if task.state != "failed" {
+ let _ = state.db.move_attempt(a, "scheduled", "skipped", Some("the task moved on before the retry")).await;
+ emit_task(state, &task).await;
+ return;
+ }
+ if let Some(code) = limit(state, &task).await {
+ let _ = state.db.move_attempt(a, "scheduled", "skipped", Some(limit_reason(code))).await;
+ emit_task(state, &task).await;
+ return;
+ }
+ match state.db.move_attempt(a, "scheduled", "running", None).await {
+ Ok(true) => {}
+ Ok(false) => return,
+ Err(e) => {
+ tracing::info!(autofix_id = %a.id, error = %e, "an autofix attempt couldn't start");
+ let _ = state.db.move_attempt(a, "scheduled", "skipped", Some(limit_reason("no_attempts_left"))).await;
+ return;
+ }
+ }
+ if retried_in_place(&task) {
+ let change = TaskChange {
+ kind: "autofix".into(),
+ reason: Some(format!("AutoFix: {}", a.reason)),
+ detail: Some(json!({"autofix_id": a.id, "strategy": a.strategy})),
+ ..Default::default()
+ };
+ if let Err(e) = transition(state, &task.id, "failed", "ready", Actor::AutoFix, "kwant", change).await {
+ let _ = state.db.move_attempt(a, "running", "failed", Some(&format!("couldn't make the task ready: {e}"))).await;
+ emit_task(state, &task).await;
+ return;
+ }
+ if let Some(mid) = &task.mission_id {
+ if let Ok(Some(m)) = state.db.get_mission(mid).await {
+ if m.status == "active" && !super::runner::is_running(mid) {
+ let _ = super::runner::run_mission(state, &m, 1).await;
+ }
+ }
+ }
+ } else if task.source_kind == "routine" {
+ retry_routine(state, a, &task).await;
+ }
+}
+
+/// A routine retry is a new run of the routine; its task is linked to the failed one (§4.4).
+async fn retry_routine(state: &AppState, a: &Attempt, failed: &Task) {
+ let routine = match failed.source_id.as_deref() {
+ Some(run) => match state.db.routine_run_of(run).await {
+ Ok(Some((routine, _))) => state.db.get_routine(&routine).await.ok().flatten(),
+ _ => None,
+ },
+ None => None,
+ };
+ let Some(routine) = routine else {
+ let _ = state.db.move_attempt(a, "running", "failed", Some("the routine is gone")).await;
+ return;
+ };
+ let routine_id = routine.id.clone();
+ let Some(run) = crate::server::scheduler::start_run(state, routine, "manual").await else {
+ let _ = state.db.move_attempt(a, "running", "failed", Some("the routine run couldn't start")).await;
+ return;
+ };
+ if run.status != "running" {
+ let _ = state.db.move_attempt(a, "running", "failed", Some("the routine was still running")).await;
+ return;
+ }
+ super::listener::on_routine_run(state, &routine_id, &run.id, "running").await;
+ if let Ok(Some(new)) = state.db.task_by_source("routine", &run.id).await {
+ let _ = state.db.link_retry_task(&new.id, failed, &a.id).await;
+ let _ = state.db.set_retry_task(&a.id, &new.id).await;
+ super::emit_task_id(state, &new.id).await;
+ }
+ super::emit_task_id(state, &failed.id).await;
+}
+
+/// The task's live attempt ended with the task: verified → succeeded, cancelled → skipped.
+pub async fn settle(state: &AppState, task: &Task, to: &str) {
+ let status = match to {
+ "verified" => "succeeded",
+ "cancelled" => "skipped",
+ _ => return,
+ };
+ let _ = state.db.finish_running_attempt(&task.id, status).await;
+}
+
+// Recovery spend
+
+/// Recovery spend: a turn of a claim AutoFix took the task for adds to `recovery_spent_tokens`
+/// and the attempt's `tokens_spent` too.
+pub async fn spend_on_claim(state: &AppState, task_id: &str, claim_id: Option<&str>, tokens: i64) {
+ let aid = match claim_id {
+ Some(c) => state.db.claim_autofix(c).await.ok().flatten(),
+ None => state.db.latest_claim_autofix(task_id).await.ok().flatten(),
+ };
+ if let Some(aid) = aid {
+ let _ = state.db.spend_recovery(task_id, &aid, tokens).await;
+ }
+}
+
+// The retry prompt
+
+/// What a retry's prompt adds: why it runs again, the diagnostics, the idempotency key and the
+/// external calls already made. `None` when the task isn't on an AutoFix attempt.
+pub async fn retry_note(state: &AppState, task: &Task) -> Option<String> {
+ let a = state.db.current_attempt(&task.id).await.ok().flatten().filter(|a| a.status == "running")?;
+ let failure = state.db.get_failure(&a.failure_id).await.ok().flatten()?;
+ let mut out = format!(
+ "\n\n[AutoFix] This is attempt {} of {} (strategy {}). The last attempt failed: {}.\n",
+ task.attempts + 1,
+ task.max_attempts,
+ a.strategy,
+ failure.summary
+ );
+ match a.strategy.as_str() {
+ "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()));
+ }
+ if let Some(x) = &failure.excerpt {
+ out.push_str(&format!("Its output (secrets masked):\n{x}\n"));
+ }
+ }
+ "retry_from_checkpoint" | "retry_same" if failure.class == "stalled" => out.push_str("Continue; the files are as you left them.\n"),
+ _ => {
+ if let Some(x) = &failure.excerpt {
+ out.push_str(&format!("The error (secrets masked):\n{}\n", cut(x, 500)));
+ }
+ }
+ }
+ out.push_str(&format!("KWANT_IDEMPOTENCY_KEY={}\n", a.idempotency_key));
+ let external: Vec<String> = state
+ .db
+ .tool_calls_of(&task.id)
+ .await
+ .unwrap_or_default()
+ .into_iter()
+ .filter(|c| c.effect == "external" && c.decision != "denied")
+ .map(|c| format!("- {}: {}", c.tool_name, cut(&redact(&c.summary), 160)))
+ .collect();
+ if external.is_empty() {
+ out.push_str("No external calls are recorded for this task yet.");
+ } else {
+ out.push_str(&format!(
+ "These external calls already happened in earlier attempts; check before repeating them, and pass the key where the service accepts one:\n{}",
+ external.iter().rev().take(20).rev().cloned().collect::<Vec<_>>().join("\n")
+ ));
+ }
+ Some(out)
+}
+
+// Board JSON
+
+pub fn attempt_json(a: &Attempt) -> Value {
+ json!({
+ "id": a.id,
+ "strategy": a.strategy,
+ "status": a.status,
+ "not_before": a.not_before,
+ "reason": a.reason,
+ "tokens_spent": a.tokens_spent,
+ "retry_task_id": a.retry_task_id,
+ })
+}
+
+/// Adds the AutoFix fields to a task's JSON.
+pub async fn extend_task_json(state: &AppState, task: &Task, obj: &mut serde_json::Map<String, Value>) {
+ let pct = recovery_pct(state).await;
+ obj.insert("recovery_budget_tokens".into(), json!(recovery_budget(task, pct)));
+ let failures = state.db.failures_of(&task.id).await.unwrap_or_default();
+ obj.insert(
+ "last_failure".into(),
+ failures.last().map_or(Value::Null, |f| json!({"class": f.class, "summary": f.summary, "created_at": f.created_at})),
+ );
+ let current = state.db.current_attempt(&task.id).await.ok().flatten();
+ obj.insert("autofix".into(), current.as_ref().map_or(Value::Null, attempt_json));
+}
+
+/// AutoFix's Needs-you items, for a task that isn't running: a suggested retry, a proposed
+/// change, or what the person must fix.
+pub async fn needs_you(state: &AppState, task: &Task) -> Vec<Value> {
+ if matches!(task.state.as_str(), "working" | "needs_you") {
+ return Vec::new();
+ }
+ let mut items = Vec::new();
+ let failures = state.db.failures_of(&task.id).await.unwrap_or_default();
+ let last = failures.last();
+ if matches!(task.state.as_str(), "failed" | "blocked") {
+ if let Some(a) = state.db.current_attempt(&task.id).await.ok().flatten().filter(|a| a.status == "suggested" && a.strategy != "propose_change") {
+ let summary = last.map(|f| f.summary.as_str()).unwrap_or("");
+ let text = match a.strategy.as_str() {
+ "retry_with_diagnostics" => format!("Retry with the check output? {summary}"),
+ "wait_and_retry" => format!("Retry after a temporary error? {summary}"),
+ _ => format!("Retry from where it stopped? {summary}"),
+ };
+ items.push(json!({"kind": "autofix_suggested", "id": a.id, "text": cut(&text, 200)}));
+ }
+ if let Some(f) = last {
+ if let Some(text) = fix_text(&f.class, &f.summary) {
+ items.push(json!({"kind": "fix_needed", "id": f.id, "text": cut(&text, 200)}));
+ }
+ }
+ }
+ for c in state.db.list_changes(Some("proposed"), Some(&task.id)).await.unwrap_or_default() {
+ let text = format!("Allow this change to {}: {}", target_label(&c.target), c.reason);
+ items.push(json!({"kind": "workflow_change", "id": c.id, "text": cut(&text, 200)}));
+ }
+ items
+}
+
+fn target_label(target: &str) -> &'static str {
+ match target {
+ "routine_instructions" => "the routine's instructions",
+ "routine_schedule" => "the routine's schedule",
+ "check_spec" => "a check",
+ "task_acceptance" => "the task's acceptance",
+ _ => "the task's max attempts",
+ }
+}
+
+// API
+
+/// `GET /api/tasks/:id/failures`
+pub async fn task_failures(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
+ let t = match load_task(&state, q.as_deref(), &id).await {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ let failures = match state.db.failures_of(&t.id).await {
+ Ok(f) => f,
+ Err(e) => return internal(e),
+ };
+ let attempts = state.db.attempts_of(&t.id).await.unwrap_or_default();
+ let list: Vec<Value> = failures
+ .iter()
+ .map(|f| {
+ let a = attempts.iter().rev().find(|a| a.failure_id == f.id);
+ json!({
+ "id": f.id,
+ "attempt": f.attempt,
+ "source": f.source,
+ "class": f.class,
+ "summary": f.summary,
+ "excerpt": f.excerpt,
+ "checkpoint_id": f.checkpoint_id,
+ "created_at": f.created_at,
+ "autofix": a.map_or(Value::Null, attempt_json),
+ })
+ })
+ .collect();
+ Json(json!(list)).into_response()
+}
+
+#[derive(Deserialize, Default)]
+#[serde(deny_unknown_fields)]
+pub struct AutofixBody {
+ pub failure_id: Option<String>,
+}
+
+fn coded(status: StatusCode, code: &str, msg: &str) -> Response {
+ (status, Json(json!({"error": msg, "code": code}))).into_response()
+}
+
+/// `POST /api/tasks/:id/autofix` (person-only, `Idempotency-Key`): runs the suggested retry of a
+/// failure (the last one by default), or plans one and runs it.
+pub async fn run_autofix(State(state): State<AppState>, RawQuery(q): RawQuery, headers: HeaderMap, Path(id): Path<String>, body: Option<Json<AutofixBody>>) -> Response {
+ let body = body.map(|b| b.0).unwrap_or_default();
+ let route = format!("POST /api/tasks/{id}/autofix");
+ super::graph::idempotent(&state, &headers, route, || async {
+ let t = load_task(&state, q.as_deref(), &id).await?;
+ let failures = state.db.failures_of(&t.id).await.map_err(internal)?;
+ let failure = match &body.failure_id {
+ Some(fid) => failures.iter().find(|f| &f.id == fid).cloned().ok_or_else(|| not_found("failure"))?,
+ None => failures.last().cloned().ok_or_else(|| coded(StatusCode::CONFLICT, "not_retryable", "the task has no failure to fix"))?,
+ };
+ if t.state != "failed" || matches!(failure.class.as_str(), "auth" | "budget" | "denied" | "needs_input" | "bad_spec") || t.source_kind == "delegation" {
+ return Err(coded(StatusCode::CONFLICT, "not_retryable", "AutoFix can't retry this; see the task's Needs-you item"));
+ }
+ if let Some(code) = limit(&state, &t).await {
+ return Err(coded(StatusCode::CONFLICT, code, limit_reason(code)));
+ }
+ let attempts = state.db.attempts_of(&t.id).await.map_err(internal)?;
+ let live = attempts.iter().find(|a| matches!(a.status.as_str(), "scheduled" | "running"));
+ let a = match (attempts.iter().rev().find(|a| a.failure_id == failure.id && a.status == "suggested"), live) {
+ (_, Some(live)) => live.clone(),
+ (Some(s), None) => {
+ if !state.db.move_attempt(s, "suggested", "scheduled", Some("the person asked for this retry")).await.map_err(internal)? {
+ return Err(conflict("the retry changed meanwhile; look at it again"));
+ }
+ state.db.get_attempt(&s.id).await.map_err(internal)?.ok_or_else(|| not_found("autofix"))?
+ }
+ (None, None) => {
+ let strategy = match strategy_for(&failure.class) {
+ "none" => "retry_same",
+ s => s,
+ };
+ let new = NewAttempt {
+ task: &t,
+ failure_id: &failure.id,
+ strategy,
+ idempotency_key: key(&t.id, &failure.id, strategy),
+ status: "scheduled",
+ not_before: None,
+ reason: "the person asked for this retry".into(),
+ };
+ match state.db.insert_attempt(&new).await {
+ Ok(Some(a)) => a,
+ Ok(None) => return Err(coded(StatusCode::CONFLICT, "not_retryable", "this failure was retried that way already")),
+ Err(e) => return Err(conflict(e.to_string())),
+ }
+ }
+ };
+ // The person asked now: no waiting for a backoff
+ if a.status == "scheduled" && !busy(&state, &t.id).await {
+ let now = Attempt { not_before: None, ..a.clone() };
+ execute(&state, &now).await;
+ } else if a.status == "scheduled" {
+ soon(&state, &Attempt { not_before: None, ..a.clone() });
+ }
+ let a = state.db.get_attempt(&a.id).await.map_err(internal)?.unwrap_or(a);
+ Ok(attempt_json(&a))
+ })
+ .await
+}
+
+/// `POST /api/tasks/:id/autofix/:aid/cancel` (person-only): a planned retry won't run.
+pub async fn cancel_autofix(State(state): State<AppState>, RawQuery(q): RawQuery, Path((id, aid)): Path<(String, String)>) -> Response {
+ let t = match load_task(&state, q.as_deref(), &id).await {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ let a = match state.db.get_attempt(&aid).await {
+ Ok(Some(a)) if a.task_id == t.id => a,
+ Ok(_) => return not_found("autofix"),
+ Err(e) => return internal(e),
+ };
+ if !matches!(a.status.as_str(), "scheduled" | "suggested") {
+ return conflict("only a planned retry can be cancelled");
+ }
+ match state.db.move_attempt(&a, &a.status, "skipped", Some("cancelled by the person")).await {
+ Ok(true) => {}
+ Ok(false) => return conflict("the retry changed meanwhile; look at it again"),
+ Err(e) => return internal(e),
+ }
+ emit_task(&state, &t).await;
+ let a = state.db.get_attempt(&aid).await.ok().flatten().unwrap_or(a);
+ Json(attempt_json(&a)).into_response()
+}
+
+async fn change_json(state: &AppState, c: &WorkflowChange) -> Value {
+ let parse = |s: &str| serde_json::from_str::<Value>(s).unwrap_or(Value::Null);
+ json!({
+ "id": c.id,
+ "task_id": c.task_id,
+ "routine_id": c.routine_id,
+ "target": c.target,
+ "before": parse(&c.before),
+ "after": parse(&c.after),
+ "reason": c.reason,
+ "proposed_by": c.proposed_by,
+ "proposed_by_name": super::name_of(state, Some(&c.proposed_by)).await,
+ "status": c.status,
+ "decided_at": c.decided_at,
+ "created_at": c.created_at,
+ })
+}
+
+/// `GET /api/workflow-changes?status=proposed` (person-only).
+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})"));
+ }
+ match state.db.list_changes(status.as_deref(), None).await {
+ Ok(list) => {
+ let mut out = Vec::new();
+ for c in &list {
+ out.push(change_json(&state, c).await);
+ }
+ Json(json!(out)).into_response()
+ }
+ Err(e) => internal(e),
+ }
+}
+
+/// `POST /api/workflow-changes/:id/approve` (person-only): approves and applies it once.
+pub async fn approve_change(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ decide(&state, &id, true).await
+}
+
+/// `POST /api/workflow-changes/:id/reject` (person-only).
+pub async fn reject_change(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ decide(&state, &id, false).await
+}
+
+async fn decide(state: &AppState, id: &str, approve: bool) -> Response {
+ let c = match state.db.get_change(id).await {
+ Ok(Some(c)) => c,
+ Ok(None) => return not_found("workflow change"),
+ Err(e) => return internal(e),
+ };
+ let to = if approve { "approved" } else { "rejected" };
+ match state.db.decide_change(&c, to).await {
+ Ok(true) => {}
+ Ok(false) => return conflict(format!("this change is {} already", c.status)),
+ Err(e) => return internal(e),
+ }
+ if approve {
+ let write = change_write(state, &c).await;
+ if let Err(e) = state.db.apply_change(&c, &write).await {
+ return internal(e);
+ }
+ }
+ if let Some(t) = &c.task_id {
+ super::emit_task_id(state, t).await;
+ }
+ let c = state.db.get_change(id).await.ok().flatten().unwrap_or(c);
+ Json(change_json(state, &c).await).into_response()
+}
+
+/// What applying `c` writes, if its target still holds `before`.
+async fn change_write(state: &AppState, c: &WorkflowChange) -> ChangeWrite {
+ let before: Value = serde_json::from_str(&c.before).unwrap_or(Value::Null);
+ let after: Value = serde_json::from_str(&c.after).unwrap_or(Value::Null);
+ let task = match &c.task_id {
+ Some(t) => state.db.get_task(t).await.ok().flatten(),
+ None => None,
+ };
+ match c.target.as_str() {
+ "routine_instructions" | "routine_schedule" => {
+ let Some(rid) = &c.routine_id else { return ChangeWrite::Stale };
+ let Ok(Some(r)) = state.db.get_routine(rid).await else { return ChangeWrite::Stale };
+ if c.target == "routine_instructions" {
+ let (Some(b), Some(a)) = (before["instructions"].as_str(), after["instructions"].as_str()) else { return ChangeWrite::Stale };
+ if r.instructions != b {
+ return ChangeWrite::Stale;
+ }
+ return ChangeWrite::RoutineInstructions { routine_id: rid.clone(), before: b.into(), after: a.into() };
+ }
+ let Ok(schedule) = serde_json::from_value::<crate::routines::Schedule>(after["schedule"].clone()) else { return ChangeWrite::Stale };
+ if schedule.validate().is_err() || serde_json::from_str::<Value>(&r.schedule).ok() != Some(before["schedule"].clone()) {
+ return ChangeWrite::Stale;
+ }
+ let schedule = schedule.canonical();
+ let next_run_at = if r.enabled { schedule.next_after(Utc::now(), r.last_run_at) } else { r.next_run_at };
+ let after = serde_json::to_string(&schedule).unwrap_or_default();
+ ChangeWrite::RoutineSchedule { routine_id: rid.clone(), before: r.schedule.clone(), after, next_run_at }
+ }
+ "check_spec" => {
+ let Some(cid) = before["check_id"].as_str() else { return ChangeWrite::Stale };
+ let Ok(Some(check)) = state.db.get_check(cid).await else { return ChangeWrite::Stale };
+ if check.spec_value() != before["spec"] || check.required != before["required"].as_bool().unwrap_or(check.required) {
+ return ChangeWrite::Stale;
+ }
+ let after_spec = after.get("spec").cloned().unwrap_or_else(|| check.spec_value());
+ if super::validate_check(&check.kind, &after_spec, true).is_err() {
+ return ChangeWrite::Stale;
+ }
+ ChangeWrite::CheckSpec {
+ check_id: cid.into(),
+ before_spec: check.spec.clone(),
+ before_required: check.required,
+ after_spec: after_spec.to_string(),
+ after_required: after["required"].as_bool().unwrap_or(check.required),
+ }
+ }
+ "task_acceptance" => {
+ let (Some(t), Some(b), Some(a)) = (task, before["acceptance"].as_str(), after["acceptance"].as_str()) else { return ChangeWrite::Stale };
+ if t.acceptance != b {
+ return ChangeWrite::Stale;
+ }
+ ChangeWrite::Acceptance { task_id: t.id, before: b.into(), after: a.into() }
+ }
+ "max_attempts" => {
+ let (Some(t), Some(b), Some(a)) = (task, before["max_attempts"].as_i64(), after["max_attempts"].as_i64()) else { return ChangeWrite::Stale };
+ if t.max_attempts != b || !(1..=10).contains(&a) {
+ return ChangeWrite::Stale;
+ }
+ ChangeWrite::MaxAttempts { task_id: t.id, before: b, after: a }
+ }
+ _ => ChangeWrite::Stale,
+ }
+}
+
+/// The bot tool `workflow_propose`: only ever a `proposed` row. `before` is read here, never
+/// taken from the bot.
+pub async fn propose(state: &AppState, bot_id: &str, args: &Value) -> Result<Value, String> {
+ let target = args["target"].as_str().unwrap_or("");
+ if !TARGETS.contains(&target) {
+ return Err(format!("target must be one of {}", TARGETS.join(", ")));
+ }
+ let reason = args["reason"].as_str().map(str::trim).filter(|r| !r.is_empty()).ok_or("reason is required")?;
+ let reason: String = reason.chars().take(1000).collect();
+ let after = &args["after"];
+ let task = match args["task_id"].as_str() {
+ Some(t) => Some(state.db.get_task(t).await.map_err(|e| e.to_string())?.ok_or("no such task")?),
+ None => None,
+ };
+ let (routine_id, before, after) = match target {
+ "routine_instructions" | "routine_schedule" => {
+ let rid = args["routine_id"].as_str().ok_or("routine_id is required for a routine change")?;
+ let r = state.db.get_routine(rid).await.map_err(|e| e.to_string())?.ok_or("no such routine")?;
+ if target == "routine_instructions" {
+ let a = after.as_str().ok_or("after must be the new instructions (a string)")?;
+ (Some(rid.to_string()), json!({"instructions": r.instructions}), json!({"instructions": a.chars().take(20_000).collect::<String>()}))
+ } else {
+ let s = serde_json::from_value::<crate::routines::Schedule>(after.clone()).map_err(|e| format!("after must be a schedule: {e}"))?;
+ s.validate()?;
+ let before = serde_json::from_str::<Value>(&r.schedule).unwrap_or(Value::Null);
+ (Some(rid.to_string()), json!({"schedule": before}), json!({"schedule": after}))
+ }
+ }
+ "check_spec" => {
+ let t = task.as_ref().ok_or("task_id is required for a check change")?;
+ let 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());
+ 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}))
+ }
+ "task_acceptance" => {
+ let t = task.as_ref().ok_or("task_id is required")?;
+ let a = after.as_str().ok_or("after must be the new acceptance (a string)")?;
+ (None, json!({"acceptance": t.acceptance}), json!({"acceptance": a.chars().take(4000).collect::<String>()}))
+ }
+ _ => {
+ let t = task.as_ref().ok_or("task_id is required")?;
+ let a = after.as_i64().filter(|n| (1..=10).contains(n)).ok_or("after must be a number 1–10")?;
+ (None, json!({"max_attempts": t.max_attempts}), json!({"max_attempts": a}))
+ }
+ };
+ let c = state.db.propose_change(task.as_ref(), routine_id.as_deref(), target, &before, &after, &reason, bot_id).await.map_err(|e| e.to_string())?;
+ if let Some(t) = &task {
+ emit_task(state, t).await;
+ }
+ 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();
+ 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/graph.rs b/src/server/missions/graph.rs
index 31d698e3..01867479 100644
--- a/src/server/missions/graph.rs
+++ b/src/server/missions/graph.rs
@@ -364,6 +364,8 @@ pub async fn resolve_flag(
return Err(conflict("this flag is already resolved"));
}
let mut fork_out = None;
+ let mut claimed = false;
+ let flag_claim = (flag.id.clone(), p.resolution.clone(), note.clone());
match (p.resolution.as_str(), t.state.as_str()) {
("still_valid", _) => {}
("redo", "working" | "needs_you") => return Err(conflict("it's running; resolve when it stops")),
@@ -374,14 +376,28 @@ pub async fn resolve_flag(
let claim = FlagClaim { id: &flag.id, resolution: &p.resolution, note: note.as_deref() };
fork_out = Some(fork(&state, &t, &reason, Some(&claim)).await?);
}
+ // The move claims the flag first, in its own transaction (D12): of two racing
+ // resolves one moves the task and the other gets a 409
("redo", from @ ("review" | "failed")) => {
- let change = TaskChange { reason: Some("redo: it may no longer hold".into()), detail: Some(json!({"flag_id": flag.id})), ..Default::default() };
- moved(transition(&state, &t.id, from, "ready", Actor::Person, "person", change).await)?;
+ let change = TaskChange {
+ reason: Some("redo: it may no longer hold".into()),
+ detail: Some(json!({"flag_id": flag.id})),
+ flag: Some(flag_claim.clone()),
+ ..Default::default()
+ };
+ claimed_move(&state, &flag.id, transition(&state, &t.id, from, "ready", Actor::Person, "person", change).await).await?;
+ claimed = true;
let _ = state.db.reset_attempts(&t.id).await;
}
("redo", "blocked") => {
- let change = TaskChange { reason: Some("redo: it may no longer hold".into()), detail: Some(json!({"flag_id": flag.id})), ..Default::default() };
- let t = moved(transition(&state, &t.id, "blocked", "backlog", Actor::Person, "person", change).await)?;
+ let change = TaskChange {
+ reason: Some("redo: it may no longer hold".into()),
+ detail: Some(json!({"flag_id": flag.id})),
+ flag: Some(flag_claim.clone()),
+ ..Default::default()
+ };
+ let t = claimed_move(&state, &flag.id, transition(&state, &t.id, "blocked", "backlog", Actor::Person, "person", change).await).await?;
+ claimed = true;
super::promote_one(&state, &t).await;
}
// backlog or ready: it runs again anyway
@@ -389,12 +405,17 @@ pub async fn resolve_flag(
("cancelled", "verified") => return Err(conflict("a verified task can't be cancelled; choose still_valid or redo")),
("cancelled", "cancelled") => {}
("cancelled", from) => {
- let change = TaskChange { reason: Some("cancelled by the person: it may no longer hold".into()), ..Default::default() };
- moved(transition(&state, &t.id, from, "cancelled", Actor::Person, "person", change).await)?;
+ let change = TaskChange {
+ reason: Some("cancelled by the person: it may no longer hold".into()),
+ flag: Some(flag_claim.clone()),
+ ..Default::default()
+ };
+ claimed_move(&state, &flag.id, transition(&state, &t.id, from, "cancelled", Actor::Person, "person", change).await).await?;
+ claimed = true;
}
_ => return Err(bad("resolution must be still_valid, redo or cancelled")),
}
- if fork_out.is_none() {
+ if fork_out.is_none() && !claimed {
match state.db.resolve_flag(&flag.id, &p.resolution, note.as_deref(), None).await {
Ok(true) => {}
Ok(false) => return Err(conflict("this flag is already resolved")),
@@ -416,6 +437,15 @@ pub async fn resolve_flag(
.await
}
+/// A move that claimed `flag_id` first: when it didn't happen because the flag was resolved
+/// meanwhile, that's the 409 to give.
+async fn claimed_move(state: &AppState, flag_id: &str, r: Result<Task, super::MoveError>) -> Result<Task, Response> {
+ if matches!(r, Err(super::MoveError::Stale)) && state.db.get_flag(flag_id).await.ok().flatten().is_some_and(|f| f.resolved_at.is_some()) {
+ return Err(conflict("this flag is already resolved"));
+ }
+ moved(r)
+}
+
/// `GET /api/tasks/:id/flags` (open ones; `?all=1` adds resolved ones).
pub async fn task_flags(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
let t = match load_task(&state, q.as_deref(), &id).await {
diff --git a/src/server/missions/listener.rs b/src/server/missions/listener.rs
index d1e4fc51..ab0afe7a 100644
--- a/src/server/missions/listener.rs
+++ b/src/server/missions/listener.rs
@@ -147,25 +147,28 @@ async fn hold(state: &AppState, task: &Task, owner: &str, context_id: &str) {
}
}
-/// The source finished: to review (and its checks), failed, cancelled or back to ready.
-async fn finish(state: &AppState, task: &Task, to: &str, why: &str) {
+/// The source finished: to review (and its checks), failed, cancelled or back to ready. Whether
+/// the task moved.
+async fn finish(state: &AppState, task: &Task, to: &str, why: &str) -> bool {
let mut from = task.state.clone();
if !matches!(from.as_str(), "working" | "needs_you") {
- return;
+ return false;
}
if to == "review" && from == "needs_you" {
// review is reached from working only
let _ = state.db.refresh_claim(&task.id, lease_ms(state).await).await;
let change = TaskChange { reason: Some(why.into()), ..Default::default() };
if transition(state, &task.id, "needs_you", "working", Actor::Kwant, "kwant", change).await.is_err() {
- return;
+ return false;
}
from = "working".into();
}
let change = TaskChange { reason: Some(why.into()), ..Default::default() };
- if transition(state, &task.id, &from, to, Actor::Kwant, "kwant", change).await.is_ok() && to == "review" {
+ let moved = transition(state, &task.id, &from, to, Actor::Kwant, "kwant", change).await.is_ok();
+ if moved && to == "review" {
run_task_checks(state, &task.id, None).await;
}
+ moved
}
pub async fn on_delegation(state: &AppState, delegation_id: &str) {
@@ -189,10 +192,21 @@ pub async fn on_delegation(state: &AppState, delegation_id: &str) {
// Still going: keep kwant's lease on it
let _ = state.db.refresh_claim(&t.id, lease_ms(state).await).await;
}
- (Some(t), "completed") => finish(state, &t, "review", "the hand-off finished").await,
- (Some(t), "failed") => finish(state, &t, "failed", d.error.as_deref().unwrap_or("the hand-off failed")).await,
- (Some(t), "cancelled") => finish(state, &t, "cancelled", "the hand-off was cancelled").await,
- (Some(t), "interrupted") => finish(state, &t, "ready", "a restart interrupted the hand-off").await,
+ (Some(t), "completed") => {
+ finish(state, &t, "review", "the hand-off finished").await;
+ }
+ (Some(t), "failed") => {
+ let why = d.error.as_deref().unwrap_or("the hand-off failed");
+ if finish(state, &t, "failed", why).await {
+ super::autofix::record(state, &t.id, "handoff", "error", why, why.lines().next().unwrap_or(why)).await;
+ }
+ }
+ (Some(t), "cancelled") => {
+ finish(state, &t, "cancelled", "the hand-off was cancelled").await;
+ }
+ (Some(t), "interrupted") => {
+ finish(state, &t, "ready", "a restart interrupted the hand-off").await;
+ }
_ => {}
}
}
@@ -216,8 +230,15 @@ pub async fn on_routine_run(state: &AppState, routine_id: &str, run_id: &str, st
(Some(t), "running") => {
let _ = state.db.refresh_claim(&t.id, lease_ms(state).await).await;
}
- (Some(t), "ok") => finish(state, &t, "review", "the routine run finished").await,
- (Some(t), "error") => finish(state, &t, "failed", "the routine run failed").await,
+ (Some(t), "ok") => {
+ finish(state, &t, "review", "the routine run finished").await;
+ }
+ (Some(t), "error") => {
+ if finish(state, &t, "failed", "the routine run failed").await {
+ 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/mod.rs b/src/server/missions/mod.rs
index 79ae26cf..ac39b760 100644
--- a/src/server/missions/mod.rs
+++ b/src/server/missions/mod.rs
@@ -12,6 +12,7 @@
//! - nothing here widens a bot's permissions: the bot tools only touch the board, `command` checks
//! a bot adds run only after the person approves them, and person actions are person-only routes.
+pub mod autofix;
pub mod checkpoints;
pub mod checks;
pub mod graph;
@@ -91,6 +92,8 @@ pub enum Actor {
Person,
/// kwant itself: checks, leases, hand-offs, routine runs, cards.
Kwant,
+ /// AutoFix, retrying a failed task (Phase B3): only `failed → ready`.
+ AutoFix,
}
/// Whether `actor` may move a task from `from` to `to`. Conditions beyond the pair (live claim,
@@ -113,7 +116,7 @@ pub fn allowed(from: &str, to: &str, actor: Actor) -> bool {
("review", "verified") => actor == Kwant,
("review", "ready") => matches!(actor, Kwant | Person),
("review", "failed") => actor == Kwant,
- ("failed", "ready") => actor == Person,
+ ("failed", "ready") => matches!(actor, Person | AutoFix),
(_, "cancelled") => open && matches!(actor, Person | Kwant),
_ => false,
}
@@ -188,6 +191,9 @@ pub async fn transition(
}
async fn after_move(state: &AppState, task: &Task, to: &str) {
+ autofix::settle(state, task, to).await;
+ // A task parked for AutoFix isn't done failing: no "failed" line until it is
+ let to = if to == "failed" && autofix::parked(state, task).await { "parked" } else { to };
let Some(mid) = task.mission_id.clone() else {
if matches!(to, "verified" | "failed") {
task_chat_line(state, task, None).await;
@@ -336,9 +342,18 @@ pub async fn evaluate(state: &AppState, task_id: &str) -> Option<Task> {
}
Verdict::Fail(why) => {
let last = task.attempts + 1 >= task.max_attempts;
- let to = if last { "failed" } else { "ready" };
- let change = TaskChange { reason: Some(why), attempt: true, ..Default::default() };
- transition(state, task_id, "review", to, Actor::Kwant, "kwant", change).await.ok().or(Some(task))
+ let to = if last || autofix::parks(state, &task, true).await { "failed" } else { "ready" };
+ let change = TaskChange { reason: Some(why.clone()), attempt: true, ..Default::default() };
+ let moved = transition(state, task_id, "review", to, Actor::Kwant, "kwant", change).await.ok();
+ 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(""));
+ autofix::record(state, task_id, "check", &c.status, &text, &why).await;
+ }
+ }
+ let task = state.db.get_task(task_id).await.ok().flatten().or(moved).unwrap_or(task);
+ Some(task)
}
Verdict::Waiting => Some(task),
}
@@ -400,6 +415,7 @@ pub async fn spend(state: &AppState, kwant_id: &str, context_id: &str, turn_id:
if state.db.spend_on_task(&claim.task_id, due).await.is_err() {
return;
}
+ 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") {
@@ -409,7 +425,10 @@ pub async fn spend(state: &AppState, kwant_id: &str, context_id: &str, turn_id:
detail: Some(json!({"spent_tokens": task.spent_tokens, "budget_tokens": task.budget_tokens})),
..Default::default()
};
- let _ = transition(state, &task.id, &task.state, "blocked", Actor::Kwant, "kwant", change).await;
+ if transition(state, &task.id, &task.state, "blocked", Actor::Kwant, "kwant", change).await.is_ok() {
+ let summary = format!("over budget: {} of {} tokens", task.spent_tokens, task.budget_tokens);
+ autofix::record(state, &task.id, "budget", "error", &summary, &summary).await;
+ }
} else {
emit_task(state, &task).await;
}
@@ -432,6 +451,7 @@ pub async fn spend_at_hand_in(state: &AppState, task_id: &str, turn_id: Option<&
if state.db.spend_on_task(task_id, tokens).await.is_err() {
return;
}
+ autofix::spend_on_claim(state, task_id, None, tokens).await;
if let Ok(Some(task)) = state.db.get_task(task_id).await {
emit_task(state, &task).await;
if let Some(m) = &task.mission_id {
@@ -440,13 +460,16 @@ pub async fn spend_at_hand_in(state: &AppState, task_id: &str, turn_id: Option<&
}
}
-/// Working tasks whose lease ran out go back to ready (one attempt used).
+/// Working tasks whose lease ran out go back to ready (one attempt used), or park in `failed` for
+/// AutoFix.
pub async fn sweep_leases(state: &AppState) -> usize {
let mut n = 0;
for t in state.db.expired_working().await.unwrap_or_default() {
let change = TaskChange { kind: "lease_expired".into(), reason: Some("the lease ran out".into()), attempt: true, ..Default::default() };
- if transition(state, &t.id, "working", "ready", Actor::Kwant, "kwant", change).await.is_ok() {
+ let to = if autofix::parks(state, &t, true).await { "failed" } else { "ready" };
+ if transition(state, &t.id, "working", to, Actor::Kwant, "kwant", change).await.is_ok() {
n += 1;
+ autofix::record(state, &t.id, "lease", "stalled", "", "the lease ran out").await;
}
}
n
@@ -466,6 +489,7 @@ pub(crate) async fn name_of(state: &AppState, id: Option<&str>) -> Option<String
/// steps) or, in review, check approvals; then, in every state, its open "may be invalid" flags.
pub async fn needs_you(state: &AppState, task: &Task) -> Vec<Value> {
let mut items = owner_needs_you(state, task).await;
+ items.extend(autofix::needs_you(state, task).await);
items.extend(graph::flag_items(state, task).await);
items
}
@@ -530,6 +554,7 @@ pub async fn task_json(state: &AppState, task: &Task) -> Value {
let (count, last) = state.db.checkpoint_stats(&task.id).await.unwrap_or((0, None));
obj.insert("checkpoint_count".into(), json!(count));
obj.insert("last_checkpoint_at".into(), json!(last));
+ autofix::extend_task_json(state, task, obj).await;
}
v
}
@@ -966,6 +991,7 @@ mod tests {
finished_at: None,
forked_from: None,
held_at: None,
+ recovery_spent_tokens: 0,
}
}
diff --git a/src/server/missions/routes.rs b/src/server/missions/routes.rs
index 37d657c9..2183ebf9 100644
--- a/src/server/missions/routes.rs
+++ b/src/server/missions/routes.rs
@@ -324,6 +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;
Json(json!({
"verified_7d": verified.len(),
"false_success_7d": false_success,
@@ -333,6 +334,8 @@ pub async fn insights(State(state): State<AppState>, Scope(space): Scope) -> Res
"interventions_7d": interventions,
"tokens_7d": tokens,
"tokens_per_verified_7d": per,
+ "autofix_7d": autofix_7d,
+ "failures_by_class_7d": failures_by_class_7d,
}))
.into_response()
}
diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rs
index 5d375cd1..22ba7490 100644
--- a/src/server/missions/runner.rs
+++ b/src/server/missions/runner.rs
@@ -51,6 +51,8 @@ pub async fn tick(state: &AppState) {
// Sources first, so a live hand-off or routine refreshes kwant's lease before the sweep
super::listener::reconcile(state).await;
super::sweep_leases(state).await;
+ // AutoFix retries whose time has come, before tasks are picked (Phase B3)
+ super::autofix::run_due(state).await;
for m in state.db.active_missions().await.unwrap_or_default() {
// Evidence drift, at most every 10 minutes per mission (Phase B1)
super::graph::scan_if_due(state, &m).await;
@@ -156,6 +158,7 @@ async fn prompt(state: &AppState, m: &Mission, t: &Task) -> String {
}
async fn run_one(state: &AppState, m: &Mission, task: &Task, bot: &crate::db::models::Kwant) {
+ let started = chrono::Utc::now();
let context = mission_context(m, bot);
let job = state.turns.start_job([context.clone()]);
let (channel, thread) = mission_place(m, bot);
@@ -163,7 +166,10 @@ async fn run_one(state: &AppState, m: &Mission, task: &Task, bot: &crate::db::mo
Ok(scope) => {
let mut opts = TurnOpts::default();
(opts.unsaved, opts.quiet_failure, opts.purpose) = (true, true, Some(PURPOSE.into()));
- let p = prompt(state, m, task).await;
+ let mut p = prompt(state, m, task).await;
+ if let Some(note) = super::autofix::retry_note(state, task).await {
+ p.push_str(&note);
+ }
turn_once(&scope, bot, p, opts).await
}
Err(e) => Err(e),
@@ -171,22 +177,46 @@ async fn run_one(state: &AppState, m: &Mission, task: &Task, bot: &crate::db::mo
if let Err(e) = &reply {
tracing::info!(task_id = %task.id, error = %e, "mission runner turn ended without a reply");
}
- // Still working after the turn: the bot didn't finish or let go, so the lease is released
- if let Ok(Some(t)) = state.db.get_task(&task.id).await {
- if t.state == "working" {
- let change = TaskChange {
- kind: "released".into(),
- reason: Some("the runner turn ended without a review".into()),
- attempt: true,
- ..Default::default()
- };
- let _ = transition(state, &t.id, "working", "ready", Actor::Kwant, "kwant", change).await;
- if let Ok(Some(t)) = state.db.get_task(&task.id).await {
- if t.attempts >= t.max_attempts && t.state == "ready" {
- let change = TaskChange { reason: Some("no review after its last attempt".into()), ..Default::default() };
- let _ = transition(state, &t.id, "ready", "blocked", Actor::Kwant, "kwant", change).await;
- }
+ let err = reply.as_ref().err().map(ToString::to_string);
+ after_turn(state, &task.id, err.as_deref(), started).await;
+}
+
+/// 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
+/// `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 };
+ if t.state == "needs_you" {
+ super::autofix::record(state, &t.id, "turn", "needs_input", "", "the bot is waiting on the person").await;
+ return;
+ }
+ if t.state != "working" {
+ return;
+ }
+ let park = super::autofix::parks(state, &t, true).await;
+ let change = TaskChange {
+ kind: "released".into(),
+ reason: Some("the runner turn ended without a review".into()),
+ attempt: true,
+ ..Default::default()
+ };
+ let to = if park { "failed" } else { "ready" };
+ if transition(state, &t.id, "working", to, Actor::Kwant, "kwant", change).await.is_err() {
+ return;
+ }
+ if !park {
+ if let Ok(Some(t)) = state.db.get_task(task_id).await {
+ if t.attempts >= t.max_attempts && t.state == "ready" {
+ let change = TaskChange { reason: Some("no review after its last attempt".into()), ..Default::default() };
+ let _ = transition(state, &t.id, "ready", "blocked", Actor::Kwant, "kwant", change).await;
}
}
}
+ let denied = state.db.denied_since(task_id, started).await.unwrap_or_default();
+ match (err, denied) {
+ (Some(e), _) => super::autofix::record(state, task_id, "turn", "error", e, e.lines().next().unwrap_or("the turn failed")).await,
+ (None, Some(what)) => super::autofix::record(state, task_id, "turn", "denied", &what, &format!("denied: {what}")).await,
+ (None, None) => super::autofix::record(state, task_id, "turn", "stalled", "", "the runner turn ended without a review").await,
+ };
}
diff --git a/src/server/missions/tools.rs b/src/server/missions/tools.rs
index b9d6f0c2..758fbd34 100644
--- a/src/server/missions/tools.rs
+++ b/src/server/missions/tools.rs
@@ -21,7 +21,7 @@ fn ok(v: Value) -> ToolResult {
(serde_json::to_string_pretty(&v).unwrap_or_default(), false)
}
-const NAMES: [&str; 7] = ["mission_plan", "task_list", "task_claim", "task_update", "task_attach_evidence", "task_request_check", "task_review"];
+const NAMES: [&str; 8] = ["mission_plan", "task_list", "task_claim", "task_update", "task_attach_evidence", "task_request_check", "task_review", "workflow_propose"];
pub fn handles(name: &str) -> bool {
NAMES.contains(&name)
@@ -148,6 +148,21 @@ pub fn tools() -> Vec<Value> {
"required": ["task_id", "verdict", "note"],
},
}),
+ json!({
+ "name": "workflow_propose",
+ "description": "Propose a lasting fix after a failure: a routine's instructions or schedule, a check's spec, a task's acceptance or max attempts. It is only a proposal: the person approves or rejects it, and nothing changes until they approve.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "target": {"type": "string", "enum": crate::db::autofix::TARGETS},
+ "routine_id": {"type": "string", "description": "For routine_instructions and routine_schedule."},
+ "task_id": {"type": "string", "description": "For check_spec, task_acceptance and max_attempts."},
+ "after": {"description": "The new value: instructions or acceptance (string), a schedule (object), {check_id, spec?, required?} for a check, or a number 1–10 for max_attempts."},
+ "reason": {"type": "string", "description": "Why, in a sentence: what failed and how this fixes it."},
+ },
+ "required": ["target", "after", "reason"],
+ },
+ }),
]
}
@@ -165,6 +180,22 @@ pub async fn call(state: &AppState, scope: &SelfScope, name: &str, args: &Value)
if name == "task_list" {
return list(state, scope, &space, args).await;
}
+ if name == "workflow_propose" {
+ if let Some(t) = args["task_id"].as_str() {
+ if !matches!(state.db.get_task(t).await, Ok(Some(t)) if t.space_id == space.as_str()) {
+ return fail("No such task in your space.");
+ }
+ }
+ if let Some(r) = args["routine_id"].as_str() {
+ if !matches!(state.db.get_routine(r).await, Ok(Some(r)) if r.space_id == space.as_str()) {
+ return fail("No such routine in your space.");
+ }
+ }
+ return match super::autofix::propose(state, &scope.kwant_id, args).await {
+ Ok(v) => ok(v),
+ Err(e) => fail(e),
+ };
+ }
let Some(task_id) = args["task_id"].as_str().map(str::trim).filter(|s| !s.is_empty()) else {
return fail("task_id is required.");
};
@@ -258,12 +289,16 @@ async fn claim(state: &AppState, scope: &SelfScope, task: &Task) -> ToolResult {
super::emit_mission(state, m).await;
}
let checks = state.db.list_checks(&t.id).await.unwrap_or_default();
- ok(json!({
+ 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<_>>(),
"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 {
+ out["autofix"] = json!(note.trim());
+ }
+ ok(out)
}
Ok(Err(why)) => fail(format!("Not claimed: {why}.")),
Err(e) => fail(format!("Could not claim: {e}")),
@@ -327,6 +362,7 @@ async fn update(state: &AppState, scope: &SelfScope, task: &Task, args: &Value)
"review" if summary["status"] == "not_checked" => "No checks: it stays in review (not checked) until a teammate reviews it or the person verifies it.",
"review" => "Waiting on checks that need the person's approval.",
"ready" => "A check failed; the task is back in ready. Fix it and claim it again.",
+ "failed" if after.attempts < after.max_attempts => "A check failed; AutoFix decides whether to retry it (see the task's autofix). Don't claim it again yourself.",
"failed" => "A check failed on the last attempt; the task failed.",
_ => "",
};
diff --git a/src/server/mod.rs b/src/server/mod.rs
index bed21b62..3efe578b 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -379,6 +379,12 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/tasks/:id/checkpoints/:cid/restore-preview", get(missions::checkpoints::preview))
.route("/api/tasks/:id/checkpoints/:cid/restore", post(missions::checkpoints::restore))
.route("/api/tasks/:id/flags", get(missions::graph::task_flags))
+ .route("/api/tasks/:id/failures", get(missions::autofix::task_failures))
+ .route("/api/tasks/:id/autofix", post(missions::autofix::run_autofix))
+ .route("/api/tasks/:id/autofix/:aid/cancel", post(missions::autofix::cancel_autofix))
+ .route("/api/workflow-changes", get(missions::autofix::list_changes))
+ .route("/api/workflow-changes/:id/approve", post(missions::autofix::approve_change))
+ .route("/api/workflow-changes/:id/reject", post(missions::autofix::reject_change))
.route("/api/tasks/:id/flags/:flag_id/resolve", post(missions::graph::resolve_flag))
.route("/api/tasks/:id/checks", post(missions::routes::add_task_check))
.route("/api/tasks/:id/checks/run", post(missions::routes::run_task_checks))
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 6e209f54..15b5fdf3 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -3273,6 +3273,10 @@ pub struct SettingsResponse {
pub checkpoint_max_mb: i64,
/// Checkpoints kept per task (1–20), plus its first `before_run`.
pub checkpoint_keep: i64,
+ /// AutoFix: `off` (record failures only), `suggest` (the person starts each retry) or `on`.
+ pub autofix: String,
+ /// Share of a task's budget its AutoFix retries may spend (0–100).
+ pub recovery_budget_pct: i64,
}
/// Unknown keys are refused, so a typo or a key from another version fails loudly instead of
@@ -3311,6 +3315,8 @@ pub struct SaveSettingsPayload {
pub checkpoints: Option<bool>,
pub checkpoint_max_mb: Option<i64>,
pub checkpoint_keep: Option<i64>,
+ pub autofix: Option<String>,
+ pub recovery_budget_pct: Option<i64>,
}
pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {
@@ -3358,6 +3364,8 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settings
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,
+ autofix: super::missions::autofix::mode(&state).await.into(),
+ recovery_budget_pct: super::missions::autofix::recovery_pct(&state).await,
}))
}
@@ -3410,6 +3418,9 @@ pub async fn save_settings(
if let Some(e) = super::missions::checkpoints::settings_error(payload.checkpoint_max_mb, payload.checkpoint_keep) {
return bad(e);
}
+ if let Some(e) = super::missions::autofix::settings_error(payload.autofix.as_deref(), payload.recovery_budget_pct) {
+ return bad(e);
+ }
if payload.chain_token_budget.is_some_and(|n| n > super::budget::MAX) {
return bad(format!("chain_token_budget must be 0–{}", super::budget::MAX));
}
@@ -3517,6 +3528,12 @@ pub async fn save_settings(
if let Some(n) = payload.checkpoint_keep {
let _ = state.db.set_setting(super::missions::checkpoints::KEEP_SETTING, &n.to_string()).await;
}
+ if let Some(m) = &payload.autofix {
+ let _ = state.db.set_setting(super::missions::autofix::SETTING, m).await;
+ }
+ if let Some(n) = payload.recovery_budget_pct {
+ let _ = state.db.set_setting(super::missions::autofix::PCT_SETTING, &n.to_string()).await;
+ }
if let Some(on) = payload.agent_tools {
let _ = state.db.set_setting("agent_tools", if on { "on" } else { "off" }).await;
}