{"slug": "ctxblame-git-blame-for-llm-agent-decisions-via-counterfactual-replay", "title": "Ctxblame – \"Git blame\" for LLM agent decisions via counterfactual replay", "summary": "Ctxblame v0.2.2, a tool that attributes LLM agent decisions to specific context chunks by replaying a recorded request with pieces of context removed, has been validated on open models, the project reports. Version 0.2.1 added correct chunking of Claude Code–style traces and audits reported causes on fresh replays with family-wise error at or below α, while v0.2.2 distinguishes a rule that makes the agent act from one that also determines what it does by replaying with the tool forced. On a real v0.2.1 trace (real/run1/step21, Qwen3-14B on local vLLM), ctxblame separated the edit_file precondition, caught all 3 redundant --tb=line carriers that leave-one-out misses (5/5 kept alone), and certified the bundle on 20 fresh replays (p = 1.9e-6, 91% KV-cache hit).", "body_md": "\"git blame\" for LLM agent decisions: replay one recorded LLM request with\npieces of context removed and report which chunk caused the decision.\nWorks with any model: the evidence comes from replays, not from the model's\nown explanation. Status: v0.2.2, validated on open models (see\n[docs/WRITEUP.md](https://github.com/kekeandzeyu/ctxblame/blob/main/docs/WRITEUP.md)). v0.2.1 added correct chunking of Claude\nCode–style traces and audits reported causes on fresh replays (family-wise\nerror ≤ α). v0.2.2 tells a rule that makes the agent act *and* picks what it\ndoes from one that only makes it act, by replaying with the tool forced.\n\n```\nuvx ctxblame --help        # or: pip install ctxblame\n```\n\n*Real v0.2.1 trace (`real/run1/step21`, Qwen3-14B on local vLLM): `ctxblame` separates the `edit_file` precondition, catches all 3 redundant `--tb=line` carriers that leave-one-out misses (`5/5 kept` alone), and certifies the bundle on 20 fresh replays (`p = 1.9e-6`, 91% KV-cache hit).*\n\nThe examples below use `uv run ctxblame` from a checkout; `uvx ctxblame` works the same.\n\nTwo wire formats are supported, which covers most models: Anthropic Messages\n(`/v1/messages`) and OpenAI Chat Completions (`/chat/completions`).\n\n```\n# Anthropic format (Claude, or DeepSeek's Anthropic endpoint)\nuv run ctxblame record --upstream https://api.deepseek.com/anthropic\nANTHROPIC_BASE_URL=http://127.0.0.1:8787 your-agent ...\n\n# OpenAI format (OpenAI, DeepSeek, Qwen, OpenRouter, vLLM, Ollama, ...)\nuv run ctxblame record --upstream https://api.deepseek.com\nOPENAI_BASE_URL=http://127.0.0.1:8787 your-agent ...\n```\n\nThe proxy appends every `POST /v1/messages` or `POST /chat/completions`\nexchange to one JSON-lines trace (`traces/<time>-<id>.jsonl`, or `--trace FILE`), numbered in send order: the request body, and either the response\nbody or (for streams) every raw SSE event plus the reassembled message. Auth\nheaders are forwarded but never written to disk. `traces/` is git-ignored\nbecause it holds your prompts.\n\n```\nuv run ctxblame steps traces/<trace>.jsonl          # one line per LLM call and its decision\nexport DEEPSEEK_API_KEY=...        # or ANTHROPIC_API_KEY / OPENAI_API_KEY; see --api-key-env\nuv run ctxblame replay traces/<trace>.jsonl --step 14 -n 10\n```\n\nRe-sends the recorded request unchanged N times (no tool is executed) and\nreports how often the same decision comes back, with a 95% interval. \"Same\ndecision\" defaults to `--match intent`: what the call does, whichever tool\ndoes it (`Read src/a.py` and `Bash cat src/a.py` are both `read src/a.py`).\n`--match exact|args|name` and `--key-arg` are stricter or looser.\nEvery call is priced and logged to `.ctxblame/spend.jsonl`; `--budget`\n(default $5) is a hard cap across runs.\n\n```\nuv run ctxblame replay T.jsonl --step 14 --list-units          # what can be removed\nuv run ctxblame replay T.jsonl --step 14 -n 20 --remove pair:toolu_12\nuv run ctxblame replay T.jsonl --step 14 -n 20 --remove-text \"We use pnpm in this repo.\"\nuv run ctxblame replay T.jsonl --step 14 -n 10 --remove-random 45 --seed 1 --protect \"<the user's task>\"\n```\n\nRemoving a tool call always removes its result too (and the reverse), empty\nmessages are dropped and same-role neighbours merged, so the ablated request\nstays valid. `--key-arg 'command~\\bpnpm\\b'` makes \"same decision\" mean \"the\ncommand matches this regex\" instead of exact arguments. `--any-call` counts a reply as the same\ndecision when any of its parallel tool calls matches. `thinking:msg[i]`\nremoves one turn's reasoning (its calls get fresh ids, so a provider that\nkeeps reasoning server-side cannot restore it).\n\n```\nuv run ctxblame why traces/<trace>.jsonl --step 14\n\n# Conditional / contrastive blame (auto-enabled with --key-arg; --given none to disable)\nuv run ctxblame why traces/<trace>.jsonl --step 5 --key-arg 'command~^python -m pytest'\n\n# Run against a local or Google Colab vLLM/Ollama server at $0 API cost\nuv run ctxblame why traces/<trace>.jsonl --step 5 --key-arg 'command~^python -m pytest' \\\n    --base-url http://127.0.0.1:8000/v1 --model Qwen/Qwen3-8B --max-tokens 2048 --no-thinking-param --free\nDecision:  Bash({\"command~\\\\bpnpm\\\\b\": true})\nBaseline:  10/10 replays (stable)\nGiven:     Bash (10/10 baseline; P(decision | given) = 10/10)\nChunks:    8 (3 tool desc, 1 system, 1 user, 2 assistant, 1 tool call)\nEverything but the task removed: 0/10 (given 10/10)  -> the decision comes from the context\n\nCause 1 (removing it flips the decision: 1/20 (given 20/20)):\n  - turn 0 user message sentence 3: 'We use pnpm in this repo, never npm or yarn.'\n  controls (random same-size removals): 5/5 (given 5/5), 5/5 (given 5/5)\n\nTests: 16, replays: 160, cost $0.07\n```\n\nHow it works:\n\n1. **Baseline & Conditioning (`--given`).** Replay the step unchanged. If no\ndecision comes back reliably it stops (\"coin flip\"); if the recorded call is\nunusual it explains the usual one instead. When`--key-arg` or`--given` is\nset, blame conditions on the coarser action family`E` (e.g.`run pytest` or\ntool`Bash` ) and scores`P(decision | E)` separately from`P(E)` .\n2. **Chunks & KV-Cache Tiers.** System-prompt paragraphs, earlier user and\nassistant text, each tool call with its result, each turn's reasoning, and\ntool descriptions are partitioned from prefix to suffix (`Tool Schemas → System Prompt → Early History → Tail History` ). The task (the latest user\nmessage with text) is never removed.\n3. **Suffix-First Stratified Search & Precondition Isolation.** Instead of\nmutating byte`0` upfront, search widens from tail history toward prefix\ntiers to preserve KV prompt-cache hits. If removing a subset collapses`P(E)` (e.g. removing an earlier`edit_file` makes the agent stop running\ntests altogether), that workflow precondition is isolated, reported under`Preconditions` , and auto-protected while choice search continues on`P(decision | E)` .\n4. **Hitchhiker Pruning & Refinement.** Multi-member bundles are verified via a\nleave-one-in restoration check (`C \\ {c_i}` ): holding all other carriers\nremoved must prove each`c_i` alone restores the decision (pruning noisy\nhitchhikers and distinguishing single necessary`AND` chunks from minimal`OR` hitting sets). Each surviving member is refined to the lines that\nmatter.\n5. **Check.** Each finding is compared with random removals of the same size.\nFindings that random removals reproduce too are reported as*context the\ndecision needs (not specific)* , not as causes.\n6. **Audit.** The search decides*what* to report; fresh replays it never saw\ndecide*whether* to report it. For each finding:`--audit-n` (default 20) new\nreplays of the removal, plus 20 of each leave-one-in restore, are tested with\nexact one-sided binomial tests (intersection-union inside a bundle). Holm's\ncorrection across findings then holds the family-wise error at`--alpha` (default 0.05). Findings that fail are listed as`uncertified` .`--audit-n 0` turns the audit off (the v0.2 behaviour).\n7. **Forced action (v0.2.2).** When E is a tool (`--given bash` ), a\nprecondition is also replayed with that tool forced by`tool_choice` . The\nchoice rate there is compared with the equally forced baseline, never with\nthe unforced one. If removing the precondition still changes the choice, it\nis reported as*triggers and steers* : it makes the agent act and also picks\nwhat it does. It is then listed as a cause \"with E forced\" and audited like\nany finding.`coupled` bundle members get the same forced test of whether\nthey restore the choice. The report also says what the forced replies did\ninstead (`instead: run git status 12` ), so a line that decides*what to do\nnext* can be told from one that decides*how* (`instead: run flake8` ). With\nan intent-level E, or Anthropic extended thinking, E cannot be forced and the\nreport says so.`--no-force` gives the v0.2.1 behaviour. On the Phase 6 suite\nthis raises F1 on such cases by 9–10 points (Qwen3-14B, Llama-3.1-8B).\n\nIf whether the agent acts at all depends on context spread over many chunks\n(every precondition found reveals another), the search keeps a minimal set\nthat keeps it acting (*diffuse context*), then keeps searching for what\ndecides the choice. Context a harness injects into user turns\n(`<system-reminder>`, `<environment_details>`, `<context>`) is removable like\nany other chunk; only the user's own text is protected. Anthropic\n`cache_control` breakpoints are moved to the unchanged prefix of each ablated\nrequest.\n\nEach test replays in batches of 5 until the rate is clearly above or below\nhalf the baseline rate (a flip needs at least 10 replays). By default a reply\ncounts as the same decision when *any* of its parallel calls matches\n(`--first-call` to compare only the first). Removing reasoning gives those\ncalls fresh ids; a provider that then demands the reasoning makes it\n\"not removable\", and the report says so. `--budget` caps the spend, `--free`\n(or any unknown model on `localhost`/` 127.0.0.1`) runs at `$0`, and the full\nlog of tests plus `cache_stats` is saved as JSON in `runs/`.\n\nOpen [notebooks/colab_vllm.ipynb](https://github.com/kekeandzeyu/ctxblame/blob/main/notebooks/colab_vllm.ipynb) on a Colab **L4**\nor **A100** GPU to serve an open tool-calling model (`Qwen/Qwen3-8B` or\n`Qwen3-14B`) via `vLLM --enable-prefix-caching` and run `ctxblame why` or the\nPhase 3 attribution benchmark at **$0 API cost**.\n\n- \n**Phase 0** ([experiments/phase0](https://github.com/kekeandzeyu/ctxblame/blob/main/experiments/phase0/README.md) ): five\nplanted-cause scenarios, both wire formats, two DeepSeek models.\n- \n**Phase 1** ([experiments/phase1](https://github.com/kekeandzeyu/ctxblame/blob/main/experiments/phase1/README.md) ): planted\ncauses in real agent traces with thinking on. Causes are usually redundant,\nthe agent's own history takes over later in a run, and DeepSeek restores\nremoved reasoning server-side unless the call ids change.\n- \n**Phase 2** ([experiments/phase2/results/results.md](https://github.com/kekeandzeyu/ctxblame/blob/main/experiments/phase2/results/results.md) ):\nend-to-end validation of the original`ddmin` engine, exposing precondition\nconfounding (`step5` /`step7` ), hitchhikers, and byte-0 cache invalidation.\n- \n**Phase 3–4** ([experiments/phase3/RESULTS.md](https://github.com/kekeandzeyu/ctxblame/blob/main/experiments/phase3/RESULTS.md) ):\nattribution benchmark on open models at $0 (Qwen3-8B, Qwen3-14B-FP8 with\nthinking off and on, Llama-3.1-8B; vLLM, 3 seeds, oracle-validated cases): generated cases (8 tool conventions\n× 5 carrier places, redundancy, preconditions, negatives), ~35k-char\nprompts, and 15 real recorded agent runs. ctxblame against`--given none` , ContextCite, leave-one-out and self-explanation: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 **ctxblame****94%****95%****95%****85%****92%****95%** ctxblame `--given none` 79% 76% 81% 77% 60% – ContextCite 71% 84% 83% 84% 29% – self-explanation 73% 60% 80% 67% 46% – leave-one-out 34% 39% 34% 36% 0% – On the noisier Llama-3.1-8B, ctxblame ties ContextCite on F1 but is still the only method that separates preconditions and gets negatives right. On long requests the suffix-first search needs 27% fewer replays and 34–38% less uncached input than a flat search; on short ones it saves nothing. \n\n```\nuv run python experiments/phase3/benchmark.py --dry-run   # offline check ($0)\n```\n\n- **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%).\n- **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.\n\n- **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.\n- **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` ).\n- **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).\n\nSee [docs/ROADMAP.md](https://github.com/kekeandzeyu/ctxblame/blob/main/docs/ROADMAP.md) for the audit, the theory plan and the exit gate of each phase:\n\n- \n**Phase 5, engine correctness:** split`<system-reminder>` blocks inside user turns into removable chunks, keep searching past diffuse preconditions, audit every reported cause on fresh replays (intersection-union + Holm), pin Anthropic`cache_control` breakpoints.\n- \n**Phase 6, ground truth independent of the method:** exhaustive$2^m$ removal tables per case (no oracle dropping), neutral probe lines, matched`tool_choice` interventions for rules that both trigger and steer the action.*Done:* 250 cases × 2 models. ctxblame scores 95% / 85% F1 on the cases`v0.2` 's oracle kept and 71% / 44% on the ones it dropped (Qwen3-14B / Llama-3.1-8B). With the action forced (6.4, v0.2.2), F1 on rules that trigger and steer rises from 53% to 62% (Qwen) and from 46% to 56% (Llama).\n- \n**Phase 7, steelmanned baselines and theory:** contrastive ContextCite, black-box group testing over keep-probabilities, full-context self-explanation; a group-testing formulation with the precondition gate as the separating structure.\n- \n**Phase 8, external validity:**`ctxblame wrap` , wire-captured steps from real harnesses on SWE-bench,`ctxblame verify` fix study, one approved closed-API run.`ctxblame import` (best effort, marked reconstructed) follows in`v0.3` .\n\n```\nuv run pytest\n```\n\n", "url": "https://wpnews.pro/news/ctxblame-git-blame-for-llm-agent-decisions-via-counterfactual-replay", "canonical_source": "https://github.com/kekeandzeyu/ctxblame", "published_at": "2026-11-28 12:47:34+00:00", "updated_at": "2026-11-28 13:12:37.199166+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "large-language-models", "ai-safety"], "entities": ["Ctxblame", "Qwen3-14B", "vLLM", "Anthropic", "OpenAI", "DeepSeek", "Claude Code"], "also_reported_by": [], "takeaway": "Ctxblame v0.2.2 attributes an agent decision to specific context chunks by replaying the recorded request with each chunk removed, and on a Qwen3-14B trace it caught all 3 redundant --tb=line carriers that leave-one-out missed, certifying the bundle on 20 fresh replays at p = 1.9e-6.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/ctxblame-git-blame-for-llm-agent-decisions-via-counterfactual-replay", "markdown": "https://wpnews.pro/news/ctxblame-git-blame-for-llm-agent-decisions-via-counterfactual-replay.md", "text": "https://wpnews.pro/news/ctxblame-git-blame-for-llm-agent-decisions-via-counterfactual-replay.txt", "jsonld": "https://wpnews.pro/news/ctxblame-git-blame-for-llm-agent-decisions-via-counterfactual-replay.jsonld"}}