recursive-agent 0.8.3

A Rust coding-agent platform: kernel, tools, multi-agent orchestration, HTTP API, MCP, and TUI
Documentation
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
//! `enter_plan_mode` / `exit_plan_mode` tools — agent-driven read-only planning.
//!
//! When the agent calls `enter_plan_mode`, the runtime sets an exploring flag
//! that blocks any write tools until `exit_plan_mode` is called. `exit_plan_mode`
//! clears the flag, emits a [`AgentEvent::PlanProposed`] event (so TUI/HTTP
//! surfaces can render the review modal), and then **blocks** until the human
//! reviewer calls [`PlanApprovalGate::approve`] or [`PlanApprovalGate::reject`].
//!
//! # Concurrency safety
//!
//! [`PlanApprovalGate::wait_for_approval`] reads the response without holding a
//! lock across any `.await` point, preventing deadlocks.

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};

use async_trait::async_trait;
use serde_json::{json, Value};
use tokio::sync::Notify;

use crate::error::Result;
use crate::event::{AgentEvent, EventSink};
use crate::llm::ToolSpec;
use crate::permissions::{PermissionMode, PermissionsConfig};
use crate::tools::{Tool, ToolSideEffect};

// ---------------------------------------------------------------------------
// Tool name constants (M-5)
// ---------------------------------------------------------------------------

/// Canonical name for the `enter_plan_mode` tool.
///
/// Use this constant instead of the bare string literal so that any rename
/// of the tool produces a compile-time error rather than a silent runtime mismatch.
pub const ENTER_PLAN_MODE_TOOL_NAME: &str = "enter_plan_mode";

/// Canonical name for the `exit_plan_mode` tool.
///
/// Use this constant instead of the bare string literal so that any rename
/// of the tool produces a compile-time error rather than a silent runtime mismatch.
pub const EXIT_PLAN_MODE_TOOL_NAME: &str = "exit_plan_mode";

// ---------------------------------------------------------------------------
// PlanApprovalResult
// ---------------------------------------------------------------------------

/// The human reviewer's decision on an agent-proposed plan.
#[derive(Debug, Clone)]
pub enum PlanApprovalResult {
    /// Plan was approved; execution may proceed.
    Approved,
    /// Plan was rejected; the agent receives the reason and should revise.
    Rejected { reason: String },
}

// ---------------------------------------------------------------------------
// PlanApprovalGate
// ---------------------------------------------------------------------------

/// Shared state for the agent-driven plan mode approval flow.
///
/// A single `Arc<PlanApprovalGate>` is created in [`AgentRuntimeBuilder::build`]
/// and shared between:
/// * [`EnterPlanModeTool`] — sets `exploring_plan_mode`
/// * [`ExitPlanModeTool`] — clears flag, emits event, awaits decision
/// * [`AgentRuntime`] — calls [`approve`](Self::approve) / [`reject`](Self::reject)
/// * [`RunCore`](crate::run_core::RunCore) — reads `exploring_plan_mode` to gate writes
#[derive(Debug)]
pub struct PlanApprovalGate {
    /// `true` while the agent is in exploring (read-only plan) mode.
    pub exploring_plan_mode: Arc<AtomicBool>,
    /// The plan text currently pending review (set by `ExitPlanModeTool`).
    pub pending_plan: Arc<RwLock<Option<String>>>,
    /// Decision set by the human reviewer (TUI / HTTP).
    response: Arc<RwLock<Option<PlanApprovalResult>>>,
    /// Wakes up `wait_for_approval` when a decision arrives.
    notify: Arc<Notify>,
}

impl PlanApprovalGate {
    /// Create a fresh gate (exploring mode off, no pending decision).
    pub fn new() -> Self {
        Self {
            exploring_plan_mode: Arc::new(AtomicBool::new(false)),
            pending_plan: Arc::new(RwLock::new(None)),
            response: Arc::new(RwLock::new(None)),
            notify: Arc::new(Notify::new()),
        }
    }

