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 | """Human and JSON output formatting with secret redaction.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | import json |
| 7 | import sys |
| 8 | from typing import Any, TextIO |
| 9 | |
| 10 | from rich.console import Console |
| 11 | from rich.panel import Panel |
| 12 | from rich.text import Text |
| 13 | |
| 14 | from agent_guard.models import Decision, GuardResult, RiskLevel |
| 15 | from agent_guard.redactor import redact |
| 16 | from agent_guard.rules import RuleDefinition |
| 17 | from agent_guard.scanner import ScanResult |
| 18 | |
| 19 | # Exit codes |
| 20 | EXIT_ALLOW = 0 |
| 21 | EXIT_WARN = 10 |
| 22 | EXIT_BLOCK = 20 |
| 23 | EXIT_ERROR = 30 |
| 24 | |
| 25 | |
| 26 | def decision_exit_code(decision: Decision) -> int: |
| 27 | return { |
| 28 | Decision.ALLOW: EXIT_ALLOW, |
| 29 | Decision.WARN: EXIT_WARN, |
| 30 | Decision.BLOCK: EXIT_BLOCK, |
| 31 | }[decision] |
| 32 | |
| 33 | |
| 34 | def format_result_text(result: GuardResult) -> str: |
| 35 | """Plain-text explainable output (no ANSI).""" |
| 36 | lines = [result.decision.value, ""] |
| 37 | lines.append(f"Risk: {result.risk.value}") |
| 38 | lines.append("") |
| 39 | lines.append("Reason:") |
| 40 | lines.append(redact(result.reason)) |
| 41 | if result.target: |
| 42 | lines.append("") |
| 43 | lines.append("Target:") |
| 44 | lines.append(redact(result.target)) |
| 45 | if result.detected: |
| 46 | lines.append("") |
| 47 | lines.append("Detected:") |
| 48 | for item in result.detected: |
| 49 | lines.append(redact(str(item))) |
| 50 | if result.rule_id: |
| 51 | lines.append("") |
| 52 | lines.append("Policy:") |
| 53 | lines.append(result.rule_id.replace(".", "-") if "." in result.rule_id else result.rule_id) |
| 54 | # Also show category-friendly name |
| 55 | if result.findings: |
| 56 | cat = result.findings[0].category.replace("_", "-") |
| 57 | if cat not in lines[-1]: |
| 58 | lines.append(cat) |
| 59 | if result.suggestions: |
| 60 | lines.append("") |
| 61 | lines.append("Suggestions:") |
| 62 | for s in result.suggestions: |
| 63 | lines.append(f"- {redact(s)}") |
| 64 | return "\n".join(lines).rstrip() + "\n" |
| 65 | |
| 66 | |
| 67 | def format_result_json(result: GuardResult) -> str: |
| 68 | data = result.to_dict() |
| 69 | # Ensure redaction on all string fields |
| 70 | return json.dumps(_redact_obj(data), indent=2, sort_keys=True) + "\n" |
| 71 | |
| 72 | |
| 73 | def _redact_obj(obj: Any) -> Any: |
| 74 | if isinstance(obj, str): |
| 75 | return redact(obj) |
| 76 | if isinstance(obj, list): |
| 77 | return [_redact_obj(x) for x in obj] |
| 78 | if isinstance(obj, dict): |
| 79 | return {k: _redact_obj(v) for k, v in obj.items()} |
| 80 | return obj |
| 81 | |
| 82 | |
| 83 | def format_result(result: GuardResult, *, json_mode: bool = False) -> str: |
| 84 | if json_mode: |
| 85 | return format_result_json(result) |
| 86 | return format_result_text(result) |
| 87 | |
| 88 | |
| 89 | def print_result( |
| 90 | result: GuardResult, |
| 91 | *, |
| 92 | json_mode: bool = False, |
| 93 | console: Console | None = None, |
| 94 | ) -> None: |
| 95 | text = format_result(result, json_mode=json_mode) |
| 96 | if json_mode: |
| 97 | sys.stdout.write(text) |
| 98 | return |
| 99 | out = console or Console(highlight=False) |
| 100 | color = { |
| 101 | Decision.ALLOW: "green", |
| 102 | Decision.WARN: "yellow", |
| 103 | Decision.BLOCK: "red", |
| 104 | }[result.decision] |
| 105 | out.print(Text(result.decision.value, style=f"bold {color}")) |
| 106 | out.print() |
| 107 | out.print(f"Risk: {result.risk.value}") |
| 108 | out.print() |
| 109 | out.print("Reason:") |
| 110 | out.print(redact(result.reason)) |
| 111 | if result.target: |
| 112 | out.print() |
| 113 | out.print("Target:") |
| 114 | out.print(redact(result.target)) |
| 115 | if result.detected: |
| 116 | out.print() |
| 117 | out.print("Detected:") |
| 118 | for item in result.detected: |
| 119 | out.print(redact(str(item))) |
| 120 | if result.findings: |
| 121 | primary = max( |
| 122 | result.findings, |
| 123 | key=lambda f: ({"BLOCK": 2, "WARN": 1, "ALLOW": 0}[f.decision.value], f.risk.rank), |
| 124 | ) |
| 125 | out.print() |
| 126 | out.print("Policy:") |
| 127 | out.print(primary.category.replace("_", "-")) |
| 128 | if result.suggestions: |
| 129 | out.print() |
| 130 | out.print("Suggestions:") |
| 131 | for s in result.suggestions: |
| 132 | out.print(f"- {redact(s)}") |
| 133 | |
| 134 | |
| 135 | def confirm_warn(result: GuardResult, stream: TextIO | None = None) -> bool: |
| 136 | """Interactive WARN confirmation. Default is No.""" |
| 137 | console = Console(file=stream or sys.stderr, highlight=False) |
| 138 | console.print() |
| 139 | console.print(Text(f"! {result.risk.value} RISK", style="bold yellow")) |
| 140 | console.print() |
| 141 | if result.command: |
| 142 | console.print("Command:") |
| 143 | console.print(redact(result.command)) |
| 144 | console.print() |
| 145 | console.print("Reason:") |
| 146 | console.print(redact(result.reason)) |
| 147 | console.print() |
| 148 | try: |
| 149 | answer = input("Continue? [y/N] ").strip().lower() |
| 150 | except EOFError: |
| 151 | return False |
| 152 | return answer in {"y", "yes"} |
| 153 | |
| 154 | |
| 155 | def format_rules_text(rules: list[RuleDefinition]) -> str: |
| 156 | lines: list[str] = [] |
| 157 | for rule in sorted(rules, key=lambda r: r.id): |
| 158 | lines.extend( |
| 159 | [ |
| 160 | f"ID: {rule.id}", |
| 161 | f"Category: {rule.category}", |
| 162 | f"Risk: {rule.risk.value}", |
| 163 | f"Default decision: {rule.default_decision.value}", |
| 164 | f"Description: {rule.description}", |
| 165 | "", |
| 166 | ] |
| 167 | ) |
| 168 | return "\n".join(lines) |
| 169 | |
| 170 | |
| 171 | def format_rules_json(rules: list[RuleDefinition]) -> str: |
| 172 | data = [ |
| 173 | { |
| 174 | "id": r.id, |
| 175 | "category": r.category, |
| 176 | "risk": r.risk.value, |
| 177 | "default_decision": r.default_decision.value, |
| 178 | "description": r.description, |
| 179 | } |
| 180 | for r in sorted(rules, key=lambda x: x.id) |
| 181 | ] |
| 182 | return json.dumps(data, indent=2, sort_keys=True) + "\n" |
| 183 | |
| 184 | |
| 185 | def format_scan_text(scan: ScanResult) -> str: |
| 186 | lines = [ |
| 187 | "Agent Guard Scan", |
| 188 | "----------------", |
| 189 | "", |
| 190 | "Project:", |
| 191 | scan.project_name, |
| 192 | "", |
| 193 | "Detected:", |
| 194 | "", |
| 195 | ] |
| 196 | if scan.detected: |
| 197 | for item in scan.detected: |
| 198 | lines.append(f"[+] {item}") |
| 199 | else: |
| 200 | lines.append("(none)") |
| 201 | lines.append("") |
| 202 | lines.append("Protected:") |
| 203 | if scan.protected: |
| 204 | for item in scan.protected: |
| 205 | lines.append(f"[+] {item}") |
| 206 | else: |
| 207 | lines.append("(none configured on disk)") |
| 208 | lines.append("") |
| 209 | lines.append("Potential risks:") |
| 210 | lines.append("") |
| 211 | if scan.risks: |
| 212 | for risk in scan.risks: |
| 213 | msg = redact(risk.message) |
| 214 | if risk.path: |
| 215 | msg = f"{msg}: {redact(risk.path)}" |
| 216 | lines.append(f"[!] {msg}") |
| 217 | else: |
| 218 | lines.append("[+] No obvious configuration risks found") |
| 219 | return "\n".join(lines) + "\n" |
| 220 | |
| 221 | |
| 222 | def format_scan_json(scan: ScanResult) -> str: |
| 223 | return json.dumps(_redact_obj(scan.to_dict()), indent=2, sort_keys=True) + "\n" |
| 224 | |
| 225 | |
| 226 | def risk_style(risk: RiskLevel) -> str: |
| 227 | return { |
| 228 | RiskLevel.LOW: "green", |
| 229 | RiskLevel.MEDIUM: "yellow", |
| 230 | RiskLevel.HIGH: "dark_orange", |
| 231 | RiskLevel.CRITICAL: "red", |
| 232 | }[risk] |
| 233 | |
| 234 | |
| 235 | def print_panel(title: str, body: str, console: Console | None = None) -> None: |
| 236 | c = console or Console() |
| 237 | c.print(Panel(redact(body), title=title)) |