contextgate-core 0.6.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,48 @@
1
+ """ContextGate: a deterministic, zero-LLM gate for prompts and LLM requests.
2
+
3
+ Public API (every name below is covered by tests/test_public_api.py; imports are lazy so ``import contextgate_core`` stays instant,
4
+ which the Claude Code hook depends on)::
5
+
6
+ from contextgate_core import gate_text, gate_request, optimize, estimate_tokens
7
+
8
+ text, ok = gate_text("Could you please fix this in order to be safe", "balanced") # str -> (str, bool)
9
+ result = gate_request(chat_body) # dict -> GateResult
10
+ compiled = optimize(RawRequest(text="...")) # RawRequest -> CompiledPrompt
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from importlib import import_module
15
+ from typing import TYPE_CHECKING, Any
16
+
17
+ from .protocol import __version__
18
+
19
+ if TYPE_CHECKING: # static analysis / IDE completion only; never executed at runtime
20
+ from .data_contracts import CompiledPrompt, OptimizationTrace, RawRequest, TokenBudget
21
+ from .gate import PROFILES, GateResult, gate_request, gate_text
22
+ from .pipeline import audit_agent_response, estimate_tokens, optimize
23
+
24
+ _LAZY = {
25
+ "gate_text": "gate",
26
+ "gate_request": "gate",
27
+ "GateResult": "gate",
28
+ "PROFILES": "gate",
29
+ "optimize": "pipeline",
30
+ "estimate_tokens": "pipeline",
31
+ "audit_agent_response": "pipeline",
32
+ "RawRequest": "data_contracts",
33
+ "TokenBudget": "data_contracts",
34
+ "CompiledPrompt": "data_contracts",
35
+ "OptimizationTrace": "data_contracts",
36
+ }
37
+
38
+ __all__ = ["__version__", *_LAZY]
39
+
40
+
41
+ def __getattr__(name: str) -> Any:
42
+ if name in _LAZY:
43
+ return getattr(import_module(f".{_LAZY[name]}", __name__), name)
44
+ raise AttributeError(f"module 'contextgate_core' has no attribute {name!r}")
45
+
46
+
47
+ def __dir__() -> list[str]:
48
+ return sorted([*globals(), *_LAZY])
@@ -0,0 +1,566 @@
1
+ """
2
+ A/B comparison for NLP-Smarty: does the retrieval capsule actually reduce what an agent reads/spends?
3
+
4
+ Two complementary layers (neither alone is proof):
5
+
6
+ simulate Offline, deterministic, zero-LLM MODEL of an agent locating code with vs. without smarty.
7
+ Baseline agent = grep distinctive keywords, then read matching files (best-ranked first) until the target
8
+ file is read. Savings are EXPLORATION avoided minus capsule overhead; a miss or a silent gate saves
9
+ nothing (a wrong capsule is pure cost). Assumptions are explicit and conservative (see below).
10
+
11
+ transcripts Real measurement from Claude Code session transcripts (~/.claude/projects/<proj>/<session>.jsonl):
12
+ tokens by component, exploration tool calls/result size before the first edit, smarty usage.
13
+ Compare groups of runs (A = baseline, B = smarty).
14
+
15
+ Protocol for a real A/B (the only evidence that settles the question):
16
+ 1. Same commit, same model, same prompt text, fresh session per run. >=5 distinct tasks x >=3 runs per arm
17
+ (LLM runs vary a lot; one pair of runs proves nothing).
18
+ 2. Arm A (baseline): a `git worktree add ../repo-baseline` checkout. It lacks the untracked .claude/.mcp.json, so no
19
+ hook and no MCP tools. Arm B: the main checkout where `smarty init` was run.
20
+ 3. Finish each run (or stop at the same point, e.g. first successful edit), then:
21
+ python ab_compare.py transcripts --a A1.jsonl A2.jsonl --b B1.jsonl B2.jsonl
22
+ Stdlib only; no network; no LLM.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import json
29
+ import os
30
+ import re
31
+ import statistics
32
+ import sys
33
+ from typing import Any
34
+
35
+ os.environ.setdefault("SMARTY_LIGHT_TOKENS", "1") # same estimator for both arms; --bpe switches to the BPE-calibrated one
36
+
37
+ from . import repo_indexer as ri # noqa: E402
38
+
39
+ MAX_READS = 12 # a baseline agent that has not found the target after this many reads keeps going: cap the model
40
+ GREP_LINES = 20 # matching lines shown per grep
41
+ MAX_KEYWORDS = 4 # distinctive keywords a baseline agent greps for
42
+
43
+
44
+ # ── label loading ─────────────────────────────────────────────────────────────
45
+ def load_labels(path: str) -> tuple[list[dict], list[str]]:
46
+ """Accepts tests/golden_queries.json style ([{q, expect: ["path:Symbol"]}]) or {"code": [...], "silent": [...]}."""
47
+ data = json.load(open(path))
48
+ code, silent = (data.get("code", []), data.get("silent", [])) if isinstance(data, dict) else (data, [])
49
+ norm = [{"q": c["q"], "expect": sorted({e.split(":")[0] for e in c["expect"]})} for c in code]
50
+ return norm, list(silent)
51
+
52
+
53
+ # ── offline simulation ────────────────────────────────────────────────────────
54
+ class RepoText:
55
+ def __init__(self, root: str) -> None:
56
+ self.root = os.path.abspath(root)
57
+ self.text: dict[str, str] = {}
58
+ for rel in ri.iter_repo_files(self.root):
59
+ try:
60
+ with open(os.path.join(self.root, rel), encoding="utf-8", errors="replace") as f:
61
+ self.text[rel] = f.read()
62
+ except OSError:
63
+ pass
64
+ self.lower = {p: t.lower() for p, t in self.text.items()}
65
+ self.tokens = {p: ri.est_tokens(t) for p, t in self.text.items()}
66
+
67
+
68
+ def path_candidates(repo: RepoText, words: set[str]) -> tuple[list[str], int]:
69
+ """Files an agent would find by globbing file names for query words (4-char stems: 'healing' -> *heal*).
70
+ Words that match many paths (src, test, utils) are ignored. Returns (ordered paths, tokens of the glob listing)."""
71
+ stems = {w[:4] if len(w) >= 5 else w for w in words}
72
+ flat = {p: p.lower() for p in repo.lower}
73
+ n = max(1, len(flat))
74
+ usable = {s for s in stems if 0 < sum(s in f for f in flat.values()) <= n * 0.2}
75
+ scored = [(-sum(s in f for s in usable), p) for p, f in flat.items() if any(s in f for s in usable)]
76
+ order = [p for _, p in sorted(scored)]
77
+ return order, ri.est_tokens("\n".join(order[:25]))
78
+
79
+
80
+ def baseline_explore(repo: RepoText, query: str, expect: list[str], path_discovery: bool = True) -> dict[str, Any] | None:
81
+ """Model of a grep-then-read agent (optionally also globbing file names first). None = nothing to grep for."""
82
+ words = {w for w in re.findall(r"[a-z][a-z0-9_]{2,}", query.lower()) if w not in ri.STOPWORDS}
83
+ n = max(1, len(repo.lower))
84
+ df = {w: sum(1 for t in repo.lower.values() if w in t) for w in words}
85
+ kws = sorted((w for w in words if 0 < df[w] <= n * 0.5), key=lambda w: (df[w], w))[:MAX_KEYWORDS]
86
+ if not kws:
87
+ return None
88
+ grep_cost = 0
89
+ for k in kws: # each grep returns up to GREP_LINES "path:line:text" rows
90
+ shown = 0
91
+ for p, t in repo.lower.items():
92
+ for i, ln in enumerate(t.split("\n"), 1):
93
+ if k in ln:
94
+ grep_cost += ri.est_tokens(f"{p}:{i}:{repo.text[p].split(chr(10))[i - 1][:160]}")
95
+ shown += 1
96
+ if shown >= GREP_LINES:
97
+ break
98
+ if shown >= GREP_LINES:
99
+ break
100
+ scored = []
101
+ for p, t in repo.lower.items():
102
+ hit = [k for k in kws if k in t]
103
+ if hit:
104
+ scored.append((-len(hit), -sum(t.count(k) for k in hit), p))
105
+ order = [p for _, _, p in sorted(scored)]
106
+ if path_discovery:
107
+ by_name, glob_cost = path_candidates(repo, words)
108
+ grep_cost += glob_cost
109
+ order = by_name + [p for p in order if p not in by_name]
110
+ explore, read, found = 0, 0, None
111
+ for p in order[:MAX_READS]:
112
+ read += 1
113
+ if p in expect:
114
+ found = p
115
+ break
116
+ explore += repo.tokens[p]
117
+ target = found or next((e for e in expect if e in repo.tokens), None)
118
+ if target is None:
119
+ return None
120
+ return {"explore": explore + grep_cost, "reads": read, "found": found is not None, "target": target,
121
+ "target_read": repo.tokens[target], "keywords": kws}
122
+
123
+
124
+ def span_tokens(repo: RepoText, path: str, start: int, end: int) -> int:
125
+ return ri.est_tokens("\n".join(repo.text[path].split("\n")[start - 1:end]))
126
+
127
+
128
+ def simulate(root: str, code: list[dict], silent: list[str], min_confidence: float, budget: int,
129
+ path_discovery: bool = True) -> dict[str, Any]:
130
+ ri.refresh(root)
131
+ repo = RepoText(root)
132
+ rows = []
133
+ for c in code:
134
+ base = baseline_explore(repo, c["q"], c["expect"], path_discovery)
135
+ if base is None:
136
+ rows.append({"q": c["q"], "skipped": True})
137
+ continue
138
+ cap = ri.build_capsule(root, c["q"], token_budget=budget, min_confidence=min_confidence)
139
+ base_total = base["explore"] + base["target_read"]
140
+ emitted = cap["reason"] == "ok"
141
+ hit_hit = next((h for h in cap["hits"] if h["path"] in c["expect"]), None) if emitted else None
142
+ if not emitted:
143
+ outcome, cons, opt = "silent", base_total, base_total
144
+ elif hit_hit is None:
145
+ outcome, cons, opt = "miss", cap["tokens"] + base_total, cap["tokens"] + base_total
146
+ else:
147
+ outcome = "hit"
148
+ cons = cap["tokens"] + base["target_read"] # agent still reads the whole target file
149
+ opt = cap["tokens"] + min(base["target_read"], span_tokens(repo, hit_hit["path"], hit_hit["start"], hit_hit["end"]))
150
+ rows.append({"q": c["q"], "outcome": outcome, "baseline": base_total, "explore": base["explore"],
151
+ "target_read": base["target_read"], "capsule": cap["tokens"] if emitted else 0,
152
+ "conservative": cons, "optimistic": opt, "baseline_found": base["found"], "reads": base["reads"]})
153
+ used = [r for r in rows if not r.get("skipped")]
154
+ wasted = [ri.build_capsule(root, q, token_budget=budget, min_confidence=min_confidence) for q in silent]
155
+ false_inj = [w for w in wasted if w["reason"] == "ok"]
156
+ n = len(used)
157
+
158
+ def mean(key: str) -> float:
159
+ return round(sum(r[key] for r in used) / n, 1) if n else 0.0
160
+
161
+ def saving(key: str) -> float:
162
+ b = sum(r["baseline"] for r in used)
163
+ return round(100 * (1 - sum(r[key] for r in used) / b), 1) if b else 0.0
164
+
165
+ per_task = sorted(1 - r["conservative"] / r["baseline"] for r in used) if used else []
166
+ return {
167
+ "min_confidence": min_confidence, "baseline_model": "grep+filename-glob" if path_discovery else "grep-only", "tasks": n, "skipped_no_keywords": len(rows) - n,
168
+ "hit": sum(r["outcome"] == "hit" for r in used), "miss": sum(r["outcome"] == "miss" for r in used),
169
+ "silent": sum(r["outcome"] == "silent" for r in used),
170
+ "mean_baseline_tokens": mean("baseline"), "mean_explore_tokens": mean("explore"),
171
+ "mean_target_read_tokens": mean("target_read"), "mean_capsule_tokens_when_emitted": round(
172
+ sum(r["capsule"] for r in used if r["capsule"]) / max(1, sum(1 for r in used if r["capsule"])), 1),
173
+ "mean_with_smarty_conservative": mean("conservative"), "mean_with_smarty_optimistic": mean("optimistic"),
174
+ "saving_pct_conservative": saving("conservative"), "saving_pct_optimistic": saving("optimistic"),
175
+ "median_task_saving_pct_conservative": round(100 * statistics.median(per_task), 1) if per_task else 0.0,
176
+ "tasks_where_smarty_costs_more": sum(r["conservative"] > r["baseline"] for r in used),
177
+ "baseline_never_found_target": sum(not r["baseline_found"] for r in used),
178
+ "chatty_prompts": len(silent), "chatty_false_injections": len(false_inj),
179
+ "chatty_wasted_tokens": sum(w["tokens"] for w in false_inj), "rows": rows,
180
+ }
181
+
182
+
183
+ # ── real transcripts ──────────────────────────────────────────────────────────
184
+ INSTRUCTIONS_MARKER = "nlp-smarty index:" # start of mcp_server.INSTRUCTIONS; present when the agent received them
185
+ EDIT_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"}
186
+ EXPLORE_TOOLS = {"Read", "Grep", "Glob", "LS"}
187
+ _BASH_EXPLORE = re.compile(r"(^|[\s;&|])(grep|rg|find|ls|cat|head|tail|tree|wc|git\s+(grep|ls-files)|sed\s+-n)\b")
188
+
189
+
190
+ def _is_explore(u: dict) -> bool:
191
+ if u["name"] in EXPLORE_TOOLS:
192
+ return True
193
+ return u["name"] == "Bash" and bool(_BASH_EXPLORE.search(str(u["input"].get("command", ""))))
194
+
195
+
196
+ def _result_text(content: Any) -> str:
197
+ if isinstance(content, str):
198
+ return content
199
+ if isinstance(content, list):
200
+ return "\n".join(b.get("text", "") for b in content if isinstance(b, dict) and b.get("type") == "text")
201
+ return ""
202
+
203
+
204
+ def analyze_transcript(path: str) -> dict[str, Any]:
205
+ usage: dict[str, dict] = {} # message.id -> usage (lines repeat per content block; count each message once)
206
+ uses: list[dict] = [] # tool_use in order
207
+ seen_tool: set[str] = set()
208
+ results: dict[str, int] = {} # tool_use_id -> estimated result tokens
209
+ hooks = hook_tokens = 0
210
+ instr_seen = 0
211
+ ts: list[str] = []
212
+ with open(path, encoding="utf-8") as f:
213
+ for line in f:
214
+ try:
215
+ d = json.loads(line)
216
+ except ValueError:
217
+ continue
218
+ t = d.get("type")
219
+ if d.get("timestamp") and t in ("user", "assistant"):
220
+ ts.append(d["timestamp"])
221
+ if t == "assistant":
222
+ m = d.get("message", {})
223
+ if m.get("id") and m.get("usage"):
224
+ usage[m["id"]] = m["usage"]
225
+ for b in m.get("content", []) or []:
226
+ if isinstance(b, dict) and b.get("type") == "tool_use" and b.get("id") not in seen_tool:
227
+ seen_tool.add(b["id"])
228
+ uses.append({"id": b["id"], "name": b.get("name", ""), "input": b.get("input", {})})
229
+ elif t == "user":
230
+ c = d.get("message", {}).get("content")
231
+ for b in c if isinstance(c, list) else []:
232
+ if isinstance(b, dict) and b.get("type") == "tool_result":
233
+ results[b.get("tool_use_id", "")] = ri.est_tokens(_result_text(b.get("content")))
234
+ elif t == "attachment":
235
+ a = d.get("attachment", {})
236
+ if a.get("type") == "hook_additional_context" and "retrieved_context" in str(a.get("content", "")):
237
+ hooks += 1
238
+ hook_tokens += ri.est_tokens(str(a.get("content", "")))
239
+ elif INSTRUCTIONS_MARKER in json.dumps(a):
240
+ instr_seen = 1
241
+ inp = sum(u.get("input_tokens", 0) for u in usage.values())
242
+ cw = sum(u.get("cache_creation_input_tokens", 0) for u in usage.values())
243
+ cr = sum(u.get("cache_read_input_tokens", 0) for u in usage.values())
244
+ out = sum(u.get("output_tokens", 0) for u in usage.values())
245
+ first_edit = next((i for i, u in enumerate(uses) if u["name"] in EDIT_TOOLS), len(uses))
246
+
247
+ pre = [u for u in uses[:first_edit] if _is_explore(u)]
248
+ return {
249
+ "api_calls": len(usage), "input_tokens": inp, "cache_write_tokens": cw, "cache_read_tokens": cr,
250
+ "output_tokens": out,
251
+ # ASSUMPTION: Anthropic-style relative pricing (cache write 1.25x, cache read 0.1x of base input). Adjust to taste.
252
+ "weighted_input_equiv": round(inp + 1.25 * cw + 0.1 * cr),
253
+ "tool_calls": len(uses), "tool_calls_before_first_edit": first_edit,
254
+ "explore_calls_before_first_edit": len(pre),
255
+ "explore_result_tokens_before_first_edit": sum(results.get(u["id"], 0) for u in pre),
256
+ "had_edit": first_edit < len(uses),
257
+ "smarty_tool_calls": sum("smarty" in u["name"].lower() for u in uses),
258
+ "smarty_tools_used": sorted({u["name"].split("__")[-1] for u in uses if "smarty" in u["name"].lower()}),
259
+ "hook_injections": hooks, "hook_injection_tokens": hook_tokens,
260
+ "smarty_instructions_seen": instr_seen,
261
+ "wall_seconds": _span(ts),
262
+ }
263
+
264
+
265
+ def _prompt_text(d: dict) -> str | None:
266
+ """Text of a real user prompt entry (None for tool results / empty). Harness <system-reminder> blocks are dropped."""
267
+ c = d.get("message", {}).get("content")
268
+ if isinstance(c, list):
269
+ if any(isinstance(b, dict) and b.get("type") == "tool_result" for b in c):
270
+ return None
271
+ c = " ".join(b.get("text", "") for b in c if isinstance(b, dict) and b.get("type") == "text")
272
+ t = re.sub(r"<system-reminder>.*?</system-reminder>", "", c or "", flags=re.S).strip()
273
+ return t or None
274
+
275
+
276
+ SEGMENT_METRICS = ["weighted_input_equiv", "output_tokens", "api_calls", "tool_calls",
277
+ "explore_calls_before_first_edit", "explore_result_tokens_before_first_edit",
278
+ "smarty_tool_calls", "hook_injections", "hook_injection_tokens"]
279
+
280
+
281
+ def analyze_segments(path: str) -> list[dict[str, Any]]:
282
+ """Split a session at each real user prompt and attribute usage, tool calls and hook injections to the prompt
283
+ (task) they belong to. A sequence of tasks in one session is then comparable task by task."""
284
+ segs: list[dict[str, Any]] = []
285
+ seen_msg: set[str] = set()
286
+ seen_tool: set[str] = set()
287
+ with open(path, encoding="utf-8") as f:
288
+ for line in f:
289
+ try:
290
+ d = json.loads(line)
291
+ except ValueError:
292
+ continue
293
+ t = d.get("type")
294
+ if t == "user":
295
+ txt = _prompt_text(d)
296
+ if txt is not None:
297
+ segs.append({"prompt": txt, "usage": [], "uses": [], "results": {}, "hooks": 0, "hook_tokens": 0})
298
+ continue
299
+ if not segs:
300
+ continue
301
+ cur = segs[-1]
302
+ if t == "user":
303
+ c = d.get("message", {}).get("content")
304
+ for b in c if isinstance(c, list) else []:
305
+ if isinstance(b, dict) and b.get("type") == "tool_result":
306
+ cur["results"][b.get("tool_use_id", "")] = ri.est_tokens(_result_text(b.get("content")))
307
+ elif t == "assistant":
308
+ m = d.get("message", {})
309
+ if m.get("id") and m.get("usage") and m["id"] not in seen_msg:
310
+ seen_msg.add(m["id"])
311
+ cur["usage"].append(m["usage"])
312
+ for b in m.get("content", []) or []:
313
+ if isinstance(b, dict) and b.get("type") == "tool_use" and b.get("id") not in seen_tool:
314
+ seen_tool.add(b["id"])
315
+ cur["uses"].append({"id": b["id"], "name": b.get("name", ""), "input": b.get("input", {})})
316
+ elif t == "attachment":
317
+ a = d.get("attachment", {})
318
+ if a.get("type") == "hook_additional_context" and "retrieved_context" in str(a.get("content", "")):
319
+ cur["hooks"] += 1
320
+ cur["hook_tokens"] += ri.est_tokens(str(a.get("content", "")))
321
+ out = []
322
+ for sg in segs:
323
+ u = sg["usage"]
324
+ inp, cw = sum(x.get("input_tokens", 0) for x in u), sum(x.get("cache_creation_input_tokens", 0) for x in u)
325
+ cr, outp = sum(x.get("cache_read_input_tokens", 0) for x in u), sum(x.get("output_tokens", 0) for x in u)
326
+ uses = sg["uses"]
327
+ first_edit = next((i for i, x in enumerate(uses) if x["name"] in EDIT_TOOLS), len(uses))
328
+ pre = [x for x in uses[:first_edit] if _is_explore(x)]
329
+ out.append({"prompt": sg["prompt"], "api_calls": len(u), "weighted_input_equiv": round(inp + 1.25 * cw + 0.1 * cr),
330
+ "output_tokens": outp, "tool_calls": len(uses), "explore_calls_before_first_edit": len(pre),
331
+ "explore_result_tokens_before_first_edit": sum(sg["results"].get(x["id"], 0) for x in pre),
332
+ "smarty_tool_calls": sum("smarty" in x["name"].lower() for x in uses),
333
+ "hook_injections": sg["hooks"], "hook_injection_tokens": sg["hook_tokens"]})
334
+ return out
335
+
336
+
337
+ def compare_segments(a: list[list[dict]], b: list[list[dict]]) -> list[dict]:
338
+ """Pair prompt k of every run in A with prompt k of every run in B; report mean per metric per task."""
339
+ rows = []
340
+ for k in range(min(max(map(len, a), default=0), max(map(len, b), default=0))):
341
+ ga = [r[k] for r in a if len(r) > k]
342
+ gb = [r[k] for r in b if len(r) > k]
343
+ if not ga or not gb:
344
+ continue
345
+ task = {"task": k + 1, "prompt": (ga[0]["prompt"] or "")[:70], "n_a": len(ga), "n_b": len(gb), "metrics": []}
346
+ for m in SEGMENT_METRICS:
347
+ ma, mb = statistics.mean(x[m] for x in ga), statistics.mean(x[m] for x in gb)
348
+ task["metrics"].append({"metric": m, "A": round(ma, 1), "B": round(mb, 1),
349
+ "delta_pct": round(100 * (mb - ma) / ma, 1) if ma else None})
350
+ rows.append(task)
351
+ return rows
352
+
353
+
354
+ class InputError(Exception):
355
+ pass
356
+
357
+
358
+ PROJECTS_DIR = "~/.claude/projects"
359
+
360
+
361
+ def match_project_dirs(match: str, root: str | None = None) -> list[str]:
362
+ """Claude Code project directories whose name contains `match` (avoids shell-glob 'no matches found' errors)."""
363
+ root = os.path.expanduser(root or PROJECTS_DIR)
364
+ if not os.path.isdir(root):
365
+ raise InputError(f"Claude Code projects directory not found: {root}")
366
+ found = sorted(os.path.join(root, d) for d in os.listdir(root) if match in d and os.path.isdir(os.path.join(root, d)))
367
+ if not found:
368
+ raise InputError(f"no Claude Code project directory matching '{match}' under {root} yet "
369
+ f"(a directory only appears once a session has run in that folder)")
370
+ return found
371
+
372
+
373
+ def expand_inputs(paths: list[str], last: int | None = None, match: str | None = None) -> list[str]:
374
+ """Files are used as given. Directories expand to their *.jsonl sessions; with `last`, only the newest N sessions
375
+ across ALL given directories are kept (so several worktree project dirs can be passed with one --last)."""
376
+ files: list[str] = []
377
+ from_dirs: list[str] = []
378
+ seen_dirs: list[str] = []
379
+ if match:
380
+ paths = list(paths) + match_project_dirs(match)
381
+ if not paths:
382
+ raise InputError("give transcript paths/directories or --match NAME")
383
+ for p in paths:
384
+ p = os.path.expanduser(p)
385
+ if os.path.isdir(p):
386
+ from_dirs.extend(os.path.join(p, f) for f in os.listdir(p) if f.endswith(".jsonl"))
387
+ seen_dirs.append(p)
388
+ elif os.path.isfile(p):
389
+ files.append(p)
390
+ else:
391
+ raise InputError(f"not found: {p} (substitute your real transcript paths or a project directory under "
392
+ f"~/.claude/projects/; 'A1.jsonl'-style names in the docs are placeholders)")
393
+ if seen_dirs and not from_dirs and not files: # empty dirs are fine inside a glob; nothing anywhere is an error
394
+ raise InputError(f"no .jsonl transcripts in {', '.join(seen_dirs)} (has a session been run there yet?)")
395
+ from_dirs.sort(key=os.path.getmtime, reverse=True)
396
+ return files + (from_dirs[:last] if last else from_dirs)
397
+
398
+
399
+ def _span(ts: list[str]) -> float:
400
+ from datetime import datetime
401
+
402
+ try:
403
+ parse = lambda s: datetime.fromisoformat(s.replace("Z", "+00:00")) # noqa: E731
404
+ return round((parse(max(ts)) - parse(min(ts))).total_seconds(), 1) if ts else 0.0
405
+ except ValueError:
406
+ return 0.0
407
+
408
+
409
+ METRICS = ["weighted_input_equiv", "input_tokens", "cache_write_tokens", "cache_read_tokens", "output_tokens",
410
+ "api_calls", "tool_calls_before_first_edit", "explore_calls_before_first_edit",
411
+ "explore_result_tokens_before_first_edit", "smarty_tool_calls", "hook_injections", "hook_injection_tokens",
412
+ "smarty_instructions_seen", "wall_seconds"]
413
+
414
+
415
+ def guess_arm(a: dict) -> str:
416
+ """A = no smarty activity; B = hook (and/or tools) but no instructions; C = the agent received the MCP instructions."""
417
+ if a["smarty_instructions_seen"]:
418
+ return "C"
419
+ return "B" if (a["hook_injections"] or a["smarty_tool_calls"]) else "A"
420
+
421
+
422
+ def compare(a: list[dict], b: list[dict]) -> list[dict]:
423
+ rows = []
424
+ for m in METRICS:
425
+ ma, mb = statistics.mean(x[m] for x in a), statistics.mean(x[m] for x in b)
426
+ rows.append({"metric": m, "A": round(ma, 1), "B": round(mb, 1),
427
+ "delta_pct": round(100 * (mb - ma) / ma, 1) if ma else None})
428
+ return rows
429
+
430
+
431
+ # ── CLI ───────────────────────────────────────────────────────────────────────
432
+ def _print_sim(s: dict) -> None:
433
+ print(f"\n== baseline={s['baseline_model']} min_confidence={s['min_confidence']} tasks={s['tasks']} (skipped {s['skipped_no_keywords']}: nothing to grep)")
434
+ print(f" outcomes: hit={s['hit']} miss(wasted capsule)={s['miss']} silent={s['silent']}")
435
+ print(f" baseline tokens/task: {s['mean_baseline_tokens']} (exploration {s['mean_explore_tokens']} + target read {s['mean_target_read_tokens']})")
436
+ print(f" with smarty : {s['mean_with_smarty_conservative']} conservative | {s['mean_with_smarty_optimistic']} optimistic"
437
+ f" (capsule ~{s['mean_capsule_tokens_when_emitted']} tokens when emitted)")
438
+ print(f" SAVING : {s['saving_pct_conservative']}% conservative | {s['saving_pct_optimistic']}% optimistic"
439
+ f" (median task {s['median_task_saving_pct_conservative']}%; costs MORE on {s['tasks_where_smarty_costs_more']} tasks)")
440
+ print(f" chatty prompts : {s['chatty_false_injections']}/{s['chatty_prompts']} wrongly injected ({s['chatty_wasted_tokens']} wasted tokens)")
441
+
442
+
443
+ def main(argv: list[str] | None = None) -> int:
444
+ ap = argparse.ArgumentParser(prog="ab_compare", description=__doc__.split("\n")[1])
445
+ sub = ap.add_subparsers(dest="cmd", required=True)
446
+ s = sub.add_parser("simulate", help="offline model of exploration with vs. without smarty")
447
+ s.add_argument("--root", required=True)
448
+ s.add_argument("--labels", required=True)
449
+ s.add_argument("--min-confidence", type=float, nargs="+", default=[ri.MIN_CONFIDENCE])
450
+ s.add_argument("--budget", type=int, default=450)
451
+ s.add_argument("--baseline", choices=("grep+path", "grep"), nargs="+", default=["grep+path"],
452
+ help="baseline agent model(s): grep+path also globs file names (fairer, default); grep is the strawman")
453
+ s.add_argument("--bpe", action="store_true", help="use the BPE-calibrated estimator instead of the light heuristic")
454
+ s.add_argument("--json", dest="json_out")
455
+ i = sub.add_parser("inspect", help="one line per session: inferred arm, hook/instructions/tool use, cost (validity check)")
456
+ i.add_argument("paths", nargs="*", help=".jsonl files and/or project directories")
457
+ i.add_argument("--match", help="select project directories by name substring, e.g. NexusAI-smarty-c (no shell glob needed)")
458
+ i.add_argument("--last", type=int, help="newest N sessions across the given directories")
459
+ t = sub.add_parser("transcripts", help="compare real Claude Code sessions: A (baseline) vs B (smarty)")
460
+ t.add_argument("--smarty-vs-smarty", action="store_true",
461
+ help="reference arm (--a) is hook-only smarty and --b is hook + MCP instructions; adjusts the validity checks")
462
+ t.add_argument("--a", nargs="*", default=[], help="baseline transcripts: .jsonl files and/or project directories")
463
+ t.add_argument("--b", nargs="*", default=[], help="smarty transcripts: .jsonl files and/or project directories")
464
+ t.add_argument("--by-arm", nargs=2, metavar=("REF", "CAND"), choices=("A", "B", "C"),
465
+ help="gather sessions via --match/--a/--b paths, group them by the arm each one ACTUALLY was (A none / B hook "
466
+ "only / C hook+instructions, inferred from content) and compare REF vs CAND. Needed because Claude "
467
+ "Code names project dirs after the repo root, so folder names cannot identify an arm.")
468
+ t.add_argument("--match", help="with --by-arm: select project directories by name substring")
469
+ t.add_argument("--a-match", help="select arm-A project directories by name substring")
470
+ t.add_argument("--b-match", help="select arm-B project directories by name substring")
471
+ t.add_argument("--per-prompt", action="store_true",
472
+ help="split each session at its user prompts and compare task by task (use when a session ran several tasks)")
473
+ t.add_argument("--last", type=int, help="when a directory is given, use only its newest N sessions")
474
+ t.add_argument("--json", dest="json_out")
475
+ a = ap.parse_args(argv)
476
+ if a.cmd == "inspect":
477
+ try:
478
+ paths = expand_inputs(a.paths, a.last, a.match)
479
+ except InputError as exc:
480
+ print(f"error: {exc}", file=sys.stderr)
481
+ return 2
482
+ print(f"{'modified':12}{'arm':4}{'hook':>5}{'instr':>6}{'mcp':>5}{'explore':>8}{'api':>5}{'wIn':>9} {'edit':5} prompt / smarty tools used")
483
+ for p in sorted(paths, key=os.path.getmtime):
484
+ x = analyze_transcript(p)
485
+ seg = analyze_segments(p)
486
+ when = __import__("time").strftime("%m-%d %H:%M", __import__("time").localtime(os.path.getmtime(p)))
487
+ prompt = (seg[0]["prompt"] if seg else "")[:46].replace("\n", " ")
488
+ tools = ",".join(x["smarty_tools_used"]) or "-"
489
+ print(f"{when:12}{guess_arm(x):4}{x['hook_injections']:>5}{x['smarty_instructions_seen']:>6}{x['smarty_tool_calls']:>5}"
490
+ f"{x['explore_calls_before_first_edit']:>8}{x['api_calls']:>5}{x['weighted_input_equiv']:>9} "
491
+ f"{'yes' if x['had_edit'] else 'no':5} {prompt!r} [{tools}]" + (f" (+{len(seg)-1} more prompts)" if len(seg) > 1 else ""))
492
+ return 0
493
+ if a.cmd == "simulate":
494
+ if a.bpe:
495
+ ri._ESTIMATOR = None
496
+ os.environ.pop("SMARTY_LIGHT_TOKENS", None)
497
+ code, silent = load_labels(a.labels)
498
+ out = [simulate(a.root, code, silent, mc, a.budget, bm == "grep+path")
499
+ for bm in a.baseline for mc in a.min_confidence]
500
+ for r in out:
501
+ _print_sim(r)
502
+ print("\nMODEL ASSUMPTIONS: baseline agent globs file names and greps <=4 distinctive keywords, reads matching files best-first (<=12) until it "
503
+ "reads the target; 'conservative' still reads the whole target file after a hit; a miss or a silent gate saves "
504
+ "nothing. This is a MODEL, not a measurement: use `transcripts` on real runs to confirm.")
505
+ if a.json_out:
506
+ json.dump(out, open(a.json_out, "w"), indent=2)
507
+ return 0
508
+ try:
509
+ if a.by_arm:
510
+ allp = expand_inputs(a.a + a.b, a.last, a.match)
511
+ arms = {p: guess_arm(analyze_transcript(p)) for p in allp}
512
+ pa = [p for p in allp if arms[p] == a.by_arm[0]]
513
+ pb = [p for p in allp if arms[p] == a.by_arm[1]]
514
+ counts = {k: sum(1 for v in arms.values() if v == k) for k in "ABC"}
515
+ print(f"sessions by inferred arm: A={counts['A']} B={counts['B']} C={counts['C']} (comparing {a.by_arm[0]} vs {a.by_arm[1]})")
516
+ if not pa or not pb:
517
+ raise InputError(f"need sessions in both arms; found {a.by_arm[0]}={len(pa)}, {a.by_arm[1]}={len(pb)}")
518
+ if set(a.by_arm) == {"B", "C"}:
519
+ a.smarty_vs_smarty = True
520
+ else:
521
+ pa, pb = expand_inputs(a.a, a.last, a.a_match), expand_inputs(a.b, a.last, a.b_match)
522
+ except InputError as exc:
523
+ print(f"error: {exc}", file=sys.stderr)
524
+ return 2
525
+ ga, gb = [analyze_transcript(p) for p in pa], [analyze_transcript(p) for p in pb]
526
+ if a.per_prompt:
527
+ sa, sb = [analyze_segments(p) for p in pa], [analyze_segments(p) for p in pb]
528
+ for task in compare_segments(sa, sb):
529
+ print(f"\n== task {task['task']}: {task['prompt']!r} (A n={task['n_a']}, B n={task['n_b']})")
530
+ print(f"{'metric':44}{'A':>12}{'B':>12}{'B vs A':>10}")
531
+ for r in task["metrics"]:
532
+ print(f"{r['metric']:44}{r['A']:>12}{r['B']:>12}{(str(r['delta_pct']) + '%') if r['delta_pct'] is not None else '-':>10}")
533
+ print("\n--- whole-session totals (all tasks together) ---")
534
+ rows = compare(ga, gb)
535
+ print(f"A (baseline) n={len(ga)} B (smarty) n={len(gb)}")
536
+ if a.smarty_vs_smarty:
537
+ if any(not x["hook_injections"] for x in ga + gb):
538
+ print("WARNING: some runs had no hook injection; both arms are supposed to use the hook.")
539
+ if any(x["smarty_instructions_seen"] for x in ga):
540
+ print("WARNING: reference arm (--a) received the MCP instructions - it is not hook-only; comparison invalid.")
541
+ if not all(x["smarty_instructions_seen"] for x in gb):
542
+ print("WARNING: not every --b run received the MCP instructions (smarty_instructions_seen); check the server is "
543
+ "current and SMARTY_MCP_INSTRUCTIONS is not 'off' in that folder.")
544
+ used = sum(1 for x in gb if x["smarty_tool_calls"])
545
+ print(f"MCP tools were called in {used}/{len(gb)} instruction-arm runs "
546
+ f"(and {sum(1 for x in ga if x['smarty_tool_calls'])}/{len(ga)} in the reference arm).")
547
+ else:
548
+ if any(x["hook_injections"] or x["smarty_tool_calls"] for x in ga):
549
+ print("WARNING: arm A shows smarty activity - the baseline is contaminated; this comparison is invalid.")
550
+ if not any(x["hook_injections"] or x["smarty_tool_calls"] for x in gb):
551
+ print("WARNING: arm B shows NO smarty activity (0 hook injections, 0 smarty tool calls) - smarty may not have loaded.")
552
+ print(f"{'metric':44}{'A':>12}{'B':>12}{'B vs A':>10}")
553
+ for r in rows:
554
+ print(f"{r['metric']:44}{r['A']:>12}{r['B']:>12}{(str(r['delta_pct']) + '%') if r['delta_pct'] is not None else '-':>10}")
555
+ if min(len(ga), len(gb)) < 3:
556
+ print("\nWARNING: fewer than 3 runs per arm. LLM runs vary widely; treat these deltas as anecdotes, not evidence.")
557
+ if not all(x["had_edit"] for x in ga + gb):
558
+ print("NOTE: some runs never edited a file; 'before first edit' metrics then cover the whole run.")
559
+ if a.json_out:
560
+ json.dump({"A": ga, "B": gb, "compare": rows,
561
+ "per_prompt": compare_segments(sa, sb) if a.per_prompt else None}, open(a.json_out, "w"), indent=2)
562
+ return 0
563
+
564
+
565
+ if __name__ == "__main__":
566
+ sys.exit(main())