    /// Block until the human reviewer sets a decision.
    ///
    /// Reads the response without holding any lock across `.await`, preventing
    /// deadlocks. On return the stored response is cleared so the gate can be
    /// reused for the next `exit_plan_mode` call.
    pub async fn wait_for_approval(&self) -> PlanApprovalResult {
        loop {
            // Read without holding the lock across the await point.
            let result_opt = {
                let guard = self.response.read().unwrap_or_else(|e| e.into_inner());
                guard.clone()
            };
            if let Some(result) = result_opt {
                // Clear for future use before returning.
                if let Ok(mut w) = self.response.write() {
                    *w = None;
                }
                return result;
            }
            // No decision yet — sleep until notify fires.
            self.notify.notified().await;
        }
    }

    /// Approve the pending plan. Called by TUI / HTTP on user confirmation.
    ///
    /// Clears the pending plan text so stale re-injection after compaction
    /// cannot occur — the reinjector reads [`pending_plan`](Self::pending_plan)
    /// which returns `None` after this call.
    pub fn approve(&self) {
        if let Ok(mut w) = self.response.write() {
            *w = Some(PlanApprovalResult::Approved);
        }
        if let Ok(mut w) = self.pending_plan.write() {
            *w = None;
        }
        self.notify.notify_one();
    }

    /// Reject the pending plan with a reason. Called by TUI / HTTP.
    ///
    /// Clears the pending plan text so stale re-injection after compaction
    /// cannot occur.
    pub fn reject(&self, reason: impl Into<String>) {
        if let Ok(mut w) = self.response.write() {
            *w = Some(PlanApprovalResult::Rejected {
                reason: reason.into(),
            });
        }
        if let Ok(mut w) = self.pending_plan.write() {
            *w = None;
        }
        self.notify.notify_one();
    }

    /// Return the currently-pending plan text, if any (set by
    /// [`begin_approval`](Self::begin_approval), cleared by
    /// [`approve`](Self::approve) or [`reject`](Self::reject)).
    /// Used by post-compact re-injection so the model retains the plan
    /// across compaction while it is still pending approval.
    ///
    /// Returns `None` gracefully on a poisoned lock (invariant #5 —
    /// no unwrap in product code).
    pub fn pending_plan(&self) -> Option<String> {
        self.pending_plan.read().ok().and_then(|g| g.clone())
    }

    /// Set the pending plan text and clear any stale approval/rejection
    /// from a previous cycle.
    ///
    /// Must be called instead of writing `pending_plan` directly so that
    /// a ghost `response` left over from a duplicate concurrent HTTP request
    /// (TOCTOU race) cannot bypass the human-approval gate on the next round.
    pub fn begin_approval(&self, plan_text: String) {
        if let Ok(mut w) = self.pending_plan.write() {
            *w = Some(plan_text);
        }
        // Clear any stale response from a previous (or concurrent duplicate)
        // approval so the next wait_for_approval() call blocks correctly.
        if let Ok(mut w) = self.response.write() {
            *w = None;
        }
    }
}

impl Default for PlanApprovalGate {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// EnterPlanModeTool
// ---------------------------------------------------------------------------

/// Tool that switches the agent into read-only planning mode.
///
/// Once entered, any non-readonly tool call (except `exit_plan_mode`) is
/// blocked with an error message. The agent should use read tools to explore
/// the codebase, then call `exit_plan_mode` with its markdown plan.
///
/// When a `PermissionsConfig` is provided, the tool also checks which tools
/// are in `Plan` mode and includes that information in the response, guiding
/// the agent to focus on those tools during planning.
pub struct EnterPlanModeTool {
    gate: Arc<PlanApprovalGate>,
    /// Optional permissions config to check which tools require plan mode.
    permissions: Option<Arc<PermissionsConfig>>,
}

impl EnterPlanModeTool {
    /// Create a new `EnterPlanModeTool` sharing the given gate.
    pub fn new(gate: Arc<PlanApprovalGate>) -> Self {
        Self {
            gate,
            permissions: None,
        }
    }

