vtcode 0.136.4

A Rust-based terminal coding agent with modular architecture supporting multiple LLM providers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
//! Turn-loop helpers for recovering after tool output when the follow-up LLM phase fails.

use anyhow::Result;
use vtcode_commons::ErrorCategory;
use vtcode_core::llm::provider as uni;
use vtcode_core::tools::handlers::planning_workflow::{PlanningWorkflowState, persist_plan_draft};
use vtcode_core::utils::ansi::{AnsiRenderer, MessageStyle};

use super::{
    MAX_POST_TOOL_RECOVERY_CYCLES, PLANNING_RECOVERY_SYNTHESIS_FALLBACK,
    PLANNING_RECOVERY_SYNTHESIS_FALLBACK_NO_INTERVIEW, POST_TOOL_RECOVERY_REASON, POST_TOOL_RECOVERY_REASON_PLAN_MODE,
    POST_TOOL_RESUME_DIRECTIVE, RECOVERY_CONTRACT_VIOLATION_REASON, RECOVERY_SYNTHESIS_FALLBACK_FINAL_ANSWER,
};
use crate::agent::runloop::unified::plan_blocks::extract_any_plan;
use crate::agent::runloop::unified::planning_workflow_state::{
    PlanningWorkflowSessionState, short_confirmation_hint_with_fallback,
};
use crate::agent::runloop::unified::run_loop_context::HarnessTurnState;
use crate::agent::runloop::unified::turn::context::TurnLoopResult;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum PostToolFailureRecovery {
    NotApplicable,
    RetryToolFree,
    StopAfterDirective,
}

pub(super) fn has_tool_response_since(messages: &[uni::Message], baseline_len: usize) -> bool {
    messages
        .get(baseline_len..)
        .is_some_and(|recent| recent.iter().any(|msg| msg.role == uni::MessageRole::Tool))
}

fn ensure_recent_system_message(working_history: &mut Vec<uni::Message>, content: &str) {
    let already_present = working_history
        .iter()
        .rev()
        .take(3)
        .any(|message| message.role == uni::MessageRole::System && message.content.as_text() == content);
    if already_present {
        return;
    }

    working_history.push(uni::Message::system(content.to_string()));
}

pub(super) fn ensure_post_tool_resume_directive(working_history: &mut Vec<uni::Message>) {
    ensure_recent_system_message(working_history, POST_TOOL_RESUME_DIRECTIVE);
}

pub(crate) fn prepare_post_tool_tool_free_recovery(working_history: &mut Vec<uni::Message>, reason: &str) {
    // Deliberately do NOT push POST_TOOL_RESUME_DIRECTIVE here: it instructs
    // the model to follow tool-output guidance (`next_action`, `fallback_tool`,
    // `rerun_hint`), which contradicts the tool-free recovery contract and
    // encourages emitting tool-call markup (observed in checkpoint turn_621,
    // where three stacked, conflicting system directives preceded a failed
    // synthesis). Only the tools-disabled recovery reason is injected.
    ensure_recent_system_message(working_history, reason);
}

