SLOPSHOPPER

waiter

Tracks a plan being executed and shows a progress bar with the time left for each task

panebandguardcommandtoastprocess
v0.1.0MITupdated 2026-10-25yarivzip/waiter
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · waiter
│ ┃ waiter ✕ › fix the failing auth test and add an audit log call │ ┃ No plan tracked. /waiter path/to/plan.md, or │ ┃ start executing a plan. ⏺ Read(src/auth.ts) │ ┃ [ Minimize ] ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /waiter │ ⎿ waiter: no plan yet. Run /waiter <plan.md>, or read or execute a │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · waiter
No plan tracked. /waiter path/to/plan.md, or start executing a plan. [ Minimize ]
README

waiter: plan progress for Claude Code

waiter is a Claude Code mod. While Claude works through a plan, it shows a progress bar and the time left for each task.

  • It finds the plan by itself. When Claude opens or edits a plan file, waiter picks it up. It reads many plan layouts:
  • ### Task 1: / ## Phase 2 headings
  • numbered headings
  • checkbox lists
  • GSD <task> blocks

With no plan file, it shows the session's own task list.

  • It knows what is finished from:
  • the session's task list
  • git commits that name a task, like Task 3 or (4b Task 3)
  • ticked checkboxes
  • The time estimates come from how much text each task has in the plan. They improve as tasks finish, and what it learns carries over to later plans. Hands-on tasks (CONTROLLER, manual, acceptance) get a flat 20 minutes and are marked [you].
  • It shows which step the current task is on, like "step 3/5 ~8m". It finds the step from the files being changed right now (git status in every working folder of the repo, worktrees included), matched to the files or modules (ops.burn → ops.py) each step names. It reads only file names, never their contents.
  • It works across sessions. Plan work done in another Claude session of the same project shows up within 2 minutes, through that session's git commits.
  • Minimize turns it into one line above the prompt; Expand brings the full panel back.

Install

You need Claude Code (terminal or the desktop app's Code tab). The mod was built on version 2.1.288, and the plugin system it uses is still early access. You also need git, to get the mod and so waiter can see progress from commits.

The short way: hand it to Claude

Paste this into a Claude Code session. The same prompt installs waiter, updates it, and moves an old zip install to a git clone.

Install or update the waiter mod for Claude Code from https://github.com/yarivzip/waiter.

1. Find my copy: read "env" > "CLAUDE_CODE_PLUGIN_DIRS" in ~/.claude/settings.json and
   look for a folder in it whose .claude-plugin/plugin.json has "name": "waiter".
2. If that folder is a git clone of yarivzip/waiter, run `git pull --ff-only` in it and
   skip to step 5.
3. Otherwise, git clone https://github.com/yarivzip/waiter into ~/tools/waiter (on Windows
   %USERPROFILE%\tools\waiter) unless I name another folder. Keep it outside ~/.claude.
   If my old copy was not a git clone (a zip install), ask me before deleting it.
4. Point CLAUDE_CODE_PLUGIN_DIRS at the clone's full path. Change only that value: keep
   every other setting, and keep any other folders in it (separated by ; on Windows,
   : on macOS/Linux). Write valid JSON, with doubled backslashes on Windows.
5. Run `claude plugin validate <folder>` and show me the result and the new commits, if any.
6. Tell me to start a new Claude Code session and type /waiter to check it loaded.

By hand

  1. Clone the repo into any folder outside .claude:

Windows:

   git clone https://github.com/yarivzip/waiter D:\tools\waiter

macOS / Linux:

   git clone https://github.com/yarivzip/waiter ~/tools/waiter
  1. Tell Claude Code to load it. Open your personal settings file (C:\Users\<you>\.claude\settings.json, or ~/.claude/settings.json) and add the line under "env", pointing at the folder you cloned into.

Windows (note the doubled backslashes):

   {
     "env": {
       "CLAUDE_CODE_PLUGIN_DIRS": "D:\\tools\\waiter"
     }
   }

macOS / Linux (write the full path, not ~; on Linux it starts with /home/<you>):

   {
     "env": {
       "CLAUDE_CODE_PLUGIN_DIRS": "/Users/<you>/tools/waiter"
     }
   }
  • If the file already has an "env" block, add only the CLAUDE_CODE_PLUGIN_DIRS line inside it, with a comma after the line above it.
  • If you already load other plugin folders this way, list them all in one value, separated by ; on Windows or : on macOS / Linux.
  1. Start a new Claude Code session. Sessions that are already running don't pick it up.

To check it loaded, type /waiter. It answers even before there is a plan.

Update: paste the prompt above again, or run git pull in that folder yourself. Then start a new session.

Without git: you can unzip a copy instead. Put it in a folder outside .claude so that it directly contains .claude-plugin, hooks and types, then do steps 2 and 3. To update, replace the folder with a newer zip.

Use

Most of the time you do nothing: start executing a plan and the panel appears.

