ctxtree 0.1.0 → 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 (3) hide show
  1. package/README.md +41 -21
  2. package/ctxtree.py +673 -182
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -14,28 +14,38 @@ and opens the rest when it needs to. Nothing is summarized away: every part open
14
14
  ## Install
15
15
 
16
16
  ```sh
17
- pip install ctxtree # or: pipx install ctxtree
18
- npx ctxtree # the same tool through npm; needs Python 3.8 or newer
17
+ pipx install ctxtree # recommended
18
+ npx ctxtree # nothing to install; needs Node, and Python 3.8 or newer
19
19
  ```
20
20
 
21
+ If you use uv, `uvx ctxtree` runs it without installing it. No pipx yet? `brew install pipx` on a Mac, `sudo apt install pipx` on Ubuntu or Debian, then `pipx ensurepath`. A plain
22
+ `pip install ctxtree` works inside a virtual environment; many systems (Ubuntu 24.04, Homebrew's Python) block it
23
+ outside one. Step by step, with pictures: https://ctxtree.com/install/
24
+
21
25
  ## Use
22
26
 
23
- In a project folder, type `ctxtree`. It says what your last Claude Code session there was doing, whether its cache is
24
- still warm, and what each way back costs at list price:
27
+ In a project folder, type `ctxtree`. It says what your last Claude Code session there was doing, and which way back is
28
+ cheaper right now, at list price:
25
29
 
26
30
  ```
27
31
  api: your last session here (3f9a1c02) was active Nov 30 14:02, 3 hours ago.
28
32
  The task: "move the billing webhooks to the new queue"
29
- Its cache has cooled. Going back to it re-caches its whole window: 612k tokens, about $4.90 at list price.
30
- Starting fresh from the folded view instead: about 52k tokens, about $0.42 at list price, with every word still reachable.
31
33
 
32
- ctxtree resume start a new session from the folded view
33
- ctxtree show read the folded view yourself
34
- ctxtree level see or change how much it holds (now auto)
34
+ Cheaper now: start fresh from the folded view: about 52k tokens, about $0.42 at list price, with every word still reachable.
35
+ ctxtree resume
36
+ Going back instead re-caches its whole window: 612k tokens, about $4.90 at list price.
37
+
38
+ ctxtree show read the folded view yourself
39
+ ctxtree level see or change how much it holds (now auto)
35
40
  ```
36
41
 
37
- `ctxtree resume` starts Claude Code there, told to read the folded view first. Every command works on the newest
38
- session in the folder you're in, unless you give a session id (or its first 6 characters).
42
+ `ctxtree resume` starts Claude Code there, told to read the folded view first (`--upto t21` starts again from before
43
+ turn 21). Every command works on the newest session in the folder you're in, unless you give a session id (or its
44
+ first 6 characters); `ctxtree <id>` shows that session's card. To see what cooled caches cost you lately:
45
+
46
+ ```
47
+ ctxtree report
48
+ ```
39
49
 
40
50
  The rest, mostly for the agent in the new session:
41
51
 
@@ -45,19 +55,26 @@ ctxtree open t21.3 # e3 a stretch of work, t21 a turn, t21.3 one tool
45
55
  ctxtree search --here 'queue' # every session in this folder from the last 30 days
46
56
  ctxtree status --json # warm or cooled, and what each way back costs, read fast from the end of each log
47
57
  ctxtree check --all # prove nothing is lost: every tool call and result opens to exactly what the log holds
