SLOPSHOPPER

task-progress

Right-side pane that monitors any session (model vitals, tasks, agents, skills, tool activity) plus the superpowers workflow

paneguardcommandprompttimeragents
v0.7.2no licenseupdated 2026-10-10bob-park/claude-task-progress
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · task-progress
│ ┃ Task Progress ✕ › fix the failing auth test and add an audit log call │ ┃ ╭─────────────────────────────────────────── │ ┃ │ — · main ⏺ Read(src/auth.ts) │ ┃ │ effort ▯▯▯▯ — 0 req ⎿ Read 6 lines │ ┃ │ ctx ▰▰▰▰▰▱▱▱▱▱ 49% 97k/200k ⏺ Update(src/auth.ts) │ ┃ │ $0.42 5h ▰▰▱▱▱ 31% ⎿ Added 2 lines, removed 1 line │ ┃ ╰─────────────────────────────────────────── ⏺ Bash(bun test) │ ┃ ╭─────────────────────────────────────────── ⎿ 3 pass, 1 fail │ ┃ │ ACTIVITY │ ┃ │ 08:53 ✓ Bash · Show environment file ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ 08:53 ✓ Bash · Clean build output and push │ ┃ │ 08:53 ✓ Bash · Show working tree status ✻ Worked for 42s · done 4:20 PM │ ┃ ╰─────────────────────────────────────────── │ › /task-progress │ ⎿ task-progress: Task progress opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Task Progress
╭──────────────────────────────────────────────────────╮ │ — · main ○ idle │ │ effort ▯▯▯▯ — 0 req │ │ ctx ▰▰▰▰▰▱▱▱▱▱ 49% 97k/200k │ │ $0.42 5h ▰▰▱▱▱ 31% │ ╰──────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────╮ │ ACTIVITY │ │ 08:53 ✓ Bash · Show environment file │ │ 08:53 ✓ Bash · Clean build output and push │ │ 08:53 ✓ Bash · Show working tree status │ ╰──────────────────────────────────────────────────────╯
README

claude-task-progress

