What a session left behind and a safety net: a /session pane with files changed, commits, denied calls and the longest gap, a retro band on the next start, a…

Shows what a Claude Code session left behind (files changed, commits, denied calls, longest gap between tool calls), shows it again as a band on your next start, lists stray claude -p children and stops one safely, guards dangerous commands and secret writes, keeps /memo notes, recaps before compacting at a % you set, keeps that recap for /handoff, /last-recap and /lessons, times tasks and shows the cost, shows every open session on one /board (with its harness, graph and teams runs), tells the other sessions of a repo when main moves, warns when an Agent call names no model, and stops unfinished agents with /reap. Version 0.5.6. Requires Claude Code 2.1.292+ (hooks module). It needs nothing else from this marketplace.
/plugin install session@newkayak12-claude-skills
trophy rides along. From this version, the first interactive session after you install or update this plugin installs trophy (achievements) once, in user scope, if you don't have it. Nothing is sent until you say yes; uninstalling trophy is respected (it is never reinstalled). To opt out beforehand:
mkdir -p ~/.claude/plugins/.newkayak12-trophy-ride.done. Needssh(Windows without one is not covered).
/session opens one pane with two views, switched by the buttons or keys 1 / 2:
[1]: files Claude edited or wrote this session (with +added -deleted from git diff --numstat), commits made (hash and subject), denied tool calls (tool and reason), and the longest gap between two tool calls in one turn.[2]: claude -p children still running below this session, one row each: pid, command, age, [stop]. A line points to /tasks for background shells and subagents; this plugin does not list those. For the full diff of what changed, use /diff./session retro opens the Retro view; if nothing happened yet in this session it shows the summary the last session left.
When a session ends, the summary is saved (also for claude -p runs). The next interactive start shows one row above the prompt: last session: 4 files, 2 commits, 1 denied, longest gap 6m12s with [Retro] and [dismiss]. Dismissing deletes the saved summary. Nothing is written to your repository.
[stop] sends one SIGTERM to one process, after these checks:
No kill -9, no process groups, no pattern kills, no "stop all". A refusal shows a toast and sends nothing; a process that already ended just clears its row.
A wrapper shell and its claude -p child show as one row; [stop] targets the inner claude -p.
The plugin keeps one status line: ⧗ N agent(s) · /reap while this session has unfinished agents, ⧗ N claude -p child(ren) running while children are alive (both updated at the end of each turn), and guard: N denied as soon as the guard denies something. The parts that apply are joined with · , after the task and before the cost. The line is cleared only when all are empty; headless runs show nothing.
The status line after the guard denied a .env write: guard: 1 denied · $0.11 · seven_day 35%.
A claude -p child started in the background: ⧗ 1 claude -p child(ren) running.
Before a Bash command or a Write/Edit runs, the guard checks it against a few rules and asks you first (or blocks, see Modes). It works in every repo, including bypass-permissions sessions.
hard-reset rule: the guard asks Run / Cancel before git reset --hard HEAD.
Cancel on a secret-write ask: the toast, and the reason the model gets back.
| Rule | Fires on | Default |
|---|---|---|
recursive-delete | rm with recursive and force flags aimed at /, ~, $HOME, the repo root, a parent of the cwd, or a glob of those | ask |
force-push-protected | git push with -f, --force, --force-with-lease or a +branch refspec to main, master, trunk, the remote default branch, or guard_extra_protected_branches; a bare force push counts when the current branch is protected | ask |
hard-reset | git reset --hard, git clean -f (not -n) | ask |
worktree-dirty-remove | git worktree remove --force on a worktree with uncommitted changes | block |
secret-write | Write/Edit to .env (not .env.example), *.pem, *.key, id_rsa and the like, credentials under .aws, .ssh and similar, or guard_secret_paths | ask |
running-script | Write/Edit to a .sh file a process is running right now | block |
Commands are split before checking, so cd x && rm -rf / is caught and grep -r "rm -rf" . or rm -rf node_modules is not. A command it cannot parse passes.
Set guard_mode in /config:
confirm (default): rules marked ask show Run / Cancel; block rules deny with the reason.deny: ask rules also deny, with no question.off: nothing is checked. This is the escape hatch.Bypass means no native prompts, not no safety net: the guard still asks under bypass. Headless runs (claude -p) have no one to ask, so every rule passes and nothing is logged.
Not a sandbox. python -c, find -delete, dd, shell aliases and scripts that do the same thing are not checked. Secrets are matched by path only; the content of a write is never read.
/session-denials opens a pane of denied calls, newest first, under a header with the guard mode and the stopped count (confirm mode · 6 stopped). Each stop is one row: the local time (HH:MM), the tool, what was called, the rule that stopped it, its source and a copy button, which shows the /permissions rule to add. The source reads by its mark and colour before its word: ✘ (red) guard, ○ (dim) declined, ● (amber) native. A call too long for the pane is cut with …. Esc, q, or /session-denials again closes it. Each entry holds the tool, a redacted call (tokens, NAME=value pairs and URL passwords are masked; a file call stores only its path), the reason, the guard's rule id and the source. It lives in plugin storage, newest 200, and nothing is written to your repository. log_enabled turns it off. It also records native permission denials it saw; your own "No" in a native dialog is not logged.
/session-denials: five stops, one row each, newest first. After a toast or a refused call it tells you what was stopped, when, by which rule and from which source; copy shows the rule to allow it.
/memo keeps short notes that ride along with your next prompt, so the model sees them again after /compact or /clear.
| Command | Does |
|---|---|
/memo | open the Memo pane: a header with the note count, the size against the cap (<n>/1200 chars) and when the notes last went out with this conversation (— before the first send), then one note per line: its number, scope badge (global or project), text, age (today, 2d), right-aligned in its own column, which turns yellow at 14 days (a hint to move the note to CLAUDE.md). Long text is cut with …; +N not sent counts stored notes the caps leave out. Esc, q, or /memo again closes it |
/memo add [--global] <text> | add a note (project by default) |
/memo list | open the Memo pane (headless: print the notes) |
/memo rm <n> | remove note n as numbered in list |
/memo clear [--global] | clear the project notes, or the global ones |
The Memo pane: one note per line with its scope badge and age (the age turns yellow at 14 days), the size against the cap and the last send in the header (+N not sent shows when the caps leave a note out). Open it before you add or remove a note to see what the model carries.
Two scopes: project (keyed by the repo root) and global. Caps count both together: 8 notes, 280 characters each, 1200 in total; an add past a cap is refused with the reason. A note is stale at 14 days. The injected block is a fixed header plus [global] notes then [project] notes. It is sent once per conversation and again after /compact or /clear, or after any change, from the next prompt.
Not CLAUDE.md, not auto-memory: notes are not files, are never written to your repository, and are not shared. Put lasting rules in CLAUDE.md; use a memo for something you want pinned for now.
At a context % you choose, the session is first asked for a recap built around the next steps (goal, direction, what was in progress with its file:line, decisions, open items, corrections), then compacted with that recap as the summary itself: compact adds only what the recap lacks, so nothing is carried twice and finished work drops out.
| Command | What it does |
|---|---|
/smart-compact | print the current threshold (default 70%), the last check, and this process's counts |
/smart-compact <10-95> | set it; 60 and 60% both work |
/smart-compact log | the last 10 checks, newest first: 23% vs 10% → recapping → compacted |
The same value is the Smart compact threshold (%) row in /config. It runs after a main-loop turn that ended with an answer, and usage is also checked between tool calls inside a long turn; if compact is rejected mid-turn, it waits for the turn to end. Interactive sessions only; never for subagents. If the recap fails it does nothing and the built-in auto-compact takes over. Set it below the auto-compact point, or auto-compact fires first: the % is of the model's whole window as the status line shows it, so on a 1M window 70% is 700k tokens.
Each check of an interactive main-loop turn is kept in a 50-entry log (raw %, threshold, decision, outcome) that /smart-compact log prints. Subagent and headless turns are only counted in the process, shown on /smart-compact, which also shows log write errors.
Every recap (from smart-compact or /handoff) is kept for this project, the last one only. A start offers another session's recap in a band once: after Recap or dismiss it is not offered again, and a session never gets a band for the recap it wrote itself (a smart-compact's own recap).
| Command | What it does |
|---|---|
/handoff | make a recap now, keep it, open it on the board's Recap tab |
/handoff <session> | same, and send it to that session (a peer session name or id) |
/last-recap | open the project's last recap (under 7 days old) on the board's Recap tab |
/lessons | open the "corrected more than once" lines collected from recaps (newest 20) on the board's Lessons tab; /lessons clear empties them |
In a headless run (claude -p) these commands print their text instead. On the next start a band shows last recap of this project, <age> with a Recap button that opens the board's Recap tab. Lessons are never written anywhere for you: move the ones worth keeping to CLAUDE.md yourself.
/smart-compact 60 then /handoff: the six-part recap, printed and kept.
/task <name> starts a task, /task shows it, /task done stops it, /task log opens today's totals by name on the board's Today tab (headless: prints them). The status line shows ⏱ <name> 12m while it runs, refreshed each minute; starting a new task finishes the old one.
After each turn the status line shows the session's cost and the highest rate-limit use ($1.23 · 5h 42%). Set Cost budget (USD) in /config for one toast when the cost reaches it (0 = off).
Cost budget set to $0.01: the toast after the first turn, and the cost in the status line.
Off by default (Prompt hint in /config). When on, a typed prompt of 20 characters or less that asks for work (fix/add/만들/고쳐…) and names no path, code or check gets one toast asking for scope or a check, at most every 10 minutes. The prompt itself is never changed.
Prompt hint on: add logging gets the scope/check toast; the prompt still runs.
/board opens one pane for every open interactive session that has this plugin, the default place to see what the plugin knows. Tabs: Sessions [1], Recap [2], Lessons [3], Today [4], Worktrees [5] (/board worktrees); [r] refreshes the sessions or worktrees.
Each session row shows its branch, context %, cost, running task and three cells for the runs in its folder, in the words and marks of each plugin's own pane: harness ● running 1/3, graph ○ blocked 4/9, teams ✔ finished 3/3, or – when there is none. A live run names the command that shows its detail in that session (/harness-status, /graph-status, /teams-status). The board reads the run files itself, so it needs none of those plugins.
A session writes its row at start and after each turn, and removes it when it ends; a row not updated for 30 minutes is marked idle, and one older than a day is dropped. Rows are kept in this plugin's store on your machine only.
One row per git worktree list --porcelain entry of this repo: branch (or detached), uncommitted count (ignored files not counted), merged into main, age of the last commit, and in use when an open board session's folder is inside it. A Clean button appears only on a row that is not the main checkout, is merged, has 0 uncommitted changes, is not in use and whose path exists; other rows say why (unmerged, 3 changes, in use, main, missing). Clean asks Clean / Cancel, re-reads the row, then: copies each <worktree>/.harness-run/<name> to the main checkout's .harness-run/<name> (a name already there, or any copy failure, stops the clean before anything is removed), runs git worktree remove (never --force), then git branch -d (never -D; a refusal is reported and the worktree stays removed). One toast summarises the steps. Interactive sessions only.
/reap: lists this session's unfinished agents (pending, running, waiting, idle) and its claude -p processes, asks Reap / Cancel, then stops the agents with TaskStop (children of a stopped agent are skipped) and sends SIGTERM to the claude -p processes, never to their wrapper shells. It kills no process when this session's own process cannot be confirmed. The result is printed line by line (stopped:, killed:, failed:) and the status line is refreshed. Interactive sessions only./reap-list: one pane of what a teams run left behind in this repo: claude -p drivers, judges and daemon.mjs processes, and git worktree list entries. Each row says whether it is finished, live or other (a process of no task here) and, for a worktree, removable or keep with the reason (merged into main, task finished, unmerged, uncommitted changes, its task is still running, ...). A task counts as finished when its ledger's last daemon_done / clean event says so, or, with no such event, when its 80-report.md exists; a later tm_retry makes it live again. Reap N asks Reap / Cancel, then sends SIGTERM to the finished processes and runs git worktree remove on the removable worktrees; refresh (r) lists again, q or /reap-list again closes it. It never touches: the main checkout, a bare or locked worktree, a worktree with uncommitted changes (or one whose state cannot be read), one this session runs inside, one whose task is still running; this session's process, everything above it, the nearest claude (the engine) and the live daemon and drivers of the task it runs in, and a process whose pid was reused or whose command changed since it was listed. No --force, no git branch -D, no pkill/killall, no SIGKILL. Interactive sessions only; /reap above is unchanged. The same listing is a CLI that needs no mod: node session/scripts/reap.mjs --list [--json] prints it (proc and tree lines, or the items as JSON), node session/scripts/reap.mjs --reap [--dry-run] stops and removes (--dry-run prints would stop: / would remove: and changes nothing; otherwise stopped:, removed:, skipped:, failed:). Exit 0 when nothing failed, 1 when a stop or remove failed, 2 on a bad argument.Agent call with no model (and not a fork) makes the subagent inherit the parent's model. Set Agent model guard (agent_model_guard) in /config: toast (default) warns and lets the call run, deny blocks it, off does nothing. Only the call's own model argument is seen, not one pinned in the agent's definition.When a git push to main goes through in one session (origin main, HEAD:main, x:main, or a plain push while on main), every other open session of the same repository that was active in the last 30 minutes gets a message: main moved to <sha> … Fetch before editing or bumping versions. At most one message per session every 2 minutes; this session gets a toast main moved: told N of M. Headless runs send nothing.
0.9.3: every pane, band and toast draws on terminal, desktop, mobile and vscode; /session answers in text where no pane draws; memo and hint toasts only when a surface exists.0.9.2: smart-compact computes its % from the tokens and the context window, the formula behind the status line's used_percentage; /smart-compact shows the current %, the threshold and the token count.0.9.1: /reap-list also reaps orphan daemons whose task lives under another task root, and hides the session that runs it.0.9.0: /reap-list lists the teams drivers, daemons, judges and worktrees this machine still has for the repo, with age and live/finished, and reaps the finished ones in one action (by pid, never an unmerged branch); node session/scripts/reap.mjs --list|--reap does the same without the mod.0.8.1: smart-compact also checks usage between tool calls, so one long turn compacts at the threshold before the next answer; a failed compact waits for the turn to end and logs its last error.0.8.0: the Memo pane shows each note on one line with its scope and its age in a right-aligned column, old notes by colour; the Guard pane shows one aligned row per stop (time · tool · what · rule · source), a guard deny, a decline and a native stop each with its own mark and colour, and closes on q; both stay on one line at 110 columns, long text ends in ….0.7.0: start_band (off default, recap, retro, both) picks what the band shows on a new session; /board points to the plugins' -status panes.0.6.0: /board has a Worktrees tab (key 5, /board worktrees) with a guarded Clean button for merged worktrees.0.5.7: Codex uses an explicit empty, schema-compatible hook overlay because Session's UI hook module is Claude-only; Claude behavior is unchanged and Codex no longer fails plugin initialization. The overlay also leaves out the SessionStart trophy install hook on purpose (trophy is Claude-only).0.5.6: the main-moved message reads the pushed HEAD, not origin/main — with a remote not named origin it was sent empty and every repeat was dropped as a duplicate.0.5.5: the recap keeps only what the next steps need (a new In progress section; finished work as one line), and compact takes it as the summary instead of writing its own beside it.0.5.4: the recap band is offered once per recap — Recap or dismiss is remembered, and a session's own smart-compact recap never raises it.0.5.3: the no-model toast is one short line naming the Agent call, e.g. ⚠ no model: "rb12 runner" inherits the parent model.0.5.2: the /board pane closes with Esc, [q], or a bare /board while it is open.0.5.1: /reap shows its result lines in a pane and returns one line (Ink rule).0.5.0: absorbs mods' agent model guard, agent count, /reap. /recap is now /last-recap: Claude Code 2.1.292 has a built-in /recap, and the failed registration dropped /task, /reap, /board and /session. Commands now register one by one, so one refused name drops only itself./harness-status.[stop], the retro band, guard asks in auto and bypass mode, and /memo after /clear. The desktop Code tab is not checked yet.hooks/mod.tsx 913 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import {
5 addCommit, addDeny, addFile, addStep, emptyLedger, endTurn, fmtMs, isEmpty, leftSomething, parseNumstat, statOf, stepSpan, summarize,
6} from './ledger.ts'
7import type { Ledger, Summary } from './ledger.ts'
8import { checkKill } from './kill.ts'
9import type { Verdict } from './kill.ts'
10import { ancestorsOf, fmtAge, matchOrphans, parsePs, PS_ARGV } from './procs.ts'
11import type { Row } from './procs.ts'
12import { costText, statusLine } from './status.ts'
13import { isFresh, fmtAgo, lessonsKey, recapKey } from './recap.ts'
14import type { Recap } from './recap.ts'
15import {
16 BOARD_OPEN, BOARD_PANE, brokerCell, cellText, DETAIL, harnessCell, IDLE_MS, liveRows, mainMovedText, peersOf,
17 isInUse, parseWorktrees, pushesMain, ROW_MAX_AGE_MS, ROW_PREFIX, rowKey, rowText, SEND_GAP_MS, shortId, wtReason, wtText,
18} from './board.ts'
19import type { BoardRow, BoardTab, Cell, Runs, WtRow } from './board.ts'
20import { appendLog, dayOf, parseTask, TASK_KEY, TASK_LOG_KEY, taskStatus, todayLines } from './timer.ts'
21import type { Done, Task } from './timer.ts'
22import { DENIALS_KEY, register as registerGuard } from './guard.tsx'
23import { register as registerMemo } from './memo.tsx'
24import { register as registerHint } from './hint.ts'
25import { midTurnCheck, register as registerCompact, turnEnd } from './compact.tsx'
26import { aliveCount, register as registerAgents } from './agents.tsx'
27
28const tab = atom({ plugin: 'session', key: 'tab' } as const, 'retro' as 'retro' | 'orphans')
29const band = atom({ plugin: 'session', key: 'band' } as const, false)
30const ledger = atom({ plugin: 'session', key: 'ledger' } as const, emptyLedger())
31
32const statsAtom = atom({ plugin: 'session', key: 'stats' } as const, {} as Record<string, string>)
33
34const lastAtom = atom({ plugin: 'session', key: 'last' } as const, null as Summary | null)
35// The project's last recap, when it is under 7 days old: the band offers it once per start.
36const recapAtom = atom({ plugin: 'session', key: 'recap' } as const, null as { ts: number } | null)
37
38const boardTab = atom({ plugin: 'session', key: 'boardTab' } as const, 'sessions' as BoardTab)
39const boardRows = atom({ plugin: 'session', key: 'boardRows' } as const, [] as BoardRow[])
40const boardWorktrees = atom({ plugin: 'session', key: 'boardWorktrees' } as const, [] as WtRow[])
41
42const PANE = 'session'
43const LAST_KEY = 'session.last'
44
45const recapSeenKey = (root: string) => `recap.seen:${root}`
46
47// Hides the band and remembers the recap, so no later start or compact offers it again.
48async function dismissRecap($: any, ts: number) {
49 await update($, recapAtom, () => null)
50 try {
51 await $.store.set(recapSeenKey(await $.session.root()), ts)
52 } catch {}
53}
54
55async function openPane($: any) {
56 await refreshStats($)
57 await pollOrphans($)
58 await $.ui.open({ id: PANE, title: 'Session' })
59}
60
61// One `git diff --numstat` for the touched files, never in a draw. No git or a slow one: keep what was there.
62async function refreshStats($: any) {
63 try {
64 const files = (await read($, ledger)).files
65 if (files.length === 0) return
66 const r = await $.process.run(['git', 'diff', '--numstat', '--', ...files], { timeoutMs: 5000 })
67 if (r.exitCode === 0) await update($, statsAtom, () => parseNumstat(r.stdout))
68 } catch {}
69}
70
71const orphansAtom = atom({ plugin: 'session', key: 'orphans' } as const, [] as Row[])
72const engineAtom = atom({ plugin: 'session', key: 'engine' } as const, 0)
73
74// Windows has no `ps -o lstart`: the OS-process section is hidden and no process is run for it.
75const isWindows = async ($: any) => {
76 try {
77 return (await $.env.get('OS')) === 'Windows_NT'
78 } catch {
79 return false
80 }
81}
82
83// The engine pid is the parent of `sh -c 'echo $PPID'`; asked once, kept in state.
84async function engineOf($: any): Promise<number> {
85 let pid = await read($, engineAtom)
86 if (pid > 0) return pid
87 const r = await $.process.run(['sh', '-c', 'echo $PPID'], { timeoutMs: 3000 })
88 pid = Number(String(r.stdout).trim())
89 if (!Number.isInteger(pid) || pid <= 0) return 0
90 await update($, engineAtom, () => pid)
91 return pid
92}
93
94// One ps pass at turn end and pane open, never in a draw. Failure keeps the previous list.
95async function pollOrphans($: any) {
96 try {
97 if (await isWindows($)) return await update($, orphansAtom, () => [])
98 const engine = await engineOf($)
99 if (engine === 0) return
100 const ps = await $.process.run([...PS_ARGV], { timeoutMs: 5000 })
101 if (ps.exitCode !== 0) return
102 await update($, orphansAtom, () => matchOrphans(parsePs(ps.stdout), engine))
103 } catch {}
104}
105
106// A fresh ps and the verdict on `seen` against it. The cached rows are never trusted.
107async function judge($: any, seen: Row): Promise<Verdict> {
108 if (await isWindows($)) return { ok: false, reason: 'stopping is off on Windows' }
109 const engine = await engineOf($)
110 const ps = await $.process.run([...PS_ARGV], { timeoutMs: 5000 })
111 if (ps.exitCode !== 0) return { ok: false, reason: 'could not read the process table' }
112 const rows = parsePs(ps.stdout)
113 return checkKill(seen, rows, engine, ancestorsOf(rows, engine))
114}
115
116// One pid per press, SIGTERM only: judge, ask with the full command, judge again, then the signal.
117// A refusal toasts the reason and sends nothing; a pid that is already gone just clears its row.
118async function stopOrphan($: any, seen: Row) {
119 const say = (text: string) => void $.ui.toast(text, { timeoutMs: 6000 })
120 const refuse = async (v: Extract<Verdict, { ok: false }>) => {
121 if (v.gone) await update($, orphansAtom, rows => rows.filter(r => r.pid !== seen.pid))
122 say(`not stopped: ${v.reason}`)
123 }
124 try {
125 const before = await judge($, seen)
126 if (!before.ok) return await refuse(before)
127 const answer = await $.ui.ask(`Stop pid ${seen.pid}?\n${seen.cmd}`, ['Stop', 'Cancel']).catch(() => undefined)
128 if (answer !== 'Stop') return
129 const after = await judge($, seen)
130 if (!after.ok) return await refuse(after)
131 const r = await $.process.run(['kill', '-TERM', String(after.pid)], { timeoutMs: 5000 })
132 // exit 1 with "No such process" means it ended on its own: that is success
133 if (r.exitCode !== 0 && !/no such process/i.test(String(r.stderr))) say(`not stopped: ${String(r.stderr).trim().slice(0, 120)}`)
134 await pollOrphans($)
135 } catch {
136 say('not stopped: something went wrong, nothing was sent')
137 }
138}
139
140// The running /task, read from the store each time: a reload or another window sees the same task.
141const runningTask = async ($: any): Promise<Task | undefined> => {
142 try {
143 return ((await $.store.get(TASK_KEY)) as Task | undefined) ?? undefined
144 } catch {
145 return undefined
146 }
147}
148
149const paintTask = async ($: any) => {
150 $.ui.status(statusLine({ task: taskStatus(await runningTask($), (await $.clock.now()) as number) }))
151}
152
153// Repaints the elapsed minutes while a task runs; one loop per load (a reload drops the old one).
154let isTicking = false
155const tick = async ($: any) => {
156 if (isTicking) return
157 isTicking = true
158 try {
159 while (await runningTask($)) {
160 await $.clock.sleep(60_000)
161 await paintTask($)
162 }
163 } finally {
164 isTicking = false
165 }
166}
167
168// One toast per load when the session's cost first reaches the /config budget.
169let isBudgetToasted = false
170
171// ---- the board: this session's row in the store, every session's rows in the pane ----
172
173type Ent = { name: string; kind: string; size: number; mtimeMs: number }
174const MAX_READ = 4 * 1024 * 1024 // $.fs.read rejects more
175const RUN_FILE = /^[0-9a-f-]+\.json$/ // graph's FILE: not the store's .tmp renames
176
177const listOf = async ($: any, path: string): Promise<Ent[]> => {
178 try {
179 return (await $.fs.list(path)) as Ent[]
180 } catch {
181 return []
182 }
183}
184const jsonOf = async ($: any, path: string, ent?: Ent): Promise<any> => {
185 if (ent !== undefined && ent.size > MAX_READ) return undefined
186 try {
187 return JSON.parse(await $.fs.read(path))
188 } catch {
189 return undefined
190 }
191}
192const gitOut = async ($: any, args: string[]): Promise<string> => {
193 try {
194 const r = await $.process.run(['git', ...args], { timeoutMs: 3000 })
195 return r.exitCode === 0 ? String(r.stdout).trim() : ''
196 } catch {
197 return ''
198 }
199}
200
201// harness/hooks/mod.tsx scanRun(), cut to what the board shows: the newest live fallback run, else
202// the newest; done/total = subgoals whose result.json passed / the spec's and the folders' subgoals.
203async function harnessRun($: any, now: number): Promise<Cell | undefined> {
204 const RUNS = '.harness-run'
205 const cands: { dir: string; time: number; finished: boolean; subs: { name: string; files: Ent[] }[] }[] = []
206 for (const d of await listOf($, RUNS)) {
207 if (d.kind !== 'dir' || d.name === 'broker') continue
208 const dir = `${RUNS}/${d.name}`
209 const files = await listOf($, dir)
210 const subs: { name: string; files: Ent[] }[] = []
211 if (files.some(f => f.name === 'subgoals' && f.kind === 'dir')) {
212 for (const s of await listOf($, `${dir}/subgoals`)) if (s.kind === 'dir') subs.push({ name: s.name, files: await listOf($, `${dir}/subgoals/${s.name}`) })
213 }
214 const all = [...files, ...subs.flatMap(s => s.files)].filter(f => f.kind === 'file')
215 cands.push({ dir, subs, time: Math.max(0, ...all.map(f => f.mtimeMs)), finished: files.some(f => f.name === '05-report.md') })
216 }
217 const newest = (list: typeof cands) => [...list].sort((a, b) => b.time - a.time)[0]
218 const pick = newest(cands.filter(c => harnessCell({ ...c, done: 0, total: 0 }, now).live)) ?? newest(cands)
219 if (pick === undefined) return undefined
220 const spec = await jsonOf($, `${pick.dir}/02-goal-spec.json`)
221 const specIds = Array.isArray(spec?.subgoals) ? spec.subgoals.map((s: any) => String(s?.id ?? '')).filter(Boolean) : []
222 const ids = new Set<string>([...specIds, ...pick.subs.map(s => s.name)])
223 let done = 0
224 for (const s of pick.subs) {
225 const ent = s.files.find(f => f.name === 'result.json')
226 if (ent && (await jsonOf($, `${pick.dir}/subgoals/${s.name}/result.json`, ent))?.passed === true) done++
227 }
228 return harnessCell({ finished: pick.finished, time: pick.time, done, total: ids.size }, now)
229}
230
231// graph/hooks/mod.tsx tick(): the newest run file of a broker folder (graph's, or teams').
232async function brokerRun($: any, dir: string, now: number): Promise<Cell | undefined> {
233 const newest = (await listOf($, dir)).filter(f => f.kind === 'file' && RUN_FILE.test(f.name)).sort((a, b) => b.mtimeMs - a.mtimeMs)[0]
234 if (newest === undefined) return undefined
235 const run = await jsonOf($, `${dir}/${newest.name}`, newest)
236 return run === undefined ? undefined : brokerCell(run, newest.mtimeMs, now)
237}
238
239async function scanRuns($: any, now: number): Promise<Runs> {
240 const runs: Runs = {}
241 const harness = await harnessRun($, now)
242 const graph = await brokerRun($, '.harness-run/broker/runs', now)
243 const teams = await brokerRun($, '.teams_output/broker/runs', now)
244 if (harness) runs.harness = harness
245 if (graph) runs.graph = graph
246 if (teams) runs.teams = teams
247 return runs
248}
249
250// This session's row, written at start and turn end. Interactive main sessions only; never throws.
251async function heartbeat($: any): Promise<BoardRow | undefined> {
252 try {
253 if ((await $.session.surfaces()).length === 0) return undefined
254 const now = (await $.clock.now()) as number
255 const sessionId = String(await $.session.id())
256 const usage = await $.session.usage().catch(() => undefined)
257 const row: BoardRow = {
258 sessionId,
259 root: String(await $.session.root()),
260 branch: await gitOut($, ['rev-parse', '--abbrev-ref', 'HEAD']),
261 repo: await gitOut($, ['rev-parse', '--path-format=absolute', '--git-common-dir']),
262 percent: Math.round(usage?.context?.percent ?? 0),
263 usd: usage?.cost?.usd ?? 0,
264 task: (await runningTask($))?.name ?? '',
265 runs: await scanRuns($, now),
266 ts: now,
267 }
268 await $.store.set(rowKey(sessionId), row)
269 return row
270 } catch {
271 return undefined
272 }
273}
274
275// Every session's row; a row past a day is deleted on the way.
276async function allRows($: any): Promise<BoardRow[]> {
277 const now = (await $.clock.now()) as number
278 const rows: BoardRow[] = []
279 try {
280 for (const k of (await $.store.keys()) as string[]) {
281 if (!k.startsWith(ROW_PREFIX)) continue
282 const r = (await $.store.get(k)) as BoardRow | undefined
283 if (r === undefined || typeof r.ts !== 'number' || now - r.ts >= ROW_MAX_AGE_MS) await $.store.delete(k)
284 else rows.push(r)
285 }
286 } catch {}
287 return rows
288}
289
290async function refreshBoard($: any) {
291 await heartbeat($)
292 const me = String(await $.session.id())
293 const rows = await allRows($)
294 const now = (await $.clock.now()) as number
295 await update($, boardRows, () => liveRows(rows, now, me))
296}
297
298// ---- the Worktrees tab: facts from git, never in a draw; Clean copies .harness-run, then removes ----
299
300// Exit code and trimmed stdout of one git command; exit -1 when it could not run.
301const gitRun = async ($: any, args: string[], timeoutMs = 5000): Promise<{ code: number; out: string }> => {
302 try {
303 const r = await $.process.run(['git', ...args], { timeoutMs })
304 return { code: r.exitCode, out: String(r.stdout).trim() }
305 } catch {
306 return { code: -1, out: '' }
307 }
308}
309
310async function scanWorktrees($: any): Promise<WtRow[]> {
311 const list = parseWorktrees((await gitRun($, ['worktree', 'list', '--porcelain'])).out)
312 const roots = liveRows(await allRows($), (await $.clock.now()) as number, '').map(r => r.root)
313 const rows: WtRow[] = []
314 for (const [i, w] of list.entries()) {
315 const exists = (await $.process.run(['test', '-d', w.path], { timeoutMs: 3000 }).catch(() => ({ exitCode: 1 }))).exitCode === 0
316 const status = exists ? await gitRun($, ['-C', w.path, 'status', '--porcelain']) : { code: -1, out: '' }
317 const age = exists ? await gitRun($, ['-C', w.path, 'log', '-1', '--format=%ct', 'HEAD']) : { code: -1, out: '' }
318 const merged = w.head !== '' && (await gitRun($, ['merge-base', '--is-ancestor', w.head, 'main'])).code === 0
319 rows.push({
320 ...w,
321 isMain: i === 0,
322 exists,
323 uncommitted: status.code === 0 ? status.out.split('\n').filter(l => l !== '').length : -1,
324 merged,
325 lastCommitMs: Number(age.out) > 0 ? Number(age.out) * 1000 : 0,
326 inUse: isInUse(w.path, roots),
327 })
328 }
329 return rows
330}
331
332async function refreshWorktrees($: any) {
333 const rows = await scanWorktrees($)
334 await update($, boardWorktrees, () => rows)
335}
336
337// Ask, re-read the row, then: copy each .harness-run/<name> to the main checkout (a name already there, or
338// any copy failure, stops the clean), `git worktree remove` (no --force), `git branch -d` (no -D).
339async function cleanWorktree($: any, seen: WtRow) {
340 const say = (text: string) => void $.ui.toast(text, { timeoutMs: 8000 })
341 try {
342 const answer = await $.ui.ask(`Clean ${seen.path}?\nbranch ${seen.branch || '(detached)'}, merged, no changes`, ['Clean', 'Cancel']).catch(() => undefined)
343 if (answer !== 'Clean') return
344 const fresh = await scanWorktrees($)
345 const row = fresh.find(r => r.path === seen.path)
346 const why = row === undefined ? 'gone' : wtReason(row)
347 if (row === undefined || why !== '') return say(`not cleaned: ${why}`)
348 const main = fresh.find(r => r.isMain)?.path
349 if (main === undefined) return say('not cleaned: main checkout not found')
350 const steps: string[] = []
351 const src = `${row.path}/.harness-run`
352 const names = (await listOf($, src)).map(e => e.name)
353 if (names.length > 0) {
354 const taken = new Set((await listOf($, `${main}/.harness-run`)).map(e => e.name))
355 const clash = names.find(n => taken.has(n))
356 if (clash !== undefined) return say(`not cleaned: .harness-run/${clash} already exists in main; nothing removed`)
357 const mk = await $.process.run(['mkdir', '-p', `${main}/.harness-run`], { timeoutMs: 5000 }).catch(() => ({ exitCode: 1 }))
358 if (mk.exitCode !== 0) return say('not cleaned: could not create .harness-run in main; nothing removed')
359 for (const n of names) {
360 const cp = await $.process.run(['cp', '-R', `${src}/${n}`, `${main}/.harness-run/${n}`], { timeoutMs: 60000 }).catch(() => ({ exitCode: 1 }))
361 if (cp.exitCode !== 0) return say(`not cleaned: copying .harness-run/${n} failed; nothing removed`)
362 }
363 steps.push(`copied ${names.length} .harness-run`)
364 }
365 const rm = await gitRun($, ['-C', main, 'worktree', 'remove', row.path], 60000)
366 if (rm.code !== 0) return say(`not cleaned: worktree remove refused${steps.length ? ` (${steps.join(', ')})` : ''}`)
367 steps.push('worktree removed')
368 if (row.branch !== '') {
369 const br = await gitRun($, ['-C', main, 'branch', '-d', row.branch])
370 steps.push(br.code === 0 ? `branch ${row.branch} deleted` : `branch ${row.branch} kept (-d refused)`)
371 }
372 say(steps.join(' · '))
373 } catch {
374 say('not cleaned: something went wrong')
375 } finally {
376 await refreshWorktrees($).catch(() => {})
377 }
378}
379
380async function openBoard($: any, to: BoardTab) {
381 await update($, boardTab, () => to)
382 if (to === 'sessions') await refreshBoard($)
383 if (to === 'worktrees') await refreshWorktrees($)
384 await $.ui.open(BOARD_OPEN)
385}
386
387// After a push to main: one message to each other session of this repo seen in the last 30 min,
388// at most one per peer per 2 min. A peer that is gone loses its row.
389const lastSent = new Map<string, number>()
390async function tellMainMoved($: any) {
391 if ((await $.session.surfaces()).length === 0) return
392 const me = await heartbeat($)
393 if (me === undefined) return
394 const now = (await $.clock.now()) as number
395 const peers = peersOf(await allRows($), me, now).filter(p => now - (lastSent.get(p.sessionId) ?? 0) >= SEND_GAP_MS)
396 if (peers.length === 0) return
397 // HEAD is the main just pushed; origin/main is absent when the remote has another name
398 const sha = await gitOut($, ['rev-parse', '--short', 'HEAD'])
399 const subject = await gitOut($, ['log', '-1', '--format=%s', 'HEAD'])
400 const text = mainMovedText(sha, subject, shortId(me.sessionId))
401 let told = 0
402 for (const p of peers) {
403 const sent = await $.session.send({ to: { sessionId: p.sessionId }, text }).catch((err: unknown) => ({ isDelivered: false, reason: String(err) }))
404 if (sent.isDelivered) {
405 told++
406 lastSent.set(p.sessionId, now)
407 } else {
408 await $.store.delete(rowKey(p.sessionId)).catch(() => {})
409 }
410 }
411 $.ui.toast(`main moved: told ${told} of ${peers.length} other session${peers.length === 1 ? '' : 's'}`)
412}
413
414// The ledger never changes what the engine returns: any failure while recording is swallowed.
415const track = async ($: any, change: (l: Ledger) => Ledger) => {
416 try {
417 await update($, ledger, change)
418 } catch {}
419}
420
421// One hooks module per plugin on this build: the guard registers its hooks from here.
422export const register: Register = (on, options) => {
423
424 // Non-interactive sessions (every `claude -p`) get no command and no UI; the ledger still runs below.
425 on('session.start', async ($, e, next) => {
426 if (!e.isInteractive) return next(e)
427 // The guard's log comes back from the store; its command is registered here, as a module may hook an event once.
428 try {
429 const kept = ((await $.store.get(DENIALS_KEY)) as never[] | undefined) ?? []
430 await update($, { plugin: 'session', key: 'guard' } as const, () => ({ denials: kept }))
431 } catch {}
432 // Each on its own: a name the engine refuses (a built-in took it, as /recap did on 2.1.292) must not drop the rest.
433 for (const c of [
434 { name: 'memo', description: 'Pin notes the model reads in every conversation of this project' },
435 { name: 'session-denials', description: 'Calls the guard or the permission rules denied this session' },
436 { name: 'smart-compact', description: 'Set the context % at which the session is recapped and compacted (/smart-compact 60); /smart-compact log lists its checks' },
437 { name: 'handoff', description: 'Recap this session now and keep it for the next start; /handoff <session> also sends it there' },
438 { name: 'last-recap', description: "Print this project's last recap (smart-compact or /handoff)" },
439 { name: 'lessons', description: 'Corrections collected from recaps; /lessons clear empties them' },
440 { name: 'task', description: 'Time a task: /task <name> starts, /task done stops, /task log shows today' },
441 { name: 'reap', description: "Stop this session's unfinished agents and claude -p children (asks first)" },
442 { name: 'reap-list', description: 'Leftover teams processes and worktrees; Reap stops the finished ones and removes the merged or finished ones (asks first)' },
443 { name: 'board', description: 'Open sessions: branch, context %, cost, task, harness/graph/teams runs; tabs for recap, lessons, today' },
444 ]) {
445 try {
446 await $.command.register(c)
447 } catch {}
448 }
449 await heartbeat($)
450 try {
451 // Offered once: never this session's own recap (a smart-compact just wrote it), never one dismissed.
452 const root = await $.session.root()
453 const r = (await $.store.get(recapKey(root))) as Recap | undefined
454 const seen = ((await $.store.get(recapSeenKey(root)).catch(() => undefined)) as number | undefined) ?? 0
455 const own = r?.sessionId === (await $.session.id())
456 const fresh = isFresh(r, (await $.clock.now()) as number) && !own && r!.ts > seen ? { ts: r!.ts } : null
457 await update($, recapAtom, () => fresh)
458 } catch {
459 await update($, recapAtom, () => null)
460 }
461 if (await runningTask($)) {
462 await paintTask($)
463 void tick($).catch(() => {})
464 }
465 // First start of the session: defaults. A later start (hot reload) keeps what is there.
466 await update($, tab, t => t ?? 'retro')
467 await update($, band, b => b ?? false)
468 try {
469 const stored = (await $.store.get(LAST_KEY)) as Summary | undefined
470 // Shown once: the key goes as soon as it is read; lastAtom keeps it for /session retro.
471 if (stored !== undefined) {
472 await update($, lastAtom, () => stored)
473 await update($, band, () => true)
474 await $.store.delete(LAST_KEY)
475 } else {
476 await update($, band, () => false)
477 }
478 } catch {
479 await update($, band, () => false)
480 }
481 await $.command.register({
482 name: 'session',
483 description: 'What this session left behind: files, commits, denied calls; stray claude -p children',
484 })
485 return next(e)
486 }).catch(($, e, next) => next(e))
487
488 // Every tool call: stamp it for step timing, record edits and commits, count a deny from beneath.
489 on('tool.call', async ($, e, next) => {
490 let at = 0
491 try {
492 at = (await $.clock.now()) as number
493 } catch {}
494 const result = await next(e)
495 await midTurnCheck($, e, options)
496 const r = result as { deny?: string; isError?: boolean; result?: { stdout?: string } }
497 await track($, l => {
498 let out = at > 0 ? addStep(l, at) : l
499 if (r.deny !== undefined) return addDeny(out, e.tool, String(r.deny))
500 if (e.tool === 'Edit' || e.tool === 'Write') out = addFile(out, e.file_path)
501 else if (e.tool === 'NotebookEdit') out = addFile(out, e.notebook_path)
502 else if (e.tool === 'Bash') out = addCommit(out, e.command, r.result?.stdout ?? '', !r.isError)
503 return out
504 })
505 // A push to main that went through: the other sessions of this repo hear of it.
506 if (e.tool === 'Bash' && r.deny === undefined && !r.isError && /\bgit\b[^\n]*\bpush\b/.test(e.command)) {
507 try {
508 if ((await $.session.surfaces()).length > 0 && pushesMain(e.command, await gitOut($, ['rev-parse', '--abbrev-ref', 'HEAD']))) await tellMainMoved($)
509 } catch {}
510 }
511 return result
512 }).catch(($, e, next) => next(e))
513
514 // Registered after the ledger, so the ledger wraps the guard and counts its denials too.
515 registerGuard(on, options)
516 registerMemo(on, options)
517 registerCompact(on, options)
518 registerHint(on, options)
519 registerAgents(on, options)
520
521 on('turn.complete', async ($, e, next) => {
522 turnEnd(e)
523 if (e.agentId === undefined) {
524 await track($, endTurn)
525 if ((await $.session.surfaces()).length > 0) {
526 await refreshStats($)
527 await pollOrphans($)
528 // Count of claude -p children below this session, as of this turn end.
529 const n = (await read($, orphansAtom)).length
530 const usage = await $.session.usage().catch(() => undefined)
531 const cost = costText(usage?.cost?.usd, usage?.rateLimits ?? [])
532 $.ui.status(statusLine({ agents: aliveCount(await $.agent.list().catch(() => [])), orphans: n, cost, task: taskStatus(await runningTask($), (await $.clock.now()) as number) }))
533 await heartbeat($)
534 const budget = Number(options.cost_budget_usd ?? 0)
535 if (budget > 0 && !isBudgetToasted && (usage?.cost?.usd ?? 0) >= budget) {
536 isBudgetToasted = true
537 $.ui.toast(`session cost $${usage!.cost!.usd.toFixed(2)} reached the $${budget} budget`)
538 }
539 }
540 }
541 return next(e)
542 }).catch(($, e, next) => next(e))
543
544 on('command.run', { command: 'task' }, async ($, e) => {
545 const cmd = parseTask(e.args)
546 const now = (await $.clock.now()) as number
547 const t = await runningTask($)
548 if (cmd.op === 'show') return { text: t ? taskStatus(t, now) : 'No task running. /task <name> starts one.' }
549 if (cmd.op === 'log') {
550 if ((await $.session.surfaces()).length > 0) {
551 await openBoard($, 'today')
552 return { text: 'Today opened on the board.' }
553 }
554 const log = ((await $.store.get(TASK_LOG_KEY)) as Done[] | undefined) ?? []
555 const lines = todayLines(log, dayOf(now))
556 return { text: lines.length > 0 ? lines.join('\n') : 'No finished task today.' }
557 }
558 let text = ''
559 if (t) {
560 const log = ((await $.store.get(TASK_LOG_KEY)) as Done[] | undefined) ?? []
561 await $.store.set(TASK_LOG_KEY, appendLog(log, { name: t.name, ms: now - t.start, day: dayOf(t.start) }))
562 await $.store.delete(TASK_KEY)
563 text = `done: ${taskStatus(t, now).slice(2)}`
564 }
565 if (cmd.op === 'start') {
566 await $.store.set(TASK_KEY, { name: cmd.name, start: now })
567 text = [text, `started: ${cmd.name}`].filter(Boolean).join(' · ')
568 void tick($).catch(() => {})
569 }
570 await paintTask($)
571 return { text: text || 'No task running.' }
572 }).catch(($, e, next) => next(e))
573
574 // /board [recap|lessons|today]: the pane interactive; headless, the rows as text.
575 on('command.run', { command: 'board' }, async ($, e) => {
576 const arg = e.args.trim()
577 const to: BoardTab = arg === 'recap' || arg === 'lessons' || arg === 'today' || arg === 'worktrees' ? arg : 'sessions'
578 if ((await $.session.surfaces()).length > 0) {
579 // bare /board on an open board closes it
580 if (!arg && (await $.ui.panes()).some((p: { id: string }) => p.id === BOARD_PANE)) {
581 await $.ui.close({ id: BOARD_PANE })
582 return { text: 'Board closed.' }
583 }
584 await openBoard($, to)
585 return { text: 'Board opened.' }
586 }
587 const me = String(await $.session.id())
588 const now = (await $.clock.now()) as number
589 const rows = liveRows(await allRows($), now, me)
590 return { text: rows.length > 0 ? rows.map(r => rowText(r, now, me)).join('\n') : 'No session has written a row yet.' }
591 }).catch(($, e, next) => next(e))
592
593 // The pane opens only from its command.
594 on('command.run', { command: 'session' }, async ($, e) => {
595 if ((await $.session.surfaces()).length === 0) return { text: '/session opens a pane in interactive sessions only.' }
596 if (e.args.trim() === 'retro') await update($, tab, () => 'retro')
597 await openPane($)
598 return { text: 'Session pane opened.' }
599 }).catch(($, e, next) => next(e))
600
601 // Save the summary, then reset in place: /clear ends a session with no new session.start.
602 // No UI here and no git or ps: the terminal may be gone and the time is short. Headless runs too.
603 on('session.end', async ($, e, next) => {
604 try {
605 await $.store.delete(rowKey(String(await $.session.id())))
606 } catch {}
607 try {
608 const l = await read($, ledger)
609 if (!isEmpty(l)) {
610 if (leftSomething(l)) {
611 const day = new Date((await $.clock.now()) as number).toISOString().slice(0, 10)
612 await $.store.set(LAST_KEY, summarize(l, day))
613 }
614 await update($, ledger, () => emptyLedger())
615 await update($, statsAtom, () => ({}))
616 }
617 } catch {}
618 return next(e)
619 }).catch(($, e, next) => next(e))
620
621 // One row above the prompt on the first start after a session that left something.
622 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
623 if (e.props.hasSurvey) return next(e)
624 // start_band (default off): which of the two start rows the person asked for
625 const show = String(options.start_band ?? 'off')
626 const last = (show === 'retro' || show === 'both') && (await read($, band)) ? await read($, lastAtom) : null
627 const recap = show === 'recap' || show === 'both' ? await read($, recapAtom) : null
628 if (!last && !recap) return next(e)
629 const { Box, Button, Text } = $.ui.resolve(e)
630 const now = (await $.clock.now()) as number
631 return (
632 <Box flexDirection="column">
633 {recap && (
634 <Box borderStyle="round" borderDimColor paddingX={1} gap={1}>
635 <Box flexShrink={1}>
636 <Text wrap="truncate-end">{`last recap of this project, ${fmtAgo(now - recap.ts)}`}</Text>
637 </Box>
638 <Box flexShrink={0} gap={1}>
639 <Button key="recap" label="Recap" onPress={async () => { await dismissRecap($, recap.ts); await openBoard($, 'recap') }} />
640 <Button key="recap-dismiss" label="dismiss" onPress={() => dismissRecap($, recap.ts)} />
641 </Box>
642 </Box>
643 )}
644 {last && (
645 <Box borderStyle="round" borderDimColor paddingX={1} gap={1}>
646 <Box flexShrink={1}>
647 <Text wrap="truncate-end">
648 {`last session: ${last.files} files, ${last.commits} commits, ${last.denied} denied, longest gap ${fmtMs(last.longestMs)}`}
649 </Text>
650 </Box>
651 <Box flexShrink={0} gap={1}>
652 <Button
653 key="retro"
654 label="Retro"
655 onPress={async () => {
656 await update($, tab, () => 'retro')
657 await openPane($)
658 }}
659 />
660 <Button
661 key="dismiss"
662 label="dismiss"
663 onPress={async () => {
664 await update($, band, () => false)
665 await update($, lastAtom, () => null)
666 try {
667 await $.store.delete(LAST_KEY)
668 } catch {}
669 }}
670 />
671 </Box>
672 </Box>
673 )}
674 {await next(e)}
675 </Box>
676 )
677 }).catch(($, e, next) => next(e))
678
679 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
680 const { Box, Button, Text } = $.ui.resolve(e)
681 const current = await read($, tab)
682 const header = (
683 <Box borderStyle="round" borderColor="claude" gap={1}>
684 <Text key="title" bold>session</Text>
685 <Button
686 key="tab-retro"
687 label="Retro [1]"
688 hotkey="1"
689 variant={current === 'retro' ? 'primary' : undefined}
690 onPress={() => update($, tab, () => 'retro')}
691 />
692 <Button
693 key="tab-orphans"
694 label="Orphans [2]"
695 hotkey="2"
696 variant={current === 'orphans' ? 'primary' : undefined}
697 onPress={() => update($, tab, () => 'orphans')}
698 />
699 </Box>
700 )
701 if (current === 'orphans') {
702 if (await isWindows($)) {
703 return (
704 <Box flexDirection="column">
705 {header}
706 <Text dimColor>process list is off on Windows</Text>
707 <Text dimColor>background shells and subagents: see /tasks</Text>
708 </Box>
709 )
710 }
711 const rows = await read($, orphansAtom)
712 const now = (await $.clock.now()) as number
713 return (
714 <Box flexDirection="column">
715 {header}
716 <Text bold color="claude">{`claude -p children (${rows.length})`}</Text>
717 {rows.length === 0 && <Text dimColor>○ none</Text>}
718 {rows.map(r => (
719 <Box key={`o-${r.pid}`} gap={1}>
720 <Text color="warning">●</Text>
721 <Box flexShrink={0}><Text>{String(r.pid)}</Text></Box>
722 <Box flexShrink={1}><Text wrap="truncate-end">{r.cmd}</Text></Box>
723 <Box flexShrink={0}><Text dimColor>{fmtAge(r.start, now)}</Text></Box>
724 <Button key={`stop-${r.pid}`} label="stop" onPress={() => stopOrphan($, r)} />
725 </Box>
726 ))}
727 <Text dimColor>background shells and subagents: see /tasks</Text>
728 </Box>
729 )
730 }
731 const l = await read($, ledger)
732 const stats = await read($, statsAtom)
733 const last = await read($, lastAtom)
734 // Nothing yet this session: show what the previous one left, as `/session retro` promises.
735 if (isEmpty(l) && last) {
736 return (
737 <Box flexDirection="column">
738 {header}
739 <Text bold color="claude">{`last session ${last.day}`}</Text>
740 <Text bold color="claude">{`files (${last.files})`}</Text>
741 {last.fileList.map(f => <Text key={`f-${f}`} wrap="truncate-start">{`· ${f}`}</Text>)}
742 <Text>{`${last.commits} commits · ${last.denied} denied · longest gap ${fmtMs(last.longestMs)}`}</Text>
743 </Box>
744 )
745 }
746 return (
747 <Box flexDirection="column">
748 {header}
749 <Text bold color="claude">{`files (${l.files.length})`}</Text>
750 {l.files.length === 0 && <Text dimColor>○ none</Text>}
751 {l.files.map(f => (
752 <Text key={`f-${f}`} wrap="truncate-start">{`· ${f}${statOf(stats, f) ? ` ${statOf(stats, f)}` : ''}`}</Text>
753 ))}
754 <Text bold color="claude">{`commits (${l.commits.length})`}</Text>
755 {l.commits.length === 0 && <Text dimColor>○ none</Text>}
756 {l.commits.map(c => (
757 <Box key={`c-${c.hash}`} gap={1}>
758 <Text color="success">✔</Text>
759 <Text wrap="truncate-end">{`${c.hash} ${c.subject}`}</Text>
760 </Box>
761 ))}
762 <Text bold color="claude">{`denied (${l.denied.length})`}</Text>
763 {l.denied.length === 0 && <Text dimColor>○ none</Text>}
764 {l.denied.map((d, i) => (
765 <Box key={`d-${i}`} gap={1}>
766 <Text color="error">✘</Text>
767 <Text wrap="truncate-end">{`${d.tool} ${d.reason}`}</Text>
768 </Box>
769 ))}
770 <Text bold color="claude">{`longest gap ${fmtMs(stepSpan(l.steps))}`}</Text>
771 </Box>
772 )
773 }).catch(($, e, next) => next(e))
774
775 // The board: sessions, and the 0.3.0 views (recap, lessons, today) as tabs.
776 on('ui.render', { component: 'Pane', requestId: BOARD_PANE }, async ($, e) => {
777 const { Box, Button, Text } = $.ui.resolve(e)
778 const current = await read($, boardTab)
779 const now = (await $.clock.now()) as number
780 const tabs: [BoardTab, string, string][] = [['sessions', 'Sessions', '1'], ['recap', 'Recap', '2'], ['lessons', 'Lessons', '3'], ['today', 'Today', '4'], ['worktrees', 'Worktrees', '5']]
781 const header = (
782 <Box borderStyle="round" borderColor="claude" gap={1}>
783 <Text key="title" bold>board</Text>
784 {tabs.map(([id, label, key]) => (
785 <Button
786 key={`tab-${id}`}
787 label={`${label} [${key}]`}
788 hotkey={key}
789 variant={current === id ? 'primary' : undefined}
790 onPress={async () => {
791 await update($, boardTab, () => id)
792 if (id === 'sessions') await refreshBoard($)
793 if (id === 'worktrees') await refreshWorktrees($)
794 }}
795 />
796 ))}
797 {current === 'sessions' && <Button key="refresh" label="refresh [r]" hotkey="r" onPress={() => refreshBoard($)} />}
798 {current === 'worktrees' && <Button key="refresh-wt" label="refresh [r]" hotkey="r" onPress={() => refreshWorktrees($)} />}
799 <Button key="close" role="dismiss" label="close [q]" hotkey="q" onPress={() => $.ui.close({ id: BOARD_PANE })} />
800 </Box>
801 )
802 const root = String(await $.session.root())
803
804 if (current === 'recap') {
805 const r = (await $.store.get(recapKey(root)).catch(() => undefined)) as Recap | undefined
806 return (
807 <Box flexDirection="column">
808 {header}
809 {isFresh(r, now) ? (
810 <Box flexDirection="column" paddingX={1}>
811 <Text bold color="claude">{`recap, ${fmtAgo(now - r.ts)}`}</Text>
812 <Text>{r.text}</Text>
813 </Box>
814 ) : (
815 <Text dimColor>○ no recap for this project in the last 7 days; /handoff makes one</Text>
816 )}
817 </Box>
818 )
819 }
820
821 if (current === 'lessons') {
822 const kept = ((await $.store.get(lessonsKey(root)).catch(() => undefined)) as string[] | undefined) ?? []
823 return (
824 <Box flexDirection="column">
825 {header}
826 <Text bold color="claude">{`lessons (${kept.length})`}</Text>
827 {kept.length === 0 && <Text dimColor>○ none yet: they come from each recap's Corrections</Text>}
828 {kept.map((l, i) => <Text key={`l-${i}`}>{`${i + 1}. ${l}`}</Text>)}
829 {kept.length > 0 && <Text dimColor>worth keeping? move it to CLAUDE.md · /lessons clear empties the list</Text>}
830 </Box>
831 )
832 }
833
834 if (current === 'today') {
835 const log = ((await $.store.get(TASK_LOG_KEY).catch(() => undefined)) as Done[] | undefined) ?? []
836 const lines = todayLines(log, dayOf(now))
837 const t = await runningTask($)
838 return (
839 <Box flexDirection="column">
840 {header}
841 {t && <Text color="claude">{taskStatus(t, now)}</Text>}
842 <Text bold color="claude">finished today</Text>
843 {lines.length === 0 && <Text dimColor>○ none</Text>}
844 {lines.map((l, i) => <Text key={`t-${i}`}>{l}</Text>)}
845 </Box>
846 )
847 }
848
849 if (current === 'worktrees') {
850 const wts = await read($, boardWorktrees)
851 return (
852 <Box flexDirection="column">
853 {header}
854 <Text bold color="claude">{`worktrees (${wts.length})`}</Text>
855 {wts.length === 0 && <Text dimColor>○ none</Text>}
856 {wts.map(w => {
857 const why = wtReason(w)
858 return (
859 <Box key={`w-${w.path}`} flexDirection="column" marginBottom={1}>
860 <Box gap={1}>
861 <Box flexShrink={1}><Text wrap="truncate-end">{wtText(w, now)}</Text></Box>
862 {why === '' ? (
863 <Button key={`clean-${w.path}`} label="Clean" onPress={() => cleanWorktree($, w)} />
864 ) : (
865 <Box flexShrink={0}><Text dimColor>{why}</Text></Box>
866 )}
867 </Box>
868 <Text dimColor wrap="truncate-start">{` ${w.path}`}</Text>
869 </Box>
870 )
871 })}
872 </Box>
873 )
874 }
875
876 const rows = await read($, boardRows)
877 const me = String(await $.session.id())
878 const TINT: Record<string, string> = { running: 'claude', finished: 'success', failed: 'error' }
879 return (
880 <Box flexDirection="column">
881 {header}
882 <Text bold color="claude">{`sessions (${rows.length})`}</Text>
883 {rows.length === 0 && <Text dimColor>○ none</Text>}
884 {rows.map(r => {
885 const isIdle = now - r.ts > IDLE_MS
886 const live = (['harness', 'graph', 'teams'] as const).filter(k => r.runs[k]?.live)
887 return (
888 <Box key={`s-${r.sessionId}`} flexDirection="column" marginBottom={1}>
889 <Box gap={1}>
890 <Text color={r.sessionId === me ? 'claude' : undefined} bold={r.sessionId === me}>{r.sessionId === me ? '● this' : `○ ${shortId(r.sessionId)}`}</Text>
891 <Box flexShrink={1}><Text wrap="truncate-end">{r.branch || '?'}</Text></Box>
892 <Box flexShrink={0}><Text>{`${r.percent}%`}</Text></Box>
893 <Box flexShrink={0}><Text>{`$${r.usd.toFixed(2)}`}</Text></Box>
894 {r.task !== '' && <Box flexShrink={0}><Text>{`⏱ ${r.task}`}</Text></Box>}
895 {isIdle && <Text dimColor>{`idle ${fmtAgo(now - r.ts)}`}</Text>}
896 </Box>
897 <Box gap={2} paddingLeft={2}>
898 {(['harness', 'graph', 'teams'] as const).map(k => (
899 <Text key={`${r.sessionId}-${k}`} color={r.runs[k] ? TINT[r.runs[k]!.state] : undefined} dimColor={!r.runs[k]}>
900 {`${k} ${cellText(r.runs[k])}`}
901 </Text>
902 ))}
903 </Box>
904 {live.length > 0 && <Text dimColor>{` detail: ${live.map(k => DETAIL[k]).join(', ')}${r.sessionId === me ? '' : ' (in that session)'}`}</Text>}
905 <Text dimColor wrap="truncate-start">{` ${r.root}`}</Text>
906 </Box>
907 )
908 })}
909 </Box>
910 )
911 }).catch(($, e, next) => next(e))
912}
913hooks/ledger.ts 87 lines1// Pure ledger logic: no engine calls here.
2
3export type Ledger = {
4 files: string[]
5 commits: { hash: string; subject: string }[]
6 denied: { tool: string; reason: string }[]
7 // tool.call timestamps (ms); 0 separates turns
8 steps: number[]
9}
10
11export type Summary = { day: string; files: number; commits: number; denied: number; longestMs: number; fileList: string[] }
12
13const STEPS_MAX = 2000
14const LIST_MAX = 500
15
16export const emptyLedger = (): Ledger => ({ files: [], commits: [], denied: [], steps: [] })
17
18// Worth storing for the next start: steps alone (only reads) are not.
19export const leftSomething = (l: Ledger) => l.files.length + l.commits.length + l.denied.length > 0
20
21export const isEmpty = (l: Ledger) => l.files.length + l.commits.length + l.denied.length + l.steps.length === 0
22
23export const addFile = (l: Ledger, path: string): Ledger =>
24 !path || l.files.includes(path) || l.files.length >= LIST_MAX ? l : { ...l, files: [...l.files, path] }
25
26// Only a `git commit` that exited 0: hash and subject from `[branch hash] subject`.
27export const addCommit = (l: Ledger, command: string, stdout: string, ok: boolean): Ledger => {
28 if (!ok || !/\bgit\s+(?:-\S+\s+)*commit\b/.test(command)) return l
29 const m = /\[[^\]]*?\s([0-9a-f]{7,40})\]\s*(.*)/.exec(stdout)
30 if (!m) return l
31 return { ...l, commits: [...l.commits, { hash: m[1] ?? '', subject: (m[2] ?? '').trim() }].slice(-LIST_MAX) }
32}
33
34export const addDeny = (l: Ledger, tool: string, reason: string): Ledger => ({
35 ...l,
36 denied: [...l.denied, { tool, reason }].slice(-LIST_MAX),
37})
38
39export const addStep = (l: Ledger, at: number): Ledger => ({ ...l, steps: [...l.steps, at].slice(-STEPS_MAX) })
40
41// A turn ends: the gap to the next turn's first call is the person's time, not a step.
42export const endTurn = (l: Ledger): Ledger =>
43 l.steps.length === 0 || l.steps[l.steps.length - 1] === 0 ? l : { ...l, steps: [...l.steps, 0] }
44
45// S4 (05 Task 4) not run: this is the fallback, the longest gap between two tool.call events of one
46// turn. If turn.step timing is proven, replace the timestamps with real step spans here.
47export const stepSpan = (steps: number[]): number => {
48 let best = 0
49 for (let i = 1; i < steps.length; i++) {
50 const a = steps[i - 1] ?? 0
51 const b = steps[i] ?? 0
52 if (a > 0 && b > 0) best = Math.max(best, b - a)
53 }
54 return best
55}
56
57// `git diff --numstat` lines `added<TAB>deleted<TAB>path` -> { path: '+a -d' }; binary files ('-') read +0 -0.
58export const parseNumstat = (text: string): Record<string, string> => {
59 const out: Record<string, string> = {}
60 for (const line of text.split('\n')) {
61 const m = /^(\d+|-)\t(\d+|-)\t(.+)$/.exec(line)
62 if (m) out[m[3] ?? ''] = `+${m[1] === '-' ? 0 : m[1]} -${m[2] === '-' ? 0 : m[2]}`
63 }
64 return out
65}
66
67// numstat paths are repo-relative, touched paths absolute: match on the tail.
68export const statOf = (stats: Record<string, string>, path: string): string | undefined => {
69 for (const [rel, s] of Object.entries(stats)) if (path === rel || path.endsWith(`/${rel}`)) return s
70 return undefined
71}
72
73export const fmtMs =(ms: number): string => {
74 const s = Math.round(ms / 1000)
75 const m = Math.floor(s / 60)
76 return m > 0 ? `${m}m${String(s % 60).padStart(2, '0')}s` : `${s}s`
77}
78
79export const summarize = (l: Ledger, day: string): Summary => ({
80 day,
81 files: l.files.length,
82 commits: l.commits.length,
83 denied: l.denied.length,
84 longestMs: stepSpan(l.steps),
85 fileList: l.files,
86})
87hooks/kill.ts 23 lines1import { descendants, matchOrphans } from './procs.ts'
2import type { Row } from './procs.ts'
3
4export type Verdict = { ok: true; pid: number } | { ok: false; reason: string; gone?: boolean }
5
6// What `$.process.run` itself starts for this module: never a target.
7const OWN = /^(ps -A |sh -c echo \$PPID)/
8
9// May `seen` (the row the person saw) be signalled, judged against a FRESH process table?
10// Every refusal is a reason for a toast; none sends anything.
11export const checkKill = (seen: Row, fresh: Row[], engine: number, ancestors: number[]): Verdict => {
12 if (!Number.isInteger(engine) || engine <= 0) return { ok: false, reason: 'the session process is unknown' }
13 if (seen.pid === engine) return { ok: false, reason: 'that is the session itself' }
14 if (ancestors.includes(seen.pid)) return { ok: false, reason: 'that process is above the session' }
15 const now = fresh.find(r => r.pid === seen.pid)
16 if (!now) return { ok: false, reason: 'already gone', gone: true }
17 if (!descendants(fresh, engine).some(r => r.pid === seen.pid)) return { ok: false, reason: 'no longer a child of this session' }
18 if (now.cmd !== seen.cmd || now.start !== seen.start) return { ok: false, reason: 'the process changed since it was listed (pid reused?)' }
19 if (OWN.test(now.cmd)) return { ok: false, reason: 'that is a helper of this plugin' }
20 if (!matchOrphans(fresh, engine).some(r => r.pid === seen.pid)) return { ok: false, reason: 'not a claude -p job' }
21 return { ok: true, pid: seen.pid }
22}
23hooks/procs.ts 56 lines1// Pure process-table logic over `ps -A -o pid=,ppid=,lstart=,command=` text.
2
3export type Row = { pid: number; ppid: number; start: string; cmd: string }
4
5export const PS_ARGV = ['ps', '-A', '-o', 'pid=,ppid=,lstart=,command='] as const
6
7const CLAUDE_P = /\bclaude\b.*\s-p(\s|$)/
8const LINE = /^\s*(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+\d{1,2}:\d\d:\d\d\s+\d{4})\s+(.*)$/
9
10// A line that does not parse is skipped.
11export const parsePs = (text: string): Row[] =>
12 text.split('\n').flatMap(line => {
13 const m = LINE.exec(line)
14 return m ? [{ pid: Number(m[1]), ppid: Number(m[2]), start: (m[3] ?? '').replace(/\s+/g, ' '), cmd: m[4] ?? '' }] : []
15 })
16
17// Everything below `engine` in the tree, the engine itself excluded.
18export const descendants = (rows: Row[], engine: number): Row[] => {
19 const below = new Set<number>([engine])
20 for (let grew = true; grew; ) {
21 grew = false
22 for (const r of rows) {
23 if (!below.has(r.pid) && below.has(r.ppid)) {
24 below.add(r.pid)
25 grew = true
26 }
27 }
28 }
29 return rows.filter(r => below.has(r.pid) && r.pid !== engine)
30}
31
32// The pids from `engine` up to the root, engine included.
33export const ancestorsOf = (rows: Row[], engine: number): number[] => {
34 const byPid = new Map(rows.map(r => [r.pid, r]))
35 const out: number[] = [engine]
36 for (let at = byPid.get(engine); at && at.ppid > 0 && !out.includes(at.ppid); at = byPid.get(at.ppid)) out.push(at.ppid)
37 return out
38}
39
40// `claude -p` children of the engine; a wrapper shell and its child are one job: the innermost claude -p is listed,
41// so a SIGTERM reaches claude itself and not only the shell above it.
42export const matchOrphans = (rows: Row[], engine: number): Row[] => {
43 const hits = descendants(rows, engine).filter(r => CLAUDE_P.test(r.cmd))
44 return hits.filter(r => !hits.some(h => h.ppid === r.pid))
45}
46
47// `Wed Oct 8 10:09:00 2026` (local time) against now; '' when the text does not parse.
48export const fmtAge = (start: string, now: number): string => {
49 const t = Date.parse(start)
50 if (Number.isNaN(t) || now < t) return ''
51 const s = Math.floor((now - t) / 1000)
52 if (s < 60) return `${s}s`
53 const m = Math.floor(s / 60)
54 return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
55}
56hooks/status.ts 24 lines1// The plugin owns one status line; the running task, the unfinished-agent count, the claude -p child count, the guard denial count and the cost share it.
2// Pure: callers pass the result to $.ui.status themselves ($ never crosses an import).
3const parts = { agents: 0, orphans: 0, denied: 0, task: '', cost: '' }
4
5export function statusLine(patch: Partial<typeof parts>): string | undefined {
6 Object.assign(parts, patch)
7 const shown = [
8 parts.task,
9 parts.agents > 0 ? `⧗ ${parts.agents} agent(s) · /reap` : '',
10 parts.orphans > 0 ? `⧗ ${parts.orphans} claude -p child(ren) running` : '',
11 parts.denied > 0 ? `guard: ${parts.denied} denied` : '',
12 parts.cost,
13 ].filter(Boolean)
14 return shown.length > 0 ? shown.join(' · ') : undefined
15}
16
17export const deniedCount = () => parts.denied
18
19// `$1.23 · 5h 42%`: the session's cost and the highest rate-limit use, '' when neither is known.
20export function costText(usd: number | undefined, limits: readonly { kind: string; percentUsed: number }[]): string {
21 const top = [...limits].sort((a, b) => b.percentUsed - a.percentUsed)[0]
22 return [usd === undefined ? '' : `$${usd.toFixed(2)}`, top ? `${top.kind} ${Math.round(top.percentUsed)}%` : ''].filter(Boolean).join(' · ')
23}
24hooks/recap.ts 59 lines1// The recap smart-compact and /handoff make, and what is kept of it. Pure: callers do the $ calls.
2
3export const RECAP_PROMPT = `Write a recap of this session that a fresh context can continue from. Use the session's language.
4Keep only what the next steps need; leave out finished work they do not depend on.
5Sections:
61. Goal: what the user is trying to achieve
72. Direction: the next concrete steps, in order
83. In progress: what was being done when this recap was written — file:line, the exact snippet or error text the next step needs
94. Decisions: what was settled that the next steps must respect, with the reason; finished work only as one line with its commit
105. Open: unfinished work and known problems not covered by Direction
116. Corrections: things the user had to correct more than once, one per line starting with "- "; write "- none" if there were none
12Plain text, no preamble.`
13
14export type Recap = { text: string; ts: number; sessionId: string }
15
16export const RECAP_MAX = 8000
17export const LESSONS_MAX = 20
18export const RECAP_FRESH_MS = 7 * 24 * 60 * 60 * 1000
19
20export const recapKey = (root: string) => `recap.project:${root}`
21export const lessonsKey = (root: string) => `lessons.project:${root}`
22
23export const makeRecap = (text: string, ts: number, sessionId: string): Recap => ({
24 text: text.length > RECAP_MAX ? `${text.slice(0, RECAP_MAX)}\n…(cut)` : text,
25 ts,
26 sessionId,
27})
28
29export const isFresh = (r: Recap | undefined, now: number): r is Recap =>
30 r !== undefined && typeof r.text === 'string' && now - r.ts < RECAP_FRESH_MS
31
32// The "- " lines under the Corrections heading, up to the next numbered heading; "none" is dropped.
33export function corrections(text: string): string[] {
34 const lines = text.split('\n')
35 const start = lines.findIndex(l => /^\s*(6\.|#+)?\s*\**\s*corrections\b/i.test(l))
36 if (start < 0) return []
37 const out: string[] = []
38 for (const line of lines.slice(start + 1)) {
39 if (/^\s*\d+\.\s/.test(line)) break
40 const m = line.match(/^\s*[-*]\s+(.+?)\s*$/)
41 if (m && !/^none\.?$/i.test(m[1]!)) out.push(m[1]!)
42 }
43 return out
44}
45
46// Newest last; an exact duplicate is not added twice; the oldest go past the cap.
47export function mergeLessons(kept: readonly string[], fresh: readonly string[]): string[] {
48 const out = [...kept]
49 for (const l of fresh) if (!out.includes(l)) out.push(l)
50 return out.slice(-LESSONS_MAX)
51}
52
53export const fmtAgo = (ms: number): string => {
54 const m = Math.floor(ms / 60000)
55 if (m < 60) return `${m}m ago`
56 const h = Math.floor(m / 60)
57 return h < 48 ? `${h}h ago` : `${Math.floor(h / 24)}d ago`
58}
59hooks/board.ts 175 lines1// The board: one row per live interactive session, written by that session, read by every session.
2// The rows live in $.store, shared live across concurrent sessions (spike 2026-10-10). Pure.
3
4export type RunState = 'running' | 'stalled' | 'blocked' | 'finished' | 'failed'
5export type Cell = { state: RunState; done: number; total: number; live: boolean }
6export type Runs = { harness?: Cell; graph?: Cell; teams?: Cell }
7
8export type BoardRow = {
9 sessionId: string
10 root: string
11 branch: string
12 repo: string
13 percent: number
14 usd: number
15 task: string
16 runs: Runs
17 ts: number
18}
19
20export type BoardTab = 'sessions' | 'recap' | 'lessons' | 'today' | 'worktrees'
21
22export const BOARD_PANE = 'board'
23// Esc closes it while it has the keys; focus asks for them so [q] and the tab keys work at once.
24export const BOARD_OPEN = { id: BOARD_PANE, title: 'Board', focus: true, closeOnEscape: true } as const
25export const ROW_PREFIX = 'board.session:'
26export const rowKey = (sessionId: string) => `${ROW_PREFIX}${sessionId}`
27export const ROW_MAX_AGE_MS = 24 * 60 * 60 * 1000
28export const IDLE_MS = 30 * 60 * 1000
29// harness/hooks/mod.tsx and graph/hooks/mod.tsx LIVE_MS
30export const LIVE_MS = 2 * 60 * 60 * 1000
31export const PEER_MS = 30 * 60 * 1000
32export const SEND_GAP_MS = 2 * 60 * 1000
33
34// This session first, then the newest; rows past a day are left out (and deleted by the reader).
35export function liveRows(rows: readonly BoardRow[], now: number, me: string): BoardRow[] {
36 return rows
37 .filter(r => now - r.ts < ROW_MAX_AGE_MS)
38 .sort((a, b) => (a.sessionId === me ? -1 : b.sessionId === me ? 1 : b.ts - a.ts))
39}
40
41// Other sessions of the same repo seen in the last 30 min: who hears that main moved.
42export const peersOf = (rows: readonly BoardRow[], me: BoardRow, now: number) =>
43 rows.filter(r => r.sessionId !== me.sessionId && r.repo !== '' && r.repo === me.repo && now - r.ts < PEER_MS)
44
45// Copied from graph/hooks/mod.tsx (settled, unmet, readyOf, runState = graph.mjs); copies may drift,
46// so change one and diff the other. Read the same way for graph and teams broker runs.
47type Node = { node_id: string; stage: string; state: string; deps: string[]; after?: string[]; final?: boolean }
48type Run = { nodes?: Node[]; routing_blocked?: boolean }
49
50const settled = (n: Node) =>
51 n.state === 'done' || n.state === 'skipped' || n.state === 'unreachable' || (n.state === 'failed' && n.final === true)
52
53function unmet(nodes: Node[], n: Node): string[] {
54 const get = (id: string) => nodes.find(x => x.node_id === id)
55 const data = n.deps.filter(d => get(d)?.state !== 'done')
56 const order = (n.after ?? []).filter(d => {
57 const dep = get(d)
58 return !dep || !settled(dep)
59 })
60 const live =
61 n.stage === 'report' && data.length === 0 && order.length === 0
62 ? nodes.filter(x => x !== n && x.stage !== 'report' && (x.state === 'running' || (x.state === 'pending' && unmet(nodes, x).length === 0)))
63 : []
64 return [...data, ...order, ...live.map(x => x.node_id)]
65}
66
67function runState(run: Run & { nodes: Node[] }): 'running' | 'blocked' | 'complete' {
68 if (run.nodes.some(n => n.stage === 'report' && n.state === 'done')) return 'complete'
69 const isRunning = run.nodes.some(n => n.state === 'running')
70 if (run.routing_blocked && !isRunning) return 'blocked'
71 const ready = run.nodes.filter(n => n.state === 'pending' && unmet(run.nodes, n).length === 0)
72 return ready.length === 0 && !isRunning ? 'blocked' : 'running'
73}
74
75// graph's pane: live = touched within 2 h and not complete; an old unfinished run reads stalled.
76export function brokerCell(run: Run, mtimeMs: number, now: number): Cell | undefined {
77 if (!Array.isArray(run.nodes)) return undefined
78 const s = runState(run as Run & { nodes: Node[] })
79 const live = s !== 'complete' && now - mtimeMs <= LIVE_MS
80 const state: RunState = s === 'complete' ? 'finished' : !live ? 'stalled' : s
81 return { state, done: run.nodes.filter(n => n.state === 'done').length, total: run.nodes.length, live: state === 'running' }
82}
83
84// harness/hooks/mod.tsx scanRun(): finished when 05-report.md exists, live when touched within 2 h.
85export function harnessCell(r: { finished: boolean; time: number; done: number; total: number }, now: number): Cell {
86 const live = !r.finished && now - r.time < LIVE_MS
87 return { state: r.finished ? 'finished' : live ? 'running' : 'stalled', done: r.done, total: r.total, live }
88}
89
90// The marks of draw.tsx: ● running, ✔ finished, ✘ failed, ○ otherwise.
91const MARK: Record<RunState, string> = { running: '●', finished: '✔', failed: '✘', stalled: '○', blocked: '○' }
92export const cellText = (c: Cell | undefined) =>
93 c === undefined ? '–' : `${MARK[c.state]} ${c.state}${c.total > 0 ? ` ${c.done}/${c.total}` : ''}`
94
95// The command that shows a run's detail, in the session that runs it.
96export const DETAIL: Record<keyof Runs, string> = { harness: '/harness-status', graph: '/graph-status', teams: '/teams-status' }
97
98export const shortId = (id: string) => id.replace(/^session_/, '').slice(0, 8)
99
100export function rowText(r: BoardRow, now: number, me: string): string {
101 const who = `${r.sessionId === me ? '*' : ' '} ${shortId(r.sessionId)}`
102 const idle = now - r.ts > IDLE_MS ? ' (idle)' : ''
103 const runs = (['harness', 'graph', 'teams'] as const).map(k => `${k} ${cellText(r.runs[k])}`).join(' · ')
104 return `${who} ${r.branch || '?'} ${r.percent}% $${r.usd.toFixed(2)}${r.task ? ` ⏱ ${r.task}` : ''}${idle} | ${runs}`
105}
106
107// A Bash command that pushes to main: `git push origin main`, `… HEAD:main`, `… x:main`, or a bare push on main.
108export function pushesMain(command: string, branch: string): boolean {
109 for (const part of command.split(/&&|\|\||;|\n/)) {
110 const words = part.trim().split(/\s+/)
111 // `git push …` or `git -C <dir> push …`: git is the command, push its subcommand
112 if (words[0] !== 'git') continue
113 const at = words[1] === '-C' ? (words[3] === 'push' ? 3 : -1) : words[1] === 'push' ? 1 : -1
114 if (at < 0) continue
115 const args = words.slice(at + 1).filter(w => !w.startsWith('-'))
116 if (args.some(a => a === 'main' || a.endsWith(':main') || a.endsWith(':refs/heads/main'))) return true
117 if (args.length <= 1 && branch === 'main') return true
118 }
119 return false
120}
121
122export const mainMovedText = (sha: string, subject: string, from: string) =>
123 `main moved to ${sha} (pushed by session ${from}): ${subject}. Fetch before editing or bumping versions.`
124
125// ---- the Worktrees tab: facts per `git worktree list --porcelain` entry, and when Clean is offered ----
126
127export type Worktree = { path: string; head: string; branch: string }
128export type WtRow = Worktree & {
129 isMain: boolean
130 exists: boolean
131 // -1: `git status` failed
132 uncommitted: number
133 merged: boolean
134 // ms timestamp of the last commit, 0 when unknown
135 lastCommitMs: number
136 inUse: boolean
137}
138
139// Blocks separated by a blank line: `worktree <path>`, `HEAD <sha>`, `branch refs/heads/<name>` or `detached`.
140export function parseWorktrees(porcelain: string): Worktree[] {
141 const out: Worktree[] = []
142 for (const block of porcelain.split(/\n\s*\n/)) {
143 let path = ''
144 let head = ''
145 let branch = ''
146 for (const line of block.split('\n')) {
147 if (line.startsWith('worktree ')) path = line.slice('worktree '.length).trim()
148 else if (line.startsWith('HEAD ')) head = line.slice('HEAD '.length).trim()
149 else if (line.startsWith('branch ')) branch = line.slice('branch '.length).trim().replace(/^refs\/heads\//, '')
150 }
151 if (path !== '') out.push({ path, head, branch })
152 }
153 return out
154}
155
156// An open board session whose folder is the worktree or inside it.
157export const isInUse = (path: string, roots: readonly string[]) =>
158 roots.some(r => r === path || r.startsWith(path.endsWith('/') ? path : `${path}/`))
159
160// Why a row cannot be cleaned, or '' when it can: not the main checkout, path exists, merged, 0 uncommitted, not in use.
161export function wtReason(r: WtRow): string {
162 if (r.isMain) return 'main'
163 if (!r.exists) return 'missing'
164 if (r.uncommitted < 0) return 'unreadable'
165 if (!r.merged) return 'unmerged'
166 if (r.uncommitted > 0) return `${r.uncommitted} change${r.uncommitted === 1 ? '' : 's'}`
167 if (r.inUse) return 'in use'
168 return ''
169}
170
171export const wtText = (r: WtRow, now: number) =>
172 `${r.branch || `(detached ${r.head.slice(0, 7)})`} · ${r.uncommitted < 0 ? '? changes' : `${r.uncommitted} changes`} · ${r.merged ? 'merged' : 'unmerged'} · ${
173 r.lastCommitMs > 0 ? `${Math.max(0, Math.floor((now - r.lastCommitMs) / 86400e3))}d ago` : 'age ?'
174 }${r.inUse ? ' · in use' : ''}`
175hooks/timer.ts 40 lines1// /task: one running task per session store, a log of finished ones. Pure: callers do the $ calls.
2
3export type Task = { name: string; start: number }
4export type Done = { name: string; ms: number; day: string }
5
6export const TASK_KEY = 'task.current'
7export const TASK_LOG_KEY = 'task.log'
8export const LOG_MAX = 200
9
10export type TaskCmd = { op: 'show' } | { op: 'done' } | { op: 'log' } | { op: 'start'; name: string }
11
12export function parseTask(args: string): TaskCmd {
13 const a = args.trim()
14 if (!a) return { op: 'show' }
15 if (a === 'done' || a === 'stop') return { op: 'done' }
16 if (a === 'log') return { op: 'log' }
17 return { op: 'start', name: a.slice(0, 60) }
18}
19
20export const fmtDur = (ms: number): string => {
21 const m = Math.max(0, Math.floor(ms / 60000))
22 return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
23}
24
25export const dayOf = (ts: number): string => new Date(ts).toISOString().slice(0, 10)
26
27export const taskStatus = (t: Task | undefined, now: number): string => (t ? `⏱ ${t.name} ${fmtDur(now - t.start)}` : '')
28
29export const appendLog = (log: readonly Done[], d: Done): Done[] => [...log, d].slice(-LOG_MAX)
30
31// Today's finished tasks summed by name, longest first, then the total.
32export function todayLines(log: readonly Done[], day: string): string[] {
33 const sums = new Map<string, number>()
34 for (const d of log) if (d.day === day) sums.set(d.name, (sums.get(d.name) ?? 0) + d.ms)
35 if (sums.size === 0) return []
36 const rows = [...sums].sort((a, b) => b[1] - a[1]).map(([n, ms]) => `${fmtDur(ms).padStart(6)} ${n}`)
37 const total = [...sums.values()].reduce((a, b) => a + b, 0)
38 return [...rows, `${fmtDur(total).padStart(6)} total`]
39}
40hooks/guard.tsx 187 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import { classify, classifyFile, copyReveal, pushRing, redact, splitCommands, stopCells, stopColumns, stopHeader, stopHeaderText, stopRows } from './guard-logic.ts'
5import type { Denial, Env, Verdict } from './guard-logic.ts'
6import { deniedCount, statusLine } from './status.ts'
7
8const PANE = 'guard-denials'
9export const DENIALS_KEY = 'session.denials'
10const CAP = 200
11
12export const guardAtom = atom({ plugin: 'session', key: 'guard' } as const, { denials: [] as Denial[] })
13const copyAtom = atom({ plugin: 'session', key: 'guardCopy' } as const, '')
14
15type Mode = 'confirm' | 'deny' | 'off'
16type Ctx = { tool: string; call: string; agentId?: string; log: boolean }
17
18let seq = 0
19
20const list = (s: unknown) => String(s ?? '').split(/[,\n]/).map(x => x.trim()).filter(Boolean)
21
22// One entry per stopped call. A broken store drops the entry, never the decision.
23async function record($: any, d: Omit<Denial, 'id' | 'ts'>) {
24 try {
25 const ts = (await $.clock.now()) as number
26 const cur = ((await $.store.get(DENIALS_KEY)) as Denial[] | undefined) ?? []
27 const next = pushRing(cur, { ...d, id: `${ts}-${++seq}`, ts }, CAP)
28 await $.store.set(DENIALS_KEY, next)
29 await update($, guardAtom, () => ({ denials: next }))
30 } catch {}
31}
32
33// A guard stop: log it, tell the person, answer the deny.
34async function stop($: any, ctx: Ctx, reason: string, source: 'guard' | 'declined', rule: string) {
35 if (ctx.log) await record($, { tool: ctx.tool, call: ctx.call, reason, source, rule, agentId: ctx.agentId })
36 try {
37 $.ui.toast(`guard: ${reason.split('\n')[0]}`, { timeoutMs: 6000 })
38 $.ui.status(statusLine({ denied: deniedCount() + 1 }))
39 } catch {}
40 return { deny: reason }
41}
42
43// The one place a confirm-class verdict becomes a question; a missing or failing ask counts as Cancel.
44async function askOrDeny($: any, v: NonNullable<Verdict>, e: any, next: (e: any) => any, mode: Mode, ctx: Ctx, label: string) {
45 if (mode === 'off') return next(e)
46 if (v.action === 'deny') return stop($, ctx, v.reason, 'guard', v.rule)
47 if (mode === 'deny') return stop($, ctx, `${v.reason} Set guard_mode=off in /config to allow.`, 'guard', v.rule)
48 let answer: string | undefined
49 try {
50 answer = await $.ui.ask(`Run \`${label.slice(0, 120)}\`?`, ['Run', 'Cancel'])
51 } catch {}
52 if (answer === 'Run') return next(e)
53 return stop($, ctx, `session: the person declined (${v.rule}).`, 'declined', v.rule)
54}
55
56// Interactive sessions only: headless agents pass every rule and nothing is logged.
57const live = async ($: any, mode: Mode) => mode !== 'off' && (await $.session.surfaces()).length > 0
58
59const tryRun = async ($: any, argv: string[]) => {
60 try {
61 const r = await $.process.run(argv, { timeoutMs: 5000 })
62 return r.exitCode === 0 ? (r.stdout as string) : undefined
63 } catch {
64 return undefined
65 }
66}
67
68async function envOf($: any, extraBranches: string[]): Promise<Env> {
69 const cwd = (await $.session.cwd()) as string
70 let root: string | undefined
71 let home: string | undefined
72 try {
73 root = (await $.session.root()) as string
74 } catch {}
75 try {
76 home = (await $.env.get('HOME')) as string | undefined
77 } catch {}
78 return {
79 cwd,
80 root,
81 home,
82 extraBranches,
83 git: argv => tryRun($, ['git', ...argv]),
84 pgrep: path => tryRun($, ['pgrep', '-f', path]),
85 }
86}
87
88const callOf = (tool: string, input: any) =>
89 tool === 'Bash' ? redact(String(input?.command ?? '')).slice(0, 200) : String(input?.file_path ?? '')
90
91export const register: Register = (on, options) => {
92 const mode = ((options.guard_mode as Mode | undefined) ?? 'confirm') as Mode
93 const extraBranches = list(options.guard_extra_protected_branches)
94 const secretPaths = list(options.guard_secret_paths)
95 const logOn = options.log_enabled !== false
96
97 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
98 if (e.tool !== 'Bash' || !(await live($, mode))) return next(e)
99 const cmds = splitCommands(e.command)
100 if (cmds.length === 0) return next(e)
101 const v = await classify(cmds, await envOf($, extraBranches))
102 if (!v) return next(e)
103 const ctx = { tool: 'Bash', call: callOf('Bash', e), agentId: e.agentId, log: logOn }
104 return askOrDeny($, v, e, next, mode, ctx, e.command)
105 }).catch(($, e, next) => next(e))
106
107 on('tool.call', { tool: 'Write' }, async ($, e, next) => {
108 if (e.tool !== 'Write' || !(await live($, mode))) return next(e)
109 const v = await classifyFile(e.file_path, secretPaths, await envOf($, extraBranches))
110 if (!v) return next(e)
111 const ctx = { tool: e.tool, call: e.file_path, agentId: e.agentId, log: logOn }
112 return askOrDeny($, v, e, next, mode, ctx, `${e.tool} ${e.file_path}`)
113 }).catch(($, e, next) => next(e))
114
115 on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
116 if (e.tool !== 'Edit' || !(await live($, mode))) return next(e)
117 const v = await classifyFile(e.file_path, secretPaths, await envOf($, extraBranches))
118 if (!v) return next(e)
119 const ctx = { tool: e.tool, call: e.file_path, agentId: e.agentId, log: logOn }
120 return askOrDeny($, v, e, next, mode, ctx, `${e.tool} ${e.file_path}`)
121 }).catch(($, e, next) => next(e))
122
123 // Observer: a verdict from beneath is never altered; a native deny is only written down.
124 on('tool.check', async ($, e, next) => {
125 const r = await next(e)
126 try {
127 if (r.decision === 'deny' && logOn && (await $.session.surfaces()).length > 0) {
128 await record($, {
129 tool: e.tool,
130 call: callOf(e.tool, e.input),
131 reason: r.reason ?? 'denied',
132 source: 'native',
133 nativeRule: r.rule,
134 agentId: e.agentId,
135 })
136 }
137 } catch {}
138 return r
139 }).catch(($, e, next) => next(e))
140
141 on('command.run', { command: 'session-denials' }, async ($, e) => {
142 if ((await $.session.surfaces()).length === 0) return { text: 'Nothing to show here: no screen is attached.' }
143 // the command again on an open pane closes it
144 if (((await $.ui.panes()) as { id: string }[]).some(p => p.id === PANE)) {
145 await $.ui.close({ id: PANE })
146 return { text: 'Denials pane closed.' }
147 }
148 await $.ui.open({ id: PANE, title: 'Denied calls', focus: true, closeOnEscape: true })
149 return { text: 'Denials pane opened.' }
150 }).catch(($, e, next) => next(e))
151
152 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
153 const { Box, Button, Text } = $.ui.resolve(e)
154 const ring = (await read($, guardAtom)).denials
155 const rows = stopRows(ring)
156 const width = stopColumns(rows)
157 const shown = await read($, copyAtom)
158 return (
159 <Box flexDirection="column">
160 <Text key="head" bold>{stopHeaderText(stopHeader(mode, ring))}</Text>
161 {rows.length === 0 && <Text>no denials</Text>}
162 {rows.map(r => {
163 const c = stopCells(r, width)
164 return (
165 <Box key={`d-${c.id}`} flexDirection="column">
166 <Box gap={1}>
167 <Box flexShrink={0}><Text dimColor>{c.time}</Text></Box>
168 <Box flexShrink={1}><Text bold wrap="truncate-end">{c.tool}</Text></Box>
169 <Box flexGrow={1} flexShrink={100}><Text wrap="truncate-end">{c.what}</Text></Box>
170 <Box flexShrink={1}><Text dimColor wrap="truncate-end">{c.rule}</Text></Box>
171 <Box flexShrink={0}>{c.source.tone === 'dim' ? <Text dimColor>{c.source.text}</Text> : <Text color={c.source.tone}>{c.source.text}</Text>}</Box>
172 <Button key={`copy-${c.id}`} label="copy" flexShrink={0} onPress={() => update($, copyAtom, () => c.id)} />
173 </Box>
174 {shown === c.id && <Text>{copyReveal(r)}</Text>}
175 </Box>
176 )
177 })}
178 <Box key="foot" gap={1}>
179 <Text dimColor>Esc ·</Text>
180 <Button key="close" role="dismiss" label="q" hotkey="q" onPress={() => $.ui.close({ id: PANE })} />
181 <Text dimColor wrap="truncate-end">· /session-denials closes</Text>
182 </Box>
183 </Box>
184 )
185 }).catch(($, e, next) => next(e))
186}
187hooks/memo.tsx 138 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import {
5 ageHint, clean, cutLine, facts, FOOTER_LEAD, FOOTER_TAIL, MAX_NOTES, memoHeader, memoLines, noteLines, parse, refusal, render, USAGE,
6} from './memo-logic.ts'
7import type { Note } from './memo-logic.ts'
8
9const PANE = 'memo'
10const GLOBAL = 'memo.global'
11const projectKey = (root: string) => `memo.project:${root}`
12
13// armed: true until the block went to the model in this conversation; /compact, /clear and every write set it again.
14// sentAt: epoch ms of that send, 0 before the first one.
15const armed = atom({ plugin: 'session', key: 'memo' } as const, { armed: true, sentAt: 0 })
16
17async function load($: any): Promise<{ g: Note[]; p: Note[]; root: string }> {
18 const root = (await $.session.root()) as string
19 return { g: clean(await $.store.get(GLOBAL)), p: clean(await $.store.get(projectKey(root))), root }
20}
21
22const save = async ($: any, key: string, notes: Note[]) => {
23 await $.store.set(key, notes)
24 await update($, armed, prev => ({ ...prev, armed: true }))
25}
26
27export const register: Register = (on, _options) => {
28 on('command.run', { command: 'memo' }, async ($, e) => {
29 try {
30 const cmd = parse(e.args)
31 if (cmd.op === 'usage') return { text: USAGE }
32 const { g, p, root } = await load($)
33 const now = (await $.clock.now()) as number
34 const note = 'Applies from the next prompt.'
35 if (cmd.op === 'pane' || cmd.op === 'list') {
36 const surfaces = (await $.session.surfaces()) as unknown[]
37 if (surfaces.length > 0) {
38 // bare /memo on an open pane closes it
39 if (cmd.op === 'pane' && ((await $.ui.panes()) as { id: string }[]).some(p => p.id === PANE)) {
40 await $.ui.close({ id: PANE })
41 return { text: 'Memo pane closed.' }
42 }
43 await $.ui.open({ id: PANE, title: 'Memo', focus: true, closeOnEscape: true })
44 return { text: 'Memo pane opened.' }
45 }
46 if (g.length + p.length === 0) return { text: USAGE }
47 const f = facts(g, p, now)
48 const all = [...f.v.g, ...f.v.p]
49 const lines = noteLines(f.v.g, f.v.p).map((l, i) => {
50 const h = ageHint(all[i]!, now)
51 return `${i + 1}. ${l}${h ? ` (${h})` : ''}`
52 })
53 return { text: [...lines, f.count, f.cut].filter(Boolean).join('\n') }
54 }
55 if (cmd.op === 'add') {
56 const why = refusal(g, p, cmd.text)
57 if (why) {
58 try {
59 if (((await $.session.surfaces()) as unknown[]).length > 0) $.ui.toast(`memo: ${why}`, { timeoutMs: 6000 })
60 } catch {}
61 return { text: why }
62 }
63 const entry = { text: cmd.text, ts: now }
64 if (cmd.global) await save($, GLOBAL, [...g, entry])
65 else await save($, projectKey(root), [...p, entry])
66 return { text: `Note added (${cmd.global ? 'global' : 'project'}). ${g.length + p.length + 1}/${MAX_NOTES}. ${note}` }
67 }
68 if (cmd.op === 'rm') {
69 const all = [...g.map(n => ({ n, key: GLOBAL })), ...p.map(n => ({ n, key: projectKey(root) }))]
70 const hit = all[cmd.n - 1]
71 if (!hit) return { text: `No note ${cmd.n}. ${USAGE}` }
72 const rest = all.filter(x => x !== hit && x.key === hit.key).map(x => x.n)
73 await save($, hit.key, rest)
74 return { text: `Note ${cmd.n} removed. ${note}` }
75 }
76 if (cmd.op !== 'clear') return { text: USAGE }
77 await save($, cmd.global ? GLOBAL : projectKey(root), [])
78 return { text: `Cleared ${cmd.global ? 'global' : 'project'} notes. ${note}` }
79 } catch {
80 return { text: 'memo: the note store could not be read or written; nothing changed' }
81 }
82 }).catch(($, e, next) => next(e))
83
84 // The block rides once per conversation; a bad store leaves the prompt untouched.
85 on('prompt.submit', async ($, e, next) => {
86 try {
87 if (!(await read($, armed)).armed) return next(e)
88 const { g, p } = await load($)
89 const block = render(g, p)
90 if (!block) return next(e)
91 const sentAt = (await $.clock.now()) as number
92 await update($, armed, prev => ({ ...prev, armed: false, sentAt }))
93 return next({ ...e, context: [...(e.context ?? []), block] })
94 } catch {
95 return next(e)
96 }
97 }).catch(($, e, next) => next(e))
98
99 // A new context window (after /compact or /clear) has lost the block; resume and startup have not.
100 on('classic.SessionStart', async ($, e, next) => {
101 if (e.source === 'compact' || e.source === 'clear') await update($, armed, prev => ({ ...prev, armed: true }))
102 return next(e)
103 }).catch(($, e, next) => next(e))
104
105 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
106 const { Box, Text, Button } = $.ui.resolve(e)
107 let g: Note[] = []
108 let p: Note[] = []
109 try {
110 ;({ g, p } = await load($))
111 } catch {}
112 const now = (await $.clock.now()) as number
113 const sent = await read($, armed)
114 const lines = memoLines(g, p, now)
115 const cut = cutLine(g, p)
116 return (
117 <Box flexDirection="column">
118 {lines.length === 0 && <Text>no notes</Text>}
119 {lines.length > 0 && <Text key="h" bold wrap="truncate-end">{memoHeader(g, p, sent)}</Text>}
120 {lines.map(l => (
121 <Box key={`n-${l.n}`} gap={1}>
122 <Box flexShrink={0}><Text>{String(l.n)}</Text></Box>
123 <Box flexShrink={0}><Text>{l.badge}</Text></Box>
124 <Box flexGrow={1} flexShrink={1}><Text wrap="truncate-end">{l.text}</Text></Box>
125 <Box flexShrink={0}><Text dimColor={!l.stale} color={l.stale ? 'warning' : undefined}>{l.age}</Text></Box>
126 </Box>
127 ))}
128 {cut !== '' && <Text color="warning" wrap="truncate-end">{cut}</Text>}
129 <Box key="footer" gap={1}>
130 <Text dimColor wrap="truncate-end">{FOOTER_LEAD}</Text>
131 <Button key="q" role="dismiss" label="q" hotkey="q" onPress={() => $.ui.close({ id: PANE })} />
132 <Text dimColor wrap="truncate-end">{FOOTER_TAIL}</Text>
133 </Box>
134 </Box>
135 )
136 }).catch(($, e, next) => next(e))
137}
138hooks/hint.ts 29 lines1import type { On, PluginOptions } from 'claude-code'
2
3// A short task prompt with no path, code or check named: one toast, at most every 10 minutes. The prompt is never changed.
4const TASK_VERB = /(만들|고쳐|고치|추가|바꿔|수정|구현|지워|삭제|\b(fix|add|make|build|change|implement|remove|refactor)\b)/i
5const HAS_DETAIL = /[\/\\.`]|\d|test|테스트|확인|검증|verify|check/i
6export const HINT_MAX_CHARS = 20
7const GAP_MS = 10 * 60 * 1000
8
9export const needsHint = (text: string): boolean => {
10 const t = text.trim()
11 return t.length > 0 && t.length <= HINT_MAX_CHARS && !t.startsWith('/') && TASK_VERB.test(t) && !HAS_DETAIL.test(t)
12}
13
14let lastAt = -Infinity
15
16export const register = (on: On, options: PluginOptions) => {
17 // Matched on the person's own typing, so it sits beside memo's unmatched prompt.submit hook.
18 on('prompt.submit', { origin: { kind: 'composer' } }, async ($, e, next) => {
19 if (options.prompt_hint === true && needsHint(e.text) && (await $.session.surfaces()).length > 0) {
20 const now = (await $.clock.now()) as number
21 if (now - lastAt >= GAP_MS) {
22 lastAt = now
23 $.ui.toast('short task prompt: scope or a check to verify missing?')
24 }
25 }
26 return next(e)
27 }).catch(($, e, next) => next(e))
28}
29hooks/compact.tsx 278 lines1import { atom, update } from 'claude-code'
2import type { On, PluginOptions } from 'claude-code'
3
4import { compactFailed, compactRetry, firstLine, shouldCompactNow } from './compact-logic.ts'
5import { appendLog, asLog, fmtLastCheck, fmtLog, fmtStats, LOG_KEY, patchLog } from './compact-log.ts'
6import type { LogEntry, LogStats } from './compact-log.ts'
7import { corrections, fmtAgo, isFresh, lessonsKey, makeRecap, mergeLessons, RECAP_PROMPT, recapKey } from './recap.ts'
8import type { Recap } from './recap.ts'
9import { fmtContext, statusLinePercent } from '../scripts/context-logic.mjs'
10import { statusLine } from './status.ts'
11import { BOARD_OPEN } from './board.ts'
12import type { BoardTab } from './board.ts'
13
14// Recap the session at a set context %, then compact with that recap as the summary instructions.
15// The threshold is the userConfig field, so /config shows it; /smart-compact <n> writes the same field.
16// Every recap (here or /handoff) is kept per project: the next start shows it, /lessons collects its Corrections.
17export const THRESHOLD_FIELD = 'smart_compact_threshold'
18// the board pane's tab; mod.tsx draws it
19const boardTab = atom({ plugin: 'session', key: 'boardTab' } as const, 'sessions' as BoardTab)
20const DEFAULT_THRESHOLD = 70
21const MIN = 10
22const MAX = 95
23
24const thresholdOf = (options: PluginOptions) => Number(options[THRESHOLD_FIELD] ?? DEFAULT_THRESHOLD)
25
26// The context the status line shows (window and tokens through context-logic.mjs), not usage().context.percent.
27async function readContext($: any) {
28 const c = (await $.session.usage()).context
29 return statusLinePercent({ context_window_size: c?.window, total_input_tokens: c?.tokens })
30}
31let isRunning = false
32
33// The decision log: writes run one after another on one chain, so a pending→outcome patch and the next
34// turn's append cannot overwrite each other. The turn never waits on it; a failing store is only counted.
35const stats: LogStats = { evaluated: 0, byDecision: {}, logWriteErrors: 0 }
36let logChain: Promise<void> = Promise.resolve()
37let logSeq = 0
38const PROC = Date.now().toString(36)
39
40// false from a main-thread tool call until the turn's turn.complete; compact only succeeds once it is true
41let turnEnded = true
42
43const count = (decision: string) => {
44 const kind = decision.split(':').slice(0, decision.startsWith('skipped:') ? 2 : 1).join(':')
45 stats.byDecision[kind] = (stats.byDecision[kind] ?? 0) + 1
46}
47
48function writeLog($: any, change: (list: LogEntry[]) => Promise<LogEntry[]>) {
49 logChain = logChain.then(async () => {
50 try {
51 const r: any = await $.store.set(LOG_KEY, await change(asLog(await $.store.get(LOG_KEY))))
52 if (r && typeof r === 'object' && 'deny' in r) throw new Error(String(r.deny))
53 } catch (err) {
54 stats.logWriteErrors++
55 stats.lastLogError = firstLine(err)
56 }
57 })
58}
59
60// One stored entry; returns its id so the recapping entry's outcome can be patched in later.
61function logDecision($: any, percent: number | null | undefined, threshold: number, decision: string, outcome = decision) {
62 count(decision)
63 const id = `${PROC}-${++logSeq}`
64 writeLog($, async list => {
65 const ts = (await $.clock.now()) as number
66 let session = 'unknown'
67 try {
68 session = String(await $.session.id())
69 } catch {}
70 return appendLog(list, { id, ts, session, percent: percent ?? null, threshold, decision, outcome })
71 })
72 return id
73}
74
75const readLog = async ($: any) => {
76 try {
77 return asLog(await $.store.get(LOG_KEY))
78 } catch {
79 return []
80 }
81}
82
83function logOutcome($: any, id: string, outcome: string) {
84 writeLog($, async list => patchLog(list, id, outcome))
85}
86
87// One fork over the transcript; kept as the project's recap, its Corrections added to the lessons.
88async function recapNow($: any): Promise<{ text: string } | { reason: string }> {
89 const r = await $.model.fork({ prompt: RECAP_PROMPT })
90 if (!r.isAnswered) return { reason: String(r.reason) }
91 try {
92 const root = await $.session.root()
93 const now = (await $.clock.now()) as number
94 await $.store.set(recapKey(root), makeRecap(r.text, now, await $.session.id()))
95 const kept = ((await $.store.get(lessonsKey(root))) as string[] | undefined) ?? []
96 const fresh = corrections(r.text)
97 if (fresh.length > 0) await $.store.set(lessonsKey(root), mergeLessons(kept, fresh))
98 } catch {}
99 return { text: r.text }
100}
101
102async function storedRecap($: any): Promise<Recap | undefined> {
103 try {
104 const r = (await $.store.get(recapKey(await $.session.root()))) as Recap | undefined
105 return isFresh(r, (await $.clock.now()) as number) ? r : undefined
106 } catch {
107 return undefined
108 }
109}
110
111// Interactive, these views are tabs of the board (Ink); headless, their text is the answer.
112async function onBoard($: any, to: BoardTab): Promise<boolean> {
113 if ((await $.session.surfaces()).length === 0) return false
114 await update($, boardTab, () => to)
115 await $.ui.open(BOARD_OPEN)
116 return true
117}
118
119export const register = (on: On, options: PluginOptions) => {
120 on('command.run', { command: 'smart-compact' }, async ($, e) => {
121 const current = thresholdOf(options)
122 const arg = e.args.trim().replace(/%$/, '')
123 if (arg === 'log') return { text: fmtLog(await readLog($), (await $.clock.now()) as number) }
124 if (!arg) {
125 let context = 'context unknown'
126 try {
127 context = fmtContext(await readContext($), current)
128 } catch {}
129 const lines = [
130 `recap + compact at ${current}%. Change it with /smart-compact <${MIN}-${MAX}>; /smart-compact log lists the checks.`,
131 fmtLastCheck(await readLog($), (await $.clock.now()) as number),
132 fmtStats(stats),
133 context,
134 ]
135 return { text: lines.join('\n') }
136 }
137
138 const value = Number(arg)
139 if (!Number.isInteger(value) || value < MIN || value > MAX) {
140 return { text: `"${e.args.trim()}" is not a whole number from ${MIN} to ${MAX}; still ${current}%.` }
141 }
142 const set = await $.config.set({ key: `${$.plugin.name}.${THRESHOLD_FIELD}`, value })
143 if (set.deny !== undefined) return { text: `not changed: ${set.deny}` }
144 return { text: `recap + compact at ${value}% (was ${current}%).` }
145 }).catch(($, e, next) => next(e))
146
147 // /handoff [to]: a recap now, kept for the next start; with a session name or id, sent there too.
148 on('command.run', { command: 'handoff' }, async ($, e) => {
149 const r = await recapNow($)
150 if ('reason' in r) return { text: `no recap: ${r.reason}` }
151 const to = e.args.trim()
152 let note = ''
153 if (to) {
154 const address = /^session_|^[0-9a-f]{8}-[0-9a-f-]{27}$/.test(to) ? { sessionId: to } : to
155 const sent = await $.session.send({ to: address, text: `Handoff from another session:\n\n${r.text}` }).catch(
156 (err: unknown) => ({ isDelivered: false as const, reason: String(err) }),
157 )
158 note = sent.isDelivered ? `sent to ${to}` : `not sent to ${to}: ${sent.reason.split('\n')[0]}`
159 }
160 if (await onBoard($, 'recap')) return { text: ['Recap kept, on the board', note].filter(Boolean).join('; ') + '.' }
161 return { text: note ? `${r.text}\n\n${note}` : r.text }
162 }).catch(($, e, next) => next(e))
163
164 on('command.run', { command: 'last-recap' }, async $ => {
165 if (await onBoard($, 'recap')) return { text: 'Recap opened on the board.' }
166 const r = await storedRecap($)
167 if (!r) return { text: 'No recap for this project in the last 7 days. /handoff makes one now.' }
168 return { text: `Recap from ${fmtAgo(((await $.clock.now()) as number) - r.ts)}:\n\n${r.text}` }
169 }).catch(($, e, next) => next(e))
170
171 on('command.run', { command: 'lessons' }, async ($, e) => {
172 const key = lessonsKey(await $.session.root())
173 if (e.args.trim() === 'clear') {
174 await $.store.delete(key)
175 return { text: 'Lessons cleared for this project.' }
176 }
177 if (await onBoard($, 'lessons')) return { text: 'Lessons opened on the board.' }
178 const kept = ((await $.store.get(key)) as string[] | undefined) ?? []
179 if (kept.length === 0) return { text: 'No lessons yet: they come from the Corrections section of each recap.' }
180 const lines = kept.map((l, i) => `${i + 1}. ${l}`)
181 return { text: [...lines, '', 'Worth keeping? Move it to CLAUDE.md. /lessons clear empties the list.'].join('\n') }
182 }).catch(($, e, next) => next(e))
183
184 // Matched on reason, so it sits beside mod.tsx's unmatched turn.complete hook.
185 on('turn.complete', { reason: 'answer' }, async ($, e, next) => {
186 if (!e.agentId) turnEnded = true
187 const result = await next(e)
188 stats.evaluated++
189 const threshold = thresholdOf(options)
190 if (e.agentId) return count('skipped:agent'), result
191 if (isRunning) return logDecision($, null, threshold, 'skipped:running'), result
192 if ((await $.session.surfaces()).length === 0) return count('skipped:headless'), result
193
194 let raw: number | undefined
195 try {
196 raw = (await readContext($)).percent ?? undefined
197 } catch (err) {
198 logDecision($, null, threshold, `usage-failed:${firstLine(err)}`)
199 throw err
200 }
201 const percent = raw ?? 0
202 if (percent < threshold) return logDecision($, raw, threshold, 'below'), result
203
204 startRecapThenCompact($, raw, percent, threshold)
205 return result
206 }).catch(($, e, next) => next(e))
207
208}
209
210// A module may hook an event once without a matcher, so mod.tsx's tool.call and turn.complete hooks call these.
211// Mid-turn: a long turn can cross the threshold before turn.complete. Never throws, never alters the call.
212export async function midTurnCheck($: any, e: { agentId?: string }, options: PluginOptions) {
213 if (e.agentId) return
214 turnEnded = false
215 try {
216 if (isRunning || (await $.session.surfaces()).length === 0) return
217 const raw = (await readContext($)).percent ?? undefined
218 const threshold = thresholdOf(options)
219 const percent = raw ?? 0
220 if (shouldCompactNow(percent, threshold, { isRunning, surfaces: 1 }) === 'run') startRecapThenCompact($, raw, percent, threshold)
221 } catch (err) {
222 // every tool call would write a log entry; only the count (shown by /smart-compact) is kept
223 count(`usage-failed:${firstLine(err)}`)
224 }
225}
226
227// Any turn end, whatever its reason, releases a compact that waits for the turn to finish.
228export const turnEnd = (e: { agentId?: string }) => {
229 if (!e.agentId) turnEnded = true
230}
231
232// Recap, then compact with the recap as the summary; one run at a time, off the hook that started it.
233function startRecapThenCompact($: any, raw: number | null | undefined, percent: number, threshold: number) {
234 isRunning = true
235 const id = logDecision($, raw, threshold, 'recapping', 'pending')
236 const run = async () => {
237 $.ui.status(`smart-compact: ${percent}% ≥ ${threshold}%, recapping`)
238 const recap = await recapNow($)
239 if ('reason' in recap) {
240 $.ui.toast(`smart-compact: recap failed (${recap.reason}), left to auto-compact`)
241 logOutcome($, id, `recap-failed:${recap.reason}`)
242 return
243 }
244 // the recap is the summary: compact adds only what it lacks, so the two are not carried twice
245 const instructions = `The recap below is the summary; keep it intact. Do not restate what it says, and do not list past user messages or finished work. Add only what its Direction needs and it lacks (exact code, error text):\n\n${recap.text}`
246 // compact rejects while a turn runs: wait for the turn to end, then a bounded number of final tries
247 let lastError: unknown
248 let finalTries = 0
249 for (;;) {
250 // the first try is at once, even mid-turn; after a rejection, wait for the turn end
251 const step = lastError === undefined ? 'try' : compactRetry(turnEnded, finalTries, lastError)
252 if (step === 'fail') {
253 $.ui.toast('smart-compact: could not compact, left to auto-compact')
254 logOutcome($, id, compactFailed(lastError))
255 return
256 }
257 if (step === 'wait') {
258 await $.clock.sleep(500)
259 continue
260 }
261 if (turnEnded) finalTries++
262 try {
263 const done = await $.session.compact({ instructions })
264 $.ui.toast(done.skip ? `smart-compact: skipped (${done.skip})` : 'smart-compact: recapped and compacted')
265 logOutcome($, id, done.skip ? `skip:${done.skip}` : 'compacted')
266 return
267 } catch (err) {
268 lastError = err
269 await $.clock.sleep(500)
270 }
271 }
272 }
273 void run().catch(err => logOutcome($, id, `error:${firstLine(err)}`)).finally(() => {
274 $.ui.status(statusLine({}))
275 isRunning = false
276 })
277}
278