caught 0.3.0__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.
caught/cli.py ADDED
@@ -0,0 +1,77 @@
1
+ """`caught`: the Claude Code hook entry points, and `caught check` for any git range.
2
+
3
+ caught check HEAD against the working tree, untracked files included
4
+ caught check main main against the working tree
5
+ caught check main..HEAD two commits, as in CI
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import subprocess
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ from caught.gitstate import git, snapshot_tree, toplevel
17
+ from caught.hook import inspect, session_start, stop, user_prompt
18
+
19
+ HOOKS = {"session-start": session_start, "user-prompt": user_prompt, "stop": stop}
20
+
21
+
22
+ def _tree(repo: Path, rev: str) -> str:
23
+ try:
24
+ return git(repo, "rev-parse", "--verify", "--quiet", f"{rev}^{{tree}}")
25
+ except subprocess.CalledProcessError:
26
+ raise ValueError(f"unknown revision {rev}") from None
27
+
28
+
29
+ def check(args: argparse.Namespace) -> int:
30
+ cwd = Path.cwd().resolve()
31
+ top = toplevel(cwd)
32
+ if top is None:
33
+ print("caught: not in a git repository", file=sys.stderr)
34
+ return 2
35
+ repo = top.resolve()
36
+ spec = args.range or "HEAD"
37
+ since_fork = "..." in spec
38
+ start, _, end = spec.partition("...") if since_fork else spec.partition("..")
39
+ try:
40
+ if since_fork: # A...B: what B changed since it forked from A, as git diff A...B shows
41
+ start = git(repo, "merge-base", start or "HEAD", end or "HEAD")
42
+ start_tree = _tree(repo, start or "HEAD")
43
+ end_tree = _tree(repo, end) if end else snapshot_tree(repo)
44
+ except (ValueError, subprocess.CalledProcessError) as exc:
45
+ message = str(exc) if isinstance(exc, ValueError) else f"no merge base for {spec}"
46
+ print(f"caught: {message}", file=sys.stderr)
47
+ return 2
48
+ findings, note = inspect(repo, cwd, start_tree, args.allow, end_tree, not args.no_rerun)
49
+ for f in findings:
50
+ print(f"{f.path}:{f.line}: {f.message}" if f.line else f"{f.path or 'tests'}: {f.message}")
51
+ if note:
52
+ print(note, file=sys.stderr)
53
+ if not findings:
54
+ print("caught: no findings")
55
+ return 1 if findings else 0
56
+
57
+
58
+ def main(argv: list[str] | None = None) -> int:
59
+ args = sys.argv[1:] if argv is None else argv
60
+ if args and args[0] in HOOKS:
61
+ output = HOOKS[args[0]](json.loads(sys.stdin.buffer.read().decode("utf-8")))
62
+ if output:
63
+ print(json.dumps(output))
64
+ return 0
65
+ parser = argparse.ArgumentParser(prog="caught")
66
+ commands = parser.add_subparsers(dest="command", required=True)
67
+ checker = commands.add_parser("check", help="check a git range for tests the change cheated")
68
+ checker.add_argument("range", nargs="?", help="A..B, or A for A against the working tree")
69
+ checker.add_argument(
70
+ "--allow",
71
+ action="append",
72
+ default=[],
73
+ metavar="PATH",
74
+ help="test edits to PATH were intended (repeatable)",
75
+ )
76
+ checker.add_argument("--no-rerun", action="store_true", help="skip running the tests")
77
+ return check(parser.parse_args(args))
caught/gitstate.py ADDED
@@ -0,0 +1,107 @@
1
+ """Git plumbing: snapshot the working tree as a tree object and read files back out of it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ import tempfile
9
+ from pathlib import Path
10
+
11
+ # commit-tree needs an identity; this one keeps Caught working in repos without user.name set.
12
+ _IDENTITY = {
13
+ "GIT_AUTHOR_NAME": "caught",
14
+ "GIT_AUTHOR_EMAIL": "caught@localhost",
15
+ "GIT_COMMITTER_NAME": "caught",
16
+ "GIT_COMMITTER_EMAIL": "caught@localhost",
17
+ }
18
+
19
+
20
+ def git(repo: Path, *args: str, env: dict[str, str] | None = None) -> str:
21
+ result = subprocess.run(
22
+ ["git", "-C", str(repo), *args],
23
+ capture_output=True,
24
+ env={**os.environ, **env} if env else None,
25
+ check=True,
26
+ )
27
+ return result.stdout.decode("utf-8", errors="replace").strip()
28
+
29
+
30
+ def toplevel(cwd: str | Path) -> Path | None:
31
+ result = subprocess.run(
32
+ ["git", "-C", str(cwd), "rev-parse", "--show-toplevel"], capture_output=True, text=True
33
+ )
34
+ return Path(result.stdout.strip()) if result.returncode == 0 else None
35
+
36
+
37
+ def head(repo: Path) -> str | None:
38
+ result = subprocess.run(
39
+ ["git", "-C", str(repo), "rev-parse", "--verify", "-q", "HEAD"],
40
+ capture_output=True,
41
+ text=True,
42
+ )
43
+ return result.stdout.strip() or None
44
+
45
+
46
+ def git_dir(repo: Path) -> Path:
47
+ return Path(git(repo, "rev-parse", "--absolute-git-dir"))
48
+
49
+
50
+ def snapshot_tree(repo: Path) -> str:
51
+ """Write the working tree, untracked files included, as a tree object.
52
+
53
+ Uses a throwaway copy of the index, so the user's staging area is never touched.
54
+ """
55
+ with tempfile.TemporaryDirectory(prefix="caught-") as tmp:
56
+ index = Path(tmp) / "index"
57
+ real_index = git_dir(repo) / "index"
58
+ if real_index.exists():
59
+ # Starting from the real index reuses git's stat cache, so unchanged files are cheap.
60
+ # copy2 keeps its mtime, which git needs to re-hash files edited in the same second.
61
+ shutil.copy2(real_index, index)
62
+ env = {"GIT_INDEX_FILE": str(index)}
63
+ git(repo, "add", "-A", env=env)
64
+ return git(repo, "write-tree", env=env)
65
+
66
+
67
+ def list_files(repo: Path, tree: str) -> dict[str, str]:
68
+ """Map each file path in a tree to its blob hash."""
69
+ files = {}
70
+ for entry in git(repo, "ls-tree", "-r", "-z", "--full-tree", tree).split("\0"):
71
+ if not entry:
72
+ continue
73
+ meta, path = entry.split("\t", 1)
74
+ _mode, kind, sha = meta.split()
75
+ if kind == "blob":
76
+ files[path] = sha
77
+ return files
78
+
79
+
80
+ def changed_paths(repo: Path, old_tree: str, new_tree: str) -> set[str]:
81
+ out = git(repo, "diff-tree", "-r", "-z", "--no-renames", "--name-only", old_tree, new_tree)
82
+ return {p for p in out.split("\0") if p}
83
+
84
+
85
+ def read_blobs(repo: Path, shas: set[str]) -> dict[str, str]:
86
+ """Read many blobs in one `git cat-file --batch` call."""
87
+ if not shas:
88
+ return {}
89
+ order = sorted(shas)
90
+ raw = subprocess.run(
91
+ ["git", "-C", str(repo), "cat-file", "--batch"],
92
+ input=("\n".join(order) + "\n").encode(),
93
+ capture_output=True,
94
+ check=True,
95
+ ).stdout
96
+ blobs, pos = {}, 0
97
+ for sha in order:
98
+ newline = raw.index(b"\n", pos)
99
+ size = int(raw[pos:newline].split()[2])
100
+ start = newline + 1
101
+ blobs[sha] = raw[start : start + size].decode("utf-8", errors="replace")
102
+ pos = start + size + 1
103
+ return blobs
104
+
105
+
106
+ def commit_tree(repo: Path, tree: str) -> str:
107
+ return git(repo, "commit-tree", tree, "-m", "caught snapshot", env=_IDENTITY)
caught/hook.py ADDED
@@ -0,0 +1,281 @@
1
+ """Claude Code hook entry points: `session-start` takes the snapshot, `stop` judges the session."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from dataclasses import asdict
8
+ from fnmatch import fnmatch
9
+ from pathlib import Path, PurePosixPath
10
+
11
+ from caught.checks import (
12
+ PRIORITY,
13
+ Finding,
14
+ is_command_file,
15
+ is_config_file,
16
+ is_test_file,
17
+ is_test_module,
18
+ run_checks,
19
+ )
20
+ from caught.gitstate import (
21
+ changed_paths,
22
+ git_dir,
23
+ head,
24
+ list_files,
25
+ read_blobs,
26
+ snapshot_tree,
27
+ toplevel,
28
+ )
29
+ from caught.rerun import rerun_originals
30
+
31
+ MAX_BLOCKS = 2
32
+ ADVICE = "Undo that and fix the code itself, or tell the user the task conflicts with the tests."
33
+ ALLOW = re.compile(r"\bcaught allow\b([^\n]*)", re.IGNORECASE)
34
+ # An allowance covers edits to the allowed test and config files. It never covers source that
35
+ # copies or detects the tests, or a hook that rewrites outcomes: "change the tests" means neither.
36
+ ALLOWABLE = {"test_edit", "assertion", "skip", "config"}
37
+
38
+
39
+ def _repo(payload: dict) -> tuple[Path, Path] | None:
40
+ cwd = Path(payload["cwd"]).resolve()
41
+ top = toplevel(cwd)
42
+ return (top.resolve(), cwd) if top else None
43
+
44
+
45
+ def _state_path(repo: Path, session_id: str) -> Path:
46
+ return git_dir(repo) / "caught" / f"{re.sub(r'[^A-Za-z0-9_-]', '_', session_id)}.json"
47
+
48
+
49
+ def session_start(payload: dict) -> None:
50
+ found = _repo(payload)
51
+ if found is None:
52
+ return
53
+ repo, _ = found
54
+ path = _state_path(repo, payload["session_id"])
55
+ if path.exists():
56
+ return # resume or compact: keep the snapshot from the real start of the session
57
+ tree = snapshot_tree(repo)
58
+ hashes = {
59
+ p: sha for p, sha in list_files(repo, tree).items() if is_test_file(p) or is_config_file(p)
60
+ }
61
+ path.parent.mkdir(parents=True, exist_ok=True)
62
+ state: dict[str, object] = {
63
+ "head": head(repo),
64
+ "tree": tree,
65
+ "hashes": hashes,
66
+ "blocks": 0,
67
+ "stops": [],
68
+ }
69
+ path.write_text(json.dumps(state, indent=2), encoding="utf-8")
70
+
71
+
72
+ def is_allowed(path: str, allowed: tuple[str, ...] | list[str]) -> bool:
73
+ """Whether the user allowed edits to `path`: an exact path, a directory, or a glob."""
74
+ return any(
75
+ path == a or path.startswith(a.rstrip("/") + "/") or fnmatch(path, a) for a in allowed
76
+ )
77
+
78
+
79
+ def user_prompt(payload: dict) -> dict | None:
80
+ """Record `caught allow <path> ...` from the user's own message for this session.
81
+
82
+ UserPromptSubmit fires only for what the user types, so the agent cannot allow itself.
83
+ """
84
+ found = _repo(payload)
85
+ words = [w for m in ALLOW.finditer(payload.get("prompt", "")) for w in m[1].split()]
86
+ # Quotes and brackets around a path, and a sentence's closing punctuation, are not part of it.
87
+ paths = [p for p in (w.strip("\"'`()").rstrip(",;:.!?") for w in words) if p]
88
+ if found is None or not paths:
89
+ return None
90
+ path = _state_path(found[0], payload["session_id"])
91
+ if not path.exists():
92
+ return None
93
+ state = json.loads(path.read_text(encoding="utf-8"))
94
+ state["allowed"] = sorted({*state.get("allowed", []), *paths})
95
+ path.write_text(json.dumps(state, indent=2), encoding="utf-8")
96
+ context = (
97
+ f"Caught will accept edits to {', '.join(state['allowed'])} for the rest of this session."
98
+ )
99
+ return {
100
+ "hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": context}
101
+ }
102
+
103
+
104
+ def inspect(
105
+ repo: Path,
106
+ cwd: Path,
107
+ start_tree: str,
108
+ allowed: tuple[str, ...] | list[str] = (),
109
+ end_tree: str | None = None,
110
+ rerun: bool = True,
111
+ ) -> tuple[list[Finding], str]:
112
+ """Static checks on the diff, then the original-test re-run if tests were touched.
113
+
114
+ The end state is the working tree unless `end_tree` is given. Findings on files in `allowed`
115
+ are dropped, and those files are not re-run.
116
+ """
117
+ end_tree = end_tree or snapshot_tree(repo)
118
+ if end_tree == start_tree:
119
+ return [], ""
120
+ changed = changed_paths(repo, start_tree, end_tree)
121
+ start_files, end_files = list_files(repo, start_tree), list_files(repo, end_tree)
122
+
123
+ def wanted(p: str) -> bool:
124
+ return (
125
+ is_test_file(p)
126
+ or is_config_file(p)
127
+ or (p in changed and (p.endswith(".py") or is_command_file(p)))
128
+ )
129
+
130
+ before_shas = {p: s for p, s in start_files.items() if wanted(p)}
131
+ after_shas = {p: s for p, s in end_files.items() if wanted(p)}
132
+ blobs = read_blobs(repo, set(before_shas.values()) | set(after_shas.values()))
133
+ before = {p: blobs[s] for p, s in before_shas.items()}
134
+ after = {p: blobs[s] for p, s in after_shas.items()}
135
+ findings = [
136
+ f
137
+ for f in run_checks(before, after)
138
+ if not (f.check in ALLOWABLE and is_allowed(f.path, allowed))
139
+ ]
140
+
141
+ config = {f.path for f in findings if f.check == "config"}
142
+ touched = sorted(
143
+ p
144
+ for p in changed & set(start_files)
145
+ if (is_test_file(p) and not is_allowed(p, allowed)) or p in config
146
+ )
147
+ added = sorted(config - set(start_files))
148
+ originals = sorted(p for p in start_files if is_test_module(p) and not is_allowed(p, allowed))
149
+ related = related_tests(repo, start_files, changed, originals)
150
+ if not rerun or not (touched or added or related):
151
+ return findings, ""
152
+ tests = [p for p in touched if is_test_module(p)]
153
+ if config or len(tests) < len(touched):
154
+ tests = originals # a config or helper change can affect every test
155
+ result = rerun_originals(
156
+ repo, start_tree, end_tree, touched, added, sorted({*tests, *related}), cwd
157
+ )
158
+ if not result.ran:
159
+ return findings, f"Caught could not re-run the original tests: {result.note}"
160
+ if result.failed:
161
+ findings.append(Finding("rerun", "", None, rerun_message(result.failed)))
162
+ if result.regressed:
163
+ findings.append(Finding("regression", "", None, regression_message(result.regressed)))
164
+ return findings, result.note
165
+
166
+
167
+ RELATED_LIMIT = 20
168
+
169
+
170
+ def related_tests(
171
+ repo: Path, start_files: dict[str, str], changed: set[str], originals: list[str]
172
+ ) -> list[str]:
173
+ """Original test modules that name a source module the session changed, at most 20.
174
+
175
+ Those are the tests most likely to notice when the agent changed behaviour to fit a test.
176
+ """
177
+ sources = [
178
+ PurePosixPath(p)
179
+ for p in changed & set(start_files)
180
+ if p.endswith(".py") and not is_test_file(p) and not is_config_file(p)
181
+ ]
182
+ names = {p.parent.name if p.stem == "__init__" else p.stem for p in sources} - {""}
183
+ if not names:
184
+ return []
185
+ texts = read_blobs(repo, {start_files[t] for t in originals})
186
+ alternatives = "|".join(map(re.escape, sorted(names)))
187
+ mentions = re.compile(rf"\b(?:{alternatives})\b")
188
+ imports = re.compile(rf"^\s*(?:from|import)\s+[\w., ]*\b(?:{alternatives})\b", re.M)
189
+ own = {f"test_{n}" for n in names} | {f"{n}_test" for n in names}
190
+
191
+ def rank(test: str) -> int | None:
192
+ """0 for the module's own test file, 1 for one that imports it, 2 for a mention."""
193
+ text = texts[start_files[test]]
194
+ if PurePosixPath(test).stem in own:
195
+ return 0
196
+ if imports.search(text):
197
+ return 1
198
+ return 2 if mentions.search(text) else None
199
+
200
+ ranked = sorted((r, t) for t in originals if (r := rank(t)) is not None)
201
+ return [t for _, t in ranked][:RELATED_LIMIT]
202
+
203
+
204
+ def regression_message(regressed: list[str]) -> str:
205
+ if len(regressed) == 1:
206
+ return f"the original test {regressed[0]}, which passed at session start, fails now"
207
+ shown = regressed[:3]
208
+ rest = len(regressed) - len(shown)
209
+ tail = f", {shown[-1]} and {rest} more" if rest else f" and {shown[-1]}"
210
+ names = ", ".join(shown[:-1]) + tail
211
+ return f"{len(regressed)} original tests that passed at session start fail now: {names}"
212
+
213
+
214
+ def rerun_message(failed: list[str]) -> str:
215
+ if len(failed) == 1:
216
+ return f"the original test {failed[0]} fails against your code"
217
+ shown = failed[:3]
218
+ rest = len(failed) - len(shown)
219
+ names = ", ".join(shown[:-1]) + (
220
+ f", {shown[-1]} and {rest} more" if rest else f" and {shown[-1]}"
221
+ )
222
+ return f"{len(failed)} original tests fail against your code: {names}"
223
+
224
+
225
+ def summarize(findings: list[Finding]) -> str:
226
+ # One finding from the diff and one from running the tests lead the reason.
227
+ ran = ("rerun", "regression")
228
+ static = sorted(
229
+ (f for f in findings if f.check not in ran), key=lambda f: PRIORITY.index(f.check)
230
+ )
231
+ dynamic = sorted((f for f in findings if f.check in ran), key=lambda f: ran.index(f.check))
232
+ parts = [f.message for f in static[:1] + dynamic[:1]]
233
+ extra = len(findings) - len(parts)
234
+ more = f" ({extra} more finding{'s' if extra > 1 else ''})" if extra else ""
235
+ reason = f"Not done: {', and '.join(parts)}{more}. {ADVICE}"
236
+ edited = sorted({f.path for f in findings if f.check in ALLOWABLE})
237
+ if edited:
238
+ reason += (
239
+ f" If the user asked for this change, they can reply `caught allow {' '.join(edited)}`."
240
+ )
241
+ return reason
242
+
243
+
244
+ def decide(findings: list[Finding], note: str, blocks: int) -> tuple[dict | None, int]:
245
+ """The hook's JSON output and the new block count."""
246
+ if not findings:
247
+ return ({"systemMessage": note} if note else None), blocks
248
+ reason = summarize(findings)
249
+ if blocks < MAX_BLOCKS:
250
+ return {"decision": "block", "reason": reason}, blocks + 1
251
+ warning = (
252
+ f"Caught: allowed this stop after {MAX_BLOCKS} blocks, but the problem remains. {reason}"
253
+ )
254
+ return {"systemMessage": warning}, blocks
255
+
256
+
257
+ def stop(payload: dict) -> dict | None:
258
+ found = _repo(payload)
259
+ if found is None:
260
+ return None
261
+ repo, cwd = found
262
+ path = _state_path(repo, payload["session_id"])
263
+ if not path.exists():
264
+ return None # no snapshot: the plugin was enabled mid-session
265
+ state = json.loads(path.read_text(encoding="utf-8"))
266
+ allowed = state.get("allowed", [])
267
+ end_tree = snapshot_tree(repo)
268
+ # Nothing changed since the last stop: its verdict stands, without running the tests again.
269
+ key = " ".join([end_tree, *allowed])
270
+ last = state.get("last")
271
+ if last and last["key"] == key:
272
+ findings, note = [Finding(**f) for f in last["findings"]], last["note"]
273
+ else:
274
+ findings, note = inspect(repo, cwd, state["tree"], allowed, end_tree)
275
+ state["last"] = {"key": key, "findings": [asdict(f) for f in findings], "note": note}
276
+ output, state["blocks"] = decide(findings, note, state["blocks"])
277
+ state["stops"].append(
278
+ {"findings": [asdict(f) for f in findings], "note": note, "output": output}
279
+ )
280
+ path.write_text(json.dumps(state, indent=2), encoding="utf-8")
281
+ return output
caught/rerun.py ADDED
@@ -0,0 +1,227 @@
1
+ """Run the session's original test files against the agent's final code, in a temporary worktree."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import shutil
8
+ import signal
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import xml.etree.ElementTree as ET
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path
15
+
16
+ from caught.gitstate import commit_tree, git
17
+
18
+ TIMEOUT_SECONDS = 80 # per test run; the Stop hook makes up to three and has 300 s
19
+
20
+
21
+ @dataclass
22
+ class RerunResult:
23
+ ran: bool
24
+ failed: list[str] = field(default_factory=list) # original tests the agent's test edits hid
25
+ regressed: list[str] = field(default_factory=list) # passed at session start, fail now
26
+ note: str = ""
27
+
28
+
29
+ def project_python(*dirs: Path) -> str:
30
+ """The project's virtualenv interpreter if there is one, else the one running Caught."""
31
+ for d in dirs:
32
+ for venv in (".venv", "venv"):
33
+ for exe in ("Scripts/python.exe", "bin/python"):
34
+ candidate = d / venv / exe
35
+ if candidate.exists():
36
+ return str(candidate)
37
+ return sys.executable
38
+
39
+
40
+ def _report(junit: Path) -> tuple[set[str], set[str]]:
41
+ """(failed, passed) test ids from a JUnit report, as `package.module.Class::name`."""
42
+ failed, passed = set(), set()
43
+ for case in ET.parse(junit).iter("testcase"):
44
+ test_id = f"{case.get('classname', '')}::{case.get('name', '')}"
45
+ if case.find("failure") is not None or case.find("error") is not None:
46
+ failed.add(test_id)
47
+ elif case.find("skipped") is None:
48
+ passed.add(test_id)
49
+ return failed, passed
50
+
51
+
52
+ def short(test_id: str) -> str:
53
+ """`test_calc::test_large` for `tests.test_calc::test_large`, as the block reason shows it."""
54
+ location, _, name = test_id.partition("::")
55
+ return f"{location.rsplit('.', 1)[-1]}::{name}" if name else location
56
+
57
+
58
+ class _NotRun(Exception):
59
+ pass
60
+
61
+
62
+ def _kill_tree(proc: subprocess.Popen) -> None:
63
+ if sys.platform == "win32":
64
+ subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], capture_output=True)
65
+ else:
66
+ os.killpg(proc.pid, signal.SIGKILL)
67
+
68
+
69
+ def _new_group() -> dict:
70
+ """Popen options for a process group of its own, so the whole test command can be killed."""
71
+ if sys.platform == "win32":
72
+ return {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}
73
+ return {"start_new_session": True}
74
+
75
+
76
+ def _run(command: list[str], run_dir: Path, env: dict[str, str]) -> subprocess.CompletedProcess:
77
+ """Run a test command with its output in files, killing its whole process tree on timeout.
78
+
79
+ Pipes would make a timeout wait for every child that inherited them, such as a test server.
80
+ """
81
+ with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err:
82
+ proc = subprocess.Popen(
83
+ command,
84
+ cwd=run_dir,
85
+ env={**os.environ, **env},
86
+ stdout=out,
87
+ stderr=err,
88
+ **_new_group(),
89
+ )
90
+ try:
91
+ proc.wait(timeout=TIMEOUT_SECONDS)
92
+ except subprocess.TimeoutExpired as exc:
93
+ _kill_tree(proc)
94
+ proc.wait()
95
+ raise _NotRun(f"the tests timed out after {TIMEOUT_SECONDS}s") from exc
96
+ out.seek(0)
97
+ err.seek(0)
98
+ stdout = out.read().decode("utf-8", errors="replace")
99
+ stderr = err.read().decode("utf-8", errors="replace")
100
+ return subprocess.CompletedProcess(command, proc.returncode, stdout, stderr)
101
+
102
+
103
+ def _environment(tree: Path) -> dict[str, str]:
104
+ """Import the worktree's code, not the checkout an editable install points at, and write no
105
+ bytecode a later run could load in place of changed source."""
106
+ roots = [str(p) for p in (tree / "src", tree) if p.is_dir()]
107
+ inherited = os.environ.get("PYTHONPATH")
108
+ return {
109
+ "PYTHONPATH": os.pathsep.join([*roots, inherited] if inherited else roots),
110
+ "PYTHONDONTWRITEBYTECODE": "1",
111
+ }
112
+
113
+
114
+ def _tests(
115
+ python: str, run_dir: Path, root: Path, paths: list[Path], junit: Path
116
+ ) -> tuple[set[str], set[str]]:
117
+ """(failed, passed) test ids from one run, by pytest, or by unittest without pytest."""
118
+ env = _environment(root)
119
+ proc = _run(
120
+ [
121
+ python,
122
+ "-m",
123
+ "pytest",
124
+ "-q",
125
+ "-p",
126
+ "no:cacheprovider",
127
+ f"--junitxml={junit}",
128
+ *map(str, paths),
129
+ ],
130
+ run_dir,
131
+ env,
132
+ )
133
+ if junit.exists():
134
+ return _report(junit)
135
+ if "No module named pytest" in proc.stderr:
136
+ return _unittest(python, root, paths, env)
137
+ tail = (proc.stdout + proc.stderr).strip().splitlines()[-1:] or ["no output"]
138
+ raise _NotRun(f"pytest did not run: {tail[0]}")
139
+
140
+
141
+ # unittest -v lines: "test_large (tests.test_calc.TestFee.test_large) ... ok".
142
+ UNITTEST_RESULT = re.compile(
143
+ r"^\S+ \(([^)]+)\)(?: \S.*?)? \.\.\. (ok|FAIL|ERROR|skipped|expected failure)", re.M
144
+ )
145
+
146
+
147
+ def _unittest(
148
+ python: str, root: Path, paths: list[Path], env: dict[str, str]
149
+ ) -> tuple[set[str], set[str]]:
150
+ """(failed, passed) test ids, named like pytest's, from `python -m unittest -v`."""
151
+ # From the root, where every test path is a plain relative path unittest can import.
152
+ relative = [os.path.relpath(p, root) for p in paths]
153
+ proc = _run([python, "-m", "unittest", "-v", *relative], root, env)
154
+ if not re.search(r"^Ran \d+ tests?", proc.stderr, re.M):
155
+ tail = proc.stderr.strip().splitlines()[-1:] or ["no output"]
156
+ raise _NotRun(f"unittest did not run: {tail[0]}")
157
+ failed, passed = set(), set()
158
+ for dotted, outcome in UNITTEST_RESULT.findall(proc.stderr):
159
+ location, _, name = dotted.rpartition(".")
160
+ test_id = f"{location}::{name}"
161
+ if outcome in ("FAIL", "ERROR"):
162
+ failed.add(test_id)
163
+ elif outcome == "ok":
164
+ passed.add(test_id)
165
+ return failed, passed
166
+
167
+
168
+ def rerun_originals(
169
+ repo: Path,
170
+ start_tree: str,
171
+ end_tree: str,
172
+ restore: list[str],
173
+ remove: list[str],
174
+ tests: list[str],
175
+ cwd: Path,
176
+ ) -> RerunResult:
177
+ """Run the original tests against the agent's code, and against the code it started from.
178
+
179
+ In a worktree of the end state, `tests` run as the agent left them (when it changed any),
180
+ then with the original `restore` files put back and the added `remove` files deleted, then on
181
+ the session-start code. A test that fails with the originals but not with the agent's versions
182
+ was hidden by its test edits; one that passed at the start and fails now is a regression the
183
+ agent's code caused. `cwd` is the session's directory; pytest runs from the same place in the
184
+ worktree, so rootdir and config discovery match what the agent saw.
185
+ """
186
+ tmp = Path(tempfile.mkdtemp(prefix="caught-"))
187
+ tree = tmp / "tree"
188
+ python = project_python(cwd, repo)
189
+ try:
190
+ git(repo, "worktree", "add", "--detach", "--quiet", str(tree), commit_tree(repo, end_tree))
191
+ # The session's directory may be untracked or empty, and so missing from the worktree.
192
+ run_dir = tree / cwd.relative_to(repo)
193
+ run_dir = run_dir if run_dir.is_dir() else tree
194
+ paths = [tree / t for t in tests]
195
+ agent: set[str] = set()
196
+ edited = bool(restore or remove)
197
+ if edited:
198
+ present = [p for p in paths if p.exists()]
199
+ if present:
200
+ agent, _ = _tests(python, run_dir, tree, present, tmp / "agent.xml")
201
+ if restore:
202
+ git(tree, "checkout", start_tree, "--", *restore)
203
+ for path in remove:
204
+ (tree / path).unlink(missing_ok=True)
205
+ now, _ = _tests(python, run_dir, tree, paths, tmp / "now.xml")
206
+ hidden = now - agent if edited else set()
207
+ # Anything the runs wrote goes, so the start code runs as it was.
208
+ git(tree, "clean", "-fdxq")
209
+ git(tree, "checkout", "--force", "--quiet", commit_tree(repo, start_tree))
210
+ try:
211
+ _, passed_before = _tests(python, run_dir, tree, paths, tmp / "before.xml")
212
+ except _NotRun as exc:
213
+ note = f"Caught could not check for regressions on the start code: {exc}"
214
+ return RerunResult(True, sorted({short(t) for t in hidden}), note=note)
215
+ regressed = (now & passed_before) - hidden
216
+ return RerunResult(
217
+ True, sorted({short(t) for t in hidden}), sorted({short(t) for t in regressed})
218
+ )
219
+ except _NotRun as exc:
220
+ return RerunResult(False, note=str(exc))
221
+ finally:
222
+ subprocess.run(
223
+ ["git", "-C", str(repo), "worktree", "remove", "--force", str(tree)],
224
+ capture_output=True,
225
+ )
226
+ shutil.rmtree(tmp, ignore_errors=True)
227
+ subprocess.run(["git", "-C", str(repo), "worktree", "prune"], capture_output=True)