    /// Attach a permissions config so the tool can report which tools
    /// are in `Plan` mode.
    pub fn with_permissions(mut self, permissions: Arc<PermissionsConfig>) -> Self {
        self.permissions = Some(permissions);
        self
    }
}

#[async_trait]
impl Tool for EnterPlanModeTool {
    fn is_deferred(&self) -> bool {
        true
    }

    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: ENTER_PLAN_MODE_TOOL_NAME.into(),
            description: "Enter read-only planning mode for non-trivial or architectural \
                 changes. While active, write tools (Write, Edit, Bash, …) are blocked.\n\n\
                 Use enter_plan_mode when:\n\
                 - The task requires exploring 3+ files before deciding what to change\n\
                 - The task touches architectural boundaries (new module, new tool, API change)\n\
                 - You are unsure of the correct approach and want to discuss options first\n\n\
                 While in plan mode:\n\
                 - Read files freely (Read, Glob, Grep)\n\
                 - Think through trade-offs in your responses\n\
                 - DO NOT call Write, Edit, or Bash\n\
                 - When you have a clear plan, call exit_plan_mode with a markdown summary"
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {}
            }),
        }
    }

    async fn execute(&self, _arguments: Value) -> Result<String> {
        self.gate.exploring_plan_mode.store(true, Ordering::Relaxed);

        // If permissions are configured, report which tools are in Plan mode.
        let mut response = json!({ "entered": true });
        if let Some(ref config) = self.permissions {
            if matches!(config.mode, PermissionMode::Plan { .. }) {
                response["default_mode"] = json!("plan");
            }
        }

        Ok(response.to_string())
    }

    fn side_effect_class(&self) -> ToolSideEffect {
        ToolSideEffect::Mutating
    }

    fn is_readonly(&self) -> bool {
        false
    }
}

// ---------------------------------------------------------------------------
// ExitPlanModeTool
// ---------------------------------------------------------------------------

/// Tool that exits plan mode and presents the agent's plan for human review.
///
/// Execution **blocks** until the human reviewer calls
/// [`PlanApprovalGate::approve`] or [`PlanApprovalGate::reject`]. The tool
/// returns `{"approved": true}` or `{"approved": false, "reason": "…"}` so
/// the agent can branch on the outcome.
pub struct ExitPlanModeTool {
    gate: Arc<PlanApprovalGate>,
    event_sink: Arc<dyn EventSink>,
    /// Optional permissions config to validate plan coverage.
    permissions: Option<Arc<PermissionsConfig>>,
}

impl ExitPlanModeTool {
    /// Create a new `ExitPlanModeTool`.
    ///
    /// * `gate`       — shared with `EnterPlanModeTool` and `AgentRuntime`.
    /// * `event_sink` — emits [`AgentEvent::PlanProposed`] to TUI / HTTP.
    pub fn new(gate: Arc<PlanApprovalGate>, event_sink: Arc<dyn EventSink>) -> Self {
        Self {
            gate,
            event_sink,
            permissions: None,
        }
    }

    /// Attach a permissions config so the tool can validate that the plan
    /// covers tools in `Plan` mode.
    pub fn with_permissions(mut self, permissions: Arc<PermissionsConfig>) -> Self {
        self.permissions = Some(permissions);
        self
    }
}