CommandWhat it does
/waiteropen the panel
/waiter path/to/plan.mdtrack that plan file
/waiter minminimize to one line above the prompt
/waiter refreshre-read the plan and the commits now
/waiter offstop tracking (it won't come back next session)

The panel has the buttons Minimize, Refresh and Stop tracking. The one-line bar has Expand and Hide. If you close the panel, it turns into the one-line bar.

Good to know

  • Each session shows one plan. It switches when the session opens a newer plan, starts writing one, or finishes the current one. An older plan opened only to look something up does not take over.
  • The commits pick the plan being executed. When the commits name the tasks of one plan (Task A12) and not of another, the one they name wins, even if it is older. This holds when a session starts again on the plan written last, and when Claude opens a plan.
  • Waiter only reads files that Claude already opened through its normal tools. Any guard hooks you have (for example, folders Claude must never open) still apply. /waiter <path> also goes through Claude's Read tool.
  • "saved, in review": the newest task with a commit stays in this state for 20 minutes, because review and fix commits often follow. It also ends as soon as the next task starts.
  • Remove it: delete the CLAUDE_CODE_PLUGIN_DIRS line and the folder.
  • Run its tests: claude plugin test <folder>.
  • License: MIT, see LICENSE.
Source 3 files
hooks/register.tsx 599 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { WaiterDone, WaiterMode, WaiterPlan, WaiterSessionTask } from '../types'
5import {
6  DEFAULT_RATE,
7  bar,
8  clock,
9  committedPlan,
10  duration,
11  estimate,
12  evidence,
13  isPlanPath,
14  matchCommits,
15  parseGitLog,
16  parsePlan,
17  parseStatus,
18  sessionPlan,
19  takesOver,
20} from './plan'
21import type { Commit, Evidence, Row, View } from './plan'
22
23const PANE = 'waiter'
24const TITLE = 'Waiter'
25
26const planA = atom({ plugin: 'waiter', key: 'plan' } as const, null)
27const doneA = atom({ plugin: 'waiter', key: 'done' } as const, {})
28const sessionA = atom({ plugin: 'waiter', key: 'session' } as const, [])
29const startedA = atom({ plugin: 'waiter', key: 'startedAt' } as const, 0)
30const rateA = atom({ plugin: 'waiter', key: 'rate' } as const, DEFAULT_RATE)
31const modeA = atom({ plugin: 'waiter', key: 'mode' } as const, 'pane')
32const noteA = atom({ plugin: 'waiter', key: 'note' } as const, '')
33const restoredA = atom({ plugin: 'waiter', key: 'isRestored' } as const, false)
34const changedA = atom({ plugin: 'waiter', key: 'changed' } as const, [])
35
36type $ = EngineInterface
37
38const norm = (p: string) => p.replace(/\\/g, '/')
39const dirOf = (p: string) => norm(p).replace(/\/[^/]*$/, '') || '/'
40const isAbsolute = (p: string) => /^[a-zA-Z]:\//.test(norm(p)) || norm(p).startsWith('/')
41const same = (a: string, b: string) => norm(a).toLowerCase() === norm(b).toLowerCase()
42
43async function absolute($: $, p: string): Promise<string> {
44  const path = norm(p.trim().replace(/^["']|["']$/g, ''))
45  return isAbsolute(path) ? path : `${norm(await $.session.cwd())}/${path.replace(/^\.\//, '')}`
46}
47
48async function git($: $, argv: string[], cwd: string): Promise<string | null> {
49  try {
50    const r = await $.process.run(['git', ...argv], { cwd, timeoutMs: 15_000 })
51    return r.exitCode === 0 ? r.stdout : null
52  } catch {
53    return null // no git, or no host processes on this surface
54  }
55}
56
57async function storeGet<T>($: $, key: string, fallback: T): Promise<T> {
58  try {
59    const v = await $.store.get(key)
60    return v === undefined || v === null ? fallback : (v as T)
61  } catch {
62    return fallback
63  }
64}
65
66async function storeSet($: $, key: string, value: unknown) {
67  try {
68    await $.store.set(key, value)
69  } catch {
70    // a store that refuses only costs the memory across sessions
71  }
72}
73
74// Waiter reads only files a tool call already opened: those calls pass the
75// session's PreToolUse guards (a project's off-limits folders), waiter's own
76// reads would not. A path enters this list once such a call succeeded.
77async function allow($: $, path: string) {
78  const opened = await storeGet<string[]>($, 'opened', [])
79  const key = norm(path).toLowerCase()
80  if (!opened.includes(key)) await storeSet($, 'opened', [...opened, key].slice(-200))
81}
82
83async function isAllowed($: $, path: string): Promise<boolean> {
84  return (await storeGet<string[]>($, 'opened', [])).includes(norm(path).toLowerCase())
85}
86
87// Opens `path` through the Read tool, so the session's guards decide.
88async function openGuarded($: $, path: string): Promise<boolean> {
89  try {
90    const r = await $.tool.call({ tool: 'Read', file_path: path, limit: 1 })
91    if (r.deny !== undefined || r.isError) return false
92    await allow($, path)
93    return true
94  } catch {
95    return false
96  }
97}
98
99// The learned rate: the mean of the last plans' measured rates.
100async function learnedRate($: $): Promise<number> {
101  const rates = await storeGet<Record<string, number>>($, 'rates', {})
102  const values = Object.values(rates).filter(v => v > 0)
103  return values.length > 0 ? values.reduce((a, b) => a + b, 0) / values.length : DEFAULT_RATE
104}
105
106async function current($: $): Promise<WaiterPlan | null> {
107  return (await read($, planA)) ?? sessionPlan(await read($, sessionA))
108}
109
110async function view($: $): Promise<View | null> {
111  const plan = await current($)
112  if (!plan) return null
113  return estimate(
114    plan,
115    await read($, doneA),
116    await read($, sessionA),
117    await read($, startedA),
118    await read($, rateA),
119    await $.clock.now(),
120    plan.kind === 'session' ? [] : await read($, changedA),
121  )
122}
123
124// Shows the plan the way the person last chose: the pane, or the one-line band.
125async function show($: $) {
126  if ((await read($, modeA)) !== 'pane') return
127  const opened = await $.ui.open({ id: PANE, title: TITLE })
128  if (!opened.isPlaced) await update($, modeA, () => 'band' as WaiterMode)
129}
130
131// Stops tracking, and forgets the plan so the next session does not bring it back.
132async function stop($: $) {
133  await update($, planA, () => null)
134  await storeSet($, `last:${norm(await $.session.root())}`, '')
135  await setMode($, 'hidden')
136}
137
138async function setMode($: $, mode: WaiterMode) {
139  await update($, modeA, () => mode)
140  if (mode !== 'hidden') await storeSet($, 'mode', mode)
141  if (mode === 'pane') await $.ui.open({ id: PANE, title: TITLE })
142  else await $.ui.close({ id: PANE })
143}
144
145// The repo's commits since `since`, subjects and times only; null without git.
146async function commitsSince($: $, dir: string, since: number): Promise<Commit[] | null> {
147  const out = await git($, ['log', '--all', `--since=${Math.floor(since / 1000) - 60}`, '--format=%ct%x09%s'], dir)
148  return out === null ? null : parseGitLog(out)
149}
150
151// Reads the plan's commits and records which tasks they finish.
152async function refreshGit($: $) {
153  const plan = await read($, planA)
154  if (!plan) return
155  const since = await read($, startedA)
156  const commits = await commitsSince($, dirOf(plan.path), since)
157  if (commits === null) return
158  const found = matchCommits(plan, commits, since)
159  await update($, doneA, done => {
160    // Git-found entries are re-derived each time, so a commit that no longer
161    // counts (the matching rules changed) stops marking its task done.
162    const next: WaiterDone = Object.fromEntries(Object.entries(done).filter(([, v]) => v.by !== 'git'))
163    for (const [k, v] of Object.entries(found)) {
164      if (!next[k] || v.at < next[k].at) next[k] = v
165    }
166    return next
167  })
168  await learn($)
169  await refreshChanged($)
170}
171
172// The files changed and not yet committed, in every working folder of the repo
173// (a plan is often executed in a worktree). Names only: no file is opened.
174async function refreshChanged($: $) {
175  const plan = await read($, planA)
176  if (!plan) return
177  const list = await git($, ['worktree', 'list', '--porcelain'], dirOf(plan.path))
178  const folders = (list ?? '')
179    .split(/\r?\n/)
180    .filter(l => l.startsWith('worktree '))
181    .map(l => l.slice('worktree '.length))
182  const changed: string[] = []
183  for (const folder of folders.length > 0 ? folders : [dirOf(plan.path)]) {
184    const out = await git($, ['status', '--porcelain', '--untracked-files=all'], folder)
185    if (out !== null) changed.push(...parseStatus(out))
186  }
187  await update($, changedA, () => [...new Set(changed)].slice(0, 500))
188}
189
190// Keeps this plan's measured rate, so later plans start from it.
191async function learn($: $) {
192  const plan = await read($, planA)
193  const v = await view($)
194  if (!plan || !v || v.kind === 'session' || v.measured === 0) return
195  const rates = await storeGet<Record<string, number>>($, 'rates', {})
196  rates[plan.path] = v.rate
197  await storeSet($, 'rates', Object.fromEntries(Object.entries(rates).slice(-10)))
198}
199
200async function created($: $, path: string): Promise<number | null> {
201  const out = await git($, ['log', '--follow', '--diff-filter=A', '--format=%ct', '--', path], dirOf(path))
202  const last = out?.trim().split(/\r?\n/).filter(Boolean).pop()
203  return last ? Number(last) * 1000 : null
204}
205
206// When a plan came to be: its file's first commit, else when waiter first saw it.
207async function startOf($: $, path: string, now: number): Promise<number> {
208  return (await created($, path)) ?? (await storeGet<number>($, `start:${path}`, now))
209}
210
211// The plan files this project opened, as their paths are spelled, newest last.
212async function remember($: $, path: string) {
213  const key = `plans:${norm(await $.session.root())}`
214  const known = await storeGet<string[]>($, key, [])
215  await storeSet($, key, [...known.filter(p => !same(p, path)), path].slice(-20))
216}
217
218// Switches to the sibling plan the commits say is being executed, if they name
219// one: a session that comes back on the plan written last must not show its
220// first task running while every commit names a task of another plan.
221async function followCommits($: $) {
222  const tracked = await read($, planA)
223  if (!tracked || !isPlanPath(tracked.path)) return
224  const now = await $.clock.now()
225  const paths = [
226    ...(await storeGet<string[]>($, `plans:${norm(await $.session.root())}`, [])),
227    ...(await storeGet<string[]>($, 'opened', [])), // lower case; holds plans opened before the list above
228  ]
229  const others: { path: string; plan: WaiterPlan; since: number }[] = []
230  for (const p of paths) {
231    if (!/\.(md|markdown)$/i.test(p) || !isPlanPath(p) || !same(dirOf(p), dirOf(tracked.path))) continue
232    if (same(p, tracked.path) || others.some(o => same(o.path, p))) continue
233    const plan = await load($, p)
234    if (plan) others.push({ path: p, plan, since: await startOf($, p, now) })
235  }
236  if (others.length === 0) return
237  const since = await read($, startedA)
238  const commits = await commitsSince($, dirOf(tracked.path), Math.min(since, ...others.map(o => o.since)))
239  if (commits === null) return
240  const picked = committedPlan(
241    evidence(tracked, commits, since, now),
242    others.map(o => ({ path: o.path, git: evidence(o.plan, commits, o.since, now) })),
243  )
244  if (!picked) return
245  const isRestored = await read($, restoredA)
246  await track($, picked.path)
247  await update($, restoredA, () => isRestored)
248  await update($, noteA, () => 'picked by its commits')
249}
250
251async function load($: $, path: string): Promise<WaiterPlan | null> {
252  if (!(await isAllowed($, path))) return null
253  try {
254    return parsePlan(await $.fs.read(path), path)
255  } catch {
256    return null
257  }
258}
259
260// Starts tracking the plan file at `path`. Says what happened, for the command.
261async function track($: $, path: string): Promise<string> {
262  const plan = await load($, path)
263  if (!plan) return `no tasks found in ${path}.`
264  const now = await $.clock.now()
265  const seen = await storeGet<WaiterDone>($, `seen:${plan.path}`, {})
266  const start = await startOf($, plan.path, now)
267  await storeSet($, `start:${plan.path}`, start)
268  await remember($, plan.path)
269  await update($, planA, () => plan)
270  await update($, restoredA, () => false)
271  await update($, doneA, () => seen)
272  await update($, startedA, () => start)
273  const rate = await learnedRate($)
274  await update($, rateA, () => rate)
275  await update($, noteA, () => `read from ${plan.kind}`)
276  await storeSet($, `last:${norm(await $.session.root())}`, plan.path)
277  await refreshGit($)
278  await show($)
279  return `tracking "${plan.title}" (${plan.tasks.length} tasks, read from ${plan.kind}).`
280}
281
282// The tracked file changed: read it again and time the tasks it newly marks done.
283async function reparse($: $) {
284  const old = await read($, planA)
285  if (!old) return
286  const plan = await load($, old.path)
287  if (!plan) return
288  const now = await $.clock.now()
289  const was = new Map(old.tasks.map(t => [t.key, t.isDone]))
290  const done = await update($, doneA, d => {
291    const next: WaiterDone = { ...d }
292    for (const t of plan.tasks) {
293      if (t.isDone && was.get(t.key) === false && !next[t.key]) next[t.key] = { at: now, by: 'file' }
294    }
295    return next
296  })
297  await update($, planA, () => plan)
298  const fileDone = Object.fromEntries(Object.entries(done).filter(([, v]) => v.by === 'file'))
299  await storeSet($, `seen:${plan.path}`, fileDone)
300}
301
302// A plan-like file a tool call just opened. It replaces the tracked plan when
303// nothing is tracked or the tracked one is finished. Then the commits decide: the
304// plan whose tasks they name wins, however old, even over an edit of another plan.
305// Else it replaces the tracked plan when it is being written, or the tracked one
306// came back from an earlier session or is older: an older plan opened for
307// reference does not take over this session's plan.
308async function consider($: $, path: string, isWrite: boolean) {
309  if (!/\.(md|markdown)$/i.test(path)) return
310  await allow($, path)
311  const tracked = await read($, planA)
312  if (tracked && same(tracked.path, path)) return reparse($)
313  const plan = await load($, path)
314  if (!plan || !(isPlanPath(path) || plan.kind === 'xml')) return
315  await remember($, path)
316  const v = await view($)
317  const isFinished = v !== null && v.doneCount === v.rows.length
318  const made = await created($, path)
319  const startedAt = await read($, startedA)
320  const isNewer = (made ?? Number.MAX_SAFE_INTEGER) > startedAt
321  const isRestored = await read($, restoredA)
322  const done = await read($, doneA)
323  const now = await $.clock.now()
324  const trackedIsPlan = tracked !== null && isPlanPath(tracked.path)
325  let byCommits: { read?: Evidence; trackedGit?: Evidence } = {}
326  if (tracked && trackedIsPlan && !isFinished) {
327    const since = made ?? (await storeGet<number>($, `start:${path}`, now))
328    const commits = await commitsSince($, dirOf(path), Math.min(since, startedAt))
329    if (commits) byCommits = { read: evidence(plan, commits, since, now), trackedGit: evidence(tracked, commits, startedAt, now) }
330  }
331  if (takesOver({
332    tracked: tracked !== null, trackedIsPlan,
333    isFinished, isWrite, isRestored, isNewer, done, now, ...byCommits,
334  })) {
335    await track($, path)
336    return
337  }
338  const told = await storeGet<string[]>($, 'told', [])
339  if (!told.includes(plan.path)) {
340    $.ui.toast(`waiter: found plan "${plan.title}". /waiter ${plan.path} to track it`)
341    await storeSet($, 'told', [...told, plan.path].slice(-50))
342  }
343}
344
345function filePathOf(e: unknown): string | undefined {
346  const p = (e as { file_path?: unknown }).file_path
347  return typeof p === 'string' ? p : undefined
348}
349
350function commandOf(e: unknown): string {
351  const c = (e as { command?: unknown }).command
352  return typeof c === 'string' ? c : ''
353}
354
355function rowTime(r: Row): { text: string; color?: string } {
356  if (r.state === 'done') return { text: r.tookMs !== undefined ? `took ${duration(r.tookMs)}` : 'done', color: 'green' }
357  if (r.isReview) return { text: 'saved, in review', color: 'cyan' }
358  if (r.state === 'current') {
359    const left = r.leftMs ?? r.estMs
360    if (r.stepAt !== undefined) return { text: `step ${r.stepAt}/${r.steps} ~${duration(left)}`, color: 'yellow' }
361    return left >= 0 ? { text: `~${duration(left)} left`, color: 'yellow' } : { text: `over ${duration(left)}`, color: 'red' }
362  }
363  return { text: `~${duration(r.estMs)}` }
364}
365
366function glyph(r: Row): { text: string; color?: string } {
367  if (r.state === 'done') return { text: '✓', color: 'green' }
368  if (r.state === 'current') return { text: '▶', color: 'yellow' }
369  return { text: '·' }
370}
371
372function headline(v: View): string {
373  const pct = Math.round(v.fraction * 100)
374  return `${pct}% · ${v.doneCount}/${v.rows.length} tasks · ~${duration(v.leftMs)} left · done by ${clock(v.etaAt)}`
375}
376
377async function onTasks($: $, tool: string, e: unknown, result: unknown) {
378  const now = await $.clock.now()
379  if (tool === 'TaskCreate') {
380    const task = (result as { task?: { id?: string; subject?: string } } | undefined)?.task
381    if (!task?.id) return
382    const id = String(task.id)
383    await update($, sessionA, list => [
384      ...list.filter(s => s.id !== id),
385      { id, subject: task.subject ?? '', status: 'pending' as const },
386    ])
387    return
388  }
389  if (tool === 'TaskUpdate') {
390    const u = e as { taskId?: string; status?: string; subject?: string }
391    if (!u.taskId) return
392    await update($, sessionA, list =>
393      u.status === 'deleted'
394        ? list.filter(s => s.id !== u.taskId)
395        : list.map(s => (s.id === u.taskId ? moved(s, u.status, u.subject, now) : s)),
396    )
397    return
398  }
399  const todos = (e as { todos?: { content: string; status: string }[] }).todos ?? []
400  await update($, sessionA, list => {
401    const by = new Map(list.map(s => [s.id, s]))
402    return todos.map(t => {
403      const was: WaiterSessionTask = by.get(t.content) ?? { id: t.content, subject: t.content, status: 'pending' }
404      return moved(was, t.status, undefined, now)
405    })
406  })
407}
408
409function moved(s: WaiterSessionTask, status: string | undefined, subject: string | undefined, now: number): WaiterSessionTask {
410  const next: WaiterSessionTask = { ...s, subject: subject ?? s.subject }
411  if (status === 'in_progress' || status === 'completed' || status === 'pending') next.status = status
412  if (status === 'in_progress' && next.startedAt === undefined) next.startedAt = now
413  if (status === 'completed' && next.doneAt === undefined) next.doneAt = now
414  return next
415}
416
417export const register: Register = on => {
418  on('session.start', async ($, e, next) => {
419    await $.command.register({
420      name: 'waiter',
421      description: 'Plan progress and time left per task. /waiter [plan path | min | off | refresh]',
422      argumentHint: '[plan path | min | off | refresh]',
423    })
424    const started = await next(e)
425
426    // A redraw now and then moves the clocks; a re-read picks up work done elsewhere.
427    $.clock.every(30_000, () => $.ui.invalidate('ui.render'))
428    $.clock.every(60_000, () => {
429      void reparse($).then(() => refreshGit($))
430    })
431
432    if ((await read($, modeA)) !== 'hidden') {
433      const mode = await storeGet<WaiterMode>($, 'mode', 'pane')
434      await update($, modeA, () => mode)
435    }
436    void (async () => {
437      const isRestore = !(await read($, planA))
438      if (isRestore) {
439        // A new session in the same project picks its last plan back up...
440        const last = await storeGet<string>($, `last:${norm(await $.session.root())}`, '')
441        if (!last || !(await load($, last))) return
442        await track($, last)
443        await update($, restoredA, () => true)
444      }
445      // ...unless the commits since name the tasks of another plan.
446      await followCommits($)
447      if (!isRestore) return
448      const v = await view($)
449      if (v && v.doneCount === v.rows.length) await $.ui.close({ id: PANE })
450    })()
451
452    return started
453  })
454
455  on('command.run', { command: 'waiter' }, async ($, e) => {
456    const arg = e.args.trim()
457    if (arg === '' || arg === 'show' || arg === 'max') {
458      if (!(await current($))) {
459        return { text: 'no plan yet. Run /waiter <plan.md>, or read or execute a plan and it is picked up.' }
460      }
461      await setMode($, 'pane')
462      return { text: 'pane opened.' }
463    }
464    if (arg === 'min') {
465      await setMode($, 'band')
466      return { text: 'minimized above the prompt.' }
467    }
468    if (arg === 'off') {
469      await stop($)
470      return { text: 'stopped tracking.' }
471    }
472    if (arg === 'refresh') {
473      await reparse($)
474      await refreshGit($)
475      return { text: 'refreshed.' }
476    }
477    const path = await absolute($, arg)
478    if (!(await openGuarded($, path))) return { text: `could not open ${path} (missing, or refused by a guard).` }
479    if ((await read($, modeA)) === 'hidden') await update($, modeA, () => 'pane' as WaiterMode)
480    return { text: await track($, path) }
481  })
482
483  on('tool.call', async ($, e, next) => {
484    const ran = await next(e)
485    if (ran.deny !== undefined || ran.isError) return ran
486    const tool = String(e.tool)
487    try {
488      if (tool === 'Read' || tool === 'Edit' || tool === 'Write' || tool === 'MultiEdit') {
489        const p = filePathOf(e)
490        if (p) await consider($, await absolute($, p), tool !== 'Read')
491      } else if ((tool === 'Bash' || tool === 'PowerShell') && /\bgit\b[\s\S]*\b(commit|merge|cherry-pick|rebase)\b/.test(commandOf(e))) {
492        await refreshGit($)
493      } else if (e.agentId === undefined && (tool === 'TaskCreate' || tool === 'TaskUpdate' || tool === 'TodoWrite')) {
494        await onTasks($, tool, e, ran.result)
495        if (!(await read($, planA))) await show($)
496      }
497    } catch (err) {
498      // tracking never gets in the way of the tool
499      $.ui.log(`waiter: ${String(err)}`, { to: 'debug' })
500    }
501    return ran
502  })
503
504  on('ui.close', { id: PANE }, async ($, e, next) => {
505    // The person closed the pane: keep the plan as the one-line band.
506    if (e.origin.kind === 'person') await update($, modeA, () => 'band' as WaiterMode)
507    return next(e)
508  })
509
510  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
511    const { Box, Text, Button } = $.ui.resolve(e)
512    const v = await view($)
513    const cols = Math.max(30, e.props.bodyColumns)
514    if (!v) {
515      return (
516        <Box flexDirection="column">
517          <Text dimColor>No plan tracked. /waiter path/to/plan.md, or start executing a plan.</Text>
518          <Button key="minimize" label="Minimize" hotkey="m" onPress={() => setMode($, 'band')} />
519        </Box>
520      )
521    }
522    const note = await read($, noteA)
523    const barW = Math.min(12, Math.max(6, Math.floor(cols / 6)))
524    const titleW = Math.max(8, cols - barW - 18)
525    return (
526      <Box flexDirection="column">
527        <Text bold wrap="truncate-end">
528          {v.title}
529        </Text>
530        <Text color="green">{bar(v.fraction, Math.max(10, cols - 2))}</Text>
531        <Text wrap="truncate-end">{headline(v)}</Text>
532        <Text dimColor wrap="truncate-end">
533          {note || v.kind} · {v.kind === 'session' ? `${duration(v.rate)} per task` : `${duration(v.rate * 10)} per 10 plan lines`}
534          {v.measured > 0 ? ` (learned from ${v.measured} done)` : ' (first guess)'}
535        </Text>
536        <Box flexDirection="column" marginTop={1}>
537          {v.rows.map(r => {
538            const g = glyph(r)
539            const t = rowTime(r)
540            return (
541              <Box key={r.key} flexDirection="column">
542               <Box flexDirection="row">
543                <Text color={g.color}>{g.text} </Text>
544                <Box width={titleW}>
545                  <Text wrap="truncate-end" dimColor={r.state === 'done'} bold={r.state === 'current'}>
546                    {r.title}
547                    {r.isManual ? ' [you]' : ''}
548                  </Text>
549                </Box>
550                <Text color={r.state === 'todo' ? undefined : g.color} dimColor={r.state === 'todo'}>
551                  {' '}
552                  {bar(r.fraction, barW)}{' '}
553                </Text>
554                <Text color={t.color} dimColor={r.state === 'todo'}>
555                  {t.text}
556                </Text>
557               </Box>
558               {r.stepTitle !== undefined && (
559                <Text dimColor wrap="truncate-end">
560                  {'    '}step {r.stepAt} of {r.steps}: {r.stepTitle}
561                </Text>
562               )}
563              </Box>
564            )
565          })}
566        </Box>
567        <Box flexDirection="row" gap={1} marginTop={1}>
568          <Button key="minimize" label="Minimize" hotkey="m" onPress={() => setMode($, 'band')} />
569          <Button key="refresh" label="Refresh" hotkey="r" onPress={() => reparse($).then(() => refreshGit($))} />
570          <Button key="stop" label="Stop tracking" onPress={() => stop($)} />
571        </Box>
572      </Box>
573    )
574  })
575
576  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
577    if (e.props.hasSurvey || (await read($, modeA)) !== 'band') return next(e)
578    const v = await view($)
579    if (!v) return next(e)
580    const { Box, Text, Button } = $.ui.resolve(e)
581    const cur = v.rows.find(r => r.state === 'current')
582    const curText = cur ? ` · ▶ ${cur.title.slice(0, 40)} ${rowTime(cur).text}` : ''
583    return (
584      <Box flexDirection="row" gap={1}>
585        <Text bold>waiter</Text>
586        <Text color="green">{bar(v.fraction, 16)}</Text>
587        <Box flexGrow={1} flexShrink={1}>
588          <Text wrap="truncate-end">
589            {Math.round(v.fraction * 100)}% {v.doneCount}/{v.rows.length}
590            {curText} · all ~{duration(v.leftMs)}, by {clock(v.etaAt)}
591          </Text>
592        </Box>
593        <Button key="expand" label="Expand" hotkey="e" onPress={() => setMode($, 'pane')} />
594        <Button key="hide" label="Hide" onPress={() => setMode($, 'hidden')} />
595      </Box>
596    )
597  })
598}
599
hooks/plan.ts 584 lines
1// Pure plan logic: parse a plan's structure, match commits to its tasks, and
2// estimate the time left. No `$` here, so the tests drive it with fixtures.
3
4import type {
5  WaiterDone,
6  WaiterKind,
7  WaiterPlan,
8  WaiterSessionTask,
9  WaiterTask,
10} from '../types'
11
12export const DEFAULT_RATE = 6_000 // ms per non-blank plan line, before anything is learned
13export const ITEM_MS = 10 * 60_000 // a session task with no history
14export const MANUAL_MIN_MS = 20 * 60_000 // floor for a hands-on task
15export const GAP_MS = 4 * 60 * 60_000 // a longer gap is a break, not work
16// A task's commit is often followed by review and fix commits: the newest
17// committed task counts as in review until it has been quiet this long.
18export const REVIEW_MS = 20 * 60_000
19
20const NOUNS = 'task|step|phase|milestone|stage|part|chunk|story|epic|deliverable|wave|sprint|item'
21const TASK_HEADING = new RegExp(
22  `^(#{1,6})\\s+(?:\\[[ xX]\\]\\s+)?(?:~~)?\\s*(${NOUNS})\\s*#?\\s*((?:[A-Z](?=\\d))?\\d+[a-z]?(?:\\.\\d+)*)\\b\\s*[:.)\\-–—]?\\s*(.*)$`,
23  'i',
24)
25const NUMBERED_HEADING = /^(#{2,6})\s+(\d+(?:\.\d+)*)[.)]?\s+(.+)$/
26const ANY_HEADING = /^(#{1,6})\s+(.+)$/
27const CHECKBOX = /^(\s*)[-*+]\s+\[([ xX])\]\s+(.*)$/
28const NUMBERED_ITEM = /^\s*\d+[.)]\s+\S/
29// Explicit marks only: "done" as a plain word in a title is prose, not a mark.
30const DONE_MARK = /✅|✔|☑|\[[xX]\]|\((done|DONE)\)|\bDONE\b|\bCOMPLETED?\b|^\s*~~/
31const MANUAL_MARK = /CONTROLLER|\bmanual\b|by hand|\bhuman\b|checkpoint|acceptance|with (the )?user/i
32const TOKEN = /\b(?:delivery|phase|milestone|sprint|release|iteration|stage|plan)\s+([0-9]+[a-z]?(?:\.[0-9]+)?)\b/i
33// A path that says it holds a plan: a plans/ folder, PLAN.md, *-plan.md, todo.md ...
34const PLAN_PATH = /(^|[/\\._-])(plans?|todos?|tasks|roadmap|backlog|checklist)([/\\._-]|$)/i
35
36type Line = { text: string; isCode: boolean }
37
38function lines(text: string): Line[] {
39  let isFence = false
40  return text.split(/\r?\n/).map(raw => {
41    const fence = /^\s*(```|~~~)/.test(raw)
42    const isCode = isFence || fence
43    if (fence) isFence = !isFence
44    return { text: raw, isCode }
45  })
46}
47
48function clean(title: string): string {
49  return title.replace(/\*\*|__|`|~~/g, '').replace(/\s+/g, ' ').trim()
50}
51
52function baseName(path: string): string {
53  return path.replace(/\\/g, '/').split('/').pop()?.replace(/\.md$/i, '') ?? path
54}
55
56const EXT = 'py|pyi|ts|tsx|js|jsx|mjs|cjs|json|md|yml|yaml|toml|java|kt|kts|swift|go|rs|rb|cs|cpp|cc|c|h|hpp|sql|sh|ps1|html|css|scss|xml|gradle|ini|cfg|txt'
57// A file a step names: `tools/desfire/ops.py`, burn_wizard.py, src/app.ts ...
58const FILE_NAME = new RegExp(`(?:^|[\\s(\`'"])((?:[\\w.-]+/)*[\\w-][\\w.-]*\\.(?:${EXT}))(?=$|[\\s)\`'",.:;])`, 'g')
59
60// Code a step names by module, `ops.burn` or `ev1fake.burn_script`: the module
61// is kept as "~ops", which matches a changed file named ops.<anything>.
62const MODULE_REF = new RegExp(`\`([A-Za-z_]\\w*)\\.(?!(?:${EXT})\`)[A-Za-z_][\\w.]*(?:\\(\\))?\``, 'g')
63
64function filesIn(text: string): string[] {
65  const files = [...text.matchAll(FILE_NAME)].map(m => m[1].replace(/^\.\//, '').toLowerCase())
66  const modules = [...text.matchAll(MODULE_REF)].map(m => `~${m[1].toLowerCase()}`)
67  return [...files, ...modules]
68}
69
70// The section of a task: its own line to the line before `end`. Its steps are
71// its checkboxes (else its numbered items); each step keeps the files it names
72// first, so a later "commit these files" step does not claim them.
73function section(all: Line[], start: number, end: number) {
74  let weight = 0
75  let ticked = 0
76  const boxes: number[] = []
77  const numbered: number[] = []
78  for (let i = Math.max(start, 0); i < end; i += 1) {
79    const { text, isCode } = all[i]
80    if (text.trim() !== '') weight += 1
81    if (isCode || i === start) continue
82    const box = CHECKBOX.exec(text)
83    if (box) {
84      boxes.push(i)
85      if (box[2] !== ' ') ticked += 1
86    } else if (NUMBERED_ITEM.test(text)) {
87      numbered.push(i)
88    }
89  }
90  const starts = boxes.length > 0 ? boxes : numbered
91  // A step's own line names what it works on; its notes may mention files of
92  // other steps. So the step lines claim first, then the notes, each in order.
93  const seen = new Set<string>()
94  const stepTitles = starts.map(from => clean(all[from].text.replace(CHECKBOX, '$3').replace(/^\s*\d+[.)]\s+/, '')).slice(0, 80))
95  const stepFiles: string[][] = starts.map(() => [])
96  const claim = (n: number, text: string) => {
97    for (const f of filesIn(text)) {
98      if (!seen.has(f)) {
99        seen.add(f)
100        stepFiles[n].push(f)
101      }
102    }
103  }
104  starts.forEach((from, n) => claim(n, all[from].text))
105  starts.forEach((from, n) => {
106    const to = n + 1 < starts.length ? starts[n + 1] : end
107    for (let i = from + 1; i < to; i += 1) if (!all[i].isCode) claim(n, all[i].text)
108  })
109  return {
110    weight: Math.max(1, weight),
111    steps: starts.length,
112    stepsDone: boxes.length > 0 ? ticked : 0,
113    stepTitles,
114    stepFiles,
115  }
116}
117
118// The furthest step (1-based) that names a file now being changed; 0 for none.
119export function stepReached(t: WaiterTask, changed: readonly string[]): number {
120  const files = t.stepFiles ?? []
121  const hit = (named: string) =>
122    changed.some(c => {
123      const path = c.replace(/\\/g, '/').toLowerCase()
124      if (named.startsWith('~')) return (path.split('/').pop() ?? '').replace(/\.[^.]*$/, '') === named.slice(1)
125      return path === named || path.endsWith(`/${named}`)
126    })
127  let reached = 0
128  files.forEach((names, i) => {
129    if (names.some(hit)) reached = i + 1
130  })
131  return reached
132}
133
134// `git status --porcelain` lines to the paths they name.
135export function parseStatus(stdout: string): string[] {
136  return stdout
137    .split(/\r?\n/)
138    .filter(line => line.length > 3)
139    .map(line => {
140      const path = line.slice(3)
141      const to = path.includes(' -> ') ? path.split(' -> ').pop()! : path
142      return to.replace(/^"|"$/g, '')
143    })
144}
145
146function task(key: string, title: string, s: ReturnType<typeof section>, extra: Partial<WaiterTask>): WaiterTask {
147  const t = clean(title)
148  const isDone = DONE_MARK.test(title) || (s.steps > 0 && s.stepsDone === s.steps)
149  return { key, title: t, ...s, isDone, isManual: MANUAL_MARK.test(t), ...extra }
150}
151
152function byHeadings(all: Line[], match: (text: string) => { level: number; num?: string; noun?: string; title: string } | null) {
153  const found = all
154    .map((l, i) => (l.isCode ? null : { i, m: match(l.text) }))
155    .filter((x): x is { i: number; m: NonNullable<ReturnType<typeof match>> } => x !== null && x.m !== null)
156  if (found.length < 2) return null
157  // The level that holds most of them is the task level.
158  const counts = new Map<number, number>()
159  for (const f of found) counts.set(f.m.level, (counts.get(f.m.level) ?? 0) + 1)
160  const level = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0][0]
161  const picked = found.filter(f => f.m.level === level)
162  if (picked.length < 2) return null
163  return picked.map(f => {
164    let end = all.length
165    for (let j = f.i + 1; j < all.length; j += 1) {
166      const h = all[j].isCode ? null : ANY_HEADING.exec(all[j].text)
167      if (h && h[1].length <= level) {
168        end = j
169        break
170      }
171    }
172    const key = f.m.num !== undefined ? `${(f.m.noun ?? '').toLowerCase()}-${f.m.num}` : `l${f.i}`
173    return task(key, f.m.title, section(all, f.i, end), { num: f.m.num, noun: f.m.noun })
174  })
175}
176
177function byXml(text: string): WaiterTask[] | null {
178  const blocks = [...text.matchAll(/<task\b([^>]*)>([\s\S]*?)<\/task>/gi)]
179  if (blocks.length < 2) return null
180  return blocks.map((b, n) => {
181    const name = /<name>([\s\S]*?)<\/name>/i.exec(b[2])?.[1] ?? b[2].trim().split(/\r?\n/)[0] ?? `Task ${n + 1}`
182    const body = lines(b[2])
183    const s = section(body, -1, body.length)
184    const isDone = /status\s*=\s*["']?(done|complete|completed)/i.test(b[1])
185    const t = task(`task-${n + 1}`, name, s, { num: String(n + 1), noun: 'Task' })
186    return { ...t, isDone: t.isDone || isDone }
187  })
188}
189
190function byCheckboxes(all: Line[]): WaiterTask[] | null {
191  const top = all
192    .map((l, i) => ({ i, m: l.isCode ? null : CHECKBOX.exec(l.text) }))
193    .filter(x => x.m !== null && x.m[1].length === 0)
194  if (top.length < 2) return null
195  return top.map((x, n) => {
196    let end = all.length
197    for (let j = x.i + 1; j < all.length; j += 1) {
198      const l = all[j]
199      if (l.isCode) continue
200      const box = CHECKBOX.exec(l.text)
201      if ((box && box[1].length === 0) || ANY_HEADING.test(l.text)) {
202        end = j
203        break
204      }
205    }
206    const s = section(all, x.i, end)
207    const own = x.m![2] !== ' '
208    const t = task(`box-${n + 1}`, x.m![3], s, {})
209    // A ticked top-level box is done whatever its children say.
210    return { ...t, isDone: own || t.isDone }
211  })
212}
213
214// Reads a plan's structure. Null when the text holds no recognizable list of tasks.
215export function parsePlan(text: string, path: string): WaiterPlan | null {
216  const all = lines(text)
217  const h1 = all.find(l => !l.isCode && /^#\s+\S/.test(l.text))
218  const title = clean(h1 ? h1.text.replace(/^#\s+/, '') : baseName(path))
219  const token = (TOKEN.exec(title) ?? TOKEN.exec(baseName(path).replace(/[-_]/g, ' ')))?.[1]?.toLowerCase()
220
221  const tries: [WaiterKind, () => WaiterTask[] | null][] = [
222    ['xml', () => byXml(text)],
223    [
224      'headings',
225      () =>
226        byHeadings(all, t => {
227          const m = TASK_HEADING.exec(t)
228          return m ? { level: m[1].length, noun: m[2], num: m[3], title: `${m[2]} ${m[3]}: ${m[4] || ''}`.replace(/:\s*$/, '') } : null
229        }),
230    ],
231    [
232      'numbered',
233      () =>
234        byHeadings(all, t => {
235          const m = NUMBERED_HEADING.exec(t)
236          return m && !m[2].includes('.') ? { level: m[1].length, num: m[2], title: `${m[2]}. ${m[3]}` } : null
237        }),
238    ],
239    ['checkboxes', () => byCheckboxes(all)],
240    [
241      'sections',
242      () => {
243        if (!isPlanPath(path)) return null
244        const found = byHeadings(all, t => {
245          const m = ANY_HEADING.exec(t)
246          return m && m[1].length >= 2 && m[1].length <= 4 ? { level: m[1].length, title: m[2] } : null
247        })
248        return found && found.length >= 3 ? found : null
249      },
250    ],
251  ]
252  for (const [kind, run] of tries) {
253    const tasks = run()
254    if (tasks && tasks.length >= 2) return { title, path, kind, token, tasks }
255  }
256  return null
257}
258
259export function isPlanPath(path: string): boolean {
260  return PLAN_PATH.test(path)
261}
262
263// A tracked plan that finished a task this recently is still being executed.
264export const BUSY_MS = 3 * 60 * 60_000
265
266// What the commits say about a plan: when it came to be, the newest commit that
267// names one of its tasks (0 for none), and whether they finish it.
268export type Evidence = { since: number; hit: number; isFinished: boolean }
269
270export function evidence(plan: WaiterPlan, commits: readonly Commit[], since: number, now: number): Evidence {
271  const done = matchCommits(plan, commits, since)
272  const hit = Object.values(done).reduce((m, d) => Math.max(m, d.at), 0)
273  const v = estimate(plan, done, [], since, DEFAULT_RATE, now)
274  return { since, hit, isFinished: v.doneCount === v.rows.length }
275}
276
277// Plan `a` is being executed rather than plan `b`: a commit named one of a's tasks
278// after b existed and after b's own last one. However old a is, and however new b.
279function committedOver(a: Evidence, b: Evidence): boolean {
280  return !a.isFinished && a.hit > Math.max(b.hit, b.since)
281}
282
283// Of the other plans, the one the commits say is being executed instead of the
284// tracked one (the newest commit wins); null when they say nothing against it.
285export function committedPlan<T extends { git: Evidence }>(tracked: Evidence, others: readonly T[]): T | null {
286  const ahead = others.filter(o => committedOver(o.git, tracked))
287  return ahead.sort((x, y) => y.git.hit - x.git.hit)[0] ?? null
288}
289
290// Whether a plan file a tool call just opened replaces the tracked plan. Finding
291// nothing (or a finished plan) tracked, it does. Then the commits decide (`read` and
292// `trackedGit`): the plan whose tasks they name is the one being executed, so editing
293// a sibling plan mid-run does not take over (a brand-new plan has no commits against
294// it, and does). Writing a plan takes over. Otherwise a plan that is only read takes
295// over a restored or older tracked plan, but never one still moving: reading the next
296// plans of a delivery must not hide the one being executed.
297export function takesOver(o: {
298  tracked: boolean
299  trackedIsPlan: boolean
300  isFinished: boolean
301  isWrite: boolean
302  isRestored: boolean
303  isNewer: boolean
304  done: WaiterDone
305  now: number
306  read?: Evidence
307  trackedGit?: Evidence
308}): boolean {
309  if (!o.tracked || o.isFinished || !o.trackedIsPlan) return true
310  if (o.read && o.trackedGit) {
311    if (committedOver(o.read, o.trackedGit)) return true
312    if (committedOver(o.trackedGit, o.read)) return false
313  }
314  if (o.isWrite) return true
315  const isBusy = Object.values(o.done).some(d => o.now - d.at < BUSY_MS)
316  return !isBusy && (o.isRestored || o.isNewer)
317}
318
319// The session's own task list as a plan of equal-weight tasks.
320export function sessionPlan(list: readonly WaiterSessionTask[]): WaiterPlan | null {
321  if (list.length === 0) return null
322  return {
323    title: 'Session tasks',
324    path: '',
325    kind: 'session',
326    tasks: list.map(s => ({
327      key: `s-${s.id}`,
328      title: s.subject,
329      weight: 1,
330      steps: 0,
331      stepsDone: 0,
332      isDone: s.status === 'completed',
333      isManual: false,
334    })),
335  }
336}
337
338export type Commit = { at: number; subject: string }
339
340// Which plan tasks the commits finish: "Task 3", "(4b Task 3)", "Phase 2: ...".
341// Commits before the plan existed, commits about the plan itself, and commits
342// tagged with another delivery's token ("4b" against a "4c" plan) do not count.
343export function matchCommits(plan: WaiterPlan, commits: readonly Commit[], since: number): WaiterDone {
344  const done: WaiterDone = {}
345  const shape = /\b\d+[a-z]\b/gi
346  for (const c of commits) {
347    if (c.at < since) continue
348    if (/^\s*(plan|spec|design|memo|notes?|wip)\b/i.test(c.subject)) continue
349    // "4c Part B plan, review fix: ... a Task 3 test pins it" edits the plan, not Task 3.
350    if (/\b(plan|spec)\b/i.test(c.subject.split(/[:,]/)[0])) continue
351    if (plan.token) {
352      const tokens = (c.subject.match(shape) ?? []).map(t => t.toLowerCase())
353      if (tokens.length > 0 && !tokens.includes(plan.token)) continue
354    }
355    for (const t of plan.tasks) {
356      if (t.num === undefined || t.noun === undefined) continue
357      const re = new RegExp(`\\b${t.noun}\\s*#?${t.num.replace(/\./g, '\\.')}(?![.\\d])`, 'i')
358      if (!re.test(c.subject)) continue
359      // The last one counts: "Task 5", then "Task 5 fix 1" after the review.
360      const was = done[t.key]
361      if (!was || c.at > was.at) done[t.key] = { at: c.at, by: 'git' }
362    }
363  }
364  return done
365}
366
367// Session tasks that name a plan task ("Task 3: ...") lend it their times.
368export function sessionFor(plan: WaiterPlan, list: readonly WaiterSessionTask[]): Map<string, WaiterSessionTask> {
369  const out = new Map<string, WaiterSessionTask>()
370  if (plan.kind === 'session') {
371    for (const s of list) out.set(`s-${s.id}`, s)
372    return out
373  }
374  for (const s of list) {
375    const m = new RegExp(`\\b(${NOUNS})\\s*#?(\\d+[a-z]?(?:\\.\\d+)*)\\b`, 'i').exec(s.subject)
376    const hit = m
377      ? plan.tasks.find(t => t.num === m[2] && (t.noun ?? '').toLowerCase() === m[1].toLowerCase())
378      : plan.tasks.find(t => t.title.toLowerCase().includes(s.subject.toLowerCase()))
379    if (hit) out.set(hit.key, s)
380  }
381  return out
382}
383
384export type RowState = 'done' | 'current' | 'todo'
385export type Row = {
386  key: string
387  title: string
388  state: RowState
389  isManual: boolean
390  steps: number
391  stepsDone: number
392  estMs: number
393  tookMs?: number
394  leftMs?: number // current only; negative = over the estimate
395  isReview?: boolean // committed, review and fixes may still follow
396  stepAt?: number // current only: the step its changed files have reached (1-based)
397  stepTitle?: string
398  fraction: number // 0..1 for this task's bar
399}
400export type View = {
401  title: string
402  path: string
403  kind: WaiterKind
404  rows: Row[]
405  doneCount: number
406  fraction: number
407  leftMs: number
408  etaAt: number
409  rate: number
410  measured: number // tasks whose real duration fed the rate
411}
412
413// Puts times on the plan: what is done, which task runs, how long each takes.
414export function estimate(
415  plan: WaiterPlan,
416  done: WaiterDone,
417  session: readonly WaiterSessionTask[],
418  startedAt: number,
419  learnedRate: number,
420  now: number,
421  changed: readonly string[] = [],
422): View {
423  const linked = sessionFor(plan, session)
424  const perItem = plan.kind === 'session'
425  const finished = plan.tasks.map(t => {
426    const s = linked.get(t.key)
427    const at = s?.doneAt ?? done[t.key]?.at
428    const isDone = t.isDone || s?.status === 'completed' || done[t.key] !== undefined
429    return { t, s, isDone, at }
430  })
431  // Plans run in order: a finished task means the ones before it are finished too
432  // (an older plan whose commits never named its tasks still reads as done).
433  const lastDoneIdx = finished.map(f => f.isDone).lastIndexOf(true)
434  for (let i = 0; i < lastDoneIdx; i += 1) finished[i].isDone = true
435  // The newest task finished only by a recent commit is still in review, unless
436  // the session already marked it done or works on a later task.
437  let reviewIdx = -1
438  const newest = finished[lastDoneIdx]
439  if (newest) {
440    const g = done[newest.t.key]
441    const next = finished[lastDoneIdx + 1]
442    const isLaterRunning =
443      finished.slice(lastDoneIdx + 1).some(f => f.s?.status === 'in_progress') ||
444      (next !== undefined && stepReached(next.t, changed) > 0)
445    if (
446      !newest.t.isDone &&
447      newest.s?.status !== 'completed' &&
448      g?.by === 'git' &&
449      now - g.at < REVIEW_MS &&
450      !isLaterRunning
451    ) {
452      newest.isDone = false
453      reviewIdx = lastDoneIdx
454    }
455  }
456
457  // Real durations, in plan order: each task from the end of the one before.
458  let prev = startedAt
459  let spent = 0
460  let weighed = 0
461  let measured = 0
462  const took = new Map<string, number>()
463  for (const f of finished) {
464    if (!f.isDone || f.at === undefined) continue
465    const from = f.s?.startedAt ?? prev
466    const ms = f.at - from
467    if (ms > 0 && ms <= GAP_MS) {
468      took.set(f.t.key, ms)
469      if (!f.t.isManual) {
470        spent += ms
471        weighed += f.t.weight
472        measured += 1
473      }
474    }
475    prev = Math.max(prev, f.at)
476  }
477  const rate = perItem
478    ? measured > 0
479      ? spent / weighed
480      : ITEM_MS
481    : measured > 0
482      ? spent / weighed
483      : learnedRate
484  const est = (t: WaiterTask) => {
485    const ms = t.weight * rate
486    return t.isManual ? Math.max(ms, MANUAL_MIN_MS) : ms
487  }
488
489  const lastDone = finished.reduce((m, f) => (f.isDone && f.at !== undefined ? Math.max(m, f.at) : m), startedAt)
490  const currentIdx = (() => {
491    if (reviewIdx >= 0) return reviewIdx
492    const running = finished.findIndex(f => !f.isDone && f.s?.status === 'in_progress')
493    return running >= 0 ? running : finished.findIndex(f => !f.isDone)
494  })()
495
496  let total = 0
497  let doneWeight = 0
498  let partWeight = 0
499  let leftMs = 0
500  const rows: Row[] = finished.map((f, i) => {
501    const { t } = f
502    total += t.weight
503    const e = est(t)
504    const base = { key: t.key, title: t.title, isManual: t.isManual, steps: t.steps, stepsDone: t.stepsDone, estMs: e }
505    if (f.isDone) {
506      doneWeight += t.weight
507      return { ...base, state: 'done', tookMs: took.get(t.key), fraction: 1 }
508    }
509    if (i === reviewIdx) {
510      partWeight += t.weight * 0.95
511      return { ...base, state: 'current', isReview: true, fraction: 0.95 }
512    }
513    if (i === currentIdx) {
514      const from = f.s?.startedAt ?? lastDone
515      const elapsed = now - from >= 0 && now - from <= GAP_MS ? now - from : 0
516      const byTime = Math.min(elapsed / e, 0.95)
517      const ticked = t.steps > 0 ? t.stepsDone / t.steps : 0
518      // The files being changed say which step the work is on: halfway through it.
519      const reached = stepReached(t, changed)
520      if (reached > 0 && t.steps > 0) {
521        const fraction = Math.max((reached - 0.5) / t.steps, ticked)
522        partWeight += t.weight * fraction
523        const left = e * (1 - fraction)
524        leftMs += left
525        return { ...base, state: 'current', leftMs: left, fraction, stepAt: reached, stepTitle: t.stepTitles?.[reached - 1] }
526      }
527      const fraction = Math.max(byTime, ticked)
528      partWeight += t.weight * fraction
529      const left = e - elapsed
530      leftMs += Math.max(left, 0)
531      return { ...base, state: 'current', leftMs: left, fraction }
532    }
533    leftMs += e
534    return { ...base, state: 'todo', fraction: t.steps > 0 ? t.stepsDone / t.steps : 0 }
535  })
536
537  return {
538    title: plan.title,
539    path: plan.path,
540    kind: plan.kind,
541    rows,
542    doneCount: rows.filter(r => r.state === 'done').length,
543    fraction: total > 0 ? (doneWeight + partWeight) / total : 0,
544    leftMs,
545    etaAt: now + leftMs,
546    rate,
547    measured,
548  }
549}
550
551export function bar(fraction: number, width: number): string {
552  const w = Math.max(1, Math.floor(width))
553  const full = Math.round(Math.min(Math.max(fraction, 0), 1) * w)
554  return '█'.repeat(full) + '░'.repeat(w - full)
555}
556
557export function duration(ms: number): string {
558  const m = Math.round(Math.abs(ms) / 60_000)
559  if (m < 1) return '<1m'
560  if (m < 60) return `${m}m`
561  const h = Math.floor(m / 60)
562  const r = m % 60
563  return r === 0 ? `${h}h` : `${h}h ${r}m`
564}
565
566export function clock(at: number): string {
567  const d = new Date(at)
568  const hh = String(d.getHours()).padStart(2, '0')
569  const mm = String(d.getMinutes()).padStart(2, '0')
570  return `${hh}:${mm}`
571}
572
573export function parseGitLog(stdout: string): Commit[] {
574  return stdout
575    .split(/\r?\n/)
576    .map(line => {
577      const tab = line.indexOf('\t')
578      if (tab < 0) return null
579      const at = Number(line.slice(0, tab)) * 1000
580      return Number.isFinite(at) ? { at, subject: line.slice(tab + 1) } : null
581    })
582    .filter((c): c is Commit => c !== null)
583}
584
types/index.d.ts 73 lines
1// What a plan's structure came from: task headings, numbered headings, GSD
2// <task> blocks, a top-level checkbox list, plain sections, or the
3// session's own task list (TaskCreate / TodoWrite).
4export type WaiterKind =
5  | 'headings'
6  | 'numbered'
7  | 'xml'
8  | 'checkboxes'
9  | 'sections'
10  | 'session'
11
12export type WaiterTask = {
13  key: string
14  // The task's number as the plan writes it ("6", "2.1"), when it has one.
15  num?: string
16  // The word in front of the number ("Task", "Phase"): what commits say.
17  noun?: string
18  title: string
19  // Effort proxy: non-blank lines of the task's section (1 per session task).
20  weight: number
21  steps: number
22  stepsDone: number
23  // Each step's title, and the files it is the first to name.
24  stepTitles?: string[]
25  stepFiles?: string[][]
26  isDone: boolean
27  // A hands-on task (CONTROLLER, manual, acceptance): flat estimate, not learned from.
28  isManual: boolean
29}
30
31export type WaiterPlan = {
32  title: string
33  // Absolute path with forward slashes; '' for the session task list.
34  path: string
35  kind: WaiterKind
36  // Delivery / phase token from the title ("4b"), used to filter commits.
37  token?: string
38  tasks: WaiterTask[]
39}
40
41export type WaiterSessionTask = {
42  id: string
43  subject: string
44  status: 'pending' | 'in_progress' | 'completed'
45  startedAt?: number
46  doneAt?: number
47}
48
49// When each task was seen finished (epoch ms), by task key, and by what.
50export type WaiterDone = Record<string, { at: number; by: 'git' | 'file' | 'session' }>
51
52export type WaiterMode = 'pane' | 'band' | 'hidden'
53
54declare module 'claude-code' {
55  interface PluginState {
56    waiter: {
57      plan: WaiterPlan | null
58      done: WaiterDone
59      session: WaiterSessionTask[]
60      // When tracking of this plan started (plan file creation, or first seen).
61      startedAt: number
62      // Learned milliseconds per weight unit (lines), across plans and projects.
63      rate: number
64      mode: WaiterMode
65      note: string
66      // The plan came back from an earlier session, not from this one's work.
67      isRestored: boolean
68      // Files changed and not yet committed, in every working folder of the plan's repo.
69      changed: string[]
70    }
71  }
72}
73