58
+ ctxtree statusline # for Claude Code's status line: minutes left on the cache, then both prices
59
+ ctxtree mcp # search, open, show and report as an MCP server, for any MCP client
60
+ ctxtree titles # name each stretch of work in a few words (opt-in: asks Claude Haiku, see below)
48
61
  ```
49
62
 
63
+ With the Claude Code plugin, it also works without a command: after a compaction Claude is told the dropped turns still
64
+ open word for word, and after `/clear` on a big session the fresh one is pointed at the folded map of the one you
65
+ cleared. Codex CLI sessions work too: give ctxtree a Codex session's id.
66
+
50
67
  **How much the opening holds** works like Claude Code's effort setting. `auto`, the default, holds the current task
51
68
  word for word and a map of the rest, about 8k to 24k tokens. `low`, `medium`, `high`, `xhigh` and `max` hold about 2k,
52
- 8k, 24k, 64k tokens, or every turn; a size such as `30k` works too. `ctxtree level high` saves one; `ctxtree levels`
53
- shows what each would hold for a session.
69
+ 8k, 24k, 64k tokens, or every turn; a size such as `30k` works too. `ctxtree level` shows what each would hold for
70
+ the session here; `ctxtree level high` saves one.
54
71
 
55
72
  ## Does it work?
56
73
 
57
74
  In two small blind tests on five real sessions, an agent was asked 50 questions about earlier work.
58
75
 
59
- - **Working from the folded view, with `search` and `open`:** 49 answered right, at a fifth to a tenth of the cost of
60
- resuming.
76
+ - **Working from the folded view, with `search` and `open`:** 49 answered right, at about a fifth of the cost of
77
+ resuming, in total ($3.39 against about $17 at list price).
61
78
  - **Resuming the old session:** 32 answered right. That was all 20 where nothing had been compacted, and 12 of 30 where
62
79
  compaction had dropped the older work.
63
80
 
@@ -65,14 +82,17 @@ It's a small sample, so treat it as a sign, not a proof.
65
82
 
66
83
  ## What it touches
67
84
 
68
- - **It reads** Claude Code's session logs in `~/.claude/projects` and prints. It sends nothing anywhere.
69
- - **It writes** three things:
85
+ - **It reads** Claude Code's session logs in `~/.claude/projects` (and Codex's in `~/.codex/sessions`, when you name
86
+ one) and prints. It sends nothing anywhere, except `ctxtree titles`, which you run yourself: it sends each stretch of
87
+ work's opening words and a few tool calls, masked, to Claude Haiku through your own `claude` command.
88
+ - **It writes** a few small things:
70
89
  - the level you save, in `~/.config/ctxtree/config`
71
- - the opening message for `resume`, in `~/.local/state/ctxtree/`, readable by you only
72
- - the sizes of fresh starts, in `~/.cache/ctxtree/` (numbers only)
90
+ - the opening message for `resume` and `/clear`, in `~/.local/state/ctxtree/`, readable by you only
91
+ - the sizes of fresh starts, and titles if you ask for them, in `~/.cache/ctxtree/`
92
+ - **It masks** anything shaped like a key or token in the views it prints or writes; `open` still gives the exact text.
73
93
  - **It never watches** what you type.
74
- - **Limits:** it knows Claude Code's log format only. It leaves out sub-agents' own steps; each one's result shows as
75
- the tool call that started it. Prices are list prices for current Claude models.
94
+ - **Limits:** it knows Claude Code's and Codex CLI's log formats. It leaves out sub-agents' own steps; each one's result
95
+ shows as the tool call that started it. Prices are list prices for current Claude models.
76
96
 
77
97
  ## License
78
98
 
package/ctxtree.py CHANGED
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env python3
2
2
  """ctxtree: a folded, lossless view of a Claude Code session, opened on demand.
3
3
 
4
- Run it with nothing after it, in a project folder, to see where your last session there left off and what coming back
5
- to it costs. Every command works on that session unless you name another.
6
-
7
- ctxtree where you left off here, and how to pick it up
8
- ctxtree resume [SESSION] start a new Claude Code session from the folded view
9
- ctxtree show [SESSION] [--level L] the folded view: the map, then recent turns word for word
10
- ctxtree open [SESSION] NODE e3 an episode, t12 a turn, t12.3 one tool call with its full output
11
- ctxtree search [SESSION] PATTERN where a word or regex appears, in words and tool output alike
12
- ctxtree prime [SESSION] [--level L] the opening message a new session gets
13
- ctxtree level [L] the slider: show the level in force, or save a new one
14
- ctxtree levels [SESSION] what each level would hold for a session
15
- ctxtree sessions [--days N] big sessions everywhere: their window and their opening
16
- ctxtree status [SESSION...] [--json] warm or cooled, and what each way back costs, read fast (for deskblock)
17
- ctxtree hook for the Claude Code plugin's SessionStart hook (reads its JSON on stdin)
18
- ctxtree check [SESSION...] [--all] prove nothing is lost: every tool call and result opens, exactly
19
-
20
- search --here looks through every session in this folder, newest first. Inside a Claude Code session, "the newest
21
- session in this folder" means the newest other than that session itself.
22
-
23
- SESSION is a session id (or its first 6 or more characters) or the path of its .jsonl file; left out, it is the
24
- newest session in this folder. show, open, search, prime and levels take --upto tN to see a session only as it stood
25
- before turn N.
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
26
 
27
27
  The level works like effort. auto, the default, holds the current task word for word and a map of the rest, between
28
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
@@ -30,7 +30,7 @@ such as 30k. --level beats CTXTREE_LEVEL, which beats the level saved with `ctxt
30
30
  """
31
31
  import argparse, glob, json, os, re, shlex, shutil, subprocess, sys, time
32
32
 
33
- __version__ = "0.1.0"
33
+ __version__ = "0.2.0"
34
34
  from datetime import datetime
35
35
 
36
36
  ROOT = os.path.expanduser("~/.claude/projects")
@@ -40,17 +40,54 @@ START = 30000 # tokens a new Claude Code session holds before anything is said,
40
40
  CHARS = 4 # characters a token, roughly
41
41
  COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-\S+\s+(\S+\s+)?)*commit\b")
42
42
  HERE = os.path.realpath(__file__)
43
- # How an agent runs this: plain ctxtree when it's on the PATH (installed, or linked there), else this file
44
- ME = "ctxtree" if shutil.which("ctxtree") else "python3 " + HERE.replace(os.path.expanduser("~"), "~", 1)
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
45
61
  # The slider's fixed notches: about how many tokens the opening message may hold (max: every turn, tool calls folded)
46
62
  FIXED = (("low", 2000), ("medium", 8000), ("high", 24000), ("xhigh", 64000), ("max", None))
47
63
  NAMES = ("auto",) + tuple(n for n, _ in FIXED)
48
64
  # $ per million tokens, list prices (Nov 2026): written to a one-hour cache (coming back to a cooled window, or starting
49
65
  # fresh), and read from it (coming back while it's warm)
50
- WRITE = {"claude-fable-5-2": 16, "claude-opus-5-5": 8, "claude-opus-5": 10, "claude-opus-4-8": 10,
51
- "claude-sonnet-5-5": 4, "claude-sonnet-5": 4, "claude-haiku-5-5": 0.2}
52
- READ = {"claude-fable-5-2": 0.2, "claude-opus-5-5": 0.2, "claude-opus-5": 0.5, "claude-opus-4-8": 0.5,
53
- "claude-sonnet-5-5": 0.1, "claude-sonnet-5": 0.2, "claude-haiku-5-5": 0.01}
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
54
91
 
55
92
 
56
93
  def text_of(content):
@@ -115,84 +152,153 @@ class Turn:
115
152
  return [x for k, x in self.items if k == "call"]
116
153
 
117
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
+
118
225
  class Session:
119
226
  def __init__(self, path):
120
227
  self.path, self.id = path, os.path.basename(path)[:-len(".jsonl")]
121
228
  self.turns, self.orphans, self.cwd, self.chars, self.window, self.model = [], 0, None, 0, 0, None
122
229
  calls, seen, compacted, cur = {}, set(), False, None
123
- with open(path, errors="replace") as f:
124
- for line_no, line in enumerate(f, 1):
125
- try:
126
- e = json.loads(line)
127
- except ValueError:
128
- continue
129
- if not isinstance(e, dict) or e.get("isSidechain"):
130
- continue
131
- self.cwd = self.cwd or e.get("cwd")
132
- kind, t = e.get("type"), when(e)
133
- if kind == "system" and e.get("subtype") == "compact_boundary":
134
- compacted = True
135
- continue
136
- if kind not in ("user", "assistant"):
137
- continue
138
- message = e.get("message") if isinstance(e.get("message"), dict) else {}
139
- content = message.get("content")
140
- if kind == "user":
141
- who = starter(e)
142
- if who:
143
- cur = Turn(len(self.turns) + 1, who, text_of(content), line_no, t)
144
- cur.after_compact, compacted = compacted, False
145
- self.turns.append(cur)
146
- self.chars += len(cur.words)
147
- continue
148
- if cur and t:
149
- cur.t1 = max(cur.t1 or t, t)
150
- results = [x for x in content if isinstance(x, dict) and x.get("type") == "tool_result"] \
151
- if isinstance(content, list) else []
152
- for x in results:
153
- body = text_of(x.get("content"))
154
- self.chars += len(body)
155
- c = calls.get(x.get("tool_use_id"))
156
- if c is None:
157
- self.orphans += 1
158
- continue
159
- c.result, c.result_line, c.error = body, line_no, bool(x.get("is_error"))
160
- if c.name == "Bash" and not c.error and COMMIT.search(str(c.args.get("command", ""))):
161
- c.turn.commits += 1
162
- if not results and cur:
163
- words = text_of(content)
164
- if words.strip():
165
- cur.notes.append((line_no, words))
166
- self.chars += len(words)
167
- continue
168
- if cur is None: # a session that starts with the agent, as a resumed one can
169
- cur = Turn(1, "start", "", line_no, t)
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
170
248
  self.turns.append(cur)
171
- if t:
249
+ self.chars += len(cur.words)
250
+ continue
251
+ if cur and t:
172
252
  cur.t1 = max(cur.t1 or t, t)
173
- usage = message.get("usage") if isinstance(message.get("usage"), dict) else {}
174
- if usage and message.get("model") != "<synthetic>": # tokens the window held at the last reply
175
- self.window = sum(usage.get(k) or 0 for k in
176
- ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"))
177
- self.model = message.get("model") or self.model
178
- for x in content if isinstance(content, list) else []:
179
- if not isinstance(x, dict):
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
180
261
  continue
181
- if x.get("type") == "text" and (x.get("text") or "").strip():
182
- key = (message.get("id"), x["text"])
183
- if key not in seen:
184
- seen.add(key)
185
- cur.items.append(("text", x["text"]))
186
- self.chars += len(x["text"])
187
- elif x.get("type") == "tool_use" and x.get("id") not in calls:
188
- args = x.get("input") if isinstance(x.get("input"), dict) else {}
189
- c = Call(x.get("id"), x.get("name") or "?", args, line_no, cur)
190
- calls[c.id] = c
191
- cur.items.append(("call", c))
192
- self.chars += len(json.dumps(args, ensure_ascii=False))
193
- elif x.get("type") == "thinking":
194
- self.chars += len(x.get("thinking") or "")
195
-
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
196
302
  def episodes(self):
197
303
  """Turns split into stretches of work: a new one after a pause, a compaction or a commit"""
198
304
  eps, prev = [], None
@@ -296,7 +402,7 @@ def render_turn(turn, notes=False):
296
402
  return "\n".join(out)
297
403
 
298
404
 
299
- def episode_line(i, turns):
405
+ def episode_line(i, turns, title=None):
300
406
  files, commits = [], sum(t.commits for t in turns)
301
407
  for t in turns:
302
408
  for c in t.calls():
@@ -310,7 +416,9 @@ def episode_line(i, turns):
310
416
  parts.append("edited " + ", ".join(files[:5]) + (" and %d more" % (len(files) - 5) if len(files) > 5 else ""))
311
417
  if commits:
312
418
  parts.append("%d commit%s" % (commits, "" if commits == 1 else "s"))
313
- return " · ".join(parts) + ' · "%s"' % one_line(heading_words(task_of(turns)), 100)
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)
314
422
 
315
423
 
316
424
  def budget(level, s=None):
@@ -360,6 +468,18 @@ def slider(level, s=None):
360
468
  return "\n".join(out)
361
469
 
362
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
+
363
483
  def tokens_for(flag, s=None):
364
484
  """The level in force and its tokens; a bad level ends the run with the reason"""
365
485
  level = level_in_force(flag)
@@ -387,7 +507,8 @@ def fold(s, tokens):
387
507
  % (s.id[:8], short(s.cwd), stamp(start), stamp(end), len(s.turns), len(eps)),
388
508
  "Folded, nothing lost. Open a node with `%s open %s <node>`: e3 is an episode, t12 a turn, t12.3 one tool "
389
509
  "call with its full input and output." % (ME, s.id[:8])]
390
- lines_ = [episode_line(i, ep) for i, ep in enumerate(eps, 1)]
510
+ named = load_titles(s.id)
511
+ lines_ = [episode_line(i, ep, named.get(span(ep))) for i, ep in enumerate(eps, 1)]
391
512
  if tokens is None:
392
513
  body = ["", "## Map"] + lines_ + ["", "## Every turn"] + [render_turn(t) for t in s.turns]
393
514
  return "\n".join(out + body), len(s.turns), False, len(lines_)
@@ -476,7 +597,8 @@ def prime(s, tokens=8000):
476
597
 
477
598
 
478
599
  def live():
479
- """The sessions running on this machine now, from runwatch: session id -> its row. Empty without runwatch."""
600
+ """The sessions running on this machine now, from runwatch (an optional session watcher): session id -> its row.
601
+ Empty without it."""
480
602
  exe = shutil.which("runwatch") or os.path.expanduser("~/.local/bin/runwatch")
481
603
  try:
482
604
  out = subprocess.run([exe, "ps", "--json", "--here"], capture_output=True, text=True, timeout=8).stdout
@@ -496,17 +618,38 @@ def where_it_runs(row):
496
618
  return "in the background"
497
619
 
498
620
 
499
- def card(s, level, running=None):
500
- """Where you left off, in plain words, and what each way back costs. `running` is live()'s answer."""
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."""
501
645
  now, last = time.time(), s.last_active()
502
- task = task_of(s.episodes()[-1]) if s.turns else None
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))
503
651
  latest = next((t for t in reversed(s.turns) if t.who == "you"), None)
504
652
  opening = len(prime(s, budget(level, s))[0]) // CHARS
505
- price = WRITE.get(s.model or "")
506
-
507
- def cost(tokens):
508
- return ", about $%.2f at list price" % (tokens * price / 1e6) if price else ""
509
-
510
653
  out = ["%s: your last session here (%s) was active %s, %s." % (
511
654
  os.path.basename(s.cwd or "?"), s.id[:8], stamp(last), ago(now - last))]
512
655
  if task:
@@ -518,21 +661,24 @@ def card(s, level, running=None):
518
661
  state = {"working": "working on it right now", "needs-input": "waiting for you",
519
662
  "done": "done and waiting for your next message"}.get(row.get("state"), row.get("state") or "open")
520
663
  out.append("It's still open %s, %s." % (where_it_runs(row), state))
521
- left = TTL - (now - last)
522
- read = READ.get(s.model or "")
523
- if left > 0:
524
- out.append("Its cache is still warm for about %d more minutes. Going straight back to it is the cheaper way%s."
525
- % (left // 60 + 1, ": about $%.2f to re-read %dk tokens" % (s.window * read / 1e6, s.window // 1000)
526
- if read and s.window else ""))
527
- elif s.window:
528
- out.append("Its cache has cooled. Going back to it re-caches its whole window: %dk tokens%s."
529
- % (s.window // 1000, cost(s.window)))
530
- fresh = start_tokens(os.path.dirname(s.path)) + opening
531
- out.append("Starting fresh from the folded view instead: about %dk tokens%s, with every word still reachable."
532
- % (fresh // 1000, cost(fresh)))
533
- out += ["", " %s resume start a new session from the folded view" % ME,
534
- " %s show read the folded view yourself" % ME,
535
- " %s level see or change how much it holds (now %s)" % (ME, level)]
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)]
536
682
  return "\n".join(out)
537
683
 
538
684
 
@@ -570,6 +716,59 @@ def tail(path, size=262144):
570
716
  return info
571
717
 
572
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
+
573
772
  def cache_file():
574
773
  home = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")
575
774
  return os.path.join(home, "ctxtree", "openings-v2.json")
@@ -646,7 +845,8 @@ def status_of(path, level, now=None):
646
845
  def hook(event, now=None):
647
846
  """What the plugin's SessionStart hook says, if anything. Resuming a big session whose cache has cooled: a word to
