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 | from __future__ import annotations |
| 3 | |
| 4 | import json |
| 5 | |
| 6 | from agent_guard.config import GuardConfig |
| 7 | from agent_guard.evaluator import evaluate_command |
| 8 | from agent_guard.models import Decision |
| 9 | from agent_guard.output import ( |
| 10 | decision_exit_code, |
| 11 | format_result_json, |
| 12 | format_result_text, |
| 13 | format_rules_json, |
| 14 | ) |
| 15 | from agent_guard.rules import all_rule_definitions |
| 16 | |
| 17 | |
| 18 | def test_format_text_explainable(config: GuardConfig) -> None: |
| 19 | r = evaluate_command("rm -rf /", config) |
| 20 | text = format_result_text(r) |
| 21 | assert "BLOCK" in text |
| 22 | assert "Risk:" in text |
| 23 | assert "Reason:" in text |
| 24 | |
| 25 | |
| 26 | def test_format_json_no_ansi(config: GuardConfig) -> None: |
| 27 | r = evaluate_command("git reset --hard HEAD", config) |
| 28 | raw = format_result_json(r) |
| 29 | assert "\x1b" not in raw |
| 30 | data = json.loads(raw) |
| 31 | assert data["decision"] in {"ALLOW", "WARN", "BLOCK"} |
| 32 | assert "risk" in data |
| 33 | |
| 34 | |
| 35 | def test_json_redacts_secrets(config: GuardConfig) -> None: |
| 36 | r = evaluate_command( |
| 37 | "export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", |
| 38 | config, |
| 39 | ) |
| 40 | raw = format_result_json(r) |
| 41 | assert "wJalrXUtnFEMI" not in raw |
| 42 | |
| 43 | |
| 44 | def test_exit_codes() -> None: |
| 45 | assert decision_exit_code(Decision.ALLOW) == 0 |
| 46 | assert decision_exit_code(Decision.WARN) == 10 |
| 47 | assert decision_exit_code(Decision.BLOCK) == 20 |
| 48 | |
| 49 | |
| 50 | def test_rules_json() -> None: |
| 51 | data = json.loads(format_rules_json(list(all_rule_definitions()))) |
| 52 | assert isinstance(data, list) |
| 53 | assert data |
| 54 | assert "id" in data[0] |