| 1 | //! Turn authority and mode/posture policy projections. |
| 2 | //! |
| 3 | //! Keep mode, approval, shell, sandbox, trust, and input provenance decisions |
| 4 | //! in one place so prompt metadata, tool catalogs, and runtime gates cannot |
| 5 | //! drift independently. |
| 6 | |
| 7 | pub mod auto_review; |
| 8 | pub mod grants; |
| 9 | pub mod persistent_rules; |
| 10 | pub mod risk; |
| 11 | |
| 12 | pub use risk::{RiskLevel, classify_risk}; |
| 13 | |
| 14 | use std::ffi::OsStr; |
| 15 | use std::path::{Component, Path, PathBuf}; |
| 16 | |
| 17 | use crate::tools::spec::{ApprovalRequirement, normalize_path}; |
| 18 | use codewhale_agent_contract::worker_profile::ShellPolicy; |
| 19 | use codewhale_config::AppMode; |
| 20 | use codewhale_execpolicy::ApprovalMode; |
| 21 | use codewhale_execpolicy::canonical_action::canonical_action_alias; |
| 22 | use codewhale_sandbox::SandboxPolicy; |
| 23 | use codewhale_tools::names::is_tool_search_tool; |
| 24 | use serde_json::Value; |
| 25 | |
| 26 | use super::ops::UserInputProvenance; |
| 27 | |
| 28 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 29 | pub enum RunOrigin { |
| 30 | Interactive, |
| 31 | Headless, |
| 32 | Background, |
| 33 | } |
| 34 | |
| 35 | impl RunOrigin { |
| 36 | #[must_use] |
| 37 | pub fn as_str(self) -> &'static str { |
| 38 | match self { |
| 39 | Self::Interactive => "interactive", |
| 40 | Self::Headless => "headless", |
| 41 | Self::Background => "background", |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | /// Durable Agent-era permission baseline that Plan/YOLO restore to (#3386). |
| 47 | /// |
| 48 | /// Mode cycling used to be tangled with permission policy: each mode mutated |
| 49 | /// `allow_shell`/`trust_mode`/`approval_mode` directly and ad-hoc snapshots |
| 50 | /// tried to put things back on exit. Instead, keep one canonical baseline: the |
| 51 | /// permission surface the user has chosen for Agent mode. |
| 52 | #[derive(Debug, Clone, Copy)] |
| 53 | pub struct ModeSessionPrefs { |
| 54 | pub agent_allow_shell: bool, |
| 55 | pub agent_trust_mode: bool, |
| 56 | pub agent_approval_mode: ApprovalMode, |
| 57 | } |
| 58 | |
| 59 | /// The permission policy a given [`AppMode`] resolves to (#3386). |
| 60 | #[derive(Debug, Clone, Copy)] |
| 61 | pub struct EffectiveModePolicy { |
| 62 | pub mode: AppMode, |
| 63 | pub allow_shell: bool, |
| 64 | pub trust_mode: bool, |
| 65 | pub approval_mode: ApprovalMode, |
| 66 | } |
| 67 | |
| 68 | /// Resolve a mode's effective permission policy from the durable Agent baseline. |
| 69 | /// |
| 70 | /// This is the single source of truth for the mode/permission table: |
| 71 | /// - `Plan` -> read-only: no shell, no trust, `Suggest` approvals. |
| 72 | /// - `Agent` -> the user's durable baseline (`prefs`). |
| 73 | /// |
| 74 | /// The legacy YOLO spelling resolves to Agent plus a `Bypass` approval |
| 75 | /// posture before it reaches this table; modes no longer carry permission. |
| 76 | #[must_use] |
| 77 | pub fn base_policy_for_mode(mode: AppMode, prefs: &ModeSessionPrefs) -> EffectiveModePolicy { |
| 78 | match mode { |
| 79 | AppMode::Plan => EffectiveModePolicy { |
| 80 | mode, |
| 81 | allow_shell: false, |
| 82 | trust_mode: false, |
| 83 | approval_mode: ApprovalMode::Suggest, |
| 84 | }, |
| 85 | AppMode::Agent => EffectiveModePolicy { |
| 86 | mode, |
| 87 | allow_shell: prefs.agent_allow_shell, |
| 88 | trust_mode: prefs.agent_trust_mode, |
| 89 | approval_mode: prefs.agent_approval_mode, |
| 90 | }, |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// Why runtime policy narrowed the authority a turn was asked to run with. |
| 95 | /// |
| 96 | /// One variant per narrowing site. Adding a site means adding a variant, which |
| 97 | /// is the mechanism that makes "no silent effective mode change" enforceable |
| 98 | /// rather than aspirational (#3947). |
| 99 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 100 | pub enum PolicyNarrowingReason { |
| 101 | /// Input arrived from a provenance that cannot inherit standing |
| 102 | /// auto-approval authority (sub-agent handoffs, restored checkpoints). |
| 103 | NonAuthoritativeProvenance, |
| 104 | } |
| 105 | |
| 106 | impl PolicyNarrowingReason { |
| 107 | /// Stable machine-readable identifier. Shared by the model-visible |
| 108 | /// metadata line and doctor output so the two cannot drift. |
| 109 | pub fn as_str(self) -> &'static str { |
| 110 | match self { |
| 111 | Self::NonAuthoritativeProvenance => "non_authoritative_provenance", |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | /// A structured record of one authority narrowing. |
| 117 | /// |
| 118 | /// Before this existed, narrowing produced only a free-text UI status line: |
| 119 | /// the model saw the narrowed posture but never learned it had been narrowed |
| 120 | /// or why, and doctor could not report it at all. Every consumer now renders |
| 121 | /// from this one value, so the UI status, the `<turn_meta>` line, and doctor |
| 122 | /// necessarily agree. |
| 123 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 124 | pub struct PolicyNarrowingEvent { |
| 125 | reason: PolicyNarrowingReason, |
| 126 | /// Mode before narrowing, and after, as setting strings. |
| 127 | from_mode: &'static str, |
| 128 | to_mode: &'static str, |
| 129 | /// Permission posture before narrowing, and after. |
| 130 | from_approval: ApprovalMode, |
| 131 | to_approval: ApprovalMode, |
| 132 | /// Human-readable cause, e.g. the provenance that could not inherit. |
| 133 | detail: String, |
| 134 | } |
| 135 | |
| 136 | impl PolicyNarrowingEvent { |
| 137 | pub fn reason(&self) -> PolicyNarrowingReason { |
| 138 | self.reason |
| 139 | } |
| 140 | |
| 141 | /// The single user-facing sentence. The TUI status line renders exactly |
| 142 | /// this, and the model-visible metadata carries the same string. |
| 143 | pub fn message(&self) -> String { |
| 144 | match self.reason { |
| 145 | PolicyNarrowingReason::NonAuthoritativeProvenance => format!( |
| 146 | "Input provenance '{}' cannot inherit standing auto-approval authority; continuing with approvals required.", |
| 147 | self.detail |
| 148 | ), |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | /// Compact `from -> to` summary for doctor and debug surfaces. |
| 153 | pub fn transition(&self) -> String { |
| 154 | format!( |
| 155 | "{} ({}) -> {} ({})", |
| 156 | self.from_mode, |
| 157 | self.from_approval.permission_chip_label(), |
| 158 | self.to_mode, |
| 159 | self.to_approval.permission_chip_label(), |
| 160 | ) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | /// Effective authority for one engine turn after provenance narrowing. |
| 165 | #[derive(Debug, Clone)] |
| 166 | pub struct TurnAuthority { |
| 167 | pub mode: AppMode, |
| 168 | pub allow_shell: bool, |
| 169 | pub trust_mode: bool, |
| 170 | pub auto_approve: bool, |
| 171 | pub approval_mode: ApprovalMode, |
| 172 | run_origin: RunOrigin, |
| 173 | owner_present: bool, |
| 174 | /// Structured record of any narrowing applied to this turn (#3947). The |
| 175 | /// UI status line, `<turn_meta>`, and doctor all render from here, so a |
| 176 | /// narrowing that reaches one surface reaches all of them. |
| 177 | pub narrowing: Option<PolicyNarrowingEvent>, |
| 178 | } |
| 179 | |
| 180 | impl TurnAuthority { |
| 181 | /// The user-facing status sentence for this turn's narrowing, if any. |
| 182 | pub fn status(&self) -> Option<String> { |
| 183 | self.narrowing.as_ref().map(PolicyNarrowingEvent::message) |
| 184 | } |
| 185 | |
| 186 | #[must_use] |
| 187 | pub const fn run_origin(&self) -> RunOrigin { |
| 188 | self.run_origin |
| 189 | } |
| 190 | |
| 191 | #[must_use] |
| 192 | pub const fn owner_present(&self) -> bool { |
| 193 | self.owner_present |
| 194 | } |
| 195 | |
| 196 | #[must_use] |
| 197 | pub fn from_effective_fields( |
| 198 | mode: AppMode, |
| 199 | allow_shell: bool, |
| 200 | trust_mode: bool, |
| 201 | auto_approve: bool, |
| 202 | approval_mode: ApprovalMode, |
| 203 | ) -> Self { |
| 204 | Self { |
| 205 | mode, |
| 206 | allow_shell, |
| 207 | trust_mode, |
| 208 | auto_approve, |
| 209 | approval_mode, |
| 210 | run_origin: RunOrigin::Background, |
| 211 | owner_present: false, |
| 212 | narrowing: None, |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | #[must_use] |
| 217 | pub fn for_tui_surface( |
| 218 | mode: AppMode, |
| 219 | allow_shell: bool, |
| 220 | trust_mode: bool, |
| 221 | auto_approve: bool, |
| 222 | approval_mode: ApprovalMode, |
| 223 | ) -> Self { |
| 224 | Self::from_effective_fields(mode, allow_shell, trust_mode, auto_approve, approval_mode) |
| 225 | .with_rust_origin(RunOrigin::Interactive, true) |
| 226 | } |
| 227 | |
| 228 | #[must_use] |
| 229 | pub(crate) fn with_rust_origin( |
| 230 | mut self, |
| 231 | run_origin: RunOrigin, |
| 232 | owner_surface_attached: bool, |
| 233 | ) -> Self { |
| 234 | self.run_origin = run_origin; |
| 235 | self.owner_present = run_origin == RunOrigin::Interactive && owner_surface_attached; |
| 236 | self |
| 237 | } |
| 238 | |
| 239 | #[must_use] |
| 240 | pub fn approval_mode_for_session(&self) -> ApprovalMode { |
| 241 | agent_approval_mode_for_turn(self.auto_approve, self.approval_mode) |
| 242 | } |
| 243 | |
| 244 | /// Authority for the per-tool approval gate, folded from the legacy |
| 245 | /// session `auto_approve` bit so [`resolve_tool_permission`] observes the |
| 246 | /// same effective posture the old boolean helpers encoded: a set bit is |
| 247 | /// the Full Access posture (Bypass), a cleared bit is an ordinary Ask |
| 248 | /// turn. The engine's `Never` denial deliberately stays at the UI layer, |
| 249 | /// so this constructor never produces a `Never` posture. |
| 250 | #[must_use] |
| 251 | pub fn for_tool_approval_decision(auto_approve: bool) -> Self { |
| 252 | Self::from_effective_fields( |
| 253 | AppMode::Agent, |
| 254 | true, |
| 255 | false, |
| 256 | auto_approve, |
| 257 | ApprovalMode::from_auto_approve(auto_approve), |
| 258 | ) |
| 259 | } |
| 260 | |
| 261 | #[must_use] |
| 262 | pub fn shell_policy(&self) -> ShellPolicy { |
| 263 | shell_policy_for_mode(self.mode, self.allow_shell) |
| 264 | } |
| 265 | |
| 266 | #[must_use] |
| 267 | pub fn sandbox_policy( |
| 268 | &self, |
| 269 | workspace: &Path, |
| 270 | configured_mode: Option<&str>, |
| 271 | network_access: SandboxNetworkAccess, |
| 272 | ) -> SandboxPolicy { |
| 273 | sandbox_policy_for_turn( |
| 274 | self.mode, |
| 275 | self.approval_mode_for_session(), |
| 276 | configured_mode, |
| 277 | workspace, |
| 278 | network_access, |
| 279 | ) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | #[must_use] |
| 284 | pub fn effective_input_policy( |
| 285 | provenance: UserInputProvenance, |
| 286 | requested_mode: AppMode, |
| 287 | _content: &str, |
| 288 | allow_shell: bool, |
| 289 | trust_mode: bool, |
| 290 | auto_approve: bool, |
| 291 | approval_mode: ApprovalMode, |
| 292 | ) -> TurnAuthority { |
| 293 | let mode = requested_mode; |
| 294 | let mut trust_mode = trust_mode; |
| 295 | let mut auto_approve = auto_approve; |
| 296 | let mut approval_mode = approval_mode; |
| 297 | let mut narrowing = None; |
| 298 | |
| 299 | if !provenance_can_inherit_standing_auto_authority(provenance) { |
| 300 | let from_mode = mode; |
| 301 | let from_approval = approval_mode; |
| 302 | let had_auto_authority = trust_mode |
| 303 | || auto_approve |
| 304 | || matches!( |
| 305 | approval_mode, |
| 306 | ApprovalMode::Bypass | ApprovalMode::AcceptEdits |
| 307 | ); |
| 308 | trust_mode = false; |
| 309 | auto_approve = false; |
| 310 | if matches!( |
| 311 | approval_mode, |
| 312 | ApprovalMode::Auto | ApprovalMode::Bypass | ApprovalMode::AcceptEdits |
| 313 | ) { |
| 314 | approval_mode = ApprovalMode::Suggest; |
| 315 | } |
| 316 | if had_auto_authority { |
| 317 | // Record the transition, not just a sentence about it: the same |
| 318 | // value drives the UI status, `<turn_meta>`, and doctor (#3947). |
| 319 | narrowing = Some(PolicyNarrowingEvent { |
| 320 | reason: PolicyNarrowingReason::NonAuthoritativeProvenance, |
| 321 | from_mode: from_mode.as_setting(), |
| 322 | to_mode: mode.as_setting(), |
| 323 | from_approval, |
| 324 | to_approval: approval_mode, |
| 325 | detail: provenance.as_str().to_string(), |
| 326 | }); |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | // The named permission posture is authoritative. Normalize legacy or |
| 331 | // host inputs that carry `Bypass` with a stale false auto-approve bit so |
| 332 | // every engine surface observes the same Full Access contract. |
| 333 | if approval_mode == ApprovalMode::Bypass { |
| 334 | auto_approve = true; |
| 335 | } |
| 336 | |
| 337 | TurnAuthority { |
| 338 | mode, |
| 339 | allow_shell, |
| 340 | trust_mode, |
| 341 | auto_approve, |
| 342 | approval_mode, |
| 343 | run_origin: RunOrigin::Background, |
| 344 | owner_present: false, |
| 345 | narrowing, |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | #[must_use] |
| 350 | pub fn provenance_can_inherit_standing_auto_authority(provenance: UserInputProvenance) -> bool { |
| 351 | matches!( |
| 352 | provenance, |
| 353 | UserInputProvenance::ExternalUser |
| 354 | | UserInputProvenance::Runtime |
| 355 | | UserInputProvenance::GoalContinuation |
| 356 | | UserInputProvenance::SubAgentHandoff |
| 357 | ) |
| 358 | } |
| 359 | |
| 360 | #[must_use] |
| 361 | pub fn agent_approval_mode_for_turn( |
| 362 | auto_approve: bool, |
| 363 | approval_mode: ApprovalMode, |
| 364 | ) -> ApprovalMode { |
| 365 | if auto_approve { |
| 366 | ApprovalMode::Bypass |
| 367 | } else { |
| 368 | approval_mode |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | /// Resolve the filesystem boundary for one turn. |
| 373 | /// |
| 374 | /// Permission posture and filesystem scope are separate controls, but the |
| 375 | /// named Full Access posture must have a truthful default: outside Plan it |
| 376 | /// disables Codewhale's own sandbox, matching the product meaning of the |
| 377 | /// name. An explicit effective sandbox setting may still *tighten* that |
| 378 | /// default. It can never loosen Plan, Ask, or Auto-Review. |
| 379 | #[must_use] |
| 380 | pub fn sandbox_policy_for_turn( |
| 381 | mode: AppMode, |
| 382 | approval_mode: ApprovalMode, |
| 383 | configured_mode: Option<&str>, |
| 384 | workspace: &Path, |
| 385 | network_access: SandboxNetworkAccess, |
| 386 | ) -> SandboxPolicy { |
| 387 | let default = if mode == AppMode::Plan { |
| 388 | SandboxPolicy::read_only() |
| 389 | } else if approval_mode.agent_baseline_sandbox_mode() |
| 390 | == SandboxPolicy::DangerFullAccess.config_value() |
| 391 | { |
| 392 | SandboxPolicy::DangerFullAccess |
| 393 | } else { |
| 394 | workspace_write_policy(workspace, network_access) |
| 395 | }; |
| 396 | |
| 397 | // The effective Config has already applied managed/project precedence. |
| 398 | // Only stricter scopes clamp the posture-derived default: a configured |
| 399 | // danger-full-access value must not silently loosen Ask or Auto-Review. |
| 400 | match (default, configured_mode) { |
| 401 | (SandboxPolicy::ReadOnly { .. }, _) | (_, Some("read-only")) => SandboxPolicy::read_only(), |
| 402 | (SandboxPolicy::DangerFullAccess, Some("workspace-write")) => { |
| 403 | workspace_write_policy(workspace, network_access) |
| 404 | } |
| 405 | (SandboxPolicy::DangerFullAccess, Some("external-sandbox")) => { |
| 406 | SandboxPolicy::ExternalSandbox { |
| 407 | network_access: network_access.is_allowed(), |
| 408 | } |
| 409 | } |
| 410 | (policy, _) => policy, |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | /// Whether a sandboxed turn may open outbound connections. |
| 415 | /// |
| 416 | /// Typed rather than a bare `bool` so the two call-site meanings — "the user |
| 417 | /// asked for network" and "some caller passed true" — cannot be transposed |
| 418 | /// silently, and so the default is spelled at the type instead of at each of |
| 419 | /// the seven resolver call sites. |
| 420 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 421 | pub enum SandboxNetworkAccess { |
| 422 | /// No outbound network inside the sandbox. Editing the workspace does not |
| 423 | /// imply reaching the internet. |
| 424 | #[default] |
| 425 | Restricted, |
| 426 | /// Outbound network explicitly granted by config, policy, or an approved |
| 427 | /// elevation. |
| 428 | Allowed, |
| 429 | } |
| 430 | |
| 431 | impl SandboxNetworkAccess { |
| 432 | #[must_use] |
| 433 | pub fn from_config(configured: Option<bool>) -> Self { |
| 434 | if configured.unwrap_or(false) { |
| 435 | Self::Allowed |
| 436 | } else { |
| 437 | Self::Restricted |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | #[must_use] |
| 442 | pub fn is_allowed(self) -> bool { |
| 443 | matches!(self, Self::Allowed) |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | fn workspace_write_policy(workspace: &Path, network_access: SandboxNetworkAccess) -> SandboxPolicy { |
| 448 | SandboxPolicy::WorkspaceWrite { |
| 449 | writable_roots: vec![workspace.to_path_buf()], |
| 450 | network_access: network_access.is_allowed(), |
| 451 | exclude_tmpdir: false, |
| 452 | exclude_slash_tmp: false, |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | /// Resolve the effective shell policy for a turn from legacy shell opt-in plus mode. |
| 457 | #[must_use] |
| 458 | pub fn shell_policy_for_mode(mode: AppMode, allow_shell: bool) -> ShellPolicy { |
| 459 | if !allow_shell { |
| 460 | return ShellPolicy::None; |
| 461 | } |
| 462 | match mode { |
| 463 | AppMode::Plan => ShellPolicy::None, |
| 464 | AppMode::Agent => ShellPolicy::Full, |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | /// Per-tool permission decision from the unified resolver (#4412). |
| 469 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 470 | pub enum ToolPermission { |
| 471 | /// Tool executes without any approval prompt. |
| 472 | Allow, |
| 473 | /// Tool requires user approval before execution. |
| 474 | Prompt, |
| 475 | /// Tool is denied without a prompt (approval_mode=Never). |
| 476 | Deny, |
| 477 | } |
| 478 | |
| 479 | /// Unified per-tool permission resolver (#4412). |
| 480 | /// |
| 481 | /// Consolidates the approval decision that was previously scattered across |
| 482 | /// `registered_tool_approval_required` (turn_loop), `app_auto_approve_enabled` |
| 483 | /// (ui.rs), and the `Never` short-circuit. One call site, one answer. |
| 484 | /// |
| 485 | /// The truth table mirrors the legacy helpers exactly: |
| 486 | /// - `Auto` tools always run — even under `Never`, which stays read-only |
| 487 | /// rather than dead. |
| 488 | /// - `Never` denies any tool that would otherwise prompt, but only when the |
| 489 | /// authority is not full-access shaped: a Bypass-shaped authority carrying |
| 490 | /// a stale `Never` enum still auto-approves, matching the legacy UI order |
| 491 | /// in which the full-access shortcut ran before the `Never` check. |
| 492 | /// - `Suggest` and `Required` are both bypassable by auto-approve authority |
| 493 | /// unless the tool is on the typed non-bypassable hold list |
| 494 | /// (`is_non_bypassable`), which always prompts. A generic `Required` tool |
| 495 | /// remains auto-approved in Full Access (#3866). |
| 496 | #[must_use] |
| 497 | pub fn resolve_tool_permission( |
| 498 | authority: &TurnAuthority, |
| 499 | requirement: ApprovalRequirement, |
| 500 | is_non_bypassable: bool, |
| 501 | ) -> ToolPermission { |
| 502 | if authority.approval_mode == ApprovalMode::Never |
| 503 | && requirement != ApprovalRequirement::Auto |
| 504 | && !authority.auto_approve |
| 505 | { |
| 506 | return ToolPermission::Deny; |
| 507 | } |
| 508 | match requirement { |
| 509 | ApprovalRequirement::Auto => ToolPermission::Allow, |
| 510 | ApprovalRequirement::Suggest | ApprovalRequirement::Required => { |
| 511 | if is_non_bypassable { |
| 512 | // Full Access already grants everything these calls can do — |
| 513 | // shell included — so a hold that cannot open its own |
| 514 | // approval modal auto-approves instead of stranding the call. |
| 515 | // #3866 blocked here through v0.9.6; reversed 2026-08-10. |
| 516 | return if authority.auto_approve { |
| 517 | ToolPermission::Allow |
| 518 | } else { |
| 519 | ToolPermission::Prompt |
| 520 | }; |
| 521 | } |
| 522 | if authority.auto_approve || authority.approval_mode == ApprovalMode::Bypass { |
| 523 | ToolPermission::Allow |
| 524 | } else { |
| 525 | ToolPermission::Prompt |
| 526 | } |
| 527 | } |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | /// Whether the session posture is the one the in-workspace write carve-out |
| 532 | /// (#5185) relaxes: Accept Edits (no auto-approve) in an Agent-family mode. |
| 533 | /// |
| 534 | /// Every other posture keeps its exact meaning: Ask asks before every edit, |
| 535 | /// Full Access already runs these calls, `Never` still denies them, |
| 536 | /// Auto-Review still fails unresolved holds closed, and Plan is read-only by |
| 537 | /// mode. |
| 538 | #[must_use] |
| 539 | pub fn write_carve_out_posture( |
| 540 | mode: AppMode, |
| 541 | approval_mode: ApprovalMode, |
| 542 | auto_approve: bool, |
| 543 | ) -> bool { |
| 544 | !auto_approve && matches!(mode, AppMode::Agent) && approval_mode == ApprovalMode::AcceptEdits |
| 545 | } |
| 546 | |
| 547 | /// Whether every target path of a file-write call qualifies for the |
| 548 | /// in-workspace write carve-out (#5185): the workspace is a git work tree, |
| 549 | /// each path resolves inside it, and none touches `.git` internals, runtime |
| 550 | /// state, or a sensitive file. |
| 551 | /// |
| 552 | /// The git work-tree marker is deliberate (the same shape as kimi-code's |
| 553 | /// `git-cwd-write-approve` policy): the carve-out exists because |
| 554 | /// version-controlled edits stay reviewable and recoverable, so a workspace |
| 555 | /// without git keeps the modal. |
| 556 | #[must_use] |
| 557 | pub fn paths_within_workspace_write_carve_out(workspace: &Path, paths: &[String]) -> bool { |
| 558 | if paths.is_empty() || !workspace_is_git_work_tree(workspace) { |
| 559 | return false; |
| 560 | } |
| 561 | let Ok(workspace_canonical) = workspace.canonicalize() else { |
| 562 | return false; |
| 563 | }; |
| 564 | paths |
| 565 | .iter() |
| 566 | .all(|raw| carve_out_target_allowed(workspace, &workspace_canonical, raw)) |
| 567 | } |
| 568 | |
| 569 | /// The git work-tree marker the carve-out keys on. `.git` may be a directory |
| 570 | /// (normal checkout) or a file (worktree or submodule); either counts. |
| 571 | pub(crate) fn workspace_is_git_work_tree(workspace: &Path) -> bool { |
| 572 | workspace.join(".git").symlink_metadata().is_ok() |
| 573 | } |
| 574 | |
| 575 | pub(crate) fn normalize_auto_review_segment(raw: &str) -> String { |
| 576 | let bytes = raw.as_bytes(); |
| 577 | let without_drive = if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' { |
| 578 | &raw[2..] |
| 579 | } else { |
| 580 | raw |
| 581 | }; |
| 582 | let trimmed = without_drive.trim_end_matches(['.', ' ']); |
| 583 | let without_stream = match trimmed.split_once(':') { |
| 584 | Some((head, _)) => head, |
| 585 | None => trimmed, |
| 586 | }; |
| 587 | without_stream |
| 588 | .trim_end_matches(['.', ' ']) |
| 589 | .to_ascii_lowercase() |
| 590 | } |
| 591 | |
| 592 | fn clean_8_3_stem(base: &str) -> (String, String) { |
| 593 | let with_dash: String = base |
| 594 | .trim_start_matches(['.', ' ']) |
| 595 | .chars() |
| 596 | .filter(|ch| ch.is_ascii_alphanumeric() || *ch == '_' || *ch == '-') |
| 597 | .map(|ch| ch.to_ascii_lowercase()) |
| 598 | .collect(); |
| 599 | let without_dash: String = with_dash.chars().filter(|ch| *ch != '-').collect(); |
| 600 | (with_dash, without_dash) |
| 601 | } |
| 602 | |
| 603 | pub(crate) fn parse_8_3_alias(norm: &str) -> Option<(&str, &str, &str)> { |
| 604 | let first_len = norm.chars().next()?.len_utf8(); |
| 605 | let ext_dot = norm[first_len..].rfind('.').map(|idx| first_len + idx); |
| 606 | let (base, ext) = match ext_dot { |
| 607 | Some(dot) => (&norm[..dot], &norm[dot + 1..]), |
| 608 | None => (norm, ""), |
| 609 | }; |
| 610 | let base = base.trim_start_matches('.'); |
| 611 | let (prefix, num) = base.rsplit_once('~')?; |
| 612 | if prefix.is_empty() |
| 613 | || num.is_empty() |
| 614 | || num.len() > 2 |
| 615 | || !num.bytes().all(|b| b.is_ascii_digit()) |
| 616 | || !num.bytes().any(|b| b != b'0') |
| 617 | { |
| 618 | return None; |
| 619 | } |
| 620 | Some((prefix, num, ext)) |
| 621 | } |
| 622 | |
| 623 | pub(crate) fn is_credential_8_3_prefix(prefix: &str) -> bool { |
| 624 | matches!( |
| 625 | prefix, |
| 626 | "env" |
| 627 | | "creden" |
| 628 | | "crede" |
| 629 | | "id_rsa" |
| 630 | | "idrsa" |
| 631 | | "id_dsa" |
| 632 | | "iddsa" |
| 633 | | "id_ecd" |
| 634 | | "idecd" |
| 635 | | "id_ed2" |
| 636 | | "ided2" |
| 637 | ) |
| 638 | } |
| 639 | |
| 640 | pub(crate) fn auto_review_segment_matches(raw: &str, target: &str) -> bool { |
| 641 | let c = normalize_auto_review_segment(raw); |
| 642 | let t = target.to_ascii_lowercase(); |
| 643 | if c.is_empty() { |
| 644 | return false; |
| 645 | } |
| 646 | if c == t { |
| 647 | return true; |
| 648 | } |
| 649 | if !t.starts_with('.') |
| 650 | && let Some((tb, te)) = t.rsplit_once('.') |
| 651 | && !tb.is_empty() |
| 652 | && te.len() > 3 |
| 653 | && let Some((cb, ce)) = c.rsplit_once('.') |
| 654 | && cb == tb |
| 655 | && te.get(..3).is_some_and(|sub| ce == sub) |
| 656 | { |
| 657 | return true; |
| 658 | } |
| 659 | let Some((c_prefix, c_num, c_ext)) = parse_8_3_alias(&c) else { |
| 660 | return false; |
| 661 | }; |
| 662 | let (tb, te) = if t.starts_with('.') && !t[1..].contains('.') { |
| 663 | (&t[1..], "") |
| 664 | } else if let Some((tb, te)) = t.rsplit_once('.') { |
| 665 | (tb, te) |
| 666 | } else { |
| 667 | (t.as_str(), "") |
| 668 | }; |
| 669 | let max_len = if c_num.len() == 1 { 6 } else { 5 }; |
| 670 | let prefix_matches = |s: &str| -> bool { |
| 671 | if s.is_empty() || c_prefix.len() > max_len { |
| 672 | return false; |
| 673 | } |
| 674 | let min_len = s.len().min(max_len).saturating_sub(2).max(s.len().min(3)); |
| 675 | c_prefix.len() >= min_len && s.starts_with(c_prefix) |
| 676 | }; |
| 677 | let ext_matches = if te.is_empty() { |
| 678 | c_ext.is_empty() |
| 679 | } else { |
| 680 | c_ext == te || te.get(..3).is_some_and(|sub| c_ext == sub) |
| 681 | }; |
| 682 | if ext_matches { |
| 683 | let (s1, s2) = clean_8_3_stem(tb); |
| 684 | if prefix_matches(&s1) || prefix_matches(&s2) { |
| 685 | return true; |
| 686 | } |
| 687 | } |
| 688 | if c_ext.is_empty() && !te.is_empty() { |
| 689 | let combined = format!("{tb}{te}"); |
| 690 | let (c1, c2) = clean_8_3_stem(&combined); |
| 691 | if prefix_matches(&c1) || prefix_matches(&c2) { |
| 692 | return true; |
| 693 | } |
| 694 | } |
| 695 | false |
| 696 | } |
| 697 | |
| 698 | pub(crate) fn is_auto_review_excluded_or_credential_segment(raw: &str) -> bool { |
| 699 | let c = normalize_auto_review_segment(raw); |
| 700 | if c.is_empty() { |
| 701 | return false; |
| 702 | } |
| 703 | if is_carve_out_excluded_name(&c) { |
| 704 | return true; |
| 705 | } |
| 706 | if [ |
| 707 | ".git", |
| 708 | ".codewhale", |
| 709 | ".ssh", |
| 710 | ".aws", |
| 711 | ".gnupg", |
| 712 | ".kube", |
| 713 | ".docker", |
| 714 | ".netrc", |
| 715 | ".npmrc", |
| 716 | ".pypirc", |
| 717 | ".git-credentials", |
| 718 | ] |
| 719 | .iter() |
| 720 | .any(|target| auto_review_segment_matches(raw, target)) |
| 721 | { |
| 722 | return true; |
| 723 | } |
| 724 | parse_8_3_alias(&c).is_some_and(|(c_prefix, _, _)| is_credential_8_3_prefix(c_prefix)) |
| 725 | } |
| 726 | |
| 727 | pub(crate) fn is_auto_review_protected_segments(segments: &[String]) -> bool { |
| 728 | const SINGLE_PROTECTED: &[&str] = &[ |
| 729 | ".vscode", |
| 730 | ".claude", |
| 731 | ".mcp.json", |
| 732 | ".claude.json", |
| 733 | ".gitconfig", |
| 734 | ".bashrc", |
| 735 | ".zshrc", |
| 736 | ".profile", |
| 737 | ".bash_profile", |
| 738 | ".zprofile", |
| 739 | ".zshenv", |
| 740 | ".bash_login", |
| 741 | ]; |
| 742 | const MULTI_PROTECTED: &[&[&str]] = &[ |
| 743 | &[".config", "gh", "hosts.yml"], |
| 744 | &[".github", "workflows"], |
| 745 | &["library", "launchagents"], |
| 746 | &[".config", "autostart"], |
| 747 | &[".cargo", "config.toml"], |
| 748 | &[".cargo", "config"], |
| 749 | &[".config", "fish", "config.fish"], |
| 750 | &[".config", "fish", "conf.d"], |
| 751 | &[".config", "systemd", "user"], |
| 752 | &["start menu", "programs", "startup"], |
| 753 | ]; |
| 754 | |
| 755 | if segments.iter().any(|seg| { |
| 756 | is_auto_review_excluded_or_credential_segment(seg) |
| 757 | || SINGLE_PROTECTED |
| 758 | .iter() |
| 759 | .any(|target| auto_review_segment_matches(seg, target)) |
| 760 | }) { |
| 761 | return true; |
| 762 | } |
| 763 | MULTI_PROTECTED.iter().any(|pattern| { |
| 764 | segments.len() >= pattern.len() |
| 765 | && segments.windows(pattern.len()).any(|window| { |
| 766 | window |
| 767 | .iter() |
| 768 | .zip(pattern.iter()) |
| 769 | .all(|(seg, target)| auto_review_segment_matches(seg, target)) |
| 770 | }) |
| 771 | }) |
| 772 | } |
| 773 | |
| 774 | fn path_normal_segments(path: &Path) -> Vec<String> { |
| 775 | path.components() |
| 776 | .filter_map(|comp| match comp { |
| 777 | Component::Normal(part) => Some(part.to_string_lossy().into_owned()), |
| 778 | _ => None, |
| 779 | }) |
| 780 | .collect() |
| 781 | } |
| 782 | |
| 783 | pub(crate) fn expand_home_prefix(raw: &str, home: Option<&Path>) -> PathBuf { |
| 784 | let trimmed = raw.trim(); |
| 785 | if let Some(home_dir) = home { |
| 786 | if trimmed == "~" { |
| 787 | return home_dir.to_path_buf(); |
| 788 | } |
| 789 | if let Some(rest) = trimmed |
| 790 | .strip_prefix("~/") |
| 791 | .or_else(|| trimmed.strip_prefix("~\\")) |
| 792 | { |
| 793 | return home_dir.join(rest); |
| 794 | } |
| 795 | if trimmed == "$HOME" || trimmed == "${HOME}" { |
| 796 | return home_dir.to_path_buf(); |
| 797 | } |
| 798 | if let Some(rest) = trimmed |
| 799 | .strip_prefix("$HOME/") |
| 800 | .or_else(|| trimmed.strip_prefix("$HOME\\")) |
| 801 | .or_else(|| trimmed.strip_prefix("${HOME}/")) |
| 802 | .or_else(|| trimmed.strip_prefix("${HOME}\\")) |
| 803 | { |
| 804 | return home_dir.join(rest); |
| 805 | } |
| 806 | } |
| 807 | PathBuf::from(trimmed) |
| 808 | } |
| 809 | |
| 810 | pub(crate) fn auto_review_path_is_protected( |
| 811 | candidate: &Path, |
| 812 | workspace: Option<&Path>, |
| 813 | home: Option<&Path>, |
| 814 | ) -> bool { |
| 815 | let joined = match workspace { |
| 816 | Some(ws) if !candidate.is_absolute() => ws.join(candidate), |
| 817 | _ => candidate.to_path_buf(), |
| 818 | }; |
| 819 | let lexical = normalize_path(&joined); |
| 820 | let check_relative_from_base = |path: &Path, base: &Path| -> Option<bool> { |
| 821 | let lex_base = normalize_path(base); |
| 822 | let rel = path.strip_prefix(&lex_base).ok()?; |
| 823 | let segs = path_normal_segments(rel); |
| 824 | Some(is_auto_review_protected_segments(&segs)) |
| 825 | }; |
| 826 | |
| 827 | let lexical_protected = if let Some(ws) = workspace { |
| 828 | if let Some(matched) = check_relative_from_base(&lexical, ws) { |
| 829 | matched |
| 830 | } else if let Some(home_dir) = home { |
| 831 | check_relative_from_base(&lexical, home_dir).unwrap_or_else(|| { |
| 832 | is_auto_review_protected_segments(&path_normal_segments(&lexical)) |
| 833 | }) |
| 834 | } else { |
| 835 | is_auto_review_protected_segments(&path_normal_segments(&lexical)) |
| 836 | } |
| 837 | } else if let Some(home_dir) = home { |
| 838 | check_relative_from_base(&lexical, home_dir) |
| 839 | .unwrap_or_else(|| is_auto_review_protected_segments(&path_normal_segments(&lexical))) |
| 840 | } else { |
| 841 | is_auto_review_protected_segments(&path_normal_segments(&lexical)) |
| 842 | }; |
| 843 | if lexical_protected { |
| 844 | return true; |
| 845 | } |
| 846 | |
| 847 | let Some(resolved) = resolve_deepest_existing(&joined) else { |
| 848 | return false; |
| 849 | }; |
| 850 | if let Some(ws) = workspace |
| 851 | && let Some(ws_resolved) = resolve_deepest_existing(ws) |
| 852 | && let Ok(rel) = resolved.strip_prefix(&ws_resolved) |
| 853 | { |
| 854 | return is_auto_review_protected_segments(&path_normal_segments(rel)); |
| 855 | } |
| 856 | if let Some(home_dir) = home |
| 857 | && let Some(home_resolved) = resolve_deepest_existing(home_dir) |
| 858 | && let Ok(rel) = resolved.strip_prefix(&home_resolved) |
| 859 | && is_auto_review_protected_segments(&path_normal_segments(rel)) |
| 860 | { |
| 861 | return true; |
| 862 | } |
| 863 | is_auto_review_protected_segments(&path_normal_segments(&resolved)) |
| 864 | } |
| 865 | |
| 866 | pub(crate) fn auto_review_workspace_is_safe_with_home( |
| 867 | workspace: &Path, |
| 868 | home: Option<&Path>, |
| 869 | ) -> bool { |
| 870 | if workspace.as_os_str().is_empty() { |
| 871 | return false; |
| 872 | } |
| 873 | let ws_canon = resolve_deepest_existing(workspace).unwrap_or_else(|| normalize_path(workspace)); |
| 874 | if ws_canon.parent().is_none() || normalize_path(workspace).parent().is_none() { |
| 875 | return false; |
| 876 | } |
| 877 | let home_canon = home.map(|h| resolve_deepest_existing(h).unwrap_or_else(|| normalize_path(h))); |
| 878 | if let Some(ref hc) = home_canon |
| 879 | && (hc == &ws_canon || hc.starts_with(&ws_canon)) |
| 880 | { |
| 881 | return false; |
| 882 | } |
| 883 | if let Some(h) = home { |
| 884 | let hl = normalize_path(h); |
| 885 | let wl = normalize_path(workspace); |
| 886 | if hl == wl || hl.starts_with(&wl) { |
| 887 | return false; |
| 888 | } |
| 889 | } |
| 890 | if codewhale_snapshot::repo::unsafe_workspace_snapshot_reason(workspace, home).is_some() { |
| 891 | return false; |
| 892 | } |
| 893 | if codewhale_snapshot::repo::unsafe_workspace_snapshot_reason(&ws_canon, home_canon.as_deref()) |
| 894 | .is_some() |
| 895 | { |
| 896 | return false; |
| 897 | } |
| 898 | true |
| 899 | } |
| 900 | |
| 901 | pub(crate) fn auto_review_write_targets_bounded_with_home( |
| 902 | workspace: &Path, |
| 903 | home: Option<&Path>, |
| 904 | snapshots_enabled: bool, |
| 905 | paths: &[String], |
| 906 | ) -> bool { |
| 907 | if paths.is_empty() || !auto_review_workspace_is_safe_with_home(workspace, home) { |
| 908 | return false; |
| 909 | } |
| 910 | if !workspace_is_git_work_tree(workspace) && !snapshots_enabled { |
| 911 | return false; |
| 912 | } |
| 913 | let Some(workspace_root) = resolve_deepest_existing(workspace) else { |
| 914 | return false; |
| 915 | }; |
| 916 | let lexical_root = normalize_path(workspace); |
| 917 | paths.iter().all(|raw| { |
| 918 | let candidate = expand_home_prefix(raw, home); |
| 919 | let joined = if candidate.is_absolute() { |
| 920 | candidate |
| 921 | } else { |
| 922 | workspace.join(&candidate) |
| 923 | }; |
| 924 | let lexical = normalize_path(&joined); |
| 925 | if !lexical.starts_with(&lexical_root) { |
| 926 | return false; |
| 927 | } |
| 928 | let Some(resolved) = resolve_deepest_existing(&joined) else { |
| 929 | return false; |
| 930 | }; |
| 931 | if !resolved.starts_with(&workspace_root) { |
| 932 | return false; |
| 933 | } |
| 934 | !auto_review_path_is_protected(&joined, Some(workspace), home) |
| 935 | }) |
| 936 | } |
| 937 | |
| 938 | /// Whether a file-write approval card should say that the folder has no git |
| 939 | /// repository: the posture is the one the carve-out (#5185) relaxes, the call |
| 940 | /// is a canonical file-write tool, and the workspace has no git work tree, so |
| 941 | /// the same edit would run without a card in a repository. |
| 942 | /// |
| 943 | /// Presentation only. The engine has already decided to ask; this never |
| 944 | /// opens, skips or answers a card. |
| 945 | #[must_use] |
| 946 | pub fn file_write_asks_without_git( |
| 947 | mode: AppMode, |
| 948 | approval_mode: ApprovalMode, |
| 949 | workspace: &Path, |
| 950 | tool_name: &str, |
| 951 | input: &Value, |
| 952 | ) -> bool { |
| 953 | write_carve_out_posture(mode, approval_mode, false) |
| 954 | && matches!( |
| 955 | canonical_action_alias(tool_name, input), |
| 956 | "write_file" | "edit_file" | "apply_patch" |
| 957 | ) |
| 958 | && !workspace_is_git_work_tree(workspace) |
| 959 | } |
| 960 | |
| 961 | fn carve_out_target_allowed(workspace: &Path, workspace_canonical: &Path, raw: &str) -> bool { |
| 962 | let raw = raw.trim(); |
| 963 | if raw.is_empty() { |
| 964 | return false; |
| 965 | } |
| 966 | let raw_path = Path::new(raw); |
| 967 | let candidate = if raw_path.is_absolute() { |
| 968 | raw_path.to_path_buf() |
| 969 | } else { |
| 970 | workspace.join(raw_path) |
| 971 | }; |
| 972 | // Lexical containment first: `..` escapes and absolute out-of-tree paths |
| 973 | // fail here without touching the filesystem. |
| 974 | let lexical = normalize_path(&candidate); |
| 975 | let workspace_lexical = normalize_path(workspace); |
| 976 | let workspace_canonical_lexical = normalize_path(workspace_canonical); |
| 977 | let Ok(relative) = lexical |
| 978 | .strip_prefix(&workspace_lexical) |
| 979 | .or_else(|_| lexical.strip_prefix(&workspace_canonical_lexical)) |
| 980 | else { |
| 981 | return false; |
| 982 | }; |
| 983 | if !carve_out_relative_path_allowed(relative) { |
| 984 | return false; |
| 985 | } |
| 986 | // Then symlink reality: resolve the deepest existing ancestor and |
| 987 | // require the real path to stay inside the real workspace and off the |
| 988 | // same exclusions (a symlink hop into `.git` or out of the tree fails). |
| 989 | let Some(resolved) = resolve_deepest_existing(&candidate) else { |
| 990 | return false; |
| 991 | }; |
| 992 | let Ok(resolved_relative) = resolved.strip_prefix(workspace_canonical) else { |
| 993 | return false; |
| 994 | }; |
| 995 | carve_out_relative_path_allowed(resolved_relative) |
| 996 | } |
| 997 | |
| 998 | /// Canonicalize the deepest existing ancestor of `candidate` and re-append |
| 999 | /// the not-yet-existing tail, so write targets that do not exist yet still |
| 1000 | /// get a real-path check. Shared crate-wide so the subagent write-claim lane |
| 1001 | /// resolves spellings through the same walk as the carve-out boundary and |
| 1002 | /// cannot drift from it on symlinked or partially-existing targets. |
| 1003 | pub(crate) fn resolve_deepest_existing(candidate: &Path) -> Option<PathBuf> { |
| 1004 | let mut ancestor = candidate; |
| 1005 | let mut suffix: Vec<&OsStr> = Vec::new(); |
| 1006 | loop { |
| 1007 | if let Ok(canonical) = ancestor.canonicalize() { |
| 1008 | let mut resolved = canonical; |
| 1009 | for part in suffix.iter().rev() { |
| 1010 | resolved.push(part); |
| 1011 | } |
| 1012 | return Some(resolved); |
| 1013 | } |
| 1014 | suffix.push(ancestor.file_name()?); |
| 1015 | ancestor = ancestor.parent()?; |
| 1016 | } |
| 1017 | } |
| 1018 | |
| 1019 | fn carve_out_relative_path_allowed(relative: &Path) -> bool { |
| 1020 | relative.components().all(|component| { |
| 1021 | let Component::Normal(part) = component else { |
| 1022 | return true; |
| 1023 | }; |
| 1024 | !is_carve_out_excluded_name(&part.to_string_lossy().to_ascii_lowercase()) |
| 1025 | }) |
| 1026 | } |
| 1027 | |
| 1028 | /// Names the carve-out never auto-allows, matched per path component: |
| 1029 | /// `.git` internals, runtime/project state, credential-bearing directories |
| 1030 | /// and files, and key material. |
| 1031 | fn is_carve_out_excluded_name(name: &str) -> bool { |
| 1032 | // The shared `.git` rule, so a Windows alias (`.git.`, `GIT~1`) is |
| 1033 | // excluded here exactly as the workspace file routes exclude it. |
| 1034 | // `.codewhale` holds session state plus MCP/hook configuration — editing |
| 1035 | // it changes what runs, so it keeps the modal. |
| 1036 | codewhale_util::git_metadata::is_git_metadata_name(OsStr::new(name)) |
| 1037 | || name == ".codewhale" |
| 1038 | || is_credential_file_name(name) |
| 1039 | } |
| 1040 | |
| 1041 | pub fn is_credential_file_name(name: &str) -> bool { |
| 1042 | // Credential-bearing directories. |
| 1043 | if matches!(name, ".ssh" | ".aws" | ".gnupg" | ".kube" | ".docker") { |
| 1044 | return true; |
| 1045 | } |
| 1046 | // Environment files and well-known credential stores. |
| 1047 | if name.starts_with(".env") |
| 1048 | || name == ".netrc" |
| 1049 | || name == ".npmrc" |
| 1050 | || name == ".pypirc" |
| 1051 | || name == ".git-credentials" |
| 1052 | || name == "credentials" |
| 1053 | || name.starts_with("credentials.") |
| 1054 | { |
| 1055 | return true; |
| 1056 | } |
| 1057 | // SSH private (and public) key material. |
| 1058 | if name.starts_with("id_rsa") |
| 1059 | || name.starts_with("id_dsa") |
| 1060 | || name.starts_with("id_ecdsa") |
| 1061 | || name.starts_with("id_ed25519") |
| 1062 | { |
| 1063 | return true; |
| 1064 | } |
| 1065 | // Key/certificate containers by extension. |
| 1066 | matches!( |
| 1067 | Path::new(name).extension().and_then(|ext| ext.to_str()), |
| 1068 | Some("pem" | "key" | "p12" | "pfx" | "jks" | "keystore") |
| 1069 | ) |
| 1070 | } |
| 1071 | |
| 1072 | /// Disposition for an approval request that reached the UI (#4412). |
| 1073 | /// |
| 1074 | /// The engine emits `ApprovalRequired` whenever its resolver answer was |
| 1075 | /// `Prompt`; the UI then disposes of that request — honoring session caches |
| 1076 | /// and posture races — through this single decision. |
| 1077 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1078 | pub enum ApprovalRequestDisposition { |
| 1079 | /// Session grant or full-access posture: approve without a modal. |
| 1080 | AutoApprove, |
| 1081 | /// The user already denied this approval key this session (#360). |
| 1082 | AutoDenySessionDenied, |
| 1083 | /// A forced (non-bypassable) policy hold arrived under a full-access |
| 1084 | /// posture that opens no modal: fail closed. |
| 1085 | AutoDenyFullAccessPolicyHold, |
| 1086 | /// Auto-Review runs autonomously when no owner surface is present or no |
| 1087 | /// forced prompt requires the person: unresolved non-forced holds fail |
| 1088 | /// closed instead of opening a user-approval modal. |
| 1089 | AutoDenyAutoReview, |
| 1090 | /// approval_mode=Never: deny without a modal. |
| 1091 | AutoDenyNeverPosture, |
| 1092 | /// Open the approval modal. |
| 1093 | Prompt, |
| 1094 | } |
| 1095 | |
| 1096 | /// Resolve how the UI disposes of one incoming approval request. |
| 1097 | /// |
| 1098 | /// `session_approved` / `session_denied` are the caller's lookups into the |
| 1099 | /// session approval caches (grouping key or tool name / exact approval key). |
| 1100 | /// The branch order: session denial, then Auto-Review (which prompts only when |
| 1101 | /// `approval_force_prompt && authority.owner_present()`, and otherwise fails |
| 1102 | /// closed), then the full-access policy-hold denial, then the `Never` denial — |
| 1103 | /// the live posture wins over any remembered grant (approvals J) — then |
| 1104 | /// auto-approval (full access or a session grant), and only finally a modal. |
| 1105 | /// Extension-origin, creator human-decision and search-consent forced calls |
| 1106 | /// reach that modal under Full Access and interactive Auto-Review with the |
| 1107 | /// owner present; no remembered grant can satisfy them. `approval_key` is a |
| 1108 | /// Rust-minted key, never an extension label or a claim supplied by the host. |
| 1109 | #[must_use] |
| 1110 | pub fn resolve_approval_request_disposition( |
| 1111 | authority: &TurnAuthority, |
| 1112 | session_approved: bool, |
| 1113 | session_denied: bool, |
| 1114 | approval_force_prompt: bool, |
| 1115 | approval_key: &str, |
| 1116 | ) -> ApprovalRequestDisposition { |
| 1117 | if session_denied { |
| 1118 | return ApprovalRequestDisposition::AutoDenySessionDenied; |
| 1119 | } |
| 1120 | if authority.approval_mode_for_session() == ApprovalMode::Auto { |
| 1121 | return if approval_force_prompt && authority.owner_present() { |
| 1122 | ApprovalRequestDisposition::Prompt |
| 1123 | } else { |
| 1124 | ApprovalRequestDisposition::AutoDenyAutoReview |
| 1125 | }; |
| 1126 | } |
| 1127 | // The request exists, so the engine already resolved Prompt for the tool |
| 1128 | // itself. What remains is the posture question: how does this authority |
| 1129 | // treat an ordinary promptable tool? |
| 1130 | let posture = resolve_tool_permission(authority, ApprovalRequirement::Suggest, false); |
| 1131 | if approval_force_prompt |
| 1132 | && !crate::tools::approval_cache::forces_full_access_prompt_for_key(approval_key) |
| 1133 | && posture == ToolPermission::Allow |
| 1134 | { |
| 1135 | return ApprovalRequestDisposition::AutoDenyFullAccessPolicyHold; |
| 1136 | } |
| 1137 | // The live posture wins over any remembered grant: a conversation grant |
| 1138 | // given under Ask never outlives a later switch to Never (approvals J). |
| 1139 | if posture == ToolPermission::Deny { |
| 1140 | return ApprovalRequestDisposition::AutoDenyNeverPosture; |
| 1141 | } |
| 1142 | if !approval_force_prompt && (posture == ToolPermission::Allow || session_approved) { |
| 1143 | return ApprovalRequestDisposition::AutoApprove; |
| 1144 | } |
| 1145 | ApprovalRequestDisposition::Prompt |
| 1146 | } |
| 1147 | |
| 1148 | /// Categorizes tools by cost/risk level. |
| 1149 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1150 | pub enum ToolCategory { |
| 1151 | /// Free, read-only operations (`list_dir`, `read_file`, todo_*) |
| 1152 | Safe, |
| 1153 | /// File modifications (`write_file`, `edit_file`) |
| 1154 | FileWrite, |
| 1155 | /// Shell execution (`exec_shell`) |
| 1156 | Shell, |
| 1157 | /// Network-oriented built-in tools |
| 1158 | Network, |
| 1159 | /// Read-only MCP discovery and resource access |
| 1160 | McpRead, |
| 1161 | /// MCP actions that may change remote state |
| 1162 | McpAction, |
| 1163 | /// Sub-agent lifecycle (`agent` start/status/peek/cancel); the child's |
| 1164 | /// own tool gates govern what it may actually do. |
| 1165 | Agent, |
| 1166 | /// Unknown or unclassified tool surface |
| 1167 | Unknown, |
| 1168 | } |
| 1169 | |
| 1170 | /// Get the category for a tool by name. |
| 1171 | pub fn get_tool_category(name: &str) -> ToolCategory { |
| 1172 | if name == "agent" || name == "workflow" { |
| 1173 | // Workflow is multi-agent orchestration; reuse Agent stakes/routing |
| 1174 | // and specialize the impact card via build_impact_summary (#4126). |
| 1175 | ToolCategory::Agent |
| 1176 | } else if matches!( |
| 1177 | name, |
| 1178 | "write" | "edit" | "write_file" | "edit_file" | "apply_patch" |
| 1179 | ) { |
| 1180 | ToolCategory::FileWrite |
| 1181 | } else if matches!( |
| 1182 | name, |
| 1183 | "web_run" | "web_search" | "fetch_url" | "wait_for_dev_server" | "registry_sync" |
| 1184 | ) { |
| 1185 | ToolCategory::Network |
| 1186 | } else if matches!( |
| 1187 | name, |
| 1188 | "bash" |
| 1189 | | "Bash" |
| 1190 | | "exec_shell" |
| 1191 | | "task_shell_start" |
| 1192 | | "task_shell_wait" |
| 1193 | | "exec_shell_wait" |
| 1194 | | "exec_shell_interact" |
| 1195 | | "exec_shell_cancel" |
| 1196 | | "exec_wait" |
| 1197 | | "exec_interact" |
| 1198 | ) { |
| 1199 | ToolCategory::Shell |
| 1200 | } else if name.starts_with("list_mcp_") |
| 1201 | || name.starts_with("read_mcp_") |
| 1202 | || name.starts_with("get_mcp_") |
| 1203 | { |
| 1204 | ToolCategory::McpRead |
| 1205 | } else if name.starts_with("mcp_") { |
| 1206 | ToolCategory::McpAction |
| 1207 | } else if matches!( |
| 1208 | name, |
| 1209 | "read" |
| 1210 | | "read_file" |
| 1211 | | "list_dir" |
| 1212 | | "work_update" |
| 1213 | | "todo_write" |
| 1214 | | "todo_read" |
| 1215 | | "checklist_write" |
| 1216 | | "update_plan" |
| 1217 | | "search" |
| 1218 | | "file_search" |
| 1219 | | "grep_files" |
| 1220 | | "git_status" |
| 1221 | | "git_diff" |
| 1222 | | "git_log" |
| 1223 | | "git_show" |
| 1224 | | "git_blame" |
| 1225 | | "git_commit_plan" |
| 1226 | | "git_review_scope" |
| 1227 | | "project" |
| 1228 | | "load_skill" |
| 1229 | | "handle_read" |
| 1230 | | "retrieve_tool_result" |
| 1231 | | "context_archive_search" |
| 1232 | | "session_search" |
| 1233 | | "memory_search" |
| 1234 | | "validate_data" |
| 1235 | | "tui_help" |
| 1236 | | "show_data" |
| 1237 | | "present" |
| 1238 | | "agents/list" |
| 1239 | | "agents/wait" |
| 1240 | | "task_list" |
| 1241 | | "task_read" |
| 1242 | | "pr_attempt_list" |
| 1243 | | "pr_attempt_read" |
| 1244 | | "automation_list" |
| 1245 | | "automation_read" |
| 1246 | ) || is_tool_search_tool(name) |
| 1247 | || name.starts_with("read_") |
| 1248 | || name.starts_with("list_") |
| 1249 | || name.starts_with("get_") |
| 1250 | { |
| 1251 | ToolCategory::Safe |
| 1252 | } else if matches!(name, "start_mcp_server" | "start_registry_mcp_server") { |
| 1253 | // Starting an MCP server spawns child processes or opens network |
| 1254 | // connections — classify as McpAction to trigger appropriate |
| 1255 | // approval prompts. |
| 1256 | ToolCategory::McpAction |
| 1257 | } else { |
| 1258 | ToolCategory::Unknown |
| 1259 | } |
| 1260 | } |
| 1261 | |
| 1262 | /// Categorize a concrete call after resolving an action-based canonical tool. |
| 1263 | #[must_use] |
| 1264 | pub fn get_tool_category_for_call(name: &str, params: &Value) -> ToolCategory { |
| 1265 | if name == "plugin_manager" && crate::extension_host::creator_policy::is_list_action(params) { |
| 1266 | return ToolCategory::Safe; |
| 1267 | } |
| 1268 | get_tool_category(canonical_action_alias(name, params)) |
| 1269 | } |
| 1270 | |
| 1271 | pub fn permission_label_for( |
| 1272 | locale: codewhale_localization::Locale, |
| 1273 | mode: AppMode, |
| 1274 | approval: ApprovalMode, |
| 1275 | ) -> std::borrow::Cow<'static, str> { |
| 1276 | use codewhale_localization::{MessageId, tr}; |
| 1277 | if mode == AppMode::Plan { |
| 1278 | return tr(locale, MessageId::ChipPermissionReadOnly); |
| 1279 | } |
| 1280 | match approval { |
| 1281 | ApprovalMode::Suggest => tr(locale, MessageId::ChipPermissionAsk), |
| 1282 | ApprovalMode::AcceptEdits => tr(locale, MessageId::ChipPermissionAcceptEdits), |
| 1283 | ApprovalMode::Auto => tr(locale, MessageId::ChipPermissionAuto), |
| 1284 | ApprovalMode::Bypass => tr(locale, MessageId::ChipPermissionFullAccess), |
| 1285 | ApprovalMode::Never => tr(locale, MessageId::ChipPermissionNever), |
| 1286 | } |
| 1287 | } |
| 1288 | |
| 1289 | #[cfg(test)] |
| 1290 | mod tests { |
| 1291 | use super::*; |
| 1292 | |
| 1293 | fn authority(mode: AppMode, auto_approve: bool, approval_mode: ApprovalMode) -> TurnAuthority { |
| 1294 | TurnAuthority::from_effective_fields(mode, true, false, auto_approve, approval_mode) |
| 1295 | } |
| 1296 | |
| 1297 | #[test] |
| 1298 | fn a_managed_network_grant_survives_the_ask_posture_and_shares_the_network() { |
| 1299 | let workspace = Path::new("/srv/workspace"); |
| 1300 | for approval_mode in [ApprovalMode::Suggest, ApprovalMode::Bypass] { |
| 1301 | let policy = sandbox_policy_for_turn( |
| 1302 | AppMode::Agent, |
| 1303 | approval_mode, |
| 1304 | Some("workspace-write"), |
| 1305 | workspace, |
| 1306 | SandboxNetworkAccess::from_config(Some(true)), |
| 1307 | ); |
| 1308 | assert!( |
| 1309 | matches!( |
| 1310 | policy, |
| 1311 | SandboxPolicy::WorkspaceWrite { |
| 1312 | network_access: true, |
| 1313 | .. |
| 1314 | } |
| 1315 | ), |
| 1316 | "{approval_mode:?}: {policy:?}" |
| 1317 | ); |
| 1318 | } |
| 1319 | let unset = sandbox_policy_for_turn( |
| 1320 | AppMode::Agent, |
| 1321 | ApprovalMode::Suggest, |
| 1322 | Some("workspace-write"), |
| 1323 | workspace, |
| 1324 | SandboxNetworkAccess::from_config(None), |
| 1325 | ); |
| 1326 | assert!(!unset.has_network_access(), "{unset:?}"); |
| 1327 | } |
| 1328 | |
| 1329 | #[test] |
| 1330 | fn write_carve_out_posture_is_exactly_accept_edits() { |
| 1331 | assert!(write_carve_out_posture( |
| 1332 | AppMode::Agent, |
| 1333 | ApprovalMode::AcceptEdits, |
| 1334 | false |
| 1335 | )); |
| 1336 | assert!(!write_carve_out_posture( |
| 1337 | AppMode::Agent, |
| 1338 | ApprovalMode::Suggest, |
| 1339 | false |
| 1340 | )); |
| 1341 | // Full Access already runs these calls; the carve-out must not be |
| 1342 | // what allows them. |
| 1343 | assert!(!write_carve_out_posture( |
| 1344 | AppMode::Agent, |
| 1345 | ApprovalMode::Bypass, |
| 1346 | true |
| 1347 | )); |
| 1348 | // Never still denies; Auto-Review still fails unresolved holds closed; |
| 1349 | // Plan is read-only by mode. |
| 1350 | assert!(!write_carve_out_posture( |
| 1351 | AppMode::Agent, |
| 1352 | ApprovalMode::Never, |
| 1353 | false |
| 1354 | )); |
| 1355 | assert!(!write_carve_out_posture( |
| 1356 | AppMode::Agent, |
| 1357 | ApprovalMode::Auto, |
| 1358 | false |
| 1359 | )); |
| 1360 | assert!(!write_carve_out_posture( |
| 1361 | AppMode::Plan, |
| 1362 | ApprovalMode::AcceptEdits, |
| 1363 | false |
| 1364 | )); |
| 1365 | } |
| 1366 | |
| 1367 | #[test] |
| 1368 | fn file_write_card_names_the_missing_repository_only_where_git_changes_the_answer() { |
| 1369 | let plain = tempfile::tempdir().expect("tempdir"); |
| 1370 | let repo = carve_out_workspace(); |
| 1371 | let edit = serde_json::json!({ "path": "notes.txt", "search": "a", "replace": "b" }); |
| 1372 | let asks = |mode, approval_mode, workspace: &Path, tool: &str| { |
| 1373 | file_write_asks_without_git(mode, approval_mode, workspace, tool, &edit) |
| 1374 | }; |
| 1375 | |
| 1376 | // The lesson-1 case: Accept Edits, plain folder, a file edit. |
| 1377 | for tool in ["edit_file", "write_file", "apply_patch"] { |
| 1378 | assert!( |
| 1379 | asks( |
| 1380 | AppMode::Agent, |
| 1381 | ApprovalMode::AcceptEdits, |
| 1382 | plain.path(), |
| 1383 | tool |
| 1384 | ), |
| 1385 | "{tool}" |
| 1386 | ); |
| 1387 | } |
| 1388 | // In a repository the same call runs without a card, so a card that |
| 1389 | // does open there is asking for some other reason. |
| 1390 | assert!(!asks( |
| 1391 | AppMode::Agent, |
| 1392 | ApprovalMode::AcceptEdits, |
| 1393 | repo.path(), |
| 1394 | "edit_file" |
| 1395 | )); |
| 1396 | assert!(paths_within_workspace_write_carve_out( |
| 1397 | repo.path(), |
| 1398 | &["notes.txt".to_string()] |
| 1399 | )); |
| 1400 | assert!(!paths_within_workspace_write_carve_out( |
| 1401 | plain.path(), |
| 1402 | &["notes.txt".to_string()] |
| 1403 | )); |
| 1404 | // Postures the carve-out never relaxes ask with or without git. |
| 1405 | for approval_mode in [ApprovalMode::Suggest, ApprovalMode::Auto] { |
| 1406 | assert!(!asks( |
| 1407 | AppMode::Agent, |
| 1408 | approval_mode, |
| 1409 | plain.path(), |
| 1410 | "edit_file" |
| 1411 | )); |
| 1412 | } |
| 1413 | assert!(!asks( |
| 1414 | AppMode::Plan, |
| 1415 | ApprovalMode::AcceptEdits, |
| 1416 | plain.path(), |
| 1417 | "edit_file" |
| 1418 | )); |
| 1419 | // Git presence never changes whether a command asks. |
| 1420 | assert!(!asks( |
| 1421 | AppMode::Agent, |
| 1422 | ApprovalMode::AcceptEdits, |
| 1423 | plain.path(), |
| 1424 | "exec_shell" |
| 1425 | )); |
| 1426 | } |
| 1427 | |
| 1428 | fn carve_out_workspace() -> tempfile::TempDir { |
| 1429 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1430 | std::fs::create_dir(tmp.path().join(".git")).expect("git marker"); |
| 1431 | std::fs::create_dir_all(tmp.path().join("src")).expect("src dir"); |
| 1432 | std::fs::write(tmp.path().join("src/main.rs"), "fn main() {}\n").expect("source file"); |
| 1433 | tmp |
| 1434 | } |
| 1435 | |
| 1436 | #[test] |
| 1437 | fn carve_out_allows_in_workspace_write_targets() { |
| 1438 | let tmp = carve_out_workspace(); |
| 1439 | let workspace = tmp.path(); |
| 1440 | for paths in [ |
| 1441 | vec!["src/main.rs".to_string()], |
| 1442 | vec!["src/new_file.rs".to_string()], |
| 1443 | vec!["deeply/nested/not-yet-created.rs".to_string()], |
| 1444 | vec!["./src/main.rs".to_string()], |
| 1445 | vec![workspace.join("src/main.rs").to_string_lossy().into_owned()], |
| 1446 | vec!["src/main.rs".to_string(), "src/other.rs".to_string()], |
| 1447 | ] { |
| 1448 | assert!( |
| 1449 | paths_within_workspace_write_carve_out(workspace, &paths), |
| 1450 | "{paths:?} should qualify" |
| 1451 | ); |
| 1452 | } |
| 1453 | } |
| 1454 | |
| 1455 | #[test] |
| 1456 | fn carve_out_rejects_out_of_tree_sensitive_and_git_paths() { |
| 1457 | let tmp = carve_out_workspace(); |
| 1458 | let workspace = tmp.path(); |
| 1459 | for paths in [ |
| 1460 | vec!["../outside.rs".to_string()], |
| 1461 | vec!["src/../../outside.rs".to_string()], |
| 1462 | vec!["/etc/passwd".to_string()], |
| 1463 | vec![".git/config".to_string()], |
| 1464 | vec!["nested/.git/hooks/pre-commit".to_string()], |
| 1465 | vec![".env".to_string()], |
| 1466 | vec!["config/.env.production".to_string()], |
| 1467 | vec![".ssh/config".to_string()], |
| 1468 | vec!["deploy/id_rsa".to_string()], |
| 1469 | vec!["certs/server.pem".to_string()], |
| 1470 | vec![".codewhale/mcp.json".to_string()], |
| 1471 | vec!["aws/credentials".to_string()], |
| 1472 | // One bad target poisons the whole call. |
| 1473 | vec!["src/main.rs".to_string(), ".env".to_string()], |
| 1474 | ] { |
| 1475 | assert!( |
| 1476 | !paths_within_workspace_write_carve_out(workspace, &paths), |
| 1477 | "{paths:?} must keep the modal" |
| 1478 | ); |
| 1479 | } |
| 1480 | } |
| 1481 | |
| 1482 | #[test] |
| 1483 | fn carve_out_excludes_git_metadata_by_the_shared_rule() { |
| 1484 | let tmp = carve_out_workspace(); |
| 1485 | let workspace = tmp.path(); |
| 1486 | let mut refused = vec![".GIT/config", "nested/.Git/hooks/pre-commit"]; |
| 1487 | if cfg!(windows) { |
| 1488 | refused.extend([".git./config", ".git /config", "GIT~1/config"]); |
| 1489 | } |
| 1490 | for path in refused { |
| 1491 | assert!( |
| 1492 | !paths_within_workspace_write_carve_out(workspace, &[path.to_string()]), |
| 1493 | "{path} must keep the modal" |
| 1494 | ); |
| 1495 | } |
| 1496 | assert!(paths_within_workspace_write_carve_out( |
| 1497 | workspace, |
| 1498 | &[".github/workflows/ci.yml".to_string()] |
| 1499 | )); |
| 1500 | } |
| 1501 | |
| 1502 | #[test] |
| 1503 | fn carve_out_requires_a_git_work_tree() { |
| 1504 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1505 | assert!(!paths_within_workspace_write_carve_out( |
| 1506 | tmp.path(), |
| 1507 | &["src/main.rs".to_string()] |
| 1508 | )); |
| 1509 | } |
| 1510 | |
| 1511 | #[test] |
| 1512 | fn carve_out_rejects_empty_target_list() { |
| 1513 | let tmp = carve_out_workspace(); |
| 1514 | assert!(!paths_within_workspace_write_carve_out(tmp.path(), &[])); |
| 1515 | } |
| 1516 | |
| 1517 | #[cfg(unix)] |
| 1518 | #[test] |
| 1519 | fn carve_out_rejects_symlink_escapes() { |
| 1520 | let tmp = carve_out_workspace(); |
| 1521 | let outside = tempfile::tempdir().expect("outside tempdir"); |
| 1522 | std::os::unix::fs::symlink(outside.path(), tmp.path().join("link")).expect("symlink"); |
| 1523 | assert!(!paths_within_workspace_write_carve_out( |
| 1524 | tmp.path(), |
| 1525 | &["link/evil.rs".to_string()] |
| 1526 | )); |
| 1527 | // A symlink that stays inside the workspace is fine. |
| 1528 | std::os::unix::fs::symlink(tmp.path().join("src"), tmp.path().join("src-link")) |
| 1529 | .expect("inner symlink"); |
| 1530 | assert!(paths_within_workspace_write_carve_out( |
| 1531 | tmp.path(), |
| 1532 | &["src-link/main.rs".to_string()] |
| 1533 | )); |
| 1534 | } |
| 1535 | |
| 1536 | #[test] |
| 1537 | fn full_access_is_unsandboxed_unless_effective_config_is_stricter() { |
| 1538 | let workspace = Path::new("/work"); |
| 1539 | let full_access = authority(AppMode::Agent, true, ApprovalMode::Bypass); |
| 1540 | |
| 1541 | assert_eq!( |
| 1542 | full_access.sandbox_policy(workspace, None, SandboxNetworkAccess::Restricted), |
| 1543 | SandboxPolicy::DangerFullAccess |
| 1544 | ); |
| 1545 | // Clamping full-access down to workspace-write must land on the same |
| 1546 | // restricted posture an ordinary Agent turn gets, not on a wider one. |
| 1547 | assert!(matches!( |
| 1548 | full_access.sandbox_policy( |
| 1549 | workspace, |
| 1550 | Some("workspace-write"), |
| 1551 | SandboxNetworkAccess::Restricted |
| 1552 | ), |
| 1553 | SandboxPolicy::WorkspaceWrite { writable_roots, network_access, .. } |
| 1554 | if writable_roots == vec![workspace.to_path_buf()] && !network_access |
| 1555 | )); |
| 1556 | assert_eq!( |
| 1557 | full_access.sandbox_policy( |
| 1558 | workspace, |
| 1559 | Some("read-only"), |
| 1560 | SandboxNetworkAccess::Restricted |
| 1561 | ), |
| 1562 | SandboxPolicy::read_only() |
| 1563 | ); |
| 1564 | // The external sandbox no longer claims network unconditionally; it |
| 1565 | // reports what was actually granted. |
| 1566 | assert!(matches!( |
| 1567 | full_access.sandbox_policy( |
| 1568 | workspace, |
| 1569 | Some("external-sandbox"), |
| 1570 | SandboxNetworkAccess::Restricted |
| 1571 | ), |
| 1572 | SandboxPolicy::ExternalSandbox { |
| 1573 | network_access: false |
| 1574 | } |
| 1575 | )); |
| 1576 | assert!(matches!( |
| 1577 | full_access.sandbox_policy( |
| 1578 | workspace, |
| 1579 | Some("external-sandbox"), |
| 1580 | SandboxNetworkAccess::Allowed |
| 1581 | ), |
| 1582 | SandboxPolicy::ExternalSandbox { |
| 1583 | network_access: true |
| 1584 | } |
| 1585 | )); |
| 1586 | } |
| 1587 | |
| 1588 | #[test] |
| 1589 | fn workspace_write_never_grants_network_without_an_explicit_opt_in() { |
| 1590 | let workspace = Path::new("/work"); |
| 1591 | // Every non-Yolo posture, with and without a configured sandbox mode. |
| 1592 | for approval_mode in [ |
| 1593 | ApprovalMode::Suggest, |
| 1594 | ApprovalMode::Auto, |
| 1595 | ApprovalMode::Never, |
| 1596 | ] { |
| 1597 | for configured in [None, Some("workspace-write"), Some("danger-full-access")] { |
| 1598 | let auth = authority(AppMode::Agent, false, approval_mode); |
| 1599 | let policy = |
| 1600 | auth.sandbox_policy(workspace, configured, SandboxNetworkAccess::Restricted); |
| 1601 | assert!( |
| 1602 | !policy.has_network_access(), |
| 1603 | "{approval_mode:?}/{configured:?} leaked network: {policy:?}" |
| 1604 | ); |
| 1605 | } |
| 1606 | } |
| 1607 | |
| 1608 | // The Bypass posture is deliberately unsandboxed and keeps its |
| 1609 | // semantics: DangerFullAccess reports network regardless of this key, |
| 1610 | // because it applies no sandbox at all. |
| 1611 | let bypass = authority(AppMode::Agent, true, ApprovalMode::Bypass); |
| 1612 | let policy = bypass.sandbox_policy(workspace, None, SandboxNetworkAccess::Restricted); |
| 1613 | assert_eq!(policy, SandboxPolicy::DangerFullAccess); |
| 1614 | assert!(policy.has_network_access()); |
| 1615 | |
| 1616 | // Plan is read-only and denies network under either setting. |
| 1617 | let plan = authority(AppMode::Plan, false, ApprovalMode::Suggest); |
| 1618 | for access in [ |
| 1619 | SandboxNetworkAccess::Restricted, |
| 1620 | SandboxNetworkAccess::Allowed, |
| 1621 | ] { |
| 1622 | assert!( |
| 1623 | !plan |
| 1624 | .sandbox_policy(workspace, None, access) |
| 1625 | .has_network_access() |
| 1626 | ); |
| 1627 | } |
| 1628 | } |
| 1629 | |
| 1630 | #[test] |
| 1631 | fn sandbox_network_access_defaults_to_restricted() { |
| 1632 | assert_eq!( |
| 1633 | SandboxNetworkAccess::default(), |
| 1634 | SandboxNetworkAccess::Restricted |
| 1635 | ); |
| 1636 | assert_eq!( |
| 1637 | SandboxNetworkAccess::from_config(None), |
| 1638 | SandboxNetworkAccess::Restricted |
| 1639 | ); |
| 1640 | assert_eq!( |
| 1641 | SandboxNetworkAccess::from_config(Some(false)), |
| 1642 | SandboxNetworkAccess::Restricted |
| 1643 | ); |
| 1644 | assert_eq!( |
| 1645 | SandboxNetworkAccess::from_config(Some(true)), |
| 1646 | SandboxNetworkAccess::Allowed |
| 1647 | ); |
| 1648 | } |
| 1649 | |
| 1650 | #[test] |
| 1651 | fn plan_ask_and_auto_review_cannot_be_loosened_by_sandbox_config() { |
| 1652 | let workspace = Path::new("/work"); |
| 1653 | for approval_mode in [ApprovalMode::Suggest, ApprovalMode::Auto] { |
| 1654 | let authority = authority(AppMode::Agent, false, approval_mode); |
| 1655 | assert!(matches!( |
| 1656 | authority.sandbox_policy( |
| 1657 | workspace, |
| 1658 | Some("danger-full-access"), |
| 1659 | SandboxNetworkAccess::Restricted |
| 1660 | ), |
| 1661 | SandboxPolicy::WorkspaceWrite { .. } |
| 1662 | )); |
| 1663 | } |
| 1664 | |
| 1665 | let plan = authority(AppMode::Plan, true, ApprovalMode::Bypass); |
| 1666 | assert_eq!( |
| 1667 | plan.sandbox_policy( |
| 1668 | workspace, |
| 1669 | Some("danger-full-access"), |
| 1670 | SandboxNetworkAccess::Restricted |
| 1671 | ), |
| 1672 | SandboxPolicy::read_only() |
| 1673 | ); |
| 1674 | } |
| 1675 | |
| 1676 | #[test] |
| 1677 | fn outbound_web_payloads_require_a_session_decision_even_for_allowed_hosts() { |
| 1678 | use crate::tools::{ |
| 1679 | fetch_url::FetchUrlTool, spec::ToolSpec, web_run::WebRunTool, |
| 1680 | web_search::WebSearchTool, web_tool::WebTool, |
| 1681 | }; |
| 1682 | let request = serde_json::json!({"action": "fetch", "url": "https://example.com/collect?data=synthetic-secret"}); |
| 1683 | for requirement in [ |
| 1684 | FetchUrlTool.approval_requirement_for(&request), |
| 1685 | WebTool::new("Web").approval_requirement_for(&request), |
| 1686 | WebSearchTool.approval_requirement(), |
| 1687 | WebRunTool.approval_requirement(), |
| 1688 | ] { |
| 1689 | for approval in [ApprovalMode::Suggest, ApprovalMode::Auto] { |
| 1690 | let ask = authority(AppMode::Agent, false, approval); |
| 1691 | assert_eq!( |
| 1692 | resolve_tool_permission(&ask, requirement, false), |
| 1693 | ToolPermission::Prompt |
| 1694 | ); |
| 1695 | } |
| 1696 | let never = authority(AppMode::Agent, false, ApprovalMode::Never); |
| 1697 | assert_eq!( |
| 1698 | resolve_tool_permission(&never, requirement, false), |
| 1699 | ToolPermission::Deny |
| 1700 | ); |
| 1701 | let granted = authority(AppMode::Agent, true, ApprovalMode::Bypass); |
| 1702 | assert_eq!( |
| 1703 | resolve_tool_permission(&granted, requirement, false), |
| 1704 | ToolPermission::Allow |
| 1705 | ); |
| 1706 | } |
| 1707 | let local_read = crate::tools::file::ReadFileTool.approval_requirement(); |
| 1708 | assert_eq!( |
| 1709 | resolve_tool_permission( |
| 1710 | &authority(AppMode::Agent, false, ApprovalMode::Suggest), |
| 1711 | local_read, |
| 1712 | false |
| 1713 | ), |
| 1714 | ToolPermission::Allow |
| 1715 | ); |
| 1716 | } |
| 1717 | |
| 1718 | #[test] |
| 1719 | fn auto_requirement_always_allows() { |
| 1720 | for (mode, auto_approve, approval_mode) in [ |
| 1721 | (AppMode::Agent, false, ApprovalMode::Suggest), |
| 1722 | (AppMode::Agent, false, ApprovalMode::Auto), |
| 1723 | (AppMode::Agent, false, ApprovalMode::Never), |
| 1724 | (AppMode::Agent, true, ApprovalMode::Bypass), |
| 1725 | (AppMode::Plan, false, ApprovalMode::Suggest), |
| 1726 | ] { |
| 1727 | let auth = authority(mode, auto_approve, approval_mode); |
| 1728 | for non_bypassable in [false, true] { |
| 1729 | assert_eq!( |
| 1730 | resolve_tool_permission(&auth, ApprovalRequirement::Auto, non_bypassable), |
| 1731 | ToolPermission::Allow, |
| 1732 | "{mode:?}/{auto_approve}/{approval_mode:?}/nb={non_bypassable}" |
| 1733 | ); |
| 1734 | } |
| 1735 | } |
| 1736 | } |
| 1737 | |
| 1738 | #[test] |
| 1739 | fn ask_posture_prompts_for_non_auto_tools() { |
| 1740 | let auth = authority(AppMode::Agent, false, ApprovalMode::Suggest); |
| 1741 | for requirement in [ApprovalRequirement::Suggest, ApprovalRequirement::Required] { |
| 1742 | assert_eq!( |
| 1743 | resolve_tool_permission(&auth, requirement, false), |
| 1744 | ToolPermission::Prompt |
| 1745 | ); |
| 1746 | assert_eq!( |
| 1747 | resolve_tool_permission(&auth, requirement, true), |
| 1748 | ToolPermission::Prompt |
| 1749 | ); |
| 1750 | } |
| 1751 | } |
| 1752 | |
| 1753 | #[test] |
| 1754 | fn full_access_allows_bypassable_but_prompts_for_non_bypassable() { |
| 1755 | for auth in [ |
| 1756 | authority(AppMode::Agent, true, ApprovalMode::Bypass), |
| 1757 | TurnAuthority::for_tool_approval_decision(true), |
| 1758 | ] { |
| 1759 | for requirement in [ApprovalRequirement::Suggest, ApprovalRequirement::Required] { |
| 1760 | assert_eq!( |
| 1761 | resolve_tool_permission(&auth, requirement, false), |
| 1762 | ToolPermission::Allow, |
| 1763 | "generic {requirement:?} tool stays auto-approved in Full Access" |
| 1764 | ); |
| 1765 | assert_eq!( |
| 1766 | resolve_tool_permission(&auth, requirement, true), |
| 1767 | ToolPermission::Allow, |
| 1768 | "non-bypassable {requirement:?} tool auto-approves in Full Access (#3866 reversed)" |
| 1769 | ); |
| 1770 | } |
| 1771 | } |
| 1772 | |
| 1773 | // Ask (the default suggest posture without auto-approve) can open the |
| 1774 | // modal, so the hold still prompts there. |
| 1775 | let ask = authority(AppMode::Agent, false, ApprovalMode::Suggest); |
| 1776 | for requirement in [ApprovalRequirement::Suggest, ApprovalRequirement::Required] { |
| 1777 | assert_eq!( |
| 1778 | resolve_tool_permission(&ask, requirement, true), |
| 1779 | ToolPermission::Prompt, |
| 1780 | "non-bypassable {requirement:?} tool still prompts in Ask" |
| 1781 | ); |
| 1782 | } |
| 1783 | } |
| 1784 | |
| 1785 | #[test] |
| 1786 | fn never_denies_promptable_tools_but_not_reads_or_full_access_shapes() { |
| 1787 | let never = authority(AppMode::Agent, false, ApprovalMode::Never); |
| 1788 | assert_eq!( |
| 1789 | resolve_tool_permission(&never, ApprovalRequirement::Suggest, false), |
| 1790 | ToolPermission::Deny |
| 1791 | ); |
| 1792 | assert_eq!( |
| 1793 | resolve_tool_permission(&never, ApprovalRequirement::Required, true), |
| 1794 | ToolPermission::Deny |
| 1795 | ); |
| 1796 | assert_eq!( |
| 1797 | resolve_tool_permission(&never, ApprovalRequirement::Auto, false), |
| 1798 | ToolPermission::Allow, |
| 1799 | "Never remains read-only rather than dead" |
| 1800 | ); |
| 1801 | |
| 1802 | // Legacy host shape: a full-access bit with a stale Never enum still |
| 1803 | // auto-approves — the UI's full-access shortcut ran before its Never |
| 1804 | // check. |
| 1805 | let stale = authority(AppMode::Agent, true, ApprovalMode::Never); |
| 1806 | assert_eq!( |
| 1807 | resolve_tool_permission(&stale, ApprovalRequirement::Suggest, false), |
| 1808 | ToolPermission::Allow |
| 1809 | ); |
| 1810 | } |
| 1811 | |
| 1812 | #[test] |
| 1813 | fn approval_request_disposition_preserves_legacy_branch_order() { |
| 1814 | let ask = authority(AppMode::Agent, false, ApprovalMode::Suggest); |
| 1815 | let auto = authority(AppMode::Agent, false, ApprovalMode::Auto); |
| 1816 | let full_access = authority(AppMode::Agent, true, ApprovalMode::Bypass); |
| 1817 | let never = authority(AppMode::Agent, false, ApprovalMode::Never); |
| 1818 | |
| 1819 | // Session denial wins over everything, including full access. |
| 1820 | assert_eq!( |
| 1821 | resolve_approval_request_disposition(&full_access, true, true, false, ""), |
| 1822 | ApprovalRequestDisposition::AutoDenySessionDenied |
| 1823 | ); |
| 1824 | // Forced hold under full access fails closed instead of auto-approving. |
| 1825 | assert_eq!( |
| 1826 | resolve_approval_request_disposition(&full_access, true, false, true, ""), |
| 1827 | ApprovalRequestDisposition::AutoDenyFullAccessPolicyHold |
| 1828 | ); |
| 1829 | // Full access and session grants auto-approve ordinary requests. |
| 1830 | assert_eq!( |
| 1831 | resolve_approval_request_disposition(&full_access, false, false, false, ""), |
| 1832 | ApprovalRequestDisposition::AutoApprove |
| 1833 | ); |
| 1834 | assert_eq!( |
| 1835 | resolve_approval_request_disposition(&ask, true, false, false, ""), |
| 1836 | ApprovalRequestDisposition::AutoApprove |
| 1837 | ); |
| 1838 | // The live Never posture wins over a remembered session grant |
| 1839 | // (approvals J, CURRENT_DECISIONS §21), and denies everything else |
| 1840 | // promptable. |
| 1841 | assert_eq!( |
| 1842 | resolve_approval_request_disposition(&never, true, false, false, ""), |
| 1843 | ApprovalRequestDisposition::AutoDenyNeverPosture |
| 1844 | ); |
| 1845 | assert_eq!( |
| 1846 | resolve_approval_request_disposition(&never, false, false, false, ""), |
| 1847 | ApprovalRequestDisposition::AutoDenyNeverPosture |
| 1848 | ); |
| 1849 | for force_prompt in [false, true] { |
| 1850 | assert_eq!( |
| 1851 | resolve_approval_request_disposition(&auto, false, false, force_prompt, ""), |
| 1852 | ApprovalRequestDisposition::AutoDenyAutoReview |
| 1853 | ); |
| 1854 | } |
| 1855 | // Ask posture with no grant opens the modal. |
| 1856 | assert_eq!( |
| 1857 | resolve_approval_request_disposition(&ask, false, false, false, ""), |
| 1858 | ApprovalRequestDisposition::Prompt |
| 1859 | ); |
| 1860 | } |
| 1861 | |
| 1862 | #[test] |
| 1863 | fn auto_review_forced_prompts_require_owner_presence_and_preserve_other_modes() { |
| 1864 | let ask = TurnAuthority::for_tui_surface( |
| 1865 | AppMode::Agent, |
| 1866 | false, |
| 1867 | false, |
| 1868 | false, |
| 1869 | ApprovalMode::Suggest, |
| 1870 | ); |
| 1871 | let accept_edits = TurnAuthority::for_tui_surface( |
| 1872 | AppMode::Agent, |
| 1873 | false, |
| 1874 | false, |
| 1875 | false, |
| 1876 | ApprovalMode::AcceptEdits, |
| 1877 | ); |
| 1878 | let plan = |
| 1879 | TurnAuthority::for_tui_surface(AppMode::Plan, false, false, false, ApprovalMode::Auto); |
| 1880 | let full_access = TurnAuthority::for_tui_surface( |
| 1881 | AppMode::Agent, |
| 1882 | false, |
| 1883 | false, |
| 1884 | true, |
| 1885 | ApprovalMode::Bypass, |
| 1886 | ); |
| 1887 | let full_access_headless = authority(AppMode::Agent, true, ApprovalMode::Bypass); |
| 1888 | let never = TurnAuthority::for_tui_surface( |
| 1889 | AppMode::Agent, |
| 1890 | false, |
| 1891 | false, |
| 1892 | false, |
| 1893 | ApprovalMode::Never, |
| 1894 | ); |
| 1895 | |
| 1896 | let auto_interactive = |
| 1897 | TurnAuthority::for_tui_surface(AppMode::Agent, false, false, false, ApprovalMode::Auto); |
| 1898 | let auto_attached = authority(AppMode::Agent, false, ApprovalMode::Auto) |
| 1899 | .with_rust_origin(RunOrigin::Interactive, true); |
| 1900 | let auto_background = authority(AppMode::Agent, false, ApprovalMode::Auto) |
| 1901 | .with_rust_origin(RunOrigin::Background, false); |
| 1902 | let auto_headless = authority(AppMode::Agent, false, ApprovalMode::Auto); |
| 1903 | let auto_interactive_unattached = authority(AppMode::Agent, false, ApprovalMode::Auto) |
| 1904 | .with_rust_origin(RunOrigin::Interactive, false); |
| 1905 | |
| 1906 | for owner_present in [&auto_interactive, &auto_attached] { |
| 1907 | for approval_key in ["", "extcall:ext:test", "creator-human:install"] { |
| 1908 | for session_approved in [false, true] { |
| 1909 | assert_eq!( |
| 1910 | resolve_approval_request_disposition( |
| 1911 | owner_present, |
| 1912 | session_approved, |
| 1913 | false, |
| 1914 | true, |
| 1915 | approval_key, |
| 1916 | ), |
| 1917 | ApprovalRequestDisposition::Prompt |
| 1918 | ); |
| 1919 | assert_eq!( |
| 1920 | resolve_approval_request_disposition( |
| 1921 | owner_present, |
| 1922 | session_approved, |
| 1923 | true, |
| 1924 | true, |
| 1925 | approval_key, |
| 1926 | ), |
| 1927 | ApprovalRequestDisposition::AutoDenySessionDenied |
| 1928 | ); |
| 1929 | } |
| 1930 | assert_eq!( |
| 1931 | resolve_approval_request_disposition( |
| 1932 | owner_present, |
| 1933 | false, |
| 1934 | false, |
| 1935 | false, |
| 1936 | approval_key, |
| 1937 | ), |
| 1938 | ApprovalRequestDisposition::AutoDenyAutoReview |
| 1939 | ); |
| 1940 | } |
| 1941 | } |
| 1942 | |
| 1943 | for owner_absent in [ |
| 1944 | &auto_background, |
| 1945 | &auto_headless, |
| 1946 | &auto_interactive_unattached, |
| 1947 | ] { |
| 1948 | for approval_key in ["", "extcall:ext:test", "creator-human:install"] { |
| 1949 | for force_prompt in [false, true] { |
| 1950 | assert_eq!( |
| 1951 | resolve_approval_request_disposition( |
| 1952 | owner_absent, |
| 1953 | false, |
| 1954 | false, |
| 1955 | force_prompt, |
| 1956 | approval_key, |
| 1957 | ), |
| 1958 | ApprovalRequestDisposition::AutoDenyAutoReview |
| 1959 | ); |
| 1960 | } |
| 1961 | } |
| 1962 | } |
| 1963 | |
| 1964 | assert_eq!( |
| 1965 | resolve_approval_request_disposition(&ask, false, false, true, ""), |
| 1966 | ApprovalRequestDisposition::Prompt |
| 1967 | ); |
| 1968 | assert_eq!( |
| 1969 | resolve_approval_request_disposition(&accept_edits, false, false, true, ""), |
| 1970 | ApprovalRequestDisposition::Prompt |
| 1971 | ); |
| 1972 | assert_eq!( |
| 1973 | resolve_approval_request_disposition(&plan, false, false, true, ""), |
| 1974 | ApprovalRequestDisposition::Prompt |
| 1975 | ); |
| 1976 | assert_eq!( |
| 1977 | resolve_approval_request_disposition(&full_access, false, false, true, ""), |
| 1978 | ApprovalRequestDisposition::AutoDenyFullAccessPolicyHold |
| 1979 | ); |
| 1980 | assert_eq!( |
| 1981 | resolve_approval_request_disposition( |
| 1982 | &full_access, |
| 1983 | false, |
| 1984 | false, |
| 1985 | true, |
| 1986 | "extcall:ext:test", |
| 1987 | ), |
| 1988 | ApprovalRequestDisposition::Prompt |
| 1989 | ); |
| 1990 | assert_eq!( |
| 1991 | resolve_approval_request_disposition( |
| 1992 | &full_access, |
| 1993 | false, |
| 1994 | false, |
| 1995 | true, |
| 1996 | "creator-human:install", |
| 1997 | ), |
| 1998 | ApprovalRequestDisposition::Prompt |
| 1999 | ); |
| 2000 | assert_eq!( |
| 2001 | resolve_approval_request_disposition(&full_access_headless, false, false, true, ""), |
| 2002 | ApprovalRequestDisposition::AutoDenyFullAccessPolicyHold |
| 2003 | ); |
| 2004 | assert_eq!( |
| 2005 | resolve_approval_request_disposition( |
| 2006 | &full_access_headless, |
| 2007 | false, |
| 2008 | false, |
| 2009 | true, |
| 2010 | "creator-human:install", |
| 2011 | ), |
| 2012 | ApprovalRequestDisposition::Prompt |
| 2013 | ); |
| 2014 | assert_eq!( |
| 2015 | resolve_approval_request_disposition(&never, false, false, true, ""), |
| 2016 | ApprovalRequestDisposition::AutoDenyNeverPosture |
| 2017 | ); |
| 2018 | assert_eq!( |
| 2019 | resolve_approval_request_disposition( |
| 2020 | &never, |
| 2021 | false, |
| 2022 | false, |
| 2023 | true, |
| 2024 | "creator-human:install", |
| 2025 | ), |
| 2026 | ApprovalRequestDisposition::AutoDenyNeverPosture |
| 2027 | ); |
| 2028 | } |
| 2029 | |
| 2030 | #[test] |
| 2031 | fn turn_origin_and_owner_presence_default_fail_closed_and_clamp() { |
| 2032 | for mode in [AppMode::Plan, AppMode::Agent] { |
| 2033 | for allow_shell in [false, true] { |
| 2034 | for trust_mode in [false, true] { |
| 2035 | for auto_approve in [false, true] { |
| 2036 | for approval_mode in [ |
| 2037 | ApprovalMode::Suggest, |
| 2038 | ApprovalMode::Auto, |
| 2039 | ApprovalMode::Never, |
| 2040 | ApprovalMode::Bypass, |
| 2041 | ] { |
| 2042 | let from_fields = TurnAuthority::from_effective_fields( |
| 2043 | mode, |
| 2044 | allow_shell, |
| 2045 | trust_mode, |
| 2046 | auto_approve, |
| 2047 | approval_mode, |
| 2048 | ); |
| 2049 | assert_eq!(from_fields.run_origin(), RunOrigin::Background); |
| 2050 | assert!(!from_fields.owner_present()); |
| 2051 | } |
| 2052 | } |
| 2053 | } |
| 2054 | } |
| 2055 | } |
| 2056 | |
| 2057 | let cases = [ |
| 2058 | (RunOrigin::Interactive, true, RunOrigin::Interactive, true), |
| 2059 | (RunOrigin::Interactive, false, RunOrigin::Interactive, false), |
| 2060 | (RunOrigin::Headless, true, RunOrigin::Headless, false), |
| 2061 | (RunOrigin::Headless, false, RunOrigin::Headless, false), |
| 2062 | (RunOrigin::Background, true, RunOrigin::Background, false), |
| 2063 | (RunOrigin::Background, false, RunOrigin::Background, false), |
| 2064 | ]; |
| 2065 | for (requested_origin, attached, expected_origin, expected_owner) in cases { |
| 2066 | let auth = authority(AppMode::Agent, false, ApprovalMode::Auto) |
| 2067 | .with_rust_origin(requested_origin, attached); |
| 2068 | assert_eq!(auth.run_origin(), expected_origin); |
| 2069 | assert_eq!(auth.owner_present(), expected_owner); |
| 2070 | } |
| 2071 | |
| 2072 | let tui = |
| 2073 | TurnAuthority::for_tui_surface(AppMode::Agent, false, false, false, ApprovalMode::Auto); |
| 2074 | assert_eq!(tui.run_origin(), RunOrigin::Interactive); |
| 2075 | assert!(tui.owner_present()); |
| 2076 | } |
| 2077 | |
| 2078 | #[test] |
| 2079 | fn tool_category_keeps_deferred_read_only_tools_safe() { |
| 2080 | let policy = auto_review::AutoReviewPolicy::default(); |
| 2081 | let empty = serde_json::json!({}); |
| 2082 | |
| 2083 | for name in [ |
| 2084 | "load_skill", |
| 2085 | "tool_search", |
| 2086 | "handle_read", |
| 2087 | "retrieve_tool_result", |
| 2088 | "context_archive_search", |
| 2089 | "session_search", |
| 2090 | "memory_search", |
| 2091 | "validate_data", |
| 2092 | "tui_help", |
| 2093 | "show_data", |
| 2094 | "present", |
| 2095 | "agents/list", |
| 2096 | "agents/wait", |
| 2097 | "task_list", |
| 2098 | "task_read", |
| 2099 | "pr_attempt_list", |
| 2100 | "pr_attempt_read", |
| 2101 | "automation_list", |
| 2102 | "automation_read", |
| 2103 | ] { |
| 2104 | assert_eq!(get_tool_category(name), ToolCategory::Safe, "{name}"); |
| 2105 | let ctx = auto_review::AutoReviewContext::from_tool_call( |
| 2106 | name, |
| 2107 | &empty, |
| 2108 | RunOrigin::Background, |
| 2109 | ApprovalMode::Auto, |
| 2110 | true, |
| 2111 | None, |
| 2112 | ); |
| 2113 | assert_eq!( |
| 2114 | policy.evaluate(&ctx).action, |
| 2115 | auto_review::AutoReviewAction::Allow, |
| 2116 | "{name}" |
| 2117 | ); |
| 2118 | } |
| 2119 | |
| 2120 | for (family, action) in [ |
| 2121 | ("tasks", "list"), |
| 2122 | ("tasks", "read"), |
| 2123 | ("tasks", "pr_attempt_list"), |
| 2124 | ("tasks", "pr_attempt_read"), |
| 2125 | ("automation", "list"), |
| 2126 | ("automation", "read"), |
| 2127 | ] { |
| 2128 | let params = serde_json::json!({ "action": action }); |
| 2129 | assert_eq!( |
| 2130 | get_tool_category_for_call(family, ¶ms), |
| 2131 | ToolCategory::Safe, |
| 2132 | "{family}.{action}" |
| 2133 | ); |
| 2134 | let ctx = auto_review::AutoReviewContext::from_tool_call( |
| 2135 | family, |
| 2136 | ¶ms, |
| 2137 | RunOrigin::Background, |
| 2138 | ApprovalMode::Auto, |
| 2139 | true, |
| 2140 | None, |
| 2141 | ); |
| 2142 | assert_eq!( |
| 2143 | policy.evaluate(&ctx).action, |
| 2144 | auto_review::AutoReviewAction::Allow, |
| 2145 | "{family}.{action}" |
| 2146 | ); |
| 2147 | } |
| 2148 | |
| 2149 | for name in [ |
| 2150 | "lsp", |
| 2151 | "notify", |
| 2152 | "git_merge_tree", |
| 2153 | "image_ocr", |
| 2154 | "image_analyze", |
| 2155 | "pandoc_convert", |
| 2156 | "review", |
| 2157 | "github_issue_context", |
| 2158 | "github_pr_context", |
| 2159 | "github_report_read", |
| 2160 | "pr_attempt_preflight", |
| 2161 | ] { |
| 2162 | assert_eq!(get_tool_category(name), ToolCategory::Unknown, "{name}"); |
| 2163 | let ctx = auto_review::AutoReviewContext::from_tool_call( |
| 2164 | name, |
| 2165 | &empty, |
| 2166 | RunOrigin::Background, |
| 2167 | ApprovalMode::Auto, |
| 2168 | true, |
| 2169 | None, |
| 2170 | ); |
| 2171 | assert_eq!( |
| 2172 | policy.evaluate(&ctx).action, |
| 2173 | auto_review::AutoReviewAction::AskUser, |
| 2174 | "{name}" |
| 2175 | ); |
| 2176 | } |
| 2177 | |
| 2178 | for (family, action) in [ |
| 2179 | ("Git", "fetch"), |
| 2180 | ("Git", "merge_tree"), |
| 2181 | ("tasks", "pr_attempt_preflight"), |
| 2182 | ("tasks", "create"), |
| 2183 | ("tasks", "gate_run"), |
| 2184 | ("automation", "create"), |
| 2185 | ("automation", "run"), |
| 2186 | ("github", "issue_context"), |
| 2187 | ("github", "pr_context"), |
| 2188 | ("github", "report_read"), |
| 2189 | ] { |
| 2190 | let params = serde_json::json!({ "action": action }); |
| 2191 | assert_eq!( |
| 2192 | get_tool_category_for_call(family, ¶ms), |
| 2193 | ToolCategory::Unknown, |
| 2194 | "{family}.{action}" |
| 2195 | ); |
| 2196 | let ctx = auto_review::AutoReviewContext::from_tool_call( |
| 2197 | family, |
| 2198 | ¶ms, |
| 2199 | RunOrigin::Background, |
| 2200 | ApprovalMode::Auto, |
| 2201 | true, |
| 2202 | None, |
| 2203 | ); |
| 2204 | assert_eq!( |
| 2205 | policy.evaluate(&ctx).action, |
| 2206 | auto_review::AutoReviewAction::AskUser, |
| 2207 | "{family}.{action}" |
| 2208 | ); |
| 2209 | } |
| 2210 | } |
| 2211 | } |
| 2212 |