collet 0.1.0

Relentless agentic coding orchestrator with zero-drop agent loops
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
//! Tool approval gate — controls whether tools require user approval before execution.
//!
//! Three modes:
//! - **Yolo**: all tools auto-approved.
//! - **Auto**: safe (read-only) tools auto-approved, write tools require approval.
//! - **Manual**: all tools require approval.
//!
//! The gate uses atomic mode storage so frontends can switch modes at runtime
//! (e.g. TUI Shift+Tab cycles Manual → Auto → Yolo).
//!
//! # Session-level approval cache
//!
//! `SessionApprovals` tracks which unsafe tools the user has approved or denied
//! during the current session.  Once a tool is approved it is auto-passed for
//! the rest of the session; once denied it is auto-skipped.  The cache is held
//! in memory only and resets when the process exits.
//!
//! Parallel (swarm) agents share the same `SessionApprovals` instance via `Arc`.
//! The first agent to encounter an unknown tool sends the approval request; all
//! others wait on a `watch` channel and receive the same decision.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicU8, Ordering};
use tokio::sync::{Mutex, mpsc, oneshot, watch};

// ── Approval mode ────────────────────────────────────────────────────────────

/// Approval mode for tool execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum ApproveMode {
    /// All tools execute without asking.
    Yolo = 0,
    /// Read-only tools auto-approved; write tools need approval.
    #[default]
    Auto = 1,
    /// Every tool needs explicit approval.
    Manual = 2,
}

impl ApproveMode {
    fn from_u8(v: u8) -> Self {
        match v {
            0 => Self::Yolo,
            2 => Self::Manual,
            _ => Self::Auto,
        }
    }

    /// Cycle to the next mode: Manual → Auto → Yolo → Manual.
    pub fn next(self) -> Self {
        match self {
            Self::Manual => Self::Auto,
            Self::Auto => Self::Yolo,
            Self::Yolo => Self::Manual,
        }
    }
}

impl std::fmt::Display for ApproveMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Yolo => write!(f, "yolo"),
            Self::Auto => write!(f, "auto"),
            Self::Manual => write!(f, "manual"),
        }
    }
}

impl std::str::FromStr for ApproveMode {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "yolo" => Ok(Self::Yolo),
            "auto" => Ok(Self::Auto),
            "manual" => Ok(Self::Manual),
            _ => Err(format!("unknown approve mode: {s}")),
        }
    }
}

// ── Safe-tool list ────────────────────────────────────────────────────────────

/// Tools that are considered safe (read-only) and auto-approved in Auto mode.
const SAFE_TOOLS: &[&str] = &[
    "file_read",
    "search",
    "search_symbol",
    "list_dir",
    "git_diff",
    "git_log",
    "git_status",
    "codebase_summary",
];

/// Lazily-initialized HashSet for O(1) safe-tool lookups on the hot path.
static SAFE_TOOLS_SET: std::sync::LazyLock<HashSet<&'static str>> =
    std::sync::LazyLock::new(|| SAFE_TOOLS.iter().copied().collect());

/// Returns true if a tool is considered safe (read-only).
pub fn is_safe_tool(name: &str) -> bool {
    if SAFE_TOOLS_SET.contains(name) {
        return true;
    }
    // MCP tools: auto-approve read-like operations
    if name.starts_with("mcp__") {
        let parts: Vec<&str> = name.split("__").collect();
        if parts.len() >= 3 {
            let op = parts.last().unwrap_or(&"");
            return matches!(
                *op,
                "search" | "read" | "get" | "list" | "query" | "find" | "resolve"
            );
        }
    }
    false
}

/// Whether a tool needs approval given the current mode.
pub fn needs_approval(mode: ApproveMode, tool_name: &str) -> bool {
    match mode {
        ApproveMode::Yolo => false,
        ApproveMode::Auto => !is_safe_tool(tool_name),
        ApproveMode::Manual => true,
    }
}

// ── Destructive command detection ─────────────────────────────────────────────