Claude Code mod: a pane docked to the right of the transcript that monitors any session, with a separate section for the superpowers workflow. Sections with nothing to show stay hidden.

  1. main — model, working/idle, effort, permission mode, request count, context gauge (⟲ compactions), cost and rate limits (layout from Flightdeck, MIT)
  2. ⚡ SUPERPOWERS — shows once a superpowers skill runs (or a superpowers plan is opened):
  3. how big the work is (superpowers 7.0.0): PROJECT once a spec or plan is written, SPIKE when brainstorming proposes one (6.4.1's bounded / architectural show as SMALL / PROJECT)
  4. the pipeline ✓brainstorm ✓spec ✓plan ●execute ○review ○finish for a project, otherwise the stages reached; worktree joins once reached, and done stages fold into ✓… when the pane is narrow (the current stage always stays)
  5. the plan's progress bar and current task (docs/superpowers/plans/*.md, ### Task N: headings, completed by the SDD ledger or ticked steps), and when it all finished
  6. its agents by role, working ones first: impl #4 Haiku 5.5 01:12, review #3 approved 00:41 (⚠ … issues when the review wants fixes); brainstorming's builder check shows as a review
  7. extras used along the way: + tdd + debugging + verification
  8. TASKS — todos (TodoWrite / TaskCreate), else a plan-mode plan (~/.claude/plans/*.md, its - [ ] checkboxes, else its numbered steps ticked as 1. [x]): progress bar with done/total · % beside it, in-progress tasks in yellow, the current step below with its number (▸ #2 Wiring), and ✓ completed · 26.10.09 PM 02:05 once every task is done
  9. AGENTS — every other subagent as 1: Explore auth --- Haiku 5.5 01:23, running ones first (⏸ when waiting on its own background work), then the latest 3 that ended (✓ done, ✗ failed) with their final time. The header counts all agents: 2 running · 5 done · 1 failed
  10. SKILLS — every skill run, in order: brainstorming → writing-plans → subagent-driven-development
  11. ACTIVITY — the main loop's latest 3 tool calls: 14:05 ⠹ Bash · Run tests, ✓ once done, ✗ on error

While Claude or an agent works, spinners turn and a bright cell sweeps the in-progress part of each progress bar.

task-progress demo

task-progress screenshot

The pane opens on session start. /task-progress reopens it, /task-progress close closes it. In a non-fullscreen terminal it sits inline above the prompt instead.

Install

/plugin install task-progress --marketplace bob-park/claude-task-progress

Answer y to add the marketplace, then pick a scope.

Source 5 files
hooks/register.tsx 331 lines
1import { atom, read, update } from 'claude-code'
2import type { BuiltinToolResults, EngineInterface, Register, Timer } from 'claude-code'
3
4import type { Activity, AgentRun, AgentStatus, Main, Plan, SkillUse, Sp, Task } from '../types'
5import { isPlanPath, keepCompleted, ledgerOwns, ledgerPath, parsePlan } from './plan'
6import { addExtra, EMPTY_SP, extraOf, isSpecPath, pathFrom, reach, roleOf, skillName, stageOf, taskNOf, verdictOf } from './superpowers'
7import { activityPanel, agentsPanel, FRAME_MS, mainPanel, skillsPanel, spPanel, SPINNER, tasksPanel } from './view'
8
9const tasks = atom({ plugin: 'task-progress', key: 'tasks' } as const, {} as Record<string, Task>)
10const plan = atom({ plugin: 'task-progress', key: 'plan' } as const, { path: '', tasks: [] } as Plan)
11const agents = atom({ plugin: 'task-progress', key: 'agents' } as const, {} as Record<string, AgentRun>)
12const skills = atom({ plugin: 'task-progress', key: 'skills' } as const, [] as SkillUse[])
13const activity = atom({ plugin: 'task-progress', key: 'activity' } as const, [] as Activity[])
14const sp = atom({ plugin: 'task-progress', key: 'sp' } as const, EMPTY_SP)
15const updateSp = ($: EngineInterface, patch: (s: Sp) => Sp) => update($, sp, s => patch({ ...EMPTY_SP, ...s }))
16
17const MAX_AGENTS = 20
18const MAX_ACTIVITY = 10
19const MAX_SKILLS = 30
20/** An agent saved before `status` existed (0.6, kept across a hot reload) reads from its end time */
21export const withStatus = (r: AgentRun): AgentRun => (r.status ? r : { ...r, status: r.endedAt === undefined ? 'running' : 'done' })
22const live = (r: AgentRun) => ['running', 'waiting'].includes(withStatus(r).status)
23// the oldest ended agents go first; running ones always stay
24const trimAgents = (all: Record<string, AgentRun>) => {
25  const ended = Object.entries(all).filter(([, r]) => !live(r)).sort(([, a], [, b]) => a.startedAt - b.startedAt)
26  const drop = new Set(ended.slice(0, Math.max(0, Object.keys(all).length - MAX_AGENTS)).map(([id]) => id))
27  return Object.fromEntries(Object.entries(all).filter(([id]) => !drop.has(id)))
28}
29/** Appends a row with the next id after the kept rows: ids outlive a hot reload, a module counter would not */
30export const pushActivity = (all: Activity[], row: Omit<Activity, 'id'>) => {
31  const id = Math.max(0, ...all.map(a => a.id)) + 1
32  return { id, list: [...all, { ...row, id }].slice(-MAX_ACTIVITY) }
33}
34
35// a failed read keeps what the pane already shows
36const refreshPlan = async ($: EngineInterface, path: string) => {
37  const text = await $.fs.read(path).catch(() => null)
38  if (typeof text !== 'string') return
39  const at = ledgerPath(path)
40  const ledger = at ? await $.fs.read(at).catch(() => null) : null
41  const owned = typeof ledger === 'string' && ledgerOwns(path, ledger) ? ledger : undefined
42  const base = (p: string) => p.slice(p.lastIndexOf('/') + 1)
43  await update($, plan, prev => {
44    const tasks = parsePlan(text, owned)
45    // same plan (maybe now in the main checkout): done stays done
46    const same = !!prev?.path && base(prev.path) === base(path)
47    return { path, tasks: same ? keepCompleted(prev.tasks, tasks) : tasks }
48  })
49}
50
51const DEFAULT_MAIN: Main = {
52  model: '',
53  effort: '',
54  mode: '',
55  steps: 0,
56  isRunning: false,
57  pct: null,
58  tokens: null,
59  window: 0,
60  compactions: 0,
61  costUsd: null,
62  limits: [],
63  doneAt: null,
64}
65const main = atom({ plugin: 'task-progress', key: 'main' } as const, DEFAULT_MAIN)
66
67const PANE = 'task-progress'
68const PANE_COLUMNS = 48
69
70const setMain = ($: EngineInterface, patch: (m: Main) => Partial<Main>) => update($, main, m => ({ ...DEFAULT_MAIN, ...m, ...patch({ ...DEFAULT_MAIN, ...m }) }))
71
72type Usage = Awaited<ReturnType<EngineInterface['session']['usage']>>
73const usageOf = (u: Pick<Usage, 'context' | 'cost' | 'rateLimits'>): Partial<Main> => ({
74  pct: u.context.percent ?? null,
75  tokens: u.context.tokens ?? null,
76  window: u.context.window,
77  costUsd: u.cost?.usd ?? null,
78  limits: u.rateLimits.map(r => ({ kind: r.kind, pct: r.percentUsed })),
79})
80
81// while a turn runs the pane redraws on a clock so the spinner and shimmer move
82const frame = () => Math.floor(Date.now() / FRAME_MS)
83let ticker: Timer | undefined
84// the clock runs while the main turn or any agent is working
85const animate = async ($: EngineInterface) => {
86  const [m, a] = await Promise.all([read($, main), read($, agents)])
87  const on = !!m?.isRunning || Object.values(a ?? {}).some(live)
88  if (on) ticker ??= $.clock.every(FRAME_MS, () => $.ui.invalidate('ui.render'))
89  else ticker = void ticker?.cancel()
90}
91
92// a superpowers plan has an SDD ledger beside it; a plan-mode plan has none
93const isSpPlan = (p: Plan | undefined) => !!p?.path && ledgerPath(p.path) !== null
94const spTasks = (p: Plan | undefined) => (isSpPlan(p) ? p!.tasks : [])
95
96// TASKS: todos win, unless all are done and a plan-mode plan still has open work
97const shownTasks = (todos: Task[], p: Plan | undefined) => {
98  const pm = isSpPlan(p) ? [] : (p?.tasks ?? [])
99  const planOpen = pm.some(t => t.status !== 'completed')
100  return todos.some(t => t.status !== 'completed') || (todos.length > 0 && !planOpen) ? todos : pm
101}
102
103const allDone = (list: Task[]) => list.length > 0 && list.every(t => t.status === 'completed')
104
105// the moment each list became all done; cleared once something is open again
106const stampDone = async ($: EngineInterface) => {
107  const [todos, p, m, s] = await Promise.all([read($, tasks).then(t => Object.values(t ?? {})), read($, plan), read($, main), read($, sp)])
108  const tasksDone = allDone(shownTasks(todos, p))
109  const planDone = allDone(spTasks(p))
110  if (tasksDone === (typeof m?.doneAt === 'number') && planDone === (typeof s?.doneAt === 'number')) return
111  const at = await $.clock.now()
112  if (tasksDone !== (typeof m?.doneAt === 'number')) await setMain($, () => ({ doneAt: tasksDone ? at : null }))
113  if (planDone !== (typeof s?.doneAt === 'number')) await updateSp($, x => ({ ...x, doneAt: planDone ? at : null }))
114}
115
116// `Bash · Run tests`, `Read · plan.ts`: the tool and the most telling input it has
117const activityOf = (e: { tool: string; description?: unknown; file_path?: unknown; pattern?: unknown; command?: unknown }) => {
118  const what = [e.description, e.file_path, e.pattern, e.command].find(x => typeof x === 'string' && x) as string | undefined
119  return what ? `${e.tool} · ${what.slice(what.lastIndexOf('/') + 1)}` : e.tool
120}
121
122const openPane = ($: EngineInterface) => $.ui.open({ id: PANE, title: 'Task Progress', columns: PANE_COLUMNS, rows: 8 })
123
124export const register: Register = on => {
125  on('session.start', async ($, e, next) => {
126    await $.command.register({ name: 'task-progress', description: 'Open or close the task progress pane', argumentHint: '[close]' })
127    // a host without usage (headless, SDK) just starts without it
128    const u = await $.session.usage().catch(() => null)
129    if (u) await setMain($, () => usageOf(u))
130    void openPane($).catch(() => undefined)
131    return next(e)
132  })
133
134  on('command.run', { command: 'task-progress' }, async ($, e) => {
135    if (e.args.trim() === 'close') {
136      await $.ui.close({ id: PANE })
137      return { text: 'Task progress closed.' }
138    }
139    const opened = await openPane($)
140    return { text: opened.isPlaced ? 'Task progress opened.' : `Task progress is not shown yet: ${opened.reason}` }
141  })
142
143  on('classic.UserPromptSubmit', async ($, e, next) => {
144    if (e.permission_mode) await setMain($, () => ({ mode: e.permission_mode }))
145    return next(e)
146  })
147
148  on('turn.start', async ($, e, next) => {
149    await setMain($, () => ({ isRunning: true }))
150    await animate($)
151    return next(e)
152  })
153
154  on('turn.complete', async ($, e, next) => {
155    const done = await next(e)
156    if (e.agentId) {
157      const { agentId } = e
158      // an agent waiting on its own background work ends its turn but isn't done
159      const waiting = (await $.agent.list().catch(() => [])).find(a => a.id === agentId)?.status === 'waiting'
160      const at = await $.clock.now()
161      const status: AgentStatus = waiting ? 'waiting' : e.reason === 'error' || e.reason === 'aborted' ? 'failed' : 'done'
162      await update($, agents, all => {
163        const r = all?.[agentId]
164        const verdict = r?.role === 'review' && !waiting ? verdictOf(e.answer) : undefined
165        return r ? { ...all, [agentId]: { ...r, status, ...(waiting ? {} : { endedAt: at }), ...(verdict ? { verdict } : {}) } } : all
166      })
167    } else {
168      await setMain($, () => ({ isRunning: false }))
169      // brainstorming says out loud which path it takes
170      const path = pathFrom(e.answer)
171      if (path) await updateSp($, s => (s.current === 'brainstorm' ? { ...s, path } : s))
172    }
173    await animate($)
174    return done
175  })
176
177  on('turn.step', async function* ($, e, next) {
178    const { agentId } = e
179    if (!agentId) await setMain($, m => ({ model: e.model, effort: String(e.effort ?? m.effort), steps: m.steps + 1 }))
180    else {
181      // a step after its end: the agent resumed once its background work came back
182      const r = (await read($, agents))?.[agentId]
183      if (r) {
184        const { endedAt: _, ...run } = r
185        await update($, agents, all => ({ ...all, [agentId]: { ...run, model: e.model, status: 'running' as const } }))
186        if (!live(r)) await animate($)
187      }
188    }
189    return yield* next(e)
190  })
191
192  on('agent.spawn', async ($, e, next) => {
193    const spawned = await next(e)
194    const { agentId, model = '' } = spawned as { agentId?: string; model?: string }
195    if (agentId) {
196      const startedAt = await $.clock.now()
197      // while superpowers runs (until it finishes), its implementers and reviewers get a role
198      const s = await read($, sp)
199      const role = s?.stages.length && s.current !== 'finish' ? roleOf(e.description) : undefined
200      // the description alone: prompts quote plan text, Task numbers included
201      const taskN = role ? taskNOf(e.description) : undefined
202      // SDD's whole-branch review has no task: execution is over
203      if (role === 'review' && !taskN && s?.current === 'execute') await updateSp($, x => reach(x, 'review'))
204      // next after the highest still listed: one left running keeps its number
205      await update($, agents, all =>
206        trimAgents({
207          ...all,
208          [agentId]: { n: Math.max(0, ...Object.values(all ?? {}).map(r => r.n)) + 1, label: e.description || e.subagentType, model, startedAt, status: 'running', ...(role ? { role } : {}), ...(taskN ? { taskN } : {}) },
209        }),
210      )
211      await animate($)
212    }
213    return spawned
214  })
215
216  on('skill.prompt', async ($, e, next) => {
217    const at = await $.clock.now()
218    const name = skillName(e.skill)
219    // the same skill twice in a row is one entry
220    await update($, skills, all => (all?.at(-1)?.name === name ? all : [...(all ?? []), { name, at }].slice(-MAX_SKILLS)))
221    const stage = stageOf(e.skill)
222    const extra = extraOf(e.skill)
223    if (stage) await updateSp($, s => reach(s, stage))
224    else if (extra) await updateSp($, s => addExtra(s, extra))
225    return next(e)
226  })
227
228  on('session.measure', async ($, e, next) => {
229    await setMain($, () => usageOf(e))
230    return next(e)
231  })
232
233  on('session.compact', async ($, e, next) => {
234    const done = await next(e)
235    if (!e.agentId && e.trigger !== 'precompute') await setMain($, m => ({ compactions: m.compactions + 1 }))
236    return done
237  })
238
239  on('tool.call', async ($, e, next) => {
240    let id = 0
241    if (!e.agentId) {
242      const row = { at: await $.clock.now(), label: activityOf(e as Parameters<typeof activityOf>[0]), status: 'running' as const }
243      await update($, activity, all => {
244        const pushed = pushActivity(all ?? [], row)
245        id = pushed.id
246        return pushed.list
247      })
248    }
249    const settle = async (status: Activity['status']) => {
250      if (id) await update($, activity, all => (all ?? []).map(a => (a.id === id ? { ...a, status } : a)))
251    }
252    let ran: Awaited<ReturnType<typeof next>>
253    try {
254      ran = await next(e)
255    } catch (err) {
256      await settle('error')
257      throw err
258    }
259    await settle(ran.deny !== undefined || ran.isError ? 'error' : 'ok')
260    if (ran.deny !== undefined || ran.isError) return ran
261
262    if (e.tool === 'TodoWrite') {
263      // TodoWrite replaces the whole list
264      const list = Object.fromEntries(e.todos.map((t, i) => [`todo:${i}`, { status: t.status, label: t.activeForm || t.content }]))
265      await update($, tasks, () => list)
266    } else if (e.tool === 'TaskCreate') {
267      // next(e) ran before e.tool was narrowed, so result isn't typed per tool
268      const id = (ran.result as BuiltinToolResults['TaskCreate'] | undefined)?.task?.id
269      const label = e.activeForm || e.subject
270      if (id) await update($, tasks, all => ({ ...all, [id]: { status: 'pending' as const, label, n: id } }))
271    } else if (e.tool === 'TaskUpdate') {
272      const { taskId, status, activeForm, subject } = e
273      await update($, tasks, all => {
274        const { [taskId]: prev, ...rest } = all
275        if (status === 'deleted' || !prev) return rest
276        return { ...rest, [taskId]: { ...prev, status: status ?? prev.status, label: activeForm || subject || prev.label } }
277      })
278    }
279
280    if (e.agentId) {
281      await stampDone($)
282      return ran
283    }
284    const planned = e.tool === 'ExitPlanMode' ? (ran.result as BuiltinToolResults['ExitPlanMode'] | undefined)?.filePath : undefined
285    // Read too: a plan written in an earlier session is executed by reading it
286    const written = (e.tool === 'Write' || e.tool === 'Edit' || e.tool === 'Read') && isPlanPath(e.file_path) ? e.file_path : undefined
287    const prev = await read($, plan)
288    const path = planned ?? written ?? prev?.path
289    if (path) await refreshPlan($, path)
290    if ((e.tool === 'Write' || e.tool === 'Edit') && isSpecPath(e.file_path)) await updateSp($, s => reach(s, 'spec'))
291    // a superpowers plan reaches the plan stage; one already reached is only re-read
292    const base = (p: string) => p.slice(p.lastIndexOf('/') + 1)
293    if (written && ledgerPath(written)) {
294      const fresh = !prev?.path || base(prev.path) !== base(written)
295      await updateSp($, s => (fresh || !s.stages.includes('plan') ? reach(s, 'plan') : s))
296    }
297    await stampDone($)
298    if (!planned) return ran
299    return { ...ran, context: [...(ran.context ?? []), `Mark each step done by ticking it (- [x], or 1. [x] for numbered steps) in ${planned} as you finish it.`] }
300  })
301
302  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
303    const [m, todos, p, runs, used, acts, s, now] = await Promise.all([
304      read($, main).then(x => ({ ...DEFAULT_MAIN, ...x })),
305      read($, tasks).then(Object.values),
306      read($, plan),
307      read($, agents).then(a => Object.values(a ?? {}).map(withStatus)),
308      read($, skills).then(s => s ?? []),
309      read($, activity).then(a => a ?? []),
310      read($, sp).then(x => ({ ...EMPTY_SP, ...x })),
311      $.clock.now(),
312    ])
313    const list = shownTasks(todos, p)
314    const ui = $.ui.resolve(e)
315    const { Box } = ui
316    const f = frame()
317    // a background agent keeps the session working after the main turn ends
318    const v = { W: Math.max(30, e.props.bodyColumns), f, spin: SPINNER[f % SPINNER.length]!, busy: m.isRunning || runs.some(live), now }
319    return (
320      <Box flexDirection="column">
321        {mainPanel(ui, m, v)}
322        {s.stages.length > 0 ? spPanel(ui, s, spTasks(p), runs, v) : null}
323        {list.length > 0 ? tasksPanel(ui, list, m.doneAt, v) : null}
324        {runs.some(r => !r.role) ? agentsPanel(ui, runs, v) : null}
325        {used.length > 0 ? skillsPanel(ui, used.map(u => u.name), v) : null}
326        {acts.length > 0 ? activityPanel(ui, acts, v) : null}
327      </Box>
328    )
329  })
330}
331
hooks/plan.ts 78 lines
1import type { Task } from '../types'
2
3const TASK_HEADING = /^###\s+Task\s+(\d+):\s*(.+)$/
4const CHECKBOX = /^\s*[-*]\s+\[([ xX])\]\s+(.+)$/
5const NUMBERED = /^(\d+)\.\s+(?:\[([ xX])\]\s+)?(.+)$/
6
7const clean = (s: string) => s.replace(/\*\*/g, '').trim()
8
9/** Plan lines outside fenced code blocks: plans quote templates inside fences */
10const planLines = (text: string) => {
11  let fenced = false
12  return text.split(/\r?\n/).filter(l => {
13    if (l.trimStart().startsWith('```')) fenced = !fenced
14    else return !fenced
15    return false
16  })
17}
18
19export const isPlanPath = (p: string) => /\/(docs\/superpowers\/plans|\.claude\/plans)\/[^/]+\.md$/.test(p)
20
21/** The SDD ledger beside a superpowers plan; null for any other plan */
22export const ledgerPath = (planPath: string) => {
23  const m = /^(.*)\/docs\/superpowers\/plans\/([^/]+)\.md$/.exec(planPath)
24  return m ? `${m[1]}/.superpowers/sdd/${m[2]}/progress.md` : null
25}
26
27/** A ledger's first line names the plan it tracks */
28export const ledgerOwns = (planPath: string, ledger: string) =>
29  (ledger.split(/\r?\n/, 1)[0] ?? '').includes(planPath.slice(planPath.lastIndexOf('/') + 1))
30
31/** Done items first get their status; the first open one is current once anything has started */
32const withCurrent = (items: Array<{ label: string; done: boolean; n?: string }>, started: boolean): Task[] => {
33  const current = items.findIndex(i => !i.done)
34  return items.map((i, k) => ({
35    status: i.done ? 'completed' : started && k === current ? 'in_progress' : 'pending',
36    label: i.label,
37    ...(i.n ? { n: i.n } : {}),
38  }))
39}
40
41/** Re-read plan keeps what was done: finishing a branch drops the SDD ledger */
42export const keepCompleted = (prev: Task[], next: Task[]): Task[] => {
43  const done = new Set(prev.filter(t => t.status === 'completed').map(t => t.label))
44  return withCurrent(
45    next.map(t => ({ label: t.label, n: t.n, done: t.status === 'completed' || done.has(t.label) })),
46    next.some(t => t.status !== 'pending') || next.some(t => done.has(t.label)),
47  )
48}
49
50export const parsePlan = (text: string, ledger?: string): Task[] => {
51  const lines = planLines(text)
52
53  // superpowers: `### Task N:` headings, steps beneath, ledger lines `Task N: complete`
54  const tasks: Array<{ n: string; label: string; steps: boolean[] }> = []
55  for (const line of lines) {
56    const h = TASK_HEADING.exec(line)
57    if (h) tasks.push({ n: h[1]!, label: clean(h[2]!), steps: [] })
58    else {
59      const c = CHECKBOX.exec(line)
60      if (c) tasks.at(-1)?.steps.push(c[1] !== ' ')
61    }
62  }
63  if (tasks.length > 0) {
64    const logged = new Set([...(ledger ?? '').matchAll(/^Task (\d+): complete/gm)].map(m => m[1]))
65    const started = logged.size > 0 || tasks.some(t => t.steps.some(Boolean))
66    return withCurrent(
67      tasks.map(t => ({ label: t.label, n: t.n, done: logged.has(t.n) || (t.steps.length > 0 && t.steps.every(Boolean)) })),
68      started,
69    )
70  }
71
72  // plan mode: checkboxes, else top-level numbered items (ticked as `1. [x]`)
73  const items = lines.map(l => CHECKBOX.exec(l)).filter(m => m !== null).map(m => ({ label: clean(m[2]!), done: m[1] !== ' ' }))
74  if (items.length > 0) return withCurrent(items, items.some(i => i.done))
75  const numbered = lines.map(l => NUMBERED.exec(l)).filter(m => m !== null).map(m => ({ label: clean(m[3]!), n: m[1]!, done: !!m[2] && m[2] !== ' ' }))
76  return withCurrent(numbered, numbered.some(i => i.done))
77}
78
hooks/superpowers.ts 91 lines
1import type { Role, Sp, SpPath, Stage } from '../types'
2
3/** Workflow order; a stage only moves forward within one cycle */
4export const ORDER: Stage[] = ['brainstorm', 'spec', 'plan', 'worktree', 'execute', 'review', 'finish']
5
6const STAGE_OF: Record<string, Stage> = {
7  brainstorming: 'brainstorm',
8  'writing-plans': 'plan',
9  'using-git-worktrees': 'worktree',
10  'subagent-driven-development': 'execute',
11  'executing-plans': 'execute',
12  'dispatching-parallel-agents': 'execute',
13  'requesting-code-review': 'review',
14  'receiving-code-review': 'review',
15  'finishing-a-development-branch': 'finish',
16}
17
18const EXTRA_OF: Record<string, string> = {
19  'test-driven-development': 'tdd',
20  'systematic-debugging': 'debugging',
21  'verification-before-completion': 'verification',
22}
23
24export const isSpecPath = (p: string) => /\/docs\/superpowers\/specs\/[^/]+\.md$/.test(p)
25
26export const EMPTY_SP: Sp = { stages: [], extras: [], doneAt: null }
27
28/** `superpowers:brainstorming` → `brainstorming` */
29export const skillName = (skill: string) => skill.slice(skill.lastIndexOf(':') + 1)
30export const stageOf = (skill: string): Stage | undefined => STAGE_OF[skillName(skill)]
31export const extraOf = (skill: string): string | undefined => EXTRA_OF[skillName(skill)]
32
33/** A stage before the current one never moves it back; after finish it starts a new cycle */
34export const reach = (sp: Sp, stage: Stage): Sp => {
35  const at = (s: Stage | undefined) => (s ? ORDER.indexOf(s) : -1)
36  const base = sp.stages.includes('finish') && at(stage) < at('finish') ? EMPTY_SP : sp
37  const stages = base.stages.includes(stage) ? base.stages : [...base.stages, stage]
38  const current = at(base.current) > at(stage) ? base.current : stage
39  // a spec or plan is only written for a project
40  const path = stage === 'spec' || stage === 'plan' ? 'project' : base.path
41  return { ...base, stages, ...(current ? { current } : {}), ...(path ? { path } : {}) }
42}
43
44export const addExtra = (sp: Sp, extra: string): Sp => (sp.extras.includes(extra) ? sp : { ...sp, extras: [...sp.extras, extra] })
45
46// 7.0.0 sizes the work in plain words and names only a spike; 6.4.1 named three paths
47const PATH_OF: Record<string, SpPath> = { spike: 'spike', bounded: 'small', architectural: 'project' }
48
49/** The last spike (or 6.4.1 path) a reply names */
50export const pathFrom = (text: string) => PATH_OF[[...text.matchAll(/\b(spike|bounded|architectural)\b/gi)].at(-1)?.[1]?.toLowerCase() ?? '']
51
52// a small change or a spike goes through the normal workflow: only reached stages draw
53const TEMPLATE: Record<SpPath, Stage[]> = {
54  project: ['brainstorm', 'spec', 'plan', 'execute', 'review', 'finish'],
55  small: [],
56  spike: [],
57}
58
59export type Step = { stage: Stage; state: 'done' | 'current' | 'todo' }
60
61/** The path's stages plus every stage reached, in order; before the current one counts as done */
62export const pipeline = (sp: Sp): Step[] => {
63  const template = sp.path ? TEMPLATE[sp.path] : []
64  const at = sp.current ? ORDER.indexOf(sp.current) : -1
65  return ORDER.filter(s => sp.stages.includes(s) || template.includes(s)).map(stage => {
66    const i = ORDER.indexOf(stage)
67    return { stage, state: i < at ? 'done' : i === at ? 'current' : 'todo' }
68  })
69}
70
71/** SDD dispatches `Implement Task N: …`, `Review Task N (…)`, `Re-review Task N …`; 7.0.0 brainstorming a builder check */
72export const roleOf = (description: string): Role | undefined =>
73  /^implement\b/i.test(description) ? 'impl' : /review|builder/i.test(description) ? 'review' : undefined
74
75export const taskNOf = (text: string) => /\bTask\s+(\d+)/.exec(text)?.[1]
76
77/** A reviewer's report: `Needs fixes` / `NOT ADDRESSED` / ❌ before `Approved` / `ADDRESSED` / ✅ / a builder check's `nothing important left` */
78export const verdictOf = (answer: string): 'ok' | 'issues' | undefined =>
79  /needs fixes|not addressed|❌/i.test(answer) ? 'issues' : /approved|addressed|✅|nothing important left/i.test(answer) ? 'ok' : undefined
80
81/** Joins parts; too wide drops the oldest (at most `droppable`) behind `lead` so the latest stay */
82export const fitTail = (parts: string[], sep: string, width: number, lead: string, droppable = parts.length - 1) => {
83  let rest = parts
84  let line = rest.join(sep)
85  while (line.length > width && parts.length - rest.length < droppable) {
86    rest = rest.slice(1)
87    line = [lead, ...rest].join(sep)
88  }
89  return line
90}
91
hooks/view.tsx 257 lines
1import type { EngineInterface } from 'claude-code'
2
3import type { Activity, AgentRun, Main, Sp, Task } from '../types'
4import { fitTail, pipeline } from './superpowers'
5
6/** `$.ui.resolve(e)`: the surface's Box, Text, ... */
7export type UI = ReturnType<EngineInterface['ui']['resolve']>
8
9/** What every section draws with: the body width, the clock and whether anything works */
10export type Frame = { W: number; f: number; spin: string; busy: boolean; now: number }
11
12export const SPINNER = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
13export const FRAME_MS = 100
14
15// Formatting below is adapted from Flightdeck (MIT, github.com/scasella/claude-flightdeck)
16export const prettyModel = (id: string) => {
17  if (!id) return '—'
18  const m = /claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?![\d])/i.exec(id)
19  return m?.[1] ? `${m[1].charAt(0).toUpperCase()}${m[1].slice(1).toLowerCase()} ${m[2]}${m[3] ? `.${m[3]}` : ''}` : id.slice(0, 22)
20}
21const kTokens = (n: number) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n))
22const fmtUsd = (n: number) => (n >= 100 ? `$${Math.round(n)}` : `$${n.toFixed(2)}`)
23const gauge = (pct: number, width: number) => {
24  const full = Math.max(0, Math.min(width, Math.round((pct / 100) * width)))
25  return { on: '▰'.repeat(full), off: '▱'.repeat(width - full) }
26}
27const limitLabel = (kind: string) =>
28  kind
29    .replace(/five[_ -]?hours?/i, '5h')
30    .replace(/seven[_ -]?days?/i, '7d')
31    .replace(/[_-]+/g, ' ')
32    .trim()
33
34export const mmss = (ms: number) => {
35  const s = Math.max(0, Math.floor(ms / 1000))
36  return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`
37}
38// `26.10.09 PM 02:05`
39export const doneTime = (at: number) => {
40  const d = new Date(at)
41  const h = d.getHours()
42  const p2 = (n: number) => String(n).padStart(2, '0')
43  return `${p2(d.getFullYear() % 100)}.${p2(d.getMonth() + 1)}.${p2(d.getDate())} ${h < 12 ? 'AM' : 'PM'} ${p2(h % 12 || 12)}:${p2(d.getMinutes())}`
44}
45
46const numbered = (t: Task) => (t.n ? `#${t.n} ${t.label}` : t.label)
47
48// `icon left ----- right`, the right column lined up; a long left is cut with …
49export const lineUp = (icon: string, left: string, right: string, W: number, fill: string) => {
50  const room = W - 4 - 2 - right.length - 4 // icon, then ` ---` at the least
51  const l = left.length > room ? `${left.slice(0, Math.max(0, room - 1))}…` : left
52  return `${icon} ${l} ${fill.repeat(Math.max(3, room - l.length + 3))}${right}`
53}
54
55// ---- main (layout from Flightdeck's main panel)
56export const mainPanel = ({ Box, Text }: UI, m: Main, v: Frame) => {
57  const effortN = { low: 1, medium: 2, high: 3, xhigh: 4, max: 4 }[m.effort] ?? 0
58  const ctx = m.pct !== null ? gauge(m.pct, 10) : null
59  return (
60    <Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} width={v.W}>
61      <Box justifyContent="space-between">
62        <Text color="cyan" bold>{`${prettyModel(m.model)} · main`}</Text>
63        <Text color={v.busy ? 'cyan' : undefined} dimColor={!v.busy}>{v.busy ? `${v.spin} working` : '○ idle'}</Text>
64      </Box>
65      <Text wrap="truncate">
66        <Text dimColor>effort </Text>
67        <Text color="cyan">{'▮'.repeat(effortN) + '▯'.repeat(4 - effortN)} </Text>
68        <Text color="cyan" bold>{m.effort || '—'}</Text>
69        {m.mode ? <Text dimColor>{`   mode ${m.mode}`}</Text> : null}
70        <Text dimColor>{`   ${m.steps} req`}</Text>
71      </Text>
72      {ctx ? (
73        <Text wrap="truncate">
74          <Text dimColor>ctx </Text>
75          <Text color={m.pct !== null && m.pct >= 80 ? 'red' : 'cyan'}>{ctx.on}</Text>
76          <Text dimColor>{ctx.off}</Text>
77          <Text bold>{` ${Math.round(m.pct ?? 0)}%`}</Text>
78          {m.tokens !== null ? <Text dimColor>{` ${kTokens(m.tokens)}/${kTokens(m.window)}`}</Text> : null}
79          {m.compactions > 0 ? <Text color="yellow">{`  ⟲${m.compactions}`}</Text> : null}
80        </Text>
81      ) : null}
82      {m.costUsd !== null || m.limits.length > 0 ? (
83        <Text wrap="truncate">
84          {m.costUsd !== null ? <Text>{`${fmtUsd(m.costUsd)}   `}</Text> : null}
85          {m.limits.slice(0, 2).map(l => {
86            const g = gauge(l.pct, 5)
87            return (
88              <Text key={l.kind}>
89                <Text dimColor>{`${limitLabel(l.kind)} `}</Text>
90                <Text color={l.pct >= 80 ? 'red' : 'cyan'}>{g.on}</Text>
91                <Text dimColor>{`${g.off} ${Math.round(l.pct)}%  `}</Text>
92              </Text>
93            )
94          })}
95        </Text>
96      ) : null}
97    </Box>
98  )
99}
100
101// ---- progress: the bar with done/total right after it, and the current step below
102export const progressLines = ({ Text }: UI, list: Task[], doneAt: number | null, v: Frame) => {
103  const total = list.length
104  const done = list.filter(t => t.status === 'completed').length
105  const active = list.filter(t => t.status === 'in_progress')
106  const barW = Math.max(10, v.W - 4 - ` ${total}/${total} · 100%`.length - 1)
107  const filled = Math.round((done / total) * barW)
108  const activeCells = Math.round(((done + active.length) / total) * barW) - filled
109  const percent = Math.round((done / total) * 100)
110  const next = list.find(t => t.status === 'pending')
111  // a bright cell sweeps across the in-progress part of the bar while working
112  const sweep = v.busy && activeCells > 0 ? v.f % activeCells : -1
113  return [
114    // count sits right after the bar so the eye doesn't travel
115    <Text key="bar" wrap="truncate">
116      <Text color="green">{'█'.repeat(filled)}</Text>
117      {sweep >= 0 ? (
118        <Text color="yellow">
119          {'▓'.repeat(sweep)}
120          <Text bold>█</Text>
121          {'▓'.repeat(activeCells - sweep - 1)}
122        </Text>
123      ) : (
124        <Text color="yellow">{'▓'.repeat(activeCells)}</Text>
125      )}
126      <Text dimColor>{'░'.repeat(barW - filled - activeCells)}</Text>
127      <Text bold color="blue">{` ${done}/${total}`}</Text>
128      <Text dimColor>{` · ${percent}%`}</Text>
129    </Text>,
130    done === total ? (
131      <Text key="now" color="green">{doneAt !== null ? `✓ completed · ${doneTime(doneAt)}` : '✓ completed'}</Text>
132    ) : active.length > 0 ? (
133      <Text key="now" color="yellow" wrap="truncate">{`${v.busy ? v.spin : '▸'} ${active.map(numbered).join(', ')}`}</Text>
134    ) : (
135      <Text key="now" dimColor wrap="truncate">{`○ 다음: ${next ? numbered(next) : '—'}`}</Text>
136    ),
137  ]
138}
139
140// ---- tasks
141export const tasksPanel = (ui: UI, list: Task[], doneAt: number | null, v: Frame) => {
142  const { Box, Text } = ui
143  const allDone = list.every(t => t.status === 'completed')
144  return (
145    <Box flexDirection="column" borderStyle="round" borderColor="green" paddingX={1} width={v.W}>
146      <Text color="green" bold>{allDone ? '✓ TASKS' : 'TASKS'}</Text>
147      {progressLines(ui, list, doneAt, v)}
148    </Box>
149  )
150}
151
152// ---- agents: running ones first, the latest on top, then the latest ended ones
153const ENDED_SHOWN = 3
154const ICON = { waiting: '⏸', done: '✓', failed: '✗' } as const
155const COLOR = { running: 'yellow', waiting: 'cyan', done: undefined, failed: 'red' } as const
156
157/** `⠹ 1: label --- Model mm:ss`; an ended row keeps its final time */
158export const agentRow = ({ Text }: UI, r: AgentRun, left: string, right: string, fill: string, v: Frame, icon?: string) => (
159  <Text key={String(r.n)} color={COLOR[r.status]} dimColor={r.status === 'done'} wrap="truncate">
160    {lineUp(icon ?? (r.status === 'running' ? v.spin : ICON[r.status]), left, right, v.W, fill)}
161  </Text>
162)
163
164export const agentsPanel = (ui: UI, all: AgentRun[], v: Frame) => {
165  const { Box, Text } = ui
166  const live = all.filter(r => r.status === 'running' || r.status === 'waiting').sort((x, y) => y.startedAt - x.startedAt)
167  const ended = all.filter(r => r.status === 'done' || r.status === 'failed').sort((x, y) => (y.endedAt ?? 0) - (x.endedAt ?? 0))
168  const failed = ended.filter(r => r.status === 'failed').length
169  // superpowers' own agents show under SUPERPOWERS; the header still counts them
170  const shown = (rs: AgentRun[]) => rs.filter(r => !r.role)
171  return (
172    <Box flexDirection="column" borderStyle="round" borderColor="magenta" paddingX={1} width={v.W}>
173      <Text wrap="truncate">
174        <Text color="magenta" bold>AGENTS</Text>
175        <Text dimColor>{`  ${live.length} running · ${ended.length - failed} done${failed > 0 ? ` · ${failed} failed` : ''}`}</Text>
176      </Text>
177      {[...shown(live), ...shown(ended).slice(0, ENDED_SHOWN)].map(r =>
178        agentRow(ui, r, `${r.n}: ${r.label}`, ` ${prettyModel(r.model)} ${mmss((r.endedAt ?? v.now) - r.startedAt)}`, '-', v),
179      )}
180    </Box>
181  )
182}
183
184// ---- superpowers: path badge, pipeline, plan progress, its agents by role, extras
185const ROLES_SHOWN = 4
186export const spPanel = (ui: UI, sp: Sp, plan: Task[], runs: AgentRun[], v: Frame) => {
187  const { Box, Text } = ui
188  const mark = { done: '✓', current: v.busy ? v.spin : '●', todo: '○' }
189  const steps = pipeline(sp)
190  // only done stages fold: the current one never leaves the line
191  const line = fitTail(
192    steps.map(s => `${mark[s.state]}${s.stage}`),
193    ' ',
194    v.W - 4,
195    '✓…',
196    steps.filter(s => s.state === 'done').length,
197  )
198  // working ones first, then the latest: SDD runs one at a time, so that is where it is now
199  const roles = runs
200    .filter(r => r.role)
201    .sort((x, y) => Number(y.status === 'running' || y.status === 'waiting') - Number(x.status === 'running' || x.status === 'waiting') || y.n - x.n)
202    .slice(0, ROLES_SHOWN)
203  return (
204    <Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} width={v.W}>
205      <Box justifyContent="space-between">
206        <Text color="yellow" bold>⚡ SUPERPOWERS</Text>
207        {sp.path ? <Text color="magenta" bold>{sp.path.toUpperCase()}</Text> : null}
208      </Box>
209      <Text wrap="truncate">{line}</Text>
210      {plan.length > 0 ? progressLines(ui, plan, sp.doneAt, v) : null}
211      {roles.map(r =>
212        agentRow(
213          ui,
214          r,
215          `${r.role} ${r.taskN ? `#${r.taskN}` : r.label}`,
216          ` ${r.verdict ? (r.verdict === 'ok' ? 'approved' : 'issues') : prettyModel(r.model)} ${mmss((r.endedAt ?? v.now) - r.startedAt)}`,
217          ' ',
218          v,
219          r.verdict === 'issues' ? '⚠' : undefined,
220        ),
221      )}
222      {sp.extras.length > 0 ? <Text dimColor wrap="truncate">{sp.extras.map(x => `+ ${x}`).join('  ')}</Text> : null}
223    </Box>
224  )
225}
226
227// ---- skills: every skill run, oldest dropped first when too wide
228export const skillsPanel = ({ Box, Text }: UI, names: string[], v: Frame) => (
229  <Box flexDirection="column" borderStyle="round" borderColor="blue" paddingX={1} width={v.W}>
230    <Text color="blue" bold>SKILLS</Text>
231    <Text wrap="truncate">{fitTail(names, ' → ', v.W - 4, '…')}</Text>
232  </Box>
233)
234
235// ---- activity: the main loop's latest tool calls, newest on top
236const ACTIVITY_SHOWN = 3
237const hhmm = (at: number) => {
238  const d = new Date(at)
239  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
240}
241export const activityPanel = ({ Box, Text }: UI, items: Activity[], v: Frame) => (
242  <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1} width={v.W}>
243    <Text bold>ACTIVITY</Text>
244    {items
245      .slice(-ACTIVITY_SHOWN)
246      .reverse()
247      .map(a => (
248        <Text key={String(a.id)} wrap="truncate">
249          <Text dimColor>{`${hhmm(a.at)} `}</Text>
250          <Text color={a.status === 'running' ? 'yellow' : a.status === 'error' ? 'red' : undefined}>
251            {`${a.status === 'running' ? v.spin : a.status === 'error' ? '✗' : '✓'} ${a.label}`}
252          </Text>
253        </Text>
254      ))}
255  </Box>
256)
257
types/index.d.ts 71 lines
1export type TaskStatus = 'pending' | 'in_progress' | 'completed'
2
3/** `n`: the task's number when its source has one (plan `Task N`, TaskCreate id, `1.` step) */
4export type Task = { status: TaskStatus; label: string; n?: string }
5
6export type AgentStatus = 'running' | 'waiting' | 'done' | 'failed'
7
8/** A subagent the model spawned; kept once it ends (`endedAt`), up to the latest 20 */
9export type AgentRun = {
10  n: number
11  label: string
12  model: string
13  startedAt: number
14  endedAt?: number
15  status: AgentStatus
16  /** Set when superpowers dispatched it; such an agent shows under SUPERPOWERS, not AGENTS */
17  role?: Role
18  taskN?: string
19  /** A reviewer's report: approved, or issues to fix */
20  verdict?: 'ok' | 'issues'
21}
22
23/** A skill the session ran, in order */
24export type SkillUse = { name: string; at: number }
25
26/** A main-loop tool call: `Bash · Run tests` */
27export type Activity = { id: number; at: number; label: string; status: 'running' | 'ok' | 'error' }
28
29/** The active plan: a superpowers plan shows under SUPERPOWERS, a plan-mode plan under TASKS */
30export type Plan = { path: string; tasks: Task[] }
31
32/** Main-loop vitals, drawn like Flightdeck's main panel */
33export type Main = {
34  model: string
35  effort: string
36  mode: string
37  steps: number
38  isRunning: boolean
39  pct: number | null
40  tokens: number | null
41  window: number
42  compactions: number
43  costUsd: number | null
44  limits: Array<{ kind: string; pct: number }>
45  /** When the shown tasks all became completed */
46  doneAt: number | null
47}
48
49export type Stage = 'brainstorm' | 'spec' | 'plan' | 'worktree' | 'execute' | 'review' | 'finish'
50/** How big the work is: superpowers 7.0.0 sizes it; a spike skips the plan workflow */
51export type SpPath = 'spike' | 'small' | 'project'
52/** What superpowers dispatched an agent for: SDD's implementer, or any review */
53export type Role = 'impl' | 'review'
54
55/** The superpowers workflow so far; empty `stages` until a superpowers skill runs */
56export type Sp = { path?: SpPath; stages: Stage[]; current?: Stage; extras: string[]; doneAt: number | null }
57
58declare module 'claude-code' {
59  interface PluginState {
60    'task-progress': {
61      tasks: Record<string, Task>
62      main: Main
63      plan: Plan
64      agents: Record<string, AgentRun>
65      skills: SkillUse[]
66      activity: Activity[]
67      sp: Sp
68    }
69  }
70}
71