Skip to main content

vtcode_core/tools/safety_gateway/
mod.rs

1//! Unified Safety Gateway
2//!
3//! Consolidates all safety checking mechanisms into a single gateway:
4//! - Rate limiting (from runloop's tool_call_safety)
5//! - Destructive tool detection
6//! - Command policy enforcement
7//! - Planning workflow restrictions
8//!
9//! This provides consistent safety decisions across all tool execution paths.
10
11mod file_targets;
12#[cfg(test)]
13use file_targets::patch_file_access_targets;
14use file_targets::{command_text_for_tool, file_access_targets, proposed_changes_preview};
15
16use hashbrown::HashSet;
17use parking_lot::{Mutex, RwLock};
18use std::future::Future;
19use std::path::{Path, PathBuf};
20use std::sync::Arc;
21use std::time::{Duration, Instant};
22
23use serde::{Deserialize, Serialize};
24use serde_json::Value;
25use thiserror::Error;
26
27use crate::config::CommandsConfig;
28use crate::config::constants::tools;
29use crate::dotfile_protection::{AccessContext, AccessType, DotfileGuardian, ProtectionDecision, get_global_guardian};
30use crate::tools::apply_patch::{Patch, PatchOperation, decode_apply_patch_input};
31use crate::tools::command_policy::CommandPolicyEvaluator;
32use crate::tools::invocation::ToolInvocationId;
33use crate::tools::rate_limit_config::{tool_calls_per_minute_from_env, tool_calls_per_second_from_env};
34use crate::tools::registry::{RiskLevel, ToolRiskContext, ToolRiskScorer, ToolSource, WorkspaceTrust};
35use crate::tools::tool_intent::{
36    ToolIntent, action_qualified_policy_name, classify_tool_intent, command_session_action_in,
37    command_session_action_is, file_operation_action_is,
38};
39use vtcode_config::constants::tool_limits::{
40    DEFAULT_MAX_TOOL_CALLS_PER_TURN, DEFAULT_SAFETY_MAX_TOOL_CALLS_PER_SESSION, MAX_CONTROL_PLANE_TOOL_CALLS_PER_TURN,
41};
42use vtcode_config::core::DotfileProtectionConfig;
43
44/// Trust level used by the safety gateway for approval bypass decisions.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
46pub enum SafetyTrustLevel {
47    Untrusted,
48    #[default]
49    Standard,
50    Elevated,
51    Full,
52}
53
54impl SafetyTrustLevel {
55    #[inline]
56    #[must_use]
57    pub const fn can_bypass_approval(self) -> bool {
58        matches!(self, Self::Elevated | Self::Full)
59    }
60}
61
62/// Minimal execution context required for safety decisions.
63#[derive(Debug, Clone)]
64pub struct SafetyContext {
65    pub session_id: String,
66    pub trust_level: SafetyTrustLevel,
67}
68
69impl SafetyContext {
70    #[must_use]
71    pub fn new(session_id: impl Into<String>) -> Self {
72        Self {
73            session_id: session_id.into(),
74            trust_level: SafetyTrustLevel::default(),
75        }
76    }
77}
78
79/// Safety decision for a tool invocation
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81#[must_use = "safety decisions must be enforced before execution"]
82pub enum SafetyDecision {
83    /// Tool execution is allowed without user approval
84    Allow,
85    /// Tool execution is denied with a reason
86    Deny(String),
87    /// Tool execution requires user approval with justification
88    NeedsApproval(String),
89}
90
91impl SafetyDecision {
92    /// Whether execution can proceed (Allow only)
93    #[inline]
94    #[must_use]
95    pub fn is_allowed(&self) -> bool {
96        matches!(self, SafetyDecision::Allow)
97    }
98
99    /// Whether execution is blocked (Deny)
100    #[inline]
101    #[must_use]
102    pub fn is_denied(&self) -> bool {
103        matches!(self, SafetyDecision::Deny(_))
104    }
105
106    /// Whether user approval is needed
107    #[inline]
108    pub fn needs_approval(&self) -> bool {
109        matches!(self, SafetyDecision::NeedsApproval(_))
110    }
111
112    /// Get the reason/justification if present
113    pub fn reason(&self) -> Option<&str> {
114        match self {
115            SafetyDecision::Allow => None,
116            SafetyDecision::Deny(reason) | SafetyDecision::NeedsApproval(reason) => Some(reason),
117        }
118    }
119}
120
121/// Errors from safety checks
122#[derive(Debug, Error, Clone)]
123pub enum SafetyError {
124    #[error("Rate limit exceeded: {current} calls in {window} (max: {max})")]
125    RateLimitExceeded {
126        current: usize,
127        max: usize,
128        window: &'static str,
129    },
130    #[error("Per-turn tool limit reached (max: {max})")]
131    TurnLimitReached { max: usize },
132    #[error("Session tool limit reached (max: {max})")]
133    SessionLimitReached { max: usize },
134    #[error("Planning workflow violation: {0}")]
135    PlanningPolicyViolation(String),
136    #[error("Command policy denied: {0}")]
137    CommandPolicyDenied(String),
138    #[error("Dotfile protection violation: {0}")]
139    DotfileProtectionViolation(String),
140}
141
142/// Result of a safety check with optional retry hint metadata.
143#[derive(Debug, Clone)]
144pub struct SafetyCheckResult {
145    /// Final decision for this invocation.
146    pub decision: SafetyDecision,
147    /// Suggested delay before retrying if the decision is a rate-limit denial.
148    pub retry_after: Option<Duration>,
149    /// Structured error when denial is produced by a safety limit.
150    pub violation: Option<SafetyError>,
151}
152
153/// Configuration for the safety gateway
154#[derive(Debug, Clone)]
155pub struct SafetyGatewayConfig {
156    /// Maximum tool calls per turn
157    pub max_per_turn: usize,
158    /// Maximum tool calls per session
159    pub max_per_session: usize,
160    /// Rate limit: calls per second
161    pub rate_limit_per_second: usize,
162    /// Rate limit: calls per minute (optional burst protection)
163    pub rate_limit_per_minute: Option<usize>,
164    /// Whether planning workflow is active (read-only)
165    pub planning_active: bool,
166    /// Workspace trust level
167    pub workspace_trust: WorkspaceTrust,
168    /// Risk threshold for requiring approval
169    pub approval_risk_threshold: RiskLevel,
170    /// Enforce short-window rate limiting (per-second/per-minute).
171    /// Turn/session limits are always enforced.
172    pub enforce_rate_limits: bool,
173}
174
175impl Default for SafetyGatewayConfig {
176    fn default() -> Self {
177        let rate_limit_per_second = tool_calls_per_second_from_env().unwrap_or(5);
178
179        Self {
180            max_per_turn: DEFAULT_MAX_TOOL_CALLS_PER_TURN,
181            max_per_session: DEFAULT_SAFETY_MAX_TOOL_CALLS_PER_SESSION,
182            rate_limit_per_second,
183            rate_limit_per_minute: tool_calls_per_minute_from_env(),
184            planning_active: false,
185            workspace_trust: WorkspaceTrust::Trusted,
186            approval_risk_threshold: RiskLevel::Medium,
187            enforce_rate_limits: true,
188        }
189    }
190}
191
192/// Rate limiter state (shared across async contexts)
193#[derive(Debug, Default)]
194struct RateLimiterState {
195    calls_per_second: std::collections::VecDeque<Instant>,
196    calls_per_minute: std::collections::VecDeque<Instant>,
197    current_turn_count: usize,
198    session_count: usize,
199    /// Count of control-plane calls (`wait`/`inspect`) recorded this turn.
200    /// These are exempt from `current_turn_count` so a long build does not
201    /// consume the budget its follow-up work needs, but they remain bounded
202    /// by their own per-turn cap and the session fuse.
203    control_plane_turn_count: usize,
204}
205
206/// Unified Safety Gateway
207///
208/// Consolidates rate limiting, destructive tool detection, command policy
209/// enforcement, planning workflow restrictions, and dotfile protection into a single
210/// safety decision point.
211pub struct SafetyGateway {
212    /// Configuration
213    config: RwLock<SafetyGatewayConfig>,
214    /// Command policy evaluator (optional, for shell commands)
215    command_policy: Option<CommandPolicyEvaluator>,
216    /// Rate limiter state
217    rate_state: Mutex<RateLimiterState>,
218    /// Preapproved tools for this session
219    preapproved: Mutex<HashSet<String>>,
220    /// Dotfile guardian for protected file access
221    dotfile_guardian: Option<Arc<DotfileGuardian>>,
222}
223
224impl SafetyGateway {
225    /// Create a new safety gateway with default configuration
226    pub fn new() -> Self {
227        Self::with_config(SafetyGatewayConfig::default())
228    }
229
230    /// Create a new safety gateway with custom configuration
231    pub fn with_config(config: SafetyGatewayConfig) -> Self {
232        Self {
233            config: RwLock::new(config),
234            command_policy: None,
235            rate_state: Mutex::new(RateLimiterState::default()),
236            preapproved: Mutex::new(HashSet::new()),
237            dotfile_guardian: None,
238        }
239    }
240
241    /// Set the dotfile guardian for protected file access
242    pub fn with_dotfile_guardian(mut self, guardian: Arc<DotfileGuardian>) -> Self {
243        self.dotfile_guardian = Some(guardian);
244        self
245    }
246
247    /// Create and set a dotfile guardian from configuration
248    pub async fn with_dotfile_protection(mut self, config: DotfileProtectionConfig) -> anyhow::Result<Self> {
249        let guardian = DotfileGuardian::new(config).await?;
250        self.dotfile_guardian = Some(Arc::new(guardian));
251        Ok(self)
252    }
253
254    /// Set the command policy evaluator for shell command checks
255    pub fn with_command_policy(mut self, policy: CommandPolicyEvaluator) -> Self {
256        self.command_policy = Some(policy);
257        self
258    }
259
260    /// Create from commands config
261    pub fn with_commands_config(mut self, config: &CommandsConfig) -> Self {
262        self.command_policy = Some(CommandPolicyEvaluator::from_config(config));
263        self
264    }
265
266    /// Enable or disable planning workflow
267    pub fn set_planning_workflow(&self, active: bool) {
268        self.config.write().planning_active = active;
269    }
270
271    /// Set workspace trust level
272    pub fn set_workspace_trust(&self, trust: WorkspaceTrust) {
273        self.config.write().workspace_trust = trust;
274    }
275
276    /// Update rate limits
277    pub fn set_limits(&self, max_per_turn: usize, max_per_session: usize) {
278        let mut config = self.config.write();
279        config.max_per_turn = max_per_turn;
280        config.max_per_session = max_per_session;
281    }
282
283    /// Update rate-limiter thresholds.
284    pub fn set_rate_limits(&self, rate_limit_per_second: usize, rate_limit_per_minute: Option<usize>) {
285        let mut config = self.config.write();
286        if rate_limit_per_second > 0 {
287            config.rate_limit_per_second = rate_limit_per_second;
288        }
289        config.rate_limit_per_minute = rate_limit_per_minute.filter(|v| *v > 0);
290    }
291
292    /// Enable or disable rate-limit enforcement while preserving counters.
293    pub fn set_rate_limit_enforcement(&self, enabled: bool) {
294        self.config.write().enforce_rate_limits = enabled;
295    }
296
297    /// Increase session limit dynamically
298    pub fn increase_session_limit(&self, increment: usize) {
299        let mut config = self.config.write();
300        let new_max = config.max_per_session.saturating_add(increment);
301        config.max_per_session = new_max;
302        tracing::info!("Session tool limit increased to {}", new_max);
303    }
304
305    pub fn max_per_session(&self) -> usize {
306        self.config.read().max_per_session
307    }
308
309    /// Reset turn counters (call at start of new turn)
310    pub fn start_turn(&self) {
311        let mut state = self.rate_state.lock();
312        state.current_turn_count = 0;
313        state.control_plane_turn_count = 0;
314        state.calls_per_second.clear();
315        state.calls_per_minute.clear();
316    }
317
318    /// Reset all transient tool-budget state for a newly reconstructed
319    /// execution context and restore the limits supplied by the build mode.
320    pub fn reset_for_fresh_execution(&self, max_per_turn: usize, max_per_session: usize) {
321        self.set_limits(max_per_turn, max_per_session);
322        let mut state = self.rate_state.lock();
323        state.current_turn_count = 0;
324        state.control_plane_turn_count = 0;
325        state.session_count = 0;
326        state.calls_per_second.clear();
327        state.calls_per_minute.clear();
328    }
329
330    /// Preapprove a tool for this session
331    pub fn preapprove(&self, tool_name: &str) {
332        let mut preapproved = self.preapproved.lock();
333        preapproved.insert(tool_name.to_string());
334    }
335
336    /// Check if a tool is preapproved
337    pub fn is_preapproved(&self, tool_name: &str) -> bool {
338        let preapproved = self.preapproved.lock();
339        preapproved.contains(tool_name)
340    }
341
342    /// Main entry point: check safety for a tool invocation.
343    ///
344    /// Returns a [`SafetyDecision`] indicating whether execution can proceed.
345    /// Inline-delegating wrapper that returns the inner future directly to
346    /// avoid an extra coroutine state machine (audit section 16).
347    pub fn check_safety<'a>(
348        &'a self,
349        ctx: &'a SafetyContext,
350        tool_name: &'a str,
351        args: &'a Value,
352    ) -> impl Future<Output = SafetyDecision> + 'a {
353        self.check_safety_with_id(ctx, tool_name, args, None)
354    }
355
356    /// Check safety with explicit invocation ID for correlation
357    pub async fn check_safety_with_id(
358        &self,
359        ctx: &SafetyContext,
360        tool_name: &str,
361        args: &Value,
362        invocation_id: Option<ToolInvocationId>,
363    ) -> SafetyDecision {
364        let inv_id = invocation_id.map(|id| id.short()).unwrap_or_else(|| "unknown".to_string());
365
366        tracing::trace!(
367            invocation_id = %inv_id,
368            tool = %tool_name,
369            "SafetyGateway: checking safety"
370        );
371
372        if let Err(err) = self.check_rate_limits(crate::tools::tool_intent::is_turn_budget_exempt_call(tool_name, args))
373        {
374            tracing::warn!(
375                invocation_id = %inv_id,
376                error = %err,
377                "SafetyGateway: rate limit exceeded"
378            );
379            return SafetyDecision::Deny(err.to_string());
380        }
381
382        self.evaluate_non_rate_decision(ctx, tool_name, args, &inv_id).await
383    }
384
385    /// Check safety and atomically reserve a rate-limit slot on success.
386    ///
387    /// This avoids split check/record races by validating rate limits and recording
388    /// execution under a single lock acquisition.
389    pub async fn check_and_record(&self, ctx: &SafetyContext, tool_name: &str, args: &Value) -> SafetyCheckResult {
390        self.check_and_record_with_id(ctx, tool_name, args, None).await
391    }
392
393    /// Check safety with correlation ID and atomically reserve a rate-limit slot.
394    pub async fn check_and_record_with_id(
395        &self,
396        ctx: &SafetyContext,
397        tool_name: &str,
398        args: &Value,
399        invocation_id: Option<ToolInvocationId>,
400    ) -> SafetyCheckResult {
401        let inv_id = invocation_id.map(|id| id.short()).unwrap_or_else(|| "unknown".to_string());
402        tracing::trace!(
403            invocation_id = %inv_id,
404            tool = %tool_name,
405            "SafetyGateway: checking and recording safety"
406        );
407
408        let decision = self.evaluate_non_rate_decision(ctx, tool_name, args, &inv_id).await;
409
410        if decision.is_denied() {
411            return SafetyCheckResult { decision, retry_after: None, violation: None };
412        }
413
414        let control_plane = crate::tools::tool_intent::is_turn_budget_exempt_call(tool_name, args);
415        let now = Instant::now();
416        let mut state = self.rate_state.lock();
417        match self.check_rate_limits_locked(&mut state, now, control_plane) {
418            Ok(()) => {
419                self.record_execution_locked(&mut state, now, control_plane);
420                SafetyCheckResult { decision, retry_after: None, violation: None }
421            }
422            Err(err) => {
423                tracing::warn!(
424                    invocation_id = %inv_id,
425                    error = %err,
426                    "SafetyGateway: rate limit exceeded during atomic reservation"
427                );
428                SafetyCheckResult {
429                    decision: SafetyDecision::Deny(err.to_string()),
430                    retry_after: self.retry_after_for_violation(&err, &state, now),
431                    violation: Some(err),
432                }
433            }
434        }
435    }
436
437    async fn evaluate_non_rate_decision(
438        &self,
439        ctx: &SafetyContext,
440        tool_name: &str,
441        args: &Value,
442        inv_id: &str,
443    ) -> SafetyDecision {
444        // Extract the command text once: the policy check, the risk context,
445        // and the approval justification all read the same value, and each
446        // extraction re-parses the command payload (shell_words split plus
447        // action re-derivation).
448        let command = command_text_for_tool(tool_name, args);
449
450        if let Some(decision) = self.check_dotfile_protection(tool_name, args, &ctx.session_id).await {
451            tracing::info!(
452                invocation_id = %inv_id,
453                tool = %tool_name,
454                "SafetyGateway: dotfile protection triggered"
455            );
456            return decision;
457        }
458
459        if let Some(ref policy) = self.command_policy
460            && let Some(command) = command.as_deref()
461            && !policy.allows_text(command)
462        {
463            let reason = format!("Command '{command}' blocked by policy");
464            tracing::info!(
465                invocation_id = %inv_id,
466                command = %command,
467                "SafetyGateway: command policy denied"
468            );
469            return SafetyDecision::Deny(reason);
470        }
471
472        if self.is_preapproved(tool_name) {
473            tracing::trace!(
474                invocation_id = %inv_id,
475                tool = %tool_name,
476                "SafetyGateway: tool preapproved"
477            );
478            return SafetyDecision::Allow;
479        }
480
481        if ctx.trust_level.can_bypass_approval() {
482            tracing::trace!(
483                invocation_id = %inv_id,
484                tool = %tool_name,
485                trust_level = ?ctx.trust_level,
486                "SafetyGateway: trust level allows bypass"
487            );
488            return SafetyDecision::Allow;
489        }
490
491        // Classify once for the risk context, the justification, and the
492        // destructive gate below: all three read the same tool name and args,
493        // and each re-classification re-parses command payloads.
494        let intent = classify_tool_intent(tool_name, args);
495        let command = command.as_deref();
496        let risk_ctx = self.build_risk_context(tool_name, args, &intent, command);
497        let risk_level = ToolRiskScorer::calculate_risk(&risk_ctx);
498
499        if ToolRiskScorer::requires_justification(risk_level, self.config.read().approval_risk_threshold) {
500            let justification = self.build_approval_justification(tool_name, &risk_level, args, &intent, command);
501            tracing::info!(
502                invocation_id = %inv_id,
503                tool = %tool_name,
504                risk = %risk_level,
505                "SafetyGateway: requires approval"
506            );
507            return SafetyDecision::NeedsApproval(justification);
508        }
509
510        if intent.destructive {
511            let justification = format!("Tool '{tool_name}' is destructive and may modify files or execute commands.");
512            tracing::info!(
513                invocation_id = %inv_id,
514                tool = %tool_name,
515                "SafetyGateway: destructive tool requires approval"
516            );
517            return SafetyDecision::NeedsApproval(justification);
518        }
519
520        SafetyDecision::Allow
521    }
522
523    /// Record that a tool call was executed (for rate limiting)
524    pub fn record_execution(&self) {
525        let mut state = self.rate_state.lock();
526        self.record_execution_locked(&mut state, Instant::now(), false);
527    }
528
529    /// Check rate limits without recording
530    fn check_rate_limits(&self, control_plane: bool) -> Result<(), SafetyError> {
531        let mut state = self.rate_state.lock();
532        self.check_rate_limits_locked(&mut state, Instant::now(), control_plane)
533    }
534
535    fn check_rate_limits_locked(
536        &self,
537        state: &mut RateLimiterState,
538        now: Instant,
539        control_plane: bool,
540    ) -> Result<(), SafetyError> {
541        let config = self.config.read();
542        self.prune_rate_windows(state, now);
543
544        if config.enforce_rate_limits {
545            if state.calls_per_second.len() >= config.rate_limit_per_second {
546                return Err(SafetyError::RateLimitExceeded {
547                    current: state.calls_per_second.len(),
548                    max: config.rate_limit_per_second,
549                    window: "1s",
550                });
551            }
552
553            if let Some(limit) = config.rate_limit_per_minute
554                && state.calls_per_minute.len() >= limit
555            {
556                return Err(SafetyError::RateLimitExceeded {
557                    current: state.calls_per_minute.len(),
558                    max: limit,
559                    window: "60s",
560                });
561            }
562        }
563
564        if control_plane {
565            // Control-plane calls bypass the per-turn work budget but keep
566            // their own bounded cap so the exemption cannot become the
567            // dominant spend path.
568            if state.control_plane_turn_count >= MAX_CONTROL_PLANE_TOOL_CALLS_PER_TURN {
569                return Err(SafetyError::TurnLimitReached { max: MAX_CONTROL_PLANE_TOOL_CALLS_PER_TURN });
570            }
571        } else if state.current_turn_count >= config.max_per_turn {
572            return Err(SafetyError::TurnLimitReached { max: config.max_per_turn });
573        }
574
575        if state.session_count >= config.max_per_session {
576            return Err(SafetyError::SessionLimitReached { max: config.max_per_session });
577        }
578
579        Ok(())
580    }
581
582    fn record_execution_locked(&self, state: &mut RateLimiterState, now: Instant, control_plane: bool) {
583        state.calls_per_second.push_back(now);
584        state.calls_per_minute.push_back(now);
585        state.session_count = state.session_count.saturating_add(1);
586        if control_plane {
587            state.control_plane_turn_count = state.control_plane_turn_count.saturating_add(1);
588        } else {
589            state.current_turn_count = state.current_turn_count.saturating_add(1);
590        }
591    }
592
593    fn prune_rate_windows(&self, state: &mut RateLimiterState, now: Instant) {
594        while let Some(front) = state.calls_per_second.front() {
595            if now.duration_since(*front) > Duration::from_secs(1) {
596                state.calls_per_second.pop_front();
597            } else {
598                break;
599            }
600        }
601        while let Some(front) = state.calls_per_minute.front() {
602            if now.duration_since(*front) > Duration::from_secs(60) {
603                state.calls_per_minute.pop_front();
604            } else {
605                break;
606            }
607        }
608    }
609
610    fn retry_after_for_violation(
611        &self,
612        violation: &SafetyError,
613        state: &RateLimiterState,
614        now: Instant,
615    ) -> Option<Duration> {
616        match violation {
617            SafetyError::RateLimitExceeded { window: "1s", .. } => state
618                .calls_per_second
619                .front()
620                .map(|first| Duration::from_secs(1).saturating_sub(now.duration_since(*first))),
621            SafetyError::RateLimitExceeded { window: "60s", .. } => state
622                .calls_per_minute
623                .front()
624                .map(|first| Duration::from_secs(60).saturating_sub(now.duration_since(*first))),
625            _ => None,
626        }
627    }
628
629    /// Check dotfile protection for file operations.
630    /// Returns Some(SafetyDecision) if dotfile protection applies, None otherwise.
631    async fn check_dotfile_protection(
632        &self,
633        tool_name: &str,
634        args: &Value,
635        session_id: &str,
636    ) -> Option<SafetyDecision> {
637        // Use local guardian if set, otherwise try global guardian
638        let guardian = match self.dotfile_guardian.as_ref() {
639            Some(g) => g.clone(),
640            None => get_global_guardian()?,
641        };
642
643        let file_targets = file_access_targets(tool_name, args);
644        if file_targets.is_empty() {
645            return None;
646        }
647
648        let proposed_changes = proposed_changes_preview(args);
649
650        for target in file_targets {
651            if !guardian.is_protected(Path::new(&target.path)) {
652                continue;
653            }
654
655            let context = AccessContext::new(&target.path, target.access_type, tool_name, session_id)
656                .with_proposed_changes(&proposed_changes);
657
658            match guardian.request_access(&context).await {
659                Ok(ProtectionDecision::Allowed) => continue,
660                Ok(ProtectionDecision::RequiresConfirmation(req)) => {
661                    return Some(SafetyDecision::NeedsApproval(format!(
662                        "DOTFILE PROTECTION\n\n\
663                        File: {}\n\
664                        Operation: {}\n\
665                        Reason: {}\n\n\
666                        Proposed changes:\n{}\n\n\
667                        {}",
668                        req.file_path, req.access_type, req.protection_reason, req.proposed_changes, req.warning
669                    )));
670                }
671                Ok(ProtectionDecision::RequiresSecondaryAuth(req)) => {
672                    return Some(SafetyDecision::NeedsApproval(format!(
673                        "DOTFILE SECONDARY AUTHENTICATION REQUIRED\n\n\
674                        File: {} (whitelisted)\n\
675                        Operation: {}\n\
676                        Reason: {}\n\n\
677                        This file is on the whitelist but requires secondary authentication.\n\n\
678                        Proposed changes:\n{}\n\n\
679                        {}",
680                        req.file_path, req.access_type, req.protection_reason, req.proposed_changes, req.warning
681                    )));
682                }
683                Ok(ProtectionDecision::Blocked(violation)) => {
684                    return Some(SafetyDecision::Deny(format!(
685                        "DOTFILE MODIFICATION BLOCKED\n\n\
686                            File: {}\n\
687                            Reason: {}\n\n\
688                            Suggestion: {}",
689                        violation.file_path, violation.reason, violation.suggestion
690                    )));
691                }
692                Ok(ProtectionDecision::Denied(violation)) => {
693                    return Some(SafetyDecision::Deny(format!(
694                        "DOTFILE ACCESS DENIED\n\n\
695                            File: {}\n\
696                            Reason: {}\n\n\
697                            Suggestion: {}",
698                        violation.file_path, violation.reason, violation.suggestion
699                    )));
700                }
701                Err(e) => {
702                    tracing::error!("Dotfile protection check failed: {}", e);
703                    return Some(SafetyDecision::Deny(format!("Dotfile protection check failed: {e}")));
704                }
705            }
706        }
707
708        None
709    }
710
711    /// Get the dotfile guardian (if configured)
712    pub fn dotfile_guardian(&self) -> Option<&Arc<DotfileGuardian>> {
713        self.dotfile_guardian.as_ref()
714    }
715
716    /// Build risk context from tool name and arguments
717    ///
718    /// `command` is the command extracted once by the caller
719    /// ([`Self::evaluate_non_rate_decision`]); re-deriving it here would
720    /// re-parse the command payload for every risk evaluation.
721    fn build_risk_context(
722        &self,
723        tool_name: &str,
724        args: &Value,
725        intent: &ToolIntent,
726        command: Option<&str>,
727    ) -> ToolRiskContext {
728        let source = if tool_name.starts_with("mcp_") {
729            ToolSource::Mcp
730        } else if tool_name.starts_with("acp_") {
731            ToolSource::Acp
732        } else {
733            ToolSource::Internal
734        };
735
736        let risk_tool_name = action_qualified_policy_name(tool_name, Some(args)).unwrap_or(tool_name);
737
738        let mut ctx = ToolRiskContext::new(risk_tool_name.to_string(), source, self.config.read().workspace_trust);
739
740        // Set flags based on tool type
741        if intent.mutating {
742            ctx = ctx.as_write();
743        }
744        if intent.destructive {
745            ctx = ctx.as_destructive();
746        }
747
748        if ToolRiskScorer::is_network_tool(risk_tool_name) {
749            ctx = ctx.accesses_network();
750        }
751
752        // Extract command args for shell tools
753        if let Some(command) = command {
754            ctx = ctx.with_args(command.split_whitespace().map(String::from).collect());
755        }
756
757        ctx
758    }
759
760    /// Build justification message for approval prompt
761    ///
762    /// `command` is the command extracted once by the caller
763    /// ([`Self::evaluate_non_rate_decision`]); re-deriving it here would
764    /// re-parse the command payload on every approval prompt.
765    fn build_approval_justification(
766        &self,
767        tool_name: &str,
768        risk_level: &RiskLevel,
769        args: &Value,
770        intent: &ToolIntent,
771        command: Option<&str>,
772    ) -> String {
773        let mut parts = Vec::new();
774
775        parts.push(format!("Tool: {tool_name}"));
776        parts.push(format!("Risk level: {risk_level}"));
777
778        if intent.destructive {
779            parts.push("This tool may modify or delete files.".to_string());
780        }
781
782        if let Some(command) = command {
783            parts.push(format!("Command: {command}"));
784        }
785
786        let file_targets = file_access_targets(tool_name, args);
787        if let Some(target) = file_targets.first() {
788            parts.push(format!("Path: {}", target.path.display()));
789            if file_targets.len() > 1 {
790                parts.push(format!("Additional targets: {}", file_targets.len() - 1));
791            }
792        }
793
794        parts.join("\n")
795    }
796
797    /// Get current session statistics
798    pub fn get_stats(&self) -> SafetyStats {
799        let state = self.rate_state.lock();
800        let preapproved = self.preapproved.lock();
801        let config = self.config.read();
802
803        SafetyStats {
804            turn_count: state.current_turn_count,
805            session_count: state.session_count,
806            max_per_turn: config.max_per_turn,
807            max_per_session: config.max_per_session,
808            planning_active: config.planning_active,
809            preapproved_count: preapproved.len(),
810        }
811    }
812}
813
814impl Default for SafetyGateway {
815    fn default() -> Self {
816        Self::new()
817    }
818}
819
820/// Statistics from the safety gateway
821#[derive(Debug, Clone)]
822pub struct SafetyStats {
823    pub turn_count: usize,
824    pub session_count: usize,
825    pub max_per_turn: usize,
826    pub max_per_session: usize,
827    pub planning_active: bool,
828    pub preapproved_count: usize,
829}
830
831#[cfg(test)]
832mod tests;