codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
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
//! Turn authority and mode/posture policy projections.
//!
//! Keep mode, approval, shell, sandbox, trust, and input provenance decisions
//! in one place so prompt metadata, tool catalogs, and runtime gates cannot
//! drift independently.

use std::ffi::OsStr;
use std::path::{Component, Path, PathBuf};

use crate::sandbox::SandboxPolicy;
use crate::tools::spec::{ApprovalRequirement, normalize_path};
use crate::tui::app::AppMode;
use crate::tui::approval::ApprovalMode;
use crate::worker_profile::ShellPolicy;

use super::ops::UserInputProvenance;

/// Durable Agent-era permission baseline that Plan/YOLO restore to (#3386).
///
/// Mode cycling used to be tangled with permission policy: each mode mutated
/// `allow_shell`/`trust_mode`/`approval_mode` directly and ad-hoc snapshots
/// tried to put things back on exit. Instead, keep one canonical baseline: the
/// permission surface the user has chosen for Agent mode.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ModeSessionPrefs {
    pub(crate) agent_allow_shell: bool,
    pub(crate) agent_trust_mode: bool,
    pub(crate) agent_approval_mode: ApprovalMode,
}

/// The permission policy a given [`AppMode`] resolves to (#3386).
#[derive(Debug, Clone, Copy)]
pub(crate) struct EffectiveModePolicy {
    #[allow(dead_code)]
    pub(crate) mode: AppMode,
    pub(crate) allow_shell: bool,
    pub(crate) trust_mode: bool,
    pub(crate) approval_mode: ApprovalMode,
}

/// Resolve a mode's effective permission policy from the durable Agent baseline.
///
/// This is the single source of truth for the mode/permission table:
/// - `Plan`   -> read-only: no shell, no trust, `Suggest` approvals.
/// - `Agent`  -> the user's durable baseline (`prefs`).
/// - `Auto`   -> compatibility alias for Agent; not a separate behavior.
/// - `Operate` -> Agent baseline plus orchestration capabilities in the runtime.
/// - `Yolo`   -> legacy compat; full authority: shell + trust + `Bypass` approvals.
#[must_use]
pub(crate) fn base_policy_for_mode(mode: AppMode, prefs: &ModeSessionPrefs) -> EffectiveModePolicy {
    match mode {
        AppMode::Plan => EffectiveModePolicy {
            mode,
            allow_shell: false,
            trust_mode: false,
            approval_mode: ApprovalMode::Suggest,
        },
        AppMode::Agent | AppMode::Auto | AppMode::Operate => EffectiveModePolicy {
            mode,
            allow_shell: prefs.agent_allow_shell,
            trust_mode: prefs.agent_trust_mode,
            approval_mode: prefs.agent_approval_mode,
        },
        AppMode::Yolo => EffectiveModePolicy {
            mode,
            allow_shell: true,
            trust_mode: true,
            approval_mode: ApprovalMode::Bypass,
        },
    }
}

/// Why runtime policy narrowed the authority a turn was asked to run with.
///
/// One variant per narrowing site. Adding a site means adding a variant, which
/// is the mechanism that makes "no silent effective mode change" enforceable
/// rather than aspirational (#3947).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PolicyNarrowingReason {
    /// Input arrived from a provenance that cannot inherit standing
    /// auto-approval authority (sub-agent handoffs, restored checkpoints).
    NonAuthoritativeProvenance,
}

impl PolicyNarrowingReason {
    /// Stable machine-readable identifier. Shared by the model-visible
    /// metadata line and doctor output so the two cannot drift.
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::NonAuthoritativeProvenance => "non_authoritative_provenance",
        }
    }
}

/// A structured record of one authority narrowing.
///
/// Before this existed, narrowing produced only a free-text UI status line:
/// the model saw the narrowed posture but never learned it had been narrowed
/// or why, and doctor could not report it at all. Every consumer now renders
/// from this one value, so the UI status, the `<turn_meta>` line, and doctor
/// necessarily agree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PolicyNarrowingEvent {
    reason: PolicyNarrowingReason,
    /// Mode before narrowing, and after, as setting strings.
    from_mode: &'static str,
    to_mode: &'static str,
    /// Permission posture before narrowing, and after.
    from_approval: ApprovalMode,
    to_approval: ApprovalMode,
    /// Human-readable cause, e.g. the provenance that could not inherit.
    detail: String,
}

impl PolicyNarrowingEvent {
    pub(crate) fn reason(&self) -> PolicyNarrowingReason {
        self.reason
    }

