patchproof-core 0.3.1__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.
Files changed (56) hide show
  1. patchproof/__init__.py +44 -0
  2. patchproof/__main__.py +8 -0
  3. patchproof/benchmarks/__init__.py +17 -0
  4. patchproof/benchmarks/swe_bench.py +159 -0
  5. patchproof/cli.py +1254 -0
  6. patchproof/core/__init__.py +33 -0
  7. patchproof/core/agent_init.py +103 -0
  8. patchproof/core/anti_cheat.py +396 -0
  9. patchproof/core/applier.py +159 -0
  10. patchproof/core/ast_analyzer.py +254 -0
  11. patchproof/core/detector.py +78 -0
  12. patchproof/core/git_provider.py +298 -0
  13. patchproof/core/healer.py +104 -0
  14. patchproof/core/mutator.py +223 -0
  15. patchproof/core/normalizer.py +338 -0
  16. patchproof/core/polyglot_guard.py +167 -0
  17. patchproof/core/runtime_guard.py +188 -0
  18. patchproof/core/search_replace.py +222 -0
  19. patchproof/core/slicer.py +172 -0
  20. patchproof/core/sparse_tree.py +95 -0
  21. patchproof/docker/runner.Dockerfile +42 -0
  22. patchproof/exceptions.py +37 -0
  23. patchproof/factory/__init__.py +22 -0
  24. patchproof/factory/blast_radius.py +120 -0
  25. patchproof/factory/engine.py +134 -0
  26. patchproof/factory/models.py +75 -0
  27. patchproof/mcp.py +532 -0
  28. patchproof/models/__init__.py +57 -0
  29. patchproof/models/ast.py +78 -0
  30. patchproof/models/patch.py +106 -0
  31. patchproof/models/sandbox.py +417 -0
  32. patchproof/reporting/__init__.py +19 -0
  33. patchproof/reporting/asymmetric.py +88 -0
  34. patchproof/reporting/badge.py +86 -0
  35. patchproof/reporting/certificate.py +230 -0
  36. patchproof/reporting/diagnostic.py +330 -0
  37. patchproof/reporting/html_report.py +367 -0
  38. patchproof/reporting/in_toto.py +188 -0
  39. patchproof/reporting/markdown.py +179 -0
  40. patchproof/reporting/sbom.py +152 -0
  41. patchproof/sandbox/__init__.py +37 -0
  42. patchproof/sandbox/classifier.py +289 -0
  43. patchproof/sandbox/comparative.py +478 -0
  44. patchproof/sandbox/docker_cli.py +384 -0
  45. patchproof/sandbox/doctor.py +605 -0
  46. patchproof/sandbox/flakiness.py +87 -0
  47. patchproof/sandbox/network_bridge.py +145 -0
  48. patchproof/sandbox/parser.py +172 -0
  49. patchproof/sandbox/runner.py +424 -0
  50. patchproof/sandbox/setup_runner.py +261 -0
  51. patchproof_core-0.3.1.dist-info/METADATA +212 -0
  52. patchproof_core-0.3.1.dist-info/RECORD +56 -0
  53. patchproof_core-0.3.1.dist-info/WHEEL +5 -0
  54. patchproof_core-0.3.1.dist-info/entry_points.txt +2 -0
  55. patchproof_core-0.3.1.dist-info/licenses/LICENSE +13 -0
  56. patchproof_core-0.3.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,330 @@
