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.

46.0 KB
Raw Blame
//! `/api/missions`, `/api/tasks` and `/api/checks`. Reads are open like the rest of the app API;
//! every change is person-only (`auth.rs`), so a bot token can't verify, approve or cancel.

use super::{
    checks, checks_json, emit_mission, emit_task, evaluate, mission_json, task_json, transition, validate_check, Actor, MoveError,
    PlanBy, PlanCheck, PlanPlace, PlanTask,
};
use crate::db::missions::{NewCheck, NewTask, Task, TaskChange, TaskEvent, MISSION_STATUSES, SOURCE_KINDS, TASK_STATES};
use crate::db::spaces::SpaceId;
use crate::server::spaces::{space_param, Scope};
use crate::server::AppState;
use axum::{
    extract::{Path, Query, RawQuery, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde::Deserialize;
use serde_json::{json, Value};

pub(super) fn err(status: StatusCode, msg: impl Into<String>) -> Response {
    (status, Json(json!({"error": msg.into()}))).into_response()
}

pub(super) fn bad(msg: impl Into<String>) -> Response {
    err(StatusCode::BAD_REQUEST, msg)
}

pub(super) fn conflict(msg: impl Into<String>) -> Response {
    err(StatusCode::CONFLICT, msg)
}

pub(super) fn not_found(what: &str) -> Response {
    err(StatusCode::NOT_FOUND, format!("no such {what}"))
}

pub(super) fn internal(e: impl std::fmt::Display) -> Response {
    tracing::warn!(error = %e, "mission control");
    err(StatusCode::INTERNAL_SERVER_ERROR, "something went wrong")
}

#[allow(clippy::result_large_err)]
pub(super) fn moved(r: Result<Task, MoveError>) -> Result<Task, Response> {
    r.map_err(|e| match e {
        MoveError::Missing => not_found("task"),
        MoveError::Db(crate::db::DbError::Sqlx(_)) | MoveError::NotAllowed(_) | MoveError::Stale => conflict(e.to_string()),
        MoveError::Db(e) => internal(e),
    })
}

/// The task `id`, refused (404) when an explicit `?space=` names another space.
#[allow(clippy::result_large_err)]
pub(super) async fn load_task(state: &AppState, query: Option<&str>, id: &str) -> Result<Task, Response> {
    match state.db.get_task(id).await {
        Ok(Some(t)) if space_param(query).is_none_or(|s| s.trim() == t.space_id) => Ok(t),
        Ok(_) => Err(not_found("task")),
        Err(e) => Err(internal(e)),
    }
}

#[allow(clippy::result_large_err)]
pub(super) async fn load_mission(state: &AppState, query: Option<&str>, id: &str) -> Result<crate::db::missions::Mission, Response> {
    match state.db.get_mission(id).await {
        Ok(Some(m)) if space_param(query).is_none_or(|s| s.trim() == m.space_id) => Ok(m),
        Ok(_) => Err(not_found("mission")),
        Err(e) => Err(internal(e)),
    }
}

async fn task_out(state: &AppState, t: &Task) -> Response {
    Json(task_json(state, t).await).into_response()
}

async fn mission_out(state: &AppState, id: &str) -> Response {
    match state.db.get_mission(id).await {
        Ok(Some(m)) => Json(mission_json(state, &m).await).into_response(),
        Ok(None) => not_found("mission"),
        Err(e) => internal(e),
    }
}

async fn event_json(state: &AppState, e: &TaskEvent) -> Value {
    let mut v = serde_json::to_value(e).unwrap_or(Value::Null);
    if let Some(obj) = v.as_object_mut() {
        obj.insert("detail".into(), e.detail_value());
        obj.insert("actor_name".into(), json!(super::name_of(state, Some(&e.actor)).await));
    }
    v
}

// Missions

#[derive(Deserialize)]
pub struct MissionQuery {
    status: Option<String>,
    /// Verified remediation missions leave the board; they stay in the goal's timeline
    #[serde(default)]
    include_archived: bool,
}

pub async fn list_missions(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<MissionQuery>) -> Response {
    if q.status.as_deref().is_some_and(|s| !MISSION_STATUSES.contains(&s)) {
        return bad("unknown status");
    }
    match state.db.list_missions(&space, q.status.as_deref()).await {
        Ok(ms) => {
            let archived = if q.include_archived { Vec::new() } else { state.db.archived_mission_ids().await.unwrap_or_default() };
            let mut out = Vec::new();
            for m in ms.iter().filter(|m| !archived.contains(&m.id)) {
                out.push(mission_json(&state, m).await);
            }
            Json(json!({"missions": out})).into_response()
        }
        Err(e) => internal(e),
    }
}

#[derive(Deserialize)]
pub struct CreateMission {
    title: String,
    #[serde(default)]
    goal: String,
    lead_kwant_id: Option<String>,
    budget_tokens: Option<i64>,
    #[serde(default)]
    tasks: Vec<PlanTask>,
    channel_id: Option<String>,
    thread_id: Option<String>,
}

pub async fn create_mission(State(state): State<AppState>, Scope(space): Scope, Json(p): Json<CreateMission>) -> Response {
    let bots = match state.db.list_kwants(&space).await {
        Ok(b) => b,
        Err(e) => return internal(e),
    };
    let lead = match &p.lead_kwant_id {
        Some(id) => match super::bot_in_space(&state, &space, id).await {
            Some(k) => k,
            None => return bad("lead_kwant_id isn't a bot in this space"),
        },
        None => match bots.first() {
            Some(k) => k.clone(),
            None => return bad("this space has no bots to lead a mission"),
        },
    };
    let ws = crate::tools::bot_workspace(&crate::db::spaces::space_data_dir(&state.config.data_dir, &space), &lead.id);
    let place = PlanPlace {
        direct_kwant_id: if p.channel_id.is_none() && p.thread_id.is_none() { Some(lead.id.clone()) } else { None },
        channel_id: p.channel_id.clone(),
        thread_id: p.thread_id.clone(),
        workspace_path: ws.to_string_lossy().into_owned(),
    };
    let by = PlanBy { created_by: "person", active: true };
    match super::create_plan(&state, &space, &lead, &p.title, &p.goal, p.budget_tokens, &p.tasks, by, place).await {
        Ok((m, _)) => {
            super::mission_chat_line(&state, &m, format!("Mission \"{}\" started.", m.title)).await;
            mission_out(&state, &m.id).await
        }
        Err(e) => bad(e),
    }
}

pub async fn get_mission(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
    let m = match load_mission(&state, q.as_deref(), &id).await {
        Ok(m) => m,
        Err(r) => return r,
    };
    let space = SpaceId::new(&m.space_id);
    let tasks = state.db.list_tasks(&space, None, Some(&m.id), None, 1000).await.unwrap_or_default();
    let mut out = Vec::new();
    for t in &tasks {
        out.push(task_json(&state, t).await);
    }
    Json(json!({"mission": mission_json(&state, &m).await, "tasks": out})).into_response()
}

#[derive(Deserialize)]
pub struct PatchMission {
    title: Option<String>,
    goal: Option<String>,
    budget_tokens: Option<i64>,
}

pub async fn patch_mission(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, Json(p): Json<PatchMission>) -> Response {
    let m = match load_mission(&state, q.as_deref(), &id).await {
        Ok(m) => m,
        Err(r) => return r,
    };
    if matches!(m.status.as_str(), "done" | "cancelled") {
        return conflict(format!("the mission is {}", m.status));
    }
    let title = p.title.as_deref().map(str::trim);
    if title.is_some_and(|t| t.is_empty() || t.chars().count() > 200) {
        return bad("title must be 1–200 characters");
    }
    let (lo, hi) = super::BUDGET_RANGE;
    if p.budget_tokens.is_some_and(|b| !super::valid_mission_budget(b)) {
        return bad(format!("budget_tokens must be 0 (no limit) or {lo}–{hi}"));
    }
    if let Err(e) = state.db.edit_mission(&id, title, p.goal.as_deref().map(str::trim), p.budget_tokens).await {
        return internal(e);
    }
    emit_mission(&state, &id).await;
    mission_out(&state, &id).await
}

pub async fn approve_mission(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
    let m = match load_mission(&state, q.as_deref(), &id).await {
        Ok(m) => m,
        Err(r) => return r,
    };
    match state.db.set_mission_status(&id, "draft", "active", Some("person")).await {
        Ok(true) => {}
        Ok(false) => return conflict(format!("the mission is {}, not a draft", m.status)),
        Err(e) => return internal(e),
    }
    super::promote(&state, &id).await;
    if let Ok(Some(m)) = state.db.get_mission(&id).await {
        super::mission_chat_line(&state, &m, format!("Approved: mission \"{}\" is running.", m.title)).await;
    }
    emit_mission(&state, &id).await;
    mission_out(&state, &id).await
}

pub async fn cancel_mission(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
    let m = match load_mission(&state, q.as_deref(), &id).await {
        Ok(m) => m,
        Err(r) => return r,
    };
    let ok = match m.status.as_str() {
        "draft" | "active" => state.db.set_mission_status(&id, &m.status, "cancelled", Some("person")).await,
        s => return conflict(format!("the mission is already {s}")),
    };
    match ok {
        Ok(true) => {}
        Ok(false) => return conflict("the mission changed meanwhile"),
        Err(e) => return internal(e),
    }
    let space = SpaceId::new(&m.space_id);
    for t in state.db.list_tasks(&space, None, Some(&id), None, 1000).await.unwrap_or_default() {
        if !matches!(t.state.as_str(), "verified" | "cancelled") {
            let change = TaskChange { reason: Some("the mission was cancelled".into()), ..Default::default() };
            let _ = transition(&state, &t.id, &t.state, "cancelled", Actor::Person, "person", change).await;
        }
    }
    emit_mission(&state, &id).await;
    mission_out(&state, &id).await
}

#[derive(Deserialize, Default)]
pub struct RunMission {
    max_tasks: Option<usize>,
}

/// Test hook and "Run now": starts up to `max_tasks` runner turns now, even with the board off.
pub async fn run_mission(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, body: Option<Json<RunMission>>) -> Response {
    let m = match load_mission(&state, q.as_deref(), &id).await {
        Ok(m) => m,
        Err(r) => return r,
    };
    let max = body.and_then(|b| b.0.max_tasks).unwrap_or(1);
    if !(1..=5).contains(&max) {
        return bad("max_tasks must be 1–5");
    }
    if m.status != "active" {
        return conflict(format!("the mission is {}, not active", m.status));
    }
    let (started, reason) = super::runner::run_mission(&state, &m, max).await;
    let started: Vec<Value> = started.into_iter().map(|(t, k)| json!({"task_id": t, "kwant_id": k})).collect();
    let mut v = json!({"started": started});
    if let Some(r) = reason {
        v["reason"] = json!(r);
    }
    Json(v).into_response()
}

pub async fn insights(State(state): State<AppState>, Scope(space): Scope) -> Response {
    let since = chrono::Utc::now() - chrono::Duration::days(7);
    let events = match state.db.space_events_since(&space, since).await {
        Ok(e) => e,
        Err(e) => return internal(e),
    };
    let mut verified = std::collections::HashSet::new();
    let mut false_success = 0;
    let mut waiting_result: std::collections::HashSet<String> = Default::default();
    let mut interventions = 0;
    for e in &events {
        let person = e.actor == "person";
        match e.kind.as_str() {
            "state" | "lease_expired" | "budget" => {
                if e.to_state.as_deref() == Some("verified") {
                    verified.insert(e.task_id.clone());
                }
                if e.to_state.as_deref() == Some("review") && !matches!(e.actor.as_str(), "kwant" | "person") {
                    waiting_result.insert(e.task_id.clone());
                }
                if person {
                    interventions += 1;
                }
            }
            "check_result" if waiting_result.contains(&e.task_id) => {
                let status = e.detail_value()["status"].as_str().unwrap_or("").to_string();
                if !person && matches!(status.as_str(), "failed" | "error") {
                    false_success += 1;
                    waiting_result.remove(&e.task_id);
                } else if status == "passed" {
                    waiting_result.remove(&e.task_id);
                }
                if person {
                    interventions += 1;
                }
            }
            "check_result" if person => interventions += 1,
            "check_added" if person && e.detail_value()["approval"] == json!(true) => interventions += 1,
            _ => {}
        }
    }
    let all = state.db.list_tasks(&space, None, None, None, 1000).await.unwrap_or_default();
    let flagged: std::collections::HashSet<String> = state.db.flagged_task_ids(&space).await.unwrap_or_default().into_iter().collect();
    // The board's Needs-you column: tasks in needs_you, flagged ones, review tasks waiting on a
    // check approval, tasks AutoFix holds (fix_needed, autofix_suggested, workflow_change), and
    // tasks Flight School's engine guard blocked (engine_cant_sandbox).
    // Cancelled tasks aren't on the board.
    let mut needs_you = 0;
    for t in all.iter().filter(|t| t.state != "cancelled") {
        if t.state == "needs_you"
            || flagged.contains(&t.id)
            || (t.state == "review" && !super::check_approvals(&state, t).await.is_empty())
            || !super::autofix::needs_you(&state, t).await.is_empty()
            || super::flight_school::needs_you(t).is_some()
        {
            needs_you += 1;
        }
    }
    let blocked = all.iter().filter(|t| t.state == "blocked").count();
    let tokens: i64 = all.iter().filter(|t| t.updated_at >= since).map(|t| t.spent_tokens).sum();
    let still_blocked: Vec<&str> = all.iter().filter(|t| t.state == "blocked").map(|t| t.id.as_str()).collect();
    let blocked_minutes = blocked_minutes(&events, &still_blocked, since, chrono::Utc::now());
    let per = if verified.is_empty() { Value::Null } else { json!(tokens / verified.len() as i64) };
    let (autofix_7d, failures_by_class_7d) = super::autofix::insights(&state, space.as_str(), since).await;
    let now = chrono::Utc::now();
    let weekly = match state.db.space_events_since(&space, now - chrono::Duration::weeks(WEEKS)).await {
        Ok(e) => verified_weekly(&e, now),
        Err(e) => return internal(e),
    };
    let observed = match state.db.observations(space.as_str(), since, None, None).await {
        Ok(o) => o,
        Err(e) => return internal(e),
    };
    let cost = outcome_cost(&observed);
    Json(json!({
        "verified_7d": verified.len(),
        "false_success_7d": false_success,
        "needs_you_now": needs_you,
        "blocked_now": blocked,
        "blocked_minutes_7d": blocked_minutes,
        "interventions_7d": interventions,
        "tokens_7d": tokens,
        "tokens_per_verified_7d": per,
        "autofix_7d": autofix_7d,
        "failures_by_class_7d": failures_by_class_7d,
        "verified_weekly": weekly.weeks,
        "active_weeks": weekly.active,
        "verified_per_active_week": weekly.per_active,
        "cost_7d_usd": cost.total,
        "cost_per_verified_7d_usd": cost.per_verified,
        "verified_observed_7d": cost.verified,
        "verified_priced_7d": cost.verified_priced,
        "settled_7d": cost.settled,
        "unpriced_7d": cost.unpriced,
    }))
    .into_response()
}

/// How many weeks the Insights trend covers.
pub const WEEKS: i64 = 8;

pub struct Weekly {
    /// Oldest first; the last entry is the 7 days ending now, the same window as `verified_7d`.
    pub weeks: Vec<Value>,
    /// Weeks with any task activity in the space.
    pub active: usize,
    /// Verified tasks per active week, one decimal; null with no active week.
    pub per_active: Value,
}

/// Verified tasks per rolling week over the last [`WEEKS`] weeks. A task counts once per week it
/// reached `verified` in (the `verified_7d` rule); a week is active when any task in the space had
/// an event in it.
pub fn verified_weekly(events: &[TaskEvent], now: chrono::DateTime<chrono::Utc>) -> Weekly {
    let mut weeks = Vec::new();
    let (mut active, mut total) = (0, 0);
    for i in (0..WEEKS).rev() {
        let end = now - chrono::Duration::weeks(i);
        let start = end - chrono::Duration::weeks(1);
        let inside: Vec<_> = events.iter().filter(|e| e.created_at >= start && (i == 0 || e.created_at < end)).collect();
        let verified: std::collections::HashSet<&str> = inside
            .iter()
            .filter(|e| matches!(e.kind.as_str(), "state" | "lease_expired" | "budget") && e.to_state.as_deref() == Some("verified"))
            .map(|e| e.task_id.as_str())
            .collect();
        let is_active = !inside.is_empty();
        active += usize::from(is_active);
        total += verified.len();
        weeks.push(json!({"start": start, "end": end, "verified": verified.len(), "active": is_active}));
    }
    let per_active = if active == 0 { Value::Null } else { json!((total as f64 / active as f64 * 10.0).round() / 10.0) };
    Weekly { weeks, active, per_active }
}

pub struct OutcomeCost {
    /// Reported model cost of every task that settled in the window, verified or not; null when
    /// none reported a cost.
    pub total: Value,
    /// `total` over the verified tasks that reported a cost: what one verified outcome cost,
    /// failures included. A verified task with no reported cost is left out of the divisor, so it
    /// can't pull the figure down.
    pub per_verified: Value,
    pub verified: usize,
    /// Verified tasks that reported a cost: the divisor of `per_verified`.
    pub verified_priced: usize,
    pub settled: usize,
    /// Settled tasks whose model calls reported no cost (so `total` undercounts them).
    pub unpriced: usize,
}

/// Cost per verified outcome from the settled tasks' performance observations.
pub fn outcome_cost(observed: &[crate::db::performance::Observation]) -> OutcomeCost {
    let priced: Vec<f64> = observed.iter().filter_map(|o| o.cost_usd).collect();
    let verified = observed.iter().filter(|o| o.result == "verified").count();
    let verified_priced = observed.iter().filter(|o| o.result == "verified" && o.cost_usd.is_some()).count();
    let sum: f64 = priced.iter().sum();
    let round = |x: f64| json!((x * 1_000_000.0).round() / 1_000_000.0);
    OutcomeCost {
        total: if priced.is_empty() { Value::Null } else { round(sum) },
        per_verified: if verified_priced == 0 { Value::Null } else { round(sum / verified_priced as f64) },
        verified,
        verified_priced,
        settled: observed.len(),
        unpriced: observed.len() - priced.len(),
    }
}

/// Minutes tasks spent in `blocked` between `since` and `now`, from the state events in that
/// window. A task whose first event in the window leaves `blocked`, or that is still blocked with
/// no event in the window, counts from `since`.
pub fn blocked_minutes(
    events: &[TaskEvent],
    still_blocked: &[&str],
    since: chrono::DateTime<chrono::Utc>,
    now: chrono::DateTime<chrono::Utc>,
) -> i64 {
    let mut open: std::collections::HashMap<&str, chrono::DateTime<chrono::Utc>> = Default::default();
    let mut seen: std::collections::HashSet<&str> = Default::default();
    let mut total = chrono::Duration::zero();
    for e in events.iter().filter(|e| e.to_state.is_some()) {
        let id = e.task_id.as_str();
        if seen.insert(id) && e.from_state.as_deref() == Some("blocked") {
            open.insert(id, since);
        }
        if let Some(start) = open.remove(id) {
            total += e.created_at - start;
        }
        if e.to_state.as_deref() == Some("blocked") {
            open.insert(id, e.created_at);
        }
    }
    for id in still_blocked {
        if !seen.contains(id) {
            open.insert(id, since);
        }
    }
    for start in open.values() {
        total += now - *start;
    }
    total.num_minutes().max(0)
}

// Tasks

#[derive(Deserialize)]
pub struct TaskQuery {
    state: Option<String>,
    mission_id: Option<String>,
    source_kind: Option<String>,
    limit: Option<i64>,
}

pub async fn list_tasks(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<TaskQuery>) -> Response {
    if q.state.as_deref().is_some_and(|s| !TASK_STATES.contains(&s)) {
        return bad("unknown state");
    }
    if q.source_kind.as_deref().is_some_and(|s| !SOURCE_KINDS.contains(&s)) {
        return bad("unknown source_kind");
    }
    let limit = q.limit.unwrap_or(500).clamp(1, 1000);
    match state.db.list_tasks(&space, q.state.as_deref(), q.mission_id.as_deref(), q.source_kind.as_deref(), limit).await {
        Ok(ts) => {
            let mut out = Vec::new();
            for t in &ts {
                out.push(task_json(&state, t).await);
            }
            Json(json!({"tasks": out})).into_response()
        }
        Err(e) => internal(e),
    }
}

#[derive(Deserialize)]
pub struct CreateTask {
    title: String,
    #[serde(default)]
    acceptance: String,
    mission_id: Option<String>,
    owner_kwant_id: Option<String>,
    priority: Option<i64>,
    #[serde(default)]
    depends_on: Vec<String>,
    budget_tokens: Option<i64>,
    #[serde(default)]
    checks: Vec<PlanCheck>,
    source_kind: Option<String>,
    source_id: Option<String>,
    /// Flight School's class (D10); `general` when left out.
    task_class: Option<String>,
}

pub async fn create_task(State(state): State<AppState>, Scope(space): Scope, Json(p): Json<CreateTask>) -> Response {
    let title = p.title.trim();
    if title.is_empty() || title.chars().count() > 200 {
        return bad("title must be 1–200 characters");
    }
    let source = p.source_kind.as_deref().unwrap_or("person");
    if !matches!(source, "person" | "zombie") {
        return bad("source_kind must be person or zombie");
    }
    if source == "zombie" && p.source_id.as_deref().is_none_or(|s| s.trim().is_empty()) {
        return bad("a zombie task needs source_id");
    }
    if source == "zombie" {
        if let Ok(Some(t)) = state.db.task_by_source("zombie", p.source_id.as_deref().unwrap_or("")).await {
            if !matches!(t.state.as_str(), "verified" | "cancelled" | "failed") {
                return conflict("that loose end already has a task");
            }
        }
    }
    if p.priority.is_some_and(|x| !(0..=3).contains(&x)) {
        return bad("priority must be 0–3");
    }
    if p.task_class.as_deref().is_some_and(|c| !crate::db::flight_school::valid_class(c)) {
        return bad("task_class must be 1–40 of a-z, 0-9 and -");
    }
    let mission = match &p.mission_id {
        Some(id) => match state.db.get_mission(id).await {
            Ok(Some(m)) if m.space_id == space.as_str() => {
                if matches!(m.status.as_str(), "done" | "cancelled") {
                    return conflict(format!("the mission is {}", m.status));
                }
                Some(m)
            }
            Ok(_) => return bad("mission_id isn't a mission in this space"),
            Err(e) => return internal(e),
        },
        None => None,
    };
    let owner = match &p.owner_kwant_id {
        Some(o) => match super::bot_in_space(&state, &space, o).await {
            Some(k) => Some(k),
            None => return bad("owner_kwant_id isn't a bot in this space"),
        },
        None => None,
    };
    let budget = match p.budget_tokens {
        Some(b) => b,
        None => super::default_task_budget(&state).await,
    };
    if !super::valid_task_budget(budget) {
        return bad(format!("budget_tokens must be 0 (no limit) or 1–{}", super::BUDGET_RANGE.1));
    }
    let mut approvals = Vec::new();
    for c in &p.checks {
        match validate_check(&c.kind, &c.spec, true) {
            Ok(a) => approvals.push(a),
            Err(e) => return bad(e),
        }
    }
    for d in &p.depends_on {
        match state.db.get_task(d).await {
            Ok(Some(t)) if t.space_id == space.as_str() && t.mission_id == p.mission_id => {}
            Ok(_) => return bad(format!("depends_on: {d} isn't a task of the same mission in this space")),
            Err(e) => return internal(e),
        }
    }
    // Ready at once unless it waits on something; a draft mission's tasks wait for approval
    let ready = p.depends_on.is_empty() && mission.as_ref().is_none_or(|m| m.status == "active");
    let (channel_id, direct_kwant_id, thread_id) = match (&mission, &owner) {
        (Some(m), _) => (m.channel_id.clone(), m.direct_kwant_id.clone(), m.thread_id.clone()),
        (None, Some(k)) => (None, Some(k.id.clone()), None),
        (None, None) => (None, None, None),
    };
    let new = NewTask {
        mission_id: p.mission_id.clone(),
        title: title.into(),
        acceptance: p.acceptance.trim().into(),
        state: "backlog".into(),
        priority: p.priority.unwrap_or(1),
        owner_kwant_id: None,
        suggested_kwant_id: owner.map(|k| k.id),
        budget_tokens: budget,
        max_attempts: super::DEFAULT_MAX_ATTEMPTS,
        source_kind: source.into(),
        source_id: p.source_id.clone(),
        channel_id,
        direct_kwant_id,
        thread_id,
        created_by: "person".into(),
    };
    let task = match state.db.create_task(&space, &new).await {
        Ok(t) => t,
        Err(e) => return internal(e),
    };
    if let Some(class) = p.task_class.as_deref().filter(|c| *c != crate::db::flight_school::DEFAULT_CLASS) {
        if let Err(e) = state.db.set_task_class(&task.id, class, "person").await {
            return internal(e);
        }
    }
    for (c, approved) in p.checks.iter().zip(approvals) {
        let nc = NewCheck {
            task_id: task.id.clone(),
            kind: c.kind.clone(),
            spec: c.spec.clone(),
            required: c.required.unwrap_or(true),
            approved,
            requested_by: "person".into(),
            approved_by: Some("person".into()),
        };
        if let Err(e) = state.db.add_check(&nc).await {
            return internal(e);
        }
    }
    for d in &p.depends_on {
        if let Err(e) = state.db.add_dependency(&task.id, d).await {
            return bad(e.to_string());
        }
    }
    let task = if ready {
        let change = TaskChange { reason: Some("created by the person".into()), ..Default::default() };
        match transition(&state, &task.id, "backlog", "ready", Actor::Kwant, "kwant", change).await {
            Ok(t) => t,
            Err(_) => task,
        }
    } else {
        if let Some(m) = &mission {
            super::promote(&state, &m.id).await;
        }
        state.db.get_task(&task.id).await.ok().flatten().unwrap_or(task)
    };
    emit_task(&state, &task).await;
    if let Some(m) = &task.mission_id {
        emit_mission(&state, m).await;
    }
    (StatusCode::OK, task_out(&state, &task).await).into_response()
}

pub async fn get_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
    let t = match load_task(&state, q.as_deref(), &id).await {
        Ok(t) => t,
        Err(r) => return r,
    };
    let checks = state.db.list_checks(&id).await.unwrap_or_default();
    let evidence = state.db.list_evidence(&id).await.unwrap_or_default();
    let events = state.db.task_events(&id, 500).await.unwrap_or_default();
    let mut ev = Vec::new();
    for e in &events {
        ev.push(event_json(&state, e).await);
    }
    Json(json!({
        "task": task_json(&state, &t).await,
        "checks": checks_json(&state, &t, &checks).await,
        "evidence": evidence,
        "events": ev,
    }))
    .into_response()
}

#[derive(Deserialize)]
pub struct PatchTask {
    title: Option<String>,
    acceptance: Option<String>,
    priority: Option<i64>,
    owner_kwant_id: Option<String>,
    budget_tokens: Option<i64>,
    /// Only the person changes a class (this route is person-only for bot tokens).
    task_class: Option<String>,
}

pub async fn patch_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, Json(p): Json<PatchTask>) -> Response {
    let t = match load_task(&state, q.as_deref(), &id).await {
        Ok(t) => t,
        Err(r) => return r,
    };
    if matches!(t.state.as_str(), "verified" | "cancelled") {
        return conflict(format!("the task is {}", t.state));
    }
    let title = p.title.as_deref().map(str::trim);
    if title.is_some_and(|x| x.is_empty() || x.chars().count() > 200) {
        return bad("title must be 1–200 characters");
    }
    if p.priority.is_some_and(|x| !(0..=3).contains(&x)) {
        return bad("priority must be 0–3");
    }
    if p.budget_tokens.is_some_and(|b| !super::valid_task_budget(b)) {
        return bad(format!("budget_tokens must be 0 (no limit) or 1–{}", super::BUDGET_RANGE.1));
    }
    if p.task_class.as_deref().is_some_and(|c| !crate::db::flight_school::valid_class(c)) {
        return bad("task_class must be 1–40 of a-z, 0-9 and -");
    }
    let owner = match &p.owner_kwant_id {
        Some(o) => match super::bot_in_space(&state, &SpaceId::new(&t.space_id), o).await {
            Some(k) => Some(k.id),
            None => return bad("owner_kwant_id isn't a bot in this space"),
        },
        None => None,
    };
    if let Err(e) = state.db.edit_task(&id, title, p.acceptance.as_deref().map(str::trim), p.priority, owner.as_deref(), p.budget_tokens, "person").await {
        return internal(e);
    }
    if let Some(class) = &p.task_class {
        if let Err(e) = state.db.set_task_class(&id, class, "person").await {
            return internal(e);
        }
    }
    match state.db.get_task(&id).await {
        Ok(Some(t)) => {
            emit_task(&state, &t).await;
            task_out(&state, &t).await
        }
        _ => not_found("task"),
    }
}

