Skip to main content

agent_base/engine/
session.rs

1use std::collections::HashSet;
2
3use serde::{Deserialize, Serialize};
4
5use crate::types::{ChatMessage, ImageAttachment, Message, MessageRole, ToolCallMessage};
6
7use crate::types::SessionId;
8
9/// Run-level state tracking for the react loop.
10///
11/// Manages counters and flags that track the current run's progress.
12/// All fields are reset at the start of each run (when a new user message arrives).
13///
14/// # Backward compatibility
15///
16/// Before this struct existed, `nudge_count` and `turn_tool_calls` were flat
17/// fields on `AgentSession`.  The [`RawAgentSession`] deserialization shim
18/// migrates them automatically.
19#[derive(Clone, Debug, Default, Serialize, Deserialize)]
20pub struct RunState {
21    /// Number of tool calls already executed in the current turn.
22    /// Reset to 0 at the start of each turn (when a new user message arrives).
23    /// Used by `TurnToolLimitMiddleware` to enforce per-turn tool call limits.
24    pub turn_tool_calls: usize,
25    /// Whether any tools were called in the current run.
26    /// Reset to false at the start of each run. Used by the completion judge
27    /// to determine if tools were used before a text-only response.
28    pub run_has_tool_calls: bool,
29    /// Number of consecutive LLM turns that produced only reasoning_content
30    /// (no text, no tool call). Reset to 0 when a normal response or tool call
31    /// is produced. Used by the react loop to fail instead of looping forever
32    /// on a reasoning-model runaway.
33    pub reasoning_only_strikes: usize,
34    /// Number of consecutive LLM turns that produced a completely empty response
35    /// (no text, no reasoning, no tool call). Reset to 0 when a normal response
36    /// or tool call is produced. Used by the react loop to retry a bounded
37    /// number of times, then fail instead of looping forever.
38    pub empty_response_strikes: usize,
39    /// Number of tool-enforcement nudges issued in the current turn.
40    /// Reset to 0 at the start of each turn (when a new user message arrives).
41    /// Used by `ToolEnforcementMiddleware` to cap nudge attempts per turn.
42    pub nudge_count: usize,
43    /// Thinking is disabled for the rest of the current run.
44    /// Set to true when reasoning_only_strikes reaches the maximum (3).
45    /// Reset to false at the start of each new run (when a new user message arrives).
46    /// This allows the model to continue without thinking after too many
47    /// reasoning-only responses.
48    #[serde(default)]
49    pub thinking_disabled_for_rest_of_run: bool,
50
51    // ─── New fields for thinking guard ─────────────────────────────
52    /// Original thinking configuration (for restoration)
53    ///
54    /// Records whether thinking was originally enabled when the session started.
55    /// Used to restore thinking to its original state after DisableThinking → RestoreThinking cycle.
56    #[serde(default)]
57    pub original_thinking_enabled: bool,
58
59    /// Number of consecutive LLM turns where the truncation guard fired
60    /// (all tool_calls had invalid/truncated arguments). Reset to 0 when
61    /// at least one valid tool call executes successfully. Used to break
62    /// the re-issue death spiral: after N consecutive truncations, stop
63    /// retrying and fail with an actionable message.
64    #[serde(default)]
65    pub truncation_strikes: usize,
66}
67
68impl RunState {
69    /// Reset all run-level state for a new run (when a new user message arrives).
70    pub fn reset_for_new_run(&mut self) {
71        self.turn_tool_calls = 0;
72        self.run_has_tool_calls = false;
73        self.reasoning_only_strikes = 0;
74        self.empty_response_strikes = 0;
75        self.nudge_count = 0;
76        self.thinking_disabled_for_rest_of_run = false;
77        self.truncation_strikes = 0;
78        // Note: original_thinking_enabled is NOT reset here
79        // It should be set once when the session starts
80    }
81
82    /// Record tool calls (branch 3: tool calls).
83    /// Resets reasoning_only_strikes, empty_response_strikes, and truncation_strikes.
84    pub fn record_tool_calls(&mut self, n: usize) {
85        self.turn_tool_calls += n;
86        self.run_has_tool_calls = true;
87        self.reasoning_only_strikes = 0;
88        self.empty_response_strikes = 0;
89        self.truncation_strikes = 0;
90    }
91
92    /// Record reasoning-only response (branch 1).
93    /// Resets empty_response_strikes.
94    /// Returns the new strike count.
95    /// If strikes reach 3, disables thinking for the rest of the run.
96    pub fn record_reasoning_only(&mut self) -> usize {
97        self.empty_response_strikes = 0;
98        self.reasoning_only_strikes += 1;
99        if self.reasoning_only_strikes >= 3 {
100            tracing::info!(
101                strikes = self.reasoning_only_strikes,
102                "reasoning_only_strikes reached 3, disabling thinking for rest of run"
103            );
104            self.thinking_disabled_for_rest_of_run = true;
105        }
106        self.reasoning_only_strikes
107    }
108
109    /// Record empty response (branch 2).
110    /// Resets reasoning_only_strikes.
111    /// Returns the new strike count.
112    pub fn record_empty_response(&mut self) -> usize {
113        self.reasoning_only_strikes = 0;
114        self.empty_response_strikes += 1;
115        self.empty_response_strikes
116    }
117
118    /// Record a truncation guard firing (all tool_calls had invalid arguments).
119    /// Returns the new strike count. Caller should check against threshold.
120    pub fn record_truncation(&mut self) -> usize {
121        self.truncation_strikes += 1;
122        self.truncation_strikes
123    }
124}
125
126/// Deserialization shim for backward compatibility.
127///
128/// Before `RunState` was introduced, `nudge_count`, `turn_tool_calls`,
129/// `reasoning_only_strikes`, and `empty_response_strikes` were flat fields
130/// on `AgentSession`.  This struct accepts **both** the old flat format and
131/// the new nested `run_state` format, migrating legacy data on the fly.
132#[derive(Deserialize)]
133struct RawAgentSession {
134    id: Option<SessionId>,
135    chat_messages: Vec<ChatMessage>,
136    always_allowed_actions: HashSet<String>,
137    total_tool_calls: usize,
138
139    // ── new format (preferred) ──
140    run_state: Option<RunState>,
141
142    // ── legacy flat fields (fallback) ──
143    nudge_count: Option<usize>,
144    turn_tool_calls: Option<usize>,
145    reasoning_only_strikes: Option<usize>,
146    empty_response_strikes: Option<usize>,
147}
148
149impl From<RawAgentSession> for AgentSession {
150    fn from(raw: RawAgentSession) -> Self {
151        let run_state = raw.run_state.unwrap_or_else(|| RunState {
152            nudge_count: raw.nudge_count.unwrap_or(0),
153            turn_tool_calls: raw.turn_tool_calls.unwrap_or(0),
154            reasoning_only_strikes: raw.reasoning_only_strikes.unwrap_or(0),
155            empty_response_strikes: raw.empty_response_strikes.unwrap_or(0),
156            ..RunState::default()
157        });
158        Self {
159            id: raw.id,
160            chat_messages: raw.chat_messages,
161            always_allowed_actions: raw.always_allowed_actions,
162            total_tool_calls: raw.total_tool_calls,
163            run_state,
164        }
165    }
166}
167
168/// Stable identity + rolling state of a single chat thread.
169///
170/// `Default` returns a fresh session; load persisted state via serde.
171/// Backward-compatible with the old flat-field format (pre-`RunState` migration).
172#[derive(Clone, Debug, Default, Serialize, Deserialize)]
173#[serde(from = "RawAgentSession")]
174pub struct AgentSession {
175    id: Option<SessionId>,
176    /// LLM API format messages, sent directly to the provider.
177    /// This is the single source of truth for the conversation state.
178    chat_messages: Vec<ChatMessage>,
179    always_allowed_actions: HashSet<String>,
180    /// Total number of tool calls made in this session (across all turns).
181    /// Used by middleware for decisions like "first_turn_only" enforcement.
182    pub total_tool_calls: usize,
183    /// Run-level state tracking for the react loop.
184    pub run_state: RunState,
185}
186
187impl AgentSession {
188    pub fn new(id: SessionId) -> Self {
189        Self {
190            id: Some(id),
191            chat_messages: Vec::new(),
192            always_allowed_actions: HashSet::new(),
193            total_tool_calls: 0,
194            run_state: RunState::default(),
195        }
196    }
197
198    pub fn id(&self) -> Option<SessionId> {
199        self.id.clone()
200    }
201
202    /// Derive a simplified `Vec<Message>` view from the canonical `chat_messages`.
203    /// Assistant messages that contain only tool_calls (no text content) are
204    /// skipped, since they have no corresponding simplified representation.
205    pub fn simple_messages(&self) -> Vec<Message> {
206        self.chat_messages
207            .iter()
208            .filter_map(|cm| match cm {
209                ChatMessage::Assistant { content: None, .. } => None,
210                ChatMessage::Assistant {
211                    content: Some(c),
212                    tool_calls: Some(tc),
213                    ..
214                } if c.is_empty() && !tc.is_empty() => None,
215                _ => Some(Message::from(cm)),
216            })
217            .collect()
218    }
219
220    pub fn chat_messages(&self) -> &[ChatMessage] {
221        &self.chat_messages
222    }
223
224    /// Mutable reference, for advanced scenarios that need to operate on messages directly.
225    pub fn chat_messages_mut(&mut self) -> &mut Vec<ChatMessage> {
226        &mut self.chat_messages
227    }
228
229    pub fn is_action_allowed(&self, action_key: &str) -> bool {
230        self.always_allowed_actions.contains(action_key)
231    }
232
233    pub fn allow_action(&mut self, action_key: impl Into<String>) {
234        self.always_allowed_actions.insert(action_key.into());
235    }
236
237    pub fn push_message(&mut self, role: MessageRole, content: impl Into<String>) {
238        let content = content.into();
239        let chat_msg = match role {
240            MessageRole::System => ChatMessage::system(content),
241            MessageRole::User => ChatMessage::user(content),
242            MessageRole::Assistant => ChatMessage::assistant(content),
243            MessageRole::Tool => ChatMessage::tool(String::new(), content),
244        };
245        self.chat_messages.push(chat_msg);
246    }
247
248    /// Push a message as ephemeral (user/system only): the LLM sees it this
249    /// turn, then `remove_ephemeral_messages` strips it at turn end — from
250    /// both memory and persistence.
251    pub fn push_message_ephemeral(&mut self, role: MessageRole, content: impl Into<String>) {
252        let content = content.into();
253        let chat_msg = match role {
254            MessageRole::System => ChatMessage::system_ephemeral(content),
255            MessageRole::User => ChatMessage::user_ephemeral(content),
256            MessageRole::Assistant | MessageRole::Tool => {
257                // Ephemeral assistant/tool messages are not a thing; fall back
258                // to a regular push rather than silently mis-marking.
259                self.push_message(role, content);
260                return;
261            }
262        };
263        self.chat_messages.push(chat_msg);
264    }
265
266    /// Replace the system prompt — the first **non-ephemeral** System message
267    /// (wherever it sits, matching how `context` locates it); inserted at
268    /// index 0 if none exists. All other messages are untouched. Hosts that
269    /// own prompt composition (e.g. skill activation) re-bake through this.
270    pub fn set_system_prompt(&mut self, content: impl Into<String>) {
271        let content = content.into();
272        if let Some(idx) = self.chat_messages.iter().position(|m| {
273            matches!(
274                m,
275                ChatMessage::System {
276                    ephemeral: false,
277                    ..
278                }
279            )
280        }) {
281            self.chat_messages[idx] = ChatMessage::system(content);
282        } else {
283            self.chat_messages.insert(0, ChatMessage::system(content));
284        }
285    }
286
287    /// Push an assistant message with reasoning/thinking content preserved.
288    /// This allows the LLM to see its own prior reasoning in subsequent turns,
289    /// preventing it from re-deriving the same conclusions every turn.
290    pub fn push_assistant_with_reasoning(
291        &mut self,
292        content: impl Into<String>,
293        reasoning: impl Into<String>,
294    ) {
295        self.chat_messages
296            .push(ChatMessage::assistant_with_reasoning(content, reasoning));
297    }
298
299    pub fn push_user_message_with_images(
300        &mut self,
301        content: impl Into<String>,
302        images: Vec<ImageAttachment>,
303    ) {
304        self.chat_messages
305            .push(ChatMessage::user_with_images(content, images));
306    }
307
308    pub fn push_assistant_tool_call(
309        &mut self,
310        tool_call_id: &str,
311        tool_name: &str,
312        arguments_json: &str,
313    ) {
314        self.chat_messages.push(ChatMessage::assistant_tool_call(
315            tool_call_id,
316            tool_name,
317            arguments_json,
318        ));
319    }
320
321    /// Escape and truncate the arguments to their first `max_chars` characters, so the
322    /// truncation WARN can display the raw content directly. Rust debug escaping keeps
323    /// unclosed JSON, control characters, and CJK boundaries clearly distinguishable, so
324    /// troubleshooting provider truncation in production no longer requires indirectly
325    /// reconstructing the content.
326    fn preview_args(args: &str, max_chars: usize) -> String {
327        format!("{:?}", args.chars().take(max_chars).collect::<String>())
328    }
329
330    pub fn push_assistant_tool_calls(
331        &mut self,
332        tool_calls: &[(String, String, String)],
333        reasoning: Option<String>,
334        content: Option<String>,
335    ) {
336        let calls: Vec<ToolCallMessage> = tool_calls
337            .iter()
338            .map(|(id, name, args)| {
339                // Invalid JSON args (provider truncated the stream mid-generation)
340                // are sanitized to an empty object. We deliberately do NOT wrap
341                // them in a descriptive `{error, original_args_preview, message}`
342                // object: "{}" is valid JSON so the next request is never rejected
343                // with 400, and — critically — a rich error object here becomes an
344                // imitation vector: the model replays it verbatim as the next
345                // call's arguments and, because it parses, it slips past the react
346                // truncation guard. The truncation explanation lives in the
347                // paired tool_result, which is where the model reads feedback.
348                let valid_args = if serde_json::from_str::<serde_json::Value>(args).is_ok() {
349                    args.clone()
350                } else {
351                    tracing::warn!(
352                        tool_name = %name,
353                        args_len = args.len(),
354                        args_preview = %Self::preview_args(args, 80),
355                        "tool call arguments are not valid JSON (provider truncated them), \
356                         sanitizing to empty object; re-issue instruction goes to the tool_result"
357                    );
358                    "{}".to_string()
359                };
360                ToolCallMessage {
361                    id: id.clone(),
362                    name: name.clone(),
363                    arguments: valid_args,
364                }
365            })
366            .collect();
367        self.chat_messages.push(ChatMessage::Assistant {
368            content,
369            reasoning_content: reasoning,
370            tool_calls: Some(calls),
371            thinking_signature: None,
372        });
373    }
374
375    pub fn push_tool_result(&mut self, tool_call_id: &str, content: impl Into<String>) {
376        self.chat_messages
377            .push(ChatMessage::tool(tool_call_id, content));
378    }
379
380    /// Remove all ephemeral messages (ephemeral=true).
381    ///
382    /// Called at the end of a turn to ensure injected ephemeral content does not linger into the next turn.
383    pub fn remove_ephemeral_messages(&mut self) {
384        let before = self.chat_messages.len();
385        self.chat_messages.retain(|m| !m.is_ephemeral());
386        let removed = before - self.chat_messages.len();
387        if removed > 0 {
388            tracing::debug!(
389                removed,
390                remaining = self.chat_messages.len(),
391                "ephemeral messages cleaned up"
392            );
393        }
394    }
395
396    /// Count the number of conversation turns.
397    /// A turn starts with a User message and includes subsequent Assistant/Tool messages.
398    pub fn turn_count(&self) -> usize {
399        self.chat_messages
400            .iter()
401            .filter(|m| matches!(m, ChatMessage::User { .. }))
402            .count()
403    }
404
405    /// Remove the oldest turns from the front until turn count ≤ max_turns.
406    /// Preserves the System message at index 0 if present.
407    pub fn trim_oldest_turns(&mut self, max_turns: usize) {
408        let current_turns = self.turn_count();
409        if current_turns <= max_turns {
410            return;
411        }
412        let turns_to_remove = current_turns - max_turns;
413
414        // Find User message positions (turn boundaries) in chat_messages
415        let user_positions: Vec<usize> = self
416            .chat_messages
417            .iter()
418            .enumerate()
419            .filter_map(|(i, m)| {
420                if matches!(m, ChatMessage::User { .. }) {
421                    Some(i)
422                } else {
423                    None
424                }
425            })
426            .collect();
427
428        if user_positions.len() <= turns_to_remove {
429            return;
430        }
431
432        // Preserve system prefix: count leading System messages
433        let system_prefix = self
434            .chat_messages
435            .iter()
436            .take_while(|m| matches!(m, ChatMessage::System { .. }))
437            .count();
438
439        // Drain from system_prefix up to the start of the (turns_to_remove + 1)-th turn
440        let drain_end = user_positions[turns_to_remove];
441        if system_prefix >= drain_end {
442            return; // nothing to drain after system messages
443        }
444
445        self.chat_messages.drain(system_prefix..drain_end);
446    }
447
448    /// Remove the last message from `chat_messages`.
449    /// Used by the max_message_tokens safety valve to discard oversized messages.
450    pub fn pop_last_message(&mut self) {
451        self.chat_messages.pop();
452    }
453
454    pub fn close_dangling_tool_calls(&mut self, error_summary: &str) {
455        let assistant_idx = self.chat_messages.iter().rposition(
456            |m| matches!(m, ChatMessage::Assistant { tool_calls: Some(tc), .. } if !tc.is_empty()),
457        );
458
459        let Some(assistant_idx) = assistant_idx else {
460            return;
461        };
462
463        let ChatMessage::Assistant {
464            tool_calls: Some(tc),
465            ..
466        } = &self.chat_messages[assistant_idx]
467        else {
468            return;
469        };
470
471        let all_ids: Vec<String> = tc.iter().map(|t| t.id.clone()).collect();
472
473        let answered_ids: Vec<String> = self.chat_messages[assistant_idx + 1..]
474            .iter()
475            .filter_map(|m| match m {
476                ChatMessage::Tool { tool_call_id, .. } => Some(tool_call_id.clone()),
477                _ => None,
478            })
479            .collect();
480
481        for id in &all_ids {
482            if !answered_ids.iter().any(|a| a == id) {
483                self.push_tool_result(id, error_summary);
484            }
485        }
486    }
487
488    /// Replace chat messages — only for persistence restore.
489    /// Validates message sequence before replacing.
490    ///
491    /// For persistence restore use only. Callers must ensure the `messages` sequence is valid.
492    pub fn set_chat_messages(&mut self, messages: Vec<ChatMessage>) -> Result<(), String> {
493        validate_message_sequence(&messages)?;
494        // Recalculate total_tool_calls from the incoming messages so middleware
495        // decisions (e.g. first_turn_only enforcement) see the correct count.
496        self.total_tool_calls = messages
497            .iter()
498            .filter_map(|m| match m {
499                ChatMessage::Assistant {
500                    tool_calls: Some(tc),
501                    ..
502                } => Some(tc.len()),
503                _ => None,
504            })
505            .sum();
506        self.chat_messages = messages;
507        Ok(())
508    }
509}
510
511/// Validate that a chat message sequence is well-formed for LLM API consumption.
512///
513/// Checks:
514/// - At least one non-System/non-Custom message (System maps to the
515///   top-level `system` parameter, Custom is stripped — a sequence of only
516///   those leaves an empty `messages` array, which providers reject with
517///   HTTP 400). Guards compaction outputs against producing an unsendable
518///   window.
519/// - No Tool message without a preceding Assistant with matching tool_call
520/// - No duplicate Tool messages for the same tool_call_id
521/// - All tool_calls in an Assistant batch must be answered before the next Assistant batch
522/// - No unanswered tool calls at the end of the sequence
523pub fn validate_message_sequence(messages: &[ChatMessage]) -> Result<(), String> {
524    if !messages
525        .iter()
526        .any(|m| !matches!(m, ChatMessage::System { .. } | ChatMessage::Custom { .. }))
527    {
528        return Err(
529            "sequence contains no sendable message: System/Custom alone leave the \
530             provider `messages` array empty"
531                .to_string(),
532        );
533    }
534
535    let mut pending_tool_call_ids: HashSet<String> = HashSet::new();
536
537    for (i, msg) in messages.iter().enumerate() {
538        match msg {
539            ChatMessage::Tool { tool_call_id, .. } => {
540                if pending_tool_call_ids.is_empty() {
541                    return Err(format!(
542                        "message[{}]: Tool message with call_id '{}' has no preceding tool_call",
543                        i, tool_call_id
544                    ));
545                }
546                // Remove the ID on match — also detects duplicates (second remove returns false)
547                if !pending_tool_call_ids.remove(tool_call_id) {
548                    return Err(format!(
549                        "message[{}]: Tool message with call_id '{}' does not match any pending tool_call (already answered or unknown)",
550                        i, tool_call_id
551                    ));
552                }
553            }
554            ChatMessage::Assistant {
555                tool_calls: Some(tc),
556                ..
557            } => {
558                // Previous batch must be fully answered before a new batch starts
559                if !pending_tool_call_ids.is_empty() {
560                    return Err(format!(
561                        "message[{}]: Assistant message with new tool_calls appears before pending calls were answered: {:?}",
562                        i, pending_tool_call_ids
563                    ));
564                }
565                pending_tool_call_ids = tc.iter().map(|t| t.id.clone()).collect();
566            }
567            _ => {}
568        }
569    }
570
571    // All tool calls must be answered by the end of the sequence
572    if !pending_tool_call_ids.is_empty() {
573        return Err(format!(
574            "message sequence ends with unanswered tool calls: {:?}",
575            pending_tool_call_ids
576        ));
577    }
578
579    Ok(())
580}
581
582#[cfg(test)]
583fn make_session() -> AgentSession {
584    AgentSession::new(SessionId::new(1))
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590
591    #[test]
592    fn test_turn_count_empty() {
593        let s = make_session();
594        assert_eq!(s.turn_count(), 0);
595    }
596
597    #[test]
598    fn test_turn_count_with_system_and_user() {
599        let mut s = make_session();
600        s.push_message(MessageRole::System, "system");
601        assert_eq!(s.turn_count(), 0);
602        s.push_message(MessageRole::User, "hello");
603        assert_eq!(s.turn_count(), 1);
604        s.push_message(MessageRole::Assistant, "hi");
605        assert_eq!(s.turn_count(), 1);
606        s.push_message(MessageRole::User, "bye");
607        assert_eq!(s.turn_count(), 2);
608    }
609
610    #[test]
611    fn test_turn_count_with_tool_calls() {
612        let mut s = make_session();
613        s.push_message(MessageRole::User, "do something");
614        s.push_assistant_tool_calls(&[("id1".into(), "tool".into(), "{}".into())], None, None);
615        s.push_tool_result("id1", "result");
616        s.push_message(MessageRole::Assistant, "done");
617        // One user turn: User -> Assistant(tool_calls) -> Tool -> Assistant(text)
618        assert_eq!(s.turn_count(), 1);
619    }
620
621    #[test]
622    fn test_trim_oldest_turns_noop() {
623        let mut s = make_session();
624        s.push_message(MessageRole::User, "hello");
625        s.push_message(MessageRole::Assistant, "hi");
626        s.trim_oldest_turns(5);
627        assert_eq!(s.turn_count(), 1);
628        assert_eq!(s.chat_messages().len(), 2);
629    }
630
631    #[test]
632    fn test_trim_oldest_turns_removes_old() {
633        let mut s = make_session();
634        s.push_message(MessageRole::System, "sys");
635        // Turn 1
636        s.push_message(MessageRole::User, "u1");
637        s.push_message(MessageRole::Assistant, "a1");
638        // Turn 2
639        s.push_message(MessageRole::User, "u2");
640        s.push_message(MessageRole::Assistant, "a2");
641        // Turn 3
642        s.push_message(MessageRole::User, "u3");
643        s.push_message(MessageRole::Assistant, "a3");
644
645        s.trim_oldest_turns(2);
646        assert_eq!(s.turn_count(), 2);
647        // System message preserved
648        assert!(matches!(s.chat_messages()[0], ChatMessage::System { .. }));
649        // Oldest user message is u2
650        assert!(
651            matches!(s.chat_messages()[1], ChatMessage::User { ref content, .. } if content == "u2")
652        );
653    }
654
655    #[test]
656    fn test_trim_oldest_turns_with_tool_calls() {
657        let mut s = make_session();
658        // Turn 1 with tool call
659        s.push_message(MessageRole::User, "u1");
660        s.push_assistant_tool_calls(&[("id1".into(), "t".into(), "{}".into())], None, None);
661        s.push_tool_result("id1", "r1");
662        s.push_message(MessageRole::Assistant, "a1");
663        // Turn 2
664        s.push_message(MessageRole::User, "u2");
665        s.push_message(MessageRole::Assistant, "a2");
666
667        let msg_before = s.simple_messages().len();
668        let chat_before = s.chat_messages().len();
669        s.trim_oldest_turns(1);
670        assert_eq!(s.turn_count(), 1);
671        // chat_messages should have lost 4 entries (User, Assistant(tool), Tool, Assistant(text))
672        assert_eq!(s.chat_messages().len(), chat_before - 4);
673        // simple_messages (derived from chat_messages, tool_calls-only filtered) loses 3 entries
674        assert_eq!(s.simple_messages().len(), msg_before - 3);
675    }
676
677    #[test]
678    fn test_pop_last_message_text() {
679        let mut s = make_session();
680        s.push_message(MessageRole::User, "hello");
681        s.push_message(MessageRole::Assistant, "hi");
682        assert_eq!(s.chat_messages().len(), 2);
683        s.pop_last_message();
684        assert_eq!(s.chat_messages().len(), 1);
685        assert_eq!(s.simple_messages().len(), 1);
686    }
687
688    #[test]
689    fn test_pop_last_message_tool_calls_only() {
690        let mut s = make_session();
691        s.push_message(MessageRole::User, "do it");
692        s.push_assistant_tool_calls(&[("id1".into(), "t".into(), "{}".into())], None, None);
693        assert_eq!(s.chat_messages().len(), 2);
694        assert_eq!(s.simple_messages().len(), 1); // only User in simple_messages (tool_calls-only filtered)
695        s.pop_last_message();
696        assert_eq!(s.chat_messages().len(), 1);
697        assert_eq!(s.simple_messages().len(), 1); // simple_messages unchanged (still just User)
698    }
699
700    #[test]
701    fn test_pop_last_message_empty_session() {
702        let mut s = make_session();
703        s.pop_last_message(); // should not panic
704        assert_eq!(s.chat_messages().len(), 0);
705    }
706
707    // ── B5: remaining session lifecycle paths ──────────────────────────────
708
709    #[test]
710    fn test_id_and_action_allowlist() {
711        let mut s = make_session();
712        assert_eq!(s.id(), Some(SessionId::new(1)));
713        assert!(!s.is_action_allowed("approve:rm"));
714        s.allow_action("approve:rm");
715        assert!(s.is_action_allowed("approve:rm"));
716        assert!(!s.is_action_allowed("approve:shell"));
717    }
718
719    #[test]
720    fn test_chat_messages_mut() {
721        let mut s = make_session();
722        s.chat_messages_mut().push(ChatMessage::user("direct"));
723        assert_eq!(s.chat_messages().len(), 1);
724    }
725
726    #[test]
727    fn test_push_message_tool_role() {
728        let mut s = make_session();
729        s.push_message(MessageRole::Tool, "result");
730        assert!(matches!(s.chat_messages()[0], ChatMessage::Tool { .. }));
731    }
732
733    #[test]
734    fn test_push_assistant_with_reasoning() {
735        let mut s = make_session();
736        s.push_assistant_with_reasoning("answer", "thinking");
737        match &s.chat_messages()[0] {
738            ChatMessage::Assistant {
739                content,
740                reasoning_content,
741                ..
742            } => {
743                assert_eq!(content.as_deref(), Some("answer"));
744                assert_eq!(reasoning_content.as_deref(), Some("thinking"));
745            }
746            other => panic!("unexpected message: {other:?}"),
747        }
748    }
749
750    #[test]
751    fn test_push_user_message_with_images() {
752        let mut s = make_session();
753        s.push_user_message_with_images(
754            "look",
755            vec![ImageAttachment::Url {
756                url: "http://x".into(),
757                detail: None,
758            }],
759        );
760        match &s.chat_messages()[0] {
761            ChatMessage::User { images, .. } => assert_eq!(images.len(), 1),
762            other => panic!("unexpected message: {other:?}"),
763        }
764    }
765
766    #[test]
767    fn test_push_assistant_tool_call_singular() {
768        let mut s = make_session();
769        s.push_assistant_tool_call("call_1", "bash", "{}");
770        match &s.chat_messages()[0] {
771            ChatMessage::Assistant {
772                tool_calls: Some(tc),
773                ..
774            } => {
775                assert_eq!(tc.len(), 1);
776                assert_eq!(tc[0].id, "call_1");
777                assert_eq!(tc[0].name, "bash");
778            }
779            other => panic!("unexpected message: {other:?}"),
780        }
781    }
782
783    #[test]
784    fn test_simple_messages_filters_empty_content_tool_calls() {
785        let mut s = make_session();
786        s.chat_messages_mut().push(ChatMessage::Assistant {
787            content: Some(String::new()),
788            reasoning_content: None,
789            tool_calls: Some(vec![ToolCallMessage {
790                id: "c".into(),
791                name: "t".into(),
792                arguments: "{}".into(),
793            }]),
794            thinking_signature: None,
795        });
796        assert!(s.simple_messages().is_empty());
797    }
798
799    #[test]
800    fn test_remove_ephemeral_messages() {
801        let mut s = make_session();
802        s.push_message(MessageRole::System, "keep");
803        s.chat_messages_mut()
804            .push(ChatMessage::user_ephemeral("temp"));
805        s.chat_messages_mut()
806            .push(ChatMessage::system_ephemeral("temp2"));
807        s.push_message(MessageRole::User, "keep2");
808        assert_eq!(s.chat_messages().len(), 4);
809        s.remove_ephemeral_messages();
810        assert_eq!(s.chat_messages().len(), 2);
811        assert!(s.chat_messages().iter().all(|m| !m.is_ephemeral()));
812    }
813
814    #[test]
815    fn test_set_system_prompt_replaces_first_non_ephemeral_system() {
816        let mut s = make_session();
817        s.push_message(MessageRole::System, "old prompt");
818        s.push_message(MessageRole::User, "hi");
819        s.push_message(MessageRole::Assistant, "hello");
820
821        s.set_system_prompt("new prompt");
822
823        let msgs = s.chat_messages();
824        assert_eq!(msgs.len(), 3, "history length unchanged");
825        assert!(
826            matches!(&msgs[0], ChatMessage::System { content, ephemeral: false } if content == "new prompt")
827        );
828        assert!(matches!(&msgs[1], ChatMessage::User { content, .. } if content == "hi"));
829        assert!(
830            matches!(&msgs[2], ChatMessage::Assistant { content: Some(c), .. } if c == "hello")
831        );
832    }
833
834    #[test]
835    fn test_set_system_prompt_inserts_when_absent() {
836        let mut s = make_session();
837        s.push_message(MessageRole::User, "hi");
838
839        s.set_system_prompt("fresh prompt");
840
841        let msgs = s.chat_messages();
842        assert_eq!(msgs.len(), 2);
843        assert!(
844            matches!(&msgs[0], ChatMessage::System { content, ephemeral: false } if content == "fresh prompt")
845        );
846        assert!(matches!(&msgs[1], ChatMessage::User { .. }));
847    }
848
849    #[test]
850    fn test_set_system_prompt_skips_ephemeral_system_and_inserts() {
851        let mut s = make_session();
852        s.chat_messages_mut()
853            .push(ChatMessage::system_ephemeral("ephemeral nudge"));
854        s.push_message(MessageRole::User, "hi");
855
856        s.set_system_prompt("real prompt");
857
858        // No non-ephemeral System exists → insert at the very front; the ephemeral nudge stays where it is.
859        let msgs = s.chat_messages();
860        assert_eq!(msgs.len(), 3);
861        assert!(
862            matches!(&msgs[0], ChatMessage::System { content, ephemeral: false } if content == "real prompt")
863        );
864        assert!(matches!(
865            &msgs[1],
866            ChatMessage::System {
867                ephemeral: true,
868                ..
869            }
870        ));
871        assert!(matches!(&msgs[2], ChatMessage::User { .. }));
872    }
873
874    #[test]
875    fn test_close_dangling_tool_calls_noop_without_tool_call() {
876        let mut s = make_session();
877        s.push_message(MessageRole::User, "hi");
878        s.push_message(MessageRole::Assistant, "hi");
879        s.close_dangling_tool_calls("failed");
880        assert_eq!(s.chat_messages().len(), 2);
881    }
882
883    #[test]
884    fn test_close_dangling_tool_calls_adds_missing_results() {
885        let mut s = make_session();
886        s.push_message(MessageRole::User, "do");
887        s.push_assistant_tool_calls(
888            &[
889                ("c1".into(), "t".into(), "{}".into()),
890                ("c2".into(), "t".into(), "{}".into()),
891            ],
892            None,
893            None,
894        );
895        s.push_tool_result("c1", "ok"); // only c1 answered
896        s.close_dangling_tool_calls("failed");
897
898        let tool_results: Vec<(String, String)> = s
899            .chat_messages()
900            .iter()
901            .filter_map(|m| match m {
902                ChatMessage::Tool {
903                    tool_call_id,
904                    name: _,
905                    content,
906                } => Some((tool_call_id.clone(), content.clone())),
907                _ => None,
908            })
909            .collect();
910        assert_eq!(tool_results.len(), 2);
911        assert!(
912            tool_results
913                .iter()
914                .any(|(id, c)| id == "c2" && c == "failed")
915        );
916    }
917
918    #[test]
919    fn test_set_chat_messages_recalculates_total_tool_calls() {
920        let mut s = make_session();
921        let msgs = vec![
922            ChatMessage::user("do"),
923            ChatMessage::assistant_tool_call("c1", "t", "{}"),
924            ChatMessage::tool("c1", "result"),
925        ];
926        s.set_chat_messages(msgs).unwrap();
927        assert_eq!(s.total_tool_calls, 1);
928    }
929}
930
931#[cfg(test)]
932mod validate_tests {
933    use super::*;
934
935    #[test]
936    fn test_valid_simple_sequence() {
937        let msgs = vec![ChatMessage::user("hello"), ChatMessage::assistant("hi")];
938        assert!(validate_message_sequence(&msgs).is_ok());
939    }
940
941    #[test]
942    fn test_valid_tool_call_sequence() {
943        let msgs = vec![
944            ChatMessage::user("run command"),
945            ChatMessage::assistant_tool_call("call_1", "bash", r#"{"cmd":"ls"}"#),
946            ChatMessage::tool("call_1", "file1 file2"),
947            ChatMessage::assistant("done"),
948        ];
949        assert!(validate_message_sequence(&msgs).is_ok());
950    }
951
952    #[test]
953    fn test_valid_multi_tool_call_sequence() {
954        let msgs = vec![
955            ChatMessage::user("run commands"),
956            ChatMessage::Assistant {
957                content: None,
958                reasoning_content: None,
959                tool_calls: Some(vec![
960                    crate::types::ToolCallMessage {
961                        id: "call_1".into(),
962                        name: "bash".into(),
963                        arguments: "{}".into(),
964                    },
965                    crate::types::ToolCallMessage {
966                        id: "call_2".into(),
967                        name: "read".into(),
968                        arguments: "{}".into(),
969                    },
970                ]),
971                thinking_signature: None,
972            },
973            ChatMessage::tool("call_1", "result1"),
974            ChatMessage::tool("call_2", "result2"),
975            ChatMessage::assistant("done"),
976        ];
977        assert!(validate_message_sequence(&msgs).is_ok());
978    }
979
980    #[test]
981    fn test_orphaned_tool_result() {
982        let msgs = vec![
983            ChatMessage::user("hello"),
984            ChatMessage::tool("call_1", "orphaned result"),
985        ];
986        let err = validate_message_sequence(&msgs).unwrap_err();
987        assert!(err.contains("no preceding tool_call"));
988    }
989
990    #[test]
991    fn test_system_only_sequence_rejected() {
992        // A compaction that leaves only System/Custom messages would send an
993        // empty `messages` array (System maps to the `system` param) — the
994        // contract rejects it.
995        let msgs = vec![
996            ChatMessage::system("prompt"),
997            ChatMessage::system_ephemeral("reminder"),
998            ChatMessage::Custom {
999                role: "artifact".into(),
1000                data: serde_json::json!({"id": "x"}),
1001            },
1002        ];
1003        let err = validate_message_sequence(&msgs).unwrap_err();
1004        assert!(err.contains("no sendable message"));
1005    }
1006
1007    #[test]
1008    fn test_system_plus_user_ok() {
1009        let msgs = vec![ChatMessage::system("prompt"), ChatMessage::user("hi")];
1010        assert!(validate_message_sequence(&msgs).is_ok());
1011    }
1012
1013    #[test]
1014    fn test_mismatched_tool_call_id() {
1015        let msgs = vec![
1016            ChatMessage::user("run"),
1017            ChatMessage::assistant_tool_call("call_1", "bash", "{}"),
1018            ChatMessage::tool("call_2", "wrong id"),
1019        ];
1020        let err = validate_message_sequence(&msgs).unwrap_err();
1021        assert!(err.contains("does not match"));
1022    }
1023
1024    #[test]
1025    fn test_set_chat_messages_valid() {
1026        let mut s = make_session();
1027        let msgs = vec![ChatMessage::user("hello"), ChatMessage::assistant("hi")];
1028        assert!(s.set_chat_messages(msgs.clone()).is_ok());
1029        assert_eq!(s.chat_messages().len(), 2);
1030    }
1031
1032    #[test]
1033    fn test_set_chat_messages_invalid() {
1034        let mut s = make_session();
1035        let msgs = vec![ChatMessage::tool("call_1", "orphaned")];
1036        assert!(s.set_chat_messages(msgs).is_err());
1037    }
1038
1039    // ── RunState tests ────────────────────────────────────────────────────
1040
1041    #[test]
1042    fn run_state_default() {
1043        let rs = RunState::default();
1044        assert_eq!(rs.turn_tool_calls, 0);
1045        assert!(!rs.run_has_tool_calls);
1046        assert_eq!(rs.reasoning_only_strikes, 0);
1047        assert_eq!(rs.empty_response_strikes, 0);
1048        assert_eq!(rs.nudge_count, 0);
1049    }
1050
1051    #[test]
1052    fn run_state_reset_for_new_run() {
1053        let mut rs = RunState {
1054            turn_tool_calls: 5,
1055            run_has_tool_calls: true,
1056            reasoning_only_strikes: 2,
1057            empty_response_strikes: 1,
1058            nudge_count: 3,
1059            thinking_disabled_for_rest_of_run: true,
1060            original_thinking_enabled: true,
1061            truncation_strikes: 4,
1062        };
1063
1064        rs.reset_for_new_run();
1065
1066        assert_eq!(rs.turn_tool_calls, 0);
1067        assert!(!rs.run_has_tool_calls);
1068        assert_eq!(rs.reasoning_only_strikes, 0);
1069        assert_eq!(rs.empty_response_strikes, 0);
1070        assert_eq!(rs.nudge_count, 0);
1071        assert_eq!(rs.truncation_strikes, 0);
1072        assert!(!rs.thinking_disabled_for_rest_of_run);
1073        // original_thinking_enabled is NOT reset
1074        assert!(rs.original_thinking_enabled);
1075    }
1076
1077    #[test]
1078    fn run_state_record_tool_calls() {
1079        let mut rs = RunState {
1080            reasoning_only_strikes: 2,
1081            empty_response_strikes: 1,
1082            ..RunState::default()
1083        };
1084
1085        rs.record_tool_calls(3);
1086
1087        assert_eq!(rs.turn_tool_calls, 3);
1088        assert!(rs.run_has_tool_calls);
1089        assert_eq!(rs.reasoning_only_strikes, 0); // reset
1090        assert_eq!(rs.empty_response_strikes, 0); // reset
1091    }
1092
1093    #[test]
1094    fn run_state_record_tool_calls_accumulates() {
1095        let mut rs = RunState::default();
1096        rs.record_tool_calls(2);
1097        rs.record_tool_calls(3);
1098
1099        assert_eq!(rs.turn_tool_calls, 5);
1100        assert!(rs.run_has_tool_calls);
1101    }
1102
1103    #[test]
1104    fn run_state_record_reasoning_only() {
1105        let mut rs = RunState {
1106            empty_response_strikes: 2,
1107            ..RunState::default()
1108        };
1109
1110        let strikes = rs.record_reasoning_only();
1111
1112        assert_eq!(strikes, 1);
1113        assert_eq!(rs.reasoning_only_strikes, 1);
1114        assert_eq!(rs.empty_response_strikes, 0); // reset
1115    }
1116
1117    #[test]
1118    fn run_state_record_reasoning_only_consecutive() {
1119        let mut rs = RunState::default();
1120
1121        assert_eq!(rs.record_reasoning_only(), 1);
1122        assert_eq!(rs.record_reasoning_only(), 2);
1123        assert_eq!(rs.record_reasoning_only(), 3);
1124    }
1125
1126    #[test]
1127    fn run_state_record_empty_response() {
1128        let mut rs = RunState {
1129            reasoning_only_strikes: 2,
1130            ..RunState::default()
1131        };
1132
1133        let strikes = rs.record_empty_response();
1134
1135        assert_eq!(strikes, 1);
1136        assert_eq!(rs.empty_response_strikes, 1);
1137        assert_eq!(rs.reasoning_only_strikes, 0); // reset
1138    }
1139
1140    #[test]
1141    fn run_state_record_empty_response_consecutive() {
1142        let mut rs = RunState::default();
1143
1144        assert_eq!(rs.record_empty_response(), 1);
1145        assert_eq!(rs.record_empty_response(), 2);
1146        assert_eq!(rs.record_empty_response(), 3);
1147    }
1148
1149    #[test]
1150    fn run_state_branch_cross_reset() {
1151        // Simulate: reasoning only → tool calls → reasoning only
1152        let mut rs = RunState::default();
1153
1154        // Branch 1: reasoning only
1155        rs.record_reasoning_only();
1156        assert_eq!(rs.reasoning_only_strikes, 1);
1157
1158        // Branch 3: tool calls (should reset reasoning_only_strikes)
1159        rs.record_tool_calls(2);
1160        assert_eq!(rs.reasoning_only_strikes, 0);
1161        assert_eq!(rs.turn_tool_calls, 2);
1162
1163        // Branch 1 again: reasoning only (should start from 1, not 2)
1164        let strikes = rs.record_reasoning_only();
1165        assert_eq!(strikes, 1);
1166    }
1167
1168    #[test]
1169    fn run_state_empty_to_reasoning_reset() {
1170        // Simulate: empty → empty → reasoning only (should reset empty strikes)
1171        let mut rs = RunState::default();
1172
1173        rs.record_empty_response();
1174        rs.record_empty_response();
1175        assert_eq!(rs.empty_response_strikes, 2);
1176
1177        // Branch 1: reasoning only (should reset empty_response_strikes)
1178        rs.record_reasoning_only();
1179        assert_eq!(rs.empty_response_strikes, 0);
1180        assert_eq!(rs.reasoning_only_strikes, 1);
1181    }
1182
1183    #[test]
1184    fn run_state_thinking_disabled_default() {
1185        let rs = RunState::default();
1186        assert!(!rs.thinking_disabled_for_rest_of_run);
1187    }
1188
1189    #[test]
1190    fn run_state_thinking_disabled_after_3_strikes() {
1191        let mut rs = RunState::default();
1192
1193        // After 1st reasoning-only: not disabled
1194        rs.record_reasoning_only();
1195        assert!(!rs.thinking_disabled_for_rest_of_run);
1196        assert_eq!(rs.reasoning_only_strikes, 1);
1197
1198        // After 2nd reasoning-only: not disabled
1199        rs.record_reasoning_only();
1200        assert!(!rs.thinking_disabled_for_rest_of_run);
1201        assert_eq!(rs.reasoning_only_strikes, 2);
1202
1203        // After 3rd reasoning-only: disabled!
1204        rs.record_reasoning_only();
1205        assert!(rs.thinking_disabled_for_rest_of_run);
1206        assert_eq!(rs.reasoning_only_strikes, 3);
1207    }
1208
1209    #[test]
1210    fn run_state_thinking_disabled_resets_on_new_run() {
1211        let mut rs = RunState::default();
1212
1213        // Simulate 3 reasoning-only responses
1214        rs.record_reasoning_only();
1215        rs.record_reasoning_only();
1216        rs.record_reasoning_only();
1217        assert!(rs.thinking_disabled_for_rest_of_run);
1218        assert_eq!(rs.reasoning_only_strikes, 3);
1219
1220        // Reset for new run (new user message)
1221        rs.reset_for_new_run();
1222        assert!(!rs.thinking_disabled_for_rest_of_run);
1223        assert_eq!(rs.reasoning_only_strikes, 0);
1224    }
1225
1226    #[test]
1227    fn run_state_thinking_disabled_stays_after_tool_calls() {
1228        let mut rs = RunState::default();
1229
1230        // Simulate 3 reasoning-only responses
1231        rs.record_reasoning_only();
1232        rs.record_reasoning_only();
1233        rs.record_reasoning_only();
1234        assert!(rs.thinking_disabled_for_rest_of_run);
1235
1236        // Tool calls should NOT reset thinking_disabled_for_rest_of_run
1237        // (it should stay disabled for the rest of the run)
1238        rs.record_tool_calls(2);
1239        assert!(rs.thinking_disabled_for_rest_of_run);
1240        assert_eq!(rs.reasoning_only_strikes, 0); // strikes reset, but thinking stays disabled
1241    }
1242
1243    // ── Backward-compatible deserialization ────────────────────────────────
1244
1245    #[test]
1246    fn deserialize_legacy_flat_fields() {
1247        // Old format: nudge_count, turn_tool_calls, etc. as flat fields
1248        let json = r#"{
1249            "id": null,
1250            "chat_messages": [],
1251            "always_allowed_actions": [],
1252            "total_tool_calls": 5,
1253            "nudge_count": 3,
1254            "turn_tool_calls": 2,
1255            "reasoning_only_strikes": 1,
1256            "empty_response_strikes": 0
1257        }"#;
1258        let session: AgentSession = serde_json::from_str(json).unwrap();
1259        assert_eq!(session.run_state.nudge_count, 3);
1260        assert_eq!(session.run_state.turn_tool_calls, 2);
1261        assert_eq!(session.run_state.reasoning_only_strikes, 1);
1262        assert_eq!(session.run_state.empty_response_strikes, 0);
1263        assert!(!session.run_state.run_has_tool_calls); // default
1264    }
1265
1266    #[test]
1267    fn deserialize_new_run_state_format() {
1268        // New format: nested run_state
1269        let json = r#"{
1270            "id": null,
1271            "chat_messages": [],
1272            "always_allowed_actions": [],
1273            "total_tool_calls": 5,
1274            "run_state": {
1275                "turn_tool_calls": 4,
1276                "run_has_tool_calls": true,
1277                "reasoning_only_strikes": 0,
1278                "empty_response_strikes": 1,
1279                "nudge_count": 2
1280            }
1281        }"#;
1282        let session: AgentSession = serde_json::from_str(json).unwrap();
1283        assert_eq!(session.run_state.turn_tool_calls, 4);
1284        assert!(session.run_state.run_has_tool_calls);
1285        assert_eq!(session.run_state.empty_response_strikes, 1);
1286        assert_eq!(session.run_state.nudge_count, 2);
1287    }
1288
1289    #[test]
1290    fn deserialize_run_state_takes_precedence_over_flat() {
1291        // When both are present, run_state wins
1292        let json = r#"{
1293            "id": null,
1294            "chat_messages": [],
1295            "always_allowed_actions": [],
1296            "total_tool_calls": 0,
1297            "run_state": {
1298                "turn_tool_calls": 10,
1299                "run_has_tool_calls": true,
1300                "reasoning_only_strikes": 0,
1301                "empty_response_strikes": 0,
1302                "nudge_count": 0
1303            },
1304            "nudge_count": 99,
1305            "turn_tool_calls": 99
1306        }"#;
1307        let session: AgentSession = serde_json::from_str(json).unwrap();
1308        assert_eq!(session.run_state.turn_tool_calls, 10); // run_state wins
1309        assert_eq!(session.run_state.nudge_count, 0); // run_state wins
1310    }
1311
1312    #[test]
1313    fn deserialize_legacy_missing_optional_fields() {
1314        // Old format with some fields missing (defaults to 0)
1315        let json = r#"{
1316            "id": null,
1317            "chat_messages": [],
1318            "always_allowed_actions": [],
1319            "total_tool_calls": 0,
1320            "nudge_count": 1
1321        }"#;
1322        let session: AgentSession = serde_json::from_str(json).unwrap();
1323        assert_eq!(session.run_state.nudge_count, 1);
1324        assert_eq!(session.run_state.turn_tool_calls, 0); // missing → 0
1325        assert_eq!(session.run_state.reasoning_only_strikes, 0);
1326        assert_eq!(session.run_state.empty_response_strikes, 0);
1327    }
1328
1329    #[test]
1330    fn roundtrip_preserves_run_state() {
1331        let mut session = AgentSession::new(SessionId::new(1));
1332        session.run_state.nudge_count = 5;
1333        session.run_state.turn_tool_calls = 3;
1334        session.run_state.run_has_tool_calls = true;
1335        session.run_state.reasoning_only_strikes = 2;
1336
1337        let json = serde_json::to_string(&session).unwrap();
1338        let restored: AgentSession = serde_json::from_str(&json).unwrap();
1339        assert_eq!(restored.run_state.nudge_count, 5);
1340        assert_eq!(restored.run_state.turn_tool_calls, 3);
1341        assert!(restored.run_state.run_has_tool_calls);
1342        assert_eq!(restored.run_state.reasoning_only_strikes, 2);
1343    }
1344
1345    #[test]
1346    fn push_assistant_tool_calls_validates_json_args() {
1347        let mut s = make_session();
1348
1349        // Valid JSON args should pass through unchanged
1350        let valid_args = r#"{"path": "src/main.rs", "content": "fn main() {}"}"#;
1351        s.push_assistant_tool_calls(
1352            &[("id1".into(), "write_file".into(), valid_args.into())],
1353            None,
1354            None,
1355        );
1356        if let ChatMessage::Assistant {
1357            tool_calls: Some(ref tc),
1358            ..
1359        } = s.chat_messages[0]
1360        {
1361            assert_eq!(tc[0].arguments, valid_args);
1362        } else {
1363            panic!("expected Assistant message with tool_calls");
1364        }
1365
1366        // Truncated (invalid JSON) args must be sanitized to an empty object,
1367        // NOT wrapped in a descriptive error object. Two reasons:
1368        //   1. "{}" is valid JSON, so the next request is never rejected 400.
1369        //   2. a rich `{error, original_args_preview, message}` object in
1370        //      assistant history is an imitation vector — the model replays it
1371        //      verbatim as the next call's arguments, and because it parses as
1372        //      valid JSON it slips past the react truncation guard and resurfaces
1373        //      as a downstream ToolArgsInvalid. The truncation explanation
1374        //      belongs in the tool_result, not the assistant arguments.
1375        let truncated_args = r#"{"path": "src/ui/markdown.rs", "content": "#;
1376        s.push_assistant_tool_calls(
1377            &[("id2".into(), "write_file".into(), truncated_args.into())],
1378            None,
1379            None,
1380        );
1381        if let ChatMessage::Assistant {
1382            tool_calls: Some(ref tc),
1383            ..
1384        } = s.chat_messages[1]
1385        {
1386            assert_eq!(tc[0].arguments, "{}");
1387            assert!(
1388                !tc[0].arguments.contains("tool_call_arguments_truncated"),
1389                "assistant arguments must not carry the poison wrapper object"
1390            );
1391        } else {
1392            panic!("expected Assistant message with tool_calls");
1393        }
1394    }
1395
1396    #[test]
1397    fn push_assistant_tool_calls_truncated_multibyte_no_panic() {
1398        // Bug-2: Invalid JSON args with multi-byte UTF-8 chars near byte 200
1399        // cause a panic at char boundary when slicing &args[..args.len().min(200)].
1400        let mut s = make_session();
1401
1402        // Build invalid JSON with CJK chars that straddle the 200-byte boundary.
1403        // "あ" = 3 bytes in UTF-8. Repeating ~70 times = ~210 bytes, then add invalid suffix.
1404        let mut bad_args = "あ".repeat(70); // 70 * 3 = 210 bytes
1405        bad_args.push_str("truncated"); // makes it invalid JSON
1406
1407        // This must NOT panic. Invalid args are sanitized to "{}" (a fixed
1408        // literal), so no slicing of the multibyte string happens at all.
1409        s.push_assistant_tool_calls(&[("id1".into(), "tool".into(), bad_args)], None, None);
1410
1411        if let ChatMessage::Assistant {
1412            tool_calls: Some(ref tc),
1413            ..
1414        } = s.chat_messages[0]
1415        {
1416            assert_eq!(tc[0].arguments, "{}");
1417        } else {
1418            panic!("expected Assistant message with tool_calls");
1419        }
1420    }
1421
1422    #[test]
1423    fn push_assistant_tool_calls_then_tool_result_matches_anthropic_protocol() {
1424        // Regression test for: when LLM response is truncated (finish_reason=max_tokens),
1425        // the code must push assistant message WITH tool_use blocks (not plain text)
1426        // so that subsequent tool_result messages can match the tool_use_id.
1427        // This is required by Anthropic protocol.
1428        let mut s = make_session();
1429
1430        // Simulate truncated tool call response
1431        let tool_calls = vec![
1432            (
1433                "call_00_VJtlnKha0ZZ2Yo8t5ysQ8883".to_string(),
1434                "write_file".to_string(),
1435                "{}".to_string(),
1436            ),
1437            (
1438                "call_01_abc123".to_string(),
1439                "bash".to_string(),
1440                r#"{"command": "ls"}"#.to_string(),
1441            ),
1442        ];
1443
1444        // Push assistant message with tool_calls (as the fix does)
1445        s.push_assistant_tool_calls(
1446            &tool_calls,
1447            Some("thinking...".to_string()),
1448            Some("I'll help you".to_string()),
1449        );
1450
1451        // Push tool results for each tool call
1452        for (tc_id, _, _) in &tool_calls {
1453            s.push_tool_result(
1454                tc_id,
1455                "Tool call was not executed: the response hit the output token limit.",
1456            );
1457        }
1458
1459        // Verify the message sequence is valid
1460        // 1. Assistant message should have tool_calls
1461        if let ChatMessage::Assistant {
1462            tool_calls: Some(ref tc),
1463            ..
1464        } = s.chat_messages[0]
1465        {
1466            assert_eq!(tc.len(), 2);
1467            assert_eq!(tc[0].id, "call_00_VJtlnKha0ZZ2Yo8t5ysQ8883");
1468            assert_eq!(tc[0].name, "write_file");
1469            assert_eq!(tc[1].id, "call_01_abc123");
1470            assert_eq!(tc[1].name, "bash");
1471        } else {
1472            panic!("expected Assistant message with tool_calls");
1473        }
1474
1475        // 2. Tool result messages should have matching tool_use_id
1476        if let ChatMessage::Tool { tool_call_id, .. } = &s.chat_messages[1] {
1477            assert_eq!(tool_call_id, "call_00_VJtlnKha0ZZ2Yo8t5ysQ8883");
1478        } else {
1479            panic!("expected Tool message for first tool call");
1480        }
1481
1482        if let ChatMessage::Tool { tool_call_id, .. } = &s.chat_messages[2] {
1483            assert_eq!(tool_call_id, "call_01_abc123");
1484        } else {
1485            panic!("expected Tool message for second tool call");
1486        }
1487
1488        // 3. Validate message sequence (this would catch the bug)
1489        assert!(
1490            validate_message_sequence(&s.chat_messages).is_ok(),
1491            "message sequence should be valid with matching tool_use and tool_result"
1492        );
1493    }
1494}
1495
1496#[cfg(test)]
1497mod proptest_tests {
1498    use super::*;
1499    use proptest::prelude::*;
1500
1501    proptest! {
1502        // ── RunState property tests ─────────────────────────────────────────
1503
1504        #[test]
1505        fn reset_for_new_run_zeros_all_fields(
1506            turn_tool_calls in 0usize..1000,
1507            run_has_tool_calls in proptest::bool::ANY,
1508            reasoning_only_strikes in 0usize..100,
1509            empty_response_strikes in 0usize..100,
1510            nudge_count in 0usize..100,
1511        ) {
1512            let mut rs = RunState {
1513                turn_tool_calls,
1514                run_has_tool_calls,
1515                reasoning_only_strikes,
1516                empty_response_strikes,
1517                nudge_count,
1518                thinking_disabled_for_rest_of_run: true,
1519                original_thinking_enabled: true,
1520                truncation_strikes: 5,
1521            };
1522            rs.reset_for_new_run();
1523            assert_eq!(rs.turn_tool_calls, 0);
1524            assert!(!rs.run_has_tool_calls);
1525            assert_eq!(rs.reasoning_only_strikes, 0);
1526            assert_eq!(rs.empty_response_strikes, 0);
1527            assert_eq!(rs.nudge_count, 0);
1528            assert_eq!(rs.truncation_strikes, 0);
1529            assert!(!rs.thinking_disabled_for_rest_of_run);
1530            // original_thinking_enabled is NOT reset
1531            assert!(rs.original_thinking_enabled);
1532        }
1533
1534        #[test]
1535        fn record_tool_calls_accumulates(n in 0usize..100) {
1536            let mut rs = RunState::default();
1537            rs.record_tool_calls(n);
1538            assert_eq!(rs.turn_tool_calls, n);
1539            assert!(rs.run_has_tool_calls);
1540            assert_eq!(rs.reasoning_only_strikes, 0);
1541            assert_eq!(rs.empty_response_strikes, 0);
1542        }
1543
1544        #[test]
1545        fn record_reasoning_only_increments(count in 1usize..50) {
1546            let mut rs = RunState::default();
1547            for i in 1..=count {
1548                let strikes = rs.record_reasoning_only();
1549                assert_eq!(strikes, i);
1550                assert_eq!(rs.empty_response_strikes, 0);
1551            }
1552        }
1553
1554        #[test]
1555        fn record_empty_response_increments(count in 1usize..50) {
1556            let mut rs = RunState::default();
1557            for i in 1..=count {
1558                let strikes = rs.record_empty_response();
1559                assert_eq!(strikes, i);
1560                assert_eq!(rs.reasoning_only_strikes, 0);
1561            }
1562        }
1563
1564        // ── push_assistant_tool_calls property tests ────────────────────────
1565
1566        #[test]
1567        fn push_assistant_tool_calls_valid_json_unchanged(args in r"\{[^{}]{0,200}\}") {
1568            // Only test strings that are actually valid JSON objects
1569            if serde_json::from_str::<serde_json::Value>(&args).is_err() {
1570                return Ok(());
1571            }
1572            let mut s = make_session();
1573            s.push_assistant_tool_calls(
1574                &[("id".into(), "tool".into(), args.clone())],
1575                None,
1576                None,
1577            );
1578            if let ChatMessage::Assistant { tool_calls: Some(ref tc), .. } = s.chat_messages()[0] {
1579                assert_eq!(tc[0].arguments, args);
1580            } else {
1581                panic!("expected Assistant with tool_calls");
1582            }
1583        }
1584
1585        #[test]
1586        fn push_assistant_tool_calls_invalid_json_sanitized_to_empty(
1587            bad_args in "[a-z\u{4e00}-\u{9fff}]{0,300}"
1588        ) {
1589            // Skip if it happens to be valid JSON
1590            if serde_json::from_str::<serde_json::Value>(&bad_args).is_ok() {
1591                return Ok(());
1592            }
1593            let mut s = make_session();
1594            s.push_assistant_tool_calls(
1595                &[("id".into(), "tool".into(), bad_args)],
1596                None,
1597                None,
1598            );
1599            if let ChatMessage::Assistant { tool_calls: Some(ref tc), .. } = s.chat_messages()[0] {
1600                // Must be valid JSON (no 400 on replay) AND carry no poison
1601                // wrapper the model could echo back as arguments.
1602                serde_json::from_str::<serde_json::Value>(&tc[0].arguments)
1603                    .expect("sanitized args must be valid JSON");
1604                assert_eq!(tc[0].arguments, "{}");
1605            } else {
1606                panic!("expected Assistant with tool_calls");
1607            }
1608        }
1609
1610        #[test]
1611        fn preview_args_escapes_and_caps_at_max_chars(payload in "[a-z\u{4e00}-\u{9fff}\n\t]{0,400}") {
1612            // args_preview for the truncation WARN: truncate by characters (not bytes),
1613            // escape control characters in debug form (each input character expands to
1614            // at most 2 characters), with length capped at min(80, len) * 2 + the paired quotes.
1615            let preview = AgentSession::preview_args(&payload, 80);
1616            let expected_cap = 2 * payload.chars().count().min(80) + 2;
1617            assert!(
1618                preview.chars().count() <= expected_cap,
1619                "preview must cap at escaped length plus quotes: {preview}"
1620            );
1621            if payload.contains('\n') || payload.contains('\t') {
1622                assert!(
1623                    preview.contains("\\n") || preview.contains("\\t"),
1624                    "control chars must be escaped: {preview}"
1625                );
1626            }
1627            if payload.chars().count() <= 80 && !payload.contains('\n') && !payload.contains('\t') {
1628                assert_eq!(preview, format!("{payload:?}"));
1629            }
1630        }
1631
1632        // ── trim_oldest_turns property tests ────────────────────────────────
1633
1634        #[test]
1635        fn trim_oldest_turns_never_exceeds_max(turns in 1usize..20, max in 1usize..20) {
1636            let mut s = make_session();
1637            for i in 0..turns {
1638                s.push_message(MessageRole::User, format!("u{}", i));
1639                s.push_message(MessageRole::Assistant, format!("a{}", i));
1640            }
1641            s.trim_oldest_turns(max);
1642            assert!(s.turn_count() <= max || turns <= max);
1643        }
1644
1645        // ── validate_message_sequence property tests ────────────────────────
1646
1647        #[test]
1648        fn validate_simple_user_assistant_always_passes(count in 1usize..20) {
1649            let mut msgs = Vec::new();
1650            for i in 0..count {
1651                msgs.push(ChatMessage::user(format!("msg{}", i)));
1652                msgs.push(ChatMessage::assistant(format!("reply{}", i)));
1653            }
1654            assert!(validate_message_sequence(&msgs).is_ok());
1655        }
1656    }
1657}