merry-runtime 0.1.3

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
//! Structured action-review trigger classification for process intents.
//!
//! Replaces opaque boolean review gates with typed triggers so runtime policy,
//! AI review, and user-facing approval dialogs all know *why* a command paused
//! and whether a narrow session grant is permitted.

#[cfg(windows)]
use super::windows_shell::analyze_powershell_script;
use super::{
    git::classify_git_review_trigger,
    rm_review_target,
    shell::{
        ShellKind, command_words_have_env_injection, executable_name, parse_bash_security_analysis,
        shell_like_process_input_from_argv,
    },
    strip_shell_command_prefixes,
};
use crate::ProcessActionIntent;
use serde::{Deserialize, Serialize};

const PRIVILEGE_EXECUTABLES: &[&str] = &["su", "sudo"];
const NESTED_SHELL_EXECUTABLES: &[&str] = &["bash", "cmd", "powershell", "pwsh", "sh", "zsh"];

/// Concrete reason why a process action requires an independent action review.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ActionReviewTrigger {
    /// Non-allowlisted git operation evaluated by AI review first under `auto` mode.
    GitReview { subcommand: String },
    /// Obviously irreversible / destructive git operation (`reset --hard`, `clean -f`, `checkout --`, `restore`, `stash drop/clear`, `branch -D`, `push --force`).
    GitDestructive { subcommand: String },
    /// Recursive or wildcard file deletion (`rm -rf`, `rm *.rs`, etc.).
    RecursiveDelete { target: Option<String> },
    /// Privilege escalation (`sudo`, `su`) or dangerous environment/config injection.
    PrivilegeOrEnvInjection { detail: String },
    /// Nested shell invocation whose inner commands are opaque to single-level inspection.
    NestedShell { executable: String },
    /// Shell script could not be parsed reliably (fail-closed).
    UnparseableShell,
}

impl ActionReviewTrigger {
    /// Returns whether this trigger may be remembered for the current session.
    ///
    /// Action-review triggers stay action-scoped.
    #[must_use]
    pub const fn is_session_grantable(&self) -> bool {
        false
    }

    /// Returns whether this trigger represents a high-risk / destructive action
    /// that should default to `Deny` in interactive review UIs.
    #[must_use]
    pub const fn is_high_risk(&self) -> bool {
        !matches!(self, Self::GitReview { .. })
    }

    /// Returns a concise human-readable label for prompts and review views.
    #[must_use]
    pub fn summary(&self) -> String {
        match self {
            Self::GitReview { subcommand } => format!("git operation review (git {subcommand})"),
            Self::GitDestructive { subcommand } => {
                format!("destructive git operation (git {subcommand})")
            }
            Self::RecursiveDelete {
                target: Some(target),
            } => {
                format!("recursive or wildcard delete ({target})")
            }
            Self::RecursiveDelete { target: None } => "recursive or wildcard delete".to_owned(),
            Self::PrivilegeOrEnvInjection { detail } => {
                format!("privilege or environment injection ({detail})")
            }
            Self::NestedShell { executable } => {
                format!("nested shell invocation ({executable})")
            }
            Self::UnparseableShell => "unparseable shell script (fail-closed review)".to_owned(),
        }
    }
}

/// Classifies all concrete AST-based action-review triggers for one process intent.
#[must_use]
pub fn classify_process_action_review_triggers(
    intent: &ProcessActionIntent,
) -> Vec<ActionReviewTrigger> {
    let mut triggers = Vec::new();
    collect_high_risk_triggers(intent.argv(), &mut triggers);
    triggers
}

/// Formats a compact human-readable reason sentence from structured triggers.
#[must_use]
pub fn summarize_action_review_triggers(triggers: &[ActionReviewTrigger]) -> String {
    if triggers.is_empty() {
        return "action review required".to_owned();
    }
    let parts = triggers
        .iter()
        .map(ActionReviewTrigger::summary)
        .collect::<Vec<_>>();
    format!("Action review: {}", parts.join("; "))
}

fn collect_high_risk_triggers(argv: &[String], triggers: &mut Vec<ActionReviewTrigger>) {
    if let Some(shell_input) = shell_like_process_input_from_argv(argv) {
        collect_shell_triggers(shell_input.kind(), shell_input.script(), triggers);
        return;
    }
    collect_direct_argv_triggers(argv, triggers);
}

fn collect_shell_triggers(kind: ShellKind, script: &str, triggers: &mut Vec<ActionReviewTrigger>) {
    match kind {
        ShellKind::Bash => {
            let Some(analysis) = parse_bash_security_analysis(script) else {
                push_unique(triggers, ActionReviewTrigger::UnparseableShell);
                return;
            };
            if analysis.env_injection {
                push_unique(
                    triggers,
                    ActionReviewTrigger::PrivilegeOrEnvInjection {
                        detail: "dangerous environment override".to_owned(),
                    },
                );
            }
            for command in &analysis.commands {
                collect_direct_argv_triggers(command, triggers);
            }
        }
        #[cfg(windows)]
        ShellKind::PowerShell => {
            let Some(analysis) = analyze_powershell_script(script) else {
                push_unique(triggers, ActionReviewTrigger::UnparseableShell);
                return;
            };
            if analysis.env_or_eval_injection {
                push_unique(
                    triggers,
                    ActionReviewTrigger::PrivilegeOrEnvInjection {
                        detail: "PowerShell eval or environment injection".to_owned(),
                    },
                );
            }
            if analysis.has_destructive_delete {
                push_unique(
                    triggers,
                    ActionReviewTrigger::RecursiveDelete { target: None },
                );
            }
            for command in &analysis.commands {
                collect_direct_argv_triggers(command, triggers);
            }
        }
        #[cfg(windows)]
        ShellKind::Cmd => {
            push_unique(
                triggers,
                ActionReviewTrigger::NestedShell {
                    executable: "cmd".to_owned(),
                },
            );
        }
    }
}

fn collect_direct_argv_triggers(argv: &[String], triggers: &mut Vec<ActionReviewTrigger>) {
    if command_words_have_env_injection(argv) {
        push_unique(
            triggers,
            ActionReviewTrigger::PrivilegeOrEnvInjection {
                detail: "dangerous environment variable".to_owned(),
            },
        );
    }
    let argv = strip_shell_command_prefixes(argv);
    let Some(executable) = argv.first().map(|argument| executable_name(argument)) else {
        return;
    };

    if executable == "rm" {
        if let Some(target) = rm_review_target(argv) {
            push_unique(triggers, ActionReviewTrigger::RecursiveDelete { target });
        }
        return;
    }

    if PRIVILEGE_EXECUTABLES.contains(&executable.as_str()) {
        push_unique(
            triggers,
            ActionReviewTrigger::PrivilegeOrEnvInjection { detail: executable },
        );
        return;
    }

    if NESTED_SHELL_EXECUTABLES.contains(&executable.as_str()) {
        push_unique(triggers, ActionReviewTrigger::NestedShell { executable });
        return;
    }

    if executable == "git"
        && let Some(trigger) = classify_git_review_trigger(argv)
    {
        push_unique(triggers, trigger);
    }
}

fn push_unique(triggers: &mut Vec<ActionReviewTrigger>, trigger: ActionReviewTrigger) {
    if !triggers.contains(&trigger) {
        triggers.push(trigger);
    }
}