pub(super) fn maybe_recover_after_post_tool_llm_failure(
    renderer: &mut AnsiRenderer,
    working_history: &mut Vec<uni::Message>,
    err: &anyhow::Error,
    step_count: usize,
    turn_history_start_len: usize,
    failure_stage: &'static str,
    allow_tool_free_retry: bool,
    planning_active: bool,
) -> Result<PostToolFailureRecovery> {
    let has_partial_tool_progress = has_tool_response_since(working_history, turn_history_start_len);
    if !has_partial_tool_progress {
        return Ok(PostToolFailureRecovery::NotApplicable);
    }

    let err_cat = vtcode_commons::classify_anyhow_error(err);
    let transient_hint = if err_cat.is_retryable() {
        " (transient — may resolve on retry)"
    } else {
        ""
    };
    let summary =
        format!("Tool execution completed, but the model follow-up failed{transient_hint}. Output above is valid.",);
    renderer.line(MessageStyle::Info, &summary)?;
    renderer.line(MessageStyle::Info, &format!("Follow-up error category: {}", err_cat.user_label()))?;
    if !err_cat.is_retryable() {
        renderer.line(
            MessageStyle::Info,
            "Tip: rerun with a narrower prompt or switch provider/model for the follow-up.",
        )?;
    }
    let should_retry =
        allow_tool_free_retry && (err_cat.is_retryable() || matches!(err_cat, ErrorCategory::ExecutionError));
    let action = if should_retry {
        // Tool-free recovery: inject only the tools-disabled recovery reason.
        // The resume directive would contradict it (see
        // `prepare_post_tool_tool_free_recovery`). In plan mode use the
        // plan-aware reason so the model finalizes the `<proposed_plan>` from
        // gathered research instead of re-attempting tool calls.
        let reason = if planning_active {
            POST_TOOL_RECOVERY_REASON_PLAN_MODE
        } else {
            POST_TOOL_RECOVERY_REASON
        };
        prepare_post_tool_tool_free_recovery(working_history, reason);
        renderer.line(
            MessageStyle::Info,
            "[!] Follow-up failed after tool execution; scheduling a final tool-free recovery pass.",
        )?;
        PostToolFailureRecovery::RetryToolFree
    } else {
        // Turn ends here; the resume directive guides the *next* turn to
        // reuse this turn's tool outputs instead of re-running exploration.
        ensure_post_tool_resume_directive(working_history);
        PostToolFailureRecovery::StopAfterDirective
    };

    tracing::warn!(
        error = %err,
        step = step_count,
        stage = failure_stage,
        category = ?err_cat,
        retryable = err_cat.is_retryable(),
        recovery_action = ?action,
        "Recovered turn after post-tool LLM phase failure"
    );
    Ok(action)
}

/// Extract file paths from tool responses in the working history.
/// Looks for JSON tool outputs that contain a `path` field, which indicates
/// a file read operation. Returns deduplicated paths.
fn gather_files_read_this_turn(working_history: &[uni::Message]) -> Vec<String> {
    let mut files = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for msg in working_history.iter() {
        if msg.role != uni::MessageRole::Tool {
            continue;
        }
        let text = msg.content.as_text();
        // Tool outputs are JSON with a `path` field for file reads.
        if let Ok(val) = serde_json::from_str::<serde_json::Value>(&text) {
            if let Some(path) = val.get("path").and_then(serde_json::Value::as_str) {
                if seen.insert(path.to_string()) {
                    files.push(path.to_string());
                }
            }
        }
    }
    files
}

/// Plan-mode recovery fallback. When the tool-free synthesis fails, the
/// "salvaged" text is usually just a rambling recovery monologue with tool-call
/// markup stripped out — not a plan. Injecting that as the plan the user sees is
/// worse than the structured plan-mode message. We only keep the salvage when it
/// actually contains a `<proposed_plan>` (a real, if partial, plan); otherwise we
/// fall back to the informative plan-mode message so the turn ends cleanly
/// instead of leaking garbage into the proposed plan.
fn plan_mode_recovery_fallback(
    salvaged_text: Option<String>,
    structured_message: &str,
    working_history: &[uni::Message],
) -> String {
    if let Some(text) = salvaged_text
        && text.trim().contains("<proposed_plan")
    {
        // Trim only the outer whitespace so a plan salvaged with stray
        // blank lines isn't injected with that garbage framing intact.
        text.trim().to_string()
    } else {
        build_recovery_fallback(working_history, structured_message)
    }
}

/// Build the deterministic recovery fallback, optionally appending the list of
/// files already read this turn so the next turn can reuse them instead of
/// re-exploring. `lead_in` is the provider-agnostic message shown first.
fn build_recovery_fallback(working_history: &[uni::Message], lead_in: &str) -> String {
    let files_read = gather_files_read_this_turn(working_history);
    if files_read.is_empty() {
        lead_in.to_string()
    } else {
        format!(
            "{lead_in}\n\nFiles already read this turn (do NOT re-read):\n{}",
            files_read.iter().map(|f| format!("  - {f}")).collect::<Vec<_>>().join("\n")
        )
    }
}