648
847
  you about the cheaper way back. Starting a new session where the last one has cooled: a note for Claude that the
649
- earlier work is kept and how to search it. Otherwise nothing."""
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."""
650
850
  now = now or time.time()
651
851
  if event.get("source") == "resume":
652
852
  tokens, path = event.get("context_tokens") or 0, event.get("transcript_path") or ""
@@ -655,8 +855,19 @@ def hook(event, now=None):
655
855
  return {"systemMessage": "Picking this session up re-caches %dk tokens%s. To start fresh from its folded "
656
856
  "history instead (about %dk tokens, every word still reachable), quit and run: "
657
857
  "%s resume %s" % (tokens // 1000, ", about $%.2f" % usd if usd else "",
658
- fresh // 1000, ME, os.path.basename(path)[:8])}
858
+ fresh // 1000, YOU, os.path.basename(path)[:8])}
659
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)
660
871
  if event.get("source") != "startup":
661
872
  return None
662
873
  folder = os.path.join(ROOT, folder_key(os.path.abspath(event.get("cwd") or os.getcwd())))
@@ -675,27 +886,73 @@ def hook(event, now=None):
675
886
  return {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": note}}
676
887
 
677
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
+
678
932
  def state_dir():
679
933
  d = os.path.join(os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"), "ctxtree")
680
934
  os.makedirs(d, mode=0o700, exist_ok=True)
681
935
  return d
682
936
 
683
937
 
684
- def resume(s, tokens, dry=False):
938
+ def resume(s, tokens, dry=False, upto=None, level=None):
685
939
  """Start Claude Code in the session's folder, told to read the folded view first. The view goes in a private file
686
940
  (it can be bigger than a command line holds)."""
687
- path = os.path.join(state_dir(), "opening-%s.md" % s.id[:8])
688
- with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
689
- f.write(prime(s, tokens)[0])
690
- os.chmod(path, 0o600)
941
+ path = write_opening(s, tokens)
691
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 "
692
- "picking up. Then say in two lines where it left off, and wait for my next message." % (path, s.id[:8]))
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 ""))
693
945
  folder = s.cwd if s.cwd and os.path.isdir(s.cwd) else os.getcwd()