/// Bash command substrings that indicate irreversible/destructive operations.
/// These require approval regardless of the current approval mode (even Yolo).
const DESTRUCTIVE_PATTERNS: &[&str] = &[
    // Git force operations
    "git push --force",
    "git push -f ",
    "git push -f\n",
    "git push -f\"",
    "git push origin +", // force-push via refspec prefix
    "git reset --hard",
    "git branch -D ",
    "git branch -d ",
    // SQL DDL destructive statements
    "drop table",
    "drop database",
    "drop schema",
    // Disk/filesystem destruction
    "dd if=", // disk overwrite (e.g. dd if=/dev/zero of=/dev/sda)
    "mkfs.",  // filesystem format (mkfs.ext4, mkfs.vfat, …)
    "mkfs ",
    // System control (match as commands, not substrings in strings)
    "shutdown -", // shutdown -h now / shutdown -r
    "reboot\n",
    "reboot ",
    "reboot\"",
    " halt\n",
    " halt ",
    "poweroff\n",
    "poweroff ",
    // Fork bomb
    ":(){ :|:",
    // Broad recursive permission/ownership wipe on root
    "chmod -r 777 /",
    "chmod -r 000 /",
    "chown -r nobody /",
    "chown -r root /",
    // Remote code execution via pipe-to-shell
    "| bash",
    "| sh\n",
    "| sh ",
    "| sh\"",
    "|bash",
    "|sh",
    // Dangerous process/service management
    "kill -9 -1",  // kill all user processes
    "kill -9 1",   // kill init (PID 1)
    "pkill -9 ",   // mass process kill
    "killall -9 ", // mass process kill
    "crontab -r",  // wipe all cron jobs
    // Firewall / network
    "iptables -f", // flush firewall rules (lowered by to_lowercase)
    "iptables --flush",
    // Service management (system-level)
    "systemctl mask ",
    "systemctl disable ",
    // History / log wipe
    "history -c", // clear shell history
    "shred ",     // secure erase (irreversible)
];

/// Returns true if the tool invocation is destructive/irreversible.
///
/// Destructive commands bypass even Yolo mode — the user must confirm them
/// explicitly. The check is intentionally conservative: only patterns with
/// high blast radius and low false-positive rate are included.
///
/// For rm -rf, only the most dangerous patterns (system-wide deletion) require approval:
/// - rm -rf / (entire filesystem)
/// - rm -rf ~/ (entire home directory)
pub fn is_destructive_command(tool_name: &str, tool_args: &str) -> bool {
    if tool_name != "bash" {
        return false;
    }
    let lower = tool_args.to_lowercase();

    // Check standard destructive patterns
    if DESTRUCTIVE_PATTERNS.iter().any(|p| lower.contains(p)) {
        return true;
    }

    // Only flag rm -rf if targeting system root (/) or home (~/) directory.
    // Be careful to match only "rm -rf /" not "rm -rf /tmp" or similar subdirectories.
    if lower.contains("rm -rf /") || lower.contains("rm -fr /") {
        // Check if it's actually "rm -rf /" (just root) not "rm -rf /something"
        // Look for the pattern: "rm -rf /" potentially followed by quotes, newlines, etc.
        if lower.contains("rm -rf / ")
            || lower.contains("rm -rf /\"")
            || lower.contains("rm -rf /\n")
            || lower.ends_with("rm -rf /")
            || lower.contains("rm -fr / ")
            || lower.contains("rm -fr /\"")
            || lower.contains("rm -fr /\n")
            || lower.ends_with("rm -fr /")
        {
            return true;
        }
    }

    // Check for rm -rf ~/ (home directory)
    if lower.contains("rm -rf ~/") || lower.contains("rm -fr ~/") {
        return true;
    }

    false
}

// ── Path traversal detection ─────────────────────────────────────────────────

/// Normalize a path lexically (no I/O) by resolving `..` and `.` components.
/// Used to detect working-directory escapes without requiring files to exist.
pub(crate) fn normalize_path_lexical(path: &std::path::Path) -> std::path::PathBuf {
    use std::path::Component;
    let mut out = std::path::PathBuf::new();
    for component in path.components() {
        match component {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => {}
            c => out.push(c),
        }
    }
    out
}

/// Returns true if `resolved_path` matches any entry in `deny_patterns`.
///
/// Matching rules:
/// - `~/<rest>` expands to `$HOME/<rest>` and is checked as a path prefix.
/// - `**/<name>` matches any path whose final component (or any trailing
///   segment) equals `<name>` — e.g. `**/.env` blocks `/any/dir/.env`.
/// - Any other pattern is treated as a path prefix: `deny_paths = ["/etc"]`
///   blocks `/etc/passwd`, `/etc/shadow`, etc.
///
/// `resolved_path` is expected to be an absolute, lexically-normalized path
/// (as produced by `normalize_path_lexical`).
pub fn is_path_denied(resolved_path: &str, deny_patterns: &[String]) -> bool {
    let home = dirs::home_dir().map(|h| h.to_string_lossy().to_string());
    for pattern in deny_patterns {
        let expanded: std::borrow::Cow<str> = if pattern.starts_with("~/") {
            // Skip ~/ patterns when home directory cannot be resolved (e.g. unusual
            // environments) to avoid matching against an empty path prefix.
            let Some(ref h) = home else { continue };
            format!("{}{}", h, &pattern[1..]).into()
        } else {
            pattern.as_str().into()
        };

        if let Some(glob_suffix) = expanded.strip_prefix("**/") {
            // `**/<suffix>` — match if the resolved path ends with `/<suffix>`
            // or equals the suffix exactly.
            let suffix = format!("/{glob_suffix}");
            if resolved_path.ends_with(suffix.as_str()) || resolved_path == glob_suffix {
                return true;
            }
        } else {
            // Prefix match: pattern "/a/b" blocks "/a/b", "/a/b/c", etc.
            let prefix_slash = format!("{}/", expanded);
            if resolved_path == expanded.as_ref()
                || resolved_path.starts_with(prefix_slash.as_str())
            {
                return true;
            }
        }
    }
    false
}