#[derive(Deserialize, Default)]
pub struct Note {
    note: Option<String>,
    reason: Option<String>,
    /// Verify only: the verdict the person saw (contract §9.5); refused as stale when it isn't
    /// the task's latest, or the files it judged changed since.
    verdict_id: Option<String>,
}

fn body(b: Option<Json<Note>>) -> Note {
    b.map(|b| b.0).unwrap_or_default()
}

fn stale(paths: Vec<String>, message: &str) -> Response {
    (StatusCode::CONFLICT, Json(json!({"error": message, "code": "stale", "message": message, "paths": paths}))).into_response()
}

/// Contract §9.5: `verdict_id` is this task's latest verdict, and the run it judged is still what
/// the folder holds. Checked before anything is written: a refusal verifies nothing, touches no
/// hold and records no overturn.
#[allow(clippy::result_large_err)]
async fn fresh_verdict(state: &AppState, task_id: &str, verdict_id: &str) -> Result<(), Response> {
    let verdicts = state.db.verdicts_of(task_id).await.map_err(internal)?;
    let Some(v) = verdicts.iter().find(|v| v.id == verdict_id) else {
        return Err((StatusCode::NOT_FOUND, Json(json!({"error": "no such verdict on this task", "code": "not_found"}))).into_response());
    };
    if verdicts.first().map(|l| l.id.as_str()) != Some(verdict_id) {
        return Err(stale(vec![], "a newer verdict exists"));
    }
    let Some(cid) = v.after_run_checkpoint_id.as_deref() else { return Ok(()) };
    match super::checkpoints::freshness(state, task_id, cid).await.map_err(internal)? {
        super::checkpoints::Freshness::Fresh => Ok(()),
        super::checkpoints::Freshness::Stale(paths, why) => Err(stale(paths, why)),
    }
}

