Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Mission Control B2: checkpoints, restore, tool-call ledger
Lin (kwant bot)51eceb8c9597
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 23a56a82..edcd642f 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: checkpoints and restore (backend).** kwant snapshots a task's folder before and+ after each run, and on demand. You can preview and restore a checkpoint: only the files that task's+ runs changed are written back, after a safety checkpoint you can restore in turn. What the bot did+ outside the folder (commands, web, messages) is listed as not undone. Every tool call of a task's+ turns is now recorded with its effect. Snapshots stay private on the server. The board UI follows+ separately.- **Mission Control: work graph and "may be invalid" flags (backend).** When a verified task's evidencefile changes or disappears, or a verified task is redone, kwant flags that task and the started tasksthat directly depend on it as "may be invalid". Their state never changes, and only you decide:diff --git a/docs/mission-control.md b/docs/mission-control.mdindex 538a9a9c..6f803419 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -395,3 +395,50 @@ The header works on `POST /api/tasks/:id/fork` and `POST /api/tasks/:id/retry`.- `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`.++## 12. Checkpoints and restore (Phase B2)++Design and decisions: `/home/maus/shared/ship-software-safely/mission-control/phase-b/contract.md` §3+and `decisions.md` (D4, D6, D8, D9). A checkpoint is a snapshot of a task's folder (the mission's+`workspace_path`, else the owner bot's workspace). A restore writes back only the paths this task's+own runs changed. What a tool did outside the folder (Bash, web, email, other bots) is never undone:+it is listed as "not undone".++### When a checkpoint is taken++- `before_run` when a task is claimed (runner, `task_claim`, a team-lead hand-off), and `after_run` when the claim ends (the task leaves `working`/`needs_you`).+- `manual`: `POST /api/tasks/:id/checkpoints` (person only).+- `before_restore`: always, right before a restore writes anything. If it can't be taken, nothing is restored (500, `code: checkpoint_failed`).+- The setting `checkpoints` (default on) turns off only `before_run`/`after_run`. Manual and safety checkpoints are always taken.+- A failed snapshot (for example an unreadable folder) never stops the turn. It is stored as a checkpoint with `error` set and `restorable: false`, plus a `checkpoint_failed` task event.++### The store++- Under `<data_dir>/checkpoints/` (folder mode 0700, files 0600): `blobs/<sha256>` is deduplicated content, `<task_id>/<checkpoint_id>.json` is each manifest, and `<task_id>/runs.jsonl` holds the paths each run changed.+- Snapshots include `.env`, keys and other secrets, which is why no route ever returns a manifest path, a blob path or file contents.+- Never snapshotted (counted in `skipped`; the manifest keeps each path and why): symlinks (never followed), `.git`, `node_modules`, `target`, `.venv`, files over 20 MB, and anything past 20,000 files. Past the per-checkpoint cap, the largest files are skipped first.+- Caps (settings): `checkpoint_max_mb` (10–2000, default 200) per checkpoint; `checkpoint_keep` (1–20, default 5) per task, plus the task's first `before_run`, which is always kept. All checkpoints together are kept under 2 GB, oldest first. Pruning writes a `checkpoint_pruned` event. Blobs no manifest uses are removed after every checkpoint.++### Tables++- `task_checkpoints`: `id`, `task_id`, `mission_id`, `kind` (`before_run`, `after_run`, `manual`, `before_restore`), `claim_id`, `turn_id`, `attempt`, `created_at`, `created_by`, `files`, `bytes`, `skipped` (a count; the paths and reasons stay in the manifest), `git_head`, `error`. Server-only columns `manifest_path`, `manifest_sha256`, `folder` are never serialized. Rows are never updated; pruning deletes them.+- `turn_tool_calls` (the ledger; append-only, no UPDATE or DELETE): `turn_id`, `kwant_id`, `task_id`, `tool_name`, `effect` (`none`, `workspace`, `external`), `summary`, `decision`, `approval_id`, `created_at`.+ - Only task turns are logged (D9): a call is logged when the bot holds a task in that turn.+ - Every call that reaches kwant's permission check is logged, including the ones allowed without a card and the ones refused.+ - `none`: read-only tools (Read, Glob, Grep, LS, WebSearch, TodoWrite…) and the `task_*`/`mission_plan` self tools. `workspace`: Write, Edit, MultiEdit, NotebookEdit inside the task folder. Everything else is `external`, Bash always (D6).+ - `summary` is at most 300 characters, never a file body or message text, with credentials masked.++### Routes++- `GET /api/tasks/:id/checkpoints`: oldest first. Each item: `{id, kind, attempt, created_at, created_by, files, bytes, skipped, git_head, error, restorable, effects_after: {workspace: n, external: [{tool_name, summary, at}]}}`. `effects_after` covers the calls between this checkpoint and the next.+- `POST /api/tasks/:id/checkpoints` (person only): a manual checkpoint; 201 with the item, 500 if the snapshot failed.+- `GET /api/tasks/:id/checkpoints/:cid/restore-preview`: `{checkpoint_id, preview_sha256, changes: [{path, action: overwrite|create|delete}], conflicts: [{path, changed_by_task}], skipped: [{path, why}], external_not_undone: [{tool_name, summary, at}], not_undone_note, effects_known, task_state_after, refused: null|fork_instead|running}`.+ - Only paths this task's runs changed are restored. A path another task's run changed after the checkpoint is a conflict, left alone unless forced.+ - `effects_known` is false when a run after the checkpoint changed files but no tool call that could have was logged.+ - 409 `not_restorable` when the snapshot failed or was pruned.+- `POST /api/tasks/:id/checkpoints/:cid/restore` (person only, `Idempotency-Key` required): body `{preview_sha256, force_paths?: [path]}`. Returns `{restored, deleted, failed: [{path, why}], before_restore_checkpoint_id, external_not_undone, not_undone_note, effects_known, task}`.+ - 409 `fork_instead` for a verified task, `running` while a claim is live, `stale_preview` when the folder or task changed since the preview.+ - The task moves review/failed → ready and blocked → backlog; other states stay. A `restored` task event records the counts.+ - Never writes through a symlink or outside the folder.+- `POST /api/tasks/:id/fork` accepts `from_checkpoint`: the original's task-owned paths are restored to that checkpoint first (after a `before_restore`), then the fork is made. The response adds `restore`.+- `task_json` gains `checkpoint_count` and `last_checkpoint_at`.diff --git a/frontend/src/missions.ts b/frontend/src/missions.tsindex cba1b2bc..3d395656 100644--- a/frontend/src/missions.ts+++ b/frontend/src/missions.ts@@ -102,6 +102,80 @@ export interface Task {forked_from?: string | null;/** Open "may be invalid" flags; older servers leave it out. */flags?: TaskFlag[];+ /** Time Machine checkpoints of this task; older servers leave these out. */+ checkpoint_count?: number;+ last_checkpoint_at?: string | null;+}++// Time Machine (Phase B2, docs/mission-control.md §12)++export type CheckpointKind = 'before_run' | 'after_run' | 'manual' | 'before_restore';++/** A tool call the task's runs made that kwant can't undo. */+export interface ExternalCall {+ tool_name: string;+ /** Tool name plus a redacted outline of the arguments (≤ 300 chars, never a body). */+ summary: string;+ at: string;+}++/** `GET /api/tasks/:id/checkpoints` item (oldest first); `POST` (person-only) returns one. */+export interface Checkpoint {+ id: string;+ kind: CheckpointKind;+ attempt: number;+ created_at: string;+ created_by: 'kwant' | 'person';+ files: number;+ bytes: number;+ skipped: number;+ git_head: string | null;+ /** Why the snapshot failed; such a checkpoint isn't restorable. */+ error: string | null;+ restorable: boolean;+ /** Tool calls of this task between this checkpoint and the next one. */+ effects_after: { workspace: number; external: ExternalCall[] };+}++export type RestoreAction = 'overwrite' | 'create' | 'delete';+export type RestoreRefusal = 'fork_instead' | 'running';++/** `GET /api/tasks/:id/checkpoints/:cid/restore-preview`. Only paths this task's runs changed are listed. */+export interface RestorePreview {+ checkpoint_id: string;+ /** Send back as `preview_sha256`; a changed folder or task makes the restore 409 `stale_preview`. */+ preview_sha256: string;+ changes: { path: string; action: RestoreAction }[];+ /** Changed by another task since the checkpoint: skipped unless named in `force_paths`. */+ conflicts: { path: string; changed_by_task: string }[];+ skipped: { path: string; why: string }[];+ external_not_undone: ExternalCall[];+ /** Always "kwant can't undo these. Check them yourself." */+ not_undone_note: string;+ /** False when a run changed files but logged no call that could have: show "side effects unknown", never "none". */+ effects_known: boolean;+ task_state_after: 'ready' | 'backlog' | null;+ refused: RestoreRefusal | null;+}++/** `POST /api/tasks/:id/checkpoints/:cid/restore` (person-only; `Idempotency-Key` header required). */+export interface RestoreResult {+ restored: string[];+ deleted: string[];+ /** Paths that couldn't be written (e.g. a symlink appeared). */+ failed: { path: string; why: string }[];+ /** Restore this one to undo the restore. */+ before_restore_checkpoint_id: string;+ external_not_undone: ExternalCall[];+ not_undone_note: string;+ effects_known: boolean;+ task: Task;+}++/** 409 bodies carry `code`: `fork_instead`, `running`, `stale_preview` or `not_restorable`. */+export interface RestoreError {+ error: string;+ code?: RestoreRefusal | 'stale_preview' | 'not_restorable' | 'checkpoint_failed';}// Work graph (Phase B1, docs/mission-control.md §11)diff --git a/src/db/checkpoints.rs b/src/db/checkpoints.rsnew file mode 100644index 00000000..2ea8968b--- /dev/null+++ b/src/db/checkpoints.rs@@ -0,0 +1,312 @@+//! Mission Control Phase B2: the Time Machine's bookkeeping. Checkpoints of a task's folder+//! (before and after each run, manual ones, and one before every restore) and the per-turn log+//! of every permission decision with its side-effect class. The files themselves live under+//! `<data_dir>/checkpoints/` (see [`crate::server::missions::checkpoints`]); no path stored here+//! ever reaches the API. Contract: docs/mission-control.md §12.++use super::missions::{insert_event, Claim};+use super::{Database, DbError};+use chrono::{DateTime, Utc};+use serde::Serialize;+use serde_json::Value;+use sqlx::FromRow;+use uuid::Uuid;++pub const CHECKPOINT_KINDS: [&str; 4] = ["before_run", "after_run", "manual", "before_restore"];+pub const EFFECTS: [&str; 3] = ["none", "workspace", "external"];+pub const DECISIONS: [&str; 4] = ["allowed", "auto_allowed", "approved", "denied"];++#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct Checkpoint {+ pub id: String,+ pub task_id: String,+ pub mission_id: Option<String>,+ pub kind: String,+ pub claim_id: Option<String>,+ pub turn_id: Option<String>,+ pub attempt: i64,+ /// Server-only.+ #[serde(skip)]+ pub manifest_path: String,+ #[serde(skip)]+ pub manifest_sha256: String,+ /// Server-only: the folder it was taken of.+ #[serde(skip)]+ pub folder: String,+ pub files: i64,+ pub bytes: i64,+ pub skipped: i64,+ pub git_head: Option<String>,+ /// Why the snapshot failed; such a checkpoint can't be restored.+ pub error: Option<String>,+ pub created_by: String,+ pub created_at: DateTime<Utc>,+}++impl Checkpoint {+ pub fn failed(&self) -> bool {+ self.error.is_some()+ }+}++pub struct NewCheckpoint<'a> {+ pub id: String,+ pub task_id: &'a str,+ pub mission_id: Option<&'a str>,+ pub kind: &'a str,+ pub claim_id: Option<&'a str>,+ pub turn_id: Option<&'a str>,+ pub attempt: i64,+ pub manifest_path: String,+ pub manifest_sha256: String,+ pub folder: String,+ pub files: i64,+ pub bytes: i64,+ pub skipped: i64,+ pub git_head: Option<String>,+ pub error: Option<String>,+ pub created_by: &'a str,+}++#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct ToolCall {+ pub id: i64,+ pub turn_id: String,+ pub kwant_id: String,+ pub task_id: Option<String>,+ pub tool_name: String,+ pub effect: String,+ pub summary: String,+ pub decision: String,+ pub approval_id: Option<String>,+ pub idempotency_key: Option<String>,+ pub created_at: DateTime<Utc>,+}++const TRIGGERS: [&str; 3] = [+ // A checkpoint is never edited; retention deletes it (logging `checkpoint_pruned`)+ "CREATE TRIGGER IF NOT EXISTS task_checkpoints_no_update BEFORE UPDATE ON task_checkpoints \+ BEGIN SELECT RAISE(ABORT, 'checkpoints are append-only'); END",+ // The side-effect ledger is history+ "CREATE TRIGGER IF NOT EXISTS turn_tool_calls_no_update BEFORE UPDATE ON turn_tool_calls \+ BEGIN SELECT RAISE(ABORT, 'the tool-call log is append-only'); END",+ "CREATE TRIGGER IF NOT EXISTS turn_tool_calls_no_delete BEFORE DELETE ON turn_tool_calls \+ BEGIN SELECT RAISE(ABORT, 'the tool-call log is append-only'); END",+];++impl Database {+ pub(super) async fn migrate_checkpoints(&self) -> Result<(), DbError> {+ for stmt in [+ "CREATE TABLE IF NOT EXISTS task_checkpoints (+ id TEXT PRIMARY KEY,+ task_id TEXT NOT NULL REFERENCES tasks(id),+ mission_id TEXT,+ kind TEXT NOT NULL CHECK (kind IN ('before_run', 'after_run', 'manual', 'before_restore')),+ claim_id TEXT,+ turn_id TEXT,+ attempt INTEGER NOT NULL,+ manifest_path TEXT NOT NULL,+ manifest_sha256 TEXT NOT NULL,+ folder TEXT NOT NULL DEFAULT '',+ files INTEGER NOT NULL,+ bytes INTEGER NOT NULL,+ skipped INTEGER NOT NULL DEFAULT 0,+ git_head TEXT,+ error TEXT,+ created_by TEXT NOT NULL,+ created_at TIMESTAMP NOT NULL+ )",+ "CREATE INDEX IF NOT EXISTS task_checkpoints_task ON task_checkpoints (task_id, created_at)",+ "CREATE TABLE IF NOT EXISTS turn_tool_calls (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ turn_id TEXT NOT NULL,+ kwant_id TEXT NOT NULL,+ task_id TEXT,+ tool_name TEXT NOT NULL,+ effect TEXT NOT NULL CHECK (effect IN ('none', 'workspace', 'external')),+ summary TEXT NOT NULL,+ decision TEXT NOT NULL CHECK (decision IN ('allowed', 'auto_allowed', 'approved', 'denied')),+ approval_id TEXT,+ idempotency_key TEXT,+ created_at TIMESTAMP NOT NULL+ )",+ "CREATE INDEX IF NOT EXISTS turn_tool_calls_task ON turn_tool_calls (task_id, id)",+ ] {+ sqlx::query(stmt).execute(&self.pool).await?;+ }+ for t in TRIGGERS {+ sqlx::query(t).execute(&self.pool).await?;+ }+ Ok(())+ }++ // Checkpoints++ /// Stores a checkpoint and its task event (`checkpoint`, or `checkpoint_failed` when the+ /// snapshot failed) in one transaction.+ pub async fn insert_checkpoint(&self, c: &NewCheckpoint<'_>) -> Result<Checkpoint, DbError> {+ let mut tx = self.pool.begin().await?;+ let row = sqlx::query_as::<_, Checkpoint>(+ "INSERT INTO task_checkpoints (id, task_id, mission_id, kind, claim_id, turn_id, attempt, manifest_path, manifest_sha256, folder, \+ files, bytes, skipped, git_head, error, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *",+ )+ .bind(&c.id)+ .bind(c.task_id)+ .bind(c.mission_id)+ .bind(c.kind)+ .bind(c.claim_id)+ .bind(c.turn_id)+ .bind(c.attempt)+ .bind(&c.manifest_path)+ .bind(&c.manifest_sha256)+ .bind(&c.folder)+ .bind(c.files)+ .bind(c.bytes)+ .bind(c.skipped)+ .bind(&c.git_head)+ .bind(&c.error)+ .bind(c.created_by)+ .bind(Utc::now())+ .fetch_one(&mut *tx)+ .await?;+ let (kind, detail) = match &c.error {+ Some(e) => ("checkpoint_failed", serde_json::json!({"checkpoint_id": row.id, "kind": row.kind, "error": e})),+ None => (+ "checkpoint",+ serde_json::json!({"checkpoint_id": row.id, "kind": row.kind, "files": row.files, "bytes": row.bytes, "skipped": row.skipped}),+ ),+ };+ insert_event(&mut tx, c.task_id, c.mission_id, kind, c.created_by, None, None, &detail).await?;+ tx.commit().await?;+ Ok(row)+ }++ pub async fn get_checkpoint(&self, id: &str) -> Result<Option<Checkpoint>, DbError> {+ Ok(sqlx::query_as::<_, Checkpoint>("SELECT * FROM task_checkpoints WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)+ }++ /// The task's checkpoints, oldest first.+ pub async fn checkpoints_of(&self, task_id: &str) -> Result<Vec<Checkpoint>, DbError> {+ Ok(sqlx::query_as::<_, Checkpoint>("SELECT * FROM task_checkpoints WHERE task_id = ? ORDER BY created_at, rowid")+ .bind(task_id)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Run checkpoints (`before_run` / `after_run`) of other tasks, oldest first.+ pub async fn run_checkpoints_except(&self, task_id: &str) -> Result<Vec<Checkpoint>, DbError> {+ Ok(sqlx::query_as::<_, Checkpoint>(+ "SELECT * FROM task_checkpoints WHERE task_id != ? AND kind IN ('before_run', 'after_run') AND error IS NULL ORDER BY created_at, rowid",+ )+ .bind(task_id)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Every checkpoint, oldest first (for the total cap and blob GC).+ pub async fn all_checkpoints(&self) -> Result<Vec<Checkpoint>, DbError> {+ Ok(sqlx::query_as::<_, Checkpoint>("SELECT * FROM task_checkpoints ORDER BY created_at, rowid").fetch_all(&self.pool).await?)+ }++ /// `(count, newest created_at)` of the task's checkpoints.+ pub async fn checkpoint_stats(&self, task_id: &str) -> Result<(i64, Option<DateTime<Utc>>), DbError> {+ Ok(sqlx::query_as("SELECT COUNT(*), MAX(created_at) FROM task_checkpoints WHERE task_id = ?").bind(task_id).fetch_one(&self.pool).await?)+ }++ /// Deletes a checkpoint row (retention), logging `checkpoint_pruned` on its task.+ pub async fn prune_checkpoint(&self, c: &Checkpoint, why: &str) -> Result<(), DbError> {+ let mut tx = self.pool.begin().await?;+ let r = sqlx::query("DELETE FROM task_checkpoints WHERE id = ?").bind(&c.id).execute(&mut *tx).await?;+ if r.rows_affected() == 1 {+ let detail = serde_json::json!({"checkpoint_id": c.id, "kind": c.kind, "why": why});+ insert_event(&mut tx, &c.task_id, c.mission_id.as_deref(), "checkpoint_pruned", "kwant", None, None, &detail).await?;+ }+ tx.commit().await?;+ Ok(())+ }++ /// The task's most recently released claim (the run that just ended).+ pub async fn last_released_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 NOT NULL ORDER BY released_at DESC, claimed_at DESC LIMIT 1",+ )+ .bind(task_id)+ .fetch_optional(&self.pool)+ .await?)+ }++ // The tool-call log++ /// The task a turn's tool call belongs to: the claim taken in this turn, else the bot's own+ /// open claim, else one kwant holds for it. `None`: not a task turn, nothing is logged (D9).+ pub async fn task_of_turn(&self, kwant_id: &str, turn_id: &str) -> Result<Option<String>, DbError> {+ let row: Option<(String,)> = sqlx::query_as(+ "SELECT task_id FROM agent_claims WHERE kwant_id = ?1 AND (released_at IS NULL OR turn_id = ?2) \+ ORDER BY turn_id IS NOT ?2, released_at IS NOT NULL, system, claimed_at DESC LIMIT 1",+ )+ .bind(kwant_id)+ .bind(turn_id)+ .fetch_optional(&self.pool)+ .await?;+ Ok(row.map(|r| r.0))+ }++ #[allow(clippy::too_many_arguments)]+ pub async fn log_tool_call(+ &self,+ turn_id: &str,+ kwant_id: &str,+ task_id: &str,+ tool_name: &str,+ effect: &str,+ summary: &str,+ decision: &str,+ approval_id: Option<&str>,+ ) -> Result<(), DbError> {+ sqlx::query(+ "INSERT INTO turn_tool_calls (turn_id, kwant_id, task_id, tool_name, effect, summary, decision, approval_id, created_at) \+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",+ )+ .bind(turn_id)+ .bind(kwant_id)+ .bind(task_id)+ .bind(tool_name)+ .bind(effect)+ .bind(summary)+ .bind(decision)+ .bind(approval_id)+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// The task's logged tool calls, oldest first.+ pub async fn tool_calls_of(&self, task_id: &str) -> Result<Vec<ToolCall>, DbError> {+ Ok(sqlx::query_as::<_, ToolCall>("SELECT * FROM turn_tool_calls WHERE task_id = ? ORDER BY id").bind(task_id).fetch_all(&self.pool).await?)+ }++ /// A task event outside a state change (`restored`).+ pub async fn task_event(&self, task_id: &str, mission_id: Option<&str>, kind: &str, actor: &str, detail: &Value) -> Result<(), DbError> {+ let mut tx = self.pool.begin().await?;+ insert_event(&mut tx, task_id, mission_id, kind, actor, None, None, detail).await?;+ tx.commit().await?;+ Ok(())+ }++ /// Checkpoint test hook: the detail JSON of the task's events of `kind`.+ #[doc(hidden)]+ pub async fn event_details(&self, task_id: &str, kind: &str) -> Result<Vec<Value>, DbError> {+ let rows: Vec<(String,)> = sqlx::query_as("SELECT detail FROM task_events WHERE task_id = ? AND kind = ? ORDER BY rowid")+ .bind(task_id)+ .bind(kind)+ .fetch_all(&self.pool)+ .await?;+ Ok(rows.into_iter().map(|r| serde_json::from_str(&r.0).unwrap_or(Value::Null)).collect())+ }+}++/// A fresh checkpoint id.+pub fn new_id() -> String {+ Uuid::new_v4().to_string()+}diff --git a/src/db/mod.rs b/src/db/mod.rsindex 82374876..45888234 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -26,6 +26,7 @@ pub mod api_context;pub mod usage;pub mod missions;pub mod mission_graph;+pub mod checkpoints;/// What a space's #general says about itself.pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";@@ -160,6 +161,7 @@ impl Database {db.migrate_usage().await?;db.migrate_missions().await?;db.migrate_mission_graph().await?;+ db.migrate_checkpoints().await?;if spaces {let migration = db.migrate_spaces(data_dir, fresh).await?;db.require_spaces_schema(&migration).await?;diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsindex c4f1e3e6..47a605d2 100644--- a/src/mcp/mod.rs+++ b/src/mcp/mod.rs@@ -311,6 +311,11 @@ pub trait ToolApprover: Send + Sync {ApprovalOutcome::Denied}}++ /// Records a decision in the task's side-effect ledger (`turn_tool_calls`): `allowed`,+ /// `auto_allowed`, `approved` or `denied`. Called for the calls the permission hook lets+ /// through on its own too. Default: nothing is recorded.+ async fn note(&self, _request: &ToolApprovalRequest, _decision: &'static str, _approval_id: Option<&str>) {}}/// What became of a call that may have needed a card.diff --git a/src/server/auth.rs b/src/server/auth.rsindex 6bb2adea..2e616a5a 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -848,6 +848,10 @@ mod tests {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/checkpoints"));+ assert!(person_only(&post, "/api/tasks/t1/checkpoints/c1/restore"));+ assert!(!person_only(&get, "/api/tasks/t1/checkpoints"));+ assert!(!person_only(&get, "/api/tasks/t1/checkpoints/c1/restore-preview"));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"));diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex dd9d3b92..e6d5388c 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -342,10 +342,15 @@ impl ToolApprover for SelfToolsApprover {async fn decide(&self, req: ToolApprovalRequest) -> crate::mcp::ApprovalOutcome {if req.server == SELF_SERVER_NAME && (!self.always_ask || READ_ONLY_SELF_TOOLS.contains(&req.tool.as_str())) {+ self.inner.note(&req, "allowed", None).await;return crate::mcp::ApprovalOutcome::Allowed;}self.inner.decide(req).await}++ async fn note(&self, req: &ToolApprovalRequest, decision: &'static str, approval_id: Option<&str>) {+ self.inner.note(req, decision, approval_id).await+ }}fn tool_list(scope: &SelfScope, board: bool) -> Value {diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex bfb536a3..59f32aea 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -129,6 +129,8 @@ pub struct BrokerApprover {/// turns kwnt starts on its own that nobody asked for (the loose-ends owner). A call the/// person allowed on a card (late Allow) still runs once.pub always_ask: bool,+ /// Where task folders resolve, for the side-effect ledger (`turn_tool_calls`).+ pub data_dir: PathBuf,}/// Withdraws the ticket if the waiting turn is cancelled (its future dropped) mid-wait.@@ -161,6 +163,20 @@ impl ToolApprover for BrokerApprover {}async fn decide(&self, req: ToolApprovalRequest) -> ApprovalOutcome {+ let noted = req.clone();+ let (outcome, decision, ticket) = self.classified(req).await;+ self.note(¬ed, decision, ticket.as_deref()).await;+ outcome+ }++ async fn note(&self, req: &ToolApprovalRequest, decision: &'static str, approval_id: Option<&str>) {+ super::missions::checkpoints::log_call(&self.db, &self.data_dir, req, decision, approval_id).await;+ }+}++impl BrokerApprover {+ /// [`ToolApprover::decide`], with the ledger's decision class and the card's id.+ async fn classified(&self, req: ToolApprovalRequest) -> (ApprovalOutcome, &'static str, Option<String>) {// Approvals the person switched off: run, and keep a record of what ran. A setting that// can't be read asks, as before.let mode = self.db.kwant_approvals(&req.kwant_id).await.ok();@@ -209,28 +225,28 @@ impl ToolApprover for BrokerApprover {if let Err(e) = self.db.save_refused(&record).await {tracing::warn!(error = %e, "could not record a refused call");}- return ApprovalOutcome::Denied;+ return (ApprovalOutcome::Denied, "denied", None);}if let Some(mcp::SmartVerdict::Allow(why)) = &smart {tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, reason = %why, "ran without a card: not risky");if let Err(e) = self.db.save_auto_allowed(&record).await {tracing::warn!(error = %e, "could not record a call that ran without a card");}- return ApprovalOutcome::Allowed;+ return (ApprovalOutcome::Allowed, "auto_allowed", None);}if !off && !self.always_ask && self.broker.is_allowed_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await {- return ApprovalOutcome::Allowed;+ return (ApprovalOutcome::Allowed, "allowed", None);}if off {if let Err(e) = self.db.save_auto_allowed(&record).await {tracing::warn!(error = %e, "could not record a call that ran with approvals off");}- return ApprovalOutcome::Allowed;+ return (ApprovalOutcome::Allowed, "auto_allowed", None);}// The person allowed this exact call on a card its earlier turn stopped waiting forif self.broker.take_grant(&req.kwant_id, &self.conversation, &req.tool_name, &req.arguments).await {tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, "ran a call the person allowed after its turn ended");- return ApprovalOutcome::Allowed;+ return (ApprovalOutcome::Allowed, "approved", None);}let ticket = match self.db@@ -240,7 +256,7 @@ impl ToolApprover for BrokerApprover {Ok(a) => a.id,Err(e) => {tracing::warn!(error = %e, "could not store MCP approval ticket; denying");- return ApprovalOutcome::Denied;+ return (ApprovalOutcome::Denied, "denied", None);}};let rx = self@@ -274,7 +290,7 @@ impl ToolApprover for BrokerApprover {Err(_) => "stopped",};super::activity::approval_settled(&req.turn_id, &ticket, settled);- match decision {+ let outcome = match decision {Ok(Ok(ApprovalDecision::AllowOnce)) => ApprovalOutcome::Allowed,Ok(Ok(ApprovalDecision::AlwaysAllowSession)) => {self.broker.allow_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await;@@ -285,19 +301,21 @@ impl ToolApprover for BrokerApprover {// (see `resume_late_approval`)Err(_) => {if !self.broker.cancel(&ticket).await {- return ApprovalOutcome::Denied;+ return (ApprovalOutcome::Denied, "denied", Some(ticket));}let chat = self.chat.clone().unwrap_or_else(|| json!({"direct_kwant_id": req.kwant_id}));match self.db.park_approval(&ticket, &chat).await {Ok(true) => ApprovalOutcome::Unanswered,_ => {let _ = self.db.update_approval_status(&ticket, "expired").await;- let _ = self.events.send(RuntimeEvent::ApprovalWithdrawn { id: ticket });+ let _ = self.events.send(RuntimeEvent::ApprovalWithdrawn { id: ticket.clone() });ApprovalOutcome::Denied}}}- }+ };+ let class = if outcome.allowed() { "approved" } else { "denied" };+ (outcome, class, Some(ticket))}}@@ -485,6 +503,7 @@ pub async fn prepare_turn_with_opts(conversation: turn_conversation(state, &turn_id),chat,always_ask: opts.always_ask,+ data_dir: state.config.data_dir.clone(),});let ctx = McpTurnContext {servers,@@ -524,6 +543,21 @@ fn rpc_error(id: Value, code: i64, message: &str) -> Response {Json(json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})).into_response()}+/// A request for the side-effect ledger only (the call never reaches the approver).+fn noted_request(session: &PermissionSession, tool_name: &str, server: &str, tool: &str, input: &Value, builtin: Option<mcp::BuiltinCall>) -> ToolApprovalRequest {+ ToolApprovalRequest {+ kwant_id: session.kwant_id.clone(),+ kwant_name: session.kwant_name.clone(),+ turn_id: session.turn_id.clone(),+ tool_name: tool_name.to_string(),+ server: server.to_string(),+ tool: tool.to_string(),+ arguments: input.clone(),+ builtin,+ smart: None,+ }+}+/// Answers one claude permission prompt. MCP tools from the kwant's own servers get their/// approval card; claude's own tools follow [`mcp::builtin_tools`]; tools from servers the/// kwant doesn't have are denied.@@ -550,6 +584,10 @@ async fn decide(session: &PermissionSession, args: &Value, smart: bool) -> Value(server, tool, None)}_ if tool_name.is_empty() || tool_name.starts_with("mcp__") => {+ if !tool_name.is_empty() {+ let req = noted_request(session, tool_name, "", tool_name, &input, None);+ session.ctx.approver.note(&req, "denied", None).await;+ }return json!({"behavior": "deny", "message": format!("{tool_name} is not available to this bot.")});}_ => {@@ -568,6 +606,10 @@ async fn decide(session: &PermissionSession, args: &Value, smart: bool) -> Value};match decision {mcp::builtin_tools::BuiltinDecision::Allow => {+ // No card and no approval record, but the task's ledger still gets it+ let cwd = folder.or_else(|| session.cwd.clone()).map(|f| f.display().to_string());+ let req = noted_request(session, tool_name, "", tool_name, &input, Some(mcp::BuiltinCall { cwd, outside_folder: false }));+ session.ctx.approver.note(&req, "allowed", None).await;return json!({"behavior": "allow", "updatedInput": input});}mcp::builtin_tools::BuiltinDecision::Ask { outside_folder } => {diff --git a/src/server/missions/checkpoints.rs b/src/server/missions/checkpoints.rsnew file mode 100644index 00000000..04ab07a5--- /dev/null+++ b/src/server/missions/checkpoints.rs@@ -0,0 +1,1110 @@+//! Mission Control Phase B2: the Time Machine. Checkpoints of a task's folder, restore of the+//! paths the task's own runs changed, and the side-effect ledger it reports as "not undone".+//!+//! The store is `<data_dir>/checkpoints/` (0700): `blobs/<sha256>` (deduplicated across+//! checkpoints) and `<task_id>/<checkpoint_id>.json` manifests, plus `<task_id>/runs.jsonl`,+//! the paths each run of the task changed (the task-owned paths). Nothing under it, no path+//! and no file content ever reaches the API. Contract: docs/mission-control.md §12.++use super::routes::{bad, internal, load_task, not_found};+use super::{emit_task, int_setting, task_folder, task_json, transition, Actor};+use crate::db::checkpoints::{new_id, Checkpoint, NewCheckpoint, ToolCall};+use crate::db::missions::{Claim, Task, TaskChange};+use crate::server::AppState;+use axum::{+ extract::{Path, RawQuery, State},+ http::{HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ Json,+};+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::collections::{BTreeMap, BTreeSet};+use std::io::{Read, Write};+use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};+use std::path::{Component, Path as FsPath, PathBuf};++pub const SETTING: &str = "checkpoints";+pub const MAX_MB_SETTING: &str = "checkpoint_max_mb";+pub const KEEP_SETTING: &str = "checkpoint_keep";+pub const DEFAULT_MAX_MB: i64 = 200;+pub const MAX_MB_RANGE: (i64, i64) = (10, 2000);+pub const DEFAULT_KEEP: i64 = 5;+pub const KEEP_RANGE: (i64, i64) = (1, 20);+/// A bigger file is never snapshotted.+pub const FILE_MAX_BYTES: u64 = 20 * 1024 * 1024;+/// All checkpoints together; past it the oldest unprotected ones are pruned.+pub const TOTAL_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;+/// Files per checkpoint.+pub const MAX_FILES: usize = 20_000;+/// Folders never snapshotted (and never restored).+pub const SKIP_DIRS: [&str; 4] = [".git", "node_modules", "target", ".venv"];+/// What restore says about external side effects, always.+pub const NOT_UNDONE: &str = "kwant can't undo these. Check them yourself.";++/// One snapshot, prune or restore at a time: blob GC never races a snapshot writing blobs.+static STORE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());++pub async fn enabled(state: &AppState) -> bool {+ !matches!(state.db.get_setting(SETTING).await.ok().flatten().as_deref().map(str::trim), Some("false" | "0" | "off"))+}++pub async fn max_mb(state: &AppState) -> i64 {+ int_setting(state, MAX_MB_SETTING, MAX_MB_RANGE, DEFAULT_MAX_MB).await+}++pub async fn keep(state: &AppState) -> i64 {+ int_setting(state, KEEP_SETTING, KEEP_RANGE, DEFAULT_KEEP).await+}++pub fn settings_error(max_mb: Option<i64>, keep: Option<i64>) -> Option<String> {+ if let Some(n) = max_mb.filter(|n| !(MAX_MB_RANGE.0..=MAX_MB_RANGE.1).contains(n)) {+ return Some(format!("checkpoint_max_mb must be {}–{} (got {n})", MAX_MB_RANGE.0, MAX_MB_RANGE.1));+ }+ if let Some(n) = keep.filter(|n| !(KEEP_RANGE.0..=KEEP_RANGE.1).contains(n)) {+ return Some(format!("checkpoint_keep must be {}–{} (got {n})", KEEP_RANGE.0, KEEP_RANGE.1));+ }+ None+}++fn root(state: &AppState) -> PathBuf {+ state.config.data_dir.join("checkpoints")+}++// The store (blocking; callers hold STORE and run these in spawn_blocking)++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct Manifest {+ pub files: Vec<Entry>,+ #[serde(default)]+ pub skipped: Vec<Skip>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Entry {+ pub path: String,+ pub sha256: String,+ pub bytes: u64,+ pub mode: u32,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Skip {+ pub path: String,+ pub why: String,+}++/// One run of a task: the paths that differ between its `before_run` and `after_run`.+#[derive(Debug, Clone, Serialize, Deserialize)]+struct Run {+ claim_id: Option<String>,+ after_run_id: String,+ at: chrono::DateTime<chrono::Utc>,+ folder: String,+ paths: Vec<String>,+}++fn private_dir(dir: &FsPath) -> std::io::Result<()> {+ std::fs::create_dir_all(dir)?;+ std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))+}++fn hex(bytes: &[u8]) -> String {+ super::checks::hex(bytes)+}++/// `rel` is a plain relative path: no `..`, not absolute, no empty or `.` parts.+pub fn safe_rel(rel: &str) -> bool {+ !rel.is_empty()+ && !rel.contains('\0')+ && !rel.ends_with('/')+ && FsPath::new(rel).components().all(|c| matches!(c, Component::Normal(_)))+}++/// Whether `folder/rel` or any folder on the way is a symlink (never followed by restore).+fn through_symlink(folder: &FsPath, rel: &str) -> bool {+ let mut p = folder.to_path_buf();+ for c in FsPath::new(rel).components() {+ p.push(c);+ match std::fs::symlink_metadata(&p) {+ Ok(m) if m.file_type().is_symlink() => return true,+ Ok(_) => {}+ Err(_) => return false,+ }+ }+ false+}++/// What the folder holds at `rel` now: `Ok(Some(sha))`, `Ok(None)` when absent, `Err(why)`.+fn current(folder: &FsPath, rel: &str) -> Result<Option<String>, String> {+ if through_symlink(folder, rel) {+ return Err("symlink, not followed".into());+ }+ let p = folder.join(rel);+ let meta = match std::fs::symlink_metadata(&p) {+ Ok(m) => m,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(_) => return Err("can't be read".into()),+ };+ if !meta.is_file() {+ return Err("not a regular file".into());+ }+ let mut f = std::fs::File::open(&p).map_err(|_| "can't be read".to_string())?;+ let mut h = <sha2::Sha256 as sha2::Digest>::new();+ std::io::copy(&mut f, &mut h).map_err(|_| "can't be read".to_string())?;+ Ok(Some(hex(&sha2::Digest::finalize(h))))+}++/// Streams `src` into the blob store, returning its sha256.+fn store_blob(blobs: &FsPath, src: &FsPath) -> std::io::Result<String> {+ let mut input = std::fs::File::open(src)?;+ let tmp = blobs.join(format!(".tmp-{}", new_id()));+ let mut out = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&tmp)?;+ let mut h = <sha2::Sha256 as sha2::Digest>::new();+ let mut buf = vec![0u8; 64 * 1024];+ let res = (|| -> std::io::Result<()> {+ loop {+ let n = input.read(&mut buf)?;+ if n == 0 {+ break;+ }+ sha2::Digest::update(&mut h, &buf[..n]);+ out.write_all(&buf[..n])?;+ }+ out.flush()+ })();+ drop(out);+ if let Err(e) = res {+ let _ = std::fs::remove_file(&tmp);+ return Err(e);+ }+ let sha = hex(&sha2::Digest::finalize(h));+ let dest = blobs.join(&sha);+ if dest.exists() {+ let _ = std::fs::remove_file(&tmp);+ } else {+ std::fs::rename(&tmp, &dest)?;+ }+ Ok(sha)+}++/// The commit the folder's git checkout is on, if it is one (read-only info).+fn git_head(folder: &FsPath) -> Option<String> {+ let git = folder.join(".git");+ let head = std::fs::read_to_string(git.join("HEAD")).ok()?;+ let head = head.trim();+ let Some(r) = head.strip_prefix("ref: ") else {+ return Some(head.chars().take(64).collect());+ };+ if let Ok(s) = std::fs::read_to_string(git.join(r)) {+ return Some(s.trim().chars().take(64).collect());+ }+ let packed = std::fs::read_to_string(git.join("packed-refs")).ok()?;+ packed.lines().find_map(|l| l.strip_suffix(r).map(|sha| sha.trim().chars().take(64).collect()))+}++struct Taken {+ manifest: Manifest,+ bytes: u64,+ git_head: Option<String>,+}++/// Walks `folder` (never following symlinks) and stores each file's content as a blob.+/// A missing folder is an empty snapshot; an unreadable one is an error.+fn snapshot(blobs: &FsPath, folder: &FsPath, max_bytes: u64) -> Result<Taken, String> {+ private_dir(blobs).map_err(|e| format!("the checkpoint store can't be written: {e}"))?;+ let mut m = Manifest::default();+ match std::fs::symlink_metadata(folder) {+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Taken { manifest: m, bytes: 0, git_head: None }),+ Err(e) => return Err(format!("the folder can't be read: {e}")),+ Ok(meta) if !meta.is_dir() => return Err("the task's folder isn't a folder".into()),+ Ok(_) => {}+ }+ let mut candidates: Vec<(String, PathBuf, u64, u32)> = Vec::new();+ let mut stack: Vec<(PathBuf, String)> = vec![(folder.to_path_buf(), String::new())];+ let mut first = true;+ while let Some((dir, prefix)) = stack.pop() {+ let entries = match std::fs::read_dir(&dir) {+ Ok(e) => e,+ Err(e) if first => return Err(format!("the folder can't be read: {e}")),+ Err(_) => {+ m.skipped.push(Skip { path: prefix.to_string(), why: "folder can't be read".into() });+ continue;+ }+ };+ first = false;+ for entry in entries.flatten() {+ let name = entry.file_name().to_string_lossy().into_owned();+ let rel = format!("{prefix}{name}");+ let Ok(meta) = std::fs::symlink_metadata(entry.path()) else {+ m.skipped.push(Skip { path: rel, why: "can't be read".into() });+ continue;+ };+ let ft = meta.file_type();+ if ft.is_symlink() {+ m.skipped.push(Skip { path: rel, why: "symlink, not followed".into() });+ } else if ft.is_dir() {+ if SKIP_DIRS.contains(&name.as_str()) {+ m.skipped.push(Skip { path: format!("{rel}/"), why: "not snapshotted".into() });+ } else {+ stack.push((entry.path(), format!("{rel}/")));+ }+ } else if !ft.is_file() {+ m.skipped.push(Skip { path: rel, why: "not a regular file".into() });+ } else if meta.len() > FILE_MAX_BYTES {+ m.skipped.push(Skip { path: rel, why: "over 20 MB".into() });+ } else {+ candidates.push((rel, entry.path(), meta.len(), meta.permissions().mode() & 0o777));+ }+ }+ }+ candidates.sort_by(|a, b| a.0.cmp(&b.0));+ if candidates.len() > MAX_FILES {+ for c in candidates.drain(MAX_FILES..) {+ m.skipped.push(Skip { path: c.0, why: format!("over the {MAX_FILES}-file limit") });+ }+ }+ // Past the cap, the largest files go first+ let mut total: u64 = candidates.iter().map(|c| c.2).sum();+ if total > max_bytes {+ let mut by_size: Vec<usize> = (0..candidates.len()).collect();+ by_size.sort_by(|a, b| candidates[*b].2.cmp(&candidates[*a].2));+ let mut drop = BTreeSet::new();+ for i in by_size {+ if total <= max_bytes {+ break;+ }+ total -= candidates[i].2;+ drop.insert(i);+ }+ let mb = max_bytes / (1024 * 1024);+ let mut kept = Vec::new();+ for (i, c) in candidates.into_iter().enumerate() {+ if drop.contains(&i) {+ m.skipped.push(Skip { path: c.0, why: format!("over the {mb} MB checkpoint cap") });+ } else {+ kept.push(c);+ }+ }+ candidates = kept;+ }+ let mut bytes = 0;+ for (rel, abs, len, mode) in candidates {+ match store_blob(blobs, &abs) {+ Ok(sha) => {+ bytes += len;+ m.files.push(Entry { path: rel, sha256: sha, bytes: len, mode });+ }+ Err(_) => m.skipped.push(Skip { path: rel, why: "can't be read".into() }),+ }+ }+ m.skipped.sort_by(|a, b| a.path.cmp(&b.path));+ Ok(Taken { manifest: m, bytes, git_head: git_head(folder) })+}++fn write_manifest(dir: &FsPath, id: &str, m: &Manifest) -> std::io::Result<(PathBuf, String)> {+ private_dir(dir)?;+ let body = serde_json::to_vec(m).map_err(std::io::Error::other)?;+ let path = dir.join(format!("{id}.json"));+ let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&path)?;+ f.write_all(&body)?;+ Ok((path, hex(&<sha2::Sha256 as sha2::Digest>::digest(&body))))+}++/// The manifest of `c`, if it is still on disk.+pub fn read_manifest(c: &Checkpoint) -> Option<Manifest> {+ if c.failed() || c.manifest_path.is_empty() {+ return None;+ }+ serde_json::from_slice(&std::fs::read(&c.manifest_path).ok()?).ok()+}++/// A path's state in a manifest: its sha, `Skipped`, or absent.+#[derive(Debug, Clone, PartialEq)]+enum At {+ File(String),+ Skipped(String),+ Absent,+}++fn index(m: &Manifest) -> BTreeMap<String, At> {+ let mut out = BTreeMap::new();+ for s in &m.skipped {+ if !s.path.ends_with('/') {+ out.insert(s.path.clone(), At::Skipped(s.why.clone()));+ }+ }+ for f in &m.files {+ out.insert(f.path.clone(), At::File(f.sha256.clone()));+ }+ out+}++/// The paths that differ between two snapshots of the same folder.+fn changed(before: &Manifest, after: &Manifest) -> Vec<String> {+ let (b, a) = (index(before), index(after));+ let keys: BTreeSet<&String> = b.keys().chain(a.keys()).collect();+ keys.into_iter()+ .filter(|k| {+ let (x, y) = (b.get(*k).cloned().unwrap_or(At::Absent), a.get(*k).cloned().unwrap_or(At::Absent));+ x != y && !matches!((&x, &y), (At::Skipped(_), At::Skipped(_)))+ })+ .cloned()+ .collect()+}++fn read_runs(dir: &FsPath) -> Vec<Run> {+ std::fs::read_to_string(dir.join("runs.jsonl"))+ .unwrap_or_default()+ .lines()+ .filter_map(|l| serde_json::from_str(l).ok())+ .collect()+}++fn append_run(dir: &FsPath, run: &Run) -> std::io::Result<()> {+ private_dir(dir)?;+ let mut f = std::fs::OpenOptions::new().append(true).create(true).mode(0o600).open(dir.join("runs.jsonl"))?;+ writeln!(f, "{}", serde_json::to_string(run).map_err(std::io::Error::other)?)+}++// Taking checkpoints++/// Takes a checkpoint of `task`'s folder. Best-effort: a failure is stored as a checkpoint with+/// its `error` (not restorable) and a `checkpoint_failed` event, and never stops the run.+/// Run checkpoints (`before_run`, `after_run`) follow the `checkpoints` setting; manual and+/// `before_restore` ones are always taken.+pub async fn take(state: &AppState, task: &Task, kind: &str, claim: Option<&Claim>, created_by: &str) -> Option<Checkpoint> {+ if matches!(kind, "before_run" | "after_run") && !enabled(state).await {+ return None;+ }+ let folder = task_folder(state, task).await;+ let max_bytes = max_mb(state).await as u64 * 1024 * 1024;+ let root = root(state);+ let task_dir = root.join(&task.id);+ let id = new_id();+ let held = STORE.lock().await;+ let result = match folder.clone() {+ None => Err("the task has no folder".to_string()),+ Some(folder) => {+ let (root, task_dir, id) = (root.clone(), task_dir.clone(), id.clone());+ tokio::task::spawn_blocking(move || -> Result<(Taken, PathBuf, String), String> {+ private_dir(&root).map_err(|e| format!("the checkpoint store can't be written: {e}"))?;+ let taken = snapshot(&root.join("blobs"), &folder, max_bytes)?;+ let (path, sha) = write_manifest(&task_dir, &id, &taken.manifest).map_err(|e| format!("the manifest can't be written: {e}"))?;+ Ok((taken, path, sha))+ })+ .await+ .unwrap_or_else(|e| Err(format!("the snapshot stopped: {e}")))+ }+ };+ let folder_s = folder.as_ref().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();+ let new = |manifest_path: String, manifest_sha256: String, files: i64, bytes: i64, skipped: i64, git_head: Option<String>, error: Option<String>| NewCheckpoint {+ id: id.clone(),+ task_id: &task.id,+ mission_id: task.mission_id.as_deref(),+ kind,+ claim_id: claim.map(|c| c.id.as_str()),+ turn_id: claim.and_then(|c| c.turn_id.as_deref()),+ attempt: task.attempts,+ manifest_path,+ manifest_sha256,+ folder: folder_s.clone(),+ files,+ bytes,+ skipped,+ git_head,+ error,+ created_by,+ };+ let (row, manifest) = match result {+ Ok((t, path, sha)) => {+ let n = new(+ path.to_string_lossy().into_owned(),+ sha,+ t.manifest.files.len() as i64,+ t.bytes as i64,+ t.manifest.skipped.len() as i64,+ t.git_head.clone(),+ None,+ );+ (state.db.insert_checkpoint(&n).await, Some(t.manifest))+ }+ Err(why) => {+ tracing::warn!(task_id = %task.id, %kind, %why, "checkpoint failed");+ (state.db.insert_checkpoint(&new(String::new(), String::new(), 0, 0, 0, None, Some(why))).await, None)+ }+ };+ let row = match row {+ Ok(r) => r,+ Err(e) => {+ tracing::warn!(error = %e, "could not store a checkpoint");+ return None;+ }+ };+ if kind == "after_run" {+ if let Some(after) = &manifest {+ note_run(state, task, &row, after).await;+ }+ }+ retain(state, &task.id).await;+ gc(state).await;+ drop(held);+ emit_task_id(state, &task.id).await;+ Some(row)+}++async fn emit_task_id(state: &AppState, id: &str) {+ if let Ok(Some(t)) = state.db.get_task(id).await {+ emit_task(state, &t).await;+ }+}++/// Records the paths this run changed: its `after_run` against the `before_run` of the same claim.+async fn note_run(state: &AppState, task: &Task, after: &Checkpoint, after_m: &Manifest) {+ let all = state.db.checkpoints_of(&task.id).await.unwrap_or_default();+ let before = all+ .iter()+ .rev()+ .find(|c| c.kind == "before_run" && c.claim_id.is_some() && c.claim_id == after.claim_id && !c.failed())+ .and_then(|c| read_manifest(c).map(|m| (c.folder.clone(), m)));+ let paths = match before {+ Some((folder, m)) if folder == after.folder => changed(&m, after_m),+ // No usable before_run (it failed, or checkpoints were off): every file is the task's+ _ => {+ tracing::info!(task_id = %task.id, "after_run without its before_run: every file counts as changed");+ after_m.files.iter().map(|f| f.path.clone()).collect()+ }+ };+ let run = Run { claim_id: after.claim_id.clone(), after_run_id: after.id.clone(), at: after.created_at, folder: after.folder.clone(), paths };+ let dir = root(state).join(&task.id);+ if let Err(e) = tokio::task::spawn_blocking(move || append_run(&dir, &run)).await.unwrap_or_else(|e| Err(std::io::Error::other(e))) {+ tracing::warn!(error = %e, "could not record a run's paths");+ }+}++/// Keeps the last `checkpoint_keep` of the task plus its first `before_run`. Caller holds STORE.+async fn retain(state: &AppState, task_id: &str) {+ let keep = keep(state).await as usize;+ let all = state.db.checkpoints_of(task_id).await.unwrap_or_default();+ if all.len() <= keep {+ return;+ }+ let first = all.iter().find(|c| c.kind == "before_run").map(|c| c.id.clone());+ let cut = all.len() - keep;+ for c in all.iter().take(cut).filter(|c| Some(&c.id) != first.as_ref()) {+ prune(state, c, "past checkpoint_keep").await;+ }+}++async fn prune(state: &AppState, c: &Checkpoint, why: &str) {+ if !c.manifest_path.is_empty() {+ let _ = std::fs::remove_file(&c.manifest_path);+ }+ if let Err(e) = state.db.prune_checkpoint(c, why).await {+ tracing::warn!(error = %e, "could not prune a checkpoint");+ }+}++/// Deletes blobs no manifest refers to, then prunes the oldest checkpoints (sparing each task's+/// first `before_run`) while the store is over 2 GB. Caller holds STORE.+async fn gc(state: &AppState) {+ let blobs = root(state).join("blobs");+ loop {+ let all = state.db.all_checkpoints().await.unwrap_or_default();+ let manifests: Vec<String> = all.iter().filter(|c| !c.manifest_path.is_empty()).map(|c| c.manifest_path.clone()).collect();+ let dir = blobs.clone();+ let total = tokio::task::spawn_blocking(move || sweep_blobs(&dir, &manifests)).await.unwrap_or(0);+ if total <= TOTAL_MAX_BYTES {+ return;+ }+ let mut firsts = BTreeSet::new();+ for c in &all {+ if c.kind == "before_run" && !firsts.iter().any(|(t, _): &(String, String)| *t == c.task_id) {+ firsts.insert((c.task_id.clone(), c.id.clone()));+ }+ }+ let Some(oldest) = all.iter().find(|c| !firsts.iter().any(|(_, id)| *id == c.id)) else { return };+ prune(state, oldest, "over the 2 GB total").await;+ }+}++/// Removes unreferenced blobs and leftover temp files; returns the bytes still stored.+fn sweep_blobs(blobs: &FsPath, manifests: &[String]) -> u64 {+ let mut used = BTreeSet::new();+ for p in manifests {+ if let Some(m) = std::fs::read(p).ok().and_then(|b| serde_json::from_slice::<Manifest>(&b).ok()) {+ used.extend(m.files.into_iter().map(|f| f.sha256));+ }+ }+ let mut total = 0;+ for e in std::fs::read_dir(blobs).into_iter().flatten().flatten() {+ let name = e.file_name().to_string_lossy().into_owned();+ if !used.contains(&name) {+ let _ = std::fs::remove_file(e.path());+ } else {+ total += e.metadata().map(|m| m.len()).unwrap_or(0);+ }+ }+ total+}++/// `before_run`, right after a successful claim and before the turn starts.+pub async fn before_run(state: &AppState, task: &Task) {+ let claim = state.db.open_claim(&task.id).await.ok().flatten();+ take(state, task, "before_run", claim.as_ref(), "kwant").await;+}++/// `after_run`, once a run's claim was released (from `transition`, after the commit).+pub async fn after_run(state: &AppState, task: &Task) {+ let claim = state.db.last_released_claim(&task.id).await.ok().flatten();+ take(state, task, "after_run", claim.as_ref(), "kwant").await;+}++// The side-effect ledger++/// Claude's tools that only read or plan.+const NO_EFFECT_TOOLS: [&str; 11] =+ ["Read", "Glob", "Grep", "LS", "WebSearch", "TodoWrite", "TodoRead", "NotebookRead", "ToolSearch", "BashOutput", "ExitPlanMode"];+/// Claude's tools that write one file.+const FILE_TOOLS: [&str; 4] = ["Write", "Edit", "MultiEdit", "NotebookEdit"];++/// The side-effect class of a call (contract §3.4): unproven is `external`, and `Bash` always is.+pub fn effect(req: &crate::mcp::ToolApprovalRequest, task_folder: Option<&FsPath>) -> &'static str {+ if req.server == crate::mcp::SELF_SERVER_NAME {+ return if req.tool.starts_with("task_") || req.tool == "mission_plan" { "none" } else { "external" };+ }+ if !req.server.is_empty() || req.tool_name.starts_with("mcp__") {+ return "external";+ }+ let tool = req.tool_name.as_str();+ if NO_EFFECT_TOOLS.contains(&tool) {+ return "none";+ }+ if FILE_TOOLS.contains(&tool) {+ let path = ["file_path", "notebook_path", "path"].iter().find_map(|k| req.arguments[*k].as_str()).unwrap_or("");+ let Some(folder) = task_folder.and_then(|f| crate::mcp::builtin_tools::canonical_folder(Some(f))) else { return "external" };+ if path.is_empty() {+ return "external";+ }+ // A relative path is the bot's working folder's+ let p = FsPath::new(path);+ let abs = match (p.is_absolute(), req.builtin.as_ref().and_then(|b| b.cwd.as_deref())) {+ (true, _) => p.to_path_buf(),+ (false, Some(cwd)) => FsPath::new(cwd).join(p),+ (false, None) => return "external",+ };+ return if crate::mcp::builtin_tools::is_inside(&folder, &abs.to_string_lossy()) { "workspace" } else { "external" };+ }+ "external"+}++/// Keys whose values are bodies, never shown: only their length.+const BODY_KEYS: [&str; 8] = ["content", "new_string", "old_string", "edits", "new_source", "body", "text", "html"];++/// The tool name and a redacted outline of its arguments, at most 300 characters.+pub fn summary(tool_name: &str, args: &Value) -> String {+ let mut parts = Vec::new();+ if let Some(obj) = args.as_object() {+ for (k, v) in obj.iter().take(8) {+ let shown = match v {+ Value::String(s) if BODY_KEYS.contains(&k.as_str()) => format!("<{} chars>", s.chars().count()),+ Value::String(s) => {+ let short: String = s.chars().take(80).collect();+ if s.chars().count() > 80 {+ format!("{short}…")+ } else {+ short+ }+ }+ Value::Array(a) => format!("[{} items]", a.len()),+ Value::Object(_) => "{…}".into(),+ other => other.to_string(),+ };+ parts.push(format!("{k}={shown}"));+ }+ }+ let raw = if parts.is_empty() { tool_name.to_string() } else { format!("{tool_name} {}", parts.join(", ")) };+ let (scrubbed, _) = crate::import::scrub::scrub_text(&crate::profiles::classify::mask_credentials(&raw));+ let mut out: String = scrubbed.chars().take(300).collect();+ if scrubbed.chars().count() > 300 {+ out.pop();+ out.push('…');+ }+ out+}++/// Records one permission decision of a task turn (D9: a turn without a task records nothing).+pub async fn log_call(db: &crate::db::Database, data_dir: &FsPath, req: &crate::mcp::ToolApprovalRequest, decision: &'static str, approval_id: Option<&str>) {+ let Ok(Some(task_id)) = db.task_of_turn(&req.kwant_id, &req.turn_id).await else { return };+ let folder = match db.get_task(&task_id).await {+ Ok(Some(t)) => super::task_folder_in(db, data_dir, &t).await,+ _ => None,+ };+ let effect = effect(req, folder.as_deref());+ let summary = summary(&req.tool_name, &req.arguments);+ if let Err(e) = db.log_tool_call(&req.turn_id, &req.kwant_id, &task_id, &req.tool_name, effect, &summary, decision, approval_id).await {+ tracing::warn!(error = %e, "could not log a tool call");+ }+}++// Restore planning++#[derive(Debug, Clone, Serialize)]+pub struct Change {+ pub path: String,+ pub action: &'static str,+}++/// What restoring `c` would do. `conflicts` are left out of `changes`; `forced` holds what each+/// would do if `force_paths` names it.+#[derive(Debug, Clone)]+pub struct Plan {+ pub changes: Vec<Change>,+ pub conflicts: Vec<Value>,+ forced: BTreeMap<String, &'static str>,+ pub skipped: Vec<Value>,+ pub external: Vec<Value>,+ pub effects_known: bool,+ pub refused: Option<&'static str>,+ pub state_after: Option<&'static str>,+ pub sha: String,+ folder: PathBuf,+ entries: BTreeMap<String, Entry>,+}++#[derive(Debug)]+pub enum PlanError {+ NotRestorable,+ Db(String),+}++fn tool_json(t: &ToolCall) -> Value {+ json!({"tool_name": t.tool_name, "summary": t.summary, "at": t.created_at})+}++/// Whether a run's claim is still live.+async fn running(state: &AppState, task: &Task) -> bool {+ matches!(task.state.as_str(), "working" | "needs_you")+ && matches!(state.db.open_claim(&task.id).await, Ok(Some(c)) if c.expires_at > crate::db::missions::now_ms())+}++pub async fn plan(state: &AppState, task: &Task, c: &Checkpoint) -> Result<Plan, PlanError> {+ let Some(manifest) = read_manifest(c) else { return Err(PlanError::NotRestorable) };+ let folder = PathBuf::from(&c.folder);+ let task_dir = root(state).join(&task.id);+ let blobs = root(state).join("blobs");+ // Every path this task's runs changed, and what other tasks' runs changed after `c`+ let mut owned = BTreeSet::new();+ for r in read_runs(&task_dir) {+ if r.folder == c.folder {+ owned.extend(r.paths);+ }+ }+ let mut others: BTreeMap<String, String> = BTreeMap::new();+ let mut seen = BTreeSet::new();+ for o in state.db.run_checkpoints_except(&task.id).await.map_err(|e| PlanError::Db(e.to_string()))? {+ if seen.insert(o.task_id.clone()) {+ for r in read_runs(&root(state).join(&o.task_id)) {+ if r.folder == c.folder && r.at > c.created_at {+ for p in r.paths {+ others.entry(p).or_insert_with(|| o.task_id.clone());+ }+ }+ }+ }+ }+ let mut skipped = Vec::new();+ let mut entries = BTreeMap::new();+ for e in &manifest.files {+ if !safe_rel(&e.path) {+ skipped.push(json!({"path": e.path, "why": "unsafe path"}));+ } else if owned.contains(&e.path) {+ entries.insert(e.path.clone(), e.clone());+ }+ }+ let skipped_in: BTreeMap<&str, &str> = manifest.skipped.iter().map(|s| (s.path.as_str(), s.why.as_str())).collect();+ let mut changes = Vec::new();+ let mut conflicts = Vec::new();+ let mut forced = BTreeMap::new();+ let mut hashes = Vec::new();+ let check = {+ let (folder, owned, entries, blobs) = (folder.clone(), owned.clone(), entries.clone(), blobs.clone());+ let skipped_in: BTreeMap<String, String> = skipped_in.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();+ tokio::task::spawn_blocking(move || {+ owned+ .into_iter()+ .map(|p| {+ if !safe_rel(&p) {+ return (p, Err("unsafe path".to_string()));+ }+ if let Some(why) = skipped_in.get(&p) {+ return (p, Err(format!("{why}, not in the checkpoint")));+ }+ let now = match current(&folder, &p) {+ Ok(now) => now,+ Err(why) => return (p, Err(why)),+ };+ let action: Result<Option<&'static str>, String> = match (entries.get(&p), &now) {+ (Some(e), Some(sha)) if *sha == e.sha256 => Ok(None),+ (Some(e), _) if !blobs.join(&e.sha256).is_file() => Err("the stored copy is missing".into()),+ (Some(_), Some(_)) => Ok(Some("overwrite")),+ (Some(_), None) => Ok(Some("create")),+ (None, Some(_)) => Ok(Some("delete")),+ (None, None) => Ok(None),+ };+ let sha = now.unwrap_or_default();+ (p, action.map(|a| (a, sha)))+ })+ .collect::<Vec<_>>()+ })+ .await+ .map_err(|e| PlanError::Db(e.to_string()))?+ };+ for (p, r) in check {+ match r {+ Err(why) => skipped.push(json!({"path": p, "why": why})),+ Ok((None, sha)) => hashes.push((p, sha)),+ Ok((Some(action), sha)) => {+ hashes.push((p.clone(), sha));+ if let Some(t) = others.get(&p) {+ conflicts.push(json!({"path": p, "changed_by_task": t}));+ forced.insert(p, action);+ } else {+ changes.push(Change { path: p, action });+ }+ }+ }+ }+ let calls = state.db.tool_calls_of(&task.id).await.map_err(|e| PlanError::Db(e.to_string()))?;+ let after: Vec<&ToolCall> = calls.iter().filter(|t| t.created_at >= c.created_at).collect();+ let external: Vec<Value> = after.iter().filter(|t| t.effect == "external").map(|t| tool_json(t)).collect();+ // A run after `c` changed files but logged no call that could have: the log is incomplete+ let runs_after = read_runs(&task_dir).into_iter().any(|r| r.at > c.created_at && !r.paths.is_empty());+ let effects_known = !runs_after || after.iter().any(|t| t.effect != "none");+ let refused = if task.state == "verified" {+ Some("fork_instead")+ } else if running(state, task).await {+ Some("running")+ } else {+ None+ };+ let state_after = match task.state.as_str() {+ "review" | "failed" => Some("ready"),+ "blocked" => Some("backlog"),+ _ => None,+ };+ let fingerprint = json!({"checkpoint": c.id, "task_state": task.state, "paths": hashes, "skipped": skipped, "conflicts": conflicts});+ let sha = hex(&<sha2::Sha256 as sha2::Digest>::digest(fingerprint.to_string().as_bytes()));+ Ok(Plan { changes, conflicts, forced, skipped, external, effects_known, refused, state_after, sha, folder, entries })+}++fn plan_json(c: &Checkpoint, p: &Plan) -> Value {+ json!({+ "checkpoint_id": c.id,+ "preview_sha256": p.sha,+ "changes": p.changes,+ "conflicts": p.conflicts,+ "skipped": p.skipped,+ "external_not_undone": p.external,+ "not_undone_note": NOT_UNDONE,+ "effects_known": p.effects_known,+ "task_state_after": p.state_after,+ "refused": p.refused,+ })+}++/// Writes the plan's changes (plus the forced conflicts) into the folder; never through a symlink.+fn apply(blobs: &FsPath, p: &Plan, force: &BTreeSet<String>) -> (Vec<String>, Vec<String>, Vec<Value>) {+ let mut todo: Vec<(String, &'static str)> = p.changes.iter().map(|c| (c.path.clone(), c.action)).collect();+ todo.extend(p.forced.iter().filter(|(k, _)| force.contains(*k)).map(|(k, a)| (k.clone(), *a)));+ let (mut restored, mut deleted, mut failed) = (Vec::new(), Vec::new(), Vec::new());+ for (rel, action) in todo {+ if !safe_rel(&rel) || through_symlink(&p.folder, &rel) {+ failed.push(json!({"path": rel, "why": "symlink, not followed"}));+ continue;+ }+ let dest = p.folder.join(&rel);+ let r = if action == "delete" {+ std::fs::remove_file(&dest).map(|_| false)+ } else {+ let e = &p.entries[&rel];+ (|| -> std::io::Result<bool> {+ let parent = dest.parent().unwrap_or(&p.folder);+ std::fs::create_dir_all(parent)?;+ // The folders just created can't be symlinks, but one may have appeared meanwhile+ if through_symlink(&p.folder, &rel) {+ return Err(std::io::Error::other("symlink"));+ }+ let tmp = parent.join(format!(".kwant-restore-{}", new_id()));+ std::fs::copy(blobs.join(&e.sha256), &tmp)?;+ std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(if e.mode == 0 { 0o644 } else { e.mode }))?;+ std::fs::rename(&tmp, &dest).inspect_err(|_| {+ let _ = std::fs::remove_file(&tmp);+ })?;+ Ok(true)+ })()+ };+ match r {+ Ok(true) => restored.push(rel),+ Ok(false) => deleted.push(rel),+ Err(e) => failed.push(json!({"path": rel, "why": format!("couldn't be written: {}", e.kind())})),+ }+ }+ (restored, deleted, failed)+}++/// Takes a `before_restore` checkpoint, then writes the plan. Returns the counts JSON.+#[allow(clippy::result_large_err)]+async fn write_back(state: &AppState, task: &Task, c: &Checkpoint, p: &Plan, force: BTreeSet<String>) -> Result<Value, Response> {+ let Some(safety) = take(state, task, "before_restore", None, "person").await.filter(|s| !s.failed()) else {+ return Err(coded(StatusCode::INTERNAL_SERVER_ERROR, "checkpoint_failed", "the safety checkpoint couldn't be taken, so nothing was restored"));+ };+ let held = STORE.lock().await;+ let (blobs, plan) = (root(state).join("blobs"), p.clone());+ let (restored, deleted, failed) = tokio::task::spawn_blocking(move || apply(&blobs, &plan, &force)).await.map_err(internal)?;+ drop(held);+ let detail = json!({+ "checkpoint_id": c.id,+ "before_restore_checkpoint_id": safety.id,+ "restored": restored.len(),+ "deleted": deleted.len(),+ "failed": failed.len(),+ "external_not_undone": p.external.len(),+ });+ state.db.task_event(&task.id, task.mission_id.as_deref(), "restored", "person", &detail).await.map_err(internal)?;+ Ok(json!({+ "restored": restored,+ "deleted": deleted,+ "failed": failed,+ "before_restore_checkpoint_id": safety.id,+ "external_not_undone": p.external,+ "not_undone_note": NOT_UNDONE,+ "effects_known": p.effects_known,+ }))+}++fn coded(status: StatusCode, code: &str, msg: &str) -> Response {+ (status, Json(json!({"error": msg, "code": code}))).into_response()+}++#[allow(clippy::result_large_err)]+async fn load_checkpoint(state: &AppState, task: &Task, cid: &str) -> Result<Checkpoint, Response> {+ match state.db.get_checkpoint(cid).await {+ Ok(Some(c)) if c.task_id == task.id => Ok(c),+ Ok(_) => Err(not_found("checkpoint")),+ Err(e) => Err(internal(e)),+ }+}++#[allow(clippy::result_large_err)]+fn plan_err(e: PlanError) -> Response {+ match e {+ PlanError::NotRestorable => coded(StatusCode::CONFLICT, "not_restorable", "that checkpoint can't be restored (its snapshot failed or was removed)"),+ PlanError::Db(e) => internal(e),+ }+}++// API++/// The list item of one checkpoint; `next` is when the following one was taken.+fn item(c: &Checkpoint, calls: &[ToolCall], next: Option<chrono::DateTime<chrono::Utc>>) -> Value {+ let between: Vec<&ToolCall> = calls.iter().filter(|t| t.created_at >= c.created_at && next.is_none_or(|n| t.created_at < n)).collect();+ json!({+ "id": c.id,+ "kind": c.kind,+ "attempt": c.attempt,+ "created_at": c.created_at,+ "created_by": c.created_by,+ "files": c.files,+ "bytes": c.bytes,+ "skipped": c.skipped,+ "git_head": c.git_head,+ "error": c.error,+ "restorable": !c.failed() && FsPath::new(&c.manifest_path).is_file(),+ "effects_after": {+ "workspace": between.iter().filter(|t| t.effect == "workspace").count(),+ "external": between.iter().filter(|t| t.effect == "external").map(|t| tool_json(t)).collect::<Vec<_>>(),+ },+ })+}++#[allow(clippy::result_large_err)]+async fn items(state: &AppState, task: &Task) -> Result<Vec<Value>, Response> {+ let all = state.db.checkpoints_of(&task.id).await.map_err(internal)?;+ let calls = state.db.tool_calls_of(&task.id).await.map_err(internal)?;+ Ok(all.iter().enumerate().map(|(i, c)| item(c, &calls, all.get(i + 1).map(|n| n.created_at))).collect())+}++/// `GET /api/tasks/:id/checkpoints`+pub async fn list(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {+ let task = match load_task(&state, q.as_deref(), &id).await {+ Ok(t) => t,+ Err(r) => return r,+ };+ match items(&state, &task).await {+ Ok(v) => Json(v).into_response(),+ Err(r) => r,+ }+}++/// `POST /api/tasks/:id/checkpoints` (person-only): a manual checkpoint.+pub async fn create(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {+ let task = match load_task(&state, q.as_deref(), &id).await {+ Ok(t) => t,+ Err(r) => return r,+ };+ let Some(c) = take(&state, &task, "manual", None, "person").await else { return internal("the checkpoint wasn't stored") };+ let calls = state.db.tool_calls_of(&task.id).await.unwrap_or_default();+ let status = if c.failed() { StatusCode::INTERNAL_SERVER_ERROR } else { StatusCode::CREATED };+ (status, Json(item(&c, &calls, None))).into_response()+}++/// `GET /api/tasks/:id/checkpoints/:cid/restore-preview`+pub async fn preview(State(state): State<AppState>, RawQuery(q): RawQuery, Path((id, cid)): Path<(String, String)>) -> Response {+ let task = match load_task(&state, q.as_deref(), &id).await {+ Ok(t) => t,+ Err(r) => return r,+ };+ let c = match load_checkpoint(&state, &task, &cid).await {+ Ok(c) => c,+ Err(r) => return r,+ };+ match plan(&state, &task, &c).await {+ Ok(p) => Json(plan_json(&c, &p)).into_response(),+ Err(e) => plan_err(e),+ }+}++#[derive(Deserialize)]+pub struct RestoreBody {+ preview_sha256: String,+ #[serde(default)]+ force_paths: Vec<String>,+}++/// `POST /api/tasks/:id/checkpoints/:cid/restore` (person-only, `Idempotency-Key` required).+pub async fn restore(+ State(state): State<AppState>,+ RawQuery(q): RawQuery,+ headers: HeaderMap,+ Path((id, cid)): Path<(String, String)>,+ Json(b): Json<RestoreBody>,+) -> Response {+ if headers.get("idempotency-key").is_none() {+ return bad("an Idempotency-Key header is required");+ }+ let route = format!("POST /api/tasks/{id}/checkpoints/{cid}/restore");+ super::graph::idempotent(&state, &headers, route, || async {+ let task = load_task(&state, q.as_deref(), &id).await?;+ let c = load_checkpoint(&state, &task, &cid).await?;+ let p = plan(&state, &task, &c).await.map_err(plan_err)?;+ match p.refused {+ Some("fork_instead") => {+ return Err(coded(StatusCode::CONFLICT, "fork_instead", "a verified task isn't restored; fork it from this checkpoint instead"))+ }+ Some(_) => return Err(coded(StatusCode::CONFLICT, "running", "the task is running; restore it once the run ends")),+ None => {}+ }+ if p.sha != b.preview_sha256.trim() {+ return Err(coded(StatusCode::CONFLICT, "stale_preview", "the folder or the task changed since the preview; look at it again"));+ }+ let mut out = write_back(&state, &task, &c, &p, b.force_paths.into_iter().collect()).await?;+ let mut t = state.db.get_task(&task.id).await.map_err(internal)?.unwrap_or(task.clone());+ if let Some(to) = p.state_after {+ let change = TaskChange { reason: Some("restored from a checkpoint".into()), detail: Some(json!({"checkpoint_id": c.id})), ..Default::default() };+ t = super::routes::moved(transition(&state, &task.id, &task.state, to, Actor::Person, "person", change).await)?;+ } else {+ emit_task(&state, &t).await;+ }+ out["task"] = task_json(&state, &t).await;+ Ok(out)+ })+ .await+}++/// Fork `from_checkpoint` (B1 `POST /api/tasks/:id/fork`): writes the original's task-owned+/// paths back to the checkpoint (after a `before_restore`), skipping other tasks' changes.+#[allow(clippy::result_large_err)]+pub async fn restore_for_fork(state: &AppState, orig: &Task, cid: &str) -> Result<Value, Response> {+ let c = load_checkpoint(state, orig, cid).await?;+ let p = plan(state, orig, &c).await.map_err(plan_err)?;+ if p.refused == Some("running") {+ return Err(coded(StatusCode::CONFLICT, "running", "the task is running; fork it once the run ends"));+ }+ let mut out = write_back(state, orig, &c, &p, BTreeSet::new()).await?;+ out["checkpoint_id"] = json!(c.id);+ out["conflicts"] = json!(p.conflicts);+ Ok(out)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn only_plain_relative_paths_are_safe() {+ assert!(safe_rel("a.txt"));+ assert!(safe_rel("dir/b.txt"));+ assert!(!safe_rel("../escape"));+ assert!(!safe_rel("a/../../b"));+ assert!(!safe_rel("/etc/passwd"));+ assert!(!safe_rel("./a"));+ assert!(!safe_rel(""));+ assert!(!safe_rel("dir/"));+ }++ fn m(files: &[(&str, &str)], skipped: &[&str]) -> Manifest {+ Manifest {+ files: files.iter().map(|(p, s)| Entry { path: p.to_string(), sha256: s.to_string(), bytes: 1, mode: 0o644 }).collect(),+ skipped: skipped.iter().map(|p| Skip { path: p.to_string(), why: "over 20 MB".into() }).collect(),+ }+ }++ fn req(tool_name: &str, server: &str, args: Value, cwd: &str) -> crate::mcp::ToolApprovalRequest {+ crate::mcp::ToolApprovalRequest {+ kwant_id: "k".into(),+ kwant_name: "K".into(),+ turn_id: "t".into(),+ tool_name: tool_name.into(),+ server: server.into(),+ tool: tool_name.rsplit("__").next().unwrap_or(tool_name).into(),+ arguments: args,+ builtin: server.is_empty().then(|| crate::mcp::BuiltinCall { cwd: Some(cwd.into()), outside_folder: false }),+ smart: None,+ }+ }++ #[test]+ fn unproven_side_effects_are_external() {+ let dir = tempfile::tempdir().unwrap();+ let d = dir.path().to_str().unwrap();+ let f = Some(dir.path());+ assert_eq!(effect(&req("Read", "", json!({"file_path": "/etc/hosts"}), d), f), "none");+ assert_eq!(effect(&req("Write", "", json!({"file_path": "a.txt"}), d), f), "workspace");+ assert_eq!(effect(&req("Edit", "", json!({"file_path": format!("{d}/b/c.txt")}), d), f), "workspace");+ assert_eq!(effect(&req("Write", "", json!({"file_path": "/tmp/elsewhere.txt"}), d), f), "external");+ assert_eq!(effect(&req("Write", "", json!({"file_path": "../up.txt"}), d), f), "external");+ assert_eq!(effect(&req("Write", "", json!({"file_path": "a.txt"}), d), None), "external");+ assert_eq!(effect(&req("Bash", "", json!({"command": "ls"}), d), f), "external", "D6: Bash is always external");+ assert_eq!(effect(&req("WebFetch", "", json!({"url": "https://x"}), d), f), "external");+ assert_eq!(effect(&req("mcp__gmail__send", "gmail", json!({}), d), f), "external");+ assert_eq!(effect(&req("mcp__kwnt_tools__task_update", crate::mcp::SELF_SERVER_NAME, json!({}), d), f), "none");+ assert_eq!(effect(&req("mcp__kwnt_tools__delegate", crate::mcp::SELF_SERVER_NAME, json!({}), d), f), "external");+ }++ #[test]+ fn summaries_never_carry_bodies_or_secrets() {+ let s = summary("Write", &json!({"file_path": "a.txt", "content": "TOP SECRET BODY"}));+ assert!(s.starts_with("Write ") && s.contains("a.txt") && s.contains("<15 chars>") && !s.contains("SECRET BODY"), "{s}");+ let s = summary("Bash", &json!({"command": "curl -H 'Authorization: Bearer sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789' https://x"}));+ assert!(!s.contains("abcdefghijklmnopqrstuvwxyz0123456789"), "{s}");+ assert!(summary("Bash", &json!({"command": "x".repeat(1000)})).chars().count() <= 300);+ }++ #[test]+ fn a_run_owns_what_it_created_changed_or_deleted() {+ let before = m(&[("same", "1"), ("edited", "1"), ("gone", "1")], &["big", "node_modules/"]);+ let after = m(&[("same", "1"), ("edited", "2"), ("new", "1")], &["big", "node_modules/", "huge"]);+ assert_eq!(changed(&before, &after), vec!["edited", "gone", "huge", "new"]);+ }+}diff --git a/src/server/missions/graph.rs b/src/server/missions/graph.rsindex 96fa67c2..567a6529 100644--- a/src/server/missions/graph.rs+++ b/src/server/missions/graph.rs@@ -309,14 +309,20 @@ pub async fn fork_task(State(state): State<AppState>, RawQuery(q): RawQuery, heaif 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?;+ // The fork starts from the checkpoint: the original's task-owned paths go back first+ let restore = match p.from_checkpoint.as_deref().map(str::trim) {+ Some(cid) => Some(super::checkpoints::restore_for_fork(&state, &orig, cid).await?),+ None => None,+ };let f = fork(&state, &orig, &reason).await?;- Ok(task_json(&state, &f).await)+ let mut out = task_json(&state, &f).await;+ if let Some(r) = restore {+ out["restore"] = r;+ }+ Ok(out)}).await}diff --git a/src/server/missions/listener.rs b/src/server/missions/listener.rsindex 76594b27..d1e4fc51 100644--- a/src/server/missions/listener.rs+++ b/src/server/missions/listener.rs@@ -132,7 +132,10 @@ async fn start_held(/// 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(Ok(t)) => {+ super::emit_task(state, &t).await;+ super::checkpoints::before_run(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;diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rsindex 395bd26e..8a7eeefc 100644--- a/src/server/missions/mod.rs+++ b/src/server/missions/mod.rs@@ -12,6 +12,7 @@//! - 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 checkpoints;pub mod checks;pub mod graph;pub mod listener;@@ -46,7 +47,7 @@ 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 {+pub(crate) async fn int_setting(state: &AppState, key: &str, range: (i64, i64), default: i64) -> i64 {state.db.get_setting(key)@@ -178,6 +179,10 @@ pub async fn transition(}let task = state.db.get_task(task_id).await.map_err(MoveError::Db)?.ok_or(MoveError::Missing)?;emit_task(state, &task).await;+ // The run's claim was released: snapshot what it left (after the commit, never inside it)+ if matches!(from, "working" | "needs_you") && !matches!(to, "working" | "needs_you") {+ checkpoints::after_run(state, &task).await;+ }after_move(state, &task, to).await;Ok(task)}@@ -522,6 +527,9 @@ 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));+ let (count, last) = state.db.checkpoint_stats(&task.id).await.unwrap_or((0, None));+ obj.insert("checkpoint_count".into(), json!(count));+ obj.insert("last_checkpoint_at".into(), json!(last));}v}@@ -883,8 +891,13 @@ pub async fn create_task(state: &AppState, space: &SpaceId, t: NewTask) -> Resul/// 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> {+ task_folder_in(&state.db, &state.config.data_dir, task).await+}++/// [`task_folder`] without the app state (the permission hook has only the database).+pub async fn task_folder_in(db: &crate::db::Database, data_dir: &std::path::Path, 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 let Ok(Some(m)) = db.get_mission(mid).await {if !m.workspace_path.is_empty() {return Some(std::path::PathBuf::from(m.workspace_path));}@@ -892,7 +905,7 @@ pub async fn task_folder(state: &AppState, task: &Task) -> Option<std::path::Pat}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))+ Some(crate::tools::bot_workspace(&crate::db::spaces::space_data_dir(data_dir, &space), owner))}#[cfg(test)]diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rsindex a0147766..06b3b8ec 100644--- a/src/server/missions/runner.rs+++ b/src/server/missions/runner.rs@@ -86,6 +86,7 @@ pub async fn run_mission(state: &AppState, mission: &Mission, max: usize) -> (Vematch 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;+ super::checkpoints::before_run(state, &task).await;picked.push((task, bot));}Ok(Err(ClaimRefused::Budget { remaining, needed })) => {diff --git a/src/server/missions/tools.rs b/src/server/missions/tools.rsindex 2ad79fe6..b9d6f0c2 100644--- a/src/server/missions/tools.rs+++ b/src/server/missions/tools.rs@@ -253,6 +253,7 @@ async fn claim(state: &AppState, scope: &SelfScope, task: &Task) -> ToolResult {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;+ super::checkpoints::before_run(state, &t).await;if let Some(m) = &t.mission_id {super::emit_mission(state, m).await;}diff --git a/src/server/mod.rs b/src/server/mod.rsindex c2a88445..0b84c5f3 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -374,6 +374,9 @@ pub fn create_router(state: AppState) -> Router {.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/checkpoints", get(missions::checkpoints::list).post(missions::checkpoints::create))+ .route("/api/tasks/:id/checkpoints/:cid/restore-preview", get(missions::checkpoints::preview))+ .route("/api/tasks/:id/checkpoints/:cid/restore", post(missions::checkpoints::restore)).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))diff --git a/src/server/routes.rs b/src/server/routes.rsindex 237ec54c..6e209f54 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -3267,6 +3267,12 @@ pub struct SettingsResponse {pub mission_lease_minutes: i64,/// A new mission's token budget when none is given.pub mission_default_budget_tokens: i64,+ /// Time Machine: checkpoints before and after each task run (see `super::missions::checkpoints`).+ pub checkpoints: bool,+ /// Largest checkpoint, in MB (10–2000).+ pub checkpoint_max_mb: i64,+ /// Checkpoints kept per task (1–20), plus its first `before_run`.+ pub checkpoint_keep: i64,}/// Unknown keys are refused, so a typo or a key from another version fails loudly instead of@@ -3302,6 +3308,9 @@ pub struct SaveSettingsPayload {pub mission_board: Option<bool>,pub mission_lease_minutes: Option<i64>,pub mission_default_budget_tokens: Option<i64>,+ pub checkpoints: Option<bool>,+ pub checkpoint_max_mb: Option<i64>,+ pub checkpoint_keep: Option<i64>,}pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {@@ -3346,6 +3355,9 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settingsmission_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,+ checkpoints: super::missions::checkpoints::enabled(&state).await,+ checkpoint_max_mb: super::missions::checkpoints::max_mb(&state).await,+ checkpoint_keep: super::missions::checkpoints::keep(&state).await,}))}@@ -3395,6 +3407,9 @@ pub async fn save_settings(if let Some(e) = super::missions::settings_error(payload.mission_lease_minutes, payload.mission_default_budget_tokens) {return bad(e);}+ if let Some(e) = super::missions::checkpoints::settings_error(payload.checkpoint_max_mb, payload.checkpoint_keep) {+ 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));}@@ -3493,6 +3508,15 @@ pub async fn save_settings(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.checkpoints {+ let _ = state.db.set_setting(super::missions::checkpoints::SETTING, if on { "true" } else { "false" }).await;+ }+ if let Some(n) = payload.checkpoint_max_mb {+ let _ = state.db.set_setting(super::missions::checkpoints::MAX_MB_SETTING, &n.to_string()).await;+ }+ if let Some(n) = payload.checkpoint_keep {+ let _ = state.db.set_setting(super::missions::checkpoints::KEEP_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/tests/approvals_off_test.rs b/tests/approvals_off_test.rsindex 48847f86..584131e1 100644--- a/tests/approvals_off_test.rs+++ b/tests/approvals_off_test.rs@@ -262,6 +262,7 @@ async fn an_always_ask_turn_asks_even_with_approvals_off() {for (always_ask, want) in [(false, ApprovalOutcome::Allowed), (true, ApprovalOutcome::Unanswered)] {let approver = mcp_runtime::BrokerApprover {db: e.state.db.clone(),+ data_dir: e.state.config.data_dir.clone(),broker: e.state.broker.clone(),events: e.state.event_sender.clone(),timeout: Duration::from_millis(200),diff --git a/tests/late_approval_test.rs b/tests/late_approval_test.rsindex 6bea88c8..13525b15 100644--- a/tests/late_approval_test.rs+++ b/tests/late_approval_test.rs@@ -14,6 +14,7 @@ use std::time::Duration;fn approver(env: &Env, timeout: Duration) -> Arc<BrokerApprover> {Arc::new(BrokerApprover {db: env.state.db.clone(),+ data_dir: env.state.config.data_dir.clone(),broker: env.state.broker.clone(),events: env.state.event_sender.clone(),timeout,@@ -93,6 +94,7 @@ async fn a_grant_runs_once_only_in_its_own_conversation() {// Another conversation of the same bot can't use itlet elsewhere = BrokerApprover {db: env.state.db.clone(),+ data_dir: env.state.config.data_dir.clone(),broker: env.state.broker.clone(),events: env.state.event_sender.clone(),timeout: Duration::from_millis(200),diff --git a/tests/mcp_gateway_test.rs b/tests/mcp_gateway_test.rsindex 2ec3b7df..8b75c6c0 100644--- a/tests/mcp_gateway_test.rs+++ b/tests/mcp_gateway_test.rs@@ -179,6 +179,7 @@ async fn gateway_calls_wait_for_the_approval_card() {let base = serve(state.clone()).await;let approver = Arc::new(BrokerApprover {db: state.db.clone(),+ data_dir: state.config.data_dir.clone(),broker: state.broker.clone(),events: state.event_sender.clone(),timeout: Duration::from_secs(10),@@ -238,6 +239,7 @@ async fn ending_the_turn_cancels_a_call_waiting_for_its_card() {let base = serve(state.clone()).await;let approver = Arc::new(BrokerApprover {db: state.db.clone(),+ data_dir: state.config.data_dir.clone(),broker: state.broker.clone(),events: state.event_sender.clone(),timeout: Duration::from_secs(300),diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rsindex 93e0861f..bd77eb2f 100644--- a/tests/mcp_runtime_test.rs+++ b/tests/mcp_runtime_test.rs@@ -104,6 +104,7 @@ async fn ask(state: &AppState, approver: Arc<BrokerApprover>, tool: &str) -> (tofn approver(state: &AppState, timeout: Duration) -> Arc<BrokerApprover> {Arc::new(BrokerApprover {db: state.db.clone(),+ data_dir: state.config.data_dir.clone(),broker: state.broker.clone(),events: state.event_sender.clone(),timeout,diff --git a/tests/mission_checkpoints_test.rs b/tests/mission_checkpoints_test.rsnew file mode 100644index 00000000..511ead87--- /dev/null+++ b/tests/mission_checkpoints_test.rs@@ -0,0 +1,655 @@+//! Mission Control Phase B2: checkpoints and restore. A task's runs are snapshotted before and+//! after, a restore writes back only the paths this task's runs changed (after a safety+//! checkpoint), and every tool call of a task turn is in the ledger with its effect. These are the+//! contract's 9 acceptance tests (docs/mission-control.md §12), numbered as there, plus two B1+//! gaps: the retry `Idempotency-Key` and the drift scan's limits. Its own test binary: it changes+//! PATH and listens on a real port the stand-in CLI calls back on.++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 std::os::unix::fs::PermissionsExt;+use std::path::{Path, PathBuf};+use std::sync::OnceLock;+use std::time::Duration;+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++/// On a Mission Control prompt: asks kwant's permission tool (the `--permission-prompt-tool`+/// server in its `--mcp-config`) for a Write of a.txt and writes it when allowed, asks for a Bash+/// `echo` and runs it, then moves the task it holds to review through its kwant tools.+const FAKE_CLAUDE: &str = r#"#!/usr/bin/env python3+import json, re, subprocess, 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)++def post(s, name, arguments):+ call = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": arguments}}+ headers = dict(s.get("headers", {}), **{"content-type": "application/json"})+ req = urllib.request.Request(s["url"], data=json.dumps(call).encode(), headers=headers)+ return json.loads(urllib.request.urlopen(req, timeout=30).read() or b"null")++def allowed(r):+ try:+ return json.loads(r["result"]["content"][0]["text"]).get("behavior") == "allow"+ except Exception:+ return False++if held and "--mcp-config" in args:+ with open(args[args.index("--mcp-config") + 1]) as f:+ servers = json.load(f).get("mcpServers", {})+ perm = next((s for s in servers.values() if "/api/mcp/permission/" in s.get("url", "")), None)+ me = next((s for s in servers.values() if s.get("url", "").endswith("/api/mcp/self")), None)+ if perm and allowed(post(perm, "approve", {"tool_name": "Write", "input": {"file_path": "a.txt", "content": "changed"}, "tool_use_id": "t1"})):+ with open("a.txt", "w") as f:+ f.write("changed")+ if perm and allowed(post(perm, "approve", {"tool_name": "Bash", "input": {"command": "echo hi", "description": "say hi"}, "tool_use_id": "t2"})):+ subprocess.run(["echo", "hi"], stdout=subprocess.DEVNULL)+ if me:+ post(me, "task_update", {"task_id": held.group(1), "status": "review"})+print(json.dumps({"type": "result", "is_error": False, "num_turns": 1, "result": "done, sent for review",+ "usage": {"input_tokens": 10, "output_tokens": 10}}))+"#;++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();+ 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+ });+}++struct Env {+ app: Router,+ state: AppState,+ bot: Kwant,+ general: String,+ _tmp: TempDir,+}++/// kwant on a real port (the stand-in CLI calls back), with the mission board on.+async fn setup() -> Env {+ let tmp = tempdir().unwrap();+ 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() });+ let space = SpaceId::default_space();+ let bot = state.db.list_kwants(&space).await.unwrap()[0].clone();+ let general = state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap().id;+ let e = Env { app, state, bot, general, _tmp: tmp };+ person(&e, "POST", "/api/settings", Some(json!({"mission_board": true}))).await;+ e+}++async fn send(app: &Router, method: &str, uri: &str, auth: Option<&str>, key: Option<&str>, body: Option<Value>) -> (StatusCode, Value, bool) {+ 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}"));+ }+ if let Some(k) = key {+ req = req.header("idempotency-key", k);+ }+ 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 replayed = resp.headers().get("idempotent-replayed").is_some_and(|v| v == "true");+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null), replayed)+}++async fn call(app: &Router, method: &str, uri: &str, auth: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {+ let (s, v, _) = send(app, method, uri, auth, None, body).await;+ (s, v)+}++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+}++async fn ok(e: &Env, token: &str, name: &str, args: Value) -> Value {+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});+ let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc)).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ let text = v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string();+ assert!(!v["result"]["isError"].as_bool().unwrap_or(false), "{name} {args} failed: {text}");+ serde_json::from_str(&text).unwrap_or(Value::Null)+}++/// 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+}++fn id(v: &Value) -> String {+ v["id"].as_str().unwrap().to_string()+}++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 led by `lead` with `tasks`; returns the mission id and task ids sorted by title.+async fn mission(e: &Env, lead: &str, tasks: Value) -> (String, Vec<String>) {+ let body = json!({"title": "Ship it", "goal": "a release", "lead_kwant_id": lead, "budget_tokens": 900_000,+ "channel_id": e.general, "tasks": tasks});+ let m = person(e, "POST", "/api/missions", Some(body)).await;+ let detail = person(e, "GET", &format!("/api/missions/{}", id(&m)), None).await;+ let mut listed = detail["tasks"].as_array().unwrap().clone();+ listed.sort_by_key(|t| t["title"].as_str().unwrap().to_string());+ (id(&m), listed.iter().map(id).collect())+}++async fn folder(e: &Env, mission_id: &str) -> PathBuf {+ let m = e.state.db.get_mission(mission_id).await.unwrap().unwrap();+ let p = PathBuf::from(m.workspace_path);+ std::fs::create_dir_all(&p).unwrap();+ p+}++/// The bot claims `tid`, makes `writes` in the folder (`None` deletes) and hands it in.+async fn run(e: &Env, mid: &str, tid: &str, writes: &[(&str, Option<&str>)]) {+ let dir = folder(e, mid).await;+ let token = turn(e, &e.bot, &format!("t-{tid}-{}", uuid::Uuid::new_v4())).await;+ ok(e, &token, "task_claim", json!({"task_id": tid})).await;+ for (p, body) in writes {+ match body {+ Some(b) => std::fs::write(dir.join(p), b).unwrap(),+ None => std::fs::remove_file(dir.join(p)).unwrap(),+ }+ }+ ok(e, &token, "task_update", json!({"task_id": tid, "status": "review"})).await;+}++async fn checkpoints(e: &Env, tid: &str) -> Vec<Value> {+ person(e, "GET", &format!("/api/tasks/{tid}/checkpoints"), None).await.as_array().unwrap().clone()+}++fn of_kind<'a>(list: &'a [Value], kind: &str) -> Vec<&'a Value> {+ list.iter().filter(|c| c["kind"] == kind).collect()+}++async fn preview(e: &Env, tid: &str, cid: &str) -> Value {+ person(e, "GET", &format!("/api/tasks/{tid}/checkpoints/{cid}/restore-preview"), None).await+}++async fn restore(e: &Env, tid: &str, cid: &str, key: &str, sha: &Value) -> (StatusCode, Value, bool) {+ let uri = format!("/api/tasks/{tid}/checkpoints/{cid}/restore");+ send(&e.app, "POST", &uri, None, Some(key), Some(json!({"preview_sha256": sha}))).await+}++/// A bot that runs on the stand-in claude CLI, with approvals off for the space.+async fn cli_bot(e: &Env) -> String {+ fake_cli();+ e.state.db.set_space_approvals(&SpaceId::default_space(), "off").await.unwrap();+ let bot = json!({"name": "Ann", "title": "Ann the tester", "persona_prompt": "Test persona",+ "avatar_sprite": "s", "driver_type": "cli", "preferred_model": "claude"});+ id(&person(e, "POST", "/api/kwants", Some(bot)).await)+}++/// The runner starts `tid` on the stand-in CLI; waits until the turn hands it in.+async fn cli_run(e: &Env, mid: &str, tid: &str) {+ let r = person(e, "POST", &format!("/api/missions/{mid}/run"), Some(json!({"max_tasks": 1}))).await;+ assert_eq!(r["started"][0]["task_id"], tid, "{r}");+ for _ in 0..300 {+ if state_of(e, tid).await == "review" {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ assert_eq!(state_of(e, tid).await, "review", "{}", task(e, tid).await);+ // The after_run checkpoint is taken in the move to review; the turn may still be ending+ for _ in 0..100 {+ if e.state.db.open_claim(tid).await.unwrap().is_none() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+}++fn sha(bytes: &[u8]) -> String {+ let d = <sha2::Sha256 as sha2::Digest>::digest(bytes);+ d.iter().map(|b| format!("{b:02x}")).collect()+}++fn blobs(e: &Env) -> PathBuf {+ e.state.config.data_dir.join("checkpoints").join("blobs")+}++async fn events(e: &Env, tid: &str, kind: &str) -> Vec<Value> {+ e.state.db.event_details(tid, kind).await.unwrap()+}++/// A mission on the stand-in CLI whose folder holds a.txt ("original") and keep.txt, run once.+async fn cli_mission(e: &Env) -> (String, String, PathBuf) {+ let ann = cli_bot(e).await;+ let (mid, ids) = mission(e, &ann, json!([{"title": "A", "owner": ann}])).await;+ let dir = folder(e, &mid).await;+ std::fs::write(dir.join("a.txt"), "original").unwrap();+ std::fs::write(dir.join("keep.txt"), b"untouched \x00\x01 bytes").unwrap();+ cli_run(e, &mid, &ids[0]).await;+ (mid, ids[0].clone(), dir)+}++// 1+#[tokio::test]+async fn a_task_run_is_checkpointed_and_its_tool_calls_are_in_the_ledger() {+ let e = setup().await;+ let (_mid, tid, dir) = cli_mission(&e).await;+ assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "changed", "the turn wrote a.txt");+ let list = checkpoints(&e, &tid).await;+ let before = of_kind(&list, "before_run");+ let after = of_kind(&list, "after_run");+ assert_eq!((before.len(), after.len()), (1, 1), "{list:?}");+ assert!(before[0]["restorable"].as_bool().unwrap() && after[0]["restorable"].as_bool().unwrap(), "{list:?}");+ assert!(before[0]["files"].as_i64().unwrap() >= 2, "{list:?}");+ let calls = e.state.db.tool_calls_of(&tid).await.unwrap();+ let effect = |name: &str| calls.iter().find(|c| c.tool_name == name).map(|c| c.effect.clone());+ assert_eq!(effect("Write").as_deref(), Some("workspace"), "{calls:?}");+ assert_eq!(effect("Bash").as_deref(), Some("external"), "D6: Bash is always external: {calls:?}");+ assert!(calls.iter().all(|c| c.decision.contains("allowed")), "approvals are off: {calls:?}");+ // The list shows what happened after the before_run checkpoint+ assert_eq!(before[0]["effects_after"]["workspace"], 1, "{list:?}");+ assert_eq!(before[0]["effects_after"]["external"][0]["tool_name"], "Bash", "{list:?}");+ let t = task(&e, &tid).await;+ assert_eq!(t["task"]["checkpoint_count"], 2, "{t}");+}++// 2+#[tokio::test]+async fn a_restore_brings_back_the_tasks_files_and_can_itself_be_undone() {+ let e = setup().await;+ let (_mid, tid, dir) = cli_mission(&e).await;+ let keep_before = std::fs::read(dir.join("keep.txt")).unwrap();+ let list = checkpoints(&e, &tid).await;+ let cid = id(of_kind(&list, "before_run")[0]);+ let p = preview(&e, &tid, &cid).await;+ assert_eq!(p["changes"], json!([{"path": "a.txt", "action": "overwrite"}]), "{p}");+ assert_eq!(p["task_state_after"], "ready", "{p}");+ assert!(p["refused"].is_null(), "{p}");+ let external = p["external_not_undone"].as_array().unwrap();+ assert!(external.iter().any(|x| x["tool_name"] == "Bash"), "{p}");+ assert!(p["not_undone_note"].as_str().unwrap().contains("can't undo"), "{p}");++ let (s, r, _) = restore(&e, &tid, &cid, "restore-1", &p["preview_sha256"]).await;+ assert_eq!(s, StatusCode::OK, "{r}");+ assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "original");+ assert_eq!(std::fs::read(dir.join("keep.txt")).unwrap(), keep_before, "an untouched file stays byte-identical");+ assert_eq!(r["restored"], json!(["a.txt"]), "{r}");+ assert!(r["external_not_undone"].as_array().unwrap().iter().any(|x| x["tool_name"] == "Bash"), "{r}");+ assert_eq!(r["task"]["state"], "ready", "{r}");+ let safety = r["before_restore_checkpoint_id"].as_str().unwrap().to_string();+ let list = checkpoints(&e, &tid).await;+ assert_eq!(of_kind(&list, "before_restore").len(), 1, "{list:?}");+ assert_eq!(events(&e, &tid, "restored").await.len(), 1);++ // The restore is undone from its own safety checkpoint+ let p = preview(&e, &tid, &safety).await;+ assert_eq!(p["changes"], json!([{"path": "a.txt", "action": "overwrite"}]), "{p}");+ let (s, r, _) = restore(&e, &tid, &safety, "restore-2", &p["preview_sha256"]).await;+ assert_eq!(s, StatusCode::OK, "{r}");+ assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "changed");+ assert_eq!(std::fs::read(dir.join("keep.txt")).unwrap(), keep_before);+}++// 3+#[tokio::test]+async fn a_verified_task_forks_instead_and_a_running_one_is_refused() {+ let e = setup().await;+ let plan = json!([{"title": "A", "owner": e.bot.id, "checks": [{"kind": "file_exists", "spec": {"path": "a.txt"}}]},+ {"title": "B", "owner": e.bot.id}]);+ let (mid, ids) = mission(&e, &e.bot.id, plan).await;+ run(&e, &mid, &ids[0], &[("a.txt", Some("v1"))]).await;+ assert_eq!(state_of(&e, &ids[0]).await, "verified");+ let cid = id(of_kind(&checkpoints(&e, &ids[0]).await, "before_run")[0]);+ let p = preview(&e, &ids[0], &cid).await;+ assert_eq!(p["refused"], "fork_instead", "{p}");+ let (s, v, _) = restore(&e, &ids[0], &cid, "k-verified", &p["preview_sha256"]).await;+ assert_eq!((s, v["code"].as_str()), (StatusCode::CONFLICT, Some("fork_instead")), "{v}");+ assert_eq!(std::fs::read_to_string(folder(&e, &mid).await.join("a.txt")).unwrap(), "v1", "nothing written");++ let token = turn(&e, &e.bot, "t-running").await;+ ok(&e, &token, "task_claim", json!({"task_id": ids[1]})).await;+ assert_eq!(state_of(&e, &ids[1]).await, "working");+ let cid = id(of_kind(&checkpoints(&e, &ids[1]).await, "before_run")[0]);+ let p = preview(&e, &ids[1], &cid).await;+ assert_eq!(p["refused"], "running", "{p}");+ let (s, v, _) = restore(&e, &ids[1], &cid, "k-running", &p["preview_sha256"]).await;+ assert_eq!((s, v["code"].as_str()), (StatusCode::CONFLICT, Some("running")), "{v}");+ assert!(of_kind(&checkpoints(&e, &ids[1]).await, "before_restore").is_empty(), "no safety checkpoint for a refused restore");+}++// 4+#[tokio::test]+async fn a_stale_preview_is_refused_and_a_repeated_key_writes_nothing() {+ let e = setup().await;+ let (mid, ids) = mission(&e, &e.bot.id, json!([{"title": "A", "owner": e.bot.id}])).await;+ let dir = folder(&e, &mid).await;+ std::fs::write(dir.join("a.txt"), "v0").unwrap();+ run(&e, &mid, &ids[0], &[("a.txt", Some("v1"))]).await;+ assert_eq!(state_of(&e, &ids[0]).await, "review");+ let cid = id(of_kind(&checkpoints(&e, &ids[0]).await, "before_run")[0]);+ let stale = preview(&e, &ids[0], &cid).await;+ std::fs::write(dir.join("a.txt"), "v2, edited after the preview").unwrap();+ let (s, v, _) = restore(&e, &ids[0], &cid, "k-stale", &stale["preview_sha256"]).await;+ assert_eq!((s, v["code"].as_str()), (StatusCode::CONFLICT, Some("stale_preview")), "{v}");+ assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "v2, edited after the preview");++ let fresh = preview(&e, &ids[0], &cid).await;+ assert_ne!(fresh["preview_sha256"], stale["preview_sha256"]);+ let (s1, first, replay1) = restore(&e, &ids[0], &cid, "k-once", &fresh["preview_sha256"]).await;+ assert_eq!(s1, StatusCode::OK, "{first}");+ assert!(!replay1);+ assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "v0");+ std::fs::write(dir.join("a.txt"), "v3, after the restore").unwrap();+ let (s2, second, replay2) = restore(&e, &ids[0], &cid, "k-once", &fresh["preview_sha256"]).await;+ assert_eq!(s2, StatusCode::OK, "{second}");+ assert!(replay2, "the same key replays the first response");+ assert_eq!(first, second);+ assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "v3, after the restore", "a replay writes nothing");+ assert_eq!(of_kind(&checkpoints(&e, &ids[0]).await, "before_restore").len(), 1);+ assert_eq!(events(&e, &ids[0], "restored").await.len(), 1);+ // The key is required+ let uri = format!("/api/tasks/{}/checkpoints/{cid}/restore", ids[0]);+ let (s, _, _) = send(&e.app, "POST", &uri, None, None, Some(json!({"preview_sha256": fresh["preview_sha256"]}))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+}++// 5+#[tokio::test]+async fn unsafe_manifest_paths_and_symlinks_are_skipped_and_never_followed() {+ let e = setup().await;+ let (mid, ids) = mission(&e, &e.bot.id, json!([{"title": "A", "owner": e.bot.id}])).await;+ let dir = folder(&e, &mid).await;+ let outside = dir.parent().unwrap().join("outside.txt");+ std::fs::write(&outside, "outside, never touched").unwrap();+ std::os::unix::fs::symlink(&outside, dir.join("link.txt")).unwrap();+ std::fs::write(dir.join("s.txt"), "s v0").unwrap();+ run(&e, &mid, &ids[0], &[("s.txt", Some("s v1")), ("a.txt", Some("a v1"))]).await;+ let list = checkpoints(&e, &ids[0]).await;+ let before = of_kind(&list, "before_run")[0].clone();+ let cid = id(&before);+ // The snapshot didn't follow the symlink+ let m_path = e.state.config.data_dir.join("checkpoints").join(&ids[0]).join(format!("{cid}.json"));+ let mut m: Value = serde_json::from_slice(&std::fs::read(&m_path).unwrap()).unwrap();+ assert!(m["files"].as_array().unwrap().iter().all(|f| f["path"] != "link.txt"), "{m}");+ let skip = m["skipped"].as_array().unwrap().iter().find(|s| s["path"] == "link.txt").cloned();+ assert_eq!(skip.unwrap()["why"], "symlink, not followed", "{m}");++ // A hand-edited manifest with an escaping and an absolute path+ let blob = sha(b"s v0");+ let escape_abs = dir.parent().unwrap().join("abs-escape.txt");+ for p in ["../escape.txt".to_string(), escape_abs.display().to_string()] {+ m["files"].as_array_mut().unwrap().push(json!({"path": p, "sha256": blob, "bytes": 4, "mode": 420}));+ }+ std::fs::write(&m_path, serde_json::to_vec(&m).unwrap()).unwrap();+ // s.txt, which the run changed, is now a symlink out of the folder+ std::fs::remove_file(dir.join("s.txt")).unwrap();+ std::os::unix::fs::symlink(&outside, dir.join("s.txt")).unwrap();++ let p = preview(&e, &ids[0], &cid).await;+ let skipped = p["skipped"].as_array().unwrap();+ let why = |path: &str| skipped.iter().find(|s| s["path"] == path).map(|s| s["why"].as_str().unwrap().to_string());+ assert_eq!(why("../escape.txt").as_deref(), Some("unsafe path"), "{p}");+ assert_eq!(why(&escape_abs.display().to_string()).as_deref(), Some("unsafe path"), "{p}");+ assert_eq!(why("s.txt").as_deref(), Some("symlink, not followed"), "{p}");+ assert_eq!(p["changes"], json!([{"path": "a.txt", "action": "delete"}]), "{p}");+ let (s, r, _) = restore(&e, &ids[0], &cid, "k-unsafe", &p["preview_sha256"]).await;+ assert_eq!(s, StatusCode::OK, "{r}");+ assert_eq!(std::fs::read_to_string(&outside).unwrap(), "outside, never touched", "nothing written through a symlink");+ assert!(!dir.parent().unwrap().join("escape.txt").exists() && !escape_abs.exists(), "nothing written outside the folder");+ assert!(!dir.join("a.txt").exists(), "the run's new file is gone");+}++// 6+#[tokio::test]+async fn large_files_are_skipped_and_old_checkpoints_and_orphan_blobs_are_pruned() {+ let e = setup().await;+ person(&e, "POST", "/api/settings", Some(json!({"checkpoint_keep": 2}))).await;+ let (mid, ids) = mission(&e, &e.bot.id, json!([{"title": "A", "owner": e.bot.id}])).await;+ let dir = folder(&e, &mid).await;+ std::fs::File::create(dir.join("big.bin")).unwrap().set_len(25 * 1024 * 1024).unwrap();+ std::fs::write(dir.join("u.txt"), "u0").unwrap();+ run(&e, &mid, &ids[0], &[]).await;+ let first = id(of_kind(&checkpoints(&e, &ids[0]).await, "before_run")[0]);++ std::fs::write(blobs(&e).join("f".repeat(64)), "orphan").unwrap();+ for n in 1..=4 {+ std::fs::write(dir.join("u.txt"), format!("u{n}")).unwrap();+ let c = person(&e, "POST", &format!("/api/tasks/{}/checkpoints", ids[0]), None).await;+ assert_eq!(c["kind"], "manual");+ assert_eq!(c["skipped"], 1, "{c}");+ let m_path = e.state.config.data_dir.join("checkpoints").join(&ids[0]).join(format!("{}.json", id(&c)));+ let m: Value = serde_json::from_slice(&std::fs::read(m_path).unwrap()).unwrap();+ assert_eq!(m["skipped"], json!([{"path": "big.bin", "why": "over 20 MB"}]), "{m}");+ }+ let list = checkpoints(&e, &ids[0]).await;+ let kinds: Vec<&str> = list.iter().map(|c| c["kind"].as_str().unwrap()).collect();+ assert_eq!(kinds, ["before_run", "manual", "manual"], "keep 2, plus the task's first before_run: {list:?}");+ assert_eq!(id(&list[0]), first);+ assert!(events(&e, &ids[0], "checkpoint_pruned").await.len() >= 3);+ assert!(!blobs(&e).join("f".repeat(64)).exists(), "an orphan blob is removed");+ for (content, kept) in [("u0", true), ("u1", false), ("u2", false), ("u3", true), ("u4", true)] {+ assert_eq!(blobs(&e).join(sha(content.as_bytes())).exists(), kept, "blob of {content}");+ }+ assert!(!blobs(&e).join(sha(&vec![0u8; 25 * 1024 * 1024])).exists(), "the big file was never stored");+ let (s, v) = call(&e.app, "POST", "/api/settings", None, Some(json!({"checkpoint_keep": 0}))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");+}++// 7+#[tokio::test]+async fn no_route_returns_manifest_or_blob_paths_or_file_contents() {+ let e = setup().await;+ let (mid, ids) = mission(&e, &e.bot.id, json!([{"title": "A", "owner": e.bot.id}])).await;+ let dir = folder(&e, &mid).await;+ std::fs::write(dir.join(".env"), "API_KEY=SECRET-CONTENT-4242").unwrap();+ std::fs::write(dir.join("key.pem"), "-----BEGIN PRIVATE KEY----- PEM-CONTENT-4242").unwrap();+ run(&e, &mid, &ids[0], &[("a.txt", Some("BODY-CONTENT-4242"))]).await;+ let tid = &ids[0];+ let created = person(&e, "POST", &format!("/api/tasks/{tid}/checkpoints"), None).await;+ let list = checkpoints(&e, tid).await;+ let cid = id(of_kind(&list, "before_run")[0]);+ let p = preview(&e, tid, &cid).await;+ let (_, r, _) = restore(&e, tid, &cid, "k-leak", &p["preview_sha256"]).await;+ let mut seen = vec![created, json!(list), p, r, task(&e, tid).await, checkpoints(&e, tid).await.into()];+ for uri in [format!("/api/missions/{mid}"), format!("/api/missions/{mid}/graph"), "/api/missions".into(), "/api/settings".into()] {+ seen.push(person(&e, "GET", &uri, None).await);+ }+ // The snapshot holds the secrets (it must), under a 0700 folder+ let root = e.state.config.data_dir.join("checkpoints");+ assert_eq!(std::fs::metadata(&root).unwrap().permissions().mode() & 0o777, 0o700);+ assert!(blobs(&e).join(sha(b"API_KEY=SECRET-CONTENT-4242")).exists());+ let root_s = root.display().to_string();+ for v in seen {+ let s = v.to_string();+ for bad in ["manifest", "blobs", root_s.as_str(), "SECRET-CONTENT-4242", "PEM-CONTENT-4242", "BODY-CONTENT-4242"] {+ assert!(!s.contains(bad), "{bad} leaked in {s}");+ }+ }+}++// 8+#[tokio::test]+async fn a_bot_token_cant_checkpoint_restore_or_fork() {+ let e = setup().await;+ let (mid, ids) = mission(&e, &e.bot.id, json!([{"title": "A", "owner": e.bot.id}])).await;+ run(&e, &mid, &ids[0], &[("a.txt", Some("v1"))]).await;+ let tid = &ids[0];+ let cid = id(of_kind(&checkpoints(&e, tid).await, "before_run")[0]);+ let token = turn(&e, &e.bot, "t-bot").await;+ let (s, _) = call(&e.app, "POST", &format!("/api/tasks/{tid}/checkpoints"), Some(&token), None).await;+ assert_eq!(s, StatusCode::FORBIDDEN);+ let uri = format!("/api/tasks/{tid}/checkpoints/{cid}/restore");+ let (s, _, _) = send(&e.app, "POST", &uri, Some(&token), Some("k-bot"), Some(json!({"preview_sha256": "x"}))).await;+ assert_eq!(s, StatusCode::FORBIDDEN);+ let (s, _, _) = send(&e.app, "POST", &format!("/api/tasks/{tid}/fork"), Some(&token), Some("k-bot-fork"), Some(json!({"from_checkpoint": cid}))).await;+ assert_eq!(s, StatusCode::FORBIDDEN);+ assert_eq!(checkpoints(&e, tid).await.len(), 2, "nothing was taken");+}++// 9+#[tokio::test]+async fn an_unreadable_folder_fails_the_checkpoint_but_not_the_turn() {+ let e = setup().await;+ let ann = cli_bot(&e).await;+ let (mid, ids) = mission(&e, &ann, json!([{"title": "A", "owner": ann}])).await;+ let dir = folder(&e, &mid).await;+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o300)).unwrap();+ if std::fs::read_dir(&dir).is_ok() {+ // Running as root: permissions don't stop reads, so there is nothing to test+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();+ eprintln!("skipped: the folder stays readable (root?)");+ return;+ }+ let tid = &ids[0];+ cli_run(&e, &mid, tid).await;+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();+ assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "changed", "the turn still ran");+ assert!(!events(&e, tid, "checkpoint_failed").await.is_empty());+ let list = checkpoints(&e, tid).await;+ assert!(!list.is_empty());+ for c in &list {+ assert_eq!(c["restorable"], false, "{c}");+ assert!(c["error"].is_string(), "{c}");+ }+ let cid = id(&list[0]);+ let (s, v) = call(&e.app, "GET", &format!("/api/tasks/{tid}/checkpoints/{cid}/restore-preview"), None, None).await;+ assert_eq!((s, v["code"].as_str()), (StatusCode::CONFLICT, Some("not_restorable")), "{v}");+}++// B1 gap: a retry with the same Idempotency-Key happens once+#[tokio::test]+async fn an_idempotency_key_retries_once() {+ let e = setup().await;+ let (_mid, ids) = mission(&e, &e.bot.id, json!([{"title": "A", "owner": e.bot.id}])).await;+ let tid = &ids[0];+ let token = turn(&e, &e.bot, "t-fail").await;+ ok(&e, &token, "task_claim", json!({"task_id": tid})).await;+ ok(&e, &token, "task_update", json!({"task_id": tid, "status": "failed", "note": "can't"})).await;+ assert_eq!(state_of(&e, tid).await, "failed");+ let uri = format!("/api/tasks/{tid}/retry");+ let (s1, first, r1) = send(&e.app, "POST", &uri, None, Some("retry-1"), None).await;+ let (s2, second, r2) = send(&e.app, "POST", &uri, None, Some("retry-1"), None).await;+ assert!(s1.is_success() && s2.is_success(), "{first} {second}");+ assert!(!r1 && r2, "the second call is a replay");+ assert_eq!(first, second);+ assert_eq!(state_of(&e, tid).await, "ready");+ let t = task(&e, tid).await;+ let retries = t["events"].as_array().unwrap().iter().filter(|ev| ev["from_state"] == "failed" && ev["to_state"] == "ready").count();+ assert_eq!(retries, 1, "one retry for one key: {t}");+ // Without a key a second retry is a real one, refused: the task isn't failed any more+ let (s3, _, _) = send(&e.app, "POST", &uri, None, None, None).await;+ assert!(!s3.is_success());+}++/// The owner verifies a task by `a.txt`; returns the mission and task id.+async fn verified(e: &Env) -> (String, String) {+ let plan = json!([{"title": "A", "owner": e.bot.id, "checks": [{"kind": "file_exists", "spec": {"path": "a.txt"}}]}]);+ let (mid, ids) = mission(e, &e.bot.id, plan).await;+ std::fs::write(folder(e, &mid).await.join("a.txt"), "a v1").unwrap();+ let token = turn(e, &e.bot, "t-verify").await;+ ok(e, &token, "task_claim", json!({"task_id": ids[0]})).await;+ ok(e, &token, "task_attach_evidence", json!({"task_id": ids[0], "kind": "file", "label": "a", "path": "a.txt"})).await;+ ok(e, &token, "task_update", json!({"task_id": ids[0], "status": "review"})).await;+ assert_eq!(state_of(e, &ids[0]).await, "verified");+ (mid, ids[0].clone())+}++fn evidence(e: &Env, tid: &str, path: &str, sha256: String) -> kwnt::db::missions::NewEvidence {+ kwnt::db::missions::NewEvidence {+ task_id: tid.into(),+ kind: "file".into(),+ label: path.into(),+ path: Some(path.into()),+ sha256: Some(sha256),+ captured_by: e.bot.id.clone(),+ ..Default::default()+ }+}++// B1 gap: the drift scan hashes at most 200 files and skips files over 50 MB+#[tokio::test]+async fn the_scan_stops_at_200_files_and_skips_files_over_50_mb() {+ let e = setup().await;+ let (mid, tid) = verified(&e).await;+ let dir = folder(&e, &mid).await;+ for n in 0..200 {+ let p = format!("f{n:03}.txt");+ std::fs::write(dir.join(&p), "same").unwrap();+ e.state.db.add_evidence(&evidence(&e, &tid, &p, sha(b"same"))).await.unwrap();+ }+ let r = person(&e, "POST", &format!("/api/missions/{mid}/graph/scan"), None).await;+ assert_eq!(r["scanned"], 200, "{r}");+ assert_eq!(r["flagged"], json!([]), "{r}");+ let skipped = r["skipped"].as_array().unwrap();+ assert_eq!(skipped.len(), 1, "{r}");+ assert_eq!(skipped[0]["why"], "over the 200-file scan limit", "{r}");++ let e = setup().await;+ let (mid, tid) = verified(&e).await;+ let big = folder(&e, &mid).await.join("big.bin");+ std::fs::File::create(&big).unwrap().set_len(51 * 1024 * 1024).unwrap();+ e.state.db.add_evidence(&evidence(&e, &tid, "big.bin", "0".repeat(64))).await.unwrap();+ let r = person(&e, "POST", &format!("/api/missions/{mid}/graph/scan"), None).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(), 1, "{r}");+ assert_eq!((skipped[0]["path"].as_str(), skipped[0]["why"].as_str()), (Some("big.bin"), Some("over 50 MB")), "{r}");+ assert_eq!(Path::new(&big).metadata().unwrap().len(), 51 * 1024 * 1024);+}