/// Returns true if the file tool's path argument escapes the working directory.
///
/// Applies to `file_read`, `file_write`, `file_edit`, and `git_patch`.
/// Used in Auto mode to force approval for out-of-workdir access that would
/// otherwise be silently permitted (e.g. `file_read` is a safe/auto-approved tool).
/// Does **not** bypass Yolo — callers must skip this check in Yolo mode.
pub fn is_path_outside_workdir(tool_name: &str, tool_args: &str, working_dir: &str) -> bool {
    if !matches!(
        tool_name,
        "file_read" | "file_write" | "file_edit" | "git_patch"
    ) {
        return false;
    }
    let Ok(val) = serde_json::from_str::<serde_json::Value>(tool_args) else {
        return false;
    };
    let Some(path) = val.get("path").and_then(|p| p.as_str()) else {
        return false;
    };
    let candidate = if std::path::Path::new(path).is_absolute() {
        std::path::PathBuf::from(path)
    } else {
        std::path::Path::new(working_dir).join(path)
    };
    let normalized = normalize_path_lexical(&candidate);
    let workdir_norm = normalize_path_lexical(std::path::Path::new(working_dir));
    !normalized.starts_with(&workdir_norm)
}

// ── Session-level approval cache ─────────────────────────────────────────────

/// Internal state of the session approval cache.
#[derive(Default)]
struct SessionApprovalsInner {
    /// Tools approved for the rest of this session.
    allowed: HashSet<String>,
    /// Tools denied for the rest of this session.
    denied: HashSet<String>,
    /// Tools currently waiting for a frontend decision.
    ///
    /// The first agent to request approval for a tool inserts a watch sender
    /// here.  Subsequent agents subscribe to it and wait for the result.
    pending: HashMap<String, watch::Sender<Option<bool>>>,
}

/// What `SessionApprovals::pre_check` returns for a given tool name.
pub enum SessionCheckResult {
    /// Already approved this session — proceed without asking.
    Allowed,
    /// Already denied this session — skip without asking.
    Denied,
    /// This agent is the first to ask — it should send an `ApprovalRequest`.
    NeedsApproval,
    /// Another agent is already asking — wait on this receiver for the result.
    WaitForResult(watch::Receiver<Option<bool>>),
}

/// Session-scoped, thread-safe approval cache shared across all agents.
///
/// Clone is cheap (Arc clone).  Pass one instance to every `ApprovalGate`
/// spawned during the same user session.
#[derive(Clone, Default)]
pub struct SessionApprovals(Arc<Mutex<SessionApprovalsInner>>);

impl SessionApprovals {
    pub fn new() -> Self {
        Self::default()
    }

    /// Check the current state for `tool_name` without blocking.
    ///
    /// * `Allowed`/`Denied` — already decided, no popup needed.
    /// * `NeedsApproval`    — caller should show popup then call `resolve()`.
    /// * `WaitForResult(rx)` — another agent is asking; await `rx` for result.
    pub async fn pre_check(&self, tool_name: &str) -> SessionCheckResult {
        let mut inner = self.0.lock().await;
        if inner.allowed.contains(tool_name) {
            return SessionCheckResult::Allowed;
        }
        if inner.denied.contains(tool_name) {
            return SessionCheckResult::Denied;
        }
        if let Some(tx) = inner.pending.get(tool_name) {
            return SessionCheckResult::WaitForResult(tx.subscribe());
        }
        // First requester — mark pending and let caller handle the popup.
        let (tx, _rx) = watch::channel(None::<bool>);
        inner.pending.insert(tool_name.to_string(), tx);
        SessionCheckResult::NeedsApproval
    }