    /// The single user-facing sentence. The TUI status line renders exactly
    /// this, and the model-visible metadata carries the same string.
    pub(crate) fn message(&self) -> String {
        match self.reason {
            PolicyNarrowingReason::NonAuthoritativeProvenance => format!(
                "Input provenance '{}' cannot inherit standing auto-approval authority; continuing with approvals required.",
                self.detail
            ),
        }
    }

    /// Compact `from -> to` summary for doctor and debug surfaces.
    pub(crate) fn transition(&self) -> String {
        format!(
            "{} ({}) -> {} ({})",
            self.from_mode,
            self.from_approval.permission_chip_label(),
            self.to_mode,
            self.to_approval.permission_chip_label(),
        )
    }
}

/// Effective authority for one engine turn after provenance narrowing.
#[derive(Debug, Clone)]
pub(crate) struct TurnAuthority {
    pub(crate) mode: AppMode,
    pub(crate) allow_shell: bool,
    pub(crate) trust_mode: bool,
    pub(crate) auto_approve: bool,
    pub(crate) approval_mode: ApprovalMode,
    pub(crate) dynamic_active_tools: Vec<&'static str>,
    /// Structured record of any narrowing applied to this turn (#3947). The
    /// UI status line, `<turn_meta>`, and doctor all render from here, so a
    /// narrowing that reaches one surface reaches all of them.
    pub(crate) narrowing: Option<PolicyNarrowingEvent>,
}

impl TurnAuthority {
    /// The user-facing status sentence for this turn's narrowing, if any.
    pub(crate) fn status(&self) -> Option<String> {
        self.narrowing.as_ref().map(PolicyNarrowingEvent::message)
    }

    #[must_use]
    pub(crate) fn from_effective_fields(
        mode: AppMode,
        allow_shell: bool,
        trust_mode: bool,
        auto_approve: bool,
        approval_mode: ApprovalMode,
    ) -> Self {
        Self {
            mode,
            allow_shell,
            trust_mode,
            auto_approve,
            approval_mode,
            dynamic_active_tools: Vec::new(),
            narrowing: None,
        }
    }

    #[must_use]
    pub(crate) fn approval_mode_for_session(&self) -> ApprovalMode {
        agent_approval_mode_for_turn(self.auto_approve, self.approval_mode)
    }

    /// Authority for the per-tool approval gate, folded from the legacy
    /// session `auto_approve` bit so [`resolve_tool_permission`] observes the
    /// same effective posture the old boolean helpers encoded: a set bit is
    /// Full Access (Yolo/Bypass-shaped), a cleared bit is an ordinary Ask
    /// turn. The engine's `Never` denial deliberately stays at the UI layer,
    /// so this constructor never produces a `Never` posture.
    #[must_use]
    pub(crate) fn for_tool_approval_decision(auto_approve: bool) -> Self {
        Self::from_effective_fields(
            if auto_approve {
                AppMode::Yolo
            } else {
                AppMode::Agent
            },
            true,
            false,
            auto_approve,
            if auto_approve {
                ApprovalMode::Bypass
            } else {
                ApprovalMode::Suggest
            },
        )
    }

    #[must_use]
    pub(crate) fn shell_policy(&self) -> ShellPolicy {
        shell_policy_for_mode(self.mode, self.allow_shell)
    }

    #[must_use]
    pub(crate) fn sandbox_policy(
        &self,
        workspace: &Path,
        configured_mode: Option<&str>,
    ) -> SandboxPolicy {
        sandbox_policy_for_turn(
            self.mode,
            self.approval_mode_for_session(),
            configured_mode,
            workspace,
        )
    }
}

