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 B1: work graph, may-be-invalid flags, fork, Idempotency-Key

Lin (kwant bot)5445b8c1c821
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b889775a..23a56a82 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
### Added
+- **Mission Control: work graph and "may be invalid" flags (backend).** When a verified task's evidence
+ file changes or disappears, or a verified task is redone, kwant flags that task and the started tasks
+ that directly depend on it as "may be invalid". Their state never changes, and only you decide:
+ still valid, redo, or cancel. Redo forks the task, so verified history stays untouched. New
+ endpoints serve the mission's graph (`/api/missions/:id/graph`), flags, forks and an on-demand drift
+ scan. Fork and retry accept an `Idempotency-Key`. The board UI follows separately.
- **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
diff --git a/docs/mission-control.md b/docs/mission-control.md
index 6190dec3..538a9a9c 100644
--- a/docs/mission-control.md
+++ b/docs/mission-control.md
@@ -292,3 +292,106 @@ because kwant counts tokens when a model call returns.
`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).
+
+## 11. Work graph (Phase B1)
+
+Design and decisions: `/home/maus/shared/ship-software-safely/mission-control/phase-b/contract.md` §2
+and `decisions.md` (D1–D3). A verified task stays final. When its inputs may have changed, kwant
+**flags** it as "may be invalid", and the person decides. A flag never changes any task's state.
+
+### Tables
+
+- `tasks.forked_from TEXT`: the task this one redoes (a fork), else NULL.
+- `task_flags`:
+ - `id`, `task_id`, `kind` (`may_be_invalid`)
+ - `cause`: one of `evidence_changed`, `upstream_evidence_changed`, `upstream_forked`
+ - `cause_task_id`: the upstream task, or the task itself for `evidence_changed`
+ - `detail` JSON, `created_at`
+ - `resolved_at`, `resolved_by`, and `resolution`: one of `still_valid`, `redo`, `cancelled`
+- Indexes and triggers on `task_flags`:
+ - The unique index `task_flags_one_open (task_id, cause_task_id, cause) WHERE resolved_at IS NULL` allows at most one open flag per cause.
+ - `task_flags_resolve_once`: a resolved flag can't change.
+ - `task_flags_person_resolves`: only `resolved_by = 'person'` resolves a flag.
+ - `task_flags_no_delete`: flags are never deleted.
+- `idempotency_keys (key, route, response, created_at)` keeps each key for 24 h.
+- `graph_scans (mission_id, scanned_at, skipped)` records each mission's last drift scan. It feeds the graph's `scanned_at`/`scan_skipped` and the 10-minute throttle.
+
+### When a flag is raised
+
+1. **Evidence drift.** The scan looks at each verified task's `file` evidence and uses the latest row per path.
+ - If the file now hashes differently or is gone, the task gets `evidence_changed` with detail `{path, old_sha256, new_sha256|null}`.
+ - Each **direct** dependent that has started gets `upstream_evidence_changed`. Started means the state is past `ready`, or `attempts > 0`, or the task was ever claimed. Cancelled dependents are left out.
+2. **Fork of a verified task.** Each started direct dependent of the original gets `upstream_forked`, with detail `{fork_id, reason}`.
+
+Things that are never flagged:
+- Backlog or ready dependents, and anything further down the graph (D2). The graph shows how many tasks sit further down as `downstream`.
+- A drift that a flag already recorded: same task, cause task, cause, path and new hash. Once the person calls a drift `still_valid`, the same file contents don't flag it again. A new change does.
+
+Each flag:
+- writes a `flagged` event (actor `kwant`, no state change);
+- posts a line in the mission's chat (or the task's own) as the owner;
+- adds a `{"kind": "may_be_invalid", "id": <flag id>, "text": "Check this still holds: …"}` item to `needs_you` in **every** state. Insights `needs_you_now` counts flagged tasks.
+
+Bots have no tool to resolve a flag (D1).
+
+### The drift scan
+
+- The runner tick scans each active mission at most every 10 minutes. `POST /api/missions/:id/graph/scan` also runs it on demand for any mission that isn't cancelled, which matters because a mission whose tasks are all verified is `done`.
+- It hashes at most 200 files and skips files over 50 MB.
+- Paths go through the same `inside(folder, rel)` guard as evidence capture: no `..`, nothing outside the task folder, no secret or env files.
+- A skipped file is reported with a reason and never counts as changed.
+
+### Resolving (person only)
+
+`POST /api/tasks/:id/flags/:flag_id/resolve` with body `{"resolution", "note"?}` writes `flag_resolved` (actor `person`).
+
+| resolution | effect |
+|---|---|
+| `still_valid` | Closes the flag. The task is unchanged. |
+| `redo` | **Verified:** forks the task and returns the fork. **review/failed:** moves it to `ready` (attempts reset). **blocked:** moves it to `backlog`. **backlog/ready:** just closes the flag. **working/needs_you:** 409 "it's running; resolve when it stops". **cancelled:** 409. |
+| `cancelled` | A verified task gets 409. A cancelled task just has the flag closed. Any other task is cancelled. |
+
+Other responses:
+- 409 when the flag is already resolved.
+- 404 when the flag belongs to another task.
+- Success returns `{flag, task, fork|null}`.
+
+### Fork (person only)
+
+`POST /api/tasks/:id/fork` with body `{"reason", "from_checkpoint"?}`.
+- `reason` is required, at most 500 characters.
+- `from_checkpoint` gets 400 until Phase B2.
+- The `Idempotency-Key` header is optional.
+
+The new `backlog` task copies these from the original:
+- `mission_id`, `title`, `acceptance`, `priority`, `budget_tokens`, `max_attempts`, `source_kind` and the chat;
+- its dependencies;
+- its checks, reset to pending with results cleared. An approval carries over only when `approved_by` is `person` or `mission`. Any other check waits for approval again (`needs_approval`).
+
+Other fields on the new task:
+- `suggested_kwant_id` is the original's owner.
+- `source_id` is NULL, `created_by` is `person`, and `forked_from` is the original's id.
+
+What else happens:
+- The original is untouched. Its dependents are not rewired (D3).
+- `promote_one` runs on the fork.
+- Events: `forked` on the original (`{fork_id, reason}`) and `created` on the fork (`{forked_from}`).
+- A `done` mission opens again (`active`) so the fork can run. A cancelled mission refuses with 409.
+
+### Idempotency-Key
+
+The header works on `POST /api/tasks/:id/fork` and `POST /api/tasks/:id/retry`. Keys are 1–200 characters.
+- The same key on the same route (method plus path, task id included) returns the stored response with `idempotent-replayed: true`, and nothing runs again.
+- The same key on another route gets 422.
+- Only successful responses are stored. Keyed requests run one at a time.
+
+### Graph routes
+
+- `GET /api/missions/:id/graph` returns `{mission_id, nodes, edges, scanned_at, scan_skipped}`.
+ - Each node: `{id, title, state, owner_kwant_id, owner_name, attempts, max_attempts, forked_from, downstream, flags (open), checks_summary}`.
+ - Each edge: `{from: depends_on_id, to: task_id}`.
+- `GET /api/graph` is the active space's tasks without a mission: open ones, plus ones finished in the last 7 days. `mission_id` is null there, and so is `scanned_at`.
+- `GET /api/tasks/:id/flags` lists open flags; `?all=1` adds resolved ones. Flag shape: `{id, kind, cause, cause_task_id, cause_title, detail, created_at, resolved_at, resolution}`.
+- `POST /api/missions/:id/graph/scan` (person only) returns `{scanned, flagged: [flag ids], skipped: [{task_id, path, why}]}`.
+- `task_json` gains `forked_from` and `flags` (open only).
+- There are no new SSE types: flags and forks go out as `task_updated` and `mission_updated`.
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index 4a68264e..cba1b2bc 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -41,8 +41,11 @@ export interface Mission {
}
export interface NeedsYouItem {
- /** check_approval: a required check waits for the person's OK (id = the check's id); only on tasks in review. Optional checks never appear here. */
- kind: 'question' | 'approval' | 'human_step' | 'check_approval';
+ /** check_approval: a required check waits for the person's OK (id = the check's id); only on tasks in review.
+ * Optional checks never appear here.
+ * may_be_invalid: an open flag (id = the flag's id), in any state, verified included; resolve it with
+ * `POST /api/tasks/:id/flags/:flag_id/resolve`. */
+ kind: 'question' | 'approval' | 'human_step' | 'check_approval' | 'may_be_invalid';
id: string;
text: string;
}
@@ -95,6 +98,80 @@ export interface Task {
claim: Claim | null;
needs_you: NeedsYouItem[];
checks_summary: ChecksSummary;
+ /** The task this one redoes (a fork); older servers leave it out. */
+ forked_from?: string | null;
+ /** Open "may be invalid" flags; older servers leave it out. */
+ flags?: TaskFlag[];
+}
+
+// Work graph (Phase B1, docs/mission-control.md §11)
+
+export type FlagCause = 'evidence_changed' | 'upstream_evidence_changed' | 'upstream_forked';
+export type FlagResolution = 'still_valid' | 'redo' | 'cancelled';
+
+export interface TaskFlag {
+ id: string;
+ kind: 'may_be_invalid';
+ cause: FlagCause;
+ /** The upstream task, or the task itself for evidence_changed. */
+ cause_task_id: string;
+ cause_title: string | null;
+ /** evidence_*: {path, old_sha256, new_sha256 (null when the file is gone)}; upstream_forked: {fork_id, reason}. */
+ detail: Record<string, unknown>;
+ created_at: string;
+ resolved_at: string | null;
+ resolution: FlagResolution | null;
+}
+
+export interface GraphNode {
+ id: string;
+ title: string;
+ state: TaskState;
+ owner_kwant_id: string | null;
+ owner_name: string | null;
+ attempts: number;
+ max_attempts: number;
+ forked_from: string | null;
+ /** Tasks that depend on this one, directly or further down ("N more downstream"). */
+ downstream: number;
+ /** Open flags only. */
+ flags: TaskFlag[];
+ checks_summary: ChecksSummary;
+}
+
+/** `from` is the upstream task (depends_on_id), `to` the task that depends on it. */
+export interface GraphEdge {
+ from: string;
+ to: string;
+}
+
+export interface ScanSkipped {
+ task_id: string;
+ path: string;
+ why: string;
+}
+
+/** `GET /api/missions/:id/graph`, or `GET /api/graph` (tasks without a mission; mission_id null). */
+export interface WorkGraph {
+ mission_id: string | null;
+ nodes: GraphNode[];
+ edges: GraphEdge[];
+ scanned_at: string | null;
+ scan_skipped: ScanSkipped[];
+}
+
+/** `POST /api/missions/:id/graph/scan`. */
+export interface GraphScanResult {
+ scanned: number;
+ flagged: string[];
+ skipped: ScanSkipped[];
+}
+
+/** `POST /api/tasks/:id/flags/:flag_id/resolve`: the closed flag, the task, and the fork when `redo` forked a verified task. */
+export interface ResolveFlagResult {
+ flag: TaskFlag;
+ task: Task;
+ fork: Task | null;
}
export interface Check {
diff --git a/src/db/mission_graph.rs b/src/db/mission_graph.rs
new file mode 100644
index 00000000..b53d3a4b
--- /dev/null
+++ b/src/db/mission_graph.rs
@@ -0,0 +1,369 @@
+//! Mission Control Phase B1: the work graph's "may be invalid" flags, forks of a task (redo
+//! without touching verified history), the drift scan's bookkeeping and HTTP idempotency keys.
+//! Contract: docs/mission-control.md §11. As in Phase A, the rules hold twice: in
+//! [`crate::server::missions::graph`] and by SQLite triggers here, so a flag is resolved only by
+//! the person, only once, and never deleted.
+
+use super::missions::{insert_event, Task};
+use super::spaces::SpaceId;
+use super::{Database, DbError};
+use chrono::{DateTime, Utc};
+use serde::Serialize;
+use serde_json::Value;
+use sqlx::FromRow;
+use uuid::Uuid;
+
+pub const FLAG_CAUSES: [&str; 3] = ["evidence_changed", "upstream_evidence_changed", "upstream_forked"];
+pub const FLAG_RESOLUTIONS: [&str; 3] = ["still_valid", "redo", "cancelled"];
+/// How long an `Idempotency-Key` is remembered.
+pub const IDEMPOTENCY_HOURS: i64 = 24;
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct TaskFlag {
+ pub id: String,
+ pub task_id: String,
+ pub kind: String,
+ pub cause: String,
+ pub cause_task_id: String,
+ /// The cause task's title (joined in).
+ pub cause_title: Option<String>,
+ /// JSON text; see [`TaskFlag::detail_value`].
+ #[serde(skip)]
+ pub detail: String,
+ pub created_at: DateTime<Utc>,
+ pub resolved_at: Option<DateTime<Utc>>,
+ pub resolved_by: Option<String>,
+ pub resolution: Option<String>,
+}
+
+impl TaskFlag {
+ pub fn detail_value(&self) -> Value {
+ serde_json::from_str(&self.detail).unwrap_or(Value::Null)
+ }
+}
+
+/// A mission's last drift scan.
+#[derive(Debug, Clone, FromRow, PartialEq)]
+pub struct GraphScan {
+ pub mission_id: String,
+ pub scanned_at: DateTime<Utc>,
+ /// JSON array of `{task_id, path, why}`.
+ pub skipped: String,
+}
+
+const FLAG_SELECT: &str = "SELECT f.id, f.task_id, f.kind, f.cause, f.cause_task_id, c.title AS cause_title, f.detail, \
+ f.created_at, f.resolved_at, f.resolved_by, f.resolution FROM task_flags f LEFT JOIN tasks c ON c.id = f.cause_task_id";
+
+const TRIGGERS: [&str; 3] = [
+ // A flag is resolved once, and only by the person
+ "CREATE TRIGGER IF NOT EXISTS task_flags_resolve_once BEFORE UPDATE ON task_flags \
+ WHEN OLD.resolved_at IS NOT NULL \
+ BEGIN SELECT RAISE(ABORT, 'a flag is resolved once'); END",
+ "CREATE TRIGGER IF NOT EXISTS task_flags_person_resolves BEFORE UPDATE ON task_flags \
+ WHEN NEW.resolved_at IS NOT NULL AND COALESCE(NEW.resolved_by, '') != 'person' \
+ BEGIN SELECT RAISE(ABORT, 'only the person resolves a flag'); END",
+ // Flags are history
+ "CREATE TRIGGER IF NOT EXISTS task_flags_no_delete BEFORE DELETE ON task_flags \
+ BEGIN SELECT RAISE(ABORT, 'flags are history'); END",
+];
+
+impl Database {
+ pub(super) async fn migrate_mission_graph(&self) -> Result<(), DbError> {
+ // The task this one redoes (a fork); fails harmlessly once the column exists
+ let _ = sqlx::query("ALTER TABLE tasks ADD COLUMN forked_from TEXT").execute(&self.pool).await;
+ for stmt in [
+ "CREATE TABLE IF NOT EXISTS task_flags (
+ id TEXT PRIMARY KEY,
+ task_id TEXT NOT NULL REFERENCES tasks(id),
+ kind TEXT NOT NULL CHECK (kind IN ('may_be_invalid')),
+ cause TEXT NOT NULL CHECK (cause IN ('evidence_changed', 'upstream_evidence_changed', 'upstream_forked')),
+ cause_task_id TEXT NOT NULL REFERENCES tasks(id),
+ detail TEXT NOT NULL DEFAULT '{}',
+ created_at TIMESTAMP NOT NULL,
+ resolved_at TIMESTAMP,
+ resolved_by TEXT,
+ resolution TEXT CHECK (resolution IN ('still_valid', 'redo', 'cancelled'))
+ )",
+ "CREATE UNIQUE INDEX IF NOT EXISTS task_flags_one_open ON task_flags (task_id, cause_task_id, cause) WHERE resolved_at IS NULL",
+ "CREATE INDEX IF NOT EXISTS task_flags_task ON task_flags (task_id, resolved_at)",
+ "CREATE INDEX IF NOT EXISTS tasks_forked_from ON tasks (forked_from)",
+ "CREATE TABLE IF NOT EXISTS idempotency_keys (
+ key TEXT PRIMARY KEY,
+ route TEXT NOT NULL,
+ response TEXT NOT NULL,
+ created_at TIMESTAMP NOT NULL
+ )",
+ "CREATE TABLE IF NOT EXISTS graph_scans (
+ mission_id TEXT PRIMARY KEY,
+ scanned_at TIMESTAMP NOT NULL,
+ skipped TEXT NOT NULL DEFAULT '[]'
+ )",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ for t in TRIGGERS {
+ sqlx::query(t).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ // Flags
+
+ /// Raises a flag unless the same one (task, cause task, cause) is already open. Writes a
+ /// `flagged` event with the flag in the same transaction. `Ok(None)` when it was already open.
+ pub async fn raise_flag(&self, task_id: &str, cause: &str, cause_task_id: &str, detail: &Value) -> Result<Option<TaskFlag>, DbError> {
+ let id = Uuid::new_v4().to_string();
+ let mut tx = self.pool.begin().await?;
+ let r = sqlx::query(
+ "INSERT OR IGNORE INTO task_flags (id, task_id, kind, cause, cause_task_id, detail, created_at) VALUES (?, ?, 'may_be_invalid', ?, ?, ?, ?)",
+ )
+ .bind(&id)
+ .bind(task_id)
+ .bind(cause)
+ .bind(cause_task_id)
+ .bind(detail.to_string())
+ .bind(Utc::now())
+ .execute(&mut *tx)
+ .await?;
+ if r.rows_affected() == 0 {
+ return Ok(None);
+ }
+ let flag = sqlx::query_as::<_, TaskFlag>(&format!("{FLAG_SELECT} WHERE f.id = ?")).bind(&id).fetch_one(&mut *tx).await?;
+ let event = serde_json::json!({"flag_id": flag.id, "kind": flag.kind, "cause": flag.cause, "cause_task_id": flag.cause_task_id, "detail": flag.detail_value()});
+ insert_event(&mut tx, task_id, None, "flagged", "kwant", None, None, &event).await?;
+ tx.commit().await?;
+ Ok(Some(flag))
+ }
+
+ pub async fn get_flag(&self, id: &str) -> Result<Option<TaskFlag>, DbError> {
+ Ok(sqlx::query_as::<_, TaskFlag>(&format!("{FLAG_SELECT} WHERE f.id = ?")).bind(id).fetch_optional(&self.pool).await?)
+ }
+
+ /// The task's flags, oldest first; open ones only unless `all`.
+ pub async fn flags_of(&self, task_id: &str, all: bool) -> Result<Vec<TaskFlag>, DbError> {
+ Ok(sqlx::query_as::<_, TaskFlag>(&format!("{FLAG_SELECT} WHERE f.task_id = ? AND (? OR f.resolved_at IS NULL) ORDER BY f.created_at, f.rowid"))
+ .bind(task_id)
+ .bind(all)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Whether a flag (open or resolved) already records this drift: same task, cause task, cause,
+ /// path and new hash. A drift the person called still valid isn't raised again.
+ pub async fn drift_known(&self, task_id: &str, cause: &str, cause_task_id: &str, path: &str, new_sha256: Option<&str>) -> Result<bool, DbError> {
+ let (n,): (i64,) = sqlx::query_as(
+ "SELECT COUNT(*) FROM task_flags WHERE task_id = ? AND cause = ? AND cause_task_id = ? \
+ AND json_extract(detail, '$.path') = ? AND json_extract(detail, '$.new_sha256') IS ?",
+ )
+ .bind(task_id)
+ .bind(cause)
+ .bind(cause_task_id)
+ .bind(path)
+ .bind(new_sha256)
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(n > 0)
+ }
+
+ /// Closes an open flag as the person. False when it was already resolved.
+ pub async fn resolve_flag(&self, id: &str, resolution: &str, note: Option<&str>, detail: Option<&Value>) -> Result<bool, DbError> {
+ let mut tx = self.pool.begin().await?;
+ let r = sqlx::query("UPDATE task_flags SET resolved_at = ?, resolved_by = 'person', resolution = ? WHERE id = ? AND resolved_at IS NULL")
+ .bind(Utc::now())
+ .bind(resolution)
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ if r.rows_affected() == 0 {
+ return Ok(false);
+ }
+ let (task_id,): (String,) = sqlx::query_as("SELECT task_id FROM task_flags WHERE id = ?").bind(id).fetch_one(&mut *tx).await?;
+ let mut event = serde_json::json!({"flag_id": id, "resolution": resolution, "note": note});
+ if let (Some(obj), Some(Value::Object(more))) = (event.as_object_mut(), detail) {
+ obj.extend(more.clone());
+ }
+ insert_event(&mut tx, &task_id, None, "flag_resolved", "person", None, None, &event).await?;
+ tx.commit().await?;
+ Ok(true)
+ }
+
+ /// Ids of the space's tasks with an open flag.
+ pub async fn flagged_task_ids(&self, space: &SpaceId) -> Result<Vec<String>, DbError> {
+ let rows: Vec<(String,)> = sqlx::query_as(
+ "SELECT DISTINCT f.task_id FROM task_flags f JOIN tasks t ON t.id = f.task_id WHERE t.space_id = ? AND f.resolved_at IS NULL",
+ )
+ .bind(space.as_str())
+ .fetch_all(&self.pool)
+ .await?;
+ Ok(rows.into_iter().map(|r| r.0).collect())
+ }
+
+ // The graph
+
+ /// Direct dependents of `task_id` that have started: past `ready`, attempted, or ever claimed.
+ /// Cancelled ones are left alone.
+ pub async fn started_dependents(&self, task_id: &str) -> Result<Vec<Task>, DbError> {
+ Ok(sqlx::query_as::<_, Task>(
+ "SELECT t.* FROM tasks t JOIN task_dependencies d ON d.task_id = t.id AND d.depends_on_id = ? \
+ WHERE t.state != 'cancelled' AND (t.state NOT IN ('backlog', 'ready') OR t.attempts > 0 \
+ OR EXISTS (SELECT 1 FROM agent_claims a WHERE a.task_id = t.id)) ORDER BY t.created_at, t.rowid",
+ )
+ .bind(task_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Dependency edges among `task_ids` as (from = depends_on_id, to = task_id).
+ pub async fn edges_among(&self, task_ids: &[String]) -> Result<Vec<(String, String)>, DbError> {
+ if task_ids.is_empty() {
+ return Ok(Vec::new());
+ }
+ let ids = serde_json::to_string(task_ids)?;
+ Ok(sqlx::query_as(
+ "SELECT d.depends_on_id, d.task_id FROM task_dependencies d \
+ WHERE d.task_id IN (SELECT value FROM json_each(?1)) AND d.depends_on_id IN (SELECT value FROM json_each(?1)) \
+ ORDER BY d.rowid",
+ )
+ .bind(ids)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// The space's tasks without a mission: open ones, and ones finished since `since`.
+ pub async fn loose_tasks(&self, space: &SpaceId, since: DateTime<Utc>) -> Result<Vec<Task>, DbError> {
+ Ok(sqlx::query_as::<_, Task>(
+ "SELECT * FROM tasks WHERE space_id = ? AND mission_id IS NULL \
+ AND (state NOT IN ('verified', 'cancelled') OR COALESCE(finished_at, updated_at) >= ?) \
+ ORDER BY priority DESC, created_at, rowid LIMIT 500",
+ )
+ .bind(space.as_str())
+ .bind(since)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Verified tasks of the mission, for the drift scan.
+ pub async fn verified_in_mission(&self, mission_id: &str) -> Result<Vec<Task>, DbError> {
+ Ok(sqlx::query_as::<_, Task>("SELECT * FROM tasks WHERE mission_id = ? AND state = 'verified' ORDER BY created_at, rowid")
+ .bind(mission_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ pub async fn graph_scan(&self, mission_id: &str) -> Result<Option<GraphScan>, DbError> {
+ Ok(sqlx::query_as::<_, GraphScan>("SELECT * FROM graph_scans WHERE mission_id = ?").bind(mission_id).fetch_optional(&self.pool).await?)
+ }
+
+ pub async fn record_graph_scan(&self, mission_id: &str, skipped: &Value) -> Result<(), DbError> {
+ sqlx::query("INSERT INTO graph_scans (mission_id, scanned_at, skipped) VALUES (?, ?, ?) ON CONFLICT(mission_id) DO UPDATE SET scanned_at = excluded.scanned_at, skipped = excluded.skipped")
+ .bind(mission_id)
+ .bind(Utc::now())
+ .bind(skipped.to_string())
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ // Forks
+
+ /// A new backlog task redoing `orig`: same mission, title, acceptance, priority, budget and
+ /// attempts, suggested to the original owner, the same dependencies, and the same checks reset
+ /// to pending (approval carries over only when the person or the approved plan gave it). The
+ /// original is untouched. Logs `forked` on the original and `created` on the fork.
+ pub async fn fork_task(&self, orig: &Task, reason: &str) -> Result<Task, DbError> {
+ let now = Utc::now();
+ let mut tx = self.pool.begin().await?;
+ let fork = sqlx::query_as::<_, Task>(
+ "INSERT INTO tasks (id, space_id, mission_id, title, acceptance, state, priority, suggested_kwant_id, budget_tokens, max_attempts, \
+ source_kind, source_id, channel_id, direct_kwant_id, thread_id, created_by, created_at, updated_at, forked_from) \
+ VALUES (?, ?, ?, ?, ?, 'backlog', ?, ?, ?, ?, ?, NULL, ?, ?, ?, 'person', ?, ?, ?) RETURNING *",
+ )
+ .bind(Uuid::new_v4().to_string())
+ .bind(&orig.space_id)
+ .bind(&orig.mission_id)
+ .bind(&orig.title)
+ .bind(&orig.acceptance)
+ .bind(orig.priority)
+ .bind(orig.owner_kwant_id.as_ref().or(orig.suggested_kwant_id.as_ref()))
+ .bind(orig.budget_tokens)
+ .bind(orig.max_attempts)
+ .bind(&orig.source_kind)
+ .bind(&orig.channel_id)
+ .bind(&orig.direct_kwant_id)
+ .bind(&orig.thread_id)
+ .bind(now)
+ .bind(now)
+ .bind(&orig.id)
+ .fetch_one(&mut *tx)
+ .await?;
+ sqlx::query("INSERT INTO task_dependencies (task_id, depends_on_id) SELECT ?, depends_on_id FROM task_dependencies WHERE task_id = ?")
+ .bind(&fork.id)
+ .bind(&orig.id)
+ .execute(&mut *tx)
+ .await?;
+ let checks = sqlx::query_as::<_, super::missions::OutcomeCheck>("SELECT * FROM outcome_checks WHERE task_id = ? ORDER BY created_at, rowid")
+ .bind(&orig.id)
+ .fetch_all(&mut *tx)
+ .await?;
+ for c in &checks {
+ let keep = c.approved && matches!(c.approved_by.as_deref(), Some("person" | "mission"));
+ sqlx::query(
+ "INSERT INTO outcome_checks (id, task_id, kind, spec, required, approved, status, requested_by, approved_by, created_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ )
+ .bind(Uuid::new_v4().to_string())
+ .bind(&fork.id)
+ .bind(&c.kind)
+ .bind(&c.spec)
+ .bind(c.required)
+ .bind(keep)
+ .bind(if keep { "pending" } else { "needs_approval" })
+ .bind(&c.requested_by)
+ .bind(if keep { c.approved_by.clone() } else { None })
+ .bind(now)
+ .execute(&mut *tx)
+ .await?;
+ }
+ insert_event(&mut tx, &orig.id, orig.mission_id.as_deref(), "forked", "person", None, None, &serde_json::json!({"fork_id": fork.id, "reason": reason})).await?;
+ insert_event(
+ &mut tx,
+ &fork.id,
+ fork.mission_id.as_deref(),
+ "created",
+ "person",
+ None,
+ Some("backlog"),
+ &serde_json::json!({"source_kind": fork.source_kind, "forked_from": orig.id, "reason": reason}),
+ )
+ .await?;
+ tx.commit().await?;
+ Ok(fork)
+ }
+
+ /// Forks of `task_id`, newest first.
+ pub async fn forks_of(&self, task_id: &str) -> Result<Vec<Task>, DbError> {
+ Ok(sqlx::query_as::<_, Task>("SELECT * FROM tasks WHERE forked_from = ? ORDER BY created_at DESC, rowid DESC").bind(task_id).fetch_all(&self.pool).await?)
+ }
+
+ // Idempotency keys
+
+ /// The stored response for `key` as (route, response JSON), forgetting keys older than 24 h.
+ pub async fn idempotent_response(&self, key: &str) -> Result<Option<(String, String)>, DbError> {
+ sqlx::query("DELETE FROM idempotency_keys WHERE created_at < ?")
+ .bind(Utc::now() - chrono::Duration::hours(IDEMPOTENCY_HOURS))
+ .execute(&self.pool)
+ .await?;
+ Ok(sqlx::query_as("SELECT route, response FROM idempotency_keys WHERE key = ?").bind(key).fetch_optional(&self.pool).await?)
+ }
+
+ pub async fn store_idempotent_response(&self, key: &str, route: &str, response: &Value) -> Result<(), DbError> {
+ sqlx::query("INSERT OR IGNORE INTO idempotency_keys (key, route, response, created_at) VALUES (?, ?, ?, ?)")
+ .bind(key)
+ .bind(route)
+ .bind(response.to_string())
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+}
diff --git a/src/db/missions.rs b/src/db/missions.rs
index 3c1ce802..a148f9ad 100644
--- a/src/db/missions.rs
+++ b/src/db/missions.rs
@@ -69,6 +69,8 @@ pub struct Task {
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub finished_at: Option<DateTime<Utc>>,
+ /// The task this one redoes (a fork, Phase B1); `None` otherwise.
+ pub forked_from: Option<String>,
}
/// A lease on a task. Times are unix milliseconds so the SQLite triggers can compare them.
@@ -1144,7 +1146,7 @@ impl Default for TaskChange {
}
#[allow(clippy::too_many_arguments)]
-async fn insert_event(
+pub(super) async fn insert_event(
tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
task_id: &str,
mission_id: Option<&str>,
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 3401d710..82374876 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -25,6 +25,7 @@ pub mod work_ahead;
pub mod api_context;
pub mod usage;
pub mod missions;
+pub mod mission_graph;
/// What a space's #general says about itself.
pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
@@ -158,6 +159,7 @@ impl Database {
db.migrate_api_context().await?;
db.migrate_usage().await?;
db.migrate_missions().await?;
+ db.migrate_mission_graph().await?;
if spaces {
let migration = db.migrate_spaces(data_dir, fresh).await?;
db.require_spaces_schema(&migration).await?;
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 5ec4c2a3..6bb2adea 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -847,6 +847,11 @@ mod tests {
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(&post, "/api/tasks/t1/fork"));
+ assert!(person_only(&post, "/api/tasks/t1/flags/f1/resolve"));
+ assert!(person_only(&post, "/api/missions/m1/graph/scan"));
+ assert!(!person_only(&get, "/api/missions/m1/graph"));
+ assert!(!person_only(&get, "/api/tasks/t1/flags"));
assert!(!person_only(&get, "/api/tasks"));
assert!(!person_only(&get, "/api/missions/insights"));
assert!(person_only(&post, "/api/passwords/bitwarden/unlock"));
diff --git a/src/server/missions/graph.rs b/src/server/missions/graph.rs
new file mode 100644
index 00000000..96fa67c2
--- /dev/null
+++ b/src/server/missions/graph.rs
@@ -0,0 +1,538 @@
+//! Phase B1: the work graph. "May be invalid" flags (evidence drift and forks of verified work),
+//! the drift scan, resolving a flag (the person only) and forking a task to redo it. A flag never
+//! moves a task; only the person's resolution does. Contract: docs/mission-control.md §11.
+#![allow(clippy::result_large_err)]
+
+use super::checks::{hex, inside};
+use super::routes::{bad, conflict, internal, load_mission, load_task, moved, not_found};
+use super::{emit_mission, emit_task, emit_task_id, name_of, post_line, task_folder, task_json, transition, Actor};
+use crate::db::mission_graph::{GraphScan, TaskFlag, FLAG_RESOLUTIONS};
+use crate::db::missions::{Mission, Task, TaskChange};
+use crate::server::spaces::Scope;
+use crate::server::AppState;
+use axum::{
+ extract::{Path, RawQuery, State},
+ http::{HeaderMap, StatusCode},
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde::Deserialize;
+use serde_json::{json, Value};
+use std::collections::{HashMap, HashSet};
+
+/// Most evidence files one scan hashes.
+pub const SCAN_MAX_FILES: usize = 200;
+/// Files over this are skipped, never treated as changed.
+pub const SCAN_MAX_BYTES: u64 = 50 * 1024 * 1024;
+/// The runner scans an active mission at most this often.
+pub const SCAN_EVERY_MINUTES: i64 = 10;
+
+pub fn flag_json(f: &TaskFlag) -> Value {
+ json!({
+ "id": f.id,
+ "kind": f.kind,
+ "cause": f.cause,
+ "cause_task_id": f.cause_task_id,
+ "cause_title": f.cause_title,
+ "detail": f.detail_value(),
+ "created_at": f.created_at,
+ "resolved_at": f.resolved_at,
+ "resolution": f.resolution,
+ })
+}
+
+/// Why the task may no longer hold, as a sentence.
+pub fn cause_text(f: &TaskFlag) -> String {
+ let d = f.detail_value();
+ let path = d["path"].as_str().unwrap_or("a file");
+ let upstream = f.cause_title.as_deref().unwrap_or("a task it depends on");
+ match f.cause.as_str() {
+ "evidence_changed" if d["new_sha256"].is_null() => format!("its evidence file {path} is gone"),
+ "evidence_changed" => format!("its evidence file {path} changed"),
+ "upstream_evidence_changed" => format!("\"{upstream}\", which it depends on, has a changed evidence file ({path})"),
+ "upstream_forked" => format!("\"{upstream}\", which it depends on, is being redone"),
+ _ => "an input changed".into(),
+ }
+}
+
+pub async fn open_flags(state: &AppState, task: &Task) -> Vec<Value> {
+ state.db.flags_of(&task.id, false).await.unwrap_or_default().iter().map(flag_json).collect()
+}
+
+/// The `needs_you` items of the task's open flags, for every state.
+pub async fn flag_items(state: &AppState, task: &Task) -> Vec<Value> {
+ let flags = state.db.flags_of(&task.id, false).await.unwrap_or_default();
+ flags
+ .iter()
+ .map(|f| {
+ let text = format!("Check this still holds: {}", cause_text(f));
+ json!({"kind": "may_be_invalid", "id": f.id, "text": text.chars().take(200).collect::<String>()})
+ })
+ .collect()
+}
+
+/// Raises a flag on `task` unless the same one is open, then tells the board and the owner.
+async fn raise(state: &AppState, task: &Task, cause: &str, cause_task_id: &str, detail: &Value) -> Option<TaskFlag> {
+ let flag = match state.db.raise_flag(&task.id, cause, cause_task_id, detail).await {
+ Ok(Some(f)) => f,
+ Ok(None) => return None,
+ Err(e) => {
+ tracing::warn!(error = %e, task = %task.id, "could not raise a flag");
+ return None;
+ }
+ };
+ emit_task(state, task).await;
+ flag_chat_line(state, task, &flag).await;
+ Some(flag)
+}
+
+/// Tells the task's owner (in the mission's chat, or the task's own) that it may be invalid.
+/// There is no tool to resolve it: the person decides.
+async fn flag_chat_line(state: &AppState, t: &Task, f: &TaskFlag) {
+ let text = format!("Flagged \"{}\": {}. It may no longer hold; the person decides on the board.", t.title, cause_text(f));
+ let meta = json!({"kind": "mission", "task_id": t.id, "mission_id": t.mission_id, "flag_id": f.id});
+ let m = match &t.mission_id {
+ Some(m) => state.db.get_mission(m).await.ok().flatten(),
+ None => None,
+ };
+ let sender = t.owner_kwant_id.clone().or_else(|| m.as_ref().map(|m| m.lead_kwant_id.clone())).unwrap_or_else(|| "kwant".into());
+ match m {
+ Some(m) => post_line(state, m.channel_id, m.direct_kwant_id, m.thread_id, &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,
+ }
+}
+
+// The drift scan
+
+#[derive(Debug, Default)]
+pub struct ScanResult {
+ pub scanned: usize,
+ pub flagged: Vec<String>,
+ pub skipped: Vec<Value>,
+}
+
+/// The sha256 of `path`, `Ok(None)` when it is gone, or why it was skipped.
+async fn hash_file(path: std::path::PathBuf) -> Result<Option<String>, String> {
+ tokio::task::spawn_blocking(move || {
+ let meta = match std::fs::metadata(&path) {
+ Ok(m) => m,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(_) => return Err("can't be read".to_string()),
+ };
+ if !meta.is_file() {
+ return Err("not a file".into());
+ }
+ if meta.len() > SCAN_MAX_BYTES {
+ return Err("over 50 MB".into());
+ }
+ let mut file = std::fs::File::open(&path).map_err(|_| "can't be read".to_string())?;
+ let mut hasher = <sha2::Sha256 as sha2::Digest>::new();
+ std::io::copy(&mut file, &mut hasher).map_err(|_| "can't be read".to_string())?;
+ Ok(Some(hex(&sha2::Digest::finalize(hasher))))
+ })
+ .await
+ .unwrap_or_else(|_| Err("can't be read".into()))
+}
+
+/// Hashes the file evidence of the mission's verified tasks (the latest row per path) and flags
+/// each task whose file changed or is gone, plus its started direct dependents. Idempotent: an
+/// open flag isn't raised twice, and a drift already flagged (even one the person called still
+/// valid) isn't raised again.
+pub async fn scan_mission(state: &AppState, mission: &Mission) -> ScanResult {
+ let mut out = ScanResult::default();
+ for task in state.db.verified_in_mission(&mission.id).await.unwrap_or_default() {
+ let evidence = state.db.list_evidence(&task.id).await.unwrap_or_default();
+ // Latest row per path: a file captured twice is judged against its last hash
+ let mut latest: Vec<(String, String)> = Vec::new();
+ for e in evidence.iter().rev().filter(|e| e.kind == "file") {
+ let (Some(path), Some(sha)) = (&e.path, &e.sha256) else { continue };
+ if !latest.iter().any(|(p, _)| p == path) {
+ latest.push((path.clone(), sha.clone()));
+ }
+ }
+ latest.reverse();
+ let folder = task_folder(state, &task).await;
+ for (path, old) in latest {
+ let skip = |why: &str| json!({"task_id": task.id, "path": path, "why": why});
+ if out.scanned >= SCAN_MAX_FILES {
+ out.skipped.push(skip("over the 200-file scan limit"));
+ continue;
+ }
+ let Some(folder) = &folder else {
+ out.skipped.push(skip("the task has no folder"));
+ continue;
+ };
+ let real = match inside(folder, &path) {
+ Ok(p) => p,
+ Err(why) => {
+ out.skipped.push(skip(&why));
+ continue;
+ }
+ };
+ let new = match hash_file(real).await {
+ Ok(h) => h,
+ Err(why) => {
+ out.skipped.push(skip(&why));
+ continue;
+ }
+ };
+ out.scanned += 1;
+ if new.as_deref() == Some(old.as_str()) {
+ continue;
+ }
+ let detail = json!({"path": path, "old_sha256": old, "new_sha256": new});
+ if !state.db.drift_known(&task.id, "evidence_changed", &task.id, &path, new.as_deref()).await.unwrap_or(true) {
+ if let Some(f) = raise(state, &task, "evidence_changed", &task.id, &detail).await {
+ out.flagged.push(f.id);
+ }
+ }
+ for dep in state.db.started_dependents(&task.id).await.unwrap_or_default() {
+ if state.db.drift_known(&dep.id, "upstream_evidence_changed", &task.id, &path, new.as_deref()).await.unwrap_or(true) {
+ continue;
+ }
+ if let Some(f) = raise(state, &dep, "upstream_evidence_changed", &task.id, &detail).await {
+ out.flagged.push(f.id);
+ }
+ }
+ }
+ }
+ if let Err(e) = state.db.record_graph_scan(&mission.id, &json!(out.skipped)).await {
+ tracing::warn!(error = %e, mission = %mission.id, "could not record the graph scan");
+ }
+ if !out.flagged.is_empty() {
+ emit_mission(state, &mission.id).await;
+ }
+ out
+}
+
+/// Scans the mission if its last scan is older than [`SCAN_EVERY_MINUTES`]; for the runner tick.
+pub async fn scan_if_due(state: &AppState, mission: &Mission) {
+ let due = match state.db.graph_scan(&mission.id).await {
+ Ok(Some(s)) => chrono::Utc::now() - s.scanned_at >= chrono::Duration::minutes(SCAN_EVERY_MINUTES),
+ Ok(None) => true,
+ Err(_) => false,
+ };
+ if due {
+ scan_mission(state, mission).await;
+ }
+}
+
+// Forks
+
+/// Forks `orig` to redo it (see `Database::fork_task`). A done mission opens again so the fork
+/// runs; a cancelled one refuses. Forking a verified task flags its started direct dependents
+/// (`upstream_forked`); they keep depending on the original until the person decides.
+pub async fn fork(state: &AppState, orig: &Task, reason: &str) -> Result<Task, Response> {
+ if let Some(mid) = &orig.mission_id {
+ let m = match state.db.get_mission(mid).await {
+ Ok(Some(m)) => m,
+ Ok(None) => return Err(not_found("mission")),
+ Err(e) => return Err(internal(e)),
+ };
+ match m.status.as_str() {
+ "cancelled" => return Err(conflict("the mission is cancelled")),
+ "done" if state.db.set_mission_status(mid, "done", "active", Some("person")).await.unwrap_or(false) => {
+ super::mission_chat_line(state, &m, format!("Mission \"{}\" is open again: \"{}\" is being redone.", m.title, orig.title)).await;
+ }
+ _ => {}
+ }
+ }
+ let f = state.db.fork_task(orig, reason).await.map_err(internal)?;
+ if orig.state == "verified" {
+ let detail = json!({"fork_id": f.id, "reason": reason});
+ for dep in state.db.started_dependents(&orig.id).await.unwrap_or_default() {
+ raise(state, &dep, "upstream_forked", &orig.id, &detail).await;
+ }
+ }
+ emit_task_id(state, &orig.id).await;
+ emit_task(state, &f).await;
+ super::promote_one(state, &f).await;
+ if let Some(mid) = &f.mission_id {
+ emit_mission(state, mid).await;
+ }
+ Ok(state.db.get_task(&f.id).await.ok().flatten().unwrap_or(f))
+}
+
+// Idempotency
+
+static IDEMPOTENT: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+
+/// Runs `f` once per `Idempotency-Key`: the same key on the same route returns the stored
+/// response, the same key on another route is refused (422). Only successful responses are
+/// stored, for 24 h. Without the header `f` just runs.
+pub async fn idempotent<F, Fut>(state: &AppState, headers: &HeaderMap, route: String, f: F) -> Response
+where
+ F: FnOnce() -> Fut,
+ Fut: std::future::Future<Output = Result<Value, Response>>,
+{
+ let key = match headers.get("idempotency-key").map(|v| v.to_str().map(str::trim)) {
+ None => return f().await.map_or_else(|r| r, |v| Json(v).into_response()),
+ Some(Ok(k)) if !k.is_empty() && k.len() <= 200 => k.to_string(),
+ Some(_) => return bad("Idempotency-Key must be 1–200 visible characters"),
+ };
+ // One keyed request at a time, so two retries with the same key can't both run
+ let _held = IDEMPOTENT.lock().await;
+ match state.db.idempotent_response(&key).await {
+ Ok(Some((r, _))) if r != route => {
+ return super::routes::err(StatusCode::UNPROCESSABLE_ENTITY, "that Idempotency-Key was used for another request");
+ }
+ Ok(Some((_, stored))) => {
+ let v: Value = serde_json::from_str(&stored).unwrap_or(Value::Null);
+ return ([("idempotent-replayed", "true")], Json(v)).into_response();
+ }
+ Ok(None) => {}
+ Err(e) => return internal(e),
+ }
+ match f().await {
+ Ok(v) => {
+ if let Err(e) = state.db.store_idempotent_response(&key, &route, &v).await {
+ tracing::warn!(error = %e, "could not store an idempotent response");
+ }
+ Json(v).into_response()
+ }
+ Err(r) => r,
+ }
+}
+
+// Routes
+
+#[derive(Deserialize)]
+pub struct ForkBody {
+ #[serde(default)]
+ reason: String,
+ from_checkpoint: Option<String>,
+}
+
+/// `POST /api/tasks/:id/fork` (person-only; `Idempotency-Key` optional).
+pub async fn fork_task(State(state): State<AppState>, RawQuery(q): RawQuery, headers: HeaderMap, Path(id): Path<String>, Json(p): Json<ForkBody>) -> Response {
+ let reason = p.reason.trim().to_string();
+ if reason.is_empty() || reason.chars().count() > 500 {
+ return bad("reason is required (at most 500 characters)");
+ }
+ if p.from_checkpoint.is_some() {
+ return bad("from_checkpoint isn't supported yet");
+ }
+ let route = format!("POST /api/tasks/{id}/fork");
+ idempotent(&state, &headers, route, || async {
+ let orig = load_task(&state, q.as_deref(), &id).await?;
+ let f = fork(&state, &orig, &reason).await?;
+ Ok(task_json(&state, &f).await)
+ })
+ .await
+}
+
+#[derive(Deserialize)]
+pub struct ResolveBody {
+ resolution: String,
+ note: Option<String>,
+}
+
+/// `POST /api/tasks/:id/flags/:flag_id/resolve` (person-only).
+pub async fn resolve_flag(
+ State(state): State<AppState>,
+ RawQuery(q): RawQuery,
+ Path((id, flag_id)): Path<(String, String)>,
+ Json(p): Json<ResolveBody>,
+) -> Response {
+ if !FLAG_RESOLUTIONS.contains(&p.resolution.as_str()) {
+ return bad("resolution must be still_valid, redo or cancelled");
+ }
+ let note = p.note.as_deref().map(str::trim).filter(|n| !n.is_empty()).map(|n| n.chars().take(500).collect::<String>());
+ let t = match load_task(&state, q.as_deref(), &id).await {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ let flag = match state.db.get_flag(&flag_id).await {
+ Ok(Some(f)) if f.task_id == t.id => f,
+ Ok(_) => return not_found("flag"),
+ Err(e) => return internal(e),
+ };
+ if flag.resolved_at.is_some() {
+ return conflict("this flag is already resolved");
+ }
+ let mut fork_out = None;
+ let mut extra = json!({});
+ match (p.resolution.as_str(), t.state.as_str()) {
+ ("still_valid", _) => {}
+ ("redo", "working" | "needs_you") => return conflict("it's running; resolve when it stops"),
+ ("redo", "cancelled") => return conflict("the task is cancelled; fork it to redo it"),
+ ("redo", "verified") => {
+ let reason = note.clone().unwrap_or_else(|| "redo: it may no longer hold".into());
+ match fork(&state, &t, &reason).await {
+ Ok(f) => {
+ extra = json!({"fork_id": f.id});
+ fork_out = Some(f);
+ }
+ Err(r) => return r,
+ }
+ }
+ ("redo", from @ ("review" | "failed")) => {
+ let change = TaskChange { reason: Some("redo: it may no longer hold".into()), detail: Some(json!({"flag_id": flag.id})), ..Default::default() };
+ if let Err(r) = moved(transition(&state, &t.id, from, "ready", Actor::Person, "person", change).await) {
+ return r;
+ }
+ let _ = state.db.reset_attempts(&t.id).await;
+ }
+ ("redo", "blocked") => {
+ let change = TaskChange { reason: Some("redo: it may no longer hold".into()), detail: Some(json!({"flag_id": flag.id})), ..Default::default() };
+ match moved(transition(&state, &t.id, "blocked", "backlog", Actor::Person, "person", change).await) {
+ Ok(t) => super::promote_one(&state, &t).await,
+ Err(r) => return r,
+ }
+ }
+ // backlog or ready: it runs again anyway
+ ("redo", _) => {}
+ ("cancelled", "verified") => return conflict("a verified task can't be cancelled; choose still_valid or redo"),
+ ("cancelled", "cancelled") => {}
+ ("cancelled", from) => {
+ let change = TaskChange { reason: Some("cancelled by the person: it may no longer hold".into()), ..Default::default() };
+ if let Err(r) = moved(transition(&state, &t.id, from, "cancelled", Actor::Person, "person", change).await) {
+ return r;
+ }
+ }
+ _ => return bad("resolution must be still_valid, redo or cancelled"),
+ }
+ match state.db.resolve_flag(&flag.id, &p.resolution, note.as_deref(), Some(&extra)).await {
+ Ok(true) => {}
+ Ok(false) => return conflict("this flag is already resolved"),
+ Err(e) => return internal(e),
+ }
+ let t = state.db.get_task(&t.id).await.ok().flatten().unwrap_or(t);
+ emit_task(&state, &t).await;
+ if let Some(mid) = &t.mission_id {
+ emit_mission(&state, mid).await;
+ }
+ let flag = state.db.get_flag(&flag.id).await.ok().flatten().unwrap_or(flag);
+ let fork_json = match &fork_out {
+ Some(f) => task_json(&state, f).await,
+ None => Value::Null,
+ };
+ Json(json!({"flag": flag_json(&flag), "task": task_json(&state, &t).await, "fork": fork_json})).into_response()
+}
+
+/// `GET /api/tasks/:id/flags` (open ones; `?all=1` adds resolved ones).
+pub async fn task_flags(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 all = q.as_deref().unwrap_or("").split('&').any(|p| matches!(p, "all=1" | "all=true"));
+ match state.db.flags_of(&t.id, all).await {
+ Ok(flags) => Json(json!({"flags": flags.iter().map(flag_json).collect::<Vec<_>>()})).into_response(),
+ Err(e) => internal(e),
+ }
+}
+
+/// `POST /api/missions/:id/graph/scan` (person-only).
+pub async fn scan(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,
+ };
+ if m.status == "cancelled" {
+ return conflict("the mission is cancelled");
+ }
+ let r = scan_mission(&state, &m).await;
+ Json(json!({"scanned": r.scanned, "flagged": r.flagged, "skipped": r.skipped})).into_response()
+}
+
+/// `GET /api/missions/:id/graph`.
+pub async fn mission_graph(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 = crate::db::spaces::SpaceId::new(&m.space_id);
+ let tasks = match state.db.list_tasks(&space, None, Some(&m.id), None, 1000).await {
+ Ok(t) => t,
+ Err(e) => return internal(e),
+ };
+ let scan = state.db.graph_scan(&m.id).await.ok().flatten();
+ graph_out(&state, Some(&m.id), &tasks, scan).await
+}
+
+/// `GET /api/graph`: the active space's tasks without a mission, open or finished in the last 7 days.
+pub async fn loose_graph(State(state): State<AppState>, Scope(space): Scope) -> Response {
+ let since = chrono::Utc::now() - chrono::Duration::days(7);
+ match state.db.loose_tasks(&space, since).await {
+ Ok(tasks) => graph_out(&state, None, &tasks, None).await,
+ Err(e) => internal(e),
+ }
+}
+
+async fn graph_out(state: &AppState, mission_id: Option<&str>, tasks: &[Task], scan: Option<GraphScan>) -> Response {
+ let ids: Vec<String> = tasks.iter().map(|t| t.id.clone()).collect();
+ let edges = match state.db.edges_among(&ids).await {
+ Ok(e) => e,
+ Err(e) => return internal(e),
+ };
+ let downstream = downstream_counts(&ids, &edges);
+ let mut nodes = Vec::with_capacity(tasks.len());
+ for t in tasks {
+ let checks = state.db.list_checks(&t.id).await.unwrap_or_default();
+ nodes.push(json!({
+ "id": t.id,
+ "title": t.title,
+ "state": t.state,
+ "owner_kwant_id": t.owner_kwant_id,
+ "owner_name": name_of(state, t.owner_kwant_id.as_deref()).await,
+ "attempts": t.attempts,
+ "max_attempts": t.max_attempts,
+ "forked_from": t.forked_from,
+ "downstream": downstream.get(t.id.as_str()).copied().unwrap_or(0),
+ "flags": open_flags(state, t).await,
+ "checks_summary": super::checks_summary(t, &checks),
+ }));
+ }
+ let (scanned_at, skipped) = match scan {
+ Some(s) => (json!(s.scanned_at), serde_json::from_str(&s.skipped).unwrap_or_else(|_| json!([]))),
+ None => (Value::Null, json!([])),
+ };
+ Json(json!({
+ "mission_id": mission_id,
+ "nodes": nodes,
+ "edges": edges.iter().map(|(from, to)| json!({"from": from, "to": to})).collect::<Vec<_>>(),
+ "scanned_at": scanned_at,
+ "scan_skipped": skipped,
+ }))
+ .into_response()
+}
+
+/// For each task, how many tasks depend on it directly or further down (the graph shows "N more
+/// downstream" next to a flag without flagging them, decision D2).
+pub fn downstream_counts<'a>(ids: &'a [String], edges: &[(String, String)]) -> HashMap<&'a str, usize> {
+ let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
+ for (from, to) in edges {
+ children.entry(from.as_str()).or_default().push(to.as_str());
+ }
+ let mut out = HashMap::new();
+ for id in ids {
+ let mut seen: HashSet<&str> = HashSet::new();
+ let mut stack: Vec<&str> = children.get(id.as_str()).cloned().unwrap_or_default();
+ while let Some(n) = stack.pop() {
+ if seen.insert(n) {
+ stack.extend(children.get(n).cloned().unwrap_or_default());
+ }
+ }
+ out.insert(id.as_str(), seen.len());
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn downstream_counts_every_task_below_once() {
+ let ids: Vec<String> = ["a", "b", "c", "d"].iter().map(|s| s.to_string()).collect();
+ let e = |a: &str, b: &str| (a.to_string(), b.to_string());
+ // a → b → c, a → c, d alone
+ let edges = vec![e("a", "b"), e("b", "c"), e("a", "c")];
+ let n = downstream_counts(&ids, &edges);
+ assert_eq!(n["a"], 2);
+ assert_eq!(n["b"], 1);
+ assert_eq!(n["c"], 0);
+ assert_eq!(n["d"], 0);
+ }
+}
diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rs
index 674980a2..395bd26e 100644
--- a/src/server/missions/mod.rs
+++ b/src/server/missions/mod.rs
@@ -13,6 +13,7 @@
//! a bot adds run only after the person approves them, and person actions are person-only routes.
pub mod checks;
+pub mod graph;
pub mod listener;
pub mod routes;
pub mod runner;
@@ -456,8 +457,15 @@ pub(crate) async fn name_of(state: &AppState, id: Option<&str>) -> Option<String
}
}
-/// The open cards (questions, approvals, human steps) the task's owner waits on the person with.
+/// What the task waits on the person for: the owner's open cards (questions, approvals, human
+/// steps) or, in review, check approvals; then, in every state, its open "may be invalid" flags.
pub async fn needs_you(state: &AppState, task: &Task) -> Vec<Value> {
+ let mut items = owner_needs_you(state, task).await;
+ items.extend(graph::flag_items(state, task).await);
+ items
+}
+
+async fn owner_needs_you(state: &AppState, task: &Task) -> Vec<Value> {
if task.state == "review" {
return check_approvals(state, task).await;
}
@@ -512,6 +520,7 @@ pub async fn task_json(state: &AppState, task: &Task) -> Value {
}),
);
obj.insert("needs_you".into(), json!(needs_you(state, task).await));
+ obj.insert("flags".into(), json!(graph::open_flags(state, task).await));
obj.insert("checks_summary".into(), checks_summary(task, &checks));
}
v
@@ -942,6 +951,7 @@ mod tests {
created_at: Utc::now(),
updated_at: Utc::now(),
finished_at: None,
+ forked_from: None,
}
}
diff --git a/src/server/missions/routes.rs b/src/server/missions/routes.rs
index 8577f6f5..37d657c9 100644
--- a/src/server/missions/routes.rs
+++ b/src/server/missions/routes.rs
@@ -18,29 +18,29 @@ use axum::{
use serde::Deserialize;
use serde_json::{json, Value};
-fn err(status: StatusCode, msg: impl Into<String>) -> Response {
+pub(super) fn err(status: StatusCode, msg: impl Into<String>) -> Response {
(status, Json(json!({"error": msg.into()}))).into_response()
}
-fn bad(msg: impl Into<String>) -> Response {
+pub(super) fn bad(msg: impl Into<String>) -> Response {
err(StatusCode::BAD_REQUEST, msg)
}
-fn conflict(msg: impl Into<String>) -> Response {
+pub(super) fn conflict(msg: impl Into<String>) -> Response {
err(StatusCode::CONFLICT, msg)
}
-fn not_found(what: &str) -> Response {
+pub(super) fn not_found(what: &str) -> Response {
err(StatusCode::NOT_FOUND, format!("no such {what}"))
}
-fn internal(e: impl std::fmt::Display) -> Response {
+pub(super) fn internal(e: impl std::fmt::Display) -> Response {
tracing::warn!(error = %e, "mission control");
err(StatusCode::INTERNAL_SERVER_ERROR, "something went wrong")
}
#[allow(clippy::result_large_err)]
-fn moved(r: Result<Task, MoveError>) -> Result<Task, Response> {
+pub(super) fn moved(r: Result<Task, MoveError>) -> Result<Task, Response> {
r.map_err(|e| match e {
MoveError::Missing => not_found("task"),
MoveError::Db(crate::db::DbError::Sqlx(_)) | MoveError::NotAllowed(_) | MoveError::Stale => conflict(e.to_string()),
@@ -50,7 +50,7 @@ fn moved(r: Result<Task, MoveError>) -> Result<Task, Response> {
/// 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> {
+pub(super) async fn load_task(state: &AppState, query: Option<&str>, id: &str) -> Result<Task, Response> {
match state.db.get_task(id).await {
Ok(Some(t)) if space_param(query).is_none_or(|s| s.trim() == t.space_id) => Ok(t),
Ok(_) => Err(not_found("task")),
@@ -59,7 +59,7 @@ async fn load_task(state: &AppState, query: Option<&str>, id: &str) -> Result<Ta
}
#[allow(clippy::result_large_err)]
-async fn load_mission(state: &AppState, query: Option<&str>, id: &str) -> Result<crate::db::missions::Mission, Response> {
+pub(super) async fn load_mission(state: &AppState, query: Option<&str>, id: &str) -> Result<crate::db::missions::Mission, Response> {
match state.db.get_mission(id).await {
Ok(Some(m)) if space_param(query).is_none_or(|s| s.trim() == m.space_id) => Ok(m),
Ok(_) => Err(not_found("mission")),
@@ -312,9 +312,10 @@ pub async fn insights(State(state): State<AppState>, Scope(space): Scope) -> Res
}
}
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() {
+ let flagged: std::collections::HashSet<String> = state.db.flagged_task_ids(&space).await.unwrap_or_default().into_iter().collect();
+ let mut needs_you = 0;
+ for t in &all {
+ if t.state == "needs_you" || flagged.contains(&t.id) || (t.state == "review" && !super::check_approvals(&state, t).await.is_empty()) {
needs_you += 1;
}
}
@@ -716,21 +717,20 @@ pub async fn unblock_task(State(state): State<AppState>, RawQuery(q): RawQuery,
}
}
-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,
- }
+/// `Idempotency-Key` optional (Phase B1 §5): a repeated retry returns the first response.
+pub async fn retry_task(State(state): State<AppState>, RawQuery(q): RawQuery, headers: axum::http::HeaderMap, Path(id): Path<String>) -> Response {
+ let route = format!("POST /api/tasks/{id}/retry");
+ super::graph::idempotent(&state, &headers, route, || async {
+ load_task(&state, q.as_deref(), &id).await?;
+ // A retry gets the same number of attempts again
+ let change = TaskChange { reason: Some("retried by the person".into()), detail: Some(json!({"reset_attempts": true})), ..Default::default() };
+ let t = moved(transition(&state, &id, "failed", "ready", Actor::Person, "person", change).await)?;
+ let _ = state.db.reset_attempts(&id).await;
+ let t = state.db.get_task(&id).await.ok().flatten().unwrap_or(t);
+ emit_task(&state, &t).await;
+ Ok(task_json(&state, &t).await)
+ })
+ .await
}
pub async fn cancel_task(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rs
index 6a4c160f..a0147766 100644
--- a/src/server/missions/runner.rs
+++ b/src/server/missions/runner.rs
@@ -52,6 +52,8 @@ pub async fn tick(state: &AppState) {
super::listener::reconcile(state).await;
super::sweep_leases(state).await;
for m in state.db.active_missions().await.unwrap_or_default() {
+ // Evidence drift, at most every 10 minutes per mission (Phase B1)
+ super::graph::scan_if_due(state, &m).await;
if is_running(&m.id) {
continue;
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 0e3465f2..c2a88445 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -362,6 +362,9 @@ pub fn create_router(state: AppState) -> Router {
.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/missions/:id/graph", get(missions::graph::mission_graph))
+ .route("/api/missions/:id/graph/scan", post(missions::graph::scan))
+ .route("/api/graph", get(missions::graph::loose_graph))
.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))
@@ -370,6 +373,9 @@ pub fn create_router(state: AppState) -> Router {
.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/fork", post(missions::graph::fork_task))
+ .route("/api/tasks/:id/flags", get(missions::graph::task_flags))
+ .route("/api/tasks/:id/flags/:flag_id/resolve", post(missions::graph::resolve_flag))
.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))
diff --git a/tests/mission_graph_test.rs b/tests/mission_graph_test.rs
new file mode 100644
index 00000000..d64415ef
--- /dev/null
+++ b/tests/mission_graph_test.rs
@@ -0,0 +1,556 @@
+//! Mission Control Phase B1: the work graph. Evidence drift and forks of verified work raise
+//! "may be invalid" flags on the task and its started direct dependents, never move a task, and are
+//! resolved only by the person. Fork redoes a task without touching verified history. These are
+//! the contract's 11 acceptance tests (docs/mission-control.md §11), numbered as there.
+
+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, 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
+}
+
+/// 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
+}
+
+
+fn flags(t: &Value) -> Vec<Value> {
+ t["task"]["flags"].as_array().cloned().unwrap_or_default()
+}
+
+fn causes(t: &Value) -> Vec<String> {
+ flags(t).iter().map(|f| f["cause"].as_str().unwrap().to_string()).collect()
+}
+
+/// A mission of `titles` (one bot owns them all), each checked by `file_exists <key>.txt` and
+/// depending on the keys in `deps`; returns the mission id and task ids in `titles` order.
+async fn graph_mission(e: &Env, tasks: &[(&str, &[&str])]) -> (String, Vec<String>) {
+ let plan: Vec<Value> = tasks
+ .iter()
+ .map(|(k, deps)| json!({"key": k, "title": format!("{k} step"), "owner": e.bot.id, "depends_on": deps,
+ "checks": [{"kind": "file_exists", "spec": {"path": format!("{k}.txt")}}]}))
+ .collect();
+ let (m, listed) = mission(e, 900_000, json!(plan)).await;
+ let ids = tasks.iter().map(|(k, _)| listed.iter().find(|t| t["title"] == format!("{k} step")).map(id).unwrap()).collect();
+ (id(&m), ids)
+}
+
+/// The owner does `tid`: writes `<key>.txt`, attaches it as file evidence and hands it in; its
+/// plan check passes, so it is verified.
+async fn do_task(e: &Env, mid: &str, tid: &str, key: &str) {
+ std::fs::write(folder(e, mid).await.join(format!("{key}.txt")), format!("{key} v1")).unwrap();
+ let token = turn(e, &e.bot, &format!("t-{tid}")).await;
+ ok(e, &token, "task_claim", json!({"task_id": tid})).await;
+ ok(e, &token, "task_attach_evidence", json!({"task_id": tid, "kind": "file", "label": key, "path": format!("{key}.txt")})).await;
+ ok(e, &token, "task_update", json!({"task_id": tid, "status": "review"})).await;
+ assert_eq!(state_of(e, tid).await, "verified");
+}
+
+async fn scan(e: &Env, mid: &str) -> Value {
+ person(e, "POST", &format!("/api/missions/{mid}/graph/scan"), None).await
+}
+
+async fn drift(e: &Env, mid: &str, key: &str) {
+ std::fs::write(folder(e, mid).await.join(format!("{key}.txt")), format!("{key} v2, changed")).unwrap();
+}
+
+// 1
+#[tokio::test]
+async fn a_flag_never_changes_a_tasks_state() {
+ let e = setup().await;
+ let (mid, ids) = graph_mission(&e, &[("a", &[])]).await;
+ do_task(&e, &mid, &ids[0], "a").await;
+ let (_, tasks) = mission(&e, 200_000, json!([{"title": "Draft", "owner": e.bot.id}])).await;
+ let r = id(&tasks[0]);
+ let token = turn(&e, &e.bot, "t-review").await;
+ ok(&e, &token, "task_claim", json!({"task_id": r})).await;
+ ok(&e, &token, "task_update", json!({"task_id": r, "status": "review"})).await;
+ assert_eq!(state_of(&e, &r).await, "review");
+
+ for (t, cause) in [(&ids[0], "evidence_changed"), (&r, "upstream_forked")] {
+ let f = e.state.db.raise_flag(t, cause, &ids[0], &json!({"path": "a.txt"})).await.unwrap();
+ assert!(f.is_some());
+ }
+ assert_eq!(state_of(&e, &ids[0]).await, "verified");
+ assert_eq!(state_of(&e, &r).await, "review");
+ // The Phase A triggers still hold
+ let a = &ids[0];
+ assert!(e.state.db.exec_raw_for_test(&format!("UPDATE tasks SET state = 'ready' WHERE id = '{a}'")).await.is_err());
+ assert!(e.state.db.exec_raw_for_test(&format!("UPDATE tasks SET state = 'verified' WHERE id = '{r}'")).await.is_err());
+ let events = e.state.db.task_events(a, 100).await.unwrap();
+ let flagged = events.iter().find(|ev| ev.kind == "flagged").expect("a flagged event");
+ assert_eq!(flagged.actor, "kwant");
+ assert!(flagged.from_state.is_none() && flagged.to_state.is_none());
+}
+
+// 2
+#[tokio::test]
+async fn only_the_person_resolves_a_flag_once_and_flags_are_never_deleted() {
+ let e = setup().await;
+ let (mid, ids) = graph_mission(&e, &[("a", &[])]).await;
+ do_task(&e, &mid, &ids[0], "a").await;
+ let f = e.state.db.raise_flag(&ids[0], "evidence_changed", &ids[0], &json!({})).await.unwrap().unwrap();
+ let fid = &f.id;
+ for by in ["kwant", &e.bot.id, ""] {
+ let sql = format!("UPDATE task_flags SET resolved_at = '2026-10-27T00:00:00Z', resolved_by = '{by}', resolution = 'still_valid' WHERE id = '{fid}'");
+ assert!(e.state.db.exec_raw_for_test(&sql).await.is_err(), "resolved_by {by:?} must be refused");
+ }
+ let sql = format!("UPDATE task_flags SET resolved_at = '2026-10-27T00:00:00Z', resolution = 'still_valid' WHERE id = '{fid}'");
+ assert!(e.state.db.exec_raw_for_test(&sql).await.is_err(), "no resolver is refused");
+ assert!(e.state.db.resolve_flag(fid, "still_valid", None, None).await.unwrap());
+ assert!(!e.state.db.resolve_flag(fid, "redo", None, None).await.unwrap(), "resolved once");
+ let sql = format!("UPDATE task_flags SET resolution = 'redo' WHERE id = '{fid}'");
+ assert!(e.state.db.exec_raw_for_test(&sql).await.is_err(), "a resolved flag can't change");
+ assert!(e.state.db.exec_raw_for_test(&format!("DELETE FROM task_flags WHERE id = '{fid}'")).await.is_err());
+ let events = e.state.db.task_events(&ids[0], 100).await.unwrap();
+ let resolved = events.iter().find(|ev| ev.kind == "flag_resolved").expect("a flag_resolved event");
+ assert_eq!(resolved.actor, "person");
+}
+
+// 3
+#[tokio::test]
+async fn two_scans_of_the_same_drift_give_one_open_flag() {
+ let e = setup().await;
+ let (mid, ids) = graph_mission(&e, &[("a", &[])]).await;
+ do_task(&e, &mid, &ids[0], "a").await;
+ let clean = scan(&e, &mid).await;
+ assert_eq!(clean["scanned"], 1, "{clean}");
+ assert_eq!(clean["flagged"], json!([]));
+ drift(&e, &mid, "a").await;
+ let first = scan(&e, &mid).await;
+ assert_eq!(first["flagged"].as_array().unwrap().len(), 1, "{first}");
+ let second = scan(&e, &mid).await;
+ assert_eq!(second["flagged"], json!([]), "{second}");
+ assert_eq!(e.state.db.flags_of(&ids[0], true).await.unwrap().len(), 1);
+ // Straight at the table too: the unique open index
+ let again = e.state.db.raise_flag(&ids[0], "evidence_changed", &ids[0], &json!({})).await.unwrap();
+ assert!(again.is_none());
+}
+
+// 4
+#[tokio::test]
+async fn drift_flags_the_task_and_its_started_dependent_both_stay_verified() {
+ let e = setup().await;
+ let (mid, ids) = graph_mission(&e, &[("a", &[]), ("b", &["a"])]).await;
+ do_task(&e, &mid, &ids[0], "a").await;
+ do_task(&e, &mid, &ids[1], "b").await;
+ let before = person(&e, "GET", "/api/missions/insights", None).await;
+ assert_eq!(before["needs_you_now"], 0, "{before}");
+
+ drift(&e, &mid, "a").await;
+ let r = scan(&e, &mid).await;
+ assert_eq!(r["flagged"].as_array().unwrap().len(), 2, "{r}");
+ let (a, b) = (task(&e, &ids[0]).await, task(&e, &ids[1]).await);
+ assert_eq!(causes(&a), ["evidence_changed"]);
+ assert_eq!(causes(&b), ["upstream_evidence_changed"]);
+ assert_eq!(a["task"]["state"], "verified");
+ assert_eq!(b["task"]["state"], "verified");
+ let fa = &flags(&a)[0];
+ assert_eq!(fa["detail"]["path"], "a.txt");
+ assert!(fa["detail"]["old_sha256"].is_string() && fa["detail"]["new_sha256"].is_string());
+ assert_ne!(fa["detail"]["old_sha256"], fa["detail"]["new_sha256"]);
+ assert_eq!(flags(&b)[0]["cause_task_id"], ids[0].as_str());
+ assert_eq!(flags(&b)[0]["cause_title"], "a step");
+ for t in [&a, &b] {
+ let items = t["task"]["needs_you"].as_array().unwrap();
+ assert_eq!(items.len(), 1, "{t}");
+ assert_eq!(items[0]["kind"], "may_be_invalid");
+ assert_eq!(items[0]["id"], flags(t)[0]["id"]);
+ assert!(items[0]["text"].as_str().unwrap().starts_with("Check this still holds: "));
+ }
+ let after = person(&e, "GET", "/api/missions/insights", None).await;
+ assert_eq!(after["needs_you_now"], 2, "{after}");
+
+ // A file that is gone is drift too, and a new hash of it is a new drift
+ std::fs::remove_file(folder(&e, &mid).await.join("a.txt")).unwrap();
+ let gone = e.state.db.get_flag(fa["id"].as_str().unwrap()).await.unwrap().unwrap();
+ assert!(gone.resolved_at.is_none());
+ person(&e, "POST", &format!("/api/tasks/{}/flags/{}/resolve", ids[0], fa["id"].as_str().unwrap()), Some(json!({"resolution": "still_valid"}))).await;
+ scan(&e, &mid).await;
+ let a = task(&e, &ids[0]).await;
+ assert_eq!(flags(&a).len(), 1, "{a}");
+ assert!(flags(&a)[0]["detail"]["new_sha256"].is_null());
+ assert!(flags(&a)[0]["detail"]["path"] == "a.txt");
+}
+
+// 5
+#[tokio::test]
+async fn only_direct_dependents_are_flagged() {
+ let e = setup().await;
+ let (mid, ids) = graph_mission(&e, &[("a", &[]), ("b", &["a"]), ("c", &["b"])]).await;
+ for (i, k) in ["a", "b", "c"].iter().enumerate() {
+ do_task(&e, &mid, &ids[i], k).await;
+ }
+ drift(&e, &mid, "a").await;
+ scan(&e, &mid).await;
+ assert_eq!(causes(&task(&e, &ids[0]).await), ["evidence_changed"]);
+ assert_eq!(causes(&task(&e, &ids[1]).await), ["upstream_evidence_changed"]);
+ assert!(causes(&task(&e, &ids[2]).await).is_empty(), "C is two steps down: not flagged");
+ let g = person(&e, "GET", &format!("/api/missions/{mid}/graph"), None).await;
+ let node = |tid: &str| g["nodes"].as_array().unwrap().iter().find(|n| n["id"] == tid).unwrap().clone();
+ assert_eq!(node(&ids[1])["downstream"], 1, "B shows C as one more downstream");
+ assert!(node(&ids[2])["flags"].as_array().unwrap().is_empty());
+}
+
+// 6
+#[tokio::test]
+async fn a_dependent_that_has_not_started_is_not_flagged() {
+ let e = setup().await;
+ let (mid, ids) = graph_mission(&e, &[("a", &[]), ("d", &["a"])]).await;
+ do_task(&e, &mid, &ids[0], "a").await;
+ assert_eq!(state_of(&e, &ids[1]).await, "ready");
+ drift(&e, &mid, "a").await;
+ let r = scan(&e, &mid).await;
+ assert_eq!(r["flagged"].as_array().unwrap().len(), 1, "only A: {r}");
+ assert!(causes(&task(&e, &ids[1]).await).is_empty());
+ assert_eq!(state_of(&e, &ids[1]).await, "ready");
+}
+
+// 7
+#[tokio::test]
+async fn resolving_still_valid_redo_and_cancelled() {
+ let e = setup().await;
+ let (mid, ids) = graph_mission(&e, &[("a", &[]), ("b", &["a"])]).await;
+ do_task(&e, &mid, &ids[0], "a").await;
+ do_task(&e, &mid, &ids[1], "b").await;
+ // B also has a check a teammate added and kwant approved on its own: that approval doesn't carry over
+ e.state.db.add_check(&kwnt::db::missions::NewCheck {
+ task_id: ids[1].clone(), kind: "file_contains".into(), spec: json!({"path": "b.txt", "text": "b"}),
+ required: false, approved: true, requested_by: e.other.id.clone(), approved_by: Some("auto".into()),
+ }).await.unwrap();
+ drift(&e, &mid, "a").await;
+ scan(&e, &mid).await;
+ let fa = id(&flags(&task(&e, &ids[0]).await)[0]);
+ let fb = id(&flags(&task(&e, &ids[1]).await)[0]);
+ let resolve = |t: &str, f: &str| format!("/api/tasks/{t}/flags/{f}/resolve");
+
+ // still_valid: the flag closes, the task is unchanged, and the same drift isn't raised again
+ let before = task(&e, &ids[0]).await;
+ let r = person(&e, "POST", &resolve(&ids[0], &fa), Some(json!({"resolution": "still_valid", "note": "same numbers"}))).await;
+ assert_eq!(r["flag"]["resolution"], "still_valid");
+ assert!(r["flag"]["resolved_at"].is_string());
+ assert!(r["fork"].is_null());
+ let after = task(&e, &ids[0]).await;
+ assert_eq!(after["task"]["state"], before["task"]["state"]);
+ assert_eq!(after["task"]["updated_at"], before["task"]["updated_at"]);
+ assert!(flags(&after).is_empty());
+ scan(&e, &mid).await;
+ assert!(flags(&task(&e, &ids[0]).await).is_empty(), "the person said it still holds");
+ let (status, v) = call(&e.app, "POST", &resolve(&ids[0], &fa), None, Some(json!({"resolution": "redo"}))).await;
+ assert_eq!(status, StatusCode::CONFLICT, "{v}");
+
+ // cancelled on a verified task: refused
+ let (status, v) = call(&e.app, "POST", &resolve(&ids[1], &fb), None, Some(json!({"resolution": "cancelled"}))).await;
+ assert_eq!(status, StatusCode::CONFLICT, "{v}");
+ assert!(v["error"].as_str().unwrap().contains("can't be cancelled"));
+ let (status, _) = call(&e.app, "POST", &resolve(&ids[1], &fb), None, Some(json!({"resolution": "maybe"}))).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ let (status, _) = call(&e.app, "POST", &resolve(&ids[0], &fb), None, Some(json!({"resolution": "redo"}))).await;
+ assert_eq!(status, StatusCode::NOT_FOUND, "a flag of another task");
+
+ // redo on a verified task: a fork, the original untouched
+ let r = person(&e, "POST", &resolve(&ids[1], &fb), Some(json!({"resolution": "redo"}))).await;
+ assert_eq!(r["flag"]["resolution"], "redo");
+ assert_eq!(r["task"]["state"], "verified");
+ let fork = r["fork"].clone();
+ let fid = id(&fork);
+ assert_eq!(fork["forked_from"], ids[1].as_str());
+ assert_eq!(fork["depends_on"], json!([ids[0]]));
+ assert_eq!(fork["suggested_kwant_id"], e.bot.id.as_str());
+ assert_eq!(fork["created_by"], "person");
+ assert_eq!(fork["title"], "b step");
+ assert!(fork["source_id"].is_null());
+ assert_eq!(fork["state"], "ready", "A is verified, so the fork can start");
+ let f = task(&e, &fid).await;
+ let checks = f["checks"].as_array().unwrap();
+ assert_eq!(checks.len(), 2, "{f}");
+ let plan = checks.iter().find(|c| c["kind"] == "file_exists").unwrap();
+ assert_eq!(plan["approved"], true);
+ assert_eq!(plan["approved_by"], "person", "the person wrote this check with the plan");
+ assert_eq!(plan["status"], "pending");
+ assert!(plan["checked_by"].is_null() && plan["output_excerpt"].is_null());
+ let auto = checks.iter().find(|c| c["kind"] == "file_contains").unwrap();
+ assert_eq!(auto["approved"], false);
+ assert!(auto["approved_by"].is_null());
+ assert_eq!(auto["status"], "needs_approval");
+ let original = task(&e, &ids[1]).await;
+ assert_eq!(original["task"]["state"], "verified");
+ assert!(original["checks"].as_array().unwrap().iter().all(|c| c["status"] == "passed" || c["kind"] == "file_contains"));
+ let kinds: Vec<&str> = original["events"].as_array().unwrap().iter().map(|ev| ev["kind"].as_str().unwrap()).collect();
+ assert!(kinds.contains(&"forked") && kinds.contains(&"flag_resolved"), "{kinds:?}");
+ let created = f["events"].as_array().unwrap().iter().find(|ev| ev["kind"] == "created").unwrap().clone();
+ assert_eq!(created["detail"]["forked_from"], ids[1].as_str(), "{created}");
+}
+
+// 8
+#[tokio::test]
+async fn bot_tokens_cannot_resolve_fork_or_scan() {
+ let e = setup().await;
+ let (mid, ids) = graph_mission(&e, &[("a", &[])]).await;
+ do_task(&e, &mid, &ids[0], "a").await;
+ drift(&e, &mid, "a").await;
+ scan(&e, &mid).await;
+ let fid = id(&flags(&task(&e, &ids[0]).await)[0]);
+ let token = turn(&e, &e.bot, "t-403").await;
+ let a = &ids[0];
+ for (uri, body) in [
+ (format!("/api/tasks/{a}/flags/{fid}/resolve"), json!({"resolution": "still_valid"})),
+ (format!("/api/tasks/{a}/fork"), json!({"reason": "redo"})),
+ (format!("/api/missions/{mid}/graph/scan"), json!({})),
+ ] {
+ let (status, _) = call(&e.app, "POST", &uri, Some(&token), Some(body)).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{uri}");
+ }
+ assert_eq!(flags(&task(&e, a).await).len(), 1, "nothing changed");
+ assert!(e.state.db.forks_of(a).await.unwrap().is_empty());
+ let (status, _) = call(&e.app, "GET", &format!("/api/missions/{mid}/graph"), Some(&token), None).await;
+ assert_eq!(status, StatusCode::OK, "reads stay open");
+}
+
+// 9
+#[tokio::test]
+async fn forking_a_verified_task_flags_its_started_dependents_only() {
+ let e = setup().await;
+ let (mid, ids) = graph_mission(&e, &[("a", &[]), ("b", &["a"]), ("d", &["a"])]).await;
+ do_task(&e, &mid, &ids[0], "a").await;
+ do_task(&e, &mid, &ids[1], "b").await;
+ assert_eq!(state_of(&e, &ids[2]).await, "ready");
+ let uri = format!("/api/tasks/{}/fork", ids[0]);
+ let fork = person(&e, "POST", &uri, Some(json!({"reason": "the source data was wrong"}))).await;
+ assert_eq!(fork["forked_from"], ids[0].as_str());
+ assert_eq!(state_of(&e, &ids[0]).await, "verified");
+ let b = task(&e, &ids[1]).await;
+ assert_eq!(causes(&b), ["upstream_forked"]);
+ assert_eq!(flags(&b)[0]["detail"]["fork_id"], fork["id"]);
+ assert_eq!(b["task"]["state"], "verified");
+ assert!(causes(&task(&e, &ids[2]).await).is_empty(), "D is ready, not started");
+ assert_eq!(task(&e, &ids[2]).await["task"]["depends_on"], json!([ids[0]]), "dependents aren't rewired");
+ // A done mission opened again so the fork can run
+ let m = person(&e, "GET", &format!("/api/missions/{mid}"), None).await;
+ assert_eq!(m["mission"]["status"], "active", "{m}");
+ let (status, v) = call(&e.app, "POST", &uri, None, Some(json!({"reason": " "}))).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{v}");
+}
+
+#[tokio::test]
+async fn an_idempotency_key_forks_once_and_belongs_to_one_route() {
+ let e = setup().await;
+ let (mid, ids) = graph_mission(&e, &[("a", &[]), ("b", &[])]).await;
+ do_task(&e, &mid, &ids[0], "a").await;
+ let send = |uri: String, key: &'static str| {
+ let app = e.app.clone();
+ async move {
+ let req = Request::builder().method("POST").uri(uri).header("content-type", "application/json").header("idempotency-key", key)
+ .body(Body::from(json!({"reason": "redo"}).to_string())).unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice::<Value>(&bytes).unwrap_or(Value::Null))
+ }
+ };
+ let uri = format!("/api/tasks/{}/fork", ids[0]);
+ let (s1, first) = send(uri.clone(), "fork-a-1").await;
+ let (s2, second) = send(uri.clone(), "fork-a-1").await;
+ assert!(s1.is_success() && s2.is_success(), "{first} {second}");
+ assert_eq!(first["id"], second["id"]);
+ assert_eq!(e.state.db.forks_of(&ids[0]).await.unwrap().len(), 1, "one fork for one key");
+ let (s3, v) = send(format!("/api/tasks/{}/fork", ids[1]), "fork-a-1").await;
+ assert_eq!(s3, StatusCode::UNPROCESSABLE_ENTITY, "{v}");
+ let (s4, v) = send(format!("/api/tasks/{}/retry", ids[1]), "fork-a-1").await;
+ assert_eq!(s4, StatusCode::UNPROCESSABLE_ENTITY, "{v}");
+ let (s5, _) = send(uri, "fork-a-2").await;
+ assert!(s5.is_success());
+ assert_eq!(e.state.db.forks_of(&ids[0]).await.unwrap().len(), 2, "a new key is a new fork");
+}
+
+// 10
+#[tokio::test]
+async fn a_scan_reads_nothing_outside_the_task_folder() {
+ let e = setup().await;
+ let (mid, ids) = graph_mission(&e, &[("a", &[])]).await;
+ do_task(&e, &mid, &ids[0], "a").await;
+ let outside = folder(&e, &mid).await.parent().unwrap().join("x");
+ std::fs::write(&outside, "secret-ish").unwrap();
+ for path in ["../x", ".env"] {
+ e.state.db.add_evidence(&kwnt::db::missions::NewEvidence {
+ task_id: ids[0].clone(), kind: "file".into(), label: path.into(), path: Some(path.into()),
+ sha256: Some("0".repeat(64)), captured_by: e.bot.id.clone(), ..Default::default()
+ }).await.unwrap();
+ }
+ std::fs::write(folder(&e, &mid).await.join(".env"), "TOKEN=1").unwrap();
+ let r = scan(&e, &mid).await;
+ assert_eq!(r["scanned"], 1, "only a.txt is hashed: {r}");
+ assert_eq!(r["flagged"], json!([]), "a skipped file is never 'changed': {r}");
+ let skipped = r["skipped"].as_array().unwrap();
+ assert_eq!(skipped.len(), 2, "{r}");
+ let why = |p: &str| skipped.iter().find(|s| s["path"] == p).unwrap()["why"].as_str().unwrap().to_string();
+ assert!(why("../x").contains(".."), "{r}");
+ assert!(why(".env").contains("env"), "{r}");
+ let g = person(&e, "GET", &format!("/api/missions/{mid}/graph"), None).await;
+ assert_eq!(g["scan_skipped"].as_array().unwrap().len(), 2, "{g}");
+ assert!(g["scanned_at"].is_string());
+}
+
+// 11
+#[tokio::test]
+async fn the_graph_edges_match_the_dependencies_and_shows_open_flags_only() {
+ let e = setup().await;
+ let (mid, ids) = graph_mission(&e, &[("a", &[]), ("b", &["a"]), ("c", &["a", "b"])]).await;
+ let g = person(&e, "GET", &format!("/api/missions/{mid}/graph"), None).await;
+ assert_eq!(g["mission_id"], mid.as_str());
+ assert!(g["scanned_at"].is_null());
+ assert_eq!(g["nodes"].as_array().unwrap().len(), 3);
+ let mut edges: Vec<(String, String)> = g["edges"].as_array().unwrap().iter()
+ .map(|x| (x["from"].as_str().unwrap().to_string(), x["to"].as_str().unwrap().to_string())).collect();
+ edges.sort();
+ let mut want = vec![(ids[0].clone(), ids[1].clone()), (ids[0].clone(), ids[2].clone()), (ids[1].clone(), ids[2].clone())];
+ want.sort();
+ assert_eq!(edges, want);
+ let node = g["nodes"].as_array().unwrap().iter().find(|n| n["id"] == ids[0].as_str()).unwrap().clone();
+ for k in ["title", "state", "owner_kwant_id", "owner_name", "attempts", "max_attempts", "forked_from", "flags", "checks_summary", "downstream"] {
+ assert!(node.get(k).is_some(), "node lacks {k}: {node}");
+ }
+ assert_eq!(node["downstream"], 2);
+
+ do_task(&e, &mid, &ids[0], "a").await;
+ drift(&e, &mid, "a").await;
+ scan(&e, &mid).await;
+ let fid = id(&flags(&task(&e, &ids[0]).await)[0]);
+ let flags_of = |g: &Value| g["nodes"].as_array().unwrap().iter().find(|n| n["id"] == ids[0].as_str()).unwrap()["flags"].as_array().unwrap().len();
+ let g = person(&e, "GET", &format!("/api/missions/{mid}/graph"), None).await;
+ assert_eq!(flags_of(&g), 1);
+ person(&e, "POST", &format!("/api/tasks/{}/flags/{fid}/resolve", ids[0]), Some(json!({"resolution": "still_valid"}))).await;
+ let g = person(&e, "GET", &format!("/api/missions/{mid}/graph"), None).await;
+ assert_eq!(flags_of(&g), 0, "resolved flags leave the graph");
+ let open = person(&e, "GET", &format!("/api/tasks/{}/flags", ids[0]), None).await;
+ assert!(open["flags"].as_array().unwrap().is_empty());
+ let all = person(&e, "GET", &format!("/api/tasks/{}/flags?all=1", ids[0]), None).await;
+ assert_eq!(all["flags"].as_array().unwrap().len(), 1);
+ assert_eq!(all["flags"][0]["resolution"], "still_valid");
+
+ // Tasks outside a mission have a graph too
+ let loose = person(&e, "POST", "/api/tasks", Some(json!({"title": "Loose end"}))).await;
+ let lg = person(&e, "GET", "/api/graph", None).await;
+ assert!(lg["mission_id"].is_null());
+ let lid = loose["id"].as_str().or(loose["task"]["id"].as_str()).unwrap();
+ assert!(lg["nodes"].as_array().unwrap().iter().any(|n| n["id"] == lid), "{lg}");
+ assert!(lg["nodes"].as_array().unwrap().iter().all(|n| n["id"] != ids[0].as_str()), "mission tasks stay in their mission's graph");
+}