ctxtree 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.4
2
+ Name: ctxtree
3
+ Version: 0.1.0
4
+ Summary: Pick up a Claude Code session from a folded, lossless view of its history, instead of re-caching its whole window
5
+ Author: CodeWheel
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://ctxtree.com
8
+ Keywords: claude-code,claude,prompt-cache,context,agents
9
+ Classifier: Environment :: Console
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development
13
+ Requires-Python: >=3.8
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # ctxtree
19
+
20
+ Pick up a Claude Code session from a folded, lossless view of its history, instead of paying to take its whole window
21
+ in again.
22
+
23
+ Claude Code's prompt cache lasts an hour on a Claude subscription (five minutes on an API key). Come back to a long
24
+ session after that, and its whole window is processed again: often hundreds of thousands of tokens. Most of that window
25
+ is tool output from long ago; the conversation itself is a small part of it.
26
+
27
+ ctxtree reads the session's log and folds it into a tree: stretches of work, the turns in them, and one line for each
28
+ tool call. A new session starts from a short opening message (a map of the work, and the current task word for word)
29
+ and opens the rest when it needs to. Nothing is summarized away: every part opens back to the exact text in the log.
30
+
31
+ ## Install
32
+
33
+ ```sh
34
+ pip install ctxtree # or: pipx install ctxtree
35
+ npx ctxtree # the same tool through npm; needs Python 3.8 or newer
36
+ ```
37
+
38
+ ## Use
39
+
40
+ In a project folder, type `ctxtree`. It says what your last Claude Code session there was doing, whether its cache is
41
+ still warm, and what each way back costs at list price:
42
+
43
+ ```
44
+ api: your last session here (3f9a1c02) was active Nov 30 14:02, 3 hours ago.
45
+ The task: "move the billing webhooks to the new queue"
46
+ Its cache has cooled. Going back to it re-caches its whole window: 612k tokens, about $4.90 at list price.
47
+ Starting fresh from the folded view instead: about 52k tokens, about $0.42 at list price, with every word still reachable.
48
+
49
+ ctxtree resume start a new session from the folded view
50
+ ctxtree show read the folded view yourself
51
+ ctxtree level see or change how much it holds (now auto)
52
+ ```
53
+
54
+ `ctxtree resume` starts Claude Code there, told to read the folded view first. Every command works on the newest
55
+ session in the folder you're in, unless you give a session id (or its first 6 characters).
56
+
57
+ The rest, mostly for the agent in the new session:
58
+
59
+ ```sh
60
+ ctxtree search 'webhook' # where a word or regex appears, in what was said and in tool output
61
+ ctxtree open t21.3 # e3 a stretch of work, t21 a turn, t21.3 one tool call with its full input and output
62
+ ctxtree search --here 'queue' # every session in this folder from the last 30 days
63
+ ctxtree status --json # warm or cooled, and what each way back costs, read fast from the end of each log
64
+ ctxtree check --all # prove nothing is lost: every tool call and result opens to exactly what the log holds
65
+ ```
66
+
67
+ **How much the opening holds** works like Claude Code's effort setting. `auto`, the default, holds the current task
68
+ word for word and a map of the rest, about 8k to 24k tokens. `low`, `medium`, `high`, `xhigh` and `max` hold about 2k,
69
+ 8k, 24k, 64k tokens, or every turn; a size such as `30k` works too. `ctxtree level high` saves one; `ctxtree levels`
70
+ shows what each would hold for a session.
71
+
72
+ ## Does it work?
73
+
74
+ In two small blind tests on five real sessions, an agent was asked 50 questions about earlier work.
75
+
76
+ - **Working from the folded view, with `search` and `open`:** 49 answered right, at a fifth to a tenth of the cost of
77
+ resuming.
78
+ - **Resuming the old session:** 32 answered right. That was all 20 where nothing had been compacted, and 12 of 30 where
79
+ compaction had dropped the older work.
80
+
81
+ It's a small sample, so treat it as a sign, not a proof.
82
+
83
+ ## What it touches
84
+
85
+ - **It reads** Claude Code's session logs in `~/.claude/projects` and prints. It sends nothing anywhere.
86
+ - **It writes** three things:
87
+ - the level you save, in `~/.config/ctxtree/config`
88
+ - the opening message for `resume`, in `~/.local/state/ctxtree/`, readable by you only
89
+ - the sizes of fresh starts, in `~/.cache/ctxtree/` (numbers only)
90
+ - **It never watches** what you type.
91
+ - **Limits:** it knows Claude Code's log format only. It leaves out sub-agents' own steps; each one's result shows as
92
+ the tool call that started it. Prices are list prices for current Claude models.
93
+
94
+ ## License
95
+
96
+ Apache-2.0
@@ -0,0 +1,7 @@
1
+ ctxtree.py,sha256=F0tGNft-4Ac9JWCVFvjzudHNhjxruAIWi74HaBbeaA8,47002
2
+ ctxtree-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
3
+ ctxtree-0.1.0.dist-info/METADATA,sha256=0B6jt9HDKRyX8d0Se_39c0719Q4T_6ReLScHVuBJb7k,4581
4
+ ctxtree-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ ctxtree-0.1.0.dist-info/entry_points.txt,sha256=t2ZVBBzlMdOVosX0IOr8gUGwdvEtzdMWpfq_3LxjJtg,42
6
+ ctxtree-0.1.0.dist-info/top_level.txt,sha256=YtslSug0UZT1RdmlTuq6LOG55zPHSX5bnF1mMdcjhs4,8
7
+ ctxtree-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ctxtree = ctxtree:entry
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ ctxtree
ctxtree.py ADDED
@@ -0,0 +1,940 @@
1
+ #!/usr/bin/env python3
2
+ """ctxtree: a folded, lossless view of a Claude Code session, opened on demand.
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.
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.1.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
+ # 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)
45
+ # The slider's fixed notches: about how many tokens the opening message may hold (max: every turn, tool calls folded)
46
+ FIXED = (("low", 2000), ("medium", 8000), ("high", 24000), ("xhigh", 64000), ("max", None))
47
+ NAMES = ("auto",) + tuple(n for n, _ in FIXED)
48
+ # $ per million tokens, list prices (Nov 2026): written to a one-hour cache (coming back to a cooled window, or starting
49
+ # 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}
54
+
55
+
56
+ def text_of(content):
57
+ """The words in a message's content, whether it is a string or a list of blocks"""
58
+ if isinstance(content, str):
59
+ return content
60
+ out = []
61
+ for x in content if isinstance(content, list) else []:
62
+ if isinstance(x, dict) and x.get("type") == "text":
63
+ out.append(x.get("text") or "")
64
+ elif isinstance(x, dict) and x.get("type") == "image":
65
+ out.append("[image]")
66
+ return "\n".join(out)
67
+
68
+
69
+ def when(e):
70
+ try:
71
+ return datetime.fromisoformat(e["timestamp"].replace("Z", "+00:00")).timestamp()
72
+ except (KeyError, AttributeError, ValueError):
73
+ return None
74
+
75
+
76
+ def starter(e):
77
+ """Who a user entry comes from when it starts a turn ('you', 'task', 'command', 'sdk'), else None"""
78
+ if e.get("isMeta") or e.get("isCompactSummary"):
79
+ return None
80
+ content = (e.get("message") or {}).get("content")
81
+ if isinstance(content, list) and any(isinstance(x, dict) and x.get("type") == "tool_result" for x in content):
82
+ return None
83
+ words = text_of(content)
84
+ if not words.strip() or words.startswith("[Request interrupted"):
85
+ return None
86
+ origin = e.get("origin") if isinstance(e.get("origin"), dict) else {}
87
+ if origin.get("kind") == "peer":
88
+ return None
89
+ if origin.get("kind") == "task-notification":
90
+ return "task"
91
+ if words.startswith(("<command-", "<local-command")):
92
+ return "command"
93
+ return "sdk" if e.get("promptSource") == "sdk" else "you"
94
+
95
+
96
+ class Call:
97
+ def __init__(self, cid, name, args, line, turn):
98
+ self.id, self.name, self.args, self.line, self.turn = cid, name, args, line, turn
99
+ self.node = "%s.%d" % (turn.node, sum(1 for k, _ in turn.items if k == "call") + 1)
100
+ self.result, self.result_line, self.error = None, None, False
101
+
102
+
103
+ class Turn:
104
+ def __init__(self, n, who, words, line, t):
105
+ self.n, self.who, self.words, self.line, self.t0, self.t1 = n, who, words, line, t, t
106
+ self.items = [] # in order: ("text", words the agent wrote) or ("call", Call)
107
+ self.notes = [] # text injected into the turn (skills, hook feedback, messages): (line, text)
108
+ self.commits, self.after_compact = 0, False
109
+
110
+ @property
111
+ def node(self):
112
+ return "t%d" % self.n
113
+
114
+ def calls(self):
115
+ return [x for k, x in self.items if k == "call"]
116
+
117
+
118
+ class Session:
119
+ def __init__(self, path):
120
+ self.path, self.id = path, os.path.basename(path)[:-len(".jsonl")]
121
+ self.turns, self.orphans, self.cwd, self.chars, self.window, self.model = [], 0, None, 0, 0, None
122
+ 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)
170
+ self.turns.append(cur)
171
+ if t:
172
+ 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):
180
+ 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
+
196
+ def episodes(self):
197
+ """Turns split into stretches of work: a new one after a pause, a compaction or a commit"""
198
+ eps, prev = [], None
199
+ for turn in self.turns:
200
+ if not eps or turn.after_compact or prev.commits or \
201
+ (turn.t0 and prev.t1 and turn.t0 - prev.t1 > GAP):
202
+ eps.append([])
203
+ eps[-1].append(turn)
204
+ prev = turn
205
+ return eps
206
+
207
+ def last_active(self):
208
+ return (self.turns[-1].t1 if self.turns else None) or os.path.getmtime(self.path)
209
+
210
+ def find(self, node):
211
+ m = re.fullmatch(r"t(\d+)(?:\.(\d+))?", node)
212
+ if m and 0 < int(m.group(1)) <= len(self.turns):
213
+ turn = self.turns[int(m.group(1)) - 1]
214
+ if m.group(2) is None:
215
+ return turn
216
+ calls = turn.calls()
217
+ return calls[int(m.group(2)) - 1] if 0 < int(m.group(2)) <= len(calls) else None
218
+ m = re.fullmatch(r"e(\d+)", node)
219
+ eps = self.episodes()
220
+ return eps[int(m.group(1)) - 1] if m and 0 < int(m.group(1)) <= len(eps) else None
221
+
222
+
223
+ def short(path, n=60):
224
+ p = str(path or "").replace(os.path.expanduser("~"), "~", 1)
225
+ return p if len(p) <= n else "…" + p[-(n - 1):]
226
+
227
+
228
+ def one_line(s, n=90):
229
+ s = " ".join(str(s or "").split())
230
+ return s if len(s) <= n else s[:n - 1] + "…"
231
+
232
+
233
+ def lines(s):
234
+ return s.count("\n") + (not s.endswith("\n")) if s else 0
235
+
236
+
237
+ def stamp(t, fmt="%b %d %H:%M"):
238
+ return datetime.fromtimestamp(t).strftime(fmt) if t else "?"
239
+
240
+
241
+ def ago(seconds):
242
+ minutes, hours = int(seconds // 60), int(seconds // 3600)
243
+ return "just now" if minutes < 2 else "%d minutes ago" % minutes if minutes < 90 else \
244
+ "%d hours ago" % hours if hours < 36 else "%d days ago" % int(seconds // 86400)
245
+
246
+
247
+ def gist(c):
248
+ """One line for a tool call: what it did and what came back"""
249
+ a = c.args
250
+ if c.name == "Read":
251
+ what = short(a.get("file_path")) + (" from line %s" % a["offset"] if a.get("offset") else "")
252
+ elif c.name == "Edit":
253
+ what = "%s (-%d +%d lines)" % (short(a.get("file_path")), lines(a.get("old_string")), lines(a.get("new_string")))
254
+ elif c.name == "Write":
255
+ what = "%s (%d lines)" % (short(a.get("file_path")), lines(a.get("content")))
256
+ elif c.name == "Bash":
257
+ what = a.get("description") or a.get("command")
258
+ elif c.name in ("Grep", "Glob"):
259
+ what = repr(a.get("pattern")) + (" in " + short(a["path"]) if a.get("path") else "")
260
+ elif c.name in ("Agent", "Task"):
261
+ what = a.get("description")
262
+ else:
263
+ what = a.get("query") or a.get("url") or a.get("skill") or \
264
+ next((v for v in a.values() if isinstance(v, str)), "")
265
+ n = lines(c.result)
266
+ got = "no result" if c.result is None else "error: " + one_line(c.result, 50) if c.error \
267
+ else "ok" if c.name in ("Edit", "Write", "NotebookEdit") else "%d line%s" % (n, "" if n == 1 else "s")
268
+ return "%s %s: %s → %s" % (c.node, c.name, one_line(what), got)
269
+
270
+
271
+ def heading_words(turn):
272
+ if turn.who == "command":
273
+ m = re.search(r"<command-name>(.*?)</command-name>", turn.words)
274
+ return m.group(1) if m else one_line(re.sub(r"<[^>]+>", " ", turn.words), 80)
275
+ if turn.who == "task":
276
+ m = re.search(r"<summary>(.*?)</summary>", turn.words, re.S)
277
+ return "task notification: " + one_line(m.group(1) if m else re.sub(r"<[^>]+>", " ", turn.words), 100)
278
+ return turn.words.strip()
279
+
280
+
281
+ def task_of(turns):
282
+ """The turn that best says what a stretch of work was about: its first prompt of some length, else its first"""
283
+ yours = [t for t in turns if t.who == "you"] or turns
284
+ return next((t for t in yours if len(t.words.strip()) >= 25), yours[0])
285
+
286
+
287
+ def render_turn(turn, notes=False):
288
+ out = ["### %s · %s · %s" % (turn.node, turn.who, stamp(turn.t0)), heading_words(turn)]
289
+ for kind, x in turn.items:
290
+ out.append(("agent: " + x.strip()) if kind == "text" else " " + gist(x))
291
+ if turn.notes and not notes:
292
+ out.append(" (%d injected notes, %d characters: open %s to read them)"
293
+ % (len(turn.notes), sum(len(t) for _, t in turn.notes), turn.node))
294
+ for line_no, words in turn.notes if notes else []:
295
+ out.append("note (line %d):\n%s" % (line_no, words.strip()))
296
+ return "\n".join(out)
297
+
298
+
299
+ def episode_line(i, turns):
300
+ files, commits = [], sum(t.commits for t in turns)
301
+ for t in turns:
302
+ for c in t.calls():
303
+ name = os.path.basename(str(c.args.get("file_path") or ""))
304
+ if c.name in ("Edit", "Write") and name and name not in files:
305
+ files.append(name)
306
+ parts = ["e%d" % i, "%s to %s" % (stamp(turns[0].t0), stamp(turns[-1].t1, "%H:%M")),
307
+ "1 turn (%s)" % turns[0].node if len(turns) == 1 else
308
+ "%d turns (%s-%s)" % (len(turns), turns[0].node, turns[-1].node)]
309
+ if files:
310
+ parts.append("edited " + ", ".join(files[:5]) + (" and %d more" % (len(files) - 5) if len(files) > 5 else ""))
311
+ if commits:
312
+ parts.append("%d commit%s" % (commits, "" if commits == 1 else "s"))
313
+ return " · ".join(parts) + ' · "%s"' % one_line(heading_words(task_of(turns)), 100)
314
+
315
+
316
+ def budget(level, s=None):
317
+ """Tokens for a level (None for max). auto: the current task word for word plus the map, kept within 8k-24k"""
318
+ if level == "auto":
319
+ if s is None or not s.turns:
320
+ return 8000
321
+ task = sum(len(render_turn(t)) + 1 for t in s.episodes()[-1])
322
+ return min(24000, max(8000, 2 * task // CHARS + 1000))
323
+ for name, tokens in FIXED:
324
+ if level == name:
325
+ return tokens
326
+ m = re.fullmatch(r"(\d+(?:\.\d+)?)([kK]?)", str(level or ""))
327
+ if not m:
328
+ raise ValueError("a level is auto, low, medium, high, xhigh or max, or a size such as 30k, not %r" % level)
329
+ return max(1000, int(float(m.group(1)) * (1000 if m.group(2) else 1)))
330
+
331
+
332
+ def config_path():
333
+ home = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")
334
+ return os.path.join(home, "ctxtree", "config")
335
+
336
+
337
+ def level_in_force(flag=None):
338
+ """The level to use: --level, then CTXTREE_LEVEL, then the saved one, then auto"""
339
+ if flag:
340
+ return flag
341
+ if os.environ.get("CTXTREE_LEVEL"):
342
+ return os.environ["CTXTREE_LEVEL"]
343
+ try:
344
+ with open(config_path()) as f:
345
+ for line in f:
346
+ key, _, value = line.partition("=")
347
+ if key.strip() == "level" and value.strip():
348
+ return value.strip()
349
+ except OSError:
350
+ pass
351
+ return "auto"
352
+
353
+
354
+ def slider(level, s=None):
355
+ marks = " · ".join("[%s]" % n if n == level else n for n in NAMES) + ("" if level in NAMES else " · [%s]" % level)
356
+ out = [marks, "auto, the default, holds the current task word for word and a map of the rest (8k to 24k tokens). "
357
+ "The others hold about: low 2k, medium 8k, high 24k, xhigh 64k, max every turn."]
358
+ if s is not None and level == "auto":
359
+ out.append("For the session here, auto comes to about %dk." % (budget("auto", s) // 1000))
360
+ return "\n".join(out)
361
+
362
+
363
+ def tokens_for(flag, s=None):
364
+ """The level in force and its tokens; a bad level ends the run with the reason"""
365
+ level = level_in_force(flag)
366
+ try:
367
+ return level, budget(level, s)
368
+ except ValueError as e:
369
+ sys.exit(str(e))
370
+
371
+
372
+ def squeeze(text, keep, node):
373
+ """A turn cut to about `keep` characters: two fifths from its start, the rest from its end, and where to open it"""
374
+ head = text[:keep * 2 // 5]
375
+ tail = text[len(text) - (keep - len(head)):]
376
+ return "%s\n(… %d characters left out here: open %s for all of it)\n%s" % (head, len(text) - keep, node, tail)
377
+
378
+
379
+ def fold(s, tokens):
380
+ """The folded view in about `tokens` tokens: the map (its newest episodes, if it must be cut, in at most half the
381
+ room), then as many recent turns word for word as fit. None: every turn, tool calls still folded to a line.
382
+ Returns (text, turns shown word for word, whether the oldest of them was cut short, episodes on the map)."""
383
+ eps = s.episodes()
384
+ start = s.turns[0].t0 if s.turns else None
385
+ end = s.turns[-1].t1 if s.turns else None
386
+ out = ["# Session %s · %s · %s to %s · %d turns in %d episodes"
387
+ % (s.id[:8], short(s.cwd), stamp(start), stamp(end), len(s.turns), len(eps)),
388
+ "Folded, nothing lost. Open a node with `%s open %s <node>`: e3 is an episode, t12 a turn, t12.3 one tool "
389
+ "call with its full input and output." % (ME, s.id[:8])]
390
+ lines_ = [episode_line(i, ep) for i, ep in enumerate(eps, 1)]
391
+ if tokens is None:
392
+ body = ["", "## Map"] + lines_ + ["", "## Every turn"] + [render_turn(t) for t in s.turns]
393
+ return "\n".join(out + body), len(s.turns), False, len(lines_)
394
+ room = tokens * CHARS - len("\n".join(out)) - 80
395
+ mapped, used = [], 0
396
+ for line in reversed(lines_):
397
+ if mapped and used + len(line) + 1 > room / 2:
398
+ break
399
+ mapped.append(line)
400
+ used += len(line) + 1
401
+ older = len(lines_) - len(mapped)
402
+ if older:
403
+ note = "e1 to e%d: %d older episode%s; `show --level max` lists them all" % (older, older, "s"[:older > 1])
404
+ mapped.append(note)
405
+ used += len(note) + 1
406
+ room -= used
407
+ shown, cut = [], False
408
+ for turn in reversed(s.turns):
409
+ text = render_turn(turn)
410
+ if len(text) + 1 <= room:
411
+ shown.append(text)
412
+ room -= len(text) + 1
413
+ continue
414
+ # A turn too big for what's left goes in cut to fit, rather than leave the room unused: its start (the ask)
415
+ # and its end (where it got to). The latest turn always shows, however little room there is.
416
+ if room > 1500 or (not shown and room > 400):
417
+ shown.append(squeeze(text, room - 120, turn.node))
418
+ cut = True
419
+ break
420
+ body = ["", "## Map"] + mapped[::-1]
421
+ if shown:
422
+ title = "## Every turn" if len(shown) == len(s.turns) and not cut else \
423
+ "## The last %d turn%s, word for word" % (len(shown), "s"[:len(shown) > 1])
424
+ body += ["", title] + shown[::-1]
425
+ return "\n".join(out + body), len(shown), cut, len(lines_) - older
426
+
427
+
428
+ def open_node(s, node):
429
+ x = s.find(node)
430
+ if x is None:
431
+ return None
432
+ if isinstance(x, list):
433
+ return "\n\n".join([episode_line(int(node[1:]), x)] + [render_turn(t) for t in x])
434
+ if isinstance(x, Turn):
435
+ return render_turn(x, notes=True)
436
+ where = "%s, line %d" % (short(s.path, 120), x.line) + \
437
+ (", result at line %d" % x.result_line if x.result_line else "")
438
+ return "\n".join(["### %s %s (%s)" % (x.node, x.name, where), "input:",
439
+ json.dumps(x.args, indent=1, ensure_ascii=False),
440
+ "output%s:" % (" (an error)" if x.error else ""),
441
+ x.result if x.result is not None else "(no result recorded)"])
442
+
443
+
444
+ def search(s, pattern, most=50):
445
+ rx = re.compile(pattern, re.I)
446
+ hits = []
447
+
448
+ def look(node, where, text):
449
+ m = rx.search(text or "")
450
+ if m:
451
+ hits.append("%s %s: %s" % (node, where, one_line(text[max(0, m.start() - 120):m.end() + 120], 300)))
452
+
453
+ for turn in s.turns:
454
+ look(turn.node, turn.who, turn.words)
455
+ for kind, x in turn.items:
456
+ if kind == "text":
457
+ look(turn.node, "agent", x)
458
+ else:
459
+ look(x.node, "input", json.dumps(x.args, ensure_ascii=False))
460
+ look(x.node, "output", x.result)
461
+ for _, words in turn.notes:
462
+ look(turn.node, "note", words)
463
+ return hits[:most] + (["… and %d more" % (len(hits) - most)] if len(hits) > most else [])
464
+
465
+
466
+ def prime(s, tokens=8000):
467
+ """The opening message for a new session, in about `tokens` tokens (None: every turn). Returns what fold does."""
468
+ intro = ("You are picking up work from an earlier Claude Code session (%s, in %s). Its whole history is kept. What "
469
+ "follows is a folded view of it: a map of its episodes, then its last turns word for word. When something "
470
+ "from the past matters, open the node it came from rather than guess:\n %s open %s <node>\n"
471
+ "and search the whole history with:\n %s search %s '<words or regex>'\n"
472
+ "Files may have changed since, so read them fresh rather than trusting an old copy.\n\n"
473
+ % (s.id[:8], short(s.cwd), ME, s.id[:8], ME, s.id[:8]))
474
+ text, *rest = fold(s, None if tokens is None else max(500, tokens - len(intro) // CHARS))
475
+ return (intro + text, *rest)
476
+
477
+
478
+ def live():
479
+ """The sessions running on this machine now, from runwatch: session id -> its row. Empty without runwatch."""
480
+ exe = shutil.which("runwatch") or os.path.expanduser("~/.local/bin/runwatch")
481
+ try:
482
+ out = subprocess.run([exe, "ps", "--json", "--here"], capture_output=True, text=True, timeout=8).stdout
483
+ rows = json.loads(out)
484
+ except (OSError, ValueError, subprocess.SubprocessError):
485
+ return {}
486
+ rows = rows.get("sessions", []) if isinstance(rows, dict) else rows
487
+ return {r["session"]: r for r in rows if isinstance(r, dict) and r.get("session")}
488
+
489
+
490
+ def where_it_runs(row):
491
+ reach = row.get("reach") if isinstance(row.get("reach"), dict) else {}
492
+ if reach.get("kind") == "tmux":
493
+ return "in tmux session %s" % str(reach.get("target") or "?").split(":")[0]
494
+ if reach.get("kind") == "window":
495
+ return "in a terminal of its own"
496
+ return "in the background"
497
+
498
+
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."""
501
+ now, last = time.time(), s.last_active()
502
+ task = task_of(s.episodes()[-1]) if s.turns else None
503
+ latest = next((t for t in reversed(s.turns) if t.who == "you"), None)
504
+ 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
+ out = ["%s: your last session here (%s) was active %s, %s." % (
511
+ os.path.basename(s.cwd or "?"), s.id[:8], stamp(last), ago(now - last))]
512
+ if task:
513
+ out.append('The task: "%s"' % one_line(heading_words(task), 150))
514
+ if latest and latest is not task:
515
+ out.append('Last you said: "%s"' % one_line(heading_words(latest), 150))
516
+ row = (running or {}).get(s.id)
517
+ if row:
518
+ state = {"working": "working on it right now", "needs-input": "waiting for you",
519
+ "done": "done and waiting for your next message"}.get(row.get("state"), row.get("state") or "open")
520
+ 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)]
536
+ return "\n".join(out)
537
+
538
+
539
+ def tail(path, size=262144):
540
+ """The end of a session's log, read fast: when it last worked, its window and model, its folder and the last thing
541
+ a person said. Enough to tell warm from cooled without reading the whole file."""
542
+ info = {"last": None, "window": 0, "model": None, "cwd": None, "said": ""}
543
+ with open(path, "rb") as f:
544
+ f.seek(0, 2)
545
+ end = f.tell()
546
+ f.seek(max(0, end - size))
547
+ chunk = f.read().decode("utf-8", "replace").splitlines()
548
+ for line in reversed(chunk[1:] if end > size else chunk): # the first line of a cut chunk is half a line
549
+ try:
550
+ e = json.loads(line)
551
+ except ValueError:
552
+ continue
553
+ if not isinstance(e, dict) or e.get("isSidechain"):
554
+ continue
555
+ info["cwd"] = info["cwd"] or e.get("cwd")
556
+ message = e.get("message") if isinstance(e.get("message"), dict) else {}
557
+ if e.get("type") in ("user", "assistant") and info["last"] is None:
558
+ info["last"] = when(e)
559
+ usage = message.get("usage")
560
+ if e.get("type") == "assistant" and not info["model"] and isinstance(usage, dict) and \
561
+ message.get("model") not in (None, "<synthetic>"):
562
+ info["window"] = sum(usage.get(k) or 0 for k in
563
+ ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"))
564
+ info["model"] = message["model"]
565
+ if e.get("type") == "user" and not info["said"] and starter(e) == "you":
566
+ info["said"] = text_of(message.get("content"))
567
+ if info["last"] and info["model"] and info["said"] and info["cwd"]:
568
+ break
569
+ info["last"] = info["last"] or os.path.getmtime(path)
570
+ return info
571
+
572
+
573
+ def cache_file():
574
+ home = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")
575
+ return os.path.join(home, "ctxtree", "openings-v2.json")
576
+
577
+
578
+ def start_tokens(folder):
579
+ """Tokens a new session in this folder holds at its first reply (Claude Code's system prompt and tools, plus what
580
+ start-up hooks add there), the middle of its recent sessions; START when there are fewer than 3 to go by. A first
581
+ reply over 150k is a resumed session, not a fresh start, and is left out."""
582
+ sizes = []
583
+ for path in sorted(glob.glob(os.path.join(folder, "*.jsonl")), key=os.path.getmtime, reverse=True)[:12]:
584
+ try:
585
+ with open(path, errors="replace") as f:
586
+ for line in f:
587
+ if '"usage"' not in line:
588
+ continue
589
+ e = json.loads(line)
590
+ m = e.get("message") if isinstance(e.get("message"), dict) else {}
591
+ u = m.get("usage")
592
+ if e.get("type") == "assistant" and not e.get("isSidechain") and isinstance(u, dict) and \
593
+ m.get("model") != "<synthetic>":
594
+ size = sum(u.get(k) or 0 for k in
595
+ ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"))
596
+ if 0 < size < 150000:
597
+ sizes.append(size)
598
+ break
599
+ except (OSError, ValueError):
600
+ continue
601
+ sizes.sort()
602
+ return sizes[len(sizes) // 2] if len(sizes) >= 3 else START
603
+
604
+
605
+ def opening_tokens(path, level):
606
+ """Tokens a fresh start from this session holds (Claude Code's own start plus the opening). Remembered per file
607
+ size and level, so a session that has stopped changing is read in full once. The file keeps only numbers."""
608
+ key, st = os.path.realpath(path), os.stat(path)
609
+ try:
610
+ with open(cache_file()) as f:
611
+ known = json.load(f)
612
+ except (OSError, ValueError):
613
+ known = {}
614
+ if known.get(key, [])[:3] == [st.st_size, int(st.st_mtime), level]:
615
+ return known[key][3]
616
+ s = Session(path)
617
+ tokens = start_tokens(os.path.dirname(path)) + len(prime(s, budget(level, s))[0]) // CHARS
618
+ known = {k: v for k, v in known.items() if os.path.exists(k)}
619
+ known[key] = [st.st_size, int(st.st_mtime), level, tokens]
620
+ os.makedirs(os.path.dirname(cache_file()), mode=0o700, exist_ok=True)
621
+ with open(cache_file() + ".new", "w") as f:
622
+ json.dump(known, f)
623
+ os.replace(cache_file() + ".new", cache_file())
624
+ return tokens
625
+
626
+
627
+ def status_of(path, level, now=None):
628
+ """Warm or cooled, and what each way back costs at list price, from the end of the log (and, for a cooled
629
+ session, the size of its fresh start)"""
630
+ now, i = now or time.time(), tail(path)
631
+ read, write = READ.get(i["model"] or ""), WRITE.get(i["model"] or "")
632
+ money = lambda tokens, price: round(tokens * price / 1e6, 2) if price else None # noqa: E731
633
+ out = {"session": os.path.basename(path)[:-len(".jsonl")], "cwd": i["cwd"], "last": int(i["last"]), "ttl": TTL,
634
+ "window": i["window"], "model": i["model"], "said": one_line(i["said"], 200),
635
+ "warm_usd": money(i["window"], read), "cold_usd": money(i["window"], write),
636
+ "fresh_tokens": None, "fresh_usd": None}
637
+ if i["last"] + TTL <= now and i["window"] >= 20000:
638
+ try:
639
+ out["fresh_tokens"] = opening_tokens(path, level)
640
+ out["fresh_usd"] = money(out["fresh_tokens"], write)
641
+ except (OSError, ValueError):
642
+ pass
643
+ return out
644
+
645
+
646
+ def hook(event, now=None):
647
+ """What the plugin's SessionStart hook says, if anything. Resuming a big session whose cache has cooled: a word to
648
+ 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."""
650
+ now = now or time.time()
651
+ if event.get("source") == "resume":
652
+ tokens, path = event.get("context_tokens") or 0, event.get("transcript_path") or ""
653
+ if event.get("prompt_cache_likely_expired") and tokens >= 100000 and os.path.exists(path):
654
+ fresh, usd = opening_tokens(path, level_in_force()), event.get("estimated_cache_write_usd")
655
+ return {"systemMessage": "Picking this session up re-caches %dk tokens%s. To start fresh from its folded "
656
+ "history instead (about %dk tokens, every word still reachable), quit and run: "
657
+ "%s resume %s" % (tokens // 1000, ", about $%.2f" % usd if usd else "",
658
+ fresh // 1000, ME, os.path.basename(path)[:8])}
659
+ return None
660
+ if event.get("source") != "startup":
661
+ return None
662
+ folder = os.path.join(ROOT, folder_key(os.path.abspath(event.get("cwd") or os.getcwd())))
663
+ others = sorted((p for p in glob.glob(os.path.join(folder, "*.jsonl")) if os.path.getsize(p) > 2000 and
664
+ os.path.basename(p)[:-len(".jsonl")] != event.get("session_id")), key=os.path.getmtime)
665
+ if not others:
666
+ return None
667
+ i = tail(others[-1])
668
+ age = now - i["last"]
669
+ if age <= TTL or age > 14 * 86400 or i["window"] < 100000:
670
+ return None
671
+ note = ("Earlier work in this folder is kept in full and can be searched. The last session here (%s, %s) ended "
672
+ "on: \"%s\". When the user refers to earlier work, find it with `%s search --here '<regex>'`, then open "
673
+ "the node a hit names with `%s open <session> <node>`; `%s show <session>` maps a session."
674
+ % (os.path.basename(others[-1])[:8], ago(age), one_line(i["said"], 160), ME, ME, ME))
675
+ return {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": note}}
676
+
677
+
678
+ def state_dir():
679
+ d = os.path.join(os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"), "ctxtree")
680
+ os.makedirs(d, mode=0o700, exist_ok=True)
681
+ return d
682
+
683
+
684
+ def resume(s, tokens, dry=False):
685
+ """Start Claude Code in the session's folder, told to read the folded view first. The view goes in a private file
686
+ (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)
691
+ 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]))
693
+ folder = s.cwd if s.cwd and os.path.isdir(s.cwd) else os.getcwd()
694
+ if dry:
695
+ print("cd %s && claude %s" % (shlex.quote(folder), shlex.quote(ask)))
696
+ return 0
697
+ if not shutil.which("claude"):
698
+ sys.exit("claude isn't on your PATH. The opening is in %s" % path)
699
+ os.chdir(folder)
700
+ os.execvp("claude", ["claude", ask])
701
+
702
+
703
+ def check(s):
704
+ """Every tool call and every tool result in the file opens, and opens to exactly the text the file holds"""
705
+ 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")))
720
+ calls = {c.id: c for t in s.turns for c in t.calls()}
721
+ missing = uses - set(calls)
722
+ unopened = [k for k in results if k not in calls]
723
+ wrong = [k for k, (line_no, body) in results.items() if k in calls and
724
+ (calls[k].result != body or calls[k].result_line != line_no)]
725
+ return {"calls": len(uses), "results": len(results), "missing_calls": len(missing),
726
+ "unopened_results": len(unopened), "wrong_results": len(wrong)}
727
+
728
+
729
+ def folder_key(path):
730
+ """The name Claude Code gives a folder's sessions directory: every character but letters and digits becomes -"""
731
+ return re.sub(r"[^A-Za-z0-9]", "-", path)
732
+
733
+
734
+ def here(cwd=None):
735
+ """This folder's sessions, newest first, leaving out empty ones and the Claude Code session this runs inside"""
736
+ d = os.path.join(ROOT, folder_key(os.path.abspath(cwd or os.getcwd())))
737
+ me = os.environ.get("CLAUDE_CODE_SESSION_ID")
738
+ return [p for p in sorted(glob.glob(os.path.join(d, "*.jsonl")), key=os.path.getmtime, reverse=True)
739
+ if os.path.getsize(p) > 2000 and os.path.basename(p)[:-len(".jsonl")] != me]
740
+
741
+
742
+ def newest_here(cwd=None):
743
+ found = here(cwd)
744
+ if not found:
745
+ sys.exit("No Claude Code sessions for this folder. Run it in a project folder, or name a session.")
746
+ return found[0]
747
+
748
+
749
+ def find_session(arg):
750
+ """A session's log by id, id prefix (6 or more characters) or path; None when not exactly one matches"""
751
+ if arg.endswith(".jsonl") and os.path.exists(arg):
752
+ return arg
753
+ found = glob.glob(os.path.join(ROOT, "*", glob.escape(arg) + "*.jsonl")) if len(arg) >= 6 else []
754
+ return found[0] if len(found) == 1 else None
755
+
756
+
757
+ def locate(arg):
758
+ if not arg:
759
+ return newest_here()
760
+ path = find_session(arg)
761
+ if not path:
762
+ sys.exit("No single session matches %r; give 6 or more characters of its id, or its path" % arg)
763
+ return path
764
+
765
+
766
+ def recent_paths(days, project=None):
767
+ since = time.time() - days * 86400
768
+ return sorted((p for p in glob.glob(os.path.join(ROOT, "*", "*.jsonl"))
769
+ if os.path.getmtime(p) >= since and (not project or project in os.path.dirname(p))),
770
+ key=os.path.getmtime)
771
+
772
+
773
+ def main(argv):
774
+ ap = argparse.ArgumentParser(prog="ctxtree", description=__doc__.split("\n\n")[0])
775
+ ap.add_argument("--version", action="version", version="ctxtree " + __version__)
776
+ sub = ap.add_subparsers(dest="verb")
777
+ upto = argparse.ArgumentParser(add_help=False)
778
+ upto.add_argument("--upto", help="see the session only as it stood before this turn, such as t29")
779
+ lv = argparse.ArgumentParser(add_help=False)
780
+ 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])
784
+ p.add_argument("session", nargs="?")
785
+ p.add_argument("--dry-run", action="store_true", help="write the opening and print the command, but don't start")
786
+ sub.add_parser("open", parents=[upto]).add_argument("args", nargs="+", metavar="[SESSION] NODE")
787
+ p = sub.add_parser("search", parents=[upto])
788
+ p.add_argument("args", nargs="+", metavar="[SESSION] PATTERN")
789
+ p.add_argument("--here", action="store_true", help="every session in this folder from the last 30 days")
790
+ sub.add_parser("level").add_argument("name", nargs="?")
791
+ p = sub.add_parser("status", parents=[lv])
792
+ p.add_argument("session", nargs="*")
793
+ p.add_argument("--json", action="store_true")
794
+ sub.add_parser("hook")
795
+ p = sub.add_parser("sessions")
796
+ p.add_argument("--days", type=float, default=7)
797
+ p.add_argument("--project")
798
+ p.add_argument("--min", type=float, default=1.0, help="leave out sessions under this many million characters")
799
+ p = sub.add_parser("check")
800
+ p.add_argument("session", nargs="*")
801
+ p.add_argument("--all", action="store_true")
802
+ p.add_argument("--days", type=float, default=7)
803
+ a = ap.parse_args(argv)
804
+
805
+ if a.verb == "hook":
806
+ try:
807
+ out = hook(json.loads(sys.stdin.read() or "{}"))
808
+ except Exception: # noqa: BLE001 - a hook must never get in the way of a session starting
809
+ out = None
810
+ if out:
811
+ print(json.dumps(out))
812
+ return 0
813
+ if a.verb == "status":
814
+ level = level_in_force(a.level)
815
+ paths = [p for p in map(find_session, a.session) if p] if a.session else here()[:1]
816
+ rows = [status_of(p, level) for p in paths]
817
+ if not rows and not a.json:
818
+ print("No other Claude Code session in this folder to say anything about.")
819
+ if a.json:
820
+ print(json.dumps(rows))
821
+ for r in rows if not a.json else []:
822
+ left = r["last"] + r["ttl"] - time.time()
823
+ print("%s %-16s %s window %dk%s" % (
824
+ r["session"][:8], os.path.basename(r["cwd"] or "?")[:16],
825
+ "warm %dm" % (left // 60 + 1) if left > 0 else "cooled %s" % ago(-left),
826
+ r["window"] // 1000, " back $%.2f, fresh $%.2f" % (r["cold_usd"], r["fresh_usd"])
827
+ if left <= 0 and r["cold_usd"] is not None and r["fresh_usd"] is not None else ""))
828
+ return 0
829
+ 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")
839
+ return 0
840
+ if a.verb == "sessions":
841
+ level = level_in_force()
842
+ print("Opening at level %s. words: every turn folded, as a share of the whole history." % level)
843
+ print("%-8s %-16s %-12s %5s %8s %7s %7s %7s" %
844
+ ("session", "folder", "last", "turns", "history", "words", "window", "opening"))
845
+ for path in recent_paths(a.days, a.project):
846
+ s = Session(path)
847
+ if s.chars < a.min * 1e6 or not s.turns:
848
+ continue
849
+ print("%-8s %-16s %-12s %5d %7.1fM %6.1f%% %6dk %6.1fk" % (
850
+ s.id[:8], os.path.basename(s.cwd or "?")[:16], stamp(os.path.getmtime(path)), len(s.turns),
851
+ s.chars / 1e6, 100 * len(fold(s, None)[0]) / s.chars, s.window / 1e3,
852
+ len(prime(s, tokens_for(level, s)[1])[0]) / (CHARS * 1000)))
853
+ return 0
854
+ if a.verb == "level":
855
+ if a.name:
856
+ try:
857
+ budget(a.name)
858
+ except ValueError as e:
859
+ sys.exit(str(e))
860
+ os.makedirs(os.path.dirname(config_path()), exist_ok=True)
861
+ with open(config_path(), "w") as f:
862
+ f.write("# ctxtree: how much the opening message holds. auto, low, medium, high, xhigh, max or a "
863
+ "size such as 30k.\nlevel = %s\n" % a.name)
864
+ print(slider(a.name))
865
+ print("Saved in %s. --level or CTXTREE_LEVEL still win for one run." % short(config_path(), 120))
866
+ else:
867
+ level = level_in_force()
868
+ source = "CTXTREE_LEVEL" if os.environ.get("CTXTREE_LEVEL") else \
869
+ 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
872
+ print(slider(level, s))
873
+ print("From %s. Change it with: %s level <%s|30k>" % (source, ME, "|".join(NAMES)))
874
+ return 0
875
+ if a.verb == "check":
876
+ paths = recent_paths(a.days) if a.all else [locate(x) for x in a.session] or [newest_here()]
877
+ bad = 0
878
+ for path in paths:
879
+ r = check(Session(path))
880
+ lost = r["missing_calls"] + r["unopened_results"] + r["wrong_results"]
881
+ bad += lost > 0
882
+ if lost or not a.all:
883
+ 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"],
885
+ r["unopened_results"], r["wrong_results"]))
886
+ print("%d of %d sessions lossless" % (len(paths) - bad, len(paths)))
887
+ return 1 if bad else 0
888
+
889
+ rest = None
890
+ if a.verb in ("open", "search"):
891
+ if len(a.args) > 2:
892
+ sys.exit("give at most a session and a %s" % ("node" if a.verb == "open" else "pattern"))
893
+ session, rest = (a.args[0], a.args[1]) if len(a.args) == 2 else (None, a.args[0])
894
+ else:
895
+ session = getattr(a, "session", None)
896
+ s = Session(locate(session))
897
+ if getattr(a, "upto", None):
898
+ m = re.fullmatch(r"t(\d+)", a.upto)
899
+ if not m:
900
+ sys.exit("--upto takes a turn, such as t29")
901
+ s.turns = s.turns[:int(m.group(1)) - 1]
902
+ if a.verb is None:
903
+ print(card(s, level_in_force(), live()))
904
+ 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])
910
+ 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))
918
+ if not a.upto:
919
+ print("Its window held %dk tokens at the last reply: what coming back after a lapse re-caches."
920
+ % (s.window // 1000))
921
+ elif a.verb == "search":
922
+ print("\n".join(search(s, rest)) or "nothing matches")
923
+ else:
924
+ out = open_node(s, rest)
925
+ if out is None:
926
+ sys.exit("no node %r: try e1 (an episode), t1 (a turn) or t1.1 (a tool call)" % rest)
927
+ print(out)
928
+ return 0
929
+
930
+
931
+ def entry():
932
+ """The ctxtree command"""
933
+ import signal
934
+ if hasattr(signal, "SIGPIPE"):
935
+ signal.signal(signal.SIGPIPE, signal.SIG_DFL) # piped into head: stop quietly
936
+ sys.exit(main(sys.argv[1:]))
937
+
938
+
939
+ if __name__ == "__main__":
940
+ entry()