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.
- patchproof/__init__.py +44 -0
- patchproof/__main__.py +8 -0
- patchproof/benchmarks/__init__.py +17 -0
- patchproof/benchmarks/swe_bench.py +159 -0
- patchproof/cli.py +1254 -0
- patchproof/core/__init__.py +33 -0
- patchproof/core/agent_init.py +103 -0
- patchproof/core/anti_cheat.py +396 -0
- patchproof/core/applier.py +159 -0
- patchproof/core/ast_analyzer.py +254 -0
- patchproof/core/detector.py +78 -0
- patchproof/core/git_provider.py +298 -0
- patchproof/core/healer.py +104 -0
- patchproof/core/mutator.py +223 -0
- patchproof/core/normalizer.py +338 -0
- patchproof/core/polyglot_guard.py +167 -0
- patchproof/core/runtime_guard.py +188 -0
- patchproof/core/search_replace.py +222 -0
- patchproof/core/slicer.py +172 -0
- patchproof/core/sparse_tree.py +95 -0
- patchproof/docker/runner.Dockerfile +42 -0
- patchproof/exceptions.py +37 -0
- patchproof/factory/__init__.py +22 -0
- patchproof/factory/blast_radius.py +120 -0
- patchproof/factory/engine.py +134 -0
- patchproof/factory/models.py +75 -0
- patchproof/mcp.py +532 -0
- patchproof/models/__init__.py +57 -0
- patchproof/models/ast.py +78 -0
- patchproof/models/patch.py +106 -0
- patchproof/models/sandbox.py +417 -0
- patchproof/reporting/__init__.py +19 -0
- patchproof/reporting/asymmetric.py +88 -0
- patchproof/reporting/badge.py +86 -0
- patchproof/reporting/certificate.py +230 -0
- patchproof/reporting/diagnostic.py +330 -0
- patchproof/reporting/html_report.py +367 -0
- patchproof/reporting/in_toto.py +188 -0
- patchproof/reporting/markdown.py +179 -0
- patchproof/reporting/sbom.py +152 -0
- patchproof/sandbox/__init__.py +37 -0
- patchproof/sandbox/classifier.py +289 -0
- patchproof/sandbox/comparative.py +478 -0
- patchproof/sandbox/docker_cli.py +384 -0
- patchproof/sandbox/doctor.py +605 -0
- patchproof/sandbox/flakiness.py +87 -0
- patchproof/sandbox/network_bridge.py +145 -0
- patchproof/sandbox/parser.py +172 -0
- patchproof/sandbox/runner.py +424 -0
- patchproof/sandbox/setup_runner.py +261 -0
- patchproof_core-0.3.1.dist-info/METADATA +212 -0
- patchproof_core-0.3.1.dist-info/RECORD +56 -0
- patchproof_core-0.3.1.dist-info/WHEEL +5 -0
- patchproof_core-0.3.1.dist-info/entry_points.txt +2 -0
- patchproof_core-0.3.1.dist-info/licenses/LICENSE +13 -0
- patchproof_core-0.3.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Predictive Test Slicing via Python AST Import and Dependency Graph Analysis.
|
|
2
|
+
|
|
3
|
+
Selects the minimal impacted test closure for a patch to achieve sub-second verification,
|
|
4
|
+
falling back safely to the full test suite when non-Python files or configurations change.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import ast
|
|
10
|
+
import logging
|
|
11
|
+
import pathlib
|
|
12
|
+
import time
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
from patchproof.core.ast_analyzer import _extract_imports
|
|
16
|
+
from patchproof.models.patch import CanonicalPatch
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
NON_PYTHON_EXTENSIONS = (
|
|
21
|
+
".toml",
|
|
22
|
+
".yaml",
|
|
23
|
+
".yml",
|
|
24
|
+
".json",
|
|
25
|
+
".ini",
|
|
26
|
+
".cfg",
|
|
27
|
+
".txt",
|
|
28
|
+
".md",
|
|
29
|
+
".sh",
|
|
30
|
+
".bat",
|
|
31
|
+
".dockerfile",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class TestSliceResult:
|
|
37
|
+
"""Outcome of predictive test slicing."""
|
|
38
|
+
|
|
39
|
+
__test__ = False
|
|
40
|
+
|
|
41
|
+
selected_test_paths: tuple[str, ...]
|
|
42
|
+
is_full_suite_fallback: bool
|
|
43
|
+
fallback_reason: str | None = None
|
|
44
|
+
impacted_modules: tuple[str, ...] = ()
|
|
45
|
+
duration_ms: float = 0.0
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def has_targeted_selection(self) -> bool:
|
|
49
|
+
"""Return True if specific test targets were isolated."""
|
|
50
|
+
return not self.is_full_suite_fallback and len(self.selected_test_paths) > 0
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _derive_module_candidates(rel_path_str: str) -> tuple[str, ...]:
|
|
54
|
+
"""Derive possible Python import module paths from relative file path."""
|
|
55
|
+
clean = rel_path_str.replace("\\", "/").strip("/")
|
|
56
|
+
if clean.endswith(".py"):
|
|
57
|
+
clean = clean[:-3]
|
|
58
|
+
parts = [p for p in clean.split("/") if p and p != "__init__"]
|
|
59
|
+
candidates: list[str] = []
|
|
60
|
+
|
|
61
|
+
# 1. Full dotted path
|
|
62
|
+
candidates.append(".".join(parts))
|
|
63
|
+
|
|
64
|
+
# 2. Path without leading 'src'
|
|
65
|
+
if parts and parts[0] == "src":
|
|
66
|
+
candidates.append(".".join(parts[1:]))
|
|
67
|
+
|
|
68
|
+
# 3. Base filename only
|
|
69
|
+
if parts:
|
|
70
|
+
candidates.append(parts[-1])
|
|
71
|
+
|
|
72
|
+
return tuple(sorted({p for p in candidates if p}))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def slice_test_suite(
|
|
76
|
+
repo_path: pathlib.Path,
|
|
77
|
+
patch: CanonicalPatch,
|
|
78
|
+
tests_root: str = "tests",
|
|
79
|
+
) -> TestSliceResult:
|
|
80
|
+
"""Analyze patch impact and return targeted test suite slice."""
|
|
81
|
+
start_time = time.perf_counter()
|
|
82
|
+
|
|
83
|
+
# 1. Check for non-Python or configuration file changes
|
|
84
|
+
for delta in patch.file_deltas:
|
|
85
|
+
norm_path = delta.path.lower().replace("\\", "/")
|
|
86
|
+
if (
|
|
87
|
+
any(norm_path.endswith(ext) for ext in NON_PYTHON_EXTENSIONS)
|
|
88
|
+
or "docker" in norm_path
|
|
89
|
+
or norm_path.startswith(".github/")
|
|
90
|
+
):
|
|
91
|
+
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
|
92
|
+
reason = (
|
|
93
|
+
f"Configuration or non-Python change in '{delta.path}' "
|
|
94
|
+
"requires full suite validation"
|
|
95
|
+
)
|
|
96
|
+
return TestSliceResult(
|
|
97
|
+
selected_test_paths=(),
|
|
98
|
+
is_full_suite_fallback=True,
|
|
99
|
+
fallback_reason=reason,
|
|
100
|
+
duration_ms=elapsed_ms,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
selected_tests: set[str] = set()
|
|
104
|
+
impacted_modules: set[str] = set()
|
|
105
|
+
source_deltas: list[str] = []
|
|
106
|
+
|
|
107
|
+
tests_dir = repo_path / tests_root
|
|
108
|
+
|
|
109
|
+
# 2. Separate direct test modifications from source modifications
|
|
110
|
+
for delta in patch.file_deltas:
|
|
111
|
+
norm_path = delta.path.replace("\\", "/").strip("/")
|
|
112
|
+
if (
|
|
113
|
+
norm_path.startswith(f"{tests_root}/")
|
|
114
|
+
or "test_" in norm_path
|
|
115
|
+
or "_test.py" in norm_path
|
|
116
|
+
):
|
|
117
|
+
# Direct test edit
|
|
118
|
+
selected_tests.add(norm_path)
|
|
119
|
+
else:
|
|
120
|
+
source_deltas.append(norm_path)
|
|
121
|
+
impacted_modules.update(_derive_module_candidates(norm_path))
|
|
122
|
+
|
|
123
|
+
# 3. If source modules were modified, scan tests directory for importing test files
|
|
124
|
+
if source_deltas and tests_dir.is_dir():
|
|
125
|
+
for test_file in tests_dir.rglob("*.py"):
|
|
126
|
+
if not test_file.is_file():
|
|
127
|
+
continue
|
|
128
|
+
rel_test_str = str(test_file.relative_to(repo_path)).replace("\\", "/")
|
|
129
|
+
try:
|
|
130
|
+
content = test_file.read_text(encoding="utf-8")
|
|
131
|
+
tree = ast.parse(content, filename=str(test_file))
|
|
132
|
+
except (SyntaxError, UnicodeDecodeError, OSError):
|
|
133
|
+
continue
|
|
134
|
+
|
|
135
|
+
file_imports = _extract_imports(tree)
|
|
136
|
+
matched = False
|
|
137
|
+
for imp in file_imports:
|
|
138
|
+
for mod in impacted_modules:
|
|
139
|
+
if imp == mod or imp.startswith(f"{mod}.") or mod.endswith(f".{imp}"):
|
|
140
|
+
matched = True
|
|
141
|
+
break
|
|
142
|
+
if matched:
|
|
143
|
+
break
|
|
144
|
+
|
|
145
|
+
# Check filename counterpart heuristic (e.g. test_billing.py for billing.py)
|
|
146
|
+
if not matched:
|
|
147
|
+
for s in source_deltas:
|
|
148
|
+
base_stem = pathlib.Path(s).stem
|
|
149
|
+
if test_file.stem in (f"test_{base_stem}", f"{base_stem}_test"):
|
|
150
|
+
matched = True
|
|
151
|
+
break
|
|
152
|
+
|
|
153
|
+
if matched:
|
|
154
|
+
selected_tests.add(rel_test_str)
|
|
155
|
+
|
|
156
|
+
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
|
157
|
+
|
|
158
|
+
if not selected_tests:
|
|
159
|
+
return TestSliceResult(
|
|
160
|
+
selected_test_paths=(),
|
|
161
|
+
is_full_suite_fallback=True,
|
|
162
|
+
fallback_reason="No direct or importing test files found for modified modules",
|
|
163
|
+
impacted_modules=tuple(sorted(impacted_modules)),
|
|
164
|
+
duration_ms=elapsed_ms,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
return TestSliceResult(
|
|
168
|
+
selected_test_paths=tuple(sorted(selected_tests)),
|
|
169
|
+
is_full_suite_fallback=False,
|
|
170
|
+
impacted_modules=tuple(sorted(impacted_modules)),
|
|
171
|
+
duration_ms=elapsed_ms,
|
|
172
|
+
)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Monorepo Sparse Tree and Scoped Staging Subsystem.
|
|
2
|
+
|
|
3
|
+
Calculates minimal common ancestor directories for patches to enable fast scoped
|
|
4
|
+
git archive extraction in multi-gigabyte monorepos.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
|
|
12
|
+
from patchproof.models.patch import CanonicalPatch
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def compute_minimal_common_ancestor(modified_paths: Sequence[str]) -> str | None:
|
|
16
|
+
"""Calculate the shallowest common directory among all modified files in a patch.
|
|
17
|
+
|
|
18
|
+
Example:
|
|
19
|
+
['services/auth/models.py', 'services/auth/tests/test_login.py']
|
|
20
|
+
-> 'services/auth'
|
|
21
|
+
['foo.py', 'bar.py']
|
|
22
|
+
-> None (root directory)
|
|
23
|
+
"""
|
|
24
|
+
clean_paths: list[list[str]] = []
|
|
25
|
+
for p in modified_paths:
|
|
26
|
+
normalized = p.replace("\\", "/").strip("/")
|
|
27
|
+
if not normalized or normalized in ("/dev/null", "dev/null"):
|
|
28
|
+
continue
|
|
29
|
+
parts = normalized.split("/")
|
|
30
|
+
# Path must have at least 2 parts (dir + filename) to have a parent directory
|
|
31
|
+
if len(parts) > 1:
|
|
32
|
+
clean_paths.append(parts[:-1]) # Keep only directory segments
|
|
33
|
+
else:
|
|
34
|
+
# File is in root directory; no common non-root ancestor can exist
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
if not clean_paths:
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
common_segments: list[str] = []
|
|
41
|
+
for segments in zip(*clean_paths, strict=False):
|
|
42
|
+
if len(set(segments)) == 1:
|
|
43
|
+
common_segments.append(segments[0])
|
|
44
|
+
else:
|
|
45
|
+
break
|
|
46
|
+
|
|
47
|
+
return "/".join(common_segments) if common_segments else None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def extract_patch_modified_paths(patch: str | CanonicalPatch) -> list[str]:
|
|
51
|
+
"""Extract list of target file paths modified by a unified diff or CanonicalPatch."""
|
|
52
|
+
if isinstance(patch, CanonicalPatch):
|
|
53
|
+
return [delta.path for delta in patch.file_deltas if delta.path]
|
|
54
|
+
|
|
55
|
+
paths: list[str] = []
|
|
56
|
+
for line in patch.splitlines():
|
|
57
|
+
if line.startswith("+++ "):
|
|
58
|
+
# Strip +++ and b/ prefix if present
|
|
59
|
+
raw_target = line[4:].strip()
|
|
60
|
+
# Handle timestamps e.g. +++ b/file.py \t 2026-01-01
|
|
61
|
+
target = raw_target.split("\t")[0].strip()
|
|
62
|
+
if target.startswith("b/"):
|
|
63
|
+
target = target[2:]
|
|
64
|
+
if target and target != "/dev/null" and target not in paths:
|
|
65
|
+
paths.append(target)
|
|
66
|
+
elif line.startswith("diff --git "):
|
|
67
|
+
match = re.match(r"diff --git a/(.*?) b/(.*)", line)
|
|
68
|
+
if match:
|
|
69
|
+
b_path = match.group(2).strip()
|
|
70
|
+
if b_path and b_path != "/dev/null" and b_path not in paths:
|
|
71
|
+
paths.append(b_path)
|
|
72
|
+
|
|
73
|
+
return paths
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def should_use_sparse_extraction(
|
|
77
|
+
modified_paths: Sequence[str], min_depth: int = 1
|
|
78
|
+
) -> str | None:
|
|
79
|
+
"""Determine if a patch qualifies for scoped monorepo sparse extraction.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
modified_paths: List of relative file paths in patch.
|
|
83
|
+
min_depth: Minimum directory hierarchy depth required to activate scoping.
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
str | None: Subtree directory path if applicable, None otherwise.
|
|
87
|
+
"""
|
|
88
|
+
ancestor = compute_minimal_common_ancestor(modified_paths)
|
|
89
|
+
if not ancestor:
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
depth = len(ancestor.split("/"))
|
|
93
|
+
if depth >= min_depth:
|
|
94
|
+
return ancestor
|
|
95
|
+
return None
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# PatchProof Standard Python 3.11 Test Runner
|
|
2
|
+
# Version: 0.1.0-m4.1
|
|
3
|
+
# Base Image: python:3.11-slim-bookworm (pinned Debian Bookworm)
|
|
4
|
+
FROM python:3.11-slim-bookworm
|
|
5
|
+
|
|
6
|
+
# Metadata labels
|
|
7
|
+
LABEL org.opencontainers.image.title="PatchProof Python Test Runner"
|
|
8
|
+
LABEL org.opencontainers.image.description="Minimal, hardened container image for isolated Python test execution"
|
|
9
|
+
LABEL org.opencontainers.image.version="0.1.0-m4.1"
|
|
10
|
+
LABEL patchproof.runner=true
|
|
11
|
+
LABEL patchproof.version="0.1.0"
|
|
12
|
+
LABEL patchproof.python="3.11"
|
|
13
|
+
|
|
14
|
+
# Environment: Disable bytecode caching and unbuffer output
|
|
15
|
+
ENV PYTHONUNBUFFERED=1 \
|
|
16
|
+
PYTHONDONTWRITEBYTECODE=1 \
|
|
17
|
+
PIP_NO_CACHE_DIR=1 \
|
|
18
|
+
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
|
19
|
+
HOME=/home/patchproof
|
|
20
|
+
|
|
21
|
+
# Install core test execution dependencies
|
|
22
|
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
23
|
+
ca-certificates \
|
|
24
|
+
&& rm -rf /var/lib/apt/lists/* \
|
|
25
|
+
&& pip install --no-cache-dir \
|
|
26
|
+
pytest>=8.0.0 \
|
|
27
|
+
pytest-timeout \
|
|
28
|
+
pytest-xdist
|
|
29
|
+
|
|
30
|
+
# Security: Create unprivileged user and group with UID/GID 10001
|
|
31
|
+
RUN groupadd -g 10001 patchproof \
|
|
32
|
+
&& useradd -u 10001 -g 10001 -m -s /bin/bash -d /home/patchproof patchproof \
|
|
33
|
+
&& mkdir -p /workspace /tmp \
|
|
34
|
+
&& chown -R patchproof:patchproof /workspace /tmp /home/patchproof \
|
|
35
|
+
&& chmod 1777 /tmp /workspace
|
|
36
|
+
|
|
37
|
+
# Switch to unprivileged user
|
|
38
|
+
USER 10001:10001
|
|
39
|
+
WORKDIR /workspace
|
|
40
|
+
|
|
41
|
+
# Default command
|
|
42
|
+
CMD ["pytest", "-q"]
|
patchproof/exceptions.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""PatchProof custom exception hierarchy."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class PatchProofError(Exception):
|
|
5
|
+
"""Base exception for all PatchProof errors."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class InvalidPatchFormatError(PatchProofError):
|
|
9
|
+
"""Raised when a patch cannot be parsed or violates unified diff specifications."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SandboxSecurityError(PatchProofError):
|
|
13
|
+
"""Raised when an invalid, insecure, or prohibited sandbox configuration is attempted."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class DockerUnavailableError(PatchProofError):
|
|
17
|
+
"""Raised when the Docker daemon is inactive, inaccessible, or unresponsive."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class UnsupportedDockerEngineError(DockerUnavailableError):
|
|
21
|
+
"""Raised when Docker Desktop is running in Windows Containers mode instead of Linux/WSL2."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ContainerExecutionTimeoutError(PatchProofError):
|
|
25
|
+
"""Raised when an isolated test container exceeds the maximum execution timeout."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class PatchApplicationError(PatchProofError):
|
|
29
|
+
"""Raised when a patch cannot be applied cleanly to the staging worktree."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class GitRepositoryError(PatchProofError):
|
|
33
|
+
"""Raised when a Git command fails or the target path is not a Git repository."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class NoChangesDetectedError(PatchProofError):
|
|
37
|
+
"""Raised when no diff changes are detected in the working tree or target commit."""
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""PatchProof AI Software Factory Subsystem."""
|
|
2
|
+
|
|
3
|
+
from patchproof.factory.blast_radius import BlastRadiusClassifier
|
|
4
|
+
from patchproof.factory.engine import FactoryEngine, GateResult
|
|
5
|
+
from patchproof.factory.models import (
|
|
6
|
+
BlastRadiusReport,
|
|
7
|
+
FactoryLineage,
|
|
8
|
+
FactoryRunResult,
|
|
9
|
+
HybridLoopState,
|
|
10
|
+
RiskLevel,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"BlastRadiusClassifier",
|
|
15
|
+
"BlastRadiusReport",
|
|
16
|
+
"FactoryEngine",
|
|
17
|
+
"FactoryLineage",
|
|
18
|
+
"FactoryRunResult",
|
|
19
|
+
"GateResult",
|
|
20
|
+
"HybridLoopState",
|
|
21
|
+
"RiskLevel",
|
|
22
|
+
]
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Blast Radius Assessment Gate for PatchProof AI Software Factory.
|
|
2
|
+
|
|
3
|
+
Categorizes incoming patches into:
|
|
4
|
+
- Lineage A (Contained / Level 4): Low risk, verified autonomously.
|
|
5
|
+
- Lineage B (Breaking / Level 3): High risk, executed in ephemeral sandbox with human operator gate.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from pathlib import PurePosixPath
|
|
11
|
+
|
|
12
|
+
from patchproof.core.normalizer import parse_patch
|
|
13
|
+
from patchproof.factory.models import BlastRadiusReport, FactoryLineage, RiskLevel
|
|
14
|
+
from patchproof.models.patch import FileDelta
|
|
15
|
+
|
|
16
|
+
CORE_SENSITIVE_PREFIXES: tuple[str, ...] = (
|
|
17
|
+
"src/patchproof/core/",
|
|
18
|
+
"src/patchproof/sandbox/",
|
|
19
|
+
"src/patchproof/reporting/",
|
|
20
|
+
"src/patchproof/models/",
|
|
21
|
+
".github/workflows/",
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
CRITICAL_ROOT_FILES: tuple[str, ...] = (
|
|
25
|
+
"pyproject.toml",
|
|
26
|
+
"AGENTS.md",
|
|
27
|
+
"CLAUDE.md",
|
|
28
|
+
"dockerfile",
|
|
29
|
+
"docker-compose.yml",
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class BlastRadiusClassifier:
|
|
34
|
+
"""Evaluates patch diffs to compute blast radius and route to Lineage A or B."""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
sensitive_prefixes: tuple[str, ...] = CORE_SENSITIVE_PREFIXES,
|
|
39
|
+
critical_files: tuple[str, ...] = CRITICAL_ROOT_FILES,
|
|
40
|
+
) -> None:
|
|
41
|
+
self.sensitive_prefixes = sensitive_prefixes
|
|
42
|
+
self.critical_files = tuple(f.lower() for f in critical_files)
|
|
43
|
+
|
|
44
|
+
def assess_patch(self, patch_str: str) -> BlastRadiusReport:
|
|
45
|
+
"""Parse unified diff and assess blast radius risk."""
|
|
46
|
+
if not patch_str.strip():
|
|
47
|
+
return BlastRadiusReport(
|
|
48
|
+
risk_level=RiskLevel.LOW,
|
|
49
|
+
lineage=FactoryLineage.LINEAGE_A,
|
|
50
|
+
is_contained=True,
|
|
51
|
+
touched_files=(),
|
|
52
|
+
core_files_touched=(),
|
|
53
|
+
rationale="Empty patch contains no modifications.",
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
canonical = parse_patch(patch_str)
|
|
57
|
+
return self.assess_deltas(canonical.file_deltas)
|
|
58
|
+
|
|
59
|
+
def assess_deltas(self, deltas: tuple[FileDelta, ...]) -> BlastRadiusReport:
|
|
60
|
+
"""Assess parsed file deltas against security boundaries."""
|
|
61
|
+
touched: list[str] = []
|
|
62
|
+
core_touched: list[str] = []
|
|
63
|
+
reasons: list[str] = []
|
|
64
|
+
|
|
65
|
+
for delta in deltas:
|
|
66
|
+
normalized_path = PurePosixPath(delta.path.replace("\\", "/")).as_posix()
|
|
67
|
+
touched.append(normalized_path)
|
|
68
|
+
basename = PurePosixPath(normalized_path).name.lower()
|
|
69
|
+
|
|
70
|
+
# 1. Critical governance or configuration files
|
|
71
|
+
if basename in self.critical_files or normalized_path.lower() in self.critical_files:
|
|
72
|
+
core_touched.append(normalized_path)
|
|
73
|
+
reasons.append(
|
|
74
|
+
f"Modifies critical configuration/governance file: {normalized_path}"
|
|
75
|
+
)
|
|
76
|
+
continue
|
|
77
|
+
|
|
78
|
+
# 2. Check if file is in sensitive core path
|
|
79
|
+
is_sensitive_path = any(
|
|
80
|
+
normalized_path.startswith(prefix) for prefix in self.sensitive_prefixes
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
if is_sensitive_path:
|
|
84
|
+
# Inspect if modifications are purely comments/whitespace
|
|
85
|
+
if not self._is_comment_only_delta(delta):
|
|
86
|
+
core_touched.append(normalized_path)
|
|
87
|
+
reasons.append(f"Modifies executable core code: {normalized_path}")
|
|
88
|
+
|
|
89
|
+
if core_touched:
|
|
90
|
+
return BlastRadiusReport(
|
|
91
|
+
risk_level=RiskLevel.HIGH,
|
|
92
|
+
lineage=FactoryLineage.LINEAGE_B,
|
|
93
|
+
is_contained=False,
|
|
94
|
+
touched_files=tuple(touched),
|
|
95
|
+
core_files_touched=tuple(core_touched),
|
|
96
|
+
rationale="; ".join(reasons),
|
|
97
|
+
confidence_score=0.95,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
return BlastRadiusReport(
|
|
101
|
+
risk_level=RiskLevel.LOW,
|
|
102
|
+
lineage=FactoryLineage.LINEAGE_A,
|
|
103
|
+
is_contained=True,
|
|
104
|
+
touched_files=tuple(touched),
|
|
105
|
+
core_files_touched=(),
|
|
106
|
+
rationale=(
|
|
107
|
+
"All modifications are contained within safe documentation or non-core boundaries."
|
|
108
|
+
),
|
|
109
|
+
confidence_score=0.98,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
def _is_comment_only_delta(self, delta: FileDelta) -> bool:
|
|
113
|
+
"""Check if delta contains only comments or blank lines."""
|
|
114
|
+
for hunk in delta.hunks:
|
|
115
|
+
for line in hunk.lines:
|
|
116
|
+
if line.startswith(("+", "-")) and not line.startswith(("+++", "---")):
|
|
117
|
+
content = line[1:].strip()
|
|
118
|
+
if content and not content.startswith("#"):
|
|
119
|
+
return False
|
|
120
|
+
return True
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""The Hybrid Loop Engine for the PatchProof AI Software Factory.
|
|
2
|
+
|
|
3
|
+
Implements the candidate -> gate -> feedback -> retry execution cycle
|
|
4
|
+
with cryptographic Ed25519 attestation and blast-radius lineage routing.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
|
|
12
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
13
|
+
|
|
14
|
+
from patchproof.factory.blast_radius import BlastRadiusClassifier
|
|
15
|
+
from patchproof.factory.models import (
|
|
16
|
+
BlastRadiusReport,
|
|
17
|
+
FactoryLineage,
|
|
18
|
+
FactoryRunResult,
|
|
19
|
+
HybridLoopState,
|
|
20
|
+
RiskLevel,
|
|
21
|
+
)
|
|
22
|
+
from patchproof.reporting.asymmetric import generate_ed25519_keypair, sign_payload_ed25519
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class GateResult(BaseModel):
|
|
26
|
+
"""Result of deterministic verification gate."""
|
|
27
|
+
|
|
28
|
+
model_config = ConfigDict(frozen=True)
|
|
29
|
+
|
|
30
|
+
passed: bool = Field(description="True if all deterministic gates passed")
|
|
31
|
+
diagnostics: str = Field(default="", description="Failure reasons or error traces")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class FactoryEngine:
|
|
35
|
+
"""Orchestrates candidate generation, deterministic gating, and lineage routing."""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
max_retries: int = 3,
|
|
40
|
+
classifier: BlastRadiusClassifier | None = None,
|
|
41
|
+
) -> None:
|
|
42
|
+
self.max_retries = max(1, max_retries)
|
|
43
|
+
self.classifier = classifier or BlastRadiusClassifier()
|
|
44
|
+
|
|
45
|
+
def run(
|
|
46
|
+
self,
|
|
47
|
+
run_id: str,
|
|
48
|
+
generator_fn: Callable[[str | None], str],
|
|
49
|
+
gate_fn: Callable[[str], GateResult],
|
|
50
|
+
) -> FactoryRunResult:
|
|
51
|
+
"""Execute the hybrid loop from signal to closed lineage."""
|
|
52
|
+
attempt = 0
|
|
53
|
+
last_feedback: str | None = None
|
|
54
|
+
last_report: BlastRadiusReport | None = None
|
|
55
|
+
|
|
56
|
+
while attempt < self.max_retries:
|
|
57
|
+
attempt += 1
|
|
58
|
+
patch = generator_fn(last_feedback)
|
|
59
|
+
report = self.classifier.assess_patch(patch)
|
|
60
|
+
last_report = report
|
|
61
|
+
|
|
62
|
+
gate_result = gate_fn(patch)
|
|
63
|
+
if not gate_result.passed:
|
|
64
|
+
last_feedback = gate_result.diagnostics
|
|
65
|
+
continue
|
|
66
|
+
|
|
67
|
+
# Deterministic gate passed -> Generate cryptographic Ed25519 provenance
|
|
68
|
+
priv_pem, pub_pem = generate_ed25519_keypair()
|
|
69
|
+
patch_digest = hashlib.sha256(patch.encode("utf-8")).hexdigest()
|
|
70
|
+
provenance_payload = (
|
|
71
|
+
f"run_id:{run_id};lineage:{report.lineage};digest:{patch_digest}".encode()
|
|
72
|
+
)
|
|
73
|
+
signature = sign_payload_ed25519(provenance_payload, priv_pem)
|
|
74
|
+
|
|
75
|
+
if report.lineage == FactoryLineage.LINEAGE_A:
|
|
76
|
+
# Level 4: Contained -> Auto-ships to production
|
|
77
|
+
return FactoryRunResult(
|
|
78
|
+
run_id=run_id,
|
|
79
|
+
lineage=FactoryLineage.LINEAGE_A,
|
|
80
|
+
status=HybridLoopState.PASSED,
|
|
81
|
+
iterations=attempt,
|
|
82
|
+
blast_radius=report,
|
|
83
|
+
provenance_signature=signature,
|
|
84
|
+
provenance_key=pub_pem,
|
|
85
|
+
shipped_to_production=True,
|
|
86
|
+
operator_approval_required=False,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# Level 3: Breaking -> Ephemeral environment passed, awaiting operator gate
|
|
90
|
+
return FactoryRunResult(
|
|
91
|
+
run_id=run_id,
|
|
92
|
+
lineage=FactoryLineage.LINEAGE_B,
|
|
93
|
+
status=HybridLoopState.PASSED,
|
|
94
|
+
iterations=attempt,
|
|
95
|
+
blast_radius=report,
|
|
96
|
+
provenance_signature=signature,
|
|
97
|
+
provenance_key=pub_pem,
|
|
98
|
+
shipped_to_production=False,
|
|
99
|
+
operator_approval_required=True,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
# Max retries exceeded -> Route to human exception queue
|
|
103
|
+
fallback_report = last_report or BlastRadiusReport(
|
|
104
|
+
risk_level=RiskLevel.HIGH,
|
|
105
|
+
lineage=FactoryLineage.LINEAGE_B,
|
|
106
|
+
is_contained=False,
|
|
107
|
+
rationale="Run exceeded maximum retry iterations without passing verification.",
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
return FactoryRunResult(
|
|
111
|
+
run_id=run_id,
|
|
112
|
+
lineage=fallback_report.lineage,
|
|
113
|
+
status=HybridLoopState.EXCEPTION_QUEUED,
|
|
114
|
+
iterations=attempt,
|
|
115
|
+
blast_radius=fallback_report,
|
|
116
|
+
diagnostic_message=last_feedback or "Max retries exceeded",
|
|
117
|
+
shipped_to_production=False,
|
|
118
|
+
operator_approval_required=False,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
def operator_approve(self, result: FactoryRunResult) -> FactoryRunResult:
|
|
122
|
+
"""Human operator approves a Lineage B run for production shipment."""
|
|
123
|
+
return FactoryRunResult(
|
|
124
|
+
run_id=result.run_id,
|
|
125
|
+
lineage=result.lineage,
|
|
126
|
+
status=result.status,
|
|
127
|
+
iterations=result.iterations,
|
|
128
|
+
blast_radius=result.blast_radius,
|
|
129
|
+
provenance_signature=result.provenance_signature,
|
|
130
|
+
provenance_key=result.provenance_key,
|
|
131
|
+
diagnostic_message=result.diagnostic_message,
|
|
132
|
+
shipped_to_production=True,
|
|
133
|
+
operator_approval_required=False,
|
|
134
|
+
)
|