#[must_use]
pub(crate) fn effective_input_policy(
    provenance: UserInputProvenance,
    requested_mode: AppMode,
    _content: &str,
    allow_shell: bool,
    trust_mode: bool,
    auto_approve: bool,
    approval_mode: ApprovalMode,
) -> TurnAuthority {
    let mut mode = requested_mode;
    let mut trust_mode = trust_mode;
    let mut auto_approve = auto_approve;
    let mut approval_mode = approval_mode;
    let mut narrowing = None;

    if !provenance_can_inherit_standing_auto_authority(provenance) {
        let from_mode = mode;
        let from_approval = approval_mode;
        let had_auto_authority = matches!(mode, AppMode::Yolo)
            || trust_mode
            || auto_approve
            || matches!(approval_mode, ApprovalMode::Bypass);
        if matches!(mode, AppMode::Yolo) {
            mode = AppMode::Agent;
        }
        trust_mode = false;
        auto_approve = false;
        if matches!(approval_mode, ApprovalMode::Auto | ApprovalMode::Bypass) {
            approval_mode = ApprovalMode::Suggest;
        }
        if had_auto_authority {
            // Record the transition, not just a sentence about it: the same
            // value drives the UI status, `<turn_meta>`, and doctor (#3947).
            narrowing = Some(PolicyNarrowingEvent {
                reason: PolicyNarrowingReason::NonAuthoritativeProvenance,
                from_mode: from_mode.as_setting(),
                to_mode: mode.as_setting(),
                from_approval,
                to_approval: approval_mode,
                detail: provenance.as_str().to_string(),
            });
        }
    }

    // The named permission posture is authoritative. Normalize legacy or
    // host inputs that carry `Bypass` with a stale false auto-approve bit so
    // every engine surface observes the same Full Access contract.
    if approval_mode == ApprovalMode::Bypass {
        auto_approve = true;
    }

    TurnAuthority {
        mode,
        allow_shell,
        trust_mode,
        auto_approve,
        approval_mode,
        dynamic_active_tools: Vec::new(),
        narrowing,
    }
}

#[must_use]
pub(crate) fn provenance_can_inherit_standing_auto_authority(
    provenance: UserInputProvenance,
) -> bool {
    matches!(
        provenance,
        UserInputProvenance::ExternalUser
            | UserInputProvenance::Runtime
            | UserInputProvenance::SubAgentHandoff
    )
}

/// Whether the active permission posture may pause the turn for a user
/// decision. Auto-Review is the fully autonomous posture: it must decide from
/// available context and keep moving. Tool approval and user-question policy
/// stay deliberately separate in every other posture.
#[must_use]
pub(crate) fn permission_posture_allows_questions(approval_mode: ApprovalMode) -> bool {
    approval_mode != ApprovalMode::Auto
}

#[must_use]
pub(crate) fn agent_approval_mode_for_turn(
    auto_approve: bool,
    approval_mode: ApprovalMode,
) -> ApprovalMode {
    if auto_approve {
        ApprovalMode::Bypass
    } else {
        approval_mode
    }
}

/// Resolve the filesystem boundary for one turn.
///
/// Permission posture and filesystem scope are separate controls, but the
/// named Full Access posture must have a truthful default: outside Plan it
/// disables Codewhale's own sandbox, matching the product meaning of the
/// name. An explicit effective sandbox setting may still *tighten* that
/// default. It can never loosen Plan, Ask, or Auto-Review.
#[must_use]
pub(crate) fn sandbox_policy_for_turn(
    mode: AppMode,
    approval_mode: ApprovalMode,
    configured_mode: Option<&str>,
    workspace: &Path,
) -> SandboxPolicy {
    let default = if mode == AppMode::Plan {
        SandboxPolicy::ReadOnly
    } else if mode == AppMode::Yolo || approval_mode == ApprovalMode::Bypass {
        SandboxPolicy::DangerFullAccess
    } else {
        workspace_write_policy(workspace)
    };

    // The effective Config has already applied managed/project precedence.
    // Only stricter scopes clamp the posture-derived default: a configured
    // danger-full-access value must not silently loosen Ask or Auto-Review.
    match (default, configured_mode) {
        (SandboxPolicy::ReadOnly, _) | (_, Some("read-only")) => SandboxPolicy::ReadOnly,
        (SandboxPolicy::DangerFullAccess, Some("workspace-write")) => {
            workspace_write_policy(workspace)
        }
        (SandboxPolicy::DangerFullAccess, Some("external-sandbox")) => {
            SandboxPolicy::ExternalSandbox {
                network_access: true,
            }
        }
        (policy, _) => policy,
    }
}

fn workspace_write_policy(workspace: &Path) -> SandboxPolicy {
    SandboxPolicy::WorkspaceWrite {
        writable_roots: vec![workspace.to_path_buf()],
        network_access: true,
        exclude_tmpdir: false,
        exclude_slash_tmp: false,
    }
}

/// Resolve the effective shell policy for a turn from legacy shell opt-in plus mode.
#[must_use]
pub(crate) fn shell_policy_for_mode(mode: AppMode, allow_shell: bool) -> ShellPolicy {
    if !allow_shell {
        return ShellPolicy::None;
    }
    match mode {
        AppMode::Plan => ShellPolicy::None,
        AppMode::Agent | AppMode::Auto | AppMode::Operate | AppMode::Yolo => ShellPolicy::Full,
    }
}

