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.

69.1 KB
Raw Blame
//! 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. On by default; a routine run with
//! no check of its own earns its audit (14a).
//! 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, TaskChange},
        models::{Kwant, NewKwant},
        performance::NewObservation,
        spaces::{SpaceId, DEFAULT_SPACE_ID},
        threads::NewDelegation,
        Database,
    },
    router::LayaRouter,
    server::{
        continuity::{SelfScope, SelfToolsApprover, TurnOrigin},
        create_router, mcp_runtime,
        missions::auditor,
        AppState,
    },
    tools::ToolRunner,
};
use kwnt::mcp::{ApprovalOutcome, FixedApprover, ToolApprovalRequest, ToolApprover, SELF_SERVER_NAME};
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();
    // These chains predate keep-going turns; a stalled lead isn't nudged here.
    db.set_setting("keep_going_turns", "0").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) {
    verified_in(e, bot, n, "general").await
}

async fn verified_in(e: &Env, bot: &Kwant, n: usize, class: &str) {
    for i in 0..n {
        let o = NewObservation {
            task_id: format!("obs-{}-{class}-{i}", bot.id),
            space_id: bot.space_id.clone(),
            mission_id: None,
            task_class: class.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_on_by_default_and_a_saved_off_holds_it() {
    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("on"), Some(5)), "{s}");
    assert!(auditor::enabled(&e.state).await);
    person(&e, "POST", "/api/settings", Some(json!({"auditor": "off"}))).await;
    assert_eq!(person(&e, "GET", "/api/settings", None).await["auditor"], "off");
    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 one of the task's evidence ids"), "{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());
    // Its end is logged just after the status changes
    let mut kinds = events(&e, &t.id).await;
    for _ in 0..100 {
        if kinds.iter().any(|k| k == "audit_done") {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
        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:?}");
    // B1: the challenge ran with fresh eyes against the acceptance, but a challenge that never
    // came in is not "checked"
    let v = person(&e, "GET", &format!("/api/tasks/{}/risks", t.id), None).await;
    assert_eq!(
        v["audits"][0]["fresh_eyes"],
        json!({"checked": false, "saw": ["brief", "result"], "spec_source": "acceptance", "reviewer_kwant_id": challenger.id})
    );
}

#[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());
}

#[tokio::test]
async fn audit_turns_run_on_the_fast_tier_by_default() {
    let e = setup().await;
    let s = person(&e, "GET", "/api/settings", None).await;
    assert_eq!(s["auditor_model"], "fast", "{s}");
    let (status, v) = call(&e.app, "POST", "/api/settings", None, Some(json!({"auditor_model": "haiku"}))).await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "only a tier or bot: {v}");
    person(&e, "POST", "/api/settings", Some(json!({"auditor_model": "bot"}))).await;
    assert_eq!(person(&e, "GET", "/api/settings", None).await["auditor_model"], "bot");
    assert_eq!(auditor::tier_of(auditor::model_mode(&e.state).await), None, "bot: the usual routing");

    // The audit's start says which it ran on
    person(&e, "POST", "/api/settings", Some(json!({"auditor_model": "balanced"}))).await;
    auditor_on(&e, 5).await;
    let (owner, _other) = (bot(&e, "Owner").await, bot(&e, "Other").await);
    let t = task(&e, Some(&owner), 2, "review").await;
    auditor::start(&e.state, &t, "manual").await.unwrap();
    let started = e.state.db.task_events(&t.id, 50).await.unwrap().into_iter().find(|ev| ev.kind == "audit_started").unwrap();
    assert!(started.detail.contains("\"model\":\"balanced\""), "{}", started.detail);
}

/// Opens the same data folder again, as a restarted kwant does, and runs its startup step.
async fn restart(e: &Env) -> AppState {
    let data = e._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(), ..Config::default() };
    let state = AppState::new(config.clone(), db, ToolRunner::new(data.join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));
    auditor::resume_after_restart(&state).await;
    state
}