/// The person's Verify: runs the task's pending kwant checks, then records a passing `person` check.
/// Verified only if every required check then passes.
pub async fn verify_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, b: Option<Json<Note>>) -> Response {
    let t = match load_task(&state, q.as_deref(), &id).await {
        Ok(t) => t,
        Err(r) => return r,
    };
    if t.state != "review" {
        return conflict(format!("only a task in review can be verified; this one is {}", t.state));
    }
    let b = body(b);
    if let Some(vid) = b.verdict_id.as_deref().map(str::trim).filter(|v| !v.is_empty()) {
        if let Err(r) = fresh_verdict(&state, &id, vid).await {
            return r;
        }
    }
    let note = b.note.unwrap_or_default();
    let c = NewCheck {
        task_id: id.clone(),
        kind: "person".into(),
        spec: json!({"note": note.chars().take(2000).collect::<String>()}),
        required: true,
        approved: true,
        requested_by: "person".into(),
        approved_by: Some("person".into()),
    };
    let check = match state.db.add_check(&c).await {
        Ok(c) => c,
        Err(e) => return internal(e),
    };
    if let Err(e) = state.db.finish_check(&check.id, "passed", Some(&note), "person", None).await {
        return internal(e);
    }
    // The person decides over the verifier: its hold passes, and a fail or needs-you is recorded as overturned
    super::verifier::person_verified(&state, &t).await;
    // Runs the approved kwant checks that haven't passed yet; evaluates
    let pending: Vec<_> = state.db.list_checks(&id).await.unwrap_or_default().into_iter().filter(|c| c.approved && c.status == "pending").collect();
    for c in &pending {
        checks::run_check(&state, &t, c).await;
    }
    let after = evaluate(&state, &id).await;
    match after {
        Some(t) if t.state == "verified" => task_out(&state, &t).await,
        Some(t) => {
            emit_task(&state, &t).await;
            let summary = super::checks_summary(&t, &state.db.list_checks(&id).await.unwrap_or_default());
            conflict(format!("not verified: its checks are {} (the task is {})", summary["status"].as_str().unwrap_or("?"), t.state))
        }
        None => not_found("task"),
    }
}

