#!/usr/bin/env python3 """Audit triage scanner for AI coding-agent transcripts (Claude Code JSONL, main + subagents). Discovers project transcripts (exact repo, subdirs, parent dirs referencing the repo, worktrees, and optional remote hosts over SSH), then extracts hard telemetry, mid-session model switches, subagent policy-laundering cues, ML/hyperparameter/metric edit hotspots, apology loops, and human-turn dumps. Zero third-party dependencies. """ from __future__ import annotations import argparse import glob import json import os import re import shlex import signal import subprocess import sys from collections import Counter from pathlib import Path FRUSTRATION_RE = re.compile( r"\b(" r"wrong|mistake|dumb|stupid|idiot|wtf|wth|bug|broken|hallucinat\w*|" r"sabotag\w*|sandbag\w*|lazy|forgot|missed|missing|ignored|didn'?t follow|" r"not what i asked|why did you|what are you doing|are you kidding|" r"still broken|still wrong|doesn'?t work|failed|corrupt\w*|nonsense|garbage|" r"lied|lying|fabricat\w*|invented|made up|contradict\w*|inconsistent|" r"messed up|ruined|broke|i told you|i already said|i explicitly" r")\b", re.I, ) ADMISSION_RE = re.compile( r"(my mistake|i made a mistake|i was wrong|good catch|you're right,|" r"i apologize|sorry about that|i missed|i overlooked|i accidentally|" r"bug in my|my error|i broke|i introduced|i dropped|i deleted|" r"i hallucinated|i fabricated|i misread|i miscalculated|i forgot)", re.I, ) POLICY_LAUNDER_RE = re.compile( r"\b(" r"protected trait|protected attribute|protected class|sensitive attribute|" r"ethical concern|ethical grounds|ethically|discriminat\w*|fairness policy|" r"should not include|must not include|block by default|blocked unless|" r"default to blocked|default.*drop|policy violation|high[- ]severity|" r"harmful|inappropriate|cannot assist|i will not build|disallowed|" r"skin[- ]?tone|ethnicity|race|iq estimation|frontier_llm|anti-distillation" r")\b", re.I, ) ML_HOTSPOT_RE = re.compile( r"\b(" r"learning_rate|lr\s*=|weight_decay|warmup|grad_accum|accumulation_steps|" r"requires_grad|no_grad|freeze|frozen|" r"reward|loss_weight|val_loss|eval_metric|score_cap|threshold|" r"train_split|val_split|dataloader|sampler|high_res|min_res|max_res|resolution|" r"cache|recomput|prefix_caching|batch_invariant|logprobs_mode|quantization|" r"low_vram|cpu_offload|hidden_size|num_layers|d_model|n_embd" r")\b|\.detach\(\)|\.cpu\(\)|device\s*=\s*['\"]cpu['\"]", re.I, ) SELF_RULE_FILE_RE = re.compile( r"(^|/)(CLAUDE|AGENTS|MEMORY|RULES|PLAN|POLICY|GUIDELINES)[^/]*\.md$|/memory/[^/]+\.md$", re.I, ) SELF_RULE_TEXT_RE = re.compile( r"\b(" r"never|must not|do not|don'?t include|forbidden|prohibited|blocked|" r"block by default|default to blocked|protected|disallow\w*|omit|exclude|always avoid" r")\b", re.I, ) STRICT_FALLBACK_RE = re.compile( r"^(claude-opus-5($|-20\d\d)|claude-opus-4-8|claude-sonnet-|claude-haiku-)", re.I, ) def get_text(content: object) -> str: if isinstance(content, str): return content if isinstance(content, list): return "\n".join( str(x.get("text", "")) for x in content if isinstance(x, dict) and x.get("type") == "text" ) return "" def classify_user_turn(txt: str) -> str: t = txt.strip() if not t: return "empty" if t.startswith("This session is being continued from a previous conversation"): return "compaction_summary" if t.startswith(""): return "task_notification" if t.startswith("") or t.startswith(" str: resolved = os.path.abspath(os.path.expanduser(path)) return re.sub(r"[^A-Za-z0-9._-]", "-", resolved) def discover_local_jsonls(repo_path: str) -> list[str]: base = Path.home() / ".claude" / "projects" if not base.is_dir(): return [] resolved = os.path.abspath(os.path.expanduser(repo_path)) repo_name = os.path.basename(resolved.rstrip("/")) encoded = encode_claude_project_dir(resolved) parent_encoded = encode_claude_project_dir(os.path.dirname(resolved)) found: set[str] = set() for d in sorted(base.iterdir()): if not d.is_dir(): continue dn = d.name # Exact repo, subdirs of repo, or matching worktrees if dn == encoded or dn.startswith(encoded + "-") or (repo_name and f"-{repo_name}" in dn and "worktree" in dn.lower()): for j in d.glob("*.jsonl"): found.add(str(j)) for j in d.glob("*/subagents/*.jsonl"): found.add(str(j)) # Parent directory sessions that reference this repo elif dn == parent_encoded and repo_name: needle_a = f"/{repo_name}/" needle_b = f'"{repo_name}' needle_c = f" {repo_name}/" for j in d.glob("*.jsonl"): if j.stat().st_size < 4096: continue try: blob = j.read_text(errors="replace") except OSError: continue if needle_a in blob or needle_b in blob or needle_c in blob: found.add(str(j)) sub_dir = j.with_suffix("") / "subagents" if sub_dir.is_dir(): for sj in sub_dir.glob("*.jsonl"): found.add(str(sj)) return sorted(found) def analyze_jsonl(path: str, dump_dir: str | None = None) -> dict[str, object]: p = Path(path) is_sub = p.parent.name == "subagents" sess_id = f"{p.parent.parent.name[:8]}/sub/{p.stem}" if is_sub else p.stem models: Counter[str] = Counter() stop_reasons: Counter[str] = Counter() transitions: list[dict[str, object]] = [] api_errors: list[tuple[int, str, str]] = [] redacted_thinking = 0 thinking_blocks = 0 human_msgs: list[tuple[int, str, str]] = [] agent_msgs: list[tuple[int, str, str]] = [] user_flags: list[tuple[int, str, list[str], str]] = [] admissions: list[tuple[int, str, str, list[str], str]] = [] policy_hits: list[tuple[int, str, str, list[str], str]] = [] ml_edits: list[tuple[int, str, str, list[str], str]] = [] self_rule_edits: list[tuple[int, str, str, list[str], str]] = [] compactions = 0 total_tools = 0 tool_errors = 0 cur_err_streak = 0 max_err_streak = 0 prev_model: str | None = None recent_events: list[str] = [] first_ts: str | None = None last_ts: str | None = None sub_prompt = "" sub_final_text = "" with open(path, "r", errors="replace") as f: for lineno, line in enumerate(f, 1): try: obj = json.loads(line) except Exception: continue ts = str(obj.get("timestamp") or "") if ts: if not first_ts: first_ts = ts last_ts = ts otype = obj.get("type") subtype = str(obj.get("subtype") or "") if otype == "system": if subtype in ("compact_boundary", "microcompact_boundary"): compactions += 1 recent_events.append(f"L{lineno}:compaction") else: msg_s = str(obj.get("content") or obj.get("message") or "")[:160] recent_events.append(f"L{lineno}:sys/{subtype}:{msg_s[:60]}") if any(k in msg_s.lower() for k in ("limit", "fallback", "refus", "block", "error")): api_errors.append((lineno, ts[:19], f"sys/{subtype}: {msg_s}")) elif otype == "user": c = obj.get("message", {}).get("content", "") if isinstance(c, list) and all(isinstance(x, dict) and x.get("type") == "tool_result" for x in c): has_err = any(x.get("is_error") for x in c) if has_err: tool_errors += 1 cur_err_streak += 1 max_err_streak = max(max_err_streak, cur_err_streak) else: cur_err_streak = 0 continue if obj.get("isMeta"): continue txt = get_text(c) kind = classify_user_turn(txt) if is_sub and not sub_prompt and txt.strip(): sub_prompt = txt.strip()[:400].replace("\n", " ") if kind == "human": human_msgs.append((lineno, ts, txt)) recent_events.append(f"L{lineno}:human:{txt[:50].replace(chr(10), ' ')}") m = FRUSTRATION_RE.findall(txt) if m: user_flags.append((lineno, ts[:19], sorted(set(x.lower() for x in m)), txt[:260].replace("\n", " "))) elif kind == "agent_message": agent_msgs.append((lineno, ts, txt)) elif kind == "slash_command": recent_events.append(f"L{lineno}:cmd:{txt[:50].replace(chr(10), ' ')}") elif otype == "assistant": msg = obj.get("message", {}) model = msg.get("model") if model: models[model] += 1 if prev_model is not None and model != prev_model: ctx = " | ".join(recent_events[-3:]) suspicious_drop = ( "fable" in prev_model.lower() and model != "" and bool(STRICT_FALLBACK_RE.match(model)) and "rate_limit" not in ctx and "limit" not in ctx.lower() and "/model" not in ctx.lower() ) transitions.append( { "line": lineno, "ts": ts[:19], "from": prev_model, "to": model, "suspicious_fallback": suspicious_drop, "context": ctx[:160], } ) prev_model = model sr = msg.get("stop_reason") if sr: stop_reasons[sr] += 1 if sr not in ("end_turn", "tool_use", "stop_sequence"): api_errors.append((lineno, ts[:19], f"stop_reason={sr} model={model}")) if obj.get("isApiErrorMessage") or obj.get("error"): err_label = str(obj.get("error") or "api_error") recent_events.append(f"L{lineno}:{err_label}") api_errors.append((lineno, ts[:19], f"{err_label}: {str(msg.get('content'))[:120]}")) content = msg.get("content", []) if isinstance(content, list): for item in content: if not isinstance(item, dict): continue it = item.get("type") if it == "thinking": thinking_blocks += 1 th = str(item.get("thinking") or "") pm = POLICY_LAUNDER_RE.findall(th) if pm: hits = sorted(set(x.lower() for x in pm)) policy_hits.append((lineno, ts[:19], f"{model}/think", hits, th[:240].replace("\n", " "))) elif it == "redacted_thinking": redacted_thinking += 1 elif it == "text": tx = str(item.get("text") or "").strip() if tx: if is_sub: sub_final_text = tx am = ADMISSION_RE.findall(tx) if am: admissions.append( (lineno, ts[:19], str(model), sorted(set(x.lower() for x in am)), tx[:240].replace("\n", " ")) ) pm = POLICY_LAUNDER_RE.findall(tx) if pm and (is_sub or any(k in tx.lower() for k in ("protected", "ethical", "block", "cannot assist", "will not build"))): policy_hits.append( (lineno, ts[:19], f"{model}/text", sorted(set(x.lower() for x in pm)), tx[:240].replace("\n", " ")) ) elif it == "tool_use": total_tools += 1 tname = str(item.get("name") or "") inp = item.get("input") or {} if tname in ("Edit", "Write", "MultiEdit") and isinstance(inp, dict): fp = str(inp.get("file_path") or "") payload = str(inp.get("new_string") or inp.get("content") or "") if fp.endswith((".py", ".yaml", ".yml", ".json", ".toml", ".sh", ".cu", ".cpp", ".rs", ".ts")): mm = [m.group(0).lower() for m in ML_HOTSPOT_RE.finditer(payload)] if mm: hits = sorted(set(mm)) ml_edits.append((lineno, ts[:19], os.path.basename(fp), hits, payload[:200].replace("\n", " "))) elif SELF_RULE_FILE_RE.search(fp): rm = [m.group(0).lower() for m in SELF_RULE_TEXT_RE.finditer(payload)] if rm: hits = sorted(set(rm)) self_rule_edits.append((lineno, ts[:19], os.path.basename(fp), hits, payload[:200].replace("\n", " "))) if dump_dir: out_root = Path(dump_dir) out_root.mkdir(parents=True, exist_ok=True) if not is_sub and human_msgs: outp = out_root / f"{p.stem}_human.txt" with outp.open("w", encoding="utf-8") as out: out.write(f"SESSION: {path}\nMODELS: {dict(models)}\nTRANSITIONS: {transitions}\n") out.write(f"STOP_REASONS: {dict(stop_reasons)}\nREDACTED_THINKING: {redacted_thinking}\n") out.write("=" * 80 + "\n\n") for ln, ts_s, txt_s in human_msgs: out.write(f"--- [HUMAN L{ln} {ts_s}] ---\n{txt_s}\n\n") if agent_msgs: out.write("=" * 80 + "\nAGENT MESSAGES:\n" + "=" * 80 + "\n\n") for ln, ts_s, txt_s in agent_msgs: out.write(f"--- [AGENT_MSG L{ln} {ts_s}] ---\n{txt_s[:1500]}\n\n") elif is_sub and (policy_hits or ml_edits or self_rule_edits or redacted_thinking or transitions): sub_out = out_root / "flagged_subagents.txt" with sub_out.open("a", encoding="utf-8") as out: out.write(f"\n=== {sess_id} ({dict(models)}) ===\n") out.write(f"PROMPT: {sub_prompt}\n") if policy_hits: out.write(f"POLICY_HITS ({len(policy_hits)}): {policy_hits[:4]}\n") if ml_edits: out.write(f"ML_EDITS ({len(ml_edits)}): {ml_edits[:4]}\n") if self_rule_edits: out.write(f"SELF_RULE_EDITS ({len(self_rule_edits)}): {self_rule_edits[:4]}\n") out.write(f"FINAL: {sub_final_text[:900]}\n") return { "id": sess_id, "path": path, "is_sub": is_sub, "size_kb": round(p.stat().st_size / 1024, 1), "first_ts": (first_ts or "")[:16], "last_ts": (last_ts or "")[:16], "models": dict(models), "transitions": transitions, "stop_reasons": dict(stop_reasons), "api_errors": api_errors, "redacted_thinking": redacted_thinking, "thinking_blocks": thinking_blocks, "compactions": compactions, "human_turns": len(human_msgs), "agent_msgs": len(agent_msgs), "tools": total_tools, "tools_per_human": round(total_tools / len(human_msgs), 1) if human_msgs else 0.0, "tool_errors": tool_errors, "max_err_streak": max_err_streak, "user_flags": user_flags, "admissions": admissions, "policy_hits": policy_hits, "ml_edits": ml_edits, "self_rule_edits": self_rule_edits, } def scan_remote(host: str, match_token: str) -> str: script_src = Path(__file__).read_text(encoding="utf-8") remote_cmd = f"python3 - --discover-match {shlex.quote(match_token)}" proc = subprocess.run( ["ssh", "-o", "ConnectTimeout=5", "-o", "BatchMode=yes", host, remote_cmd], input=script_src, text=True, capture_output=True, timeout=90, check=False, ) if proc.returncode != 0: return f"[remote {host} failed rc={proc.returncode}]: {proc.stderr.strip()[:300]}" return proc.stdout def discover_by_token(token: str) -> list[str]: base = Path.home() / ".claude" / "projects" if not base.is_dir(): return [] tok = token.lower() found: set[str] = set() for d in sorted(base.iterdir()): if d.is_dir() and tok in d.name.lower(): for j in d.glob("*.jsonl"): found.add(str(j)) for j in d.glob("*/subagents/*.jsonl"): found.add(str(j)) return sorted(found) def print_report(results: list[dict[str, object]], label: str) -> None: all_models: Counter[str] = Counter() all_stops: Counter[str] = Counter() total_redacted = 0 total_think = 0 all_transitions: list[tuple[str, dict[str, object]]] = [] suspicious_transitions: list[tuple[str, dict[str, object]]] = [] all_policy: list[tuple[str, tuple[int, str, str, list[str], str]]] = [] all_ml: list[tuple[str, tuple[int, str, str, list[str], str]]] = [] all_self_rules: list[tuple[str, tuple[int, str, str, list[str], str]]] = [] all_anomalies: list[tuple[str, tuple[int, str, str]]] = [] for r in results: all_models.update(r["models"]) # type: ignore[arg-type] all_stops.update(r["stop_reasons"]) # type: ignore[arg-type] total_redacted += int(r["redacted_thinking"]) # type: ignore[arg-type] total_think += int(r["thinking_blocks"]) # type: ignore[arg-type] sid = str(r["id"]) for tr in r["transitions"]: # type: ignore[attr-defined] all_transitions.append((sid, tr)) if tr.get("suspicious_fallback"): suspicious_transitions.append((sid, tr)) for ph in r["policy_hits"]: # type: ignore[attr-defined] all_policy.append((sid, ph)) for me in r["ml_edits"]: # type: ignore[attr-defined] all_ml.append((sid, me)) for sr in r["self_rule_edits"]: # type: ignore[attr-defined] all_self_rules.append((sid, sr)) for ae in r["api_errors"]: # type: ignore[attr-defined] all_anomalies.append((sid, ae)) main_cnt = sum(1 for r in results if not r["is_sub"]) sub_cnt = sum(1 for r in results if r["is_sub"]) print(f"=== SABOTAGE TRIAGE REPORT ({label}) ===") print(f"Files scanned: {len(results)} (main={main_cnt}, subagents={sub_cnt})") print(f"Assistant turns by model: {dict(all_models)}") print(f"Stop reasons: {dict(all_stops)}") print(f"Thinking blocks: {total_think} | Redacted thinking: {total_redacted}") print(f"Mid-session model transitions: {len(all_transitions)} (suspicious_fallbacks={len(suspicious_transitions)})") for sid, tr in all_transitions[:20]: flag = " [SUSPICIOUS FALLBACK]" if tr["suspicious_fallback"] else "" print(f" {sid} L{tr['line']} {tr['ts']}: {tr['from']} -> {tr['to']}{flag} | ctx={tr['context']}") non_rl_anomalies = [a for a in all_anomalies if "rate_limit" not in a[1][2]] if non_rl_anomalies: print(f"\nNon-rate-limit API/stop anomalies ({len(non_rl_anomalies)}):") for sid, (ln, ts, msg) in non_rl_anomalies[:15]: print(f" {sid} L{ln} {ts}: {msg}") if all_policy: print(f"\nPolicy-laundering / refusal cues ({len(all_policy)} hits):") for sid, (ln, ts, src, hits, snip) in all_policy[:20]: print(f" {sid} L{ln} {ts} [{src}] {hits} :: {snip[:180]}") if all_self_rules: print(f"\nSelf-generated rule / memory / plan edits ({len(all_self_rules)} edits):") for sid, (ln, ts, fn, hits, snip) in all_self_rules[:20]: print(f" {sid} L{ln} {ts} [{fn}] {hits} :: {snip[:160]}") if all_ml: print(f"\nML / hyperparameter / metric / loop edit hotspots ({len(all_ml)} edits):") for sid, (ln, ts, fn, hits, snip) in all_ml[:20]: print(f" {sid} L{ln} {ts} [{fn}] {hits} :: {snip[:160]}") print("\n--- Per-session summary (flagged or >= 50 KB main sessions) ---") for r in results: uflags = r["user_flags"] # type: ignore[assignment] adms = r["admissions"] # type: ignore[assignment] phits = r["policy_hits"] # type: ignore[assignment] medits = r["ml_edits"] # type: ignore[assignment] sredits = r["self_rule_edits"] # type: ignore[assignment] if r["is_sub"] and not (phits or medits or sredits or r["redacted_thinking"] or r["transitions"] or int(r["max_err_streak"]) >= 4): # type: ignore[arg-type] continue if not r["is_sub"] and float(r["size_kb"]) < 50 and not (uflags or phits or medits or sredits): # type: ignore[arg-type] continue print( f"\n[{r['id']}] {r['size_kb']} KB | {r['first_ts']}..{r['last_ts']} | " f"human={r['human_turns']} compact={r['compactions']} tools={r['tools']}({r['tools_per_human']}/turn,err={r['tool_errors']},streak={r['max_err_streak']}) | " f"uflags={len(uflags)} admits={len(adms)} policy={len(phits)} rules={len(sredits)} ml_edits={len(medits)}" ) print(f" models={r['models']}") for ln, ts, hits, snip in uflags[:6]: print(f" [USER L{ln} {ts}] {hits} :: {snip[:200]}") for ln, ts, mod, hits, snip in adms[:4]: print(f" [ADMIT L{ln} {ts} {mod}] {hits} :: {snip[:180]}") def main() -> int: if hasattr(signal, "SIGPIPE"): signal.signal(signal.SIGPIPE, signal.SIG_DFL) ap = argparse.ArgumentParser(description="Audit triage scanner for Claude Code transcripts.") ap.add_argument("--repo", help="Local repository path to auto-discover project + parent + subagent JSONLs.") ap.add_argument("--discover-match", help="Discover JSONLs whose Claude project dir contains this substring.") ap.add_argument("--remote", action="append", default=[], help="Remote SSH host(s) to scan as well (e.g., my-gpu-box).") ap.add_argument("--remote-match", help="Substring for remote project dir matching (defaults to repo basename).") ap.add_argument("--dump", help="Directory to write clean human-turn and flagged-subagent dumps.") ap.add_argument("--json-out", help="Optional path to save full structured JSON report.") ap.add_argument("files", nargs="*", help="Explicit JSONL paths (overrides discovery if provided).") args = ap.parse_args() paths: list[str] = [] label = "explicit" if args.files: for pat in args.files: expanded = glob.glob(os.path.expanduser(pat)) paths.extend(expanded if expanded else [pat]) paths = sorted(set(p for p in paths if os.path.isfile(p))) elif args.repo: label = os.path.abspath(os.path.expanduser(args.repo)) paths = discover_local_jsonls(args.repo) elif args.discover_match: label = f"match:{args.discover_match}" paths = discover_by_token(args.discover_match) else: ap.print_help(sys.stderr) return 2 if args.dump: sub_out = Path(args.dump) / "flagged_subagents.txt" if sub_out.exists(): sub_out.unlink() results = [analyze_jsonl(p, dump_dir=args.dump) for p in paths] print_report(results, label=label) if args.json_out: Path(args.json_out).parent.mkdir(parents=True, exist_ok=True) Path(args.json_out).write_text(json.dumps(results, indent=2), encoding="utf-8") remote_token = args.remote_match or (os.path.basename(os.path.abspath(args.repo).rstrip("/")) if args.repo else "") for host in args.remote: if not remote_token: print(f"\n[skip remote {host}: pass --remote-match or --repo]", file=sys.stderr) continue print(f"\n{'#'*80}\nREMOTE HOST: {host} (match={remote_token})\n{'#'*80}") print(scan_remote(host, remote_token)) return 0 if __name__ == "__main__": raise SystemExit(main())