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    /// The tools this run has called, in order, by name. The completion judge
51    /// is handed the response and nothing else, so without this it cannot tell
52    /// "the agent did the work and is reporting" from "the agent said a few
53    /// words and stopped" — both look like a short text-only turn.
54    /// Names only: no arguments, so nothing sensitive rides along.
55    /// Reset by [`reset_for_new_run`](Self::reset_for_new_run).
56    #[serde(default)]
57    pub run_actions: Vec<String>,
58    /// Number of consecutive LLM turns that produced only reasoning_content
59    /// (no text, no tool call). Reset to 0 when a normal response or tool call
60    /// is produced. Used by the react loop to fail instead of looping forever
61    /// on a reasoning-model runaway.
62    pub reasoning_only_strikes: usize,
63    /// Number of consecutive LLM turns that produced a completely empty response
64    /// (no text, no reasoning, no tool call). Reset to 0 when a normal response
65    /// or tool call is produced. Used by the react loop to retry a bounded
66    /// number of times, then fail instead of looping forever.
67    pub empty_response_strikes: usize,
68    /// Number of tool-enforcement nudges issued in the current turn.
69    /// Reset to 0 at the start of each turn (when a new user message arrives).
70    /// Used by `ToolEnforcementMiddleware` to cap nudge attempts per turn.
71    pub nudge_count: usize,
72    /// Thinking is disabled for the rest of the current run.
73    /// Set to true when reasoning_only_strikes reaches the maximum (3).
74    /// Reset to false at the start of each new run (when a new user message arrives).
75    /// This allows the model to continue without thinking after too many
76    /// reasoning-only responses.
77    #[serde(default)]
78    pub thinking_disabled_for_rest_of_run: bool,
79
80    // ─── New fields for thinking guard ─────────────────────────────
81    /// Original thinking configuration (for restoration)
82    ///
83    /// Records whether thinking was originally enabled when the session started.
84    /// Used to restore thinking to its original state after DisableThinking → RestoreThinking cycle.
85    #[serde(default)]
86    pub original_thinking_enabled: bool,
87
88    /// Number of consecutive LLM turns where the truncation guard fired
89    /// (all tool_calls had invalid/truncated arguments). Reset to 0 when
90    /// at least one valid tool call executes successfully. Used to break
91    /// the re-issue death spiral: after N consecutive truncations, stop
92    /// retrying and fail with an actionable message.
93    #[serde(default)]
94    pub truncation_strikes: usize,
95    /// Session-lifetime count of structurally corrupt tool-call batches seen.
96    #[serde(default)]
97    pub integrity_failures: u32,
98    /// Session-lifetime count of silent retries spent (corrupt round discarded
99    /// whole, LLM re-asked from the same state).
100    #[serde(default)]
101    pub silent_retries: u32,
102
103    /// The latest tool batch parked on a human step (a design-canvas screen
104    /// awaiting a pick) and no tool ran after it. Overwritten per batch by
105    /// `handle_tool_calls`. When true at the end of a run, the run is
106    /// *waiting for the user* — the guard must complete instead of nudging
107    /// "continue working" over their pending answer.
108    #[serde(default)]
109    pub awaiting_human: bool,
110}
111
112impl RunState {
113    /// Reset all run-level state for a new run (when a new user message arrives).
114    /// Session-lifetime state (`total_actions`, `original_thinking_enabled`)
115    /// is not reset.
116    pub fn reset_for_new_run(&mut self) {
117        self.turn_actions = 0;
118        self.run_has_actions = false;
119        self.run_actions.clear();
120        self.reasoning_only_strikes = 0;
121        self.empty_response_strikes = 0;
122        self.nudge_count = 0;
123        self.thinking_disabled_for_rest_of_run = false;
124        self.truncation_strikes = 0;
125        self.awaiting_human = false;
126        // Note: original_thinking_enabled is NOT reset here
127        // It should be set once when the session starts
128    }
129
130    /// Record executed actions (branch 3: actions ran).
131    /// Counts them against both the turn and the session total (D5: one
132    /// counting entry point, unit = actions) and resets reasoning_only_strikes,
133    /// empty_response_strikes, and truncation_strikes.
134    pub fn record_actions(&mut self, n: usize, names: &[String]) {
135        self.turn_actions += n;
136        self.total_actions += n;
137        self.run_has_actions = true;
138        self.run_actions.extend_from_slice(names);
139        self.reasoning_only_strikes = 0;
140        self.empty_response_strikes = 0;
141        self.truncation_strikes = 0;
142    }
143
144    /// Record reasoning-only response (branch 1).
145    /// Resets empty_response_strikes.
146    /// Returns the new strike count.
147    /// If strikes reach 3, disables thinking for the rest of the run (the
148    /// caller owns the observability for that flip — types stay I/O-free).
149    pub fn record_reasoning_only(&mut self) -> usize {
150        self.empty_response_strikes = 0;
151        self.reasoning_only_strikes += 1;
152        if self.reasoning_only_strikes >= 3 {
153            self.thinking_disabled_for_rest_of_run = true;
154        }
155        self.reasoning_only_strikes
156    }
157
158    /// Record empty response (branch 2).
159    /// Resets reasoning_only_strikes.
160    /// Returns the new strike count.
161    pub fn record_empty_response(&mut self) -> usize {
162        self.reasoning_only_strikes = 0;
163        self.empty_response_strikes += 1;
164        self.empty_response_strikes
165    }
166
167    /// Record a truncation guard firing (all tool_calls had invalid arguments).
168    /// Returns the new strike count. Caller should check against threshold.
169    pub fn record_truncation(&mut self) -> usize {
170        self.truncation_strikes += 1;
171        self.truncation_strikes
172    }
173
174    /// A tool-call batch arrived structurally corrupt (wire truncation /
175    /// misplaced args fragments). Counted per dirty batch — whether or not a
176    /// silent retry was spent on it. Session-lifetime (not reset per run).
177    pub fn record_integrity_failure(&mut self) -> u32 {
178        self.integrity_failures += 1;
179        self.integrity_failures
180    }
181
182    /// A corrupt round was discarded whole and the LLM re-asked. Session-
183    /// lifetime; the per-round budget travels with the retry itself.
184    pub fn record_silent_retry(&mut self) -> u32 {
185        self.silent_retries += 1;
186        self.silent_retries
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    /// Value: protects=the run's tool trace reaches the completion judge, so
195    /// it can tell "the agent did the work and is reporting" from "the agent
196    /// said a few words and stopped"; fails_when=the trace is dropped and the
197    /// judge sees only `user_input` + `model_response` again.
198    /// why_new=no test today records *which* actions ran — `record_actions`
199    /// takes a bare count.
200    /// seam=none; no_claim=judge quality from the trace alone.
201    #[test]
202    fn record_actions_keeps_the_tool_trace_and_a_new_run_clears_it() {
203        let mut s = RunState::default();
204        s.record_actions(
205            3,
206            &[
207                "read_file".into(),
208                "execute_command".into(),
209                "read_file".into(),
210            ],
211        );
212        assert_eq!(s.run_actions, ["read_file", "execute_command", "read_file"]);
213        assert_eq!(s.total_actions, 3);
214        assert!(s.run_has_actions);
215
216        s.reset_for_new_run();
217        assert!(
218            s.run_actions.is_empty(),
219            "a new run must start with an empty trace"
220        );
221        assert!(!s.run_has_actions);
222    }
223
224    #[test]
225    fn run_state_default() {
226        let rs = RunState::default();
227        assert_eq!(rs.total_actions, 0);
228        assert_eq!(rs.turn_actions, 0);
229        assert!(!rs.run_has_actions);
230        assert_eq!(rs.reasoning_only_strikes, 0);
231        assert_eq!(rs.empty_response_strikes, 0);
232        assert_eq!(rs.nudge_count, 0);
233    }
234
235    #[test]
236    fn run_state_reset_for_new_run() {
237        let mut rs = RunState {
238            total_actions: 9,
239            turn_actions: 5,
240            run_has_actions: true,
241            run_actions: vec!["read_file".into()],
242            reasoning_only_strikes: 2,
243            empty_response_strikes: 1,
244            nudge_count: 3,
245            thinking_disabled_for_rest_of_run: true,
246            original_thinking_enabled: true,
247            truncation_strikes: 4,
248            awaiting_human: true,
249        };
250
251        rs.reset_for_new_run();
252
253        // Session-lifetime state survives the run boundary.
254        assert_eq!(rs.total_actions, 9);
255        assert_eq!(rs.turn_actions, 0);
256        assert!(!rs.run_has_actions);
257        assert!(rs.run_actions.is_empty());
258        assert_eq!(rs.reasoning_only_strikes, 0);
259        assert_eq!(rs.empty_response_strikes, 0);
260        assert_eq!(rs.nudge_count, 0);
261        assert_eq!(rs.truncation_strikes, 0);
262        assert!(!rs.thinking_disabled_for_rest_of_run);
263        assert!(!rs.awaiting_human);
264        // original_thinking_enabled is NOT reset
265        assert!(rs.original_thinking_enabled);
266    }
267
268    #[test]
269    fn run_state_record_actions() {
270        let mut rs = RunState {
271            reasoning_only_strikes: 2,
272            empty_response_strikes: 1,
273            ..RunState::default()
274        };
275
276        rs.record_actions(3, &[]);
277
278        assert_eq!(rs.turn_actions, 3);
279        assert_eq!(rs.total_actions, 3);
280        assert!(rs.run_has_actions);
281        assert_eq!(rs.reasoning_only_strikes, 0); // reset
282        assert_eq!(rs.empty_response_strikes, 0); // reset
283    }
284
285    #[test]
286    fn run_state_record_actions_accumulates() {
287        let mut rs = RunState::default();
288        rs.record_actions(2, &[]);
289        rs.record_actions(3, &[]);
290
291        assert_eq!(rs.turn_actions, 5);
292        assert_eq!(rs.total_actions, 5);
293        assert!(rs.run_has_actions);
294    }
295
296    #[test]
297    fn run_state_record_reasoning_only() {
298        let mut rs = RunState {
299            empty_response_strikes: 2,
300            ..RunState::default()
301        };
302
303        let strikes = rs.record_reasoning_only();
304
305        assert_eq!(strikes, 1);
306        assert_eq!(rs.reasoning_only_strikes, 1);
307        assert_eq!(rs.empty_response_strikes, 0); // reset
308    }
309
310    #[test]
311    fn run_state_record_reasoning_only_consecutive() {
312        let mut rs = RunState::default();
313
314        assert_eq!(rs.record_reasoning_only(), 1);
315        assert_eq!(rs.record_reasoning_only(), 2);
316        assert_eq!(rs.record_reasoning_only(), 3);
317    }
318
319    #[test]
320    fn run_state_record_empty_response() {
321        let mut rs = RunState {
322            reasoning_only_strikes: 2,
323            ..RunState::default()
324        };
325
326        let strikes = rs.record_empty_response();
327
328        assert_eq!(strikes, 1);
329        assert_eq!(rs.empty_response_strikes, 1);
330        assert_eq!(rs.reasoning_only_strikes, 0); // reset
331    }
332
333    #[test]
334    fn run_state_record_empty_response_consecutive() {
335        let mut rs = RunState::default();
336
337        assert_eq!(rs.record_empty_response(), 1);
338        assert_eq!(rs.record_empty_response(), 2);
339        assert_eq!(rs.record_empty_response(), 3);
340    }
341
342    #[test]
343    fn run_state_branch_cross_reset() {
344        // Simulate: reasoning only → actions → reasoning only
345        let mut rs = RunState::default();
346
347        // Branch 1: reasoning only
348        rs.record_reasoning_only();
349        assert_eq!(rs.reasoning_only_strikes, 1);
350
351        // Branch 3: actions (should reset reasoning_only_strikes)
352        rs.record_actions(2, &[]);
353        assert_eq!(rs.reasoning_only_strikes, 0);
354        assert_eq!(rs.turn_actions, 2);
355
356        // Branch 1 again: reasoning only (should start from 1, not 2)
357        let strikes = rs.record_reasoning_only();
358        assert_eq!(strikes, 1);
359    }
360
361    #[test]
362    fn run_state_empty_to_reasoning_reset() {
363        // Simulate: empty → empty → reasoning only (should reset empty strikes)
364        let mut rs = RunState::default();
365
366        rs.record_empty_response();
367        rs.record_empty_response();
368        assert_eq!(rs.empty_response_strikes, 2);
369
370        // Branch 1: reasoning only (should reset empty_response_strikes)
371        rs.record_reasoning_only();
372        assert_eq!(rs.empty_response_strikes, 0);
373        assert_eq!(rs.reasoning_only_strikes, 1);
374    }
375
376    #[test]
377    fn run_state_thinking_disabled_default() {
378        let rs = RunState::default();
379        assert!(!rs.thinking_disabled_for_rest_of_run);
380    }
381
382    #[test]
383    fn run_state_thinking_disabled_after_3_strikes() {
384        let mut rs = RunState::default();
385
386        // After 1st reasoning-only: not disabled
387        rs.record_reasoning_only();
388        assert!(!rs.thinking_disabled_for_rest_of_run);
389        assert_eq!(rs.reasoning_only_strikes, 1);
390
391        // After 2nd reasoning-only: not disabled
392        rs.record_reasoning_only();
393        assert!(!rs.thinking_disabled_for_rest_of_run);
394        assert_eq!(rs.reasoning_only_strikes, 2);
395
396        // After 3rd reasoning-only: disabled!
397        rs.record_reasoning_only();
398        assert!(rs.thinking_disabled_for_rest_of_run);
399        assert_eq!(rs.reasoning_only_strikes, 3);
400    }
401
402    #[test]
403    fn run_state_thinking_disabled_resets_on_new_run() {
404        let mut rs = RunState::default();
405
406        // Simulate 3 reasoning-only responses
407        rs.record_reasoning_only();
408        rs.record_reasoning_only();
409        rs.record_reasoning_only();
410        assert!(rs.thinking_disabled_for_rest_of_run);
411        assert_eq!(rs.reasoning_only_strikes, 3);
412
413        // Reset for new run (new user message)
414        rs.reset_for_new_run();
415        assert!(!rs.thinking_disabled_for_rest_of_run);
416        assert_eq!(rs.reasoning_only_strikes, 0);
417    }
418
419    #[test]
420    fn run_state_thinking_disabled_stays_after_actions() {
421        let mut rs = RunState::default();
422
423        // Simulate 3 reasoning-only responses
424        rs.record_reasoning_only();
425        rs.record_reasoning_only();
426        rs.record_reasoning_only();
427        assert!(rs.thinking_disabled_for_rest_of_run);
428
429        // Actions should NOT reset thinking_disabled_for_rest_of_run
430        // (it should stay disabled for the rest of the run)
431        rs.record_actions(2, &[]);
432        assert!(rs.thinking_disabled_for_rest_of_run);
433        assert_eq!(rs.reasoning_only_strikes, 0); // strikes reset, but thinking stays disabled
434    }
435
436    #[test]
437    fn pre_t7_wire_keys_are_read_through_aliases() {
438        // A P2-era `run_state` payload: the counting fields still spelled
439        // "tool calls". The aliases keep that corpus readable verbatim.
440        let json = r#"{
441            "turn_tool_calls": 4,
442            "run_has_tool_calls": true,
443            "reasoning_only_strikes": 0,
444            "empty_response_strikes": 1,
445            "nudge_count": 2
446        }"#;
447        let rs: RunState = serde_json::from_str(json).unwrap();
448        assert_eq!(rs.turn_actions, 4);
449        assert!(rs.run_has_actions);
450        assert_eq!(rs.empty_response_strikes, 1);
451        assert_eq!(rs.nudge_count, 2);
452    }
453
454    #[test]
455    fn run_state_round_trips_under_the_new_wire_keys() {
456        let mut rs = RunState::default();
457        rs.record_actions(3, &[]);
458        let json = serde_json::to_string(&rs).unwrap();
459        assert!(json.contains("\"total_actions\":3"), "new key: {json}");
460        assert!(json.contains("\"turn_actions\":3"), "new key: {json}");
461        assert!(json.contains("\"run_has_actions\":true"), "new key: {json}");
462        let decoded: RunState = serde_json::from_str(&json).unwrap();
463        assert_eq!(decoded.turn_actions, 3);
464        assert_eq!(decoded.total_actions, 3);
465        assert!(decoded.run_has_actions);
466    }
467}
468
469#[cfg(test)]
470mod proptest_tests {
471    use super::*;
472    use proptest::prelude::*;
473
474    proptest! {
475        #[test]
476        fn reset_for_new_run_zeros_run_fields(
477            total_actions in 0usize..1000,
478            turn_actions in 0usize..1000,
479            run_has_actions in proptest::bool::ANY,
480            reasoning_only_strikes in 0usize..100,
481            empty_response_strikes in 0usize..100,
482            nudge_count in 0usize..100,
483        ) {
484            let mut rs = RunState {
485                total_actions,
486                turn_actions,
487                run_has_actions,
488                run_actions: vec!["tool_a".into(), "tool_b".into()],
489                reasoning_only_strikes,
490                empty_response_strikes,
491                nudge_count,
492                thinking_disabled_for_rest_of_run: true,
493                original_thinking_enabled: true,
494                truncation_strikes: 5,
495                awaiting_human: true,
496            };
497            rs.reset_for_new_run();
498            // Session-lifetime count survives; run-level state is zeroed.
499            assert_eq!(rs.total_actions, total_actions);
500            assert_eq!(rs.turn_actions, 0);
501            assert!(!rs.run_has_actions);
502            assert!(rs.run_actions.is_empty());
503            assert_eq!(rs.reasoning_only_strikes, 0);
504            assert_eq!(rs.empty_response_strikes, 0);
505            assert_eq!(rs.nudge_count, 0);
506            assert_eq!(rs.truncation_strikes, 0);
507            assert!(!rs.thinking_disabled_for_rest_of_run);
508            assert!(!rs.awaiting_human);
509            // original_thinking_enabled is NOT reset
510            assert!(rs.original_thinking_enabled);
511        }
512
513        #[test]
514        fn record_actions_accumulates(n in 0usize..100) {
515            let mut rs = RunState::default();
516            rs.record_actions(n, &[]);
517            assert_eq!(rs.turn_actions, n);
518            assert_eq!(rs.total_actions, n);
519            assert!(rs.run_has_actions);
520            assert_eq!(rs.reasoning_only_strikes, 0);
521            assert_eq!(rs.empty_response_strikes, 0);
522        }
523
524        #[test]
525        fn record_reasoning_only_increments(count in 1usize..50) {
526            let mut rs = RunState::default();
527            for i in 1..=count {
528                let strikes = rs.record_reasoning_only();
529                assert_eq!(strikes, i);
530                assert_eq!(rs.empty_response_strikes, 0);
531            }
532        }
533
534        #[test]
535        fn record_empty_response_increments(count in 1usize..50) {
536            let mut rs = RunState::default();
537            for i in 1..=count {
538                let strikes = rs.record_empty_response();
539                assert_eq!(strikes, i);
540                assert_eq!(rs.reasoning_only_strikes, 0);
541            }
542        }
543    }
544}