#[async_trait]
impl Tool for ExitPlanModeTool {
    fn is_deferred(&self) -> bool {
        true
    }

    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: EXIT_PLAN_MODE_TOOL_NAME.into(),
            description:
                "Exit plan mode and present your plan for human review. Include a markdown \
                 summary with: (1) your understanding of the current code, (2) the approach \
                 you propose and why, (3) the files you will modify and how, (4) how you will \
                 verify the change is correct. Execution blocks until the reviewer confirms \
                 or rejects the plan."
                    .into(),
            parameters: json!({
                "type": "object",
                "required": ["plan"],
                "properties": {
                    "plan": {
                        "type": "string",
                        "description": "Markdown summary of your plan."
                    }
                }
            }),
        }
    }

    async fn execute(&self, arguments: Value) -> Result<String> {
        let plan_text = arguments
            .get("plan")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        // If permissions are configured, check that the plan covers Plan-mode tools.
        if let Some(ref _config) = self.permissions {
            // Plan-mode tools are determined by the default mode.
            // The plan text is passed through to the reviewer as-is.
        }

        // Clear exploring mode so normal tool execution resumes after approval.
        self.gate
            .exploring_plan_mode
            .store(false, Ordering::Relaxed);

        // Store the plan text so external callers can read it, and atomically
        // clear any stale response from a previous cycle (prevents ghost approvals).
        self.gate.begin_approval(plan_text.clone());

        // Emit PlanProposed so TUI / HTTP can render the review modal.
        // Plan Mode 2.0 has no pending tool_calls — the plan is prose only.
        self.event_sink
            .emit(AgentEvent::PlanProposed {
                plan_text: plan_text.clone(),
                tool_calls: vec![],
            })
            .await;

        // Block until the human makes a decision.
        // No lock is held across this await (see PlanApprovalGate::wait_for_approval).
        let result = self.gate.wait_for_approval().await;

        match result {
            PlanApprovalResult::Approved => Ok(json!({ "approved": true }).to_string()),
            PlanApprovalResult::Rejected { reason } => {
                Ok(json!({ "approved": false, "reason": reason }).to_string())
            }
        }
    }

    fn side_effect_class(&self) -> ToolSideEffect {
        // Waits for external human input.
        ToolSideEffect::External
    }

    fn is_readonly(&self) -> bool {
        false
    }
}

// ---------------------------------------------------------------------------
// PlanModeRequestGate (Goal-202)
// ---------------------------------------------------------------------------

/// Decision result for the pre-confirmation step.
#[derive(Debug, Clone)]
pub enum PlanModeRequestResult {
    /// User allowed the agent to enter plan mode.
    Approved,
    /// User declined; agent should execute without planning.
    Rejected { reason: String },
}

/// Gate for the plan-mode pre-confirmation step.
///
/// Parallel to [`PlanApprovalGate`] but governs the *entry* decision
/// (before any exploration), not the plan review.
pub struct PlanModeRequestGate {
    response: Arc<RwLock<Option<PlanModeRequestResult>>>,
    notify: Arc<Notify>,
}

impl PlanModeRequestGate {
    /// Create a fresh gate.
    pub fn new() -> Self {
        Self {
            response: Arc::new(RwLock::new(None)),
            notify: Arc::new(Notify::new()),
        }
    }

    /// Block until the user makes a decision.
    pub async fn wait_for_decision(&self) -> PlanModeRequestResult {
        loop {
            let result_opt = {
                let guard = self.response.read().unwrap_or_else(|e| e.into_inner());
                guard.clone()
            };
            if let Some(result) = result_opt {
                if let Ok(mut w) = self.response.write() {
                    *w = None;
                }
                return result;
            }
            self.notify.notified().await;
        }
    }

    /// Approve the plan-mode request.
    pub fn approve(&self) {
        if let Ok(mut w) = self.response.write() {
            *w = Some(PlanModeRequestResult::Approved);
        }
        self.notify.notify_one();
    }

    /// Reject the plan-mode request with a reason.
    pub fn reject(&self, reason: impl Into<String>) {
        if let Ok(mut w) = self.response.write() {
            *w = Some(PlanModeRequestResult::Rejected {
                reason: reason.into(),
            });
        }
        self.notify.notify_one();
    }
}