pub(super) async fn complete_turn_after_failed_tool_free_recovery(
    working_history: &mut Vec<uni::Message>,
    failure_stage: &str,
    err: Option<&anyhow::Error>,
    salvaged_text: Option<String>,
    plan_session: Option<&mut PlanningWorkflowSessionState>,
    plan_state: Option<&PlanningWorkflowState>,
) -> TurnLoopResult {
    // In plan mode, the recovery salvage (the inline `<proposed_plan>` the model
    // produced) must be persisted to the session plan file even though tools
    // were disabled during the tool-free recovery pass. Otherwise the plan
    // exists only in chat history while the user-facing notices promise it is
    // "preserved in the session plan file (.vtcode/plans/)". Best-effort: a
    // write failure is logged and must never dead-end the turn.
    if let (Some(state), Some(salvaged)) = (plan_state, salvaged_text.as_ref()) {
        if let Some(plan_text) = extract_any_plan(salvaged).plan_text {
            if state.get_plan_file().await.is_some() {
                if let Err(e) = persist_plan_draft(state, &plan_text).await {
                    tracing::warn!(
                        error = %e,
                        "plan-mode recovery: failed to persist salvaged plan to session plan file"
                    );
                }
            }
        }
    }

    // Plan mode: never dead-end. Preserve the planning session and re-force
    // the interview on the next turn (unless budget/recovery is exhausted).
    // A rejected synthesis usually leaves only a garbled recovery monologue
    // with tool-call markup stripped out — not a plan. We therefore only
    // surface the salvaged prose when it actually contains a `<proposed_plan>`
    // (a real, if partial, plan); otherwise we fall back to the structured
    // plan-aware message, which still lists the files read this turn, so we
    // never inject garbage as the proposed plan. See `plan_mode_recovery_fallback`.
    //
    // EXCEPTION:
    // If the budget is exhausted, do NOT mark interview as pending because no
    // further LLM calls are possible and re-forcing the interview would loop
    // forever. Instead, finalize the plan from gathered evidence.
    //
    // Transient (retryable) errors are intentionally NOT finalized here. The
    // interview-synthesis call now retries internally and falls back to an
    // adaptive interview, so re-forcing the interview on the next turn makes
    // forward progress instead of dead-ending. We keep the planning session
    // alive and preserve the research gathered this turn.
    let is_transient_error = err
        .map(|e| vtcode_commons::classify_anyhow_error(e).is_retryable())
        .unwrap_or(false);
    if let Some(plan_session) = plan_session {
        if plan_session.is_budget_exhausted()
            || plan_session.is_recovery_exhausted()
            || plan_session.is_interview_denied()
        {
            // NOTE: use the USER-facing notices here, not the `*_FINALIZE`
            // model directives. No LLM call follows this path, so a model
            // directive pushed as the final answer just shows the user a bare
            // instruction and dead-ends the turn (checkpoint turn_655). The
            // planning session stays alive, so append the confirmation hint —
            // the user can type `implement` to execute the drafted plan or
            // `keep planning` to revise it.
            let finalize_message = if plan_session.is_budget_exhausted() {
                super::PLANNING_BUDGET_EXHAUSTED_USER_NOTICE
            } else if plan_session.is_recovery_exhausted() {
                super::PLANNING_RECOVERY_EXHAUSTED_USER_NOTICE
            } else {
                PLANNING_RECOVERY_SYNTHESIS_FALLBACK_NO_INTERVIEW
            };
            let mut planning_fallback = plan_mode_recovery_fallback(salvaged_text, finalize_message, working_history);
            planning_fallback.push_str("\n\n");
            planning_fallback.push_str(&short_confirmation_hint_with_fallback());
            push_final_answer_if_absent(working_history, &planning_fallback);
            tracing::warn!(
                stage = failure_stage,
                budget_exhausted = plan_session.is_budget_exhausted(),
                recovery_exhausted = plan_session.is_recovery_exhausted(),
                interview_denied = plan_session.is_interview_denied(),
                "Plan-mode tool-free recovery failed; finalizing plan from gathered evidence."
            );
            return TurnLoopResult::Completed;
        }
        plan_session.mark_interview_pending();
        let planning_fallback =
            plan_mode_recovery_fallback(salvaged_text, PLANNING_RECOVERY_SYNTHESIS_FALLBACK, working_history);
        push_final_answer_if_absent(working_history, &planning_fallback);
        tracing::warn!(
            stage = failure_stage,
            transient_error = is_transient_error,
            "Plan-mode tool-free recovery failed; marking interview pending for next turn."
        );
        return TurnLoopResult::Completed;
    }

    // Prefer prose salvaged from a rejected synthesis response over the
    // canned fallback string: a partially cleaned answer still reflects the
    // tool outputs gathered this turn, while the canned string discards them.
    if let Some(salvaged) = salvaged_text.filter(|text| !text.trim().is_empty()) {
        let answer = format!(
            "[!] Recovery synthesis was interrupted; best-effort answer below \
             (tool-call markup removed):\n\n{salvaged}"
        );
        push_final_answer_if_absent(working_history, &answer);
        tracing::warn!(
            stage = failure_stage,
            "Tool-free recovery failed; concluding turn with salvaged synthesis prose."
        );
        return TurnLoopResult::Completed;
    }

    let fallback = build_recovery_fallback(working_history, RECOVERY_SYNTHESIS_FALLBACK_FINAL_ANSWER);
    push_final_answer_if_absent(working_history, &fallback);

    tracing::warn!(
        stage = failure_stage,
        error = ?err,
        "Final tool-free recovery pass failed; concluding turn with deterministic fallback answer."
    );

    TurnLoopResult::Completed
}