694
946
  if dry:
695
947
  print("cd %s && claude %s" % (shlex.quote(folder), shlex.quote(ask)))
696
948
  return 0
697
949
  if not shutil.which("claude"):
698
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 ""))
699
956
  os.chdir(folder)
700
957
  os.execvp("claude", ["claude", ask])
701
958
 
@@ -703,20 +960,16 @@ def resume(s, tokens, dry=False):
703
960
  def check(s):
704
961
  """Every tool call and every tool result in the file opens, and opens to exactly the text the file holds"""
705
962
  uses, results = set(), {}
706
- with open(s.path, errors="replace") as f:
707
- for line_no, line in enumerate(f, 1):
708
- try:
709
- e = json.loads(line)
710
- except ValueError:
711
- continue
712
- if not isinstance(e, dict) or e.get("isSidechain") or e.get("type") not in ("user", "assistant"):
713
- continue
714
- content = (e.get("message") or {}).get("content") if isinstance(e.get("message"), dict) else None
715
- for x in content if isinstance(content, list) else []:
716
- if isinstance(x, dict) and x.get("type") == "tool_use":
717
- uses.add(x.get("id"))
718
- elif isinstance(x, dict) and x.get("type") == "tool_result":
719
- results[x.get("tool_use_id")] = (line_no, text_of(x.get("content")))
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")))
720
973
  calls = {c.id: c for t in s.turns for c in t.calls()}
