Workstream board, charters, tmux sidebar and active-session dispatch

A Claude Code plugin for people who run several sessions at once. It groups sessions into workstreams, gives each workstream a charter file, and shows all of them on a live board in a tmux sidebar. The plugin is a Claude Code mod (TypeScript) plus a stdlib-only Python board script. It is for one person working across many long-running efforts, not for teams.
workstream (the key), purpose, scope, focus, goals, status, blocked, blocked_since, note, snoozed_until and project, then a record of dated entries as the body.workstream: key equals the session's name. A session named control is the control session. A name of the form KEY work: <task> is a worker of KEY: it reads a short brief instead of the charter, and the sidebar draws it under its workstream's row./clear and after a compaction. Rows over the record budget roll to <KEY>/record-archive.md beside the charter, and done goals are left out of what a session reads. It records board state from turn, ask, answer and sub-agent events. It registers the mcp__workstreams__charter tool, the session's only way to write its charter (focus, record entries, goals, block), and the mcp__workstreams__worker tool, which starts a worker (claude --bg, named KEY work: <task>, from the project root) for work in a repo or worktree of its own, and closes one of the session's workers by id once it has reported: claude stop then claude rm, which deletes its session and worktree, and, when it keeps the worktree, removes it only if the worker's changes are committed and its commits are on the default branch or its branch has a merged PR. It then deletes the worker's local branch. It keeps the charter's goals in step with the session's task list: completing a goal's task ticks the goal.board.py render prints every workstream grouped as Control, then one group per project, then Active, Blocked, Idle, Unassigned, Done and Snoozed, with a stale line for workstreams that have had no session for a while. bin/ws runs it in a tmux sidebar; the /workstreams:board skill prints it in a session and ranks what to do next.kind: project and a repos: list; a workstream joins one with a project: line, set by board.py join <KEY> <PROJECT>. Its manager is the session named by the project's key, started from its row in the project's group. While you are engaged, for 20 minutes after your last prompt in any session, its /workstreams:project skill runs board.py watch <PROJECT>, which reports finished turns, waits, idle sessions and context size across the members' managers and workers, the PRs their charters' blocked: lines name, all read in one gh query, and the 5h quota crossing 70% and 90%. It nudges an idle session onto a settled step, orders merges across members in a shared repo, tells a member to merge master when a sibling's merge leaves its PR behind, relays asks between members, which never message each other, restarts a manager whose context runs high from its charter, and keeps one list of what needs you. Decisions, merges and pushes stay yours.$.tool.register and the session, turn and tool events). It is developed against 2.1.289 to 2.1.291.tmux, for the sidebar.uv, which runs board.py with its own Python (uv run --no-project). The script uses only the standard library.gh, only for /workstreams:board --deep, which also reads Jira through an MCP server when one is configured, and for a project manager's watch of PRs.claude plugin marketplace add ikstewa/workstreams
claude plugin install workstreams@ikstewa
The /plugin command inside Claude Code does the same.
Charters live in ~/.claude/projects/<project>/workstreams/<KEY>.md. <project> is the project directory with every character other than letters, digits and - replaced by -, so /Users/me/dev/myproject becomes -Users-me-dev-myproject. A .worktrees/<name> suffix is dropped, so a worktree shares its project's charters. The board finds a charter by its workstream: line; the file name is a convention.
A minimal charter:
---
workstream: PAYMENTS_API
purpose: Move invoice creation to the new payments API.
scope:
in: [invoice creation, refunds]
out: [subscription billing]
focus: Client library merged; next is the refund endpoint.
status: active
goals:
- "[x] Client library for the payments API"
- "[ ] Refund endpoint"
- "[ ] Retire the old invoice path"
---
- **10-02** Client library merged. Refund endpoint design agreed.
Set status: done or status: archived to take a workstream off the board's active groups; an archived workstream leaves the board. Do not edit a bound session's charter by hand while the session runs; the session writes it through its charter tool. Only you write note:, snoozed_until: and project:. You set the note from the sidebar. You snooze a workstream by clicking the ☾ on the key row of the sidebar's panel, which offers 1h, 3h or 08:00 tomorrow, or with board.py snooze <KEY> <length> (such as 90m, 3h or 1d). A snoozed workstream sits as one dim line in the board's Snoozed group until the time passes, while its sessions keep running; a permission or a question from any of them ends the snooze, and board.py unsnooze <KEY> or a click on the ☾ ends it by hand.
Name the session after the charter key. From the project directory:
claude -n PAYMENTS_API
/rename in a running session binds it the same way. If the session does not show its charter, its name does not match any charter's workstream: key.
bin/ws creates a tmux session named ws: the board's tree sidebar (40 columns) on the left and claude agents --permission-mode auto on the right, then attaches to it. Run it from the project directory, since the sidebar's directory selects the project:
/path/to/workstreams/bin/ws
Put it on your PATH or alias it. It re-applies its tmux bindings on every run, so a reattach picks up changes.
Inside the ws session:
| Input | Action |
|---|---|
| Click a sidebar row | Open the row's session in the right pane, or reset a stale one from its ↻ |
| Option+j / Option+k | Open the next or previous session without starting one |
| Option+n | Open the next workstream session that needs you, never a worker |
| Option+m | Menu of every row |
| Option+e | Edit the note on the open workstream |
| Click a session id in a reply | Open that session in the right pane, as a click on its row does. Only an id with a sidebar row is a link: an 8-character id or a full one, bare or alone in inline code |
Outside ws these keys pass through to the pane unchanged.
In a session, /workstreams:board prints the same board, ranks the decisions it raises and asks about the first. /workstreams:board --deep adds open pull requests from gh; /workstreams:board <WORKSTREAM> shows one workstream.
The mod can also draw Jira issue keys and GitHub refs written as <repo> #<n> in Claude's replies as links to their issues or pull requests. It changes only what the terminal draws: the stored message and the model's context keep the bare text. A key or ref inside code, an existing link or a URL is left as written. Only the listed projects' keys and the listed repositories' refs link, so UTF-8, SHA-256, PR #198 and a bare #197 stay as written.
It links nothing until you set your Jira site and project keys, or your repositories as owner/repo, in /config or in ~/.claude/settings.json:
"pluginConfigs": {
"workstreams@ikstewa": {
"options": {
"jiraUrl": "https://example.atlassian.net",
"jiraProjectKeys": ["PROJ", "OPS"],
"githubRepos": ["octo-org/widgets"]
}
}
}
uv run --no-project -m unittest discover -s tests
claude plugin test .
claude plugin validate .
tsconfig.json extends ./.claude-plugin/types/tsconfig.json, which is not committed. claude plugin test does not create it, so editor type checking of hooks/mod.ts needs that directory from elsewhere. claude plugin validate . passes with warnings about hooks in mod.ts that have no .catch.
The design is in docs/spec.html.
A personal tool built on Claude Code's early-access mods API, which can change between releases.
hooks/mod.ts 426 lines1import type { ApiMessage, EngineInterface, Register, ToolCallResult, ToolSpec } from 'claude-code'
2import { issueLinks } from './jira-links.ts'
3import { sessionLinks } from './session-links.tsx'
4
5// A bound session's charter, as a user row of its conversation; the charter tool, its one way to write that charter; the worker tool,
6// its one way to start and close a worker session; a worker's brief; its goals kept in step with its task list; and every session's board record.
7// board.py builds the text, makes the writes and keeps the record's state machine; this module decides when each runs and forwards the events the record moves on.
8// Every $-taking helper is a top-level function: the validator lets $ into no other.
9
10const HEAD = '# Workstream charter ('
11const TOOL = 'mcp__workstreams__charter'
12const WORKER_TOOL = 'mcp__workstreams__worker'
13
14// What the model reads to learn the tool: BOUND_RULES in board.py say when to write, this says how.
15const CHARTER: ToolSpec = {
16 name: 'charter',
17 // One line per paragraph and per field: a source line wrapped inside one would reach the model as a break mid-sentence.
18 description: [
19 'Writes the charter of your workstream. The charter is the file named in the header of the charter row in your conversation. ' +
20 'Use this tool for every change to the charter. Do not edit the charter file yourself.',
21 '',
22 'Give one or more of the fields below. One call can carry several fields. The tool applies them in the order below. ' +
23 'The result has one line for each change, then the number of open goals. If the tool refuses a call, the error says why.',
24 '- focus: Replaces the focus line. Say what the workstream is on now: the progress of the plan, the work in flight, and the next ' +
25 'step. The tool changes each newline to a space.',
26 '- record: Adds one entry at the end of the record, as a new top-level bullet. The tool puts "- " and a bold date, "**MM-DD** ", ' +
27 'in front of the first line. If the first line starts with a bold date of your own, such as **10-05, Ian: "go".**, the tool adds ' +
28 'no date. Put each nested bullet on a new line, indented by two spaces.',
29 '- add_goals: Adds each text as an open goal at the end of the goals list. The tool also adds a task for each new goal to your task ' +
30 'list. The tool skips a goal that the list already has, open or ticked.',
31 '- block: Sets blocked: to the thing that the work waits on. Use it only for a wait outside this session and not on Ian, such as a ' +
32 'review, feedback or a merge. The tool also sets blocked_since: to the time now. If you set a block again, its age starts again.',
33 '- clear_block: true removes blocked: and blocked_since:. Do not send clear_block and block in the same call.',
34 '',
35 'This tool does not tick or untick a goal. To tick a goal, complete its task with TaskUpdate. This tool cannot change note:, which ' +
36 'is Ian\'s line. It cannot change any other line of the charter. Only the main session can use this tool. A sub-agent cannot.',
37 ].join('\n'),
38 inputSchema: {
39 type: 'object',
40 properties: {
41 focus: { type: 'string', description: 'The new focus, as one line: progress, in flight, next.' },
42 record: { type: 'string', description: 'One record entry. The tool adds the bullet and the date.' },
43 add_goals: { type: 'array', items: { type: 'string' }, description: 'New open goals, one text each.' },
44 block: { type: 'string', description: 'What the work waits on, outside this session and not on Ian.' },
45 clear_block: { type: 'boolean', description: 'true removes the block.' },
46 },
47 additionalProperties: false,
48 },
49}
50
51// Where BOUND_RULES in board.py say when to start a worker, this says how.
52const WORKER: ToolSpec = {
53 name: 'worker',
54 description: [
55 'Starts a worker of your workstream: a background session named "<KEY> work: <task>", launched from the project root. ' +
56 'The worker enters its own worktree and messages you when it finishes. Start one worker for each repo or worktree, and a new one for each new task, a follow-up PR included; never send a finished worker a second task. Do not run claude --bg yourself.',
57 'Or, with close, closes one of your workers once its PR merges or its task is done and you have what you needed from it: the session ends, and it and its worktree are deleted. A closed worker cannot be reopened. A worker whose changes are uncommitted, or whose commits are neither on the default branch nor in a merged PR, is stopped but kept.',
58 '',
59 'Give task and prompt to start a worker, or close to close one, never both. The result has the name and the id of the worker. If the tool refuses a call, the error says why.',
60 '- task: A short label for the work. It becomes the part of the name after "work: ".',
61 '- prompt: The worker\'s brief. The worker does not see this conversation: say what to do, in which repo, and what to report.',
62 '- close: The id of the worker to close, as the start result printed it.',
63 '',
64 'Only the main session can use this tool. A sub-agent cannot.',
65 ].join('\n'),
66 inputSchema: {
67 type: 'object',
68 properties: {
69 task: { type: 'string', description: 'A short label for the work.' },
70 prompt: { type: 'string', description: 'The worker\'s brief.' },
71 close: { type: 'string', description: 'The id of the worker to close.' },
72 },
73 additionalProperties: false,
74 },
75}
76
77// worker: a worker of a charter's key, which is briefed and given no charter tool.
78type Charter = { registry?: string; name?: string | null; key?: string; text?: string; worker?: boolean }
79
80// What `board.py event` applies to the record, each with what it carries.
81type Board =
82 | { event: 'start' | 'turn.start' | 'answered' | 'prompt' }
83 | { event: 'turn.complete'; reason: string; answer: string }
84 | { event: 'ask'; kind: 'permission' | 'question' }
85 | { event: 'child.start'; agent_id: string; name: string }
86 | { event: 'child.stop'; agent_id: string }
87 | { event: 'end'; reason: string }
88
89// One board.py run, `board.py <cmd> <session id> [...args]`, its stdin built from the session's cwd as it starts; done hands what it
90// printed, or why it failed, to a caller that waits for it. `what` leads its debug line when it fails.
91type Job = { cmd: 'event' | 'write' | 'worker' | 'mirror' | 'tick'; args?: string[]; stdin?: (cwd: string) => string; sid?: string; timeoutMs: number; what: string; done: (out: Out) => void }
92type Out = { stdout: string } | { failed: string }
93
94// The registry file and name the last board.py read reported, and what is owed at the next prompt or main-loop model request.
95// restart: the new session id of a /clear or a /resume owes its record a start. pending: calls that went to the mode's decider, by
96// their asked() key, until a dialog shows. asks: calls a person was asked about that have not returned. kids: the sub-agents whose
97// run the record shows. queue: board.py runs not yet made; draining: one makes them.
98type State = {
99 registry?: string
100 name?: string | null
101 owed?: 'full' | 'start'
102 restart?: boolean
103 pending: Map<string, string>
104 asks: Set<string>
105 kids: Set<string>
106 queue: Job[]
107 draining: boolean
108}
109
110// How often, and how many times, to look for the session id a /clear or a /resume goes on under: 5 s in all. The live check saw
111// the new id's settings SessionStart 0.12 s after session.end.
112const FOLLOW_MS = 50
113const FOLLOW_TRIES = 100
114
115// Read in the API form: the rows form leaves out meta rows, and the charter row is one. There it is a text block of a user
116// message, among the reminders and the prompt merged into it. The declarations say content is always blocks; a string is taken too.
117const holdsCharter = (m: ApiMessage) => {
118 const blocks = typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : m.content
119 return m.role === 'user' && blocks.some(b => b.type === 'text' && String(b.text).startsWith(HEAD))
120}
121
122// A PermissionRequest carries no call id: its call is the pending one with the same tool, loop and input.
123const asked = (tool: string, agentId: string | undefined, input: unknown) => JSON.stringify([tool, agentId ?? null, input])
124
125const reason = (err: unknown) => (err instanceof Error ? err.message : String(err))
126const exited = (run: { exitCode: number; stderr: string }) => new Error(`board.py exited ${run.exitCode}: ${run.stderr.trim().split('\n').at(-1) ?? ''}`)
127
128async function inject($: EngineInterface, st: State, mode: 'full' | 'refresh'): Promise<void> {
129 let key: string | undefined
130 try {
131 const cwd = await $.session.cwd()
132 const argv = ['uv', 'run', '--no-project', `${$.plugin.root}/hooks/board.py`, 'charter', await $.session.id()]
133 // CLAUDE_PROJECT_DIR set to the cwd, as a settings hook started there would see it: an inherited one could name another project.
134 const run = await $.process.run(mode === 'refresh' ? [...argv, '--refresh'] : argv, { cwd, env: { CLAUDE_PROJECT_DIR: cwd }, timeoutMs: 10_000 })
135 if (run.exitCode !== 0) throw exited(run)
136 const out = JSON.parse(run.stdout) as Charter
137 if (out.registry) Object.assign(st, { registry: out.registry, name: out.name ?? null })
138 if (!out.text) return
139 key = out.key
140 if (!out.worker) await offer($)
141 const kept = await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: out.text }] } })
142 if (kept.deny !== undefined) throw new Error(`append refused: ${kept.deny}`)
143 } catch (err) {
144 $.ui.log(`charter${key ? ` of ${key}` : ''} not appended (${mode}): ${reason(err)}`, { to: 'debug' })
145 }
146}
147
148// The charter and worker tools, for a session board.py has just found bound. Registering one again replaces it with itself, so every
149// bound read registers them, a /clear's or a /rename's included; an unbound session, or a worker, never has them.
150async function offer($: EngineInterface): Promise<void> {
151 for (const spec of [CHARTER, WORKER]) {
152 try {
153 await $.tool.register(spec)
154 } catch (err) {
155 $.ui.log(`${spec.name} tool not registered: ${reason(err)}`, { to: 'debug' })
156 }
157 }
158}
159
160// Queues a board.py run; it resolves with what the run printed, or why it failed. One queue, run one at a time in the order queued,
161// since two runs at once would each write the record or the charter over the other's change. It runs from a $.clock callback, so no
162// hook's dispatch owns the run: one abandoned (an Esc at a dialog, an interrupt) cannot abort it.
163function queue($: EngineInterface, st: State, job: Omit<Job, 'done'>): Promise<Out> {
164 return new Promise<Out>(done => {
165 st.queue.push({ ...job, done })
166 // Each run asks for a drain while none runs, so a timer that never fires costs only the wait for the next run.
167 if (!st.draining) $.clock.after(0, () => void drain($, st))
168 })
169}
170
171// A board.py event the record moves on. No hook but session.end waits for one.
172function record($: EngineInterface, st: State, ev: Board, sid?: string, timeoutMs = 10_000): Promise<Out> {
173 return queue($, st, { cmd: 'event', stdin: cwd => JSON.stringify({ ...ev, cwd }), sid, timeoutMs, what: `board ${ev.event} not recorded` })
174}
175
176// The task list from the charter's goals, for the session that `sid` names or the one running.
177function mirror($: EngineInterface, st: State, sid?: string): Promise<Out> {
178 return queue($, st, { cmd: 'mirror', sid, timeoutMs: 10_000, what: 'goals not mirrored' })
179}
180
181// ponytail: a run still queued when a /clear moves the session to its new id is made under the new one; a queued run waits
182// milliseconds, and a /clear never comes mid-turn
183async function drain($: EngineInterface, st: State): Promise<void> {
184 if (st.draining) return
185 st.draining = true
186 for (let job = st.queue.shift(); job; job = st.queue.shift()) {
187 let out: Out = { failed: 'not run' }
188 try {
189 const cwd = await $.session.cwd()
190 const id = job.sid ?? (await $.session.id())
191 const run = await $.process.run(['uv', 'run', '--no-project', `${$.plugin.root}/hooks/board.py`, job.cmd, id, ...(job.args ?? [])],
192 { cwd, env: { CLAUDE_PROJECT_DIR: cwd }, ...(job.stdin && { stdin: job.stdin(cwd) }), timeoutMs: job.timeoutMs })
193 if (run.exitCode !== 0) throw exited(run)
194 out = { stdout: run.stdout }
195 } catch (err) {
196 out = { failed: reason(err) }
197 $.ui.log(`${job.what}: ${out.failed}`, { to: 'debug' })
198 } finally {
199 job.done(out)
200 }
201 }
202 st.draining = false
203}
204
205// What a write printed, as the tool's answer: its summary, or a refusal the model reads as an error. `did` names what was not done.
206function answer(out: Out, did: { failed: string; json: string }): ToolCallResult {
207 if ('failed' in out) return { deny: `${did.failed}: ${out.failed}` }
208 try {
209 const said = JSON.parse(out.stdout) as { ok?: boolean; summary?: string; error?: string }
210 if (said.ok === true) return { result: said.summary ?? '' }
211 return { deny: said.error ?? 'board.py answered neither ok nor error' }
212 } catch (err) {
213 return { deny: `${did.json}: ${reason(err)}` }
214 }
215}
216
217// The record starts over with the session, and the sub-agents and waits this module tracks go with the run they belonged to.
218function begin($: EngineInterface, st: State, sid?: string): Promise<Out> {
219 st.kids.clear()
220 st.pending.clear()
221 st.asks.clear()
222 return record($, st, { event: 'start' }, sid)
223}
224
225// No event fires on the id a /clear or a /resume goes on under, so look for it from $.clock, which outlives session.end's dispatch,
226// and start its record once it shows. A prompt that comes first starts it instead, and so does the next prompt after the last look.
227async function follow($: EngineInterface, st: State, ended: string, tries: number): Promise<void> {
228 let id: string | undefined
229 try { id = await $.session.id() } catch {}
230 if (!st.restart) return
231 if (id !== undefined && id !== ended) {
232 st.restart = false
233 void begin($, st, id)
234 void mirror($, st, id)
235 } else if (tries > 1) $.clock.after(FOLLOW_MS, () => void follow($, st, ended, tries - 1))
236}
237
238// A sub-agent shows from its run's first model request. Only an agent the session lists is one: the engine's own forks (compaction,
239// memory) make requests under ids no list names. Its name is its type, as SubagentStart's agent_type was.
240async function child($: EngineInterface, st: State, agentId: string): Promise<void> {
241 let type: string | undefined
242 try {
243 type = (await $.agent.list()).find(a => a.id === agentId)?.type
244 } catch (err) {
245 $.ui.log(`agents not listed: ${reason(err)}`, { to: 'debug' })
246 }
247 if (type === undefined) return
248 st.kids.add(agentId)
249 void record($, st, { event: 'child.start', agent_id: agentId, name: type })
250}
251
252// A transcript that already holds a charter row is a resume, a reopen or a reload: the session keeps the record, so only the refresh.
253async function start($: EngineInterface, st: State): Promise<void> {
254 let held = false
255 try { held = (await $.session.messages({ as: 'api' })).some(holdsCharter) } catch {}
256 await inject($, st, held ? 'refresh' : 'full')
257}
258
259async function settle($: EngineInterface, st: State): Promise<void> {
260 const owed = st.owed
261 st.owed = undefined
262 await (owed === 'full' ? inject($, st, 'full') : start($, st))
263}
264
265// A /rename shows as a new name in the session's registry file, read in process; board.py runs only once it changed.
266async function renamed($: EngineInterface, st: State): Promise<boolean> {
267 if (!st.registry) return false
268 try {
269 const name = (JSON.parse(await $.fs.read(st.registry)) as { name?: string | null }).name ?? null
270 if (name === st.name) return false
271 st.name = name
272 await inject($, st, 'full')
273 return true
274 } catch (err) {
275 $.ui.log(`registry not read: ${reason(err)}`, { to: 'debug' })
276 return false
277 }
278}
279
280export const register: Register = (on, options) => {
281 const st: State = { pending: new Map(), asks: new Set(), kids: new Set(), queue: [], draining: false }
282 issueLinks(on, options)
283 sessionLinks(on)
284
285 // The goals are mirrored at a start, at each prompt and at a main-loop turn's end, as the settings hooks did before the mod.
286 on('session.start', async ($, e, next) => {
287 const r = await next(e)
288 void begin($, st)
289 void mirror($, st)
290 await start($, st)
291 // No registry file named the session yet: look once more at the first prompt.
292 if (!st.registry) st.owed ??= 'start'
293 return r
294 })
295
296 // No session.start follows a /clear, which starts an empty conversation, or a /resume or /branch (reason resume), which load a held one.
297 on('session.end', async ($, e, next) => {
298 if (e.reason === 'clear') st.owed = 'full'
299 else if (e.reason === 'resume') st.owed = 'start'
300 if (e.reason === 'clear' || e.reason === 'resume') st.restart = true
301 const r = await next(e)
302 // The ending id, not the one the process goes on under. The one hook that waits for its run: an exit ends the process after this
303 // chain, which shares one short bound.
304 const ended = record($, st, { event: 'end', reason: e.reason }, e.sessionId, Math.max(100, Math.min(10_000, next.budget.remainingMs)))
305 if (e.reason === 'clear' || e.reason === 'resume') $.clock.after(FOLLOW_MS, () => void follow($, st, e.sessionId, FOLLOW_TRIES))
306 await ended
307 return r
308 })
309
310 // Ahead of next(e), so the row lands ahead of the prompt and the record's start is queued ahead of the turn's. A prompt typed over
311 // a running turn starts no record over: the turn's next event brings a new name from the registry anyway.
312 on('prompt.submit', async ($, e, next) => {
313 let named = false
314 if (st.owed) await settle($, st)
315 else named = await renamed($, st)
316 if ((st.restart || named) && e.turnId === undefined) {
317 st.restart = false
318 void begin($, st)
319 }
320 // Ian's own prompt, at the terminal or through Remote Control, stamps the project managers' lease. A peer's message, a task notification
321 // or a sub-agent's handback raises this event too, under another origin.
322 if (e.origin?.kind === 'composer' || e.origin?.kind === 'bridge') void record($, st, { event: 'prompt' })
323 void mirror($, st)
324 return next(e)
325 })
326
327 // Any hook may still rewrite a compaction's messages on the way up, so the conversation becomes them only after this chain returns:
328 // a row appended inside it would join the conversation being replaced. The full row is owed instead, and paid at the next prompt
329 // or main-loop model request, whichever comes first. A precompute installs nothing.
330 // ponytail: the charter rows are summarized with the rest: e.messages is declared in the rows form, which leaves meta rows out
331 // (measured on $.session.messages()), and the event offers no other form to drop them from
332 on('session.compact', async ($, e, next) => {
333 const r = await next(e)
334 if (e.agentId === undefined && r.messages && e.trigger !== 'precompute') st.owed = 'full'
335 return r
336 })
337
338 // Every main-loop turn, a prompt's or one begun without one (a task notification, a peer's message, a sub-agent's handback).
339 on('turn.start', async ($, e, next) => {
340 const r = await next(e)
341 void record($, st, { event: 'turn.start' })
342 return r
343 })
344
345 on('turn.step', async function* ($, e, next) {
346 if (e.agentId !== undefined && !st.kids.has(e.agentId)) await child($, st, e.agentId)
347 if (st.owed && e.agentId === undefined) await settle($, st)
348 return yield* next(e)
349 })
350
351 // A sub-agent's run raises no turn.start, and its turn.complete carries its id.
352 on('turn.complete', async ($, e, next) => {
353 const r = await next(e)
354 if (e.agentId === undefined) {
355 st.pending.clear()
356 st.asks.clear() // the turn's end ends the record's wait: a call still out returns to none
357 void record($, st, { event: 'turn.complete', reason: e.reason, answer: e.answer })
358 void mirror($, st)
359 } else if (st.kids.delete(e.agentId)) void record($, st, { event: 'child.stop', agent_id: e.agentId })
360 return r
361 })
362
363 // A call that goes to the mode's decider waits for a person only once its dialog shows: auto mode's classifier settles most with
364 // none. AskUserQuestion always shows its dialog. A query ($.tool.check) carries no call id and asks no one.
365 on('tool.check', async ($, e, next) => {
366 const r = await next(e)
367 if (r.decision !== 'ask' || e.tool_use_id === undefined) return r
368 if (e.tool !== 'AskUserQuestion') st.pending.set(e.tool_use_id, asked(e.tool, e.agentId, e.input))
369 else {
370 st.asks.add(e.tool_use_id)
371 void record($, st, { event: 'ask', kind: 'question' })
372 }
373 return r
374 })
375
376 // Raised as a dialog is about to show, or as a call that cannot show one is about to be refused. A settings hook that answers it
377 // asks no one.
378 on('classic.PermissionRequest', async ($, e, next) => {
379 const r = await next(e)
380 const key = asked(e.tool_name, e.agent_id, e.tool_input)
381 const id = [...st.pending].find(([, k]) => k === key)?.[0]
382 if (id === undefined) return r
383 st.pending.delete(id)
384 if (r.decision === undefined) {
385 st.asks.add(id)
386 void record($, st, { event: 'ask', kind: 'permission' })
387 }
388 return r
389 })
390
391 // A call that asked returns once it has run, been refused, or met an Esc at the dialog. No event marks a person's answer, so an
392 // approved call's wait lasts its run. The wait ends when no such call is still out.
393 on('tool.call', async ($, e, next) => {
394 const r = await next(e)
395 if (e.tool_use_id !== undefined) st.pending.delete(e.tool_use_id)
396 if (e.tool_use_id !== undefined && st.asks.delete(e.tool_use_id) && st.asks.size === 0) void record($, st, { event: 'answered' })
397 return r
398 })
399
400 // The charter tool, answered here so core never runs it: no check, no dialog. The write waits on the one queue, behind the record's
401 // events, and the call waits for that write alone. That wait is no $ call, so it counts against the hook's 10 s budget, past which
402 // core would answer the call with a failure of its own: the write's run stops at 8 s, so a timeout still reaches the model as its why.
403 // ponytail: runs queued ahead of the write count against the same budget; each takes a fraction of a second
404 on('tool.call', { tool: TOOL }, async ($, e) => {
405 if (e.agentId !== undefined) return { deny: 'only the main session writes the charter' }
406 const fields = { focus: e.focus, record: e.record, add_goals: e.add_goals, block: e.block, clear_block: e.clear_block }
407 return answer(await queue($, st, { cmd: 'write', stdin: () => JSON.stringify(fields), timeoutMs: 8_000, what: 'charter not written' }),
408 { failed: 'the charter was not written', json: 'the charter write answered no JSON' })
409 })
410
411 // The worker tool, answered the same way. board.py runs `claude --bg` from the project root, which returns at once and is cut off at 6 s.
412 on('tool.call', { tool: WORKER_TOOL }, async ($, e) => {
413 if (e.agentId !== undefined) return { deny: 'only the main session starts a worker' }
414 const fields = { task: e.task, prompt: e.prompt, close: e.close }
415 return answer(await queue($, st, { cmd: 'worker', stdin: () => JSON.stringify(fields), timeoutMs: 50_000, what: 'worker not started' }),
416 { failed: 'the worker was not started', json: 'the worker launch answered no JSON' })
417 })
418
419 // A goal task's status onto its goal once the update has run, queued, so two updates in parallel tick one after the other.
420 on('tool.call', { tool: 'TaskUpdate' }, async ($, e, next) => {
421 const r = await next(e)
422 if (r.deny === undefined && r.isError !== true) void queue($, st, { cmd: 'tick', args: [e.taskId], timeoutMs: 10_000, what: `goal of task ${e.taskId} not ticked` })
423 return r
424 })
425}
426hooks/jira-links.ts 48 lines1import type { On, PluginOptions } from 'claude-code'
2
3// Jira issue keys and GitHub refs (`repo #12`) in the model's replies, drawn as links to their issues. The drawing alone changes:
4// the stored message and the model's context keep the bare text.
5
6// Spans that must stay as written come first in the alternation; a key or ref outside them is one of the last alternatives. The
7// lookbehind keeps one inside a URL path or a longer token (`…/browse/PROJ-1`, `X-PROJ-1`, `my-repo #1`) from matching.
8const spans = (keys: readonly string[], repos: readonly string[]) =>
9 new RegExp(
10 [
11 String.raw`(?:\`{3,}|~{3,})[\s\S]*?(?:\`{3,}|~{3,}|$)`, // fenced block
12 String.raw`(\`+)[^\n]*?\1`, // inline code
13 String.raw`\[[^\]]*\]\([^)]*\)`, // markdown link
14 String.raw`<[^>\s]*>`, // autolink
15 String.raw`https?://[^\s<>)\]]*`, // bare URL
16 ...(keys.length ? [String.raw`(?<![\w/.-])(?<key>(?:${keys.join('|')})-\d+)\b`] : []),
17 ...(repos.length ? [String.raw`(?<![\w/.-])(?<repo>${repos.map(r => r.replaceAll('.', '\\.')).join('|')}) #(?<num>\d+)\b`] : []),
18 ].join('|'),
19 'g',
20 )
21
22const listed = (given: unknown) => (Array.isArray(given) ? given : String(given ?? '').split(/[\s,]+/)).map(k => String(k).trim())
23
24// It hooks nothing until Jira (a site and keys) or GitHub repos are configured. Each list comes as a list, or as one string with
25// commas or spaces between them. An entry not of its expected shape is dropped, so it never reaches the pattern as regex syntax.
26// Only a listed repo's name links, so `issue #193` or `PR #198` stays as written.
27export function issueLinks(on: On, options: PluginOptions): void {
28 const site = String(options.jiraUrl ?? '').trim().replace(/\/+$/, '')
29 const keys = site ? listed(options.jiraProjectKeys).filter(k => /^[A-Z][A-Z0-9_]*$/.test(k)) : []
30 const owners = new Map(
31 listed(options.githubRepos)
32 .filter(r => /^[\w.-]+\/[\w.-]+$/.test(r))
33 .map(r => r.split('/').reverse() as [string, string]),
34 )
35 if (keys.length === 0 && owners.size === 0) return
36 const pattern = spans(keys, [...owners.keys()])
37
38 on('ui.render', { component: 'AssistantMessage' }, ($, e, next) => {
39 const text = e.props.text.replace(pattern, (...args) => {
40 const { key, repo, num } = args.at(-1) as { key?: string; repo?: string; num?: string }
41 if (key !== undefined) return `[${key}](${site}/browse/${key})`
42 if (repo !== undefined) return `[${repo} #${num}](https://github.com/${owners.get(repo)}/${repo}/issues/${num})`
43 return args[0] as string
44 })
45 return next({ ...e, props: { ...e.props, text } })
46 })
47}
48hooks/session-links.tsx 78 lines1import type { EngineInterface, On } from 'claude-code'
2
3// Session ids in the model's replies that name a row of the board's sidebar, drawn as links: a click opens the row's session in the
4// right pane, as a click on the row does. Only a Markdown the mod draws itself hears a click, so such a block is drawn by the mod,
5// with the engine's reply bullet, and every other block as the engine draws it.
6
7const ID = '[0-9a-f]{8}(?:-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})?'
8const WHOLE = new RegExp(`^${ID}$`)
9// A link the surface would open on a modified click: .invalid names no host, so that opens nothing.
10const HREF = 'https://workstreams.invalid/session/'
11
12// As jira-links.ts reads a reply, except that an inline code span holding only an id links too: most ids are written as one.
13const SPANS = new RegExp(
14 [
15 String.raw`(?:\`{3,}|~{3,})[\s\S]*?(?:\`{3,}|~{3,}|$)`, // fenced block
16 String.raw`(\`+)(?<code>[^\n]*?)\1`, // inline code
17 String.raw`\[[^\]]*\]\([^)]*\)`, // markdown link
18 String.raw`<[^>\s]*>`, // autolink
19 String.raw`https?://[^\s<>)\]]*`, // bare URL
20 String.raw`(?<![\w/.-])(?<id>${ID})(?![\w-])`,
21 ].join('|'),
22 'g',
23)
24
25// The text with each id of a session in `sessions` (full ids) linked, and the links it made.
26export function linkify(text: string, sessions: readonly string[]): { text: string; hrefs: string[] } {
27 const hrefs = new Set<string>()
28 const out = text.replace(SPANS, (span, ...args) => {
29 const { code, id } = args.at(-1) as { code?: string; id?: string }
30 const token = id ?? code?.trim() ?? ''
31 const sid = WHOLE.test(token) ? sessions.find(s => s === token || (token.length === 8 && s.startsWith(token))) : undefined
32 if (sid === undefined) return span
33 hrefs.add(HREF + sid)
34 return `[${span}](${HREF}${sid})`
35 })
36 return { text: out, hrefs: [...hrefs] }
37}
38
39// The session ids of the sidebar's rows, from the click map board.py's watch writes, where board.py's board_dir() keeps it.
40async function onBoard($: EngineInterface): Promise<string[]> {
41 try {
42 const project = (await $.session.cwd()).replace(/\/\.worktrees\/.*$/, '').replace(/[^A-Za-z0-9-]/g, '-')
43 const rows = JSON.parse(await $.fs.read(`${await $.env.get('HOME')}/.claude/projects/${project}/board/tree-rows.json`)) as Record<string, { session_id?: string | null; goal?: unknown; pin?: unknown }>
44 return Object.values(rows).flatMap(e => (e.session_id && e.goal === undefined && e.pin === undefined ? [e.session_id] : []))
45 } catch {
46 return [] // no sidebar has run for this project
47 }
48}
49
50async function open($: EngineInterface, sid: string): Promise<void> {
51 try {
52 const cwd = await $.session.cwd()
53 const run = await $.process.run(['uv', 'run', '--no-project', `${$.plugin.root}/hooks/board.py`, 'open-session', sid], { cwd, env: { CLAUDE_PROJECT_DIR: cwd }, timeoutMs: 120_000 })
54 if (run.exitCode !== 0) throw new Error(`board.py exited ${run.exitCode}: ${run.stderr.trim().split('\n').at(-1) ?? ''}`)
55 } catch (err) {
56 $.ui.log(`session ${sid} not opened: ${err instanceof Error ? err.message : String(err)}`, { to: 'debug' })
57 }
58}
59
60// A summary block is left to the engine, which marks it as one.
61export function sessionLinks(on: On): void {
62 on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
63 if (e.props.isSummary) return next(e)
64 const { text, hrefs } = linkify(e.props.text, await onBoard($))
65 if (hrefs.length === 0) return next(e)
66 const { Box, Text, Markdown } = $.ui.resolve(e)
67
68 return (
69 <Box flexDirection="row">
70 <Box minWidth={2} flexShrink={0}><Text>{e.props.isFirstOfReply ? '⏺' : ''}</Text></Box>
71 <Box flexGrow={1} flexShrink={1}>
72 <Markdown key="session-links" text={text} pressableLinks={hrefs} onLinkPress={link => void open($, link.href.slice(HREF.length))} />
73 </Box>
74 </Box>
75 )
76 })
77}
78