Skip to main content

vtcode_core/core/agent/
completion.rs

1use crate::core::agent::session::AgentSessionState;
2use crate::llm::provider::MessageRole;
3
4/// Successful tracker mutations establish adoption within the caller's current
5/// request history. Listing, rejected calls, and unrelated tool results do not.
6pub fn tracker_was_adopted(history: &[crate::llm::provider::Message]) -> bool {
7    let mut pending_tracker_calls = std::collections::HashMap::new();
8    for message in history {
9        if message.role == MessageRole::Assistant {
10            // Call IDs can be reused between batches; never match an unanswered
11            // tracker request to a later batch's result.
12            pending_tracker_calls.clear();
13            for call in message.tool_calls.iter().flatten() {
14                let Some(function) = call
15                    .function
16                    .as_ref()
17                    .filter(|function| function.name == crate::config::constants::tools::TASK_TRACKER)
18                else {
19                    continue;
20                };
21                let Ok(args) = serde_json::from_str::<serde_json::Value>(&function.arguments) else {
22                    continue;
23                };
24                if matches!(args.get("action").and_then(serde_json::Value::as_str), Some("create" | "update" | "add")) {
25                    pending_tracker_calls.insert(call.id.as_str(), args);
26                }
27            }
28        } else if message.role == MessageRole::Tool
29            && let Some(args) = message.tool_call_id.as_deref().and_then(|id| pending_tracker_calls.remove(id))
30            && let Ok(output) = serde_json::from_str::<serde_json::Value>(message.content.as_text().as_ref())
31            && tracker_adoption_succeeded(crate::config::constants::tools::TASK_TRACKER, &args, &output)
32        {
33            return true;
34        }
35    }
36    false
37}
38
39/// Observe adoption before tool output or conversation history is compacted.
40pub fn tracker_adoption_succeeded(tool_name: &str, args: &serde_json::Value, output: &serde_json::Value) -> bool {
41    use serde_json::Value;
42    tool_name == crate::config::constants::tools::TASK_TRACKER
43        && output.get("error").is_none()
44        && output.get("success").and_then(Value::as_bool) != Some(false)
45        && output.get("blocked").and_then(Value::as_bool) != Some(true)
46        && output.get("not_executed").and_then(Value::as_bool) != Some(true)
47        && matches!(
48            (args.get("action").and_then(Value::as_str), output.get("status").and_then(Value::as_str)),
49            (Some("create"), Some("created" | "replaced" | "unchanged"))
50                | (Some("update"), Some("updated" | "unchanged"))
51                | (Some("add"), Some("added"))
52        )
53}
54
55/// True when assistant text is a genuine safety/permission handoff that must
56/// not be auto-continued, even if `task_tracker` still has incomplete steps.
57///
58/// Shared by the binary outer-loop Completed queue and AgentRunner status
59/// continuation so both surfaces use the same vocabulary. Safety/policy
60/// denials are evaluated first so a recap that mentions both a budget and a
61/// policy denial still counts as a handoff. Pure budget/recovery recaps are
62/// not handoffs (outer/in-turn recoverable classifiers treat those as continue).
63pub fn tracker_final_text_is_safety_handoff(text: &str) -> bool {
64    let lower = text.to_ascii_lowercase();
65    tracker_final_text_is_policy_handoff_lowercase(&lower)
66        || lower.contains("verification is still pending")
67        || lower.contains("unverified assistant responses")
68        || lower.contains("anti-blind")
69        || lower.contains("verification gate")
70}
71
72/// Permission, policy, safety, and credential handoffs remain terminal even
73/// when a pending-verification block can recover with fresh execution budget.
74/// Verification wording is handled separately by the turn's recovery gate.
75pub fn tracker_final_text_is_policy_handoff(text: &str) -> bool {
76    let lower = text.to_ascii_lowercase();
77    tracker_final_text_is_policy_handoff_lowercase(&lower)
78}
79
80fn tracker_final_text_is_policy_handoff_lowercase(lower: &str) -> bool {
81    if lower.trim().is_empty() {
82        return false;
83    }
84    // True handoffs win even when the text also mentions a budget.
85    if lower.contains("permission denied")
86        || lower.contains("access denied")
87        || lower.contains("safety fuse")
88        || lower.contains("tool-call safety fuse")
89        || lower.contains("policy block")
90        || lower.contains("blocked by policy")
91        || lower.contains("requires manual intervention")
92        || lower.contains("missing credentials")
93        || lower.contains("credentials are missing")
94        || lower.contains("denied by policy")
95        || lower.contains("denied by workspace tool policy")
96        || lower.contains("denied by tool policy")
97        || lower.contains("execution denied by policy")
98        || lower.contains("blocked by tool policy")
99    {
100        return true;
101    }
102    // Pure budget/recovery recaps ("blocked by wall-clock budget", "tool
103    // loop budget exhausted", …) are not user handoffs.
104    false
105}
106
107/// Shared recoverable status-recap vocabulary for tracker continuation.
108///
109/// Used by the binary in-turn override and outer blocked-reason classifier
110/// tests so session/production budget phrases cannot drift between surfaces.
111/// Lowercase input expected.
112pub fn recoverable_status_recap_phrasing(lower: &str) -> bool {
113    lower.contains("preview budget")
114        || lower.contains("tool preview budget")
115        || lower.contains("wall clock")
116        || lower.contains("wall-clock")
117        || lower.contains("safety cap")
118        || lower.contains("recovery fallback")
119        || lower.contains("recovery could not confirm")
120        || lower.contains("recovery exhausted")
121        || lower.contains("recovery was exhausted")
122        || lower.contains("tool loop")
123        || lower.contains("tool follow-up")
124        || lower.contains("read cap")
125        || lower.contains("max tool")
126        || lower.contains("budget exhausted")
127        || lower.contains("budget ran out")
128}
129
130/// True when final assistant text asks the user for a decision/confirmation.
131///
132/// Shared by outer tracker auto-queue and in-turn continuation so Completed
133/// turns that end with a genuine question are not auto-continued past the ask.
134pub fn tracker_final_text_requires_user_input(text: &str) -> bool {
135    let trimmed = text.trim();
136    if trimmed.is_empty() {
137        return false;
138    }
139    if trimmed.ends_with('?') {
140        return true;
141    }
142    let lower = trimmed.to_ascii_lowercase();
143    const STRONG: &[&str] = &[
144        "please provide",
145        "please confirm",
146        "please approve",
147        "need your approval",
148        "need your permission",
149        "need your decision",
150        "need you to choose",
151        "need you to confirm",
152        "waiting for your",
153        "awaiting your",
154        "your choice",
155        "your decision",
156        "need approval",
157        "requires approval",
158        "approval is required",
159        "need permission",
160        "requires permission",
161        "permission is required",
162        "grant permission",
163        "authorize this",
164        "need a decision",
165        "need clarification",
166        "waiting for input",
167        "awaiting input",
168        "waiting on you",
169        "how should i proceed",
170        "what should i do",
171        "what would you like",
172        "how would you like",
173        "do you want me to",
174    ];
175    const CLAUSE_START: &[&str] = &["could you ", "can you ", "shall i ", "should i "];
176    if STRONG.iter().any(|p| lower.contains(p)) {
177        return true;
178    }
179    CLAUSE_START
180        .iter()
181        .any(|p| lower.trim_start().starts_with(p) || lower.contains(&format!("\n{p}")))
182}
183
184/// Checks if the agent's response is a candidate for completion handling.
185pub fn check_completion_candidate(response_text: &str) -> bool {
186    // High-confidence terminal markers that strongly indicate intent to stop.
187    const COMPLETION_SENTENCES: &[&str] = &[
188        "the task is complete",
189        "task is complete",
190        "task has been completed",
191        "i have successfully completed the task",
192        "work is finished",
193        "operation successful",
194        "i am done",
195        "no more actions needed",
196        "successfully accomplished",
197        "task is now complete",
198        "everything is finished",
199        "i've finished the task",
200        "all requested changes have been applied",
201        "i have finished all the work",
202    ];
203
204    // Lower-confidence markers that need to be at the core of the message.
205    const SOFT_INDICATORS: &[&str] = &[
206        "task completed",
207        "task done",
208        "all done",
209        "finished.",
210        "complete.",
211        "done.",
212    ];
213
214    const UNRESOLVED_PHRASES: &[&str] = &[
215        "still need to",
216        "remaining step",
217        "remaining work",
218        "verification pending",
219        "verification still pending",
220        "tests not run",
221        "haven't run",
222        "have not run",
223        "blocked on",
224        "open questions remain",
225        "question remains",
226        "todo:",
227        "not complete yet",
228        "once verification",
229        "after verification",
230    ];
231
232    let response_lower = response_text.to_lowercase();
233
234    if UNRESOLVED_PHRASES.iter().any(|phrase| response_lower.contains(phrase))
235        || structured_contract_has_unresolved_sections(response_text)
236    {
237        return false;
238    }
239
240    // Strategy 1: Explicit terminal sentences
241    if COMPLETION_SENTENCES.iter().any(|&s| response_lower.contains(s)) {
242        return true;
243    }
244
245    // Strategy 2: Soft indicators that appear at the very end or are the entire message
246    let trimmed = response_lower.trim();
247    for &indicator in SOFT_INDICATORS {
248        if trimmed.ends_with(indicator) || trimmed == indicator {
249            // Heuristic: Ensure it's not "I will soon have the task completed"
250            // Check if preceded by future-tense markers within the same sentence
251            let sentences: Vec<_> = trimmed.split(['.', '!', '?']).collect();
252            if let Some(last_sentence) = sentences.last() {
253                let ls = last_sentence.trim();
254                if ls.contains(indicator)
255                    && !ls.contains("will")
256                    && !ls.contains("going to")
257                    && !ls.contains("about to")
258                    && !ls.contains("once")
259                    && !ls.contains("after")
260                {
261                    return true;
262                }
263            }
264        }
265    }
266
267    // Strategy 3: Structured subagent markdown contract output.
268    // When the model produces the canonical "## Summary / ## Facts / ..." contract, it has
269    // finished its task even without an explicit done phrase.  Detect this by checking that
270    // the response opens with a "## Summary" heading (after stripping leading whitespace) and
271    // also contains a "## Facts" section.  Headers are matched line-by-line after trimming so
272    // CRLF, extra spaces, and capitalisation variations are handled uniformly.
273    {
274        let mut has_summary_header = false;
275        let mut has_facts_header = false;
276        for line in response_text.lines() {
277            let line_lower = line.trim().to_lowercase();
278            if line_lower == "## summary" || line_lower == "# summary" {
279                has_summary_header = true;
280            }
281            if line_lower == "## facts" || line_lower == "# facts" {
282                has_facts_header = true;
283            }
284            if has_summary_header && has_facts_header {
285                return true;
286            }
287        }
288    }
289
290    false
291}
292
293fn structured_contract_has_unresolved_sections(response_text: &str) -> bool {
294    let mut in_open_questions = false;
295    let mut in_verification = false;
296
297    for line in response_text.lines() {
298        let line_lower = line.trim().to_lowercase();
299        if line_lower.starts_with('#') {
300            in_open_questions = line_lower == "## open questions" || line_lower == "# open questions";
301            in_verification = line_lower == "## verification" || line_lower == "# verification";
302            continue;
303        }
304
305        if line_lower.is_empty() {
306            continue;
307        }
308
309        if in_open_questions && !section_entry_is_none(&line_lower) {
310            return true;
311        }
312
313        if in_verification && section_entry_is_unresolved(&line_lower) {
314            return true;
315        }
316    }
317
318    false
319}
320
321fn section_entry_is_none(line: &str) -> bool {
322    let normalized = normalized_section_entry(line).trim_end_matches('.');
323    matches!(normalized, "none" | "n/a")
324}
325
326fn section_entry_is_unresolved(line: &str) -> bool {
327    let normalized = normalized_section_entry(line);
328    normalized.contains("pending")
329        || normalized.contains("not run")
330        || normalized.contains("failed")
331        || normalized.contains("blocked")
332}
333
334fn normalized_section_entry(line: &str) -> &str {
335    line.trim_start_matches(['-', '*']).trim()
336}
337
338/// Check for repetitive text in assistant responses to catch non-tool-calling loops.
339/// Returns true if a loop is detected.
340pub fn check_for_response_loop(response_text: &str, session_state: &mut AgentSessionState) -> bool {
341    if response_text.len() < 10 {
342        return false;
343    }
344
345    // Compare word sequences, ignoring whitespace differences.
346    let repeated = session_state
347        .messages
348        .iter()
349        .rev()
350        .filter(|m| m.role == MessageRole::Assistant)
351        .skip(1)
352        .take(2)
353        .any(|m| {
354            let previous_text = m.content.as_text();
355            previous_text.split_whitespace().eq(response_text.split_whitespace())
356        });
357
358    if repeated {
359        let warning = "Repetitive assistant response detected. Breaking potential loop.".to_string();
360        session_state.push_warning(warning);
361        session_state.consecutive_idle_turns = session_state.consecutive_idle_turns.saturating_add(1);
362        return true;
363    }
364
365    false
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371    use crate::llm::provider::{ContentPart, Message};
372
373    #[test]
374    fn handoff_classification_preserves_case_and_policy_precedence() {
375        for text in [
376            "Permission denied after wall-clock budget exhaustion.",
377            "Access denied.",
378            "Safety fuse reached.",
379            "Tool-call safety fuse stopped verification.",
380            "Policy block remains.",
381            "Blocked by policy.",
382            "Requires manual intervention.",
383            "Missing credentials.",
384            "Credentials are missing.",
385            "Denied by policy.",
386            "Denied by workspace tool policy.",
387            "Denied by tool policy.",
388            "Execution denied by policy.",
389            "Blocked by tool policy.",
390        ] {
391            for variant in [text.to_string(), text.to_ascii_uppercase()] {
392                assert!(tracker_final_text_is_policy_handoff(&variant), "policy: {variant}");
393                assert!(tracker_final_text_is_safety_handoff(&variant), "safety: {variant}");
394            }
395        }
396        for text in [
397            "Verification is still pending after wall-clock budget exhaustion.",
398            "Unverified assistant responses remain.",
399            "Anti-blind checkpoint reached.",
400            "Verification gate remains.",
401        ] {
402            let variant = text.to_ascii_uppercase();
403            assert!(!tracker_final_text_is_policy_handoff(&variant), "policy: {variant}");
404            assert!(tracker_final_text_is_safety_handoff(&variant), "safety: {variant}");
405        }
406        for text in [
407            "",
408            " \t\n\u{2003}",
409            "TOOL LOOP BUDGET EXHAUSTED.",
410            "REVIEWED TOOL POLICY.",
411            "VERIFICATION PASSED.",
412        ] {
413            assert!(!tracker_final_text_is_policy_handoff(text), "policy: {text:?}");
414            assert!(!tracker_final_text_is_safety_handoff(text), "safety: {text:?}");
415        }
416    }
417
418    #[test]
419    fn policy_handoffs_are_distinct_from_pending_verification_recaps() {
420        for text in [
421            "Verification is still pending after the wall-clock budget was exhausted.",
422            "Repeated unverified assistant responses reached the anti-blind verification gate.",
423        ] {
424            assert!(tracker_final_text_is_safety_handoff(text));
425            assert!(!tracker_final_text_is_policy_handoff(text));
426        }
427        for text in [
428            "Verification is still pending; permission denied.",
429            "Tool loop budget exhausted; blocked by tool policy.",
430            "Missing credentials for the verifier.",
431            "Tool-call safety fuse stopped verification.",
432        ] {
433            assert!(tracker_final_text_is_policy_handoff(text));
434            assert!(tracker_final_text_is_safety_handoff(text));
435        }
436    }
437
438    #[test]
439    fn tracker_final_text_is_safety_handoff_vocabulary() {
440        assert!(tracker_final_text_is_safety_handoff(
441            "Permission denied for exec_command. Next step: retry after access is granted."
442        ));
443        assert!(tracker_final_text_is_safety_handoff(
444            "I hit the tool-call safety fuse mid-verification; policy block."
445        ));
446        assert!(tracker_final_text_is_safety_handoff(
447            "Blocked action: exec_command is denied by workspace tool policy."
448        ));
449        assert!(tracker_final_text_is_safety_handoff(
450            "Turn blocked after repeated unverified assistant responses; verification is still pending."
451        ));
452        assert!(tracker_final_text_is_safety_handoff(
453            "Anti-blind checkpoint remains; verification is still pending."
454        ));
455        assert!(!tracker_final_text_is_safety_handoff(
456            "## Status\nBlocked by wall-clock budget. Next step: read design/diff.rs."
457        ));
458        assert!(!tracker_final_text_is_safety_handoff(
459            "## Status\nBlocked by tool loop budget. Next step: patch the struct."
460        ));
461        assert!(!tracker_final_text_is_safety_handoff(
462            "Tool loop budget exhausted; continuing next turn with remaining tracker steps."
463        ));
464        assert!(!tracker_final_text_is_safety_handoff(
465            "Fix 1 partially applied, needs verification; next step is cargo check."
466        ));
467        // Bare tool-policy mention is not a handoff; explicit denial still is.
468        assert!(!tracker_final_text_is_safety_handoff("Reviewed tool policy docs; next step is the tracker patch."));
469        assert!(tracker_final_text_is_safety_handoff(
470            "Blocked action: exec_command is denied by workspace tool policy."
471        ));
472        assert!(!tracker_final_text_is_safety_handoff("Implemented patch apply; verification passed."));
473        assert!(!tracker_final_text_is_safety_handoff(""));
474        // Policy denial wins even when a budget is also mentioned.
475        assert!(tracker_final_text_is_safety_handoff(
476            "Tool loop budget exhausted; denied by policy for exec_command."
477        ));
478        assert!(tracker_final_text_is_safety_handoff("Wall-clock budget hit, then permission denied for the write."));
479    }
480
481    #[test]
482    fn recoverable_status_recap_phrasing_covers_session_budget_recaps() {
483        for phrase in [
484            "blocked by the turn's preview budget",
485            "wall-clock budget ran out",
486            "hit the per-file read cap",
487            "preview budget exhausted",
488            "tool loop budget exhausted",
489            "recovery fallback",
490            "reached the safety cap",
491            "wall-clock budget exhausted",
492        ] {
493            assert!(
494                recoverable_status_recap_phrasing(&phrase.to_ascii_lowercase()),
495                "must treat as recoverable: {phrase}"
496            );
497        }
498        for phrase in [
499            "permission denied for exec_command",
500            "verification is still pending",
501            "needs a user decision",
502        ] {
503            assert!(
504                !recoverable_status_recap_phrasing(&phrase.to_ascii_lowercase()),
505                "must not treat as recoverable budget phrasing: {phrase}"
506            );
507        }
508    }
509
510    #[test]
511    fn tracker_final_text_requires_user_input_vocabulary() {
512        assert!(tracker_final_text_requires_user_input("Step 1 done. Which branch should I use for step 2?"));
513        assert!(tracker_final_text_requires_user_input(
514            "## Status\nPlease confirm whether to use the stable schema."
515        ));
516        assert!(tracker_final_text_requires_user_input("Can you confirm the migration path before I edit."));
517        assert!(!tracker_final_text_requires_user_input(
518            "## Status\nNext we need your workspace path in CONFIG; patching the struct now."
519        ));
520        assert!(!tracker_final_text_requires_user_input("Blocked by wall-clock budget. Next step: read helpers.rs."));
521        assert!(!tracker_final_text_requires_user_input(""));
522    }
523
524    #[test]
525    fn test_completion_candidates() {
526        assert!(check_completion_candidate("The task is complete"));
527        assert!(check_completion_candidate("Revision 1: task is complete."));
528        assert!(check_completion_candidate("I have successfully completed the task."));
529        assert!(check_completion_candidate("Task done"));
530        assert!(check_completion_candidate("All done"));
531
532        // Negative cases
533        assert!(!check_completion_candidate("I will have the task done soon"));
534        assert!(!check_completion_candidate("Is the task done?"));
535        assert!(!check_completion_candidate("random text"));
536        assert!(!check_completion_candidate("The task is complete once verification finishes."));
537        assert!(!check_completion_candidate("All done. Verification pending."));
538        assert!(!check_completion_candidate("All done, but open questions remain."));
539    }
540
541    #[test]
542    fn subagent_markdown_contract_detected_as_complete() {
543        let contract = "## Summary\n- Background subprocess launched; PID 86065.\n\n## Facts\n- Script started at 2026-04-25T08:39:10Z.\n\n## Touched Files\n- None\n\n## Verification\n- Process confirmed.\n\n## Open Questions\n- None";
544        assert!(check_completion_candidate(contract));
545    }
546
547    #[test]
548    fn subagent_markdown_contract_with_crlf_detected_as_complete() {
549        let contract = "## Summary\r\n- Done.\r\n\r\n## Facts\r\n- Fact 1.\r\n";
550        assert!(check_completion_candidate(contract));
551    }
552
553    #[test]
554    fn subagent_markdown_contract_with_leading_whitespace_detected() {
555        let contract = "\n\n## Summary\n- item\n\n## Facts\n- fact\n";
556        assert!(check_completion_candidate(contract));
557    }
558
559    #[test]
560    fn document_with_only_summary_header_not_detected() {
561        let doc = "## Summary\n- This is a doc without a Facts section.\n";
562        assert!(!check_completion_candidate(doc));
563    }
564
565    #[test]
566    fn document_with_only_facts_header_not_detected() {
567        let doc = "## Facts\n- Fact without summary.\n";
568        assert!(!check_completion_candidate(doc));
569    }
570
571    #[test]
572    fn structured_contract_with_open_questions_is_not_complete() {
573        let doc = "## Summary\n- Work applied.\n\n## Facts\n- Fact.\n\n## Verification\n- Process confirmed.\n\n## Open Questions\n- Need to rerun the end-to-end flow.";
574        assert!(!check_completion_candidate(doc));
575    }
576
577    #[test]
578    fn structured_contract_with_unresolved_verification_is_not_complete() {
579        let doc = "## Summary\n- Work applied.\n\n## Facts\n- Fact.\n\n## Verification\n- Verification pending.\n\n## Open Questions\n- None";
580        assert!(!check_completion_candidate(doc));
581    }
582
583    #[test]
584    fn structured_contract_with_none_punctuation_is_complete() {
585        let doc = "## Summary\n- Work applied.\n\n## Facts\n- Fact.\n\n## Verification\n- Process confirmed.\n\n## Open Questions\n- None.";
586        assert!(check_completion_candidate(doc));
587    }
588
589    #[test]
590    fn response_loop_ignores_current_assistant_message() {
591        let repeated_response = "The task is complete";
592        let mut state = AgentSessionState::new("session".to_string(), 8, 4, 128_000);
593        state.messages_mut().push(Message::assistant(repeated_response.to_string()));
594        let history = state.messages.clone();
595        state.push_warning("Existing warning");
596        state.consecutive_idle_turns = 3;
597
598        assert!(!check_for_response_loop(repeated_response, &mut state));
599        assert_eq!(state.warnings, ["Existing warning"]);
600        assert_eq!(state.consecutive_idle_turns, 3);
601        assert!(std::sync::Arc::ptr_eq(&history, &state.messages));
602    }
603
604    #[test]
605    fn response_loop_still_detects_prior_duplicate_assistant_message() {
606        let repeated_response = "The task is complete";
607        for prior_position in 0..2 {
608            let mut state = AgentSessionState::new("session".to_string(), 8, 4, 128_000);
609            for position in 0..2 {
610                let text = if position == prior_position {
611                    repeated_response
612                } else {
613                    "A different earlier response"
614                };
615                state.messages_mut().push(Message::assistant(text.to_string()));
616            }
617            state.messages_mut().push(Message::assistant(repeated_response.to_string()));
618
619            assert!(check_for_response_loop(repeated_response, &mut state), "prior position {prior_position}");
620        }
621    }
622
623    #[test]
624    fn response_loop_equates_ascii_and_unicode_whitespace() {
625        for response in [
626            "The task is complete",
627            " \tThe\r\ntask\u{000b}is\u{000c}complete  ",
628            "\u{00a0}The\u{2003}task\u{2028}is\u{3000}complete\u{0085}",
629        ] {
630            let mut state = AgentSessionState::new("session".to_string(), 8, 4, 128_000);
631            state
632                .messages_mut()
633                .push(Message::assistant("The\ttask  is\ncomplete".to_string()));
634            state.messages_mut().push(Message::assistant(response.to_string()));
635
636            assert!(check_for_response_loop(response, &mut state), "response: {response:?}");
637        }
638    }
639
640    #[test]
641    fn response_loop_equates_whitespace_only_responses() {
642        let response = " \t\n\r\u{2003}\u{3000}";
643        let mut state = AgentSessionState::new("session".to_string(), 8, 4, 128_000);
644        state.messages_mut().push(Message::assistant("\n \t".to_string()));
645        state.messages_mut().push(Message::assistant(response.to_string()));
646
647        assert!(check_for_response_loop(response, &mut state));
648    }
649
650    #[test]
651    fn response_loop_rejects_different_word_sequences_without_mutating_state() {
652        for response in [
653            "The task complete is",
654            "the task is complete",
655            "The task is complete.",
656            "The task is",
657            "The task is complete now",
658            "Thetask is complete",
659            "The\u{200b}task is complete",
660        ] {
661            let mut state = AgentSessionState::new("session".to_string(), 8, 4, 128_000);
662            state
663                .messages_mut()
664                .push(Message::assistant("The task is complete".to_string()));
665            state.messages_mut().push(Message::assistant(response.to_string()));
666            let history = state.messages.clone();
667            state.push_warning("Existing warning");
668            state.consecutive_idle_turns = 3;
669
670            assert!(!check_for_response_loop(response, &mut state), "response: {response:?}");
671            assert_eq!(state.warnings, ["Existing warning"]);
672            assert_eq!(state.consecutive_idle_turns, 3);
673            assert!(std::sync::Arc::ptr_eq(&history, &state.messages));
674        }
675    }
676
677    #[test]
678    fn response_loop_ignores_duplicates_outside_prior_assistant_window() {
679        let response = "The task is complete";
680        let mut state = AgentSessionState::new("session".to_string(), 8, 4, 128_000);
681        for text in [
682            response,
683            "Second older response",
684            "Most recent prior response",
685            response,
686        ] {
687            state.messages_mut().push(Message::assistant(text.to_string()));
688        }
689        let history = state.messages.clone();
690
691        assert!(!check_for_response_loop(response, &mut state));
692        assert!(state.warnings.is_empty());
693        assert_eq!(state.consecutive_idle_turns, 0);
694        assert!(std::sync::Arc::ptr_eq(&history, &state.messages));
695    }
696
697    #[test]
698    fn response_loop_filters_interleaved_user_and_tool_messages_before_windowing() {
699        let response = "The task is complete";
700        for prior_response in [response, "An unrelated prior response"] {
701            let mut state = AgentSessionState::new("session".to_string(), 8, 4, 128_000);
702            state.messages_mut().extend([
703                Message::assistant(prior_response.to_string()),
704                Message::user(response.to_string()),
705                Message::tool_response("older-call".to_string(), response.to_string()),
706                Message::assistant("Another prior response".to_string()),
707                Message::user(response.to_string()),
708                Message::tool_response("recent-call".to_string(), response.to_string()),
709                Message::assistant(response.to_string()),
710                Message::user(response.to_string()),
711                Message::tool_response("latest-call".to_string(), response.to_string()),
712            ]);
713
714            assert_eq!(check_for_response_loop(response, &mut state), prior_response == response);
715        }
716    }
717
718    #[test]
719    fn response_loop_preserves_ten_byte_cutoff() {
720        for response in ["123456789", "éééé", "1234567890", "ééééé"] {
721            let mut state = AgentSessionState::new("session".to_string(), 8, 4, 128_000);
722            state.messages_mut().push(Message::assistant(response.to_string()));
723            state.messages_mut().push(Message::assistant(response.to_string()));
724
725            let expected = matches!(response, "1234567890" | "ééééé");
726            assert_eq!(check_for_response_loop(response, &mut state), expected, "response: {response:?}");
727            assert_eq!(state.warnings.len(), usize::from(expected));
728            assert_eq!(state.consecutive_idle_turns, usize::from(expected));
729        }
730    }
731
732    #[test]
733    fn response_loop_preserves_multipart_text_concatenation() {
734        for response in ["The task is complete", "The ta sk is complete"] {
735            let mut state = AgentSessionState::new("session".to_string(), 8, 4, 128_000);
736            state.messages_mut().push(Message::assistant_with_parts(vec![
737                ContentPart::Text { text: "The ta".to_string() },
738                ContentPart::Text { text: "sk\tis complete".to_string() },
739            ]));
740            state.messages_mut().push(Message::assistant(response.to_string()));
741            let history = state.messages.clone();
742
743            assert_eq!(check_for_response_loop(response, &mut state), response == "The task is complete");
744            assert!(std::sync::Arc::ptr_eq(&history, &state.messages));
745        }
746    }
747
748    #[test]
749    fn response_loop_preserves_warning_and_saturating_idle_counter() {
750        let response = "The task is complete";
751        for initial_idle_turns in [3, usize::MAX] {
752            let mut state = AgentSessionState::new("session".to_string(), 8, 4, 128_000);
753            state.messages_mut().push(Message::assistant(response.to_string()));
754            state.messages_mut().push(Message::assistant(response.to_string()));
755            let history = state.messages.clone();
756            state.push_warning("Existing warning");
757            state.consecutive_idle_turns = initial_idle_turns;
758
759            assert!(check_for_response_loop(response, &mut state));
760            assert_eq!(state.consecutive_idle_turns, if initial_idle_turns == 3 { 4 } else { usize::MAX });
761            assert_eq!(
762                state.warnings,
763                [
764                    "Existing warning",
765                    "Repetitive assistant response detected. Breaking potential loop."
766                ]
767            );
768            assert!(std::sync::Arc::ptr_eq(&history, &state.messages));
769        }
770    }
771}