Skip to main content

merry_runtime/process/classification/
triggers.rs

1//! Structured action-review trigger classification for process intents.
2//!
3//! Replaces opaque boolean review gates with typed triggers so runtime policy,
4//! AI review, and user-facing approval dialogs all know *why* a command paused
5//! and whether a narrow session grant is permitted.
6
7#[cfg(windows)]
8use super::windows_shell::analyze_powershell_script;
9use super::{
10    git::classify_git_review_trigger,
11    rm_review_target,
12    shell::{
13        ShellKind, command_words_have_env_injection, executable_name, parse_bash_security_analysis,
14        shell_like_process_input_from_argv,
15    },
16    strip_shell_command_prefixes,
17};
18use crate::ProcessActionIntent;
19use serde::{Deserialize, Serialize};
20
21const PRIVILEGE_EXECUTABLES: &[&str] = &["su", "sudo"];
22const NESTED_SHELL_EXECUTABLES: &[&str] = &["bash", "cmd", "powershell", "pwsh", "sh", "zsh"];
23
24/// Concrete reason why a process action requires an independent action review.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(tag = "kind", rename_all = "snake_case")]
27pub enum ActionReviewTrigger {
28    /// Non-allowlisted git operation evaluated by AI review first under `auto` mode.
29    GitReview { subcommand: String },
30    /// Obviously irreversible / destructive git operation (`reset --hard`, `clean -f`, `checkout --`, `restore`, `stash drop/clear`, `branch -D`, `push --force`).
31    GitDestructive { subcommand: String },
32    /// Recursive or wildcard file deletion (`rm -rf`, `rm *.rs`, etc.).
33    RecursiveDelete { target: Option<String> },
34    /// Privilege escalation (`sudo`, `su`) or dangerous environment/config injection.
35    PrivilegeOrEnvInjection { detail: String },
36    /// Nested shell invocation whose inner commands are opaque to single-level inspection.
37    NestedShell { executable: String },
38    /// Shell script could not be parsed reliably (fail-closed).
39    UnparseableShell,
40}
41
42impl ActionReviewTrigger {
43    /// Returns whether this trigger may be remembered for the current session.
44    ///
45    /// Action-review triggers stay action-scoped.
46    #[must_use]
47    pub const fn is_session_grantable(&self) -> bool {
48        false
49    }
50
51    /// Returns whether this trigger represents a high-risk / destructive action
52    /// that should default to `Deny` in interactive review UIs.
53    #[must_use]
54    pub const fn is_high_risk(&self) -> bool {
55        !matches!(self, Self::GitReview { .. })
56    }
57
58    /// Returns a concise human-readable label for prompts and review views.
59    #[must_use]
60    pub fn summary(&self) -> String {
61        match self {
62            Self::GitReview { subcommand } => format!("git operation review (git {subcommand})"),
63            Self::GitDestructive { subcommand } => {
64                format!("destructive git operation (git {subcommand})")
65            }
66            Self::RecursiveDelete {
67                target: Some(target),
68            } => {
69                format!("recursive or wildcard delete ({target})")
70            }
71            Self::RecursiveDelete { target: None } => "recursive or wildcard delete".to_owned(),
72            Self::PrivilegeOrEnvInjection { detail } => {
73                format!("privilege or environment injection ({detail})")
74            }
75            Self::NestedShell { executable } => {
76                format!("nested shell invocation ({executable})")
77            }
78            Self::UnparseableShell => "unparseable shell script (fail-closed review)".to_owned(),
79        }
80    }
81}
82
83/// Classifies all concrete AST-based action-review triggers for one process intent.
84#[must_use]
85pub fn classify_process_action_review_triggers(
86    intent: &ProcessActionIntent,
87) -> Vec<ActionReviewTrigger> {
88    let mut triggers = Vec::new();
89    collect_high_risk_triggers(intent.argv(), &mut triggers);
90    triggers
91}
92
93/// Formats a compact human-readable reason sentence from structured triggers.
94#[must_use]
95pub fn summarize_action_review_triggers(triggers: &[ActionReviewTrigger]) -> String {
96    if triggers.is_empty() {
97        return "action review required".to_owned();
98    }
99    let parts = triggers
100        .iter()
101        .map(ActionReviewTrigger::summary)
102        .collect::<Vec<_>>();
103    format!("Action review: {}", parts.join("; "))
104}
105
106fn collect_high_risk_triggers(argv: &[String], triggers: &mut Vec<ActionReviewTrigger>) {
107    if let Some(shell_input) = shell_like_process_input_from_argv(argv) {
108        collect_shell_triggers(shell_input.kind(), shell_input.script(), triggers);
109        return;
110    }
111    collect_direct_argv_triggers(argv, triggers);
112}
113
114fn collect_shell_triggers(kind: ShellKind, script: &str, triggers: &mut Vec<ActionReviewTrigger>) {
115    match kind {
116        ShellKind::Bash => {
117            let Some(analysis) = parse_bash_security_analysis(script) else {
118                push_unique(triggers, ActionReviewTrigger::UnparseableShell);
119                return;
120            };
121            if analysis.env_injection {
122                push_unique(
123                    triggers,
124                    ActionReviewTrigger::PrivilegeOrEnvInjection {
125                        detail: "dangerous environment override".to_owned(),
126                    },
127                );
128            }
129            for command in &analysis.commands {
130                collect_direct_argv_triggers(command, triggers);
131            }
132        }
133        #[cfg(windows)]
134        ShellKind::PowerShell => {
135            let Some(analysis) = analyze_powershell_script(script) else {
136                push_unique(triggers, ActionReviewTrigger::UnparseableShell);
137                return;
138            };
139            if analysis.env_or_eval_injection {
140                push_unique(
141                    triggers,
142                    ActionReviewTrigger::PrivilegeOrEnvInjection {
143                        detail: "PowerShell eval or environment injection".to_owned(),
144                    },
145                );
146            }
147            if analysis.has_destructive_delete {
148                push_unique(
149                    triggers,
150                    ActionReviewTrigger::RecursiveDelete { target: None },
151                );
152            }
153            for command in &analysis.commands {
154                collect_direct_argv_triggers(command, triggers);
155            }
156        }
157        #[cfg(windows)]
158        ShellKind::Cmd => {
159            push_unique(
160                triggers,
161                ActionReviewTrigger::NestedShell {
162                    executable: "cmd".to_owned(),
163                },
164            );
165        }
166    }
167}
168
169fn collect_direct_argv_triggers(argv: &[String], triggers: &mut Vec<ActionReviewTrigger>) {
170    if command_words_have_env_injection(argv) {
171        push_unique(
172            triggers,
173            ActionReviewTrigger::PrivilegeOrEnvInjection {
174                detail: "dangerous environment variable".to_owned(),
175            },
176        );
177    }
178    let argv = strip_shell_command_prefixes(argv);
179    let Some(executable) = argv.first().map(|argument| executable_name(argument)) else {
180        return;
181    };
182
183    if executable == "rm" {
184        if let Some(target) = rm_review_target(argv) {
185            push_unique(triggers, ActionReviewTrigger::RecursiveDelete { target });
186        }
187        return;
188    }
189
190    if PRIVILEGE_EXECUTABLES.contains(&executable.as_str()) {
191        push_unique(
192            triggers,
193            ActionReviewTrigger::PrivilegeOrEnvInjection { detail: executable },
194        );
195        return;
196    }
197
198    if NESTED_SHELL_EXECUTABLES.contains(&executable.as_str()) {
199        push_unique(triggers, ActionReviewTrigger::NestedShell { executable });
200        return;
201    }
202
203    if executable == "git"
204        && let Some(trigger) = classify_git_review_trigger(argv)
205    {
206        push_unique(triggers, trigger);
207    }
208}
209
210fn push_unique(triggers: &mut Vec<ActionReviewTrigger>, trigger: ActionReviewTrigger) {
211    if !triggers.contains(&trigger) {
212        triggers.push(trigger);
213    }
214}