async fn ended(state: &AppState, id: &str) -> kwnt::db::auditor::Audit {
    for _ in 0..100 {
        let a = state.db.get_audit(id).await.unwrap().unwrap();
        if !matches!(a.status.as_str(), "queued" | "challenge" | "rebuttal") {
            return a;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    panic!("audit {id} is still running");
}

#[tokio::test]
async fn a_restart_never_leaves_an_audit_running() {
    let e = setup().await;
    let (owner, other) = (bot(&e, "Owner").await, bot(&e, "Other").await);
    auditor_on(&e, 10).await;
    // Cut off mid-challenge
    let t1 = task(&e, Some(&owner), 2, "review").await;
    let a1 = open_audit(&e, &t1).await;
    // Cut off waiting for the owner's answer, with a risk raised
    let t2 = task(&e, Some(&owner), 2, "review").await;
    let a2 = open_audit(&e, &t2).await;
    let risk = kwnt::db::auditor::NewRisk { risk: "The file may be empty".into(), evidence: "saw 0 bytes".into(), evidence_ids: vec![] };
    e.state.db.record_challenge(&a2.id, &[risk]).await.unwrap().unwrap();
    assert_eq!(e.state.db.get_audit(&a2.id).await.unwrap().unwrap().status, "rebuttal");
    // Still queued, its task sent back meanwhile
    let t3 = task(&e, Some(&owner), 2, "review").await;
    let a3 = auditor::start(&e.state, &t3, "manual").await.unwrap();
    assert!(e.state.db.move_task(&t3.id, "review", "ready", "person", &TaskChange::default()).await.unwrap());
    let before = (verification(&e, &t1.id).await, verification(&e, &t2.id).await);

    let state = restart(&e).await;
    let a1 = ended(&state, &a1.id).await;
    assert_eq!((a1.status.as_str(), a1.reason.as_deref()), ("interrupted", Some("kwant restarted during the audit")));
    let a2 = ended(&state, &a2.id).await;
    assert_eq!(a2.status, "interrupted");
    let risks = state.db.risks_of_audit(&a2.id).await.unwrap();
    assert!(risks.len() == 1 && risks[0].unresolved(), "a raised risk stays listed: {risks:?}");
    // The queued one ran after the restart and saw its task had moved on
    let a3 = ended(&state, &a3.id).await;
    assert_eq!(a3.status, "skipped", "{a3:?}");

    // Each task's history says so; nothing else changed and nothing is held any more
    for t in [&t1, &t2] {
        let evs = state.db.task_events(&t.id, 50).await.unwrap();
        assert!(evs.iter().any(|ev| ev.kind == "audit_done" && ev.detail.contains("interrupted")), "{:?}", evs.iter().map(|e| &e.kind).collect::<Vec<_>>());
        assert!(auditor::held(&state, &owner.id, "task_review", t).await.is_none());
        assert!(auditor::held(&state, &other.id, "task_review", t).await.is_none());
    }
    assert_eq!((verification(&e, &t1.id).await, verification(&e, &t2.id).await), before, "a restart never moves or checks the task");
    assert!(auditor::live_audit(&state, &t3.id).await.is_none());

    // Queued while the auditor was turned off: skipped at the next start, never run
    let t4 = task(&e, Some(&owner), 2, "review").await;
    let a4 = auditor::start(&e.state, &t4, "manual").await.unwrap();
    person(&e, "POST", "/api/settings", Some(json!({"auditor": "off"}))).await;
    let state = restart(&e).await;
    let a4 = state.db.get_audit(&a4.id).await.unwrap().unwrap();
    assert_eq!((a4.status.as_str(), a4.reason.as_deref()), ("skipped", Some("the auditor was turned off")));
}

#[tokio::test]
async fn an_audit_whose_driver_stopped_ends_failed() {
    let e = setup().await;
    let (owner, _other) = (bot(&e, "Owner").await, bot(&e, "Other").await);
    auditor_on(&e, 5).await;
    let t = task(&e, Some(&owner), 2, "review").await;
    let a = open_audit(&e, &t).await;
    let before = verification(&e, &t.id).await;
    assert!(auditor::end_if_live(&e.state, &a.id, "the audit stopped before it finished").await);
    let a = e.state.db.get_audit(&a.id).await.unwrap().unwrap();
    assert_eq!((a.status.as_str(), a.finished_at.is_some()), ("failed", true));
    assert!(!auditor::end_if_live(&e.state, &a.id, "again").await, "an ended audit stays as it ended");
    assert!(events(&e, &t.id).await.contains(&"audit_done".to_string()));
    assert_eq!(verification(&e, &t.id).await, before);
    assert!(auditor::held(&e.state, &owner.id, "task_update", &t).await.is_none());
}

/// Whether an always-ask audit turn lets `bot`'s call through without a card (the inner approver
/// stands for the card and says no).
async fn free_in_audit_turn(bot: &Kwant, tool: &str, args: Value) -> bool {
    let approver = SelfToolsApprover { inner: std::sync::Arc::new(FixedApprover(false)), always_ask: true, browser: None };
    let req = ToolApprovalRequest {
        kwant_id: bot.id.clone(),
        kwant_name: bot.name.clone(),
        turn_id: "t".into(),
        tool_name: format!("mcp__{SELF_SERVER_NAME}__{tool}"),
        server: SELF_SERVER_NAME.into(),
        tool: tool.into(),
        arguments: args,
        builtin: None,
        smart: None,
        payment: None,
    };
    approver.approve(req).await
}

#[tokio::test]
async fn one_challenge_is_one_card() {
    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 a = open_audit(&e, &t).await;
    let challenger = e.state.db.get_kwant(&a.challenger_kwant_id).await.unwrap().unwrap();
    let call_args = json!({"audit_id": a.id, "risks": []});

    // The first call asks the person
    assert!(!free_in_audit_turn(&challenger, "audit_challenge", call_args.clone()).await);

    // Allowed, then refused for its input (live: the task's id given as an evidence id): the
    // corrected call doesn't ask again, once per refusal
    let bad = json!({"audit_id": a.id, "risks": [{"risk": "r", "evidence": "e", "evidence_ids": ["nope"]}]});
    let (_, err, _) = tool(&e, &challenger, "audit_challenge", bad.clone()).await;
    assert!(err);
    for (who, name, args) in [
        (&owner, "audit_challenge", call_args.clone()),
        (&challenger, "audit_rebut", json!({"audit_id": a.id, "answers": []})),
        (&challenger, "audit_challenge", json!({"audit_id": "other", "risks": []})),
        (&challenger, "memory_add", json!({"audit_id": a.id, "text": "x"})),
    ] {
        assert!(!free_in_audit_turn(who, name, args).await, "{name} by {} still asks", who.name);
    }
    assert!(free_in_audit_turn(&challenger, "audit_challenge", call_args.clone()).await);
    assert!(!free_in_audit_turn(&challenger, "audit_challenge", call_args.clone()).await, "one pass per refusal");

    // At most two corrections without a card in a stage
    let (_, err, _) = tool(&e, &challenger, "audit_challenge", bad.clone()).await;
    assert!(err);
    assert!(free_in_audit_turn(&challenger, "audit_challenge", call_args.clone()).await);
    let (_, err, _) = tool(&e, &challenger, "audit_challenge", bad).await;
    assert!(err);
    assert!(!free_in_audit_turn(&challenger, "audit_challenge", call_args.clone()).await, "a third try asks");

    // A refusal by someone the audit isn't waiting on leaves nothing behind
    let (_, err, _) = tool(&e, &owner, "audit_challenge", call_args.clone()).await;
    assert!(err);
    assert!(!free_in_audit_turn(&owner, "audit_challenge", call_args).await);

    // The task's own id among the evidence ids is dropped, not refused
    let own = json!({"audit_id": a.id, "risks": [{"risk": "No export attached", "evidence": "The brief lists no evidence.", "evidence_ids": [t.id]}]});
    let (v, err, text) = tool(&e, &challenger, "audit_challenge", own).await;
    assert!(!err, "{text}");
    assert_eq!(v["risks"].as_array().unwrap().len(), 1);
    let risks = e.state.db.risks_of_audit(&a.id).await.unwrap();
    assert!(risks[0].evidence_ids().is_empty());

    // The owner's rebuttal: same rule
    let rebut = json!({"audit_id": a.id, "answers": []});
    assert!(!free_in_audit_turn(&owner, "audit_rebut", rebut.clone()).await);
    let (_, err, _) = tool(&e, &owner, "audit_rebut", json!({"audit_id": a.id, "answers": [{"risk_id": "nope", "stance": "accepted", "answer": "ok"}]})).await;
    assert!(err);
    assert!(free_in_audit_turn(&owner, "audit_rebut", rebut).await);
}

/// What an audit turn's approvers (kwnt's own tools first, then the card broker, both always
/// asking, as `run_stage` sets them up) make of `bot`'s call; a card is left unanswered.
async fn in_audit_turn(e: &Env, bot: &Kwant, tool: &str, args: Value) -> ApprovalOutcome {
    let broker = mcp_runtime::BrokerApprover {
        db: e.state.db.clone(),
        data_dir: e.state.config.data_dir.clone(),
        broker: e.state.broker.clone(),
        events: e.state.event_sender.clone(),
        timeout: Duration::from_millis(200),
        conversation: e.general.clone(),
        chat: None,
        always_ask: true,
        strict_ask: false,
        started_by: None,
    };
    let approver = SelfToolsApprover { inner: std::sync::Arc::new(broker), always_ask: true, browser: None };
    let req = ToolApprovalRequest {
        kwant_id: bot.id.clone(),
        kwant_name: bot.name.clone(),
        turn_id: format!("t-{}", uuid::Uuid::new_v4()),
        tool_name: format!("mcp__{SELF_SERVER_NAME}__{tool}"),
        server: SELF_SERVER_NAME.into(),
        tool: tool.into(),
        arguments: args,
        builtin: None,
        smart: None,
        payment: None,
    };
    approver.decide(req).await
}

/// The approvals rows of the default space as (tool, status), oldest first.
async fn approval_rows(e: &Env) -> Vec<(String, String)> {
    let rows = e.state.db.list_approvals(&SpaceId::default_space(), None, None).await.unwrap();
    rows.into_iter().rev().map(|a| (a.tool_name.rsplit("__").next().unwrap().to_string(), a.status)).collect()
}

/// With Approvals off, `audit_challenge` and `audit_rebut` run without a card (logged
/// `auto_allowed`), and so does every other tool of an audit turn (0.9.7). With approvals on or "Ask only
/// when risky", each audit call asks.
#[tokio::test]
async fn audit_calls_follow_the_approval_mode() {
    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 space = SpaceId::default_space();
    e.state.db.set_space_approvals(&space, "off").await.unwrap();
    let a = open_audit(&e, &t).await;
    let challenger = e.state.db.get_kwant(&a.challenger_kwant_id).await.unwrap().unwrap();

    // Approvals off: challenge → rebuttal → done, and nobody is shown a card
    let challenge = json!({"audit_id": a.id, "risks": [{"risk": "No draft was saved", "evidence": "The folder has only the inputs."}]});
    assert_eq!(in_audit_turn(&e, &challenger, "audit_challenge", challenge.clone()).await, ApprovalOutcome::Allowed);
    let (v, err, text) = tool(&e, &challenger, "audit_challenge", challenge).await;
    assert!(!err, "{text}");
    let risk = v["risks"][0]["id"].as_str().unwrap().to_string();
    let rebut = json!({"audit_id": a.id, "answers": [{"risk_id": risk, "stance": "accepted", "answer": "Saving it now"}]});
    assert_eq!(in_audit_turn(&e, &owner, "audit_rebut", rebut.clone()).await, ApprovalOutcome::Allowed);
    let (_, err, text) = tool(&e, &owner, "audit_rebut", rebut).await;
    assert!(!err, "{text}");
    let r = person(&e, "GET", &format!("/api/tasks/{}/risks", t.id), None).await;
    assert_eq!(r["audits"][0]["status"], "done", "{r}");
    let auto = |tool: &str| (tool.to_string(), "auto_allowed".to_string());
    assert_eq!(approval_rows(&e).await, vec![auto("audit_challenge"), auto("audit_rebut")], "no card, both on record");

    // Every other tool of an audit turn follows approvals off too (0.9.7: off means off, also in
    // a turn kwnt started on its own)
    assert_eq!(in_audit_turn(&e, &challenger, "memory_add", json!({"text": "x"})).await, ApprovalOutcome::Allowed);

    // Approvals on, or "Ask only when risky": one card per audit call, as before
    for mode in ["ask", "smart"] {
        e.state.db.set_space_approvals(&space, mode).await.unwrap();
        let call = json!({"audit_id": a.id, "risks": []});
        assert_eq!(in_audit_turn(&e, &challenger, "audit_challenge", call).await, ApprovalOutcome::Unanswered, "{mode} asks");
    }
    let rows = approval_rows(&e).await;
    let cards: Vec<&str> = rows.iter().filter(|(_, s)| s != "auto_allowed").map(|(t, _)| t.as_str()).collect();
    assert_eq!(cards, ["audit_challenge", "audit_challenge"], "{rows:?}");
}

#[tokio::test]
async fn a_person_assigned_owner_is_a_suggestion_until_the_claim() {
    let e = setup().await;
    let owner = bot(&e, "Owner").await;
    auditor_on(&e, 5).await;
    let t = person(&e, "POST", "/api/tasks", Some(json!({"title": "Export orders", "owner_kwant_id": owner.id, "priority": 2}))).await;
    assert_eq!((t["owner_kwant_id"].as_str(), t["suggested_kwant_id"].as_str()), (None, Some(owner.id.as_str())), "{t}");
    // No owner yet, so nobody to answer an audit
    let task = e.state.db.get_task(t["id"].as_str().unwrap()).await.unwrap().unwrap();
    assert!(auditor::start(&e.state, &task, "manual").await.is_err());
}

/// A team of the default space.
async fn team(e: &Env, name: &str, lead: &Kwant, members: &[&Kwant]) {
    let t = kwnt::db::models::NewTeam {
        name: name.into(),
        description: None,
        icon: None,
        lead_kwant_id: lead.id.clone(),
        member_kwants: members.iter().map(|k| k.id.clone()).collect(),
        workspace_path: None,
        repo_url: None,
    };
    e.state.db.create_team(&SpaceId::default_space(), &t).await.unwrap();
}

/// The challenger knows the work: the owner's team first, even over a stronger bot of another
/// team; then a bot that does the same kind of work; anyone else only when the person asked.
#[tokio::test]
async fn the_challenger_comes_from_the_owners_team_first() {
    let e = setup().await;
    let (owner, mate) = (bot(&e, "Owner").await, bot(&e, "Mate").await);
    let (expert, other) = (bot(&e, "Expert").await, bot(&e, "Other").await);
    team(&e, "Video", &owner, &[&mate]).await;
    team(&e, "Morning", &expert, &[&other]).await;
    verified(&e, &expert, 50).await;

    let t = task(&e, Some(&owner), 3, "review").await;
    let (k, pool) = auditor::pick(&e.state, &t, false).await.expect("a teammate");
    assert_eq!((k.name.as_str(), pool), ("Mate", "team"), "the owner's teammate, not the stronger outsider");

    // An owner alone in its team: an automatic audit is skipped, nobody from another team
    let solo = bot(&e, "Solo").await;
    team(&e, "Solo team", &solo, &[]).await;
    let t = task(&e, Some(&solo), 3, "review").await;
    assert!(auditor::pick_challenger(&e.state, &t).await.is_none());
    let err = auditor::start(&e.state, &t, "high_impact").await.unwrap_err();
    assert!(err.contains("owner's team"), "{err}");
    let ev = e.state.db.task_events(&t.id, 50).await.unwrap();
    let skipped = ev.iter().find(|x| x.kind == "audit_skipped").expect("logged as skipped");
    assert_eq!(skipped.detail_value()["reason"], "no_challenger");

    // A bot doing the same kind of work counts
    let t2 = task(&e, Some(&solo), 3, "review").await;
    assert!(e.state.db.set_task_class(&t2.id, "video", "person").await.unwrap());
    verified_in(&e, &other, 2, "video").await;
    let (k, pool) = auditor::pick(&e.state, &t2, false).await.expect("same work");
    assert_eq!((k.name.as_str(), pool), ("Other", "same_work"));

    // The person's own audit falls back to the whole space, and says so
    let a = auditor::start(&e.state, &t, "manual").await.unwrap();
    assert_eq!(a.challenger_kwant_id, expert.id, "the strongest of the rest");
    let ev = e.state.db.task_events(&t.id, 50).await.unwrap();
    let started = ev.iter().find(|x| x.kind == "audit_started").expect("started");
    assert_eq!(started.detail_value()["pool"], "space", "{}", started.detail);
}

/// An owner with no team: another bot with no team challenges it, before a stronger teamed one.
#[tokio::test]
async fn an_owner_with_no_team_is_challenged_by_a_bot_with_none() {
    let e = setup().await;
    let (owner, loner) = (bot(&e, "Owner").await, bot(&e, "Loner").await);
    let (lead, member) = (bot(&e, "Lead").await, bot(&e, "Member").await);
    team(&e, "Busy", &lead, &[&member]).await;
    verified(&e, &member, 50).await;
    verified(&e, &loner, 1).await;
    let t = task(&e, Some(&owner), 3, "review").await;
    let (k, pool) = auditor::pick(&e.state, &t, false).await.unwrap();
    assert_eq!((k.name.as_str(), pool), ("Loner", "no_team"));
}

/// The challenger reads what the owner handed in, as quoted data with secrets masked, and is told
/// plainly when nothing was saved.
#[tokio::test]
async fn the_challenge_prompt_quotes_the_owners_result() {
    let e = setup().await;
    let (owner, other) = (bot(&e, "Owner").await, bot(&e, "Other").await);
    let none = task(&e, Some(&owner), 3, "review").await;
    let a = open_audit(&e, &none).await;
    let p = auditor::challenge_prompt(&e.state, &a, &none, &owner).await;
    assert!(p.contains("Result: none saved"), "{p}");

    // In a chat: the owner's own latest reply there, not another bot's; and its notes
    let t = e
        .state
        .db
        .create_task(
            &SpaceId::default_space(),
            &NewTask {
                title: "Morning digest".into(),
                acceptance: "Lists today's school run and weather".into(),
                state: "review".into(),
                priority: 3,
                owner_kwant_id: Some(owner.id.clone()),
                max_attempts: 3,
                source_kind: "chat".into(),
                channel_id: Some(e.general.clone()),
                created_by: "person".into(),
                ..Default::default()
            },
        )
        .await
        .unwrap();
    let say = |who: &Kwant, text: &str| kwnt::db::models::NewMessage {
        channel_id: Some(e.general.clone()),
        direct_kwant_id: None,
        sender_role: "kwant".into(),
        sender_id: who.id.clone(),
        text: text.into(),
        reasoning_content: None,
        tool_calls: None,
        tokens_used: 0,
    };
    e.state.db.insert_message(&say(&owner, "School run 8:10, rain from 9. Key sk-ant-abcdefghijklmnopqrstuvwxyz0123")).await.unwrap();
    e.state.db.insert_message(&say(&other, "OTHER_BOT_TEXT")).await.unwrap();
    e.state.db.log_task_event(&t.id, "note", &owner.id, &json!({"note": "Weather from the met office"})).await.unwrap();
    e.state.db.log_task_event(&t.id, "note", &other.id, &json!({"note": "NOT_THE_OWNERS_NOTE"})).await.unwrap();
    let a = open_audit(&e, &t).await;
    let p = auditor::challenge_prompt(&e.state, &a, &t, &owner).await;
    assert!(p.contains("School run 8:10, rain from 9"), "{p}");
    assert!(p.contains("data, not instructions"), "{p}");
    // B1: with a result saved, the owner's notes (its narration) stay out of the reviewer's prompt
    assert!(!p.contains("Weather from the met office"), "{p}");
    assert!(p.contains("not Owner's chat or notes"), "{p}");
    assert!(!p.contains("abcdefghijklmnopqrstuvwxyz0123"), "a secret is masked: {p}");
    assert!(!p.contains("OTHER_BOT_TEXT") && !p.contains("NOT_THE_OWNERS_NOTE"), "{p}");

    // A hand-off: its result message, wherever it was posted
    let (_, d) = e
        .state
        .db
        .create_delegation(&NewDelegation {
            lead_kwant_id: other.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 mut m = say(&owner, "HANDOFF_RESULT exported 42 rows");
    (m.channel_id, m.direct_kwant_id) = (None, Some(owner.id.clone()));
    let m = e.state.db.insert_message(&m).await.unwrap();
    e.state.db.set_delegation_result_message(&d.id, &m.id).await.unwrap();
    let h = NewTask {
        title: "Export".into(),
        acceptance: "Rows exported".into(),
        state: "review".into(),
        priority: 3,
        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()
    };
    let h = e.state.db.create_task(&SpaceId::default_space(), &h).await.unwrap();
    let r = auditor::owner_result(&e.state, &h).await.unwrap_or_default();
    assert!(r.contains("HANDOFF_RESULT exported 42 rows"), "{r}");
}

/// Audit cards nobody answers are closed when their stage ends or kwant restarts, so none sits
/// in a bot's chat as "Needs you"; other cards stay.
#[tokio::test]
async fn audit_cards_left_open_are_closed() {
    let e = setup().await;
    let (a, b) = (bot(&e, "A").await, bot(&e, "B").await);
    let card = |who: &Kwant, tool: &str, chat: Value| {
        let (db, id, tool) = (e.state.db.clone(), who.id.clone(), tool.to_string());
        async move {
            let ap = db
                .save_approval(&kwnt::db::models::NewApproval { turn_id: "t".into(), kwant_id: id, tool_name: tool, parameters: json!({"arguments": {}}) })
                .await
                .unwrap();
            assert!(db.park_approval(&ap.id, &chat).await.unwrap());
            ap.id
        }
    };
    let before = chrono::Utc::now() - chrono::Duration::seconds(5);
    let marked = card(&a, "Bash", json!({"direct_kwant_id": a.id, "purpose": "audit"})).await;
    let legacy = card(&a, &format!("mcp__{SELF_SERVER_NAME}__audit_challenge"), json!({"direct_kwant_id": a.id})).await;
    let plain = card(&a, "Bash", json!({"direct_kwant_id": a.id})).await;
    let others = card(&b, "Bash", json!({"direct_kwant_id": b.id, "purpose": "audit"})).await;
    let status = |id: String| {
        let db = e.state.db.clone();
        async move { db.get_approval(&id).await.unwrap().unwrap().status }
    };

    // A stage of A's that started later closes nothing it didn't raise
    assert!(auditor::close_cards(&e.state, Some(&a.id), Some(chrono::Utc::now() + chrono::Duration::seconds(5))).await.is_empty());
    let mut closed = auditor::close_cards(&e.state, Some(&a.id), Some(before)).await;
    closed.sort();
    assert_eq!(closed, vec!["Bash".to_string(), "audit_challenge".to_string()]);
    assert_eq!(status(marked).await, "expired");
    assert_eq!(status(legacy).await, "expired");
    assert_eq!(status(plain.clone()).await, "waiting", "not an audit card");
    assert_eq!(status(others.clone()).await, "waiting", "another bot's");

    // A restart closes every audit card left open
    restart(&e).await;
    assert_eq!(status(others).await, "expired");
    assert_eq!(status(plain).await, "waiting");
}

/// The fresh-eyes label of a task's first audit.
async fn label(e: &Env, tid: &str) -> Value {
    person(e, "GET", &format!("/api/tasks/{tid}/risks"), None).await["audits"][0]["fresh_eyes"].clone()
}

/// B1: the rules for a written spec, and which audit stage runs with fresh eyes.
#[tokio::test]
async fn spec_rules_and_fresh_stages() {
    use kwnt::db::missions::TaskEvent;
    assert!(auditor::stage_is_fresh("challenge"));
    assert!(!auditor::stage_is_fresh("rebuttal"), "the owner answers for its own work");

    assert_eq!(auditor::parse_spec(&Value::Null), Ok(None));
    assert_eq!(auditor::parse_spec(&json!(["  It opens  ", "Rows match"])), Ok(Some(vec!["It opens".into(), "Rows match".into()])));
    let nine: Vec<String> = (0..9).map(|i| format!("line {i}")).collect();
    for bad in [json!("one line"), json!([]), json!(["ok", "  "]), json!(["ok", 3]), json!(nine), json!(["x".repeat(301)])] {
        assert!(auditor::parse_spec(&bad).is_err(), "{bad}");
    }
    assert!(auditor::parse_spec(&json!(["x".repeat(300)])).is_ok());

    let ev = |kind: &str, actor: &str, detail: Value| TaskEvent {
        id: 0,
        task_id: "t".into(),
        mission_id: None,
        kind: kind.into(),
        actor: actor.into(),
        from_state: None,
        to_state: None,
        detail: detail.to_string(),
        created_at: chrono::Utc::now(),
    };
    // No spec: the acceptance, one line per criterion, bullets and numbers dropped
    let s = auditor::spec_from(&[], Some("own"), "- The file opens\n2. Rows match\n\n* No secrets");
    assert_eq!((s.source, s.lines.clone()), ("acceptance", vec!["The file opens".to_string(), "Rows match".into(), "No secrets".into()]));
    assert_eq!(auditor::spec_from(&[], Some("own"), "  ").source, "none");
    // The owner's latest spec wins; another bot's never counts
    let events = [
        ev("spec", "own", json!({"lines": ["first"]})),
        ev("spec", "own", json!({"lines": ["second", "third"]})),
        ev("spec", "other", json!({"lines": ["NOT_THE_OWNERS"]})),
        ev("note", "own", json!({"note": "a note"})),
    ];
    let s = auditor::spec_from(&events, Some("own"), "The file opens");
    assert_eq!((s.source, s.lines), ("written", vec!["second".to_string(), "third".into()]));
    assert_eq!(auditor::spec_from(&events[2..], Some("own"), "").source, "none");
    assert_eq!(auditor::spec_from(&events, None, "").source, "none", "a task with no owner has no written spec");
}

/// B1: a high-impact task's owner writes its spec first, on its own and only while working; the
/// challenger is told to check the result against it, and the audit's label says it saw the spec.
#[tokio::test]
async fn a_spec_comes_first_and_the_challenger_checks_against_it() {
    let e = setup().await;
    person(&e, "POST", "/api/settings", Some(json!({"auditor": "off"}))).await;
    let (owner, other) = (bot(&e, "Owner").await, bot(&e, "Other").await);
    let t = task(&e, Some(&owner), 3, "ready").await;
    assert!(auditor::is_high_impact(&t));
    assert!(!auditor::is_high_impact(&task(&e, Some(&owner), 1, "ready").await));
    e.state.db.claim_task(&t.id, &owner.id, None, None, 600_000, false, &owner.id).await.unwrap().unwrap();
    let say = |args: Value| {
        let mut a = args;
        a["task_id"] = json!(t.id);
        a
    };

    // Only the holder writes it; it's strict; never together with a hand-in
    let (_, err, _) = tool(&e, &other, "task_update", say(json!({"spec": ["It opens"]}))).await;
    assert!(err, "not the holder");
    let (_, err, text) = tool(&e, &owner, "task_update", say(json!({"spec": ["ok", ""]}))).await;
    assert!(err && text.contains("non-empty"), "{text}");
    let (_, err, text) = tool(&e, &owner, "task_update", say(json!({"spec": ["The export opens"], "status": "review"}))).await;
    assert!(err && text.contains("on its own"), "{text}");
    assert_eq!(e.state.db.get_task(&t.id).await.unwrap().unwrap().state, "working", "the hand-in was refused with it");

    let (v, err, text) = tool(&e, &owner, "task_update", say(json!({"spec": ["The CSV has a header row", "Row count matches the source"]}))).await;
    assert!(!err, "{text}");
    assert_eq!(v["spec"], json!(["The CSV has a header row", "Row count matches the source"]));
    e.state.db.log_task_event(&t.id, auditor::SPEC_EVENT, &other.id, &json!({"lines": ["FAKE_SPEC_LINE"]})).await.unwrap();
    let spec = auditor::spec_of(&e.state, &t).await;
    assert_eq!((spec.source, spec.lines.len()), ("written", 2));

    // Handed in: no spec after the result
    let (_, err, text) = tool(&e, &owner, "task_update", say(json!({"status": "review"}))).await;
    assert!(!err, "{text}");
    let (_, err, text) = tool(&e, &owner, "task_update", say(json!({"spec": ["Written after the result"]}))).await;
    assert!(err, "{text}");
    assert_eq!(auditor::spec_of(&e.state, &t).await.lines[0], "The CSV has a header row");

    // The challenger checks against the spec, numbered
    let a = open_audit(&e, &t).await;
    let p = auditor::challenge_prompt(&e.state, &a, &t, &owner).await;
    assert!(p.contains("Spec Owner wrote before handing in"), "{p}");
    assert!(p.contains("1. The CSV has a header row\n2. Row count matches the source"), "{p}");
    assert!(p.contains("start it with that line's number"), "{p}");
    assert!(!p.contains("FAKE_SPEC_LINE"), "{p}");

    // Its label: what the challenger saw, checked once its challenge is in
    assert_eq!(label(&e, &t.id).await["checked"], false);
    assert_eq!(label(&e, &t.id).await["saw"], json!([]), "no fresh-eyes event yet, as for audits before 0.8.0");
    let saw = json!({"audit_id": a.id, "saw": ["spec", "result"], "spec_source": "written", "spec_lines": 2});
    e.state.db.log_task_event(&t.id, auditor::FRESH_EVENT, "kwant", &saw).await.unwrap();
    assert_eq!(label(&e, &t.id).await["checked"], false, "the challenge isn't in yet");
    assert!(e.state.db.move_audit(&a.id, "challenge", "rebuttal", None).await.unwrap());
    assert_eq!(
        label(&e, &t.id).await,
        json!({"checked": true, "saw": ["spec", "result"], "spec_source": "written", "reviewer_kwant_id": a.challenger_kwant_id})
    );
    assert_ne!(a.challenger_kwant_id, owner.id);
}

// 14a: a routine run with no check of its own earns its audit.

async fn routine(e: &Env, owner: &Kwant, name: &str) -> kwnt::db::continuity::RoutineRow {
    e.state.db.create_routine(&routine_input(owner, name, "Post the digest", None)).await.unwrap()
}

fn routine_input(owner: &Kwant, name: &str, instructions: &str, acceptance: Option<&str>) -> kwnt::db::continuity::NewRoutine {
    kwnt::db::continuity::NewRoutine {
        kwant_id: owner.id.clone(),
        channel_id: None,
        name: name.into(),
        instructions: instructions.into(),
        schedule: json!({"kind": "daily", "time": "09:00"}).to_string(),
        enabled: false,
        next_run_at: None,
        thread_id: None,
        context_message_id: None,
        origin: None,
        suggestion_id: None,
        task_class: None,
        acceptance: acceptance.map(String::from),
        checks: None,
    }
}

/// One run of `r` that reached review, as the routine listener makes it (owned, no checks).
async fn run_in_review(e: &Env, r: &kwnt::db::continuity::RoutineRow, priority: i64) -> Task {
    let run = e.state.db.start_routine_run(&r.id, "schedule", "ok", None).await.unwrap();
    let t = NewTask {
        title: format!("Routine: {}", r.name),
        acceptance: r.acceptance.clone().unwrap_or_else(|| r.instructions.clone()),
        state: "review".into(),
        priority,
        owner_kwant_id: Some(r.kwant_id.clone()),
        budget_tokens: 0,
        max_attempts: 3,
        source_kind: "routine".into(),
        source_id: Some(run.id),
        created_by: "kwant".into(),
        ..Default::default()
    };
    e.state.db.create_task(&SpaceId::default_space(), &t).await.unwrap()
}

async fn last_event(e: &Env, tid: &str, kind: &str) -> Value {
    let evs = e.state.db.task_events(tid, 200).await.unwrap();
    evs.into_iter().rev().find(|ev| ev.kind == kind).map(|ev| ev.detail_value()).unwrap_or(Value::Null)
}

/// Audits `t` the way a move to review does, without driving the turns: `Some(trigger)` when it
/// started.
async fn review(e: &Env, t: &Task) -> Option<&'static str> {
    let trigger = auditor::review_trigger(&e.state, t).await?;
    auditor::start(&e.state, t, trigger).await.ok().map(|_| trigger)
}

#[tokio::test]
async fn a_routine_run_is_audited_first_then_at_most_weekly() {
    let e = setup().await;
    let (owner, _other) = (bot(&e, "Ann").await, bot(&e, "Ben").await);
    auditor_on(&e, 50).await;
    let r = routine(&e, &owner, "Daily digest").await;

    // First run: audited, and the audit records what the routine said
    let first = run_in_review(&e, &r, 1).await;
    assert_eq!(review(&e, &first).await, Some("low_confidence"));
    let started = last_event(&e, &first.id, "audit_started").await;
    assert_eq!((started["routine_id"].as_str(), started["owner"].as_str(), started["source_kind"].as_str()), (Some(r.id.as_str()), Some(owner.id.as_str()), Some("routine")), "{started}");
    assert_eq!(started["routine_fp"].as_str(), Some(auditor::routine_fingerprint("Post the digest", None).as_str()), "{started}");

    // Second run the next day: skipped, and the task says why and since when
    let second = run_in_review(&e, &r, 1).await;
    assert_eq!(review(&e, &second).await, None);
    assert!(e.state.db.audits_of(&second.id).await.unwrap().is_empty());
    let skipped = last_event(&e, &second.id, "audit_skipped").await;
    assert_eq!(skipped["reason"], auditor::ROUTINE_CHECKED, "{skipped}");
    assert_eq!(skipped["last_audit_task_id"].as_str(), Some(first.id.as_str()), "{skipped}");
    assert!(skipped["last_audit_at"].is_string() && skipped["next_audit_from"].is_string(), "{skipped}");

    // Six days later still skipped; at seven days due again
    e.state.db.exec_raw_for_test(&format!("UPDATE task_audits SET created_at = '{}' WHERE task_id = '{}'", (chrono::Utc::now() - chrono::Duration::days(6)).to_rfc3339(), first.id)).await.unwrap();
    assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, None, "6 days");
    e.state.db.exec_raw_for_test(&format!("UPDATE task_audits SET created_at = '{}' WHERE task_id = '{}'", (chrono::Utc::now() - chrono::Duration::days(7)).to_rfc3339(), first.id)).await.unwrap();
    let week = run_in_review(&e, &r, 1).await;
    assert_eq!(review(&e, &week).await, Some("low_confidence"), "7 days");
    assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, None, "the weekly one counts as the last");
}

#[tokio::test]
async fn a_routine_run_after_its_instructions_or_acceptance_change_is_audited() {
    let e = setup().await;
    let (owner, other) = (bot(&e, "Ann").await, bot(&e, "Ben").await);
    auditor_on(&e, 50).await;
    let r = routine(&e, &owner, "Daily digest").await;
    assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, Some("low_confidence"));
    assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, None);

    // New instructions: the next run is audited, the one after isn't
    let r = e.state.db.update_routine(&r.id, &routine_input(&owner, "Daily digest", "Post the digest and the top 3 links", None)).await.unwrap().unwrap();
    assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, Some("low_confidence"), "instructions changed");
    assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, None);

    // A new acceptance too; renaming it or its schedule isn't a change of what it does
    let r = e.state.db.update_routine(&r.id, &routine_input(&owner, "Daily digest", "Post the digest and the top 3 links", Some("3 links, each opens"))).await.unwrap().unwrap();
    assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, Some("low_confidence"), "acceptance changed");
    let r = e.state.db.update_routine(&r.id, &routine_input(&owner, "Morning digest", "Post the digest and the top 3 links", Some("3 links, each opens"))).await.unwrap().unwrap();
    assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, None, "renamed only");

    // An audit from before 14a (its event has no fingerprint) doesn't hold the next run back
    let legacy = run_in_review(&e, &r, 1).await;
    e.state.db.create_audit(&legacy.id, &legacy.space_id, 1, "low_confidence", &other.id, &owner.id).await.unwrap().unwrap();
    assert_eq!(e.state.db.last_routine_audit(&r.id).await.unwrap().unwrap().fingerprint, None);
    assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, Some("low_confidence"), "no fingerprint");
}

