ctxtree 0.0.0-stage → 0.2.0

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.
Files changed (4) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +98 -2
  3. package/ctxtree.py +1431 -0
  4. package/package.json +15 -4
package/ctxtree.py ADDED
@@ -0,0 +1,1431 @@
1
+ #!/usr/bin/env python3
2
+ """ctxtree: a folded, lossless view of a Claude Code session, opened on demand.
3
+
4
+ For you:
5
+ ctxtree where your last session here left off, and the cheaper way back
6
+ ctxtree resume [--upto tN] start a new Claude Code session from the folded view (or from before turn N)
7
+ ctxtree level [L] how much the folded view holds: see what each level would hold, or save one
8
+ ctxtree report [--days N] how often you went back to a cooled session lately, and what that cost
9
+ ctxtree titles [SESSION] name each stretch of work in a few words (asks Claude Haiku: opt-in, sends excerpts)
10
+
11
+ For Claude and other tools:
12
+ ctxtree show [--opening] the folded view: the map, then recent turns word for word (or the exact opening)
13
+ ctxtree open NODE e3 an episode, t12 a turn, t12.3 one tool call with its full input and output
14
+ ctxtree search PATTERN where a word or regex appears, in words and tool output alike
15
+ ctxtree status [--json] warm or cooled, and what each way back costs, read fast
16
+ ctxtree hook for the Claude Code plugin's SessionStart hook (reads its JSON on stdin)
17
+ ctxtree statusline a line for Claude Code's status line: the cache's minutes left, then both prices
18
+ ctxtree mcp search, open, show and report as an MCP server on stdio, for any MCP client
19
+ ctxtree check [--all] prove nothing is lost: every tool call and result opens to exactly what the log holds
20
+
21
+ Each command works on the newest session in this folder unless you name another: its id, its first 6 or more
22
+ characters, or its .jsonl file (`ctxtree <id>` shows that session's card). Codex CLI sessions work too, named by
23
+ their id (from ~/.codex/sessions). Inside a Claude Code session, the newest
24
+ session means the newest other than that one. search --here looks through every session in this folder. show, open,
25
+ search and resume take --upto tN to see a session as it stood before turn N.
26
+
27
+ The level works like effort. auto, the default, holds the current task word for word and a map of the rest, between
28
+ 8k and 24k tokens. Or pick low, medium, high, xhigh or max (about 2k, 8k, 24k, 64k tokens, or every turn), or a size
29
+ such as 30k. --level beats CTXTREE_LEVEL, which beats the level saved with `ctxtree level <name>`.
30
+ """
31
+ import argparse, glob, json, os, re, shlex, shutil, subprocess, sys, time
32
+
33
+ __version__ = "0.2.0"
34
+ from datetime import datetime
35
+
36
+ ROOT = os.path.expanduser("~/.claude/projects")
37
+ GAP = 45 * 60 # a pause this long starts a new episode
38
+ TTL = 3600 # how long a Claude subscription's prompt cache lives with nothing asked (API keys: 5 minutes)
39
+ START = 30000 # tokens a new Claude Code session holds before anything is said, roughly (system prompt, tools)
40
+ CHARS = 4 # characters a token, roughly
41
+ COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-\S+\s+(\S+\s+)?)*commit\b")
42
+ HERE = os.path.realpath(__file__)
43
+ # Run by npx: ctxtree is on the PATH only until npx exits
44
+ NPX = os.environ.get("npm_lifecycle_event") == "npx"
45
+ # Run by the Claude Code plugin's launcher, whose folder is on Claude's PATH but not on the person's
46
+ PLUGIN_BIN = os.environ.get("CTXTREE_PLUGIN_BIN")
47
+
48
+
49
+ def installed():
50
+ """A ctxtree the person can type: on the PATH, and not the plugin's own launcher"""
51
+ skip = os.path.realpath(PLUGIN_BIN) if PLUGIN_BIN else None
52
+ dirs = [d for d in os.environ.get("PATH", "").split(os.pathsep) if d and os.path.realpath(d) != skip]
53
+ return shutil.which("ctxtree", path=os.pathsep.join(dirs))
54
+
55
+
56
+ FULL = "python3 " + HERE.replace(os.path.expanduser("~"), "~", 1)
57
+ # How an agent runs this: plain ctxtree when it's on its PATH (installed, or the plugin's), else this file in full
58
+ ME = "ctxtree" if (PLUGIN_BIN or installed()) and not NPX else FULL
59
+ # How a person runs it again
60
+ YOU = "npx ctxtree" if NPX else "ctxtree" if installed() else FULL
61
+ # The slider's fixed notches: about how many tokens the opening message may hold (max: every turn, tool calls folded)
62
+ FIXED = (("low", 2000), ("medium", 8000), ("high", 24000), ("xhigh", 64000), ("max", None))
63
+ NAMES = ("auto",) + tuple(n for n, _ in FIXED)
64
+ # $ per million tokens, list prices (Nov 2026): written to a one-hour cache (coming back to a cooled window, or starting
65
+ # fresh), and read from it (coming back while it's warm)
66
+ # List prices, $ per million tokens: input, output, cache read, 5-minute cache write, 1-hour cache write (Nov 2026)
67
+ PRICES = {"claude-fable-5-2": (8, 40, 0.20, 10, 16), "claude-fable-5-1": (10, 50, 0.25, 12.5, 20),
68
+ "claude-opus-5-5": (4, 20, 0.20, 5, 8), "claude-opus-5": (5, 25, 0.50, 6.25, 10),
69
+ "claude-opus-4-8": (5, 25, 0.50, 6.25, 10), "claude-sonnet-5-5": (2, 10, 0.10, 2.5, 4),
70
+ "claude-sonnet-5": (2, 10, 0.20, 2.5, 4), "claude-haiku-5-5": (0.10, 0.50, 0.01, 0.125, 0.20),
71
+ "claude-haiku-4-5": (1, 5, 0.10, 1.25, 2)}
72
+
73
+
74
+ def prices(model):
75
+ """A model's list prices, also for a dated name such as claude-haiku-4-5-20251001; None for one it doesn't know"""
76
+ model = model or ""
77
+ return PRICES.get(model) or next((p for k, p in PRICES.items() if model.startswith(k + "-")), None)
78
+
79
+
80
+ class _Rate(dict):
81
+ def __init__(self, i):
82
+ super().__init__()
83
+ self.i = i
84
+
85
+ def get(self, model, default=None):
86
+ p = prices(model)
87
+ return p[self.i] if p else default
88
+
89
+
90
+ WRITE, READ = _Rate(4), _Rate(2) # what re-caching a window costs (an hour's cache), and re-reading it
91
+
92
+
93
+ def text_of(content):
94
+ """The words in a message's content, whether it is a string or a list of blocks"""
95
+ if isinstance(content, str):
96
+ return content
97
+ out = []
98
+ for x in content if isinstance(content, list) else []:
99
+ if isinstance(x, dict) and x.get("type") == "text":
100
+ out.append(x.get("text") or "")
101
+ elif isinstance(x, dict) and x.get("type") == "image":
102
+ out.append("[image]")
103
+ return "\n".join(out)
104
+
105
+
106
+ def when(e):
107
+ try:
108
+ return datetime.fromisoformat(e["timestamp"].replace("Z", "+00:00")).timestamp()
109
+ except (KeyError, AttributeError, ValueError):
110
+ return None
111
+
112
+
113
+ def starter(e):
114
+ """Who a user entry comes from when it starts a turn ('you', 'task', 'command', 'sdk'), else None"""
115
+ if e.get("isMeta") or e.get("isCompactSummary"):
116
+ return None
117
+ content = (e.get("message") or {}).get("content")
118
+ if isinstance(content, list) and any(isinstance(x, dict) and x.get("type") == "tool_result" for x in content):
119
+ return None
120
+ words = text_of(content)
121
+ if not words.strip() or words.startswith("[Request interrupted"):
122
+ return None
123
+ origin = e.get("origin") if isinstance(e.get("origin"), dict) else {}
124
+ if origin.get("kind") == "peer":
125
+ return None
126
+ if origin.get("kind") == "task-notification":
127
+ return "task"
128
+ if words.startswith(("<command-", "<local-command")):
129
+ return "command"
130
+ return "sdk" if e.get("promptSource") == "sdk" else "you"
131
+
132
+
133
+ class Call:
134
+ def __init__(self, cid, name, args, line, turn):
135
+ self.id, self.name, self.args, self.line, self.turn = cid, name, args, line, turn
136
+ self.node = "%s.%d" % (turn.node, sum(1 for k, _ in turn.items if k == "call") + 1)
137
+ self.result, self.result_line, self.error = None, None, False
138
+
139
+
140
+ class Turn:
141
+ def __init__(self, n, who, words, line, t):
142
+ self.n, self.who, self.words, self.line, self.t0, self.t1 = n, who, words, line, t, t
143
+ self.items = [] # in order: ("text", words the agent wrote) or ("call", Call)
144
+ self.notes = [] # text injected into the turn (skills, hook feedback, messages): (line, text)
145
+ self.commits, self.after_compact = 0, False
146
+
147
+ @property
148
+ def node(self):
149
+ return "t%d" % self.n
150
+
151
+ def calls(self):
152
+ return [x for k, x in self.items if k == "call"]
153
+
154
+
155
+ CODEX = os.path.expanduser("~/.codex/sessions")
156
+
157
+
158
+ def entries(path, codex=None):
159
+ """A session log's entries with their line numbers. A Codex CLI log is translated as it's read, one entry for each of
160
+ its lines, into the shape Claude Code writes, so everything else reads both; `codex` collects its id, model and
161
+ window."""
162
+ state = codex if codex is not None else {}
163
+ with open(path, errors="replace") as f:
164
+ for line_no, line in enumerate(f, 1):
165
+ try:
166
+ e = json.loads(line)
167
+ except ValueError:
168
+ continue
169
+ if not isinstance(e, dict):
170
+ continue
171
+ if line_no == 1 and isinstance(e.get("payload"), dict) and e.get("type") in ("session_meta", "turn_context"):
172
+ state["codex"] = True
173
+ if state.get("codex"):
174
+ e = from_codex(e, state)
175
+ if e is None:
176
+ continue
177
+ yield line_no, e
178
+
179
+
180
+ def from_codex(e, state):
181
+ kind, p = e.get("type"), e.get("payload") if isinstance(e.get("payload"), dict) else {}
182
+ stamp_ = {"timestamp": e.get("timestamp"), "cwd": state.get("cwd")}
183
+ if kind in ("session_meta", "turn_context"):
184
+ state["id"] = state.get("id") or p.get("id")
185
+ state["cwd"], state["model"] = p.get("cwd") or state.get("cwd"), p.get("model") or state.get("model")
186
+ return None
187
+ if kind == "compacted":
188
+ return {"type": "system", "subtype": "compact_boundary", "timestamp": e.get("timestamp")}
189
+ if kind == "event_msg" and p.get("type") == "user_message":
190
+ return dict(stamp_, type="user", origin={"kind": "human"}, promptSource="typed",
191
+ message={"role": "user", "content": p.get("message") or ""})
192
+ if kind == "event_msg" and p.get("type") == "token_count":
193
+ last = ((p.get("info") or {}).get("last_token_usage") or {})
194
+ state["window"] = last.get("input_tokens") or state.get("window") # Codex counts cached input inside it
195
+ return None
196
+ if kind != "response_item":
197
+ return None
198
+ item = p.get("type")
199
+ if item == "agent_message": # a message from another agent, such as the task a worker was given: not you
200
+ words = p.get("content") if isinstance(p.get("content"), str) else "".join(
201
+ c.get("text") or "" for c in p.get("content") or [] if isinstance(c, dict))
202
+ return dict(stamp_, type="user", promptSource="sdk", message={"role": "user", "content": words})
203
+ reply = lambda content: dict(stamp_, type="assistant", message={
204
+ "id": p.get("id") or p.get("call_id"), "role": "assistant", "model": state.get("model"), "content": content})
205
+ if item == "message" and p.get("role") == "assistant":
206
+ return reply([{"type": "text", "text": "".join(c.get("text") or "" for c in p.get("content") or []
207
+ if isinstance(c, dict))}])
208
+ if item in ("function_call", "custom_tool_call"):
209
+ args = p.get("arguments") if item == "function_call" else {"input": p.get("input")}
210
+ if isinstance(args, str):
211
+ try:
212
+ args = json.loads(args)
213
+ except ValueError:
214
+ args = {"arguments": args}
215
+ return reply([{"type": "tool_use", "id": p.get("call_id"), "name": p.get("name") or item,
216
+ "input": args if isinstance(args, dict) else {"arguments": args}}])
217
+ if item in ("function_call_output", "custom_tool_call_output"):
218
+ out = p.get("output")
219
+ return dict(stamp_, type="user", message={"role": "user", "content": [
220
+ {"type": "tool_result", "tool_use_id": p.get("call_id"),
221
+ "content": out if isinstance(out, str) else json.dumps(out)}]})
222
+ return None
223
+
224
+
225
+ class Session:
226
+ def __init__(self, path):
227
+ self.path, self.id = path, os.path.basename(path)[:-len(".jsonl")]
228
+ self.turns, self.orphans, self.cwd, self.chars, self.window, self.model = [], 0, None, 0, 0, None
229
+ calls, seen, compacted, cur = {}, set(), False, None
230
+ codex = {}
231
+ for line_no, e in entries(path, codex):
232
+ if e.get("isSidechain"):
233
+ continue
234
+ self.cwd = self.cwd or e.get("cwd")
235
+ kind, t = e.get("type"), when(e)
236
+ if kind == "system" and e.get("subtype") == "compact_boundary":
237
+ compacted = True
238
+ continue
239
+ if kind not in ("user", "assistant"):
240
+ continue
241
+ message = e.get("message") if isinstance(e.get("message"), dict) else {}
242
+ content = message.get("content")
243
+ if kind == "user":
244
+ who = starter(e)
245
+ if who:
246
+ cur = Turn(len(self.turns) + 1, who, text_of(content), line_no, t)
247
+ cur.after_compact, compacted = compacted, False
248
+ self.turns.append(cur)
249
+ self.chars += len(cur.words)
250
+ continue
251
+ if cur and t:
252
+ cur.t1 = max(cur.t1 or t, t)
253
+ results = [x for x in content if isinstance(x, dict) and x.get("type") == "tool_result"] \
254
+ if isinstance(content, list) else []
255
+ for x in results:
256
+ body = text_of(x.get("content"))
257
+ self.chars += len(body)
258
+ c = calls.get(x.get("tool_use_id"))
259
+ if c is None:
260
+ self.orphans += 1
261
+ continue
262
+ c.result, c.result_line, c.error = body, line_no, bool(x.get("is_error"))
263
+ if c.name == "Bash" and not c.error and COMMIT.search(str(c.args.get("command", ""))):
264
+ c.turn.commits += 1
265
+ if not results and cur:
266
+ words = text_of(content)
267
+ if words.strip():
268
+ cur.notes.append((line_no, words))
269
+ self.chars += len(words)
270
+ continue
271
+ if cur is None: # a session that starts with the agent, as a resumed one can
272
+ cur = Turn(1, "start", "", line_no, t)
273
+ self.turns.append(cur)
274
+ if t:
275
+ cur.t1 = max(cur.t1 or t, t)
276
+ usage = message.get("usage") if isinstance(message.get("usage"), dict) else {}
277
+ if usage and message.get("model") != "<synthetic>": # tokens the window held at the last reply
278
+ self.window = sum(usage.get(k) or 0 for k in
279
+ ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"))
280
+ self.model = message.get("model") or self.model
281
+ for x in content if isinstance(content, list) else []:
282
+ if not isinstance(x, dict):
283
+ continue
284
+ if x.get("type") == "text" and (x.get("text") or "").strip():
285
+ key = (message.get("id"), x["text"])
286
+ if key not in seen:
287
+ seen.add(key)
288
+ cur.items.append(("text", x["text"]))
289
+ self.chars += len(x["text"])
290
+ elif x.get("type") == "tool_use" and x.get("id") not in calls:
291
+ args = x.get("input") if isinstance(x.get("input"), dict) else {}
292
+ c = Call(x.get("id"), x.get("name") or "?", args, line_no, cur)
293
+ calls[c.id] = c
294
+ cur.items.append(("call", c))
295
+ self.chars += len(json.dumps(args, ensure_ascii=False))
296
+ elif x.get("type") == "thinking":
297
+ self.chars += len(x.get("thinking") or "")
298
+
299
+ if codex.get("id"): # a Codex CLI log: its id, window and model come from its own fields
300
+ self.id, self.window = codex["id"], codex.get("window") or self.window
301
+ self.model = codex.get("model") or self.model
302
+ def episodes(self):
303
+ """Turns split into stretches of work: a new one after a pause, a compaction or a commit"""
304
+ eps, prev = [], None
305
+ for turn in self.turns:
306
+ if not eps or turn.after_compact or prev.commits or \
307
+ (turn.t0 and prev.t1 and turn.t0 - prev.t1 > GAP):
308
+ eps.append([])
309
+ eps[-1].append(turn)
310
+ prev = turn
311
+ return eps
312
+
313
+ def last_active(self):
314
+ return (self.turns[-1].t1 if self.turns else None) or os.path.getmtime(self.path)
315
+
316
+ def find(self, node):
317
+ m = re.fullmatch(r"t(\d+)(?:\.(\d+))?", node)
318
+ if m and 0 < int(m.group(1)) <= len(self.turns):
319
+ turn = self.turns[int(m.group(1)) - 1]
320
+ if m.group(2) is None:
321
+ return turn
322
+ calls = turn.calls()
323
+ return calls[int(m.group(2)) - 1] if 0 < int(m.group(2)) <= len(calls) else None
324
+ m = re.fullmatch(r"e(\d+)", node)
325
+ eps = self.episodes()
326
+ return eps[int(m.group(1)) - 1] if m and 0 < int(m.group(1)) <= len(eps) else None
327
+
328
+
329
+ def short(path, n=60):
330
+ p = str(path or "").replace(os.path.expanduser("~"), "~", 1)
331
+ return p if len(p) <= n else "…" + p[-(n - 1):]
332
+
333
+
334
+ def one_line(s, n=90):
335
+ s = " ".join(str(s or "").split())
336
+ return s if len(s) <= n else s[:n - 1] + "…"
337
+
338
+
339
+ def lines(s):
340
+ return s.count("\n") + (not s.endswith("\n")) if s else 0
341
+
342
+
343
+ def stamp(t, fmt="%b %d %H:%M"):
344
+ return datetime.fromtimestamp(t).strftime(fmt) if t else "?"
345
+
346
+
347
+ def ago(seconds):
348
+ minutes, hours = int(seconds // 60), int(seconds // 3600)
349
+ return "just now" if minutes < 2 else "%d minutes ago" % minutes if minutes < 90 else \
350
+ "%d hours ago" % hours if hours < 36 else "%d days ago" % int(seconds // 86400)
351
+
352
+
353
+ def gist(c):
354
+ """One line for a tool call: what it did and what came back"""
355
+ a = c.args
356
+ if c.name == "Read":
357
+ what = short(a.get("file_path")) + (" from line %s" % a["offset"] if a.get("offset") else "")
358
+ elif c.name == "Edit":
359
+ what = "%s (-%d +%d lines)" % (short(a.get("file_path")), lines(a.get("old_string")), lines(a.get("new_string")))
360
+ elif c.name == "Write":
361
+ what = "%s (%d lines)" % (short(a.get("file_path")), lines(a.get("content")))
362
+ elif c.name == "Bash":
363
+ what = a.get("description") or a.get("command")
364
+ elif c.name in ("Grep", "Glob"):
365
+ what = repr(a.get("pattern")) + (" in " + short(a["path"]) if a.get("path") else "")
366
+ elif c.name in ("Agent", "Task"):
367
+ what = a.get("description")
368
+ else:
369
+ what = a.get("query") or a.get("url") or a.get("skill") or \
370
+ next((v for v in a.values() if isinstance(v, str)), "")
371
+ n = lines(c.result)
372
+ got = "no result" if c.result is None else "error: " + one_line(c.result, 50) if c.error \
373
+ else "ok" if c.name in ("Edit", "Write", "NotebookEdit") else "%d line%s" % (n, "" if n == 1 else "s")
374
+ return "%s %s: %s → %s" % (c.node, c.name, one_line(what), got)
375
+
376
+
377
+ def heading_words(turn):
378
+ if turn.who == "command":
379
+ m = re.search(r"<command-name>(.*?)</command-name>", turn.words)
380
+ return m.group(1) if m else one_line(re.sub(r"<[^>]+>", " ", turn.words), 80)
381
+ if turn.who == "task":
382
+ m = re.search(r"<summary>(.*?)</summary>", turn.words, re.S)
383
+ return "task notification: " + one_line(m.group(1) if m else re.sub(r"<[^>]+>", " ", turn.words), 100)
384
+ return turn.words.strip()
385
+
386
+
387
+ def task_of(turns):
388
+ """The turn that best says what a stretch of work was about: its first prompt of some length, else its first"""
389
+ yours = [t for t in turns if t.who == "you"] or turns
390
+ return next((t for t in yours if len(t.words.strip()) >= 25), yours[0])
391
+
392
+
393
+ def render_turn(turn, notes=False):
394
+ out = ["### %s · %s · %s" % (turn.node, turn.who, stamp(turn.t0)), heading_words(turn)]
395
+ for kind, x in turn.items:
396
+ out.append(("agent: " + x.strip()) if kind == "text" else " " + gist(x))
397
+ if turn.notes and not notes:
398
+ out.append(" (%d injected notes, %d characters: open %s to read them)"
399
+ % (len(turn.notes), sum(len(t) for _, t in turn.notes), turn.node))
400
+ for line_no, words in turn.notes if notes else []:
401
+ out.append("note (line %d):\n%s" % (line_no, words.strip()))
402
+ return "\n".join(out)
403
+
404
+
405
+ def episode_line(i, turns, title=None):
406
+ files, commits = [], sum(t.commits for t in turns)
407
+ for t in turns:
408
+ for c in t.calls():
409
+ name = os.path.basename(str(c.args.get("file_path") or ""))
410
+ if c.name in ("Edit", "Write") and name and name not in files:
411
+ files.append(name)
412
+ parts = ["e%d" % i, "%s to %s" % (stamp(turns[0].t0), stamp(turns[-1].t1, "%H:%M")),
413
+ "1 turn (%s)" % turns[0].node if len(turns) == 1 else
414
+ "%d turns (%s-%s)" % (len(turns), turns[0].node, turns[-1].node)]
415
+ if files:
416
+ parts.append("edited " + ", ".join(files[:5]) + (" and %d more" % (len(files) - 5) if len(files) > 5 else ""))
417
+ if commits:
418
+ parts.append("%d commit%s" % (commits, "" if commits == 1 else "s"))
419
+ if title: # a name from `ctxtree titles`; the exact words follow it, so the map still quotes the session
420
+ parts.insert(1, title)
421
+ return " · ".join(parts) + ' · "%s"' % one_line(heading_words(task_of(turns)), 100 if not title else 70)
422
+
423
+
424
+ def budget(level, s=None):
425
+ """Tokens for a level (None for max). auto: the current task word for word plus the map, kept within 8k-24k"""
426
+ if level == "auto":
427
+ if s is None or not s.turns:
428
+ return 8000
429
+ task = sum(len(render_turn(t)) + 1 for t in s.episodes()[-1])
430
+ return min(24000, max(8000, 2 * task // CHARS + 1000))
431
+ for name, tokens in FIXED:
432
+ if level == name:
433
+ return tokens
434
+ m = re.fullmatch(r"(\d+(?:\.\d+)?)([kK]?)", str(level or ""))
435
+ if not m:
436
+ raise ValueError("a level is auto, low, medium, high, xhigh or max, or a size such as 30k, not %r" % level)
437
+ return max(1000, int(float(m.group(1)) * (1000 if m.group(2) else 1)))
438
+
439
+
440
+ def config_path():
441
+ home = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")
442
+ return os.path.join(home, "ctxtree", "config")
443
+
444
+
445
+ def level_in_force(flag=None):
446
+ """The level to use: --level, then CTXTREE_LEVEL, then the saved one, then auto"""
447
+ if flag:
448
+ return flag
449
+ if os.environ.get("CTXTREE_LEVEL"):
450
+ return os.environ["CTXTREE_LEVEL"]
451
+ try:
452
+ with open(config_path()) as f:
453
+ for line in f:
454
+ key, _, value = line.partition("=")
455
+ if key.strip() == "level" and value.strip():
456
+ return value.strip()
457
+ except OSError:
458
+ pass
459
+ return "auto"
460
+
461
+
462
+ def slider(level, s=None):
463
+ marks = " · ".join("[%s]" % n if n == level else n for n in NAMES) + ("" if level in NAMES else " · [%s]" % level)
464
+ out = [marks, "auto, the default, holds the current task word for word and a map of the rest (8k to 24k tokens). "
465
+ "The others hold about: low 2k, medium 8k, high 24k, xhigh 64k, max every turn."]
466
+ if s is not None and level == "auto":
467
+ out.append("For the session here, auto comes to about %dk." % (budget("auto", s) // 1000))
468
+ return "\n".join(out)
469
+
470
+
471
+ def levels_table(s, current):
472
+ """What each level's opening would hold for a session"""
473
+ eps = len(s.episodes())
474
+ rows = ["%-8s %8s %-30s %s" % ("level", "opening", "turns word for word", "episodes on the map")]
475
+ for name in NAMES:
476
+ text, n, cut, mapped = prime(s, budget(name, s))
477
+ rows.append("%-8s %7.1fk %-30s %d of %d" % (
478
+ "[%s]" % name if name == current else name, len(text) / (CHARS * 1000),
479
+ "%d of %d%s" % (n, len(s.turns), ", the oldest cut" if cut else ""), mapped, eps))
480
+ return "\n".join(rows)
481
+
482
+
483
+ def tokens_for(flag, s=None):
484
+ """The level in force and its tokens; a bad level ends the run with the reason"""
485
+ level = level_in_force(flag)
486
+ try:
487
+ return level, budget(level, s)
488
+ except ValueError as e:
489
+ sys.exit(str(e))
490
+
491
+
492
+ def squeeze(text, keep, node):
493
+ """A turn cut to about `keep` characters: two fifths from its start, the rest from its end, and where to open it"""
494
+ head = text[:keep * 2 // 5]
495
+ tail = text[len(text) - (keep - len(head)):]
496
+ return "%s\n(… %d characters left out here: open %s for all of it)\n%s" % (head, len(text) - keep, node, tail)
497
+
498
+
499
+ def fold(s, tokens):
500
+ """The folded view in about `tokens` tokens: the map (its newest episodes, if it must be cut, in at most half the
501
+ room), then as many recent turns word for word as fit. None: every turn, tool calls still folded to a line.
502
+ Returns (text, turns shown word for word, whether the oldest of them was cut short, episodes on the map)."""
503
+ eps = s.episodes()
504
+ start = s.turns[0].t0 if s.turns else None
505
+ end = s.turns[-1].t1 if s.turns else None
506
+ out = ["# Session %s · %s · %s to %s · %d turns in %d episodes"
507
+ % (s.id[:8], short(s.cwd), stamp(start), stamp(end), len(s.turns), len(eps)),
508
+ "Folded, nothing lost. Open a node with `%s open %s <node>`: e3 is an episode, t12 a turn, t12.3 one tool "
509
+ "call with its full input and output." % (ME, s.id[:8])]
510
+ named = load_titles(s.id)
511
+ lines_ = [episode_line(i, ep, named.get(span(ep))) for i, ep in enumerate(eps, 1)]
512
+ if tokens is None:
513
+ body = ["", "## Map"] + lines_ + ["", "## Every turn"] + [render_turn(t) for t in s.turns]
514
+ return "\n".join(out + body), len(s.turns), False, len(lines_)
515
+ room = tokens * CHARS - len("\n".join(out)) - 80
516
+ mapped, used = [], 0
517
+ for line in reversed(lines_):
518
+ if mapped and used + len(line) + 1 > room / 2:
519
+ break
520
+ mapped.append(line)
521
+ used += len(line) + 1
522
+ older = len(lines_) - len(mapped)
523
+ if older:
524
+ note = "e1 to e%d: %d older episode%s; `show --level max` lists them all" % (older, older, "s"[:older > 1])
525
+ mapped.append(note)
526
+ used += len(note) + 1
527
+ room -= used
528
+ shown, cut = [], False
529
+ for turn in reversed(s.turns):
530
+ text = render_turn(turn)
531
+ if len(text) + 1 <= room:
532
+ shown.append(text)
533
+ room -= len(text) + 1
534
+ continue
535
+ # A turn too big for what's left goes in cut to fit, rather than leave the room unused: its start (the ask)
536
+ # and its end (where it got to). The latest turn always shows, however little room there is.
537
+ if room > 1500 or (not shown and room > 400):
538
+ shown.append(squeeze(text, room - 120, turn.node))
539
+ cut = True
540
+ break
541
+ body = ["", "## Map"] + mapped[::-1]
542
+ if shown:
543
+ title = "## Every turn" if len(shown) == len(s.turns) and not cut else \
544
+ "## The last %d turn%s, word for word" % (len(shown), "s"[:len(shown) > 1])
545
+ body += ["", title] + shown[::-1]
546
+ return "\n".join(out + body), len(shown), cut, len(lines_) - older
547
+
548
+
549
+ def open_node(s, node):
550
+ x = s.find(node)
551
+ if x is None:
552
+ return None
553
+ if isinstance(x, list):
554
+ return "\n\n".join([episode_line(int(node[1:]), x)] + [render_turn(t) for t in x])
555
+ if isinstance(x, Turn):
556
+ return render_turn(x, notes=True)
557
+ where = "%s, line %d" % (short(s.path, 120), x.line) + \
558
+ (", result at line %d" % x.result_line if x.result_line else "")
559
+ return "\n".join(["### %s %s (%s)" % (x.node, x.name, where), "input:",
560
+ json.dumps(x.args, indent=1, ensure_ascii=False),
561
+ "output%s:" % (" (an error)" if x.error else ""),
562
+ x.result if x.result is not None else "(no result recorded)"])
563
+
564
+
565
+ def search(s, pattern, most=50):
566
+ rx = re.compile(pattern, re.I)
567
+ hits = []
568
+
569
+ def look(node, where, text):
570
+ m = rx.search(text or "")
571
+ if m:
572
+ hits.append("%s %s: %s" % (node, where, one_line(text[max(0, m.start() - 120):m.end() + 120], 300)))
573
+
574
+ for turn in s.turns:
575
+ look(turn.node, turn.who, turn.words)
576
+ for kind, x in turn.items:
577
+ if kind == "text":
578
+ look(turn.node, "agent", x)
579
+ else:
580
+ look(x.node, "input", json.dumps(x.args, ensure_ascii=False))
581
+ look(x.node, "output", x.result)
582
+ for _, words in turn.notes:
583
+ look(turn.node, "note", words)
584
+ return hits[:most] + (["… and %d more" % (len(hits) - most)] if len(hits) > most else [])
585
+
586
+
587
+ def prime(s, tokens=8000):
588
+ """The opening message for a new session, in about `tokens` tokens (None: every turn). Returns what fold does."""
589
+ intro = ("You are picking up work from an earlier Claude Code session (%s, in %s). Its whole history is kept. What "
590
+ "follows is a folded view of it: a map of its episodes, then its last turns word for word. When something "
591
+ "from the past matters, open the node it came from rather than guess:\n %s open %s <node>\n"
592
+ "and search the whole history with:\n %s search %s '<words or regex>'\n"
593
+ "Files may have changed since, so read them fresh rather than trusting an old copy.\n\n"
594
+ % (s.id[:8], short(s.cwd), ME, s.id[:8], ME, s.id[:8]))
595
+ text, *rest = fold(s, None if tokens is None else max(500, tokens - len(intro) // CHARS))
596
+ return (intro + text, *rest)
597
+
598
+
599
+ def live():
600
+ """The sessions running on this machine now, from runwatch (an optional session watcher): session id -> its row.
601
+ Empty without it."""
602
+ exe = shutil.which("runwatch") or os.path.expanduser("~/.local/bin/runwatch")
603
+ try:
604
+ out = subprocess.run([exe, "ps", "--json", "--here"], capture_output=True, text=True, timeout=8).stdout
605
+ rows = json.loads(out)
606
+ except (OSError, ValueError, subprocess.SubprocessError):
607
+ return {}
608
+ rows = rows.get("sessions", []) if isinstance(rows, dict) else rows
609
+ return {r["session"]: r for r in rows if isinstance(r, dict) and r.get("session")}
610
+
611
+
612
+ def where_it_runs(row):
613
+ reach = row.get("reach") if isinstance(row.get("reach"), dict) else {}
614
+ if reach.get("kind") == "tmux":
615
+ return "in tmux session %s" % str(reach.get("target") or "?").split(":")[0]
616
+ if reach.get("kind") == "window":
617
+ return "in a terminal of its own"
618
+ return "in the background"
619
+
620
+
621
+ def usd(amount):
622
+ return ", about $%.2f at list price" % amount if amount is not None else ""
623
+
624
+
625
+ def ways_back(s, level, now=None, opening=None):
626
+ """The two ways back to a session, and which is cheaper now: straight back (a re-read while the cache is warm, a
627
+ re-cache of the whole window once it has cooled) or a fresh start from the folded view."""
628
+ now = now or time.time()
629
+ if opening is None:
630
+ opening = len(prime(s, budget(level, s))[0]) // CHARS
631
+ left = TTL - (now - s.last_active())
632
+ write, read = WRITE.get(s.model or ""), READ.get(s.model or "")
633
+ rate = read if left > 0 else write
634
+ fresh = start_tokens(os.path.dirname(s.path)) + opening
635
+ back_usd = s.window * rate / 1e6 if rate else None
636
+ fresh_usd = fresh * write / 1e6 if write else None
637
+ back_first = back_usd < fresh_usd if back_usd is not None and fresh_usd is not None else left > 0
638
+ return {"warm_minutes": int(left // 60 + 1) if left > 0 else 0, "back_usd": back_usd, "fresh": fresh,
639
+ "fresh_usd": fresh_usd, "back_first": back_first}
640
+
641
+
642
+ def card(s, level, running=None, named=False):
643
+ """Where you left off, in plain words, and what each way back costs. `running` is live()'s answer; `named` when the
644
+ session was asked for by id, so its commands name it too."""
645
+ now, last = time.time(), s.last_active()
646
+ eps = s.episodes()
647
+ # the latest stretch of work you spoke in: an agent left running can end on stretches of background notices
648
+ mine = next((ep for ep in reversed(eps) if any(t.who == "you" for t in ep)), eps[-1] if eps else None)
649
+ task = task_of(mine) if mine else None
650
+ me = (lambda verb: "%s %s %s" % (YOU, verb, s.id[:8])) if named else (lambda verb: "%s %s" % (YOU, verb))
651
+ latest = next((t for t in reversed(s.turns) if t.who == "you"), None)
652
+ opening = len(prime(s, budget(level, s))[0]) // CHARS
653
+ out = ["%s: your last session here (%s) was active %s, %s." % (
654
+ os.path.basename(s.cwd or "?"), s.id[:8], stamp(last), ago(now - last))]
655
+ if task:
656
+ out.append('The task: "%s"' % one_line(heading_words(task), 150))
657
+ if latest and latest is not task:
658
+ out.append('Last you said: "%s"' % one_line(heading_words(latest), 150))
659
+ row = (running or {}).get(s.id)
660
+ if row:
661
+ state = {"working": "working on it right now", "needs-input": "waiting for you",
662
+ "done": "done and waiting for your next message"}.get(row.get("state"), row.get("state") or "open")
663
+ out.append("It's still open %s, %s." % (where_it_runs(row), state))
664
+ w = ways_back(s, level, now, opening)
665
+ if not s.window:
666
+ out += ["", " %s start a new session from the folded view" % me("resume")]
667
+ elif w["back_first"]:
668
+ out += ["", "Cheaper now: go straight back while its cache is warm, about %d more minutes%s."
669
+ % (w["warm_minutes"], ": about $%.2f to re-read %dk tokens" % (w["back_usd"], s.window // 1000)
670
+ if w["back_usd"] is not None else ""),
671
+ " " + ("switch to it %s" % where_it_runs(row) if row else "claude --resume %s" % s.id),
672
+ "Starting fresh from the folded view instead: about %dk tokens%s." % (w["fresh"] // 1000, usd(w["fresh_usd"]))]
673
+ else:
674
+ out += ["", "Cheaper now: start fresh from the folded view: about %dk tokens%s, with every word still reachable."
675
+ % (w["fresh"] // 1000, usd(w["fresh_usd"])),
676
+ " " + me("resume"),
677
+ "Going back instead %s: %dk tokens%s." % (
678
+ "re-caches its whole window" if w["warm_minutes"] <= 0 else "re-reads its window",
679
+ s.window // 1000, usd(w["back_usd"]))]
680
+ out += ["", " %s read the folded view yourself" % me("show"),
681
+ " %s level see or change how much it holds (now %s)" % (YOU, level)]
682
+ return "\n".join(out)
683
+
684
+
685
+ def tail(path, size=262144):
686
+ """The end of a session's log, read fast: when it last worked, its window and model, its folder and the last thing
687
+ a person said. Enough to tell warm from cooled without reading the whole file."""
688
+ info = {"last": None, "window": 0, "model": None, "cwd": None, "said": ""}
689
+ with open(path, "rb") as f:
690
+ f.seek(0, 2)
691
+ end = f.tell()
692
+ f.seek(max(0, end - size))
693
+ chunk = f.read().decode("utf-8", "replace").splitlines()
694
+ for line in reversed(chunk[1:] if end > size else chunk): # the first line of a cut chunk is half a line
695
+ try:
696
+ e = json.loads(line)
697
+ except ValueError:
698
+ continue
699
+ if not isinstance(e, dict) or e.get("isSidechain"):
700
+ continue
701
+ info["cwd"] = info["cwd"] or e.get("cwd")
702
+ message = e.get("message") if isinstance(e.get("message"), dict) else {}
703
+ if e.get("type") in ("user", "assistant") and info["last"] is None:
704
+ info["last"] = when(e)
705
+ usage = message.get("usage")
706
+ if e.get("type") == "assistant" and not info["model"] and isinstance(usage, dict) and \
707
+ message.get("model") not in (None, "<synthetic>"):
708
+ info["window"] = sum(usage.get(k) or 0 for k in
709
+ ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"))
710
+ info["model"] = message["model"]
711
+ if e.get("type") == "user" and not info["said"] and starter(e) == "you":
712
+ info["said"] = text_of(message.get("content"))
713
+ if info["last"] and info["model"] and info["said"] and info["cwd"]:
714
+ break
715
+ info["last"] = info["last"] or os.path.getmtime(path)
716
+ return info
717
+
718
+
719
+ def span(turns):
720
+ return "%s-%s" % (turns[0].node, turns[-1].node)
721
+
722
+
723
+ def titles_file():
724
+ return os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), "ctxtree", "titles.json")
725
+
726
+
727
+ def load_titles(sid):
728
+ try:
729
+ with open(titles_file()) as f:
730
+ return json.load(f).get(sid, {})
731
+ except (OSError, ValueError):
732
+ return {}
733
+
734
+
735
+ def make_titles(s, run=None):
736
+ """Names for a session's stretches of work, a few words each, from Claude (Haiku) through your own claude command:
737
+ one call for every stretch not yet named. Opt-in: it sends each stretch's opening words and a few tool calls,
738
+ masked. Returns (the titles, how many were new, the call's usage)."""
739
+ have = load_titles(s.id)
740
+ todo = [(i, ep) for i, ep in enumerate(s.episodes(), 1) if span(ep) not in have]
741
+ if not todo:
742
+ return have, 0, {}
743
+ blocks = []
744
+ for i, ep in todo:
745
+ said = [one_line(heading_words(t), 200) for t in ep if t.who == "you"][:5]
746
+ calls = [gist(c) for t in ep for c in t.calls()][:8]
747
+ blocks.append("## e%d\n%s" % (i, masked("\n".join(said + calls))[:1500]))
748
+ ask = ("Each block below is a stretch of work from a coding session. Give each a title of 3 to 6 plain words that "
749
+ "says what was done. Reply with JSON only: an object from the block's name (e1, e2, ...) to its title.\n\n"
750
+ + "\n\n".join(blocks))
751
+ run = run or (lambda text: subprocess.run(
752
+ # no tools and no MCP servers: with tools off, Claude Code sends every MCP tool's full description instead of
753
+ # loading them on demand (measured here: 247k tokens for a two-word prompt, 4.5k without them)
754
+ ["claude", "-p", "--model", "claude-haiku-5-5", "--no-session-persistence", "--tools", "", "--strict-mcp-config",
755
+ "--mcp-config", '{"mcpServers":{}}', "--output-format", "json"], input=text, capture_output=True, text=True, timeout=300, cwd=os.path.expanduser("~")).stdout)
756
+ reply = json.loads(run(ask))
757
+ text = reply.get("result") or ""
758
+ got = json.loads(text[text.index("{"):text.rindex("}") + 1])
759
+ new = {span(ep): one_line(str(got["e%d" % i]), 60) for i, ep in todo if got.get("e%d" % i)}
760
+ try:
761
+ with open(titles_file()) as f:
762
+ everything = json.load(f)
763
+ except (OSError, ValueError):
764
+ everything = {}
765
+ everything.setdefault(s.id, {}).update(new)
766
+ os.makedirs(os.path.dirname(titles_file()), exist_ok=True)
767
+ with open(titles_file(), "w") as f:
768
+ json.dump(everything, f)
769
+ return everything[s.id], len(new), reply.get("usage") or {}
770
+
771
+
772
+ def cache_file():
773
+ home = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")
774
+ return os.path.join(home, "ctxtree", "openings-v2.json")
775
+
776
+
777
+ def start_tokens(folder):
778
+ """Tokens a new session in this folder holds at its first reply (Claude Code's system prompt and tools, plus what
779
+ start-up hooks add there), the middle of its recent sessions; START when there are fewer than 3 to go by. A first
780
+ reply over 150k is a resumed session, not a fresh start, and is left out."""
781
+ sizes = []
782
+ for path in sorted(glob.glob(os.path.join(folder, "*.jsonl")), key=os.path.getmtime, reverse=True)[:12]:
783
+ try:
784
+ with open(path, errors="replace") as f:
785
+ for line in f:
786
+ if '"usage"' not in line:
787
+ continue
788
+ e = json.loads(line)
789
+ m = e.get("message") if isinstance(e.get("message"), dict) else {}
790
+ u = m.get("usage")
791
+ if e.get("type") == "assistant" and not e.get("isSidechain") and isinstance(u, dict) and \
792
+ m.get("model") != "<synthetic>":
793
+ size = sum(u.get(k) or 0 for k in
794
+ ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"))
795
+ if 0 < size < 150000:
796
+ sizes.append(size)
797
+ break
798
+ except (OSError, ValueError):
799
+ continue
800
+ sizes.sort()
801
+ return sizes[len(sizes) // 2] if len(sizes) >= 3 else START
802
+
803
+
804
+ def opening_tokens(path, level):
805
+ """Tokens a fresh start from this session holds (Claude Code's own start plus the opening). Remembered per file
806
+ size and level, so a session that has stopped changing is read in full once. The file keeps only numbers."""
807
+ key, st = os.path.realpath(path), os.stat(path)
808
+ try:
809
+ with open(cache_file()) as f:
810
+ known = json.load(f)
811
+ except (OSError, ValueError):
812
+ known = {}
813
+ if known.get(key, [])[:3] == [st.st_size, int(st.st_mtime), level]:
814
+ return known[key][3]
815
+ s = Session(path)
816
+ tokens = start_tokens(os.path.dirname(path)) + len(prime(s, budget(level, s))[0]) // CHARS
817
+ known = {k: v for k, v in known.items() if os.path.exists(k)}
818
+ known[key] = [st.st_size, int(st.st_mtime), level, tokens]
819
+ os.makedirs(os.path.dirname(cache_file()), mode=0o700, exist_ok=True)
820
+ with open(cache_file() + ".new", "w") as f:
821
+ json.dump(known, f)
822
+ os.replace(cache_file() + ".new", cache_file())
823
+ return tokens
824
+
825
+
826
+ def status_of(path, level, now=None):
827
+ """Warm or cooled, and what each way back costs at list price, from the end of the log (and, for a cooled
828
+ session, the size of its fresh start)"""
829
+ now, i = now or time.time(), tail(path)
830
+ read, write = READ.get(i["model"] or ""), WRITE.get(i["model"] or "")
831
+ money = lambda tokens, price: round(tokens * price / 1e6, 2) if price else None # noqa: E731
832
+ out = {"session": os.path.basename(path)[:-len(".jsonl")], "cwd": i["cwd"], "last": int(i["last"]), "ttl": TTL,
833
+ "window": i["window"], "model": i["model"], "said": one_line(i["said"], 200),
834
+ "warm_usd": money(i["window"], read), "cold_usd": money(i["window"], write),
835
+ "fresh_tokens": None, "fresh_usd": None}
836
+ if i["last"] + TTL <= now and i["window"] >= 20000:
837
+ try:
838
+ out["fresh_tokens"] = opening_tokens(path, level)
839
+ out["fresh_usd"] = money(out["fresh_tokens"], write)
840
+ except (OSError, ValueError):
841
+ pass
842
+ return out
843
+
844
+
845
+ def hook(event, now=None):
846
+ """What the plugin's SessionStart hook says, if anything. Resuming a big session whose cache has cooled: a word to
847
+ you about the cheaper way back. Starting a new session where the last one has cooled: a note for Claude that the
848
+ earlier work is kept and how to search it. After a compaction: that every compacted turn still opens. After /clear
849
+ on a big session: its folded map, for Claude to read if the work carries on. Otherwise nothing."""
850
+ now = now or time.time()
851
+ if event.get("source") == "resume":
852
+ tokens, path = event.get("context_tokens") or 0, event.get("transcript_path") or ""
853
+ if event.get("prompt_cache_likely_expired") and tokens >= 100000 and os.path.exists(path):
854
+ fresh, usd = opening_tokens(path, level_in_force()), event.get("estimated_cache_write_usd")
855
+ return {"systemMessage": "Picking this session up re-caches %dk tokens%s. To start fresh from its folded "
856
+ "history instead (about %dk tokens, every word still reachable), quit and run: "
857
+ "%s resume %s" % (tokens // 1000, ", about $%.2f" % usd if usd else "",
858
+ fresh // 1000, YOU, os.path.basename(path)[:8])}
859
+ return None
860
+ if event.get("source") == "compact":
861
+ sid = (event.get("session_id") or os.path.basename(event.get("transcript_path") or "")[:-len(".jsonl")])[:8]
862
+ if not sid:
863
+ return None
864
+ note = ("This session was just compacted, but nothing before it is lost: every turn and tool call is kept word "
865
+ "for word. When a detail matters (a decision and its reason, an error, a number), find it with "
866
+ "`%s search %s '<regex>'` and open the node a hit names with `%s open %s <node>` rather than trusting "
867
+ "the summary; `%s show %s` maps the session." % (ME, sid, ME, sid, ME, sid))
868
+ return {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": note}}
869
+ if event.get("source") == "clear":
870
+ return after_clear(event, now)
871
+ if event.get("source") != "startup":
872
+ return None
873
+ folder = os.path.join(ROOT, folder_key(os.path.abspath(event.get("cwd") or os.getcwd())))
874
+ others = sorted((p for p in glob.glob(os.path.join(folder, "*.jsonl")) if os.path.getsize(p) > 2000 and
875
+ os.path.basename(p)[:-len(".jsonl")] != event.get("session_id")), key=os.path.getmtime)
876
+ if not others:
877
+ return None
878
+ i = tail(others[-1])
879
+ age = now - i["last"]
880
+ if age <= TTL or age > 14 * 86400 or i["window"] < 100000:
881
+ return None
882
+ note = ("Earlier work in this folder is kept in full and can be searched. The last session here (%s, %s) ended "
883
+ "on: \"%s\". When the user refers to earlier work, find it with `%s search --here '<regex>'`, then open "
884
+ "the node a hit names with `%s open <session> <node>`; `%s show <session>` maps a session."
885
+ % (os.path.basename(others[-1])[:8], ago(age), one_line(i["said"], 160), ME, ME, ME))
886
+ return {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": note}}
887
+
888
+
889
+ def after_clear(event, now):
890
+ """After /clear: if the session just cleared here was big, its folded map, ready for the fresh session to read if
891
+ the next message carries on that work. Nothing is read unless it's needed."""
892
+ found = [p for p in here(event.get("cwd")) if os.path.basename(p)[:-len(".jsonl")] != event.get("session_id")]
893
+ if not found:
894
+ return None
895
+ i = tail(found[0])
896
+ if now - i["last"] > 600 or i["window"] < 100000: # cleared just now, and big enough to be worth carrying over
897
+ return None
898
+ s = Session(found[0])
899
+ path = write_opening(s, budget(level_in_force(), s))
900
+ task = task_of(next((ep for ep in reversed(s.episodes()) if any(t.who == "you" for t in ep)), s.turns))
901
+ note = ("The user just ran /clear on session %s here (%dk tokens; its task: \"%s\"). If their next message carries "
902
+ "on that work, read %s first: a folded, lossless map of it, with how to open any part word for word. If they "
903
+ "are starting something new, ignore it." % (s.id[:8], i["window"] // 1000, one_line(heading_words(task), 120),
904
+ path))
905
+ return {"systemMessage": "ctxtree: the folded map of the session you cleared is ready, if you carry on with it.",
906
+ "hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": note}}
907
+
908
+
909
+ SECRETS = re.compile("|".join([
910
+ r"sk-ant-[A-Za-z0-9_\-]{20,}", r"\bsk-(?:proj-)?[A-Za-z0-9]{20,}", r"\bgh[pousr]_[A-Za-z0-9]{30,}",
911
+ r"\bgithub_pat_[A-Za-z0-9_]{40,}", r"\bAKIA[0-9A-Z]{16}\b", r"\bxox[abprs]-[A-Za-z0-9\-]{10,}",
912
+ r"\b[rs]k_live_[A-Za-z0-9]{20,}", r"\bAIza[0-9A-Za-z_\-]{35}\b", r"\bnpm_[A-Za-z0-9]{36}\b",
913
+ r"\bpypi-[A-Za-z0-9_\-]{50,}", r"\beyJ[A-Za-z0-9_\-]{10,}\.eyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}",
914
+ r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)",
915
+ r"(?i:(?<=password=)|(?<=secret=)|(?<=token=))[^\s'\"&]{8,}"]))
916
+
917
+
918
+ def masked(text):
919
+ """A view with anything shaped like a key, token or private key masked. open still gives the exact text."""
920
+ return SECRETS.sub("[masked: open its node for the exact text]", text)
921
+
922
+
923
+ def write_opening(s, tokens):
924
+ """The opening message, in a file only you can read (it can be bigger than a command line holds)"""
925
+ path = os.path.join(state_dir(), "opening-%s.md" % s.id[:8])
926
+ with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
927
+ f.write(masked(prime(s, tokens)[0]))
928
+ os.chmod(path, 0o600)
929
+ return path
930
+
931
+
932
+ def state_dir():
933
+ d = os.path.join(os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"), "ctxtree")
934
+ os.makedirs(d, mode=0o700, exist_ok=True)
935
+ return d
936
+
937
+
938
+ def resume(s, tokens, dry=False, upto=None, level=None):
939
+ """Start Claude Code in the session's folder, told to read the folded view first. The view goes in a private file
940
+ (it can be bigger than a command line holds)."""
941
+ path = write_opening(s, tokens)
942
+ ask = ("Read %s first, all of it: it is a folded view of an earlier session in this folder (%s), whose work you are "
943
+ "picking up%s. Then say in two lines where it left off, and wait for my next message."
944
+ % (path, s.id[:8], " from before turn %s" % upto if upto else ""))
945
+ folder = s.cwd if s.cwd and os.path.isdir(s.cwd) else os.getcwd()
946
+ if dry:
947
+ print("cd %s && claude %s" % (shlex.quote(folder), shlex.quote(ask)))
948
+ return 0
949
+ if not shutil.which("claude"):
950
+ sys.exit("claude isn't on your PATH. The opening is in %s" % path)
951
+ w = ways_back(s, level or "auto", opening=len(open(path).read()) // CHARS)
952
+ if s.window and w["fresh_usd"] is not None and w["back_usd"] is not None:
953
+ print("Starting fresh: about %dk tokens, $%.2f at list price, against $%.2f to go back%s." % (
954
+ w["fresh"] // 1000, w["fresh_usd"], w["back_usd"],
955
+ " (it's still warm, so going back was the cheaper way)" if w["back_first"] else ""))
956
+ os.chdir(folder)
957
+ os.execvp("claude", ["claude", ask])
958
+
959
+
960
+ def check(s):
961
+ """Every tool call and every tool result in the file opens, and opens to exactly the text the file holds"""
962
+ uses, results = set(), {}
963
+ codex = {}
964
+ for line_no, e in entries(s.path, codex):
965
+ if e.get("isSidechain") or e.get("type") not in ("user", "assistant"):
966
+ continue
967
+ content = (e.get("message") or {}).get("content") if isinstance(e.get("message"), dict) else None
968
+ for x in content if isinstance(content, list) else []:
969
+ if isinstance(x, dict) and x.get("type") == "tool_use":
970
+ uses.add(x.get("id"))
971
+ elif isinstance(x, dict) and x.get("type") == "tool_result":
972
+ results[x.get("tool_use_id")] = (line_no, text_of(x.get("content")))
973
+ calls = {c.id: c for t in s.turns for c in t.calls()}
974
+ missing = uses - set(calls)
975
+ unopened = [k for k in results if k not in calls]
976
+ wrong = [k for k, (line_no, body) in results.items() if k in calls and
977
+ (calls[k].result != body or calls[k].result_line != line_no)]
978
+ return {"calls": len(uses), "results": len(results), "missing_calls": len(missing),
979
+ "unopened_results": len(unopened), "wrong_results": len(wrong)}
980
+
981
+
982
+ def folder_key(path):
983
+ """The name Claude Code gives a folder's sessions directory: every character but letters and digits becomes -"""
984
+ return re.sub(r"[^A-Za-z0-9]", "-", path)
985
+
986
+
987
+ def here(cwd=None):
988
+ """This folder's sessions, newest first, leaving out empty ones and the Claude Code session this runs inside"""
989
+ d = os.path.join(ROOT, folder_key(os.path.abspath(cwd or os.getcwd())))
990
+ me = os.environ.get("CLAUDE_CODE_SESSION_ID")
991
+ return [p for p in sorted(glob.glob(os.path.join(d, "*.jsonl")), key=os.path.getmtime, reverse=True)
992
+ if os.path.getsize(p) > 2000 and os.path.basename(p)[:-len(".jsonl")] != me]
993
+
994
+
995
+ def newest_here(cwd=None):
996
+ found = here(cwd)
997
+ if not found:
998
+ sys.exit("No Claude Code sessions for this folder. Run it in a project folder, or name a session.")
999
+ return found[0]
1000
+
1001
+
1002
+ def find_session(arg):
1003
+ """A session's log by id, id prefix (6 or more characters) or path; None when not exactly one matches"""
1004
+ if arg.endswith(".jsonl") and os.path.exists(arg):
1005
+ return arg
1006
+ found = glob.glob(os.path.join(ROOT, "*", glob.escape(arg) + "*.jsonl")) if len(arg) >= 6 else []
1007
+ if not found and len(arg) >= 6: # a Codex CLI session, by the id at the end of its file's name
1008
+ found = glob.glob(os.path.join(CODEX, "**", "*" + glob.escape(arg) + "*.jsonl"), recursive=True)
1009
+ return found[0] if len(found) == 1 else None
1010
+
1011
+
1012
+ def locate(arg):
1013
+ if not arg:
1014
+ return newest_here()
1015
+ path = find_session(arg)
1016
+ if not path:
1017
+ sys.exit("No single session matches %r; give 6 or more characters of its id, or its path" % arg)
1018
+ return path
1019
+
1020
+
1021
+ def recent_paths(days, project=None):
1022
+ since = time.time() - days * 86400
1023
+ return sorted((p for p in glob.glob(os.path.join(ROOT, "*", "*.jsonl"))
1024
+ if os.path.getmtime(p) >= since and (not project or project in os.path.dirname(p))),
1025
+ key=os.path.getmtime)
1026
+
1027
+
1028
+ def main(argv):
1029
+ if argv[:1] in (["-h"], ["--help"]):
1030
+ print(__doc__.strip())
1031
+ return 0
1032
+ head, rest = __doc__.split("\n\n", 1)
1033
+ ap = argparse.ArgumentParser(prog="ctxtree", description=head, epilog=rest,
1034
+ formatter_class=argparse.RawDescriptionHelpFormatter, usage="ctxtree [COMMAND] [SESSION]")
1035
+ ap.add_argument("--version", action="version", version="ctxtree " + __version__)
1036
+ sub = ap.add_subparsers(dest="verb", metavar="COMMAND")
1037
+ upto = argparse.ArgumentParser(add_help=False)
1038
+ upto.add_argument("--upto", help="see the session only as it stood before this turn, such as t29")
1039
+ lv = argparse.ArgumentParser(add_help=False)
1040
+ lv.add_argument("--level", help="auto, low, medium, high, xhigh, max, or a size such as 30k (tokens)")
1041
+ for verb, parents in (("card", [upto, lv]), ("show", [upto, lv]), ("prime", [upto, lv]), ("levels", [upto])):
1042
+ p = sub.add_parser(verb, parents=parents)
1043
+ p.add_argument("session", nargs="?")
1044
+ if verb == "show":
1045
+ p.add_argument("--opening", action="store_true", help="the exact opening message a new session gets")
1046
+ p = sub.add_parser("resume", parents=[lv, upto])
1047
+ p.add_argument("session", nargs="?")
1048
+ p.add_argument("--dry-run", action="store_true", help="write the opening and print the command, but don't start")
1049
+ sub.add_parser("open", parents=[upto]).add_argument("args", nargs="+", metavar="[SESSION] NODE")
1050
+ p = sub.add_parser("search", parents=[upto])
1051
+ p.add_argument("args", nargs="+", metavar="[SESSION] PATTERN")
1052
+ p.add_argument("--here", action="store_true", help="every session in this folder from the last 30 days")
1053
+ sub.add_parser("level").add_argument("name", nargs="?")
1054
+ p = sub.add_parser("status", parents=[lv])
1055
+ p.add_argument("session", nargs="*")
1056
+ p.add_argument("--json", action="store_true")
1057
+ sub.add_parser("hook")
1058
+ p = sub.add_parser("sessions")
1059
+ p.add_argument("--days", type=float, default=7)
1060
+ p.add_argument("--project")
1061
+ p.add_argument("--min", type=float, default=1.0, help="leave out sessions under this many million characters")
1062
+ sub.add_parser("titles").add_argument("session", nargs="?")
1063
+ sub.add_parser("statusline")
1064
+ sub.add_parser("mcp")
1065
+ p = sub.add_parser("report")
1066
+ p.add_argument("--days", type=float, default=7)
1067
+ p.add_argument("--json", action="store_true")
1068
+ p = sub.add_parser("check")
1069
+ p.add_argument("session", nargs="*")
1070
+ p.add_argument("--all", action="store_true")
1071
+ p.add_argument("--days", type=float, default=7)
1072
+ if argv and not argv[0].startswith("-") and argv[0] not in sub.choices:
1073
+ argv = ["card"] + list(argv) # ctxtree <session>: that session's card
1074
+ a = ap.parse_args(argv)
1075
+
1076
+ if a.verb == "hook":
1077
+ try:
1078
+ out = hook(json.loads(sys.stdin.read() or "{}"))
1079
+ except Exception: # noqa: BLE001 - a hook must never get in the way of a session starting
1080
+ out = None
1081
+ if out:
1082
+ print(json.dumps(out))
1083
+ return 0
1084
+ if a.verb == "status":
1085
+ level = level_in_force(a.level)
1086
+ paths = [p for p in map(find_session, a.session) if p] if a.session else here()[:1]
1087
+ rows = [status_of(p, level) for p in paths]
1088
+ if not rows and not a.json:
1089
+ print("No other Claude Code session in this folder to say anything about.")
1090
+ if a.json:
1091
+ print(json.dumps(rows))
1092
+ for r in rows if not a.json else []:
1093
+ left = r["last"] + r["ttl"] - time.time()
1094
+ print("%s %-16s %s window %dk%s" % (
1095
+ r["session"][:8], os.path.basename(r["cwd"] or "?")[:16],
1096
+ "warm %dm" % (left // 60 + 1) if left > 0 else "cooled %s" % ago(-left),
1097
+ r["window"] // 1000, " back $%.2f, fresh $%.2f" % (r["cold_usd"], r["fresh_usd"])
1098
+ if left <= 0 and r["cold_usd"] is not None and r["fresh_usd"] is not None else ""))
1099
+ return 0
1100
+ if a.verb == "search" and a.here:
1101
+ print(search_here(os.getcwd(), a.args[-1]))
1102
+ return 0
1103
+ if a.verb == "mcp":
1104
+ mcp(sys.stdin, sys.stdout)
1105
+ return 0
1106
+ if a.verb == "sessions":
1107
+ level = level_in_force()
1108
+ print("Opening at level %s. words: every turn folded, as a share of the whole history." % level)
1109
+ print("%-8s %-16s %-12s %5s %8s %7s %7s %7s" %
1110
+ ("session", "folder", "last", "turns", "history", "words", "window", "opening"))
1111
+ shown = 0
1112
+ for path in recent_paths(a.days, a.project):
1113
+ s = Session(path)
1114
+ if s.chars < a.min * 1e6 or not s.turns:
1115
+ continue
1116
+ print("%-8s %-16s %-12s %5d %7.1fM %6.1f%% %6dk %6.1fk" % (
1117
+ s.id[:8], os.path.basename(s.cwd or "?")[:16], stamp(os.path.getmtime(path)), len(s.turns),
1118
+ s.chars / 1e6, 100 * len(fold(s, None)[0]) / s.chars, s.window / 1e3,
1119
+ len(prime(s, tokens_for(level, s)[1])[0]) / (CHARS * 1000)))
1120
+ shown += 1
1121
+ if not shown:
1122
+ print("(none yet: no session in the last %d days has a history over %gM characters)" % (a.days, a.min))
1123
+ return 0
1124
+ if a.verb == "level":
1125
+ if a.name:
1126
+ try:
1127
+ budget(a.name)
1128
+ except ValueError as e:
1129
+ sys.exit(str(e))
1130
+ os.makedirs(os.path.dirname(config_path()), exist_ok=True)
1131
+ with open(config_path(), "w") as f:
1132
+ f.write("# ctxtree: how much the opening message holds. auto, low, medium, high, xhigh, max or a "
1133
+ "size such as 30k.\nlevel = %s\n" % a.name)
1134
+ print(slider(a.name))
1135
+ print("Saved in %s. --level or CTXTREE_LEVEL still win for one run." % short(config_path(), 120))
1136
+ else:
1137
+ level = level_in_force()
1138
+ source = "CTXTREE_LEVEL" if os.environ.get("CTXTREE_LEVEL") else \
1139
+ short(config_path(), 120) if os.path.exists(config_path()) else "the default"
1140
+ found = here()
1141
+ s = Session(found[0]) if found else None
1142
+ print(slider(level, s))
1143
+ if s is not None:
1144
+ print("\nWhat each would hold for the session here (%s):\n%s" % (s.id[:8], levels_table(s, level)))
1145
+ print("\nFrom %s. Change it with: %s level <%s|30k>" % (source, YOU, "|".join(NAMES)))
1146
+ return 0
1147
+ if a.verb == "statusline":
1148
+ try:
1149
+ print(statusline(json.loads(sys.stdin.read() or "{}")))
1150
+ except Exception: # noqa: BLE001 - a status line must never show an error
1151
+ print("")
1152
+ return 0
1153
+ if a.verb == "report":
1154
+ r = report(a.days)
1155
+ print(json.dumps(r) if a.json else say_report(r))
1156
+ return 0
1157
+ if a.verb == "check":
1158
+ paths = recent_paths(a.days) if a.all else [locate(x) for x in a.session] or [newest_here()]
1159
+ bad = 0
1160
+ for path in paths:
1161
+ s = Session(path)
1162
+ r = check(s)
1163
+ lost = r["missing_calls"] + r["unopened_results"] + r["wrong_results"]
1164
+ bad += lost > 0
1165
+ if lost or not a.all:
1166
+ print("%s %d calls, %d results: %d calls missing, %d results that don't open, %d that open wrong"
1167
+ % (s.id[:8], r["calls"], r["results"], r["missing_calls"],
1168
+ r["unopened_results"], r["wrong_results"]))
1169
+ print("%d of %d sessions lossless" % (len(paths) - bad, len(paths)))
1170
+ return 1 if bad else 0
1171
+
1172
+ rest = None
1173
+ if a.verb in ("open", "search"):
1174
+ if len(a.args) > 2:
1175
+ sys.exit("give at most a session and a %s" % ("node" if a.verb == "open" else "pattern"))
1176
+ session, rest = (a.args[0], a.args[1]) if len(a.args) == 2 else (None, a.args[0])
1177
+ else:
1178
+ session = getattr(a, "session", None)
1179
+ if a.verb in (None, "card") and session is None and not here():
1180
+ # The card has nothing to say yet; that isn't an error (and /ctxtree:where would fail on one)
1181
+ print("No Claude Code sessions for this folder yet. Run it in a folder where you've used Claude Code.")
1182
+ return 0
1183
+ s = Session(locate(session))
1184
+ if getattr(a, "upto", None):
1185
+ m = re.fullmatch(r"t(\d+)", a.upto)
1186
+ if not m:
1187
+ sys.exit("--upto takes a turn, such as t29")
1188
+ s.turns = s.turns[:int(m.group(1)) - 1]
1189
+ if a.verb in (None, "card"):
1190
+ print(card(s, level_in_force(getattr(a, "level", None)), live(), named=session is not None))
1191
+ elif a.verb == "resume":
1192
+ return resume(s, tokens_for(a.level, s)[1], a.dry_run, a.upto, level_in_force(a.level))
1193
+ elif a.verb == "show" and not a.opening:
1194
+ print(masked(fold(s, tokens_for(a.level, s)[1])[0]))
1195
+ elif a.verb in ("show", "prime"):
1196
+ print(masked(prime(s, tokens_for(a.level, s)[1])[0]))
1197
+ elif a.verb == "levels":
1198
+ print(levels_table(s, level_in_force()))
1199
+ if not a.upto:
1200
+ print("Its window held %dk tokens at the last reply: what coming back after a lapse re-caches."
1201
+ % (s.window // 1000))
1202
+ elif a.verb == "search":
1203
+ print(masked("\n".join(search(s, rest))) or "nothing matches")
1204
+ elif a.verb == "titles":
1205
+ if not shutil.which("claude"):
1206
+ sys.exit("titles asks Claude through your claude command, and it isn't on your PATH")
1207
+ titles, new, usage = make_titles(s)
1208
+ print("Named %d stretch%s of work (%d named in all)%s." % (
1209
+ new, "" if new == 1 else "es", len(titles), ", with %dk tokens in and %d out on Haiku" % (
1210
+ (usage.get("input_tokens", 0) + usage.get("cache_creation_input_tokens", 0)
1211
+ + usage.get("cache_read_input_tokens", 0)) // 1000, usage.get("output_tokens", 0)) if usage else ""))
1212
+ for i, ep in enumerate(s.episodes(), 1):
1213
+ print(episode_line(i, ep, titles.get(span(ep))))
1214
+ else:
1215
+ out = open_node(s, rest)
1216
+ if out is None:
1217
+ sys.exit("no node %r: try e1 (an episode), t1 (a turn) or t1.1 (a tool call)" % rest)
1218
+ print(out)
1219
+ return 0
1220
+
1221
+
1222
+ def statusline(info, now=None):
1223
+ """One line for Claude Code's status line, from the JSON it passes: how long the cache stays warm, and near the end
1224
+ what each way back will cost. Reads nothing while there's time left, since a status line runs often."""
1225
+ now = now or time.time()
1226
+ cache = info.get("prompt_cache") if isinstance(info.get("prompt_cache"), dict) else {}
1227
+ expires, tokens = cache.get("expires_at"), cache.get("recache_tokens_if_cold")
1228
+ if not expires or not tokens:
1229
+ return ""
1230
+ left = expires - now
1231
+ if left > 600:
1232
+ return "cache warm %dm" % (left // 60)
1233
+ model = info.get("model")
1234
+ model = model.get("id") if isinstance(model, dict) else model
1235
+ write, path = WRITE.get(model), info.get("transcript_path") or ""
1236
+ back = "$%.2f" % (tokens * write / 1e6) if write else "%dk tokens" % (tokens // 1000)
1237
+ fresh = ""
1238
+ if write and os.path.exists(path):
1239
+ f = start_tokens(os.path.dirname(path)) + opening_tokens(path, level_in_force())
1240
+ fresh = ", /clear starts fresh for $%.2f" % (f * write / 1e6)
1241
+ if left > 0:
1242
+ return "cache cools in %dm: then %s to come back%s" % (left // 60 + 1, back, fresh)
1243
+ return "cache cooled: the next message re-caches %s%s" % (back, fresh)
1244
+
1245
+
1246
+ def search_here(cwd, pattern, days=30):
1247
+ """Every session in a folder from the last `days`, newest first, searched; each hit names its session and node"""
1248
+ folder = os.path.join(ROOT, folder_key(os.path.abspath(cwd)))
1249
+ paths = [p for p in sorted(glob.glob(os.path.join(folder, "*.jsonl")), key=os.path.getmtime, reverse=True)
1250
+ if os.path.getsize(p) > 2000 and os.path.getmtime(p) > time.time() - days * 86400][:15]
1251
+ hits = []
1252
+ for path in paths:
1253
+ hits += ["%s %s" % (os.path.basename(path)[:8], h) for h in search(Session(path), pattern, most=20)
1254
+ if not h.startswith("…")]
1255
+ return masked("\n".join(hits[:60]) + ("\n… and %d more" % (len(hits) - 60) if len(hits) > 60 else "")
1256
+ if hits else "nothing matches")
1257
+
1258
+
1259
+ MCP_TOOLS = [
1260
+ {"name": "search", "description": "Search a folder's Claude Code sessions from the last 30 days, word for word, "
1261
+ "including turns that were compacted away. Each hit starts with its session's id and node; open a node with the "
1262
+ "open tool.", "inputSchema": {"type": "object", "required": ["pattern"], "properties": {
1263
+ "pattern": {"type": "string", "description": "a word or regular expression"},
1264
+ "folder": {"type": "string", "description": "the project folder; the server's own folder if left out"}}}},
1265
+ {"name": "open", "description": "One part of a session, word for word: e3 an episode, t12 a turn, t12.3 one tool "
1266
+ "call with its full input and output.", "inputSchema": {"type": "object", "required": ["session", "node"],
1267
+ "properties": {
1268
+ "session": {"type": "string", "description": "a session id, or its first 6 or more characters"},
1269
+ "node": {"type": "string", "description": "e3, t12 or t12.3"}}}},
1270
+ {"name": "show", "description": "A session folded: a map of its work, then its last turns word for word. The newest "
1271
+ "session in the folder if no session is given.", "inputSchema": {"type": "object", "properties": {
1272
+ "session": {"type": "string"}, "folder": {"type": "string"},
1273
+ "opening": {"type": "boolean", "description": "the exact opening message a new session would get"}}}},
1274
+ {"name": "report", "description": "How often sessions were picked up after their cache had cooled lately, and what "
1275
+ "that cost at list price.", "inputSchema": {"type": "object", "properties": {"days": {"type": "number"}}}},
1276
+ ]
1277
+
1278
+
1279
+ def session_id(value):
1280
+ """A session as an MCP client names it: an id or its start, never a path, so a client can't point it at other files"""
1281
+ value = str(value or "")
1282
+ if not re.fullmatch(r"[0-9A-Za-z-]{6,64}", value):
1283
+ raise ValueError("give a session id, or its first 6 or more characters")
1284
+ return value
1285
+
1286
+
1287
+ def mcp_call(name, args):
1288
+ if name == "search":
1289
+ return search_here(args.get("folder") or os.getcwd(), args["pattern"])
1290
+ if name == "open":
1291
+ out = open_node(Session(locate(session_id(args["session"]))), args["node"])
1292
+ if out is None:
1293
+ raise ValueError("no node %r: try e1 (an episode), t1 (a turn) or t1.1 (a tool call)" % args["node"])
1294
+ return out
1295
+ if name == "show":
1296
+ found = [locate(session_id(args["session"]))] if args.get("session") else here(args.get("folder"))
1297
+ if not found:
1298
+ raise ValueError("no Claude Code sessions for that folder")
1299
+ s = Session(found[0])
1300
+ tokens = budget(level_in_force(), s)
1301
+ return masked(prime(s, tokens)[0] if args.get("opening") else fold(s, tokens)[0])
1302
+ if name == "report":
1303
+ return say_report(report(float(args.get("days") or 7)))
1304
+ raise ValueError("no tool %r" % name)
1305
+
1306
+
1307
+ def mcp(stdin, stdout):
1308
+ """ctxtree as an MCP server on stdio: search, open, show and report. A tool that fails answers with an error; the
1309
+ server keeps going."""
1310
+ for line in stdin:
1311
+ try:
1312
+ msg = json.loads(line)
1313
+ except ValueError:
1314
+ continue
1315
+ if not isinstance(msg, dict) or msg.get("id") is None:
1316
+ continue # a notification: nothing to answer
1317
+ method, params = msg.get("method"), msg.get("params") or {}
1318
+ if method == "initialize":
1319
+ result = {"protocolVersion": params.get("protocolVersion") or "2025-06-18", "capabilities": {"tools": {}},
1320
+ "serverInfo": {"name": "ctxtree", "version": __version__}}
1321
+ elif method == "tools/list":
1322
+ result = {"tools": MCP_TOOLS}
1323
+ elif method == "tools/call":
1324
+ try:
1325
+ text, failed = mcp_call(params.get("name"), params.get("arguments") or {}), False
1326
+ except (SystemExit, ValueError, KeyError, OSError, re.error) as e:
1327
+ text, failed = str(e) or type(e).__name__, True
1328
+ result = {"content": [{"type": "text", "text": text}], "isError": failed}
1329
+ elif method == "ping":
1330
+ result = {}
1331
+ else:
1332
+ stdout.write(json.dumps({"jsonrpc": "2.0", "id": msg["id"],
1333
+ "error": {"code": -32601, "message": "no method %s" % method}}) + "\n")
1334
+ stdout.flush()
1335
+ continue
1336
+ stdout.write(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": result}) + "\n")
1337
+ stdout.flush()
1338
+
1339
+
1340
+ def report(days=7, root=None, now=None):
1341
+ """Every time a session was picked up after its cache had cooled, over the last `days`: how often, what re-caching
1342
+ cost against reading a warm cache, and the share of all usage that was, at list price. A cache lapsed when a reply
1343
+ came after the cache's life (an hour if the last write asked for one, else 5 minutes) and read much less from it
1344
+ than the reply before had left there."""
1345
+ now, root = now or time.time(), root or ROOT
1346
+ since = now - days * 86400
1347
+ spend, lapses = 0.0, []
1348
+ for path in glob.glob(os.path.join(root, "*", "*.jsonl")):
1349
+ if os.path.getmtime(path) < since:
1350
+ continue
1351
+ replies, order, folder, after_compact = {}, [], None, False
1352
+ with open(path, errors="replace") as f:
1353
+ for line in f:
1354
+ if '"assistant"' not in line and '"compact_boundary"' not in line:
1355
+ continue
1356
+ try:
1357
+ e = json.loads(line)
1358
+ except ValueError:
1359
+ continue
1360
+ if not isinstance(e, dict) or e.get("isSidechain"):
1361
+ continue
1362
+ if isinstance(e.get("cwd"), str) and not folder:
1363
+ folder = os.path.basename(e["cwd"].rstrip("/"))
1364
+ if e.get("type") == "system" and e.get("subtype") == "compact_boundary":
1365
+ after_compact = True
1366
+ continue
1367
+ m = e.get("message") if isinstance(e.get("message"), dict) else {}
1368
+ if e.get("type") != "assistant":
1369
+ continue
1370
+ mid = m.get("id") or e.get("uuid")
1371
+ if mid not in replies:
1372
+ replies[mid] = {"t": when(e), "usage": {}, "model": None, "compacted": after_compact}
1373
+ after_compact = False
1374
+ order.append(mid)
1375
+ if isinstance(m.get("usage"), dict):
1376
+ replies[mid]["usage"] = m["usage"]
1377
+ replies[mid]["model"] = m.get("model") or replies[mid]["model"]
1378
+ last = None
1379
+ for mid in order:
1380
+ r = replies[mid]
1381
+ u, t, p = r["usage"], r["t"], prices(r["model"])
1382
+ if not u or t is None or not p:
1383
+ continue
1384
+ num = lambda k: u.get(k) if isinstance(u.get(k), (int, float)) else 0
1385
+ made = u.get("cache_creation") if isinstance(u.get("cache_creation"), dict) else {}
1386
+ write, read = num("cache_creation_input_tokens"), num("cache_read_input_tokens")
1387
+ hour = min(write, made.get("ephemeral_1h_input_tokens") or 0)
1388
+ size = num("input_tokens") + read + write
1389
+ if t >= since:
1390
+ spend += (num("input_tokens") * p[0] + num("output_tokens") * p[1] + read * p[2]
1391
+ + (write - hour) * p[3] + hour * p[4]) / 1e6
1392
+ if last and t >= since and not r["compacted"]:
1393
+ gone = last["size"] - read
1394
+ if t - last["t"] > (3600 if last["hour"] else 300) and gone >= 2000 and gone * 20 > last["size"]:
1395
+ lapses.append({"folder": folder or "?", "t": t, "tokens": gone,
1396
+ "usd": gone * ((p[4] if last["hour"] else p[3]) - p[2]) / 1e6})
1397
+ last = {"t": t, "size": size, "hour": hour > 0 if write else (last["hour"] if last else False)}
1398
+ lapses.sort(key=lambda x: -x["usd"])
1399
+ return {"days": days, "spend_usd": spend, "lapses": len(lapses), "lapse_usd": sum(x["usd"] for x in lapses),
1400
+ "biggest": lapses[:3]}
1401
+
1402
+
1403
+ def say_report(r):
1404
+ if not r["spend_usd"]:
1405
+ return "No Claude Code use in the last %g days to report on." % r["days"]
1406
+ share = 100 * r["lapse_usd"] / r["spend_usd"]
1407
+ out = ["Last %g days, at list price (on a Claude plan, this is usage against your limits, not a bill):" % r["days"],
1408
+ " Claude Code used about $%s of tokens." % format(round(r["spend_usd"]), ","),
1409
+ " %d time%s, you went back to a session after its cache had cooled. Reading %s back in cost about $%s"
1410
+ " more than a warm cache would have: %.0f%% of the total." % (
1411
+ r["lapses"], "" if r["lapses"] == 1 else "s", "it" if r["lapses"] == 1 else "those",
1412
+ format(round(r["lapse_usd"]), ","), share)]
1413
+ if r["biggest"]:
1414
+ out.append(" The biggest:")
1415
+ out += [" %-18s %5dk tokens about %-8s %s" % (x["folder"][:18], x["tokens"] // 1000, "$%.2f" % x["usd"],
1416
+ stamp(x["t"])) for x in r["biggest"]]
1417
+ out += ["", "Next time, type ctxtree in the folder first: it says when starting fresh from the folded view is "
1418
+ "the cheaper way."]
1419
+ return "\n".join(out)
1420
+
1421
+
1422
+ def entry():
1423
+ """The ctxtree command"""
1424
+ import signal
1425
+ if hasattr(signal, "SIGPIPE"):
1426
+ signal.signal(signal.SIGPIPE, signal.SIG_DFL) # piped into head: stop quietly
1427
+ sys.exit(main(sys.argv[1:]))
1428
+
1429
+
1430
+ if __name__ == "__main__":
1431
+ entry()