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.

Mission Control Phase A: one tasks table and verified outcomes (#87)

lin-botd6d0c81cc492
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dbd706ed..a257e8aa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
+### Added
+- **Mission Control (preview, off by default).** One task board for everything bots work on: planned
+ missions, team hand-offs, routine runs, Loose Ends you take on and work-ahead posts. A task counts as
+ **verified** only when an outcome check passes (a command, a URL, a file, a teammate's review with
+ evidence, or you), never on the bot's own word. Missions have a token budget that claims can't
+ exceed, tasks wait for the tasks they depend on, and anything waiting on you shows under **Needs
+ you**. Turn it on with `mission_board` in settings. API: `docs/mission-control.md`.
+
### Changed
- **Deciding for you costs fewer tokens.** Before deciding a choice itself, a bot now hears at most one
teammate, and only when the choice or an open check names that teammate.
diff --git a/docs/mission-control.md b/docs/mission-control.md
new file mode 100644
index 00000000..3676a618
--- /dev/null
+++ b/docs/mission-control.md
@@ -0,0 +1,287 @@
+# Mission Control + Verified Outcomes (Phase A)
+
+API and data contract of the task board. Field names are stable; changes are additions only.
+
+One task universe: every unit of work (a planned mission task, a team-lead hand-off, a routine run, a
+Loose End taken on, a work-ahead run) is a row in `tasks`. Nothing reaches **verified** on a bot's word.
+
+All times are RFC 3339 UTC strings. All ids are UUID strings unless noted. Every list is space-scoped
+with `?space=<id>` (default space when omitted), like the rest of the API.
+
+---
+
+## 1. Settings (`GET/POST /api/settings`)
+
+| key | type | default | notes |
+|---|---|---|---|
+| `mission_board` | bool | `false` | Shows the board, gives bots the mission tools, auto-creates tasks from hand-offs, routine runs, Loose Ends and work-ahead runs, and runs active missions. Off: routes still answer (read and person actions), bots get no task tools, nothing is auto-created, the runner is idle. |
+| `mission_lease_minutes` | int 5–240 | `30` | How long a claim lives without activity. |
+| `mission_default_budget_tokens` | int 1 000–5 000 000 | `200000` | A mission's budget when none is given. |
+
+Changing settings is person-only (as today). Bots can't change these through `settings_update`.
+
+## 2. States
+
+Task `state` (exactly these strings):
+
+| state | board column | meaning |
+|---|---|---|
+| `backlog` | Ready (dimmed, "waiting on …") | Mission not approved yet, or a dependency isn't verified. |
+| `ready` | Ready | Can be claimed. |
+| `working` | Working | A bot holds a live lease (`claim`). |
+| `needs_you` | Needs you | The owner has an open question card, approval card or human step (`needs_you` lists them). |
+| `review` | Review | Owner says done. Waiting for its checks. `checks_summary.status = "not_checked"` when no check that counts exists and none waits for approval. A check waiting for the person's approval keeps it here and adds a `check_approval` item to `needs_you`. |
+| `verified` | Verified | Every required check that counts has passed, none waits for approval, and at least one isn't the owner's own (see §4). Terminal. |
+| `blocked` | badge | `blocked_reason` says why (owner/person said so, or `budget`). |
+| `failed` | badge | Checks failed `max_attempts` times. The person can retry. |
+| `cancelled` | hidden by default | The person cancelled it, or its mission. Terminal. |
+
+Transitions (enforced in Rust and by SQLite triggers; anything else is refused with 409):
+
+| from → to | who |
+|---|---|
+| backlog → ready | kwant: mission is active and every dependency is `verified` |
+| ready → working | a claim: bot `task_claim`, the mission runner, or a hand-off starting. Needs remaining budget. |
+| working → review | the owner (`task_update {status:"review"}`), or kwant when a hand-off / routine run / work-ahead run finishes |
+| working → ready | the owner releases it, or its lease expires (`attempts` +1) |
+| working ↔ needs_you | kwant only: the owner opened / closed a question, approval or human step |
+| backlog, ready, working, needs_you → blocked | the owner or the person, with a reason; kwant with `budget` |
+| blocked → backlog | the owner or the person (then promoted to ready if it can be) |
+| review → verified | kwant only, when the newest result of every required check passed and at least one passing check is not by the owner |
+| review → ready | a check failed (`attempts` +1, below `max_attempts`), or the person rejects |
+| review → failed | a check failed and `attempts` reached `max_attempts` (default 3) |
+| failed → ready | the person retries |
+| any non-terminal → cancelled | the person |
+
+Mission `status`: `draft` (proposed by a bot, waiting for the person's approval) → `active` → `done`
+(every task is verified or cancelled, at least one verified), or `cancelled`. `over_budget` is a flag,
+not a status.
+
+## 3. Tables
+
+```
+missions(id, space_id, title, goal, status, lead_kwant_id, channel_id?, direct_kwant_id?, thread_id?,
+ workspace_path (server only, not in the API), budget_tokens, spent_tokens, created_by, approved_at?, approved_by?,
+ created_at, updated_at, finished_at?)
+tasks(id, space_id, mission_id?, title, acceptance, state, priority, owner_kwant_id?,
+ suggested_kwant_id?, budget_tokens, spent_tokens, attempts, max_attempts, blocked_reason?,
+ source_kind, source_id?, channel_id?, direct_kwant_id?, thread_id?, created_by,
+ created_at, updated_at, finished_at?)
+task_dependencies(task_id, depends_on_id) -- same mission, no cycles
+task_events(id INTEGER, task_id, mission_id?, kind, actor, from_state?, to_state?, detail JSON,
+ created_at) -- append-only: UPDATE/DELETE abort
+agent_claims(id, task_id, kwant_id, turn_id?, claimed_at, expires_at, released_at?, release_reason?)
+evidence(id, task_id, kind, label, uri?, path?, sha256?, bytes?, excerpt?, captured_by, run_id?,
+ captured_at)
+outcome_checks(id, task_id, kind, spec JSON, required, approved, status, output_excerpt?, checked_by?,
+ requested_by, approved_by?, evidence_id?, created_at, started_at?, finished_at?)
+```
+
+- `priority`: `0` low, `1` normal (default), `2` high, `3` urgent.
+- `source_kind`: `mission` | `person` | `delegation` | `routine` | `zombie` | `work_ahead` | `chat`.
+ `source_id` is the delegation id, routine run id, Loose End case id or work-ahead run id.
+- `actor` / `created_by` / `captured_by` / `checked_by` / `requested_by`: `"person"`, `"kwant"`
+ (kwant itself ran it) or a bot id.
+- Only one live claim per bot at a time, and per task. A claim is live when `released_at` is null and
+ `expires_at` is in the future. Any task tool call by the owner, and every turn of the owner, renews it.
+
+## 4. Outcome checks
+
+`kind` and `spec`:
+
+| kind | spec | passes when | who may add it |
+|---|---|---|---|
+| `command` | `{"command": "cargo test -q", "timeout_secs": 300}` | exit code 0. Runs in the mission's folder with `bash -c`. | The person, or a bot in `mission_plan` (approved with the mission). A bot adding one later gets `approved:false`, and it runs only after the person approves it. |
+| `http` | `{"url": "https://…", "expect_status": 200, "contains": "optional text"}` | GET returns the status (default any 2xx) and the text if given | Anyone. A URL on this computer or a private network needs the person's approval (same rule as WebFetch). |
+| `file_exists` | `{"path": "dist/app.dmg"}` | the file exists inside the mission's folder | Anyone (the task's own bot: see below) |
+| `file_contains` | `{"path": "CHANGELOG.md", "text": "0.1.4"}` | the file contains the text | Anyone |
+| `file_sha256` | `{"path": "out.zip", "sha256": "…"}` | the hash matches | Anyone |
+| `peer_review` | `{"note": "…", "evidence_ids": ["…"]}` | a bot that is **not the owner** gives `pass` and cites at least one evidence item | Recorded by `task_review` |
+| `person` | `{"note": "…"}` | the person pressed Verify | `POST /api/tasks/:id/verify` |
+
+- Paths are relative to the mission's folder (the team's workspace when the mission came from a team
+ chat, else the lead bot's folder). `..`, absolute paths outside it, symlinks out of it and
+ password/key files are refused.
+- `status`: `pending` | `needs_approval` | `running` | `passed` | `failed` | `error` (couldn't run, e.g.
+ a timeout; counts as not passed). `output_excerpt` is at most 2 000 chars, with secrets left as the
+ command printed them, so commands that print secrets are the person's responsibility.
+- kwant runs `command`, `http` and `file_*` checks itself (`checked_by: "kwant"`) and stores the output
+ as evidence (`kind: "check_output"`).
+- `approved_by`: who let the check run and count. `"person"` (the person added it, approved it, or
+ made the mission), `"mission"` (part of a bot's `mission_plan` that the person approved), `"auto"` (a
+ safe check a bot other than the owner added), or `null` while `status = "needs_approval"`.
+- **The owner's own checks.** A check the task's owner (or suggested owner) adds with
+ `task_request_check` always starts as `approved: false`, `status: "needs_approval"`, even a
+ `file_*` check, so a bot can't verify itself with "the file I just wrote exists". It runs and counts
+ only after the person approves it (`approved_by: "person"`). A check whose requester later became the
+ owner counts only if `approved_by` is `"person"` or `"mission"`.
+- `counts` (on each Check in the API): whether this check can count toward Verified under those rules.
+- `required` (default `true`): **every** required check must count and its newest result must be
+ `passed`. A required check that is `failed`/`error` sends the task back (`ready`, or `failed` after
+ `max_attempts`). A required check that is `pending`/`running`, or waits for approval, keeps the task
+ in `review`; one waiting for approval also shows as a `check_approval` item in the task's
+ `needs_you` and counts in Insights `needs_you_now`. The person's own Verify (a passed `person`
+ check) doesn't wait for unapproved checks, but approved checks still have to pass. Optional checks
+ (`required: false`) are shown but never hold, fail or verify a task.
+- A task with no checks stays in `review` ("not checked") until a peer review or the person verifies it.
+
+`checks_summary` on each task: `{"status": "not_checked" | "pending" | "passed" | "failed",
+"passed": n, "failed": n, "needs_approval": n, "total": n}`. `passed`/`failed` count checks that
+count; `needs_approval` counts checks waiting for the person. `status` is `passed` only when the task
+could be verified on them, and `pending` while a required check waits for approval (an optional
+one waiting is counted in `needs_approval` but doesn't hold the task).
+
+## 5. Bot tools (MCP self tools; only while `mission_board` is on)
+
+| tool | args | result / rules |
+|---|---|---|
+| `mission_plan` | `{title, goal, budget_tokens?, tasks: [{key, title, acceptance, owner?, priority?, depends_on?: [key], budget_tokens?, checks?: [{kind, spec, required?}]}]}` | Creates a **draft** mission led by the caller, with up to 30 tasks in `backlog`. The person approves it once (card in chat + board). Nothing runs until then. Owners are bots in the same space. |
+| `task_list` | `{mission_id?, state?, mine?}` | Read-only. Tasks in the caller's space. |
+| `task_claim` | `{task_id}` | Atomic: `ready` → `working` with a lease. Refused if someone else holds it, a dependency isn't verified, the mission isn't active, the remaining budget can't cover the task's budget, or the caller already holds another live claim. |
+| `task_update` | `{task_id, status?: "review" \| "ready" \| "blocked", note?, reason?}` | Owner only, with a live claim. `review` = I'm done (releases the lease and runs the task's checks now). `ready` = release. `blocked` needs `reason`. A `note` alone renews the lease and is logged. Can never set `verified`. |
+| `task_attach_evidence` | `{task_id, kind: "file" \| "url" \| "note" \| "screenshot", label, path?, url?, text?}` | Records evidence. For files kwant reads the file itself and stores `sha256` and `bytes` (the bot's own hash is ignored). Evidence alone never verifies anything. |
+| `task_request_check` | `{task_id, check_id?, kind?, spec?, required?}` | Runs the task's approved checks (or one), or adds a new check and runs it if it may run. Returns each result. |
+| `task_review` | `{task_id, verdict: "pass" \| "fail", evidence_ids: [..], note}` | A teammate's review. Refused for the owner. `pass` needs at least one evidence id on that task. |
+
+The self-tools approver treats `task_list` as read-only. All other tools change only the task board,
+never files, messages or money, so they don't ask for a card. Turns keep their normal approval mode.
+Sending, paying, deleting, publishing and sign-ins still ask as today.
+
+## 6. HTTP routes
+
+Reads (`GET`) are open like the rest of the app API. Every non-GET route below is **person-only**
+(`auth.rs`), so bot tokens get 403.
+
+```
+GET /api/missions?space=&status= -> {missions: [Mission]}
+POST /api/missions -> Mission (person creates; active at once)
+GET /api/missions/insights?space= -> Insights
+GET /api/missions/:id -> MissionDetail
+PATCH /api/missions/:id {title?, goal?, budget_tokens?}
+POST /api/missions/:id/approve -> Mission (draft -> active)
+POST /api/missions/:id/cancel -> Mission
+POST /api/missions/:id/run {max_tasks?: 1-5} -> {started: [{task_id, kwant_id}], reason?} (test hook / "Run now")
+
+GET /api/tasks?space=&state=&mission_id=&source_kind=&limit= -> {tasks: [Task]}
+POST /api/tasks {title, acceptance?, mission_id?, owner_kwant_id?, priority?, depends_on?, budget_tokens?,
+ checks?, source_kind?: "person"|"zombie", source_id?} -> Task
+GET /api/tasks/:id -> TaskDetail
+PATCH /api/tasks/:id {title?, acceptance?, priority?, owner_kwant_id?, budget_tokens?}
+POST /api/tasks/:id/verify {note?} -> Task (review -> verified, a `person` check)
+POST /api/tasks/:id/reject {reason} -> Task (review -> ready)
+POST /api/tasks/:id/block {reason} -> Task
+POST /api/tasks/:id/unblock -> Task
+POST /api/tasks/:id/retry -> Task (failed -> ready)
+POST /api/tasks/:id/cancel -> Task
+POST /api/tasks/:id/checks {kind, spec, required?} -> Check (approved, runs if the task is in review)
+POST /api/tasks/:id/checks/run -> {checks: [Check], task: Task}
+POST /api/checks/:id/approve -> Check (needs_approval -> runs)
+```
+
+Errors: `{"error": "plain sentence"}` with 400 (bad input), 404, 409 (illegal transition, budget,
+claim conflict), 403 (bot token on a person route).
+
+### Shapes
+
+```jsonc
+// Mission
+{"id","space_id","title","goal","status","lead_kwant_id","lead_name",
+ "channel_id","direct_kwant_id","thread_id",
+ "budget_tokens","spent_tokens","reserved_tokens","over_budget": false,
+ // no workspace_path: the folder stays on the server (checks and evidence paths are relative to it)
+ "created_by","approved_at","approved_by","created_at","updated_at","finished_at",
+ "counts": {"backlog":0,"ready":0,"working":0,"needs_you":0,"review":0,"verified":0,"blocked":0,"failed":0,"cancelled":0}}
+
+// Task
+{"id","space_id","mission_id","mission_title","title","acceptance","state","priority",
+ "owner_kwant_id","owner_name","suggested_kwant_id","budget_tokens","spent_tokens",
+ "attempts","max_attempts","blocked_reason","source_kind","source_id",
+ "channel_id","direct_kwant_id","thread_id","created_by","created_at","updated_at","finished_at",
+ "depends_on": ["task id"], "waiting_on": ["task id not verified yet"],
+ "claim": null | {"kwant_id","claimed_at","expires_at"},
+ "needs_you": [{"kind": "question"|"approval"|"human_step"|"check_approval", "id", "text"}],
+ "checks_summary": {"status","passed","failed","needs_approval","total"}}
+// needs_you: question/approval/human_step while working or needs_you; check_approval (id = the
+// check's id, approve it with POST /api/checks/:id/approve) while in review
+
+// TaskDetail = {"task": Task, "checks": [Check], "evidence": [Evidence], "events": [Event]} (events oldest first, max 500)
+// MissionDetail = {"mission": Mission, "tasks": [Task]}
+
+// Check
+{"id","task_id","kind","spec","required","approved","approved_by","counts","status","output_excerpt",
+ "checked_by","checked_by_name","requested_by","evidence_id","created_at","started_at","finished_at"}
+
+// Evidence
+{"id","task_id","kind","label","uri","path","sha256","bytes","excerpt","captured_by","run_id","captured_at"}
+// kind: "file" | "url" | "note" | "screenshot" | "check_output"
+
+// Event
+{"id": 42, "task_id","mission_id","kind","actor","actor_name","from_state","to_state","detail": {}, "created_at"}
+// kind: created | state | claimed | released | lease_expired | note | evidence | check_added |
+// check_started | check_result | review | budget | edited
+
+// Insights (counts, last 7 days unless noted)
+{"verified_7d": 0, "false_success_7d": 0, "needs_you_now": 0, "blocked_now": 0, "blocked_minutes_7d": 0,
+ "interventions_7d": 0, "tokens_7d": 0, "tokens_per_verified_7d": null}
+```
+
+`false_success_7d` counts tasks whose owner moved them to `review` and whose next check result was
+`failed`. `interventions_7d` counts person actions on tasks (verify, reject, block, unblock, retry,
+cancel, check approval).
+
+## 7. Live events (SSE `/api/events`)
+
+```
+{"type": "task_updated", "space_id": "…", "data": {"task": Task}}
+{"type": "mission_updated", "space_id": "…", "data": {"mission": Mission}}
+```
+
+Sent on every change. The board can patch its list from `data` or refetch. The chat also gets a short
+kwant line (`meta.kind = "mission"`) in the mission's chat when a mission is proposed, approved or done,
+and when a task is verified or failed.
+
+## 8. Where tasks come from (one task universe, only while `mission_board` is on)
+
+| source | created when | state |
+|---|---|---|
+| `mission` | `mission_plan` / `POST /api/missions` | backlog → ready after approval |
+| `person` | `POST /api/tasks` | ready (backlog if it has unverified deps) |
+| `delegation` | a team lead hands work on (`delegate` tool or @mention in a team chat) | working (kwant holds the specialist's lease) → review when the hand-off completes, failed if it fails, cancelled if cancelled. Inside a mission task, it joins that mission. |
+| `routine` | a routine run starts | working → review when it completes, failed if it fails |
+| `zombie` | the person takes a Loose End on (`POST /api/tasks {source_kind:"zombie", source_id}`), or kwant starts its owner turn | ready, or working while the owner turn runs |
+| `work_ahead` | a work-ahead run posts its message | review |
+
+"Needs you" reuses the existing question, approval and human-step cards. The board links to them. It
+doesn't create its own cards.
+
+## 9. Mission runner
+
+While `mission_board` is on, every scheduler tick (and `POST /api/missions/:id/run`) looks at active
+missions. Each mission gets at most one runner turn at a time, server-wide at most 2. The runner picks
+the highest-priority `ready` task, claims it for its owner (or suggested owner, else the lead) and runs
+one hidden turn in the mission's chat with the task, its acceptance criteria and checks. At the end
+of every turn its fresh tokens go to the task and the mission: the task the bot holds, or the one it
+claimed or let go of during that turn (`task_update review` releases the claim before the turn ends,
+and the turn still pays for itself). When the turn ends and the task is still `working`, the
+lease is released (`ready`, attempt +1).
+
+Budget: a claim needs `spent + reserved + task budget ≤ mission budget`, where `reserved` is what
+working tasks may still spend. After every turn the tokens are added. A task over its own budget is
+blocked (`budget`). A mission at or over its budget gets `over_budget: true`, and no new claims start
+until the person raises the budget. One turn already running can overshoot by what that turn uses,
+because kwant counts tokens when a model call returns.
+
+## 10. Implementation notes
+
+- `agent_claims` also has `context_id` (the chat the claim's turns run in; spend goes to the claim
+ whose context matches the turn) and `system` (1 = kwant holds it for a hand-off or routine run; it
+ doesn't count as the bot's own live claim, so the bot can still claim its own task).
+- `working`/`needs_you` → `failed`: kwant, when a hand-off or routine run fails. `working`/`needs_you`
+ → `cancelled`: also kwant, when a hand-off is cancelled.
+- Event kind `released` is used when a runner turn ends with the task still `working` (`attempts` +1).
+ If that was the last attempt, kwant then moves it `ready` → `blocked`.
+- `POST /api/tasks/:id/retry` resets `attempts` to 0.
+- `POST /api/missions` also takes `tasks` (same shape as `mission_plan` tasks) and `lead_kwant_id`,
+ `channel_id`, `thread_id`. A command check in a person-created mission is approved at once.
+- Not in Phase A: a plain @mention hand-off creates a task only when it goes through the delegation
+ machinery; a Loose End's own owner turn doesn't create a `zombie` task (the person taking it on does).
diff --git a/src/db/missions.rs b/src/db/missions.rs
new file mode 100644
index 00000000..d91c6c82
--- /dev/null
+++ b/src/db/missions.rs
@@ -0,0 +1,1176 @@
+//! Mission Control: missions, the one `tasks` table every kind of work lands in, their
+//! dependencies, claims (leases), evidence, outcome checks and the append-only `task_events` log.
+//! Contract: docs/mission-control.md. The rules that matter are enforced twice: in
+//! [`crate::server::missions`] and by SQLite triggers here, so no code path (or a stray UPDATE) can
+//! verify a task on its owner's word, start work without a live lease, make a task ready before its
+//! dependencies are verified, or rewrite the event log.
+
+use super::spaces::SpaceId;
+use super::{Database, DbError};
+use chrono::{DateTime, TimeZone, Utc};
+use serde::Serialize;
+use serde_json::Value;
+use sqlx::FromRow;
+use uuid::Uuid;
+
+pub const TASK_STATES: [&str; 9] = ["backlog", "ready", "working", "needs_you", "review", "verified", "blocked", "failed", "cancelled"];
+pub const MISSION_STATUSES: [&str; 4] = ["draft", "active", "done", "cancelled"];
+pub const SOURCE_KINDS: [&str; 7] = ["mission", "person", "delegation", "routine", "zombie", "work_ahead", "chat"];
+pub const CHECK_KINDS: [&str; 7] = ["command", "http", "file_exists", "file_contains", "file_sha256", "peer_review", "person"];
+/// Checks kwant runs itself (the rest are recorded by a teammate or the person).
+pub const KWANT_CHECK_KINDS: [&str; 5] = ["command", "http", "file_exists", "file_contains", "file_sha256"];
+/// States a task can't leave.
+pub const TERMINAL: [&str; 2] = ["verified", "cancelled"];
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct Mission {
+ pub id: String,
+ pub space_id: String,
+ pub title: String,
+ pub goal: String,
+ pub status: String,
+ pub lead_kwant_id: String,
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ pub workspace_path: String,
+ pub budget_tokens: i64,
+ pub spent_tokens: i64,
+ pub created_by: String,
+ pub approved_at: Option<DateTime<Utc>>,
+ pub approved_by: Option<String>,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+ pub finished_at: Option<DateTime<Utc>>,
+}
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct Task {
+ pub id: String,
+ pub space_id: String,
+ pub mission_id: Option<String>,
+ pub title: String,
+ pub acceptance: String,
+ pub state: String,
+ pub priority: i64,
+ pub owner_kwant_id: Option<String>,
+ pub suggested_kwant_id: Option<String>,
+ pub budget_tokens: i64,
+ pub spent_tokens: i64,
+ pub attempts: i64,
+ pub max_attempts: i64,
+ pub blocked_reason: Option<String>,
+ pub source_kind: String,
+ pub source_id: Option<String>,
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ pub created_by: String,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+ pub finished_at: Option<DateTime<Utc>>,
+}
+
+/// A lease on a task. Times are unix milliseconds so the SQLite triggers can compare them.
+#[derive(Debug, Clone, FromRow, PartialEq)]
+pub struct Claim {
+ pub id: String,
+ pub task_id: String,
+ pub kwant_id: String,
+ pub turn_id: Option<String>,
+ /// The chat whose turns spend on this task; `None` = any turn of the bot.
+ pub context_id: Option<String>,
+ /// Held by kwant for a hand-off or routine run, not taken by the bot itself.
+ pub system: bool,
+ pub claimed_at: i64,
+ pub expires_at: i64,
+ pub released_at: Option<i64>,
+ pub release_reason: Option<String>,
+}
+
+impl Claim {
+ pub fn claimed_at_utc(&self) -> DateTime<Utc> {
+ ms_to_utc(self.claimed_at)
+ }
+ pub fn expires_at_utc(&self) -> DateTime<Utc> {
+ ms_to_utc(self.expires_at)
+ }
+}
+
+pub fn ms_to_utc(ms: i64) -> DateTime<Utc> {
+ Utc.timestamp_millis_opt(ms).single().unwrap_or_else(Utc::now)
+}
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct Evidence {
+ pub id: String,
+ pub task_id: String,
+ pub kind: String,
+ pub label: String,
+ pub uri: Option<String>,
+ pub path: Option<String>,
+ pub sha256: Option<String>,
+ pub bytes: Option<i64>,
+ pub excerpt: Option<String>,
+ pub captured_by: String,
+ pub run_id: Option<String>,
+ pub captured_at: DateTime<Utc>,
+}
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct OutcomeCheck {
+ pub id: String,
+ pub task_id: String,
+ pub kind: String,
+ /// JSON text; see [`OutcomeCheck::spec_value`].
+ #[serde(skip)]
+ pub spec: String,
+ pub required: bool,
+ pub approved: bool,
+ pub status: String,
+ pub output_excerpt: Option<String>,
+ pub checked_by: Option<String>,
+ pub requested_by: String,
+ /// Who let it run and count: `person` (added or approved by the person), `mission` (part of a
+ /// plan the person approved), `auto` (a safe check a bot other than the owner added), or
+ /// `None` while it waits for approval.
+ pub approved_by: Option<String>,
+ pub evidence_id: Option<String>,
+ pub created_at: DateTime<Utc>,
+ pub started_at: Option<DateTime<Utc>>,
+ pub finished_at: Option<DateTime<Utc>>,
+}
+
+impl OutcomeCheck {
+ pub fn spec_value(&self) -> Value {
+ serde_json::from_str(&self.spec).unwrap_or(Value::Null)
+ }
+}
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct TaskEvent {
+ pub id: i64,
+ pub task_id: String,
+ pub mission_id: Option<String>,
+ pub kind: String,
+ pub actor: String,
+ pub from_state: Option<String>,
+ pub to_state: Option<String>,
+ #[serde(skip)]
+ pub detail: String,
+ pub created_at: DateTime<Utc>,
+}
+
+impl TaskEvent {
+ pub fn detail_value(&self) -> Value {
+ serde_json::from_str(&self.detail).unwrap_or(Value::Null)
+ }
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct NewMission {
+ pub title: String,
+ pub goal: String,
+ pub status: String,
+ pub lead_kwant_id: String,
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ pub workspace_path: String,
+ pub budget_tokens: i64,
+ pub created_by: String,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct NewTask {
+ pub mission_id: Option<String>,
+ pub title: String,
+ pub acceptance: String,
+ pub state: String,
+ pub priority: i64,
+ pub owner_kwant_id: Option<String>,
+ pub suggested_kwant_id: Option<String>,
+ pub budget_tokens: i64,
+ pub max_attempts: i64,
+ pub source_kind: String,
+ pub source_id: Option<String>,
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ pub created_by: String,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct NewCheck {
+ pub task_id: String,
+ pub kind: String,
+ pub spec: Value,
+ pub required: bool,
+ pub approved: bool,
+ pub requested_by: String,
+ /// See [`OutcomeCheck::approved_by`]; ignored unless `approved`.
+ pub approved_by: Option<String>,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct NewEvidence {
+ pub task_id: String,
+ pub kind: String,
+ pub label: String,
+ pub uri: Option<String>,
+ pub path: Option<String>,
+ pub sha256: Option<String>,
+ pub bytes: Option<i64>,
+ pub excerpt: Option<String>,
+ pub captured_by: String,
+ pub run_id: Option<String>,
+}
+
+/// Why a claim was refused.
+#[derive(Debug, Clone, PartialEq)]
+pub enum ClaimRefused {
+ NotReady(String),
+ Held,
+ BotBusy(String),
+ Budget { remaining: i64, needed: i64 },
+ MissionNotActive,
+ Missing,
+}
+
+impl std::fmt::Display for ClaimRefused {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ ClaimRefused::NotReady(state) => write!(f, "the task is {state}, not ready"),
+ ClaimRefused::Held => write!(f, "someone else holds this task"),
+ ClaimRefused::BotBusy(task) => write!(f, "you already hold task {task}; finish or release it first"),
+ ClaimRefused::Budget { remaining, needed } => {
+ write!(f, "the mission's budget can't cover it: {remaining} tokens left, the task needs {needed}")
+ }
+ ClaimRefused::MissionNotActive => write!(f, "the mission isn't approved and active"),
+ ClaimRefused::Missing => write!(f, "no such task"),
+ }
+ }
+}
+
+pub fn now_ms() -> i64 {
+ Utc::now().timestamp_millis()
+}
+
+const TRIGGERS: [&str; 8] = [
+ // The log is history: nothing rewrites or removes it
+ "CREATE TRIGGER IF NOT EXISTS task_events_append_only_update BEFORE UPDATE ON task_events \
+ BEGIN SELECT RAISE(ABORT, 'task_events is append-only'); END",
+ "CREATE TRIGGER IF NOT EXISTS task_events_append_only_delete BEFORE DELETE ON task_events \
+ BEGIN SELECT RAISE(ABORT, 'task_events is append-only'); END",
+ // Verified only through a passing, approved check that isn't the owner's
+ "CREATE TRIGGER IF NOT EXISTS tasks_verified_needs_check BEFORE UPDATE OF state ON tasks \
+ WHEN NEW.state = 'verified' AND OLD.state != 'verified' AND NOT EXISTS ( \
+ SELECT 1 FROM outcome_checks c WHERE c.task_id = NEW.id AND c.status = 'passed' AND c.approved = 1 \
+ AND c.checked_by IS NOT NULL AND c.checked_by != COALESCE(NEW.owner_kwant_id, '')) \
+ BEGIN SELECT RAISE(ABORT, 'a task is verified only by a passing check that is not its owner''s'); END",
+ "CREATE TRIGGER IF NOT EXISTS tasks_insert_not_verified BEFORE INSERT ON tasks \
+ WHEN NEW.state IN ('verified', 'working', 'needs_you') \
+ BEGIN SELECT RAISE(ABORT, 'a new task starts before work'); END",
+ // Working only with a live lease
+ "CREATE TRIGGER IF NOT EXISTS tasks_working_needs_lease BEFORE UPDATE OF state ON tasks \
+ WHEN NEW.state = 'working' AND NOT EXISTS ( \
+ SELECT 1 FROM agent_claims a WHERE a.task_id = NEW.id AND a.released_at IS NULL \
+ AND a.expires_at > CAST(strftime('%s', 'now') AS INTEGER) * 1000) \
+ BEGIN SELECT RAISE(ABORT, 'a task is worked on only under a live lease'); END",
+ // Ready only when every dependency is verified and the mission is active
+ "CREATE TRIGGER IF NOT EXISTS tasks_ready_needs_deps BEFORE UPDATE OF state ON tasks \
+ WHEN NEW.state = 'ready' AND (EXISTS ( \
+ SELECT 1 FROM task_dependencies d JOIN tasks t ON t.id = d.depends_on_id \
+ WHERE d.task_id = NEW.id AND t.state != 'verified') \
+ OR EXISTS (SELECT 1 FROM missions m WHERE m.id = NEW.mission_id AND m.status != 'active')) \
+ BEGIN SELECT RAISE(ABORT, 'a task is ready only when its mission is active and its dependencies are verified'); END",
+ "CREATE TRIGGER IF NOT EXISTS tasks_insert_ready_needs_mission BEFORE INSERT ON tasks \
+ WHEN NEW.state = 'ready' AND EXISTS (SELECT 1 FROM missions m WHERE m.id = NEW.mission_id AND m.status != 'active') \
+ BEGIN SELECT RAISE(ABORT, 'a task is ready only when its mission is active'); END",
+ // Terminal states stay terminal
+ "CREATE TRIGGER IF NOT EXISTS tasks_terminal BEFORE UPDATE OF state ON tasks \
+ WHEN OLD.state IN ('verified', 'cancelled') AND NEW.state != OLD.state \
+ BEGIN SELECT RAISE(ABORT, 'a verified or cancelled task is final'); END",
+];
+
+impl Database {
+ pub(super) async fn migrate_missions(&self) -> Result<(), DbError> {
+ for stmt in [
+ "CREATE TABLE IF NOT EXISTS missions (
+ id TEXT PRIMARY KEY,
+ space_id TEXT NOT NULL,
+ title TEXT NOT NULL,
+ goal TEXT NOT NULL DEFAULT '',
+ status TEXT NOT NULL CHECK (status IN ('draft', 'active', 'done', 'cancelled')),
+ lead_kwant_id TEXT NOT NULL,
+ channel_id TEXT,
+ direct_kwant_id TEXT,
+ thread_id TEXT,
+ workspace_path TEXT NOT NULL DEFAULT '',
+ budget_tokens INTEGER NOT NULL CHECK (budget_tokens > 0),
+ spent_tokens INTEGER NOT NULL DEFAULT 0,
+ created_by TEXT NOT NULL,
+ approved_at TIMESTAMP,
+ approved_by TEXT,
+ created_at TIMESTAMP NOT NULL,
+ updated_at TIMESTAMP NOT NULL,
+ finished_at TIMESTAMP
+ )",
+ "CREATE INDEX IF NOT EXISTS missions_space ON missions (space_id, status)",
+ "CREATE TABLE IF NOT EXISTS tasks (
+ id TEXT PRIMARY KEY,
+ space_id TEXT NOT NULL,
+ mission_id TEXT REFERENCES missions(id),
+ title TEXT NOT NULL,
+ acceptance TEXT NOT NULL DEFAULT '',
+ state TEXT NOT NULL CHECK (state IN ('backlog', 'ready', 'working', 'needs_you', 'review', 'verified', 'blocked', 'failed', 'cancelled')),
+ priority INTEGER NOT NULL DEFAULT 1 CHECK (priority BETWEEN 0 AND 3),
+ owner_kwant_id TEXT,
+ suggested_kwant_id TEXT,
+ budget_tokens INTEGER NOT NULL CHECK (budget_tokens > 0),
+ spent_tokens INTEGER NOT NULL DEFAULT 0,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ max_attempts INTEGER NOT NULL DEFAULT 3,
+ blocked_reason TEXT,
+ source_kind TEXT NOT NULL CHECK (source_kind IN ('mission', 'person', 'delegation', 'routine', 'zombie', 'work_ahead', 'chat')),
+ source_id TEXT,
+ channel_id TEXT,
+ direct_kwant_id TEXT,
+ thread_id TEXT,
+ created_by TEXT NOT NULL,
+ created_at TIMESTAMP NOT NULL,
+ updated_at TIMESTAMP NOT NULL,
+ finished_at TIMESTAMP
+ )",
+ "CREATE INDEX IF NOT EXISTS tasks_space_state ON tasks (space_id, state)",
+ "CREATE INDEX IF NOT EXISTS tasks_mission ON tasks (mission_id)",
+ "CREATE INDEX IF NOT EXISTS tasks_source ON tasks (source_kind, source_id)",
+ "CREATE TABLE IF NOT EXISTS task_dependencies (
+ task_id TEXT NOT NULL REFERENCES tasks(id),
+ depends_on_id TEXT NOT NULL REFERENCES tasks(id),
+ PRIMARY KEY (task_id, depends_on_id),
+ CHECK (task_id != depends_on_id)
+ )",
+ "CREATE TABLE IF NOT EXISTS task_events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ task_id TEXT NOT NULL,
+ mission_id TEXT,
+ kind TEXT NOT NULL,
+ actor TEXT NOT NULL,
+ from_state TEXT,
+ to_state TEXT,
+ detail TEXT NOT NULL DEFAULT '{}',
+ created_at TIMESTAMP NOT NULL
+ )",
+ "CREATE INDEX IF NOT EXISTS task_events_task ON task_events (task_id, id)",
+ "CREATE TABLE IF NOT EXISTS agent_claims (
+ id TEXT PRIMARY KEY,
+ task_id TEXT NOT NULL REFERENCES tasks(id),
+ kwant_id TEXT NOT NULL,
+ turn_id TEXT,
+ context_id TEXT,
+ system INTEGER NOT NULL DEFAULT 0,
+ claimed_at INTEGER NOT NULL,
+ expires_at INTEGER NOT NULL,
+ released_at INTEGER,
+ release_reason TEXT
+ )",
+ // One open claim per task, and per bot for the claims a bot takes itself
+ "CREATE UNIQUE INDEX IF NOT EXISTS agent_claims_one_per_task ON agent_claims (task_id) WHERE released_at IS NULL",
+ "CREATE UNIQUE INDEX IF NOT EXISTS agent_claims_one_per_bot ON agent_claims (kwant_id) WHERE released_at IS NULL AND system = 0",
+ "CREATE TABLE IF NOT EXISTS evidence (
+ id TEXT PRIMARY KEY,
+ task_id TEXT NOT NULL REFERENCES tasks(id),
+ kind TEXT NOT NULL CHECK (kind IN ('file', 'url', 'note', 'screenshot', 'check_output')),
+ label TEXT NOT NULL,
+ uri TEXT,
+ path TEXT,
+ sha256 TEXT,
+ bytes INTEGER,
+ excerpt TEXT,
+ captured_by TEXT NOT NULL,
+ run_id TEXT,
+ captured_at TIMESTAMP NOT NULL
+ )",
+ "CREATE INDEX IF NOT EXISTS evidence_task ON evidence (task_id)",
+ "CREATE TABLE IF NOT EXISTS outcome_checks (
+ id TEXT PRIMARY KEY,
+ task_id TEXT NOT NULL REFERENCES tasks(id),
+ kind TEXT NOT NULL CHECK (kind IN ('command', 'http', 'file_exists', 'file_contains', 'file_sha256', 'peer_review', 'person')),
+ spec TEXT NOT NULL,
+ required INTEGER NOT NULL DEFAULT 1,
+ approved INTEGER NOT NULL DEFAULT 1,
+ status TEXT NOT NULL CHECK (status IN ('pending', 'needs_approval', 'running', 'passed', 'failed', 'error')),
+ output_excerpt TEXT,
+ checked_by TEXT,
+ requested_by TEXT NOT NULL,
+ approved_by TEXT,
+ evidence_id TEXT,
+ created_at TIMESTAMP NOT NULL,
+ started_at TIMESTAMP,
+ finished_at TIMESTAMP
+ )",
+ "CREATE INDEX IF NOT EXISTS outcome_checks_task ON outcome_checks (task_id)",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ for t in TRIGGERS {
+ sqlx::query(t).execute(&self.pool).await?;
+ }
+ // A restart stops every check that was running
+ sqlx::query("UPDATE outcome_checks SET status = 'error', output_excerpt = 'kwnt restarted while the check ran', finished_at = ? WHERE status = 'running'")
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ // Missions
+
+ pub async fn create_mission(&self, space: &SpaceId, m: &NewMission) -> Result<Mission, DbError> {
+ let now = Utc::now();
+ let approved = m.status == "active";
+ Ok(sqlx::query_as::<_, Mission>(
+ "INSERT INTO missions (id, space_id, title, goal, status, lead_kwant_id, channel_id, direct_kwant_id, thread_id, \
+ workspace_path, budget_tokens, created_by, approved_at, approved_by, created_at, updated_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *",
+ )
+ .bind(Uuid::new_v4().to_string())
+ .bind(space.as_str())
+ .bind(&m.title)
+ .bind(&m.goal)
+ .bind(&m.status)
+ .bind(&m.lead_kwant_id)
+ .bind(&m.channel_id)
+ .bind(&m.direct_kwant_id)
+ .bind(&m.thread_id)
+ .bind(&m.workspace_path)
+ .bind(m.budget_tokens)
+ .bind(&m.created_by)
+ .bind(approved.then_some(now))
+ .bind(approved.then(|| m.created_by.clone()))
+ .bind(now)
+ .bind(now)
+ .fetch_one(&self.pool)
+ .await?)
+ }
+
+ pub async fn get_mission(&self, id: &str) -> Result<Option<Mission>, DbError> {
+ Ok(sqlx::query_as::<_, Mission>("SELECT * FROM missions WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)
+ }
+
+ pub async fn list_missions(&self, space: &SpaceId, status: Option<&str>) -> Result<Vec<Mission>, DbError> {
+ Ok(sqlx::query_as::<_, Mission>(
+ "SELECT * FROM missions WHERE space_id = ? AND (? IS NULL OR status = ?) ORDER BY created_at DESC, rowid DESC LIMIT 200",
+ )
+ .bind(space.as_str())
+ .bind(status)
+ .bind(status)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ pub async fn active_missions(&self) -> Result<Vec<Mission>, DbError> {
+ Ok(sqlx::query_as::<_, Mission>("SELECT * FROM missions WHERE status = 'active' ORDER BY created_at")
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Moves a mission from `from` to `to`; false when it wasn't in `from`.
+ pub async fn set_mission_status(&self, id: &str, from: &str, to: &str, by: Option<&str>) -> Result<bool, DbError> {
+ let now = Utc::now();
+ let done = matches!(to, "done" | "cancelled");
+ let r = sqlx::query(
+ "UPDATE missions SET status = ?, updated_at = ?, \
+ approved_at = CASE WHEN ? = 'active' THEN ? ELSE approved_at END, \
+ approved_by = CASE WHEN ? = 'active' THEN ? ELSE approved_by END, \
+ finished_at = CASE WHEN ? THEN ? ELSE finished_at END \
+ WHERE id = ? AND status = ?",
+ )
+ .bind(to)
+ .bind(now)
+ .bind(to)
+ .bind(now)
+ .bind(to)
+ .bind(by)
+ .bind(done)
+ .bind(now)
+ .bind(id)
+ .bind(from)
+ .execute(&self.pool)
+ .await?;
+ Ok(r.rows_affected() == 1)
+ }
+
+ pub async fn edit_mission(&self, id: &str, title: Option<&str>, goal: Option<&str>, budget: Option<i64>) -> Result<bool, DbError> {
+ let r = sqlx::query(
+ "UPDATE missions SET title = COALESCE(?, title), goal = COALESCE(?, goal), budget_tokens = COALESCE(?, budget_tokens), \
+ updated_at = ? WHERE id = ?",
+ )
+ .bind(title)
+ .bind(goal)
+ .bind(budget)
+ .bind(Utc::now())
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(r.rows_affected() == 1)
+ }
+
+ /// Tokens working tasks of the mission may still spend (their budget minus what they spent).
+ pub async fn mission_reserved(&self, mission_id: &str) -> Result<i64, DbError> {
+ let (n,): (i64,) = sqlx::query_as(
+ "SELECT COALESCE(SUM(MAX(budget_tokens - spent_tokens, 0)), 0) FROM tasks \
+ WHERE mission_id = ? AND state IN ('working', 'needs_you')",
+ )
+ .bind(mission_id)
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(n)
+ }
+
+ pub async fn mission_counts(&self, mission_id: &str) -> Result<Vec<(String, i64)>, DbError> {
+ Ok(sqlx::query_as("SELECT state, COUNT(*) FROM tasks WHERE mission_id = ? GROUP BY state")
+ .bind(mission_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ // Tasks
+
+ pub async fn create_task(&self, space: &SpaceId, t: &NewTask) -> Result<Task, DbError> {
+ let now = Utc::now();
+ let mut tx = self.pool.begin().await?;
+ let task = sqlx::query_as::<_, Task>(
+ "INSERT INTO tasks (id, space_id, mission_id, title, acceptance, state, priority, owner_kwant_id, suggested_kwant_id, \
+ budget_tokens, max_attempts, source_kind, source_id, channel_id, direct_kwant_id, thread_id, created_by, created_at, updated_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *",
+ )
+ .bind(Uuid::new_v4().to_string())
+ .bind(space.as_str())
+ .bind(&t.mission_id)
+ .bind(&t.title)
+ .bind(&t.acceptance)
+ .bind(&t.state)
+ .bind(t.priority)
+ .bind(&t.owner_kwant_id)
+ .bind(&t.suggested_kwant_id)
+ .bind(t.budget_tokens)
+ .bind(t.max_attempts.max(1))
+ .bind(&t.source_kind)
+ .bind(&t.source_id)
+ .bind(&t.channel_id)
+ .bind(&t.direct_kwant_id)
+ .bind(&t.thread_id)
+ .bind(&t.created_by)
+ .bind(now)
+ .bind(now)
+ .fetch_one(&mut *tx)
+ .await?;
+ insert_event(&mut tx, &task.id, task.mission_id.as_deref(), "created", &t.created_by, None, Some(&task.state), &serde_json::json!({"source_kind": t.source_kind, "source_id": t.source_id})).await?;
+ tx.commit().await?;
+ Ok(task)
+ }
+
+ pub async fn get_task(&self, id: &str) -> Result<Option<Task>, DbError> {
+ Ok(sqlx::query_as::<_, Task>("SELECT * FROM tasks WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)
+ }
+
+ pub async fn task_by_source(&self, kind: &str, source_id: &str) -> Result<Option<Task>, DbError> {
+ Ok(sqlx::query_as::<_, Task>("SELECT * FROM tasks WHERE source_kind = ? AND source_id = ? ORDER BY created_at DESC LIMIT 1")
+ .bind(kind)
+ .bind(source_id)
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ pub async fn list_tasks(
+ &self,
+ space: &SpaceId,
+ state: Option<&str>,
+ mission_id: Option<&str>,
+ source_kind: Option<&str>,
+ limit: i64,
+ ) -> Result<Vec<Task>, DbError> {
+ Ok(sqlx::query_as::<_, Task>(
+ "SELECT * FROM tasks WHERE space_id = ? AND (? IS NULL OR state = ?) AND (? IS NULL OR mission_id = ?) \
+ AND (? IS NULL OR source_kind = ?) ORDER BY priority DESC, created_at, rowid LIMIT ?",
+ )
+ .bind(space.as_str())
+ .bind(state)
+ .bind(state)
+ .bind(mission_id)
+ .bind(mission_id)
+ .bind(source_kind)
+ .bind(source_kind)
+ .bind(limit.clamp(1, 1000))
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ pub async fn tasks_in_state(&self, state: &str) -> Result<Vec<Task>, DbError> {
+ Ok(sqlx::query_as::<_, Task>("SELECT * FROM tasks WHERE state = ? ORDER BY created_at").bind(state).fetch_all(&self.pool).await?)
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub async fn edit_task(
+ &self,
+ id: &str,
+ title: Option<&str>,
+ acceptance: Option<&str>,
+ priority: Option<i64>,
+ owner: Option<&str>,
+ budget: Option<i64>,
+ actor: &str,
+ ) -> Result<bool, DbError> {
+ let mut tx = self.pool.begin().await?;
+ let r = sqlx::query(
+ "UPDATE tasks SET title = COALESCE(?, title), acceptance = COALESCE(?, acceptance), priority = COALESCE(?, priority), \
+ suggested_kwant_id = COALESCE(?, suggested_kwant_id), budget_tokens = COALESCE(?, budget_tokens), updated_at = ? WHERE id = ?",
+ )
+ .bind(title)
+ .bind(acceptance)
+ .bind(priority)
+ .bind(owner)
+ .bind(budget)
+ .bind(Utc::now())
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ if r.rows_affected() == 1 {
+ let detail = serde_json::json!({"title": title, "acceptance": acceptance.map(|_| "changed"), "priority": priority, "owner": owner, "budget_tokens": budget});
+ insert_event(&mut tx, id, None, "edited", actor, None, None, &detail).await?;
+ }
+ tx.commit().await?;
+ Ok(r.rows_affected() == 1)
+ }
+
+ /// Moves a task from `from` to `to` (compare-and-set) and logs it. `Ok(false)` when it wasn't in
+ /// `from`; a trigger refusing the move is an error. Leaving `working` / `needs_you` releases the claim.
+ pub async fn move_task(&self, id: &str, from: &str, to: &str, actor: &str, change: &TaskChange) -> Result<bool, DbError> {
+ let now = Utc::now();
+ let mut tx = self.pool.begin().await?;
+ let r = sqlx::query(
+ "UPDATE tasks SET state = ?, updated_at = ?, \
+ attempts = attempts + ?, \
+ blocked_reason = CASE WHEN ? = 'blocked' THEN ? ELSE NULL END, \
+ owner_kwant_id = CASE WHEN ? THEN ? ELSE owner_kwant_id END, \
+ finished_at = CASE WHEN ? IN ('verified', 'cancelled', 'failed') THEN ? ELSE NULL END \
+ WHERE id = ? AND state = ?",
+ )
+ .bind(to)
+ .bind(now)
+ .bind(i64::from(change.attempt))
+ .bind(to)
+ .bind(&change.reason)
+ .bind(change.owner.is_some())
+ .bind(change.owner.as_ref().and_then(|o| o.clone()))
+ .bind(to)
+ .bind(now)
+ .bind(id)
+ .bind(from)
+ .execute(&mut *tx)
+ .await?;
+ if r.rows_affected() != 1 {
+ return Ok(false);
+ }
+ let releases = matches!(from, "working" | "needs_you") && !matches!(to, "working" | "needs_you");
+ if releases {
+ sqlx::query("UPDATE agent_claims SET released_at = ?, release_reason = ? WHERE task_id = ? AND released_at IS NULL")
+ .bind(now_ms())
+ .bind(to)
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ }
+ let mission: Option<(Option<String>,)> = sqlx::query_as("SELECT mission_id FROM tasks WHERE id = ?").bind(id).fetch_optional(&mut *tx).await?;
+ let mut detail = change.detail.clone().unwrap_or_else(|| serde_json::json!({}));
+ if let (Some(reason), Some(obj)) = (&change.reason, detail.as_object_mut()) {
+ obj.insert("reason".into(), Value::String(reason.clone()));
+ }
+ insert_event(&mut tx, id, mission.and_then(|m| m.0).as_deref(), &change.kind, actor, Some(from), Some(to), &detail).await?;
+ tx.commit().await?;
+ Ok(true)
+ }
+
+ /// Takes `task_id` for `kwant_id` with a lease of `lease_ms`, atomically: the task must be
+ /// ready, its dependencies verified, its mission active and able to cover the task's budget,
+ /// and the bot must hold no other claim of its own (`system` claims are kwant's, for hand-offs).
+ #[allow(clippy::too_many_arguments)]
+ pub async fn claim_task(
+ &self,
+ task_id: &str,
+ kwant_id: &str,
+ turn_id: Option<&str>,
+ context_id: Option<&str>,
+ lease_ms: i64,
+ system: bool,
+ actor: &str,
+ ) -> Result<Result<Task, ClaimRefused>, DbError> {
+ let mut tx = self.pool.begin().await?;
+ // Take the write lock first, so two claims can't both read "ready"
+ sqlx::query("UPDATE tasks SET updated_at = updated_at WHERE id = ?").bind(task_id).execute(&mut *tx).await?;
+ let Some(task) = sqlx::query_as::<_, Task>("SELECT * FROM tasks WHERE id = ?").bind(task_id).fetch_optional(&mut *tx).await? else {
+ return Ok(Err(ClaimRefused::Missing));
+ };
+ if task.state != "ready" {
+ let held = matches!(task.state.as_str(), "working" | "needs_you");
+ return Ok(Err(if held { ClaimRefused::Held } else { ClaimRefused::NotReady(task.state) }));
+ }
+ let now = now_ms();
+ if !system {
+ let busy: Option<(String,)> = sqlx::query_as(
+ "SELECT task_id FROM agent_claims WHERE kwant_id = ? AND system = 0 AND released_at IS NULL AND expires_at > ?",
+ )
+ .bind(kwant_id)
+ .bind(now)
+ .fetch_optional(&mut *tx)
+ .await?;
+ if let Some((other,)) = busy {
+ return Ok(Err(ClaimRefused::BotBusy(other)));
+ }
+ }
+ if let Some(mid) = &task.mission_id {
+ let Some(m) = sqlx::query_as::<_, Mission>("SELECT * FROM missions WHERE id = ?").bind(mid).fetch_optional(&mut *tx).await? else {
+ return Ok(Err(ClaimRefused::MissionNotActive));
+ };
+ if m.status != "active" {
+ return Ok(Err(ClaimRefused::MissionNotActive));
+ }
+ let (reserved,): (i64,) = sqlx::query_as(
+ "SELECT COALESCE(SUM(MAX(budget_tokens - spent_tokens, 0)), 0) FROM tasks WHERE mission_id = ? AND state IN ('working', 'needs_you')",
+ )
+ .bind(mid)
+ .fetch_one(&mut *tx)
+ .await?;
+ let needed = (task.budget_tokens - task.spent_tokens).max(1);
+ let remaining = m.budget_tokens - m.spent_tokens - reserved;
+ if needed > remaining {
+ return Ok(Err(ClaimRefused::Budget { remaining: remaining.max(0), needed }));
+ }
+ }
+ // Expired claims of this task (or the bot's own) are let go before the new one
+ sqlx::query("UPDATE agent_claims SET released_at = ?, release_reason = 'expired' WHERE released_at IS NULL AND expires_at <= ? AND (task_id = ? OR kwant_id = ?)")
+ .bind(now)
+ .bind(now)
+ .bind(task_id)
+ .bind(kwant_id)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query(
+ "INSERT INTO agent_claims (id, task_id, kwant_id, turn_id, context_id, system, claimed_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+ )
+ .bind(Uuid::new_v4().to_string())
+ .bind(task_id)
+ .bind(kwant_id)
+ .bind(turn_id)
+ .bind(context_id)
+ .bind(system)
+ .bind(now)
+ .bind(now + lease_ms.max(1000))
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("UPDATE tasks SET state = 'working', owner_kwant_id = ?, updated_at = ? WHERE id = ? AND state = 'ready'")
+ .bind(kwant_id)
+ .bind(Utc::now())
+ .bind(task_id)
+ .execute(&mut *tx)
+ .await?;
+ insert_event(
+ &mut tx,
+ task_id,
+ task.mission_id.as_deref(),
+ "claimed",
+ actor,
+ Some("ready"),
+ Some("working"),
+ &serde_json::json!({"kwant_id": kwant_id, "lease_ms": lease_ms, "system": system}),
+ )
+ .await?;
+ let task = sqlx::query_as::<_, Task>("SELECT * FROM tasks WHERE id = ?").bind(task_id).fetch_one(&mut *tx).await?;
+ tx.commit().await?;
+ Ok(Ok(task))
+ }
+
+ /// The task's open claim, live or expired-but-not-yet-swept.
+ pub async fn open_claim(&self, task_id: &str) -> Result<Option<Claim>, DbError> {
+ Ok(sqlx::query_as::<_, Claim>("SELECT * FROM agent_claims WHERE task_id = ? AND released_at IS NULL")
+ .bind(task_id)
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ /// Open claims of `kwant_id`: system claims first.
+ pub async fn claims_of(&self, kwant_id: &str) -> Result<Vec<Claim>, DbError> {
+ Ok(sqlx::query_as::<_, Claim>(
+ "SELECT * FROM agent_claims WHERE kwant_id = ? AND released_at IS NULL ORDER BY system DESC, claimed_at",
+ )
+ .bind(kwant_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Claims of `kwant_id` that a turn's tokens can land on: open ones, plus those taken in
+ /// `turn_id` or released since `since_ms` (the bot finished its task during that turn). Open
+ /// claims first, then system claims, then the most recent.
+ pub async fn spend_claims(&self, kwant_id: &str, turn_id: Option<&str>, since_ms: i64) -> Result<Vec<Claim>, DbError> {
+ Ok(sqlx::query_as::<_, Claim>(
+ "SELECT * FROM agent_claims WHERE kwant_id = ?1 \
+ AND (released_at IS NULL OR released_at >= ?2 OR (?3 IS NOT NULL AND turn_id = ?3)) \
+ ORDER BY released_at IS NOT NULL, system DESC, claimed_at DESC",
+ )
+ .bind(kwant_id)
+ .bind(since_ms)
+ .bind(turn_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Pushes the task's open claim out to `now + lease_ms` (never shortens it).
+ pub async fn renew_claim(&self, task_id: &str, lease_ms: i64) -> Result<bool, DbError> {
+ let now = now_ms();
+ let r = sqlx::query("UPDATE agent_claims SET expires_at = MAX(expires_at, ?) WHERE task_id = ? AND released_at IS NULL AND expires_at > ?")
+ .bind(now + lease_ms)
+ .bind(task_id)
+ .bind(now)
+ .execute(&self.pool)
+ .await?;
+ Ok(r.rows_affected() == 1)
+ }
+
+ /// Working tasks whose lease ran out (needs_you tasks wait for the person and don't expire).
+ pub async fn expired_working(&self) -> Result<Vec<Task>, DbError> {
+ Ok(sqlx::query_as::<_, Task>(
+ "SELECT t.* FROM tasks t WHERE t.state = 'working' AND NOT EXISTS ( \
+ SELECT 1 FROM agent_claims a WHERE a.task_id = t.id AND a.released_at IS NULL AND a.expires_at > ?)",
+ )
+ .bind(now_ms())
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Test hook: makes the task's open claim expire now.
+ #[doc(hidden)]
+ pub async fn expire_claim_now(&self, task_id: &str) -> Result<(), DbError> {
+ sqlx::query("UPDATE agent_claims SET expires_at = ? WHERE task_id = ? AND released_at IS NULL")
+ .bind(now_ms() - 1)
+ .bind(task_id)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// Adds `tokens` to the task and its mission.
+ pub async fn spend_on_task(&self, task_id: &str, tokens: i64) -> Result<(), DbError> {
+ if tokens <= 0 {
+ return Ok(());
+ }
+ let mut tx = self.pool.begin().await?;
+ sqlx::query("UPDATE tasks SET spent_tokens = spent_tokens + ? WHERE id = ?").bind(tokens).bind(task_id).execute(&mut *tx).await?;
+ sqlx::query("UPDATE missions SET spent_tokens = spent_tokens + ?, updated_at = ? WHERE id = (SELECT mission_id FROM tasks WHERE id = ?)")
+ .bind(tokens)
+ .bind(Utc::now())
+ .bind(task_id)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(())
+ }
+
+ // Dependencies
+
+ /// Adds `task_id` → `depends_on`, refusing a cycle or a link across missions.
+ pub async fn add_dependency(&self, task_id: &str, depends_on: &str) -> Result<(), DbError> {
+ let a = self.get_task(task_id).await?.ok_or_else(|| DbError::Conflict("no such task".into()))?;
+ let b = self.get_task(depends_on).await?.ok_or_else(|| DbError::Conflict("no such dependency".into()))?;
+ if a.mission_id != b.mission_id || a.space_id != b.space_id {
+ return Err(DbError::Conflict("a task can depend only on a task of the same mission".into()));
+ }
+ // depends_on (transitively) on task_id already → a cycle
+ let (cycle,): (i64,) = sqlx::query_as(
+ "WITH RECURSIVE up(id) AS (SELECT ? UNION SELECT d.depends_on_id FROM task_dependencies d JOIN up ON d.task_id = up.id) \
+ SELECT COUNT(*) FROM up WHERE id = ?",
+ )
+ .bind(depends_on)
+ .bind(task_id)
+ .fetch_one(&self.pool)
+ .await?;
+ if cycle > 0 {
+ return Err(DbError::Conflict("that dependency would make a cycle".into()));
+ }
+ sqlx::query("INSERT OR IGNORE INTO task_dependencies (task_id, depends_on_id) VALUES (?, ?)")
+ .bind(task_id)
+ .bind(depends_on)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ pub async fn dependencies_of(&self, task_id: &str) -> Result<Vec<(String, String)>, DbError> {
+ Ok(sqlx::query_as("SELECT t.id, t.state FROM task_dependencies d JOIN tasks t ON t.id = d.depends_on_id WHERE d.task_id = ?")
+ .bind(task_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Backlog tasks of `mission_id` whose dependencies are all verified.
+ pub async fn promotable(&self, mission_id: &str) -> Result<Vec<Task>, DbError> {
+ Ok(sqlx::query_as::<_, Task>(
+ "SELECT t.* FROM tasks t WHERE t.mission_id = ? AND t.state = 'backlog' AND NOT EXISTS ( \
+ SELECT 1 FROM task_dependencies d JOIN tasks u ON u.id = d.depends_on_id WHERE d.task_id = t.id AND u.state != 'verified')",
+ )
+ .bind(mission_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Backlog tasks waiting on `task_id` whose dependencies are now all verified.
+ pub async fn dependents_promotable(&self, task_id: &str) -> Result<Vec<Task>, DbError> {
+ Ok(sqlx::query_as::<_, Task>(
+ "SELECT t.* FROM tasks t JOIN task_dependencies w ON w.task_id = t.id AND w.depends_on_id = ? WHERE t.state = 'backlog' AND NOT EXISTS ( \
+ SELECT 1 FROM task_dependencies d JOIN tasks u ON u.id = d.depends_on_id WHERE d.task_id = t.id AND u.state != 'verified')",
+ )
+ .bind(task_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// A retried task gets its attempts back.
+ pub async fn reset_attempts(&self, id: &str) -> Result<(), DbError> {
+ sqlx::query("UPDATE tasks SET attempts = 0, updated_at = ? WHERE id = ?").bind(Utc::now()).bind(id).execute(&self.pool).await?;
+ Ok(())
+ }
+
+ /// A routine run's routine and status.
+ pub async fn routine_run_of(&self, run_id: &str) -> Result<Option<(String, String)>, DbError> {
+ Ok(sqlx::query_as("SELECT routine_id, status FROM routine_runs WHERE id = ?").bind(run_id).fetch_optional(&self.pool).await?)
+ }
+
+ /// Open tasks kwant holds a system claim on (hand-offs, routine runs).
+ pub async fn system_held(&self) -> Result<Vec<Task>, DbError> {
+ Ok(sqlx::query_as::<_, Task>(
+ "SELECT t.* FROM tasks t JOIN agent_claims a ON a.task_id = t.id AND a.released_at IS NULL AND a.system = 1 \
+ WHERE t.state IN ('working', 'needs_you')",
+ )
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// The bot an approval card belongs to.
+ pub async fn approval_kwant(&self, approval_id: &str) -> Result<Option<String>, DbError> {
+ let row: Option<(String,)> = sqlx::query_as("SELECT kwant_id FROM approvals WHERE id = ?").bind(approval_id).fetch_optional(&self.pool).await?;
+ Ok(row.map(|r| r.0))
+ }
+
+ // Evidence and checks
+
+ pub async fn add_evidence(&self, e: &NewEvidence) -> Result<Evidence, DbError> {
+ let mut tx = self.pool.begin().await?;
+ let ev = sqlx::query_as::<_, Evidence>(
+ "INSERT INTO evidence (id, task_id, kind, label, uri, path, sha256, bytes, excerpt, captured_by, run_id, captured_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *",
+ )
+ .bind(Uuid::new_v4().to_string())
+ .bind(&e.task_id)
+ .bind(&e.kind)
+ .bind(&e.label)
+ .bind(&e.uri)
+ .bind(&e.path)
+ .bind(&e.sha256)
+ .bind(e.bytes)
+ .bind(&e.excerpt)
+ .bind(&e.captured_by)
+ .bind(&e.run_id)
+ .bind(Utc::now())
+ .fetch_one(&mut *tx)
+ .await?;
+ insert_event(&mut tx, &e.task_id, None, "evidence", &e.captured_by, None, None, &serde_json::json!({"evidence_id": ev.id, "kind": e.kind, "label": e.label})).await?;
+ tx.commit().await?;
+ Ok(ev)
+ }
+
+ pub async fn list_evidence(&self, task_id: &str) -> Result<Vec<Evidence>, DbError> {
+ Ok(sqlx::query_as::<_, Evidence>("SELECT * FROM evidence WHERE task_id = ? ORDER BY captured_at, rowid").bind(task_id).fetch_all(&self.pool).await?)
+ }
+
+ pub async fn add_check(&self, c: &NewCheck) -> Result<OutcomeCheck, DbError> {
+ let status = if c.approved { "pending" } else { "needs_approval" };
+ let mut tx = self.pool.begin().await?;
+ let check = sqlx::query_as::<_, OutcomeCheck>(
+ "INSERT INTO outcome_checks (id, task_id, kind, spec, required, approved, status, requested_by, approved_by, created_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *",
+ )
+ .bind(Uuid::new_v4().to_string())
+ .bind(&c.task_id)
+ .bind(&c.kind)
+ .bind(c.spec.to_string())
+ .bind(c.required)
+ .bind(c.approved)
+ .bind(status)
+ .bind(&c.requested_by)
+ .bind(c.approved.then(|| c.approved_by.clone().unwrap_or_else(|| "auto".into())))
+ .bind(Utc::now())
+ .fetch_one(&mut *tx)
+ .await?;
+ insert_event(&mut tx, &c.task_id, None, "check_added", &c.requested_by, None, None, &serde_json::json!({"check_id": check.id, "kind": c.kind, "approved": c.approved})).await?;
+ tx.commit().await?;
+ Ok(check)
+ }
+
+ pub async fn get_check(&self, id: &str) -> Result<Option<OutcomeCheck>, DbError> {
+ Ok(sqlx::query_as::<_, OutcomeCheck>("SELECT * FROM outcome_checks WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)
+ }
+
+ pub async fn list_checks(&self, task_id: &str) -> Result<Vec<OutcomeCheck>, DbError> {
+ Ok(sqlx::query_as::<_, OutcomeCheck>("SELECT * FROM outcome_checks WHERE task_id = ? ORDER BY created_at, rowid").bind(task_id).fetch_all(&self.pool).await?)
+ }
+
+ pub async fn approve_check(&self, id: &str) -> Result<bool, DbError> {
+ let r = sqlx::query("UPDATE outcome_checks SET approved = 1, approved_by = 'person', status = 'pending' WHERE id = ? AND status = 'needs_approval'")
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(r.rows_affected() == 1)
+ }
+
+ /// Marks a check running; false when it is already running or not approved.
+ pub async fn start_check(&self, id: &str) -> Result<bool, DbError> {
+ let r = sqlx::query("UPDATE outcome_checks SET status = 'running', started_at = ?, finished_at = NULL WHERE id = ? AND approved = 1 AND status != 'running'")
+ .bind(Utc::now())
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(r.rows_affected() == 1)
+ }
+
+ pub async fn finish_check(&self, id: &str, status: &str, output: Option<&str>, checked_by: &str, evidence_id: Option<&str>) -> Result<(), DbError> {
+ let mut tx = self.pool.begin().await?;
+ sqlx::query("UPDATE outcome_checks SET status = ?, output_excerpt = ?, checked_by = ?, evidence_id = ?, finished_at = ? WHERE id = ?")
+ .bind(status)
+ .bind(output)
+ .bind(checked_by)
+ .bind(evidence_id)
+ .bind(Utc::now())
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ let task: Option<(String,)> = sqlx::query_as("SELECT task_id FROM outcome_checks WHERE id = ?").bind(id).fetch_optional(&mut *tx).await?;
+ if let Some((task_id,)) = task {
+ insert_event(&mut tx, &task_id, None, "check_result", checked_by, None, None, &serde_json::json!({"check_id": id, "status": status})).await?;
+ }
+ tx.commit().await?;
+ Ok(())
+ }
+
+ // Events
+
+ pub async fn log_task_event(&self, task_id: &str, kind: &str, actor: &str, detail: &Value) -> Result<(), DbError> {
+ let mut tx = self.pool.begin().await?;
+ insert_event(&mut tx, task_id, None, kind, actor, None, None, detail).await?;
+ tx.commit().await?;
+ Ok(())
+ }
+
+ pub async fn task_events(&self, task_id: &str, limit: i64) -> Result<Vec<TaskEvent>, DbError> {
+ let mut rows = sqlx::query_as::<_, TaskEvent>("SELECT * FROM task_events WHERE task_id = ? ORDER BY id DESC LIMIT ?")
+ .bind(task_id)
+ .bind(limit)
+ .fetch_all(&self.pool)
+ .await?;
+ rows.reverse();
+ Ok(rows)
+ }
+
+ /// Events of `kinds` in `space` since `since`, for the Insights counts.
+ pub async fn space_events_since(&self, space: &SpaceId, since: DateTime<Utc>) -> Result<Vec<TaskEvent>, DbError> {
+ Ok(sqlx::query_as::<_, TaskEvent>(
+ "SELECT e.* FROM task_events e JOIN tasks t ON t.id = e.task_id WHERE t.space_id = ? AND e.created_at >= ? ORDER BY e.id",
+ )
+ .bind(space.as_str())
+ .bind(since)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// The bot's open question, human-step and approval cards as (kind, id, text, where): `where`
+ /// is the chat (thread, channel or direct) for questions and steps, the turn for approvals.
+ pub async fn open_cards_of(&self, kwant_id: &str) -> Result<Vec<(String, String, String, Option<String>)>, DbError> {
+ Ok(sqlx::query_as(
+ "SELECT 'question', id, question, COALESCE(thread_id, channel_id, direct_kwant_id) FROM questions WHERE kwant_id = ?1 AND status = 'open' \
+ UNION ALL SELECT 'human_step', id, reason, COALESCE(thread_id, channel_id, direct_kwant_id) FROM human_steps WHERE kwant_id = ?1 AND status = 'open' \
+ UNION ALL SELECT 'approval', id, tool_name, turn_id FROM approvals WHERE kwant_id = ?1 AND status = 'pending'",
+ )
+ .bind(kwant_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Sets the task's open claim to expire `lease_ms` from now, live or not (a task back from
+ /// `needs_you` gets a fresh lease).
+ pub async fn refresh_claim(&self, task_id: &str, lease_ms: i64) -> Result<bool, DbError> {
+ let r = sqlx::query("UPDATE agent_claims SET expires_at = ? WHERE task_id = ? AND released_at IS NULL")
+ .bind(now_ms() + lease_ms)
+ .bind(task_id)
+ .execute(&self.pool)
+ .await?;
+ Ok(r.rows_affected() == 1)
+ }
+
+ /// Raw SQL for tests that prove the triggers hold against a direct write.
+ #[doc(hidden)]
+ pub async fn exec_raw_for_test(&self, sql: &str) -> Result<u64, DbError> {
+ Ok(sqlx::query(sql).execute(&self.pool).await?.rows_affected())
+ }
+}
+
+/// What else a state move changes.
+#[derive(Debug, Clone)]
+pub struct TaskChange {
+ /// The event's kind ("state", "lease_expired", "review", …).
+ pub kind: String,
+ pub reason: Option<String>,
+ /// Counts one more attempt.
+ pub attempt: bool,
+ /// `Some(x)` sets the owner to `x`.
+ pub owner: Option<Option<String>>,
+ pub detail: Option<Value>,
+}
+
+impl Default for TaskChange {
+ fn default() -> Self {
+ TaskChange { kind: "state".into(), reason: None, attempt: false, owner: None, detail: None }
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn insert_event(
+ tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
+ task_id: &str,
+ mission_id: Option<&str>,
+ kind: &str,
+ actor: &str,
+ from: Option<&str>,
+ to: Option<&str>,
+ detail: &Value,
+) -> Result<(), DbError> {
+ let mission: Option<String> = match mission_id {
+ Some(m) => Some(m.to_string()),
+ None => sqlx::query_as::<_, (Option<String>,)>("SELECT mission_id FROM tasks WHERE id = ?")
+ .bind(task_id)
+ .fetch_optional(&mut **tx)
+ .await?
+ .and_then(|r| r.0),
+ };
+ sqlx::query("INSERT INTO task_events (task_id, mission_id, kind, actor, from_state, to_state, detail, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
+ .bind(task_id)
+ .bind(mission)
+ .bind(kind)
+ .bind(actor)
+ .bind(from)
+ .bind(to)
+ .bind(detail.to_string())
+ .bind(Utc::now())
+ .execute(&mut **tx)
+ .await?;
+ Ok(())
+}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 3b99f0e0..3401d710 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -24,6 +24,7 @@ pub mod decisions;
pub mod work_ahead;
pub mod api_context;
pub mod usage;
+pub mod missions;
/// What a space's #general says about itself.
pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
@@ -156,6 +157,7 @@ impl Database {
db.migrate_work_ahead().await?;
db.migrate_api_context().await?;
db.migrate_usage().await?;
+ db.migrate_missions().await?;
if spaces {
let migration = db.migrate_spaces(data_dir, fresh).await?;
db.require_spaces_schema(&migration).await?;
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index 11eddd6f..b463d4b2 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -241,6 +241,13 @@ pub enum RuntimeEvent {
run_id: String,
status: String,
},
+ /// A Mission Control task changed (state, claim, checks, evidence). `task` is the board's Task
+ /// shape and carries `space_id`.
+ #[serde(rename = "task_updated", alias = "TaskUpdated")]
+ TaskUpdated { task: Value },
+ /// A mission changed (status, budget, counts). `mission` carries `space_id`.
+ #[serde(rename = "mission_updated", alias = "MissionUpdated")]
+ MissionUpdated { mission: Value },
/// Something the user asked to be told about. `kind` is one of `continuity::NOTIFY_KINDS`
/// ("turn_finished", "approval_needed", "human_step", …). `body` never holds chat text, tool arguments or secrets.
#[serde(rename = "notify", alias = "Notify")]
diff --git a/src/mcp/fetch_risk.rs b/src/mcp/fetch_risk.rs
index 1413da01..182ffd1a 100644
--- a/src/mcp/fetch_risk.rs
+++ b/src/mcp/fetch_risk.rs
@@ -72,6 +72,37 @@ pub fn fetch_risk_with(url: &str, resolve: &dyn Fn(&str, u16) -> Option<Vec<IpAd
}
}
+/// The addresses `url` reaches when every one of them is public (no dev-server exemption), with the
+/// host name to pin them to; else why not. For fetches kwnt makes itself on a bot's behalf
+/// (outcome checks): pinning the answer closes the DNS-rebinding gap [`fetch_risk`] leaves open.
+pub fn public_only(url: &str) -> Result<(String, Vec<std::net::SocketAddr>), String> {
+ public_only_with(url, &system_resolve)
+}
+
+/// [`public_only`] with the name lookup supplied (tests).
+pub fn public_only_with(url: &str, resolve: &dyn Fn(&str, u16) -> Option<Vec<IpAddr>>) -> Result<(String, Vec<std::net::SocketAddr>), String> {
+ let parsed = url::Url::parse(url.trim()).map_err(|_| "kwnt can't read this URL".to_string())?;
+ if !matches!(parsed.scheme(), "http" | "https") {
+ return Err(format!("it fetches a `{}:` URL", parsed.scheme()));
+ }
+ let port = parsed.port_or_known_default().unwrap_or(80);
+ let (name, addrs) = match parsed.host() {
+ None => return Err("kwnt can't tell where this URL goes".into()),
+ Some(url::Host::Ipv4(ip)) => (ip.to_string(), vec![IpAddr::V4(ip)]),
+ Some(url::Host::Ipv6(ip)) => (ip.to_string(), vec![IpAddr::V6(ip)]),
+ Some(url::Host::Domain(name)) => {
+ let name = name.trim_end_matches('.').to_ascii_lowercase();
+ let addrs = resolve(&name, port).filter(|a| !a.is_empty()).ok_or_else(|| format!("kwnt couldn't look up `{name}`"))?;
+ (name, addrs)
+ }
+ };
+ match addrs.iter().map(|ip| reach(*ip)).find(|r| *r != Reach::Public) {
+ Some(Reach::Local) => Err(format!("`{name}` is this computer")),
+ Some(_) => Err(format!("`{name}` is on a private network")),
+ None => Ok((name, addrs.into_iter().map(|ip| std::net::SocketAddr::new(ip, port)).collect())),
+ }
+}
+
fn by_reach(reach: Reach, shown: &str, local_and_kwnt: impl FnOnce() -> Option<String>) -> Option<String> {
match reach {
Reach::Local => local_and_kwnt(),
@@ -242,4 +273,15 @@ mod tests {
assert!(fetch_risk_with("http://nowhere.invalid/", &fake).unwrap().contains("couldn't look up"));
assert!(fetch_risk_with("http://2130706433:8799/", &fake).unwrap().contains("kwnt itself"));
}
+
+ #[test]
+ fn public_only_has_no_dev_server_exemption_and_pins_the_answer() {
+ for url in ["http://127.0.0.1:8080/", "http://localhost:5173/", "http://[::1]:3000/", "http://localtest.me/",
+ "http://nas.example/", "http://dual.example/", "http://nowhere.example/", "file:///etc/passwd", "http://2130706433/"] {
+ assert!(public_only_with(url, &fake).is_err(), "{url}");
+ }
+ let (host, addrs) = public_only_with("https://example.com/status", &fake).unwrap();
+ assert_eq!(host, "example.com");
+ assert_eq!(addrs, vec!["93.184.216.34:443".parse().unwrap()]);
+ }
}
diff --git a/src/server/auth.rs b/src/server/auth.rs
index dee5e0b8..5ec4c2a3 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -334,6 +334,9 @@ pub fn person_only(method: &Method, path: &str) -> bool {
["", "api", "waiting", ..] => true,
// Starting work-ahead runs now spends the person's tokens
["", "api", "work-ahead", ..] => true,
+ // Mission Control: approving plans, verifying, rejecting, retrying and approving checks are
+ // the person's calls; bots act on tasks only through their task tools
+ ["", "api", "missions" | "tasks" | "checks", ..] => *method != Method::GET && *method != Method::HEAD,
// App-wide settings, including where notifications go (`notify_webhook_url`), and the
// sub-routes such as `/computer` (which machine the bots run on) and `/computer/window`:
// bots change the allowed ones through their `settings_update` action, never these routes
@@ -837,6 +840,15 @@ mod tests {
assert!(person_only(&get, "/api/passwords/store"));
assert!(person_only(&post, "/api/messages/m1/decisions/0/change"));
assert!(person_only(&post, "/api/work-ahead/run"));
+ assert!(person_only(&post, "/api/missions"));
+ assert!(person_only(&post, "/api/missions/m1/approve"));
+ assert!(person_only(&post, "/api/missions/m1/run"));
+ assert!(person_only(&Method::PATCH, "/api/missions/m1"));
+ assert!(person_only(&post, "/api/tasks/t1/verify"));
+ assert!(person_only(&post, "/api/tasks/t1/checks/run"));
+ assert!(person_only(&post, "/api/checks/c1/approve"));
+ assert!(!person_only(&get, "/api/tasks"));
+ assert!(!person_only(&get, "/api/missions/insights"));
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/continuity.rs b/src/server/continuity.rs
index 3b8b9f0f..dd9d3b92 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -331,6 +331,7 @@ const READ_ONLY_SELF_TOOLS: &[&str] = &[
"read_attachment",
"mcp_search",
"skill_get",
+ "task_list",
];
#[async_trait]
@@ -347,9 +348,12 @@ impl ToolApprover for SelfToolsApprover {
}
}
-fn tool_list(scope: &SelfScope) -> Value {
+fn tool_list(scope: &SelfScope, board: bool) -> Value {
let mut tools = memory_tools();
if let Some(list) = tools.as_array_mut() {
+ if board {
+ list.extend(super::missions::tools::tools());
+ }
list.extend(super::skills::tools());
list.extend(super::mcp_suggest::tools());
list.extend(super::bot_actions::tools());
@@ -659,7 +663,7 @@ pub async fn self_endpoint(
}),
),
"ping" => rpc_result(id, json!({})),
- "tools/list" => rpc_result(id, json!({ "tools": tool_list(&scope) })),
+ "tools/list" => rpc_result(id, json!({ "tools": tool_list(&scope, super::missions::enabled(&state).await) })),
"tools/call" => {
let args = &msg["params"]["arguments"];
let name = msg["params"]["name"].as_str().unwrap_or("");
@@ -813,6 +817,7 @@ async fn call_tool(
"mcp_suggest" => super::mcp_suggest::tool_suggest(state, scope, args).await,
n if super::bot_actions::handles(n) => super::bot_actions::call(state, scope, n, args).await,
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,
"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,
diff --git a/src/server/missions/checks.rs b/src/server/missions/checks.rs
new file mode 100644
index 00000000..42ca28e6
--- /dev/null
+++ b/src/server/missions/checks.rs
@@ -0,0 +1,290 @@
+//! Outcome checks kwant runs itself: `command` (exit code 0, in the mission's folder), `http` (GET,
+//! status and text), `file_exists`, `file_contains`, `file_sha256` (inside the mission's folder).
+//! Each result is stored on the check and as `check_output` evidence; then the task is evaluated.
+
+use super::{evaluate, task_folder, MAX_EXCERPT};
+use crate::db::missions::{NewEvidence, OutcomeCheck, Task, KWANT_CHECK_KINDS};
+use crate::server::AppState;
+use serde_json::{json, Value};
+use sha2::{Digest, Sha256};
+use std::path::{Path, PathBuf};
+
+pub const MAX_COMMAND_SECS: u64 = 900;
+const DEFAULT_COMMAND_SECS: u64 = 300;
+const HTTP_TIMEOUT_SECS: u64 = 20;
+/// Bytes of a page or file read for `contains` / `file_contains`.
+const MAX_READ_BYTES: usize = 5 * 1024 * 1024;
+
+/// File names a check or evidence never reads: saved passwords, keys and env files.
+pub fn secret_file(path: &Path) -> bool {
+ let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("").to_ascii_lowercase();
+ let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
+ name == ".env"
+ || name.starts_with(".env.")
+ || name.starts_with("id_rsa")
+ || name.starts_with("id_ed25519")
+ || name.starts_with("id_ecdsa")
+ || name.contains("password")
+ || name.contains("secret")
+ || name == ".git-credentials"
+ || name == ".netrc"
+ || matches!(ext.as_str(), "pem" | "key" | "p12" | "pfx" | "kdbx" | "keychain")
+ || path.components().any(|c| matches!(c.as_os_str().to_str(), Some(".ssh" | ".gnupg")))
+}
+
+/// `rel` resolved inside `folder` (symlinks followed), or why not.
+pub fn inside(folder: &Path, rel: &str) -> Result<PathBuf, String> {
+ let rel = rel.trim();
+ if rel.is_empty() {
+ return Err("path is empty".into());
+ }
+ let Some(root) = crate::mcp::builtin_tools::canonical_folder(Some(folder)) else {
+ return Err("the mission's folder doesn't exist".into());
+ };
+ if Path::new(rel).components().any(|c| matches!(c, std::path::Component::ParentDir)) {
+ return Err("paths can't use ..".into());
+ }
+ if !crate::mcp::builtin_tools::is_inside(&root, rel) {
+ return Err("that path is outside the mission's folder".into());
+ }
+ let p = Path::new(rel);
+ let joined = if p.is_absolute() { p.to_path_buf() } else { root.join(p) };
+ let real = joined.canonicalize().unwrap_or(joined);
+ if !real.starts_with(&root) {
+ return Err("that path is outside the mission's folder".into());
+ }
+ if secret_file(&real) {
+ return Err("checks don't read password, key or env files".into());
+ }
+ Ok(real)
+}
+
+fn excerpt(s: &str) -> String {
+ let s = s.trim();
+ if s.chars().count() <= MAX_EXCERPT {
+ return s.to_string();
+ }
+ // Keep the end: test runners print the verdict last
+ let tail: String = s.chars().rev().take(MAX_EXCERPT - 2).collect::<Vec<_>>().into_iter().rev().collect();
+ format!("…\n{tail}")
+}
+
+/// Runs one check; returns `(status, output)` with status "passed", "failed" or "error".
+/// `person_ok`: the person added or approved it, so an `http` check may reach this computer or a
+/// private network; otherwise the URL must resolve to public addresses only, and is fetched from them.
+pub async fn run_spec(kind: &str, spec: &Value, folder: Option<&Path>, person_ok: bool) -> (String, String) {
+ let s = |k: &str| spec[k].as_str().map(str::trim).filter(|v| !v.is_empty());
+ let need_folder = || folder.ok_or_else(|| "this task has no folder to check in".to_string());
+ let r: Result<(bool, String), String> = match kind {
+ "command" => match (s("command"), need_folder()) {
+ (Some(cmd), Ok(dir)) => {
+ let secs = spec["timeout_secs"].as_u64().unwrap_or(DEFAULT_COMMAND_SECS).clamp(1, MAX_COMMAND_SECS);
+ match crate::tools::shell::execute_shell(dir, &json!({"command": cmd, "timeout_secs": secs})).await {
+ Ok(v) => {
+ let code = v["exit_code"].as_i64().unwrap_or(-1);
+ let out = format!("exit code {code}\n{}{}", v["stdout"].as_str().unwrap_or(""), v["stderr"].as_str().unwrap_or(""));
+ Ok((code == 0, out))
+ }
+ Err(e) => Err(e.to_string()),
+ }
+ }
+ (None, _) => Err("spec.command is missing".into()),
+ (_, Err(e)) => Err(e),
+ },
+ "http" => match s("url") {
+ Some(url) => http(url, spec, person_ok).await,
+ None => Err("spec.url is missing".into()),
+ },
+ "file_exists" | "file_contains" | "file_sha256" => match (s("path"), need_folder()) {
+ (Some(rel), Ok(dir)) => file(kind, rel, spec, dir).await,
+ (None, _) => Err("spec.path is missing".into()),
+ (_, Err(e)) => Err(e),
+ },
+ other => Err(format!("kwant doesn't run {other} checks")),
+ };
+ match r {
+ Ok((true, out)) => ("passed".into(), excerpt(&out)),
+ Ok((false, out)) => ("failed".into(), excerpt(&out)),
+ Err(e) => ("error".into(), excerpt(&e)),
+ }
+}
+
+async fn http(url: &str, spec: &Value, person_ok: bool) -> Result<(bool, String), String> {
+ let mut builder = reqwest::Client::builder();
+ if !person_ok {
+ let (host, addrs) = crate::mcp::fetch_risk::public_only(url).map_err(|why| format!("not fetched: {why}; the person can approve it"))?;
+ // The name is fetched from the addresses just checked, not looked up again
+ builder = builder.resolve_to_addrs(&host, &addrs);
+ }
+ let client = builder
+ .timeout(std::time::Duration::from_secs(HTTP_TIMEOUT_SECS))
+ // A redirect could lead to a private address the check wasn't approved for
+ .redirect(reqwest::redirect::Policy::none())
+ .build()
+ .map_err(|e| e.to_string())?;
+ let resp = client.get(url).send().await.map_err(|e| format!("GET {url} failed: {e}"))?;
+ let status = resp.status().as_u16();
+ let ok_status = match spec["expect_status"].as_u64() {
+ Some(want) => u64::from(status) == want,
+ None => (200..300).contains(&status),
+ };
+ let mut body = Vec::new();
+ let mut stream = resp;
+ while let Ok(Some(chunk)) = stream.chunk().await {
+ body.extend_from_slice(&chunk);
+ if body.len() >= MAX_READ_BYTES {
+ break;
+ }
+ }
+ let text = String::from_utf8_lossy(&body);
+ let contains = spec["contains"].as_str().filter(|t| !t.is_empty());
+ let has = contains.is_none_or(|t| text.contains(t));
+ let mut out = format!("GET {url} → {status}");
+ if let Some(t) = contains {
+ out.push_str(&format!("; {} \"{t}\"", if has { "contains" } else { "does not contain" }));
+ }
+ Ok((ok_status && has, out))
+}
+
+async fn file(kind: &str, rel: &str, spec: &Value, dir: &Path) -> Result<(bool, String), String> {
+ let path = inside(dir, rel)?;
+ let meta = tokio::fs::metadata(&path).await;
+ match kind {
+ "file_exists" => Ok((meta.as_ref().is_ok_and(|m| m.is_file()), match &meta {
+ Ok(m) => format!("{rel} exists ({} bytes)", m.len()),
+ Err(_) => format!("{rel} doesn't exist"),
+ })),
+ _ => {
+ let Ok(m) = meta else { return Ok((false, format!("{rel} doesn't exist"))) };
+ if !m.is_file() {
+ return Ok((false, format!("{rel} isn't a file")));
+ }
+ let bytes = tokio::fs::read(&path).await.map_err(|e| format!("can't read {rel}: {e}"))?;
+ if kind == "file_sha256" {
+ let got = hex(&Sha256::digest(&bytes));
+ let want = spec["sha256"].as_str().unwrap_or("").trim().to_ascii_lowercase();
+ Ok((got == want, format!("sha256 of {rel} is {got}")))
+ } else {
+ let want = spec["text"].as_str().unwrap_or("");
+ let text = String::from_utf8_lossy(&bytes[..bytes.len().min(MAX_READ_BYTES)]);
+ let has = !want.is_empty() && text.contains(want);
+ Ok((has, format!("{rel} {} \"{want}\"", if has { "contains" } else { "does not contain" })))
+ }
+ }
+ }
+}
+
+pub fn hex(bytes: &[u8]) -> String {
+ bytes.iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// Runs `check` if kwant runs its kind and it is approved; stores the result and its evidence.
+pub async fn run_check(state: &AppState, task: &Task, check: &OutcomeCheck) -> OutcomeCheck {
+ if !KWANT_CHECK_KINDS.contains(&check.kind.as_str()) || !check.approved {
+ return check.clone();
+ }
+ if !state.db.start_check(&check.id).await.unwrap_or(false) {
+ return state.db.get_check(&check.id).await.ok().flatten().unwrap_or_else(|| check.clone());
+ }
+ super::emit_task(state, task).await;
+ let folder = task_folder(state, task).await;
+ let spec = check.spec_value();
+ // Only approved checks get here: a bot's command or private-address check is approved by the
+ // person (check approval and mission approval are person-only routes). An http check the person
+ // didn't add or approve is held to public addresses again now, pinned against DNS rebinding.
+ let person_ok = check.requested_by == "person" || approved_by_person(state, check).await;
+ let (status, output) = run_spec(&check.kind, &spec, folder.as_deref(), person_ok).await;
+ let ev = state
+ .db
+ .add_evidence(&NewEvidence {
+ task_id: task.id.clone(),
+ kind: "check_output".into(),
+ label: format!("{} check: {status}", check.kind),
+ excerpt: Some(output.clone()),
+ captured_by: "kwant".into(),
+ run_id: Some(check.id.clone()),
+ ..Default::default()
+ })
+ .await
+ .ok();
+ let _ = state.db.finish_check(&check.id, &status, Some(&output), "kwant", ev.as_ref().map(|e| e.id.as_str())).await;
+ state.db.get_check(&check.id).await.ok().flatten().unwrap_or_else(|| check.clone())
+}
+
+/// Whether the person approved `check` (`POST /api/checks/:id/approve`, or the mission it came in).
+async fn approved_by_person(state: &AppState, check: &OutcomeCheck) -> bool {
+ let events = state.db.task_events(&check.task_id, 500).await.unwrap_or_default();
+ if events.iter().any(|e| e.kind == "check_added" && e.actor == "person" && e.detail_value()["check_id"] == check.id.as_str()) {
+ return true;
+ }
+ // A check planned with a mission is approved when the person approves the mission
+ match state.db.get_task(&check.task_id).await {
+ Ok(Some(t)) => match t.mission_id {
+ Some(m) => state.db.get_mission(&m).await.ok().flatten().is_some_and(|m| m.approved_by.as_deref() == Some("person") && m.approved_at.is_some_and(|at| check.created_at <= at)),
+ None => false,
+ },
+ _ => false,
+ }
+}
+
+/// Runs the task's approved kwant checks (or just `only`), then evaluates the task. Returns the
+/// checks after the run and the task.
+pub async fn run_task_checks(state: &AppState, task_id: &str, only: Option<&str>) -> (Vec<OutcomeCheck>, Option<Task>) {
+ let Ok(Some(task)) = state.db.get_task(task_id).await else { return (Vec::new(), None) };
+ for c in state.db.list_checks(task_id).await.unwrap_or_default() {
+ if only.is_some_and(|id| id != c.id) {
+ continue;
+ }
+ run_check(state, &task, &c).await;
+ }
+ let task = evaluate(state, task_id).await;
+ if let Some(t) = &task {
+ super::emit_task(state, t).await;
+ }
+ (state.db.list_checks(task_id).await.unwrap_or_default(), task)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn secrets_and_escapes_are_refused() {
+ let dir = std::env::temp_dir().join(format!("kwnt-mc-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(dir.join("sub")).unwrap();
+ std::fs::write(dir.join("sub/out.txt"), "hello 0.1.4").unwrap();
+ std::fs::write(dir.join(".env"), "KEY=x").unwrap();
+ assert!(inside(&dir, "sub/out.txt").is_ok());
+ assert!(inside(&dir, "../etc/passwd").is_err());
+ assert!(inside(&dir, "/etc/passwd").is_err());
+ assert!(inside(&dir, ".env").is_err());
+ assert!(inside(&dir, "keys/server.pem").is_err());
+ #[cfg(unix)]
+ {
+ std::os::unix::fs::symlink("/etc", dir.join("link")).unwrap();
+ assert!(inside(&dir, "link/hostname").is_err(), "a symlink out of the folder");
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[tokio::test]
+ async fn file_and_command_checks() {
+ let dir = std::env::temp_dir().join(format!("kwnt-mc-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("CHANGELOG.md"), "## 0.1.4").unwrap();
+ let d = Some(dir.as_path());
+ assert_eq!(run_spec("file_exists", &json!({"path": "CHANGELOG.md"}), d, true).await.0, "passed");
+ assert_eq!(run_spec("file_exists", &json!({"path": "nope.md"}), d, true).await.0, "failed");
+ assert_eq!(run_spec("file_contains", &json!({"path": "CHANGELOG.md", "text": "0.1.4"}), d, true).await.0, "passed");
+ assert_eq!(run_spec("file_contains", &json!({"path": "CHANGELOG.md", "text": "0.2"}), d, true).await.0, "failed");
+ let sha = hex(&Sha256::digest(b"## 0.1.4"));
+ assert_eq!(run_spec("file_sha256", &json!({"path": "CHANGELOG.md", "sha256": sha}), d, true).await.0, "passed");
+ assert_eq!(run_spec("file_exists", &json!({"path": "../x"}), d, true).await.0, "error");
+ assert_eq!(run_spec("command", &json!({"command": "test -f CHANGELOG.md"}), d, true).await.0, "passed");
+ let (status, out) = run_spec("command", &json!({"command": "echo boom; exit 3"}), d, true).await;
+ assert_eq!(status, "failed");
+ assert!(out.contains("exit code 3") && out.contains("boom"), "{out}");
+ assert_eq!(run_spec("command", &json!({"command": "true"}), None, true).await.0, "error", "no folder");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/src/server/missions/listener.rs b/src/server/missions/listener.rs
new file mode 100644
index 00000000..76594b27
--- /dev/null
+++ b/src/server/missions/listener.rs
@@ -0,0 +1,276 @@
+//! Feeds the one task board from what already happens: hand-offs (`delegation`), routine runs
+//! (`routine`) and work-ahead posts (`work_ahead`) become tasks, and the existing question,
+//! approval and human-step cards move a task to `needs_you` and back. Only while `mission_board`
+//! is on. Each update re-reads the source row, so an event that arrives late or twice (or is lost
+//! and found again by [`reconcile`]) leaves the same result.
+
+use super::checks::run_task_checks;
+use super::{lease_ms, transition, Actor};
+use crate::db::missions::{NewTask, Task, TaskChange};
+use crate::db::spaces::SpaceId;
+use crate::drivers::events::RuntimeEvent;
+use crate::server::AppState;
+use std::sync::LazyLock;
+use tokio::sync::Mutex;
+use tokio_util::sync::CancellationToken;
+
+/// One update at a time, so two events about one hand-off can't both create its task.
+static SERIAL: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
+
+/// Listens on the event bus until `shutdown`.
+pub fn spawn(state: AppState, shutdown: CancellationToken) {
+ let mut rx = state.event_sender.subscribe();
+ tokio::spawn(async move {
+ loop {
+ let ev = tokio::select! {
+ _ = shutdown.cancelled() => return,
+ ev = rx.recv() => ev,
+ };
+ match ev {
+ Ok(ev) => handle(&state, ev).await,
+ // Missed events: the next reconcile catches up
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => reconcile(&state).await,
+ Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
+ }
+ }
+ });
+}
+
+async fn handle(state: &AppState, ev: RuntimeEvent) {
+ match ev {
+ RuntimeEvent::DelegationUpdated { delegation } => {
+ if let Some(id) = delegation["id"].as_str() {
+ on_delegation(state, id).await;
+ }
+ }
+ RuntimeEvent::RoutineRun { routine_id, run_id, status } => on_routine_run(state, &routine_id, &run_id, &status).await,
+ RuntimeEvent::QuestionUpdated { .. }
+ | RuntimeEvent::HumanStepUpdated { .. }
+ | RuntimeEvent::ApprovalRequired { .. }
+ | RuntimeEvent::ApprovalWithdrawn { .. } => refresh_needs_you(state).await,
+ _ => {}
+ }
+}
+
+/// Catches up with anything missed: every system-held task against its source, every open task's
+/// cards.
+pub async fn reconcile(state: &AppState) {
+ if !super::enabled(state).await {
+ return;
+ }
+ for t in state.db.system_held().await.unwrap_or_default() {
+ match (t.source_kind.as_str(), t.source_id.as_deref()) {
+ ("delegation", Some(id)) => on_delegation(state, id).await,
+ ("routine", Some(run)) => {
+ if let Ok(Some((routine, status))) = state.db.routine_run_of(run).await {
+ on_routine_run(state, &routine, run, &status).await;
+ }
+ }
+ _ => {}
+ }
+ }
+ refresh_needs_you(state).await;
+}
+
+/// The mission a bot's own open claim is in, so a hand-off it starts joins that mission.
+async fn mission_of_holder(state: &AppState, kwant_id: &str) -> Option<String> {
+ let claims = state.db.claims_of(kwant_id).await.ok()?;
+ for c in claims.iter().filter(|c| !c.system) {
+ if let Ok(Some(t)) = state.db.get_task(&c.task_id).await {
+ if let Some(m) = t.mission_id {
+ return Some(m);
+ }
+ }
+ }
+ None
+}
+
+/// Creates a working task held by kwant for `owner` (a hand-off or routine run), or `None`.
+#[allow(clippy::too_many_arguments)]
+async fn start_held(
+ state: &AppState,
+ space: &SpaceId,
+ mission_id: Option<String>,
+ title: &str,
+ acceptance: &str,
+ owner: &str,
+ source_kind: &str,
+ source_id: &str,
+ place: (Option<String>, Option<String>, Option<String>),
+ context_id: &str,
+) -> Option<Task> {
+ let new = |mission_id: Option<String>| NewTask {
+ mission_id,
+ title: title.chars().take(200).collect(),
+ acceptance: acceptance.chars().take(4000).collect(),
+ state: "ready".into(),
+ priority: 1,
+ owner_kwant_id: None,
+ suggested_kwant_id: Some(owner.into()),
+ budget_tokens: super::DEFAULT_TASK_BUDGET,
+ max_attempts: super::DEFAULT_MAX_ATTEMPTS,
+ source_kind: source_kind.into(),
+ source_id: Some(source_id.into()),
+ channel_id: place.0.clone(),
+ direct_kwant_id: place.1.clone(),
+ thread_id: place.2.clone(),
+ created_by: "kwant".into(),
+ };
+ let task = match state.db.create_task(space, &new(mission_id.clone())).await {
+ Ok(t) => t,
+ // The mission isn't active (the trigger refuses a ready task in it): a task of its own
+ Err(_) if mission_id.is_some() => state.db.create_task(space, &new(None)).await.ok()?,
+ Err(e) => {
+ tracing::warn!(error = %e, "could not create a {source_kind} task");
+ return None;
+ }
+ };
+ hold(state, &task, owner, context_id).await;
+ state.db.get_task(&task.id).await.ok().flatten()
+}
+
+/// kwant takes `task` for `owner` (a system claim: it doesn't stop the bot from holding its own).
+async fn hold(state: &AppState, task: &Task, owner: &str, context_id: &str) {
+ match state.db.claim_task(&task.id, owner, None, Some(context_id), lease_ms(state).await, true, "kwant").await {
+ Ok(Ok(t)) => super::emit_task(state, &t).await,
+ Ok(Err(why)) => {
+ tracing::info!(task_id = %task.id, %why, "a held task wasn't claimed");
+ super::emit_task(state, task).await;
+ }
+ Err(e) => tracing::warn!(error = %e, "could not claim a held task"),
+ }
+ if let Some(m) = &task.mission_id {
+ super::emit_mission(state, m).await;
+ }
+}
+
+/// The source finished: to review (and its checks), failed, cancelled or back to ready.
+async fn finish(state: &AppState, task: &Task, to: &str, why: &str) {
+ let mut from = task.state.clone();
+ if !matches!(from.as_str(), "working" | "needs_you") {
+ return;
+ }
+ if to == "review" && from == "needs_you" {
+ // review is reached from working only
+ let _ = state.db.refresh_claim(&task.id, lease_ms(state).await).await;
+ let change = TaskChange { reason: Some(why.into()), ..Default::default() };
+ if transition(state, &task.id, "needs_you", "working", Actor::Kwant, "kwant", change).await.is_err() {
+ return;
+ }
+ from = "working".into();
+ }
+ let change = TaskChange { reason: Some(why.into()), ..Default::default() };
+ if transition(state, &task.id, &from, to, Actor::Kwant, "kwant", change).await.is_ok() && to == "review" {
+ run_task_checks(state, &task.id, None).await;
+ }
+}
+
+pub async fn on_delegation(state: &AppState, delegation_id: &str) {
+ if !super::enabled(state).await {
+ return;
+ }
+ let _serial = SERIAL.lock().await;
+ let Ok(Some(d)) = state.db.get_delegation(delegation_id).await else { return };
+ let task = state.db.task_by_source("delegation", &d.id).await.ok().flatten();
+ let live = matches!(d.status.as_str(), "queued" | "running");
+ match (task, d.status.as_str()) {
+ (None, _) if live => {
+ let Ok(Some(space)) = state.db.space_of_kwant(&d.specialist_kwant_id).await else { return };
+ let mission = mission_of_holder(state, &d.lead_kwant_id).await;
+ let title = if d.title.trim().is_empty() { d.task.lines().next().unwrap_or("Hand-off").to_string() } else { d.title.clone() };
+ let place = (None, None, Some(d.thread_id.clone()));
+ start_held(state, &space, mission, &title, &d.task, &d.specialist_kwant_id, "delegation", &d.id, place, &d.thread_id).await;
+ }
+ (Some(t), _) if live && t.state == "ready" => hold(state, &t, &d.specialist_kwant_id, &d.thread_id).await,
+ (Some(t), _) if live => {
+ // Still going: keep kwant's lease on it
+ let _ = state.db.refresh_claim(&t.id, lease_ms(state).await).await;
+ }
+ (Some(t), "completed") => finish(state, &t, "review", "the hand-off finished").await,
+ (Some(t), "failed") => finish(state, &t, "failed", d.error.as_deref().unwrap_or("the hand-off failed")).await,
+ (Some(t), "cancelled") => finish(state, &t, "cancelled", "the hand-off was cancelled").await,
+ (Some(t), "interrupted") => finish(state, &t, "ready", "a restart interrupted the hand-off").await,
+ _ => {}
+ }
+}
+
+pub async fn on_routine_run(state: &AppState, routine_id: &str, run_id: &str, status: &str) {
+ if !super::enabled(state).await {
+ return;
+ }
+ let _serial = SERIAL.lock().await;
+ let task = state.db.task_by_source("routine", run_id).await.ok().flatten();
+ match (task, status) {
+ (None, "running") => {
+ let Ok(Some(r)) = state.db.get_routine(routine_id).await else { return };
+ let space = SpaceId::new(&r.space_id);
+ let context = r.channel_id.clone().or_else(|| r.thread_id.clone()).unwrap_or_else(|| r.kwant_id.clone());
+ let direct = if r.channel_id.is_none() && r.thread_id.is_none() { Some(r.kwant_id.clone()) } else { None };
+ let place = (r.channel_id.clone(), direct, r.thread_id.clone());
+ let title = format!("Routine: {}", r.name);
+ start_held(state, &space, None, &title, &r.instructions, &r.kwant_id, "routine", run_id, place, &context).await;
+ }
+ (Some(t), "running") => {
+ let _ = state.db.refresh_claim(&t.id, lease_ms(state).await).await;
+ }
+ (Some(t), "ok") => finish(state, &t, "review", "the routine run finished").await,
+ (Some(t), "error") => finish(state, &t, "failed", "the routine run failed").await,
+ _ => {}
+ }
+}
+
+/// Working tasks whose owner waits on a card go to `needs_you`; back to `working` (fresh lease)
+/// once nothing is open.
+pub async fn refresh_needs_you(state: &AppState) {
+ if !super::enabled(state).await {
+ return;
+ }
+ let _serial = SERIAL.lock().await;
+ let mut open = state.db.tasks_in_state("working").await.unwrap_or_default();
+ open.extend(state.db.tasks_in_state("needs_you").await.unwrap_or_default());
+ for t in open {
+ let waiting = !super::needs_you(state, &t).await.is_empty();
+ match (t.state.as_str(), waiting) {
+ ("working", true) => {
+ let change = TaskChange { reason: Some("waiting on the person".into()), ..Default::default() };
+ let _ = transition(state, &t.id, "working", "needs_you", Actor::Kwant, "kwant", change).await;
+ }
+ ("needs_you", false) => {
+ let _ = state.db.refresh_claim(&t.id, lease_ms(state).await).await;
+ let change = TaskChange { reason: Some("the person answered".into()), ..Default::default() };
+ let _ = transition(state, &t.id, "needs_you", "working", Actor::Kwant, "kwant", change).await;
+ }
+ _ => {}
+ }
+ }
+}
+
+/// A work-ahead run posted `text`: a task in `review` owned by the lead, so the person sees it on
+/// the board and verifies it (or a teammate reviews it).
+pub async fn on_work_ahead_posted(state: &AppState, lead: &crate::db::models::Kwant, place: (Option<String>, Option<String>, Option<String>), run_id: &str, text: &str) {
+ if !super::enabled(state).await {
+ return;
+ }
+ let space = SpaceId::new(&lead.space_id);
+ let first = text.lines().find(|l| !l.trim().is_empty()).unwrap_or("Worked ahead").trim();
+ let new = NewTask {
+ mission_id: None,
+ title: format!("Worked ahead: {}", first.chars().take(150).collect::<String>()),
+ acceptance: "The person finds the work-ahead result useful.".into(),
+ state: "review".into(),
+ priority: 1,
+ owner_kwant_id: Some(lead.id.clone()),
+ suggested_kwant_id: Some(lead.id.clone()),
+ budget_tokens: super::DEFAULT_TASK_BUDGET,
+ max_attempts: 1,
+ source_kind: "work_ahead".into(),
+ source_id: Some(run_id.into()),
+ channel_id: place.0,
+ direct_kwant_id: place.1,
+ thread_id: place.2,
+ created_by: "kwant".into(),
+ };
+ if let Err(e) = super::create_task(state, &space, new).await {
+ tracing::warn!(error = %e, "could not create a work-ahead task");
+ }
+}
diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rs
new file mode 100644
index 00000000..96c0dd11
--- /dev/null
+++ b/src/server/missions/mod.rs
@@ -0,0 +1,1022 @@
+//! Mission Control + Verified Outcomes (Phase A). Contract: docs/mission-control.md.
+//!
+//! One task universe: planned mission tasks, the person's tasks, hand-offs, routine runs, Loose
+//! Ends taken on and work-ahead runs are all rows in `tasks`. The rules:
+//!
+//! - a task is `verified` only through a passing outcome check that isn't its owner's own claim
+//! ([`verdict`], plus a SQLite trigger);
+//! - a task is `ready` only when its mission is active and its dependencies are verified;
+//! - claims are atomic leases that expire ([`crate::db::Database::claim_task`]);
+//! - `task_events` is append-only (triggers);
+//! - a claim never starts past the mission's budget;
+//! - nothing here widens a bot's permissions: the bot tools only touch the board, `command` checks
+//! a bot adds run only after the person approves them, and person actions are person-only routes.
+
+pub mod checks;
+pub mod listener;
+pub mod routes;
+pub mod runner;
+pub mod tools;
+
+use super::AppState;
+use crate::db::missions::{Mission, NewCheck, NewTask, OutcomeCheck, Task, TaskChange};
+use crate::db::models::{MessageExtra, NewMessage};
+use crate::db::spaces::SpaceId;
+use crate::db::DbError;
+use crate::drivers::events::RuntimeEvent;
+use serde_json::{json, Value};
+
+/// Setting key: `"true"` turns Mission Control on. Off by default.
+pub const SETTING: &str = "mission_board";
+pub const LEASE_SETTING: &str = "mission_lease_minutes";
+pub const BUDGET_SETTING: &str = "mission_default_budget_tokens";
+pub const DEFAULT_LEASE_MINUTES: i64 = 30;
+pub const LEASE_RANGE: (i64, i64) = (5, 240);
+pub const DEFAULT_BUDGET: i64 = 200_000;
+pub const BUDGET_RANGE: (i64, i64) = (1_000, 5_000_000);
+/// A task's budget when none is given (capped at its mission's budget).
+pub const DEFAULT_TASK_BUDGET: i64 = 50_000;
+pub const MAX_PLAN_TASKS: usize = 30;
+pub const DEFAULT_MAX_ATTEMPTS: i64 = 3;
+/// Longest stored check output.
+pub const MAX_EXCERPT: usize = 2_000;
+
+pub async fn enabled(state: &AppState) -> bool {
+ matches!(state.db.get_setting(SETTING).await.ok().flatten().as_deref().map(str::trim), Some("true" | "1" | "on"))
+}
+
+async fn int_setting(state: &AppState, key: &str, range: (i64, i64), default: i64) -> i64 {
+ state
+ .db
+ .get_setting(key)
+ .await
+ .ok()
+ .flatten()
+ .and_then(|v| v.trim().parse::<i64>().ok())
+ .filter(|n| (range.0..=range.1).contains(n))
+ .unwrap_or(default)
+}
+
+pub async fn lease_minutes(state: &AppState) -> i64 {
+ int_setting(state, LEASE_SETTING, LEASE_RANGE, DEFAULT_LEASE_MINUTES).await
+}
+
+pub async fn lease_ms(state: &AppState) -> i64 {
+ lease_minutes(state).await * 60_000
+}
+
+pub async fn default_budget(state: &AppState) -> i64 {
+ int_setting(state, BUDGET_SETTING, BUDGET_RANGE, DEFAULT_BUDGET).await
+}
+
+/// Why the mission settings in a `POST /api/settings` are refused, if they are.
+pub fn settings_error(lease: Option<i64>, budget: Option<i64>) -> Option<String> {
+ if lease.is_some_and(|m| !(LEASE_RANGE.0..=LEASE_RANGE.1).contains(&m)) {
+ return Some(format!("mission_lease_minutes must be {}–{}", LEASE_RANGE.0, LEASE_RANGE.1));
+ }
+ if budget.is_some_and(|n| !(BUDGET_RANGE.0..=BUDGET_RANGE.1).contains(&n)) {
+ return Some(format!("mission_default_budget_tokens must be {}–{}", BUDGET_RANGE.0, BUDGET_RANGE.1));
+ }
+ None
+}
+
+/// Who moves a task.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Actor {
+ /// The bot that holds (owns) the task.
+ Owner,
+ /// The person, through a person-only route.
+ Person,
+ /// kwant itself: checks, leases, hand-offs, routine runs, cards.
+ Kwant,
+}
+
+/// Whether `actor` may move a task from `from` to `to`. Conditions beyond the pair (live claim,
+/// dependencies, passing checks, budget) are checked where the move happens and again by the
+/// SQLite triggers.
+pub fn allowed(from: &str, to: &str, actor: Actor) -> bool {
+ use Actor::*;
+ let open = matches!(from, "backlog" | "ready" | "working" | "needs_you" | "review" | "blocked" | "failed");
+ match (from, to) {
+ ("backlog", "ready") => actor == Kwant,
+ ("ready", "working") => true,
+ ("working", "review") => matches!(actor, Owner | Kwant),
+ ("working", "ready") => matches!(actor, Owner | Kwant),
+ ("working", "needs_you") | ("needs_you", "working") => actor == Kwant,
+ // A hand-off or routine run that failed or stopped
+ ("working" | "needs_you", "failed") => actor == Kwant,
+ ("needs_you", "ready") => actor == Kwant,
+ ("backlog" | "ready" | "working" | "needs_you", "blocked") => true,
+ ("blocked", "backlog") => matches!(actor, Owner | Person),
+ ("review", "verified") => actor == Kwant,
+ ("review", "ready") => matches!(actor, Kwant | Person),
+ ("review", "failed") => actor == Kwant,
+ ("failed", "ready") => actor == Person,
+ (_, "cancelled") => open && matches!(actor, Person | Kwant),
+ _ => false,
+ }
+}
+
+/// Why a move didn't happen.
+#[derive(Debug)]
+pub enum MoveError {
+ NotAllowed(String),
+ /// The task wasn't in `from` any more (someone else moved it).
+ Stale,
+ Missing,
+ Db(DbError),
+}
+
+impl std::fmt::Display for MoveError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ MoveError::NotAllowed(s) => write!(f, "{s}"),
+ MoveError::Stale => write!(f, "the task changed meanwhile; look at it again"),
+ MoveError::Missing => write!(f, "no such task"),
+ MoveError::Db(DbError::Sqlx(e)) => write!(f, "refused: {}", trigger_message(&e.to_string())),
+ MoveError::Db(e) => write!(f, "{e}"),
+ }
+ }
+}
+
+/// The plain sentence of a trigger's `RAISE(ABORT, …)`.
+fn trigger_message(e: &str) -> String {
+ for known in ["append-only", "verified only", "live lease", "ready only", "is final", "before work"] {
+ if e.contains(known) {
+ return e.rsplit(": ").next().unwrap_or(e).to_string();
+ }
+ }
+ e.to_string()
+}
+
+/// Moves `task_id` from `from` to `to` as `actor` (logged as `actor_id`), then tells the board
+/// and does what follows: dependents become ready, a mission whose tasks are all done is done.
+pub async fn transition(
+ state: &AppState,
+ task_id: &str,
+ from: &str,
+ to: &str,
+ actor: Actor,
+ actor_id: &str,
+ change: TaskChange,
+) -> Result<Task, MoveError> {
+ if !allowed(from, to, actor) {
+ return Err(MoveError::NotAllowed(format!("a task can't go from {from} to {to} that way")));
+ }
+ if to == "verified" {
+ let task = state.db.get_task(task_id).await.map_err(MoveError::Db)?.ok_or(MoveError::Missing)?;
+ let checks = state.db.list_checks(task_id).await.map_err(MoveError::Db)?;
+ let since = review_since(state, task_id).await;
+ if verdict(&task, &checks, since) != Verdict::Pass {
+ return Err(MoveError::NotAllowed("a task is verified only by a passing check that isn't its owner's".into()));
+ }
+ }
+ let moved = state.db.move_task(task_id, from, to, actor_id, &change).await.map_err(MoveError::Db)?;
+ if !moved {
+ return Err(if state.db.get_task(task_id).await.ok().flatten().is_some() { MoveError::Stale } else { MoveError::Missing });
+ }
+ let task = state.db.get_task(task_id).await.map_err(MoveError::Db)?.ok_or(MoveError::Missing)?;
+ emit_task(state, &task).await;
+ after_move(state, &task, to).await;
+ Ok(task)
+}
+
+async fn after_move(state: &AppState, task: &Task, to: &str) {
+ let Some(mid) = task.mission_id.clone() else {
+ if matches!(to, "verified" | "failed") {
+ task_chat_line(state, task, None).await;
+ }
+ if to == "verified" {
+ for t in state.db.dependents_promotable(&task.id).await.unwrap_or_default() {
+ to_ready(state, &t.id).await;
+ }
+ }
+ return;
+ };
+ let mission = state.db.get_mission(&mid).await.ok().flatten();
+ if matches!(to, "verified" | "failed") {
+ task_chat_line(state, task, mission.as_ref()).await;
+ }
+ if to == "verified" || to == "cancelled" {
+ promote(state, &mid).await;
+ maybe_finish(state, &mid).await;
+ }
+ emit_mission(state, &mid).await;
+}
+
+/// Moves the mission's backlog tasks whose dependencies are all verified to ready.
+pub async fn promote(state: &AppState, mission_id: &str) {
+ let Ok(Some(m)) = state.db.get_mission(mission_id).await else { return };
+ if m.status != "active" {
+ return;
+ }
+ for t in state.db.promotable(mission_id).await.unwrap_or_default() {
+ to_ready(state, &t.id).await;
+ }
+}
+
+async fn to_ready(state: &AppState, task_id: &str) {
+ let change = TaskChange { reason: Some("nothing it waits on is open".into()), ..Default::default() };
+ if state.db.move_task(task_id, "backlog", "ready", "kwant", &change).await.unwrap_or(false) {
+ emit_task_id(state, task_id).await;
+ }
+}
+
+/// A backlog task outside a draft mission, with every dependency verified, becomes ready.
+pub async fn promote_one(state: &AppState, task: &Task) {
+ match &task.mission_id {
+ Some(m) => promote(state, m).await,
+ None => {
+ let deps = state.db.dependencies_of(&task.id).await.unwrap_or_default();
+ if task.state == "backlog" && deps.iter().all(|d| d.1 == "verified") {
+ to_ready(state, &task.id).await;
+ }
+ }
+ }
+}
+
+/// A mission whose tasks are all verified or cancelled, at least one verified, is done.
+pub async fn maybe_finish(state: &AppState, mission_id: &str) {
+ let counts = state.db.mission_counts(mission_id).await.unwrap_or_default();
+ let verified = counts.iter().find(|(s, _)| s == "verified").map_or(0, |c| c.1);
+ let open = counts.iter().filter(|(s, _)| s != "verified" && s != "cancelled").map(|c| c.1).sum::<i64>();
+ if verified == 0 || open > 0 {
+ return;
+ }
+ if state.db.set_mission_status(mission_id, "active", "done", Some("kwant")).await.unwrap_or(false) {
+ if let Ok(Some(m)) = state.db.get_mission(mission_id).await {
+ mission_chat_line(state, &m, format!("Mission \"{}\" is done: {verified} task(s) verified.", m.title)).await;
+ }
+ }
+}
+
+// Verification
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Verdict {
+ /// Every required check passed and one passing check isn't the owner's.
+ Pass,
+ /// A required check failed or couldn't run.
+ Fail(String),
+ /// Not yet: no check, or a required one hasn't run.
+ Waiting,
+}
+
+/// Checks kwant re-runs each time the task goes to review; peer reviews and the person's verify
+/// count only when given since then (`since`, RFC 3339 of the last move to review).
+fn fresh(c: &OutcomeCheck, since: Option<chrono::DateTime<chrono::Utc>>) -> bool {
+ if crate::db::missions::KWANT_CHECK_KINDS.contains(&c.kind.as_str()) {
+ return true;
+ }
+ match (since, c.finished_at) {
+ (Some(s), Some(f)) => f >= s,
+ (None, _) => true,
+ (Some(_), None) => false,
+ }
+}
+
+/// Whether `c` can count toward verifying `task`: approved, and not the owner's own check unless
+/// the person approved it, on its own or as part of the mission's plan (a bot that becomes the
+/// owner after adding a check doesn't get it free).
+pub fn counts(task: &Task, c: &OutcomeCheck) -> bool {
+ let own = task.owner_kwant_id.as_deref().is_some_and(|o| o == c.requested_by);
+ c.approved && (!own || matches!(c.approved_by.as_deref(), Some("person" | "mission")))
+}
+
+/// The rule for `review → verified`, on the task's checks: every required check that counts has
+/// passed (none failed, pending or waiting for approval) and at least one of them is independent
+/// of the owner. A required check waiting for approval holds the task in review, unless the
+/// person verified it themselves. Optional checks are shown but never gate or verify.
+pub fn verdict(task: &Task, checks: &[OutcomeCheck], since: Option<chrono::DateTime<chrono::Utc>>) -> Verdict {
+ let owner = task.owner_kwant_id.as_deref().unwrap_or("");
+ let required: Vec<&OutcomeCheck> = checks.iter().filter(|c| c.required).collect();
+ let live: Vec<&OutcomeCheck> = required.iter().copied().filter(|c| counts(task, c) && fresh(c, since)).collect();
+ if let Some(bad) = live.iter().find(|c| matches!(c.status.as_str(), "failed" | "error")) {
+ return Verdict::Fail(format!("{} check {}", bad.kind, bad.status));
+ }
+ if live.iter().any(|c| c.status != "passed") {
+ return Verdict::Waiting;
+ }
+ let by_person = live.iter().any(|c| c.kind == "person");
+ if !by_person && required.iter().any(|c| !c.approved) {
+ return Verdict::Waiting;
+ }
+ let independent = live.iter().any(|c| c.checked_by.as_deref().is_some_and(|by| !by.is_empty() && by != owner));
+ if independent {
+ Verdict::Pass
+ } else {
+ Verdict::Waiting
+ }
+}
+
+/// When the task last went to review.
+pub async fn review_since(state: &AppState, task_id: &str) -> Option<chrono::DateTime<chrono::Utc>> {
+ let events = state.db.task_events(task_id, 500).await.ok()?;
+ events.iter().rev().find(|e| e.to_state.as_deref() == Some("review")).map(|e| e.created_at)
+}
+
+/// Looks at a task in review after a check result: verified, back to ready, failed, or waits.
+pub async fn evaluate(state: &AppState, task_id: &str) -> Option<Task> {
+ let task = state.db.get_task(task_id).await.ok().flatten()?;
+ if task.state != "review" {
+ return Some(task);
+ }
+ let checks = state.db.list_checks(task_id).await.unwrap_or_default();
+ let since = review_since(state, task_id).await;
+ match verdict(&task, &checks, since) {
+ Verdict::Pass => {
+ let change = TaskChange { kind: "state".into(), reason: Some("its checks passed".into()), ..Default::default() };
+ transition(state, task_id, "review", "verified", Actor::Kwant, "kwant", change).await.ok().or(Some(task))
+ }
+ Verdict::Fail(why) => {
+ let last = task.attempts + 1 >= task.max_attempts;
+ let to = if last { "failed" } else { "ready" };
+ let change = TaskChange { reason: Some(why), attempt: true, ..Default::default() };
+ transition(state, task_id, "review", to, Actor::Kwant, "kwant", change).await.ok().or(Some(task))
+ }
+ Verdict::Waiting => Some(task),
+ }
+}
+
+/// `checks_summary` of a task: `passed` only when [`verdict`] could pass on them. Counts the
+/// checks that count (see [`counts`]); `needs_approval` is how many wait for the person.
+pub fn checks_summary(task: &Task, checks: &[OutcomeCheck]) -> Value {
+ let live: Vec<&OutcomeCheck> = checks.iter().filter(|c| counts(task, c)).collect();
+ let waiting = checks.iter().filter(|c| !c.approved).count();
+ // An optional check waiting for approval is listed but doesn't hold the task (see [`verdict`])
+ let holding = checks.iter().any(|c| c.required && !c.approved);
+ let gating = |c: &&&OutcomeCheck| c.required;
+ let passed = live.iter().filter(|c| c.status == "passed").count();
+ let failed = live.iter().filter(gating).filter(|c| matches!(c.status.as_str(), "failed" | "error")).count();
+ let status = if live.is_empty() && waiting == 0 {
+ "not_checked"
+ } else if failed > 0 {
+ "failed"
+ } else if holding || live.iter().filter(gating).any(|c| c.status != "passed") || !live.iter().any(|c| c.required) {
+ "pending"
+ } else {
+ "passed"
+ };
+ json!({"status": status, "passed": passed, "failed": failed, "needs_approval": waiting, "total": checks.len()})
+}
+
+// Budget
+
+/// Adds a turn's fresh tokens to the task `kwant_id` worked on in `context_id`: a claim kwant
+/// holds for it there (a hand-off, a routine run), else its own claim. A claim taken in `turn_id`
+/// or released since `turn_started_ms` counts too, so a bot that finishes its task inside the turn
+/// (`task_update review` releases the claim) still pays for that turn. Renews an open lease, and
+/// blocks the task when it goes over its own budget.
+pub async fn spend(state: &AppState, kwant_id: &str, context_id: &str, turn_id: Option<&str>, turn_started_ms: i64, fresh: u64) {
+ if fresh == 0 {
+ return;
+ }
+ let Ok(claims) = state.db.spend_claims(kwant_id, turn_id, turn_started_ms).await else { return };
+ let here = |c: &&crate::db::missions::Claim| c.context_id.as_deref().is_none_or(|x| x == context_id);
+ let claim = claims
+ .iter()
+ .find(|c| c.system && c.context_id.as_deref() == Some(context_id))
+ .or_else(|| claims.iter().filter(here).find(|c| !c.system));
+ let Some(claim) = claim else { return };
+ let tokens = i64::try_from(fresh).unwrap_or(i64::MAX);
+ if state.db.spend_on_task(&claim.task_id, tokens).await.is_err() {
+ return;
+ }
+ let _ = state.db.renew_claim(&claim.task_id, lease_ms(state).await).await;
+ let Ok(Some(task)) = state.db.get_task(&claim.task_id).await else { return };
+ if task.spent_tokens > task.budget_tokens && matches!(task.state.as_str(), "working" | "needs_you") {
+ let change = TaskChange {
+ kind: "budget".into(),
+ reason: Some("budget".into()),
+ detail: Some(json!({"spent_tokens": task.spent_tokens, "budget_tokens": task.budget_tokens})),
+ ..Default::default()
+ };
+ let _ = transition(state, &task.id, &task.state, "blocked", Actor::Kwant, "kwant", change).await;
+ } else {
+ emit_task(state, &task).await;
+ }
+ if let Some(m) = &task.mission_id {
+ emit_mission(state, m).await;
+ }
+}
+
+/// Working tasks whose lease ran out go back to ready (one attempt used).
+pub async fn sweep_leases(state: &AppState) -> usize {
+ let mut n = 0;
+ for t in state.db.expired_working().await.unwrap_or_default() {
+ let change = TaskChange { kind: "lease_expired".into(), reason: Some("the lease ran out".into()), attempt: true, ..Default::default() };
+ if transition(state, &t.id, "working", "ready", Actor::Kwant, "kwant", change).await.is_ok() {
+ n += 1;
+ }
+ }
+ n
+}
+
+// Board JSON and events
+
+pub(crate) async fn name_of(state: &AppState, id: Option<&str>) -> Option<String> {
+ match id? {
+ "person" => Some("You".into()),
+ "kwant" => Some("kwant".into()),
+ id => state.db.get_kwant(id).await.ok().flatten().map(|k| k.name),
+ }
+}
+
+/// The open cards (questions, approvals, human steps) the task's owner waits on the person with.
+pub async fn needs_you(state: &AppState, task: &Task) -> Vec<Value> {
+ if task.state == "review" {
+ return check_approvals(state, task).await;
+ }
+ let Some(owner) = &task.owner_kwant_id else { return Vec::new() };
+ if !matches!(task.state.as_str(), "working" | "needs_you") {
+ return Vec::new();
+ }
+ let claim = state.db.open_claim(&task.id).await.ok().flatten();
+ let context = claim.as_ref().and_then(|c| c.context_id.clone());
+ let cards = state.db.open_cards_of(owner).await.unwrap_or_default();
+ cards
+ .into_iter()
+ .filter(|(kind, _, _, at)| kind == "approval" || context.is_none() || at.as_deref() == context.as_deref())
+ .map(|(kind, id, text, _)| json!({"kind": kind, "id": id, "text": text.chars().take(200).collect::<String>()}))
+ .collect()
+}
+
+/// A task in review waits on the person for each check that needs their approval
+/// (`{"kind": "check_approval", "id": <check id>, "text"}`).
+pub async fn check_approvals(state: &AppState, task: &Task) -> Vec<Value> {
+ let checks = state.db.list_checks(&task.id).await.unwrap_or_default();
+ checks
+ .iter()
+ .filter(|c| !c.approved)
+ .map(|c| {
+ let text = format!("Allow this check: {} {}", c.kind, c.spec_value());
+ json!({"kind": "check_approval", "id": c.id, "text": text.chars().take(200).collect::<String>()})
+ })
+ .collect()
+}
+
+pub async fn task_json(state: &AppState, task: &Task) -> Value {
+ let mut v = serde_json::to_value(task).unwrap_or(Value::Null);
+ let deps = state.db.dependencies_of(&task.id).await.unwrap_or_default();
+ let checks = state.db.list_checks(&task.id).await.unwrap_or_default();
+ let claim = state.db.open_claim(&task.id).await.ok().flatten().filter(|c| c.expires_at > crate::db::missions::now_ms());
+ let mission_title = match &task.mission_id {
+ Some(m) => state.db.get_mission(m).await.ok().flatten().map(|m| m.title),
+ None => None,
+ };
+ if let Some(obj) = v.as_object_mut() {
+ obj.insert("owner_name".into(), json!(name_of(state, task.owner_kwant_id.as_deref()).await));
+ obj.insert("mission_title".into(), json!(mission_title));
+ obj.insert("depends_on".into(), json!(deps.iter().map(|d| &d.0).collect::<Vec<_>>()));
+ obj.insert("waiting_on".into(), json!(deps.iter().filter(|d| d.1 != "verified").map(|d| &d.0).collect::<Vec<_>>()));
+ obj.insert(
+ "claim".into(),
+ claim.map_or(Value::Null, |c| {
+ json!({"kwant_id": c.kwant_id, "claimed_at": c.claimed_at_utc(), "expires_at": c.expires_at_utc()})
+ }),
+ );
+ obj.insert("needs_you".into(), json!(needs_you(state, task).await));
+ obj.insert("checks_summary".into(), checks_summary(task, &checks));
+ }
+ v
+}
+
+pub async fn mission_json(state: &AppState, m: &Mission) -> Value {
+ let mut v = serde_json::to_value(m).unwrap_or(Value::Null);
+ let reserved = state.db.mission_reserved(&m.id).await.unwrap_or(0);
+ let mut counts = serde_json::Map::new();
+ for s in crate::db::missions::TASK_STATES {
+ counts.insert(s.into(), json!(0));
+ }
+ for (s, n) in state.db.mission_counts(&m.id).await.unwrap_or_default() {
+ counts.insert(s, json!(n));
+ }
+ if let Some(obj) = v.as_object_mut() {
+ obj.remove("workspace_path");
+ obj.insert("lead_name".into(), json!(name_of(state, Some(&m.lead_kwant_id)).await));
+ obj.insert("reserved_tokens".into(), json!(reserved));
+ obj.insert("over_budget".into(), json!(m.spent_tokens >= m.budget_tokens));
+ obj.insert("counts".into(), Value::Object(counts));
+ }
+ v
+}
+
+pub fn check_json(task: &Task, c: &OutcomeCheck, checked_by_name: Option<String>) -> Value {
+ let mut v = serde_json::to_value(c).unwrap_or(Value::Null);
+ if let Some(obj) = v.as_object_mut() {
+ obj.insert("spec".into(), c.spec_value());
+ obj.insert("checked_by_name".into(), json!(checked_by_name));
+ obj.insert("counts".into(), json!(counts(task, c)));
+ }
+ v
+}
+
+pub async fn checks_json(state: &AppState, task: &Task, checks: &[OutcomeCheck]) -> Vec<Value> {
+ let mut out = Vec::new();
+ for c in checks {
+ out.push(check_json(task, c, name_of(state, c.checked_by.as_deref()).await));
+ }
+ out
+}
+
+pub async fn emit_task(state: &AppState, task: &Task) {
+ let task = task_json(state, task).await;
+ let _ = state.event_sender.send(RuntimeEvent::TaskUpdated { task });
+}
+
+pub async fn emit_task_id(state: &AppState, task_id: &str) {
+ if let Ok(Some(t)) = state.db.get_task(task_id).await {
+ emit_task(state, &t).await;
+ }
+}
+
+pub async fn emit_mission(state: &AppState, mission_id: &str) {
+ if let Ok(Some(m)) = state.db.get_mission(mission_id).await {
+ let mission = mission_json(state, &m).await;
+ let _ = state.event_sender.send(RuntimeEvent::MissionUpdated { mission });
+ }
+}
+
+// Chat lines
+
+async fn post_line(state: &AppState, channel_id: Option<String>, direct_kwant_id: Option<String>, thread_id: Option<String>, sender: &str, text: String, meta: Value) {
+ if channel_id.is_none() && direct_kwant_id.is_none() && thread_id.is_none() {
+ return;
+ }
+ let msg = NewMessage {
+ channel_id: if thread_id.is_some() { None } else { channel_id },
+ direct_kwant_id: if thread_id.is_some() { None } else { direct_kwant_id },
+ sender_role: "kwant".into(),
+ sender_id: sender.into(),
+ text,
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let extra = MessageExtra { thread_id: thread_id.clone(), meta: Some(meta) };
+ let Ok(saved) = state.db.insert_message_with(&msg, &extra).await else { return };
+ if let Some(t) = &thread_id {
+ let _ = state.db.touch_thread(t).await;
+ }
+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or(Value::Null) });
+}
+
+/// A short line in the mission's chat (`meta.kind = "mission"`).
+pub async fn mission_chat_line(state: &AppState, m: &Mission, text: String) {
+ let meta = json!({"kind": "mission", "mission_id": m.id, "status": m.status});
+ post_line(state, m.channel_id.clone(), m.direct_kwant_id.clone(), m.thread_id.clone(), &m.lead_kwant_id, text, meta).await;
+}
+
+async fn task_chat_line(state: &AppState, t: &Task, m: Option<&Mission>) {
+ let text = match t.state.as_str() {
+ "verified" => format!("Verified: \"{}\" passed its checks.", t.title),
+ "failed" => format!("Failed: \"{}\" didn't pass its checks after {} attempts. Retry it on the board.", t.title, t.attempts),
+ _ => return,
+ };
+ let meta = json!({"kind": "mission", "task_id": t.id, "mission_id": t.mission_id, "state": t.state});
+ let sender = t.owner_kwant_id.clone().or_else(|| m.map(|m| m.lead_kwant_id.clone())).unwrap_or_else(|| "kwant".into());
+ match m {
+ Some(m) => post_line(state, m.channel_id.clone(), m.direct_kwant_id.clone(), m.thread_id.clone(), &sender, text, meta).await,
+ None => post_line(state, t.channel_id.clone(), t.direct_kwant_id.clone(), t.thread_id.clone(), &sender, text, meta).await,
+ }
+}
+
+// Plans: shared by the `mission_plan` tool and `POST /api/missions`
+
+#[derive(Debug, Clone, serde::Deserialize)]
+pub struct PlanTask {
+ pub key: Option<String>,
+ pub title: String,
+ #[serde(default)]
+ pub acceptance: String,
+ pub owner: Option<String>,
+ pub priority: Option<i64>,
+ #[serde(default)]
+ pub depends_on: Vec<String>,
+ pub budget_tokens: Option<i64>,
+ #[serde(default)]
+ pub checks: Vec<PlanCheck>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+pub struct PlanCheck {
+ pub kind: String,
+ #[serde(default)]
+ pub spec: Value,
+ pub required: Option<bool>,
+}
+
+/// Who made a plan, and so whether its `command` checks are approved with the mission.
+pub struct PlanBy<'a> {
+ pub created_by: &'a str,
+ /// Active at once (the person's plan) or a draft waiting for the person.
+ pub active: bool,
+}
+
+/// Where a mission lives.
+#[derive(Default, Clone)]
+pub struct PlanPlace {
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ pub workspace_path: String,
+}
+
+/// Validates a check a bot or the person adds. Returns whether it may run without the person's
+/// approval: `command` needs it unless `person_ok`, an `http` check of a local or private URL too.
+pub fn validate_check(kind: &str, spec: &Value, person_ok: bool) -> Result<bool, String> {
+ let s = |k: &str| spec[k].as_str().map(str::trim).filter(|v| !v.is_empty());
+ match kind {
+ "command" => {
+ let cmd = s("command").ok_or("a command check needs spec.command")?;
+ if cmd.len() > 2000 {
+ return Err("spec.command is too long".into());
+ }
+ if spec["timeout_secs"].as_u64().is_some_and(|t| !(1..=checks::MAX_COMMAND_SECS).contains(&t)) {
+ return Err(format!("spec.timeout_secs must be 1–{}", checks::MAX_COMMAND_SECS));
+ }
+ Ok(person_ok)
+ }
+ "http" => {
+ let url = s("url").ok_or("an http check needs spec.url")?;
+ if !(url.starts_with("http://") || url.starts_with("https://")) {
+ return Err("spec.url must start with http:// or https://".into());
+ }
+ // Stricter than WebFetch: kwnt fetches it itself, so no local dev-server exemption
+ Ok(person_ok || crate::mcp::fetch_risk::public_only(url).is_ok())
+ }
+ "file_exists" => {
+ s("path").ok_or("a file check needs spec.path")?;
+ Ok(true)
+ }
+ "file_contains" => {
+ s("path").ok_or("a file check needs spec.path")?;
+ spec["text"].as_str().filter(|t| !t.is_empty()).ok_or("file_contains needs spec.text")?;
+ Ok(true)
+ }
+ "file_sha256" => {
+ s("path").ok_or("a file check needs spec.path")?;
+ let h = s("sha256").ok_or("file_sha256 needs spec.sha256")?;
+ if h.len() != 64 || !h.chars().all(|c| c.is_ascii_hexdigit()) {
+ return Err("spec.sha256 must be 64 hex characters".into());
+ }
+ Ok(true)
+ }
+ "peer_review" | "person" => Err(format!("{kind} checks are recorded by task_review or the person's Verify, not added")),
+ other => Err(format!("unknown check kind {other}")),
+ }
+}
+
+/// Resolves a bot by id or name in `space`.
+pub async fn bot_in_space(state: &AppState, space: &SpaceId, who: &str) -> Option<crate::db::models::Kwant> {
+ let who = who.trim().trim_start_matches('@');
+ let bots = state.db.list_kwants(space).await.ok()?;
+ bots.iter().find(|k| k.id == who).or_else(|| bots.iter().find(|k| k.name.eq_ignore_ascii_case(who))).cloned()
+}
+
+/// Creates a mission and its tasks (backlog, or ready when active and free of dependencies).
+#[allow(clippy::too_many_arguments)]
+pub async fn create_plan(
+ state: &AppState,
+ space: &SpaceId,
+ lead: &crate::db::models::Kwant,
+ title: &str,
+ goal: &str,
+ budget: Option<i64>,
+ tasks: &[PlanTask],
+ by: PlanBy<'_>,
+ place: PlanPlace,
+) -> Result<(Mission, Vec<Task>), String> {
+ let title = title.trim();
+ if title.is_empty() || title.chars().count() > 200 {
+ return Err("title is required (at most 200 characters)".into());
+ }
+ if tasks.len() > MAX_PLAN_TASKS {
+ return Err(format!("a mission has at most {MAX_PLAN_TASKS} tasks"));
+ }
+ let budget = match budget {
+ Some(b) if !(BUDGET_RANGE.0..=BUDGET_RANGE.1).contains(&b) => {
+ return Err(format!("budget_tokens must be {}–{}", BUDGET_RANGE.0, BUDGET_RANGE.1))
+ }
+ Some(b) => b,
+ None => default_budget(state).await,
+ };
+ // Everything is checked before anything is written
+ let mut keys = std::collections::HashMap::new();
+ let mut owners = Vec::new();
+ let mut approvals = Vec::new();
+ for (i, t) in tasks.iter().enumerate() {
+ if t.title.trim().is_empty() {
+ return Err(format!("task {} needs a title", i + 1));
+ }
+ let key = t.key.clone().unwrap_or_else(|| (i + 1).to_string());
+ if keys.insert(key.clone(), i).is_some() {
+ return Err(format!("two tasks have the key {key}"));
+ }
+ if t.priority.is_some_and(|p| !(0..=3).contains(&p)) {
+ return Err(format!("task {key}: priority must be 0–3"));
+ }
+ if t.budget_tokens.is_some_and(|b| b < 1 || b > budget) {
+ return Err(format!("task {key}: budget_tokens must be 1–{budget}"));
+ }
+ let owner = match &t.owner {
+ Some(o) => Some(bot_in_space(state, space, o).await.ok_or_else(|| format!("task {key}: no bot {o} in this space"))?.id),
+ None => None,
+ };
+ owners.push(owner);
+ let mut ok = Vec::new();
+ for c in &t.checks {
+ ok.push(validate_check(&c.kind, &c.spec, true).map_err(|e| format!("task {key}: {e}"))?);
+ }
+ // A bot's plan is approved as a whole by the person; an http check of a private URL still asks
+ let ok: Vec<bool> = t
+ .checks
+ .iter()
+ .zip(ok)
+ .map(|(c, ok)| if c.kind == "http" { validate_check("http", &c.spec, false).unwrap_or(false) || by.active } else { ok })
+ .collect();
+ approvals.push(ok);
+ }
+ for t in tasks {
+ for d in &t.depends_on {
+ if !keys.contains_key(d) {
+ return Err(format!("depends_on names {d}, which isn't a task key in this plan"));
+ }
+ }
+ }
+ let mission = state
+ .db
+ .create_mission(
+ space,
+ &crate::db::missions::NewMission {
+ title: title.into(),
+ goal: goal.trim().into(),
+ status: if by.active { "active".into() } else { "draft".into() },
+ lead_kwant_id: lead.id.clone(),
+ channel_id: place.channel_id,
+ direct_kwant_id: place.direct_kwant_id,
+ thread_id: place.thread_id,
+ workspace_path: place.workspace_path,
+ budget_tokens: budget,
+ created_by: by.created_by.into(),
+ },
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ let mut ids: Vec<String> = Vec::new();
+ for (i, t) in tasks.iter().enumerate() {
+ let row = state
+ .db
+ .create_task(
+ space,
+ &NewTask {
+ mission_id: Some(mission.id.clone()),
+ title: t.title.trim().into(),
+ acceptance: t.acceptance.trim().into(),
+ state: "backlog".into(),
+ priority: t.priority.unwrap_or(1),
+ owner_kwant_id: None,
+ suggested_kwant_id: owners[i].clone(),
+ budget_tokens: t.budget_tokens.unwrap_or(DEFAULT_TASK_BUDGET.min(budget)),
+ max_attempts: DEFAULT_MAX_ATTEMPTS,
+ source_kind: "mission".into(),
+ source_id: Some(mission.id.clone()),
+ channel_id: mission.channel_id.clone(),
+ direct_kwant_id: mission.direct_kwant_id.clone(),
+ thread_id: mission.thread_id.clone(),
+ created_by: by.created_by.into(),
+ },
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ for (c, approved) in t.checks.iter().zip(&approvals[i]) {
+ state
+ .db
+ .add_check(&NewCheck {
+ task_id: row.id.clone(),
+ kind: c.kind.clone(),
+ spec: c.spec.clone(),
+ required: c.required.unwrap_or(true),
+ approved: *approved,
+ requested_by: by.created_by.into(),
+ // The person made the plan or approves it before anything runs
+ approved_by: Some(if by.created_by == "person" { "person" } else { "mission" }.into()),
+ })
+ .await
+ .map_err(|e| e.to_string())?;
+ }
+ ids.push(row.id);
+ }
+ for (i, t) in tasks.iter().enumerate() {
+ for d in &t.depends_on {
+ state.db.add_dependency(&ids[i], &ids[keys[d]]).await.map_err(|e| e.to_string())?;
+ }
+ }
+ if by.active {
+ promote(state, &mission.id).await;
+ }
+ let mut rows = Vec::new();
+ for id in &ids {
+ if let Ok(Some(t)) = state.db.get_task(id).await {
+ emit_task(state, &t).await;
+ rows.push(t);
+ }
+ }
+ emit_mission(state, &mission.id).await;
+ Ok((mission, rows))
+}
+
+/// Creates a task outside a plan (a hand-off, a routine run, a work-ahead run, the person's).
+pub async fn create_task(state: &AppState, space: &SpaceId, t: NewTask) -> Result<Task, DbError> {
+ let task = state.db.create_task(space, &t).await?;
+ emit_task(state, &task).await;
+ if let Some(m) = &task.mission_id {
+ emit_mission(state, m).await;
+ }
+ Ok(task)
+}
+
+/// The folder a task's file checks and evidence resolve in: its mission's, else its owner's.
+pub async fn task_folder(state: &AppState, task: &Task) -> Option<std::path::PathBuf> {
+ if let Some(mid) = &task.mission_id {
+ if let Ok(Some(m)) = state.db.get_mission(mid).await {
+ if !m.workspace_path.is_empty() {
+ return Some(std::path::PathBuf::from(m.workspace_path));
+ }
+ }
+ }
+ let owner = task.owner_kwant_id.as_deref().or(task.suggested_kwant_id.as_deref())?;
+ let space = SpaceId::new(&task.space_id);
+ Some(crate::tools::bot_workspace(&crate::db::spaces::space_data_dir(&state.config.data_dir, &space), owner))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono::Utc;
+
+ #[test]
+ fn transitions_follow_the_contract() {
+ use Actor::*;
+ assert!(allowed("backlog", "ready", Kwant));
+ assert!(!allowed("backlog", "ready", Owner), "only kwant promotes, after the dependencies are verified");
+ assert!(!allowed("backlog", "ready", Person));
+ assert!(allowed("ready", "working", Owner));
+ assert!(allowed("working", "review", Owner));
+ for a in [Owner, Person, Kwant] {
+ assert!(!allowed("working", "verified", a), "nobody skips review");
+ assert!(!allowed("verified", "ready", a), "verified is final");
+ assert!(!allowed("cancelled", "ready", a), "cancelled is final");
+ assert!(!allowed("verified", "cancelled", a));
+ }
+ assert!(!allowed("review", "verified", Owner), "the owner can't verify its own work");
+ assert!(!allowed("review", "verified", Person), "the person verifies through a person check");
+ assert!(allowed("review", "verified", Kwant));
+ assert!(!allowed("working", "needs_you", Owner));
+ assert!(allowed("working", "needs_you", Kwant));
+ assert!(allowed("failed", "ready", Person));
+ assert!(!allowed("failed", "ready", Owner));
+ assert!(!allowed("review", "ready", Owner), "the owner can't take back a review to dodge a failing check");
+ assert!(allowed("ready", "cancelled", Person));
+ assert!(!allowed("ready", "cancelled", Owner));
+ }
+
+ fn task(owner: &str) -> Task {
+ Task {
+ id: "t".into(),
+ space_id: "s".into(),
+ mission_id: None,
+ title: "x".into(),
+ acceptance: String::new(),
+ state: "review".into(),
+ priority: 1,
+ owner_kwant_id: Some(owner.into()),
+ suggested_kwant_id: None,
+ budget_tokens: 10,
+ spent_tokens: 0,
+ attempts: 0,
+ max_attempts: 3,
+ blocked_reason: None,
+ source_kind: "person".into(),
+ source_id: None,
+ channel_id: None,
+ direct_kwant_id: None,
+ thread_id: None,
+ created_by: "person".into(),
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ finished_at: None,
+ }
+ }
+
+ fn check(kind: &str, status: &str, by: Option<&str>, required: bool) -> OutcomeCheck {
+ OutcomeCheck {
+ id: uuid::Uuid::new_v4().to_string(),
+ task_id: "t".into(),
+ kind: kind.into(),
+ spec: "{}".into(),
+ required,
+ approved: true,
+ status: status.into(),
+ output_excerpt: None,
+ checked_by: by.map(str::to_string),
+ requested_by: "person".into(),
+ approved_by: Some("person".into()),
+ evidence_id: None,
+ created_at: Utc::now(),
+ started_at: None,
+ finished_at: Some(Utc::now()),
+ }
+ }
+
+ #[test]
+ fn the_owners_word_never_verifies() {
+ let t = task("bot-a");
+ assert_eq!(verdict(&t, &[], None), Verdict::Waiting, "no check, no verify");
+ assert_eq!(verdict(&t, &[check("peer_review", "passed", Some("bot-a"), true)], None), Verdict::Waiting, "own review");
+ assert_eq!(verdict(&t, &[check("peer_review", "passed", Some("bot-b"), true)], None), Verdict::Pass);
+ assert_eq!(verdict(&t, &[check("command", "passed", Some("kwant"), true)], None), Verdict::Pass);
+ let failing = [check("command", "passed", Some("kwant"), true), check("http", "failed", Some("kwant"), true)];
+ assert!(matches!(verdict(&t, &failing, None), Verdict::Fail(_)));
+ let optional = [check("command", "passed", Some("kwant"), true), check("http", "failed", Some("kwant"), false)];
+ assert_eq!(verdict(&t, &optional, None), Verdict::Pass, "an optional check failing doesn't block");
+ let pending = [check("command", "passed", Some("kwant"), true), check("file_exists", "pending", None, true)];
+ assert_eq!(verdict(&t, &pending, None), Verdict::Waiting);
+ let mut unapproved = check("command", "failed", Some("kwant"), true);
+ unapproved.approved = false;
+ assert_eq!(verdict(&t, &[unapproved.clone()], None), Verdict::Waiting, "an unapproved check doesn't count either way");
+ assert_eq!(verdict(&t, &[unapproved, check("person", "passed", Some("person"), true)], None), Verdict::Pass);
+ }
+
+ #[test]
+ fn the_owners_own_check_counts_only_once_the_person_approves_it() {
+ let t = task("bot-a");
+ let mut own = check("file_exists", "passed", Some("kwant"), true);
+ own.requested_by = "bot-a".into();
+ own.approved_by = Some("auto".into());
+ assert!(!counts(&t, &own));
+ assert_eq!(verdict(&t, &[own.clone()], None), Verdict::Waiting, "its own file_exists doesn't verify it");
+ // It was added before the bot became the owner, so it ran, but nothing that counts checked it
+ assert_eq!(checks_summary(&t, &[own.clone()])["status"], "not_checked");
+ own.approved_by = Some("person".into());
+ assert!(counts(&t, &own));
+ assert_eq!(verdict(&t, &[own.clone()], None), Verdict::Pass);
+ // A teammate's (or the mission's) check counts as usual
+ let mut mate = own.clone();
+ (mate.requested_by, mate.approved_by) = ("bot-b".into(), Some("auto".into()));
+ assert_eq!(verdict(&t, &[mate], None), Verdict::Pass);
+ }
+
+ #[test]
+ fn every_required_check_must_pass_a_waiting_one_holds_the_task() {
+ let t = task("bot-a");
+ let mut waiting = check("http", "needs_approval", None, true);
+ (waiting.approved, waiting.approved_by) = (false, None);
+ let both = [check("file_exists", "passed", Some("kwant"), true), waiting.clone()];
+ assert_eq!(verdict(&t, &both, None), Verdict::Waiting, "1 of 2 passed is not verified");
+ let s = checks_summary(&t, &both);
+ assert_eq!((s["status"].as_str(), s["needs_approval"].as_u64(), s["passed"].as_u64()), (Some("pending"), Some(1), Some(1)));
+ // The person's own Verify is their call
+ let with_person = [both[0].clone(), waiting.clone(), check("person", "passed", Some("person"), true)];
+ assert_eq!(verdict(&t, &with_person, None), Verdict::Pass);
+ // An optional check waiting for approval doesn't hold it
+ waiting.required = false;
+ assert_eq!(verdict(&t, &[both[0].clone(), waiting], None), Verdict::Pass);
+ }
+
+ #[test]
+ fn an_old_review_doesnt_count_after_rework() {
+ let t = task("bot-a");
+ let mut old = check("peer_review", "failed", Some("bot-b"), true);
+ old.finished_at = Some(Utc::now() - chrono::Duration::hours(1));
+ let since = Some(Utc::now() - chrono::Duration::minutes(1));
+ assert_eq!(verdict(&t, &[old.clone()], since), Verdict::Waiting, "the failed review was of the earlier attempt");
+ assert!(matches!(verdict(&t, &[old], None), Verdict::Fail(_)));
+ }
+
+ #[test]
+ fn summary_says_not_checked() {
+ let t = task("bot-a");
+ assert_eq!(checks_summary(&t, &[])["status"], "not_checked");
+ assert_eq!(checks_summary(&t, &[check("command", "passed", Some("kwant"), true)])["status"], "passed");
+ assert_eq!(checks_summary(&t, &[check("command", "error", Some("kwant"), true)])["status"], "failed");
+ }
+
+ #[test]
+ fn bots_need_approval_for_commands_and_private_urls() {
+ assert_eq!(validate_check("command", &json!({"command": "true"}), false), Ok(false));
+ assert_eq!(validate_check("command", &json!({"command": "true"}), true), Ok(true));
+ assert_eq!(validate_check("http", &json!({"url": "http://127.0.0.1:8080/"}), false), Ok(false));
+ assert_eq!(validate_check("file_exists", &json!({"path": "a.txt"}), false), Ok(true));
+ assert!(validate_check("peer_review", &json!({}), true).is_err());
+ assert!(validate_check("file_sha256", &json!({"path": "a", "sha256": "xyz"}), true).is_err());
+ assert!(validate_check("http", &json!({"url": "file:///etc/passwd"}), true).is_err());
+ }
+
+ #[test]
+ fn settings_ranges() {
+ assert!(settings_error(Some(4), None).is_some());
+ assert!(settings_error(Some(30), Some(200_000)).is_none());
+ assert!(settings_error(None, Some(999)).is_some());
+ }
+}
diff --git a/src/server/missions/routes.rs b/src/server/missions/routes.rs
new file mode 100644
index 00000000..4bca1137
--- /dev/null
+++ b/src/server/missions/routes.rs
@@ -0,0 +1,848 @@
+//! `/api/missions`, `/api/tasks` and `/api/checks`. Reads are open like the rest of the app API;
+//! every change is person-only (`auth.rs`), so a bot token can't verify, approve or cancel.
+
+use super::{
+ checks, checks_json, emit_mission, emit_task, evaluate, mission_json, task_json, transition, validate_check, Actor, MoveError,
+ PlanBy, PlanCheck, PlanPlace, PlanTask,
+};
+use crate::db::missions::{NewCheck, NewTask, Task, TaskChange, TaskEvent, MISSION_STATUSES, SOURCE_KINDS, TASK_STATES};
+use crate::db::spaces::SpaceId;
+use crate::server::spaces::{space_param, Scope};
+use crate::server::AppState;
+use axum::{
+ extract::{Path, Query, RawQuery, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+fn err(status: StatusCode, msg: impl Into<String>) -> Response {
+ (status, Json(json!({"error": msg.into()}))).into_response()
+}
+
+fn bad(msg: impl Into<String>) -> Response {
+ err(StatusCode::BAD_REQUEST, msg)
+}
+
+fn conflict(msg: impl Into<String>) -> Response {
+ err(StatusCode::CONFLICT, msg)
+}
+
+fn not_found(what: &str) -> Response {
+ err(StatusCode::NOT_FOUND, format!("no such {what}"))
+}
+
+fn internal(e: impl std::fmt::Display) -> Response {
+ tracing::warn!(error = %e, "mission control");
+ err(StatusCode::INTERNAL_SERVER_ERROR, "something went wrong")
+}
+
+#[allow(clippy::result_large_err)]
+fn moved(r: Result<Task, MoveError>) -> Result<Task, Response> {
+ r.map_err(|e| match e {
+ MoveError::Missing => not_found("task"),
+ MoveError::Db(crate::db::DbError::Sqlx(_)) | MoveError::NotAllowed(_) | MoveError::Stale => conflict(e.to_string()),
+ MoveError::Db(e) => internal(e),
+ })
+}
+
+/// The task `id`, refused (404) when an explicit `?space=` names another space.
+#[allow(clippy::result_large_err)]
+async fn load_task(state: &AppState, query: Option<&str>, id: &str) -> Result<Task, Response> {
+ match state.db.get_task(id).await {
+ Ok(Some(t)) if space_param(query).is_none_or(|s| s.trim() == t.space_id) => Ok(t),
+ Ok(_) => Err(not_found("task")),
+ Err(e) => Err(internal(e)),
+ }
+}
+
+#[allow(clippy::result_large_err)]
+async fn load_mission(state: &AppState, query: Option<&str>, id: &str) -> Result<crate::db::missions::Mission, Response> {
+ match state.db.get_mission(id).await {
+ Ok(Some(m)) if space_param(query).is_none_or(|s| s.trim() == m.space_id) => Ok(m),
+ Ok(_) => Err(not_found("mission")),
+ Err(e) => Err(internal(e)),
+ }
+}
+
+async fn task_out(state: &AppState, t: &Task) -> Response {
+ Json(task_json(state, t).await).into_response()
+}
+
+async fn mission_out(state: &AppState, id: &str) -> Response {
+ match state.db.get_mission(id).await {
+ Ok(Some(m)) => Json(mission_json(state, &m).await).into_response(),
+ Ok(None) => not_found("mission"),
+ Err(e) => internal(e),
+ }
+}
+
+async fn event_json(state: &AppState, e: &TaskEvent) -> Value {
+ let mut v = serde_json::to_value(e).unwrap_or(Value::Null);
+ if let Some(obj) = v.as_object_mut() {
+ obj.insert("detail".into(), e.detail_value());
+ obj.insert("actor_name".into(), json!(super::name_of(state, Some(&e.actor)).await));
+ }
+ v
+}
+
+// Missions
+
+#[derive(Deserialize)]
+pub struct MissionQuery {
+ status: Option<String>,
+}
+
+pub async fn list_missions(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<MissionQuery>) -> Response {
+ if q.status.as_deref().is_some_and(|s| !MISSION_STATUSES.contains(&s)) {
+ return bad("unknown status");
+ }
+ match state.db.list_missions(&space, q.status.as_deref()).await {
+ Ok(ms) => {
+ let mut out = Vec::new();
+ for m in &ms {
+ out.push(mission_json(&state, m).await);
+ }
+ Json(json!({"missions": out})).into_response()
+ }
+ Err(e) => internal(e),
+ }
+}
+
+#[derive(Deserialize)]
+pub struct CreateMission {
+ title: String,
+ #[serde(default)]
+ goal: String,
+ lead_kwant_id: Option<String>,
+ budget_tokens: Option<i64>,
+ #[serde(default)]
+ tasks: Vec<PlanTask>,
+ channel_id: Option<String>,
+ thread_id: Option<String>,
+}
+
+pub async fn create_mission(State(state): State<AppState>, Scope(space): Scope, Json(p): Json<CreateMission>) -> Response {
+ let bots = match state.db.list_kwants(&space).await {
+ Ok(b) => b,
+ Err(e) => return internal(e),
+ };
+ let lead = match &p.lead_kwant_id {
+ Some(id) => match super::bot_in_space(&state, &space, id).await {
+ Some(k) => k,
+ None => return bad("lead_kwant_id isn't a bot in this space"),
+ },
+ None => match bots.first() {
+ Some(k) => k.clone(),
+ None => return bad("this space has no bots to lead a mission"),
+ },
+ };
+ let ws = crate::tools::bot_workspace(&crate::db::spaces::space_data_dir(&state.config.data_dir, &space), &lead.id);
+ let place = PlanPlace {
+ direct_kwant_id: if p.channel_id.is_none() && p.thread_id.is_none() { Some(lead.id.clone()) } else { None },
+ channel_id: p.channel_id.clone(),
+ thread_id: p.thread_id.clone(),
+ workspace_path: ws.to_string_lossy().into_owned(),
+ };
+ let by = PlanBy { created_by: "person", active: true };
+ match super::create_plan(&state, &space, &lead, &p.title, &p.goal, p.budget_tokens, &p.tasks, by, place).await {
+ Ok((m, _)) => {
+ super::mission_chat_line(&state, &m, format!("Mission \"{}\" started.", m.title)).await;
+ mission_out(&state, &m.id).await
+ }
+ Err(e) => bad(e),
+ }
+}
+
+pub async fn get_mission(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
+ let m = match load_mission(&state, q.as_deref(), &id).await {
+ Ok(m) => m,
+ Err(r) => return r,
+ };
+ let space = SpaceId::new(&m.space_id);
+ let tasks = state.db.list_tasks(&space, None, Some(&m.id), None, 1000).await.unwrap_or_default();
+ let mut out = Vec::new();
+ for t in &tasks {
+ out.push(task_json(&state, t).await);
+ }
+ Json(json!({"mission": mission_json(&state, &m).await, "tasks": out})).into_response()
+}
+
+#[derive(Deserialize)]
+pub struct PatchMission {
+ title: Option<String>,
+ goal: Option<String>,
+ budget_tokens: Option<i64>,
+}
+
+pub async fn patch_mission(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, Json(p): Json<PatchMission>) -> Response {
+ let m = match load_mission(&state, q.as_deref(), &id).await {
+ Ok(m) => m,
+ Err(r) => return r,
+ };
+ if matches!(m.status.as_str(), "done" | "cancelled") {
+ return conflict(format!("the mission is {}", m.status));
+ }
+ let title = p.title.as_deref().map(str::trim);
+ if title.is_some_and(|t| t.is_empty() || t.chars().count() > 200) {
+ return bad("title must be 1–200 characters");
+ }
+ let (lo, hi) = super::BUDGET_RANGE;
+ if p.budget_tokens.is_some_and(|b| !(lo..=hi).contains(&b)) {
+ return bad(format!("budget_tokens must be {lo}–{hi}"));
+ }
+ if let Err(e) = state.db.edit_mission(&id, title, p.goal.as_deref().map(str::trim), p.budget_tokens).await {
+ return internal(e);
+ }
+ emit_mission(&state, &id).await;
+ mission_out(&state, &id).await
+}
+
+pub async fn approve_mission(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
+ let m = match load_mission(&state, q.as_deref(), &id).await {
+ Ok(m) => m,
+ Err(r) => return r,
+ };
+ match state.db.set_mission_status(&id, "draft", "active", Some("person")).await {
+ Ok(true) => {}
+ Ok(false) => return conflict(format!("the mission is {}, not a draft", m.status)),
+ Err(e) => return internal(e),
+ }
+ super::promote(&state, &id).await;
+ if let Ok(Some(m)) = state.db.get_mission(&id).await {
+ super::mission_chat_line(&state, &m, format!("Approved: mission \"{}\" is running.", m.title)).await;
+ }
+ emit_mission(&state, &id).await;
+ mission_out(&state, &id).await
+}
+
+pub async fn cancel_mission(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
+ let m = match load_mission(&state, q.as_deref(), &id).await {
+ Ok(m) => m,
+ Err(r) => return r,
+ };
+ let ok = match m.status.as_str() {
+ "draft" | "active" => state.db.set_mission_status(&id, &m.status, "cancelled", Some("person")).await,
+ s => return conflict(format!("the mission is already {s}")),
+ };
+ match ok {
+ Ok(true) => {}
+ Ok(false) => return conflict("the mission changed meanwhile"),
+ Err(e) => return internal(e),
+ }
+ let space = SpaceId::new(&m.space_id);
+ for t in state.db.list_tasks(&space, None, Some(&id), None, 1000).await.unwrap_or_default() {
+ if !matches!(t.state.as_str(), "verified" | "cancelled") {
+ let change = TaskChange { reason: Some("the mission was cancelled".into()), ..Default::default() };
+ let _ = transition(&state, &t.id, &t.state, "cancelled", Actor::Person, "person", change).await;
+ }
+ }
+ emit_mission(&state, &id).await;
+ mission_out(&state, &id).await
+}
+
+#[derive(Deserialize, Default)]
+pub struct RunMission {
+ max_tasks: Option<usize>,
+}
+
+/// Test hook and "Run now": starts up to `max_tasks` runner turns now, even with the board off.
+pub async fn run_mission(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, body: Option<Json<RunMission>>) -> Response {
+ let m = match load_mission(&state, q.as_deref(), &id).await {
+ Ok(m) => m,
+ Err(r) => return r,
+ };
+ let max = body.and_then(|b| b.0.max_tasks).unwrap_or(1);
+ if !(1..=5).contains(&max) {
+ return bad("max_tasks must be 1–5");
+ }
+ if m.status != "active" {
+ return conflict(format!("the mission is {}, not active", m.status));
+ }
+ let (started, reason) = super::runner::run_mission(&state, &m, max).await;
+ let started: Vec<Value> = started.into_iter().map(|(t, k)| json!({"task_id": t, "kwant_id": k})).collect();
+ let mut v = json!({"started": started});
+ if let Some(r) = reason {
+ v["reason"] = json!(r);
+ }
+ Json(v).into_response()
+}
+
+pub async fn insights(State(state): State<AppState>, Scope(space): Scope) -> Response {
+ let since = chrono::Utc::now() - chrono::Duration::days(7);
+ let events = match state.db.space_events_since(&space, since).await {
+ Ok(e) => e,
+ Err(e) => return internal(e),
+ };
+ let mut verified = std::collections::HashSet::new();
+ let mut false_success = 0;
+ let mut waiting_result: std::collections::HashSet<String> = Default::default();
+ let mut interventions = 0;
+ for e in &events {
+ let person = e.actor == "person";
+ match e.kind.as_str() {
+ "state" | "lease_expired" | "budget" => {
+ if e.to_state.as_deref() == Some("verified") {
+ verified.insert(e.task_id.clone());
+ }
+ if e.to_state.as_deref() == Some("review") && !matches!(e.actor.as_str(), "kwant" | "person") {
+ waiting_result.insert(e.task_id.clone());
+ }
+ if person {
+ interventions += 1;
+ }
+ }
+ "check_result" if waiting_result.contains(&e.task_id) => {
+ let status = e.detail_value()["status"].as_str().unwrap_or("").to_string();
+ if !person && matches!(status.as_str(), "failed" | "error") {
+ false_success += 1;
+ waiting_result.remove(&e.task_id);
+ } else if status == "passed" {
+ waiting_result.remove(&e.task_id);
+ }
+ if person {
+ interventions += 1;
+ }
+ }
+ "check_result" if person => interventions += 1,
+ "check_added" if person && e.detail_value()["approval"] == json!(true) => interventions += 1,
+ _ => {}
+ }
+ }
+ let all = state.db.list_tasks(&space, None, None, None, 1000).await.unwrap_or_default();
+ let mut needs_you = all.iter().filter(|t| t.state == "needs_you").count();
+ for t in all.iter().filter(|t| t.state == "review") {
+ if !super::check_approvals(&state, t).await.is_empty() {
+ needs_you += 1;
+ }
+ }
+ let blocked = all.iter().filter(|t| t.state == "blocked").count();
+ let tokens: i64 = all.iter().filter(|t| t.updated_at >= since).map(|t| t.spent_tokens).sum();
+ let still_blocked: Vec<&str> = all.iter().filter(|t| t.state == "blocked").map(|t| t.id.as_str()).collect();
+ let blocked_minutes = blocked_minutes(&events, &still_blocked, since, chrono::Utc::now());
+ let per = if verified.is_empty() { Value::Null } else { json!(tokens / verified.len() as i64) };
+ Json(json!({
+ "verified_7d": verified.len(),
+ "false_success_7d": false_success,
+ "needs_you_now": needs_you,
+ "blocked_now": blocked,
+ "blocked_minutes_7d": blocked_minutes,
+ "interventions_7d": interventions,
+ "tokens_7d": tokens,
+ "tokens_per_verified_7d": per,
+ }))
+ .into_response()
+}
+
+/// Minutes tasks spent in `blocked` between `since` and `now`, from the state events in that
+/// window. A task whose first event in the window leaves `blocked`, or that is still blocked with
+/// no event in the window, counts from `since`.
+pub fn blocked_minutes(
+ events: &[TaskEvent],
+ still_blocked: &[&str],
+ since: chrono::DateTime<chrono::Utc>,
+ now: chrono::DateTime<chrono::Utc>,
+) -> i64 {
+ let mut open: std::collections::HashMap<&str, chrono::DateTime<chrono::Utc>> = Default::default();
+ let mut seen: std::collections::HashSet<&str> = Default::default();
+ let mut total = chrono::Duration::zero();
+ for e in events.iter().filter(|e| e.to_state.is_some()) {
+ let id = e.task_id.as_str();
+ if seen.insert(id) && e.from_state.as_deref() == Some("blocked") {
+ open.insert(id, since);
+ }
+ if let Some(start) = open.remove(id) {
+ total += e.created_at - start;
+ }
+ if e.to_state.as_deref() == Some("blocked") {
+ open.insert(id, e.created_at);
+ }
+ }
+ for id in still_blocked {
+ if !seen.contains(id) {
+ open.insert(id, since);
+ }
+ }
+ for start in open.values() {
+ total += now - *start;
+ }
+ total.num_minutes().max(0)
+}
+
+// Tasks
+
+#[derive(Deserialize)]
+pub struct TaskQuery {
+ state: Option<String>,
+ mission_id: Option<String>,
+ source_kind: Option<String>,
+ limit: Option<i64>,
+}
+
+pub async fn list_tasks(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<TaskQuery>) -> Response {
+ if q.state.as_deref().is_some_and(|s| !TASK_STATES.contains(&s)) {
+ return bad("unknown state");
+ }
+ if q.source_kind.as_deref().is_some_and(|s| !SOURCE_KINDS.contains(&s)) {
+ return bad("unknown source_kind");
+ }
+ let limit = q.limit.unwrap_or(500).clamp(1, 1000);
+ match state.db.list_tasks(&space, q.state.as_deref(), q.mission_id.as_deref(), q.source_kind.as_deref(), limit).await {
+ Ok(ts) => {
+ let mut out = Vec::new();
+ for t in &ts {
+ out.push(task_json(&state, t).await);
+ }
+ Json(json!({"tasks": out})).into_response()
+ }
+ Err(e) => internal(e),
+ }
+}
+
+#[derive(Deserialize)]
+pub struct CreateTask {
+ title: String,
+ #[serde(default)]
+ acceptance: String,
+ mission_id: Option<String>,
+ owner_kwant_id: Option<String>,
+ priority: Option<i64>,
+ #[serde(default)]
+ depends_on: Vec<String>,
+ budget_tokens: Option<i64>,
+ #[serde(default)]
+ checks: Vec<PlanCheck>,
+ source_kind: Option<String>,
+ source_id: Option<String>,
+}
+
+pub async fn create_task(State(state): State<AppState>, Scope(space): Scope, Json(p): Json<CreateTask>) -> Response {
+ let title = p.title.trim();
+ if title.is_empty() || title.chars().count() > 200 {
+ return bad("title must be 1–200 characters");
+ }
+ let source = p.source_kind.as_deref().unwrap_or("person");
+ if !matches!(source, "person" | "zombie") {
+ return bad("source_kind must be person or zombie");
+ }
+ if source == "zombie" && p.source_id.as_deref().is_none_or(|s| s.trim().is_empty()) {
+ return bad("a zombie task needs source_id");
+ }
+ if source == "zombie" {
+ if let Ok(Some(t)) = state.db.task_by_source("zombie", p.source_id.as_deref().unwrap_or("")).await {
+ if !matches!(t.state.as_str(), "verified" | "cancelled" | "failed") {
+ return conflict("that loose end already has a task");
+ }
+ }
+ }
+ if p.priority.is_some_and(|x| !(0..=3).contains(&x)) {
+ return bad("priority must be 0–3");
+ }
+ let mission = match &p.mission_id {
+ Some(id) => match state.db.get_mission(id).await {
+ Ok(Some(m)) if m.space_id == space.as_str() => {
+ if matches!(m.status.as_str(), "done" | "cancelled") {
+ return conflict(format!("the mission is {}", m.status));
+ }
+ Some(m)
+ }
+ Ok(_) => return bad("mission_id isn't a mission in this space"),
+ Err(e) => return internal(e),
+ },
+ None => None,
+ };
+ let owner = match &p.owner_kwant_id {
+ Some(o) => match super::bot_in_space(&state, &space, o).await {
+ Some(k) => Some(k),
+ None => return bad("owner_kwant_id isn't a bot in this space"),
+ },
+ None => None,
+ };
+ let budget = p.budget_tokens.unwrap_or(super::DEFAULT_TASK_BUDGET);
+ if !(1..=super::BUDGET_RANGE.1).contains(&budget) {
+ return bad(format!("budget_tokens must be 1–{}", super::BUDGET_RANGE.1));
+ }
+ let mut approvals = Vec::new();
+ for c in &p.checks {
+ match validate_check(&c.kind, &c.spec, true) {
+ Ok(a) => approvals.push(a),
+ Err(e) => return bad(e),
+ }
+ }
+ for d in &p.depends_on {
+ match state.db.get_task(d).await {
+ Ok(Some(t)) if t.space_id == space.as_str() && t.mission_id == p.mission_id => {}
+ Ok(_) => return bad(format!("depends_on: {d} isn't a task of the same mission in this space")),
+ Err(e) => return internal(e),
+ }
+ }
+ // Ready at once unless it waits on something; a draft mission's tasks wait for approval
+ let ready = p.depends_on.is_empty() && mission.as_ref().is_none_or(|m| m.status == "active");
+ let (channel_id, direct_kwant_id, thread_id) = match (&mission, &owner) {
+ (Some(m), _) => (m.channel_id.clone(), m.direct_kwant_id.clone(), m.thread_id.clone()),
+ (None, Some(k)) => (None, Some(k.id.clone()), None),
+ (None, None) => (None, None, None),
+ };
+ let new = NewTask {
+ mission_id: p.mission_id.clone(),
+ title: title.into(),
+ acceptance: p.acceptance.trim().into(),
+ state: "backlog".into(),
+ priority: p.priority.unwrap_or(1),
+ owner_kwant_id: None,
+ suggested_kwant_id: owner.map(|k| k.id),
+ budget_tokens: budget,
+ max_attempts: super::DEFAULT_MAX_ATTEMPTS,
+ source_kind: source.into(),
+ source_id: p.source_id.clone(),
+ channel_id,
+ direct_kwant_id,
+ thread_id,
+ created_by: "person".into(),
+ };
+ let task = match state.db.create_task(&space, &new).await {
+ Ok(t) => t,
+ Err(e) => return internal(e),
+ };
+ for (c, approved) in p.checks.iter().zip(approvals) {
+ let nc = NewCheck {
+ task_id: task.id.clone(),
+ kind: c.kind.clone(),
+ spec: c.spec.clone(),
+ required: c.required.unwrap_or(true),
+ approved,
+ requested_by: "person".into(),
+ approved_by: Some("person".into()),
+ };
+ if let Err(e) = state.db.add_check(&nc).await {
+ return internal(e);
+ }
+ }
+ for d in &p.depends_on {
+ if let Err(e) = state.db.add_dependency(&task.id, d).await {
+ return bad(e.to_string());
+ }
+ }
+ let task = if ready {
+ let change = TaskChange { reason: Some("created by the person".into()), ..Default::default() };
+ match transition(&state, &task.id, "backlog", "ready", Actor::Kwant, "kwant", change).await {
+ Ok(t) => t,
+ Err(_) => task,
+ }
+ } else {
+ if let Some(m) = &mission {
+ super::promote(&state, &m.id).await;
+ }
+ state.db.get_task(&task.id).await.ok().flatten().unwrap_or(task)
+ };
+ emit_task(&state, &task).await;
+ if let Some(m) = &task.mission_id {
+ emit_mission(&state, m).await;
+ }
+ (StatusCode::OK, task_out(&state, &task).await).into_response()
+}
+
+pub async fn get_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
+ let t = match load_task(&state, q.as_deref(), &id).await {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ let checks = state.db.list_checks(&id).await.unwrap_or_default();
+ let evidence = state.db.list_evidence(&id).await.unwrap_or_default();
+ let events = state.db.task_events(&id, 500).await.unwrap_or_default();
+ let mut ev = Vec::new();
+ for e in &events {
+ ev.push(event_json(&state, e).await);
+ }
+ Json(json!({
+ "task": task_json(&state, &t).await,
+ "checks": checks_json(&state, &t, &checks).await,
+ "evidence": evidence,
+ "events": ev,
+ }))
+ .into_response()
+}
+
+#[derive(Deserialize)]
+pub struct PatchTask {
+ title: Option<String>,
+ acceptance: Option<String>,
+ priority: Option<i64>,
+ owner_kwant_id: Option<String>,
+ budget_tokens: Option<i64>,
+}
+
+pub async fn patch_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, Json(p): Json<PatchTask>) -> Response {
+ let t = match load_task(&state, q.as_deref(), &id).await {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ if matches!(t.state.as_str(), "verified" | "cancelled") {
+ return conflict(format!("the task is {}", t.state));
+ }
+ let title = p.title.as_deref().map(str::trim);
+ if title.is_some_and(|x| x.is_empty() || x.chars().count() > 200) {
+ return bad("title must be 1–200 characters");
+ }
+ if p.priority.is_some_and(|x| !(0..=3).contains(&x)) {
+ return bad("priority must be 0–3");
+ }
+ if p.budget_tokens.is_some_and(|b| !(1..=super::BUDGET_RANGE.1).contains(&b)) {
+ return bad(format!("budget_tokens must be 1–{}", super::BUDGET_RANGE.1));
+ }
+ let owner = match &p.owner_kwant_id {
+ Some(o) => match super::bot_in_space(&state, &SpaceId::new(&t.space_id), o).await {
+ Some(k) => Some(k.id),
+ None => return bad("owner_kwant_id isn't a bot in this space"),
+ },
+ None => None,
+ };
+ if let Err(e) = state.db.edit_task(&id, title, p.acceptance.as_deref().map(str::trim), p.priority, owner.as_deref(), p.budget_tokens, "person").await {
+ return internal(e);
+ }
+ match state.db.get_task(&id).await {
+ Ok(Some(t)) => {
+ emit_task(&state, &t).await;
+ task_out(&state, &t).await
+ }
+ _ => not_found("task"),
+ }
+}
+
+#[derive(Deserialize, Default)]
+pub struct Note {
+ note: Option<String>,
+ reason: Option<String>,
+}
+
+fn body(b: Option<Json<Note>>) -> Note {
+ b.map(|b| b.0).unwrap_or_default()
+}
+
+/// The person's Verify: runs the task's pending kwant checks, then records a passing `person` check.
+/// Verified only if every required check then passes.
+pub async fn verify_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, b: Option<Json<Note>>) -> Response {
+ let t = match load_task(&state, q.as_deref(), &id).await {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ if t.state != "review" {
+ return conflict(format!("only a task in review can be verified; this one is {}", t.state));
+ }
+ let note = body(b).note.unwrap_or_default();
+ let c = NewCheck {
+ task_id: id.clone(),
+ kind: "person".into(),
+ spec: json!({"note": note.chars().take(2000).collect::<String>()}),
+ required: true,
+ approved: true,
+ requested_by: "person".into(),
+ approved_by: Some("person".into()),
+ };
+ let check = match state.db.add_check(&c).await {
+ Ok(c) => c,
+ Err(e) => return internal(e),
+ };
+ if let Err(e) = state.db.finish_check(&check.id, "passed", Some(&note), "person", None).await {
+ return internal(e);
+ }
+ // Runs the approved kwant checks that haven't passed yet; evaluates
+ let pending: Vec<_> = state.db.list_checks(&id).await.unwrap_or_default().into_iter().filter(|c| c.approved && c.status == "pending").collect();
+ for c in &pending {
+ checks::run_check(&state, &t, c).await;
+ }
+ let after = evaluate(&state, &id).await;
+ match after {
+ Some(t) if t.state == "verified" => task_out(&state, &t).await,
+ Some(t) => {
+ emit_task(&state, &t).await;
+ let summary = super::checks_summary(&t, &state.db.list_checks(&id).await.unwrap_or_default());
+ conflict(format!("not verified: its checks are {} (the task is {})", summary["status"].as_str().unwrap_or("?"), t.state))
+ }
+ None => not_found("task"),
+ }
+}
+
+pub async fn reject_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, b: Option<Json<Note>>) -> Response {
+ if let Err(r) = load_task(&state, q.as_deref(), &id).await {
+ return r;
+ }
+ let b = body(b);
+ let Some(reason) = b.reason.or(b.note).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) else {
+ return bad("reason is required");
+ };
+ let change = TaskChange { reason: Some(reason), attempt: true, ..Default::default() };
+ match moved(transition(&state, &id, "review", "ready", Actor::Person, "person", change).await) {
+ Ok(t) => task_out(&state, &t).await,
+ Err(r) => r,
+ }
+}
+
+pub async fn block_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, b: Option<Json<Note>>) -> Response {
+ let t = match load_task(&state, q.as_deref(), &id).await {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ let b = body(b);
+ let Some(reason) = b.reason.or(b.note).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) else {
+ return bad("reason is required");
+ };
+ let change = TaskChange { reason: Some(reason), ..Default::default() };
+ match moved(transition(&state, &id, &t.state, "blocked", Actor::Person, "person", change).await) {
+ Ok(t) => task_out(&state, &t).await,
+ Err(r) => r,
+ }
+}
+
+pub async fn unblock_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
+ let t = match load_task(&state, q.as_deref(), &id).await {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ if t.state != "blocked" {
+ return conflict(format!("the task is {}, not blocked", t.state));
+ }
+ let change = TaskChange::default();
+ let t = match moved(transition(&state, &id, "blocked", "backlog", Actor::Person, "person", change).await) {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ super::promote_one(&state, &t).await;
+ match state.db.get_task(&id).await {
+ Ok(Some(t)) => task_out(&state, &t).await,
+ _ => not_found("task"),
+ }
+}
+
+pub async fn retry_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
+ if let Err(r) = load_task(&state, q.as_deref(), &id).await {
+ return r;
+ }
+ // A retry gets the same number of attempts again
+ let change = TaskChange { reason: Some("retried by the person".into()), detail: Some(json!({"reset_attempts": true})), ..Default::default() };
+ match moved(transition(&state, &id, "failed", "ready", Actor::Person, "person", change).await) {
+ Ok(t) => {
+ let _ = state.db.reset_attempts(&id).await;
+ let t = state.db.get_task(&id).await.ok().flatten().unwrap_or(t);
+ emit_task(&state, &t).await;
+ task_out(&state, &t).await
+ }
+ Err(r) => r,
+ }
+}
+
+pub async fn cancel_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
+ let t = match load_task(&state, q.as_deref(), &id).await {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ let change = TaskChange { reason: Some("cancelled by the person".into()), ..Default::default() };
+ match moved(transition(&state, &id, &t.state, "cancelled", Actor::Person, "person", change).await) {
+ Ok(t) => task_out(&state, &t).await,
+ Err(r) => r,
+ }
+}
+
+#[derive(Deserialize)]
+pub struct AddCheck {
+ kind: String,
+ #[serde(default)]
+ spec: Value,
+ required: Option<bool>,
+}
+
+pub async fn add_task_check(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, Json(p): Json<AddCheck>) -> Response {
+ let t = match load_task(&state, q.as_deref(), &id).await {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ if matches!(t.state.as_str(), "verified" | "cancelled") {
+ return conflict(format!("the task is {}", t.state));
+ }
+ if let Err(e) = validate_check(&p.kind, &p.spec, true) {
+ return bad(e);
+ }
+ let c = NewCheck { task_id: id.clone(), kind: p.kind, spec: p.spec, required: p.required.unwrap_or(true), approved: true, requested_by: "person".into(), approved_by: Some("person".into()) };
+ let check = match state.db.add_check(&c).await {
+ Ok(c) => c,
+ Err(e) => return internal(e),
+ };
+ let check = if t.state == "review" { checks::run_check(&state, &t, &check).await } else { check };
+ if let Some(t) = evaluate(&state, &id).await {
+ emit_task(&state, &t).await;
+ }
+ Json(super::check_json(&t, &check, super::name_of(&state, check.checked_by.as_deref()).await)).into_response()
+}
+
+pub async fn run_task_checks(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
+ if let Err(r) = load_task(&state, q.as_deref(), &id).await {
+ return r;
+ }
+ let (checks, task) = checks::run_task_checks(&state, &id, None).await;
+ let Some(task) = task else { return not_found("task") };
+ Json(json!({"checks": checks_json(&state, &task, &checks).await, "task": task_json(&state, &task).await})).into_response()
+}
+
+pub async fn approve_check(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
+ let check = match state.db.get_check(&id).await {
+ Ok(Some(c)) => c,
+ Ok(None) => return not_found("check"),
+ Err(e) => return internal(e),
+ };
+ let t = match load_task(&state, q.as_deref(), &check.task_id).await {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ match state.db.approve_check(&id).await {
+ Ok(true) => {}
+ Ok(false) => return conflict(format!("the check is {}, not waiting for approval", check.status)),
+ Err(e) => return internal(e),
+ }
+ let _ = state.db.log_task_event(&t.id, "check_added", "person", &json!({"check_id": id, "approved": true, "approval": true})).await;
+ let check = state.db.get_check(&id).await.ok().flatten().unwrap_or(check);
+ let check = if t.state == "review" { checks::run_check(&state, &t, &check).await } else { check };
+ if let Some(t) = evaluate(&state, &t.id).await {
+ emit_task(&state, &t).await;
+ }
+ Json(super::check_json(&t, &check, super::name_of(&state, check.checked_by.as_deref()).await)).into_response()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono::{Duration, TimeZone, Utc};
+
+ fn ev(task: &str, from: &str, to: &str, at: chrono::DateTime<Utc>) -> TaskEvent {
+ TaskEvent {
+ id: 0,
+ task_id: task.into(),
+ mission_id: None,
+ kind: "state".into(),
+ actor: "person".into(),
+ from_state: Some(from.into()),
+ to_state: Some(to.into()),
+ detail: String::new(),
+ created_at: at,
+ }
+ }
+
+ #[test]
+ fn blocked_minutes_sums_time_in_blocked_within_the_window() {
+ let since = Utc.with_ymd_and_hms(2026, 10, 20, 0, 0, 0).unwrap();
+ let now = since + Duration::days(7);
+ let events = vec![
+ // a: blocked for 30 minutes inside the window
+ ev("a", "ready", "blocked", since + Duration::hours(1)),
+ ev("a", "blocked", "ready", since + Duration::hours(1) + Duration::minutes(30)),
+ // b: blocked before the window, unblocked 2 hours in
+ ev("b", "blocked", "ready", since + Duration::hours(2)),
+ // c: blocked 10 minutes before now and still blocked
+ ev("c", "ready", "blocked", now - Duration::minutes(10)),
+ ];
+ // d: blocked the whole window with no event in it
+ assert_eq!(blocked_minutes(&events, &["c", "d"], since, now), 30 + 120 + 10 + 7 * 24 * 60);
+ assert_eq!(blocked_minutes(&[], &[], since, now), 0);
+ }
+}
diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rs
new file mode 100644
index 00000000..6a4c160f
--- /dev/null
+++ b/src/server/missions/runner.rs
@@ -0,0 +1,189 @@
+//! The mission runner: on each scheduler tick (and `POST /api/missions/:id/run`) it claims the
+//! highest-priority ready task of an active mission for its owner and runs one hidden turn on it.
+//! At most one runner turn per mission and [`MAX_RUNNING`] server-wide.
+
+use super::{lease_ms, transition, Actor};
+use crate::db::missions::{ClaimRefused, Mission, Task, TaskChange};
+use crate::server::routes::{scope_for, turn_once, TurnOpts};
+use crate::server::AppState;
+use std::collections::HashSet;
+use std::sync::{LazyLock, Mutex};
+
+pub const MAX_RUNNING: usize = 2;
+pub const PURPOSE: &str = "mission";
+
+/// Missions with a runner turn going.
+static RUNNING: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
+
+/// Holds a mission's runner slot; frees it when dropped.
+struct Slot(String);
+
+impl Slot {
+ fn take(mission_id: &str) -> Result<Slot, &'static str> {
+ let mut set = RUNNING.lock().unwrap_or_else(|e| e.into_inner());
+ if set.contains(mission_id) {
+ return Err("a runner turn is already going for this mission");
+ }
+ if set.len() >= MAX_RUNNING {
+ return Err("two missions are already running; it starts when one finishes");
+ }
+ set.insert(mission_id.to_string());
+ Ok(Slot(mission_id.to_string()))
+ }
+}
+
+impl Drop for Slot {
+ fn drop(&mut self) {
+ RUNNING.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.0);
+ }
+}
+
+pub fn is_running(mission_id: &str) -> bool {
+ RUNNING.lock().unwrap_or_else(|e| e.into_inner()).contains(mission_id)
+}
+
+/// One scheduler tick: leases that ran out go back to ready, then each active mission without a
+/// runner turn gets one.
+pub async fn tick(state: &AppState) {
+ if !super::enabled(state).await {
+ return;
+ }
+ // Sources first, so a live hand-off or routine refreshes kwant's lease before the sweep
+ super::listener::reconcile(state).await;
+ super::sweep_leases(state).await;
+ for m in state.db.active_missions().await.unwrap_or_default() {
+ if is_running(&m.id) {
+ continue;
+ }
+ let _ = run_mission(state, &m, 1).await;
+ }
+}
+
+/// Starts runner turns for up to `max` ready tasks of `mission` (one at a time, in the
+/// background). Returns `(task_id, kwant_id)` of each started, and why none were if so.
+pub async fn run_mission(state: &AppState, mission: &Mission, max: usize) -> (Vec<(String, String)>, Option<String>) {
+ let slot = match Slot::take(&mission.id) {
+ Ok(s) => s,
+ Err(why) => return (Vec::new(), Some(why.into())),
+ };
+ super::promote(state, &mission.id).await;
+ let space = crate::db::spaces::SpaceId::new(&mission.space_id);
+ let ready = state.db.list_tasks(&space, Some("ready"), Some(&mission.id), None, 100).await.unwrap_or_default();
+ let mut picked: Vec<(Task, crate::db::models::Kwant)> = Vec::new();
+ let mut reason = None;
+ for t in ready.iter().filter(|t| matches!(t.source_kind.as_str(), "mission" | "person")) {
+ if picked.len() >= max {
+ break;
+ }
+ let who = t.owner_kwant_id.clone().or_else(|| t.suggested_kwant_id.clone()).unwrap_or_else(|| mission.lead_kwant_id.clone());
+ let Ok(Some(bot)) = state.db.get_kwant(&who).await else { continue };
+ if picked.iter().any(|(_, k)| k.id == bot.id) {
+ continue;
+ }
+ let context = mission_context(mission, &bot);
+ match state.db.claim_task(&t.id, &bot.id, None, Some(&context), lease_ms(state).await, false, "kwant").await {
+ Ok(Ok(task)) => {
+ super::emit_task(state, &task).await;
+ picked.push((task, bot));
+ }
+ Ok(Err(ClaimRefused::Budget { remaining, needed })) => {
+ reason = Some(format!("the mission's budget can't cover the next task ({remaining} tokens left, {needed} needed)"));
+ break;
+ }
+ Ok(Err(why)) => reason = Some(why.to_string()),
+ Err(e) => reason = Some(e.to_string()),
+ }
+ }
+ if picked.is_empty() {
+ return (Vec::new(), Some(reason.unwrap_or_else(|| "no ready task to start".into())));
+ }
+ super::emit_mission(state, &mission.id).await;
+ let started = picked.iter().map(|(t, k)| (t.id.clone(), k.id.clone())).collect();
+ let state = state.clone();
+ let mission = mission.clone();
+ tokio::spawn(async move {
+ let _slot = slot;
+ for (task, bot) in picked {
+ run_one(&state, &mission, &task, &bot).await;
+ }
+ });
+ (started, None)
+}
+
+/// Where a runner turn of `bot` in `m` runs: the mission's channel; its thread or direct chat only
+/// for the lead (threads and direct chats are one bot's own), else the bot's direct chat.
+fn mission_place(m: &Mission, bot: &crate::db::models::Kwant) -> (Option<String>, Option<String>) {
+ match (&m.channel_id, &m.thread_id) {
+ (Some(c), _) => (Some(c.clone()), None),
+ (None, Some(t)) if bot.id == m.lead_kwant_id => (None, Some(t.clone())),
+ _ => (None, None),
+ }
+}
+
+/// The chat id of [`mission_place`], as `TurnScope::context_id` names it.
+fn mission_context(m: &Mission, bot: &crate::db::models::Kwant) -> String {
+ let (c, t) = mission_place(m, bot);
+ c.or(t).unwrap_or_else(|| bot.id.clone())
+}
+
+async fn prompt(state: &AppState, m: &Mission, t: &Task) -> String {
+ let checks = state.db.list_checks(&t.id).await.unwrap_or_default();
+ let list: Vec<String> = checks
+ .iter()
+ .filter(|c| c.approved)
+ .map(|c| format!("- {} {}{}", c.kind, c.spec_value(), if c.required { "" } else { " (optional)" }))
+ .collect();
+ let deps = state.db.dependencies_of(&t.id).await.unwrap_or_default();
+ format!(
+ "[Mission Control] You hold task {id} of the mission \"{mt}\" (goal: {goal}).\n\
+ Task: {title}\nAcceptance: {acc}\nChecks kwant will run when you're done:\n{checks}\n{deps}\
+ Work on it now. Attach what you produced with task_attach_evidence, then call task_update with \
+ task_id {id} and status \"review\": kwant runs the checks and only they (or a teammate's review, \
+ or the person) can verify it. If you can't finish, call task_update with status \"blocked\" and a \
+ reason, or \"ready\" to let it go. Never say it is verified yourself. Budget: {budget} tokens.",
+ id = t.id,
+ mt = m.title,
+ goal = m.goal,
+ title = t.title,
+ acc = if t.acceptance.is_empty() { "(none given)" } else { &t.acceptance },
+ checks = if list.is_empty() { "- none: a teammate or the person reviews it".into() } else { list.join("\n") },
+ deps = if deps.is_empty() { String::new() } else { format!("It builds on tasks {} (verified).\n", deps.iter().map(|d| d.0.as_str()).collect::<Vec<_>>().join(", ")) },
+ budget = t.budget_tokens - t.spent_tokens,
+ )
+}
+
+async fn run_one(state: &AppState, m: &Mission, task: &Task, bot: &crate::db::models::Kwant) {
+ let context = mission_context(m, bot);
+ let job = state.turns.start_job([context.clone()]);
+ let (channel, thread) = mission_place(m, bot);
+ let reply = match scope_for(state, bot, channel, thread, &job, 0).await {
+ Ok(scope) => {
+ let mut opts = TurnOpts::default();
+ (opts.unsaved, opts.quiet_failure, opts.purpose) = (true, true, Some(PURPOSE.into()));
+ let p = prompt(state, m, task).await;
+ turn_once(&scope, bot, p, opts).await
+ }
+ Err(e) => Err(e),
+ };
+ if let Err(e) = &reply {
+ tracing::info!(task_id = %task.id, error = %e, "mission runner turn ended without a reply");
+ }
+ // Still working after the turn: the bot didn't finish or let go, so the lease is released
+ if let Ok(Some(t)) = state.db.get_task(&task.id).await {
+ if t.state == "working" {
+ let change = TaskChange {
+ kind: "released".into(),
+ reason: Some("the runner turn ended without a review".into()),
+ attempt: true,
+ ..Default::default()
+ };
+ let _ = transition(state, &t.id, "working", "ready", Actor::Kwant, "kwant", change).await;
+ if let Ok(Some(t)) = state.db.get_task(&task.id).await {
+ if t.attempts >= t.max_attempts && t.state == "ready" {
+ let change = TaskChange { reason: Some("no review after its last attempt".into()), ..Default::default() };
+ let _ = transition(state, &t.id, "ready", "blocked", Actor::Kwant, "kwant", change).await;
+ }
+ }
+ }
+ }
+}
diff --git a/src/server/missions/tools.rs b/src/server/missions/tools.rs
new file mode 100644
index 00000000..55b7b0e0
--- /dev/null
+++ b/src/server/missions/tools.rs
@@ -0,0 +1,483 @@
+//! The task-board self tools: `mission_plan`, `task_list`, `task_claim`, `task_update`,
+//! `task_attach_evidence`, `task_request_check`, `task_review`. Offered only while `mission_board`
+//! is on. None of them can set `verified`: only a passing check that isn't the owner's does.
+
+use super::checks::{hex, inside, run_task_checks};
+use super::{evaluate, task_folder, transition, validate_check, Actor, PlanBy, PlanPlace, PlanTask};
+use crate::db::missions::{now_ms, NewCheck, NewEvidence, Task, TaskChange};
+use crate::db::spaces::SpaceId;
+use crate::server::continuity::SelfScope;
+use crate::server::AppState;
+use serde_json::{json, Value};
+use sha2::{Digest, Sha256};
+
+type ToolResult = (String, bool);
+
+fn fail(msg: impl Into<String>) -> ToolResult {
+ (msg.into(), true)
+}
+
+fn ok(v: Value) -> ToolResult {
+ (serde_json::to_string_pretty(&v).unwrap_or_default(), false)
+}
+
+const NAMES: [&str; 7] = ["mission_plan", "task_list", "task_claim", "task_update", "task_attach_evidence", "task_request_check", "task_review"];
+
+pub fn handles(name: &str) -> bool {
+ NAMES.contains(&name)
+}
+
+fn check_schema() -> Value {
+ json!({
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "enum": ["command", "http", "file_exists", "file_contains", "file_sha256"]},
+ "spec": {"type": "object", "description": "command: {command, timeout_secs?}; http: {url, expect_status?, contains?}; file_exists: {path}; file_contains: {path, text}; file_sha256: {path, sha256}. Paths are relative to the mission's folder."},
+ "required": {"type": "boolean"},
+ },
+ "required": ["kind", "spec"],
+ })
+}
+
+pub fn tools() -> Vec<Value> {
+ vec![
+ json!({
+ "name": "mission_plan",
+ "description": "Propose a mission: a goal split into tasks with acceptance criteria and outcome checks. It is a draft until the person approves it on the board; nothing runs before that. Each task is verified only by its checks passing (or a teammate's review / the person), never by its owner saying it is done. Use it for multi-step work worth tracking, not for a quick answer.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "title": {"type": "string"},
+ "goal": {"type": "string", "description": "The outcome, in a sentence or two."},
+ "budget_tokens": {"type": "integer", "description": "Token budget for the whole mission (optional)."},
+ "tasks": {
+ "type": "array",
+ "maxItems": super::MAX_PLAN_TASKS,
+ "items": {
+ "type": "object",
+ "properties": {
+ "key": {"type": "string", "description": "Short id other tasks use in depends_on."},
+ "title": {"type": "string"},
+ "acceptance": {"type": "string", "description": "What must be true when it is done."},
+ "owner": {"type": "string", "description": "Bot name or id in your space (optional)."},
+ "priority": {"type": "integer", "minimum": 0, "maximum": 3},
+ "depends_on": {"type": "array", "items": {"type": "string"}},
+ "budget_tokens": {"type": "integer"},
+ "checks": {"type": "array", "items": check_schema()},
+ },
+ "required": ["title", "acceptance"],
+ },
+ },
+ },
+ "required": ["title", "goal", "tasks"],
+ },
+ }),
+ json!({
+ "name": "task_list",
+ "description": "List tasks on your space's board.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "mission_id": {"type": "string"},
+ "state": {"type": "string", "enum": crate::db::missions::TASK_STATES},
+ "mine": {"type": "boolean", "description": "Only tasks you own."},
+ },
+ },
+ }),
+ json!({
+ "name": "task_claim",
+ "description": "Take a ready task (ready → working, with a lease). Refused if someone holds it, a dependency isn't verified, its mission isn't active or can't afford it, or you already hold another task.",
+ "inputSchema": {"type": "object", "properties": {"task_id": {"type": "string"}}, "required": ["task_id"]},
+ }),
+ json!({
+ "name": "task_update",
+ "description": "Update a task you hold. status \"review\" = done: kwant runs its checks now and verifies it only if they pass. \"ready\" = let go of it. \"blocked\" needs a reason. A note alone renews your lease. You can never mark a task verified.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "task_id": {"type": "string"},
+ "status": {"type": "string", "enum": ["review", "ready", "blocked"]},
+ "note": {"type": "string"},
+ "reason": {"type": "string"},
+ },
+ "required": ["task_id"],
+ },
+ }),
+ json!({
+ "name": "task_attach_evidence",
+ "description": "Attach evidence to a task: a file in the mission's folder (kwant hashes it itself), a url, a note or a screenshot path. Evidence alone never verifies a task.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "task_id": {"type": "string"},
+ "kind": {"type": "string", "enum": ["file", "url", "note", "screenshot"]},
+ "label": {"type": "string"},
+ "path": {"type": "string"},
+ "url": {"type": "string"},
+ "text": {"type": "string"},
+ },
+ "required": ["task_id", "kind", "label"],
+ },
+ }),
+ json!({
+ "name": "task_request_check",
+ "description": "Run a task's approved checks (or one by check_id), or add a new check (kind + spec) and run it if it may run. A command check you add, or an http check of a private address, waits for the person's approval.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "task_id": {"type": "string"},
+ "check_id": {"type": "string"},
+ "kind": {"type": "string", "enum": ["command", "http", "file_exists", "file_contains", "file_sha256"]},
+ "spec": {"type": "object"},
+ "required": {"type": "boolean"},
+ },
+ "required": ["task_id"],
+ },
+ }),
+ json!({
+ "name": "task_review",
+ "description": "Review a teammate's task in review. Not for your own tasks. A pass must cite at least one evidence id attached to that task.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "task_id": {"type": "string"},
+ "verdict": {"type": "string", "enum": ["pass", "fail"]},
+ "evidence_ids": {"type": "array", "items": {"type": "string"}},
+ "note": {"type": "string"},
+ },
+ "required": ["task_id", "verdict", "note"],
+ },
+ }),
+ ]
+}
+
+pub async fn call(state: &AppState, scope: &SelfScope, name: &str, args: &Value) -> ToolResult {
+ if !super::enabled(state).await {
+ return fail("The task board is off in Settings.");
+ }
+ let space = match state.db.space_of_kwant(&scope.kwant_id).await {
+ Ok(Some(s)) => s,
+ _ => return fail("Could not find your space."),
+ };
+ if name == "mission_plan" {
+ return plan(state, scope, &space, args).await;
+ }
+ if name == "task_list" {
+ return list(state, scope, &space, args).await;
+ }
+ let Some(task_id) = args["task_id"].as_str().map(str::trim).filter(|s| !s.is_empty()) else {
+ return fail("task_id is required.");
+ };
+ let task = match state.db.get_task(task_id).await {
+ Ok(Some(t)) if t.space_id == space.as_str() => t,
+ _ => return fail("No such task in your space."),
+ };
+ match name {
+ "task_claim" => claim(state, scope, &task).await,
+ "task_update" => update(state, scope, &task, args).await,
+ "task_attach_evidence" => evidence(state, scope, &task, args).await,
+ "task_request_check" => request_check(state, scope, &task, args).await,
+ "task_review" => review(state, scope, &task, args).await,
+ _ => fail(format!("Unknown tool {name}.")),
+ }
+}
+
+async fn plan(state: &AppState, scope: &SelfScope, space: &SpaceId, args: &Value) -> ToolResult {
+ let tasks: Vec<PlanTask> = match serde_json::from_value(args["tasks"].clone()) {
+ Ok(t) => t,
+ Err(e) => return fail(format!("tasks: {e}")),
+ };
+ if tasks.is_empty() {
+ return fail("A mission needs at least one task.");
+ }
+ let Ok(Some(lead)) = state.db.get_kwant(&scope.kwant_id).await else { return fail("Could not find you.") };
+ let origin = scope.origin.clone().unwrap_or_default();
+ let workspace = scope.workspace.clone().unwrap_or_else(|| {
+ crate::tools::bot_workspace(&crate::db::spaces::space_data_dir(&state.config.data_dir, space), &scope.kwant_id)
+ });
+ let place = PlanPlace {
+ channel_id: origin.channel_id,
+ direct_kwant_id: origin.direct_kwant_id,
+ thread_id: origin.thread_id,
+ workspace_path: workspace.to_string_lossy().into_owned(),
+ };
+ let budget = args["budget_tokens"].as_i64();
+ let by = PlanBy { created_by: &scope.kwant_id, active: false };
+ let title = args["title"].as_str().unwrap_or("");
+ let goal = args["goal"].as_str().unwrap_or("");
+ match super::create_plan(state, space, &lead, title, goal, budget, &tasks, by, place).await {
+ Ok((m, rows)) => {
+ super::mission_chat_line(
+ state,
+ &m,
+ format!("Proposed mission \"{}\" with {} task{}. Approve it on the board to start.", m.title, rows.len(), if rows.len() == 1 { "" } else { "s" }),
+ )
+ .await;
+ ok(json!({
+ "mission_id": m.id,
+ "status": m.status,
+ "tasks": rows.iter().map(|t| json!({"id": t.id, "title": t.title, "state": t.state})).collect::<Vec<_>>(),
+ "next": "The person approves the mission on the board; nothing runs until then.",
+ }))
+ }
+ Err(e) => fail(e),
+ }
+}
+
+fn brief(t: &Task) -> Value {
+ json!({
+ "id": t.id, "title": t.title, "state": t.state, "mission_id": t.mission_id, "priority": t.priority,
+ "owner_kwant_id": t.owner_kwant_id, "suggested_kwant_id": t.suggested_kwant_id, "acceptance": t.acceptance,
+ "budget_tokens": t.budget_tokens, "spent_tokens": t.spent_tokens, "attempts": t.attempts, "blocked_reason": t.blocked_reason,
+ })
+}
+
+async fn list(state: &AppState, scope: &SelfScope, space: &SpaceId, args: &Value) -> ToolResult {
+ let st = args["state"].as_str();
+ let tasks = match state.db.list_tasks(space, st, args["mission_id"].as_str(), None, 200).await {
+ Ok(t) => t,
+ Err(e) => return fail(format!("Could not list tasks: {e}")),
+ };
+ let mine = args["mine"].as_bool().unwrap_or(false);
+ let rows: Vec<Value> = tasks
+ .iter()
+ .filter(|t| !mine || t.owner_kwant_id.as_deref() == Some(scope.kwant_id.as_str()))
+ .filter(|t| st.is_some() || t.state != "cancelled")
+ .map(brief)
+ .collect();
+ ok(json!({"tasks": rows}))
+}
+
+async fn claim(state: &AppState, scope: &SelfScope, task: &Task) -> ToolResult {
+ let lease = super::lease_ms(state).await;
+ match state.db.claim_task(&task.id, &scope.kwant_id, scope.turn_id.as_deref(), None, lease, false, &scope.kwant_id).await {
+ Ok(Ok(t)) => {
+ super::emit_task(state, &t).await;
+ if let Some(m) = &t.mission_id {
+ super::emit_mission(state, m).await;
+ }
+ let checks = state.db.list_checks(&t.id).await.unwrap_or_default();
+ ok(json!({
+ "task": brief(&t),
+ "lease_minutes": lease / 60_000,
+ "checks": checks.iter().map(|c| json!({"id": c.id, "kind": c.kind, "spec": c.spec_value(), "approved": c.approved})).collect::<Vec<_>>(),
+ "next": "Do the work, attach evidence with task_attach_evidence, then task_update status=review.",
+ }))
+ }
+ Ok(Err(why)) => fail(format!("Not claimed: {why}.")),
+ Err(e) => fail(format!("Could not claim: {e}")),
+ }
+}
+
+/// The caller's live claim on `task`, if it holds one.
+async fn holds(state: &AppState, scope: &SelfScope, task: &Task) -> bool {
+ matches!(state.db.open_claim(&task.id).await, Ok(Some(c))
+ if c.kwant_id == scope.kwant_id && !c.system && c.expires_at > now_ms())
+ && task.owner_kwant_id.as_deref() == Some(scope.kwant_id.as_str())
+ && matches!(task.state.as_str(), "working" | "needs_you")
+}
+
+async fn update(state: &AppState, scope: &SelfScope, task: &Task, args: &Value) -> ToolResult {
+ if !holds(state, scope, task).await {
+ return fail("You don't hold this task (claim it first, or your lease ran out).");
+ }
+ let note = args["note"].as_str().map(str::trim).filter(|s| !s.is_empty());
+ let reason = args["reason"].as_str().map(str::trim).filter(|s| !s.is_empty());
+ if let Some(n) = note {
+ let _ = state.db.log_task_event(&task.id, "note", &scope.kwant_id, &json!({"note": n.chars().take(2000).collect::<String>()})).await;
+ }
+ let status = args["status"].as_str();
+ let change = |reason: Option<&str>| TaskChange { reason: reason.map(String::from), ..Default::default() };
+ let moved = match status {
+ None if note.is_some() => {
+ let _ = state.db.renew_claim(&task.id, super::lease_ms(state).await).await;
+ super::emit_task_id(state, &task.id).await;
+ return ok(json!({"task": brief(task), "lease": "renewed"}));
+ }
+ None => return fail("Give a status or a note."),
+ Some("verified") => return fail("You can't mark a task verified; its checks or a teammate's review do."),
+ Some("review") => {
+ if task.state != "working" {
+ return fail("Answer the open question or step first; the task is waiting on the person.");
+ }
+ transition(state, &task.id, "working", "review", Actor::Owner, &scope.kwant_id, change(note)).await
+ }
+ Some("ready") => transition(state, &task.id, &task.state, "ready", Actor::Owner, &scope.kwant_id, change(reason.or(note))).await,
+ Some("blocked") => match reason {
+ Some(r) => transition(state, &task.id, &task.state, "blocked", Actor::Owner, &scope.kwant_id, change(Some(r))).await,
+ None => return fail("blocked needs a reason."),
+ },
+ Some(other) => return fail(format!("status must be review, ready or blocked, not {other}.")),
+ };
+ let task = match moved {
+ Ok(t) => t,
+ Err(e) => return fail(format!("Not moved: {e}.")),
+ };
+ if task.state != "review" {
+ return ok(json!({"task": brief(&task)}));
+ }
+ let (checks, after) = run_task_checks(state, &task.id, None).await;
+ let after = after.unwrap_or(task);
+ let summary = super::checks_summary(&after, &checks);
+ let next = match after.state.as_str() {
+ "verified" => "Verified by its checks.",
+ "review" if summary["status"] == "not_checked" => "No checks: it stays in review (not checked) until a teammate reviews it or the person verifies it.",
+ "review" => "Waiting on checks that need the person's approval.",
+ "ready" => "A check failed; the task is back in ready. Fix it and claim it again.",
+ "failed" => "A check failed on the last attempt; the task failed.",
+ _ => "",
+ };
+ ok(json!({
+ "task": brief(&after),
+ "checks": checks.iter().map(|c| json!({"id": c.id, "kind": c.kind, "status": c.status, "output": c.output_excerpt})).collect::<Vec<_>>(),
+ "next": next,
+ }))
+}
+
+async fn evidence(state: &AppState, scope: &SelfScope, task: &Task, args: &Value) -> ToolResult {
+ if matches!(task.state.as_str(), "verified" | "cancelled") {
+ return fail("This task is closed.");
+ }
+ let kind = args["kind"].as_str().unwrap_or("");
+ let label = args["label"].as_str().map(str::trim).filter(|s| !s.is_empty());
+ let Some(label) = label else { return fail("label is required.") };
+ let s = |k: &str| args[k].as_str().map(str::trim).filter(|v| !v.is_empty()).map(String::from);
+ let mut e = NewEvidence {
+ task_id: task.id.clone(),
+ kind: kind.into(),
+ label: label.chars().take(200).collect(),
+ captured_by: scope.kwant_id.clone(),
+ ..Default::default()
+ };
+ match kind {
+ "file" | "screenshot" => {
+ let Some(rel) = s("path") else { return fail("path is required for a file.") };
+ let Some(folder) = task_folder(state, task).await else { return fail("This task has no folder.") };
+ let path = match inside(&folder, &rel) {
+ Ok(p) => p,
+ Err(why) => return fail(format!("Not attached: {why}.")),
+ };
+ let bytes = match tokio::fs::read(&path).await {
+ Ok(b) => b,
+ Err(_) => return fail(format!("{rel} doesn't exist or can't be read.")),
+ };
+ e.sha256 = Some(hex(&Sha256::digest(&bytes)));
+ e.bytes = i64::try_from(bytes.len()).ok();
+ e.path = Some(rel);
+ }
+ "url" => {
+ let Some(url) = s("url").filter(|u| u.starts_with("http://") || u.starts_with("https://")) else {
+ return fail("url must start with http:// or https://.");
+ };
+ e.uri = Some(url);
+ }
+ "note" => {
+ let Some(text) = s("text") else { return fail("text is required for a note.") };
+ e.excerpt = Some(text.chars().take(super::MAX_EXCERPT).collect());
+ }
+ _ => return fail("kind must be file, url, note or screenshot."),
+ }
+ match state.db.add_evidence(&e).await {
+ Ok(ev) => {
+ super::emit_task_id(state, &task.id).await;
+ ok(json!({"evidence_id": ev.id, "sha256": ev.sha256, "bytes": ev.bytes}))
+ }
+ Err(err) => fail(format!("Could not attach: {err}")),
+ }
+}
+
+async fn request_check(state: &AppState, scope: &SelfScope, task: &Task, args: &Value) -> ToolResult {
+ if matches!(task.state.as_str(), "verified" | "cancelled") {
+ return fail("This task is closed.");
+ }
+ let mut only = args["check_id"].as_str().map(String::from);
+ let mut added = None;
+ if let Some(kind) = args["kind"].as_str() {
+ let spec = args["spec"].clone();
+ let approved = match validate_check(kind, &spec, false) {
+ Ok(a) => a,
+ Err(e) => return fail(e),
+ };
+ // The owner's own check would let it verify its own work: it counts only once the person
+ // approves it, so it waits like any other check that needs approval
+ let own = [&task.owner_kwant_id, &task.suggested_kwant_id].iter().any(|o| o.as_deref() == Some(scope.kwant_id.as_str()));
+ let approved = approved && !own;
+ let c = NewCheck {
+ task_id: task.id.clone(),
+ kind: kind.into(),
+ spec,
+ required: args["required"].as_bool().unwrap_or(true),
+ approved,
+ requested_by: scope.kwant_id.clone(),
+ approved_by: None,
+ };
+ match state.db.add_check(&c).await {
+ Ok(c) => {
+ only = Some(c.id.clone());
+ added = Some(c);
+ }
+ Err(e) => return fail(format!("Could not add the check: {e}")),
+ }
+ } else if let Some(id) = &only {
+ if !matches!(state.db.get_check(id).await, Ok(Some(c)) if c.task_id == task.id) {
+ return fail("No such check on this task.");
+ }
+ }
+ let (checks, after) = run_task_checks(state, &task.id, only.as_deref()).await;
+ let shown: Vec<Value> = checks
+ .iter()
+ .filter(|c| only.as_deref().is_none_or(|id| id == c.id))
+ .map(|c| json!({"id": c.id, "kind": c.kind, "approved": c.approved, "status": c.status, "output": c.output_excerpt}))
+ .collect();
+ let mut v = json!({"checks": shown, "task_state": after.map(|t| t.state)});
+ if added.is_some_and(|c| !c.approved) {
+ v["note"] = json!("This check waits for the person's approval before it runs.");
+ }
+ ok(v)
+}
+
+async fn review(state: &AppState, scope: &SelfScope, task: &Task, args: &Value) -> ToolResult {
+ if task.owner_kwant_id.as_deref() == Some(scope.kwant_id.as_str()) {
+ return fail("You can't review your own task; a teammate or the person does.");
+ }
+ if task.state != "review" {
+ return fail(format!("The task is {}, not in review.", task.state));
+ }
+ let verdict = args["verdict"].as_str().unwrap_or("");
+ if !matches!(verdict, "pass" | "fail") {
+ return fail("verdict must be pass or fail.");
+ }
+ let Some(note) = args["note"].as_str().map(str::trim).filter(|s| !s.is_empty()) else { return fail("note is required.") };
+ let ids: Vec<String> = args["evidence_ids"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect()).unwrap_or_default();
+ let on_task = state.db.list_evidence(&task.id).await.unwrap_or_default();
+ if let Some(bad) = ids.iter().find(|id| !on_task.iter().any(|e| &e.id == *id)) {
+ return fail(format!("Evidence {bad} isn't attached to this task."));
+ }
+ if verdict == "pass" && ids.is_empty() {
+ return fail("A pass must cite at least one evidence id on this task.");
+ }
+ let c = NewCheck {
+ task_id: task.id.clone(),
+ kind: "peer_review".into(),
+ spec: json!({"note": note.chars().take(2000).collect::<String>(), "evidence_ids": ids}),
+ required: true,
+ approved: true,
+ requested_by: scope.kwant_id.clone(),
+ approved_by: None,
+ };
+ let check = match state.db.add_check(&c).await {
+ Ok(c) => c,
+ Err(e) => return fail(format!("Could not record the review: {e}")),
+ };
+ let status = if verdict == "pass" { "passed" } else { "failed" };
+ if let Err(e) = state.db.finish_check(&check.id, status, Some(note), &scope.kwant_id, None).await {
+ return fail(format!("Could not record the review: {e}"));
+ }
+ let _ = state.db.log_task_event(&task.id, "review", &scope.kwant_id, &json!({"verdict": verdict, "check_id": check.id})).await;
+ let after = evaluate(state, &task.id).await;
+ if let Some(t) = &after {
+ super::emit_task(state, t).await;
+ }
+ ok(json!({"task_state": after.map(|t| t.state), "check_id": check.id}))
+}
+
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 16533b7b..0e3465f2 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -43,6 +43,7 @@ pub mod push;
pub mod waiting;
pub mod decide;
pub mod work_ahead;
+pub mod missions;
pub mod app_update_routes;
use crate::broker::PermissionBroker;
@@ -355,6 +356,23 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/questions/:id/answer", post(questions::answer))
.route("/api/messages/:message_id/decisions/:index/change", post(decide::change))
.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/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))
+ .route("/api/missions/:id/run", post(missions::routes::run_mission))
+ .route("/api/tasks", get(missions::routes::list_tasks).post(missions::routes::create_task))
+ .route("/api/tasks/:id", get(missions::routes::get_task).patch(missions::routes::patch_task))
+ .route("/api/tasks/:id/verify", post(missions::routes::verify_task))
+ .route("/api/tasks/:id/reject", post(missions::routes::reject_task))
+ .route("/api/tasks/:id/block", post(missions::routes::block_task))
+ .route("/api/tasks/:id/unblock", post(missions::routes::unblock_task))
+ .route("/api/tasks/:id/retry", post(missions::routes::retry_task))
+ .route("/api/tasks/:id/cancel", post(missions::routes::cancel_task))
+ .route("/api/tasks/:id/checks", post(missions::routes::add_task_check))
+ .route("/api/tasks/:id/checks/run", post(missions::routes::run_task_checks))
+ .route("/api/checks/:id/approve", post(missions::routes::approve_check))
.route("/api/questions/:id/cancel", post(questions::cancel))
.route("/api/human-steps", get(human_steps::list))
.route("/api/human-steps/:id", get(human_steps::get))
diff --git a/src/server/routes.rs b/src/server/routes.rs
index df8f4e47..00d05353 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2422,6 +2422,9 @@ async fn run_kwant_turn_inner(
// Counts toward the chain's token budget (see `super::budget`)
let fresh = output.usage.map_or(output.tokens_used as u64, |u| u.fresh());
state.turns.add_job_tokens(&scope.job_id, fresh);
+ // …and toward the task the bot holds, if any (see `super::missions`)
+ let turn_started_ms = chrono::Utc::now().timestamp_millis() - turn_start.elapsed().as_millis() as i64;
+ super::missions::spend(state, &target_kwant.id, &scope.context_id(target_kwant), Some(&tag.turn_id), turn_started_ms, fresh).await;
let mut reply_text = output.text.clone();
let saved = match &opts.discussion {
@@ -3254,6 +3257,12 @@ pub struct SettingsResponse {
pub work_ahead: bool,
/// Work-ahead runs per space per day (1–10).
pub work_ahead_daily_cap: u64,
+ /// Mission Control: the board, the bots' task tools and the mission runner (see `super::missions`).
+ pub mission_board: bool,
+ /// Minutes a task claim lives without activity (5–240).
+ pub mission_lease_minutes: i64,
+ /// A new mission's token budget when none is given.
+ pub mission_default_budget_tokens: i64,
}
/// Unknown keys are refused, so a typo or a key from another version fails loudly instead of
@@ -3286,6 +3295,9 @@ pub struct SaveSettingsPayload {
pub decide_first: Option<bool>,
pub work_ahead: Option<bool>,
pub work_ahead_daily_cap: Option<u64>,
+ pub mission_board: Option<bool>,
+ pub mission_lease_minutes: Option<i64>,
+ pub mission_default_budget_tokens: Option<i64>,
}
pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {
@@ -3327,6 +3339,9 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settings
decide_first: super::decide::enabled(&state).await,
work_ahead: super::decide::work_ahead_enabled(&state).await,
work_ahead_daily_cap: super::decide::work_ahead_cap(&state).await,
+ mission_board: super::missions::enabled(&state).await,
+ mission_lease_minutes: super::missions::lease_minutes(&state).await,
+ mission_default_budget_tokens: super::missions::default_budget(&state).await,
}))
}
@@ -3373,6 +3388,9 @@ pub async fn save_settings(
if payload.work_ahead_daily_cap.is_some_and(|n| !(1..=super::decide::MAX_WORK_AHEAD_CAP).contains(&n)) {
return bad(format!("work_ahead_daily_cap must be 1–{}", super::decide::MAX_WORK_AHEAD_CAP));
}
+ if let Some(e) = super::missions::settings_error(payload.mission_lease_minutes, payload.mission_default_budget_tokens) {
+ return bad(e);
+ }
if payload.chain_token_budget.is_some_and(|n| n > super::budget::MAX) {
return bad(format!("chain_token_budget must be 0–{}", super::budget::MAX));
}
@@ -3462,6 +3480,15 @@ pub async fn save_settings(
if let Some(n) = payload.work_ahead_daily_cap {
let _ = state.db.set_setting(super::decide::WORK_AHEAD_CAP_SETTING, &n.to_string()).await;
}
+ if let Some(on) = payload.mission_board {
+ let _ = state.db.set_setting(super::missions::SETTING, if on { "true" } else { "false" }).await;
+ }
+ if let Some(m) = payload.mission_lease_minutes {
+ let _ = state.db.set_setting(super::missions::LEASE_SETTING, &m.to_string()).await;
+ }
+ if let Some(n) = payload.mission_default_budget_tokens {
+ let _ = state.db.set_setting(super::missions::BUDGET_SETTING, &n.to_string()).await;
+ }
if let Some(on) = payload.agent_tools {
let _ = state.db.set_setting("agent_tools", if on { "on" } else { "off" }).await;
}
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index 47af9769..4bc7a295 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -651,6 +651,7 @@ pub fn spawn(state: AppState, shutdown: CancellationToken) -> tokio::task::JoinH
super::parked::run_due(&state, Utc::now()).await;
super::waiting::run_due(&state, Utc::now()).await;
super::work_ahead::scan(&state, Utc::now(), false).await;
+ super::missions::runner::tick(&state).await;
let next = [
state.db.next_routine_due().await.ok().flatten(),
state.db.next_parked_due().await.ok().flatten(),
@@ -682,5 +683,6 @@ pub fn spawn_background(state: AppState, shutdown: CancellationToken) {
super::continuity::spawn_notifier(state.clone());
crate::zombie::hunt::spawn(state.clone(), shutdown.clone());
crate::documents::reminders::spawn(state.clone(), shutdown.clone());
+ super::missions::listener::spawn(state.clone(), shutdown.clone());
spawn(state, shutdown);
}
diff --git a/src/server/sse.rs b/src/server/sse.rs
index 282c9069..9b507be6 100644
--- a/src/server/sse.rs
+++ b/src/server/sse.rs
@@ -107,6 +107,7 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {
E::DecideUpdated { kwant_id, context_id, thread_id, .. } => contexts([context_id, thread_id, &Some(kwant_id.clone())]),
E::Error { kwant_id, .. } => contexts([kwant_id]),
E::RoutineRun { routine_id, .. } => vec![Owner::Routine(routine_id.clone())],
+ E::TaskUpdated { task: v } | E::MissionUpdated { mission: v } => fields(v, &["space_id"], Owner::Space),
E::Notify { space_id, kwant_id, channel_id, .. } => {
let mut out: Vec<Owner> = space_id.iter().cloned().map(Owner::Space).collect();
out.extend(contexts([channel_id, &Some(kwant_id.clone())]));
@@ -280,6 +281,8 @@ mod tests {
E::Error { code: s("x"), message: s("x"), kwant_id: Some(s("k")) },
E::MemoryChanged { kwant_id: s("k") },
E::RoutineRun { routine_id: s("r"), run_id: s("x"), status: s("ok") },
+ E::TaskUpdated { task: json!({"id": "t", "space_id": "spc_x"}) },
+ E::MissionUpdated { mission: json!({"id": "m", "space_id": "spc_x"}) },
E::Notify {
kind: s("x"),
kwant_id: s("k"),
@@ -328,6 +331,8 @@ mod tests {
| E::Error { .. }
| E::MemoryChanged { .. }
| E::RoutineRun { .. }
+ | E::TaskUpdated { .. }
+ | E::MissionUpdated { .. }
| E::Notify { .. } => {}
}
}
diff --git a/src/server/work_ahead.rs b/src/server/work_ahead.rs
index a05b4e06..c539db15 100644
--- a/src/server/work_ahead.rs
+++ b/src/server/work_ahead.rs
@@ -202,6 +202,8 @@ pub async fn run(state: &AppState, c: Candidate, row: WorkAheadRun) -> Option<Me
let saved = scope.save(&scope.message("kwant", &c.lead.name, text), Some(meta)).await;
let _ = state.db.finish_work_ahead_run(&row.id, if saved.is_some() { "posted" } else { "failed" }, saved.as_ref().map(|m| m.id.as_str()), tokens).await;
let saved = saved?;
+ let place = (scope.channel_id.clone(), scope.kwant_id.clone(), scope.thread_id.clone());
+ super::missions::listener::on_work_ahead_posted(state, &c.lead, place, &row.id, &saved.text).await;
let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or(Value::Null) });
notify(
state,
diff --git a/tests/mission_control_test.rs b/tests/mission_control_test.rs
new file mode 100644
index 00000000..cba3c37f
--- /dev/null
+++ b/tests/mission_control_test.rs
@@ -0,0 +1,481 @@
+//! Mission Control (Phase A): one task board where a task is `verified` only by an outcome check
+//! that isn't its owner's own claim. Covers the hard rules: verification, dependencies, atomic
+//! claims with expiring leases, the append-only event log, the mission budget, person-only routes,
+//! approval of bot-added commands, folder escapes, and the run hook Rigel's eval drives.
+
+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,
+ other: 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(), other: kwants[1].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)
+}
+
+async fn ok(e: &Env, token: &str, name: &str, args: Value) -> Value {
+ let (v, err, text) = tool(e, token, name, args.clone()).await;
+ assert!(!err, "{name} {args} failed: {text}");
+ v
+}
+
+async fn refused(e: &Env, token: &str, name: &str, args: Value) -> String {
+ let (_, err, text) = tool(e, token, name, args.clone()).await;
+ assert!(err, "{name} {args} should be refused: {text}");
+ 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
+}
+
+async fn state_of(e: &Env, id: &str) -> String {
+ task(e, id).await["task"]["state"].as_str().unwrap().to_string()
+}
+
+/// A mission the person creates (active at once), led by `e.bot`; returns `(mission, tasks)`.
+async fn mission(e: &Env, budget: i64, tasks: Value) -> (Value, Vec<Value>) {
+ let body = json!({"title": "Ship it", "goal": "a release", "lead_kwant_id": e.bot.id, "budget_tokens": budget,
+ "channel_id": e.general, "tasks": tasks});
+ let m = person(e, "POST", "/api/missions", Some(body)).await;
+ let detail = person(e, "GET", &format!("/api/missions/{}", m["id"].as_str().unwrap()), None).await;
+ let mut tasks = detail["tasks"].as_array().unwrap().clone();
+ tasks.sort_by_key(|t| t["title"].as_str().unwrap().to_string());
+ (detail["mission"].clone(), tasks)
+}
+
+fn id(v: &Value) -> String {
+ v["id"].as_str().unwrap().to_string()
+}
+
+async fn folder(e: &Env, mission_id: &str) -> std::path::PathBuf {
+ let m = e.state.db.get_mission(mission_id).await.unwrap().unwrap();
+ let p = std::path::PathBuf::from(m.workspace_path);
+ std::fs::create_dir_all(&p).unwrap();
+ p
+}
+
+#[tokio::test]
+async fn tools_exist_only_while_the_board_is_on() {
+ let e = setup().await;
+ let token = turn(&e, &e.bot, "t-list").await;
+ let names = |v: &Value| v["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect::<Vec<_>>();
+ let (_, v) = call(&e.app, "POST", "/api/mcp/self", Some(&token), Some(rpc("tools/list", json!({})))).await;
+ assert!(names(&v).contains(&"task_claim".to_string()));
+ person(&e, "POST", "/api/settings", Some(json!({"mission_board": false}))).await;
+ let (_, v) = call(&e.app, "POST", "/api/mcp/self", Some(&token), Some(rpc("tools/list", json!({})))).await;
+ assert!(!names(&v).iter().any(|n| n.starts_with("task_") || n == "mission_plan"));
+ refused(&e, &token, "task_list", json!({})).await;
+}
+
+#[tokio::test]
+async fn a_bot_cannot_verify_its_own_work_only_a_passing_check_does() {
+ let e = setup().await;
+ let token = turn(&e, &e.bot, "t-plan").await;
+ let plan = ok(&e, &token, "mission_plan", json!({
+ "title": "Notes", "goal": "write notes",
+ "tasks": [{"key": "a", "title": "Write notes", "owner": e.bot.id,
+ "checks": [{"kind": "file_contains", "spec": {"path": "notes.md", "text": "done"}}]}]
+ })).await;
+ let mid = plan["mission"]["id"].as_str().or(plan["mission_id"].as_str()).unwrap().to_string();
+ let detail = person(&e, "GET", &format!("/api/missions/{mid}"), None).await;
+ assert_eq!(detail["mission"]["status"], "draft");
+ let tid = id(&detail["tasks"][0]);
+ assert_eq!(state_of(&e, &tid).await, "backlog", "nothing runs before the person approves");
+ refused(&e, &token, "task_claim", json!({"task_id": tid})).await;
+
+ // Approval is the person's
+ let (status, _) = call(&e.app, "POST", &format!("/api/missions/{mid}/approve"), Some(&token), None).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ person(&e, "POST", &format!("/api/missions/{mid}/approve"), None).await;
+ assert_eq!(state_of(&e, &tid).await, "ready");
+
+ ok(&e, &token, "task_claim", json!({"task_id": tid})).await;
+ refused(&e, &token, "task_update", json!({"task_id": tid, "status": "verified"})).await;
+ // Claiming done without the outcome: the check fails, the task goes back to ready
+ ok(&e, &token, "task_update", json!({"task_id": tid, "status": "review"})).await;
+ let t = task(&e, &tid).await;
+ assert_eq!(t["task"]["state"], "ready", "{t}");
+ assert_eq!(t["task"]["attempts"], 1);
+ assert_eq!(t["checks"][0]["status"], "failed");
+ assert_eq!(t["checks"][0]["checked_by"], "kwant");
+ let insights = person(&e, "GET", "/api/missions/insights", None).await;
+ assert_eq!(insights["false_success_7d"], 1, "{insights}");
+
+ // Now the outcome is real
+ std::fs::write(folder(&e, &mid).await.join("notes.md"), "all done").unwrap();
+ ok(&e, &token, "task_claim", json!({"task_id": tid})).await;
+ ok(&e, &token, "task_update", json!({"task_id": tid, "status": "review"})).await;
+ let t = task(&e, &tid).await;
+ assert_eq!(t["task"]["state"], "verified", "{t}");
+ assert_eq!(t["task"]["checks_summary"]["status"], "passed");
+ assert!(t["evidence"].as_array().unwrap().iter().any(|ev| ev["kind"] == "check_output" && ev["captured_by"] == "kwant"));
+ let kinds: Vec<&str> = t["events"].as_array().unwrap().iter().map(|ev| ev["kind"].as_str().unwrap()).collect();
+ assert!(kinds.contains(&"check_result") && kinds.contains(&"claimed"), "{kinds:?}");
+ let insights = person(&e, "GET", "/api/missions/insights", None).await;
+ assert_eq!(insights["verified_7d"], 1);
+}
+
+#[tokio::test]
+async fn the_owner_cannot_review_itself_a_teammate_needs_evidence() {
+ let e = setup().await;
+ let (m, tasks) = mission(&e, 200_000, json!([{"title": "Draft", "owner": e.bot.id}])).await;
+ let tid = id(&tasks[0]);
+ let token = turn(&e, &e.bot, "t-own").await;
+ let peer = turn(&e, &e.other, "t-peer").await;
+
+ ok(&e, &token, "task_claim", json!({"task_id": tid})).await;
+ refused(&e, &peer, "task_update", json!({"task_id": tid, "status": "review"})).await;
+ let ev = ok(&e, &token, "task_attach_evidence", json!({"task_id": tid, "kind": "note", "label": "draft", "text": "here it is"})).await;
+ let ev_id = ev["evidence_id"].as_str().unwrap().to_string();
+ ok(&e, &token, "task_update", json!({"task_id": tid, "status": "review"})).await;
+ let t = task(&e, &tid).await;
+ assert_eq!(t["task"]["state"], "review", "no checks: it waits for a review");
+ assert_eq!(t["task"]["checks_summary"]["status"], "not_checked");
+
+ refused(&e, &token, "task_review", json!({"task_id": tid, "verdict": "pass", "evidence_ids": [ev_id], "note": "lgtm"})).await;
+ refused(&e, &peer, "task_review", json!({"task_id": tid, "verdict": "pass", "evidence_ids": [], "note": "lgtm"})).await;
+ refused(&e, &peer, "task_review", json!({"task_id": tid, "verdict": "pass", "evidence_ids": ["not-on-this-task"], "note": "lgtm"})).await;
+ ok(&e, &peer, "task_review", json!({"task_id": tid, "verdict": "pass", "evidence_ids": [ev_id], "note": "read it"})).await;
+ let t = task(&e, &tid).await;
+ assert_eq!(t["task"]["state"], "verified", "{t}");
+ let review = t["checks"].as_array().unwrap().iter().find(|c| c["kind"] == "peer_review").unwrap().clone();
+ assert_eq!(review["checked_by"], e.other.id.as_str());
+ assert_eq!(review["status"], "passed");
+ let _ = m;
+}
+
+#[tokio::test]
+async fn a_task_is_ready_only_after_its_dependencies_are_verified() {
+ let e = setup().await;
+ let token = turn(&e, &e.bot, "t-deps").await;
+ let plan = ok(&e, &token, "mission_plan", json!({
+ "title": "Two steps", "goal": "in order",
+ "tasks": [{"key": "a", "title": "A first", "owner": e.bot.id},
+ {"key": "b", "title": "B second", "owner": e.bot.id, "depends_on": ["a"]}]
+ })).await;
+ let mid = plan["mission"]["id"].as_str().or(plan["mission_id"].as_str()).unwrap().to_string();
+ person(&e, "POST", &format!("/api/missions/{mid}/approve"), None).await;
+ let detail = person(&e, "GET", &format!("/api/missions/{mid}"), None).await;
+ let by_title = |t: &str| detail["tasks"].as_array().unwrap().iter().find(|x| x["title"] == t).map(id).unwrap();
+ let (a, b) = (by_title("A first"), by_title("B second"));
+ let tb = task(&e, &b).await;
+ assert_eq!(tb["task"]["state"], "backlog");
+ assert_eq!(tb["task"]["waiting_on"], json!([a]));
+ refused(&e, &token, "task_claim", json!({"task_id": b})).await;
+ // Not even a raw write gets around it
+ let raw = e.state.db.exec_raw_for_test(&format!("UPDATE tasks SET state = 'ready' WHERE id = '{b}'")).await;
+ assert!(raw.is_err(), "a raw write must not make a waiting task ready");
+
+ ok(&e, &token, "task_claim", json!({"task_id": a})).await;
+ ok(&e, &token, "task_update", json!({"task_id": a, "status": "review"})).await;
+ assert_eq!(state_of(&e, &b).await, "backlog", "review is not verified");
+ person(&e, "POST", &format!("/api/tasks/{a}/verify"), Some(json!({"note": "checked by hand"}))).await;
+ assert_eq!(state_of(&e, &a).await, "verified");
+ assert_eq!(state_of(&e, &b).await, "ready");
+}
+
+#[tokio::test]
+async fn claims_are_atomic_one_at_a_time_and_leases_expire() {
+ let e = setup().await;
+ let (_, tasks) = mission(&e, 500_000, json!([{"title": "One"}, {"title": "Two"}])).await;
+ let (one, two) = (id(&tasks[0]), id(&tasks[1]));
+ let db = &e.state.db;
+ let (r1, r2) = tokio::join!(
+ db.claim_task(&one, &e.bot.id, None, None, 60_000, false, &e.bot.id),
+ db.claim_task(&one, &e.other.id, None, None, 60_000, false, &e.other.id),
+ );
+ let wins = [r1.unwrap().is_ok(), r2.unwrap().is_ok()];
+ assert_eq!(wins.iter().filter(|w| **w).count(), 1, "exactly one claim wins: {wins:?}");
+ let holder = if wins[0] { &e.bot } else { &e.other };
+ // One live claim per bot
+ assert!(db.claim_task(&two, &holder.id, None, None, 60_000, false, &holder.id).await.unwrap().is_err());
+
+ db.expire_claim_now(&one).await.unwrap();
+ assert!(missions::sweep_leases(&e.state).await >= 1);
+ let t = task(&e, &one).await;
+ assert_eq!(t["task"]["state"], "ready");
+ assert!(t["task"]["claim"].is_null());
+ assert!(t["events"].as_array().unwrap().iter().any(|ev| ev["kind"] == "lease_expired"));
+ // A worked-on task without a live lease is refused by the database itself
+ let raw = db.exec_raw_for_test(&format!("UPDATE tasks SET state = 'working' WHERE id = '{one}'")).await;
+ assert!(raw.is_err());
+}
+
+#[tokio::test]
+async fn the_event_log_is_append_only_and_verified_needs_a_check() {
+ let e = setup().await;
+ let (_, tasks) = mission(&e, 200_000, json!([{"title": "Only"}])).await;
+ let tid = id(&tasks[0]);
+ let db = &e.state.db;
+ assert!(!task(&e, &tid).await["events"].as_array().unwrap().is_empty());
+ assert!(db.exec_raw_for_test("UPDATE task_events SET kind = 'note'").await.is_err());
+ assert!(db.exec_raw_for_test("DELETE FROM task_events").await.is_err());
+ assert!(db.exec_raw_for_test(&format!("UPDATE tasks SET state = 'verified' WHERE id = '{tid}'")).await.is_err());
+ // Verify from anywhere but review is refused through the API too
+ let (status, v) = call(&e.app, "POST", &format!("/api/tasks/{tid}/verify"), None, Some(json!({}))).await;
+ assert_eq!(status, StatusCode::CONFLICT, "{v}");
+ assert!(v["error"].is_string());
+}
+
+#[tokio::test]
+async fn the_mission_budget_is_never_exceeded() {
+ let e = setup().await;
+ let (m, tasks) = mission(&e, 10_000, json!([
+ {"title": "A", "owner": e.bot.id, "budget_tokens": 6_000},
+ {"title": "B", "owner": e.other.id, "budget_tokens": 6_000}
+ ])).await;
+ let db = &e.state.db;
+ assert!(db.claim_task(&id(&tasks[0]), &e.bot.id, None, None, 60_000, false, &e.bot.id).await.unwrap().is_ok());
+ let second = db.claim_task(&id(&tasks[1]), &e.other.id, None, None, 60_000, false, &e.other.id).await.unwrap();
+ assert!(matches!(second, Err(kwnt::db::missions::ClaimRefused::Budget { .. })), "{second:?}");
+ let detail = person(&e, "GET", &format!("/api/missions/{}", id(&m)), None).await;
+ assert_eq!(detail["mission"]["reserved_tokens"], 6_000);
+ assert_eq!(detail["mission"]["over_budget"], false);
+ // The person can't set the budget below what's already reserved or spent either
+ let (status, _) = call(&e.app, "PATCH", &format!("/api/missions/{}", id(&m)), None, Some(json!({"budget_tokens": 10}))).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+}
+
+#[tokio::test]
+async fn board_changes_are_the_persons_bot_tokens_get_403() {
+ let e = setup().await;
+ let (m, tasks) = mission(&e, 200_000, json!([{"title": "X"}])).await;
+ let token = turn(&e, &e.bot, "t-403").await;
+ let tid = id(&tasks[0]);
+ for (method, uri) in [
+ ("POST", "/api/missions".to_string()),
+ ("POST", format!("/api/missions/{}/run", id(&m))),
+ ("POST", format!("/api/missions/{}/cancel", id(&m))),
+ ("POST", "/api/tasks".to_string()),
+ ("POST", format!("/api/tasks/{tid}/verify")),
+ ("PATCH", format!("/api/tasks/{tid}")),
+ ("POST", format!("/api/tasks/{tid}/checks")),
+ ("POST", "/api/checks/x/approve".to_string()),
+ ] {
+ let (status, _) = call(&e.app, method, &uri, Some(&token), Some(json!({"title": "t", "reason": "r"}))).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{method} {uri}");
+ }
+ let (status, _) = call(&e.app, "GET", "/api/tasks", Some(&token), None).await;
+ assert_eq!(status, StatusCode::OK, "reads stay open");
+}
+
+#[tokio::test]
+async fn a_command_a_bot_adds_later_waits_for_the_persons_approval() {
+ let e = setup().await;
+ let (m, tasks) = mission(&e, 200_000, json!([{"title": "Build", "owner": e.bot.id}])).await;
+ let tid = id(&tasks[0]);
+ let token = turn(&e, &e.bot, "t-cmd").await;
+ let marker = folder(&e, &id(&m)).await.join("ran.txt");
+ let added = ok(&e, &token, "task_request_check", json!({"task_id": tid, "kind": "command", "spec": {"command": "echo hi > ran.txt"}})).await;
+ let check = added["checks"].as_array().unwrap().iter().find(|c| c["kind"] == "command").unwrap().clone();
+ assert_eq!(check["approved"], false, "{added}");
+ assert!(!marker.exists(), "an unapproved command never runs");
+ // A URL on this computer is the person's call too, even a dev-server port WebFetch allows
+ let local = ok(&e, &token, "task_request_check", json!({"task_id": tid, "kind": "http", "spec": {"url": "http://127.0.0.1:5173/"}})).await;
+ assert!(local["checks"].as_array().unwrap().iter().all(|c| c["approved"] == false), "{local}");
+ let t = task(&e, &tid).await;
+ assert!(t["checks"].as_array().unwrap().iter().all(|c| c["status"] == "needs_approval"), "{t}");
+ let (status, _) = call(&e.app, "POST", &format!("/api/checks/{}/approve", id(&check)), Some(&token), None).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ let approved = person(&e, "POST", &format!("/api/checks/{}/approve", id(&check)), None).await;
+ assert_eq!(approved["approved"], true);
+ // A command the person adds is approved at once
+ let c = person(&e, "POST", &format!("/api/tasks/{tid}/checks"), Some(json!({"kind": "command", "spec": {"command": "true"}}))).await;
+ assert_eq!(c["approved"], true);
+ let run = person(&e, "POST", &format!("/api/tasks/{tid}/checks/run"), None).await;
+ for c in run["checks"].as_array().unwrap() {
+ // The local URL nobody approved never ran; the approved ones passed
+ let want = if c["kind"] == "http" { "needs_approval" } else { "passed" };
+ assert_eq!(c["status"], want, "{run}");
+ }
+ assert!(marker.exists());
+}
+
+#[tokio::test]
+async fn evidence_and_checks_stay_inside_the_folder_and_skip_secrets() {
+ let e = setup().await;
+ let (m, tasks) = mission(&e, 200_000, json!([{"title": "Files", "owner": e.bot.id}])).await;
+ let tid = id(&tasks[0]);
+ let dir = folder(&e, &id(&m)).await;
+ std::fs::write(dir.join(".env"), "TOKEN=x").unwrap();
+ std::fs::write(dir.join("out.txt"), "hello").unwrap();
+ let token = turn(&e, &e.bot, "t-files").await;
+ ok(&e, &token, "task_claim", json!({"task_id": tid})).await;
+ for path in ["../../etc/passwd", "/etc/passwd", ".env"] {
+ refused(&e, &token, "task_attach_evidence", json!({"task_id": tid, "kind": "file", "label": "x", "path": path})).await;
+ }
+ let ev = ok(&e, &token, "task_attach_evidence", json!({"task_id": tid, "kind": "file", "label": "out", "path": "out.txt", "sha256": "fake"})).await;
+ assert_eq!(ev["bytes"], 5);
+ assert_eq!(ev["sha256"], "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", "kwant hashes it itself");
+ let c = person(&e, "POST", &format!("/api/tasks/{tid}/checks"), Some(json!({"kind": "file_exists", "spec": {"path": "../outside"}}))).await;
+ let run = person(&e, "POST", &format!("/api/tasks/{tid}/checks/run"), None).await;
+ let res = run["checks"].as_array().unwrap().iter().find(|x| x["id"] == c["id"]).unwrap().clone();
+ assert_ne!(res["status"], "passed", "{res}");
+}
+
+#[tokio::test]
+async fn the_run_hook_starts_one_turn_per_mission_and_releases_an_unfinished_task() {
+ let e = setup().await;
+ let (m, tasks) = mission(&e, 200_000, json!([{"title": "Go", "owner": e.bot.id}])).await;
+ let tid = id(&tasks[0]);
+ let out = person(&e, "POST", &format!("/api/missions/{}/run", id(&m)), Some(json!({"max_tasks": 1}))).await;
+ assert_eq!(out["started"][0]["task_id"], tid.as_str(), "{out}");
+ assert_eq!(out["started"][0]["kwant_id"], e.bot.id.as_str());
+ let (status, _) = call(&e.app, "POST", &format!("/api/missions/{}/run", id(&m)), None, Some(json!({"max_tasks": 9}))).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ // No engine is set up here, so the turn ends without a review: the lease is let go
+ let mut released = false;
+ for _ in 0..100 {
+ let t = task(&e, &tid).await;
+ if t["events"].as_array().unwrap().iter().any(|ev| ev["kind"] == "released") {
+ assert_eq!(t["task"]["attempts"], 1);
+ assert_ne!(t["task"]["state"], "working");
+ released = true;
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ }
+ assert!(released, "the runner releases a task its turn didn't finish");
+}
+
+#[tokio::test]
+async fn the_owners_own_check_waits_for_the_person_before_it_can_verify() {
+ let e = setup().await;
+ let (m, tasks) = mission(&e, 200_000, json!([{"title": "Out", "owner": e.bot.id}])).await;
+ let tid = id(&tasks[0]);
+ std::fs::write(folder(&e, &id(&m)).await.join("out.txt"), "made it").unwrap();
+ let token = turn(&e, &e.bot, "t-own-check").await;
+ ok(&e, &token, "task_claim", json!({"task_id": tid})).await;
+ // A file check is safe to run, but it's the owner's own: it waits like a command would
+ let added = ok(&e, &token, "task_request_check", json!({"task_id": tid, "kind": "file_exists", "spec": {"path": "out.txt"}})).await;
+ let check = added["checks"][0].clone();
+ assert_eq!((check["approved"].as_bool(), check["status"].as_str()), (Some(false), Some("needs_approval")), "{added}");
+ ok(&e, &token, "task_update", json!({"task_id": tid, "status": "review"})).await;
+ let t = task(&e, &tid).await;
+ assert_eq!(t["task"]["state"], "review", "its own file_exists doesn't verify it: {t}");
+ assert_eq!(t["checks"][0]["counts"], false);
+ assert_eq!(t["checks"][0]["approved_by"], Value::Null);
+ assert_eq!(t["task"]["checks_summary"]["needs_approval"], 1);
+ assert_eq!(t["task"]["needs_you"][0]["kind"], "check_approval", "{t}");
+ assert_eq!(t["task"]["needs_you"][0]["id"], check["id"]);
+ let insights = person(&e, "GET", "/api/missions/insights", None).await;
+ assert_eq!(insights["needs_you_now"], 1, "{insights}");
+
+ let approved = person(&e, "POST", &format!("/api/checks/{}/approve", id(&check)), None).await;
+ assert_eq!((approved["approved_by"].as_str(), approved["counts"].as_bool()), (Some("person"), Some(true)), "{approved}");
+ let t = task(&e, &tid).await;
+ assert_eq!(t["task"]["state"], "verified", "approved and passing: {t}");
+ assert_eq!(t["task"]["needs_you"], json!([]));
+}
+
+#[tokio::test]
+async fn every_check_must_pass_one_waiting_for_approval_holds_the_task_in_review() {
+ let e = setup().await;
+ let (m, tasks) = mission(&e, 200_000, json!([{"title": "Page", "owner": e.bot.id,
+ "checks": [{"kind": "file_exists", "spec": {"path": "page.html"}}]}])).await;
+ let tid = id(&tasks[0]);
+ std::fs::write(folder(&e, &id(&m)).await.join("page.html"), "<h1>hi</h1>").unwrap();
+ // A teammate adds a check of a local URL: the person's call
+ let peer = turn(&e, &e.other, "t-peer-http").await;
+ let added = ok(&e, &peer, "task_request_check", json!({"task_id": tid, "kind": "http", "spec": {"url": "http://127.0.0.1:9/"}})).await;
+ assert_eq!(added["checks"][0]["status"], "needs_approval", "{added}");
+ let token = turn(&e, &e.bot, "t-page").await;
+ ok(&e, &token, "task_claim", json!({"task_id": tid})).await;
+ ok(&e, &token, "task_update", json!({"task_id": tid, "status": "review"})).await;
+ let t = task(&e, &tid).await;
+ assert_eq!(t["task"]["state"], "review", "1 of 2 passed is not verified: {t}");
+ let s = &t["task"]["checks_summary"];
+ assert_eq!((s["status"].as_str(), s["passed"].as_u64(), s["needs_approval"].as_u64()), (Some("pending"), Some(1), Some(1)), "{s}");
+ let plan_check = t["checks"].as_array().unwrap().iter().find(|c| c["kind"] == "file_exists").unwrap().clone();
+ assert_eq!((plan_check["approved_by"].as_str(), plan_check["counts"].as_bool()), (Some("person"), Some(true)));
+ assert_eq!(t["task"]["needs_you"][0]["kind"], "check_approval");
+ // Once approved it runs, fails (nothing listens there), and the task goes back to ready
+ let http = t["checks"].as_array().unwrap().iter().find(|c| c["kind"] == "http").unwrap().clone();
+ person(&e, "POST", &format!("/api/checks/{}/approve", id(&http)), None).await;
+ let t = task(&e, &tid).await;
+ assert_eq!(t["task"]["state"], "ready", "{t}");
+ assert_eq!(t["task"]["attempts"], 1);
+}
diff --git a/tests/mission_spend_test.rs b/tests/mission_spend_test.rs
new file mode 100644
index 00000000..314ad2c5
--- /dev/null
+++ b/tests/mission_spend_test.rs
@@ -0,0 +1,161 @@
+//! Mission Control spend through the real end-of-turn path: the mission runner starts a turn on a
+//! fake claude CLI, which calls `task_update review` through the turn's own MCP server (so the
+//! claim is released inside the turn), then reports its usage. The turn's tokens must still land
+//! on the task and the mission, and the mission budget must use that number. Its own test binary:
+//! it changes PATH and listens on a real port the CLI calls back on.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::Database,
+ router::LayaRouter,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::sync::OnceLock;
+use std::time::Duration;
+use tower::ServiceExt;
+
+/// On a Mission Control prompt, moves the task it holds to review through the kwant tools in its
+/// `--mcp-config`, then reports 12 new input, 8,211 cache-write, 83,544 cache-read and 487 output
+/// tokens: 8,710 fresh.
+const FAKE_CLAUDE: &str = r#"#!/usr/bin/env python3
+import json, re, sys, urllib.request
+args = sys.argv[1:]
+if args[:1] == ["auth"]:
+ print('{"loggedIn":true}')
+ sys.exit(0)
+prompt = args[-1] if args else ""
+held = re.search(r"You hold task (\S+) of", prompt)
+if held and "--mcp-config" in args:
+ with open(args[args.index("--mcp-config") + 1]) as f:
+ servers = json.load(f).get("mcpServers", {})
+ for s in servers.values():
+ if s.get("url", "").endswith("/api/mcp/self"):
+ call = {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": {"name": "task_update", "arguments": {"task_id": held.group(1), "status": "review"}}}
+ headers = dict(s.get("headers", {}), **{"content-type": "application/json"})
+ req = urllib.request.Request(s["url"], data=json.dumps(call).encode(), headers=headers)
+ urllib.request.urlopen(req, timeout=30).read()
+print(json.dumps({"type": "result", "is_error": False, "num_turns": 1, "result": "done, sent for review",
+ "total_cost_usd": 0.42,
+ "usage": {"input_tokens": 12, "cache_creation_input_tokens": 8211,
+ "cache_read_input_tokens": 83544, "output_tokens": 487},
+ "modelUsage": {"claude-opus-5-5": {"outputTokens": 487}}}))
+"#;
+
+const FRESH_PER_TURN: i64 = 12 + 8_211 + 487;
+
+fn fake_cli() {
+ static DONE: OnceLock<PathBuf> = OnceLock::new();
+ DONE.get_or_init(|| {
+ let bin = tempfile::tempdir().unwrap().keep().join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ let fake = bin.join("claude");
+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ bin
+ });
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ let body = body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let s = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+async fn ok(app: &Router, method: &str, uri: &str, body: Option<Value>) -> Value {
+ let (s, v) = call(app, method, uri, body).await;
+ assert!(s.is_success(), "{method} {uri}: {s} {v}");
+ v
+}
+
+#[tokio::test]
+async fn a_turn_that_finishes_its_task_still_pays_for_itself() {
+ fake_cli();
+ let tmp = tempfile::tempdir().unwrap();
+ // The CLI reaches its kwant tools over HTTP, so kwant listens for real
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config {
+ data_dir: tmp.path().to_path_buf(),
+ host: "127.0.0.1".into(),
+ port,
+ laya_url: "http://127.0.0.1:9".into(),
+ browser_cdp_url: Some("http://127.0.0.1:9".into()),
+ ..Config::default()
+ };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let app = create_router(state.clone());
+ let served = app.clone();
+ tokio::spawn(async move { axum::serve(listener, served).await.unwrap() });
+
+ ok(&app, "POST", "/api/settings", Some(json!({"mission_board": true}))).await;
+ let bot = json!({"name": "Ann", "title": "Ann the tester", "persona_prompt": "Test persona",
+ "avatar_sprite": "s", "driver_type": "cli", "preferred_model": "claude"});
+ let ann = ok(&app, "POST", "/api/kwants", Some(bot)).await["id"].as_str().unwrap().to_string();
+ let channel = ok(&app, "POST", "/api/channels", Some(json!({"name": "desk", "lead_kwant_id": ann, "member_kwants": []}))).await;
+ let channel = channel["id"].as_str().unwrap().to_string();
+ let body = json!({"title": "Ship it", "goal": "a release", "lead_kwant_id": ann, "budget_tokens": 10_000, "channel_id": channel,
+ "tasks": [{"title": "A", "owner": ann, "budget_tokens": 9_000},
+ {"title": "B", "owner": ann, "budget_tokens": 2_000}]});
+ let m = ok(&app, "POST", "/api/missions", Some(body)).await;
+ let mid = m["id"].as_str().unwrap().to_string();
+ let detail = ok(&app, "GET", &format!("/api/missions/{mid}"), None).await;
+ let by_title = |t: &str| detail["tasks"].as_array().unwrap().iter().find(|x| x["title"] == t).unwrap()["id"].as_str().unwrap().to_string();
+ let (a, b) = (by_title("A"), by_title("B"));
+
+ let run = ok(&app, "POST", &format!("/api/missions/{mid}/run"), Some(json!({"max_tasks": 1}))).await;
+ let started = run["started"][0]["task_id"].as_str().unwrap().to_string();
+ let other = if started == a { b.clone() } else { a.clone() };
+ assert_eq!(started, a, "the runner starts the first task: {run}");
+
+ // The turn moves A to review (releasing its claim) and then ends with its usage
+ let mut t = Value::Null;
+ for _ in 0..300 {
+ t = ok(&app, "GET", &format!("/api/tasks/{a}"), None).await;
+ if t["task"]["spent_tokens"].as_i64().unwrap_or(0) > 0 {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ assert_eq!(t["task"]["state"], "review", "the bot sent it for review inside the turn: {t}");
+ assert!(t["task"]["claim"].is_null(), "review released the claim: {t}");
+ assert_eq!(t["task"]["spent_tokens"], FRESH_PER_TURN, "the turn's tokens land on the task: {t}");
+ let released = t["events"].as_array().unwrap().iter().any(|ev| ev["to_state"] == "review");
+ assert!(released, "{t}");
+ let detail = ok(&app, "GET", &format!("/api/missions/{mid}"), None).await;
+ assert_eq!(detail["mission"]["spent_tokens"], FRESH_PER_TURN, "…and on the mission: {detail}");
+
+ // The budget uses that real number: 10,000 − 8,710 can't cover B's 2,000
+ let lease = 60_000;
+ let refused = state.db.claim_task(&other, &ann, None, None, lease, false, &ann).await.unwrap();
+ match refused {
+ Err(kwnt::db::missions::ClaimRefused::Budget { remaining, needed }) => {
+ assert_eq!((remaining, needed), (10_000 - FRESH_PER_TURN, 2_000));
+ }
+ other => panic!("B must not start past the mission budget: {other:?}"),
+ }
+}