SLOPSHOPPER

plan-progress

Reads a phased plan into a live progress tree: phases, steps, elapsed time and an estimate of what is left

paneguardcommandtoaststatustool
★ 1v0.5.0no licenseupdated 2026-10-24WeaponizedLego/claude-code-mods/plan-progress
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · plan-progress
│ ┃ Plan progress ✕ › fix the failing auth test and add an audit log call │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ No plan yet │ ⏺ Read(src/auth.ts) │ ┃ │ Approve a plan in plan mode, or ask │ ⎿ Read 6 lines │ ┃ │ Claude to lay a long task out in phases. │ ⏺ Update(src/auth.ts) │ ┃ ╰──────────────────────────────────────────╯ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /plan-progress │ ⎿ plan-progress: No plan yet: approve a plan in plan mode, or ask │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Plan progress
╭──────────────────────────────────────────────────────────╮ │ No plan yet │ │ Approve a plan in plan mode, or ask Claude to lay a long │ │ task out in phases. │ ╰──────────────────────────────────────────────────────────╯
README

claude-code-mods

My Claude Code mods, one folder per mod. Needs Claude Code 2.1.287 or newer.

ModWhat it does
usage-bandA band above the prompt showing context fill, tokens, cost and rate limits: stat tiles in the desktop app, a coloured row in the terminal
plan-progressReads a phased plan into a live progress tree: phases, steps, elapsed time and an estimate of what is left
test-userA Haiku test user that clicks through your locally running app and reports UI/UX issues: its task list, findings and failures in a live pane
change-cardA short card explaining what an agent changed on this branch: a headline, a few one-line changes, where to look first and what was not checked
control-towerA board for a sentinel-hill hub: every ticket worktree with its PR, checks and next step, the validate run above the prompt, and guard rails that enforce the hub's steering

All five mods share one look, dark only: square slate panels on a navy ground, hairline rules, small spaced capitals for labels, light wide numerals, arc gauges and square-ended segment tracks. Amber marks what needs a look or is under way, periwinkle what is done, red what failed. In the desktop app's Code tab they draw as images, in Barlow where it is installed and the system sans otherwise; in the terminal they use the same colours as text.

usage-band in the desktop app

Install

At the prompt of a terminal Claude Code session:

/plugin install usage-band --marketplace WeaponizedLego/claude-code-mods
/plugin install plan-progress --marketplace WeaponizedLego/claude-code-mods

Answer y to add the marketplace, then pick the user scope. Or from a shell:

claude plugin marketplace add WeaponizedLego/claude-code-mods
claude plugin install usage-band@claude-code-mods
claude plugin install plan-progress@claude-code-mods

Update later with claude plugin marketplace update claude-code-mods, then claude plugin update usage-band@claude-code-mods.

plan-progress

plan-progress in the desktop app

When a plan with several phases is approved in plan mode, the mod reads its phases and steps (## Phase 1: ... headings, other work headings, or a nested list) into a tree and opens it in a pane. In the terminal it looks like this:

Move auth to sessions                         20m in · ~40m left
━━━━━━━━━━━━━━━━━━ 33%  2/6 steps · phase 2/3

✓ 1 Setup                                                 20m
  ├ ✓ Add the sessions table                              10m
  └ ✓ Write the session store                             10m
● 2 Switch over
  ├ ● Replace token checks in the middleware
  ├ ○ Update the login endpoint
  └ ○ Remove the old token helpers
○ 3 Verify
  └ ○ Run the auth test suite

The status line carries the short form (▰▰▱▱ 2/6 · phase 2/3: Switch over · 20m in · ~40m left). Steps move when Claude calls the mod's plan_mark tool, or by themselves when Claude's tasks or todos are named like a step. Without plan mode, ask Claude to lay the work out in phases and it calls plan_set. The estimate is the pace so far times the steps left.

During a run of small steps Claude can forget to mark them. When the tree hasn't moved for a while (at least 6 tool calls, and 3 minutes or 1.5× the pace so far, whichever is longer), the next tool result reminds Claude which step the tree shows. Claude can then catch up in one call: plan_mark with through: true closes every earlier open step and splits the elapsed time evenly between them.

/plan-progress opens the tree (it also works mid-turn); /plan-progress clear stops tracking.

test-user

test-user in the desktop app

A test user for the app you are running locally. Ask Claude to "test the app" (or a feature, a page, a flow) and it hands the job to test-user:tester, a subagent on Haiku that drives the app in the browser the way a person would: it works out what to test, finds the app (the URL you gave, .claude/launch.json, package.json), plans a handful of user tasks, works through them and reports each problem it sees. It never edits code, stays on localhost and only uses test data.

When you just say "test the app", Claude points it at the feature most recently built in the session; with nothing built, the tester looks at git diff and git log for a recent feature, and failing that tests the whole application.

The pane shows the run as it goes: status, tasks passed out of total, a count per severity (blocker, major, minor, polish), the task list with a note on each failure, a card per finding (worst first, with where and how to reproduce), a red card when it could not test at all, and earlier runs folded at the bottom. The status line carries the short form (test-user ● 3/6 tasks · 2 findings · 4m · Pay with the test card) and a toast says how it ended.

The session gets the full record, not just the tester's closing message: it rides back on the Agent result when the tester ran in the foreground, and on the next prompt (or the background task's notification) otherwise; test_report reads it any time. A tester whose turn ends early and is resumed carries on with the same run.

Claude gets the same reporting tools (test_plan, test_task, test_finding, test_finish), so a test it runs by hand shows in the pane too, and it can amend the latest tester run with what it re-checked. If the tester stops without a verdict, the record decides it; a "passed" never hides a failed task.

/test-user opens the pane; /test-user run [what to test] starts a run; /test-user clear forgets the runs.

change-card

change-card in the desktop app

/changes opens a Changes pane and asks Claude to explain what changed on the branch since it forked from origin/HEAD (or main/master), uncommitted and untracked files included. Run from a folder that is not itself a repository but holds checkouts (a task folder with one worktree per repo), it reads each of them and prefixes their paths with the folder's name. Claude answers by filling in the mod's change_card tool, which keeps the card short by refusing anything over its limits: a 70-character headline, a one-sentence gist, at most 5 one-line changes (with an optional before → after), at most 3 places to look first and 3 things nobody checked. Every changed file has to sit under one of the changes (a path ending in / covers a folder), so nothing hides.

When the code moves on after the card was written, the pane says which files and /changes asks Claude to update just what they affect. After a turn that leaves a sizeable diff (over 5 files or 200 lines) a toast suggests /changes, once per card; nothing is written unasked.

/changes <worktree or branch> explains that one instead of the session's own checkout: a worktree by its path, folder name, branch or any unique part of those (/changes PLAT-421), or a local branch at its tip. When the session's checkout has nothing changed (say, main with the work in .claude/worktrees/), /changes lists the worktrees that do. /changes <ref> compares against another ref; /changes clear forgets the card.

control-tower

control-tower in the desktop app

For a sentinel-hill hub: a repo you run agents from, with a repos.yaml registry, scripts/worktree.sh and one worktree per ticket under work/<repo>/<KEY>-<slug>. The mod does nothing in any other folder.

