Skip to main content

agent_types/
run_state.rs

1//! Run-state pure types: [`RunState`] — the counting and strike state of a run.
2//!
3//! M3 D5+OV-11: this is THE counting evidence. Restores trust its persisted
4//! value ("恢复计数信 RunState 持久值"); it rides in [`crate::CheckpointData`]
5//! so it is co-written with the checkpoint/journal in one write ("与
6//! checkpoint/journal 事务性同写") — the recorded batch and the counts can
7//! never disagree across a crash window. The message-lens recount stays as
8//! old-format compatibility only.
9//!
10//! Counting unit = **actions** (D5: 口径=动作) — tool calls today, CodeAct
11//! cells tomorrow — so the fields and methods say `actions`, not `tool_calls`.
12//! Old wire keys (`turn_tool_calls`, `run_has_tool_calls`, `total_tool_calls`)
13//! are read through serde aliases.
14
15use serde::{Deserialize, Serialize};
16
17/// Run-level state tracking for the react loop.
18///
19/// Manages counters and flags that track the current run's progress.
20/// Most fields are reset at the start of each run (when a new user message
21/// arrives); [`total_actions`](Self::total_actions) and
22/// [`original_thinking_enabled`](Self::original_thinking_enabled) are
23/// session-lifetime and survive run boundaries.
24///
25/// # Backward compatibility
26///
27/// Before this struct existed, `nudge_count` and `turn_tool_calls` were flat
28/// fields on `AgentSession` (and the session total lived in a top-level
29/// `total_tool_calls`). The `RawAgentSession` deserialization shim migrates
30/// them automatically; the field aliases below keep pre-T7 `run_state` wire
31/// keys readable.
32#[derive(Clone, Debug, Default, Serialize, Deserialize)]
33pub struct RunState {
34    /// Session-lifetime count of actions executed (across all runs).
35    /// Not reset by [`reset_for_new_run`](Self::reset_for_new_run) — a session
36    /// that already acted stays "not first turn" across run boundaries.
37    /// Used by `ToolEnforcementMiddleware` for "first_turn_only" enforcement.
38    #[serde(default, alias = "total_tool_calls")]
39    pub total_actions: usize,
40    /// Number of actions already executed in the current turn.
41    /// Reset to 0 at the start of each turn (when a new user message arrives).
42    /// Used by `TurnToolLimitMiddleware` to enforce per-turn action limits.
43    #[serde(default, alias = "turn_tool_calls")]
44    pub turn_actions: usize,
45    /// Whether any actions ran in the current run.
46    /// Reset to false at the start of each run. Used by the completion judge
47    /// to determine if actions were used before a text-only response.
48    #[serde(default, alias = "run_has_tool_calls")]
49    pub run_has_actions: bool,
50    /// Number of consecutive LLM turns that produced only reasoning_content
51    /// (no text, no tool call). Reset to 0 when a normal response or tool call
52    /// is produced. Used by the react loop to fail instead of looping forever
53    /// on a reasoning-model runaway.
54    pub reasoning_only_strikes: usize,
55    /// Number of consecutive LLM turns that produced a completely empty response
56    /// (no text, no reasoning, no tool call). Reset to 0 when a normal response
57    /// or tool call is produced. Used by the react loop to retry a bounded
58    /// number of times, then fail instead of looping forever.
59    pub empty_response_strikes: usize,
60    /// Number of tool-enforcement nudges issued in the current turn.
61    /// Reset to 0 at the start of each turn (when a new user message arrives).
62    /// Used by `ToolEnforcementMiddleware` to cap nudge attempts per turn.
63    pub nudge_count: usize,
64    /// Thinking is disabled for the rest of the current run.
65    /// Set to true when reasoning_only_strikes reaches the maximum (3).
66    /// Reset to false at the start of each new run (when a new user message arrives).
67    /// This allows the model to continue without thinking after too many
68    /// reasoning-only responses.
69    #[serde(default)]
70    pub thinking_disabled_for_rest_of_run: bool,
71
72    // ─── New fields for thinking guard ─────────────────────────────
73    /// Original thinking configuration (for restoration)
74    ///
75    /// Records whether thinking was originally enabled when the session started.
76    /// Used to restore thinking to its original state after DisableThinking → RestoreThinking cycle.
77    #[serde(default)]
78    pub original_thinking_enabled: bool,
79
80    /// Number of consecutive LLM turns where the truncation guard fired
81    /// (all tool_calls had invalid/truncated arguments). Reset to 0 when
82    /// at least one valid tool call executes successfully. Used to break
83    /// the re-issue death spiral: after N consecutive truncations, stop
84    /// retrying and fail with an actionable message.
85    #[serde(default)]
86    pub truncation_strikes: usize,
87
88    /// The latest tool batch parked on a human step (a design-canvas screen
89    /// awaiting a pick) and no tool ran after it. Overwritten per batch by
90    /// `handle_tool_calls`. When true at the end of a run, the run is
91    /// *waiting for the user* — the guard must complete instead of nudging
92    /// "continue working" over their pending answer.
93    #[serde(default)]
94    pub awaiting_human: bool,
95}
96
97impl RunState {
98    /// Reset all run-level state for a new run (when a new user message arrives).
99    /// Session-lifetime state (`total_actions`, `original_thinking_enabled`)
100    /// is not reset.
101    pub fn reset_for_new_run(&mut self) {
102        self.turn_actions = 0;
103        self.run_has_actions = false;
104        self.reasoning_only_strikes = 0;
105        self.empty_response_strikes = 0;
106        self.nudge_count = 0;
107        self.thinking_disabled_for_rest_of_run = false;
108        self.truncation_strikes = 0;
109        self.awaiting_human = false;
110        // Note: original_thinking_enabled is NOT reset here
111        // It should be set once when the session starts
112    }
113
114    /// Record executed actions (branch 3: actions ran).
115    /// Counts them against both the turn and the session total (D5: one
116    /// counting entry point, unit = actions) and resets reasoning_only_strikes,
117    /// empty_response_strikes, and truncation_strikes.
118    pub fn record_actions(&mut self, n: usize) {
119        self.turn_actions += n;
120        self.total_actions += n;
121        self.run_has_actions = true;
122        self.reasoning_only_strikes = 0;
123        self.empty_response_strikes = 0;
124        self.truncation_strikes = 0;
125    }
126
127    /// Record reasoning-only response (branch 1).
128    /// Resets empty_response_strikes.
129    /// Returns the new strike count.
130    /// If strikes reach 3, disables thinking for the rest of the run (the
131    /// caller owns the observability for that flip — types stay I/O-free).
132    pub fn record_reasoning_only(&mut self) -> usize {
133        self.empty_response_strikes = 0;
134        self.reasoning_only_strikes += 1;
135        if self.reasoning_only_strikes >= 3 {
136            self.thinking_disabled_for_rest_of_run = true;
137        }
138        self.reasoning_only_strikes
139    }
140
141    /// Record empty response (branch 2).
142    /// Resets reasoning_only_strikes.
143    /// Returns the new strike count.
144    pub fn record_empty_response(&mut self) -> usize {
145        self.reasoning_only_strikes = 0;
146        self.empty_response_strikes += 1;
147        self.empty_response_strikes
148    }
149
150    /// Record a truncation guard firing (all tool_calls had invalid arguments).
151    /// Returns the new strike count. Caller should check against threshold.
152    pub fn record_truncation(&mut self) -> usize {
153        self.truncation_strikes += 1;
154        self.truncation_strikes
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    #[test]
163    fn run_state_default() {
164        let rs = RunState::default();
165        assert_eq!(rs.total_actions, 0);
166        assert_eq!(rs.turn_actions, 0);
167        assert!(!rs.run_has_actions);
168        assert_eq!(rs.reasoning_only_strikes, 0);
169        assert_eq!(rs.empty_response_strikes, 0);
170        assert_eq!(rs.nudge_count, 0);
171    }
172
173    #[test]
174    fn run_state_reset_for_new_run() {
175        let mut rs = RunState {
176            total_actions: 9,
177            turn_actions: 5,
178            run_has_actions: true,
179            reasoning_only_strikes: 2,
180            empty_response_strikes: 1,
181            nudge_count: 3,
182            thinking_disabled_for_rest_of_run: true,
183            original_thinking_enabled: true,
184            truncation_strikes: 4,
185            awaiting_human: true,
186        };
187
188        rs.reset_for_new_run();
189
190        // Session-lifetime state survives the run boundary.
191        assert_eq!(rs.total_actions, 9);
192        assert_eq!(rs.turn_actions, 0);
193        assert!(!rs.run_has_actions);
194        assert_eq!(rs.reasoning_only_strikes, 0);
195        assert_eq!(rs.empty_response_strikes, 0);
196        assert_eq!(rs.nudge_count, 0);
197        assert_eq!(rs.truncation_strikes, 0);
198        assert!(!rs.thinking_disabled_for_rest_of_run);
199        assert!(!rs.awaiting_human);
200        // original_thinking_enabled is NOT reset
201        assert!(rs.original_thinking_enabled);
202    }
203
204    #[test]
205    fn run_state_record_actions() {
206        let mut rs = RunState {
207            reasoning_only_strikes: 2,
208            empty_response_strikes: 1,
209            ..RunState::default()
210        };
211
212        rs.record_actions(3);
213
214        assert_eq!(rs.turn_actions, 3);
215        assert_eq!(rs.total_actions, 3);
216        assert!(rs.run_has_actions);
217        assert_eq!(rs.reasoning_only_strikes, 0); // reset
218        assert_eq!(rs.empty_response_strikes, 0); // reset
219    }
220
221    #[test]
222    fn run_state_record_actions_accumulates() {
223        let mut rs = RunState::default();
224        rs.record_actions(2);
225        rs.record_actions(3);
226
227        assert_eq!(rs.turn_actions, 5);
228        assert_eq!(rs.total_actions, 5);
229        assert!(rs.run_has_actions);
230    }
231
232    #[test]
233    fn run_state_record_reasoning_only() {
234        let mut rs = RunState {
235            empty_response_strikes: 2,
236            ..RunState::default()
237        };
238
239        let strikes = rs.record_reasoning_only();
240
241        assert_eq!(strikes, 1);
242        assert_eq!(rs.reasoning_only_strikes, 1);
243        assert_eq!(rs.empty_response_strikes, 0); // reset
244    }
245
246    #[test]
247    fn run_state_record_reasoning_only_consecutive() {
248        let mut rs = RunState::default();
249
250        assert_eq!(rs.record_reasoning_only(), 1);
251        assert_eq!(rs.record_reasoning_only(), 2);
252        assert_eq!(rs.record_reasoning_only(), 3);
253    }
254
255    #[test]
256    fn run_state_record_empty_response() {
257        let mut rs = RunState {
258            reasoning_only_strikes: 2,
259            ..RunState::default()
260        };
261
262        let strikes = rs.record_empty_response();
263
264        assert_eq!(strikes, 1);
265        assert_eq!(rs.empty_response_strikes, 1);
266        assert_eq!(rs.reasoning_only_strikes, 0); // reset
267    }
268
269    #[test]
270    fn run_state_record_empty_response_consecutive() {
271        let mut rs = RunState::default();
272
273        assert_eq!(rs.record_empty_response(), 1);
274        assert_eq!(rs.record_empty_response(), 2);
275        assert_eq!(rs.record_empty_response(), 3);
276    }
277
278    #[test]
279    fn run_state_branch_cross_reset() {
280        // Simulate: reasoning only → actions → reasoning only
281        let mut rs = RunState::default();
282
283        // Branch 1: reasoning only
284        rs.record_reasoning_only();
285        assert_eq!(rs.reasoning_only_strikes, 1);
286
287        // Branch 3: actions (should reset reasoning_only_strikes)
288        rs.record_actions(2);
289        assert_eq!(rs.reasoning_only_strikes, 0);
290        assert_eq!(rs.turn_actions, 2);
291
292        // Branch 1 again: reasoning only (should start from 1, not 2)
293        let strikes = rs.record_reasoning_only();
294        assert_eq!(strikes, 1);
295    }
296
297    #[test]
298    fn run_state_empty_to_reasoning_reset() {
299        // Simulate: empty → empty → reasoning only (should reset empty strikes)
300        let mut rs = RunState::default();
301
302        rs.record_empty_response();
303        rs.record_empty_response();
304        assert_eq!(rs.empty_response_strikes, 2);
305
306        // Branch 1: reasoning only (should reset empty_response_strikes)
307        rs.record_reasoning_only();
308        assert_eq!(rs.empty_response_strikes, 0);
309        assert_eq!(rs.reasoning_only_strikes, 1);
310    }
311
312    #[test]
313    fn run_state_thinking_disabled_default() {
314        let rs = RunState::default();
315        assert!(!rs.thinking_disabled_for_rest_of_run);
316    }
317
318    #[test]
319    fn run_state_thinking_disabled_after_3_strikes() {
320        let mut rs = RunState::default();
321
322        // After 1st reasoning-only: not disabled
323        rs.record_reasoning_only();
324        assert!(!rs.thinking_disabled_for_rest_of_run);
325        assert_eq!(rs.reasoning_only_strikes, 1);
326
327        // After 2nd reasoning-only: not disabled
328        rs.record_reasoning_only();
329        assert!(!rs.thinking_disabled_for_rest_of_run);
330        assert_eq!(rs.reasoning_only_strikes, 2);
331
332        // After 3rd reasoning-only: disabled!
333        rs.record_reasoning_only();
334        assert!(rs.thinking_disabled_for_rest_of_run);
335        assert_eq!(rs.reasoning_only_strikes, 3);
336    }
337
338    #[test]
339    fn run_state_thinking_disabled_resets_on_new_run() {
340        let mut rs = RunState::default();
341
342        // Simulate 3 reasoning-only responses
343        rs.record_reasoning_only();
344        rs.record_reasoning_only();
345        rs.record_reasoning_only();
346        assert!(rs.thinking_disabled_for_rest_of_run);
347        assert_eq!(rs.reasoning_only_strikes, 3);
348
349        // Reset for new run (new user message)
350        rs.reset_for_new_run();
351        assert!(!rs.thinking_disabled_for_rest_of_run);
352        assert_eq!(rs.reasoning_only_strikes, 0);
353    }
354
355    #[test]
356    fn run_state_thinking_disabled_stays_after_actions() {
357        let mut rs = RunState::default();
358
359        // Simulate 3 reasoning-only responses
360        rs.record_reasoning_only();
361        rs.record_reasoning_only();
362        rs.record_reasoning_only();
363        assert!(rs.thinking_disabled_for_rest_of_run);
364
365        // Actions should NOT reset thinking_disabled_for_rest_of_run
366        // (it should stay disabled for the rest of the run)
367        rs.record_actions(2);
368        assert!(rs.thinking_disabled_for_rest_of_run);
369        assert_eq!(rs.reasoning_only_strikes, 0); // strikes reset, but thinking stays disabled
370    }
371
372    #[test]
373    fn pre_t7_wire_keys_are_read_through_aliases() {
374        // A P2-era `run_state` payload: the counting fields still spelled
375        // "tool calls". The aliases keep that corpus readable verbatim.
376        let json = r#"{
377            "turn_tool_calls": 4,
378            "run_has_tool_calls": true,
379            "reasoning_only_strikes": 0,
380            "empty_response_strikes": 1,
381            "nudge_count": 2
382        }"#;
383        let rs: RunState = serde_json::from_str(json).unwrap();
384        assert_eq!(rs.turn_actions, 4);
385        assert!(rs.run_has_actions);
386        assert_eq!(rs.empty_response_strikes, 1);
387        assert_eq!(rs.nudge_count, 2);
388    }
389
390    #[test]
391    fn run_state_round_trips_under_the_new_wire_keys() {
392        let mut rs = RunState::default();
393        rs.record_actions(3);
394        let json = serde_json::to_string(&rs).unwrap();
395        assert!(json.contains("\"total_actions\":3"), "new key: {json}");
396        assert!(json.contains("\"turn_actions\":3"), "new key: {json}");
397        assert!(json.contains("\"run_has_actions\":true"), "new key: {json}");
398        let decoded: RunState = serde_json::from_str(&json).unwrap();
399        assert_eq!(decoded.turn_actions, 3);
400        assert_eq!(decoded.total_actions, 3);
401        assert!(decoded.run_has_actions);
402    }
403}
404
405#[cfg(test)]
406mod proptest_tests {
407    use super::*;
408    use proptest::prelude::*;
409
410    proptest! {
411        #[test]
412        fn reset_for_new_run_zeros_run_fields(
413            total_actions in 0usize..1000,
414            turn_actions in 0usize..1000,
415            run_has_actions in proptest::bool::ANY,
416            reasoning_only_strikes in 0usize..100,
417            empty_response_strikes in 0usize..100,
418            nudge_count in 0usize..100,
419        ) {
420            let mut rs = RunState {
421                total_actions,
422                turn_actions,
423                run_has_actions,
424                reasoning_only_strikes,
425                empty_response_strikes,
426                nudge_count,
427                thinking_disabled_for_rest_of_run: true,
428                original_thinking_enabled: true,
429                truncation_strikes: 5,
430                awaiting_human: true,
431            };
432            rs.reset_for_new_run();
433            // Session-lifetime count survives; run-level state is zeroed.
434            assert_eq!(rs.total_actions, total_actions);
435            assert_eq!(rs.turn_actions, 0);
436            assert!(!rs.run_has_actions);
437            assert_eq!(rs.reasoning_only_strikes, 0);
438            assert_eq!(rs.empty_response_strikes, 0);
439            assert_eq!(rs.nudge_count, 0);
440            assert_eq!(rs.truncation_strikes, 0);
441            assert!(!rs.thinking_disabled_for_rest_of_run);
442            assert!(!rs.awaiting_human);
443            // original_thinking_enabled is NOT reset
444            assert!(rs.original_thinking_enabled);
445        }
446
447        #[test]
448        fn record_actions_accumulates(n in 0usize..100) {
449            let mut rs = RunState::default();
450            rs.record_actions(n);
451            assert_eq!(rs.turn_actions, n);
452            assert_eq!(rs.total_actions, n);
453            assert!(rs.run_has_actions);
454            assert_eq!(rs.reasoning_only_strikes, 0);
455            assert_eq!(rs.empty_response_strikes, 0);
456        }
457
458        #[test]
459        fn record_reasoning_only_increments(count in 1usize..50) {
460            let mut rs = RunState::default();
461            for i in 1..=count {
462                let strikes = rs.record_reasoning_only();
463                assert_eq!(strikes, i);
464                assert_eq!(rs.empty_response_strikes, 0);
465            }
466        }
467
468        #[test]
469        fn record_empty_response_increments(count in 1usize..50) {
470            let mut rs = RunState::default();
471            for i in 1..=count {
472                let strikes = rs.record_empty_response();
473                assert_eq!(strikes, i);
474                assert_eq!(rs.reasoning_only_strikes, 0);
475            }
476        }
477    }
478}