SLOPSHOPPER

Taskrail

A live wave board of your session's plan above the prompt: waves, tasks and their state, kept current by Claude through three tools and switched with /taskrail.

bandguardcommandtooltimeragents
v0.3.0MITupdated 2026-10-24drolosoft/taskrail
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · taskrail
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /taskrail ⎿ taskrail: board: mode full (no plan in this session) ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

<h1 align="center">taskrail</h1>

<a href="https://github.com/drolosoft/taskrail/releases/latest"><img src="https://img.shields.io/github/v/release/drolosoft/taskrail?label=release" alt="GitHub Release"></a> <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a> <img src="https://img.shields.io/badge/Claude%20Code-2.1.287%2B-lightgrey.svg" alt="Claude Code 2.1.287+">

🛤️ A live board of your session's plan, right above the prompt.

taskrail is a Claude Code mod. When Claude works through a plan with several tasks, the board shows the waves, the tasks under each one and the state each task is in, updated by Claude itself as the work moves. You pick how much of it you see with /taskrail.


Install

claude plugin marketplace add drolosoft/claude-plugins
claude plugin install taskrail@drolosoft-marketplace

Start a new session, or run /reload-plugins. /plugin then lists it as 1 mod active · taskrail.

For one session with a local copy: claude --plugin-dir ./taskrail.

Modes

/taskrail …What the band shows
fullThe whole board: header, description, rail, tasks, key line and progress bar (the default)
barOne line: project, plan, time, a station per wave, the goal and ten tiles
bothThe whole board, and Claude also pastes it in the chat at every milestone
offNothing in the band; Claude shows the board in the chat only when you ask

/taskrail alone answers the current mode. The choice is kept across sessions.

If you already have a skill or a command named taskrail, Claude Code keeps yours and refuses the mod's. The board and the three tools still work, in the mode last chosen; rename yours to get /taskrail back.

How Claude uses it

The mod registers three tools. Claude calls them on its own when it runs a plan with several tasks; you can also ask for them by name.

ToolWhat it does
planStarts (or replaces) the board: project, title, goal, description and the waves with their task ids. Every task starts 🥚.
setUpdates task icons by id, the key line, the goal, the title or the description. Its result tells Claude what the current mode asks of the chat. When a wave that has begun still has two or more tasks in 🥚 and at most one running, the result adds one line saying so (never on the board), so Claude starts the independent ones at once.
showReturns the board as text, for the chat.

Icons: 🥚 pending · 🔧 working · 👀 in review · 🩹 fixing · 🧪 testing · 🟩 merged · 🚀 shipped · 🔑 needs you · 👻 missing · 🧟 stale · 💥 broken · 🥱 idle · 🛑 stopped. The header counts each of these icons in use. A wave's station is 🟩 when every task is merged; otherwise it shows the most pressing state among its tasks, in this order: 🛑 🔑 💥 🧟 👻 🩹 👀 🧪 🔧 🚀, else 🥚. The "N of M" counts 🟩 only; the tiles are green for 🟩, yellow for the running states (🔧 👀 🩹 🧪, at least one tile while anything runs) and red for the rest. plan and set also take a note, the key line under the rail. set reads ✅ (and ✔️, ☑️) as 🟩; any other icon outside this list is refused, the task keeps its icon and the result names the valid ones.

Each task keeps the time of its last move, when it first left 🥚 and when it reached 🟩 or 🚀. The full board and show print it after the task: how long it has run while it is under way (🔧 T4 · 12m), how long it took once it is done (🟩 T4 · 48m), in minutes under an hour and 1h12m above; nothing for a pending task or under a minute. A wave's column widens to fit its times. The header keeps the time of the last update, and the bar mode shows no task times. A plan saved by an earlier version draws as before: the tasks it had under way show no time, and its pending ones are timed once they start.

Running the waves fast

The plugin ships a skill, running-waves, that Claude loads when it runs a plan with several tasks. It holds the rules that keep the waves fast, measured on real runs: subagents never wait on each other's processes, each worktree has its own port and test server, anything long runs in the background, only the tests of what changed run while iterating, a server is not rebuilt when nothing changed, briefs are short, and independent plans run at once. Several tasks in 🔧 at the same time is the board working as intended; one 🔧 at a time means the waves are being run in series.

What moves on its own

Claude does not have to report everything. The mod listens to the engine's own agent events and moves a task when they are clear enough:

EventWhat the board does
A subagent is spawned whose description or name carries a task id (Implement T4)ties the agent to the task; a task nobody was on (🥚 🥱 👻 🧟) becomes 🔧
That agent asks you for a permissionthe task becomes 🔑 while it waits
The agent calls its next toolthe task takes back the icon it had; with nothing held, the call counts as news of the task
The agent's turn endsan answer hands a working task (🔧 🔑 🧟) to 👀; an error or a refusal makes it 💥; an interruption 🛑
Fifteen minutes go by with no set and no agent event touching a task in 🔧 👀 🩹 🧪the task becomes 🧟; the key line stays as it was. The next set or event moves it on as usual

The stale check runs once a minute, and also whenever the board is drawn. A task waiting for you (🔑) never goes stale.

A task that is 🟩 or 🚀 is never touched, and set still has the last word: an icon Claude sets stays until an event with something new to say. Name the task id in each Agent call's description and the board follows it.

The plan lives in the session's plugin state and in the plugin store under the session id, so it survives /resume, including a restart of Claude Code followed by --resume. /clear drops the plan along with the conversation, and a new session starts with no plan. The ties between agents and tasks live in the session only: agents do not survive a resume.

What it reads and writes

Nothing outside Claude Code. taskrail opens no network connection and reads or writes no file. It keeps the plan in the plugin's session state and in the plugin store, and draws it in the band above the prompt. When one of its hooks fails (a plan the renderer cannot draw, say) it writes one dim line under its name in the transcript and lets the event through; it never takes a turn, a tool call or the band down with it.

Requirements

  • Claude Code 2.1.287 or later.
  • Works in the terminal, the IDE extensions and the desktop app's Code tab. Mods do not run in the VS Code chat panel, in claude -p, or in cloud sessions.

Development

claude plugin validate --strict .
claude plugin test .
claude --plugin-dir .

Saving a file reloads the mod in a session started with --plugin-dir. Do not load the same mod from --plugin-dir and from the marketplace in one session: two plugins named taskrail would register the same tools twice.

Contributing

See CONTRIBUTING.md. Security reports go by email, see SECURITY.md.

License

MIT. Copyright (c) 2026 Drolosoft.