721
974
  missing = uses - set(calls)
722
975
  unopened = [k for k in results if k not in calls]
@@ -751,6 +1004,8 @@ def find_session(arg):
751
1004
  if arg.endswith(".jsonl") and os.path.exists(arg):
752
1005
  return arg
753
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)
754
1009
  return found[0] if len(found) == 1 else None
755
1010
 
756
1011
 
@@ -771,16 +1026,24 @@ def recent_paths(days, project=None):
771
1026
 
772
1027
 
773
1028
  def main(argv):
774
- ap = argparse.ArgumentParser(prog="ctxtree", description=__doc__.split("\n\n")[0])
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]")
775
1035
  ap.add_argument("--version", action="version", version="ctxtree " + __version__)
776
- sub = ap.add_subparsers(dest="verb")
1036
+ sub = ap.add_subparsers(dest="verb", metavar="COMMAND")
777
1037
  upto = argparse.ArgumentParser(add_help=False)
778
1038
  upto.add_argument("--upto", help="see the session only as it stood before this turn, such as t29")
779
1039
  lv = argparse.ArgumentParser(add_help=False)
780
1040
  lv.add_argument("--level", help="auto, low, medium, high, xhigh, max, or a size such as 30k (tokens)")
781
- for verb, parents in (("show", [upto, lv]), ("prime", [upto, lv]), ("levels", [upto])):
782
- sub.add_parser(verb, parents=parents).add_argument("session", nargs="?")
783
- p = sub.add_parser("resume", parents=[lv])
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])
784
1047
  p.add_argument("session", nargs="?")
