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 | """Rule registry and shared rule protocol.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | from collections.abc import Callable, Sequence |
| 7 | from dataclasses import dataclass |
| 8 | from typing import Protocol |
| 9 | |
| 10 | from agent_guard.config import GuardConfig |
| 11 | from agent_guard.models import Decision, Finding, ParsedCommand, RiskLevel |
| 12 | |
| 13 | |
| 14 | class RuleContext(Protocol): |
| 15 | config: GuardConfig |
| 16 | command: ParsedCommand |
| 17 | raw: str |
| 18 | |
| 19 | |
| 20 | @dataclass(frozen=True) |
| 21 | class RuleDefinition: |
| 22 | """Metadata for a registered rule (for ``rules`` CLI).""" |
| 23 | |
| 24 | id: str |
| 25 | category: str |
| 26 | risk: RiskLevel |
| 27 | default_decision: Decision |
| 28 | description: str |
| 29 | |
| 30 | |
| 31 | RuleFunc = Callable[[ParsedCommand, GuardConfig], list[Finding]] |
| 32 | |
| 33 | _RULES: list[tuple[RuleDefinition, RuleFunc]] = [] |
| 34 | _RULE_DEFS: list[RuleDefinition] = [] |
| 35 | |
| 36 | |
| 37 | def register_rule(definition: RuleDefinition) -> Callable[[RuleFunc], RuleFunc]: |
| 38 | def decorator(func: RuleFunc) -> RuleFunc: |
| 39 | _RULES.append((definition, func)) |
| 40 | _RULE_DEFS.append(definition) |
| 41 | return func |
| 42 | |
| 43 | return decorator |
| 44 | |
| 45 | |
| 46 | def all_rule_definitions() -> Sequence[RuleDefinition]: |
| 47 | # Ensure rules modules are imported |
| 48 | _ensure_loaded() |
| 49 | return list(_RULE_DEFS) |
| 50 | |
| 51 | |
| 52 | def run_all_rules(command: ParsedCommand, config: GuardConfig) -> list[Finding]: |
| 53 | _ensure_loaded() |
| 54 | findings: list[Finding] = [] |
| 55 | for _defn, func in _RULES: |
| 56 | findings.extend(func(command, config)) |
| 57 | return findings |
| 58 | |
| 59 | |
| 60 | _loaded = False |
| 61 | |
| 62 | |
| 63 | def _ensure_loaded() -> None: |
| 64 | global _loaded |
| 65 | if _loaded: |
| 66 | return |
| 67 | # Import rule modules for side-effect registration |
| 68 | from agent_guard.rules import ( # noqa: F401 |
| 69 | database, |
| 70 | docker, |
| 71 | filesystem, |
| 72 | git, |
| 73 | network, |
| 74 | secrets, |
| 75 | shell, |
| 76 | ) |
| 77 | |
| 78 | _loaded = True |
| 79 | |
| 80 | |
| 81 | def reset_registry_for_tests() -> None: |
| 82 | """Test helper to clear load flag (rules stay registered).""" |
| 83 | global _loaded |
| 84 | _loaded = True # keep registered; just mark loaded |