SLOPSHOPPER

backlog-tools

Backlog-native Claude Code skills for the Backlog product itself — writing a Backlog import plan from an agreed specification, running one item of such a plan…

panebandguardcommandtoaststatus
v0.20.0MITupdated 2026-10-26JSdotNet/Backlog/plugins/backlog-tools
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · backlog-tools
│ ┃ Plan progress ✕ › fix the failing auth test and add an audit log call │ ┃ No plan running yet. │ ┃ Run /backlog-tools:execute-plan +tag to ⏺ Read(src/auth.ts) │ ┃ start one. ⎿ 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 │ │ › /plan-progress │ ⎿ backlog-tools: Plan progress pane opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Plan progress
No plan running yet. Run /backlog-tools:execute-plan +tag to start one.
README

backlog-tools

Backlog-native tooling — skills specific to the Backlog product itself, as opposed to general-purpose or devbook tooling. Six skills: one for each direction of a plan, one for running a whole plan, one for closing the entries whose pull request merged, one for bringing another tool's items into the Inbox, and one for the remarks a person leaves while reading — and a pane that follows a running plan.

  • import-plan — turns an agreed specification into a Backlog import plan (ADR 0007: .devbook/arc42/adr/0007-import-reuses-the-entry-text-grammar.md). Every entry is a prompt an AI session runs, or a task or test only the user does — never both in one entry. Prompts are the default: while it writes the plan it interviews you — the open decisions, the values and access the work needs, what a pass looks like — and writes the answers into the prompts, so no step stops to ask when it runs. A manual check is offered as an AI-run QA prompt first, and a step stays a task or test only when you keep it, with a Kept manual: line saying why. Every step, whatever its kind, names its repository with repo:. Every prompt — and every task or test that checks what the source describes — carries a Read first: line naming the sections and designs it was planned from, by repository path and #anchor or artifact URL, so a session running the pasted entry reads the same context; run-plan-item reads them before it starts. It always ships a review view next to the raw plan — one HTML page built from skills/import-plan/assets/plan-review.html that parses the embedded plan itself and shows its checks, dependency order and entries, published as an artifact every run before the plan text is shown — a local HTML file only when the host has no artifacts. User-invoked only (disable-model-invocation: true); it never talks to the Backlog app or GitHub. A plan imports at two levels (ADR 0013: .devbook/arc42/adr/0013-imported-plan-is-a-roadmap-item-laid-out-by-import.md): it opens with one plan entry, which Import turns into the Roadmap Item, and the step entries under it share its +tag, so the item gathers them:
  # VS Code desktop rollout

  `plan` `*high` `+vscode-desktop-rollout` `repo:backlog-desktop`

  # Add the export command

  `prompt` `!ready` `+vscode-desktop-rollout` `id:add-command` `repo:backlog-desktop` `effort:5`