785
1048
  p.add_argument("--dry-run", action="store_true", help="write the opening and print the command, but don't start")
786
1049
  sub.add_parser("open", parents=[upto]).add_argument("args", nargs="+", metavar="[SESSION] NODE")
@@ -796,10 +1059,18 @@ def main(argv):
796
1059
  p.add_argument("--days", type=float, default=7)
797
1060
  p.add_argument("--project")
798
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")
799
1068
  p = sub.add_parser("check")
800
1069
  p.add_argument("session", nargs="*")
801
1070
  p.add_argument("--all", action="store_true")
802
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
803
1074
  a = ap.parse_args(argv)
804
1075
 
805
1076
  if a.verb == "hook":
@@ -827,21 +1098,17 @@ def main(argv):
827
1098
  if left <= 0 and r["cold_usd"] is not None and r["fresh_usd"] is not None else ""))
828
1099
  return 0
829
1100
  if a.verb == "search" and a.here:
830
- folder = os.path.join(ROOT, folder_key(os.getcwd()))
831
- paths = [p for p in sorted(glob.glob(os.path.join(folder, "*.jsonl")), key=os.path.getmtime, reverse=True)
832
- if os.path.getsize(p) > 2000 and os.path.getmtime(p) > time.time() - 30 * 86400][:15]
833
- hits = []
834
- for path in paths:
835
- hits += ["%s %s" % (os.path.basename(path)[:8], h) for h in search(Session(path), a.args[-1], most=20)
836
- if not h.startswith("…")]
837
- print("\n".join(hits[:60]) + ("\n… and %d more" % (len(hits) - 60) if len(hits) > 60 else "")
838
- if hits else "nothing matches")
1101
+ print(search_here(os.getcwd(), a.args[-1]))
1102
+ return 0
1103
+ if a.verb == "mcp":
1104
+ mcp(sys.stdin, sys.stdout)
839
1105
  return 0
