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
Flight School C4: scorecards, tier proposals, grant and decline
Lin (kwant bot)edcc1185dd43
diff --git a/docs/mission-control.md b/docs/mission-control.mdindex de27e2f9..d6d0bbfd 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -584,7 +584,8 @@ the turn ended, and the next tick put the task back in `working` with no turn ru### Routes- `GET /api/capabilities?kwant_id=&space=` (open): `{flight_school, kwant_id, default_tier, policies,- effective: [{task_class, tier, from: class|any_class|default|unreadable}], events}`.+ effective: [{task_class, tier, from: class|any_class|default|unreadable}], proposals, events}` (`proposals`:+ the bot's last 20, newest first, C4).- `POST /api/capabilities` `{kwant_id, task_class, tier, note?}` (person only): sets the tier; the same tieragain returns `unchanged: true`.- `POST /api/capabilities/:kwant_id/revoke` `{task_class, to_tier: observe|sandbox, note?}` (person only):@@ -592,6 +593,63 @@ the turn ended, and the next tick put the task back in `working` with no turn ru- Bot tool `tier_status {task_class?}` (read-only, offered with the task board).- `task_json` gains `task_class` and `owner_tier` (`null` while Flight School is off).+### Scorecards and proposals (Phase C4)++A bot earns a tier from verified work, and only the person gives it. kwant computes the scorecard every+time from rows it wrote itself; it is never stored as truth, and a bot can't edit any of its inputs.++**The scorecard** of a bot for a class covers its settled tasks of that class (`verified`, `failed`,+`cancelled`) that it ran (at least one claim) and that finished in the last 30 days, newest first:++| field | from |+|---|---|+| `tasks {settled, verified, failed, cancelled}` | `tasks.state`, `finished_at` |+| `first_try {k, n, rate}`: verified on attempt ≤ 1 with no failure row | `tasks.attempts`, `task_failures` |+| `false_success {k, n, rate}`: verified, then flagged `evidence_changed` and not resolved `still_valid` | `task_flags` |+| `failures {total, by_class {denied, check_failed}}` | `task_failures` |+| `cards {shown, approved, denied, approved_rate}`, `calls`, `external_calls` | `turn_tool_calls` |+| `interventions`: the person's state moves (except accepting a verify), edits, forks, checks added, flags resolved | `task_events` actor `person` |+| `tokens {spent, recovery}` | `tasks.spent_tokens`, `recovery_spent_tokens` |+| `recent_denials {n, of, with_denial}`: tasks with a denied call or a `denied` failure among the last 5/10 | the above |++Every rate comes with its `k` and `n`; with `n = 0` the rate is `null`. The card also carries `tier`,+`tier_from`, `next_tier` (`null` at `act`), `eligible` and `missing` (one plain sentence per unmet rule).++**Eligibility** (§9 D5): `observe → sandbox` needs ≥ 5 verified and no denial in the last 5 tasks;+`sandbox → act` needs ≥ 10 verified, first try ≥ 70 %, no false success and no denial in the last 10.++**`tier_propose {task_class, reason}`** (bot tool, offered with the task board, free at every tier) asks for+the next tier up. kwant refuses it while Flight School is off, at `act`, within 7 days of the person+declining the same step, and when the card doesn't qualify (the reply lists what is missing). Otherwise it+saves a `tier_proposals` row with the card it qualified with, sends the notification `tier_proposed`+(on by default, also for notification lists saved before it existed) and `capability_changed`. One open+proposal per bot and class (a unique index); asking again reports the open one.++**Deciding** is the person's (`/api/capabilities` writes are person-only; a bot token gets 403). A grant first+checks again that the bot is still at `from_tier` and still qualifies; if not, the proposal goes `stale` with+the reason in `note` and the grant answers 409. Otherwise one transaction moves the proposal from `proposed`+to `granted` (claim-first, so of racing grants exactly one does anything; the rest get 409 with the status+it has now), revokes the live class row and writes the new tier with an event. A decline writes no tier.+Open proposals are also checked for staleness whenever they are read (`GET /api/capabilities`, the+proposals list, `tier_status`, `tier_propose`); while Flight School is off they are left alone. Revoke+stays instant and needs no proposal, and no tier lifts the payment floor or a high-risk card.++`tier_proposals` (C4): `id, space_id, kwant_id, task_class, from_tier observe|sandbox, to_tier sandbox|act,+scorecard (JSON), reason (the bot's words), status proposed|granted|declined|stale, decided_at, note,+created_at`. Triggers: a row is never deleted, and only its status (out of `proposed`), `decided_at` and+`note` change, once. `FLIGHT_SCHOOL_DOWN` drops it.++Routes (C4):+- `GET /api/capabilities/:kwant_id/scorecard?class=` (open; class defaults to `general`): the card above.+- `GET /api/capabilities/proposals?status=&kwant_id=` (open): `{proposals: [...]}`, newest first; each has+ `kind: "tier_proposal"` (its Needs-you kind) and `scorecard` as JSON.+- `POST /api/capabilities/proposals/:id/grant` (person only, `Idempotency-Key` optional):+ `{proposal, capabilities}`; 409 `{error, status}` when it isn't open or went stale; 404 when unknown.+- `POST /api/capabilities/proposals/:id/decline {note?}` (person only, `Idempotency-Key` optional): same+ shape.+- SSE `{"type": "capability_changed", "data": {"capability": {space_id, kwant_id, task_class, proposal}}}`: reload the bot's+ capabilities.+## 15. Opt-in budgetsToken budgets are opt-in. `budget_tokens` 0 means no limit, for tasks and missions.diff --git a/frontend/src/continuity.ts b/frontend/src/continuity.tsindex 6860f54a..06749d5b 100644--- a/frontend/src/continuity.ts+++ b/frontend/src/continuity.ts@@ -118,7 +118,8 @@ export type NotifyKind =| 'human_step'| 'app_update'| 'work_ahead'- | 'automation_suggested';+ | 'automation_suggested'+ | 'tier_proposed';export const NOTIFY_KINDS: Array<{ id: NotifyKind; label: string }> = [{ id: 'turn_finished', label: 'A bot finished replying' },{ id: 'approval_needed', label: 'A bot needs your approval' },diff --git a/src/db/flight_school.rs b/src/db/flight_school.rsindex 9ff8fba4..65fcc5c8 100644--- a/src/db/flight_school.rs+++ b/src/db/flight_school.rs@@ -18,7 +18,11 @@ pub const ANY_CLASS: &str = "*";/// Undoes [`Database::migrate_flight_school`]: the tables go and `tasks` gets back the shape older/// releases read. Kept for rollbacks and tested.-pub const FLIGHT_SCHOOL_DOWN: &str = "DROP TRIGGER IF EXISTS kwants_flight_school_default; \+pub const FLIGHT_SCHOOL_DOWN: &str = "DROP TRIGGER IF EXISTS tier_proposals_no_delete; \+ DROP TRIGGER IF EXISTS tier_proposals_only_decide; \+ DROP INDEX IF EXISTS tier_proposals_one_open; \+ DROP TABLE IF EXISTS tier_proposals; \+ DROP TRIGGER IF EXISTS kwants_flight_school_default; \DROP TRIGGER IF EXISTS capability_policies_no_delete; \DROP TRIGGER IF EXISTS capability_policies_only_revoke; \DROP TRIGGER IF EXISTS capability_events_no_update; \@@ -52,6 +56,57 @@ pub struct CapabilityEvent {pub created_at: String,}+/// A bot's request to move up one tier for a class (C4). Only the person grants or declines it;+/// kwant marks it `stale` when the bot's tier or scorecard no longer matches what it asked from.+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct TierProposal {+ pub id: String,+ pub space_id: String,+ pub kwant_id: String,+ pub task_class: String,+ pub from_tier: String,+ pub to_tier: String,+ /// The scorecard kwant computed when the bot asked (JSON), never the bot's own text.+ pub scorecard: String,+ /// The bot's reason, shown as the bot's words.+ pub reason: Option<String>,+ pub status: String,+ pub decided_at: Option<String>,+ /// Why kwant marked it stale, or the person's note on a decline.+ pub note: Option<String>,+ pub created_at: String,+}++/// One settled task of a bot in a class, with what the scorecard counts about it.+#[derive(Debug, Clone, FromRow, PartialEq)]+pub struct ScoreTask {+ pub id: String,+ pub state: String,+ pub attempts: i64,+ pub finished_at: chrono::DateTime<Utc>,+ pub failures: i64,+ pub denied_failures: i64,+ pub check_failures: i64,+ pub calls: i64,+ pub external_calls: i64,+ pub cards: i64,+ pub approved: i64,+ pub denied: i64,+ pub false_success: i64,+ pub interventions: i64,+ pub spent_tokens: i64,+ pub recovery_tokens: i64,+}++/// What a grant or decline found.+#[derive(Debug, Clone, PartialEq)]+pub enum Decided {+ Done(Box<TierProposal>),+ /// It wasn't `proposed` any more: its status now.+ NotOpen(String),+ Missing,+}+/// `observe` < `sandbox` < `act`; an unknown tier is the lowest.pub fn rank(tier: &str) -> usize {TIERS.iter().position(|t| *t == tier).unwrap_or(0)@@ -62,7 +117,17 @@ pub fn valid_class(class: &str) -> bool {(1..=40).contains(&class.len()) && class.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')}-const TRIGGERS: [&str; 5] = [+const TRIGGERS: [&str; 7] = [+ // A proposal is decided once: only `proposed` moves, to a final status, and only its status,+ // decision time and note change+ "CREATE TRIGGER IF NOT EXISTS tier_proposals_only_decide BEFORE UPDATE ON tier_proposals \+ WHEN OLD.status != 'proposed' OR NEW.status = 'proposed' OR NEW.id IS NOT OLD.id OR NEW.kwant_id IS NOT OLD.kwant_id \+ OR NEW.space_id IS NOT OLD.space_id OR NEW.task_class IS NOT OLD.task_class OR NEW.from_tier IS NOT OLD.from_tier \+ OR NEW.to_tier IS NOT OLD.to_tier OR NEW.scorecard IS NOT OLD.scorecard OR NEW.reason IS NOT OLD.reason \+ OR NEW.created_at IS NOT OLD.created_at OR NEW.decided_at IS NULL \+ BEGIN SELECT RAISE(ABORT, 'a tier proposal is decided once'); END",+ "CREATE TRIGGER IF NOT EXISTS tier_proposals_no_delete BEFORE DELETE ON tier_proposals \+ BEGIN SELECT RAISE(ABORT, 'tier proposals are kept'); END",// A tier row is never deleted or rewritten: revoking sets `revoked_at` once, and a new row// carries the new tier"CREATE TRIGGER IF NOT EXISTS capability_policies_no_delete BEFORE DELETE ON capability_policies \@@ -122,6 +187,22 @@ impl Database {created_at TEXT NOT NULL)","CREATE INDEX IF NOT EXISTS capability_events_kwant ON capability_events (kwant_id, id)",+ "CREATE TABLE IF NOT EXISTS tier_proposals (+ id TEXT PRIMARY KEY,+ space_id TEXT NOT NULL,+ kwant_id TEXT NOT NULL,+ task_class TEXT NOT NULL,+ from_tier TEXT NOT NULL CHECK (from_tier IN ('observe', 'sandbox')),+ to_tier TEXT NOT NULL CHECK (to_tier IN ('sandbox', 'act')),+ scorecard TEXT NOT NULL,+ reason TEXT,+ status TEXT NOT NULL CHECK (status IN ('proposed', 'granted', 'declined', 'stale')),+ decided_at TEXT,+ note TEXT,+ created_at TEXT NOT NULL+ )",+ "CREATE UNIQUE INDEX IF NOT EXISTS tier_proposals_one_open ON tier_proposals (kwant_id, task_class) WHERE status = 'proposed'",+ "CREATE INDEX IF NOT EXISTS tier_proposals_space ON tier_proposals (space_id, status, created_at)",] {sqlx::query(stmt).execute(&self.pool).await?;}@@ -230,6 +311,199 @@ impl Database {Ok(policy)}+ /// A bot's settled tasks of `class` that ran (had a claim), finished since `since`, newest first,+ /// with everything the scorecard counts. Every number comes from rows kwant wrote itself: the+ /// task, its failures, its tool-call ledger, its flags and the person's moves on it.+ pub async fn score_tasks(&self, kwant_id: &str, class: &str, since: chrono::DateTime<Utc>) -> Result<Vec<ScoreTask>, DbError> {+ Ok(sqlx::query_as::<_, ScoreTask>(+ "SELECT t.id, t.state, t.attempts, t.finished_at, \+ (SELECT COUNT(*) FROM task_failures f WHERE f.task_id = t.id) AS failures, \+ (SELECT COUNT(*) FROM task_failures f WHERE f.task_id = t.id AND f.class = 'denied') AS denied_failures, \+ (SELECT COUNT(*) FROM task_failures f WHERE f.task_id = t.id AND f.class = 'check_failed') AS check_failures, \+ (SELECT COUNT(*) FROM turn_tool_calls c WHERE c.task_id = t.id) AS calls, \+ (SELECT COUNT(*) FROM turn_tool_calls c WHERE c.task_id = t.id AND c.effect = 'external') AS external_calls, \+ (SELECT COUNT(*) FROM turn_tool_calls c WHERE c.task_id = t.id AND c.approval_id IS NOT NULL) AS cards, \+ (SELECT COUNT(*) FROM turn_tool_calls c WHERE c.task_id = t.id AND c.decision = 'approved') AS approved, \+ (SELECT COUNT(*) FROM turn_tool_calls c WHERE c.task_id = t.id AND c.decision = 'denied') AS denied, \+ (t.state = 'verified' AND EXISTS (SELECT 1 FROM task_flags g WHERE g.task_id = t.id AND g.cause = 'evidence_changed' \+ AND (g.resolution IS NULL OR g.resolution != 'still_valid'))) AS false_success, \+ (SELECT COUNT(*) FROM task_events e WHERE e.task_id = t.id AND e.actor = 'person' \+ AND e.kind IN ('state', 'edited', 'forked', 'check_added', 'flag_resolved') AND (e.to_state IS NULL OR e.to_state != 'verified')) AS interventions, \+ t.spent_tokens, t.recovery_spent_tokens AS recovery_tokens \+ FROM tasks t \+ WHERE t.owner_kwant_id = ? AND t.task_class = ? AND t.state IN ('verified', 'failed', 'cancelled') \+ AND t.finished_at IS NOT NULL AND t.finished_at >= ? \+ AND EXISTS (SELECT 1 FROM agent_claims a WHERE a.task_id = t.id) \+ ORDER BY t.finished_at DESC, t.id",+ )+ .bind(kwant_id)+ .bind(class)+ .bind(since)+ .fetch_all(&self.pool)+ .await?)+ }++ pub async fn tier_proposal(&self, id: &str) -> Result<Option<TierProposal>, DbError> {+ Ok(sqlx::query_as::<_, TierProposal>("SELECT * FROM tier_proposals WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)+ }++ /// Proposals in a space (optionally one bot's, optionally one status), newest first.+ pub async fn tier_proposals(&self, space_id: &str, kwant_id: Option<&str>, status: Option<&str>, limit: i64) -> Result<Vec<TierProposal>, DbError> {+ Ok(sqlx::query_as::<_, TierProposal>(+ "SELECT * FROM tier_proposals WHERE space_id = ? AND (?2 IS NULL OR kwant_id = ?2) AND (?3 IS NULL OR status = ?3) \+ ORDER BY created_at DESC, id LIMIT ?4",+ )+ .bind(space_id)+ .bind(kwant_id)+ .bind(status)+ .bind(limit)+ .fetch_all(&self.pool)+ .await?)+ }++ /// A bot's proposals, newest first.+ pub async fn tier_proposals_of(&self, kwant_id: &str, limit: i64) -> Result<Vec<TierProposal>, DbError> {+ Ok(sqlx::query_as::<_, TierProposal>("SELECT * FROM tier_proposals WHERE kwant_id = ? ORDER BY created_at DESC, id LIMIT ?")+ .bind(kwant_id)+ .bind(limit)+ .fetch_all(&self.pool)+ .await?)+ }++ /// The bot's open proposal for `class`, if any.+ pub async fn open_tier_proposal(&self, kwant_id: &str, class: &str) -> Result<Option<TierProposal>, DbError> {+ Ok(sqlx::query_as::<_, TierProposal>("SELECT * FROM tier_proposals WHERE kwant_id = ? AND task_class = ? AND status = 'proposed'")+ .bind(kwant_id)+ .bind(class)+ .fetch_optional(&self.pool)+ .await?)+ }++ /// When the person last declined the bot moving to `to_tier` on `class`.+ pub async fn last_declined(&self, kwant_id: &str, class: &str, to_tier: &str) -> Result<Option<String>, DbError> {+ let row: Option<(String,)> = sqlx::query_as(+ "SELECT decided_at FROM tier_proposals WHERE kwant_id = ? AND task_class = ? AND to_tier = ? AND status = 'declined' ORDER BY decided_at DESC LIMIT 1",+ )+ .bind(kwant_id)+ .bind(class)+ .bind(to_tier)+ .fetch_optional(&self.pool)+ .await?;+ Ok(row.map(|r| r.0))+ }++ /// Saves a bot's proposal. `Ok(Err(open))` when the bot already has one open for the class+ /// (one per bot and class, by the unique index; a race lands here too).+ #[allow(clippy::too_many_arguments)]+ pub async fn create_tier_proposal(+ &self,+ space_id: &str,+ kwant_id: &str,+ class: &str,+ from_tier: &str,+ to_tier: &str,+ scorecard: &serde_json::Value,+ reason: Option<&str>,+ ) -> Result<Result<TierProposal, TierProposal>, DbError> {+ let now = Utc::now().to_rfc3339();+ let mut tx = self.pool.begin().await?;+ let r = sqlx::query_as::<_, TierProposal>(+ "INSERT INTO tier_proposals (id, space_id, kwant_id, task_class, from_tier, to_tier, scorecard, reason, status, created_at) \+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'proposed', ?) ON CONFLICT DO NOTHING RETURNING *",+ )+ .bind(Uuid::new_v4().to_string())+ .bind(space_id)+ .bind(kwant_id)+ .bind(class)+ .bind(from_tier)+ .bind(to_tier)+ .bind(scorecard.to_string())+ .bind(reason)+ .bind(&now)+ .fetch_optional(&mut *tx)+ .await?;+ match r {+ Some(p) => {+ sqlx::query("INSERT INTO capability_events (kwant_id, task_class, kind, tier, actor, detail, created_at) VALUES (?, ?, 'proposed', ?, ?, ?, ?)")+ .bind(kwant_id)+ .bind(class)+ .bind(to_tier)+ .bind(kwant_id)+ .bind(&p.id)+ .bind(&now)+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;+ Ok(Ok(p))+ }+ None => {+ drop(tx);+ match self.open_tier_proposal(kwant_id, class).await? {+ Some(open) => Ok(Err(open)),+ None => Err(DbError::Sqlx(sqlx::Error::RowNotFound)),+ }+ }+ }+ }++ /// Decides an open proposal: `granted` (writes the bot's tier for the class, revoking the+ /// live class row, in the same transaction), `declined` or `stale`. Claim-first: the status+ /// moves only from `proposed`, so of racing clicks exactly one changes anything.+ pub async fn decide_tier_proposal(&self, id: &str, status: &str, actor: &str, note: Option<&str>) -> Result<Decided, DbError> {+ let now = Utc::now().to_rfc3339();+ let mut tx = self.pool.begin().await?;+ let claimed = sqlx::query_as::<_, TierProposal>(+ "UPDATE tier_proposals SET status = ?, decided_at = ?, note = ? WHERE id = ? AND status = 'proposed' RETURNING *",+ )+ .bind(status)+ .bind(&now)+ .bind(note)+ .bind(id)+ .fetch_optional(&mut *tx)+ .await?;+ let Some(p) = claimed else {+ drop(tx);+ return Ok(match self.tier_proposal(id).await? {+ Some(p) => Decided::NotOpen(p.status),+ None => Decided::Missing,+ });+ };+ if status == "granted" {+ sqlx::query("UPDATE capability_policies SET revoked_at = ? WHERE kwant_id = ? AND task_class = ? AND revoked_at IS NULL")+ .bind(&now)+ .bind(&p.kwant_id)+ .bind(&p.task_class)+ .execute(&mut *tx)+ .await?;+ sqlx::query("INSERT INTO capability_policies (id, kwant_id, task_class, tier, granted_by, granted_at, note) VALUES (?, ?, ?, ?, 'person', ?, ?)")+ .bind(Uuid::new_v4().to_string())+ .bind(&p.kwant_id)+ .bind(&p.task_class)+ .bind(&p.to_tier)+ .bind(&now)+ .bind(format!("granted proposal {}", p.id))+ .execute(&mut *tx)+ .await?;+ }+ let kind = match status {+ "granted" => "granted",+ "declined" => "proposal_declined",+ _ => "proposal_stale",+ };+ sqlx::query("INSERT INTO capability_events (kwant_id, task_class, kind, tier, actor, detail, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)")+ .bind(&p.kwant_id)+ .bind(&p.task_class)+ .bind(kind)+ .bind(&p.to_tier)+ .bind(actor)+ .bind(serde_json::json!({"proposal": p.id, "note": note}).to_string())+ .bind(&now)+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;+ Ok(Decided::Done(Box::new(p)))+ }+/// Whether the task's open claim (the run going on now) has a usable `before_run` checkpoint:/// what lets a sandboxed bot write in its task folder.pub async fn run_has_checkpoint(&self, task_id: &str) -> Result<bool, DbError> {@@ -327,10 +601,43 @@ mod tests {sqlx::raw_sql(FLIGHT_SCHOOL_DOWN).execute(&db.pool).await.unwrap();let col: Option<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info('tasks') WHERE name = 'task_class'").fetch_optional(&db.pool).await.unwrap();assert!(col.is_none());- let t: Option<(String,)> = sqlx::query_as("SELECT name FROM sqlite_master WHERE name = 'capability_policies'").fetch_optional(&db.pool).await.unwrap();- assert!(t.is_none());+ let left: Vec<(String,)> = sqlx::query_as(+ "SELECT name FROM sqlite_master WHERE name LIKE 'capability%' OR name LIKE 'tier_proposals%' OR name = 'kwants_flight_school_default'",+ )+ .fetch_all(&db.pool)+ .await+ .unwrap();+ assert!(left.is_empty(), "{left:?}");db.migrate_flight_school().await.unwrap();db.migrate_flight_school().await.unwrap();assert_eq!(db.task_class("missing").await.unwrap(), "general");}++ #[tokio::test]+ async fn a_proposal_is_decided_once_and_kept() {+ let (_tmp, db) = db().await;+ let card = serde_json::json!({"tasks": {"verified": 5}});+ let p = db.create_tier_proposal("spc_default", "k1", "research", "observe", "sandbox", &card, Some("why")).await.unwrap().unwrap();+ // One open per bot and class+ let again = db.create_tier_proposal("spc_default", "k1", "research", "observe", "sandbox", &card, None).await.unwrap();+ assert_eq!(again.unwrap_err().id, p.id);+ assert!(matches!(db.decide_tier_proposal(&p.id, "declined", "person", None).await.unwrap(), Decided::Done(_)));+ assert_eq!(db.decide_tier_proposal(&p.id, "granted", "person", None).await.unwrap(), Decided::NotOpen("declined".into()));+ assert_eq!(db.decide_tier_proposal("nope", "granted", "person", None).await.unwrap(), Decided::Missing);+ assert!(db.policies_of("k1").await.unwrap().is_empty(), "a decline writes no policy");+ for bad in [+ "UPDATE tier_proposals SET status = 'granted'",+ "UPDATE tier_proposals SET scorecard = '{}'",+ "DELETE FROM tier_proposals",+ ] {+ assert!(sqlx::query(bad).execute(&db.pool).await.is_err(), "{bad}");+ }+ // A grant revokes the live class row and writes the new tier in the same transaction+ db.set_policy("k1", "ops", "observe", "granted", None).await.unwrap();+ let q = db.create_tier_proposal("spc_default", "k1", "ops", "observe", "sandbox", &card, None).await.unwrap().unwrap();+ assert!(matches!(db.decide_tier_proposal(&q.id, "granted", "person", None).await.unwrap(), Decided::Done(_)));+ let live: Vec<_> = db.policies_of("k1").await.unwrap().into_iter().filter(|x| x.task_class == "ops").collect();+ assert_eq!(live.len(), 1);+ assert_eq!(live[0].tier, "sandbox");+ }}diff --git a/src/drivers/events.rs b/src/drivers/events.rsindex ca2188b6..7e5174c2 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -117,6 +117,11 @@ pub enum RuntimeEvent {/// whole proposal with its `card`. See `crate::db::hires` and docs/bot-actions.md → "Hiring".#[serde(rename = "hire_updated", alias = "HireUpdated")]HireUpdated { hire: Value },+ /// Flight School (C4): a bot proposed a tier, or the person granted, declined or kwant marked+ /// a proposal stale. `capability` is `{space_id, kwant_id, task_class, proposal?}`; clients+ /// reload `GET /api/capabilities`. See docs/mission-control.md §14.+ #[serde(rename = "capability_changed", alias = "CapabilityChanged")]+ CapabilityChanged { capability: Value },/// An event from inside one turn, tagged with the turn and its chat. On the SSE wire it is/// the inner event with `turn_id`, `kwant_id`, `context_id` and `thread_id` added at the top/// level (see [`RuntimeEvent::to_wire`]), so clients that ignore the tags still work.diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 3299edf7..10f7dc96 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -34,7 +34,7 @@ const AGENT_SEARCH_LIMIT: i64 = 20;/// Longest notification body.pub const NOTIFY_BODY_CHARS: usize = 200;const WEBHOOK_TIMEOUT: Duration = Duration::from_secs(5);-pub const NOTIFY_KINDS: [&str; 12] = [+pub const NOTIFY_KINDS: [&str; 13] = ["turn_finished","approval_needed","routine_failed",@@ -47,6 +47,7 @@ pub const NOTIFY_KINDS: [&str; 12] = ["app_update","work_ahead","automation_suggested",+ "tier_proposed",];const MASK: &str = "••••••••";@@ -481,6 +482,7 @@ fn tool_list(scope: &SelfScope, board: bool) -> Value {if board {list.extend(super::missions::tools::tools());list.push(super::missions::flight_school::tool());+ list.push(super::missions::flight_school::propose_tool());}list.extend(super::skills::tools());list.extend(super::mcp_suggest::tools());@@ -1075,6 +1077,7 @@ async fn call_tool(n if super::hires::handles(n) => super::hires::call(state, scope, n, args).await,n if super::missions::tools::handles(n) => super::missions::tools::call(state, scope, n, args).await,"tier_status" => super::missions::flight_school::call_tool(state, &scope.kwant_id, args).await,+ "tier_propose" => super::missions::flight_school::call_propose(state, scope, args).await,"list_attachments" if scope.origin.is_some() => super::attachments::tool_list(state, scope).await,"share_file" if scope.origin.is_some() => super::attachments::tool_share(state, scope, args).await,"delegate" => super::delegation::tool_delegate(state, scope, args).await,@@ -1415,7 +1418,7 @@ pub async fn notify_settings_view(state: &AppState) -> (String, Vec<String>) {pub const NOTIFY_KNOWN_SETTING: &str = "notify_known";/// Kinds added after `notify_on` lists were first saved but before `notify_known` existed: a list/// saved without `notify_known` was chosen from every kind but these.-const KINDS_SINCE_FIRST_LIST: [&str; 3] = ["app_update", "work_ahead", "automation_suggested"];+const KINDS_SINCE_FIRST_LIST: [&str; 4] = ["app_update", "work_ahead", "automation_suggested", "tier_proposed"];/// Kinds the user wants to hear about; all of them unless set. A kind added after the list was/// saved is on, so a new event isn't silently off for everyone who ever saved the settings.diff --git a/src/server/missions/flight_school.rs b/src/server/missions/flight_school.rsindex a19e47b5..5491ad39 100644--- a/src/server/missions/flight_school.rs+++ b/src/server/missions/flight_school.rs@@ -7,7 +7,7 @@use super::routes::{bad, conflict, internal, not_found};use super::{bot_in_space, task_folder_in, transition, Actor};-use crate::db::flight_school::{rank, valid_class, ANY_CLASS, DEFAULT_CLASS, TIERS};+use crate::db::flight_school::{rank, valid_class, Decided, ScoreTask, TierProposal, ANY_CLASS, DEFAULT_CLASS, TIERS};use crate::db::missions::{Task, TaskChange};use crate::db::Database;use crate::mcp::ToolApprovalRequest;@@ -15,6 +15,7 @@ use crate::server::spaces::Scope;use crate::server::AppState;use axum::{extract::{Path, Query, State},+ http::{HeaderMap, StatusCode},response::{IntoResponse, Response},Json,};@@ -60,7 +61,7 @@ fn self_tool_is_free(tool: &str) -> bool {tool.starts_with("memory_")|| tool.starts_with("fact_")|| tool.starts_with("task_")- || matches!(tool, "mission_plan" | "tier_status" | "ask_user")+ || matches!(tool, "mission_plan" | "tier_status" | "tier_propose" | "ask_user")|| crate::server::continuity::READ_ONLY_SELF_TOOLS.contains(&tool)}@@ -212,6 +213,7 @@ pub async fn status_json(state: &AppState, kwant_id: &str) -> Value {"default_tier": any.unwrap_or_else(|| "act".into()),"policies": policies,"effective": effective,+ "proposals": state.db.tier_proposals_of(kwant_id, 20).await.unwrap_or_default().iter().map(proposal_json).collect::<Vec<_>>(),"events": state.db.capability_events(kwant_id, 50).await.unwrap_or_default(),})}@@ -226,6 +228,7 @@ pub struct CapQuery {/// `GET /api/capabilities?kwant_id=`.pub async fn get_capabilities(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<CapQuery>) -> Response {let Some(bot) = bot_in_space(&state, &space, &q.kwant_id).await else { return not_found("bot") };+ refresh_stale(&state, &bot.id, None).await;Json(status_json(&state, &bot.id).await).into_response()}@@ -314,6 +317,7 @@ pub fn tool() -> Value {}pub async fn call_tool(state: &AppState, kwant_id: &str, args: &Value) -> (String, bool) {+ refresh_stale(state, kwant_id, None).await;let mut v = status_json(state, kwant_id).await;if let Some(class) = args["task_class"].as_str().map(str::trim).filter(|c| !c.is_empty()) {if !valid_class(class) {@@ -328,6 +332,414 @@ pub async fn call_tool(state: &AppState, kwant_id: &str, args: &Value) -> (Strin(serde_json::to_string_pretty(&v).unwrap_or_default(), false)}+// C4: scorecards and proposals. A scorecard is computed from rows kwant wrote itself, never+// stored as truth; a proposal snapshots the one the bot was eligible with. Contract §3.4.++/// Days a scorecard looks back.+pub const WINDOW_DAYS: i64 = 30;+/// Days after the person declines a bot's step up before it may ask for the same step again.+pub const DECLINE_COOLDOWN_DAYS: i64 = 7;++/// The tier one step up, `None` at `act`.+pub fn next_tier(tier: &str) -> Option<&'static str> {+ match tier {+ "observe" => Some("sandbox"),+ "sandbox" => Some("act"),+ _ => None,+ }+}++/// What a move up to `to` asks of the scorecard (§9 D5): verified tasks, the last-n window that+/// must have no denial, and the first-try rate (`act` only, which also wants no false success).+struct Rule {+ min_verified: usize,+ last_n: usize,+ min_first_try: Option<f64>,+ no_false_success: bool,+}++fn rule(to: &str) -> Rule {+ if to == "act" {+ Rule { min_verified: 10, last_n: 10, min_first_try: Some(0.7), no_false_success: true }+ } else {+ Rule { min_verified: 5, last_n: 5, min_first_try: None, no_false_success: false }+ }+}++fn rate(k: usize, n: usize) -> Value {+ if n == 0 {+ Value::Null+ } else {+ json!(((k as f64 / n as f64) * 1000.0).round() / 1000.0)+ }+}++fn denied(t: &ScoreTask) -> bool {+ t.denied > 0 || t.denied_failures > 0+}++/// Verified on the first attempt, with no failure on the way.+fn first_try(t: &ScoreTask) -> bool {+ t.state == "verified" && t.attempts <= 1 && t.failures == 0+}++/// The scorecard of `tasks` (a bot's settled tasks of one class, newest first) and whether it+/// may move from `tier` one step up, with what is missing. Pure, so the rules are unit-tested.+pub fn card_of(tasks: &[ScoreTask], tier: &str) -> (Value, Option<&'static str>, Vec<String>) {+ let n = |f: &dyn Fn(&ScoreTask) -> bool| tasks.iter().filter(|t| f(t)).count();+ let sum = |f: &dyn Fn(&ScoreTask) -> i64| tasks.iter().map(f).sum::<i64>();+ let verified = n(&|t| t.state == "verified");+ let first = n(&first_try);+ let false_success = n(&|t| t.false_success > 0);+ let next = next_tier(tier);+ let mut missing = Vec::new();+ let mut recent = Value::Null;+ if let Some(to) = next {+ let r = rule(to);+ let last: Vec<&ScoreTask> = tasks.iter().take(r.last_n).collect();+ let last_denied = last.iter().filter(|t| denied(t)).count();+ if verified < r.min_verified {+ missing.push(format!("{} more verified task(s) (has {verified}, needs {})", r.min_verified - verified, r.min_verified));+ }+ if last_denied > 0 {+ missing.push(format!("no denied call in the last {} tasks (has {last_denied})", r.last_n));+ }+ if let Some(min) = r.min_first_try {+ if verified == 0 || (first as f64) < min * verified as f64 {+ missing.push(format!("first-try rate of at least {}% (has {first} of {verified})", (min * 100.0) as i64));+ }+ }+ if r.no_false_success && false_success > 0 {+ missing.push(format!("no false success (has {false_success})"));+ }+ recent = json!({"n": last.len(), "of": r.last_n, "with_denial": last_denied});+ }+ let mut by_class = serde_json::Map::new();+ by_class.insert("denied".into(), json!(sum(&|t| t.denied_failures)));+ by_class.insert("check_failed".into(), json!(sum(&|t| t.check_failures)));+ let cards = sum(&|t| t.cards);+ let approved = sum(&|t| t.approved);+ let card = json!({+ "tasks": {+ "settled": tasks.len(),+ "verified": verified,+ "failed": n(&|t| t.state == "failed"),+ "cancelled": n(&|t| t.state == "cancelled"),+ },+ "first_try": {"k": first, "n": verified, "rate": rate(first, verified)},+ "verified_rate": {"k": verified, "n": tasks.len(), "rate": rate(verified, tasks.len())},+ "false_success": {"k": false_success, "n": verified, "rate": rate(false_success, verified)},+ "failures": {"total": sum(&|t| t.failures), "by_class": by_class},+ "cards": {+ "shown": cards,+ "approved": approved,+ "denied": sum(&|t| t.denied),+ "approved_rate": {"k": approved, "n": cards, "rate": rate(approved as usize, cards as usize)},+ },+ "calls": sum(&|t| t.calls),+ "external_calls": sum(&|t| t.external_calls),+ "interventions": sum(&|t| t.interventions),+ "tokens": {"spent": sum(&|t| t.spent_tokens), "recovery": sum(&|t| t.recovery_tokens)},+ "recent_denials": recent,+ });+ (card, next, missing)+}++/// `GET /api/capabilities/:kwant_id/scorecard?class=` and the snapshot a proposal keeps.+pub async fn scorecard(db: &Database, kwant_id: &str, class: &str) -> Result<Value, crate::db::DbError> {+ let since = chrono::Utc::now() - chrono::Duration::days(WINDOW_DAYS);+ let tasks = db.score_tasks(kwant_id, class, since).await?;+ let (tier, from) = tier_of(db, kwant_id, class).await;+ let (mut card, next, missing) = card_of(&tasks, tier);+ if let Some(o) = card.as_object_mut() {+ o.insert("kwant_id".into(), json!(kwant_id));+ o.insert("task_class".into(), json!(class));+ o.insert("window_days".into(), json!(WINDOW_DAYS));+ o.insert("since".into(), json!(since.to_rfc3339()));+ o.insert("tier".into(), json!(tier));+ o.insert("tier_from".into(), json!(from));+ o.insert("next_tier".into(), json!(next));+ o.insert("eligible".into(), json!(next.is_some() && missing.is_empty()));+ o.insert("missing".into(), json!(missing));+ }+ Ok(card)+}++/// A proposal as the API shows it: the snapshot as JSON and the Needs-you kind.+pub fn proposal_json(p: &TierProposal) -> Value {+ let mut v = serde_json::to_value(p).unwrap_or(Value::Null);+ v["scorecard"] = serde_json::from_str(&p.scorecard).unwrap_or(Value::Null);+ v["kind"] = json!("tier_proposal");+ v+}++fn changed(state: &AppState, p: &TierProposal) {+ let _ = state.event_sender.send(crate::drivers::events::RuntimeEvent::CapabilityChanged {+ capability: json!({+ "space_id": p.space_id,+ "kwant_id": p.kwant_id,+ "task_class": p.task_class,+ "proposal": proposal_json(p),+ }),+ });+}++/// Why an open proposal can't be granted as asked any more: the bot's tier moved, or its+/// scorecard fell below the step it asked for. `None`: still good.+async fn stale_reason(db: &Database, p: &TierProposal) -> Option<String> {+ let (tier, _) = tier_of(db, &p.kwant_id, &p.task_class).await;+ if tier != p.from_tier {+ return Some(format!("the tier changed to {tier} since the bot asked"));+ }+ let card = scorecard(db, &p.kwant_id, &p.task_class).await.ok()?;+ (card["eligible"] != json!(true)).then(|| {+ let missing: Vec<&str> = card["missing"].as_array().map(|m| m.iter().filter_map(Value::as_str).collect()).unwrap_or_default();+ format!("the scorecard no longer qualifies: {}", missing.join("; "))+ })+}++/// Marks the bot's open proposals (one class, or all) stale where they no longer hold. Lazy:+/// called wherever proposals are read or decided. Leaves them alone while Flight School is off.+pub async fn refresh_stale(state: &AppState, kwant_id: &str, class: Option<&str>) {+ if !enabled(&state.db).await {+ return;+ }+ let open = state.db.tier_proposals_of(kwant_id, 200).await.unwrap_or_default();+ for p in open.iter().filter(|p| p.status == "proposed" && class.is_none_or(|c| c == p.task_class)) {+ if let Some(why) = stale_reason(&state.db, p).await {+ if let Ok(Decided::Done(p)) = state.db.decide_tier_proposal(&p.id, "stale", "kwant", Some(&why)).await {+ tracing::info!(kwant = %p.kwant_id, proposal = %p.id, why = %why, "tier proposal went stale");+ changed(state, &p);+ }+ }+ }+}++// The `tier_propose` bot tool++pub fn propose_tool() -> Value {+ json!({+ "name": "tier_propose",+ "description": "Ask the person to move you one Flight School tier up for a class of tasks (observe → sandbox → act). kwant checks your scorecard (last 30 days of your verified, failed and denied work in that class) and refuses when you don't qualify yet; only the person can grant it. Say why in `reason`.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "task_class": {"type": "string", "description": "The class of tasks, e.g. general or research."},+ "reason": {"type": "string", "description": "Why you should do more on your own here, in a sentence or two."},+ },+ "required": ["task_class", "reason"],+ },+ })+}++pub async fn call_propose(state: &AppState, scope: &crate::server::continuity::SelfScope, args: &Value) -> (String, bool) {+ if !enabled(&state.db).await {+ return ("Flight School is off, so there is no tier to ask for.".into(), true);+ }+ let class = args["task_class"].as_str().map(str::trim).unwrap_or("");+ if !valid_class(class) {+ return ("task_class must be 1–40 of a-z, 0-9 and -".into(), true);+ }+ let reason: String = args["reason"].as_str().map(str::trim).unwrap_or("").chars().take(500).collect();+ if reason.is_empty() {+ return ("Say why in reason.".into(), true);+ }+ let bot = match state.db.get_kwant(&scope.kwant_id).await {+ Ok(Some(b)) => b,+ _ => return ("Couldn't find you.".into(), true),+ };+ refresh_stale(state, &bot.id, Some(class)).await;+ let (tier, _) = tier_of(&state.db, &bot.id, class).await;+ let Some(to) = next_tier(tier) else { return (format!("You already have act for {class}."), true) };+ if let Ok(Some(open)) = state.db.open_tier_proposal(&bot.id, class).await {+ return (format!("You already asked for {} on {class} (proposal {}); it waits for the person.", open.to_tier, open.id), false);+ }+ if let Ok(Some(at)) = state.db.last_declined(&bot.id, class, to).await {+ if let Ok(at) = chrono::DateTime::parse_from_rfc3339(&at) {+ let until = at.with_timezone(&chrono::Utc) + chrono::Duration::days(DECLINE_COOLDOWN_DAYS);+ if until > chrono::Utc::now() {+ return (format!("The person declined {to} on {class} recently; you can ask again after {}.", until.format("%Y-%m-%d")), true);+ }+ }+ }+ let card = match scorecard(&state.db, &bot.id, class).await {+ Ok(c) => c,+ Err(e) => {+ tracing::warn!(error = %e, "could not compute a scorecard");+ return ("Couldn't read your scorecard; try again later.".into(), true);+ }+ };+ if card["eligible"] != json!(true) {+ let missing: Vec<&str> = card["missing"].as_array().map(|m| m.iter().filter_map(Value::as_str).collect()).unwrap_or_default();+ return (format!("Not yet: to ask for {to} on {class} you need {}.", missing.join("; ")), true);+ }+ match state.db.create_tier_proposal(&bot.space_id, &bot.id, class, tier, to, &card, Some(&reason)).await {+ Ok(Ok(p)) => {+ changed(state, &p);+ let verified = card["tasks"]["verified"].as_u64().unwrap_or(0);+ crate::server::continuity::notify(+ state,+ crate::server::continuity::Notification {+ kind: "tier_proposed",+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ channel_id: None,+ title: format!("{} asks for {to} on {class}", bot.name),+ body: format!("{} asks to move from {tier} to {to} on {class} tasks, with {verified} verified in the last {WINDOW_DAYS} days.", bot.name),+ },+ )+ .await;+ tracing::info!(kwant = %bot.id, proposal = %p.id, class, to, "tier proposed");+ (format!("Asked the person for {to} on {class} (proposal {}). Until they grant it you stay at {tier}.", p.id), false)+ }+ Ok(Err(open)) => (format!("You already asked for {} on {class} (proposal {}); it waits for the person.", open.to_tier, open.id), false),+ Err(e) => {+ tracing::warn!(error = %e, "could not save a tier proposal");+ ("Couldn't save the proposal; try again later.".into(), true)+ }+ }+}++// Proposal and scorecard routes. Reads are open; grant and decline are person-only (`auth.rs`)++#[derive(Deserialize)]+pub struct CardQuery {+ class: Option<String>,+}++/// `GET /api/capabilities/:kwant_id/scorecard?class=` (class defaults to `general`).+pub async fn get_scorecard(State(state): State<AppState>, Scope(space): Scope, Path(kwant_id): Path<String>, Query(q): Query<CardQuery>) -> Response {+ let class = q.class.as_deref().map(str::trim).filter(|c| !c.is_empty()).unwrap_or(DEFAULT_CLASS);+ if !valid_class(class) {+ return bad("class must be 1–40 of a-z, 0-9 and -");+ }+ let Some(bot) = bot_in_space(&state, &space, &kwant_id).await else { return not_found("bot") };+ match scorecard(&state.db, &bot.id, class).await {+ Ok(v) => Json(v).into_response(),+ Err(e) => internal(e),+ }+}++#[derive(Deserialize)]+pub struct ProposalQuery {+ status: Option<String>,+ kwant_id: Option<String>,+}++/// `GET /api/capabilities/proposals?status=&kwant_id=`: the space's proposals, newest first.+pub async fn list_proposals(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<ProposalQuery>) -> Response {+ let status = q.status.as_deref().map(str::trim).filter(|s| !s.is_empty());+ if status.is_some_and(|s| !matches!(s, "proposed" | "granted" | "declined" | "stale")) {+ return bad("status must be proposed, granted, declined or stale");+ }+ let bot = match q.kwant_id.as_deref().map(str::trim).filter(|k| !k.is_empty()) {+ Some(k) => match bot_in_space(&state, &space, k).await {+ Some(b) => Some(b.id),+ None => return not_found("bot"),+ },+ None => None,+ };+ let open = state.db.tier_proposals(space.as_str(), bot.as_deref(), Some("proposed"), 200).await.unwrap_or_default();+ let mut bots: Vec<&str> = open.iter().map(|p| p.kwant_id.as_str()).collect();+ bots.sort_unstable();+ bots.dedup();+ for b in bots {+ refresh_stale(&state, b, None).await;+ }+ match state.db.tier_proposals(space.as_str(), bot.as_deref(), status, 200).await {+ Ok(list) => Json(json!({"proposals": list.iter().map(proposal_json).collect::<Vec<_>>()})).into_response(),+ Err(e) => internal(e),+ }+}++fn not_open(status: &str, why: Option<&str>) -> Response {+ let error = match (status, why) {+ ("stale", Some(w)) => format!("this proposal is stale: {w}"),+ _ => format!("this proposal is already {status}"),+ };+ (StatusCode::CONFLICT, Json(json!({"error": error, "status": status}))).into_response()+}++#[derive(Deserialize, Default)]+#[serde(deny_unknown_fields)]+pub struct DecideBody {+ note: Option<String>,+}++#[allow(clippy::result_large_err)]+async fn proposal_in(state: &AppState, space: &crate::db::spaces::SpaceId, id: &str) -> Result<TierProposal, Response> {+ match state.db.tier_proposal(id).await {+ Ok(Some(p)) if p.space_id == space.as_str() => Ok(p),+ Ok(_) => Err(not_found("proposal")),+ Err(e) => Err(internal(e)),+ }+}++/// `POST /api/capabilities/proposals/:id/grant` (person-only; `Idempotency-Key` optional). kwant+/// checks again that the bot is still at the tier it asked from and still qualifies; if not, the+/// proposal goes stale and this answers 409. Of racing grants exactly one writes the policy.+pub async fn grant_proposal(State(state): State<AppState>, Scope(space): Scope, headers: HeaderMap, Path(id): Path<String>) -> Response {+ let route = format!("capabilities/proposals/{id}/grant");+ super::graph::idempotent(&state, &headers, route, || async {+ let p = proposal_in(&state, &space, &id).await?;+ if p.status != "proposed" {+ return Err(not_open(&p.status, p.note.as_deref()));+ }+ if !enabled(&state.db).await {+ return Err(super::routes::conflict("Flight School is off; switch it on to grant tiers"));+ }+ if let Some(why) = stale_reason(&state.db, &p).await {+ return Err(match state.db.decide_tier_proposal(&p.id, "stale", "kwant", Some(&why)).await {+ Ok(Decided::Done(p)) => {+ changed(&state, &p);+ not_open("stale", Some(&why))+ }+ Ok(Decided::NotOpen(s)) => not_open(&s, None),+ Ok(Decided::Missing) => not_found("proposal"),+ Err(e) => internal(e),+ });+ }+ match state.db.decide_tier_proposal(&p.id, "granted", "person", None).await {+ Ok(Decided::Done(p)) => {+ tracing::info!(kwant = %p.kwant_id, proposal = %p.id, tier = %p.to_tier, "tier proposal granted");+ changed(&state, &p);+ Ok(json!({"proposal": proposal_json(&p), "capabilities": status_json(&state, &p.kwant_id).await}))+ }+ Ok(Decided::NotOpen(s)) => Err(not_open(&s, None)),+ Ok(Decided::Missing) => Err(not_found("proposal")),+ Err(crate::db::DbError::Sqlx(e)) if e.to_string().contains("UNIQUE") => Err(not_open("granted", None)),+ Err(e) => Err(internal(e)),+ }+ })+ .await+}++/// `POST /api/capabilities/proposals/:id/decline {note?}` (person-only; `Idempotency-Key`+/// optional). The bot may ask for the same step again after [`DECLINE_COOLDOWN_DAYS`].+pub async fn decline_proposal(+ State(state): State<AppState>,+ Scope(space): Scope,+ headers: HeaderMap,+ Path(id): Path<String>,+ body: Option<Json<DecideBody>>,+) -> Response {+ let note = body.and_then(|Json(b)| b.note).map(|n| n.trim().chars().take(500).collect::<String>()).filter(|n| !n.is_empty());+ let route = format!("capabilities/proposals/{id}/decline");+ super::graph::idempotent(&state, &headers, route, || async {+ let p = proposal_in(&state, &space, &id).await?;+ match state.db.decide_tier_proposal(&p.id, "declined", "person", note.as_deref()).await {+ Ok(Decided::Done(p)) => {+ changed(&state, &p);+ Ok(json!({"proposal": proposal_json(&p), "capabilities": status_json(&state, &p.kwant_id).await}))+ }+ Ok(Decided::NotOpen(s)) => Err(not_open(&s, None)),+ Ok(Decided::Missing) => Err(not_found("proposal")),+ Err(e) => Err(internal(e)),+ }+ })+ .await+}+#[cfg(test)]mod tests {use super::*;@@ -352,6 +764,51 @@ mod tests {assert_eq!(decide("sandbox", "external", true, true), Some("Sandbox: commands that can change things ask"));}+ fn task(state: &str, attempts: i64) -> ScoreTask {+ ScoreTask {+ id: "t".into(),+ state: state.into(),+ attempts,+ finished_at: chrono::Utc::now(),+ failures: 0,+ denied_failures: 0,+ check_failures: 0,+ calls: 0,+ external_calls: 0,+ cards: 0,+ approved: 0,+ denied: 0,+ false_success: 0,+ interventions: 0,+ spent_tokens: 0,+ recovery_tokens: 0,+ }+ }++ #[test]+ fn eligibility_rules() {+ // sandbox → act: 10 verified, first try at 70% exactly qualifies, 60% doesn't+ let mut ten: Vec<ScoreTask> = (0..10).map(|i| task("verified", if i < 7 { 1 } else { 2 })).collect();+ assert_eq!(card_of(&ten, "sandbox").1, Some("act"));+ assert!(card_of(&ten, "sandbox").2.is_empty(), "{:?}", card_of(&ten, "sandbox").2);+ ten[0].attempts = 3;+ assert!(card_of(&ten, "sandbox").2.iter().any(|m| m.contains("first-try")));+ // A denial older than the last 10 doesn't count; a newer one does+ let mut eleven: Vec<ScoreTask> = (0..11).map(|_| task("verified", 1)).collect();+ eleven[10].denied = 1;+ assert!(card_of(&eleven, "sandbox").2.is_empty());+ eleven[9].denied_failures = 1;+ assert!(card_of(&eleven, "sandbox").2.iter().any(|m| m.contains("last 10")));+ // observe → sandbox: 5 verified, no first-try rule+ let five: Vec<ScoreTask> = (0..5).map(|_| task("verified", 3)).collect();+ assert!(card_of(&five, "observe").2.is_empty());+ assert!(!card_of(&five[..4], "observe").2.is_empty());+ // act: nothing above it+ assert_eq!(card_of(&five, "act").1, None);+ // No rate without its n+ assert_eq!(card_of(&[], "observe").0["first_try"], json!({"k": 0, "n": 0, "rate": null}));+ }+#[test]fn engines_kwant_can_hold() {for ok in ["claude", "claude-sonnet-4-6", "grok", "grok-4", "anthropic/claude-opus"] {diff --git a/src/server/mod.rs b/src/server/mod.rsindex 8b965ebc..ea84ca99 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -394,6 +394,10 @@ pub fn create_router(state: AppState) -> Router {.route("/api/workflow-changes", get(missions::autofix::list_changes)).route("/api/capabilities", get(missions::flight_school::get_capabilities).post(missions::flight_school::set_capability)).route("/api/capabilities/:kwant_id/revoke", post(missions::flight_school::revoke_capability))+ .route("/api/capabilities/:kwant_id/scorecard", get(missions::flight_school::get_scorecard))+ .route("/api/capabilities/proposals", get(missions::flight_school::list_proposals))+ .route("/api/capabilities/proposals/:id/grant", post(missions::flight_school::grant_proposal))+ .route("/api/capabilities/proposals/:id/decline", post(missions::flight_school::decline_proposal)).route("/api/workflow-changes/:id/approve", post(missions::autofix::approve_change)).route("/api/workflow-changes/:id/reject", post(missions::autofix::reject_change)).route("/api/tasks/:id/flags/:flag_id/resolve", post(missions::graph::resolve_flag))diff --git a/src/server/sse.rs b/src/server/sse.rsindex 22959dff..cdfe871a 100644--- a/src/server/sse.rs+++ b/src/server/sse.rs@@ -91,7 +91,7 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {out.extend(fields(suggestion, &["kwant_id", "channel_id", "direct_kwant_id", "thread_id"], Owner::Context));out}- E::BotActionUpdated { action: v } | E::HireUpdated { hire: v } => {+ E::BotActionUpdated { action: v } | E::HireUpdated { hire: v } | E::CapabilityChanged { capability: v } => {let mut out = fields(v, &["space_id"], Owner::Space);out.extend(fields(v, &["kwant_id", "channel_id", "direct_kwant_id", "thread_id"], Owner::Context));out@@ -227,6 +227,7 @@ mod tests {E::McpSuggestionUpdated { suggestion: json!({"id": "g", "space_id": "spc_default", "kwant_id": "k"}) },E::BotActionUpdated { action: json!({"id": "b", "space_id": "spc_default", "kwant_id": "k"}) },E::HireUpdated { hire: json!({"id": "h", "space_id": "spc_default", "kwant_id": "k"}) },+ E::CapabilityChanged { capability: json!({"space_id": "spc_default", "kwant_id": "k", "task_class": "general"}) },E::Scoped {tag: TurnTag { turn_id: s("x"), kwant_id: s("k"), context_id: s("c"), thread_id: None },event: Box::new(E::TextDelta(s("x"))),@@ -319,6 +320,7 @@ mod tests {| E::McpSuggestionUpdated { .. }| E::BotActionUpdated { .. }| E::HireUpdated { .. }+ | E::CapabilityChanged { .. }| E::Scoped { .. }| E::ProfileSwitched { .. }| E::DiscussionStarted { .. }diff --git a/tests/app_update_test.rs b/tests/app_update_test.rsindex 01215c3e..703af915 100644--- a/tests/app_update_test.rs+++ b/tests/app_update_test.rs@@ -263,7 +263,7 @@ async fn app_update_and_work_ahead_are_on_for_lists_saved_before_they_existed()// What a person who saved their notification settings before #78 has storede.state.db.set_setting("notify_on", r#"["turn_finished","approval_needed"]"#).await.unwrap();let on = continuity::notify_on(&e.state).await;- assert_eq!(on, kinds(&["turn_finished", "approval_needed", "app_update", "work_ahead", "automation_suggested"]));+ assert_eq!(on, kinds(&["turn_finished", "approval_needed", "app_update", "work_ahead", "automation_suggested", "tier_proposed"]));assert!(update_notification_delivered(&e, "0.1.2").await);let (_, s) = call(&e.app, "GET", "/api/settings", None).await;assert!(s["notify_on"].as_array().unwrap().contains(&json!("app_update")), "the switch shows on: {s}");diff --git a/tests/continuity_test.rs b/tests/continuity_test.rsindex c78ba8fd..819540b8 100644--- a/tests/continuity_test.rs+++ b/tests/continuity_test.rs@@ -1569,7 +1569,7 @@ async fn webhook_setting_is_https_only_and_masked() {assert_eq!(s["notify_webhook_url"], "");assert_eq!(s["notify_on"],- json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed", "question_asked", "loose_ends", "human_step", "app_update", "work_ahead", "automation_suggested"])+ json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed", "question_asked", "loose_ends", "human_step", "app_update", "work_ahead", "automation_suggested", "tier_proposed"]));let (status, _) = req(diff --git a/tests/flight_school_scorecard_test.rs b/tests/flight_school_scorecard_test.rsnew file mode 100644index 00000000..fc1c7968--- /dev/null+++ b/tests/flight_school_scorecard_test.rs@@ -0,0 +1,615 @@+//! Mission Control Phase C4: Flight School scorecards and tier proposals. The contract's+//! acceptance tests (docs/mission-control.md §14, "Scorecards and proposals"): scorecard counts on+//! seeded rows, `tier_propose` refused when the bot doesn't qualify and accepted when it does, a+//! proposal going stale when the card drops or the tier moves, grant writing exactly one live+//! policy with racing grants giving one 200, only the person deciding, and the payment floor+//! still carding after a grant to act.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use chrono::{DateTime, Duration as Days, Utc};+use kwnt::{+ broker::{ApprovalDecision, PermissionBroker},+ config::Config,+ db::{models::Kwant, spaces::SpaceId, Database},+ drivers::events::RuntimeEvent,+ router::LayaRouter,+ server::{+ continuity::{SelfScope, TurnOrigin},+ create_router, mcp_runtime,+ turns::ActiveTurn,+ AppState,+ },+ tools::ToolRunner,+};+use serde_json::{json, Value};+use sqlx::sqlite::SqlitePoolOptions;+use std::path::{Path, PathBuf};+use std::time::Duration;+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++const STRIPE_POST: &str = "curl -X POST https://api.stripe.com/v1/charges -u sk_test_x: -d amount=100 -d currency=usd";++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 bot = state.db.list_kwants(&space).await.unwrap()[0].clone();+ 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, general, state, _tmp: tmp };+ person(&e, "POST", "/api/settings", json!({"mission_board": true})).await;+ 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: Value) -> Value {+ let body = (method != "GET").then_some(body);+ let (status, v) = call(&e.app, method, uri, Some(e.state.api_token.reveal()), body).await;+ assert!(status.is_success(), "{method} {uri}: {status} {v}");+ v+}++async fn set_tier(e: &Env, class: &str, tier: &str) {+ person(e, "POST", "/api/capabilities", json!({"kwant_id": e.bot.id, "task_class": class, "tier": tier})).await;+}++async fn flight_school(e: &Env, on: bool) {+ person(e, "POST", "/api/settings", json!({"flight_school": on})).await;+}++fn id(v: &Value) -> String {+ v["id"].as_str().unwrap().to_string()+}++/// A live turn of the bot in #general with its own tools, working in `folder`; returns (turn id, token).+async fn turn(e: &Env, folder: &Path) -> (String, String) {+ let turn_id = uuid::Uuid::new_v4().to_string();+ let scope = SelfScope {+ kwant_id: e.bot.id.clone(),+ kwant_name: e.bot.name.clone(),+ origin: Some(TurnOrigin { channel_id: Some(e.general.clone()), ..Default::default() }),+ turn_id: Some(turn_id.clone()),+ ..Default::default()+ };+ let (_, token) =+ mcp_runtime::prepare_turn_with_opts(&e.state, &e.bot, Some(turn_id.clone()), Some(folder.to_path_buf()), Some(scope), Default::default())+ .await+ .unwrap();+ e.state.turns.set_turn(ActiveTurn {+ turn_id: turn_id.clone(),+ kwant_id: e.bot.id.clone(),+ context_id: e.general.clone(),+ thread_id: None,+ state: "running".into(),+ since: Utc::now(),+ purpose: None,+ });+ (turn_id, token)+}++async fn end(e: &Env, turn_id: &str, token: &str) {+ mcp_runtime::finish_turn(&e.state, token).await;+ e.state.turns.end_turn(turn_id);+}++async fn self_tool(e: &Env, token: &str, name: &str, args: Value) -> (bool, String) {+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});+ let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc)).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ (v["result"]["isError"].as_bool().unwrap_or(false), v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string())+}++/// A person's mission with one task the bot owns, of `class`, claimed by the bot (with a+async fn claimed_task(e: &Env, class: &str, checkpoint: bool) -> (String, PathBuf) {+ person(e, "POST", "/api/settings", json!({"checkpoints": checkpoint})).await;+ let body = json!({"title": "Ship it", "goal": "a release", "lead_kwant_id": e.bot.id, "budget_tokens": 900_000,+ "channel_id": e.general, "tasks": [{"title": "A", "owner": e.bot.id, "task_class": class}]});+ let m = person(e, "POST", "/api/missions", body).await;+ let detail = person(e, "GET", &format!("/api/missions/{}", id(&m)), json!(null)).await;+ let tid = id(&detail["tasks"][0]);+ let mission = e.state.db.get_mission(&id(&m)).await.unwrap().unwrap();+ let dir = PathBuf::from(mission.workspace_path);+ std::fs::create_dir_all(&dir).unwrap();+ let (turn_id, token) = turn(e, &dir).await;+ let (err, text) = self_tool(e, &token, "task_claim", json!({"task_id": tid})).await;+ assert!(!err, "{text}");+ end(e, &turn_id, &token).await;+ assert_eq!(e.state.db.run_has_checkpoint(&tid).await.unwrap(), checkpoint);+ (tid, dir)+}++/// What claude's permission prompt gets for `tool {input}` in a turn working in `folder`:+/// `Ok(behavior)` when kwnt answers without a card, `Err(card details)` when it shows one (denied).+async fn claude_asks(e: &Env, folder: &Path, tool: &str, input: Value) -> Result<String, Value> {+ let (turn_id, token) = turn(e, folder).await;+ let out = ask_in(e, &token, tool, input).await;+ end(e, &turn_id, &token).await;+ out+}++async fn ask_in(e: &Env, token: &str, tool: &str, input: Value) -> Result<String, Value> {+ let mut events = e.state.event_sender.subscribe();+ let ask = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "approve",+ "arguments": {"tool_name": tool, "input": input, "tool_use_id": "tu_1"}}});+ let app = e.app.clone();+ let path = format!("/api/mcp/permission/{token}");+ let mut prompt = tokio::spawn(async move { call(&app, "POST", &path, None, Some(ask)).await });+ let behavior = |v: &Value| {+ let text = v["result"]["content"][0]["text"].as_str().unwrap();+ serde_json::from_str::<Value>(text).unwrap()["behavior"].as_str().unwrap().to_string()+ };+ let answered = tokio::time::timeout(Duration::from_millis(1500), &mut prompt).await;+ let card = loop {+ match events.try_recv() {+ Ok(RuntimeEvent::ApprovalRequired { id, details, .. }) => break Some((id, details)),+ Ok(_) => continue,+ Err(_) => break None,+ }+ };+ match (answered, card) {+ (Ok(done), None) => Ok(behavior(&done.unwrap().1)),+ (Err(_), Some((id, details))) => {+ assert!(e.state.broker.resolve(&id, ApprovalDecision::Deny).await);+ let (_, v) = prompt.await.unwrap();+ assert_eq!(behavior(&v), "deny");+ Err(details)+ }+ (answered, card) => panic!("answered {} with card {card:?}", answered.is_ok()),+ }+}++/// One settled task kwant would have written: owned by the bot, of `class`, claimed once, in+/// `state` (verified through a passing person check), finished `days_ago`.+#[derive(Clone)]+struct Seed {+ class: &'static str,+ state: &'static str,+ attempts: i64,+ days_ago: i64,+ claimed: bool,+ denied_call: bool,+ denied_failure: bool,+ check_failure: bool,+ approved_card: bool,+ external_call: bool,+ flag: Option<&'static str>,+ person_retry: bool,+ spent: i64,+ recovery: i64,+}++fn verified() -> Seed {+ Seed {+ class: "research",+ state: "verified",+ attempts: 1,+ days_ago: 1,+ claimed: true,+ denied_call: false,+ denied_failure: false,+ check_failure: false,+ approved_card: false,+ external_call: false,+ flag: None,+ person_retry: false,+ spent: 100,+ recovery: 0,+ }+}++/// Seeds tasks straight into the database, oldest first (so the last one is the newest), at+/// one-minute steps so their order is fixed.+async fn seed(e: &Env, tasks: Vec<Seed>) -> Vec<String> {+ let pool = SqlitePoolOptions::new()+ .max_connections(1)+ .connect(&format!("sqlite://{}", e.state.config.data_dir.join("kwnt.db").display()))+ .await+ .unwrap();+ let mut ids = Vec::new();+ let base = Utc::now() - Days::minutes(tasks.len() as i64 + 5);+ for (i, s) in tasks.iter().enumerate() {+ let id = uuid::Uuid::new_v4().to_string();+ let finished: DateTime<Utc> = base + Days::minutes(i as i64) - Days::days(s.days_ago);+ let first = if s.state == "verified" { "review" } else { s.state };+ sqlx::query(+ "INSERT INTO tasks (id, space_id, title, state, owner_kwant_id, budget_tokens, spent_tokens, attempts, source_kind, created_by, \+ created_at, updated_at, task_class, recovery_spent_tokens, finished_at) \+ VALUES (?, 'spc_default', 'seeded', ?, ?, 100000, ?, ?, 'person', 'person', ?, ?, ?, ?, ?)",+ )+ .bind(&id)+ .bind(first)+ .bind(&e.bot.id)+ .bind(s.spent)+ .bind(s.attempts)+ .bind(finished)+ .bind(finished)+ .bind(s.class)+ .bind(s.recovery)+ .bind(finished)+ .execute(&pool)+ .await+ .unwrap();+ if s.state == "verified" {+ sqlx::query(+ "INSERT INTO outcome_checks (id, task_id, kind, spec, status, checked_by, requested_by, created_at) \+ VALUES (?, ?, 'person', '{}', 'passed', 'person', 'person', ?)",+ )+ .bind(uuid::Uuid::new_v4().to_string())+ .bind(&id)+ .bind(finished)+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query("UPDATE tasks SET state = 'verified' WHERE id = ?").bind(&id).execute(&pool).await.unwrap();+ }+ if s.claimed {+ let ms = finished.timestamp_millis();+ sqlx::query("INSERT INTO agent_claims (id, task_id, kwant_id, claimed_at, expires_at, released_at, release_reason) VALUES (?, ?, ?, ?, ?, ?, 'done')")+ .bind(uuid::Uuid::new_v4().to_string())+ .bind(&id)+ .bind(&e.bot.id)+ .bind(ms - 60_000)+ .bind(ms + 60_000)+ .bind(ms)+ .execute(&pool)+ .await+ .unwrap();+ }+ let call = |effect: &'static str, decision: &'static str, card: bool| {+ sqlx::query(+ "INSERT INTO turn_tool_calls (turn_id, kwant_id, task_id, tool_name, effect, summary, decision, approval_id, created_at) \+ VALUES ('t', ?, ?, 'Bash', ?, 'x', ?, ?, ?)",+ )+ .bind(e.bot.id.clone())+ .bind(id.clone())+ .bind(effect)+ .bind(decision)+ .bind(card.then(|| uuid::Uuid::new_v4().to_string()))+ .bind(finished)+ };+ if s.denied_call {+ call("external", "denied", true).execute(&pool).await.unwrap();+ }+ if s.approved_card {+ call("workspace", "approved", true).execute(&pool).await.unwrap();+ }+ if s.external_call {+ call("external", "allowed", false).execute(&pool).await.unwrap();+ }+ for (on, class) in [(s.denied_failure, "denied"), (s.check_failure, "check_failed")] {+ if on {+ sqlx::query("INSERT INTO task_failures (id, task_id, attempt, source, class, summary, created_at) VALUES (?, ?, 1, 'check', ?, 'x', ?)")+ .bind(uuid::Uuid::new_v4().to_string())+ .bind(&id)+ .bind(class)+ .bind(finished)+ .execute(&pool)+ .await+ .unwrap();+ }+ }+ if let Some(resolution) = s.flag {+ let resolved = (resolution != "open").then_some(finished);+ sqlx::query(+ "INSERT INTO task_flags (id, task_id, kind, cause, cause_task_id, created_at, resolved_at, resolved_by, resolution) \+ VALUES (?, ?, 'may_be_invalid', 'evidence_changed', ?, ?, ?, ?, ?)",+ )+ .bind(uuid::Uuid::new_v4().to_string())+ .bind(&id)+ .bind(&id)+ .bind(finished)+ .bind(resolved)+ .bind(resolved.map(|_| "person"))+ .bind((resolution != "open").then_some(resolution))+ .execute(&pool)+ .await+ .unwrap();+ }+ if s.person_retry {+ sqlx::query("INSERT INTO task_events (task_id, kind, actor, from_state, to_state, created_at) VALUES (?, 'state', 'person', 'failed', 'ready', ?)")+ .bind(&id)+ .bind(finished)+ .execute(&pool)+ .await+ .unwrap();+ }+ ids.push(id);+ }+ pool.close().await;+ ids+}++async fn card(e: &Env, class: &str) -> Value {+ person(e, "GET", &format!("/api/capabilities/{}/scorecard?class={class}", e.bot.id), json!(null)).await+}++/// The bot calls `tier_propose` in a chat turn; (refused?, text).+async fn propose(e: &Env, class: &str) -> (bool, String) {+ let dir = e.state.config.data_dir.join("chat");+ std::fs::create_dir_all(&dir).unwrap();+ let (turn_id, token) = turn(e, &dir).await;+ let out = self_tool(e, &token, "tier_propose", json!({"task_class": class, "reason": "I keep landing these"})).await;+ end(e, &turn_id, &token).await;+ out+}++async fn proposals(e: &Env, status: &str) -> Vec<Value> {+ let v = person(e, "GET", &format!("/api/capabilities/proposals?status={status}"), json!(null)).await;+ v["proposals"].as_array().unwrap().clone()+}++async fn live_rows(e: &Env, class: &str) -> Vec<Value> {+ let v = person(e, "GET", &format!("/api/capabilities?kwant_id={}", e.bot.id), json!(null)).await;+ v["policies"].as_array().unwrap().iter().filter(|p| p["task_class"] == class).cloned().collect()+}++#[tokio::test]+async fn the_scorecard_counts_seeded_rows() {+ let e = setup().await;+ let mut tasks = vec![+ // 3 verified first try, one with an approved card and one external call+ verified(),+ Seed { approved_card: true, external_call: true, ..verified() },+ verified(),+ // verified on the second attempt, after a failed check, with a person retry+ Seed { attempts: 2, check_failure: true, person_retry: true, spent: 300, recovery: 50, ..verified() },+ // verified, then its evidence changed and the person said redo: a false success+ Seed { flag: Some("redo"), ..verified() },+ // verified and flagged, but the person said it still holds: not a false success+ Seed { flag: Some("still_valid"), ..verified() },+ // failed with a denied call (and a denied failure)+ Seed { state: "failed", denied_call: true, denied_failure: true, ..verified() },+ Seed { state: "cancelled", ..verified() },+ ];+ // Not counted: another class, older than 30 days, never claimed+ tasks.push(Seed { class: "general", ..verified() });+ tasks.push(Seed { days_ago: 31, ..verified() });+ tasks.push(Seed { claimed: false, ..verified() });+ seed(&e, tasks).await;+ let c = card(&e, "research").await;+ assert_eq!(c["tasks"], json!({"settled": 8, "verified": 6, "failed": 1, "cancelled": 1}), "{c}");+ assert_eq!(c["first_try"], json!({"k": 5, "n": 6, "rate": 0.833}), "{c}");+ assert_eq!(c["false_success"]["k"], 1, "{c}");+ assert_eq!(c["failures"], json!({"total": 2, "by_class": {"denied": 1, "check_failed": 1}}), "{c}");+ assert_eq!(c["cards"]["shown"], 2, "{c}");+ assert_eq!(c["cards"]["approved"], 1, "{c}");+ assert_eq!(c["cards"]["denied"], 1, "{c}");+ assert_eq!(c["external_calls"], 2, "{c}");+ assert_eq!(c["interventions"], 1, "{c}");+ assert_eq!(c["tokens"], json!({"spent": 1000, "recovery": 50}), "{c}");+ assert_eq!(c["window_days"], 30);+ // No policy row is act: nothing to ask for+ assert_eq!(c["tier"], "act");+ assert_eq!(c["next_tier"], Value::Null);+ assert_eq!(c["eligible"], false);+ // A class with no tasks: no rate without its n+ let empty = card(&e, "nothing-here").await;+ assert_eq!(empty["first_try"], json!({"k": 0, "n": 0, "rate": null}), "{empty}");+ // At sandbox the card says what act still needs+ set_tier(&e, "research", "sandbox").await;+ let c = card(&e, "research").await;+ assert_eq!(c["next_tier"], "act");+ let missing = c["missing"].to_string();+ assert!(missing.contains("4 more verified") && missing.contains("denied") && missing.contains("false success"), "{missing}");+ assert!(!missing.contains("first-try"), "5 of 6 is over 70%: {missing}");+ // A bot reads scorecards; class slugs are checked+ let (s, _) = call(&e.app, "GET", &format!("/api/capabilities/{}/scorecard?class=Bad%20Class", e.bot.id), Some(e.state.api_token.reveal()), None).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+}++#[tokio::test]+async fn propose_is_refused_until_the_bot_qualifies_then_waits_for_the_person() {+ let e = setup().await;+ // Off: no tiers to ask for+ let (err, text) = propose(&e, "research").await;+ assert!(err && text.contains("Flight School is off"), "{text}");+ flight_school(&e, true).await;+ // Act (no row): nothing above it+ let (err, text) = propose(&e, "research").await;+ assert!(err && text.contains("already have act"), "{text}");+ set_tier(&e, "*", "observe").await;+ seed(&e, vec![verified(); 4]).await;+ let (err, text) = propose(&e, "research").await;+ assert!(err && text.contains("1 more verified"), "{text}");+ assert!(proposals(&e, "proposed").await.is_empty());+ seed(&e, vec![verified()]).await;+ let (err, text) = propose(&e, "research").await;+ assert!(!err, "{text}");+ let open = proposals(&e, "proposed").await;+ assert_eq!(open.len(), 1);+ let p = &open[0];+ assert_eq!((p["from_tier"].as_str(), p["to_tier"].as_str(), p["task_class"].as_str()), (Some("observe"), Some("sandbox"), Some("research")));+ assert_eq!(p["kind"], "tier_proposal");+ assert_eq!(p["scorecard"]["tasks"]["verified"], 5, "the snapshot is kwant's card: {p}");+ assert_eq!(p["reason"], "I keep landing these");+ // Asking again reports the one waiting, it doesn't add another+ let (err, text) = propose(&e, "research").await;+ assert!(!err && text.contains("already asked"), "{text}");+ assert_eq!(proposals(&e, "proposed").await.len(), 1);+ // Proposing changes no tier+ let caps = person(&e, "GET", &format!("/api/capabilities?kwant_id={}", e.bot.id), json!(null)).await;+ assert!(caps["effective"].as_array().unwrap().iter().any(|x| x["task_class"] == "research" && x["tier"] == "observe"), "{caps}");+ assert_eq!(caps["proposals"].as_array().unwrap().len(), 1, "{caps}");+ // A denied call in the last 5 tasks refuses the next class's ask+ seed(&e, vec![Seed { class: "ops", ..verified() }; 5]).await;+ seed(&e, vec![Seed { class: "ops", state: "failed", denied_call: true, ..verified() }]).await;+ let (err, text) = propose(&e, "ops").await;+ assert!(err && text.contains("no denied call in the last 5"), "{text}");+}++#[tokio::test]+async fn only_the_person_grants_or_declines_and_a_decline_cools_down() {+ let e = setup().await;+ flight_school(&e, true).await;+ set_tier(&e, "research", "observe").await;+ seed(&e, vec![verified(); 5]).await;+ assert!(!propose(&e, "research").await.0);+ let pid = proposals(&e, "proposed").await[0]["id"].as_str().unwrap().to_string();+ let dir = e.state.config.data_dir.join("chat");+ let (turn_id, token) = turn(&e, &dir).await;+ for verb in ["grant", "decline"] {+ let (s, v) = call(&e.app, "POST", &format!("/api/capabilities/proposals/{pid}/{verb}"), Some(&token), Some(json!({}))).await;+ assert_eq!(s, StatusCode::FORBIDDEN, "a bot token can't {verb}: {v}");+ }+ let (s, _) = call(&e.app, "GET", "/api/capabilities/proposals", Some(&token), None).await;+ assert_eq!(s, StatusCode::OK, "reads stay open");+ end(&e, &turn_id, &token).await;+ let v = person(&e, "POST", &format!("/api/capabilities/proposals/{pid}/decline"), json!({"note": "not this week"})).await;+ assert_eq!(v["proposal"]["status"], "declined");+ assert_eq!(v["proposal"]["note"], "not this week");+ assert_eq!(live_rows(&e, "research").await[0]["tier"], "observe", "a decline changes no tier");+ let (s, v) = call(&e.app, "POST", &format!("/api/capabilities/proposals/{pid}/grant"), Some(e.state.api_token.reveal()), None).await;+ assert_eq!(s, StatusCode::CONFLICT);+ assert_eq!(v["status"], "declined", "{v}");+ let (err, text) = propose(&e, "research").await;+ assert!(err && text.contains("declined"), "{text}");+ // An unknown proposal is 404+ let (s, _) = call(&e.app, "POST", "/api/capabilities/proposals/nope/grant", Some(e.state.api_token.reveal()), None).await;+ assert_eq!(s, StatusCode::NOT_FOUND);+}++#[tokio::test]+async fn a_proposal_goes_stale_when_the_card_drops_or_the_tier_moves() {+ let e = setup().await;+ flight_school(&e, true).await;+ set_tier(&e, "research", "observe").await;+ seed(&e, vec![verified(); 5]).await;+ assert!(!propose(&e, "research").await.0);+ // A denied call lands in the last 5 before the person answers+ seed(&e, vec![Seed { state: "failed", denied_call: true, ..verified() }]).await;+ let stale = proposals(&e, "stale").await;+ assert_eq!(stale.len(), 1, "{stale:?}");+ assert!(stale[0]["note"].as_str().unwrap().contains("no longer qualifies"), "{}", stale[0]);+ let pid = stale[0]["id"].as_str().unwrap();+ let (s, v) = call(&e.app, "POST", &format!("/api/capabilities/proposals/{pid}/grant"), Some(e.state.api_token.reveal()), None).await;+ assert_eq!((s, v["status"].as_str()), (StatusCode::CONFLICT, Some("stale")), "{v}");+ assert_eq!(live_rows(&e, "research").await[0]["tier"], "observe");++ // The person moves the tier by hand while a proposal waits: the grant refuses it as stale+ seed(&e, vec![Seed { class: "ops", ..verified() }; 5]).await;+ set_tier(&e, "ops", "observe").await;+ assert!(!propose(&e, "ops").await.0);+ let pid = proposals(&e, "proposed").await[0]["id"].as_str().unwrap().to_string();+ set_tier(&e, "ops", "act").await;+ let (s, v) = call(&e.app, "POST", &format!("/api/capabilities/proposals/{pid}/grant"), Some(e.state.api_token.reveal()), None).await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ assert!(v["error"].as_str().unwrap().contains("tier changed"), "{v}");+ assert_eq!(live_rows(&e, "ops").await[0]["tier"], "act", "the stale grant wrote nothing");+}++#[tokio::test]+async fn racing_grants_write_exactly_one_live_policy() {+ let e = setup().await;+ flight_school(&e, true).await;+ set_tier(&e, "research", "observe").await;+ seed(&e, vec![verified(); 5]).await;+ assert!(!propose(&e, "research").await.0);+ let pid = proposals(&e, "proposed").await[0]["id"].as_str().unwrap().to_string();+ let mut events = e.state.event_sender.subscribe();+ let mut racers = Vec::new();+ for _ in 0..10 {+ let app = e.app.clone();+ let uri = format!("/api/capabilities/proposals/{pid}/grant");+ let token = e.state.api_token.reveal().to_string();+ racers.push(tokio::spawn(async move { call(&app, "POST", &uri, Some(&token), None).await }));+ }+ let mut ok = 0;+ for r in racers {+ let (s, v) = r.await.unwrap();+ match s {+ StatusCode::OK => ok += 1,+ StatusCode::CONFLICT => assert_eq!(v["status"], "granted", "{v}"),+ other => panic!("{other}: {v}"),+ }+ }+ assert_eq!(ok, 1, "one grant wins");+ let live = live_rows(&e, "research").await;+ assert_eq!(live.len(), 1, "{live:?}");+ assert_eq!(live[0]["tier"], "sandbox");+ assert_eq!(live[0]["granted_by"], "person");+ let caps = person(&e, "GET", &format!("/api/capabilities?kwant_id={}", e.bot.id), json!(null)).await;+ let grants = caps["events"].as_array().unwrap().iter().filter(|x| x["kind"] == "granted" && x["task_class"] == "research" && x["tier"] == "sandbox").count();+ assert_eq!(grants, 1, "{caps}");+ // The board hears about it+ let mut heard = false;+ while let Ok(ev) = events.try_recv() {+ if let RuntimeEvent::CapabilityChanged { capability } = ev {+ heard |= capability["proposal"]["status"] == "granted" && capability["space_id"] == "spc_default";+ }+ }+ assert!(heard);+ // A retry with the same Idempotency-Key replays the answer+ seed(&e, vec![Seed { class: "ops", ..verified() }; 5]).await;+ set_tier(&e, "ops", "observe").await;+ assert!(!propose(&e, "ops").await.0);+ let pid = proposals(&e, "proposed").await[0]["id"].as_str().unwrap().to_string();+ let req = || {+ Request::builder()+ .method("POST")+ .uri(format!("/api/capabilities/proposals/{pid}/grant"))+ .header("authorization", format!("Bearer {}", e.state.api_token.reveal()))+ .header("idempotency-key", "grant-ops-1")+ .body(Body::empty())+ .unwrap()+ };+ let a = e.app.clone().oneshot(req()).await.unwrap();+ assert_eq!(a.status(), StatusCode::OK);+ let b = e.app.clone().oneshot(req()).await.unwrap();+ assert_eq!(b.status(), StatusCode::OK);+ assert_eq!(b.headers().get("idempotent-replayed").map(|v| v.to_str().unwrap()), Some("true"));+ assert_eq!(live_rows(&e, "ops").await.len(), 1);+}++#[tokio::test]+async fn a_grant_to_act_keeps_the_payment_floor() {+ let e = setup().await;+ person(&e, "PUT", &format!("/api/kwants/{}/approvals", e.bot.id), json!({"approvals": "off"})).await;+ flight_school(&e, true).await;+ set_tier(&e, "general", "sandbox").await;+ seed(&e, vec![Seed { class: "general", ..verified() }; 10]).await;+ let (err, text) = propose(&e, "general").await;+ assert!(!err, "{text}");+ let pid = proposals(&e, "proposed").await[0]["id"].as_str().unwrap().to_string();+ person(&e, "POST", &format!("/api/capabilities/proposals/{pid}/grant"), json!(null)).await;+ assert_eq!(live_rows(&e, "general").await[0]["tier"], "act");+ let (_tid, dir) = claimed_task(&e, "general", true).await;+ let Err(d) = claude_asks(&e, &dir, "Bash", json!({"command": STRIPE_POST})).await else { panic!("a payment asks at a granted act") };+ assert!(d["payment_reason"].as_str().unwrap().contains("stripe.com"), "{d}");+ // And a revoke is still instant after a grant+ person(&e, "POST", &format!("/api/capabilities/{}/revoke", e.bot.id), json!({"task_class": "general", "to_tier": "observe"})).await;+ let Err(d) = claude_asks(&e, &dir, "Write", json!({"file_path": dir.join("a.md").display().to_string(), "content": "x"})).await else {+ panic!("observe cards a write")+ };+ assert!(d["tier_reason"].as_str().is_some(), "{d}");+}