pub async fn reject_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, b: Option<Json<Note>>) -> Response {
    let t = match load_task(&state, q.as_deref(), &id).await {
        Ok(t) => t,
        Err(r) => return r,
    };
    let b = body(b);
    let Some(reason) = b.reason.or(b.note).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) else {
        return bad("reason is required");
    };
    if t.state == "review" {
        // V2: a pass the person sends back is overturned; V3: the note becomes a criterion
        super::verifier::person_sent_back(&state, &t, &reason).await;
        super::contract::add_send_back(&state, &t, &reason).await;
    }
    let change = TaskChange { reason: Some(reason), attempt: true, ..Default::default() };
    match moved(transition(&state, &id, "review", "ready", Actor::Person, "person", change).await) {
        Ok(t) => task_out(&state, &t).await,
        Err(r) => r,
    }
}

pub async fn block_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, b: Option<Json<Note>>) -> Response {
    let t = match load_task(&state, q.as_deref(), &id).await {
        Ok(t) => t,
        Err(r) => return r,
    };
    let b = body(b);
    let Some(reason) = b.reason.or(b.note).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) else {
        return bad("reason is required");
    };
    let change = TaskChange { reason: Some(reason), ..Default::default() };
    match moved(transition(&state, &id, &t.state, "blocked", Actor::Person, "person", change).await) {
        Ok(t) => task_out(&state, &t).await,
        Err(r) => r,
    }
}