840
1106
  if a.verb == "sessions":
841
1107
  level = level_in_force()
842
1108
  print("Opening at level %s. words: every turn folded, as a share of the whole history." % level)
843
1109
  print("%-8s %-16s %-12s %5s %8s %7s %7s %7s" %
844
1110
  ("session", "folder", "last", "turns", "history", "words", "window", "opening"))
1111
+ shown = 0
845
1112
  for path in recent_paths(a.days, a.project):
846
1113
  s = Session(path)
847
1114
  if s.chars < a.min * 1e6 or not s.turns:
@@ -850,6 +1117,9 @@ def main(argv):
850
1117
  s.id[:8], os.path.basename(s.cwd or "?")[:16], stamp(os.path.getmtime(path)), len(s.turns),
851
1118
  s.chars / 1e6, 100 * len(fold(s, None)[0]) / s.chars, s.window / 1e3,
852
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))
853
1123
  return 0
854
1124
  if a.verb == "level":
855
1125
  if a.name:
@@ -867,21 +1137,34 @@ def main(argv):
867
1137
  level = level_in_force()
868
1138
  source = "CTXTREE_LEVEL" if os.environ.get("CTXTREE_LEVEL") else \
869
1139
  short(config_path(), 120) if os.path.exists(config_path()) else "the default"
