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,75 @@
1
+ """Data models for PatchProof AI Software Factory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import StrEnum
6
+
7
+ from pydantic import BaseModel, ConfigDict, Field
8
+
9
+
10
+ class RiskLevel(StrEnum):
11
+ """Blast radius risk classification."""
12
+
13
+ LOW = "low"
14
+ HIGH = "high"
15
+
16
+
17
+ class FactoryLineage(StrEnum):
18
+ """Lineage routing through the AI Software Factory."""
19
+
20
+ LINEAGE_A = "lineage_a" # Level 4: Contained, autonomous ship to production
21
+ LINEAGE_B = "lineage_b" # Level 3: Breaking, ephemeral sandbox with operator gate
22
+
23
+
24
+ class HybridLoopState(StrEnum):
25
+ """Lifecycle state of an iteration within the factory hybrid loop."""
26
+
27
+ INIT = "init"
28
+ EVALUATING = "evaluating"
29
+ RETRYING = "retrying"
30
+ PASSED = "passed"
31
+ FAILED = "failed"
32
+ EXCEPTION_QUEUED = "exception_queued"
33
+
34
+
35
+ class BlastRadiusReport(BaseModel):
36
+ """Assessment report determining blast radius and lineage routing."""
37
+
38
+ model_config = ConfigDict(frozen=True)
39
+
40
+ risk_level: RiskLevel = Field(description="Calculated risk severity")
41
+ lineage: FactoryLineage = Field(description="Assigned factory lineage")
42
+ is_contained: bool = Field(description="True if change cannot compromise boundaries")
43
+ touched_files: tuple[str, ...] = Field(
44
+ default_factory=tuple, description="All altered file paths"
45
+ )
46
+ core_files_touched: tuple[str, ...] = Field(
47
+ default_factory=tuple, description="Sensitive core files altered"
48
+ )
49
+ rationale: str = Field(description="Explanation of routing decision")
50
+ confidence_score: float = Field(default=1.0, description="Confidence in assessment")
51
+
52
+
53
+ class FactoryRunResult(BaseModel):
54
+ """Outcome of an end-to-end factory lineage execution."""
55
+
56
+ model_config = ConfigDict(frozen=True)
57
+
58
+ run_id: str = Field(description="Unique run execution identifier")
59
+ lineage: FactoryLineage = Field(description="Executed lineage")
60
+ status: HybridLoopState = Field(description="Final terminal state")
61
+ iterations: int = Field(description="Number of feedback loop attempts")
62
+ blast_radius: BlastRadiusReport = Field(description="Input blast radius assessment")
63
+ provenance_signature: str | None = Field(
64
+ default=None, description="Ed25519 signature of verified patch"
65
+ )
66
+ provenance_key: str | None = Field(default=None, description="Ed25519 public key")
67
+ diagnostic_message: str = Field(
68
+ default="", description="Detailed error diagnostics if failed"
69
+ )
70
+ shipped_to_production: bool = Field(
71
+ default=False, description="True if autonomously merged/deployed"
72
+ )
73
+ operator_approval_required: bool = Field(
74
+ default=False, description="True if awaiting human sign-off"
75
+ )
patchproof/mcp.py ADDED
@@ -0,0 +1,532 @@
1
+ """Built-in Model Context Protocol (MCP) server for PatchProof.
2
+
3
+ Exposes deterministic code patch verification to AI agents (Antigravity, Cursor, Claude Code).
4
+ Runs over standard I/O using JSON-RPC 2.0.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import logging
11
+ import pathlib
12
+ import sys
13
+ from typing import Any
14
+
15
+ from patchproof.core.git_provider import get_head_diff, get_uncommitted_diff
16
+ from patchproof.core.healer import AutonomousHealer
17
+ from patchproof.core.normalizer import parse_patch
18
+ from patchproof.core.slicer import slice_test_suite
19
+ from patchproof.exceptions import (
20
+ GitRepositoryError,
21
+ NoChangesDetectedError,
22
+ SandboxSecurityError,
23
+ )
24
+ from patchproof.models.patch import CanonicalPatch
25
+ from patchproof.models.sandbox import (
26
+ ComparativeExecutionResult,
27
+ ContainerConfig,
28
+ PatchVerdict,
29
+ ResourceLimits,
30
+ )
31
+ from patchproof.reporting.certificate import generate_certificate
32
+ from patchproof.reporting.diagnostic import AISelfHealingReport, generate_ai_feedback
33
+ from patchproof.sandbox.comparative import ComparativeRunner
34
+ from patchproof.sandbox.docker_cli import parse_test_command
35
+ from patchproof.sandbox.doctor import SystemDoctor
36
+ from patchproof.sandbox.setup_runner import DEFAULT_RUNNER_TAG
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ PROTOCOL_VERSION = "2024-11-05"
41
+
42
+ TOOLS_DEFINITIONS: list[dict[str, Any]] = [
43
+ {
44
+ "name": "patchproof_verify_patch",
45
+ "description": (
46
+ "Verify a code patch (unified diff or SEARCH/REPLACE format) against the test suite "
47
+ "in an isolated, zero-network Docker sandbox. Returns baseline vs patched test results "
48
+ "and regression classification (ACCEPTED / REJECTED)."
49
+ ),
50
+ "inputSchema": {
51
+ "type": "object",
52
+ "properties": {
53
+ "patch": {
54
+ "type": "string",
55
+ "description": "Unified diff or SEARCH/REPLACE patch content to verify.",
56
+ },
57
+ "repo": {
58
+ "type": "string",
59
+ "description": "Path to target repository on host (default: .).",
60
+ "default": ".",
61
+ },
62
+ "test_command": {
63
+ "type": "string",
64
+ "description": "Custom test execution command (e.g. 'pytest tests/unit/ -q').",
65
+ },
66
+ "timeout": {
67
+ "type": "number",
68
+ "description": "Per-run execution timeout in seconds (default: 15.0).",
69
+ "default": 15.0,
70
+ },
71
+ "image": {
72
+ "type": "string",
73
+ "description": f"Runner Docker image (default: {DEFAULT_RUNNER_TAG}).",
74
+ "default": DEFAULT_RUNNER_TAG,
75
+ },
76
+ "allow_test_edits": {
77
+ "type": "boolean",
78
+ "description": "Allow test modifications without triggering anti-cheat alerts.",
79
+ "default": False,
80
+ },
81
+ },
82
+ "required": ["patch"],
83
+ },
84
+ },
85
+ {
86
+ "name": "patchproof_verify_git",
87
+ "description": (
88
+ "Verify uncommitted working tree changes or latest HEAD commit in a Git repository "
89
+ "in an isolated Docker sandbox. Returns comparative regression analysis."
90
+ ),
91
+ "inputSchema": {
92
+ "type": "object",
93
+ "properties": {
94
+ "repo": {
95
+ "type": "string",
96
+ "description": "Path to target Git repository (default: current directory).",
97
+ "default": ".",
98
+ },
99
+ "target": {
100
+ "type": "string",
101
+ "enum": ["uncommitted", "head"],
102
+ "description": (
103
+ "What to verify: 'uncommitted' (working tree changes) or 'head' "
104
+ "(latest commit). Default: 'uncommitted'."
105
+ ),
106
+ "default": "uncommitted",
107
+ },
108
+ "test_command": {
109
+ "type": "string",
110
+ "description": "Custom test execution command (e.g. 'pytest tests/unit/ -q').",
111
+ },
112
+ "timeout": {
113
+ "type": "number",
114
+ "description": "Per-run execution timeout in seconds (default: 15.0).",
115
+ "default": 15.0,
116
+ },
117
+ },
118
+ },
119
+ },
120
+ {
121
+ "name": "patchproof_doctor",
122
+ "description": (
123
+ "Diagnose host system prerequisites (Python version, Docker daemon availability, "
124
+ "Linux container mode, runner image readiness) and return actionable recovery guidance."
125
+ ),
126
+ "inputSchema": {
127
+ "type": "object",
128
+ "properties": {},
129
+ },
130
+ },
131
+ {
132
+ "name": "patchproof_heal",
133
+ "description": (
134
+ "Run autonomous verification and self-healing convergence loop on a patch or Git repo. "
135
+ "Returns iterative diagnosis, pinpoint fault localization, and convergence status."
136
+ ),
137
+ "inputSchema": {
138
+ "type": "object",
139
+ "properties": {
140
+ "patch": {
141
+ "type": "string",
142
+ "description": "Unified diff or patch to heal (default: uncommitted changes).",
143
+ },
144
+ "repo": {
145
+ "type": "string",
146
+ "description": "Path to target repository on host (default: .).",
147
+ "default": ".",
148
+ },
149
+ "test_command": {
150
+ "type": "string",
151
+ "description": "Custom test execution command (e.g. 'pytest -q').",
152
+ },
153
+ "max_iterations": {
154
+ "type": "integer",
155
+ "description": "Maximum healing convergence turns (default: 3).",
156
+ "default": 3,
157
+ },
158
+ "timeout": {
159
+ "type": "number",
160
+ "description": "Execution timeout per run in seconds (default: 15.0).",
161
+ "default": 15.0,
162
+ },
163
+ },
164
+ },
165
+ },
166
+ ]
167
+
168
+
169
+ def _format_result_json(result: ComparativeExecutionResult, patch_content: str = "") -> str:
170
+ """Format comparative result as machine-readable JSON with AI feedback diagnostics."""
171
+ canonical_patch: CanonicalPatch | None = None
172
+ if patch_content:
173
+ try:
174
+ canonical_patch = parse_patch(patch_content)
175
+ except Exception:
176
+ pass
177
+
178
+ ai_report = generate_ai_feedback(result, patch=canonical_patch)
179
+
180
+ report = {
181
+ "verdict": result.verdict.value,
182
+ "summary": result.summary,
183
+ "ai_feedback": ai_report.to_dict(),
184
+ "counts": {
185
+ "introduced_regressions": result.introduced_regressions_count,
186
+ "flaky_tests": result.flaky_tests_count,
187
+ "resolved_defects": result.resolved_defects_count,
188
+ "suppressed_tests": result.suppressed_tests_count,
189
+ "pre_existing_failures": result.pre_existing_failures_count,
190
+ },
191
+ "baseline": {
192
+ "exit_code": result.baseline_result.exit_code,
193
+ "duration_seconds": result.baseline_result.duration_seconds,
194
+ "failure_reason": result.baseline_result.failure_reason.value,
195
+ },
196
+ "patched": {
197
+ "exit_code": result.patched_result.exit_code,
198
+ "duration_seconds": result.patched_result.duration_seconds,
199
+ "failure_reason": result.patched_result.failure_reason.value,
200
+ },
201
+ "comparisons": [
202
+ {
203
+ "test_name": c.test_name,
204
+ "baseline_outcome": (c.baseline_outcome.value if c.baseline_outcome else None),
205
+ "patched_outcome": (c.patched_outcome.value if c.patched_outcome else None),
206
+ "classification": c.classification.value,
207
+ }
208
+ for c in result.test_comparisons
209
+ ],
210
+ }
211
+ if result.verdict == PatchVerdict.ACCEPTED:
212
+ try:
213
+ cert = generate_certificate(result, patch_content=patch_content)
214
+ report["proof_certificate"] = cert.to_dict()
215
+ except Exception:
216
+ pass
217
+ return json.dumps(report, indent=2)
218
+
219
+
220
+ def handle_verify_patch_tool(arguments: dict[str, Any]) -> dict[str, Any]:
221
+ """Execute patchproof_verify_patch tool."""
222
+ patch_content = arguments.get("patch", "")
223
+ repo = arguments.get("repo", ".")
224
+ image = arguments.get("image", DEFAULT_RUNNER_TAG)
225
+ timeout = float(arguments.get("timeout", 15.0))
226
+ test_cmd_str = arguments.get("test_command")
227
+ slice_tests = bool(arguments.get("slice", False))
228
+ disambiguate_flakes = bool(arguments.get("disambiguate_flakes", False))
229
+
230
+ entrypoint_cmd: tuple[str, ...] = ("pytest", "-q")
231
+ if test_cmd_str:
232
+ try:
233
+ entrypoint_cmd = parse_test_command(test_cmd_str)
234
+ except SandboxSecurityError as err:
235
+ return {
236
+ "isError": True,
237
+ "content": [{"type": "text", "text": f"Invalid test command: {err}"}],
238
+ }
239
+ elif slice_tests:
240
+ try:
241
+ can_p = parse_patch(patch_content)
242
+ slice_res = slice_test_suite(pathlib.Path(repo).resolve(), can_p)
243
+ if not slice_res.is_full_suite_fallback and slice_res.selected_test_paths:
244
+ entrypoint_cmd = ("pytest", "-q", *slice_res.selected_test_paths)
245
+ except Exception:
246
+ pass
247
+
248
+ repo_path = pathlib.Path(repo).resolve()
249
+ if not repo_path.is_dir():
250
+ return {
251
+ "isError": True,
252
+ "content": [{"type": "text", "text": f"Repository directory not found: {repo}"}],
253
+ }
254
+
255
+ try:
256
+ config = ContainerConfig(
257
+ host_repo_path=str(repo_path),
258
+ image=image,
259
+ resources=ResourceLimits(timeout_seconds=timeout),
260
+ entrypoint_command=entrypoint_cmd,
261
+ )
262
+ except Exception as err:
263
+ return {
264
+ "isError": True,
265
+ "content": [{"type": "text", "text": f"Configuration error: {err}"}],
266
+ }
267
+
268
+ runner = ComparativeRunner()
269
+ allow_test_edits = bool(arguments.get("allow_test_edits", False))
270
+ try:
271
+ res = runner.run(
272
+ config,
273
+ patch_content,
274
+ disambiguate_flakes=disambiguate_flakes,
275
+ allow_test_edits=allow_test_edits,
276
+ )
277
+ return {
278
+ "content": [
279
+ {
280
+ "type": "text",
281
+ "text": _format_result_json(res, patch_content=patch_content),
282
+ }
283
+ ],
284
+ }
285
+ except Exception as err:
286
+ return {
287
+ "isError": True,
288
+ "content": [{"type": "text", "text": f"Execution error: {err}"}],
289
+ }
290
+
291
+
292
+ def handle_verify_git_tool(arguments: dict[str, Any]) -> dict[str, Any]:
293
+ """Execute patchproof_verify_git tool."""
294
+ repo = arguments.get("repo", ".")
295
+ target = arguments.get("target", "uncommitted")
296
+ repo_path = pathlib.Path(repo).resolve()
297
+
298
+ if not repo_path.is_dir():
299
+ return {
300
+ "isError": True,
301
+ "content": [{"type": "text", "text": f"Repository directory not found: {repo}"}],
302
+ }
303
+
304
+ try:
305
+ if target == "head":
306
+ patch_content = get_head_diff(repo_path)
307
+ else:
308
+ patch_content = get_uncommitted_diff(repo_path)
309
+ except NoChangesDetectedError:
310
+ clean_msg = {"verdict": "accepted", "summary": "Working tree is clean; no changes."}
311
+ return {
312
+ "content": [
313
+ {
314
+ "type": "text",
315
+ "text": json.dumps(clean_msg, indent=2),
316
+ }
317
+ ],
318
+ }
319
+ except GitRepositoryError as err:
320
+ return {
321
+ "isError": True,
322
+ "content": [{"type": "text", "text": f"Git error: {err}"}],
323
+ }
324
+
325
+ # Delegate to verify_patch
326
+ forwarded_args = dict(arguments)
327
+ forwarded_args["patch"] = patch_content
328
+ return handle_verify_patch_tool(forwarded_args)
329
+
330
+
331
+ def handle_doctor_tool(arguments: dict[str, Any]) -> dict[str, Any]:
332
+ """Execute patchproof_doctor tool."""
333
+ doctor = SystemDoctor(timeout_seconds=5.0)
334
+ results = doctor.run_all_checks()
335
+ all_passed = all(r.passed for r in results)
336
+
337
+ checks_data = [
338
+ {
339
+ "name": r.name,
340
+ "passed": r.passed,
341
+ "details": r.details,
342
+ "remediation": r.remediation,
343
+ }
344
+ for r in results
345
+ ]
346
+
347
+ report = {
348
+ "all_passed": all_passed,
349
+ "checks": checks_data,
350
+ }
351
+ return {
352
+ "content": [{"type": "text", "text": json.dumps(report, indent=2)}],
353
+ }
354
+
355
+
356
+ def handle_heal_tool(arguments: dict[str, Any]) -> dict[str, Any]:
357
+ """Execute patchproof_heal tool."""
358
+ repo = arguments.get("repo", ".")
359
+ repo_path = pathlib.Path(repo).resolve()
360
+ patch_content = arguments.get("patch", "")
361
+ max_iter = int(arguments.get("max_iterations", 3))
362
+ timeout = float(arguments.get("timeout", 15.0))
363
+ test_cmd_str = arguments.get("test_command")
364
+
365
+ if not patch_content:
366
+ try:
367
+ patch_content = get_uncommitted_diff(repo_path)
368
+ except Exception as err:
369
+ return {
370
+ "isError": True,
371
+ "content": [{"type": "text", "text": f"Failed reading changes: {err}"}],
372
+ }
373
+
374
+ entrypoint_cmd: tuple[str, ...] = ("pytest", "-q")
375
+ if test_cmd_str:
376
+ try:
377
+ entrypoint_cmd = parse_test_command(test_cmd_str)
378
+ except SandboxSecurityError as err:
379
+ return {
380
+ "isError": True,
381
+ "content": [{"type": "text", "text": f"Invalid test command: {err}"}],
382
+ }
383
+
384
+ config = ContainerConfig(
385
+ host_repo_path=str(repo_path),
386
+ resources=ResourceLimits(timeout_seconds=timeout),
387
+ entrypoint_command=entrypoint_cmd,
388
+ )
389
+
390
+ healer = AutonomousHealer()
391
+
392
+ def default_repair_cb(report: AISelfHealingReport) -> str | None:
393
+ return None
394
+
395
+ heal_res = healer.heal(
396
+ config,
397
+ patch_content,
398
+ repair_agent_fn=default_repair_cb,
399
+ max_iterations=max_iter,
400
+ )
401
+
402
+ last_verdict = "unknown"
403
+ if heal_res.last_result and hasattr(heal_res.last_result, "verdict"):
404
+ v = heal_res.last_result.verdict
405
+ last_verdict = str(getattr(v, "value", v))
406
+
407
+ output = {
408
+ "success": heal_res.success,
409
+ "iterations": heal_res.iterations,
410
+ "summary": heal_res.summary,
411
+ "final_patch": heal_res.final_patch,
412
+ "last_verdict": last_verdict,
413
+ }
414
+ return {
415
+ "content": [{"type": "text", "text": json.dumps(output, indent=2)}],
416
+ }
417
+
418
+
419
+ class MCPServer:
420
+ """Zero-dependency JSON-RPC 2.0 Model Context Protocol (MCP) server."""
421
+
422
+ def __init__(self) -> None:
423
+ self.handlers = {
424
+ "patchproof_verify_patch": handle_verify_patch_tool,
425
+ "patchproof_verify_git": handle_verify_git_tool,
426
+ "patchproof_doctor": handle_doctor_tool,
427
+ "patchproof_heal": handle_heal_tool,
428
+ }
429
+
430
+ def process_request(self, req: dict[str, Any]) -> dict[str, Any] | None:
431
+ """Process incoming JSON-RPC request and return response dict (or None)."""
432
+ method = req.get("method")
433
+ msg_id = req.get("id")
434
+
435
+ if method == "notifications/initialized":
436
+ return None
437
+
438
+ if method == "initialize":
439
+ return {
440
+ "jsonrpc": "2.0",
441
+ "id": msg_id,
442
+ "result": {
443
+ "protocolVersion": PROTOCOL_VERSION,
444
+ "capabilities": {
445
+ "tools": {},
446
+ },
447
+ "serverInfo": {
448
+ "name": "patchproof",
449
+ "version": "0.1.0",
450
+ },
451
+ },
452
+ }
453
+
454
+ if method == "ping":
455
+ return {
456
+ "jsonrpc": "2.0",
457
+ "id": msg_id,
458
+ "result": {},
459
+ }
460
+
461
+ if method == "tools/list":
462
+ return {
463
+ "jsonrpc": "2.0",
464
+ "id": msg_id,
465
+ "result": {
466
+ "tools": TOOLS_DEFINITIONS,
467
+ },
468
+ }
469
+
470
+ if method == "tools/call":
471
+ params = req.get("params", {})
472
+ tool_name = params.get("name")
473
+ tool_args = params.get("arguments", {})
474
+
475
+ handler = self.handlers.get(tool_name)
476
+ if not handler:
477
+ return {
478
+ "jsonrpc": "2.0",
479
+ "id": msg_id,
480
+ "error": {
481
+ "code": -32601,
482
+ "message": f"Tool '{tool_name}' not found",
483
+ },
484
+ }
485
+
486
+ try:
487
+ res = handler(tool_args)
488
+ return {
489
+ "jsonrpc": "2.0",
490
+ "id": msg_id,
491
+ "result": res,
492
+ }
493
+ except Exception as err:
494
+ return {
495
+ "jsonrpc": "2.0",
496
+ "id": msg_id,
497
+ "result": {
498
+ "isError": True,
499
+ "content": [{"type": "text", "text": f"Tool error: {err}"}],
500
+ },
501
+ }
502
+
503
+ # Unknown method
504
+ return {
505
+ "jsonrpc": "2.0",
506
+ "id": msg_id,
507
+ "error": {
508
+ "code": -32601,
509
+ "message": f"Method '{method}' not found",
510
+ },
511
+ }
512
+
513
+ def run_stdio(self) -> None:
514
+ """Run JSON-RPC loop reading line-delimited messages from sys.stdin."""
515
+ for line in sys.stdin:
516
+ line = line.strip()
517
+ if not line:
518
+ continue
519
+ try:
520
+ req = json.loads(line)
521
+ res = self.process_request(req)
522
+ if res is not None:
523
+ sys.stdout.write(json.dumps(res) + "\n")
524
+ sys.stdout.flush()
525
+ except json.JSONDecodeError as err:
526
+ err_res = {
527
+ "jsonrpc": "2.0",
528
+ "id": None,
529
+ "error": {"code": -32700, "message": f"Parse error: {err}"},
530
+ }
531
+ sys.stdout.write(json.dumps(err_res) + "\n")
532
+ sys.stdout.flush()
@@ -0,0 +1,57 @@
1
+ """Domain models for PatchProof."""
2
+
3
+ from patchproof.models.ast import (
4
+ ASTAnalysisReport,
5
+ ASTEntity,
6
+ EntityType,
7
+ FileASTReport,
8
+ )
9
+ from patchproof.models.patch import (
10
+ CanonicalPatch,
11
+ ChangeType,
12
+ FileDelta,
13
+ PatchHunk,
14
+ PatchType,
15
+ )
16
+ from patchproof.models.sandbox import (
17
+ ComparativeExecutionResult,
18
+ ComparativeTestCase,
19
+ ContainerConfig,
20
+ ContainerEnvironment,
21
+ ExecutionResult,
22
+ NetworkMode,
23
+ PatchVerdict,
24
+ RegressionClassification,
25
+ ResourceLimits,
26
+ SandboxFailureReason,
27
+ SecurityPolicy,
28
+ TestCaseResult,
29
+ TestOutcome,
30
+ TestRunReport,
31
+ )
32
+
33
+ __all__ = [
34
+ "ASTAnalysisReport",
35
+ "ASTEntity",
36
+ "CanonicalPatch",
37
+ "ChangeType",
38
+ "ComparativeExecutionResult",
39
+ "ComparativeTestCase",
40
+ "ContainerConfig",
41
+ "ContainerEnvironment",
42
+ "EntityType",
43
+ "ExecutionResult",
44
+ "FileASTReport",
45
+ "FileDelta",
46
+ "NetworkMode",
47
+ "PatchHunk",
48
+ "PatchType",
49
+ "PatchVerdict",
50
+ "RegressionClassification",
51
+ "ResourceLimits",
52
+ "SandboxFailureReason",
53
+ "SecurityPolicy",
54
+ "TestCaseResult",
55
+ "TestOutcome",
56
+ "TestRunReport",
57
+ ]