/// Per-tool permission decision from the unified resolver (#4412).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ToolPermission {
    /// Tool executes without any approval prompt.
    Allow,
    /// Tool requires user approval before execution.
    Prompt,
    /// Tool is denied without a prompt (approval_mode=Never).
    Deny,
}

/// Unified per-tool permission resolver (#4412).
///
/// Consolidates the approval decision that was previously scattered across
/// `registered_tool_approval_required` (turn_loop), `app_auto_approve_enabled`
/// (ui.rs), and the `Never` short-circuit. One call site, one answer.
///
/// The truth table mirrors the legacy helpers exactly:
/// - `Auto` tools always run — even under `Never`, which stays read-only
///   rather than dead.
/// - `Never` denies any tool that would otherwise prompt, but only when the
///   authority is not full-access shaped: a Yolo/Bypass authority carrying a
///   stale `Never` enum still auto-approves, matching the legacy UI order in
///   which the full-access shortcut ran before the `Never` check.
/// - `Suggest` and `Required` are both bypassable by auto-approve authority
///   unless the tool is on the typed non-bypassable hold list
///   (`is_non_bypassable`), which always prompts. A generic `Required` tool
///   remains auto-approved in Full Access (#3866).
#[must_use]
pub(crate) fn resolve_tool_permission(
    authority: &TurnAuthority,
    requirement: ApprovalRequirement,
    is_non_bypassable: bool,
) -> ToolPermission {
    if authority.approval_mode == ApprovalMode::Never
        && requirement != ApprovalRequirement::Auto
        && !authority.auto_approve
        && authority.mode != AppMode::Yolo
    {
        return ToolPermission::Deny;
    }
    match requirement {
        ApprovalRequirement::Auto => ToolPermission::Allow,
        ApprovalRequirement::Suggest | ApprovalRequirement::Required => {
            if is_non_bypassable {
                // Full Access already grants everything these calls can do —
                // shell included — so a hold that cannot open its own
                // approval modal auto-approves instead of stranding the call.
                // #3866 blocked here through v0.9.6; reversed 2026-08-10.
                return if authority.auto_approve || authority.mode == AppMode::Yolo {
                    ToolPermission::Allow
                } else {
                    ToolPermission::Prompt
                };
            }
            if authority.auto_approve
                || authority.approval_mode == ApprovalMode::Bypass
                || authority.mode == AppMode::Yolo
            {
                ToolPermission::Allow
            } else {
                ToolPermission::Prompt
            }
        }
    }
}

/// Whether the session posture is the one the in-workspace write carve-out
/// (#5185) relaxes: the default Ask posture (`Suggest` approvals, no
/// auto-approve) in an Agent-family mode.
///
/// Every other posture keeps its exact prior meaning: Full Access already
/// runs these calls, `Never` still denies them, Auto-Review still fails
/// unresolved holds closed, and Plan is read-only by mode.
#[must_use]
pub(crate) fn write_carve_out_posture(
    mode: AppMode,
    approval_mode: ApprovalMode,
    auto_approve: bool,
) -> bool {
    !auto_approve
        && matches!(mode, AppMode::Agent | AppMode::Auto | AppMode::Operate)
        && approval_mode == ApprovalMode::Suggest
}

/// Whether every target path of a file-write call qualifies for the
/// in-workspace write carve-out (#5185): the workspace is a git work tree,
/// each path resolves inside it, and none touches `.git` internals, runtime
/// state, or a sensitive file.
///
/// The git work-tree marker is deliberate (the same shape as kimi-code's
/// `git-cwd-write-approve` policy): the carve-out exists because
/// version-controlled edits stay reviewable and recoverable, so a workspace
/// without git keeps the modal.
#[must_use]
pub(crate) fn paths_within_workspace_write_carve_out(workspace: &Path, paths: &[String]) -> bool {
    if paths.is_empty() {
        return false;
    }
    // `.git` may be a directory (normal checkout) or a file (worktree or
    // submodule); either marks a git work tree.
    if workspace.join(".git").symlink_metadata().is_err() {
        return false;
    }
    let Ok(workspace_canonical) = workspace.canonicalize() else {
        return false;
    };
    paths
        .iter()
        .all(|raw| carve_out_target_allowed(workspace, &workspace_canonical, raw))
}