/// Push an `Assistant` `FinalAnswer` message only if the tail of
/// `working_history` does not already contain the same fallback text, so
/// repeated recovery attempts don't stack duplicate final answers.
fn push_final_answer_if_absent(working_history: &mut Vec<uni::Message>, text: &str) {
    let already_present = working_history.iter().rev().take(3).any(|message| {
        message.role == uni::MessageRole::Assistant
            && message.phase == Some(uni::AssistantPhase::FinalAnswer)
            && message.content.as_text() == text
    });
    if !already_present {
        working_history
            .push(uni::Message::assistant(text.to_string()).with_phase(Some(uni::AssistantPhase::FinalAnswer)));
    }
}

pub(super) async fn normalize_tool_free_recovery_break_outcome(
    working_history: &mut Vec<uni::Message>,
    outcome_result: TurnLoopResult,
    tool_free_recovery: bool,
    salvaged_text: Option<String>,
    plan_session: Option<&mut PlanningWorkflowSessionState>,
    plan_state: Option<&PlanningWorkflowState>,
) -> TurnLoopResult {
    let should_fallback = tool_free_recovery
        && matches!(
            outcome_result,
            TurnLoopResult::Blocked {
                reason: Some(ref reason)
            } if reason == RECOVERY_CONTRACT_VIOLATION_REASON
        );

    if should_fallback {
        return complete_turn_after_failed_tool_free_recovery(
            working_history,
            "handle_turn_processing_result.tool_free_recovery_contract_violation",
            None,
            salvaged_text,
            plan_session,
            plan_state,
        )
        .await;
    }

    outcome_result
}

/// Action the turn loop should take after dispatching a post-tool failure.
#[derive(Debug)]
pub(super) enum PostToolFailureAction {
    /// Continue the loop (after RetryToolFree).
    Continue,
    /// Break with the given result (after StopAfterDirective or cycle cap).
    Break(TurnLoopResult),
    /// Fall through to error display and abort (block A only).
    Fallthrough,
}

/// Bundled inputs for post-tool failure recovery. Replaces the nine positional
/// borrows that previously reached directly into the turn context, giving the
/// recovery module a single, stable interface (guard rail) and making it
/// independently testable without the full turn-loop context.
pub(super) struct PostToolRecoveryContext<'a> {
    pub renderer: &'a mut AnsiRenderer,
    pub working_history: &'a mut Vec<uni::Message>,
    pub harness_state: &'a mut HarnessTurnState,
    pub plan_session: Option<&'a mut PlanningWorkflowSessionState>,
    pub plan_state: Option<&'a PlanningWorkflowState>,
    pub err: &'a anyhow::Error,
    pub step_count: usize,
    pub turn_history_start_len: usize,
    pub stage: &'static str,
    pub tool_free_recovery: bool,
}