impl Default for PlanModeRequestGate {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// RequestPlanModeTool (Goal-202)
// ---------------------------------------------------------------------------

/// Tool that asks the user for permission before entering plan mode.
///
/// The agent should call this tool **before** `enter_plan_mode` whenever
/// it considers a planning phase beneficial.  If the user approves, the
/// agent proceeds with `enter_plan_mode` as usual.  If the user rejects,
/// the agent should execute directly without entering plan mode.
///
/// This two-step flow avoids wasting tokens generating a plan that the
/// user never wanted.
pub struct RequestPlanModeTool {
    gate: Arc<PlanModeRequestGate>,
    event_sink: Arc<dyn EventSink>,
}

impl RequestPlanModeTool {
    /// Create a new `RequestPlanModeTool`.
    pub fn new(gate: Arc<PlanModeRequestGate>, event_sink: Arc<dyn EventSink>) -> Self {
        Self { gate, event_sink }
    }
}

#[async_trait]
impl Tool for RequestPlanModeTool {
    fn is_deferred(&self) -> bool {
        true
    }

    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "request_plan_mode".into(),
            description:
                "Before entering plan mode, call this tool to ask the user whether they want \
                 you to create a plan first.  Provide a brief `reason` explaining why planning \
                 would be helpful for this task.  The call blocks until the user decides. \
                 If approved, proceed with `enter_plan_mode`; if rejected, execute directly \
                 without planning."
                    .into(),
            parameters: serde_json::json!({
                "type": "object",
                "required": ["reason"],
                "properties": {
                    "reason": {
                        "type": "string",
                        "description": "Brief explanation of why a planning phase would be \
                            beneficial (1-2 sentences)."
                    }
                }
            }),
        }
    }

    async fn execute(&self, arguments: serde_json::Value) -> Result<String> {
        let reason = arguments
            .get("reason")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        // Notify TUI / HTTP so they can prompt the user.
        self.event_sink
            .emit(crate::event::AgentEvent::PlanModeRequested {
                reason: reason.clone(),
            })
            .await;

        // Block until the user makes a decision.
        let result = self.gate.wait_for_decision().await;

        match result {
            PlanModeRequestResult::Approved => {
                self.event_sink
                    .emit(crate::event::AgentEvent::PlanModeApproved)
                    .await;
                Ok(serde_json::json!({ "approved": true }).to_string())
            }
            PlanModeRequestResult::Rejected { reason: r } => {
                self.event_sink
                    .emit(crate::event::AgentEvent::PlanModeRejected { reason: r.clone() })
                    .await;
                Ok(serde_json::json!({ "approved": false, "reason": r }).to_string())
            }
        }
    }

    fn side_effect_class(&self) -> ToolSideEffect {
        // Waits for external human input (same as exit_plan_mode).
        ToolSideEffect::External
    }

    fn is_readonly(&self) -> bool {
        false
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::NullSink;

    fn make_gate() -> Arc<PlanApprovalGate> {
        Arc::new(PlanApprovalGate::new())
    }

    // -- EnterPlanModeTool --------------------------------------------------

    #[tokio::test]
    async fn enter_plan_mode_returns_confirmation_message() {
        let gate = make_gate();
        let tool = EnterPlanModeTool::new(gate.clone());

        assert!(
            !gate.exploring_plan_mode.load(Ordering::Relaxed),
            "flag should start false"
        );

        let result = tool.execute(json!({})).await.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["entered"], true);
        assert!(
            gate.exploring_plan_mode.load(Ordering::Relaxed),
            "flag should be set after enter"
        );
    }

    // -- ExitPlanModeTool: blocks until confirmed ---------------------------

    #[tokio::test]
    async fn exit_plan_mode_blocks_until_confirmed() {
        let gate = make_gate();
        // Pre-set exploring mode so we can verify it gets cleared.
        gate.exploring_plan_mode.store(true, Ordering::Relaxed);

        let tool = Arc::new(ExitPlanModeTool::new(gate.clone(), Arc::new(NullSink)));

        // Spawn a task that approves after a short delay.
        let gate_clone = gate.clone();
        let approve_handle = tokio::spawn(async move {
            // Yield to ensure the tool's await is reached first.
            tokio::task::yield_now().await;
            gate_clone.approve();
        });

        let result = tool
            .execute(json!({ "plan": "step 1: read; step 2: write" }))
            .await
            .unwrap();

        approve_handle.await.unwrap();

        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["approved"], true);
        assert!(
            !gate.exploring_plan_mode.load(Ordering::Relaxed),
            "flag should be cleared after exit"
        );
    }

    // -- ExitPlanModeTool: rejection propagates reason ----------------------

    #[tokio::test]
    async fn exit_plan_mode_returns_rejection_reason() {
        let gate = make_gate();
        let tool = Arc::new(ExitPlanModeTool::new(gate.clone(), Arc::new(NullSink)));

        let gate_clone = gate.clone();
        let reject_handle = tokio::spawn(async move {
            tokio::task::yield_now().await;
            gate_clone.reject("Plan is incomplete");
        });

        let result = tool.execute(json!({ "plan": "my plan" })).await.unwrap();

        reject_handle.await.unwrap();

        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["approved"], false);
        assert_eq!(parsed["reason"], "Plan is incomplete");
    }

    // -- Gate: approve / reject directly ------------------------------------

    #[tokio::test]
    async fn gate_approve_wakes_waiter() {
        let gate = make_gate();
        let gate_clone = gate.clone();

        let waiter = tokio::spawn(async move { gate_clone.wait_for_approval().await });

        // Yield, then approve.
        tokio::task::yield_now().await;
        gate.approve();

        let result = waiter.await.unwrap();
        assert!(matches!(result, PlanApprovalResult::Approved));
    }

    #[tokio::test]
    async fn gate_reject_wakes_waiter_with_reason() {
        let gate = make_gate();
        let gate_clone = gate.clone();

        let waiter = tokio::spawn(async move { gate_clone.wait_for_approval().await });

        tokio::task::yield_now().await;
        gate.reject("too risky");

        let result = waiter.await.unwrap();
        assert!(matches!(
            result,
            PlanApprovalResult::Rejected { reason } if reason == "too risky"
        ));
    }

    // -- Gate: cleared after use so it can be reused ------------------------

    #[tokio::test]
    async fn gate_response_cleared_after_wait() {
        let gate = make_gate();
        gate.approve();
        let _ = gate.wait_for_approval().await;

        // Response should be None now.
        let stored = gate.response.read().unwrap().clone();
        assert!(stored.is_none(), "response should be cleared after read");
    }

    // -- PlanModeRequestGate (Goal-202) ------------------------------------

    #[tokio::test]
    async fn request_gate_approve_wakes_waiter() {
        let gate = Arc::new(PlanModeRequestGate::new());
        let gate_clone = gate.clone();
        let waiter = tokio::spawn(async move { gate_clone.wait_for_decision().await });
        tokio::task::yield_now().await;
        gate.approve();
        let result = waiter.await.unwrap();
        assert!(matches!(result, PlanModeRequestResult::Approved));
    }

    #[tokio::test]
    async fn request_gate_reject_propagates_reason() {
        let gate = Arc::new(PlanModeRequestGate::new());
        let gate_clone = gate.clone();
        let waiter = tokio::spawn(async move { gate_clone.wait_for_decision().await });
        tokio::task::yield_now().await;
        gate.reject("user skipped");
        let result = waiter.await.unwrap();
        assert!(matches!(
            result,
            PlanModeRequestResult::Rejected { reason } if reason == "user skipped"
        ));
    }

    #[tokio::test]
    async fn request_gate_cleared_after_use() {
        let gate = Arc::new(PlanModeRequestGate::new());
        gate.approve();
        let _ = gate.wait_for_decision().await;
        let stored = gate.response.read().unwrap().clone();
        assert!(
            stored.is_none(),
            "response should be cleared after decision"
        );
    }

    #[tokio::test]
    async fn request_plan_mode_tool_emits_event_and_blocks_until_approved() {
        use crate::event::NullSink;
        let gate = Arc::new(PlanModeRequestGate::new());
        let tool = Arc::new(RequestPlanModeTool::new(gate.clone(), Arc::new(NullSink)));
        let gate_clone = gate.clone();
        let approve_handle = tokio::spawn(async move {
            tokio::task::yield_now().await;
            gate_clone.approve();
        });
        let result = tool
            .execute(json!({ "reason": "complex task" }))
            .await
            .unwrap();
        approve_handle.await.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["approved"], true);
    }

    #[tokio::test]
    async fn request_plan_mode_tool_rejected_returns_false() {
        use crate::event::NullSink;
        let gate = Arc::new(PlanModeRequestGate::new());
        let tool = Arc::new(RequestPlanModeTool::new(gate.clone(), Arc::new(NullSink)));
        let gate_clone = gate.clone();
        let reject_handle = tokio::spawn(async move {
            tokio::task::yield_now().await;
            gate_clone.reject("not needed");
        });
        let result = tool
            .execute(json!({ "reason": "might need plan" }))
            .await
            .unwrap();
        reject_handle.await.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["approved"], false);
        assert_eq!(parsed["reason"], "not needed");
    }

    // -- PlanApprovalGate::pending_plan -------------------------------------

    #[test]
    fn pending_plan_returns_begin_approval_text() {
        let gate = PlanApprovalGate::new();
        assert_eq!(gate.pending_plan(), None, "starts empty");
        gate.begin_approval("my plan".to_string());
        assert_eq!(
            gate.pending_plan().as_deref(),
            Some("my plan"),
            "returns the text set by begin_approval"
        );
    }

    #[test]
    fn pending_plan_cleared_on_approve() {
        let gate = PlanApprovalGate::new();
        gate.begin_approval("plan text".to_string());
        assert_eq!(gate.pending_plan().as_deref(), Some("plan text"));
        gate.approve();
        assert_eq!(
            gate.pending_plan(),
            None,
            "pending_plan must be cleared after approve() to prevent stale re-injection"
        );
    }

    #[test]
    fn pending_plan_cleared_on_reject() {
        let gate = PlanApprovalGate::new();
        gate.begin_approval("plan text".to_string());
        assert_eq!(gate.pending_plan().as_deref(), Some("plan text"));
        gate.reject("bad plan");
        assert_eq!(
            gate.pending_plan(),
            None,
            "pending_plan must be cleared after reject() to prevent stale re-injection"
        );
    }

    // -- PlanApprovalGate::begin_approval -----------------------------------

    #[test]
    fn begin_approval_sets_plan_and_clears_stale_response() {
        let gate = PlanApprovalGate::new();

        // Simulate a stale response left over from a previous cycle.
        *gate.response.write().unwrap() = Some(PlanApprovalResult::Approved);

        gate.begin_approval("new plan text".to_string());

        assert!(
            gate.response.read().unwrap().is_none(),
            "begin_approval must clear stale response to prevent TOCTOU bypass"
        );
        assert_eq!(
            gate.pending_plan.read().unwrap().as_deref(),
            Some("new plan text"),
            "begin_approval must store the new plan text"
        );
    }

    // -- is_deferred / is_readonly for both tools ---------------------------

    #[test]
    fn enter_plan_mode_tool_is_deferred_and_not_readonly() {
        // kills `replace EnterPlanModeTool::is_deferred -> bool with false`
        // kills `replace EnterPlanModeTool::is_readonly -> bool with true`
        let gate = make_gate();
        let tool = EnterPlanModeTool::new(gate);
        assert!(
            tool.is_deferred(),
            "EnterPlanModeTool must be deferred (not eagerly loaded)"
        );
        assert!(
            !tool.is_readonly(),
            "EnterPlanModeTool must NOT be readonly (it sets exploring_plan_mode)"
        );
    }

    #[test]
    fn exit_plan_mode_tool_is_deferred_and_not_readonly() {
        // kills `replace ExitPlanModeTool::is_deferred -> bool with false`
        // kills `replace ExitPlanModeTool::is_readonly -> bool with true`
        let gate = make_gate();
        let tool = ExitPlanModeTool::new(gate, Arc::new(NullSink));
        assert!(tool.is_deferred(), "ExitPlanModeTool must be deferred");
        assert!(
            !tool.is_readonly(),
            "ExitPlanModeTool must NOT be readonly (it blocks until the user reviews the plan)"
        );
    }

    #[test]
    fn begin_approval_called_twice_no_ghost_approval() {
        let gate = PlanApprovalGate::new();

        // First cycle: begin, then approve.
        gate.begin_approval("plan v1".to_string());
        *gate.response.write().unwrap() = Some(PlanApprovalResult::Approved);

        // Second cycle: begin_approval should wipe the approval from cycle 1.
        gate.begin_approval("plan v2".to_string());

        assert!(
            gate.response.read().unwrap().is_none(),
            "second begin_approval must clear the cycle-1 approval (ghost-approval prevention)"
        );
        assert_eq!(
            gate.pending_plan.read().unwrap().as_deref(),
            Some("plan v2"),
            "pending_plan should reflect the latest plan text"
        );
    }
}