fn carve_out_target_allowed(workspace: &Path, workspace_canonical: &Path, raw: &str) -> bool {
    let raw = raw.trim();
    if raw.is_empty() {
        return false;
    }
    let raw_path = Path::new(raw);
    let candidate = if raw_path.is_absolute() {
        raw_path.to_path_buf()
    } else {
        workspace.join(raw_path)
    };
    // Lexical containment first: `..` escapes and absolute out-of-tree paths
    // fail here without touching the filesystem.
    let lexical = normalize_path(&candidate);
    let workspace_lexical = normalize_path(workspace);
    let workspace_canonical_lexical = normalize_path(workspace_canonical);
    let Ok(relative) = lexical
        .strip_prefix(&workspace_lexical)
        .or_else(|_| lexical.strip_prefix(&workspace_canonical_lexical))
    else {
        return false;
    };
    if !carve_out_relative_path_allowed(relative) {
        return false;
    }
    // Then symlink reality: resolve the deepest existing ancestor and
    // require the real path to stay inside the real workspace and off the
    // same exclusions (a symlink hop into `.git` or out of the tree fails).
    let Some(resolved) = resolve_deepest_existing(&candidate) else {
        return false;
    };
    let Ok(resolved_relative) = resolved.strip_prefix(workspace_canonical) else {
        return false;
    };
    carve_out_relative_path_allowed(resolved_relative)
}

/// Canonicalize the deepest existing ancestor of `candidate` and re-append
/// the not-yet-existing tail, so write targets that do not exist yet still
/// get a real-path check.
fn resolve_deepest_existing(candidate: &Path) -> Option<PathBuf> {
    let mut ancestor = candidate;
    let mut suffix: Vec<&OsStr> = Vec::new();
    loop {
        if let Ok(canonical) = ancestor.canonicalize() {
            let mut resolved = canonical;
            for part in suffix.iter().rev() {
                resolved.push(part);
            }
            return Some(resolved);
        }
        suffix.push(ancestor.file_name()?);
        ancestor = ancestor.parent()?;
    }
}

fn carve_out_relative_path_allowed(relative: &Path) -> bool {
    relative.components().all(|component| {
        let Component::Normal(part) = component else {
            return true;
        };
        !is_carve_out_excluded_name(&part.to_string_lossy().to_ascii_lowercase())
    })
}

/// Names the carve-out never auto-allows, matched per path component:
/// `.git` internals, runtime/project state, credential-bearing directories
/// and files, and key material.
fn is_carve_out_excluded_name(name: &str) -> bool {
    if name == ".git" {
        return true;
    }
    // Runtime/project state and credential-bearing directories. `.codewhale`
    // holds session state plus MCP/hook configuration — editing it changes
    // what runs, so it keeps the modal.
    if matches!(
        name,
        ".codewhale" | ".ssh" | ".aws" | ".gnupg" | ".kube" | ".docker"
    ) {
        return true;
    }
    // Environment files and well-known credential stores.
    if name.starts_with(".env")
        || name == ".netrc"
        || name == ".npmrc"
        || name == ".pypirc"
        || name == ".git-credentials"
        || name == "credentials"
        || name.starts_with("credentials.")
    {
        return true;
    }
    // SSH private (and public) key material.
    if name.starts_with("id_rsa")
        || name.starts_with("id_dsa")
        || name.starts_with("id_ecdsa")
        || name.starts_with("id_ed25519")
    {
        return true;
    }
    // Key/certificate containers by extension.
    matches!(
        Path::new(name).extension().and_then(|ext| ext.to_str()),
        Some("pem" | "key" | "p12" | "pfx" | "jks" | "keystore")
    )
}

/// Disposition for an approval request that reached the UI (#4412).
///
/// The engine emits `ApprovalRequired` whenever its resolver answer was
/// `Prompt`; the UI then disposes of that request — honoring session caches
/// and posture races — through this single decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ApprovalRequestDisposition {
    /// Session grant or full-access posture: approve without a modal.
    AutoApprove,
    /// The user already denied this approval key this session (#360).
    AutoDenySessionDenied,
    /// A forced (non-bypassable) policy hold arrived under a full-access
    /// posture that opens no modal: fail closed.
    AutoDenyFullAccessPolicyHold,
    /// Auto-Review is autonomous: unresolved holds fail closed instead of
    /// opening a user-approval modal.
    AutoDenyAutoReview,
    /// approval_mode=Never: deny without a modal.
    AutoDenyNeverPosture,
    /// Open the approval modal.
    Prompt,
}

