Shows the session's tasks as a CLI-style checklist above the prompt

Draws the session's tasks as a checklist above the prompt:

The first line counts the finished tasks and says what Claude is doing now. A finished task is dimmed and struck through, the one in progress is bold, and the rest wait with an empty box.
claude plugin marketplace add vmlinuz82/claude-mods
claude plugin install task-list@claude-mods
/task-demo fills the checklist with sample tasks, /task-demo clear empties it — handy to check the mod loaded.TaskCreate, TaskUpdate and TodoWrite tools.todo_write, so Claude can keep a todo list there too. In the terminal it adds nothing.× closes the checklist until the list changes: a new task, or one starting or finishing, brings it back.The band also shows the background agents running in the session — under the plan task each one works on, matched by its description (Plan 10 Task 10: referral invites → Task 10; Review Plan 11 tasks 1–4 works on all four and shows once, under Task 1; Fix Plan 11 review findings names the plan but no task, so it sits under the plan, after its tasks), and the rest under „Other agents“:
◼ Task 10 Referral invites · implementing
⠹ referral invites · running 5 min · Bash: npx vitest run apps/client · 9 s ago
Other agents
◦ Investigate the flaky e2e · running 2 min · Read …/e2e/shots-lib.ts · 1 min ago
◦ means running but quiet; the folded line spins too while any agent works.While superpowers runs a plan with subagent-driven development, the band shows that plan, its tasks and the todos of the task in progress:
◼ Plan 3 — Frontend Foundation · 1/7 tasks Details – ×
✔ Task 1 Workspace, shared tooling and packages/ui
◼ Task 2 packages/api — OpenAPI types and the client · fix round 1
◼ Run the type generation
◻ Wire the session client
◻ Task 3 The three app shells
– folds the band to one line, where the work is: □ unfolds it. It stays folded for the rest of the session; every new session starts unfolded.
Phase 7 (7/7) \ Plan (3/3) \ Task (3/7) The three app shells · fix round 1 Details □ ×
Without a phase the line starts at Plan; with only a todo list it reads Todo (2/4) Build.
Details (or /task-tree) opens a pane with the whole tree: every phase and plan, and the running plan's phase down to each task, done, current and to do.
docs/superpowers/plans/*.md, ### Task N: headings) and each plan's ledger (.superpowers/sdd/<plan>/progress.md). Superpowers itself is unchanged..superpowers folder. A plan only prepared ahead (its workspace holds just the ledger with no task entries, plan-path and the task briefs) waits its turn: it becomes the running plan once the started plan before it is finished, the earliest prepared first. An entry for several tasks (Tasks 1–4: review dispatched, Tasks 2, 3 and 5: complete) applies to each. A task is done at its Task N: complete line (colon optional) or at an approved review with no problem reported beside it; a task in progress shows its latest step (implementing, review, fix round 2…). Tasks may run in parallel, each with its own ◼. A task the ledger defers (Ruling: Task 6 … deferred to after Task 7) shows ◐ … · on hold until its next entry, and a task implemented but never reviewed while a later task is under way shows ◐ … · implemented, not reviewed. A task a running agent works on shows ◼ in progress even before its ledger says so. With its reviewer at work (an agent whose description says review) the step reads review. The session's todos sit under the task in progress, or under the plan when several tasks run in parallel. A todo that names a plan (Review Plan 11, merge into main, Plan 12: …) is the session's work across plans: it shows in a Todos section of its own, level with the plan line, not inside the running plan. The folded line names the first task in progress and adds (+n in parallel).Phase 7 · Plan 3 — …, … Phase 4 — … and … (Phase 1.5) all work. A sub-phase joins its main phase (3a–3e are Phase 3, 1.5 is Phase 1) and keeps its label in the plan name: 3e · Affiliate Links. Plans without a phase are listed together.MERGED … line in a ledger marks the whole plan done. Only the running plan can be in progress: another plan with open tasks shows ◐ … · left open in the pane.# SDD ledger — plan: first line are read the same way.hooks/register.tsx 711 lines1import { atom, read, update } from 'claude-code'
2import type { AgentInfo, EngineInterface, Register, RenderInput, RenderElement } from 'claude-code'
3
4import type { PlanTask, PlanView, Task, Todo, TrackedAgent } from '../types'
5import {
6 agentActivity,
7 agentText,
8 ALIVE,
9 describeAction,
10 GRACE_MS,
11 isActive,
12 isStuck,
13 roleUnderTask,
14 SPINNER,
15 SPINNER_SVG,
16 isOnPlan,
17 tasksOfAgent,
18} from './agents'
19import { breadcrumb, isPlanTodo, loadPlanView } from './sdd'
20
21const tasks = atom({ plugin: 'task-list', key: 'tasks' } as const, [])
22const closedOn = atom({ plugin: 'task-list', key: 'closedOn' } as const, null)
23const plan = atom({ plugin: 'task-list', key: 'plan' } as const, null)
24const cwd = atom({ plugin: 'task-list', key: 'cwd' } as const, null)
25// The band folded to one line, for this session only: every new session starts expanded
26const isMinimized = atom({ plugin: 'task-list', key: 'isMinimized' } as const, false)
27const agents = atom({ plugin: 'task-list', key: 'agents' } as const, [])
28const clock = atom({ plugin: 'task-list', key: 'clock' } as const, 0)
29const frame = atom({ plugin: 'task-list', key: 'frame' } as const, 0)
30
31// The clock is read every TICK_MS (for „9 s ago“), the engine's agent list every LIST_EVERY ticks
32const TICK_MS = 5_000
33const LIST_EVERY = 3
34const SPIN_MS = 250
35
36const snapshot = (running: PlanView | null, list: readonly Task[], followed: readonly TrackedAgent[]): string =>
37 JSON.stringify({ running, list, agents: followed.map(agent => agent.id) })
38
39// A tool call that may have written a superpowers ledger: superpowers appends to it from Bash
40const touchesLedger = (input: unknown): boolean => /\.superpowers|progress\.md|sdd-workspace/.test(JSON.stringify(input))
41
42const refreshPlan = async ($: EngineInterface): Promise<void> => {
43 const dir = await read($, cwd)
44 if (dir === null) {
45 return
46 }
47
48 const running = await loadPlanView(
49 {
50 read: path => $.fs.read(path).catch(() => null),
51 list: path => $.fs.list(path).catch(() => []),
52 exists: path => $.fs.exists(path).catch(() => false),
53 },
54 dir,
55 await $.clock.now(),
56 )
57 await update($, plan, () => running)
58}
59
60const MARK = { pending: '◻', in_progress: '◼', completed: '✔', on_hold: '◐', unreviewed: '◐' } as const
61
62let spinner: { cancel: () => void } | null = null
63
64// The terminal spinner steps only while some agent is active
65const keepSpinning = async ($: EngineInterface): Promise<void> => {
66 const at = await $.clock.now()
67 const isWorking = (await read($, agents)).some(agent => isActive(agent, at))
68 if (isWorking && spinner === null) {
69 spinner = $.clock.every(SPIN_MS, () => {
70 void update($, frame, step => step + 1)
71 void keepSpinning($)
72 })
73 }
74 if (!isWorking && spinner !== null) {
75 spinner.cancel()
76 spinner = null
77 }
78}
79
80// The engine's list says which agents still run: finished, failed, stopped and waiting ones leave. Agents are added
81// only when this mod sees them start or act, never from the list alone (it keeps finished agents for a while)
82const syncAgents = async ($: EngineInterface, at: number, listed: readonly AgentInfo[]): Promise<void> => {
83 const statusOf = new Map(listed.map(agent => [agent.id, agent.status]))
84 await update($, agents, followed =>
85 followed.filter(agent => {
86 const status = statusOf.get(agent.id)
87
88 return status === undefined ? at - agent.startedAt < GRACE_MS : ALIVE.includes(status)
89 }),
90 )
91}
92
93const refreshAgents = async ($: EngineInterface): Promise<void> => {
94 const at = await $.clock.now()
95 await syncAgents($, at, await $.agent.list().catch(() => []))
96 await update($, clock, () => at)
97 await keepSpinning($)
98}
99
100let ticks = 0
101
102const tick = async ($: EngineInterface): Promise<void> => {
103 ticks += 1
104 if (ticks % LIST_EVERY === 0) {
105 await refreshAgents($)
106 return
107 }
108 const at = await $.clock.now()
109 await update($, clock, () => at)
110}
111
112const followAgent = async ($: EngineInterface, agentId: string, description: string | null, action: string | null): Promise<void> => {
113 const at = await $.clock.now()
114 const known = (await read($, agents)).find(agent => agent.id === agentId)
115 // An agent started before this mod loaded joins at its first action, named as the engine lists it
116 const name = description ?? known?.description ?? (await $.agent.list().catch(() => [])).find(agent => agent.id === agentId)?.description ?? 'Agent'
117 await update($, agents, followed => [
118 ...followed.filter(agent => agent.id !== agentId),
119 known && description === null
120 ? { ...known, lastAt: at, lastAction: action ?? known.lastAction, toolsRunning: (known.toolsRunning ?? 0) + (action === null ? 0 : 1) }
121 : { id: agentId, description: name, startedAt: known?.startedAt ?? at, lastAt: at, lastAction: action, toolsRunning: action === null ? 0 : 1 },
122 ])
123 await update($, clock, () => at)
124 await keepSpinning($)
125}
126
127// The agent's tool call came back: that is activity too, and the quiet starts from here
128const finishTool = async ($: EngineInterface, agentId: string): Promise<void> => {
129 const at = await $.clock.now()
130 await update($, agents, followed =>
131 followed.map(agent =>
132 agent.id === agentId ? { ...agent, lastAt: at, toolsRunning: Math.max(0, (agent.toolsRunning ?? 0) - 1) } : agent,
133 ),
134 )
135 await update($, clock, () => at)
136 await keepSpinning($)
137}
138
139const PANE = 'task-list'
140const PANE_TITLE = 'Plan & tasks'
141
142// Sessions without the built-in task tools (the desktop app's Code tab) get this one instead
143const BUILT_IN_TASK_TOOLS = ['TaskCreate', 'TodoWrite']
144const OWN_TOOL = 'mcp__task-list__todo_write'
145
146const isTodo = (value: unknown): value is Todo => {
147 if (typeof value !== 'object' || value === null) {
148 return false
149 }
150
151 const { content, status, activeForm } = value as Record<string, unknown>
152
153 return (
154 typeof content === 'string' &&
155 typeof status === 'string' &&
156 status in MARK &&
157 (activeForm === undefined || typeof activeForm === 'string')
158 )
159}
160
161const fromTodos = (todos: readonly Todo[]): Task[] =>
162 todos.map((todo, index) => ({
163 id: `todo-${index}`,
164 subject: todo.content,
165 activeForm: todo.activeForm,
166 status: todo.status,
167 }))
168
169const DEMO: Task[] = [
170 { id: 'demo-1', subject: 'Read the responses screen', status: 'completed' },
171 { id: 'demo-2', subject: 'Compute the response rate', activeForm: 'Computing the response rate', status: 'in_progress' },
172 { id: 'demo-3', subject: 'Add the KPI card', status: 'pending' },
173 { id: 'demo-4', subject: 'Write tests', status: 'pending' },
174]
175
176export const register: Register = on => {
177 on('session.start', async ($, e, next) => {
178 await $.command.register({
179 name: 'task-tree',
180 description: 'Show the whole superpowers plan tree (phases, plans, tasks, todos) in a pane',
181 })
182 await $.command.register({
183 name: 'task-demo',
184 description: 'Fill the task band with sample tasks; `/task-demo clear` empties it',
185 })
186
187 const tools = await $.tool.list()
188 if (!tools.some(one => BUILT_IN_TASK_TOOLS.includes(one.name))) {
189 await $.tool.register({
190 name: 'todo_write',
191 description:
192 'Create and update the todo list for the current work; the person sees it as a checklist above the prompt. ' +
193 'Use it for any task with three or more steps: write the whole list at the start, keep exactly one item ' +
194 'in_progress, and send the whole list again each time an item starts or finishes. Every call replaces the list.',
195 inputSchema: {
196 type: 'object',
197 properties: {
198 todos: {
199 type: 'array',
200 items: {
201 type: 'object',
202 properties: {
203 content: { type: 'string', description: 'What to do, in the imperative: "Run the tests"' },
204 activeForm: { type: 'string', description: 'The same, while it runs: "Running the tests"' },
205 status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] },
206 },
207 required: ['content', 'status', 'activeForm'],
208 },
209 },
210 },
211 required: ['todos'],
212 },
213 })
214 }
215
216 await update($, cwd, () => e.cwd)
217 await refreshPlan($)
218 await refreshAgents($)
219 $.clock.every(TICK_MS, () => void tick($))
220
221 return next(e)
222 })
223
224 // The background agents: each one started, and each tool call one makes (below; it carries the agent's id)
225 on('agent.spawn', async ($, e, next) => {
226 const started = await next(e)
227 if (started.agentId) {
228 await followAgent($, started.agentId, e.description, null)
229 }
230
231 return started
232 })
233
234 // A tool call made inside a background agent is that agent's latest action. A superpowers plan's progress lives
235 // in its ledger: read it again after a call that may have written it, and at the end of every turn
236 on('tool.call', async ($, e, next) => {
237 const agentId = e.agentId
238 if (agentId) {
239 await followAgent($, agentId, null, describeAction(e.tool, e as unknown as Record<string, unknown>))
240 }
241 const ran = await next(e).finally(() => (agentId ? finishTool($, agentId) : undefined))
242 if (touchesLedger(e)) {
243 await refreshPlan($)
244 }
245
246 return ran
247 })
248
249 on('turn.complete', async ($, e, next) => {
250 await refreshPlan($)
251
252 return next(e)
253 })
254
255 on('tool.call', { tool: OWN_TOOL }, async ($, e) => {
256 // The model's input is not checked against the schema on the way in
257 const todos: unknown = e.todos
258 if (!Array.isArray(todos) || !todos.every(isTodo)) {
259 return { deny: 'todos must be a list of { content, status, activeForm }, status one of pending, in_progress, completed' }
260 }
261
262 await update($, tasks, () => fromTodos(todos))
263 const done = todos.filter(todo => todo.status === 'completed').length
264
265 return { result: `Todo list updated: ${done}/${todos.length} done.` }
266 })
267
268 on('command.run', { command: 'task-demo' }, async ($, e) => {
269 if (e.args.trim() === 'clear') {
270 await update($, tasks, () => [])
271
272 return { text: 'Task band cleared.' }
273 }
274
275 await update($, tasks, () => DEMO)
276
277 return { text: 'Sample tasks added above the prompt.' }
278 })
279
280 on('tool.call', { tool: 'TaskCreate' }, async ($, e, next) => {
281 const ran = await next(e)
282 if (ran.isError || !ran.result) {
283 return ran
284 }
285
286 const task: Task = {
287 id: ran.result.task.id,
288 subject: e.subject,
289 activeForm: e.activeForm,
290 status: 'pending',
291 }
292 await update($, tasks, list => [...list.filter(one => one.id !== task.id), task])
293
294 return ran
295 })
296
297 on('tool.call', { tool: 'TaskUpdate' }, async ($, e, next) => {
298 const ran = await next(e)
299 if (ran.isError || !ran.result?.success) {
300 return ran
301 }
302
303 const { taskId, status, subject, activeForm } = e
304 if (status === 'deleted') {
305 await update($, tasks, list => list.filter(one => one.id !== taskId))
306
307 return ran
308 }
309
310 await update($, tasks, list =>
311 list.map(one =>
312 one.id !== taskId
313 ? one
314 : {
315 ...one,
316 status: status ?? one.status,
317 subject: subject ?? one.subject,
318 activeForm: activeForm ?? one.activeForm,
319 },
320 ),
321 )
322
323 return ran
324 })
325
326 on('tool.call', { tool: 'TodoWrite' }, async ($, e, next) => {
327 const ran = await next(e)
328 if (ran.isError) {
329 return ran
330 }
331
332 await update($, tasks, () => fromTodos(e.todos))
333
334 return ran
335 })
336
337 on('command.run', { command: 'task-tree' }, async $ => {
338 await refreshPlan($)
339 await $.ui.open({ id: PANE, title: PANE_TITLE })
340
341 return { text: `${PANE_TITLE} pane opened.` }
342 })
343
344 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
345 const view = await read($, plan)
346 // The band follows a plan only while it runs; a finished one stays in the pane
347 const running = view?.isRunning ? view : null
348 const list = withoutPlanTodos(await read($, tasks), running)
349 const done = list.filter(one => one.status === 'completed').length
350 // A finished list is history, not current work, so it hides even while Claude keeps working
351 const hasTodos = list.length > 0 && done < list.length
352 const followed = await read($, agents)
353
354 // Closed by the person: hidden until the plan, the list or the agents change
355 const isClosed = (await read($, closedOn)) === snapshot(running, list, followed)
356
357 if (e.props.hasSurvey || (running === null && !hasTodos && followed.length === 0) || isClosed) {
358 return next(e)
359 }
360
361 const { Box, Button, Text } = $.ui.resolve(e)
362 const at = await read($, clock)
363 const art = await agentArt($, e)
364 const isWorking = followed.some(agent => isActive(agent, at))
365 const byTask = agentsByTask(followed, running)
366 const shown = running === null ? null : withAgentsAtWork(running, byTask.on)
367 const active = list.find(one => one.status === 'in_progress')
368 const minimized = await read($, isMinimized)
369 const setMinimized = (value: boolean) => update($, isMinimized, () => value)
370 // Minimized: one line naming where the work is; the todo in progress, else the next to do
371 const current = active ?? list.find(one => one.status !== 'completed')
372 const summary = minimized
373 ? shown === null
374 ? hasTodos
375 ? `Todo (${current ? list.indexOf(current) + 1 : 0}/${list.length}) ${current?.subject ?? ''}`
376 : `${followed.length} agent${followed.length === 1 ? '' : 's'} running`
377 : breadcrumb(shown)
378 : shown === null
379 ? hasTodos
380 ? `${done}/${list.length} done${active?.activeForm ? ` · ${active.activeForm}…` : ''}`
381 : 'Agents'
382 : `${MARK.in_progress} ${planSummary(shown.name, shown.tasks)}`
383 // While an agent works the folded line spins in front
384 const foldedSpinner = minimized && isWorking ? art.marker(true) : ''
385 // Folded, the line also says what the latest active agent is doing, and how many others run
386 const latest = [...followed].sort((a, b) => b.lastAt - a.lastAt)[0]
387 const crumbTask = shown?.tasks.find(task => task.status === 'in_progress') ?? shown?.tasks.find(task => task.status === 'pending')
388 const others = followed.length - 1
389 const foldedActivity =
390 minimized && latest
391 ? ` — ${agentActivity(latest, at, crumbTask && byTask.of(crumbTask.n).includes(latest) ? roleUnderTask(latest.description) : latest.description)}${
392 others > 0 ? ` (+${others} agent${others === 1 ? '' : 's'})` : ''
393 }`
394 : ''
395 const unmatched = followed.filter(agent => !byTask.matched.has(agent.id))
396
397 const mine = (
398 <Box key="task-list" flexDirection="column">
399 <Box key="head" flexDirection="row" justifyContent="space-between" columnGap={2}>
400 <Box key="title" flexDirection="row" columnGap={1} flexShrink={1} minWidth={0}>
401 {minimized && isWorking && art.image('head-spinner')}
402 <Text key="summary" bold={running !== null} dimColor={running === null} wrap="truncate-end">
403 {foldedSpinner}
404 {summary}
405 {foldedActivity}
406 </Text>
407 </Box>
408 {/* Never squeezed: a long folded line truncates instead of pushing the buttons out */}
409 <Box key="actions" flexDirection="row" columnGap={2} flexShrink={0}>
410 <Button key="details" label="Details" plain dimColor onPress={() => $.ui.open({ id: PANE, title: PANE_TITLE })} />
411 {/* Minimize and close sit together at the right edge, as a window's controls do */}
412 <Box key="window" flexDirection="row" columnGap={1}>
413 {minimized ? (
414 <Button key="restore" label="□" plain dimColor onPress={() => setMinimized(false)} />
415 ) : (
416 <Button key="minimize" label="–" plain dimColor onPress={() => setMinimized(true)} />
417 )}
418 <Button
419 key="close"
420 label="×"
421 role="dismiss"
422 plain
423 dimColor
424 onPress={() => update($, closedOn, () => snapshot(running, list, followed))}
425 />
426 </Box>
427 </Box>
428 </Box>
429 {!minimized &&
430 (shown === null
431 ? todoLines($, e, hasTodos ? list : [])
432 : taskTree($, e, shown.tasks, hasTodos ? list.filter(todo => !isPlansTodo(todo)) : [], n => agentLines($, e, byTask.of(n), at, art, true)))}
433 {!minimized && shown !== null && planAgents($, e, byTask.plan, at, art)}
434 {!minimized && unmatched.length > 0 && (
435 <Box key="other-agents" flexDirection="column" paddingLeft={running === null && !hasTodos ? 0 : 2}>
436 {(running !== null || hasTodos) && (
437 <Text key="other-agents-title" dimColor>
438 Other agents
439 </Text>
440 )}
441 {agentLines($, e, unmatched, at, art, false)}
442 </Box>
443 )}
444 {!minimized && shown !== null && hasTodos && plansTodos($, e, list)}
445 </Box>
446 )
447
448 // Plugins of one tier nest in no fixed order: another mod's band beneath this one (skill-usage)
449 // stays, under the task list; the engine's own placeholder is left out
450 const below = await next(e)
451 if (below.type === 'engine') {
452 return mine
453 }
454
455 // Bands stacked: each framed like the prompt box, a row apart, so they read apart; a stack another mod already
456 // framed (key band-stack) is joined rather than framed again
457 const stacked = (below as { props?: { key?: string } }).props?.key === 'band-stack'
458
459 return (
460 <Box key="band-stack" flexDirection="column" rowGap={1}>
461 <Box key="task-list-frame" flexDirection="column" borderStyle="round" borderColor="promptBorder" paddingX={1}>
462 {mine}
463 </Box>
464 {stacked ? (below as { children?: RenderElement[] }).children : (
465 <Box key="upper" flexDirection="column" borderStyle="round" borderColor="promptBorder" paddingX={1}>
466 {below}
467 </Box>
468 )}
469 </Box>
470 )
471 })
472
473 // The whole tree: every phase and plan; the running plan's phase with each plan's tasks, done and to do
474 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
475 const { Box, Text } = $.ui.resolve(e)
476 const view = await read($, plan)
477 const list = withoutPlanTodos(await read($, tasks), view)
478 const followed = await read($, agents)
479 const at = await read($, clock)
480 const art = await agentArt($, e)
481 const byTask = agentsByTask(followed, view)
482
483 if (view === null) {
484 return (
485 <Box flexDirection="column">
486 <Text key="none" dimColor>
487 No superpowers plan in this folder.
488 </Text>
489 {todoLines($, e, list)}
490 </Box>
491 )
492 }
493
494 return (
495 <Box flexDirection="column">
496 {view.groups.map((group, index) => {
497 const plansDone = group.plans.filter(row => row.status === 'completed').length
498 const isCurrentGroup = group.plans.some(row => row.isCurrent)
499
500 return (
501 <Box key={`group-${index}`} flexDirection="column" marginBottom={1}>
502 <Text key="head" bold>
503 {group.phase === null ? 'Plans' : `Phase ${group.phase}`} · {plansDone}/{group.plans.length} plans done
504 </Text>
505 {group.plans.map((row, at) => (
506 <Box key={`plan-${at}`} flexDirection="column" paddingLeft={2}>
507 <Text
508 key="line"
509 bold={row.isCurrent}
510 dimColor={row.status === 'completed'}
511 wrap="truncate-end"
512 >
513 {MARK[row.status]} {planSummary(row.name, row.tasks)}
514 {row.status === 'on_hold' ? ' · left open' : ''}
515 </Text>
516 {isCurrentGroup &&
517 taskTree($, e, row.isCurrent ? withAgentsAtWork(row, byTask.on).tasks : row.tasks, row.isCurrent ? list.filter(todo => !isPlansTodo(todo)) : [], n =>
518 row.isCurrent ? agentLines($, e, byTask.of(n), at, art, true) : [],
519 )}
520 {row.isCurrent && planAgents($, e, byTask.plan, at, art)}
521 </Box>
522 ))}
523 </Box>
524 )
525 })}
526 {plansTodos($, e, list)}
527 </Box>
528 )
529 })
530}
531
532// The plan's todos repeat its tasks (superpowers makes one per task): the tree shows them once
533const withoutPlanTodos = (list: readonly Task[], view: PlanView | null): Task[] =>
534 view === null ? [...list] : list.filter(task => !isPlanTodo(task.subject, view.tasks))
535
536// Agents on the running plan as a whole, after its tasks and in line with them
537const planAgents = (
538 $: EngineInterface,
539 e: RenderInput,
540 list: readonly TrackedAgent[],
541 at: number,
542 art: Awaited<ReturnType<typeof agentArt>>,
543) => {
544 const { Box } = $.ui.resolve(e)
545
546 return (
547 list.length > 0 && (
548 <Box key="plan-agents" flexDirection="column" paddingLeft={2}>
549 {agentLines($, e, list, at, art, false)}
550 </Box>
551 )
552 )
553}
554
555// A todo naming a plan (`Review Plan 11, merge into main`, `Plan 12: …`) is the session's work across plans, no task's
556// and no one plan's: it shows in a section of its own, beside the plan, level with the plan line
557const isPlansTodo = (todo: Task): boolean => /\bPlan\s+[0-9]/i.test(todo.subject)
558
559const plansTodos = ($: EngineInterface, e: RenderInput, list: readonly Task[]) => {
560 const { Box, Text } = $.ui.resolve(e)
561 const across = list.filter(isPlansTodo)
562
563 return (
564 across.length > 0 && (
565 <Box key="plans-todos" flexDirection="column">
566 <Text key="plans-todos-title" dimColor>
567 Todos
568 </Text>
569 {todoLines($, e, across)}
570 </Box>
571 )
572 )
573}
574
575const planSummary = (name: string, planned: readonly PlanTask[]): string =>
576 `${name} · ${planned.filter(task => task.status === 'completed').length}/${planned.length} tasks`
577
578const todoLines = ($: EngineInterface, e: RenderInput, list: readonly Task[]) => {
579 const { Text } = $.ui.resolve(e)
580
581 return list.map(task => (
582 <Text
583 key={task.id}
584 bold={task.status === 'in_progress'}
585 dimColor={task.status === 'completed'}
586 strikethrough={task.status === 'completed'}
587 >
588 {MARK[task.status]} {task.subject}
589 </Text>
590 ))
591}
592
593// A plan's tasks, each with the agents working on it, and the todos under the task in progress (after the tasks when
594// none is)
595const taskTree = (
596 $: EngineInterface,
597 e: RenderInput,
598 planned: readonly PlanTask[],
599 todos: readonly Task[],
600 agentsUnder: (n: number) => ReturnType<typeof agentLines>,
601) => {
602 const { Box, Text } = $.ui.resolve(e)
603 // The todos are the running task's: under it while one task runs, under the plan while several run in parallel
604 const running = planned.filter(task => task.status === 'in_progress')
605 const activeTask = running.length === 1 ? running[0] : undefined
606 const todoBox = (key: string, shown: readonly Task[], indent: number) =>
607 shown.length > 0 && (
608 <Box key={key} flexDirection="column" paddingLeft={indent}>
609 {todoLines($, e, shown)}
610 </Box>
611 )
612 const taskTodos = todoBox('todos', todos, 2)
613
614 return (
615 <Box key="tasks" flexDirection="column" paddingLeft={2}>
616 {planned.map(task => {
617 const working = agentsUnder(task.n)
618 // A task with an agent on it (its implementer, or the reviewer of an unreviewed one) is being worked on
619 const status = task.status !== 'completed' && working.length > 0 ? 'in_progress' : task.status
620
621 return (
622 <Box key={`task-${task.n}`} flexDirection="column">
623 <Text key="line" bold={status === 'in_progress'} dimColor={status === 'completed' || status === 'unreviewed'} wrap="truncate-end">
624 {MARK[status]} Task {task.n} {task.title}
625 {status === 'unreviewed' ? ' · implemented, not reviewed' : task.step ? ` · ${task.step}` : ''}
626 {status === 'on_hold' ? ' · on hold' : ''}
627 </Text>
628 {working.length > 0 && (
629 <Box key="agents" flexDirection="column" paddingLeft={2}>
630 {working}
631 </Box>
632 )}
633 {task === activeTask && taskTodos}
634 </Box>
635 )
636 })}
637 {activeTask === undefined && taskTodos}
638 </Box>
639 )
640}
641
642// How a working agent's marker is drawn: an animated image where the surface has one, a text spinner stepped by the
643// clock in the terminal; a quiet agent gets a still dot
644const agentArt = async ($: EngineInterface, e: RenderInput) => {
645 const table = $.ui.resolve(e)
646 const svg = e.surface !== 'terminal' && 'Svg' in table ? table.Svg : null
647 const step = svg === null ? await read($, frame) : 0
648
649 return {
650 marker: (isWorking: boolean): string => (isWorking ? (svg === null ? `${SPINNER[step % SPINNER.length]} ` : '') : '◦ '),
651 image: (key: string) => svg !== null && h(svg, { key, source: SPINNER_SVG, alt: 'working', width: 12, height: 12, isInteractive: true }),
652 }
653}
654
655// A task with an agent on it is being worked on, whatever its ledger says yet: in the tree and the folded line
656const withAgentsAtWork = <T extends { tasks: PlanTask[] }>(view: T, agentsOf: (n: number) => readonly TrackedAgent[]): T => ({
657 ...view,
658 tasks: view.tasks.map(task => {
659 const agents = agentsOf(task.n)
660 if (task.status === 'completed' || agents.length === 0) {
661 return task
662 }
663 // Its reviewer at work: the step is the review, until the ledger names a later one
664 const isReviewed = agents.some(agent => /\breview/i.test(agent.description)) && [undefined, 'implementing', 'implemented'].includes(task.step)
665
666 return { ...task, status: 'in_progress' as const, ...(isReviewed ? { step: 'review' } : {}) }
667 }),
668})
669
670// Agents by the plan tasks they work on, from their descriptions; the rest are no task's. One on several tasks
671// (`Review tasks 1–4`) works on all of them, and its line shows once, under the first
672const agentsByTask = (followed: readonly TrackedAgent[], view: PlanView | null) => {
673 const tasksOf = new Map(followed.map(agent => [agent.id, view === null ? [] : tasksOfAgent(agent.description, view.name, view.tasks)]))
674 const onPlan = followed.filter(agent => view !== null && (tasksOf.get(agent.id) ?? []).length === 0 && isOnPlan(agent.description, view.name))
675
676 return {
677 matched: new Set([...followed.filter(agent => (tasksOf.get(agent.id) ?? []).length > 0), ...onPlan].map(agent => agent.id)),
678 of: (n: number) => followed.filter(agent => tasksOf.get(agent.id)?.[0] === n),
679 on: (n: number) => followed.filter(agent => tasksOf.get(agent.id)?.includes(n)),
680 // On the plan as a whole: under it, after its tasks
681 plan: onPlan,
682 }
683}
684
685// One line per agent: its spinner or dot, its name (its role, under its task), how long it has run, its latest action
686// and how long ago; amber once quiet for 5 minutes
687const agentLines = (
688 $: EngineInterface,
689 e: RenderInput,
690 list: readonly TrackedAgent[],
691 at: number,
692 art: Awaited<ReturnType<typeof agentArt>>,
693 isUnderTask: boolean,
694) => {
695 const { Box, Text } = $.ui.resolve(e)
696
697 return list.map(agent => {
698 const working = isActive(agent, at)
699
700 return (
701 <Box key={`agent-${agent.id}`} flexDirection="row" columnGap={1}>
702 {working && art.image('spinner')}
703 <Text key="line" color={isStuck(agent, at) ? 'warning' : undefined} wrap="truncate-end">
704 {art.marker(working)}
705 {agentText(agent, at, isUnderTask ? roleUnderTask(agent.description) : agent.description)}
706 </Text>
707 </Box>
708 )
709 })
710}
711hooks/agents.ts 118 lines1import type { AgentStatus } from 'claude-code'
2
3import type { PlanTask, TrackedAgent } from '../types'
4import { taskNumbers } from './sdd'
5
6// The background agents beside the task list: what each is doing, matched to the plan task it works on
7
8// An agent that acted this recently is working right now: its marker spins
9export const ACTIVE_MS = 30_000
10// One quiet this long while still running looks stuck: its line turns amber
11export const STUCK_MS = 5 * 60_000
12// A just-started agent the engine does not list yet is kept this long
13export const GRACE_MS = 60_000
14// Running only: a finished subagent that could be resumed stays listed as waiting or idle
15export const ALIVE: readonly AgentStatus[] = ['pending', 'running']
16
17export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
18export const SPINNER_SVG =
19 '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12">' +
20 '<circle cx="6" cy="6" r="4.5" fill="none" stroke="currentColor" stroke-opacity="0.25" stroke-width="1.5"/>' +
21 '<path d="M6 1.5a4.5 4.5 0 0 1 4.5 4.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round">' +
22 '<animateTransform attributeName="transform" type="rotate" from="0 6 6" to="360 6 6" dur="0.9s" repeatCount="indefinite"/>' +
23 '</path></svg>'
24
25const shorten = (text: string, max: number): string => {
26 const line = text.split('\n')[0] ?? ''
27
28 return line.length > max ? `${line.slice(0, max - 1)}…` : line
29}
30
31const shortPath = (path: string): string => {
32 const parts = path.split('/').filter(Boolean)
33
34 return parts.length > 2 ? `…/${parts.slice(-2).join('/')}` : path
35}
36
37// A tool call in one line: „Edit …/profile/PlanCard.tsx“, „Bash: npx vitest run apps/client“
38export const describeAction = (tool: string, input: Readonly<Record<string, unknown>>): string => {
39 const name = tool.startsWith('mcp__') ? (tool.split('__').pop() ?? tool) : tool
40 const text = (key: string): string | null => (typeof input[key] === 'string' ? (input[key] as string) : null)
41 const path = text('file_path') ?? text('notebook_path') ?? text('path')
42 if (path) {
43 return `${name} ${shortPath(path)}`
44 }
45 // A Bash call says what it does in its description; else its command, past the `cd <dir> &&` that opens it
46 const command = text('command')?.replace(/^(\s*cd\s+\S+\s*(&&|;)\s*)+/, '') ?? null
47 const detail = (name === 'Bash' ? text('description') : null) ?? command ?? text('pattern') ?? text('description') ?? text('url') ?? text('query')
48
49 return detail ? `${name}: ${shorten(detail, 40)}` : name
50}
51
52// A tool call still running (a test suite, a build) keeps its agent active however long it takes
53export const isBusy = (agent: TrackedAgent): boolean => (agent.toolsRunning ?? 0) > 0
54export const isActive = (agent: TrackedAgent, at: number): boolean => isBusy(agent) || at - agent.lastAt < ACTIVE_MS
55export const isStuck = (agent: TrackedAgent, at: number): boolean => !isBusy(agent) && at - agent.lastAt >= STUCK_MS
56
57const minutes = (ms: number): number => Math.max(0, Math.floor(ms / 60_000))
58const span = (ms: number): string => (ms < 60_000 ? `${Math.max(0, Math.round(ms / 1000))} s` : `${minutes(ms)} min`)
59const ago = (ms: number): string => `${span(ms)} ago`
60
61// „Bash: ./run test · 6 min so far“ while the call runs, „Edit …/a/b · 9 s ago“ after
62const lastStep = (agent: TrackedAgent, quiet: number): string =>
63 `${agent.lastAction} · ${isBusy(agent) ? `${span(quiet)} so far` : ago(quiet)}`
64
65// „builder · running 5 min · Bash: npx vitest run · 9 s ago“; under a task the agent goes by its role, without the
66// task it repeats
67export const agentText = (agent: TrackedAgent, at: number, name: string = agent.description): string => {
68 const quiet = at - agent.lastAt
69 const running = `${name} · running ${minutes(at - agent.startedAt)} min`
70 if (isStuck(agent, at)) {
71 return `${running} · no activity for ${minutes(quiet)} min`
72 }
73
74 return agent.lastAction ? `${running} · ${lastStep(agent, quiet)}` : running
75}
76
77// Which plan tasks an agent works on, from its description (`Plan 10 Task 10: referral invites`, `Review Plan 11
78// tasks 1–4`, `Tasks 2, 3 and 5`): the tasks named that the running plan has, when the description names no other plan
79export const tasksOfAgent = (description: string, planName: string, tasks: readonly PlanTask[]): number[] => {
80 const named = description.match(/\bTasks?\s+(\d+(?:\s*(?:[,&+–—-]|and|to)\s*\d+)*)/i)?.[1]
81 if (named === undefined) {
82 return []
83 }
84 if (isOtherPlan(planOf(description), planOf(planName))) {
85 return []
86 }
87
88 return taskNumbers(named).filter(n => tasks.some(task => task.n === n))
89}
90
91// The plan number a text names: `Plan 11`, `Plan 4b`
92const planOf = (text: string): string | undefined => text.match(/\bPlan\s+([0-9][\w.]*)/i)?.[1]?.toLowerCase()
93
94const isOtherPlan = (agentPlan: string | undefined, runningPlan: string | undefined): boolean =>
95 agentPlan !== undefined && runningPlan !== undefined && agentPlan !== runningPlan
96
97// An agent on the running plan as a whole (`Fix Plan 11 review findings`): it names a plan, no other than the running
98// one (whose title may carry no number), and no task
99export const isOnPlan = (description: string, planName: string): boolean =>
100 planOf(description) !== undefined && !isOtherPlan(planOf(description), planOf(planName))
101
102// Under its task the agent's line names what it does there: „Plan 10 Task 10: referral invites“ → „referral invites“
103export const roleUnderTask = (description: string): string => {
104 const rest = description.replace(/^.*?\bTask\s+\d+\b\s*[:—–-]?\s*/i, '').trim()
105
106 return rest === '' ? description : rest
107}
108
109// What an agent is doing, for the folded line: „referral rework · Edit …/ReferralCard.tsx · 4 s ago“
110export const agentActivity = (agent: TrackedAgent, at: number, name: string): string => {
111 const quiet = at - agent.lastAt
112 if (isStuck(agent, at)) {
113 return `${name} · no activity for ${minutes(quiet)} min`
114 }
115
116 return agent.lastAction ? `${name} · ${lastStep(agent, quiet)}` : `${name} · started`
117}
118hooks/sdd.ts 433 lines1import type { PhaseGroup, PlanRow, PlanTask, PlanView, TaskStatus } from '../types'
2
3// Reads superpowers' subagent-driven-development files: the plan
4// (docs/superpowers/plans/*.md, `### Task N: title` headings) and the plan's ledger
5// (.superpowers/sdd/<plan>/progress.md, `Task N: …` lines, `Task N: complete` when done)
6
7export type PlanHeading = { n: number; title: string }
8// isOnHold: deferred by a ledger line (`Ruling: Task 6 … deferred to after Task 7`) and not moved since
9export type LedgerTask = { isComplete: boolean; step?: string; isOnHold?: true }
10// isMerged: a `MERGED …` line — the plan is finished, every task done
11export type Ledger = { plan: string | null; tasks: Record<number, LedgerTask>; isMerged?: true }
12
13// What the loader reads the disk with; never rejects: a missing path is null, [] or false
14export type Files = {
15 read: (path: string) => Promise<string | null>
16 list: (path: string) => Promise<{ name: string; kind: string; mtimeMs: number }[]>
17 exists: (path: string) => Promise<boolean>
18}
19
20const TASK_HEADING = /^#+\s+Task\s+(\d+)\b[:.\s—–-]*(.*)$/
21const REVIEW_PROBLEM = /❌|changes (needed|requested)|not ready/i
22const NOTE = /^\s*:\s*(ruling|minor|parked|note)\b/i
23const DEFERRAL = /\bdefer(red|s)?\b|\bon hold\b/i
24const LEDGER_IDENTITY = /^# SDD ledger — plan:\s*(.+?)\s*$/
25// A ledger line, bare or as a list item (`- Task 3: …`): controllers write it both ways
26// …or one entry for several tasks: `Tasks 1–4: review dispatched`, `Tasks 2, 3 and 5: complete`
27const LEDGER_TASK = /^\s*(?:[-*+]\s+)?Tasks?\s+(\d+(?:\s*(?:[,&+–—-]|and|to)\s*\d+)*)\b(.*)$/
28
29// The tasks a `1–4`, `1 to 4` or `2, 3 and 5` names: a range is every task in it
30export const taskNumbers = (named: string): number[] =>
31 [...named.matchAll(/(\d+)(?:\s*(?:[–—-]|to)\s*(\d+))?/gi)].flatMap(([, from, to]) => {
32 const first = Number(from)
33 const last = to === undefined ? first : Math.max(first, Number(to))
34
35 return Array.from({ length: last - first + 1 }, (_, at) => first + at)
36 })
37const PHASE_IN_PARENS = /\s*\(Phase\s+([0-9][\w.]*)\)/
38const PHASE_PREFIX = /^.*?\bPhase\s+([0-9][\w.]*)\s*[·—–:-]?\s*(.*)$/
39const IMPLEMENTATION_PLAN = /[\s—–-]*Implementation Plan\s*$/
40
41// A ledger line's step, most specific first; null for a line that is no step (minor, ruling, carry)
42const STEPS: [RegExp, (match: RegExpMatchArray) => string][] = [
43 [/\bfix round (\d+)/i, match => `fix round ${match[1]}`],
44 [/\bre-review\b/i, () => 're-review'],
45 // A review still to come (`implemented, review pending`, `awaiting review`) is not one under way
46 [/(?<!\b(awaiting|needs|before|for|to)\s+)\breview(er)?\b(?!\s+(pending|next|later|queued|due))/i, () => 'review'],
47 // The implementer's report (`Task 5: DONE — …`, `DONE_WITH_CONCERNS`), upper case as superpowers writes it
48 [/\bDONE(_WITH_CONCERNS)?\b/, () => 'implemented'],
49 [/\b(dispatched|started)\b/i, () => 'implementing'],
50 [/\bimplement(er|ed)\b/i, () => 'implemented'],
51]
52
53const stepOf = (rest: string): string | null => {
54 for (const [pattern, name] of STEPS) {
55 const match = rest.match(pattern)
56 if (match) {
57 return name(match)
58 }
59 }
60
61 return null
62}
63
64const plainTitle = (title: string): string => title.replace(/`/g, '').trim()
65
66export const parsePlan = (text: string): { title: string; tasks: PlanHeading[] } => {
67 let title = ''
68 let isInFence = false
69 const tasks: PlanHeading[] = []
70
71 for (const line of text.split('\n')) {
72 if (line.startsWith('```')) {
73 isInFence = !isInFence
74 continue
75 }
76 if (isInFence) {
77 continue
78 }
79 if (title === '' && line.startsWith('# ')) {
80 title = line.slice(2).trim()
81 continue
82 }
83
84 const heading = line.match(TASK_HEADING)
85 if (heading) {
86 tasks.push({ n: Number(heading[1]), title: plainTitle(heading[2] ?? '') })
87 }
88 }
89
90 return { title, tasks }
91}
92
93// One task's entry after a ledger part about it; undefined when the part only names it in passing
94const nextEntry = (known: LedgerTask | undefined, rest: string, isLineStart: boolean): LedgerTask | undefined => {
95 // The task moves again: no longer on hold
96 const { isOnHold: _wasOnHold, ...task } = known ?? { isComplete: false }
97 // Done at `Task N: complete` (or `Task N complete`), or at an approved review with no problem reported beside it:
98 // some controllers write no complete line after `Task 1 review: APPROVED`
99 if (/^\s*:?\s*complete\b/i.test(rest)) {
100 return { ...task, isComplete: true }
101 }
102
103 // A note on the task (`Task 2: Ruling: …`, `Task 1: minor (deferred): …`) is no step of it
104 const step = NOTE.test(rest) ? null : stepOf(rest)
105 const isApproved = /\bapproved\b/i.test(rest) && !REVIEW_PROBLEM.test(rest)
106 // Mid-line, a task is named in passing (`…; Task 17 added to Plan 10`) unless the part records a step of it
107 if (!isLineStart && step === null && !isApproved && known === undefined) {
108 return undefined
109 }
110 const moved = step === null ? task : { ...task, step }
111
112 return isApproved ? { ...moved, isComplete: true } : moved
113}
114
115export const parseLedger = (text: string): Ledger => {
116 const lines = text.split('\n')
117 const plan = lines[0]?.match(LEDGER_IDENTITY)?.[1] ?? null
118 const tasks: Record<number, LedgerTask> = {}
119
120 // A line may hold several events (`Scoped re-review dispatched; Task 4 dispatched in parallel`): each part
121 // starting `Task N` opens a segment of that task, and the parts after it stay with it
122 const segments = lines.flatMap(line =>
123 // `;` separates events, and so does a sentence break before an entry `Task N:`, `Task N complete` or `Task N dispatched` (`Task 23: complete. Task 37: complete.`);
124 // prose that names a task (`… precedes it. Task 6 must hoist it`) is no entry
125 line.split(/;|\.\s+(?=Task\s+\d+\s*(?::|complete\b|dispatched\b))/).reduce<{ text: string; isLineStart: boolean }[]>(
126 (parts, part) => {
127 if (LEDGER_TASK.test(part) || parts.length === 0) {
128 return [...parts, { text: part, isLineStart: parts.length === 0 }]
129 }
130 const last = parts[parts.length - 1] as { text: string; isLineStart: boolean }
131
132 return [...parts.slice(0, -1), { ...last, text: `${last.text};${part}` }]
133 },
134 [],
135 ),
136 )
137
138 for (const { text: segment, isLineStart } of segments) {
139 const match = segment.match(LEDGER_TASK)
140 if (!match) {
141 // A ruling that defers a task puts it on hold (`Ruling: Task 6 I1 … deferred to after Task 7`)
142 const held = DEFERRAL.test(segment) ? Number(segment.match(/\bTask\s+(\d+)/)?.[1]) : NaN
143 const heldTask = tasks[held]
144 if (heldTask && !heldTask.isComplete) {
145 tasks[held] = { ...heldTask, isOnHold: true }
146 }
147 continue
148 }
149 const rest = match[2] ?? ''
150 // `Task 1 → Task 2 carry: …` is a note between tasks, not a step of either
151 if (/^\s*→/.test(rest)) {
152 continue
153 }
154 for (const n of taskNumbers(match[1] ?? '')) {
155 const entry = nextEntry(tasks[n], rest, isLineStart)
156 if (entry) {
157 tasks[n] = entry
158 }
159 }
160 }
161
162 // `MERGED …` or `Plan 8 MERGED …`, upper case: a lower-case „Ready to merge“ is only a review verdict
163 const isMerged = lines.some(line => /\bMERGED\b/.test(line))
164
165 return isMerged ? { plan, tasks, isMerged } : { plan, tasks }
166}
167
168// A sub-phase (3e, 1.5) belongs to its main phase (3, 1); its own label stays at the front of the name
169const inMainPhase = (label: string, name: string): { phase: string; name: string } => {
170 const main = label.match(/^\d+/)?.[0] ?? label
171
172 return { phase: main, name: label === main ? name : `${label} · ${name}` }
173}
174
175export const splitTitle = (title: string): { phase: string | null; name: string } => {
176 const bare = title.replace(IMPLEMENTATION_PLAN, '')
177 const inParens = bare.match(PHASE_IN_PARENS)
178 if (inParens?.[1]) {
179 return inMainPhase(inParens[1], bare.replace(PHASE_IN_PARENS, '').trim())
180 }
181
182 const prefixed = bare.match(PHASE_PREFIX)
183 if (prefixed?.[1]) {
184 return inMainPhase(prefixed[1], (prefixed[2] ?? '').trim())
185 }
186
187 return { phase: null, name: bare.trim() }
188}
189
190export const planTasks = (headings: readonly PlanHeading[], ledger: Ledger): PlanTask[] => {
191 const tasks = headings.map(({ n, title }): PlanTask => {
192 const entry = ledger.tasks[n]
193 if (entry?.isComplete || ledger.isMerged) {
194 return { n, title, status: 'completed' }
195 }
196 if (entry === undefined) {
197 return { n, title, status: 'pending' }
198 }
199
200 // Tasks may run in parallel: each open task is in progress unless the ledger deferred it
201 const status = entry.isOnHold ? 'on_hold' : 'in_progress'
202
203 return entry.step === undefined ? { n, title, status } : { n, title, status, step: entry.step }
204 })
205 // A task implemented but never reviewed, while a later task is already under way, is not being worked on
206 const newestStarted = Math.max(0, ...tasks.filter(task => task.status !== 'pending').map(task => task.n))
207
208 return tasks.map(task =>
209 task.status === 'in_progress' && task.step === 'implemented' && task.n < newestStarted ? { ...task, status: 'unreviewed' } : task,
210 )
211}
212
213const normalized = (text: string): string => text.trim().toLowerCase()
214
215// Superpowers makes a todo per plan task; those repeat the tree and are left out of it
216export const isPlanTodo = (content: string, tasks: readonly PlanTask[]): boolean =>
217 /\btask\s+\d+\b/i.test(content) || tasks.some(task => normalized(task.title) === normalized(content))
218
219const planStatus = (tasks: readonly PlanTask[], ledger: Ledger | null): TaskStatus => {
220 if (tasks.length > 0 && tasks.every(task => task.status === 'completed')) {
221 return 'completed'
222 }
223
224 return ledger !== null && Object.keys(ledger.tasks).length > 0 ? 'in_progress' : 'pending'
225}
226
227const parentOf = (path: string): string => path.slice(0, Math.max(path.lastIndexOf('/'), 0)) || '/'
228const nameOf = (path: string): string => path.slice(path.lastIndexOf('/') + 1)
229
230// The folder holding .superpowers/sdd: the working directory or the nearest parent with one
231const findRoot = async (files: Files, cwd: string): Promise<string | null> => {
232 let dir = cwd
233 for (;;) {
234 if (await files.exists(`${dir}/.superpowers/sdd`)) {
235 return dir
236 }
237 const parent = parentOf(dir)
238 if (parent === dir) {
239 return null
240 }
241 dir = parent
242 }
243}
244
245// The ledger written last that names its plan: superpowers runs one plan at a time, and a ledger
246// without the `# SDD ledger — plan:` line predates the format, its tasks unreadable
247// What preparing a plan writes: its ledger, the plan's path and the task briefs. A workspace holding nothing else,
248// with no task in its ledger, is prepared but not started
249const PREPARED_FILE = /^(progress\.md|plan-path|task-\d+-brief\.md)$/
250
251type Found = { ledger: Ledger; mtimeMs: number; isStarted: boolean }
252
253// The ledger of the plan being worked on: the newest started one while it is open. A plan prepared ahead (its
254// workspace and briefs written before the running plan is done) waits its turn: it is current only once the
255// latest started plan is finished, the oldest prepared one first
256const currentLedger = async (files: Files, sdd: string, root: string): Promise<Found | null> => {
257 const dirs = (await files.list(sdd)).filter(entry => entry.kind === 'dir')
258 const found: Found[] = []
259 for (const dir of dirs) {
260 const entries = await files.list(`${sdd}/${dir.name}`)
261 const file = entries.find(entry => entry.name === 'progress.md' && entry.kind === 'file')
262 const text = file ? await files.read(`${sdd}/${dir.name}/progress.md`) : null
263 const ledger = text === null ? null : parseLedger(text)
264 if (file && ledger?.plan) {
265 const isStarted = Object.keys(ledger.tasks).length > 0 || entries.some(entry => !PREPARED_FILE.test(entry.name))
266 found.push({ ledger, mtimeMs: file.mtimeMs, isStarted })
267 }
268 }
269
270 const newestFirst = found.sort((a, b) => b.mtimeMs - a.mtimeMs)
271 const [latest, before] = newestFirst.filter(one => one.isStarted)
272 if (latest && (await isOpenPlan(files, root, latest.ledger))) {
273 return latest
274 }
275 // Prepared since the started plan before the latest: older preparations were left
276 const next = newestFirst.filter(one => !one.isStarted && one.mtimeMs > (before?.mtimeMs ?? -Infinity)).pop()
277
278 return next ?? latest ?? null
279}
280
281const planPathOf = (root: string, named: string): string => (named.startsWith('/') ? named : `${root}/${named}`)
282
283const isOpenPlan = async (files: Files, root: string, ledger: Ledger): Promise<boolean> => {
284 const text = ledger.plan ? await files.read(planPathOf(root, ledger.plan)) : null
285
286 return text !== null && planStatus(planTasks(parsePlan(text).tasks, ledger), ledger) !== 'completed'
287}
288
289// Plans by the date their file name starts with; plans of the same day by when their workspace was made (its oldest
290// file: the plan path and briefs are written once), since their names sort only by the alphabet. A plan with no
291// workspace left was cleaned up, so it is older: it goes first
292const inPlanOrder = async (files: Files, root: string, names: readonly string[]): Promise<string[]> => {
293 const keyed = await Promise.all(
294 names.map(async name => {
295 const workspace = await files.list(`${root}/.superpowers/sdd/${name.replace(/\.md$/, '')}`)
296 const made = workspace.filter(entry => entry.kind === 'file').map(entry => entry.mtimeMs)
297 const born = made.length > 0 ? Math.min(...made) : -Infinity
298
299 return { name, day: name.match(/^\d{4}-\d{2}-\d{2}/)?.[0] ?? name, born }
300 }),
301 )
302
303 return keyed
304 .sort((a, b) => a.day.localeCompare(b.day) || (a.born === b.born ? 0 : a.born < b.born ? -1 : 1) || a.name.localeCompare(b.name))
305 .map(one => one.name)
306}
307
308// Every plan next to the running one, in file name (date) order, each with its own ledger's tasks
309const allPlans = async (
310 files: Files,
311 root: string,
312 current: { path: string; ledger: Ledger },
313): Promise<(PlanRow & { phase: string | null })[]> => {
314 const dir = parentOf(current.path)
315 const names = await inPlanOrder(
316 files,
317 root,
318 (await files.list(dir)).filter(entry => entry.kind === 'file' && entry.name.endsWith('.md')).map(entry => entry.name),
319 )
320 const rows: (PlanRow & { phase: string | null })[] = []
321 // Superpowers' workspaces are scratch and often cleaned: a plan without a ledger before the
322 // running one was run before it, one after it is still to do
323 let isBeforeCurrent = names.some(file => `${dir}/${file}` === current.path)
324
325 for (const file of names) {
326 const text = await files.read(`${dir}/${file}`)
327 if (text === null) {
328 continue
329 }
330 const plan = parsePlan(text)
331 const { phase, name } = splitTitle(plan.title)
332 const isCurrent = `${dir}/${file}` === current.path
333 if (isCurrent) {
334 isBeforeCurrent = false
335 }
336 // The running plan's ledger is known; another plan's sits in the workspace named after its file
337 const ledgerText = isCurrent ? null : await files.read(`${root}/.superpowers/sdd/${file.replace(/\.md$/, '')}/progress.md`)
338 const parsed = ledgerText === null ? null : parseLedger(ledgerText)
339 // A ledger from before the identity line can't be read: such a plan counts as having none
340 const ledger = isCurrent ? current.ledger : parsed?.plan ? parsed : null
341 const tasks =
342 ledger === null && isBeforeCurrent
343 ? plan.tasks.map(({ n, title }): PlanTask => ({ n, title, status: 'completed' }))
344 : planTasks(plan.tasks, ledger ?? { plan: null, tasks: {} })
345 const status = planStatus(tasks, ledger)
346 // One plan runs at a time, the newest ledger's: another plan with open tasks was left open, not worked on
347 const isLeftOpen = !isCurrent && status === 'in_progress'
348 rows.push(
349 isLeftOpen
350 ? { phase, name: name || file, status: 'on_hold', isCurrent, tasks: tasks.map(task => (task.status === 'in_progress' ? { ...task, status: 'on_hold' } : task)) }
351 : { phase, name: name || file, status, isCurrent, tasks },
352 )
353 }
354
355 return rows
356}
357
358// Plans grouped by phase; plans without one share a group
359const byPhase = (rows: readonly (PlanRow & { phase: string | null })[]): PhaseGroup[] => {
360 const groups: PhaseGroup[] = []
361 for (const { phase, ...row } of rows) {
362 const group = groups.find(one => one.phase === phase)
363 if (group) {
364 group.plans.push(row)
365 continue
366 }
367 groups.push({ phase, plans: [row] })
368 }
369
370 // Phases in number order whatever the files' dates; the plans without a phase last
371 return groups.sort((a, b) => (a.phase === null ? Infinity : Number(a.phase)) - (b.phase === null ? Infinity : Number(b.phase)))
372}
373
374// A plan whose ledger hasn't changed for a day is left, not running
375const RUNNING_WINDOW_MS = 24 * 60 * 60 * 1000
376
377// The newest ledger's plan and every plan beside it, or null when there is no superpowers plan
378export const loadPlanView = async (files: Files, cwd: string, now: number): Promise<PlanView | null> => {
379 const root = await findRoot(files, cwd)
380 if (root === null) {
381 return null
382 }
383
384 const current = await currentLedger(files, `${root}/.superpowers/sdd`, root)
385 const named = current?.ledger.plan
386 if (current === null || !named) {
387 return null
388 }
389
390 const { ledger, mtimeMs } = current
391 const planPath = planPathOf(root, named)
392 const planText = await files.read(planPath)
393 if (planText === null) {
394 return null
395 }
396
397 const plan = parsePlan(planText)
398 const tasks = planTasks(plan.tasks, ledger)
399 const { phase, name } = splitTitle(plan.title)
400 const groups = byPhase(await allPlans(files, root, { path: planPath, ledger }))
401
402 return {
403 // A finished or left plan is history, as a finished todo list is: the band hides it, the pane keeps it
404 isRunning: tasks.length > 0 && planStatus(tasks, ledger) !== 'completed' && now - mtimeMs < RUNNING_WINDOW_MS,
405 phase,
406 name: name || nameOf(planPath),
407 tasks,
408 groups,
409 }
410}
411
412// The running task in one line: Phase 7 (13/13) \ Plan (3/4) \ Task (3/7) title · step. The task is
413// the one in progress, else the next to do; a plan without a phase starts at Plan
414export const breadcrumb = (view: PlanView): string => {
415 const phases = view.groups.filter(group => group.phase !== null)
416 const group = view.groups.find(one => one.plans.some(row => row.isCurrent))
417 const planAt = group ? group.plans.findIndex(row => row.isCurrent) + 1 : 1
418 const planCount = group ? group.plans.length : 1
419 const running = view.tasks.filter(one => one.status === 'in_progress')
420 const task = running[0] ?? view.tasks.find(one => one.status === 'pending') ?? view.tasks[view.tasks.length - 1]
421 const taskAt = task ? view.tasks.indexOf(task) + 1 : 0
422 const parallel = running.length > 1 ? ` (+${running.length - 1} in parallel)` : ''
423 const crumbs = [
424 `Plan (${planAt}/${planCount})`,
425 `Task (${taskAt}/${view.tasks.length})${task ? ` ${task.title}${task.step ? ` · ${task.step}` : ''}${parallel}` : ''}`,
426 ]
427 if (view.phase !== null && group) {
428 crumbs.unshift(`Phase ${view.phase} (${phases.indexOf(group) + 1}/${phases.length})`)
429 }
430
431 return crumbs.join(' \\ ')
432}
433types/index.d.ts 88 lines1export type TaskStatus = 'pending' | 'in_progress' | 'completed'
2
3export type Task = {
4 id: string
5 subject: string
6 activeForm?: string
7 status: TaskStatus
8}
9
10export type Todo = {
11 content: string
12 status: TaskStatus
13 activeForm?: string
14}
15
16// One task of a superpowers plan, its status from the subagent-driven-development ledger
17export type PlanTask = {
18 n: number
19 title: string
20 // on_hold: deferred by the ledger; unreviewed: implemented, no review yet, while a later task is under way
21 status: TaskStatus | 'on_hold' | 'unreviewed'
22 // The latest ledger step of a task in progress: implementing, review, fix round 2…
23 step?: string
24}
25
26// One plan in the plans folder, with its tasks as its own ledger has them
27export type PlanRow = {
28 name: string
29 // on_hold: a plan other than the running one, with tasks left open
30 status: TaskStatus | 'on_hold'
31 isCurrent: boolean
32 tasks: PlanTask[]
33}
34
35// The plans of one phase, in file name order; phase null holds the plans without a phase
36export type PhaseGroup = {
37 phase: string | null
38 plans: PlanRow[]
39}
40
41// The plan of the newest superpowers ledger and every plan beside it
42export type PlanView = {
43 // false once every task of the plan is complete: the band hides it, the pane keeps it
44 isRunning: boolean
45 phase: string | null
46 name: string
47 tasks: PlanTask[]
48 groups: PhaseGroup[]
49}
50
51// One running background agent, as this mod follows it
52export type TrackedAgent = {
53 id: string
54 // The Agent tool's description: „Plan 10 Task 10: referral invites“
55 description: string
56 // When it started (or was first seen acting), and when it last did something
57 startedAt: number
58 lastAt: number
59 // Its latest tool call, shortened: „Edit …/profile/PlanCard.tsx“; null before its first
60 lastAction: string | null
61 // How many of its tool calls are still running: a long test run is work, not silence
62 toolsRunning: number
63}
64
65declare module 'claude-code' {
66 interface PluginState {
67 // closedOn: what the band showed when it was closed; the band stays hidden until it changes
68 // isMinimized: the band folded to one breadcrumb line
69 // agents: the running background agents; clock: the time as last read, for „running 5 min“ and „9 s ago“;
70 // frame: the terminal spinner's step
71 'task-list': {
72 tasks: Task[]
73 closedOn: string | null
74 plan: PlanView | null
75 cwd: string | null
76 isMinimized: boolean
77 agents: TrackedAgent[]
78 clock: number
79 frame: number
80 }
81 }
82
83 interface McpToolInputs {
84 /** The mod's own todo tool, registered where the built-in task tools are missing */
85 'mcp__task-list__todo_write': { todos: Todo[] }
86 }
87}
88