git-security-sentinel 1.2.0__py3-none-any.whl
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.
- git_security_sentinel/__init__.py +74 -0
- git_security_sentinel/__main__.py +9 -0
- git_security_sentinel/ai/__init__.py +17 -0
- git_security_sentinel/ai/cost.py +34 -0
- git_security_sentinel/ai/prompts.py +81 -0
- git_security_sentinel/ai_cli.py +884 -0
- git_security_sentinel/cli.py +937 -0
- git_security_sentinel/config/__init__.py +16 -0
- git_security_sentinel/config/loader.py +245 -0
- git_security_sentinel/core/__init__.py +42 -0
- git_security_sentinel/core/diff_parser.py +93 -0
- git_security_sentinel/core/models.py +111 -0
- git_security_sentinel/core/scanner.py +360 -0
- git_security_sentinel/hooks/__init__.py +8 -0
- git_security_sentinel/hooks/bootstrap.py +84 -0
- git_security_sentinel/hooks/installer.py +103 -0
- git_security_sentinel/output/__init__.py +18 -0
- git_security_sentinel/output/sarif.py +179 -0
- git_security_sentinel/py.typed +0 -0
- git_security_sentinel/redaction/__init__.py +15 -0
- git_security_sentinel/redaction/redactor.py +313 -0
- git_security_sentinel/rules/__init__.py +29 -0
- git_security_sentinel/rules/auth.py +103 -0
- git_security_sentinel/rules/catalog.py +63 -0
- git_security_sentinel/rules/cloud.py +132 -0
- git_security_sentinel/rules/compliance.py +54 -0
- git_security_sentinel/rules/database.py +87 -0
- git_security_sentinel/rules/insecure_code.py +130 -0
- git_security_sentinel/rules/sensitive_files.py +48 -0
- git_security_sentinel/suppression/__init__.py +31 -0
- git_security_sentinel/suppression/baseline.py +133 -0
- git_security_sentinel/suppression/comment_filter.py +99 -0
- git_security_sentinel/suppression/ignore_filter.py +154 -0
- git_security_sentinel/update/__init__.py +27 -0
- git_security_sentinel/update/checker.py +189 -0
- git_security_sentinel-1.2.0.dist-info/METADATA +583 -0
- git_security_sentinel-1.2.0.dist-info/RECORD +41 -0
- git_security_sentinel-1.2.0.dist-info/WHEEL +5 -0
- git_security_sentinel-1.2.0.dist-info/entry_points.txt +4 -0
- git_security_sentinel-1.2.0.dist-info/licenses/LICENSE +21 -0
- git_security_sentinel-1.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,884 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Git Security Sentinel - Universal AI Security Reviewer CLI.
|
|
3
|
+
Contextual security reviewer for Git Security Sentinel reports.
|
|
4
|
+
Supports local open-weight models via Ollama (default: loopback only) and
|
|
5
|
+
cloud models via Google AI Studio (Gemini), Groq, and OpenAI with pre-redacted privacy.
|
|
6
|
+
Complies with the Agent Skills Open Standard (https://agentskills.io/specification).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.parse
|
|
18
|
+
import urllib.request
|
|
19
|
+
|
|
20
|
+
from git_security_sentinel.core.models import VERSION
|
|
21
|
+
from git_security_sentinel.ai.cost import (
|
|
22
|
+
PRICING_TABLE,
|
|
23
|
+
calculate_token_estimate,
|
|
24
|
+
estimate_query_cost,
|
|
25
|
+
)
|
|
26
|
+
from git_security_sentinel.ai.prompts import build_system_prompt
|
|
27
|
+
|
|
28
|
+
DEFAULT_TIMEOUT_SEC = 120
|
|
29
|
+
|
|
30
|
+
LOOPBACK_HOSTS = {"127.0.0.1", "localhost", "::1", "0.0.0.0"}
|
|
31
|
+
|
|
32
|
+
PROVIDER_DEFAULTS = {
|
|
33
|
+
"ollama": {
|
|
34
|
+
"model": "gemma3:4b",
|
|
35
|
+
"endpoint": "http://127.0.0.1:11434",
|
|
36
|
+
"env_var": None,
|
|
37
|
+
},
|
|
38
|
+
"gemini": {
|
|
39
|
+
"model": "gemma-4-26b-a4b-it",
|
|
40
|
+
"endpoint": "https://generativelanguage.googleapis.com",
|
|
41
|
+
"env_var": "GEMINI_API_KEY",
|
|
42
|
+
},
|
|
43
|
+
"openai": {
|
|
44
|
+
"model": "gpt-4o-mini",
|
|
45
|
+
"endpoint": "https://api.openai.com/v1/chat/completions",
|
|
46
|
+
"env_var": "OPENAI_API_KEY",
|
|
47
|
+
},
|
|
48
|
+
"groq": {
|
|
49
|
+
"model": "llama-3.3-70b-versatile",
|
|
50
|
+
"endpoint": "https://api.groq.com/openai/v1/chat/completions",
|
|
51
|
+
"env_var": "GROQ_API_KEY",
|
|
52
|
+
},
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def load_env_file(env_path: Optional[Path] = None) -> None:
|
|
57
|
+
"""Load environment variables from a local .env file if it exists, without third-party packages."""
|
|
58
|
+
target = env_path or (Path.cwd() / ".env")
|
|
59
|
+
if not target.is_file():
|
|
60
|
+
# Fallback to the scanner repository root .env if cwd has no .env
|
|
61
|
+
repo_root_env = Path(__file__).resolve().parent.parent.parent / ".env"
|
|
62
|
+
if repo_root_env.is_file():
|
|
63
|
+
target = repo_root_env
|
|
64
|
+
else:
|
|
65
|
+
return
|
|
66
|
+
try:
|
|
67
|
+
for line in target.read_text(encoding="utf-8").splitlines():
|
|
68
|
+
line = line.strip()
|
|
69
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
70
|
+
continue
|
|
71
|
+
k, v = line.split("=", 1)
|
|
72
|
+
k = k.strip()
|
|
73
|
+
v = v.strip().strip("'\"")
|
|
74
|
+
if k and k not in os.environ:
|
|
75
|
+
os.environ[k] = v
|
|
76
|
+
except Exception:
|
|
77
|
+
pass
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def detect_provider(requested: Optional[str] = None) -> str:
|
|
81
|
+
"""Determine provider based on user request or environment variable detection."""
|
|
82
|
+
if requested and requested.lower() != "auto":
|
|
83
|
+
return requested.lower()
|
|
84
|
+
if os.environ.get("GEMINI_API_KEY"):
|
|
85
|
+
return "gemini"
|
|
86
|
+
if os.environ.get("GROQ_API_KEY"):
|
|
87
|
+
return "groq"
|
|
88
|
+
if os.environ.get("OPENAI_API_KEY"):
|
|
89
|
+
return "openai"
|
|
90
|
+
return "ollama"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def is_loopback_url(url: str) -> bool:
|
|
94
|
+
"""Validate that the given URL resolves strictly to a loopback host."""
|
|
95
|
+
parsed = urllib.parse.urlparse(url)
|
|
96
|
+
hostname = (parsed.hostname or "").lower()
|
|
97
|
+
return hostname in LOOPBACK_HOSTS
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def check_ollama_available(endpoint: str, timeout_sec: int = 5) -> Tuple[bool, str]:
|
|
101
|
+
"""Check if the local Ollama daemon is reachable and responding."""
|
|
102
|
+
url = f"{endpoint.rstrip('/')}/api/tags"
|
|
103
|
+
req = urllib.request.Request(
|
|
104
|
+
url,
|
|
105
|
+
headers={"User-Agent": f"git-security-sentinel-ai-reviewer/{VERSION}"},
|
|
106
|
+
method="GET",
|
|
107
|
+
)
|
|
108
|
+
try:
|
|
109
|
+
with urllib.request.urlopen(req, timeout=timeout_sec) as response:
|
|
110
|
+
if response.status == 200:
|
|
111
|
+
data = json.loads(response.read().decode("utf-8"))
|
|
112
|
+
models = [m.get("name") for m in data.get("models", [])]
|
|
113
|
+
return True, f"Ollama available with models: {', '.join(models) if models else 'none loaded'}"
|
|
114
|
+
return False, f"Ollama returned HTTP status {response.status}"
|
|
115
|
+
except urllib.error.URLError as e:
|
|
116
|
+
return False, f"Could not connect to Ollama at {endpoint}: {e.reason}"
|
|
117
|
+
except Exception as e:
|
|
118
|
+
return False, f"Ollama connection error: {e}"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def query_ollama(
|
|
122
|
+
endpoint: str,
|
|
123
|
+
model: str,
|
|
124
|
+
prompt: str,
|
|
125
|
+
system_prompt: str,
|
|
126
|
+
timeout_sec: int = DEFAULT_TIMEOUT_SEC,
|
|
127
|
+
) -> Tuple[bool, Optional[str], Optional[str]]:
|
|
128
|
+
"""Send prompt to Ollama /api/generate without streaming."""
|
|
129
|
+
url = f"{endpoint.rstrip('/')}/api/generate"
|
|
130
|
+
payload = {
|
|
131
|
+
"model": model,
|
|
132
|
+
"prompt": prompt,
|
|
133
|
+
"system": system_prompt,
|
|
134
|
+
"stream": False,
|
|
135
|
+
"options": {
|
|
136
|
+
"temperature": 0.2,
|
|
137
|
+
"top_p": 0.9,
|
|
138
|
+
},
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
try:
|
|
142
|
+
data_bytes = json.dumps(payload).encode("utf-8")
|
|
143
|
+
req = urllib.request.Request(
|
|
144
|
+
url,
|
|
145
|
+
data=data_bytes,
|
|
146
|
+
headers={
|
|
147
|
+
"Content-Type": "application/json",
|
|
148
|
+
"User-Agent": f"git-security-sentinel-ai-reviewer/{VERSION}",
|
|
149
|
+
},
|
|
150
|
+
method="POST",
|
|
151
|
+
)
|
|
152
|
+
with urllib.request.urlopen(req, timeout=timeout_sec) as resp:
|
|
153
|
+
if resp.status == 200:
|
|
154
|
+
resp_json = json.loads(resp.read().decode("utf-8"))
|
|
155
|
+
return True, resp_json.get("response", ""), None
|
|
156
|
+
return False, None, f"Ollama responded with HTTP {resp.status}"
|
|
157
|
+
except urllib.error.HTTPError as e:
|
|
158
|
+
error_body = ""
|
|
159
|
+
try:
|
|
160
|
+
error_body = e.read().decode("utf-8")
|
|
161
|
+
except Exception:
|
|
162
|
+
pass
|
|
163
|
+
return False, None, f"HTTP Error {e.code}: {e.reason}. Details: {error_body}"
|
|
164
|
+
except urllib.error.URLError as e:
|
|
165
|
+
return False, None, f"Connection error: {e.reason}"
|
|
166
|
+
except TimeoutError:
|
|
167
|
+
return False, None, f"Inference request timed out after {timeout_sec} seconds."
|
|
168
|
+
except Exception as e:
|
|
169
|
+
return False, None, f"Unexpected error querying Ollama: {e}"
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def query_gemini(
|
|
173
|
+
api_key: str,
|
|
174
|
+
model: str,
|
|
175
|
+
prompt: str,
|
|
176
|
+
system_prompt: str,
|
|
177
|
+
timeout_sec: int = DEFAULT_TIMEOUT_SEC,
|
|
178
|
+
) -> Tuple[bool, Optional[str], Optional[str]]:
|
|
179
|
+
"""Query Google AI Studio Gemini API using standard library urllib.request."""
|
|
180
|
+
clean_key = api_key.strip()
|
|
181
|
+
clean_model = model.strip()
|
|
182
|
+
if clean_model.startswith("models/"):
|
|
183
|
+
clean_model = clean_model[len("models/"):]
|
|
184
|
+
if clean_model.lower() in {"gemma", "gemma-4", "gemma4", "gemma-4-26b", "gemma4-26b", "gemma-4-moe", "gemma-2-9b-it"}:
|
|
185
|
+
clean_model = "gemma-4-26b-a4b-it"
|
|
186
|
+
elif clean_model.lower() in {"gemma-4-31b", "gemma4-31b", "gemma 4 31b"}:
|
|
187
|
+
clean_model = "gemma-4-31b-it"
|
|
188
|
+
elif clean_model == "gemini-1.5-flash":
|
|
189
|
+
clean_model = "gemini-2.5-flash"
|
|
190
|
+
|
|
191
|
+
url = f"https://generativelanguage.googleapis.com/v1beta/models/{clean_model}:generateContent?key={clean_key}"
|
|
192
|
+
payload = {
|
|
193
|
+
"contents": [{"parts": [{"text": prompt}]}],
|
|
194
|
+
"system_instruction": {"parts": [{"text": system_prompt}]},
|
|
195
|
+
"generationConfig": {
|
|
196
|
+
"temperature": 0.2,
|
|
197
|
+
},
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
try:
|
|
201
|
+
data_bytes = json.dumps(payload).encode("utf-8")
|
|
202
|
+
req = urllib.request.Request(
|
|
203
|
+
url,
|
|
204
|
+
data=data_bytes,
|
|
205
|
+
headers={
|
|
206
|
+
"Content-Type": "application/json",
|
|
207
|
+
"User-Agent": f"git-security-sentinel-ai-reviewer/{VERSION}",
|
|
208
|
+
},
|
|
209
|
+
method="POST",
|
|
210
|
+
)
|
|
211
|
+
with urllib.request.urlopen(req, timeout=timeout_sec) as resp:
|
|
212
|
+
if resp.status == 200:
|
|
213
|
+
resp_json = json.loads(resp.read().decode("utf-8"))
|
|
214
|
+
candidates = resp_json.get("candidates", [])
|
|
215
|
+
if candidates and "content" in candidates[0]:
|
|
216
|
+
parts = candidates[0]["content"].get("parts", [])
|
|
217
|
+
if parts and "text" in parts[0]:
|
|
218
|
+
return True, parts[0]["text"], None
|
|
219
|
+
return False, None, "Gemini API returned an empty candidate list."
|
|
220
|
+
return False, None, f"Gemini API returned HTTP status {resp.status}"
|
|
221
|
+
except urllib.error.HTTPError as e:
|
|
222
|
+
error_body = ""
|
|
223
|
+
try:
|
|
224
|
+
error_body = e.read().decode("utf-8")
|
|
225
|
+
except Exception:
|
|
226
|
+
pass
|
|
227
|
+
if e.code in {503, 429} and clean_model == "gemma-4-31b-it":
|
|
228
|
+
sys.stderr.write(
|
|
229
|
+
f"Notice: Google AI Studio returned HTTP {e.code} (high demand) for {clean_model}. "
|
|
230
|
+
"Failing over to fast Gemma 4 MoE (gemma-4-26b-a4b-it)...\n"
|
|
231
|
+
)
|
|
232
|
+
return query_gemini(
|
|
233
|
+
api_key=api_key,
|
|
234
|
+
model="gemma-4-26b-a4b-it",
|
|
235
|
+
prompt=prompt,
|
|
236
|
+
system_prompt=system_prompt,
|
|
237
|
+
timeout_sec=timeout_sec,
|
|
238
|
+
)
|
|
239
|
+
return False, None, f"Gemini HTTP Error {e.code}: {e.reason}. Details: {error_body}"
|
|
240
|
+
except urllib.error.URLError as e:
|
|
241
|
+
return False, None, f"Connection error contacting Gemini: {e.reason}"
|
|
242
|
+
except TimeoutError:
|
|
243
|
+
if clean_model == "gemma-4-31b-it":
|
|
244
|
+
sys.stderr.write(
|
|
245
|
+
f"Notice: Google AI Studio timed out on {clean_model}. "
|
|
246
|
+
"Failing over to fast Gemma 4 MoE (gemma-4-26b-a4b-it)...\n"
|
|
247
|
+
)
|
|
248
|
+
return query_gemini(
|
|
249
|
+
api_key=api_key,
|
|
250
|
+
model="gemma-4-26b-a4b-it",
|
|
251
|
+
prompt=prompt,
|
|
252
|
+
system_prompt=system_prompt,
|
|
253
|
+
timeout_sec=timeout_sec,
|
|
254
|
+
)
|
|
255
|
+
return False, None, f"Inference request timed out after {timeout_sec} seconds."
|
|
256
|
+
except Exception as e:
|
|
257
|
+
return False, None, f"Unexpected error querying Gemini API: {e}"
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def query_openai_compatible(
|
|
261
|
+
endpoint: str,
|
|
262
|
+
api_key: str,
|
|
263
|
+
model: str,
|
|
264
|
+
prompt: str,
|
|
265
|
+
system_prompt: str,
|
|
266
|
+
timeout_sec: int = DEFAULT_TIMEOUT_SEC,
|
|
267
|
+
) -> Tuple[bool, Optional[str], Optional[str]]:
|
|
268
|
+
"""Query OpenAI-compatible endpoint (OpenAI, Groq, Mistral, OpenRouter)."""
|
|
269
|
+
clean_key = api_key.strip()
|
|
270
|
+
payload = {
|
|
271
|
+
"model": model,
|
|
272
|
+
"messages": [
|
|
273
|
+
{"role": "system", "content": system_prompt},
|
|
274
|
+
{"role": "user", "content": prompt},
|
|
275
|
+
],
|
|
276
|
+
"temperature": 0.2,
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
try:
|
|
280
|
+
data_bytes = json.dumps(payload).encode("utf-8")
|
|
281
|
+
req = urllib.request.Request(
|
|
282
|
+
endpoint,
|
|
283
|
+
data=data_bytes,
|
|
284
|
+
headers={
|
|
285
|
+
"Content-Type": "application/json",
|
|
286
|
+
"Authorization": f"Bearer {clean_key}",
|
|
287
|
+
"User-Agent": f"git-security-sentinel-ai-reviewer/{VERSION}",
|
|
288
|
+
},
|
|
289
|
+
method="POST",
|
|
290
|
+
)
|
|
291
|
+
with urllib.request.urlopen(req, timeout=timeout_sec) as resp:
|
|
292
|
+
if resp.status == 200:
|
|
293
|
+
resp_json = json.loads(resp.read().decode("utf-8"))
|
|
294
|
+
choices = resp_json.get("choices", [])
|
|
295
|
+
if choices and "message" in choices[0]:
|
|
296
|
+
return True, choices[0]["message"].get("content", ""), None
|
|
297
|
+
return False, None, "API returned an empty choices list."
|
|
298
|
+
return False, None, f"API returned HTTP status {resp.status}"
|
|
299
|
+
except urllib.error.HTTPError as e:
|
|
300
|
+
error_body = ""
|
|
301
|
+
try:
|
|
302
|
+
error_body = e.read().decode("utf-8")
|
|
303
|
+
except Exception:
|
|
304
|
+
pass
|
|
305
|
+
return False, None, f"API HTTP Error {e.code}: {e.reason}. Details: {error_body}"
|
|
306
|
+
except urllib.error.URLError as e:
|
|
307
|
+
return False, None, f"Connection error: {e.reason}"
|
|
308
|
+
except TimeoutError:
|
|
309
|
+
return False, None, f"Inference request timed out after {timeout_sec} seconds."
|
|
310
|
+
except Exception as e:
|
|
311
|
+
return False, None, f"Unexpected error querying API: {e}"
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def extract_json_from_text(text: str) -> Optional[Dict[str, Any]]:
|
|
315
|
+
"""Extract and parse JSON object from LLM output, gracefully stripping code fences."""
|
|
316
|
+
cleaned = text.strip()
|
|
317
|
+
if cleaned.startswith("```"):
|
|
318
|
+
lines = cleaned.splitlines()
|
|
319
|
+
if lines[0].startswith("```"):
|
|
320
|
+
lines = lines[1:]
|
|
321
|
+
if lines and lines[-1].startswith("```"):
|
|
322
|
+
lines = lines[:-1]
|
|
323
|
+
cleaned = "\n".join(lines).strip()
|
|
324
|
+
|
|
325
|
+
try:
|
|
326
|
+
return json.loads(cleaned)
|
|
327
|
+
except Exception:
|
|
328
|
+
start = cleaned.find("{")
|
|
329
|
+
end = cleaned.rfind("}")
|
|
330
|
+
if start != -1 and end != -1 and end > start:
|
|
331
|
+
try:
|
|
332
|
+
return json.loads(cleaned[start : end + 1])
|
|
333
|
+
except Exception:
|
|
334
|
+
pass
|
|
335
|
+
return None
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def format_cost_banner(cost_data: Dict[str, Any]) -> str:
|
|
339
|
+
"""Format a clean visual banner summarizing token estimates and query cost."""
|
|
340
|
+
prov = cost_data.get("provider", "UNKNOWN").upper()
|
|
341
|
+
model = cost_data.get("model", "default")
|
|
342
|
+
p_tok = cost_data.get("prompt_tokens", 0)
|
|
343
|
+
c_tok = cost_data.get("completion_tokens", 0)
|
|
344
|
+
t_tok = cost_data.get("total_tokens", 0)
|
|
345
|
+
cost_val = cost_data.get("estimated_cost_usd", 0.0)
|
|
346
|
+
note = " (Free / Local)" if cost_data.get("provider") == "ollama" else ""
|
|
347
|
+
return (
|
|
348
|
+
"--------------------------------------------------------------------\n"
|
|
349
|
+
" COST ESTIMATION BANNER\n"
|
|
350
|
+
"--------------------------------------------------------------------\n"
|
|
351
|
+
f" Provider : {prov} ({model})\n"
|
|
352
|
+
f" Prompt Tokens : ~{p_tok:,}\n"
|
|
353
|
+
f" Completion Tokens : ~{c_tok:,}\n"
|
|
354
|
+
f" Total Tokens : ~{t_tok:,}\n"
|
|
355
|
+
f" Estimated USD Cost: ${cost_val:.6f}{note}\n"
|
|
356
|
+
"--------------------------------------------------------------------"
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def build_user_prompt(
|
|
361
|
+
report_data: Dict[str, Any],
|
|
362
|
+
sanitized_diff: Optional[str] = None,
|
|
363
|
+
format_mode: str = "text",
|
|
364
|
+
fix_mode: bool = False,
|
|
365
|
+
) -> str:
|
|
366
|
+
findings = report_data.get("findings", [])
|
|
367
|
+
license_info = report_data.get("license", {})
|
|
368
|
+
summary = report_data.get("summary", {})
|
|
369
|
+
|
|
370
|
+
prompt_parts = [
|
|
371
|
+
"Please review the following Git Security Sentinel scan findings:",
|
|
372
|
+
f"- Scanner Version: {report_data.get('version', 'unknown')}",
|
|
373
|
+
f"- Scan Mode: {report_data.get('scan_mode', 'unknown')}",
|
|
374
|
+
f"- Total Findings: {summary.get('total', 0)} (Critical: {summary.get('critical', 0)}, High: {summary.get('high', 0)}, Medium: {summary.get('medium', 0)}, Low: {summary.get('low', 0)})",
|
|
375
|
+
f"- Root License Present: {license_info.get('root_license_present', False)} (File: {license_info.get('license_file', 'None')})",
|
|
376
|
+
"",
|
|
377
|
+
"Detected Findings (Sensitive data has been deterministically redacted by the scanner):",
|
|
378
|
+
]
|
|
379
|
+
|
|
380
|
+
if not findings:
|
|
381
|
+
prompt_parts.append("No findings were detected in this diff.")
|
|
382
|
+
else:
|
|
383
|
+
for idx, f in enumerate(findings, start=1):
|
|
384
|
+
prompt_parts.append(
|
|
385
|
+
f"{idx}. [{f.get('severity', 'UNKNOWN').upper()}] Rule: {f.get('rule_id')} in {f.get('file')}:{f.get('line')}\n"
|
|
386
|
+
f" Message: {f.get('message')}\n"
|
|
387
|
+
f" Redacted Evidence: {f.get('evidence')}\n"
|
|
388
|
+
f" Scanner Recommendation: {f.get('recommendation')}"
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
if sanitized_diff:
|
|
392
|
+
trimmed_diff = sanitized_diff[:3000]
|
|
393
|
+
if len(sanitized_diff) > 3000:
|
|
394
|
+
trimmed_diff += "\n... [diff truncated for length] ..."
|
|
395
|
+
prompt_parts.append("")
|
|
396
|
+
prompt_parts.append("Sanitized Diff Context (secrets already masked):")
|
|
397
|
+
prompt_parts.append("```diff")
|
|
398
|
+
prompt_parts.append(trimmed_diff)
|
|
399
|
+
prompt_parts.append("```")
|
|
400
|
+
|
|
401
|
+
prompt_parts.append("")
|
|
402
|
+
if fix_mode:
|
|
403
|
+
prompt_parts.append(
|
|
404
|
+
"Remediation Diff Requirement:\n"
|
|
405
|
+
"For each verified security risk, include a minimal suggested remediation unified diff "
|
|
406
|
+
"showing how to safely refactor the code (e.g. parameterize queries, remove secrets to environment variables, "
|
|
407
|
+
"or use safe loaders). Do NOT write or apply files to disk."
|
|
408
|
+
)
|
|
409
|
+
prompt_parts.append("")
|
|
410
|
+
|
|
411
|
+
if format_mode == "json":
|
|
412
|
+
prompt_parts.append(
|
|
413
|
+
"Evaluate each finding and return the requested structured JSON object"
|
|
414
|
+
+ (" including suggested_fix_diff where applicable." if fix_mode else ".")
|
|
415
|
+
)
|
|
416
|
+
else:
|
|
417
|
+
prompt_parts.append(
|
|
418
|
+
"Provide your contextual security evaluation. For each finding, evaluate whether it is likely a true vulnerability or a false positive, explain why, and suggest the safest alternative."
|
|
419
|
+
)
|
|
420
|
+
|
|
421
|
+
return "\n".join(prompt_parts)
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def format_ai_review_report(
|
|
425
|
+
model: str,
|
|
426
|
+
provider: str,
|
|
427
|
+
endpoint: str,
|
|
428
|
+
available: bool,
|
|
429
|
+
review_text: Optional[str],
|
|
430
|
+
error_msg: Optional[str],
|
|
431
|
+
report_data: Dict[str, Any],
|
|
432
|
+
format_mode: str = "text",
|
|
433
|
+
fix_mode: bool = False,
|
|
434
|
+
cost_estimate_data: Optional[Dict[str, Any]] = None,
|
|
435
|
+
) -> Dict[str, Any]:
|
|
436
|
+
"""Structure the combined scan and AI review output."""
|
|
437
|
+
structured_data = None
|
|
438
|
+
if review_text and format_mode == "json":
|
|
439
|
+
structured_data = extract_json_from_text(review_text)
|
|
440
|
+
|
|
441
|
+
out: Dict[str, Any] = {
|
|
442
|
+
"reviewer": "git-security-sentinel-ai",
|
|
443
|
+
"version": VERSION,
|
|
444
|
+
"provider": provider,
|
|
445
|
+
"model": model,
|
|
446
|
+
"endpoint": endpoint if provider == "ollama" else "[CLOUD_PROVIDER]",
|
|
447
|
+
"format": format_mode,
|
|
448
|
+
"fix_mode": fix_mode,
|
|
449
|
+
"inference_completed": available and bool(review_text),
|
|
450
|
+
"error": error_msg,
|
|
451
|
+
"original_summary": report_data.get("summary", {}),
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
if cost_estimate_data is not None:
|
|
455
|
+
out["cost_estimate"] = cost_estimate_data
|
|
456
|
+
|
|
457
|
+
if structured_data is not None:
|
|
458
|
+
out["structured_review"] = structured_data
|
|
459
|
+
out["ai_review"] = review_text
|
|
460
|
+
else:
|
|
461
|
+
out["ai_review"] = review_text
|
|
462
|
+
|
|
463
|
+
return out
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def run_ai_review(
|
|
467
|
+
report_data: Dict[str, Any],
|
|
468
|
+
sanitized_diff: Optional[str] = None,
|
|
469
|
+
provider: str = "auto",
|
|
470
|
+
model: Optional[str] = None,
|
|
471
|
+
endpoint: Optional[str] = None,
|
|
472
|
+
allow_remote: bool = False,
|
|
473
|
+
timeout_sec: int = DEFAULT_TIMEOUT_SEC,
|
|
474
|
+
format_mode: str = "text",
|
|
475
|
+
fix_mode: bool = False,
|
|
476
|
+
cost_estimate: bool = False,
|
|
477
|
+
) -> Tuple[bool, Dict[str, Any], str]:
|
|
478
|
+
"""
|
|
479
|
+
Execute AI security review programmatically on a parsed scan report.
|
|
480
|
+
Returns:
|
|
481
|
+
(success: bool, structured_result: Dict[str, Any], formatted_output: str)
|
|
482
|
+
"""
|
|
483
|
+
load_env_file()
|
|
484
|
+
active_provider = detect_provider(provider)
|
|
485
|
+
defaults = PROVIDER_DEFAULTS.get(active_provider, PROVIDER_DEFAULTS["ollama"])
|
|
486
|
+
active_model = model or defaults["model"]
|
|
487
|
+
active_endpoint = endpoint or defaults["endpoint"]
|
|
488
|
+
|
|
489
|
+
# 1. Build prompts & estimate prompt tokens
|
|
490
|
+
system_prompt = build_system_prompt(format_mode=format_mode, fix_mode=fix_mode)
|
|
491
|
+
user_prompt = build_user_prompt(
|
|
492
|
+
report_data,
|
|
493
|
+
sanitized_diff,
|
|
494
|
+
format_mode=format_mode,
|
|
495
|
+
fix_mode=fix_mode,
|
|
496
|
+
)
|
|
497
|
+
prompt_tokens = calculate_token_estimate(system_prompt + "\n" + user_prompt)
|
|
498
|
+
|
|
499
|
+
def _calc_cost_data(comp_tokens: int) -> Optional[Dict[str, Any]]:
|
|
500
|
+
if not cost_estimate:
|
|
501
|
+
return None
|
|
502
|
+
cost_usd = estimate_query_cost(
|
|
503
|
+
prompt_tokens=prompt_tokens,
|
|
504
|
+
completion_tokens=comp_tokens,
|
|
505
|
+
provider=active_provider,
|
|
506
|
+
)
|
|
507
|
+
return {
|
|
508
|
+
"provider": active_provider,
|
|
509
|
+
"model": active_model,
|
|
510
|
+
"prompt_tokens": prompt_tokens,
|
|
511
|
+
"completion_tokens": comp_tokens,
|
|
512
|
+
"total_tokens": prompt_tokens + comp_tokens,
|
|
513
|
+
"estimated_cost_usd": round(cost_usd, 6),
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
# 2. Provider validation & authentication
|
|
517
|
+
api_key: Optional[str] = None
|
|
518
|
+
if active_provider == "ollama":
|
|
519
|
+
if not allow_remote and not is_loopback_url(active_endpoint):
|
|
520
|
+
err_msg = (
|
|
521
|
+
f"Non-loopback endpoint '{active_endpoint}' rejected for privacy. "
|
|
522
|
+
f"By default, Ollama requests must connect to local loopback (127.0.0.1 / localhost). "
|
|
523
|
+
f"Use --allow-remote to explicitly override."
|
|
524
|
+
)
|
|
525
|
+
cost_data = _calc_cost_data(500)
|
|
526
|
+
out_struct = format_ai_review_report(
|
|
527
|
+
model=active_model,
|
|
528
|
+
provider=active_provider,
|
|
529
|
+
endpoint=active_endpoint,
|
|
530
|
+
available=False,
|
|
531
|
+
review_text=None,
|
|
532
|
+
error_msg=err_msg,
|
|
533
|
+
report_data=report_data,
|
|
534
|
+
format_mode=format_mode,
|
|
535
|
+
fix_mode=fix_mode,
|
|
536
|
+
cost_estimate_data=cost_data,
|
|
537
|
+
)
|
|
538
|
+
banner_str = ("\n" + format_cost_banner(cost_data)) if (cost_estimate and cost_data) else ""
|
|
539
|
+
return False, out_struct, f"Error: {err_msg}{banner_str}"
|
|
540
|
+
elif active_provider == "gemini":
|
|
541
|
+
api_key = os.environ.get("GEMINI_API_KEY")
|
|
542
|
+
if not api_key:
|
|
543
|
+
err_msg = (
|
|
544
|
+
"Google AI Studio requires GEMINI_API_KEY environment variable.\n"
|
|
545
|
+
"Set it via PowerShell: $env:GEMINI_API_KEY = 'your_key_here'\n"
|
|
546
|
+
"Or define GEMINI_API_KEY in a local .env file."
|
|
547
|
+
)
|
|
548
|
+
cost_data = _calc_cost_data(500)
|
|
549
|
+
out_struct = format_ai_review_report(
|
|
550
|
+
model=active_model,
|
|
551
|
+
provider=active_provider,
|
|
552
|
+
endpoint=active_endpoint,
|
|
553
|
+
available=False,
|
|
554
|
+
review_text=None,
|
|
555
|
+
error_msg=err_msg,
|
|
556
|
+
report_data=report_data,
|
|
557
|
+
format_mode=format_mode,
|
|
558
|
+
fix_mode=fix_mode,
|
|
559
|
+
cost_estimate_data=cost_data,
|
|
560
|
+
)
|
|
561
|
+
banner_str = ("\n" + format_cost_banner(cost_data)) if (cost_estimate and cost_data) else ""
|
|
562
|
+
return False, out_struct, f"Error: {err_msg}{banner_str}"
|
|
563
|
+
elif active_provider == "openai":
|
|
564
|
+
api_key = os.environ.get("OPENAI_API_KEY")
|
|
565
|
+
if not api_key:
|
|
566
|
+
err_msg = (
|
|
567
|
+
"OpenAI provider requires OPENAI_API_KEY environment variable.\n"
|
|
568
|
+
"Set it via PowerShell: $env:OPENAI_API_KEY = 'your_key_here'"
|
|
569
|
+
)
|
|
570
|
+
cost_data = _calc_cost_data(500)
|
|
571
|
+
out_struct = format_ai_review_report(
|
|
572
|
+
model=active_model,
|
|
573
|
+
provider=active_provider,
|
|
574
|
+
endpoint=active_endpoint,
|
|
575
|
+
available=False,
|
|
576
|
+
review_text=None,
|
|
577
|
+
error_msg=err_msg,
|
|
578
|
+
report_data=report_data,
|
|
579
|
+
format_mode=format_mode,
|
|
580
|
+
fix_mode=fix_mode,
|
|
581
|
+
cost_estimate_data=cost_data,
|
|
582
|
+
)
|
|
583
|
+
banner_str = ("\n" + format_cost_banner(cost_data)) if (cost_estimate and cost_data) else ""
|
|
584
|
+
return False, out_struct, f"Error: {err_msg}{banner_str}"
|
|
585
|
+
elif active_provider == "groq":
|
|
586
|
+
api_key = os.environ.get("GROQ_API_KEY") or os.environ.get("OPENAI_API_KEY")
|
|
587
|
+
if not api_key:
|
|
588
|
+
err_msg = (
|
|
589
|
+
"Groq provider requires GROQ_API_KEY environment variable.\n"
|
|
590
|
+
"Set it via PowerShell: $env:GROQ_API_KEY = 'your_key_here'"
|
|
591
|
+
)
|
|
592
|
+
cost_data = _calc_cost_data(500)
|
|
593
|
+
out_struct = format_ai_review_report(
|
|
594
|
+
model=active_model,
|
|
595
|
+
provider=active_provider,
|
|
596
|
+
endpoint=active_endpoint,
|
|
597
|
+
available=False,
|
|
598
|
+
review_text=None,
|
|
599
|
+
error_msg=err_msg,
|
|
600
|
+
report_data=report_data,
|
|
601
|
+
format_mode=format_mode,
|
|
602
|
+
fix_mode=fix_mode,
|
|
603
|
+
cost_estimate_data=cost_data,
|
|
604
|
+
)
|
|
605
|
+
banner_str = ("\n" + format_cost_banner(cost_data)) if (cost_estimate and cost_data) else ""
|
|
606
|
+
return False, out_struct, f"Error: {err_msg}{banner_str}"
|
|
607
|
+
|
|
608
|
+
# 3. Check Ollama server availability
|
|
609
|
+
if active_provider == "ollama":
|
|
610
|
+
# Support mock patch in caller or wrapper if running under test
|
|
611
|
+
checker = check_ollama_available
|
|
612
|
+
if not hasattr(checker, "assert_called"):
|
|
613
|
+
for mod_name in ("scripts.ai_review", "ai_review"):
|
|
614
|
+
if mod_name in sys.modules:
|
|
615
|
+
mod = sys.modules[mod_name]
|
|
616
|
+
fn = getattr(mod, "check_ollama_available", None)
|
|
617
|
+
if fn and fn is not check_ollama_available:
|
|
618
|
+
checker = fn
|
|
619
|
+
break
|
|
620
|
+
|
|
621
|
+
available, avail_msg = checker(active_endpoint, timeout_sec=5)
|
|
622
|
+
if not available:
|
|
623
|
+
error_info = (
|
|
624
|
+
f"Local Ollama server is not reachable at {active_endpoint}.\n"
|
|
625
|
+
f"Details: {avail_msg}\n\n"
|
|
626
|
+
f"To enable local Gemma AI contextual review:\n"
|
|
627
|
+
f" 1. Install Ollama: https://ollama.com\n"
|
|
628
|
+
f" 2. Start the Ollama daemon: `ollama serve` (or open Ollama app)\n"
|
|
629
|
+
f" 3. Pull the recommended open-weight model: `ollama pull {active_model}`\n"
|
|
630
|
+
f" 4. Re-run this scan.\n\n"
|
|
631
|
+
f"Alternative: If you have a Google AI Studio key, set GEMINI_API_KEY and use `--provider gemini`."
|
|
632
|
+
)
|
|
633
|
+
cost_data = _calc_cost_data(500)
|
|
634
|
+
out_struct = format_ai_review_report(
|
|
635
|
+
model=active_model,
|
|
636
|
+
provider=active_provider,
|
|
637
|
+
endpoint=active_endpoint,
|
|
638
|
+
available=False,
|
|
639
|
+
review_text=None,
|
|
640
|
+
error_msg=error_info,
|
|
641
|
+
report_data=report_data,
|
|
642
|
+
format_mode=format_mode,
|
|
643
|
+
fix_mode=fix_mode,
|
|
644
|
+
cost_estimate_data=cost_data,
|
|
645
|
+
)
|
|
646
|
+
if format_mode == "json":
|
|
647
|
+
out_str = json.dumps(out_struct, indent=2)
|
|
648
|
+
else:
|
|
649
|
+
banner_str = ("\n" + format_cost_banner(cost_data) + "\n") if (cost_estimate and cost_data) else ""
|
|
650
|
+
out_str = (
|
|
651
|
+
"====================================================================\n"
|
|
652
|
+
" GIT SECURITY SENTINEL - LOCAL AI REVIEWER\n"
|
|
653
|
+
"====================================================================\n"
|
|
654
|
+
f"Status: INFERENCE SKIPPED (Ollama Unavailable)\n\n"
|
|
655
|
+
f"{error_info}\n"
|
|
656
|
+
f"{banner_str}"
|
|
657
|
+
"===================================================================="
|
|
658
|
+
)
|
|
659
|
+
return False, out_struct, out_str
|
|
660
|
+
|
|
661
|
+
sys.stderr.write(f"Connecting to {active_provider.upper()} (model: {active_model})...\n")
|
|
662
|
+
|
|
663
|
+
# 4. Query provider
|
|
664
|
+
success: bool = False
|
|
665
|
+
review_text: Optional[str] = None
|
|
666
|
+
err_msg: Optional[str] = None
|
|
667
|
+
|
|
668
|
+
if active_provider == "ollama":
|
|
669
|
+
ollama_query_fn = query_ollama
|
|
670
|
+
if not hasattr(ollama_query_fn, "assert_called"):
|
|
671
|
+
for mod_name in ("scripts.ai_review", "ai_review"):
|
|
672
|
+
if mod_name in sys.modules:
|
|
673
|
+
mod = sys.modules[mod_name]
|
|
674
|
+
fn = getattr(mod, "query_ollama", None)
|
|
675
|
+
if fn and fn is not query_ollama:
|
|
676
|
+
ollama_query_fn = fn
|
|
677
|
+
break
|
|
678
|
+
success, review_text, err_msg = ollama_query_fn(
|
|
679
|
+
endpoint=active_endpoint,
|
|
680
|
+
model=active_model,
|
|
681
|
+
prompt=user_prompt,
|
|
682
|
+
system_prompt=system_prompt,
|
|
683
|
+
timeout_sec=timeout_sec,
|
|
684
|
+
)
|
|
685
|
+
elif active_provider == "gemini":
|
|
686
|
+
success, review_text, err_msg = query_gemini(
|
|
687
|
+
api_key=api_key or "",
|
|
688
|
+
model=active_model,
|
|
689
|
+
prompt=user_prompt,
|
|
690
|
+
system_prompt=system_prompt,
|
|
691
|
+
timeout_sec=timeout_sec,
|
|
692
|
+
)
|
|
693
|
+
elif active_provider in {"openai", "groq"}:
|
|
694
|
+
success, review_text, err_msg = query_openai_compatible(
|
|
695
|
+
endpoint=active_endpoint,
|
|
696
|
+
api_key=api_key or "",
|
|
697
|
+
model=active_model,
|
|
698
|
+
prompt=user_prompt,
|
|
699
|
+
system_prompt=system_prompt,
|
|
700
|
+
timeout_sec=timeout_sec,
|
|
701
|
+
)
|
|
702
|
+
|
|
703
|
+
# 5. Calculate completion tokens and monetary cost
|
|
704
|
+
completion_tokens = calculate_token_estimate(review_text) if (success and review_text) else 500
|
|
705
|
+
cost_data = _calc_cost_data(completion_tokens)
|
|
706
|
+
|
|
707
|
+
# 6. Format results
|
|
708
|
+
out_structure = format_ai_review_report(
|
|
709
|
+
model=active_model,
|
|
710
|
+
provider=active_provider,
|
|
711
|
+
endpoint=active_endpoint,
|
|
712
|
+
available=True,
|
|
713
|
+
review_text=review_text if success else None,
|
|
714
|
+
error_msg=err_msg if not success else None,
|
|
715
|
+
report_data=report_data,
|
|
716
|
+
format_mode=format_mode,
|
|
717
|
+
fix_mode=fix_mode,
|
|
718
|
+
cost_estimate_data=cost_data,
|
|
719
|
+
)
|
|
720
|
+
|
|
721
|
+
if format_mode == "json":
|
|
722
|
+
out_str = json.dumps(out_structure, indent=2)
|
|
723
|
+
else:
|
|
724
|
+
out_lines = [
|
|
725
|
+
"====================================================================",
|
|
726
|
+
f" GIT SECURITY SENTINEL - AI SECURITY REVIEW ({active_provider.upper()} - {active_model})",
|
|
727
|
+
"====================================================================",
|
|
728
|
+
f"Provider : {active_provider.upper()}",
|
|
729
|
+
f"Status : {'COMPLETED' if success else 'FAILED'}",
|
|
730
|
+
"-" * 68,
|
|
731
|
+
]
|
|
732
|
+
if cost_estimate and cost_data:
|
|
733
|
+
out_lines.append(format_cost_banner(cost_data))
|
|
734
|
+
if success and review_text:
|
|
735
|
+
out_lines.append(review_text)
|
|
736
|
+
else:
|
|
737
|
+
out_lines.append(f"Inference Error: {err_msg}")
|
|
738
|
+
out_lines.append("=" * 68)
|
|
739
|
+
out_str = "\n".join(out_lines)
|
|
740
|
+
|
|
741
|
+
return success, out_structure, out_str
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
def build_arg_parser(prog: Optional[str] = None) -> argparse.ArgumentParser:
|
|
745
|
+
parser = argparse.ArgumentParser(
|
|
746
|
+
prog=prog or "git-sentinel-ai",
|
|
747
|
+
description="Git Security Sentinel: Multi-Provider AI Security Reviewer.",
|
|
748
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
749
|
+
epilog="""Examples:
|
|
750
|
+
# 1. Local Ollama (Default, 100% Private, Zero Key):
|
|
751
|
+
git-sentinel-ai --report scan-report.json
|
|
752
|
+
git-sentinel-ai --report scan-report.json --provider ollama --model gemma3:4b
|
|
753
|
+
|
|
754
|
+
# 2. Google AI Studio (Gemini):
|
|
755
|
+
git-sentinel-ai --report scan-report.json --provider gemini --model gemini-1.5-flash
|
|
756
|
+
|
|
757
|
+
# 3. OpenAI or Groq:
|
|
758
|
+
git-sentinel-ai --report scan-report.json --provider openai --model gpt-4o-mini
|
|
759
|
+
git-sentinel-ai --report scan-report.json --provider groq --model llama-3.3-70b-versatile
|
|
760
|
+
|
|
761
|
+
# 4. Machine-Readable Structured JSON Mode:
|
|
762
|
+
git-sentinel-ai --report scan-report.json --format json --output ai-review.json
|
|
763
|
+
""",
|
|
764
|
+
)
|
|
765
|
+
|
|
766
|
+
parser.add_argument(
|
|
767
|
+
"--version",
|
|
768
|
+
action="version",
|
|
769
|
+
version=f"%(prog)s {VERSION}",
|
|
770
|
+
help="Show program's version number and exit.",
|
|
771
|
+
)
|
|
772
|
+
parser.add_argument(
|
|
773
|
+
"--report",
|
|
774
|
+
required=True,
|
|
775
|
+
metavar="JSON_FILE",
|
|
776
|
+
help="Path to JSON scan report generated by scan_diff.py or git-scan.",
|
|
777
|
+
)
|
|
778
|
+
parser.add_argument(
|
|
779
|
+
"--diff",
|
|
780
|
+
metavar="DIFF_FILE",
|
|
781
|
+
help="Optional path to sanitized diff patch file for contextual inspection.",
|
|
782
|
+
)
|
|
783
|
+
parser.add_argument(
|
|
784
|
+
"--provider",
|
|
785
|
+
choices=["auto", "ollama", "gemini", "openai", "groq"],
|
|
786
|
+
default="auto",
|
|
787
|
+
help="Inference provider to use (default: auto detects based on API keys, or falls back to ollama).",
|
|
788
|
+
)
|
|
789
|
+
parser.add_argument(
|
|
790
|
+
"--model",
|
|
791
|
+
metavar="MODEL_NAME",
|
|
792
|
+
help="Model name (defaults to provider's recommended model if omitted).",
|
|
793
|
+
)
|
|
794
|
+
parser.add_argument(
|
|
795
|
+
"--endpoint",
|
|
796
|
+
metavar="URL",
|
|
797
|
+
help="Custom API endpoint (defaults to provider's standard endpoint).",
|
|
798
|
+
)
|
|
799
|
+
parser.add_argument(
|
|
800
|
+
"--allow-remote",
|
|
801
|
+
action="store_true",
|
|
802
|
+
help="Explicitly permit non-loopback endpoints for Ollama (disabled by default for privacy).",
|
|
803
|
+
)
|
|
804
|
+
parser.add_argument(
|
|
805
|
+
"--timeout",
|
|
806
|
+
type=int,
|
|
807
|
+
default=DEFAULT_TIMEOUT_SEC,
|
|
808
|
+
metavar="SECONDS",
|
|
809
|
+
help=f"Inference HTTP request timeout in seconds (default: {DEFAULT_TIMEOUT_SEC}).",
|
|
810
|
+
)
|
|
811
|
+
parser.add_argument(
|
|
812
|
+
"--format",
|
|
813
|
+
choices=["text", "json"],
|
|
814
|
+
default="text",
|
|
815
|
+
help="Output format (default: text).",
|
|
816
|
+
)
|
|
817
|
+
parser.add_argument(
|
|
818
|
+
"--fix",
|
|
819
|
+
action="store_true",
|
|
820
|
+
help="Generate and display suggested remediation diffs without auto-applying to files on disk.",
|
|
821
|
+
)
|
|
822
|
+
parser.add_argument(
|
|
823
|
+
"--cost-estimate",
|
|
824
|
+
action="store_true",
|
|
825
|
+
help="Estimate prompt and completion token counts and compute monetary cost in USD across providers.",
|
|
826
|
+
)
|
|
827
|
+
parser.add_argument(
|
|
828
|
+
"--output",
|
|
829
|
+
metavar="OUT_FILE",
|
|
830
|
+
help="Path to save AI review output.",
|
|
831
|
+
)
|
|
832
|
+
|
|
833
|
+
return parser
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def main(argv: Optional[List[str]] = None, prog: Optional[str] = None) -> int:
|
|
837
|
+
load_env_file()
|
|
838
|
+
parser = build_arg_parser(prog=prog)
|
|
839
|
+
args = parser.parse_args(argv)
|
|
840
|
+
|
|
841
|
+
# Read scan report
|
|
842
|
+
report_path = Path(args.report)
|
|
843
|
+
if not report_path.is_file():
|
|
844
|
+
sys.stderr.write(f"Error: Scan report file '{args.report}' does not exist.\n")
|
|
845
|
+
return 2
|
|
846
|
+
|
|
847
|
+
try:
|
|
848
|
+
report_data = json.loads(report_path.read_text(encoding="utf-8"))
|
|
849
|
+
except Exception as e:
|
|
850
|
+
sys.stderr.write(f"Error: Failed to parse scan report JSON '{args.report}': {e}\n")
|
|
851
|
+
return 2
|
|
852
|
+
|
|
853
|
+
# Read optional sanitized diff
|
|
854
|
+
sanitized_diff = None
|
|
855
|
+
if args.diff:
|
|
856
|
+
diff_path = Path(args.diff)
|
|
857
|
+
if diff_path.is_file():
|
|
858
|
+
try:
|
|
859
|
+
sanitized_diff = diff_path.read_text(encoding="utf-8", errors="replace")
|
|
860
|
+
except Exception as e:
|
|
861
|
+
sys.stderr.write(f"Warning: Could not read diff file '{args.diff}': {e}\n")
|
|
862
|
+
|
|
863
|
+
success, out_struct, out_str = run_ai_review(
|
|
864
|
+
report_data=report_data,
|
|
865
|
+
sanitized_diff=sanitized_diff,
|
|
866
|
+
provider=args.provider,
|
|
867
|
+
model=args.model,
|
|
868
|
+
endpoint=args.endpoint,
|
|
869
|
+
allow_remote=args.allow_remote,
|
|
870
|
+
timeout_sec=args.timeout,
|
|
871
|
+
format_mode=args.format,
|
|
872
|
+
fix_mode=args.fix,
|
|
873
|
+
cost_estimate=args.cost_estimate,
|
|
874
|
+
)
|
|
875
|
+
|
|
876
|
+
print(out_str)
|
|
877
|
+
if args.output:
|
|
878
|
+
Path(args.output).write_text(out_str, encoding="utf-8")
|
|
879
|
+
|
|
880
|
+
return 0 if success else 1
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
if __name__ == "__main__":
|
|
884
|
+
sys.exit(main())
|