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/server.py ADDED
@@ -0,0 +1,438 @@
1
+ """Local FastAPI server for the BlastDiff Web Review Workbench."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from pathlib import Path
7
+ from typing import Any, Literal
8
+
9
+ from fastapi import FastAPI, HTTPException, Query
10
+ from fastapi.responses import FileResponse
11
+ from fastapi.staticfiles import StaticFiles
12
+ from pydantic import BaseModel, Field
13
+
14
+ from blastdiff import __version__
15
+ from blastdiff.core.languages.base import detect_language
16
+ from blastdiff.core.models import DiffAnalysis, ReviewThread, RoundDelta, SymbolImpactReport
17
+ from blastdiff.engine import analyze_repository, analyze_symbol_impact_in_repo
18
+ from blastdiff.export import render_agent_repair_prompt
19
+ from blastdiff.git_adapter import GitAdapter, GitError
20
+ from blastdiff.store import ReviewStore
21
+
22
+ WEB_DIR = Path(__file__).resolve().parent / "web"
23
+
24
+
25
+ class CreateThreadRequest(BaseModel):
26
+ """Payload for creating a persisted inline review thread."""
27
+
28
+ file_path: str = Field(min_length=1)
29
+ line: int = Field(ge=1)
30
+ body: str = Field(min_length=1)
31
+ severity: Literal["blocker", "suggestion", "question", "note"] = "blocker"
32
+ symbol_name: str | None = None
33
+ hunk_fingerprint: str = ""
34
+ base_ref: str | None = None
35
+ round_created: int | None = Field(default=None, ge=1)
36
+
37
+
38
+ class UpdateThreadRequest(BaseModel):
39
+ """Payload for updating a review thread's status."""
40
+
41
+ status: Literal["open", "resolved", "outdated"]
42
+ round_resolved: int | None = Field(default=None, ge=1)
43
+
44
+
45
+ class ExportResponse(BaseModel):
46
+ """Rendered Markdown payload for the Agent Repair Prompt."""
47
+
48
+ markdown: str
49
+
50
+
51
+ class FileContextLine(BaseModel):
52
+ """Single numbered line returned for caller context preview."""
53
+
54
+ lineno: int
55
+ content: str
56
+
57
+
58
+ class FileContextResponse(BaseModel):
59
+ """Surrounding source lines around a caller or test location."""
60
+
61
+ file_path: str
62
+ abs_path: str
63
+ target_line: int
64
+ start_line: int
65
+ end_line: int
66
+ total_lines: int
67
+ language: str
68
+ lines: list[FileContextLine] = Field(default_factory=list)
69
+
70
+
71
+ def _extract_session_id(session_obj: Any) -> str:
72
+ """Normalize session return values from ReviewStore.get_or_create_session."""
73
+ if isinstance(session_obj, str):
74
+ return session_obj
75
+ if isinstance(session_obj, dict) and "id" in session_obj:
76
+ return str(session_obj["id"])
77
+ session_id = getattr(session_obj, "id", None)
78
+ if session_id is not None:
79
+ return str(session_id)
80
+ return str(session_obj)
81
+
82
+
83
+ def _derive_current_file_hashes(analysis: DiffAnalysis) -> dict[str, str]:
84
+ """Return canonical file hashes matching the active DiffAnalysis state.
85
+
86
+ Prefers the recorded ReviewRound whose diff_fingerprint matches the
87
+ current analysis so hashes align identically with ReviewStore snapshots.
88
+ """
89
+ for review_round in reversed(analysis.rounds):
90
+ if review_round.diff_fingerprint == analysis.diff_fingerprint and review_round.file_hashes:
91
+ return dict(review_round.file_hashes)
92
+
93
+ hashes: dict[str, str] = {}
94
+ for file_review in analysis.files:
95
+ raw = "|".join(hunk.fingerprint for hunk in file_review.hunks)
96
+ if not raw:
97
+ raw = f"{file_review.status}:{file_review.additions}:{file_review.deletions}"
98
+ hashes[file_review.path] = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
99
+ return hashes
100
+
101
+
102
+ def create_app(
103
+ repo_path: str | Path = ".",
104
+ base_ref: str | None = None,
105
+ staged: bool = False,
106
+ coverage_path: str | Path | None = None,
107
+ ) -> FastAPI:
108
+ """Create and configure the local BlastDiff FastAPI application."""
109
+ resolved_repo = Path(repo_path).resolve()
110
+ resolved_coverage = Path(coverage_path).resolve() if coverage_path is not None else None
111
+
112
+ runtime_context: dict[str, Any] = {
113
+ "resolved_base_ref": base_ref,
114
+ "staged": staged,
115
+ "current_round": 1,
116
+ "last_files": None,
117
+ }
118
+
119
+ app = FastAPI(
120
+ title="BlastDiff",
121
+ version=__version__,
122
+ description="Local-first AI diff review and blast-radius workbench.",
123
+ )
124
+
125
+ if WEB_DIR.exists():
126
+ app.mount("/static", StaticFiles(directory=str(WEB_DIR)), name="static")
127
+
128
+ def _effective_options(
129
+ req_base_ref: str | None = None,
130
+ req_staged: bool | None = None,
131
+ ) -> tuple[str | None, bool]:
132
+ effective_base = req_base_ref if req_base_ref not in (None, "") else base_ref
133
+ effective_staged = staged if req_staged is None else req_staged
134
+ return effective_base, effective_staged
135
+
136
+ def _open_store_and_session(
137
+ req_base_ref: str | None = None,
138
+ ) -> tuple[ReviewStore, str, int]:
139
+ try:
140
+ git_info = GitAdapter(resolved_repo).info()
141
+ except GitError as exc:
142
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
143
+
144
+ active_base = req_base_ref or runtime_context["resolved_base_ref"]
145
+ active_round = int(runtime_context["current_round"])
146
+
147
+ if active_base is None:
148
+ try:
149
+ snapshot = analyze_repository(
150
+ resolved_repo,
151
+ base_ref=base_ref,
152
+ staged=staged,
153
+ coverage_path=resolved_coverage,
154
+ record_round=False,
155
+ )
156
+ except GitError as exc:
157
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
158
+ active_base = snapshot.base_ref
159
+ active_round = snapshot.current_round
160
+ runtime_context["resolved_base_ref"] = active_base
161
+ runtime_context["current_round"] = active_round
162
+
163
+ store = ReviewStore(git_info.git_dir)
164
+ session = store.get_or_create_session(git_info.branch, active_base)
165
+ return store, _extract_session_id(session), active_round
166
+
167
+ @app.get("/", include_in_schema=False)
168
+ def index() -> FileResponse:
169
+ index_path = WEB_DIR / "index.html"
170
+ if not index_path.exists():
171
+ raise HTTPException(status_code=404, detail="Web workbench assets not found.")
172
+ return FileResponse(index_path, media_type="text/html; charset=utf-8")
173
+
174
+ @app.get("/api/health")
175
+ def health() -> dict[str, str]:
176
+ return {"status": "ok", "version": __version__}
177
+
178
+ @app.get("/api/refs")
179
+ def list_refs() -> dict[str, Any]:
180
+ try:
181
+ adapter = GitAdapter(resolved_repo)
182
+ git_info = adapter.info()
183
+ refs = adapter.list_recent_refs(limit=8)
184
+ except GitError as exc:
185
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
186
+ return {
187
+ "current_branch": git_info.branch,
188
+ "default_base_ref": base_ref or "",
189
+ "branches": refs["branches"],
190
+ "recent_commits": refs["recent_commits"],
191
+ }
192
+
193
+ @app.get("/api/analysis", response_model=DiffAnalysis)
194
+ def get_analysis(
195
+ base_ref_param: str | None = Query(default=None, alias="base_ref"),
196
+ staged_param: bool | None = Query(default=None, alias="staged"),
197
+ record_round: bool = Query(default=True),
198
+ ) -> DiffAnalysis:
199
+ effective_base, effective_staged = _effective_options(base_ref_param, staged_param)
200
+ try:
201
+ analysis = analyze_repository(
202
+ resolved_repo,
203
+ base_ref=effective_base,
204
+ staged=effective_staged,
205
+ coverage_path=resolved_coverage,
206
+ record_round=record_round,
207
+ )
208
+ except GitError as exc:
209
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
210
+
211
+ runtime_context["resolved_base_ref"] = analysis.base_ref
212
+ runtime_context["staged"] = effective_staged
213
+ runtime_context["current_round"] = analysis.current_round
214
+ runtime_context["last_files"] = analysis.files
215
+ return analysis
216
+
217
+ @app.post("/api/threads", response_model=ReviewThread, status_code=201)
218
+ def create_thread(payload: CreateThreadRequest) -> ReviewThread:
219
+ body = payload.body.strip()
220
+ if not body:
221
+ raise HTTPException(status_code=422, detail="Review comment body cannot be empty.")
222
+
223
+ store, session_id, active_round = _open_store_and_session(payload.base_ref)
224
+ round_created = payload.round_created if payload.round_created is not None else active_round
225
+ thread = store.add_thread(
226
+ session_id=session_id,
227
+ file_path=payload.file_path,
228
+ line=payload.line,
229
+ body=body,
230
+ severity=payload.severity,
231
+ symbol_name=payload.symbol_name,
232
+ hunk_fingerprint=payload.hunk_fingerprint,
233
+ round_created=round_created,
234
+ )
235
+ return thread
236
+
237
+ @app.patch("/api/threads/{thread_id}")
238
+ def patch_thread(thread_id: str, payload: UpdateThreadRequest) -> Any:
239
+ try:
240
+ git_info = GitAdapter(resolved_repo).info()
241
+ except GitError as exc:
242
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
243
+
244
+ store = ReviewStore(git_info.git_dir)
245
+ round_resolved = payload.round_resolved
246
+ if payload.status == "resolved" and round_resolved is None:
247
+ round_resolved = int(runtime_context["current_round"])
248
+
249
+ try:
250
+ updated = store.update_thread_status(
251
+ thread_id=thread_id,
252
+ status=payload.status,
253
+ round_resolved=round_resolved,
254
+ )
255
+ except (KeyError, ValueError) as exc:
256
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
257
+
258
+ if updated is None or updated is False:
259
+ raise HTTPException(status_code=404, detail=f"Review thread '{thread_id}' not found.")
260
+ if isinstance(updated, ReviewThread):
261
+ return updated
262
+ return {"id": thread_id, "status": payload.status, "round_resolved": round_resolved}
263
+
264
+ @app.delete("/api/threads/{thread_id}")
265
+ def remove_thread(thread_id: str) -> dict[str, Any]:
266
+ try:
267
+ git_info = GitAdapter(resolved_repo).info()
268
+ except GitError as exc:
269
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
270
+
271
+ store = ReviewStore(git_info.git_dir)
272
+ deleted = store.delete_thread(thread_id)
273
+ if deleted is False:
274
+ raise HTTPException(status_code=404, detail=f"Review thread '{thread_id}' not found.")
275
+ return {"deleted": True, "id": thread_id}
276
+
277
+ @app.get("/api/export", response_model=ExportResponse)
278
+ def export_repair_prompt(
279
+ include_hazards: bool = Query(default=True),
280
+ base_ref_param: str | None = Query(default=None, alias="base_ref"),
281
+ staged_param: bool | None = Query(default=None, alias="staged"),
282
+ ) -> ExportResponse:
283
+ effective_base, effective_staged = _effective_options(base_ref_param, staged_param)
284
+ try:
285
+ analysis = analyze_repository(
286
+ resolved_repo,
287
+ base_ref=effective_base,
288
+ staged=effective_staged,
289
+ coverage_path=resolved_coverage,
290
+ record_round=False,
291
+ )
292
+ except GitError as exc:
293
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
294
+
295
+ markdown = render_agent_repair_prompt(analysis, include_hazards=include_hazards)
296
+ return ExportResponse(markdown=markdown)
297
+
298
+ @app.get("/api/rounds/{round_number}/delta", response_model=RoundDelta)
299
+ def get_round_delta(
300
+ round_number: int,
301
+ base_ref_param: str | None = Query(default=None, alias="base_ref"),
302
+ staged_param: bool | None = Query(default=None, alias="staged"),
303
+ ) -> RoundDelta:
304
+ if round_number < 1:
305
+ raise HTTPException(status_code=400, detail="Round number must be >= 1.")
306
+
307
+ effective_base, effective_staged = _effective_options(base_ref_param, staged_param)
308
+ try:
309
+ git_info = GitAdapter(resolved_repo).info()
310
+ analysis = analyze_repository(
311
+ resolved_repo,
312
+ base_ref=effective_base,
313
+ staged=effective_staged,
314
+ coverage_path=resolved_coverage,
315
+ record_round=False,
316
+ )
317
+ except GitError as exc:
318
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
319
+
320
+ if not any(r.round_number == round_number for r in analysis.rounds):
321
+ raise HTTPException(
322
+ status_code=404,
323
+ detail=f"Review round {round_number} not found for this branch session.",
324
+ )
325
+
326
+ store = ReviewStore(git_info.git_dir)
327
+ session_id = _extract_session_id(
328
+ store.get_or_create_session(git_info.branch, analysis.base_ref)
329
+ )
330
+ current_hashes = _derive_current_file_hashes(analysis)
331
+ delta = store.compute_delta(
332
+ session_id=session_id,
333
+ current_file_hashes=current_hashes,
334
+ from_round=round_number,
335
+ )
336
+ if delta is None:
337
+ raise HTTPException(
338
+ status_code=404,
339
+ detail=f"Could not compute delta from round {round_number}.",
340
+ )
341
+ return delta
342
+
343
+ @app.get("/api/file-context", response_model=FileContextResponse)
344
+ def get_file_context(
345
+ path: str = Query(..., min_length=1),
346
+ line: int = Query(default=1, ge=1),
347
+ radius: int = Query(default=18, ge=1, le=100),
348
+ ) -> FileContextResponse:
349
+ if "\x00" in path:
350
+ raise HTTPException(status_code=400, detail="Invalid file path.")
351
+
352
+ try:
353
+ git_info = GitAdapter(resolved_repo).info()
354
+ except GitError as exc:
355
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
356
+
357
+ repo_root = Path(git_info.repo_root).resolve()
358
+ normalized_rel = path.replace("\\", "/")
359
+ while normalized_rel.startswith("./"):
360
+ normalized_rel = normalized_rel[2:]
361
+ if (
362
+ normalized_rel.startswith("/")
363
+ or Path(normalized_rel).is_absolute()
364
+ or ".." in normalized_rel.split("/")
365
+ or normalized_rel == ".git"
366
+ or normalized_rel.startswith(".git/")
367
+ ):
368
+ raise HTTPException(status_code=400, detail="Access outside working tree is forbidden.")
369
+
370
+ target = (repo_root / normalized_rel).resolve()
371
+ if not target.is_relative_to(repo_root):
372
+ raise HTTPException(status_code=400, detail="Path traversal outside repository root is forbidden.")
373
+ rel_parts = target.relative_to(repo_root).parts
374
+ if ".git" in rel_parts:
375
+ raise HTTPException(status_code=400, detail="Reading .git internals is forbidden.")
376
+ if not target.exists() or not target.is_file():
377
+ raise HTTPException(status_code=404, detail=f"File '{normalized_rel}' not found.")
378
+ if target.stat().st_size > 1_000_000:
379
+ raise HTTPException(status_code=400, detail="File exceeds 1MB preview limit.")
380
+
381
+ raw_bytes = target.read_bytes()
382
+ if b"\x00" in raw_bytes[:8192]:
383
+ raise HTTPException(status_code=400, detail="Binary files cannot be previewed.")
384
+
385
+ all_lines = raw_bytes.decode("utf-8", errors="replace").splitlines()
386
+ total_lines = len(all_lines)
387
+ clamped_target = min(max(1, line), max(1, total_lines))
388
+ start_line = max(1, clamped_target - radius)
389
+ end_line = min(total_lines, clamped_target + radius)
390
+
391
+ context_lines = [
392
+ FileContextLine(lineno=idx, content=all_lines[idx - 1])
393
+ for idx in range(start_line, end_line + 1)
394
+ ]
395
+ canonical_rel = target.relative_to(repo_root).as_posix()
396
+ return FileContextResponse(
397
+ file_path=canonical_rel,
398
+ abs_path=target.as_posix(),
399
+ target_line=clamped_target,
400
+ start_line=start_line,
401
+ end_line=end_line,
402
+ total_lines=total_lines,
403
+ language=detect_language(canonical_rel),
404
+ lines=context_lines,
405
+ )
406
+
407
+ @app.get("/api/symbol-impact", response_model=SymbolImpactReport)
408
+ def get_symbol_impact(
409
+ path: str = Query(..., min_length=1),
410
+ line: int = Query(default=1, ge=1),
411
+ symbol: str = Query(..., min_length=1, max_length=128),
412
+ base_ref_param: str | None = Query(default=None, alias="base_ref"),
413
+ staged_param: bool | None = Query(default=None, alias="staged"),
414
+ ) -> SymbolImpactReport:
415
+ clean_sym = symbol.strip()
416
+ if not clean_sym:
417
+ raise HTTPException(status_code=400, detail="Symbol name cannot be empty.")
418
+
419
+ effective_base, effective_staged = _effective_options(base_ref_param, staged_param)
420
+ cached_files = (
421
+ runtime_context["last_files"]
422
+ if base_ref_param in (None, "") and staged_param is None
423
+ else None
424
+ )
425
+ try:
426
+ return analyze_symbol_impact_in_repo(
427
+ repo_path=resolved_repo,
428
+ symbol=clean_sym,
429
+ file_path=path,
430
+ line=line,
431
+ base_ref=effective_base,
432
+ staged=effective_staged,
433
+ cached_files=cached_files,
434
+ )
435
+ except GitError as exc:
436
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
437
+
438
+ return app