ctxblame 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.
ctxblame-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kekeandzeyu
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,224 @@
1
+ Metadata-Version: 2.4
2
+ Name: ctxblame
3
+ Version: 0.2.0
4
+ Summary: git blame for LLM agent decisions: find which context chunk caused a tool call
5
+ Author: kekeandzeyu
6
+ Author-email: kekeandzeyu <162712521+kekeandzeyu@users.noreply.github.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Dist: aiohttp>=3.14.5
10
+ Requires-Python: >=3.12
11
+ Description-Content-Type: text/markdown
12
+
13
+ # ctxblame
14
+
15
+ "git blame" for LLM agent decisions: replay one recorded LLM request with
16
+ pieces of context removed and report which chunk caused the decision.
17
+ Works with any model: the evidence comes from replays, not from the model's
18
+ own explanation. Status: v0.2, validated on open models (see
19
+ [docs/WRITEUP.md](docs/WRITEUP.md)); not yet on PyPI.
20
+
21
+ ```sh
22
+ uvx --from git+https://github.com/kekeandzeyu/ctxblame@v0.2.0 ctxblame --help
23
+ ```
24
+
25
+ The examples below use `uv run ctxblame` from a checkout; with the line above,
26
+ use `uvx --from git+https://github.com/kekeandzeyu/ctxblame@v0.2.0 ctxblame`.
27
+
28
+ Two wire formats are supported, which covers most models: Anthropic Messages
29
+ (`/v1/messages`) and OpenAI Chat Completions (`/chat/completions`).
30
+
31
+ ## Record
32
+
33
+ ```sh
34
+ # Anthropic format (Claude, or DeepSeek's Anthropic endpoint)
35
+ uv run ctxblame record --upstream https://api.deepseek.com/anthropic
36
+ ANTHROPIC_BASE_URL=http://127.0.0.1:8787 your-agent ...
37
+
38
+ # OpenAI format (OpenAI, DeepSeek, Qwen, OpenRouter, vLLM, Ollama, ...)
39
+ uv run ctxblame record --upstream https://api.deepseek.com
40
+ OPENAI_BASE_URL=http://127.0.0.1:8787 your-agent ...
41
+ ```
42
+
43
+ The proxy appends every `POST /v1/messages` or `POST /chat/completions`
44
+ exchange to one JSON-lines trace (`traces/<time>-<id>.jsonl`, or `--trace
45
+ FILE`), numbered in send order: the request body, and either the response
46
+ body or (for streams) every raw SSE event plus the reassembled message. Auth
47
+ headers are forwarded but never written to disk. `traces/` is git-ignored
48
+ because it holds your prompts.
49
+
50
+ ```sh
51
+ uv run ctxblame steps traces/<trace>.jsonl # one line per LLM call and its decision
52
+ ```
53
+
54
+ ## Replay
55
+
56
+ ```sh
57
+ export DEEPSEEK_API_KEY=... # or ANTHROPIC_API_KEY / OPENAI_API_KEY; see --api-key-env
58
+ uv run ctxblame replay traces/<trace>.jsonl --step 14 -n 10
59
+ ```
60
+
61
+ Re-sends the recorded request unchanged N times (no tool is executed) and
62
+ reports how often the same decision comes back, with a 95% interval. "Same
63
+ decision" defaults to `--match intent`: what the call does, whichever tool
64
+ does it (`Read src/a.py` and `Bash cat src/a.py` are both `read src/a.py`).
65
+ `--match exact|args|name` and `--key-arg` are stricter or looser.
66
+ Every call is priced and logged to `.ctxblame/spend.jsonl`; `--budget`
67
+ (default $5) is a hard cap across runs.
68
+
69
+ ## Ablation
70
+
71
+ ```sh
72
+ uv run ctxblame replay T.jsonl --step 14 --list-units # what can be removed
73
+ uv run ctxblame replay T.jsonl --step 14 -n 20 --remove pair:toolu_12
74
+ uv run ctxblame replay T.jsonl --step 14 -n 20 --remove-text "We use pnpm in this repo."
75
+ uv run ctxblame replay T.jsonl --step 14 -n 10 --remove-random 45 --seed 1 --protect "<the user's task>"
76
+ ```
77
+
78
+ Removing a tool call always removes its result too (and the reverse), empty
79
+ messages are dropped and same-role neighbours merged, so the ablated request
80
+ stays valid. `--key-arg 'command~\bpnpm\b'` makes "same decision" mean "the
81
+ command matches this regex" instead of exact arguments. `--any-call` counts a reply as the same
82
+ decision when any of its parallel tool calls matches. `thinking:msg[i]`
83
+ removes one turn's reasoning (its calls get fresh ids, so a provider that
84
+ keeps reasoning server-side cannot restore it).
85
+
86
+ ## Blame
87
+
88
+ ```sh
89
+ uv run ctxblame why traces/<trace>.jsonl --step 14
90
+
91
+ # Conditional / contrastive blame (auto-enabled with --key-arg; --given none to disable)
92
+ uv run ctxblame why traces/<trace>.jsonl --step 5 --key-arg 'command~^python -m pytest'
93
+
94
+ # Run against a local or Google Colab vLLM/Ollama server at $0 API cost
95
+ uv run ctxblame why traces/<trace>.jsonl --step 5 --key-arg 'command~^python -m pytest' \
96
+ --base-url http://127.0.0.1:8000/v1 --model Qwen/Qwen3-8B --max-tokens 2048 --no-thinking-param --free
97
+ ```
98
+
99
+ ```
100
+ Decision: Bash({"command~\\bpnpm\\b": true})
101
+ Baseline: 10/10 replays (stable)
102
+ Given: Bash (10/10 baseline; P(decision | given) = 10/10)
103
+ Chunks: 8 (3 tool desc, 1 system, 1 user, 2 assistant, 1 tool call)
104
+ Everything but the task removed: 0/10 (given 10/10) -> the decision comes from the context
105
+
106
+ Cause 1 (removing it flips the decision: 1/20 (given 20/20)):
107
+ - turn 0 user message sentence 3: 'We use pnpm in this repo, never npm or yarn.'
108
+ controls (random same-size removals): 5/5 (given 5/5), 5/5 (given 5/5)
109
+
110
+ Tests: 16, replays: 160, cost $0.07
111
+ ```
112
+
113
+ How it works:
114
+
115
+ 1. **Baseline & Conditioning (`--given`).** Replay the step unchanged. If no
116
+ decision comes back reliably it stops ("coin flip"); if the recorded call is
117
+ unusual it explains the usual one instead. When `--key-arg` or `--given` is
118
+ set, blame conditions on the coarser action family `E` (e.g. `run pytest` or
119
+ tool `Bash`) and scores `P(decision | E)` separately from `P(E)`.
120
+ 2. **Chunks & KV-Cache Tiers.** System-prompt paragraphs, earlier user and
121
+ assistant text, each tool call with its result, each turn's reasoning, and
122
+ tool descriptions are partitioned from prefix to suffix (`Tool Schemas →
123
+ System Prompt → Early History → Tail History`). The task (the latest user
124
+ message with text) is never removed.
125
+ 3. **Suffix-First Stratified Search & Precondition Isolation.** Instead of
126
+ mutating byte `0` upfront, search widens from tail history toward prefix
127
+ tiers to preserve KV prompt-cache hits. If removing a subset collapses
128
+ `P(E)` (e.g. removing an earlier `edit_file` makes the agent stop running
129
+ tests altogether), that workflow precondition is isolated, reported under
130
+ `Preconditions`, and auto-protected while choice search continues on
131
+ `P(decision | E)`.
132
+ 4. **Hitchhiker Pruning & Refinement.** Multi-member bundles are verified via a
133
+ leave-one-in restoration check (`C \ {c_i}`): holding all other carriers
134
+ removed must prove each `c_i` alone restores the decision (pruning noisy
135
+ hitchhikers and distinguishing single necessary `AND` chunks from minimal
136
+ `OR` hitting sets). Each surviving member is refined to the lines that
137
+ matter.
138
+ 5. **Check.** Each finding is confirmed with more replays, and compared with
139
+ random removals of the same size. Findings that random removals reproduce
140
+ too are reported as *context the decision needs (not specific)*, not as
141
+ causes.
142
+
143
+ Each test replays in batches of 5 until the rate is clearly above or below
144
+ half the baseline rate (a flip needs at least 10 replays). By default a reply
145
+ counts as the same decision when *any* of its parallel calls matches
146
+ (`--first-call` to compare only the first). Removing reasoning gives those
147
+ calls fresh ids; a provider that then demands the reasoning makes it
148
+ "not removable", and the report says so. `--budget` caps the spend, `--free`
149
+ (or any unknown model on `localhost`/`127.0.0.1`) runs at `$0`, and the full
150
+ log of tests plus `cache_stats` is saved as JSON in `runs/`.
151
+
152
+ ## Run at $0 on Google Colab (vLLM)
153
+
154
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/kekeandzeyu/ctxblame/blob/main/notebooks/colab_vllm.ipynb)
155
+
156
+ Open [notebooks/colab_vllm.ipynb](notebooks/colab_vllm.ipynb) on a Colab **L4**
157
+ or **A100** GPU to serve an open tool-calling model (`Qwen/Qwen3-8B` or
158
+ `Qwen3-14B`) via `vLLM --enable-prefix-caching` and run `ctxblame why` or the
159
+ Phase 3 attribution benchmark at **$0 API cost**.
160
+
161
+ ## Experiments & Benchmarks
162
+
163
+ - **Phase 0** ([experiments/phase0](experiments/phase0/README.md)): five
164
+ planted-cause scenarios, both wire formats, two DeepSeek models.
165
+ - **Phase 1** ([experiments/phase1](experiments/phase1/README.md)): planted
166
+ causes in real agent traces with thinking on. Causes are usually redundant,
167
+ the agent's own history takes over later in a run, and DeepSeek restores
168
+ removed reasoning server-side unless the call ids change.
169
+ - **Phase 2** ([experiments/phase2/results/results.md](experiments/phase2/results/results.md)):
170
+ end-to-end validation of the original `ddmin` engine, exposing precondition
171
+ confounding (`step5`/`step7`), hitchhikers, and byte-0 cache invalidation.
172
+ - **Phase 3–4** ([experiments/phase3/RESULTS.md](experiments/phase3/RESULTS.md)):
173
+ attribution benchmark on open models at $0 (Qwen3-8B, Qwen3-14B-FP8 with
174
+ thinking off and on, Llama-3.1-8B; vLLM, 3 seeds, oracle-validated cases): generated cases (8 tool conventions
175
+ × 5 carrier places, redundancy, preconditions, negatives), ~35k-char
176
+ prompts, and 15 real recorded agent runs. ctxblame against
177
+ `--given none`, ContextCite, leave-one-out and self-explanation:
178
+
179
+ | F1 | Qwen3-8B gen | Qwen3-14B gen | Qwen3-14B gen, thinking on | Llama-3.1-8B gen | Qwen3-14B real traces | Qwen3-14B long prompts |
180
+ |---|---:|---:|---:|---:|---:|---:|
181
+ | **ctxblame** | **94%** | **95%** | **95%** | **85%** | **92%** | **95%** |
182
+ | ctxblame `--given none` | 79% | 76% | 81% | 77% | 60% | – |
183
+ | ContextCite | 71% | 84% | 83% | 84% | 29% | – |
184
+ | self-explanation | 73% | 60% | 80% | 67% | 46% | – |
185
+ | leave-one-out | 34% | 39% | 34% | 36% | 0% | – |
186
+
187
+ On the noisier Llama-3.1-8B, ctxblame ties ContextCite on F1 but is still
188
+ the only method that separates preconditions and gets negatives right.
189
+ On long requests the suffix-first search needs 27% fewer replays and 34–38%
190
+ less uncached input than a flat search; on short ones it saves nothing.
191
+ ```sh
192
+ uv run python experiments/phase3/benchmark.py --dry-run # offline check ($0)
193
+ ```
194
+
195
+ ## Related Work & Limitations
196
+
197
+ ### How `ctxblame` differs from prior work
198
+ - **Logprob-based context attribution ([ContextCite](https://arxiv.org/abs/2409.00729)):** Fits a sparse linear surrogate over random context ablations using token log-probabilities. That works well for single-turn text generation on open-logprob endpoints, whereas `ctxblame` targets **discrete black-box tool decisions** (`/v1/messages` and closed thinking models expose no input/output logprobs), handles **redundant `OR`-carriers** (where single-chunk leave-one-out effects are ~0 because `AGENTS.md`, tool schemas, and earlier turns back each other up), and separates **workflow preconditions from choice carriers** (`--given`). In our benchmark ContextCite does find redundant carriers (its random ablations remove backups together), but it blames workflow preconditions as causes, never answers "nothing in the context", and drops to 29% F1 on real agent traces (ctxblame: 92%).
199
+ - **Trajectory-level auditing (Counterfactual Trace Auditing, LangSmith / Braintrust playgrounds):** Whole-run audits re-execute entire multi-step sessions with or without a skill, while UI playgrounds rely on manual prompt editing. `ctxblame` automates exact **single-step request blame** with statistical stopping rules and KV-cache-aware search.
200
+
201
+ ### Scope & practical limits
202
+ - **An MRI for stubborn bugs, not an every-turn linter:** Isolating minimal causes takes ~200 replays per blamed step on short requests and ~300–550 on long agent traces (`$0` on local/Colab `vLLM`, `~$0.05–$0.10` on DeepSeek/Flash with prefix caching, but up to several dollars and 1–2 minutes on 60k+ token frontier models). Run it on the specific turn where an agent went off the rails.
203
+ - **Upfront proxy capture (until `v0.3` log import):** `ctxblame` currently requires recording traffic through `ctxblame record` before the failure happens; retroactive import from existing local CLI transcripts is scheduled next (`v0.3`).
204
+ - **High-entropy / coin-flip turns:** If the unablated step already splits ~50/50 across decisions on replay, there is no stable decision for context ablation to explain (`ctxblame` detects this on baseline replay and stops early).
205
+
206
+ ## Next Steps
207
+
208
+ See [docs/ROADMAP.md](docs/ROADMAP.md) for the full technical audit, bottleneck analysis, and milestone details. Milestones 1–3 (`--given` conditional blame, `C \ {c_i}` hitchhiker pruning & AND/OR duality, KV-cache-stratified suffix-first search, and `$0` local/Colab vLLM support) are implemented and unit-tested.
209
+
210
+ ### `v0.2` — Empirical Validation & Initial Release (Released)
211
+ 1. ~~**Phase 3–4 benchmark on open models**~~ — done: see [experiments/phase3/RESULTS.md](experiments/phase3/RESULTS.md). Milestone 1's acceptance (all carriers, 100% precision, edits kept apart) holds on real Qwen3-14B agent traces.
212
+ 2. ~~**Robustness at $0**~~ — done: Qwen3-14B with thinking on (95%), Llama-3.1-8B (85%, tied with ContextCite on F1; see the writeup for why). Still open: `gen-open` cases (the carrier decides whether the agent acts at all) and the optional paid DeepSeek re-run of `experiments/phase2/run.py --only step5 step7` (~$1–$2).
213
+ 3. ~~**Publish `v0.2`**~~ — tagged `v0.2.0` on GitHub with the [technical writeup](docs/WRITEUP.md); PyPI upload pending.
214
+
215
+ ### `v0.3` — Zero-Setup Adoption & Prompt-Repair Workflow
216
+ 1. **Retroactive transcript importers (`ctxblame import`):** Reconstruct replayable `/v1/messages` and `/chat/completions` requests directly from local session logs already saved by **Claude Code** (`~/.claude/projects/**/*.jsonl`), **OpenCode**, and **Harbor**—eliminating the need to run a proxy *before* a surprise bug occurs.
217
+ 2. **One-command CLI wrapper (`ctxblame wrap -- claude`):** Auto-assign an ephemeral local proxy port and inject `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` in one command when full wire-level SSE capture is wanted.
218
+ 3. **3-second counterfactual fix verification (`--replace-text` / `ctxblame verify`):** Once `ctxblame why` blames a specific line in `CLAUDE.md`, `AGENTS.md`, or a tool schema, replay that frozen step (`-n 10`) with the user's edited wording to verify the fix flips the tool call before launching a new full session.
219
+
220
+ ## Tests
221
+
222
+ ```sh
223
+ uv run pytest
224
+ ```
@@ -0,0 +1,212 @@
1
+ # ctxblame
2
+
3
+ "git blame" for LLM agent decisions: replay one recorded LLM request with
4
+ pieces of context removed and report which chunk caused the decision.
5
+ Works with any model: the evidence comes from replays, not from the model's
6
+ own explanation. Status: v0.2, validated on open models (see
7
+ [docs/WRITEUP.md](docs/WRITEUP.md)); not yet on PyPI.
8
+
9
+ ```sh
10
+ uvx --from git+https://github.com/kekeandzeyu/ctxblame@v0.2.0 ctxblame --help
11
+ ```
12
+
13
+ The examples below use `uv run ctxblame` from a checkout; with the line above,
14
+ use `uvx --from git+https://github.com/kekeandzeyu/ctxblame@v0.2.0 ctxblame`.
15
+
16
+ Two wire formats are supported, which covers most models: Anthropic Messages
17
+ (`/v1/messages`) and OpenAI Chat Completions (`/chat/completions`).
18
+
19
+ ## Record
20
+
21
+ ```sh
22
+ # Anthropic format (Claude, or DeepSeek's Anthropic endpoint)
23
+ uv run ctxblame record --upstream https://api.deepseek.com/anthropic
24
+ ANTHROPIC_BASE_URL=http://127.0.0.1:8787 your-agent ...
25
+
26
+ # OpenAI format (OpenAI, DeepSeek, Qwen, OpenRouter, vLLM, Ollama, ...)
27
+ uv run ctxblame record --upstream https://api.deepseek.com
28
+ OPENAI_BASE_URL=http://127.0.0.1:8787 your-agent ...
29
+ ```
30
+
31
+ The proxy appends every `POST /v1/messages` or `POST /chat/completions`
32
+ exchange to one JSON-lines trace (`traces/<time>-<id>.jsonl`, or `--trace
33
+ FILE`), numbered in send order: the request body, and either the response
34
+ body or (for streams) every raw SSE event plus the reassembled message. Auth
35
+ headers are forwarded but never written to disk. `traces/` is git-ignored
36
+ because it holds your prompts.
37
+
38
+ ```sh
39
+ uv run ctxblame steps traces/<trace>.jsonl # one line per LLM call and its decision
40
+ ```
41
+
42
+ ## Replay
43
+
44
+ ```sh
45
+ export DEEPSEEK_API_KEY=... # or ANTHROPIC_API_KEY / OPENAI_API_KEY; see --api-key-env
46
+ uv run ctxblame replay traces/<trace>.jsonl --step 14 -n 10
47
+ ```
48
+
49
+ Re-sends the recorded request unchanged N times (no tool is executed) and
50
+ reports how often the same decision comes back, with a 95% interval. "Same
51
+ decision" defaults to `--match intent`: what the call does, whichever tool
52
+ does it (`Read src/a.py` and `Bash cat src/a.py` are both `read src/a.py`).
53
+ `--match exact|args|name` and `--key-arg` are stricter or looser.
54
+ Every call is priced and logged to `.ctxblame/spend.jsonl`; `--budget`
55
+ (default $5) is a hard cap across runs.
56
+
57
+ ## Ablation
58
+
59
+ ```sh
60
+ uv run ctxblame replay T.jsonl --step 14 --list-units # what can be removed
61
+ uv run ctxblame replay T.jsonl --step 14 -n 20 --remove pair:toolu_12
62
+ uv run ctxblame replay T.jsonl --step 14 -n 20 --remove-text "We use pnpm in this repo."
63
+ uv run ctxblame replay T.jsonl --step 14 -n 10 --remove-random 45 --seed 1 --protect "<the user's task>"
64
+ ```
65
+
66
+ Removing a tool call always removes its result too (and the reverse), empty
67
+ messages are dropped and same-role neighbours merged, so the ablated request
68
+ stays valid. `--key-arg 'command~\bpnpm\b'` makes "same decision" mean "the
69
+ command matches this regex" instead of exact arguments. `--any-call` counts a reply as the same
70
+ decision when any of its parallel tool calls matches. `thinking:msg[i]`
71
+ removes one turn's reasoning (its calls get fresh ids, so a provider that
72
+ keeps reasoning server-side cannot restore it).
73
+
74
+ ## Blame
75
+
76
+ ```sh
77
+ uv run ctxblame why traces/<trace>.jsonl --step 14
78
+
79
+ # Conditional / contrastive blame (auto-enabled with --key-arg; --given none to disable)
80
+ uv run ctxblame why traces/<trace>.jsonl --step 5 --key-arg 'command~^python -m pytest'
81
+
82
+ # Run against a local or Google Colab vLLM/Ollama server at $0 API cost
83
+ uv run ctxblame why traces/<trace>.jsonl --step 5 --key-arg 'command~^python -m pytest' \
84
+ --base-url http://127.0.0.1:8000/v1 --model Qwen/Qwen3-8B --max-tokens 2048 --no-thinking-param --free
85
+ ```
86
+
87
+ ```
88
+ Decision: Bash({"command~\\bpnpm\\b": true})
89
+ Baseline: 10/10 replays (stable)
90
+ Given: Bash (10/10 baseline; P(decision | given) = 10/10)
91
+ Chunks: 8 (3 tool desc, 1 system, 1 user, 2 assistant, 1 tool call)
92
+ Everything but the task removed: 0/10 (given 10/10) -> the decision comes from the context
93
+
94
+ Cause 1 (removing it flips the decision: 1/20 (given 20/20)):
95
+ - turn 0 user message sentence 3: 'We use pnpm in this repo, never npm or yarn.'
96
+ controls (random same-size removals): 5/5 (given 5/5), 5/5 (given 5/5)
97
+
98
+ Tests: 16, replays: 160, cost $0.07
99
+ ```
100
+
101
+ How it works:
102
+
103
+ 1. **Baseline & Conditioning (`--given`).** Replay the step unchanged. If no
104
+ decision comes back reliably it stops ("coin flip"); if the recorded call is
105
+ unusual it explains the usual one instead. When `--key-arg` or `--given` is
106
+ set, blame conditions on the coarser action family `E` (e.g. `run pytest` or
107
+ tool `Bash`) and scores `P(decision | E)` separately from `P(E)`.
108
+ 2. **Chunks & KV-Cache Tiers.** System-prompt paragraphs, earlier user and
109
+ assistant text, each tool call with its result, each turn's reasoning, and
110
+ tool descriptions are partitioned from prefix to suffix (`Tool Schemas →
111
+ System Prompt → Early History → Tail History`). The task (the latest user
112
+ message with text) is never removed.
113
+ 3. **Suffix-First Stratified Search & Precondition Isolation.** Instead of
114
+ mutating byte `0` upfront, search widens from tail history toward prefix
115
+ tiers to preserve KV prompt-cache hits. If removing a subset collapses
116
+ `P(E)` (e.g. removing an earlier `edit_file` makes the agent stop running
117
+ tests altogether), that workflow precondition is isolated, reported under
118
+ `Preconditions`, and auto-protected while choice search continues on
119
+ `P(decision | E)`.
120
+ 4. **Hitchhiker Pruning & Refinement.** Multi-member bundles are verified via a
121
+ leave-one-in restoration check (`C \ {c_i}`): holding all other carriers
122
+ removed must prove each `c_i` alone restores the decision (pruning noisy
123
+ hitchhikers and distinguishing single necessary `AND` chunks from minimal
124
+ `OR` hitting sets). Each surviving member is refined to the lines that
125
+ matter.
126
+ 5. **Check.** Each finding is confirmed with more replays, and compared with
127
+ random removals of the same size. Findings that random removals reproduce
128
+ too are reported as *context the decision needs (not specific)*, not as
129
+ causes.
130
+
131
+ Each test replays in batches of 5 until the rate is clearly above or below
132
+ half the baseline rate (a flip needs at least 10 replays). By default a reply
133
+ counts as the same decision when *any* of its parallel calls matches
134
+ (`--first-call` to compare only the first). Removing reasoning gives those
135
+ calls fresh ids; a provider that then demands the reasoning makes it
136
+ "not removable", and the report says so. `--budget` caps the spend, `--free`
137
+ (or any unknown model on `localhost`/`127.0.0.1`) runs at `$0`, and the full
138
+ log of tests plus `cache_stats` is saved as JSON in `runs/`.
139
+
140
+ ## Run at $0 on Google Colab (vLLM)
141
+
142
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/kekeandzeyu/ctxblame/blob/main/notebooks/colab_vllm.ipynb)
143
+
144
+ Open [notebooks/colab_vllm.ipynb](notebooks/colab_vllm.ipynb) on a Colab **L4**
145
+ or **A100** GPU to serve an open tool-calling model (`Qwen/Qwen3-8B` or
146
+ `Qwen3-14B`) via `vLLM --enable-prefix-caching` and run `ctxblame why` or the
147
+ Phase 3 attribution benchmark at **$0 API cost**.
148
+
149
+ ## Experiments & Benchmarks
150
+
151
+ - **Phase 0** ([experiments/phase0](experiments/phase0/README.md)): five
152
+ planted-cause scenarios, both wire formats, two DeepSeek models.
153
+ - **Phase 1** ([experiments/phase1](experiments/phase1/README.md)): planted
154
+ causes in real agent traces with thinking on. Causes are usually redundant,
155
+ the agent's own history takes over later in a run, and DeepSeek restores
156
+ removed reasoning server-side unless the call ids change.
157
+ - **Phase 2** ([experiments/phase2/results/results.md](experiments/phase2/results/results.md)):
158
+ end-to-end validation of the original `ddmin` engine, exposing precondition
159
+ confounding (`step5`/`step7`), hitchhikers, and byte-0 cache invalidation.
160
+ - **Phase 3–4** ([experiments/phase3/RESULTS.md](experiments/phase3/RESULTS.md)):
161
+ attribution benchmark on open models at $0 (Qwen3-8B, Qwen3-14B-FP8 with
162
+ thinking off and on, Llama-3.1-8B; vLLM, 3 seeds, oracle-validated cases): generated cases (8 tool conventions
163
+ × 5 carrier places, redundancy, preconditions, negatives), ~35k-char
164
+ prompts, and 15 real recorded agent runs. ctxblame against
165
+ `--given none`, ContextCite, leave-one-out and self-explanation:
166
+
167
+ | F1 | Qwen3-8B gen | Qwen3-14B gen | Qwen3-14B gen, thinking on | Llama-3.1-8B gen | Qwen3-14B real traces | Qwen3-14B long prompts |
168
+ |---|---:|---:|---:|---:|---:|---:|
169
+ | **ctxblame** | **94%** | **95%** | **95%** | **85%** | **92%** | **95%** |
170
+ | ctxblame `--given none` | 79% | 76% | 81% | 77% | 60% | – |
171
+ | ContextCite | 71% | 84% | 83% | 84% | 29% | – |
172
+ | self-explanation | 73% | 60% | 80% | 67% | 46% | – |
173
+ | leave-one-out | 34% | 39% | 34% | 36% | 0% | – |
174
+
175
+ On the noisier Llama-3.1-8B, ctxblame ties ContextCite on F1 but is still
176
+ the only method that separates preconditions and gets negatives right.
177
+ On long requests the suffix-first search needs 27% fewer replays and 34–38%
178
+ less uncached input than a flat search; on short ones it saves nothing.
179
+ ```sh
180
+ uv run python experiments/phase3/benchmark.py --dry-run # offline check ($0)
181
+ ```
182
+
183
+ ## Related Work & Limitations
184
+
185
+ ### How `ctxblame` differs from prior work
186
+ - **Logprob-based context attribution ([ContextCite](https://arxiv.org/abs/2409.00729)):** Fits a sparse linear surrogate over random context ablations using token log-probabilities. That works well for single-turn text generation on open-logprob endpoints, whereas `ctxblame` targets **discrete black-box tool decisions** (`/v1/messages` and closed thinking models expose no input/output logprobs), handles **redundant `OR`-carriers** (where single-chunk leave-one-out effects are ~0 because `AGENTS.md`, tool schemas, and earlier turns back each other up), and separates **workflow preconditions from choice carriers** (`--given`). In our benchmark ContextCite does find redundant carriers (its random ablations remove backups together), but it blames workflow preconditions as causes, never answers "nothing in the context", and drops to 29% F1 on real agent traces (ctxblame: 92%).
187
+ - **Trajectory-level auditing (Counterfactual Trace Auditing, LangSmith / Braintrust playgrounds):** Whole-run audits re-execute entire multi-step sessions with or without a skill, while UI playgrounds rely on manual prompt editing. `ctxblame` automates exact **single-step request blame** with statistical stopping rules and KV-cache-aware search.
188
+
189
+ ### Scope & practical limits
190
+ - **An MRI for stubborn bugs, not an every-turn linter:** Isolating minimal causes takes ~200 replays per blamed step on short requests and ~300–550 on long agent traces (`$0` on local/Colab `vLLM`, `~$0.05–$0.10` on DeepSeek/Flash with prefix caching, but up to several dollars and 1–2 minutes on 60k+ token frontier models). Run it on the specific turn where an agent went off the rails.
191
+ - **Upfront proxy capture (until `v0.3` log import):** `ctxblame` currently requires recording traffic through `ctxblame record` before the failure happens; retroactive import from existing local CLI transcripts is scheduled next (`v0.3`).
192
+ - **High-entropy / coin-flip turns:** If the unablated step already splits ~50/50 across decisions on replay, there is no stable decision for context ablation to explain (`ctxblame` detects this on baseline replay and stops early).
193
+
194
+ ## Next Steps
195
+
196
+ See [docs/ROADMAP.md](docs/ROADMAP.md) for the full technical audit, bottleneck analysis, and milestone details. Milestones 1–3 (`--given` conditional blame, `C \ {c_i}` hitchhiker pruning & AND/OR duality, KV-cache-stratified suffix-first search, and `$0` local/Colab vLLM support) are implemented and unit-tested.
197
+
198
+ ### `v0.2` — Empirical Validation & Initial Release (Released)
199
+ 1. ~~**Phase 3–4 benchmark on open models**~~ — done: see [experiments/phase3/RESULTS.md](experiments/phase3/RESULTS.md). Milestone 1's acceptance (all carriers, 100% precision, edits kept apart) holds on real Qwen3-14B agent traces.
200
+ 2. ~~**Robustness at $0**~~ — done: Qwen3-14B with thinking on (95%), Llama-3.1-8B (85%, tied with ContextCite on F1; see the writeup for why). Still open: `gen-open` cases (the carrier decides whether the agent acts at all) and the optional paid DeepSeek re-run of `experiments/phase2/run.py --only step5 step7` (~$1–$2).
201
+ 3. ~~**Publish `v0.2`**~~ — tagged `v0.2.0` on GitHub with the [technical writeup](docs/WRITEUP.md); PyPI upload pending.
202
+
203
+ ### `v0.3` — Zero-Setup Adoption & Prompt-Repair Workflow
204
+ 1. **Retroactive transcript importers (`ctxblame import`):** Reconstruct replayable `/v1/messages` and `/chat/completions` requests directly from local session logs already saved by **Claude Code** (`~/.claude/projects/**/*.jsonl`), **OpenCode**, and **Harbor**—eliminating the need to run a proxy *before* a surprise bug occurs.
205
+ 2. **One-command CLI wrapper (`ctxblame wrap -- claude`):** Auto-assign an ephemeral local proxy port and inject `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` in one command when full wire-level SSE capture is wanted.
206
+ 3. **3-second counterfactual fix verification (`--replace-text` / `ctxblame verify`):** Once `ctxblame why` blames a specific line in `CLAUDE.md`, `AGENTS.md`, or a tool schema, replay that frozen step (`-n 10`) with the user's edited wording to verify the fix flips the tool call before launching a new full session.
207
+
208
+ ## Tests
209
+
210
+ ```sh
211
+ uv run pytest
212
+ ```
@@ -0,0 +1,26 @@
1
+ [project]
2
+ name = "ctxblame"
3
+ version = "0.2.0"
4
+ description = "git blame for LLM agent decisions: find which context chunk caused a tool call"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.12"
9
+ dependencies = ["aiohttp>=3.14.5"]
10
+
11
+ [[project.authors]]
12
+ name = "kekeandzeyu"
13
+ email = "162712521+kekeandzeyu@users.noreply.github.com"
14
+
15
+ [project.scripts]
16
+ ctxblame = "ctxblame.cli:main"
17
+
18
+ [build-system]
19
+ requires = ["uv_build>=0.13.7,<0.14.0"]
20
+ build-backend = "uv_build"
21
+
22
+ [dependency-groups]
23
+ dev = ["pytest>=9.2.0"]
24
+
25
+ [tool.pytest.ini_options]
26
+ testpaths = ["tests"]
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "ctxblame"
3
+ version = "0.2.0"
4
+ description = "git blame for LLM agent decisions: find which context chunk caused a tool call"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [
9
+ { name = "kekeandzeyu", email = "162712521+kekeandzeyu@users.noreply.github.com" }
10
+ ]
11
+ requires-python = ">=3.12"
12
+ dependencies = [
13
+ "aiohttp>=3.14.5",
14
+ ]
15
+
16
+ [project.scripts]
17
+ ctxblame = "ctxblame.cli:main"
18
+
19
+ [build-system]
20
+ requires = ["uv_build>=0.13.7,<0.14.0"]
21
+ build-backend = "uv_build"
22
+
23
+ [dependency-groups]
24
+ dev = [
25
+ "pytest>=9.2.0",
26
+ ]
27
+
28
+ [tool.pytest.ini_options]
29
+ testpaths = ["tests"]
@@ -0,0 +1 @@
1
+ """ctxblame: git blame for LLM agent decisions (Phase 0 spike)."""