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 ADDED
@@ -0,0 +1,3 @@
1
+ """BlastDiff: Local-first AI diff review and blast-radius workbench."""
2
+
3
+ __version__ = "0.1.0"
blastdiff/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Module entry point for `python -m blastdiff`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from blastdiff.cli import app
6
+
7
+ if __name__ == "__main__":
8
+ app()
blastdiff/cli.py ADDED
@@ -0,0 +1,448 @@
1
+ """Command-line interface for BlastDiff."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import threading
7
+ import webbrowser
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import typer
12
+ import uvicorn
13
+ from rich.console import Console
14
+ from rich.panel import Panel
15
+ from rich.table import Table
16
+ from rich.text import Text
17
+
18
+ from blastdiff import __version__
19
+ from blastdiff.core.models import (
20
+ STORY_ORDER,
21
+ DiffAnalysis,
22
+ HazardSeverity,
23
+ StoryBucket,
24
+ )
25
+ from blastdiff.engine import analyze_repository, run_verification
26
+ from blastdiff.export import render_agent_repair_prompt
27
+ from blastdiff.git_adapter import GitError
28
+ from blastdiff.mcp_server import run_mcp_stdio
29
+ from blastdiff.server import create_app
30
+
31
+ app = typer.Typer(
32
+ name="blastdiff",
33
+ help="Local-first AI diff review and blast-radius workbench.",
34
+ add_completion=False,
35
+ no_args_is_help=False,
36
+ invoke_without_command=True,
37
+ )
38
+
39
+ console = Console()
40
+ err_console = Console(stderr=True)
41
+
42
+ STORY_LABELS: dict[StoryBucket, str] = {
43
+ StoryBucket.CONTRACT: "CONTRACT & SCHEMA",
44
+ StoryBucket.CORE: "CORE LOGIC",
45
+ StoryBucket.TESTS: "TESTS",
46
+ StoryBucket.CONFIG: "CONFIG",
47
+ StoryBucket.DOCS: "DOCS",
48
+ }
49
+
50
+ SEVERITY_STYLES: dict[HazardSeverity, str] = {
51
+ HazardSeverity.CRITICAL: "bold red",
52
+ HazardSeverity.HIGH: "bold dark_orange",
53
+ HazardSeverity.MEDIUM: "bold yellow",
54
+ }
55
+
56
+
57
+ def _configure_utf8_stdout() -> None:
58
+ """Ensure stdout handles UTF-8 user repository data cleanly on Windows."""
59
+ reconfigure = getattr(sys.stdout, "reconfigure", None)
60
+ if callable(reconfigure):
61
+ try:
62
+ reconfigure(encoding="utf-8", errors="replace")
63
+ except Exception:
64
+ pass
65
+
66
+
67
+ def _format_coverage_pct(analysis: DiffAnalysis) -> str:
68
+ proof = analysis.proof
69
+ if proof.coverage_pct is not None:
70
+ return f"{proof.coverage_pct:.1f}% ({proof.covered_added_lines}/{proof.added_lines_total} lines)"
71
+ if proof.added_lines_total > 0:
72
+ return f"N/A (0/{proof.added_lines_total} measured)"
73
+ return "N/A (no executable additions)"
74
+
75
+
76
+ def _print_compact_banner(analysis: DiffAnalysis, url: str | None = None) -> None:
77
+ """Print a concise mission summary to the terminal."""
78
+ critical_high = sum(
79
+ 1 for h in analysis.hazards if h.severity in (HazardSeverity.CRITICAL, HazardSeverity.HIGH)
80
+ )
81
+ open_threads = sum(1 for t in analysis.threads if t.status == "open")
82
+
83
+ lines = [
84
+ f"[bold cyan]{analysis.repo_name}[/bold cyan] "
85
+ f"[white]{analysis.branch}[/white] vs [dim]{analysis.base_ref}[/dim] "
86
+ f"[dim]({analysis.analysis_ms} ms, Round {analysis.current_round})[/dim]",
87
+ (
88
+ f"Files: [bold]{len(analysis.files)}[/bold] | "
89
+ f"Hazards: [{'bold red' if critical_high else 'bold green'}]{len(analysis.hazards)}[/] | "
90
+ f"Untouched Callers: [{'bold red' if analysis.blast_radius.unmodified_callers_total else 'bold green'}]"
91
+ f"{analysis.blast_radius.unmodified_callers_total}[/] | "
92
+ f"Diff Coverage: [bold]{_format_coverage_pct(analysis)}[/bold] | "
93
+ f"Open Threads: [bold]{open_threads}[/bold]"
94
+ ),
95
+ ]
96
+ if url:
97
+ lines.append(f"Workbench URL: [bold underline blue]{url}[/bold underline blue] [dim](Ctrl+C to stop)[/dim]")
98
+
99
+ console.print(Panel("\n".join(lines), title=f"BlastDiff v{__version__}", border_style="bright_blue"))
100
+
101
+
102
+ def _render_check_report(analysis: DiffAnalysis) -> None:
103
+ """Render full Rich check tables for story buckets, blast radius, proof, and hazards."""
104
+ _print_compact_banner(analysis)
105
+
106
+ # Story Buckets table
107
+ story_table = Table(title="Review Story Buckets", show_header=True, header_style="bold cyan")
108
+ story_table.add_column("Bucket", style="bold")
109
+ story_table.add_column("Files", justify="right")
110
+ story_table.add_column("Additions", justify="right", style="green")
111
+ story_table.add_column("Deletions", justify="right", style="red")
112
+ story_table.add_column("Hazards", justify="right")
113
+
114
+ for bucket in sorted(StoryBucket, key=lambda b: STORY_ORDER[b]):
115
+ bucket_files = [f for f in analysis.files if f.story_bucket == bucket]
116
+ if not bucket_files:
117
+ continue
118
+ adds = sum(f.additions for f in bucket_files)
119
+ dels = sum(f.deletions for f in bucket_files)
120
+ hz = sum(len(f.hazards) for f in bucket_files)
121
+ story_table.add_row(
122
+ STORY_LABELS[bucket],
123
+ str(len(bucket_files)),
124
+ f"+{adds}",
125
+ f"-{dels}",
126
+ f"[red]{hz}[/red]" if hz else "0",
127
+ )
128
+
129
+ if story_table.row_count == 0:
130
+ console.print("[green]Working tree is clean. No diff changes detected.[/green]")
131
+ else:
132
+ console.print(story_table)
133
+
134
+ # Blast Radius & Coverage Proof summary table
135
+ br = analysis.blast_radius
136
+ proof = analysis.proof
137
+ metrics_table = Table(title="Blast Radius & Verification Proof", show_header=True, header_style="bold cyan")
138
+ metrics_table.add_column("Signal", style="bold")
139
+ metrics_table.add_column("Value")
140
+
141
+ metrics_table.add_row("Changed Symbols", str(br.total_symbol_changes))
142
+ metrics_table.add_row(
143
+ "Signature Breaks",
144
+ f"[bold red]{br.signature_breaks}[/bold red]" if br.signature_breaks else "[green]0[/green]",
145
+ )
146
+ metrics_table.add_row(
147
+ "Removed Symbols",
148
+ f"[bold red]{br.removed_symbols}[/bold red]" if br.removed_symbols else "[green]0[/green]",
149
+ )
150
+ metrics_table.add_row(
151
+ "Untouched External Callers",
152
+ f"[bold red]{br.unmodified_callers_total}[/bold red]" if br.unmodified_callers_total else "[green]0[/green]",
153
+ )
154
+ metrics_table.add_row("Coverage Source", proof.coverage_source or "None detected")
155
+ metrics_table.add_row("Diff Line Coverage", _format_coverage_pct(analysis))
156
+ metrics_table.add_row(
157
+ "Static Test Reachability",
158
+ f"{proof.statically_reached_symbols} reached / {proof.unreached_symbols} unreached symbols",
159
+ )
160
+ if proof.last_verify_command:
161
+ status_label = "[bold green]PASS[/bold green]" if proof.last_verify_passed else "[bold red]FAIL[/bold red]"
162
+ metrics_table.add_row("Last Verify Command", f"{status_label} {proof.last_verify_command}")
163
+ console.print(metrics_table)
164
+
165
+ # Hazards table
166
+ if analysis.hazards:
167
+ hazard_table = Table(title="Detected Hazards", show_header=True, header_style="bold cyan")
168
+ hazard_table.add_column("Severity", width=10)
169
+ hazard_table.add_column("Location", style="cyan")
170
+ hazard_table.add_column("Finding")
171
+ hazard_table.add_column("Evidence", style="dim")
172
+
173
+ severity_rank = {
174
+ HazardSeverity.CRITICAL: 0,
175
+ HazardSeverity.HIGH: 1,
176
+ HazardSeverity.MEDIUM: 2,
177
+ }
178
+ for hazard in sorted(analysis.hazards, key=lambda h: (severity_rank[h.severity], h.file_path, h.line)):
179
+ style = SEVERITY_STYLES[hazard.severity]
180
+ sev_text = Text(hazard.severity.value.upper(), style=style)
181
+ hazard_table.add_row(
182
+ sev_text,
183
+ f"{hazard.file_path}:{hazard.line}",
184
+ hazard.title,
185
+ hazard.evidence,
186
+ )
187
+ console.print(hazard_table)
188
+ else:
189
+ console.print("[bold green]No hazards detected.[/bold green]")
190
+
191
+
192
+ def _launch_workbench(
193
+ repo: Path,
194
+ base: str | None,
195
+ staged: bool,
196
+ coverage: Path | None,
197
+ host: str,
198
+ port: int,
199
+ no_open: bool,
200
+ ) -> None:
201
+ """Analyze the repository, print a terminal summary, and start the local web workbench."""
202
+ try:
203
+ analysis = analyze_repository(
204
+ repo_path=repo,
205
+ base_ref=base,
206
+ staged=staged,
207
+ coverage_path=coverage,
208
+ record_round=True,
209
+ )
210
+ except GitError as exc:
211
+ err_console.print(f"[bold red]Git error:[/bold red] {exc}")
212
+ raise typer.Exit(code=1) from exc
213
+
214
+ url = f"http://{host}:{port}"
215
+ _print_compact_banner(analysis, url=url)
216
+
217
+ fastapi_app = create_app(
218
+ repo_path=repo,
219
+ base_ref=base,
220
+ staged=staged,
221
+ coverage_path=coverage,
222
+ )
223
+
224
+ if not no_open:
225
+ timer = threading.Timer(0.6, webbrowser.open, args=[url])
226
+ timer.daemon = True
227
+ timer.start()
228
+
229
+ uvicorn.run(fastapi_app, host=host, port=port, log_level="warning")
230
+
231
+
232
+ @app.callback(invoke_without_command=True)
233
+ def main(
234
+ ctx: typer.Context,
235
+ repo: Path = typer.Option(Path("."), "--repo", "-r", help="Path to the Git repository."),
236
+ base: str | None = typer.Option(None, "--base", "-b", help="Base Git ref to diff against."),
237
+ staged: bool = typer.Option(False, "--staged", help="Analyze staged changes only."),
238
+ coverage: Path | None = typer.Option(None, "--coverage", "-c", help="Path to coverage XML or LCOV file."),
239
+ host: str = typer.Option("127.0.0.1", "--host", help="Bind host for the local web server."),
240
+ port: int = typer.Option(4173, "--port", "-p", help="Bind port for the local web server."),
241
+ no_open: bool = typer.Option(False, "--no-open", help="Do not open the browser automatically."),
242
+ version: bool = typer.Option(False, "--version", "-V", is_eager=True, help="Show BlastDiff version and exit."),
243
+ ) -> None:
244
+ """Launch the local BlastDiff Web Review Workbench when no subcommand is specified."""
245
+ if version:
246
+ typer.echo(f"blastdiff {__version__}")
247
+ raise typer.Exit(code=0)
248
+
249
+ if ctx.invoked_subcommand is None:
250
+ _launch_workbench(
251
+ repo=repo,
252
+ base=base,
253
+ staged=staged,
254
+ coverage=coverage,
255
+ host=host,
256
+ port=port,
257
+ no_open=no_open,
258
+ )
259
+
260
+
261
+ @app.command("open")
262
+ def open_workbench(
263
+ repo: Path = typer.Option(Path("."), "--repo", "-r", help="Path to the Git repository."),
264
+ base: str | None = typer.Option(None, "--base", "-b", help="Base Git ref to diff against."),
265
+ staged: bool = typer.Option(False, "--staged", help="Analyze staged changes only."),
266
+ coverage: Path | None = typer.Option(None, "--coverage", "-c", help="Path to coverage XML or LCOV file."),
267
+ host: str = typer.Option("127.0.0.1", "--host", help="Bind host for the local web server."),
268
+ port: int = typer.Option(4173, "--port", "-p", help="Bind port for the local web server."),
269
+ no_open: bool = typer.Option(False, "--no-open", help="Do not open the browser automatically."),
270
+ ) -> None:
271
+ """Analyze the repository and start the local BlastDiff Web Review Workbench."""
272
+ _launch_workbench(
273
+ repo=repo,
274
+ base=base,
275
+ staged=staged,
276
+ coverage=coverage,
277
+ host=host,
278
+ port=port,
279
+ no_open=no_open,
280
+ )
281
+
282
+
283
+ @app.command("check")
284
+ def check_repo(
285
+ repo: Path = typer.Option(Path("."), "--repo", "-r", help="Path to the Git repository."),
286
+ base: str | None = typer.Option(None, "--base", "-b", help="Base Git ref to diff against."),
287
+ staged: bool = typer.Option(False, "--staged", help="Analyze staged changes only."),
288
+ coverage: Path | None = typer.Option(None, "--coverage", "-c", help="Path to coverage XML or LCOV file."),
289
+ json_output: bool = typer.Option(False, "--json", help="Emit full DiffAnalysis JSON to stdout."),
290
+ fail_on_hazard: bool = typer.Option(
291
+ False,
292
+ "--fail-on-hazard",
293
+ help="Exit with code 1 if any CRITICAL or HIGH hazard is detected.",
294
+ ),
295
+ ) -> None:
296
+ """Run deterministic diff, blast-radius, and coverage checks in the terminal."""
297
+ try:
298
+ analysis = analyze_repository(
299
+ repo_path=repo,
300
+ base_ref=base,
301
+ staged=staged,
302
+ coverage_path=coverage,
303
+ record_round=True,
304
+ )
305
+ except GitError as exc:
306
+ err_console.print(f"[bold red]Git error:[/bold red] {exc}")
307
+ raise typer.Exit(code=1) from exc
308
+
309
+ if json_output:
310
+ _configure_utf8_stdout()
311
+ typer.echo(analysis.model_dump_json(indent=2))
312
+ else:
313
+ _render_check_report(analysis)
314
+
315
+ if fail_on_hazard:
316
+ has_blocking = any(
317
+ h.severity in (HazardSeverity.CRITICAL, HazardSeverity.HIGH) for h in analysis.hazards
318
+ )
319
+ if has_blocking:
320
+ raise typer.Exit(code=1)
321
+
322
+
323
+ @app.command(
324
+ "verify",
325
+ context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
326
+ )
327
+ def verify_repo(
328
+ ctx: typer.Context,
329
+ repo: Path = typer.Option(Path("."), "--repo", "-r", help="Path to the Git repository."),
330
+ base: str | None = typer.Option(None, "--base", "-b", help="Base Git ref to diff against."),
331
+ staged: bool = typer.Option(False, "--staged", help="Analyze staged changes only."),
332
+ ) -> None:
333
+ """Run a verification/test command and update diff coverage proof.
334
+
335
+ Example: blastdiff verify -- pytest --cov=src --cov-report=xml
336
+ """
337
+ cmd_args = list(ctx.args)
338
+ if cmd_args and cmd_args[0] == "--":
339
+ cmd_args = cmd_args[1:]
340
+
341
+ if not cmd_args:
342
+ err_console.print(
343
+ "[bold red]Error:[/bold red] Provide a command to run, e.g. "
344
+ "`blastdiff verify -- pytest --cov=src --cov-report=xml`"
345
+ )
346
+ raise typer.Exit(code=2)
347
+
348
+ try:
349
+ result: dict[str, Any] = run_verification(
350
+ repo_path=repo,
351
+ command=cmd_args,
352
+ base_ref=base,
353
+ staged=staged,
354
+ )
355
+ except GitError as exc:
356
+ err_console.print(f"[bold red]Git error:[/bold red] {exc}")
357
+ raise typer.Exit(code=1) from exc
358
+
359
+ passed = bool(result.get("passed", result.get("returncode", result.get("exit_code", 1)) == 0))
360
+ returncode = int(result.get("returncode", result.get("exit_code", 0 if passed else 1)))
361
+ command_display = result.get("command") or " ".join(cmd_args)
362
+ output_text = str(result.get("output") or result.get("stdout") or "").strip()
363
+ stderr_text = str(result.get("stderr") or "").strip()
364
+
365
+ status_badge = "[bold green]PASSED[/bold green]" if passed else "[bold red]FAILED[/bold red]"
366
+ console.print(f"Verification {status_badge} (exit {returncode}): [cyan]{command_display}[/cyan]")
367
+
368
+ if output_text:
369
+ tail = "\n".join(output_text.splitlines()[-20:])
370
+ console.print(Panel(tail, title="Command Output (tail)", border_style="dim"))
371
+ if stderr_text and stderr_text not in output_text:
372
+ tail_err = "\n".join(stderr_text.splitlines()[-15:])
373
+ err_console.print(Panel(tail_err, title="Stderr (tail)", border_style="red"))
374
+
375
+ # Display updated diff coverage proof
376
+ analysis_obj = result.get("analysis")
377
+ updated_analysis: DiffAnalysis | None = None
378
+ if isinstance(analysis_obj, DiffAnalysis):
379
+ updated_analysis = analysis_obj
380
+ elif isinstance(analysis_obj, dict):
381
+ try:
382
+ updated_analysis = DiffAnalysis.model_validate(analysis_obj)
383
+ except Exception:
384
+ updated_analysis = None
385
+
386
+ if updated_analysis is None:
387
+ try:
388
+ updated_analysis = analyze_repository(
389
+ repo_path=repo,
390
+ base_ref=base,
391
+ staged=staged,
392
+ record_round=False,
393
+ )
394
+ except GitError:
395
+ updated_analysis = None
396
+
397
+ if updated_analysis is not None:
398
+ proof_table = Table(title="Updated Diff Coverage Proof", show_header=True, header_style="bold cyan")
399
+ proof_table.add_column("Metric", style="bold")
400
+ proof_table.add_column("Value")
401
+ proof_table.add_row("Coverage Source", updated_analysis.proof.coverage_source or "None detected")
402
+ proof_table.add_row("Diff Line Coverage", _format_coverage_pct(updated_analysis))
403
+ proof_table.add_row("Covered Added Lines", str(updated_analysis.proof.covered_added_lines))
404
+ proof_table.add_row("Uncovered Added Lines", str(updated_analysis.proof.uncovered_added_lines))
405
+ console.print(proof_table)
406
+ else:
407
+ cov_pct = result.get("coverage_pct")
408
+ if cov_pct is not None:
409
+ console.print(f"Updated Diff Coverage: [bold]{cov_pct}%[/bold]")
410
+
411
+ if not passed:
412
+ raise typer.Exit(code=returncode if returncode != 0 else 1)
413
+
414
+
415
+ @app.command("export")
416
+ def export_prompt(
417
+ repo: Path = typer.Option(Path("."), "--repo", "-r", help="Path to the Git repository."),
418
+ base: str | None = typer.Option(None, "--base", "-b", help="Base Git ref to diff against."),
419
+ staged: bool = typer.Option(False, "--staged", help="Analyze staged changes only."),
420
+ include_hazards: bool = typer.Option(
421
+ True,
422
+ "--include-hazards/--no-hazards",
423
+ help="Include automated deterministic hazards in the Agent Repair Prompt.",
424
+ ),
425
+ ) -> None:
426
+ """Print the Agent Repair Prompt Markdown to stdout."""
427
+ try:
428
+ analysis = analyze_repository(
429
+ repo_path=repo,
430
+ base_ref=base,
431
+ staged=staged,
432
+ record_round=False,
433
+ )
434
+ except GitError as exc:
435
+ err_console.print(f"[bold red]Git error:[/bold red] {exc}")
436
+ raise typer.Exit(code=1) from exc
437
+
438
+ markdown = render_agent_repair_prompt(analysis, include_hazards=include_hazards)
439
+ _configure_utf8_stdout()
440
+ typer.echo(markdown)
441
+
442
+
443
+ @app.command("mcp")
444
+ def start_mcp(
445
+ repo: Path = typer.Option(Path("."), "--repo", "-r", help="Path to the Git repository."),
446
+ ) -> None:
447
+ """Start the BlastDiff MCP server over stdio."""
448
+ run_mcp_stdio(str(repo))
@@ -0,0 +1,5 @@
1
+ """Pure domain analysis layer for BlastDiff.
2
+
3
+ Modules in this package perform deterministic data transformations with zero
4
+ HTTP, CLI, database, or subprocess imports.
5
+ """