exitproof 0.1.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.
exitproof/__init__.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
"""exitproof: receipts for test runs, so "all tests pass" has to be true.
|
|
2
|
+
|
|
3
|
+
The exit code is the authority. Counts parsed from the output are best effort.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import shlex
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
__version__ = "0.1.0"
|
|
20
|
+
DIR = ".exitproof"
|
|
21
|
+
MAX_BLOCKS = 3 # Stop-hook blocks per turn before letting the agent stop anyway.
|
|
22
|
+
JUNK = {b"__pycache__", b".pytest_cache", b".mypy_cache", b".ruff_cache", b"node_modules", b".coverage"}
|
|
23
|
+
|
|
24
|
+
# ---------------------------------------------------------------- repo state
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _git(root: str, *args: str) -> bytes | None:
|
|
28
|
+
try:
|
|
29
|
+
return subprocess.run(["git", *args], cwd=root, capture_output=True, check=True).stdout
|
|
30
|
+
except (OSError, subprocess.CalledProcessError):
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def find_root(cwd: str) -> str | None:
|
|
35
|
+
out = _git(cwd, "rev-parse", "--show-toplevel")
|
|
36
|
+
return out.decode().strip() if out else None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def fingerprint(root: str) -> str | None:
|
|
40
|
+
"""Hash of every tracked + untracked (non-ignored) file as it is on disk now."""
|
|
41
|
+
# ponytail: rehashes the whole tree each call; fine up to ~10k files,
|
|
42
|
+
# switch to git's stat cache (temp index + write-tree) if it gets slow.
|
|
43
|
+
out = _git(root, "ls-files", "-z", "--cached", "--others", "--exclude-standard")
|
|
44
|
+
if out is None:
|
|
45
|
+
return None
|
|
46
|
+
h = hashlib.sha256()
|
|
47
|
+
for rel in sorted(set(out.split(b"\0")) - {b""}):
|
|
48
|
+
if JUNK.intersection(rel.split(b"/")):
|
|
49
|
+
continue # runners write these during the run; they are not code
|
|
50
|
+
path = os.path.join(root, os.fsdecode(rel))
|
|
51
|
+
h.update(rel + b"\0")
|
|
52
|
+
try:
|
|
53
|
+
if os.path.islink(path):
|
|
54
|
+
h.update(os.readlink(path).encode())
|
|
55
|
+
else:
|
|
56
|
+
with open(path, "rb") as f:
|
|
57
|
+
h.update(hashlib.sha256(f.read()).digest())
|
|
58
|
+
except OSError:
|
|
59
|
+
h.update(b"<missing>")
|
|
60
|
+
return h.hexdigest()[:16]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _store(root: str) -> Path:
|
|
64
|
+
d = Path(root) / DIR
|
|
65
|
+
if not d.exists():
|
|
66
|
+
d.mkdir(parents=True)
|
|
67
|
+
(d / ".gitignore").write_text("*\n") # never committed, never part of the fingerprint
|
|
68
|
+
return d
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def load_runs(root: str) -> list[dict]:
|
|
72
|
+
f = Path(root) / DIR / "runs.jsonl"
|
|
73
|
+
if not f.exists():
|
|
74
|
+
return []
|
|
75
|
+
return [json.loads(line) for line in f.read_text().splitlines() if line.strip()]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# ---------------------------------------------------------------- output parsing
|
|
79
|
+
|
|
80
|
+
ANSI = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
|
|
81
|
+
SUMMARY = re.compile(r"^=+ .* =+$|\bin \d+(?:\.\d+)?m?s\b|^\s*Tests:?\s") # pytest, jest, vitest
|
|
82
|
+
COUNT = re.compile(r"(\d+) (passed|failed|skipped|errors?)\b")
|
|
83
|
+
CARGO = re.compile(r"^test result: \w+\. (\d+) passed; (\d+) failed; (\d+) ignored")
|
|
84
|
+
GO = re.compile(r"^\s*--- (PASS|FAIL|SKIP):")
|
|
85
|
+
RAN = re.compile(r"^Ran (\d+) tests? in ")
|
|
86
|
+
UNITTEST = re.compile(r"^(OK|FAILED)(?: \((.*)\))?$")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _zero() -> dict:
|
|
90
|
+
return {"passed": 0, "failed": 0, "skipped": 0, "errors": 0}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class Counts:
|
|
94
|
+
"""Feed output lines; result() gives test counts or None if no known summary was seen."""
|
|
95
|
+
|
|
96
|
+
def __init__(self) -> None:
|
|
97
|
+
self.cargo = self.go = self.generic = self.unittest = None
|
|
98
|
+
self.ran: int | None = None
|
|
99
|
+
|
|
100
|
+
def feed(self, line: str) -> None:
|
|
101
|
+
line = ANSI.sub("", line).rstrip()
|
|
102
|
+
m = CARGO.match(line)
|
|
103
|
+
if m: # one summary per test binary: sum them
|
|
104
|
+
self.cargo = self.cargo or _zero()
|
|
105
|
+
for key, n in zip(("passed", "failed", "skipped"), m.groups()):
|
|
106
|
+
self.cargo[key] += int(n)
|
|
107
|
+
return
|
|
108
|
+
m = GO.match(line)
|
|
109
|
+
if m: # go test -v
|
|
110
|
+
self.go = self.go or _zero()
|
|
111
|
+
self.go[{"PASS": "passed", "FAIL": "failed", "SKIP": "skipped"}[m[1]]] += 1
|
|
112
|
+
return
|
|
113
|
+
m = RAN.match(line)
|
|
114
|
+
if m:
|
|
115
|
+
self.ran = int(m[1])
|
|
116
|
+
return
|
|
117
|
+
m = UNITTEST.match(line)
|
|
118
|
+
if m and self.ran is not None:
|
|
119
|
+
kv = {k.strip(): int(v) for k, v in re.findall(r"([a-z ]+)=(\d+)", m[2] or "")}
|
|
120
|
+
c = {"failed": kv.get("failures", 0), "errors": kv.get("errors", 0), "skipped": kv.get("skipped", 0)}
|
|
121
|
+
other = kv.get("expected failures", 0) + kv.get("unexpected successes", 0)
|
|
122
|
+
self.unittest = {"passed": self.ran - sum(c.values()) - other, **c}
|
|
123
|
+
return
|
|
124
|
+
if SUMMARY.search(line):
|
|
125
|
+
found = COUNT.findall(line)
|
|
126
|
+
# last summary wins: jest/vitest print suites first, then tests
|
|
127
|
+
if found or "no tests ran" in line or " deselected" in line:
|
|
128
|
+
self.generic = _zero()
|
|
129
|
+
for n, word in found:
|
|
130
|
+
self.generic["errors" if word.startswith("error") else word] += int(n)
|
|
131
|
+
|
|
132
|
+
def result(self) -> dict | None:
|
|
133
|
+
return self.cargo or self.generic or self.unittest or self.go
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def describe(c: dict | None) -> str:
|
|
137
|
+
if not c:
|
|
138
|
+
return "counts unknown"
|
|
139
|
+
return ", ".join(f"{n} {k}" for k, n in c.items() if n) or "0 tests"
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# ---------------------------------------------------------------- commands
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def run(argv: list[str], cwd: str) -> int:
|
|
146
|
+
if argv[:1] == ["--"]:
|
|
147
|
+
argv = argv[1:]
|
|
148
|
+
if not argv:
|
|
149
|
+
print("usage: exitproof run -- <command> [args...]", file=sys.stderr)
|
|
150
|
+
return 2
|
|
151
|
+
root = find_root(cwd) or cwd
|
|
152
|
+
shell = len(argv) == 1 and " " in argv[0] # `exitproof run "make test"`
|
|
153
|
+
cmd = argv[0] if shell else shlex.join(argv)
|
|
154
|
+
counts, start = Counts(), time.time()
|
|
155
|
+
# ponytail: stderr is merged into stdout so lines stay ordered; tools that
|
|
156
|
+
# colorize only on a TTY will print plain text.
|
|
157
|
+
try:
|
|
158
|
+
proc = subprocess.Popen(argv[0] if shell else argv, shell=shell, cwd=cwd,
|
|
159
|
+
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
|
160
|
+
except OSError as e:
|
|
161
|
+
print(f"exitproof: cannot start `{cmd}`: {e}", file=sys.stderr)
|
|
162
|
+
code = 127
|
|
163
|
+
else:
|
|
164
|
+
try:
|
|
165
|
+
for raw in proc.stdout:
|
|
166
|
+
sys.stdout.buffer.write(raw)
|
|
167
|
+
sys.stdout.flush()
|
|
168
|
+
counts.feed(raw.decode("utf-8", "replace"))
|
|
169
|
+
code = proc.wait()
|
|
170
|
+
except KeyboardInterrupt:
|
|
171
|
+
proc.wait()
|
|
172
|
+
code = 130
|
|
173
|
+
rec = {"v": 1, "t": round(time.time(), 3), "cmd": cmd, "exit": code,
|
|
174
|
+
"secs": round(time.time() - start, 2), "tree": fingerprint(root), "counts": counts.result()}
|
|
175
|
+
with open(_store(root) / "runs.jsonl", "a") as f:
|
|
176
|
+
f.write(json.dumps(rec) + "\n")
|
|
177
|
+
print(f"exitproof: exit {code} | {describe(rec['counts'])} | {rec['secs']}s | recorded", file=sys.stderr)
|
|
178
|
+
return code
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def evaluate(root: str, strict: bool = False, since: float = 0.0) -> tuple[list[str], list[str]]:
|
|
182
|
+
"""Return (problems, warnings) for the latest run of every recorded command."""
|
|
183
|
+
latest: dict[str, dict] = {}
|
|
184
|
+
for r in load_runs(root):
|
|
185
|
+
if r["t"] >= since:
|
|
186
|
+
latest[r["cmd"]] = r
|
|
187
|
+
if not latest:
|
|
188
|
+
return ["no test run recorded" + (" since this session started" if since else "")], []
|
|
189
|
+
tree = fingerprint(root)
|
|
190
|
+
problems, warnings = [], []
|
|
191
|
+
for cmd, r in latest.items():
|
|
192
|
+
if r["exit"] != 0:
|
|
193
|
+
problems.append(f"`{cmd}` exited {r['exit']} ({describe(r['counts'])})")
|
|
194
|
+
elif tree is not None and r["tree"] != tree:
|
|
195
|
+
problems.append(f"`{cmd}` passed, but files changed after it ran (stale)")
|
|
196
|
+
c = r.get("counts")
|
|
197
|
+
if r["exit"] == 0 and c:
|
|
198
|
+
if c["skipped"]:
|
|
199
|
+
warnings.append(f"`{cmd}` is green with {c['skipped']} skipped")
|
|
200
|
+
if not (c["passed"] or c["failed"] or c["errors"]):
|
|
201
|
+
warnings.append(f"`{cmd}` is green but ran 0 tests")
|
|
202
|
+
if strict:
|
|
203
|
+
problems, warnings = problems + warnings, []
|
|
204
|
+
return problems, warnings
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def check(cwd: str, strict: bool) -> int:
|
|
208
|
+
root = find_root(cwd) or cwd
|
|
209
|
+
problems, warnings = evaluate(root, strict)
|
|
210
|
+
for line in problems:
|
|
211
|
+
print(f"FAIL {line}")
|
|
212
|
+
for line in warnings:
|
|
213
|
+
print(f"WARN {line}")
|
|
214
|
+
if not problems:
|
|
215
|
+
print("ok every recorded command is green on the current files")
|
|
216
|
+
return 1 if problems else 0
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
# ---------------------------------------------------------------- Claude Code hooks
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _session_file(root: str, sid: str) -> Path:
|
|
223
|
+
d = _store(root) / "sessions"
|
|
224
|
+
d.mkdir(exist_ok=True)
|
|
225
|
+
return d / (re.sub(r"[^\w-]", "_", sid) + ".json")
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _runner() -> str:
|
|
229
|
+
"""How the agent can invoke exitproof: the PATH command, or this module (plugin installs)."""
|
|
230
|
+
if shutil.which("exitproof"):
|
|
231
|
+
return "exitproof"
|
|
232
|
+
# double quotes work in both sh and cmd.exe
|
|
233
|
+
return f'"{sys.executable}" "{Path(__file__).resolve().parent / "__main__.py"}"'
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def hook(event: str, data: dict, strict: bool) -> dict | None:
|
|
237
|
+
"""Handle a Claude Code hook event. Returns the JSON to print, or None to allow silently."""
|
|
238
|
+
root = find_root(data.get("cwd") or os.getcwd())
|
|
239
|
+
if root is None:
|
|
240
|
+
return None
|
|
241
|
+
f = _session_file(root, str(data.get("session_id") or "default"))
|
|
242
|
+
if event == "session-start":
|
|
243
|
+
if not f.exists(): # resume/compact keep the original baseline
|
|
244
|
+
f.write_text(json.dumps({"t": time.time(), "tree": fingerprint(root), "blocks": 0}))
|
|
245
|
+
return None
|
|
246
|
+
if event != "stop" or not f.exists():
|
|
247
|
+
return None
|
|
248
|
+
state = json.loads(f.read_text())
|
|
249
|
+
if fingerprint(root) == state["tree"]:
|
|
250
|
+
return None # nothing changed this session: nothing to prove
|
|
251
|
+
problems, warnings = evaluate(root, strict, since=state["t"])
|
|
252
|
+
if not data.get("stop_hook_active"):
|
|
253
|
+
state["blocks"] = 0 # a fresh turn
|
|
254
|
+
if not problems:
|
|
255
|
+
state["blocks"] = 0
|
|
256
|
+
f.write_text(json.dumps(state))
|
|
257
|
+
return {"systemMessage": "exitproof: " + "; ".join(warnings)} if warnings else None
|
|
258
|
+
if state["blocks"] >= MAX_BLOCKS:
|
|
259
|
+
return {"systemMessage": "exitproof: agent stopped with unproven changes: " + "; ".join(problems)}
|
|
260
|
+
state["blocks"] += 1
|
|
261
|
+
f.write_text(json.dumps(state))
|
|
262
|
+
reason = (
|
|
263
|
+
"exitproof: you changed files in this session, but no green test run covers the current files:\n"
|
|
264
|
+
+ "".join(f"- {p}\n" for p in problems)
|
|
265
|
+
+ f"Run the project's checks through exitproof (e.g. `{_runner()} run -- pytest -q`) and fix what fails. "
|
|
266
|
+
"If you cannot make them pass, say exactly what is failing instead of reporting success."
|
|
267
|
+
)
|
|
268
|
+
return {"decision": "block", "reason": reason}
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def install(cwd: str, user: bool, strict: bool) -> int:
|
|
272
|
+
base = Path.home() if user else Path(find_root(cwd) or cwd)
|
|
273
|
+
path = base / ".claude" / "settings.json"
|
|
274
|
+
settings = json.loads(path.read_text()) if path.exists() else {}
|
|
275
|
+
hooks = settings.setdefault("hooks", {})
|
|
276
|
+
flag = " --strict" if strict else ""
|
|
277
|
+
exe = _runner() # an absolute command when exitproof is not on PATH, so the hook never fails open
|
|
278
|
+
if exe != "exitproof":
|
|
279
|
+
print("note: `exitproof` is not on PATH; the hooks call this Python directly")
|
|
280
|
+
for event, cmd in (("SessionStart", f"{exe} hook session-start"), ("Stop", f"{exe} hook stop{flag}")):
|
|
281
|
+
entries = hooks.setdefault(event, [])
|
|
282
|
+
cmds = [h.get("command", "") for e in entries for h in e.get("hooks", [])]
|
|
283
|
+
if any("exitproof" in c and " hook " in c for c in cmds):
|
|
284
|
+
print(f"{event}: already installed")
|
|
285
|
+
continue
|
|
286
|
+
entries.append({"hooks": [{"type": "command", "command": cmd}]})
|
|
287
|
+
print(f"{event}: added `{cmd}`")
|
|
288
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
289
|
+
path.write_text(json.dumps(settings, indent=2) + "\n")
|
|
290
|
+
print(f"wrote {path}")
|
|
291
|
+
return 0
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
# ---------------------------------------------------------------- CLI
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def main(argv: list[str] | None = None) -> int:
|
|
298
|
+
p = argparse.ArgumentParser(prog="exitproof", description=__doc__.splitlines()[0])
|
|
299
|
+
p.add_argument("--version", action="version", version=__version__)
|
|
300
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
301
|
+
r = sub.add_parser("run", help="run a command and record its exit code against the current files")
|
|
302
|
+
r.add_argument("argv", nargs=argparse.REMAINDER)
|
|
303
|
+
c = sub.add_parser("check", help="exit 1 unless every recorded command is green on the current files")
|
|
304
|
+
c.add_argument("--strict", action="store_true", help="also fail on skipped tests or 0 tests ran")
|
|
305
|
+
sub.add_parser("clear", help="forget all recorded runs")
|
|
306
|
+
i = sub.add_parser("install", help="install the Claude Code hooks")
|
|
307
|
+
i.add_argument("agent", choices=["claude"])
|
|
308
|
+
i.add_argument("--user", action="store_true", help="~/.claude/settings.json instead of the repo's")
|
|
309
|
+
i.add_argument("--strict", action="store_true")
|
|
310
|
+
h = sub.add_parser("hook", help="hook entry point (reads the event JSON on stdin)")
|
|
311
|
+
h.add_argument("event", choices=["session-start", "stop"])
|
|
312
|
+
h.add_argument("--strict", action="store_true")
|
|
313
|
+
a = p.parse_args(argv)
|
|
314
|
+
cwd = os.getcwd()
|
|
315
|
+
if a.command == "run":
|
|
316
|
+
return run(a.argv, cwd)
|
|
317
|
+
if a.command == "check":
|
|
318
|
+
return check(cwd, a.strict)
|
|
319
|
+
if a.command == "clear":
|
|
320
|
+
(Path(find_root(cwd) or cwd) / DIR / "runs.jsonl").unlink(missing_ok=True)
|
|
321
|
+
return 0
|
|
322
|
+
if a.command == "install":
|
|
323
|
+
return install(cwd, a.user, a.strict)
|
|
324
|
+
try:
|
|
325
|
+
data = json.loads(sys.stdin.read() or "{}")
|
|
326
|
+
except ValueError:
|
|
327
|
+
data = {}
|
|
328
|
+
out = hook(a.event, data, a.strict)
|
|
329
|
+
if out:
|
|
330
|
+
print(json.dumps(out))
|
|
331
|
+
return 0
|
exitproof/__main__.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: exitproof
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Receipts for test runs: your coding agent can't say 'all tests pass' unless they did, on the current files.
|
|
5
|
+
Project-URL: Homepage, https://github.com/RAFAELDCOELHO/exitproof
|
|
6
|
+
Project-URL: Issues, https://github.com/RAFAELDCOELHO/exitproof/issues
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: ai-agents,ci,claude-code,codex,hooks,testing
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Software Development :: Testing
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# exitproof
|
|
18
|
+
|
|
19
|
+
Receipts for test runs, so "all tests pass" has to be true.
|
|
20
|
+
|
|
21
|
+
Coding agents (Claude Code, Codex, and friends) sometimes report "all tests pass" when:
|
|
22
|
+
|
|
23
|
+
- they never re-ran the tests after their last edit,
|
|
24
|
+
- the suite was green only because tests were skipped, or zero tests ran,
|
|
25
|
+
- the run they quote happened before the code they are now describing.
|
|
26
|
+
|
|
27
|
+
exitproof records every test run with its exit code and a fingerprint of your files. Any change after the last run makes that run stale. A Claude Code hook can then refuse to let the agent finish until a green run covers the code it actually changed.
|
|
28
|
+
|
|
29
|
+
Pure Python standard library, Python 3.9+, no dependencies.
|
|
30
|
+
|
|
31
|
+
## Quickstart
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
uv tool install exitproof # or: pipx install exitproof
|
|
35
|
+
cd your-repo
|
|
36
|
+
exitproof install claude # add the Claude Code hooks to .claude/settings.json
|
|
37
|
+
exitproof run -- pytest -q # run your tests through exitproof
|
|
38
|
+
exitproof check # exit 0 only if every recorded command is green on the current files
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Or install the hooks as a Claude Code plugin (no PATH setup; needs `python3`):
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
/plugin install exitproof --marketplace RAFAELDCOELHO/exitproof
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Any command works, not just pytest: `exitproof run -- npm test`, `exitproof run -- cargo test`, `exitproof run "make test && make lint"`.
|
|
48
|
+
|
|
49
|
+
## What it looks like
|
|
50
|
+
|
|
51
|
+
All output below is real, from a small repo with `calc.py` and two pytest tests.
|
|
52
|
+
|
|
53
|
+
A green run, then a check:
|
|
54
|
+
|
|
55
|
+
```console
|
|
56
|
+
$ exitproof run -- pytest -q
|
|
57
|
+
.. [100%]
|
|
58
|
+
2 passed in 0.01s
|
|
59
|
+
exitproof: exit 0 | 2 passed | 0.67s | recorded
|
|
60
|
+
$ exitproof check
|
|
61
|
+
ok every recorded command is green on the current files
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Then someone edits `calc.py` (`a + b` becomes `a - b`). The old green run no longer counts:
|
|
65
|
+
|
|
66
|
+
```console
|
|
67
|
+
$ exitproof check
|
|
68
|
+
FAIL `pytest -q` passed, but files changed after it ran (stale)
|
|
69
|
+
$ exitproof run -- pytest -q
|
|
70
|
+
FF [100%]
|
|
71
|
+
[... pytest failure details ...]
|
|
72
|
+
FAILED test_calc.py::test_add - assert 0 == 4
|
|
73
|
+
FAILED test_calc.py::test_add_negative - assert -2 == 0
|
|
74
|
+
2 failed in 0.02s
|
|
75
|
+
exitproof: exit 1 | 2 failed | 0.48s | recorded
|
|
76
|
+
$ exitproof check
|
|
77
|
+
FAIL `pytest -q` exited 1 (2 failed)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Green with a skipped test is a warning by default and a failure with `--strict`:
|
|
81
|
+
|
|
82
|
+
```console
|
|
83
|
+
$ exitproof run -- pytest -q
|
|
84
|
+
..s [100%]
|
|
85
|
+
2 passed, 1 skipped in 0.01s
|
|
86
|
+
exitproof: exit 0 | 2 passed, 1 skipped | 0.47s | recorded
|
|
87
|
+
$ exitproof check
|
|
88
|
+
WARN `pytest -q` is green with 1 skipped
|
|
89
|
+
ok every recorded command is green on the current files
|
|
90
|
+
$ exitproof check --strict
|
|
91
|
+
FAIL `pytest -q` is green with 1 skipped
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## With Claude Code
|
|
95
|
+
|
|
96
|
+
```console
|
|
97
|
+
$ exitproof install claude
|
|
98
|
+
SessionStart: added `exitproof hook session-start`
|
|
99
|
+
Stop: added `exitproof hook stop`
|
|
100
|
+
wrote .../your-repo/.claude/settings.json
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
(`wrote` prints the absolute path. It is shortened here.) Use `--user` to write `~/.claude/settings.json` instead, and `--strict` to make the Stop hook also reject skipped or zero tests. Running `install` twice is safe: it reports `already installed`.
|
|
104
|
+
|
|
105
|
+
What the hooks do:
|
|
106
|
+
|
|
107
|
+
1. **SessionStart** records a baseline fingerprint of your files.
|
|
108
|
+
2. **Stop**, when the agent tries to finish its turn:
|
|
109
|
+
- If no file changed since the baseline, it does nothing. Questions and read-only sessions are never blocked.
|
|
110
|
+
- If files changed and a green run made after the session started covers the current files, it lets the agent stop.
|
|
111
|
+
- Otherwise it blocks the stop and tells the agent why. This is the real message:
|
|
112
|
+
|
|
113
|
+
```
|
|
114
|
+
exitproof: you changed files in this session, but no green test run covers the current files:
|
|
115
|
+
- no test run recorded since this session started
|
|
116
|
+
Run the project's checks through exitproof (e.g. `exitproof run -- pytest -q`) and fix what fails. If you cannot make them pass, say exactly what is failing instead of reporting success.
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
- After 3 blocks in one turn it lets the agent stop, so it can never loop forever. You get a visible message instead: `exitproof: agent stopped with unproven changes: ...`.
|
|
120
|
+
|
|
121
|
+
The block message tells the agent how to call exitproof: `exitproof` if it is on `PATH` (installed with `uv tool` or `pipx`), otherwise the full `python -m exitproof` command from the plugin's own copy.
|
|
122
|
+
|
|
123
|
+
### Tried on a real agent
|
|
124
|
+
|
|
125
|
+
In a scratch repo (`calc.py` plus one pytest test, hooks installed), a headless Claude Code session (`claude -p`, v2.1.337) was asked to *"add a subtract function to calc.py"*, with no mention of tests. It edited the file, told the user it hadn't run anything, and tried to finish. The Stop hook blocked once with the message above. The agent then ran `exitproof run -- pytest -q` (1 passed), added a `test_subtract` on its own, and ran it again (2 passed). The second stop was allowed. A second run with *"add a multiply function"* went the same way: 1 block, then 2 recorded green runs. That is n=2 on one model and one tiny repo, a smoke test, not a benchmark.
|
|
126
|
+
|
|
127
|
+
When exitproof blocks, Claude Code may show a "stop hook" notice in the UI. That notice is the block working, not a crash.
|
|
128
|
+
|
|
129
|
+
## In CI or a pre-push hook
|
|
130
|
+
|
|
131
|
+
In CI there is no history, so run and check in one step. `--strict` turns "green but skipped" and "green but ran nothing" into failures:
|
|
132
|
+
|
|
133
|
+
```sh
|
|
134
|
+
exitproof run -- pytest -q && exitproof check --strict
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
As a git pre-push hook (`.git/hooks/pre-push`), refuse to push code whose last recorded run is red or stale:
|
|
138
|
+
|
|
139
|
+
```sh
|
|
140
|
+
#!/bin/sh
|
|
141
|
+
exec exitproof check
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## How it works
|
|
145
|
+
|
|
146
|
+
- `exitproof run -- <cmd>` streams the command's output unchanged and returns its exit code. It then appends one JSON line to `.exitproof/runs.jsonl`: the command, exit code, duration, parsed test counts, and a fingerprint.
|
|
147
|
+
- The fingerprint is a hash of every tracked file plus every untracked file that is not ignored, as they are on disk. Ignored files do not count, and neither do `__pycache__/`, `.pytest_cache/`, `.mypy_cache/`, `.ruff_cache/`, `node_modules/` and `.coverage` anywhere in the tree. Keep other build output (`target/`, `dist/`) in `.gitignore`, or every build makes your runs stale.
|
|
148
|
+
- `exitproof check` looks at the **latest run of each distinct command string**. It fails if any of them exited non-zero or ran on different files than the current ones.
|
|
149
|
+
- Test counts are parsed from pytest, unittest, jest, vitest, `cargo test`, and `go test -v` output. Other tools still work; they just show `counts unknown`.
|
|
150
|
+
- `.exitproof/` creates its own `.gitignore`, so it is never committed and never affects the fingerprint.
|
|
151
|
+
- `exitproof clear` forgets all recorded runs.
|
|
152
|
+
|
|
153
|
+
## Limitations
|
|
154
|
+
|
|
155
|
+
- **It is a guardrail, not security.** An agent that wants to cheat can edit or delete `.exitproof/`, or run a command that always exits 0. exitproof catches the common honest mistake: claiming success from an old or partial run. It does not stop deliberate evasion.
|
|
156
|
+
- **The exit code is the authority.** Counts are best effort, scraped from the output with regular expressions. If your runner prints an unusual summary, counts may be wrong or `unknown`, and `--strict` cannot see skips it cannot parse.
|
|
157
|
+
- **stderr is merged into stdout** so lines stay in order. Tools that only colorize when writing to a terminal will print plain text.
|
|
158
|
+
- **Every distinct command is tracked separately.** A one-off red run of `pytest -k something` keeps `check` failing until you rerun that exact command green or run `exitproof clear`.
|
|
159
|
+
- **Git repos only, in practice.** Outside a git repo, runs are recorded but no fingerprint is taken, so staleness cannot be detected.
|
|
160
|
+
- **The fingerprint rereads every file** on each run and check. That is fine for typical repos but slow for very large ones.
|
|
161
|
+
|
|
162
|
+
## License
|
|
163
|
+
|
|
164
|
+
MIT
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
exitproof/__init__.py,sha256=zDg6eF1xNQznKGQ-Ew-BS-v6oECJ-ELk_YL9HnaqRnY,13541
|
|
2
|
+
exitproof/__main__.py,sha256=DkhpUbeIKrp4JNwp9dqhlZnPKuf5_s2Obxba_UfjzVQ,242
|
|
3
|
+
exitproof-0.1.0.dist-info/METADATA,sha256=V5fie4RvR1UCjIg73Vxm3kkGTl4sdIj1NUn45_vHnjM,8481
|
|
4
|
+
exitproof-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
5
|
+
exitproof-0.1.0.dist-info/entry_points.txt,sha256=EDA3Wn5FkfBAomZy_BBBsnrVbL_2q7tqqwCPYp_AV00,45
|
|
6
|
+
exitproof-0.1.0.dist-info/licenses/LICENSE,sha256=7ds2kD6ZXPKj_YyIE-qMl97Fbz528uKw33LhntOxdS0,1079
|
|
7
|
+
exitproof-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 exitproof contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|