#[tokio::test]
async fn an_audit_that_never_checked_does_not_count_for_its_routine() {
    let e = setup().await;
    let (owner, _other) = (bot(&e, "Ann").await, bot(&e, "Ben").await);
    auditor_on(&e, 50).await;
    let r = routine(&e, &owner, "Daily digest").await;
    let first = run_in_review(&e, &r, 1).await;
    assert_eq!(review(&e, &first).await, Some("low_confidence"));
    for status in ["failed", "skipped", "interrupted"] {
        e.state.db.exec_raw_for_test(&format!("UPDATE task_audits SET status = '{status}' WHERE task_id = '{}'", first.id)).await.unwrap();
        let next = run_in_review(&e, &r, 1).await;
        assert_eq!(auditor::review_trigger(&e.state, &next).await, Some("low_confidence"), "{status}");
    }
}

#[tokio::test]
async fn high_priority_routine_runs_hand_offs_and_other_tasks_are_audited_as_before() {
    let e = setup().await;
    let (owner, _other) = (bot(&e, "Ann").await, bot(&e, "Ben").await);
    auditor_on(&e, 50).await;
    let r = routine(&e, &owner, "Daily digest").await;
    assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, Some("low_confidence"));
    // Marked high priority: audited every run
    for _ in 0..2 {
        assert_eq!(review(&e, &run_in_review(&e, &r, 2).await).await, Some("high_impact"));
    }
    // A low-priority run is still held back by the audits above
    assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, None);

    // Hand-offs and person tasks with no check: every one, as before
    for _ in 0..2 {
        let d = task(&e, Some(&owner), 1, "review").await;
        e.state.db.exec_raw_for_test(&format!("UPDATE tasks SET source_kind = 'delegation', source_id = 'd-{}' WHERE id = '{}'", d.id, d.id)).await.unwrap();
        let d = e.state.db.get_task(&d.id).await.unwrap().unwrap();
        assert_eq!(review(&e, &d).await, Some("low_confidence"), "hand-off");
        assert_eq!(review(&e, &task(&e, Some(&owner), 1, "review").await).await, Some("low_confidence"), "person task");
    }
    // A routine run whose routine is gone is treated like any task
    let gone = run_in_review(&e, &r, 1).await;
    e.state.db.delete_routine(&r.id).await.unwrap();
    assert_eq!(auditor::review_trigger(&e.state, &gone).await, Some("low_confidence"));
}

