Claude Code sidebar: plan and execution flow, prompt check at submit, subagent workers, git, memories, output styles and a Hooks tab for the settings hooks.

A Claude Code sidebar (a mod: a hooks module drawn as a pane). Per turn it shows how the model understood the request and how it split it (the Flow tab, published through the plan tool), the execution step by step with each step's model, tokens and cost, and the subagent workers. Around it:
0 keeps the default), the plan as a checklist (1a, 1b run in parallel; press a step for its details), the execution one row per step, and "next time, write it like this" always last. A step the model would hand to a subagent on another model shows the suggestion; nothing is delegated until you press it. No model routing: the session model does the work.unlink keeps the word; what the Sonnet audit flagged, with fix/delete; code that is gone; a memory outside MEMORY.md), then one section per type. The audit first checks the paths and symbols each memory names against the repo.Every tab uses Flow's layout: a card on top with where things stand, NEEDS YOU for decisions, foldable sections with the summary on the right.
Aa, y) — the output styles, two lines each: the name (opens it to edit the description and instructions line by line) with use on the right, the description under it. use writes outputStyle in settings.json, read at the start of the next session; a new style starts as a copy of the active one..claude/settings.json, .claude/settings.local.json) can be added, edited, deleted and turned off. "Off" parks the hook in a sibling *.hooks-off.json; a change applies from the next session..codegraph/ index, codegraph_explore goes before Grep/Glob./lens opens the pane. Hotkeys inside it: f Flow, c Git, e Memories, h Hooks, y Styles, k prompt check, n miniplan, g codegraph; 1-4 answer the first open question, 0 keeps its default.
At the prompt of a terminal session:
/plugin install agent-lens --marketplace ionutm87/agent-lens
Answer y to add the marketplace, then pick a scope (user is the first). From a shell:
claude plugin install agent-lens --marketplace ionutm87/agent-lens
In the desktop app: + next to the prompt box → Plugins → Add marketplace with ionutm87/agent-lens → Add plugin.
git clone git@github.com:ionutm87/agent-lens.git
claude --plugin-dir ./agent-lens # loads it for that session and hot-reloads on save
claude plugin validate ./agent-lens
claude plugin test ./agent-lenshooks/register.tsx 1708 lines1import { atom, read, update } from 'claude-code'
2import type { Engine, HookFor, Register, RenderChildren } from 'claude-code'
3
4import type { Answer, Change, Diff, GitNote, HookDraft, HookPaths, HookRow, Memory, MemoryAudit, MemoryMeta, MemoryUse, MemoryView, Plan, PlanStep, PromptCheck, Repo, Step, StepView, Style, StyleDraft, Tab, Totals, Worker } from '../types'
5import { branchLabel, cleanMessage, clip, outcomeOf, parseNumstat, parseStatus, syncSteps, withCounts } from './changes'
6import { PLAN_DESCRIPTION, PLAN_RULE, PLAN_SCHEMA, PLAN_TOOL, PLAN_TOOL_ID, answersMessage, delegationAsk, delegationText, layers, normalizePlan } from './plan'
7import { INDEX, memoriesView } from './memories-tab'
8import { stylesView } from './styles-tab'
9import { hooksView } from './hooks-tab'
10import { checkPrompt, parseCheck, worthChecking } from './check'
11import { hasHook, hookFromDraft, mainText, offFile, parseSettings, replaceHook, rowsOf, serialize, withHook, withoutHook } from './settings-hooks'
12import type { HookRef, Settings } from './settings-hooks'
13import { activeStyle, buildStyle, parseStyle, slugName, withOutputStyle } from './styles'
14import { namesIn, parseIndex, parseMemory, parseVerdicts, projectSlug, refsOf, toMermaid, withBody, withoutIndexLine, withoutLink } from './memories'
15import { card, section as kitSection } from './kit'
16import type { Ref } from './memories'
17import { costOf, tierOf } from './cost'
18import type { Tier } from './cost'
19
20const PANE = 'agent-lens'
21
22const steps = atom({ plugin: 'agent-lens', key: 'steps' } as const, [])
23const workers = atom({ plugin: 'agent-lens', key: 'workers' } as const, [])
24const skillsUsed = atom({ plugin: 'agent-lens', key: 'skillsUsed' } as const, {})
25const toolCounts = atom({ plugin: 'agent-lens', key: 'toolCounts' } as const, {})
26const prompt = atom({ plugin: 'agent-lens', key: 'prompt' } as const, '')
27const tab = atom({ plugin: 'agent-lens', key: 'tab' } as const, 'think' as Tab)
28// What is open/closed in Flow, by key; a missing key = the row's default state.
29const folds = atom({ plugin: 'agent-lens', key: 'fold' } as const, {} as Record<string, boolean>)
30const totals = atom({ plugin: 'agent-lens', key: 'totals' } as const, { steps: 0, tokensIn: 0, tokensOut: 0, cacheRead: 0 } as Totals)
31const hasGraph = atom({ plugin: 'agent-lens', key: 'hasGraph' } as const, false)
32const graphFirst = atom({ plugin: 'agent-lens', key: 'graphFirst' } as const, true)
33const graphSeen = atom({ plugin: 'agent-lens', key: 'graphSeen' } as const, false)
34const changes = atom({ plugin: 'agent-lens', key: 'changes' } as const, [] as Change[])
35const repo = atom({ plugin: 'agent-lens', key: 'repo' } as const, { top: '', branch: '', loaded: false } as Repo)
36const commitMsg = atom({ plugin: 'agent-lens', key: 'commitMsg' } as const, '')
37const gitNote = atom({ plugin: 'agent-lens', key: 'gitNote' } as const, null as GitNote | null)
38const diff = atom({ plugin: 'agent-lens', key: 'diff' } as const, null as Diff | null)
39const drafting = atom({ plugin: 'agent-lens', key: 'drafting' } as const, false)
40const syncing = atom({ plugin: 'agent-lens', key: 'syncing' } as const, false)
41const stepView = atom({ plugin: 'agent-lens', key: 'stepView' } as const, null as StepView | null)
42const memories = atom({ plugin: 'agent-lens', key: 'memories' } as const, [] as Memory[])
43const memMeta = atom({ plugin: 'agent-lens', key: 'memMeta' } as const, { dir: '', loaded: false, context: [], remember: [], recalls: [] } as MemoryMeta)
44const memUse = atom({ plugin: 'agent-lens', key: 'memUse' } as const, {} as Record<string, MemoryUse>)
45const memView = atom({ plugin: 'agent-lens', key: 'memView' } as const, null as MemoryView | null)
46const memAudit = atom({ plugin: 'agent-lens', key: 'memAudit' } as const, { at: 0, running: false, note: '', verdicts: {} } as MemoryAudit)
47const styles = atom({ plugin: 'agent-lens', key: 'styles' } as const, [] as Style[])
48const styleActive = atom({ plugin: 'agent-lens', key: 'styleActive' } as const, '')
49const styleDraft = atom({ plugin: 'agent-lens', key: 'styleDraft' } as const, null as StyleDraft | null)
50const styleFresh = atom({ plugin: 'agent-lens', key: 'styleFresh' } as const, '')
51const styleNote = atom({ plugin: 'agent-lens', key: 'styleNote' } as const, '')
52const styleLoaded = atom({ plugin: 'agent-lens', key: 'styleLoaded' } as const, false)
53const plan = atom({ plugin: 'agent-lens', key: 'plan' } as const, null as Plan | null)
54const answers = atom({ plugin: 'agent-lens', key: 'answers' } as const, {} as Record<string, Answer>)
55const busy = atom({ plugin: 'agent-lens', key: 'busy' } as const, false)
56const planFirst = atom({ plugin: 'agent-lens', key: 'planFirst' } as const, true)
57const planAsked = atom({ plugin: 'agent-lens', key: 'planAsked' } as const, false)
58const turnAt = atom({ plugin: 'agent-lens', key: 'turnAt' } as const, 0)
59const checkOn = atom({ plugin: 'agent-lens', key: 'checkOn' } as const, true)
60const promptCheck = atom({ plugin: 'agent-lens', key: 'promptCheck' } as const, null as PromptCheck | null)
61const hookRows = atom({ plugin: 'agent-lens', key: 'hookRows' } as const, [] as HookRow[])
62const hookDraft = atom({ plugin: 'agent-lens', key: 'hookDraft' } as const, null as HookDraft | null)
63const hookNote = atom({ plugin: 'agent-lens', key: 'hookNote' } as const, '')
64const hooksLoaded = atom({ plugin: 'agent-lens', key: 'hooksLoaded' } as const, false)
65const hookPaths = atom({ plugin: 'agent-lens', key: 'hookPaths' } as const, { global: '', project: '', local: '' } as HookPaths)
66
67const EDIT_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit'])
68
69// ANSI colors by name: Omarchy writes the terminal's 16-color palette
70// (ghostty/alacritty/kitty) on every theme change, so the sidebar follows it on its own.
71const C = {
72 accent: 'green',
73 model: 'cyan',
74 ok: 'green',
75 run: 'yellow',
76 bad: 'red',
77 info: 'blue',
78 graph: 'cyan',
79} as const
80
81// One color per model: opus magenta, sonnet blue, haiku green.
82const TIER_COLOR: Record<Tier, string | undefined> = { opus: 'magenta', sonnet: 'blue', haiku: 'green' }
83const modelColor = (model: string) => TIER_COLOR[tierOf(model) ?? 'opus']
84
85const short = (model: string) => model.replace(/^claude-/, '').replace(/-\d{8}$/, '')
86
87const k = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 10000 ? 0 : 1)}k` : String(n))
88
89// "2h13m" until the limit window resets
90const until = (ms: number) => {
91 const m = Math.max(0, Math.round(ms / 60000))
92
93 return m >= 60 ? `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m` : `${m}m`
94}
95
96const WINDOWS: Record<string, string> = { five_hour: '5h', seven_day: '7 days', spend_limit: 'budget' }
97
98// green, yellow 20 points before the threshold, red from the threshold
99const pctColor = (pct: number, bad: number) => (pct >= bad ? C.bad : pct >= bad - 20 ? C.run : C.ok)
100
101const secs = (ms: number) => (ms >= 60000 ? `${Math.floor(ms / 60000)}m${Math.round((ms % 60000) / 1000)}s` : `${Math.round(ms / 1000)}s`)
102
103// What a tool does, briefly: the main input field (command, file, search), otherwise JSON.
104export const brief = (input: unknown) => {
105 const o = (input ?? {}) as Record<string, unknown>
106 const main = ['command', 'file_path', 'pattern', 'query', 'description', 'prompt', 'url', 'skill'].map(key => o[key]).find(v => typeof v === 'string')
107
108 return String(main ?? JSON.stringify(input) ?? '').slice(0, 400)
109}
110
111// Each tool of the step gets the output of the first unconsumed transcript call with the same tool + input.
112export const pairUses = <U extends { tool: string; brief: string }, D extends U & { output?: string; isError?: boolean }>(uses: U[], done: D[]) => {
113 const taken = new Set<number>()
114
115 return uses.map(u => {
116 const i = done.findIndex((d, n) => !taken.has(n) && d.tool === u.tool && d.brief === u.brief)
117 if (i < 0) return { ...u }
118 taken.add(i)
119
120 return { ...u, output: done[i]?.output ? clip(done[i].output, 3000) : undefined, isError: done[i]?.isError }
121 })
122}
123
124const usd = (n: number) => `$${n.toFixed(n < 1 ? 3 : 2)}`
125
126const toolLabel = (tool: string) => tool.replace(/^mcp__(?:plugin_)?([^_]+(?:_[^_]+)*?)__/, '$1:')
127
128const git = ($: Engine, top: string, args: string[], timeoutMs = 20_000) =>
129 $.process.run(['git', '--no-optional-locks', '-C', top, ...args], { timeoutMs, env: { GIT_TERMINAL_PROMPT: '0' } })
130
131// Rendering doesn't run processes: the status is read here and lands in atoms.
132const refreshChanges = async ($: Engine) => {
133 let snap: { top: string; branch: string; list: Change[] } | null = null
134 try {
135 const found = await git($, await $.session.root(), ['rev-parse', '--show-toplevel'])
136 const top = found.stdout.trim()
137 const status = found.exitCode === 0 ? await git($, top, ['status', '--porcelain=v1', '-b', '-z', '--untracked-files=all']) : null
138 if (status?.exitCode === 0) {
139 const parsed = parseStatus(status.stdout)
140 const diff = await git($, top, ['diff', 'HEAD', '--numstat', '-z'])
141 snap = { top, branch: parsed.branch, list: withCounts(parsed.changes, diff.exitCode === 0 ? parseNumstat(diff.stdout) : {}) }
142 }
143 } catch {
144 snap = null
145 }
146 await update($, repo, () => ({ top: snap?.top ?? '', branch: snap?.branch ?? '', loaded: true }))
147 await update($, changes, () => snap?.list ?? [])
148}
149
150const stage = async ($: Engine, top: string, paths: string[] | 'all') =>
151 outcomeOf(await git($, top, paths === 'all' ? ['add', '-A'] : ['add', '--', ...paths]))
152
153// ponytail: `restore --staged` needs a HEAD; it fails before the repo's first commit
154const unstage = async ($: Engine, top: string, paths: string[] | 'all') =>
155 outcomeOf(await git($, top, ['restore', '--staged', '--', ...(paths === 'all' ? ['.'] : paths)]))
156
157// No --no-verify: the repo's hooks run, and their failure shows in the note.
158const commit = async ($: Engine, top: string, message: string) => outcomeOf(await git($, top, ['commit', '-m', message]))
159
160// Any git action of the tab: runs, keeps the result note, then re-reads the status.
161const gitAct = async ($: Engine, run: (top: string) => Promise<GitNote>) => {
162 const { top } = await read($, repo)
163 if (!top) return
164 const note = await run(top)
165 await update($, gitNote, () => note)
166 await refreshChanges($)
167}
168
169// Fetch, then only the missing steps (pull --ff-only / push) on the current branch. A timeout (network, SSH key
170// with a passphrase) throws: it ends up in the note as a failure and doesn't block the button.
171const syncRepo = async ($: Engine) => {
172 const { top } = await read($, repo)
173 if (!top || (await read($, syncing))) return
174 await update($, syncing, () => true)
175 let note: GitNote
176 try {
177 const fetched = outcomeOf(await git($, top, ['fetch', '--prune'], 120_000))
178 await refreshChanges($)
179 const branch = branchLabel((await read($, repo)).branch)
180 const steps = fetched.ok ? syncSteps(branch) : []
181 note = !fetched.ok ? fetched : branch.gone ? { ok: false, text: 'branch is gone from the remote (deleted after merge?)' } : { ok: true, text: 'up to date with the remote' }
182 for (const step of steps) {
183 const res = await git($, top, step, 120_000)
184 note = res.exitCode === 0 ? { ok: true, text: `${step[0]} ✓` } : outcomeOf(res)
185 if (!note.ok) break
186 }
187 if (steps.length > 1 && note.ok) note = { ok: true, text: 'pull + push ✓' }
188 } catch (err) {
189 note = { ok: false, text: `sync: ${err instanceof Error ? err.message : String(err)}` }
190 } finally {
191 await update($, syncing, () => false)
192 }
193 await update($, gitNote, () => note)
194 await refreshChanges($)
195}
196
197// An opened step: tool outputs don't exist at the end of the step (they arrive later), so they are looked up
198// in the transcript on open, by tool + input.
199const openStep = async ($: Engine, s: Step) => {
200 const messages = await $.session.messages(s.agentId ? { agentId: s.agentId } : {})
201 const done = messages.flatMap(m => m.toolUses).map(u => ({ tool: u.tool, brief: brief(u.input), output: u.text, isError: u.isError }))
202 await update($, stepView, () => ({ id: s.id, title: `${short(s.model)} #${s.index}`, answer: s.answer, uses: pairUses(s.uses ?? [], done) }))
203}
204
205// A file's diff against HEAD (index + working tree). A new, untracked file is compared with /dev/null;
206// `diff --no-index` exits with 1 when there are differences, so 0 and 1 both count as success.
207const openDiff = async ($: Engine, c: Change) => {
208 const { top } = await read($, repo)
209 if (!top) return
210 const res = await git($, top, c.code === '?' ? ['diff', '--no-index', '--', '/dev/null', c.path] : ['diff', 'HEAD', '--', c.path])
211 await update($, diff, () => ({ path: c.path, text: clip(res.exitCode <= 1 ? res.stdout : res.stderr, 90_000) }))
212}
213
214// The commit message from the staged files (not everything modified), written by Haiku in the style of
215// the repo's recent subjects. A single line: the commit field is single-line.
216const draftMessage = async ($: Engine) => {
217 const { top } = await read($, repo)
218 if (!top || (await read($, drafting))) return
219 if (!(await read($, changes)).some(c => c.staged)) {
220 return void (await update($, gitNote, () => ({ ok: false, text: 'Nothing staged: tick the files for the message.' })))
221 }
222 await update($, drafting, () => true)
223 try {
224 const [stat, patch, recent] = await Promise.all([
225 git($, top, ['diff', '--cached', '--stat']),
226 git($, top, ['diff', '--cached']),
227 git($, top, ['log', '-8', '--format=%s']),
228 ])
229 const res = await $.model.complete({
230 model: 'haiku',
231 effort: 'low',
232 maxTokens: 200,
233 timeoutMs: 30_000,
234 prompt: `Write a git commit message for the staged changes.
235Rules: one line, imperative, at most 72 characters, same language and style as the recent subjects; no quotes, no trailing period, no explanation.
236
237Recent subjects:
238${recent.stdout}
239Files:
240${stat.stdout}
241Diff:
242${clip(patch.stdout, 12_000)}`,
243 })
244 const text = res.isAnswered ? cleanMessage(res.text) : ''
245 if (text) {
246 await update($, commitMsg, () => text)
247 await update($, gitNote, () => null)
248 } else {
249 await update($, gitNote, () => ({ ok: false, text: `Haiku gave no message${res.isAnswered ? '' : ` (${res.reason})`}.` }))
250 }
251 } finally {
252 await update($, drafting, () => false)
253 }
254}
255
256// Answers from the Flow tab go to the model as soon as there is a way: in the running turn,
257// attached to the next tool result (without interrupting it), otherwise as a user prompt.
258const takeAnswers = async ($: Engine) => {
259 const pending = Object.entries(await read($, answers)).filter(([, a]) => a.state === 'pending')
260 if (!pending.length) return ''
261 await update($, answers, all => {
262 const next = { ...all }
263 for (const [ask] of pending) if (next[ask]?.state === 'pending') next[ask] = { ...next[ask], state: 'sent' }
264 return next
265 })
266
267 return answersMessage(pending.map(([ask, a]) => ({ ask, text: a.text })))
268}
269
270const submitAnswers = async ($: Engine) => {
271 const text = await takeAnswers($)
272 if (!text) return
273 await update($, busy, () => true)
274 void $.prompt.submit({ text, asUser: true })
275}
276
277const answer = async ($: Engine, ask: string, text: string) => {
278 if (!text.trim()) return
279 await update($, answers, all => ({ ...all, [ask]: { text: text.trim(), state: 'pending' as const } }))
280 if (!(await read($, busy))) await submitAnswers($)
281}
282
283const commitStaged = async ($: Engine) => {
284 const message = (await read($, commitMsg)).trim()
285 const list = await read($, changes)
286 if (!message) return void (await update($, gitNote, () => ({ ok: false, text: 'Write a commit message.' })))
287 if (!list.some(c => c.staged)) return void (await update($, gitNote, () => ({ ok: false, text: 'Nothing staged: tick files or [stage all].' })))
288 await gitAct($, async top => {
289 const res = await commit($, top, message)
290 if (res.ok) await update($, commitMsg, () => '')
291
292 return res
293 })
294}
295
296// The "Memories" tab: the current project's auto-memory as a graph, and how it reaches the model.
297// The directory comes from /context (the AutoMem file the engine actually loads); without it, the project slug.
298const memoryDir = async ($: Engine, context: MemoryMeta['context']) => {
299 const auto = context.find(f => f.type === 'AutoMem')
300 if (auto) return auto.path.slice(0, auto.path.lastIndexOf('/'))
301 const base = await $.process.run(['sh', '-c', 'printf %s "${CLAUDE_CONFIG_DIR:-$HOME/.claude}"'])
302
303 return `${base.stdout}/projects/${projectSlug(await $.session.root())}/memory`
304}
305
306// The "Style" tab: output styles are Markdown files in <config>/output-styles/; the active one is
307// "outputStyle" in <config>/settings.json. A change reaches the model at the next session start.
308const configDir = async ($: Engine) => (await $.process.run(['sh', '-c', 'printf %s "${CLAUDE_CONFIG_DIR:-$HOME/.claude}"'])).stdout
309
310const styleNotice = (ok: boolean, text: string) => (ok ? `✓ ${text}` : `✗ ${text}`)
311
312const loadStyles = async ($: Engine) => {
313 try {
314 const base = await configDir($)
315 const entries = (await $.fs.list(`${base}/output-styles`).catch(() => [])).filter(f => f.kind === 'file' && f.name.endsWith('.md'))
316 const list: Style[] = []
317 for (const f of entries) list.push(parseStyle(f.name, await $.fs.read(`${base}/output-styles/${f.name}`)))
318 const active = activeStyle(await $.fs.read(`${base}/settings.json`).catch(() => ''))
319 await update($, styles, () => list.sort((a, b) => a.name.localeCompare(b.name)))
320 await update($, styleActive, () => active)
321 } catch (err) {
322 await update($, styleNote, () => styleNotice(false, `could not read the styles: ${(err as Error).message}`))
323 }
324 await update($, styleLoaded, () => true)
325}
326
327const openStyle = async ($: Engine, file: string) => {
328 const s = (await read($, styles)).find(x => x.file === file)
329 if (!s) return
330 await update($, styleNote, () => '')
331 await update($, styleDraft, () => ({ file, description: s.description, lines: s.body.split('\n'), dirty: false }))
332}
333
334const editStyle = ($: Engine, fn: (d: StyleDraft) => StyleDraft) => void update($, styleDraft, d => (d ? { ...fn(d), dirty: true } : d))
335
336const saveStyle = async ($: Engine) => {
337 const d = await read($, styleDraft)
338 const s = d && (await read($, styles)).find(x => x.file === d.file)
339 if (!d || !s) return
340 try {
341 await $.fs.write(`${await configDir($)}/output-styles/${s.file}`, buildStyle({ ...s, description: d.description, body: d.lines.join('\n') }))
342 await loadStyles($)
343 await update($, styleDraft, cur => (cur ? { ...cur, dirty: false } : cur))
344 await update($, styleNote, () => styleNotice(true, 'saved'))
345 } catch (err) {
346 await update($, styleNote, () => styleNotice(false, `not saved: ${(err as Error).message}`))
347 }
348}
349
350const useStyle = async ($: Engine, file: string) => {
351 const s = (await read($, styles)).find(x => x.file === file)
352 if (!s) return
353 try {
354 const path = `${await configDir($)}/settings.json`
355 // Only a missing settings.json starts empty; a file that exists but cannot be read must not be overwritten.
356 await $.fs.write(path, withOutputStyle((await $.fs.exists(path)) ? await $.fs.read(path) : '', s.name))
357 await update($, styleActive, () => s.name)
358 await update($, styleNote, () => styleNotice(true, `${s.name} is the output style from the next session`))
359 } catch (err) {
360 await update($, styleNote, () => styleNotice(false, `settings.json not changed: ${(err as Error).message}`))
361 }
362}
363
364// A new style starts as a copy of the active one (or the first), so it is never an empty page.
365const createStyle = async ($: Engine, name: string) => {
366 const slug = slugName(name)
367 const list = await read($, styles)
368 if (!slug) return void (await update($, styleNote, () => styleNotice(false, 'give the style a name (letters or digits)')))
369 if (list.some(s => s.file === `${slug}.md`)) return void (await update($, styleNote, () => styleNotice(false, `${slug}.md already exists`)))
370 const active = await read($, styleActive)
371 const from = list.find(s => s.name === active) ?? list[0]
372 try {
373 await $.fs.write(`${await configDir($)}/output-styles/${slug}.md`, buildStyle({ file: `${slug}.md`, name: slug, description: from?.description ?? '', keep: from?.keep ?? true, body: from?.body ?? '' }))
374 await update($, styleFresh, () => '')
375 await loadStyles($)
376 await openStyle($, `${slug}.md`)
377 } catch (err) {
378 await update($, styleNote, () => styleNotice(false, `not created: ${(err as Error).message}`))
379 }
380}
381
382// The "analyze" button. First the code: every path or symbol a memory names in backticks is looked up in the repo
383// (tracked contents and file names), and what is gone becomes hard evidence. Then Sonnet reads each memory with that
384// evidence, the project's CLAUDE.md and recent commits, and says whether it still helps here, with the body rewritten
385// for a stale one. It only marks; "fix" and "delete" are clicks. Kept per project in $.store.
386const auditKey = async ($: Engine) => `memaudit:${await $.session.root()}`
387
388// ponytail: git grep on tracked files + file names; untracked work is invisible, a false "gone" reads as a hint, not a verdict
389const isInRepo = async ($: Engine, root: string, r: Ref) => {
390 if (r.kind === 'path') return $.fs.exists(`${root}/${r.needle}`)
391 const res = await $.process.run(['sh', '-c', 'git -C "$1" grep -q -I -F -- "$2" || [ -n "$(git -C "$1" ls-files -- "*$2*")" ]', 'sh', root, r.needle], { timeoutMs: 10_000 }).catch(() => null)
392
393 return res?.exitCode === 0
394}
395
396const checkRefs = async ($: Engine, root: string, list: Memory[], dir: string) => {
397 const texts: Record<string, string> = {}
398 const gone: Record<string, string[]> = {}
399 const seen = new Map<string, boolean>()
400 const isGit = (await git($, root, ['rev-parse', '--show-toplevel']).catch(() => ({ exitCode: 1 }))).exitCode === 0
401 for (const m of list) {
402 texts[m.name] = await $.fs.read(`${dir}/${m.file}`).catch(() => '')
403 if (!isGit) continue
404 for (const r of refsOf(parseMemory(m.file, texts[m.name] ?? '').body)) {
405 if (!seen.has(r.ref)) seen.set(r.ref, await isInRepo($, root, r))
406 if (!seen.get(r.ref)) (gone[m.name] ??= []).push(r.ref)
407 }
408 }
409
410 return { texts, gone, checked: seen.size, isGit }
411}
412
413const analyzeMemories = async ($: Engine) => {
414 const list = await read($, memories)
415 const { dir } = await read($, memMeta)
416 if (!list.length || (await read($, memAudit)).running) return
417 await update($, memAudit, a => ({ ...a, running: true, note: '' }))
418 try {
419 const root = await $.session.root()
420 const now = await $.clock.now()
421 const day = (ms: number) => new Date(ms).toISOString().slice(0, 10)
422 const { texts, gone, checked, isGit } = await checkRefs($, root, list, dir)
423 const notes = list.map(m => {
424 const evidence = gone[m.name]?.length ? `CODE CHECK: not in the repo any more: ${gone[m.name]!.map(r => `\`${r}\``).join(', ')}` : isGit ? 'CODE CHECK: every path and symbol it names still exists' : ''
425 return `### ${m.name} (type ${m.type}, changed ${day(m.mtimeMs)})\n${evidence}\n${clip(parseMemory(m.file, texts[m.name] ?? '').body, 2500)}`
426 })
427 const guide = await $.fs.read(`${root}/CLAUDE.md`).catch(() => '')
428 const log = await git($, root, ['log', '-25', '--format=%as %s']).catch(() => ({ stdout: '' }))
429 const res = await $.model.complete({
430 model: 'sonnet',
431 maxTokens: 12_000,
432 timeoutMs: 240_000,
433 prompt: `You audit the persistent memory an AI coding agent keeps for one project. Each memory comes with a CODE CHECK: the paths and symbols it names that the repository no longer has (hard evidence: something was removed or renamed). For EACH memory decide:
434- relevant: still true and useful when working on this project
435- stale: about this project, but partly done, outdated, contradicted by the guide, the commits or the code check, or its dates have passed
436- irrelevant: not about this project, of no use to the agent here, or entirely about things that no longer exist
437Today is ${day(now)}. Project root: ${root}.
438For a stale memory also write "fix": its body rewritten in Markdown, same language, with what no longer holds removed or corrected and what still holds kept (the **Why:** / **How to apply:** lines, the [[links]]); shorter is better. Leave "fix" empty for relevant and irrelevant.
439Answer ONLY a JSON array, one entry per memory: [{"name": "<exact name>", "verdict": "relevant" | "stale" | "irrelevant", "why": "<at most 14 words, same language as the memories>", "fix": "<rewritten body or empty>"}]
440
441Project guide (CLAUDE.md, start):
442${clip(guide, 5000) || '(none)'}
443
444Recent commits:
445${log.stdout || '(none)'}
446
447Memories:
448${notes.join('\n\n')}`,
449 })
450 const verdicts = res.isAnswered ? parseVerdicts(res.text, list.map(m => m.name)) : {}
451 for (const [name, v] of Object.entries(verdicts)) if (gone[name]?.length) v.gone = gone[name]
452 const n = Object.keys(verdicts).length
453 if (!n) return void (await update($, memAudit, a => ({ ...a, running: false, note: `✗ Sonnet gave no usable verdict${res.isAnswered ? '' : ` (${res.reason})`}` })))
454 const note = [n < list.length ? `${list.length - n} memories got no verdict` : '', isGit ? `${checked} code references checked` : 'not a git repository: no code check'].filter(Boolean).join(' · ')
455 await update($, memAudit, () => ({ at: now, running: false, note, verdicts }))
456 await $.store.set(await auditKey($), { at: now, verdicts })
457 } catch (err) {
458 await update($, memAudit, a => ({ ...a, running: false, note: `✗ analysis failed: ${(err as Error).message}` }))
459 }
460}
461
462const dropVerdict = async ($: Engine, names: string[]) => {
463 await update($, memAudit, a => {
464 const verdicts = { ...a.verdicts }
465 for (const n of names) delete verdicts[n]
466 return { ...a, verdicts }
467 })
468 const a = await read($, memAudit)
469 await $.store.set(await auditKey($), { at: a.at, verdicts: a.verdicts })
470}
471
472// "delete": the file goes, and its line in MEMORY.md with it. Links from other memories stay and show as missing.
473const deleteMemories = async ($: Engine, names: string[]) => {
474 const { dir } = await read($, memMeta)
475 const list = (await read($, memories)).filter(m => names.includes(m.name))
476 if (!dir || !list.length) return
477 try {
478 const res = await $.process.run(['rm', '-f', '--', ...list.map(m => `${dir}/${m.file}`)])
479 if (res.exitCode !== 0) throw new Error(res.stderr.trim() || `rm exited ${res.exitCode}`)
480 const index = `${dir}/${INDEX}`
481 if (await $.fs.exists(index)) await $.fs.write(index, list.reduce((t, m) => withoutIndexLine(t, m.file), await $.fs.read(index)))
482 await dropVerdict($, names)
483 await update($, memView, v => (v && names.includes(v.name) ? null : v))
484 $.ui.toast(`Deleted ${list.length === 1 ? list[0]!.name : `${list.length} memories`}`)
485 } catch (err) {
486 await update($, memAudit, a => ({ ...a, note: `✗ not deleted: ${(err as Error).message}` }))
487 }
488 await loadMemories($)
489}
490
491// "fix": Sonnet's rewrite replaces the body; the frontmatter stays. The memory then counts as relevant.
492const fixMemory = async ($: Engine, name: string) => {
493 const { dir } = await read($, memMeta)
494 const m = (await read($, memories)).find(x => x.name === name)
495 const fix = (await read($, memAudit)).verdicts[name]?.fix
496 if (!dir || !m || !fix) return
497 try {
498 await $.fs.write(`${dir}/${m.file}`, withBody(await $.fs.read(`${dir}/${m.file}`), fix))
499 await update($, memAudit, a => ({ ...a, verdicts: { ...a.verdicts, [name]: { verdict: 'relevant', why: 'rewritten by the fix' } } }))
500 const a = await read($, memAudit)
501 await $.store.set(await auditKey($), { at: a.at, verdicts: a.verdicts })
502 await update($, memView, v => (v?.name === name ? { name, body: clip(fix, 6000) } : v))
503 $.ui.toast(`${name} rewritten`)
504 } catch (err) {
505 await update($, memAudit, a => ({ ...a, note: `✗ not rewritten: ${(err as Error).message}` }))
506 }
507 await loadMemories($)
508}
509
510// "unlink": every memory citing a memory that does not exist keeps the word, without the [[ ]].
511const unlinkMemory = async ($: Engine, target: string) => {
512 const { dir } = await read($, memMeta)
513 const list = (await read($, memories)).filter(m => m.links.includes(target))
514 if (!dir || !list.length) return
515 try {
516 for (const m of list) await $.fs.write(`${dir}/${m.file}`, withoutLink(await $.fs.read(`${dir}/${m.file}`), target))
517 $.ui.toast(`[[${target}]] unlinked in ${list.length === 1 ? list[0]!.name : `${list.length} memories`}`)
518 } catch (err) {
519 await update($, memAudit, a => ({ ...a, note: `✗ not unlinked: ${(err as Error).message}` }))
520 }
521 await loadMemories($)
522}
523
524const copyMermaid = async ($: Engine, surface: any) => {
525 const r = await $.ui.copy({ text: toMermaid(await read($, memories), (await read($, memAudit)).verdicts), surface })
526 $.ui.toast(r.isCopied ? 'Mermaid copied: paste it into mermaid.live or a ```mermaid block' : `Not copied: ${r.reason}`)
527}
528
529const loadMemories = async ($: Engine) => {
530 try {
531 const usage = await $.session.usage({ breakdown: 'summary', columns: 60 })
532 const context = (usage.context.breakdown?.memoryFiles ?? []).map(f => ({ path: f.path, type: f.type, tokens: f.tokens }))
533 const dir = await memoryDir($, context)
534 const entries = (await $.fs.list(dir).catch(() => [])).filter(f => f.kind === 'file' && f.name.endsWith('.md'))
535 const index = entries.some(f => f.name === INDEX) ? parseIndex(await $.fs.read(`${dir}/${INDEX}`)) : {}
536 const list: Memory[] = []
537 for (const f of entries.filter(f => f.name !== INDEX)) {
538 const m = parseMemory(f.name, await $.fs.read(`${dir}/${f.name}`))
539 list.push({ name: m.name, file: f.name, type: m.type, description: m.description, links: m.links, indexed: f.name in index, hook: index[f.name]?.hook ?? '', size: f.size, mtimeMs: f.mtimeMs })
540 }
541 // The remember plugin keeps its log in the project (.remember/); the days are folded into a single row.
542 const root = await $.session.root()
543 const rem = (await $.fs.list(`${root}/.remember`).catch(() => [])).filter(f => f.kind === 'file' && f.name.endsWith('.md'))
544 const days = rem.filter(f => f.name.startsWith('today-'))
545 const remember = [
546 ...rem.filter(f => !f.name.startsWith('today-')).map(f => ({ name: f.name, size: f.size })),
547 ...(days.length ? [{ name: `today-*.md ×${days.length}`, size: days.reduce((n, f) => n + f.size, 0) }] : []),
548 ]
549 await update($, memories, () => list)
550 await update($, memMeta, meta => ({ ...meta, dir, loaded: true, context, remember }))
551 const saved = (await $.store.get(await auditKey($))) as Pick<MemoryAudit, 'at' | 'verdicts'> | undefined
552 if (saved?.verdicts) await update($, memAudit, a => (a.at ? a : { ...a, at: saved.at, verdicts: saved.verdicts }))
553 } catch {
554 await update($, memMeta, meta => ({ ...meta, loaded: true }))
555 }
556}
557
558const bump = ($: Engine, names: string[], key: keyof MemoryUse) =>
559 update($, memUse, use => {
560 const next = { ...use }
561 for (const n of names) next[n] = { ...(next[n] ?? { read: 0, write: 0, recalled: 0 }), [key]: (next[n]?.[key] ?? 0) + 1 }
562
563 return next
564 })
565
566const openMemory = async ($: Engine, name: string) => {
567 const { dir } = await read($, memMeta)
568 const m = (await read($, memories)).find(x => x.name === name)
569 if (!m) return
570 const text = await $.fs.read(`${dir}/${m.file}`).catch(() => '')
571 await update($, memView, () => ({ name, body: clip(parseMemory(m.file, text).body, 6000) }))
572}
573
574// Per tool, with a matcher: the mod already has a matcher-less `tool.call`, and a second one is rejected.
575const trackMemory: HookFor<'tool.call'> = async ($, e, next) => {
576 const { dir } = await read($, memMeta)
577 if (!dir) return next(e)
578 const input = e as { file_path?: string; command?: string }
579 const list = await read($, memories)
580 const path = input.file_path ?? ''
581 const isWrite = /^(Write|Edit)$/.test(String(e.tool))
582 if (path.startsWith(`${dir}/`)) {
583 const file = path.slice(dir.length + 1)
584 const name = file === INDEX ? INDEX : (list.find(m => m.file === file)?.name ?? file.replace(/\.md$/, ''))
585 await bump($, [name], isWrite ? 'write' : 'read')
586 } else if (String(e.tool) === 'Bash' && input.command?.includes(dir)) {
587 await bump($, namesIn(input.command, list), 'read')
588 }
589 const res = await next(e)
590 if (isWrite && path.startsWith(`${dir}/`)) void loadMemories($)
591
592 return res
593}
594
595// The switches the person flips are kept across sessions.
596const flipCheck = async ($: Engine) => {
597 const isOn = !(await read($, checkOn))
598 await update($, checkOn, () => isOn)
599 await $.store.set('check', isOn)
600}
601
602// At submit, Haiku reads the prompt alone and suggests in Flow what to clarify; the model's turn does not wait.
603// A result for an older prompt is dropped.
604const runCheck = async ($: Engine, text: string, previous: string, at: number) => {
605 await update($, promptCheck, () => ({ at, running: true, clarity: 0, missing: [], questions: [], better: '', note: '' }))
606 let found: PromptCheck | null = null
607 let why = ''
608 try {
609 const res = await $.model.complete({ model: 'haiku', effort: 'low', maxTokens: 800, timeoutMs: 30_000, prompt: checkPrompt(text, previous) })
610 found = res.isAnswered ? parseCheck(res.text, at) : null
611 why = res.isAnswered ? '' : ` (${res.reason})`
612 } catch (err) {
613 why = ` (${(err as Error).message})`
614 }
615 await update($, promptCheck, cur => (cur?.at !== at ? cur : (found ?? { ...cur, running: false, note: `✗ haiku gave no check${why}` })))
616}
617
618const copyText = async ($: Engine, text: string, surface: any) => {
619 const r = await $.ui.copy({ text, surface })
620 $.ui.toast(r.isCopied ? 'Prompt copied' : `Not copied: ${r.reason}`)
621}
622
623// The "Hooks" tab: Claude Code's own hooks in the settings files. Global (<config>/settings.json) only turns on/off;
624// the project's (.claude/settings.json shared, .claude/settings.local.json just you) take any change.
625const readSettings = async ($: Engine, file: string) => parseSettings((await $.fs.exists(file)) ? await $.fs.read(file) : '')
626
627const loadHooks = async ($: Engine) => {
628 const rows: HookRow[] = []
629 const bad: string[] = []
630 try {
631 const root = await $.session.root()
632 const global = `${await configDir($)}/settings.json`
633 const project = `${root}/.claude/settings.json`
634 // A session started in the config dir's parent has no project of its own.
635 const paths: HookPaths = project === global ? { global, project: '', local: '' } : { global, project, local: `${root}/.claude/settings.local.json` }
636 await update($, hookPaths, () => paths)
637 for (const scope of ['global', 'project', 'local'] as const) {
638 if (!paths[scope]) continue
639 for (const isOff of [false, true]) {
640 const path = isOff ? offFile(paths[scope]) : paths[scope]
641 try {
642 rows.push(...rowsOf(await readSettings($, path), scope, paths[scope], isOff))
643 } catch (err) {
644 bad.push(`${path}: ${(err as Error).message}`)
645 }
646 }
647 }
648 } catch (err) {
649 bad.push((err as Error).message)
650 }
651 await update($, hookRows, () => rows)
652 if (bad.length) await update($, hookNote, () => `✗ not read, left alone: ${bad.join('; ')}`)
653 await update($, hooksLoaded, () => true)
654}
655
656const GONE = 'the file changed since the tab read it: reloaded, try again'
657
658const refOf = (r: HookRow): HookRef => ({ event: r.event, matcher: r.matcher, hook: r.hook })
659
660// Every change re-reads the hook's file and its *.hooks-off.json, so an edit made elsewhere meanwhile is never
661// overwritten (a hook no longer there is refused), and writes only the files that changed.
662const changeHooks = async ($: Engine, file: string, change: (on: Settings, off: Settings) => [Settings, Settings] | string, done: string) => {
663 try {
664 const on = await readSettings($, file)
665 const off = await readSettings($, offFile(file))
666 const out = change(on, off)
667 if (typeof out === 'string') {
668 await update($, hookNote, () => `✗ ${out}`)
669 } else {
670 if (serialize(out[0]) !== serialize(on)) await $.fs.write(file, serialize(out[0]))
671 if (serialize(out[1]) !== serialize(off)) await $.fs.write(offFile(file), serialize(out[1]))
672 await update($, hookDraft, () => null)
673 await update($, hookNote, () => `✓ ${done} · Claude Code reads it from the next session`)
674 }
675 } catch (err) {
676 await update($, hookNote, () => `✗ ${file} not changed: ${(err as Error).message}`)
677 }
678 await loadHooks($)
679}
680
681const toggleHook = ($: Engine, r: HookRow) =>
682 changeHooks(
683 $,
684 r.file,
685 (on, off) => {
686 const ref = refOf(r)
687 if (!hasHook(r.isOff ? off : on, ref)) return GONE
688
689 return r.isOff ? [withHook(on, ref), withoutHook(off, ref)] : [withoutHook(on, ref), withHook(off, ref)]
690 },
691 `${r.event} ${r.isOff ? 'on' : 'off'}`,
692 )
693
694// Global hooks are only turned on/off here, never deleted.
695const removeHook = async ($: Engine, r: HookRow) => {
696 if (r.scope === 'global') return
697 await changeHooks(
698 $,
699 r.file,
700 (on, off) => {
701 const ref = refOf(r)
702 if (!hasHook(r.isOff ? off : on, ref)) return GONE
703
704 return r.isOff ? [on, withoutHook(off, ref)] : [withoutHook(on, ref), off]
705 },
706 `${r.event} deleted`,
707 )
708}
709
710const saveHook = async ($: Engine) => {
711 const d = await read($, hookDraft)
712 if (!d || d.row?.scope === 'global') return
713 const timeout = d.timeout.trim()
714 if (!d.text.trim()) return void (await update($, hookNote, () => '✗ write what the hook runs'))
715 if (timeout && !/^[1-9]\d*$/.test(timeout)) return void (await update($, hookNote, () => '✗ timeout: whole seconds'))
716 const next: HookRef = { event: d.event, matcher: d.matcher.trim(), hook: hookFromDraft(d.row?.hook, d.text, timeout) }
717 const row = d.row
718 if (!row) {
719 const file = (await read($, hookPaths))[d.scope]
720 if (!file) return void (await update($, hookNote, () => '✗ this session has no project folder'))
721
722 return changeHooks($, file, (on, off) => [withHook(on, next), off], `${next.event} added`)
723 }
724 const old = refOf(row)
725
726 return changeHooks(
727 $,
728 row.file,
729 (on, off) => {
730 if (!hasHook(row.isOff ? off : on, old)) return GONE
731
732 return row.isOff ? [on, replaceHook(off, old, next)] : [replaceHook(on, old, next), off]
733 },
734 `${next.event} saved`,
735 )
736}
737
738const openHook = async ($: Engine, r: HookRow | null) => {
739 await update($, hookNote, () => '')
740 await update($, hookDraft, () =>
741 r
742 ? { row: r, scope: r.scope === 'project' ? ('project' as const) : ('local' as const), event: r.event, matcher: r.matcher, text: mainText(r.hook), timeout: r.hook.timeout === undefined ? '' : String(r.hook.timeout) }
743 : { row: null, scope: 'local' as const, event: 'PreToolUse', matcher: '', text: '', timeout: '' },
744 )
745}
746
747export const register: Register = on => {
748 // Memory usage: reads and writes through tools (including subagents'), recalls through attachments.
749 on('tool.call', { tool: 'Read' }, trackMemory)
750 on('tool.call', { tool: 'Write' }, trackMemory)
751 on('tool.call', { tool: 'Edit' }, trackMemory)
752 on('tool.call', { tool: 'Bash' }, trackMemory)
753
754 on('prompt.attachment', async ($, e, next) => {
755 const res = await next(e)
756 const text = (e as { text?: string }).text ?? ''
757 if (/memor/i.test(e.type) && text) {
758 const names = namesIn(text, await read($, memories))
759 await update($, memMeta, meta => ({ ...meta, recalls: [...meta.recalls, { type: e.type, names }].slice(-20) }))
760 if (names.length) await bump($, names, 'recalled')
761 }
762
763 return res
764 })
765
766 on('session.start', async ($, e, next) => {
767 await $.command.register({ name: 'lens', description: 'Open the Agent Lens sidebar' })
768 await $.tool.register({ name: PLAN_TOOL, description: PLAN_DESCRIPTION, inputSchema: PLAN_SCHEMA, isDeferred: false })
769 void refreshChanges($)
770 void loadMemories($)
771 void loadStyles($)
772 // The prompt check stays on until the person turns it off.
773 const check = await $.store.get('check')
774 await update($, checkOn, () => check !== false)
775 await update($, hasGraph, () => false)
776 if (await $.fs.exists('.codegraph')) await update($, hasGraph, () => true)
777 void $.ui.open({ id: PANE, title: 'Agent Lens' })
778
779 return next(e)
780 })
781
782 on('command.run', { command: 'lens' }, async $ => {
783 await $.ui.open({ id: PANE, title: 'Agent Lens', focus: true })
784
785 return { text: 'Agent Lens opened.' }
786 })
787
788 // A prompt sent by a human counts as "requested": the panel settles at any width,
789 // and if it was closed by hand, it comes back. On an already open id it's a no-op.
790 on('prompt.submit', async ($, e, next) => {
791 void $.ui.open({ id: PANE, title: 'Agent Lens' })
792 const now = await $.clock.now()
793 const isHuman = !e.origin || e.origin.kind === 'composer' || e.origin.kind === 'bridge'
794 if (isHuman) {
795 await update($, graphSeen, () => false)
796 await update($, planAsked, () => false)
797 await update($, turnAt, () => now)
798 await update($, plan, () => null)
799 await update($, answers, () => ({}))
800 await update($, folds, () => ({}))
801 await update($, promptCheck, () => null)
802 }
803 const previous = await read($, prompt)
804 await update($, busy, () => true)
805 await update($, prompt, () => e.text)
806 if (isHuman && (await read($, checkOn)) && worthChecking(e.text)) void runCheck($, e.text, previous, now)
807
808 return next(e)
809 })
810
811 // The mod's rules go into the system prompt: the miniplan first, CodeGraph before Grep/Read when the
812 // project has an index, the reply language. No model routing: the session model does the work.
813 on('prompt.compose', async ($, e, next) => {
814 const res = await next(e)
815 const extra = []
816 if (await read($, planFirst)) extra.push({ id: 'agent-lens:plan', scope: 'session' as const, text: PLAN_RULE })
817 if ((await read($, hasGraph)) && (await read($, graphFirst))) {
818 extra.push({
819 id: 'agent-lens:codegraph',
820 scope: 'session' as const,
821 text: 'The project has a CodeGraph index (.codegraph/). For any question about code and before any change, call codegraph_explore first (verbatim source, callers, blast radius); use Grep, Glob and Read only for what it does not cover. Tell subagents to use it too.',
822 })
823 }
824 extra.push({
825 id: 'agent-lens:language',
826 scope: 'session' as const,
827 text: "Reply to the user in the language of their latest prompt (Romanian prompt → Romanian reply, English prompt → English reply), including the fields you pass to the plan tool. Keep code, identifiers and commands as they are.",
828 })
829
830 return extra.length ? { sections: [...res.sections, ...extra] } : res
831 })
832
833 on('skill.prompt', async ($, e, next) => {
834 await update($, skillsUsed, used => ({ ...used, [e.skill]: (used[e.skill] ?? 0) + 1 }))
835
836 return next(e)
837 })
838
839 // The model's plan lands in the Flow tab; a republish keeps its place and bumps the revision.
840 // The literal (not the constant) so the validator sees the matcher; `as never` until the MCP types generated on load include the tool.
841 on('tool.call', { tool: 'mcp__agent-lens__plan' as never }, async ($, e) => {
842 const fresh = normalizePlan(e, await $.clock.now())
843 await update($, plan, old => ({ ...fresh, revision: old ? old.revision + 1 : 0 }))
844
845 return { result: `Plan shown in Agent Lens · Flow (${fresh.steps.length} steps).` }
846 })
847
848 on('tool.call', async ($, e, next) => {
849 const name = toolLabel(String(e.tool))
850 await update($, toolCounts, counts => ({ ...counts, [name]: (counts[name] ?? 0) + 1 }))
851 if (name.startsWith('codegraph:')) await update($, graphSeen, () => true)
852 // The miniplan comes before any tool: the first tool of a turn without a published plan is denied once.
853 if (!e.agentId && String(e.tool) !== PLAN_TOOL_ID && (await read($, planFirst)) && !(await read($, plan)) && !(await read($, planAsked))) {
854 await update($, planAsked, () => true)
855
856 return { deny: `Publish the miniplan with ${PLAN_TOOL_ID} first: what you understood (goal) and how you will act (approach), with the steps. Then repeat the tool.` }
857 }
858 // The turn's first classic search, without CodeGraph before it, is denied once; the second goes through.
859 if (!e.agentId && /^(Grep|Glob)$/.test(String(e.tool)) && (await read($, hasGraph)) && (await read($, graphFirst)) && !(await read($, graphSeen))) {
860 await update($, graphSeen, () => true)
861
862 return { deny: 'The project has a CodeGraph index: start with codegraph_explore (verbatim source and callers in a single call). If it does not cover what you are looking for, repeat Grep/Glob.' }
863 }
864 if (e.agentId) {
865 await update($, workers, list =>
866 list.map(w => (w.agentId === e.agentId ? { ...w, tools: w.tools + 1 } : w)),
867 )
868 }
869
870 const res = await next(e)
871 if (e.agentId || res.deny !== undefined || res.isError) return res
872 const text = await takeAnswers($)
873
874 return text ? { ...res, context: [...(res.context ?? []), text] } : res
875 })
876
877 // Every step of the main loop and of the subagents, with its model, tools, tokens and cost.
878 on('turn.step', async function* ($, e, next) {
879 const id = `${e.turnId}:${e.agentId ?? 'main'}:${e.index}`
880 const step: Step = {
881 id,
882 turnId: e.turnId,
883 index: e.index,
884 model: e.model,
885 effort: e.effort === undefined ? undefined : String(e.effort),
886 agentId: e.agentId,
887 isDone: false,
888 tools: [],
889 tokensIn: 0,
890 tokensOut: 0,
891 cacheRead: 0,
892 stop: null,
893 answer: '',
894 uses: [],
895 }
896 await update($, steps, list => [...list, step].slice(-60))
897
898 const res = yield* next(e)
899
900 const usage = res.usage
901 const cost = usage ? costOf(tierOf(usage.model ?? e.model) ?? 'opus', usage) : 0
902 await update($, steps, list =>
903 list.map(s =>
904 s.id === id
905 ? {
906 ...s,
907 isDone: true,
908 model: usage?.model ?? s.model,
909 tools: res.toolUses.map(u => toolLabel(u.name)),
910 tokensIn: usage ? usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens : 0,
911 tokensOut: usage?.output_tokens ?? 0,
912 cacheRead: usage?.cache_read_input_tokens ?? 0,
913 cost,
914 stop: res.stopReason,
915 answer: clip(res.answer, 4000),
916 uses: res.toolUses.map(u => ({ tool: u.name, brief: brief(u.input) })),
917 }
918 : s,
919 ),
920 )
921
922 if (usage) {
923 await update($, totals, t => ({
924 steps: t.steps + 1,
925 tokensIn: t.tokensIn + usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens,
926 tokensOut: t.tokensOut + usage.output_tokens,
927 cacheRead: t.cacheRead + usage.cache_read_input_tokens,
928 cost: (t.cost ?? 0) + cost,
929 }))
930 }
931
932 return res
933 })
934
935 // A subagent runs on the model the main model asked for, or inherits its parent's; the mod only watches.
936 on('agent.spawn', async ($, e, next) => {
937 const id = e.tool_use_id || `${e.subagentType}:${await $.clock.now()}`
938 const worker: Worker = {
939 id,
940 type: e.subagentType,
941 description: e.description,
942 model: e.model ?? e.parentModel,
943 parentModel: e.parentModel,
944 isBackground: Boolean(e.background),
945 status: 'running',
946 startedAt: await $.clock.now(),
947 tools: 0,
948 prompt: clip(e.prompt, 1500),
949 }
950 await update($, workers, list => [...list, worker].slice(-30))
951
952 const res = await next(e)
953
954 await update($, workers, list =>
955 list.map(w =>
956 w.id === id
957 ? res.deny !== undefined
958 ? { ...w, status: 'denied' as const }
959 : { ...w, agentId: res.agentId, model: res.model }
960 : w,
961 ),
962 )
963
964 return res
965 })
966
967 on('turn.complete', async ($, e, next) => {
968 if (!e.agentId) {
969 void refreshChanges($)
970 await update($, busy, () => false)
971 await submitAnswers($)
972 }
973
974 if (e.agentId) {
975 await update($, workers, list =>
976 list.map(w =>
977 w.agentId === e.agentId
978 ? {
979 ...w,
980 answer: e.answer ? clip(e.answer, 1500) : undefined,
981 status: e.isAborted ? ('aborted' as const) : ('done' as const),
982 durationMs: e.durationMs,
983 tokensOut: e.usage?.output_tokens,
984 }
985 : w,
986 ),
987 )
988 }
989
990 return next(e)
991 })
992
993 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
994 const { Box, Text, Button, Input, Code } = $.ui.resolve(e)
995 const list = await read($, changes)
996 const repoNow = await read($, repo)
997 const message = await read($, commitMsg)
998 const note = await read($, gitNote)
999 const diffNow = await read($, diff)
1000 // Steps from before a reload have no `answer`/`uses`: their absence must not block the panel.
1001 const opened = await read($, stepView)
1002 const stepNow = opened && { ...opened, answer: opened.answer ?? '', uses: opened.uses ?? [] }
1003 const isDrafting = await read($, drafting)
1004 const planNow = await read($, plan)
1005 const answered = await read($, answers)
1006 const isSyncing = await read($, syncing)
1007 const graphReady = await read($, hasGraph)
1008 const isGraphFirst = await read($, graphFirst)
1009 const allSteps = await read($, steps)
1010 const allWorkers = await read($, workers)
1011 const used = await read($, skillsUsed)
1012 const counts = await read($, toolCounts)
1013 const lastPrompt = await read($, prompt)
1014 // A tab saved by an older version (Steps, Skills) falls back to Flow.
1015 const stored = String(await read($, tab))
1016 const current: Tab = ['think', 'changes', 'memories', 'styles', 'hooks'].includes(stored) ? (stored as Tab) : 'think'
1017 const foldNow = await read($, folds)
1018 const sessionModel = await $.session.model()
1019 const sum = await read($, totals)
1020 const isBusy = await read($, busy)
1021 const isPlanFirst = await read($, planFirst)
1022 const isChecking = await read($, checkOn)
1023 const checkNow = await read($, promptCheck)
1024 const since = await read($, turnAt)
1025 const { context, rateLimits } = await $.session.usage()
1026 const now = await $.clock.now()
1027 const room = Math.max(6, (e.viewport?.rows ?? 30) - 12)
1028
1029 const mainSteps = allSteps.filter(s => !s.agentId)
1030 const last = mainSteps.at(-1)
1031 const turnId = last?.turnId
1032 const turnSteps = allSteps.filter(s => s.turnId === turnId || (s.agentId && allWorkers.some(w => w.agentId === s.agentId && w.status === 'running')))
1033 const tokensIn = turnSteps.reduce((n, s) => n + s.tokensIn, 0)
1034 const tokensOut = turnSteps.reduce((n, s) => n + s.tokensOut, 0)
1035 const cacheRead = turnSteps.reduce((n, s) => n + s.cacheRead, 0)
1036 const turnCost = turnSteps.reduce((n, s) => n + (s.cost ?? 0), 0)
1037 const running = allWorkers.filter(w => w.status === 'running').length
1038 const workerType = (agentId: string) => allWorkers.find(w => w.agentId === agentId)?.type ?? 'worker'
1039
1040 const header = (
1041 <Box flexDirection="column" borderStyle="round" borderColor={C.accent} paddingX={1}>
1042 <Box justifyContent="space-between">
1043 <Text bold color={C.accent}>◆ AGENT LENS</Text>
1044 <Box gap={1}>
1045 <Text color={running ? C.run : C.ok}>{running ? `● ${running} worker${running > 1 ? 's' : ''}` : '○ idle'}</Text>
1046 {/* Output styles: a small icon, not a tab; pressed again it goes back to Flow. */}
1047 <Button
1048 key="tab-styles"
1049 plain
1050 label={current === 'styles' ? '[Aa]' : 'Aa'}
1051 hotkey="y"
1052 onPress={() => {
1053 void update($, tab, () => (current === 'styles' ? 'think' : 'styles'))
1054 if (current !== 'styles') void loadStyles($)
1055 }}
1056 />
1057 </Box>
1058 </Box>
1059 {/* One line each: who works, how much room is left (context, 5h / 7-day from /usage), what it costs
1060 (API list prices: on a subscription a measure, not the bill), then the switches. */}
1061 <Text wrap="truncate-end">
1062 <Text bold color={C.model}>{short(last?.model ?? String(sessionModel ?? '—'))}</Text>
1063 {last?.effort && <Text color={C.info}> {last.effort}</Text>}
1064 <Text dimColor> · turn </Text>
1065 <Text>{usd(turnCost)}</Text>
1066 <Text dimColor> · session </Text>
1067 <Text>{usd(sum.cost ?? 0)}</Text>
1068 </Text>
1069 <Text wrap="truncate-end">
1070 <Text dimColor>context </Text>
1071 <Text color={pctColor(context.percent ?? 0, 85)}>{context.percent ?? '—'}%</Text>
1072 {rateLimits.filter(r => r.kind === 'five_hour' || r.kind === 'seven_day').map(r => (
1073 <Text key={`rl-${r.kind}`}>
1074 <Text dimColor> · {WINDOWS[r.kind]} </Text>
1075 <Text color={pctColor(r.percentUsed, 90)}>{r.percentUsed}%</Text>
1076 {r.resetsAt && <Text dimColor> {until(Date.parse(r.resetsAt) - now)}</Text>}
1077 </Text>
1078 ))}
1079 </Text>
1080 <Box gap={1}>
1081 <Button key="planfirst" plain dimColor={!isPlanFirst} label={`${isPlanFirst ? '✓' : '○'} miniplan`} hotkey="n" onPress={() => update($, planFirst, v => !v)} />
1082 <Button key="check" plain dimColor={!isChecking} label={`${isChecking ? '✓' : '○'} prompt check`} hotkey="k" onPress={() => void flipCheck($)} />
1083 {graphReady && <Button key="graph" plain dimColor={!isGraphFirst} label={`${isGraphFirst ? '✓' : '○'} graph first`} hotkey="g" onPress={() => update($, graphFirst, v => !v)} />}
1084 </Box>
1085 </Box>
1086 )
1087
1088 const tabs = (
1089 <Box gap={1}>
1090 {(
1091 [
1092 ['think', 'Flow', 'f'],
1093 ['changes', `Git ${list.length}`, 'c'],
1094 ['memories', 'Memories', 'e'],
1095 ['hooks', 'Hooks', 'h'],
1096 ] as [Tab, string, string][]
1097 ).map(([id, label, hotkey]) => (
1098 <Button
1099 key={`tab-${id}`}
1100 label={label}
1101 hotkey={hotkey}
1102 variant={current === id ? 'primary' : 'secondary'}
1103 onPress={() => {
1104 void update($, tab, () => id)
1105 if (id === 'changes') void refreshChanges($)
1106 if (id === 'memories') void loadMemories($)
1107 if (id === 'hooks') void loadHooks($)
1108 }}
1109 />
1110 ))}
1111 </Box>
1112 )
1113
1114 const toolIcon = (name: string) =>
1115 name.startsWith('codegraph:') ? '◈' : /^(Read|Grep|Glob)$/.test(name) ? '⌕' : EDIT_TOOLS.has(name) ? '✎' : name === 'Bash' ? '$' : /^(Agent|Task)$/.test(name) ? '⤷' : name === 'Skill' ? '✦' : '•'
1116 const toolColor = (name: string) => (name.startsWith('codegraph:') ? C.graph : EDIT_TOOLS.has(name) ? C.run : name === 'Skill' ? C.info : undefined)
1117 const chips = (tools: string[]) => {
1118 const counts = new Map<string, number>()
1119 for (const name of tools) counts.set(name, (counts.get(name) ?? 0) + 1)
1120
1121 return [...counts].map(([name, n]) => (
1122 <Text key={name} color={toolColor(name)} bold={name.startsWith('codegraph:')}>
1123 {toolIcon(name)} {name.replace(/^codegraph:(codegraph_)?/, 'graph:')}
1124 {n > 1 ? `×${n}` : ''}{' '}
1125 </Text>
1126 ))
1127 }
1128
1129 const turnTools = turnSteps.flatMap(s => s.tools)
1130 const graphN = turnTools.filter(t => t.startsWith('codegraph:')).length
1131 const classicN = turnTools.filter(t => /^(Read|Grep|Glob)$/.test(t)).length
1132 const graphCells = graphN + classicN === 0 ? 0 : Math.round((graphN / (graphN + classicN)) * 10)
1133 const turnWorkers = allWorkers.filter(w => w.startedAt >= since)
1134
1135 // Everything foldable: sections, plan steps, execution steps. A missing key = the default state.
1136 const isOpen = (key: string, byDefault: boolean) => foldNow[key] ?? byDefault
1137 const toggle = (key: string, open: boolean) => void update($, folds, f => ({ ...f, [key]: open }))
1138 const fold = { isOpen, toggle }
1139 const section = (key: string, title: string, byDefault: boolean, body: () => RenderChildren, aside?: RenderChildren) => kitSection({ Box, Text, Button }, fold, key, title, byDefault, body, aside)
1140
1141 // The Flow tab: a stage line, what needs the person first, how the model understood the request, the plan
1142 // by level (steps on the same level run in parallel: ┬ ├ └) and what was actually executed, step by step.
1143 const STATUS_MARK = { todo: ['○', undefined], run: ['●', C.run], done: ['✓', C.ok], skip: ['⊘', undefined] } as const
1144 const WORKER_COLOR = { running: C.run, done: C.ok, aborted: C.bad, denied: C.bad } as const
1145 const sessionTier = tierOf(String(sessionModel ?? '')) ?? 'opus'
1146 const planLevels = planNow ? layers(planNow.steps) : []
1147 const doneN = planNow?.steps.filter(s => s.status === 'done' || s.status === 'skip').length ?? 0
1148 const clarityColor = (n: number) => (n >= 8 ? C.ok : n >= 5 ? C.run : C.bad)
1149 const skillList = Object.entries(used).sort((a, b) => b[1] - a[1])
1150 const pad = ' '
1151 const isOpenQ = (ask: string) => !answered[ask] || answered[ask].state === 'draft'
1152 // Questions from the prompt check and the plan, the open ones first; the first open one takes the digit hotkeys.
1153 const questions = [...(checkNow?.questions ?? []), ...(planNow?.questions ?? [])].filter((q, i, all) => all.findIndex(x => x.ask === q.ask) === i)
1154 const openQ = questions.filter(q => isOpenQ(q.ask))
1155 const suggested = planNow?.steps.filter(s => s.tier && s.status !== 'done' && s.status !== 'skip' && isOpenQ(delegationAsk(s))) ?? []
1156 // Where the turn is: understanding (no plan yet), planning (plan, no tool after it), executing, done.
1157 const execN = turnSteps.filter(s => !s.agentId && s.tools.some(t => t !== 'agent-lens:plan')).length
1158 const phase = !isBusy && !planNow && turnSteps.length === 0 ? 'idle' : !planNow ? 'understand' : isBusy ? (execN ? 'execute' : 'plan') : 'done'
1159 const PHASES = ['understand', 'plan', 'execute', 'done'] as const
1160 const phaseAt = PHASES.indexOf(phase as (typeof PHASES)[number])
1161
1162 const phaseLine = (
1163 <Text wrap="truncate-end">
1164 {PHASES.map((name, i) => (
1165 <Text key={`phase-${name}`}>
1166 {i > 0 && <Text dimColor> → </Text>}
1167 <Text color={i < phaseAt ? C.ok : i === phaseAt ? C.run : undefined} dimColor={i > phaseAt || phase === 'idle'} bold={i === phaseAt}>
1168 {i < phaseAt ? '✓' : i === phaseAt ? '●' : '○'} {name}
1169 </Text>
1170 </Text>
1171 ))}
1172 </Text>
1173 )
1174
1175 // Where the turn is, at a glance: the request, the stage and the plan's progress with the step under way.
1176 const runningStep = planNow?.steps.find(s => s.status === 'run')
1177 const total = planNow?.steps.length ?? 0
1178 const filled = total ? Math.round((doneN / total) * 10) : 0
1179 const nowCard = (
1180 <Box flexDirection="column" borderStyle="round" borderColor={phase === 'done' ? C.ok : phase === 'idle' ? C.info : C.run} borderDimColor={phase === 'idle'} paddingX={1}>
1181 {lastPrompt !== '' ? (
1182 <Text wrap="truncate-end">
1183 <Text color={C.accent}>▸ </Text>
1184 <Text italic>{lastPrompt.replace(/\s+/g, ' ')}</Text>
1185 </Text>
1186 ) : (
1187 <Text dimColor>Send a prompt: the plan shows up here first.</Text>
1188 )}
1189 {phaseLine}
1190 {total > 0 && (
1191 <Text wrap="truncate-end">
1192 <Text color={C.ok}>{'▰'.repeat(filled)}</Text>
1193 <Text dimColor>{'▱'.repeat(10 - filled)} {doneN}/{total}</Text>
1194 {runningStep && <Text dimColor> · now </Text>}
1195 {runningStep && <Text color={C.run}>{runningStep.title}</Text>}
1196 </Text>
1197 )}
1198 </Box>
1199 )
1200hooks/changes.ts 93 lines1// The "Git" tab: only the modified files, not the whole tree. The commands (`status --porcelain=v1 -z`,
2// `diff HEAD --numstat -z`) follow the approach from data-goblin/claude-code-filetree (MIT).
3import type { Change } from '../types'
4
5export const parseStatus = (out: string): { branch: string; changes: Change[] } => {
6 const parts = out.split('\0').filter(Boolean)
7 const changes: Change[] = []
8 let branch = ''
9 for (let i = 0; i < parts.length; i++) {
10 const rec = parts[i] ?? ''
11 if (rec.startsWith('## ')) {
12 branch = rec.slice(3)
13 continue
14 }
15 const [x = ' ', y = ' '] = rec
16 const path = rec.slice(3)
17 if (x === 'R' || x === 'C') i++ // the next record is the old path
18 const isNew = x === '?'
19 const isConflict = x === 'U' || y === 'U' || (x === 'A' && y === 'A') || (x === 'D' && y === 'D')
20 changes.push({
21 path,
22 code: isNew ? '?' : isConflict ? 'U' : x !== ' ' ? x : y,
23 staged: !isNew && !isConflict && x !== ' ',
24 unstaged: isNew || isConflict || y !== ' ',
25 add: 0,
26 del: 0,
27 })
28 }
29
30 return { branch, changes }
31}
32
33export const parseNumstat = (out: string): Record<string, [number, number]> => {
34 const parts = out.split('\0')
35 const nums: Record<string, [number, number]> = {}
36 for (let i = 0; i < parts.length; i++) {
37 const m = (parts[i] ?? '').match(/^(\d+|-)\t(\d+|-)\t([\s\S]*)$/)
38 if (!m) continue
39 let path = m[3] ?? ''
40 if (path === '') {
41 i += 2 // rename: the old path follows, then the new one
42 path = parts[i] ?? ''
43 }
44 nums[path] = [Number(m[1]) || 0, Number(m[2]) || 0]
45 }
46
47 return nums
48}
49
50// "master...origin/master [ahead 1]" → { name, sync }
51export const branchLabel = (line: string) => {
52 const name = line.split('...')[0]?.replace(/^No commits yet on /, '') ?? ''
53 const ahead = line.match(/ahead (\d+)/)?.[1]
54 const behind = line.match(/behind (\d+)/)?.[1]
55
56 return { name, upstream: line.includes('...'), gone: line.includes('[gone]'), ahead: Number(ahead ?? 0), behind: Number(behind ?? 0), sync: `${ahead ? `↑${ahead}` : ''}${behind ? `↓${behind}` : ''}` }
57}
58
59// Sync = only what is missing, after a `fetch`: no upstream → push -u; behind → pull; ahead → push.
60// Upstream `[gone]` (branch deleted on the remote, usually after a merge): nothing, so it isn't re-created.
61// ponytail: pull is --ff-only only; on diverged branches it stops with git's error, rebase/merge stay manual
62export const syncSteps = (b: ReturnType<typeof branchLabel>): string[][] => {
63 if (b.gone) return []
64 if (!b.upstream) return [['push', '-u', 'origin', 'HEAD']]
65
66 return [...(b.behind ? [['pull', '--ff-only']] : []), ...(b.ahead ? [['push']] : [])]
67}
68
69export type Outcome = { ok: boolean; text: string }
70
71// The first useful line of a git command's output (without the `hint:` suggestions).
72export const outcomeOf = (run: { exitCode: number; stdout: string; stderr: string }): Outcome => {
73 const lines = (run.exitCode === 0 ? run.stdout : run.stderr || run.stdout).split('\n').map(l => l.trim()).filter(Boolean)
74
75 return { ok: run.exitCode === 0, text: lines.find(l => !l.startsWith('hint:')) ?? (run.exitCode === 0 ? 'done' : 'failed') }
76}
77
78// Whether or not `diff` was read, files come sorted by path and with line counts filled in.
79export const withCounts = (changes: Change[], nums: Record<string, [number, number]>) =>
80 changes.map(c => ({ ...c, add: nums[c.path]?.[0] ?? 0, del: nums[c.path]?.[1] ?? 0 })).sort((a, b) => a.path.localeCompare(b.path))
81
82// Cuts at a whole line (a hunk cut in the middle no longer parses); without a newline, cuts at the limit.
83export const clip = (text: string, max: number) => {
84 if (text.length <= max) return text
85 const cut = text.slice(0, max)
86
87 return cut.slice(0, cut.lastIndexOf('\n') + 1 || max)
88}
89
90// Haiku sometimes wraps the answer in quotes or a code fence: keep the first useful line.
91export const cleanMessage = (text: string) =>
92 (text.split('\n').map(l => l.trim()).find(l => l && !l.startsWith('```')) ?? '').replace(/^["'`]+|["'`]+$/g, '')
93hooks/plan.ts 133 lines1import type { Plan, PlanStep } from '../types'
2
3// The tool the main model uses to publish its plan: what it understood, what it assumes,
4// the step flow (after what, which step a subagent on another model could take) and what would make the request more precise.
5export const PLAN_TOOL = 'plan'
6export const PLAN_TOOL_ID = 'mcp__agent-lens__plan'
7
8const TIERS = ['haiku', 'sonnet', 'opus'] as const
9const STATUSES = ['todo', 'run', 'done', 'skip'] as const
10
11export const PLAN_SCHEMA = {
12 type: 'object',
13 properties: {
14 goal: { type: 'string', description: 'What you understood the user wants, in one sentence, in your own words.' },
15 approach: { type: 'string', description: 'How you will act, in 1-2 sentences: what you do first, what you change, how you verify.' },
16 clarity: { type: 'integer', minimum: 0, maximum: 10, description: 'How clear the request is: 10 = you know exactly what and where, 0 = you are guessing.' },
17 assumptions: { type: 'array', items: { type: 'string' }, description: 'What you assume without having been told.' },
18 questions: {
19 type: 'array',
20 items: {
21 type: 'object',
22 properties: {
23 ask: { type: 'string', description: 'A closed question, answered with a word or a choice.' },
24 why: { type: 'string', description: 'What would change in the work depending on the answer.' },
25 options: { type: 'array', items: { type: 'string' }, description: '2-4 short answers (1-4 words) the user picks with one click; the first is the recommended one.' },
26 default: { type: 'string', description: 'What you do if there is no answer; the work continues on this.' },
27 },
28 required: ['ask'],
29 },
30 description: 'Only what concretely changes the work (at most 3). The user answers from the tab; the answer reaches you in the same turn, after a tool result.',
31 },
32 better_prompt: { type: 'string', description: 'The request rewritten the way it should have been phrased, as a model for next time.' },
33 steps: {
34 type: 'array',
35 items: {
36 type: 'object',
37 properties: {
38 id: { type: 'string' },
39 title: { type: 'string' },
40 tier: { enum: [...TIERS], description: 'Only when a subagent on this model would do the step well (haiku: lookups and reads; sonnet: mechanical changes with a clear spec; opus: a parallel worker on the session model). A suggestion: you do the step yourself unless the user confirms it from the Flow tab. Omit for steps you do yourself.' },
41 why: { type: 'string', description: 'With tier: why a subagent on that model fits this step, in a few words.' },
42 after: { type: 'array', items: { type: 'string' }, description: 'Ids of the steps that must finish first; steps with no shared dependencies run in parallel.' },
43 status: { enum: [...STATUSES] },
44 },
45 required: ['id', 'title'],
46 },
47 },
48 savings: { type: 'array', items: { type: 'string' }, description: 'Efficiencies: what you skip, what runs in parallel, what you reuse.' },
49 },
50 required: ['goal', 'approach', 'clarity', 'steps'],
51}
52
53export const PLAN_DESCRIPTION =
54 'Publishes to the Agent Lens sidebar (Flow tab) how you understood the request and how you split it into steps: what you assume, what runs in parallel, which step a subagent on another model could take (a suggestion the user confirms from the tab), what you make more efficient and what the user should clarify. Call it once at the start of every request, however short, before any other tool; call it again with the whole plan only when the plan changes or a phase ends (status per step). Write the plan fields in the language of the user\'s latest prompt.'
55
56export const ANSWERS_TAG = '[Agent Lens · answers]'
57
58export const PLAN_RULE = `At the start of every request, however short (even ones of 1-2 tool calls), before any other tool, call ${PLAN_TOOL_ID} with a mini-plan, even if you are not in plan mode: what you understood (goal) and how you act (approach), the clarity, the assumptions, the steps with their dependencies (and, where a subagent on another model would do a step well, its tier and why: a suggestion only, do the step yourself unless the user confirms it), the efficiencies, and the questions that would make the user more specific (each with options and what you do by default, so you do not stop and wait). Call it again only when the plan changes or a phase ends; at the end mark the steps done. The user answers questions from the Flow tab: the answers arrive marked ${ANSWERS_TAG}, either after a tool result or as a new message. They override your assumptions: apply them immediately, and if they change the steps, republish the plan without the answered questions. A confirmed step suggestion arrives the same way ("step <title> → delegate to <model>"): only then start that subagent through Agent with that model. Write the plan fields in the language of the user's latest prompt.`
59
60export const strs = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string' && x.trim() !== '') : [])
61const oneOf = <T extends string>(v: unknown, list: readonly T[], fallback: T) => (list.includes(v as T) ? (v as T) : fallback)
62
63// Questions from a model (the plan, the prompt check): a bare string or { ask, why, options, default }.
64export const questionsOf = (v: unknown): Plan['questions'] =>
65 (Array.isArray(v) ? v : [])
66 .map(q =>
67 typeof q === 'string'
68 ? { ask: q, why: '', options: [], fallback: '' }
69 : { ask: String(q?.ask ?? ''), why: String(q?.why ?? ''), options: strs(q?.options).slice(0, 4), fallback: typeof q?.default === 'string' ? q.default : '' },
70 )
71 .filter(q => q.ask.trim() !== '')
72
73// The input comes from the model: any missing or wrongly typed field gets a safe value.
74export const normalizePlan = (input: unknown, at: number): Plan => {
75 const o = (input ?? {}) as Record<string, unknown>
76 const raw = Array.isArray(o.steps) ? (o.steps as Record<string, unknown>[]) : []
77 const steps: PlanStep[] = raw.map((s, i) => ({
78 id: String(s?.id ?? i + 1),
79 title: String(s?.title ?? '—'),
80 tier: TIERS.includes(s?.tier as never) ? (s?.tier as PlanStep['tier']) : undefined,
81 why: typeof s?.why === 'string' ? s.why : '',
82 after: strs(s?.after),
83 status: oneOf(s?.status, STATUSES, 'todo'),
84 }))
85 return {
86 goal: String(o.goal ?? ''),
87 approach: typeof o.approach === 'string' ? o.approach : '',
88 clarity: Math.max(0, Math.min(10, Math.round(Number(o.clarity) || 0))),
89 assumptions: strs(o.assumptions),
90 questions: questionsOf(o.questions),
91 betterPrompt: typeof o.better_prompt === 'string' ? o.better_prompt : '',
92 steps,
93 savings: strs(o.savings),
94 revision: 0,
95 at,
96 }
97}
98
99// Flow levels: a step sits on the level after its latest dependency,
100// so steps on the same level can run in parallel. Unknown dependencies are ignored;
101// a cycle lands on the last level instead of blocking the drawing.
102export const layers = (steps: readonly PlanStep[]): PlanStep[][] => {
103 const ids = new Set(steps.map(s => s.id))
104 const level = new Map<string, number>()
105 let changed = true
106 for (let pass = 0; changed && pass <= steps.length; pass++) {
107 changed = false
108 for (const s of steps) {
109 const deps = s.after.filter(d => ids.has(d) && d !== s.id)
110 if (!deps.every(d => level.has(d))) continue
111 const l = deps.length ? Math.max(...deps.map(d => level.get(d)!)) + 1 : 0
112 if (level.get(s.id) !== l) {
113 level.set(s.id, l)
114 changed = true
115 }
116 }
117 }
118 const last = level.size ? Math.max(...level.values()) + 1 : 0
119 const out: PlanStep[][] = []
120 for (const s of steps) (out[level.get(s.id) ?? last] ??= []).push(s)
121
122 return out.filter(Boolean)
123}
124
125// What the model reads when the user answers from the tab: the question next to the answer,
126// so it does not depend on question order in a newer plan revision.
127export const answersMessage = (answered: readonly { ask: string; text: string }[]) =>
128 answered.length ? [ANSWERS_TAG, ...answered.map(a => `- ${a.ask}\n → ${a.text}`)].join('\n') : ''
129
130// A step suggestion confirmed from Flow travels as an answer: the question is the step, the answer the delegation.
131export const delegationAsk = (s: PlanStep) => `step ${s.title}`
132export const delegationText = (s: PlanStep) => `delegate to a ${s.tier} subagent${s.why ? ` (${s.why})` : ''}`
133hooks/memories-tab.tsx 349 lines1import type { Memory, MemoryAudit, MemoryMeta, MemoryUse, MemoryView } from '../types'
2import { backlinks, isolated } from './memories'
3import { bar, card, needsYou, section } from './kit'
4import type { Fold } from './kit'
5
6// Memories tab, drawing only. Whatever touches `$` (reading the directory, tracking tools) lives in
7// register.tsx, with the atoms: the engine does not let `$` pass into an imported function and reads atoms only from their own file.
8
9export const INDEX = 'MEMORY.md'
10const TYPE_COLOR: Record<string, string> = { project: 'cyan', feedback: 'yellow', reference: 'blue', user: 'magenta' }
11// What each memory type is for, and why it matters to the model. The four types are the memory system's own taxonomy.
12const TYPE_HELP: Record<string, string> = {
13 user: 'user: who you are, your role and preferences. Shapes every answer.',
14 feedback: 'feedback: how to work with you, corrections and confirmed approaches, with the why. Applied to every similar task.',
15 project: 'project: ongoing work, goals and deadlines not visible in the code. Goes stale, so check its dates.',
16 reference: 'reference: pointers to external systems (dashboards, tickets, docs). Tells the model where to look.',
17}
18// The four types in the order they matter to the model, then whatever else the frontmatter says.
19const TYPE_ORDER = ['user', 'feedback', 'project', 'reference']
20const TYPE_SHORT: Record<string, string> = { user: 'who you are', feedback: 'how to work with you', project: 'ongoing work, goes stale', reference: 'where to look' }
21// The analysis verdicts.
22export const VERDICT = {
23 irrelevant: { mark: '✗', color: 'red', rank: 0 },
24 stale: { mark: '◐', color: 'yellow', rank: 1 },
25 relevant: { mark: '✓', color: 'green', rank: 2 },
26} as const
27// One mark per memory, the verdict and the problems together: ✗ delete it, ◐ look at it, ✓ fine, · not checked yet.
28const HEALTH = {
29 drop: { mark: '✗', color: 'red', rank: 0 },
30 look: { mark: '◐', color: 'yellow', rank: 1 },
31 new: { mark: '·', color: undefined, rank: 2 },
32 ok: { mark: '✓', color: 'green', rank: 3 },
33} as const
34const ago = (ms: number) => (ms < 3_600_000 ? `${Math.max(1, Math.round(ms / 60_000))}m` : ms < 86_400_000 ? `${Math.round(ms / 3_600_000)}h` : `${Math.round(ms / 86_400_000)}d`)
35const UNTYPED = 'untyped: no type in the frontmatter, so the model cannot tell when it applies.'
36const k = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n))
37const tail = (path: string) => path.split('/').slice(-2).join('/')
38const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? '' : 's'}`
39
40export type MemoryData = { list: Memory[]; meta: MemoryMeta; use: Record<string, MemoryUse>; opened: MemoryView | null; audit: MemoryAudit; now: number; fold: Fold }
41export type MemoryActions = { open: (name: string) => void; back: () => void; refresh: () => void; analyze: () => void; mermaid: (press: any) => void; fix: (name: string) => void; remove: (names: string[]) => void; unlink: (target: string) => void }
42type Ui = { Box: any; Text: any; Button: any; Markdown: any } // ponytail: terminal elements, untyped here; register.tsx provides them from $.ui.resolve
43
44export const memoriesView = (ui: Ui, { list, meta, use, opened, audit, now, fold }: MemoryData, act: MemoryActions) => {
45 const { Box, Text, Button, Markdown } = ui
46 const back = backlinks(list)
47 const names = new Set(list.map(m => m.name))
48 const edges = list.reduce((n, m) => n + m.links.filter(l => names.has(l)).length, 0)
49 const lonely = isolated(list)
50 const marks = (name: string) => {
51 const u = use[name]
52
53 return u ? `${u.read ? ` ◉${u.read}` : ''}${u.write ? ` ✎${u.write}` : ''}${u.recalled ? ` ↺${u.recalled}` : ''}` : ''
54 }
55 const open = (name: string) => () => act.open(name)
56
57 if (!meta.loaded) return <Text dimColor>Reading the project memory…</Text>
58 if (!list.length) return <Text dimColor>The project has no memories in {meta.dir || '—'}.</Text>
59
60 const v = (name: string) => audit.verdicts[name]
61 const broken = (m: Memory) => m.links.filter(l => !names.has(l))
62 // What is wrong with a memory, in words; empty = nothing.
63 const issues = (m: Memory) => {
64 const verdict = v(m.name)
65
66 return [
67 verdict && verdict.verdict !== 'relevant' ? verdict.verdict : '',
68 broken(m).length ? plural(broken(m).length, 'broken link') : '',
69 verdict?.gone?.length ? 'names gone code' : '',
70 m.indexed ? '' : 'outside MEMORY.md',
71 ].filter(Boolean)
72 }
73 const health = (m: Memory) => (v(m.name)?.verdict === 'irrelevant' ? HEALTH.drop : issues(m).length ? HEALTH.look : v(m.name) ? HEALTH.ok : HEALTH.new)
74
75 // An open memory: where it stands and what to do, then what it says, its neighbors and how it was used.
76 const node = opened && list.find(m => m.name === opened.name)
77 if (opened && node) {
78 const out = node.links
79 const inc = back[node.name] ?? []
80 const u = use[node.name]
81 const verdict = v(node.name)
82 const look = health(node)
83 const edge = (name: string, i: number, all: string[], dir: string) => (
84 <Box key={`${dir}-${name}`}>
85 <Text dimColor>{i === all.length - 1 ? ' └─ ' : ' ├─ '}</Text>
86 {names.has(name) ? (
87 <Button key={`go-${dir}-${name}`} plain label={name} onPress={open(name)} />
88 ) : (
89 <Text color="red">✗ {name} (does not exist yet)</Text>
90 )}
91 <Text dimColor>{marks(name)}</Text>
92 </Box>
93 )
94
95 return (
96 <Box flexDirection="column" gap={1}>
97 {card(
98 ui,
99 look.color ?? 'blue',
100 <>
101 <Box justifyContent="space-between">
102 <Text bold color={look.color} wrap="truncate-end">
103 {look.mark} {node.name}
104 </Text>
105 <Button key="mem-back" plain label="← all" hotkey="b" onPress={act.back} />
106 </Box>
107 <Text dimColor wrap="wrap">{node.description}</Text>
108 <Text wrap="wrap" color={TYPE_COLOR[node.type]}>{TYPE_HELP[node.type] ?? UNTYPED}</Text>
109 {verdict && (
110 <Text wrap="wrap">
111 <Text color={VERDICT[verdict.verdict].color}>{VERDICT[verdict.verdict].mark} {verdict.verdict}</Text>
112 <Text dimColor> · {verdict.why}</Text>
113 </Text>
114 )}
115 {verdict?.gone?.length ? <Text wrap="wrap" color="red">gone from the code: {verdict.gone.map(r => `\`${r}\``).join(', ')}</Text> : null}
116 <Text wrap="wrap">
117 <Text dimColor>in the prompt (MEMORY.md): </Text>
118 {node.indexed ? <Text>„{node.hook}”</Text> : <Text color="red">missing from the index: the model sees it only if it looks for it</Text>}
119 </Text>
120 <Text dimColor>
121 this session: read {u?.read ?? 0} · written {u?.write ?? 0} · recalled {u?.recalled ?? 0}
122 </Text>
123 </>,
124 )}
125 {verdict && verdict.verdict !== 'relevant' &&
126 needsYou(
127 ui,
128 verdict.fix ? 'apply the fix or delete' : 'delete or keep',
129 <Box gap={1}>
130 {verdict.fix ? <Button key={`mem-fix-${node.name}`} variant="primary" label="apply the fix" onPress={() => act.fix(node.name)} /> : null}
131 <Button key={`mem-del-${node.name}`} label="delete" onPress={() => act.remove([node.name])} />
132 </Box>,
133 'unanswered = the memory stays as it is',
134 )}
135 {verdict?.fix ? section(ui, fold, 'mv-fix', 'Proposed fix · replaces the body, keeps the frontmatter', true, () => <Markdown text={verdict.fix!} />) : null}
136 {section(ui, fold, 'mv-links', 'Links', true, () => (
137 <Box flexDirection="column">
138 <Text dimColor>links to → {out.length}</Text>
139 {out.map((n, i) => edge(n, i, out, 'out'))}
140 <Text dimColor>cited by ← {inc.length}</Text>
141 {inc.map((n, i) => edge(n, i, inc, 'in'))}
142 </Box>
143 ))}
144 {section(ui, fold, 'mv-body', 'What it says', true, () => <Markdown text={opened.body} />)}
145 </Box>
146 )
147 }
148
149 const analyzed = Object.keys(audit.verdicts).length > 0
150 const types = [...new Set([...TYPE_ORDER.filter(t => list.some(m => m.type === t)), ...list.map(m => m.type)])]
151 const degree = (m: Memory) => (back[m.name]?.length ?? 0) + m.links.length
152 const order = (a: Memory, b: Memory) => health(a).rank - health(b).rank || degree(b) - degree(a) || a.name.localeCompare(b.name)
153 const count = (h: (typeof HEALTH)[keyof typeof HEALTH]) => list.filter(m => health(m) === h).length
154 const reads = Object.entries(use).filter(([n, u]) => n !== INDEX && u.read).length
155 const writes = Object.values(use).reduce((n, u) => n + u.write, 0)
156 const recalled = Object.entries(use).filter(([, u]) => u.recalled).length
157 const promptTokens = meta.context.reduce((n, f) => n + f.tokens, 0)
158
159 // The decisions, one per row: a link to a memory that does not exist (grouped by target, so one press fixes
160 // every memory citing it), what Sonnet flagged, code that is gone, a memory the index does not list.
161 const missing = [...new Set(list.flatMap(broken))].map(to => ({ to, by: list.filter(m => m.links.includes(to)).map(m => m.name) }))
162 const flagged = list.filter(m => v(m.name) && v(m.name)!.verdict !== 'relevant').sort(order)
163 const goneOnly = list.filter(m => v(m.name)?.verdict === 'relevant' && v(m.name)?.gone?.length)
164 const unindexed = list.filter(m => !m.indexed)
165 const irrelevant = list.filter(m => v(m.name)?.verdict === 'irrelevant').map(m => m.name)
166 const decisions = missing.length + flagged.length + goneOnly.length + unindexed.length
167 const row = (key: string, mark: string, color: string, text: any, buttons: any) => (
168 <Box key={key} justifyContent="space-between">
169 <Text wrap="truncate-end">
170 <Text color={color}>{mark} </Text>
171 {text}
172 </Text>
173 <Box flexShrink={0} gap={1}>
174 {buttons}
175 </Box>
176 </Box>
177 )
178
179 // One memory, two lines: the mark, the name (press = open), who cites it and what is wrong; its description under it.
180 const memoryRow = (m: Memory) => {
181 const look = health(m)
182 const inN = back[m.name]?.length ?? 0
183 const wrong = issues(m)
184
185 return (
186 <Box key={`mem-${m.name}`} flexDirection="column">
187 <Box>
188 <Text color={look.color} dimColor={!look.color}>{look.mark} </Text>
189 <Button key={`mo-${m.name}`} plain label={m.name} onPress={open(m.name)} />
190 <Text wrap="truncate-end">
191 {inN > 0 && <Text color="cyan">{` ←${inN}`}</Text>}
192 {lonely.includes(m.name) && <Text dimColor> isolated</Text>}
193 {wrong.length > 0 && <Text color={look.color}> {wrong.join(' · ')}</Text>}
194 <Text color="green">{marks(m.name)}</Text>
195 </Text>
196 </Box>
197 <Text wrap="truncate-end" dimColor>
198 {' '}
199 {v(m.name) && v(m.name)!.verdict !== 'relevant' ? v(m.name)!.why : m.description || m.hook}
200 </Text>
201 </Box>
202 )
203 }
204
205 return (
206 <Box flexDirection="column" gap={1}>
207 {card(
208 ui,
209 count(HEALTH.drop) ? 'red' : count(HEALTH.look) ? 'yellow' : 'green',
210 <>
211 <Box justifyContent="space-between">
212 <Text wrap="truncate-end">
213 <Text bold>{list.length}</Text>
214 <Text dimColor> memories · </Text>
215 <Text color="green">✓ {count(HEALTH.ok)} fine</Text>
216 <Text color="yellow"> · ◐ {count(HEALTH.look)} to look at</Text>
217 <Text color="red"> · ✗ {count(HEALTH.drop)} to delete</Text>
218 </Text>
219 <Button key="mem-refresh" plain label="↻" onPress={act.refresh} />
220 </Box>
221 <Text wrap="truncate-end">
222 {bar(ui, count(HEALTH.ok), list.length)}
223 <Text dimColor> {count(HEALTH.ok)}/{list.length} healthy · {edges} links · {lonely.length} isolated</Text>
224 </Text>
225 {audit.running ? (
226 <Text color="yellow" wrap="wrap">● checking {list.length} memories against the code, then Sonnet reads them with CLAUDE.md and the recent commits…</Text>
227 ) : analyzed ? (
228 <Text dimColor>checked {ago(now - audit.at)} ago: the code, then Sonnet</Text>
229 ) : (
230 <Text dimColor wrap="wrap">Not analyzed yet: “analyze” checks what each memory names in the code, then asks Sonnet which still matter here. It only marks; fix and delete are presses.</Text>
231 )}
232 <Box gap={1}>
233 <Button key="mem-analyze" variant="primary" label={audit.running ? 'analyzing…' : analyzed ? 're-analyze' : 'analyze'} hotkey="a" onPress={act.analyze} />
234 <Button key="mem-mermaid" label="copy as mermaid" onPress={act.mermaid} />
235 </Box>
236 {audit.note ? <Text wrap="wrap" color={audit.note.startsWith('✗') ? 'red' : 'yellow'}>{audit.note}</Text> : null}
237 </>,
238 )}
239
240 {decisions > 0 &&
241 needsYou(
242 ui,
243 plural(decisions, 'decision'),
244 <>
245 {missing.map(({ to, by }) =>
246 row(
247 `mn-${to}`,
248 '✗',
249 'red',
250 <Text>
251 [[{to}]] <Text dimColor>does not exist · cited by {by.join(', ')}</Text>
252 </Text>,
253 <Button key={`mu-${to}`} plain label={`[unlink ×${by.length}]`} onPress={() => act.unlink(to)} />,
254 ),
255 )}
256 {flagged.map(m =>
257 row(
258 `mf-row-${m.name}`,
259 VERDICT[v(m.name)!.verdict].mark,
260 VERDICT[v(m.name)!.verdict].color,
261 <Text>
262 {m.name} <Text dimColor>{v(m.name)!.verdict}: {v(m.name)!.why}</Text>
263 </Text>,
264 <>
265 {v(m.name)!.fix ? <Button key={`mf-${m.name}`} plain label="[fix]" onPress={() => act.fix(m.name)} /> : null}
266 <Button key={`md-${m.name}`} plain label="[delete]" onPress={() => act.remove([m.name])} />
267 </>,
268 ),
269 )}
270 {goneOnly.map(m =>
271 row(
272 `mg-row-${m.name}`,
273 '?',
274 'yellow',
275 <Text>
276 {m.name} <Text dimColor>names code not found: {v(m.name)!.gone!.map(r => `\`${r}\``).join(' ')} (Sonnet still finds it relevant)</Text>
277 </Text>,
278 <Button key={`mg-${m.name}`} plain label="[open]" onPress={open(m.name)} />,
279 ),
280 )}
281 {unindexed.map(m =>
282 row(
283 `mi-row-${m.name}`,
284 '!',
285 'yellow',
286 <Text>
287 {m.name} <Text dimColor>outside the index: the model sees it only if it looks for it</Text>
288 </Text>,
289 <Button key={`mi-${m.name}`} plain label="[open]" onPress={open(m.name)} />,
290 ),
291 )}
292 {irrelevant.length > 1 && <Button key="mem-del-irrelevant" plain label={`[delete all ✗ ${irrelevant.length}]`} onPress={() => act.remove(irrelevant)} />}
293 </>,
294 'unlink keeps the word and drops the [[ ]] · unanswered = nothing changes',
295 )}
296
297 {types.map(t => {
298 const group = list.filter(m => m.type === t).sort(order)
299 const bad = group.filter(m => health(m) === HEALTH.look || health(m) === HEALTH.drop).length
300
301 return section(
302 ui,
303 fold,
304 `mem-${t}`,
305 `${t[0]!.toUpperCase()}${t.slice(1)} · ${TYPE_SHORT[t] ?? 'no type: the model cannot tell when it applies'}`,
306 true,
307 () => <Box flexDirection="column">{group.map(memoryRow)}</Box>,
308 <Text color={bad ? 'yellow' : TYPE_COLOR[t]} dimColor={!bad}>{bad ? `${bad} to look at · ${group.length}` : group.length}</Text>,
309 )
310 })}
311
312 {section(
313 ui,
314 fold,
315 'mem-prompt',
316 'In the prompt',
317 false,
318 () => (
319 <Box flexDirection="column">
320 {meta.context.map(f => (
321 <Text key={`ctx-${f.path}`} wrap="truncate-end">
322 <Text color="green">● </Text>
323 <Text>{tail(f.path)}</Text>
324 <Text dimColor> {f.type} · {k(f.tokens)} tok on every request</Text>
325 </Text>
326 ))}
327 {meta.context.length === 0 && <Text dimColor>nothing from memory in context</Text>}
328 <Text wrap="truncate-end">
329 <Text color="cyan">◉ read {reads}</Text>
330 <Text color="blue"> ↺ recalled {recalled}</Text>
331 <Text color="yellow"> ✎ written {writes}</Text>
332 {use[INDEX]?.read ? <Text dimColor> (MEMORY.md read ×{use[INDEX]!.read})</Text> : null}
333 </Text>
334 {meta.remember.length > 0 && (
335 <Text wrap="wrap" dimColor>
336 <Text color="magenta">+ .remember </Text>
337 {meta.remember.map(f => `${f.name} ${k(f.size)}`).join(' · ')} (remember plugin, at SessionStart)
338 </Text>
339 )}
340 <Text wrap="truncate-start" dimColor>{meta.dir}</Text>
341 </Box>
342 ),
343 <Text dimColor>{k(promptTokens)} tok / request</Text>,
344 )}
345 <Text dimColor wrap="wrap">✓ fine ◐ look at it ✗ delete · not checked · ←n cited by · press a name to open it</Text>
346 </Box>
347 )
348}
349hooks/styles-tab.tsx 117 lines1import type { Style, StyleDraft } from '../types'
2
3import { card, section } from './kit'
4import type { Fold } from './kit'
5
6// Output style tab, drawing only (like memories-tab.tsx): what touches `$` lives in register.tsx.
7
8export type StyleData = { list: Style[]; active: string; draft: StyleDraft | null; fresh: string; note: string; loaded: boolean; fold: Fold }
9export type StyleActions = {
10 open: (file: string) => void
11 back: () => void
12 use: (file: string) => void
13 desc: (v: string) => void
14 line: (i: number, v: string) => void
15 add: (i: number) => void
16 drop: (i: number) => void
17 save: () => void
18 fresh: (v: string) => void
19 create: (name: string) => void
20 refresh: () => void
21}
22type Ui = { Box: any; Text: any; Button: any; Input: any } // ponytail: terminal elements, untyped here; register.tsx provides them from $.ui.resolve
23
24export const stylesView = (ui: Ui, { list, active, draft, fresh, note, loaded, fold }: StyleData, act: StyleActions) => {
25 const { Box, Text, Button, Input } = ui
26 if (!loaded) return <Text dimColor>Reading the output styles…</Text>
27
28 const status = note ? <Text wrap="wrap" color={note.startsWith('✗') ? 'red' : 'green'}>{note}</Text> : null
29 const style = draft && list.find(s => s.file === draft.file)
30
31 // An open style: description and instructions edited line by line. Enter in a field = save.
32 if (draft && style) {
33 const isActive = style.name === active
34
35 return (
36 <Box flexDirection="column">
37 <Box justifyContent="space-between">
38 <Text bold color={isActive ? 'green' : undefined} wrap="truncate-end">{isActive ? '● ' : '○ '}{style.name}</Text>
39 <Button key="st-back" plain label="← list" hotkey="b" onPress={act.back} />
40 </Box>
41 <Text dimColor wrap="truncate-start">{style.file}{draft.dirty ? ' · unsaved changes' : ''}</Text>
42 <Box gap={1} marginTop={1}>
43 <Button key="st-use" variant="primary" label={isActive ? 'in use' : 'use this style'} onPress={() => act.use(style.file)} />
44 <Button key="st-save" label="save" hotkey="s" onPress={act.save} />
45 </Box>
46 {status}
47 <Box marginTop={1} flexDirection="column">
48 <Input key="st-desc" label="description " placeholder="one line" value={draft.description} submitLabel="save" onInput={act.desc} onSubmit={act.save} />
49 <Text bold dimColor>INSTRUCTIONS · one line per field</Text>
50 {draft.lines.map((l, i) => (
51 <Box key={`st-row-${i}`}>
52 <Input key={`st-line-${i}`} placeholder="(empty line)" value={l} submitLabel="save" onInput={(v: string) => act.line(i, v)} onSubmit={act.save} />
53 <Button key={`st-add-${i}`} plain label=" +" onPress={() => act.add(i)} />
54 <Button key={`st-drop-${i}`} plain label=" ×" onPress={() => act.drop(i)} />
55 </Box>
56 ))}
57 </Box>
58 <Text dimColor wrap="wrap">+ inserts a line below · × removes it · a style change reaches the model from the next session.</Text>
59 </Box>
60 )
61 }
62
63 return (
64 <Box flexDirection="column" gap={1}>
65 {/* A Button is no inline element: inside a Text the engine refuses the whole tree. */}
66 {card(
67 ui,
68 'green',
69 <>
70 <Box justifyContent="space-between">
71 <Text wrap="truncate-end">
72 <Text bold>{list.length}</Text>
73 <Text dimColor> styles · active: </Text>
74 <Text bold color="green">{active || 'default'}</Text>
75 </Text>
76 <Button key="st-refresh" plain label="↻" onPress={act.refresh} />
77 </Box>
78 <Text dimColor wrap="wrap">Press a name to read and edit it · “use” writes outputStyle in settings.json, read at the start of the next session.</Text>
79 {status}
80 </>,
81 )}
82 {section(
83 ui,
84 fold,
85 'st-list',
86 'Styles',
87 true,
88 () => (
89 <Box flexDirection="column">
90 {/* Two lines per style: name and "use" on one, the description under it, cut at the pane's width. */}
91 {list.map(s => (
92 <Box key={`st-${s.file}`} flexDirection="column">
93 <Box justifyContent="space-between">
94 <Box flexShrink={1} minWidth={0}>
95 <Text color={s.name === active ? 'green' : undefined}>{s.name === active ? '● ' : '○ '}</Text>
96 <Button key={`st-open-${s.file}`} plain label={s.name} onPress={() => act.open(s.file)} />
97 </Box>
98 <Box flexShrink={0} marginLeft={2}>
99 {s.name === active ? <Text color="green">in use</Text> : <Button key={`st-quick-${s.file}`} plain label="use" onPress={() => act.use(s.file)} />}
100 </Box>
101 </Box>
102 <Box marginLeft={2}>
103 <Text dimColor wrap="truncate-end">{s.description}</Text>
104 </Box>
105 </Box>
106 ))}
107 </Box>
108 ),
109 <Text dimColor>{list.length}</Text>,
110 )}
111 {section(ui, fold, 'st-new', 'New style', true, () => (
112 <Input key="st-new" label="name " placeholder={`name; starts as a copy of ${active || 'the first style'}`} value={fresh} submitLabel="create" onInput={act.fresh} onSubmit={act.create} />
113 ))}
114 </Box>
115 )
116}
117hooks/hooks-tab.tsx 170 lines1import type { HookDraft, HookPaths, HookRow } from '../types'
2import { EVENTS, hookLabel, mainKey, mainText } from './settings-hooks'
3import { card, section } from './kit'
4import type { Fold } from './kit'
5
6// Hooks tab, drawing only (like styles-tab.tsx): what touches `$` lives in register.tsx.
7// Global hooks only turn on/off; the project's take any change. "Off" = parked in a *.hooks-off.json beside the file.
8
9export type LensSwitch = { key: string; label: string; on: boolean; what: string }
10export type HookData = { rows: HookRow[]; draft: HookDraft | null; note: string; loaded: boolean; paths: HookPaths; lens: LensSwitch[]; fold: Fold }
11export type HookActions = {
12 open: (row: HookRow) => void
13 fresh: () => void
14 back: () => void
15 toggle: (row: HookRow) => void
16 remove: (row: HookRow) => void
17 edit: (patch: Partial<HookDraft>) => void
18 save: () => void
19 refresh: () => void
20 lens: (key: string) => void
21}
22type Ui = { Box: any; Text: any; Button: any; Input: any; Select: any } // ponytail: terminal elements, untyped here; register.tsx provides them from $.ui.resolve
23
24const WHERE = { global: 'global settings', project: '.claude/settings.json · shared', local: '.claude/settings.local.json · just you' } as const
25
26export const hooksView = (ui: Ui, { rows, draft, note, loaded, paths, lens, fold }: HookData, act: HookActions) => {
27 const { Box, Text, Button, Input, Select } = ui
28 if (!loaded) return <Text dimColor>Reading the hooks…</Text>
29
30 const status = note ? <Text wrap="wrap" color={note.startsWith('✗') ? 'red' : 'green'}>{note}</Text> : null
31 const title = (r: HookRow) => `${r.isOff ? '○' : '●'} ${r.event}${r.matcher ? ` · ${r.matcher}` : ''}`
32
33 if (draft) {
34 const r = draft.row
35 const back = <Button key="hk-back" plain label="← list" hotkey="b" onPress={act.back} />
36
37 // A global hook: read here, only turned on/off.
38 if (r?.scope === 'global') {
39 return (
40 <Box flexDirection="column">
41 <Box justifyContent="space-between">
42 <Text bold wrap="truncate-end">{title(r)}</Text>
43 {back}
44 </Box>
45 <Text dimColor wrap="truncate-start">{r.file}{r.isOff ? ' · off, parked beside it' : ''}</Text>
46 <Box marginTop={1}>
47 <Text wrap="wrap">{mainText(r.hook)}</Text>
48 </Box>
49 <Box marginTop={1}>
50 <Button key="hk-global-toggle" variant="primary" label={r.isOff ? 'turn on' : 'turn off'} onPress={() => act.toggle(r)} />
51 </Box>
52 {status}
53 </Box>
54 )
55 }
56
57 const field = r ? mainKey(r.hook) : 'command'
58
59 return (
60 <Box flexDirection="column">
61 <Box justifyContent="space-between">
62 <Text bold wrap="truncate-end">{r ? title(r) : '+ new hook'}</Text>
63 {back}
64 </Box>
65 {r && <Text dimColor wrap="wrap">{WHERE[r.scope]}{r.isOff ? ' · off, parked beside it' : ''}</Text>}
66 <Box flexDirection="column" marginTop={1}>
67 <Select key="hk-event" label="event " options={EVENTS.map(v => ({ value: v }))} value={draft.event} onSelect={(v: string) => act.edit({ event: v })} />
68 <Input key="hk-matcher" label="matcher " placeholder="all (or e.g. Bash|Edit|Write)" value={draft.matcher} submitLabel="save" onInput={(v: string) => act.edit({ matcher: v })} onSubmit={act.save} />
69 <Input key="hk-text" label={`${field} `} placeholder={field === 'command' ? 'shell command; reads the event JSON on stdin' : field} value={draft.text} submitLabel="save" onInput={(v: string) => act.edit({ text: v })} onSubmit={act.save} />
70 <Input key="hk-timeout" label="timeout " placeholder="seconds (empty = default)" value={draft.timeout} submitLabel="save" onInput={(v: string) => act.edit({ timeout: v })} onSubmit={act.save} />
71 {!r && (
72 <Select key="hk-where" label="file " options={[{ value: 'local', label: WHERE.local }, { value: 'project', label: WHERE.project }]} value={draft.scope} onSelect={(v: string) => act.edit({ scope: v === 'project' ? 'project' : 'local' })} />
73 )}
74 </Box>
75 <Box gap={1} marginTop={1}>
76 <Button key="hk-save" variant="primary" label={r ? 'save' : 'add'} hotkey="s" onPress={act.save} />
77 {r && <Button key="hk-toggle" label={r.isOff ? 'turn on' : 'turn off'} onPress={() => act.toggle(r)} />}
78 {r && <Button key="hk-delete" label="delete" onPress={() => act.remove(r)} />}
79 </Box>
80 {status}
81 </Box>
82 )
83 }
84
85 // A Button is no inline element: inside a Text the engine refuses the whole tree.
86 const row = (r: HookRow) => (
87 <Box key={`hk-${r.id}`}>
88 <Text color={r.isOff ? undefined : 'green'} dimColor={r.isOff}>{r.isOff ? '○ ' : '● '}</Text>
89 <Button key={`hk-open-${r.id}`} plain label={`${r.event}${r.matcher ? ` ${r.matcher}` : ''}`} onPress={() => act.open(r)} />
90 <Text dimColor wrap="truncate-end"> {r.scope === 'global' ? '' : `${r.scope} · `}{hookLabel(r.hook)}</Text>
91 <Button key={`hk-toggle-${r.id}`} plain label={r.isOff ? ' on' : ' off'} onPress={() => act.toggle(r)} />
92 </Box>
93 )
94 const global = rows.filter(r => r.scope === 'global')
95 const project = rows.filter(r => r.scope !== 'global')
96 const on = rows.filter(r => !r.isOff).length
97
98 return (
99 <Box flexDirection="column" gap={1}>
100 {card(
101 ui,
102 'green',
103 <>
104 <Box justifyContent="space-between">
105 <Text wrap="truncate-end">
106 <Text bold>{rows.length}</Text>
107 <Text dimColor> hooks · </Text>
108 <Text color="green">● {on} on</Text>
109 <Text dimColor> · ○ {rows.length - on} off</Text>
110 </Text>
111 <Button key="hk-refresh" plain label="↻" onPress={act.refresh} />
112 </Box>
113 <Text dimColor wrap="wrap">Claude Code reads hooks when a session starts: a change applies from the next one (or after review in /hooks). Off = parked in *.hooks-off.json beside the file.</Text>
114 {status}
115 </>,
116 )}
117 {section(
118 ui,
119 fold,
120 'hk-lens',
121 "Agent Lens · this mod's switches",
122 true,
123 () => (
124 <Box flexDirection="column">
125 {lens.map(s => (
126 <Box key={`hl-${s.key}`}>
127 <Text color={s.on ? 'green' : undefined} dimColor={!s.on}>{s.on ? '● ' : '○ '}{s.label}</Text>
128 <Text dimColor wrap="truncate-end"> {s.what}</Text>
129 <Button key={`hl-${s.key}-toggle`} plain label={s.on ? ' off' : ' on'} onPress={() => act.lens(s.key)} />
130 </Box>
131 ))}
132 </Box>
133 ),
134 <Text dimColor>{lens.filter(s => s.on).length}/{lens.length} on</Text>,
135 )}
136 {section(
137 ui,
138 fold,
139 'hk-global',
140 'Global · on/off only',
141 true,
142 () => (
143 <Box flexDirection="column">
144 <Text dimColor wrap="truncate-start">{paths.global || '—'}</Text>
145 {global.length === 0 && <Text dimColor>no hooks</Text>}
146 {global.map(r => row(r))}
147 </Box>
148 ),
149 <Text dimColor>{global.length}</Text>,
150 )}
151 {section(
152 ui,
153 fold,
154 'hk-project',
155 'Project · add, edit, delete',
156 true,
157 () => (
158 <Box flexDirection="column">
159 <Text dimColor wrap="truncate-start">{paths.project ? paths.project.replace(/settings\.json$/, 'settings{,.local}.json') : 'no project folder in this session'}</Text>
160 {paths.project !== '' && project.length === 0 && <Text dimColor>no hooks · “+ new” writes to .claude/settings.local.json</Text>}
161 {project.map(r => row(r))}
162 </Box>
163 ),
164 paths.project !== '' ? <Button key="hk-new" plain label="+ new" hotkey="a" onPress={act.fresh} /> : <Text dimColor>{project.length}</Text>,
165 )}
166 <Text dimColor>● on ○ off · press a hook to open it · plugin hooks are not listed</Text>
167 </Box>
168 )
169}
170hooks/check.ts 45 lines1import type { PromptCheck } from '../types'
2import { clip } from './changes'
3import { ANSWERS_TAG, questionsOf, strs } from './plan'
4
5// The prompt check: at submit, Haiku reads the prompt alone (not the code) and says what is missing, with
6// questions answered from Flow and the prompt rewritten. It helps the person phrase the request; the model does not wait.
7
8// Too short to judge ("da", "ok"), a slash command, or answers sent from the tab: not checked.
9export const worthChecking = (text: string) => {
10 const t = text.trim()
11
12 return t.length >= 8 && !t.startsWith('/') && !t.startsWith(ANSWERS_TAG)
13}
14
15export const checkPrompt = (text: string, previous: string) => `You check a prompt a developer just sent to an AI coding agent that works in their repository. You see the prompt only; the agent will read the code itself, so never ask what the code answers.
16Ask only what the developer alone knows: the intended result, the scope (which screens, modules, platforms), constraints, what "done" means, a choice between reasonable options. A short follow-up ("yes", "go on", "do it") is as clear as the previous prompt.
17Answer ONLY a JSON object, in the prompt's language:
18{"clarity": <0-10, 10 = nothing left to guess>, "missing": [<up to 3 things the prompt leaves out, at most 8 words each>], "questions": [<up to 3, only when clarity < 8: {"ask": "<closed question>", "options": [<2-4 answers of 1-4 words, the first recommended>], "default": "<what the agent will likely assume>"}>], "better": "<the prompt rewritten so nothing is left to guess, or \\"\\" when it is already clear>"}
19
20Previous prompt: ${clip(previous, 1500) || '(none)'}
21
22Prompt:
23${clip(text, 4000)}`
24
25// Lenient: the first {...} in the answer; anything missing or mistyped gets a safe value.
26export const parseCheck = (raw: string, at: number): PromptCheck | null => {
27 const json = raw.match(/\{[\s\S]*\}/)?.[0]
28 if (!json) return null
29 try {
30 const o = JSON.parse(json) as Record<string, unknown>
31
32 return {
33 at,
34 running: false,
35 clarity: Math.max(0, Math.min(10, Math.round(Number(o.clarity) || 0))),
36 missing: strs(o.missing).slice(0, 3),
37 questions: questionsOf(o.questions).slice(0, 3),
38 better: typeof o.better === 'string' ? o.better.trim() : '',
39 note: '',
40 }
41 } catch {
42 return null
43 }
44}
45hooks/settings-hooks.ts 116 lines1// The "Hooks" tab: Claude Code's own hooks, from the settings files. Pure parsing/editing here; the I/O lives in register.tsx.
2// Settings have no per-hook switch: an "off" hook is parked, in the same shape, in a sibling *.hooks-off.json.
3import type { HookEntry, HookRow } from '../types'
4
5type Group = { matcher?: string; hooks: HookEntry[] }
6export type Settings = { [key: string]: unknown; hooks?: Record<string, Group[]> }
7export type HookRef = { event: string; matcher: string; hook: HookEntry }
8
9export const EVENTS = ['PreToolUse', 'PostToolUse', 'PostToolUseFailure', 'PermissionRequest', 'UserPromptSubmit', 'Notification', 'Stop', 'StopFailure', 'SubagentStart', 'SubagentStop', 'PreCompact', 'SessionStart', 'SessionEnd'] as const
10
11export const offFile = (file: string) => file.replace(/\.json$/, '.hooks-off.json')
12
13// A missing file is empty; one that is not a JSON object throws, so it is never overwritten.
14export const parseSettings = (text: string): Settings => {
15 if (!text.trim()) return {}
16 const v: unknown = JSON.parse(text)
17 if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error('not a JSON object')
18
19 return v as Settings
20}
21
22export const serialize = (s: Settings) => `${JSON.stringify(s, null, 2)}\n`
23
24const groupsOf = (s: Settings): Record<string, Group[]> => (s.hooks && typeof s.hooks === 'object' ? s.hooks : {})
25
26const matcherOf = (g: Group) => (typeof g?.matcher === 'string' ? g.matcher : '')
27
28const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
29
30// `hooks` keeps its place among the settings' keys; left empty, it goes.
31const withGroups = (s: Settings, hooks: Record<string, Group[]>): Settings => {
32 const out: Settings = { ...s, hooks }
33 if (!Object.keys(hooks).length) delete out.hooks
34
35 return out
36}
37
38export const rowsOf = (s: Settings, scope: HookRow['scope'], file: string, isOff: boolean): HookRow[] =>
39 Object.entries(groupsOf(s)).flatMap(([event, groups]) =>
40 (Array.isArray(groups) ? groups : []).flatMap((g, gi) =>
41 (Array.isArray(g?.hooks) ? g.hooks : []).map((hook, hi) => ({ id: `${scope}:${isOff ? 'off' : 'on'}:${event}:${gi}:${hi}`, scope, file, event, matcher: matcherOf(g), hook, isOff })),
42 ),
43 )
44
45export const hasHook = (s: Settings, r: HookRef) => (groupsOf(s)[r.event] ?? []).some(g => matcherOf(g) === r.matcher && g.hooks?.some(h => same(h, r.hook)))
46
47// Drops the first equal hook, then a group or an event left empty.
48export const withoutHook = (s: Settings, r: HookRef): Settings => {
49 let isGone = false
50 const groups = (groupsOf(s)[r.event] ?? [])
51 .map(g => {
52 const i = isGone || matcherOf(g) !== r.matcher ? -1 : g.hooks.findIndex(h => same(h, r.hook))
53 if (i < 0) return g
54 isGone = true
55
56 return { ...g, hooks: g.hooks.filter((_, j) => j !== i) }
57 })
58 .filter(g => g.hooks?.length)
59 const hooks = { ...groupsOf(s), [r.event]: groups }
60 if (!groups.length) delete hooks[r.event]
61
62 return withGroups(s, hooks)
63}
64
65// Into the event's group with the same matcher, else a new group at its end.
66export const withHook = (s: Settings, r: HookRef): Settings => {
67 const groups = groupsOf(s)[r.event] ?? []
68 const i = groups.findIndex(g => matcherOf(g) === r.matcher)
69 const next = i >= 0 ? groups.map((g, j) => (j === i ? { ...g, hooks: [...g.hooks, r.hook] } : g)) : [...groups, { ...(r.matcher ? { matcher: r.matcher } : {}), hooks: [r.hook] }]
70
71 return withGroups(s, { ...groupsOf(s), [r.event]: next })
72}
73
74// Same event and matcher: in place, so the order the hooks run in stays; otherwise it moves.
75export const replaceHook = (s: Settings, old: HookRef, next: HookRef): Settings => {
76 if (old.event !== next.event || old.matcher !== next.matcher) return withHook(withoutHook(s, old), next)
77 let isDone = false
78 const groups = (groupsOf(s)[old.event] ?? []).map(g =>
79 matcherOf(g) !== old.matcher
80 ? g
81 : {
82 ...g,
83 hooks: g.hooks.map(h => {
84 if (isDone || !same(h, old.hook)) return h
85 isDone = true
86
87 return next.hook
88 }),
89 },
90 )
91
92 return withGroups(s, { ...groupsOf(s), [old.event]: groups })
93}
94
95// The field a hook's work is written in, by type: a command, an http url, otherwise a prompt (prompt, agent).
96export const mainKey = (hook: HookEntry) => (hook.type === 'command' ? 'command' : hook.type === 'http' ? 'url' : 'prompt')
97export const mainText = (hook: HookEntry) => String(hook[mainKey(hook)] ?? '')
98
99// A long one-liner reads by the script it runs: "claude-hook.sh · 3120 chars".
100export const hookLabel = (hook: HookEntry) => {
101 const text = mainText(hook).replace(/\s+/g, ' ').trim()
102 const script = text.length > 90 ? text.match(/[\w.-]+\.(?:sh|py|js|mjs|ts|rb|cmd)\b/g)?.at(-1) : undefined
103
104 return script ? `${script} · ${text.length} chars` : text
105}
106
107// The edited hook keeps its other fields (async, statusMessage…); a new one is a command hook.
108export const hookFromDraft = (base: HookEntry | undefined, text: string, timeout: string): HookEntry => {
109 const hook: HookEntry = { ...(base ?? { type: 'command' }) }
110 hook[mainKey(hook)] = text.trim()
111 if (timeout.trim()) hook.timeout = Number(timeout.trim())
112 else delete hook.timeout
113
114 return hook
115}
116hooks/styles.ts 42 lines1// Output style tab: the styles are plain Markdown files in <config>/output-styles/, the active one is
2// "outputStyle" in <config>/settings.json. Pure parsing/serialising here; the I/O lives in register.tsx.
3import type { Style } from '../types'
4
5const field = (front: string, key: string) => (front.match(new RegExp(`^${key}:[ \\t]*(.*)$`, 'm'))?.[1] ?? '').trim()
6
7// Frontmatter (name, description, keep-coding-instructions) + the instructions body.
8export const parseStyle = (file: string, raw: string): Style => {
9 const text = raw.replace(/\r\n/g, '\n')
10 const m = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/)
11 const front = m?.[1] ?? ''
12
13 return {
14 file,
15 name: field(front, 'name') || file.replace(/\.md$/, ''),
16 description: field(front, 'description'),
17 keep: field(front, 'keep-coding-instructions') !== 'false',
18 body: ((m ? m[2] : text) ?? '').trim(),
19 }
20}
21
22const oneLine = (s: string) => s.replace(/\s*\n\s*/g, ' ').trim()
23
24export const buildStyle = (s: Style) => `---\nname: ${oneLine(s.name)}\ndescription: ${oneLine(s.description)}\nkeep-coding-instructions: ${s.keep}\n---\n\n${s.body.trim()}\n`
25
26// "My style!" -> "my-style": a safe file name from what the person typed.
27export const slugName = (s: string) => s.toLowerCase().normalize('NFKD').replace(/\p{M}/gu, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
28
29// settings.json with `outputStyle` set; the file is plain JSON, written back with the same 2-space layout.
30export const withOutputStyle = (settingsText: string, name: string) =>
31 `${JSON.stringify({ ...(JSON.parse(settingsText || '{}') as Record<string, unknown>), outputStyle: name }, null, 2)}\n`
32
33export const activeStyle = (settingsText: string) => {
34 try {
35 const v = (JSON.parse(settingsText) as { outputStyle?: unknown }).outputStyle
36
37 return typeof v === 'string' ? v : ''
38 } catch {
39 return ''
40 }
41}
42hooks/memories.ts 151 lines1// Memories tab: the current project's auto memory (~/.claude/projects/<slug>/memory) as a graph.
2// Only the open project's directory: other projects' memories live in other slugs and are not read.
3import type { Memory } from '../types'
4
5// Same slug as the engine: any non-alphanumeric character in the path becomes "-".
6export const projectSlug = (root: string) => root.replace(/[^a-zA-Z0-9]/g, '-')
7
8const field = (front: string, key: string) => {
9 const m = front.match(new RegExp(`^\\s*${key}:\\s*(.*)$`, 'm'))
10
11 return (m?.[1] ?? '').trim().replace(/^"(.*)"$/, '$1').replace(/\\"/g, '"')
12}
13
14// Frontmatter (name, description, type — also under `metadata:`) + the [[name]] links from the body.
15export const parseMemory = (file: string, text: string) => {
16 const m = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/)
17 const front = m?.[1] ?? ''
18 const body = (m ? m[2] : text) ?? ''
19 const links = [...new Set([...body.matchAll(/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g)].map(l => (l[1] ?? '').trim()))]
20
21 return {
22 name: field(front, 'name') || file.replace(/\.md$/, ''),
23 type: field(front, 'type') || 'untyped',
24 description: field(front, 'description'),
25 links,
26 body: body.trim(),
27 }
28}
29
30// MEMORY.md: "- [Title](file.md) — hook", one line per memory.
31export const parseIndex = (text: string) => {
32 const out: Record<string, { title: string; hook: string }> = {}
33 for (const m of text.matchAll(/^\s*-\s*\[([^\]]+)\]\(([^)]+\.md)\)\s*(?:[—–-]\s*(.*))?$/gm)) {
34 out[m[2] ?? ''] = { title: m[1] ?? '', hook: (m[3] ?? '').trim() }
35 }
36
37 return out
38}
39
40// Incoming links: who links to each memory.
41export const backlinks = (list: readonly Pick<Memory, 'name' | 'links'>[]) => {
42 const out: Record<string, string[]> = {}
43 for (const m of list) for (const to of m.links) (out[to] ??= []).push(m.name)
44
45 return out
46}
47
48// Which memories a text names (a Bash command, an attachment): by file, as "…/name.md", not as the suffix of another name.
49export const namesIn = (text: string, list: readonly Pick<Memory, 'name' | 'file'>[]) =>
50 list.filter(m => new RegExp(`(^|[/\\s"'(\\[])${m.file.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`).test(text)).map(m => m.name)
51
52// Memories with no link at all, in either direction.
53export const isolated = (list: readonly Pick<Memory, 'name' | 'links'>[]) => {
54 const back = backlinks(list)
55
56 return list.filter(m => m.links.length === 0 && !back[m.name]?.length).map(m => m.name)
57}
58
59// What a memory names in the code, from its backtick spans: a path (`lib/x/y.ex`, `docs/specs/`), a dotted module or
60// function (`Billing.Proration`, `Recurring.MonthlyCost.build/2`) or a snake/Camel identifier (`price_cents`, `MF_BANK`).
61// Prose, commands with spaces and short words are skipped. Checked in the repo at analyze time: a reference that is
62// gone is hard evidence the memory went stale.
63export type Ref = { ref: string; kind: 'path' | 'symbol'; needle: string }
64
65export const refsOf = (body: string): Ref[] => {
66 const out = new Map<string, Ref>()
67 for (const m of body.matchAll(/`([^`\n]{3,80})`/g)) {
68 const ref = (m[1] ?? '').trim()
69 if (/\s/.test(ref) || /^[-$]/.test(ref) || ref.includes('..')) continue
70 if (/^[\w.@-]+(\/[\w.@-]+)+\/?$/.test(ref) && !/\/\d+$/.test(ref)) {
71 out.set(ref, { ref, kind: 'path', needle: ref.replace(/\/$/, '') })
72 continue
73 }
74 // `Mod.Sub.fun/2` → its most specific segment (the longest); `snake_case` / `CamelCase` → itself. A miss is what matters.
75 const name = ref.replace(/\/\d+$/, '').replace(/\(.*\)$/, '')
76 if (!/^[A-Za-z][\w.]*$/.test(name)) continue
77 const needle = name.split('.').filter(Boolean).sort((a, b) => b.length - a.length)[0] ?? ''
78 if (needle.length < 4 || !(/_/.test(needle) || /[a-z][A-Z]|[A-Z][a-z]+[A-Z]/.test(needle) || name.includes('.'))) continue
79 out.set(ref, { ref, kind: 'symbol', needle })
80 }
81
82 return [...out.values()].slice(0, 12)
83}
84
85// The "analyze" verdict on one memory, against the open project: does it still help the model here?
86// `fix` = the body rewritten with what no longer holds dropped or corrected (stale only); `gone` = references not in the code.
87export const VERDICTS = ['relevant', 'stale', 'irrelevant'] as const
88export type Verdict = { verdict: (typeof VERDICTS)[number]; why: string; fix?: string; gone?: string[] }
89
90// The model's reply → verdicts by name. It answers a JSON array; anything around it (a fence, a sentence) is ignored,
91// and only names that exist with a known verdict are kept.
92export const parseVerdicts = (text: string, names: readonly string[]) => {
93 const out: Record<string, Verdict> = {}
94 const json = text.slice(text.indexOf('['), text.lastIndexOf(']') + 1)
95 let rows: unknown = []
96 try {
97 rows = JSON.parse(json)
98 } catch {
99 return out
100 }
101 if (!Array.isArray(rows)) return out
102 for (const r of rows as { name?: unknown; verdict?: unknown; why?: unknown }[]) {
103 const name = String(r?.name ?? '')
104 const verdict = String(r?.verdict ?? '') as Verdict['verdict']
105 if (!names.includes(name) || !VERDICTS.includes(verdict)) continue
106 const fix = typeof r?.fix === 'string' ? r.fix.trim() : ''
107 out[name] = { verdict, why: String(r?.why ?? '').trim(), ...(verdict === 'stale' && fix ? { fix } : {}) }
108 }
109
110 return out
111}
112
113// The memory file with its body replaced and the frontmatter kept as it was.
114export const withBody = (text: string, body: string) => {
115 const m = text.match(/^---\n[\s\S]*?\n---\n?/)
116
117 return `${m ? m[0] : ''}\n${body.trim()}\n`
118}
119
120// MEMORY.md without the line that points at this file.
121export const withoutIndexLine = (text: string, file: string) =>
122 text
123 .split('\n')
124 .filter(l => !new RegExp(`^\\s*-\\s*\\[[^\\]]*\\]\\(${file.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\)`).test(l))
125 .join('\n')
126
127// The memory text with [[target]] (or [[target|alias]]) turned into plain words: the link goes, the sentence stays.
128export const withoutLink = (text: string, target: string) =>
129 text.replace(new RegExp(`\\[\\[\\s*${target.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*(?:\\|([^\\]]*))?\\]\\]`, 'g'), (_, alias?: string) => alias ?? target)
130
131// The graph as Mermaid source, to paste in any viewer (GitHub, mermaid.live): one class per type, a missing target dashed.
132export const toMermaid = (list: readonly Pick<Memory, 'name' | 'type' | 'links'>[], verdicts: Record<string, Verdict> = {}) => {
133 const id = (name: string) => `m_${name.replace(/[^a-zA-Z0-9]/g, '_')}`
134 const names = new Set(list.map(m => m.name))
135 const mark = { relevant: '✓ ', stale: '◐ ', irrelevant: '✗ ' } as const
136 const lines = ['graph LR']
137 for (const m of list) lines.push(` ${id(m.name)}["${verdicts[m.name] ? mark[verdicts[m.name]!.verdict] : ''}${m.name}<br/><small>${m.type}</small>"]:::${m.type}`)
138 for (const m of list)
139 for (const to of m.links) lines.push(names.has(to) ? ` ${id(m.name)} --> ${id(to)}` : ` ${id(m.name)} -.-> ${id(to)}["✗ ${to}"]:::missing`)
140 lines.push(
141 ' classDef user fill:#f5d0fe,stroke:#a21caf',
142 ' classDef feedback fill:#fef08a,stroke:#a16207',
143 ' classDef project fill:#a5f3fc,stroke:#0e7490',
144 ' classDef reference fill:#bfdbfe,stroke:#1d4ed8',
145 ' classDef untyped fill:#e5e7eb,stroke:#6b7280',
146 ' classDef missing fill:#fecaca,stroke:#b91c1c,stroke-dasharray:4',
147 )
148
149 return `${lines.join('\n')}\n`
150}
151hooks/kit.tsx 48 lines1// The Flow tab's design, shared by every tab: a card on top saying where things stand, a NEEDS YOU box with
2// the decisions, foldable sections (title on the left, the summary on the right). Drawing only, like the tabs.
3
4type Ui = { Box: any; Text: any; Button: any } // ponytail: terminal elements, untyped here; register.tsx provides them from $.ui.resolve
5export type Fold = { isOpen: (key: string, byDefault: boolean) => boolean; toggle: (key: string, open: boolean) => void }
6
7export const card = ({ Box }: Ui, color: string, children: any) => (
8 <Box flexDirection="column" borderStyle="round" borderColor={color} paddingX={1}>
9 {children}
10 </Box>
11)
12
13// "▰▰▰▱▱▱▱▱▱▱": how much of the whole is done (or healthy), at a glance.
14export const bar = ({ Text }: Ui, part: number, whole: number) => {
15 const n = whole ? Math.round((part / whole) * 10) : 0
16
17 return (
18 <Text>
19 <Text color="green">{'▰'.repeat(n)}</Text>
20 <Text dimColor>{'▱'.repeat(10 - n)}</Text>
21 </Text>
22 )
23}
24
25export const needsYou = ({ Box, Text }: Ui, summary: string, children: any, hint: string) => (
26 <Box flexDirection="column" borderStyle="round" borderColor="blue" paddingX={1}>
27 <Text bold color="blue">
28 NEEDS YOU <Text dimColor>{summary}</Text>
29 </Text>
30 {children}
31 <Text dimColor wrap="wrap">{hint}</Text>
32 </Box>
33)
34
35export const section = ({ Box, Button }: Ui, fold: Fold, key: string, title: string, byDefault: boolean, body: () => any, aside?: any) => {
36 const open = fold.isOpen(key, byDefault)
37
38 return (
39 <Box key={`sec-${key}`} flexDirection="column">
40 <Box justifyContent="space-between">
41 <Button key={`fold-${key}`} plain label={`${open ? '▾' : '▸'} ${title}`} onPress={() => fold.toggle(key, !open)} />
42 {aside}
43 </Box>
44 {open && body()}
45 </Box>
46 )
47}
48hooks/cost.ts 22 lines1// Cost of a step at its real model. USD per million tokens (claude-api skill, 2026-10-06); cache writes at 1h TTL,
2// as Claude Code runs. Haiku costs 5x above 100K prompt tokens. On a subscription this is a measure, not the bill.
3export type Tier = 'opus' | 'sonnet' | 'haiku'
4
5export const PRICES: Record<Tier, { input: number; output: number; write: number; read: number }> = {
6 opus: { input: 4, output: 20, write: 8, read: 0.2 },
7 sonnet: { input: 2, output: 10, write: 4, read: 0.2 },
8 haiku: { input: 0.1, output: 0.5, write: 0.2, read: 0.01 },
9}
10
11export const tierOf = (model: string): Tier | undefined => /opus|sonnet|haiku/i.exec(model)?.[0].toLowerCase() as Tier | undefined
12
13type Usage = { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
14
15export const costOf = (tier: Tier, u: Usage) => {
16 const p = PRICES[tier]
17 const prompt = u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
18 const long = tier === 'haiku' && prompt > 100_000 ? 5 : 1
19
20 return (long * (u.input_tokens * p.input + u.cache_creation_input_tokens * p.write + u.cache_read_input_tokens * p.read + u.output_tokens * p.output)) / 1e6
21}
22