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.

Insights measures: weekly verified trend and cost per verified outcome

Lin (kwant bot)9f8a8313437b
diff --git a/docs/mission-control.md b/docs/mission-control.md
index dfd97e3d..20ca6427 100644
--- a/docs/mission-control.md
+++ b/docs/mission-control.md
@@ -239,6 +239,28 @@ claim conflict), 403 (bot token on a person route).
`failed`. `interventions_7d` counts person actions on tasks (verify, reject, block, unblock, retry,
cancel, check approval).
+**Measures (Phase C).** The north star and its cost, for the space. Counts only: nothing here
+changes routing, budgets or who gets work.
+
+```
+{"verified_weekly": [{"start": "…", "end": "…", "verified": 0, "active": false}, …], // 8, oldest first
+ "active_weeks": 0, "verified_per_active_week": null,
+ "cost_7d_usd": null, "cost_per_verified_7d_usd": null,
+ "verified_observed_7d": 0, "settled_7d": 0, "unpriced_7d": 0}
+```
+
+- `verified_weekly` is 8 rolling weeks ending now. A task counts once in each week it reached
+ `verified` in, the `verified_7d` rule, so the last entry always equals `verified_7d`. A week is
+ `active` when any task in the space had an event in it. `verified_per_active_week` is the total over
+ the active weeks, one decimal, or null with none: verified tasks per active space per week.
+- Cost comes from the Performance Market observations (§17) of tasks that settled in the last 7 days:
+ the owner's reported model cost inside its claims. `cost_7d_usd` sums every settled task, verified,
+ failed or cancelled-after-running, and `cost_per_verified_7d_usd` divides it by the verified ones
+ (`verified_observed_7d`), so failures are part of what an outcome costs. Both are null when nothing
+ reported a cost; `cost_per_verified_7d_usd` is also null with no verified task. `unpriced_7d` counts
+ settled tasks whose engine reported no cost: when it is above 0 the cost undercounts, and the panel
+ should say so. Costs are rounded to 6 decimals.
+
## 7. Live events (SSE `/api/events`)
```
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index f92b036d..157db270 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -414,6 +414,17 @@ export interface Insights {
/** AutoFix over the last 7 days (older servers leave these out). */
autofix_7d?: { attempts: number; succeeded: number; tokens: number };
failures_by_class_7d?: Partial<Record<FailureClass, number>>;
+ /** Measures (older servers leave these out): 8 rolling weeks, oldest first; the last is `verified_7d`. */
+ verified_weekly?: Array<{ start: string; end: string; verified: number; active: boolean }>;
+ active_weeks?: number;
+ verified_per_active_week?: number | null;
+ /** Reported model cost of tasks settled in the last 7 days; null when none reported one. */
+ cost_7d_usd?: number | null;
+ cost_per_verified_7d_usd?: number | null;
+ verified_observed_7d?: number;
+ settled_7d?: number;
+ /** Settled tasks with no reported cost: above 0, the cost undercounts. */
+ unpriced_7d?: number;
}
// ---------------------------------------------------------------------------
diff --git a/src/server/missions/routes.rs b/src/server/missions/routes.rs
index 790d2307..236a80a4 100644
--- a/src/server/missions/routes.rs
+++ b/src/server/missions/routes.rs
@@ -334,6 +334,16 @@ pub async fn insights(State(state): State<AppState>, Scope(space): Scope) -> Res
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,
@@ -345,10 +355,81 @@ pub async fn insights(State(state): State<AppState>, Scope(space): Scope) -> Res
"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,
+ "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 ones: what one verified outcome cost, failures included.
+ pub per_verified: Value,
+ pub verified: 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 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 priced.is_empty() || verified == 0 { Value::Null } else { round(sum / verified as f64) },
+ verified,
+ 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`.
@@ -882,4 +963,64 @@ mod tests {
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(),
+ };
+ 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.settled, c.unpriced), (json!(0.6), json!(0.2), 3, 4, 1));
+ 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));
+ }
}
diff --git a/tests/performance_test.rs b/tests/performance_test.rs
index 5a5e473a..3f3ac049 100644
--- a/tests/performance_test.rs
+++ b/tests/performance_test.rs
@@ -311,3 +311,40 @@ async fn the_report_groups_with_a_wilson_interval_and_flags_small_groups() {
let (s, _) = call(&e.app, "GET", "/api/performance", Some(&token), None).await;
assert_eq!(s, StatusCode::FORBIDDEN);
}
+
+/// Insights measures (Phase C): weekly verified tasks with the active weeks, and cost per verified
+/// outcome from the settled tasks' observations. Counts only.
+#[tokio::test]
+async fn insights_counts_verified_tasks_per_week_and_cost_per_verified_outcome() {
+ let e = setup().await;
+ let db = &e.state.db;
+ let empty = person(&e, "GET", "/api/missions/insights", None).await;
+ assert_eq!(empty["verified_weekly"].as_array().map(Vec::len), Some(8), "{empty}");
+ assert_eq!((empty["active_weeks"].as_u64(), &empty["verified_per_active_week"]), (Some(0), &Value::Null), "{empty}");
+ assert_eq!((&empty["cost_7d_usd"], &empty["cost_per_verified_7d_usd"], empty["settled_7d"].as_u64()), (&Value::Null, &Value::Null, Some(0)));
+
+ // Two tasks verified this week through the real flow (each run reports $0.25)
+ for title in ["One", "Two"] {
+ let tid = id(&person(&e, "POST", "/api/tasks", Some(json!({"title": title, "owner_kwant_id": e.bot.id}))).await);
+ to_review(&e, &tid).await;
+ person(&e, "POST", &format!("/api/tasks/{tid}/verify"), Some(json!({"note": "ok"}))).await;
+ observed(&e, &tid, "verified").await;
+ }
+ // This week also settled a failed task that cost $0.15 and one whose calls reported no cost;
+ // an observation from 10 days ago is outside the window
+ db.store_observation(&NewObservation { cost_usd: Some(0.15), ..obs(1, "general", &e.bot.id, "m1", "failed", 1) }, "live").await.unwrap();
+ db.store_observation(&obs(2, "general", &e.bot.id, "m1", "unverified", 2), "live").await.unwrap();
+ db.store_observation(&NewObservation { cost_usd: Some(9.0), ..obs(3, "general", &e.bot.id, "m1", "verified", 10) }, "live").await.unwrap();
+
+ let v = person(&e, "GET", "/api/missions/insights", None).await;
+ let weeks: Vec<(u64, bool)> = v["verified_weekly"].as_array().unwrap().iter().map(|w| (w["verified"].as_u64().unwrap(), w["active"].as_bool().unwrap())).collect();
+ assert_eq!(weeks[..7], [(0, false); 7], "{v}");
+ assert_eq!(weeks[7], (2, true), "{v}");
+ assert_eq!(v["verified_weekly"][7]["verified"], v["verified_7d"], "the last week is the verified_7d window");
+ assert_eq!((v["active_weeks"].as_u64(), v["verified_per_active_week"].as_f64()), (Some(1), Some(2.0)), "{v}");
+ // $0.25 + $0.25 verified + $0.15 failed, over the two verified outcomes
+ assert_eq!((v["cost_7d_usd"].as_f64(), v["cost_per_verified_7d_usd"].as_f64()), (Some(0.65), Some(0.325)), "{v}");
+ assert_eq!((v["verified_observed_7d"].as_u64(), v["settled_7d"].as_u64(), v["unpriced_7d"].as_u64()), (Some(2), Some(4), Some(1)), "{v}");
+ // The old fields are unchanged
+ assert_eq!(v["verified_7d"], 2);
+}