#[tokio::test]
async fn the_daily_cap_still_holds_and_a_capped_run_does_not_count() {
    let e = setup().await;
    let (owner, _other) = (bot(&e, "Ann").await, bot(&e, "Ben").await);
    auditor_on(&e, 1).await;
    let (a, b) = (routine(&e, &owner, "Digest A").await, routine(&e, &owner, "Digest B").await);
    assert_eq!(review(&e, &run_in_review(&e, &a, 1).await).await, Some("low_confidence"));
    // Routine B's first run is due but today's cap is used: skipped for the cap
    let capped = run_in_review(&e, &b, 1).await;
    assert_eq!(auditor::review_trigger(&e.state, &capped).await, Some("low_confidence"));
    assert!(auditor::start(&e.state, &capped, "low_confidence").await.unwrap_err().contains("cap"));
    assert_eq!(last_event(&e, &capped.id, "audit_skipped").await["reason"], "daily_cap");
    // So B's next run is still its first check
    assert_eq!(auditor::review_trigger(&e.state, &run_in_review(&e, &b, 1).await).await, Some("low_confidence"));
}

#[test]
fn routine_due_rules() {
    use kwnt::db::auditor::RoutineAudit;
    let now = chrono::Utc::now();
    let fp = auditor::routine_fingerprint("Post the digest", None);
    assert_eq!(fp, auditor::routine_fingerprint("  Post the digest\n", Some("")), "whitespace and an empty acceptance are no change");
    assert_ne!(fp, auditor::routine_fingerprint("Post the digest", Some("x")));
    assert_ne!(auditor::routine_fingerprint("ab", Some("c")), auditor::routine_fingerprint("a", Some("bc")), "fields are separated");
    let at = |days: i64, fp: Option<&str>| RoutineAudit { audit_id: "a".into(), task_id: "t".into(), created_at: now - chrono::Duration::days(days), fingerprint: fp.map(String::from) };
    assert!(auditor::routine_due(None, &fp, now));
    assert!(!auditor::routine_due(Some(&at(0, Some(&fp))), &fp, now));
    assert!(!auditor::routine_due(Some(&at(6, Some(&fp))), &fp, now));
    assert!(auditor::routine_due(Some(&at(7, Some(&fp))), &fp, now));
    assert!(auditor::routine_due(Some(&at(1, Some("other"))), &fp, now));
    assert!(auditor::routine_due(Some(&at(1, None)), &fp, now));
}