agent: loop-repetition guard, earlier notepad warn, tighter silence watchdog

Feedback from the framework agent (agent-feedback/2026-11-30-proposte.md),
evaluated against the real code; outcome in agent-feedback/2026-11-30-esito.md.

- agent/mod.rs: detect REPEAT_LIMIT=3 consecutive identical tool-call batches and
  stop with agent_loop_detected before burning MAX_ITERS; the repeating request
  is dropped before persistence so no dangling tool_call turn is left. New test
  loop_detects_repeated_tool_calls; step-limit test now varies its commands.
- notepad: SOFT_WARN_CHARS 6000 -> 4000 (warn at half the ceiling; consolidation
  itself costs an extra model turn).
- config/supervisor: silence watchdog default 600s -> 120s (already configurable
  via silence_timeout_secs); a long output gap is almost always a hang.

Rejected: bash -lc -> bash -c (the login shell preserves the user environment).
Deferred: token-based window cut (heavy; KV-cache interaction; to design with the
new engine). Suite: 204 passed / 3 ignored, clippy/fmt clean.
This commit is contained in:
adm committed 2026-11-30 02:30:00 +01:00
1 parent 0d335b808c
commit 6898cdf113
6 files changed
+328 -9

No files matched your search

+96 -2
View File
@@ -28,6 +28,11 @@ use shell::{ShellRequest, ShellRunner};
/// Default cap on model↔tool iterations, so a misbehaving model cannot loop forever.
pub const MAX_ITERS: usize = 24;
/// Consecutive identical tool-call batches that trip the loop detector. A model
/// re-issuing the exact same call(s) with nothing changing between is stuck in a
/// loop trap; catch it well before [`MAX_ITERS`] burns the whole budget.
pub const REPEAT_LIMIT: usize = 3;
/// The tools offered to the agent: the universal `shell_exec` (action), the
/// `notepad` (per-session context management) and `share_file` (hand the user a
/// download link for a file the agent has on disk).
@@ -237,6 +242,10 @@ where
max_iters,
progress,
} = ctx;
// Loop-detector state: signature of the previous tool-call batch and how many
// times it has repeated consecutively.
let mut last_sig: Option<String> = None;
let mut repeats: usize = 0;
for _ in 0..max_iters {
let resp = model(req.clone()).await?;
let choice = resp
@@ -270,6 +279,29 @@ where
return Ok(resp);
}
// Loop detector: the same tool-call batch repeated consecutively (same
// names + arguments, nothing changing between) is a loop trap. Stop with
// an explicit error before burning the rest of the iteration budget. The
// repeated request is dropped before persistence, so the trajectory keeps
// no dangling tool_call turn without its result.
let sig = calls
.iter()
.map(|c| format!("{}:{}", c.function.name, c.function.arguments))
.collect::<Vec<_>>()
.join("|");
if last_sig.as_deref() == Some(sig.as_str()) {
repeats += 1;
} else {
repeats = 1;
last_sig = Some(sig);
}
if repeats >= REPEAT_LIMIT {
return Err(envelope(
format!("agent repeated the same tool call {repeats} times (loop detected)"),
"agent_loop_detected",
));
}
// Assistant turn requesting tools: persist it, then run each call.
let tool_json = serde_json::to_string(&calls).ok();
persist(
@@ -509,8 +541,33 @@ mod tests {
)
.unwrap();
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
// Model always asks for a tool -> never finishes.
let model = move |_req: ChatRequest| async { Ok(tool_call_response()) };
// Model always asks for a tool but with a DIFFERENT command each turn, so
// the repetition detector does not fire: it never finishes -> step limit.
let n = Arc::new(AtomicUsize::new(0));
let model = move |_req: ChatRequest| {
let n = n.clone();
async move {
let i = n.fetch_add(1, Ordering::SeqCst);
Ok(response(
ChatMessage {
role: Role::Assistant,
content: None,
tool_call_id: None,
tool_calls: Some(vec![ToolCall {
id: format!("call_{i}"),
kind: "function".into(),
function: FunctionCall {
name: "shell_exec".into(),
arguments: json!({"command": format!("echo step-{i}")}).to_string(),
},
}]),
name: None,
reasoning_content: None,
},
FinishReason::ToolCalls,
))
}
};
let err = run_loop(
model,
LoopContext {
@@ -529,6 +586,43 @@ mod tests {
assert_eq!(err.error.code.as_deref(), Some("agent_step_limit"));
}
#[tokio::test]
async fn loop_detects_repeated_tool_calls() {
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
let sess = store
.create_session(
"Agent",
"test-model",
&crate::store::SessionSettings::default(),
)
.unwrap();
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
// Model re-issues the identical call every turn: the detector must trip at
// REPEAT_LIMIT, well before the (larger) iteration cap.
let model = move |_req: ChatRequest| async { Ok(tool_call_response()) };
let err = run_loop(
model,
LoopContext {
runner,
store: store.clone(),
default_cwd: None,
workspace_root: None,
max_iters: MAX_ITERS,
progress: None,
},
&sess.id,
base_req(),
)
.await
.unwrap_err();
assert_eq!(err.error.code.as_deref(), Some("agent_loop_detected"));
// Only REPEAT_LIMIT-1 tool results were persisted: the repeating request is
// dropped before execution/persistence (no dangling tool_call turn).
let msgs = store.messages(&sess.id).unwrap();
let tool_results = msgs.iter().filter(|m| m.role == "tool").count();
assert_eq!(tool_results, REPEAT_LIMIT - 1);
}
#[tokio::test]
async fn unknown_tool_yields_error_result() {
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
+3 -2
View File
@@ -19,8 +19,9 @@ const MAX_ENTRY_CHARS: usize = 1024;
/// Total notepad char cap (hard ceiling). Over it, a `set` is refused and the
/// agent is asked to consolidate stale entries itself.
const MAX_TOTAL_CHARS: usize = 8000;
/// Soft warning threshold: near the ceiling, nudge consolidation.
const SOFT_WARN_CHARS: usize = 6000;
/// Soft warning threshold: warn early (half the ceiling) so the model has room
/// to consolidate — consolidation itself costs an extra model turn.
const SOFT_WARN_CHARS: usize = 4000;
/// Max key length.
const MAX_KEY_CHARS: usize = 64;