pub async fn unblock_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
    let t = match load_task(&state, q.as_deref(), &id).await {
        Ok(t) => t,
        Err(r) => return r,
    };
    if t.state != "blocked" {
        return conflict(format!("the task is {}, not blocked", t.state));
    }
    let change = TaskChange::default();
    let t = match moved(transition(&state, &id, "blocked", "backlog", Actor::Person, "person", change).await) {
        Ok(t) => t,
        Err(r) => return r,
    };
    super::promote_one(&state, &t).await;
    match state.db.get_task(&id).await {
        Ok(Some(t)) => task_out(&state, &t).await,
        _ => not_found("task"),
    }
}

/// `Idempotency-Key` optional (Phase B1 §5): a repeated retry returns the first response.
pub async fn retry_task(State(state): State<AppState>, RawQuery(q): RawQuery, headers: axum::http::HeaderMap, Path(id): Path<String>) -> Response {
    let route = format!("POST /api/tasks/{id}/retry");
    super::graph::idempotent(&state, &headers, route, || async {
        load_task(&state, q.as_deref(), &id).await?;
        // A retry gets the same number of attempts again
        let change = TaskChange { reason: Some("retried by the person".into()), detail: Some(json!({"reset_attempts": true})), ..Default::default() };
        let t = moved(transition(&state, &id, "failed", "ready", Actor::Person, "person", change).await)?;
        let _ = state.db.reset_attempts(&id).await;
        let t = state.db.get_task(&id).await.ok().flatten().unwrap_or(t);
        emit_task(&state, &t).await;
        Ok(task_json(&state, &t).await)
    })
    .await
}