1
+ """Fault Localization and AI Self-Healing Diagnostic Engine.
2
+
3
+ Provides spectrum-based fault localization (SBFL), hunk correlation, traceback condensation,
4
+ and token-optimized feedback prompt generation for AI coding agents (Aider, Cursor, Claude Code).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import re
11
+ from collections.abc import Sequence
12
+ from dataclasses import dataclass
13
+ from typing import Any
14
+
15
+ from patchproof.models.patch import CanonicalPatch
16
+ from patchproof.models.sandbox import (
17
+ ComparativeExecutionResult,
18
+ PatchVerdict,
19
+ RegressionClassification,
20
+ )
21
+
22
+ _TB_FRAME_RE = re.compile(
23
+ r'File\s+"(?P<file>[^"]+)",\s+line\s+(?P<line>\d+)(?:,\s+in\s+(?P<func>[^\n]+))?(?:\n\s+(?P<code>.+))?'
24
+ )
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class TracebackFrame:
29
+ """Represents a single execution frame parsed from a Python traceback."""
30
+
31
+ file_path: str
32
+ line_number: int
33
+ func_name: str
34
+ code_line: str
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class HunkSuspicion:
39
+ """Represents a patch hunk correlated with a failure, accompanied by a suspicion score."""
40
+
41
+ file_path: str
42
+ hunk_index: int
43
+ suspicion_score: float
44
+ matched_lines: tuple[int, ...]
45
+ reason: str
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class RegressionDetail:
50
+ """Detailed fault diagnostic for an introduced regression."""
51
+
52
+ test_id: str
53
+ failure_message: str
54
+ condensed_traceback: str
55
+ suspected_hunks: tuple[HunkSuspicion, ...]
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class AISelfHealingReport:
60
+ """Structured report and token-optimized feedback prompt for AI self-correction."""
61
+
62
+ verdict: str
63
+ summary: str
64
+ regressions: tuple[RegressionDetail, ...]
65
+ preserved_tests_count: int
66
+ hunk_suspicions: tuple[HunkSuspicion, ...]
67
+ prompt_feedback: str
68
+
69
+ def to_dict(self) -> dict[str, Any]:
70
+ """Convert diagnostic report to JSON-serializable dictionary."""
71
+ return {
72
+ "verdict": self.verdict,
73
+ "summary": self.summary,
74
+ "preserved_tests_count": self.preserved_tests_count,
75
+ "regressions_count": len(self.regressions),
76
+ "hunk_suspicions": [
77
+ {
78
+ "file_path": s.file_path,
79
+ "hunk_index": s.hunk_index,
80
+ "suspicion_score": round(s.suspicion_score, 3),
81
+ "matched_lines": list(s.matched_lines),
82
+ "reason": s.reason,
83
+ }
84
+ for s in self.hunk_suspicions
85
+ ],
86
+ "prompt_feedback": self.prompt_feedback,
87
+ }
88
+
89
+
90
+ def extract_traceback_frames(traceback_text: str) -> list[TracebackFrame]:
91
+ """Parse stack frames out of a standard Python traceback string."""
92
+ frames: list[TracebackFrame] = []
93
+ lines = traceback_text.splitlines()
94
+ i = 0
95
+ while i < len(lines):
96
+ line = lines[i]
97
+ match = re.search(
98
+ r'File\s+"(?P<file>[^"]+)",\s+line\s+(?P<line>\d+)(?:,\s+in\s+(?P<func>[^\n]+))?',
99
+ line,
100
+ )
101
+ if match:
102
+ file_path = match.group("file")
103
+ line_no = int(match.group("line"))
104
+ func_name = (match.group("func") or "unknown").strip()
105
+ code_line = ""
106
+ if i + 1 < len(lines) and lines[i + 1].startswith(" "):
107
+ code_line = lines[i + 1].strip()
108
+ i += 1
109
+ frames.append(
110
+ TracebackFrame(
111
+ file_path=file_path,
112
+ line_number=line_no,
113
+ func_name=func_name,
114
+ code_line=code_line,
115
+ )
116
+ )
117
+ i += 1
118
+ return frames
119
+
120
+
121
+ def _normalize_path(path: str) -> str:
122
+ """Normalize file paths for cross-platform comparison."""
123
+ return path.replace("\\", "/").strip().lower()
124
+
125
+
126
+ def correlate_hunks_with_traceback(
127
+ patch: CanonicalPatch,
128
+ frames: Sequence[TracebackFrame],
129
+ total_failed: int = 1,
130
+ total_passed: int = 1,
131
+ ) -> list[HunkSuspicion]:
132
+ """Correlate traceback frames against patch hunks using Ochiai-inspired suspicion scoring."""
133
+ suspicions: list[HunkSuspicion] = []
134
+
135
+ for delta in patch.file_deltas:
136
+ normalized_delta_path = _normalize_path(delta.path)
137
+ for h_idx, hunk in enumerate(delta.hunks):
138
+ # Calculate modified new line range [new_start, new_start + new_lines]
139
+ hunk_start = hunk.new_start
140
+ hunk_end = hunk.new_start + max(1, hunk.new_lines)
141
+
142
+ matched_lines: list[int] = []
143
+ matched_funcs: list[str] = []
144
+
145
+ for frame in frames:
146
+ norm_frame_path = _normalize_path(frame.file_path)
147
+ # Check path suffix or equality
148
+ if norm_frame_path.endswith(
149
+ normalized_delta_path
150
+ ) or normalized_delta_path.endswith(norm_frame_path):
151
+ # Check if frame line falls in or immediately adjacent (+/- 2 lines) to hunk
152
+ if hunk_start - 2 <= frame.line_number <= hunk_end + 2:
153
+ matched_lines.append(frame.line_number)
154
+ matched_funcs.append(frame.func_name)
155
+
156
+ if matched_lines:
157
+ # Ochiai Suspicion: failed / sqrt(total_failed * (failed + passed))
158
+ # For direct traceback hit, failed=1, passed=0 gives score 1.0 / sqrt(total_failed)
159
+ denom = math.sqrt(max(1, total_failed) * max(1, total_failed))
160
+ score = min(1.0, 1.0 / denom if denom > 0 else 0.95)
161
+ # Boost if exact line matched
162
+ if any(hunk_start <= line <= hunk_end for line in matched_lines):
163
+ score = max(score, 0.92)
164
+
165
+ unique_lines = tuple(sorted(set(matched_lines)))
166
+ suspicions.append(
167
+ HunkSuspicion(
168
+ file_path=delta.path,
169
+ hunk_index=h_idx,
170
+ suspicion_score=score,
171
+ matched_lines=unique_lines,
172
+ reason=(
173
+ f"Frame execution in {delta.path} at line(s) {unique_lines} "
174
+ f"within hunk {hunk.header}"
175
+ ),
176
+ )
177
+ )
178
+
179
+ suspicions.sort(key=lambda s: s.suspicion_score, reverse=True)
180
+ return suspicions
181
+
182
+
183
+ def _condense_traceback(raw_tb: str, max_lines: int = 15) -> str:
184
+ """Condense raw traceback to essential user frames and error message."""
185
+ lines = [line for line in raw_tb.splitlines() if line.strip()]
186
+ if len(lines) <= max_lines:
187
+ return "\n".join(lines)
188
+
189
+ # Keep the header, the last few frames, and the final exception
190
+ header = lines[:2]
191
+ tail = lines[-(max_lines - 2) :]
192
+ return "\n".join([*header, " ... [intermediate frames omitted] ...", *tail])
193
+
194
+
195
+ def generate_ai_feedback(
196
+ result: ComparativeExecutionResult,
197
+ patch: CanonicalPatch | None = None,
198
+ max_traceback_lines: int = 15,
199
+ ) -> AISelfHealingReport:
200
+ """Generate high-density, token-optimized feedback prompt for AI self-correction."""
201
+ verdict_str = result.verdict.value.upper()
202
+ preserved_count = sum(
203
+ 1
204
+ for c in result.test_comparisons
205
+ if c.classification == RegressionClassification.CLEAN_PRESERVATION
206
+ )
207
+
208
+ if result.verdict == PatchVerdict.ACCEPTED:
209
+ prompt = (
210
+ "================================================================================\n"
211
+ "PATCHPROOF VERIFICATION PASSED (VERDICT: ACCEPTED)\n"
212
+ "================================================================================\n"
213
+ f"All {preserved_count} test(s) preserved cleanly with 0 regressions.\n"
214
+ "No corrective action required.\n"
215
+ "================================================================================"
216
+ )
217
+ return AISelfHealingReport(
218
+ verdict="ACCEPTED",
219
+ summary=result.summary,
220
+ regressions=(),
221
+ preserved_tests_count=preserved_count,
222
+ hunk_suspicions=(),
223
+ prompt_feedback=prompt,
224
+ )
225
+
226
+ # Gather regression details
227
+ regressions: list[RegressionDetail] = []
228
+ all_suspicions: list[HunkSuspicion] = []
229
+
230
+ # Map patched test cases for failure messages
231
+ patched_test_map = (
232
+ result.patched_result.test_report.test_map if result.patched_result.test_report else {}
233
+ )
234
+
235
+ regressed_comparisons = [
236
+ c
237
+ for c in result.test_comparisons
238
+ if c.classification == RegressionClassification.INTRODUCED_REGRESSION
239
+ ]
240
+
241
+ for comp in regressed_comparisons:
242
+ test_case = patched_test_map.get(comp.test_name)
243
+ raw_msg = (
244
+ test_case.failure_message
245
+ if test_case and test_case.failure_message
246
+ else comp.message or "Test failed without captured traceback"
247
+ )
248
+
249
+ condensed_tb = _condense_traceback(raw_msg, max_lines=max_traceback_lines)
250
+ frames = extract_traceback_frames(raw_msg)
251
+
252
+ hunk_suspicions: list[HunkSuspicion] = []
253
+ if patch:
254
+ hunk_suspicions = correlate_hunks_with_traceback(
255
+ patch,
256
+ frames,
257
+ total_failed=len(regressed_comparisons),
258
+ total_passed=preserved_count,
259
+ )
260
+ all_suspicions.extend(hunk_suspicions)
261
+
262
+ regressions.append(
263
+ RegressionDetail(
264
+ test_id=comp.test_name,
265
+ failure_message=raw_msg.splitlines()[-1] if raw_msg else "Unknown failure",
266
+ condensed_traceback=condensed_tb,
267
+ suspected_hunks=tuple(hunk_suspicions),
268
+ )
269
+ )
270
+
271
+ # Deduplicate suspicions
272
+ unique_suspicions_map: dict[tuple[str, int], HunkSuspicion] = {}
273
+ for s in all_suspicions:
274
+ key = (s.file_path, s.hunk_index)
275
+ if (
276
+ key not in unique_suspicions_map
277
+ or s.suspicion_score > unique_suspicions_map[key].suspicion_score
278
+ ):
279
+ unique_suspicions_map[key] = s
280
+ sorted_suspicions = tuple(
281
+ sorted(unique_suspicions_map.values(), key=lambda s: s.suspicion_score, reverse=True)
282
+ )
283
+
284
+ # Build token-budgeted prompt
285
+ buf: list[str] = [
286
+ "================================================================================",
287
+ f"PATCHPROOF VERIFICATION FAILED (VERDICT: {verdict_str})",
288
+ "================================================================================",
289
+ (
290
+ f"Your proposed changes introduced {len(regressions)} "
291
+ "regression(s) against the test suite.\n"
292
+ ),
293
+ ]
294
+
295
+ if sorted_suspicions:
296
+ buf.append("FAULT LOCALIZATION (Suspicious Hunks):")
297
+ for s in sorted_suspicions[:3]:
298
+ score_pct = int(s.suspicion_score * 100)
299
+ buf.append(
300
+ f"- [{score_pct}% Suspicion] {s.file_path} (Hunk #{s.hunk_index + 1}) "
301
+ f"Line(s) {list(s.matched_lines)}: {s.reason}"
302
+ )
303
+ buf.append("")
304
+
305
+ buf.append("REGRESSION DETAILS:")
306
+ for idx, reg in enumerate(regressions[:5], start=1):
307
+ buf.append(f"[{idx}/{len(regressions)}] Test: {reg.test_id}")
308
+ buf.append(f"- Failure: {reg.failure_message}")
309
+ buf.append("```traceback")
310
+ buf.append(reg.condensed_traceback)
311
+ buf.append("```")
312
+ buf.append("")
313
+
314
+ buf.append("CRITICAL INVARIANTS:")
315
+ buf.append(
316
+ f"1. Fix the above regression(s) without breaking the "
317
+ f"{preserved_count} existing test(s) that passed."
318
+ )
319
+ buf.append("2. Do not modify or suppress existing test files to make tests pass.")
320
+ buf.append("3. Provide your corrected patch preserving all baseline behaviors.")
321
+ buf.append("================================================================================")
322
+
323
+ return AISelfHealingReport(
324
+ verdict=verdict_str,
325
+ summary=result.summary,
326
+ regressions=tuple(regressions),
327
+ preserved_tests_count=preserved_count,
328
+ hunk_suspicions=sorted_suspicions,
329
+ prompt_feedback="\n".join(buf),
330
+ )
@@ -0,0 +1,367 @@
1
+ """Standalone, zero-dependency visual HTML evidence report generator.
2
+
3
+ Produces an interactive, self-contained HTML dashboard with metrics, test transition
4
+ matrices, diagnostic tracebacks, and syntax-highlighted diffs.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import html
10
+ from typing import TYPE_CHECKING
11
+
12
+ if TYPE_CHECKING:
13
+ from patchproof.models.sandbox import ComparativeExecutionResult
14
+
15
+ VERDICT_COLORS = {
16
+ "accepted": "#10b981", # emerald green
17
+ "rejected": "#ef4444", # rose red
18
+ "suspicious": "#f59e0b", # amber
19
+ "inconclusive": "#64748b", # slate
20
+ "infrastructure_failure": "#dc2626", # dark red
21
+ }
22
+
23
+ CLASSIFICATION_STYLES = {
24
+ "clean_preservation": ("#10b981", "Preserved (Pass)"),
25
+ "introduced_regression": ("#ef4444", "Regression"),
26
+ "resolved_defect": ("#3b82f6", "Fixed Defect"),
27
+ "pre_existing_failure": ("#64748b", "Pre-existing Fail"),
28
+ "suppression_alert": ("#f59e0b", "Suppressed"),
29
+ "pre_existing_skip": ("#475569", "Pre-existing Skip"),
30
+ "new_test_passing": ("#06b6d4", "New Test (Pass)"),
31
+ "new_test_failing": ("#f43f5e", "New Test (Fail)"),
32
+ "new_test_skipped": ("#64748b", "New Test (Skip)"),
33
+ "removed_test": ("#94a3b8", "Removed Test"),
34
+ }
35
+
36
+ CSS_STYLES = """
37
+ :root {
38
+ --bg-color: #0f172a;
39
+ --surface-color: #1e293b;
40
+ --surface-hover: #334155;
41
+ --border-color: #334155;
42
+ --text-primary: #f8fafc;
43
+ --text-secondary: #94a3b8;
44
+ --text-muted: #64748b;
45
+ --accent-blue: #38bdf8;
46
+ --status-green: #10b981;
47
+ --status-red: #ef4444;
48
+ --status-amber: #f59e0b;
49
+ --code-bg: #0b1120;
50
+ }
51
+ * { box-sizing: border-box; margin: 0; padding: 0; }
52
+ body {
53
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
54
+ background-color: var(--bg-color);
55
+ color: var(--text-primary);
56
+ line-height: 1.5;
57
+ padding: 2rem 1rem;
58
+ }
59
+ .container {
60
+ max-width: 1200px;
61
+ margin: 0 auto;
62
+ }
63
+ .header {
64
+ display: flex;
65
+ justify-content: space-between;
66
+ align-items: center;
67
+ margin-bottom: 2rem;
68
+ padding-bottom: 1.5rem;
69
+ border-bottom: 1px solid var(--border-color);
70
+ }
71
+ .header-title h1 {
72
+ font-size: 1.75rem;
73
+ font-weight: 700;
74
+ display: flex;
75
+ align-items: center;
76
+ gap: 0.75rem;
77
+ }
78
+ .header-title p {
79
+ color: var(--text-secondary);
80
+ font-size: 0.95rem;
81
+ margin-top: 0.25rem;
82
+ }
83
+ .badge-verdict {
84
+ font-size: 1.1rem;
85
+ font-weight: 800;
86
+ padding: 0.5rem 1.25rem;
87
+ border-radius: 9999px;
88
+ text-transform: uppercase;
89
+ letter-spacing: 0.05em;
90
+ display: inline-block;
91
+ }
92
+ .status-accepted {
93
+ background-color: rgba(16, 185, 129, 0.15);
94
+ color: #34d399;
95
+ border: 1px solid #10b981;
96
+ }
97
+ .status-rejected {
98
+ background-color: rgba(239, 68, 68, 0.15);
99
+ color: #f87171;
100
+ border: 1px solid #ef4444;
101
+ }
102
+ .status-suspicious {
103
+ background-color: rgba(245, 158, 11, 0.15);
104
+ color: #fbbf24;
105
+ border: 1px solid #f59e0b;
106
+ }
107
+ .status-inconclusive {
108
+ background-color: rgba(100, 116, 139, 0.15);
109
+ color: #94a3b8;
110
+ border: 1px solid #64748b;
111
+ }
112
+ .status-infrastructure_failure {
113
+ background-color: rgba(220, 38, 38, 0.2);
114
+ color: #f87171;
115
+ border: 1px solid #dc2626;
116
+ }
117
+
118
+ .grid-metrics {
119
+ display: grid;
120
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
121
+ gap: 1rem;
122
+ margin-bottom: 2rem;
123
+ }
124
+ .card-metric {
125
+ background: var(--surface-color);
126
+ border: 1px solid var(--border-color);
127
+ border-radius: 0.75rem;
128
+ padding: 1.25rem;
129
+ }
130
+ .card-metric .metric-label {
131
+ font-size: 0.85rem;
132
+ font-weight: 600;
133
+ color: var(--text-secondary);
134
+ text-transform: uppercase;
135
+ letter-spacing: 0.05em;
136
+ }
137
+ .card-metric .metric-value {
138
+ font-size: 1.85rem;
139
+ font-weight: 700;
140
+ margin-top: 0.5rem;
141
+ }
142
+ .text-danger { color: #f87171; }
143
+ .text-success { color: #34d399; }
144
+ .text-accent { color: #38bdf8; }
145
+
146
+ .section {
147
+ background: var(--surface-color);
148
+ border: 1px solid var(--border-color);
149
+ border-radius: 0.75rem;
150
+ padding: 1.5rem;
151
+ margin-bottom: 2rem;
152
+ }
153
+ .section h2 {
154
+ font-size: 1.25rem;
155
+ font-weight: 700;
156
+ margin-bottom: 1rem;
157
+ display: flex;
158
+ align-items: center;
159
+ gap: 0.5rem;
160
+ }
161
+ .table-container {
162
+ overflow-x: auto;
163
+ }
164
+ table {
165
+ width: 100%;
166
+ border-collapse: collapse;
167
+ font-size: 0.9rem;
168
+ }
169
+ th {
170
+ text-align: left;
171
+ padding: 0.75rem 1rem;
172
+ background-color: rgba(0, 0, 0, 0.2);
173
+ color: var(--text-secondary);
174
+ border-bottom: 1px solid var(--border-color);
175
+ font-weight: 600;
176
+ }
177
+ td {
178
+ padding: 0.75rem 1rem;
179
+ border-bottom: 1px solid rgba(255, 255, 255, 0.05);
180
+ }
181
+ tr:hover td {
182
+ background-color: var(--surface-hover);
183
+ }
184
+ .pill {
185
+ font-size: 0.75rem;
186
+ font-weight: 700;
187
+ padding: 0.25rem 0.65rem;
188
+ border-radius: 9999px;
189
+ display: inline-block;
190
+ text-transform: uppercase;
191
+ }
192
+ .diff-pre {
193
+ background-color: var(--code-bg);
194
+ border: 1px solid var(--border-color);
195
+ border-radius: 0.5rem;
196
+ padding: 1rem;
197
+ overflow-x: auto;
198
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
199
+ font-size: 0.85rem;
200
+ line-height: 1.45;
201
+ }
202
+ .diff-add { color: #34d399; background: rgba(16, 185, 129, 0.1); display: block; }
203
+ .diff-sub { color: #f87171; background: rgba(239, 68, 68, 0.1); display: block; }
204
+ .diff-hunk { color: #38bdf8; font-weight: bold; display: block; }
205
+ .footer {
206
+ text-align: center;
207
+ color: var(--text-muted);
208
+ font-size: 0.85rem;
209
+ margin-top: 3rem;
210
+ }
211
+ """
212
+
213
+
214
+ def _render_diff_html(patch_text: str) -> str:
215
+ """Format patch diff with inline line-by-line syntax coloring."""
216
+ lines_html = []
217
+ for line in patch_text.splitlines():
218
+ escaped = html.escape(line)
219
+ if line.startswith("+") and not line.startswith("+++"):
220
+ lines_html.append(f'<span class="diff-add">{escaped}</span>')
221
+ elif line.startswith("-") and not line.startswith("---"):
222
+ lines_html.append(f'<span class="diff-sub">{escaped}</span>')
223
+ elif line.startswith("@@"):
224
+ lines_html.append(f'<span class="diff-hunk">{escaped}</span>')
225
+ else:
226
+ lines_html.append(f"<span>{escaped}</span>")
227
+ return "\n".join(lines_html)
228
+
229
+
230
+ def generate_html_report(
231
+ result: ComparativeExecutionResult,
232
+ patch_content: str | None = None,
233
+ ) -> str:
234
+ """Generate self-contained, standalone HTML verification report."""
235
+ verdict_str = result.verdict.value.lower()
236
+ badge_class = f"badge-verdict status-{verdict_str}"
237
+ verdict_upper = html.escape(result.verdict.value.upper())
238
+ summary_escaped = html.escape(result.summary)
239
+
240
+ # Comparisons rows
241
+ table_rows = []
242
+ for c in result.test_comparisons:
243
+ name_esc = html.escape(c.test_name)
244
+ base_val = c.baseline_outcome.value if c.baseline_outcome else "—"
245
+ patch_val = c.patched_outcome.value if c.patched_outcome else "—"
246
+
247
+ color, _label = CLASSIFICATION_STYLES.get(
248
+ c.classification.value, ("#64748b", c.classification.value)
249
+ )
250
+ pill_html = (
251
+ f'<span class="pill" style="background-color: rgba({int(color[1:3], 16)}, '
252
+ f"{int(color[3:5], 16)}, {int(color[5:7], 16)}, 0.15); color: {color}; "
253
+ f'border: 1px solid {color};">{html.escape(c.classification.value)}</span>'
254
+ )
255
+
256
+ table_rows.append(
257
+ f"<tr>"
258
+ f'<td style="font-family: monospace;">{name_esc}</td>'
259
+ f'<td style="text-transform: uppercase; font-weight: 600;">{base_val}</td>'
260
+ f'<td style="text-transform: uppercase; font-weight: 600;">{patch_val}</td>'
261
+ f"<td>{pill_html}</td>"
262
+ f"</tr>"
263
+ )
264
+
265
+ comparisons_html = (
266
+ "".join(table_rows)
267
+ if table_rows
268
+ else '<tr><td colspan="4" style="text-align: center; color: var(--text-muted);">'
269
+ "No test comparison data available</td></tr>"
270
+ )
271
+
272
+ diff_section_html = ""
273
+ if patch_content:
274
+ rendered_diff = _render_diff_html(patch_content)
275
+ diff_section_html = f"""
276
+ <div class="section">
277
+ <h2>Verified Patch Content</h2>
278
+ <pre class="diff-pre"><code>{rendered_diff}</code></pre>
279
+ </div>
280
+ """
281
+
282
+ diag_section_html = ""
283
+ err_text = result.patched_result.stderr.strip()
284
+ if err_text:
285
+ diag_section_html = f"""
286
+ <div class="section">
287
+ <h2>Diagnostic Output (Stderr)</h2>
288
+ <pre class="diff-pre" style="color: #f87171;"><code>{html.escape(err_text)}</code></pre>
289
+ </div>
290
+ """
291
+
292
+ total_tests = len(result.test_comparisons)
293
+ reg_color = "text-danger" if result.introduced_regressions_count > 0 else ""
294
+ fix_color = "text-success" if result.resolved_defects_count > 0 else ""
295
+
296
+ return f"""<!DOCTYPE html>
297
+ <html lang="en">
298
+ <head>
299
+ <meta charset="UTF-8">
300
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
301
+ <title>PatchProof Verification Report - {verdict_upper}</title>
302
+ <style>{CSS_STYLES}</style>
303
+ </head>
304
+ <body>
305
+ <div class="container">
306
+ <header class="header">
307
+ <div class="header-title">
308
+ <h1>PatchProof Verification Report</h1>
309
+ <p>{summary_escaped}</p>
310
+ </div>
311
+ <div>
312
+ <span class="{badge_class}">{verdict_upper}</span>
313
+ </div>
314
+ </header>
315
+
316
+ <div class="grid-metrics">
317
+ <div class="card-metric">
318
+ <div class="metric-label">Regressions</div>
319
+ <div class="metric-value {reg_color}">{result.introduced_regressions_count}</div>
320
+ </div>
321
+ <div class="card-metric">
322
+ <div class="metric-label">Defects Resolved</div>
323
+ <div class="metric-value {fix_color}">{result.resolved_defects_count}</div>
324
+ </div>
325
+ <div class="card-metric">
326
+ <div class="metric-label">Pre-existing Fails</div>
327
+ <div class="metric-value">{result.pre_existing_failures_count}</div>
328
+ </div>
329
+ <div class="card-metric">
330
+ <div class="metric-label">Total Tests Evaluated</div>
331
+ <div class="metric-value text-accent">{total_tests}</div>
332
+ </div>
333
+ <div class="card-metric">
334
+ <div class="metric-label">Execution Duration</div>
335
+ <div class="metric-value">{result.patched_result.duration_seconds:.2f}s</div>
336
+ </div>
337
+ </div>
338
+
339
+ <div class="section">
340
+ <h2>Test Transition Analysis</h2>
341
+ <div class="table-container">
342
+ <table>
343
+ <thead>
344
+ <tr>
345
+ <th>Test Case</th>
346
+ <th>Baseline</th>
347
+ <th>Patched</th>
348
+ <th>Classification</th>
349
+ </tr>
350
+ </thead>
351
+ <tbody>
352
+ {comparisons_html}
353
+ </tbody>
354
+ </table>
355
+ </div>
356
+ </div>
357
+
358
+ {diff_section_html}
359
+ {diag_section_html}
360
+
361
+ <footer class="footer">
362
+ Generated deterministically by PatchProof Isolated Verification Engine
363
+ </footer>
364
+ </div>
365
+ </body>
366
+ </html>
367
+ """