/// Resolve how the UI disposes of one incoming approval request.
///
/// `session_approved` / `session_denied` are the caller's lookups into the
/// session approval caches (grouping key or tool name / exact approval key).
/// The branch order is the legacy handler's order: session denial, then the
/// full-access forced-hold denial, then auto-approval (full access or a
/// session grant), then the `Never` denial, and only finally a modal.
#[must_use]
pub(crate) fn resolve_approval_request_disposition(
    authority: &TurnAuthority,
    session_approved: bool,
    session_denied: bool,
    approval_force_prompt: bool,
) -> ApprovalRequestDisposition {
    if session_denied {
        return ApprovalRequestDisposition::AutoDenySessionDenied;
    }
    if authority.approval_mode_for_session() == ApprovalMode::Auto {
        return ApprovalRequestDisposition::AutoDenyAutoReview;
    }
    // The request exists, so the engine already resolved Prompt for the tool
    // itself. What remains is the posture question: how does this authority
    // treat an ordinary promptable tool?
    let posture = resolve_tool_permission(authority, ApprovalRequirement::Suggest, false);
    if approval_force_prompt && posture == ToolPermission::Allow {
        return ApprovalRequestDisposition::AutoDenyFullAccessPolicyHold;
    }
    if !approval_force_prompt && (posture == ToolPermission::Allow || session_approved) {
        return ApprovalRequestDisposition::AutoApprove;
    }
    if posture == ToolPermission::Deny {
        return ApprovalRequestDisposition::AutoDenyNeverPosture;
    }
    ApprovalRequestDisposition::Prompt
}

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

    fn authority(mode: AppMode, auto_approve: bool, approval_mode: ApprovalMode) -> TurnAuthority {
        TurnAuthority::from_effective_fields(mode, true, false, auto_approve, approval_mode)
    }

    #[test]
    fn write_carve_out_posture_is_exactly_the_default_ask_posture() {
        assert!(write_carve_out_posture(
            AppMode::Agent,
            ApprovalMode::Suggest,
            false
        ));
        assert!(write_carve_out_posture(
            AppMode::Operate,
            ApprovalMode::Suggest,
            false
        ));
        // Full Access already runs these calls; the carve-out must not be
        // what allows them.
        assert!(!write_carve_out_posture(
            AppMode::Agent,
            ApprovalMode::Bypass,
            true
        ));
        assert!(!write_carve_out_posture(
            AppMode::Yolo,
            ApprovalMode::Bypass,
            true
        ));
        // Never still denies; Auto-Review still fails unresolved holds closed;
        // Plan is read-only by mode.
        assert!(!write_carve_out_posture(
            AppMode::Agent,
            ApprovalMode::Never,
            false
        ));
        assert!(!write_carve_out_posture(
            AppMode::Agent,
            ApprovalMode::Auto,
            false
        ));
        assert!(!write_carve_out_posture(
            AppMode::Plan,
            ApprovalMode::Suggest,
            false
        ));
    }

    fn carve_out_workspace() -> tempfile::TempDir {
        let tmp = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir(tmp.path().join(".git")).expect("git marker");
        std::fs::create_dir_all(tmp.path().join("src")).expect("src dir");
        std::fs::write(tmp.path().join("src/main.rs"), "fn main() {}\n").expect("source file");
        tmp
    }

    #[test]
    fn carve_out_allows_in_workspace_write_targets() {
        let tmp = carve_out_workspace();
        let workspace = tmp.path();
        for paths in [
            vec!["src/main.rs".to_string()],
            vec!["src/new_file.rs".to_string()],
            vec!["deeply/nested/not-yet-created.rs".to_string()],
            vec!["./src/main.rs".to_string()],
            vec![workspace.join("src/main.rs").to_string_lossy().into_owned()],
            vec!["src/main.rs".to_string(), "src/other.rs".to_string()],
        ] {
            assert!(
                paths_within_workspace_write_carve_out(workspace, &paths),
                "{paths:?} should qualify"
            );
        }
    }

    #[test]
    fn carve_out_rejects_out_of_tree_sensitive_and_git_paths() {
        let tmp = carve_out_workspace();
        let workspace = tmp.path();
        for paths in [
            vec!["../outside.rs".to_string()],
            vec!["src/../../outside.rs".to_string()],
            vec!["/etc/passwd".to_string()],
            vec![".git/config".to_string()],
            vec!["nested/.git/hooks/pre-commit".to_string()],
            vec![".env".to_string()],
            vec!["config/.env.production".to_string()],
            vec![".ssh/config".to_string()],
            vec!["deploy/id_rsa".to_string()],
            vec!["certs/server.pem".to_string()],
            vec![".codewhale/mcp.json".to_string()],
            vec!["aws/credentials".to_string()],
            // One bad target poisons the whole call.
            vec!["src/main.rs".to_string(), ".env".to_string()],
        ] {
            assert!(
                !paths_within_workspace_write_carve_out(workspace, &paths),
                "{paths:?} must keep the modal"
            );
        }
    }

    #[test]
    fn carve_out_requires_a_git_work_tree() {
        let tmp = tempfile::tempdir().expect("tempdir");
        assert!(!paths_within_workspace_write_carve_out(
            tmp.path(),
            &["src/main.rs".to_string()]
        ));
    }

    #[test]
    fn carve_out_rejects_empty_target_list() {
        let tmp = carve_out_workspace();
        assert!(!paths_within_workspace_write_carve_out(tmp.path(), &[]));
    }

    #[cfg(unix)]
    #[test]
    fn carve_out_rejects_symlink_escapes() {
        let tmp = carve_out_workspace();
        let outside = tempfile::tempdir().expect("outside tempdir");
        std::os::unix::fs::symlink(outside.path(), tmp.path().join("link")).expect("symlink");
        assert!(!paths_within_workspace_write_carve_out(
            tmp.path(),
            &["link/evil.rs".to_string()]
        ));
        // A symlink that stays inside the workspace is fine.
        std::os::unix::fs::symlink(tmp.path().join("src"), tmp.path().join("src-link"))
            .expect("inner symlink");
        assert!(paths_within_workspace_write_carve_out(
            tmp.path(),
            &["src-link/main.rs".to_string()]
        ));
    }

    #[test]
    fn full_access_is_unsandboxed_unless_effective_config_is_stricter() {
        let workspace = Path::new("/work");
        let full_access = authority(AppMode::Agent, true, ApprovalMode::Bypass);

        assert_eq!(
            full_access.sandbox_policy(workspace, None),
            SandboxPolicy::DangerFullAccess
        );
        assert!(matches!(
            full_access.sandbox_policy(workspace, Some("workspace-write")),
            SandboxPolicy::WorkspaceWrite { writable_roots, .. }
                if writable_roots == vec![workspace.to_path_buf()]
        ));
        assert_eq!(
            full_access.sandbox_policy(workspace, Some("read-only")),
            SandboxPolicy::ReadOnly
        );
        assert!(matches!(
            full_access.sandbox_policy(workspace, Some("external-sandbox")),
            SandboxPolicy::ExternalSandbox {
                network_access: true
            }
        ));
    }

    #[test]
    fn plan_ask_and_auto_review_cannot_be_loosened_by_sandbox_config() {
        let workspace = Path::new("/work");
        for approval_mode in [ApprovalMode::Suggest, ApprovalMode::Auto] {
            let authority = authority(AppMode::Agent, false, approval_mode);
            assert!(matches!(
                authority.sandbox_policy(workspace, Some("danger-full-access")),
                SandboxPolicy::WorkspaceWrite { .. }
            ));
        }

        let plan = authority(AppMode::Plan, true, ApprovalMode::Bypass);
        assert_eq!(
            plan.sandbox_policy(workspace, Some("danger-full-access")),
            SandboxPolicy::ReadOnly
        );
    }

    #[test]
    fn auto_requirement_always_allows() {
        for (mode, auto_approve, approval_mode) in [
            (AppMode::Agent, false, ApprovalMode::Suggest),
            (AppMode::Agent, false, ApprovalMode::Auto),
            (AppMode::Agent, false, ApprovalMode::Never),
            (AppMode::Agent, true, ApprovalMode::Bypass),
            (AppMode::Yolo, true, ApprovalMode::Bypass),
            (AppMode::Plan, false, ApprovalMode::Suggest),
        ] {
            let auth = authority(mode, auto_approve, approval_mode);
            for non_bypassable in [false, true] {
                assert_eq!(
                    resolve_tool_permission(&auth, ApprovalRequirement::Auto, non_bypassable),
                    ToolPermission::Allow,
                    "{mode:?}/{auto_approve}/{approval_mode:?}/nb={non_bypassable}"
                );
            }
        }
    }

    #[test]
    fn ask_posture_prompts_for_non_auto_tools() {
        let auth = authority(AppMode::Agent, false, ApprovalMode::Suggest);
        for requirement in [ApprovalRequirement::Suggest, ApprovalRequirement::Required] {
            assert_eq!(
                resolve_tool_permission(&auth, requirement, false),
                ToolPermission::Prompt
            );
            assert_eq!(
                resolve_tool_permission(&auth, requirement, true),
                ToolPermission::Prompt
            );
        }
    }

    #[test]
    fn full_access_allows_bypassable_but_prompts_for_non_bypassable() {
        for auth in [
            authority(AppMode::Agent, true, ApprovalMode::Bypass),
            authority(AppMode::Yolo, true, ApprovalMode::Bypass),
            TurnAuthority::for_tool_approval_decision(true),
        ] {
            for requirement in [ApprovalRequirement::Suggest, ApprovalRequirement::Required] {
                assert_eq!(
                    resolve_tool_permission(&auth, requirement, false),
                    ToolPermission::Allow,
                    "generic {requirement:?} tool stays auto-approved in Full Access"
                );
                assert_eq!(
                    resolve_tool_permission(&auth, requirement, true),
                    ToolPermission::Allow,
                    "non-bypassable {requirement:?} tool auto-approves in Full Access (#3866 reversed)"
                );
            }
        }

        // Ask (the default suggest posture without auto-approve) can open the
        // modal, so the hold still prompts there.
        let ask = authority(AppMode::Agent, false, ApprovalMode::Suggest);
        for requirement in [ApprovalRequirement::Suggest, ApprovalRequirement::Required] {
            assert_eq!(
                resolve_tool_permission(&ask, requirement, true),
                ToolPermission::Prompt,
                "non-bypassable {requirement:?} tool still prompts in Ask"
            );
        }
    }

    #[test]
    fn never_denies_promptable_tools_but_not_reads_or_full_access_shapes() {
        let never = authority(AppMode::Agent, false, ApprovalMode::Never);
        assert_eq!(
            resolve_tool_permission(&never, ApprovalRequirement::Suggest, false),
            ToolPermission::Deny
        );
        assert_eq!(
            resolve_tool_permission(&never, ApprovalRequirement::Required, true),
            ToolPermission::Deny
        );
        assert_eq!(
            resolve_tool_permission(&never, ApprovalRequirement::Auto, false),
            ToolPermission::Allow,
            "Never remains read-only rather than dead"
        );

        // Legacy host shape: full-access bit/Yolo mode with a stale Never enum
        // still auto-approves — the UI's full-access shortcut ran before its
        // Never check.
        let stale = authority(AppMode::Agent, true, ApprovalMode::Never);
        assert_eq!(
            resolve_tool_permission(&stale, ApprovalRequirement::Suggest, false),
            ToolPermission::Allow
        );
        let yolo_never = authority(AppMode::Yolo, false, ApprovalMode::Never);
        assert_eq!(
            resolve_tool_permission(&yolo_never, ApprovalRequirement::Suggest, false),
            ToolPermission::Allow
        );
    }

    #[test]
    fn approval_request_disposition_preserves_legacy_branch_order() {
        let ask = authority(AppMode::Agent, false, ApprovalMode::Suggest);
        let auto = authority(AppMode::Agent, false, ApprovalMode::Auto);
        let full_access = authority(AppMode::Agent, true, ApprovalMode::Bypass);
        let never = authority(AppMode::Agent, false, ApprovalMode::Never);

        // Session denial wins over everything, including full access.
        assert_eq!(
            resolve_approval_request_disposition(&full_access, true, true, false),
            ApprovalRequestDisposition::AutoDenySessionDenied
        );
        // Forced hold under full access fails closed instead of auto-approving.
        assert_eq!(
            resolve_approval_request_disposition(&full_access, true, false, true),
            ApprovalRequestDisposition::AutoDenyFullAccessPolicyHold
        );
        // Full access and session grants auto-approve ordinary requests.
        assert_eq!(
            resolve_approval_request_disposition(&full_access, false, false, false),
            ApprovalRequestDisposition::AutoApprove
        );
        assert_eq!(
            resolve_approval_request_disposition(&ask, true, false, false),
            ApprovalRequestDisposition::AutoApprove
        );
        // A session grant still auto-approves under Never (legacy order), and
        // Never denies everything else promptable.
        assert_eq!(
            resolve_approval_request_disposition(&never, true, false, false),
            ApprovalRequestDisposition::AutoApprove
        );
        assert_eq!(
            resolve_approval_request_disposition(&never, false, false, false),
            ApprovalRequestDisposition::AutoDenyNeverPosture
        );
        for force_prompt in [false, true] {
            assert_eq!(
                resolve_approval_request_disposition(&auto, false, false, force_prompt),
                ApprovalRequestDisposition::AutoDenyAutoReview
            );
        }
        // Ask posture with no grant opens the modal.
        assert_eq!(
            resolve_approval_request_disposition(&ask, false, false, false),
            ApprovalRequestDisposition::Prompt
        );
    }
}