The pane opens when a session starts in the hub (or with /tower). It reads every worktree under work/ from disk and asks gh about its PR: one card per ticket, those that need you first, each with a big number (unresolved review threads, checks passed, commits ahead, time since merge) beside a five-stop track (start, build, PR, feedback, close). Under each card are buttons for the next step: Review and Finish while you build, Handle feedback when a PR has unresolved threads, Fix checks when they fail, Close task once it is merged. They run the hub's own skills (/review, /task-finish, /handle-pr-feedback, /task-close). A field at the bottom starts a ticket with /task-start or /implement-ticket. The board syncs every 3 minutes and after a push or gh pr create; a toast says when a PR gets new review threads or is merged.

Above the prompt, a band shows the repo's validate commands from repos.yaml as Claude runs them (done out of total, one bar per command, what is running or failed), or says when the hub is not set up (repos.local.yaml missing, or a gh token without read:packages) with a button that walks you through it. The status line names the ticket Claude is working in: ● OPS-123 · platform-apps · base develop · unattended.

control-tower's validate band

Guard rails refuse tool calls that break the hub's steering, with the reason as the tool result so Claude fixes the call and carries on:

  • git add -A, ., -u and the like: add files by name
  • a commit message that does not match the repo's commit_format with the branch's key, or that carries a Co-Authored-By or "Generated with" line
  • git merge
  • gh pr create from a ticket worktree without --draft, or without the label and assignee the repo's pr_labels and pr_assignee ask for
  • writing into a clone listed in repos.local.yaml (the worktree is the place), or into /tmp (use work/scratch/)
  • a Jira key in code or comments inside a worktree (prose files are fine)

The Unattended and Interactive buttons set the hub's mode: in interactive mode each prompt reminds Claude to stop for approval after the plan. /tower refresh syncs now; /tower interactive and /tower unattended set the mode.

Adding a mod

Put it in its own folder (<mod>/.claude-plugin/plugin.json, <mod>/hooks/...) and add an entry to .claude-plugin/marketplace.json. Check it with claude plugin validate ..

