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,254 @@
1
+ """Deterministic Python AST analysis for modified entities, imports, and calls."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import textwrap
7
+ from collections.abc import Callable, Iterable
8
+
9
+ from patchproof.models.ast import (
10
+ ASTAnalysisReport,
11
+ ASTEntity,
12
+ EntityType,
13
+ FileASTReport,
14
+ )
15
+ from patchproof.models.patch import CanonicalPatch, FileDelta
16
+
17
+
18
+ class _EntityVisitor(ast.NodeVisitor):
19
+ """AST visitor extracting class and function boundaries with line numbers."""
20
+
21
+ def __init__(self) -> None:
22
+ self.entities: list[ASTEntity] = []
23
+ self.class_stack: list[str] = []
24
+ self.function_depth: int = 0
25
+
26
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
27
+ end_line = getattr(node, "end_lineno", node.lineno)
28
+ current_class = self.class_stack[-1] if self.class_stack else None
29
+ entity = ASTEntity(
30
+ name=node.name,
31
+ entity_type=EntityType.CLASS,
32
+ parent_class=current_class,
33
+ start_line=node.lineno,
34
+ end_line=end_line,
35
+ )
36
+ self.entities.append(entity)
37
+
38
+ self.class_stack.append(node.name)
39
+ self.generic_visit(node)
40
+ self.class_stack.pop()
41
+
42
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
43
+ self._record_func(node)
44
+
45
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
46
+ self._record_func(node)
47
+
48
+ def _record_func(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
49
+ end_line = getattr(node, "end_lineno", node.lineno)
50
+ if self.class_stack and self.function_depth == 0:
51
+ ent_type = EntityType.METHOD
52
+ parent_class = self.class_stack[-1]
53
+ else:
54
+ ent_type = EntityType.FUNCTION
55
+ parent_class = None
56
+
57
+ entity = ASTEntity(
58
+ name=node.name,
59
+ entity_type=ent_type,
60
+ parent_class=parent_class,
61
+ start_line=node.lineno,
62
+ end_line=end_line,
63
+ )
64
+ self.entities.append(entity)
65
+ self.function_depth += 1
66
+ self.generic_visit(node)
67
+ self.function_depth -= 1
68
+
69
+
70
+ def _extract_imports(tree: ast.AST) -> tuple[str, ...]:
71
+ """Extract all static imported module names from an AST."""
72
+ imported_modules: set[str] = set()
73
+ for node in ast.walk(tree):
74
+ if isinstance(node, ast.Import):
75
+ for alias in node.names:
76
+ imported_modules.add(alias.name)
77
+ elif isinstance(node, ast.ImportFrom):
78
+ dots = "." * (node.level or 0)
79
+ if node.module:
80
+ imported_modules.add(f"{dots}{node.module}")
81
+ elif dots:
82
+ imported_modules.add(dots)
83
+ return tuple(sorted(imported_modules))
84
+
85
+
86
+ def _extract_call_name(node: ast.Call) -> str | None:
87
+ """Extract string identifier from a Call node."""
88
+ func = node.func
89
+ if isinstance(func, ast.Name):
90
+ return func.id
91
+ if isinstance(func, ast.Attribute):
92
+ return func.attr
93
+ return None
94
+
95
+
96
+ def _extract_calls_in_ranges(tree: ast.AST, ranges: Iterable[tuple[int, int]]) -> tuple[str, ...]:
97
+ """Extract syntactic function/method calls whose line numbers fall within modified spans."""
98
+ calls: set[str] = set()
99
+ for node in ast.walk(tree):
100
+ if isinstance(node, ast.Call):
101
+ lineno = getattr(node, "lineno", None)
102
+ if lineno is None:
103
+ continue
104
+ for start, end in ranges:
105
+ if start <= lineno <= end:
106
+ name = _extract_call_name(node)
107
+ if name:
108
+ calls.add(name)
109
+ break
110
+ return tuple(sorted(calls))
111
+
112
+
113
+ def _extract_calls_from_text(code_fragment: str) -> set[str]:
114
+ """Extract calls from an arbitrary snippet of code."""
115
+ calls: set[str] = set()
116
+ try:
117
+ tree = ast.parse(code_fragment)
118
+ for node in ast.walk(tree):
119
+ if isinstance(node, ast.Call):
120
+ name = _extract_call_name(node)
121
+ if name:
122
+ calls.add(name)
123
+ except SyntaxError:
124
+ pass
125
+ return calls
126
+
127
+
128
+ def _spans_overlap(s1: int, e1: int, s2: int, e2: int) -> bool:
129
+ """Return True if span [s1, e1] overlaps with [s2, e2]."""
130
+ return not (e1 < s2 or s1 > e2)
131
+
132
+
133
+ def analyze_python_source(
134
+ source_code: str,
135
+ modified_ranges: list[tuple[int, int]],
136
+ file_path: str = "",
137
+ ) -> FileASTReport:
138
+ """Deterministically analyze Python source code against a set of modified line spans.
139
+
140
+ Args:
141
+ source_code: Raw Python source code string.
142
+ modified_ranges: List of (start_line, end_line) spans affected by changes.
143
+ file_path: Optional repository-relative path of the analyzed file.
144
+
145
+ Returns:
146
+ FileASTReport: Report detailing modified entities, static imports, and calls.
147
+ """
148
+ try:
149
+ tree = ast.parse(source_code, filename=file_path or "<string>")
150
+ except SyntaxError:
151
+ return FileASTReport(
152
+ path=file_path,
153
+ modified_entities=(),
154
+ imported_modules=(),
155
+ syntactic_calls=(),
156
+ )
157
+
158
+ visitor = _EntityVisitor()
159
+ visitor.visit(tree)
160
+
161
+ intersected_entities: list[ASTEntity] = []
162
+ for entity in visitor.entities:
163
+ for m_start, m_end in modified_ranges:
164
+ if _spans_overlap(entity.start_line, entity.end_line, m_start, m_end):
165
+ intersected_entities.append(entity)
166
+ break
167
+
168
+ imports = _extract_imports(tree)
169
+ calls = _extract_calls_in_ranges(tree, modified_ranges)
170
+
171
+ return FileASTReport(
172
+ path=file_path,
173
+ modified_entities=tuple(intersected_entities),
174
+ imported_modules=imports,
175
+ syntactic_calls=calls,
176
+ )
177
+
178
+
179
+ def extract_delta_line_ranges(delta: FileDelta, pre_patch: bool = False) -> list[tuple[int, int]]:
180
+ """Calculate the line ranges affected by a FileDelta.
181
+
182
+ Args:
183
+ delta: File delta containing hunks.
184
+ pre_patch: If True, extract line coordinates from the pre-patch file
185
+ (old_start, old_lines). Otherwise, extract post-patch coordinates
186
+ (new_start, new_lines).
187
+ """
188
+ ranges: list[tuple[int, int]] = []
189
+ for hunk in delta.hunks:
190
+ if pre_patch:
191
+ start = hunk.old_start if hunk.old_start > 0 else 1
192
+ length = hunk.old_lines if hunk.old_lines > 0 else 1
193
+ else:
194
+ start = hunk.new_start if hunk.new_start > 0 else 1
195
+ length = hunk.new_lines if hunk.new_lines > 0 else 1
196
+ ranges.append((start, start + length - 1))
197
+ return ranges
198
+
199
+
200
+ def analyze_patch_ast(
201
+ patch: CanonicalPatch,
202
+ source_resolver: Callable[[str], str | None] | None = None,
203
+ pre_patch: bool = False,
204
+ ) -> ASTAnalysisReport:
205
+ """Analyze all Python files in a CanonicalPatch against available source code.
206
+
207
+ Args:
208
+ patch: Canonical patch to inspect.
209
+ source_resolver: Optional callable `(path: str) -> source_code | None`.
210
+ pre_patch: If True, interpret source code and hunk line coordinates in pre-patch state.
211
+
212
+ Returns:
213
+ ASTAnalysisReport: Consolidated AST report across all patch files.
214
+ """
215
+ file_reports: list[FileASTReport] = []
216
+
217
+ for delta in patch.file_deltas:
218
+ if not delta.path.endswith(".py"):
219
+ continue
220
+
221
+ ranges = extract_delta_line_ranges(delta, pre_patch=pre_patch)
222
+ source = source_resolver(delta.path) if source_resolver else None
223
+
224
+ # Extract calls introduced in added hunk lines (dedented for valid AST parsing)
225
+ added_lines = [
226
+ line[1:]
227
+ for hunk in delta.hunks
228
+ for line in hunk.lines
229
+ if line.startswith("+") and not line.startswith("+++")
230
+ ]
231
+ added_snippet = textwrap.dedent("\n".join(added_lines))
232
+ patch_introduced_calls = _extract_calls_from_text(added_snippet)
233
+
234
+ if source is not None:
235
+ rep = analyze_python_source(source, ranges, file_path=delta.path)
236
+ all_file_calls = tuple(sorted(set(rep.syntactic_calls) | patch_introduced_calls))
237
+ merged_rep = FileASTReport(
238
+ path=rep.path,
239
+ modified_entities=rep.modified_entities,
240
+ imported_modules=rep.imported_modules,
241
+ syntactic_calls=all_file_calls,
242
+ )
243
+ file_reports.append(merged_rep)
244
+ else:
245
+ file_reports.append(
246
+ FileASTReport(
247
+ path=delta.path,
248
+ modified_entities=(),
249
+ imported_modules=(),
250
+ syntactic_calls=tuple(sorted(patch_introduced_calls)),
251
+ )
252
+ )
253
+
254
+ return ASTAnalysisReport(file_reports=tuple(file_reports))
@@ -0,0 +1,78 @@
1
+ """Polyglot repository stack detector.
2
+
3
+ Auto-detects project language stack (Python, Node.js, Go, Rust),
4
+ associated runner images, and default test commands.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import pathlib
10
+ from dataclasses import dataclass
11
+ from enum import StrEnum
12
+
13
+
14
+ class ProjectKind(StrEnum):
15
+ """Supported project language ecosystems."""
16
+
17
+ PYTHON = "python"
18
+ NODE = "node"
19
+ GO = "go"
20
+ RUST = "rust"
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class ProjectProfile:
25
+ """Detected project configuration profile."""
26
+
27
+ kind: ProjectKind
28
+ default_image: str | None
29
+ default_test_command: tuple[str, ...]
30
+
31
+
32
+ DEFAULT_PROFILES: dict[ProjectKind, ProjectProfile] = {
33
+ ProjectKind.PYTHON: ProjectProfile(
34
+ kind=ProjectKind.PYTHON,
35
+ default_image="patchproof-runner-python:3.11",
36
+ default_test_command=("pytest", "-q"),
37
+ ),
38
+ ProjectKind.NODE: ProjectProfile(
39
+ kind=ProjectKind.NODE,
40
+ default_image=None,
41
+ default_test_command=("npm", "test"),
42
+ ),
43
+ ProjectKind.GO: ProjectProfile(
44
+ kind=ProjectKind.GO,
45
+ default_image=None,
46
+ default_test_command=("go", "test", "./..."),
47
+ ),
48
+ ProjectKind.RUST: ProjectProfile(
49
+ kind=ProjectKind.RUST,
50
+ default_image=None,
51
+ default_test_command=("cargo", "test"),
52
+ ),
53
+ }
54
+
55
+ PYTHON_MARKERS = ("pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "pytest.ini")
56
+ NODE_MARKERS = ("package.json", "tsconfig.json")
57
+ GO_MARKERS = ("go.mod", "go.sum")
58
+ RUST_MARKERS = ("Cargo.toml", "Cargo.lock")
59
+
60
+
61
+ def detect_project_stack(repo_path: pathlib.Path | str) -> ProjectProfile:
62
+ """Inspect repository root and return the matching ProjectProfile."""
63
+ root = pathlib.Path(repo_path).resolve()
64
+
65
+ if any((root / m).is_file() for m in RUST_MARKERS):
66
+ return DEFAULT_PROFILES[ProjectKind.RUST]
67
+
68
+ if any((root / m).is_file() for m in GO_MARKERS):
69
+ return DEFAULT_PROFILES[ProjectKind.GO]
70
+
71
+ if any((root / m).is_file() for m in PYTHON_MARKERS):
72
+ return DEFAULT_PROFILES[ProjectKind.PYTHON]
73
+
74
+ if any((root / m).is_file() for m in NODE_MARKERS):
75
+ return DEFAULT_PROFILES[ProjectKind.NODE]
76
+
77
+ # Default fallback
78
+ return DEFAULT_PROFILES[ProjectKind.PYTHON]
@@ -0,0 +1,298 @@
1
+ """Git provider for extracting uncommitted changes, HEAD diffs, and installing hooks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import pathlib
7
+ import subprocess
8
+ import tarfile
9
+
10
+ from patchproof.exceptions import GitRepositoryError, NoChangesDetectedError, SandboxSecurityError
11
+
12
+ GIT_COMMAND_TIMEOUT_SECONDS = 15.0
13
+ MAX_UNTRACKED_FILE_BYTES = 5 * 1024 * 1024 # 5MB safety limit per untracked file
14
+
15
+
16
+ def is_git_repository(repo_path: pathlib.Path | str) -> bool:
17
+ """Check if target directory is inside an active Git worktree.
18
+
19
+ Never executes shell=True; handles missing git binary gracefully.
20
+ """
21
+ resolved = pathlib.Path(repo_path).resolve()
22
+ try:
23
+ res = subprocess.run(
24
+ ["git", "rev-parse", "--is-inside-work-tree"],
25
+ cwd=str(resolved),
26
+ capture_output=True,
27
+ text=True,
28
+ shell=False,
29
+ close_fds=True,
30
+ timeout=GIT_COMMAND_TIMEOUT_SECONDS,
31
+ )
32
+ return res.returncode == 0 and res.stdout.strip() == "true"
33
+ except (subprocess.SubprocessError, OSError):
34
+ return False
35
+
36
+
37
+ def get_untracked_files(repo_path: pathlib.Path | str) -> tuple[str, ...]:
38
+ """Capture list of untracked files not ignored by .gitignore in working tree.
39
+
40
+ Returns tuple of relative POSIX file paths.
41
+ """
42
+ resolved = pathlib.Path(repo_path).resolve()
43
+ try:
44
+ res = subprocess.run(
45
+ ["git", "ls-files", "--others", "--exclude-standard"],
46
+ cwd=str(resolved),
47
+ capture_output=True,
48
+ text=True,
49
+ shell=False,
50
+ close_fds=True,
51
+ timeout=GIT_COMMAND_TIMEOUT_SECONDS,
52
+ )
53
+ except (subprocess.SubprocessError, OSError):
54
+ return ()
55
+
56
+ if res.returncode != 0:
57
+ return ()
58
+
59
+ files: list[str] = []
60
+ for line in res.stdout.splitlines():
61
+ cleaned = line.strip()
62
+ if cleaned:
63
+ files.append(cleaned.replace("\\", "/"))
64
+ return tuple(files)
65
+
66
+
67
+ def export_git_tree(
68
+ repo_path: pathlib.Path | str,
69
+ ref: str,
70
+ dest_dir: pathlib.Path | str,
71
+ subtree: str | None = None,
72
+ ) -> bool:
73
+ """Export pristine git tree at ref into dest_dir without touching working copy.
74
+
75
+ Guarantees baseline purity by extracting committed files directly from Git archive.
76
+ Rejects and fails closed on any path traversal attacks inside tar archive members.
77
+
78
+ Raises:
79
+ SandboxSecurityError: If tar archive or subtree contains path traversal sequences.
80
+ """
81
+ resolved_repo = pathlib.Path(repo_path).resolve()
82
+ dest_root = pathlib.Path(dest_dir).resolve()
83
+ dest_root.mkdir(parents=True, exist_ok=True)
84
+
85
+ archive_cmd = ["git", "archive", ref]
86
+ if subtree:
87
+ clean_sub = subtree.replace("\\", "/").strip("/")
88
+ if ".." in clean_sub or clean_sub.startswith("/"):
89
+ raise SandboxSecurityError(f"Path traversal detected in export subtree: {subtree}")
90
+ archive_cmd.append(f"{clean_sub}/")
91
+
92
+ try:
93
+ res = subprocess.run(
94
+ archive_cmd,
95
+ cwd=str(resolved_repo),
96
+ capture_output=True,
97
+ shell=False,
98
+ close_fds=True,
99
+ timeout=GIT_COMMAND_TIMEOUT_SECONDS,
100
+ )
101
+ except (subprocess.SubprocessError, OSError):
102
+ return False
103
+
104
+ if res.returncode != 0 or not res.stdout:
105
+ return False
106
+
107
+ tar_bytes = res.stdout
108
+ try:
109
+ with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:*") as tar:
110
+ for member in tar.getmembers():
111
+ target_path = (dest_root / member.name).resolve()
112
+ try:
113
+ target_path.relative_to(dest_root)
114
+ except ValueError as err:
115
+ raise SandboxSecurityError(
116
+ f"Tar traversal detected in git archive member: '{member.name}' "
117
+ f"points outside destination root to '{target_path}'"
118
+ ) from err
119
+ if hasattr(tarfile, "data_filter"):
120
+ tar.extractall(dest_root, filter="data")
121
+ else:
122
+ tar.extractall(dest_root)
123
+ return True
124
+ except SandboxSecurityError:
125
+ raise
126
+ except Exception:
127
+ return False
128
+
129
+
130
+ def get_uncommitted_diff(
131
+ repo_path: pathlib.Path | str,
132
+ include_untracked: bool = True,
133
+ ) -> str:
134
+ """Capture uncommitted changes (both staged and unstaged) in working tree.
135
+
136
+ Optionally includes newly created untracked files as unified diff additions against /dev/null.
137
+
138
+ Raises:
139
+ GitRepositoryError: If path is not a git repository.
140
+ NoChangesDetectedError: If working tree is clean.
141
+ """
142
+ resolved = pathlib.Path(repo_path).resolve()
143
+ if not is_git_repository(resolved):
144
+ raise GitRepositoryError(f"Target path is not a Git repository: {resolved}")
145
+
146
+ # First attempt: git diff HEAD (captures both staged and unstaged vs last commit)
147
+ res = subprocess.run(
148
+ ["git", "diff", "HEAD"],
149
+ cwd=str(resolved),
150
+ capture_output=True,
151
+ text=True,
152
+ shell=False,
153
+ close_fds=True,
154
+ timeout=GIT_COMMAND_TIMEOUT_SECONDS,
155
+ )
156
+
157
+ # Fallback to plain git diff if HEAD does not exist (new repository before first commit)
158
+ if res.returncode != 0:
159
+ res = subprocess.run(
160
+ ["git", "diff"],
161
+ cwd=str(resolved),
162
+ capture_output=True,
163
+ text=True,
164
+ shell=False,
165
+ close_fds=True,
166
+ timeout=GIT_COMMAND_TIMEOUT_SECONDS,
167
+ )
168
+
169
+ if res.returncode != 0:
170
+ err_msg = res.stderr.strip() or f"exit code {res.returncode}"
171
+ raise GitRepositoryError(f"Failed to capture git diff: {err_msg}")
172
+
173
+ diff_text = res.stdout
174
+
175
+ if include_untracked:
176
+ untracked = get_untracked_files(resolved)
177
+ for rel_file in untracked:
178
+ file_path = resolved / rel_file
179
+ if file_path.is_file():
180
+ try:
181
+ stat_res = file_path.stat()
182
+ if stat_res.st_size <= MAX_UNTRACKED_FILE_BYTES:
183
+ content = file_path.read_text(encoding="utf-8", errors="replace")
184
+ lines = content.splitlines(keepends=True)
185
+ line_count = len(lines)
186
+ diff_parts = [
187
+ f"diff --git a/{rel_file} b/{rel_file}",
188
+ "new file mode 100644",
189
+ "--- /dev/null",
190
+ f"+++ b/{rel_file}",
191
+ f"@@ -0,0 +1,{line_count} @@",
192
+ ]
193
+ for l_str in lines:
194
+ clean_line = l_str.rstrip("\r\n")
195
+ diff_parts.append(f"+{clean_line}")
196
+ diff_text += "\n" + "\n".join(diff_parts) + "\n"
197
+ except (OSError, UnicodeDecodeError):
198
+ continue
199
+
200
+ if not diff_text or not diff_text.strip():
201
+ raise NoChangesDetectedError(f"No uncommitted changes detected in repository: {resolved}")
202
+
203
+ return diff_text
204
+
205
+
206
+ def get_head_diff(repo_path: pathlib.Path | str) -> str:
207
+ """Capture changes introduced by the most recent HEAD commit.
208
+
209
+ Raises:
210
+ GitRepositoryError: If path is not a git repository or no commits exist.
211
+ NoChangesDetectedError: If HEAD commit has no diff.
212
+ """
213
+ resolved = pathlib.Path(repo_path).resolve()
214
+ if not is_git_repository(resolved):
215
+ raise GitRepositoryError(f"Target path is not a Git repository: {resolved}")
216
+
217
+ res = subprocess.run(
218
+ ["git", "show", "--format=", "HEAD"],
219
+ cwd=str(resolved),
220
+ capture_output=True,
221
+ text=True,
222
+ shell=False,
223
+ close_fds=True,
224
+ timeout=GIT_COMMAND_TIMEOUT_SECONDS,
225
+ )
226
+
227
+ if res.returncode != 0:
228
+ err_msg = res.stderr.strip() or f"exit code {res.returncode}"
229
+ raise GitRepositoryError(f"Failed to retrieve HEAD diff: {err_msg}")
230
+
231
+ diff_text = res.stdout
232
+ if not diff_text or not diff_text.strip():
233
+ raise NoChangesDetectedError(
234
+ f"No changes detected in HEAD commit for repository: {resolved}"
235
+ )
236
+
237
+ return diff_text
238
+
239
+
240
+ def install_pre_commit_hook(repo_path: pathlib.Path | str) -> pathlib.Path:
241
+ """Install .git/hooks/pre-commit verification hook in target repository.
242
+
243
+ Supports standard Git repositories, Git worktrees, and submodules.
244
+
245
+ Raises:
246
+ GitRepositoryError: If repo_path is not a valid Git repository.
247
+ """
248
+ resolved = pathlib.Path(repo_path).resolve()
249
+ git_entry = resolved / ".git"
250
+ if not git_entry.exists() and not is_git_repository(resolved):
251
+ raise GitRepositoryError(f"Not a Git repository: {resolved}")
252
+
253
+ # Use git rev-parse to accurately resolve hooks path
254
+ # across standard repos, worktrees, and submodules
255
+ hooks_rel_path: str | None = None
256
+ try:
257
+ res = subprocess.run(
258
+ ["git", "rev-parse", "--git-path", "hooks"],
259
+ cwd=resolved,
260
+ capture_output=True,
261
+ text=True,
262
+ shell=False,
263
+ close_fds=True,
264
+ timeout=10,
265
+ )
266
+ if res.returncode == 0 and res.stdout.strip():
267
+ hooks_rel_path = res.stdout.strip()
268
+ except Exception:
269
+ pass
270
+
271
+ if hooks_rel_path:
272
+ hooks_dir = (resolved / hooks_rel_path).resolve()
273
+ else:
274
+ # Fallback to standard .git/hooks directory
275
+ base_git = git_entry if git_entry.is_dir() else (resolved / ".git")
276
+ hooks_dir = base_git / "hooks"
277
+
278
+ hooks_dir.mkdir(parents=True, exist_ok=True)
279
+
280
+ hook_file = hooks_dir / "pre-commit"
281
+ hook_script = (
282
+ "#!/bin/sh\n"
283
+ "# PatchProof Pre-Commit Verification Hook\n"
284
+ "# Automatically verifies uncommitted changes in isolated sandbox\n"
285
+ "set -e\n"
286
+ "patchproof verify --git\n"
287
+ )
288
+
289
+ hook_file.write_text(hook_script, encoding="utf-8")
290
+
291
+ # On POSIX systems, ensure executable permission
292
+ try:
293
+ current_mode = hook_file.stat().st_mode
294
+ hook_file.chmod(current_mode | 0o755)
295
+ except OSError:
296
+ pass
297
+
298
+ return hook_file