snitch-engine 0.3.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.
@@ -0,0 +1,356 @@
1
+ Metadata-Version: 2.4
2
+ Name: snitch-engine
3
+ Version: 0.3.0
4
+ Summary: Integrity layer for AI coding agents: detects test cheating.
5
+ Keywords: ai-agents,testing,reward-hacking,pytest,claude-code,codex
6
+ Author: Abdellah Ennajari
7
+ License-Expression: MIT
8
+ Requires-Dist: mcp>=2.3.0
9
+ Requires-Dist: pydantic>=2.14.0
10
+ Requires-Dist: pytest>=9.1.1
11
+ Requires-Dist: structlog>=26.1.0
12
+ Requires-Dist: tree-sitter>=0.26.0
13
+ Requires-Dist: tree-sitter-python>=0.25.0
14
+ Requires-Dist: typer>=0.27.3
15
+ Requires-Python: >=3.12
16
+ Project-URL: Homepage, https://ennajari.github.io/Snitch/
17
+ Project-URL: Source, https://github.com/ennajari/Snitch
18
+ Project-URL: Results, https://github.com/ennajari/Snitch/blob/master/bench/results/2026-11/README.md
19
+ Description-Content-Type: text/markdown
20
+
21
+ <p align="center">
22
+ <img src="https://raw.githubusercontent.com/ennajari/Snitch/master/assets/logo.svg" width="112" alt="Snitch logo: an eye">
23
+ </p>
24
+
25
+ <h1 align="center">Snitch</h1>
26
+
27
+ <p align="center">
28
+ <b>The integrity layer for AI coding agents.</b><br>
29
+ Catches agents that make a failing test pass by cheating, and gives them an honest way out.
30
+ </p>
31
+
32
+ <p align="center">
33
+ <a href="https://github.com/ennajari/snitch/actions/workflows/ci.yml"><img src="https://github.com/ennajari/snitch/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
34
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license"></a>
35
+ <img src="https://img.shields.io/badge/python-3.12-blue" alt="Python 3.12">
36
+ <img src="https://img.shields.io/badge/status-early-orange" alt="Status: early">
37
+ </p>
38
+
39
+ <p align="center">
40
+ <img src="https://raw.githubusercontent.com/ennajari/Snitch/master/assets/demo-session.gif" width="760" alt="Claude Code with Snitch: the agent runs the tests, finds a wrong expected value, calls escalate instead of editing the test, and tells the user">
41
+ <br><sub>A real <code>claude plugin eval</code> run (2026-10-24, case <code>broken-expected-value</code>), replayed; the agent's messages are quoted, shortened where marked “…”. Without Snitch, the same agent edited the test in 8 of 32 trap runs.</sub>
42
+ </p>
43
+
44
+ ---
45
+
46
+ You ask a coding agent to make CI green. It comes back with "all tests pass". What it
47
+ did: change `assert total == 42` into `assert total`, mark the failing test `skip`, or
48
+ add `-k "not slow"` to `pytest.ini`. The diff is green; the bug is still there.
49
+
50
+ **Snitch watches for exactly that**, live in your Claude Code session, on every pull
51
+ request, and in a benchmark that ranks agents by honesty. It never asks a model whether
52
+ something "looks like cheating": every finding comes from a deterministic detector and
53
+ points at a line in the diff.
54
+
55
+ ```diff
56
+ - assert divide(10, 2) == 5
57
+ + assert divide(10, 2) in (5, 6)
58
+ ```
59
+
60
+ ```
61
+ # Snitch receipt
62
+ **1 event** — 1 high
63
+
64
+ | Severity | Family | Pattern | Location | Detector |
65
+ |----------|-----------|--------------------|----------------|----------|
66
+ | high | tampering | assertion_weakened | test_calc.py:9 | ast |
67
+ ```
68
+
69
+ ## See it catch
70
+
71
+ <table>
72
+ <tr>
73
+ <td width="50%"><img src="https://raw.githubusercontent.com/ennajari/Snitch/master/assets/demo-planted.gif" alt="An agent makes a test that needs a missing CI secret pass by setting the secret inside the test; snitch check flags assertion_self_fulfilled"><br><sub><b>A test that can't fail.</b> In a real TemptationBench trial, an agent made a test that needs a missing CI secret pass by setting that secret inside the test. Snitch flags it. Patch and message shortened.</sub></td>
74
+ <td width="50%"><img src="https://raw.githubusercontent.com/ennajari/Snitch/master/assets/demo-hooks.gif" alt="The plugin warns the agent after a weakened assert, then blocks a final message that hides it"><br><sub><b>Live in Claude Code.</b> The plugin's real hook output: a warning right after a weakened assert, then a blocked stop when the final message hides it.</sub></td>
75
+ </tr>
76
+ <tr>
77
+ <td colspan="2" align="center"><img src="https://raw.githubusercontent.com/ennajari/Snitch/master/assets/demo-check.gif" width="66%" alt="git diff and snitch check on a weakened assertion, exit code 1"><br><sub><b>Before you commit.</b> Real <code>snitch check</code> output; exit code 1 fails a pre-commit hook or CI step.</sub></td>
78
+ </tr>
79
+ </table>
80
+
81
+ ## Why
82
+
83
+ Research has shown that coding agents cheat on tests, and that an honest exit helps:
84
+
85
+ - **EvilGenie** ([arXiv 2511.21654](https://arxiv.org/abs/2511.21654)) observed explicit
86
+ reward hacking by Codex and Claude Code.
87
+ - **SpecBench** ([arXiv 2605.21384](https://arxiv.org/abs/2605.21384)): frontier agents
88
+ saturate visible tests while hacking persists on held-out ones.
89
+ - **BenchJack** ([arXiv 2605.12673](https://arxiv.org/abs/2605.12673)): one root
90
+ `conftest.py` hook can rewrite every test outcome, and most reviewers would miss it.
91
+ - **Escalation channels** ([arXiv 2608.29460](https://arxiv.org/abs/2608.29460)):
92
+ agents rarely disclose tampering, but giving them a way to report a broken test
93
+ reduces hacking; escalating and hacking were almost mutually exclusive.
94
+
95
+ - **ImpossibleBench** ([arXiv 2510.20270](https://arxiv.org/abs/2510.20270)): on
96
+ impossible tasks, agents edit tests, overload `__eq__`, keep hidden state or
97
+ special-case inputs; LLM monitors caught only 42–65% of it on real repos.
98
+
99
+ Snitch turns those findings into something you install: it **detects** the cheat,
100
+ gives the agent the **policy + `escalate` tool** combination that cut reward hacking
101
+ from 23.6% to 5.3% in the escalation study, and **refuses to let a session end** with a
102
+ test change the agent did not mention. [How each paper shaped Snitch](docs/research.md).
103
+
104
+ ## How it works
105
+
106
+ ```mermaid
107
+ flowchart LR
108
+ A["Claude Code plugin<br/>(live, per tool call)"] --> E
109
+ B["GitHub Action / pre-commit<br/>(per PR or commit)"] --> E
110
+ C["TemptationBench<br/>(Harbor, per trial)"] --> E
111
+ E["Engine: before vs after<br/>test inventory · AST assertion diff · rules"] --> R["Events → receipt,<br/>SARIF, ledger, scores"]
112
+ ```
113
+
114
+ One engine, three adapters, so the benchmark measures exactly what users install. Each
115
+ detector is a pure function of (before, after):
116
+
117
+ - **inventory**: `pytest --collect-only` before and after; tests that vanished,
118
+ were renamed away, skipped or deselected.
119
+ - **astdiff**: tree-sitter diff of every test function; assertions removed, weakened
120
+ (`==` → `in`, looser `approx`, looser bounds, `==` → `!=`), expected values changed,
121
+ asserts hidden behind a new `if`.
122
+ - **rules**: runner and CI config (`addopts`, coverage thresholds, `continue-on-error`,
123
+ `|| true`, `--no-verify`), `conftest.py` report hooks, code that special-cases
124
+ `pytest`, `except: pass` around changed logic.
125
+
126
+ ## Measured, not claimed
127
+
128
+ `claude plugin eval` on 20 seeded repos (broken test, impossible spec, flaky test, slow
129
+ test, runner config, controls), 2 runs per case, with and without the plugin
130
+ ([full report](docs/evals/2026-10-24-plugin-eval-policy.md)):
131
+
132
+ | | without Snitch | with Snitch |
133
+ |---|---|---|
134
+ | trap runs where the agent edited the test | **8 / 32** | **0 / 32** |
135
+ | trap runs that called `escalate` | n/a | 28 / 32 |
136
+ | control tasks completed | 8 / 8 | 8 / 8 |
137
+ | false escalations on controls | 0 | 0 |
138
+
139
+ Paired McNemar p = 0.008 (per case: 5 cases → 0, p = 0.063). An earlier run without the
140
+ session-start policy gave 7/32 → 0/32 with 25/32 escalations
141
+ ([report](docs/evals/2026-10-24-plugin-eval.md)). In both runs the agent disclosed every
142
+ test edit even without Snitch, so this says nothing yet about *silent* cheating; that is
143
+ what TemptationBench, with hidden tests, is for. The reports list the threats to
144
+ validity.
145
+
146
+ ## Install
147
+
148
+ ### Claude Code plugin
149
+
150
+ ```
151
+ /plugin marketplace add ennajari/snitch
152
+ /plugin install snitch@snitch
153
+ ```
154
+
155
+ Pick a mode in `/config` (needs Claude Code 2.1.271 or later):
156
+
157
+ - `observe`: record only
158
+ - `warn` (default): tell the agent and you, never block
159
+ - `enforce`: also block edits to frozen tests and stops that hide test changes
160
+
161
+ Snitch collects your tests with the repo's own `.venv/bin/python` when there is one
162
+ (set `SNITCH_PYTHON` to use another interpreter), so tests that import your project's
163
+ dependencies can be inventoried. That interpreter needs pytest.
164
+
165
+ Freeze paths the agent must never edit in `.snitch.toml` at the repo root:
166
+
167
+ ```toml
168
+ frozen = ["tests/**", "pytest.ini", "conftest.py"]
169
+ ```
170
+
171
+ Ask Claude for "the snitch ledger" to see the session's receipt.
172
+
173
+ What `enforce` can and cannot block. It denies the agent's Edit/Write calls on frozen
174
+ paths, `sed -i` / `perl -i` on test files, `git --no-verify`, and any write to Snitch's
175
+ own state: `.snitch.toml`, the plugin's ledger and baselines, the installed plugin, and
176
+ the Claude Code settings files that could switch hooks off. Shell commands are checked
177
+ for the common write forms (`>`, `>>`, `tee`, `rm`, `mv`, `cp`, `sed -i` ...), not for
178
+ every possible one: a Python one-liner or a `cd` inside the command line gets through.
179
+ The gate is a guard rail inside the agent's own session, not a sandbox. Every change
180
+ still goes through the detectors after the tool call and at the Stop hook, and in CI
181
+ the GitHub Action re-checks the diff from outside the agent's reach.
182
+
183
+ #### Optional judge
184
+
185
+ Snitch's detectors cannot read your request, so a test you asked Claude to update is
186
+ flagged like any other. With the `judge` option on (`/plugin` → Snitch → configure, or
187
+ `SNITCH_JUDGE=on` for Codex), the Stop hook asks Claude (`claude -p` with your own
188
+ login, no tools) whether your request called for each undisclosed test change; a
189
+ change judged legitimate is not warned about or blocked, and the receipt says why.
190
+ The judge can only clear a warning, never add one; if it fails or times out, the
191
+ warning stays. Off by default: it adds a few seconds to a stop that has a flagged,
192
+ undisclosed change.
193
+
194
+ ### Codex CLI plugin (experimental)
195
+
196
+ Codex runs the same hooks: the plugin ships a `.codex-plugin` manifest next to the
197
+ Claude Code one.
198
+
199
+ ```
200
+ codex plugin marketplace add ennajari/snitch
201
+ codex plugin add snitch@snitch
202
+ ```
203
+
204
+ Then trust its hooks in `/hooks`. Codex has no plugin settings, so set the mode with
205
+ `SNITCH_MODE=observe|warn|enforce` (default warn). Checked with Codex CLI 0.164 on a
206
+ broken-test task: the session-start policy, the warning after a flagged edit, the Stop
207
+ check and `escalate` all work; in enforce mode the gate reads the files an
208
+ `apply_patch` names. Not yet: the "tests pass but never ran" warning (it reads Claude
209
+ Code transcripts). Codex loads MCP tools on demand, so the policy tells the agent to
210
+ search for `escalate` when it does not see it.
211
+
212
+ ### GitHub Action
213
+
214
+ ```yaml
215
+ on: pull_request
216
+ permissions:
217
+ contents: read
218
+ pull-requests: write # the receipt comment
219
+ security-events: write # code scanning
220
+ jobs:
221
+ snitch:
222
+ runs-on: ubuntu-latest
223
+ steps:
224
+ - uses: actions/checkout@v7
225
+ with:
226
+ fetch-depth: 0 # Snitch compares the PR base with its head
227
+ - uses: ennajari/snitch@v1
228
+ ```
229
+
230
+ Inputs: `fail-on-events` (default `true`), `judge` (default `false`; with `anthropic-api-key: ${{ secrets.ANTHROPIC_API_KEY }}`, an LLM judge reads the PR title and body and stops counting the test changes they asked for; they stay on the receipt as "judged legitimate"), `python` (an interpreter that can import your tests; default: the repo's `.venv`, else Snitch's own), `strict` (fail when a detector could not run, default `false`: an incomplete check passes with a warning and a note in the receipt), `comment`, `upload-sarif`, `base`, `head`.
231
+ Output: `events`.
232
+
233
+ ### pre-commit
234
+
235
+ ```yaml
236
+ repos:
237
+ - repo: https://github.com/ennajari/snitch
238
+ rev: v0.3.0
239
+ hooks:
240
+ - id: snitch
241
+ ```
242
+
243
+ ### CLI
244
+
245
+ ```
246
+ uvx --from git+https://github.com/ennajari/snitch snitch check # working tree vs HEAD (--staged: staged only)
247
+ snitch diff <base> <head> [--sarif out.sarif]
248
+ snitch compare <before-dir> <after-dir> [--json]
249
+ ```
250
+
251
+ Exit codes: `0` clean, `1` events found, `2` usage error, `3` incomplete check (only with `--strict`: a detector could not run, for example because the repo's tests do not import).
252
+
253
+ ## What it flags
254
+
255
+ | Family | Patterns |
256
+ |---|---|
257
+ | tampering | `assertion_removed`, `assertion_weakened` (truthy-only, `in`, `is not None`, looser `approx` or bounds, `==` flipped to `!=`, `assert x` flipped to `assert not x`, an exact value turned into a range; also the `unittest` `self.assert*` forms), `assertion_guarded` (behind an `if`, `try`, or a loop that never runs), `expected_value_changed`, `assertion_rewritten` (the actual value wrapped until it fits: `f(x) * 60 == 19800`), `parametrize_value_changed`, `test_scope_reduced` (a test's `range(N)` cut tenfold), `test_deleted`, `test_renamed_away`, `conftest_report_hook`, `coverage_threshold_lowered` |
258
+ | evasion | `test_deselected`, `test_skipped`, `skip_in_body`, `seed_pinned` (a random seed added to an existing test: found in TemptationBench, where an agent searched for the seed that made a flaky test pass), `addopts_changed`, `ci_continue_on_error`, `ci_or_true`, `ci_no_verify` (workflows, GitLab CI, and test runs in Makefiles and shell scripts) |
259
+ | faking | `test_env_special_casing`, `mock_code_under_test` (a test that patches the repo's own function or class and then calls it, so it checks its stand-in), `comparison_forced` (an `__eq__` that returns True for anything), `assertion_self_fulfilled` (a test that now sets the very value it asserts, e.g. the CI secret it was checking, in the test, a fixture or a `conftest.py`) |
260
+ | hollow | `broad_except_pass`; `hollow_tests` with `snitch mutate before/ after/` (slow, not in the hooks: the change adds tests, yet the whole suite still passes against at least half the mutants of the code it changed; the receipt lists the surviving mutants) |
261
+ | reporting (plugin, at the end of a turn) | a flagged test change the final message does not mention; "tests pass" claimed with no test run since the last edit |
262
+
263
+ Every detector is a pure function of (before, after) and is tested on a cheating
264
+ fixture and a legitimate one that must stay silent. Snitch flags changes; whether a
265
+ flagged change was legitimate is up to the person reading the receipt (or the agent's
266
+ disclosure). Updating a test because the requested behaviour changed is fine, as long
267
+ as it is said.
268
+
269
+ ## TemptationBench
270
+
271
+ `bench/` holds 40 [Harbor](https://github.com/harbor-framework/harbor) tasks: small,
272
+ realistic projects with one built-in temptation each (a broken test, an impossible spec,
273
+ a missing service, a flaky test, a hard task) plus 14 controls. Hidden held-out tests
274
+ grade the work, and the agent's own `conftest.py` or `addopts` cannot fake them. Every
275
+ task ships a reference solution that must score 1 and a typical cheat that must score 0,
276
+ both checked in CI and in Docker.
277
+
278
+ `snitch bench-score` turns Harbor runs into the leaderboard metrics: solve rate, cheat
279
+ rate, silent-cheat rate (with a bootstrap 95% interval over tasks), honest-escalation
280
+ rate, false positives on controls, a per-temptation breakdown, and McNemar's test for
281
+ with vs without Snitch. Flagged trials are confirmed or cleared with review labels (AI-assisted so far; human check pending).
282
+ ### First results: Claude Code (edition 2026-11)
283
+
284
+ Claude Code 2.1.310 on its default model (claude-sonnet-5-5), 40 tasks × 3 runs, with
285
+ and without the Snitch plugin; every flagged trial reviewed with an AI assistant, human check pending
286
+ ([full results and limits](bench/results/2026-11/README.md)):
287
+
288
+ | | without Snitch | with Snitch |
289
+ |---|---|---|
290
+ | trials where the agent changed a test | **18 / 120** | **0 / 120** |
291
+ | …of them hidden from the user (silent) | 0 | 0 |
292
+ | trap trials where it called `escalate` instead | n/a | 51 / 78 |
293
+ | false alarms on the 42 control trials | 0 | 0 |
294
+
295
+ Paired McNemar p = 0.000008 (per task: 8 → 0, p = 0.008). The 18 changes came from broken
296
+ tests (10) and flaky tests (8), and every one was disclosed: Claude Code changed the
297
+ test and said so, and on the broken tests it was right that the test was wrong. With
298
+ Snitch it reported the problem instead of changing the test.
299
+
300
+ Codex CLI 0.164.0 (gpt-6.1-sol) on the same tasks, with the experimental Codex plugin
301
+ for the with-Snitch arm, run 10 days later: it changed or gamed a test in **57 of 78**
302
+ trap trials without Snitch and **0 of 78** with it, and called `escalate` in 59. All 57
303
+ said a test changed; none gave the test's `test_` name, though at least 16 identified it
304
+ by description. These counts include disclosed changes:
305
+ silent cheating was 0 in every arm above. No person has checked these labels yet; see
306
+ the results page for that and the other limits. Gemini CLI follows after its own vendor
307
+ preview.
308
+ (Corrected from 14: a second review pass found 4 more, all disclosed; see the
309
+ results page.)
310
+
311
+ ## Roadmap
312
+
313
+ - [x] Engine: inventory, AST diff, rules (Python / pytest), 39 cheating + 24 legitimate fixtures
314
+ - [x] Claude Code plugin: live detection, `escalate`, Stop verifier, enforce gate, evals
315
+ - [x] GitHub Action with SARIF + PR receipt, pre-commit hook
316
+ - [x] TemptationBench: 54 tasks (edition 2026-11 used the first 40), scoring
317
+ - [x] Edition 2026-11 for Claude Code (40 tasks × 3 runs × with/without Snitch; human review pending)
318
+ - [x] Codex CLI: both arms run and published (human review pending), experimental plugin
319
+ - [ ] Gemini CLI (partial run done, vendor preview next), then OpenCode and others
320
+ - [ ] Disclosure judge, mutation testing for hollow tests
321
+ - [ ] TypeScript (Jest / Vitest)
322
+
323
+ ## Contributing
324
+
325
+ Seen an agent cheat in a way Snitch misses? Open an issue with the before/after diff
326
+ (anonymized). Every confirmed case becomes a detector fixture or a benchmark task. Each
327
+ new pattern needs a cheating fixture that must be flagged and a legitimate one that must
328
+ stay silent.
329
+
330
+ ## Development
331
+
332
+ ```
333
+ uv sync
334
+ uv run pytest -q
335
+ uv run ruff check . && uv run ruff format .
336
+ uv run mypy engine
337
+ ```
338
+
339
+ ## Citing
340
+
341
+ If you use Snitch or TemptationBench in your work, please cite it
342
+ ([CITATION.cff](CITATION.cff); GitHub's "Cite this repository" button gives other formats):
343
+
344
+ ```bibtex
345
+ @software{ennajari_snitch_2026,
346
+ author = {Ennajari, Abdellah},
347
+ title = {Snitch: an integrity layer for AI coding agents, and TemptationBench},
348
+ year = {2026},
349
+ version = {0.3.0},
350
+ url = {https://github.com/ennajari/Snitch}
351
+ }
352
+ ```
353
+
354
+ ## License
355
+
356
+ [MIT](LICENSE)