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: a restore holds the task; conflicts name a task only on proof
Lin (kwant bot)c460b450a18b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6fe5ca2d..d304f2ec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -41,6 +41,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).and blocked work. Turn it on in Settings → Mission board. It works on phone and desktop.### Changed+- **Mission Control: a restore no longer starts the task again by itself.** A restored task that could+ run waits until you press Run; "restore and run again" keeps the old behaviour. A restore conflict+ names another task only when that task's own file edits wrote the file; otherwise it says "changed+ outside this task".- **An optional check never shows as needing you.** While a required check is still running, anoptional check waiting for your OK no longer counts in "Needs you now" or shows the amber "Waitingfor you" block on the receipt. You can still allow it from its row.diff --git a/docs/mission-control.md b/docs/mission-control.mdindex a7fccf03..d3ff3745 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -422,7 +422,7 @@ it is listed as "not undone".### 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`.+- `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`, and server-only `path` (for a `workspace` file call: the file it names, relative to the task folder; D11).- 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).@@ -434,12 +434,14 @@ it is listed as "not undone".- `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.+ - Conflict attribution (D11): `changed_by_task` names a task only when that task's own logged file calls (Write/Edit/MultiEdit/NotebookEdit, `turn_tool_calls.path`) wrote the path during a run after the checkpoint. A path that merely changed while another task ran in the same folder (a shell command, or anyone) is `{path, changed_by_task: null, why: "changed outside this task"}`, unless this task's own calls wrote it and it is still as this task's last run left it.- Every `force_paths` entry must be listed by the preview (in `changes` or `conflicts`); otherwise 422 `unknown_force_path` naming the paths, and nothing is written.- `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}`.+- `POST /api/tasks/:id/checkpoints/:cid/restore` (person only, `Idempotency-Key` required): body `{preview_sha256, force_paths?: [path], rerun?: bool}`. 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.+ - A restore never re-runs a task by itself (D10). When the task ends up ready or backlog it is held (`held_at` set, `held` task event): neither the runner nor a bot's `task_claim` takes it until the person calls `POST /api/tasks/:id/run` (person only; 409 `not_held` when it isn't held; `released` task event). `rerun: true` ("restore and run again") leaves it unheld, or lets go of an earlier hold.- 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`.+- `task_json` gains `checkpoint_count`, `last_checkpoint_at` and `held_at` (null unless a restore holds the task).diff --git a/frontend/src/missions.ts b/frontend/src/missions.tsindex dc2317ab..e15dd37a 100644--- a/frontend/src/missions.ts+++ b/frontend/src/missions.ts@@ -100,6 +100,9 @@ export interface Task {checks_summary: ChecksSummary;/** The task this one redoes (a fork); older servers leave it out. */forked_from?: string | null;+ /** Set when a restore held the task: nothing claims it until `POST /api/tasks/:id/run`+ * (the person's Run). Older servers leave it out. */+ held_at?: 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. */@@ -146,8 +149,10 @@ export interface RestorePreview {/** 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 }[];+ /** Changed since the checkpoint by someone else: skipped unless named in `force_paths`.+ * `changed_by_task` names a task only when that task's own file calls wrote the path;+ * otherwise it is null and `why` is "changed outside this task". */+ conflicts: { path: string; changed_by_task: string | null; why?: string }[];skipped: { path: string; why: string }[];external_not_undone: ExternalCall[];/** Always "kwant can't undo these. Check them yourself." */diff --git a/src/db/checkpoints.rs b/src/db/checkpoints.rsindex 2ea8968b..a00fb98d 100644--- a/src/db/checkpoints.rs+++ b/src/db/checkpoints.rs@@ -81,6 +81,9 @@ pub struct ToolCall {pub approval_id: Option<String>,pub idempotency_key: Option<String>,pub created_at: DateTime<Utc>,+ /// For a `workspace` file tool: the file it names, relative to the task's folder.+ /// Server-only; it proves which task wrote a path (D11).+ pub path: Option<String>,}const TRIGGERS: [&str; 3] = [@@ -134,6 +137,18 @@ impl Database {] {sqlx::query(stmt).execute(&self.pool).await?;}+ // The file a workspace call named came after the first ledgers+ let has_path: Option<(String,)> =+ sqlx::query_as("SELECT name FROM pragma_table_info('turn_tool_calls') WHERE name = 'path'").fetch_optional(&self.pool).await?;+ if has_path.is_none() {+ sqlx::query("ALTER TABLE turn_tool_calls ADD COLUMN path TEXT").execute(&self.pool).await?;+ }+ // A restore holds a task until the person runs it (D10)+ let has_held: Option<(String,)> =+ sqlx::query_as("SELECT name FROM pragma_table_info('tasks') WHERE name = 'held_at'").fetch_optional(&self.pool).await?;+ if has_held.is_none() {+ sqlx::query("ALTER TABLE tasks ADD COLUMN held_at TIMESTAMP").execute(&self.pool).await?;+ }for t in TRIGGERS {sqlx::query(t).execute(&self.pool).await?;}@@ -262,10 +277,11 @@ impl Database {summary: &str,decision: &str,approval_id: Option<&str>,+ path: 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 (?, ?, ?, ?, ?, ?, ?, ?, ?)",+ "INSERT INTO turn_tool_calls (turn_id, kwant_id, task_id, tool_name, effect, summary, decision, approval_id, created_at, path) \+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",).bind(turn_id).bind(kwant_id)@@ -276,11 +292,24 @@ impl Database {.bind(decision).bind(approval_id).bind(Utc::now())+ .bind(path).execute(&self.pool).await?;Ok(())}+ /// Holds `task_id` (a restore, D10) or lets it go; returns whether a hold changed.+ pub async fn set_task_hold(&self, task_id: &str, held: bool) -> Result<bool, DbError> {+ let r = if held {+ sqlx::query("UPDATE tasks SET held_at = ?, updated_at = ? WHERE id = ? AND held_at IS NULL").bind(Utc::now()).bind(Utc::now()).bind(task_id)+ } else {+ sqlx::query("UPDATE tasks SET held_at = NULL, updated_at = ? WHERE id = ? AND held_at IS NOT NULL").bind(Utc::now()).bind(task_id)+ }+ .execute(&self.pool)+ .await?;+ Ok(r.rows_affected() > 0)+ }+/// 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?)diff --git a/src/db/missions.rs b/src/db/missions.rsindex a148f9ad..dc1a8e7c 100644--- a/src/db/missions.rs+++ b/src/db/missions.rs@@ -71,6 +71,8 @@ pub struct Task {pub finished_at: Option<DateTime<Utc>>,/// The task this one redoes (a fork, Phase B1); `None` otherwise.pub forked_from: Option<String>,+ /// Set by a restore (D10): no claim until the person runs the task (`POST /api/tasks/:id/run`).+ pub held_at: Option<DateTime<Utc>>,}/// A lease on a task. Times are unix milliseconds so the SQLite triggers can compare them.@@ -237,6 +239,8 @@ pub enum ClaimRefused {Budget { remaining: i64, needed: i64 },MissionNotActive,Missing,+ /// A restore put the task on hold until the person runs it (D10)+ OnHold,}impl std::fmt::Display for ClaimRefused {@@ -250,6 +254,7 @@ impl std::fmt::Display for ClaimRefused {}ClaimRefused::MissionNotActive => write!(f, "the mission isn't approved and active"),ClaimRefused::Missing => write!(f, "no such task"),+ ClaimRefused::OnHold => write!(f, "the task was restored and waits for the person to run it"),}}}@@ -719,6 +724,9 @@ impl Database {let held = matches!(task.state.as_str(), "working" | "needs_you");return Ok(Err(if held { ClaimRefused::Held } else { ClaimRefused::NotReady(task.state) }));}+ if task.held_at.is_some() {+ return Ok(Err(ClaimRefused::OnHold));+ }let now = now_ms();if !system {let busy: Option<(String,)> = sqlx::query_as(diff --git a/src/mcp/builtin_tools.rs b/src/mcp/builtin_tools.rsindex 76e3e01e..ee545495 100644--- a/src/mcp/builtin_tools.rs+++ b/src/mcp/builtin_tools.rs@@ -405,6 +405,18 @@ pub fn is_inside(folder: &Path, path: &str) -> bool {}}+/// `path` (absolute, or relative to `folder`) relative to `folder`, judged like [`is_inside`];+/// `None` when it is outside or is the folder itself.+pub fn inside_rel(folder: &Path, path: &str) -> Option<String> {+ if path.starts_with('~') {+ return None;+ }+ let p = Path::new(path);+ let joined = if p.is_absolute() { p.to_path_buf() } else { folder.join(p) };+ let rel = resolve(&joined)?.strip_prefix(folder).ok()?.to_string_lossy().into_owned();+ (!rel.is_empty()).then_some(rel)+}+/// Follows symlinks through the existing part of `path` and appends the rest, refusing a `..`/// (or anything but a plain name) in the part that doesn't exist yet.fn resolve(path: &Path) -> Option<PathBuf> {diff --git a/src/server/auth.rs b/src/server/auth.rsindex 2e616a5a..501c5c48 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -848,6 +848,7 @@ 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/run"));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"));diff --git a/src/server/missions/checkpoints.rs b/src/server/missions/checkpoints.rsindex 74c3968d..a381c68b 100644--- a/src/server/missions/checkpoints.rs+++ b/src/server/missions/checkpoints.rs@@ -41,6 +41,8 @@ pub const MAX_FILES: usize = 20_000;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.";+/// A conflict no task's own calls account for (D11).+pub const OUTSIDE: &str = "changed outside this task";/// 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(());@@ -95,6 +97,8 @@ pub struct Skip {}/// One run of a task: the paths that differ between its `before_run` and `after_run`.+/// In a shared folder `paths` also holds what other tasks changed meanwhile; `touched` is+/// only what this run's own logged file calls named (D11: the proof that names a task).#[derive(Debug, Clone, Serialize, Deserialize)]struct Run {claim_id: Option<String>,@@ -102,6 +106,8 @@ struct Run {at: chrono::DateTime<chrono::Utc>,folder: String,paths: Vec<String>,+ #[serde(default)]+ touched: Vec<String>,}fn private_dir(dir: &FsPath) -> std::io::Result<()> {@@ -475,7 +481,23 @@ async fn note_run(state: &AppState, task: &Task, after: &Checkpoint, after_m: &Mafter_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 };+ // The run's own workspace calls since its before_run (all of the task's when there is none)+ let since = all.iter().rev().find(|c| c.kind == "before_run" && c.claim_id.is_some() && c.claim_id == after.claim_id).map(|c| c.created_at);+ let calls = state.db.tool_calls_of(&task.id).await.unwrap_or_default();+ let named: BTreeSet<&str> = calls+ .iter()+ .filter(|t| t.decision != "denied" && since.is_none_or(|s| t.created_at >= s) && t.created_at <= after.created_at)+ .filter_map(|t| t.path.as_deref())+ .collect();+ let touched = paths.iter().filter(|p| named.contains(p.as_str())).cloned().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,+ touched,+ };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");@@ -581,23 +603,35 @@ pub fn effect(req: &crate::mcp::ToolApprovalRequest, task_folder: Option<&FsPathreturn "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",- };+ let Some((folder, abs)) = file_target(req, task_folder) else { return "external" };return if crate::mcp::builtin_tools::is_inside(&folder, &abs.to_string_lossy()) { "workspace" } else { "external" };}"external"}+/// A file tool's canonical task folder and the absolute path it names (a relative path is the+/// bot's working folder's).+fn file_target(req: &crate::mcp::ToolApprovalRequest, task_folder: Option<&FsPath>) -> Option<(PathBuf, PathBuf)> {+ let path = ["file_path", "notebook_path", "path"].iter().find_map(|k| req.arguments[*k].as_str()).unwrap_or("");+ let folder = task_folder.and_then(|f| crate::mcp::builtin_tools::canonical_folder(Some(f)))?;+ if path.is_empty() {+ return None;+ }+ 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 None,+ };+ Some((folder, abs))+}++/// The task-folder-relative file a `workspace` call names, as the manifests spell it.+fn workspace_path(req: &crate::mcp::ToolApprovalRequest, task_folder: Option<&FsPath>) -> Option<String> {+ let (folder, abs) = file_target(req, task_folder)?;+ crate::mcp::builtin_tools::inside_rel(&folder, &abs.to_string_lossy()).filter(|r| safe_rel(r))+}+/// 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"];@@ -641,8 +675,9 @@ pub async fn log_call(db: &crate::db::Database, data_dir: &FsPath, req: &crate::_ => None,};let effect = effect(req, folder.as_deref());+ let path = if effect == "workspace" { workspace_path(req, folder.as_deref()) } else { None };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 {+ if let Err(e) = db.log_tool_call(&req.turn_id, &req.kwant_id, &task_id, &req.tool_name, effect, &summary, decision, approval_id, path.as_deref()).await {tracing::warn!(error = %e, "could not log a tool call");}}@@ -695,24 +730,38 @@ pub async fn plan(state: &AppState, task: &Task, c: &Checkpoint) -> Result<Plan,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();+ let mut own_touched = BTreeSet::new();for r in read_runs(&task_dir) {if r.folder == c.folder {owned.extend(r.paths);+ own_touched.extend(r.touched);}}+ // D11: a task is named only when its own logged calls wrote the path; a path that merely+ // changed while another task ran in the same folder is "changed outside this task"let mut others: BTreeMap<String, String> = BTreeMap::new();+ let mut outside = BTreeSet::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 {+ for p in r.touched {others.entry(p).or_insert_with(|| o.task_id.clone());}+ outside.extend(r.paths);}}}}+ // What this task's last run left: a path its own calls wrote, still as it left it, is its own+ let all = state.db.checkpoints_of(&task.id).await.map_err(|e| PlanError::Db(e.to_string()))?;+ let left: Option<BTreeMap<String, String>> = all+ .iter()+ .rev()+ .find(|x| x.kind == "after_run" && !x.failed() && x.folder == c.folder && x.created_at >= c.created_at)+ .and_then(read_manifest)+ .map(|m| m.files.into_iter().map(|e| (e.path, e.sha256)).collect());let mut skipped = Vec::new();let mut entries = BTreeMap::new();for e in &manifest.files {@@ -765,10 +814,14 @@ pub async fn plan(state: &AppState, task: &Task, c: &Checkpoint) -> Result<Plan,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));+ hashes.push((p.clone(), sha.clone()));+ let as_left = own_touched.contains(&p) && left.as_ref().is_some_and(|l| l.get(&p).map(String::as_str).unwrap_or("") == sha);if let Some(t) = others.get(&p) {conflicts.push(json!({"path": p, "changed_by_task": t}));forced.insert(p, action);+ } else if outside.contains(&p) && !as_left {+ conflicts.push(json!({"path": p, "changed_by_task": null, "why": OUTSIDE}));+ forced.insert(p, action);} else {changes.push(Change { path: p, action });}@@ -988,6 +1041,9 @@ pub struct RestoreBody {preview_sha256: String,#[serde(default)]force_paths: Vec<String>,+ /// "Restore and run again"; otherwise a task the runner could pick up is held (D10).+ #[serde(default)]+ rerun: bool,}/// `POST /api/tasks/:id/checkpoints/:cid/restore` (person-only, `Idempotency-Key` required).@@ -1022,6 +1078,13 @@ pub async fn restore(return Err(coded(StatusCode::UNPROCESSABLE_ENTITY, "unknown_force_path", &msg));}let mut out = write_back(&state, &task, &c, &p, b.force_paths.into_iter().collect()).await?;+ // Held before the move, so the runner never sees it ready and unheld (D10)+ let runnable = matches!(p.state_after.unwrap_or(task.state.as_str()), "ready" | "backlog");+ let changed = state.db.set_task_hold(&task.id, runnable && !b.rerun).await.map_err(internal)?;+ if changed {+ let kind = if b.rerun { "released" } else { "held" };+ state.db.task_event(&task.id, task.mission_id.as_deref(), kind, "person", &json!({"checkpoint_id": c.id})).await.map_err(internal)?;+ }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() };@@ -1035,6 +1098,24 @@ pub async fn restore(.await}+/// `POST /api/tasks/:id/run` (person-only): lets a task a restore held be claimed again (D10).+pub async fn run_held(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 state.db.set_task_hold(&task.id, false).await {+ Ok(true) => {+ let _ = state.db.task_event(&task.id, task.mission_id.as_deref(), "released", "person", &json!({})).await;+ }+ Ok(false) => return coded(StatusCode::CONFLICT, "not_held", "the task isn't on hold"),+ Err(e) => return internal(e),+ }+ let t = state.db.get_task(&task.id).await.ok().flatten().unwrap_or(task);+ emit_task(&state, &t).await;+ Json(json!({"task": task_json(&state, &t).await})).into_response()+}+/// 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)]diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rsindex 8a7eeefc..79ae26cf 100644--- a/src/server/missions/mod.rs+++ b/src/server/missions/mod.rs@@ -965,6 +965,7 @@ mod tests {updated_at: Utc::now(),finished_at: None,forked_from: None,+ held_at: None,}}diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rsindex 06b3b8ec..5d375cd1 100644--- a/src/server/missions/runner.rs+++ b/src/server/missions/runner.rs@@ -73,7 +73,7 @@ pub async fn run_mission(state: &AppState, mission: &Mission, max: usize) -> (Velet ready = state.db.list_tasks(&space, Some("ready"), Some(&mission.id), None, 100).await.unwrap_or_default();let mut picked: Vec<(Task, crate::db::models::Kwant)> = Vec::new();let mut reason = None;- for t in ready.iter().filter(|t| matches!(t.source_kind.as_str(), "mission" | "person")) {+ for t in ready.iter().filter(|t| matches!(t.source_kind.as_str(), "mission" | "person") && t.held_at.is_none()) {if picked.len() >= max {break;}diff --git a/src/server/mod.rs b/src/server/mod.rsindex 0b84c5f3..bed21b62 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -374,6 +374,7 @@ 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/run", post(missions::checkpoints::run_held)).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))diff --git a/tests/mission_checkpoints_test.rs b/tests/mission_checkpoints_test.rsindex 2ca0bb84..77d2b87c 100644--- a/tests/mission_checkpoints_test.rs+++ b/tests/mission_checkpoints_test.rs@@ -691,3 +691,125 @@ async fn the_scan_stops_at_200_files_and_skips_files_over_50_mb() {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);}++// D10+#[tokio::test]+async fn a_restore_holds_the_task_until_the_person_runs_it() {+ let e = setup().await;+ let (mid, tid, dir) = cli_mission(&e).await;+ let cid = id(of_kind(&checkpoints(&e, &tid).await, "before_run")[0]);+ let p = preview(&e, &tid, &cid).await;+ let (s, r, _) = restore(&e, &tid, &cid, "hold-1", &p["preview_sha256"]).await;+ assert_eq!(s, StatusCode::OK, "{r}");+ assert_eq!(r["task"]["state"], "ready", "{r}");+ assert!(r["task"]["held_at"].is_string(), "a restored task is held: {r}");+ assert_eq!(events(&e, &tid, "held").await.len(), 1);++ // The runner (tick and the Run button of the mission) leaves it alone+ kwnt::server::missions::runner::tick(&e.state).await;+ let run = person(&e, "POST", &format!("/api/missions/{mid}/run"), Some(json!({"max_tasks": 1}))).await;+ assert!(run["started"].as_array().unwrap().is_empty(), "{run}");+ assert!(e.state.db.open_claim(&tid).await.unwrap().is_none(), "a held task isn't claimed");+ assert_eq!(state_of(&e, &tid).await, "ready");+ // A bot can't claim it either+ let token = turn(&e, &e.bot, "t-held").await;+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "task_claim", "arguments": {"task_id": tid}}});+ let (_, v) = call(&e.app, "POST", "/api/mcp/self", Some(&token), Some(rpc)).await;+ assert!(v["result"]["isError"].as_bool().unwrap_or(false), "{v}");+ assert!(v["result"]["content"][0]["text"].as_str().unwrap().contains("waits for the person"), "{v}");++ // Undo works: the task never started, so no 409 running; it stays held+ let safety = r["before_restore_checkpoint_id"].as_str().unwrap().to_string();+ let p = preview(&e, &tid, &safety).await;+ assert!(p["refused"].is_null(), "{p}");+ let (s, r, _) = restore(&e, &tid, &safety, "hold-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!(r["task"]["held_at"].is_string(), "{r}");++ // The person's Run lets it go, once+ let r = person(&e, "POST", &format!("/api/tasks/{tid}/run"), None).await;+ assert!(r["task"]["held_at"].is_null(), "{r}");+ let (s, v) = call(&e.app, "POST", &format!("/api/tasks/{tid}/run"), None, None).await;+ assert_eq!((s, v["code"].as_str()), (StatusCode::CONFLICT, Some("not_held")), "{v}");+ assert_eq!(events(&e, &tid, "released").await.len(), 1);+ cli_run(&e, &mid, &tid).await;++ // "Restore and run again" doesn't hold it: the runner picks it up+ let cid = id(of_kind(&checkpoints(&e, &tid).await, "before_run").last().unwrap());+ let p = preview(&e, &tid, &cid).await;+ let uri = format!("/api/tasks/{tid}/checkpoints/{cid}/restore");+ let (s, r, _) = send(&e.app, "POST", &uri, None, Some("hold-3"), Some(json!({"preview_sha256": p["preview_sha256"], "rerun": true}))).await;+ assert_eq!(s, StatusCode::OK, "{r}");+ assert!(r["task"]["held_at"].is_null(), "{r}");+ cli_run(&e, &mid, &tid).await;+}++/// `bot` claims `tid` in its own turn; returns the turn id and token.+async fn claim_as(e: &Env, bot: &Kwant, tid: &str) -> (String, String) {+ let turn_id = format!("t-{tid}-{}", uuid::Uuid::new_v4());+ let token = turn(e, bot, &turn_id).await;+ ok(e, &token, "task_claim", json!({"task_id": tid})).await;+ (turn_id, token)+}++/// `bot` writes `rel` in `dir`, through a logged Write call when `logged` (else like a shell would).+async fn write_as(e: &Env, bot: &Kwant, turn_id: &str, dir: &Path, rel: &str, body: &str, logged: bool) {+ if logged {+ let req = kwnt::mcp::ToolApprovalRequest {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ turn_id: turn_id.into(),+ tool_name: "Write".into(),+ server: String::new(),+ tool: "Write".into(),+ arguments: json!({"file_path": rel, "content": body}),+ builtin: Some(kwnt::mcp::BuiltinCall { cwd: Some(dir.to_string_lossy().into_owned()), outside_folder: false }),+ smart: None,+ };+ kwnt::server::missions::checkpoints::log_call(&e.state.db, &e.state.config.data_dir, &req, "allowed", None).await;+ }+ std::fs::write(dir.join(rel), body).unwrap();+}++// D11+#[tokio::test]+async fn a_conflict_names_another_task_only_when_its_own_calls_wrote_the_path() {+ let e = setup().await;+ let bot = json!({"name": "Bea", "title": "Bea the builder", "persona_prompt": "Test persona",+ "avatar_sprite": "s", "driver_type": "cli", "preferred_model": "claude"});+ let bea: Kwant = e.state.db.get_kwant(&id(&person(&e, "POST", "/api/kwants", Some(bot)).await)).await.unwrap().unwrap();+ let me = e.bot.id.clone();+ let (mid, ids) = mission(&e, &me, json!([{"title": "A", "owner": me}, {"title": "B", "owner": bea.id}])).await;+ let (a, b) = (ids[0].clone(), ids[1].clone());+ let dir = folder(&e, &mid).await;+ std::fs::write(dir.join("seed.txt"), "seed").unwrap();+ // A and B run at the same time in one folder+ let (ta, ka) = claim_as(&e, &e.bot, &a).await;+ let (tb, kb) = claim_as(&e, &bea, &b).await;+ write_as(&e, &e.bot, &ta, &dir, "a.txt", "by A", true).await;+ write_as(&e, &bea, &tb, &dir, "b.txt", "by B", true).await;+ write_as(&e, &bea, &tb, &dir, "seed.txt", "by a shell", false).await;+ ok(&e, &ka, "task_update", json!({"task_id": a, "status": "review"})).await;+ ok(&e, &kb, "task_update", json!({"task_id": b, "status": "review"})).await;+ let calls = e.state.db.tool_calls_of(&a).await.unwrap();+ assert_eq!(calls.iter().filter_map(|c| c.path.as_deref()).collect::<Vec<_>>(), vec!["a.txt"], "{calls:?}");++ let conflict = |p: &Value, path: &str| p["conflicts"].as_array().unwrap().iter().find(|c| c["path"] == path).cloned();+ let change = |p: &Value, path: &str| p["changes"].as_array().unwrap().iter().any(|c| c["path"] == path);+ // Restoring B: a.txt is A's (A's own Write), seed.txt nobody's own call wrote+ let cb = id(of_kind(&checkpoints(&e, &b).await, "before_run")[0]);+ let pb = preview(&e, &b, &cb).await;+ assert_eq!(conflict(&pb, "a.txt").map(|c| c["changed_by_task"].clone()), Some(json!(a)), "{pb}");+ assert!(change(&pb, "b.txt"), "B's own file is a plain change: {pb}");+ let seed = conflict(&pb, "seed.txt").unwrap_or_else(|| panic!("{pb}"));+ assert!(seed["changed_by_task"].is_null() && seed["why"] == "changed outside this task", "{pb}");+ // Restoring A: b.txt is B's; a.txt, only A's own call wrote, is never shown as B's+ let ca = id(of_kind(&checkpoints(&e, &a).await, "before_run")[0]);+ let pa = preview(&e, &a, &ca).await;+ assert_eq!(conflict(&pa, "b.txt").map(|c| c["changed_by_task"].clone()), Some(json!(b)), "{pa}");+ assert!(change(&pa, "a.txt") && conflict(&pa, "a.txt").is_none(), "{pa}");+ assert!(conflict(&pa, "seed.txt").is_some_and(|c| c["changed_by_task"].is_null()), "{pa}");+ let named: Vec<&Value> = pa["conflicts"].as_array().unwrap().iter().chain(pb["conflicts"].as_array().unwrap()).filter(|c| !c["changed_by_task"].is_null()).collect();+ assert_eq!(named.len(), 2, "only proven writes name a task: {named:?}");+}