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,167 @@
1
+ """Polyglot Anti-Cheat and Runtime Assertion Guard subsystem for TypeScript and JavaScript.
2
+
3
+ Provides lexical analysis, test tampering detection, and Jest/Vitest runtime assertion tracking
4
+ for Node/TypeScript environments.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ from patchproof.core.anti_cheat import (
12
+ TamperingViolation,
13
+ TamperingViolationType,
14
+ )
15
+ from patchproof.models.patch import FileDelta
16
+
17
+ JS_TS_TEST_PATTERN = re.compile(
18
+ r'(?:^|\s)(?:it|test|describe)(?:\.(?:skip|only))?\s*\(\s*["\'`]([^"\'`]+)["\'`]',
19
+ re.MULTILINE,
20
+ )
21
+ JS_TS_SUPPRESSION_PATTERN = re.compile(
22
+ r'(?:^|\s)(?:(?:it|test|describe)\.skip|x(?:it|test|describe))\s*\(\s*["\'`]([^"\'`]+)["\'`]',
23
+ re.MULTILINE,
24
+ )
25
+ JS_TS_ASSERTION_PATTERN = re.compile(
26
+ r'(?:expect\s*\(|assert\s*\(|\.assert[a-zA-Z0-9_]*\s*\()',
27
+ re.MULTILINE,
28
+ )
29
+
30
+
31
+ def extract_js_ts_tests(content: str) -> set[str]:
32
+ """Extract test names defined with it(), test(), or describe()."""
33
+ return set(JS_TS_TEST_PATTERN.findall(content))
34
+
35
+
36
+ def extract_js_ts_suppressions(content: str) -> set[str]:
37
+ """Extract names of skipped tests defined with it.skip(), xit(), etc."""
38
+ return set(JS_TS_SUPPRESSION_PATTERN.findall(content))
39
+
40
+
41
+ def count_js_ts_assertions(content: str) -> int:
42
+ """Count occurrences of expect() and assert() in JS/TS content."""
43
+ return len(JS_TS_ASSERTION_PATTERN.findall(content))
44
+
45
+
46
+ def audit_js_ts_test_content(
47
+ delta: FileDelta,
48
+ original_text: str,
49
+ patched_text: str,
50
+ ) -> tuple[list[TamperingViolation], int, int, int]:
51
+ """Audit differences between baseline and patched content of a JS/TS test file.
52
+
53
+ Returns:
54
+ tuple[list[TamperingViolation], int, int, int]:
55
+ (violations, assertion_delta, tests_deleted, tests_suppressed)
56
+ """
57
+ violations: list[TamperingViolation] = []
58
+ tests_deleted = 0
59
+ tests_suppressed = 0
60
+
61
+ orig_tests = extract_js_ts_tests(original_text)
62
+ patched_tests = extract_js_ts_tests(patched_text)
63
+
64
+ orig_suppressions = extract_js_ts_suppressions(original_text)
65
+ patched_suppressions = extract_js_ts_suppressions(patched_text)
66
+
67
+ orig_asserts = count_js_ts_assertions(original_text)
68
+ patched_asserts = count_js_ts_assertions(patched_text)
69
+ assertion_delta = patched_asserts - orig_asserts
70
+
71
+ # 1. Check assertion count drop
72
+ if assertion_delta < 0:
73
+ violations.append(
74
+ TamperingViolation(
75
+ violation_type=TamperingViolationType.ASSERTION_COUNT_REDUCED,
76
+ file_path=delta.path,
77
+ details=(
78
+ f"Test assertion count decreased from {orig_asserts} "
79
+ f"to {patched_asserts} (delta: {assertion_delta})"
80
+ ),
81
+ )
82
+ )
83
+
84
+ # 2. Check for deleted tests
85
+ for test_name in orig_tests:
86
+ if test_name not in patched_tests and test_name not in patched_suppressions:
87
+ tests_deleted += 1
88
+ violations.append(
89
+ TamperingViolation(
90
+ violation_type=TamperingViolationType.TEST_FUNCTION_DELETED,
91
+ file_path=delta.path,
92
+ target_name=test_name,
93
+ details=f"Test '{test_name}' was deleted in patched test file",
94
+ )
95
+ )
96
+
97
+ # 3. Check for newly injected suppressions
98
+ new_suppressions = patched_suppressions - orig_suppressions
99
+ for test_name in sorted(new_suppressions):
100
+ tests_suppressed += 1
101
+ violations.append(
102
+ TamperingViolation(
103
+ violation_type=TamperingViolationType.TEST_SUPPRESSION_INJECTED,
104
+ file_path=delta.path,
105
+ target_name=test_name,
106
+ details=f"Test '{test_name}' was suppressed (skip/xfail injected)",
107
+ )
108
+ )
109
+
110
+ return violations, assertion_delta, tests_deleted, tests_suppressed
111
+
112
+
113
+ def generate_jest_runtime_guard_script() -> str:
114
+ """Generate Node.js / JavaScript setup script for Jest/Vitest runtime assertion tracking."""
115
+ return """/**
116
+ * PatchProof Jest/Vitest Runtime Assertion Guard setup script.
117
+ * Auto-injected into container test runner to collect assertion metrics.
118
+ */
119
+ const MARKER_PREFIX = "__PATCHPROOF_RUNTIME_PROFILE__=";
120
+
121
+ let executedAssertions = 0;
122
+ const assertionsByTest = {};
123
+ let currentTestName = null;
124
+
125
+ if (typeof beforeEach === "function") {
126
+ beforeEach(() => {
127
+ try {
128
+ const state = expect.getState();
129
+ currentTestName = state.currentTestName || "unknown_test";
130
+ if (!assertionsByTest[currentTestName]) {
131
+ assertionsByTest[currentTestName] = 0;
132
+ }
133
+ } catch (e) {}
134
+ });
135
+ }
136
+
137
+ // Wrap global expect to track dynamic assertion calls
138
+ if (typeof global !== "undefined" && global.expect) {
139
+ const originalExpect = global.expect;
140
+ const expectProxy = new Proxy(originalExpect, {
141
+ apply(target, thisArg, argArray) {
142
+ executedAssertions += 1;
143
+ if (currentTestName) {
144
+ assertionsByTest[currentTestName] = (assertionsByTest[currentTestName] || 0) + 1;
145
+ }
146
+ return Reflect.apply(target, thisArg, argArray);
147
+ }
148
+ });
149
+ global.expect = expectProxy;
150
+ }
151
+
152
+ const emitProfile = () => {
153
+ const payload = JSON.stringify({
154
+ collected_count: Object.keys(assertionsByTest).length,
155
+ executed_count: Object.keys(assertionsByTest).length,
156
+ executed_assertions: executedAssertions,
157
+ assertions_by_test: assertionsByTest,
158
+ });
159
+ process.stdout.write(`\\n${MARKER_PREFIX}${payload}\\n`);
160
+ };
161
+
162
+ if (typeof afterAll === "function") {
163
+ afterAll(emitProfile);
164
+ } else {
165
+ process.on("exit", emitProfile);
166
+ }
167
+ """
@@ -0,0 +1,188 @@
1
+ """Dynamic Runtime Assertion Auditor and Pytest Injected Guard subsystem.
2
+
3
+ Provides deterministic runtime tracing of assertions and test executions
4
+ to catch metaprogramming, dynamic test suppression, and assertion stripping.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import logging
11
+ from typing import Any
12
+
13
+ from pydantic import BaseModel, ConfigDict, Field
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ MARKER_PREFIX = "__PATCHPROOF_RUNTIME_PROFILE__="
18
+
19
+
20
+ class RuntimeProfile(BaseModel):
21
+ """Immutable telemetry profile capturing dynamic runtime test execution metrics."""
22
+
23
+ model_config = ConfigDict(frozen=True)
24
+
25
+ collected_count: int = Field(ge=0, description="Total number of test items discovered")
26
+ executed_count: int = Field(ge=0, description="Total number of test items run to completion")
27
+ executed_assertions: int = Field(
28
+ ge=0, description="Total dynamic assertions executed across test suite"
29
+ )
30
+ assertions_by_test: dict[str, int] = Field(
31
+ default_factory=dict, description="Mapping of test nodeid to executed assertion count"
32
+ )
33
+
34
+
35
+ def generate_runtime_guard_plugin() -> str:
36
+ """Generate self-contained Python source code for the injected pytest runtime guard plugin."""
37
+ return f'''"""Auto-injected PatchProof Runtime Assertion Guard plugin.
38
+
39
+ Collects empirical assertion counts and execution metrics during test execution.
40
+ """
41
+ from __future__ import annotations
42
+
43
+ import json
44
+ import linecache
45
+ import pathlib
46
+ import sys
47
+
48
+ MARKER_PREFIX = "{MARKER_PREFIX}"
49
+
50
+ class RuntimeAssertionTracker:
51
+ def __init__(self) -> None:
52
+ self.assertions: int = 0
53
+ self.by_test: dict[str, int] = {{}}
54
+ self.current_test: str | None = None
55
+ self.current_file: str | None = None
56
+
57
+ def trace(self, frame, event, arg):
58
+ if event == "line":
59
+ filename = frame.f_code.co_filename
60
+ # Restrict tracing to the active test module to exclude pytest/stdlib internals
61
+ is_target = self.current_file and (
62
+ filename == self.current_file or filename.endswith(self.current_file)
63
+ )
64
+ if is_target:
65
+ line = linecache.getline(filename, frame.f_lineno).strip()
66
+ if line.startswith("assert ") or line.startswith("assert(") or ".assert" in line:
67
+ self.assertions += 1
68
+ if self.current_test:
69
+ self.by_test[self.current_test] = self.by_test.get(self.current_test, 0) + 1
70
+ return self.trace
71
+
72
+ tracker = RuntimeAssertionTracker()
73
+
74
+ def pytest_runtest_call(item) -> None:
75
+ tracker.current_test = item.nodeid
76
+ file_path = getattr(item, "path", getattr(item, "fspath", None))
77
+ tracker.current_file = str(file_path) if file_path else None
78
+ sys.settrace(tracker.trace)
79
+
80
+ def pytest_runtest_teardown(item, nextitem) -> None:
81
+ sys.settrace(None)
82
+
83
+ def pytest_sessionfinish(session, exitstatus) -> None:
84
+ collected = len(session.items)
85
+ executed = getattr(session, "testscount", collected)
86
+ data = {{
87
+ "collected_count": collected,
88
+ "executed_count": executed,
89
+ "executed_assertions": tracker.assertions,
90
+ "assertions_by_test": tracker.by_test,
91
+ }}
92
+ payload = json.dumps(data)
93
+ # 1. Output marked payload to stdout for StreamCapture
94
+ sys.stdout.write(f"\\n{{MARKER_PREFIX}}{{payload}}\\n")
95
+ sys.stdout.flush()
96
+
97
+ # 2. Persist to ephemeral container tmpfs as backup
98
+ try:
99
+ tmp_target = pathlib.Path("/tmp/patchproof_runtime_profile.json")
100
+ tmp_target.write_text(payload, encoding="utf-8")
101
+ except OSError:
102
+ pass
103
+ '''
104
+
105
+
106
+ def extract_runtime_profile(stdout: str) -> RuntimeProfile | None:
107
+ """Extract and parse RuntimeProfile from captured container stdout.
108
+
109
+ Returns None if marker is not found or payload is invalid JSON.
110
+ """
111
+ if MARKER_PREFIX not in stdout:
112
+ return None
113
+
114
+ # Find the last marker occurrence in case of multiple runs
115
+ idx = stdout.rfind(MARKER_PREFIX)
116
+ remainder = stdout[idx + len(MARKER_PREFIX) :]
117
+ first_line = remainder.splitlines()[0].strip()
118
+
119
+ try:
120
+ raw_data: Any = json.loads(first_line)
121
+ if not isinstance(raw_data, dict):
122
+ return None
123
+ return RuntimeProfile(
124
+ collected_count=int(raw_data.get("collected_count", 0)),
125
+ executed_count=int(raw_data.get("executed_count", 0)),
126
+ executed_assertions=int(raw_data.get("executed_assertions", 0)),
127
+ assertions_by_test={
128
+ str(k): int(v) for k, v in raw_data.get("assertions_by_test", {}).items()
129
+ },
130
+ )
131
+ except (json.JSONDecodeError, ValueError, TypeError) as err:
132
+ logger.warning("Failed to decode runtime profile payload: %s", err)
133
+ return None
134
+
135
+
136
+ def reconcile_runtime_profiles(
137
+ baseline_profile: RuntimeProfile | None,
138
+ patched_profile: RuntimeProfile | None,
139
+ ) -> tuple[bool, str | None]:
140
+ """Compare runtime execution profiles between baseline and patched containers.
141
+
142
+ Returns:
143
+ tuple[bool, str | None]: (tampering_detected, reason)
144
+ """
145
+ if baseline_profile is None:
146
+ # Baseline didn't produce profile (e.g. non-pytest suite); cannot deduce tampering
147
+ return False, None
148
+
149
+ if patched_profile is None:
150
+ # Baseline had guard active, but patched suite dropped or bypassed it
151
+ return (
152
+ True,
153
+ "Dynamic test tampering detected: Patched test suite suppressed the "
154
+ "PatchProof runtime guard",
155
+ )
156
+
157
+ # Invariant 1: Total executed assertions must not drop
158
+ if patched_profile.executed_assertions < baseline_profile.executed_assertions:
159
+ drop = baseline_profile.executed_assertions - patched_profile.executed_assertions
160
+ return (
161
+ True,
162
+ f"Dynamic test tampering detected: {drop} fewer assertion(s) executed at runtime "
163
+ f"(baseline: {baseline_profile.executed_assertions}, "
164
+ f"patched: {patched_profile.executed_assertions})",
165
+ )
166
+
167
+ # Invariant 2: Per-test assertion counts must not drop for pre-existing tests
168
+ for test_name, b_count in baseline_profile.assertions_by_test.items():
169
+ if test_name in patched_profile.assertions_by_test:
170
+ p_count = patched_profile.assertions_by_test[test_name]
171
+ if p_count < b_count:
172
+ return (
173
+ True,
174
+ f"Dynamic test tampering detected in '{test_name}': assertion count dropped "
175
+ f"from {b_count} to {p_count}",
176
+ )
177
+
178
+ # Invariant 3: Total executed test count must not drop
179
+ if patched_profile.executed_count < baseline_profile.executed_count:
180
+ drop = baseline_profile.executed_count - patched_profile.executed_count
181
+ return (
182
+ True,
183
+ f"Dynamic test tampering detected: {drop} fewer test(s) executed at runtime "
184
+ f"(baseline: {baseline_profile.executed_count}, "
185
+ f"patched: {patched_profile.executed_count})",
186
+ )
187
+
188
+ return False, None
@@ -0,0 +1,222 @@
1
+ """Aider SEARCH/REPLACE block parsing and normalization into canonical patch representations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from patchproof.exceptions import InvalidPatchFormatError
8
+ from patchproof.models.patch import (
9
+ CanonicalPatch,
10
+ ChangeType,
11
+ FileDelta,
12
+ PatchHunk,
13
+ PatchType,
14
+ )
15
+
16
+ SEARCH_START = "<<<<<<< SEARCH"
17
+ DIVIDER = "======="
18
+ REPLACE_END = ">>>>>>> REPLACE"
19
+
20
+
21
+ def _clean_filename(line: str) -> str:
22
+ """Extract and sanitize filename preceding a search/replace block."""
23
+ cleaned = line.strip()
24
+ cleaned = cleaned.strip("`'\"#* ")
25
+ if ":" in cleaned:
26
+ parts = cleaned.split(":", 1)
27
+ if parts[0].strip().lower() in ("file", "filename", "path"):
28
+ cleaned = parts[1].strip().strip("`'\" ")
29
+ return cleaned
30
+
31
+
32
+ class _SearchReplaceParser:
33
+ """State-machine parser for Aider-style SEARCH/REPLACE edit blocks."""
34
+
35
+ def __init__(self, raw_text: str) -> None:
36
+ self.raw_text = raw_text.replace("\r\n", "\n").replace("\r", "\n")
37
+ self.lines = self.raw_text.split("\n")
38
+ if self.lines and self.lines[-1] == "":
39
+ self.lines.pop()
40
+ self.idx = 0
41
+ self.total = len(self.lines)
42
+
43
+ def parse(self) -> CanonicalPatch:
44
+ if not self.raw_text.strip():
45
+ msg = "Search/Replace content is empty or contains only whitespace"
46
+ raise InvalidPatchFormatError(msg)
47
+
48
+ if SEARCH_START not in self.raw_text:
49
+ if DIVIDER in self.raw_text or REPLACE_END in self.raw_text:
50
+ raise InvalidPatchFormatError("Unexpected delimiter found outside an active block")
51
+ raise InvalidPatchFormatError(
52
+ f"Missing required delimiter '{SEARCH_START}' in search/replace input"
53
+ )
54
+
55
+ file_deltas_map: dict[str, list[PatchHunk]] = {}
56
+ current_file: str | None = None
57
+
58
+ while self.idx < self.total:
59
+ line = self.lines[self.idx].strip()
60
+
61
+ if line == SEARCH_START:
62
+ if not current_file:
63
+ raise InvalidPatchFormatError(
64
+ f"Found '{SEARCH_START}' at line {self.idx + 1} without a target filename"
65
+ )
66
+ hunk = self._parse_block()
67
+ file_deltas_map.setdefault(current_file, []).append(hunk)
68
+ continue
69
+
70
+ if self._is_potential_file_path(line):
71
+ next_non_empty = self._peek_next_non_empty()
72
+ if next_non_empty == SEARCH_START:
73
+ current_file = _clean_filename(line)
74
+ self.idx += 1
75
+ continue
76
+
77
+ if line in (DIVIDER, REPLACE_END):
78
+ msg = (
79
+ f"Unexpected delimiter '{line}' found outside an active block "
80
+ f"at line {self.idx + 1}"
81
+ )
82
+ raise InvalidPatchFormatError(msg)
83
+
84
+ self.idx += 1
85
+
86
+ if not file_deltas_map:
87
+ raise InvalidPatchFormatError("No valid SEARCH/REPLACE blocks successfully parsed")
88
+
89
+ deltas: list[FileDelta] = []
90
+ for path, hunks in file_deltas_map.items():
91
+ all_additions = all(h.old_lines == 0 and h.new_lines > 0 for h in hunks)
92
+ all_deletions = all(h.new_lines == 0 and h.old_lines > 0 for h in hunks)
93
+ if all_additions:
94
+ change_type = ChangeType.ADD
95
+ elif all_deletions:
96
+ change_type = ChangeType.DELETE
97
+ else:
98
+ change_type = ChangeType.MODIFY
99
+
100
+ delta = FileDelta(
101
+ path=path,
102
+ change_type=change_type,
103
+ old_path=path,
104
+ new_path=path,
105
+ hunks=tuple(hunks),
106
+ )
107
+ deltas.append(delta)
108
+
109
+ return CanonicalPatch(
110
+ patch_type=PatchType.SEARCH_REPLACE,
111
+ file_deltas=tuple(deltas),
112
+ raw_diff=self.raw_text,
113
+ )
114
+
115
+ def _is_potential_file_path(self, line: str) -> bool:
116
+ if not line:
117
+ return False
118
+ if line.startswith("<") or line.startswith("=") or line.startswith(">"):
119
+ return False
120
+ cleaned = _clean_filename(line)
121
+ if not cleaned:
122
+ return False
123
+ if re.search(r"\.[A-Za-z0-9_-]+$", cleaned) or "/" in cleaned or "\\" in cleaned:
124
+ return True
125
+ return bool(re.match(r"^[A-Za-z0-9_.-]+$", cleaned))
126
+
127
+ def _peek_next_non_empty(self) -> str | None:
128
+ lookahead = self.idx + 1
129
+ while lookahead < self.total:
130
+ item = self.lines[lookahead].strip()
131
+ if item:
132
+ return item
133
+ lookahead += 1
134
+ return None
135
+
136
+ def _parse_block(self) -> PatchHunk:
137
+ start_line_idx = self.idx + 1
138
+ self.idx += 1
139
+
140
+ search_lines: list[str] = []
141
+ replace_lines: list[str] = []
142
+ found_divider = False
143
+ found_end = False
144
+
145
+ while self.idx < self.total:
146
+ line = self.lines[self.idx]
147
+ if line.strip() == DIVIDER:
148
+ found_divider = True
149
+ self.idx += 1
150
+ break
151
+ if line.strip() == SEARCH_START:
152
+ raise InvalidPatchFormatError(
153
+ f"Nested or unclosed '{SEARCH_START}' at line {self.idx + 1}"
154
+ )
155
+ if line.strip() == REPLACE_END:
156
+ raise InvalidPatchFormatError(
157
+ f"Found '{REPLACE_END}' before '{DIVIDER}' at line {self.idx + 1}"
158
+ )
159
+ search_lines.append(line)
160
+ self.idx += 1
161
+
162
+ if not found_divider:
163
+ raise InvalidPatchFormatError(
164
+ f"Block starting at line {start_line_idx} missing '{DIVIDER}' delimiter"
165
+ )
166
+
167
+ while self.idx < self.total:
168
+ line = self.lines[self.idx]
169
+ if line.strip() == REPLACE_END:
170
+ found_end = True
171
+ self.idx += 1
172
+ break
173
+ if line.strip() in (SEARCH_START, DIVIDER):
174
+ delim = line.strip()
175
+ msg = f"Unexpected delimiter '{delim}' inside REPLACE block at line {self.idx + 1}"
176
+ raise InvalidPatchFormatError(msg)
177
+ replace_lines.append(line)
178
+ self.idx += 1
179
+
180
+ if not found_end:
181
+ raise InvalidPatchFormatError(
182
+ f"Block starting at line {start_line_idx} missing '{REPLACE_END}' delimiter"
183
+ )
184
+
185
+ old_count = len(search_lines)
186
+ new_count = len(replace_lines)
187
+
188
+ if old_count == 0 and new_count == 0:
189
+ raise InvalidPatchFormatError(
190
+ f"Block starting at line {start_line_idx} has both empty SEARCH and empty REPLACE"
191
+ )
192
+
193
+ hunk_body = tuple(
194
+ ["-" + line_text for line_text in search_lines]
195
+ + ["+" + line_text for line_text in replace_lines]
196
+ )
197
+ header = f"@@ -1,{old_count} +1,{new_count} @@"
198
+
199
+ return PatchHunk(
200
+ old_start=1 if old_count > 0 else 0,
201
+ old_lines=old_count,
202
+ new_start=1 if new_count > 0 else 0,
203
+ new_lines=new_count,
204
+ header=header,
205
+ lines=hunk_body,
206
+ )
207
+
208
+
209
+ def parse_search_replace(raw_text: str) -> CanonicalPatch:
210
+ """Parse an Aider-style SEARCH/REPLACE text block into a CanonicalPatch model.
211
+
212
+ Args:
213
+ raw_text: Raw string containing one or more SEARCH/REPLACE edit blocks.
214
+
215
+ Returns:
216
+ CanonicalPatch: Immutable canonical representation of the edits.
217
+
218
+ Raises:
219
+ InvalidPatchFormatError: If delimiters are missing, ambiguous, or malformed.
220
+ """
221
+ parser = _SearchReplaceParser(raw_text)
222
+ return parser.parse()