refusectomy 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2747 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Refusectomy's Claude Code engine — find the exact moment a turn acquired a refusal, and what
4
+ actually fixes it.
5
+
6
+ Works on local Claude Code transcripts (~/.claude/projects/<slug>/*.jsonl).
7
+
8
+ A safety decline is HTTP 200 with message.stop_reason == "refusal" and an informational
9
+ message.stop_details {type, category, explanation, [fallback_has_prefill_claim]}.
10
+ stop_details can be null even on a refusal, so we always branch on stop_reason.
11
+
12
+ Subcommands
13
+ scan every refusal event, newest first
14
+ profile base rates + correlations: what actually predicts a refusal
15
+ trace one refusal in conversational context (the "moment")
16
+ session refusals in one session; --live for the session running right now
17
+ remedy the grounded remediation playbook for a category
18
+ bisect replay a conversation prefix-by-prefix to isolate the trigger (needs credentials)
19
+
20
+ Scope: this diagnoses over-refusal on legitimate work and applies documented remedies
21
+ (model/effort choice, context hygiene, fallbacks where they apply, verification programs).
22
+ It is not a classifier-evasion fuzzer and deliberately has no mutate-until-accepted mode.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import collections
28
+ import datetime as dt
29
+ import functools
30
+ import glob
31
+ import hashlib
32
+ import inspect
33
+ import json
34
+ import math
35
+ import os
36
+ import re
37
+ import statistics
38
+ import sys
39
+ import textwrap
40
+ from dataclasses import dataclass, field, asdict
41
+ from datetime import datetime, timezone
42
+
43
+ # Claude Code honours CLAUDE_CONFIG_DIR for everything it writes, transcripts included.
44
+ CLAUDE_HOME = os.path.expanduser(os.environ.get("CLAUDE_CONFIG_DIR") or "~/.claude")
45
+ TRANSCRIPT_ROOT = os.path.join(CLAUDE_HOME, "projects")
46
+ from refusectomy import __version__ # noqa: E402
47
+
48
+ def _state_home() -> str:
49
+ """Where reports, profiles and hook state live: $REFUSECTOMY_HOME, else the platform's
50
+ per-user state directory. Never the package directory, which an installed copy
51
+ cannot write to and which would put corpus-derived files inside a source tree."""
52
+ if os.environ.get("REFUSECTOMY_HOME"):
53
+ return os.path.expanduser(os.environ["REFUSECTOMY_HOME"])
54
+ if sys.platform == "darwin":
55
+ return os.path.expanduser("~/Library/Application Support/refusectomy")
56
+ if os.name == "nt":
57
+ return os.path.join(os.environ.get("LOCALAPPDATA") or os.path.expanduser("~"), "refusectomy")
58
+ return os.path.join(os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"),
59
+ "refusectomy")
60
+
61
+
62
+ REPORT_DIR = _state_home()
63
+
64
+ # Categories and what is documented to recover them. Source: bundled claude-api skill,
65
+ # shared/model-migration.md (refusal stop reason; per-model Safeguards sections).
66
+ FALLBACK_COVERS = {
67
+ "cyber": True,
68
+ "frontier_llm": True,
69
+ "bio": False, # explicitly NOT retried by server-side fallback
70
+ "reasoning_extraction": False,
71
+ "general_harms": False,
72
+ None: None,
73
+ }
74
+
75
+
76
+ def _js_hash(s: str) -> int:
77
+ """JavaScript's `(h << 5) - h + charCodeAt(i) | 0` over UTF-16 code units."""
78
+ h = 0
79
+ data = s.encode("utf-16-le", "surrogatepass")
80
+ for i in range(0, len(data), 2):
81
+ h = ((h << 5) - h + (data[i] | data[i + 1] << 8)) & 0xFFFFFFFF
82
+ return h - 0x100000000 if h & 0x80000000 else h
83
+
84
+
85
+ def _base36(n: int) -> str:
86
+ out = ""
87
+ while True:
88
+ n, r = divmod(n, 36)
89
+ out = "0123456789abcdefghijklmnopqrstuvwxyz"[r] + out
90
+ if not n:
91
+ return out
92
+
93
+
94
+ def slug_for(path: str) -> str:
95
+ """Claude Code's project directory name for a cwd, ported from its binary (2.1.333):
96
+ every character outside [A-Za-z0-9] becomes '-' (per UTF-16 code unit), and a name
97
+ longer than 200 is cut to 200 plus '-' and a base-36 hash of the original path.
98
+ Replacing only '/' -- the old rule -- found nothing for any path with '_', '.', ' '."""
99
+ n = "".join(c if c.isascii() and c.isalnum() else ("--" if ord(c) > 0xFFFF else "-")
100
+ for c in path)
101
+ return n if len(n) <= 200 else f"{n[:200]}-{_base36(abs(_js_hash(path)))}"
102
+
103
+
104
+ def project_dirs(cwd_filter: str | None = None) -> list[str]:
105
+ if cwd_filter:
106
+ d = os.path.join(TRANSCRIPT_ROOT, slug_for(os.path.abspath(cwd_filter)))
107
+ return [d] if os.path.isdir(d) else []
108
+ return sorted(
109
+ p for p in glob.glob(os.path.join(TRANSCRIPT_ROOT, "*")) if os.path.isdir(p)
110
+ )
111
+
112
+
113
+ def transcript_files(cwd_filter: str | None = None) -> list[str]:
114
+ """All transcripts under each project dir, including nested subagents/*.jsonl."""
115
+ out: list[str] = []
116
+ for d in project_dirs(cwd_filter):
117
+ out.extend(sorted(glob.glob(os.path.join(d, "**", "*.jsonl"), recursive=True)))
118
+ return sorted(set(out))
119
+
120
+
121
+ @dataclass
122
+ class Turn:
123
+ """One assistant API result, refusal or not."""
124
+ uuid: str = ""
125
+ parent: str = ""
126
+ session: str = ""
127
+ project: str = ""
128
+ cwd: str = ""
129
+ ts: str = ""
130
+ version: str = ""
131
+ model: str = ""
132
+ effort: str = ""
133
+ synthetic: bool = False
134
+ sidechain: bool = False
135
+ # One conversation thread: the session for the main loop, session/agent for a
136
+ # subagent (whose records carry the PARENT's sessionId). Sequences are per thread.
137
+ thread: str = ""
138
+ has_request_id: bool = True
139
+ stop_reason: str | None = None
140
+ category: str | None = None
141
+ explanation: str | None = None
142
+ prefill_claim: bool | None = None
143
+ classifier_req: str | None = None
144
+ request_id: str | None = None
145
+ input_tokens: int = 0
146
+ cache_read: int = 0
147
+ cache_create: int = 0
148
+ output_tokens: int = 0
149
+ thinking_tokens: int = 0
150
+ content_types: list[str] = field(default_factory=list)
151
+ thinking_ms: int | None = None
152
+ has_usage: bool = True
153
+
154
+ @property
155
+ def context_tokens(self) -> int:
156
+ return self.input_tokens + self.cache_read + self.cache_create
157
+
158
+ @property
159
+ def refused(self) -> bool:
160
+ return self.stop_reason == "refusal"
161
+
162
+ @property
163
+ def pre_output(self) -> bool:
164
+ """Classifier fired before any output block was produced."""
165
+ return self.refused and not self.content_types
166
+
167
+
168
+ def _iget(d, *names, default=0):
169
+ for n in names:
170
+ v = d.get(n)
171
+ if isinstance(v, (int, float)):
172
+ return int(v)
173
+ return default
174
+
175
+
176
+ def project_of(path: str) -> str:
177
+ """Project dir name for a transcript, however deeply nested.
178
+
179
+ Transcripts live at <root>/<project>/<session>.jsonl and subagent transcripts at
180
+ <root>/<project>/<session>/subagents/agent-*.jsonl, so walk up to the child of root.
181
+ """
182
+ d = os.path.dirname(os.path.abspath(path))
183
+ root = os.path.abspath(TRANSCRIPT_ROOT)
184
+ while os.path.dirname(d) != root and os.path.dirname(d) != d:
185
+ d = os.path.dirname(d)
186
+ return os.path.basename(d)
187
+
188
+
189
+ @dataclass
190
+ class Event:
191
+ """One refusal EVENT, keyed off Claude Code's own system warning record.
192
+
193
+ Claude Code writes a `type: "system"` record with subtype `model_refusal_fallback`
194
+ or `model_refusal_no_fallback` for each decline, carrying apiRefusalCategory,
195
+ apiRefusalExplanation, refusedUserMessageUuid, originalModel and requestId.
196
+ That record is authoritative: it names the refused user message directly, so we
197
+ never have to guess an antecedent by walking parentUuid (which lands on harness
198
+ bookkeeping records like total_tokens_reminder ~2/3 of the time).
199
+ """
200
+ request_id: str | None = None
201
+ ts: str = ""
202
+ session: str = ""
203
+ project: str = ""
204
+ cwd: str = ""
205
+ category: str | None = None
206
+ explanation: str | None = None
207
+ fallback_attempted: bool = False
208
+ original_model: str = ""
209
+ sidechain: bool = False
210
+ refused_user_uuid: str | None = None
211
+ antecedent: str = "<unresolved>"
212
+ antecedent_text: str = ""
213
+ antecedent_chars: int = 0
214
+ # Identity without content: a digest and a coarse shape are enough to cross-reference
215
+ # a refused message, cite it in a false-positive report, or count it -- without
216
+ # reproducing it. See fingerprint() for why that distinction is load-bearing.
217
+ antecedent_sha: str = ""
218
+ antecedent_nsha: str = "" # digest of the whitespace-normalised text
219
+ antecedent_words: int = 0
220
+ antecedent_shape: str = ""
221
+ # enriched from the matching assistant record, when the join succeeds
222
+ effort: str = ""
223
+ thinking_tokens: int = 0
224
+ context_tokens: int = 0
225
+ content_types: list[str] = field(default_factory=list)
226
+ classifier_req: str | None = None
227
+ joined: bool = False
228
+
229
+
230
+ REFUSAL_NOTICE = "stopped by a safety classifier"
231
+
232
+ # Short control utterances observed in this corpus: the press of "go", carrying no content
233
+ # of their own -- most of this corpus's refused messages are one of these. Naming one is
234
+ # strictly more informative than redacting it, so these are always shown. The live share is
235
+ # printed by `profile` (shape of the refused message), never hardcoded here.
236
+ CONTROL_TOKENS = {
237
+ "continue", "continue.", "cont", "go", "go on", "go ahead", "next", "ok", "okay", "k",
238
+ "yes", "y", "yep", "do it", "proceed", "keep going", "more", "and?", "?", "??", "...",
239
+ "..", ".", "bro", "lol", "wow", "write", "now what?", "lol irony", "thanks", "ty", "nice",
240
+ }
241
+
242
+
243
+ def fingerprint(txt: str) -> tuple[str, int, str]:
244
+ """Identify a refused message without reproducing it.
245
+
246
+ A forensic tool that can only print refused text verbatim cannot be operated by a
247
+ model: the text lands in the operating model's own context, where it can trip the
248
+ same classifier. That is not hypothetical -- on 2026-11-27 presenting the output of
249
+ `trace --project <its heaviest project>` was itself declined, mid-sentence, by the bio classifier.
250
+ The content was never the user's request; it was this tool's own stdout.
251
+
252
+ So every default surface identifies a message by digest + shape, which is what
253
+ forensics actually needs (cross-reference, dedupe, cite in a report), and verbatim
254
+ text is opt-in and goes to a file the human reads directly.
255
+ """
256
+ sha = hashlib.sha256(txt.encode("utf-8", "replace")).hexdigest()[:12]
257
+ words = len(txt.split())
258
+ n = len(txt)
259
+ if not n:
260
+ return sha, 0, "empty"
261
+ alpha = sum(c.isalpha() for c in txt)
262
+ digit = sum(c.isdigit() for c in txt)
263
+ space = sum(c.isspace() for c in txt)
264
+ other = n - alpha - digit - space
265
+ shape = (f"{n}c/{words}w alpha {100 * alpha // n}% digit {100 * digit // n}% "
266
+ f"space {100 * space // n}% other {100 * other // n}%")
267
+ return sha, words, shape
268
+
269
+
270
+ def is_control(txt: str) -> bool:
271
+ """True when the refused message is a bare control token (no content of its own)."""
272
+ return " ".join(txt.split()).strip().lower() in CONTROL_TOKENS
273
+
274
+
275
+ def classify_user_record(rec) -> tuple[str, str]:
276
+ """-> (kind, text). Kind is what the refused user message actually was."""
277
+ m = rec.get("message")
278
+ if not isinstance(m, dict):
279
+ return "<no message>", ""
280
+ c = m.get("content")
281
+ has_tr = False
282
+ texts: list[str] = []
283
+ if isinstance(c, str):
284
+ texts.append(c)
285
+ elif isinstance(c, list):
286
+ for b in c:
287
+ if not isinstance(b, dict):
288
+ continue
289
+ if b.get("type") == "tool_result":
290
+ has_tr = True
291
+ elif b.get("type") == "text":
292
+ texts.append(str(b.get("text", "")))
293
+ joined = " ".join(texts)
294
+ has_tx = bool(joined.strip())
295
+ if REFUSAL_NOTICE in joined:
296
+ kind = "refusal notice (loop)"
297
+ elif has_tr and has_tx:
298
+ kind = "tool_result + text"
299
+ elif has_tr:
300
+ kind = "tool_result"
301
+ elif has_tx:
302
+ kind = "real user text"
303
+ else:
304
+ kind = "empty/other"
305
+ return kind, joined
306
+
307
+
308
+ def load_events(cwd_filter: str | None = None, sessions: set[str] | None = None,
309
+ files: list[str] | None = None):
310
+ """Authoritative refusal events + deduped assistant turns for base rates.
311
+
312
+ Returns (events, turns_by_request, seen_files). Assistant records are deduped by
313
+ requestId: streaming writes several records per API request, all carrying the final
314
+ stop_reason, so counting records inflates everything.
315
+
316
+ `files` reads exactly those transcripts instead of globbing the corpus. The live
317
+ guard needs one session's file in milliseconds on every turn end, and giving it a
318
+ narrow entry into this parser is the alternative to writing it a second one --
319
+ which is bug 7, and is now an audit invariant.
320
+ """
321
+ sys_refusals: list[dict] = []
322
+ by_uuid: dict[str, dict] = {}
323
+ assistant: dict[str, Turn] = {}
324
+ synth: dict[str, Turn] = {}
325
+ derived: dict[str, set] = {} # session -> sessions it was forked from
326
+ rid_sessions: dict[str, set] = collections.defaultdict(set)
327
+ files = list(files) if files is not None else transcript_files(cwd_filter)
328
+ for f in files:
329
+ project = project_of(f)
330
+ stem = os.path.splitext(os.path.basename(f))[0]
331
+ try:
332
+ fh = open(f, "r", errors="replace")
333
+ except OSError:
334
+ continue
335
+ with fh:
336
+ for line in fh:
337
+ if not line.strip():
338
+ continue
339
+ try:
340
+ rec = json.loads(line)
341
+ except Exception:
342
+ continue
343
+ if not isinstance(rec, dict):
344
+ continue
345
+ sid = rec.get("sessionId") or rec.get("session_id") or ""
346
+ if sessions and sid not in sessions:
347
+ continue
348
+ u = rec.get("uuid")
349
+ if u:
350
+ by_uuid[u] = rec
351
+ rtype = rec.get("type")
352
+ if rtype == "derived-from":
353
+ derived.setdefault(sid, set()).update(
354
+ x.get("id") for x in rec.get("sessions") or [] if isinstance(x, dict) and x.get("id"))
355
+ continue
356
+ if rtype == "system" and str(rec.get("subtype", "")).startswith("model_refusal"):
357
+ rec["_project"] = project
358
+ sys_refusals.append(rec)
359
+ continue
360
+ if rtype != "assistant":
361
+ continue
362
+ msg = rec.get("message")
363
+ if not isinstance(msg, dict) or msg.get("stop_reason") is None:
364
+ continue
365
+ rid = rec.get("requestId") or u or ""
366
+ sd = msg.get("stop_details")
367
+ sd = sd if isinstance(sd, dict) else {}
368
+ usage = msg.get("usage") if isinstance(msg.get("usage"), dict) else {}
369
+ otd = usage.get("output_tokens_details")
370
+ otd = otd if isinstance(otd, dict) else {}
371
+ content = msg.get("content")
372
+ ctypes = [b.get("type", "?") for b in content
373
+ if isinstance(b, dict)] if isinstance(content, list) else []
374
+ model = rec.get("requestedModel") or msg.get("model") or ""
375
+ t = Turn(
376
+ uuid=u or "", parent=rec.get("parentUuid") or "", session=sid,
377
+ project=project, cwd=rec.get("cwd") or "", ts=rec.get("timestamp") or "",
378
+ version=rec.get("version") or "", model=model,
379
+ effort=str(rec.get("effort") or rec.get("perTurnEffort") or ""),
380
+ synthetic=(model == "<synthetic>"), sidechain=bool(rec.get("isSidechain")),
381
+ thread=(f"{sid}/{rec.get('agentId') or stem}" if rec.get("isSidechain")
382
+ else sid),
383
+ has_request_id=bool(rec.get("requestId")),
384
+ stop_reason=msg.get("stop_reason"),
385
+ category=sd.get("category"), explanation=sd.get("explanation"),
386
+ prefill_claim=sd.get("fallback_has_prefill_claim"),
387
+ classifier_req=rec.get("serverClassifierRequest"), request_id=rid,
388
+ input_tokens=_iget(usage, "input_tokens"),
389
+ cache_read=_iget(usage, "cache_read_input_tokens"),
390
+ cache_create=_iget(usage, "cache_creation_input_tokens"),
391
+ output_tokens=_iget(usage, "output_tokens"),
392
+ thinking_tokens=_iget(otd, "thinking_tokens"),
393
+ content_types=ctypes, thinking_ms=rec.get("thinkingDurationMs"),
394
+ has_usage=bool(usage),
395
+ )
396
+ # <synthetic> records are the harness's own notices and can carry the
397
+ # refused request's requestId. One used to replace an empty (pre-output)
398
+ # real record -- a one-block notice outranks zero blocks -- which joined
399
+ # the event to the notice and dropped the refusal from every count. Real
400
+ # records only compete with real ones; a notice stands in only where
401
+ # nothing real exists, and never joins an event.
402
+ if t.synthetic:
403
+ old = synth.get(rid)
404
+ if old is None or (t.output_tokens, len(t.content_types)) > \
405
+ (old.output_tokens, len(old.content_types)):
406
+ synth[rid] = t
407
+ continue
408
+ rid_sessions[rid].add(sid)
409
+ prev = assistant.get(rid)
410
+ if prev is None:
411
+ assistant[rid] = t
412
+ continue
413
+ # Streaming writes a record per content block: the request's content is
414
+ # their union, not whichever record happened to carry the most tokens.
415
+ merged = list(dict.fromkeys(prev.content_types + t.content_types))
416
+ if (t.output_tokens, len(t.content_types)) > \
417
+ (prev.output_tokens, len(prev.content_types)):
418
+ assistant[rid] = t
419
+ assistant[rid].content_types = merged
420
+
421
+ for rid, t in synth.items():
422
+ assistant.setdefault(rid, t)
423
+ # A fork (Claude Code's own, or refusectomy's excised copy) repeats its source's history
424
+ # under a new sessionId, and the dedupe keeps whichever copy it read first. Credit each
425
+ # copied request to the session it was actually asked in -- the one not derived from any
426
+ # other that carries it -- or every per-session sequence splits across copies.
427
+ def ancestors(x: str) -> set:
428
+ out, todo = set(), list(derived.get(x, ()))
429
+ while todo and len(out) < 64:
430
+ y = todo.pop()
431
+ if y not in out:
432
+ out.add(y)
433
+ todo.extend(derived.get(y, ()))
434
+ return out
435
+ if derived:
436
+ for rid, ss in rid_sessions.items():
437
+ if len(ss) < 2 or rid not in assistant:
438
+ continue
439
+ roots = [x for x in ss if not (ancestors(x) & ss)]
440
+ t = assistant[rid]
441
+ if len(roots) == 1 and t.session != roots[0]:
442
+ if t.thread == t.session:
443
+ t.thread = roots[0]
444
+ elif t.thread.startswith(t.session + "/"):
445
+ t.thread = roots[0] + t.thread[len(t.session):]
446
+ t.session = roots[0]
447
+ # A forked or continued session copies the history -- warning records included, same
448
+ # uuid -- under a new sessionId, which counted one decline twice. Count it once, in
449
+ # the session the same request's turn is attributed to, so numerator and denominator
450
+ # agree; otherwise keep the first copy seen.
451
+ chosen: dict = {}
452
+ for s in sys_refusals:
453
+ key = s.get("uuid") or (s.get("requestId"), s.get("timestamp"))
454
+ cur = chosen.get(key)
455
+ if cur is None:
456
+ chosen[key] = s
457
+ continue
458
+ home = assistant[s["requestId"]].session if s.get("requestId") in assistant else None
459
+ if home and s.get("sessionId") == home and cur.get("sessionId") != home:
460
+ chosen[key] = s
461
+ sys_refusals = list(chosen.values())
462
+
463
+ events: list[Event] = []
464
+ for s in sys_refusals:
465
+ ru = s.get("refusedUserMessageUuid")
466
+ ev = Event(
467
+ request_id=s.get("requestId"), ts=s.get("timestamp") or "",
468
+ session=s.get("sessionId") or s.get("session_id") or "",
469
+ project=s.get("_project", ""), cwd=s.get("cwd") or "",
470
+ category=s.get("apiRefusalCategory"),
471
+ explanation=s.get("apiRefusalExplanation"),
472
+ fallback_attempted=(s.get("subtype") == "model_refusal_fallback"),
473
+ original_model=s.get("originalModel") or "",
474
+ sidechain=bool(s.get("isSidechain")), refused_user_uuid=ru,
475
+ )
476
+ ur = by_uuid.get(ru) if ru else None
477
+ if ur is None:
478
+ ev.antecedent = "<refused uuid not in corpus>"
479
+ elif ur.get("type") != "user":
480
+ ev.antecedent = f"<{ur.get('type')}>"
481
+ else:
482
+ kind, text = classify_user_record(ur)
483
+ ev.antecedent = kind
484
+ ev.antecedent_text = text[:4000]
485
+ ev.antecedent_chars = len(text)
486
+ ev.antecedent_sha, ev.antecedent_words, ev.antecedent_shape = fingerprint(text)
487
+ ev.antecedent_nsha = fingerprint(" ".join(text.split()))[0]
488
+ a = assistant.get(ev.request_id) if ev.request_id else None
489
+ if a is not None and not a.synthetic:
490
+ ev.joined = True
491
+ ev.effort = a.effort
492
+ ev.thinking_tokens = a.thinking_tokens
493
+ ev.context_tokens = a.context_tokens
494
+ ev.content_types = a.content_types
495
+ ev.classifier_req = a.classifier_req
496
+ events.append(ev)
497
+ # A null "timestamp" would make this compare None with str; _ts sorts it first.
498
+ events.sort(key=lambda e: _ts(e.ts))
499
+ return events, assistant, files
500
+
501
+
502
+ def real_refusals(turns, include_synthetic=False):
503
+ return [t for t in turns if t.refused and (include_synthetic or not t.synthetic)]
504
+
505
+
506
+ # ---------------------------------------------------------------- live session
507
+
508
+ def current_session_id() -> str | None:
509
+ for var in ("CLAUDE_SESSION_ID", "CLAUDE_CODE_SESSION_ID"):
510
+ if os.environ.get(var):
511
+ return os.environ[var]
512
+ # Claude Code's scratchpad path embeds the session id:
513
+ # /tmp/<uid>/<project-slug>/<session-id>/scratchpad
514
+ for var in ("CLAUDE_SCRATCHPAD_DIR", "TMPDIR"):
515
+ v = os.environ.get(var, "")
516
+ for part in v.split("/"):
517
+ if len(part) == 36 and part.count("-") == 4:
518
+ return part
519
+ return None
520
+
521
+
522
+ def session_transcript(session_id: str, cwd: str | None = None) -> str | None:
523
+ """Path of one session's transcript, by direct construction where possible.
524
+
525
+ Claude Code writes <root>/<cwd-slug>/<session-id>.jsonl, so the common case is a
526
+ single stat rather than a glob over every project. Only an unknown cwd falls back
527
+ to searching, and even then it matches on the file name, not on file contents.
528
+ """
529
+ if not session_id:
530
+ return None
531
+ if cwd:
532
+ p = os.path.join(TRANSCRIPT_ROOT, slug_for(os.path.abspath(cwd)),
533
+ f"{session_id}.jsonl")
534
+ if os.path.exists(p):
535
+ return p
536
+ hits = glob.glob(os.path.join(TRANSCRIPT_ROOT, "*", f"{session_id}.jsonl"))
537
+ return hits[0] if hits else None
538
+
539
+
540
+ def newest_session(cwd: str) -> tuple[str | None, str | None]:
541
+ files = [f for f in transcript_files(cwd) if f"{os.sep}subagents{os.sep}" not in f]
542
+ if not files:
543
+ return None, None
544
+ newest = max(files, key=lambda p: os.path.getmtime(p))
545
+ return os.path.splitext(os.path.basename(newest))[0], newest
546
+
547
+
548
+ # ---------------------------------------------------------------- commands
549
+
550
+ def fmt_tok(n: int) -> str:
551
+ if n >= 1_000_000:
552
+ return f"{n/1_000_000:.2f}M"
553
+ if n >= 1000:
554
+ return f"{n/1000:.0f}k"
555
+ return str(n)
556
+
557
+
558
+ SCOPE_MARKERS = ("audit", "entire", "everything", "all claims", "from scratch",
559
+ "go deep", "deep dive", "comprehensive", "exhaustive", "whole",
560
+ "full review", "adversarial", "ignore previous")
561
+
562
+
563
+ def cmd_audit(args):
564
+ """Self-check: verify the invariants this tool's conclusions depend on."""
565
+ events, turns, files = load_events(args.cwd)
566
+ ref_turns = [t for t in turns.values()
567
+ if t.stop_reason == "refusal" and not t.synthetic]
568
+ answered = [t for t in turns.values() if not t.synthetic]
569
+ ok = True
570
+
571
+ def chk(label, passed, detail=""):
572
+ nonlocal ok
573
+ ok = ok and passed
574
+ print(f" [{'PASS' if passed else 'FAIL'}] {label}" + (f" {detail}" if detail else ""))
575
+
576
+ print("=" * 74)
577
+ print("AUDIT — invariants behind every number this tool prints")
578
+ print("=" * 74)
579
+ print(f"\ntranscripts read: {len(files)}"
580
+ f" (nested subagent files included: "
581
+ f"{sum(1 for f in files if os.sep + 'subagents' + os.sep in f)})")
582
+ print(f"refusal events (system records) : {len(events)}")
583
+ print(f"refusal turns (deduped by requestId, non-synthetic) : {len(ref_turns)}")
584
+ print(f"answered turns (deduped, non-synthetic) : {len(answered)}")
585
+ print()
586
+
587
+ chk("found any refusal events", len(events) > 0, f"{len(events)}")
588
+ cats = collections.Counter(str(e.category) for e in events)
589
+ chk("every event has a category", "None" not in cats, dict(cats))
590
+ unres = [e for e in events if e.antecedent.startswith("<")]
591
+ chk("antecedent resolved for >=95% of events",
592
+ len(events) and len(unres) / len(events) <= 0.05,
593
+ f"{len(events)-len(unres)}/{len(events)} resolved")
594
+ # A fallback event's persisted assistant record belongs to the FALLBACK request
595
+ # under a new requestId, so the original refused request has no record to join.
596
+ # The real invariant is that every non-fallback event joins.
597
+ nofb = [e for e in events if not e.fallback_attempted]
598
+ nofb_joined = [e for e in nofb if e.joined]
599
+ fb = [e for e in events if e.fallback_attempted]
600
+ fb_joined = [e for e in fb if e.joined]
601
+ # Three honest states for an event, and nothing else. Joined: a real response
602
+ # record carries its requestId. Notice-only: the harness persisted no response, just
603
+ # its own <synthetic> notice -- which once joined as if it were the response, making
604
+ # pre-output declines look mid-stream. Fallback: the response was retracted and the
605
+ # retry persisted under a new requestId.
606
+ notice_only = [e for e in nofb if not e.joined and e.request_id in turns
607
+ and turns[e.request_id].synthetic]
608
+ chk("every non-fallback event joins a real response or a notice-only record",
609
+ len(nofb) == len(nofb_joined) + len(notice_only),
610
+ f"{len(nofb_joined)} joined, {len(notice_only)} notice-only (no persisted response)"
611
+ f", {len(nofb) - len(nofb_joined) - len(notice_only)} neither")
612
+ chk("fallback events never join a response record",
613
+ len(fb_joined) == 0,
614
+ f"{len(fb)} fallback events, unjoined as expected "
615
+ f"(their record is the fallback response under a new requestId)")
616
+ # request_id is backfilled from the record uuid, so test what the record carried.
617
+ rid_dupes = len([t for t in turns.values() if not t.synthetic and not t.has_request_id])
618
+ chk("every deduped turn has a requestId", rid_dupes == 0,
619
+ f"{rid_dupes} without")
620
+ # Redaction is an invariant, not a convention: a report that embeds refused prose
621
+ # cannot be handed to a model, and this tool's own stdout has tripped the classifier.
622
+ resolved = [e for e in events if not e.antecedent.startswith("<")]
623
+ nodigest = [e for e in resolved if not e.antecedent_sha]
624
+ chk("every resolved antecedent carries a digest", not nodigest,
625
+ f"{len(resolved)-len(nodigest)}/{len(resolved)} fingerprinted")
626
+ sample = scan_payload(resolved[:5], verbatim=False)
627
+ chk("default JSON report carries no verbatim refused text",
628
+ bool(sample) and all("antecedent_text" not in r for r in sample)
629
+ and all(r.get("antecedent_sha") for r in sample),
630
+ "digest-only rows")
631
+ nousage = [t for t in answered if not t.has_usage]
632
+ chk("usage present on answered turns", len(nousage) == 0,
633
+ f"{len(nousage)} missing usage (excluded from size stats)")
634
+
635
+ # The bug this invariant exists to catch: the bio playbook was once frozen prose, and it
636
+ # went on asserting a headline ("180 of 262 followed a TOOL RESULT") that this audit had
637
+ # already disproved -- giving the opposite of the supported advice. A static playbook may
638
+ # state documented API facts; a corpus statistic has to be computed.
639
+ stat_like = re.compile(r"\d+(?:\.\d+)?\s?%|\bof \d{3,}\b|\b\d{3,} (?:events|refusals)\b")
640
+ static_prose = dict(REMEDIES)
641
+ static_prose.update({f"DOC_FACTS[{t}]": q for t, q, _ in DOC_FACTS})
642
+ offenders = {c: stat_like.findall(t) for c, t in static_prose.items()
643
+ if stat_like.search(t)}
644
+ chk("static playbooks quote no corpus statistics", not offenders,
645
+ "computed, not frozen" if not offenders else f"{offenders}")
646
+ rendered_blind = render_bio(None)
647
+ chk("bio playbook degrades without a profile instead of inventing numbers",
648
+ not stat_like.search(rendered_blind) and "profile" in rendered_blind,
649
+ "says to run `profile`")
650
+ # Bug 4 was a nested subagent path resolving to a dir name that is not a project.
651
+ # It was fixed in one loader and survived in the other for as long as there were
652
+ # two, so the invariant is now about attribution itself, not about one call site:
653
+ # every turn and every event must land in a directory that really is a project.
654
+ real_projects = {os.path.basename(d) for d in project_dirs(args.cwd)}
655
+ bad_t = {t.project for t in turns.values()} - real_projects
656
+ bad_e = {e.project for e in events} - real_projects
657
+ chk("every turn lands in a real project directory", not bad_t,
658
+ "no nested dir names leaking in" if not bad_t else f"bogus: {sorted(bad_t)}")
659
+ chk("numerator and denominator share one project attribution", not bad_e,
660
+ f"{len(real_projects)} project dirs, events and turns agree"
661
+ if not bad_e else f"events in non-projects: {sorted(bad_e)}")
662
+ # ... and only one function may derive it, so the two cannot drift apart again.
663
+ me = open(os.path.abspath(__file__), errors="replace").read()
664
+ # assembled, so this check does not match its own source line
665
+ needle = "basename(os.path." + "dirname(f))" # split so it misses its own line
666
+ dup_attr = me.count(needle)
667
+ chk("exactly one corpus parser derives the project", dup_attr == 0,
668
+ "project_of() is the only path" if dup_attr == 0
669
+ else f"{dup_attr} flat basename attribution(s) -- bug 4 regressed")
670
+
671
+ # ------------------------------------------------------------------ live guard
672
+ # The guard is the only surface that speaks while a session is still running, so
673
+ # it is the one most able to do harm. Two things must stay true of it, and both
674
+ # are the sort of thing a later well-meaning edit would undo.
675
+ # read the functions themselves: slicing the file by name would match the names
676
+ # written here, in this check
677
+ guard_src = inspect.getsource(guard_message) + inspect.getsource(cmd_guard)
678
+ chk("guard never feeds the model, only the user",
679
+ "additionalContext" not in guard_src and "systemMessage" in guard_src,
680
+ "systemMessage only — reacting to a decline in the declined context is what "
681
+ "produces the runs")
682
+ # Render a real warning for whichever session declined most, and check the refused
683
+ # text is nowhere in it. The guard reports counts, models and context size only.
684
+ worst = collections.Counter(e.session for e in events).most_common(1)
685
+ leak = []
686
+ if worst:
687
+ sess = worst[0][0]
688
+ sev = [e for e in events if e.session == sess]
689
+ rt = [t for t in turns.values()
690
+ if t.session == sess and t.stop_reason == "refusal"]
691
+ gm = guard_message(len(sev), len(rt),
692
+ [e.category for e in sev],
693
+ rt[-1].model if rt else "", rt[-1].context_tokens if rt else 0,
694
+ load_profile())
695
+ leak = [e.antecedent_sha for e in events
696
+ if len(e.antecedent_text) >= 16 and e.antecedent_text in gm]
697
+ chk("guard warning carries no refused text", not leak,
698
+ "counts, model and context only" if not leak else f"leaked: {leak}")
699
+ # ------------------------------------------------------------------ fp report
700
+ # The report is the one artifact built to leave this machine, so what it must not
701
+ # carry matters more here than anywhere else.
702
+ rep_turns = [t for t in turns.values()
703
+ if not t.synthetic and t.stop_reason == "refusal"]
704
+ rep = render_fp_report(_incidents(events, rep_turns), rep_turns, events,
705
+ load_profile(), None)
706
+ leaked = [e.antecedent_sha for e in events
707
+ if len(e.antecedent_text) >= 16 and e.antecedent_text in rep]
708
+ chk("default fp report carries no refused text", not leaked,
709
+ "request IDs and digests only" if not leaked else f"leaked: {leaked}")
710
+ # Support can only act on a request it can look up, so every refused request in
711
+ # scope must appear with its id -- including the retries that got no warning record,
712
+ # which are billed requests too and were invisible before this was checked.
713
+ missing_id = [t for t in rep_turns if t.request_id and f"`{t.request_id}`" not in rep]
714
+ chk("fp report names every refused request by requestId", not missing_id,
715
+ f"{len(rep_turns)} refused requests, all with ids in the bundle"
716
+ if not missing_id else f"{len(missing_id)} absent from the report")
717
+ n_cls = len([t for t in rep_turns if t.classifier_req])
718
+ chk("fp report states classifier-id coverage rather than dropping gaps",
719
+ "serverClassifierRequest" in rep
720
+ and (n_cls == len(rep_turns) or "not recorded" in rep),
721
+ f"{n_cls}/{len(rep_turns)} carry one; gaps are printed as 'not recorded'")
722
+ # It must not write the user's own justification for them.
723
+ chk("fp report leaves the legitimate-use statement to the user",
724
+ WORK_PLACEHOLDER in rep and "What this work is" in rep,
725
+ "placeholder present, nothing invented")
726
+ # --verbatim is an opt-in for the markdown. The JSON is the record you keep, so it
727
+ # must never carry the text whatever the flag says.
728
+ vmap = {e.request_id: " ".join(e.antecedent_text.split())[:400]
729
+ for e in events if e.request_id and e.antecedent_text
730
+ and not is_control(e.antecedent_text)}
731
+ jrows = json.dumps(_incidents(events, rep_turns))
732
+ jleak = [e.antecedent_sha for e in events
733
+ if len(e.antecedent_text) >= 16
734
+ and json.dumps(e.antecedent_text)[1:-1] in jrows] # as JSON escapes it
735
+ vrep = render_fp_report(_incidents(events, rep_turns), rep_turns, events, None, vmap)
736
+ chk("fp report JSON never carries refused text, even under --verbatim",
737
+ not jleak and (not vmap or any(v in vrep for v in list(vmap.values())[:1])),
738
+ "text reaches the .md only; the .json stays digest-only"
739
+ if not jleak else f"leaked into JSON: {jleak}")
740
+
741
+ blind_guard = guard_message(1, 1, ["bio"], "", 0, None)
742
+ chk("guard degrades without a profile instead of inventing numbers",
743
+ not stat_like.search(blind_guard) and "profile" in blind_guard,
744
+ "names the condition, says to run `profile`")
745
+
746
+ prof = load_profile()
747
+ needed = ("refused_shape", "rates", "timing", "generated")
748
+ missing = [k for k in needed if not (prof or {}).get(k)]
749
+ # A marginal rate presented as an effect is the next bug in the documented
750
+ # family, so the profile is not allowed to ship without the controlled view.
751
+ conf = (prof or {}).get("confounds") or {}
752
+ # Bug 10: the paired within-session model estimate set one model's pre-decline turns
753
+ # against another's post-decline turns, because the refusal fallback latches a declined
754
+ # session onto its fallback model. The profile must carry the first-decline comparison
755
+ # instead, and must not carry the paired one under its old name.
756
+ has_mh = bool((conf.get("model_hazard") or {}).get("scopes"))
757
+ good = bool(conf.get("independent")) and has_mh and "paired_model" not in conf
758
+ chk("profile reports controlled estimates, not marginal rates alone", good,
759
+ "independent rate + first-decline model comparison, no turn-level pairing" if good
760
+ else ("profile carries the retracted paired estimate -- re-run `profile`"
761
+ if "paired_model" in conf else "missing confound controls -- run `profile`"))
762
+ # Behavioural, on a synthetic session: a latched session's post-fallback turns must
763
+ # never enter the model comparison, and the retracted decline must count against the
764
+ # model that declined.
765
+ syn_t = [Turn(session="s", ts=f"2026-01-01T00:00:0{i}.000Z", model="m-new",
766
+ stop_reason="end_turn") for i in range(3)]
767
+ syn_t += [Turn(session="s", ts=f"2026-01-01T00:00:1{i}.000Z", model="m-old",
768
+ stop_reason="refusal" if i % 2 else "end_turn") for i in range(5)]
769
+ syn_e = [Event(session="s", ts="2026-01-01T00:00:05.000Z", fallback_attempted=True,
770
+ original_model="m-new", category="bio")]
771
+ hz = {r[0]: r for r in _first_decline(syn_t, syn_e)}
772
+ chk("models are compared only before each session's first decline",
773
+ hz.get("m-new", [None, 0, 0])[1:3] == [1, 4] and "m-old" not in hz,
774
+ "a latched session's post-fallback turns never enter the comparison")
775
+ fbe = [e for e in events if e.fallback_attempted]
776
+ unnamed = [e.request_id for e in fbe if not e.original_model]
777
+ chk("every fallback event names the model that declined", not unnamed,
778
+ f"{len(fbe)} fallback events, each attributed via originalModel" if not unnamed
779
+ else f"no originalModel on {unnamed[:5]}")
780
+ # Excision is held to its contract on a synthetic declined turn that made a tool call:
781
+ # only the decline's debris goes, the chain stays resumable, the user's words stay.
782
+ from refusectomy import excise as _ex
783
+ def _r(u, p, typ, **kw):
784
+ return {"uuid": u, "parentUuid": p, "type": typ, "sessionId": "src", **kw}
785
+ syn = [_r("u1", None, "user", message={"role": "user", "content": "hello"}),
786
+ _r("a1", "u1", "assistant", requestId="q1", message={"stop_reason": "end_turn", "content": [{"type": "text"}]}),
787
+ _r("u2", "a1", "user", message={"role": "user", "content": "next"}),
788
+ _r("a2", "u2", "assistant", requestId="q2", message={"stop_reason": "refusal",
789
+ "content": [{"type": "tool_use", "id": "t1"}]}),
790
+ _r("u3", "a2", "user", message={"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1"}]}),
791
+ _r("s1", "u3", "system", subtype="model_refusal_no_fallback", requestId="q2"),
792
+ _r("a3", "s1", "assistant", requestId="q2", requestedModel="<synthetic>",
793
+ message={"stop_reason": "refusal", "content": [{"type": "text"}]}),
794
+ _r("u4", "a3", "user", isMeta=True, message={"role": "user", "content": REFUSAL_NOTICE}),
795
+ _r("u5", "u4", "user", message={"role": "user", "content": "go on"}),
796
+ _r("a4", "u5", "assistant", requestId="q3", message={"stop_reason": "end_turn", "content": []})]
797
+ fork, xn = _ex.excise_records(syn, "src", "new")
798
+ kept = [r.get("uuid") for r in fork[1:]]
799
+ xprob = _ex.verify(syn, fork)
800
+ chk("excision removes only a decline's debris and keeps a resumable chain",
801
+ not xprob and kept == ["u1", "a1", "u2", "u5", "a4"]
802
+ and next(r for r in fork if r.get("uuid") == "u5")["parentUuid"] == "u2",
803
+ "declined response, its tool result, refusal record, notices out; chain re-linked"
804
+ if not xprob else "; ".join(xprob[:3]))
805
+ mfiles = memory_files({t.cwd for t in turns.values() if t.cwd})
806
+ leaks = memory_leaks(mfiles, {x for e in events for x in (e.antecedent_sha, e.antecedent_nsha) if x})
807
+ chk("no memory or CLAUDE.md that loads into a session reproduces a refused message",
808
+ not leaks, f"{len(mfiles)} files, compared by digest" if not leaks else
809
+ "; ".join(f"{p}:{ln} sha256:{d} ({n}c)" for p, ln, d, n, _a, _b in leaks[:5])
810
+ + " -- analysis/memory_poison.py --fix replaces them by digest")
811
+ chk("profile.json carries what `remedy` renders from",
812
+ prof is not None and not missing,
813
+ "present" if prof and not missing
814
+ else (f"missing {missing} -- run `profile`" if prof else "no profile.json -- run `profile`"))
815
+ # is parentUuid a trustworthy antecedent? (the bug this audit exists to catch)
816
+ print()
817
+ print(" parentUuid reliability check (why we use refusedUserMessageUuid):")
818
+ pk = collections.Counter()
819
+ for e in events:
820
+ pk[e.antecedent] += 1
821
+ sc = len([e for e in events if e.sidechain])
822
+ print(f" events on subagent sidechains: {sc}")
823
+ # Two different real quantities, not a discrepancy to be explained away.
824
+ ev_rids = {e.request_id for e in events if e.request_id}
825
+ extra = [t for t in ref_turns if t.request_id not in ev_rids]
826
+ sess_with = {e.session for e in events}
827
+ orphan = [t for t in extra if t.session not in sess_with]
828
+ print()
829
+ chk("no orphan refused requests (outside any warned session)",
830
+ len(extra) == 0 or len(orphan) / max(1, len(extra)) < 0.05,
831
+ f"{len(orphan)} orphan of {len(extra)} extra")
832
+ print(f"\nreconciliation — these measure different things:")
833
+ print(f" {len(events):>5} user-visible declines (one system warning each)")
834
+ print(f" {len(ref_turns):>5} refused API requests (billing / rate-limit footprint)")
835
+ print(f" {len(extra):>5} extra refused requests, {len(extra)-len(orphan)} of them inside a session")
836
+ print(f" that already has a warning -> harness retries within one declined turn.")
837
+ print(f"\n{'AUDIT OK' if ok else 'AUDIT FOUND PROBLEMS'}")
838
+ return 0 if ok else 1
839
+
840
+
841
+ def scan_payload(events, verbatim: bool = False) -> list[dict]:
842
+ """JSON rows for a report. Verbatim refused text is opt-in; the digest is always
843
+ present, which is what a false-positive report to Anthropic actually needs
844
+ (requestId + classifier id + digest, not the prose)."""
845
+ rows = []
846
+ for e in events:
847
+ d = asdict(e)
848
+ if not verbatim:
849
+ d.pop("antecedent_text", None)
850
+ rows.append(d)
851
+ return rows
852
+
853
+
854
+ def cmd_scan(args):
855
+ events, turns, files = load_events(args.cwd)
856
+ if args.category:
857
+ events = [e for e in events if e.category == args.category]
858
+ events = sorted(events, key=lambda e: e.ts, reverse=True)
859
+ print(f"{len(events)} refusal events across {len(files)} transcripts\n")
860
+ hdr = (f"{'when (UTC)':20} {'cat':5} {'model':18} {'fb':3} {'ctx':>6} {'think':>6} "
861
+ f"{'antecedent':22} {'project':20}")
862
+ print(hdr); print("-" * len(hdr))
863
+ for e in events[: args.limit]:
864
+ print(f"{e.ts[:19]:20} {str(e.category):5} {e.original_model[:18]:18} "
865
+ f"{'yes' if e.fallback_attempted else 'no ':3} "
866
+ f"{fmt_tok(e.context_tokens):>6} {fmt_tok(e.thinking_tokens):>6} "
867
+ f"{e.antecedent[:22]:22} {e.project[:20]:20}")
868
+ if len(events) > args.limit:
869
+ print(f"... {len(events)-args.limit} more (--limit)")
870
+ if args.json:
871
+ os.makedirs(REPORT_DIR, exist_ok=True)
872
+ out = os.path.join(REPORT_DIR, "refusals.json")
873
+ payload = scan_payload(events, verbatim=args.verbatim)
874
+ fd = os.open(out, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
875
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
876
+ json.dump(payload, fh, indent=2)
877
+ os.chmod(out, 0o600) # O_CREAT's mode applies only when the file is new
878
+ print(f"\nwrote {out} ({len(payload)} events, mode 0600)")
879
+ print(" !! includes verbatim refused text (--verbatim)." if args.verbatim
880
+ else " refused text identified by sha256 digest, not included.")
881
+ return 0
882
+
883
+
884
+ def _rate_table(title, keyfn, turns, min_n=1):
885
+ tot = collections.Counter(); ref = collections.Counter()
886
+ for t in turns:
887
+ if t.synthetic or t.stop_reason is None:
888
+ continue
889
+ k = keyfn(t)
890
+ tot[k] += 1
891
+ if t.stop_reason == "refusal":
892
+ ref[k] += 1
893
+ rows = [(k, ref[k], tot[k], 100.0 * ref[k] / tot[k]) for k in tot if tot[k] >= min_n]
894
+ rows.sort(key=lambda r: -r[3])
895
+ print(f"\n{title} (buckets with n>={min_n})")
896
+ print(f" {'bucket':28} {'refused':>8} {'turns':>8} {'rate':>8}")
897
+ for k, r, n, pct in rows:
898
+ print(f" {str(k)[:28]:28} {r:>8} {n:>8} {pct:>7.2f}%")
899
+ return rows
900
+
901
+
902
+ # ---------------------------------------------------------------- confounds
903
+ # Every bug in this tool's documented list was a confident headline that turned out
904
+ # to be an artefact of how the number was computed. A marginal rate is the next one
905
+ # in that family: each table above pools projects, models and eras, so it can report
906
+ # an ordering that no controlled comparison supports. These helpers compute the
907
+ # controlled version beside the marginal one, so the gap is visible rather than
908
+ # argued about.
909
+
910
+ def _independent(answered):
911
+ """Turns whose in-session predecessor did not refuse.
912
+
913
+ Declines cascade hard (see the stickiness section), so a turn taken straight after
914
+ one is not an independent observation of the classifier -- it mostly measures the
915
+ cascade. Prospective risk, the kind you can act on before anything has gone wrong,
916
+ is the rate over independent turns only.
917
+ """
918
+ by_sess = collections.defaultdict(list)
919
+ for t in answered:
920
+ by_sess[t.thread or t.session].append(t)
921
+ keep = []
922
+ for v in by_sess.values():
923
+ v.sort(key=lambda t: t.ts)
924
+ prev_ref = False
925
+ for t in v:
926
+ if not prev_ref:
927
+ keep.append(t)
928
+ prev_ref = t.stop_reason == "refusal"
929
+ return keep
930
+
931
+
932
+ def _rate(turns) -> tuple[int, int]:
933
+ return sum(1 for t in turns if t.stop_reason == "refusal"), len(turns)
934
+
935
+
936
+ def _pair_str(rn: tuple[int, int], w: int = 11) -> str:
937
+ """`refused/total` and its rate, as two fixed-width fields so columns line up."""
938
+ r, n = rn
939
+ return f"{f'{r}/{n}':>{w}}{100.0*r/max(1,n):>7.2f}%"
940
+
941
+
942
+ def _ratio(a: tuple[int, int], b: tuple[int, int]) -> float | None:
943
+ """Rate ratio a:b, or None when b's rate is zero (a ratio would be meaningless)."""
944
+ ra, rb = a[0] / max(1, a[1]), b[0] / max(1, b[1])
945
+ return ra / rb if rb else None
946
+
947
+
948
+ @functools.lru_cache(maxsize=None)
949
+ def _ts(s: str | None) -> datetime:
950
+ """Parse a transcript timestamp for ordering; unparseable sorts first, never raises.
951
+
952
+ Claude Code writes `...T16:10:05.867Z`. Comparing those as strings breaks the moment
953
+ one lacks milliseconds (`.` sorts before `Z`), so anything that orders events against
954
+ turns goes through here.
955
+ """
956
+ try:
957
+ d = datetime.fromisoformat(str(s).replace("Z", "+00:00"))
958
+ except (TypeError, ValueError):
959
+ return datetime.min.replace(tzinfo=timezone.utc)
960
+ return d if d.tzinfo else d.replace(tzinfo=timezone.utc)
961
+
962
+
963
+ def _poisson_ci(k: int, expo: float) -> tuple[float, float]:
964
+ """Exact (Garwood) 95% interval on a Poisson rate k/expo, by bisection, stdlib only."""
965
+ if expo <= 0:
966
+ return 0.0, float("inf")
967
+
968
+ def cdf(x: int, lam: float) -> float:
969
+ if lam <= 0:
970
+ return 1.0
971
+ return sum(math.exp(-lam + i * math.log(lam) - math.lgamma(i + 1)) for i in range(x + 1))
972
+
973
+ def solve(pred) -> float:
974
+ lo, hi = 0.0, 10.0 * (k + 5)
975
+ for _ in range(100):
976
+ mid = (lo + hi) / 2
977
+ lo, hi = (mid, hi) if pred(mid) else (lo, mid)
978
+ return lo
979
+
980
+ lo = 0.0 if k == 0 else solve(lambda lam: 1.0 - cdf(k - 1, lam) < 0.025)
981
+ hi = solve(lambda lam: cdf(k, lam) > 0.025)
982
+ return lo / expo, hi / expo
983
+
984
+
985
+ def _first_decline(answered, events, project: str | None = None) -> list[list]:
986
+ """Hazard of a session's FIRST decline per request before it, by model.
987
+
988
+ Why not a turn-level by-model rate (bug 10): Claude Code's refusal fallback retries a
989
+ declined request on another model and LATCHES the session there -- system subtype
990
+ `model_refusal_fallback`, scope "session" -- until /clear or /model, and retracts the
991
+ declined request's own assistant record. So any turn-level comparison, marginal or
992
+ "inside the sessions that ran both models", sets one model's pre-decline turns against
993
+ the other's post-decline turns, where the cascade alone re-refuses most of the time.
994
+ Before a session's first decline neither has started, so that is the only place two
995
+ models can be compared. Each pre-decline request counts for its own model; the first
996
+ decline counts for the model that declined (`originalModel`), retracted or not.
997
+ Main loop only: subagents choose their own model.
998
+
999
+ Rows: [model, first_declines, requests, ci_lo, ci_hi,
1000
+ sessions_started, sessions_declined, declined_by_request_3, top_session_share]
1001
+ The last column is the largest share of the model's requests that one session supplied:
1002
+ on a few dozen sessions, one long one can decide the rate, and that should be visible.
1003
+ """
1004
+ by_s = collections.defaultdict(list)
1005
+ for t in answered:
1006
+ if not t.sidechain and t.stop_reason is not None and (project is None or t.project == project):
1007
+ by_s[t.session].append(t)
1008
+ first: dict = {}
1009
+ for e in events:
1010
+ if e.sidechain or (project is not None and e.project != project):
1011
+ continue
1012
+ if e.session not in first or _ts(e.ts) < _ts(first[e.session].ts):
1013
+ first[e.session] = e
1014
+ expo, dec = collections.Counter(), collections.Counter()
1015
+ started, sdec, early = collections.Counter(), collections.Counter(), collections.Counter()
1016
+ per_sess = collections.defaultdict(collections.Counter)
1017
+ for s in set(by_s) | set(first):
1018
+ v = sorted(by_s.get(s, []), key=lambda t: _ts(t.ts))
1019
+ fe = first.get(s)
1020
+ # The clean stretch ends at whichever comes first: the first warning record, or a
1021
+ # refused turn whose warning record is missing or not written yet. A fallback's own
1022
+ # refused turn is retracted, so for those the warning record is what remains.
1023
+ r0 = next((t for t in v if t.stop_reason == "refusal"), None)
1024
+ ends = ([(_ts(fe.ts), fe.original_model)] if fe is not None else []) + \
1025
+ ([(_ts(r0.ts), r0.model)] if r0 is not None else [])
1026
+ cut, culprit = min(ends, key=lambda x: x[0]) if ends else (None, None)
1027
+ pre = [t for t in v if cut is None or (_ts(t.ts) < cut and t.stop_reason != "refusal")]
1028
+ start = (pre[0].model if pre else culprit) or "?"
1029
+ for t in pre:
1030
+ expo[t.model or "?"] += 1
1031
+ per_sess[t.model or "?"][s] += 1
1032
+ started[start] += 1
1033
+ if cut is not None:
1034
+ m = culprit or start
1035
+ expo[m] += 1 # the declined request itself
1036
+ per_sess[m][s] += 1
1037
+ dec[m] += 1
1038
+ sdec[start] += 1
1039
+ early[start] += len(pre) <= 2
1040
+ rows = []
1041
+ for m in sorted(expo, key=lambda m: (-expo[m], m)):
1042
+ lo, hi = _poisson_ci(dec[m], expo[m])
1043
+ top = max(per_sess[m].values()) / expo[m] if per_sess[m] else 0.0
1044
+ rows.append([m, dec[m], expo[m], lo, hi, started[m], sdec[m], early[m], top])
1045
+ return rows
1046
+
1047
+
1048
+ def _fallback_outcomes(answered, events) -> dict:
1049
+ """What the harness refusal fallback did: the retried request, then the latched rest.
1050
+
1051
+ One entry per session, its first fallback: the latch is per session, so counting a
1052
+ second fallback in the same session would count the same later turns twice.
1053
+ """
1054
+ by_s = collections.defaultdict(list)
1055
+ for t in answered:
1056
+ if not t.sidechain and t.stop_reason is not None:
1057
+ by_s[t.session].append(t)
1058
+ firsts: dict = {}
1059
+ for e in events:
1060
+ if e.fallback_attempted and not e.sidechain:
1061
+ if e.session not in firsts or _ts(e.ts) < _ts(firsts[e.session].ts):
1062
+ firsts[e.session] = e
1063
+ retry, models = collections.Counter(), collections.Counter()
1064
+ latched = [0, 0]
1065
+ for s, e in firsts.items():
1066
+ after = sorted((t for t in by_s.get(s, []) if _ts(t.ts) > _ts(e.ts)),
1067
+ key=lambda t: _ts(t.ts))
1068
+ retry[after[0].stop_reason if after else "(none)"] += 1
1069
+ for t in after[1:]:
1070
+ latched[1] += 1
1071
+ latched[0] += t.stop_reason == "refusal"
1072
+ models[t.model or "?"] += 1
1073
+ return {"sessions": len(firsts), "retry": dict(retry), "latched": latched,
1074
+ "latched_models": dict(models)}
1075
+
1076
+
1077
+ # ---------------------------------------------------------------- memory hygiene
1078
+ _QUOTED = re.compile(r'"([^"]{8,20000})"|`([^`\n]{8,20000})`|```[^\n]*\n(.*?)```', re.S)
1079
+ _LINE = re.compile(r"^[ \t>*-]*(.+?)[ \t]*$", re.M)
1080
+ _PARA = re.compile(r"(?:^[^\n]*\S[^\n]*(?:\n|$)){2,}", re.M)
1081
+ _MARK = re.compile(r"^[ \t]*(?:>[ \t]?|[-*][ \t]+)", re.M)
1082
+
1083
+
1084
+ def memory_files(cwds) -> list[str]:
1085
+ """Every file Claude Code can load into a session as memory or instructions:
1086
+ ~/.claude/CLAUDE.md, each project's CLAUDE.md / CLAUDE.local.md / .claude/CLAUDE.md
1087
+ from its cwd up to the root, and every auto-memory file under TRANSCRIPT_ROOT."""
1088
+ out = {os.path.join(CLAUDE_HOME, "CLAUDE.md")}
1089
+ for c in cwds:
1090
+ d = os.path.abspath(c)
1091
+ while True:
1092
+ for n in ("CLAUDE.md", "CLAUDE.local.md", os.path.join(".claude", "CLAUDE.md")):
1093
+ out.add(os.path.join(d, n))
1094
+ parent = os.path.dirname(d)
1095
+ if parent == d:
1096
+ break
1097
+ d = parent
1098
+ out.update(glob.glob(os.path.join(TRANSCRIPT_ROOT, "*", "memory", "*.md")))
1099
+ return sorted(p for p in out if os.path.isfile(p))
1100
+
1101
+
1102
+ def _leak_spans(text: str, refused: set[str]) -> list[tuple[int, int, str, int]]:
1103
+ """(start, end, sha, chars) for each non-overlapping span of `text` that is a refused
1104
+ message, verbatim or with its whitespace re-flowed: a quoted, backticked or fenced
1105
+ span, a whole line, or a multi-line paragraph with its blockquote / list markers
1106
+ stripped. `refused` holds both digests per message (raw and whitespace-normalised),
1107
+ so a message saved with a trailing space, flattened onto one line, or kept as a
1108
+ blockquote still matches. Control tokens and spans of 20 characters or fewer are
1109
+ skipped -- they carry no content."""
1110
+ def dig(s):
1111
+ c = " ".join(s.split())
1112
+ if len(c) <= 20 or is_control(c):
1113
+ return None, 0
1114
+ for cand in (s.strip(), c):
1115
+ d = fingerprint(cand)[0]
1116
+ if d in refused:
1117
+ return d, len(c)
1118
+ return None, 0
1119
+ spans = []
1120
+ for m in _QUOTED.finditer(text):
1121
+ g = next(i for i in (1, 2, 3) if m.group(i) is not None)
1122
+ d, n = dig(m.group(g))
1123
+ if d:
1124
+ spans.append((m.start(), m.end(), d, n))
1125
+ for m in _LINE.finditer(text):
1126
+ d, n = dig(m.group(1))
1127
+ if d:
1128
+ spans.append((m.start(1), m.end(1), d, n))
1129
+ for m in _PARA.finditer(text):
1130
+ block = m.group(0).rstrip("\n")
1131
+ d, n = dig(_MARK.sub("", block))
1132
+ if d:
1133
+ spans.append((m.start(), m.start() + len(block), d, n))
1134
+ keep, end = [], -1
1135
+ for a, b, d, n in sorted(spans, key=lambda x: (x[0], -(x[1] - x[0]))):
1136
+ if a >= end:
1137
+ keep.append((a, b, d, n))
1138
+ end = b
1139
+ return keep
1140
+
1141
+
1142
+ def memory_leaks(files, refused: set[str]) -> list[tuple]:
1143
+ """Spans of `files` that are, verbatim, a refused message.
1144
+
1145
+ Identify, don't reproduce, applied to what a session loads: a refused message stored
1146
+ in memory is read back into every session that loads it. Compared by digest only, so
1147
+ nothing is printed. Returns (path, line, sha, chars, start, end).
1148
+ """
1149
+ out = []
1150
+ for f in files:
1151
+ try:
1152
+ with open(f, encoding="utf-8", errors="replace") as fh:
1153
+ t = fh.read()
1154
+ except OSError:
1155
+ continue
1156
+ out.extend((f, t.count("\n", 0, a) + 1, d, n, a, b) for a, b, d, n in _leak_spans(t, refused))
1157
+ return out
1158
+
1159
+
1160
+ def _excision_outcomes(answered, events) -> dict:
1161
+ """What happened after each clean copy `excise` wrote was resumed -- measured, because
1162
+ whether removing a decline's debris prevents the next one is an open question: the
1163
+ cascade could be the debris, or the material that is still there."""
1164
+ from refusectomy import excise
1165
+ led = excise.ledger()
1166
+ if not led:
1167
+ return {}
1168
+ print("\n" + "=" * 74)
1169
+ print("EXCISION OUTCOMES -- clean copies of declined sessions, after resume")
1170
+ print("=" * 74)
1171
+ first_ev = {}
1172
+ for e in events:
1173
+ if not e.sidechain and (e.session not in first_ev or _ts(e.ts) < _ts(first_ev[e.session])):
1174
+ first_ev[e.session] = e.ts
1175
+ resumed = declined = early = expo = 0
1176
+ for entry in led:
1177
+ fs, t0 = entry.get("fork_session"), _ts(entry.get("ts"))
1178
+ after = sorted((t for t in answered if t.session == fs and not t.sidechain and _ts(t.ts) > t0),
1179
+ key=lambda t: _ts(t.ts))
1180
+ if not after:
1181
+ continue
1182
+ resumed += 1
1183
+ cut = next((i for i, t in enumerate(after) if t.stop_reason == "refusal"), None)
1184
+ if fs in first_ev and _ts(first_ev[fs]) > t0:
1185
+ idx = sum(1 for t in after if _ts(t.ts) < _ts(first_ev[fs]))
1186
+ cut = idx if cut is None else min(cut, idx)
1187
+ expo += len(after) if cut is None else cut + 1
1188
+ if cut is not None:
1189
+ declined += 1
1190
+ early += cut < 3
1191
+ lo, hi = _poisson_ci(declined, expo) if expo else (0.0, 0.0)
1192
+ print(f"clean copies written: {len(led)}; resumed: {resumed}")
1193
+ if resumed:
1194
+ print(f" declined again: {declined}/{resumed} (within 3 requests: {early}); first declines"
1195
+ f" per 100 requests after resume: {100 * declined / max(1, expo):.2f}"
1196
+ f" ({100 * lo:.2f}-{100 * hi:.2f})")
1197
+ print(" compare with P(next request also declines) below and with section 3's fresh-"
1198
+ "session rate: a copy that\n declines like the cascade means the debris was not "
1199
+ "the cause; one that declines like a fresh session means it was.")
1200
+ else:
1201
+ print(" none resumed yet -- nothing to measure.")
1202
+ return {"written": len(led), "resumed": resumed, "declined_again": declined,
1203
+ "declined_within_3": early, "requests_after_resume": expo}
1204
+
1205
+
1206
+ def _print_confounds(answered, rates, ctx_bucket, events=()) -> dict:
1207
+ """Print the three controls, each beside the marginal figure it corrects."""
1208
+ print("\n" + "=" * 74)
1209
+ print("CONFOUNDS — a marginal rate is not an effect")
1210
+ print("=" * 74)
1211
+ print("Every table above pools projects, models and eras. Four controls, in order of")
1212
+ print("how much they move the advice, each printed beside the marginal figure it")
1213
+ print("corrects. Where a control does not change the answer, that is the finding.")
1214
+ out: dict = {}
1215
+ glob = _rate(answered)
1216
+
1217
+ # 1. composition
1218
+ projrows = [r for r in (rates.get("project") or []) if r[2] >= 100]
1219
+ if len(projrows) >= 2:
1220
+ hi = max(projrows, key=lambda r: r[3])
1221
+ nonzero = [r for r in projrows if r[3] > 0]
1222
+ lo = min(nonzero, key=lambda r: r[3]) if nonzero else None
1223
+ quiet = [r for r in projrows if r[1] == 0]
1224
+ pooled_pct = 100.0 * glob[0] / max(1, glob[1])
1225
+ print("\n1. composition — the pooled rate is a property of the mix")
1226
+ print(f" heaviest project {str(hi[0])[:24]:24}{_pair_str((hi[1], hi[2]))}")
1227
+ if lo is not None:
1228
+ print(f" lightest non-zero {str(lo[0])[:24]:24}{_pair_str((lo[1], lo[2]))}")
1229
+ print(f" pooled {'all projects':24}{_pair_str(glob)}")
1230
+ print(f" -> the heaviest project runs {hi[3]/max(pooled_pct, 1e-9):.0f}x the pooled "
1231
+ f"rate, and {len(quiet)} of {len(projrows)} projects")
1232
+ print(f" never refuse at all, so nothing experiences {pooled_pct:.2f}%. It moves")
1233
+ print(f" when the mix of work moves. Quote a project rate, not this one.")
1234
+ out["composition"] = {"high": list(hi), "low": list(lo) if lo else None,
1235
+ "pooled": list(glob), "projects": len(projrows),
1236
+ "projects_at_zero": len(quiet)}
1237
+
1238
+ # 2. cascade
1239
+ ind = _independent(answered)
1240
+ ri = _rate(ind)
1241
+ print("\n2. cascade — a turn after a decline is not an independent observation")
1242
+ print(f" {'all refused requests':<43}{_pair_str(glob)}")
1243
+ print(f" {'independent only (predecessor ok)':<43}{_pair_str(ri)}")
1244
+ print(f" {'cascade echoes dropped':<43}{glob[0]-ri[0]:>11}"
1245
+ f" ({100.0*(glob[0]-ri[0])/max(1,glob[0]):.0f}% of all refused)")
1246
+ print(" -> prospective risk is the independent rate. The cascade is a consequence")
1247
+ print(" of the first decline, which is what playbook rule 1 acts on.")
1248
+ out["independent"] = list(ri)
1249
+
1250
+ # Needed by section 4 whether or not section 3 prints. It used to be defined only
1251
+ # inside section 3, so a corpus where no session ran two models hit a NameError.
1252
+ projrefs = collections.Counter(t.project for t in answered
1253
+ if t.stop_reason == "refusal")
1254
+
1255
+ # 3. model -- compared only before each session's first decline (bug 10)
1256
+ sess_dec = collections.Counter(p_ for p_, _s in
1257
+ {(e.project, e.session) for e in events if not e.sidechain})
1258
+ hot = sess_dec.most_common(1)[0][0] if sess_dec else None
1259
+ scopes = {"all projects": _first_decline(answered, events)}
1260
+ if hot:
1261
+ scopes[hot] = _first_decline(answered, events, hot)
1262
+ shown = {k: [r for r in v if r[2] >= 50] for k, v in scopes.items()}
1263
+ key = hot if hot and len(shown.get(hot) or []) >= 2 else "all projects"
1264
+ top = (shown.get(key) or [])[:2]
1265
+ verdict = None
1266
+ if len(top) == 2:
1267
+ (ma, da, na, la, ha, *_), (mb, db, nb, lb, hb, *_) = top
1268
+ overlap = not (ha < lb or hb < la)
1269
+ point = ma if da / na < db / nb else mb if db / nb < da / na else None
1270
+ verdict = {"scope": key, "models": [ma, mb], "overlap": overlap,
1271
+ "lower": None if overlap else point, "point_lower": point}
1272
+ fo = _fallback_outcomes(answered, events)
1273
+ if any(shown.values()):
1274
+ print("\n3. model — compared only before each session's first decline")
1275
+ print(" Claude Code retries a declined request on another model and keeps the")
1276
+ print(" session there until /clear or /model, retracting the declined record, so")
1277
+ print(" every turn-level by-model rate sets one model's pre-decline turns against")
1278
+ print(" another's post-decline turns. Before the first decline neither has begun.")
1279
+ print(f" {'':<22}{'first declines':>16}{'per 100 req (95% CI)':>24}"
1280
+ f"{'sessions':>10}{'declined':>9}{'by req 3':>9}")
1281
+ for scope, rows in shown.items():
1282
+ if rows:
1283
+ print(f" {scope[:60]}")
1284
+ for m, d, n, lo, hi, ss, sd, ea, *rest in rows:
1285
+ ci = f"{100 * d / n:.2f} ({100 * lo:.2f}-{100 * hi:.2f})"
1286
+ print(f" {m[:20]:<20}{f'{d}/{n}':>16}{ci:>24}{ss:>10}{sd:>9}{ea:>9}")
1287
+ if rest and rest[0] >= 0.4:
1288
+ print(f" one session is {100 * rest[0]:.0f}% of these requests -- "
1289
+ f"the rate rests on it")
1290
+ if verdict and verdict["overlap"]:
1291
+ print(f" -> inside {key} the intervals overlap: no evidence that switching the")
1292
+ print(" default model helps where the declines are."
1293
+ + (f" The point estimate is lower for" if verdict.get("point_lower") else ""))
1294
+ if verdict.get("point_lower"):
1295
+ print(f" {verdict['point_lower']}; read the concentration notes before leaning on it.")
1296
+ elif verdict:
1297
+ print(f" -> inside {key}, {verdict['lower']} is lower with non-overlapping")
1298
+ print(" intervals. The models also ran in different periods on different")
1299
+ print(" work, so treat it as a lead to check, not a result.")
1300
+ if fo["sessions"]:
1301
+ done = sum(v for k, v in fo["retry"].items() if k not in ("refusal", "(none)"))
1302
+ lr, ln = fo["latched"]
1303
+ print(f" fallback: {fo['sessions']} sessions fell back; the retry completed "
1304
+ f"{done}, declined {fo['retry'].get('refusal', 0)}. The latched rest of")
1305
+ print(f" those sessions refused {lr}/{ln}: finish the rescued step, then")
1306
+ print(" /clear or /model to release the latch.")
1307
+ out["model_hazard"] = {
1308
+ "method": "first decline per request before it; decline -> originalModel; main loop",
1309
+ "hot_project": hot, "scopes": scopes, "verdict": verdict, "fallback": fo}
1310
+
1311
+ # 5. survivorship — the control the context-size claim actually needed.
1312
+ # A session that declines early tends to be abandoned, so it never contributes turns
1313
+ # at 300k; a session that never declines grows long and fills the upper bands by
1314
+ # itself. That selection alone produces a rate that falls as context grows, with no
1315
+ # causal link at all. Restricting to sessions that REACHED the top band makes every
1316
+ # band come from the same sessions and removes it.
1317
+ by_sess_all = collections.defaultdict(list)
1318
+ for t in answered:
1319
+ if t.has_usage:
1320
+ by_sess_all[t.thread or t.session].append(t)
1321
+ if by_sess_all:
1322
+ TOP = 250_000
1323
+ survivors = {s for s, v in by_sess_all.items()
1324
+ if max(t.context_tokens for t in v) >= TOP}
1325
+ short = set(by_sess_all) - survivors
1326
+
1327
+ def _bands(sessions):
1328
+ rows = [t for s in sessions for t in _independent(sorted(
1329
+ by_sess_all[s], key=lambda t: t.ts))]
1330
+ agg = collections.defaultdict(lambda: [0, 0])
1331
+ for t in rows:
1332
+ agg[ctx_bucket(t)][1] += 1
1333
+ if t.stop_reason == "refusal":
1334
+ agg[ctx_bucket(t)][0] += 1
1335
+ return {k: v for k, v in agg.items() if v[1] >= 40}, len(rows)
1336
+
1337
+ surv_b, surv_n = _bands(survivors)
1338
+ short_b, short_n = _bands(short)
1339
+ if len(surv_b) >= 3:
1340
+ print("\n5. survivorship — a session that declines early never reaches 300k")
1341
+ keys = sorted(set(surv_b) | set(short_b))
1342
+ print(f" {'band':<14}{'reached >=250k':>18}{'never did':>18}")
1343
+ for k in keys:
1344
+ a = surv_b.get(k)
1345
+ b = short_b.get(k)
1346
+ print(f" {k:<14}{(_pair_str(tuple(a)) if a else '—'):>18}"
1347
+ f"{(_pair_str(tuple(b)) if b else '—'):>18}")
1348
+ sv = [100.0 * v[0] / v[1] for v in surv_b.values()]
1349
+ sh = [100.0 * v[0] / v[1] for v in short_b.values()]
1350
+ print(f" -> inside the survivors the bands are flat "
1351
+ f"({min(sv):.2f}%-{max(sv):.2f}%), so the fall across the marginal table")
1352
+ print(f" is mostly selection, not context size.", end="")
1353
+ if sh:
1354
+ print(f" Sessions that never passed 250k run"
1355
+ f" {sum(sh)/len(sh):.1f}% at every size.")
1356
+ else:
1357
+ print()
1358
+ dcl = {t.session for t in answered if t.stop_reason == "refusal"}
1359
+ print(f" {len(dcl & survivors)}/{len(survivors)} long sessions ever "
1360
+ f"declined, against {len(dcl & short)}/{len(short)} short ones: the"
1361
+ f" variance is")
1362
+ print(f" between sessions, not along the context axis within one.")
1363
+ out["survivorship"] = {
1364
+ "threshold": TOP,
1365
+ "survivors": {"sessions": len(survivors), "turns": surv_n,
1366
+ "bands": {k: list(v) for k, v in surv_b.items()},
1367
+ "declined": len(dcl & survivors)},
1368
+ "short": {"sessions": len(short), "turns": short_n,
1369
+ "bands": {k: list(v) for k, v in short_b.items()},
1370
+ "declined": len(dcl & short)},
1371
+ }
1372
+
1373
+ # 4. stratification — does a marginal ordering survive inside one project?
1374
+ if projrefs:
1375
+ proj = projrefs.most_common(1)[0][0]
1376
+ inp = [t for t in answered if t.project == proj]
1377
+ marg = [(str(r[0]), r[3]) for r in (rates.get("context") or [])]
1378
+ strat = []
1379
+ for name in sorted({ctx_bucket(t) for t in inp}):
1380
+ s = [t for t in inp if ctx_bucket(t) == name]
1381
+ if len(s) >= 30:
1382
+ r, n = _rate(s)
1383
+ strat.append((name, 100.0 * r / n, r, n))
1384
+ if len(strat) >= 3 and len(marg) >= 3:
1385
+ print(f"\n4. stratification — context-size ordering, re-checked inside {proj}")
1386
+ for name, pct, r, n in strat:
1387
+ print(f" {name:<20}{_pair_str((r, n))}")
1388
+ # Pairwise concordance, not strict rank equality: with buckets this small
1389
+ # one bucket swapping rank is noise, and a binary verdict on it would
1390
+ # overclaim in both directions.
1391
+ mp = {k: v for k, v in marg}
1392
+ keys = [k for k, _, _, _ in strat if k in mp]
1393
+ agree = disagree = 0
1394
+ moved = []
1395
+ for i, x in enumerate(keys):
1396
+ for y in keys[i+1:]:
1397
+ sx = next(p for k, p, _, _ in strat if k == x)
1398
+ sy = next(p for k, p, _, _ in strat if k == y)
1399
+ if (mp[x] > mp[y]) == (sx > sy):
1400
+ agree += 1
1401
+ else:
1402
+ disagree += 1
1403
+ moved += [x, y]
1404
+ tot = agree + disagree
1405
+ peak_m = max(keys, key=lambda k: mp[k])
1406
+ peak_s = max(strat, key=lambda r: r[1])[0]
1407
+ print(f" -> {agree}/{tot} pairwise orderings agree with the marginal table; "
1408
+ f"peak bucket")
1409
+ print(f" {'matches' if peak_m == peak_s else 'moves'} "
1410
+ f"({peak_m} marginal, {peak_s} stratified).")
1411
+ if disagree:
1412
+ worst = collections.Counter(moved).most_common(1)[0][0]
1413
+ print(f" {worst} is the bucket that moves rank — small n, treat its")
1414
+ print(f" marginal position as noise, not as a finding.")
1415
+ if agree and not disagree:
1416
+ print(f" Nothing here is explained by project mix.")
1417
+ out["stratified_context"] = {
1418
+ "project": proj, "rows": [list(x) for x in strat],
1419
+ "pairwise_agree": [agree, tot],
1420
+ "peak_marginal": peak_m, "peak_stratified": peak_s}
1421
+ return out
1422
+
1423
+
1424
+ def cmd_profile(args):
1425
+ events, turnmap, files = load_events(args.cwd)
1426
+ turns = list(turnmap.values())
1427
+ answered = [t for t in turns if not t.synthetic and t.stop_reason is not None]
1428
+ ref_turns = [t for t in answered if t.stop_reason == "refusal"]
1429
+
1430
+ print("=" * 74)
1431
+ print("REFUSAL PROFILE")
1432
+ print("=" * 74)
1433
+ print(f"transcripts : {len(files)}")
1434
+ print(f"refusal events (authoritative) : {len(events)}")
1435
+ print(f"answered API requests (deduped) : {len(answered)}")
1436
+ print(f"of those, refused : {len(ref_turns)} "
1437
+ f"({100.0*len(ref_turns)/max(1,len(answered)):.2f}%)")
1438
+
1439
+ cats = collections.Counter(str(e.category) for e in events)
1440
+ print("\ncategories:")
1441
+ for k, v in cats.most_common():
1442
+ cov = FALLBACK_COVERS.get(None if k == "None" else k)
1443
+ tag = {True: "server-side fallback retries this",
1444
+ False: "NOT retried by server-side fallback",
1445
+ None: "no documented coverage"}[cov]
1446
+ print(f" {k:22} {v:>5} {tag}")
1447
+ fb = collections.Counter("attempted" if e.fallback_attempted else "none"
1448
+ for e in events)
1449
+ print(f"\nfallback actually attempted by the harness: "
1450
+ f"{fb.get('attempted',0)} of {len(events)}")
1451
+ print(f"explanation text supplied by the API : "
1452
+ f"{len([e for e in events if e.explanation])} of {len(events)}")
1453
+
1454
+ print("\n" + "=" * 74)
1455
+ print("WHAT WAS REFUSED (via refusedUserMessageUuid — authoritative)")
1456
+ print("=" * 74)
1457
+ ante = collections.Counter(e.antecedent for e in events)
1458
+ for k, v in ante.most_common():
1459
+ print(f" {k:30} {v:>4} ({100.0*v/max(1,len(events)):.1f}%)")
1460
+ user_evs = [e for e in events if e.antecedent == "real user text"]
1461
+ shape_payload: dict = {}
1462
+ if user_evs:
1463
+ lens = sorted(e.antecedent_chars for e in user_evs)
1464
+ print(f"\n refused user messages: median {lens[len(lens)//2]} chars, "
1465
+ f"max {lens[-1]}")
1466
+
1467
+ # The headline of this whole corpus, so it is measured here rather than asserted
1468
+ # in prose: most refused messages are a bare press of "go". A control token carries
1469
+ # no content of its own, so for those there is no wording to fix -- the decline is
1470
+ # about the accumulated work the model was mid-way through.
1471
+ n_u = len(user_evs)
1472
+ ctl = [e for e in user_evs if is_control(e.antecedent_text)]
1473
+ buckets = [
1474
+ ("bare control token", len(ctl)),
1475
+ ("<= 15 chars", len([e for e in user_evs if e.antecedent_chars <= 15])),
1476
+ ("<= 60 chars (shown inline)",
1477
+ len([e for e in user_evs if e.antecedent_chars <= 60])),
1478
+ ("> 60 chars (withheld by default)",
1479
+ len([e for e in user_evs if e.antecedent_chars > 60])),
1480
+ ]
1481
+ print("\n shape of the refused message:")
1482
+ for label, c in buckets:
1483
+ print(f" {label:34} {c:>4} of {n_u} ({100.0*c/n_u:.0f}%)")
1484
+ shape_payload = {"refused_user_messages": n_u,
1485
+ "median_chars": lens[len(lens)//2], "max_chars": lens[-1],
1486
+ **{label: c for label, c in buckets}}
1487
+ if ctl:
1488
+ top = collections.Counter(" ".join(e.antecedent_text.split()) for e in ctl)
1489
+ print(" most common: "
1490
+ + " ".join(f"{t!r} x{c}" for t, c in top.most_common(6)))
1491
+ print(" -> naming these is the finding; they carry no content of their own.")
1492
+ shape_payload["control_tokens"] = dict(top.most_common())
1493
+ hits = collections.Counter()
1494
+ for e in user_evs:
1495
+ low = e.antecedent_text.lower()
1496
+ for m in SCOPE_MARKERS:
1497
+ if m in low:
1498
+ hits[m] += 1
1499
+ if hits:
1500
+ print(" broad-scope markers present in the refused request:")
1501
+ for m, c in hits.most_common(8):
1502
+ print(f" {m:18} {c:>4} ({100.0*c/len(user_evs):.0f}% of them)")
1503
+ any_marker = len([e for e in user_evs
1504
+ if any(m in e.antecedent_text.lower() for m in SCOPE_MARKERS)])
1505
+ print(f" -> {any_marker}/{len(user_evs)} "
1506
+ f"({100.0*any_marker/len(user_evs):.0f}%) carry at least one")
1507
+
1508
+ timing: dict = {}
1509
+ joined = [e for e in events if e.joined]
1510
+ if joined:
1511
+ pre = len([e for e in joined if not e.content_types])
1512
+ print(f"\nwhen the classifier fired (of {len(joined)} joined events):")
1513
+ print(f" before any output block : {pre}")
1514
+ print(f" after output began : {len(joined)-pre}")
1515
+ think_only = len([e for e in joined
1516
+ if e.content_types and set(e.content_types) == {"thinking"}])
1517
+ print(f" of those, thinking-only output: {think_only}")
1518
+ # No real record, only the harness's notice: nothing was persisted as a response,
1519
+ # which is what a decline before any output looks like. Counted apart, because
1520
+ # joining the notice used to file these under "after output began".
1521
+ notice = len([e for e in events if not e.joined and not e.fallback_attempted
1522
+ and e.request_id in turnmap and turnmap[e.request_id].synthetic])
1523
+ print(f" no persisted response : {notice} (only the harness notice; consistent"
1524
+ f" with a decline before output)")
1525
+ print(" caveat: this reads what Claude Code persisted, which may not distinguish a")
1526
+ print(" true pre-output block from a record written after streaming began.")
1527
+ timing.update(joined=len(joined), pre_output=pre, thinking_only=think_only,
1528
+ notice_only=notice)
1529
+ tt = sorted(e.thinking_tokens for e in joined)
1530
+ ct = sorted(e.context_tokens for e in joined if e.context_tokens)
1531
+ timing["thinking_median"] = tt[len(tt)//2]
1532
+ timing["thinking_max"] = tt[-1]
1533
+ if ct:
1534
+ timing["ctx_refused_median"] = ct[len(ct)//2]
1535
+ print(f"\n thinking tokens at refusal : median {tt[len(tt)//2]}, max {tt[-1]}")
1536
+ if ct:
1537
+ print(f" context at refusal : median {fmt_tok(ct[len(ct)//2])}, "
1538
+ f"max {fmt_tok(ct[-1])}")
1539
+ okctx = sorted(t.context_tokens for t in answered
1540
+ if t.stop_reason != "refusal" and t.has_usage and t.context_tokens)
1541
+ if okctx:
1542
+ print(f" context when NOT refused : median {fmt_tok(okctx[len(okctx)//2])}")
1543
+ timing["ctx_ok_median"] = okctx[len(okctx)//2]
1544
+
1545
+ rates: dict[str, list] = {}
1546
+ rates["model"] = _rate_table("rate by model", lambda t: t.model or "?", turns, min_n=50)
1547
+ print(" (turn-level: the refusal fallback moves a declined session onto another model,")
1548
+ print(" so this table is not a model comparison -- CONFOUNDS section 3 is)")
1549
+ rates["effort"] = _rate_table("rate by effort", lambda t: t.effort or "(unset)",
1550
+ turns, min_n=50)
1551
+
1552
+ def ctx_bucket(t):
1553
+ if not t.has_usage:
1554
+ return "(no usage)"
1555
+ c = t.context_tokens
1556
+ for lim, name in ((20_000, "a <20k"), (60_000, "b 20-60k"), (120_000, "c 60-120k"),
1557
+ (250_000, "d 120-250k"), (500_000, "e 250-500k")):
1558
+ if c < lim:
1559
+ return name
1560
+ return "f >500k"
1561
+ rates["context"] = _rate_table("rate by context size", ctx_bucket, turns, min_n=50)
1562
+ rates["project"] = _rate_table("rate by project", lambda t: t.project, turns, min_n=100)
1563
+
1564
+ confounds = _print_confounds(answered, rates, ctx_bucket, events)
1565
+
1566
+ excision = _excision_outcomes(answered, events)
1567
+
1568
+ print("\n" + "=" * 74)
1569
+ print('THE "POISONED CONTEXT" HYPOTHESIS')
1570
+ print("=" * 74)
1571
+ # Main conversation only, one sequence per thread. Subagent records carry the
1572
+ # parent's sessionId, so grouping by session interleaved them into the main loop and
1573
+ # broke "the previous turn" -- and put thousands of near-zero-rate subagent turns
1574
+ # into the baseline that guard and remedy quote.
1575
+ by_sess = collections.defaultdict(list)
1576
+ for t in answered:
1577
+ if not t.sidechain:
1578
+ by_sess[t.thread or t.session].append(t)
1579
+ for v in by_sess.values():
1580
+ v.sort(key=lambda t: _ts(t.ts))
1581
+ print("(main conversation only; each subagent is its own thread and is left out)")
1582
+ ar = arr = ao = aor = 0
1583
+ for v in by_sess.values():
1584
+ for prev, cur in zip(v, v[1:]):
1585
+ if prev.stop_reason == "refusal":
1586
+ ar += 1; arr += cur.stop_reason == "refusal"
1587
+ else:
1588
+ ao += 1; aor += cur.stop_reason == "refusal"
1589
+ print(f"P(refuse | previous turn refused) = {arr}/{ar} = {100.0*arr/max(1,ar):.1f}%")
1590
+ print(f"P(refuse | previous turn was ok) = {aor}/{ao} = {100.0*aor/max(1,ao):.1f}%")
1591
+ if ar and ao and aor:
1592
+ print(f"lift = {(arr/ar)/(aor/ao):.1f}x")
1593
+ runs = collections.Counter()
1594
+ for v in by_sess.values():
1595
+ n = 0
1596
+ for t in v:
1597
+ if t.stop_reason == "refusal":
1598
+ n += 1
1599
+ else:
1600
+ if n: runs[n] += 1
1601
+ n = 0
1602
+ if n: runs[n] += 1
1603
+ if runs:
1604
+ print(f"consecutive-refusal runs: {dict(sorted(runs.items()))}")
1605
+ print(f"longest unbroken run : {max(runs)}")
1606
+ nxt = collections.Counter()
1607
+ for v in by_sess.values():
1608
+ for i, t in enumerate(v):
1609
+ if t.stop_reason != "refusal":
1610
+ continue
1611
+ if i + 1 >= len(v):
1612
+ nxt["(no further turn)"] += 1
1613
+ else:
1614
+ nxt["refused again" if v[i+1].stop_reason == "refusal"
1615
+ else f"recovered ({v[i+1].stop_reason})"] += 1
1616
+ print("\nthe very next attempt:")
1617
+ for k, c in nxt.most_common():
1618
+ print(f" {k:24} {c}")
1619
+
1620
+ os.makedirs(REPORT_DIR, exist_ok=True)
1621
+ # A scoped run gets its own file. Writing it over profile.json made guard and remedy
1622
+ # quote one project's figures as "your corpus" (or none at all, for an empty scope).
1623
+ out = os.path.join(REPORT_DIR, "profile.json" if not args.cwd else
1624
+ f"profile-{slug_for(os.path.abspath(args.cwd))}.json")
1625
+ with open(out, "w") as fh:
1626
+ json.dump({"generated": dt.datetime.now(dt.timezone.utc)
1627
+ .strftime("%Y-%m-%dT%H:%M:%SZ"),
1628
+ "cwd_filter": args.cwd,
1629
+ "transcripts": len(files), "events": len(events),
1630
+ "answered_requests": len(answered), "refused_requests": len(ref_turns),
1631
+ "categories": dict(cats), "antecedents": dict(ante),
1632
+ "refused_shape": shape_payload,
1633
+ "fallback_attempted": fb.get("attempted", 0),
1634
+ "explanation_supplied": len([e for e in events if e.explanation]),
1635
+ "p_after_refuse": [arr, ar], "p_after_ok": [aor, ao],
1636
+ "runs": dict(runs), "next_attempt": dict(nxt),
1637
+ "rates": {k: [list(r) for r in v] for k, v in rates.items()},
1638
+ "confounds": confounds, "excision": excision,
1639
+ "timing": timing}, fh, indent=2)
1640
+ print(f"\nwrote {out}")
1641
+ return 0
1642
+
1643
+
1644
+ def _show_refused(e, inline_chars: int, show_text: bool, width: int, lines: int) -> None:
1645
+ """Report what was refused at the least disclosure that still answers the question.
1646
+
1647
+ A bare control token is named outright (it IS the finding), a short message prints
1648
+ inline, anything longer is identified by digest only. See fingerprint() for why.
1649
+ """
1650
+ txt = " ".join(e.antecedent_text.split())
1651
+ print(f"\n --- THE REFUSED MESSAGE ({e.antecedent}, {e.antecedent_chars} chars) ---")
1652
+ print(f" digest sha256:{e.antecedent_sha or '-'}")
1653
+ if e.antecedent_shape:
1654
+ print(f" shape {e.antecedent_shape}")
1655
+ if not txt:
1656
+ print(" text (empty)")
1657
+ elif is_control(txt):
1658
+ print(f" text bare control token {txt!r} -- no content of its own.")
1659
+ print(" Nothing here to reword: the decline is about the accumulated")
1660
+ print(" work the turn resumed, not about the message.")
1661
+ elif show_text or e.antecedent_chars <= inline_chars:
1662
+ for i in range(0, min(len(txt), width * lines), width):
1663
+ print(f" | {txt[i:i+width]}")
1664
+ if len(txt) > width * lines:
1665
+ print(f" | ... (+{len(txt)-width*lines} chars, --lines to see more)")
1666
+ else:
1667
+ print(f" text [withheld: {e.antecedent_chars} chars > --inline-chars {inline_chars}]")
1668
+ print(" --verbatim writes it to a file you read directly;")
1669
+ print(" add --print to send it to stdout instead.")
1670
+
1671
+
1672
+ def _write_verbatim(events, scope: str) -> str:
1673
+ """Write full refused text to a 0600 file; return the path. Never to stdout."""
1674
+ os.makedirs(REPORT_DIR, exist_ok=True)
1675
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
1676
+ safe = "".join(c if c.isalnum() or c in "-_" else "-" for c in scope)[:40] or "all"
1677
+ out = os.path.join(REPORT_DIR, f"trace-{safe}-{stamp}.txt")
1678
+ fd = os.open(out, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
1679
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
1680
+ fh.write(f"# refusectomy verbatim trace -- {stamp} -- scope: {scope}\n")
1681
+ fh.write("# Unredacted text of refused messages. Read it directly.\n\n")
1682
+ for e in events:
1683
+ fh.write("=" * 74 + "\n")
1684
+ fh.write(f"{e.ts} session {e.session} {e.original_model} cat={e.category}\n")
1685
+ fh.write(f"project {e.project} ({e.cwd})\n")
1686
+ fh.write(f"antecedent {e.antecedent} {e.antecedent_chars} chars "
1687
+ f"sha256:{e.antecedent_sha}\n")
1688
+ fh.write(f"request {e.request_id} classifier {e.classifier_req}\n\n")
1689
+ fh.write((e.antecedent_text or "(empty)") + "\n\n")
1690
+ os.chmod(out, 0o600) # O_CREAT's mode applies only when the file is new
1691
+ return out
1692
+
1693
+
1694
+ def cmd_trace(args):
1695
+ sess = {args.session} if args.session else None
1696
+ events, turns, files = load_events(args.cwd, sessions=sess)
1697
+ if args.project:
1698
+ events = [e for e in events if args.project in e.project or args.project in e.cwd]
1699
+ if not events:
1700
+ print("no refusal events in that scope.")
1701
+ return 0
1702
+ print(f"{len(events)} event(s) in scope; showing {min(args.limit, len(events))}\n")
1703
+ for e in events[: args.limit]:
1704
+ print("=" * 74)
1705
+ print(f"REFUSAL {e.ts} (UTC) session {e.session[:8]}")
1706
+ print("=" * 74)
1707
+ print(f" project {e.project} ({e.cwd})")
1708
+ print(f" model {e.original_model} effort={e.effort or '?'}")
1709
+ print(f" category {e.category} explanation={e.explanation!r}")
1710
+ print(f" fallback tried {'yes' if e.fallback_attempted else 'no'}")
1711
+ print(f" sidechain {e.sidechain}")
1712
+ if e.joined:
1713
+ print(f" context {e.context_tokens:,} tokens")
1714
+ print(f" output {e.thinking_tokens} thinking tokens, "
1715
+ f"blocks={e.content_types or '[]'}")
1716
+ print(f" classifier req {e.classifier_req}")
1717
+ else:
1718
+ print(" (no assistant record joined by requestId)")
1719
+ _show_refused(e, args.inline_chars, args.verbatim and args.print_text,
1720
+ args.width, args.lines)
1721
+ print()
1722
+ if args.verbatim and not args.print_text:
1723
+ shown = events[: args.limit]
1724
+ path = _write_verbatim(shown, args.project or args.session or "all")
1725
+ print(f"verbatim text of {len(shown)} event(s) -> {path} (mode 0600)")
1726
+ print("Read that file directly.")
1727
+ return 0
1728
+
1729
+
1730
+ def cmd_session(args):
1731
+ cwd = args.cwd or os.getcwd()
1732
+ sid = args.session
1733
+ if args.live and not sid:
1734
+ sid = current_session_id()
1735
+ exact = os.path.join(TRANSCRIPT_ROOT, slug_for(os.path.abspath(cwd)), f"{sid}.jsonl") \
1736
+ if sid else None
1737
+ if not (exact and os.path.exists(exact)):
1738
+ sid, _ = newest_session(cwd)
1739
+ if not sid:
1740
+ print("could not determine a session; pass --session <id>")
1741
+ return 1
1742
+ events, turnmap, files = load_events(cwd, sessions={sid})
1743
+ turns = [t for t in turnmap.values() if not t.synthetic and t.stop_reason is not None]
1744
+ ref_turns = sorted((t for t in turns if t.stop_reason == "refusal"), key=lambda t: t.ts)
1745
+ # The authoritative system warning can lag behind, or be absent, for a decline that
1746
+ # just happened — so never rely on it alone when watching a live session.
1747
+ ev_rids = {e.request_id for e in events if e.request_id}
1748
+ unwarned = [t for t in ref_turns if t.request_id not in ev_rids]
1749
+ print(f"session {sid}")
1750
+ print(f" cwd {cwd}")
1751
+ print(f" answered requests {len(turns)}")
1752
+ print(f" refused requests {len(ref_turns)}")
1753
+ print(f" refusal events {len(events)} (harness warning records)")
1754
+ if unwarned:
1755
+ print(f"\n !! {len(unwarned)} refused request(s) with NO warning record yet —")
1756
+ print(f" detected from assistant stop_reason directly:")
1757
+ for t in unwarned:
1758
+ print(f" {t.ts[:19]}Z {t.model} effort={t.effort or '-'} "
1759
+ f"ctx={fmt_tok(t.context_tokens)} thinking={t.thinking_tokens} tok "
1760
+ f"blocks={t.content_types or '[]'}")
1761
+ if t.classifier_req:
1762
+ print(f" classifier req {t.classifier_req}")
1763
+ if not events and not ref_turns:
1764
+ print("\n clean so far — no refusal recorded in this session.")
1765
+ if turns:
1766
+ last = max(turns, key=lambda t: t.ts)
1767
+ print(f" last request {last.ts[:19]}Z {last.model} "
1768
+ f"effort={last.effort or '-'} ctx={fmt_tok(last.context_tokens)} "
1769
+ f"stop={last.stop_reason}")
1770
+ print(f" peak context "
1771
+ f"{fmt_tok(max(t.context_tokens for t in turns))}")
1772
+ return 0
1773
+ if not events:
1774
+ return 0
1775
+ for e in events:
1776
+ print(f"\n !! {e.ts[:19]}Z category={e.category} model={e.original_model}")
1777
+ print(f" refused: {e.antecedent} ({e.antecedent_chars} chars)")
1778
+ print(f" thinking={e.thinking_tokens} tok ctx={fmt_tok(e.context_tokens)}"
1779
+ f" fallback={'yes' if e.fallback_attempted else 'no'}")
1780
+ print(f" classifier req {e.classifier_req}")
1781
+ return 0
1782
+
1783
+
1784
+ def load_profile() -> dict | None:
1785
+ """Last measured profile, or None. `remedy` renders its numbers from this file.
1786
+
1787
+ The bio playbook used to be frozen prose, and it went stale the only way that really
1788
+ matters: it kept asserting a headline (`180 of 262 refusals followed a TOOL RESULT`)
1789
+ that `audit` had already disproved, and therefore gave the opposite advice to what the
1790
+ corpus supports. Numbers in this tool are computed or they are not printed.
1791
+ """
1792
+ try:
1793
+ with open(os.path.join(REPORT_DIR, "profile.json")) as fh:
1794
+ d = json.load(fh)
1795
+ # A scoped profile is not the machine's; older versions wrote one here.
1796
+ return d if isinstance(d, dict) and d.get("events") and not d.get("cwd_filter") else None
1797
+ except (OSError, ValueError):
1798
+ return None
1799
+
1800
+
1801
+ def _pct(num, den) -> str:
1802
+ return f"{100.0*num/den:.2f}%" if den else "n/a"
1803
+
1804
+
1805
+ def _wrap(text: str, indent: int, width: int = 94) -> list[str]:
1806
+ """Wrap a computed figure list so rendered advice stays readable in a terminal."""
1807
+ pad = " " * indent
1808
+ return textwrap.wrap(text, width=width, initial_indent=pad, subsequent_indent=pad,
1809
+ break_on_hyphens=False, break_long_words=False) or [pad.rstrip()]
1810
+
1811
+
1812
+ def _rate_line(rows, n=4) -> str:
1813
+ """'name rate (n=..)' for the first n rows of a persisted rate table."""
1814
+ return ", ".join(f"{k} {pct:.2f}% (n={tot})" for k, _r, tot, pct in rows[:n]) or "n/a"
1815
+
1816
+
1817
+ def render_bio(p: dict | None) -> str:
1818
+ """The bio playbook, with every figure taken from the last `profile` run."""
1819
+ if not p:
1820
+ return ("CATEGORY: bio (\"could enable biological harm, such as dangerous lab methods\")\n\n"
1821
+ "No measured profile on this machine yet, and this playbook refuses to quote\n"
1822
+ "numbers it has not measured. Run:\n\n"
1823
+ " refusectomy audit && refusectomy profile\n\n"
1824
+ "then re-run `remedy --category bio`. The documented, corpus-independent facts:\n"
1825
+ " - server-side fallback does NOT cover bio (only cyber / frontier_llm);\n"
1826
+ " - Claude Code's own refusal fallback DOES fire on bio: it retries on another\n"
1827
+ " model and keeps the session there until /clear or /model;\n"
1828
+ " - no prompt rewording is documented to avoid Claude Opus 5.5 false positives;\n"
1829
+ " - the institutional route is Anthropic's Life Sciences Verification Program;\n"
1830
+ " - branch on stop_reason, never on stop_details (it can be null on a refusal).")
1831
+
1832
+ ev = p["events"]
1833
+ ans, ref = p.get("answered_requests", 0), p.get("refused_requests", 0)
1834
+ sh = p.get("refused_shape") or {}
1835
+ nu = sh.get("refused_user_messages", 0)
1836
+ ctl = sh.get("bare control token", 0)
1837
+ tm = p.get("timing") or {}
1838
+ rates = p.get("rates") or {}
1839
+ conf = p.get("confounds") or {}
1840
+ ar_n, ar_d = p.get("p_after_refuse", [0, 0])
1841
+ ao_n, ao_d = p.get("p_after_ok", [0, 0])
1842
+ lift = ((ar_n/ar_d)/(ao_n/ao_d)) if ar_d and ao_d and ao_n else 0.0
1843
+ runs = {int(k): v for k, v in (p.get("runs") or {}).items()}
1844
+ nxt = p.get("next_attempt") or {}
1845
+ recovered = sum(v for k, v in nxt.items() if k.startswith("recovered"))
1846
+ ctxrows = rates.get("context") or []
1847
+ worst = min(ctxrows, key=lambda r: -r[3]) if ctxrows else None
1848
+ best = min(ctxrows, key=lambda r: r[3]) if ctxrows else None
1849
+ # Ranked by refused-request COUNT: ranking by rate alone promotes a small
1850
+ # denominator (this tool's own project) above the material that actually drives it.
1851
+ projrows = sorted(rates.get("project") or [], key=lambda r: (-r[1], -r[3]))
1852
+ L = []
1853
+ A = L.append
1854
+ A('CATEGORY: bio ("could enable biological harm, such as dangerous lab methods")')
1855
+ A("")
1856
+ A(f"Measured on this machine's own corpus, {p.get('generated','(unknown date)')}"
1857
+ f" — re-run `profile` to refresh.")
1858
+ A(f" {ev} events, {p.get('transcripts','?')} transcripts, "
1859
+ f"{ref} of {ans} answered requests ({_pct(ref, ans)} pooled).")
1860
+ ind = conf.get("independent")
1861
+ if ind and ind[1]:
1862
+ A(f" Pooled across every project, so it is a property of the mix. Dropping turns")
1863
+ A(f" that merely followed a decline: {ind[0]} of {ind[1]} ({_pct(ind[0], ind[1])}) —"
1864
+ f" that is the")
1865
+ A(f" prospective rate, and the gap is the cascade below.")
1866
+ if tm.get("joined"):
1867
+ A(f" {tm['joined'] - tm.get('pre_output', 0)} of {tm['joined']} joined events fired AFTER"
1868
+ f" output began ({tm.get('thinking_only', 0)} with thinking-only output)"
1869
+ + (f"; {tm['notice_only']} more left no persisted response at all." if tm.get("notice_only")
1870
+ else "."))
1871
+ A("")
1872
+ A("What the data says the cause is NOT:")
1873
+ if nu:
1874
+ A(f" x Your wording. {nu} of {ev} declines resolve to real user text, and "
1875
+ f"{ctl} of those ({100.0*ctl/nu:.0f}%)")
1876
+ A(f" are a bare control token — a median of {sh.get('median_chars','?')} characters, "
1877
+ f"most often \"continue\".")
1878
+ A(" There is nothing in the message to rewrite. The decline is about the accumulated")
1879
+ A(" work the model was mid-way through, not the sentence that pressed go.")
1880
+ if ctxrows:
1881
+ # Ordered by bucket, not by rate: the point is the monotone trend above the peak.
1882
+ # Quoting only the extremes made the smallest bucket look safest, which inverts it.
1883
+ ordered = sorted(ctxrows, key=lambda r: r[0])
1884
+ peak = max(ordered, key=lambda r: r[3])
1885
+ A(f" x Context being too big — but not for the reason this tool used to give.")
1886
+ A(f" The marginal rate peaks at {peak[0].split(' ', 1)[-1]} "
1887
+ f"({peak[3]:.2f}%) and falls as context grows:")
1888
+ for line in _wrap(", ".join(f"{k.split(' ', 1)[-1]} {pct:.2f}%"
1889
+ for k, _r, _t, pct in ordered), 5):
1890
+ A(line)
1891
+ sv = (conf.get("survivorship") or {})
1892
+ if sv.get("survivors", {}).get("bands"):
1893
+ b = sv["survivors"]["bands"]
1894
+ pcts = [100.0 * v[0] / v[1] for v in b.values() if v[1]]
1895
+ sb = (sv.get("short") or {}).get("bands") or {}
1896
+ spc = [100.0 * v[0] / v[1] for v in sb.values() if v[1]]
1897
+ for line in _wrap(
1898
+ f"That fall is mostly survivorship: a session that declines early is "
1899
+ f"abandoned and never reaches the upper bands. Inside the "
1900
+ f"{sv['survivors']['sessions']} sessions that did reach "
1901
+ f"{sv['threshold']//1000}k, the bands are flat "
1902
+ f"({min(pcts):.2f}%-{max(pcts):.2f}%)"
1903
+ + (f", while sessions that never got there run about "
1904
+ f"{sum(spc)/len(spc):.1f}% at every size" if spc else "")
1905
+ + f". {sv['short']['declined']}/{sv['short']['sessions']} short "
1906
+ f"sessions ever declined against "
1907
+ f"{sv['survivors']['declined']}/{sv['survivors']['sessions']} long "
1908
+ f"ones, so the variance is BETWEEN sessions, not along one "
1909
+ f"session's context axis. Do not let context grow in the hope it "
1910
+ f"gets safer, and do not trim a session that is going fine.", 5):
1911
+ A(line)
1912
+ if tm.get("ctx_refused_median") and tm.get("ctx_ok_median"):
1913
+ A(f" Median context at refusal {fmt_tok(tm['ctx_refused_median'])}"
1914
+ f" vs {fmt_tok(tm['ctx_ok_median'])} when not refused.")
1915
+ if rates.get("effort"):
1916
+ for line in _wrap("x Effort. " + _rate_line(rates["effort"], 3)
1917
+ + " — no useful signal.", 2):
1918
+ A(line)
1919
+ ex = p.get("explanation_supplied")
1920
+ if ex == 0:
1921
+ A(f" x stop_details.explanation. Null on all {ev}.")
1922
+ elif ex:
1923
+ A(f" - stop_details.explanation. Supplied on {ex} of {ev}: read them with `trace`.")
1924
+ A("")
1925
+ A("What does NOT work mechanically:")
1926
+ A(' x Server-side fallback in your own API calls. `fallbacks: "default"` retries cyber')
1927
+ A(" and frontier_llm and explicitly does NOT retry bio. (Claude Code's own refusal")
1928
+ A(" fallback is a different mechanism and does fire on bio -- see 4.)")
1929
+ A(" x Rewording tricks for Claude Opus 5.5. The docs state no prompt change is documented")
1930
+ A(" to avoid its false positives, and the Fable-5.1-only tips must not be used for it.")
1931
+ A("")
1932
+ A("What actually works, strongest first:")
1933
+ A(f" 1. ABANDON THE SESSION. P(refuse | previous turn refused) = {_pct(ar_n, ar_d)}"
1934
+ f" against a {_pct(ao_n, ao_d)} baseline")
1935
+ A(f" — a {lift:.0f}x lift, with unbroken runs up to {max(runs) if runs else '?'} turns."
1936
+ f" Only {recovered} of {ar_d} attempts after a")
1937
+ A(" decline recovered. This is the highest-leverage move by a wide margin, and it is")
1938
+ A(" cheap: open a new session and carry only the excerpt the question actually needs.")
1939
+ A(" A new session (or /clear) also releases the refusal-fallback model latch (see 4).")
1940
+ A(f" 2. Do not react to the refusal notice in the same context. {ar_n} of {ref} refused")
1941
+ A(" requests landed directly after another decline, with the notice already in context:")
1942
+ A(" the model reasons about why it was refused, and that reasoning trips the same")
1943
+ A(" classifier. The loop is self-reinforcing — this is what produces the long runs.")
1944
+ if projrows:
1945
+ A(" 3. Suspect the MATERIAL, not the task. Refused requests concentrate in a few")
1946
+ A(" projects, and the ranking is by volume (rate alone favours small denominators):")
1947
+ for line in _wrap(", ".join(f"{k} {r}/{tot} ({pct:.2f}%)"
1948
+ for k, r, tot, pct in projrows[:4]), 5):
1949
+ A(line)
1950
+ zeros = [f"{r[0]} (n={r[2]})" for r in projrows if r[1] == 0][:3]
1951
+ if zeros:
1952
+ for line in _wrap("other bio projects on this machine sit at 0.00%: "
1953
+ + ", ".join(zeros) + ".", 5):
1954
+ A(line)
1955
+ A(" It is not \"bio work\" that trips it; it is specific source material. Identify")
1956
+ A(" that and you have the handle. `trace --project <name>` names them by digest.")
1957
+ mh = conf.get("model_hazard") or {}
1958
+ verdict = mh.get("verdict") or {}
1959
+ vrows = [r for r in ((mh.get("scopes") or {}).get(verdict.get("scope")) or [])
1960
+ if len(r) >= 5 and r[2] >= 50]
1961
+ if verdict and vrows:
1962
+ A(" 4. Model choice, measured only before each session's first decline: Claude Code's")
1963
+ A(" refusal fallback moves a declined session onto another model and keeps it")
1964
+ A(" there, so every turn-level by-model rate compares before with after.")
1965
+ for line in _wrap(f"Inside {verdict['scope']}, first declines per 100 requests: "
1966
+ + "; ".join(f"{r[0]} {100 * r[1] / r[2]:.2f} "
1967
+ f"({100 * r[3]:.2f}-{100 * r[4]:.2f})"
1968
+ for r in vrows[:3]) + ".", 5):
1969
+ A(line)
1970
+ if verdict.get("overlap"):
1971
+ for line in _wrap("The intervals overlap: no evidence that switching the default model "
1972
+ "helps here" + (f" (the point estimate is lower for "
1973
+ f"{verdict['point_lower']}, and on few sessions one "
1974
+ f"long one can decide it)" if verdict.get("point_lower")
1975
+ else "") + ".", 5):
1976
+ A(line)
1977
+ elif verdict.get("lower"):
1978
+ for line in _wrap(f"{verdict['lower']} is lower with non-overlapping intervals, "
1979
+ f"but the models ran in different periods on different work: "
1980
+ f"a lead to check, not a result.", 5):
1981
+ A(line)
1982
+ fo = mh.get("fallback") or {}
1983
+ if fo.get("sessions"):
1984
+ rt = fo.get("retry") or {}
1985
+ done = sum(v for k, v in rt.items() if k not in ("refusal", "(none)"))
1986
+ lr, ln = (list(fo.get("latched") or []) + [0, 0])[:2]
1987
+ for line in _wrap(
1988
+ f"The fallback helps once: it retried {fo['sessions']} declined sessions on "
1989
+ f"another model and the retry completed {done} times. The session then "
1990
+ f"stays latched ({lr}/{ln} later requests refused) until /clear or /model, "
1991
+ f"so finish the rescued step and /clear (rule 1).", 5):
1992
+ A(line)
1993
+ else:
1994
+ A(" 4. Model choice: run `profile` for it. It compares models only before each")
1995
+ A(" session's first decline, the one place the refusal fallback cannot reach.")
1996
+ A(" 5. Handle it correctly so it degrades instead of crashing: branch on stop_reason BEFORE")
1997
+ A(" reading content; treat stop_details as informational (it can be null on a refusal);")
1998
+ A(" discard partial mid-stream output rather than treating it as an answer.")
1999
+ A(" 6. Life Sciences Verification Program — the documented institutional route when the bio")
2000
+ A(" classifier blocks an organization's legitimate life-sciences work. The only fix that")
2001
+ A(" addresses the cause rather than routing around it. Apply with your institution.")
2002
+ A(" 7. Report the false positives. Every event carries a serverClassifierRequest UUID.")
2003
+ A(" `scan --json` collects them into refusals.json, digest-only — a report needs")
2004
+ A(" requestId + serverClassifierRequest + digest, never the prose.")
2005
+ A("")
2006
+ A("Keep exact computation out of the model regardless: melting temperatures, digests and")
2007
+ A("translations belong in a deterministic library such as Biopython, which sidesteps the")
2008
+ A("classifier for the part that must be exact.")
2009
+ return "\n".join(L)
2010
+
2011
+
2012
+ # "bio" is rendered from the measured profile (render_bio), not stored as prose.
2013
+ CATEGORIES = ("bio", "cyber", "reasoning_extraction", "general_harms")
2014
+
2015
+ REMEDIES = {
2016
+ "reasoning_extraction": """\
2017
+ CATEGORY: reasoning_extraction (asks the model to reproduce its internal reasoning as text)
2018
+
2019
+ This one is self-inflicted and genuinely fixable:
2020
+ 1. Find the instruction. Grep your prompts, skills, CLAUDE.md and tool descriptions for
2021
+ requests to "show your reasoning", "explain your thinking step by step", "output your
2022
+ chain of thought". Remove it.
2023
+ 2. Read reasoning the supported way: thinking: {type: "adaptive", display: "summarized"}
2024
+ and render the thinking blocks.
2025
+ 3. Asking for a short explanation of the answer, or a summary of actions taken, is fine.
2026
+ 4. Not retried by server-side fallback — fix the prompt, there is nothing to fall back to.""",
2027
+ "cyber": """\
2028
+ CATEGORY: cyber (malware/exploit development; finding vulnerabilities in source code IS allowed)
2029
+
2030
+ 1. Server-side fallback DOES cover this one: betas=["server-side-fallback-2026-07-01"]
2031
+ plus fallbacks="default" routes by category (cyber -> claude-opus-4-8).
2032
+ 2. Documented false-positive triggers (Fable 5.1): compile-check phrasing — ask "are there
2033
+ bugs in this program?" not "does this compile without errors?"; lesser-known languages —
2034
+ give the model the language's docs; tools returning base64 blobs into context — remove them.
2035
+ 3. Legitimate security work blocked at scale: Cyber Verification Program.""",
2036
+ "general_harms": """\
2037
+ CATEGORY: general_harms (another usage-policy area; benign work can trigger it)
2038
+
2039
+ 1. Not retried by server-side fallback.
2040
+ 2. No documented prompt remedy. State the legitimate purpose and context plainly, and if a
2041
+ route is persistently blocked, raise it with Anthropic citing the serverClassifierRequest id.""",
2042
+ }
2043
+
2044
+
2045
+ def cmd_remedy(args):
2046
+ cats = [args.category] if args.category else None
2047
+ if not cats:
2048
+ _, turnmap, _ = load_events(args.cwd)
2049
+ refs = real_refusals(turnmap.values())
2050
+ cats = [c for c, _ in collections.Counter(
2051
+ str(r.category) for r in refs).most_common()]
2052
+ if not cats:
2053
+ cats = ["bio"]
2054
+ print(f"(no --category given; your corpus shows: {', '.join(cats)})\n")
2055
+ prof = None
2056
+ for c in cats:
2057
+ if c == "bio":
2058
+ prof = prof if prof is not None else load_profile()
2059
+ print(render_bio(prof))
2060
+ else:
2061
+ print(REMEDIES.get(c, f"No playbook for category {c!r}. "
2062
+ f"Known: {', '.join(sorted(CATEGORIES))}"))
2063
+ print()
2064
+ print("-" * 74)
2065
+ print("""Correct handling, any category:
2066
+
2067
+ resp = client.messages.create(model="claude-opus-5-5", max_tokens=16000, messages=msgs)
2068
+ if resp.stop_reason == "refusal": # branch on stop_reason, never stop_details
2069
+ sd = resp.stop_details # informational; may be None even here
2070
+ cat = getattr(sd, "category", None)
2071
+ # discard any partial mid-stream output; do not treat it as an answer
2072
+ handle_decline(cat, getattr(sd, "recommended_model", None))
2073
+ else:
2074
+ use(resp.content)
2075
+
2076
+ Where fallback applies (cyber / frontier_llm), opt in server-side rather than hand-rolling:
2077
+
2078
+ client.messages.create(..., betas=["server-side-fallback-2026-07-01"], fallbacks="default")""")
2079
+
2080
+
2081
+ def cmd_bisect(args):
2082
+ print("bisect: replay a refused conversation prefix-by-prefix to isolate the trigger.\n")
2083
+ have = any(os.environ.get(v) for v in
2084
+ ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"))
2085
+ ant = any(os.path.exists(os.path.expanduser(p)) for p in
2086
+ ("~/.config/anthropic/", ))
2087
+ if not have and not ant:
2088
+ print("BLOCKED: no credentials on this machine.")
2089
+ print(" checked: ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, ~/.config/anthropic/")
2090
+ print(" the `ant` CLI is not installed, so there is no OAuth profile to read either.\n")
2091
+ print("To enable: export ANTHROPIC_API_KEY=... (or install the `ant` CLI, `ant auth login`)\n")
2092
+ print("Then bisect will, for a chosen refused session:")
2093
+ print(" 1. rebuild the message list up to the refused turn")
2094
+ print(" 2. binary-search over message prefixes, re-sending each to find the shortest")
2095
+ print(" prefix that still returns stop_reason == 'refusal'")
2096
+ print(" 3. narrow within that turn, block by block")
2097
+ print(" 4. report the minimal context that reproduces it, plus a control run of the")
2098
+ print(" same final question with no history\n")
2099
+ print("Cost warning: each probe is a billed request, and these contexts run to 100k-400k")
2100
+ print("tokens. A bisect over a 400k-token session is roughly log2(turns) full-price")
2101
+ print("requests. Set --max-probes and start on your smallest refused session.")
2102
+ print("\nNote: replay is diagnostic. It reports what reproduces a decline; it does not")
2103
+ print("search for phrasings that get past one.")
2104
+ return 2
2105
+ print("credentials present — implement the probe loop before running against live API.")
2106
+ print("(deliberately not auto-firing billed requests on a corpus this large)")
2107
+ return 0
2108
+
2109
+
2110
+ # ---------------------------------------------------------------- live guard
2111
+ # The corpus says the single highest-leverage move is to abandon a session once it has
2112
+ # declined once, and that reacting to the decline notice *inside that same context* is
2113
+ # what turns one decline into a run. Both facts are about the moment a decline lands,
2114
+ # which is a moment no report can reach. This is the hook that can.
2115
+ #
2116
+ # Two constraints follow from the measurements rather than from taste:
2117
+ #
2118
+ # 1. The warning goes to the human, via `systemMessage`, and NEVER to the model via
2119
+ # `hookSpecificOutput.additionalContext`. Injecting "you were just declined" into
2120
+ # the context that just produced a decline is a mechanical implementation of
2121
+ # playbook rule 2 -- the thing that produces the 19-turn runs. An audit invariant
2122
+ # holds this line, because it is the kind of helpful-looking change someone adds
2123
+ # later.
2124
+ # 2. It reports counts, models and context size. It never reports the refused text,
2125
+ # for the same reason nothing else here does: that text would land in the context
2126
+ # of whatever reads the warning.
2127
+ #
2128
+ # It also has to be cheap, because it runs at the end of every turn in every project:
2129
+ # one session's transcript through the one parser, no corpus glob.
2130
+
2131
+ GUARD_STATE = os.path.join(REPORT_DIR, "guard-state.json") # legacy shared file, read to migrate
2132
+
2133
+
2134
+ def _guard_path(sid: str) -> str:
2135
+ return os.path.join(REPORT_DIR, "guard",
2136
+ re.sub(r"[^A-Za-z0-9_.-]", "_", sid)[:200] + ".json")
2137
+
2138
+
2139
+ def _guard_load(sid: str) -> dict:
2140
+ """This session's last-seen counts; anything malformed is dropped, never raised.
2141
+
2142
+ A hook that crashes on its own state is broken for good, and silently: the hook
2143
+ wrapper swallows the error, and the save that would repair the state is never
2144
+ reached. So a bad entry costs one re-warning, not the guard. One file per session:
2145
+ concurrent Stop hooks from different sessions used to read-modify-write one shared
2146
+ file and lose each other's updates. The legacy shared file is read once, to migrate.
2147
+ """
2148
+ for path, pick in ((_guard_path(sid), lambda d: d), (GUARD_STATE, lambda d: d.get(sid))):
2149
+ try:
2150
+ with open(path) as fh:
2151
+ d = pick(json.load(fh))
2152
+ except Exception:
2153
+ continue
2154
+ if isinstance(d, dict) and all(isinstance(d.get(k, 0), int) for k in ("n", "ev")):
2155
+ return d
2156
+ return {}
2157
+
2158
+
2159
+ def _guard_store(sid: str, state: dict) -> None:
2160
+ # never let a write failure break the user's turn
2161
+ try:
2162
+ path = _guard_path(sid)
2163
+ os.makedirs(os.path.dirname(path), exist_ok=True)
2164
+ tmp = f"{path}.{os.getpid()}.tmp"
2165
+ with open(tmp, "w") as fh:
2166
+ json.dump(state, fh)
2167
+ os.replace(tmp, path)
2168
+ olds = sorted(glob.glob(os.path.join(os.path.dirname(path), "*.json")),
2169
+ key=os.path.getmtime)
2170
+ for f in olds[:-500]:
2171
+ os.remove(f)
2172
+ except Exception:
2173
+ pass
2174
+
2175
+
2176
+ def _ordinal(n: int) -> str:
2177
+ return f"{n}{'th' if 11 <= n % 100 <= 13 else {1:'st',2:'nd',3:'rd'}.get(n % 10, 'th')}"
2178
+
2179
+
2180
+ def guard_message(n_ev: int, n_req: int, cats: list[str], model: str, ctx: int,
2181
+ prof: dict | None, resumed: bool = False,
2182
+ fallback: tuple[str, str] | None = None, subagent_refusals: int = 0,
2183
+ clean_copy: str | None = None) -> str:
2184
+ """The warning text. Every statistic is read from profile.json or omitted.
2185
+
2186
+ Same rule as the playbooks: this must degrade to naming the condition rather than
2187
+ inventing a number for it, so a stale or missing profile costs you the figures and
2188
+ not the warning.
2189
+ """
2190
+ p = prof or {}
2191
+ cat = f" ({'/'.join(sorted(set(c for c in cats if c)))})" if any(cats) else ""
2192
+ # The user-visible decline count and the refused-request count are different
2193
+ # quantities -- one warning notice each versus the harness's retries inside one
2194
+ # declined turn -- and this tool's whole reconciliation section exists because
2195
+ # conflating them inflates everything. Lead with what the human actually saw, and
2196
+ # say so when the API count is higher. A decline detected from stop_reason before
2197
+ # the harness has written its warning record has no event count yet; that is the
2198
+ # case worth being early about, so it is reported as such rather than rounded off.
2199
+ n_shown = n_ev or n_req
2200
+ if resumed:
2201
+ L = [f"refusectomy: this session already carries {n_shown} decline"
2202
+ f"{'s' if n_shown != 1 else ''}{cat}."]
2203
+ else:
2204
+ L = [f"refusectomy: {_ordinal(n_shown)} decline in this session{cat}"
2205
+ + ("." if n_ev else
2206
+ " — inside a subagent, which never gets a warning record."
2207
+ if subagent_refusals and subagent_refusals >= n_req else
2208
+ " — detected from stop_reason, no warning record yet.")]
2209
+ if n_ev and n_req > n_ev:
2210
+ L.append(f" {n_req} refused API requests behind those {n_ev} notices "
2211
+ f"(harness retries inside the declined turns).")
2212
+ if subagent_refusals and n_ev:
2213
+ L.append(f" {subagent_refusals} of the refused requests came from subagents.")
2214
+
2215
+ ar, ao = p.get("p_after_refuse"), p.get("p_after_ok")
2216
+ if ar and ao and ar[1] and ao[1] and ao[0]:
2217
+ pr, po = 100.0 * ar[0] / ar[1], 100.0 * ao[0] / ao[1]
2218
+ L.append(f" P(next request also declines) = {pr:.0f}% on your corpus, against "
2219
+ f"{po:.1f}% baseline ({pr/po:.0f}x).")
2220
+ runs = p.get("runs") or {}
2221
+ longest = max((int(k) for k in runs), default=0)
2222
+ if resumed:
2223
+ L.append(" You are resuming a context that has already been declined in, which is")
2224
+ L.append(" the same move as rephrasing in place. Start a new session and carry only")
2225
+ L.append(" the excerpt the next question needs.")
2226
+ elif n_shown >= 2:
2227
+ L.append(f" You are in a run. Longest observed here: {longest or '?'} turns. "
2228
+ f"Rephrasing in place is what extends it.")
2229
+ else:
2230
+ L.append(" ABANDON THIS SESSION rather than rephrasing in it. Open a new one and")
2231
+ L.append(" carry only the excerpt the next question actually needs.")
2232
+
2233
+ # Named, not quantified: the paired "Nx less" this line used to print was the
2234
+ # fallback measuring itself (bug 10). What is actionable is the latch.
2235
+ if fallback and all(fallback) and fallback[0] != fallback[1]:
2236
+ L.append(f" Claude Code moved this session from {fallback[0]} to {fallback[1]} after")
2237
+ L.append(" the decline (refusal fallback) and keeps it there until /clear or /model.")
2238
+ if clean_copy:
2239
+ L.append(f" Clean copy, without the decline's debris: /resume {clean_copy}")
2240
+ L.append(f" (or: claude --resume {clean_copy}) -- your messages and work are all in it.")
2241
+ if ctx:
2242
+ L.append(f" This session: {model or '?'} at {fmt_tok(ctx)} context.")
2243
+ if not p:
2244
+ L.append(" (no profile.json yet — run `refusectomy profile` for the"
2245
+ " figures)")
2246
+ L.append(" Detail: refusectomy session --live (no refused text is printed)")
2247
+ return "\n".join(L)
2248
+
2249
+
2250
+ # ---------------------------------------------------------------- fp report
2251
+ # The documented route for a classifier false positive is a support ticket carrying the
2252
+ # request ID -- there is no separate false-positive form. Quoted from the refusals docs
2253
+ # (2026-11-28), with their links, so the bundle states its own provenance:
2254
+ DOC_FACTS = [
2255
+ ("bio category",
2256
+ "The request could enable biological harm, such as dangerous lab methods. "
2257
+ "Beneficial life sciences work can also trigger this category.",
2258
+ "https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback"
2259
+ "#refusal-response"),
2260
+ ("how to report one",
2261
+ "If a reworded request is still declined, contact support and include the request ID.",
2262
+ "https://support.claude.com/en/articles/9015913-how-to-get-support"),
2263
+ ("request ID is the handle",
2264
+ "Log the request ID when reporting failures to Anthropic.",
2265
+ "https://platform.claude.com/docs/en/api/errors#request-id"),
2266
+ ("mid-stream declines are billed",
2267
+ "A mid-stream refusal bills the input tokens and the output already streamed at "
2268
+ "normal rates.",
2269
+ "https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback"
2270
+ "#how-refusals-are-billed"),
2271
+ ("why bio is billed before output, and what would change it",
2272
+ "a refusal that arrives before any output is billed when its stop_details.category "
2273
+ "is \"bio\", \"frontier_llm\", or \"reasoning_extraction\". These are the categories "
2274
+ "where Anthropic measures low volumes of false positives, as of September 2026. ... "
2275
+ "The billed categories may change as Anthropic keeps measuring and refining its "
2276
+ "safeguards\u2019 false positive rates.",
2277
+ "https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback"
2278
+ "#how-refusals-are-billed"),
2279
+ ("the institutional route for bio",
2280
+ "If the bio classifier gets in the way of an organization\u2019s life-sciences work, "
2281
+ "it can apply to the Life Sciences Verification Program.",
2282
+ "https://support.claude.com/en/articles/9015913-how-to-get-support"),
2283
+ ]
2284
+
2285
+ # The one thing this tool must not write for you. A support ticket turns on what the work
2286
+ # actually was, and inventing a research description would be fabricating the evidence --
2287
+ # so the bundle leaves a marked hole instead, and `audit` checks the hole is still there.
2288
+ WORK_PLACEHOLDER = (
2289
+ "<!-- REQUIRED, IN YOUR OWN WORDS. Two or three sentences: what the project is, what\n"
2290
+ " the model was being asked to do, and why it is legitimate work. This tool will\n"
2291
+ " not write this for you -- a description it invented would misrepresent you. -->"
2292
+ )
2293
+
2294
+
2295
+ def _incidents(events, turns):
2296
+ """Group refused requests into one incident per session.
2297
+
2298
+ Declines cascade, so N declines in one session are one incident with N requests, not
2299
+ N incidents -- filing them separately would misrepresent 19 retries of one blocked
2300
+ turn as 19 independent findings. Identifiers come from the refused *turns*: the
2301
+ harness warning record names what was refused, but the turn is what carries
2302
+ requestId and serverClassifierRequest for every refused request, including the
2303
+ retries that never got a warning record of their own.
2304
+ """
2305
+ # A request can be known from its warning record alone: when the refusal fallback
2306
+ # rescues it, the harness retracts the refused turn and persists the retry under a
2307
+ # new requestId. Those were billed declines too, and a bundle built from turns
2308
+ # alone left them out -- with their whole session, when the fallback was its only
2309
+ # decline. Each such record adds a row carrying what the record knows, no more.
2310
+ ev_by_rid = {e.request_id: e for e in events if e.request_id}
2311
+
2312
+ def refused_message(e):
2313
+ if not e.antecedent_sha:
2314
+ return None
2315
+ return {"sha256_12": e.antecedent_sha, "chars": e.antecedent_chars,
2316
+ "shape": e.antecedent_shape,
2317
+ "control_token": (" ".join(e.antecedent_text.split())
2318
+ if is_control(e.antecedent_text) else None)}
2319
+
2320
+ by_sess: dict = collections.defaultdict(list)
2321
+ for t in turns:
2322
+ by_sess[t.session].append(t)
2323
+ ev_by_sess: dict = collections.defaultdict(list)
2324
+ for e in events:
2325
+ ev_by_sess[e.session].append(e)
2326
+ out = []
2327
+ for sess in set(by_sess) | set(ev_by_sess):
2328
+ rows, evs = by_sess.get(sess, []), ev_by_sess.get(sess, [])
2329
+ have = {t.request_id for t in rows}
2330
+ reqs = [{
2331
+ "ts": t.ts,
2332
+ "request_id": t.request_id,
2333
+ "server_classifier_request": t.classifier_req,
2334
+ "model": t.model, "effort": t.effort or None,
2335
+ "context_tokens": t.context_tokens,
2336
+ "thinking_tokens": t.thinking_tokens,
2337
+ "mid_stream": bool(t.content_types),
2338
+ "warned": t.request_id in ev_by_rid,
2339
+ "from_warning_record_only": False,
2340
+ "refused_message": (refused_message(ev_by_rid[t.request_id])
2341
+ if t.request_id in ev_by_rid else None),
2342
+ } for t in rows]
2343
+ reqs += [{
2344
+ "ts": e.ts,
2345
+ "request_id": e.request_id,
2346
+ "server_classifier_request": e.classifier_req,
2347
+ "model": e.original_model or None, "effort": e.effort or None,
2348
+ "context_tokens": e.context_tokens if e.joined else None,
2349
+ "thinking_tokens": e.thinking_tokens if e.joined else None,
2350
+ "mid_stream": bool(e.content_types) if e.joined else None,
2351
+ "warned": True,
2352
+ "from_warning_record_only": True,
2353
+ "refused_message": refused_message(e),
2354
+ } for e in evs if e.request_id and e.request_id not in have]
2355
+ reqs.sort(key=lambda r: _ts(r["ts"]))
2356
+ out.append({
2357
+ "session": sess,
2358
+ "project": (evs[0].project if evs else rows[0].project),
2359
+ "cwd": (evs[0].cwd if evs else rows[0].cwd),
2360
+ "first": reqs[0]["ts"] if reqs else "", "last": reqs[-1]["ts"] if reqs else "",
2361
+ "declines": len(evs), "refused_requests": len(reqs),
2362
+ "categories": sorted({str(e.category) for e in evs if e.category}),
2363
+ "models": sorted({r["model"] for r in reqs if r["model"]}),
2364
+ "efforts": sorted({r["effort"] for r in reqs if r["effort"]}),
2365
+ "requests": reqs,
2366
+ })
2367
+ out.sort(key=lambda i: (-i["refused_requests"], i["first"]))
2368
+ return out
2369
+
2370
+
2371
+ def _token_footprint(turns) -> dict:
2372
+ f = collections.Counter()
2373
+ for t in turns:
2374
+ f["input"] += t.input_tokens
2375
+ f["cache_read"] += t.cache_read
2376
+ f["cache_create"] += t.cache_create
2377
+ f["output"] += t.output_tokens
2378
+ return dict(f)
2379
+
2380
+
2381
+ def render_fp_report(incidents, turns, events, prof, verbatim_map=None) -> str:
2382
+ p = prof or {}
2383
+ L: list[str] = []
2384
+ A = L.append
2385
+ stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%d")
2386
+ cats = sorted({str(e.category) for e in events if e.category})
2387
+ foot = _token_footprint(turns)
2388
+ rows_all = [r for inc in incidents for r in inc["requests"]]
2389
+ only_ev = sum(1 for r in rows_all if r.get("from_warning_record_only"))
2390
+ mid = sum(1 for r in rows_all if r["mid_stream"])
2391
+ unknown = sum(1 for r in rows_all if r["mid_stream"] is None)
2392
+ with_cls = sum(1 for r in rows_all if r["server_classifier_request"])
2393
+
2394
+ A(f"# Safety classifier false positives — {stamp}")
2395
+ A("")
2396
+ A("Generated by `refusectomy report` from this machine's own Claude Code")
2397
+ A("transcripts. Every figure below is computed from them; none is typed in by hand.")
2398
+ A("")
2399
+ A("## How to file this")
2400
+ A("")
2401
+ A("There is no separate false-positive form: the documented route is a support ticket")
2402
+ A("carrying the request ID. This file is written to be pasted into one. Each request ID")
2403
+ A("below is a handle Anthropic can look up directly, which is why no refused prose is")
2404
+ A("reproduced here.")
2405
+ A("")
2406
+ A("## What this work is")
2407
+ A("")
2408
+ A(WORK_PLACEHOLDER)
2409
+ A("")
2410
+ A("## Summary")
2411
+ A("")
2412
+ nproj = len({i["project"] for i in incidents})
2413
+ A(f"- **{len(events)} user-visible declines** across **{len(incidents)} session"
2414
+ f"{'s' if len(incidents) != 1 else ''}** in {nproj} "
2415
+ f"project{'s' if nproj != 1 else ''}")
2416
+ A(f"- **{len(rows_all)} refused API requests** behind them (the harness retries inside a "
2417
+ f"declined turn)" + (f"; {only_ev} known only from a warning record, because the "
2418
+ f"refusal fallback retracted the refused turn" if only_ev else ""))
2419
+ if rows_all:
2420
+ A(f"- window: `{min(r['ts'] for r in rows_all)[:19]}Z` .. "
2421
+ f"`{max(r['ts'] for r in rows_all)[:19]}Z`")
2422
+ A(f"- categories: {', '.join(f'`{c}`' for c in cats) or 'none recorded'}")
2423
+ A(f"- `stop_details.explanation` supplied by the API: "
2424
+ f"**{len([e for e in events if e.explanation])} of {len(events)}**")
2425
+ A(f"- identifiers: **{sum(1 for r in rows_all if r['request_id'])}/{len(rows_all)}** carry "
2426
+ f"a requestId, **{with_cls}/{len(rows_all)}** a serverClassifierRequest")
2427
+ A(f"- **{mid} of {len(rows_all)}** arrived mid-stream, after output had begun — so they "
2428
+ f"bill the input and streamed output at normal rates"
2429
+ + (f" ({unknown} unknown: no persisted turn)" if unknown else ""))
2430
+ A(f"- token footprint of the {len(turns)} refused requests with a persisted turn: "
2431
+ f"**{foot.get('cache_read',0):,}** cache-read, **{foot.get('cache_create',0):,}** "
2432
+ f"cache-write, **{foot.get('input',0):,}** uncached input, "
2433
+ f"**{foot.get('output',0):,}** output")
2434
+ conf = p.get("confounds") or {}
2435
+ ind = conf.get("independent")
2436
+ if p.get("answered_requests"):
2437
+ A(f"- for context, across **every project on this machine** (not just this scope): "
2438
+ f"{p.get('refused_requests')} of {p.get('answered_requests')} answered requests "
2439
+ f"({_pct(p.get('refused_requests', 0), p.get('answered_requests', 1))} pooled"
2440
+ + (f", {_pct(ind[0], ind[1])} over turns whose predecessor did not decline"
2441
+ if ind and ind[1] else "") + ")")
2442
+ # computed from the events in scope, not from the whole-corpus profile
2443
+ user_evs = [e for e in events if e.antecedent == "real user text"]
2444
+ if user_evs:
2445
+ lens = sorted(e.antecedent_chars for e in user_evs)
2446
+ ctl = [e for e in user_evs if is_control(e.antecedent_text)]
2447
+ A(f"- **what was refused, in this scope:** {len(user_evs)} of {len(events)} declines "
2448
+ f"resolve to a real user message, median **{lens[len(lens)//2]} characters**"
2449
+ + (f"; **{len(ctl)}** of them are a bare control token such as `continue`, which "
2450
+ f"carries no content to rephrase" if ctl else ""))
2451
+ if ctl:
2452
+ top = collections.Counter(" ".join(e.antecedent_text.split()) for e in ctl)
2453
+ A(f" ({', '.join(f'`{t}` x{c}' for t, c in top.most_common(5))})")
2454
+ ar, ao = p.get("p_after_refuse"), p.get("p_after_ok")
2455
+ if ar and ao and ar[1] and ao[1] and ao[0]:
2456
+ A(f"- **declines cascade** (whole machine): P(next request also declines) = "
2457
+ f"{_pct(ar[0], ar[1])} against a {_pct(ao[0], ao[1])} baseline, which is why the "
2458
+ f"incidents below are grouped by session rather than filed one per request")
2459
+ if not p:
2460
+ A("- (no profile.json — run `profile` to include the corpus figures)")
2461
+ A("")
2462
+ A("## Documented facts this report relies on")
2463
+ A("")
2464
+ for title, quote, url in DOC_FACTS:
2465
+ A(f"- **{title}** — \u201c{quote}\u201d")
2466
+ A(f" <{url}>")
2467
+ A("")
2468
+ A("## Incidents")
2469
+ A("")
2470
+ for n, inc in enumerate(incidents, 1):
2471
+ A(f"### {n}. `{inc['session']}` — {inc['project']}")
2472
+ A("")
2473
+ A(f"{inc['declines']} decline(s), {inc['refused_requests']} refused request(s), "
2474
+ f"`{inc['first'][:19]}Z` .. `{inc['last'][:19]}Z`")
2475
+ A(f"model(s): {', '.join(f'`{m}`' for m in inc['models']) or 'n/a'}"
2476
+ + (f" · effort: {', '.join(inc['efforts'])}" if inc['efforts'] else "")
2477
+ + (f" · category: {', '.join(inc['categories'])}" if inc['categories'] else ""))
2478
+ A("")
2479
+ A("| # | timestamp | requestId | serverClassifierRequest | refused message | ctx | thinking |")
2480
+ A("|---|---|---|---|---|---|---|")
2481
+ for k, r in enumerate(inc["requests"], 1):
2482
+ rm = r["refused_message"]
2483
+ if rm is None and r.get("from_warning_record_only"):
2484
+ msg = "_(refused message not in corpus)_"
2485
+ elif rm is None:
2486
+ msg = "_(retry — no warning record)_"
2487
+ elif rm["control_token"]:
2488
+ msg = f"`{rm['control_token']}` ({rm['chars']}c)"
2489
+ elif verbatim_map is not None and r["request_id"] in verbatim_map:
2490
+ msg = "`" + verbatim_map[r["request_id"]].replace("`", "'") + "`"
2491
+ else:
2492
+ nw = rm["shape"].split("/")[1].split()[0] if "/" in rm["shape"] else ""
2493
+ msg = f"`sha256:{rm['sha256_12']}`" + (f" ({nw})" if nw else "")
2494
+ A(f"| {k} | `{r['ts'][:19]}Z` | `{r['request_id'] or '—'}` | "
2495
+ f"`{r['server_classifier_request'] or 'not recorded'}` | {msg} | "
2496
+ f"{'?' if r['context_tokens'] is None else fmt_tok(r['context_tokens'])} | "
2497
+ f"{'?' if r['thinking_tokens'] is None else r['thinking_tokens']} |")
2498
+ A("")
2499
+ A("## Appendix — every refused request ID")
2500
+ A("")
2501
+ A("Includes the retries that carry no warning record of their own; each was a billed")
2502
+ A("request.")
2503
+ A("")
2504
+ A("```")
2505
+ for r in sorted(rows_all, key=lambda r: _ts(r["ts"])):
2506
+ A(f"{r['ts'][:19]}Z {r['request_id'] or '—':28} "
2507
+ f"{r['server_classifier_request'] or 'not recorded':36} {r['model'] or '?'}")
2508
+ A("```")
2509
+ return "\n".join(L)
2510
+
2511
+
2512
+ def cmd_report(args):
2513
+ events, turnmap, _ = load_events(args.cwd)
2514
+ turns = [t for t in turnmap.values()
2515
+ if not t.synthetic and t.stop_reason == "refusal"]
2516
+ if args.session:
2517
+ events = [e for e in events if e.session == args.session]
2518
+ turns = [t for t in turns if t.session == args.session]
2519
+ if args.project:
2520
+ events = [e for e in events
2521
+ if args.project in e.project or args.project in (e.cwd or "")]
2522
+ keep = {e.session for e in events}
2523
+ turns = [t for t in turns if t.session in keep or args.project in t.project]
2524
+ if args.category:
2525
+ events = [e for e in events if e.category == args.category]
2526
+ keep = {e.session for e in events}
2527
+ turns = [t for t in turns if t.session in keep]
2528
+ if not events and not turns:
2529
+ print("no refusal events in scope; nothing to report")
2530
+ return 1
2531
+
2532
+ verbatim_map = None
2533
+ if args.verbatim:
2534
+ verbatim_map = {e.request_id: " ".join(e.antecedent_text.split())[:400]
2535
+ for e in events
2536
+ if e.request_id and e.antecedent_text
2537
+ and not is_control(e.antecedent_text)}
2538
+
2539
+ incidents = _incidents(events, turns)
2540
+ prof = load_profile()
2541
+ md = render_fp_report(incidents, turns, events, prof, verbatim_map)
2542
+ payload = {
2543
+ "generated": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
2544
+ "scope": {"cwd": args.cwd, "session": args.session,
2545
+ "project": args.project, "category": args.category},
2546
+ # --verbatim affects the markdown only: that is the file you paste into a
2547
+ # ticket, and keeping the refused text out of the JSON means the machine-readable
2548
+ # record stays safe to diff, archive and re-read. Named precisely so the split is
2549
+ # not a surprise, and held by an audit invariant.
2550
+ "verbatim_in_markdown": bool(args.verbatim),
2551
+ "json_carries_refused_text": False,
2552
+ "declines": len(events), "refused_requests": len(turns),
2553
+ "categories": sorted({str(e.category) for e in events if e.category}),
2554
+ "explanation_supplied": len([e for e in events if e.explanation]),
2555
+ "token_footprint": _token_footprint(turns),
2556
+ "mid_stream": sum(1 for t in turns if t.content_types),
2557
+ "profile_generated": (prof or {}).get("generated"),
2558
+ "incidents": incidents,
2559
+ "documented_facts": [{"title": t, "quote": q, "url": u} for t, q, u in DOC_FACTS],
2560
+ }
2561
+
2562
+ os.makedirs(REPORT_DIR, exist_ok=True)
2563
+ stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
2564
+ tag = args.session[:8] if args.session else (args.project or args.category or "all")
2565
+ base = os.path.join(REPORT_DIR, f"fp-report-{re.sub(r'[^A-Za-z0-9_.-]', '-', tag)}-{stamp}")
2566
+ for path, text in ((base + ".md", md), (base + ".json", json.dumps(payload, indent=2))):
2567
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
2568
+ with os.fdopen(fd, "w") as fh:
2569
+ fh.write(text + "\n")
2570
+
2571
+ def _pl(n, word):
2572
+ return f"{n} {word}{'s' if n != 1 else ''}"
2573
+ print(f"{_pl(len(events), 'decline')} / {_pl(len(turns), 'refused request')} in "
2574
+ f"{_pl(len(incidents), 'incident')}")
2575
+ print(f" {len([t for t in turns if t.request_id])}/{len(turns)} requestId, "
2576
+ f"{len([t for t in turns if t.classifier_req])}/{len(turns)} "
2577
+ f"serverClassifierRequest")
2578
+ if not prof:
2579
+ print(" no profile.json — run `profile` first for the corpus figures")
2580
+ print(f"\nwrote (mode 0600):\n {base}.md\n {base}.json")
2581
+ if args.verbatim:
2582
+ print("\n !! --verbatim: the refused text is in the .md (not the .json). Read it "
2583
+ "before sending.")
2584
+ else:
2585
+ print("\n digest-only. The request IDs are the handle; add --verbatim only if "
2586
+ "you decide to include the text.")
2587
+ print(" Fill in the \"What this work is\" section before filing — it is left blank "
2588
+ "deliberately.")
2589
+ return 0
2590
+
2591
+
2592
+ def cmd_guard(args):
2593
+ """Stop-hook entry point: warn the human when this session has declined.
2594
+
2595
+ Silent unless the decline count for this session went up since the last turn, so a
2596
+ clean session costs one file read and prints nothing at all.
2597
+ """
2598
+ payload = {}
2599
+ if not args.no_stdin and not sys.stdin.isatty():
2600
+ try:
2601
+ raw = sys.stdin.read()
2602
+ payload = json.loads(raw) if raw.strip() else {}
2603
+ except Exception:
2604
+ payload = {}
2605
+ if not isinstance(payload, dict):
2606
+ payload = {}
2607
+ named = args.session or payload.get("session_id") or current_session_id()
2608
+ sid = named
2609
+ cwd = args.cwd or payload.get("cwd") or os.getcwd()
2610
+ # The hook payload names the transcript, which beats rebuilding its path from the
2611
+ # config dir and Claude Code's slug rule.
2612
+ tp = payload.get("transcript_path")
2613
+ path = tp if isinstance(tp, str) and os.path.isfile(tp) else None
2614
+ if path is None and sid:
2615
+ path = session_transcript(sid, cwd)
2616
+ # Only guess at the session when nobody named one. A named-but-unresolvable id
2617
+ # falling back to "newest transcript in this directory" would warn about a
2618
+ # different session, and misattribution is the mistake this project keeps making;
2619
+ # silence is the right answer instead.
2620
+ if path is None and not named:
2621
+ sid, path = newest_session(cwd)
2622
+ if not (sid and path):
2623
+ return 0
2624
+
2625
+ # Subagent transcripts sit beside the session's, under the PARENT's sessionId, and
2626
+ # never get a warning record of their own: read them or their declines are invisible.
2627
+ subs = sorted(glob.glob(os.path.join(os.path.splitext(path)[0], "subagents", "*.jsonl")))
2628
+ events, turnmap, _ = load_events(sessions={sid}, files=[path] + subs)
2629
+ turns = [t for t in turnmap.values()
2630
+ if not t.synthetic and t.stop_reason is not None]
2631
+ main_turns = [t for t in turns if not t.sidechain]
2632
+ ref = [t for t in turns if t.stop_reason == "refusal"]
2633
+ n_ref, n_ev = len(ref), len(events)
2634
+
2635
+ # Two counts, kept apart. A decline the refusal fallback rescued leaves a warning
2636
+ # record and no refused turn (the harness retracts it); harness retries leave refused
2637
+ # turns with no record. Taking max() of the two let one rise unseen behind the other.
2638
+ # On resume nothing has risen, but resuming an already-declined context is the move
2639
+ # the corpus is most emphatic about, so it is said once, at the point of decision.
2640
+ resumed = str(payload.get("hook_event_name") or "") == "SessionStart"
2641
+ st = _guard_load(sid)
2642
+ seen_ref, seen_ev = st.get("n", 0), st.get("ev", st.get("n", 0))
2643
+ stamp = dt.datetime.now(dt.timezone.utc).isoformat()
2644
+ if not (n_ref or n_ev) or (n_ref <= seen_ref and n_ev <= seen_ev and not resumed):
2645
+ if (n_ref or n_ev) and (n_ref, n_ev) != (seen_ref, seen_ev):
2646
+ _guard_store(sid, {"n": n_ref, "ev": n_ev, "ts": stamp})
2647
+ return 0
2648
+
2649
+ last = max(ref or turns, key=lambda t: _ts(t.ts)) if (ref or turns) else None
2650
+ now = max(main_turns, key=lambda t: _ts(t.ts)).model if main_turns else ""
2651
+ fbe = sorted((e for e in events if e.fallback_attempted), key=lambda e: _ts(e.ts))
2652
+ latched = (fbe[0].original_model, now) if fbe else None
2653
+ cats = [t.category for t in ref] + [e.category for e in events]
2654
+ copy = None
2655
+ from refusectomy import excise
2656
+ if excise.enabled(getattr(args, "excise", False)):
2657
+ try: # excision is a convenience; it must never cost the warning
2658
+ res = excise.make_clean_copy(path, sid)
2659
+ copy = res["fork_session"] if res.get("written") else None
2660
+ except Exception:
2661
+ copy = None
2662
+ msg = guard_message(n_ev, n_ref, cats, now or (last.model if last else ""),
2663
+ last.context_tokens if last else 0, load_profile(),
2664
+ resumed=resumed, fallback=latched,
2665
+ subagent_refusals=sum(1 for t in ref if t.sidechain), clean_copy=copy)
2666
+ _guard_store(sid, {"n": n_ref, "ev": n_ev, "ts": stamp})
2667
+
2668
+ # systemMessage only: shown to the user, never added to the model's context.
2669
+ print(json.dumps({"systemMessage": msg, "suppressOutput": True}))
2670
+ return 0
2671
+
2672
+
2673
+ def main(argv=None):
2674
+ p = argparse.ArgumentParser(
2675
+ prog="refusectomy", description=__doc__,
2676
+ formatter_class=argparse.RawDescriptionHelpFormatter)
2677
+ p.add_argument("--version", action="version", version=f"refusectomy {__version__}")
2678
+ p.add_argument("--cwd", help="limit to one project directory (default: all)")
2679
+ p.add_argument("--include-synthetic", action="store_true",
2680
+ help="include <synthetic> re-render records in counts")
2681
+ sub = p.add_subparsers(dest="cmd", required=True)
2682
+
2683
+ s = sub.add_parser("scan", help="list refusal events")
2684
+ s.add_argument("--limit", type=int, default=40)
2685
+ s.add_argument("--category")
2686
+ s.add_argument("--json", action="store_true", help="also write refusals.json")
2687
+ s.add_argument("--verbatim", action="store_true",
2688
+ help="include full refused text in the JSON (default: digest only)")
2689
+ s.set_defaults(fn=cmd_scan)
2690
+
2691
+ s = sub.add_parser("profile", help="base rates, correlations, poisoning test")
2692
+ s.set_defaults(fn=cmd_profile)
2693
+
2694
+ s = sub.add_parser("trace", help="show the exact message that was refused")
2695
+ s.add_argument("--session")
2696
+ s.add_argument("--project", help="substring match on project dir or cwd")
2697
+ s.add_argument("--limit", type=int, default=3)
2698
+ s.add_argument("--width", type=int, default=100)
2699
+ s.add_argument("--lines", type=int, default=6, help="wrapped lines of refused text")
2700
+ s.add_argument("--inline-chars", type=int, default=60, metavar="N",
2701
+ help="print refused text inline up to N chars, withhold longer "
2702
+ "(default 60; the median refused message here is 9)")
2703
+ s.add_argument("--verbatim", action="store_true",
2704
+ help="also emit full refused text to reports/trace-*.txt (mode 0600)")
2705
+ s.add_argument("--print", dest="print_text", action="store_true",
2706
+ help="with --verbatim, print full text to stdout instead of a file")
2707
+ s.set_defaults(fn=cmd_trace)
2708
+
2709
+ s = sub.add_parser("audit", help="self-check the invariants behind the numbers")
2710
+ s.set_defaults(fn=cmd_audit)
2711
+
2712
+ s = sub.add_parser("session", help="refusals in one session (--live for the current one)")
2713
+ s.add_argument("--session")
2714
+ s.add_argument("--live", action="store_true")
2715
+ s.set_defaults(fn=cmd_session)
2716
+
2717
+ s = sub.add_parser("remedy", help="grounded remediation playbook")
2718
+ s.add_argument("--category", choices=sorted(CATEGORIES))
2719
+ s.set_defaults(fn=cmd_remedy)
2720
+
2721
+ s = sub.add_parser("report", help="support-ticket bundle for a classifier false positive")
2722
+ s.add_argument("--session")
2723
+ s.add_argument("--project", help="substring match on project dir or cwd")
2724
+ s.add_argument("--category", choices=sorted(CATEGORIES))
2725
+ s.add_argument("--verbatim", action="store_true",
2726
+ help="include the refused text in the bundle (default: digest only)")
2727
+ s.set_defaults(fn=cmd_report)
2728
+
2729
+ s = sub.add_parser("guard", help="Stop-hook: warn the user when this session declined")
2730
+ s.add_argument("--excise", action="store_true",
2731
+ help="also write a clean copy of a declined session to resume (see `excise`)")
2732
+ s.add_argument("--session")
2733
+ s.add_argument("--no-stdin", action="store_true",
2734
+ help="do not read a hook payload from stdin")
2735
+ s.set_defaults(fn=cmd_guard)
2736
+
2737
+ s = sub.add_parser("bisect", help="active replay to isolate the trigger (needs credentials)")
2738
+ s.add_argument("--session")
2739
+ s.add_argument("--max-probes", type=int, default=12)
2740
+ s.set_defaults(fn=cmd_bisect)
2741
+
2742
+ args = p.parse_args(argv)
2743
+ return args.fn(args) or 0
2744
+
2745
+
2746
+ if __name__ == "__main__":
2747
+ sys.exit(main())