refusectomy 0.2.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.
- refusectomy-0.2.0/LICENSE +21 -0
- refusectomy-0.2.0/PKG-INFO +211 -0
- refusectomy-0.2.0/README.md +187 -0
- refusectomy-0.2.0/pyproject.toml +43 -0
- refusectomy-0.2.0/setup.cfg +4 -0
- refusectomy-0.2.0/src/refusectomy/__init__.py +8 -0
- refusectomy-0.2.0/src/refusectomy/__main__.py +3 -0
- refusectomy-0.2.0/src/refusectomy/agents.py +153 -0
- refusectomy-0.2.0/src/refusectomy/claude_code.py +2747 -0
- refusectomy-0.2.0/src/refusectomy/cli.py +91 -0
- refusectomy-0.2.0/src/refusectomy/excise.py +310 -0
- refusectomy-0.2.0/src/refusectomy/providers.py +253 -0
- refusectomy-0.2.0/src/refusectomy/proxy.py +302 -0
- refusectomy-0.2.0/src/refusectomy/watch.py +248 -0
- refusectomy-0.2.0/src/refusectomy.egg-info/PKG-INFO +211 -0
- refusectomy-0.2.0/src/refusectomy.egg-info/SOURCES.txt +23 -0
- refusectomy-0.2.0/src/refusectomy.egg-info/dependency_links.txt +1 -0
- refusectomy-0.2.0/src/refusectomy.egg-info/entry_points.txt +2 -0
- refusectomy-0.2.0/src/refusectomy.egg-info/top_level.txt +1 -0
- refusectomy-0.2.0/tests/test_agents_watch.py +135 -0
- refusectomy-0.2.0/tests/test_claude_code.py +471 -0
- refusectomy-0.2.0/tests/test_excise.py +161 -0
- refusectomy-0.2.0/tests/test_metadata.py +32 -0
- refusectomy-0.2.0/tests/test_providers.py +122 -0
- refusectomy-0.2.0/tests/test_proxy.py +153 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sebastian S. Cocioba, Binomica Labs
|
|
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,211 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: refusectomy
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Find, explain and live-monitor model refusals in CLI coding agents (Claude Code, and any agent through a local proxy).
|
|
5
|
+
Author: Sebastian S. Cocioba, Binomica Labs
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Binomica-Labs/refusectomy
|
|
8
|
+
Project-URL: Repository, https://github.com/Binomica-Labs/refusectomy
|
|
9
|
+
Project-URL: Issues, https://github.com/Binomica-Labs/refusectomy/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/Binomica-Labs/refusectomy/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: claude,claude-code,llm,refusal,safety-classifier,agents,monitoring
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Topic :: Software Development :: Debuggers
|
|
19
|
+
Classifier: Topic :: System :: Monitoring
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# Refusectomy
|
|
26
|
+
|
|
27
|
+
[](https://pypi.org/project/refusectomy/)
|
|
28
|
+
[](https://www.python.org/)
|
|
29
|
+
[](https://github.com/Binomica-Labs/refusectomy/actions/workflows/test.yml)
|
|
30
|
+
[](https://opensource.org/licenses/MIT)
|
|
31
|
+
[](https://github.com/Binomica-Labs/refusectomy)
|
|
32
|
+
|
|
33
|
+
**Find, explain and live-monitor model refusals in CLI coding agents.**
|
|
34
|
+
|
|
35
|
+
By Sebastian S. Cocioba, Binomica Labs.
|
|
36
|
+
|
|
37
|
+
When a safety classifier declines legitimate work, an agent session rarely fails just once. It
|
|
38
|
+
keeps failing, and the obvious fixes (rephrasing, switching models, trimming context) mostly
|
|
39
|
+
don't help. Refusectomy measures what actually happened on your machine, watches for it as it
|
|
40
|
+
happens, and tells you what the evidence supports. It identifies refused text by digest, never by
|
|
41
|
+
printing it.
|
|
42
|
+
|
|
43
|
+
## What it can see, per agent
|
|
44
|
+
|
|
45
|
+
| agent | how Refusectomy reads it | what you get |
|
|
46
|
+
|---|---|---|
|
|
47
|
+
| **Claude Code** | its session logs, plus a Stop hook | every refusal with the classifier's category, the model, Claude Code's switch to a fallback model, and the refused message (as a digest); full forensics |
|
|
48
|
+
| **Any agent whose API base URL you can set** (Anthropic, OpenAI or Gemini wire format) | `refusectomy proxy` | every response's stop reason as it streams, request ids, and the prompt's digest |
|
|
49
|
+
| **GitHub Copilot CLI** | its session log | tool failures and session errors only: it does not log the model's stop reason |
|
|
50
|
+
| **Antigravity CLI** | its session log | error steps; a safety block only when the agent logs it as an error |
|
|
51
|
+
|
|
52
|
+
`refusectomy agents` prints this table for your own machine.
|
|
53
|
+
|
|
54
|
+
## Install
|
|
55
|
+
|
|
56
|
+
Python 3.10 or newer, no dependencies.
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pipx install refusectomy # or: uv tool install refusectomy
|
|
60
|
+
pipx install . # from a checkout
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Claude Code
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
refusectomy audit # check the parser's assumptions against your transcripts
|
|
67
|
+
refusectomy profile # rates, stickiness, the model comparison, confounds
|
|
68
|
+
refusectomy remedy --category bio # the playbook, rendered from your own profile
|
|
69
|
+
refusectomy watch # live, in a second terminal
|
|
70
|
+
refusectomy report --project DIR # a support-ticket bundle: request ids and digests
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
To get a warning inside Claude Code the moment a session declines, add the hook to
|
|
74
|
+
`~/.claude/settings.json`:
|
|
75
|
+
|
|
76
|
+
```json
|
|
77
|
+
{ "hooks": {
|
|
78
|
+
"Stop": [{ "hooks": [{ "type": "command", "timeout": 10,
|
|
79
|
+
"command": "refusectomy hook claude-code 2>/dev/null || true" }] }],
|
|
80
|
+
"SessionStart": [{ "hooks": [{ "type": "command", "timeout": 10,
|
|
81
|
+
"command": "refusectomy hook claude-code 2>/dev/null || true" }] }] } }
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The warning is shown to you as a `systemMessage`. It is never added to the model's context:
|
|
85
|
+
feeding "you were just declined" back into the context that declined is how one decline turns
|
|
86
|
+
into a run of them.
|
|
87
|
+
|
|
88
|
+
## Excise: a clean copy of a declined session
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
refusectomy excise --dry-run # what would be removed from the current session
|
|
92
|
+
refusectomy excise # write the clean copy and print its /resume command
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
To excise between turns, add `--excise` to the hook command (or put `{"excise": true}` in
|
|
96
|
+
`config.json` in the state directory, or set `REFUSECTOMY_EXCISE=1`). When a session declines,
|
|
97
|
+
the warning then names a clean copy to `/resume`. `refusectomy watch --excise` does the same from
|
|
98
|
+
the monitor, waiting until the session's log has gone quiet.
|
|
99
|
+
|
|
100
|
+
**What it removes: the decline's own debris, nothing else.**
|
|
101
|
+
|
|
102
|
+
- Every record of the declined response: the partial output that the refusal docs say to discard.
|
|
103
|
+
- The harness's placeholder notice and its refusal record.
|
|
104
|
+
- The hidden "meta" notice message that Claude Code otherwise sends back to the model.
|
|
105
|
+
- The results of any tool calls made inside the declined response. A call that had already run
|
|
106
|
+
keeps its effects on disk, and the report says how many did.
|
|
107
|
+
|
|
108
|
+
**What it keeps: everything else, byte for byte.** That covers your messages, including any that
|
|
109
|
+
quote the notice, every response that wasn't declined, and all the work material. Excision never
|
|
110
|
+
rewords anything, and never removes content because a classifier reacts to it, so the classifier
|
|
111
|
+
still sees everything you actually asked.
|
|
112
|
+
|
|
113
|
+
**How the copy behaves.** The source session is never modified. Resuming the copy starts on your
|
|
114
|
+
default model, which also releases the refusal-fallback lock.
|
|
115
|
+
|
|
116
|
+
This was verified end to end: Claude Code resumes a cleaned copy. Asked whether any earlier message
|
|
117
|
+
mentioned a safety classifier, the model in the cleaned copy says no, and the same session
|
|
118
|
+
uncleaned says yes.
|
|
119
|
+
|
|
120
|
+
**Whether it prevents the next decline is not yet known.** The run of declines could come from the
|
|
121
|
+
debris, or from the material that is still in context. `profile` reports what happened after each
|
|
122
|
+
clean copy was resumed. Until there is data, abandoning the session remains the measured lever.
|
|
123
|
+
|
|
124
|
+
## Any other agent, through the proxy
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
refusectomy proxy # loopback only; prints the URL for each provider
|
|
128
|
+
# then point the agent at it, e.g.
|
|
129
|
+
ANTHROPIC_BASE_URL=http://127.0.0.1:8787/anthropic your-agent
|
|
130
|
+
OPENAI_BASE_URL=http://127.0.0.1:8787/openai/v1 your-agent
|
|
131
|
+
refusectomy watch # in another terminal: every agent, one timeline
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
The proxy forwards each request unchanged to the real API over verified TLS. It relays the
|
|
135
|
+
response back as it streams, reading the stop reason as it goes by. It recognises:
|
|
136
|
+
|
|
137
|
+
- Anthropic: `stop_reason: "refusal"`, with its category.
|
|
138
|
+
- OpenAI: a `content_filter` finish, a `refusal` field, or a Responses refusal or content-filter
|
|
139
|
+
cut-off.
|
|
140
|
+
- Gemini: a safety finish reason or a blocked prompt.
|
|
141
|
+
|
|
142
|
+
Agents that only talk to their vendor's own backend, such as Copilot CLI and Antigravity, can't
|
|
143
|
+
be proxied without intercepting TLS, which Refusectomy doesn't do.
|
|
144
|
+
|
|
145
|
+
## What the evidence says
|
|
146
|
+
|
|
147
|
+
These come from the corpus this tool was built on. `profile` re-measures each of them on yours.
|
|
148
|
+
|
|
149
|
+
1. **Declines cluster within a session.** Once one lands, the next request in that session is
|
|
150
|
+
far more likely to decline than a request in a fresh session. Abandon the session; don't
|
|
151
|
+
rephrase inside it.
|
|
152
|
+
2. **The refused message is rarely the problem.** Most refused messages are a single word, like
|
|
153
|
+
"continue". The decline is about the work accumulated in the context, not the phrasing.
|
|
154
|
+
3. **Claude Code moves a declined session to another model.** When Opus 5.5 or Fable declines,
|
|
155
|
+
Claude Code retries on Opus 5 and keeps the session there until `/clear` or `/model`. The
|
|
156
|
+
retry usually rescues the turn, but the session stays hot.
|
|
157
|
+
4. **Compare models only before a session's first decline.** After it, the fallback and the
|
|
158
|
+
cascade decide which model you're on, so turn-level comparisons measure the fallback, not the
|
|
159
|
+
model. Measured the clean way, this corpus showed no evidence that switching models helps.
|
|
160
|
+
5. **Context size and memory files weren't levers.** The apparent effect of context size was
|
|
161
|
+
survivorship. No memory file was read more often before early declines than in clean
|
|
162
|
+
sessions.
|
|
163
|
+
6. **The real fix is institutional.** For legitimate work, that means Anthropic's verification
|
|
164
|
+
programs for life sciences and for cyber, plus false-positive reports filed with request ids.
|
|
165
|
+
`report` builds that bundle.
|
|
166
|
+
|
|
167
|
+
`refusectomy profile` prints the numbers behind each one for your own machine, beside the controls
|
|
168
|
+
that keep them honest.
|
|
169
|
+
|
|
170
|
+
## Privacy and safety
|
|
171
|
+
|
|
172
|
+
- **Refused text is never printed.** It's identified by a sha256 digest and a character shape.
|
|
173
|
+
`--verbatim` writes it to a mode-0600 file for you to read; it never goes to stdout.
|
|
174
|
+
- **Everything stays local.** There is no telemetry and no network access, except the proxy
|
|
175
|
+
forwarding your agent's own requests to the API it was already calling.
|
|
176
|
+
- **The proxy records metadata only.** It listens on loopback only, and never records headers,
|
|
177
|
+
bodies, query strings (where Gemini can carry an API key) or text.
|
|
178
|
+
- **It only observes.** It never rewrites, retries, or searches for phrasings that get past a
|
|
179
|
+
classifier. `bisect` reports what reproduces a decline, nothing more.
|
|
180
|
+
- **Where files go.** Reports and state live in `$REFUSECTOMY_HOME`, or by default in
|
|
181
|
+
`~/.local/state/refusectomy` (Linux), `~/Library/Application Support/refusectomy` (macOS) or
|
|
182
|
+
`%LOCALAPPDATA%\refusectomy` (Windows).
|
|
183
|
+
|
|
184
|
+
## How it keeps itself honest
|
|
185
|
+
|
|
186
|
+
- `audit` checks the invariants its numbers depend on, against your own transcripts, and exits
|
|
187
|
+
non-zero if any fail.
|
|
188
|
+
- Every figure that `remedy` and the hook quote comes from your last `profile`; none is typed
|
|
189
|
+
into the source.
|
|
190
|
+
- Each bug fix has a regression test on synthetic transcripts. Each of those tests was checked by
|
|
191
|
+
putting the bug back and watching it fail.
|
|
192
|
+
|
|
193
|
+
## Development
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
python3 -m unittest discover -s tests -t .
|
|
197
|
+
PYTHONPATH=src python3 -m refusectomy audit
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
The code is in `src/refusectomy/`:
|
|
201
|
+
|
|
202
|
+
- `claude_code.py`: the transcript engine and forensics
|
|
203
|
+
- `providers.py`: each provider's refusal signals
|
|
204
|
+
- `proxy.py`, `agents.py`, `watch.py`: the live monitoring
|
|
205
|
+
- `cli.py`: the command
|
|
206
|
+
|
|
207
|
+
`analysis/` holds exploratory scripts that build on the package.
|
|
208
|
+
|
|
209
|
+
## License
|
|
210
|
+
|
|
211
|
+
MIT, copyright 2026 Sebastian S. Cocioba, Binomica Labs. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# Refusectomy
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/refusectomy/)
|
|
4
|
+
[](https://www.python.org/)
|
|
5
|
+
[](https://github.com/Binomica-Labs/refusectomy/actions/workflows/test.yml)
|
|
6
|
+
[](https://opensource.org/licenses/MIT)
|
|
7
|
+
[](https://github.com/Binomica-Labs/refusectomy)
|
|
8
|
+
|
|
9
|
+
**Find, explain and live-monitor model refusals in CLI coding agents.**
|
|
10
|
+
|
|
11
|
+
By Sebastian S. Cocioba, Binomica Labs.
|
|
12
|
+
|
|
13
|
+
When a safety classifier declines legitimate work, an agent session rarely fails just once. It
|
|
14
|
+
keeps failing, and the obvious fixes (rephrasing, switching models, trimming context) mostly
|
|
15
|
+
don't help. Refusectomy measures what actually happened on your machine, watches for it as it
|
|
16
|
+
happens, and tells you what the evidence supports. It identifies refused text by digest, never by
|
|
17
|
+
printing it.
|
|
18
|
+
|
|
19
|
+
## What it can see, per agent
|
|
20
|
+
|
|
21
|
+
| agent | how Refusectomy reads it | what you get |
|
|
22
|
+
|---|---|---|
|
|
23
|
+
| **Claude Code** | its session logs, plus a Stop hook | every refusal with the classifier's category, the model, Claude Code's switch to a fallback model, and the refused message (as a digest); full forensics |
|
|
24
|
+
| **Any agent whose API base URL you can set** (Anthropic, OpenAI or Gemini wire format) | `refusectomy proxy` | every response's stop reason as it streams, request ids, and the prompt's digest |
|
|
25
|
+
| **GitHub Copilot CLI** | its session log | tool failures and session errors only: it does not log the model's stop reason |
|
|
26
|
+
| **Antigravity CLI** | its session log | error steps; a safety block only when the agent logs it as an error |
|
|
27
|
+
|
|
28
|
+
`refusectomy agents` prints this table for your own machine.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
Python 3.10 or newer, no dependencies.
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pipx install refusectomy # or: uv tool install refusectomy
|
|
36
|
+
pipx install . # from a checkout
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Claude Code
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
refusectomy audit # check the parser's assumptions against your transcripts
|
|
43
|
+
refusectomy profile # rates, stickiness, the model comparison, confounds
|
|
44
|
+
refusectomy remedy --category bio # the playbook, rendered from your own profile
|
|
45
|
+
refusectomy watch # live, in a second terminal
|
|
46
|
+
refusectomy report --project DIR # a support-ticket bundle: request ids and digests
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
To get a warning inside Claude Code the moment a session declines, add the hook to
|
|
50
|
+
`~/.claude/settings.json`:
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{ "hooks": {
|
|
54
|
+
"Stop": [{ "hooks": [{ "type": "command", "timeout": 10,
|
|
55
|
+
"command": "refusectomy hook claude-code 2>/dev/null || true" }] }],
|
|
56
|
+
"SessionStart": [{ "hooks": [{ "type": "command", "timeout": 10,
|
|
57
|
+
"command": "refusectomy hook claude-code 2>/dev/null || true" }] }] } }
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The warning is shown to you as a `systemMessage`. It is never added to the model's context:
|
|
61
|
+
feeding "you were just declined" back into the context that declined is how one decline turns
|
|
62
|
+
into a run of them.
|
|
63
|
+
|
|
64
|
+
## Excise: a clean copy of a declined session
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
refusectomy excise --dry-run # what would be removed from the current session
|
|
68
|
+
refusectomy excise # write the clean copy and print its /resume command
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
To excise between turns, add `--excise` to the hook command (or put `{"excise": true}` in
|
|
72
|
+
`config.json` in the state directory, or set `REFUSECTOMY_EXCISE=1`). When a session declines,
|
|
73
|
+
the warning then names a clean copy to `/resume`. `refusectomy watch --excise` does the same from
|
|
74
|
+
the monitor, waiting until the session's log has gone quiet.
|
|
75
|
+
|
|
76
|
+
**What it removes: the decline's own debris, nothing else.**
|
|
77
|
+
|
|
78
|
+
- Every record of the declined response: the partial output that the refusal docs say to discard.
|
|
79
|
+
- The harness's placeholder notice and its refusal record.
|
|
80
|
+
- The hidden "meta" notice message that Claude Code otherwise sends back to the model.
|
|
81
|
+
- The results of any tool calls made inside the declined response. A call that had already run
|
|
82
|
+
keeps its effects on disk, and the report says how many did.
|
|
83
|
+
|
|
84
|
+
**What it keeps: everything else, byte for byte.** That covers your messages, including any that
|
|
85
|
+
quote the notice, every response that wasn't declined, and all the work material. Excision never
|
|
86
|
+
rewords anything, and never removes content because a classifier reacts to it, so the classifier
|
|
87
|
+
still sees everything you actually asked.
|
|
88
|
+
|
|
89
|
+
**How the copy behaves.** The source session is never modified. Resuming the copy starts on your
|
|
90
|
+
default model, which also releases the refusal-fallback lock.
|
|
91
|
+
|
|
92
|
+
This was verified end to end: Claude Code resumes a cleaned copy. Asked whether any earlier message
|
|
93
|
+
mentioned a safety classifier, the model in the cleaned copy says no, and the same session
|
|
94
|
+
uncleaned says yes.
|
|
95
|
+
|
|
96
|
+
**Whether it prevents the next decline is not yet known.** The run of declines could come from the
|
|
97
|
+
debris, or from the material that is still in context. `profile` reports what happened after each
|
|
98
|
+
clean copy was resumed. Until there is data, abandoning the session remains the measured lever.
|
|
99
|
+
|
|
100
|
+
## Any other agent, through the proxy
|
|
101
|
+
|
|
102
|
+
```bash
|
|
103
|
+
refusectomy proxy # loopback only; prints the URL for each provider
|
|
104
|
+
# then point the agent at it, e.g.
|
|
105
|
+
ANTHROPIC_BASE_URL=http://127.0.0.1:8787/anthropic your-agent
|
|
106
|
+
OPENAI_BASE_URL=http://127.0.0.1:8787/openai/v1 your-agent
|
|
107
|
+
refusectomy watch # in another terminal: every agent, one timeline
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
The proxy forwards each request unchanged to the real API over verified TLS. It relays the
|
|
111
|
+
response back as it streams, reading the stop reason as it goes by. It recognises:
|
|
112
|
+
|
|
113
|
+
- Anthropic: `stop_reason: "refusal"`, with its category.
|
|
114
|
+
- OpenAI: a `content_filter` finish, a `refusal` field, or a Responses refusal or content-filter
|
|
115
|
+
cut-off.
|
|
116
|
+
- Gemini: a safety finish reason or a blocked prompt.
|
|
117
|
+
|
|
118
|
+
Agents that only talk to their vendor's own backend, such as Copilot CLI and Antigravity, can't
|
|
119
|
+
be proxied without intercepting TLS, which Refusectomy doesn't do.
|
|
120
|
+
|
|
121
|
+
## What the evidence says
|
|
122
|
+
|
|
123
|
+
These come from the corpus this tool was built on. `profile` re-measures each of them on yours.
|
|
124
|
+
|
|
125
|
+
1. **Declines cluster within a session.** Once one lands, the next request in that session is
|
|
126
|
+
far more likely to decline than a request in a fresh session. Abandon the session; don't
|
|
127
|
+
rephrase inside it.
|
|
128
|
+
2. **The refused message is rarely the problem.** Most refused messages are a single word, like
|
|
129
|
+
"continue". The decline is about the work accumulated in the context, not the phrasing.
|
|
130
|
+
3. **Claude Code moves a declined session to another model.** When Opus 5.5 or Fable declines,
|
|
131
|
+
Claude Code retries on Opus 5 and keeps the session there until `/clear` or `/model`. The
|
|
132
|
+
retry usually rescues the turn, but the session stays hot.
|
|
133
|
+
4. **Compare models only before a session's first decline.** After it, the fallback and the
|
|
134
|
+
cascade decide which model you're on, so turn-level comparisons measure the fallback, not the
|
|
135
|
+
model. Measured the clean way, this corpus showed no evidence that switching models helps.
|
|
136
|
+
5. **Context size and memory files weren't levers.** The apparent effect of context size was
|
|
137
|
+
survivorship. No memory file was read more often before early declines than in clean
|
|
138
|
+
sessions.
|
|
139
|
+
6. **The real fix is institutional.** For legitimate work, that means Anthropic's verification
|
|
140
|
+
programs for life sciences and for cyber, plus false-positive reports filed with request ids.
|
|
141
|
+
`report` builds that bundle.
|
|
142
|
+
|
|
143
|
+
`refusectomy profile` prints the numbers behind each one for your own machine, beside the controls
|
|
144
|
+
that keep them honest.
|
|
145
|
+
|
|
146
|
+
## Privacy and safety
|
|
147
|
+
|
|
148
|
+
- **Refused text is never printed.** It's identified by a sha256 digest and a character shape.
|
|
149
|
+
`--verbatim` writes it to a mode-0600 file for you to read; it never goes to stdout.
|
|
150
|
+
- **Everything stays local.** There is no telemetry and no network access, except the proxy
|
|
151
|
+
forwarding your agent's own requests to the API it was already calling.
|
|
152
|
+
- **The proxy records metadata only.** It listens on loopback only, and never records headers,
|
|
153
|
+
bodies, query strings (where Gemini can carry an API key) or text.
|
|
154
|
+
- **It only observes.** It never rewrites, retries, or searches for phrasings that get past a
|
|
155
|
+
classifier. `bisect` reports what reproduces a decline, nothing more.
|
|
156
|
+
- **Where files go.** Reports and state live in `$REFUSECTOMY_HOME`, or by default in
|
|
157
|
+
`~/.local/state/refusectomy` (Linux), `~/Library/Application Support/refusectomy` (macOS) or
|
|
158
|
+
`%LOCALAPPDATA%\refusectomy` (Windows).
|
|
159
|
+
|
|
160
|
+
## How it keeps itself honest
|
|
161
|
+
|
|
162
|
+
- `audit` checks the invariants its numbers depend on, against your own transcripts, and exits
|
|
163
|
+
non-zero if any fail.
|
|
164
|
+
- Every figure that `remedy` and the hook quote comes from your last `profile`; none is typed
|
|
165
|
+
into the source.
|
|
166
|
+
- Each bug fix has a regression test on synthetic transcripts. Each of those tests was checked by
|
|
167
|
+
putting the bug back and watching it fail.
|
|
168
|
+
|
|
169
|
+
## Development
|
|
170
|
+
|
|
171
|
+
```bash
|
|
172
|
+
python3 -m unittest discover -s tests -t .
|
|
173
|
+
PYTHONPATH=src python3 -m refusectomy audit
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
The code is in `src/refusectomy/`:
|
|
177
|
+
|
|
178
|
+
- `claude_code.py`: the transcript engine and forensics
|
|
179
|
+
- `providers.py`: each provider's refusal signals
|
|
180
|
+
- `proxy.py`, `agents.py`, `watch.py`: the live monitoring
|
|
181
|
+
- `cli.py`: the command
|
|
182
|
+
|
|
183
|
+
`analysis/` holds exploratory scripts that build on the package.
|
|
184
|
+
|
|
185
|
+
## License
|
|
186
|
+
|
|
187
|
+
MIT, copyright 2026 Sebastian S. Cocioba, Binomica Labs. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "refusectomy"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Find, explain and live-monitor model refusals in CLI coding agents (Claude Code, and any agent through a local proxy)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Sebastian S. Cocioba" },
|
|
15
|
+
{ name = "Binomica Labs" },
|
|
16
|
+
]
|
|
17
|
+
dependencies = []
|
|
18
|
+
keywords = ["claude", "claude-code", "llm", "refusal", "safety-classifier", "agents", "monitoring"]
|
|
19
|
+
classifiers = [
|
|
20
|
+
"Development Status :: 3 - Alpha",
|
|
21
|
+
"Environment :: Console",
|
|
22
|
+
"Intended Audience :: Developers",
|
|
23
|
+
"Intended Audience :: Science/Research",
|
|
24
|
+
"Operating System :: OS Independent",
|
|
25
|
+
"Programming Language :: Python :: 3",
|
|
26
|
+
"Topic :: Software Development :: Debuggers",
|
|
27
|
+
"Topic :: System :: Monitoring",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://github.com/Binomica-Labs/refusectomy"
|
|
32
|
+
Repository = "https://github.com/Binomica-Labs/refusectomy"
|
|
33
|
+
Issues = "https://github.com/Binomica-Labs/refusectomy/issues"
|
|
34
|
+
Changelog = "https://github.com/Binomica-Labs/refusectomy/blob/main/CHANGELOG.md"
|
|
35
|
+
|
|
36
|
+
[project.scripts]
|
|
37
|
+
refusectomy = "refusectomy.cli:main"
|
|
38
|
+
|
|
39
|
+
[tool.setuptools.dynamic]
|
|
40
|
+
version = {attr = "refusectomy.__version__"}
|
|
41
|
+
|
|
42
|
+
[tool.setuptools.packages.find]
|
|
43
|
+
where = ["src"]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Refusectomy: find, explain and live-monitor model refusals in CLI coding agents.
|
|
2
|
+
|
|
3
|
+
Claude Code transcripts get the full forensics (`refusectomy.claude_code`); any agent whose
|
|
4
|
+
API base URL you can point at localhost is monitored live through `refusectomy proxy`; and
|
|
5
|
+
`refusectomy watch` tails the session logs of the agents it knows. Refused text is identified
|
|
6
|
+
by digest, never reproduced.
|
|
7
|
+
"""
|
|
8
|
+
__version__ = "0.2.0"
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""The CLI agents refusectomy knows: where their session logs live, and what those logs can say.
|
|
2
|
+
|
|
3
|
+
claude-code <CLAUDE_CONFIG_DIR or ~/.claude>/projects/**/*.jsonl
|
|
4
|
+
everything: each refusal with the classifier's category, the model, the
|
|
5
|
+
harness's switch to a fallback model, and (by digest) the refused message
|
|
6
|
+
copilot ~/.copilot/session-state/<session>/events.jsonl
|
|
7
|
+
no model stop reason is written, so refusals cannot be seen; tool failures
|
|
8
|
+
and session errors only. Its model traffic goes to GitHub's backend, which
|
|
9
|
+
refusectomy does not intercept
|
|
10
|
+
antigravity ~/.gemini/antigravity-cli/brain/<conversation>/.system_generated/logs/transcript_full.jsonl
|
|
11
|
+
error steps only; a safety block is seen only if the agent logs it as an
|
|
12
|
+
error, and only its status words (SAFETY, PROHIBITED_CONTENT, ...) are read
|
|
13
|
+
proxy signals.jsonl written by `refusectomy proxy` -- any agent pointed at it
|
|
14
|
+
|
|
15
|
+
A reader turns one log record into signals: dicts of enums and identifiers, never text.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import glob
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from typing import Callable
|
|
26
|
+
|
|
27
|
+
from refusectomy.providers import GEMINI_BLOCKS, GEMINI_RECITATION
|
|
28
|
+
|
|
29
|
+
GOOGLE_STATUS = {"RESOURCE_EXHAUSTED", "UNAVAILABLE", "DEADLINE_EXCEEDED", "PERMISSION_DENIED",
|
|
30
|
+
"UNAUTHENTICATED", "INVALID_ARGUMENT", "INTERNAL", "FAILED_PRECONDITION",
|
|
31
|
+
"NOT_FOUND", "CANCELLED", "ABORTED"}
|
|
32
|
+
_CODE = re.compile(r"^[A-Za-z0-9_.:-]{1,40}$")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Agent:
|
|
37
|
+
name: str
|
|
38
|
+
pattern: str
|
|
39
|
+
sees: str
|
|
40
|
+
watch: str
|
|
41
|
+
reader: Callable[[dict, str], list]
|
|
42
|
+
refusal_aware: bool
|
|
43
|
+
|
|
44
|
+
def files(self) -> list[str]:
|
|
45
|
+
return sorted(f for f in glob.glob(self.pattern, recursive=True) if os.path.isfile(f))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _enum(v) -> str | None:
|
|
49
|
+
"""A short code-like string, or nothing: free text never becomes a signal field."""
|
|
50
|
+
return v if isinstance(v, str) and _CODE.match(v) else None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _claude(rec: dict, path: str) -> list:
|
|
54
|
+
from refusectomy.claude_code import project_of
|
|
55
|
+
t = rec.get("type")
|
|
56
|
+
base = {"agent": "claude-code", "session": rec.get("sessionId") or "",
|
|
57
|
+
"project": project_of(path), "ts": rec.get("timestamp") or ""}
|
|
58
|
+
msg = rec.get("message")
|
|
59
|
+
if t == "assistant" and isinstance(msg, dict) and msg.get("stop_reason") == "refusal":
|
|
60
|
+
model = rec.get("requestedModel") or msg.get("model") or ""
|
|
61
|
+
if model == "<synthetic>":
|
|
62
|
+
return [] # the harness's own notice, not a response
|
|
63
|
+
sd = msg.get("stop_details") if isinstance(msg.get("stop_details"), dict) else {}
|
|
64
|
+
return [{**base, "kind": "refusal", "category": _enum(sd.get("category")), "model": model,
|
|
65
|
+
"request_id": rec.get("requestId"), "subagent": bool(rec.get("isSidechain")),
|
|
66
|
+
"mid_stream": bool(msg.get("content"))}]
|
|
67
|
+
if t == "system" and str(rec.get("subtype", "")).startswith("model_refusal"):
|
|
68
|
+
fb = rec.get("subtype") == "model_refusal_fallback"
|
|
69
|
+
return [{**base, "kind": "refusal", "category": _enum(rec.get("apiRefusalCategory")),
|
|
70
|
+
"model": rec.get("originalModel"), "request_id": rec.get("requestId"),
|
|
71
|
+
"warning": True, "fallback": rec.get("fallbackModel") if fb else None}]
|
|
72
|
+
return []
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _copilot(rec: dict, path: str) -> list:
|
|
76
|
+
t = str(rec.get("type") or "")
|
|
77
|
+
data = rec.get("data") if isinstance(rec.get("data"), dict) else {}
|
|
78
|
+
err = data.get("error")
|
|
79
|
+
code = _enum(err.get("code") or err.get("type")) if isinstance(err, dict) else None
|
|
80
|
+
base = {"agent": "copilot", "session": os.path.basename(os.path.dirname(path)),
|
|
81
|
+
"ts": rec.get("timestamp") or "", "model": _enum(data.get("model"))}
|
|
82
|
+
if t == "error" or t.endswith(".error"):
|
|
83
|
+
return [{**base, "kind": "error", "reason": code or _enum(t)}]
|
|
84
|
+
if t == "tool.execution_complete" and err:
|
|
85
|
+
return [{**base, "kind": "tool_error", "reason": code}]
|
|
86
|
+
return []
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _antigravity(rec: dict, path: str) -> list:
|
|
90
|
+
if rec.get("type") != "ERROR_MESSAGE":
|
|
91
|
+
return []
|
|
92
|
+
text = str(rec.get("error") or "") + " " + str(rec.get("error_code") or "")
|
|
93
|
+
words = set(re.findall(r"\b[A-Z][A-Z_]{3,}\b", text))
|
|
94
|
+
http = re.search(r"\b([45]\d\d)\b", text)
|
|
95
|
+
conv = path.split(f"{os.sep}brain{os.sep}")[-1].split(os.sep)[0]
|
|
96
|
+
base = {"agent": "antigravity", "session": conv, "ts": rec.get("created_at") or ""}
|
|
97
|
+
if words & GEMINI_BLOCKS:
|
|
98
|
+
return [{**base, "kind": "filtered", "reason": sorted(words & GEMINI_BLOCKS)[0]}]
|
|
99
|
+
if words & GEMINI_RECITATION:
|
|
100
|
+
return [{**base, "kind": "recitation", "reason": sorted(words & GEMINI_RECITATION)[0]}]
|
|
101
|
+
status = sorted(words & GOOGLE_STATUS)
|
|
102
|
+
return [{**base, "kind": "error", "reason": status[0] if status else (http.group(1) if http else None)}]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _proxy(rec: dict, path: str) -> list:
|
|
106
|
+
if rec.get("source") != "proxy" or rec.get("kind") in (None, "ok"):
|
|
107
|
+
return []
|
|
108
|
+
return [{**rec, "agent": "proxy", "client": rec.get("agent")}]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def registry(home: str | None = None) -> list[Agent]:
|
|
112
|
+
from refusectomy.claude_code import TRANSCRIPT_ROOT
|
|
113
|
+
from refusectomy.proxy import signals_path
|
|
114
|
+
h = home or os.path.expanduser("~")
|
|
115
|
+
return [
|
|
116
|
+
Agent("claude-code", os.path.join(TRANSCRIPT_ROOT, "**", "*.jsonl"),
|
|
117
|
+
"refusals, classifier category, model fallback, refused message (digest)",
|
|
118
|
+
"watch; hook claude-code; forensics (profile, report, ...)", _claude, True),
|
|
119
|
+
Agent("copilot", os.path.join(h, ".copilot", "session-state", "*", "events.jsonl"),
|
|
120
|
+
"tool failures and session errors only -- no model stop reason is logged",
|
|
121
|
+
"watch (errors only); its model traffic is not proxiable", _copilot, False),
|
|
122
|
+
Agent("antigravity", os.path.join(h, ".gemini", "antigravity-cli", "brain", "*",
|
|
123
|
+
".system_generated", "logs", "transcript_full.jsonl"),
|
|
124
|
+
"error steps; safety blocks only when logged as errors",
|
|
125
|
+
"watch (errors only); its model traffic is not proxiable", _antigravity, False),
|
|
126
|
+
Agent("proxy", signals_path(),
|
|
127
|
+
"every response's stop reason, from any agent pointed at the proxy",
|
|
128
|
+
"proxy, then watch", _proxy, True),
|
|
129
|
+
]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def main(argv: list[str] | None = None) -> int:
|
|
133
|
+
ap = argparse.ArgumentParser(prog="refusectomy agents",
|
|
134
|
+
description="Which agents are here, and what each can report.")
|
|
135
|
+
ap.add_argument("--json", action="store_true")
|
|
136
|
+
a = ap.parse_args(argv)
|
|
137
|
+
rows = []
|
|
138
|
+
for ag in registry():
|
|
139
|
+
files = ag.files()
|
|
140
|
+
rows.append({"agent": ag.name, "detected": bool(files), "logs": len(files),
|
|
141
|
+
"refusal_aware": ag.refusal_aware, "sees": ag.sees, "watch": ag.watch,
|
|
142
|
+
"pattern": ag.pattern})
|
|
143
|
+
if a.json:
|
|
144
|
+
print(json.dumps(rows, indent=2))
|
|
145
|
+
return 0
|
|
146
|
+
print(f"{'agent':<13}{'logs':>6} what its logs can say")
|
|
147
|
+
for r in rows:
|
|
148
|
+
print(f"{r['agent']:<13}{r['logs'] if r['detected'] else '-':>6} {r['sees']}")
|
|
149
|
+
print(f"{'':<21}live: {r['watch']}")
|
|
150
|
+
print("\nAny agent whose API base URL you can set is fully visible through the proxy:\n"
|
|
151
|
+
" refusectomy proxy then ANTHROPIC_BASE_URL / OPENAI_BASE_URL / a Gemini base URL\n"
|
|
152
|
+
" -> the address it prints, and `refusectomy watch` beside it.")
|
|
153
|
+
return 0
|