Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Swarm Auditor, off by default (Phase D2)
Lin (kwant bot)cbe6c3cee2fd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8d2bd4af..871bca1b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).("56% (27–81%)"), median time and tokens, cost per task and how often you stepped in. Filter by kindof work, bot and period (30 days, 90 days, all time); groups with fewer than 5 tasks say "few tasks".It's report-only and only you can see it.+- **Swarm Auditor (off by default).** With `auditor` on in Settings, a high-priority task, or one no+ outside check will judge, gets one challenge when it reaches review: a teammate outside the owner's+ lead loop lists concrete risks with evidence, the owner answers once, and what stays unresolved is+ listed on the task until you close it. An audit never verifies, fails or moves a task, and "no risks+ raised" isn't a pass. Both turns ask before changing anything; at most 5 audits a day by default.+ `GET /api/tasks/:id/risks`, `GET /api/risks`, `POST /api/tasks/:id/audit`, and+ `POST /api/tasks/:id/risks/:risk_id/resolve`. No screen for it yet.### Fixed- **"Answer in chat" works when that chat is already open.** On the Mission board, "Answer in chat" anddiff --git a/docs/mission-control.md b/docs/mission-control.mdindex b81a163c..0dd78abd 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -681,3 +681,51 @@ with the same rules and inserted as `source = 'backfill'`; rows that exist are n`verified_rate`, `verified_ci95` (Wilson score interval, z = 1.96), `median_latency_ms`,`median_fresh_tokens`, `cost_usd` and `cost_per_task_usd` (over rows with a cost),`interventions_per_task` and `low_confidence` (n < 5). Groups sort by class, then n descending.++## 18. Swarm Auditor (Phase D2)++For high-impact or low-confidence tasks, one teammate challenges with evidence, the owner answers once,+and the risks left unresolved are listed on the task. **An audit never changes verification**: it+never moves a task, never adds or runs a check and never writes a peer review; "no risks raised" is not+a pass. Design note: `phase-d/auditor.md`.++**Settings** (app-wide, like the other Mission Control settings): `auditor` = `off` (default) | `on`;+`auditor_daily_cap` 1–50 (default 5) audits started per UTC day.++**Trigger.** A task entering `review` with an owner, while `auditor` is on, when its priority is high or+urgent (`high_impact`) or no check that counts and isn't the owner's will judge it (`low_confidence`,+`checks_summary.status = not_checked`). The person can start one with `POST /api/tasks/:id/audit`+(`manual`). One audit per task attempt; one audit runs at a time server-wide. A skipped audit (cap,+no challenger) logs `audit_skipped`.++**Challenger.** A bot of the task's space other than the owner, the mission's lead and the lead that+handed the task off. Ranked by verified tasks of the task's class (Performance Market), then fewest+challenges in the last 7 days, then name and id.++**Exchange.** Two hidden turns, each `always_ask` (any call that could change something asks the+person; payments ask in every mode, D8), each capped at 20 minutes:++1. The challenger calls `audit_challenge {audit_id, risks: [{risk, evidence, evidence_ids?}]}` once:+ at most 5 risks, each with evidence (≤1000 chars); `evidence_ids` must be the task's. An empty list+ ends the audit `done` with "no risks raised". No call → the audit ends `failed`.+2. With risks, the owner calls `audit_rebut {audit_id, answers: [{risk_id, stance, answer, evidence?}]}`+ once; `disputed` needs evidence. Unanswered risks stay `open`.++While an audit of a task is `queued`, `challenge` or `rebuttal`, its challenger and owner can't use+`task_claim`, `task_update`, `task_attach_evidence`, `task_request_check` or `task_review` on it.++**Risks** end `open` or `disputed`; both are unresolved. Only the person closes one: `resolved` or+`dismissed`. Tokens of each turn (`model_usage` in the turn's window) are stored per stage.++**Ledger** (`task_events`): `audit_started`, `audit_challenge`, `audit_rebuttal`, `audit_done`,+`audit_skipped`, `risk_resolved`. Audits left running at a restart become `interrupted`.++**API**++- `GET /api/tasks/:id/risks` → `{audits: [{…, risks: [...]}], open_risks}`.+- `GET /api/risks?space=` → `{risks}`: unresolved risks of the space, newest first.+- `POST /api/tasks/:id/audit` (person only) → 202 with the audit; 409 when the auditor is off, the task+ isn't in review or verified, has no owner, its attempt was audited, the cap is reached or nobody can+ challenge.+- `POST /api/tasks/:id/risks/:risk_id/resolve {resolution: "resolved" | "dismissed", note?}` (person+ only); 409 when already closed.diff --git a/src/db/auditor.rs b/src/db/auditor.rsnew file mode 100644index 00000000..dc6a262c--- /dev/null+++ b/src/db/auditor.rs@@ -0,0 +1,414 @@+//! Mission Control Phase D2: the Swarm Auditor's records. One `task_audits` row per audited task+//! attempt (a teammate's challenge and the owner's rebuttal) and its `audit_risks`. An audit never+//! changes a task's state or checks: only outcome checks verify. See docs/mission-control.md §18.++use super::{Database, DbError};+use chrono::{DateTime, Utc};+use serde::Serialize;+use serde_json::Value;+use sqlx::FromRow;++pub const STATUSES: [&str; 7] = ["queued", "challenge", "rebuttal", "done", "skipped", "failed", "interrupted"];+/// Risk statuses; `open` and `disputed` are unresolved.+pub const RISK_STATUSES: [&str; 4] = ["open", "disputed", "resolved", "dismissed"];++#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct Audit {+ pub id: String,+ pub task_id: String,+ pub space_id: String,+ pub attempt: i64,+ /// `high_impact`, `low_confidence` or `manual`.+ pub trigger: String,+ pub challenger_kwant_id: String,+ pub owner_kwant_id: String,+ pub status: String,+ pub reason: Option<String>,+ pub challenge_tokens: i64,+ pub rebuttal_tokens: i64,+ pub created_at: DateTime<Utc>,+ pub finished_at: Option<DateTime<Utc>>,+}++#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct Risk {+ pub id: String,+ pub audit_id: String,+ pub task_id: String,+ pub seq: i64,+ pub risk: String,+ pub evidence: String,+ /// JSON array of evidence ids on the task.+ #[serde(skip)]+ pub evidence_ids: String,+ /// The owner's stance: `disputed` or `accepted`; `None` when it didn't answer.+ pub stance: Option<String>,+ pub answer: Option<String>,+ pub answer_evidence: Option<String>,+ pub status: String,+ pub resolved_by: Option<String>,+ pub resolved_at: Option<DateTime<Utc>>,+ pub note: Option<String>,+ pub created_at: DateTime<Utc>,+}++impl Risk {+ pub fn evidence_ids(&self) -> Vec<String> {+ serde_json::from_str(&self.evidence_ids).unwrap_or_default()+ }++ pub fn unresolved(&self) -> bool {+ matches!(self.status.as_str(), "open" | "disputed")+ }+}++/// A challenge's risk before it's stored.+#[derive(Debug, Clone, PartialEq)]+pub struct NewRisk {+ pub risk: String,+ pub evidence: String,+ pub evidence_ids: Vec<String>,+}++/// The owner's answer to one risk.+#[derive(Debug, Clone, PartialEq)]+pub struct Answer {+ pub risk_id: String,+ pub stance: String,+ pub answer: String,+ pub evidence: Option<String>,+}++fn in_list(list: &[&str]) -> String {+ list.iter().map(|s| format!("'{s}'")).collect::<Vec<_>>().join(", ")+}++impl Database {+ pub(super) async fn migrate_auditor(&self) -> Result<(), DbError> {+ let audits = format!(+ "CREATE TABLE IF NOT EXISTS task_audits (+ id TEXT PRIMARY KEY,+ task_id TEXT NOT NULL,+ space_id TEXT NOT NULL,+ attempt INTEGER NOT NULL,+ trigger TEXT NOT NULL CHECK (trigger IN ('high_impact', 'low_confidence', 'manual')),+ challenger_kwant_id TEXT NOT NULL,+ owner_kwant_id TEXT NOT NULL CHECK (owner_kwant_id <> challenger_kwant_id),+ status TEXT NOT NULL CHECK (status IN ({})),+ reason TEXT,+ challenge_tokens INTEGER NOT NULL DEFAULT 0,+ rebuttal_tokens INTEGER NOT NULL DEFAULT 0,+ created_at TIMESTAMP NOT NULL,+ finished_at TIMESTAMP,+ UNIQUE (task_id, attempt)+ )",+ in_list(&STATUSES)+ );+ let risks = format!(+ "CREATE TABLE IF NOT EXISTS audit_risks (+ id TEXT PRIMARY KEY,+ audit_id TEXT NOT NULL REFERENCES task_audits(id),+ task_id TEXT NOT NULL,+ seq INTEGER NOT NULL,+ risk TEXT NOT NULL,+ evidence TEXT NOT NULL CHECK (length(trim(evidence)) > 0),+ evidence_ids TEXT NOT NULL DEFAULT '[]',+ stance TEXT CHECK (stance IS NULL OR stance IN ('disputed', 'accepted')),+ answer TEXT,+ answer_evidence TEXT,+ status TEXT NOT NULL CHECK (status IN ({})),+ resolved_by TEXT,+ resolved_at TIMESTAMP,+ note TEXT,+ created_at TIMESTAMP NOT NULL,+ UNIQUE (audit_id, seq)+ )",+ in_list(&RISK_STATUSES)+ );+ for stmt in [+ audits.as_str(),+ "CREATE INDEX IF NOT EXISTS task_audits_task ON task_audits (task_id)",+ "CREATE INDEX IF NOT EXISTS task_audits_created ON task_audits (created_at)",+ risks.as_str(),+ "CREATE INDEX IF NOT EXISTS audit_risks_task ON audit_risks (task_id, status)",+ ] {+ sqlx::query(stmt).execute(&self.pool).await?;+ }+ // Audits a restart cut off never finish: say so instead of leaving them running+ sqlx::query(+ "UPDATE task_audits SET status = 'interrupted', reason = 'kwant restarted during the audit', finished_at = ? \+ WHERE status IN ('queued', 'challenge', 'rebuttal')",+ )+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Opens an audit of `task_id`'s `attempt` in `queued`. `None` when that attempt has one.+ #[allow(clippy::too_many_arguments)]+ pub async fn create_audit(+ &self,+ task_id: &str,+ space_id: &str,+ attempt: i64,+ trigger: &str,+ challenger: &str,+ owner: &str,+ ) -> Result<Option<Audit>, DbError> {+ let id = uuid::Uuid::new_v4().to_string();+ let row = sqlx::query_as::<_, Audit>(+ "INSERT INTO task_audits (id, task_id, space_id, attempt, trigger, challenger_kwant_id, owner_kwant_id, status, created_at) \+ VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', ?) ON CONFLICT(task_id, attempt) DO NOTHING RETURNING *",+ )+ .bind(&id)+ .bind(task_id)+ .bind(space_id)+ .bind(attempt)+ .bind(trigger)+ .bind(challenger)+ .bind(owner)+ .bind(Utc::now())+ .fetch_optional(&self.pool)+ .await?;+ Ok(row)+ }++ pub async fn get_audit(&self, id: &str) -> Result<Option<Audit>, DbError> {+ Ok(sqlx::query_as::<_, Audit>("SELECT * FROM task_audits WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)+ }++ pub async fn audits_of(&self, task_id: &str) -> Result<Vec<Audit>, DbError> {+ Ok(sqlx::query_as::<_, Audit>("SELECT * FROM task_audits WHERE task_id = ? ORDER BY created_at, rowid").bind(task_id).fetch_all(&self.pool).await?)+ }++ pub async fn audit_of_attempt(&self, task_id: &str, attempt: i64) -> Result<Option<Audit>, DbError> {+ Ok(sqlx::query_as::<_, Audit>("SELECT * FROM task_audits WHERE task_id = ? AND attempt = ?")+ .bind(task_id)+ .bind(attempt)+ .fetch_optional(&self.pool)+ .await?)+ }++ /// Audits created since `since` (skipped ones included: they were started).+ pub async fn audits_since(&self, since: DateTime<Utc>) -> Result<i64, DbError> {+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM task_audits WHERE created_at >= ?").bind(since).fetch_one(&self.pool).await?;+ Ok(n)+ }++ /// How many audits each bot challenged since `since`.+ pub async fn challenges_since(&self, since: DateTime<Utc>) -> Result<Vec<(String, i64)>, DbError> {+ Ok(sqlx::query_as("SELECT challenger_kwant_id, COUNT(*) FROM task_audits WHERE created_at >= ? GROUP BY challenger_kwant_id")+ .bind(since)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Verified observations per bot in `class` (Performance Market, report data only).+ pub async fn verified_in_class(&self, space_id: &str, class: &str) -> Result<Vec<(String, i64)>, DbError> {+ Ok(sqlx::query_as(+ "SELECT kwant_id, COUNT(*) FROM performance_observations WHERE space_id = ? AND task_class = ? AND result = 'verified' GROUP BY kwant_id",+ )+ .bind(space_id)+ .bind(class)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Moves an audit from `from` to `to`; false when it wasn't in `from` any more. A final status+ /// sets `finished_at`.+ pub async fn move_audit(&self, id: &str, from: &str, to: &str, reason: Option<&str>) -> Result<bool, DbError> {+ let finished = matches!(to, "done" | "skipped" | "failed" | "interrupted").then(Utc::now);+ let r = sqlx::query("UPDATE task_audits SET status = ?, reason = COALESCE(?, reason), finished_at = COALESCE(?, finished_at) WHERE id = ? AND status = ?")+ .bind(to)+ .bind(reason)+ .bind(finished)+ .bind(id)+ .bind(from)+ .execute(&self.pool)+ .await?;+ Ok(r.rows_affected() == 1)+ }++ pub async fn add_audit_tokens(&self, id: &str, stage: &str, tokens: i64) -> Result<(), DbError> {+ let col = if stage == "rebuttal" { "rebuttal_tokens" } else { "challenge_tokens" };+ sqlx::query(&format!("UPDATE task_audits SET {col} = {col} + ? WHERE id = ?")).bind(tokens.max(0)).bind(id).execute(&self.pool).await?;+ Ok(())+ }++ /// Stores the challenge and moves the audit on, in one transaction: to `rebuttal` with risks,+ /// else `done`. `None` when the audit wasn't waiting for a challenge.+ pub async fn record_challenge(&self, audit_id: &str, risks: &[NewRisk]) -> Result<Option<Vec<Risk>>, DbError> {+ let mut tx = self.pool.begin().await?;+ let (to, finished) = if risks.is_empty() { ("done", Some(Utc::now())) } else { ("rebuttal", None) };+ let reason = risks.is_empty().then_some("no risks raised");+ let moved = sqlx::query("UPDATE task_audits SET status = ?, reason = COALESCE(?, reason), finished_at = ? WHERE id = ? AND status = 'challenge'")+ .bind(to)+ .bind(reason)+ .bind(finished)+ .bind(audit_id)+ .execute(&mut *tx)+ .await?;+ if moved.rows_affected() != 1 {+ return Ok(None);+ }+ let (task_id,): (String,) = sqlx::query_as("SELECT task_id FROM task_audits WHERE id = ?").bind(audit_id).fetch_one(&mut *tx).await?;+ let mut out = Vec::new();+ for (i, r) in risks.iter().enumerate() {+ let row = sqlx::query_as::<_, Risk>(+ "INSERT INTO audit_risks (id, audit_id, task_id, seq, risk, evidence, evidence_ids, status, created_at) \+ VALUES (?, ?, ?, ?, ?, ?, ?, 'open', ?) RETURNING *",+ )+ .bind(uuid::Uuid::new_v4().to_string())+ .bind(audit_id)+ .bind(&task_id)+ .bind(i as i64 + 1)+ .bind(&r.risk)+ .bind(&r.evidence)+ .bind(serde_json::to_string(&r.evidence_ids).unwrap_or_else(|_| "[]".into()))+ .bind(Utc::now())+ .fetch_one(&mut *tx)+ .await?;+ out.push(row);+ }+ tx.commit().await?;+ Ok(Some(out))+ }++ /// Stores the owner's answers and ends the audit, in one transaction. A disputed risk becomes+ /// `disputed`; an accepted or unanswered one stays `open`. `None` when the audit wasn't waiting+ /// for a rebuttal.+ pub async fn record_rebuttal(&self, audit_id: &str, answers: &[Answer]) -> Result<Option<Vec<Risk>>, DbError> {+ let mut tx = self.pool.begin().await?;+ let moved = sqlx::query("UPDATE task_audits SET status = 'done', finished_at = ? WHERE id = ? AND status = 'rebuttal'")+ .bind(Utc::now())+ .bind(audit_id)+ .execute(&mut *tx)+ .await?;+ if moved.rows_affected() != 1 {+ return Ok(None);+ }+ for a in answers {+ let status = if a.stance == "disputed" { "disputed" } else { "open" };+ sqlx::query("UPDATE audit_risks SET stance = ?, answer = ?, answer_evidence = ?, status = ? WHERE id = ? AND audit_id = ? AND status = 'open'")+ .bind(&a.stance)+ .bind(&a.answer)+ .bind(&a.evidence)+ .bind(status)+ .bind(&a.risk_id)+ .bind(audit_id)+ .execute(&mut *tx)+ .await?;+ }+ tx.commit().await?;+ self.risks_of_audit(audit_id).await.map(Some)+ }++ pub async fn risks_of_audit(&self, audit_id: &str) -> Result<Vec<Risk>, DbError> {+ Ok(sqlx::query_as::<_, Risk>("SELECT * FROM audit_risks WHERE audit_id = ? ORDER BY seq").bind(audit_id).fetch_all(&self.pool).await?)+ }++ pub async fn get_risk(&self, id: &str) -> Result<Option<Risk>, DbError> {+ Ok(sqlx::query_as::<_, Risk>("SELECT * FROM audit_risks WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)+ }++ /// Unresolved risks (`open` or `disputed`) of tasks in `space_id`, newest first.+ pub async fn unresolved_risks(&self, space_id: &str, limit: i64) -> Result<Vec<Risk>, DbError> {+ Ok(sqlx::query_as::<_, Risk>(+ "SELECT r.* FROM audit_risks r JOIN task_audits a ON a.id = r.audit_id \+ WHERE a.space_id = ? AND r.status IN ('open', 'disputed') ORDER BY r.created_at DESC, r.seq LIMIT ?",+ )+ .bind(space_id)+ .bind(limit)+ .fetch_all(&self.pool)+ .await?)+ }++ /// The person closes an unresolved risk; false when it was already closed.+ pub async fn resolve_risk(&self, id: &str, resolution: &str, note: Option<&str>) -> Result<bool, DbError> {+ let r = sqlx::query("UPDATE audit_risks SET status = ?, resolved_by = 'person', resolved_at = ?, note = ? WHERE id = ? AND status IN ('open', 'disputed')")+ .bind(resolution)+ .bind(Utc::now())+ .bind(note)+ .bind(id)+ .execute(&self.pool)+ .await?;+ Ok(r.rows_affected() == 1)+ }++ /// Fresh input + output of `kwant_id`'s model calls between `from` and `to`.+ pub async fn tokens_between(&self, kwant_id: &str, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<i64, DbError> {+ let (n,): (Option<i64>,) = sqlx::query_as("SELECT SUM(fresh_input + output) FROM model_usage WHERE kwant_id = ? AND created_at >= ? AND created_at <= ?")+ .bind(kwant_id)+ .bind(from)+ .bind(to)+ .fetch_one(&self.pool)+ .await?;+ Ok(n.unwrap_or(0))+ }+}++/// An audit as the API shows it, with its risks.+pub fn audit_json(a: &Audit, risks: &[Risk]) -> Value {+ let mut v = serde_json::to_value(a).unwrap_or_default();+ v["risks"] = Value::Array(+ risks+ .iter()+ .map(|r| {+ let mut j = serde_json::to_value(r).unwrap_or_default();+ j["evidence_ids"] = serde_json::json!(r.evidence_ids());+ j["unresolved"] = Value::Bool(r.unresolved());+ j+ })+ .collect(),+ );+ v+}++#[cfg(test)]+mod tests {+ use super::*;++ async fn db() -> (Database, tempfile::TempDir) {+ let tmp = tempfile::tempdir().unwrap();+ (Database::init(tmp.path()).await.unwrap(), tmp)+ }++ #[tokio::test]+ async fn an_attempt_gets_one_audit_and_a_bot_never_audits_itself() {+ let (db, _t) = db().await;+ assert!(db.create_audit("t1", "spc_default", 0, "manual", "a", "b").await.unwrap().is_some());+ assert!(db.create_audit("t1", "spc_default", 0, "manual", "c", "b").await.unwrap().is_none());+ assert!(db.create_audit("t1", "spc_default", 1, "manual", "c", "b").await.unwrap().is_some());+ assert!(db.create_audit("t2", "spc_default", 0, "manual", "b", "b").await.is_err());+ }++ #[tokio::test]+ async fn a_restart_marks_running_audits_interrupted() {+ let (db, _t) = db().await;+ let a = db.create_audit("t1", "spc_default", 0, "manual", "a", "b").await.unwrap().unwrap();+ assert!(db.move_audit(&a.id, "queued", "challenge", None).await.unwrap());+ db.migrate_auditor().await.unwrap();+ let a = db.get_audit(&a.id).await.unwrap().unwrap();+ assert_eq!((a.status.as_str(), a.finished_at.is_some()), ("interrupted", true));+ }++ #[tokio::test]+ async fn a_challenge_and_rebuttal_land_once() {+ let (db, _t) = db().await;+ let a = db.create_audit("t1", "spc_default", 0, "manual", "a", "b").await.unwrap().unwrap();+ let risk = NewRisk { risk: "r".into(), evidence: "saw x".into(), evidence_ids: vec![] };+ // Not waiting for a challenge yet+ assert!(db.record_challenge(&a.id, std::slice::from_ref(&risk)).await.unwrap().is_none());+ db.move_audit(&a.id, "queued", "challenge", None).await.unwrap();+ let risks = db.record_challenge(&a.id, &[risk.clone(), risk.clone()]).await.unwrap().unwrap();+ assert!(db.record_challenge(&a.id, &[risk]).await.unwrap().is_none());+ let answers = [Answer { risk_id: risks[0].id.clone(), stance: "disputed".into(), answer: "no".into(), evidence: Some("e".into()) }];+ let after = db.record_rebuttal(&a.id, &answers).await.unwrap().unwrap();+ assert_eq!(after.iter().map(|r| r.status.as_str()).collect::<Vec<_>>(), ["disputed", "open"]);+ assert!(db.record_rebuttal(&a.id, &answers).await.unwrap().is_none());+ assert_eq!(db.get_audit(&a.id).await.unwrap().unwrap().status, "done");+ assert!(db.resolve_risk(&after[1].id, "dismissed", None).await.unwrap());+ assert!(!db.resolve_risk(&after[1].id, "resolved", None).await.unwrap());+ }+}diff --git a/src/db/mod.rs b/src/db/mod.rsindex bd0b1ac6..10ddba09 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -30,6 +30,7 @@ pub mod checkpoints;pub mod autofix;pub mod flight_school;pub mod performance;+pub mod auditor;/// What a space's #general says about itself.pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";@@ -186,6 +187,8 @@ impl Database {db.migrate_opt_in_budgets().await?;// After it: observes finished tasks once (their class comes from Flight School)db.migrate_performance().await?;+ // Phase D2: audits and their risks (add-only)+ db.migrate_auditor().await?;db.pool.close().await;let pool = SqlitePoolOptions::new()diff --git a/src/server/missions/auditor.rs b/src/server/missions/auditor.rsnew file mode 100644index 00000000..996b8599--- /dev/null+++ b/src/server/missions/auditor.rs@@ -0,0 +1,619 @@+//! Mission Control Phase D2: the Swarm Auditor. A high-impact or low-confidence task that reaches+//! review gets one challenge from a teammate (with evidence) and one rebuttal from its owner; the+//! risks left unresolved are listed on the task until the person closes them. An audit never+//! verifies or fails a task and never counts agreement as proof: only outcome checks verify (§4).+//! Off by default. See docs/mission-control.md §18.++use super::routes::{bad, conflict, internal, not_found};+use crate::db::auditor::{audit_json, Answer, Audit, NewRisk};+use crate::db::missions::{OutcomeCheck, Task};+use crate::db::models::Kwant;+use crate::db::spaces::SpaceId;+use crate::server::continuity::SelfScope;+use crate::server::routes::{scope_for, turn_once, TurnOpts};+use crate::server::spaces::Scope;+use crate::server::AppState;+use axum::{+ extract::{Path, State},+ http::StatusCode,+ response::{IntoResponse, Response},+ Json,+};+use chrono::{Duration, Utc};+use serde::Deserialize;+use serde_json::{json, Value};+use std::sync::LazyLock;++pub const SETTING: &str = "auditor";+pub const MODES: [&str; 2] = ["off", "on"];+pub const CAP_SETTING: &str = "auditor_daily_cap";+pub const DEFAULT_CAP: i64 = 5;+pub const CAP_RANGE: (i64, i64) = (1, 50);+pub const MAX_RISKS: usize = 5;+const MAX_RISK_CHARS: usize = 500;+const MAX_EVIDENCE_CHARS: usize = 1000;+pub const PURPOSE: &str = "audit";+/// Longest an audit turn may take (an approval card it asked for included).+const TURN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20 * 60);+/// Write tools a bot in a live audit of a task can't use on that task.+pub const HELD_TOOLS: [&str; 5] = ["task_claim", "task_update", "task_attach_evidence", "task_request_check", "task_review"];++/// One audit runs at a time, server-wide; the others wait their turn.+static ONE: LazyLock<tokio::sync::Mutex<()>> = LazyLock::new(|| tokio::sync::Mutex::new(()));++pub async fn enabled(state: &AppState) -> bool {+ matches!(state.db.get_setting(SETTING).await.ok().flatten().as_deref().map(str::trim), Some("on"))+}++pub async fn daily_cap(state: &AppState) -> i64 {+ super::int_setting(state, CAP_SETTING, CAP_RANGE, DEFAULT_CAP).await+}++pub fn settings_error(mode: Option<&str>, cap: Option<i64>) -> Option<String> {+ if let Some(m) = mode.filter(|m| !MODES.contains(m)) {+ return Some(format!("auditor must be off or on (got {m})"));+ }+ if let Some(n) = cap.filter(|n| !(CAP_RANGE.0..=CAP_RANGE.1).contains(n)) {+ return Some(format!("auditor_daily_cap must be {}–{} (got {n})", CAP_RANGE.0, CAP_RANGE.1));+ }+ None+}++/// Why `task`, just in review, gets an audit: `high_impact` (priority high or urgent) or+/// `low_confidence` (no check that counts and isn't the owner's will judge it). `None` otherwise,+/// and always for a task without an owner.+pub fn trigger_of(task: &Task, checks: &[OutcomeCheck]) -> Option<&'static str> {+ task.owner_kwant_id.as_ref()?;+ if task.priority >= 2 {+ return Some("high_impact");+ }+ (super::checks_summary(task, checks)["status"] == "not_checked").then_some("low_confidence")+}++/// Bots that may not challenge `task`: its owner and the owner's own lead loop (the mission's lead,+/// the lead that handed it off).+pub async fn excluded(state: &AppState, task: &Task) -> Vec<String> {+ let mut out: Vec<String> = task.owner_kwant_id.iter().cloned().collect();+ if let Some(m) = &task.mission_id {+ if let Ok(Some(m)) = state.db.get_mission(m).await {+ out.push(m.lead_kwant_id);+ }+ }+ if let ("delegation", Some(d)) = (task.source_kind.as_str(), task.source_id.as_deref()) {+ if let Ok(Some(d)) = state.db.get_delegation(d).await {+ out.push(d.lead_kwant_id);+ }+ }+ out+}++/// The challenger of `task`: a bot of its space outside [`excluded`], with the most verified+/// tasks of its class, then the fewest challenges in the last 7 days, then by name and id.+pub async fn pick_challenger(state: &AppState, task: &Task) -> Option<Kwant> {+ let not = excluded(state, task).await;+ let bots = state.db.list_kwants(&SpaceId::new(&task.space_id)).await.ok()?;+ let class = state.db.task_class(&task.id).await.unwrap_or_else(|_| crate::db::flight_school::DEFAULT_CLASS.into());+ let verified = state.db.verified_in_class(&task.space_id, &class).await.unwrap_or_default();+ let recent = state.db.challenges_since(Utc::now() - Duration::days(7)).await.unwrap_or_default();+ let count = |list: &[(String, i64)], id: &str| list.iter().find(|(k, _)| k == id).map_or(0, |c| c.1);+ let mut cands: Vec<Kwant> = bots.into_iter().filter(|k| !not.contains(&k.id)).collect();+ cands.sort_by(|a, b| {+ count(&verified, &b.id)+ .cmp(&count(&verified, &a.id))+ .then(count(&recent, &a.id).cmp(&count(&recent, &b.id)))+ .then(a.name.to_lowercase().cmp(&b.name.to_lowercase()))+ .then(a.id.cmp(&b.id))+ });+ cands.into_iter().next()+}++async fn event(state: &AppState, task_id: &str, kind: &str, actor: &str, detail: Value) {+ if let Err(e) = state.db.log_task_event(task_id, kind, actor, &detail).await {+ tracing::warn!(task_id, kind, error = %e, "audit event not logged");+ }+}++/// After a move to review: audits the task in the background if the auditor is on and it+/// qualifies. Never blocks or fails the move.+pub fn on_review(state: &AppState, task: &Task) {+ let (state, task) = (state.clone(), task.clone());+ tokio::spawn(async move {+ if !enabled(&state).await {+ return;+ }+ let checks = state.db.list_checks(&task.id).await.unwrap_or_default();+ if let Some(trigger) = trigger_of(&task, &checks) {+ if let Err(why) = begin(&state, &task, trigger).await {+ tracing::info!(task_id = %task.id, why, "no audit");+ }+ }+ });+}++/// [`start`], then runs the audit in the background ([`drive`]).+pub async fn begin(state: &AppState, task: &Task, trigger: &str) -> Result<Audit, String> {+ let audit = start(state, task, trigger).await?;+ let (s, a) = (state.clone(), audit.clone());+ tokio::spawn(async move { drive(&s, &a).await });+ Ok(audit)+}++/// Opens an audit of `task`'s current attempt (`queued`). Refused (and, for the cap or a missing+/// challenger, logged as `audit_skipped`) when it can't start.+pub async fn start(state: &AppState, task: &Task, trigger: &str) -> Result<Audit, String> {+ let Some(owner) = task.owner_kwant_id.clone() else { return Err("the task has no owner".into()) };+ if matches!(state.db.audit_of_attempt(&task.id, task.attempts).await, Ok(Some(_))) {+ return Err("this attempt of the task was already audited".into());+ }+ let midnight = Utc::now().date_naive().and_hms_opt(0, 0, 0).map(|d| d.and_utc()).unwrap_or_else(Utc::now);+ let cap = daily_cap(state).await;+ if state.db.audits_since(midnight).await.unwrap_or(0) >= cap {+ event(state, &task.id, "audit_skipped", "kwant", json!({"reason": "daily_cap", "cap": cap})).await;+ return Err(format!("the daily audit cap ({cap}) is reached"));+ }+ let Some(challenger) = pick_challenger(state, task).await else {+ event(state, &task.id, "audit_skipped", "kwant", json!({"reason": "no_challenger"})).await;+ return Err("no teammate outside the owner's lead loop can challenge it".into());+ };+ let audit = match state.db.create_audit(&task.id, &task.space_id, task.attempts, trigger, &challenger.id, &owner).await {+ Ok(Some(a)) => a,+ Ok(None) => return Err("this attempt of the task was already audited".into()),+ Err(e) => return Err(e.to_string()),+ };+ event(state, &task.id, "audit_started", "kwant", json!({"audit_id": audit.id, "trigger": trigger, "challenger": challenger.id})).await;+ Ok(audit)+}++/// Runs an audit: the challenge turn, then the rebuttal turn if there are risks. Never moves the+/// task. Each stage that ends without its tool call ends the audit with a reason.+pub async fn drive(state: &AppState, audit: &Audit) {+ let _one = ONE.lock().await;+ let task = match state.db.get_task(&audit.task_id).await {+ Ok(Some(t)) if matches!(t.state.as_str(), "review" | "verified") => t,+ _ => {+ let _ = state.db.move_audit(&audit.id, "queued", "skipped", Some("the task moved on before its audit")).await;+ event(state, &audit.task_id, "audit_skipped", "kwant", json!({"audit_id": audit.id, "reason": "task_moved"})).await;+ return;+ }+ };+ if !state.db.move_audit(&audit.id, "queued", "challenge", None).await.unwrap_or(false) {+ return;+ }+ let (Ok(Some(challenger)), Ok(Some(owner))) = (state.db.get_kwant(&audit.challenger_kwant_id).await, state.db.get_kwant(&audit.owner_kwant_id).await) else {+ let _ = state.db.move_audit(&audit.id, "challenge", "failed", Some("a bot of the audit no longer exists")).await;+ return finish(state, audit).await;+ };+ let p = challenge_prompt(state, audit, &task, &owner).await;+ let err = run_stage(state, audit, &challenger, "challenge", p).await;+ if state.db.move_audit(&audit.id, "challenge", "failed", Some(&ended_without("challenge", err.as_deref()))).await.unwrap_or(false) {+ return finish(state, audit).await;+ }+ if matches!(state.db.get_audit(&audit.id).await, Ok(Some(a)) if a.status == "rebuttal") {+ let p = rebuttal_prompt(state, audit, &task, &challenger).await;+ let err = run_stage(state, audit, &owner, "rebuttal", p).await;+ // No answer: the audit ends with every risk still open+ if matches!(state.db.get_audit(&audit.id).await, Ok(Some(a)) if a.status == "rebuttal") && state.db.record_rebuttal(&audit.id, &[]).await.ok().flatten().is_some() {+ let _ = state.db.move_audit(&audit.id, "done", "done", Some(&ended_without("rebuttal", err.as_deref()))).await;+ }+ }+ finish(state, audit).await;+}++fn ended_without(stage: &str, err: Option<&str>) -> String {+ let who = if stage == "challenge" { "the challenger's turn ended without a challenge" } else { "the owner's turn ended without a rebuttal" };+ match err {+ Some(e) => format!("{who}: {}", e.lines().next().unwrap_or(e).chars().take(300).collect::<String>()),+ None => who.into(),+ }+}++async fn finish(state: &AppState, audit: &Audit) {+ let Ok(Some(a)) = state.db.get_audit(&audit.id).await else { return };+ let risks = state.db.risks_of_audit(&a.id).await.unwrap_or_default();+ let unresolved = risks.iter().filter(|r| r.unresolved()).count();+ event(+ state,+ &a.task_id,+ "audit_done",+ "kwant",+ json!({"audit_id": a.id, "status": a.status, "reason": a.reason, "risks": risks.len(), "unresolved": unresolved,+ "tokens": a.challenge_tokens + a.rebuttal_tokens}),+ )+ .await;+ super::emit_task_id(state, &a.task_id).await;+}++/// One hidden turn of `bot` in its direct chat, every change asking the person. Its tokens are+/// added to the stage. The turn's error, if any.+async fn run_stage(state: &AppState, audit: &Audit, bot: &Kwant, stage: &str, prompt: String) -> Option<String> {+ let started = Utc::now();+ let job = state.turns.start_job([bot.id.clone()]);+ let reply = match scope_for(state, bot, None, None, &job, 0).await {+ Ok(scope) => {+ let mut opts = TurnOpts::always_asking("Audit");+ (opts.unsaved, opts.quiet_failure, opts.purpose) = (true, true, Some(PURPOSE.into()));+ match tokio::time::timeout(TURN_TIMEOUT, turn_once(&scope, bot, prompt, opts)).await {+ Ok(r) => r,+ Err(_) => Err("the audit turn took longer than 20 minutes".into()),+ }+ }+ Err(e) => Err(e),+ };+ let tokens = state.db.tokens_between(&bot.id, started - Duration::seconds(1), Utc::now() + Duration::seconds(1)).await.unwrap_or(0);+ let _ = state.db.add_audit_tokens(&audit.id, stage, tokens).await;+ reply.err()+}++fn clip(s: &str, n: usize) -> String {+ let s = s.trim();+ if s.chars().count() <= n {+ s.to_string()+ } else {+ format!("{}…", s.chars().take(n).collect::<String>())+ }+}++async fn challenge_prompt(state: &AppState, audit: &Audit, task: &Task, owner: &Kwant) -> String {+ let evidence = state.db.list_evidence(&task.id).await.unwrap_or_default();+ let ev: Vec<String> = evidence+ .iter()+ .map(|e| {+ let at = e.uri.as_deref().or(e.path.as_deref()).unwrap_or("");+ format!("- [{}] {} \"{}\" {} {}", e.id, e.kind, e.label, at, clip(e.excerpt.as_deref().unwrap_or(""), 300))+ })+ .collect();+ let checks = state.db.list_checks(&task.id).await.unwrap_or_default();+ let ch: Vec<String> = checks+ .iter()+ .map(|c| format!("- {} {}: {}", c.kind, super::autofix::redact_value(&c.spec_value()), c.status))+ .collect();+ format!(+ "[Swarm Auditor] You are auditing task {tid} \"{title}\", done by {owner}. You are not its reviewer: \+ you can't verify or fail it, and nothing in this audit counts as proof either way; only its checks \+ or the person decide.\nAcceptance: {acc}\nEvidence attached:\n{ev}\nChecks:\n{ch}\n\+ Look for concrete reasons it may not meet its acceptance: wrong, missing, unsafe or unverifiable. \+ Read what you need, but change nothing. Then call audit_challenge once with audit_id {aid} and at \+ most {max} risks. Each risk needs `evidence`: what you looked at and what you saw (put ids from the \+ list above in evidence_ids when they apply). If you find no real risk, call it with an empty risks \+ list. Don't invent risks to have something to say.",+ tid = task.id,+ title = task.title,+ owner = owner.name,+ acc = if task.acceptance.is_empty() { "(none given)" } else { &task.acceptance },+ ev = if ev.is_empty() { "- none".into() } else { ev.join("\n") },+ ch = if ch.is_empty() { "- none: nothing outside will check it".into() } else { ch.join("\n") },+ aid = audit.id,+ max = MAX_RISKS,+ )+}++async fn rebuttal_prompt(state: &AppState, audit: &Audit, task: &Task, challenger: &Kwant) -> String {+ let risks = state.db.risks_of_audit(&audit.id).await.unwrap_or_default();+ let list: Vec<String> = risks.iter().map(|r| format!("- [{}] {} (evidence: {})", r.id, r.risk, clip(&r.evidence, 400))).collect();+ format!(+ "[Swarm Auditor] {who} challenged your task {tid} \"{title}\" with these risks:\n{list}\n\+ Call audit_rebut once with audit_id {aid} and an answer per risk: stance \"disputed\" when it \+ doesn't apply (give your evidence: what shows that), or \"accepted\" when it is a real risk. Change \+ nothing now: the person sees both sides and decides. Your answer doesn't verify the task.",+ who = challenger.name,+ tid = task.id,+ title = task.title,+ list = list.join("\n"),+ aid = audit.id,+ )+}++// Tools++type ToolResult = (String, bool);++fn fail(msg: impl Into<String>) -> ToolResult {+ (msg.into(), true)+}++fn ok(v: Value) -> ToolResult {+ (serde_json::to_string_pretty(&v).unwrap_or_default(), false)+}++pub const TOOL_NAMES: [&str; 2] = ["audit_challenge", "audit_rebut"];++pub fn tools() -> Vec<Value> {+ vec![+ json!({+ "name": "audit_challenge",+ "description": "Only when kwant asked you to audit a teammate's task: list the concrete risks you found, each with the evidence you looked at. Call it once; an empty list means you found none. It never verifies or fails the task.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "audit_id": {"type": "string"},+ "risks": {+ "type": "array",+ "maxItems": MAX_RISKS,+ "items": {+ "type": "object",+ "properties": {+ "risk": {"type": "string", "description": "What may be wrong, in a sentence."},+ "evidence": {"type": "string", "description": "What you looked at and what you saw."},+ "evidence_ids": {"type": "array", "items": {"type": "string"}, "description": "Ids of the task's evidence this rests on."},+ },+ "required": ["risk", "evidence"],+ },+ },+ },+ "required": ["audit_id", "risks"],+ },+ }),+ json!({+ "name": "audit_rebut",+ "description": "Only when kwant asked you to answer an audit of your task: per risk, \"disputed\" (with your evidence) or \"accepted\". Call it once. The person decides; your answer never verifies the task.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "audit_id": {"type": "string"},+ "answers": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "risk_id": {"type": "string"},+ "stance": {"type": "string", "enum": ["disputed", "accepted"]},+ "answer": {"type": "string"},+ "evidence": {"type": "string", "description": "Needed when disputed: what shows the risk doesn't apply."},+ },+ "required": ["risk_id", "stance", "answer"],+ },+ },+ },+ "required": ["audit_id", "answers"],+ },+ }),+ ]+}++/// The audit of `task_id` still running, if any.+pub async fn live_audit(state: &AppState, task_id: &str) -> Option<Audit> {+ state.db.audits_of(task_id).await.ok()?.into_iter().find(|a| matches!(a.status.as_str(), "queued" | "challenge" | "rebuttal"))+}++/// Why `kwant_id` can't use `tool` on `task` now: it is in a live audit of that task. A queued+/// audit of a task that already left review (a check sent it back) holds nothing: it will be skipped.+pub async fn held(state: &AppState, kwant_id: &str, tool: &str, task: &Task) -> Option<String> {+ if !HELD_TOOLS.contains(&tool) {+ return None;+ }+ let a = live_audit(state, &task.id).await?;+ if a.status == "queued" && !matches!(task.state.as_str(), "review" | "verified") {+ return None;+ }+ (a.challenger_kwant_id == kwant_id || a.owner_kwant_id == kwant_id)+ .then(|| format!("{tool} isn't available on this task during its audit: an audit never verifies, fails or changes the task."))+}++fn text(v: &Value, max: usize) -> Result<String, String> {+ let s = v.as_str().map(str::trim).unwrap_or("");+ if s.is_empty() {+ return Err("is empty".into());+ }+ if s.chars().count() > max {+ return Err(format!("is longer than {max} characters"));+ }+ Ok(s.to_string())+}++pub async fn call(state: &AppState, scope: &SelfScope, name: &str, args: &Value) -> ToolResult {+ if !enabled(state).await {+ return fail("The auditor is off in Settings.");+ }+ let Some(audit) = (match args["audit_id"].as_str() {+ Some(id) => state.db.get_audit(id).await.ok().flatten(),+ None => None,+ }) else {+ return fail("No such audit.");+ };+ match name {+ "audit_challenge" => challenge(state, scope, &audit, args).await,+ "audit_rebut" => rebut(state, scope, &audit, args).await,+ _ => fail(format!("Unknown tool {name}.")),+ }+}++async fn challenge(state: &AppState, scope: &SelfScope, audit: &Audit, args: &Value) -> ToolResult {+ if audit.challenger_kwant_id != scope.kwant_id {+ return fail("You aren't this audit's challenger.");+ }+ if audit.status != "challenge" {+ return fail(format!("This audit isn't waiting for a challenge (it is {}).", audit.status));+ }+ let Some(items) = args["risks"].as_array() else { return fail("risks must be a list (empty if you found none).") };+ if items.len() > MAX_RISKS {+ return fail(format!("At most {MAX_RISKS} risks: keep the ones that matter most."));+ }+ let on_task: Vec<String> = state.db.list_evidence(&audit.task_id).await.unwrap_or_default().into_iter().map(|e| e.id).collect();+ let mut risks = Vec::new();+ for (i, r) in items.iter().enumerate() {+ let n = i + 1;+ let risk = match text(&r["risk"], MAX_RISK_CHARS) {+ Ok(s) => s,+ Err(e) => return fail(format!("risk {n}: risk {e}.")),+ };+ let evidence = match text(&r["evidence"], MAX_EVIDENCE_CHARS) {+ Ok(s) => s,+ Err(e) => return fail(format!("risk {n}: evidence {e}; say what you looked at and what you saw.")),+ };+ let ids: Vec<String> = r["evidence_ids"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect()).unwrap_or_default();+ if let Some(bad) = ids.iter().find(|id| !on_task.contains(id)) {+ return fail(format!("risk {n}: evidence id {bad} isn't on this task."));+ }+ risks.push(NewRisk { risk, evidence, evidence_ids: ids });+ }+ match state.db.record_challenge(&audit.id, &risks).await {+ Ok(Some(rows)) => {+ event(state, &audit.task_id, "audit_challenge", &scope.kwant_id, json!({"audit_id": audit.id, "risks": rows.len()})).await;+ ok(json!({+ "audit_id": audit.id,+ "risks": rows.iter().map(|r| json!({"id": r.id, "risk": r.risk})).collect::<Vec<_>>(),+ "next": if rows.is_empty() { "Recorded: no risks raised. That isn't a pass; the task's checks still decide." } else { "Recorded. The owner answers once; the person sees both sides." },+ }))+ }+ Ok(None) => fail("This audit isn't waiting for a challenge any more."),+ Err(e) => fail(format!("Could not record the challenge: {e}")),+ }+}++async fn rebut(state: &AppState, scope: &SelfScope, audit: &Audit, args: &Value) -> ToolResult {+ if audit.owner_kwant_id != scope.kwant_id {+ return fail("Only the task's owner answers its audit.");+ }+ if audit.status != "rebuttal" {+ return fail(format!("This audit isn't waiting for a rebuttal (it is {}).", audit.status));+ }+ let risks = state.db.risks_of_audit(&audit.id).await.unwrap_or_default();+ let Some(items) = args["answers"].as_array() else { return fail("answers must be a list.") };+ let mut answers: Vec<Answer> = Vec::new();+ for (i, a) in items.iter().enumerate() {+ let n = i + 1;+ let Some(risk_id) = a["risk_id"].as_str().filter(|id| risks.iter().any(|r| r.id == *id)) else {+ return fail(format!("answer {n}: risk_id isn't one of this audit's risks."));+ };+ if answers.iter().any(|x| x.risk_id == risk_id) {+ return fail(format!("answer {n}: risk {risk_id} is answered twice."));+ }+ let stance = match a["stance"].as_str() {+ Some(s @ ("disputed" | "accepted")) => s.to_string(),+ _ => return fail(format!("answer {n}: stance must be disputed or accepted.")),+ };+ let answer = match text(&a["answer"], MAX_EVIDENCE_CHARS) {+ Ok(s) => s,+ Err(e) => return fail(format!("answer {n}: answer {e}.")),+ };+ let evidence = match (text(&a["evidence"], MAX_EVIDENCE_CHARS), stance.as_str()) {+ (Ok(s), _) => Some(s),+ (Err(_), "disputed") => return fail(format!("answer {n}: a disputed risk needs evidence: what shows it doesn't apply.")),+ (Err(_), _) => None,+ };+ answers.push(Answer { risk_id: risk_id.to_string(), stance, answer, evidence });+ }+ match state.db.record_rebuttal(&audit.id, &answers).await {+ Ok(Some(rows)) => {+ let disputed = rows.iter().filter(|r| r.status == "disputed").count();+ event(state, &audit.task_id, "audit_rebuttal", &scope.kwant_id, json!({"audit_id": audit.id, "answered": answers.len(), "disputed": disputed})).await;+ ok(json!({+ "audit_id": audit.id,+ "unresolved": rows.iter().filter(|r| r.unresolved()).count(),+ "next": "Recorded. Disputed and open risks stay listed on the task until the person closes them.",+ }))+ }+ Ok(None) => fail("This audit isn't waiting for a rebuttal any more."),+ Err(e) => fail(format!("Could not record the rebuttal: {e}")),+ }+}++// Routes++/// `GET /api/tasks/:id/risks`: the task's audits with their risks, and how many are unresolved.+pub async fn task_risks(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ match state.db.get_task(&id).await {+ Ok(Some(_)) => {}+ Ok(None) => return not_found("task"),+ Err(e) => return internal(e),+ }+ let audits = match state.db.audits_of(&id).await {+ Ok(a) => a,+ Err(e) => return internal(e),+ };+ let mut out = Vec::new();+ let mut open = 0;+ for a in &audits {+ let risks = state.db.risks_of_audit(&a.id).await.unwrap_or_default();+ open += risks.iter().filter(|r| r.unresolved()).count();+ out.push(audit_json(a, &risks));+ }+ Json(json!({"audits": out, "open_risks": open})).into_response()+}++/// `GET /api/risks?space=`: unresolved risks across the space, newest first.+pub async fn space_risks(State(state): State<AppState>, Scope(space): Scope) -> Response {+ match state.db.unresolved_risks(space.as_str(), 200).await {+ Ok(rows) => {+ let list: Vec<Value> = rows+ .iter()+ .map(|r| {+ let mut j = serde_json::to_value(r).unwrap_or_default();+ j["evidence_ids"] = json!(r.evidence_ids());+ j+ })+ .collect();+ Json(json!({"risks": list})).into_response()+ }+ Err(e) => internal(e),+ }+}++/// `POST /api/tasks/:id/audit` (person only): audit the task's current attempt now.+pub async fn start_audit(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ if !enabled(&state).await {+ return conflict("The auditor is off in Settings.");+ }+ let task = match state.db.get_task(&id).await {+ Ok(Some(t)) => t,+ Ok(None) => return not_found("task"),+ Err(e) => return internal(e),+ };+ if !matches!(task.state.as_str(), "review" | "verified") {+ return conflict("Only a task in review or verified can be audited.");+ }+ match begin(&state, &task, "manual").await {+ Ok(a) => (StatusCode::ACCEPTED, Json(audit_json(&a, &[]))).into_response(),+ Err(why) => conflict(why),+ }+}++#[derive(Deserialize)]+pub struct ResolveBody {+ resolution: String,+ note: Option<String>,+}++/// `POST /api/tasks/:id/risks/:risk_id/resolve` (person only): close an unresolved risk.+pub async fn resolve_risk(State(state): State<AppState>, Path((id, risk_id)): Path<(String, String)>, Json(body): Json<ResolveBody>) -> Response {+ if !matches!(body.resolution.as_str(), "resolved" | "dismissed") {+ return bad("resolution must be resolved or dismissed");+ }+ let note = body.note.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(|s| clip(s, MAX_EVIDENCE_CHARS));+ match state.db.get_risk(&risk_id).await {+ Ok(Some(r)) if r.task_id == id => {}+ Ok(_) => return not_found("risk"),+ Err(e) => return internal(e),+ }+ match state.db.resolve_risk(&risk_id, &body.resolution, note.as_deref()).await {+ Ok(true) => {+ event(&state, &id, "risk_resolved", "person", json!({"risk_id": risk_id, "resolution": body.resolution})).await;+ super::emit_task_id(&state, &id).await;+ match state.db.get_risk(&risk_id).await {+ Ok(Some(r)) => Json(json!({"risk": r, "unresolved": r.unresolved()})).into_response(),+ _ => internal("the risk vanished"),+ }+ }+ Ok(false) => conflict("This risk is already closed."),+ Err(e) => internal(e),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn settings_are_checked() {+ assert!(settings_error(Some("on"), Some(5)).is_none());+ assert!(settings_error(Some("suggest"), None).is_some());+ assert!(settings_error(None, Some(0)).is_some());+ assert!(settings_error(None, Some(51)).is_some());+ }++ #[test]+ fn a_stage_without_its_call_says_why() {+ assert_eq!(ended_without("challenge", None), "the challenger's turn ended without a challenge");+ assert!(ended_without("rebuttal", Some("boom\nmore")).ends_with(": boom"));+ }+}diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rsindex 34e5b0ba..e3693ab7 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 auditor;pub mod autofix;pub mod checkpoints;pub mod checks;@@ -241,6 +242,10 @@ async fn after_move(state: &AppState, task: &Task, to: &str) {if to == "ready" {listener::kick_handoff(state, task);}+ // The Swarm Auditor challenges a high-impact or low-confidence task in review (off by default, D2)+ if to == "review" {+ auditor::on_review(state, task);+ }autofix::settle(state, task, to).await;// A task parked for AutoFix isn't done failing: no "failed" line until it islet to = if to == "failed" && autofix::parked(state, task).await { "parked" } else { to };diff --git a/src/server/missions/tools.rs b/src/server/missions/tools.rsindex d1c470b7..91fbbd44 100644--- a/src/server/missions/tools.rs+++ b/src/server/missions/tools.rs@@ -1,6 +1,6 @@//! The task-board self tools: `mission_plan`, `task_list`, `task_claim`, `task_update`,-//! `task_attach_evidence`, `task_request_check`, `task_review`. Offered only while `mission_board`-//! is on. None of them can set `verified`: only a passing check that isn't the owner's does.+//! `task_attach_evidence`, `task_request_check`, `task_review`, and the auditor's `audit_challenge`,+//! `audit_rebut` (§18). Offered only while `mission_board` is on. None of them can set `verified`: only a passing check that isn't the owner's does.use super::checks::{hex, inside, run_task_checks};use super::{evaluate, task_folder, transition, validate_check, Actor, PlanBy, PlanPlace, PlanTask};@@ -24,7 +24,7 @@ fn ok(v: Value) -> ToolResult {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)+ NAMES.contains(&name) || super::auditor::TOOL_NAMES.contains(&name)}fn check_schema() -> Value {@@ -165,6 +165,9 @@ pub fn tools() -> Vec<Value> {},}),]+ .into_iter()+ .chain(super::auditor::tools())+ .collect()}pub async fn call(state: &AppState, scope: &SelfScope, name: &str, args: &Value) -> ToolResult {@@ -175,6 +178,16 @@ pub async fn call(state: &AppState, scope: &SelfScope, name: &str, args: &Value)Ok(Some(s)) => s,_ => return fail("Could not find your space."),};+ if super::auditor::TOOL_NAMES.contains(&name) {+ let in_space = match args["audit_id"].as_str() {+ Some(id) => matches!(state.db.get_audit(id).await, Ok(Some(a)) if a.space_id == space.as_str()),+ None => false,+ };+ if !in_space {+ return fail("No such audit in your space.");+ }+ return super::auditor::call(state, scope, name, args).await;+ }if name == "mission_plan" {return plan(state, scope, &space, args).await;}@@ -204,6 +217,9 @@ pub async fn call(state: &AppState, scope: &SelfScope, name: &str, args: &Value)Ok(Some(t)) if t.space_id == space.as_str() => t,_ => return fail("No such task in your space."),};+ if let Some(why) = super::auditor::held(state, &scope.kwant_id, name, &task).await {+ return fail(why);+ }match name {"task_claim" => claim(state, scope, &task).await,"task_update" => update(state, scope, &task, args).await,diff --git a/src/server/mod.rs b/src/server/mod.rsindex ca1f5027..24716b58 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -383,6 +383,10 @@ 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/risks", get(missions::auditor::task_risks))+ .route("/api/tasks/:id/risks/:risk_id/resolve", post(missions::auditor::resolve_risk))+ .route("/api/tasks/:id/audit", post(missions::auditor::start_audit))+ .route("/api/risks", get(missions::auditor::space_risks)).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))diff --git a/src/server/routes.rs b/src/server/routes.rsindex 1c1af799..c8e42ee3 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -3318,6 +3318,10 @@ pub struct SettingsResponse {pub flight_school: bool,/// The tier a bot hired while Flight School is on starts at, for every class.pub flight_school_new_bot_tier: String,+ /// Swarm Auditor: `off` or `on` (see `super::missions::auditor`).+ pub auditor: String,+ /// Audits started per UTC day (1–50).+ pub auditor_daily_cap: i64,}/// Unknown keys are refused, so a typo or a key from another version fails loudly instead of@@ -3361,6 +3365,8 @@ pub struct SaveSettingsPayload {pub recovery_budget_pct: Option<i64>,pub flight_school: Option<bool>,pub flight_school_new_bot_tier: Option<String>,+ pub auditor: Option<String>,+ pub auditor_daily_cap: Option<i64>,}pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {@@ -3413,6 +3419,8 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settingsrecovery_budget_pct: super::missions::autofix::recovery_pct(&state).await,flight_school: super::missions::flight_school::enabled(&state.db).await,flight_school_new_bot_tier: super::missions::flight_school::new_bot_tier(&state.db).await.into(),+ auditor: if super::missions::auditor::enabled(&state).await { "on" } else { "off" }.into(),+ auditor_daily_cap: super::missions::auditor::daily_cap(&state).await,}))}@@ -3471,6 +3479,9 @@ pub async fn save_settings(if let Some(e) = super::missions::flight_school::settings_error(payload.flight_school_new_bot_tier.as_deref()) {return bad(e);}+ if let Some(e) = super::missions::auditor::settings_error(payload.auditor.as_deref(), payload.auditor_daily_cap) {+ 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));}@@ -3593,6 +3604,12 @@ pub async fn save_settings(if let Some(t) = &payload.flight_school_new_bot_tier {let _ = state.db.set_setting(super::missions::flight_school::NEW_BOT_SETTING, t).await;}+ if let Some(m) = &payload.auditor {+ let _ = state.db.set_setting(super::missions::auditor::SETTING, m).await;+ }+ if let Some(n) = payload.auditor_daily_cap {+ let _ = state.db.set_setting(super::missions::auditor::CAP_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;}diff --git a/tests/auditor_test.rs b/tests/auditor_test.rsnew file mode 100644index 00000000..c80d21b3--- /dev/null+++ b/tests/auditor_test.rs@@ -0,0 +1,603 @@+//! The Swarm Auditor (Phase D2): which tasks get audited, who challenges, the caps, the two tool+//! calls, and that an audit never verifies, fails or moves a task. Off by default.+//! Contract: docs/mission-control.md §18.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{+ missions::{NewCheck, NewMission, NewTask, Task},+ models::{Kwant, NewKwant},+ performance::NewObservation,+ spaces::{SpaceId, DEFAULT_SPACE_ID},+ threads::NewDelegation,+ Database,+ },+ router::LayaRouter,+ server::{+ continuity::{SelfScope, TurnOrigin},+ create_router, mcp_runtime,+ missions::auditor,+ AppState,+ },+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::time::Duration;+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++struct Env {+ app: Router,+ state: AppState,+ general: String,+ _tmp: TempDir,+}++async fn setup() -> Env {+ let tmp = tempdir().unwrap();+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let config = Config {+ data_dir: data.clone(),+ laya_url: "http://127.0.0.1:9".into(),+ browser_cdp_url: Some("http://127.0.0.1:9".into()),+ ..Config::default()+ };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(data.join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let space = SpaceId::default_space();+ let general = state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap().id;+ let e = Env { app: create_router(state.clone()), state, general, _tmp: tmp };+ let (status, v) = call(&e.app, "POST", "/api/settings", None, Some(json!({"mission_board": true}))).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ e+}++async fn call(app: &Router, method: &str, uri: &str, auth: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");+ if let Some(token) = auth {+ req = req.header("authorization", format!("Bearer {token}"));+ }+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();+ let status = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++async fn person(e: &Env, method: &str, uri: &str, body: Option<Value>) -> Value {+ let (status, v) = call(&e.app, method, uri, None, body).await;+ assert!(status.is_success(), "{method} {uri}: {status} {v}");+ v+}++async fn auditor_on(e: &Env, cap: i64) {+ person(e, "POST", "/api/settings", Some(json!({"auditor": "on", "auditor_daily_cap": cap}))).await;+}++/// A bot of the default space that never runs a turn here (the tests that open an audit don't+/// drive it).+async fn bot(e: &Env, name: &str) -> Kwant {+ let input = NewKwant {+ name: name.into(),+ title: "Tester".into(),+ persona_prompt: String::new(),+ soul: String::new(),+ avatar_sprite: "s".into(),+ driver_type: "cli".into(),+ preferred_model: "claude".into(),+ };+ e.state.db.create_kwant(&SpaceId::default_space(), &input).await.unwrap()+}++async fn task_in(e: &Env, space: &str, owner: Option<&Kwant>, priority: i64, state: &str) -> Task {+ let t = NewTask {+ title: "Ship the export".into(),+ acceptance: "The export file opens".into(),+ state: state.into(),+ priority,+ owner_kwant_id: owner.map(|k| k.id.clone()),+ budget_tokens: 0,+ max_attempts: 3,+ source_kind: "person".into(),+ created_by: "person".into(),+ ..Default::default()+ };+ e.state.db.create_task(&SpaceId::new(space), &t).await.unwrap()+}++async fn task(e: &Env, owner: Option<&Kwant>, priority: i64, state: &str) -> Task {+ task_in(e, DEFAULT_SPACE_ID, owner, priority, state).await+}++/// A check the person added (it counts, and isn't the owner's).+async fn person_check(e: &Env, t: &Task) {+ e.state+ .db+ .add_check(&NewCheck {+ task_id: t.id.clone(),+ kind: "file_exists".into(),+ spec: json!({"path": "out.csv"}),+ required: true,+ approved: true,+ requested_by: "person".into(),+ approved_by: Some("person".into()),+ })+ .await+ .unwrap();+}++/// `bot` verified `n` tasks of class `general` (Performance Market rows).+async fn verified(e: &Env, bot: &Kwant, n: usize) {+ for i in 0..n {+ let o = NewObservation {+ task_id: format!("obs-{}-{i}", bot.id),+ space_id: bot.space_id.clone(),+ mission_id: None,+ task_class: "general".into(),+ kwant_id: bot.id.clone(),+ engine: "cli".into(),+ model: "m".into(),+ started_at: None,+ finished_at: chrono::Utc::now(),+ latency_ms: 0,+ runs: 1,+ fresh_tokens: 0,+ cost_usd: None,+ result: "verified",+ approvals: 0,+ check_approvals: 0,+ unblocks: 0,+ retries: 0,+ autofix_attempts: 0,+ };+ e.state.db.store_observation(&o, "live").await.unwrap();+ }+}++/// A turn token for `bot` with its own tools.+async fn token(e: &Env, bot: &Kwant) -> String {+ let turn_id = format!("t-{}", uuid::Uuid::new_v4());+ let origin = TurnOrigin { channel_id: Some(e.general.clone()), ..Default::default() };+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ origin: Some(origin),+ turn_id: Some(turn_id.clone()),+ ..Default::default()+ };+ mcp_runtime::prepare_turn_with_self(&e.state, bot, Some(turn_id), None, Some(scope)).await.unwrap().1+}++async fn tool(e: &Env, bot: &Kwant, name: &str, args: Value) -> (Value, bool, String) {+ let t = token(e, bot).await;+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});+ let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(&t), Some(rpc)).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ let text = v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string();+ (serde_json::from_str(&text).unwrap_or(Value::Null), v["result"]["isError"].as_bool().unwrap_or(false), text)+}++async fn events(e: &Env, tid: &str) -> Vec<String> {+ e.state.db.task_events(tid, 200).await.unwrap().into_iter().map(|ev| ev.kind).collect()+}++/// Task state and checks, which an audit must never change.+async fn verification(e: &Env, tid: &str) -> (String, Vec<(String, String)>) {+ let t = e.state.db.get_task(tid).await.unwrap().unwrap();+ let checks = e.state.db.list_checks(tid).await.unwrap().into_iter().map(|c| (c.id, c.status)).collect();+ (t.state, checks)+}++/// An audit of `t` waiting for its challenge, opened without running any turn.+async fn open_audit(e: &Env, t: &Task) -> kwnt::db::auditor::Audit {+ let a = auditor::start(&e.state, t, "manual").await.unwrap();+ assert!(e.state.db.move_audit(&a.id, "queued", "challenge", None).await.unwrap());+ a+}++#[tokio::test]+async fn the_auditor_is_off_by_default() {+ let e = setup().await;+ let s = person(&e, "GET", "/api/settings", None).await;+ assert_eq!((s["auditor"].as_str(), s["auditor_daily_cap"].as_i64()), (Some("off"), Some(5)), "{s}");+ let (owner, other) = (bot(&e, "Owner").await, bot(&e, "Other").await);++ // A high-impact task reaching review gets no audit while it is off+ let t = task(&e, Some(&owner), 3, "ready").await;+ let claim = tool(&e, &owner, "task_claim", json!({"task_id": t.id})).await;+ assert!(!claim.1, "{}", claim.2);+ let moved = tool(&e, &owner, "task_update", json!({"task_id": t.id, "status": "review"})).await;+ assert!(!moved.1, "{}", moved.2);+ tokio::time::sleep(Duration::from_millis(300)).await;+ assert!(e.state.db.audits_of(&t.id).await.unwrap().is_empty());+ assert!(!events(&e, &t.id).await.iter().any(|k| k.starts_with("audit")));++ // The person can't start one, and the tools refuse+ let (status, v) = call(&e.app, "POST", &format!("/api/tasks/{}/audit", t.id), None, None).await;+ assert_eq!(status, StatusCode::CONFLICT, "{v}");+ let a = e.state.db.create_audit(&t.id, DEFAULT_SPACE_ID, 1, "manual", &other.id, &owner.id).await.unwrap().unwrap();+ e.state.db.move_audit(&a.id, "queued", "challenge", None).await.unwrap();+ let (_, err, text) = tool(&e, &other, "audit_challenge", json!({"audit_id": a.id, "risks": []})).await;+ assert!(err && text.contains("off"), "{text}");+ // Reading still works+ let r = person(&e, "GET", &format!("/api/tasks/{}/risks", t.id), None).await;+ assert_eq!(r["audits"].as_array().unwrap().len(), 1, "{r}");+}++#[tokio::test]+async fn high_impact_or_unchecked_tasks_trigger_an_audit() {+ let e = setup().await;+ let owner = bot(&e, "Owner").await;+ let high = task(&e, Some(&owner), 2, "review").await;+ assert_eq!(auditor::trigger_of(&high, &[]), Some("high_impact"));+ person_check(&e, &high).await;+ let checks = e.state.db.list_checks(&high.id).await.unwrap();+ assert_eq!(auditor::trigger_of(&high, &checks), Some("high_impact"), "high impact even with a check");++ let low = task(&e, Some(&owner), 0, "review").await;+ assert_eq!(auditor::trigger_of(&low, &[]), Some("low_confidence"), "nothing outside will check it");+ person_check(&e, &low).await;+ let checks = e.state.db.list_checks(&low.id).await.unwrap();+ assert_eq!(auditor::trigger_of(&low, &checks), None, "a normal task with a check that counts");++ // The owner's own check doesn't count for confidence+ let own = task(&e, Some(&owner), 1, "review").await;+ let mine = e+ .state+ .db+ .add_check(&NewCheck {+ task_id: own.id.clone(),+ kind: "file_exists".into(),+ spec: json!({"path": "x"}),+ required: true,+ approved: true,+ requested_by: owner.id.clone(),+ approved_by: Some("auto".into()),+ })+ .await+ .unwrap();+ assert_eq!(auditor::trigger_of(&own, &[mine]), Some("low_confidence"));++ // Nobody owns it: nobody to answer, no audit+ let orphan = task(&e, None, 3, "review").await;+ assert_eq!(auditor::trigger_of(&orphan, &[]), None);+}++#[tokio::test]+async fn the_challenger_is_never_the_owner_or_its_lead_loop() {+ let e = setup().await;+ let (owner, lead, handoff) = (bot(&e, "Owner").await, bot(&e, "Lead").await, bot(&e, "Handoff").await);+ let (expert, fresh) = (bot(&e, "Expert").await, bot(&e, "Fresh").await);++ let mission = e+ .state+ .db+ .create_mission(+ &SpaceId::default_space(),+ &NewMission {+ title: "M".into(),+ goal: "G".into(),+ status: "active".into(),+ lead_kwant_id: lead.id.clone(),+ workspace_path: e._tmp.path().join("m").to_string_lossy().into(),+ created_by: "person".into(),+ ..Default::default()+ },+ )+ .await+ .unwrap();+ let (_, d) = e+ .state+ .db+ .create_delegation(&NewDelegation {+ lead_kwant_id: handoff.id.clone(),+ specialist_kwant_id: owner.id.clone(),+ origin_channel_id: Some(e.general.clone()),+ origin_kwant_id: None,+ origin_thread_id: None,+ team_id: None,+ task: "do it".into(),+ title: "do it".into(),+ continue_lead: false,+ depth: 1,+ follow_up_at: None,+ })+ .await+ .unwrap();+ let t = e+ .state+ .db+ .create_task(+ &SpaceId::default_space(),+ &NewTask {+ mission_id: Some(mission.id.clone()),+ title: "T".into(),+ state: "review".into(),+ priority: 2,+ owner_kwant_id: Some(owner.id.clone()),+ max_attempts: 3,+ source_kind: "delegation".into(),+ source_id: Some(d.id.clone()),+ created_by: "person".into(),+ ..Default::default()+ },+ )+ .await+ .unwrap();+ let out = auditor::excluded(&e.state, &t).await;+ for k in [&owner, &lead, &handoff] {+ assert!(out.contains(&k.id), "{} must be excluded: {out:?}", k.name);+ }++ // Most verified in the class wins, whatever the name+ verified(&e, &owner, 9).await;+ verified(&e, &lead, 9).await;+ verified(&e, &handoff, 9).await;+ verified(&e, &expert, 3).await;+ verified(&e, &fresh, 2).await;+ assert_eq!(auditor::pick_challenger(&e.state, &t).await.unwrap().id, expert.id);++ // Equal records: the one that challenged least this week+ verified(&e, &fresh, 3).await;+ let other = task(&e, Some(&owner), 2, "review").await;+ e.state.db.create_audit(&other.id, DEFAULT_SPACE_ID, other.attempts, "manual", &expert.id, &owner.id).await.unwrap().unwrap();+ assert_eq!(auditor::pick_challenger(&e.state, &t).await.unwrap().id, fresh.id);+}++#[tokio::test]+async fn one_audit_per_attempt_and_a_daily_cap() {+ let e = setup().await;+ let (owner, _other) = (bot(&e, "Owner").await, bot(&e, "Other").await);+ auditor_on(&e, 2).await;+ let t = task(&e, Some(&owner), 2, "review").await;+ let a = auditor::start(&e.state, &t, "high_impact").await.unwrap();+ assert_eq!((a.status.as_str(), a.attempt, a.owner_kwant_id.as_str()), ("queued", t.attempts, owner.id.as_str()));+ assert_ne!(a.challenger_kwant_id, owner.id);+ assert!(auditor::start(&e.state, &t, "manual").await.is_err(), "same attempt");+ let (status, v) = call(&e.app, "POST", &format!("/api/tasks/{}/audit", t.id), None, None).await;+ assert_eq!(status, StatusCode::CONFLICT, "{v}");+ assert!(events(&e, &t.id).await.contains(&"audit_started".to_string()));++ // A new attempt can be audited again+ e.state.db.exec_raw_for_test(&format!("UPDATE tasks SET attempts = attempts + 1 WHERE id = '{}'", t.id)).await.unwrap();+ let again = e.state.db.get_task(&t.id).await.unwrap().unwrap();+ auditor::start(&e.state, &again, "high_impact").await.unwrap();++ // Two today: the third is skipped and logged+ let t3 = task(&e, Some(&owner), 2, "review").await;+ let why = auditor::start(&e.state, &t3, "high_impact").await.unwrap_err();+ assert!(why.contains("cap"), "{why}");+ assert!(e.state.db.audits_of(&t3.id).await.unwrap().is_empty());+ assert!(events(&e, &t3.id).await.contains(&"audit_skipped".to_string()));++ // No owner, or nobody else to challenge+ let orphan = task(&e, None, 2, "review").await;+ assert!(auditor::start(&e.state, &orphan, "manual").await.is_err());+}++#[tokio::test]+async fn a_challenge_needs_evidence_and_only_the_challenger_gives_it() {+ let e = setup().await;+ let owner = bot(&e, "Owner").await;+ auditor_on(&e, 5).await;+ let t = task(&e, Some(&owner), 2, "review").await;+ person_check(&e, &t).await;+ let before = verification(&e, &t.id).await;+ let a = open_audit(&e, &t).await;+ let challenger = e.state.db.get_kwant(&a.challenger_kwant_id).await.unwrap().unwrap();++ // The owner can't challenge, nor answer before the challenge+ let (_, err, text) = tool(&e, &owner, "audit_challenge", json!({"audit_id": a.id, "risks": []})).await;+ assert!(err, "{text}");+ let (_, err, text) = tool(&e, &owner, "audit_rebut", json!({"audit_id": a.id, "answers": []})).await;+ assert!(err && text.contains("isn't waiting"), "{text}");++ // Evidence is required, at most 5 risks, evidence ids must be the task's+ let no_ev = json!({"audit_id": a.id, "risks": [{"risk": "The file is empty", "evidence": " "}]});+ let (_, err, text) = tool(&e, &challenger, "audit_challenge", no_ev).await;+ assert!(err && text.contains("evidence"), "{text}");+ let six: Vec<Value> = (0..6).map(|i| json!({"risk": format!("r{i}"), "evidence": "saw it"})).collect();+ let (_, err, text) = tool(&e, &challenger, "audit_challenge", json!({"audit_id": a.id, "risks": six})).await;+ assert!(err && text.contains("At most 5"), "{text}");+ let foreign = json!({"audit_id": a.id, "risks": [{"risk": "r", "evidence": "e", "evidence_ids": ["nope"]}]});+ let (_, err, text) = tool(&e, &challenger, "audit_challenge", foreign).await;+ assert!(err && text.contains("isn't on this task"), "{text}");++ // Mid-audit, neither side can review, update or add checks to the task+ for (who, name, args) in [+ (&challenger, "task_review", json!({"task_id": t.id, "verdict": "pass", "note": "fine"})),+ (&owner, "task_update", json!({"task_id": t.id, "status": "working"})),+ (&owner, "task_request_check", json!({"task_id": t.id, "kind": "file_exists", "spec": {"path": "y"}})),+ ] {+ let (_, err, text) = tool(&e, who, name, args).await;+ assert!(err && text.contains("during its audit"), "{name}: {text}");+ }++ let two = json!({"audit_id": a.id, "risks": [+ {"risk": "The export drops rows past 10k", "evidence": "Opened out.csv: 10000 rows; the source has 12 431."},+ {"risk": "No check covers the header", "evidence": "The only check is file_exists."},+ ]});+ let (v, err, text) = tool(&e, &challenger, "audit_challenge", two.clone()).await;+ assert!(!err, "{text}");+ let ids: Vec<String> = v["risks"].as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap().to_string()).collect();+ assert_eq!(ids.len(), 2);+ let (_, err, text) = tool(&e, &challenger, "audit_challenge", two).await;+ assert!(err, "one challenge only: {text}");++ // The rebuttal: a dispute needs evidence; only the owner answers, once+ let (_, err, text) = tool(&e, &challenger, "audit_rebut", json!({"audit_id": a.id, "answers": []})).await;+ assert!(err && text.contains("owner"), "{text}");+ let bare = json!({"audit_id": a.id, "answers": [{"risk_id": ids[0], "stance": "disputed", "answer": "no"}]});+ let (_, err, text) = tool(&e, &owner, "audit_rebut", bare).await;+ assert!(err && text.contains("evidence"), "{text}");+ let answers = json!({"audit_id": a.id, "answers": [+ {"risk_id": ids[0], "stance": "disputed", "answer": "The source has 10000 rows", "evidence": "wc -l source.csv: 10001"},+ ]});+ let (v, err, text) = tool(&e, &owner, "audit_rebut", answers.clone()).await;+ assert!(!err, "{text}");+ assert_eq!(v["unresolved"], 2, "a dispute isn't proof; the unanswered one stays open: {v}");+ let (_, err, _) = tool(&e, &owner, "audit_rebut", answers).await;+ assert!(err, "one rebuttal only");++ // The task, its checks and its verification are exactly as before+ assert_eq!(verification(&e, &t.id).await, before);+ let r = person(&e, "GET", &format!("/api/tasks/{}/risks", t.id), None).await;+ assert_eq!(r["open_risks"], 2, "{r}");+ let risks = r["audits"][0]["risks"].as_array().unwrap();+ assert_eq!((risks[0]["status"].as_str(), risks[1]["status"].as_str()), (Some("disputed"), Some("open")));+ assert_eq!(r["audits"][0]["status"], "done");+ let kinds = events(&e, &t.id).await;+ for k in ["audit_started", "audit_challenge", "audit_rebuttal"] {+ assert!(kinds.contains(&k.to_string()), "{k} in {kinds:?}");+ }+ // Done: the tools are the owner's again+ let (_, err, text) = tool(&e, &owner, "task_request_check", json!({"task_id": t.id, "kind": "file_exists", "spec": {"path": "y"}})).await;+ assert!(!err || !text.contains("during its audit"), "{text}");+}++#[tokio::test]+async fn no_risks_raised_is_not_a_pass() {+ let e = setup().await;+ let owner = bot(&e, "Owner").await;+ auditor_on(&e, 5).await;+ let t = task(&e, Some(&owner), 0, "review").await;+ let before = verification(&e, &t.id).await;+ let a = open_audit(&e, &t).await;+ let challenger = e.state.db.get_kwant(&a.challenger_kwant_id).await.unwrap().unwrap();+ let (v, err, text) = tool(&e, &challenger, "audit_challenge", json!({"audit_id": a.id, "risks": []})).await;+ assert!(!err && v["next"].as_str().unwrap().contains("isn't a pass"), "{text}");+ let done = e.state.db.get_audit(&a.id).await.unwrap().unwrap();+ assert_eq!((done.status.as_str(), done.reason.as_deref()), ("done", Some("no risks raised")));+ assert_eq!(verification(&e, &t.id).await, before, "still in review, nothing verified");+}++#[tokio::test]+async fn the_person_closes_risks_and_bots_cannot() {+ let e = setup().await;+ let owner = bot(&e, "Owner").await;+ auditor_on(&e, 5).await;+ let t = task(&e, Some(&owner), 2, "review").await;+ let a = open_audit(&e, &t).await;+ let challenger = e.state.db.get_kwant(&a.challenger_kwant_id).await.unwrap().unwrap();+ let risks = json!({"audit_id": a.id, "risks": [{"risk": "r1", "evidence": "e1"}, {"risk": "r2", "evidence": "e2"}]});+ let (v, err, text) = tool(&e, &challenger, "audit_challenge", risks).await;+ assert!(!err, "{text}");+ let r1 = v["risks"][0]["id"].as_str().unwrap().to_string();+ let space = person(&e, "GET", "/api/risks", None).await;+ assert_eq!(space["risks"].as_array().unwrap().len(), 2, "{space}");++ // A bot's token can't start an audit or close a risk+ let tok = token(&e, &owner).await;+ let (status, _) = call(&e.app, "POST", &format!("/api/tasks/{}/risks/{r1}/resolve", t.id), Some(&tok), Some(json!({"resolution": "dismissed"}))).await;+ assert_eq!(status, StatusCode::FORBIDDEN);+ let (status, _) = call(&e.app, "POST", &format!("/api/tasks/{}/audit", t.id), Some(&tok), None).await;+ assert_eq!(status, StatusCode::FORBIDDEN);++ let (status, _) = call(&e.app, "POST", &format!("/api/tasks/{}/risks/{r1}/resolve", t.id), None, Some(json!({"resolution": "verified"}))).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "only resolved or dismissed");+ let (status, _) = call(&e.app, "POST", &format!("/api/tasks/other/risks/{r1}/resolve"), None, Some(json!({"resolution": "resolved"}))).await;+ assert_eq!(status, StatusCode::NOT_FOUND, "the risk must be the task's");+ let v = person(&e, "POST", &format!("/api/tasks/{}/risks/{r1}/resolve", t.id), Some(json!({"resolution": "resolved", "note": "Fixed in 2.1"}))).await;+ assert_eq!((v["risk"]["status"].as_str(), v["unresolved"].as_bool()), (Some("resolved"), Some(false)), "{v}");+ let (status, _) = call(&e.app, "POST", &format!("/api/tasks/{}/risks/{r1}/resolve", t.id), None, Some(json!({"resolution": "dismissed"}))).await;+ assert_eq!(status, StatusCode::CONFLICT, "already closed");++ assert_eq!(person(&e, "GET", &format!("/api/tasks/{}/risks", t.id), None).await["open_risks"], 1);+ assert_eq!(person(&e, "GET", "/api/risks", None).await["risks"].as_array().unwrap().len(), 1);+ assert!(events(&e, &t.id).await.contains(&"risk_resolved".to_string()));+ assert_eq!(e.state.db.get_task(&t.id).await.unwrap().unwrap().state, "review", "closing a risk doesn't move the task");+}++/// A bot whose model calls go to a port nothing listens on, in a space of its own.+async fn dead_api_bot(e: &Env, space: &str, name: &str) -> Kwant {+ let (s, v) = call(+ &e.app,+ "POST",+ &format!("/api/profiles?space={space}"),+ None,+ Some(json!({+ "engine": "custom", "kind": "custom_api", "name": format!("Dead {name}"),+ "protocol": "openai-chat", "base_url": "http://127.0.0.1:9/v1",+ "api_key": "sk-test-0123456789", "model": "gpt-4.1",+ })),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ let (s, v) = call(+ &e.app,+ "POST",+ &format!("/api/kwants?space={space}"),+ None,+ Some(json!({"name": name, "title": "Tester", "persona_prompt": "Test", "avatar_sprite": "s", "driver_type": "api", "preferred_model": "custom"})),+ )+ .await;+ assert!(s.is_success(), "{s} {v}");+ e.state.db.get_kwant(v["id"].as_str().unwrap()).await.unwrap().unwrap()+}++#[tokio::test]+async fn a_failed_audit_turn_leaves_the_task_alone() {+ let e = setup().await;+ let (s, v) = call(&e.app, "POST", "/api/spaces", None, Some(json!({"name": "Audits", "icon": "🧪", "this_machine_enabled": false}))).await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ let space = v["id"].as_str().unwrap().to_string();+ let owner = dead_api_bot(&e, &space, "Owner").await;+ let challenger = dead_api_bot(&e, &space, "Challenger").await;+ verified(&e, &challenger, 50).await;+ auditor_on(&e, 5).await;+ let t = task_in(&e, &space, Some(&owner), 2, "review").await;+ person_check(&e, &t).await;+ let before = verification(&e, &t.id).await;++ let a = auditor::begin(&e.state, &t, "high_impact").await.unwrap();+ assert_eq!(a.challenger_kwant_id, challenger.id);+ let mut done = None;+ for _ in 0..600 {+ let now = e.state.db.get_audit(&a.id).await.unwrap().unwrap();+ if !matches!(now.status.as_str(), "queued" | "challenge" | "rebuttal") {+ done = Some(now);+ break;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ let done = done.expect("the audit ended");+ assert_eq!(done.status, "failed", "{done:?}");+ assert!(done.reason.as_deref().unwrap_or("").contains("without a challenge"), "{done:?}");+ assert_eq!(verification(&e, &t.id).await, before, "an audit never moves or checks the task");+ assert!(e.state.db.risks_of_audit(&a.id).await.unwrap().is_empty());+ let kinds = events(&e, &t.id).await;+ assert!(kinds.contains(&"audit_done".to_string()), "{kinds:?}");+ assert!(!kinds.iter().any(|k| k == "verified" || k == "failed" || k == "peer_review"), "{kinds:?}");+}++#[tokio::test]+async fn a_queued_audit_of_a_task_sent_back_holds_nothing() {+ let e = setup().await;+ let (owner, stranger) = (bot(&e, "Owner").await, bot(&e, "Stranger").await);+ auditor_on(&e, 5).await;+ let mut t = task(&e, Some(&owner), 2, "review").await;+ let a = auditor::start(&e.state, &t, "high_impact").await.unwrap();+ assert!(auditor::held(&e.state, &owner.id, "task_review", &t).await.is_some());+ assert!(auditor::held(&e.state, &owner.id, "task_list", &t).await.is_none(), "reading is never held");+ assert!(auditor::held(&e.state, &stranger.id, "task_review", &t).await.is_none() || stranger.id == a.challenger_kwant_id);+ // A check sent it back to work before the audit started: the owner can claim it again+ t.state = "working".into();+ assert!(auditor::held(&e.state, &owner.id, "task_claim", &t).await.is_none());+ // Once the challenge is running, both sides stay held until it ends+ e.state.db.move_audit(&a.id, "queued", "challenge", None).await.unwrap();+ assert!(auditor::held(&e.state, &owner.id, "task_claim", &t).await.is_some());+ e.state.db.move_audit(&a.id, "challenge", "failed", Some("test")).await.unwrap();+ assert!(auditor::held(&e.state, &owner.id, "task_claim", &t).await.is_none());+}