SLOPSHOPPER

pm-band

pm plan steps above the prompt; steps, backlog and dependency graph in a pane

panebandguardcommandprocesstimer
★ 1v0.1.0no licenseupdated 2026-10-21iMUngHee/dotfiles/claude/mods/pm-band
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · pm-band
│ ┃ pm ✕ › fix the failing auth test and add an audit log call │ ┃ 1: steps 2: backlog 3: graph │ ┃ ━━━━━━━━─────────────────────────────────… ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ No plan is bound to this session. ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ 1 2 3 tabs · ↑↓ scroll ⏺ 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 │ │ › /pm │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · pm
1: steps 2: backlog 3: graph ━━━━━━━━────────────────────────────────────────────── No plan is bound to this session. 1 2 3 tabs · ↑↓ scroll
README

dotfiles

Personal configuration files managed via ~/.config/ and synced with git.

What's tracked

DirectoryToolKey files
ai/Shared (Claude + Codex)PERSONAL.md, guardrails.md, rules/, memory/, skills/, AGENTS.manifest
claude/Claude CodeCLAUDE.md, DEVGUARD.md, settings.json, hooks/, agents/, commands/, skills/ (Claude-only)
codex/Codex CLIconfig.toml.template, skills/ (Codex-only), scripts/
notifier/Shared AI notifiermacOS Swift app, Linux Go daemon, Go sender, shared icon
ghostty/Ghosttyconfig, shaders/ (cursor animation)
aerospace/AeroSpace (macOS)aerospace.toml (shipped default trimmed to digit workspaces so Option stays free for terminal Meta keys; float rules, Omarchy gaps)
brave/Brave Originvimium-options.json (Vimium export; restore by hand from its Options page when Brave Sync has not carried it over)
nvim/Neoviminit.lua, lua/plugins/
tmux/tmuxtmux.conf, scripts/, status/
zsh/Zsh.zshrc, custom/plugins/
homebrew/Homebrew BundleBrewfile, bootstrap.sh (macOS package set + shell env)
arch/Arch Linux / Omarchypackages.sh (pacman + AUR, the Brewfile mapping), bootstrap.sh (packages + mise + shell env)
lib/Shared bootstrapshell-env.sh (~/.zshenv ZDOTDIR + oh-my-zsh, used by both Unix package layers)
windows/Native Windowsbootstrap.ps1, packages.ps1 (winget), profile.ps1, starship.toml, terminal/, notifier/, Cowork skill packaging
.ideavimrcIdeaVim (JetBrains)Standalone file

AI assistant 3-tier layout

ai/ is the single source of truth for tool-agnostic content (rules, memory, most skills). claude/ and codex/ hold per-tool deploy logic and tool-only files. notifier/ is shared runtime infrastructure for Claude/Codex desktop notifications. The orchestrator at ai/scripts/bootstrap.sh calls each tool's bootstrap. See ai/README.md, claude/README.md, codex/README.md.

Everything else under ~/.config/ is gitignored. See .gitignore for the allowlist.

Machine-local settings

Anything true of one machine and not another stays out of the tracked files. Each config loads an optional private file last, so it overrides without being edited into the shared one:

ConfigHook in the tracked fileMachine-local file
zshsource $ZDOTDIR/private.shzsh/private.sh
ghosttyconfig-file = ?"…/private.conf"ghostty/private.conf
tmuxif-shell '[ -r … ]' 'source-file …'tmux/private.conf
nvimplugins/99_private.lua → require("private.plugins")nvim/lua/private/plugins.lua

All four are absent by default and silent when missing, so a fresh clone works with none of them. On Omarchy they are where the theme wiring lives, which is why macOS keeps Catppuccin while that machine follows the system theme.

One case the seam cannot cover: Omarchy's display text size slider rewrites font-size in ghostty/config at a path it hardcodes, so moving the line out would make the slider silently do nothing. That one line is normalized on its way into the index by the clean filter in lib/git-filter-machine-local.sh (wired in .gitattributes, registered by ai/scripts/bootstrap.sh) — the working tree keeps this monitor's size and git never sees it. When git rewrites the file (a pull that changes it, a reset, git stash), the smudge side of the same filter puts the size back from the slider's record in ~/.config/omarchy/shell.toml, using the px-to-pt formula it reads out of the installed omarchy-display-text-size. If that formula ever changes, the smudge leaves the stored 16 in place and says so, and ai/lib/git-filter-machine-local.test.mjs fails until the filter is updated. The smudge is registered by bootstrap, which the post-merge hook runs after a pull, so the pull that first brings it in still checks files out with the old cat. That only matters if the same pull also changes ghostty/config; then move the slider once. The same filter drops a # >>> machine-local … # <<< machine-local block whole; aerospace/aerospace.toml keeps its work-machine float rules there, since AeroSpace has no include to put them in a private file.

Bootstrap registers the filter as required, with a smudge beside it: required covers checkouts too, and with no smudge to run every checkout of a filtered file aborts with smudge filter machine-local failed. A machine that ran bootstrap after c240add but before 942bb12 has required without the smudge, so the pull that brings the fix can stop there. Run git -C ~/.config config filter.machine-local.smudge cat once, then pull again.

Submodules

PathRepo
zsh/custom/plugins/zsh-autosuggestionszsh-users/zsh-autosuggestions
zsh/custom/plugins/zsh-history-substring-searchzsh-users/zsh-history-substring-search
zsh/custom/plugins/zsh-syntax-highlightingzsh-users/zsh-syntax-highlighting
zsh/custom/plugins/fzf-tabaloxaf/fzf-tab
ghostty/shaderssahaj-b/ghostty-cursor-shaders

Setup

macOS / Linux

git clone --recurse-submodules <repo> ~/.config
~/.config/bootstrap.sh   # packages + shell env, then deploys Claude + Codex config

bootstrap.sh picks the package layer from the machine, then hands off to the same ai/scripts/bootstrap.sh in every case:

MachinePackage layerSource of claude / codex
macOShomebrew/bootstrap.sh → brew bundleHomebrew casks
Arch / Omarchyarch/bootstrap.sh → pacman + AURmise (~/.config/mise/config.toml, machine-local)
Linux with Homebrew, no pacmanhomebrew/bootstrap.shHomebrew

On Omarchy the package step uses omarchy-pkg-add / omarchy-pkg-aur-add when they exist, so packages installed here look the same as ones added through the Omarchy menu. arch/packages.sh --dry-run prints the plan without installing; --skip-optional leaves out desktop apps and AUR.

~/.config is usually not empty on a fresh Omarchy install — ghostty/, nvim/ and tmux/ already exist. The tracked versions here replace them; move the originals aside first if you want them back.

Windows

winget install --id Git.Git --exact
git clone --recurse-submodules <repo> $HOME\.config
pwsh -File $HOME\.config\windows\bootstrap.ps1   # winget packages + shell/terminal, then the SAME ai/scripts/bootstrap.sh under Git Bash

Requires Developer Mode (Settings > System > For developers) so the deploy can create symlinks unelevated. windows/bootstrap.ps1 replaces bootstrap.sh only at the package layer — the Claude/Codex deploy is delegated to ai/scripts/bootstrap.sh verbatim, so there is one implementation of the 3-tier merge, not two. See windows/README.md.

For per-tool details: ai/, claude/, codex/, windows/.