Source 4 files
hooks/register.tsx 498 lines
1// The wave board as a mod: the plan of this session lives in `$.state`
2// (reactive, survives a hot reload) with a copy in `$.store` per session id
3// (survives /resume and a restart; /clear drops it). The band above the
4// prompt draws it; `/taskrail` picks the mode; the model updates it through
5// three tools, and the engine's own agent events move the tasks the model
6// has not reported yet (hooks/auto.ts).
7import { atom, read, update } from 'claude-code'
8import type { EngineInterface, Register } from 'claude-code'
9
10import type { AgentLinks, WaveBoardMode, WaveBoardPlan } from '../types'
11import { onComplete, onPermission, onSpawn, onToolStart } from './auto'
12import type { AutoResult } from './auto'
13import type { Segment } from './board'
14import {
15  DEFAULT_WIDTH,
16  ICONS,
17  STALE_AFTER_MS,
18  applyUpdates,
19  headerLine,
20  isMode,
21  markStale,
22  MODES,
23  modeHint,
24  newPlan,
25  renderBar,
26  renderFull,
27  renderText,
28  serialWarnings,
29} from './board'
30
31// The plan of the session, null until the model creates one.
32const plan = atom({ plugin: 'taskrail', key: 'plan' } as const, null)
33
34// What the band shows; the whole board by default.
35const mode = atom({ plugin: 'taskrail', key: 'mode' } as const, 'full')
36
37// The subagents the engine reported, each tied to a task. Session state
38// only: an agent does not outlive its session, so nothing goes to the store.
39const links = atom({ plugin: 'taskrail', key: 'agents' } as const, {} as AgentLinks)
40
41// The store key of the mode, shared by every session on this machine.
42const MODE_KEY = 'mode'
43
44// How often the timer looks for stale tasks and draws the band again when
45// nothing else moves it: once a minute, the unit the time after each task
46// in flight is counted in, and a fifteenth of the stale limit.
47const TICK_EVERY_MS = 60 * 1000
48
49// The last failure written to the transcript, so a hook that breaks on
50// every event (a render, say) says so once and not on every redraw.
51let lastFailure: string | null = null
52
53/**
54 * The text of an error for a log line, whatever was thrown.
55 *
56 * @param err what a call rejected with
57 * @returns its message, or the value as text
58 */
59function errorText(err: unknown): string {
60  return err instanceof Error ? err.message : String(err)
61}
62
63/**
64 * Writes one dim line under the mod's name when a hook fails, instead of
65 * letting the failure take the event down with it. The same text is not
66 * repeated while it keeps happening.
67 *
68 * @param where the hook that failed
69 * @param err what it threw
70 */
71function noteFailure($: EngineInterface, where: string, err: unknown): void {
72  const text = `taskrail: ${where} failed: ${errorText(err)}`
73
74  if (text === lastFailure) {
75    return
76  }
77
78  lastFailure = text
79  $.ui.log(text)
80}
81
82/** The store key of this session's plan. */
83async function planKey($: EngineInterface): Promise<string> {
84  return `plan:${await $.session.id()}`
85}
86
87/**
88 * Writes the plan to the state (redraws the band) and to the store (so it
89 * outlives /resume and a restart).
90 */
91async function savePlan($: EngineInterface, next: WaveBoardPlan): Promise<void> {
92  await update($, plan, () => next)
93  await $.store.set(await planKey($), next)
94}
95
96/** Loads the session's plan from the store, if any. */
97async function loadPlan($: EngineInterface): Promise<void> {
98  const stored = await $.store.get(await planKey($))
99
100  if (stored !== undefined) {
101    await update($, plan, () => stored as WaveBoardPlan)
102  }
103}
104
105/**
106 * Writes what an event rule decided: the plan when it moved a task, the
107 * links when an agent was tied or released. A rule that changed nothing
108 * writes nothing, so the band is not redrawn for every tool call.
109 */
110async function applyAuto($: EngineInterface, outcome: AutoResult): Promise<void> {
111  if (!outcome.changed) {
112    return
113  }
114
115  await update($, links, () => outcome.links)
116  await savePlan($, outcome.plan)
117}
118
119/**
120 * Turns the plan's stale tasks into 🧟 and writes it, when there are any.
121 * @returns the plan as it stands after the check, null with no plan
122 */
123async function settleStale($: EngineInterface): Promise<WaveBoardPlan | null> {
124  const current = await read($, plan)
125
126  if (current === null) {
127    return null
128  }
129
130  const { plan: marked, stale } = markStale(current, await $.clock.now(), STALE_AFTER_MS)
131
132  if (stale.length > 0) {
133    await savePlan($, marked)
134  }
135
136  return marked
137}
138
139/**
140 * What the timer does once a minute: writes the tasks gone stale, then asks
141 * the band to draw again. Every write of the plan redraws the band; between
142 * writes the minutes after a task in flight would stand still.
143 */
144async function tick($: EngineInterface): Promise<void> {
145  try {
146    await settleStale($)
147  } catch (err) {
148    noteFailure($, 'timer', err)
149  }
150
151  $.ui.invalidate('ui.render')
152}
153
154/** Loads the mode the user last chose, kept in the store across sessions. */
155async function loadMode($: EngineInterface): Promise<void> {
156  const stored = await $.store.get(MODE_KEY)
157
158  if (isMode(stored)) {
159    await update($, mode, () => stored)
160  }
161}
162
163/** The input schema of the `plan` tool. */
164const PLAN_SCHEMA = {
165  type: 'object',
166  properties: {
167    project: { type: 'string', description: 'Short project name, shown first in the bar ("shop", "api").' },
168    title: { type: 'string', description: 'The plan as the header names it: "plan 7 · cleanup".' },
169    goal: { type: 'string', description: 'What the rail ends in, after 🚀: "v0.1.0", "cleanup → main".' },
170    description: { type: 'string', description: 'What the whole plan does, two lines at most; written once.' },
171    note: { type: 'string', description: 'The key line: what is not 🟩 and what is being waited on.' },
172    waves: {
173      type: 'array',
174      description: 'The waves in order; tasks with disjoint files and no consumer relation share a wave.',
175      items: {
176        type: 'object',
177        properties: {
178          name: { type: 'string', description: 'The station letter: A, B, C.' },
179          tasks: { type: 'array', items: { type: 'string' }, description: 'Task ids, short: T1, T2, rev, CI.' },
180        },
181        required: ['name', 'tasks'],
182      },
183    },
184  },
185  required: ['project', 'title', 'goal', 'waves'],
186}
187
188/** The input schema of the `set` tool. */
189const SET_SCHEMA = {
190  type: 'object',
191  properties: {
192    tasks: {
193      type: 'object',
194      description: 'Task id to new icon: {"T4": "🟩", "T5": "👀"}. Icons: 🥚 🔧 👀 🩹 🧪 🟩 🚀 🔑 👻 🧟 💥 🥱 🛑. ✅ is read as 🟩; any other icon is refused and the task keeps its own.',
195      additionalProperties: { type: 'string' },
196    },
197    note: { type: 'string', description: 'Replaces the key line.' },
198    goal: { type: 'string' },
199    title: { type: 'string' },
200    description: { type: 'string' },
201  },
202}
203
204/**
205 * Registers `/taskrail`. The engine refuses the name when the user already
206 * has a skill or a command called `taskrail`, and the refusal throws; the
207 * mod then runs without its command and the mode stays as it was.
208 */
209async function registerCommand($: EngineInterface): Promise<void> {
210  try {
211    await $.command.register({
212      name: 'taskrail',
213      description: 'Wave board above the prompt: off, bar, full or both',
214      argumentHint: '[off|bar|full|both]',
215      immediate: true,
216    })
217  } catch (err) {
218    // The user's own /taskrail stays; the tools still carry the board. One
219    // line says why the mod's command is missing, where a silent catch left
220    // the person guessing.
221    $.ui.log(`taskrail: /taskrail not registered (${errorText(err)}); the tools and the board still work`)
222  }
223}
224
225export const register: Register = on => {
226  on('session.start', async ($, e, next) => {
227    // A refused command must not take the rest of the hook down with it:
228    // without the tools, the mode and the plan there is no board at all,
229    // while without the command the board only keeps the mode it had.
230    await registerCommand($)
231
232    await $.tool.register({
233      name: 'plan',
234      description:
235        'Starts (or replaces) the wave board of this session: the plan\'s project, title, goal, description and its waves of task ids. Every task starts 🥚. The board is drawn above the prompt by the mod. Put the task id in the description of every Agent call for it ("Implement T4"): the mod then follows the engine\'s events on its own (🔧 on spawn, 🔑 while the agent waits for approval, 👀/💥/🛑 when its turn ends); call `set` for what the engine cannot see.',
236      inputSchema: PLAN_SCHEMA,
237    })
238    await $.tool.register({
239      name: 'set',
240      description:
241        'Updates the wave board of this session: task icons by id, the key line (note), goal, title or description. The mod already moves a task from the engine\'s events when its id is in the Agent call\'s description (🔧 spawn, 🔑 waiting for approval, 👀/💥/🛑 at the turn\'s end); call `set` for everything else (🩹 🧪 🟩 🚀, a merge, CI, the note), never by editing files. What you set stays until an event has something new to say. A task in 🔧 👀 🩹 🧪 that nothing touches for 15 minutes turns 🧟 on its own; set it again to move it on. Its result says what the current mode asks of the chat.',
242      inputSchema: SET_SCHEMA,
243    })
244    await $.tool.register({
245      name: 'show',
246      description:
247        'Returns the whole board as text, to paste in the chat inside a fenced code block when the user asks for it (mode off) or at every milestone (mode both). Never in modes bar or full.',
248    })
249
250    await loadMode($)
251    await loadPlan($)
252
253    // The timer runs until the module reloads, which runs this hook again;
254    // /clear and /resume keep it, as they keep the module.
255    $.clock.every(TICK_EVERY_MS, () => {
256      void tick($)
257    })
258
259    return next(e)
260  })
261
262  // /clear, /resume and /branch reset every `$.state` value and fire no
263  // `session.start`; the classic event does, with the source that says so.
264  on('classic.SessionStart', { source: ['resume', 'fork'] }, async ($, e, next) => {
265    await loadMode($)
266    await loadPlan($)
267
268    return next(e)
269  })
270
271  // /clear starts over, and the plan goes with the conversation it belonged
272  // to; only the mode comes back, because it is a preference of the machine.
273  on('classic.SessionStart', { source: 'clear' }, async ($, e, next) => {
274    await loadMode($)
275
276    return next(e)
277  })
278
279  on('command.run', { command: 'taskrail' }, async ($, e) => {
280    const wanted = e.args.trim()
281    const current = await read($, mode)
282
283    if (wanted === '') {
284      const hasPlan = (await read($, plan)) !== null
285      return { text: `board: mode ${current}${hasPlan ? '' : ' (no plan in this session)'}` }
286    }
287
288    if (!isMode(wanted)) {
289      return { text: `usage: /taskrail [${MODES.join('|')}]` }
290    }
291
292    await update($, mode, () => wanted)
293    await $.store.set(MODE_KEY, wanted)
294
295    return { text: `board: mode ${wanted}` }
296  })
297
298  on('tool.call', { tool: 'mcp__taskrail__plan' }, async ($, e) => {
299    if (!Array.isArray(e.waves) || e.waves.length === 0) {
300      return { deny: 'taskrail: a plan needs at least one wave with its task ids.' }
301    }
302
303    const created = newPlan(e, await $.clock.now())
304    // A new plan starts with no agent tied to it: the old links named tasks
305    // of the plan it replaces.
306    await update($, links, () => ({}))
307    await savePlan($, created)
308
309    return { result: `${headerLine(created)}\n${modeHint(await read($, mode))}` }
310  })
311
312  on('tool.call', { tool: 'mcp__taskrail__set' }, async ($, e) => {
313    const current = await read($, plan)
314
315    if (current === null) {
316      return { deny: 'taskrail: no plan in this session yet; create one with mcp__taskrail__plan.' }
317    }
318
319    const now = await $.clock.now()
320    const { plan: updated, unknown, rejected } = applyUpdates(current, e, now)
321
322    // The tasks this call named were touched just now; any other one that
323    // went quiet for too long is flagged in the same write.
324    const { plan: changed } = markStale(updated, now, STALE_AFTER_MS)
325    await savePlan($, changed)
326
327    const warnings: string[] = []
328
329    if (unknown.length > 0) {
330      warnings.push(`unknown task ids, ignored: ${unknown.join(', ')}`)
331    }
332
333    // A refused icon is named with the valid list, so the next call fixes it
334    // instead of leaving a task that never counts as done.
335    if (rejected.length > 0) {
336      const pairs = rejected.map(([id, icon]) => `${id} ${icon}`).join(', ')
337      warnings.push(`unknown icons, tasks kept as they were: ${pairs}. Valid icons: ${ICONS}`)
338    }
339
340    // A wave whose tasks are being started one at a time is told so here,
341    // where the model reads it, and never on the board the person sees.
342    warnings.push(...serialWarnings(changed))
343
344    const warning = warnings.map(line => `\n${line}`).join('')
345
346    return { result: `${headerLine(changed)}${warning}\n${modeHint(await read($, mode))}` }
347  })
348
349  on('tool.call', { tool: 'mcp__taskrail__show' }, async $ => {
350    const current = await settleStale($)
351
352    if (current === null) {
353      return { deny: 'taskrail: no plan in this session yet; create one with mcp__taskrail__plan.' }
354    }
355
356    return { result: renderText(current, DEFAULT_WIDTH, await $.clock.now()) }
357  })
358
359  // The engine's agent events, each one a rule of hooks/auto.ts over the
360  // plan. Every hook passes the event on whatever happens: a rule that
361  // throws is noted once and the spawn, the call or the turn goes through.
362
363  on('agent.spawn', async ($, e, next) => {
364    const result = await next(e)
365
366    try {
367      const current = await read($, plan)
368
369      if (current !== null && result.agentId !== undefined) {
370        const spawn = { agentId: result.agentId, description: e.description, name: e.name }
371
372        await applyAuto($, onSpawn(current, await read($, links), spawn, await $.clock.now()))
373      }
374    } catch (err) {
375      noteFailure($, 'agent.spawn', err)
376    }
377
378    return result
379  })
380
381  on('turn.complete', async ($, e, next) => {
382    try {
383      const current = await read($, plan)
384
385      if (current !== null && e.agentId !== undefined) {
386        const end = { agentId: e.agentId, reason: e.reason }
387
388        await applyAuto($, onComplete(current, await read($, links), end, await $.clock.now()))
389      }
390    } catch (err) {
391      noteFailure($, 'turn.complete', err)
392    }
393
394    return next(e)
395  })
396
397  on('classic.PermissionRequest', async ($, e, next) => {
398    try {
399      const current = await read($, plan)
400
401      if (current !== null && e.agent_id !== undefined) {
402        await applyAuto($, onPermission(current, await read($, links), e.agent_id, await $.clock.now()))
403      }
404    } catch (err) {
405      noteFailure($, 'PermissionRequest', err)
406    }
407
408    return next(e)
409  })
410
411  // Registered after the mod's own tool hooks: those answer without `next`,
412  // and run on the main loop anyway, where there is no agent to release.
413  on('tool.call', async ($, e, next) => {
414    try {
415      const current = await read($, plan)
416
417      if (current !== null && e.agentId !== undefined) {
418        await applyAuto($, onToolStart(current, await read($, links), e.agentId, await $.clock.now()))
419      }
420    } catch (err) {
421      noteFailure($, 'tool.call', err)
422    }
423
424    return next(e)
425  })
426
427  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
428    const current = await read($, plan)
429    const shown: WaveBoardMode = await read($, mode)
430
431    if (e.props.hasSurvey || current === null || shown === 'off') {
432      return next(e)
433    }
434
435    // The rules stretch to the band's width, as the status line script
436    // stretched them to the terminal's; two cells short so nothing wraps.
437    const width = Math.max(40, e.props.bodyColumns - 2)
438    const now = await $.clock.now()
439
440    // The drawing is computed before anything beneath is asked: a plan the
441    // renderer cannot draw (one an older version stored, say) must leave
442    // the band to the other mods, noted once, not take it down.
443    let bar: string
444    let lines: Segment[][]
445    try {
446      // A render hook may not write, so the board is drawn with its stale
447      // tasks already marked and the timer stores them within the minute.
448      const drawn = markStale(current, now, STALE_AFTER_MS).plan
449
450      bar = renderBar(drawn)
451      lines = renderFull(drawn, width, now)
452    } catch (err) {
453      noteFailure($, 'ui.render', err)
454
455      return next(e)
456    }
457
458    // The band is one strip shared by every mod: what the hooks beneath this
459    // one drew (envrail's line, say) is kept, never replaced. When nobody
460    // beneath draws, the engine's own node draws nothing and the board is
461    // alone.
462    const others = await next(e)
463
464    const { Box, Text } = $.ui.resolve(e)
465
466    // The board goes after what it got. Short status lines stay on top,
467    // where a band taller than its rows starts showing, and the board, the
468    // one tree that can outgrow the band, is what scrolls; envrail puts its
469    // line before what it gets, so the order holds whichever of the two
470    // mods the engine calls first.
471    if (shown === 'bar') {
472      return (
473        <Box flexDirection="column">
474          {others}
475          <Box>
476            <Text wrap="truncate-end">{bar}</Text>
477          </Box>
478        </Box>
479      )
480    }
481
482    return (
483      <Box flexDirection="column">
484        {others}
485        {lines.map(segments => (
486          <Box flexDirection="row">
487            {segments.map(segment => (
488              <Text bold={segment.bold === true} wrap="truncate-end">
489                {segment.text}
490              </Text>
491            ))}
492          </Box>
493        ))}
494      </Box>
495    )
496  })
497}
498
hooks/auto.ts 249 lines
1// What the engine's own events say about the tasks, kept free of `$` like
2// the board: a subagent spawned for a task is working on it, a permission
3// request from that agent means the task needs the person, and the end of
4// its turn says how it went. The model's `set` still has the last word;
5// these rules only move a task between the states the events can tell
6// apart, and never touch one that is already merged or shipped.
7import type { AgentLink, AgentLinks, WaveBoardPlan, WaveBoardTask } from '../types'
8import { applyUpdates } from './board'
9
10/** What `turn.complete` says about why a subagent's turn ended. */
11export type EndReason = 'answer' | 'aborted' | 'refusal' | 'error'
12
13/** A plan and its links after a rule ran, and whether anything moved. */
14export type AutoResult = { plan: WaveBoardPlan; links: AgentLinks; changed: boolean }
15
16// Work that is over: no event moves a task out of these.
17const SETTLED = new Set(['🟩', '🚀'])
18
19// A task nobody is on yet: a spawn for it makes it 🔧. A task already in
20// review, testing or fixing keeps its icon when a second agent (a reviewer,
21// say) is spawned for it; the link is kept all the same.
22const FRESH = new Set(['🥚', '🥱', '👻', '🧟'])
23
24// The states in which a task can be held up by a permission prompt.
25const RUNNING = new Set(['🔧', '👀', '🩹', '🧪'])
26
27// The states a finished turn hands over to review from: the agent was
28// working, waiting for the person while working, or quiet long enough for
29// the board to call the task stale.
30const WORKING = new Set(['🔧', '🔑', '🧟'])
31
32// A linked agent's tool calls keep its task from going stale, but writing
33// the plan on every call would redraw the band for each one: a touch older
34// than a minute is renewed, a newer one is left as it is.
35const TOUCH_EVERY_MS = 60 * 1000
36
37/**
38 * The regular expression that finds a task id as a whole word, so `T1`
39 * does not match inside `T12` and `rev` not inside `review`. Ids may
40 * carry characters that mean something in a pattern (`CI/CD`), hence the
41 * escape.
42 */
43function wordPattern(id: string): RegExp {
44  const escaped = id.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
45
46  return new RegExp(`(^|[^A-Za-z0-9_])${escaped}([^A-Za-z0-9_]|$)`)
47}
48
49/** Every task id of the plan, longest first so `T12` wins over `T1`. */
50function taskIds(plan: WaveBoardPlan): string[] {
51  const ids = plan.waves.flatMap(wave => wave.tasks.map(task => task[0]))
52
53  return ids.sort((a, b) => b.length - a.length)
54}
55
56/**
57 * The task a spawn is for: the first id found as a whole word in any of
58 * the texts (the Agent call's description, then its name), or null when
59 * the spawn names none.
60 *
61 * @param plan the plan whose ids are looked for
62 * @param texts the spawn's description and name, in that order
63 */
64export function taskOf(plan: WaveBoardPlan, ...texts: Array<string | undefined>): string | null {
65  const ids = taskIds(plan)
66
67  for (const text of texts) {
68    if (text === undefined || text === '') {
69      continue
70    }
71
72    const found = ids.find(id => wordPattern(id).test(text))
73
74    if (found !== undefined) {
75      return found
76    }
77  }
78
79  return null
80}
81
82/** The task with that id, or undefined when the plan has none. */
83function taskById(plan: WaveBoardPlan, id: string): WaveBoardTask | undefined {
84  for (const wave of plan.waves) {
85    const task = wave.tasks.find(candidate => candidate[0] === id)
86
87    if (task !== undefined) {
88      return task
89    }
90  }
91
92  return undefined
93}
94
95/** The icon of a task, or undefined when the plan has no such id. */
96export function iconOf(plan: WaveBoardPlan, id: string): string | undefined {
97  return taskById(plan, id)?.[1]
98}
99
100/** The result of a rule that moved nothing. */
101function unchanged(plan: WaveBoardPlan, links: AgentLinks): AutoResult {
102  return { plan, links, changed: false }
103}
104
105/** The plan with one task's icon replaced, through the same path `set` uses. */
106function withIcon(plan: WaveBoardPlan, id: string, icon: string, now: number): WaveBoardPlan {
107  return applyUpdates(plan, { tasks: { [id]: icon } }, now).plan
108}
109
110/**
111 * A subagent started. Finds its task by the spawn's words and links the
112 * agent to it; the task becomes 🔧 when nobody was on it yet.
113 *
114 * @param spawn the agent's id and the words the Agent call gave it
115 * @param now epoch milliseconds of the event
116 */
117export function onSpawn(
118  plan: WaveBoardPlan,
119  links: AgentLinks,
120  spawn: { agentId: string; description?: string; name?: string },
121  now: number,
122): AutoResult {
123  const task = taskOf(plan, spawn.description, spawn.name)
124
125  if (task === null) {
126    return unchanged(plan, links)
127  }
128
129  const link: AgentLink = { task, before: null }
130  const linked = { ...links, [spawn.agentId]: link }
131  const icon = iconOf(plan, task)
132
133  if (icon === undefined || !FRESH.has(icon)) {
134    return { plan, links: linked, changed: true }
135  }
136
137  return { plan: withIcon(plan, task, '🔧', now), links: linked, changed: true }
138}
139
140/**
141 * A linked agent asked the person for a permission: its task needs them.
142 * The icon it had is kept in the link, so the next tool call of the same
143 * agent can give it back once the person has answered.
144 */
145export function onPermission(plan: WaveBoardPlan, links: AgentLinks, agentId: string, now: number): AutoResult {
146  const link = links[agentId]
147
148  if (link === undefined) {
149    return unchanged(plan, links)
150  }
151
152  const icon = iconOf(plan, link.task)
153
154  if (icon === undefined || !RUNNING.has(icon)) {
155    return unchanged(plan, links)
156  }
157
158  const held = { ...links, [agentId]: { task: link.task, before: icon } }
159
160  return { plan: withIcon(plan, link.task, '🔑', now), links: held, changed: true }
161}
162
163/**
164 * A linked agent that calls a tool is still on its task: the task's touch
165 * is renewed, so it does not go stale while the agent works. A touch less
166 * than a minute old is left alone, and a task out of the running stages
167 * (done, waiting, stale) is not the tool call's to change.
168 */
169function keepFresh(plan: WaveBoardPlan, links: AgentLinks, id: string, now: number): AutoResult {
170  const task = taskById(plan, id)
171
172  if (task === undefined || !RUNNING.has(task[1])) {
173    return unchanged(plan, links)
174  }
175
176  const touchedAt = task[2]?.touchedAt
177
178  if (touchedAt !== undefined && now - touchedAt < TOUCH_EVERY_MS) {
179    return unchanged(plan, links)
180  }
181
182  return { plan: withIcon(plan, id, task[1], now), links, changed: true }
183}
184
185/**
186 * A linked agent called a tool: whatever permission it waited for was
187 * answered, so a task still marked 🔑 by `onPermission` takes back the icon
188 * it had. A task the model moved meanwhile keeps the model's choice; the
189 * held icon is dropped either way. With nothing held, the call only keeps
190 * the task fresh.
191 */
192export function onToolStart(plan: WaveBoardPlan, links: AgentLinks, agentId: string, now: number): AutoResult {
193  const link = links[agentId]
194
195  if (link === undefined) {
196    return unchanged(plan, links)
197  }
198
199  if (link.before === null) {
200    return keepFresh(plan, links, link.task, now)
201  }
202
203  const released = { ...links, [agentId]: { task: link.task, before: null } }
204
205  if (iconOf(plan, link.task) !== '🔑') {
206    return { plan, links: released, changed: true }
207  }
208
209  return { plan: withIcon(plan, link.task, link.before, now), links: released, changed: true }
210}
211
212/**
213 * A linked agent's turn ended. An answer hands a task that was being
214 * worked on (or had gone quiet long enough to be stale) to review; an
215 * error or a refusal breaks it and an interruption stops it, from any
216 * state that is not settled. The link stays: a message can wake the same
217 * agent later.
218 */
219export function onComplete(
220  plan: WaveBoardPlan,
221  links: AgentLinks,
222  end: { agentId: string; reason: EndReason },
223  now: number,
224): AutoResult {
225  const link = links[end.agentId]
226
227  if (link === undefined) {
228    return unchanged(plan, links)
229  }
230
231  const icon = iconOf(plan, link.task)
232
233  if (icon === undefined || SETTLED.has(icon)) {
234    return unchanged(plan, links)
235  }
236
237  if (end.reason === 'answer') {
238    if (!WORKING.has(icon)) {
239      return unchanged(plan, links)
240    }
241
242    return { plan: withIcon(plan, link.task, '👀', now), links, changed: true }
243  }
244
245  const outcome = end.reason === 'aborted' ? '🛑' : '💥'
246
247  return { plan: withIcon(plan, link.task, outcome, now), links, changed: true }
248}
249
hooks/board.ts 606 lines
1// The board itself: pure functions from a plan to the lines the band draws,
2// kept free of `$` so the hooks module can import it and `claude plugin
3// validate` still sees every call.
4import type { PlanInput, SetInput, TaskTimes, WaveBoardMode, WaveBoardPlan, WaveBoardTask, WaveBoardWave } from '../types'
5
6/** A run of text in a row, bold when the task is in flight. */
7export type Segment = { text: string; bold?: boolean }
8
9/** The four modes `/taskrail` accepts, in the order the usage line lists them. */
10export const MODES: readonly WaveBoardMode[] = ['off', 'bar', 'full', 'both']
11
12// Every emoji the board uses is two terminal cells wide; everything else
13// (box drawing, Latin, digits) is one. Text glyphs never carry state.
14const EMOJI = new Set([...'🥚🔧👀🩹🧪🟩🚀🔑👻🧟💥🥱🛑◾🟨🟥'])
15
16// The order in which the header counts the icons: every icon the model
17// may set, finished work first and pending last.
18const ORDER = ['🟩', '🔧', '👀', '🩹', '🧪', '🚀', '🔑', '💥', '🛑', '👻', '🧟', '🥱', '🥚']
19
20// The same list as text, for the message that names a refused icon.
21export const ICONS = ORDER.join(' ')
22
23// A wave's station shows its most urgent state: a stop first, then the
24// events, the running stages and a shipped task, in this order.
25const URGENCY = ['🛑', '🔑', '💥', '🧟', '👻', '🩹', '👀', '🧪', '🔧', '🚀']
26
27// The stages that count as "running" for the yellow tiles of the bar.
28const RUNNING = new Set(['🔧', '👀', '🩹', '🧪'])
29
30// Work that is over: a task's clock stops when it reaches one of these.
31const DONE = new Set(['🟩', '🚀'])
32
33// Icons a model writes for "done" out of habit. They mean 🟩 here: the
34// board only counts the square, so a ✅ left as it was would read as a task
35// that never finished.
36const ALIASES: Record<string, string> = { '✅': '🟩', '✔️': '🟩', '✔': '🟩', '☑️': '🟩', '☑': '🟩' }
37
38/**
39 * The icon the board will store for one the model sent, or null when the
40 * board does not know it and must refuse it.
41 */
42export function normalizeIcon(icon: string): string | null {
43  const known = ALIASES[icon] ?? icon
44
45  return ORDER.includes(known) ? known : null
46}
47
48// Width of the rules when the band cannot tell its own width.
49export const DEFAULT_WIDTH = 66
50
51// Cells of a task column and of its station on the rail, unless a task's
52// time needs more.
53const COLUMN = 10
54
55// One minute in milliseconds: the board counts a task's time in minutes and
56// shows nothing for less, where "0m" would only be noise.
57const MINUTE_MS = 60 * 1000
58
59// How long a task may sit in a running stage (🔧 👀 🩹 🧪) with no `set` and
60// no agent event touching it before it turns 🧟 on its own. A quarter of an
61// hour: longer than the build or test run a working agent waits on between
62// two tool calls, short enough to flag a task nobody is on before the wave
63// is held up for long.
64export const STALE_AFTER_MS = 15 * 60 * 1000
65
66/**
67 * Terminal cells a string occupies.
68 * @param text plain text, no ANSI codes
69 */
70export function cells(text: string): number {
71  let count = 0
72
73  for (const char of text) {
74    count += EMOJI.has(char) ? 2 : 1
75  }
76
77  return count
78}
79
80/**
81 * A cell padded with spaces up to `width` terminal cells.
82 * @param cell the cell's text
83 * @param width the column width in cells, ten by default
84 */
85export function pad(cell: string, width = 10): string {
86  return cell + ' '.repeat(Math.max(0, width - cells(cell)))
87}
88
89/**
90 * A wave's station icon: green when every task is merged, else the most
91 * urgent event or stage among its tasks, else pending.
92 */
93export function aggregate(icons: readonly string[]): string {
94  if (icons.length > 0 && icons.every(icon => icon === '🟩')) {
95    return '🟩'
96  }
97
98  for (const candidate of URGENCY) {
99    if (icons.includes(candidate)) {
100      return candidate
101    }
102  }
103
104  return '🥚'
105}
106
107/** Every task icon of the plan, wave by wave. */
108function allIcons(plan: WaveBoardPlan): string[] {
109  return plan.waves.flatMap(wave => wave.tasks.map(task => task[1]))
110}
111
112/** Icons of one wave. */
113function waveIcons(wave: WaveBoardWave): string[] {
114  return wave.tasks.map(task => task[1])
115}
116
117/** Epoch milliseconds as `HH:MM` in the machine's own time zone. */
118export function clock(ms: number): string {
119  const date = new Date(ms)
120  const hours = String(date.getHours()).padStart(2, '0')
121  const minutes = String(date.getMinutes()).padStart(2, '0')
122
123  return `${hours}:${minutes}`
124}
125
126/**
127 * A span of time as the board prints it after a task: whole minutes under
128 * an hour (`12m`), hours and two-digit minutes above (`1h12m`, `2h05m`).
129 * @param ms the span in milliseconds
130 */
131export function duration(ms: number): string {
132  const minutes = Math.floor(ms / MINUTE_MS)
133
134  if (minutes < 60) {
135    return `${minutes}m`
136  }
137
138  const hours = Math.floor(minutes / 60)
139  const rest = String(minutes % 60).padStart(2, '0')
140
141  return `${hours}h${rest}m`
142}
143
144/**
145 * What the board prints after a task: how long it has run while it is
146 * under way, how long it took once it is done.
147 * @param task the task with its times, if it has any
148 * @param now epoch milliseconds of the drawing
149 * @returns the time as ` · 12m`, or null when there is nothing to tell: a
150 *   pending task, a task nobody saw start (a plan stored before the times
151 *   existed), or less than a minute
152 */
153export function taskTime(task: WaveBoardTask, now: number): string | null {
154  const [, icon, times] = task
155
156  if (icon === '🥚' || times === undefined || times.startedAt === null) {
157    return null
158  }
159
160  const end = times.doneAt ?? now
161  const spent = end - times.startedAt
162
163  if (spent < MINUTE_MS) {
164    return null
165  }
166
167  return ` · ${duration(spent)}`
168}
169
170/**
171 * The times of a task whose icon is being written: touched now, started
172 * when it first leaves 🥚, done when it reaches 🟩 or 🚀. A task that leaves
173 * done work again (reopened for a fix) runs again from its first start.
174 * @param task the task before the write
175 * @param icon the icon being written, already normalized
176 * @param now epoch milliseconds of the write
177 */
178export function stamp(task: WaveBoardTask, icon: string, now: number): TaskTimes {
179  const [, before, times] = task
180
181  // A task that was already under way when the plan was stored without
182  // times has no known start: it stays unknown rather than starting now,
183  // which would print a time too short.
184  const isStarting = before === '🥚' && icon !== '🥚'
185  const startedAt = times?.startedAt ?? (isStarting ? now : null)
186
187  // Moving between 🟩 and 🚀 keeps the first finish.
188  const doneAt = DONE.has(icon) ? (times?.doneAt ?? now) : null
189
190  return { touchedAt: now, startedAt, doneAt }
191}
192
193/**
194 * Colour tiles at scale: one tile per `100 / scale` percent of the plan,
195 * green merged, yellow running, red pending or blocked. Never one tile per
196 * task.
197 */
198export function tiles(done: number, running: number, total: number, scale: number): string {
199  const green = total > 0 ? Math.round((done / total) * scale) : 0
200  // At least one yellow tile while anything runs, so the eye sees movement
201  // even when the share rounds to zero.
202  const yellow = running > 0 ? Math.max(1, Math.round((running / total) * scale)) : 0
203  const red = Math.max(0, scale - green - yellow)
204
205  return '🟩'.repeat(green) + '🟨'.repeat(yellow) + '🟥'.repeat(red)
206}
207
208/** The counts the header shows: `🟩 13 · 👀 1 · 🥚 2`, icons in ORDER. */
209export function counts(plan: WaveBoardPlan): string {
210  const icons = allIcons(plan)
211
212  return ORDER.filter(icon => icons.includes(icon))
213    .map(icon => `${icon} ${icons.filter(one => one === icon).length}`)
214    .join(' · ')
215}
216
217/** Merged tasks, running tasks and the total, the three numbers every view needs. */
218export function progress(plan: WaveBoardPlan): { done: number; running: number; total: number } {
219  const icons = allIcons(plan)
220  const done = icons.filter(icon => icon === '🟩').length
221  const running = icons.filter(icon => RUNNING.has(icon)).length
222
223  return { done, running, total: icons.length }
224}
225
226/**
227 * The one-line summary a tool result prints and the header carries:
228 * ` title · done of total · HH:MM · counts`.
229 */
230export function headerLine(plan: WaveBoardPlan): string {
231  const { done, total } = progress(plan)
232
233  return ` ${plan.title} · ${done} of ${total} · ${clock(plan.updatedAt)} · ${counts(plan)}`
234}
235
236/**
237 * The cells each wave's column takes: ten, or as many as its longest task
238 * with its time and one space after it. A plan with no times draws exactly
239 * as it did before they existed.
240 * @param now epoch milliseconds of the drawing
241 */
242export function columnWidths(plan: WaveBoardPlan, now: number): number[] {
243  return plan.waves.map(wave => {
244    const widths = wave.tasks.map(task => {
245      const time = taskTime(task, now)
246
247      if (time === null) {
248        return COLUMN
249      }
250
251      // The glyph, the icon and its space, the id, the time and a gap.
252      return 1 + cells(`${task[1]} `) + cells(task[0]) + cells(time) + 1
253    })
254
255    return Math.max(COLUMN, ...widths)
256  })
257}
258
259/**
260 * The rail: ` main ` then one station per wave, as wide as the wave's
261 * column, and the goal. The rail glyph is `━` up to the last all-green
262 * station and `┄` after it.
263 * @param now epoch milliseconds of the drawing, which sets the columns
264 */
265export function rail(plan: WaveBoardPlan, now: number): string {
266  const greens = plan.waves
267    .map((wave, index) => (aggregate(waveIcons(wave)) === '🟩' ? index : -1))
268    .filter(index => index >= 0)
269  const lastGreen = greens.length > 0 ? Math.max(...greens) : -1
270  const widths = columnWidths(plan, now)
271  let line = ' main '
272
273  plan.waves.forEach((wave, index) => {
274    const icons = waveIcons(wave)
275    const glyph = index <= lastGreen ? '━' : '┄'
276    const merged = icons.filter(icon => icon === '🟩').length
277    // The station and its glyph fill the column the wave's tasks hang in.
278    const width = (widths[index] ?? COLUMN) - 1
279    line += pad(`${aggregate(icons)} ${wave.name} ${merged}/${icons.length} `, width) + glyph
280  })
281
282  return line + `▶ 🚀 ${plan.goal}`
283}
284
285/**
286 * The task rows under the rail: each wave hangs its tasks under its
287 * station, `├` on every row but the last, `╰` on the last, in a column as
288 * wide as the station. Empty slots stay blank: a little drift reads better
289 * than filler squares. Ids of tasks in flight go bold; after the id, the
290 * task's time when it has one.
291 * @param now epoch milliseconds of the drawing
292 */
293export function taskRows(plan: WaveBoardPlan, now: number): Segment[][] {
294  const depth = Math.max(0, ...plan.waves.map(wave => wave.tasks.length))
295  const widths = columnWidths(plan, now)
296  const rows: Segment[][] = []
297
298  for (let row = 0; row < depth; row += 1) {
299    const filled = plan.waves.map((wave, index) => (row < wave.tasks.length ? index : -1))
300    const last = Math.max(...filled)
301    const segments: Segment[] = [{ text: '      ' }]
302
303    plan.waves.slice(0, last + 1).forEach((wave, index) => {
304      const task = wave.tasks[row]
305      const width = widths[index] ?? COLUMN
306
307      if (task === undefined) {
308        segments.push({ text: pad('', width) })
309        return
310      }
311
312      const glyph = row === wave.tasks.length - 1 ? '╰' : '├'
313      const [id, icon] = task
314      const head = `${glyph}${icon} `
315      const time = taskTime(task, now) ?? ''
316      const tail = ' '.repeat(Math.max(0, width - cells(head) - cells(id) - cells(time)))
317
318      segments.push({ text: head })
319      segments.push({ text: id, bold: icon !== '🟩' && icon !== '🥚' })
320
321      if (time !== '') {
322        segments.push({ text: time })
323      }
324
325      segments.push({ text: tail })
326    })
327
328    rows.push(trimRow(segments))
329  }
330
331  return rows
332}
333
334/** Drops the trailing spaces of a row, segment by segment. */
335function trimRow(segments: Segment[]): Segment[] {
336  const trimmed = [...segments]
337
338  while (trimmed.length > 0) {
339    const lastSegment = trimmed[trimmed.length - 1]
340
341    if (lastSegment === undefined || lastSegment.text.trim() !== '') {
342      break
343    }
344
345    trimmed.pop()
346  }
347
348  const lastSegment = trimmed[trimmed.length - 1]
349
350  if (lastSegment !== undefined) {
351    trimmed[trimmed.length - 1] = { ...lastSegment, text: lastSegment.text.replace(/\s+$/, '') }
352  }
353
354  return trimmed
355}
356
357/**
358 * Greedy word wrap at `width` cells.
359 * @returns the lines, none when the text is empty
360 */
361export function wrapText(text: string, width: number): string[] {
362  const words = text.split(/\s+/).filter(word => word !== '')
363  const lines: string[] = []
364  let current = ''
365
366  for (const word of words) {
367    const candidate = current === '' ? word : `${current} ${word}`
368
369    if (cells(candidate) <= width || current === '') {
370      current = candidate
371      continue
372    }
373
374    lines.push(current)
375    current = word
376  }
377
378  if (current !== '') {
379    lines.push(current)
380  }
381
382  return lines
383}
384
385/**
386 * The boxed board: header, description, rail and rows, note and a
387 * thirty-tile bar. No right border, because rows carry different emoji
388 * counts and a right edge would zigzag.
389 * @param width cells of the rules; the band's `bodyColumns` less two
390 * @param now epoch milliseconds of the drawing, for the time of each task
391 *   still under way; the plan's last write when not given
392 */
393export function renderFull(plan: WaveBoardPlan, width = DEFAULT_WIDTH, now = plan.updatedAt): Segment[][] {
394  const { done, running, total } = progress(plan)
395  const rule = '─'.repeat(width)
396  const lines: Segment[][] = []
397
398  lines.push([{ text: `╭${rule}` }])
399  lines.push([
400    { text: '│ ' },
401    { text: plan.title, bold: true },
402    { text: ` · ${done} of ${total} · ${clock(plan.updatedAt)} · ${counts(plan)}` },
403  ])
404
405  // The plan's description, written once and shown under the title on at
406  // most two lines, behind a rule of its own.
407  const description = wrapText(plan.description, width - 4).slice(0, 2)
408
409  if (description.length > 0) {
410    lines.push([{ text: `├${rule}` }])
411    description.forEach(line => lines.push([{ text: `│ ${line}` }]))
412  }
413
414  lines.push([{ text: `├${rule}` }])
415  lines.push([{ text: `│${rail(plan, now)}` }])
416  taskRows(plan, now).forEach(row => lines.push([{ text: '│' }, ...row]))
417  lines.push([{ text: `├${rule}` }])
418  lines.push([{ text: `│ ${plan.note}` }])
419  lines.push([{ text: `│ ${tiles(done, running, total, 30)} ${done}/${total}` }])
420  lines.push([{ text: `╰${rule}` }])
421
422  return lines
423}
424
425/**
426 * The one-line rail for mode `bar`: project, title, time, one station per
427 * wave, the goal and ten tiles.
428 */
429export function renderBar(plan: WaveBoardPlan): string {
430  const { done, running, total } = progress(plan)
431  const stations = plan.waves
432    .map(wave => {
433      const icons = waveIcons(wave)
434      const merged = icons.filter(icon => icon === '🟩').length
435      return `${wave.name} ${aggregate(icons)} ${merged}/${icons.length}`
436    })
437    .join(' ┄ ')
438
439  return ` ${plan.project} · ${plan.title} · ${clock(plan.updatedAt)} · ${stations} ▶ 🚀 ${plan.goal} · ${tiles(done, running, total, 10)} ${done}/${total}`
440}
441
442/**
443 * The whole board as plain text, for the chat when the mode asks for it.
444 * @param width cells of the rules
445 * @param now epoch milliseconds of the drawing; the plan's last write when
446 *   not given
447 */
448export function renderText(plan: WaveBoardPlan, width = DEFAULT_WIDTH, now = plan.updatedAt): string {
449  return renderFull(plan, width, now)
450    .map(row => row.map(segment => segment.text).join(''))
451    .join('\n')
452}
453
454/**
455 * A fresh plan from the tool's input: every task starts pending.
456 * @param now epoch milliseconds of the write
457 */
458export function newPlan(input: PlanInput, now: number): WaveBoardPlan {
459  const waves = input.waves.map(wave => ({
460    name: wave.name,
461    tasks: wave.tasks.map((id): WaveBoardTask => [id, '🥚']),
462  }))
463
464  return {
465    project: input.project,
466    title: input.title,
467    goal: input.goal,
468    description: input.description ?? '',
469    note: input.note ?? '',
470    waves,
471    updatedAt: now,
472  }
473}
474
475/**
476 * The plan after the updates: a new object, the old one untouched. Every
477 * task the input writes an icon to is stamped with `now` (see `stamp`).
478 * @returns the plan, the task ids the input named but the plan lacks, and
479 *   the tasks whose new icon the board refused (they keep their old icon)
480 */
481export function applyUpdates(plan: WaveBoardPlan, input: SetInput, now: number): { plan: WaveBoardPlan; unknown: string[]; rejected: Array<[string, string]> } {
482  const tasks = input.tasks ?? {}
483  const seen = new Set<string>()
484  const rejected: Array<[string, string]> = []
485  const waves = plan.waves.map(wave => ({
486    name: wave.name,
487    tasks: wave.tasks.map((task): WaveBoardTask => {
488      const sent = tasks[task[0]]
489
490      // A task the input does not name keeps its icon and its times.
491      if (sent === undefined) {
492        return task
493      }
494
495      seen.add(task[0])
496
497      // An icon the board cannot count is worse than no update: the task
498      // keeps what it had and the caller is told, so the model corrects it.
499      const icon = normalizeIcon(sent)
500
501      if (icon === null) {
502        rejected.push([task[0], sent])
503        return task
504      }
505
506      return [task[0], icon, stamp(task, icon, now)]
507    }),
508  }))
509  const unknown = Object.keys(tasks).filter(id => !seen.has(id))
510
511  return {
512    plan: {
513      ...plan,
514      waves,
515      note: input.note ?? plan.note,
516      goal: input.goal ?? plan.goal,
517      title: input.title ?? plan.title,
518      description: input.description ?? plan.description,
519      updatedAt: now,
520    },
521    unknown,
522    rejected,
523  }
524}
525
526/**
527 * The tasks gone stale: in a running stage (🔧 👀 🩹 🧪) and touched for
528 * the last time more than `limit` ago. A task waiting for the person (🔑)
529 * is not stale, it is waiting; one with no times (stored before they
530 * existed) has nothing to be old against.
531 * @param now epoch milliseconds of the check
532 * @param limit how old a touch may be, in milliseconds
533 * @returns the ids, wave by wave
534 */
535export function staleTasks(plan: WaveBoardPlan, now: number, limit: number): string[] {
536  return plan.waves
537    .flatMap(wave => wave.tasks)
538    .filter(([, icon, times]) => RUNNING.has(icon) && times !== undefined && now - times.touchedAt > limit)
539    .map(([id]) => id)
540}
541
542/**
543 * The plan with its stale tasks turned 🧟, the key line left as it was:
544 * the board flags them and the model says what happened when it next
545 * writes. The same plan comes back when nothing is stale, so the caller
546 * can tell there is nothing to write.
547 * @param now epoch milliseconds of the check
548 * @param limit how old a touch may be, in milliseconds
549 */
550export function markStale(plan: WaveBoardPlan, now: number, limit: number): { plan: WaveBoardPlan; stale: string[] } {
551  const stale = staleTasks(plan, now, limit)
552
553  if (stale.length === 0) {
554    return { plan, stale }
555  }
556
557  const zombies = Object.fromEntries(stale.map(id => [id, '🧟']))
558
559  return { plan: applyUpdates(plan, { tasks: zombies }, now).plan, stale }
560}
561
562/**
563 * One line per wave that looks run in series: a wave that has begun (one
564 * of its tasks has left 🥚), still has two or more tasks in 🥚 and at most
565 * one in a running stage (🔧 👀 🩹 🧪). A fresh plan and a wave nobody has
566 * started say nothing, so the line never nags before the work begins. For
567 * the model only: the board never shows it.
568 * @returns the lines, none when every wave runs its tasks at once
569 */
570export function serialWarnings(plan: WaveBoardPlan): string[] {
571  return plan.waves.flatMap(wave => {
572    const icons = waveIcons(wave)
573    const pending = icons.filter(icon => icon === '🥚').length
574    const working = icons.filter(icon => RUNNING.has(icon)).length
575    const hasBegun = pending < icons.length
576
577    if (!hasBegun || pending < 2 || working > 1) {
578      return []
579    }
580
581    return [`wave ${wave.name}: ${pending} tasks pending and ${working} working; independent tasks can run at once.`]
582  })
583}
584
585/**
586 * The line the tools append for the model: what the current mode asks of
587 * the chat, so the model never has to read a settings file.
588 */
589export function modeHint(mode: WaveBoardMode): string {
590  switch (mode) {
591    case 'off':
592      return 'mode off: the board is not drawn above the prompt; show it in the chat only when the user asks (mcp__taskrail__show).'
593    case 'bar':
594      return 'mode bar: the one-line rail is already above the prompt; do not draw the board in the chat.'
595    case 'full':
596      return 'mode full: the board is already above the prompt; do not draw it in the chat.'
597    case 'both':
598      return 'mode both: the board is above the prompt AND is drawn in the chat at every milestone and close (mcp__taskrail__show).'
599  }
600}
601
602/** True when `value` is one of the four modes. */
603export function isMode(value: unknown): value is WaveBoardMode {
604  return typeof value === 'string' && (MODES as readonly string[]).includes(value)
605}
606
types/index.d.ts 86 lines
1/**
2 * What the band shows: nothing, the one-line rail, the whole board, or the
3 * whole board here and also in the chat at every milestone (the model's
4 * side of `both`; the mod only tells it the mode).
5 */
6export type WaveBoardMode = 'off' | 'bar' | 'full' | 'both'
7
8/**
9 * When a task moved, in epoch milliseconds. `touchedAt` is the last time
10 * `set` or an agent event wrote its icon (the same icon included);
11 * `startedAt` the moment it first left 🥚, and `doneAt` the moment it
12 * reached 🟩 or 🚀, null while it has not.
13 */
14export type TaskTimes = { touchedAt: number; startedAt: number | null; doneAt: number | null }
15
16/**
17 * One task of the plan: its id as it appears in the map, its state icon
18 * and, once its icon was first written, its times. A tuple: compact in the
19 * store and cheap to compare. Plans stored before the times existed carry
20 * the first two alone.
21 */
22export type WaveBoardTask = [id: string, icon: string, times?: TaskTimes]
23
24/** One wave: the tasks that run in parallel under one station of the rail. */
25export type WaveBoardWave = { name: string; tasks: WaveBoardTask[] }
26
27/** The plan of one session. */
28export type WaveBoardPlan = {
29  project: string
30  title: string
31  goal: string
32  description: string
33  note: string
34  waves: WaveBoardWave[]
35  /** Epoch milliseconds of the last write, shown as HH:MM in the header. */
36  updatedAt: number
37}
38
39/** What the `plan` tool receives: the plan's words and its waves with task ids. */
40export type PlanInput = {
41  project: string
42  title: string
43  goal: string
44  description?: string
45  note?: string
46  waves: { name: string; tasks: string[] }[]
47}
48
49/**
50 * A subagent the engine reported, tied to the task its spawn named.
51 * `before` is the icon the task had when the agent asked for a permission,
52 * to give back once the person has answered; null while nothing is held.
53 */
54export type AgentLink = { task: string; before: string | null }
55
56/** The links of this session, by agent id. Agents do not outlive a session, so neither do these. */
57export type AgentLinks = Record<string, AgentLink>
58
59/** What the `set` tool receives: icons per task id and the optional text fields. */
60export type SetInput = {
61  tasks?: Record<string, string>
62  note?: string
63  goal?: string
64  title?: string
65  description?: string
66}
67
68declare module 'claude-code' {
69  // The mod's own tools, by the name the engine gives them. The type layer
70  // the engine lays only knows the MCP servers a session had connected, so
71  // without these entries `tool.call` and the tests reject the three names.
72  interface McpToolInputs {
73    'mcp__taskrail__plan': PlanInput
74    'mcp__taskrail__set': SetInput
75    'mcp__taskrail__show': {}
76  }
77
78  interface PluginState {
79    'taskrail': {
80      plan: WaveBoardPlan | null
81      mode: WaveBoardMode
82      agents: AgentLinks
83    }
84  }
85}
86