Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Performance Market, report-only (Phase D1)
Lin (kwant bot)7212f94bd873
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 21e37e75..7111ed17 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).## Unreleased+### Added+- **Performance Market (report-only).** kwant now records how each finished task went: who did it, on+ which model, how long it took, its tokens and cost, whether it ended verified, and how often you had+ to step in. Earlier finished tasks are filled in once on upgrade. `GET /api/performance` groups this+ by task class and bot (and model) with a 95% confidence range on the verified rate and flags groups+ with fewer than 5 tasks. It doesn't change who gets work: Laya still routes. No screen for it yet.+### Fixed- **"Answer in chat" works when that chat is already open.** On the Mission board, "Answer in chat" and"Open the chat it came from" now close the board and show the chat even when it's the one alreadydiff --git a/docs/mission-control.md b/docs/mission-control.mdindex 67dd78af..b81a163c 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -649,3 +649,35 @@ and text "Paused after N hand-offs so it doesn't loop: A, B not sent yet. Pressperson typing "continue" while it's the newest bot message. Continuing sets `resumed` true and handsonly the waiting teammates the lead's reply, with a fresh allowance.+## 17. Performance Market (Phase D1, report-only)++kwant observes every task once it settles and reports, per task class × bot (× model), how often work+ends **verified**, how long it takes, what it costs and how often the person stepped in. Nothing reads+these numbers to route work: Laya stays the router, and bots can't read the report.++**One row per task** in `performance_observations`, written when a task moves to `verified`, `failed`+or `cancelled` (`after_move` → `performance::record_soon`, in the background; a failure is logged and+never fails or slows the move). `cancelled` counts as `unverified`, and only if the task ran (had a+claim). Tasks with no owner are skipped. A reopened task that settles again replaces its row, so it+counts once, by its last outcome, with the earlier attempts in `retries` / `autofix_attempts`.++| Field | From |+|-------|------|+| `latency_ms`, `runs`, `started_at` | the task's claims (time a bot held it), their count, the first one |+| `fresh_tokens` | `tasks.spent_tokens` |+| `model`, `cost_usd` | the owner's `model_usage` rows inside the claim windows (model with the most tokens, else the bot's preferred model); `cost_usd` is null if none was reported |+| `engine` | the bot's driver type |+| `approvals`, `check_approvals`, `unblocks`, `retries`, `autofix_attempts` | tool cards answered, owner checks the person approved, person moves out of blocked/needs you, person `failed → ready`, AutoFix attempts that ran; `interventions` is their sum |++Model and cost are attributed by time, not by turn: a bot chatting elsewhere while it holds a claim+adds to the task's cost. The token number is the exact mission meter.++**Backfill.** On startup, once (setting `performance_backfill_v1`), every finished task is observed+with the same rules and inserted as `source = 'backfill'`; rows that exist are never overwritten.++**`GET /api/performance?space=&class=&bot=&since=&by=`** (person-only, read-only). `since` is+`Nd` (1–365), a `YYYY-MM-DD` date or an RFC 3339 time, default `30d`; `by` is `model` (default) or+`bot`; anything else is 400. Each group has `n`, `verified` / `failed` / `unverified`,+`verified_rate`, `verified_ci95` (Wilson score interval, z = 1.96), `median_latency_ms`,+`median_fresh_tokens`, `cost_usd` and `cost_per_task_usd` (over rows with a cost),+`interventions_per_task` and `low_confidence` (n < 5). Groups sort by class, then n descending.diff --git a/src/db/mod.rs b/src/db/mod.rsindex c0634887..bd0b1ac6 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -29,6 +29,7 @@ pub mod mission_graph;pub mod checkpoints;pub mod autofix;pub mod flight_school;+pub mod performance;/// What a space's #general says about itself.pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";@@ -183,6 +184,8 @@ impl Database {db.migrate_flight_school().await?;// Last: it rebuilds `tasks` and `missions` from their stored SQL, columns and triggers includeddb.migrate_opt_in_budgets().await?;+ // After it: observes finished tasks once (their class comes from Flight School)+ db.migrate_performance().await?;db.pool.close().await;let pool = SqlitePoolOptions::new()diff --git a/src/db/performance.rs b/src/db/performance.rsnew file mode 100644index 00000000..939d2610--- /dev/null+++ b/src/db/performance.rs@@ -0,0 +1,346 @@+//! Mission Control Phase D1: the Performance Market's observations. One row per settled task+//! (verified, failed, or cancelled after it ran): who did it, on which model, how long it took,+//! what it spent, how it ended and how often the person stepped in. Report-only: nothing routes+//! on these rows. See docs/mission-control.md §17.++use super::{Database, DbError};+use chrono::{DateTime, Utc};+use serde::Serialize;+use sqlx::FromRow;+use std::collections::HashMap;++/// Set once the finished tasks from before this table existed were observed.+const BACKFILL_DONE: &str = "performance_backfill_v1";++/// One model call of the owner: model, fresh input, output, cost, when.+type UsageRow = (String, i64, i64, Option<f64>, DateTime<Utc>);++#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct Observation {+ pub id: i64,+ pub task_id: String,+ pub space_id: String,+ pub mission_id: Option<String>,+ pub task_class: String,+ pub kwant_id: String,+ pub engine: String,+ pub model: String,+ pub started_at: Option<DateTime<Utc>>,+ pub finished_at: DateTime<Utc>,+ /// Time a bot held the task: the sum of its claims.+ pub latency_ms: i64,+ pub runs: i64,+ pub fresh_tokens: i64,+ /// `None` when no model call in the task's claims reported a cost.+ pub cost_usd: Option<f64>,+ /// `verified`, `failed` or `unverified` (cancelled after it ran).+ pub result: String,+ pub approvals: i64,+ pub check_approvals: i64,+ pub unblocks: i64,+ pub retries: i64,+ pub autofix_attempts: i64,+ pub interventions: i64,+ /// `live` (recorded as the task settled) or `backfill`.+ pub source: String,+ pub created_at: DateTime<Utc>,+}++/// An observation before it's stored.+#[derive(Debug, Clone, PartialEq)]+pub struct NewObservation {+ pub task_id: String,+ pub space_id: String,+ pub mission_id: Option<String>,+ pub task_class: String,+ pub kwant_id: String,+ pub engine: String,+ pub model: String,+ pub started_at: Option<DateTime<Utc>>,+ pub finished_at: DateTime<Utc>,+ pub latency_ms: i64,+ pub runs: i64,+ pub fresh_tokens: i64,+ pub cost_usd: Option<f64>,+ pub result: &'static str,+ pub approvals: i64,+ pub check_approvals: i64,+ pub unblocks: i64,+ pub retries: i64,+ pub autofix_attempts: i64,+}++/// The settled state's result; `None` while the task isn't settled.+pub fn result_of(state: &str) -> Option<&'static str> {+ match state {+ "verified" => Some("verified"),+ "failed" => Some("failed"),+ "cancelled" => Some("unverified"),+ _ => None,+ }+}++#[derive(FromRow)]+struct TaskRow {+ id: String,+ space_id: String,+ mission_id: Option<String>,+ state: String,+ owner_kwant_id: Option<String>,+ spent_tokens: i64,+ finished_at: Option<DateTime<Utc>>,+ task_class: String,+}++impl Database {+ pub(super) async fn migrate_performance(&self) -> Result<(), DbError> {+ for stmt in [+ "CREATE TABLE IF NOT EXISTS performance_observations (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ task_id TEXT NOT NULL UNIQUE,+ space_id TEXT NOT NULL,+ mission_id TEXT,+ task_class TEXT NOT NULL,+ kwant_id TEXT NOT NULL,+ engine TEXT NOT NULL,+ model TEXT NOT NULL,+ started_at TIMESTAMP,+ finished_at TIMESTAMP NOT NULL,+ latency_ms INTEGER NOT NULL CHECK (latency_ms >= 0),+ runs INTEGER NOT NULL,+ fresh_tokens INTEGER NOT NULL,+ cost_usd REAL,+ result TEXT NOT NULL CHECK (result IN ('verified', 'failed', 'unverified')),+ approvals INTEGER NOT NULL,+ check_approvals INTEGER NOT NULL,+ unblocks INTEGER NOT NULL,+ retries INTEGER NOT NULL,+ autofix_attempts INTEGER NOT NULL,+ interventions INTEGER NOT NULL,+ source TEXT NOT NULL CHECK (source IN ('live', 'backfill')),+ created_at TIMESTAMP NOT NULL+ )",+ "CREATE INDEX IF NOT EXISTS performance_space_class ON performance_observations (space_id, task_class, finished_at)",+ ] {+ sqlx::query(stmt).execute(&self.pool).await?;+ }+ // Best-effort: a backfill that fails never stops kwant from starting+ if let Err(e) = self.backfill_performance().await {+ tracing::warn!(error = %e, "performance backfill failed; it runs again on the next start");+ }+ Ok(())+ }++ /// Observes every settled task once (`source = 'backfill'`), leaving rows that exist alone.+ /// Runs at most once per database (a setting marks it done). The number of rows added.+ pub async fn backfill_performance(&self) -> Result<u64, DbError> {+ if self.get_setting(BACKFILL_DONE).await?.is_some() {+ return Ok(0);+ }+ let ids: Vec<(String,)> = sqlx::query_as(+ "SELECT id FROM tasks WHERE finished_at IS NOT NULL AND state IN ('verified', 'failed', 'cancelled') ORDER BY finished_at",+ )+ .fetch_all(&self.pool)+ .await?;+ let mut added = 0;+ for (id,) in ids {+ match self.observe_task(&id).await {+ Ok(Some(o)) => added += self.store_observation(&o, "backfill").await?,+ Ok(None) => {}+ Err(e) => tracing::warn!(task_id = %id, error = %e, "task skipped in the performance backfill"),+ }+ }+ self.set_setting(BACKFILL_DONE, &Utc::now().to_rfc3339()).await?;+ Ok(added)+ }++ /// What a settled task tells about its owner. `None` while it isn't settled, when it has no+ /// owner, or when it was cancelled before any bot ran it.+ pub async fn observe_task(&self, task_id: &str) -> Result<Option<NewObservation>, DbError> {+ let Some(t) = sqlx::query_as::<_, TaskRow>(+ "SELECT id, space_id, mission_id, state, owner_kwant_id, spent_tokens, finished_at, task_class FROM tasks WHERE id = ?",+ )+ .bind(task_id)+ .fetch_optional(&self.pool)+ .await?+ else {+ return Ok(None);+ };+ let (Some(result), Some(kwant_id), Some(finished_at)) = (result_of(&t.state), t.owner_kwant_id.clone(), t.finished_at) else {+ return Ok(None);+ };+ // Claims: the windows a bot held the task (an open one ends at the settle)+ let claims: Vec<(i64, Option<i64>)> =+ sqlx::query_as("SELECT claimed_at, released_at FROM agent_claims WHERE task_id = ? ORDER BY claimed_at").bind(&t.id).fetch_all(&self.pool).await?;+ if claims.is_empty() && result == "unverified" {+ return Ok(None);+ }+ let end_ms = finished_at.timestamp_millis();+ let windows: Vec<(i64, i64)> = claims.iter().map(|&(a, b)| (a, b.unwrap_or(end_ms).max(a))).collect();+ let latency_ms = windows.iter().map(|(a, b)| b - a).sum();+ let started_at = windows.first().and_then(|(a, _)| DateTime::<Utc>::from_timestamp_millis(*a));++ // Model and cost: the owner's model calls inside the claim windows+ let (mut by_model, mut cost, mut any_cost) = (HashMap::<String, i64>::new(), 0.0, false);+ if let (Some(first), Some(last)) = (windows.iter().map(|w| w.0).min(), windows.iter().map(|w| w.1).max()) {+ // A second of slack on each side for the stored time format; the windows decide below+ let from = DateTime::<Utc>::from_timestamp_millis(first - 1000).unwrap_or(finished_at);+ let to = DateTime::<Utc>::from_timestamp_millis(last + 1000).unwrap_or(finished_at);+ let calls: Vec<UsageRow> = sqlx::query_as(+ "SELECT model, fresh_input, output, cost_usd, created_at FROM model_usage WHERE kwant_id = ? AND created_at >= ? AND created_at <= ?",+ )+ .bind(&kwant_id)+ .bind(from)+ .bind(to)+ .fetch_all(&self.pool)+ .await?;+ for (model, fresh, output, c, at) in calls {+ let ms = at.timestamp_millis();+ if !windows.iter().any(|(a, b)| ms >= *a && ms <= *b) {+ continue;+ }+ *by_model.entry(model).or_default() += fresh + output;+ if let Some(c) = c {+ cost += c;+ any_cost = true;+ }+ }+ }+ let bot: Option<(String, String)> =+ sqlx::query_as("SELECT driver_type, preferred_model FROM kwants WHERE id = ?").bind(&kwant_id).fetch_optional(&self.pool).await?;+ let engine = bot.as_ref().map(|b| b.0.clone()).unwrap_or_else(|| "unknown".into());+ let model = by_model+ .into_iter()+ .max_by(|a, b| a.1.cmp(&b.1).then_with(|| b.0.cmp(&a.0)))+ .map(|(m, _)| m)+ .or_else(|| bot.map(|b| b.1).filter(|m| !m.is_empty()))+ .unwrap_or_else(|| "unknown".into());++ // Interventions+ let (unblocks, retries): (i64, i64) = sqlx::query_as(+ "SELECT \+ COALESCE(SUM(from_state IN ('blocked', 'needs_you') AND to_state NOT IN ('cancelled', 'failed')), 0), \+ COALESCE(SUM(from_state = 'failed' AND to_state = 'ready'), 0) \+ FROM task_events WHERE task_id = ? AND kind = 'state' AND actor = 'person'",+ )+ .bind(&t.id)+ .fetch_one(&self.pool)+ .await?;+ let check_approvals: (i64,) = sqlx::query_as(+ "SELECT COUNT(*) FROM task_events WHERE task_id = ? AND kind = 'check_added' AND actor = 'person' AND json_extract(detail, '$.approval') = 1",+ )+ .bind(&t.id)+ .fetch_one(&self.pool)+ .await?;+ let approvals: (i64,) = sqlx::query_as(+ "SELECT COUNT(*) FROM turn_tool_calls WHERE task_id = ? AND approval_id IS NOT NULL AND decision IN ('approved', 'denied')",+ )+ .bind(&t.id)+ .fetch_one(&self.pool)+ .await?;+ let autofix: (i64,) = sqlx::query_as(+ "SELECT COUNT(*) FROM autofix_attempts WHERE task_id = ? AND status IN ('scheduled', 'running', 'succeeded', 'failed')",+ )+ .bind(&t.id)+ .fetch_one(&self.pool)+ .await?;++ Ok(Some(NewObservation {+ task_id: t.id,+ space_id: t.space_id,+ mission_id: t.mission_id,+ task_class: t.task_class,+ kwant_id,+ engine,+ model,+ started_at,+ finished_at,+ latency_ms,+ runs: claims.len() as i64,+ fresh_tokens: t.spent_tokens,+ cost_usd: any_cost.then_some(cost),+ result,+ approvals: approvals.0,+ check_approvals: check_approvals.0,+ unblocks,+ retries,+ autofix_attempts: autofix.0,+ }))+ }++ /// Stores `o`. A `live` row replaces the task's earlier one (a task reopened and settled+ /// again is observed by its last outcome); a `backfill` row never replaces anything.+ /// The number of rows written (0 or 1).+ pub async fn store_observation(&self, o: &NewObservation, source: &str) -> Result<u64, DbError> {+ let on_conflict = if source == "live" {+ "ON CONFLICT(task_id) DO UPDATE SET space_id = excluded.space_id, mission_id = excluded.mission_id, \+ task_class = excluded.task_class, kwant_id = excluded.kwant_id, engine = excluded.engine, model = excluded.model, \+ started_at = excluded.started_at, finished_at = excluded.finished_at, latency_ms = excluded.latency_ms, \+ runs = excluded.runs, fresh_tokens = excluded.fresh_tokens, cost_usd = excluded.cost_usd, result = excluded.result, \+ approvals = excluded.approvals, check_approvals = excluded.check_approvals, unblocks = excluded.unblocks, \+ retries = excluded.retries, autofix_attempts = excluded.autofix_attempts, interventions = excluded.interventions, \+ source = excluded.source, created_at = excluded.created_at"+ } else {+ "ON CONFLICT(task_id) DO NOTHING"+ };+ let interventions = o.approvals + o.check_approvals + o.unblocks + o.retries + o.autofix_attempts;+ let r = sqlx::query(&format!(+ "INSERT INTO performance_observations (task_id, space_id, mission_id, task_class, kwant_id, engine, model, started_at, \+ finished_at, latency_ms, runs, fresh_tokens, cost_usd, result, approvals, check_approvals, unblocks, retries, \+ autofix_attempts, interventions, source, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) {on_conflict}"+ ))+ .bind(&o.task_id)+ .bind(&o.space_id)+ .bind(&o.mission_id)+ .bind(&o.task_class)+ .bind(&o.kwant_id)+ .bind(&o.engine)+ .bind(&o.model)+ .bind(o.started_at)+ .bind(o.finished_at)+ .bind(o.latency_ms)+ .bind(o.runs)+ .bind(o.fresh_tokens)+ .bind(o.cost_usd)+ .bind(o.result)+ .bind(o.approvals)+ .bind(o.check_approvals)+ .bind(o.unblocks)+ .bind(o.retries)+ .bind(o.autofix_attempts)+ .bind(interventions)+ .bind(source)+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ Ok(r.rows_affected())+ }++ /// Observes `task_id` as it settles and stores it (`live`). `false` when there was nothing to observe.+ pub async fn record_performance(&self, task_id: &str) -> Result<bool, DbError> {+ match self.observe_task(task_id).await? {+ Some(o) => Ok(self.store_observation(&o, "live").await? > 0),+ None => Ok(false),+ }+ }++ /// The space's observations that settled at or after `since`, optionally of one class and bot.+ pub async fn observations(&self, space_id: &str, since: DateTime<Utc>, class: Option<&str>, kwant_id: Option<&str>) -> Result<Vec<Observation>, DbError> {+ Ok(sqlx::query_as::<_, Observation>(+ "SELECT * FROM performance_observations WHERE space_id = ? AND finished_at >= ? \+ AND (? IS NULL OR task_class = ?) AND (? IS NULL OR kwant_id = ?) ORDER BY finished_at",+ )+ .bind(space_id)+ .bind(since)+ .bind(class)+ .bind(class)+ .bind(kwant_id)+ .bind(kwant_id)+ .fetch_all(&self.pool)+ .await?)+ }++ pub async fn observation_of(&self, task_id: &str) -> Result<Option<Observation>, DbError> {+ Ok(sqlx::query_as::<_, Observation>("SELECT * FROM performance_observations WHERE task_id = ?").bind(task_id).fetch_optional(&self.pool).await?)+ }+}diff --git a/src/server/auth.rs b/src/server/auth.rsindex 677539cd..7dcb92a5 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -340,6 +340,9 @@ pub fn person_only(method: &Method, path: &str) -> bool {// AutoFix's proposed changes to routines, checks and tasks: only the person reads, approves// or rejects them; bots only propose (the `workflow_propose` tool)["", "api", "workflow-changes", ..] => true,+ // The Performance Market's scoreboard is the person's report: bots never read it, so it+ // can't feed a bot's own routing or be played for (Phase D1)+ ["", "api", "performance", ..] => true,// Flight School: only the person gives or takes a bot's freedom (C3); reads stay open["", "api", "capabilities", ..] => *method != Method::GET && *method != Method::HEAD,// App-wide settings, including where notifications go (`notify_webhook_url`), and the@@ -881,6 +884,7 @@ mod tests {assert!(!person_only(&get, "/api/tasks/t1/flags"));assert!(!person_only(&get, "/api/tasks"));assert!(!person_only(&get, "/api/missions/insights"));+ assert!(person_only(&get, "/api/performance"));assert!(person_only(&post, "/api/passwords/bitwarden/unlock"));assert!(person_only(&del, "/api/passwords/bitwarden"));assert!(person_only(&post, "/api/passwords/migrate"));diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rsindex c6ba4b5b..34e5b0ba 100644--- a/src/server/missions/mod.rs+++ b/src/server/missions/mod.rs@@ -18,6 +18,7 @@ pub mod checks;pub mod flight_school;pub mod graph;pub mod listener;+pub mod performance;pub mod routes;pub mod runner;pub mod tools;@@ -233,6 +234,10 @@ pub async fn transition(}async fn after_move(state: &AppState, task: &Task, to: &str) {+ // The Performance Market observes a settled task in the background (report-only, D1)+ if crate::db::performance::result_of(to).is_some() {+ performance::record_soon(state, &task.id);+ }if to == "ready" {listener::kick_handoff(state, task);}diff --git a/src/server/missions/performance.rs b/src/server/missions/performance.rsnew file mode 100644index 00000000..9e4618df--- /dev/null+++ b/src/server/missions/performance.rs@@ -0,0 +1,217 @@+//! Mission Control Phase D1: the Performance Market, report-only. A settled task is observed in+//! the background (`record_soon`); `GET /api/performance` groups the observations by task class ×+//! bot (× model) with a Wilson interval on the verified rate. Nothing routes on it: Laya stays the+//! router. See docs/mission-control.md §17.++use super::routes::{bad, internal};+use crate::db::performance::Observation;+use crate::server::spaces::Scope;+use crate::server::AppState;+use axum::{+ extract::{Query, State},+ response::{IntoResponse, Response},+ Json,+};+use chrono::{DateTime, Duration, NaiveDate, Utc};+use serde::Deserialize;+use serde_json::{json, Value};+use std::collections::{BTreeMap, HashMap};++/// Groups with fewer observations than this are `low_confidence`.+pub const MIN_N: usize = 5;+const DEFAULT_DAYS: i64 = 30;++/// Observes `task_id` in the background once it settled. Never blocks or fails the move that+/// settled it: a failure is logged and dropped.+pub fn record_soon(state: &AppState, task_id: &str) {+ let (db, id) = (state.db.clone(), task_id.to_string());+ tokio::spawn(async move {+ if let Err(e) = db.record_performance(&id).await {+ tracing::warn!(task_id = %id, error = %e, "performance observation not recorded");+ }+ });+}++/// The Wilson score interval (z = 1.96) of `k` successes in `n`; `None` when `n` is 0.+pub fn wilson(k: usize, n: usize) -> Option<(f64, f64)> {+ if n == 0 {+ return None;+ }+ let (z, n, p) = (1.96_f64, n as f64, k as f64 / n as f64);+ let z2 = z * z;+ let denom = 1.0 + z2 / n;+ let centre = (p + z2 / (2.0 * n)) / denom;+ let half = z * (p * (1.0 - p) / n + z2 / (4.0 * n * n)).sqrt() / denom;+ Some(((centre - half).max(0.0), (centre + half).min(1.0)))+}++/// The middle value, or the mean of the two middle ones; `None` when empty.+pub fn median(mut xs: Vec<i64>) -> Option<f64> {+ if xs.is_empty() {+ return None;+ }+ xs.sort_unstable();+ let m = xs.len() / 2;+ Some(if xs.len() % 2 == 1 { xs[m] as f64 } else { (xs[m - 1] as f64 + xs[m] as f64) / 2.0 })+}++/// `since` as an RFC 3339 time, a `YYYY-MM-DD` date (midnight UTC) or `Nd` (1–365 days back).+pub fn parse_since(s: Option<&str>, now: DateTime<Utc>) -> Result<DateTime<Utc>, String> {+ let Some(s) = s.map(str::trim).filter(|s| !s.is_empty()) else {+ return Ok(now - Duration::days(DEFAULT_DAYS));+ };+ if let Some(days) = s.strip_suffix('d') {+ return match days.parse::<i64>() {+ Ok(d) if (1..=365).contains(&d) => Ok(now - Duration::days(d)),+ _ => Err("since: use a number of days from 1d to 365d".into()),+ };+ }+ if let Ok(t) = DateTime::parse_from_rfc3339(s) {+ return Ok(t.with_timezone(&Utc));+ }+ if let Ok(d) = NaiveDate::parse_from_str(s, "%Y-%m-%d") {+ return Ok(d.and_hms_opt(0, 0, 0).map(|t| t.and_utc()).unwrap_or(now));+ }+ Err("since: use a time (RFC 3339), a date (YYYY-MM-DD) or a number of days such as 30d".into())+}++fn round(x: f64, places: i32) -> f64 {+ let f = 10_f64.powi(places);+ (x * f).round() / f+}++/// The report's groups, sorted by task class and then by size (largest first).+pub fn group(rows: &[Observation], by_model: bool, names: &HashMap<String, String>) -> Vec<Value> {+ let mut groups: BTreeMap<(String, String, String), Vec<&Observation>> = BTreeMap::new();+ for o in rows {+ let model = if by_model { o.model.clone() } else { String::new() };+ groups.entry((o.task_class.clone(), o.kwant_id.clone(), model)).or_default().push(o);+ }+ let mut out: Vec<(String, usize, Value)> = groups+ .into_iter()+ .map(|((class, kwant_id, model), os)| {+ let n = os.len();+ let count = |r: &str| os.iter().filter(|o| o.result == r).count();+ let verified = count("verified");+ let (lo, hi) = wilson(verified, n).unwrap_or((0.0, 1.0));+ let costs: Vec<f64> = os.iter().filter_map(|o| o.cost_usd).collect();+ let interventions: i64 = os.iter().map(|o| o.interventions).sum();+ // Engines in the group, most common first (a bot's engine can change over time)+ let mut engines: Vec<(String, usize)> = os.iter().fold(HashMap::<String, usize>::new(), |mut m, o| {+ *m.entry(o.engine.clone()).or_default() += 1;+ m+ })+ .into_iter()+ .collect();+ engines.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));+ let mut g = json!({+ "task_class": class,+ "kwant_id": kwant_id,+ "kwant_name": names.get(&kwant_id),+ "engine": engines.first().map(|e| e.0.clone()),+ "n": n,+ "verified": verified,+ "failed": count("failed"),+ "unverified": count("unverified"),+ "verified_rate": round(verified as f64 / n as f64, 4),+ "verified_ci95": [round(lo, 4), round(hi, 4)],+ "median_latency_ms": median(os.iter().map(|o| o.latency_ms).collect()),+ "median_fresh_tokens": median(os.iter().map(|o| o.fresh_tokens).collect()),+ "cost_usd": (!costs.is_empty()).then(|| round(costs.iter().sum::<f64>(), 6)),+ "cost_per_task_usd": (!costs.is_empty()).then(|| round(costs.iter().sum::<f64>() / costs.len() as f64, 6)),+ "interventions_per_task": round(interventions as f64 / n as f64, 4),+ "low_confidence": n < MIN_N,+ });+ if by_model {+ g["model"] = json!(model);+ }+ (class, n, g)+ })+ .collect();+ out.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| b.1.cmp(&a.1)));+ out.into_iter().map(|(_, _, g)| g).collect()+}++#[derive(Deserialize)]+pub struct ReportQuery {+ class: Option<String>,+ bot: Option<String>,+ since: Option<String>,+ by: Option<String>,+}++/// `GET /api/performance`: person-only (`auth.rs`), read-only.+pub async fn report(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<ReportQuery>) -> Response {+ let since = match parse_since(q.since.as_deref(), Utc::now()) {+ Ok(t) => t,+ Err(e) => return bad(e),+ };+ let by_model = match q.by.as_deref().unwrap_or("model") {+ "model" => true,+ "bot" => false,+ _ => return bad("by: use model or bot"),+ };+ let nonblank = |s: &Option<String>| s.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);+ let (class, bot) = (nonblank(&q.class), nonblank(&q.bot));+ let rows = match state.db.observations(space.as_str(), since, class.as_deref(), bot.as_deref()).await {+ Ok(r) => r,+ Err(e) => return internal(e),+ };+ let mut names = HashMap::new();+ for id in rows.iter().map(|o| o.kwant_id.clone()).collect::<std::collections::HashSet<_>>() {+ if let Ok(Some(k)) = state.db.get_kwant(&id).await {+ names.insert(id, k.name);+ }+ }+ Json(json!({+ "since": since,+ "report_only": true,+ "min_n": MIN_N,+ "observations": rows.len(),+ "groups": group(&rows, by_model, &names),+ }))+ .into_response()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn close(a: f64, b: f64) -> bool {+ (a - b).abs() < 5e-4+ }++ #[test]+ fn wilson_matches_known_intervals() {+ assert_eq!(wilson(0, 0), None);+ // Reference values (Wilson score, z = 1.96)+ let (lo, hi) = wilson(9, 12).unwrap();+ assert!(close(lo, 0.4677) && close(hi, 0.9111), "{lo} {hi}");+ let (lo, hi) = wilson(0, 10).unwrap();+ assert!(close(lo, 0.0) && close(hi, 0.2775), "{lo} {hi}");+ let (lo, hi) = wilson(10, 10).unwrap();+ assert!(close(lo, 0.7225) && close(hi, 1.0), "{lo} {hi}");+ let (lo, hi) = wilson(1, 2).unwrap();+ assert!(close(lo, 0.0945) && close(hi, 0.9055), "{lo} {hi}");+ }++ #[test]+ fn median_of_odd_and_even_lists() {+ assert_eq!(median(vec![]), None);+ assert_eq!(median(vec![7]), Some(7.0));+ assert_eq!(median(vec![30, 10, 20]), Some(20.0));+ assert_eq!(median(vec![40, 10, 30, 20]), Some(25.0));+ }++ #[test]+ fn since_takes_days_dates_and_times() {+ let now = DateTime::parse_from_rfc3339("2026-10-29T12:00:00Z").unwrap().with_timezone(&Utc);+ assert_eq!(parse_since(None, now).unwrap(), now - Duration::days(30));+ assert_eq!(parse_since(Some("7d"), now).unwrap(), now - Duration::days(7));+ assert_eq!(parse_since(Some("2026-10-01"), now).unwrap().to_rfc3339(), "2026-10-01T00:00:00+00:00");+ assert_eq!(parse_since(Some("2026-10-02T03:04:05Z"), now).unwrap().to_rfc3339(), "2026-10-02T03:04:05+00:00");+ for bad in ["0d", "366d", "xd", "yesterday", "2026-13-01"] {+ assert!(parse_since(Some(bad), now).is_err(), "{bad}");+ }+ }+}diff --git a/src/server/mod.rs b/src/server/mod.rsindex faa2c105..ca1f5027 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -361,6 +361,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/work-ahead/run", post(work_ahead::run_now)).route("/api/missions", get(missions::routes::list_missions).post(missions::routes::create_mission)).route("/api/missions/insights", get(missions::routes::insights))+ .route("/api/performance", get(missions::performance::report)).route("/api/missions/:id", get(missions::routes::get_mission).patch(missions::routes::patch_mission)).route("/api/missions/:id/approve", post(missions::routes::approve_mission)).route("/api/missions/:id/cancel", post(missions::routes::cancel_mission))diff --git a/tests/performance_test.rs b/tests/performance_test.rsnew file mode 100644index 00000000..5a5e473a--- /dev/null+++ b/tests/performance_test.rs@@ -0,0 +1,313 @@+//! The Performance Market (Phase D1, report-only): a settled task is observed once, a re-settled+//! one replaces its row, the backfill runs once and never duplicates, and GET /api/performance+//! groups with a Wilson interval. Contract: docs/mission-control.md §17.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{models::Kwant, spaces::SpaceId, Database},+ router::LayaRouter,+ server::{+ continuity::{SelfScope, TurnOrigin},+ create_router, mcp_runtime, missions, AppState,+ },+ tools::ToolRunner,+};+use serde_json::{json, Value};+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++struct Env {+ app: Router,+ state: AppState,+ bot: Kwant,+ general: String,+ _tmp: TempDir,+}++async fn setup() -> Env {+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(tmp.path().join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let space = SpaceId::default_space();+ let kwants = state.db.list_kwants(&space).await.unwrap();+ 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()), bot: kwants[0].clone(), general, state, _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+}++fn rpc(method: &str, params: Value) -> Value {+ json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})+}++async fn tool(e: &Env, token: &str, name: &str, args: Value) -> (Value, bool, String) {+ let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc("tools/call", json!({"name": name, "arguments": args})))).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ let text = v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string();+ let parsed = serde_json::from_str(&text).unwrap_or(Value::Null);+ (parsed, v["result"]["isError"].as_bool().unwrap_or(false), text)+}++/// A turn of `bot` in #general with its own tools; returns the turn token.+async fn turn(e: &Env, bot: &Kwant, turn_id: &str) -> String {+ 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.into()),+ ..Default::default()+ };+ mcp_runtime::prepare_turn_with_self(&e.state, bot, Some(turn_id.into()), None, Some(scope)).await.unwrap().1+}++async fn task(e: &Env, id: &str) -> Value {+ person(e, "GET", &format!("/api/tasks/{id}"), None).await+}++fn id(v: &Value) -> String {+ v["id"].as_str().unwrap().to_string()+}++async fn claim(e: &Env, tid: &str) -> String {+ let turn_id = format!("t-{}", uuid::Uuid::new_v4());+ let token = turn(e, &e.bot, &turn_id).await;+ let (v, err, text) = tool(e, &token, "task_claim", json!({"task_id": tid})).await;+ assert!(!err, "claim failed: {text} {v}");+ turn_id+}+++use kwnt::db::performance::NewObservation;+use kwnt::db::usage::NewUsage;+use kwnt::db::missions::TaskChange;+use std::time::Duration;++async fn observed(e: &Env, tid: &str, result: &str) -> kwnt::db::performance::Observation {+ for _ in 0..100 {+ if let Some(o) = e.state.db.observation_of(tid).await.unwrap() {+ if o.result == result {+ return o;+ }+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ panic!("no {result} observation for {tid}: {:?}", e.state.db.observation_of(tid).await.unwrap());+}++async fn to_review(e: &Env, tid: &str) {+ let turn_id = claim(e, tid).await;+ // The model call this run made (cost and model come from the owner's calls inside the claim)+ e.state+ .db+ .record_usage(&NewUsage {+ kwant_id: e.bot.id.clone(),+ context_id: e.general.clone(),+ purpose: kwnt::db::usage::PURPOSE_REPLY,+ model: "claude-opus-5-5".into(),+ fresh_input: 900,+ output: 100,+ reported: true,+ cost_usd: Some(0.25),+ ..Default::default()+ })+ .await+ .unwrap();+ let token = turn(e, &e.bot, &turn_id).await;+ let (v, err, text) = tool(e, &token, "task_update", json!({"task_id": tid, "status": "review"})).await;+ assert!(!err, "{text} {v}");+}++fn ms(x: &kwnt::db::performance::Observation) -> i64 {+ x.latency_ms+}++#[tokio::test]+async fn a_settled_task_is_observed_and_settling_again_replaces_its_row() {+ let e = setup().await;+ let tid = id(&person(&e, "POST", "/api/tasks", Some(json!({"title": "Write it", "owner_kwant_id": e.bot.id}))).await);+ // Not settled yet: nothing observed+ assert!(!e.state.db.record_performance(&tid).await.unwrap());++ // Run 1: the person blocks and unblocks it, then kwant fails it+ claim(&e, &tid).await;+ person(&e, "POST", &format!("/api/tasks/{tid}/block"), Some(json!({"reason": "wait"}))).await;+ person(&e, "POST", &format!("/api/tasks/{tid}/unblock"), None).await;+ claim(&e, &tid).await;+ missions::transition(&e.state, &tid, "working", "failed", missions::Actor::Kwant, "kwant", TaskChange::default()).await.unwrap();+ let o = observed(&e, &tid, "failed").await;+ assert_eq!((o.kwant_id.as_str(), o.task_class.as_str(), o.source.as_str()), (e.bot.id.as_str(), "general", "live"));+ assert_eq!((o.runs, o.unblocks, o.retries, o.interventions), (2, 1, 0, 1), "{o:?}");+ assert!(o.started_at.is_some() && ms(&o) >= 0, "{o:?}");++ // The person retries it; it runs, goes to review and the person verifies it+ person(&e, "POST", &format!("/api/tasks/{tid}/retry"), None).await;+ to_review(&e, &tid).await;+ let t = person(&e, "POST", &format!("/api/tasks/{tid}/verify"), Some(json!({"note": "looks right"}))).await;+ assert_eq!(t["state"], "verified", "{t}");+ let o = observed(&e, &tid, "verified").await;+ assert_eq!((o.runs, o.unblocks, o.retries, o.interventions), (3, 1, 1, 2), "one row, by its last outcome: {o:?}");+ assert_eq!((o.model.as_str(), o.cost_usd), ("claude-opus-5-5", Some(0.25)), "{o:?}");+ assert_eq!(o.fresh_tokens, task(&e, &tid).await["task"]["spent_tokens"].as_i64().unwrap());+ let n: Vec<_> = e.state.db.observations(kwnt::db::spaces::DEFAULT_SPACE_ID, chrono::Utc::now() - chrono::Duration::days(1), None, None).await.unwrap();+ assert_eq!(n.iter().filter(|x| x.task_id == tid).count(), 1);+}++#[tokio::test]+async fn a_cancelled_task_counts_only_if_it_ran() {+ let e = setup().await;+ let never = id(&person(&e, "POST", "/api/tasks", Some(json!({"title": "Never ran", "owner_kwant_id": e.bot.id}))).await);+ person(&e, "POST", &format!("/api/tasks/{never}/cancel"), None).await;+ let ran = id(&person(&e, "POST", "/api/tasks", Some(json!({"title": "Ran", "owner_kwant_id": e.bot.id}))).await);+ claim(&e, &ran).await;+ person(&e, "POST", &format!("/api/tasks/{ran}/cancel"), None).await;+ let o = observed(&e, &ran, "unverified").await;+ assert_eq!(o.runs, 1);+ assert!(e.state.db.observe_task(&never).await.unwrap().is_none());+ assert!(e.state.db.observation_of(&never).await.unwrap().is_none());+}++#[tokio::test]+async fn the_backfill_runs_once_and_never_duplicates_or_overwrites() {+ let e = setup().await;+ let db = &e.state.db;+ let mut ids = vec![];+ for title in ["A", "B", "C"] {+ let tid = id(&person(&e, "POST", "/api/tasks", Some(json!({"title": title, "owner_kwant_id": e.bot.id}))).await);+ claim(&e, &tid).await;+ person(&e, "POST", &format!("/api/tasks/{tid}/cancel"), None).await;+ observed(&e, &tid, "unverified").await;+ ids.push(tid);+ }+ // As if the first two settled before the table existed; the third stays a live row+ db.exec_raw_for_test(&format!("DELETE FROM performance_observations WHERE task_id IN ('{}', '{}')", ids[0], ids[1])).await.unwrap();+ // The fresh database already ran its (empty) backfill at startup+ assert_eq!(db.backfill_performance().await.unwrap(), 0, "marked done");+ db.exec_raw_for_test("DELETE FROM settings WHERE key = 'performance_backfill_v1'").await.unwrap();+ assert_eq!(db.backfill_performance().await.unwrap(), 2);+ assert_eq!(db.backfill_performance().await.unwrap(), 0, "once");+ db.exec_raw_for_test("DELETE FROM settings WHERE key = 'performance_backfill_v1'").await.unwrap();+ assert_eq!(db.backfill_performance().await.unwrap(), 0, "rows that exist are left alone");+ let sources: Vec<String> = sources_of(db, &ids).await;+ assert_eq!(sources, ["backfill", "backfill", "live"]);+}++async fn sources_of(db: &Database, ids: &[String]) -> Vec<String> {+ let mut out = vec![];+ for id in ids {+ out.push(db.observation_of(id).await.unwrap().unwrap().source);+ }+ out+}++/// A settled task `days_ago`; latency, tokens and cost are filled in by the caller.+fn obs(n: usize, class: &str, bot: &str, model: &str, result: &'static str, days_ago: i64) -> NewObservation {+ let finished_at = chrono::Utc::now() - chrono::Duration::days(days_ago) - chrono::Duration::minutes(n as i64);+ NewObservation {+ task_id: format!("{class}-{bot}-{model}-{result}-{n}-{days_ago}"),+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),+ mission_id: None,+ task_class: class.into(),+ kwant_id: bot.into(),+ engine: "cli".into(),+ model: model.into(),+ started_at: None,+ finished_at,+ latency_ms: 0,+ runs: 1,+ fresh_tokens: 0,+ cost_usd: None,+ result,+ approvals: (n % 2) as i64,+ check_approvals: 0,+ unblocks: 0,+ retries: 0,+ autofix_attempts: 0,+ }+}++#[tokio::test]+async fn the_report_groups_with_a_wilson_interval_and_flags_small_groups() {+ let e = setup().await;+ let db = &e.state.db;+ let bot = e.bot.id.clone();+ // Bot on m1: 9 verified, 2 failed, 1 unverified (n = 12); latencies 1..12 s, tokens 100..1200+ for i in 0..12 {+ let result = if i < 9 { "verified" } else if i < 11 { "failed" } else { "unverified" };+ let cost = if i < 6 { Some(0.5) } else { None };+ db.store_observation(&NewObservation { latency_ms: (i as i64 + 1) * 1000, fresh_tokens: (i as i64 + 1) * 100, cost_usd: cost, ..obs(i, "general", &bot, "m1", result, 1) }, "live").await.unwrap();+ }+ // Same bot, other model: 2 rows (low confidence), no cost reported+ for i in 0..2 {+ db.store_observation(&obs(i, "general", &bot, "m2", "verified", 1), "live").await.unwrap();+ }+ // Another class, and one too old for the default window+ db.store_observation(&obs(0, "code", &bot, "m1", "failed", 1), "live").await.unwrap();+ db.store_observation(&obs(0, "general", &bot, "m1", "verified", 60), "live").await.unwrap();++ let r = person(&e, "GET", "/api/performance", None).await;+ assert_eq!((r["report_only"].as_bool(), r["min_n"].as_u64(), r["observations"].as_u64()), (Some(true), Some(5), Some(15)), "{r}");+ let groups = r["groups"].as_array().unwrap();+ assert_eq!(groups.len(), 3, "{r}");+ // Sorted by class, then largest first+ assert_eq!(groups[0]["task_class"], "code");+ let g = &groups[1];+ assert_eq!((g["task_class"].as_str(), g["model"].as_str(), g["n"].as_u64()), (Some("general"), Some("m1"), Some(12)), "{g}");+ assert_eq!((g["verified"].as_u64(), g["failed"].as_u64(), g["unverified"].as_u64()), (Some(9), Some(2), Some(1)));+ assert_eq!(g["verified_rate"], 0.75);+ assert_eq!(g["verified_ci95"], json!([0.4677, 0.9111]), "{g}");+ assert_eq!((g["median_latency_ms"].as_f64(), g["median_fresh_tokens"].as_f64()), (Some(6500.0), Some(650.0)));+ assert_eq!((g["cost_usd"].as_f64(), g["cost_per_task_usd"].as_f64()), (Some(3.0), Some(0.5)), "averaged over rows with a cost");+ assert_eq!(g["interventions_per_task"], 0.5, "{g}");+ assert_eq!((g["low_confidence"].as_bool(), g["kwant_name"].as_str()), (Some(false), Some(e.bot.name.as_str())));+ assert_eq!((groups[2]["model"].as_str(), groups[2]["low_confidence"].as_bool(), groups[2]["cost_usd"].is_null()), (Some("m2"), Some(true), true));++ // by=bot folds the models together; filters narrow; since widens+ let r = person(&e, "GET", "/api/performance?by=bot&class=general", None).await;+ let g = &r["groups"][0];+ assert_eq!((r["groups"].as_array().unwrap().len(), g["n"].as_u64(), g["model"].is_null()), (1, Some(14), true), "{r}");+ let r = person(&e, "GET", "/api/performance?bot=nobody", None).await;+ assert_eq!(r["groups"], json!([]));+ let r = person(&e, "GET", "/api/performance?since=90d&class=general&by=bot", None).await;+ assert_eq!(r["groups"][0]["n"], 15, "{r}");+ for bad in ["since=0d", "since=yesterday", "by=engine"] {+ let (s, v) = call(&e.app, "GET", &format!("/api/performance?{bad}"), None, None).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{bad}: {v}");+ }+ // Bots never see the scoreboard+ let token = turn(&e, &e.bot, "t-perf").await;+ let (s, _) = call(&e.app, "GET", "/api/performance", Some(&token), None).await;+ assert_eq!(s, StatusCode::FORBIDDEN);+}