    /// Record the frontend's decision and wake any waiting agents.
    pub async fn resolve(&self, tool_name: &str, approved: bool) {
        let mut inner = self.0.lock().await;
        if approved {
            inner.allowed.insert(tool_name.to_string());
        } else {
            inner.denied.insert(tool_name.to_string());
        }
        if let Some(tx) = inner.pending.remove(tool_name) {
            let _ = tx.send(Some(approved));
        }
    }

    /// Notify parallel waiters that this single invocation was approved, but
    /// do **not** add the tool to the session `allowed` set.
    ///
    /// Used for `bash` tool with `Approve` (once) so that every command goes
    /// through the full approval flow — prevents a single approval from
    /// silently granting all future bash commands (session cache escalation).
    pub async fn resolve_once(&self, tool_name: &str) {
        let mut inner = self.0.lock().await;
        if let Some(tx) = inner.pending.remove(tool_name) {
            let _ = tx.send(Some(true));
        }
        // Intentionally not adding to inner.allowed.
    }

    /// Clear the entire session cache (e.g. on logout / hard reset).
    pub async fn clear(&self) {
        let mut inner = self.0.lock().await;
        inner.allowed.clear();
        inner.denied.clear();
        // Notify any waiters that the tool was denied (safe default).
        for (_, tx) in inner.pending.drain() {
            let _ = tx.send(Some(false));
        }
    }
}

// ── Approval request / response types ────────────────────────────────────────

/// An approval request sent from the agent loop to the frontend.
#[derive(Debug)]
pub struct ApprovalRequest {
    pub tool_name: String,
    pub tool_args: String,
    pub response_tx: oneshot::Sender<ApprovalResponse>,
}

/// The frontend's response to an approval request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApprovalResponse {
    /// Tool execution approved (this call only).
    Approve,
    /// Tool execution denied — skip this tool.
    Deny,
    /// Approve this tool for the rest of the session.
    ApproveAll,
}

// ── SharedApproveMode ─────────────────────────────────────────────────────────

/// Shared atomic mode that can be changed at runtime from any thread.
#[derive(Clone)]
pub struct SharedApproveMode(Arc<AtomicU8>);

impl SharedApproveMode {
    pub fn new(mode: ApproveMode) -> Self {
        Self(Arc::new(AtomicU8::new(mode as u8)))
    }

    pub fn get(&self) -> ApproveMode {
        ApproveMode::from_u8(self.0.load(Ordering::Acquire))
    }

    pub fn set(&self, mode: ApproveMode) {
        self.0.store(mode as u8, Ordering::Release);
    }

    /// Cycle to next mode and return the new mode.
    pub fn cycle(&self) -> ApproveMode {
        let current = self.get();
        let next = current.next();
        self.set(next);
        next
    }
}

// ── ApprovalGate ─────────────────────────────────────────────────────────────

/// Async approval gate that the agent loop uses to request approval.
///
/// Frontends create an `ApprovalGate` and pass it into the agent loop.
/// The agent sends requests through the gate; the frontend receives them
/// on the other end and responds.
///
/// When a `SessionApprovals` cache is attached, tools approved/denied earlier
/// in the session are resolved immediately without a popup.  Parallel agents
/// share the same cache so the first to ask handles the popup; others wait.
#[derive(Clone)]
pub struct ApprovalGate {
    mode: SharedApproveMode,
    /// Channel to send approval requests to the frontend.
    request_tx: Option<Arc<mpsc::UnboundedSender<ApprovalRequest>>>,
    /// Session-scoped cache shared across all agents.
    session_approvals: Option<SessionApprovals>,
}

impl ApprovalGate {
    /// Create a yolo gate that auto-approves everything.
    pub fn yolo() -> Self {
        Self {
            mode: SharedApproveMode::new(ApproveMode::Yolo),
            request_tx: None,
            session_approvals: None,
        }
    }

    /// Create a headless gate with the given shared mode (no request channel — falls back to auto-approve).
    pub fn headless(mode: SharedApproveMode) -> Self {
        Self {
            mode,
            request_tx: None,
            session_approvals: None,
        }
    }

    /// Create a gate with the given mode and request channel.
    pub fn new(
        mode: SharedApproveMode,
        request_tx: mpsc::UnboundedSender<ApprovalRequest>,
    ) -> Self {
        Self {
            mode: mode.clone(),
            request_tx: Some(Arc::new(request_tx)),
            session_approvals: None,
        }
    }

