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
Repeat guard: a stopped call gets its tries again once something changed (22t) (#738)
Oleksandr Ivanchenkob44d9b7c9550
diff --git a/src/mcp/cli_hooks.rs b/src/mcp/cli_hooks.rsindex ff44be88..c93aae45 100644--- a/src/mcp/cli_hooks.rs+++ b/src/mcp/cli_hooks.rs@@ -8,7 +8,9 @@//! `permissionDecision: "deny"` with the same [`stop_text`](super::repeat_guard::stop_text) as//! kwnt's own tools (18a), so the model reads the same words. Claude runs PreToolUse before its//! permission check, so a stopped call never shows a card.-//! - `PostToolUse` (claude 2.1.325: a call that worked) clears the call.+//! - `PostToolUse` (claude 2.1.325: a call that worked) clears the call. 22t: when that call+//! changed something ([`changes_something`]: an edit, or a shell command that isn't stopped),+//! every stopped call gets its tries again ([`RepeatGuard::changed`]), so a fixed test runs.//! - `PostToolUseFailure` (a call that failed, with its `error` text, e.g. `"Exit code 1\n…"`)//! counts one more identical failure. A call claude or the person denied fires neither event.//!@@ -96,6 +98,17 @@ pub fn key(tool: &str, input: &Value) -> [u8; 32] {}}+/// 22t: claude's tools that write files. A read (Read, Grep, Glob, LS, WebFetch…) changes nothing.+pub const WRITE_TOOLS: [&str; 4] = ["Write", "Edit", "MultiEdit", "NotebookEdit"];++/// 22t: whether a call that worked may have changed what a stopped call would see: a file write,+/// or a shell command other than a stopped one (Rigel, #693 QA). A shell command can't be read+/// for its effect, so any other one counts; [`REPEAT_CEILING`](super::repeat_guard::REPEAT_CEILING)+/// still ends a loop.+pub fn changes_something(guard: &RepeatGuard, tool: &str, key: &[u8; 32]) -> bool {+ WRITE_TOOLS.contains(&tool) || (tool == "Bash" && guard.check(key).is_none())+}+/// What kwnt does with one hook payload. `Some` is the hook's stdout (a PreToolUse deny);/// `None` means no output, and claude goes on as usual.pub fn on_event(guard: &RepeatGuard, msg: &Value) -> Option<Value> {@@ -118,7 +131,11 @@ pub fn on_event(guard: &RepeatGuard, msg: &Value) -> Option<Value> {}))}"PostToolUse" => {+ let changed = changes_something(guard, tool, &k);guard.after(&k, "ok", "");+ if changed {+ guard.changed();+ }None}"PostToolUseFailure" => {@@ -136,7 +153,7 @@ pub fn on_event(guard: &RepeatGuard, msg: &Value) -> Option<Value> {#[cfg(test)]mod tests {use super::*;- use crate::mcp::repeat_guard::{STOP_PREFIX, REPEAT_LIMIT};+ use crate::mcp::repeat_guard::{stop_text, REPEAT_CEILING, REPEAT_LIMIT, STOP_PREFIX};// Shapes recorded from claude 2.1.325 (Nov 15), see autonomy/cli-tools-repeat-guard/impl.mdfn pre(tool: &str, input: Value) -> Value {@@ -234,6 +251,143 @@ mod tests {}}+ // ---- 22t: a stopped call gets its tries again once something changed ----++ const NPM_ERR: &str = "Exit code 1\nFAIL src/sum.test.js\n expected 3, received 4";++ fn npm(description: &str) -> Value {+ json!({"command": "npm test", "description": description})+ }++ /// `npm test` fails the same way 3 times; the 4th is denied.+ fn npm_fails_three_times(g: &RepeatGuard) {+ for i in 0..REPEAT_LIMIT {+ assert_eq!(on_event(g, &pre("Bash", npm("run tests"))), None, "npm test {} runs", i + 1);+ on_event(g, &failed("Bash", npm("run tests"), NPM_ERR));+ }+ assert!(on_event(g, &pre("Bash", npm("again"))).is_some(), "4th npm test denied");+ }++ #[test]+ fn a_an_edit_that_worked_lets_the_stopped_test_run_again() {+ let g = RepeatGuard::default();+ npm_fails_three_times(&g);+ let edit = json!({"file_path": "/w/src/sum.js", "old_string": "a + b + 1", "new_string": "a + b"});+ assert_eq!(on_event(&g, &pre("Edit", edit.clone())), None);+ on_event(&g, &worked("Edit", edit));+ assert_eq!(on_event(&g, &pre("Bash", npm("after the fix"))), None, "the 4th npm test runs after the edit");+ on_event(&g, &worked("Bash", npm("after the fix")));+ assert_eq!(on_event(&g, &pre("Bash", npm("once more"))), None);+ // Write, MultiEdit and NotebookEdit change files too+ for tool in ["Write", "MultiEdit", "NotebookEdit"] {+ let g = RepeatGuard::default();+ npm_fails_three_times(&g);+ on_event(&g, &worked(tool, json!({"file_path": "/w/x"})));+ assert_eq!(on_event(&g, &pre("Bash", npm("again"))), None, "{tool} reopens it");+ }+ // An edit that failed changed nothing+ let g = RepeatGuard::default();+ npm_fails_three_times(&g);+ on_event(&g, &failed("Edit", json!({"file_path": "/w/x"}), "String to replace not found in file."));+ assert!(on_event(&g, &pre("Bash", npm("again"))).is_some());+ }++ #[test]+ fn b_a_different_shell_command_that_worked_lets_it_run_again() {+ let g = RepeatGuard::default();+ npm_fails_three_times(&g);+ let sed = json!({"command": "sed -i 's/a + b + 1/a + b/' src/sum.js", "description": "fix the sum"});+ assert_eq!(on_event(&g, &pre("Bash", sed.clone())), None);+ on_event(&g, &worked("Bash", sed));+ assert_eq!(on_event(&g, &pre("Bash", npm("after sed"))), None, "the 4th npm test runs after sed");+ // A different shell command that failed changed nothing+ let g = RepeatGuard::default();+ npm_fails_three_times(&g);+ on_event(&g, &failed("Bash", json!({"command": "sed -i 's/x/y/' nope.js"}), "Exit code 2\nsed: can't read nope.js"));+ assert!(on_event(&g, &pre("Bash", npm("again"))).is_some());+ }++ #[test]+ fn c_a_read_does_not_reopen_it_but_a_later_edit_does() {+ let g = RepeatGuard::default();+ npm_fails_three_times(&g);+ for (tool, input) in [+ ("Read", json!({"file_path": "/w/src/sum.js"})),+ ("Grep", json!({"pattern": "a \\+ b", "path": "/w/src"})),+ ("Glob", json!({"pattern": "**/*.test.js"})),+ ("LS", json!({"path": "/w/src"})),+ ("WebFetch", json!({"url": "https://jestjs.io/docs/expect", "prompt": "toBe"})),+ ("TodoWrite", json!({"todos": [{"content": "fix sum", "status": "in_progress"}]})),+ ] {+ assert_eq!(on_event(&g, &pre(tool, input.clone())), None, "{tool} runs");+ on_event(&g, &worked(tool, input));+ let out = on_event(&g, &pre("Bash", npm("again"))).unwrap_or_else(|| panic!("{tool} reopened npm test"));+ assert_eq!(out["hookSpecificOutput"]["permissionDecisionReason"], stop_text(3, NPM_ERR));+ }+ // Then the bot really fixes the file+ on_event(&g, &worked("Edit", json!({"file_path": "/w/src/sum.js", "old_string": "+ 1", "new_string": ""})));+ assert_eq!(on_event(&g, &pre("Bash", npm("after the fix"))), None);+ }++ #[test]+ fn d_with_an_edit_between_every_failure_it_stops_at_the_turn_ceiling() {+ let g = RepeatGuard::default();+ for i in 1..=REPEAT_CEILING {+ assert_eq!(on_event(&g, &pre("Bash", npm(&format!("try {i}")))), None, "npm test {i} runs");+ on_event(&g, &failed("Bash", npm(&format!("try {i}")), NPM_ERR));+ on_event(&g, &worked("Edit", json!({"file_path": "/w/src/sum.js", "old_string": format!("v{i}"), "new_string": format!("v{}", i + 1)})));+ }+ let out = on_event(&g, &pre("Bash", npm("try 7"))).expect("the 7th npm test is denied");+ let reason = out["hookSpecificOutput"]["permissionDecisionReason"].as_str().unwrap();+ assert_eq!(reason, stop_text(REPEAT_CEILING, NPM_ERR));+ assert!(reason.contains("already failed 6 times in this turn"), "{reason}");+ // Neither an edit nor another shell command lifts the ceiling+ on_event(&g, &worked("Write", json!({"file_path": "/w/src/sum.js"})));+ on_event(&g, &worked("Bash", json!({"command": "git stash"})));+ assert!(on_event(&g, &pre("Bash", npm("try 8"))).is_some());+ // 3 in a row, an edit, 3 in a row: the 6th is the ceiling too+ let g = RepeatGuard::default();+ npm_fails_three_times(&g);+ on_event(&g, &worked("Edit", json!({"file_path": "/w/a"})));+ for i in 4..=6 {+ assert_eq!(on_event(&g, &pre("Bash", npm("t"))), None, "npm test {i} runs");+ on_event(&g, &failed("Bash", npm("t"), NPM_ERR));+ }+ on_event(&g, &worked("Edit", json!({"file_path": "/w/b"})));+ assert!(on_event(&g, &pre("Bash", npm("t"))).is_some(), "stopped after 6 in the turn");+ }++ #[test]+ fn e_a_different_error_still_starts_again_at_1() {+ let g = RepeatGuard::default();+ let edit = |i: u32| worked("Edit", json!({"file_path": "/w/src/sum.js", "old_string": format!("v{i}"), "new_string": "x"}));+ // 5 identical failures with edits between: under the ceiling, so each one ran+ for i in 1..REPEAT_CEILING {+ assert_eq!(on_event(&g, &pre("Bash", npm("t"))), None, "npm test {i} runs");+ on_event(&g, &failed("Bash", npm("t"), NPM_ERR));+ on_event(&g, &edit(i));+ }+ // The fix moved the failure on: a new error counts from 1, for both counts+ let other = "Exit code 1\nFAIL src/mul.test.js\n expected 6, received 5";+ for i in 1..REPEAT_CEILING {+ assert_eq!(on_event(&g, &pre("Bash", npm("t"))), None, "npm test with the new error {i} runs");+ on_event(&g, &failed("Bash", npm("t"), other));+ on_event(&g, &edit(10 + i));+ }+ on_event(&g, &failed("Bash", npm("t"), other));+ let out = on_event(&g, &pre("Bash", npm("t"))).expect("6 of the new error stop it");+ assert_eq!(out["hookSpecificOutput"]["permissionDecisionReason"], stop_text(6, other));+ // Without edits, the new error still stops at 3, as before+ let g = RepeatGuard::default();+ npm_fails_three_times(&g);+ on_event(&g, &edit(1));+ for _ in 0..REPEAT_LIMIT {+ on_event(&g, &failed("Bash", npm("t"), other));+ }+ let out = on_event(&g, &pre("Bash", npm("t"))).expect("3 of the new error in a row");+ assert_eq!(out["hookSpecificOutput"]["permissionDecisionReason"], stop_text(3, other));+ }+#[test]fn the_bash_description_is_not_part_of_the_call() {assert_eq!(key("Bash", &bash("a")), key("Bash", &bash("b")));diff --git a/src/mcp/repeat_guard.rs b/src/mcp/repeat_guard.rsindex 0f3d3e8e..a4775058 100644--- a/src/mcp/repeat_guard.rs+++ b/src/mcp/repeat_guard.rs@@ -6,6 +6,11 @@//! times the same way, so the turn tries another way instead of spending its call cap on it.//! Successful calls (polling a status) and calls whose error changes never stop. Only `ok` and//! `error` outcomes count: a denied, unanswered or rehearsed call was the person's decision.+//!+//! 22t: when another call changed something (an edit, another shell command), the earlier+//! failures may be stale, so [`RepeatGuard::changed`] gives every call its [`REPEAT_LIMIT`] tries+//! again: a test run that failed 3 times can run once the file is fixed. The turn still stops the+//! call after [`REPEAT_CEILING`] identical failures, whatever changed in between.use serde_json::Value;use sha2::{Digest, Sha256};@@ -13,6 +18,9 @@ use std::sync::Mutex;/// Identical failures after which the same call is no longer sent.pub const REPEAT_LIMIT: u32 = 3;+/// 22t: identical failures in one turn after which the call stops even when something changed in+/// between ([`RepeatGuard::changed`] doesn't lower this count), so edit/retry can't loop forever.+pub const REPEAT_CEILING: u32 = 2 * REPEAT_LIMIT;/// Calls the guard remembers per turn; the least recently failed one is dropped first.pub const MAX_KEYS: usize = 64;/// How much of the repeated error the stop text quotes.@@ -21,7 +29,10 @@ const QUOTE_MAX_CHARS: usize = 200;struct Entry {key: [u8; 32],error: String,+ /// Identical failures since the last change ([`RepeatGuard::changed`] sets it to 0).count: u32,+ /// Identical failures in the turn: only an `ok` or a different error resets it.+ turn: u32,}/// One turn's failing calls, oldest first. Interior mutability: calls may run concurrently.@@ -62,12 +73,23 @@ impl RepeatGuard {self.entries.lock().unwrap_or_else(|e| e.into_inner())}- /// `Some` when this call already failed [`REPEAT_LIMIT`] times in a row with the same error:- /// don't send it.+ /// `Some` when this call already failed [`REPEAT_LIMIT`] times in a row with the same error+ /// since the last change, or [`REPEAT_CEILING`] times in the turn: don't send it. The count+ /// (and the stop text's number) is the turn's.pub fn check(&self, key: &[u8; 32]) -> Option<Stopped> {let entries = self.lock();let e = entries.iter().find(|e| &e.key == key)?;- (e.count >= REPEAT_LIMIT).then(|| Stopped { text: stop_text(e.count, &e.error), count: e.count })+ (e.count >= REPEAT_LIMIT || e.turn >= REPEAT_CEILING).then(|| Stopped { text: stop_text(e.turn, &e.error), count: e.turn })+ }++ /// 22t: another call changed something (a file edit, a different shell command, a tool that+ /// isn't read-only), so every call that failed gets its [`REPEAT_LIMIT`] tries again. The+ /// error text and the turn's count stay: the same error after this counts on toward+ /// [`REPEAT_CEILING`].+ pub fn changed(&self) {+ for e in self.lock().iter_mut() {+ e.count = 0;+ }}/// Records a call's outcome: `error` with the same (redacted) text as last time counts one@@ -86,13 +108,15 @@ impl RepeatGuard {let text = text.trim();let mut entry = match at {Some(i) => entries.remove(i),- None => Entry { key: *key, error: String::new(), count: 0 },+ None => Entry { key: *key, error: String::new(), count: 0, turn: 0 },};- if entry.count > 0 && entry.error == text {+ if entry.turn > 0 && entry.error == text {entry.count += 1;+ entry.turn += 1;} else {entry.error = text.to_string();entry.count = 1;+ entry.turn = 1;}if entries.len() >= MAX_KEYS {entries.remove(0);@@ -248,6 +272,46 @@ mod tests {assert_eq!(g.len(), MAX_KEYS);}+ #[test]+ fn a_change_gives_a_stopped_call_its_tries_again_up_to_the_ceiling() {+ let g = RepeatGuard::default();+ let k = RepeatGuard::key("Bash", &json!({"command": "npm test"}));+ let other = RepeatGuard::key("Read", &json!({"file_path": "/a"}));+ fail(&g, &k, 3, "1 failing");+ g.after(&other, "error", "nope");+ assert!(g.check(&k).is_some());+ g.changed();+ // 3 more tries, then the turn's 6th identical failure stops it for good+ fail(&g, &k, 3, "1 failing");+ let s = g.check(&k).expect("stopped at the ceiling");+ assert_eq!(s.count, REPEAT_CEILING);+ assert_eq!(s.text, stop_text(6, "1 failing"));+ g.changed();+ assert!(g.check(&k).is_some(), "a change doesn't lift the ceiling");+ // Other entries got their tries back too, and a change with nothing stopped is harmless+ assert!(g.check(&other).is_none());+ RepeatGuard::default().changed();+ }++ #[test]+ fn a_change_between_every_failure_stops_at_the_ceiling() {+ let g = RepeatGuard::default();+ let k = RepeatGuard::key("Bash", &json!({"command": "cargo test"}));+ for i in 1..=REPEAT_CEILING {+ assert!(g.check(&k).is_none(), "try {i} runs");+ g.after(&k, "error", "test a ... FAILED");+ g.changed();+ }+ assert_eq!(g.check(&k).map(|s| s.count), Some(REPEAT_CEILING));+ // A different error starts both counts again; an ok forgets the call+ g.after(&k, "error", "test b ... FAILED");+ assert!(g.check(&k).is_none());+ fail(&g, &k, 2, "test b ... FAILED");+ assert_eq!(g.check(&k).map(|s| s.count), Some(3));+ g.after(&k, "ok", "");+ assert!(g.check(&k).is_none());+ }+#[test]fn a_long_error_is_cut_to_200_characters() {let long = "e".repeat(500);diff --git a/src/mcp/session.rs b/src/mcp/session.rsindex 2a012f47..5f6a98dd 100644--- a/src/mcp/session.rs+++ b/src/mcp/session.rs@@ -295,6 +295,12 @@ impl McpToolSession {};let text = redact(&text, &self.secrets);self.repeats.after(&repeat_key, status, &text);+ // 22t: a call that worked and may have changed something gives the stopped calls their+ // tries again. Read-only by the server's own claim (readOnlyHint) or by its name (the+ // restart classifier's list) changes nothing.+ if status == "ok" && offered.is_some_and(|t| !t.tool.read_only) && !crate::server::restart_resume::read_only(name) {+ self.repeats.changed();+ }let (server, tool) = super::split_tool_name(name).unwrap_or(("", name));let mut record = json!({"id": call_id,diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 986c81cc..fd377df2 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -1322,6 +1322,11 @@ pub async fn self_endpoint((json!([{"type": "text", "text": text}]), is_error)};scope.repeats.after(&repeat_key, if is_error { "error" } else { "ok" }, &content_text(&content));+ // 22t: an own tool that worked and doesn't only read (READ_ONLY_SELF_TOOLS, a browser+ // look) gives the stopped calls their tries again+ if !is_error && !super::restart_resume::read_only(name) {+ scope.repeats.changed();+ }rpc_result(id, json!({"content": content, "isError": is_error}))}_ => Json(json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": "method not found"}})).into_response(),diff --git a/tests/repeat_guard_test.rs b/tests/repeat_guard_test.rsindex 1890c83d..998315dd 100644--- a/tests/repeat_guard_test.rs+++ b/tests/repeat_guard_test.rs@@ -27,7 +27,8 @@ impl Hits {}/// An http MCP server with `fail` (always the same error), `flaky` (a new error each time) and-/// `status` (always works).+/// `status` (always works, may change things). `lookup` (marked `readOnlyHint`) and `get_board`+/// (a reader by its name) always work and only read.async fn fake_mcp() -> (String, Hits) {async fn mcp(State(hits): State<Hits>, Json(msg): Json<Value>) -> axum::response::Response {use axum::response::IntoResponse;@@ -36,7 +37,11 @@ async fn fake_mcp() -> (String, Hits) {let result = match msg["method"].as_str().unwrap_or("") {"initialize" => json!({"protocolVersion": "2025-06-18", "capabilities": {"tools": {}},"serverInfo": {"name": "fake-fail", "version": "1.0.0"}}),- "tools/list" => json!({"tools": [tool("fail"), tool("flaky"), tool("status")]}),+ "tools/list" => {+ let mut lookup = tool("lookup");+ lookup["annotations"] = json!({"readOnlyHint": true});+ json!({"tools": [tool("fail"), tool("flaky"), tool("status"), lookup, tool("get_board")]})+ }"tools/call" => {let name = msg["params"]["name"].as_str().unwrap_or("").to_string();let n = {@@ -178,6 +183,45 @@ async fn working_polls_changing_errors_and_denials_are_not_stopped() {session.shutdown().await;}+/// 22t: on the API engines, a call that worked and may have changed something gives the stopped+/// call 3 more tries, up to 6 identical failures in the turn; a read changes nothing.+#[tokio::test]+async fn a_call_that_changed_something_lets_the_stopped_call_run_again() {+ let (url, hits) = fake_mcp().await;+ let c = ctx(&url, counting(true), 32);+ let (session, problems) = McpToolSession::open(&c, None).await;+ assert!(problems.is_empty(), "{problems:?}");+ macro_rules! fail {+ () => {+ session.call(&caller(), "f", "mcp__board__fail", r#"{"board": "roadmap"}"#).await+ };+ }+ for _ in 0..4 {+ fail!();+ }+ assert_eq!(hits.of("fail"), 3);+ // Reads, by the server's claim or by name, don't reopen it+ for tool in ["mcp__board__lookup", "mcp__board__get_board"] {+ let o = session.call(&caller(), "r", tool, r#"{"board": "roadmap"}"#).await;+ assert_eq!(o.status, "ok");+ assert!(fail!().record.get("repeat_stopped").is_some(), "{tool} reopened it");+ }+ assert_eq!(hits.of("fail"), 3);+ // A call that isn't marked read-only worked: 3 more tries reach the server+ assert_eq!(session.call(&caller(), "w", "mcp__board__status", r#"{"board": "roadmap"}"#).await.status, "ok");+ for i in 4..=6 {+ let o = fail!();+ assert_eq!((o.status, o.text.as_str()), ("error", FAIL_TEXT), "try {i} sent");+ }+ // 6 in the turn is the ceiling: another change doesn't send a 7th+ session.call(&caller(), "w", "mcp__board__status", r#"{"board": "roadmap"}"#).await;+ let o = fail!();+ assert_eq!(o.record["repeat_stopped"], 6);+ assert!(o.text.contains("already failed 6 times in this turn"), "{}", o.text);+ assert_eq!(hits.of("fail"), 6);+ session.shutdown().await;+}+// ---- One API-engine turn with a stub model (no paid call) ----#[derive(Clone, Default)]