The folder is the state: /molt saves a handoff to .state/ and compacts in place; /molt-lint and /molt-graph keep the folder honest. No automatic molts.

When context outgrows its shell, shed it into the folder and keep going.
A Claude Code mod. One command you run on purpose, no new session, nothing running in the background.
If your Claude Code usage looks like this, the cache is not your problem:
| Tokens, one project, one week | 158.7M |
| Cache hit rate | 96% |
| Cache read | 152.2M |
| Cache write | 5M |
| Uncached input | 0.7M |
| Output | 0.8M |
That is a healthy cache. Only 4% of input missed it. Yet 96% of all tokens were cache reads, and cache reads are what you pay for a long thread: every API call resends the whole conversation. A hit is cheaper than a miss, but half a million tokens of hits per call, hundreds of times a day, is still the bill.
Parsing the session transcripts (~/.claude/projects/<project>/*.jsonl, one usage per assistant message) found where it went. One thread had been kept open for seven days:
| The seven-day thread | |
|---|---|
| API calls | 618 |
| Average context per call | ~480k tokens |
| Peak context | 966k of a 1M window |
| Cache reads | 296M |
| Full cache rewrites | 14, each 550k to 850k tokens |
| Subagents spawned, all on the most expensive model | 61 |
Two mechanisms did the damage.
1. Thread length. Every tool call re-read ~480k tokens. A fresh session costs ~70k tokens of system prompt, tools, skills and memory. Resuming the thread cost 480k on the first message and on every call after it. The second-largest thread, same setup, averaged 230k per call and cost a quarter as much. Spend tracks thread length.
2. The cache expiring while you sleep. The prompt cache lives one hour on a subscription (five minutes on an API key). Every morning's first message rewrote the entire context at full write price. Fourteen such rewrites, 550k to 850k tokens each, every one after an idle gap over an hour. Auto-compact never helped: on a 1M-window model it fires at about 967k by default.
What it was not: the personal harness, hooks, voice calls and planning rituals accounted for under 4% of the tokens. Uninstalling them would have changed nothing. Measure before you blame your tooling.
/autocompact 150k sets the auto-compact window per model and saves it./clear between unrelated tasks. /compact <focus> at natural breaks.CLAUDE_CODE_SUBAGENT_MODEL=sonnet in settings.json env: subagents inherit the main model unless told otherwise.CLAUDE_CODE_PROMPT_CACHE_TTL=1h where available./context and /usage to see what fills the window and what hits the cache.Those cap the size. Molt adds the part they do not: a handoff in a folder, so a compaction, a /clear or a new session resumes from where you stopped.
Version 0.3 molted by itself, on an idle timer and on context size. Over two weeks its own turns were 13–87% of each session's tokens. A molt costs 3–4 full context reads (the handoff turn's calls plus the compaction); the cold cache rewrite it was meant to avoid costs one write. The automatic molts ate the per-call gain, so 0.4.0 removes them.
Claude Code's own /autocompact 150k caps the context for free; pair molt with it. What is worth keeping is the folder-as-state convention and the commands you run on purpose.
The call is /molt. The model saves state to .state/; the mod then compacts the session in place with instructions to keep only what the handoff does not cover. Same session, same prompt box, next call carries a fraction of the tokens.
.state/
INDEX.md routing table: one line per note, says WHEN to read it (cap 200)
HANDOFF.md where the last stretch stopped (cap 60; rewritten by each molt)
log.md append-only history; grep it, never load it whole
notes/*.md decisions, failures, patterns; frontmatter links/files form the graph
INDEX.md and a fresh HANDOFF.md ride the first user message next to CLAUDE.md. A HANDOFF older than 7 days is marked stale, not trusted. The folder is harness-agnostic: any agent that reads markdown can continue from it.
| Surface | Commands |
|---|---|
| Terminal, Desktop app | /molt, /molt-lint, /molt-graph |
| Remote Control thread (phone or claude.ai driving your own machine) | /molt, and /molt lint with a space |
Cloud session (claude.ai Projects, claude.ai/code, claude --cloud) | the same, once the environment loads molt (below) |
| Plain claude.ai chat without Claude Code | none: no plugins run there |
A cloud session runs in a fresh container and does not install plugins a repository declares in .claude/settings.json. Load molt through the environment instead. In claude.ai, open the project's settings, edit its cloud environment, and set:
Environment variables:
CLAUDE_CODE_PLUGIN_DIRS=~/molt
Setup script:
git clone --depth 1 https://github.com/wisbech/molt.git ~/molt
The setup script runs before Claude Code starts, and CLAUDE_CODE_PLUGIN_DIRS loads the clone like --plugin-dir. Every thread in that project then has /molt. Because the container is wiped between sessions, a cloud /molt commits .state/ and pushes the thread's branch, so the next session resumes from it.
Paste this into Claude Code and let the agent do it:
Install the molt mod for Claude Code:
1. claude plugin marketplace add wisbech/molt
2. claude plugin install molt@molt
3. If the build says hooks modules are early access, add "CLAUDE_CODE_ENABLE_FUNCTION_HOOKS": "1" under "env" in ~/.claude/settings.json.
Then tell me whether /molt shows up in the command list.
By hand:
claude plugin marketplace add wisbech/molt
claude plugin install molt@molt
Or for one launch, without installing: claude --plugin-dir /path/to/molt.
Site: https://wisbech.github.io/molt/ · Tests: CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude plugin test .
/molt [note] before you leave a thread or when it feels heavy. The model writes the handoff to .state/, then the session compacts in place. The note goes to the next stretch./molt-lint is free deterministic housekeeping: index cap, orphans, broken links, superseded notes still routed, notes about deleted files, stale handoff. No model turn./molt-graph prints note -> links. Also free./autocompact 150k for the context cap. It is Claude Code's own, it is free, and molt leaves that job to it.python3 - <<'EOF'
import json, glob, os
d = os.path.expanduser('~/.claude/projects/')
for f in sorted(glob.glob(d + '*/*.jsonl'), key=os.path.getsize, reverse=True)[:5]:
seen, n, cr, cw, mx = set(), 0, 0, 0, 0
for line in open(f):
try: o = json.loads(line)
except: continue
m = o.get('message') or {}; u = m.get('usage') or {}
if o.get('type') != 'assistant' or not u or m.get('id') in seen: continue
seen.add(m.get('id')); n += 1
ctx = u.get('input_tokens', 0) + u.get('cache_read_input_tokens', 0) + u.get('cache_creation_input_tokens', 0)
cr += u.get('cache_read_input_tokens', 0); cw += u.get('cache_creation_input_tokens', 0); mx = max(mx, ctx)
print(f"{os.path.basename(f)[:8]} calls={n} avg_ctx={(cr+cw)/max(n,1)/1e3:.0f}k peak={mx/1e3:.0f}k cache_read={cr/1e6:.0f}M cache_write={cw/1e6:.1f}M")
EOF
If avg_ctx is a few hundred k, you have the problem above.
hooks/register.tsx 209 lines1// molt: the folder is the state. /molt saves a handoff to .state/, then compacts the session in place.
2// Call: the /molt command (commands/molt.md) has the model save state to .state/,
3// then this module compacts the session in place. Same session, small context.
4//
5// .state/INDEX.md routing table, one line per note, says WHEN to read it (cap 200)
6// .state/HANDOFF.md where the last stretch stopped (cap 60, rewritten by each molt)
7// .state/log.md append-only history, greppable, never injected whole
8// .state/notes/*.md decisions, failures, patterns; frontmatter links/files = the graph
9import type { EngineInterface as Engine, Register } from 'claude-code'
10
11const DIR = '.state'
12const INDEX_CAP = 200
13const HANDOFF_CAP = 60
14const STALE_DAYS = 7
15const DAY = 86_400_000
16
17type Note = { id: string; path: string; title: string; status: string; links: string[]; files: string[] }
18type Lint = { problems: string[]; notes: Note[]; indexLines: number }
19
20// Module state. A reload starts it over, which is fine: it is all derivable.
21const S = {
22 section: null as string | null, // the context block; re-read after every molt
23 phase: 'idle' as 'idle' | 'shedding',
24}
25
26function frontmatter(text: string): Record<string, string> {
27 const m = /^---\n([\s\S]*?)\n---/.exec(text)
28 const out: Record<string, string> = {}
29 for (const line of (m?.[1] ?? '').split('\n')) {
30 const i = line.indexOf(':')
31 if (i > 0) out[line.slice(0, i).trim()] = line.slice(i + 1).trim()
32 }
33 return out
34}
35
36// `links: [a, b]`, `links: a, b`, plus [[wikilinks]] in the body
37function listOf(value: string | undefined, body: string, wiki: boolean): string[] {
38 const items = (value ?? '')
39 .replace(/^\[|\]$/g, '')
40 .split(/[,\s]+/)
41 .map(s => s.trim().replace(/^["']|["']$/g, ''))
42 .filter(Boolean)
43 if (wiki) for (const w of body.matchAll(/\[\[([^\]|#]+)/g)) items.push((w[1] ?? '').trim())
44 return [...new Set(items.filter(Boolean))]
45}
46
47async function readText($: Engine, path: string): Promise<string> {
48 return String(await $.fs.read(path))
49}
50
51async function readCapped($: Engine, path: string, cap: number): Promise<string | null> {
52 if (!(await $.fs.exists(path))) return null
53 const lines = (await readText($, path)).split('\n')
54 if (lines.length <= cap) return lines.join('\n')
55 return `${lines.slice(0, cap).join('\n')}\n… ${lines.length - cap} more lines cut. Keep this file under ${cap} lines.`
56}
57
58async function ageDays($: Engine, path: string): Promise<number> {
59 return ((await $.clock.now()) - (await $.fs.stat(path)).mtimeMs) / DAY
60}
61
62async function readNotes($: Engine): Promise<Note[]> {
63 if (!(await $.fs.exists(`${DIR}/notes`))) return []
64 const notes: Note[] = []
65 for (const entry of await $.fs.list(`${DIR}/notes`)) {
66 if (entry.kind !== 'file' || !entry.name.endsWith('.md')) continue
67 const text = await readText($, `${DIR}/notes/${entry.name}`)
68 const fm = frontmatter(text)
69 const id = entry.name.replace(/\.md$/, '')
70 notes.push({
71 id,
72 path: `notes/${entry.name}`,
73 title: fm.title ?? id,
74 status: fm.status ?? 'active',
75 links: listOf(fm.links, text, true).map(l => l.replace(/\.md$/, '').replace(/^notes\//, '')),
76 files: listOf(fm.files, '', false),
77 })
78 }
79 return notes
80}
81
82// Deterministic housekeeping: no model, no tokens.
83async function lint($: Engine): Promise<Lint> {
84 const problems: string[] = []
85 const notes = await readNotes($)
86 const ids = new Set(notes.map(n => n.id))
87 const index = (await $.fs.exists(`${DIR}/INDEX.md`)) ? await readText($, `${DIR}/INDEX.md`) : null
88 const indexLines = index ? index.split('\n').filter((l: string) => l.trim()).length : 0
89
90 if (index === null) {
91 if (notes.length) problems.push(`no ${DIR}/INDEX.md but ${notes.length} note(s): nothing routes to them`)
92 } else {
93 if (indexLines > INDEX_CAP) problems.push(`INDEX.md has ${indexLines} lines, cap is ${INDEX_CAP}: merge or archive`)
94 for (const m of index.matchAll(/\]\(([^)]+\.md)\)/g)) {
95 const target = (m[1] ?? '').replace(/^\.\//, '')
96 if (!(await $.fs.exists(`${DIR}/${target}`))) problems.push(`INDEX.md links to missing ${target}`)
97 }
98 for (const n of notes) {
99 const routed = index.includes(n.path)
100 if (!routed && n.status === 'active') problems.push(`orphan: ${n.path} is not in INDEX.md`)
101 if (routed && n.status !== 'active') problems.push(`${n.path} is ${n.status} but still in INDEX.md`)
102 }
103 }
104 for (const n of notes) {
105 for (const l of n.links) if (!ids.has(l)) problems.push(`${n.path} links to unknown note "${l}"`)
106 for (const f of n.files) if (!(await $.fs.exists(f))) problems.push(`${n.path} is about ${f}, which no longer exists`)
107 }
108 if (await $.fs.exists(`${DIR}/HANDOFF.md`)) {
109 const age = await ageDays($, `${DIR}/HANDOFF.md`)
110 if (age > STALE_DAYS) problems.push(`HANDOFF.md is ${Math.round(age)} days old: verify against git log before trusting it`)
111 }
112 return { problems, notes, indexLines }
113}
114
115// What a fresh stretch reads: the routing table and where the last one stopped.
116async function compose($: Engine): Promise<string | null> {
117 const index = await readCapped($, `${DIR}/INDEX.md`, INDEX_CAP)
118 let handoff: string | null = null
119 if (await $.fs.exists(`${DIR}/HANDOFF.md`)) {
120 const age = await ageDays($, `${DIR}/HANDOFF.md`)
121 handoff =
122 age <= STALE_DAYS
123 ? await readCapped($, `${DIR}/HANDOFF.md`, HANDOFF_CAP + 20)
124 : `(${Math.round(age)} days old, stale. Check git log before trusting it.)`
125 }
126 if (index === null && handoff === null) return null
127 return [
128 `The folder is the state. ${DIR}/INDEX.md is the routing table: one line per note saying when to read it; open a note only when its line applies. ${DIR}/HANDOFF.md is where the last stretch stopped. ${DIR}/log.md is append-only history; grep it, never load it whole. /molt saves state here, then the session compacts.`,
129 index !== null ? `## ${DIR}/INDEX.md\n${index}` : '',
130 handoff !== null ? `## ${DIR}/HANDOFF.md\n${handoff}` : '',
131 ]
132 .filter(Boolean)
133 .join('\n\n')
134}
135
136const COMPACT_INSTRUCTIONS = `The project state was just saved to ${DIR}/HANDOFF.md and ${DIR}/INDEX.md, which the conversation carries. Keep only: the user's latest request, what is in progress right now, files currently being edited, and any tool result the very next step needs. Drop everything the handoff covers.`
137
138// The free answers: lint and graph never touch the model.
139async function answer($: Engine, what: 'lint' | 'graph'): Promise<{ text: string }> {
140 const { problems, notes, indexLines } = await lint($)
141 if (what === 'graph') return { text: graphText(notes) }
142 const head = `${DIR}/: ${notes.length} note(s), INDEX.md ${indexLines}/${INDEX_CAP} lines`
143 return { text: problems.length ? `${head}\n${problems.map(p => `- ${p}`).join('\n')}` : `${head}\nclean.` }
144}
145
146function graphText(notes: Note[]): string {
147 if (!notes.length) return `${DIR}/notes/ is empty.`
148 return notes
149 .map(
150 n =>
151 `${n.id}${n.status !== 'active' ? ` (${n.status})` : ''} -> ${n.links.join(', ') || '(no links)'}${n.files.length ? ` files: ${n.files.join(', ')}` : ''}`,
152 )
153 .join('\n')
154}
155
156export const register: Register = on => {
157 on('session.start', async ($, e, next) => {
158 // Registered commands raise command.run and answer without a model turn, in every mode.
159 // (/molt itself is the plugin's markdown command: a skill the model expands.)
160 await $.command.register({ name: 'molt-lint', description: `Lint ${DIR}/: index cap, orphans, broken links, stale handoff. Free.` })
161 await $.command.register({ name: 'molt-graph', description: `Print ${DIR}/notes links as note -> links. Free.` })
162 S.section = await compose($)
163 const { problems } = await lint($)
164 if (problems.length) $.ui.toast(`${DIR}: ${problems.length} lint issue(s). Run /molt-lint.`)
165 return next(e)
166 })
167
168 // Rides the first user message next to claudeMd; changes only when a molt rewrote the files.
169 on('prompt.context', async ($, e, next) => {
170 const r = await next(e)
171 if (S.section === null) return r
172 return { ...r, blocks: [...r.blocks, { name: 'molt', text: S.section }] }
173 })
174
175 // The molt turn ended: re-read the files it wrote, then compact. A refused compaction is silent.
176 on('turn.complete', async ($, e, next) => {
177 if (e.agentId) return next(e)
178 if (S.phase === 'shedding') {
179 S.phase = 'idle'
180 if (e.reason === 'answer') {
181 S.section = await compose($)
182 await $.session.compact({ instructions: COMPACT_INSTRUCTIONS }).catch(() => undefined)
183 }
184 }
185 return next(e)
186 })
187
188 // Names may come namespaced (molt:molt-lint) from an installed plugin, bare from --plugin-dir.
189 on('command.run', { command: ['molt-lint', 'molt:molt-lint'] }, $ => answer($, 'lint'))
190 on('command.run', { command: ['molt-graph', 'molt:molt-graph'] }, $ => answer($, 'graph'))
191
192 // A molt is starting: the model is about to save state. Fires however /molt was invoked.
193 on('skill.prompt', { skill: ['molt', 'molt:molt'] }, ($, e, next) => {
194 const arg = /The user adds: (\S*)/.exec(e.text)?.[1]
195 if (arg === 'lint' || arg === 'graph') {
196 // Typed as /molt lint where the skill path took it: hand the model the free answer to relay.
197 return answer($, arg).then(r => ({ text: `Relay this to the user exactly, then stop:\n\n${r.text}` }))
198 }
199 S.phase = 'shedding'
200 return next(e)
201 })
202 on('command.run', { command: ['molt', 'molt:molt'] }, ($, e, next) => {
203 const arg = e.args.trim()
204 if (arg === 'lint' || arg === 'graph') return answer($, arg)
205 S.phase = 'shedding'
206 return next(e)
207 })
208}
209