SLOPSHOPPER

wayfinder-maps

A side drawer that shows every wayfinder map and spec in the project (markdown or GitHub issues), their tickets, statuses and dependencies.

panebandcommandtoastprocesstimer
★ 1v0.7.1MITupdated 2026-10-24Yuvalz19500/claude-mods/plugins/wayfinder-maps
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · wayfinder-maps
│ ┃ Wayfinder ✕ › fix the failing auth test and add an audit log call │ ┃ ▍Wayfinder refreshing… r: Refresh │ ┃ ⏺ Read(src/auth.ts) │ ┃ Looking for maps… ⎿ 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 │ │ › /wayfinder-maps │ ⎿ wayfinder-maps: Wayfinder drawer opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Wayfinder
▍Wayfinder refreshing… r: Refresh Looking for maps…
README

claude-mods

Mods for Claude Code, built on the function-hooks plugin API: live panes, bands and hooks that run inside the terminal and the desktop Code tab.

This repo is a plugin marketplace. Add it once, then install any mod from it:

claude plugin marketplace add Yuvalz19500/claude-mods
claude plugin install wayfinder-maps@claude-mods

To update to the latest release:

claude plugin marketplace update claude-mods
claude plugin update wayfinder-maps@claude-mods

What changed in each version is on the Releases page.

Mods

wayfinder-maps

A side drawer for projects planned with the /wayfinder skill. Run /wayfinder-maps to open it. It works in the desktop Code tab and in the terminal.

The Work buttons run Matt Pocock's skills, so install his mattpocock-skills plugin alongside it; the drawer itself reads your maps without it. This marketplace lists it too, so one marketplace gives you both (and both reach your claude.ai account and cloud sessions):

claude plugin install mattpocock-skills@claude-mods

mattpocock-skills comes straight from mattpocock/skills, always its latest version; it is not maintained here.

The drawer

  • Shows up when you need it. In a project with wayfinder maps, a slim band above the prompt sums up what is ready to take and what is waiting on you, with an Open map drawer button. It stays out of the way everywhere else.
  • Every map in the project. Each map shows its status (open, in progress, done, graduated to a spec), how many tickets are done, and how many are frontier, claimed, waiting on you or blocked.
  • Maps and specs. Wayfinder maps hold decision tickets. Graduated specs (a spec.md beside numbered implementation tickets) appear in their own section and are drawn the same way.
  • Tickets in steps. Click a map to see its tickets as cards, set out in steps from top to bottom: each ticket sits one step below the last ticket it waits on. A card's edge takes its status's color, and an after 17 ✓ 16 ◐ line names what it waits on; a long list is cut to one line ending … +12, and the ticket itself lists them all. Every card on a map is the same size. Cards fill the drawer's width and stack when it is narrow; a click anywhere on a card opens its ticket. Tree shows the same tickets as an indented list instead.
  • Status chips. All, To do, ⚑ Frontier, ◐ Claimed, ◷ Waiting on you, ◌ Blocked, ✓ Done: each counts its tickets and, clicked, shows only them.
  • A page per ticket. Click a ticket to open it on its own page: its status, what it waits on and what it unblocks (each one click away), its question and answer (or the issue and its comments), Open file or Open issue, and Work this ticket. ← Back to map returns to the map at that ticket.
  • Follows your theme. Everything is drawn with the app's own elements, light or dark; the only color it adds is each status's.

Working the tickets

Every Work button works in a new chat with no context, so free tickets can be worked in parallel. In the desktop app it copies the command, says so in a toast, and opens the app's new-session page: with the project's folder selected under the prompt (the toast names it), paste (Ctrl+V, ⌘V on a Mac) and press Enter. The page keeps the folder you last chose there rather than being pointed at one, because a link that names a folder makes the app ask "Trust this workspace?", and trusting the folder already selected breaks that page's folder and branch. The app won't let anything run a command in a new chat for you, so the paste is yours. In the terminal, a terminal window of its own runs the command at once. ↗ on a button means it opens a new chat; set workIn to here to work in the current chat instead (the buttons then show →).

WhereButtonWhat it does
MapWork next: 07 ↗A new chat on the next ticket ready to take (/wayfinder <map> <ticket>). The card then reads new chat ↗ and the button moves on to the next free ticket, so you fan out one click at a time. With nothing free it becomes Work the map.
SpecImplement frontier · 5 ↗A new chat on this plugin's /wayfinder-maps:implement-frontier: one wave of the spec, the tickets ready now, then it stops.
SpecImplement spec ↗A new chat on Matt Pocock's /implement-spec: wave after wave until the whole spec is done.
Ticket pageWork this ticket ↗A new chat on that one ticket (/wayfinder on a map ticket, /implement on a spec ticket).

The implement-frontier skill

