@aigis-ai/cli 1.0.2 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +53 -0
- package/SKILL.md +20 -55
- package/bin/aigis.js +446 -59
- package/cli-python/LICENSE +21 -0
- package/cli-python/README.md +32 -0
- package/cli-python/aigis_cli/SKILL.md +70 -0
- package/cli-python/aigis_cli/__init__.py +3 -0
- package/cli-python/aigis_cli/__pycache__/__init__.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/annotate.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/build.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/checksum.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/classify.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/cli.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/fetch.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/init_ide.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/keywords.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/search.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/annotate.py +45 -0
- package/cli-python/aigis_cli/auto_verify.py +518 -0
- package/cli-python/aigis_cli/build.py +470 -0
- package/cli-python/aigis_cli/checksum.py +22 -0
- package/cli-python/aigis_cli/classify.py +192 -0
- package/cli-python/aigis_cli/cli.py +618 -0
- package/cli-python/aigis_cli/content/index/audit-scan.md +217 -0
- package/cli-python/aigis_cli/content/index/auto-verify-rules.json +439 -0
- package/cli-python/aigis_cli/content/index/context-rules.json +90 -0
- package/cli-python/aigis_cli/content/index/frameworks.md +82 -0
- package/cli-python/aigis_cli/content/index/guardrails.json +23 -0
- package/cli-python/aigis_cli/content/index/taxonomy.md +81 -0
- package/cli-python/aigis_cli/content/resolvers/triggers.json +229 -0
- package/{content/implement → cli-python/aigis_cli/content/skills/areas}/audit-logging.md +5 -0
- package/cli-python/aigis_cli/content/skills/areas/fallback-patterns.md +200 -0
- package/cli-python/aigis_cli/content/skills/areas/input-validation.md +380 -0
- package/cli-python/aigis_cli/content/skills/areas/pii-handling.md +189 -0
- package/cli-python/aigis_cli/content/skills/areas/rate-limiting.md +246 -0
- package/cli-python/aigis_cli/content/skills/core.md +62 -0
- package/cli-python/aigis_cli/content/skills/infrastructure/logging.md +202 -0
- package/cli-python/aigis_cli/content/skills/infrastructure/rate-limiting.md +169 -0
- package/cli-python/aigis_cli/content/skills/infrastructure/secrets.md +167 -0
- package/cli-python/aigis_cli/content/skills/workflows/fastapi-llm.md +86 -0
- package/cli-python/aigis_cli/content/templates/ai-impact-assessment.md +54 -0
- package/cli-python/aigis_cli/content/templates/intended-purpose-doc.md +39 -0
- package/cli-python/aigis_cli/content/templates/risk-characterization.md +34 -0
- package/cli-python/aigis_cli/content/templates/third-party-assessment.md +41 -0
- package/cli-python/aigis_cli/content/verify/checklist-audit-logging.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-bias-monitoring.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-confidence-scoring.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-data-integrity.md +12 -0
- package/cli-python/aigis_cli/content/verify/checklist-explainability.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-fallback-patterns.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-human-oversight.md +14 -0
- package/cli-python/aigis_cli/content/verify/checklist-input-validation.md +16 -0
- package/cli-python/aigis_cli/content/verify/checklist-monitoring.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-output-sanitization.md +14 -0
- package/cli-python/aigis_cli/content/verify/checklist-pii-handling.md +14 -0
- package/cli-python/aigis_cli/content/verify/checklist-prompt-security.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-rag-security.md +12 -0
- package/cli-python/aigis_cli/content/verify/checklist-rate-limiting.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-supply-chain.md +13 -0
- package/cli-python/aigis_cli/fetch.py +232 -0
- package/cli-python/aigis_cli/init_ide.py +159 -0
- package/cli-python/aigis_cli/keywords.py +73 -0
- package/cli-python/aigis_cli/search.py +69 -0
- package/cli-python/aigis_cli.egg-info/PKG-INFO +59 -0
- package/cli-python/aigis_cli.egg-info/SOURCES.txt +56 -0
- package/cli-python/aigis_cli.egg-info/dependency_links.txt +1 -0
- package/cli-python/aigis_cli.egg-info/entry_points.txt +2 -0
- package/cli-python/aigis_cli.egg-info/requires.txt +6 -0
- package/cli-python/aigis_cli.egg-info/top_level.txt +1 -0
- package/cli-python/dist/aigis_cli-1.0.3-py3-none-any.whl +0 -0
- package/cli-python/dist/aigis_cli-1.0.3.tar.gz +0 -0
- package/cli-python/pyproject.toml +49 -0
- package/content/index/audit-scan.md +21 -207
- package/content/index/auto-verify-rules.json +439 -0
- package/content/index/context-rules.json +90 -0
- package/content/resolvers/triggers.json +229 -0
- package/content/skills/areas/audit-logging.md +176 -0
- package/content/skills/areas/bias-monitoring.md +172 -0
- package/content/skills/areas/confidence-scoring.md +180 -0
- package/content/skills/areas/data-integrity.md +257 -0
- package/content/skills/areas/explainability.md +174 -0
- package/content/skills/areas/fallback-patterns.md +200 -0
- package/content/skills/areas/human-oversight.md +220 -0
- package/content/skills/areas/input-validation.md +380 -0
- package/content/skills/areas/monitoring.md +207 -0
- package/content/skills/areas/output-sanitization.md +183 -0
- package/content/skills/areas/pii-handling.md +189 -0
- package/content/skills/areas/prompt-security.md +153 -0
- package/content/skills/areas/rag-security.md +230 -0
- package/content/skills/areas/rate-limiting.md +246 -0
- package/content/skills/areas/supply-chain.md +193 -0
- package/content/skills/core.md +62 -0
- package/content/skills/infrastructure/logging.md +202 -0
- package/content/skills/infrastructure/rate-limiting.md +169 -0
- package/content/skills/infrastructure/secrets.md +167 -0
- package/content/skills/workflows/fastapi-llm.md +86 -0
- package/docs/resolvers.md +114 -0
- package/lib/auto-verify.js +378 -0
- package/lib/build.js +629 -0
- package/lib/checksum.js +39 -0
- package/lib/fetch.js +164 -9
- package/lib/init.js +141 -93
- package/lib/keywords.js +92 -130
- package/lib/special-recognizers.js +370 -0
- package/package.json +6 -2
- package/scripts/baseline-cursorrules.snapshot.txt +30 -0
- package/scripts/bootstrap-step-6-bench.js +85 -0
- package/scripts/check-content-sync.js +91 -0
- package/scripts/triggers.schema.json +50 -0
- package/scripts/validate-triggers.js +176 -0
- package/content/implement/fallback-patterns.md +0 -190
- package/content/implement/input-validation.md +0 -212
- package/content/implement/pii-handling.md +0 -207
- package/content/implement/rate-limiting.md +0 -217
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/bias-monitoring.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/confidence-scoring.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/data-integrity.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/explainability.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/human-oversight.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/monitoring.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/output-sanitization.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/prompt-security.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/rag-security.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/supply-chain.md +0 -0
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
"""Deterministic scanner for `aigis verify <area> --auto <path>`.
|
|
2
|
+
|
|
3
|
+
Python mirror of lib/auto-verify.js. The rules file (content/index/
|
|
4
|
+
auto-verify-rules.json) is shared — behavior must stay identical between
|
|
5
|
+
runtimes. Special recognizers live below as functions.
|
|
6
|
+
|
|
7
|
+
Philosophy: heuristic regex over project source files. Goal is catching
|
|
8
|
+
common overclaim patterns, not bulletproof static analysis.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
_THIS_DIR = Path(__file__).resolve().parent
|
|
19
|
+
_CONTENT_DIR = _THIS_DIR / "content"
|
|
20
|
+
|
|
21
|
+
DEFAULT_INCLUDE_EXTS = {
|
|
22
|
+
".py", ".js", ".ts", ".tsx", ".jsx", ".mjs", ".cjs",
|
|
23
|
+
".go", ".rb", ".java", ".kt",
|
|
24
|
+
}
|
|
25
|
+
DEFAULT_CONFIG_FILES = {
|
|
26
|
+
"package.json", "requirements.txt", "pyproject.toml", "Pipfile",
|
|
27
|
+
"Pipfile.lock", "poetry.lock", "go.mod", "Gemfile", "Gemfile.lock",
|
|
28
|
+
"pom.xml",
|
|
29
|
+
}
|
|
30
|
+
SKIP_DIRS = {
|
|
31
|
+
"node_modules", ".venv", "venv", "env", "__pycache__", ".pytest_cache",
|
|
32
|
+
"dist", "build", ".git", ".tox", "target", "coverage", ".next", ".nuxt",
|
|
33
|
+
".cache", ".idea", ".vscode",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _rules_path() -> Path:
|
|
38
|
+
return _CONTENT_DIR / "index" / "auto-verify-rules.json"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def load_rules() -> dict[str, Any]:
|
|
42
|
+
raw = _rules_path().read_text(encoding="utf-8")
|
|
43
|
+
parsed = json.loads(raw)
|
|
44
|
+
return {k: v for k, v in parsed.items() if not k.startswith("_schema_")}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _walk_files(root_dir: Path):
|
|
48
|
+
stack = [root_dir]
|
|
49
|
+
while stack:
|
|
50
|
+
d = stack.pop()
|
|
51
|
+
try:
|
|
52
|
+
entries = list(d.iterdir())
|
|
53
|
+
except OSError:
|
|
54
|
+
continue
|
|
55
|
+
for entry in entries:
|
|
56
|
+
if entry.is_dir():
|
|
57
|
+
if entry.name in SKIP_DIRS or entry.name.startswith("."):
|
|
58
|
+
continue
|
|
59
|
+
stack.append(entry)
|
|
60
|
+
elif entry.is_file():
|
|
61
|
+
if entry.suffix in DEFAULT_INCLUDE_EXTS or entry.name in DEFAULT_CONFIG_FILES:
|
|
62
|
+
yield entry
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _load_files(root_dir: Path) -> list[dict[str, Any]]:
|
|
66
|
+
out: list[dict[str, Any]] = []
|
|
67
|
+
for p in _walk_files(root_dir):
|
|
68
|
+
try:
|
|
69
|
+
content = p.read_text(encoding="utf-8", errors="replace")
|
|
70
|
+
except OSError:
|
|
71
|
+
continue
|
|
72
|
+
out.append({"path": str(p.relative_to(root_dir)), "absolutePath": str(p), "content": content})
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _matches_glob(file_path: str, glob: str) -> bool:
|
|
77
|
+
norm = file_path.replace("\\", "/")
|
|
78
|
+
pattern = glob.replace("\\", "/")
|
|
79
|
+
out = ""
|
|
80
|
+
i = 0
|
|
81
|
+
while i < len(pattern):
|
|
82
|
+
c = pattern[i]
|
|
83
|
+
if c == "*":
|
|
84
|
+
if i + 1 < len(pattern) and pattern[i + 1] == "*":
|
|
85
|
+
if i + 2 < len(pattern) and pattern[i + 2] == "/":
|
|
86
|
+
out += "(?:.*/)?"
|
|
87
|
+
i += 3
|
|
88
|
+
continue
|
|
89
|
+
out += ".*"
|
|
90
|
+
i += 2
|
|
91
|
+
continue
|
|
92
|
+
out += "[^/]*"
|
|
93
|
+
i += 1
|
|
94
|
+
continue
|
|
95
|
+
if c in ".+^${}()|[]":
|
|
96
|
+
out += "\\" + c
|
|
97
|
+
else:
|
|
98
|
+
out += c
|
|
99
|
+
i += 1
|
|
100
|
+
return re.match("^" + out + "$", norm) is not None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _exists_path_rule(rule: dict[str, Any], files: list[dict[str, Any]]) -> dict[str, Any]:
|
|
104
|
+
globs = rule.get("path_globs", [])
|
|
105
|
+
evidence = []
|
|
106
|
+
for f in files:
|
|
107
|
+
if any(_matches_glob(f["path"], g) for g in globs):
|
|
108
|
+
evidence.append({"file": f["path"], "line": 1, "snippet": "(path match)", "pattern": 0})
|
|
109
|
+
if len(evidence) >= 5:
|
|
110
|
+
break
|
|
111
|
+
return {
|
|
112
|
+
"status": "PASS" if evidence else "FAIL",
|
|
113
|
+
"evidence": evidence,
|
|
114
|
+
"matched_patterns": [0] if evidence else [],
|
|
115
|
+
"total_patterns": 1,
|
|
116
|
+
"inverse": False,
|
|
117
|
+
"require": "any",
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _scan_rule(rule: dict[str, Any], files: list[dict[str, Any]]) -> dict[str, Any]:
|
|
122
|
+
if rule.get("type") == "exists_path":
|
|
123
|
+
return _exists_path_rule(rule, files)
|
|
124
|
+
|
|
125
|
+
flags = re.MULTILINE
|
|
126
|
+
if not rule.get("case_sensitive"):
|
|
127
|
+
flags |= re.IGNORECASE
|
|
128
|
+
|
|
129
|
+
patterns = []
|
|
130
|
+
for p in rule.get("patterns", []):
|
|
131
|
+
try:
|
|
132
|
+
patterns.append(re.compile(p, flags))
|
|
133
|
+
except re.error:
|
|
134
|
+
patterns.append(re.compile(re.escape(p), flags))
|
|
135
|
+
|
|
136
|
+
require = rule.get("require", "any")
|
|
137
|
+
inverse = bool(rule.get("inverse"))
|
|
138
|
+
max_evidence = 5
|
|
139
|
+
|
|
140
|
+
matched_patterns: set[int] = set()
|
|
141
|
+
evidence: list[dict[str, Any]] = []
|
|
142
|
+
|
|
143
|
+
for f in files:
|
|
144
|
+
lines = f["content"].split("\n")
|
|
145
|
+
for i, re_obj in enumerate(patterns):
|
|
146
|
+
if i in matched_patterns and len(evidence) >= max_evidence:
|
|
147
|
+
continue
|
|
148
|
+
for m in re_obj.finditer(f["content"]):
|
|
149
|
+
matched_patterns.add(i)
|
|
150
|
+
if len(evidence) < max_evidence:
|
|
151
|
+
line = f["content"].count("\n", 0, m.start()) + 1
|
|
152
|
+
snippet = (lines[line - 1] if line - 1 < len(lines) else "").strip()[:160]
|
|
153
|
+
evidence.append({"file": f["path"], "line": line, "snippet": snippet, "pattern": i})
|
|
154
|
+
if len(evidence) >= max_evidence:
|
|
155
|
+
break
|
|
156
|
+
if len(evidence) >= max_evidence:
|
|
157
|
+
break
|
|
158
|
+
if len(evidence) >= max_evidence and (require == "any" or len(matched_patterns) == len(patterns)):
|
|
159
|
+
break
|
|
160
|
+
|
|
161
|
+
if require == "all":
|
|
162
|
+
passed = len(matched_patterns) == len(patterns)
|
|
163
|
+
else:
|
|
164
|
+
passed = len(matched_patterns) >= 1
|
|
165
|
+
if inverse:
|
|
166
|
+
passed = not passed
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
"status": "PASS" if passed else "FAIL",
|
|
170
|
+
"evidence": evidence,
|
|
171
|
+
"matched_patterns": sorted(matched_patterns),
|
|
172
|
+
"total_patterns": len(patterns),
|
|
173
|
+
"inverse": inverse,
|
|
174
|
+
"require": require,
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# ── Special recognizers ────────────────────────────────────────────────
|
|
179
|
+
|
|
180
|
+
_INJECTION_DETECTOR_RE = re.compile(
|
|
181
|
+
r"\b_?(?:check|detect|scan|run|test|is)_?(?:prompt_?)?injection[a-z_]*\b"
|
|
182
|
+
r"|INJECTION_PATTERN\s*\.\s*(?:search|match|test|exec)",
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _kill_switch_restart_latched(files: list[dict[str, Any]], ctx: dict[str, Any]) -> dict[str, Any]:
|
|
187
|
+
evidence: list[dict[str, Any]] = []
|
|
188
|
+
reasons: list[str] = []
|
|
189
|
+
|
|
190
|
+
for f in files:
|
|
191
|
+
lines = f["content"].split("\n")
|
|
192
|
+
for i, line in enumerate(lines):
|
|
193
|
+
if "@lru_cache" in line:
|
|
194
|
+
follow = "\n".join(lines[i + 1 : i + 6])
|
|
195
|
+
if re.search(r"def\s+(get_)?settings\b|->\s*Settings\b|return\s+Settings\s*\(", follow):
|
|
196
|
+
evidence.append({
|
|
197
|
+
"file": f["path"],
|
|
198
|
+
"line": i + 1,
|
|
199
|
+
"snippet": "\n".join(lines[i : min(i + 4, len(lines))]),
|
|
200
|
+
})
|
|
201
|
+
reasons.append("@lru_cache on Settings retrieval (pydantic-settings cached at first call)")
|
|
202
|
+
|
|
203
|
+
for f in files:
|
|
204
|
+
if re.search(r"^settings\s*=\s*Settings\s*\(\s*\)", f["content"], re.MULTILINE):
|
|
205
|
+
lines = f["content"].split("\n")
|
|
206
|
+
for i, line in enumerate(lines):
|
|
207
|
+
if re.search(r"settings\.(ai_system_enabled|kill_switch|ai_enabled|feature_flag)", line):
|
|
208
|
+
evidence.append({"file": f["path"], "line": i + 1, "snippet": line.strip()})
|
|
209
|
+
reasons.append("Module-level `settings = Settings()` read inside handler (frozen at import)")
|
|
210
|
+
break
|
|
211
|
+
|
|
212
|
+
for f in files:
|
|
213
|
+
lines = f["content"].split("\n")
|
|
214
|
+
for i, line in enumerate(lines):
|
|
215
|
+
if re.search(r"^(KILL_SWITCH|AI_ENABLED|AI_SYSTEM_ENABLED)\s*=\s*os\.getenv", line):
|
|
216
|
+
evidence.append({"file": f["path"], "line": i + 1, "snippet": line.strip()})
|
|
217
|
+
reasons.append("Module-level `<FLAG> = os.getenv(...)` (value frozen at import)")
|
|
218
|
+
|
|
219
|
+
rereads = False
|
|
220
|
+
for f in files:
|
|
221
|
+
if re.search(r"@app\.(get|post|put|delete)|@router\.(get|post|put|delete)", f["content"]):
|
|
222
|
+
if re.search(
|
|
223
|
+
r"^(?!\s*#).*os\.getenv\s*\(\s*['\"](?:AI_SYSTEM_ENABLED|KILL_SWITCH|AI_ENABLED)",
|
|
224
|
+
f["content"],
|
|
225
|
+
re.MULTILINE,
|
|
226
|
+
):
|
|
227
|
+
rereads = True
|
|
228
|
+
|
|
229
|
+
flagged = bool(evidence) and not rereads
|
|
230
|
+
if flagged:
|
|
231
|
+
notes = (
|
|
232
|
+
f"Kill switch appears restart-latched. Reasons: {'; '.join(sorted(set(reasons)))}. "
|
|
233
|
+
"This meets Aigis V3 literal wording ('env variable') but cannot be toggled during a "
|
|
234
|
+
"live incident without a process restart. Verify manually; if confirmed, mark PARTIAL "
|
|
235
|
+
"rather than PASS."
|
|
236
|
+
)
|
|
237
|
+
elif evidence:
|
|
238
|
+
notes = (
|
|
239
|
+
"Restart-latched signals present but counter-signals (per-request env reads) also "
|
|
240
|
+
"found. Manual review recommended."
|
|
241
|
+
)
|
|
242
|
+
else:
|
|
243
|
+
notes = "No restart-latched signals detected."
|
|
244
|
+
return {"flagged": flagged, "evidence": evidence, "notes": notes}
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _injection_log_only(files: list[dict[str, Any]], ctx: dict[str, Any]) -> dict[str, Any]:
|
|
248
|
+
callsites: list[dict[str, Any]] = []
|
|
249
|
+
evidence: list[dict[str, Any]] = []
|
|
250
|
+
|
|
251
|
+
block_patterns = [
|
|
252
|
+
re.compile(
|
|
253
|
+
r"if\s+(?:injection|inj|result|flagged|inject[a-z_]*)[\s\S]{0,120}?(?:raise|return|HTTPException|abort|reject|block)",
|
|
254
|
+
re.IGNORECASE,
|
|
255
|
+
),
|
|
256
|
+
re.compile(
|
|
257
|
+
r"if\s+[^\n]*\[[\"']flagged[\"']\][\s\S]{0,120}?(?:raise|return|HTTPException|abort|reject|block)",
|
|
258
|
+
re.IGNORECASE,
|
|
259
|
+
),
|
|
260
|
+
re.compile(
|
|
261
|
+
r"if\s+[^\n]*\.flagged[\s\S]{0,120}?(?:raise|return|HTTPException|abort)",
|
|
262
|
+
re.IGNORECASE,
|
|
263
|
+
),
|
|
264
|
+
]
|
|
265
|
+
|
|
266
|
+
for f in files:
|
|
267
|
+
lines = f["content"].split("\n")
|
|
268
|
+
for i, line in enumerate(lines):
|
|
269
|
+
if re.match(r"^\s*def\s+", line) and _INJECTION_DETECTOR_RE.search(line):
|
|
270
|
+
continue
|
|
271
|
+
if _INJECTION_DETECTOR_RE.search(line) and not re.match(r"^\s*def\s+", line) and not re.match(r"^\s*(from|import)\s+", line):
|
|
272
|
+
window = "\n".join(lines[i : min(i + 20, len(lines))])
|
|
273
|
+
blocks = any(p.search(window) for p in block_patterns)
|
|
274
|
+
callsites.append({"file": f["path"], "line": i + 1, "snippet": line.strip(), "blocks": blocks})
|
|
275
|
+
if not blocks:
|
|
276
|
+
evidence.append({
|
|
277
|
+
"file": f["path"],
|
|
278
|
+
"line": i + 1,
|
|
279
|
+
"snippet": line.strip() + " // next 20 lines contain no control-flow break",
|
|
280
|
+
})
|
|
281
|
+
|
|
282
|
+
flagged = bool(callsites) and all(not c["blocks"] for c in callsites)
|
|
283
|
+
partial = any(not c["blocks"] for c in callsites) and any(c["blocks"] for c in callsites)
|
|
284
|
+
|
|
285
|
+
if not callsites:
|
|
286
|
+
notes = "No injection detector callsites found."
|
|
287
|
+
elif flagged:
|
|
288
|
+
notes = (
|
|
289
|
+
f"{len(callsites)} callsite(s) of the injection detector found; none branch on the "
|
|
290
|
+
"result. Meets Aigis V5 literal wording ('even if just logging') but the LLM call still "
|
|
291
|
+
"runs on flagged inputs. Verify manually; if confirmed, mark PARTIAL rather than PASS."
|
|
292
|
+
)
|
|
293
|
+
elif partial:
|
|
294
|
+
notes = "Some callsites block on detection, others do not. Review the non-blocking ones."
|
|
295
|
+
else:
|
|
296
|
+
notes = "All callsites of the injection detector branch on the result."
|
|
297
|
+
|
|
298
|
+
return {"flagged": flagged or partial, "evidence": evidence, "notes": notes}
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _pii_incomplete_classes(files: list[dict[str, Any]], ctx: dict[str, Any]) -> dict[str, Any]:
|
|
302
|
+
REQUIRED = ["ssn", "email", "phone", "credit_card", "address"]
|
|
303
|
+
CLASS_TOKENS = {
|
|
304
|
+
"ssn": ["ssn", "social_security", "socialsecurity", "socsec"],
|
|
305
|
+
"email": ["email", "e_mail", "e-mail"],
|
|
306
|
+
"phone": ["phone", "phone_number", "telephone", "mobile"],
|
|
307
|
+
"credit_card": ["credit_card", "creditcard", "card", "card_number", "cardnumber", "pan", "cc_number", "payment_card"],
|
|
308
|
+
"address": ["address", "street", "postal_address", "mailing_address"],
|
|
309
|
+
}
|
|
310
|
+
present = {c: False for c in REQUIRED}
|
|
311
|
+
evidence: list[dict[str, Any]] = []
|
|
312
|
+
|
|
313
|
+
for f in files:
|
|
314
|
+
content = f["content"]
|
|
315
|
+
for cls in REQUIRED:
|
|
316
|
+
if present[cls]:
|
|
317
|
+
continue
|
|
318
|
+
for token in CLASS_TOKENS[cls]:
|
|
319
|
+
upper = token.upper()
|
|
320
|
+
patterns = [
|
|
321
|
+
re.compile(r'["\'`]' + re.escape(token) + r'["\'`]\s*:'),
|
|
322
|
+
re.compile(r"\b" + re.escape(token) + r"\s*[:=]\s*re\.compile", re.IGNORECASE),
|
|
323
|
+
re.compile(r"\b" + re.escape(upper) + r"_PATTERN"),
|
|
324
|
+
re.compile(r"\[" + re.escape(upper) + r"_REDACTED\]"),
|
|
325
|
+
re.compile(r"\[REDACTED_" + re.escape(upper) + r"\]"),
|
|
326
|
+
re.compile(r"\b(?:redact|mask|scrub)_" + re.escape(token) + r"\b", re.IGNORECASE),
|
|
327
|
+
]
|
|
328
|
+
matched = False
|
|
329
|
+
for pat in patterns:
|
|
330
|
+
m = pat.search(content)
|
|
331
|
+
if m:
|
|
332
|
+
present[cls] = True
|
|
333
|
+
line = content.count("\n", 0, m.start()) + 1
|
|
334
|
+
snippet = (content.split("\n")[line - 1] if line - 1 < len(content.split("\n")) else "").strip()[:120]
|
|
335
|
+
evidence.append({"file": f["path"], "line": line, "snippet": f"{cls}: {snippet}"})
|
|
336
|
+
matched = True
|
|
337
|
+
break
|
|
338
|
+
if matched:
|
|
339
|
+
break
|
|
340
|
+
|
|
341
|
+
missing = [c for c in REQUIRED if not present[c]]
|
|
342
|
+
flagged = bool(missing)
|
|
343
|
+
if flagged:
|
|
344
|
+
notes = (
|
|
345
|
+
f"PII redactor is missing pattern coverage for: {', '.join(missing)}. "
|
|
346
|
+
f"Aigis V1 literal wording ('redaction called') is met, but inputs containing "
|
|
347
|
+
f"{' or '.join(missing)} will reach the LLM (and logs) unredacted. "
|
|
348
|
+
f"Add all 5 required classes: {', '.join(REQUIRED)}."
|
|
349
|
+
)
|
|
350
|
+
else:
|
|
351
|
+
notes = "All 5 required PII classes detected in the code."
|
|
352
|
+
return {"flagged": flagged, "evidence": evidence, "notes": notes}
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _rate_limit_no_retry_after(files: list[dict[str, Any]], ctx: dict[str, Any]) -> dict[str, Any]:
|
|
356
|
+
site_log: list[dict[str, Any]] = []
|
|
357
|
+
evidence: list[dict[str, Any]] = []
|
|
358
|
+
|
|
359
|
+
response_site_re = re.compile(
|
|
360
|
+
r"status_code\s*=\s*429|HTTPException\s*\(\s*(?:status_code\s*=\s*)?429"
|
|
361
|
+
r"|status\(429\)|response\.status\s*=\s*429"
|
|
362
|
+
)
|
|
363
|
+
retry_after_re = re.compile(r"Retry-After|retry_after|retryAfter", re.IGNORECASE)
|
|
364
|
+
|
|
365
|
+
for f in files:
|
|
366
|
+
lines = f["content"].split("\n")
|
|
367
|
+
for m in response_site_re.finditer(f["content"]):
|
|
368
|
+
line = f["content"].count("\n", 0, m.start()) + 1
|
|
369
|
+
start = max(0, line - 6)
|
|
370
|
+
end = min(len(lines), line + 15)
|
|
371
|
+
window = "\n".join(lines[start:end])
|
|
372
|
+
has_header = bool(retry_after_re.search(window))
|
|
373
|
+
site_log.append({"file": f["path"], "line": line, "hasHeader": has_header})
|
|
374
|
+
if not has_header:
|
|
375
|
+
evidence.append({
|
|
376
|
+
"file": f["path"],
|
|
377
|
+
"line": line,
|
|
378
|
+
"snippet": (lines[line - 1] if line - 1 < len(lines) else "").strip()
|
|
379
|
+
+ " // no Retry-After within surrounding 20 lines",
|
|
380
|
+
})
|
|
381
|
+
|
|
382
|
+
flagged = bool(site_log) and all(not s["hasHeader"] for s in site_log)
|
|
383
|
+
partial = any(not s["hasHeader"] for s in site_log) and any(s["hasHeader"] for s in site_log)
|
|
384
|
+
if not site_log:
|
|
385
|
+
notes = "No 429 response sites found."
|
|
386
|
+
elif flagged:
|
|
387
|
+
notes = (
|
|
388
|
+
f"{len(site_log)} site(s) returning 429 found; none set a Retry-After header. "
|
|
389
|
+
f"Aigis V1 literal wording ('per-user rate limit') is met, but clients have no "
|
|
390
|
+
f"retry-backoff signal. Add Retry-After computed from the actual bucket TTL."
|
|
391
|
+
)
|
|
392
|
+
elif partial:
|
|
393
|
+
notes = "Some 429 sites set Retry-After, others do not. Review the ones without."
|
|
394
|
+
else:
|
|
395
|
+
notes = "All 429 response sites set a Retry-After header."
|
|
396
|
+
return {"flagged": flagged or partial, "evidence": evidence, "notes": notes}
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
_SPECIAL_REGISTRY = {
|
|
400
|
+
"kill_switch_restart_latched": _kill_switch_restart_latched,
|
|
401
|
+
"injection_log_only": _injection_log_only,
|
|
402
|
+
"pii_incomplete_classes": _pii_incomplete_classes,
|
|
403
|
+
"rate_limit_no_retry_after": _rate_limit_no_retry_after,
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
# ── Public API ─────────────────────────────────────────────────────────
|
|
408
|
+
|
|
409
|
+
def auto_verify_area(area_id: str, project_dir: str) -> dict[str, Any]:
|
|
410
|
+
rules = load_rules()
|
|
411
|
+
area = rules.get(area_id)
|
|
412
|
+
if not area:
|
|
413
|
+
raise ValueError(
|
|
414
|
+
f"No auto-verify rules for pattern area '{area_id}'. "
|
|
415
|
+
f"Known: {', '.join(rules.keys())}"
|
|
416
|
+
)
|
|
417
|
+
root = Path(project_dir).resolve()
|
|
418
|
+
files = _load_files(root)
|
|
419
|
+
|
|
420
|
+
auto_results: dict[str, Any] = {}
|
|
421
|
+
for check_id, rule in (area.get("auto") or {}).items():
|
|
422
|
+
scan_files = files
|
|
423
|
+
fg = rule.get("file_glob")
|
|
424
|
+
if fg:
|
|
425
|
+
globs = [g.strip() for g in fg.split(",")]
|
|
426
|
+
scan_files = [f for f in files if any(_matches_glob(f["path"], g) for g in globs)]
|
|
427
|
+
res = _scan_rule(rule, scan_files)
|
|
428
|
+
auto_results[check_id] = {**rule, **res}
|
|
429
|
+
|
|
430
|
+
overclaim_results: dict[str, Any] = {}
|
|
431
|
+
for check_id, entry in (area.get("overclaim") or {}).items():
|
|
432
|
+
fn = _SPECIAL_REGISTRY.get(entry["recognizer"])
|
|
433
|
+
recog = fn(files, {"rootDir": str(root), "areaId": area_id, "checkId": check_id}) if fn else {
|
|
434
|
+
"flagged": False, "evidence": [], "notes": f"Unknown recognizer: {entry['recognizer']}"
|
|
435
|
+
}
|
|
436
|
+
also_auto = entry.get("also_auto")
|
|
437
|
+
raise_ = recog["flagged"]
|
|
438
|
+
if also_auto and auto_results.get(also_auto, {}).get("status") != "PASS":
|
|
439
|
+
raise_ = False
|
|
440
|
+
overclaim_results[check_id] = {
|
|
441
|
+
"desc": entry.get("desc", ""),
|
|
442
|
+
"recognizer": entry["recognizer"],
|
|
443
|
+
"also_auto": also_auto,
|
|
444
|
+
"raised": raise_,
|
|
445
|
+
"flagged": recog["flagged"],
|
|
446
|
+
"evidence": recog["evidence"],
|
|
447
|
+
"notes": recog["notes"],
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
judgment_results: dict[str, Any] = {}
|
|
451
|
+
for check_id, desc in (area.get("judgment") or {}).items():
|
|
452
|
+
judgment_results[check_id] = {"desc": desc, "status": "JUDGMENT"}
|
|
453
|
+
|
|
454
|
+
auto_pass = sum(1 for r in auto_results.values() if r["status"] == "PASS")
|
|
455
|
+
auto_fail = sum(1 for r in auto_results.values() if r["status"] == "FAIL")
|
|
456
|
+
overclaims_raised = sum(1 for r in overclaim_results.values() if r["raised"])
|
|
457
|
+
|
|
458
|
+
return {
|
|
459
|
+
"area": area_id,
|
|
460
|
+
"project_dir": str(root),
|
|
461
|
+
"files_scanned": len(files),
|
|
462
|
+
"summary": {
|
|
463
|
+
"auto_total": len(auto_results),
|
|
464
|
+
"auto_pass": auto_pass,
|
|
465
|
+
"auto_fail": auto_fail,
|
|
466
|
+
"overclaims_raised": overclaims_raised,
|
|
467
|
+
"judgment_required": len(judgment_results),
|
|
468
|
+
},
|
|
469
|
+
"auto_checks": auto_results,
|
|
470
|
+
"overclaim_checks": overclaim_results,
|
|
471
|
+
"judgment_checks": judgment_results,
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def format_text_report(result: dict[str, Any]) -> str:
|
|
476
|
+
lines: list[str] = []
|
|
477
|
+
lines.append(f"═══ AUTO-VERIFY: {result['area']} ═══\n")
|
|
478
|
+
lines.append(f"Project: {result['project_dir']}")
|
|
479
|
+
lines.append(f"Files scanned: {result['files_scanned']}")
|
|
480
|
+
s = result["summary"]
|
|
481
|
+
lines.append(f"Auto-verified: {s['auto_pass']}/{s['auto_total']} PASS, {s['auto_fail']} FAIL")
|
|
482
|
+
lines.append(f"Overclaim recognizers raised: {s['overclaims_raised']}")
|
|
483
|
+
lines.append(f"Judgment required: {s['judgment_required']} check(s)\n")
|
|
484
|
+
|
|
485
|
+
if result["auto_checks"]:
|
|
486
|
+
lines.append("── AUTO CHECKS ──")
|
|
487
|
+
for cid, r in result["auto_checks"].items():
|
|
488
|
+
badge = "[PASS]" if r["status"] == "PASS" else "[FAIL]"
|
|
489
|
+
inv = " (inverse)" if r.get("inverse") else ""
|
|
490
|
+
lines.append(f"\n{badge} {cid}: {r.get('desc','')}{inv}")
|
|
491
|
+
for e in r["evidence"][:3]:
|
|
492
|
+
lines.append(f" {e['file']}:{e['line']} {e['snippet']}")
|
|
493
|
+
if r["status"] == "FAIL" and not r.get("inverse") and not r["evidence"]:
|
|
494
|
+
lines.append(f" no matches for any of {r.get('total_patterns', 0)} pattern(s)")
|
|
495
|
+
lines.append("")
|
|
496
|
+
|
|
497
|
+
if result["overclaim_checks"]:
|
|
498
|
+
lines.append("── OVERCLAIM RECOGNIZERS ──")
|
|
499
|
+
for cid, r in result["overclaim_checks"].items():
|
|
500
|
+
badge = "[OVERCLAIM RAISED]" if r["raised"] else "[no signal]"
|
|
501
|
+
lines.append(f"\n{badge} {cid}: {r['desc']}")
|
|
502
|
+
lines.append(f" recognizer: {r['recognizer']}")
|
|
503
|
+
lines.append(f" {r['notes']}")
|
|
504
|
+
for e in r["evidence"][:3]:
|
|
505
|
+
lines.append(f" {e['file']}:{e['line']} {e['snippet']}")
|
|
506
|
+
lines.append("")
|
|
507
|
+
|
|
508
|
+
if result["judgment_checks"]:
|
|
509
|
+
lines.append("── JUDGMENT REQUIRED (agent must evaluate) ──")
|
|
510
|
+
for cid, r in result["judgment_checks"].items():
|
|
511
|
+
lines.append(f"\n[JUDGMENT] {cid}: {r['desc']}")
|
|
512
|
+
lines.append("")
|
|
513
|
+
|
|
514
|
+
lines.append("═══ SUMMARY ═══")
|
|
515
|
+
lines.append(f"Auto-verified: {s['auto_pass']} PASS, {s['auto_fail']} FAIL out of {s['auto_total']}")
|
|
516
|
+
lines.append(f"Overclaim flags raised: {s['overclaims_raised']}")
|
|
517
|
+
lines.append(f"Judgment required: {s['judgment_required']} checks")
|
|
518
|
+
return "\n".join(lines)
|