Asked for the roadmap level, it writes plan entries only, one per agreed feature chapter, ordered by after: from the chapters' depends-on lists.

  • run-plan-item — runs one entry of such a plan after it is copied out of the Backlog app and pasted into a session. The app puts the invocation on the first line of every entry it copies — /backlog-tools:run-plan-item entry <id>:, the entry under it — so the paste runs the skill outright; it is also model-invoked on the marker line every generated prompt entry opens with (Backlog plan item …`). Both shapes are defined in skills/import-plan/assets/backlog-import-grammar.md. It checks the item is still outstanding before doing anything — pasting the same item twice is expected and must not redo finished work, and declines a plan entry in one line, since only Import acts on one — and then carries out the instructions the way the current repository says work is done. When a backlog MCP server is in the session's tool list it reads the entry's status from it (read_item) and reports Ready → In progress → Done back (transition) — In progress while the pull request is open, Done once it has merged into the default branch or a plan/<slug> branch — every call carrying the repository` read off the git remote; without one it falls back to searching git and says the status has to be set by hand.
  • execute-plan — runs a whole plan, after the pattern of Matt Pocock's implement-spec. It reads the plan from the backlog MCP server by its +tag (get_plan_items) or from a file import-plan wrote, builds the graph its after: tokens draw, and changes nothing itself: each prompt entry whose prerequisites are done goes to its own sub-agent, briefed by skills/execute-plan/assets/item-brief.md, which makes its own worktree and runs the entry through run-plan-item — so every entry passes the repository's gate and its own Personal Validation. Entries that wait on nothing run in parallel. Before it starts anything — attended or unattended — it opens every entry's Read first: references and linked Devbook chapters, and warns about each one it cannot reach, asking once whether to go, hold the entries that name it, or stop to fix the plan. An entry is done when its pull request merges — into plan/<slug> in branch mode, into the base branch otherwise; the orchestrator then moves it to Done and starts what waited on it. It stops at task and test entries, listing what they hold up, starts the application in its own worktree for the first one that validates landed work, and resumes from the plan's state when invoked again. Three landing modes, defined in skills/execute-plan/assets/landing-modes.md: per item, each pull request to the base branch; branch, each into one plan/<tag without its +> branch that the orchestrator merges into, ending in a single pull request to the base branch; and stacked, each cut from and targeting its predecessor's branch, so a chain runs before anything merges and the person merges bottom-up. Attended, the orchestrator relays each Personal Validation to the person; unattended (branch or stacked), each entry parks at its gate and lands as a draft pull request whose body is the review handoff, so the whole plan runs without anyone present and Personal Validation happens on the drafts — in branch mode on the closing draft to the base branch. A failed entry blocks only what depends on it. It titles its own session <tag>:execute-plan and labels each sub-agent <tag>:<n> - <Title>, and a ready entry in another repository is handed to a new session in that repository's checkout running the same plan, per skills/execute-plan/assets/handoff.md. User-invoked only. The UserPromptSubmit hook stays quiet on a prompt that names this skill, so a pasted plan is not mistaken for one item.
  • close-merged — moves to Done every entry whose pull request has merged into the default branch or a plan/<slug> branch: the merges run-plan-item and execute-plan did not see, made on GitHub's own page or after the session ended. It lists the repository's in_progress and ready entries (list_entries) and the pull requests merged into either since the oldest of them started (gh pr list), resolves each pull request to its entry by the link link_change recorded (find_item with externalId and repoId), and transitions it. A pull request merged into a stacked parent finishes nothing yet, and a task or test — the plan's sign-off among them — is left to the person and to execute-plan's Resume. Model-invoked; it writes nothing to the repository or to GitHub.
  • import-inbox — turns an export from another to-do tool into an inbox import manifest (ADR 0017: .devbook/arc42/adr/0017-inbox-import-is-a-capture-source-with-a-markdown-manifest.md). The manifest is Markdown with front matter, one # item per open task, each with a meta fence of capture facts. The Inbox's Sources panel imports it through Import file…. Completed tasks are dropped. The person chooses which labels become tags and which lists file into which Inbox Lists. Microsoft To Do is the first tool it knows. Another tool is added as a row of the skill's Formats table, never as a second manifest shape, so the product needs no converter per tool. Like the plan skill, it always ships a review view, built from skills/import-inbox/assets/inbox-import-review.html. The view parses the embedded manifest itself and runs the checks of the grammar in skills/import-inbox/assets/inbox-import-manifest.md. That matters more here: a hand-edited manifest can break in ways a generated one never does. User-invoked only (disable-model-invocation: true); it never talks to the Backlog app, the source tool, or GitHub.
  • handle-remarks — empties the other inbox: the private reading notes a person left on a repository's Devbook chapters in the app. It reads them over MCP (list_annotations), writes each answer into the chapter as a devbook annotation fence through the devbook plugin's own annotations.mjs, and only then resolves the note (resolve_annotation). Fence first, resolve second, because that is the order whose half-done state is recoverable. It writes nothing for an archived repository, whose devbook is read-only (list_annotations answers archived: true, local ADR 0029 §4), and neither does run-plan-item's short form. The two annotation kinds stay two things — .devbook/arc42/adr/0012-backlog-is-an-mcp-server-inside-the-desktop-app.md §6 is the decision, and the app is never the fence's writer. run-plan-item carries a short form of the same procedure for the notes an item it just ran leaves answerable.

The plan-item marker exists because a plan is written before the app has given its entries an id, so it restates the id:, +tag, repo: and after: the metadata line carries. The entry line carries what only the app knows — the stored id — and is what makes any copied entry a runnable paste.

hooks/hooks.json adds a UserPromptSubmit hook (Claude Code) that notices either line in a prompt and nudges the session to invoke run-plan-item, so triggering does not rest on the skill description alone. It needs grep on the hook shell, which Claude Code provides on every platform it runs on.

It also registers hooks/telemetry-forwarder.mjs for PreToolUse, PostToolUse, SubagentStop, PreCompact, Stop and SessionEnd. Each event is posted to the app's /telemetry endpoint — beside /mcp, on the same port and behind the same bearer token — and the app attributes the tool calls, delegated agents, token usage and context gauge to the delivery run that session is driving, which the Sessions pane shows under the run's row. The port and token come from BACKLOG_MCP_PORT and BACKLOG_MCP_TOKEN, else from the app's own settings.json. The tool-call events are matched to shell, edits, sub-agents, skills and MCP tools, the calls a run's figures are read for, so a session is not paying a process spawn on every Read and Grep. The script needs Node, drops the tool's output before posting, gives up after two seconds and exits 0 on any error, so a closed app costs a session nothing but a refused connection.

The plan-progress pane

hooks/hooks.json also names a hooks module, hooks/register.tsx — Claude Code's function hooks, beside the command hooks above. It draws an execute-plan run in two places:

  • The band above the prompt, while any entry is in flow: the plan's tag and done over total, then one row per entry running, at a gate or blocked — its delivery flow's stages (✓ done, ● in progress, ✗ blocked, ‖ parked, – skipped, ○ pending) and the stage it stands at, tagged gate or blocked. Entries done or manual fold into one also: line. A band another plugin draws there, such as delivery-run-view's flow band, stays under it.
  • The Plan progress pane, the band's details button or /backlog-tools:plan-progress: the whole plan as a matrix — every entry a row, every stage a column under its short name (scp, imp, b&t, pv, …) — with the gate's review link and each block's reason under it. A surface has no parked status, so an unattended entry reports the Personal Validation it moved onto its draft as blocked; the pane draws that as parked, and keeps ✗ for a block the run stopped at.

The status line carries the counts, and a toast says when an entry reaches its gate or blocks.

It writes nothing and calls nothing: it reads the calls the run already makes.

What it showsRead from
The entries and their statusesget_plan_items and transition, on any MCP server
Which sub-agent runs which entryThe first line of skills/execute-plan/assets/item-brief.md, in the Agent call's prompt — change it and parseBrief in hooks/parse.ts with it
Each entry's stagesstart_run, update_stage and finish_run on any delivery surface, from the sub-agent's loop or one it spawned. A call the surface answered with an error still counts, since the pane mirrors what the worker said; a call a function hook refused with deny never ran and does not
How the entry endedThe sub-agent's one-line return: gate, pr <url>, blocked <stage>: …, done-before

The module's state is declared in types/index.d.ts. claude plugin validate plugins/backlog-tools checks the module against it, and claude plugin test plugins/backlog-tools runs tests/, which drive the hooks against the engine and a scripted run (tests/demo.ts). Once Claude Code has loaded the plugin from this checkout it lays its declarations in the ignored .claude-plugin/types/, and tsc -p plugins/backlog-tools type-checks the module. Function hooks are early access in Claude Code: a release can change the API, and the pane is what breaks.

The plugin ships one manifest, .claude-plugin/plugin.json, for Claude Code.

Microsoft To Do export

Microsoft To Do has no export of its own. What a route has to deliver is a stable id per task, because the import knows an item by {tool}:{external_id}. Without an id, every re-import duplicates. The routes compared on 2026-09-26:

RouteStable id per taskCompleted flagList nameWho sees the data
Microsoft Graph, read with Microsoft's Microsoft.Graph.Authentication PowerShell module (chosen)yes: the todoTask idyes: statusyes: the enclosing listonly Microsoft and the person's machine; the scope is read-only Tasks.Read
Graph Explorer, copying responses by handyesyesyes, one list per queryonly Microsoft. But each list and every @odata.nextLink page is a separate copy, which does not scale past a handful of tasks
Microsoft-To-Do-Export (open source CLI, daylamtayari)its raw JSON is Graph's shape; its CSV and Todoist formats are notyes, with --completedyesthe person's machine, but it asks for a Graph Explorer token with Tasks.ReadWrite pasted into it
Microsoft To Do Exporter (hosted web app)not documentednot documentedyesa third-party site that reads every task with Tasks.Read
To Do Vo Do (browser app)yes: its CSV carries idyesnot documented for its CSVa third-party app; by its own account the data goes between Microsoft and the browser only
Classic Outlook's CSV export (work accounts, which sync To Do into Outlook Tasks)noyesthe Outlook folderonly the person's machine; unavailable for personal accounts

The Graph route wins. It is first-party, read-only, works for work, school, and personal accounts, pages through every list, and keeps Graph's id. The steps and the script are in the skill's own Inputs section, and they are what the plan's round-trip test runs. One limitation applies to every route, because it comes from Graph itself: a task's id changes when the task is moved to another list. Graph's immutable ids cover Outlook items but not todoTask. So a task moved between two exports is imported a second time.

Install

Claude Code, inside a session started at the repository root:

/plugin marketplace add .
/plugin install backlog-tools@jsdotnet-backlog
Source 4 files
hooks/register.tsx 341 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Worker } from '../types'
5import {
6  asId,
7  asIndex,
8  isPlanItems,
9  isTransition,
10  newWorker,
11  normStatus,
12  parseBrief,
13  parsePlan,
14  parseReturn,
15  parseRunId,
16  parseStages,
17  surfaceOp,
18  tally,
19} from './parse'
20import { GLYPH, KIND, abbrev, alsoLine, bandRows, cellsOf, columnsOf, currentStage, matrixLayout, matrixSvg, rowsOf, stageStatesOf } from './view'
21
22// The execute-plan view: a band above the prompt with the entries still in flow, and a pane —
23// the band's details — with the whole plan as a matrix of entries by delivery-flow stage. Both
24// are read from the calls execute-plan and its sub-agents already make; nothing here writes.
25const PANE = 'plan-progress'
26const plan = atom({ plugin: 'backlog-tools', key: 'plan' } as const, null)
27const workers = atom({ plugin: 'backlog-tools', key: 'workers' } as const, [])
28const parents = atom({ plugin: 'backlog-tools', key: 'parents' } as const, {})
29
30const patchWorker = (list: Worker[], agentId: string, fn: (w: Worker) => Worker) =>
31  list.map(w => (w.agentId === agentId ? fn(w) : w))
32
33/**
34 * The run ids a worker holds. The session's state outlives a reload of this code, so a worker
35 * 0.17.0 stored has a single `runId` and no list: it counts as a run no surface confirmed.
36 */
37const idsOf = (w: Worker): string[] => (w as Partial<Worker>).runIds ?? []
38
39/** The execute-plan worker a loop belongs to, walking nested spawns up. */
40async function rootOf($: EngineInterface, agentId: string | undefined) {
41  if (!agentId) return undefined
42  const list = await read($, workers)
43  const map = await read($, parents)
44  let id: string | undefined = agentId
45  for (let hop = 0; id && hop < 8; hop++) {
46    if (list.some(w => w.agentId === id)) return id
47    id = map[id]
48  }
49  return undefined
50}
51
52async function refreshStatus($: EngineInterface) {
53  const c = tally(await read($, plan), await read($, workers))
54  if (c.total === 0) return
55  const parts = [`plan ${c.done}/${c.total}`]
56  if (c.running) parts.push(`${c.running} running`)
57  if (c.gate) parts.push(`${c.gate} at gate`)
58  if (c.blocked) parts.push(`${c.blocked} blocked`)
59  $.ui.status(parts.join(' · '))
60}
61
62export const register: Register = on => {
63  on('session.start', async ($, e, next) => {
64    await $.command.register({
65      name: 'plan-progress',
66      description: 'Show execute-plan progress and each entry’s delivery flow in a pane',
67    })
68    return next(e)
69  })
70
71  on('command.run', { command: 'plan-progress' }, async $ => {
72    await $.ui.open({ id: PANE, title: 'Plan progress' })
73    return { text: 'Plan progress pane opened.' }
74  })
75
76  // A pane never fails the call it watches: a hook that throws hands the call on untouched.
77  on('tool.call', async ($, e, next) => {
78    const tool = e.tool as string
79    const args = e as unknown as Record<string, unknown>
80
81    if (isPlanItems(tool)) {
82      const ran = await next(e)
83      const parsed = 'text' in ran ? parsePlan(String(args.planId ?? ''), ran.text) : null
84      if (parsed && parsed.entries.length > 0 && !ran.isError) {
85        // Another plan's items: the workers of the previous one are not this plan's.
86        if ((await read($, plan))?.tag !== parsed.tag) await update($, workers, () => [])
87        await update($, plan, () => parsed)
88        await refreshStatus($)
89      }
90      return ran
91    }
92
93    if (isTransition(tool) && args.id) {
94      const ran = await next(e)
95      if (ran.deny !== undefined || ran.isError) return ran
96      const status = normStatus(args.status)
97      await update($, plan, p =>
98        p ? { ...p, entries: p.entries.map(x => (x.id === args.id ? { ...x, status } : x)) } : p,
99      )
100      await refreshStatus($)
101      return ran
102    }
103
104    const op = surfaceOp(tool)
105    const owner = op ? await rootOf($, e.agentId) : undefined
106    if (!op || !owner) return next(e)
107
108    const ran = await next(e)
109    // The pane mirrors what the worker said, not what a surface stored: a call the surface
110    // rejected still counts. A call the host denied never ran, and the worker retries it.
111    if (ran.deny !== undefined) return ran
112    // Any report from the worker's loop means it is working again, after a gate answered too.
113    const resume = (w: Worker): Worker => (w.state === 'gate' ? { ...w, state: 'running', note: '' } : w)
114    // Until a surface confirms the run, the latest declared run is the worker's current one; after,
115    // a report under another id is another run's (a second flow), not this one's.
116    const ours = (w: Worker) => idsOf(w).length === 0 || idsOf(w).includes(asId(args.runId))
117    if (op === 'start_run') {
118      const stages = parseStages(args.stages)
119      const flow = String(args.skillId ?? '')
120      const runId = ran.isError ? '' : parseRunId(ran.text)
121      if (stages.length > 0) {
122        await update($, workers, list =>
123          patchWorker(list, owner, w => {
124            // The fan-out to a second surface, a retry and a reattach all declare the same run.
125            const same =
126              w.runStatus === 'in_progress' && w.flow === flow &&
127              w.stages.length === stages.length && w.stages.every((s, i) => s === stages[i])
128            if (same) {
129              const ids = idsOf(w)
130              return { ...resume(w), runIds: runId && !ids.includes(runId) ? [...ids, runId] : ids }
131            }
132            return {
133              ...resume(w),
134              flow,
135              runIds: runId ? [runId] : [],
136              stages,
137              stageStatus: stages.map(() => 'pending'),
138              runStatus: 'in_progress',
139            }
140          }),
141        )
142      }
143    } else if (op === 'update_stage') {
144      const i = asIndex(args.stageIndex)
145      const status = String(args.status ?? '')
146      await update($, workers, list =>
147        patchWorker(list, owner, w => {
148          if (!ours(w) || !(i >= 0 && i < w.stages.length)) return w
149          const stageStatus = [...w.stageStatus]
150          stageStatus[i] = status
151          return { ...resume(w), stageStatus }
152        }),
153      )
154    } else {
155      await update($, workers, list =>
156        patchWorker(list, owner, w => (ours(w) ? { ...w, runStatus: String(args.status ?? '') } : w)),
157      )
158    }
159    return ran
160  }).catch(($, e, next) => next(e))
161
162  on('agent.spawn', async ($, e, next) => {
163    const ran = await next(e)
164    const agentId = ran.agentId
165    if (!agentId) return ran
166
167    const brief = parseBrief(e.prompt)
168    if (brief) {
169      // A brief for another plan starts the pane over: the previous run's plan and workers go.
170      const isNewPlan = (await read($, plan))?.tag !== brief.tag
171      await update($, workers, list => [
172        ...(isNewPlan ? [] : list.filter(w => w.entryId !== brief.entryId)),
173        newWorker(agentId, brief),
174      ])
175      if (isNewPlan) await update($, parents, () => ({}))
176      await update($, plan, p => (p && p.tag === brief.tag ? p : { tag: brief.tag, entries: [] }))
177      await refreshStatus($)
178    } else if (e.parentAgentId && (await rootOf($, e.parentAgentId))) {
179      const parent = e.parentAgentId
180      await update($, parents, map => ({ ...map, [agentId]: parent }))
181    }
182    return ran
183  }).catch(($, e, next) => next(e))
184
185  on('turn.complete', async ($, e, next) => {
186    const agentId = e.agentId
187    if (agentId && (await read($, workers)).some(w => w.agentId === agentId)) {
188      const back = e.isAborted ? { state: 'stopped' as const, note: 'aborted' } : parseReturn(e.answer)
189      await update($, workers, list => patchWorker(list, agentId, w => ({ ...w, ...back })))
190      await refreshStatus($)
191      const w = (await read($, workers)).find(x => x.agentId === agentId)
192      if (w && back.state === 'gate') $.ui.toast(`${w.n} - ${w.title}: waiting at the gate`)
193      if (w && back.state === 'blocked') $.ui.toast(`${w.n} - ${w.title}: blocked ${back.note}`)
194    }
195    return next(e)
196  })
197
198  // The details: every entry of the plan, one row each, one block per stage of its flow. Every
199  // column is a Box of a set width, so the matrix holds on the desktop's proportional text too.
200  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
201    const { Box, Text } = $.ui.resolve(e)
202    const p = await read($, plan)
203    const list = await read($, workers)
204    const cols = Math.max(30, e.props.bodyColumns ?? e.viewport?.columns ?? 60)
205
206    if (!p && list.length === 0) {
207      return (
208        <Box flexDirection="column">
209          <Text dimColor>No plan running yet.</Text>
210          <Text dimColor>Run /backlog-tools:execute-plan +tag to start one.</Text>
211        </Box>
212      )
213    }
214
215    const c = tally(p, list)
216    const rows = rowsOf(p, list)
217    const stages = columnsOf(rows)
218    const attention = (['gate', 'blocked'] as const).filter(k => c[k] > 0).map(k => `${c[k]} ${KIND[k].label}`)
219    const summary = [`${c.done}/${c.total} done`, ...attention].join(' · ')
220
221    // A surface that draws SVG gets design C as drawn: rounded blocks with gaps between them.
222    if (e.surface !== 'terminal') {
223      const { Svg } = $.ui.resolve(e)
224      return (
225        <Svg
226          source={matrixSvg(p?.tag ?? 'Plan', summary, rows, stages)}
227          alt={`${p?.tag ?? 'Plan'}: ${summary}; ${rows.length} entries by delivery stage`}
228        />
229      )
230    }
231
232    const layout = matrixLayout(cols, stages.length)
233    const notes = rows.filter(r => r.w && r.w.note !== '' && r.w.state !== 'running')
234
235    return (
236      <Box flexDirection="column">
237        <Box flexDirection="row" justifyContent="space-between">
238          <Text bold wrap="truncate-end">{p?.tag ?? 'Plan'}</Text>
239          <Text>{summary}</Text>
240        </Box>
241        <Box height={1} />
242        {layout.hasHeadings && stages.length > 0 && (
243          <Box flexDirection="row">
244            <Box width={2 + layout.titleWidth + 1} />
245            {stages.map((s, i) => (
246              <Box key={`h${i}`} width={layout.cell} marginRight={layout.gap} justifyContent="center">
247                <Text dimColor wrap="truncate-end">{abbrev(s)}</Text>
248              </Box>
249            ))}
250          </Box>
251        )}
252        {rows.map(r => (
253          <Box key={r.id} flexDirection="row">
254            <Box width={2}>
255              <Text color={KIND[r.kind].color}>{KIND[r.kind].mark}</Text>
256            </Box>
257            <Box width={layout.titleWidth} marginRight={1}>
258              <Text wrap="truncate-end">{`${r.n} ${r.title}`}</Text>
259            </Box>
260            {(r.w ? stageStatesOf(r.w) : []).map((s, i) => {
261              const cell = GLYPH[s] ?? GLYPH.pending!
262              return (
263                <Box key={`c${i}`} width={layout.cell} marginRight={layout.gap} justifyContent="center">
264                  <Text color={cell.color} dimColor={cell.dim}>{cell.g}</Text>
265                </Box>
266              )
267            })}
268            {r.kind === 'manual' && <Text dimColor>{r.type}</Text>}
269            {r.w && r.w.stages.length === 0 && r.w.state === 'running' && <Text dimColor>starting…</Text>}
270          </Box>
271        ))}
272        {notes.length > 0 && <Box height={1} />}
273        {notes.map(r => (
274          <Text key={`n${r.id}`} dimColor wrap="truncate-end">
275            <Text color={KIND[r.kind].color}>{KIND[r.kind].mark}</Text> {r.n} {r.w ? currentStage(r.w) || r.w.state : ''}: {r.w?.note ?? ''}
276          </Text>
277        ))}
278      </Box>
279    )
280  })
281
282  // The band above the prompt (design F): the entries still in flow, three columns — the entry,
283  // its stage marks, where it stands — each a Box of a set width so the rows line up. Whatever
284  // the plugins beneath draw there (a flow band of this session's own run) stays, under it.
285  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
286    if (e.props.hasSurvey) return next(e)
287    const p = await read($, plan)
288    const list = await read($, workers)
289    const rows = rowsOf(p, list)
290    const { shown, more } = bandRows(rows, e.props.maxRows)
291    if (shown.length === 0) return next(e)
292
293    const { Box, Text, Button } = $.ui.resolve(e)
294    const c = tally(p, list)
295    const also = alsoLine(rows)
296    const labelWidth = Math.min(32, Math.max(14, Math.floor(e.props.bodyColumns / 3)))
297    const markWidth = Math.max(...shown.map(r => r.w?.stages.length ?? 0)) + 2
298    const band = (
299      <Box flexDirection="column">
300        <Box flexDirection="row" justifyContent="space-between">
301          <Text wrap="truncate-end">
302            <Text bold>execute-plan</Text>  <Text dimColor>{p?.tag ?? ''}</Text>  {c.done}/{c.total} done
303            {also !== '' && <Text dimColor>  also: {also}</Text>}
304          </Text>
305          <Button key="details" label="details" onPress={() => $.ui.open({ id: PANE, title: 'Plan progress' })} />
306        </Box>
307        {shown.map(r => {
308          const stage = r.w ? currentStage(r.w) : ''
309          return (
310            <Box key={r.id} flexDirection="row">
311              <Box width={labelWidth} marginRight={2}>
312                <Text dimColor wrap="truncate-end">{`${r.n} ${r.title}`}</Text>
313              </Box>
314              <Box width={markWidth} flexDirection="row">
315                {cellsOf(r.w).map((cell, i) => (
316                  <Box key={`c${i}`} width={1}>
317                    <Text color={cell.color} dimColor={cell.dim}>{cell.g}</Text>
318                  </Box>
319                ))}
320              </Box>
321              <Text wrap="truncate-end">
322                <Text color={r.kind === 'blocked' ? 'red' : 'yellow'}>{stage || (r.w && r.w.stages.length === 0 ? 'starting…' : '')}</Text>
323                {r.kind === 'gate' && <Text color="magenta"> gate</Text>}
324                {r.kind === 'blocked' && <Text color="red"> blocked</Text>}
325              </Text>
326            </Box>
327          )
328        })}
329        {more > 0 && <Text dimColor>+{more} more in flow — details</Text>}
330      </Box>
331    )
332    const below = await next(e)
333    return below ? (
334      <Box flexDirection="column">
335        {band}
336        {below}
337      </Box>
338    ) : band
339  })
340}
341
hooks/parse.ts 168 lines
1import type { Plan, PlanEntry, Worker, WorkerState } from '../types'
2
3/** get_plan_items on any server whose tool name ends in it. */
4export const isPlanItems = (tool: string) => /^mcp__.*__get_plan_items$/.test(tool)
5export const isTransition = (tool: string) => /^mcp__.*backlog.*__transition$/.test(tool)
6/** start_run/update_stage/finish_run on any delivery surface, bound or bare. */
7export const surfaceOp = (tool: string): 'start_run' | 'update_stage' | 'finish_run' | null => {
8  const m = /^mcp__.*__(start_run|update_stage|finish_run)$/.exec(tool)
9  return m ? (m[1] as 'start_run' | 'update_stage' | 'finish_run') : null
10}
11
12/** `Draft`, `in-progress`, `InProgress` → `draft`, `inprogress`. */
13export const normStatus = (s: unknown) => String(s ?? '').toLowerCase().replace(/[^a-z]/g, '')
14
15const parseJson = (text: string | undefined): unknown => {
16  if (!text) return null
17  try {
18    return JSON.parse(text)
19  } catch {
20    const at = text.indexOf('{')
21    if (at < 0) return null
22    try {
23      return JSON.parse(text.slice(at))
24    } catch {
25      return null
26    }
27  }
28}
29
30/** A stored title carries its step number (`3 - Sort by effort`): the number and the rest. */
31export const splitTitle = (title: string, fallback: number) => {
32  const m = /^(\d+)\s*-\s*(.*)$/.exec(title.trim())
33  return m ? { n: Number(m[1]), title: (m[2] ?? '').trim() } : { n: fallback, title: title.trim() }
34}
35
36/**
37 * The PlanItemsPayload: { planId, count, entries: EntryPayload[] }, wire tokens lowercase.
38 * An entry with no step number in its title — a follow-up create_item filed under the plan tag —
39 * is numbered after the highest step, so it never shows a number an imported step holds.
40 */
41export const parsePlan = (tag: string, text: string | undefined): Plan | null => {
42  const body = parseJson(text) as { planId?: string; entries?: Record<string, unknown>[] } | null
43  if (!body || !Array.isArray(body.entries)) return null
44  const split = body.entries
45    .filter(raw => String(raw.type ?? '').toLowerCase() !== 'plan')
46    .map(raw => ({ raw, ...splitTitle(String(raw.title ?? ''), NaN) }))
47  let next = Math.max(0, ...split.map(s => s.n).filter(n => !Number.isNaN(n)))
48  const entries: PlanEntry[] = split.map(({ raw, n, title }) => ({
49    id: String(raw.id ?? ''),
50    n: Number.isNaN(n) ? ++next : n,
51    title,
52    type: String(raw.type ?? '').toLowerCase(),
53    status: normStatus(raw.status),
54  }))
55  return { tag: body.planId ?? tag, entries }
56}
57
58/** The run id start_run answered with, under any of the spellings a surface uses. */
59export const parseRunId = (text: string | undefined): string => {
60  const body = parseJson(text) as Record<string, unknown> | null
61  const id = body?.runId ?? body?.id ?? (body?.run as Record<string, unknown> | undefined)?.id
62  if (id) return String(id)
63  const m = /run[_ ]?id["':\s]+([\w-]+)/i.exec(text ?? '')
64  return m?.[1] ?? ''
65}
66
67const stageName = (v: unknown): string => {
68  const raw = typeof v === 'string' ? v : v && typeof v === 'object' ? ((v as { name?: unknown; title?: unknown }).name ?? (v as { title?: unknown }).title) : undefined
69  return typeof raw === 'string' ? raw.trim() : ''
70}
71
72/**
73 * The stages a start_run declared, however the worker spelled them: an array of names or of
74 * `{ name }` / `{ title }` objects, that array JSON-encoded as a string, or a comma-separated
75 * string. Anything else declares none.
76 */
77export const parseStages = (v: unknown): string[] => {
78  if (typeof v === 'string') {
79    const text = v.trim()
80    if (text.startsWith('[')) {
81      try {
82        return parseStages(JSON.parse(text))
83      } catch {
84        return []
85      }
86    }
87    if (text.startsWith('{')) return []
88    return text.split(',').map(s => s.trim()).filter(s => s !== '')
89  }
90  if (!Array.isArray(v)) return []
91  return v.map(stageName).filter(s => s !== '')
92}
93
94/** A stage index sent as a number or a numeric string; anything else is NaN, out of every range. */
95export const asIndex = (v: unknown): number => {
96  const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v.trim()) : NaN
97  return Number.isInteger(n) ? n : NaN
98}
99
100/** A run id sent as a string or a number, as the string a surface answered; else ''. */
101export const asId = (v: unknown): string =>
102  typeof v === 'string' ? v.trim() : typeof v === 'number' && Number.isFinite(v) ? String(v) : ''
103
104/** The brief's opening line: You run one entry of the Backlog plan `<tag>`: `<n> - <Title>` (id `<id>`). */
105export const parseBrief = (prompt: string) => {
106  const m = /entry of the Backlog plan `([^`]+)`: `(\d+)\s*-\s*([^`]+)` \(id `([^`]+)`\)/.exec(prompt)
107  if (!m) return null
108  const { title } = splitTitle(m[3] ?? '', 0)
109  return { tag: m[1] ?? '', n: Number(m[2]), title, entryId: m[4] ?? '' }
110}
111
112/** A sub-agent's one-line return: done-before, gate, pr <url>, blocked <stage>: <reason>. */
113export const parseReturn = (answer: string): { state: WorkerState; note: string } => {
114  const lines = answer.trim().split(/\r?\n/)
115  for (const line of [lines[0] ?? '', ...lines.slice(1).reverse()]) {
116    const l = line.replace(/^[`*\s]+/, '')
117    const m = /^(done-before|gate|pr|blocked)\b[:\s]*(.*)$/i.exec(l)
118    if (m) return { state: (m[1] ?? '').toLowerCase() as WorkerState, note: (m[2] ?? '').trim() }
119  }
120  return { state: 'stopped', note: (lines[0] ?? '').slice(0, 80) }
121}
122
123export const newWorker = (agentId: string, b: NonNullable<ReturnType<typeof parseBrief>>): Worker => ({
124  agentId,
125  entryId: b.entryId,
126  n: b.n,
127  title: b.title,
128  state: 'running',
129  note: '',
130  flow: '',
131  runIds: [],
132  stages: [],
133  stageStatus: [],
134  runStatus: '',
135})
136
137/** Progress counted per entry, a worker's state overriding the stored status. */
138export const tally = (plan: Plan | null, workers: Worker[]) => {
139  const byEntry = new Map(workers.map(w => [w.entryId, w]))
140  // A plan read from a file never passes get_plan_items: its workers are all there is.
141  const ids = plan && plan.entries.length > 0 ? plan.entries.map(e => e.id) : workers.map(w => w.entryId)
142  const c = { total: ids.length, done: 0, running: 0, gate: 0, review: 0, blocked: 0, manual: 0, waiting: 0 }
143  for (const id of ids) {
144    const e = plan?.entries.find(x => x.id === id)
145    const w = byEntry.get(id)
146    const k = kindOf(e, w)
147    c[k] += 1
148  }
149  return c
150}
151
152export type Kind = 'done' | 'running' | 'gate' | 'review' | 'blocked' | 'manual' | 'waiting'
153
154export const kindOf = (e: PlanEntry | undefined, w: Worker | undefined): Kind => {
155  if (e && (e.status === 'done' || e.status === 'archived')) return 'done'
156  if (w) {
157    if (w.state === 'running') return 'running'
158    if (w.state === 'gate') return 'gate'
159    if (w.state === 'pr') return 'review'
160    if (w.state === 'done-before') return 'done'
161    // Aborted, or a return that is none of the four: it needs the person as much as a block.
162    if (w.state === 'blocked' || w.state === 'stopped') return 'blocked'
163  }
164  if (e && (e.type === 'task' || e.type === 'test')) return 'manual'
165  if (e?.status === 'inprogress') return 'running'
166  return 'waiting'
167}
168
hooks/view.ts 200 lines
1import type { Plan, PlanEntry, Worker } from '../types'
2import { kindOf } from './parse'
3import type { Kind } from './parse'
4
5// What the pane's matrix and the band draw, worked out apart from drawing them so the tests
6// can hold the layout without a surface.
7
8export type Cell = { g: string; color?: string; dim?: boolean }
9
10/** A stage's mark, in the band language delivery-run-view draws a flow in. */
11export const CELL: Record<string, Cell> = {
12  done: { g: '✓', color: 'green' },
13  in_progress: { g: '●', color: 'yellow' },
14  blocked: { g: '✗', color: 'red' },
15  parked: { g: '‖', color: 'magenta' },
16  skipped: { g: '–', dim: true },
17  pending: { g: '○', dim: true },
18}
19
20export const KIND: Record<Kind, { mark: string; color?: string; label: string }> = {
21  done: { mark: '✓', color: 'green', label: 'done' },
22  running: { mark: '▶', color: 'cyan', label: 'running' },
23  gate: { mark: '◆', color: 'yellow', label: 'at gate' },
24  review: { mark: '◇', color: 'magenta', label: 'PR open' },
25  blocked: { mark: '✗', color: 'red', label: 'blocked' },
26  // One cell wide in every terminal, so the matrix columns stay aligned.
27  manual: { mark: '✎', color: 'yellow', label: 'manual' },
28  waiting: { mark: '○', label: 'waiting' },
29}
30
31const SHORT: Record<string, string> = {
32  'update base': 'upd', scope: 'scp', plan: 'pln', implement: 'imp', review: 'rev',
33  'build test': 'b&t', verify: 'ver', 'spec check': 'spc', ready: 'rdy',
34  'personal validation': 'pv', 'create pull request': 'pr', 'create pr': 'pr', 'report back': 'rb',
35  summary: 'sum', drafting: 'dft', 'check review': 'c&r',
36}
37
38/**
39 * A stage's column heading: the delivery phases by their usual short name, whether start_run
40 * named them by title (`Build & Test`) or by id (`phase-build-test`); others cut to 3.
41 */
42export const abbrev = (stage: string) => {
43  const key = stage.trim().toLowerCase().replace(/^phase-/, '').replace(/[-_&]+/g, ' ').replace(/\s+/g, ' ').trim()
44  return SHORT[key] ?? key.replace(/ /g, '').slice(0, 3)
45}
46
47/**
48 * Each stage's status as drawn. A surface knows no `parked`, so an unattended run reports the
49 * Personal Validation it moved onto a draft pull request as `blocked` and carries on. A block
50 * in a run that came back with a draft, at a gate, or finished parked is parked, and so is one
51 * a later stage went on past while the run is still going. A run that came back blocked keeps
52 * every block a failure, Summary closing it `done` notwithstanding; a later `skipped` is no
53 * sign of moving on, since a red Build & Test skips Verify on its way back to Implement.
54 */
55export const stageStatesOf = (w: Worker): string[] => {
56  const s = w.stages.map((_, i) => w.stageStatus[i] ?? 'pending')
57  const failed = w.state === 'blocked' || w.state === 'stopped' || w.runStatus === 'blocked'
58  const settled = w.state === 'pr' || w.state === 'gate' || w.state === 'done-before' || w.runStatus === 'parked'
59  const movedOn = (i: number) => s.slice(i + 1).some(t => t === 'in_progress' || t === 'done')
60  return s.map((x, i) => (x === 'blocked' && !failed && (settled || movedOn(i)) ? 'parked' : x))
61}
62
63export const cellsOf = (w: Worker | undefined): Cell[] =>
64  w ? stageStatesOf(w).map(s => CELL[s] ?? { g: '○', dim: true }) : []
65
66/** The stage a worker stands at: the one running, else the one blocked, else the one parked. */
67export const currentStage = (w: Worker) => {
68  const s = stageStatesOf(w)
69  const i = [s.indexOf('in_progress'), s.indexOf('blocked'), s.indexOf('parked')].find(x => x >= 0) ?? -1
70  return i >= 0 ? (w.stages[i] ?? '') : ''
71}
72
73export type Row = { id: string; n: number; title: string; type: string; kind: Kind; w?: Worker; e?: PlanEntry }
74
75/** Every entry of the plan in plan order; without a plan read, the workers. */
76export const rowsOf = (plan: Plan | null, workers: Worker[]): Row[] => {
77  const byEntry = new Map(workers.map(w => [w.entryId, w]))
78  return plan && plan.entries.length > 0
79    ? plan.entries.map(e => ({ id: e.id, n: e.n, title: e.title, type: e.type, kind: kindOf(e, byEntry.get(e.id)), w: byEntry.get(e.id), e }))
80    : workers.map(w => ({ id: w.entryId, n: w.n, title: w.title, type: 'prompt', kind: kindOf(undefined, w), w }))
81}
82
83/** The columns of the matrix: the longest stage list any worker declared. */
84export const columnsOf = (rows: Row[]) =>
85  rows.reduce<string[]>((best, r) => (r.w && r.w.stages.length > best.length ? r.w.stages : best), [])
86
87/** A matrix cell as design C draws it: a block per stage, its mark dark on top. */
88export const BLOCK: Record<string, { bg: string; g: string }> = {
89  done: { bg: '#5fd38d', g: '' },
90  in_progress: { bg: '#56c8e8', g: '▶' },
91  blocked: { bg: '#f2767a', g: '✗' },
92  parked: { bg: '#d58be8', g: '‖' },
93  skipped: { bg: '#3a3a42', g: '–' },
94  pending: { bg: '#26262c', g: '' },
95}
96
97/** The same cell in a terminal, where a block cannot leave a gap: one coloured glyph. */
98export const GLYPH: Record<string, Cell> = {
99  done: { g: '■', color: 'green' },
100  in_progress: { g: '▶', color: 'cyan' },
101  blocked: { g: '✗', color: 'red' },
102  parked: { g: '‖', color: 'magenta' },
103  skipped: { g: '–', dim: true },
104  pending: { g: '·', dim: true },
105}
106
107/**
108 * How wide the terminal matrix draws in `cols` cells: a mark and a title column, then one cell
109 * per stage — three wide and a gap, under its short name, when that leaves the title 14 cells,
110 * else two wide and no headings. The title column stops at 36, so a wide pane does not push
111 * the cells away from the names.
112 */
113export const matrixLayout = (cols: number, stageCount: number) => {
114  const wide = cols - 2 - 1 - 14 >= stageCount * 4
115  const cell = wide ? 3 : 2
116  const gap = wide ? 1 : 0
117  const titleWidth = Math.min(36, Math.max(10, cols - 2 - 1 - stageCount * (cell + gap)))
118  return { cell, gap, hasHeadings: wide, titleWidth }
119}
120
121const HEX: Record<string, string> = {
122  green: '#5fd38d', cyan: '#56c8e8', yellow: '#e8c25a', magenta: '#d58be8', red: '#f2767a',
123}
124const xml = (text: string) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
125const clip = (text: string, max: number) => (text.length <= max ? text : `${text.slice(0, max - 1)}…`)
126
127/**
128 * Design C as one SVG, for a surface that draws one: a dark card with the plan's tag and
129 * counts, the stage headings, a row per entry with a rounded block per stage, and the gate's
130 * review link and each block's reason under it.
131 */
132export const matrixSvg = (tag: string, summary: string, rows: Row[], stages: string[]) => {
133  const pad = 16
134  const labelWidth = 260
135  const cell = 30
136  const gap = 4
137  const rowHeight = 24
138  const notes = rows.filter(r => r.w && r.w.note !== '' && r.w.state !== 'running')
139  const width = pad * 2 + labelWidth + Math.max(stages.length, 4) * (cell + gap)
140  const top = 68
141  const notesTop = top + rows.length * rowHeight + 12
142  const height = notesTop + notes.length * 20 + (notes.length > 0 ? 8 : 0)
143  const out: string[] = [
144    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace" font-size="13">`,
145    `<rect width="${width}" height="${height}" rx="8" fill="#121215"/>`,
146    `<text x="${pad}" y="28" fill="#e6e6ea" font-weight="700">${xml(tag)}</text>`,
147    `<text x="${width - pad}" y="28" fill="#e6e6ea" text-anchor="end">${xml(summary)}</text>`,
148  ]
149  const x0 = pad + labelWidth
150  stages.forEach((s, i) => {
151    out.push(`<text x="${x0 + i * (cell + gap) + cell / 2}" y="56" fill="#9a9aa3" font-size="11" text-anchor="middle">${xml(abbrev(s))}</text>`)
152  })
153  rows.forEach((r, j) => {
154    const y = top + j * rowHeight
155    const kind = KIND[r.kind]
156    out.push(`<text x="${pad}" y="${y + 14}" fill="${HEX[kind.color ?? ''] ?? '#9a9aa3'}">${xml(kind.mark)}</text>`)
157    out.push(`<text x="${pad + 20}" y="${y + 14}" fill="#e6e6ea">${xml(clip(`${r.n} ${r.title}`, 32))}</text>`)
158    const w = r.w
159    if (w && w.stages.length > 0) {
160      stageStatesOf(w).forEach((s, i) => {
161        const b = BLOCK[s] ?? BLOCK.pending!
162        const x = x0 + i * (cell + gap)
163        out.push(`<rect x="${x}" y="${y}" width="${cell}" height="18" rx="3" fill="${b.bg}"/>`)
164        if (b.g) out.push(`<text x="${x + cell / 2}" y="${y + 13}" fill="#121215" font-size="11" text-anchor="middle">${xml(b.g)}</text>`)
165      })
166    } else if (r.kind === 'manual' || (w && w.state === 'running')) {
167      out.push(`<text x="${x0}" y="${y + 14}" fill="#9a9aa3">${r.kind === 'manual' ? xml(r.type) : 'starting…'}</text>`)
168    }
169  })
170  notes.forEach((r, j) => {
171    const w = r.w!
172    const kind = KIND[r.kind]
173    out.push(`<text x="${pad}" y="${notesTop + j * 20 + 12}" fill="#9a9aa3" font-size="12"><tspan fill="${HEX[kind.color ?? ''] ?? '#9a9aa3'}">${xml(kind.mark)}</tspan> ${r.n} ${xml(currentStage(w) || w.state)}: ${xml(clip(w.note, 90))}</text>`)
174  })
175  out.push('</svg>')
176  return out.join('')
177}
178
179/** The band's rows: the entries still in flow — running, at a gate, or blocked. */
180export const liveRows = (rows: Row[]) =>
181  rows.filter(r => r.w && (r.kind === 'running' || r.kind === 'gate' || r.kind === 'blocked'))
182
183/** The band's "also": the entries off the band, counted by kind, as `✓ 12 · ◇ 2 · ✎ 1`. */
184export const alsoLine = (rows: Row[]) => {
185  const off = rows.filter(r => liveRows([r]).length === 0)
186  return (['done', 'review', 'running', 'manual', 'waiting'] as const)
187    .map(k => [k, off.filter(r => r.kind === k).length] as const)
188    .filter(([, n]) => n > 0)
189    .map(([k, n]) => `${KIND[k].mark} ${n}`)
190    .join(' · ')
191}
192
193/** The band's live rows within the rows it may take, and how many did not fit. */
194export const bandRows = (rows: Row[], maxRows: number) => {
195  const live = liveRows(rows)
196  // One row for the header, and one for "+n more" when it is needed.
197  const room = Math.max(1, maxRows - 1)
198  return live.length <= room ? { shown: live, more: 0 } : { shown: live.slice(0, room - 1), more: live.length - (room - 1) }
199}
200
types/index.d.ts 40 lines
1/** One entry of the plan, as get_plan_items answered it and transition moved it since. */
2export type PlanEntry = {
3  id: string
4  n: number
5  title: string
6  type: string
7  status: string
8}
9
10export type Plan = { tag: string; entries: PlanEntry[] }
11
12export type WorkerState = 'running' | 'gate' | 'pr' | 'blocked' | 'done-before' | 'stopped'
13
14/** One execute-plan sub-agent and the delivery-flow run it reported. */
15export type Worker = {
16  agentId: string
17  entryId: string
18  n: number
19  title: string
20  state: WorkerState
21  note: string
22  flow: string
23  /** The ids the surfaces answered for the run in hand, one per surface; none when no surface confirmed it. */
24  runIds: string[]
25  stages: string[]
26  stageStatus: string[]
27  runStatus: string
28}
29
30declare module 'claude-code' {
31  interface PluginState {
32    'backlog-tools': {
33      plan: Plan | null
34      workers: Worker[]
35      /** A nested agent (a flow-runner, a phase runner) → the agent that spawned it. */
36      parents: Record<string, string>
37    }
38  }
39}
40