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,605 @@
1
+ """System environment and dependency doctor for PatchProof."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import platform
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ DEFAULT_RUNNER_TAG = "patchproof-runner-python:3.11"
17
+
18
+
19
+ class DoctorCheckResult(BaseModel):
20
+ """Result of an individual environment health check."""
21
+
22
+ model_config = ConfigDict(frozen=True)
23
+
24
+ name: str = Field(description="Descriptive name of the diagnostic check")
25
+ passed: bool = Field(description="True if the diagnostic check satisfied all requirements")
26
+ details: str = Field(description="Detailed observation or version information")
27
+ remediation: str | None = Field(
28
+ default=None,
29
+ description="Actionable remediation steps if the check failed",
30
+ )
31
+
32
+
33
+ class SystemDoctor:
34
+ """Diagnostic inspector verifying the host environment against PatchProof prerequisites."""
35
+
36
+ def __init__(self, timeout_seconds: float = 5.0) -> None:
37
+ self.timeout_seconds = timeout_seconds
38
+
39
+ def check_python_version(self) -> DoctorCheckResult:
40
+ """Verify Python runtime version is 3.11 or higher."""
41
+ ver = sys.version_info
42
+ major, minor, micro = ver[0], ver[1], ver[2]
43
+ version_str = f"{major}.{minor}.{micro}"
44
+ passed = (major, minor) >= (3, 11)
45
+ if passed:
46
+ return DoctorCheckResult(
47
+ name="Python Version",
48
+ passed=True,
49
+ details=f"Python {version_str} (>= 3.11 required)",
50
+ )
51
+ return DoctorCheckResult(
52
+ name="Python Version",
53
+ passed=False,
54
+ details=f"Python {version_str} is unsupported",
55
+ remediation="Install Python 3.11 or newer from https://www.python.org",
56
+ )
57
+
58
+ def check_git_cli(self) -> DoctorCheckResult:
59
+ """Verify Git CLI executable is installed and reachable on PATH."""
60
+ git_path = shutil.which("git")
61
+ if not git_path:
62
+ return DoctorCheckResult(
63
+ name="Git CLI",
64
+ passed=False,
65
+ details="Executable 'git' not found on system PATH",
66
+ remediation=(
67
+ "Install Git and ensure 'git' is added to PATH (https://git-scm.com/downloads)"
68
+ ),
69
+ )
70
+
71
+ try:
72
+ res = subprocess.run(
73
+ [git_path, "--version"],
74
+ shell=False,
75
+ capture_output=True,
76
+ text=True,
77
+ check=False,
78
+ timeout=self.timeout_seconds,
79
+ )
80
+ if res.returncode == 0:
81
+ version_line = res.stdout.strip() or f"Found at {git_path}"
82
+ return DoctorCheckResult(
83
+ name="Git CLI",
84
+ passed=True,
85
+ details=version_line,
86
+ )
87
+ return DoctorCheckResult(
88
+ name="Git CLI",
89
+ passed=False,
90
+ details=f"Git command failed with exit code {res.returncode}: {res.stderr.strip()}",
91
+ remediation="Ensure the Git installation is healthy and operable",
92
+ )
93
+ except (subprocess.TimeoutExpired, OSError) as exc:
94
+ return DoctorCheckResult(
95
+ name="Git CLI",
96
+ passed=False,
97
+ details=f"Error executing git: {exc}",
98
+ remediation="Verify Git permissions and executable integrity",
99
+ )
100
+
101
+ def check_docker_cli(self) -> DoctorCheckResult:
102
+ """Verify Docker CLI binary is installed and reachable on PATH."""
103
+ docker_path = shutil.which("docker")
104
+ if not docker_path:
105
+ return DoctorCheckResult(
106
+ name="Docker CLI",
107
+ passed=False,
108
+ details="Executable 'docker' not found on system PATH",
109
+ remediation=(
110
+ "Install Docker Desktop (Windows/macOS) or Docker Engine (Linux) "
111
+ "from https://docs.docker.com/get-docker/"
112
+ ),
113
+ )
114
+
115
+ try:
116
+ res = subprocess.run(
117
+ [docker_path, "--version"],
118
+ shell=False,
119
+ capture_output=True,
120
+ text=True,
121
+ check=False,
122
+ timeout=self.timeout_seconds,
123
+ )
124
+ if res.returncode == 0:
125
+ version_line = res.stdout.strip() or f"Found at {docker_path}"
126
+ return DoctorCheckResult(
127
+ name="Docker CLI",
128
+ passed=True,
129
+ details=version_line,
130
+ )
131
+ return DoctorCheckResult(
132
+ name="Docker CLI",
133
+ passed=False,
134
+ details=(
135
+ f"Docker CLI failed with exit code {res.returncode}: {res.stderr.strip()}"
136
+ ),
137
+ remediation="Verify Docker CLI installation and executable integrity",
138
+ )
139
+ except (subprocess.TimeoutExpired, OSError) as exc:
140
+ return DoctorCheckResult(
141
+ name="Docker CLI",
142
+ passed=False,
143
+ details=f"Error executing docker: {exc}",
144
+ remediation="Verify Docker CLI permissions and executable integrity",
145
+ )
146
+
147
+ def check_docker_daemon(self) -> tuple[DoctorCheckResult, bool]:
148
+ """Verify Docker daemon is active and responding to API requests."""
149
+ docker_path = shutil.which("docker")
150
+ if not docker_path:
151
+ return (
152
+ DoctorCheckResult(
153
+ name="Docker Daemon",
154
+ passed=False,
155
+ details="Docker CLI is not installed",
156
+ remediation="Install Docker before starting the daemon",
157
+ ),
158
+ False,
159
+ )
160
+
161
+ try:
162
+ res = subprocess.run(
163
+ [docker_path, "info", "--format", "{{.ServerVersion}}"],
164
+ shell=False,
165
+ capture_output=True,
166
+ text=True,
167
+ check=False,
168
+ timeout=self.timeout_seconds,
169
+ )
170
+ if res.returncode == 0:
171
+ server_ver = res.stdout.strip()
172
+ return (
173
+ DoctorCheckResult(
174
+ name="Docker Daemon",
175
+ passed=True,
176
+ details=f"Active (Server Version: {server_ver})",
177
+ ),
178
+ True,
179
+ )
180
+ stderr_msg = res.stderr.strip() or "Daemon unreachable"
181
+ sys_os = platform.system().lower()
182
+ if sys_os == "darwin":
183
+ remed = (
184
+ "Start Docker Desktop by running 'open -a Docker' or launching Applications"
185
+ )
186
+ elif sys_os == "linux":
187
+ remed = (
188
+ "Start Docker daemon by running 'sudo systemctl start docker' "
189
+ "or 'sudo service docker start'"
190
+ )
191
+ else:
192
+ remed = (
193
+ "Start Docker Desktop or run 'sudo systemctl start docker' "
194
+ "and verify daemon is running"
195
+ )
196
+ return (
197
+ DoctorCheckResult(
198
+ name="Docker Daemon",
199
+ passed=False,
200
+ details=f"Daemon not reachable: {stderr_msg}",
201
+ remediation=remed,
202
+ ),
203
+ False,
204
+ )
205
+ except subprocess.TimeoutExpired:
206
+ return (
207
+ DoctorCheckResult(
208
+ name="Docker Daemon",
209
+ passed=False,
210
+ details="Connection to Docker daemon timed out",
211
+ remediation="Ensure Docker service is responsive and not frozen",
212
+ ),
213
+ False,
214
+ )
215
+ except OSError as exc:
216
+ return (
217
+ DoctorCheckResult(
218
+ name="Docker Daemon",
219
+ passed=False,
220
+ details=f"Error checking Docker daemon: {exc}",
221
+ remediation="Verify Docker daemon access permissions and named pipe socket",
222
+ ),
223
+ False,
224
+ )
225
+
226
+ def check_docker_engine_mode(self, daemon_active: bool) -> DoctorCheckResult:
227
+ """Verify Docker is operating in Linux containers mode (required for sandbox)."""
228
+ if not daemon_active:
229
+ return DoctorCheckResult(
230
+ name="Docker Engine Mode",
231
+ passed=False,
232
+ details="Skipped (Docker daemon is offline)",
233
+ remediation="Start Docker daemon in Linux containers mode",
234
+ )
235
+
236
+ docker_path = shutil.which("docker") or "docker"
237
+ try:
238
+ res = subprocess.run(
239
+ [docker_path, "info", "--format", "{{.OSType}}"],
240
+ shell=False,
241
+ capture_output=True,
242
+ text=True,
243
+ check=False,
244
+ timeout=self.timeout_seconds,
245
+ )
246
+ if res.returncode == 0:
247
+ os_type = res.stdout.strip().lower()
248
+ if os_type == "linux":
249
+ return DoctorCheckResult(
250
+ name="Docker Engine Mode",
251
+ passed=True,
252
+ details="Operating in Linux containers mode",
253
+ )
254
+ return DoctorCheckResult(
255
+ name="Docker Engine Mode",
256
+ passed=False,
257
+ details=f"Operating in '{os_type}' containers mode (Linux required)",
258
+ remediation=(
259
+ "Switch Docker Desktop to Linux containers mode "
260
+ "(right-click Docker tray icon -> 'Switch to Linux containers...')"
261
+ ),
262
+ )
263
+ return DoctorCheckResult(
264
+ name="Docker Engine Mode",
265
+ passed=False,
266
+ details=f"Failed to query engine mode: {res.stderr.strip()}",
267
+ remediation="Verify Docker engine status",
268
+ )
269
+ except (subprocess.TimeoutExpired, OSError) as exc:
270
+ return DoctorCheckResult(
271
+ name="Docker Engine Mode",
272
+ passed=False,
273
+ details=f"Error querying engine mode: {exc}",
274
+ remediation="Verify Docker daemon responsiveness",
275
+ )
276
+
277
+ def check_runner_image_exists(
278
+ self,
279
+ image_tag: str,
280
+ daemon_active: bool,
281
+ ) -> tuple[DoctorCheckResult, bool]:
282
+ """Verify the configured runner container image exists locally."""
283
+ if not daemon_active:
284
+ return (
285
+ DoctorCheckResult(
286
+ name="Runner Image Presence",
287
+ passed=False,
288
+ details=f"Skipped for '{image_tag}' (Docker daemon is offline)",
289
+ remediation="Start Docker daemon, then run 'patchproof setup-runner'",
290
+ ),
291
+ False,
292
+ )
293
+
294
+ docker_path = shutil.which("docker") or "docker"
295
+ try:
296
+ res = subprocess.run(
297
+ [docker_path, "image", "inspect", image_tag, "--format", "{{.Id}}"],
298
+ shell=False,
299
+ capture_output=True,
300
+ text=True,
301
+ check=False,
302
+ timeout=self.timeout_seconds,
303
+ )
304
+ if res.returncode == 0:
305
+ image_id = res.stdout.strip()[:19] # e.g. sha256:abcd...
306
+ return (
307
+ DoctorCheckResult(
308
+ name="Runner Image Presence",
309
+ passed=True,
310
+ details=f"Image '{image_tag}' found locally ({image_id})",
311
+ ),
312
+ True,
313
+ )
314
+ if image_tag == DEFAULT_RUNNER_TAG:
315
+ remed = (
316
+ f"Build the runner image by running: "
317
+ f"patchproof setup-runner --tag {image_tag}"
318
+ )
319
+ else:
320
+ remed = (
321
+ f"Pull or build custom runner image '{image_tag}' before running patchproof "
322
+ f"(e.g. 'docker pull {image_tag}')"
323
+ )
324
+ return (
325
+ DoctorCheckResult(
326
+ name="Runner Image Presence",
327
+ passed=False,
328
+ details=f"Image '{image_tag}' not found in local Docker cache",
329
+ remediation=remed,
330
+ ),
331
+ False,
332
+ )
333
+ except (subprocess.TimeoutExpired, OSError) as exc:
334
+ return (
335
+ DoctorCheckResult(
336
+ name="Runner Image Presence",
337
+ passed=False,
338
+ details=f"Error inspecting image '{image_tag}': {exc}",
339
+ remediation="Verify Docker daemon responsiveness",
340
+ ),
341
+ False,
342
+ )
343
+
344
+ def check_runner_image_compatibility(
345
+ self,
346
+ image_tag: str,
347
+ image_exists: bool,
348
+ ) -> DoctorCheckResult:
349
+ """Verify runner image compatibility (architecture, unprivileged user, test runner)."""
350
+ if not image_exists:
351
+ if image_tag == DEFAULT_RUNNER_TAG:
352
+ remed = f"Run 'patchproof setup-runner --tag {image_tag}' to build the image"
353
+ else:
354
+ remed = (
355
+ f"Pull or build custom runner image '{image_tag}' before running verification"
356
+ )
357
+ return DoctorCheckResult(
358
+ name="Runner Image Compatibility",
359
+ passed=False,
360
+ details=f"Skipped for '{image_tag}' (image does not exist)",
361
+ remediation=remed,
362
+ )
363
+
364
+ docker_path = shutil.which("docker") or "docker"
365
+ try:
366
+ # Query architecture and labels
367
+ inspect_res = subprocess.run(
368
+ [
369
+ docker_path,
370
+ "image",
371
+ "inspect",
372
+ image_tag,
373
+ "--format",
374
+ '{{.Architecture}}|{{index .Config.Labels "patchproof.runner"}}',
375
+ ],
376
+ shell=False,
377
+ capture_output=True,
378
+ text=True,
379
+ check=False,
380
+ timeout=self.timeout_seconds,
381
+ )
382
+ arch_info = ""
383
+ if inspect_res.returncode == 0:
384
+ parts = inspect_res.stdout.strip().split("|")
385
+ arch = parts[0] if parts else "unknown"
386
+ arch_info = f"arch={arch}"
387
+
388
+ # Probe entrypoint inside container with strict sandbox flags
389
+ is_bundled_runner = image_tag == DEFAULT_RUNNER_TAG
390
+ base_sandbox_cmd = [
391
+ docker_path,
392
+ "run",
393
+ "--rm",
394
+ "--network",
395
+ "none",
396
+ "--user",
397
+ "10001:10001",
398
+ "--cap-drop",
399
+ "ALL",
400
+ "--security-opt",
401
+ "no-new-privileges",
402
+ "--read-only",
403
+ image_tag,
404
+ ]
405
+ run_res = subprocess.run(
406
+ [*base_sandbox_cmd, "pytest", "--version"],
407
+ shell=False,
408
+ capture_output=True,
409
+ text=True,
410
+ check=False,
411
+ timeout=self.timeout_seconds * 2,
412
+ )
413
+ if run_res.returncode == 0:
414
+ pytest_ver = (
415
+ run_res.stdout.strip().splitlines()[0] if run_res.stdout else "pytest"
416
+ )
417
+ detail_str = f"Compatible ({arch_info}, {pytest_ver}, user 10001)"
418
+ return DoctorCheckResult(
419
+ name="Runner Image Compatibility",
420
+ passed=True,
421
+ details=detail_str,
422
+ )
423
+
424
+ # For non-Python custom runners, verify unprivileged sandbox execution with 'true'
425
+ if not is_bundled_runner:
426
+ probe_true = subprocess.run(
427
+ [*base_sandbox_cmd, "true"],
428
+ shell=False,
429
+ capture_output=True,
430
+ text=True,
431
+ check=False,
432
+ timeout=self.timeout_seconds * 2,
433
+ )
434
+ if probe_true.returncode == 0:
435
+ detail_str = (
436
+ f"Compatible custom runner ({arch_info}, unprivileged sandbox operable)"
437
+ )
438
+ return DoctorCheckResult(
439
+ name="Runner Image Compatibility",
440
+ passed=True,
441
+ details=detail_str,
442
+ )
443
+ err_msg = probe_true.stderr.strip() or f"exit code {probe_true.returncode}"
444
+ compat_remed = (
445
+ f"Ensure custom image '{image_tag}' supports unprivileged execution "
446
+ "(UID 10001) under sandbox constraints (--network none, --cap-drop ALL)"
447
+ )
448
+ else:
449
+ err_msg = run_res.stderr.strip() or f"exit code {run_res.returncode}"
450
+ compat_remed = (
451
+ f"Rebuild the image with: patchproof setup-runner --tag {image_tag} --no-cache"
452
+ )
453
+
454
+ return DoctorCheckResult(
455
+ name="Runner Image Compatibility",
456
+ passed=False,
457
+ details=f"Test runner execution failed: {err_msg}",
458
+ remediation=compat_remed,
459
+ )
460
+ except (subprocess.TimeoutExpired, OSError) as exc:
461
+ return DoctorCheckResult(
462
+ name="Runner Image Compatibility",
463
+ passed=False,
464
+ details=f"Error probing image compatibility: {exc}",
465
+ remediation="Ensure Docker daemon can execute lightweight container checks",
466
+ )
467
+
468
+ def run_all_checks(self, image_tag: str = DEFAULT_RUNNER_TAG) -> list[DoctorCheckResult]:
469
+ """Execute all 7 environment checks sequentially."""
470
+ results: list[DoctorCheckResult] = []
471
+
472
+ # 1. Python version
473
+ results.append(self.check_python_version())
474
+
475
+ # 2. Git CLI
476
+ results.append(self.check_git_cli())
477
+
478
+ # 3. Docker CLI
479
+ results.append(self.check_docker_cli())
480
+
481
+ # 4. Docker Daemon
482
+ daemon_res, daemon_active = self.check_docker_daemon()
483
+ results.append(daemon_res)
484
+
485
+ # 5. Docker Engine Mode
486
+ results.append(self.check_docker_engine_mode(daemon_active))
487
+
488
+ # 6. Runner Image Presence
489
+ image_res, image_exists = self.check_runner_image_exists(image_tag, daemon_active)
490
+ results.append(image_res)
491
+
492
+ # 7. Runner Image Compatibility
493
+ results.append(self.check_runner_image_compatibility(image_tag, image_exists))
494
+
495
+ return results
496
+
497
+ def auto_remediate(self, image_tag: str = DEFAULT_RUNNER_TAG) -> list[str]:
498
+ """Automatically remediate repairable environment issues where possible."""
499
+ actions: list[str] = []
500
+ _, daemon_active = self.check_docker_daemon()
501
+ if not daemon_active:
502
+ actions.append("Docker daemon is offline; cannot auto-remediate container image.")
503
+ return actions
504
+
505
+ _, image_exists = self.check_runner_image_exists(image_tag, daemon_active=True)
506
+ if not image_exists:
507
+ if image_tag == DEFAULT_RUNNER_TAG:
508
+ from patchproof.sandbox.setup_runner import build_runner_image
509
+
510
+ try:
511
+ build_runner_image(image_tag=image_tag)
512
+ actions.append(
513
+ f"Successfully built default runner container image '{image_tag}'."
514
+ )
515
+ except Exception as exc:
516
+ actions.append(
517
+ f"Failed to auto-build default runner image '{image_tag}': {exc}"
518
+ )
519
+ else:
520
+ # Custom runner image: never build bundled Python Dockerfile under an arbitrary tag
521
+ docker_path = shutil.which("docker") or "docker"
522
+ try:
523
+ pull_res = subprocess.run(
524
+ [docker_path, "pull", image_tag],
525
+ shell=False,
526
+ capture_output=True,
527
+ text=True,
528
+ check=False,
529
+ timeout=max(self.timeout_seconds * 12, 60.0),
530
+ )
531
+ if pull_res.returncode == 0:
532
+ actions.append(f"Successfully pulled custom runner image '{image_tag}'.")
533
+ else:
534
+ pull_err = pull_res.stderr.strip() or f"exit code {pull_res.returncode}"
535
+ actions.append(
536
+ f"Custom runner image '{image_tag}' not found locally and could not be "
537
+ f"pulled ({pull_err}). Custom runner images cannot be auto-built "
538
+ f"from bundled Python Dockerfile; build or pull '{image_tag}' manually."
539
+ )
540
+ except (subprocess.TimeoutExpired, OSError) as exc:
541
+ actions.append(
542
+ f"Custom runner image '{image_tag}' not found locally and could not be "
543
+ f"pulled ({exc}). Custom runner images cannot be auto-built "
544
+ f"from bundled Python Dockerfile; build or pull '{image_tag}' manually."
545
+ )
546
+ else:
547
+ actions.append(f"Runner container image '{image_tag}' is already present.")
548
+
549
+ return actions
550
+
551
+ def format_report(
552
+ self,
553
+ results: list[DoctorCheckResult],
554
+ json_output: bool = False,
555
+ ) -> str:
556
+ """Format check results as human-readable text or structured JSON."""
557
+ if json_output:
558
+ data = {
559
+ "system": {
560
+ "os": platform.system(),
561
+ "release": platform.release(),
562
+ "machine": platform.machine(),
563
+ },
564
+ "all_passed": all(r.passed for r in results),
565
+ "checks": [r.model_dump() for r in results],
566
+ }
567
+ return json.dumps(data, indent=2)
568
+
569
+ lines: list[str] = [
570
+ "================================================================================",
571
+ " PatchProof System Doctor ",
572
+ "================================================================================",
573
+ f"Host OS: {platform.system()} {platform.release()} ({platform.machine()})",
574
+ "",
575
+ ]
576
+
577
+ all_passed = True
578
+ failed_checks: list[DoctorCheckResult] = []
579
+
580
+ for r in results:
581
+ symbol = "[PASS]" if r.passed else "[FAIL]"
582
+ lines.append(f"{symbol} {r.name:<30} {r.details}")
583
+ if not r.passed:
584
+ all_passed = False
585
+ failed_checks.append(r)
586
+
587
+ lines.append("")
588
+ if all_passed:
589
+ lines.append("RESULT: All prerequisites passed! Environment is ready for PatchProof.")
590
+ else:
591
+ lines.append(
592
+ f"RESULT: {len(failed_checks)} prerequisite check(s) failed. "
593
+ "Actionable remediation required:\n"
594
+ )
595
+ for fc in failed_checks:
596
+ lines.append(f" * {fc.name}:")
597
+ lines.append(f" Issue: {fc.details}")
598
+ if fc.remediation:
599
+ lines.append(f" Remediation: {fc.remediation}")
600
+ lines.append("")
601
+
602
+ lines.append(
603
+ "================================================================================"
604
+ )
605
+ return "\n".join(lines)
@@ -0,0 +1,87 @@
1
+ """Flakiness Disambiguation Engine.
2
+
3
+ Differentiates true deterministic regressions from non-deterministic test flakes,
4
+ intermittent race conditions, and transient timing anomalies inside the isolated sandbox.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass
11
+ from enum import StrEnum
12
+
13
+
14
+ class FlakeStatus(StrEnum):
15
+ """Categorization of test determinism across repeated executions."""
16
+
17
+ DETERMINISTIC_REGRESSION = "deterministic_regression"
18
+ FLAKY_TRANSIENT = "flaky_transient"
19
+ TRANSIENT_ANOMALY = "transient_anomaly"
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class FlakeAnalysisReport:
24
+ """Consolidated assessment of test repeatability and flakiness."""
25
+
26
+ __test__ = False
27
+
28
+ test_name: str
29
+ attempts: int
30
+ pass_count: int
31
+ fail_count: int
32
+ status: FlakeStatus
33
+ durations: tuple[float, ...]
34
+ summary: str
35
+
36
+ @property
37
+ def is_flaky(self) -> bool:
38
+ """Return True if the test demonstrated non-deterministic outcomes."""
39
+ return self.status in (FlakeStatus.FLAKY_TRANSIENT, FlakeStatus.TRANSIENT_ANOMALY)
40
+
41
+
42
+ def disambiguate_flakiness(
43
+ test_name: str,
44
+ runner_fn: Callable[[str], tuple[bool, float]],
45
+ attempts: int = 3,
46
+ ) -> FlakeAnalysisReport:
47
+ """Execute target test repeatedly to establish determinism or flakiness."""
48
+ pass_count = 0
49
+ fail_count = 0
50
+ durations: list[float] = []
51
+
52
+ for _ in range(attempts):
53
+ passed, duration = runner_fn(test_name)
54
+ durations.append(duration)
55
+ if passed:
56
+ pass_count += 1
57
+ else:
58
+ fail_count += 1
59
+
60
+ if fail_count == attempts:
61
+ status = FlakeStatus.DETERMINISTIC_REGRESSION
62
+ summary = (
63
+ f"Test '{test_name}' failed consistently across all {attempts} runs "
64
+ "(confirmed deterministic regression)."
65
+ )
66
+ elif pass_count == attempts:
67
+ status = FlakeStatus.TRANSIENT_ANOMALY
68
+ summary = (
69
+ f"Test '{test_name}' passed across all {attempts} retry runs "
70
+ "(initial failure was a transient anomaly)."
71
+ )
72
+ else:
73
+ status = FlakeStatus.FLAKY_TRANSIENT
74
+ summary = (
75
+ f"Test '{test_name}' is non-deterministic / flaky: passed {pass_count}/{attempts}, "
76
+ f"failed {fail_count}/{attempts}."
77
+ )
78
+
79
+ return FlakeAnalysisReport(
80
+ test_name=test_name,
81
+ attempts=attempts,
82
+ pass_count=pass_count,
83
+ fail_count=fail_count,
84
+ status=status,
85
+ durations=tuple(durations),
86
+ summary=summary,
87
+ )