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
96    /// The latest tool batch parked on a human step (a design-canvas screen
97    /// awaiting a pick) and no tool ran after it. Overwritten per batch by
98    /// `handle_tool_calls`. When true at the end of a run, the run is
99    /// *waiting for the user* — the guard must complete instead of nudging
100    /// "continue working" over their pending answer.
101    #[serde(default)]
102    pub awaiting_human: bool,
103}
104
105impl RunState {
106    /// Reset all run-level state for a new run (when a new user message arrives).
107    /// Session-lifetime state (`total_actions`, `original_thinking_enabled`)
108    /// is not reset.
109    pub fn reset_for_new_run(&mut self) {
110        self.turn_actions = 0;
111        self.run_has_actions = false;
112        self.run_actions.clear();
113        self.reasoning_only_strikes = 0;
114        self.empty_response_strikes = 0;
115        self.nudge_count = 0;
116        self.thinking_disabled_for_rest_of_run = false;
117        self.truncation_strikes = 0;
118        self.awaiting_human = false;
119        // Note: original_thinking_enabled is NOT reset here
120        // It should be set once when the session starts
121    }
122
123    /// Record executed actions (branch 3: actions ran).
124    /// Counts them against both the turn and the session total (D5: one
125    /// counting entry point, unit = actions) and resets reasoning_only_strikes,
126    /// empty_response_strikes, and truncation_strikes.
127    pub fn record_actions(&mut self, n: usize, names: &[String]) {
128        self.turn_actions += n;
129        self.total_actions += n;
130        self.run_has_actions = true;
131        self.run_actions.extend_from_slice(names);
132        self.reasoning_only_strikes = 0;
133        self.empty_response_strikes = 0;
134        self.truncation_strikes = 0;
135    }
136
137    /// Record reasoning-only response (branch 1).
138    /// Resets empty_response_strikes.
139    /// Returns the new strike count.
140    /// If strikes reach 3, disables thinking for the rest of the run (the
141    /// caller owns the observability for that flip — types stay I/O-free).
142    pub fn record_reasoning_only(&mut self) -> usize {
143        self.empty_response_strikes = 0;
144        self.reasoning_only_strikes += 1;
145        if self.reasoning_only_strikes >= 3 {
146            self.thinking_disabled_for_rest_of_run = true;
147        }
148        self.reasoning_only_strikes
149    }
150
151    /// Record empty response (branch 2).
152    /// Resets reasoning_only_strikes.
153    /// Returns the new strike count.
154    pub fn record_empty_response(&mut self) -> usize {
155        self.reasoning_only_strikes = 0;
156        self.empty_response_strikes += 1;
157        self.empty_response_strikes
158    }
159
160    /// Record a truncation guard firing (all tool_calls had invalid arguments).
161    /// Returns the new strike count. Caller should check against threshold.
162    pub fn record_truncation(&mut self) -> usize {
163        self.truncation_strikes += 1;
164        self.truncation_strikes
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    /// Value: protects=the run's tool trace reaches the completion judge, so
173    /// it can tell "the agent did the work and is reporting" from "the agent
174    /// said a few words and stopped"; fails_when=the trace is dropped and the
175    /// judge sees only `user_input` + `model_response` again.
176    /// why_new=no test today records *which* actions ran — `record_actions`
177    /// takes a bare count.
178    /// seam=none; no_claim=judge quality from the trace alone.
179    #[test]
180    fn record_actions_keeps_the_tool_trace_and_a_new_run_clears_it() {
181        let mut s = RunState::default();
182        s.record_actions(
183            3,
184            &[
185                "read_file".into(),
186                "execute_command".into(),
187                "read_file".into(),
188            ],
189        );
190        assert_eq!(s.run_actions, ["read_file", "execute_command", "read_file"]);
191        assert_eq!(s.total_actions, 3);
192        assert!(s.run_has_actions);
193
194        s.reset_for_new_run();
195        assert!(
196            s.run_actions.is_empty(),
197            "a new run must start with an empty trace"
198        );
199        assert!(!s.run_has_actions);
200    }
201
202    #[test]
203    fn run_state_default() {
204        let rs = RunState::default();
205        assert_eq!(rs.total_actions, 0);
206        assert_eq!(rs.turn_actions, 0);
207        assert!(!rs.run_has_actions);
208        assert_eq!(rs.reasoning_only_strikes, 0);
209        assert_eq!(rs.empty_response_strikes, 0);
210        assert_eq!(rs.nudge_count, 0);
211    }
212
213    #[test]
214    fn run_state_reset_for_new_run() {
215        let mut rs = RunState {
216            total_actions: 9,
217            turn_actions: 5,
218            run_has_actions: true,
219            reasoning_only_strikes: 2,
220            empty_response_strikes: 1,
221            nudge_count: 3,
222            thinking_disabled_for_rest_of_run: true,
223            original_thinking_enabled: true,
224            truncation_strikes: 4,
225            awaiting_human: true,
226        };
227
228        rs.reset_for_new_run();
229
230        // Session-lifetime state survives the run boundary.
231        assert_eq!(rs.total_actions, 9);
232        assert_eq!(rs.turn_actions, 0);
233        assert!(!rs.run_has_actions);
234        assert_eq!(rs.reasoning_only_strikes, 0);
235        assert_eq!(rs.empty_response_strikes, 0);
236        assert_eq!(rs.nudge_count, 0);
237        assert_eq!(rs.truncation_strikes, 0);
238        assert!(!rs.thinking_disabled_for_rest_of_run);
239        assert!(!rs.awaiting_human);
240        // original_thinking_enabled is NOT reset
241        assert!(rs.original_thinking_enabled);
242    }
243
244    #[test]
245    fn run_state_record_actions() {
246        let mut rs = RunState {
247            reasoning_only_strikes: 2,
248            empty_response_strikes: 1,
249            ..RunState::default()
250        };
251
252        rs.record_actions(3, &[]);
253
254        assert_eq!(rs.turn_actions, 3);
255        assert_eq!(rs.total_actions, 3);
256        assert!(rs.run_has_actions);
257        assert_eq!(rs.reasoning_only_strikes, 0); // reset
258        assert_eq!(rs.empty_response_strikes, 0); // reset
259    }
260
261    #[test]
262    fn run_state_record_actions_accumulates() {
263        let mut rs = RunState::default();
264        rs.record_actions(2, &[]);
265        rs.record_actions(3, &[]);
266
267        assert_eq!(rs.turn_actions, 5);
268        assert_eq!(rs.total_actions, 5);
269        assert!(rs.run_has_actions);
270    }
271
272    #[test]
273    fn run_state_record_reasoning_only() {
274        let mut rs = RunState {
275            empty_response_strikes: 2,
276            ..RunState::default()
277        };
278
279        let strikes = rs.record_reasoning_only();
280
281        assert_eq!(strikes, 1);
282        assert_eq!(rs.reasoning_only_strikes, 1);
283        assert_eq!(rs.empty_response_strikes, 0); // reset
284    }
285
286    #[test]
287    fn run_state_record_reasoning_only_consecutive() {
288        let mut rs = RunState::default();
289
290        assert_eq!(rs.record_reasoning_only(), 1);
291        assert_eq!(rs.record_reasoning_only(), 2);
292        assert_eq!(rs.record_reasoning_only(), 3);
293    }
294
295    #[test]
296    fn run_state_record_empty_response() {
297        let mut rs = RunState {
298            reasoning_only_strikes: 2,
299            ..RunState::default()
300        };
301
302        let strikes = rs.record_empty_response();
303
304        assert_eq!(strikes, 1);
305        assert_eq!(rs.empty_response_strikes, 1);
306        assert_eq!(rs.reasoning_only_strikes, 0); // reset
307    }
308
309    #[test]
310    fn run_state_record_empty_response_consecutive() {
311        let mut rs = RunState::default();
312
313        assert_eq!(rs.record_empty_response(), 1);
314        assert_eq!(rs.record_empty_response(), 2);
315        assert_eq!(rs.record_empty_response(), 3);
316    }
317
318    #[test]
319    fn run_state_branch_cross_reset() {
320        // Simulate: reasoning only → actions → reasoning only
321        let mut rs = RunState::default();
322
323        // Branch 1: reasoning only
324        rs.record_reasoning_only();
325        assert_eq!(rs.reasoning_only_strikes, 1);
326
327        // Branch 3: actions (should reset reasoning_only_strikes)
328        rs.record_actions(2, &[]);
329        assert_eq!(rs.reasoning_only_strikes, 0);
330        assert_eq!(rs.turn_actions, 2);
331
332        // Branch 1 again: reasoning only (should start from 1, not 2)
333        let strikes = rs.record_reasoning_only();
334        assert_eq!(strikes, 1);
335    }
336
337    #[test]
338    fn run_state_empty_to_reasoning_reset() {
339        // Simulate: empty → empty → reasoning only (should reset empty strikes)
340        let mut rs = RunState::default();
341
342        rs.record_empty_response();
343        rs.record_empty_response();
344        assert_eq!(rs.empty_response_strikes, 2);
345
346        // Branch 1: reasoning only (should reset empty_response_strikes)
347        rs.record_reasoning_only();
348        assert_eq!(rs.empty_response_strikes, 0);
349        assert_eq!(rs.reasoning_only_strikes, 1);
350    }
351
352    #[test]
353    fn run_state_thinking_disabled_default() {
354        let rs = RunState::default();
355        assert!(!rs.thinking_disabled_for_rest_of_run);
356    }
357
358    #[test]
359    fn run_state_thinking_disabled_after_3_strikes() {
360        let mut rs = RunState::default();
361
362        // After 1st reasoning-only: not disabled
363        rs.record_reasoning_only();
364        assert!(!rs.thinking_disabled_for_rest_of_run);
365        assert_eq!(rs.reasoning_only_strikes, 1);
366
367        // After 2nd reasoning-only: not disabled
368        rs.record_reasoning_only();
369        assert!(!rs.thinking_disabled_for_rest_of_run);
370        assert_eq!(rs.reasoning_only_strikes, 2);
371
372        // After 3rd reasoning-only: disabled!
373        rs.record_reasoning_only();
374        assert!(rs.thinking_disabled_for_rest_of_run);
375        assert_eq!(rs.reasoning_only_strikes, 3);
376    }
377
378    #[test]
379    fn run_state_thinking_disabled_resets_on_new_run() {
380        let mut rs = RunState::default();
381
382        // Simulate 3 reasoning-only responses
383        rs.record_reasoning_only();
384        rs.record_reasoning_only();
385        rs.record_reasoning_only();
386        assert!(rs.thinking_disabled_for_rest_of_run);
387        assert_eq!(rs.reasoning_only_strikes, 3);
388
389        // Reset for new run (new user message)
390        rs.reset_for_new_run();
391        assert!(!rs.thinking_disabled_for_rest_of_run);
392        assert_eq!(rs.reasoning_only_strikes, 0);
393    }
394
395    #[test]
396    fn run_state_thinking_disabled_stays_after_actions() {
397        let mut rs = RunState::default();
398
399        // Simulate 3 reasoning-only responses
400        rs.record_reasoning_only();
401        rs.record_reasoning_only();
402        rs.record_reasoning_only();
403        assert!(rs.thinking_disabled_for_rest_of_run);
404
405        // Actions should NOT reset thinking_disabled_for_rest_of_run
406        // (it should stay disabled for the rest of the run)
407        rs.record_actions(2, &[]);
408        assert!(rs.thinking_disabled_for_rest_of_run);
409        assert_eq!(rs.reasoning_only_strikes, 0); // strikes reset, but thinking stays disabled
410    }
411
412    #[test]
413    fn pre_t7_wire_keys_are_read_through_aliases() {
414        // A P2-era `run_state` payload: the counting fields still spelled
415        // "tool calls". The aliases keep that corpus readable verbatim.
416        let json = r#"{
417            "turn_tool_calls": 4,
418            "run_has_tool_calls": true,
419            "reasoning_only_strikes": 0,
420            "empty_response_strikes": 1,
421            "nudge_count": 2
422        }"#;
423        let rs: RunState = serde_json::from_str(json).unwrap();
424        assert_eq!(rs.turn_actions, 4);
425        assert!(rs.run_has_actions);
426        assert_eq!(rs.empty_response_strikes, 1);
427        assert_eq!(rs.nudge_count, 2);
428    }
429
430    #[test]
431    fn run_state_round_trips_under_the_new_wire_keys() {
432        let mut rs = RunState::default();
433        rs.record_actions(3, &[]);
434        let json = serde_json::to_string(&rs).unwrap();
435        assert!(json.contains("\"total_actions\":3"), "new key: {json}");
436        assert!(json.contains("\"turn_actions\":3"), "new key: {json}");
437        assert!(json.contains("\"run_has_actions\":true"), "new key: {json}");
438        let decoded: RunState = serde_json::from_str(&json).unwrap();
439        assert_eq!(decoded.turn_actions, 3);
440        assert_eq!(decoded.total_actions, 3);
441        assert!(decoded.run_has_actions);
442    }
443}
444
445#[cfg(test)]
446mod proptest_tests {
447    use super::*;
448    use proptest::prelude::*;
449
450    proptest! {
451        #[test]
452        fn reset_for_new_run_zeros_run_fields(
453            total_actions in 0usize..1000,
454            turn_actions in 0usize..1000,
455            run_has_actions in proptest::bool::ANY,
456            reasoning_only_strikes in 0usize..100,
457            empty_response_strikes in 0usize..100,
458            nudge_count in 0usize..100,
459        ) {
460            let mut rs = RunState {
461                total_actions,
462                turn_actions,
463                run_has_actions,
464                reasoning_only_strikes,
465                empty_response_strikes,
466                nudge_count,
467                thinking_disabled_for_rest_of_run: true,
468                original_thinking_enabled: true,
469                truncation_strikes: 5,
470                awaiting_human: true,
471            };
472            rs.reset_for_new_run();
473            // Session-lifetime count survives; run-level state is zeroed.
474            assert_eq!(rs.total_actions, total_actions);
475            assert_eq!(rs.turn_actions, 0);
476            assert!(!rs.run_has_actions);
477            assert_eq!(rs.reasoning_only_strikes, 0);
478            assert_eq!(rs.empty_response_strikes, 0);
479            assert_eq!(rs.nudge_count, 0);
480            assert_eq!(rs.truncation_strikes, 0);
481            assert!(!rs.thinking_disabled_for_rest_of_run);
482            assert!(!rs.awaiting_human);
483            // original_thinking_enabled is NOT reset
484            assert!(rs.original_thinking_enabled);
485        }
486
487        #[test]
488        fn record_actions_accumulates(n in 0usize..100) {
489            let mut rs = RunState::default();
490            rs.record_actions(n, &[]);
491            assert_eq!(rs.turn_actions, n);
492            assert_eq!(rs.total_actions, n);
493            assert!(rs.run_has_actions);
494            assert_eq!(rs.reasoning_only_strikes, 0);
495            assert_eq!(rs.empty_response_strikes, 0);
496        }
497
498        #[test]
499        fn record_reasoning_only_increments(count in 1usize..50) {
500            let mut rs = RunState::default();
501            for i in 1..=count {
502                let strikes = rs.record_reasoning_only();
503                assert_eq!(strikes, i);
504                assert_eq!(rs.empty_response_strikes, 0);
505            }
506        }
507
508        #[test]
509        fn record_empty_response_increments(count in 1usize..50) {
510            let mut rs = RunState::default();
511            for i in 1..=count {
512                let strikes = rs.record_empty_response();
513                assert_eq!(strikes, i);
514                assert_eq!(rs.reasoning_only_strikes, 0);
515            }
516        }
517    }
518}