Source 6 files
hooks/register.tsx 658 lines
1// pm-band: the session's pm plan as one line above the prompt, and a /pm pane with
2// its steps, the backlog and the backlog's dependency graph. Read-only: every
3// fact comes from the pm CLIs; nothing here writes a plan, a task or a pointer.
4//
5// I/O happens in events and timers only; ui.render reads $.state and nothing else.
6
7import { atom, read, update } from 'claude-code'
8import type { EngineInterface as Engine, On, RenderElement, RenderInput } from 'claude-code'
9
10import type { BacklogState, BandState, PlanView, Tab } from '../types'
11import type { GraphProps } from './graph'
12import {
13  currentOf,
14  gaugeOf,
15  graphOf,
16  groupsOf,
17  listingOf,
18  meterOf,
19  planFile,
20  resolvedOf,
21  stepsOf,
22} from './plan'
23import type { Listing, Run } from './plan'
24
25export const PANE = 'pm'
26const REFRESH_DEBOUNCE_MS = 300
27// How often the session id is compared; see watchSession.
28const SESSION_WATCH_MS = 1_000
29// A row is cut at the pane edge anyway; the cap keeps a big backlog inside the
30// engine's 100,000 characters of text per drawing.
31const TITLE_CHARS = 200
32
33const band = atom({ plugin: 'pm-band', key: 'band' } as const, {
34  sessionId: '',
35  view: null,
36  error: null,
37})
38const backlog = atom({ plugin: 'pm-band', key: 'backlog' } as const, {
39  sessionId: '',
40  listing: null,
41  error: null,
42  isOutside: false,
43})
44const tab = atom({ plugin: 'pm-band', key: 'tab' } as const, 'steps')
45const selected = atom({ plugin: 'pm-band', key: 'selected' } as const, null)
46
47type Paths = { resolver: string; tsx: string; pm: string }
48
49async function pathsOf($: Engine): Promise<Paths> {
50  // $.process.run takes argv, no shell: `~` would reach the child unexpanded.
51  // Windows: HOME is only set by a shell profile, so a session started without one
52  // (the desktop app) has USERPROFILE alone.
53  const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? ''
54  const pm = `${home}/.config/ai/skills/pm-roadmap`
55  return {
56    resolver: `${home}/.config/ai/lib/worktree.mjs`,
57    // tsx's own entry run by node, not node_modules/.bin/tsx: on Windows that is a
58    // shell script and its .cmd twin, and neither starts without a shell.
59    tsx: `${pm}/node_modules/tsx/dist/cli.mjs`,
60    pm: `${pm}/pm-roadmap.ts`,
61  }
62}
63
64async function run(
65  $: Engine,
66  argv: string[],
67  init: { cwd?: string; env?: Record<string, string>; timeoutMs: number },
68): Promise<Run> {
69  try {
70    return await $.process.run(argv, init)
71  } catch (error) {
72    return { exitCode: -1, stdout: '', stderr: error instanceof Error ? error.message : String(error) }
73  }
74}
75
76// Module state: a reload starts it over, as it does $.clock timers.
77// Bumped whenever the session id changes under the process (/clear, /resume,
78// /branch): a refresh that started under an older generation is dropped.
79let generation = 0
80let isRefreshing = false
81let isDirty = false
82let pending: { cancel: () => void } | null = null
83// The id watchSession last saw.
84let sessionSeen = ''
85
86async function refreshOnce($: Engine): Promise<void> {
87  const started = generation
88  const sessionId = await $.session.id()
89  const cwd = await $.session.cwd()
90  const paths = await pathsOf($)
91  const resolved = resolvedOf(
92    await run($, ['node', paths.resolver, 'resolve-session', '--root', cwd, '--tool', 'claude'], {
93      env: { PM_SESSION_TOOL: 'claude', PM_SESSION_ID: sessionId },
94      timeoutMs: 10_000,
95    }),
96  )
97  let view: PlanView | null = null
98  let error: string | null = null
99  // Every variant reports it, so the backlog is reachable from all of them —
100  // a terminal plan and a resolver error included. See Resolved in plan.ts.
101  const mainRoot = resolved.mainRoot
102  if (resolved.kind === 'error') error = resolved.reason
103  if (resolved.kind === 'none') {
104    view = { kind: 'none' }
105  }
106  if (resolved.kind === 'plan') {
107    try {
108      const content = await $.fs.read(planFile(resolved.mainRoot, resolved.plan))
109      view = {
110        kind: 'plan',
111        status: resolved.status,
112        id: resolved.id,
113        title: resolved.title,
114        plan: resolved.plan,
115        steps: stepsOf(content),
116      }
117    } catch (failure) {
118      error = `plan unreadable: ${failure instanceof Error ? failure.message : String(failure)}`
119    }
120  }
121  const isPaneOpen = (await $.ui.panes()).some(one => one.id === PANE)
122  // `outside`: no repository, so no backlog: said at once rather than left `loading…`.
123  let listing: Listing | { error: string } | 'outside' | null = null
124  if (isPaneOpen && !mainRoot) listing = resolved.kind === 'error' ? { error: resolved.reason } : 'outside'
125  if (isPaneOpen && mainRoot) {
126    listing = listingOf(
127      await run($, ['node', paths.tsx, paths.pm, 'list', '--json', '--all'], {
128        cwd: mainRoot,
129        env: { PM_ROOT: mainRoot },
130        timeoutMs: 15_000,
131      }),
132    )
133  }
134  if (started !== generation || sessionId !== (await $.session.id())) return
135  await update($, band, (prev): BandState =>
136    error === null
137      ? { sessionId, view, error: null }
138      : { sessionId, view: prev.sessionId === sessionId ? prev.view : null, error },
139  )
140  if (listing !== null) {
141    const next = listing
142    await update($, backlog, (prev): BacklogState =>
143      next === 'outside'
144        ? { sessionId, listing: null, error: null, isOutside: true }
145        : 'error' in next
146          ? { sessionId, listing: prev.sessionId === sessionId ? prev.listing : null, error: next.error, isOutside: false }
147          : { sessionId, listing: next, error: null, isOutside: false },
148    )
149  }
150}
151
152async function refresh($: Engine): Promise<void> {
153  if (isRefreshing) {
154    isDirty = true
155    return
156  }
157  isRefreshing = true
158  try {
159    do {
160      isDirty = false
161      await refreshOnce($)
162    } while (isDirty)
163  } finally {
164    isRefreshing = false
165  }
166}
167
168function soon($: Engine): void {
169  pending?.cancel()
170  pending = $.clock.after(REFRESH_DEBOUNCE_MS, () => {
171    pending = null
172    void refresh($)
173  })
174}
175
176/** /pm and the band's controls: open the pane (on `shown`, when given) and read the backlog. */
177async function openPane($: Engine, shown?: Tab): Promise<void> {
178  if (shown !== undefined) await update($, tab, () => shown)
179  await $.ui.open({ id: PANE, title: 'pm', focus: true })
180  soon($)
181}
182
183async function switched($: Engine): Promise<void> {
184  generation += 1
185  await update($, band, () => ({ sessionId: '', view: null, error: null }))
186  await update($, backlog, () => ({ sessionId: '', listing: null, error: null, isOutside: false }))
187  await update($, selected, () => null)
188}
189
190// /clear, /resume and /branch change the id under the process. classic.SessionStart
191// said so for all three, but on a machine with managed settings (and in Team and
192// Enterprise organizations) the built-in cc-plugin-sec-default runs outermost and
193// sends every classic.* event past the plugins a person installs
194// (next.to(e, "append")): a classic hook here never runs, and the engine reports
195// it as skipped. session.end still fires for /clear and resume, but before the id
196// changes and never for /branch. So the id is compared on a timer.
197async function watchSession($: Engine): Promise<void> {
198  const sessionId = await $.session.id()
199  if (sessionId === sessionSeen) return
200  sessionSeen = sessionId
201  await switched($)
202  soon($)
203}
204
205export function register(on: On): void {
206  on('session.start', async ($, e, next) => {
207    await $.command.register({
208      name: PANE,
209      description: 'Show the plan steps, the backlog and its dependency graph',
210      immediate: true,
211    })
212    const result = await next(e)
213    sessionSeen = await $.session.id()
214    $.clock.every(SESSION_WATCH_MS, () => void watchSession($))
215    soon($)
216    return result
217  })
218
219  // The hooks below only observe; if one fails, .catch hands back what next settled
220  // to (or runs it once when it had not run), so a failure never blocks or repeats work.
221  on('tool.call', async ($, e, next) => {
222    const result = await next(e)
223    soon($)
224    return result
225  }).catch(($, e, next) => next(e))
226
227  on('turn.complete', async ($, e, next) => {
228    const result = await next(e)
229    soon($)
230    return result
231  })
232
233  on('command.run', { command: PANE }, async $ => {
234    await openPane($)
235    return {}
236  }).catch(($, e, next) => next(e))
237
238  on('ui.message', { requestId: PANE }, async ($, e) => {
239    const data = e.data as { selected?: unknown } | null
240    const id = typeof data?.selected === 'string' ? data.selected : null
241    await update($, selected, () => id)
242    return {}
243  })
244
245  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
246    if (e.props.hasSurvey) return next(e)
247    const state = await read($, band)
248    const below = await next(e)
249    const line = bandLine($, e, state)
250    if (line === null) return below
251    const { Box } = $.ui.resolve(e)
252    return (
253      <Box flexDirection="column">
254        {line}
255        {below}
256      </Box>
257    )
258  })
259
260  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
261    const state = await read($, band)
262    const list = await read($, backlog)
263    const shown = await read($, tab)
264    const pick = await read($, selected)
265    return paneOf($, e, { state, list, shown, pick })
266  })
267}
268
269function bandLine($: Engine, e: RenderInput<'AbovePrompt'>, state: BandState): RenderElement | null {
270  const { Box, Text, Button } = $.ui.resolve(e)
271  const view = state.view
272  if (state.error !== null && view === null) {
273    return (
274      <Text dimColor wrap="truncate-end">
275        ⚠ plan: {state.error}
276      </Text>
277    )
278  }
279  if (view === null) return null
280  if (view.kind === 'none') {
281    return (
282      <Text dimColor wrap="truncate-end">
283        ○ no plan
284      </Text>
285    )
286  }
287  const done = view.steps.filter(step => step.isDone).length
288  const current = currentOf(view.steps)
289  const meter = meterOf(view.steps)
290  return (
291    <Box flexDirection="row">
292      <Box flexShrink={1}>
293        <Text wrap="truncate-end">
294          <Text color={view.status === 'active' ? 'warning' : 'inactive'}>{view.status === 'active' ? '▶' : '⚙'}</Text>{' '}
295          <Text bold color="claude">
296            {view.id}
297          </Text>
298          {'  '}
299          {/* The current step is hollow like the steps ahead, so the filled ones count what is done. */}
300          {meter.map(segment => (
301            <Text
302              color={segment === 'done' ? 'success' : segment === 'current' ? 'warning' : 'subtle'}
303              bold={segment === 'current'}
304            >
305              {segment === 'done' ? '▰' : '▱'}
306            </Text>
307          ))}
308          {meter.length > 0 ? ' ' : ''}
309          <Text dimColor>
310            {done}/{view.steps.length}
311          </Text>
312          {current ? `  ${current.text}` : ''}
313          {state.error !== null ? <Text dimColor> ⚠</Text> : ''}
314        </Text>
315      </Box>
316      <Box flexGrow={1} />
317      {/* The way into /pm from the band, pinned to its right edge: each opens the pane on its tab. */}
318      <Box flexDirection="row" flexShrink={0} columnGap={2} marginLeft={2}>
319        <Button key="band-steps" label="steps" plain dimColor onPress={() => openPane($, 'steps')} />
320        <Button key="band-graph" label="graph" plain dimColor onPress={() => openPane($, 'graph')} />
321      </Box>
322    </Box>
323  )
324}
325
326const TABS: { tab: Tab; label: string; hotkey: string }[] = [
327  { tab: 'steps', label: 'steps', hotkey: '1' },
328  { tab: 'backlog', label: 'backlog', hotkey: '2' },
329  { tab: 'graph', label: 'graph', hotkey: '3' },
330]
331const TAB_GAP = 3
332
333function paneOf(
334  $: Engine,
335  e: RenderInput<'Pane'>,
336  { state, list, shown, pick }: { state: BandState; list: BacklogState; shown: Tab; pick: string | null },
337): RenderElement {
338  const { Box, Text } = $.ui.resolve(e)
339  // The pane frame is the engine's; the content keeps a column clear on each side.
340  const width = Math.max(20, e.props.bodyColumns - 2)
341  const isGraph = shown === 'graph' && hasClient(e)
342  // Seated inline above the prompt the pane shows about eleven rows: spacing goes first.
343  const isTight = e.props.placement === 'inline'
344  const body =
345    shown === 'steps'
346      ? stepsBody($, e, state, width, isTight)
347      : isGraph
348        ? graphBody($, e, list, state, pick)
349        : backlogBody($, e, list, state, width)
350  return (
351    <Box flexDirection="column" paddingX={1}>
352      {tabStrip($, e, shown, width)}
353      {/* The drawing keeps the row: its own margins already part it from the tabs. */}
354      {isGraph || isTight ? '' : <Text> </Text>}
355      {body}
356      {/* Steps and backlog have no keys of their own, so their bar names the tabs' and the
357          scroll's; the graph's line under the drawing is its bar. Text, not Buttons: the
358          tab strip already holds the digit hotkeys, and a second holder would clash. */}
359      {isGraph || e.surface !== 'terminal' ? (
360        ''
361      ) : (
362        <Box marginTop={1}>
363          <Text dimColor wrap="truncate-end">
364            1 2 3 tabs · ↑↓ scroll
365          </Text>
366        </Box>
367      )}
368    </Box>
369  )
370}
371
372/**
373 * The tabs. On the terminal, plain hotkey Buttons over a rule whose segment under
374 * the shown tab is the accent's heavy line; elsewhere Buttons are native, so the
375 * shown one is the primary instead.
376 */
377function tabStrip($: Engine, e: RenderInput<'Pane'>, shown: Tab, width: number): RenderElement {
378  const { Box, Text, Button } = $.ui.resolve(e)
379  const pressed = (one: Tab) => () => update($, tab, () => one)
380  if (e.surface !== 'terminal') {
381    return (
382      <Box flexDirection="row" columnGap={1}>
383        {TABS.map(one => (
384          <Button
385            key={`tab-${one.tab}`}
386            label={one.label}
387            hotkey={one.hotkey}
388            variant={one.tab === shown ? 'primary' : 'secondary'}
389            onPress={pressed(one.tab)}
390          />
391        ))}
392      </Box>
393    )
394  }
395  // A plain Button draws `1: steps`, so that is how wide its segment of the rule is.
396  const widths = TABS.map(one => `${one.hotkey}: ${one.label}`.length)
397  const used = widths.reduce((sum, one) => sum + one, 0) + TAB_GAP * (TABS.length - 1)
398  return (
399    <Box flexDirection="column">
400      <Box flexDirection="row" columnGap={TAB_GAP}>
401        {TABS.map(one => (
402          <Button
403            key={`tab-${one.tab}`}
404            label={one.label}
405            hotkey={one.hotkey}
406            plain
407            dimColor={one.tab !== shown}
408            onPress={pressed(one.tab)}
409          />
410        ))}
411      </Box>
412      <Text wrap="truncate-end">
413        {TABS.map((one, index) => (
414          <Text>
415            <Text color={one.tab === shown ? 'claude' : 'subtle'}>{(one.tab === shown ? '━' : '─').repeat(widths[index]!)}</Text>
416            {index < TABS.length - 1 ? <Text color="subtle">{'─'.repeat(TAB_GAP)}</Text> : ''}
417          </Text>
418        ))}
419        <Text color="subtle">{'─'.repeat(Math.max(0, width - used))}</Text>
420      </Text>
421    </Box>
422  )
423}
424
425/** The graph is a Client; VS Code and mobile have none, so they get the list. */
426function hasClient(e: RenderInput<'Pane'>): boolean {
427  return e.surface === 'terminal' || e.surface === 'desktop'
428}
429
430function stepsBody(
431  $: Engine,
432  e: RenderInput<'Pane'>,
433  state: BandState,
434  width: number,
435  isTight: boolean,
436): RenderElement {
437  const { Box, Text } = $.ui.resolve(e)
438  const view = state.view
439  if (view === null || view.kind === 'none') {
440    return <Text dimColor>{state.error !== null ? `⚠ plan: ${state.error}` : 'No plan is bound to this session.'}</Text>
441  }
442  const done = view.steps.filter(step => step.isDone).length
443  const current = currentOf(view.steps)
444  const gauge = gaugeOf(done, view.steps.length, width)
445  return (
446    <Box flexDirection="column">
447      <Box flexDirection="row">
448        <Box flexShrink={1}>
449          <Text wrap="truncate-end">
450            <Text bold color="claude">
451              {view.id}
452            </Text>
453            {'  '}
454            <Text backgroundColor={view.status === 'active' ? 'success' : 'inactive'} color="inverseText" bold>
455              {` ${view.status} `}
456            </Text>
457          </Text>
458        </Box>
459        <Box flexGrow={1} />
460        <Box flexShrink={0} marginLeft={2}>
461          <Text dimColor>
462            {done}/{view.steps.length} · {gauge.pct}%
463          </Text>
464        </Box>
465      </Box>
466      <Text dimColor wrap="truncate-end">
467        {view.title}
468      </Text>
469      <Text wrap="truncate-end">
470        <Text color="success">{'━'.repeat(gauge.filled)}</Text>
471        <Text color="subtle">{'─'.repeat(gauge.rest)}</Text>
472      </Text>
473      {isTight ? '' : <Text> </Text>}
474      {current ? (
475        // The one focal card, above the list: an inline pane shows about eleven rows,
476        // and the step being worked on has to be among them, whole.
477        <Box flexDirection="column" borderStyle="round" borderColor="warning" paddingX={1}>
478          <Text dimColor bold>
479            NOW
480          </Text>
481          <Text wrap="wrap" bold color="warning">
482            ▶ {current.n}. {current.text}
483          </Text>
484        </Box>
485      ) : (
486        ''
487      )}
488      {view.steps.map(step => (
489        <Box paddingLeft={2}>
490          <Text
491            wrap="truncate-end"
492            dimColor={step.isDone}
493            bold={step === current}
494            color={step === current ? 'warning' : undefined}
495          >
496            <Text color={step.isDone ? 'success' : undefined}>{step.isDone ? '✓' : step === current ? '▶' : '○'}</Text>{' '}
497            {step.n}. {step.text}
498          </Text>
499        </Box>
500      ))}
501    </Box>
502  )
503}
504
505function currentPlanOf(state: BandState): string | undefined {
506  return state.view?.kind === 'plan' ? state.view.plan : undefined
507}
508
509/** A tab with nothing to list: what is missing in bold, and what would fill it, dim. */
510function emptyOf($: Engine, e: RenderInput<'Pane'>, title: string, hint: string): RenderElement {
511  const { Box, Text } = $.ui.resolve(e)
512  return (
513    <Box flexDirection="column">
514      <Text bold>{title}</Text>
515      <Text dimColor wrap="wrap">
516        {hint}
517      </Text>
518    </Box>
519  )
520}
521
522const EMPTY_HINT = 'Items show up here once pm adds them (/pm-roadmap); untriaged ones wait in the inbox.'
523
524/** The backlog and graph tabs before or without a listing: outside a repository, failed, or still reading. */
525function unlistedOf($: Engine, e: RenderInput<'Pane'>, list: BacklogState): RenderElement {
526  const { Text } = $.ui.resolve(e)
527  if (list.isOutside) {
528    return emptyOf($, e, 'No pm backlog here.', '/pm reads the backlog of the git repository this session runs in; this one runs outside any.')
529  }
530  if (list.error !== null) return <Text dimColor>⚠ backlog: {list.error}</Text>
531  return <Text dimColor>loading…</Text>
532}
533
534function backlogBody(
535  $: Engine,
536  e: RenderInput<'Pane'>,
537  list: BacklogState,
538  state: BandState,
539  width: number,
540): RenderElement {
541  const { Box, Text } = $.ui.resolve(e)
542  if (list.listing === null) {
543    return unlistedOf($, e, list)
544  }
545  const groups = groupsOf(list.listing, currentPlanOf(state))
546  if (groups.length === 0) {
547    return (
548      <Box flexDirection="column">
549        {emptyOf($, e, 'The backlog is empty.', EMPTY_HINT)}
550        {list.listing.inbox > 0 ? <Text dimColor>inbox · {list.listing.inbox} awaiting triage</Text> : ''}
551      </Box>
552    )
553  }
554  // P0 and P1 stand out on the warning fill; P2 is the plain middle; the rest step back.
555  const chipOf = (priority: string) =>
556    /^P[01]$/.test(priority) ? (
557      <Text backgroundColor="warning" color="inverseText" bold>{` ${priority} `}</Text>
558    ) : priority === 'P2' ? (
559      <Text bold>{` ${priority} `}</Text>
560    ) : (
561      <Text dimColor>{` ${priority} `}</Text>
562    )
563  return (
564    <Box flexDirection="column">
565      {groups.map((group, index) => {
566        const count = String(group.rows.length)
567        return (
568          <Box flexDirection="column" marginTop={index === 0 ? 0 : 1}>
569            <Text wrap="truncate-end">
570              <Text bold color="claude">
571                {group.key}
572              </Text>
573              <Text color="subtle">{` ${'─'.repeat(Math.max(2, width - group.key.length - count.length - 2))} `}</Text>
574              <Text dimColor>{count}</Text>
575            </Text>
576            {group.rows.map(row => (
577              <Text wrap="truncate-end" dimColor={row.isBlocked && !row.isCurrent}>
578                {/* The accent is the cursor's alone; a blocked mark stays as dim as its row. */}
579                {row.isCurrent ? <Text color="claude">▌</Text> : row.isBlocked ? '◌' : ' '}{' '}
580                {chipOf(row.priority)}{' '}
581                <Text bold={row.isCurrent}>{row.id}</Text>
582                {/* What blocks the item before its title: the row is cut at the edge, and the
583                    reason is the short, telling part. */}
584                {row.blockedBy !== undefined ? (
585                  <Text color="warning">
586                    {row.blockedByReason === 'order' ? `  ⤷ after ${row.blockedBy}` : `  ⤷ needs ${row.blockedBy}`}
587                  </Text>
588                ) : (
589                  ''
590                )}
591                <Text dimColor>
592                  {'  '}
593                  {row.title.length > TITLE_CHARS ? `${row.title.slice(0, TITLE_CHARS - 1)}…` : row.title}
594                </Text>
595              </Text>
596            ))}
597          </Box>
598        )
599      })}
600      {list.listing.inbox > 0 ? (
601        <Box marginTop={1}>
602          <Text dimColor>inbox · {list.listing.inbox} awaiting triage</Text>
603        </Box>
604      ) : (
605        ''
606      )}
607      {list.error !== null ? <Text dimColor>⚠ {list.error}</Text> : ''}
608    </Box>
609  )
610}
611
612/** The picked node's detail line: the item's task, priority, title and needs, or the task. */
613function detailOf(list: BacklogState, pick: string | null): string | null {
614  if (pick === null || list.listing === null) return null
615  const chosen = [...list.listing.eligible, ...list.listing.blocked].find(item => item.id === pick)
616  if (!chosen) return `task ${pick.replace(/^#/, '')}`
617  const needs = chosen.dependsOn.length > 0 ? ` · needs ${chosen.dependsOn.join(', ')}` : ''
618  return `${chosen.key}/${chosen.id} · [${chosen.priority}] ${chosen.title}${needs}`
619}
620
621function graphBody(
622  $: Engine,
623  e: RenderInput<'Pane'>,
624  list: BacklogState,
625  state: BandState,
626  pick: string | null,
627): RenderElement {
628  const { Text } = $.ui.resolve(e)
629  if (list.listing === null) {
630    return unlistedOf($, e, list)
631  }
632  const graph: GraphProps = graphOf(list.listing, currentPlanOf(state))
633  // Nothing to draw: say so in words, not with an empty canvas.
634  if (graph.nodes.length === 0) return emptyOf($, e, 'The backlog is empty.', EMPTY_HINT)
635  const detail = detailOf(list, pick)
636  const { Box, Client } = $.ui.resolve(e as RenderInput<'Pane'> & { surface: 'terminal' })
637  // What the tab strip and the line under the drawing leave of the body.
638  const height = Math.max(5, e.props.scroll.bodyRows - 3)
639  // The desktop sets text in a proportional face: the Client places each run at
640  // its cell instead of drawing rows of spaced text (see graph.tsx).
641  const props: GraphProps = e.surface === 'terminal' ? graph : { ...graph, isPlaced: true, rows: height }
642  return (
643    <Box flexDirection="column">
644      <Client key="graph" module="./graph.tsx" props={props} width="100%" height={height} />
645      {detail !== null ? (
646        <Text wrap="truncate-end">
647          <Text color="claude">◆ </Text>
648          <Text bold>{detail}</Text>
649        </Text>
650      ) : (
651        <Text dimColor wrap="truncate-end">
652          click a node · drag it to move · drag empty space or shift+arrows to pan · + − zoom · 0 fit
653        </Text>
654      )}
655    </Box>
656  )
657}
658
hooks/graph.tsx 426 lines
1// The /pm graph tab's surface module: lays the backlog graph out on the drawing
2// thread, frame by frame, and takes the pointer and keys. It has no `$`; a pick
3// reaches the hooks module as `ui.message` data ({ selected }).
4//
5// The layout is unbounded: nodes take the room their forces give them, and the
6// region is a camera over it (`camera` is the world point at its top-left,
7// `zoom` the spacing scale). Spacing is not `world`'s to set — unbounded, the
8// layout's `k` is the fixed SPACING in layout.ts. What `world` gives is the
9// centre the weak pull aims at, the starting temperature, and the first
10// camera. Reach for SPACING, not for `world`, to spread nodes further apart.
11// Until the person moves the camera it fits the settled graph (zoom at most 1).
12// Drag a node to move it, drag empty space to pan, shift+arrows pan, + and -
13// zoom, 0 fits everything. A drag moves the node's neighbours only, so the rest
14// of the graph holds still.
15//
16// Two ways to put the cells on screen. The terminal's text is a cell grid, so
17// each row is one Text. Elsewhere (the desktop) text is set in a proportional
18// face and a row of spaces does not line up; there `isPlaced` puts every run of
19// glyphs in its own Box at its cell (`position: absolute`), so positions hold
20// whatever the face.
21
22import type { ClientModule, ClientSurface, Color } from 'claude-code'
23
24import { isSettled, placed, startTemperature, tick } from './layout'
25import type { Layout, Point, Positions, Size } from './layout'
26import type { Graph, GraphNode } from './plan'
27import { nodeAt, rasterOf } from './raster'
28import type { Tone } from './raster'
29
30/**
31 * `rows`, with `isPlaced`: the rows to lay out in. The desktop sizes a Client's
32 * region to what it draws rather than to its `height`, so the region it reports
33 * starts at the one row of `loading…` and stays there; the hooks module names
34 * the rows instead.
35 */
36export type GraphProps = Graph & { isPlaced?: boolean; rows?: number }
37
38type GraphState = {
39  /** The graph as last handed in, and a key of its shape to spot a new one. */
40  graph: GraphProps
41  shape: string
42  /** The region on screen; 0 by 0 until the first layout. */
43  size: Size
44  /**
45   * The frame the layout is centred and seeded in — the region, or more for a
46   * big graph. Not a boundary: nodes may settle outside it, which is what the
47   * camera is for.
48   */
49  world: Size
50  layout: Layout
51  camera: Point
52  zoom: number
53  isRunning: boolean
54  /** The nodes the running layout may move; null: all of them. */
55  active: string[] | null
56  /** Whether the person has moved the camera; until then it follows the graph. */
57  isCameraSet: boolean
58  pinned: string[]
59  drag: string | null
60  /** Where a pan began: the pointer's cell and the camera then. */
61  pan: { from: Point; camera: Point } | null
62  selected: string | null
63  /** The node under a resting pointer, drawn underlined. */
64  hovered: string | null
65  /** The surface the last call was handed, for the frame timer to read. */
66  box: { surface: ClientSurface<GraphState> }
67}
68
69const FRAME_MS = 33
70const ZOOMS = [0.25, 0.5, 0.75, 1, 1.5, 2] as const
71/**
72 * Cells of world each node asks for, across and down, when sizing the frame
73 * the layout is centred and seeded in. Only that: nodes are free to settle
74 * outside it, so raising these spreads the starting positions and the first
75 * camera, not the spacing the forces settle to.
76 */
77const ROOM_ACROSS = 24
78const ROOM_DOWN = 6
79const PAN_STEP = { x: 8, y: 3 }
80
81const TONE: Record<Tone, { color?: Color; dimColor?: boolean; bold?: boolean; inverse?: boolean; underline?: boolean }> = {
82  blank: {},
83  'task-edge': { color: 'subtle', dimColor: true },
84  'dependency-edge': { color: 'warning' },
85  'order-edge': { color: 'inactive' },
86  task: { color: 'claude', bold: true },
87  eligible: { color: 'success' },
88  blocked: { color: 'warning' },
89  current: { color: 'suggestion', bold: true },
90  hovered: { bold: true, underline: true },
91  selected: { inverse: true, bold: true },
92}
93
94const shapeOf = (graph: Graph) =>
95  `${graph.nodes.map(node => `${node.id}:${node.state}`).join(',')}|${graph.edges
96    .map(edge => `${edge.from}>${edge.to}:${edge.kind}`)
97    .join(',')}`
98
99// Named rows apply once the region has columns: an unmeasured (0 by 0) mount
100// still waits on `loading…` rather than laying out in no width.
101const sizeOf = (surface: ClientSurface<GraphState>, graph: GraphProps): Size => ({
102  columns: surface.columns,
103  rows: Math.max(
104    0,
105    (graph.isPlaced && graph.rows !== undefined && surface.columns > 0 ? graph.rows : surface.rows) -
106      (graph.more > 0 ? 1 : 0),
107  ),
108})
109
110const isEmpty = (size: Size) => size.columns <= 0 || size.rows <= 0
111
112/** The world for `graph` seen through `region`: never smaller, grown with the node count. */
113function worldOf(region: Size, graph: Graph): Size {
114  if (isEmpty(region)) return { columns: 0, rows: 0 }
115  const side = Math.sqrt(graph.nodes.length)
116  return {
117    columns: Math.max(region.columns, Math.ceil(side * ROOM_ACROSS)),
118    rows: Math.max(region.rows, Math.ceil(side * ROOM_DOWN)),
119  }
120}
121
122/** The camera that shows the middle of `world` in `region` at `zoom`. */
123function centred(world: Size, region: Size, zoom: number): Point {
124  return {
125    x: (world.columns - region.columns / zoom) / 2,
126    y: (world.rows - region.rows / zoom) / 2,
127  }
128}
129
130/** World positions as the region shows them. */
131function viewed(pos: Positions, camera: Point, zoom: number): Positions {
132  return Object.fromEntries(
133    Object.entries(pos).map(([id, p]) => [id, { x: (p.x - camera.x) * zoom, y: (p.y - camera.y) * zoom }]),
134  )
135}
136
137const toWorld = (state: GraphState, x: number, y: number): Point => ({
138  x: x / state.zoom + state.camera.x,
139  y: y / state.zoom + state.camera.y,
140})
141
142/** `state` with `id` at world point `at`, its neighbours free to follow. */
143function draggedTo(state: GraphState, id: string, at: Point): GraphState {
144  return {
145    ...state,
146    // A node the person moved is theirs: the camera stops following the graph.
147    isCameraSet: true,
148    layout: {
149      pos: { ...state.layout.pos, [id]: at },
150      temperature: Math.max(state.layout.temperature, startTemperature(state.world) / 8),
151    },
152    isRunning: true,
153  }
154}
155
156/** The nodes linked to `id`: what a drag of it lets move. */
157function neighboursOf(graph: Graph, id: string): string[] {
158  const linked = graph.edges.flatMap(edge => (edge.from === id ? [edge.to] : edge.to === id ? [edge.from] : []))
159  return [...new Set(linked)]
160}
161
162/** A fresh layout for `graph` in `world`. */
163function fitted(graph: Graph, world: Size): Layout {
164  return { pos: placed(graph.nodes, graph.edges, world), temperature: startTemperature(world) }
165}
166
167/** Zoom by `by` levels (0 keeps it), keeping the region's middle where it is. */
168function zoomed(state: GraphState, by: number): GraphState {
169  const at = ZOOMS.findIndex(level => level >= state.zoom)
170  const zoom = ZOOMS[Math.min(ZOOMS.length - 1, Math.max(0, (at < 0 ? ZOOMS.indexOf(1) : at) + by))]!
171  const middle = {
172    x: state.camera.x + state.size.columns / state.zoom / 2,
173    y: state.camera.y + state.size.rows / state.zoom / 2,
174  }
175  return {
176    ...state,
177    zoom,
178    camera: { x: middle.x - state.size.columns / zoom / 2, y: middle.y - state.size.rows / zoom / 2 },
179  }
180}
181
182/** The largest zoom level (at most `cap`) at which every node fits the region, centred on them. */
183function fit(state: GraphState, cap = 2): GraphState {
184  const points = Object.values(state.layout.pos)
185  if (points.length === 0) return state
186  const left = Math.min(...points.map(p => p.x))
187  const right = Math.max(...points.map(p => p.x)) + 12
188  const top = Math.min(...points.map(p => p.y))
189  const bottom = Math.max(...points.map(p => p.y)) + 1
190  const room = Math.min(state.size.columns / Math.max(1, right - left), state.size.rows / Math.max(1, bottom - top))
191  const zoom = [...ZOOMS].reverse().find(level => level <= Math.min(room, cap)) ?? ZOOMS[0]
192  return {
193    ...state,
194    zoom,
195    camera: {
196      x: (left + right) / 2 - state.size.columns / zoom / 2,
197      y: (top + bottom) / 2 - state.size.rows / zoom / 2,
198    },
199  }
200}
201
202function frame(box: GraphState['box']): void {
203  const surface = box.surface
204  const state = surface.state
205  if (!state) return
206  const size = sizeOf(surface, state.graph)
207  const isResized = size.columns !== state.size.columns || size.rows !== state.size.rows
208  if (isResized) {
209    if (isEmpty(size)) return
210    // A resize moves the camera's view, never the nodes.
211    if (!isEmpty(state.size)) {
212      surface.setState(state.isCameraSet ? { ...state, size } : fit({ ...state, size }, 1))
213      return
214    }
215    const world = worldOf(size, state.graph)
216    surface.setState({
217      ...state,
218      size,
219      world,
220      layout: fitted(state.graph, world),
221      camera: centred(world, size, state.zoom),
222      active: null,
223      isRunning: true,
224    })
225    return
226  }
227  if (!state.isRunning || isEmpty(size)) return
228  const result = tick(state.graph.nodes, state.graph.edges, state.layout, state.world, new Set(state.pinned), {
229    active: state.active === null ? undefined : new Set(state.active),
230  })
231  const isDone = state.drag === null && isSettled(result.layout, result.energy, state.graph.nodes.length)
232  const next = { ...state, layout: result.layout, isRunning: !isDone, active: isDone ? null : state.active }
233  surface.setState(isDone && !state.isCameraSet ? fit(next, 1) : next)
234}
235
236function pick(surface: ClientSurface<GraphState>, state: GraphState, id: string | null): GraphState {
237  if (id !== state.selected) surface.post({ selected: id })
238  return { ...state, selected: id }
239}
240
241function step(nodes: readonly GraphNode[], current: string | null, by: number): string | null {
242  if (nodes.length === 0) return null
243  const at = current === null ? -1 : nodes.findIndex(node => node.id === current)
244  const next = at < 0 ? (by > 0 ? 0 : nodes.length - 1) : (at + by + nodes.length) % nodes.length
245  return nodes[next]!.id
246}
247
248/** The node under a region cell, through the camera. */
249const hitAt = (state: GraphState, x: number, y: number) =>
250  nodeAt(state.graph.nodes, viewed(state.layout.pos, state.camera, state.zoom), state.size, x, y) ?? null
251
252function started(graph: GraphProps, surface: ClientSurface<GraphState>): GraphState {
253  const box = { surface }
254  const size = sizeOf(surface, graph)
255  const world = worldOf(size, graph)
256  const state: GraphState = {
257    graph,
258    shape: shapeOf(graph),
259    size: isEmpty(size) ? { columns: 0, rows: 0 } : size,
260    world,
261    layout: isEmpty(size) ? { pos: {}, temperature: 0 } : fitted(graph, world),
262    camera: isEmpty(size) ? { x: 0, y: 0 } : centred(world, size, 1),
263    zoom: 1,
264    isRunning: !isEmpty(size),
265    active: null,
266    isCameraSet: false,
267    pinned: [],
268    drag: null,
269    pan: null,
270    selected: null,
271    hovered: null,
272    box,
273  }
274  surface.every(FRAME_MS, () => frame(box))
275  surface.onPointer(event => {
276    const now = box.surface.state
277    if (!now) return
278    if (event.type === 'down' && event.button === 'left') {
279      const id = hitAt(now, event.x, event.y)
280      const picked = pick(box.surface, now, id)
281      box.surface.setState(
282        id === null
283          ? { ...picked, pan: { from: { x: event.x, y: event.y }, camera: now.camera } }
284          : {
285              ...picked,
286              drag: id,
287              pinned: [...new Set([...now.pinned, id])],
288              active: neighboursOf(now.graph, id).filter(one => !now.pinned.includes(one)),
289              isRunning: true,
290            },
291      )
292      return
293    }
294    if (event.type === 'move' && now.drag !== null) {
295      box.surface.setState(draggedTo(now, now.drag, toWorld(now, event.x, event.y)))
296      return
297    }
298    if (event.type === 'move' && now.pan !== null) {
299      box.surface.setState({
300        ...now,
301        isCameraSet: true,
302        camera: {
303          x: now.pan.camera.x - (event.x - now.pan.from.x) / now.zoom,
304          y: now.pan.camera.y - (event.y - now.pan.from.y) / now.zoom,
305        },
306      })
307      return
308    }
309    if (event.type === 'up' && (now.drag !== null || now.pan !== null)) {
310      box.surface.setState({ ...now, drag: null, pan: null })
311      return
312    }
313    const hovered =
314      event.type === 'leave' ? null : event.type === 'move' && event.button === undefined ? hitAt(now, event.x, event.y) : now.hovered
315    if (hovered !== now.hovered) box.surface.setState({ ...now, hovered })
316  })
317  surface.onKey(event => {
318    const now = box.surface.state
319    if (!now) return
320    const dx = event.key === 'right' ? 1 : event.key === 'left' ? -1 : 0
321    const dy = event.key === 'down' ? 1 : event.key === 'up' ? -1 : 0
322    if (event.shift && (dx !== 0 || dy !== 0)) {
323      box.surface.setState({
324        ...now,
325        isCameraSet: true,
326        camera: {
327          x: now.camera.x + (dx * PAN_STEP.x) / now.zoom,
328          y: now.camera.y + (dy * PAN_STEP.y) / now.zoom,
329        },
330      })
331      return
332    }
333    if (event.key === '+' || event.key === '=') return box.surface.setState({ ...zoomed(now, 1), isCameraSet: true })
334    if (event.key === '-' || event.key === '_') return box.surface.setState({ ...zoomed(now, -1), isCameraSet: true })
335    if (event.key === '0') return box.surface.setState({ ...fit(now), isCameraSet: true })
336    const by = dx + dy
337    if (by !== 0) box.surface.setState(pick(box.surface, now, step(now.graph.nodes, now.selected, by)))
338  })
339  return state
340}
341
342const GraphView: ClientModule<GraphProps, GraphState> = (graph, surface) => {
343  const { Box, Text } = surface.elements
344  let state = surface.state
345  if (!state) {
346    state = started(graph, surface)
347    surface.setState(state)
348  } else {
349    state.box.surface = surface
350    const shape = shapeOf(graph)
351    if (shape !== state.shape) {
352      const world = isEmpty(state.size) ? state.world : worldOf(state.size, graph)
353      const next: GraphState = {
354        ...state,
355        graph,
356        shape,
357        world,
358        layout: isEmpty(state.size)
359          ? state.layout
360          : {
361              pos: placed(graph.nodes, graph.edges, world, state.layout.pos),
362              temperature: startTemperature(world),
363            },
364        active: null,
365        isRunning: !isEmpty(state.size),
366        pinned: state.pinned.filter(id => graph.nodes.some(node => node.id === id)),
367        selected: graph.nodes.some(node => node.id === state!.selected) ? state.selected : null,
368        hovered: null,
369      }
370      surface.setState(next)
371      state = next
372    }
373  }
374  if (isEmpty(state.size)) return <Text dimColor>loading…</Text>
375  const rows = rasterOf(
376    state.graph.nodes,
377    state.graph.edges,
378    viewed(state.layout.pos, state.camera, state.zoom),
379    state.size,
380    state.selected,
381    state.hovered,
382  )
383  if (graph.isPlaced) {
384    const runs = rows.flatMap((line, y) => {
385      let x = 0
386      return line.map(run => {
387        const at = x
388        x += run.text.length
389        return { run, x: at, y }
390      })
391    })
392    return (
393      <Box flexDirection="column">
394        <Box position="relative" width={state.size.columns} height={state.size.rows}>
395          {runs
396            .filter(({ run }) => run.tone !== 'blank')
397            .map(({ run, x, y }) => (
398              // width, or truncate-end has no edge to cut against: the
399              // contract promises a run is never wider than the cells it took
400              // on the terminal, and on a proportional face nothing else holds
401              // it to that. Without it a long label overlaps its neighbour.
402              <Box position="absolute" left={x} top={y} width={run.text.length}>
403                <Text wrap="truncate-end" {...TONE[run.tone]}>
404                  {run.text}
405                </Text>
406              </Box>
407            ))}
408        </Box>
409        {state.graph.more > 0 && <Text dimColor>+{state.graph.more} more</Text>}
410      </Box>
411    )
412  }
413  return (
414    <Box flexDirection="column">
415      {rows.map(runs => (
416        <Text wrap="truncate-end">
417          {runs.map(run => (run.tone === 'blank' ? run.text : <Text {...TONE[run.tone]}>{run.text}</Text>))}
418        </Text>
419      ))}
420      {state.graph.more > 0 && <Text dimColor>+{state.graph.more} more</Text>}
421    </Box>
422  )
423}
424
425export default GraphView
426
hooks/plan.ts 275 lines
1// Pure readers for pm-band: what the pm CLIs print, turned into what the band, the
2// /pm pane and the graph draw. Nothing here touches `$`; register.tsx does the I/O.
3
4import type { Item, Listing, Step } from '../types'
5
6export type { Item, Listing, Step }
7
8/** What one `$.process.run` answered, the fields these readers look at. */
9export type Run = {
10  exitCode: number
11  stdout: string
12  stderr: string
13  isStdoutTruncated?: boolean
14}
15
16// The step grammar pm owns: ai/skills/pm-roadmap/ops.ts planStep counts
17// /^- \[[ x]\] (\d+)\./gm over the whole file. Keep the two in step.
18const STEP_LINE = /^- \[([ x])\] (\d+)\.[ \t]*(.*)$/gm
19
20export function stepsOf(content: string): Step[] {
21  return [...content.matchAll(STEP_LINE)].map(m => ({
22    n: Number(m[2]),
23    text: (m[3] ?? '').trim(),
24    isDone: m[1] === 'x',
25  }))
26}
27
28/** The first step not done yet, which is the one being worked on. */
29export function currentOf(steps: readonly Step[]): Step | undefined {
30  return steps.find(step => !step.isDone)
31}
32
33/** The band draws a meter segment per step up to this many; past it, the count alone. */
34export const METER_MAX = 20
35
36export type Segment = 'done' | 'current' | 'todo'
37
38/** The band's meter: one segment per step, the current one marked; empty past METER_MAX. */
39export function meterOf(steps: readonly Step[]): Segment[] {
40  if (steps.length > METER_MAX) return []
41  const current = currentOf(steps)
42  return steps.map(step => (step.isDone ? 'done' : step === current ? 'current' : 'todo'))
43}
44
45/** The steps tab's gauge over `width` cells: how many are filled, how many left, the percent. */
46export function gaugeOf(done: number, total: number, width: number): { filled: number; rest: number; pct: number } {
47  const ratio = total > 0 ? Math.min(1, Math.max(0, done / total)) : 0
48  const room = Math.max(0, Math.floor(width))
49  const filled = Math.round(room * ratio)
50  return { filled, rest: room - filled, pct: Math.round(ratio * 100) }
51}
52
53/** The resolver's `plan` is relative to `main_root`; an absolute one is kept. */
54export function planFile(mainRoot: string, plan: string): string {
55  if (plan.startsWith('/')) return plan
56  return `${mainRoot.replace(/\/+$/, '')}/${plan.replace(/^\.\//, '')}`
57}
58
59/**
60 * Every variant carries `mainRoot`, empty only where the resolver never got far
61 * enough to report one (no git repository, a failed run, unreadable output).
62 *
63 * The backlog does not depend on there being a current plan: closing a plan and
64 * opening /pm to pick the next item is the normal move, and that lands on
65 * `hidden`. When only `plan` and `none` carried the root, the pane had nothing
66 * to run `pm list` in on every other variant and both its tabs stayed on
67 * `loading…` for good — so the field is on the union, not on two of its arms.
68 */
69export type Resolved =
70  | {
71      kind: 'plan'
72      status: 'draft' | 'active'
73      id: string
74      title: string
75      plan: string
76      mainRoot: string
77    }
78  | { kind: 'none'; mainRoot: string }
79  | { kind: 'hidden'; mainRoot: string }
80  | { kind: 'error'; reason: string; mainRoot: string }
81
82function failureOf(run: Run): string | undefined {
83  if (run.isStdoutTruncated) return 'output truncated'
84  if (run.exitCode !== 0) {
85    const line = run.stderr.trim().split('\n').at(-1) ?? ''
86    return line || `exit ${run.exitCode}`
87  }
88  return undefined
89}
90
91/** `worktree.mjs resolve-session`: ok → plan, unbound → none, terminal or outside git → hidden. */
92export function resolvedOf(run: Run): Resolved {
93  if (run.exitCode !== 0 && /not a git repository/.test(run.stderr)) {
94    return { kind: 'hidden', mainRoot: '' }
95  }
96  const failure = failureOf(run)
97  if (failure) return { kind: 'error', reason: failure, mainRoot: '' }
98  let json: Record<string, unknown>
99  try {
100    json = JSON.parse(run.stdout) as Record<string, unknown>
101  } catch {
102    return { kind: 'error', reason: 'unreadable resolver output', mainRoot: '' }
103  }
104  const text = (key: string) =>
105    typeof json[key] === 'string' ? (json[key] as string) : ''
106  const status = text('status')
107  // main_root is on every resolver answer that parsed, terminal and the error
108  // statuses included, so the three above are the only roots left empty.
109  const mainRoot = text('main_root')
110  if (status === 'unbound') return { kind: 'none', mainRoot }
111  if (status === 'terminal') return { kind: 'hidden', mainRoot }
112  if (status !== 'ok') return { kind: 'error', reason: status || 'no status', mainRoot }
113  const planStatus = text('plan_status')
114  if (planStatus !== 'draft' && planStatus !== 'active') {
115    return { kind: 'hidden', mainRoot }
116  }
117  return {
118    kind: 'plan',
119    status: planStatus,
120    id: text('id'),
121    title: text('title') || text('id'),
122    plan: text('plan'),
123    mainRoot: text('main_root'),
124  }
125}
126
127export function listingOf(run: Run): Listing | { error: string } {
128  const failure = failureOf(run)
129  if (failure) return { error: failure }
130  try {
131    const json = JSON.parse(run.stdout) as Partial<Listing>
132    if (!Array.isArray(json.eligible) || !Array.isArray(json.blocked)) {
133      return { error: 'unexpected list output' }
134    }
135    return {
136      eligible: json.eligible,
137      blocked: json.blocked,
138      inbox: typeof json.inbox === 'number' ? json.inbox : 0,
139    }
140  } catch {
141    return { error: 'unreadable list output' }
142  }
143}
144
145const PRIORITY: Record<string, number> = { P0: 0, P1: 1, P2: 2, P3: 3 }
146
147function byRank(a: Item, b: Item): number {
148  const priority = (PRIORITY[a.priority] ?? 9) - (PRIORITY[b.priority] ?? 9)
149  if (priority !== 0) return priority
150  const order = (a.order || Infinity) - (b.order || Infinity)
151  if (order !== 0 && !Number.isNaN(order)) return order
152  return a.id.localeCompare(b.id)
153}
154
155export type Row = Item & { isBlocked: boolean; isCurrent: boolean }
156export type Group = { key: string; rows: Row[] }
157
158/** The backlog tab: tasks in key order, items by priority then order. */
159export function groupsOf(listing: Listing, currentPlan?: string): Group[] {
160  const rows: Row[] = [
161    ...listing.eligible.map(item => ({ ...item, isBlocked: false })),
162    ...listing.blocked.map(item => ({ ...item, isBlocked: true })),
163  ].map(row => ({ ...row, isCurrent: !!currentPlan && row.plan === currentPlan }))
164  const keys = [...new Set(rows.map(row => row.key))].sort()
165  return keys.map(key => ({
166    key,
167    rows: rows.filter(row => row.key === key).sort(byRank),
168  }))
169}
170
171export type NodeState = 'task' | 'eligible' | 'blocked' | 'current'
172
173export type GraphNode = {
174  id: string
175  label: string
176  title: string
177  task: string
178  state: NodeState
179}
180
181export type GraphEdge = {
182  from: string
183  to: string
184  kind: 'task' | 'dependency' | 'order'
185}
186
187export type Graph = { nodes: GraphNode[]; edges: GraphEdge[]; more: number }
188
189export const GRAPH_NODE_CAP = 120
190export const GRAPH_PROPS_BUDGET = 60_000
191const TITLE_CHARS = 40
192
193export const hubOf = (key: string) => `#${key}`
194
195function clip(text: string, chars: number): string {
196  return text.length > chars ? `${text.slice(0, chars - 1)}…` : text
197}
198
199function build(items: readonly Row[], total: number): Graph {
200  const keys = [...new Set(items.map(item => item.key))].sort()
201  const ids = new Set(items.map(item => item.id))
202  const nodes: GraphNode[] = [
203    ...keys.map(key => ({
204      id: hubOf(key),
205      label: key,
206      title: key,
207      task: key,
208      state: 'task' as const,
209    })),
210    ...items.map(item => ({
211      id: item.id,
212      label: item.id,
213      title: clip(item.title, TITLE_CHARS),
214      task: item.key,
215      state: item.isCurrent
216        ? ('current' as const)
217        : item.isBlocked
218          ? ('blocked' as const)
219          : ('eligible' as const),
220    })),
221  ]
222  const edges: GraphEdge[] = items.map(item => ({
223    from: item.id,
224    to: hubOf(item.key),
225    kind: 'task',
226  }))
227  for (const item of items) {
228    for (const dep of item.dependsOn) {
229      // A dependency no longer in the backlog is resolved: pm stops blocking on it.
230      if (dep !== item.id && ids.has(dep)) {
231        edges.push({ from: item.id, to: dep, kind: 'dependency' })
232      }
233    }
234  }
235  for (const key of keys) {
236    const chain = items
237      .filter(item => item.key === key && item.order > 0)
238      .sort((a, b) => a.order - b.order)
239    for (let i = 1; i < chain.length; i++) {
240      edges.push({ from: chain[i]!.id, to: chain[i - 1]!.id, kind: 'order' })
241    }
242  }
243  return { nodes, edges, more: total - items.length }
244}
245
246/**
247 * The graph tab's data: the current plan's task when there is one, every task
248 * otherwise; at most `cap` nodes (hubs included) and `budget` characters of
249 * JSON, so the Client's props stay inside the engine's bounds.
250 */
251export function graphOf(
252  listing: Listing,
253  currentPlan?: string,
254  cap = GRAPH_NODE_CAP,
255  budget = GRAPH_PROPS_BUDGET,
256): Graph {
257  const rows = groupsOf(listing, currentPlan).flatMap(group => group.rows)
258  const current = rows.find(row => row.isCurrent)
259  const scope = (current ? rows.filter(row => row.key === current.key) : rows).sort(
260    byRank,
261  )
262  let picked: Row[] = []
263  for (const row of scope) {
264    const hubs = new Set([...picked, row].map(one => one.key)).size
265    if (picked.length + 1 + hubs > cap) break
266    picked.push(row)
267  }
268  let graph = build(picked, scope.length)
269  while (picked.length > 0 && JSON.stringify(graph).length > budget) {
270    picked = picked.slice(0, -1)
271    graph = build(picked, scope.length)
272  }
273  return graph
274}
275
hooks/layout.ts 202 lines
1// A force-directed layout (Fruchterman–Reingold) in terminal cells, deterministic
2// for a given graph and size so a test can pin its result. The graph Client runs
3// one `tick` per frame until `isSettled`.
4
5import type { GraphEdge, GraphNode } from './plan'
6
7export type Point = { x: number; y: number }
8export type Positions = Record<string, Point>
9export type Size = { columns: number; rows: number }
10export type Layout = { pos: Positions; temperature: number }
11
12/** A terminal cell is about twice as tall as it is wide; forces work in square space. */
13const ASPECT = 2
14const COOLING = 0.9
15const COLD = 0.15
16const QUIET_PER_NODE = 0.02
17/** The ideal distance between linked nodes, in square cells, when unbounded. */
18const SPACING = 12
19
20/** mulberry32: a small seeded generator, so placement never depends on Math.random. */
21export function seeded(seed: number): () => number {
22  let a = seed >>> 0
23  return () => {
24    a = (a + 0x6d2b79f5) >>> 0
25    let t = a
26    t = Math.imul(t ^ (t >>> 15), t | 1)
27    t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
28    return ((t ^ (t >>> 14)) >>> 0) / 4294967296
29  }
30}
31
32function hashOf(text: string): number {
33  let h = 2166136261
34  for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 16777619)
35  return h >>> 0
36}
37
38const clamp = (value: number, low: number, high: number) =>
39  Math.min(high, Math.max(low, value))
40
41function inside(point: Point, size: Size): Point {
42  return {
43    x: clamp(point.x, 0, Math.max(0, size.columns - 1)),
44    y: clamp(point.y, 0, Math.max(0, size.rows - 1)),
45  }
46}
47
48export function startTemperature(size: Size): number {
49  return Math.max(size.columns, size.rows * ASPECT) / 6
50}
51
52/**
53 * Where each node starts: where it already was, else beside a neighbour that
54 * has a place, else a spot its id seeds. Nodes no longer in the graph drop out.
55 */
56export function placed(
57  nodes: readonly GraphNode[],
58  edges: readonly GraphEdge[],
59  size: Size,
60  prev: Positions = {},
61  isBounded = false,
62): Positions {
63  const pos: Positions = {}
64  for (const node of nodes) {
65    const kept = prev[node.id]
66    if (kept) pos[node.id] = isBounded ? inside(kept, size) : kept
67  }
68  for (const node of nodes) {
69    if (pos[node.id]) continue
70    const rand = seeded(hashOf(node.id))
71    const neighbour = edges
72      .map(edge => (edge.from === node.id ? edge.to : edge.to === node.id ? edge.from : null))
73      .find(id => id !== null && pos[id] !== undefined)
74    const near = neighbour ? pos[neighbour] : undefined
75    pos[node.id] = inside(
76      near
77        ? { x: near.x + (rand() - 0.5) * 6, y: near.y + (rand() - 0.5) * 3 }
78        : { x: rand() * (size.columns - 1), y: rand() * (size.rows - 1) },
79      size,
80    )
81  }
82  return pos
83}
84
85/**
86 * How a tick may move nodes. `active`: only these move (the rest hold still,
87 * though they still push and pull), absent all do.
88 *
89 * `isBounded` defaults to false because that is what graph.tsx runs: nodes may
90 * leave `size`, which then sets the centre the weak pull aims at and nothing
91 * else — spacing comes from the fixed SPACING, not from `size`. Bounded has to
92 * ask for itself, so a test that does not is testing the real thing. It used
93 * to default the other way, and since `settle` has no caller outside the
94 * tests, every layout test was pinning geometry the graph never ran.
95 */
96export type TickOptions = { active?: ReadonlySet<string>; isBounded?: boolean }
97
98/** One step of the simulation; pinned nodes (being dragged) hold still. */
99export function tick(
100  nodes: readonly GraphNode[],
101  edges: readonly GraphEdge[],
102  layout: Layout,
103  size: Size,
104  pinned: ReadonlySet<string> = new Set(),
105  { active, isBounded = false }: TickOptions = {},
106): { layout: Layout; energy: number } {
107  const n = nodes.length
108  if (n === 0) return { layout: { ...layout, temperature: 0 }, energy: 0 }
109  const area = size.columns * size.rows * ASPECT
110  // Unbounded, the spacing is fixed: the graph's size follows its node count,
111  // never the region it happens to be seen through.
112  const k = isBounded ? 0.75 * Math.sqrt(area / n) : SPACING
113  const disp = new Map(nodes.map(node => [node.id, { x: 0, y: 0 }]))
114  const at = (id: string) => {
115    const p = layout.pos[id] ?? { x: 0, y: 0 }
116    return { x: p.x, y: p.y * ASPECT }
117  }
118  for (let i = 0; i < n; i++) {
119    const a = nodes[i]!
120    const pa = at(a.id)
121    for (let j = i + 1; j < n; j++) {
122      const b = nodes[j]!
123      const pb = at(b.id)
124      let dx = pa.x - pb.x
125      let dy = pa.y - pb.y
126      if (dx === 0 && dy === 0) {
127        // Two nodes on one spot: part them along a direction their indices fix.
128        dx = ((i - j) % 3) * 0.1 + 0.05
129        dy = ((i + j) % 2) * 0.1 - 0.05
130      }
131      const d = Math.max(0.01, Math.hypot(dx, dy))
132      const force = (k * k) / d
133      const da = disp.get(a.id)!
134      const db = disp.get(b.id)!
135      da.x += (dx / d) * force
136      da.y += (dy / d) * force
137      db.x -= (dx / d) * force
138      db.y -= (dy / d) * force
139    }
140  }
141  for (const edge of edges) {
142    const da = disp.get(edge.from)
143    const db = disp.get(edge.to)
144    if (!da || !db) continue
145    const pa = at(edge.from)
146    const pb = at(edge.to)
147    const dx = pa.x - pb.x
148    const dy = pa.y - pb.y
149    const d = Math.max(0.01, Math.hypot(dx, dy))
150    const weight = edge.kind === 'order' ? 0.5 : 1
151    const force = ((d * d) / k) * weight
152    da.x -= (dx / d) * force
153    da.y -= (dy / d) * force
154    db.x += (dx / d) * force
155    db.y += (dy / d) * force
156  }
157  const centre = { x: (size.columns - 1) / 2, y: ((size.rows - 1) / 2) * ASPECT }
158  const pos: Positions = {}
159  let energy = 0
160  for (const node of nodes) {
161    const p = at(node.id)
162    if (pinned.has(node.id) || (active !== undefined && !active.has(node.id))) {
163      pos[node.id] = layout.pos[node.id] ?? inside({ x: 0, y: 0 }, size)
164      continue
165    }
166    const d = disp.get(node.id)!
167    // A weak pull to the centre keeps separate components together; weaker
168    // when unbounded, so the graph takes the room it needs.
169    const pull = isBounded ? 0.05 : 0.015
170    d.x += (centre.x - p.x) * pull * k
171    d.y += (centre.y - p.y) * pull * k
172    const length = Math.hypot(d.x, d.y)
173    const step = length > 0 ? Math.min(length, layout.temperature) / length : 0
174    const moved = { x: p.x + d.x * step, y: (p.y + d.y * step) / ASPECT }
175    const next = isBounded ? inside(moved, size) : moved
176    const old = layout.pos[node.id] ?? next
177    energy += Math.hypot(next.x - old.x, next.y - old.y)
178    pos[node.id] = next
179  }
180  return { layout: { pos, temperature: layout.temperature * COOLING }, energy }
181}
182
183export function isSettled(layout: Layout, energy: number, nodes: number): boolean {
184  return layout.temperature < COLD || energy / Math.max(1, nodes) < QUIET_PER_NODE
185}
186
187/** Runs ticks until the layout settles or `limit` ticks pass: what a test pins. */
188export function settle(
189  nodes: readonly GraphNode[],
190  edges: readonly GraphEdge[],
191  size: Size,
192  limit = 400,
193): { layout: Layout; ticks: number } {
194  let layout: Layout = { pos: placed(nodes, edges, size), temperature: startTemperature(size) }
195  for (let ticks = 1; ticks <= limit; ticks++) {
196    const result = tick(nodes, edges, layout, size)
197    layout = result.layout
198    if (isSettled(layout, result.energy, nodes.length)) return { layout, ticks }
199  }
200  return { layout, ticks: limit }
201}
202
hooks/raster.ts 183 lines
1// Laid-out graph → rows of styled runs the graph Client draws as Text. Edges first,
2// then nodes over them, so a node's marker and label always win a shared cell.
3
4import type { Positions, Size } from './layout'
5import type { GraphEdge, GraphNode } from './plan'
6
7export type Tone =
8  | 'blank'
9  | 'task-edge'
10  | 'dependency-edge'
11  | 'order-edge'
12  | 'task'
13  | 'eligible'
14  | 'blocked'
15  | 'current'
16  | 'hovered'
17  | 'selected'
18
19export type Run = { text: string; tone: Tone }
20
21const EDGE: Record<GraphEdge['kind'], { ch: string; tone: Tone }> = {
22  task: { ch: '·', tone: 'task-edge' },
23  dependency: { ch: '•', tone: 'dependency-edge' },
24  order: { ch: '∙', tone: 'order-edge' },
25}
26
27function cellOf(point: { x: number; y: number }) {
28  return { x: Math.round(point.x), y: Math.round(point.y) }
29}
30
31function markerOf(node: GraphNode, isSelected: boolean): string {
32  if (isSelected) return '◉'
33  return node.state === 'task' ? '◆' : '●'
34}
35
36/** Where a node's marker sits and which cells its label took (`from`..`to`, inclusive). */
37export type Placement = { x: number; y: number; from: number; to: number; text: string }
38
39/**
40 * Markers first, then each label in node order: right of its marker, else left,
41 * else cut with `…` into the free cells on the right. A label keeps one blank
42 * cell from any other marker or label, so two never read as one.
43 */
44export function placementsOf(
45  nodes: readonly GraphNode[],
46  pos: Positions,
47  size: Size,
48): Map<string, Placement> {
49  const { columns, rows } = size
50  const taken: boolean[][] = Array.from({ length: rows }, () => Array(columns).fill(false))
51  const isFree = (y: number, from: number, to: number) => {
52    if (from < 0 || to >= columns) return false
53    for (let cx = Math.max(0, from - 1); cx <= Math.min(columns - 1, to + 1); cx++) {
54      if (taken[y]![cx]) return false
55    }
56    return true
57  }
58  const placed = new Map<string, Placement>()
59  for (const node of nodes) {
60    const p = pos[node.id]
61    if (!p) continue
62    const { x, y } = cellOf(p)
63    if (x < 0 || y < 0 || x >= columns || y >= rows) continue
64    taken[y]![x] = true
65    placed.set(node.id, { x, y, from: x, to: x - 1, text: '' })
66  }
67  for (const node of nodes) {
68    const place = placed.get(node.id)
69    if (!place) continue
70    const { x, y } = place
71    const length = node.label.length
72    // The marker's own cell is not an obstacle to its label's gap.
73    taken[y]![x] = false
74    let chosen: Placement | null = null
75    if (isFree(y, x + 2, x + 1 + length)) {
76      chosen = { x, y, from: x + 2, to: x + 1 + length, text: node.label }
77    } else if (isFree(y, x - 1 - length, x - 2)) {
78      chosen = { x, y, from: x - 1 - length, to: x - 2, text: node.label }
79    } else {
80      let room = 0
81      while (x + 2 + room < columns && isFree(y, x + 2, x + 2 + room)) room += 1
82      if (room >= 2) {
83        chosen = { x, y, from: x + 2, to: x + 1 + room, text: `${node.label.slice(0, room - 1)}…` }
84      }
85    }
86    taken[y]![x] = true
87    if (!chosen) continue
88    for (let cx = chosen.from; cx <= chosen.to; cx++) taken[y]![cx] = true
89    placed.set(node.id, chosen)
90  }
91  return placed
92}
93
94export function rasterOf(
95  nodes: readonly GraphNode[],
96  edges: readonly GraphEdge[],
97  pos: Positions,
98  size: Size,
99  selected: string | null = null,
100  hovered: string | null = null,
101): Run[][] {
102  const { columns, rows } = size
103  const ch: string[][] = Array.from({ length: rows }, () => Array(columns).fill(' '))
104  const tone: Tone[][] = Array.from({ length: rows }, () => Array(columns).fill('blank'))
105  const put = (x: number, y: number, c: string, t: Tone) => {
106    if (x < 0 || y < 0 || x >= columns || y >= rows) return
107    ch[y]![x] = c
108    tone[y]![x] = t
109  }
110  for (const edge of edges) {
111    const a = pos[edge.from]
112    const b = pos[edge.to]
113    if (!a || !b) continue
114    const style = EDGE[edge.kind]
115    let { x: x0, y: y0 } = cellOf(a)
116    const { x: x1, y: y1 } = cellOf(b)
117    const dx = Math.abs(x1 - x0)
118    const dy = -Math.abs(y1 - y0)
119    const sx = x0 < x1 ? 1 : -1
120    const sy = y0 < y1 ? 1 : -1
121    let err = dx + dy
122    for (;;) {
123      put(x0, y0, style.ch, style.tone)
124      if (x0 === x1 && y0 === y1) break
125      const e2 = 2 * err
126      if (e2 >= dy) {
127        err += dy
128        x0 += sx
129      }
130      if (e2 <= dx) {
131        err += dx
132        y0 += sy
133      }
134    }
135  }
136  const placed = placementsOf(nodes, pos, size)
137  for (const node of nodes) {
138    const place = placed.get(node.id)
139    if (!place) continue
140    const t: Tone = node.id === selected ? 'selected' : node.id === hovered ? 'hovered' : node.state
141    put(place.x, place.y, markerOf(node, node.id === selected), t)
142    if (place.text === '') continue
143    // The gap cell between marker and label takes the node's tone, so a picked
144    // node inverts as one piece.
145    const from = Math.min(place.from, place.x + 1)
146    const to = Math.max(place.to, place.x - 1)
147    for (let cx = from; cx <= to; cx++) {
148      const at = cx - place.from
149      const c = cx >= place.from && cx <= place.to ? place.text[at]! : ' '
150      if (cx !== place.x) put(cx, place.y, c, t)
151    }
152  }
153  return ch.map((line, y) => {
154    const runs: Run[] = []
155    for (let x = 0; x < line.length; x++) {
156      const t = tone[y]![x]!
157      const last = runs.at(-1)
158      if (last && last.tone === t) last.text += line[x]
159      else runs.push({ text: line[x]!, tone: t })
160    }
161    return runs
162  })
163}
164
165/** The node whose marker or placed label covers a cell, the last drawn first. */
166export function nodeAt(
167  nodes: readonly GraphNode[],
168  pos: Positions,
169  size: Size,
170  x: number,
171  y: number,
172): string | undefined {
173  const placed = placementsOf(nodes, pos, size)
174  for (let i = nodes.length - 1; i >= 0; i--) {
175    const node = nodes[i]!
176    const place = placed.get(node.id)
177    if (!place || place.y !== y) continue
178    if (x === place.x) return node.id
179    if (place.text !== '' && x >= Math.min(place.from, place.x) && x <= Math.max(place.to, place.x)) return node.id
180  }
181  return undefined
182}
183
types/index.d.ts 48 lines
1export type Step = { n: number; text: string; isDone: boolean }
2
3/** One backlog item as `pm list --json` prints it (ai/skills/pm-roadmap/join.ts Candidate). */
4export type Item = {
5  key: string
6  id: string
7  title: string
8  priority: string
9  order: number
10  plan: string | null
11  status: string
12  dependsOn: string[]
13  blockedBy?: string
14  blockedByReason?: 'dependency' | 'order'
15}
16
17export type Listing = { eligible: Item[]; blocked: Item[]; inbox: number }
18
19/** What the band and the steps tab draw: a bound plan, no plan, or nothing. */
20export type PlanView =
21  | { kind: 'plan'; status: 'draft' | 'active'; id: string; title: string; plan: string; steps: Step[] }
22  | { kind: 'none' }
23
24/**
25 * The band's state. `view` is the last good read for `sessionId` (null: draw
26 * nothing); `error` says the latest refresh failed and why.
27 */
28export type BandState = { sessionId: string; view: PlanView | null; error: string | null }
29
30/**
31 * The backlog tab's state, read only while the /pm pane is open. `isOutside`: the
32 * session runs outside any git repository, so there is no backlog to read.
33 */
34export type BacklogState = { sessionId: string; listing: Listing | null; error: string | null; isOutside: boolean }
35
36export type Tab = 'steps' | 'backlog' | 'graph'
37
38declare module 'claude-code' {
39  interface PluginState {
40    'pm-band': {
41      band: BandState
42      backlog: BacklogState
43      tab: Tab
44      selected: string | null
45    }
46  }
47}
48