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,424 @@
1
+ """ContainerRunner and lifecycle management subsystem for isolated container execution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import subprocess
8
+ import threading
9
+ import time
10
+ import uuid
11
+ from typing import IO, Any
12
+
13
+ from patchproof.exceptions import (
14
+ DockerUnavailableError,
15
+ SandboxSecurityError,
16
+ UnsupportedDockerEngineError,
17
+ )
18
+ from patchproof.models.sandbox import (
19
+ ContainerConfig,
20
+ ExecutionResult,
21
+ SandboxFailureReason,
22
+ )
23
+ from patchproof.sandbox.docker_cli import (
24
+ DockerCommandBuilder,
25
+ DockerPreflight,
26
+ )
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ DEFAULT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024 # 4 MB
31
+ KILL_TIMEOUT_SECONDS = 5.0
32
+ INSPECT_TIMEOUT_SECONDS = 5.0
33
+ CLEANUP_TIMEOUT_SECONDS = 5.0
34
+
35
+
36
+ def is_docker_available() -> bool:
37
+ """Check if Docker daemon is available and operating in Linux Containers mode."""
38
+ try:
39
+ DockerPreflight().check()
40
+ return True
41
+ except (DockerUnavailableError, UnsupportedDockerEngineError):
42
+ return False
43
+
44
+
45
+ class StreamCapture:
46
+ """Captures an output stream in memory up to a bounded size limit."""
47
+
48
+ def __init__(self, stream: IO[bytes] | None, max_bytes: int) -> None:
49
+ self.stream = stream
50
+ self.max_bytes = max_bytes
51
+ self.chunks: list[bytes] = []
52
+ self.total_bytes = 0
53
+ self.truncated = False
54
+ self.thread = threading.Thread(target=self._read_worker, daemon=True)
55
+
56
+ def start(self) -> None:
57
+ """Start reading the stream in a background daemon thread."""
58
+ self.thread.start()
59
+
60
+ def join(self, timeout: float = 2.0) -> None:
61
+ """Wait for the reader thread to finish reading."""
62
+ self.thread.join(timeout=timeout)
63
+
64
+ def _read_worker(self) -> None:
65
+ if self.stream is None:
66
+ return
67
+
68
+ chunk_size = 64 * 1024
69
+ try:
70
+ while True:
71
+ chunk = self.stream.read(chunk_size)
72
+ if not chunk:
73
+ break
74
+
75
+ if self.total_bytes + len(chunk) > self.max_bytes:
76
+ remaining = self.max_bytes - self.total_bytes
77
+ if remaining > 0:
78
+ self.chunks.append(chunk[:remaining])
79
+ self.total_bytes += remaining
80
+ self.truncated = True
81
+ # Drain remaining stream to prevent child process write deadlocks
82
+ while self.stream.read(chunk_size):
83
+ pass
84
+ break
85
+
86
+ self.chunks.append(chunk)
87
+ self.total_bytes += len(chunk)
88
+ except (ValueError, OSError):
89
+ pass
90
+
91
+ def get_output(self) -> str:
92
+ """Return the collected stream content decoded as UTF-8 string."""
93
+ raw = b"".join(self.chunks)
94
+ text = raw.decode("utf-8", errors="replace")
95
+ if self.truncated:
96
+ text += "\n[TRUNCATED: Output exceeded limit]"
97
+ return text
98
+
99
+
100
+ class ContainerRunner:
101
+ """Manages the lifecycle, execution, timeout, inspection, and cleanup of test containers."""
102
+
103
+ def __init__(
104
+ self,
105
+ max_output_bytes: int = DEFAULT_MAX_OUTPUT_BYTES,
106
+ preflight: DockerPreflight | None = None,
107
+ session_id: str | None = None,
108
+ ) -> None:
109
+ self.max_output_bytes = max_output_bytes
110
+ self.preflight = preflight or DockerPreflight()
111
+ self.session_id = session_id or uuid.uuid4().hex[:8]
112
+
113
+ def run(self, config: ContainerConfig) -> ExecutionResult:
114
+ """Execute a test container according to the given configuration and monitor lifecycle.
115
+
116
+ Raises:
117
+ DockerUnavailableError: If Docker daemon is unavailable or not Linux mode.
118
+ SandboxSecurityError: If container command security validation fails.
119
+ """
120
+ # 1. Preflight health verification (fail closed)
121
+ self.preflight.check()
122
+
123
+ # 2. Generate unique execution ID and container name
124
+ execution_id = uuid.uuid4().hex[:12]
125
+ container_name = f"patchproof-exec-{execution_id}"
126
+ timestamp = str(int(time.time()))
127
+
128
+ extra_labels = {
129
+ "patchproof.session_id": self.session_id,
130
+ "patchproof.timestamp": timestamp,
131
+ }
132
+
133
+ # 3. Deterministically build hardened Docker CLI command
134
+ # (without auto-remove to permit post-exit state inspection)
135
+ builder = DockerCommandBuilder(config)
136
+ cmd = builder.build(
137
+ container_name=container_name,
138
+ execution_id=execution_id,
139
+ auto_remove=False,
140
+ extra_labels=extra_labels,
141
+ )
142
+
143
+ timeout_seconds = config.resources.timeout_seconds
144
+ start_time = time.monotonic()
145
+ timeout_triggered = False
146
+ oom_killed = False
147
+ exit_code = -1
148
+ stdout_text = ""
149
+ stderr_text = ""
150
+
151
+ proc: subprocess.Popen[bytes] | None = None
152
+ stdout_capture: StreamCapture | None = None
153
+ stderr_capture: StreamCapture | None = None
154
+
155
+ try:
156
+ # 4. Spawn container process with close_fds=True and shell=False
157
+ proc = subprocess.Popen(
158
+ cmd,
159
+ stdout=subprocess.PIPE,
160
+ stderr=subprocess.PIPE,
161
+ shell=False,
162
+ close_fds=True,
163
+ )
164
+
165
+ stdout_capture = StreamCapture(proc.stdout, self.max_output_bytes)
166
+ stderr_capture = StreamCapture(proc.stderr, self.max_output_bytes)
167
+ stdout_capture.start()
168
+ stderr_capture.start()
169
+
170
+ # 5. Host-monitored execution loop
171
+ while True:
172
+ poll_res = proc.poll()
173
+ if poll_res is not None:
174
+ exit_code = poll_res
175
+ break
176
+
177
+ elapsed = time.monotonic() - start_time
178
+ if elapsed >= timeout_seconds:
179
+ timeout_triggered = True
180
+ self._kill_container(container_name)
181
+ try:
182
+ exit_code = proc.wait(timeout=2.0)
183
+ except subprocess.TimeoutExpired:
184
+ proc.kill()
185
+ exit_code = proc.wait(timeout=1.0)
186
+ break
187
+
188
+ time.sleep(0.05)
189
+
190
+ # 6. Finalize output capture
191
+ stdout_capture.join(timeout=2.0)
192
+ stderr_capture.join(timeout=2.0)
193
+ stdout_text = stdout_capture.get_output()
194
+ stderr_text = stderr_capture.get_output()
195
+
196
+ # 7. Inspect Docker exit-state to classify OOM vs Timeout vs Execution Error
197
+ oom_killed = self._inspect_oom_killed(container_name)
198
+
199
+ finally:
200
+ # 8. Defensive host child process reaping
201
+ if proc is not None:
202
+ try:
203
+ if proc.returncode is None:
204
+ proc.kill()
205
+ proc.wait(timeout=1.0)
206
+ except Exception:
207
+ pass
208
+
209
+ # 9. Guaranteed container cleanup in finally block
210
+ self.cleanup_container(container_name)
211
+
212
+ duration_seconds = max(0.0, time.monotonic() - start_time)
213
+
214
+ # 9. Determine failure reason
215
+ if oom_killed:
216
+ failure_reason = SandboxFailureReason.OOM_KILLED
217
+ elif timeout_triggered:
218
+ failure_reason = SandboxFailureReason.TIMEOUT
219
+ elif exit_code != 0:
220
+ failure_reason = SandboxFailureReason.EXECUTION_ERROR
221
+ else:
222
+ failure_reason = SandboxFailureReason.NONE
223
+
224
+ return ExecutionResult(
225
+ exit_code=exit_code,
226
+ stdout=stdout_text,
227
+ stderr=stderr_text,
228
+ duration_seconds=round(duration_seconds, 3),
229
+ failure_reason=failure_reason,
230
+ oom_killed=oom_killed,
231
+ timeout_triggered=timeout_triggered,
232
+ )
233
+
234
+ def _kill_container(self, container_name: str) -> None:
235
+ """Kill a running container by name."""
236
+ try:
237
+ subprocess.run(
238
+ ["docker", "kill", container_name],
239
+ capture_output=True,
240
+ text=True,
241
+ timeout=KILL_TIMEOUT_SECONDS,
242
+ shell=False,
243
+ close_fds=True,
244
+ check=False,
245
+ )
246
+ except (subprocess.TimeoutExpired, OSError) as err:
247
+ logger.warning("Failed to kill container %s: %s", container_name, err)
248
+
249
+ def _inspect_oom_killed(self, container_name: str) -> bool:
250
+ """Inspect container state via Docker CLI to determine if process was OOM-killed."""
251
+ try:
252
+ res = subprocess.run(
253
+ ["docker", "inspect", container_name, "--format", "{{json .State}}"],
254
+ capture_output=True,
255
+ text=True,
256
+ timeout=INSPECT_TIMEOUT_SECONDS,
257
+ shell=False,
258
+ close_fds=True,
259
+ check=False,
260
+ )
261
+ if res.returncode == 0 and res.stdout.strip():
262
+ state: dict[str, Any] = json.loads(res.stdout.strip())
263
+ return bool(state.get("OOMKilled", False))
264
+ except (subprocess.TimeoutExpired, OSError, json.JSONDecodeError) as err:
265
+ logger.warning("State inspection failed for container %s: %s", container_name, err)
266
+ return False
267
+
268
+ def cleanup_container(self, container_name: str) -> None:
269
+ """Verify PatchProof ownership and remove the container.
270
+
271
+ Raises:
272
+ SandboxSecurityError: If container is not managed by PatchProof.
273
+ """
274
+ # Step 1: Verify container ownership
275
+ try:
276
+ res = subprocess.run(
277
+ [
278
+ "docker",
279
+ "inspect",
280
+ container_name,
281
+ "--format",
282
+ '{{index .Config.Labels "patchproof.managed"}}',
283
+ ],
284
+ capture_output=True,
285
+ text=True,
286
+ timeout=INSPECT_TIMEOUT_SECONDS,
287
+ shell=False,
288
+ close_fds=True,
289
+ check=False,
290
+ )
291
+ except (subprocess.TimeoutExpired, OSError):
292
+ return
293
+
294
+ if res.returncode != 0:
295
+ # Container already removed or does not exist
296
+ return
297
+
298
+ label_val = res.stdout.strip().lower()
299
+ if label_val != "true":
300
+ raise SandboxSecurityError(
301
+ f"Refusing to clean up container '{container_name}': not managed by PatchProof"
302
+ )
303
+
304
+ # Step 2: Remove verified container
305
+ try:
306
+ subprocess.run(
307
+ ["docker", "rm", "-f", container_name],
308
+ capture_output=True,
309
+ text=True,
310
+ timeout=CLEANUP_TIMEOUT_SECONDS,
311
+ shell=False,
312
+ close_fds=True,
313
+ check=False,
314
+ )
315
+ except (subprocess.TimeoutExpired, OSError) as err:
316
+ logger.warning("Container removal failed for %s: %s", container_name, err)
317
+
318
+
319
+ class OrphanSweeper:
320
+ """Safe detector and sweeper for orphaned PatchProof execution containers."""
321
+
322
+ def __init__(self, timeout_seconds: float = 10.0) -> None:
323
+ self.timeout_seconds = timeout_seconds
324
+
325
+ def cleanup_orphaned_containers(self, max_age_seconds: float = 0.0) -> list[str]:
326
+ """Discover and terminate orphaned PatchProof containers.
327
+
328
+ Strictly targets containers bearing 'patchproof.managed=true'.
329
+ Never issues broad pruning commands like 'docker system prune'.
330
+ """
331
+ try:
332
+ res = subprocess.run(
333
+ [
334
+ "docker",
335
+ "ps",
336
+ "-a",
337
+ "--filter",
338
+ "label=patchproof.managed=true",
339
+ "--format",
340
+ "{{.ID}}\t{{.Names}}\t{{.CreatedAt}}",
341
+ ],
342
+ capture_output=True,
343
+ text=True,
344
+ timeout=self.timeout_seconds,
345
+ shell=False,
346
+ close_fds=True,
347
+ check=False,
348
+ )
349
+ except (subprocess.TimeoutExpired, OSError) as err:
350
+ logger.warning("Orphan scan failed: %s", err)
351
+ return []
352
+
353
+ if res.returncode != 0 or not res.stdout.strip():
354
+ return []
355
+
356
+ cleaned_containers: list[str] = []
357
+ for line in res.stdout.strip().splitlines():
358
+ parts = line.strip().split("\t")
359
+ if not parts:
360
+ continue
361
+ container_id = parts[0].strip()
362
+ if not container_id:
363
+ continue
364
+
365
+ # Verify ownership and metadata independently before destruction
366
+ try:
367
+ verify_res = subprocess.run(
368
+ [
369
+ "docker",
370
+ "inspect",
371
+ container_id,
372
+ "--format",
373
+ '{{index .Config.Labels "patchproof.managed"}}\t'
374
+ '{{index .Config.Labels "patchproof.timestamp"}}\t'
375
+ "{{.State.Status}}",
376
+ ],
377
+ capture_output=True,
378
+ text=True,
379
+ timeout=INSPECT_TIMEOUT_SECONDS,
380
+ shell=False,
381
+ close_fds=True,
382
+ check=False,
383
+ )
384
+ if verify_res.returncode != 0:
385
+ continue
386
+
387
+ inspect_parts = verify_res.stdout.strip().split("\t")
388
+ if len(inspect_parts) < 3:
389
+ continue
390
+
391
+ managed_label = inspect_parts[0].strip().lower()
392
+ timestamp_str = inspect_parts[1].strip()
393
+ status = inspect_parts[2].strip().lower()
394
+
395
+ if managed_label != "true":
396
+ continue
397
+
398
+ current_time = time.time()
399
+ container_ts = float(timestamp_str) if timestamp_str.isdigit() else 0.0
400
+
401
+ if max_age_seconds > 0.0:
402
+ # Skip container if younger than max_age_seconds
403
+ if container_ts > 0.0 and (current_time - container_ts) < max_age_seconds:
404
+ continue
405
+ else:
406
+ # When max_age_seconds is 0.0, protect actively running containers
407
+ if status == "running":
408
+ continue
409
+
410
+ rm_res = subprocess.run(
411
+ ["docker", "rm", "-f", container_id],
412
+ capture_output=True,
413
+ text=True,
414
+ timeout=CLEANUP_TIMEOUT_SECONDS,
415
+ shell=False,
416
+ close_fds=True,
417
+ check=False,
418
+ )
419
+ if rm_res.returncode == 0:
420
+ cleaned_containers.append(container_id)
421
+ except (subprocess.TimeoutExpired, OSError) as err:
422
+ logger.warning("Failed cleaning orphan %s: %s", container_id, err)
423
+
424
+ return cleaned_containers
@@ -0,0 +1,261 @@
1
+ """Runner image build and lifecycle management for PatchProof."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import pathlib
7
+ import platform
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ from typing import IO
12
+
13
+ from patchproof.exceptions import DockerUnavailableError
14
+ from patchproof.sandbox.docker_cli import DockerPreflight
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ DEFAULT_RUNNER_TAG = "patchproof-runner-python:3.11"
19
+ DEFAULT_DOCKERFILE_PATH = pathlib.Path("docker/runner.Dockerfile")
20
+
21
+
22
+ def resolve_default_dockerfile() -> pathlib.Path:
23
+ """Locate the default runner Dockerfile in the project or package hierarchy."""
24
+ # Check 1: Relative to current working directory
25
+ cwd_candidate = pathlib.Path.cwd() / DEFAULT_DOCKERFILE_PATH
26
+ if cwd_candidate.exists() and cwd_candidate.is_file():
27
+ return cwd_candidate.resolve()
28
+
29
+ # Check 2: Bundled inside patchproof package (e.g. installed package in site-packages)
30
+ bundled_candidate = (
31
+ pathlib.Path(__file__).resolve().parent.parent / "docker" / "runner.Dockerfile"
32
+ )
33
+ if bundled_candidate.exists() and bundled_candidate.is_file():
34
+ return bundled_candidate.resolve()
35
+
36
+ # Check 3: Relative to patchproof package root (e.g. source checkout)
37
+ package_dir = pathlib.Path(__file__).resolve().parent.parent.parent.parent
38
+ pkg_candidate = package_dir / DEFAULT_DOCKERFILE_PATH
39
+ if pkg_candidate.exists() and pkg_candidate.is_file():
40
+ return pkg_candidate.resolve()
41
+
42
+ # Fallback to direct path representation
43
+ return DEFAULT_DOCKERFILE_PATH.resolve()
44
+
45
+
46
+ def build_runner_image(
47
+ image_tag: str = DEFAULT_RUNNER_TAG,
48
+ dockerfile_path: pathlib.Path | str | None = None,
49
+ no_cache: bool = False,
50
+ quiet: bool = False,
51
+ timeout_seconds: float | None = 600.0,
52
+ stdout_stream: IO[str] | object | None = None,
53
+ stderr_stream: IO[str] | object | None = None,
54
+ ) -> int:
55
+ """Build the standard PatchProof runner container image locally using Docker CLI.
56
+
57
+ Args:
58
+ image_tag: The Docker image tag to assign (default: 'patchproof-runner-python:3.11').
59
+ dockerfile_path: Path to the runner Dockerfile (default: auto-detected).
60
+ no_cache: If True, passes --no-cache to docker build.
61
+ quiet: If True, suppresses non-error output.
62
+ stdout_stream: Stream to direct build stdout (defaults to sys.stdout).
63
+ stderr_stream: Stream to direct build stderr (defaults to sys.stderr).
64
+
65
+ Returns:
66
+ 0 on success, non-zero exit code on failure.
67
+ """
68
+ out = stdout_stream or sys.stdout
69
+ err = stderr_stream or sys.stderr
70
+
71
+ # Step 1: Preflight check for Docker CLI and daemon
72
+ preflight = DockerPreflight(timeout_seconds=5.0)
73
+ try:
74
+ preflight.check()
75
+ except DockerUnavailableError as exc:
76
+ msg = (
77
+ f"Error: Docker is unavailable: {exc}\n"
78
+ "Remediation: Verify Docker Desktop or the docker daemon is installed and running.\n"
79
+ )
80
+ if hasattr(err, "write"):
81
+ err.write(msg)
82
+ return 1
83
+ except Exception as exc:
84
+ msg = f"Error: Docker preflight check failed: {exc}\n"
85
+ if hasattr(err, "write"):
86
+ err.write(msg)
87
+ return 1
88
+
89
+ # Step 2: Resolve Dockerfile path
90
+ if dockerfile_path is None:
91
+ resolved_dockerfile = resolve_default_dockerfile()
92
+ else:
93
+ resolved_dockerfile = pathlib.Path(dockerfile_path).resolve()
94
+
95
+ if not resolved_dockerfile.exists() or not resolved_dockerfile.is_file():
96
+ msg = (
97
+ f"Error: Runner Dockerfile not found at '{resolved_dockerfile}'.\n"
98
+ "Remediation: Ensure 'docker/runner.Dockerfile' exists in the repository root.\n"
99
+ )
100
+ if hasattr(err, "write"):
101
+ err.write(msg)
102
+ return 1
103
+
104
+ # Step 3: Determine build context directory
105
+ # Build context should be the parent repository root of the dockerfile
106
+ context_dir = resolved_dockerfile.parent.parent
107
+ if not (context_dir / "docker").exists():
108
+ context_dir = resolved_dockerfile.parent
109
+
110
+ arch = platform.machine()
111
+ if not quiet and hasattr(out, "write"):
112
+ out.write(
113
+ f"Building PatchProof runner image '{image_tag}' (arch: {arch})\n"
114
+ f"Dockerfile: {resolved_dockerfile}\n"
115
+ f"Context: {context_dir}\n"
116
+ )
117
+
118
+ # Step 4: Construct hardened argument vector (shell=False)
119
+ docker_bin = shutil.which("docker") or "docker"
120
+ build_cmd = [
121
+ docker_bin,
122
+ "build",
123
+ "-t",
124
+ image_tag,
125
+ "-f",
126
+ str(resolved_dockerfile),
127
+ ]
128
+ if no_cache:
129
+ build_cmd.append("--no-cache")
130
+ build_cmd.append(str(context_dir))
131
+
132
+ # Step 5: Execute build with bound subprocess
133
+ try:
134
+ result = subprocess.run(
135
+ build_cmd,
136
+ shell=False,
137
+ check=False,
138
+ capture_output=True,
139
+ text=True,
140
+ timeout=timeout_seconds,
141
+ )
142
+ if result.stdout and not quiet and hasattr(out, "write"):
143
+ out.write(result.stdout)
144
+ except subprocess.TimeoutExpired:
145
+ if hasattr(err, "write"):
146
+ err.write(f"Error: docker build timed out after {timeout_seconds} seconds.\n")
147
+ return 1
148
+ except FileNotFoundError:
149
+ if hasattr(err, "write"):
150
+ err.write("Error: 'docker' executable not found on system PATH.\n")
151
+ return 1
152
+ except OSError as exc:
153
+ if hasattr(err, "write"):
154
+ err.write(f"Error executing docker build: {exc}\n")
155
+ return 1
156
+
157
+ if result.returncode == 0:
158
+ if not quiet and hasattr(out, "write"):
159
+ out.write(f"\nSuccessfully built and tagged runner image: {image_tag}\n")
160
+ return 0
161
+
162
+ if hasattr(err, "write"):
163
+ err.write(f"\nError: docker build failed with exit code {result.returncode}\n")
164
+ if result.stderr:
165
+ err.write(result.stderr)
166
+ return result.returncode
167
+
168
+
169
+ def generate_ephemeral_dockerfile(
170
+ repo_path: pathlib.Path | str,
171
+ base_image: str = DEFAULT_RUNNER_TAG,
172
+ ) -> tuple[str, list[pathlib.Path]]:
173
+ """Generate layered Dockerfile caching repository dependencies for zero-network execution."""
174
+ root = pathlib.Path(repo_path).resolve()
175
+ manifests: list[pathlib.Path] = []
176
+ copy_lines: list[str] = []
177
+ install_cmds: list[str] = []
178
+
179
+ req_txt = root / "requirements.txt"
180
+ if req_txt.is_file():
181
+ manifests.append(req_txt)
182
+ copy_lines.append("COPY requirements.txt /tmp/build_deps/requirements.txt")
183
+ install_cmds.append("pip install --no-cache-dir -r /tmp/build_deps/requirements.txt")
184
+
185
+ req_dev = root / "requirements-dev.txt"
186
+ if req_dev.is_file():
187
+ manifests.append(req_dev)
188
+ copy_lines.append("COPY requirements-dev.txt /tmp/build_deps/requirements-dev.txt")
189
+ install_cmds.append("pip install --no-cache-dir -r /tmp/build_deps/requirements-dev.txt")
190
+
191
+ pyproject = root / "pyproject.toml"
192
+ if pyproject.is_file():
193
+ manifests.append(pyproject)
194
+ copy_lines.append("COPY pyproject.toml /tmp/build_deps/pyproject.toml")
195
+ install_cmds.append("pip install --no-cache-dir . || true")
196
+
197
+ setup_py = root / "setup.py"
198
+ if setup_py.is_file():
199
+ manifests.append(setup_py)
200
+ copy_lines.append("COPY setup.py /tmp/build_deps/setup.py")
201
+
202
+ setup_cfg = root / "setup.cfg"
203
+ if setup_cfg.is_file():
204
+ manifests.append(setup_cfg)
205
+ copy_lines.append("COPY setup.cfg /tmp/build_deps/setup.cfg")
206
+
207
+ copy_block = "\n".join(copy_lines)
208
+ install_block = " && ".join(install_cmds) if install_cmds else "true"
209
+
210
+ dockerfile_content = f"""# Auto-generated by PatchProof Dependency Pre-Cache Engine
211
+ FROM {base_image}
212
+
213
+ USER root
214
+ WORKDIR /tmp/build_deps
215
+ {copy_block}
216
+
217
+ RUN {install_block} \\
218
+ && rm -rf /tmp/build_deps /root/.cache
219
+
220
+ USER 10001:10001
221
+ WORKDIR /workspace
222
+ """
223
+ return dockerfile_content, manifests
224
+
225
+
226
+ def build_runner_from_repo(
227
+ repo_path: pathlib.Path | str,
228
+ image_tag: str | None = None,
229
+ base_image: str = DEFAULT_RUNNER_TAG,
230
+ no_cache: bool = False,
231
+ quiet: bool = False,
232
+ timeout_seconds: float | None = 600.0,
233
+ stdout_stream: IO[str] | object | None = None,
234
+ stderr_stream: IO[str] | object | None = None,
235
+ ) -> tuple[int, str]:
236
+ """Build a hardened, project-specific runner image with pre-cached dependencies."""
237
+ root = pathlib.Path(repo_path).resolve()
238
+ repo_clean_name = root.name.lower().replace(" ", "-").replace("_", "-")
239
+ tag = image_tag or f"patchproof-runner-{repo_clean_name}:latest"
240
+
241
+ dockerfile_content, manifests = generate_ephemeral_dockerfile(root, base_image=base_image)
242
+
243
+ import tempfile
244
+ with tempfile.TemporaryDirectory(prefix="patchproof-repo-runner-") as tmp_dir:
245
+ tmp_path = pathlib.Path(tmp_dir)
246
+ df_path = tmp_path / "Dockerfile"
247
+ df_path.write_text(dockerfile_content, encoding="utf-8")
248
+
249
+ for m in manifests:
250
+ shutil.copy2(m, tmp_path / m.name)
251
+
252
+ exit_code = build_runner_image(
253
+ image_tag=tag,
254
+ dockerfile_path=df_path,
255
+ no_cache=no_cache,
256
+ quiet=quiet,
257
+ timeout_seconds=timeout_seconds,
258
+ stdout_stream=stdout_stream,
259
+ stderr_stream=stderr_stream,
260
+ )
261
+ return exit_code, tag