Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Mission Control: one fork for racing keyless redos; refuse unlisted force_paths

Lin (kwant bot)434e500c75ef
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c409de2e..6fe5ca2d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -65,6 +65,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
check and records whether it passed or failed, with its output. The task stays Verified either way
and its spend doesn't change. Before, the check was only approved and never ran.
+### Fixed
+- **Mission Control: racing Redo requests make one copy, and restore refuses unknown forced paths.**
+ Two Redo requests on the same flag at the same moment, without an `Idempotency-Key`, could each make
+ a copy; now the flag is claimed in the same step as the copy, so one wins and the rest get 409. A
+ restore whose `force_paths` names a path the preview doesn't list is now refused with 422 naming the
+ path, instead of being ignored.
+
## [Mac 0.1.3] - 2026-10-26
### Added
diff --git a/docs/mission-control.md b/docs/mission-control.md
index 87ae5ebf..a7fccf03 100644
--- a/docs/mission-control.md
+++ b/docs/mission-control.md
@@ -352,7 +352,7 @@ Bots have no tool to resolve a flag (D1).
| `cancelled` | A verified task gets 409. A cancelled task just has the flag closed. Any other task is cancelled. |
Other responses:
-- 409 when the flag is already resolved.
+- 409 when the flag is already resolved. A Verified task's redo claims the flag in the same transaction as the fork, so of several simultaneous redos (with or without a key) one forks and the rest get 409 with no copy.
- 404 when the flag belongs to another task.
- Success returns `{flag, task, fork|null}`.
@@ -434,6 +434,7 @@ 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.
+ - 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}`.
diff --git a/src/db/mission_graph.rs b/src/db/mission_graph.rs
index b53d3a4b..b618338c 100644
--- a/src/db/mission_graph.rs
+++ b/src/db/mission_graph.rs
@@ -168,21 +168,9 @@ impl Database {
/// Closes an open flag as the person. False when it was already resolved.
pub async fn resolve_flag(&self, id: &str, resolution: &str, note: Option<&str>, detail: Option<&Value>) -> Result<bool, DbError> {
let mut tx = self.pool.begin().await?;
- let r = sqlx::query("UPDATE task_flags SET resolved_at = ?, resolved_by = 'person', resolution = ? WHERE id = ? AND resolved_at IS NULL")
- .bind(Utc::now())
- .bind(resolution)
- .bind(id)
- .execute(&mut *tx)
- .await?;
- if r.rows_affected() == 0 {
+ if !claim_flag(&mut tx, &FlagClaim { id, resolution, note }, detail).await? {
return Ok(false);
}
- let (task_id,): (String,) = sqlx::query_as("SELECT task_id FROM task_flags WHERE id = ?").bind(id).fetch_one(&mut *tx).await?;
- let mut event = serde_json::json!({"flag_id": id, "resolution": resolution, "note": note});
- if let (Some(obj), Some(Value::Object(more))) = (event.as_object_mut(), detail) {
- obj.extend(more.clone());
- }
- insert_event(&mut tx, &task_id, None, "flag_resolved", "person", None, None, &event).await?;
tx.commit().await?;
Ok(true)
}
@@ -270,15 +258,24 @@ impl Database {
/// attempts, suggested to the original owner, the same dependencies, and the same checks reset
/// to pending (approval carries over only when the person or the approved plan gave it). The
/// original is untouched. Logs `forked` on the original and `created` on the fork.
- pub async fn fork_task(&self, orig: &Task, reason: &str) -> Result<Task, DbError> {
+ ///
+ /// With `claim`, the flag is resolved in the same transaction, before anything is written:
+ /// `None` when it was already resolved, and then there is no fork.
+ pub async fn fork_task(&self, orig: &Task, reason: &str, claim: Option<&FlagClaim<'_>>) -> Result<Option<Task>, DbError> {
let now = Utc::now();
let mut tx = self.pool.begin().await?;
+ let fork_id = Uuid::new_v4().to_string();
+ if let Some(c) = claim {
+ if !claim_flag(&mut tx, c, Some(&serde_json::json!({"fork_id": fork_id}))).await? {
+ return Ok(None);
+ }
+ }
let fork = sqlx::query_as::<_, Task>(
"INSERT INTO tasks (id, space_id, mission_id, title, acceptance, state, priority, suggested_kwant_id, budget_tokens, max_attempts, \
source_kind, source_id, channel_id, direct_kwant_id, thread_id, created_by, created_at, updated_at, forked_from) \
VALUES (?, ?, ?, ?, ?, 'backlog', ?, ?, ?, ?, ?, NULL, ?, ?, ?, 'person', ?, ?, ?) RETURNING *",
)
- .bind(Uuid::new_v4().to_string())
+ .bind(&fork_id)
.bind(&orig.space_id)
.bind(&orig.mission_id)
.bind(&orig.title)
@@ -337,7 +334,7 @@ impl Database {
)
.await?;
tx.commit().await?;
- Ok(fork)
+ Ok(Some(fork))
}
/// Forks of `task_id`, newest first.
@@ -367,3 +364,31 @@ impl Database {
Ok(())
}
}
+
+/// The person resolving one flag.
+pub struct FlagClaim<'a> {
+ pub id: &'a str,
+ pub resolution: &'a str,
+ pub note: Option<&'a str>,
+}
+
+/// Resolves the flag inside `tx` if it is still open, and logs `flag_resolved` with `detail`
+/// merged in. False when it was already resolved; nothing is written then.
+async fn claim_flag(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, c: &FlagClaim<'_>, detail: Option<&Value>) -> Result<bool, DbError> {
+ let r = sqlx::query("UPDATE task_flags SET resolved_at = ?, resolved_by = 'person', resolution = ? WHERE id = ? AND resolved_at IS NULL")
+ .bind(Utc::now())
+ .bind(c.resolution)
+ .bind(c.id)
+ .execute(&mut **tx)
+ .await?;
+ if r.rows_affected() == 0 {
+ return Ok(false);
+ }
+ let (task_id,): (String,) = sqlx::query_as("SELECT task_id FROM task_flags WHERE id = ?").bind(c.id).fetch_one(&mut **tx).await?;
+ let mut event = serde_json::json!({"flag_id": c.id, "resolution": c.resolution, "note": c.note});
+ if let (Some(obj), Some(Value::Object(more))) = (event.as_object_mut(), detail) {
+ obj.extend(more.clone());
+ }
+ insert_event(tx, &task_id, None, "flag_resolved", "person", None, None, &event).await?;
+ Ok(true)
+}
diff --git a/src/server/missions/checkpoints.rs b/src/server/missions/checkpoints.rs
index 04ab07a5..74c3968d 100644
--- a/src/server/missions/checkpoints.rs
+++ b/src/server/missions/checkpoints.rs
@@ -975,6 +975,14 @@ pub async fn preview(State(state): State<AppState>, RawQuery(q): RawQuery, Path(
}
}
+/// `force_paths` entries the preview lists neither as a change nor as a conflict.
+fn unlisted_force_paths<'a>(p: &Plan, force: &'a [String]) -> Vec<&'a str> {
+ let listed: BTreeSet<&str> = p.changes.iter().map(|c| c.path.as_str()).chain(p.conflicts.iter().filter_map(|c| c["path"].as_str())).collect();
+ let mut out: Vec<&str> = force.iter().map(String::as_str).filter(|f| !listed.contains(f)).collect();
+ out.dedup();
+ out
+}
+
#[derive(Deserialize)]
pub struct RestoreBody {
preview_sha256: String,
@@ -1008,6 +1016,11 @@ pub async fn restore(
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 unknown = unlisted_force_paths(&p, &b.force_paths);
+ if !unknown.is_empty() {
+ let msg = format!("force_paths names a path the preview doesn't list: {}", unknown.join(", "));
+ 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?;
let mut t = state.db.get_task(&task.id).await.map_err(internal)?.unwrap_or(task.clone());
if let Some(to) = p.state_after {
diff --git a/src/server/missions/graph.rs b/src/server/missions/graph.rs
index a85656bc..31d698e3 100644
--- a/src/server/missions/graph.rs
+++ b/src/server/missions/graph.rs
@@ -6,7 +6,7 @@
use super::checks::{hex, inside};
use super::routes::{bad, conflict, internal, load_mission, load_task, moved, not_found};
use super::{emit_mission, emit_task, emit_task_id, name_of, post_line, task_folder, task_json, transition, Actor};
-use crate::db::mission_graph::{GraphScan, TaskFlag, FLAG_RESOLUTIONS};
+use crate::db::mission_graph::{FlagClaim, GraphScan, TaskFlag, FLAG_RESOLUTIONS};
use crate::db::missions::{Mission, Task, TaskChange};
use crate::server::spaces::Scope;
use crate::server::AppState;
@@ -222,7 +222,9 @@ pub async fn scan_if_due(state: &AppState, mission: &Mission) {
/// Forks `orig` to redo it (see `Database::fork_task`). A done mission opens again so the fork
/// runs; a cancelled one refuses. Forking a verified task flags its started direct dependents
/// (`upstream_forked`); they keep depending on the original until the person decides.
-pub async fn fork(state: &AppState, orig: &Task, reason: &str) -> Result<Task, Response> {
+/// With `claim`, the flag is resolved in the fork's own transaction: a flag that is already
+/// resolved is a 409 and makes no fork, so racing redos make one copy.
+pub async fn fork(state: &AppState, orig: &Task, reason: &str, claim: Option<&FlagClaim<'_>>) -> Result<Task, Response> {
if let Some(mid) = &orig.mission_id {
let m = match state.db.get_mission(mid).await {
Ok(Some(m)) => m,
@@ -237,7 +239,11 @@ pub async fn fork(state: &AppState, orig: &Task, reason: &str) -> Result<Task, R
_ => {}
}
}
- let f = state.db.fork_task(orig, reason).await.map_err(internal)?;
+ let f = match state.db.fork_task(orig, reason, claim).await {
+ Ok(Some(f)) => f,
+ Ok(None) => return Err(conflict("this flag is already resolved")),
+ Err(e) => return Err(internal(e)),
+ };
if orig.state == "verified" {
let detail = json!({"fork_id": f.id, "reason": reason});
for dep in state.db.started_dependents(&orig.id).await.unwrap_or_default() {
@@ -317,7 +323,7 @@ pub async fn fork_task(State(state): State<AppState>, RawQuery(q): RawQuery, hea
Some(cid) => Some(super::checkpoints::restore_for_fork(&state, &orig, cid).await?),
None => None,
};
- let f = fork(&state, &orig, &reason).await?;
+ let f = fork(&state, &orig, &reason, None).await?;
let mut out = task_json(&state, &f).await;
if let Some(r) = restore {
out["restore"] = r;
@@ -358,16 +364,15 @@ pub async fn resolve_flag(
return Err(conflict("this flag is already resolved"));
}
let mut fork_out = None;
- let mut extra = json!({});
match (p.resolution.as_str(), t.state.as_str()) {
("still_valid", _) => {}
("redo", "working" | "needs_you") => return Err(conflict("it's running; resolve when it stops")),
("redo", "cancelled") => return Err(conflict("the task is cancelled; fork it to redo it")),
("redo", "verified") => {
let reason = note.clone().unwrap_or_else(|| "redo: it may no longer hold".into());
- let f = fork(&state, &t, &reason).await?;
- extra = json!({"fork_id": f.id});
- fork_out = Some(f);
+ // The fork claims the flag first, in its own transaction
+ let claim = FlagClaim { id: &flag.id, resolution: &p.resolution, note: note.as_deref() };
+ fork_out = Some(fork(&state, &t, &reason, Some(&claim)).await?);
}
("redo", from @ ("review" | "failed")) => {
let change = TaskChange { reason: Some("redo: it may no longer hold".into()), detail: Some(json!({"flag_id": flag.id})), ..Default::default() };
@@ -389,10 +394,12 @@ pub async fn resolve_flag(
}
_ => return Err(bad("resolution must be still_valid, redo or cancelled")),
}
- match state.db.resolve_flag(&flag.id, &p.resolution, note.as_deref(), Some(&extra)).await {
- Ok(true) => {}
- Ok(false) => return Err(conflict("this flag is already resolved")),
- Err(e) => return Err(internal(e)),
+ if fork_out.is_none() {
+ match state.db.resolve_flag(&flag.id, &p.resolution, note.as_deref(), None).await {
+ Ok(true) => {}
+ Ok(false) => return Err(conflict("this flag is already resolved")),
+ Err(e) => return Err(internal(e)),
+ }
}
let t = state.db.get_task(&t.id).await.ok().flatten().unwrap_or(t);
emit_task(&state, &t).await;
diff --git a/tests/mission_checkpoints_test.rs b/tests/mission_checkpoints_test.rs
index d936e7e9..d6d60d06 100644
--- a/tests/mission_checkpoints_test.rs
+++ b/tests/mission_checkpoints_test.rs
@@ -346,6 +346,33 @@ async fn a_restore_brings_back_the_tasks_files_and_can_itself_be_undone() {
assert_eq!(std::fs::read(dir.join("keep.txt")).unwrap(), keep_before);
}
+#[tokio::test]
+async fn a_force_path_the_preview_does_not_list_is_refused_and_writes_nothing() {
+ 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;
+ assert_eq!(p["changes"], json!([{"path": "a.txt", "action": "overwrite"}]), "{p}");
+ let uri = format!("/api/tasks/{tid}/checkpoints/{cid}/restore");
+ let body = |force: Value| Some(json!({"preview_sha256": p["preview_sha256"], "force_paths": force}));
+
+ // keep.txt is in the folder but not in the preview; nope.txt is nowhere
+ let (s, r, _) = send(&e.app, "POST", &uri, None, Some("force-1"), body(json!(["a.txt", "keep.txt", "nope.txt"]))).await;
+ assert_eq!(s, StatusCode::UNPROCESSABLE_ENTITY, "{r}");
+ assert_eq!(r["code"], "unknown_force_path", "{r}");
+ let msg = r["error"].as_str().unwrap();
+ assert!(msg.contains("keep.txt") && msg.contains("nope.txt") && !msg.contains("a.txt"), "{r}");
+ assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "changed", "nothing is written");
+ assert!(of_kind(&checkpoints(&e, &tid).await, "before_restore").is_empty(), "no safety checkpoint either");
+ assert!(events(&e, &tid, "restored").await.is_empty());
+
+ // The refusal isn't stored under the key: the same key with a listed path restores
+ let (s, r, replayed) = send(&e.app, "POST", &uri, None, Some("force-1"), body(json!(["a.txt"]))).await;
+ assert_eq!(s, StatusCode::OK, "{r}");
+ assert!(!replayed);
+ assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "original");
+}
+
// 3
#[tokio::test]
async fn a_verified_task_forks_instead_and_a_running_one_is_refused() {
diff --git a/tests/mission_graph_test.rs b/tests/mission_graph_test.rs
index 439ce175..7df904cd 100644
--- a/tests/mission_graph_test.rs
+++ b/tests/mission_graph_test.rs
@@ -530,6 +530,45 @@ async fn an_idempotency_key_resolves_a_redo_once_and_belongs_to_one_flag() {
assert_eq!(e.state.db.forks_of(&ids[1]).await.unwrap().len(), 1);
}
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn racing_keyless_redos_make_one_fork_and_the_rest_are_409() {
+ let e = setup().await;
+ let (mid, ids) = graph_mission(&e, &[("a", &[])]).await;
+ do_task(&e, &mid, &ids[0], "a").await;
+ drift(&e, &mid, "a").await;
+ scan(&e, &mid).await;
+ let fa = id(&flags(&task(&e, &ids[0]).await)[0]);
+ let uri = format!("/api/tasks/{}/flags/{fa}/resolve", ids[0]);
+
+ // Eight Redo requests at once, none with an Idempotency-Key
+ let sends = (0..8).map(|_| {
+ let (app, uri) = (e.app.clone(), uri.clone());
+ tokio::spawn(async move {
+ let req = Request::builder().method("POST").uri(uri).header("content-type", "application/json");
+ let resp = app.oneshot(req.body(Body::from(json!({"resolution": "redo"}).to_string())).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice::<Value>(&bytes).unwrap_or(Value::Null))
+ })
+ });
+ let replies: Vec<(StatusCode, Value)> = futures::future::join_all(sends).await.into_iter().map(Result::unwrap).collect();
+ let won: Vec<&Value> = replies.iter().filter(|(s, _)| s.is_success()).map(|(_, v)| v).collect();
+ assert_eq!(won.len(), 1, "{replies:?}");
+ assert!(replies.iter().all(|(s, _)| s.is_success() || *s == StatusCode::CONFLICT), "{replies:?}");
+ let forks = e.state.db.forks_of(&ids[0]).await.unwrap();
+ assert_eq!(forks.len(), 1, "a loser makes no copy: {replies:?}");
+ assert_eq!(won[0]["fork"]["id"], forks[0].id.as_str());
+
+ // One flag_resolved event, naming that fork; the original is still verified
+ let events = e.state.db.task_events(&ids[0], 100).await.unwrap();
+ let resolved: Vec<Value> = events.iter().filter(|ev| ev.kind == "flag_resolved").map(|ev| ev.detail_value()).collect();
+ assert_eq!(resolved.len(), 1, "{resolved:?}");
+ assert_eq!(resolved[0]["fork_id"], forks[0].id.as_str());
+ assert_eq!(resolved[0]["resolution"], "redo");
+ assert_eq!(events.iter().filter(|ev| ev.kind == "forked").count(), 1);
+ assert_eq!(state_of(&e, &ids[0]).await, "verified");
+}
+
// 10
#[tokio::test]
async fn a_scan_reads_nothing_outside_the_task_folder() {