/// Dispatch the post-tool failure recovery match block, deduplicating the
/// near-identical 3× match in `run_turn_loop`.
///
/// Returns the action the caller should take: continue the loop, break with a
/// result, or fall through to error display.
pub(super) async fn dispatch_post_tool_failure(ctx: PostToolRecoveryContext<'_>) -> Result<PostToolFailureAction> {
    let PostToolRecoveryContext {
        renderer,
        working_history,
        harness_state,
        mut plan_session,
        plan_state,
        err,
        step_count,
        turn_history_start_len,
        stage,
        tool_free_recovery,
    } = ctx;
    let planning_active = plan_session.is_some();
    // Plan-mode: if this turn's tool wall-clock budget was exhausted, the
    // planning context is saturated — the model spent the entire budget on
    // research and the synthesis still failed. Mark the session
    // recovery-exhausted so the failure path below finalizes the plan from
    // gathered evidence instead of re-forcing the interview, which would
    // re-research the still-huge context for another full wall-clock budget
    // and loop forever across turns (observed in checkpoint turn_647).
    // `wall_clock_exhausted()` (time-based) also covers exhaustion without a
    // rejected tool call, e.g. a provider error right after a long tool batch.
    if (harness_state.wall_clock_exhausted_emitted
        || harness_state.wall_clock_exhausted()
        || harness_state.tool_budget_exhausted_emitted)
        && let Some(session) = plan_session.as_deref_mut()
    {
        session.mark_recovery_exhausted();
    }
    let recovery = maybe_recover_after_post_tool_llm_failure(
        renderer,
        working_history,
        err,
        step_count,
        turn_history_start_len,
        stage,
        !tool_free_recovery,
        planning_active,
    )?;

    match recovery {
        PostToolFailureRecovery::NotApplicable => {
            // Block A only: when tool_free_recovery is true and recovery is
            // not applicable, the turn still fails with a deterministic
            // fallback. Blocks B and C never reach this path.
            if tool_free_recovery {
                let salvaged = harness_state.take_recovery_rejected_synthesis();
                let direct_stage = concat_compact(stage, ".direct_tool_free_failure");
                let result = complete_turn_after_failed_tool_free_recovery(
                    working_history,
                    &direct_stage,
                    Some(err),
                    salvaged,
                    plan_session,
                    plan_state,
                )
                .await;
                Ok(PostToolFailureAction::Break(result))
            } else {
                Ok(PostToolFailureAction::Fallthrough)
            }
        }
        PostToolFailureRecovery::RetryToolFree => {
            let salvaged = harness_state.take_recovery_rejected_synthesis();
            let cycle_stage = concat_compact(stage, ".recovery_cycle_cap");
            if let Some(r) = check_recovery_cycle_cap(
                harness_state.post_tool_recovery_cycles(),
                working_history,
                &cycle_stage,
                err,
                salvaged,
                plan_session,
                plan_state,
            )
            .await
            {
                return Ok(PostToolFailureAction::Break(r));
            }
            harness_state.increment_post_tool_recovery_cycle();
            harness_state.switch_to_tool_free_recovery();
            Ok(PostToolFailureAction::Continue)
        }
        PostToolFailureRecovery::StopAfterDirective => {
            let result = if tool_free_recovery {
                let salvaged = harness_state.take_recovery_rejected_synthesis();
                let directive_stage = concat_compact(stage, ".stop_after_directive");
                complete_turn_after_failed_tool_free_recovery(
                    working_history,
                    &directive_stage,
                    Some(err),
                    salvaged,
                    plan_session,
                    plan_state,
                )
                .await
            } else {
                TurnLoopResult::Completed
            };
            Ok(PostToolFailureAction::Break(result))
        }
    }
}

/// Concatenate two `&str` into a `String` for composite stage labels.
fn concat_compact(a: &str, b: &str) -> String {
    let mut buf = String::with_capacity(a.len() + b.len());
    buf.push_str(a);
    buf.push_str(b);
    buf
}

