blastdiff 0.1.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.
- blastdiff/__init__.py +3 -0
- blastdiff/__main__.py +8 -0
- blastdiff/cli.py +448 -0
- blastdiff/core/__init__.py +5 -0
- blastdiff/core/blast_radius.py +456 -0
- blastdiff/core/diff_parser.py +368 -0
- blastdiff/core/languages/__init__.py +17 -0
- blastdiff/core/languages/base.py +111 -0
- blastdiff/core/languages/go_lang.py +219 -0
- blastdiff/core/languages/python_lang.py +226 -0
- blastdiff/core/languages/rust_lang.py +230 -0
- blastdiff/core/languages/ts_lang.py +406 -0
- blastdiff/core/models.py +281 -0
- blastdiff/core/proof.py +257 -0
- blastdiff/core/story.py +566 -0
- blastdiff/core/symbol_impact.py +698 -0
- blastdiff/engine.py +398 -0
- blastdiff/export.py +160 -0
- blastdiff/git_adapter.py +503 -0
- blastdiff/mcp_server.py +589 -0
- blastdiff/server.py +438 -0
- blastdiff/store.py +502 -0
- blastdiff/web/app.js +2387 -0
- blastdiff/web/index.html +272 -0
- blastdiff/web/styles.css +2092 -0
- blastdiff-0.1.0.dist-info/METADATA +186 -0
- blastdiff-0.1.0.dist-info/RECORD +31 -0
- blastdiff-0.1.0.dist-info/WHEEL +5 -0
- blastdiff-0.1.0.dist-info/entry_points.txt +2 -0
- blastdiff-0.1.0.dist-info/licenses/LICENSE +21 -0
- blastdiff-0.1.0.dist-info/top_level.txt +1 -0
blastdiff/core/story.py
ADDED
|
@@ -0,0 +1,566 @@
|
|
|
1
|
+
"""Story-order classification, Tier-1 deterministic hazard detection, and risk scoring."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import fnmatch
|
|
6
|
+
import hashlib
|
|
7
|
+
import re
|
|
8
|
+
from pathlib import PurePosixPath
|
|
9
|
+
|
|
10
|
+
import tree_sitter
|
|
11
|
+
import tree_sitter_javascript
|
|
12
|
+
import tree_sitter_python
|
|
13
|
+
import tree_sitter_typescript
|
|
14
|
+
|
|
15
|
+
from blastdiff.core.blast_radius import is_test_path
|
|
16
|
+
from blastdiff.core.languages.base import get_analyzer_for_path
|
|
17
|
+
from blastdiff.core.models import (
|
|
18
|
+
STORY_ORDER,
|
|
19
|
+
ArchRule,
|
|
20
|
+
FileReview,
|
|
21
|
+
Hazard,
|
|
22
|
+
HazardKind,
|
|
23
|
+
HazardSeverity,
|
|
24
|
+
ImportRef,
|
|
25
|
+
ProofStatus,
|
|
26
|
+
StoryBucket,
|
|
27
|
+
SymbolChange,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
_DOC_EXTENSIONS: frozenset[str] = frozenset({".md", ".markdown", ".mdx", ".rst", ".txt"})
|
|
31
|
+
_CONFIG_EXTENSIONS: frozenset[str] = frozenset({".toml", ".yaml", ".yml", ".json", ".ini", ".cfg", ".xml", ".info"})
|
|
32
|
+
_CONFIG_BASENAMES: frozenset[str] = frozenset(
|
|
33
|
+
{"dockerfile", "makefile", "docker-compose.yml", "docker-compose.yaml"}
|
|
34
|
+
)
|
|
35
|
+
_CONTRACT_PATH_RE = re.compile(
|
|
36
|
+
r"(schema|models|types|contracts|interface|proto|openapi)",
|
|
37
|
+
re.IGNORECASE,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
_SECRET_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
|
|
41
|
+
("GitHub personal access token", re.compile(r"ghp_[A-Za-z0-9]{20,}")),
|
|
42
|
+
("API secret key", re.compile(r"sk-[A-Za-z0-9]{20,}")),
|
|
43
|
+
("AWS access key ID", re.compile(r"AKIA[0-9A-Z]{16}")),
|
|
44
|
+
(
|
|
45
|
+
"Private key block",
|
|
46
|
+
re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----"),
|
|
47
|
+
),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
_PY_DEBUG_RE = re.compile(r"\b(?:breakpoint\s*\(|pdb\.set_trace\s*\()")
|
|
51
|
+
_JS_DEBUG_RE = re.compile(r"(?:^|[;\s{}])debugger\s*;?(?:\s*(?://.*)?$)")
|
|
52
|
+
_PY_EXCEPT_PASS_INLINE_RE = re.compile(r"^\s*except\b.*:\s*pass\s*(?:#.*)?$")
|
|
53
|
+
_PY_EXCEPT_HEADER_RE = re.compile(r"^\s*except\b.*:\s*(?:#.*)?$")
|
|
54
|
+
_PY_PASS_ONLY_RE = re.compile(r"^\s*pass\s*(?:#.*)?$")
|
|
55
|
+
_JS_EMPTY_CATCH_RE = re.compile(r"\bcatch\s*(?:\([^)]*\))?\s*\{\s*\}")
|
|
56
|
+
|
|
57
|
+
_PY_PARSER: tree_sitter.Parser | None = None
|
|
58
|
+
_TS_PARSER: tree_sitter.Parser | None = None
|
|
59
|
+
_TSX_PARSER: tree_sitter.Parser | None = None
|
|
60
|
+
_JS_PARSER: tree_sitter.Parser | None = None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _get_parser_for_file(file_path: str, language: str) -> tree_sitter.Parser | None:
|
|
64
|
+
global _PY_PARSER, _TS_PARSER, _TSX_PARSER, _JS_PARSER
|
|
65
|
+
if language == "python":
|
|
66
|
+
if _PY_PARSER is None:
|
|
67
|
+
_PY_PARSER = tree_sitter.Parser(tree_sitter.Language(tree_sitter_python.language()))
|
|
68
|
+
return _PY_PARSER
|
|
69
|
+
if language == "typescript":
|
|
70
|
+
suffix = PurePosixPath(file_path.replace("\\", "/")).suffix.lower()
|
|
71
|
+
if suffix == ".tsx":
|
|
72
|
+
if _TSX_PARSER is None:
|
|
73
|
+
_TSX_PARSER = tree_sitter.Parser(
|
|
74
|
+
tree_sitter.Language(tree_sitter_typescript.language_tsx())
|
|
75
|
+
)
|
|
76
|
+
return _TSX_PARSER
|
|
77
|
+
if _TS_PARSER is None:
|
|
78
|
+
_TS_PARSER = tree_sitter.Parser(
|
|
79
|
+
tree_sitter.Language(tree_sitter_typescript.language_typescript())
|
|
80
|
+
)
|
|
81
|
+
return _TS_PARSER
|
|
82
|
+
if language == "javascript":
|
|
83
|
+
if _JS_PARSER is None:
|
|
84
|
+
_JS_PARSER = tree_sitter.Parser(tree_sitter.Language(tree_sitter_javascript.language()))
|
|
85
|
+
return _JS_PARSER
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _is_exported_symbol_name(name: str) -> bool:
|
|
90
|
+
if not name or name.startswith("_"):
|
|
91
|
+
return False
|
|
92
|
+
leaf = name.rsplit(".", 1)[-1]
|
|
93
|
+
return not leaf.startswith(("_", "#"))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _make_hazard_id(kind: HazardKind, file_path: str, line: int, key: str) -> str:
|
|
97
|
+
raw = f"{kind.value}:{file_path}:{line}:{key}".encode("utf-8", errors="replace")
|
|
98
|
+
digest = hashlib.sha256(raw).hexdigest()[:10]
|
|
99
|
+
return f"{kind.value}:{digest}"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _glob_matches(file_path: str, pattern: str) -> bool:
|
|
103
|
+
norm_path = file_path.replace("\\", "/").lstrip("./")
|
|
104
|
+
norm_pat = pattern.replace("\\", "/").lstrip("./")
|
|
105
|
+
if fnmatch.fnmatch(norm_path, norm_pat):
|
|
106
|
+
return True
|
|
107
|
+
if norm_pat.startswith("**/") and fnmatch.fnmatch(norm_path, norm_pat[3:]):
|
|
108
|
+
return True
|
|
109
|
+
return False
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _import_matches_forbid(imp: ImportRef, forbid_import: str) -> bool:
|
|
113
|
+
forbid = forbid_import.strip()
|
|
114
|
+
if not forbid:
|
|
115
|
+
return False
|
|
116
|
+
mod = imp.module.strip()
|
|
117
|
+
targets = [mod] if mod else []
|
|
118
|
+
for name in imp.names:
|
|
119
|
+
if mod:
|
|
120
|
+
targets.append(f"{mod}.{name}")
|
|
121
|
+
else:
|
|
122
|
+
targets.append(name)
|
|
123
|
+
|
|
124
|
+
has_glob = any(ch in forbid for ch in ("*", "?", "["))
|
|
125
|
+
for target in targets:
|
|
126
|
+
if has_glob:
|
|
127
|
+
if fnmatch.fnmatch(target, forbid):
|
|
128
|
+
return True
|
|
129
|
+
else:
|
|
130
|
+
if target == forbid:
|
|
131
|
+
return True
|
|
132
|
+
if target.startswith(forbid + ".") or target.startswith(forbid + "/"):
|
|
133
|
+
return True
|
|
134
|
+
# Handle relative JS/TS imports like `../db/client` when forbidding `db` or `db/client`
|
|
135
|
+
if "/" in target:
|
|
136
|
+
segments = [s for s in target.split("/") if s and s not in (".", "..")]
|
|
137
|
+
joined = "/".join(segments)
|
|
138
|
+
if (
|
|
139
|
+
forbid in segments
|
|
140
|
+
or joined == forbid
|
|
141
|
+
or joined.startswith(forbid + "/")
|
|
142
|
+
or joined.endswith("/" + forbid)
|
|
143
|
+
):
|
|
144
|
+
return True
|
|
145
|
+
return False
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _redact_secret(matched: str) -> str:
|
|
149
|
+
if matched.startswith("-----BEGIN"):
|
|
150
|
+
return matched
|
|
151
|
+
if len(matched) <= 8:
|
|
152
|
+
return "***"
|
|
153
|
+
return f"{matched[:6]}...{matched[-2:]}"
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _collect_added_lines(file_review: FileReview) -> tuple[set[int], list[tuple[int, str]]]:
|
|
157
|
+
added_set: set[int] = set()
|
|
158
|
+
added_list: list[tuple[int, str]] = []
|
|
159
|
+
for hunk in file_review.hunks:
|
|
160
|
+
for dl in hunk.lines:
|
|
161
|
+
if dl.kind == "add" and dl.new_lineno is not None:
|
|
162
|
+
added_set.add(dl.new_lineno)
|
|
163
|
+
added_list.append((dl.new_lineno, dl.content))
|
|
164
|
+
return added_set, added_list
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _detect_swallowed_exceptions_ast(
|
|
168
|
+
file_path: str,
|
|
169
|
+
language: str,
|
|
170
|
+
source: str,
|
|
171
|
+
added_lines: set[int],
|
|
172
|
+
) -> list[tuple[int, str]]:
|
|
173
|
+
"""Find newly added swallowed exception handlers using tree-sitter AST."""
|
|
174
|
+
parser = _get_parser_for_file(file_path, language)
|
|
175
|
+
if parser is None or not source or not added_lines:
|
|
176
|
+
return []
|
|
177
|
+
|
|
178
|
+
source_bytes = source.encode("utf-8", errors="replace")
|
|
179
|
+
tree = parser.parse(source_bytes)
|
|
180
|
+
findings: list[tuple[int, str]] = []
|
|
181
|
+
|
|
182
|
+
def walk(node: tree_sitter.Node) -> None:
|
|
183
|
+
ntype = node.type
|
|
184
|
+
if language == "python" and ntype == "except_clause":
|
|
185
|
+
start_line = node.start_point.row + 1
|
|
186
|
+
end_line = node.end_point.row + 1
|
|
187
|
+
if any(start_line <= ln <= end_line for ln in added_lines):
|
|
188
|
+
block = next((c for c in node.children if c.type == "block"), None)
|
|
189
|
+
if block is not None:
|
|
190
|
+
stmts = [c for c in block.named_children if c.type != "comment"]
|
|
191
|
+
if len(stmts) == 1 and stmts[0].type == "pass_statement":
|
|
192
|
+
snippet = source_bytes[node.start_byte : node.end_byte].decode(
|
|
193
|
+
"utf-8", errors="replace"
|
|
194
|
+
)
|
|
195
|
+
first_line = snippet.splitlines()[0].strip() if snippet else "except: pass"
|
|
196
|
+
findings.append((start_line, first_line))
|
|
197
|
+
elif language in ("typescript", "javascript") and ntype == "catch_clause":
|
|
198
|
+
start_line = node.start_point.row + 1
|
|
199
|
+
end_line = node.end_point.row + 1
|
|
200
|
+
if any(start_line <= ln <= end_line for ln in added_lines):
|
|
201
|
+
body = node.child_by_field_name("body")
|
|
202
|
+
if body is None:
|
|
203
|
+
body = next((c for c in node.children if c.type == "statement_block"), None)
|
|
204
|
+
if body is not None:
|
|
205
|
+
stmts = [c for c in body.named_children if c.type != "comment"]
|
|
206
|
+
if len(stmts) == 0:
|
|
207
|
+
snippet = source_bytes[node.start_byte : node.end_byte].decode(
|
|
208
|
+
"utf-8", errors="replace"
|
|
209
|
+
)
|
|
210
|
+
first_line = snippet.splitlines()[0].strip() if snippet else "catch () {}"
|
|
211
|
+
findings.append((start_line, first_line))
|
|
212
|
+
|
|
213
|
+
for child in node.children:
|
|
214
|
+
walk(child)
|
|
215
|
+
|
|
216
|
+
walk(tree.root_node)
|
|
217
|
+
return findings
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _detect_swallowed_exceptions_fallback(
|
|
221
|
+
language: str,
|
|
222
|
+
added_list: list[tuple[int, str]],
|
|
223
|
+
) -> list[tuple[int, str]]:
|
|
224
|
+
"""Fallback detector when head_sources is unavailable for a file."""
|
|
225
|
+
findings: list[tuple[int, str]] = []
|
|
226
|
+
if language == "python":
|
|
227
|
+
for idx, (lineno, text) in enumerate(added_list):
|
|
228
|
+
if _PY_EXCEPT_PASS_INLINE_RE.match(text):
|
|
229
|
+
findings.append((lineno, text.strip()))
|
|
230
|
+
elif _PY_EXCEPT_HEADER_RE.match(text) and idx + 1 < len(added_list):
|
|
231
|
+
next_lineno, next_text = added_list[idx + 1]
|
|
232
|
+
if next_lineno == lineno + 1 and _PY_PASS_ONLY_RE.match(next_text):
|
|
233
|
+
findings.append((lineno, text.strip()))
|
|
234
|
+
elif language in ("typescript", "javascript"):
|
|
235
|
+
for lineno, text in added_list:
|
|
236
|
+
if _JS_EMPTY_CATCH_RE.search(text):
|
|
237
|
+
findings.append((lineno, text.strip()))
|
|
238
|
+
return findings
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _detect_debug_leftovers_ast(
|
|
242
|
+
file_path: str,
|
|
243
|
+
language: str,
|
|
244
|
+
source: str,
|
|
245
|
+
added_lines: set[int],
|
|
246
|
+
) -> list[tuple[int, str]]:
|
|
247
|
+
"""Find newly added debugger calls/statements via tree-sitter AST."""
|
|
248
|
+
parser = _get_parser_for_file(file_path, language)
|
|
249
|
+
if parser is None or not source or not added_lines:
|
|
250
|
+
return []
|
|
251
|
+
|
|
252
|
+
source_bytes = source.encode("utf-8", errors="replace")
|
|
253
|
+
tree = parser.parse(source_bytes)
|
|
254
|
+
findings: list[tuple[int, str]] = []
|
|
255
|
+
|
|
256
|
+
def walk(node: tree_sitter.Node) -> None:
|
|
257
|
+
ntype = node.type
|
|
258
|
+
if language == "python" and ntype == "call":
|
|
259
|
+
line = node.start_point.row + 1
|
|
260
|
+
if line in added_lines:
|
|
261
|
+
func_node = node.child_by_field_name("function")
|
|
262
|
+
if func_node is not None:
|
|
263
|
+
func_txt = source_bytes[func_node.start_byte : func_node.end_byte].decode(
|
|
264
|
+
"utf-8", errors="replace"
|
|
265
|
+
).strip()
|
|
266
|
+
if func_txt in ("breakpoint", "pdb.set_trace"):
|
|
267
|
+
call_txt = source_bytes[node.start_byte : node.end_byte].decode(
|
|
268
|
+
"utf-8", errors="replace"
|
|
269
|
+
).strip()
|
|
270
|
+
findings.append((line, call_txt))
|
|
271
|
+
elif language in ("typescript", "javascript") and ntype == "debugger_statement":
|
|
272
|
+
line = node.start_point.row + 1
|
|
273
|
+
if line in added_lines:
|
|
274
|
+
findings.append((line, "debugger;"))
|
|
275
|
+
|
|
276
|
+
for child in node.children:
|
|
277
|
+
walk(child)
|
|
278
|
+
|
|
279
|
+
walk(tree.root_node)
|
|
280
|
+
return findings
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _detect_debug_leftovers_fallback(
|
|
284
|
+
language: str,
|
|
285
|
+
added_list: list[tuple[int, str]],
|
|
286
|
+
) -> list[tuple[int, str]]:
|
|
287
|
+
findings: list[tuple[int, str]] = []
|
|
288
|
+
for lineno, text in added_list:
|
|
289
|
+
stripped = text.strip()
|
|
290
|
+
if not stripped or stripped.startswith("#") or stripped.startswith("//"):
|
|
291
|
+
continue
|
|
292
|
+
if language == "python" and _PY_DEBUG_RE.search(stripped):
|
|
293
|
+
findings.append((lineno, stripped))
|
|
294
|
+
elif language in ("typescript", "javascript") and _JS_DEBUG_RE.search(stripped):
|
|
295
|
+
findings.append((lineno, stripped))
|
|
296
|
+
return findings
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def classify_story_bucket(
|
|
300
|
+
file_review: FileReview,
|
|
301
|
+
symbol_changes: list[SymbolChange],
|
|
302
|
+
) -> StoryBucket:
|
|
303
|
+
"""Assign a file to its deterministic review story bucket."""
|
|
304
|
+
norm_path = file_review.path.replace("\\", "/")
|
|
305
|
+
low_path = norm_path.lower()
|
|
306
|
+
p = PurePosixPath(norm_path)
|
|
307
|
+
basename = p.name
|
|
308
|
+
basename_lower = basename.lower()
|
|
309
|
+
suffix = p.suffix.lower()
|
|
310
|
+
parts_lower = [part.lower() for part in p.parts]
|
|
311
|
+
|
|
312
|
+
if is_test_path(norm_path):
|
|
313
|
+
return StoryBucket.TESTS
|
|
314
|
+
|
|
315
|
+
if (
|
|
316
|
+
suffix in _DOC_EXTENSIONS
|
|
317
|
+
or "docs" in parts_lower[:-1]
|
|
318
|
+
or basename.upper().startswith("README")
|
|
319
|
+
):
|
|
320
|
+
return StoryBucket.DOCS
|
|
321
|
+
|
|
322
|
+
is_openapi = "openapi" in low_path
|
|
323
|
+
if not is_openapi and (
|
|
324
|
+
suffix in _CONFIG_EXTENSIONS
|
|
325
|
+
or basename_lower in _CONFIG_BASENAMES
|
|
326
|
+
or basename_lower.startswith("dockerfile.")
|
|
327
|
+
or ".github" in parts_lower[:-1]
|
|
328
|
+
):
|
|
329
|
+
return StoryBucket.CONFIG
|
|
330
|
+
|
|
331
|
+
has_contract_symbol_change = any(
|
|
332
|
+
sc.change_type in ("signature_changed", "removed") and _is_exported_symbol_name(sc.name)
|
|
333
|
+
for sc in symbol_changes
|
|
334
|
+
)
|
|
335
|
+
if has_contract_symbol_change or _CONTRACT_PATH_RE.search(low_path):
|
|
336
|
+
return StoryBucket.CONTRACT
|
|
337
|
+
|
|
338
|
+
return StoryBucket.CORE
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def detect_hazards(
|
|
342
|
+
files: list[FileReview],
|
|
343
|
+
head_sources: dict[str, str],
|
|
344
|
+
arch_rules: list[ArchRule],
|
|
345
|
+
) -> list[Hazard]:
|
|
346
|
+
"""Detect Tier-1 deterministic hard-fact hazards across reviewed files."""
|
|
347
|
+
all_hazards: list[Hazard] = []
|
|
348
|
+
hazards_by_file: dict[str, list[Hazard]] = {f.path: [] for f in files}
|
|
349
|
+
|
|
350
|
+
for file_review in files:
|
|
351
|
+
fpath = file_review.path
|
|
352
|
+
file_hazards = hazards_by_file[fpath]
|
|
353
|
+
is_test = is_test_path(fpath)
|
|
354
|
+
|
|
355
|
+
# 1 & 2. SIGNATURE_BREAK and REMOVED_SYMBOL
|
|
356
|
+
for sc in file_review.symbol_changes:
|
|
357
|
+
if not _is_exported_symbol_name(sc.name):
|
|
358
|
+
continue
|
|
359
|
+
if sc.unmodified_caller_count <= 0:
|
|
360
|
+
continue
|
|
361
|
+
|
|
362
|
+
untouched = [c for c in sc.callers if not c.in_diff and not c.is_test]
|
|
363
|
+
caller_locs = ", ".join(f"{c.file_path}:{c.line}" for c in untouched[:5])
|
|
364
|
+
if len(untouched) > 5:
|
|
365
|
+
caller_locs = f"{caller_locs} (+{len(untouched) - 5} more)"
|
|
366
|
+
|
|
367
|
+
if sc.change_type == "signature_changed":
|
|
368
|
+
hz = Hazard(
|
|
369
|
+
id=_make_hazard_id(HazardKind.SIGNATURE_BREAK, fpath, sc.start_line, sc.name),
|
|
370
|
+
kind=HazardKind.SIGNATURE_BREAK,
|
|
371
|
+
severity=HazardSeverity.CRITICAL,
|
|
372
|
+
file_path=fpath,
|
|
373
|
+
line=sc.start_line,
|
|
374
|
+
symbol_name=sc.name,
|
|
375
|
+
title=f"Signature break in '{sc.name}' affects {sc.unmodified_caller_count} untouched caller(s)",
|
|
376
|
+
evidence=(
|
|
377
|
+
f"Old: {sc.old_signature} | New: {sc.new_signature} | "
|
|
378
|
+
f"Untouched callers: {caller_locs}"
|
|
379
|
+
),
|
|
380
|
+
suggestion=(
|
|
381
|
+
f"Update untouched callers ({caller_locs}) or keep backwards-compatible defaults."
|
|
382
|
+
),
|
|
383
|
+
)
|
|
384
|
+
file_hazards.append(hz)
|
|
385
|
+
all_hazards.append(hz)
|
|
386
|
+
elif sc.change_type == "removed":
|
|
387
|
+
hz = Hazard(
|
|
388
|
+
id=_make_hazard_id(HazardKind.REMOVED_SYMBOL, fpath, sc.start_line, sc.name),
|
|
389
|
+
kind=HazardKind.REMOVED_SYMBOL,
|
|
390
|
+
severity=HazardSeverity.CRITICAL,
|
|
391
|
+
file_path=fpath,
|
|
392
|
+
line=sc.start_line,
|
|
393
|
+
symbol_name=sc.name,
|
|
394
|
+
title=f"Removed symbol '{sc.name}' still called by {sc.unmodified_caller_count} untouched caller(s)",
|
|
395
|
+
evidence=f"Removed: {sc.old_signature or sc.name} | Untouched callers: {caller_locs}",
|
|
396
|
+
suggestion=f"Update or remove remaining callers ({caller_locs}) before deleting '{sc.name}'.",
|
|
397
|
+
)
|
|
398
|
+
file_hazards.append(hz)
|
|
399
|
+
all_hazards.append(hz)
|
|
400
|
+
|
|
401
|
+
if file_review.status == "deleted":
|
|
402
|
+
continue
|
|
403
|
+
|
|
404
|
+
head_src = head_sources.get(fpath, "")
|
|
405
|
+
|
|
406
|
+
# 3. LAYER_VIOLATION
|
|
407
|
+
if arch_rules and head_src:
|
|
408
|
+
matching_rules = [r for r in arch_rules if _glob_matches(fpath, r.source_glob)]
|
|
409
|
+
if matching_rules:
|
|
410
|
+
analyzer = get_analyzer_for_path(fpath)
|
|
411
|
+
if analyzer is not None:
|
|
412
|
+
syms = analyzer.analyze_file(fpath, head_src)
|
|
413
|
+
for rule in matching_rules:
|
|
414
|
+
for imp in syms.imports:
|
|
415
|
+
if _import_matches_forbid(imp, rule.forbid_import):
|
|
416
|
+
hz = Hazard(
|
|
417
|
+
id=_make_hazard_id(
|
|
418
|
+
HazardKind.LAYER_VIOLATION,
|
|
419
|
+
fpath,
|
|
420
|
+
imp.line,
|
|
421
|
+
f"{rule.name}:{imp.module}",
|
|
422
|
+
),
|
|
423
|
+
kind=HazardKind.LAYER_VIOLATION,
|
|
424
|
+
severity=HazardSeverity.HIGH,
|
|
425
|
+
file_path=fpath,
|
|
426
|
+
line=imp.line,
|
|
427
|
+
symbol_name=None,
|
|
428
|
+
title=f"Layer violation ({rule.name}): forbidden import '{imp.module}'",
|
|
429
|
+
evidence=(
|
|
430
|
+
f"Rule '{rule.name}' forbids '{rule.forbid_import}' in "
|
|
431
|
+
f"'{rule.source_glob}'; found import '{imp.module}' at {fpath}:{imp.line}."
|
|
432
|
+
),
|
|
433
|
+
suggestion=rule.reason
|
|
434
|
+
or f"Remove import '{imp.module}' to satisfy rule '{rule.name}'.",
|
|
435
|
+
)
|
|
436
|
+
file_hazards.append(hz)
|
|
437
|
+
all_hazards.append(hz)
|
|
438
|
+
|
|
439
|
+
added_set, added_list = _collect_added_lines(file_review)
|
|
440
|
+
if not added_list:
|
|
441
|
+
continue
|
|
442
|
+
|
|
443
|
+
# 4. SWALLOWED_EXCEPTION
|
|
444
|
+
if file_review.language in ("python", "typescript", "javascript"):
|
|
445
|
+
if head_src:
|
|
446
|
+
swallowed = _detect_swallowed_exceptions_ast(
|
|
447
|
+
fpath, file_review.language, head_src, added_set
|
|
448
|
+
)
|
|
449
|
+
else:
|
|
450
|
+
swallowed = _detect_swallowed_exceptions_fallback(file_review.language, added_list)
|
|
451
|
+
|
|
452
|
+
for lineno, snippet in swallowed:
|
|
453
|
+
hz = Hazard(
|
|
454
|
+
id=_make_hazard_id(HazardKind.SWALLOWED_EXCEPTION, fpath, lineno, snippet),
|
|
455
|
+
kind=HazardKind.SWALLOWED_EXCEPTION,
|
|
456
|
+
severity=HazardSeverity.HIGH,
|
|
457
|
+
file_path=fpath,
|
|
458
|
+
line=lineno,
|
|
459
|
+
symbol_name=None,
|
|
460
|
+
title="Swallowed exception with empty handler",
|
|
461
|
+
evidence=f"{fpath}:{lineno}: {snippet}",
|
|
462
|
+
suggestion="Log, handle, or re-raise the exception instead of ignoring it silently.",
|
|
463
|
+
)
|
|
464
|
+
file_hazards.append(hz)
|
|
465
|
+
all_hazards.append(hz)
|
|
466
|
+
|
|
467
|
+
# 5. DEBUG_LEFTOVER (non-test files only)
|
|
468
|
+
if not is_test and file_review.language in ("python", "typescript", "javascript"):
|
|
469
|
+
if head_src:
|
|
470
|
+
debug_hits = _detect_debug_leftovers_ast(
|
|
471
|
+
fpath, file_review.language, head_src, added_set
|
|
472
|
+
)
|
|
473
|
+
else:
|
|
474
|
+
debug_hits = _detect_debug_leftovers_fallback(file_review.language, added_list)
|
|
475
|
+
|
|
476
|
+
for lineno, snippet in debug_hits:
|
|
477
|
+
hz = Hazard(
|
|
478
|
+
id=_make_hazard_id(HazardKind.DEBUG_LEFTOVER, fpath, lineno, snippet),
|
|
479
|
+
kind=HazardKind.DEBUG_LEFTOVER,
|
|
480
|
+
severity=HazardSeverity.MEDIUM,
|
|
481
|
+
file_path=fpath,
|
|
482
|
+
line=lineno,
|
|
483
|
+
symbol_name=None,
|
|
484
|
+
title=f"Debug statement left in code: '{snippet}'",
|
|
485
|
+
evidence=f"{fpath}:{lineno}: {snippet}",
|
|
486
|
+
suggestion="Remove debug breakpoints before merging.",
|
|
487
|
+
)
|
|
488
|
+
file_hazards.append(hz)
|
|
489
|
+
all_hazards.append(hz)
|
|
490
|
+
|
|
491
|
+
# 6. HARDCODED_SECRET (non-test files only)
|
|
492
|
+
if not is_test:
|
|
493
|
+
for lineno, line_text in added_list:
|
|
494
|
+
for label, pattern in _SECRET_PATTERNS:
|
|
495
|
+
match = pattern.search(line_text)
|
|
496
|
+
if match:
|
|
497
|
+
redacted = _redact_secret(match.group(0))
|
|
498
|
+
hz = Hazard(
|
|
499
|
+
id=_make_hazard_id(HazardKind.HARDCODED_SECRET, fpath, lineno, label),
|
|
500
|
+
kind=HazardKind.HARDCODED_SECRET,
|
|
501
|
+
severity=HazardSeverity.CRITICAL,
|
|
502
|
+
file_path=fpath,
|
|
503
|
+
line=lineno,
|
|
504
|
+
symbol_name=None,
|
|
505
|
+
title=f"Potential hardcoded secret detected ({label})",
|
|
506
|
+
evidence=f"{fpath}:{lineno}: matched {label} ({redacted})",
|
|
507
|
+
suggestion="Remove the secret from source control and load it from environment variables.",
|
|
508
|
+
)
|
|
509
|
+
file_hazards.append(hz)
|
|
510
|
+
all_hazards.append(hz)
|
|
511
|
+
break
|
|
512
|
+
|
|
513
|
+
for file_review in files:
|
|
514
|
+
file_review.hazards = hazards_by_file.get(file_review.path, [])
|
|
515
|
+
|
|
516
|
+
severity_rank = {
|
|
517
|
+
HazardSeverity.CRITICAL: 0,
|
|
518
|
+
HazardSeverity.HIGH: 1,
|
|
519
|
+
HazardSeverity.MEDIUM: 2,
|
|
520
|
+
}
|
|
521
|
+
all_hazards.sort(key=lambda h: (severity_rank[h.severity], h.file_path, h.line, h.kind.value))
|
|
522
|
+
return all_hazards
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def compute_risk_score(file_review: FileReview) -> int:
|
|
526
|
+
"""Compute a deterministic 0-100 risk score for a single FileReview."""
|
|
527
|
+
score = 0
|
|
528
|
+
|
|
529
|
+
for hz in file_review.hazards:
|
|
530
|
+
if hz.severity == HazardSeverity.CRITICAL:
|
|
531
|
+
score += 40
|
|
532
|
+
elif hz.severity == HazardSeverity.HIGH:
|
|
533
|
+
score += 25
|
|
534
|
+
elif hz.severity == HazardSeverity.MEDIUM:
|
|
535
|
+
score += 10
|
|
536
|
+
|
|
537
|
+
untouched_callers = 0
|
|
538
|
+
for sc in file_review.symbol_changes:
|
|
539
|
+
if sc.change_type == "signature_changed":
|
|
540
|
+
score += 20
|
|
541
|
+
elif sc.change_type == "removed":
|
|
542
|
+
score += 15
|
|
543
|
+
untouched_callers += sc.unmodified_caller_count
|
|
544
|
+
|
|
545
|
+
score += min(30, untouched_callers * 5)
|
|
546
|
+
|
|
547
|
+
if file_review.proof_status == ProofStatus.UNVERIFIED:
|
|
548
|
+
score += 10
|
|
549
|
+
|
|
550
|
+
if file_review.story_bucket == StoryBucket.CONTRACT:
|
|
551
|
+
score += 10
|
|
552
|
+
elif file_review.story_bucket == StoryBucket.CORE:
|
|
553
|
+
score += 5
|
|
554
|
+
|
|
555
|
+
churn = file_review.additions + file_review.deletions
|
|
556
|
+
score += min(15, churn // 20)
|
|
557
|
+
|
|
558
|
+
return min(100, score)
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def sort_files_by_story(files: list[FileReview]) -> list[FileReview]:
|
|
562
|
+
"""Return files sorted by story bucket order, descending risk score, and path."""
|
|
563
|
+
return sorted(
|
|
564
|
+
files,
|
|
565
|
+
key=lambda f: (STORY_ORDER.get(f.story_bucket, 99), -f.risk_score, f.path),
|
|
566
|
+
)
|