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/store.py ADDED
@@ -0,0 +1,502 @@
1
+ """SQLite WAL review session store strictly under .git/blastdiff/state.db."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sqlite3
7
+ from contextlib import contextmanager
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+ from typing import Any, Iterator
11
+ from uuid import uuid4
12
+
13
+ from blastdiff.core.models import ReviewRound, ReviewThread, RoundDelta
14
+
15
+ MAX_STORED_OUTPUT_CHARS = 20_000
16
+ VALID_SEVERITIES = frozenset({"blocker", "suggestion", "question", "note"})
17
+ VALID_THREAD_STATUSES = frozenset({"open", "resolved", "outdated"})
18
+
19
+ SCHEMA_SQL = """
20
+ CREATE TABLE IF NOT EXISTS sessions (
21
+ id TEXT PRIMARY KEY,
22
+ branch TEXT NOT NULL,
23
+ base_ref TEXT NOT NULL,
24
+ created_at TEXT NOT NULL,
25
+ updated_at TEXT NOT NULL
26
+ );
27
+
28
+ CREATE TABLE IF NOT EXISTS rounds (
29
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
30
+ session_id TEXT NOT NULL,
31
+ round_number INTEGER NOT NULL,
32
+ head_sha TEXT NOT NULL,
33
+ diff_fingerprint TEXT NOT NULL,
34
+ file_hashes TEXT NOT NULL,
35
+ summary TEXT NOT NULL,
36
+ created_at TEXT NOT NULL
37
+ );
38
+
39
+ CREATE INDEX IF NOT EXISTS idx_rounds_session_num
40
+ ON rounds (session_id, round_number);
41
+
42
+ CREATE TABLE IF NOT EXISTS threads (
43
+ id TEXT PRIMARY KEY,
44
+ session_id TEXT NOT NULL,
45
+ file_path TEXT NOT NULL,
46
+ line INTEGER NOT NULL,
47
+ symbol_name TEXT,
48
+ hunk_fingerprint TEXT NOT NULL,
49
+ severity TEXT NOT NULL,
50
+ body TEXT NOT NULL,
51
+ status TEXT NOT NULL,
52
+ round_created INTEGER NOT NULL,
53
+ round_resolved INTEGER,
54
+ created_at TEXT NOT NULL,
55
+ updated_at TEXT NOT NULL
56
+ );
57
+
58
+ CREATE INDEX IF NOT EXISTS idx_threads_session_status
59
+ ON threads (session_id, status);
60
+
61
+ CREATE TABLE IF NOT EXISTS verifications (
62
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
63
+ session_id TEXT NOT NULL,
64
+ command TEXT NOT NULL,
65
+ passed INTEGER NOT NULL,
66
+ output TEXT NOT NULL,
67
+ coverage_source TEXT,
68
+ created_at TEXT NOT NULL
69
+ );
70
+
71
+ CREATE INDEX IF NOT EXISTS idx_verifications_session
72
+ ON verifications (session_id, id);
73
+ """
74
+
75
+
76
+ def _utc_now() -> str:
77
+ return datetime.now(timezone.utc).isoformat()
78
+
79
+
80
+ def _row_to_round(row: sqlite3.Row) -> ReviewRound:
81
+ try:
82
+ raw_hashes = json.loads(row["file_hashes"])
83
+ file_hashes = (
84
+ {str(k): str(v) for k, v in raw_hashes.items()}
85
+ if isinstance(raw_hashes, dict)
86
+ else {}
87
+ )
88
+ except (json.JSONDecodeError, TypeError):
89
+ file_hashes = {}
90
+ return ReviewRound(
91
+ round_number=int(row["round_number"]),
92
+ created_at=str(row["created_at"]),
93
+ head_sha=str(row["head_sha"]),
94
+ diff_fingerprint=str(row["diff_fingerprint"]),
95
+ file_hashes=file_hashes,
96
+ summary=str(row["summary"]),
97
+ )
98
+
99
+
100
+ def _row_to_thread(row: sqlite3.Row) -> ReviewThread:
101
+ return ReviewThread(
102
+ id=str(row["id"]),
103
+ session_id=str(row["session_id"]),
104
+ file_path=str(row["file_path"]),
105
+ line=int(row["line"]),
106
+ symbol_name=row["symbol_name"],
107
+ hunk_fingerprint=str(row["hunk_fingerprint"] or ""),
108
+ severity=row["severity"],
109
+ body=str(row["body"]),
110
+ status=row["status"],
111
+ round_created=int(row["round_created"]),
112
+ round_resolved=(
113
+ int(row["round_resolved"])
114
+ if row["round_resolved"] is not None
115
+ else None
116
+ ),
117
+ created_at=str(row["created_at"]),
118
+ updated_at=str(row["updated_at"]),
119
+ )
120
+
121
+
122
+ class ReviewStore:
123
+ """Single owner of persistent local review state inside .git/blastdiff/."""
124
+
125
+ def __init__(self, git_dir: str | Path) -> None:
126
+ self.store_dir = Path(git_dir) / "blastdiff"
127
+ self.store_dir.mkdir(parents=True, exist_ok=True)
128
+ self.db_path = self.store_dir / "state.db"
129
+ self._init_schema()
130
+
131
+ @contextmanager
132
+ def _connect(self) -> Iterator[sqlite3.Connection]:
133
+ conn = sqlite3.connect(str(self.db_path), timeout=5.0)
134
+ conn.row_factory = sqlite3.Row
135
+ try:
136
+ conn.execute("PRAGMA journal_mode=WAL;")
137
+ conn.execute("PRAGMA busy_timeout=5000;")
138
+ yield conn
139
+ conn.commit()
140
+ except Exception:
141
+ conn.rollback()
142
+ raise
143
+ finally:
144
+ conn.close()
145
+
146
+ def _init_schema(self) -> None:
147
+ with self._connect() as conn:
148
+ conn.executescript(SCHEMA_SQL)
149
+
150
+ def get_or_create_session(self, branch: str, base_ref: str) -> str:
151
+ now = _utc_now()
152
+ with self._connect() as conn:
153
+ row = conn.execute(
154
+ """
155
+ SELECT id FROM sessions
156
+ WHERE branch = ? AND base_ref = ?
157
+ ORDER BY created_at DESC
158
+ LIMIT 1
159
+ """,
160
+ (branch, base_ref),
161
+ ).fetchone()
162
+ if row is not None:
163
+ session_id = str(row["id"])
164
+ conn.execute(
165
+ "UPDATE sessions SET updated_at = ? WHERE id = ?",
166
+ (now, session_id),
167
+ )
168
+ return session_id
169
+
170
+ session_id = f"ses_{uuid4().hex[:12]}"
171
+ conn.execute(
172
+ """
173
+ INSERT INTO sessions (id, branch, base_ref, created_at, updated_at)
174
+ VALUES (?, ?, ?, ?, ?)
175
+ """,
176
+ (session_id, branch, base_ref, now, now),
177
+ )
178
+ return session_id
179
+
180
+ def list_rounds(self, session_id: str) -> list[ReviewRound]:
181
+ with self._connect() as conn:
182
+ rows = conn.execute(
183
+ """
184
+ SELECT round_number, created_at, head_sha, diff_fingerprint,
185
+ file_hashes, summary
186
+ FROM rounds
187
+ WHERE session_id = ?
188
+ ORDER BY round_number ASC
189
+ """,
190
+ (session_id,),
191
+ ).fetchall()
192
+ return [_row_to_round(row) for row in rows]
193
+
194
+ def record_round_if_changed(
195
+ self,
196
+ session_id: str,
197
+ head_sha: str,
198
+ diff_fingerprint: str,
199
+ file_hashes: dict[str, str],
200
+ summary: str = "",
201
+ ) -> tuple[ReviewRound, bool]:
202
+ now = _utc_now()
203
+ serialized_hashes = json.dumps(file_hashes, sort_keys=True)
204
+ with self._connect() as conn:
205
+ latest = conn.execute(
206
+ """
207
+ SELECT round_number, created_at, head_sha, diff_fingerprint,
208
+ file_hashes, summary
209
+ FROM rounds
210
+ WHERE session_id = ?
211
+ ORDER BY round_number DESC
212
+ LIMIT 1
213
+ """,
214
+ (session_id,),
215
+ ).fetchone()
216
+
217
+ if latest is not None and str(latest["diff_fingerprint"]) == diff_fingerprint:
218
+ return _row_to_round(latest), False
219
+
220
+ next_round = int(latest["round_number"]) + 1 if latest is not None else 1
221
+ conn.execute(
222
+ """
223
+ INSERT INTO rounds (
224
+ session_id, round_number, head_sha, diff_fingerprint,
225
+ file_hashes, summary, created_at
226
+ )
227
+ VALUES (?, ?, ?, ?, ?, ?, ?)
228
+ """,
229
+ (
230
+ session_id,
231
+ next_round,
232
+ head_sha,
233
+ diff_fingerprint,
234
+ serialized_hashes,
235
+ summary,
236
+ now,
237
+ ),
238
+ )
239
+ conn.execute(
240
+ "UPDATE sessions SET updated_at = ? WHERE id = ?",
241
+ (now, session_id),
242
+ )
243
+
244
+ return (
245
+ ReviewRound(
246
+ round_number=next_round,
247
+ created_at=now,
248
+ head_sha=head_sha,
249
+ diff_fingerprint=diff_fingerprint,
250
+ file_hashes=dict(file_hashes),
251
+ summary=summary,
252
+ ),
253
+ True,
254
+ )
255
+
256
+ def compute_delta(
257
+ self,
258
+ session_id: str,
259
+ current_file_hashes: dict[str, str],
260
+ from_round: int | None = None,
261
+ ) -> RoundDelta | None:
262
+ rounds = self.list_rounds(session_id)
263
+ if not rounds:
264
+ return None
265
+
266
+ target: ReviewRound | None = None
267
+ if from_round is not None:
268
+ for item in rounds:
269
+ if item.round_number == from_round:
270
+ target = item
271
+ break
272
+ if target is None:
273
+ return None
274
+ else:
275
+ if len(rounds) < 2:
276
+ return None
277
+ target = rounds[-2]
278
+
279
+ prev_hashes = target.file_hashes
280
+ prev_keys = set(prev_hashes.keys())
281
+ curr_keys = set(current_file_hashes.keys())
282
+
283
+ added_files = sorted(curr_keys - prev_keys)
284
+ removed_files = sorted(prev_keys - curr_keys)
285
+ common = prev_keys & curr_keys
286
+ changed_files = sorted(
287
+ path for path in common if prev_hashes[path] != current_file_hashes[path]
288
+ )
289
+ unchanged_files = sorted(
290
+ path for path in common if prev_hashes[path] == current_file_hashes[path]
291
+ )
292
+
293
+ return RoundDelta(
294
+ from_round=target.round_number,
295
+ to_label="current",
296
+ changed_files=changed_files,
297
+ added_files=added_files,
298
+ removed_files=removed_files,
299
+ unchanged_files=unchanged_files,
300
+ )
301
+
302
+ def add_thread(
303
+ self,
304
+ session_id: str,
305
+ file_path: str,
306
+ line: int,
307
+ body: str,
308
+ severity: str = "blocker",
309
+ symbol_name: str | None = None,
310
+ hunk_fingerprint: str = "",
311
+ round_created: int = 1,
312
+ ) -> ReviewThread:
313
+ if severity not in VALID_SEVERITIES:
314
+ raise ValueError(
315
+ f"Invalid thread severity '{severity}'. Expected one of {sorted(VALID_SEVERITIES)}."
316
+ )
317
+ clean_body = body.strip()
318
+ if not clean_body:
319
+ raise ValueError("Review thread body must not be empty.")
320
+
321
+ now = _utc_now()
322
+ thread_id = f"thr_{uuid4().hex[:10]}"
323
+ norm_path = file_path.replace("\\", "/")
324
+ while norm_path.startswith("./"):
325
+ norm_path = norm_path[2:]
326
+ norm_path = norm_path.lstrip("/")
327
+ line_num = max(1, int(line))
328
+
329
+ with self._connect() as conn:
330
+ conn.execute(
331
+ """
332
+ INSERT INTO threads (
333
+ id, session_id, file_path, line, symbol_name,
334
+ hunk_fingerprint, severity, body, status,
335
+ round_created, round_resolved, created_at, updated_at
336
+ )
337
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
338
+ """,
339
+ (
340
+ thread_id,
341
+ session_id,
342
+ norm_path,
343
+ line_num,
344
+ symbol_name,
345
+ hunk_fingerprint,
346
+ severity,
347
+ clean_body,
348
+ "open",
349
+ round_created,
350
+ None,
351
+ now,
352
+ now,
353
+ ),
354
+ )
355
+ conn.execute(
356
+ "UPDATE sessions SET updated_at = ? WHERE id = ?",
357
+ (now, session_id),
358
+ )
359
+
360
+ return ReviewThread(
361
+ id=thread_id,
362
+ session_id=session_id,
363
+ file_path=norm_path,
364
+ line=line_num,
365
+ symbol_name=symbol_name,
366
+ hunk_fingerprint=hunk_fingerprint,
367
+ severity=severity, # type: ignore[arg-type]
368
+ body=clean_body,
369
+ status="open",
370
+ round_created=round_created,
371
+ round_resolved=None,
372
+ created_at=now,
373
+ updated_at=now,
374
+ )
375
+
376
+ def get_thread(self, thread_id: str) -> ReviewThread | None:
377
+ with self._connect() as conn:
378
+ row = conn.execute(
379
+ "SELECT * FROM threads WHERE id = ?", (thread_id,)
380
+ ).fetchone()
381
+ return _row_to_thread(row) if row is not None else None
382
+
383
+ def list_threads(
384
+ self, session_id: str, status: str | None = None
385
+ ) -> list[ReviewThread]:
386
+ with self._connect() as conn:
387
+ if status is not None:
388
+ rows = conn.execute(
389
+ """
390
+ SELECT * FROM threads
391
+ WHERE session_id = ? AND status = ?
392
+ ORDER BY created_at ASC
393
+ """,
394
+ (session_id, status),
395
+ ).fetchall()
396
+ else:
397
+ rows = conn.execute(
398
+ """
399
+ SELECT * FROM threads
400
+ WHERE session_id = ?
401
+ ORDER BY created_at ASC
402
+ """,
403
+ (session_id,),
404
+ ).fetchall()
405
+ return [_row_to_thread(row) for row in rows]
406
+
407
+ def update_thread_status(
408
+ self,
409
+ thread_id: str,
410
+ status: str,
411
+ round_resolved: int | None = None,
412
+ ) -> ReviewThread | None:
413
+ if status not in VALID_THREAD_STATUSES:
414
+ raise ValueError(
415
+ f"Invalid thread status '{status}'. Expected one of {sorted(VALID_THREAD_STATUSES)}."
416
+ )
417
+ now = _utc_now()
418
+ with self._connect() as conn:
419
+ existing = conn.execute(
420
+ "SELECT * FROM threads WHERE id = ?", (thread_id,)
421
+ ).fetchone()
422
+ if existing is None:
423
+ return None
424
+
425
+ resolved_val = None if status == "open" else round_resolved
426
+ conn.execute(
427
+ """
428
+ UPDATE threads
429
+ SET status = ?, round_resolved = ?, updated_at = ?
430
+ WHERE id = ?
431
+ """,
432
+ (status, resolved_val, now, thread_id),
433
+ )
434
+ updated = conn.execute(
435
+ "SELECT * FROM threads WHERE id = ?", (thread_id,)
436
+ ).fetchone()
437
+ return _row_to_thread(updated) if updated is not None else None
438
+
439
+ def delete_thread(self, thread_id: str) -> bool:
440
+ with self._connect() as conn:
441
+ cursor = conn.execute(
442
+ "DELETE FROM threads WHERE id = ?", (thread_id,)
443
+ )
444
+ return cursor.rowcount > 0
445
+
446
+ def record_verification(
447
+ self,
448
+ session_id: str,
449
+ command: str,
450
+ passed: bool,
451
+ output: str,
452
+ coverage_source: str | None = None,
453
+ ) -> None:
454
+ now = _utc_now()
455
+ trimmed_output = (
456
+ output[-MAX_STORED_OUTPUT_CHARS:]
457
+ if len(output) > MAX_STORED_OUTPUT_CHARS
458
+ else output
459
+ )
460
+ with self._connect() as conn:
461
+ conn.execute(
462
+ """
463
+ INSERT INTO verifications (
464
+ session_id, command, passed, output, coverage_source, created_at
465
+ )
466
+ VALUES (?, ?, ?, ?, ?, ?)
467
+ """,
468
+ (
469
+ session_id,
470
+ command,
471
+ 1 if passed else 0,
472
+ trimmed_output,
473
+ coverage_source,
474
+ now,
475
+ ),
476
+ )
477
+ conn.execute(
478
+ "UPDATE sessions SET updated_at = ? WHERE id = ?",
479
+ (now, session_id),
480
+ )
481
+
482
+ def get_latest_verification(self, session_id: str) -> dict[str, Any] | None:
483
+ with self._connect() as conn:
484
+ row = conn.execute(
485
+ """
486
+ SELECT command, passed, output, coverage_source, created_at
487
+ FROM verifications
488
+ WHERE session_id = ?
489
+ ORDER BY id DESC
490
+ LIMIT 1
491
+ """,
492
+ (session_id,),
493
+ ).fetchone()
494
+ if row is None:
495
+ return None
496
+ return {
497
+ "command": str(row["command"]),
498
+ "passed": bool(row["passed"]),
499
+ "output": str(row["output"]),
500
+ "coverage_source": row["coverage_source"],
501
+ "created_at": str(row["created_at"]),
502
+ }