merry-runtime 0.1.3

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
//! Git subcommand parsing, safe-allowlist direct pass, and action-review trigger classification.
//!
//! Instead of trying to blacklist every destructive flag combination (which is
//! impossible to enumerate completely), this module keeps a small allowlist of
//! clearly safe, reversible local git commands that pass directly without review.
//! Everything else enters permission review (handled by AI review first under
//! `--permission-mode auto`, escalating to the user only when genuinely risky).

use super::{is_positive_decimal, is_workspace_relative_file_argument};

/// Read-only git subcommands that never mutate the working tree, refs, or remotes.
const SAFE_READ_ONLY_GIT_SUBCOMMANDS: &[&str] = &[
    "blame",
    "cat-file",
    "check-ignore",
    "describe",
    "diff",
    "for-each-ref",
    "grep",
    "log",
    "ls-files",
    "ls-tree",
    "merge-base",
    "name-rev",
    "reflog",
    "rev-list",
    "rev-parse",
    "shortlog",
    "show",
    "status",
];

/// Clearly reversible local development mutations that pass directly without review.
const SAFE_LOCAL_DEV_GIT_SUBCOMMANDS: &[&str] = &["add", "apply", "commit", "fetch", "mv", "rm"];

pub(super) fn is_read_only_git_command(subcommand: &str, args: &[String]) -> bool {
    match subcommand {
        "status" => {
            let mut short = false;
            let mut branch = false;
            for argument in args {
                match argument.as_str() {
                    "--short" if !short => short = true,
                    "--branch" if !branch => branch = true,
                    _ => return false,
                }
            }
            true
        }
        "branch" => matches!(args, [arg] if arg.as_str() == "--show-current"),
        "log" => args
            .iter()
            .all(|arg| arg.as_str() == "--oneline" || is_git_count_arg(arg)),
        "diff" => is_read_only_git_diff_args(args),
        "show" => is_read_only_git_show_args(args),
        _ => false,
    }
}

fn is_git_count_arg(argument: &str) -> bool {
    let Some(count) = argument.strip_prefix('-') else {
        return false;
    };
    is_positive_decimal(count)
}

fn is_read_only_git_diff_args(args: &[String]) -> bool {
    match args {
        [] => true,
        [separator, path] if separator.as_str() == "--" => {
            is_workspace_relative_file_argument(path)
        }
        _ => false,
    }
}

fn is_read_only_git_show_args(args: &[String]) -> bool {
    match args {
        [arg] => !arg.starts_with('-') && !arg.contains(':'),
        [stat, rev] if stat.as_str() == "--stat" => !rev.starts_with('-') && !rev.contains(':'),
        _ => false,
    }
}

pub(super) fn git_invocation_is_forbidden(argv: &[String]) -> bool {
    classify_git_review_trigger(argv).is_some()
}

pub(super) fn classify_git_review_trigger(
    argv: &[String],
) -> Option<super::triggers::ActionReviewTrigger> {
    if let Some(override_flag) = dangerous_git_global_override(argv) {
        return Some(
            super::triggers::ActionReviewTrigger::PrivilegeOrEnvInjection {
                detail: format!("git global override ({override_flag})"),
            },
        );
    }
    let (subcommand, sub_args) = git_subcommand_and_args(argv)?;
    if is_safe_direct_git_command(subcommand, sub_args) {
        return None;
    }

    if is_obviously_destructive_git(subcommand, sub_args) {
        return Some(super::triggers::ActionReviewTrigger::GitDestructive {
            subcommand: subcommand.to_owned(),
        });
    }

    Some(super::triggers::ActionReviewTrigger::GitReview {
        subcommand: subcommand.to_owned(),
    })
}

/// Small allowlist of obviously safe/reversible local git commands that bypass
/// review completely. Anything outside this allowlist goes to AI review first.
fn is_safe_direct_git_command(subcommand: &str, args: &[String]) -> bool {
    if SAFE_READ_ONLY_GIT_SUBCOMMANDS.contains(&subcommand)
        || SAFE_LOCAL_DEV_GIT_SUBCOMMANDS.contains(&subcommand)
    {
        return true;
    }
    match subcommand {
        "branch" => is_safe_git_branch(args),
        "remote" => is_safe_git_remote(args),
        "tag" => is_safe_git_tag(args),
        "switch" => !args
            .iter()
            .take_while(|arg| arg.as_str() != "--")
            .any(|arg| {
                matches!(arg.as_str(), "--force" | "--discard-changes" | "-C")
                    || has_short_flag_token(arg, 'f')
            }),
        "checkout" => is_safe_git_checkout_create_branch(args),
        "stash" => is_safe_git_stash(args),
        "restore" => is_staged_only_git_restore(args),
        "reset" => is_soft_git_reset(args),
        _ => false,
    }
}

fn is_safe_git_branch(args: &[String]) -> bool {
    // Allow read-only listing and `-d` (safe merged-only delete); send `-D` / `-f` / `-m` to review.
    let mut saw_only_safe = true;
    for arg in args {
        if matches!(
            arg.as_str(),
            "--show-current"
                | "--list"
                | "--all"
                | "--remotes"
                | "--verbose"
                | "-a"
                | "-r"
                | "-v"
                | "-vv"
                | "-l"
        ) {
            continue;
        }
        saw_only_safe = false;
        break;
    }
    saw_only_safe
}