pub async fn cancel_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
    let t = match load_task(&state, q.as_deref(), &id).await {
        Ok(t) => t,
        Err(r) => return r,
    };
    let change = TaskChange { reason: Some("cancelled by the person".into()), ..Default::default() };
    match moved(transition(&state, &id, &t.state, "cancelled", Actor::Person, "person", change).await) {
        Ok(t) => task_out(&state, &t).await,
        Err(r) => r,
    }
}

#[derive(Deserialize)]
pub struct AddCheck {
    kind: String,
    #[serde(default)]
    spec: Value,
    required: Option<bool>,
}

pub async fn add_task_check(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, Json(p): Json<AddCheck>) -> Response {
    let t = match load_task(&state, q.as_deref(), &id).await {
        Ok(t) => t,
        Err(r) => return r,
    };
    if matches!(t.state.as_str(), "verified" | "cancelled") {
        return conflict(format!("the task is {}", t.state));
    }
    if let Err(e) = validate_check(&p.kind, &p.spec, true) {
        return bad(e);
    }
    let c = NewCheck { task_id: id.clone(), kind: p.kind, spec: p.spec, required: p.required.unwrap_or(true), approved: true, requested_by: "person".into(), approved_by: Some("person".into()) };
    let check = match state.db.add_check(&c).await {
        Ok(c) => c,
        Err(e) => return internal(e),
    };
    let check = if t.state == "review" { checks::run_check(&state, &t, &check).await } else { check };
    if let Some(t) = evaluate(&state, &id).await {
        emit_task(&state, &t).await;
    }
    Json(super::check_json(&t, &check, super::name_of(&state, check.checked_by.as_deref()).await)).into_response()
}