Shipped with this plugin, for implementing a spec one wave at a time, so you can check each wave and answer what waits on you before starting the next. Run it from the drawer or as /wayfinder-maps:implement-frontier <spec>. It:

  1. Fixes the wave: the frontier tickets as they stand when it starts. Tickets that unblock during the run wait for the next wave.
  2. Claims them, opens one branch and one draft PR for the wave, and starts a subagent per ticket, each in its own worktree, doing what /implement does (TDD, typecheck, the tests its change affects, commit). Subagents code against the library and framework versions the repo has installed, read their current docs, and never use deprecated APIs. When a test-audit skill is installed, every test a subagent writes passes its authoring gate: it names what it protects and the bug that would fail it, and doesn't copy a test that already proves the same thing.
  3. Merges each finished ticket into the wave branch, marks it done, and deletes that subagent's worktree and branch (local and remote) right away.
  4. Runs the change-aware tests for the whole wave (what the wave's diff affects, never the full suite) and fixes what fails. The full suite runs once per wave, right before you merge it, and every failure it shows gets fixed, pre-existing and flaky ones included; the report reminds you it is owed.
  5. Leaves /code-review and verify for the pre-merge pass: they run once per wave, on the wave branch after you've checked it and every fix is in, so one review and one verify cover all of the wave's changes.
  6. Marks the PR ready, confirms no subagent worktree or branch is left (the wave branch is the only one it leaves), and reports what it built, what the wave unblocked, what waits on you, and that the pre-merge pass (code review, verify, full suite) is still owed. Then it stops.

More skills

Four more skills ship with the plugin. Claude loads each one on its own when the situation fits; you can also ask for one by name.

SkillWhen it appliesWhat it does
lean-testsChoosing which tests to run while implementing, merging or fixing, in any kind of project, and any repo with no affected-only test command yet.Runs only the tests a change affects and the full suite once right before merge, with every failure fixed. In a repo without it, sets it up itself: finds the project's own test tools (any stack, games included), uses their change-aware or hash-caching options (Bazel, Gradle, Turborepo/Nx, Playwright --only-changed, Vitest --changed, pytest-testmon and the like), wires them into one affected-tests command, proves it, and records it and the latest-versions rule in CLAUDE.md. Until then it falls back to the full suite.
test-auditWriting, changing or reviewing tests in any repo, and the audit before a wave or feature merges.Gates every new test (what it protects, the bug that fails it, the cheapest layer that catches it, extend rather than copy) and, in an audit, deletes, merges or repairs tests that prove nothing new, with a report of what still proves each deleted one. implement-frontier holds every test to its gate.
wayfinder-map-threadsRunning /wayfinder on a map that already exists, in a Claude project.Claims every unblocked ticket and starts one thread per ticket (a cloud thread, or a Remote Control thread on your PC when the ticket needs it), instead of working a ticket in the current chat.
wayfinder-wave-runnerBuilding a spec wave by wave with implement-frontier, in a Claude project.Where each wave runs (cloud or your PC), one thread per wave, code review and verify once in the pre-merge pass, models and effort, branch names, latest versions with no deprecated APIs, lean change-aware tests during the wave and one full run before merge with every failure fixed, the test audit before merge, the manual-test checklist walked item by item, and the cleanup after every merge.

Where it looks

TrackerWhat it reads
Local markdownAny folder (up to 4 levels deep) holding map.md or spec.md beside an issues/ or tickets/ folder of NN-slug.md files: .scratch/<effort>/, docs/wayfinder/<effort>/ and the like. Each ticket's Type:, Status:, Assignee: and Blocked by: lines (plain or bold, inline or as a list).
GitHubMaps: issues labelled wayfinder:map in the session's repo. Specs: issues titled Spec: … or labelled wayfinder:spec; a spec's Parent map: #n line marks that map graduated. Their sub-issues are the tickets; a sub-issue that has sub-issues of its own (a big spec grouped by build step) is opened up into its tickets. GitHub's native blocked-by dependencies count, falling back to a task list in the map body and Blocked by: #n lines or a ## Blocked by list of - #n items. Needs the gh CLI, signed in.

Status words are folded into five states. resolved, done and closed issues are done. claimed, or any assignee on an open ticket, is claimed. awaiting-design and ready-for-human are waiting on you. An open ticket with an unfinished blocker is blocked. Everything else open (open, ready-for-agent) is frontier.

The drawer refreshes after every turn and every 30 seconds while it's open. GitHub is fetched at most once a minute; press Refresh to fetch now.

Settings

Where the Work buttons work, and the prompts they send, can be changed under /config (or pluginConfigs in settings):

OptionDefault
workInnew-chat: a new chat with no context (on the desktop, the command copied and the app's new-session page opened; in the terminal, a window of its own). here: this chat.
mapPrompt/mattpocock-skills:wayfinder {map}
mapTicketPrompt/mattpocock-skills:wayfinder {map} {ticket}
specTicketPrompt/mattpocock-skills:implement {ticket}
specPrompt/mattpocock-skills:implement-spec {map}
frontierPrompt/wayfinder-maps:implement-frontier {map}

{map} is the map's (or spec's) path or issue URL, {ticket} the ticket's path or issue URL, {title} its title. A prompt starting with / runs as that slash command; anything else is sent as a message.

Developing a mod

Each mod is a folder under plugins/ with .claude-plugin/plugin.json, hooks/hooks.json and a hooks module. Check one with:

claude plugin validate plugins/<mod>

Run its tests with claude plugin test plugins/<mod>. Load a working copy into a session with claude --plugin-dir plugins/<mod>; it hot-reloads on save. Add the mod to .claude-plugin/marketplace.json to publish it. CLAUDE.md has the full build-and-release checklist and the engine's gotchas.

Source 10 files
hooks/register.tsx 927 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { WfCopied, WfData, WfDetail, WfFilter, WfLayout, WfMap, WfTicket, WfView } from '../types'
5import type { CardProps } from './card'
6import { ClickGate } from './clicks'
7import { githubIssueBody, githubRepo, loadGithubMaps } from './github'
8import { STATUS_STYLE, afterLine, cardLayout, cardRows, dependents, layers, treeRows } from './graph'
9import { appChat, clipboardArgv, folderName, pasteKeys, terminalChat } from './launch'
10import type { Launch, Platform } from './launch'
11import { loadMarkdownMaps, readText } from './markdown'
12import { counts } from './parse'
13import type { Io } from './parse'
14import { absolutizeLinks, fileUrl, stripHeaderFields, wrapLines } from './text'
15
16const PANE = 'wayfinder'
17const TITLE = 'Wayfinder'
18const GITHUB_EVERY_MS = 60_000
19const POLL_MS = 30_000
20
21const data = atom({ plugin: 'wayfinder-maps', key: 'data' } as const, null)
22const isLoading = atom({ plugin: 'wayfinder-maps', key: 'isLoading' } as const, false)
23const isPaneOpen = atom({ plugin: 'wayfinder-maps', key: 'isPaneOpen' } as const, false)
24const view = atom(
25  { plugin: 'wayfinder-maps', key: 'view' } as const,
26  { mapId: null, ticketId: null, filter: 'all', layout: 'steps' } as WfView,
27)
28const detail = atom({ plugin: 'wayfinder-maps', key: 'detail' } as const, null as WfDetail)
29const started = atom({ plugin: 'wayfinder-maps', key: 'started' } as const, {} as Record<string, number>)
30
31/** How long a ticket opened in a new chat stays out of "Work next", for its chat to claim it. */
32const STARTED_MS = 15 * 60_000
33/** The command a Work button last copied for the person to paste in a new chat. */
34const copied = atom({ plugin: 'wayfinder-maps', key: 'copied' } as const, null as WfCopied)
35/** How long the toast shows before the app moves to the new chat. */
36const OPEN_AFTER_MS = 1_500
37
38const MAP_STATUS_LABEL: Record<WfMap['status'], { text: string; color: string }> = {
39  open: { text: 'open', color: STATUS_STYLE.open.fill },
40  active: { text: 'in progress', color: STATUS_STYLE.claimed.fill },
41  done: { text: 'done', color: STATUS_STYLE.done.fill },
42  graduated: { text: 'graduated → spec', color: STATUS_STYLE.done.fill },
43}
44
45const prompts = {
46  map: '/mattpocock-skills:wayfinder {map}',
47  mapTicket: '/mattpocock-skills:wayfinder {map} {ticket}',
48  specTicket: '/mattpocock-skills:implement {ticket}',
49  /** The whole spec: the skill takes the frontier and runs a subagent per ticket, in parallel. */
50  spec: '/mattpocock-skills:implement-spec {map}',
51  /** One wave: the spec's frontier tickets in parallel, then stop (this plugin's own skill). */
52  frontier: '/wayfinder-maps:implement-frontier {map}',
53}
54/** Where Work buttons work: a new chat (the default), always a terminal window, or this chat. */
55let workIn: 'new-chat' | 'here' = 'new-chat'
56let platform: Platform | undefined
57let lastGithubAt = 0
58let githubMaps: WfMap[] = []
59let githubError: string | undefined
60let isRefreshing = false
61/** A refresh asked for while one runs: runs after it; true when it should fetch GitHub. */
62let queued: boolean | null = null
63
64// Button actions by key, so a focus move (desktop) can run the same action a press does.
65const handlers = new Map<string, () => void>()
66const gate = new ClickGate()
67let drawnOn: string | undefined
68
69function bind(key: string, fn: () => unknown): () => void {
70  const handler = () => void fn()
71  handlers.set(key, handler)
72  return handler
73}
74
75const bar = (done: number, total: number, width = 16) => {
76  const filled = total === 0 ? 0 : Math.round((done / total) * width)
77  return '▰'.repeat(filled) + '▱'.repeat(width - filled)
78}
79
80const relative = (root: string, path: string) => {
81  const r = root.replace(/\\/g, '/').replace(/\/$/, '')
82  const p = path.replace(/\\/g, '/')
83  return p.startsWith(r + '/') ? p.slice(r.length + 1) : p
84}
85
86const fill = (template: string, values: Record<string, string>) =>
87  template.replace(/\{(\w+)\}/g, (whole, k: string) => values[k] ?? whole)
88
89const norm = (path: string) => path.replace(/\\/g, '/').replace(/\/{2,}/g, '/').toLowerCase()
90
91const isClosed = (t: WfTicket) => t.status === 'done' || t.status === 'dropped'
92
93function visible(tickets: WfTicket[], filter: WfFilter): WfTicket[] {
94  if (filter === 'all') return tickets
95  if (filter === 'frontier') return tickets.filter(t => t.isFrontier)
96  if (filter === 'unresolved') return tickets.filter(t => !isClosed(t))
97  if (filter === 'done') return tickets.filter(isClosed)
98  return tickets.filter(t => t.status === filter)
99}
100
101/** What a status reads as on a card: the assignee rides along when claimed. */
102const statusText = (t: WfTicket, isOpened = false) =>
103  t.status === 'claimed' && t.assignee
104    ? `claimed · ${t.assignee.split(/[\s(]/)[0]}`
105    : isOpened && t.isFrontier
106      ? 'new chat ↗'
107      : STATUS_STYLE[t.status].label
108
109/** True for a ticket a Work button opened a new chat on a moment ago: its chat has not claimed it yet. */
110const isOpened = (opened: Record<string, number>, t: WfTicket, now: number) => (opened[t.id] ?? -Infinity) > now - STARTED_MS
111
112/** The frontier tickets no new chat was opened on yet: what "Work next" and "Start all" take. */
113const takeable = (map: WfMap, opened: Record<string, number>, now: number) =>
114  map.tickets.filter(t => t.isFrontier && !isOpened(opened, t, now))
115
116/** Where a Work button works, from the setting and the surface it was pressed on. */
117const chatFor = (): 'app' | 'terminal' | 'here' =>
118  workIn === 'here' || drawnOn === 'mobile' ? 'here' : drawnOn === 'desktop' ? 'app' : 'terminal'
119
120function ioFor($: EngineInterface): Io {
121  return {
122    list: path => $.fs.list(path),
123    read: async path => String(await $.fs.read(path)),
124    run: (argv, cwd) => $.process.run(argv, { cwd, timeoutMs: 30_000 }),
125  }
126}
127
128/**
129 * Rescans the project. A quiet refresh (the background polls) draws nothing
130 * while it runs, and nothing at all when the maps did not change.
131 */
132async function refresh($: EngineInterface, github: boolean, isQuiet: boolean) {
133  if (isRefreshing) {
134    queued = (queued ?? false) || github
135    return
136  }
137  isRefreshing = true
138  if (!isQuiet) await update($, isLoading, () => true)
139  try {
140    const io = ioFor($)
141    const root = await $.session.root()
142    const errors: string[] = []
143    const mdPromise = loadMarkdownMaps(io, root).catch(error => {
144      errors.push(`Markdown: ${String(error)}`)
145      return [] as WfMap[]
146    })
147    if (github || lastGithubAt === 0) {
148      lastGithubAt = await $.clock.now()
149      const repo = await githubRepo(io, root)
150      if (repo) {
151        const r = await loadGithubMaps(io, root, repo).catch(error => ({ maps: [] as WfMap[], error: String(error) }))
152        githubMaps = r.maps
153        githubError = r.error
154      } else {
155        githubMaps = []
156        githubError = undefined
157      }
158    }
159    if (githubError) errors.push(githubError)
160    const isFinished = (m: WfMap) => Number(m.status === 'done' || m.status === 'graduated')
161    const all = [...githubMaps, ...(await mdPromise)].sort(
162      (a, b) =>
163        Number(a.kind === 'spec') - Number(b.kind === 'spec') || isFinished(a) - isFinished(b) || a.title.localeCompare(b.title),
164    )
165    const next: WfData = { root, maps: all, loadedAt: await $.clock.now(), errors }
166    const prev = await read($, data)
167    const isSame = prev !== null && JSON.stringify({ ...prev, loadedAt: 0 }) === JSON.stringify({ ...next, loadedAt: 0 })
168    if (!isSame) await update($, data, () => next)
169  } finally {
170    isRefreshing = false
171    if (!isQuiet) await update($, isLoading, () => false)
172  }
173  if (queued !== null) {
174    const fetchGithub = queued
175    queued = null
176    await refresh($, fetchGithub, true)
177  }
178}
179
180async function openDrawer($: EngineInterface) {
181  await $.ui.open({ id: PANE, title: TITLE })
182  await update($, isPaneOpen, () => true)
183  void refresh($, true, false)
184}
185
186async function pollIfOpen($: EngineInterface, github: boolean) {
187  const isOpen = (await $.ui.panes()).some(p => p.id === PANE)
188  if (isOpen) await refresh($, github, true)
189}
190
191/** Brings the drawer's window back to its top, or to one element; best effort. */
192async function scrollTo($: EngineInterface, to: 'start' | { key: string }) {
193  try {
194    await $.ui.scroll({ to, in: PANE, block: to === 'start' ? 'start' : 'center' })
195  } catch {
196    // The pane may not be placed (a narrow terminal); nothing to scroll.
197  }
198}
199
200/** Shows one ticket on a page of its own: its body is read first, so the page draws once. */
201async function openTicket($: EngineInterface, map: WfMap, ticket: WfTicket) {
202  await update($, copied, () => null)
203  const io = ioFor($)
204  const root = (await read($, data))?.root ?? (await $.session.root())
205  let body: string
206  if (map.source === 'github' && ticket.url) body = await githubIssueBody(io, root, ticket.url)
207  else body = ticket.path ? await readText(io, ticket.path) : ''
208  body = stripHeaderFields(body.replace(/^\uFEFF?# .*\r?\n/, '')).trim()
209  let links: { href: string; path: string }[] = []
210  if (ticket.path) ({ text: body, links } = absolutizeLinks(body, ticket.path))
211  if (body.length > 9000) body = body.slice(0, 9000) + '\n\n_…truncated; open the file for the rest._'
212  await update($, detail, () => ({ id: ticket.id, body: body || '_This ticket has no body yet._', links }))
213  await update($, view, v => ({ ...v, mapId: map.id, ticketId: ticket.id }))
214  await scrollTo($, 'start')
215}
216
217/** Back from a ticket's page to its map, with that ticket's card in view. */
218async function backToMap($: EngineInterface) {
219  const from = (await read($, view)).ticketId
220  await update($, view, v => ({ ...v, ticketId: null }))
221  if (from) await scrollTo($, { key: `t:${from}` })
222}
223
224async function openMap($: EngineInterface, mapId: string | null) {
225  await update($, copied, () => null)
226  await update($, view, v => ({ ...v, mapId, ticketId: null }))
227  await scrollTo($, 'start')
228}
229
230/** The prompt a Work button sends: the configured template, filled in for the map or spec, or one ticket. */
231function promptFor(root: string, map: WfMap, ticket: WfTicket | null, isWave = false) {
232  const mapRef = map.source === 'github' ? (map.url ?? map.ref) : map.ref
233  const ticketRef = ticket ? (ticket.path ? relative(root, ticket.path) : (ticket.url ?? ticket.ref)) : ''
234  const isSpec = map.kind === 'spec'
235  const template = isWave
236    ? prompts.frontier
237    : !ticket
238      ? isSpec
239        ? prompts.spec
240        : prompts.map
241      : isSpec
242        ? prompts.specTicket
243        : prompts.mapTicket
244  return fill(template, { map: mapRef, ticket: ticketRef, title: ticket?.title ?? map.title }).trim()
245}
246
247async function platformOf($: EngineInterface): Promise<Platform> {
248  if (platform) return platform
249  if ((await $.env.get('OS')) === 'Windows_NT') platform = 'windows'
250  else {
251    const r = await $.process.run(['uname', '-s'], { timeoutMs: 5_000 }).catch(() => null)
252    platform = r?.stdout.trim() === 'Darwin' ? 'mac' : 'linux'
253  }
254  return platform
255}
256
257/**
258 * Opens one new chat: an empty desktop-app session in the project, or a
259 * terminal window on `prompt`. What was run, or null when the host could not run it.
260 */
261async function openChat($: EngineInterface, how: 'app' | 'terminal', prompt: string, root: string, title: string) {
262  const p = await platformOf($)
263  const launch: Launch = how === 'app' ? appChat(p) : terminalChat(prompt, root, title, p)
264  const r = await $.process.run(launch.argv, { cwd: launch.cwd ?? root, timeoutMs: 15_000 }).catch(() => null)
265  return r?.exitCode === 0 ? launch : null
266}
267
268/** Puts `text` on the clipboard: through the surface, else the host's own tool. True when it took. */
269async function copyText($: EngineInterface, text: string): Promise<boolean> {
270  const surface = drawnOn === 'desktop' || drawnOn === 'terminal' || drawnOn === 'vscode' ? drawnOn : undefined
271  const viaSurface = await $.ui.copy({ text, surface }).catch(() => null)
272  if (viaSurface?.isCopied) return true
273  const r = await $.process.run(clipboardArgv(await platformOf($)), { stdin: text, timeoutMs: 5_000 }).catch(() => null)
274  return r?.exitCode === 0
275}
276
277/** Keeps the tickets just opened in new chats out of "Work next" until their chats claim them. */
278async function markOpened($: EngineInterface, ids: string[]) {
279  if (ids.length === 0) return
280  const now = await $.clock.now()
281  await update($, started, prev => {
282    const kept = Object.fromEntries(Object.entries(prev ?? {}).filter(([, at]) => at > now - STARTED_MS))
283    for (const id of ids) kept[id] = now
284    return kept
285  })
286}
287
288/**
289 * Works the map or spec, one ticket, or (`wave`) a spec's frontier tickets
290 * at once: in a new chat with no context, or here (the `workIn` setting).
291 */
292async function work($: EngineInterface, map: WfMap, ticket: WfTicket | null, wave: WfTicket[] = []) {
293  const root = (await read($, data))?.root ?? (await $.session.root())
294  const text = promptFor(root, map, ticket, wave.length > 0)
295  const how = chatFor()
296  if (how === 'here') {
297    // A slash command (a skill) runs as one; anything else is sent as a prompt.
298    const slash = text.match(/^\/(\S+)\s*([\s\S]*)$/)
299    if (slash) await $.command.run({ command: slash[1]!, args: slash[2] ?? '' })
300    else await $.prompt.submit({ text, asUser: true })
301    $.ui.toast(`Started: ${text}`)
302    return
303  }
304  const name = ticket ? ticket.ref : wave.length > 0 ? `the frontier (${wave.map(t => t.ref).join(' ')})` : `the ${map.kind}`
305  if (how === 'app') {
306    // The app opens a new chat but never runs a command for it: the person pastes the copied one.
307    const isCopied = await copyText($, text)
308    const keys = pasteKeys(await platformOf($))
309    const project = folderName(root)
310    await update($, copied, () => ({ text, isCopied, keys }))
311    $.ui.toast(
312      isCopied
313        ? `Copied ${text}. Opening a new chat: with ${project} selected under the prompt, paste it (${keys}) and press Enter.`
314        : `Could not copy. Opening a new chat: with ${project} selected under the prompt, type ${text} there.`,
315      { timeoutMs: 10_000 },
316    )
317    // Long enough to read the toast before the app moves to the new chat.
318    await $.clock.sleep(OPEN_AFTER_MS)
319    if (!(await openChat($, 'app', text, root, ''))) {
320      $.ui.toast(`Could not open a new chat. Open one in this project and paste ${text}.`, { timeoutMs: 10_000 })
321      return
322    }
323    await markOpened($, ticket ? [ticket.id] : wave.map(t => t.id))
324    return
325  }
326  const opened = await openChat($, how, text, root, `Wayfinder ${ticket?.ref ?? map.kind}`)
327  if (!opened) {
328    $.ui.toast(`Could not open a new chat. Its prompt: ${text}`, { timeoutMs: 10_000 })
329    return
330  }
331  await markOpened($, ticket ? [ticket.id] : wave.map(t => t.id))
332  $.ui.toast(opened.startsAtOnce ? `New chat working on ${name}` : `New chat on ${name}: press Enter there to start`)
333}
334
335
336// ── Drawing ──────────────────────────────────────────────────────────
337// Native elements only: the surface's own type, colors and theme. The one
338// color the drawer adds is each status's, on its glyph and its card's edge.
339
340type Els = ReturnType<EngineInterface['ui']['resolve']>
341
342/**
343 * The mod's mark: a trail blaze, the painted bar a hiker follows, before the
344 * name. One text cell, so the terminal and the desktop draw it alike.
345 */
346function mark(el: Els) {
347  const { Box, Text } = el
348  return (
349    <Box flexDirection="row" flexShrink={0}>
350      <Text color={STATUS_STYLE.open.fill}>▍</Text>
351      <Text bold>Wayfinder</Text>
352    </Box>
353  )
354}
355
356function header($: EngineInterface, el: Els, loading: boolean) {
357  const { Box, Text, Button } = el
358  return (
359    <Box flexDirection="row" justifyContent="space-between">
360      {mark(el)}
361      <Box flexDirection="row" gap={1}>
362        {loading && <Text dimColor>refreshing…</Text>}
363        <Button key="refresh" label="Refresh" hotkey="r" plain onPress={bind('refresh', () => refresh($, true, false))} />
364      </Box>
365    </Box>
366  )
367}
368
369function mapList($: EngineInterface, el: Els, d: WfData) {
370  const { Box, Text, Button } = el
371  const maps = d.maps.filter(m => m.kind === 'map')
372  const specs = d.maps.filter(m => m.kind === 'spec')
373  const row = (m: WfMap) => {
374    const c = counts(m.tickets)
375    const st = MAP_STATUS_LABEL[m.status]
376    return (
377      <Box key={`row:${m.id}`} flexDirection="column" marginBottom={1}>
378        <Button key={`open:${m.id}`} label={m.title} plain onPress={bind(`open:${m.id}`, () => openMap($, m.id))} />
379        <Box flexDirection="row" gap={1} flexWrap="wrap">
380          <Text color={st.color}>● {st.text}</Text>
381          <Text dimColor>{m.source === 'github' ? `GitHub ${m.ref}` : m.dir}</Text>
382        </Box>
383        <Box flexDirection="row" gap={1} flexWrap="wrap">
384          <Text color={STATUS_STYLE.done.fill}>{bar(c.done, c.total)}</Text>
385          <Text dimColor>
386            {c.done}/{c.total} done
387            {c.frontier ? ` · ${c.frontier} frontier` : ''}
388            {c.claimed ? ` · ${c.claimed} claimed` : ''}
389            {c.waiting ? ` · ${c.waiting} waiting` : ''}
390            {c.blocked ? ` · ${c.blocked} blocked` : ''}
391          </Text>
392        </Box>
393      </Box>
394    )
395  }
396  return (
397    <Box flexDirection="column" gap={1}>
398      {d.maps.length === 0 && (
399        <Text dimColor>
400          No wayfinder maps here. A map is a folder with a map.md beside issues/ or tickets/, or a GitHub issue labelled
401          wayfinder:map.
402        </Text>
403      )}
404      {maps.length > 0 && <Text bold>Maps · {maps.length}</Text>}
405      {maps.map(row)}
406      {specs.length > 0 && <Text bold>Specs · {specs.length}</Text>}
407      {specs.map(row)}
408      {d.errors.map(err => (
409        <Text color={STATUS_STYLE.waiting.fill}>{err}</Text>
410      ))}
411    </Box>
412  )
413}
414
415/**
416 * What a card holds besides its header: the title wrapped to the card (a
417 * Button draws on one line, so a line each) and the one-line "after" list.
418 */
419function cardContent(t: WfTicket, width: number, byNum: Map<number, WfTicket>) {
420  const blockers = t.blockedBy.map(n => byNum.get(n)).filter((x): x is WfTicket => !!x)
421  return {
422    lines: wrapLines(t.title, width - 4, 3),
423    after: afterLine(
424      blockers.map(b => ({ ref: b.ref, glyph: STATUS_STYLE[b.status].glyph })),
425      width - 4,
426    ),
427  }
428}
429
430/**
431 * One ticket as a card, its status's color on the edge. Where the surface
432 * runs surface modules (terminal, desktop) the card is a `Client`, so the
433 * whole card is one click target (see card.tsx); elsewhere its title lines
434 * are the buttons.
435 */
436function ticketCard(
437  $: EngineInterface,
438  el: Els,
439  map: WfMap,
440  t: WfTicket,
441  width: number,
442  byNum: Map<number, WfTicket>,
443  isNewChat: boolean,
444  height: number,
445) {
446  const { Box, Text, Button } = el
447  const st = STATUS_STYLE[t.status]
448  const closed = isClosed(t)
449  const status = statusText(t, isNewChat)
450  const { lines, after: afterText } = cardContent(t, width, byNum)
451  if ('Client' in el) {
452    const { Client } = el
453    const props: CardProps = {
454      id: t.id,
455      ref: t.ref,
456      type: (t.type ?? '').toUpperCase(),
457      lines,
458      status,
459      color: st.fill,
460      glyph: st.glyph,
461      after: afterText,
462      isClosed: closed,
463      width,
464      height,
465    }
466    // An explicit height: left to the module, the pane measures before it draws and cuts the last card.
467    return <Client key={`card:${t.id}`} module="./card.tsx" props={props} width={width} height={height} />
468  }
469  const open = bind(`t:${t.id}`, () => openTicket($, map, t))
470  return (
471    <Box
472      key={`card:${t.id}`}
473      flexDirection="column"
474      width={width}
475      height={height}
476      borderStyle="round"
477      borderColor={st.fill}
478      borderDimColor={closed}
479      paddingX={1}
480    >
481      <Box flexDirection="row" justifyContent="space-between" gap={1}>
482        <Box flexDirection="row" gap={1} flexShrink={0}>
483          <Text color={st.fill}>{st.glyph}</Text>
484          <Text bold dimColor={closed}>
485            {t.ref}
486          </Text>
487          {t.type && <Text dimColor>{t.type.toUpperCase()}</Text>}
488        </Box>
489        <Text color={closed ? undefined : st.fill} dimColor={closed}>
490          {status}
491        </Text>
492      </Box>
493      {lines.map((line, i) => (
494        <Button key={i === 0 ? `t:${t.id}` : `t:${t.id}#${i + 1}`} label={line} plain dimColor={closed} onPress={i === 0 ? open : bind(`t:${t.id}#${i + 1}`, () => openTicket($, map, t))} />
495      ))}
496      <Box flexGrow={1} />
497      {afterText && (
498        <Text dimColor wrap="truncate-end">
499          {afterText}
500        </Text>
501      )}
502    </Box>
503  )
504}
505
506/** Steps, top to bottom: a ticket sits one step below the last of its blockers; cards flow across each step. */
507function stepsView($: EngineInterface, el: Els, map: WfMap, shown: WfTicket[], columns: number, newChat: Set<string>) {
508  const { Box, Text } = el
509  const byNum = new Map(map.tickets.map(t => [t.num, t]))
510  const layerOf = layers(shown)
511  const steps = new Map<number, WfTicket[]>()
512  for (const t of shown) {
513    const l = layerOf.get(t.num) ?? 0
514    steps.set(l, [...(steps.get(l) ?? []), t])
515  }
516  const { cardWidth, gap } = cardLayout(columns)
517  // Every card on the board takes the height of the tallest, so they line up.
518  const height = Math.max(...shown.map(t => cardRows(cardContent(t, cardWidth, byNum))))
519  return (
520    <Box flexDirection="column" gap={1}>
521      {[...steps.keys()]
522        .sort((a, b) => a - b)
523        .map((l, i) => {
524          const tickets = steps.get(l)!
525          const done = tickets.filter(isClosed).length
526          return (
527            <Box key={`step:${l}`} flexDirection="column" gap={1}>
528              <Box flexDirection="row" gap={1}>
529                <Text bold dimColor>
530                  STEP {i + 1}
531                </Text>
532                <Text dimColor>· {done === tickets.length ? 'all done' : `${done} of ${tickets.length} done`}</Text>
533              </Box>
534              <Box flexDirection="row" flexWrap="wrap" columnGap={gap} rowGap={1}>
535                {tickets.map(t => ticketCard($, el, map, t, cardWidth, byNum, newChat.has(t.id), height))}
536              </Box>
537            </Box>
538          )
539        })}
540    </Box>
541  )
542}
543
544/** The same tickets as an indented tree: each under the first ticket that blocks it. */
545function treeView($: EngineInterface, el: Els, map: WfMap, shown: WfTicket[]) {
546  const { Box, Text, Button } = el
547  return (
548    <Box flexDirection="column">
549      {treeRows(shown).map(({ ticket: t, depth, isRepeat, extraParents }, i) => {
550        const st = STATUS_STYLE[t.status]
551        return (
552          <Box key={`r:${i}`} flexDirection="row" marginLeft={depth * 2}>
553            <Text color={st.fill}>
554              {depth > 0 ? '└ ' : ''}
555              {st.glyph}{' '}
556            </Text>
557            {isRepeat ? (
558              <Text dimColor>
559                {t.ref} {t.title} ↑
560              </Text>
561            ) : (
562              <Button
563                key={`t:${t.id}`}
564                label={`${t.ref} ${t.title}`}
565                plain
566                dimColor={isClosed(t)}
567                onPress={bind(`t:${t.id}`, () => openTicket($, map, t))}
568              />
569            )}
570            {!isRepeat && t.type && <Text dimColor> · {t.type}</Text>}
571            {!isRepeat && extraParents.length > 0 && <Text dimColor> · also after {extraParents.join(', ')}</Text>}
572          </Box>
573        )
574      })}
575    </Box>
576  )
577}
578
579/** The status chips: each one both counts its tickets and shows only them. */
580const CHIPS: { filter: WfFilter; label: string }[] = [
581  { filter: 'all', label: 'All' },
582  { filter: 'unresolved', label: 'To do' },
583  { filter: 'frontier', label: `${STATUS_STYLE.open.glyph} Frontier` },
584  { filter: 'claimed', label: `${STATUS_STYLE.claimed.glyph} Claimed` },
585  { filter: 'waiting', label: `${STATUS_STYLE.waiting.glyph} Waiting on you` },
586  { filter: 'blocked', label: `${STATUS_STYLE.blocked.glyph} Blocked` },
587  { filter: 'done', label: `${STATUS_STYLE.done.glyph} Done` },
588]
589
590type Launches = { opened: Record<string, number>; now: number; copied: WfCopied }
591
592/** What the last Work button copied, for the person coming back from the new chat. */
593function pasteNote(el: Els, c: WfCopied) {
594  const { Text } = el
595  if (!c) return ''
596  return (
597    <Text dimColor wrap="wrap">
598      {c.isCopied
599        ? `✓ Copied ${c.text} · paste it in the new chat (${c.keys}) and press Enter`
600        : `Could not copy · type ${c.text} in the new chat`}
601    </Text>
602  )
603}
604
605function mapView($: EngineInterface, el: Els, map: WfMap, v: WfView, columns: number, launches: Launches) {
606  const { Box, Text, Button, Markdown, Link } = el
607  const c = counts(map.tickets)
608  const st = MAP_STATUS_LABEL[map.status]
609  const filter: WfFilter = CHIPS.some(x => x.filter === v.filter) ? v.filter : 'all'
610  const shown = visible(map.tickets, filter)
611  const ready = takeable(map, launches.opened, launches.now)
612  const nextUp = ready[0]
613  const newChat = new Set(map.tickets.filter(t => isOpened(launches.opened, t, launches.now)).map(t => t.id))
614  const isLive = map.status !== 'done' && map.status !== 'graduated'
615  // ↗ where the work opens in another chat, → where it runs in this one.
616  const arrow = chatFor() === 'here' ? '→' : '↗'
617  const countOf: Record<WfFilter, number> = {
618    all: c.total,
619    unresolved: c.total - c.done,
620    frontier: c.frontier,
621    claimed: c.claimed,
622    waiting: c.waiting,
623    blocked: c.blocked,
624    done: c.done,
625  }
626  const layoutButton = (layout: WfLayout, label: string) => (
627    <Button
628      key={`layout:${layout}`}
629      label={label}
630      variant={(v.layout ?? 'steps') === layout ? 'primary' : 'secondary'}
631      onPress={bind(`layout:${layout}`, () => update($, view, x => ({ ...x, layout })))}
632    />
633  )
634  return (
635    <Box flexDirection="column" gap={1}>
636      <Box flexDirection="row" justifyContent="space-between" gap={1}>
637        <Button key="back" label="← All maps" plain hotkey="b" onPress={bind('back', () => openMap($, null))} />
638        <Box flexDirection="row" gap={1} flexShrink={0}>
639          <Text dimColor>View</Text>
640          {layoutButton('steps', 'Steps')}
641          {layoutButton('tree', 'Tree')}
642        </Box>
643      </Box>
644      <Box flexDirection="column">
645        <Text bold wrap="wrap">
646          {map.title}
647        </Text>
648        <Box flexDirection="row" gap={1} flexWrap="wrap">
649          <Text color={st.color}>● {st.text}</Text>
650          <Text dimColor>· {map.kind} · {map.source === 'github' ? `GitHub ${map.ref}` : map.dir} ·</Text>
651          {map.url ? <Link href={map.url} label="Open map ↗" /> : map.path ? <Markdown text={`[Open ${map.kind} ↗](${fileUrl(map.path)})`} /> : ''}
652        </Box>
653      </Box>
654      <Box flexDirection="row" gap={2} flexWrap="wrap" alignItems="center">
655        <Box flexDirection="row" gap={1} flexShrink={0}>
656          <Text color={STATUS_STYLE.done.fill}>{bar(c.done, c.total, 20)}</Text>
657          <Text>
658            {c.done} of {c.total} done
659          </Text>
660        </Box>
661        {isLive && map.kind === 'map' && (
662          <Button
663            key="work-next"
664            label={nextUp ? `Work next: ${nextUp.ref} ${arrow}` : `Work the map ${arrow}`}
665            variant="primary"
666            onPress={bind('work-next', () => work($, map, nextUp ?? null))}
667          />
668        )}
669        {/* A spec is implemented in waves (its frontier, then stop) or whole; each runs a subagent per ticket. */}
670        {isLive && map.kind === 'spec' && ready.length > 0 && (
671          <Button
672            key="work-frontier"
673            label={`Implement frontier · ${ready.length} ${arrow}`}
674            variant="primary"
675            onPress={bind('work-frontier', () => work($, map, null, ready))}
676          />
677        )}
678        {isLive && map.kind === 'spec' && c.done < c.total && (
679          <Button key="work-spec" label={`Implement spec ${arrow}`} variant="secondary" onPress={bind('work-spec', () => work($, map, null))} />
680        )}
681      </Box>
682      {pasteNote(el, launches.copied)}
683      <Box flexDirection="row" gap={1} flexWrap="wrap">
684        {CHIPS.filter(x => x.filter === 'all' || x.filter === 'unresolved' || x.filter === 'frontier' || countOf[x.filter] > 0).map(x => (
685          <Button
686            key={`filter:${x.filter}`}
687            label={`${x.label} ${countOf[x.filter]}`}
688            variant={filter === x.filter ? 'primary' : 'secondary'}
689            onPress={bind(`filter:${x.filter}`, () => update($, view, y => ({ ...y, filter: x.filter })))}
690          />
691        ))}
692      </Box>
693      {shown.length === 0 && (
694        <Text dimColor>
695          {filter === 'frontier' ? 'Nothing is ready to take: every open ticket is blocked or claimed.' : 'No tickets match this filter.'}
696        </Text>
697      )}
698      {shown.length > 0 && (v.layout === 'tree' ? treeView($, el, map, shown) : stepsView($, el, map, shown, columns, newChat))}
699    </Box>
700  )
701}
702
703/** A ticket on a page of its own: what it waits on, what waits on it, its body and actions. */
704function ticketPage($: EngineInterface, el: Els, map: WfMap, t: WfTicket, det: WfDetail, launches: Launches) {
705  const { Box, Text, Button, Markdown, Link } = el
706  const st = STATUS_STYLE[t.status]
707  const isNewChat = isOpened(launches.opened, t, launches.now)
708  const byNum = new Map(map.tickets.map(x => [x.num, x]))
709  const after = t.blockedBy.map(n => byNum.get(n)).filter((x): x is WfTicket => !!x)
710  const unblocks = dependents(map.tickets, t.num)
711  const link = (x: WfTicket, prefix: string) => (
712    <Box key={`${prefix}:${x.id}`} flexDirection="row" gap={1}>
713      <Text color={STATUS_STYLE[x.status].fill}>{STATUS_STYLE[x.status].glyph}</Text>
714      <Button
715        key={`${prefix}:${x.id}`}
716        label={`${x.ref} ${x.title}`}
717        plain
718        dimColor={isClosed(x)}
719        onPress={bind(`${prefix}:${x.id}`, () => openTicket($, map, x))}
720      />
721      <Text dimColor>{statusText(x)}</Text>
722    </Box>
723  )
724  // A link in the body to another ticket of this map opens it here (where the surface hands link clicks over).
725  const byPath = new Map(map.tickets.filter(x => x.path).map(x => [norm(x.path!), x]))
726  const ticketLinks = (det?.id === t.id ? (det.links ?? []) : []).filter(l => byPath.has(norm(l.path)))
727  return (
728    <Box flexDirection="column" gap={1}>
729      <Button key="back-map" label="← Back to map" plain hotkey="b" onPress={bind('back-map', () => backToMap($))} />
730      <Text dimColor wrap="truncate-end">
731        {map.title}
732      </Text>
733      <Box flexDirection="column" borderStyle="round" borderColor={st.fill} paddingX={1}>
734        <Box flexDirection="row" gap={1} flexWrap="wrap">
735          <Text color={st.fill}>{st.glyph}</Text>
736          <Text bold>{t.ref}</Text>
737          {t.type && <Text dimColor>{t.type.toUpperCase()}</Text>}
738          <Text color={st.fill}>{statusText(t, isNewChat)}</Text>
739          {t.rawStatus && !['open', 'closed', st.label].includes(t.rawStatus.toLowerCase()) && <Text dimColor>({t.rawStatus})</Text>}
740        </Box>
741        <Text bold wrap="wrap">
742          {t.title}
743        </Text>
744      </Box>
745      <Box flexDirection="row" gap={2} flexWrap="wrap" alignItems="center">
746        {!isClosed(t) && (
747          <Button
748            key={`work:${t.id}`}
749            label={`Work this ticket ${chatFor() === 'here' ? '→' : '↗'}`}
750            variant="primary"
751            onPress={bind(`work:${t.id}`, () => work($, map, t))}
752          />
753        )}
754        {t.url ? <Link href={t.url} label="Open issue ↗" /> : t.path ? <Markdown text={`[Open file ↗](${fileUrl(t.path)})`} /> : ''}
755      </Box>
756      {pasteNote(el, launches.copied)}
757      {after.length > 0 && (
758        <Box flexDirection="column">
759          <Text dimColor bold>
760            WAITS ON
761          </Text>
762          {after.map(x => link(x, 'dep'))}
763        </Box>
764      )}
765      {unblocks.length > 0 && (
766        <Box flexDirection="column">
767          <Text dimColor bold>
768            UNBLOCKS
769          </Text>
770          {unblocks.map(x => link(x, 'next'))}
771        </Box>
772      )}
773      {ticketLinks.length > 0 ? (
774        <Markdown
775          key="body"
776          text={det!.body}
777          pressableLinks={ticketLinks.map(l => l.href)}
778          onLinkPress={link => {
779            const target = ticketLinks.find(l => l.href === link.href)
780            const x = target ? byPath.get(norm(target.path)) : undefined
781            if (x) void openTicket($, map, x)
782          }}
783        />
784      ) : (
785        <Markdown text={det?.id === t.id ? det.body : '_Loading…_'} />
786      )}
787    </Box>
788  )
789}
790
791export const register: Register = (on, options) => {
792  if (options.workIn === 'new-chat' || options.workIn === 'here') workIn = options.workIn
793  if (typeof options.mapPrompt === 'string') prompts.map = options.mapPrompt
794  if (typeof options.mapTicketPrompt === 'string') prompts.mapTicket = options.mapTicketPrompt
795  if (typeof options.specTicketPrompt === 'string') prompts.specTicket = options.specTicketPrompt
796  if (typeof options.specPrompt === 'string') prompts.spec = options.specPrompt
797  if (typeof options.frontierPrompt === 'string') prompts.frontier = options.frontierPrompt
798
799  on('session.start', async ($, e, next) => {
800    await $.command.register({
801      name: 'wayfinder-maps',
802      description: 'Open the Wayfinder drawer: every map and spec in this project, their tickets and dependencies',
803    })
804    $.clock.every(POLL_MS, () => void pollIfOpen($, false))
805    // A first scan in the background, so the band can offer the drawer in a wayfinder project.
806    $.clock.after(500, () => void refresh($, false, true).then(() => platformOf($)))
807    return next(e)
808  })
809
810  on('command.run', { command: 'wayfinder-maps' }, async $ => {
811    await openDrawer($)
812    return { text: 'Wayfinder drawer opened.' }
813  })
814
815  // Desktop: the click that brings the focus onto a button is the press (see ClickGate).
816  on('ui.focus', async ($, e, next) => {
817    const result = await next(e)
818    const isOurs = (e.requestId === PANE || e.component === 'AbovePrompt') && (!e.plugin || e.plugin === 'wayfinder-maps')
819    if (!isOurs || 'deny' in result) return result
820    const handler = e.element ? handlers.get(e.element) : undefined
821    const now = await $.clock.now()
822    const isPerson = e.origin.kind === 'person'
823    if (gate.focus({ key: e.element, isPerson, isDesktop: drawnOn === 'desktop', now }) && handler) handler()
824    return result
825  }).catch(($, e, next) => next(e))
826
827  on('ui.press', async ($, e, next) => {
828    if (!handlers.has(e.element)) return next(e)
829    if (!gate.press(e.element, await $.clock.now())) return { element: e.element }
830    return next(e)
831  })
832
833  // A ticket card (card.tsx) posts `{ open: id }` when clicked anywhere.
834  on('ui.message', async ($, e, next) => {
835    const open = (e.data as { open?: unknown } | null)?.open
836    if (e.requestId !== PANE || typeof open !== 'string') return next(e)
837    const d = await read($, data)
838    const v = await read($, view)
839    const map = d?.maps.find(m => m.id === v.mapId)
840    const ticket = map?.tickets.find(t => t.id === open)
841    if (map && ticket) await openTicket($, map, ticket)
842    return {}
843  })
844
845  on('ui.close', async ($, e, next) => {
846    const result = await next(e)
847    if (e.id === PANE) await update($, isPaneOpen, () => false)
848    return result
849  }).catch(($, e, next) => next(e))
850
851  // The band above the prompt: shown only where the project has maps, and only while the drawer is closed.
852  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
853    const d = await read($, data)
854    const open = await read($, isPaneOpen)
855    if (e.props.hasSurvey || open || !d || d.maps.length === 0) return next(e)
856    drawnOn = e.surface
857    const el = $.ui.resolve(e)
858    const { Box, Text, Button } = el
859    const live = d.maps.filter(m => m.status !== 'done' && m.status !== 'graduated')
860    const all = live.flatMap(m => m.tickets)
861    const frontier = all.filter(t => t.isFrontier).length
862    const waiting = all.filter(t => t.status === 'waiting').length
863    const maps = d.maps.filter(m => m.kind === 'map').length
864    const specs = d.maps.length - maps
865    const summary = [
866      maps ? `${maps} map${maps === 1 ? '' : 's'}` : '',
867      specs ? `${specs} spec${specs === 1 ? '' : 's'}` : '',
868      frontier ? `${frontier} ready to take` : '',
869      waiting ? `${waiting} waiting on you` : '',
870    ]
871      .filter(Boolean)
872      .join(' · ')
873    return (
874      <Box flexDirection="row" gap={1}>
875        {mark(el)}
876        <Text dimColor>·</Text>
877        <Text dimColor>{summary}</Text>
878        <Button key="open-drawer" label="Open map drawer" plain onPress={bind('open-drawer', () => openDrawer($))} />
879      </Box>
880    )
881  })
882
883  on('turn.complete', async ($, e, next) => {
884    const result = await next(e)
885    if (e.agentId === undefined) {
886      const now = await $.clock.now()
887      void pollIfOpen($, now - lastGithubAt > GITHUB_EVERY_MS)
888    }
889    return result
890  })
891
892  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
893    drawnOn = e.surface
894    const el = $.ui.resolve(e)
895    const { Box, Text } = el
896    const d = await read($, data)
897    const loading = await read($, isLoading)
898    const v = await read($, view)
899    const columns = Math.max(20, (e.props.bodyColumns ?? 60) - 2)
900    const top = header($, el, loading)
901
902    if (!d) {
903      return (
904        <Box flexDirection="column" gap={1}>
905          {top}
906          <Text dimColor>{loading ? 'Looking for maps…' : 'Press Refresh to scan this project.'}</Text>
907        </Box>
908      )
909    }
910    const map = v.mapId ? d.maps.find(m => m.id === v.mapId) : undefined
911    const ticket = map && v.ticketId ? map.tickets.find(t => t.id === v.ticketId) : undefined
912    // `started` may predate a hot reload that added it.
913    const launches: Launches = { opened: (await read($, started)) ?? {}, now: await $.clock.now(), copied: (await read($, copied)) ?? null }
914    const body = !map
915      ? mapList($, el, d)
916      : ticket
917        ? ticketPage($, el, map, ticket, await read($, detail), launches)
918        : mapView($, el, map, v, columns, launches)
919    return (
920      <Box flexDirection="column" gap={1} paddingBottom={1}>
921        {top}
922        {body}
923      </Box>
924    )
925  })
926}
927
hooks/card.tsx 77 lines
1import type { ClientModule } from 'claude-code'
2
3/** What the hooks module hands a ticket card: everything it draws, as plain data. */
4export type CardProps = {
5  id: string
6  ref: string
7  type: string
8  /** The title, already wrapped to the card's width: the card's height is known before it draws. */
9  lines: string[]
10  status: string
11  color: string
12  glyph: string
13  after: string
14  isClosed: boolean
15  width: number
16  /** Every card on a board is this tall, the tallest card's rows, so cards line up. */
17  height: number
18}
19
20type CardState = { isHover: boolean }
21
22/**
23 * One ticket card, drawn by a surface module so the whole card is one target:
24 * a click anywhere on it, or Enter while it has the focus, posts `{ open }`
25 * to the hooks module, and the pointer over it lights the whole card.
26 */
27const TicketCard: ClientModule<CardProps, CardState> = (p, surface) => {
28  const { Box, Text } = surface.elements
29  const isHover = surface.state?.isHover ?? false
30
31  // Set on every draw (each call replaces the last), so a handler never holds stale props.
32  surface.onPointer(e => {
33    if (e.type === 'enter' && !isHover) surface.setState({ isHover: true })
34    if (e.type === 'leave' && isHover) surface.setState({ isHover: false })
35    // Before the first layout the region's size is 0: a click then is taken as inside.
36    const isLaidOut = surface.columns > 0 && surface.rows > 0
37    const isInside = e.x >= 0 && e.y >= 0 && (!isLaidOut || (e.x < surface.columns && e.y < surface.rows))
38    if (e.type === 'up' && e.button === 'left' && isInside) surface.post({ open: p.id })
39  })
40  surface.onKey(e => {
41    if (e.key === 'return' || e.key === ' ') surface.post({ open: p.id })
42  })
43
44  const isDim = p.isClosed && !isHover
45  return (
46    <Box flexDirection="column" width={p.width} height={p.height} borderStyle="round" borderColor={p.color} borderDimColor={isDim} paddingX={1}>
47      <Box flexDirection="row" justifyContent="space-between" gap={1}>
48        <Box flexDirection="row" gap={1} flexShrink={0}>
49          <Text color={p.color}>{p.glyph}</Text>
50          <Text bold dimColor={isDim}>
51            {p.ref}
52          </Text>
53          {p.type ? <Text dimColor>{p.type}</Text> : ''}
54        </Box>
55        <Text color={p.isClosed ? undefined : p.color} dimColor={p.isClosed}>
56          {p.status}
57        </Text>
58      </Box>
59      {p.lines.map(line => (
60        <Text dimColor={isDim} underline={isHover} wrap="truncate-end">
61          {line}
62        </Text>
63      ))}
64      <Box flexGrow={1} />
65      {p.after ? (
66        <Text dimColor wrap="truncate-end">
67          {p.after}
68        </Text>
69      ) : (
70        ''
71      )}
72    </Box>
73  )
74}
75
76export default TicketCard
77
hooks/clicks.ts 44 lines
1/**
2 * Decides which focus moves and presses run a Button's action.
3 *
4 * The desktop app gives a Button the focus on the first click and presses it
5 * only on a second one. So on desktop a person's focus move onto one of our
6 * buttons runs its action, and the gate keeps each click to one action:
7 *
8 * - focus landing again on the button that already holds the ring (a redraw
9 *   re-seating it) runs nothing;
10 * - a press, or a repeat focus, on a button whose action ran in the last
11 *   ECHO_MS runs nothing (one click raising both events).
12 */
13export const ECHO_MS = 600
14
15export type GateFocus = { key: string | undefined; isPerson: boolean; isDesktop: boolean; now: number }
16
17export class ClickGate {
18  private ring: string | undefined
19  private last = { key: '', at: -Infinity }
20
21  /** True when this focus move should run the button's action. */
22  focus({ key, isPerson, isDesktop, now }: GateFocus): boolean {
23    const previous = this.ring
24    this.ring = key
25    if (!key || !isPerson || !isDesktop) return false
26    if (key === previous) return false
27    if (this.isEcho(key, now)) return false
28    this.last = { key, at: now }
29    return true
30  }
31
32  /** True when this press should run the button's action. */
33  press(key: string, now: number): boolean {
34    this.ring = key
35    if (this.isEcho(key, now)) return false
36    this.last = { key, at: now }
37    return true
38  }
39
40  private isEcho(key: string, now: number): boolean {
41    return this.last.key === key && now - this.last.at < ECHO_MS
42  }
43}
44
hooks/github.ts 191 lines
1
2import type { WfMap, WfStatus } from '../types'
3import { finishTickets, mapStatus } from './parse'
4import type { Io } from './parse'
5import type { ParsedTicketFile } from './parse'
6
7type GhIssue = {
8  number: number
9  title: string
10  state: 'OPEN' | 'CLOSED'
11  stateReason?: string | null
12  url: string
13  body?: string
14  assignees?: { nodes: { login: string }[] }
15  labels?: { nodes: { name: string }[] }
16  blockedBy?: { nodes: { number: number }[] }
17  subIssues?: { totalCount?: number; nodes: GhIssue[] }
18}
19
20const CHILD = `number title state stateReason url body
21  assignees(first: 3) { nodes { login } }
22  labels(first: 10) { nodes { name } }
23  blockedBy(first: 30) { nodes { number } }
24  subIssues(first: 1) { totalCount }`
25
26const HEAD = `number title state stateReason url body labels(first: 10) { nodes { name } } subIssues(first: 100) { nodes { ${CHILD} } }`
27
28const MAPS_QUERY = `query($owner: String!, $name: String!) {
29  repository(owner: $owner, name: $name) {
30    issues(first: 50, labels: ["wayfinder:map"], states: [OPEN, CLOSED], orderBy: { field: CREATED_AT, direction: DESC }) {
31      nodes { ${HEAD} }
32    }
33  }
34}`
35
36/** A graduated spec is an issue titled `Spec: …` (or labelled `wayfinder:spec`); search finds both. */
37const SPECS_QUERY = `query($byTitle: String!, $byLabel: String!) {
38  byTitle: search(query: $byTitle, type: ISSUE, first: 50) { nodes { ... on Issue { ${HEAD} } } }
39  byLabel: search(query: $byLabel, type: ISSUE, first: 20) { nodes { ... on Issue { ${HEAD} } } }
40}`
41const SPEC_TITLE = /^\s*spec\s*[:·—–-]/i
42
43async function gh(io: Io, root: string, args: string[]): Promise<{ ok: boolean; out: string; err: string }> {
44  try {
45    const r = await io.run(['gh', ...args], root)
46    return { ok: r.exitCode === 0, out: r.stdout, err: r.stderr }
47  } catch (error) {
48    return { ok: false, out: '', err: String(error) }
49  }
50}
51
52/** `owner/name` of the repo's GitHub remote, or null when it has none (or gh is missing). */
53export async function githubRepo(io: Io, root: string): Promise<string | null> {
54  const r = await gh(io, root, ['repo', 'view', '--json', 'nameWithOwner', '-q', '.nameWithOwner'])
55  return r.ok && r.out.trim() ? r.out.trim() : null
56}
57
58/** Without native links: `- [ ] #12` task-list children on the map, `Blocked by: #3` lines on the child. */
59function taskListNumbers(body: string): number[] {
60  return [...body.matchAll(/^\s*[-*]\s+\[[ xX]\]\s+.*?#(\d+)/gm)].map(m => Number(m[1]))
61}
62/** `Blocked by: #3 #4` near the top, or a `## Blocked by` heading (or bare `Blocked by:` line) over a `- #3` list. */
63function bodyBlockers(body: string): number[] {
64  const lines = body.split(/\r?\n/)
65  const line = lines.slice(0, 15).find(l => /^\**blocked by\**\s*:/i.test(l))
66  if (line && /#\d+/.test(line)) return [...line.matchAll(/#(\d+)/g)].map(m => Number(m[1]))
67  const start = lines.findIndex(l => /^\s*(#{1,6}\s*)?\**blocked by\**\s*:?\s*\**\s*$/i.test(l))
68  if (start < 0) return []
69  const found: number[] = []
70  for (const l of lines.slice(start + 1)) {
71    if (/^\s*#{1,6}\s/.test(l)) break
72    const item = l.match(/^\s*[-*]\s+(?:\[[ xX]\]\s+)?.*?#(\d+)/)
73    if (item) found.push(Number(item[1]))
74    else if (l.trim() !== '') break
75  }
76  return found
77}
78
79async function fetchByNumber(io: Io, root: string, owner: string, name: string, numbers: number[]): Promise<GhIssue[]> {
80  if (numbers.length === 0) return []
81  const fields = numbers.map(n => `i${n}: issue(number: ${n}) { ${CHILD} }`).join('\n')
82  const q = `query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${fields} } }`
83  const r = await gh(io, root, ['api', 'graphql', '-f', `query=${q}`, '-F', `owner=${owner}`, '-F', `name=${name}`])
84  if (!r.ok) return []
85  const repo = JSON.parse(r.out).data?.repository ?? {}
86  return Object.values(repo).filter(Boolean) as GhIssue[]
87}
88
89/**
90 * Children that have sub-issues of their own are groups (GitHub caps a parent at 100 sub-issues,
91 * so a big spec groups its tickets, by build step say): their sub-issues are the tickets.
92 */
93async function expandGroups(io: Io, root: string, owner: string, name: string, children: GhIssue[]): Promise<GhIssue[]> {
94  const groups = children.filter(c => (c.subIssues?.totalCount ?? 0) > 0)
95  if (groups.length === 0) return children
96  const fields = groups.map(g => `g${g.number}: issue(number: ${g.number}) { subIssues(first: 100) { nodes { ${CHILD} } } }`).join('\n')
97  const q = `query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${fields} } }`
98  const r = await gh(io, root, ['api', 'graphql', '-f', `query=${q}`, '-F', `owner=${owner}`, '-F', `name=${name}`])
99  if (!r.ok) return children
100  const repo = JSON.parse(r.out).data?.repository ?? {}
101  const inner = new Map(groups.map(g => [g.number, (repo[`g${g.number}`]?.subIssues?.nodes ?? []) as GhIssue[]]))
102  return children.flatMap(c => inner.get(c.number) ?? [c])
103}
104
105function toTicket(issue: GhIssue): ParsedTicketFile & { closedAs?: WfStatus } {
106  const labels = issue.labels?.nodes.map(l => l.name) ?? []
107  const type = labels.find(l => l.startsWith('wayfinder:'))?.slice('wayfinder:'.length)
108  const native = issue.blockedBy?.nodes.map(n => n.number) ?? []
109  const closedAs: WfStatus | undefined =
110    issue.state === 'CLOSED' ? (issue.stateReason === 'NOT_PLANNED' ? 'dropped' : 'done') : undefined
111  const awaiting = labels.some(l => /awaiting|ready-for-human|needs-human/.test(l))
112  return {
113    id: issue.url,
114    num: issue.number,
115    ref: `#${issue.number}`,
116    title: issue.title,
117    rawStatus: closedAs ? 'closed' : awaiting ? 'awaiting' : 'open',
118    closedAs,
119    type: type && type !== 'map' ? type : undefined,
120    assignee: issue.assignees?.nodes[0]?.login,
121    blockedBy: native.length > 0 ? native : bodyBlockers(issue.body ?? ''),
122    url: issue.url,
123  }
124}
125
126/** The spec issues of the repo: titled `Spec: …` or labelled `wayfinder:spec`, maps left out. */
127async function findSpecs(io: Io, root: string, repo: string): Promise<GhIssue[]> {
128  const r = await gh(io, root, [
129    'api', 'graphql',
130    '-f', `query=${SPECS_QUERY}`,
131    '-f', `byTitle=repo:${repo} is:issue in:title spec`,
132    '-f', `byLabel=repo:${repo} is:issue label:"wayfinder:spec"`,
133  ])
134  if (!r.ok) return []
135  const data = JSON.parse(r.out).data ?? {}
136  const found = new Map<number, GhIssue>()
137  for (const issue of [...(data.byTitle?.nodes ?? []), ...(data.byLabel?.nodes ?? [])] as GhIssue[]) {
138    if (!issue?.number) continue
139    const labels = issue.labels?.nodes.map(l => l.name) ?? []
140    if (labels.includes('wayfinder:map')) continue
141    if (labels.includes('wayfinder:spec') || SPEC_TITLE.test(issue.title)) found.set(issue.number, issue)
142  }
143  return [...found.values()]
144}
145
146/** Loads every `wayfinder:map` issue and every spec issue of the repo with their sub-issues and blocking edges. */
147export async function loadGithubMaps(io: Io, root: string, repo: string): Promise<{ maps: WfMap[]; error?: string }> {
148  const [owner = '', name = ''] = repo.split('/')
149  const [r, specIssues] = await Promise.all([
150    gh(io, root, ['api', 'graphql', '-f', `query=${MAPS_QUERY}`, '-F', `owner=${owner}`, '-F', `name=${name}`]),
151    findSpecs(io, root, repo),
152  ])
153  if (!r.ok) return { maps: [], error: `GitHub: ${(r.err || r.out).trim().split('\n')[0]}` }
154  const mapIssues: GhIssue[] = JSON.parse(r.out).data?.repository?.issues?.nodes ?? []
155  // A spec names the map it graduated from: `Parent map: #1`.
156  const graduated = new Set(
157    specIssues.flatMap(s => [...(s.body ?? '').matchAll(/parent map\**\s*:\**\s*#(\d+)/gi)].map(m => Number(m[1]))),
158  )
159
160  const load = async (issue: GhIssue, kind: WfMap['kind']): Promise<WfMap> => {
161    let children = issue.subIssues?.nodes ?? []
162    if (children.length === 0) {
163      children = await fetchByNumber(io, root, owner, name, taskListNumbers(issue.body ?? ''))
164    }
165    children = await expandGroups(io, root, owner, name, children)
166    const tickets = finishTickets(children.map(toTicket))
167    const isClosed = issue.state === 'CLOSED'
168    return {
169      id: `gh:${repo}#${issue.number}`,
170      kind,
171      source: 'github',
172      title: issue.title,
173      ref: `#${issue.number}`,
174      url: issue.url,
175      status: mapStatus(kind, tickets, isClosed ? 'closed' : undefined, kind === 'map' && graduated.has(issue.number)),
176      tickets,
177    }
178  }
179  const maps = await Promise.all([...mapIssues.map(i => load(i, 'map')), ...specIssues.map(i => load(i, 'spec'))])
180  return { maps }
181}
182
183/** A ticket's full body and comments, for the details view. */
184export async function githubIssueBody(io: Io, root: string, url: string): Promise<string> {
185  const r = await gh(io, root, ['issue', 'view', url, '--json', 'body,comments', '-q', '{body: .body, comments: [.comments[] | {author: .author.login, body: .body}]}'])
186  if (!r.ok) return `_Could not load the issue: ${r.err.trim()}_`
187  const data = JSON.parse(r.out) as { body: string; comments: { author: string; body: string }[] }
188  const comments = data.comments.map(c => `**${c.author}:**\n\n${c.body}`).join('\n\n---\n\n')
189  return comments ? `${data.body}\n\n## Comments\n\n${comments}` : data.body
190}
191
hooks/graph.ts 106 lines
1import type { WfStatus, WfTicket } from '../types'
2
3/**
4 * Each status's color and glyph: the only color the drawer adds to the
5 * surface's own theme. Mid-tone hues, legible on light and dark alike.
6 */
7export const STATUS_STYLE: Record<WfStatus, { fill: string; label: string; glyph: string }> = {
8  open: { fill: '#e8702a', label: 'frontier', glyph: '⚑' },
9  claimed: { fill: '#4a86e8', label: 'claimed', glyph: '◐' },
10  waiting: { fill: '#d4a017', label: 'waiting on you', glyph: '◷' },
11  blocked: { fill: '#8a8f98', label: 'blocked', glyph: '◌' },
12  done: { fill: '#3fa36b', label: 'done', glyph: '✓' },
13  dropped: { fill: '#8a8f98', label: 'out of scope', glyph: '✕' },
14}
15
16/** Layer = longest chain of blockers above it, within the shown set. */
17export function layers(tickets: WfTicket[]): Map<number, number> {
18  const byNum = new Map(tickets.map(t => [t.num, t]))
19  const memo = new Map<number, number>()
20  const visit = (num: number, seen: Set<number>): number => {
21    if (memo.has(num)) return memo.get(num)!
22    if (seen.has(num)) return 0
23    seen.add(num)
24    const t = byNum.get(num)!
25    const parents = t.blockedBy.filter(n => byNum.has(n))
26    const layer = parents.length === 0 ? 0 : 1 + Math.max(...parents.map(p => visit(p, seen)))
27    seen.delete(num)
28    memo.set(num, layer)
29    return layer
30  }
31  for (const t of tickets) visit(t.num, new Set())
32  return memo
33}
34
35/** The tickets a ticket blocks: what opens up once it is done. */
36export function dependents(tickets: WfTicket[], num: number): WfTicket[] {
37  return tickets.filter(t => t.blockedBy.includes(num))
38}
39
40export const CARD_MIN = 30
41export const CARD_MAX = 52
42export const CARD_GAP = 2
43
44/**
45 * How many cards fit across `columns` cells and how wide each is: as many as
46 * fit at CARD_MIN, widened to share the row, one full-width card when narrow.
47 */
48export function cardLayout(columns: number): { perRow: number; cardWidth: number; gap: number } {
49  const perRow = Math.max(1, Math.floor((columns + CARD_GAP) / (CARD_MIN + CARD_GAP)))
50  const cardWidth = Math.min(CARD_MAX, Math.floor((columns - CARD_GAP * (perRow - 1)) / perRow))
51  return { perRow, cardWidth: Math.max(Math.min(columns, CARD_MIN), cardWidth), gap: CARD_GAP }
52}
53
54/** Rows a ticket card takes: its border, the header, the title lines and the "after" line. */
55export const cardRows = (card: { lines: readonly string[]; after: string }) => 2 + 1 + card.lines.length + (card.after ? 1 : 0)
56
57/**
58 * A card's "after" line, kept to one line of `width` cells: the blockers that
59 * fit, then `… +N` for the rest, which the ticket itself lists in full.
60 */
61export function afterLine(blockers: readonly { ref: string; glyph: string }[], width: number): string {
62  if (blockers.length === 0) return ''
63  const items = blockers.map(b => `${b.ref} ${b.glyph}`)
64  const full = `after ${items.join('  ')}`
65  if (full.length <= width) return full
66  let text = 'after'
67  for (let i = 0; i < items.length; i++) {
68    const next = `${text}${i === 0 ? ' ' : '  '}${items[i]}`
69    const tail = `  … +${items.length - i - 1}`
70    if (next.length + tail.length > width) return `${text}${i === 0 ? ' ' : '  '}… +${items.length - i}`
71    text = next
72  }
73  return text
74}
75
76/**
77 * The same graph as an indented tree: each ticket under the first ticket that
78 * blocks it, later mentions as a pointer back. Rows in display order.
79 */
80export function treeRows(tickets: WfTicket[]): { ticket: WfTicket; depth: number; isRepeat: boolean; extraParents: number[] }[] {
81  const shown = new Set(tickets.map(t => t.num))
82  const children = new Map<number, WfTicket[]>()
83  const roots: WfTicket[] = []
84  for (const t of tickets) {
85    const parents = t.blockedBy.filter(n => shown.has(n))
86    if (parents.length === 0) roots.push(t)
87    else for (const p of parents) children.set(p, [...(children.get(p) ?? []), t])
88  }
89  const rows: { ticket: WfTicket; depth: number; isRepeat: boolean; extraParents: number[] }[] = []
90  const placed = new Set<number>()
91  const walk = (t: WfTicket, depth: number, parent: number | null) => {
92    if (placed.has(t.num)) {
93      rows.push({ ticket: t, depth, isRepeat: true, extraParents: [] })
94      return
95    }
96    placed.add(t.num)
97    const extraParents = t.blockedBy.filter(n => shown.has(n) && n !== parent)
98    rows.push({ ticket: t, depth, isRepeat: false, extraParents })
99    for (const c of children.get(t.num) ?? []) walk(c, depth + 1, t.num)
100  }
101  for (const r of roots) walk(r, 0, null)
102  // Cycles leave tickets unplaced: show them at the top level.
103  for (const t of tickets) if (!placed.has(t.num)) walk(t, 0, null)
104  return rows
105}
106
hooks/launch.ts 72 lines
1/**
2 * How a Work button opens a new chat on a ticket: the command line the host
3 * runs (no shell), built here so tests reach it without the engine.
4 */
5export type Platform = 'windows' | 'mac' | 'linux'
6
7export type Launch = {
8  argv: string[]
9  /** Where to run it; absent, the project root. */
10  cwd?: string
11  /** True when the chat starts working at once; false when its prompt waits for Enter. */
12  startsAtOnce: boolean
13}
14
15/**
16 * The desktop app's link to its new-session page. It names no folder: a
17 * `folder` makes the app ask "Trust this workspace?", and trusting the folder
18 * already selected there leaves the page's folder and branch broken. The
19 * page keeps the folder last chosen; the toast names the project to check.
20 * It carries no prompt either: the app turns the `/` of a slash command in
21 * one into `/`, so a link can never run a skill. The person pastes the
22 * copied command instead.
23 */
24export const appLink = () => 'claude://code/new'
25
26/** A folder's own name, the last part of its path, as the app's folder picker shows it. */
27export const folderName = (path: string) => path.split(/[\\/]+/).filter(Boolean).pop() ?? path
28
29/** Claude Code's link to a new terminal session in `cwd`, the prompt filled in (not sent). */
30export const cliLink = (prompt: string, cwd: string) =>
31  `claude-cli://open?q=${encodeURIComponent(prompt)}&cwd=${encodeURIComponent(cwd)}`
32
33/** Opens a link with the system's handler for its scheme. */
34export function openLink(url: string, platform: Platform): string[] {
35  // rundll32 hands the link to the shell as is; `start` would read the `&` in it.
36  if (platform === 'windows') return ['rundll32.exe', 'url.dll,FileProtocolHandler', url]
37  return [platform === 'mac' ? 'open' : 'xdg-open', url]
38}
39
40/** A new, empty session in the desktop app, in the folder its picker holds. */
41export const appChat = (platform: Platform): Launch => ({
42  argv: openLink(appLink(), platform),
43  startsAtOnce: false,
44})
45
46/** The host's own clipboard tool, reading the text on stdin: where the surface takes no copy. */
47export function clipboardArgv(platform: Platform): string[] {
48  if (platform === 'windows') return ['clip.exe']
49  if (platform === 'mac') return ['pbcopy']
50  return ['sh', '-c', 'wl-copy 2>/dev/null || xclip -selection clipboard']
51}
52
53/** The paste shortcut, as the person's keyboard spells it. */
54export const pasteKeys = (platform: Platform) => (platform === 'mac' ? '⌘V' : 'Ctrl+V')
55
56// cmd.exe reads its own command line: these end or change it, quoted or not.
57const CMD_UNSAFE = /["%^&|<>!\r\n]/
58
59/**
60 * A terminal window of its own. On Windows `start` opens one running
61 * `claude <prompt>`, so the chat starts at once; elsewhere, or for a prompt
62 * cmd.exe would misread, Claude Code's link opens the person's terminal with
63 * the prompt filled in.
64 */
65export function terminalChat(prompt: string, root: string, title: string, platform: Platform): Launch {
66  if (platform === 'windows' && !CMD_UNSAFE.test(prompt) && !CMD_UNSAFE.test(title) && title.includes(' ')) {
67    // `start` takes its first quoted argument as the window's title; the space gets it quoted.
68    return { argv: ['cmd.exe', '/d', '/c', 'start', title, 'claude', prompt], cwd: root, startsAtOnce: true }
69  }
70  return { argv: openLink(cliLink(prompt, root), platform), startsAtOnce: false }
71}
72
hooks/markdown.ts 103 lines
1import type { WfMap } from '../types'
2import { finishTickets, mapStatus, parseHeadDoc, parseTicketFile } from './parse'
3import type { Io } from './parse'
4import type { ParsedTicketFile } from './parse'
5
6/** Folders never worth descending into. */
7const NEVER = new Set(['node_modules', '.git', '.pnpm-store', '.venv', 'venv', '__pycache__', 'worktrees'])
8/** Code and build folders, skipped outside planning folders (an effort may well be named build). */
9const CODE = new Set(['dist', 'build', 'out', 'coverage', 'target', 'vendor', '.next', '.turbo', '.cache', 'src', 'assets', 'designs', 'research', 'spikes'])
10/** Where efforts live: inside these, every folder name is fair game. */
11const PLANNING = /(^|\/)(\.scratch|\.wayfinder|\.planning|docs|planning|wayfinder)(\/|$)/
12const TICKET_DIRS = ['issues', 'tickets']
13const MAX_DEPTH = 4
14
15const join = (a: string, b: string) => (a.endsWith('/') || a.endsWith('\\') ? a + b : `${a}/${b}`)
16
17async function list(io: Io, path: string) {
18  try {
19    return await io.list(path)
20  } catch {
21    return []
22  }
23}
24
25async function readText(io: Io, path: string): Promise<string> {
26  try {
27    return await io.read(path)
28  } catch {
29    return ''
30  }
31}
32
33/** Every folder holding a `map.md` / `spec.md` beside an `issues/` or `tickets/` folder, to MAX_DEPTH. */
34async function findEffortDirs(io: Io, root: string): Promise<{ dir: string; rel: string; names: Set<string> }[]> {
35  const found: { dir: string; rel: string; names: Set<string> }[] = []
36  let frontier: { dir: string; rel: string }[] = [{ dir: root, rel: '' }]
37  for (let depth = 0; depth <= MAX_DEPTH && frontier.length > 0; depth++) {
38    const next: { dir: string; rel: string }[] = []
39    await Promise.all(
40      frontier.map(async ({ dir, rel }) => {
41        const entries = await list(io, dir)
42        const names = new Set(entries.map(e => e.name))
43        const ticketDir = TICKET_DIRS.find(d => entries.some(e => e.name === d && e.kind === 'dir'))
44        if (ticketDir && rel !== '') found.push({ dir, rel, names })
45        for (const e of entries) {
46          if (e.kind !== 'dir' || NEVER.has(e.name) || TICKET_DIRS.includes(e.name)) continue
47          if (CODE.has(e.name) && !PLANNING.test(rel)) continue
48          if (e.name.startsWith('.') && !['.scratch', '.wayfinder', '.planning'].includes(e.name)) continue
49          next.push({ dir: join(dir, e.name), rel: rel ? `${rel}/${e.name}` : e.name })
50        }
51      }),
52    )
53    frontier = next
54  }
55  return found
56}
57
58/** Loads every markdown map and spec under the project root. */
59export async function loadMarkdownMaps(io: Io, root: string): Promise<WfMap[]> {
60  const dirs = await findEffortDirs(io, root)
61  const maps = await Promise.all(
62    dirs.map(async ({ dir, rel, names }): Promise<WfMap | null> => {
63      const ticketDirName = TICKET_DIRS.find(d => names.has(d))!
64      const ticketDir = join(dir, ticketDirName)
65      const files = (await list(io, ticketDir)).filter(e => e.kind === 'file' && /^\d+-.*\.md$/.test(e.name))
66      const parsed = (
67        await Promise.all(
68          files.map(async f => {
69            const path = join(ticketDir, f.name)
70            return parseTicketFile(f.name, path, await readText(io, path))
71          }),
72        )
73      ).filter((t): t is ParsedTicketFile => t !== null)
74
75      const hasMap = names.has('map.md')
76      const hasSpec = names.has('spec.md')
77      // A plain issues folder only counts when its files look like tracker tickets.
78      if (!hasMap && !hasSpec && !parsed.some(t => t.rawStatus !== '')) return null
79      if (parsed.length === 0 && !hasMap) return null
80
81      const kind: WfMap['kind'] = hasMap ? 'map' : 'spec'
82      const headPath = join(dir, hasMap ? 'map.md' : hasSpec ? 'spec.md' : '')
83      const head = hasMap || hasSpec ? parseHeadDoc(await readText(io, headPath)) : {}
84      const tickets = finishTickets(parsed)
85      const folder = rel.split('/').pop() ?? rel
86      return {
87        id: `md:${rel}`,
88        kind,
89        source: 'md',
90        title: head.title ?? folder,
91        ref: hasMap || hasSpec ? `${rel}/${hasMap ? 'map.md' : 'spec.md'}` : rel,
92        dir: rel,
93        path: hasMap || hasSpec ? headPath : dir,
94        status: mapStatus(kind, tickets, head.status, hasSpec),
95        tickets,
96      }
97    }),
98  )
99  return maps.filter((m): m is WfMap => m !== null)
100}
101
102export { readText }
103
hooks/parse.ts 147 lines
1import type { WfMap, WfMapStatus, WfStatus, WfTicket } from '../types'
2
3const HEADER_FIELD = /^\*{0,2}(type|status|assignee|blocked by)\s*:\s*\*{0,2}\s*(.*)$/i
4
5/** Folds the many status words the trackers use into five buckets. */
6export function normalizeStatus(raw: string): WfStatus {
7  const s = raw.trim().toLowerCase()
8  if (/^(resolved|done|closed|complete|completed|shipped|merged)\b/.test(s)) return 'done'
9  if (/^(claimed|in[- ]progress|wip|doing|active)\b/.test(s)) return 'claimed'
10  if (/^(awaiting|ready-for-human|needs-human|waiting|blocked-on-human)/.test(s)) return 'waiting'
11  if (/^(out[- ]of[- ]scope|dropped|wontfix|won't fix|not[- ]planned)/.test(s)) return 'dropped'
12  return 'open'
13}
14
15/** Leading ticket numbers out of `03, 07`, `#12 #13`, `106 — Versions`. */
16function numbersIn(text: string): number[] {
17  if (/^\s*(none|n\/a|-|—|nothing)?\s*$/i.test(text)) return []
18  return text
19    .split(/[,;]|\band\b/)
20    .map(part => part.trim().match(/^#?(\d+)/))
21    .filter((m): m is RegExpMatchArray => m !== null)
22    .map(m => Number(m[1]))
23}
24
25function cleanTitle(title: string, num: number): string {
26  return title
27    .replace(/^#+\s*/, '')
28    .replace(new RegExp(`^0*${num}\\s*[—–·:.\\-]\\s*`), '')
29    .replace(/^map\s*[·:—-]\s*/i, '')
30    .trim()
31}
32
33export type ParsedTicketFile = Omit<WfTicket, 'status' | 'isFrontier'> & { rawStatus: string }
34
35/** Reads one ticket file: `NN-slug.md` with `Type:` / `Status:` / `Blocked by:` lines up top. */
36export function parseTicketFile(fileName: string, path: string, text: string): ParsedTicketFile | null {
37  const numMatch = fileName.match(/^(\d+)-.*\.md$/)
38  if (!numMatch || /\.brief\.md$/.test(fileName)) return null
39  const num = Number(numMatch[1])
40  const lines = text.split(/\r?\n/)
41  let title = fileName.replace(/^\d+-/, '').replace(/\.md$/, '').replace(/-/g, ' ')
42  let rawStatus = ''
43  let type: string | undefined
44  let assignee: string | undefined
45  const blockedBy: number[] = []
46  let inBlockedList = false
47
48  for (const line of lines) {
49    if (/^## /.test(line) || /^- \[[ x]\]/i.test(line)) break
50    if (/^# /.test(line)) {
51      title = cleanTitle(line, num)
52      continue
53    }
54    const field = line.match(HEADER_FIELD)
55    if (field) {
56      inBlockedList = false
57      const [, key = '', value = ''] = field
58      const name = key.toLowerCase()
59      if (name === 'status') rawStatus = value.replace(/\*+/g, '').trim()
60      else if (name === 'type') type = value.replace(/\*+/g, '').trim() || undefined
61      else if (name === 'assignee') assignee = value.replace(/\*+/g, '').trim() || undefined
62      else if (name === 'blocked by') {
63        blockedBy.push(...numbersIn(value))
64        inBlockedList = value.trim() === ''
65      }
66      continue
67    }
68    if (inBlockedList) {
69      const item = line.match(/^\s*[-*]\s+#?(\d+)/)
70      if (item) blockedBy.push(Number(item[1]))
71      else if (line.trim() !== '') inBlockedList = false
72    }
73  }
74
75  return {
76    id: path,
77    num,
78    ref: String(numMatch[1]),
79    title,
80    rawStatus,
81    type,
82    assignee,
83    blockedBy: [...new Set(blockedBy)].filter(n => n !== num),
84    path,
85  }
86}
87
88/** The map's or spec's own title and any `Status:` line it carries. */
89export function parseHeadDoc(text: string): { title?: string; status?: string } {
90  let title: string | undefined
91  let status: string | undefined
92  for (const line of text.split(/\r?\n/).slice(0, 30)) {
93    if (!title && /^# /.test(line)) title = cleanTitle(line, -1)
94    const field = line.match(HEADER_FIELD)
95    if (field && field[1]?.toLowerCase() === 'status') status = (field[2] ?? '').replace(/\*+/g, '').trim()
96  }
97  return { title, status }
98}
99
100/** Finalises tickets: blocked when any blocker inside the map is unfinished; frontier = open, unblocked, unclaimed. */
101export function finishTickets(parsed: (ParsedTicketFile & { closedAs?: WfStatus })[]): WfTicket[] {
102  const base = new Map(parsed.map(t => [t.num, t.closedAs ?? normalizeStatus(t.rawStatus)]))
103  return parsed
104    .map(t => {
105      let status = base.get(t.num) as WfStatus
106      const openBlockers = t.blockedBy.filter(n => {
107        const s = base.get(n)
108        return s !== undefined && s !== 'done' && s !== 'dropped'
109      })
110      if (status === 'open' && t.assignee && !/^(none|-|—)$/i.test(t.assignee)) status = 'claimed'
111      if (status === 'open' && openBlockers.length > 0) status = 'blocked'
112      const { closedAs: _closedAs, ...rest } = t
113      return { ...rest, status, isFrontier: status === 'open' }
114    })
115    .sort((a, b) => a.num - b.num)
116}
117
118export function mapStatus(kind: WfMap['kind'], tickets: WfTicket[], headStatus: string | undefined, hasSpec: boolean): WfMapStatus {
119  if (headStatus && normalizeStatus(headStatus) === 'done') return 'done'
120  if (kind === 'map' && hasSpec) return 'graduated'
121  const live = tickets.filter(t => t.status !== 'dropped')
122  if (live.length > 0 && live.every(t => t.status === 'done')) return 'done'
123  if (live.some(t => t.status === 'claimed' || t.status === 'done')) return 'active'
124  return 'open'
125}
126
127export function counts(tickets: WfTicket[]) {
128  const c = { total: 0, done: 0, claimed: 0, waiting: 0, blocked: 0, frontier: 0 }
129  for (const t of tickets) {
130    if (t.status === 'dropped') continue
131    c.total += 1
132    if (t.status === 'done') c.done += 1
133    else if (t.status === 'claimed') c.claimed += 1
134    else if (t.status === 'waiting') c.waiting += 1
135    else if (t.status === 'blocked') c.blocked += 1
136    else c.frontier += 1
137  }
138  return c
139}
140
141/** What the loaders need from the host, handed in by the hooks module. */
142export type Io = {
143  list: (path: string) => Promise<readonly { name: string; kind: string }[]>
144  read: (path: string) => Promise<string>
145  run: (argv: string[], cwd: string) => Promise<{ exitCode: number | null; stdout: string; stderr: string }>
146}
147
hooks/text.ts 94 lines
1/** Text shaping for the drawer: ticket bodies made readable there, titles fitted to cards. */
2
3const FIELD = /^\*{0,2}(type|status|assignee|blocked by|label|charted)\s*:\s*\*{0,2}/i
4
5/**
6 * Drops the tracker's header lines (`Type:`, `Status:`, `Blocked by:` and its
7 * list) from above a ticket's first section: the drawer shows them already.
8 */
9export function stripHeaderFields(body: string): string {
10  const lines = body.split(/\r?\n/)
11  const out: string[] = []
12  let inSections = false
13  let inBlockedList = false
14  for (const line of lines) {
15    if (!inSections && /^## /.test(line)) inSections = true
16    if (inSections) {
17      out.push(line)
18      continue
19    }
20    if (FIELD.test(line)) {
21      inBlockedList = /^\*{0,2}blocked by\s*:\s*\*{0,2}\s*$/i.test(line)
22      continue
23    }
24    if (inBlockedList && /^\s*[-*]\s+/.test(line)) continue
25    if (line.trim() !== '') inBlockedList = false
26    out.push(line)
27  }
28  return out.join('\n').replace(/^\s+/, '').replace(/\n{3,}/g, '\n\n')
29}
30
31/** Joins a relative link onto a folder, resolving `.` and `..`, with forward slashes. */
32export function resolvePath(dir: string, rel: string): string {
33  const parts = dir.replace(/\\/g, '/').split('/')
34  for (const seg of rel.replace(/\\/g, '/').split('/')) {
35    if (seg === '' || seg === '.') continue
36    if (seg === '..') parts.length > 1 && parts.pop()
37    else parts.push(seg)
38  }
39  return parts.join('/').replace(/\/{2,}/g, '/')
40}
41
42export const fileUrl = (path: string) =>
43  'file:///' + encodeURI(path.replace(/\\/g, '/').replace(/^\/+/, '')).replace(/#/g, '%23').replace(/\?/g, '%3F')
44
45/**
46 * Makes a markdown file's relative links work outside its folder: each
47 * becomes an absolute `file:` link. Returns the new text and every link it
48 * rewrote, with the file it points at.
49 */
50export function absolutizeLinks(body: string, filePath: string): { text: string; links: { href: string; path: string }[] } {
51  const dir = filePath.replace(/\\/g, '/').replace(/\/[^/]*$/, '')
52  const links: { href: string; path: string }[] = []
53  const text = body.replace(/(\]\()([^)\s]+)((?:\s+"[^"]*")?\))/g, (whole, open: string, target: string, close: string) => {
54    if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith('#') || target.startsWith('/')) return whole
55    const [pathPart, anchor] = target.split('#') as [string, string | undefined]
56    let decoded = pathPart
57    try {
58      decoded = decodeURI(pathPart)
59    } catch {
60      // Keep it as written.
61    }
62    const path = resolvePath(dir, decoded)
63    const href = fileUrl(path) + (anchor ? `#${anchor}` : '')
64    links.push({ href, path })
65    return `${open}${href}${close}`
66  })
67  return { text, links }
68}
69
70/**
71 * Breaks a title into lines of at most `width` characters, at most `maxLines`
72 * of them, the last ending in an ellipsis when the title runs on.
73 */
74export function wrapLines(text: string, width: number, maxLines: number): string[] {
75  const w = Math.max(8, width)
76  const lines: string[] = []
77  let cur = ''
78  for (const word of text.split(/\s+/).filter(Boolean)) {
79    const next = cur ? `${cur} ${word}` : word
80    if (next.length <= w) {
81      cur = next
82      continue
83    }
84    if (cur) lines.push(cur)
85    cur = word.length > w ? word.slice(0, w - 1) + '…' : word
86  }
87  if (cur) lines.push(cur)
88  if (lines.length <= maxLines) return lines
89  const kept = lines.slice(0, maxLines)
90  const last = kept[maxLines - 1]!
91  kept[maxLines - 1] = (last.length + 2 > w ? last.slice(0, w - 2) : last) + ' …'
92  return kept
93}
94
types/index.d.ts 78 lines
1/** A ticket's state, folded from whatever its tracker writes. */
2export type WfStatus = 'done' | 'claimed' | 'waiting' | 'blocked' | 'open' | 'dropped'
3
4export type WfTicket = {
5  id: string
6  num: number
7  /** How a prompt names it: `07` for a file, `#42` for an issue. */
8  ref: string
9  title: string
10  rawStatus: string
11  status: WfStatus
12  /** Open, unblocked and unclaimed: takeable now. */
13  isFrontier: boolean
14  type?: string
15  assignee?: string
16  blockedBy: number[]
17  path?: string
18  url?: string
19}
20
21export type WfMapStatus = 'open' | 'active' | 'done' | 'graduated'
22
23export type WfMap = {
24  id: string
25  /** `map` is a wayfinder map of decision tickets; `spec` a graduated spec of implementation tickets. */
26  kind: 'map' | 'spec'
27  source: 'md' | 'github'
28  title: string
29  /** How a prompt names it: a relative path or `#12`. */
30  ref: string
31  /** Folder (md) relative to the project root. */
32  dir?: string
33  path?: string
34  url?: string
35  status: WfMapStatus
36  tickets: WfTicket[]
37}
38
39export type WfData = {
40  root: string
41  maps: WfMap[]
42  loadedAt: number
43  errors: string[]
44}
45
46export type WfFilter = 'all' | 'unresolved' | 'frontier' | 'claimed' | 'waiting' | 'blocked' | 'done'
47
48export type WfLayout = 'steps' | 'tree'
49
50export type WfView = {
51  mapId: string | null
52  /** The ticket shown on a page of its own, or null for the map. */
53  ticketId: string | null
54  filter: WfFilter
55  layout: WfLayout
56}
57
58/** The command a Work button copied for a new chat, whether it reached the clipboard, and the paste keys. */
59export type WfCopied = { text: string; isCopied: boolean; keys: string } | null
60
61/** The open ticket body as the drawer shows it, and the file links in it. */
62export type WfDetail = { id: string; body: string; links: { href: string; path: string }[] } | null
63
64declare module 'claude-code' {
65  interface PluginState {
66    'wayfinder-maps': {
67      data: WfData | null
68      isLoading: boolean
69      isPaneOpen: boolean
70      view: WfView
71      detail: WfDetail
72      /** Tickets a Work button opened a new chat on, by id: when. */
73      started: Record<string, number>
74      copied: WfCopied
75    }
76  }
77}
78