fn is_safe_git_remote(args: &[String]) -> bool {
    args.is_empty()
        || args
            .iter()
            .all(|arg| matches!(arg.as_str(), "-v" | "--verbose"))
}

fn is_safe_git_tag(args: &[String]) -> bool {
    args.is_empty() || matches!(args.first().map(String::as_str), Some("-l" | "--list"))
}

fn is_safe_git_checkout_create_branch(args: &[String]) -> bool {
    // `git checkout -b <new-branch> [start-point]` without force or `--` pathspec.
    matches!(args.first().map(String::as_str), Some("-b"))
        && args.len() >= 2
        && !args
            .iter()
            .any(|arg| arg == "--" || arg == "--force" || has_short_flag_token(arg, 'f'))
}

fn is_safe_git_stash(args: &[String]) -> bool {
    let first_op = args
        .iter()
        .find(|arg| !arg.starts_with('-'))
        .map(String::as_str);
    matches!(
        first_op,
        None | Some("list" | "show" | "push" | "pop" | "apply")
    )
}

fn is_staged_only_git_restore(args: &[String]) -> bool {
    let mut staged = false;
    let mut worktree = false;
    for arg in args.iter().take_while(|arg| arg.as_str() != "--") {
        if arg == "--staged" || has_short_flag_token(arg, 'S') {
            staged = true;
        }
        if arg == "--worktree" || has_short_flag_token(arg, 'W') {
            worktree = true;
        }
    }
    staged && !worktree
}

fn is_soft_git_reset(args: &[String]) -> bool {
    let mut soft = false;
    for arg in args.iter().take_while(|arg| arg.as_str() != "--") {
        if arg == "--soft" {
            soft = true;
        } else if matches!(arg.as_str(), "--hard" | "--merge") {
            return false;
        }
    }
    soft
}

/// Identifies the most obvious irreversible / high-risk git operations so
/// interactive review UIs default them to `Deny`. Non-obvious commands still
/// enter review via `GitReview` (evaluated by AI review first under `auto`).
fn is_obviously_destructive_git(subcommand: &str, args: &[String]) -> bool {
    match subcommand {
        "reset" => args
            .iter()
            .take_while(|arg| arg.as_str() != "--")
            .any(|arg| matches!(arg.as_str(), "--hard" | "--merge")),
        "clean" => args
            .iter()
            .take_while(|arg| arg.as_str() != "--")
            .any(|arg| arg == "--force" || has_short_flag_token(arg, 'f')),
        "checkout" => args.iter().any(|arg| {
            matches!(arg.as_str(), "--" | "--force" | "--ours" | "--theirs" | ".")
                || has_short_flag_token(arg, 'f')
        }),
        "restore" => !is_staged_only_git_restore(args),
        "stash" => {
            let first_op = args
                .iter()
                .find(|arg| !arg.starts_with('-'))
                .map(String::as_str);
            matches!(first_op, Some("drop" | "clear"))
        }
        "branch" => args
            .iter()
            .take_while(|arg| arg.as_str() != "--")
            .any(|arg| has_short_flag_token(arg, 'D')),
        "push" => args.iter().any(|arg| {
            matches!(
                arg.as_str(),
                "--force" | "--force-with-lease" | "--force-if-includes" | "--delete" | "--mirror"
            ) || arg.starts_with("--force-with-lease=")
                || has_short_flag_token(arg, 'f')
                || has_short_flag_token(arg, 'd')
                || arg.starts_with(':')
                || arg.starts_with('+')
        }),
        _ => false,
    }
}

fn has_short_flag_token(arg: &str, needle: char) -> bool {
    arg.strip_prefix('-')
        .filter(|rest| !rest.is_empty() && !rest.starts_with('-'))
        .is_some_and(|short| short.contains(needle))
}

/// Detects global git flags before the subcommand that inject config, execute
/// arbitrary helpers, or redirect repository metadata paths.
fn dangerous_git_global_override(argv: &[String]) -> Option<&str> {
    let mut index = 1;
    while let Some(arg) = argv.get(index) {
        if matches!(
            arg.as_str(),
            "-c" | "--config-env" | "--exec-path" | "--git-dir" | "--work-tree"
        ) || arg.starts_with("-c")
            || arg.starts_with("--config-env=")
            || arg.starts_with("--exec-path=")
            || arg.starts_with("--git-dir=")
            || arg.starts_with("--work-tree=")
        {
            return Some(arg.as_str());
        }
        if matches!(arg.as_str(), "-C" | "--namespace" | "--super-prefix") {
            index += 2;
            continue;
        }
        if arg.starts_with('-') {
            index += 1;
            continue;
        }
        break;
    }
    None
}

/// Returns the git subcommand and its trailing arguments, skipping recognized
/// global git options before the subcommand.
fn git_subcommand_and_args(argv: &[String]) -> Option<(&str, &[String])> {
    let mut index = 1;
    while let Some(arg) = argv.get(index) {
        if matches!(
            arg.as_str(),
            "-C" | "-c"
                | "--git-dir"
                | "--work-tree"
                | "--namespace"
                | "--super-prefix"
                | "--exec-path"
                | "--config-env"
        ) {
            index += 2;
            continue;
        }
        if arg.starts_with('-') {
            index += 1;
            continue;
        }
        return Some((arg.as_str(), &argv[index + 1..]));
    }
    None
}