Source 4 files
hooks/register.tsx 443 lines
1import { atom, read, update } from 'claude-code'
2import type { Color, EngineInterface, Register } from 'claude-code'
3
4import type { Plan, StepStatus } from '../types'
5import { C, emptySvg, planSvg } from './look'
6import {
7  TASK_STATUS,
8  bar,
9  duration,
10  findStep,
11  isStale,
12  mark,
13  markThrough,
14  newPlan,
15  outline,
16  parsePlan,
17  phaseDuration,
18  phaseState,
19  stats,
20  statusLine,
21} from './plan'
22
23const PANE = 'plan-progress'
24const TITLE = 'Plan progress'
25const SET = 'mcp__plan-progress__plan_set'
26const MARK = 'mcp__plan-progress__plan_mark'
27const TICK_MS = 30_000
28// Roughly one cell of the desktop's code font, in CSS pixels: the pane's
29// width in pixels, for an image that fills it.
30const CELL_PX = 8
31
32const planAtom = atom({ plugin: 'plan-progress', key: 'plan' } as const, null)
33const nowAtom = atom({ plugin: 'plan-progress', key: 'now' } as const, 0)
34const tasksAtom = atom({ plugin: 'plan-progress', key: 'tasks' } as const, {})
35const quietAtom = atom({ plugin: 'plan-progress', key: 'quiet' } as const, { since: 0, calls: 0, nudgedAt: 0 })
36
37type PlanSetInput = { title?: string; phases?: { title?: string; steps?: string[] }[] }
38type PlanMarkInput = { phase?: number; step?: number; status?: StepStatus; through?: boolean }
39
40// With nothing in progress, the first open step after the last one finished
41// becomes the current one, so its time starts counting.
42function advance(plan: Plan, now: number): Plan {
43  const steps = plan.phases.flatMap((p, pi) => p.steps.map((s, si) => ({ s, pi, si })))
44  if (steps.some(x => x.s.status === 'active')) return plan
45  const next = steps.find(x => x.s.status === 'pending')
46  return next ? mark(plan, next.pi, next.si, 'active', now) : plan
47}
48
49async function setPlan($: EngineInterface, plan: Plan | null, isMoved = true) {
50  await update($, planAtom, () => plan)
51  const t = await $.clock.now()
52  await update($, nowAtom, () => t)
53  if (isMoved) await update($, quietAtom, () => ({ since: t, calls: 0, nudgedAt: 0 }))
54  $.ui.status(plan ? statusLine(plan, t) : undefined)
55}
56
57async function change($: EngineInterface, fn: (plan: Plan, now: number) => Plan): Promise<Plan | null> {
58  const now = await $.clock.now()
59  const before = await read($, planAtom)
60  if (!before) return null
61  const after = advance(fn(before, now), now)
62  // A todo list that names no step leaves the tree, and its quiet, as they were.
63  await setPlan($, after, JSON.stringify(after) !== JSON.stringify(before))
64  return after
65}
66
67const progressText = (plan: Plan, now: number) => {
68  const s = stats(plan, now)
69  if (s.isFinished) return `Plan finished: ${s.total} steps in ${duration(s.elapsedMs)}.`
70  const parts = [`${s.closed}/${s.total} steps (${s.percent}%)`]
71  if (s.currentPhase != null) parts.push(`phase ${s.currentPhase + 1}/${plan.phases.length}`)
72  parts.push(`${duration(s.elapsedMs)} in`)
73  if (s.remainingMs != null) parts.push(`~${duration(s.remainingMs)} left`)
74  return parts.join(' · ')
75}
76
77const howToKeepIt = (plan: Plan) =>
78  [
79    `plan-progress: the user sees this plan as a progress tree (${plan.phases.length} phases, ${plan.phases.flatMap(p => p.steps).length} steps):`,
80    outline(plan),
81    `Keep it current as you work: call ${MARK} with { phase, step, status } as you finish each step ("done"; the next step becomes current by itself) or skip one. ` +
82      `The tree moves only when you mark it, so mark each step the moment you move on, however small; to catch up after several, mark the one you are on with through: true. ` +
83      `If you track the work with TaskCreate/TaskUpdate or TodoWrite instead, name the tasks exactly like the steps above and the tree follows them. ` +
84      `If this tree misreads the plan, call ${SET} with the right phases and steps.`,
85  ].join('\n\n')
86
87// A pane that cannot open (refused, or no surface to draw on) never costs the plan.
88async function openPane($: EngineInterface, isAsked: boolean) {
89  const opened = await $.ui.open({ id: PANE, title: TITLE }).catch(() => ({ isPlaced: false }))
90  if (!opened.isPlaced && !isAsked) $.ui.toast('plan-progress: run /plan-progress to see the phase tree')
91}
92
93export const register: Register = on => {
94  on('session.start', async ($, e, next) => {
95    const result = await next(e)
96
97    await $.tool.register({
98      name: 'plan_set',
99      description:
100        'Show the user a progress tree for a long, multi-phase task: the phases in order, each with its steps. ' +
101        'Use it when you start work that spans several phases and no plan-mode plan was approved, or to correct a tree that misread the plan. ' +
102        'Replaces the current tree. Then report progress with plan_mark.',
103      inputSchema: {
104        type: 'object',
105        properties: {
106          title: { type: 'string', description: 'A short name for the whole task' },
107          phases: {
108            type: 'array',
109            minItems: 1,
110            items: {
111              type: 'object',
112              properties: {
113                title: { type: 'string' },
114                steps: { type: 'array', items: { type: 'string' }, description: 'Short step titles, in order' },
115              },
116              required: ['title', 'steps'],
117            },
118          },
119        },
120        required: ['phases'],
121      },
122      isDeferred: false,
123    })
124    await $.tool.register({
125      name: 'plan_mark',
126      description:
127        "Update the user's plan progress tree. Mark a step done when you finish it (the next step becomes current by itself), " +
128        'active when you start one out of order, skipped when you drop it, or leave out step to mark a whole phase. ' +
129        'With through: true every open step before it is marked done too, to catch up after finishing several. ' +
130        'Phases and steps count from 1, as the outline shows them. Only use while a plan tree exists.',
131      inputSchema: {
132        type: 'object',
133        properties: {
134          phase: { type: 'integer', minimum: 1 },
135          step: { type: 'integer', minimum: 1, description: 'Leave out to mark every open step of the phase' },
136          status: { type: 'string', enum: ['done', 'active', 'skipped', 'pending'] },
137          through: { type: 'boolean', description: 'Also mark every open step before this one done' },
138        },
139        required: ['phase', 'status'],
140      },
141      isDeferred: false,
142    })
143    await $.command.register({
144      name: 'plan-progress',
145      description: 'Show the phase tree of the current plan (clear: stop tracking it)',
146      argumentHint: '[clear]',
147      immediate: true,
148    })
149
150    // Elapsed times move while a plan runs: redraw them twice a minute.
151    $.clock.every(TICK_MS, () => {
152      void (async () => {
153        const plan = await read($, planAtom)
154        if (!plan || stats(plan, 0).isFinished) return
155        const t = await $.clock.now()
156        await update($, nowAtom, () => t)
157        $.ui.status(statusLine(plan, t))
158      })()
159    })
160
161    // After a reload the plan is still in the session's state.
162    const plan = await read($, planAtom)
163    if (plan) $.ui.status(statusLine(plan, await $.clock.now()))
164
165    return result
166  })
167
168  // An approved plan-mode plan becomes the tree.
169  on('tool.call', { tool: 'ExitPlanMode' }, async ($, e, next) => {
170    const ran = await next(e)
171    if (ran.deny !== undefined || ran.isError) return ran
172
173    const text = (ran.result as { plan?: string | null } | undefined)?.plan
174    if (!text) return ran
175    const parsed = parsePlan(text)
176    if (parsed.phases.flatMap(p => p.steps).length < 2) return ran
177
178    const now = await $.clock.now()
179    const plan = advance(newPlan(parsed.title, parsed.phases.map(p => ({ title: p.title, steps: p.steps.map(s => s.title) })), 'plan-mode', now), now)
180    await setPlan($, plan)
181    await openPane($, false)
182
183    return { ...ran, context: [...(ran.context ?? []), howToKeepIt(plan)] }
184  })
185
186  on('tool.call', { tool: SET }, async ($, e) => {
187    const input = e as unknown as PlanSetInput
188    const phases = (input.phases ?? [])
189      .map(p => ({ title: String(p.title ?? ''), steps: (p.steps ?? []).map(String) }))
190      .filter(p => p.title || p.steps.length)
191    if (phases.length === 0) return { deny: 'plan_set needs at least one phase with a title and steps.' }
192
193    const now = await $.clock.now()
194    const plan = advance(newPlan(input.title ?? 'Plan', phases, 'model', now), now)
195    await setPlan($, plan)
196    await openPane($, false)
197    return { result: `Tree shown to the user:\n${outline(plan)}\n\nReport progress with plan_mark.` }
198  })
199
200  on('tool.call', { tool: MARK }, async ($, e) => {
201    const input = e as unknown as PlanMarkInput
202    const plan = await read($, planAtom)
203    if (!plan) return { deny: 'No plan is being tracked. Call plan_set first.' }
204
205    const pi = Number(input.phase) - 1
206    const phase = plan.phases[pi]
207    if (!phase) return { deny: `There is no phase ${input.phase}; the plan has ${plan.phases.length}.\n${outline(plan)}` }
208    const si = input.step == null ? undefined : Number(input.step) - 1
209    if (si !== undefined && !phase.steps[si]) {
210      return { deny: `Phase ${input.phase} has no step ${input.step}; it has ${phase.steps.length}.\n${outline(plan)}` }
211    }
212    const status = input.status ?? 'done'
213
214    const after = (await change($, (p, now) =>
215      input.through && si !== undefined ? markThrough(p, pi, si, status, now) : mark(p, pi, si, status, now),
216    ))!
217    const now = await $.clock.now()
218    const nextUp = after.phases.flatMap((p, i) => p.steps.map((s, j) => ({ s, at: `${i + 1}.${j + 1}` }))).find(x => x.s.status === 'active')
219    const what = si === undefined ? `Phase ${pi + 1}` : `Step ${pi + 1}.${si + 1}`
220    return { result: `${what} marked ${status}. ${progressText(after, now)}${nextUp ? `. Current: ${nextUp.at} ${nextUp.s.title}` : ''}` }
221  })
222
223  // The tree moves only when the model marks it, and in a run of small steps
224  // it forgets to. When the tree has sat still through steady work, the next
225  // tool result tells it where the tree stands.
226  on('tool.call', async ($, e, next) => {
227    const ran = await next(e)
228    if (e.agentId || e.tool === MARK || e.tool === SET || ran.deny !== undefined) return ran
229    const plan = await read($, planAtom)
230    if (!plan || stats(plan, 0).isFinished) return ran
231
232    const quiet = await update($, quietAtom, q => ({ ...q, calls: q.calls + 1 }))
233    const now = await $.clock.now()
234    const quietMs = now - (quiet.since || plan.createdAt)
235    if (!isStale(plan, quietMs, quiet.calls, quiet.calls - quiet.nudgedAt)) return ran
236    await update($, quietAtom, q => ({ ...q, nudgedAt: q.calls }))
237
238    const steps = plan.phases.flatMap((p, pi) => p.steps.map((s, si) => ({ s, pi, si })))
239    const cur = steps.find(x => x.s.status === 'active') ?? steps.find(x => x.s.status === 'pending')!
240    const phase = plan.phases[cur.pi]!
241    const nudge =
242      `plan-progress: the user's progress tree has not moved for ${duration(quietMs)} (${quiet.calls} tool calls). ` +
243      `It shows ${cur.pi + 1}.${cur.si + 1} "${cur.s.title}" as current, in phase ${cur.pi + 1} "${phase.title}":\n` +
244      outline({ ...plan, phases: [phase] }).replace(/^(\s*)1\./gm, `$1${cur.pi + 1}.`) +
245      `\nIf you have moved past it, call ${MARK} now: mark the step you are on active with through: true, and every earlier open step is marked done. ` +
246      `If you are still on it, carry on.`
247    return { ...ran, context: [...(ran.context ?? []), nudge] }
248  }).catch(($, e, next) => next(e))
249
250  // Tasks and todos named like a step move that step.
251  on('tool.call', { tool: 'TodoWrite' }, async ($, e, next) => {
252    const ran = await next(e)
253    if (ran.deny !== undefined || ran.isError || !(await read($, planAtom))) return ran
254    const todos = (e as unknown as { todos?: { content: string; status: string }[] }).todos ?? []
255    await change($, (plan, now) =>
256      todos.reduce((p, todo) => {
257        const at = findStep(p, todo.content)
258        const status = TASK_STATUS[todo.status]
259        const current = at && p.phases[at.phase]!.steps[at.step]!.status
260        return at && status && current !== status && current !== 'done' ? mark(p, at.phase, at.step, status, now) : p
261      }, plan),
262    )
263    return ran
264  })
265
266  on('tool.call', { tool: 'TaskCreate' }, async ($, e, next) => {
267    const ran = await next(e)
268    const id = (ran.result as { task?: { id?: string } } | undefined)?.task?.id
269    const subject = (e as unknown as { subject?: string }).subject
270    if (id && subject) await update($, tasksAtom, t => ({ ...t, [id]: subject }))
271    return ran
272  })
273
274  on('tool.call', { tool: 'TaskUpdate' }, async ($, e, next) => {
275    const ran = await next(e)
276    const input = e as unknown as { taskId: string; subject?: string; status?: string }
277    if (ran.deny !== undefined || ran.isError) return ran
278    const tasks = await read($, tasksAtom)
279    const subject = input.subject ?? tasks[input.taskId]
280    if (input.subject) await update($, tasksAtom, t => ({ ...t, [input.taskId]: input.subject! }))
281    const status = input.status ? TASK_STATUS[input.status] : undefined
282    if (!subject || !status || !(await read($, planAtom))) return ran
283    await change($, (plan, now) => {
284      const at = findStep(plan, subject)
285      return at && plan.phases[at.phase]!.steps[at.step]!.status !== 'done' ? mark(plan, at.phase, at.step, status, now) : plan
286    })
287    return ran
288  })
289
290  on('command.run', { command: 'plan-progress' }, async ($, e) => {
291    if (e.args.trim() === 'clear') {
292      await setPlan($, null)
293      await $.ui.close({ id: PANE }).catch(() => {})
294      return { text: 'Stopped tracking the plan.' }
295    }
296    const plan = await read($, planAtom)
297    await openPane($, true)
298    if (!plan) return { text: 'No plan yet: approve a plan in plan mode, or ask Claude to lay the task out in phases.' }
299    return { text: `${plan.title}: ${progressText(plan, await $.clock.now())}` }
300  })
301
302  on('session.end', async ($, e, next) => {
303    if (e.reason === 'clear') await setPlan($, null)
304    return next(e)
305  })
306
307  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
308    const plan = await read($, planAtom)
309    await read($, nowAtom)
310    const now = await $.clock.now()
311
312    // Where the surface draws images, the pane is a stack of cards.
313    if (e.surface !== 'terminal') {
314      const { Box, Svg } = $.ui.resolve(e)
315      const width = e.props.bodyColumns * CELL_PX
316      if (!plan) {
317        const empty = emptySvg(width)
318        return <Svg source={empty.source} alt="No plan yet" width={Math.max(300, width)} height={empty.height} />
319      }
320      const drawn = planSvg(plan, now, width)
321      return (
322        <Box flexDirection="column" key="plan-progress">
323          <Svg source={drawn.source} alt={drawn.alt} width={Math.max(300, width)} height={drawn.height} />
324        </Box>
325      )
326    }
327
328    const { Box, Text } = $.ui.resolve(e)
329    if (!plan) {
330      return (
331        <Box flexDirection="column" borderStyle="round" borderColor={C.edge} paddingX={1}>
332          <Text bold color={C.text}>
333            No plan yet
334          </Text>
335          <Text color={C.muted} wrap="wrap">
336            Approve a plan in plan mode, or ask Claude to lay a long task out in phases.
337          </Text>
338        </Box>
339      )
340    }
341
342    const s = stats(plan, now)
343    const room = Math.max(4, e.props.scroll.bodyRows)
344    const current = s.currentPhase ?? -1
345    // The current phase opens in a frame (two rows more); the phases to come,
346    // then the finished ones, open while the tree still fits.
347    const isOpen = plan.phases.map((_, i) => i === current)
348    const rows = () => 3 + plan.phases.reduce((n, p, i) => n + 1 + (isOpen[i] ? p.steps.length + (i === current ? 2 : 0) : 0), 0)
349    for (const wantDone of [false, true]) {
350      plan.phases.forEach((p, i) => {
351        if (!isOpen[i] && (phaseState(p) === 'done') === wantDone && rows() + p.steps.length <= room) isOpen[i] = true
352      })
353    }
354
355    const cells = Math.max(6, Math.min(24, e.props.bodyColumns - 36))
356    const { filled, track } = bar(s.percent, cells, '━', '━')
357    const glyph: Record<string, [string, Color]> = {
358      done: ['✓', C.done],
359      active: ['●', C.accent],
360      pending: ['○', C.dim],
361      skipped: ['–', C.dim],
362    }
363    const phaseNo = Math.min(plan.phases.length, current + 1 || plan.phases.length)
364
365    const stepRow = (pi: number, si: number, inFrame: boolean) => {
366      const p = plan.phases[pi]!
367      const step = p.steps[si]!
368      const [sg, sc] = glyph[step.status]!
369      const took = step.startedAt != null ? (step.endedAt ?? now) - step.startedAt : null
370      const branch = inFrame ? '' : si === p.steps.length - 1 ? '  └ ' : '  ├ '
371      return (
372        <Box flexDirection="row" justifyContent="space-between" key={`step-${pi}-${si}`}>
373          <Box flexDirection="row" flexShrink={1}>
374            <Text color={C.dim}>{branch}</Text>
375            <Text color={sc}>{`${sg} `}</Text>
376            <Text
377              color={step.status === 'active' ? C.text : step.status === 'done' ? C.soft : C.muted}
378              bold={step.status === 'active'}
379              strikethrough={step.status === 'skipped'}
380              wrap="truncate"
381            >
382              {step.title}
383            </Text>
384          </Box>
385          <Text color={step.status === 'active' ? C.accent : C.muted}>{took != null && step.status !== 'skipped' ? ` ${duration(took)}` : ''}</Text>
386        </Box>
387      )
388    }
389
390    return (
391      <Box flexDirection="column" key="plan-progress">
392        <Box flexDirection="row" justifyContent="space-between">
393          <Text bold color={C.text} wrap="truncate">
394            {plan.title}
395          </Text>
396          <Box flexDirection="row">
397            <Text color={C.muted}>{` ${duration(s.elapsedMs)} ${s.isFinished ? 'total' : 'in'}`}</Text>
398            {!s.isFinished && s.remainingMs != null && <Text color={C.soft}>{` · ~${duration(s.remainingMs)} left`}</Text>}
399          </Box>
400        </Box>
401        <Box flexDirection="row">
402          <Text color={C.done}>{filled}</Text>
403          <Text color={C.edge}>{track}</Text>
404          <Text bold color={C.text}>
405            {` ${s.percent}%`}
406          </Text>
407          <Text color={C.muted}>{`  ${s.closed}/${s.total} steps · phase ${phaseNo}/${plan.phases.length}`}</Text>
408        </Box>
409        <Text> </Text>
410        {plan.phases.flatMap((p, pi) => {
411          const state = phaseState(p)
412          const [g, color] = glyph[state]!
413          const took = phaseDuration(plan, pi, now)
414          const closed = p.steps.filter(x => x.status === 'done' || x.status === 'skipped').length
415          const right = [isOpen[pi] ? '' : `${closed}/${p.steps.length}`, took != null ? duration(took) : ''].filter(Boolean).join(' · ')
416          const head = (
417            <Box flexDirection="row" justifyContent="space-between" key={`phase-${pi}`}>
418              <Box flexDirection="row" flexShrink={1}>
419                <Text color={color}>{`${g} `}</Text>
420                <Text color={pi === current ? C.accent : C.muted}>{`${pi + 1} `}</Text>
421                <Text bold={pi === current} color={state === 'pending' && pi !== current ? C.soft : C.text} wrap="truncate">
422                  {p.title}
423                </Text>
424              </Box>
425              <Text color={C.muted}>{right ? ` ${right}` : ''}</Text>
426            </Box>
427          )
428          if (!isOpen[pi]) return [head]
429          if (pi === current) {
430            return [
431              <Box flexDirection="column" borderStyle="round" borderColor={C.accent} paddingX={1} key={`now-${pi}`}>
432                {head}
433                {p.steps.map((_, si) => stepRow(pi, si, true))}
434              </Box>,
435            ]
436          }
437          return [head, ...p.steps.map((_, si) => stepRow(pi, si, false))]
438        })}
439      </Box>
440    )
441  })
442}
443
hooks/look.ts 213 lines
1import type { Plan, Step } from '../types'
2import { duration, phaseDuration, phaseState, stats } from './plan'
3
4// Dark only: square slate panels on a navy ground, hairline rules, light wide
5// numerals. Periwinkle for what is done, one amber for the step under way. An
6// SVG is drawn as an image, so it takes real colours, not theme keys; the
7// terminal uses the same.
8export const C = {
9  ground: '#1f2433',
10  card: '#282e40',
11  raised: '#2f3549',
12  stroke: '#353c50',
13  edge: '#4a5168',
14  text: '#e8eaf0',
15  soft: '#c4c8d4',
16  muted: '#9aa1b5',
17  dim: '#6b7287',
18  accent: '#f5a524',
19  ember: '#3d3220',
20  done: '#8b90d6',
21  good: '#3fc9b4',
22  hot: '#f0605d',
23} as const
24
25const SANS = `font-family="Barlow, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif"`
26
27export const esc = (t: string) => t.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
28
29// Text in an image cannot wrap or truncate itself: cut it to an estimated width.
30const fit = (t: string, px: number, size: number, spacing = 0, upper = false) => {
31  const max = Math.max(3, Math.floor(px / (size * (upper ? 0.68 : 0.55) + spacing)))
32  return t.length > max ? `${t.slice(0, max - 1)}…` : t
33}
34/** Estimated width of a small uppercase label. */
35const labelWidth = (t: string) => t.length * (10 * 0.68 + 1.2)
36
37const text = (x: number, y: number, size: number, fill: string, body: string, extra = '') =>
38  `<text x="${x}" y="${y}" font-size="${size}" fill="${fill}" ${extra}>${body}</text>`
39const label = (x: number, y: number, fill: string, body: string, px: number, extra = '') =>
40  text(x, y, 10, fill, esc(fit(body.toUpperCase(), px, 10, 1.2, true)), `letter-spacing="1.2" ${extra}`)
41/** A big light numeral, shrunk to fit its room. */
42const big = (x: number, y: number, size: number, fill: string, body: string, px: number, extra = '') => {
43  const s = Math.max(14, Math.min(size, px / Math.max(1, body.length * 0.56)))
44  return text(x, y, Math.round(s), fill, esc(body), `font-weight="300" letter-spacing="1" ${extra}`)
45}
46
47const svg = (W: number, H: number, body: string) =>
48  `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" ${SANS}>${body}</svg>`
49const card = (y: number, W: number, H: number, stroke: string = C.stroke) =>
50  `<rect x="0.5" y="${y + 0.5}" width="${W - 1}" height="${H - 1}" fill="${C.card}" stroke="${stroke}"/>`
51const hollow = (y: number, W: number, H: number) =>
52  `<rect x="0.5" y="${y + 0.5}" width="${W - 1}" height="${H - 1}" fill="none" stroke="${C.edge}" stroke-dasharray="3 5"/>`
53/** The title marker: a short bar in the text colour left of a card's title. */
54const marker = (x: number, y: number) => `<rect x="${x}" y="${y}" width="2" height="14" fill="${C.text}"/>`
55
56/** An open arc gauge: a track over 80% of the circle, the value along it, the number inside. */
57function gauge(cx: number, cy: number, r: number, percent: number, color: string, under: string): string {
58  const circ = 2 * Math.PI * r
59  const arc = 0.8 * circ
60  const value = (arc * Math.max(0, Math.min(100, percent))) / 100
61  const at = `cx="${cx}" cy="${cy}" r="${r}" fill="none" stroke-width="3" transform="rotate(126 ${cx} ${cy})"`
62  return (
63    `<circle ${at} stroke="${C.edge}" stroke-dasharray="${arc.toFixed(1)} ${circ.toFixed(1)}"/>` +
64    (value > 0 ? `<circle ${at} stroke="${color}" stroke-dasharray="${value.toFixed(1)} ${circ.toFixed(1)}"/>` : '') +
65    text(cx, cy + 8, 26, C.text, `${Math.round(percent)}`, 'font-weight="300" letter-spacing="1" text-anchor="middle"') +
66    text(cx, cy + 24, 8, C.muted, under, 'letter-spacing="1.2" text-anchor="middle"')
67  )
68}
69
70/** A step's mark: done a periwinkle square, current amber, skipped a dim dash, to come a hollow square. */
71function mark(s: Step, x: number, cy: number): string {
72  if (s.status === 'done') return `<rect x="${x}" y="${cy - 3}" width="6" height="6" fill="${C.done}"/>`
73  if (s.status === 'active') return `<rect x="${x}" y="${cy - 3}" width="6" height="6" fill="${C.accent}"/>`
74  if (s.status === 'skipped') return `<rect x="${x}" y="${cy - 0.5}" width="6" height="1" fill="${C.dim}"/>`
75  return `<rect x="${x + 0.5}" y="${cy - 2.5}" width="5" height="5" fill="none" stroke="${C.muted}"/>`
76}
77
78const plural = (n: number) => `${n} step${n === 1 ? '' : 's'}`
79
80const HEAD_H = 172
81const CARD_H = 62
82const STEP_H = 24
83const GAP = 10
84
85/** The whole pane as one SVG: a summary card, then a card per phase. */
86export function planSvg(plan: Plan, now: number, width: number): { source: string; height: number; alt: string } {
87  const W = Math.max(300, Math.round(width))
88  const s = stats(plan, now)
89  const parts: string[] = []
90  const steps = plan.phases.flatMap(p => p.steps)
91  const phaseNo = Math.min(plan.phases.length, (s.currentPhase ?? plan.phases.length - 1) + 1)
92
93  // ---- the summary card: its name and where the plan is, a gauge, the big numbers, a cell per step
94  parts.push(card(0, W, HEAD_H))
95  const where = s.isFinished ? 'finished' : `phase ${phaseNo} / ${plan.phases.length}`
96  parts.push(label(W - 16, 29, s.isFinished ? C.done : C.muted, where, 120, 'text-anchor="end"'))
97  parts.push(marker(16, 17))
98  parts.push(text(26, 29, 15, C.text, esc(fit(plan.title, W - 26 - 16 - labelWidth(where) - 16, 15)), 'font-weight="500"'))
99
100  parts.push(gauge(60, 92, 34, s.percent, s.isFinished ? C.done : C.accent, 'DONE %'))
101
102  // Elapsed, what is left (amber: it is the estimate to watch) and the steps closed.
103  const cols: { head: string; value: string; color: string }[] = [
104    { head: s.isFinished ? 'total' : 'elapsed', value: duration(s.elapsedMs), color: C.text },
105    ...(s.isFinished ? [] : [{ head: 'left ~', value: s.remainingMs != null ? `~${duration(s.remainingMs)}` : '--', color: s.remainingMs != null ? C.accent : C.muted }]),
106    { head: 'steps', value: `${s.closed}/${s.total}`, color: C.text },
107  ]
108  const colX = 122
109  const colW = (W - colX - 16) / cols.length
110  cols.forEach((c, i) => {
111    const x = Math.round(colX + i * colW)
112    parts.push(label(x, 76, C.muted, c.head, colW - 8))
113    parts.push(big(x, 110, 30, c.color, c.value, colW - 10))
114  })
115  if (!s.isFinished && s.remainingMs == null) parts.push(label(colX, 132, C.muted, 'pace after the first step', W - colX - 16))
116
117  const avail = W - 32
118  const n = Math.max(1, steps.length)
119  const cell = Math.max(2, Math.min(56, (avail - (n - 1) * 4) / n))
120  const gap = n > 1 ? Math.max(0, Math.min(4, (avail - cell * n) / (n - 1))) : 0
121  steps.forEach((st, i) => {
122    const x = (16 + i * (cell + gap)).toFixed(1)
123    const fill = st.status === 'done' ? C.done : st.status === 'active' ? C.accent : st.status === 'skipped' ? C.stroke : C.edge
124    parts.push(`<rect x="${x}" y="148" width="${cell.toFixed(1)}" height="6" fill="${fill}"/>`)
125  })
126
127  // ---- the phase cards; long plans fold the old and the far
128  let y = HEAD_H + GAP
129  const current = s.currentPhase ?? -1
130  const shown = plan.phases.map((_, i) => current < 0 || (i >= current - 2 && i <= current + 3))
131  const before = shown.indexOf(true)
132  const after = plan.phases.length - 1 - shown.lastIndexOf(true)
133  const fold = (what: string) => {
134    parts.push(hollow(y, W, 34))
135    parts.push(text(W / 2, y + 21, 12, C.muted, esc(fit(what, W - 32, 12)), 'text-anchor="middle"'))
136    y += 34 + GAP
137  }
138  if (before > 0) fold(`${before} earlier phase${before > 1 ? 's' : ''} done`)
139
140  plan.phases.forEach((p, pi) => {
141    if (!shown[pi]) return
142    const state = phaseState(p)
143    const isNow = state === 'active' || (state === 'pending' && pi === current)
144    const h = isNow ? 74 + p.steps.length * STEP_H : CARD_H
145    const closed = p.steps.filter(x => x.status === 'done' || x.status === 'skipped').length
146    const took = phaseDuration(plan, pi, now)
147
148    parts.push(card(y, W, h, isNow ? C.accent : C.stroke))
149
150    // Top right: a periwinkle square when done, ACTIVE under way, a dash per step to come.
151    let rightW = 0
152    if (state === 'done') {
153      parts.push(`<rect x="${W - 24}" y="${y + 21}" width="8" height="8" fill="${C.done}"/>`)
154      rightW = 16
155    } else if (isNow) {
156      parts.push(label(W - 16, y + 29, C.accent, 'active', 80, 'text-anchor="end"'))
157      rightW = labelWidth('active')
158    } else {
159      const k = Math.min(8, p.steps.length)
160      for (let i = 0; i < k; i++) parts.push(`<rect x="${W - 16 - (k - i) * 26 + 4}" y="${y + 23}" width="22" height="4" fill="${C.edge}"/>`)
161      rightW = k * 26
162    }
163
164    // "01 Setup": the number in the phase's colour, then its name.
165    const numColor = state === 'done' ? C.done : isNow ? C.accent : C.muted
166    parts.push(text(16, y + 29, 15, numColor, String(pi + 1).padStart(2, '0'), 'font-weight="500"'))
167    parts.push(text(42, y + 29, 15, C.text, esc(fit(p.title, W - 42 - 16 - rightW - 12, 15)), 'font-weight="500"'))
168
169    const sub = state === 'done' ? `${plural(p.steps.length)} done` : state === 'pending' && !isNow ? `${plural(p.steps.length)} to go` : `${closed} of ${plural(p.steps.length)}`
170    const tookText = took != null ? duration(took) : ''
171    parts.push(text(16, y + 48, 12, C.muted, esc(fit(sub, W - 32 - tookText.length * 7 - 12, 12))))
172    if (tookText) parts.push(text(W - 16, y + 48, 12, C.muted, tookText, 'text-anchor="end"'))
173
174    // The phase under way lists its steps under a rule, each with its mark.
175    if (isNow) {
176      parts.push(`<line x1="16" y1="${y + 62.5}" x2="${W - 16}" y2="${y + 62.5}" stroke="${C.stroke}"/>`)
177      p.steps.forEach((st, si) => {
178        const cy = y + 82 + si * STEP_H
179        parts.push(mark(st, 16, cy))
180        const color = st.status === 'active' ? C.text : st.status === 'skipped' ? C.dim : C.muted
181        const deco = st.status === 'skipped' ? ' text-decoration="line-through"' : ''
182        const weight = st.status === 'active' ? ' font-weight="500"' : ''
183        parts.push(text(34, cy + 4.5, 13, color, esc(fit(st.title, W - 34 - 72, 13)), `${weight}${deco}`.trim()))
184        if (st.startedAt != null && st.status !== 'skipped') {
185          parts.push(text(W - 16, cy + 4.5, 12, st.status === 'active' ? C.accent : C.muted, duration((st.endedAt ?? now) - st.startedAt), 'text-anchor="end"'))
186        }
187      })
188    }
189    y += h + GAP
190  })
191  if (after > 0) fold(`${after} more phase${after > 1 ? 's' : ''} after this`)
192
193  const height = Math.round(y - GAP)
194  const active = steps.find(x => x.status === 'active')
195  const alt =
196    `${plan.title}: ${s.percent}% done, ${s.closed} of ${s.total} steps, ` +
197    (s.isFinished
198      ? `finished in ${duration(s.elapsedMs)}`
199      : `phase ${phaseNo} of ${plan.phases.length}, ${duration(s.elapsedMs)} in${s.remainingMs != null ? `, about ${duration(s.remainingMs)} left` : ''}${active ? `. Current step: ${active.title}` : ''}`)
200  return { source: svg(W, height, parts.join('')), height, alt }
201}
202
203export function emptySvg(width: number): { source: string; height: number } {
204  const W = Math.max(300, Math.round(width))
205  const H = 100
206  const body =
207    hollow(0, W, H) +
208    big(16, 44, 26, C.muted, 'No plan', W - 32) +
209    text(16, 66, 12, C.muted, esc(fit('Approve a plan in plan mode,', W - 32, 12))) +
210    text(16, 83, 12, C.muted, esc(fit('or ask Claude to lay it out in phases', W - 32, 12)))
211  return { source: svg(W, H, body), height: H }
212}
213
hooks/plan.ts 321 lines
1import type { Phase, Plan, Step, StepStatus } from '../types'
2
3const MAX_PHASES = 20
4const MAX_STEPS = 30
5const MAX_TITLE = 90
6
7// Headings that read as a phase of work: "Phase 2: ...", "Step 3 - ...", "2. ...".
8const PHASE_HEADING = /^(phase|stage|step|part|milestone|sprint|iteration|wave)\b|^\d+[.):]?\s/i
9// Sections a plan carries that are not work to do.
10const NOT_WORK =
11  /^(context|background|overview|summary|tl;?dr|goals?|non-goals?|motivation|problem|why|risks?|notes?|open questions|questions|assumptions|references|(critical |key |relevant )?files|out of scope|alternatives( considered)?|decisions|trade-?offs|approach|recommendation)\b/i
12
13type Item = { indent: number; text: string }
14type Section = { level: number; title: string; items: Item[] }
15
16export function clean(text: string): string {
17  const out = text
18    .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
19    .replace(/[*_`~]/g, '')
20    .replace(/\s+/g, ' ')
21    .replace(/[:\s]+$/, '')
22    .trim()
23  return out.length > MAX_TITLE ? `${out.slice(0, MAX_TITLE - 1)}…` : out
24}
25
26// "Phase 2: Build the API" -> "Build the API"; "3. Tests" -> "Tests".
27export function stripNumbering(title: string): string {
28  const stripped = title
29    .replace(/^(phase|stage|step|part|milestone|sprint|iteration|wave)\s*[\w.]*\s*[:.)\-–—]\s*/i, '')
30    .replace(/^\d+[.):]\s*/, '')
31    .trim()
32  return stripped || title
33}
34
35function sections(markdown: string): Section[] {
36  const out: Section[] = [{ level: 0, title: '', items: [] }]
37  let fenced = false
38  for (const raw of markdown.split(/\r?\n/)) {
39    if (/^\s*(```|~~~)/.test(raw)) {
40      fenced = !fenced
41      continue
42    }
43    if (fenced) continue
44
45    const heading = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(raw)
46    if (heading) {
47      out.push({ level: heading[1]!.length, title: clean(heading[2]!), items: [] })
48      continue
49    }
50    // A line that is only bold text works as a heading in many plans: "**Phase 1: Setup**".
51    const bold = /^\s*\*\*([^*]+)\*\*:?\s*$/.exec(raw)
52    if (bold) {
53      out.push({ level: 7, title: clean(bold[1]!), items: [] })
54      continue
55    }
56    const item = /^(\s*)(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?(.+)$/.exec(raw)
57    if (item) {
58      const text = clean(item[2]!)
59      if (text) out[out.length - 1]!.items.push({ indent: item[1]!.replace(/\t/g, '    ').length, text })
60    }
61  }
62  return out
63}
64
65const topLevel = (items: Item[]): string[] => {
66  const min = Math.min(...items.map(i => i.indent))
67  return items.filter(i => i.indent === min).map(i => i.text)
68}
69
70const toPhase = (title: string, steps: string[]): Phase => {
71  const name = stripNumbering(title)
72  const list = steps.length > 0 ? steps : [name]
73  return { title: name, steps: list.slice(0, MAX_STEPS).map(t => ({ title: t, status: 'pending' as const })) }
74}
75
76/**
77 * Reads a markdown plan into phases of steps. Phase headings win; failing
78 * those, every heading that holds a list and is not context; failing that,
79 * one list whose nested items are the steps, or one flat list as one phase.
80 */
81export function parsePlan(markdown: string): { title: string; phases: Phase[] } {
82  const all = sections(markdown)
83  const h1 = all.find(s => s.level === 1)
84  let title = h1 ? stripNumbering(h1.title.replace(/^plan\s*[:\-–—]\s*/i, '')) : ''
85  if (!title || /^plan$/i.test(title)) title = 'Plan'
86
87  const body = all.filter(s => s !== h1)
88  const named = body.filter(s => s.level > 0 && PHASE_HEADING.test(s.title) && !NOT_WORK.test(stripNumbering(s.title)))
89
90  let phases: Phase[] = []
91  if (named.length > 0) {
92    // A phase takes the items of the sections nested under it, up to the next phase.
93    for (let i = 0; i < body.length; i++) {
94      const s = body[i]!
95      if (!named.includes(s)) continue
96      const items = [...s.items]
97      for (let j = i + 1; j < body.length; j++) {
98        const sub = body[j]!
99        if (named.includes(sub) || sub.level <= s.level) break
100        if (sub.items.length === 0) items.push({ indent: 0, text: sub.title })
101        else items.push(...sub.items)
102      }
103      phases.push(toPhase(s.title, items.length ? topLevel(items) : []))
104    }
105  } else {
106    const work = body.filter(s => s.level > 0 && s.items.length > 0 && !NOT_WORK.test(s.title))
107    if (work.length >= 2) {
108      phases = work.map(s => toPhase(s.title, topLevel(s.items)))
109    } else {
110      const items = work[0]?.items ?? body.flatMap(s => s.items)
111      if (items.length > 0) {
112        const min = Math.min(...items.map(i => i.indent))
113        const hasNesting = items.some(i => i.indent > min)
114        if (hasNesting) {
115          // Each top item is a phase, the items under it its steps.
116          let current: { title: string; steps: Item[] } | null = null
117          const groups: { title: string; steps: Item[] }[] = []
118          for (const it of items) {
119            if (it.indent === min) groups.push((current = { title: it.text, steps: [] }))
120            else current?.steps.push(it)
121          }
122          phases = groups.map(g => toPhase(g.title, g.steps.length ? topLevel(g.steps) : []))
123        } else {
124          phases = [toPhase(work[0]?.title || title, items.map(i => i.text))]
125        }
126      }
127    }
128  }
129
130  return { title, phases: phases.slice(0, MAX_PHASES) }
131}
132
133export function newPlan(title: string, phases: { title: string; steps: string[] }[], source: Plan['source'], now: number): Plan {
134  return {
135    title: clean(title) || 'Plan',
136    source,
137    createdAt: now,
138    phases: phases.slice(0, MAX_PHASES).map(p => toPhase(clean(p.title), p.steps.map(clean).filter(Boolean))),
139  }
140}
141
142// ---------------------------------------------------------------- progress
143
144const isClosed = (s: Step) => s.status === 'done' || s.status === 'skipped'
145
146export type PhaseState = 'done' | 'active' | 'pending'
147
148export function phaseState(p: Phase): PhaseState {
149  if (p.steps.every(isClosed)) return 'done'
150  if (p.steps.some(s => s.status === 'active' || isClosed(s))) return 'active'
151  return 'pending'
152}
153
154const lastEnd = (plan: Plan): number =>
155  Math.max(plan.createdAt, ...plan.phases.flatMap(p => p.steps.map(s => s.endedAt ?? 0)))
156
157/** Sets one step, or every open step of a phase, to `status`, stamping times. */
158export function mark(plan: Plan, phase: number, step: number | undefined, status: StepStatus, now: number): Plan {
159  const since = lastEnd(plan)
160  const set = (s: Step): Step => {
161    if (status === 'pending') return { title: s.title, status }
162    if (status === 'active') return { ...s, status, startedAt: s.startedAt ?? now, endedAt: undefined }
163    return { ...s, status, startedAt: s.startedAt ?? since, endedAt: s.endedAt ?? now }
164  }
165  return {
166    ...plan,
167    phases: plan.phases.map((p, pi) =>
168      pi !== phase
169        ? p
170        : { ...p, steps: p.steps.map((s, si) => (step === undefined ? (isClosed(s) && status !== 'pending' ? s : set(s)) : si === step ? set(s) : s)) },
171    ),
172  }
173}
174
175/**
176 * Catches up: closes every open step before the given one as done, sharing
177 * the time since the first of them began evenly between them, then sets the
178 * step itself (a step marked done takes its share too).
179 */
180export function markThrough(plan: Plan, phase: number, step: number, status: StepStatus, now: number): Plan {
181  const flat = plan.phases.flatMap((p, pi) => p.steps.map((s, si) => ({ s, pi, si })))
182  const at = flat.findIndex(x => x.pi === phase && x.si === step)
183  const closing = flat.slice(0, at).filter(x => !isClosed(x.s))
184  if (status === 'done' && !isClosed(flat[at]!.s)) closing.push(flat[at]!)
185  if (closing.length === 0) return mark(plan, phase, step, status, now)
186
187  const start = Math.min(now, closing[0]!.s.startedAt ?? lastEnd(plan))
188  const share = (now - start) / closing.length
189  const times = new Map(closing.map((x, i) => [`${x.pi}.${x.si}`, [start + i * share, start + (i + 1) * share]]))
190  const caught: Plan = {
191    ...plan,
192    phases: plan.phases.map((p, pi) => ({
193      ...p,
194      steps: p.steps.map((s, si) => {
195        const t = times.get(`${pi}.${si}`)
196        return t ? { ...s, status: 'done' as const, startedAt: Math.round(t[0]!), endedAt: Math.round(t[1]!) } : s
197      }),
198    })),
199  }
200  return status === 'done' ? caught : mark(caught, phase, step, status, now)
201}
202
203/** Whether a nudge is due: the tree has sat still for a while of steady work. */
204export function isStale(plan: Plan, quietMs: number, calls: number, callsSinceNudge: number): boolean {
205  const s = stats(plan, 0)
206  if (s.isFinished) return false
207  const done = plan.phases.flatMap(p => p.steps).filter(x => x.status === 'done').length
208  const pace = done > 0 ? (lastEnd(plan) - plan.createdAt) / done : 0
209  return calls >= NUDGE_CALLS && callsSinceNudge >= NUDGE_CALLS && quietMs >= Math.max(NUDGE_MS, 1.5 * pace)
210}
211
212export const NUDGE_CALLS = 6
213export const NUDGE_MS = 3 * 60_000
214
215export type Stats = {
216  total: number
217  closed: number
218  percent: number
219  elapsedMs: number
220  remainingMs: number | null
221  currentPhase: number | null
222  isFinished: boolean
223}
224
225export function stats(plan: Plan, now: number): Stats {
226  const steps = plan.phases.flatMap(p => p.steps)
227  const closed = steps.filter(isClosed).length
228  const isFinished = closed === steps.length
229  const end = isFinished ? lastEnd(plan) : now
230  const elapsedMs = Math.max(0, end - plan.createdAt)
231  // The pace so far: the time up to the last finished step over the steps finished.
232  const done = steps.filter(s => s.status === 'done').length
233  const paceMs = done > 0 ? (lastEnd(plan) - plan.createdAt) / done : null
234  const currentIdx = plan.phases.findIndex(p => phaseState(p) !== 'done')
235  return {
236    total: steps.length,
237    closed,
238    percent: steps.length ? Math.round((closed / steps.length) * 100) : 0,
239    elapsedMs,
240    remainingMs: isFinished ? 0 : paceMs == null ? null : Math.round(paceMs * (steps.length - closed)),
241    currentPhase: currentIdx === -1 ? null : currentIdx,
242    isFinished,
243  }
244}
245
246export function phaseDuration(plan: Plan, index: number, now: number): number | null {
247  const p = plan.phases[index]!
248  const starts = p.steps.map(s => s.startedAt).filter((t): t is number => t != null)
249  if (starts.length === 0) return null
250  const ends = p.steps.map(s => s.endedAt).filter((t): t is number => t != null)
251  const end = phaseState(p) === 'done' ? Math.max(...ends) : now
252  return Math.max(0, end - Math.min(...starts))
253}
254
255export function duration(ms: number): string {
256  const min = Math.round(ms / 60_000)
257  if (min < 1) return `${Math.max(0, Math.round(ms / 1000))}s`
258  if (min < 60) return `${min}m`
259  const h = Math.floor(min / 60)
260  return `${h}h${String(min % 60).padStart(2, '0')}m`
261}
262
263// The status line has no colours, so its cells differ in shape; the pane's bar
264// is one line, filled and track told apart by colour.
265export function bar(percent: number, cells: number, on = '▰', off = '▱'): { filled: string; track: string } {
266  const filled = Math.min(cells, Math.round((percent / 100) * cells))
267  return { filled: on.repeat(filled), track: off.repeat(cells - filled) }
268}
269
270/** One line for the status bar. */
271export function statusLine(plan: Plan, now: number): string {
272  const s = stats(plan, now)
273  const { filled, track } = bar(s.percent, 8)
274  if (s.isFinished) return `✓ ${plan.title} · ${s.total} steps in ${duration(s.elapsedMs)}`
275  const parts = [`${filled}${track} ${s.closed}/${s.total}`]
276  if (s.currentPhase != null) {
277    parts.push(`phase ${s.currentPhase + 1}/${plan.phases.length}: ${plan.phases[s.currentPhase]!.title}`)
278  }
279  parts.push(`${duration(s.elapsedMs)} in`)
280  if (s.remainingMs != null) parts.push(`~${duration(s.remainingMs)} left`)
281  return parts.join(' · ')
282}
283
284/** The tree as plain text, numbered as plan_mark takes it, for the model. */
285export function outline(plan: Plan): string {
286  return plan.phases
287    .map((p, pi) => {
288      const glyph = (st: StepStatus) => (st === 'done' ? '[x]' : st === 'active' ? '[>]' : st === 'skipped' ? '[-]' : '[ ]')
289      const steps = p.steps.map((s, si) => `  ${pi + 1}.${si + 1} ${glyph(s.status)} ${s.title}`)
290      return [`${pi + 1}. ${p.title}`, ...steps].join('\n')
291    })
292    .join('\n')
293}
294
295// ---------------------------------------------------------------- task sync
296
297const norm = (t: string) => t.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()
298
299/** The step a task or todo names: an exact match, or one containing the other. */
300export function findStep(plan: Plan, text: string): { phase: number; step: number } | null {
301  const want = norm(text)
302  if (!want) return null
303  let loose: { phase: number; step: number } | null = null
304  for (let pi = 0; pi < plan.phases.length; pi++) {
305    const steps = plan.phases[pi]!.steps
306    for (let si = 0; si < steps.length; si++) {
307      const have = norm(steps[si]!.title)
308      if (have === want) return { phase: pi, step: si }
309      const shorter = have.length < want.length ? have : want
310      if (!loose && shorter.length >= 12 && (have.includes(want) || want.includes(have))) loose = { phase: pi, step: si }
311    }
312  }
313  return loose
314}
315
316export const TASK_STATUS: Record<string, StepStatus | undefined> = {
317  pending: undefined,
318  in_progress: 'active',
319  completed: 'done',
320}
321
types/index.d.ts 29 lines
1export type StepStatus = 'pending' | 'active' | 'done' | 'skipped'
2
3export type Step = { title: string; status: StepStatus; startedAt?: number; endedAt?: number }
4
5export type Phase = { title: string; steps: Step[] }
6
7export type Plan = {
8  title: string
9  // Where the tree came from: an approved plan-mode plan, or the model's plan_set.
10  source: 'plan-mode' | 'model'
11  createdAt: number
12  phases: Phase[]
13}
14
15declare module 'claude-code' {
16  interface PluginState {
17    'plan-progress': {
18      plan: Plan | null
19      // Bumped by the ticker so elapsed times redraw while a plan runs.
20      now: number
21      // Task ids to subjects, so a TaskUpdate can be matched to a step.
22      tasks: Record<string, string>
23      // How long the tree has sat still: since when, the model's tool calls
24      // since then, and the call count at the last nudge to update it.
25      quiet: { since: number; calls: number; nudgedAt: number }
26    }
27  }
28}
29