Metadata-Version: 2.4
Name: refusectomy
Version: 0.2.0
Summary: Find, explain and live-monitor model refusals in CLI coding agents (Claude Code, and any agent through a local proxy).
Author: Sebastian S. Cocioba, Binomica Labs
License-Expression: MIT
Project-URL: Homepage, https://github.com/Binomica-Labs/refusectomy
Project-URL: Repository, https://github.com/Binomica-Labs/refusectomy
Project-URL: Issues, https://github.com/Binomica-Labs/refusectomy/issues
Project-URL: Changelog, https://github.com/Binomica-Labs/refusectomy/blob/main/CHANGELOG.md
Keywords: claude,claude-code,llm,refusal,safety-classifier,agents,monitoring
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Debuggers
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# Refusectomy

[![PyPI](https://img.shields.io/pypi/v/refusectomy.svg)](https://pypi.org/project/refusectomy/)
[![Standard library only](https://img.shields.io/badge/dependencies-none-3776AB?logo=python&logoColor=white)](https://www.python.org/)
[![Tests](https://github.com/Binomica-Labs/refusectomy/actions/workflows/test.yml/badge.svg)](https://github.com/Binomica-Labs/refusectomy/actions/workflows/test.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Status: alpha](https://img.shields.io/badge/status-alpha-orange.svg)](https://github.com/Binomica-Labs/refusectomy)

**Find, explain and live-monitor model refusals in CLI coding agents.**

By Sebastian S. Cocioba, Binomica Labs.

When a safety classifier declines legitimate work, an agent session rarely fails just once. It
keeps failing, and the obvious fixes (rephrasing, switching models, trimming context) mostly
don't help. Refusectomy measures what actually happened on your machine, watches for it as it
happens, and tells you what the evidence supports. It identifies refused text by digest, never by
printing it.

## What it can see, per agent

| agent | how Refusectomy reads it | what you get |
|---|---|---|
| **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 |
| **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 |
| **GitHub Copilot CLI** | its session log | tool failures and session errors only: it does not log the model's stop reason |
| **Antigravity CLI** | its session log | error steps; a safety block only when the agent logs it as an error |

`refusectomy agents` prints this table for your own machine.

## Install

Python 3.10 or newer, no dependencies.

```bash
pipx install refusectomy          # or: uv tool install refusectomy
pipx install .                    # from a checkout
```

## Claude Code

```bash
refusectomy audit                 # check the parser's assumptions against your transcripts
refusectomy profile               # rates, stickiness, the model comparison, confounds
refusectomy remedy --category bio # the playbook, rendered from your own profile
refusectomy watch                 # live, in a second terminal
refusectomy report --project DIR  # a support-ticket bundle: request ids and digests
```

To get a warning inside Claude Code the moment a session declines, add the hook to
`~/.claude/settings.json`:

```json
{ "hooks": {
    "Stop":         [{ "hooks": [{ "type": "command", "timeout": 10,
                       "command": "refusectomy hook claude-code 2>/dev/null || true" }] }],
    "SessionStart": [{ "hooks": [{ "type": "command", "timeout": 10,
                       "command": "refusectomy hook claude-code 2>/dev/null || true" }] }] } }
```

The warning is shown to you as a `systemMessage`. It is never added to the model's context:
feeding "you were just declined" back into the context that declined is how one decline turns
into a run of them.

## Excise: a clean copy of a declined session

```bash
refusectomy excise --dry-run      # what would be removed from the current session
refusectomy excise                # write the clean copy and print its /resume command
```

To excise between turns, add `--excise` to the hook command (or put `{"excise": true}` in
`config.json` in the state directory, or set `REFUSECTOMY_EXCISE=1`). When a session declines,
the warning then names a clean copy to `/resume`. `refusectomy watch --excise` does the same from
the monitor, waiting until the session's log has gone quiet.

**What it removes: the decline's own debris, nothing else.**

- Every record of the declined response: the partial output that the refusal docs say to discard.
- The harness's placeholder notice and its refusal record.
- The hidden "meta" notice message that Claude Code otherwise sends back to the model.
- The results of any tool calls made inside the declined response. A call that had already run
  keeps its effects on disk, and the report says how many did.

**What it keeps: everything else, byte for byte.** That covers your messages, including any that
quote the notice, every response that wasn't declined, and all the work material. Excision never
rewords anything, and never removes content because a classifier reacts to it, so the classifier
still sees everything you actually asked.

**How the copy behaves.** The source session is never modified. Resuming the copy starts on your
default model, which also releases the refusal-fallback lock.

This was verified end to end: Claude Code resumes a cleaned copy. Asked whether any earlier message
mentioned a safety classifier, the model in the cleaned copy says no, and the same session
uncleaned says yes.

**Whether it prevents the next decline is not yet known.** The run of declines could come from the
debris, or from the material that is still in context. `profile` reports what happened after each
clean copy was resumed. Until there is data, abandoning the session remains the measured lever.

## Any other agent, through the proxy

```bash
refusectomy proxy                 # loopback only; prints the URL for each provider
# then point the agent at it, e.g.
ANTHROPIC_BASE_URL=http://127.0.0.1:8787/anthropic   your-agent
OPENAI_BASE_URL=http://127.0.0.1:8787/openai/v1      your-agent
refusectomy watch                 # in another terminal: every agent, one timeline
```

The proxy forwards each request unchanged to the real API over verified TLS. It relays the
response back as it streams, reading the stop reason as it goes by. It recognises:

- Anthropic: `stop_reason: "refusal"`, with its category.
- OpenAI: a `content_filter` finish, a `refusal` field, or a Responses refusal or content-filter
  cut-off.
- Gemini: a safety finish reason or a blocked prompt.

Agents that only talk to their vendor's own backend, such as Copilot CLI and Antigravity, can't
be proxied without intercepting TLS, which Refusectomy doesn't do.

## What the evidence says

These come from the corpus this tool was built on. `profile` re-measures each of them on yours.

1. **Declines cluster within a session.** Once one lands, the next request in that session is
   far more likely to decline than a request in a fresh session. Abandon the session; don't
   rephrase inside it.
2. **The refused message is rarely the problem.** Most refused messages are a single word, like
   "continue". The decline is about the work accumulated in the context, not the phrasing.
3. **Claude Code moves a declined session to another model.** When Opus 5.5 or Fable declines,
   Claude Code retries on Opus 5 and keeps the session there until `/clear` or `/model`. The
   retry usually rescues the turn, but the session stays hot.
4. **Compare models only before a session's first decline.** After it, the fallback and the
   cascade decide which model you're on, so turn-level comparisons measure the fallback, not the
   model. Measured the clean way, this corpus showed no evidence that switching models helps.
5. **Context size and memory files weren't levers.** The apparent effect of context size was
   survivorship. No memory file was read more often before early declines than in clean
   sessions.
6. **The real fix is institutional.** For legitimate work, that means Anthropic's verification
   programs for life sciences and for cyber, plus false-positive reports filed with request ids.
   `report` builds that bundle.

`refusectomy profile` prints the numbers behind each one for your own machine, beside the controls
that keep them honest.

## Privacy and safety

- **Refused text is never printed.** It's identified by a sha256 digest and a character shape.
  `--verbatim` writes it to a mode-0600 file for you to read; it never goes to stdout.
- **Everything stays local.** There is no telemetry and no network access, except the proxy
  forwarding your agent's own requests to the API it was already calling.
- **The proxy records metadata only.** It listens on loopback only, and never records headers,
  bodies, query strings (where Gemini can carry an API key) or text.
- **It only observes.** It never rewrites, retries, or searches for phrasings that get past a
  classifier. `bisect` reports what reproduces a decline, nothing more.
- **Where files go.** Reports and state live in `$REFUSECTOMY_HOME`, or by default in
  `~/.local/state/refusectomy` (Linux), `~/Library/Application Support/refusectomy` (macOS) or
  `%LOCALAPPDATA%\refusectomy` (Windows).

## How it keeps itself honest

- `audit` checks the invariants its numbers depend on, against your own transcripts, and exits
  non-zero if any fail.
- Every figure that `remedy` and the hook quote comes from your last `profile`; none is typed
  into the source.
- Each bug fix has a regression test on synthetic transcripts. Each of those tests was checked by
  putting the bug back and watching it fail.

## Development

```bash
python3 -m unittest discover -s tests -t .
PYTHONPATH=src python3 -m refusectomy audit
```

The code is in `src/refusectomy/`:

- `claude_code.py`: the transcript engine and forensics
- `providers.py`: each provider's refusal signals
- `proxy.py`, `agents.py`, `watch.py`: the live monitoring
- `cli.py`: the command

`analysis/` holds exploratory scripts that build on the package.

## License

MIT, copyright 2026 Sebastian S. Cocioba, Binomica Labs. See [LICENSE](LICENSE).