870
- folder = os.path.join(ROOT, folder_key(os.getcwd()))
871
- s = Session(newest_here()) if glob.glob(os.path.join(folder, "*.jsonl")) else None
1140
+ found = here()
1141
+ s = Session(found[0]) if found else None
872
1142
  print(slider(level, s))
873
- print("From %s. Change it with: %s level <%s|30k>" % (source, ME, "|".join(NAMES)))
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))
874
1156
  return 0
875
1157
  if a.verb == "check":
876
1158
  paths = recent_paths(a.days) if a.all else [locate(x) for x in a.session] or [newest_here()]
877
1159
  bad = 0
878
1160
  for path in paths:
879
- r = check(Session(path))
1161
+ s = Session(path)
1162
+ r = check(s)
880
1163
  lost = r["missing_calls"] + r["unopened_results"] + r["wrong_results"]
881
1164
  bad += lost > 0
882
1165
  if lost or not a.all:
883
1166
  print("%s %d calls, %d results: %d calls missing, %d results that don't open, %d that open wrong"
884
- % (os.path.basename(path)[:8], r["calls"], r["results"], r["missing_calls"],
1167
+ % (s.id[:8], r["calls"], r["results"], r["missing_calls"],
885
1168
  r["unopened_results"], r["wrong_results"]))
886
1169
  print("%d of %d sessions lossless" % (len(paths) - bad, len(paths)))
887
1170
  return 1 if bad else 0
@@ -893,33 +1176,41 @@ def main(argv):
893
1176
  session, rest = (a.args[0], a.args[1]) if len(a.args) == 2 else (None, a.args[0])
894
1177
  else:
895
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
896
1183
  s = Session(locate(session))
897
1184
  if getattr(a, "upto", None):
898
1185
  m = re.fullmatch(r"t(\d+)", a.upto)
899
1186
  if not m:
900
1187
  sys.exit("--upto takes a turn, such as t29")
901
1188
  s.turns = s.turns[:int(m.group(1)) - 1]
902
- if a.verb is None:
903
- print(card(s, level_in_force(), live()))
1189
+ if a.verb in (None, "card"):
1190
+ print(card(s, level_in_force(getattr(a, "level", None)), live(), named=session is not None))
904
1191
  elif a.verb == "resume":
905
- return resume(s, tokens_for(a.level, s)[1], a.dry_run)
906
- elif a.verb == "show":
907
- print(fold(s, tokens_for(a.level, s)[1])[0])
908
- elif a.verb == "prime":
909
- print(prime(s, tokens_for(a.level, s)[1])[0])
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]))
910
1197
  elif a.verb == "levels":
911
- current, eps = level_in_force(), len(s.episodes())
912
- print("%-8s %8s %-30s %s" % ("level", "opening", "turns word for word", "episodes on the map"))
913
- for name in NAMES:
914
- text, n, cut, mapped = prime(s, budget(name, s))
915
- print("%-8s %7.1fk %-30s %d of %d" % (
916
- "[%s]" % name if name == current else name, len(text) / (CHARS * 1000),
917
- "%d of %d%s" % (n, len(s.turns), ", the oldest cut" if cut else ""), mapped, eps))
1198
+ print(levels_table(s, level_in_force()))
918
1199
  if not a.upto:
919
1200
  print("Its window held %dk tokens at the last reply: what coming back after a lapse re-caches."
920
1201
  % (s.window // 1000))
921
1202
  elif a.verb == "search":
922
- print("\n".join(search(s, rest)) or "nothing matches")
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))))
923
1214
  else:
924
1215
  out = open_node(s, rest)
925
1216
  if out is None:
@@ -928,6 +1219,206 @@ def main(argv):
928
1219
  return 0
929
1220
 
930
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
+
931
1422
  def entry():
932
1423
  """The ctxtree command"""
933
1424
  import signal
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ctxtree",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Pick up a Claude Code session from a folded, lossless view of its history, instead of re-caching its whole window",
5
5
  "bin": {
6
6
  "ctxtree": "ctxtree.py"