SLOPSHOPPER

session-board

Adds /board, a pane of every session on this machine with state and update-ready marks, and /safe-stop, which asks one session to write its handoff.

paneguardcommandprocesstimer
★ 1v0.1.5no licenseupdated 2026-10-21shivinate7/claude-settings/mods/session-board
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-board
│ ┃ Session board ✕ › fix the failing auth test and add an audit log call │ ┃ 0 working, 1 waiting, update-ready 0 of 1 │ ┃ repo branch ⏺ Read(src/auth.ts) │ ┃ state update ctx ag ⎿ Read 6 lines │ ┃ [ app - ⏺ Update(src/auth.ts) │ ┃ claude agents output not usable: shown from ⎿ Added 2 lines, removed 1 line │ ┃ the store only ⏺ Bash(bun test) │ ┃ Press a number or a row to open one session. ⎿ 3 pass, 1 fail │ ┃ [ Refresh ] │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /board │ ⎿ session-board: Session board opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Session board
0 working, 1 waiting, update-ready 0 of 1 repo branch state update ctx ag [ app - waiting unk claude agents output not usable: shown from the store only Press a number or a row to open one session. [ Refresh ]
README

session-board

A mod. It adds two commands. /board shows the local sessions and agents and what each one is doing. /safe-stop checks that a session has no running work before you stop it. It draws nothing else. It calls no model.

/board

The command opens a pane with two levels.

All sessions: one band, then one row per session.

  • The band reads like "5 working, 2 waiting, update-ready 6 of 8".
  • A row shows repo, branch, state, update mark, context percent, and running agents.
  • State is "working", "waiting", or "permission". "Permission" means that a tool check returned "ask" and its tool call has not returned yet. An approved long tool call keeps the label until the call ends.
  • The update mark is "ready", "not ready", "unknown", or "no detail".
  • Press a row, or its number, to open that session.
  • The pane shows 40 rows. A line says how many more exist. The count includes entries the board did not read.

One session: agents with status, the last 5 tool calls, files touched, context percent, permission checks, and a receipt for the last turn.

/board text prints the same board as plain text. Use it where no pane shows.

Update-ready

A session is update-ready when all five hold: no running agents, state is waiting, no permission ask, no unpushed commits, and a clean tree.

  • Running servers and background tasks are not part of it. A session with a dev server can read "ready".
  • The git counts come from a reading at turn end and on attach. While the session waits, the heartbeat reads git again 5 minutes after the last read, one read at a time. A session at work reads git only at turn end.
  • A failed or hung git read waits the same 5 minutes before the next one.
  • A read that began before the latest turn start is dropped when it lands.
  • A reading older than 330 s is "unknown". A failed or slow git call is "unknown". A branch with no upstream is "unknown". Unknown is never ready.
  • The 330 s rule (5 minutes plus one beat) guards against a stuck reader, not against idleness.

Where the data comes from

  • claude agents --json seeds the list. One call per refresh, 8 s timeout. A session without this mod shows as "no detail".
  • Each session with the mod writes sess:<sessionId> to $.store. The entry holds repo folder name, branch, and state. It also holds the git counts with their reading time, and the running agent count. It holds spawn counts by agent type, the context percent, and a time stamp. It stays under 1 KB.
  • It also writes detail:<sessionId>, under about 3 KB, for the one-session view. The mod writes it again only when its content changes.
  • A heartbeat refreshes the entry every 30 s. The board hides an entry older than 2 minutes, or stamped more than 30 s ahead of now. The session removes both records at session end. A killed session leaves them. The 2-minute rule hides them. An entry older than one day is deleted at the next session start or /board, unless claude agents lists that session as live. If the list is not available, nothing is deleted.
  • The board reads the 200 newest entries. It says how many more exist.
  • After /clear or a resume, the mod writes nothing for the old id and reads the id again on each beat. It writes under the new id when that binds. After session end it writes nothing.
  • The git call runs once per turn end, once per attach and once per 5 idle minutes: argv array, no shell, core.fsmonitor=false, --no-optional-locks, 5 s timeout.
  • These steps each wait at most 100 ms for their git, agent, context, and store work: session start, turn start, turn end, a permission ask, and the end of a tool call. The work then finishes on its own.
  • The 100 ms wait does not cover everything. At session start, $.session.repo() and $.command.register() are not bounded by it. At session end, the store deletes are not bounded by it. On /clear or a resume, $.session.repo() is not bounded either.
  • A permission ask with no tool id writes nothing.
  • The pane refreshes the board on the heartbeat while it is open. It stops when the pane closes, or after 10 refreshes with no /board call.

Privacy

  • The store is on this machine and is read by this machine only.
  • The mod stores no prompt text, no file content, and no folder path. It shows the repo folder name and the branch.
  • The recent list names a file only for the file tools: Read, Edit, Write, MultiEdit, NotebookEdit, Glob, and Grep. It stores the file name, never the folder. A Bash command and an MCP tool give the tool name only.
  • A name that looks secret shows as "(secret file)". The rule is the one in mods/plain-diff. Examples are .env, *.pem, id_rsa, and credentials.json. .env.example and credentials.ts keep their names.
  • A Grep or Glob path shows only when its last part has an extension. A folder named like a file still shows. That is a known hole.
  • Names on the board are plain text. Control characters, bidi marks, and the characters < > & " backtick are removed or replaced. Long names are cut. The mod reads store values back through the same check.
  • The mod shows no cost figure. The cost figure is not reliable.

/safe-stop

It asks this session to reach a stopping point and write its handoff.

  1. It runs the installed handoff hook's own path functions (hooks/precompact_handoff.py, through python3 or python). It gets the handoff path and the prompt file path. This makes the handoff folder if it is missing.
  2. It sends this session one prompt. The prompt says: finish the step, start no new work, and follow the hook's prompt file. It also says: rewrite the handoff whole, then report branch, uncommitted files, unpushed commits, and running agents.

The prompt is queued until the session is idle. The reply says so. If the host rejects the prompt, the reply says "could not send".

The mod writes no handoff. The session does, by the hook's own rules.

/safe-stop plan prints the prompt and sends nothing. If python or the hook is missing, /safe-stop prints what is missing and sends nothing.

The origin check is a block-list. A run from a plugin, a peer session, a coordinator, a schedule, or an auto-continuation is refused. Other origins run, such as unclassified, sdk, and bridge. The check does not prove that a person typed the command.

The python call runs with -I and with the config folder as its working directory, never the session folder. A repo file named json.py cannot run. A path over 4000 characters is refused, not cut.

Unknown

  • Whether turn end fires while a session waits on a permission prompt. Headless mode cannot test it. The mod uses a tool check that returns "ask" as the waiting signal. An auto-approve mode can answer an "ask" with no person.
  • The order of hooks in the desktop app. The mod clears a permission ask after the tool call returns. This assumes that the host runs the permission check inside the tool call. A headless run did not confirm it.
  • Whether the pane draws well in the desktop app. Only a terminal or the app can show it. Headless runs cannot.
  • Whether $.process works in the desktop app. The API says "CLI only". If it fails there, branch, readiness, and the claude agents seed are missing. The board then shows store entries alone, and no session is ready.
  • Whether the app and the terminal share one store. Same config folder should do it.
  • Whether a prompt sent from a command starts a turn in the desktop app (/safe-stop).
  • The time of the git call in the biggest repo. In the q_max clone, one run took 0.11 s with a warm cache. That is one run on one machine. The real per-turn cost is not measured.
  • Context percent reads 0 in a headless -p run.

Checked: the session id in claude agents --json equals the id the mod writes. Two live sessions merged into one row each.

Limits

  • A session without the mod shows on the board as "no detail", from the agents list. It shows repo and state only. It gets full detail after it loads the mod.
  • The store file name carries the install: a --plugin-dir run wrote session-board_inline-<hash>.json. Sessions loaded two ways probably do not share one file. Load every session the same way.
  • The running agent count is as of the last turn end or heartbeat. It can lag by 30 s.
  • A denied permission clears when the tool call returns, the same as an approved one. Turn end also clears it.
  • Named hole, the sweep: it deletes day-old records only when claude agents --json gives a valid JSON list. A banner line, an object, or no output deletes nothing. A valid empty list [] counts as real, so day-old records of sessions with no live row go.
  • Named hole, the clear race: after /clear or a resume, a store write already held at the host can land late. The mod removes it again after it lands. The old entry can show for a short moment.
  • Named hole, the idle git read: the tree can change between reads, so a clean tree can read as clean for up to 5 minutes after an edit made outside the session. A turn end reads again.
  • Named hole, the config folder: under Git Bash, HOME is a path like /c/Users/x. /safe-stop uses USERPROFILE first when it starts with a drive letter. Another setup can pick the wrong folder. Set CLAUDE_CONFIG_DIR to be sure.
  • A mod error is not shown in the session. It goes to the debug log (claude --debug), one line starting "session-board:".

Try in the desktop app

  1. Install: /plugin install session-board --marketplace shivinate7/claude-settings, then restart the session.
  2. Run /board. Check that the pane draws, that rows open, and that a session without the mod shows "no detail".
  3. Start a long turn in a second session. Check that its row reads "working", then "waiting" at the end.
  4. Trigger a permission prompt. Check that the row reads "permission".
  5. Run /safe-stop plan, then /safe-stop. Check that the handoff file changes.

Check

  • node mods/session-board/session-board.test.mjs runs the tests (stdlib only).
  • claude plugin validate mods/session-board checks the mod.
  • Try it: claude --plugin-dir mods/session-board, then /board.
Source 2 files
hooks/register.mjs 441 lines
1// session-board: one entry per session in the shared store, a pane that reads them, and /safe-stop.
2// Every host call sits in a try: a mod error never breaks a session. No model call anywhere.
3// The host reads on(...) and $.noun.method(...) from source, so they are spelled literally,
4// and helpers that take $ are top-level functions.
5import {
6  AGENTS_TIMEOUT_MS, GC_MS, GIT_IDLE_MS, GIT_TIMEOUT_MS, GRACE_MS, HEARTBEAT_MS, MAX_KEYS, MAX_PATH, MAX_POLLS, READ_BUDGET_MS,
7  bandText, baseName, clean, cleanPath, detailLines, gitArgs, headerText, isSessionId, isUserOrigin, makeTracker,
8  agentRows, configDir, mergeRows, num, parseStatus, readDetail, readEntry, rowText, safeStopMessage, safeStopPlan,
9} from './lib.mjs'
10
11const PANE = 'session-board'
12const tracker = makeTracker()
13let beat = null // the heartbeat timer
14let sid = '' // this session's id, read again on every write (a /clear changes it)
15let staleId = '' // after /clear: the id the host may still answer until the new one binds
16let watching = false // /board ran and its pane is open: the heartbeat also refreshes the board
17let polls = 0 // board refreshes on the heartbeat since the last /board
18let gitBusy = false // a heartbeat git read is running
19let gen = 0 // counts turn starts: a git read that began in an earlier count is dropped when it lands
20let ended = false // the session ended: nothing is written after that
21const retired = new Set() // ids a /clear or resume left behind: a write that lands late is removed again
22let gitNextAt = 0 // an idle beat reads git from this time on; every read moves it GIT_IDLE_MS ahead
23let lastDetail = '' // the detail record as last written, without its stamp
24let board = null // { rows, band, note, now, hidden }
25let view = { id: null, detail: null } // id null: all-sessions view
26
27export function register(on) {
28  on('session.start', async ($, e, next) => {
29    const result = await next(e)
30    try { await startUp($) } catch (err) { note($, 'start failed: ' + (err && err.message)) } // never breaks a session
31    return result
32  })
33
34  on('session.end', async ($, e, next) => {
35    try {
36      if (e.reason !== 'clear' && e.reason !== 'resume') ended = true // first: no write lands between the deletes and the flag
37      if (isSessionId(e.sessionId)) {
38        await $.store.delete('sess:' + e.sessionId)
39        await $.store.delete('detail:' + e.sessionId)
40      }
41      if (e.reason === 'clear' || e.reason === 'resume') {
42        // The process goes on under a new id and no session.start fires. The heartbeat keeps
43        // running and reads the id again each beat. Until the new id binds the host still
44        // answers the old one: write nothing for it.
45        staleId = e.sessionId
46        if (isSessionId(e.sessionId)) retired.add(e.sessionId)
47        lastDetail = ''
48        tracker.reset()
49        await setRepo($)
50        $.clock.after(1500, () => { void (async () => { await refreshGit($); await tick($) })() })
51      } else {
52        if (beat) beat.cancel()
53        beat = null
54        tracker.reset()
55      }
56    } catch (err) { note($, 'end failed: ' + (err && err.message)) } // a killed session leaves its entry: the 2-minute rule hides it
57    return next(e)
58  })
59
60  on('turn.start', async ($, e, next) => {
61    const result = await next(e)
62    if (!e.agentId) {
63      gen++
64      tracker.turnStart()
65      await soon($, flush($, false)) // the write runs on its own; the hook waits at most GRACE_MS
66    }
67    return result
68  })
69
70  on('turn.complete', async ($, e, next) => {
71    const result = await next(e)
72    try {
73      if (!e.agentId) tracker.turnComplete(e)
74      await soon($, refreshAll($, !e.agentId))
75    } catch (err) { note($, 'turn end failed: ' + (err && err.message)) }
76    return result
77  })
78
79  // A client attached: read git once, so the board is current for the person who just looked.
80  on('session.attach', async ($, e, next) => {
81    const result = await next(e)
82    try { await soon($, refreshAll($, true)) } catch (err) { note($, 'attach failed: ' + (err && err.message)) }
83    return result
84  })
85
86  // Observes only. The verdict is the rest of the chain's: an "ask" is the waiting signal.
87  on('tool.check', async ($, e, next) => {
88    const result = await next(e)
89    try {
90      const verdict = result && typeof result === 'object' ? result.decision : undefined
91      tracker.toolCheck({ tool: e.tool, input: e.input, id: e.tool_use_id, verdict })
92      if (verdict === 'ask' && e.tool_use_id) await soon($, flush($, false))
93    } catch { /* observing never changes the verdict */ }
94    return result
95  }).catch(($, e, next) => next(e)) // a failure here lets the tool run as the others decided
96
97  // The host runs the permission check inside next(): the ask is answered once next() returns.
98  on('tool.call', async ($, e, next) => {
99    try {
100      return await next(e)
101    } finally {
102      try { if (tracker.toolCall(e.tool_use_id)) await soon($, flush($, false)) } catch { /* ignore */ }
103    }
104  }).catch(($, e, next) => next(e))
105
106  on('command.run', { command: 'board' }, async ($, e) => {
107    try {
108      view = { id: null, detail: null }
109      polls = 0
110      await loadBoard($)
111      if (String(e.args).trim() === 'text') return { text: boardText() } // no pane: plain text, also for -p
112      watching = true
113      const opened = await $.ui.open({ id: PANE, title: 'Session board' })
114      $.ui.invalidate('ui.render')
115      return { text: opened && opened.isPlaced ? 'Session board opened.' : boardText() }
116    } catch (err) {
117      return { text: 'board: could not open: ' + clean(err && err.message, 100) }
118    }
119  })
120
121  on('command.run', { command: 'safe-stop' }, async ($, e) => {
122    try {
123      if (!isUserOrigin(e.origin)) return { text: 'safe-stop: ignored. Only the person starts it, not a plugin, a peer, or a schedule.' }
124      return { text: await safeStop($, e.args) }
125    } catch (err) {
126      return { text: 'safe-stop: failed, nothing sent: ' + clean(err && err.message, 100) }
127    }
128  })
129
130  // The pane closed: stop refreshing the board on the heartbeat.
131  on('ui.close', async ($, e, next) => {
132    if (e && e.id === PANE) watching = false
133    return next(e)
134  }).catch(($, e, next) => next(e))
135
136  on('ui.render', { component: 'Pane', requestId: PANE }, ($, e) => {
137    const { Box, Text, Button } = $.ui.resolve(e)
138    return paneTree($, e, Box, Text, Button)
139  })
140}
141
142async function startUp($) {
143  tracker.reset()
144  staleId = ''
145  ended = false
146  retired.clear()
147  lastDetail = ''
148  await $.command.register({ name: 'board', description: 'Show every session on this machine: state, update-ready, agents', argumentHint: '[text]' })
149  await $.command.register({ name: 'safe-stop', description: 'Reach a stopping point and write this session\'s handoff', argumentHint: '[plan]' })
150  await setRepo($)
151  if (beat) beat.cancel()
152  beat = $.clock.every(HEARTBEAT_MS, () => { void tick($) })
153  // The first reading and the sweep of killed sessions' entries share one wait of GRACE_MS.
154  await soon($, Promise.all([refreshAll($, true), sweepAll($)]))
155}
156
157async function setRepo($) {
158  try {
159    const repo = await $.session.repo()
160    tracker.setRepo(baseName(repo && repo.root ? repo.root : await $.session.cwd()))
161  } catch { /* the repo name stays empty */ }
162}
163
164// A failure leaves one line in the debug log (claude --debug) and nothing else.
165function note($, text) {
166  try { $.ui.log('session-board: ' + clean(text, 160), { to: 'debug' }) } catch { /* nothing to do */ }
167}
168
169// One host read, at most READ_BUDGET_MS: a hung read never holds the rest.
170function bounded($, p, ms = READ_BUDGET_MS) {
171  return new Promise((resolve, reject) => {
172    const timer = $.clock.after(ms, () => reject(new Error('timed out')))
173    p.then(v => { timer.cancel(); resolve(v) }, err => { timer.cancel(); reject(err) })
174  })
175}
176
177// Git (turn end only), agents, context, then the write. Never throws.
178async function refreshAll($, withGit) {
179  if (withGit) await refreshGit($)
180  await Promise.all([refreshAgents($), refreshCtx($)])
181  await flush($, true)
182}
183
184// The work (a refresh, a store write) runs on its own. A hook waits for it at most GRACE_MS, so
185// a slow or hung read or write never holds a hook, and a quick one is done before the hook returns.
186async function soon($, work) {
187  const w = Promise.resolve(work).catch(() => {})
188  let timer
189  const grace = new Promise(resolve => { timer = $.clock.after(GRACE_MS, resolve) })
190  await Promise.race([w, grace])
191  timer.cancel()
192}
193
194// Heartbeat. It writes the entry on every beat. While the session waits, it reads git again only
195// GIT_IDLE_MS after the last read (a turn end and an attach also read). One read at a time: a beat that finds the last read still running skips it. This
196// runs from a timer, never inside a hook. A failed read makes the counts unknown.
197async function tick($) {
198  try {
199    if (tracker.isIdle() && !gitBusy && (await $.clock.now()) >= gitNextAt) {
200      gitBusy = true
201      try { await refreshGit($) } finally { gitBusy = false }
202    }
203    await refreshAll($, false)
204    if (watching) {
205      if (++polls > MAX_POLLS) watching = false // no /board call for 10 beats: stop polling
206      else await refreshBoard($)
207    }
208  } catch { /* the next beat tries again */ }
209}
210
211async function ident($) {
212  try { sid = await $.session.id() } catch { /* keep the last id */ }
213  return sid
214}
215
216const gone = id => ended || retired.has(id)
217
218// The entry always; the detail record at turn end and on a beat, only when its content changed.
219async function flush($, withDetail) {
220  if (ended) return // the session ended: a refresh that lands now writes nothing
221  try {
222    const id = await ident($)
223    if (ended) return
224    if (!isSessionId(id)) return note($, 'no usable session id: entry not written')
225    if (id === staleId) return // /clear ran and the new id is not bound yet
226    staleId = ''
227    retired.delete(id) // the host answers this id as current
228    const now = await $.clock.now()
229    if (ended) return
230    await $.store.set('sess:' + id, tracker.entry(now))
231    if (withDetail && !gone(id)) {
232      const detail = tracker.detail(now)
233      const key = id + JSON.stringify({ ...detail, at: 0 })
234      if (key !== lastDetail) {
235        await $.store.set('detail:' + id, detail)
236        lastDetail = key
237      }
238    }
239    // A write held at the host can land after the session ended or the id was retired by a
240    // /clear or resume. It recreated the records: remove them again.
241    if (gone(id)) {
242      await $.store.delete('sess:' + id)
243      await $.store.delete('detail:' + id)
244    }
245  } catch (err) { note($, 'store write failed: ' + (err && err.message)) } // the entry goes stale and hides: the safe failure
246}
247
248// One cheap git call per turn end, per attach and per GIT_IDLE_MS of idleness. A failed or slow read makes the counts
249// unknown. A read that began before the latest turn start is dropped when it lands: it may
250// describe the tree from before the turn.
251async function refreshGit($) {
252  const mine = gen
253  try {
254    gitNextAt = (await $.clock.now()) + GIT_IDLE_MS // set first: a failed or hung read waits as long as a good one
255    const cwd = await bounded($, $.session.cwd())
256    const r = await bounded($, $.process.run(gitArgs(), { cwd, timeoutMs: GIT_TIMEOUT_MS }), GIT_TIMEOUT_MS + 1000)
257    const at = await $.clock.now()
258    if (mine !== gen) return
259    if (r.exitCode !== 0) throw new Error('git exited ' + r.exitCode)
260    tracker.setGit(parseStatus(r.stdout), at)
261  } catch (err) {
262    if (mine === gen) {
263      tracker.setGit(null)
264      note($, 'git read failed: ' + (err && err.message))
265    }
266  }
267}
268
269async function refreshAgents($) {
270  try { tracker.setAgents(await bounded($, $.agent.list())) } catch (err) { note($, 'agent list read failed: ' + (err && err.message)) }
271}
272
273async function refreshCtx($) {
274  try {
275    const { context } = await bounded($, $.session.usage())
276    if (context && context.window) tracker.setCtx(num(context.percent ?? ((context.tokens ?? 0) / context.window) * 100, 0, 100))
277  } catch (err) { note($, 'usage read failed: ' + (err && err.message)) }
278}
279
280// Store entries by session id, newest key first, at most MAX_KEYS. total counts every entry key,
281// read or not. old lists the ids of entries a day past their last beat: sweep() decides on those.
282async function readEntries($) {
283  const entries = new Map()
284  const old = []
285  const now = await $.clock.now()
286  const keys = (await $.store.keys()).filter(k => typeof k === 'string' && k.startsWith('sess:'))
287  const newest = keys.slice().reverse().slice(0, MAX_KEYS)
288  await Promise.all(newest.map(async k => {
289    try {
290      const e = readEntry(await $.store.get(k))
291      if (!e) return
292      if (now - e.at > GC_MS) old.push(k.slice(5))
293      else entries.set(k.slice(5), e)
294    } catch { /* one bad key hides one row */ }
295  }))
296  return { entries, old, total: keys.length, read: newest.length }
297}
298
299// Removes the records of sessions a day past their last beat, except a session that
300// `claude agents` lists as live. live: a Set of ids, or null when that list is unknown: then
301// nothing is removed. Removing this session's own detail makes the next beat write it again.
302async function sweep($, old, live) {
303  if (!live) return
304  for (const id of old) {
305    if (live.has(id)) continue
306    try {
307      await $.store.delete('sess:' + id)
308      await $.store.delete('detail:' + id)
309      if (id === sid) lastDetail = ''
310    } catch { /* the next sweep tries again */ }
311  }
312}
313
314async function sweepAll($) {
315  const [agents, store] = await Promise.all([readAgents($), readEntries($)])
316  await sweep($, store.old, agents.ok ? new Set(agents.rows.map(r => r.id)) : null)
317}
318
319// One process call to `claude agents --json`. Never fatal: the note says what is missing.
320async function readAgents($) {
321  try {
322    const r = await bounded($, $.process.run(['claude', 'agents', '--json'], { timeoutMs: AGENTS_TIMEOUT_MS }), AGENTS_TIMEOUT_MS + 1000)
323    if (r.exitCode !== 0) return { rows: [], ok: false, note: 'claude agents failed: shown from the store only' }
324    // Parse once. Anything but a JSON array (a banner line, an object, a string) is not a list:
325    // not ok, so the sweep deletes nothing. A valid [] is a real list with no live session.
326    let list
327    try { list = JSON.parse(String(r.stdout)) } catch { list = null }
328    if (!Array.isArray(list)) return { rows: [], ok: false, note: 'claude agents output not usable: shown from the store only' }
329    return { rows: agentRows(list), ok: true, note: '' }
330  } catch {
331    return { rows: [], ok: false, note: 'claude agents unavailable: shown from the store only' }
332  }
333}
334
335async function loadBoard($) {
336  const [agents, store, now] = await Promise.all([readAgents($), readEntries($), $.clock.now()])
337  const rows = mergeRows(agents.rows, store.entries, now)
338  board = { rows, band: bandText(rows), note: agents.note, now, hidden: store.total - store.read }
339  await sweep($, store.old, agents.ok ? new Set(agents.rows.map(r => r.id)) : null)
340  if (view.id) await loadDetail($, view.id, rows)
341}
342
343async function refreshBoard($) {
344  try { await loadBoard($) } catch { /* keep the last board */ }
345  $.ui.invalidate('ui.render')
346}
347
348async function loadDetail($, id, rows) {
349  const now = await $.clock.now()
350  let detail = null
351  if (id === sid) detail = tracker.detail(now)
352  else detail = readDetail(await $.store.get('detail:' + id))
353  view = { id, detail, row: rows.find(r => r.id === id) ?? null }
354}
355
356function boardText() {
357  if (!board) return 'No board yet.'
358  const hidden = board.hidden > 0 ? `+${board.hidden} more entries not read` : ''
359  return [board.band, headerText(80), ...board.rows.map(r => rowText(r, 80)), hidden, board.note].filter(Boolean).join('\n')
360}
361
362function paneTree($, e, Box, Text, Button) {
363  const cols = e.bodyColumns ?? 80
364  const line = (s, dim) => Text({ dimColor: !!dim, children: s })
365  const refresh = Button({ key: 'refresh', label: 'Refresh', hotkey: 'r', onPress: () => { void refreshBoard($) } })
366  if (!board) return Box({ flexDirection: 'column', children: [line('Loading...', true), refresh] })
367  if (view.id) {
368    const row = view.row ?? { id: view.id, repo: '?', branch: '', state: 'unknown', ask: false, ready: null, ctx: null, agents: null, detail: false }
369    const back = Button({ key: 'back', label: 'Back to all sessions', hotkey: 'b', onPress: () => { view = { id: null, detail: null }; $.ui.invalidate('ui.render') } })
370    return Box({ flexDirection: 'column', children: [...detailLines(row, view.detail, board.now).map(s => line(s)), back, refresh] })
371  }
372  const rows = board.rows.slice(0, 40).map((r, i) => Button({
373    key: 'row-' + r.id,
374    label: rowText(r, cols),
375    ...(i < 9 ? { hotkey: String(i + 1) } : {}),
376    onPress: () => { void openSession($, r.id) },
377  }))
378  const unseen = Math.max(0, board.rows.length - 40) + Math.max(0, board.hidden)
379  const more = unseen > 0 ? [line(`+${unseen} more not shown`, true)] : []
380  return Box({
381    flexDirection: 'column',
382    children: [line(board.band), line(headerText(cols), true), ...rows, ...more, ...(board.note ? [line(board.note, true)] : []), line('Press a number or a row to open one session.', true), refresh],
383  })
384}
385
386async function openSession($, id) {
387  try { await loadDetail($, id, board ? board.rows : []) } catch { view = { id, detail: null, row: null } }
388  $.ui.invalidate('ui.render')
389}
390
391// Python that reuses the installed handoff hook's own path functions, so no second copy of
392// the handoff path rules lives here. argv: hooks folder, session id, mode ("plan" makes no folder).
393const HANDOFF_PY = [
394  'import sys, json',
395  'sys.path.append(sys.argv[1])',
396  'import precompact_handoff as p',
397  'if sys.argv[3] != "plan": p.ensure_handoff_dir(sys.argv[2])',
398  'print(json.dumps({"handoff": p.handoff_path(sys.argv[2]), "prompt": p.prompt_path()}))',
399].join('\n')
400
401async function safeStop($, args) {
402  const plan = String(args ?? '').trim() === 'plan'
403  const id = await ident($)
404  if (!isSessionId(id)) return safeStopPlan(null, ['this session id'])
405  const env = { CLAUDE_CONFIG_DIR: await $.env.get('CLAUDE_CONFIG_DIR'), USERPROFILE: await $.env.get('USERPROFILE'), HOME: await $.env.get('HOME') }
406  // A drive-letter USERPROFILE means Windows; the mod has no platform call.
407  const win = /^[A-Za-z]:[\\/]/.test(env.USERPROFILE || '')
408  const config = configDir(env, win ? 'win32' : 'posix')
409  if (!config) return safeStopPlan(null, ['the config folder (set CLAUDE_CONFIG_DIR, HOME, or USERPROFILE)'])
410  const hooks = config + (win ? '\\' : '/') + 'hooks'
411  const why = []
412  let paths = null
413  for (const py of ['python3', 'python']) {
414    try {
415      // -I: no current-folder or user-site imports. cwd is the config folder, never the session's:
416      // a json.py or datetime.py in a repo must not run.
417      const r = await $.process.run([py, '-I', '-B', '-c', HANDOFF_PY, hooks, id, plan ? 'plan' : 'run'], { cwd: config, timeoutMs: 10_000 })
418      const o = r.exitCode === 0 ? JSON.parse(String(r.stdout).trim().split('\n').pop()) : null
419      if (o && typeof o.handoff === 'string' && typeof o.prompt === 'string') { paths = o; break }
420      why.push(`${py}: ${clean(String(r.stderr).trim().split('\n').pop(), 100) || 'no usable output'}`)
421    } catch (err) {
422      why.push(`${py}: ${clean(err && err.message, 100)}`)
423    }
424  }
425  if (!paths) return safeStopPlan(null, [`python with ${hooks}${win ? '\\' : '/'}precompact_handoff.py (${why.join('; ')})`])
426  for (const p of [paths.handoff, paths.prompt]) {
427    // A path is shown and sent whole or not at all: never a cut path.
428    if (Array.from(p).length > MAX_PATH) return `Safe stop: a path from the handoff hook is over ${MAX_PATH} characters. Nothing was sent.`
429  }
430  const handoff = cleanPath(paths.handoff)
431  const text = safeStopMessage(cleanPath(paths.prompt), handoff)
432  if (plan) return safeStopPlan(text, [])
433  try {
434    const sent = await $.prompt.submit({ text })
435    if (sent && sent.drop) throw new Error('dropped: ' + clean(sent.drop, 80))
436  } catch (err) {
437    return 'Safe stop: could not send (' + clean(err && err.message, 100) + '). Nothing was sent.'
438  }
439  return 'Safe stop sent. The prompt is queued until this session is idle. It then rewrites its handoff at ' + handoff + '.'
440}
441
hooks/lib.mjs 395 lines
1// Pure helpers for session-board. No host calls here, so node can test them.
2
3export const STALE_MS = 120_000
4export const HEARTBEAT_MS = 30_000
5export const ENTRY_MAX_BYTES = 1024
6export const DETAIL_MAX_BYTES = 3072
7export const MAX_KEYS = 200 // entries read per refresh, newest key first
8export const GC_MS = 86_400_000 // an entry this long past its last beat is deleted
9export const SKEW_MS = 30_000 // a stamp further ahead than this is not fresh
10export const READ_MAX_AGE_MS = 330_000 // a git reading older than this is unknown: the idle read interval plus one beat
11export const MAX_POLLS = 10 // board refreshes on the heartbeat with no /board call
12export const GRACE_MS = 100 // most a hook waits for its refresh
13export const READ_BUDGET_MS = 3000 // most one host read may take
14export const MAX_PATH = 4000
15export const TO_MAX = 300 // a session name is kept and matched to this length (review round 2 of judge-scope), never the 40-char display cap
16export const GIT_IDLE_MS = 300_000 // an idle session reads git at most this often (a turn end or an attach reads too)
17export const MAX_RECENT = 5
18export const MAX_AGENTS = 8
19export const MAX_SPAWN_TYPES = 6
20export const MAX_FILES = 2000
21export const AGENTS_TIMEOUT_MS = 8000
22export const GIT_TIMEOUT_MS = 5000
23const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
24const FILE_TOOLS = new Set(['Read', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Glob', 'Grep'])
25const SPAWN_TOOLS = new Set(['Agent', 'Task'])
26const LIVE = new Set(['pending', 'running', 'waiting'])
27// Runs of /safe-stop that do not come from the person. Not a list of who may run it: the
28// desktop app can arrive as "unclassified", so only these are refused.
29const NON_USER_ORIGINS = new Set(['plugin', 'peer', 'peer-send-message', 'projects-relay', 'channel', 'coordinator', 'observer', 'observer-activity', 'task-notification', 'scheduled-trigger', 'auto-continuation'])
30export const isUserOrigin = origin => !(origin && typeof origin === 'object' && NON_USER_ORIGINS.has(origin.kind))
31
32// Plain text for anything shown. Control, format and bidi characters become spaces. Markup
33// characters become "_". Long runs of combining marks go. The result is short and inert.
34export function clean(v, max = 40) {
35  let s = typeof v === 'string' ? v : v == null ? '' : String(v)
36  s = s.replace(/[\p{C}]/gu, ' ').replace(/[<>&"`]/g, '_')
37  s = s.replace(/\p{M}{3,}/gu, '').replace(/\s+/g, ' ').trim()
38  const chars = Array.from(s)
39  return chars.length > max ? chars.slice(0, Math.max(0, max - 1)).join('') + '…' : s
40}
41
42// A path or file path shown or sent whole: control and bidi characters go, nothing else changes.
43// Not for names on the board: those go through clean().
44export function cleanPath(v) {
45  const s = typeof v === 'string' ? v : ''
46  return Array.from(s.replace(/\p{C}/gu, '')).slice(0, MAX_PATH).join('')
47}
48
49// A whole number in [lo, hi], else null.
50export const num = (v, lo = 0, hi = 999_999) =>
51  typeof v === 'number' && Number.isFinite(v) ? Math.min(hi, Math.max(lo, Math.round(v))) : null
52
53export const baseName = p => String(p ?? '').split(/[\\/]/).filter(Boolean).pop() ?? ''
54// UTF-8 size of the JSON text. The mod runs where there is no Node, so no Buffer.
55export function byteLen(o) {
56  let n = 0
57  for (const ch of JSON.stringify(o)) {
58    const c = ch.codePointAt(0)
59    n += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4
60  }
61  return n
62}
63const isId = v => typeof v === 'string' && /^[0-9a-zA-Z_-]{8,64}$/.test(v)
64export const isSessionId = isId
65
66// The one git call per turn. Hooks, the optional lock and fsmonitor stay off.
67export const gitArgs = () => ['git', '-c', 'core.fsmonitor=false', '--no-optional-locks', 'status', '--porcelain=v2', '--branch']
68
69// `git status --porcelain=v2 --branch`. unpushed is null when git gives no ahead count
70// (no upstream): unknown, never zero.
71export function parseStatus(text) {
72  let branch = ''
73  let ahead = null
74  let dirty = 0
75  for (const line of String(text ?? '').split('\n')) {
76    if (line.startsWith('# branch.head ')) branch = line.slice(14).trim()
77    else if (line.startsWith('# branch.ab ')) {
78      const m = line.match(/\+(\d+) -(\d+)/)
79      if (m) ahead = Number(m[1])
80    } else if (line && line[0] !== '#') dirty++
81  }
82  return { branch: branch === '(detached)' ? 'detached' : branch, dirty: Math.min(dirty, 9999), unpushed: ahead === null ? null : Math.min(ahead, 9999) }
83}
84
85// Names that say they hold secrets. The same rule as isSecretPath in mods/plain-diff, copied
86// on purpose: each mod stands alone and neither imports the other.
87export function isSecretName(name) {
88  const b = String(name).replace(/\\/g, '/').split('/').pop().toLowerCase()
89  return (
90    (/^\.env(\..*)?$/.test(b) && !/\.(example|sample|template|dist)$/.test(b)) ||
91    /\.(env|pem|key|p12|pfx|jks|keystore|ppk|asc|tfvars)$/.test(b) ||
92    /^\.(envrc|npmrc|netrc|pgpass|pypirc|htpasswd|git-credentials)$/.test(b) ||
93    b === '_netrc' ||
94    /^id_(rsa|dsa|ecdsa|ed25519)$/.test(b) ||
95    /^(application_default_)?credentials(\.(json|ya?ml|toml|ini|xml|csv|txt))?$/.test(b) ||
96    /^secrets?\.(json|ya?ml|md|txt|env|toml)$/.test(b) ||
97    /^service-account.*\.json$/.test(b)
98  )
99}
100
101// What one tool call adds to the recent list: the tool name and, for a file tool only, a file
102// name. An MCP tool, a Bash command and any tool off the list give no name. A Grep or Glob path
103// counts only when its last part has an extension: a folder path never shows.
104// ponytail: a folder named like a file (v1.2) still passes. Upgrade: ask the file system.
105export function toolTarget(tool, input) {
106  const i = input && typeof input === 'object' ? input : {}
107  const out = { t: clean(tool, 24), f: '', edit: EDIT_TOOLS.has(tool), path: '' }
108  if (!FILE_TOOLS.has(tool)) return out
109  const path = tool === 'NotebookEdit' ? i.notebook_path : tool === 'Glob' || tool === 'Grep' ? i.path : i.file_path
110  if (typeof path !== 'string' || !path) return out
111  const name = baseName(path)
112  if ((tool === 'Glob' || tool === 'Grep') && !/\.[^.\s]+$/.test(name)) return out
113  out.f = isSecretName(name) ? '(secret file)' : clean(name, 40)
114  if (out.edit) out.path = path
115  return out
116}
117
118export const spawnType = input => clean(input && typeof input === 'object' ? input.subagent_type || 'general-purpose' : 'general-purpose', 24)
119
120// Spawn counts as a plain object, from a Map or an object. A type named like an
121// Object.prototype key (constructor, __proto__) is an own key here, never the inherited one.
122const put = (o, k, n) => Object.defineProperty(o, k, { value: n, enumerable: true, writable: true, configurable: true })
123function capSpawns(spawns) {
124  const out = {}
125  const sums = new Map()
126  for (const [k, n] of spawns instanceof Map ? spawns : Object.entries(spawns ?? {})) {
127    const key = clean(k, 24)
128    const count = num(n, 0, 9999) ?? 0
129    if (key && count > 0) sums.set(key, (sums.get(key) ?? 0) + count)
130  }
131  let other = 0
132  ;[...sums].sort((a, b) => b[1] - a[1]).forEach(([k, n], i) => {
133    if (i < MAX_SPAWN_TYPES) put(out, k, n)
134    else other += n
135  })
136  if (other) put(out, 'other', (Object.prototype.hasOwnProperty.call(out, 'other') ? out.other : 0) + other)
137  return out
138}
139
140// Shrink until the JSON fits the cap: spawn types first, then the long text fields.
141function fit(obj, cap, steps) {
142  for (const step of steps) {
143    if (byteLen(obj) <= cap) return obj
144    step(obj)
145  }
146  return byteLen(obj) <= cap ? obj : { v: 1, at: obj.at }
147}
148const half = (o, k) => { o[k] = Array.from(o[k]).slice(0, Math.max(1, Math.floor(Array.from(o[k]).length / 2))).join('') }
149
150// The `sess:<id>` entry. Under 1 KB. Repo name and branch only: no prompt, no path.
151export function buildEntry(s) {
152  const e = {
153    v: 1,
154    repo: clean(s.repo, 40),
155    branch: clean(s.branch, 60),
156    state: s.ask || !s.working ? 'waiting' : 'working',
157    ask: !!s.ask,
158    dirty: num(s.dirty, 0, 9999),
159    unpushed: num(s.unpushed, 0, 9999),
160    agents: num(s.agents, 0, 99) ?? 0,
161    spawns: capSpawns(s.spawns),
162    ctx: num(s.ctx, 0, 100),
163    at: s.now,
164  }
165  // When the git counts were read. Absent for an entry that has no reading time.
166  if (num(s.rt, 0, 8.64e15) !== null) e.rt = num(s.rt, 0, 8.64e15)
167  const dropSpawn = o => { const k = Object.keys(o.spawns).pop(); if (k) delete o.spawns[k] }
168  return fit(e, ENTRY_MAX_BYTES, [...Array(MAX_SPAWN_TYPES + 1).fill(dropSpawn), o => half(o, 'branch'), o => half(o, 'branch'), o => half(o, 'repo'), o => half(o, 'repo'), o => half(o, 'repo')])
169}
170
171// The `detail:<id>` record. About 3 KB. File names only.
172export function buildDetail(s) {
173  const d = {
174    v: 1,
175    at: s.now,
176    recent: (s.recent ?? []).slice(-MAX_RECENT).map(r => ({ t: clean(r.t, 24), f: clean(r.f, 40) })),
177    files: num(s.files, 0, 99_999) ?? 0,
178    agents: (s.agents ?? []).slice(0, MAX_AGENTS).map(a => ({ t: clean(a.type, 24), s: clean(a.status, 12) })),
179    spawns: capSpawns(s.spawns),
180    perm: { ask: num(s.perm?.ask, 0, 99_999) ?? 0, deny: num(s.perm?.deny, 0, 99_999) ?? 0, wait: num(s.perm?.wait, 0, 99) ?? 0 },
181    receipt: s.receipt ? { sec: num(s.receipt.sec, 0, 999_999) ?? 0, tools: num(s.receipt.tools, 0, 99_999) ?? 0, edits: num(s.receipt.edits, 0, 99_999) ?? 0, asks: num(s.receipt.asks, 0, 99_999) ?? 0, aborted: !!s.receipt.aborted } : null,
182  }
183  return fit(d, DETAIL_MAX_BYTES, [o => { o.agents.length = Math.min(o.agents.length, 3) }, o => { o.recent = o.recent.slice(-2) }, o => { o.agents = [] }, o => { o.recent = [] }, o => { o.spawns = {} }])
184}
185
186// Read back from the store: another writer on the machine may have put anything there.
187export function readEntry(raw) {
188  if (!raw || typeof raw !== 'object' || raw.v !== 1) return null
189  const at = num(raw.at, 0, 8.64e15)
190  if (at === null) return null
191  const spawns = capSpawns(raw.spawns && typeof raw.spawns === 'object' ? raw.spawns : {})
192  const e = {
193    repo: clean(raw.repo, 40),
194    branch: clean(raw.branch, 60),
195    // A missing or odd state is unknown, never waiting: waiting would let it count as ready.
196    state: raw.state === 'working' || raw.state === 'waiting' ? raw.state : 'unknown',
197    ask: raw.ask === true,
198    dirty: num(raw.dirty, 0, 9999),
199    unpushed: num(raw.unpushed, 0, 9999),
200    agents: num(raw.agents, 0, 99) ?? 0,
201    spawns,
202    ctx: num(raw.ctx, 0, 100),
203    at,
204  }
205  const rt = num(raw.rt, 0, 8.64e15)
206  if (rt !== null) e.rt = rt
207  return e
208}
209export function readDetail(raw) {
210  if (!raw || typeof raw !== 'object' || raw.v !== 1) return null
211  return buildDetail({
212    now: num(raw.at, 0, 8.64e15) ?? 0,
213    recent: Array.isArray(raw.recent) ? raw.recent.filter(r => r && typeof r === 'object').map(r => ({ t: r.t, f: r.f })) : [],
214    files: raw.files,
215    agents: Array.isArray(raw.agents) ? raw.agents.filter(a => a && typeof a === 'object').map(a => ({ type: a.t, status: a.s })) : [],
216    spawns: raw.spawns && typeof raw.spawns === 'object' ? raw.spawns : {},
217    perm: raw.perm && typeof raw.perm === 'object' ? raw.perm : {},
218    receipt: raw.receipt && typeof raw.receipt === 'object' ? raw.receipt : null,
219  })
220}
221
222// Hidden after 2 minutes without a heartbeat. A stamp more than 30 s ahead of now is not fresh.
223export const isFresh = (entry, now) => !!entry && entry.at <= now + SKEW_MS && now - entry.at <= STALE_MS
224
225// Update-ready: no running agents, waiting, no permission ask, no unpushed commits, clean tree.
226// true, false, or 'unknown' when a git count is missing or its reading (e.rt) is older than
227// 330 s or stamped ahead. Only true counts as ready. Without `now`, the reading time is not checked.
228export function readiness(e, now) {
229  if (!e || e.agents !== 0 || e.state !== 'waiting' || e.ask) return false
230  if (e.dirty === null || e.unpushed === null) return 'unknown'
231  if (typeof e.rt === 'number' && typeof now === 'number' && (now - e.rt > READ_MAX_AGE_MS || e.rt - now > SKEW_MS)) return 'unknown'
232  return e.dirty === 0 && e.unpushed === 0
233}
234export const isUpdateReady = (e, now) => readiness(e, now) === true
235
236// `claude agents --json` text to rows. Anything else gives []. A "waiting" row is a session
237// that waits on a permission answer.
238export function parseAgentsJson(text) {
239  let list
240  try { list = JSON.parse(text) } catch { return [] }
241  return agentRows(list)
242}
243
244// Rows from an already parsed `claude agents --json` list. Not an array gives [].
245export function agentRows(list) {
246  if (!Array.isArray(list)) return []
247  const state = s => (s === 'busy' ? 'working' : s === 'idle' || s === 'waiting' ? 'waiting' : 'unknown')
248  return list
249    .filter(r => r && typeof r === 'object' && isId(r.sessionId))
250    .map(r => ({ id: r.sessionId, name: typeof r.name === 'string' ? clean(r.name, TO_MAX) : '', repo: clean(baseName(r.cwd), 40), state: state(r.status), ask: r.status === 'waiting' }))
251}
252
253// The `claude agents` state of the one row named `name`: busy, idle or waiting (on a permission
254// answer). 'unseen' when no row, or more than one row, has that name, or its state is unknown.
255export function receiverState(rows, name) {
256  const find = n => (rows ?? []).filter(r => n && r.name === n)
257  const full = typeof name === 'string' ? clean(name, TO_MAX) : ''
258  let hits = find(full)
259  // ListAgents prints `name [ref]` when names clash. Only when the full name matches nothing, drop the ref.
260  if (!hits.length && typeof name === 'string') hits = find(clean(name.replace(/ \[[^\]]*\]$/, ''), TO_MAX))
261  if (hits.length !== 1) return 'unseen'
262  const r = hits[0]
263  return r.state === 'working' ? 'busy' : r.state !== 'waiting' ? 'unseen' : r.ask ? 'waiting' : 'idle'
264}
265
266// Rows for the board: `claude agents` rows seeded first, then fresh store entries merged in by
267// session id. A session without an entry shows as "no detail". entries: Map id -> readEntry().
268export function mergeRows(agentRows, entries, now) {
269  const rows = new Map()
270  for (const a of agentRows ?? []) rows.set(a.id, { id: a.id, repo: a.repo, branch: '', state: a.state, ask: !!a.ask, ready: null, ctx: null, agents: null, detail: false })
271  for (const [id, e] of entries ?? []) {
272    if (!isFresh(e, now) || !isId(id)) continue
273    rows.set(id, { id, repo: e.repo, branch: e.branch, state: e.state, ask: e.ask, ready: readiness(e, now), ctx: e.ctx, agents: e.agents, detail: true, at: e.at })
274  }
275  const order = { working: 0, waiting: 1, unknown: 2 }
276  return [...rows.values()].sort((a, b) => order[a.state] - order[b.state] || a.repo.localeCompare(b.repo) || a.branch.localeCompare(b.branch) || a.id.localeCompare(b.id))
277}
278
279export function bandText(rows) {
280  if (!rows.length) return 'No sessions found'
281  const n = s => rows.filter(r => r.state === s).length
282  const parts = [`${n('working')} working`, `${n('waiting')} waiting`, `update-ready ${rows.filter(r => r.ready === true).length} of ${rows.length}`]
283  if (n('unknown')) parts.push(`${n('unknown')} unknown`)
284  const blind = rows.filter(r => !r.detail).length
285  if (blind) parts.push(`${blind} no detail`)
286  return parts.join(', ')
287}
288
289const pad = (s, n) => { const c = Array.from(s); return c.length > n ? c.slice(0, n - 1).join('') + '…' : s + ' '.repeat(n - c.length) }
290const stateLabel = r => (r.state === 'waiting' && r.ask ? 'permission' : r.state)
291const readyLabel = r => (r.ready === null ? 'no detail' : r.ready === 'unknown' ? 'unknown' : r.ready ? 'ready' : 'not ready')
292function widths(cols) {
293  const c = num(cols, 40, 400) ?? 80
294  return { repo: 18, branch: Math.max(8, Math.min(24, c - 52)), state: 10, ready: 9 }
295}
296export function headerText(cols) {
297  const w = widths(cols)
298  return [pad('repo', w.repo), pad('branch', w.branch), pad('state', w.state), pad('update', w.ready), pad('ctx', 4), 'ag'].join(' ')
299}
300export function rowText(r, cols) {
301  const w = widths(cols)
302  return [pad(r.repo, w.repo), pad(r.branch || '-', w.branch), pad(stateLabel(r), w.state), pad(readyLabel(r), w.ready), pad(r.ctx === null ? '-' : `${r.ctx}%`, 4), r.agents === null ? '-' : String(r.agents)].join(' ')
303}
304
305export const ago = (now, at) => {
306  const s = Math.max(0, Math.round((now - at) / 1000))
307  return s < 90 ? `${s} s ago` : `${Math.round(s / 60)} min ago`
308}
309
310// Lines for the per-session view. row: a mergeRows row; detail: readDetail() or null.
311export function detailLines(row, detail, now) {
312  const out = [`${clean(row.repo, 24)}  ${clean(row.branch, 32) || '-'}  ${stateLabel(row)}  ${readyLabel(row)}`]
313  if (!row.detail || !detail) {
314    out.push(row.detail ? 'Detail record not found yet.' : 'No detail: this session does not run the session-board mod.')
315    return out
316  }
317  const spawns = Object.entries(detail.spawns).map(([k, n]) => `${k} ${n}`).join(', ')
318  out.push(`Context ${row.ctx === null ? '-' : row.ctx + '%'}   Files touched ${detail.files}   Updated ${ago(now, row.at ?? detail.at)}`)
319  out.push(`Agents running ${row.agents ?? 0}: ${detail.agents.map(a => `${a.t} ${a.s}`).join(', ') || 'none'}`)
320  out.push(`Spawned: ${spawns || 'none'}`)
321  out.push(`Permission checks: ${detail.perm.ask} asked, ${detail.perm.deny} denied, ${detail.perm.wait} waiting now`)
322  out.push(`Recent: ${detail.recent.map(r => (r.f ? `${r.t} ${r.f}` : r.t)).join(' | ') || 'none'}`)
323  const r = detail.receipt
324  out.push(r ? `Last turn: ${r.sec} s, ${r.tools} tool calls, ${r.edits} edits, ${r.asks} permission checks${r.aborted ? ', stopped early' : ''}` : 'Last turn: none yet')
325  return out
326}
327
328// The Claude config folder: CLAUDE_CONFIG_DIR, else the home folder plus .claude. On win32 the
329// home folder is USERPROFILE before HOME: under Git Bash HOME is an MSYS path (/c/Users/x) that
330// a Windows program cannot use. env holds CLAUDE_CONFIG_DIR, USERPROFILE and HOME, as set.
331export function configDir(env, platform) {
332  const e = env ?? {}
333  if (e.CLAUDE_CONFIG_DIR) return e.CLAUDE_CONFIG_DIR
334  const win = platform === 'win32'
335  const home = win ? e.USERPROFILE || e.HOME : e.HOME || e.USERPROFILE
336  return home ? home + (win ? '\\' : '/') + '.claude' : ''
337}
338
339// /safe-stop. The text goes to the session as a prompt. The handoff hook's own prompt file holds
340// the rules for the file itself. No handoff writer lives in this mod.
341export const safeStopMessage = (prompt, handoff) =>
342  `Safe stop. Finish or park the step you are on. Start no new work and no new agent. Then follow ${prompt} and rewrite your handoff at ${handoff}: the whole file, never append. When done, reply with one line: branch, uncommitted files, unpushed commits, running agents.`
343
344export function safeStopPlan(text, missing) {
345  const steps = ["/safe-stop would: (1) ask the installed handoff hook (hooks/precompact_handoff.py) for this session's handoff and prompt paths; (2) send this session one prompt."]
346  if (text) steps.push('Prompt: ' + text)
347  if (missing.length) steps.push('Missing: ' + missing.join('; ') + '. Nothing was sent.')
348  else steps.push('Plan only: nothing was sent.')
349  return steps.join('\n')
350}
351
352// One session's running record. The hooks feed it; entry() and detail() read it.
353export function makeTracker() {
354  let t
355  const reset = () => {
356    t = { inTurn: false, pending: new Set(), spawns: new Map(), recent: [], files: new Set(), ask: 0, deny: 0, turn: { tools: 0, edits: 0, asks: 0 }, receipt: null, git: { branch: '', dirty: null, unpushed: null, rt: null }, agents: [], ctx: null, repo: '' }
357  }
358  reset()
359  const live = () => t.agents.filter(a => LIVE.has(a.status))
360  return {
361    reset,
362    isIdle: () => !t.inTurn,
363    turnStart() { t.inTurn = true; t.pending.clear(); t.turn = { tools: 0, edits: 0, asks: 0 } },
364    turnComplete({ durationMs, isAborted }) {
365      t.inTurn = false
366      t.pending.clear()
367      t.receipt = { sec: Math.round((durationMs ?? 0) / 1000), ...t.turn, aborted: !!isAborted }
368    },
369    // verdict: what the rest of the chain decided: allow, ask or deny. A query has no id: skipped.
370    toolCheck({ tool, input, id, verdict }) {
371      if (!id) return
372      const g = toolTarget(tool, input)
373      t.recent.push({ t: g.t, f: g.f })
374      t.recent = t.recent.slice(-MAX_RECENT)
375      t.turn.tools++
376      if (verdict === 'deny') { t.deny++; return }
377      if (g.edit) { t.turn.edits++; if (g.path && t.files.size < MAX_FILES) t.files.add(g.path) }
378      if (SPAWN_TOOLS.has(tool)) { const k = spawnType(input); t.spawns.set(k, (t.spawns.get(k) ?? 0) + 1) }
379      if (verdict === 'ask') { t.ask++; t.turn.asks++; t.pending.add(id) }
380    },
381    toolCall(id) { return t.pending.delete(id) },
382    // g: parseStatus() output read at time `at`; null: the read failed, so the counts are unknown.
383    setGit(g, at) { t.git = g ? { ...g, rt: at ?? null } : { branch: t.git.branch, dirty: null, unpushed: null, rt: null } },
384    setAgents(list) { t.agents = (list ?? []).map(a => ({ type: a.type, status: a.status })) },
385    setCtx(p) { t.ctx = p },
386    setRepo(r) { t.repo = r },
387    entry(now) {
388      return buildEntry({ repo: t.repo, branch: t.git.branch, working: t.inTurn, ask: t.pending.size > 0, dirty: t.git.dirty, unpushed: t.git.unpushed, agents: live().length, spawns: t.spawns, ctx: t.ctx, rt: t.git.rt, now })
389    },
390    detail(now) {
391      return buildDetail({ now, recent: t.recent, files: t.files.size, agents: live(), spawns: t.spawns, perm: { ask: t.ask, deny: t.deny, wait: t.pending.size }, receipt: t.receipt })
392    },
393  }
394}
395