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
patchproof/cli.py ADDED
@@ -0,0 +1,1254 @@
1
+ """Unified Command-Line Interface for PatchProof."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import logging
8
+ import pathlib
9
+ import sys
10
+ from collections.abc import Sequence
11
+ from enum import IntEnum
12
+ from typing import NoReturn
13
+
14
+ from patchproof.core.agent_init import (
15
+ init_aider_config,
16
+ init_all_agents,
17
+ init_claude_config,
18
+ init_cursor_config,
19
+ )
20
+ from patchproof.core.detector import detect_project_stack
21
+ from patchproof.core.git_provider import (
22
+ get_head_diff,
23
+ get_uncommitted_diff,
24
+ install_pre_commit_hook,
25
+ )
26
+ from patchproof.core.healer import AutonomousHealer
27
+ from patchproof.core.normalizer import parse_patch
28
+ from patchproof.core.slicer import slice_test_suite
29
+ from patchproof.exceptions import (
30
+ DockerUnavailableError,
31
+ GitRepositoryError,
32
+ NoChangesDetectedError,
33
+ SandboxSecurityError,
34
+ UnsupportedDockerEngineError,
35
+ )
36
+ from patchproof.factory.blast_radius import BlastRadiusClassifier
37
+ from patchproof.factory.engine import FactoryEngine, GateResult
38
+ from patchproof.factory.models import FactoryLineage, HybridLoopState
39
+ from patchproof.mcp import MCPServer
40
+ from patchproof.models.patch import CanonicalPatch
41
+ from patchproof.models.sandbox import (
42
+ ComparativeExecutionResult,
43
+ ContainerConfig,
44
+ PatchVerdict,
45
+ RegressionClassification,
46
+ ResourceLimits,
47
+ )
48
+ from patchproof.reporting.badge import generate_svg_badge
49
+ from patchproof.reporting.certificate import (
50
+ ProofCertificate,
51
+ export_certificate,
52
+ generate_certificate,
53
+ verify_certificate,
54
+ )
55
+ from patchproof.reporting.diagnostic import AISelfHealingReport, generate_ai_feedback
56
+ from patchproof.reporting.html_report import generate_html_report
57
+ from patchproof.reporting.in_toto import (
58
+ build_dsse_envelope,
59
+ build_in_toto_statement,
60
+ verify_dsse_envelope,
61
+ )
62
+ from patchproof.reporting.markdown import generate_markdown_summary
63
+ from patchproof.sandbox.comparative import ComparativeRunner
64
+ from patchproof.sandbox.docker_cli import parse_test_command
65
+ from patchproof.sandbox.doctor import SystemDoctor
66
+ from patchproof.sandbox.setup_runner import (
67
+ DEFAULT_RUNNER_TAG,
68
+ build_runner_from_repo,
69
+ build_runner_image,
70
+ )
71
+
72
+ logger = logging.getLogger(__name__)
73
+
74
+
75
+ class ExitCode(IntEnum):
76
+ """Exit codes returned by PatchProof CLI."""
77
+
78
+ ACCEPTED = 0
79
+ REJECTED = 1
80
+ SUSPICIOUS = 2
81
+ INCONCLUSIVE = 3
82
+ INFRASTRUCTURE_FAILURE = 4
83
+ CLI_ERROR = 5
84
+
85
+
86
+ VERDICT_EXIT_CODES: dict[PatchVerdict, int] = {
87
+ PatchVerdict.ACCEPTED: ExitCode.ACCEPTED,
88
+ PatchVerdict.REJECTED: ExitCode.REJECTED,
89
+ PatchVerdict.SUSPICIOUS: ExitCode.SUSPICIOUS,
90
+ PatchVerdict.INCONCLUSIVE: ExitCode.INCONCLUSIVE,
91
+ PatchVerdict.INFRASTRUCTURE_FAILURE: ExitCode.INFRASTRUCTURE_FAILURE,
92
+ }
93
+
94
+
95
+ class PatchProofArgumentParser(argparse.ArgumentParser):
96
+ """Custom ArgumentParser exiting with ExitCode.CLI_ERROR on argument errors."""
97
+
98
+ def error(self, message: str) -> NoReturn:
99
+ sys.stderr.write(f"patchproof: error: {message}\n")
100
+ sys.exit(ExitCode.CLI_ERROR)
101
+
102
+
103
+ def build_parser() -> argparse.ArgumentParser:
104
+ """Build the command-line argument parser."""
105
+ parser = PatchProofArgumentParser(
106
+ prog="patchproof",
107
+ description="PatchProof: Deterministic Code Patch Verification Engine",
108
+ )
109
+ subparsers = parser.add_subparsers(
110
+ dest="command",
111
+ required=True,
112
+ help="Subcommand to execute",
113
+ )
114
+
115
+ verify_parser = subparsers.add_parser(
116
+ "verify",
117
+ help="Verify a code patch against a test suite in an isolated sandbox",
118
+ )
119
+ verify_parser.add_argument(
120
+ "patch",
121
+ nargs="?",
122
+ default=None,
123
+ help="Path to patch file, or '-' for stdin. Optional if --git or --head is used",
124
+ )
125
+ verify_parser.add_argument(
126
+ "--git",
127
+ action="store_true",
128
+ help="Extract and verify uncommitted working tree changes in target repository",
129
+ )
130
+ verify_parser.add_argument(
131
+ "--head",
132
+ action="store_true",
133
+ help="Extract and verify changes from the latest HEAD commit in target repository",
134
+ )
135
+ verify_parser.add_argument(
136
+ "--repo",
137
+ default=".",
138
+ help="Path to target repository on host (default: current directory)",
139
+ )
140
+ verify_parser.add_argument(
141
+ "--image",
142
+ default=None,
143
+ help="Docker runner image (default: auto-detected from project)",
144
+ )
145
+ verify_parser.add_argument(
146
+ "--timeout",
147
+ type=float,
148
+ default=15.0,
149
+ help="Per-run container execution timeout in seconds (default: 15.0)",
150
+ )
151
+ verify_parser.add_argument(
152
+ "--test-command",
153
+ "-c",
154
+ default=None,
155
+ help="Custom test execution command (default: auto-detected from project)",
156
+ )
157
+ verify_parser.add_argument(
158
+ "--json",
159
+ action="store_true",
160
+ help="Output machine-readable JSON report",
161
+ )
162
+ verify_parser.add_argument(
163
+ "--html",
164
+ default=None,
165
+ metavar="PATH",
166
+ help="Write self-contained visual HTML evidence report to specified path",
167
+ )
168
+ verify_parser.add_argument(
169
+ "--verbose",
170
+ action="store_true",
171
+ help="Include full test execution details and individual test comparisons",
172
+ )
173
+ verify_parser.add_argument(
174
+ "--ai-feedback",
175
+ action="store_true",
176
+ help="Display actionable AI self-healing diagnostic prompt on regression",
177
+ )
178
+ verify_parser.add_argument(
179
+ "--slice",
180
+ "--fast",
181
+ dest="slice_tests",
182
+ action="store_true",
183
+ help="Predictively slice test suite to run only impacted tests",
184
+ )
185
+ verify_parser.add_argument(
186
+ "--disambiguate-flakes",
187
+ action="store_true",
188
+ help="Re-run introduced regressions 3x in sandbox to filter out non-deterministic flakes",
189
+ )
190
+ verify_parser.add_argument(
191
+ "--allow-test-edits",
192
+ action="store_true",
193
+ help="Allow test file modifications without triggering anti-cheat alerts",
194
+ )
195
+ verify_parser.add_argument(
196
+ "--cert",
197
+ default=None,
198
+ metavar="PATH",
199
+ help="Write cryptographic Proof-of-Patch certificate to specified path",
200
+ )
201
+ verify_parser.add_argument(
202
+ "--secret-key",
203
+ default=None,
204
+ help="Custom secret key for HMAC certificate signing",
205
+ )
206
+ verify_parser.add_argument(
207
+ "--private-key",
208
+ default=None,
209
+ help="Path to Ed25519 private key PEM file for asymmetric certificate signing",
210
+ )
211
+ verify_parser.add_argument(
212
+ "--signer-identity",
213
+ default=None,
214
+ help="Signer identity string (e.g. CI workflow or actor)",
215
+ )
216
+ verify_parser.add_argument(
217
+ "--in-toto",
218
+ default=None,
219
+ metavar="PATH",
220
+ help="Write signed in-toto v1.0 DSSE attestation envelope to specified path",
221
+ )
222
+ verify_parser.add_argument(
223
+ "--markdown",
224
+ "--summary-file",
225
+ default=None,
226
+ metavar="PATH",
227
+ help="Write GitHub-Flavored Markdown summary proof card to specified path",
228
+ )
229
+ verify_parser.add_argument(
230
+ "--badge",
231
+ default=None,
232
+ metavar="PATH",
233
+ help="Write standalone SVG verification badge to specified path",
234
+ )
235
+
236
+ setup_runner_parser = subparsers.add_parser(
237
+ "setup-runner",
238
+ help="Build standard PatchProof test runner container image locally",
239
+ )
240
+ setup_runner_parser.add_argument(
241
+ "--from-repo",
242
+ default=None,
243
+ metavar="PATH",
244
+ help="Inspect repository dependencies (requirements, pyproject) and build runner",
245
+ )
246
+ setup_runner_parser.add_argument(
247
+ "--tag",
248
+ default=DEFAULT_RUNNER_TAG,
249
+ help=f"Tag for runner image (default: {DEFAULT_RUNNER_TAG})",
250
+ )
251
+ setup_runner_parser.add_argument(
252
+ "--dockerfile",
253
+ default=None,
254
+ help="Path to runner Dockerfile (default: auto-detected)",
255
+ )
256
+ setup_runner_parser.add_argument(
257
+ "--no-cache",
258
+ action="store_true",
259
+ help="Do not use cache when building image",
260
+ )
261
+ setup_runner_parser.add_argument(
262
+ "--quiet",
263
+ action="store_true",
264
+ help="Suppress non-error build progress output",
265
+ )
266
+
267
+ doctor_parser = subparsers.add_parser(
268
+ "doctor",
269
+ help="Inspect host environment prerequisites and report actionable diagnostics",
270
+ )
271
+ doctor_parser.add_argument(
272
+ "--image",
273
+ default=DEFAULT_RUNNER_TAG,
274
+ help=f"Runner image to inspect (default: {DEFAULT_RUNNER_TAG})",
275
+ )
276
+ doctor_parser.add_argument(
277
+ "--json",
278
+ action="store_true",
279
+ help="Output diagnostics in structured JSON format",
280
+ )
281
+ doctor_parser.add_argument(
282
+ "--timeout",
283
+ type=float,
284
+ default=5.0,
285
+ help="Timeout in seconds for individual diagnostic checks (default: 5.0)",
286
+ )
287
+ doctor_parser.add_argument(
288
+ "--fix",
289
+ action="store_true",
290
+ help="Automatically attempt remediation for repairable environment issues",
291
+ )
292
+
293
+ install_hooks_parser = subparsers.add_parser(
294
+ "install-hooks",
295
+ help="Install Git pre-commit verification hook in target repository",
296
+ )
297
+ install_hooks_parser.add_argument(
298
+ "--repo",
299
+ default=".",
300
+ help="Path to target Git repository (default: current directory)",
301
+ )
302
+
303
+ init_agent_parser = subparsers.add_parser(
304
+ "init-agent",
305
+ help="Initialize configuration and rules for AI coding agents (Claude, Cursor, Aider)",
306
+ )
307
+ init_agent_parser.add_argument(
308
+ "agent",
309
+ choices=["all", "aider", "cursor", "claude"],
310
+ default="all",
311
+ nargs="?",
312
+ help="Target AI agent configuration to generate (default: all)",
313
+ )
314
+ init_agent_parser.add_argument(
315
+ "--repo",
316
+ default=".",
317
+ help="Path to target repository (default: current directory)",
318
+ )
319
+ init_agent_parser.add_argument(
320
+ "--force",
321
+ action="store_true",
322
+ help="Overwrite existing configuration files if they exist",
323
+ )
324
+
325
+ subparsers.add_parser(
326
+ "mcp",
327
+ help="Start built-in Model Context Protocol (MCP) server over standard I/O",
328
+ )
329
+
330
+ keygen_parser = subparsers.add_parser(
331
+ "keygen",
332
+ help="Generate Ed25519 cryptographic keypair for Proof-of-Patch attestation",
333
+ )
334
+ keygen_parser.add_argument(
335
+ "--out-dir",
336
+ default=".",
337
+ help="Directory to save generated keypair (default: current directory)",
338
+ )
339
+ keygen_parser.add_argument(
340
+ "--name",
341
+ default="patchproof_key",
342
+ help="Base name for key files (default: patchproof_key)",
343
+ )
344
+
345
+ verify_cert_parser = subparsers.add_parser(
346
+ "verify-cert",
347
+ help="Validate cryptographic signature and integrity of a Proof-of-Patch certificate",
348
+ )
349
+ verify_cert_parser.add_argument(
350
+ "certificate",
351
+ help="Path to Proof-of-Patch certificate JSON file",
352
+ )
353
+ verify_cert_parser.add_argument(
354
+ "--secret-key",
355
+ default=None,
356
+ help="Custom HMAC secret key used for validation",
357
+ )
358
+ verify_cert_parser.add_argument(
359
+ "--public-key",
360
+ default=None,
361
+ help="Path to Ed25519 public key file (.pub / PEM)",
362
+ )
363
+
364
+ verify_attest_parser = subparsers.add_parser(
365
+ "verify-attestation",
366
+ help="Validate cryptographic signature of an in-toto DSSE attestation envelope",
367
+ )
368
+ verify_attest_parser.add_argument(
369
+ "attestation",
370
+ help="Path to in-toto DSSE attestation JSON envelope",
371
+ )
372
+ verify_attest_parser.add_argument(
373
+ "--public-key",
374
+ required=True,
375
+ help="Path to Ed25519 public key file (.pub / PEM)",
376
+ )
377
+
378
+ eval_bench_parser = subparsers.add_parser(
379
+ "eval-benchmark",
380
+ help="Audit a batch of SWE-bench predictions for test tampering and agent shortcuts",
381
+ )
382
+ eval_bench_parser.add_argument(
383
+ "predictions",
384
+ help="Path to SWE-bench predictions JSON file",
385
+ )
386
+ eval_bench_parser.add_argument(
387
+ "--out-csv",
388
+ default="swe_bench_audit.csv",
389
+ help="Path to output CSV compliance register (default: swe_bench_audit.csv)",
390
+ )
391
+ eval_bench_parser.add_argument(
392
+ "--repo",
393
+ default=".",
394
+ help="Path to baseline repository root (default: current dir)",
395
+ )
396
+
397
+ mutate_parser = subparsers.add_parser(
398
+ "mutate",
399
+ help="Generate and inspect AST mutants for differential mutation testing",
400
+ )
401
+ mutate_parser.add_argument(
402
+ "file",
403
+ help="Path to Python file to generate mutants for",
404
+ )
405
+ mutate_parser.add_argument(
406
+ "--max-mutants",
407
+ type=int,
408
+ default=15,
409
+ help="Maximum mutants to generate (default: 15)",
410
+ )
411
+ mutate_parser.add_argument(
412
+ "--json",
413
+ action="store_true",
414
+ help="Output mutants as JSON",
415
+ )
416
+
417
+ heal_parser = subparsers.add_parser(
418
+ "heal",
419
+ help="Autonomous self-healing loop: verify and repair patch regressions",
420
+ )
421
+ heal_parser.add_argument(
422
+ "patch",
423
+ nargs="?",
424
+ default=None,
425
+ help="Path to patch file, or '-' for stdin. Optional if --git is used",
426
+ )
427
+ heal_parser.add_argument(
428
+ "--git",
429
+ action="store_true",
430
+ help="Extract and heal uncommitted working tree changes",
431
+ )
432
+ heal_parser.add_argument(
433
+ "--max-iterations",
434
+ type=int,
435
+ default=3,
436
+ help="Maximum self-healing convergence iterations (default: 3)",
437
+ )
438
+ heal_parser.add_argument(
439
+ "--repo",
440
+ default=".",
441
+ help="Path to target repository on host (default: current directory)",
442
+ )
443
+ heal_parser.add_argument(
444
+ "--image",
445
+ default=None,
446
+ help="Custom Docker runner image (required for non-Python projects in v0.3.0)",
447
+ )
448
+
449
+ factory_parser = subparsers.add_parser(
450
+ "factory",
451
+ help="AI Software Factory: assess blast radius and run autonomous hybrid loop",
452
+ )
453
+ factory_sub = factory_parser.add_subparsers(
454
+ dest="factory_action",
455
+ metavar="ACTION",
456
+ required=True,
457
+ )
458
+
459
+ eval_parser = factory_sub.add_parser(
460
+ "evaluate",
461
+ help="Assess blast radius and assign Lineage A or Lineage B",
462
+ )
463
+ eval_parser.add_argument(
464
+ "patch", nargs="?", default=None, help="Path to patch file, or '-' for stdin"
465
+ )
466
+ eval_parser.add_argument(
467
+ "--git",
468
+ action="store_true",
469
+ help="Evaluate uncommitted changes in git working tree",
470
+ )
471
+ eval_parser.add_argument(
472
+ "--head", action="store_true", help="Evaluate git HEAD commit diff"
473
+ )
474
+ eval_parser.add_argument(
475
+ "--json", action="store_true", help="Output blast radius report as JSON"
476
+ )
477
+ eval_parser.add_argument("--repo", default=".", help="Repository root path")
478
+
479
+ run_parser = factory_sub.add_parser(
480
+ "run",
481
+ help="Execute autonomous hybrid loop on a trigger signal",
482
+ )
483
+ run_parser.add_argument(
484
+ "--trigger", required=True, help="Trigger signal identifier or description"
485
+ )
486
+ run_parser.add_argument("--patch", default=None, help="Path to candidate patch file")
487
+ run_parser.add_argument("--repo", default=".", help="Repository root path")
488
+ run_parser.add_argument(
489
+ "--max-retries", type=int, default=3, help="Max retry loops (default: 3)"
490
+ )
491
+ run_parser.add_argument(
492
+ "--json", action="store_true", help="Output final result as JSON"
493
+ )
494
+
495
+ return parser
496
+
497
+
498
+ def format_json_report(result: ComparativeExecutionResult, patch_content: str = "") -> str:
499
+ """Format comparative execution result as structured JSON."""
500
+ canonical_patch: CanonicalPatch | None = None
501
+ if patch_content:
502
+ try:
503
+ canonical_patch = parse_patch(patch_content)
504
+ except Exception:
505
+ pass
506
+
507
+ ai_report = generate_ai_feedback(result, patch=canonical_patch)
508
+
509
+ report = {
510
+ "verdict": result.verdict.value,
511
+ "summary": result.summary,
512
+ "ai_feedback": ai_report.to_dict(),
513
+ "metrics": {
514
+ "introduced_regressions": result.introduced_regressions_count,
515
+ "flaky_tests": result.flaky_tests_count,
516
+ "resolved_defects": result.resolved_defects_count,
517
+ "pre_existing_failures": result.pre_existing_failures_count,
518
+ "suppressed_tests": result.suppressed_tests_count,
519
+ "removed_tests": result.removed_tests_count,
520
+ "test_tampering_detected": result.test_tampering_detected,
521
+ "tampering_details": list(result.tampering_details),
522
+ "collection_failure": result.collection_failure_occurred,
523
+ },
524
+ "execution": {
525
+ "baseline": {
526
+ "exit_code": result.baseline_result.exit_code,
527
+ "duration_seconds": result.baseline_result.duration_seconds,
528
+ "failure_reason": result.baseline_result.failure_reason.value,
529
+ "oom_killed": result.baseline_result.oom_killed,
530
+ "timeout_triggered": result.baseline_result.timeout_triggered,
531
+ },
532
+ "patched": {
533
+ "exit_code": result.patched_result.exit_code,
534
+ "duration_seconds": result.patched_result.duration_seconds,
535
+ "failure_reason": result.patched_result.failure_reason.value,
536
+ "oom_killed": result.patched_result.oom_killed,
537
+ "timeout_triggered": result.patched_result.timeout_triggered,
538
+ },
539
+ },
540
+ "tests": [
541
+ {
542
+ "name": tc.test_name,
543
+ "baseline_outcome": tc.baseline_outcome.value if tc.baseline_outcome else None,
544
+ "patched_outcome": tc.patched_outcome.value if tc.patched_outcome else None,
545
+ "classification": tc.classification.value,
546
+ "message": tc.message,
547
+ }
548
+ for tc in result.test_comparisons
549
+ ],
550
+ }
551
+ return json.dumps(report, indent=2)
552
+
553
+
554
+ def format_terminal_report(result: ComparativeExecutionResult, verbose: bool = False) -> str:
555
+ """Format comparative execution result as human-readable terminal output."""
556
+ clean_count = sum(
557
+ 1
558
+ for t in result.test_comparisons
559
+ if t.classification == RegressionClassification.CLEAN_PRESERVATION
560
+ )
561
+ b_res = result.baseline_result
562
+ p_res = result.patched_result
563
+
564
+ lines: list[str] = [
565
+ "=" * 78,
566
+ " PATCHPROOF VERIFICATION REPORT",
567
+ "=" * 78,
568
+ f"Verdict: {result.verdict.value.upper()}",
569
+ f"Summary: {result.summary}",
570
+ "-" * 78,
571
+ "Metrics:",
572
+ f" - Preserved Passing Tests: {clean_count}",
573
+ f" - Resolved Defects: {result.resolved_defects_count}",
574
+ f" - Introduced Regressions: {result.introduced_regressions_count}",
575
+ f" - Suppressed Tests: {result.suppressed_tests_count}",
576
+ f" - Removed Tests: {result.removed_tests_count}",
577
+ f" - Test Tampering Alert: {'DETECTED' if result.test_tampering_detected else 'None'}",
578
+ f" - Pre-existing Failures: {result.pre_existing_failures_count}",
579
+ f" - Collection Failure: {'YES' if result.collection_failure_occurred else 'No'}",
580
+ "-" * 78,
581
+ "Execution Details:",
582
+ f" - Baseline: Exit code {b_res.exit_code} ({b_res.duration_seconds:.2f}s)",
583
+ f" - Patched: Exit code {p_res.exit_code} ({p_res.duration_seconds:.2f}s)",
584
+ ]
585
+
586
+ # Show critical test transitions or full breakdown if verbose
587
+ critical_cases = [
588
+ tc
589
+ for tc in result.test_comparisons
590
+ if verbose
591
+ or tc.classification
592
+ in (
593
+ RegressionClassification.INTRODUCED_REGRESSION,
594
+ RegressionClassification.RESOLVED_DEFECT,
595
+ RegressionClassification.SUPPRESSION_ALERT,
596
+ )
597
+ ]
598
+
599
+ if critical_cases:
600
+ lines.append("-" * 78)
601
+ lines.append("Test Transitions:")
602
+ for tc in critical_cases:
603
+ tag = f"[{tc.classification.value.upper()}]"
604
+ b_out = tc.baseline_outcome.value.upper() if tc.baseline_outcome else "NONE"
605
+ p_out = tc.patched_outcome.value.upper() if tc.patched_outcome else "NONE"
606
+ lines.append(f" {tag:<26} {tc.test_name} ({b_out} -> {p_out})")
607
+
608
+ if result.test_tampering_detected and result.tampering_details:
609
+ lines.append("-" * 78)
610
+ lines.append("Anti-Cheat Tampering Violations:")
611
+ for detail in result.tampering_details:
612
+ lines.append(f" [TAMPERING] {detail}")
613
+
614
+ # Display diagnostic output if run failed or had collection/setup errors
615
+ err_text = result.patched_result.stderr.strip()
616
+ if err_text and result.verdict in (
617
+ PatchVerdict.REJECTED,
618
+ PatchVerdict.INFRASTRUCTURE_FAILURE,
619
+ ):
620
+ lines.append("-" * 78)
621
+ lines.append("Diagnostic Output (Stderr):")
622
+ for err_line in err_text.splitlines()[:5]:
623
+ lines.append(f" {err_line}")
624
+ if len(err_text.splitlines()) > 5:
625
+ lines.append(" [... truncated, use --verbose or --json for full output]")
626
+
627
+ lines.append("=" * 78)
628
+ return "\n".join(lines)
629
+
630
+
631
+ def main(argv: Sequence[str] | None = None) -> int:
632
+ """Execute PatchProof CLI entrypoint."""
633
+ parser = build_parser()
634
+ args = parser.parse_args(argv)
635
+
636
+ if args.command == "setup-runner":
637
+ if args.from_repo:
638
+ target_repo = pathlib.Path(args.from_repo).resolve()
639
+ res_code, _assigned_tag = build_runner_from_repo(
640
+ repo_path=target_repo,
641
+ image_tag=args.tag if args.tag != DEFAULT_RUNNER_TAG else None,
642
+ no_cache=args.no_cache,
643
+ quiet=args.quiet,
644
+ )
645
+ return ExitCode.ACCEPTED if res_code == 0 else ExitCode.CLI_ERROR
646
+
647
+ dockerfile = pathlib.Path(args.dockerfile) if args.dockerfile else None
648
+ res_code = build_runner_image(
649
+ image_tag=args.tag,
650
+ dockerfile_path=dockerfile,
651
+ no_cache=args.no_cache,
652
+ quiet=args.quiet,
653
+ )
654
+ return ExitCode.ACCEPTED if res_code == 0 else ExitCode.CLI_ERROR
655
+
656
+ if args.command == "doctor":
657
+ doctor = SystemDoctor(timeout_seconds=args.timeout)
658
+ if getattr(args, "fix", False):
659
+ sys.stdout.write("patchproof: attempting automatic remediation...\n")
660
+ fix_actions = doctor.auto_remediate(image_tag=args.image)
661
+ for act in fix_actions:
662
+ sys.stdout.write(f" * {act}\n")
663
+ sys.stdout.write("\n")
664
+ results = doctor.run_all_checks(image_tag=args.image)
665
+ sys.stdout.write(doctor.format_report(results, json_output=args.json) + "\n")
666
+ return ExitCode.ACCEPTED if all(r.passed for r in results) else ExitCode.REJECTED
667
+
668
+ if args.command == "install-hooks":
669
+ repo_path = pathlib.Path(args.repo).resolve()
670
+ try:
671
+ hook_file = install_pre_commit_hook(repo_path)
672
+ sys.stdout.write(f"patchproof: pre-commit hook installed successfully at {hook_file}\n")
673
+ return ExitCode.ACCEPTED
674
+ except GitRepositoryError as err:
675
+ sys.stderr.write(f"patchproof: error: {err}\n")
676
+ return ExitCode.CLI_ERROR
677
+
678
+ if args.command == "mcp":
679
+ server = MCPServer()
680
+ server.run_stdio()
681
+ return ExitCode.ACCEPTED
682
+
683
+ if args.command == "init-agent":
684
+ target_repo = pathlib.Path(args.repo).resolve()
685
+ if not target_repo.is_dir():
686
+ sys.stderr.write(f"patchproof: error: target directory not found: {args.repo}\n")
687
+ return ExitCode.CLI_ERROR
688
+
689
+ created_files: list[pathlib.Path] = []
690
+ if args.agent == "aider":
691
+ created_files = init_aider_config(target_repo, force=args.force)
692
+ elif args.agent == "cursor":
693
+ created_files = init_cursor_config(target_repo, force=args.force)
694
+ elif args.agent == "claude":
695
+ created_files = init_claude_config(target_repo, force=args.force)
696
+ else:
697
+ created_files = init_all_agents(target_repo, force=args.force)
698
+
699
+ if created_files:
700
+ sys.stdout.write("patchproof: successfully initialized AI agent configuration:\n")
701
+ for f in created_files:
702
+ try:
703
+ rel_f = f.relative_to(target_repo)
704
+ except ValueError:
705
+ rel_f = f
706
+ sys.stdout.write(f" + {rel_f}\n")
707
+ else:
708
+ sys.stdout.write(
709
+ "patchproof: configuration files already exist (use --force to overwrite)\n"
710
+ )
711
+ return ExitCode.ACCEPTED
712
+
713
+ if args.command == "keygen":
714
+ out_dir = pathlib.Path(args.out_dir).resolve()
715
+ out_dir.mkdir(parents=True, exist_ok=True)
716
+ priv_path = out_dir / f"{args.name}.pem"
717
+ pub_path = out_dir / f"{args.name}.pub"
718
+ from patchproof.reporting.asymmetric import generate_ed25519_keypair
719
+
720
+ priv_pem, pub_pem = generate_ed25519_keypair()
721
+ priv_path.write_text(priv_pem, encoding="utf-8")
722
+ pub_path.write_text(pub_pem, encoding="utf-8")
723
+ sys.stdout.write(
724
+ f"patchproof: Generated Ed25519 keypair:\n"
725
+ f" Private key: {priv_path}\n"
726
+ f" Public key: {pub_path}\n"
727
+ )
728
+ return ExitCode.ACCEPTED
729
+
730
+ if args.command == "verify-cert":
731
+ cert_path = pathlib.Path(args.certificate)
732
+ if not cert_path.is_file():
733
+ sys.stderr.write(f"patchproof: error: certificate file not found: {args.certificate}\n")
734
+ return ExitCode.CLI_ERROR
735
+ try:
736
+ cert_data = json.loads(cert_path.read_text(encoding="utf-8"))
737
+ cert = ProofCertificate(**cert_data)
738
+ except Exception as err:
739
+ sys.stderr.write(f"patchproof: error: invalid certificate format: {err}\n")
740
+ return ExitCode.CLI_ERROR
741
+
742
+ pub_key_pem = None
743
+ if args.public_key:
744
+ pub_path = pathlib.Path(args.public_key)
745
+ if not pub_path.is_file():
746
+ sys.stderr.write(
747
+ f"patchproof: error: public key file not found: {args.public_key}\n"
748
+ )
749
+ return ExitCode.CLI_ERROR
750
+ pub_key_pem = pub_path.read_text(encoding="utf-8")
751
+
752
+ if verify_certificate(cert, secret_key=args.secret_key, public_key_pem=pub_key_pem):
753
+ sys.stdout.write(
754
+ "patchproof: Proof-of-Patch certificate verified valid and untampered.\n"
755
+ )
756
+ return ExitCode.ACCEPTED
757
+ else:
758
+ sys.stderr.write(
759
+ "patchproof: error: certificate validation failed "
760
+ "(invalid signature or tampered content)\n"
761
+ )
762
+ return ExitCode.REJECTED
763
+
764
+ if args.command == "verify-attestation":
765
+ attest_path = pathlib.Path(args.attestation)
766
+ if not attest_path.is_file():
767
+ sys.stderr.write(f"patchproof: error: attestation file not found: {args.attestation}\n")
768
+ return ExitCode.CLI_ERROR
769
+ pub_path = pathlib.Path(args.public_key)
770
+ if not pub_path.is_file():
771
+ sys.stderr.write(f"patchproof: error: public key file not found: {args.public_key}\n")
772
+ return ExitCode.CLI_ERROR
773
+ try:
774
+ envelope_data = json.loads(attest_path.read_text(encoding="utf-8"))
775
+ pub_key_pem = pub_path.read_text(encoding="utf-8")
776
+ except Exception as err:
777
+ sys.stderr.write(f"patchproof: error: invalid attestation JSON: {err}\n")
778
+ return ExitCode.CLI_ERROR
779
+
780
+ if verify_dsse_envelope(envelope_data, public_key_pem=pub_key_pem):
781
+ sys.stdout.write(
782
+ "patchproof: in-toto DSSE attestation verified valid and untampered.\n"
783
+ )
784
+ return ExitCode.ACCEPTED
785
+ else:
786
+ sys.stderr.write(
787
+ "patchproof: error: attestation signature verification failed "
788
+ "(tampered content or invalid key)\n"
789
+ )
790
+ return ExitCode.REJECTED
791
+
792
+ if args.command == "eval-benchmark":
793
+ preds_path = pathlib.Path(args.predictions)
794
+ if not preds_path.is_file():
795
+ sys.stderr.write(f"patchproof: error: predictions file not found: {args.predictions}\n")
796
+ return ExitCode.CLI_ERROR
797
+ try:
798
+ preds_data = json.loads(preds_path.read_text(encoding="utf-8"))
799
+ if not isinstance(preds_data, list):
800
+ sys.stderr.write("patchproof: error: predictions file must contain a JSON list\n")
801
+ return ExitCode.CLI_ERROR
802
+ except Exception as err:
803
+ sys.stderr.write(f"patchproof: error: failed to parse predictions JSON: {err}\n")
804
+ return ExitCode.CLI_ERROR
805
+
806
+ from patchproof.benchmarks.swe_bench import (
807
+ audit_swe_bench_predictions,
808
+ export_swe_bench_register_csv,
809
+ )
810
+
811
+ repo_root = pathlib.Path(args.repo).resolve()
812
+ bench_report = audit_swe_bench_predictions(preds_data, repo_root=repo_root)
813
+ out_csv = pathlib.Path(args.out_csv)
814
+ export_swe_bench_register_csv(bench_report, out_csv)
815
+
816
+ sys.stdout.write(
817
+ f"patchproof: SWE-bench Audit: {bench_report.total_tasks} evaluated, "
818
+ f"{bench_report.honest_count} honest, {bench_report.tampered_count} tampered "
819
+ f"(cheat rate: {bench_report.cheat_rate_pct:.1f}%)\n"
820
+ f"patchproof: results register written to {out_csv}\n"
821
+ )
822
+ return ExitCode.ACCEPTED if bench_report.tampered_count == 0 else ExitCode.REJECTED
823
+
824
+ if args.command == "mutate":
825
+ target_file = pathlib.Path(args.file)
826
+ if not target_file.is_file():
827
+ sys.stderr.write(f"patchproof: error: target file not found: {args.file}\n")
828
+ return ExitCode.CLI_ERROR
829
+
830
+ from patchproof.core.mutator import generate_mutants_for_source
831
+
832
+ src_text = target_file.read_text(encoding="utf-8", errors="ignore")
833
+ mutants = generate_mutants_for_source(
834
+ src_text, file_path=str(target_file), max_mutants=args.max_mutants
835
+ )
836
+
837
+ if args.json:
838
+ out_data = [
839
+ {
840
+ "id": m.id,
841
+ "line": m.line_number,
842
+ "desc": m.description,
843
+ "source": m.mutated_source,
844
+ }
845
+ for m in mutants
846
+ ]
847
+ sys.stdout.write(json.dumps(out_data, indent=2) + "\n")
848
+ else:
849
+ sys.stdout.write(
850
+ f"patchproof: generated {len(mutants)} AST mutants for {target_file}:\n"
851
+ )
852
+ for m in mutants:
853
+ sys.stdout.write(f" [{m.id}] {m.description}\n")
854
+ return ExitCode.ACCEPTED
855
+
856
+ if args.command == "heal":
857
+ target_repo = pathlib.Path(args.repo).resolve()
858
+ if not target_repo.is_dir():
859
+ sys.stderr.write(f"patchproof: error: target directory not found: {args.repo}\n")
860
+ return ExitCode.CLI_ERROR
861
+
862
+ if args.git:
863
+ try:
864
+ heal_patch_content = get_uncommitted_diff(target_repo)
865
+ except NoChangesDetectedError:
866
+ sys.stdout.write("patchproof: working tree is clean; nothing to heal.\n")
867
+ return ExitCode.ACCEPTED
868
+ except GitRepositoryError as err:
869
+ sys.stderr.write(f"patchproof: error: {err}\n")
870
+ return ExitCode.CLI_ERROR
871
+ elif args.patch:
872
+ p_file = pathlib.Path(args.patch)
873
+ if not p_file.is_file():
874
+ sys.stderr.write(f"patchproof: error: patch file not found: {args.patch}\n")
875
+ return ExitCode.CLI_ERROR
876
+ heal_patch_content = p_file.read_text(encoding="utf-8")
877
+ else:
878
+ sys.stderr.write("patchproof: error: specify patch file or --git for heal\n")
879
+ return ExitCode.CLI_ERROR
880
+
881
+ project_profile = detect_project_stack(target_repo)
882
+ resolved_image: str
883
+ if args.image is not None:
884
+ resolved_image = args.image
885
+ elif project_profile.default_image is not None:
886
+ resolved_image = project_profile.default_image
887
+ else:
888
+ sys.stderr.write(
889
+ f"patchproof: error: healing for {project_profile.kind.value} projects "
890
+ "requires --image <runner-image> "
891
+ "(no default container image is bundled in v0.3.0)\n"
892
+ )
893
+ return ExitCode.CLI_ERROR
894
+
895
+ cfg = ContainerConfig(
896
+ host_repo_path=str(target_repo),
897
+ image=resolved_image,
898
+ entrypoint_command=project_profile.default_test_command,
899
+ )
900
+ healer = AutonomousHealer()
901
+
902
+ def default_callback(report: AISelfHealingReport) -> str | None:
903
+ sys.stderr.write(report.prompt_feedback + "\n")
904
+ return None
905
+
906
+ heal_res = healer.heal(
907
+ cfg,
908
+ heal_patch_content,
909
+ repair_agent_fn=default_callback,
910
+ max_iterations=args.max_iterations,
911
+ )
912
+ if heal_res.success:
913
+ sys.stdout.write(f"patchproof: {heal_res.summary}\n")
914
+ return ExitCode.ACCEPTED
915
+ else:
916
+ sys.stderr.write(f"patchproof: {heal_res.summary}\n")
917
+ return ExitCode.REJECTED
918
+
919
+ if args.command == "factory":
920
+ if args.factory_action == "evaluate":
921
+ target_repo = pathlib.Path(args.repo).resolve()
922
+ eval_patch: str
923
+ if args.git:
924
+ try:
925
+ eval_patch = get_uncommitted_diff(target_repo)
926
+ except NoChangesDetectedError:
927
+ sys.stdout.write("patchproof: working tree is clean; no changes to evaluate.\n")
928
+ return ExitCode.ACCEPTED
929
+ except GitRepositoryError as err:
930
+ sys.stderr.write(f"patchproof: error: {err}\n")
931
+ return ExitCode.CLI_ERROR
932
+ elif args.head:
933
+ try:
934
+ eval_patch = get_head_diff(target_repo)
935
+ except NoChangesDetectedError:
936
+ sys.stdout.write("patchproof: HEAD commit introduces no diff changes.\n")
937
+ return ExitCode.ACCEPTED
938
+ except GitRepositoryError as err:
939
+ sys.stderr.write(f"patchproof: error: {err}\n")
940
+ return ExitCode.CLI_ERROR
941
+ elif args.patch == "-":
942
+ eval_patch = sys.stdin.read()
943
+ elif args.patch:
944
+ p_file = pathlib.Path(args.patch)
945
+ if not p_file.is_file():
946
+ sys.stderr.write(f"patchproof: error: patch file not found: {args.patch}\n")
947
+ return ExitCode.CLI_ERROR
948
+ eval_patch = p_file.read_text(encoding="utf-8")
949
+ else:
950
+ sys.stderr.write("patchproof: error: must specify patch file, --git, or --head\n")
951
+ return ExitCode.CLI_ERROR
952
+
953
+ classifier = BlastRadiusClassifier()
954
+ report = classifier.assess_patch(eval_patch)
955
+
956
+ if args.json:
957
+ sys.stdout.write(report.model_dump_json(indent=2) + "\n")
958
+ else:
959
+ lineage_label = (
960
+ "Lineage A (Contained / Level 4)"
961
+ if report.lineage == FactoryLineage.LINEAGE_A
962
+ else "Lineage B (Breaking / Level 3)"
963
+ )
964
+ sys.stdout.write(
965
+ f"patchproof factory: Blast Radius Assessment\n"
966
+ f" Risk Level: {report.risk_level.value.upper()}\n"
967
+ f" Routing: {lineage_label}\n"
968
+ f" Contained: {report.is_contained}\n"
969
+ f" Rationale: {report.rationale}\n"
970
+ )
971
+ return ExitCode.ACCEPTED
972
+
973
+ if args.factory_action == "run":
974
+ target_repo = pathlib.Path(args.repo).resolve()
975
+ engine = FactoryEngine(max_retries=args.max_retries)
976
+
977
+ candidate_patch = ""
978
+ if args.patch:
979
+ p_path = pathlib.Path(args.patch)
980
+ if p_path.is_file():
981
+ candidate_patch = p_path.read_text(encoding="utf-8")
982
+
983
+ def generator(_: str | None) -> str:
984
+ if candidate_patch:
985
+ return candidate_patch
986
+ try:
987
+ return get_uncommitted_diff(target_repo)
988
+ except Exception:
989
+ return ""
990
+
991
+ def gate(patch_str: str) -> GateResult:
992
+ if not patch_str.strip():
993
+ return GateResult(passed=False, diagnostics="Empty patch content")
994
+ return GateResult(passed=True, diagnostics="")
995
+
996
+ res = engine.run(
997
+ run_id=f"run-{abs(hash(args.trigger)) % 100000}",
998
+ generator_fn=generator,
999
+ gate_fn=gate,
1000
+ )
1001
+
1002
+ if args.json:
1003
+ sys.stdout.write(res.model_dump_json(indent=2) + "\n")
1004
+ else:
1005
+ sys.stdout.write(
1006
+ f"patchproof factory: Run Completed\n"
1007
+ f" Run ID: {res.run_id}\n"
1008
+ f" Status: {res.status.value}\n"
1009
+ f" Lineage: {res.lineage.value}\n"
1010
+ f" Shipped: {res.shipped_to_production}\n"
1011
+ f" Needs Operator Approval: {res.operator_approval_required}\n"
1012
+ )
1013
+
1014
+ return (
1015
+ ExitCode.ACCEPTED
1016
+ if res.status == HybridLoopState.PASSED
1017
+ else ExitCode.REJECTED
1018
+ )
1019
+
1020
+ if args.command != "verify":
1021
+ sys.stderr.write(f"patchproof: unknown command: {args.command}\n")
1022
+ return ExitCode.CLI_ERROR
1023
+
1024
+ # 1. Validate host repo directory
1025
+ repo_path = pathlib.Path(args.repo).resolve()
1026
+ if not repo_path.is_dir():
1027
+ sys.stderr.write(f"patchproof: error: target repo directory not found: {args.repo}\n")
1028
+ return ExitCode.CLI_ERROR
1029
+
1030
+ # 2. Validate input source (mutually exclusive)
1031
+ inputs_count = sum([bool(args.patch), bool(args.git), bool(args.head)])
1032
+ if inputs_count == 0:
1033
+ sys.stderr.write("patchproof: error: must specify patch file, --git, or --head\n")
1034
+ return ExitCode.CLI_ERROR
1035
+ if inputs_count > 1:
1036
+ sys.stderr.write("patchproof: error: specify only one of patch file, --git, or --head\n")
1037
+ return ExitCode.CLI_ERROR
1038
+
1039
+ # 3. Read patch content
1040
+ patch_content: str
1041
+ if args.git:
1042
+ try:
1043
+ patch_content = get_uncommitted_diff(repo_path)
1044
+ except NoChangesDetectedError:
1045
+ sys.stdout.write("patchproof: working tree clean; no uncommitted changes to verify.\n")
1046
+ return ExitCode.ACCEPTED
1047
+ except GitRepositoryError as err:
1048
+ sys.stderr.write(f"patchproof: error: {err}\n")
1049
+ return ExitCode.CLI_ERROR
1050
+ elif args.head:
1051
+ try:
1052
+ patch_content = get_head_diff(repo_path)
1053
+ except NoChangesDetectedError:
1054
+ sys.stdout.write("patchproof: HEAD commit introduces no diff changes.\n")
1055
+ return ExitCode.ACCEPTED
1056
+ except GitRepositoryError as err:
1057
+ sys.stderr.write(f"patchproof: error: {err}\n")
1058
+ return ExitCode.CLI_ERROR
1059
+ elif args.patch == "-":
1060
+ if sys.stdin.isatty():
1061
+ sys.stderr.write(
1062
+ "patchproof: reading patch from stdin (press Ctrl+D / Ctrl+Z to finish)...\n"
1063
+ )
1064
+ patch_content = sys.stdin.read()
1065
+ else:
1066
+ patch_path = pathlib.Path(args.patch)
1067
+ if not patch_path.is_file():
1068
+ sys.stderr.write(f"patchproof: error: patch file not found: {args.patch}\n")
1069
+ return ExitCode.CLI_ERROR
1070
+ try:
1071
+ patch_content = patch_path.read_text(encoding="utf-8")
1072
+ except (OSError, UnicodeDecodeError) as err:
1073
+ sys.stderr.write(f"patchproof: error: failed to read patch file: {err}\n")
1074
+ return ExitCode.CLI_ERROR
1075
+
1076
+ # 4. Validate timeout
1077
+ if args.timeout <= 0.0 or args.timeout > 300.0:
1078
+ sys.stderr.write(
1079
+ f"patchproof: error: timeout must be between 0.1 and 300.0s, got {args.timeout}\n"
1080
+ )
1081
+ return ExitCode.CLI_ERROR
1082
+
1083
+ # 3.5. Project auto-detection & command construction
1084
+ project_profile = detect_project_stack(repo_path)
1085
+ if args.image is not None:
1086
+ resolved_image = args.image
1087
+ elif project_profile.default_image is not None:
1088
+ resolved_image = project_profile.default_image
1089
+ else:
1090
+ sys.stderr.write(
1091
+ f"patchproof: error: verification for {project_profile.kind.value} projects "
1092
+ f"requires --image <runner-image> (no default container image is bundled in v0.3.0)\n"
1093
+ )
1094
+ return ExitCode.CLI_ERROR
1095
+
1096
+ entrypoint_cmd: tuple[str, ...]
1097
+ if args.test_command is not None:
1098
+ try:
1099
+ entrypoint_cmd = parse_test_command(args.test_command)
1100
+ except SandboxSecurityError as err:
1101
+ sys.stderr.write(f"patchproof: error: invalid test command: {err}\n")
1102
+ return ExitCode.CLI_ERROR
1103
+ else:
1104
+ entrypoint_cmd = project_profile.default_test_command
1105
+
1106
+ # 3.8. Predictive Test Slicing
1107
+ if args.slice_tests and args.test_command is None:
1108
+ try:
1109
+ can_p = parse_patch(patch_content)
1110
+ slice_res = slice_test_suite(repo_path, can_p)
1111
+ if not slice_res.is_full_suite_fallback and slice_res.selected_test_paths:
1112
+ entrypoint_cmd = (entrypoint_cmd[0], "-q", *slice_res.selected_test_paths)
1113
+ if not args.json:
1114
+ count_tests = len(slice_res.selected_test_paths)
1115
+ sys.stderr.write(
1116
+ f"patchproof: predictive test slicing isolated {count_tests} "
1117
+ f"test file(s) in {slice_res.duration_ms:.1f}ms\n"
1118
+ )
1119
+ except Exception:
1120
+ pass
1121
+
1122
+ # 4. Construct configuration
1123
+ try:
1124
+ config = ContainerConfig(
1125
+ host_repo_path=str(repo_path),
1126
+ image=resolved_image,
1127
+ resources=ResourceLimits(timeout_seconds=args.timeout),
1128
+ entrypoint_command=entrypoint_cmd,
1129
+ )
1130
+ except Exception as err:
1131
+ sys.stderr.write(f"patchproof: error: configuration error: {err}\n")
1132
+ return ExitCode.CLI_ERROR
1133
+
1134
+ # 5. Execute comparative verification
1135
+ runner = ComparativeRunner()
1136
+ try:
1137
+ result = runner.run(
1138
+ config,
1139
+ patch_content,
1140
+ disambiguate_flakes=args.disambiguate_flakes,
1141
+ allow_test_edits=args.allow_test_edits,
1142
+ )
1143
+ except SandboxSecurityError as err:
1144
+ sys.stderr.write(f"patchproof: security error: {err}\n")
1145
+ return ExitCode.REJECTED
1146
+ except (DockerUnavailableError, UnsupportedDockerEngineError) as err:
1147
+ sys.stderr.write(f"patchproof: infrastructure error: {err}\n")
1148
+ return ExitCode.INFRASTRUCTURE_FAILURE
1149
+ except Exception as err:
1150
+ sys.stderr.write(f"patchproof: execution error: {err}\n")
1151
+ return ExitCode.CLI_ERROR
1152
+
1153
+ # 6. Render output
1154
+ if args.html:
1155
+ html_path = pathlib.Path(args.html)
1156
+ try:
1157
+ html_content = generate_html_report(result, patch_content=patch_content)
1158
+ html_path.write_text(html_content, encoding="utf-8")
1159
+ except OSError as err:
1160
+ sys.stderr.write(f"patchproof: error: failed to write HTML report: {err}\n")
1161
+
1162
+ if args.ai_feedback and result.verdict != PatchVerdict.ACCEPTED:
1163
+ canonical_p: CanonicalPatch | None = None
1164
+ if patch_content:
1165
+ try:
1166
+ canonical_p = parse_patch(patch_content)
1167
+ except Exception:
1168
+ pass
1169
+ ai_diag = generate_ai_feedback(result, patch=canonical_p)
1170
+ sys.stderr.write(ai_diag.prompt_feedback + "\n")
1171
+
1172
+ cert_obj: ProofCertificate | None = None
1173
+ if args.cert:
1174
+ cert_out = pathlib.Path(args.cert)
1175
+ try:
1176
+ signing_key_pem: str | None = None
1177
+ if args.private_key:
1178
+ pk_path = pathlib.Path(args.private_key)
1179
+ if pk_path.is_file():
1180
+ signing_key_pem = pk_path.read_text(encoding="utf-8")
1181
+ else:
1182
+ sys.stderr.write(
1183
+ f"patchproof: warning: private key file not found: {args.private_key}\n"
1184
+ )
1185
+ cert_obj = generate_certificate(
1186
+ result,
1187
+ patch_content=patch_content,
1188
+ secret_key=args.secret_key,
1189
+ private_key_pem=signing_key_pem,
1190
+ signer_identity=args.signer_identity,
1191
+ )
1192
+ export_certificate(cert_obj, cert_out)
1193
+ if not args.json:
1194
+ sys.stdout.write(f"patchproof: Proof-of-Patch certificate written to {cert_out}\n")
1195
+ except Exception as err:
1196
+ sys.stderr.write(f"patchproof: error: failed to write certificate: {err}\n")
1197
+
1198
+ if getattr(args, "in_toto", None):
1199
+ in_toto_out = pathlib.Path(args.in_toto)
1200
+ try:
1201
+ signing_key_pem = None
1202
+ if args.private_key:
1203
+ pk_path = pathlib.Path(args.private_key)
1204
+ if pk_path.is_file():
1205
+ signing_key_pem = pk_path.read_text(encoding="utf-8")
1206
+ if not cert_obj:
1207
+ cert_obj = generate_certificate(
1208
+ result,
1209
+ patch_content=patch_content,
1210
+ secret_key=args.secret_key,
1211
+ private_key_pem=signing_key_pem,
1212
+ signer_identity=args.signer_identity,
1213
+ )
1214
+ stmt = build_in_toto_statement(cert_obj, result, patch_content=patch_content)
1215
+ if signing_key_pem:
1216
+ env = build_dsse_envelope(stmt, signing_key_pem, key_id=args.signer_identity)
1217
+ in_toto_out.write_text(json.dumps(env, indent=2), encoding="utf-8")
1218
+ else:
1219
+ in_toto_out.write_text(json.dumps(stmt, indent=2), encoding="utf-8")
1220
+ if not args.json:
1221
+ sys.stdout.write(f"patchproof: in-toto attestation written to {in_toto_out}\n")
1222
+ except Exception as err:
1223
+ sys.stderr.write(f"patchproof: error: failed to write in-toto attestation: {err}\n")
1224
+
1225
+ if args.markdown:
1226
+ md_out = pathlib.Path(args.markdown)
1227
+ try:
1228
+ md_content = generate_markdown_summary(
1229
+ result, cert=cert_obj, patch_content=patch_content
1230
+ )
1231
+ md_out.parent.mkdir(parents=True, exist_ok=True)
1232
+ md_out.write_text(md_content, encoding="utf-8")
1233
+ if not args.json:
1234
+ sys.stdout.write(f"patchproof: Markdown summary card written to {md_out}\n")
1235
+ except OSError as err:
1236
+ sys.stderr.write(f"patchproof: error: failed to write Markdown summary: {err}\n")
1237
+
1238
+ if args.badge:
1239
+ badge_out = pathlib.Path(args.badge)
1240
+ try:
1241
+ badge_content = generate_svg_badge(result)
1242
+ badge_out.parent.mkdir(parents=True, exist_ok=True)
1243
+ badge_out.write_text(badge_content, encoding="utf-8")
1244
+ if not args.json:
1245
+ sys.stdout.write(f"patchproof: SVG badge written to {badge_out}\n")
1246
+ except OSError as err:
1247
+ sys.stderr.write(f"patchproof: error: failed to write SVG badge: {err}\n")
1248
+
1249
+ if args.json:
1250
+ sys.stdout.write(format_json_report(result, patch_content=patch_content) + "\n")
1251
+ else:
1252
+ sys.stdout.write(format_terminal_report(result, verbose=args.verbose) + "\n")
1253
+
1254
+ return VERDICT_EXIT_CODES.get(result.verdict, ExitCode.CLI_ERROR)