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 | """Deterministic risk scoring.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | from agent_guard.models import Finding, RiskLevel |
| 7 | |
| 8 | # Score signal constants (documented for auditability) |
| 9 | SCORE_ROOT_DELETION = 100 |
| 10 | SCORE_RECURSIVE_DELETION = 60 |
| 11 | SCORE_PROTECTED_PATH = 50 |
| 12 | SCORE_SECRET_ACCESS = 50 |
| 13 | SCORE_PRODUCTION_DATABASE = 100 |
| 14 | SCORE_FORCE_PUSH_PROTECTED = 90 |
| 15 | SCORE_DOCKER_VOLUME_DELETE = 80 |
| 16 | SCORE_DESTRUCTIVE_GIT = 55 |
| 17 | SCORE_DATABASE_DESTRUCTIVE = 85 |
| 18 | SCORE_PRODUCTION_NETWORK = 70 |
| 19 | SCORE_SYSTEM_PATH = 80 |
| 20 | SCORE_SHELL_CHAIN = 15 |
| 21 | |
| 22 | |
| 23 | def score_to_risk(score: int) -> RiskLevel: |
| 24 | """Map numeric score to risk band.""" |
| 25 | if score >= 80: |
| 26 | return RiskLevel.CRITICAL |
| 27 | if score >= 50: |
| 28 | return RiskLevel.HIGH |
| 29 | if score >= 20: |
| 30 | return RiskLevel.MEDIUM |
| 31 | return RiskLevel.LOW |
| 32 | |
| 33 | |
| 34 | def calculate_score(findings: list[Finding]) -> int: |
| 35 | """Sum score deltas; floor at 0.""" |
| 36 | total = sum(max(0, f.score_delta) for f in findings) |
| 37 | return total |
| 38 | |
| 39 | |
| 40 | def resolve_risk(findings: list[Finding], score: int) -> RiskLevel: |
| 41 | """ |
| 42 | Combine calculated score with explicit finding risks. |
| 43 | |
| 44 | The highest explicit finding risk and the score-derived risk are compared; |
| 45 | the more severe wins. Rules may set CRITICAL explicitly to force the band. |
| 46 | """ |
| 47 | from_score = score_to_risk(score) |
| 48 | if not findings: |
| 49 | return from_score |
| 50 | explicit = max((f.risk for f in findings), key=lambda r: r.rank) |
| 51 | return explicit if explicit.rank >= from_score.rank else from_score |