    /// Create a gate with mode, request channel, and session approval cache.
    pub fn new_with_session(
        mode: SharedApproveMode,
        request_tx: mpsc::UnboundedSender<ApprovalRequest>,
        session_approvals: SessionApprovals,
    ) -> Self {
        Self {
            mode: mode.clone(),
            request_tx: Some(Arc::new(request_tx)),
            session_approvals: Some(session_approvals),
        }
    }

    /// Attach (or replace) the session approval cache after construction.
    pub fn with_session_approvals(mut self, sa: SessionApprovals) -> Self {
        self.session_approvals = Some(sa);
        self
    }

    pub fn mode(&self) -> ApproveMode {
        self.mode.get()
    }

    /// Get shared mode handle for runtime switching.
    pub fn shared_mode(&self) -> SharedApproveMode {
        self.mode.clone()
    }

    /// Check if a tool needs approval.
    ///
    /// Resolution order:
    /// 1. Mode is Yolo, or tool is safe in Auto → immediate Approve.
    /// 2. Session cache: already allowed → Approve, already denied → Deny.
    /// 3. Session cache: pending (another agent is asking) → wait for result.
    /// 4. Send `ApprovalRequest` to the frontend and await response.
    ///    On approval, record in session cache so future calls skip the popup.
    pub async fn check(
        &self,
        tool_name: &str,
        tool_args: &str,
        working_dir: &str,
    ) -> ApprovalResponse {
        let current_mode = self.mode.get();
        let destructive = is_destructive_command(tool_name, tool_args);

        // In Auto mode, file tools accessing paths outside the working directory
        // require approval even though they are otherwise safe/auto-approved.
        // Yolo mode skips this check entirely (user has opted out of all approvals).
        let outside_workdir = current_mode != ApproveMode::Yolo
            && is_path_outside_workdir(tool_name, tool_args, working_dir);

        // Destructive commands always require approval — bypass Yolo.
        // Non-destructive commands follow the normal mode check.
        if !destructive && !outside_workdir && !needs_approval(current_mode, tool_name) {
            return ApprovalResponse::Approve;
        }

        // ── Session cache ────────────────────────────────────────────────────
        // Destructive commands skip the session cache: each invocation must be
        // explicitly confirmed regardless of prior approvals in this session.
        if !destructive && let Some(ref sa) = self.session_approvals {
            match sa.pre_check(tool_name).await {
                SessionCheckResult::Allowed => return ApprovalResponse::Approve,
                SessionCheckResult::Denied => return ApprovalResponse::Deny,
                SessionCheckResult::WaitForResult(mut rx) => {
                    // Another agent is already asking — wait for their decision.
                    let _ = rx.wait_for(|v| v.is_some()).await;
                    return match *rx.borrow() {
                        Some(true) => ApprovalResponse::Approve,
                        _ => ApprovalResponse::Deny,
                    };
                }
                SessionCheckResult::NeedsApproval => {
                    // Fall through to send request to frontend.
                }
            }
        }

        // ── Send request to frontend ─────────────────────────────────────────
        let Some(tx) = &self.request_tx else {
            if destructive {
                // No frontend to confirm — deny destructive ops to prevent silent damage.
                tracing::warn!("No approval frontend, denying destructive command: {tool_name}");
                return ApprovalResponse::Deny;
            }
            // Without a frontend, only auto-approve known-safe (read-only) tools.
            // Write tools (bash, file_write, etc.) are denied to prevent silent damage.
            if !is_safe_tool(tool_name) {
                tracing::warn!(
                    "No approval frontend, denying non-safe tool in headless mode: {tool_name}"
                );
                return ApprovalResponse::Deny;
            }
            if let Some(ref sa) = self.session_approvals {
                sa.resolve(tool_name, true).await;
            }
            tracing::warn!("No approval frontend, auto-approving safe tool: {tool_name}");
            return ApprovalResponse::Approve;
        };

        let (response_tx, response_rx) = oneshot::channel();
        let request = ApprovalRequest {
            tool_name: tool_name.to_string(),
            tool_args: tool_args.to_string(),
            response_tx,
        };

        if tx.send(request).is_err() {
            tracing::warn!("Approval frontend disconnected, auto-approving {tool_name}");
            if let Some(ref sa) = self.session_approvals {
                sa.resolve(tool_name, true).await;
            }
            return ApprovalResponse::Approve;
        }

        let response = match response_rx.await {
            Ok(r) => r,
            Err(_) => {
                tracing::warn!("Approval response channel dropped for {tool_name}, auto-approving");
                ApprovalResponse::Approve
            }
        };

        // ── Update session cache ─────────────────────────────────────────────
        if let Some(ref sa) = self.session_approvals {
            match response {
                // bash: single Approve is ephemeral — notify parallel waiters
                // but do NOT add to the session allowed set.  This prevents
                // one approved command from silently auto-approving all future
                // bash invocations (session cache privilege escalation).
                ApprovalResponse::Approve if tool_name == "bash" => {
                    sa.resolve_once(tool_name).await;
                }
                _ => {
                    let approved = matches!(
                        response,
                        ApprovalResponse::Approve | ApprovalResponse::ApproveAll
                    );
                    sa.resolve(tool_name, approved).await;
                }
            }
        }

        response
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_safe_tools() {
        assert!(is_safe_tool("file_read"));
        assert!(is_safe_tool("search"));
        assert!(!is_safe_tool("file_write"));
        assert!(!is_safe_tool("bash"));
    }

    #[test]
    fn test_mcp_safe_tools() {
        assert!(is_safe_tool("mcp__serena__search"));
        assert!(is_safe_tool("mcp__context7__query"));
        assert!(!is_safe_tool("mcp__serena__edit"));
    }

    #[test]
    fn test_needs_approval() {
        assert!(!needs_approval(ApproveMode::Yolo, "bash"));
        assert!(!needs_approval(ApproveMode::Auto, "file_read"));
        assert!(needs_approval(ApproveMode::Auto, "file_write"));
        assert!(needs_approval(ApproveMode::Auto, "bash"));
        assert!(needs_approval(ApproveMode::Manual, "file_read"));
    }

    #[test]
    fn test_mode_cycle() {
        assert_eq!(ApproveMode::Manual.next(), ApproveMode::Auto);
        assert_eq!(ApproveMode::Auto.next(), ApproveMode::Yolo);
        assert_eq!(ApproveMode::Yolo.next(), ApproveMode::Manual);
    }

    #[test]
    fn test_shared_mode() {
        let shared = SharedApproveMode::new(ApproveMode::Manual);
        assert_eq!(shared.get(), ApproveMode::Manual);
        assert_eq!(shared.cycle(), ApproveMode::Auto);
        assert_eq!(shared.get(), ApproveMode::Auto);
    }

    #[test]
    fn test_is_destructive_command() {
        // Non-bash tools are never destructive
        assert!(!is_destructive_command("file_write", r#"{"path":"x"}"#));

        // Safe bash commands
        assert!(!is_destructive_command(
            "bash",
            r#"{"command":"git status"}"#
        ));
        assert!(!is_destructive_command(
            "bash",
            r#"{"command":"git push origin main"}"#
        ));
        assert!(!is_destructive_command(
            "bash",
            r#"{"command":"rm -r build/"}"#
        ));

        // rm -rf on project directories is safe (not destructive)
        assert!(!is_destructive_command(
            "bash",
            r#"{"command":"rm -rf /tmp/build"}"#
        ));
        assert!(!is_destructive_command(
            "bash",
            r#"{"command":"rm -rf ./dist"}"#
        ));
        assert!(!is_destructive_command(
            "bash",
            r#"{"command":"rm -rf node_modules"}"#
        ));

        // Only system-wide rm -rf is destructive
        assert!(is_destructive_command("bash", r#"{"command":"rm -rf /"}"#));
        assert!(is_destructive_command("bash", r#"{"command":"rm -fr /"}"#));
        assert!(is_destructive_command("bash", r#"{"command":"rm -rf ~/"}"#));
        assert!(is_destructive_command("bash", r#"{"command":"rm -fr ~/"}"#));

        // Standard destructive patterns still apply
        assert!(is_destructive_command(
            "bash",
            r#"{"command":"git push --force origin main"}"#
        ));
        assert!(is_destructive_command(
            "bash",
            r#"{"command":"git push -f origin main"}"#
        ));
        assert!(is_destructive_command(
            "bash",
            r#"{"command":"git reset --hard HEAD~1"}"#
        ));
        assert!(is_destructive_command(
            "bash",
            r#"{"command":"git branch -D feature/old"}"#
        ));
        assert!(is_destructive_command(
            "bash",
            r#"{"command":"DROP TABLE users;"}"#
        ));
    }

    #[test]
    fn test_is_path_outside_workdir() {
        let wd = "/home/user/project";

        // Inside working dir — relative
        assert!(!is_path_outside_workdir(
            "file_read",
            r#"{"path":"src/main.rs"}"#,
            wd
        ));
        // Inside working dir — absolute
        assert!(!is_path_outside_workdir(
            "file_read",
            r#"{"path":"/home/user/project/src/main.rs"}"#,
            wd
        ));
        // Outside via absolute path
        assert!(is_path_outside_workdir(
            "file_read",
            r#"{"path":"/etc/passwd"}"#,
            wd
        ));
        // Outside via path traversal
        assert!(is_path_outside_workdir(
            "file_write",
            r#"{"path":"../../etc/shadow"}"#,
            wd
        ));
        // Non-file tool — always false
        assert!(!is_path_outside_workdir(
            "bash",
            r#"{"command":"cat /etc/passwd"}"#,
            wd
        ));
        // No path field — always false
        assert!(!is_path_outside_workdir("file_read", r#"{}"#, wd));
    }

    #[tokio::test]
    async fn test_auto_gate_file_read_outside_workdir_requires_approval() {
        let shared = SharedApproveMode::new(ApproveMode::Auto);
        let (tx, mut rx) = mpsc::unbounded_channel::<ApprovalRequest>();
        let gate = ApprovalGate::new(shared, tx);

        tokio::spawn(async move {
            let req = rx.recv().await.unwrap();
            assert_eq!(req.tool_name, "file_read");
            req.response_tx.send(ApprovalResponse::Approve).unwrap();
        });

        // file_read is normally auto-approved, but /etc/passwd is outside workdir
        let result = gate
            .check(
                "file_read",
                r#"{"path":"/etc/passwd"}"#,
                "/home/user/project",
            )
            .await;
        assert_eq!(result, ApprovalResponse::Approve);
    }

    #[tokio::test]
    async fn test_yolo_gate_file_read_outside_workdir_auto_approved() {
        // Yolo bypasses all approval checks including outside-workdir
        let gate = ApprovalGate::yolo();
        let result = gate
            .check(
                "file_read",
                r#"{"path":"/etc/passwd"}"#,
                "/home/user/project",
            )
            .await;
        assert_eq!(result, ApprovalResponse::Approve);
    }

    #[tokio::test]
    async fn test_yolo_gate_safe() {
        let gate = ApprovalGate::yolo();
        assert_eq!(
            gate.check("bash", r#"{"command":"git status"}"#, "/tmp")
                .await,
            ApprovalResponse::Approve
        );
    }

    #[tokio::test]
    async fn test_yolo_gate_destructive_no_frontend() {
        // Yolo gate has no request_tx — destructive ops must be denied
        let gate = ApprovalGate::yolo();
        assert_eq!(
            gate.check("bash", r#"{"command":"git reset --hard HEAD"}"#, "/tmp")
                .await,
            ApprovalResponse::Deny
        );
    }

    #[tokio::test]
    async fn test_yolo_gate_destructive_with_frontend() {
        // With a frontend, destructive ops prompt even in Yolo mode
        let shared = SharedApproveMode::new(ApproveMode::Yolo);
        let (tx, mut rx) = mpsc::unbounded_channel();
        let gate = ApprovalGate::new(shared, tx);

        tokio::spawn(async move {
            let req = rx.recv().await.unwrap();
            assert!(req.tool_args.contains("reset --hard"));
            req.response_tx.send(ApprovalResponse::Approve).unwrap();
        });

        assert_eq!(
            gate.check("bash", r#"{"command":"git reset --hard HEAD"}"#, "/tmp")
                .await,
            ApprovalResponse::Approve
        );
    }

    #[tokio::test]
    async fn test_auto_gate_safe_tool() {
        let shared = SharedApproveMode::new(ApproveMode::Auto);
        let (tx, _rx) = mpsc::unbounded_channel();
        let gate = ApprovalGate::new(shared, tx);
        assert_eq!(
            gate.check("file_read", "{}", "/tmp").await,
            ApprovalResponse::Approve
        );
    }

    #[tokio::test]
    async fn test_manual_gate_sends_request() {
        let shared = SharedApproveMode::new(ApproveMode::Manual);
        let (tx, mut rx) = mpsc::unbounded_channel();
        let gate = ApprovalGate::new(shared, tx);

        tokio::spawn(async move {
            let req = rx.recv().await.unwrap();
            assert_eq!(req.tool_name, "bash");
            req.response_tx.send(ApprovalResponse::Deny).unwrap();
        });

        let result = gate.check("bash", "{}", "/tmp").await;
        assert_eq!(result, ApprovalResponse::Deny);
    }

    #[tokio::test]
    async fn test_runtime_mode_switch() {
        let shared = SharedApproveMode::new(ApproveMode::Yolo);
        let (tx, _rx) = mpsc::unbounded_channel();
        let gate = ApprovalGate::new(shared.clone(), tx);

        assert_eq!(
            gate.check("bash", "{}", "/tmp").await,
            ApprovalResponse::Approve
        );

        shared.set(ApproveMode::Manual);
        assert_eq!(gate.mode(), ApproveMode::Manual);
    }

    #[tokio::test]
    async fn test_session_approvals_cache() {
        let sa = SessionApprovals::new();
        let shared = SharedApproveMode::new(ApproveMode::Auto);
        let (tx, mut rx) = mpsc::unbounded_channel::<ApprovalRequest>();
        let gate = ApprovalGate::new_with_session(shared, tx, sa.clone());

        // First request — frontend approves
        tokio::spawn(async move {
            let req = rx.recv().await.unwrap();
            req.response_tx.send(ApprovalResponse::Approve).unwrap();
        });
        assert_eq!(
            gate.check("bash", "{}", "/tmp").await,
            ApprovalResponse::Approve
        );

        // Second request — cache hit, no popup
        assert_eq!(
            gate.check("bash", "{}", "/tmp").await,
            ApprovalResponse::Approve
        );
    }

    #[tokio::test]
    async fn test_session_approvals_deny_cached() {
        let sa = SessionApprovals::new();
        let shared = SharedApproveMode::new(ApproveMode::Manual);
        let (tx, mut rx) = mpsc::unbounded_channel::<ApprovalRequest>();
        let gate = ApprovalGate::new_with_session(shared, tx, sa.clone());

        tokio::spawn(async move {
            let req = rx.recv().await.unwrap();
            req.response_tx.send(ApprovalResponse::Deny).unwrap();
        });
        assert_eq!(
            gate.check("file_write", "{}", "/tmp").await,
            ApprovalResponse::Deny
        );

        // Subsequent calls return Deny immediately without sending another request
        assert_eq!(
            gate.check("file_write", "{}", "/tmp").await,
            ApprovalResponse::Deny
        );
    }

    #[tokio::test]
    async fn test_parallel_agents_share_approval() {
        let sa = SessionApprovals::new();
        let shared = SharedApproveMode::new(ApproveMode::Auto);
        let (tx, mut rx) = mpsc::unbounded_channel::<ApprovalRequest>();

        let gate_a = ApprovalGate::new_with_session(shared.clone(), tx.clone(), sa.clone());
        let gate_b = ApprovalGate::new_with_session(shared.clone(), tx, sa.clone());

        // Respond to the single popup (only one should fire)
        tokio::spawn(async move {
            let req = rx.recv().await.unwrap();
            req.response_tx.send(ApprovalResponse::Approve).unwrap();
            // Second request should NOT arrive
            assert!(
                tokio::time::timeout(std::time::Duration::from_millis(50), rx.recv())
                    .await
                    .is_err(),
                "Expected only one approval popup for parallel agents"
            );
        });

        // Both gates request the same tool concurrently
        let (r_a, r_b) = tokio::join!(
            gate_a.check("bash", "{}", "/tmp"),
            gate_b.check("bash", "{}", "/tmp"),
        );
        assert_eq!(r_a, ApprovalResponse::Approve);
        assert_eq!(r_b, ApprovalResponse::Approve);
    }

    // ── is_path_denied ───────────────────────────────────────────────────────

    fn patterns(strs: &[&str]) -> Vec<String> {
        strs.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn test_deny_prefix_exact_match() {
        let p = patterns(&["/etc/passwd"]);
        assert!(is_path_denied("/etc/passwd", &p));
    }

    #[test]
    fn test_deny_prefix_child_match() {
        let p = patterns(&["/etc"]);
        assert!(is_path_denied("/etc/shadow", &p));
        assert!(is_path_denied("/etc/ssh/sshd_config", &p));
    }

    #[test]
    fn test_deny_prefix_no_partial_match() {
        // "/etcfoo" must NOT match "/etc" prefix
        let p = patterns(&["/etc"]);
        assert!(!is_path_denied("/etcfoo/bar", &p));
    }

    #[test]
    fn test_deny_glob_suffix() {
        let p = patterns(&["**/.env"]);
        assert!(is_path_denied("/project/backend/.env", &p));
        assert!(is_path_denied("/any/deeply/nested/.env", &p));
        assert!(!is_path_denied("/project/.env.local", &p));
    }

    #[test]
    fn test_deny_empty_patterns() {
        assert!(!is_path_denied("/etc/passwd", &[]));
    }

    #[test]
    fn test_deny_no_match() {
        let p = patterns(&["/etc", "~/.ssh"]);
        // ~/.ssh expansion depends on HOME; test a non-home path
        assert!(!is_path_denied("/home/user/projects/main.rs", &p));
    }
}