AI coding agents can edit files, run shell commands, and touch infrastructure. One bad rm -rf, force-push, or docker compose down -v can wipe hours of work or production data.
| 1 | # SPDX-License-Identifier: MIT |
| 2 | """Core evaluation pipeline: normalize → parse → detect → policy → decision.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | from pathlib import Path |
| 7 | |
| 8 | from agent_guard.config import GuardConfig, load_config |
| 9 | from agent_guard.models import ( |
| 10 | Decision, |
| 11 | GuardResult, |
| 12 | OperationType, |
| 13 | ParsedCommand, |
| 14 | RiskLevel, |
| 15 | ) |
| 16 | from agent_guard.normalizer import normalize_command |
| 17 | from agent_guard.parser import parse_argv, parse_command |
| 18 | from agent_guard.policies import apply_policy |
| 19 | from agent_guard.redactor import redact |
| 20 | from agent_guard.risk import calculate_score, resolve_risk |
| 21 | from agent_guard.rules import run_all_rules |
| 22 | |
| 23 | |
| 24 | def _infer_operation(parsed: ParsedCommand, result_decision_rule: str | None) -> OperationType: |
| 25 | prog = parsed.program.lower().replace("\\", "/").split("/")[-1] |
| 26 | if prog.endswith(".exe"): |
| 27 | prog = prog[:-4] |
| 28 | (parsed.subcommand or "").lower() |
| 29 | |
| 30 | if prog == "git": |
| 31 | return OperationType.GIT_OPERATION |
| 32 | if prog in {"docker", "docker-compose", "podman"}: |
| 33 | return OperationType.DOCKER_OPERATION |
| 34 | if prog in {"curl", "wget", "ssh", "scp", "rsync", "nc", "netcat"}: |
| 35 | return OperationType.NETWORK_OPERATION |
| 36 | if prog in {"rm", "rmdir", "del", "rd"} or "rmtree" in parsed.raw.lower(): |
| 37 | if any(f for f in parsed.flags if "r" in f.lower()): |
| 38 | return OperationType.DIRECTORY_DELETE |
| 39 | return OperationType.FILE_DELETE |
| 40 | if result_decision_rule and "secret" in (result_decision_rule or ""): |
| 41 | return OperationType.SECRET_ACCESS |
| 42 | if "drop" in parsed.raw.lower() or "flushall" in parsed.raw.lower(): |
| 43 | return OperationType.DATABASE_OPERATION |
| 44 | if prog: |
| 45 | return OperationType.COMMAND |
| 46 | return OperationType.UNKNOWN |
| 47 | |
| 48 | |
| 49 | def evaluate_parsed(parsed: ParsedCommand, config: GuardConfig) -> GuardResult: |
| 50 | """Evaluate an already-parsed command against config/rules.""" |
| 51 | findings = run_all_rules(parsed, config) |
| 52 | score = calculate_score(findings) |
| 53 | risk = resolve_risk(findings, score) |
| 54 | policy = config.to_policy() |
| 55 | decision = apply_policy(findings, policy, risk) |
| 56 | |
| 57 | # Filter ALLOW-only low noise when we also have stronger findings |
| 58 | [f for f in findings if f.decision != Decision.ALLOW or f.risk.rank > 0] |
| 59 | primary = None |
| 60 | if findings: |
| 61 | # Pick most restrictive finding as primary explanation |
| 62 | primary = max( |
| 63 | findings, |
| 64 | key=lambda f: ( |
| 65 | {"BLOCK": 2, "WARN": 1, "ALLOW": 0}[f.decision.value], |
| 66 | f.risk.rank, |
| 67 | f.score_delta, |
| 68 | ), |
| 69 | ) |
| 70 | |
| 71 | if decision == Decision.ALLOW and not findings: |
| 72 | return GuardResult( |
| 73 | decision=Decision.ALLOW, |
| 74 | risk=RiskLevel.LOW, |
| 75 | operation=_infer_operation(parsed, None), |
| 76 | rule_id=None, |
| 77 | reason="No risky patterns detected.", |
| 78 | matched_policy=policy.name, |
| 79 | score=score, |
| 80 | command=redact(parsed.raw), |
| 81 | ) |
| 82 | |
| 83 | reason = primary.reason if primary else "Policy evaluation complete." |
| 84 | # Spec-friendly reason prefixes for common cases |
| 85 | if primary and primary.rule_id == "git.force_push_protected": |
| 86 | reason = ( |
| 87 | f"Protected branch force-push detected.\n\nBranch:\n{primary.target}\n\n" |
| 88 | f"Reason:\n{primary.reason}" |
| 89 | ) |
| 90 | |
| 91 | suggestions: list[str] = [] |
| 92 | detected: list[str] = [] |
| 93 | for f in findings: |
| 94 | suggestions.extend(f.suggestions) |
| 95 | detected.extend(f.detected) |
| 96 | |
| 97 | # Deduplicate |
| 98 | suggestions = list(dict.fromkeys(suggestions)) |
| 99 | detected = list(dict.fromkeys(detected)) |
| 100 | |
| 101 | op = _infer_operation(parsed, primary.rule_id if primary else None) |
| 102 | if primary and primary.category == "secret_access": |
| 103 | op = OperationType.SECRET_ACCESS |
| 104 | if primary and primary.category == "database_destructive": |
| 105 | op = OperationType.DATABASE_OPERATION |
| 106 | |
| 107 | return GuardResult( |
| 108 | decision=decision, |
| 109 | risk=risk if findings else RiskLevel.LOW, |
| 110 | operation=op, |
| 111 | rule_id=primary.rule_id if primary else None, |
| 112 | reason=redact(reason), |
| 113 | target=primary.target if primary else None, |
| 114 | suggestions=suggestions, |
| 115 | matched_policy=policy.name, |
| 116 | detected=detected, |
| 117 | findings=findings, |
| 118 | score=score, |
| 119 | command=redact(parsed.raw), |
| 120 | ) |
| 121 | |
| 122 | |
| 123 | def evaluate_command( |
| 124 | command: str, |
| 125 | config: GuardConfig | None = None, |
| 126 | *, |
| 127 | project_root: Path | None = None, |
| 128 | ) -> GuardResult: |
| 129 | """ |
| 130 | Analyze a command string. NEVER executes the command. |
| 131 | """ |
| 132 | cfg = config or load_config(project_root=project_root) |
| 133 | normalized = normalize_command(command) |
| 134 | parsed = parse_command(normalized) |
| 135 | return evaluate_parsed(parsed, cfg) |
| 136 | |
| 137 | |
| 138 | def evaluate_argv( |
| 139 | argv: list[str], |
| 140 | config: GuardConfig | None = None, |
| 141 | *, |
| 142 | project_root: Path | None = None, |
| 143 | ) -> GuardResult: |
| 144 | """Analyze an argv list. NEVER executes the command.""" |
| 145 | cfg = config or load_config(project_root=project_root) |
| 146 | parsed = parse_argv(argv) |
| 147 | return evaluate_parsed(parsed, cfg) |
| 148 | |
| 149 | |
| 150 | def evaluate_file_operation( |
| 151 | operation: str, |
| 152 | path: str, |
| 153 | config: GuardConfig | None = None, |
| 154 | *, |
| 155 | project_root: Path | None = None, |
| 156 | ) -> GuardResult: |
| 157 | """Analyze a declared file operation without executing it.""" |
| 158 | cfg = config or load_config(project_root=project_root) |
| 159 | op = operation.strip().lower() |
| 160 | if op in {"delete", "remove", "rm"}: |
| 161 | # Synthesize a command-like string for rule reuse |
| 162 | synthetic = f"rm -rf {path}" |
| 163 | elif op in {"read", "cat"}: |
| 164 | synthetic = f"cat {path}" |
| 165 | elif op in {"write"}: |
| 166 | synthetic = f"tee {path}" |
| 167 | else: |
| 168 | synthetic = f"{op} {path}" |
| 169 | return evaluate_command(synthetic, cfg) |