/// Shared logic for the `PostToolFailureRecovery::RetryToolFree` arm.
///
/// Checks the post-tool recovery cycle cap. If the cap is reached, completes
/// the turn with a deterministic fallback answer and returns `Some(result)`.
/// Otherwise returns `None`. The caller should increment the cycle counter,
/// switch to tool-free recovery, and `continue` the turn loop.
async fn check_recovery_cycle_cap(
    cycles: u8,
    working_history: &mut Vec<uni::Message>,
    stage: &str,
    err: &anyhow::Error,
    salvaged_text: Option<String>,
    mut plan_session: Option<&mut PlanningWorkflowSessionState>,
    plan_state: Option<&PlanningWorkflowState>,
) -> Option<TurnLoopResult> {
    if cycles >= MAX_POST_TOOL_RECOVERY_CYCLES {
        tracing::warn!(
            cycles,
            "Post-tool recovery cycle cap reached; concluding turn \
             with deterministic fallback answer"
        );
        // In plan mode, repeated tool-free synthesis failures mean the
        // planning context is saturated. Mark the session recovery-exhausted
        // so the next turn does NOT re-force the interview (which would
        // re-research the still-huge context and loop forever). The call
        // below then finalizes the plan from gathered evidence.
        if let Some(plan_session) = plan_session.as_deref_mut() {
            plan_session.mark_recovery_exhausted();
        }
        return Some(
            complete_turn_after_failed_tool_free_recovery(
                working_history,
                stage,
                Some(err),
                salvaged_text,
                plan_session,
                plan_state,
            )
            .await,
        );
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::runloop::unified::planning_workflow_state::PlanningWorkflowSessionState;
    use vtcode_commons::llm::LLMError;

    fn transient_err() -> anyhow::Error {
        anyhow::Error::new(LLMError::Network {
            message: "simulated network blip".to_string(),
            metadata: None,
        })
    }

    #[tokio::test]
    async fn tool_free_recovery_keeps_planning_alive_on_transient_error() {
        let mut working_history: Vec<uni::Message> = Vec::new();
        let mut plan_session = PlanningWorkflowSessionState::default();

        let result = complete_turn_after_failed_tool_free_recovery(
            &mut working_history,
            "stage",
            Some(&transient_err()),
            None,
            Some(&mut plan_session),
            None,
        )
        .await;

        assert!(matches!(result, TurnLoopResult::Completed));
        assert!(
            plan_session.interview_pending(),
            "transient error must keep planning alive by re-forcing the interview"
        );
    }

    #[tokio::test]
    async fn tool_free_recovery_keeps_planning_alive_on_non_transient_error() {
        let mut working_history: Vec<uni::Message> = Vec::new();
        let mut plan_session = PlanningWorkflowSessionState::default();
        let err = anyhow::Error::new(LLMError::InvalidRequest { message: "bad request".to_string(), metadata: None });

        let result = complete_turn_after_failed_tool_free_recovery(
            &mut working_history,
            "stage",
            Some(&err),
            None,
            Some(&mut plan_session),
            None,
        )
        .await;

        assert!(matches!(result, TurnLoopResult::Completed));
        assert!(
            plan_session.interview_pending(),
            "any tool-free recovery failure must keep planning alive (not dead-end)"
        );
    }

    #[tokio::test]
    async fn dispatch_marks_recovery_exhausted_when_wall_clock_exhausted_in_plan_mode() {
        use crate::agent::runloop::unified::run_loop_context::{HarnessTurnState, TurnId, TurnRunId};
        use vtcode_core::utils::ansi::AnsiRenderer;

        let mut renderer = AnsiRenderer::stdout();
        let mut working_history: Vec<uni::Message> = Vec::new();
        let mut harness_state =
            HarnessTurnState::new(TurnRunId("test-run".to_string()), TurnId("test-turn".to_string()), 4, 600, 0);
        harness_state.wall_clock_exhausted_emitted = true;
        let mut plan_session = PlanningWorkflowSessionState::default();
        let err = transient_err();

        let action = dispatch_post_tool_failure(PostToolRecoveryContext {
            renderer: &mut renderer,
            working_history: &mut working_history,
            harness_state: &mut harness_state,
            plan_session: Some(&mut plan_session),
            plan_state: None,
            err: &err,
            step_count: 1,
            turn_history_start_len: 0,
            stage: "stage",
            tool_free_recovery: true,
        })
        .await
        .expect("dispatch must not error");

        assert!(
            plan_session.is_recovery_exhausted(),
            "wall-clock exhaustion during planning must mark the session \
             recovery-exhausted so the plan finalizes instead of looping"
        );
        assert!(!plan_session.interview_pending(), "must not re-force the interview after wall-clock exhaustion");
        assert!(matches!(action, PostToolFailureAction::Break(_)));
    }

    #[tokio::test]
    async fn tool_free_recovery_finalizes_when_budget_exhausted() {
        let mut working_history: Vec<uni::Message> = Vec::new();
        let mut plan_session = PlanningWorkflowSessionState::default();
        plan_session.mark_budget_exhausted();

        let result = complete_turn_after_failed_tool_free_recovery(
            &mut working_history,
            "stage",
            Some(&transient_err()),
            None,
            Some(&mut plan_session),
            None,
        )
        .await;

        assert!(matches!(result, TurnLoopResult::Completed));
        assert!(
            !plan_session.interview_pending(),
            "budget-exhausted must not re-force the interview (would loop forever)"
        );
        assert!(
            working_history.iter().any(|m| m.role == uni::MessageRole::Assistant),
            "budget-exhausted must finalize the plan with a fallback answer"
        );
    }

    #[tokio::test]
    async fn plan_mode_recovery_rejects_garbled_tool_call_salvage() {
        // When the tool-free synthesis fails and the only "salvage" is a
        // rambling monologue with tool-call markup stripped out (no real
        // plan), plan mode must NOT inject that garbage as the proposed plan.
        let mut working_history: Vec<uni::Message> = Vec::new();
        let mut plan_session = PlanningWorkflowSessionState::default();
        let garbled = "I have enough to plan. <invoke name=\"unified_search\"> \
            read more files</invoke> Here is my half-baked plan.";

        let result = complete_turn_after_failed_tool_free_recovery(
            &mut working_history,
            "stage",
            None,
            Some(garbled.to_string()),
            Some(&mut plan_session),
            None,
        )
        .await;

        assert!(matches!(result, TurnLoopResult::Completed));
        assert!(plan_session.interview_pending(), "non-exhausted plan failure must re-force the interview");
        let text = working_history
            .iter()
            .rev()
            .find(|m| m.role == uni::MessageRole::Assistant)
            .expect("a final answer must be pushed")
            .content
            .as_text();
        assert!(
            text.contains("final synthesis failed"),
            "plan-mode fallback must be the structured message, not garbled salvage: {text}"
        );
        assert!(!text.contains("unified_search"), "garbled tool-call salvage must not leak into the plan: {text}");
    }

    #[tokio::test]
    async fn plan_mode_recovery_keeps_partial_proposed_plan_salvage() {
        // A real (if partial) proposed plan in the salvage is worth keeping.
        let mut working_history: Vec<uni::Message> = Vec::new();
        let mut plan_session = PlanningWorkflowSessionState::default();
        let partial_plan =
            "<proposed_plan>\n- Action: add caching -> src/cache.rs\n  verify: cargo test\n</proposed_plan>";

        let result = complete_turn_after_failed_tool_free_recovery(
            &mut working_history,
            "stage",
            None,
            Some(partial_plan.to_string()),
            Some(&mut plan_session),
            None,
        )
        .await;

        assert!(matches!(result, TurnLoopResult::Completed));
        let text = working_history
            .iter()
            .rev()
            .find(|m| m.role == uni::MessageRole::Assistant)
            .expect("a final answer must be pushed")
            .content
            .as_text();
        assert!(text.contains("<proposed_plan"), "a real partial plan must be kept as the plan: {text}");
    }

    #[tokio::test]
    async fn plan_mode_recovery_persists_salvaged_proposed_plan_to_session_file() {
        // Regression: when the tool-free recovery pass finalizes the plan from
        // an inline `<proposed_plan>` (tools were disabled, so the model could
        // not write the file itself), the plan must be persisted to the
        // session plan file so the "preserved in the session plan file"
        // notice is truthful. Previously the plan lived only in chat history
        // and `.vtcode/plans/` stayed empty/template-only.
        use tempfile::TempDir;
        use vtcode_core::tools::handlers::planning_workflow::PlanningWorkflowState;

        let temp_dir = TempDir::new().unwrap();
        let state = PlanningWorkflowState::new(temp_dir.path().to_path_buf());
        let plan_file = state.plans_dir().join("recovered-plan.md");
        state.set_plan_file(Some(plan_file.clone())).await;

        let mut working_history: Vec<uni::Message> = Vec::new();
        let mut plan_session = PlanningWorkflowSessionState::default();
        plan_session.mark_budget_exhausted();
        let salvaged = "<proposed_plan>\n- Action: add caching -> src/cache.rs\n  verify: cargo test\n</proposed_plan>";

        let result = complete_turn_after_failed_tool_free_recovery(
            &mut working_history,
            "stage",
            Some(&transient_err()),
            Some(salvaged.to_string()),
            Some(&mut plan_session),
            Some(&state),
        )
        .await;

        assert!(matches!(result, TurnLoopResult::Completed));
        let content =
            std::fs::read_to_string(&plan_file).expect("salvaged plan must be persisted to the session plan file");
        assert!(
            content.contains("add caching"),
            "salvaged plan must be written to the session plan file, got: {content}"
        );
    }
}