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/engine.py ADDED
@@ -0,0 +1,398 @@
1
+ """Orchestration engine connecting GitAdapter, pure core analyzers, and ReviewStore."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import shlex
7
+ import subprocess
8
+ import time
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from blastdiff.core.blast_radius import analyze_blast_radius
13
+ from blastdiff.core.diff_parser import (
14
+ build_untracked_file_review,
15
+ compute_diff_fingerprint,
16
+ parse_unified_diff,
17
+ )
18
+ from blastdiff.core.models import (
19
+ DiffAnalysis,
20
+ FileReview,
21
+ Hazard,
22
+ StoryBucket,
23
+ SymbolImpactReport,
24
+ )
25
+ from blastdiff.core.proof import (
26
+ apply_proof_to_files,
27
+ parse_coverage_xml,
28
+ parse_lcov,
29
+ )
30
+ from blastdiff.core.story import (
31
+ classify_story_bucket,
32
+ compute_risk_score,
33
+ detect_hazards,
34
+ sort_files_by_story,
35
+ )
36
+ from blastdiff.core.symbol_impact import analyze_symbol_impact
37
+ from blastdiff.git_adapter import GitAdapter
38
+ from blastdiff.store import ReviewStore
39
+
40
+ VERIFY_TIMEOUT_SECONDS = 300
41
+
42
+
43
+ def resolve_session_base_ref(
44
+ base_ref: str | None = None, staged: bool = False
45
+ ) -> str:
46
+ """Return the canonical session base_ref key shared by CLI, HTTP, and MCP."""
47
+ if base_ref:
48
+ return base_ref
49
+ if staged:
50
+ return "staged"
51
+ return "HEAD"
52
+
53
+
54
+ def compute_file_hashes(files: list[FileReview]) -> dict[str, str]:
55
+ """Compute stable per-file hashes across hunks and diff metadata."""
56
+ hashes: dict[str, str] = {}
57
+ for file_review in files:
58
+ digest = hashlib.sha256()
59
+ digest.update(file_review.path.encode("utf-8", errors="replace"))
60
+ digest.update(b"\0")
61
+ digest.update((file_review.old_path or "").encode("utf-8", errors="replace"))
62
+ digest.update(b"\0")
63
+ digest.update(file_review.status.encode("ascii"))
64
+ digest.update(f":{file_review.additions}:{file_review.deletions}".encode("ascii"))
65
+ for hunk in file_review.hunks:
66
+ digest.update(b"\0")
67
+ digest.update(hunk.fingerprint.encode("utf-8", errors="replace"))
68
+ hashes[file_review.path] = digest.hexdigest()[:16]
69
+ return hashes
70
+
71
+
72
+ def _parse_coverage(
73
+ coverage_source: str | None, coverage_text: str | None
74
+ ) -> dict[str, dict[int, int]] | None:
75
+ if not coverage_source or coverage_text is None:
76
+ return None
77
+ stripped = coverage_text.lstrip()
78
+ if coverage_source.lower().endswith(".xml") or stripped.startswith("<"):
79
+ return parse_coverage_xml(coverage_text)
80
+ return parse_lcov(coverage_text)
81
+
82
+
83
+ def analyze_repository(
84
+ repo_path: str | Path = ".",
85
+ base_ref: str | None = None,
86
+ staged: bool = False,
87
+ coverage_path: str | Path | None = None,
88
+ record_round: bool = True,
89
+ ) -> DiffAnalysis:
90
+ """Run deterministic end-to-end review analysis on a local Git repository."""
91
+ started = time.perf_counter()
92
+
93
+ adapter = GitAdapter(repo_path)
94
+ repo_info = adapter.info()
95
+ raw_diff, target_label = adapter.get_diff(base_ref=base_ref, staged=staged)
96
+
97
+ files = parse_unified_diff(raw_diff)
98
+
99
+ if base_ref is None and not staged:
100
+ seen_paths = {item.path for item in files}
101
+ for rel_path in adapter.list_untracked_files():
102
+ if rel_path in seen_paths:
103
+ continue
104
+ content = adapter.read_working_file(rel_path)
105
+ if content is not None:
106
+ files.append(build_untracked_file_review(rel_path, content))
107
+ seen_paths.add(rel_path)
108
+
109
+ effective_base_ref: str | None
110
+ if base_ref:
111
+ if target_label.endswith("...HEAD") and adapter.has_head():
112
+ effective_base_ref = adapter.get_merge_base(base_ref, "HEAD") or base_ref
113
+ else:
114
+ effective_base_ref = base_ref
115
+ else:
116
+ effective_base_ref = "HEAD" if adapter.has_head() else None
117
+
118
+ base_sources: dict[str, str] = {}
119
+ head_sources: dict[str, str] = {}
120
+
121
+ if effective_base_ref:
122
+ base_paths_to_read = [
123
+ file_review.old_path or file_review.path
124
+ for file_review in files
125
+ if file_review.status != "added"
126
+ ]
127
+ base_blobs = adapter.read_files_at_ref_batch(effective_base_ref, base_paths_to_read)
128
+ for file_review in files:
129
+ if file_review.status == "added":
130
+ continue
131
+ old_rel = file_review.old_path or file_review.path
132
+ base_text = base_blobs.get(old_rel)
133
+ if base_text is not None:
134
+ base_sources[file_review.path] = base_text
135
+ if old_rel != file_review.path:
136
+ base_sources[old_rel] = base_text
137
+
138
+ if base_ref and target_label.endswith("...HEAD"):
139
+ head_paths_to_read = [f.path for f in files if f.status != "deleted"]
140
+ head_sources = adapter.read_files_at_ref_batch("HEAD", head_paths_to_read)
141
+ else:
142
+ for file_review in files:
143
+ if file_review.status == "deleted":
144
+ continue
145
+ if staged:
146
+ head_text = adapter.read_staged_file(file_review.path)
147
+ if head_text is None:
148
+ head_text = adapter.read_working_file(file_review.path)
149
+ else:
150
+ head_text = adapter.read_working_file(file_review.path)
151
+
152
+ if head_text is not None:
153
+ head_sources[file_review.path] = head_text
154
+
155
+ repo_sources = adapter.list_repo_source_files()
156
+ for file_review in files:
157
+ if file_review.status == "deleted":
158
+ repo_sources.pop(file_review.path, None)
159
+ elif file_review.path in head_sources:
160
+ repo_sources[file_review.path] = head_sources[file_review.path]
161
+
162
+ blast_radius, symbol_changes_by_file, reaching_tests_by_file = analyze_blast_radius(
163
+ files=files,
164
+ base_sources=base_sources,
165
+ head_sources=head_sources,
166
+ repo_sources=repo_sources,
167
+ )
168
+
169
+ for file_review in files:
170
+ file_review.symbol_changes = symbol_changes_by_file.get(file_review.path, [])
171
+ file_review.reaching_tests = reaching_tests_by_file.get(file_review.path, [])
172
+ file_review.story_bucket = classify_story_bucket(
173
+ file_review, file_review.symbol_changes
174
+ )
175
+
176
+ coverage_source, coverage_text = adapter.auto_discover_coverage(
177
+ explicit_path=coverage_path
178
+ )
179
+ coverage_map = _parse_coverage(coverage_source, coverage_text)
180
+ proof_summary = apply_proof_to_files(files, coverage_map, coverage_source)
181
+
182
+ arch_rules = adapter.load_arch_rules()
183
+ hazards = detect_hazards(files, head_sources, arch_rules)
184
+
185
+ hazards_by_file: dict[str, list[Hazard]] = {}
186
+ for hazard in hazards:
187
+ hazards_by_file.setdefault(hazard.file_path, []).append(hazard)
188
+
189
+ for file_review in files:
190
+ file_review.hazards = hazards_by_file.get(file_review.path, [])
191
+ file_review.risk_score = compute_risk_score(file_review)
192
+
193
+ files = sort_files_by_story(files)
194
+
195
+ story_counts = {bucket.value: 0 for bucket in StoryBucket}
196
+ for file_review in files:
197
+ bucket_key = file_review.story_bucket.value
198
+ story_counts[bucket_key] = story_counts.get(bucket_key, 0) + 1
199
+
200
+ diff_fingerprint = compute_diff_fingerprint(files)
201
+ file_hashes = compute_file_hashes(files)
202
+
203
+ store = ReviewStore(repo_info.git_dir)
204
+ session_base_ref = resolve_session_base_ref(base_ref=base_ref, staged=staged)
205
+ session_id = store.get_or_create_session(
206
+ branch=repo_info.branch, base_ref=session_base_ref
207
+ )
208
+
209
+ round_summary = (
210
+ f"{len(files)} files, {len(hazards)} hazards, "
211
+ f"{blast_radius.signature_breaks} signature breaks"
212
+ )
213
+ if record_round:
214
+ current_round_obj, _ = store.record_round_if_changed(
215
+ session_id=session_id,
216
+ head_sha=repo_info.head_sha,
217
+ diff_fingerprint=diff_fingerprint,
218
+ file_hashes=file_hashes,
219
+ summary=round_summary,
220
+ )
221
+ rounds = store.list_rounds(session_id)
222
+ current_round = current_round_obj.round_number
223
+ else:
224
+ rounds = store.list_rounds(session_id)
225
+ current_round = rounds[-1].round_number if rounds else 1
226
+
227
+ delta_since_last_round = store.compute_delta(session_id, file_hashes)
228
+
229
+ # Preserve every tracked thread without dropping open threads whose hunk moved.
230
+ threads = store.list_threads(session_id)
231
+
232
+ latest_verification = store.get_latest_verification(session_id)
233
+ if latest_verification is not None:
234
+ proof_summary.last_verify_command = latest_verification["command"]
235
+ proof_summary.last_verify_passed = latest_verification["passed"]
236
+ proof_summary.last_verify_output = latest_verification["output"]
237
+
238
+ analysis_ms = max(0, int((time.perf_counter() - started) * 1000))
239
+
240
+ return DiffAnalysis(
241
+ repo_name=repo_info.repo_name,
242
+ repo_root=repo_info.repo_root,
243
+ branch=repo_info.branch,
244
+ base_ref=session_base_ref,
245
+ target_label=target_label,
246
+ diff_fingerprint=diff_fingerprint,
247
+ analysis_ms=analysis_ms,
248
+ files=files,
249
+ story_counts=story_counts,
250
+ hazards=hazards,
251
+ blast_radius=blast_radius,
252
+ proof=proof_summary,
253
+ arch_rules_loaded=len(arch_rules),
254
+ current_round=current_round,
255
+ rounds=rounds,
256
+ threads=threads,
257
+ delta_since_last_round=delta_since_last_round,
258
+ )
259
+
260
+
261
+ def run_verification(
262
+ repo_path: str | Path,
263
+ command: list[str],
264
+ base_ref: str | None = None,
265
+ staged: bool = False,
266
+ ) -> dict[str, Any]:
267
+ """Run a verification command in the repo, store the result, and re-analyze."""
268
+ if not command:
269
+ raise ValueError("Verification command must not be empty.")
270
+
271
+ adapter = GitAdapter(repo_path)
272
+ repo_info = adapter.info()
273
+ command_str = shlex.join(command)
274
+
275
+ try:
276
+ proc = subprocess.run(
277
+ command,
278
+ cwd=str(adapter.repo_root),
279
+ capture_output=True,
280
+ text=True,
281
+ encoding="utf-8",
282
+ errors="replace",
283
+ timeout=VERIFY_TIMEOUT_SECONDS,
284
+ check=False,
285
+ )
286
+ exit_code = int(proc.returncode)
287
+ passed = exit_code == 0
288
+ output_parts = [part for part in (proc.stdout, proc.stderr) if part]
289
+ output = "\n".join(output_parts).strip()
290
+ except subprocess.TimeoutExpired as exc:
291
+ exit_code = 124
292
+ passed = False
293
+ stdout = exc.stdout.decode("utf-8", errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
294
+ stderr = exc.stderr.decode("utf-8", errors="replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "")
295
+ output = "\n".join(
296
+ part
297
+ for part in (
298
+ stdout,
299
+ stderr,
300
+ f"Command timed out after {VERIFY_TIMEOUT_SECONDS}s: {command_str}",
301
+ )
302
+ if part
303
+ ).strip()
304
+ except FileNotFoundError:
305
+ exit_code = 127
306
+ passed = False
307
+ output = f"Command executable not found: {command[0]}"
308
+ except OSError as exc:
309
+ exit_code = 1
310
+ passed = False
311
+ output = f"Failed to execute verification command: {exc}"
312
+
313
+ coverage_source, _ = adapter.auto_discover_coverage()
314
+ store = ReviewStore(repo_info.git_dir)
315
+ session_base_ref = resolve_session_base_ref(base_ref=base_ref, staged=staged)
316
+ session_id = store.get_or_create_session(
317
+ branch=repo_info.branch, base_ref=session_base_ref
318
+ )
319
+ store.record_verification(
320
+ session_id=session_id,
321
+ command=command_str,
322
+ passed=passed,
323
+ output=output,
324
+ coverage_source=coverage_source,
325
+ )
326
+
327
+ analysis = analyze_repository(
328
+ repo_path=repo_path,
329
+ base_ref=base_ref,
330
+ staged=staged,
331
+ record_round=True,
332
+ )
333
+
334
+ return {
335
+ "passed": passed,
336
+ "exit_code": exit_code,
337
+ "command": command_str,
338
+ "output": output,
339
+ "analysis": analysis,
340
+ }
341
+
342
+
343
+ def analyze_symbol_impact_in_repo(
344
+ repo_path: str | Path,
345
+ symbol: str,
346
+ file_path: str,
347
+ line: int,
348
+ base_ref: str | None = None,
349
+ staged: bool = False,
350
+ cached_files: list[FileReview] | None = None,
351
+ ) -> SymbolImpactReport:
352
+ """Resolve diff-aware bidirectional impact for a symbol at (file_path, line)."""
353
+ adapter = GitAdapter(repo_path)
354
+
355
+ if cached_files is None:
356
+ analysis = analyze_repository(
357
+ repo_path=repo_path,
358
+ base_ref=base_ref,
359
+ staged=staged,
360
+ record_round=False,
361
+ )
362
+ diff_files = analysis.files
363
+ target_label = analysis.target_label
364
+ else:
365
+ diff_files = cached_files
366
+ target_label = f"{base_ref}...HEAD" if base_ref else ("staged" if staged else "working-tree")
367
+
368
+ head_sources: dict[str, str] = {}
369
+ if base_ref and target_label.endswith("...HEAD"):
370
+ head_paths = [f.path for f in diff_files if f.status != "deleted"]
371
+ head_sources = adapter.read_files_at_ref_batch("HEAD", head_paths)
372
+ else:
373
+ for f in diff_files:
374
+ if f.status == "deleted":
375
+ continue
376
+ content = (
377
+ adapter.read_staged_file(f.path) if staged else adapter.read_working_file(f.path)
378
+ )
379
+ if content is None:
380
+ content = adapter.read_working_file(f.path)
381
+ if content is not None:
382
+ head_sources[f.path] = content
383
+
384
+ repo_sources = adapter.list_repo_source_files()
385
+ for f in diff_files:
386
+ if f.status == "deleted":
387
+ repo_sources.pop(f.path, None)
388
+ elif f.path in head_sources:
389
+ repo_sources[f.path] = head_sources[f.path]
390
+
391
+ return analyze_symbol_impact(
392
+ symbol=symbol,
393
+ source_file=file_path,
394
+ source_line=line,
395
+ files=diff_files,
396
+ head_sources=head_sources,
397
+ repo_sources=repo_sources,
398
+ )
blastdiff/export.py ADDED
@@ -0,0 +1,160 @@
1
+ """Agent Repair Prompt exporter for BlastDiff."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from blastdiff.core.models import (
6
+ DiffAnalysis,
7
+ Hazard,
8
+ HazardSeverity,
9
+ ReviewThread,
10
+ )
11
+
12
+ _SEVERITY_RANK: dict[HazardSeverity, int] = {
13
+ HazardSeverity.CRITICAL: 0,
14
+ HazardSeverity.HIGH: 1,
15
+ HazardSeverity.MEDIUM: 2,
16
+ }
17
+
18
+ _THREAD_SEVERITY_RANK: dict[str, int] = {
19
+ "blocker": 0,
20
+ "suggestion": 1,
21
+ "question": 2,
22
+ "note": 3,
23
+ }
24
+
25
+
26
+ def render_agent_repair_prompt(
27
+ analysis: DiffAnalysis, include_hazards: bool = True
28
+ ) -> str:
29
+ """Render a focused Markdown repair brief for any AI coding agent."""
30
+ lines: list[str] = [
31
+ "# BlastDiff Repair Brief",
32
+ "",
33
+ f"- Repository: `{analysis.repo_name}`",
34
+ f"- Branch: `{analysis.branch}`",
35
+ f"- Base: `{analysis.base_ref}` (target: `{analysis.target_label}`)",
36
+ f"- Review Round: `{analysis.current_round}`",
37
+ "",
38
+ ]
39
+
40
+ file_order = {
41
+ file_review.path: index for index, file_review in enumerate(analysis.files)
42
+ }
43
+
44
+ open_threads = [
45
+ thread for thread in analysis.threads if thread.status == "open"
46
+ ]
47
+ lines.append("## Open Review Threads")
48
+ lines.append("")
49
+
50
+ if not open_threads:
51
+ lines.append("No open review threads.")
52
+ lines.append("")
53
+ else:
54
+ grouped: dict[str, list[ReviewThread]] = {}
55
+ for thread in open_threads:
56
+ grouped.setdefault(thread.file_path, []).append(thread)
57
+
58
+ sorted_paths = sorted(
59
+ grouped.keys(),
60
+ key=lambda path: (file_order.get(path, 10_000), path),
61
+ )
62
+ for file_path in sorted_paths:
63
+ lines.append(f"### `{file_path}`")
64
+ file_threads = sorted(
65
+ grouped[file_path],
66
+ key=lambda item: (
67
+ item.line,
68
+ _THREAD_SEVERITY_RANK.get(item.severity, 9),
69
+ item.id,
70
+ ),
71
+ )
72
+ for thread in file_threads:
73
+ anchor = f"`{thread.file_path}:{thread.line}`"
74
+ symbol_part = (
75
+ f" (`{thread.symbol_name}`)" if thread.symbol_name else ""
76
+ )
77
+ severity_tag = thread.severity.upper()
78
+ lines.append(
79
+ f"- **[{severity_tag}]** {anchor}{symbol_part} "
80
+ f"[thread `{thread.id}`]: {thread.body}"
81
+ )
82
+ lines.append("")
83
+
84
+ if include_hazards:
85
+ priority_hazards: list[Hazard] = sorted(
86
+ (
87
+ hazard
88
+ for hazard in analysis.hazards
89
+ if hazard.severity
90
+ in (HazardSeverity.CRITICAL, HazardSeverity.HIGH)
91
+ ),
92
+ key=lambda item: (
93
+ _SEVERITY_RANK.get(item.severity, 9),
94
+ file_order.get(item.file_path, 10_000),
95
+ item.file_path,
96
+ item.line,
97
+ ),
98
+ )
99
+
100
+ lines.append("## Structural Hazards (Critical & High)")
101
+ lines.append("")
102
+ if not priority_hazards:
103
+ lines.append("No critical or high structural hazards detected.")
104
+ lines.append("")
105
+ else:
106
+ for hazard in priority_hazards:
107
+ anchor = f"`{hazard.file_path}:{hazard.line}`"
108
+ symbol_part = (
109
+ f" (`{hazard.symbol_name}`)" if hazard.symbol_name else ""
110
+ )
111
+ lines.append(
112
+ f"- **[{hazard.severity.value.upper()}]** "
113
+ f"{anchor}{symbol_part}: {hazard.title}"
114
+ )
115
+ if hazard.evidence:
116
+ lines.append(f" - Evidence: {hazard.evidence}")
117
+ if hazard.suggestion:
118
+ lines.append(f" - Fix: {hazard.suggestion}")
119
+ lines.append("")
120
+
121
+ untouched_changes = [
122
+ change
123
+ for change in analysis.blast_radius.changes
124
+ if change.unmodified_caller_count > 0
125
+ ]
126
+ if untouched_changes:
127
+ lines.append("## Untouched Callers to Verify")
128
+ lines.append("")
129
+ for change in untouched_changes:
130
+ lines.append(
131
+ f"- `{change.file_path}:{change.start_line}` "
132
+ f"`{change.name}` ({change.change_type}, "
133
+ f"{change.unmodified_caller_count} untouched caller(s)):"
134
+ )
135
+ untouched = [
136
+ caller for caller in change.callers if not caller.in_diff
137
+ ]
138
+ for caller in untouched[:15]:
139
+ enclosing = (
140
+ f" in `{caller.enclosing_symbol}`"
141
+ if caller.enclosing_symbol
142
+ else ""
143
+ )
144
+ lines.append(
145
+ f" - `{caller.file_path}:{caller.line}`{enclosing}"
146
+ )
147
+ lines.append("")
148
+
149
+ lines.extend(
150
+ [
151
+ "## Instructions",
152
+ "",
153
+ "1. Fix only the listed open review threads and structural hazards.",
154
+ "2. Update all affected callers for any changed or removed symbols.",
155
+ "3. Run the relevant tests and confirm changed lines are covered and passing.",
156
+ "4. Leave unrelated files and formatting untouched.",
157
+ ]
158
+ )
159
+
160
+ return "\n".join(lines) + "\n"