exitproof 0.1.0__tar.gz

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.
Binary file
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "exitproof",
3
+ "description": "exitproof: test-run receipts for coding agents.",
4
+ "owner": {
5
+ "name": "RAFAELDCOELHO"
6
+ },
7
+ "plugins": [
8
+ {
9
+ "name": "exitproof",
10
+ "source": "./",
11
+ "description": "Blocks the agent from finishing while its file changes are not covered by a green test run on the current files."
12
+ }
13
+ ]
14
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "exitproof",
3
+ "version": "0.1.0",
4
+ "description": "Blocks the agent from finishing while its file changes are not covered by a green test run on the current files.",
5
+ "repository": "https://github.com/RAFAELDCOELHO/exitproof",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "testing",
9
+ "hooks",
10
+ "verification"
11
+ ],
12
+ "author": {
13
+ "name": "RAFAELDCOELHO",
14
+ "url": "https://github.com/RAFAELDCOELHO"
15
+ },
16
+ "network": {
17
+ "hosts": []
18
+ },
19
+ "icon": ".claude-plugin/icon.png"
20
+ }
@@ -0,0 +1,17 @@
1
+ name: ci
2
+ on: [push, pull_request]
3
+ jobs:
4
+ test:
5
+ runs-on: ${{ matrix.os }}
6
+ strategy:
7
+ fail-fast: false
8
+ matrix:
9
+ os: [ubuntu-latest, macos-latest, windows-latest]
10
+ python: ["3.9", "3.13"]
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: astral-sh/setup-uv@v6
14
+ - run: uvx ruff check src tests
15
+ - run: uv run --no-project --python ${{ matrix.python }} --with pytest -- python -m pytest -q
16
+ env:
17
+ PYTHONPATH: src
@@ -0,0 +1,15 @@
1
+ name: publish
2
+ on:
3
+ release:
4
+ types: [published]
5
+ jobs:
6
+ pypi:
7
+ runs-on: ubuntu-latest
8
+ environment: pypi
9
+ permissions:
10
+ id-token: write
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: astral-sh/setup-uv@v6
14
+ - run: uv build
15
+ - run: uv publish --trusted-publishing always
@@ -0,0 +1,6 @@
1
+ __pycache__/
2
+ *.pyc
3
+ dist/
4
+ .venv/
5
+ .pytest_cache/
6
+ .ruff_cache/
@@ -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.
@@ -0,0 +1,6 @@
1
+ .PHONY: test lint check
2
+ test:
3
+ uv run --no-project --with pytest -- env PYTHONPATH=src python -m pytest -q
4
+ lint:
5
+ uvx ruff check src tests
6
+ check: lint test
@@ -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,148 @@
1
+ # exitproof
2
+
3
+ Receipts for test runs, so "all tests pass" has to be true.
4
+
5
+ Coding agents (Claude Code, Codex, and friends) sometimes report "all tests pass" when:
6
+
7
+ - they never re-ran the tests after their last edit,
8
+ - the suite was green only because tests were skipped, or zero tests ran,
9
+ - the run they quote happened before the code they are now describing.
10
+
11
+ 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.
12
+
13
+ Pure Python standard library, Python 3.9+, no dependencies.
14
+
15
+ ## Quickstart
16
+
17
+ ```sh
18
+ uv tool install exitproof # or: pipx install exitproof
19
+ cd your-repo
20
+ exitproof install claude # add the Claude Code hooks to .claude/settings.json
21
+ exitproof run -- pytest -q # run your tests through exitproof
22
+ exitproof check # exit 0 only if every recorded command is green on the current files
23
+ ```
24
+
25
+ Or install the hooks as a Claude Code plugin (no PATH setup; needs `python3`):
26
+
27
+ ```
28
+ /plugin install exitproof --marketplace RAFAELDCOELHO/exitproof
29
+ ```
30
+
31
+ Any command works, not just pytest: `exitproof run -- npm test`, `exitproof run -- cargo test`, `exitproof run "make test && make lint"`.
32
+
33
+ ## What it looks like
34
+
35
+ All output below is real, from a small repo with `calc.py` and two pytest tests.
36
+
37
+ A green run, then a check:
38
+
39
+ ```console
40
+ $ exitproof run -- pytest -q
41
+ .. [100%]
42
+ 2 passed in 0.01s
43
+ exitproof: exit 0 | 2 passed | 0.67s | recorded
44
+ $ exitproof check
45
+ ok every recorded command is green on the current files
46
+ ```
47
+
48
+ Then someone edits `calc.py` (`a + b` becomes `a - b`). The old green run no longer counts:
49
+
50
+ ```console
51
+ $ exitproof check
52
+ FAIL `pytest -q` passed, but files changed after it ran (stale)
53
+ $ exitproof run -- pytest -q
54
+ FF [100%]
55
+ [... pytest failure details ...]
56
+ FAILED test_calc.py::test_add - assert 0 == 4
57
+ FAILED test_calc.py::test_add_negative - assert -2 == 0
58
+ 2 failed in 0.02s
59
+ exitproof: exit 1 | 2 failed | 0.48s | recorded
60
+ $ exitproof check
61
+ FAIL `pytest -q` exited 1 (2 failed)
62
+ ```
63
+
64
+ Green with a skipped test is a warning by default and a failure with `--strict`:
65
+
66
+ ```console
67
+ $ exitproof run -- pytest -q
68
+ ..s [100%]
69
+ 2 passed, 1 skipped in 0.01s
70
+ exitproof: exit 0 | 2 passed, 1 skipped | 0.47s | recorded
71
+ $ exitproof check
72
+ WARN `pytest -q` is green with 1 skipped
73
+ ok every recorded command is green on the current files
74
+ $ exitproof check --strict
75
+ FAIL `pytest -q` is green with 1 skipped
76
+ ```
77
+
78
+ ## With Claude Code
79
+
80
+ ```console
81
+ $ exitproof install claude
82
+ SessionStart: added `exitproof hook session-start`
83
+ Stop: added `exitproof hook stop`
84
+ wrote .../your-repo/.claude/settings.json
85
+ ```
86
+
87
+ (`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`.
88
+
89
+ What the hooks do:
90
+
91
+ 1. **SessionStart** records a baseline fingerprint of your files.
92
+ 2. **Stop**, when the agent tries to finish its turn:
93
+ - If no file changed since the baseline, it does nothing. Questions and read-only sessions are never blocked.
94
+ - If files changed and a green run made after the session started covers the current files, it lets the agent stop.
95
+ - Otherwise it blocks the stop and tells the agent why. This is the real message:
96
+
97
+ ```
98
+ exitproof: you changed files in this session, but no green test run covers the current files:
99
+ - no test run recorded since this session started
100
+ 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.
101
+ ```
102
+
103
+ - 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: ...`.
104
+
105
+ 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.
106
+
107
+ ### Tried on a real agent
108
+
109
+ 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.
110
+
111
+ When exitproof blocks, Claude Code may show a "stop hook" notice in the UI. That notice is the block working, not a crash.
112
+
113
+ ## In CI or a pre-push hook
114
+
115
+ 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:
116
+
117
+ ```sh
118
+ exitproof run -- pytest -q && exitproof check --strict
119
+ ```
120
+
121
+ As a git pre-push hook (`.git/hooks/pre-push`), refuse to push code whose last recorded run is red or stale:
122
+
123
+ ```sh
124
+ #!/bin/sh
125
+ exec exitproof check
126
+ ```
127
+
128
+ ## How it works
129
+
130
+ - `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.
131
+ - 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.
132
+ - `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.
133
+ - 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`.
134
+ - `.exitproof/` creates its own `.gitignore`, so it is never committed and never affects the fingerprint.
135
+ - `exitproof clear` forgets all recorded runs.
136
+
137
+ ## Limitations
138
+
139
+ - **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.
140
+ - **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.
141
+ - **stderr is merged into stdout** so lines stay in order. Tools that only colorize when writing to a terminal will print plain text.
142
+ - **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`.
143
+ - **Git repos only, in practice.** Outside a git repo, runs are recorded but no fingerprint is taken, so staleness cannot be detected.
144
+ - **The fingerprint rereads every file** on each run and check. That is fine for typical repos but slow for very large ones.
145
+
146
+ ## License
147
+
148
+ MIT
@@ -0,0 +1,6 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [{"hooks": [{"type": "command", "command": "python3 \"${CLAUDE_PLUGIN_ROOT}/src/exitproof/__main__.py\" hook session-start"}]}],
4
+ "Stop": [{"hooks": [{"type": "command", "command": "python3 \"${CLAUDE_PLUGIN_ROOT}/src/exitproof/__main__.py\" hook stop"}]}]
5
+ }
6
+ }
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "exitproof"
7
+ version = "0.1.0"
8
+ description = "Receipts for test runs: your coding agent can't say 'all tests pass' unless they did, on the current files."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ keywords = ["testing", "claude-code", "codex", "ai-agents", "ci", "hooks"]
14
+ classifiers = [
15
+ "Environment :: Console",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Topic :: Software Development :: Testing",
19
+ ]
20
+ dependencies = []
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/RAFAELDCOELHO/exitproof"
24
+ Issues = "https://github.com/RAFAELDCOELHO/exitproof/issues"
25
+
26
+ [project.scripts]
27
+ exitproof = "exitproof:main"
28
+
29
+ [tool.ruff]
30
+ line-length = 120
31
+ target-version = "py39"
32
+
33
+ [tool.ruff.lint]
34
+ select = ["E", "F", "W", "B", "UP", "RUF100"]
@@ -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
@@ -0,0 +1,9 @@
1
+ import os
2
+ import sys
3
+
4
+ if not __package__: # run as a file (plugin/hook installs): make `import exitproof` work
5
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
6
+
7
+ from exitproof import main
8
+
9
+ sys.exit(main())
@@ -0,0 +1,19 @@
1
+ Compiling cargo_green v0.1.0 (/home/user/proj)
2
+ Building [ ] 0/3: cargo_green, cargo_green(test)
3
+ Building [==================> ] 2/3: cargo_green(test)
4
+ Finished `test` profile [unoptimized + debuginfo] target(s) in 0.19s
5
+ Running unittests src/lib.rs (target/debug/deps/cargo_green-07d907bd103f37ce)
6
+
7
+ running 5 tests
8
+ test tests::e ... ignored
9
+ test tests::f ... ignored
10
+ test tests::a ... ok
11
+ test tests::b ... ok
12
+ test tests::c ... ok
13
+
14
+ test result: ok. 3 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out; finished in 0.00s
15
+
16
+ Doc-tests cargo_green
17
+
18
+ running 0 tests
19
+
20
+ test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
21
+
@@ -0,0 +1,29 @@
1
+ Compiling cargo_red v0.1.0 (/home/user/proj)
2
+ Building [ ] 0/3: cargo_red
3
+ Building [ ] 0/3: cargo_red, cargo_red(test)
4
+ Building [==================> ] 2/3: cargo_red(test)
5
+ Finished `test` profile [unoptimized + debuginfo] target(s) in 1.18s
6
+ Running unittests src/lib.rs (target/debug/deps/cargo_red-33780f3e7fc1b233)
7
+
8
+ running 6 tests
9
+ test tests::a ... ok
10
+ test tests::e ... ignored
11
+ test tests::f ... ignored
12
+ test tests::c ... ok
13
+ test tests::b ... ok
14
+ test tests::d ... FAILED
15
+
16
+ failures:
17
+
18
+ ---- tests::d stdout ----
19
+
20
+ thread 'tests::d' (31720543) panicked at src/lib.rs:6:22:
21
+ assertion `left == right` failed
22
+ left: 1
23
+ right: 2
24
+ note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
25
+
26
+
27
+ failures:
28
+ tests::d
29
+
30
+ test result: FAILED. 3 passed; 1 failed; 2 ignored; 0 measured; 0 filtered out; finished in 0.00s
31
+
32
+ error: test failed, to rerun pass `--lib`
@@ -0,0 +1,6 @@
1
+ npm warn Unknown user config "allow-scripts". This will stop working in the next major version of npm.
2
+ Test Suites: 1 passed, 1 total
3
+ Tests: 2 skipped, 3 passed, 5 total
4
+ Snapshots: 0 total
5
+ Time: 0.217 s
6
+ Ran all test suites.
@@ -0,0 +1,23 @@
1
+ npm warn Unknown user config "allow-scripts". This will stop working in the next major version of npm.
2
+ FAIL ./x.test.js
3
+ ● d
4
+
5
+ expect(received).toBe(expected) // Object.is equality
6
+
7
+ Expected: 2
8
+ Received: 1
9
+
10
+ 1 | const t = (n, f) => test(n, f);
11
+ 2 | test("a", () => {}); test("b", () => {}); test("c", () => {});
12
+ > 3 | test("d", () => { expect(1).toBe(2); });
13
+ | ^
14
+ 4 | test.skip("e", () => {}); test.skip("f", () => {});
15
+ 5 |
16
+
17
+ at Object.toBe (x.test.js:3:29)
18
+
19
+ Test Suites: 1 failed, 1 total
20
+ Tests: 1 failed, 2 skipped, 3 passed, 6 total
21
+ Snapshots: 0 total
22
+ Time: 0.342 s
23
+ Ran all test suites.
@@ -0,0 +1,8 @@
1
+ ============================= test session starts ==============================
2
+ platform darwin -- Python 3.9.6, pytest-8.4.2, pluggy-1.6.0
3
+ rootdir: /home/user/proj
4
+ plugins: anyio-4.12.1, asyncio-1.2.0
5
+ asyncio: mode=strict, debug=False, asyncio_default_fixture_loop_scope=None, asyncio_default_test_loop_scope=function
6
+ collected 0 items
7
+
8
+ ============================ no tests ran in 0.00s =============================
@@ -0,0 +1,10 @@
1
+ ============================= test session starts ==============================
2
+ platform darwin -- Python 3.9.6, pytest-8.4.2, pluggy-1.6.0
3
+ rootdir: /home/user/proj
4
+ plugins: anyio-4.12.1, asyncio-1.2.0
5
+ asyncio: mode=strict, debug=False, asyncio_default_fixture_loop_scope=None, asyncio_default_test_loop_scope=function
6
+ collected 5 items
7
+
8
+ test_x.py ...ss [100%]
9
+
10
+ ========================= 3 passed, 2 skipped in 0.01s =========================
@@ -0,0 +1,21 @@
1
+ ============================= test session starts ==============================
2
+ platform darwin -- Python 3.9.6, pytest-8.4.2, pluggy-1.6.0
3
+ rootdir: /home/user/proj
4
+ plugins: anyio-4.12.1, asyncio-1.2.0
5
+ asyncio: mode=strict, debug=False, asyncio_default_fixture_loop_scope=None, asyncio_default_test_loop_scope=function
6
+ collected 6 items
7
+
8
+ test_x.py ...Fss [100%]
9
+
10
+ =================================== FAILURES ===================================
11
+ ___________________________________ T.test_d ___________________________________
12
+
13
+ self = <test_x.T testMethod=test_d>
14
+
15
+ > def test_d(self): self.assertEqual(1, 2)
16
+ E AssertionError: 1 != 2
17
+
18
+ test_x.py:6: AssertionError
19
+ =========================== short test summary info ============================
20
+ FAILED test_x.py::T::test_d - AssertionError: 1 != 2
21
+ ==================== 1 failed, 3 passed, 2 skipped in 0.03s ====================
@@ -0,0 +1,10 @@
1
+ test_a (test_x.T) ... ok
2
+ test_b (test_x.T) ... ok
3
+ test_c (test_x.T) ... ok
4
+ test_e (test_x.T) ... skipped 's'
5
+ test_f (test_x.T) ... skipped 's'
6
+
7
+ ----------------------------------------------------------------------
8
+ Ran 5 tests in 0.000s
9
+
10
+ OK (skipped=2)
@@ -0,0 +1,19 @@
1
+ test_a (test_x.T) ... ok
2
+ test_b (test_x.T) ... ok
3
+ test_c (test_x.T) ... ok
4
+ test_d (test_x.T) ... FAIL
5
+ test_e (test_x.T) ... skipped 's'
6
+ test_f (test_x.T) ... skipped 's'
7
+
8
+ ======================================================================
9
+ FAIL: test_d (test_x.T)
10
+ ----------------------------------------------------------------------
11
+ Traceback (most recent call last):
12
+ File "/home/user/proj/test_x.py", line 6, in test_d
13
+ def test_d(self): self.assertEqual(1, 2)
14
+ AssertionError: 1 != 2
15
+
16
+ ----------------------------------------------------------------------
17
+ Ran 6 tests in 0.000s
18
+
19
+ FAILED (failures=1, skipped=2)
@@ -0,0 +1,10 @@
1
+ npm warn Unknown user config "allow-scripts". This will stop working in the next major version of npm.
2
+
3
+ RUN v5.1.2 /home/user/proj
4
+
5
+
6
+ Test Files 1 passed (1)
7
+ Tests 3 passed | 2 skipped (5)
8
+ Start at 15:26:43
9
+ Duration 107ms (transform 60%, import 25%, worker 8%, tests 6%)
10
+
@@ -0,0 +1,34 @@
1
+ npm warn Unknown user config "allow-scripts". This will stop working in the next major version of npm.
2
+
3
+ RUN v5.1.2 /home/user/proj
4
+
5
+ ❯ x.test.mjs (6 tests | 1 failed | 2 skipped) 9ms
6
+ × d 5ms
7
+
8
+ ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
9
+
10
+ FAIL x.test.mjs > d
11
+ AssertionError: expected 1 to be 2 // Object.is equality
12
+
13
+ - Expected
14
+ + Received
15
+
16
+ - 2
17
+ + 1
18
+
19
+ ❯ x.test.mjs:4:29
20
+ 2| const t = (n, f) => test(n, f);
21
+ 3| test("a", () => {}); test("b", () => {}); test("c", () => {});
22
+ 4| test("d", () => { expect(1).toBe(2); });
23
+ | ^
24
+ 5| test.skip("e", () => {}); test.skip("f", () => {});
25
+ 6|
26
+
27
+ ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
28
+
29
+
30
+ Test Files 1 failed (1)
31
+ Tests 1 failed | 3 passed | 2 skipped (6)
32
+ Start at 15:26:41
33
+ Duration 171ms (transform 52%, import 24%, tests 17%, worker 7%)
34
+
@@ -0,0 +1,128 @@
1
+ """End-to-end: the real CLI, in a real temp git repo."""
2
+ import json
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ SRC = str(Path(__file__).resolve().parents[1] / "src")
11
+ PY = sys.executable
12
+
13
+
14
+ def ep(repo, *args, stdin=None):
15
+ env = {**os.environ, "PYTHONPATH": SRC}
16
+ return subprocess.run([PY, "-m", "exitproof", *args], check=False, cwd=repo, input=stdin,
17
+ capture_output=True, text=True, env=env)
18
+
19
+
20
+ @pytest.fixture
21
+ def repo(tmp_path):
22
+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)
23
+ (tmp_path / "app.py").write_text("x = 1\n")
24
+ return tmp_path
25
+
26
+
27
+ def say(text, code=0):
28
+ return ["run", "--", PY, "-c", f"print({text!r}); raise SystemExit({code})"]
29
+
30
+
31
+ def test_green_then_stale_then_green(repo):
32
+ assert ep(repo, *say("3 passed in 0.01s")).returncode == 0
33
+ assert ep(repo, "check").returncode == 0 # also proves .exitproof/ is outside the fingerprint
34
+ (repo / "app.py").write_text("x = 2\n")
35
+ r = ep(repo, "check")
36
+ assert r.returncode == 1 and "stale" in r.stdout
37
+ assert ep(repo, *say("3 passed in 0.01s")).returncode == 0
38
+ assert ep(repo, "check").returncode == 0
39
+
40
+
41
+ def test_red_run_propagates_exit_code_and_fails_check(repo):
42
+ r = ep(repo, *say("1 failed, 2 passed in 0.01s", code=3))
43
+ assert r.returncode == 3
44
+ assert "1 failed, 2 passed" in r.stdout + r.stderr
45
+ c = ep(repo, "check")
46
+ assert c.returncode == 1 and "exited 3" in c.stdout
47
+
48
+
49
+ def test_every_command_counts_not_just_the_last(repo):
50
+ ep(repo, *say("1 failed in 0.01s", code=1))
51
+ ep(repo, *say("lint ok"))
52
+ assert ep(repo, "check").returncode == 1
53
+
54
+
55
+ def test_skips_warn_by_default_fail_when_strict(repo):
56
+ ep(repo, *say("1 passed, 2 skipped in 0.01s"))
57
+ r = ep(repo, "check")
58
+ assert r.returncode == 0 and "2 skipped" in r.stdout
59
+ assert ep(repo, "check", "--strict").returncode == 1
60
+
61
+
62
+ def test_no_runs_fails_check(repo):
63
+ assert ep(repo, "check").returncode == 1
64
+
65
+
66
+ def test_missing_command_is_recorded_as_failure(repo):
67
+ assert ep(repo, "run", "--", "definitely-not-a-command-xyz").returncode == 127
68
+ assert ep(repo, "check").returncode == 1
69
+
70
+
71
+ def test_stop_hook_flow(repo):
72
+ ev = {"session_id": "s1", "cwd": str(repo)}
73
+ assert ep(repo, "hook", "session-start", stdin=json.dumps(ev)).stdout == ""
74
+ # nothing changed: stopping is fine
75
+ assert ep(repo, "hook", "stop", stdin=json.dumps(ev)).stdout == ""
76
+ (repo / "app.py").write_text("x = 2\n")
77
+ out = json.loads(ep(repo, "hook", "stop", stdin=json.dumps(ev)).stdout)
78
+ assert out["decision"] == "block" and "no test run recorded since this session started" in out["reason"]
79
+ # keeps blocking while the agent keeps trying to stop, then gives up loudly
80
+ cont = {**ev, "stop_hook_active": True}
81
+ for _ in range(2):
82
+ assert json.loads(ep(repo, "hook", "stop", stdin=json.dumps(cont)).stdout)["decision"] == "block"
83
+ out = json.loads(ep(repo, "hook", "stop", stdin=json.dumps(cont)).stdout)
84
+ assert "decision" not in out and "unproven" in out["systemMessage"]
85
+ # a new turn blocks again; a green run on the current files lets it stop
86
+ assert json.loads(ep(repo, "hook", "stop", stdin=json.dumps(ev)).stdout)["decision"] == "block"
87
+ ep(repo, *say("4 passed in 0.01s"))
88
+ assert ep(repo, "hook", "stop", stdin=json.dumps(ev)).stdout == ""
89
+
90
+
91
+ def test_stop_hook_ignores_runs_from_before_the_session(repo):
92
+ ep(repo, *say("1 failed in 0.01s", code=1)) # old red run, other session
93
+ ev = json.dumps({"session_id": "s2", "cwd": str(repo)})
94
+ ep(repo, "hook", "session-start", stdin=ev)
95
+ (repo / "app.py").write_text("x = 3\n")
96
+ ep(repo, *say("2 passed in 0.01s"))
97
+ assert ep(repo, "hook", "stop", stdin=ev).stdout == ""
98
+
99
+
100
+ def test_install_merges_and_is_idempotent(repo):
101
+ settings = repo / ".claude" / "settings.json"
102
+ settings.parent.mkdir()
103
+ other = {"hooks": [{"type": "command", "command": "other"}]}
104
+ settings.write_text(json.dumps({"model": "x", "hooks": {"Stop": [other]}}))
105
+ assert ep(repo, "install", "claude").returncode == 0
106
+ assert ep(repo, "install", "claude").returncode == 0
107
+ s = json.loads(settings.read_text())
108
+ assert s["model"] == "x"
109
+ stop_cmds = [h["command"] for e in s["hooks"]["Stop"] for h in e["hooks"]]
110
+ assert stop_cmds[0] == "other" and len(stop_cmds) == 2 and stop_cmds[1].endswith(" hook stop")
111
+ [start] = [h["command"] for e in s["hooks"]["SessionStart"] for h in e["hooks"]]
112
+ # the written command must actually run, even with exitproof absent from PATH
113
+ r = subprocess.run(start, shell=True, input=json.dumps({"session_id": "i", "cwd": str(repo)}),
114
+ capture_output=True, text=True, cwd=repo, check=False)
115
+ assert r.returncode == 0 and (repo / ".exitproof" / "sessions" / "i.json").exists()
116
+
117
+
118
+ def test_runner_caches_do_not_make_runs_stale(repo):
119
+ ep(repo, *say("1 passed in 0.01s"))
120
+ (repo / "__pycache__").mkdir()
121
+ (repo / "__pycache__" / "app.cpython-39.pyc").write_bytes(b"\x00junk")
122
+ assert ep(repo, "check").returncode == 0
123
+
124
+
125
+ def test_everything_deselected_is_zero_tests(repo):
126
+ ep(repo, *say("3 deselected in 0.01s"))
127
+ r = ep(repo, "check", "--strict")
128
+ assert r.returncode == 1 and "ran 0 tests" in r.stdout
@@ -0,0 +1,38 @@
1
+ """Counts() against real runner output.
2
+
3
+ Fixtures in tests/fixtures/ are real stdout+stderr (merged, no TTY, as `exitproof run`
4
+ sees it) captured from throwaway projects written with known counts. The expected
5
+ values below come from those projects, not from the parser:
6
+ red = 3 passing, 1 failing, 2 skipped/ignored tests
7
+ green = 3 passing, 2 skipped/ignored tests
8
+ empty = pytest with a test file that defines no tests
9
+ Runners: pytest 8, python -m unittest -v, cargo test, jest, vitest run.
10
+ go test was not captured (go is not installed on the capture machine).
11
+ """
12
+ from pathlib import Path
13
+
14
+ import pytest
15
+
16
+ from exitproof import Counts
17
+
18
+ FIX = Path(__file__).parent / "fixtures"
19
+ RED = {"passed": 3, "failed": 1, "skipped": 2, "errors": 0}
20
+ GREEN = {"passed": 3, "failed": 0, "skipped": 2, "errors": 0}
21
+ ZERO = {"passed": 0, "failed": 0, "skipped": 0, "errors": 0}
22
+
23
+ CASES = [(f"{r}_{c}", exp) for r in ("pytest", "unittest", "cargo", "jest", "vitest")
24
+ for c, exp in (("red", RED), ("green", GREEN))]
25
+ CASES.append(("pytest_empty", ZERO))
26
+
27
+
28
+ def parse(name: str):
29
+ c = Counts()
30
+ with open(FIX / f"{name}.txt", encoding="utf-8") as f:
31
+ for line in f:
32
+ c.feed(line)
33
+ return c.result()
34
+
35
+
36
+ @pytest.mark.parametrize("name,expected", CASES)
37
+ def test_real_runner_output(name, expected):
38
+ assert parse(name) == expected