1use serde::{Deserialize, Serialize};
2
3use crate::receipt::{Receipt, ReceiptStatus};
4
5#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
8pub struct StuckConfig {
9 pub repeat_threshold: usize,
11 pub error_threshold: usize,
13 pub ping_pong_window: usize,
15 pub max_nudges: u32,
17}
18
19impl Default for StuckConfig {
20 fn default() -> Self {
21 Self {
22 repeat_threshold: 3,
23 error_threshold: 3,
24 ping_pong_window: 6,
25 max_nudges: 2,
26 }
27 }
28}
29
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(rename_all = "snake_case", tag = "kind")]
32pub enum StuckSignal {
33 RepeatedCall { tool: String, count: usize },
34 RepeatedError { tool: String, count: usize },
35 PingPong { first: String, second: String },
36}
37
38impl StuckSignal {
39 pub(crate) fn nudge_text(&self) -> String {
40 match self {
41 Self::RepeatedCall { tool, count } => format!(
42 "[harness] You have called `{tool}` {count} times with the same arguments and \
43 received the same result. Repeating it will not change the outcome. Try a \
44 different approach, or explain what is blocking you."
45 ),
46 Self::RepeatedError { tool, count } => format!(
47 "[harness] `{tool}` has failed {count} times in a row. Read the last error \
48 carefully and change approach instead of retrying the same way."
49 ),
50 Self::PingPong { first, second } => format!(
51 "[harness] You are alternating between `{first}` and `{second}` without making \
52 progress. Step back and pick a different approach."
53 ),
54 }
55 }
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61struct Observation {
62 tool: String,
63 call_fp: u64,
64 pair_fp: u64,
65 failed: bool,
66}
67
68#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
70pub struct StuckState {
71 history: Vec<Observation>,
72}
73
74const WINDOW: usize = 32;
75
76impl StuckState {
77 pub(crate) fn observe(
78 &mut self,
79 config: &StuckConfig,
80 receipt: &Receipt,
81 output: &str,
82 ) -> Option<StuckSignal> {
83 let args = receipt.arguments.to_string();
84 let call_fp = fnv1a(&[receipt.tool.as_bytes(), b"\0", args.as_bytes()]);
85 let pair_fp = fnv1a(&[&call_fp.to_le_bytes(), output.as_bytes()]);
86 let failed = !matches!(receipt.status, ReceiptStatus::Succeeded);
87 self.history.push(Observation {
88 tool: receipt.tool.clone(),
89 call_fp,
90 pair_fp,
91 failed,
92 });
93 if self.history.len() > WINDOW {
94 self.history.remove(0);
95 }
96 self.detect(config)
97 }
98
99 pub(crate) fn reset(&mut self) {
100 self.history.clear();
101 }
102
103 fn detect(&self, config: &StuckConfig) -> Option<StuckSignal> {
104 let h = &self.history;
105 let last = h.last()?;
106
107 let n = config.repeat_threshold;
108 if n > 1 && h.len() >= n && h[h.len() - n..].iter().all(|o| o.pair_fp == last.pair_fp) {
109 return Some(StuckSignal::RepeatedCall {
110 tool: last.tool.clone(),
111 count: n,
112 });
113 }
114
115 let n = config.error_threshold;
116 if n > 1
117 && h.len() >= n
118 && h[h.len() - n..]
119 .iter()
120 .all(|o| o.failed && o.tool == last.tool)
121 {
122 return Some(StuckSignal::RepeatedError {
123 tool: last.tool.clone(),
124 count: n,
125 });
126 }
127
128 let w = config.ping_pong_window;
129 if w >= 4 && h.len() >= w {
130 let tail = &h[h.len() - w..];
131 let (a, b) = (tail[0].call_fp, tail[1].call_fp);
132 let alternates = a != b
133 && tail
134 .iter()
135 .enumerate()
136 .all(|(i, o)| o.call_fp == if i % 2 == 0 { a } else { b });
137 if alternates {
138 return Some(StuckSignal::PingPong {
139 first: tail[0].tool.clone(),
140 second: tail[1].tool.clone(),
141 });
142 }
143 }
144 None
145 }
146}
147
148fn fnv1a(parts: &[&[u8]]) -> u64 {
149 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
150 for part in parts {
151 for byte in *part {
152 hash ^= u64::from(*byte);
153 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
154 }
155 }
156 hash
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162 use crate::receipt::InvocationStage;
163 use serde_json::json;
164
165 fn receipt(tool: &str, args: serde_json::Value, status: ReceiptStatus) -> Receipt {
166 Receipt {
167 run_id: crate::state::RunId::new(),
168 call_id: "c".into(),
169 tool: tool.into(),
170 arguments: args,
171 turn: 1,
172 stage: InvocationStage::Dispatched,
173 status,
174 read_only: true,
175 duration_ms: 0,
176 reason: None,
177 details: serde_json::Value::Null,
178 source: Default::default(),
179 after_untrusted: false,
180 }
181 }
182
183 #[test]
184 fn repeated_identical_pairs_fire() {
185 let cfg = StuckConfig::default();
186 let mut s = StuckState::default();
187 let r = receipt("ls", json!({"p": "."}), ReceiptStatus::Succeeded);
188 assert!(s.observe(&cfg, &r, "a b").is_none());
189 assert!(s.observe(&cfg, &r, "a b").is_none());
190 assert!(matches!(
191 s.observe(&cfg, &r, "a b"),
192 Some(StuckSignal::RepeatedCall { .. })
193 ));
194 }
195
196 #[test]
197 fn same_call_with_changing_output_is_polling_not_stuck() {
198 let cfg = StuckConfig::default();
199 let mut s = StuckState::default();
200 let r = receipt("status", json!({}), ReceiptStatus::Succeeded);
201 for i in 0..10 {
202 assert!(s.observe(&cfg, &r, &format!("progress {i}%")).is_none());
203 }
204 }
205
206 #[test]
207 fn repeated_errors_fire_even_with_different_args() {
208 let cfg = StuckConfig::default();
209 let mut s = StuckState::default();
210 for i in 0..2 {
211 let r = receipt("build", json!({"try": i}), ReceiptStatus::Failed);
212 assert!(s.observe(&cfg, &r, &format!("err {i}")).is_none());
213 }
214 let r = receipt("build", json!({"try": 9}), ReceiptStatus::Failed);
215 assert!(matches!(
216 s.observe(&cfg, &r, "err 9"),
217 Some(StuckSignal::RepeatedError { .. })
218 ));
219 }
220
221 #[test]
222 fn ping_pong_fires() {
223 let cfg = StuckConfig::default();
224 let mut s = StuckState::default();
225 let mut last = None;
226 for i in 0..6 {
227 let (tool, out) = if i % 2 == 0 { ("a", i) } else { ("b", i) };
228 let r = receipt(tool, json!({}), ReceiptStatus::Succeeded);
229 last = s.observe(&cfg, &r, &out.to_string());
230 }
231 assert!(matches!(last, Some(StuckSignal::PingPong { .. })));
232 }
233}