pub async fn run_task_checks(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
    if let Err(r) = load_task(&state, q.as_deref(), &id).await {
        return r;
    }
    let (checks, task) = checks::run_task_checks(&state, &id, None).await;
    let Some(task) = task else { return not_found("task") };
    Json(json!({"checks": checks_json(&state, &task, &checks).await, "task": task_json(&state, &task).await})).into_response()
}

pub async fn approve_check(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
    let check = match state.db.get_check(&id).await {
        Ok(Some(c)) => c,
        Ok(None) => return not_found("check"),
        Err(e) => return internal(e),
    };
    let t = match load_task(&state, q.as_deref(), &check.task_id).await {
        Ok(t) => t,
        Err(r) => return r,
    };
    match state.db.approve_check(&id).await {
        Ok(true) => {}
        Ok(false) => return conflict(format!("the check is {}, not waiting for approval", check.status)),
        Err(e) => return internal(e),
    }
    let _ = state.db.log_task_event(&t.id, "check_added", "person", &json!({"check_id": id, "approved": true, "approval": true})).await;
    let check = state.db.get_check(&id).await.ok().flatten().unwrap_or(check);
    // In review the check may decide the task. On a verified task it runs for the record only:
    // `evaluate` leaves a verified task alone, so a failing optional check can't undo it.
    let check = if matches!(t.state.as_str(), "review" | "verified") { checks::run_check(&state, &t, &check).await } else { check };
    if let Some(t) = evaluate(&state, &t.id).await {
        emit_task(&state, &t).await;
    }
    Json(super::check_json(&t, &check, super::name_of(&state, check.checked_by.as_deref()).await)).into_response()
}

/// `POST /api/checks/:id/wait-more` (person only): a check waiting on an outside service, or
/// stopped at its deadline, waits 24 h more and runs again on the next tick. The task must be in
/// review.
pub async fn wait_more(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
    let check = match state.db.get_check(&id).await {
        Ok(Some(c)) => c,
        Ok(None) => return not_found("check"),
        Err(e) => return internal(e),
    };
    let t = match load_task(&state, q.as_deref(), &check.task_id).await {
        Ok(t) => t,
        Err(r) => return r,
    };
    if t.state != "review" {
        return conflict(format!("only a task in review waits on its checks; this one is {}", t.state));
    }
    let hours = crate::db::missions::WAIT_MORE_HOURS;
    match state.db.extend_wait(&id, chrono::Utc::now(), hours).await {
        Ok(true) => {}
        Ok(false) => return conflict(format!("the check is {}, not waiting", check.status)),
        Err(e) => return internal(e),
    }
    let _ = state.db.log_task_event(&t.id, "check_wait_more", "person", &json!({"check_id": id, "hours": hours})).await;
    let check = state.db.get_check(&id).await.ok().flatten().unwrap_or(check);
    emit_task(&state, &t).await;
    Json(super::check_json(&t, &check, super::name_of(&state, check.checked_by.as_deref()).await)).into_response()
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{Duration, TimeZone, Utc};

    fn ev(task: &str, from: &str, to: &str, at: chrono::DateTime<Utc>) -> TaskEvent {
        TaskEvent {
            id: 0,
            task_id: task.into(),
            mission_id: None,
            kind: "state".into(),
            actor: "person".into(),
            from_state: Some(from.into()),
            to_state: Some(to.into()),
            detail: String::new(),
            created_at: at,
        }
    }

    #[test]
    fn blocked_minutes_sums_time_in_blocked_within_the_window() {
        let since = Utc.with_ymd_and_hms(2026, 10, 20, 0, 0, 0).unwrap();
        let now = since + Duration::days(7);
        let events = vec![
            // a: blocked for 30 minutes inside the window
            ev("a", "ready", "blocked", since + Duration::hours(1)),
            ev("a", "blocked", "ready", since + Duration::hours(1) + Duration::minutes(30)),
            // b: blocked before the window, unblocked 2 hours in
            ev("b", "blocked", "ready", since + Duration::hours(2)),
            // c: blocked 10 minutes before now and still blocked
            ev("c", "ready", "blocked", now - Duration::minutes(10)),
        ];
        // d: blocked the whole window with no event in it
        assert_eq!(blocked_minutes(&events, &["c", "d"], since, now), 30 + 120 + 10 + 7 * 24 * 60);
        assert_eq!(blocked_minutes(&[], &[], since, now), 0);
    }

    #[test]
    fn verified_weekly_buckets_rolling_weeks_and_counts_active_ones() {
        let now = Utc.with_ymd_and_hms(2026, 11, 1, 12, 0, 0).unwrap();
        let events = vec![
            // this week: a verified twice (once), b verified, c only moved
            ev("a", "review", "verified", now - Duration::days(1)),
            ev("a", "review", "verified", now - Duration::hours(2)),
            ev("b", "review", "verified", now),
            ev("c", "ready", "working", now - Duration::days(3)),
            // just over a week back: the previous week
            ev("d", "review", "verified", now - Duration::weeks(1) - Duration::minutes(1)),
            // three weeks back: activity, nothing verified
            ev("e", "ready", "blocked", now - Duration::days(17)),
            // older than the 8 weeks: ignored
            ev("f", "review", "verified", now - Duration::weeks(9)),
        ];
        let w = verified_weekly(&events, now);
        let got: Vec<(u64, bool)> = w.weeks.iter().map(|x| (x["verified"].as_u64().unwrap(), x["active"].as_bool().unwrap())).collect();
        assert_eq!(got, vec![(0, false), (0, false), (0, false), (0, false), (0, false), (0, true), (1, true), (2, true)]);
        assert_eq!((w.active, w.per_active.clone()), (3, json!(1.0)));
        assert_eq!(w.weeks[7]["end"], json!(now));
        let none = verified_weekly(&[], now);
        assert_eq!((none.weeks.len(), none.active, none.per_active), (8, 0, Value::Null));
    }

    #[test]
    fn outcome_cost_spreads_failures_over_verified_outcomes() {
        let o = |result: &str, cost: Option<f64>| crate::db::performance::Observation {
            id: 0,
            task_id: String::new(),
            space_id: String::new(),
            mission_id: None,
            task_class: "general".into(),
            kwant_id: String::new(),
            engine: String::new(),
            model: String::new(),
            started_at: None,
            finished_at: Utc::now(),
            latency_ms: 0,
            runs: 1,
            fresh_tokens: 0,
            cost_usd: cost,
            result: result.into(),
            approvals: 0,
            check_approvals: 0,
            unblocks: 0,
            retries: 0,
            autofix_attempts: 0,
            interventions: 0,
            source: "live".into(),
            created_at: Utc::now(),
        };
        // The unpriced verified task isn't in the divisor: 0.6 over the 2 priced verified, not 3
        let c = outcome_cost(&[o("verified", Some(0.1)), o("verified", Some(0.2)), o("failed", Some(0.3)), o("verified", None)]);
        assert_eq!((c.total, c.per_verified, c.verified, c.verified_priced, c.settled, c.unpriced), (json!(0.6), json!(0.3), 3, 2, 4, 1));
        // Priced failures but no priced verified task: no per-outcome figure, never a made-up one
        let c = outcome_cost(&[o("failed", Some(0.3)), o("verified", None)]);
        assert_eq!((c.total, c.per_verified, c.verified, c.verified_priced), (json!(0.3), Value::Null, 1, 0));
        let c = outcome_cost(&[o("failed", Some(0.3))]);
        assert_eq!((c.total, c.per_verified), (json!(0.3), Value::Null), "no verified outcome: no per-outcome cost");
        let c = outcome_cost(&[o("verified", None)]);
        assert_eq!((c.total, c.per_verified, c.unpriced), (Value::Null, Value::Null, 1));
    }
}