SLOPSHOPPER

loopd — pane (a mod that draws the board inside the session)

COMPANION, a mod. /pane opens a pane beside the session. In operator mode (the default) it draws the board — in-flight tasks, the need-you rail, per-project…

panecommandtimer
v3.1.0MITupdated 2026-10-20cbmono/loopd/plugin-mod-pane
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · loopd-mod-pane
│ ┃ loopd board ✕ › fix the failing auth test and add an audit log call │ ┃ not a loopd bundle — no instance.config.json │ ┃ in /work/app ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ [ Tick ] [ Refresh ] ⏺ 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 │ │ › /pane │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · loopd board
not a loopd bundle — no instance.config.json in /work/app [ Tick ] [ Refresh ]
README

loopd-mod-pane — the board-in-a-pane companion (a mod)

A mod: a hooks module Claude Code runs inside every session that loads it. This one adds /pane, which opens a pane drawing this bundle's board beside the transcript (or above the prompt in a narrow terminal), and nothing else.

One switch, mode, in /config (the plugin's userConfig; nothing else decides it):

modeDrawsReads
operator (default)the board below, with Tick and Refreshthe snapshot
simplean inbox — questions, stuck tasks, progress — and a form to start a project; nothing elsethe task documents and the form
/plugin marketplace add cbmono/loopd     # already added? skip
/plugin install loopd-mod-pane@loopd

Uninstall it (/plugin → Installed) and the three core renderers — build-board.sh, print-board.sh, watch-board.sh — are all there is, with no other edits anywhere. Absence is the safe behaviour, never an error.

What it draws — operator mode

The fourth renderer over the one board contract, plugin/scripts/write-snapshot.sh → .loopd/SNAPSHOT.json (docs/conventions.md §11 in cbmono/loopd). It reads the snapshot, never the bundle, so the snapshot writer's field allowlist holds here without being re-implemented: nothing this pane shows is anything the file does not already carry.

SectionFrom the snapshot's fields
headergroup, counts.projects, counts.tasks, counts.awaiting
need youthe AWAITING verbs — approve · answer · merge · unblock · close — counted off each task's awaiting verb, plus one close per project with awaiting_close (print-board.sh's rule)
in flighteach task with in_flight: <project slug>/<task id>, assignee (a role, never a person), status, the PR's pr_mergeable when prs is non-empty, title
projectsper project: slug, status, phase_progress.done/total, the task count, in-flight count, awaiting count, title
footergenerated_at — when the writer last wrote the file — and tick queued while a Tick is waiting for the session to go idle

Not drawn, because the snapshot does not carry it: a round number, a session id, a usage line, a continue verb, any question or blocker text, any document body, any author identity (owner is in the file for the HTML board's partitioning and is deliberately not drawn here), any URL. The two things that would make those appear are a field added to the writer — read its header first — or a second reader of the bundle, which this must never be.

Untrusted text, untrusted types. Every string passes one clean() for the terminal medium — every Unicode category-C code point is dropped (so ESC cannot repaint what you already read and a newline cannot forge a row), whitespace controls become one space — and every number passes one toint(), so a "tasks": "many" draws as 0 and never throws. A number is never truncated: a clipped count is a wrong count.

The pane redraws from the file every 5 seconds, by stat first and read only when the mtime moved; the poll starts when the pane opens and stops when it closes.

What it draws — simple mode

For someone who answers questions and does not run the loop. One inbox, top to bottom:

SectionShows
Questions for youevery unanswered open_questions entry across the projects, oldest task first (docs/operations.md → "The serve-time fill", the order rule): its task's timestamp:, then slug and task id, then Q<n> within the task — board-serve.sh's keys; undated last, deferred ones after that. Only the top one is open — its code and project, its text, Recommended: … (option 1 of its ### Q<n> block), the other options, a text field, More and Later — and n more after this counts the rest. Every other question is one line: code, project, text.
Stuck — you can helpeach status: blocked task, pink, in the same order (no field records when it became blocked), as one sentence — Unblock "…" in …: it cannot move until you do. — and one Unblock it button. Never its blocker text, and it opens no card: its open questions are in the section above.
Stuck — we're on iteach in-progress or in-review task with stall_count ≥ 1, quiet, never pink: "…" in …: nothing for you to do, we're on it. (last_blocker is not the test — stall-counter.sh keeps it after a reset.)
Progressper project, in creation order (project.md timestamp:, undated last), a done/total bar over its tasks (cancelled not counted); every finished project — status: done, or all its tasks done — folds into one green ✓ Finished: line
New projectNew project (Start your first project on an empty bundle); while a form is open it replaces the inbox — below

No role, tick, pull request, session, usage, round, worktree or branch is drawn; the kit test asserts their absence against task documents that carry all of them.

Pink means you, green means done. The open question's text and a blocked task's sentence are drawn #ff7ac2; a sent answer and the finished line #76d6a4 (Text's color prop); every other line keeps the theme default or dimColor.

Every button is one slash command ($.command.run, as Tick is), and every hotkey is unique on the screen:

KeyButtonRuns
1–9an option of the open question/loopd:answer <task> Q<n> <n>
—the text field/loopd:answer <task> Q<n> --text <words>
mMore/loopd:answer <task> Q<n> more
lLater/loopd:answer <task> Q<n> later — the question goes to the end; the next one opens
c d eUnblock it (the first three stuck tasks; the rest by click)/loopd:unblock <task> — the blocker is shown in the session, never here
nNew project/loopd:new-project — opens the form
—the form's text field: a field number, then the text/loopd:new-project <n> "<text>"
yStart the project (form)/loopd:new-project submit
xCancel (form)/loopd:new-project cancel — back to the board, nothing saved
rRefreshnothing — re-reads now

Keys act on the open card only. answer.sh and unblock.sh do the writing; this pane writes nothing. A run is a model turn queued until the session is idle, and it resolves when queued, before the document moves (measured on 2.1.300). While one is being queued the card shows Sending your answer to Q<n>… and has no buttons, so a second 1 runs nothing; once it is queued the line ✓ Sent your answer to Q<n> · project · task names it, the answered question is held out of the inbox until its document's mtime moves, and the next question opens in the same place — 1 five times answers five questions. A deferred one is held at the end until the later file moves. If the turn that ran it ends with nothing moved (answer.sh refused), the question comes back with a note. A refused run is drawn. A read that fails is retried on the next scan.

The new project form is the skill's, not the pane's. Five fields — 1 Title, 2 What, 3 For whom, 4 Done when, 5 Target repo (prefilled with defaultRepo) — live in one gitignored file, .loopd/.new-project/form.json, which plugin/scripts/new-project-form.sh writes on each run above; the pane draws it in place of the inbox and writes nothing. A field just typed shows · saving… until the file moves. Start the project asks the script to check every field: one missing redraws the form with a pink ✗ and a plain fix under each, and nothing is created; complete, the skill creates the project as kind: build, autonomy: yolo, with the form's repo as repo= and owner: the creating clone's login, commits, pushes when the bundle has an upstream, and removes the form. Field text is data: autonomy=… or --no-ask typed into a field is that field's words. Until a new project whose title matches appears the board shows Creating "…"…; then Created "…"., plus Its first questions will appear here, or, when the project did not resolve to yolo, It moves only as far as the operator approves. A refused run, or a turn that ends with nothing moved, is one line; nothing retries it.

What it reads

Only under the session's working directory as $.session.cwd() gives it — never a parent directory, never a path a config file names:

PathModeWhy
instance.config.jsonbothexists? — the cwd is a loopd bundle. Absent ⇒ not a loopd bundle and nothing else.
.loopd/SNAPSHOT.jsonoperatorstat every poll, read when the mtime moved. Absent ⇒ board OFF with the touch that turns it on (absence is the off switch — conventions 3 and 11) and nothing else. Unparseable ⇒ one line, and the next write-snapshot.sh run overwrites it.
projects/*/project.mdsimpletitle, status, autonomy and timestamp.
projects/*/tasks/*.mdsimpletitle, status, timestamp, stall_count, open_questions and the ### Q<n> blocks. Listed every poll, read when an mtime moved. A list it cannot parse is drawn as could not read, never guessed.
.loopd/.new-project/form.jsonsimplethe new project form in progress (AB_NEW_PROJECT_FORM, written by new-project-form.sh): stat every poll, read when the mtime moved; absent ⇒ no form open. Its directory carries a * .gitignore, so it is never tracked.
.loopd/.answer-latersimplethe questions answer.sh later deferred, one <task path>#Q<n> a line (AB_ANSWER_LATER in plugin/scripts/bundle-paths.sh). stat every poll, read when the mtime moved; absent ⇒ nothing deferred. Per clone and gitignored, so a deferral on one clone is not one on another.

Simple mode reads the task documents and not the snapshot because the snapshot carries no question text by design (conventions 11b) and is rewritten only by a clone that dispatches. The pane is local, never published — it shows what AWAITING.md and /loopd:answer already show this clone.

The .loopd/SNAPSHOT.json spelling is AB_SNAPSHOT in plugin/scripts/bundle-paths.sh; tests/mods.test.sh asserts the module and that file agree, that every path the module names — every quoted literal an fs call is given included — is listed in this section, and that a module which lists a directory spells its walk as a glob.

The two buttons — operator mode

ButtonDoes
Tick (t)$.command.run({ command: 'loopd:dispatch' }) — runs /loopd:dispatch once in this session, as if you had typed it. The engine queues a plugin's command run until the session is idle, so this is idle-only by contract. (Not $.prompt.submit: the host refuses a prompt text that begins with /, measured on 2.1.293.) A refused run is drawn in the footer as tick refused: <reason>, never swallowed. It is the human pressing a key at their own prompt, not automation: nothing here runs on a timer, and no message goes to another session. One press, one queued tick; a second press while one is queued is ignored and the footer says tick queued.
Refresh (r)re-read the snapshot now, mtime or not.

Where no surface places the pane (a terminal under the width floor, a claude -p run), /pane prints one dim ● loopd-mod-pane: line with the header counts instead.

What it never does

A mod runs with your permissions in every session on the machine, so the lines it does not cross are the whole design, and tests/mods.test.sh in cbmono/loopd asserts each on the source and on what claude plugin validate reads out of it:

  • No model call — nothing here spends the plan.
  • No permission decision — it never hooks tool.check; every event it sees is handed on.
  • No process, no network, no environment — $.process, $.http and $.env are never called.
  • No write — $.fs.write is never called, and $.fs.ancestors (which walks UP from the cwd) is never called either. The reads above are the whole file-system footprint, and they are the one widening of the mod rule tests/mods.test.sh grants, to a mod whose README names its paths here.
  • No cross-session message — $.session.send is not used; the cross-session half is unmeasured (docs/spikes/mods-in-background-sessions.md).
  • No timer-driven run — the poll reads files; only a press runs a command, and nothing here ever submits a prompt.

Tested with

Claude Code 2.1.302 (claude plugin validate . --strict passes, claude plugin test 36/36, 2026-10-19), written against the mods docs and the 2.1.289 claude-code.d.ts. Mods need v2.1.287 or later. After a CLI update run, from this directory:

claude plugin validate . --strict
claude plugin test

Settled by that run: $.prompt.submit refuses a text beginning with / ("would run a command as the user; run one with $.command.run"), so Tick is a $.command.run. Measured on 2.1.300: an interactive session lists loopd-mod-pane.mode in /config as a choice (a -p run lists no plugin rows), and a plugin's $.command.run runs a disable-model-invocation skill. Still assumed: that a /config change reaches a loaded module without a reload; that ui.close fires with e.id for a pane the person closes (else the poll outlives the pane until reload); that $.fs.stat rejects rather than resolving for a missing file (the code handles both).

Delete it

/plugin uninstall loopd-mod-pane@loopd, or remove the directory from a checkout. The contract this plugin is an instance of — how a companion registers, where core looks, and the rule that a companion ADDS behaviour and never removes a core gate — is in ../plugin/README.md → "Companion plugins".

Source 1 files
hooks/register.ts 803 lines
1// loopd-mod-pane — the bundle's board, drawn in a pane of the session that opens it.
2//
3// TWO MODES, decided by the `mode` userConfig field alone (register's `options`):
4// operator — the fourth renderer over `.loopd/SNAPSHOT.json` (docs/conventions.md §11), with
5// Tick and Refresh; simple — an inbox of open questions, stuck tasks and progress, read from
6// the task documents, every button one slash command. What each mode reads is README.md → "What it
7// reads", asserted by tests/mods.test.sh. Untrusted text and types: every string through
8// clean(), every number through toint(), none truncated (conventions 11d, 11e).
9//
10// NEVER: a model call, a hook on the permission event, a process, the network, the
11// environment, a file write, a walk up from the cwd — tests/mods.test.sh asserts each
12// absence on this source, so none of those is spelled here even as a comment.
13
14const PANE = 'loopd-board'
15const COMMAND = 'pane'
16const TITLE = 'loopd board'
17const CONFIG = 'instance.config.json'
18const SNAPSHOT = '.loopd/SNAPSHOT.json'
19const POLL_MS = 5000
20const DISPATCH = 'loopd:dispatch'   // the command, without its slash, as $.command.run names it
21// write-snapshot.sh's verb set, minus nothing: the pane names the verb, never the reason.
22const VERBS = ['approve', 'answer', 'merge', 'unblock', 'close'] as const
23const ANSWER = 'loopd:answer'
24const NEW_PROJECT = 'loopd:new-project'
25// The simple mode's whole walk. The list and read calls below are derived from these two
26// globs, so the README's declaration of them is the declaration of the walk.
27const TASK_DOCS = 'projects/*/tasks/*.md'
28const PROJECT_DOC = 'projects/*/project.md'
29const [PROJECTS_DIR, , TASKS_DIR, TASK_GLOB] = TASK_DOCS.split('/')
30const PROJECT_FILE = PROJECT_DOC.split('/')[2]
31const TASK_SUFFIX = TASK_GLOB.slice(1)
32let MODE: 'operator' | 'simple' = 'operator'
33
34type Kind = 'unread' | 'not-bundle' | 'off' | 'malformed' | 'ok'
35
36type Task = {
37  id: string
38  title: string
39  status: string
40  assignee: string
41  in_flight: boolean
42  pr_mergeable: string
43  awaiting: string
44  open_questions: number
45  prs: number
46}
47type Project = {
48  slug: string
49  title: string
50  status: string
51  awaiting_close: boolean
52  phase_done: number
53  phase_total: number
54  tasks: Task[]
55}
56type Board = {
57  group: string
58  generated_at: string
59  projects: number
60  tasks: number
61  awaiting: number
62  rows: Project[]
63}
64
65// Module state. A reload starts it over, and the next poll or /pane fills it again.
66let kind: Kind = 'unread'
67let board: Board | null = null
68let detail = ''          // the one line a non-ok kind shows
69let mtimeMs = -1         // the snapshot's mtime at the last read; -1 = never read
70let reads = 0            // how many times the file was actually read (the poll skips an unchanged one)
71let timer: { cancel: () => void } | null = null
72let tickQueued = false
73let tickRefused = ''     // why the last Tick's submit was refused, drawn in the footer; '' = it was not
74
75// ---------------------------------------------------------------- untrusted input
76// The TERMINAL sink's one sanitising point, the same rule print-board.sh applies: drop
77// every code point in Unicode general category C (ESC, the bidi overrides, surrogates…),
78// turn whitespace controls into one space, collapse runs. One rule, not a blocklist.
79// The property escape is tried once; an engine without it gets the C0/C1/format fallback.
80// Both are built from STRINGS, double-escaped, so this source stays ASCII: a raw U+2028 in
81// a regex literal is a line terminator to the parser and ends the literal early.
82let CAT_C: RegExp
83try { CAT_C = new RegExp('\\p{C}', 'gu') } catch {
84  CAT_C = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2064\\u2066-\\u206f\\ufeff\\ufff9-\\ufffb]', 'g')
85}
86function clean(v: unknown): string {
87  const s = typeof v === 'string' ? v : (v === null || v === undefined ? '' : String(v))
88  return s.replace(/[\t\n\r\f\v]/g, ' ').replace(CAT_C, '').replace(/ {2,}/g, ' ').trim()
89}
90
91// Every number off the snapshot goes through here — a `"tasks": "many"` is 0, not a throw.
92// Never truncated downstream: the caller prints String(n) whole.
93function toint(v: unknown): number {
94  if (typeof v === 'number' && isFinite(v)) return Math.max(0, Math.floor(v))
95  if (typeof v === 'string' && /^[0-9]+$/.test(v.trim())) return parseInt(v.trim(), 10)
96  return 0
97}
98function str(v: unknown): string { return typeof v === 'string' ? clean(v) : '' }
99function obj(v: unknown): Record<string, unknown> | null {
100  return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null
101}
102function arr(v: unknown): unknown[] { return Array.isArray(v) ? v : [] }
103
104// Presentation over the parsed JSON: shape it once, cleanly, so the render hook is a pure
105// function of `board`. Nothing here is derived from the bundle — only from the snapshot.
106function shape(json: unknown): Board | null {
107  const top = obj(json)
108  if (!top) return null
109  const counts = obj(top.counts) || {}
110  const rows: Project[] = []
111  for (const p of arr(top.projects)) {
112    const po = obj(p)
113    if (!po) continue
114    const pp = obj(po.phase_progress) || {}
115    const tasks: Task[] = []
116    for (const t of arr(po.tasks)) {
117      const to = obj(t)
118      if (!to) continue
119      tasks.push({
120        id: str(to.id), title: str(to.title), status: str(to.status), assignee: str(to.assignee),
121        in_flight: to.in_flight === true, pr_mergeable: str(to.pr_mergeable), awaiting: str(to.awaiting),
122        open_questions: toint(to.open_questions), prs: arr(to.prs).length,
123      })
124    }
125    rows.push({
126      slug: str(po.slug), title: str(po.title), status: str(po.status),
127      awaiting_close: po.awaiting_close === true,
128      phase_done: toint(pp.done), phase_total: toint(pp.total), tasks,
129    })
130  }
131  return {
132    group: str(top.group), generated_at: str(top.generated_at),
133    projects: toint(counts.projects), tasks: toint(counts.tasks), awaiting: toint(counts.awaiting),
134    rows,
135  }
136}
137
138// ---------------------------------------------------------------- the read
139// `force` re-reads regardless of mtime (Refresh, the first open); the poll passes false and
140// reads only when stat says the file moved. Every `$` call is caught: a missing or renamed
141// field, a vanished file or a refused call costs one line in the pane, never a throw.
142async function refresh($: any, force: boolean): Promise<void> {
143  let cwd: unknown = null
144  try { cwd = await $.session.cwd() } catch { cwd = null }
145  if (typeof cwd !== 'string' || !cwd) { kind = 'malformed'; board = null; detail = 'cannot read the working directory'; return }
146  const root = cwd.replace(/\/+$/, '')
147  let isBundle = false
148  try { isBundle = (await $.fs.exists(root + '/' + CONFIG)) === true } catch { isBundle = false }
149  if (!isBundle) { kind = 'not-bundle'; board = null; detail = 'not a loopd bundle — no ' + CONFIG + ' in ' + clean(root); mtimeMs = -1; return }
150  const path = root + '/' + SNAPSHOT
151  let st: any = null
152  try { st = await $.fs.stat(path) } catch { st = null }
153  if (!st || st.kind !== 'file') {
154    kind = 'off'; board = null; mtimeMs = -1
155    detail = 'board OFF — no ' + SNAPSHOT + ' here. `touch ' + SNAPSHOT + '` in the bundle root turns it on (absence is the off switch).'
156    return
157  }
158  const m = typeof st.mtimeMs === 'number' ? st.mtimeMs : -2
159  if (!force && kind !== 'unread' && m === mtimeMs) return
160  let text: unknown = null
161  try { text = await $.fs.read(path) } catch { text = null }
162  reads += 1
163  mtimeMs = m
164  if (typeof text !== 'string') { kind = 'malformed'; board = null; detail = 'could not read ' + SNAPSHOT; return }
165  let json: unknown
166  try { json = JSON.parse(text) } catch { kind = 'malformed'; board = null; detail = SNAPSHOT + ' is not valid JSON — the next write-snapshot.sh run overwrites it'; return }
167  const b = shape(json)
168  if (!b) { kind = 'malformed'; board = null; detail = SNAPSHOT + ' is not a JSON object — the next write-snapshot.sh run overwrites it'; return }
169  kind = 'ok'; board = b; detail = ''
170}
171
172function summary(): string {
173  if (kind !== 'ok' || !board) return detail
174  return 'loopd board: ' + board.projects + ' project(s) · ' + board.tasks + ' task(s) · ' + board.awaiting + ' awaiting you'
175}
176
177// ---------------------------------------------------------------- the drawing
178// Function-call form (this is a .ts file, so no JSX); Box, Text and Button are the three
179// elements every surface draws. Every string passed to Text has been through clean().
180function draw($: any, e: any): any {
181  const { Box, Text, Button } = $.ui.resolve(e)
182  const line = (s: string, props: Record<string, unknown> = {}) => Text({ ...props, children: [s] })
183  const rows: any[] = []
184
185  if (kind !== 'ok' || !board) {
186    rows.push(line(kind === 'unread' ? 'loopd board: reading…' : detail, { dimColor: kind === 'unread' }))
187  } else {
188    const b = board
189    rows.push(line(TITLE + (b.group ? ' · ' + b.group : '') + ' · ' + b.projects + ' project(s) · ' + b.tasks + ' task(s) · ' + b.awaiting + ' awaiting you', { bold: true }))
190
191    // The need-you rail: the AWAITING verbs, counted off each task's `awaiting` plus one
192    // `close` per project whose `awaiting_close` is set — print-board.sh's rule.
193    const need: Record<string, number> = {}
194    for (const v of VERBS) need[v] = 0
195    const inFlight: { slug: string; t: Task }[] = []
196    for (const p of b.rows) {
197      if (p.awaiting_close) need.close += 1
198      for (const t of p.tasks) {
199        if ((VERBS as readonly string[]).includes(t.awaiting)) need[t.awaiting] += 1
200        if (t.in_flight) inFlight.push({ slug: p.slug, t })
201      }
202    }
203    rows.push(line('need you: ' + VERBS.map(v => v + ' ' + need[v]).join(' · ')))
204
205    rows.push(line(' '))
206    rows.push(line('in flight (' + inFlight.length + ')', { bold: true }))
207    if (inFlight.length === 0) rows.push(line('nothing in flight', { dimColor: true }))
208    for (const { slug, t } of inFlight) {
209      rows.push(line('  ' + slug + '/' + t.id + ' · ' + (t.assignee || 'unassigned') + ' · ' + t.status
210        + (t.prs ? ' · PR ' + (t.pr_mergeable || 'UNKNOWN') : '') + ' · ' + t.title))
211    }
212
213    rows.push(line(' '))
214    rows.push(line('projects (' + b.rows.length + ')', { bold: true }))
215    for (const p of b.rows) {
216      let aw = p.awaiting_close ? 1 : 0
217      let fly = 0
218      for (const t of p.tasks) { if ((VERBS as readonly string[]).includes(t.awaiting)) aw += 1; if (t.in_flight) fly += 1 }
219      rows.push(line('  ' + p.slug + ' · ' + p.status + ' · phases ' + p.phase_done + '/' + p.phase_total
220        + ' · tasks ' + p.tasks.length + ' · in flight ' + fly + ' · awaiting ' + aw + ' · ' + p.title))
221    }
222
223    rows.push(line(' '))
224    rows.push(line('snapshot written ' + (b.generated_at || 'unknown') + (tickQueued ? ' · tick queued' : ''), { dimColor: true }))
225  }
226  // A refused submit is said, not swallowed: a Tick that silently did nothing is the
227  // silent wrong answer convention 12 is about.
228  if (tickRefused) rows.push(line('tick refused: ' + tickRefused, { dimColor: true }))
229
230  rows.push(line(' '))
231  rows.push(Box({
232    flexDirection: 'row', columnGap: 2, children: [
233      Button({
234        key: 'tick', label: 'Tick', hotkey: 't',
235        // The human pressed a key in their own session: one /loopd:dispatch run, queued
236        // until the session is idle (the engine's own contract for a plugin's command.run).
237        // Not awaited — a handler that waits for the run would block the press. Never on
238        // a timer. A COMMAND run, not a prompt: the host refuses a `/` text as a prompt.
239        onPress: () => {
240          if (tickQueued) return
241          tickQueued = true
242          tickRefused = ''
243          const done = (err?: unknown) => {
244            tickQueued = false
245            if (err !== undefined) tickRefused = clean(err && (err as any).message ? (err as any).message : String(err)) || 'refused'
246            try { $.ui.invalidate('ui.render') } catch { /* no surface to redraw */ }
247          }
248          let p: any = null
249          try { p = $.command.run({ command: DISPATCH }) } catch (err) { done(err); return }
250          if (p && typeof p.then === 'function') p.then(() => done(), (err: unknown) => done(err ?? 'refused')); else done()
251          try { $.ui.invalidate('ui.render') } catch { /* no surface to redraw */ }
252        },
253      }),
254      Button({
255        key: 'refresh', label: 'Refresh', hotkey: 'r',
256        onPress: async () => { await refresh($, true); $.ui.invalidate('ui.render') },
257      }),
258    ],
259  }))
260
261  return Box({ flexDirection: 'column', children: rows })
262}
263
264// ---------------------------------------------------------------- simple mode
265// An inbox, top to bottom: questions, stuck tasks a person can clear, stuck tasks we are
266// on, progress. One order rule, board-serve.sh's rank(): oldest task `timestamp:` first,
267// then slug, then task id, then Q<n> within the task; undated last.
268type Question = { label: string; text: string; options: string[]; first: boolean }
269type Item = { slug: string; file: string; mtimeMs: number; title: string; status: string; ts: number; stall: number; questions: Question[]; unreadable: boolean }
270type Simple = { slug: string; title: string; autonomy: string; ts: number; finished: boolean; done: number; total: number; items: Item[] }
271type Doc = { title: string; status: string; autonomy: string; timestamp: string; stall: string; open: string[] | null; body: string } | null
272type Held = { kind: 'answer' | 'later'; mtimeMs: number; laterMtime: number; at: number; text: string }
273type Entry = { p: Simple; it: Item; q: Question; id: string; later: number }
274
275const UNBLOCK = 'loopd:unblock'
276// answer.sh's `later` record, AB_ANSWER_LATER in bundle-paths.sh: one `<task path>#Q<n>` a line.
277const LATER = '.loopd/.answer-later'
278let simple: Simple[] = []
279let docs = new Map<string, { mtimeMs: number; doc: Doc }>()
280let sig = ''             // names and mtimes of every file the last scan saw; a change redraws
281let later: string[] = []
282let laterMtime = -1      // -1 = no file; -2 = a read failed, so the next scan reads again
283let sending = ''         // the run that is queued; '' = none, and only then does a key act
284let sendLine = ''        // what the open card shows while it is
285let sendNote = ''        // the line drawn after a run: a confirmation naming its code, or a refusal
286// The run resolves once the command is queued, before answer.sh has written (measured on
287// 2.1.300), so an answered question is held until its document's mtime moves (a deferred
288// one until the later file's does), or until a turn that started after the press completes
289// without moving it (answer.sh refused).
290let held = new Map<string, Held>()
291// The pane's colours: pink for a row only a person can clear, green for sent and finished
292// (loopd-design/cli-theme.json human_pink; plugin/themes/loopd.json success).
293const NEEDS_YOU = { color: '#ff7ac2' }
294const DONE = { color: '#76d6a4' }
295const STUCK_KEYS = ['c', 'd', 'e']
296
297// AB_NEW_PROJECT_FORM in bundle-paths.sh: new-project-form.sh writes it and its ✗ marks; the pane only draws it.
298const FORM_FILE = '.loopd/.new-project/form.json'
299const FIELDS = [['title', 'Title', 'a short name'], ['what', 'What', 'what it should do, in a line'],
300  ['whom', 'For whom', 'who needs it'], ['done', 'Done when', 'how you will know; separate several with ;'],
301  ['repo', 'Target repo', 'owner/name']] as const
302type Form = { fields: Record<string, string>; errors: Record<string, string> }
303let pform: Form | null = null
304let formBroken = false
305let formMtime = -1       // -1 = no form open; -2 = a read failed, so the next scan reads again
306let formSkip = -3        // the mtime of a form already turned into a project, drawn as the board
307// A form command is held, like an answer, until the form file moves or its turn ends unmoved.
308let formHeld: { kind: 'open' | 'fill' | 'cancel'; at: number; mtimeMs: number; n: number; text: string } | null = null
309let creating: { at: number; slugs: Set<string>; title: string; mtimeMs: number } | null = null
310let createNote = ''
311
312function readForm(text: unknown): Form | null {
313  if (typeof text !== 'string') return null
314  let j: unknown
315  try { j = JSON.parse(text) } catch { return null }
316  const o = obj(j), f = o && obj(o.fields)
317  if (!f) return null
318  const e = obj(o!.errors) || {}
319  const out: Form = { fields: {}, errors: {} }
320  for (const [k] of FIELDS) { out.fields[k] = str(f[k]); if (str(e[k])) out.errors[k] = str(e[k]) }
321  return out
322}
323
324// The YAML subset fold-answers.sh's --list reads (a flow or block list of scalars, its
325// escapes only). Anything else is null, drawn as "could not read" — never a guess.
326const ESC: Record<string, string> = { n: '\n', t: '\t', '"': '"', '\\': '\\', '/': '/' }
327function quoted(s: string, i: number): [string, number] | null {
328  const q = s[i]; let out = ''; i += 1
329  while (i < s.length) {
330    const c = s[i]
331    if (q === '"' && c === '\\') { const e = ESC[s[i + 1]]; if (e === undefined) return null; out += e; i += 2; continue }
332    if (c === q) { if (q === "'" && s[i + 1] === "'") { out += "'"; i += 2; continue } return [out, i + 1] }
333    out += c; i += 1
334  }
335  return null
336}
337function scalar(raw: string | undefined): string {
338  if (raw === undefined) return ''
339  const v = raw.trim()
340  if (v[0] === '"' || v[0] === "'") { const r = quoted(v, 0); return r ? r[0] : '' }
341  return v.split(/[ \t]#/)[0].trim()
342}
343function list(fm: string, at: number): string[] | null {
344  const rest = fm.slice(at)
345  const lead = rest.match(/^[ \t]*/)![0].length
346  const out: string[] = []
347  if (rest[lead] === '[') {
348    let i = lead + 1
349    for (;;) {
350      while (i < rest.length && /[ \t\n,]/.test(rest[i])) i += 1
351      if (i >= rest.length) return null
352      if (rest[i] === ']') return out
353      if (rest[i] === '"' || rest[i] === "'") { const r = quoted(rest, i); if (!r) return null; out.push(r[0]); i = r[1]; continue }
354      let j = i; while (j < rest.length && !/[,\]\n]/.test(rest[j])) j += 1
355      const v = rest.slice(i, j).trim(); if (v) out.push(v); i = j
356    }
357  }
358  const lines = rest.split('\n')
359  const head = lines[0].trim()
360  if (head && head[0] !== '#') return null
361  for (const l of lines.slice(1)) {
362    const m = l.match(/^[ \t]+-(?:[ \t]+|$)/)
363    if (!m) { if (!l.trim()) continue; if (/^[ \t]/.test(l)) return null; break }
364    const v = l.slice(m[0].length)
365    if (v[0] === '"' || v[0] === "'") { const r = quoted(v, 0); if (!r) return null; out.push(r[0]) } else out.push(v.split(/[ \t]#/)[0].trim())
366  }
367  return out
368}
369function parse(text: string): Doc {
370  if (!text.startsWith('---\n')) return null
371  const end = text.indexOf('\n---', 3)
372  if (end < 0) return null
373  const fm = text.slice(4, end + 1)
374  const oq = fm.match(/^open_questions:/m)
375  return {
376    title: scalar((fm.match(/^title:(.*)$/m) || [])[1]),
377    status: scalar((fm.match(/^status:(.*)$/m) || [])[1]),
378    autonomy: scalar((fm.match(/^autonomy:(.*)$/m) || [])[1]),
379    timestamp: scalar((fm.match(/^timestamp:(.*)$/m) || [])[1]),
380    stall: scalar((fm.match(/^stall_count:(.*)$/m) || [])[1]),
381    open: oq ? list(fm, oq.index! + oq[0].length) : [],
382    body: text.slice(end + 4),
383  }
384}
385// The `### Q<n>` block, read as answer.sh reads it: lines up to the next h1–h3, a bare
386// `Name:` line switches field, options are `n. text` numbered 1 up without a gap.
387// Option 1 is the recommendation (SCHEMA.md → "Question details").
388function qblock(body: string, label: string): string[] {
389  const lines = body.split('\n')
390  const at = lines.findIndex(l => /^###\s+/.test(l) && l.replace(/^###\s+/, '').trim() === label)
391  const opts: Record<number, string> = {}
392  let field = ''
393  if (at >= 0) {
394    for (const l of lines.slice(at + 1)) {
395      if (/^#{1,3}\s/.test(l)) break
396      const f = l.match(/^(\w+):\s*$/)
397      if (f) { field = f[1]; continue }
398      const o = field === 'Options' ? l.match(/^\s*(\d+)\.\s+(.*\S)/) : null
399      if (o) opts[parseInt(o[1], 10)] = o[2]
400    }
401  }
402  const options: string[] = []
403  while (opts[options.length + 1] !== undefined) options.push(clean(opts[options.length + 1]))
404  return options
405}
406function questions(d: Doc): Question[] {
407  const out: Question[] = []
408  for (const e of (d && d.open) || []) {
409    const cut = e.lastIndexOf(' --- ')
410    if (cut >= 0 && e.slice(cut + 5).trim()) continue
411    const m = e.match(/^(Q[0-9]+):\s*/)
412    const label = m ? m[1] : ''
413    const text = clean((m ? e.slice(m[0].length) : e).replace(/ ---\s*$/, ''))
414    out.push({ label, text, options: label ? qblock(d!.body, label) : [], first: out.length === 0 })
415  }
416  return out
417}
418function when(v: string): number { const t = Date.parse(v); return isFinite(t) ? t : NaN }
419
420// A name that goes into the command line the answer runs as: nothing a shell or the
421// skill's argument split could read as more than one word.
422const SAFE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
423async function entries($: any, path: string): Promise<{ name: string; kind: string; mtimeMs: number }[]> {
424  try { const r = await $.fs.list(path); return Array.isArray(r) ? r : [] } catch { return [] }
425}
426async function doc($: any, path: string, mtimeMs: number): Promise<Doc> {
427  const hit = docs.get(path)
428  if (hit && hit.mtimeMs === mtimeMs) return hit.doc
429  let text: unknown = null
430  try { text = await $.fs.read(path) } catch { text = null }
431  reads += 1
432  if (typeof text !== 'string') return null
433  const d = parse(text)
434  docs.set(path, { mtimeMs, doc: d })
435  return d
436}
437
438async function refreshSimple($: any): Promise<boolean> {
439  let cwd: unknown = null
440  try { cwd = await $.session.cwd() } catch { cwd = null }
441  if (typeof cwd !== 'string' || !cwd) { const was = kind; kind = 'malformed'; detail = 'cannot read the working directory'; return was !== kind }
442  const root = cwd.replace(/\/+$/, '')
443  let isBundle = false
444  try { isBundle = (await $.fs.exists(root + '/' + CONFIG)) === true } catch { isBundle = false }
445  if (!isBundle) { const was = kind; kind = 'not-bundle'; detail = 'not a loopd bundle — no ' + CONFIG + ' in ' + clean(root); simple = []; return was !== kind }
446  const next: Simple[] = []
447  const seen = new Map<string, { mtimeMs: number; doc: Doc }>()
448  let s = ''
449  for (const p of await entries($, root + '/' + PROJECTS_DIR)) {
450    if (p.kind !== 'dir' || !SAFE.test(p.name)) continue
451    const pdir = root + '/' + PROJECTS_DIR + '/' + p.name
452    const files = await entries($, pdir)
453    const pf = files.find(f => f.name === PROJECT_FILE && f.kind === 'file')
454    const pd = pf ? await doc($, pdir + '/' + PROJECT_FILE, pf.mtimeMs) : null
455    if (pf) { const c = docs.get(pdir + '/' + PROJECT_FILE); if (c) seen.set(pdir + '/' + PROJECT_FILE, c); s += pdir + ':' + pf.mtimeMs + (c ? ';' : '!;') }
456    if (pd && pd.status === 'cancelled') continue
457    const row: Simple = { slug: p.name, title: (pd && clean(pd.title)) || p.name, autonomy: pd ? pd.autonomy : '', ts: when(pd ? pd.timestamp : ''),
458      finished: !!pd && pd.status === 'done', done: 0, total: 0, items: [] }
459    next.push(row)
460    if (row.finished) continue
461    for (const t of await entries($, pdir + '/' + TASKS_DIR)) {
462      if (t.kind !== 'file' || !t.name.endsWith(TASK_SUFFIX) || !SAFE.test(t.name)) continue
463      const path = pdir + '/' + TASKS_DIR + '/' + t.name
464      const d = await doc($, path, t.mtimeMs)
465      const c = docs.get(path)
466      if (c) seen.set(path, c)
467      s += path + ':' + t.mtimeMs + (c ? ';' : '!;')
468      const status = d ? d.status : ''
469      if (status === 'cancelled') continue
470      row.total += 1
471      if (status === 'done') row.done += 1
472      row.items.push({ slug: p.name, file: t.name, mtimeMs: t.mtimeMs, title: (d && clean(d.title)) || t.name, status, ts: when(d ? d.timestamp : ''),
473        stall: toint(d ? d.stall : ''), questions: questions(d), unreadable: !d || d.open === null })
474    }
475    if (row.total > 0 && row.done === row.total) row.finished = true
476  }
477  docs = seen
478  let st: any = null
479  try { st = await $.fs.stat(root + '/' + LATER) } catch { st = null }
480  const lm = st && st.kind === 'file' && typeof st.mtimeMs === 'number' ? st.mtimeMs : -1
481  if (lm !== laterMtime) {
482    let text: unknown = ''
483    if (lm >= 0) { try { text = await $.fs.read(root + '/' + LATER) } catch { text = null } reads += 1 }
484    later = typeof text === 'string' ? text.split('\n').map(l => clean(l)).filter(Boolean) : []
485    laterMtime = typeof text === 'string' ? lm : -2
486  }
487  s += LATER + ':' + laterMtime + ';'
488  let fst: any = null
489  try { fst = await $.fs.stat(root + '/' + FORM_FILE) } catch { fst = null }
490  const fm = fst && fst.kind === 'file' && typeof fst.mtimeMs === 'number' ? fst.mtimeMs : -1
491  if (fm !== formMtime) {
492    let text: unknown = null
493    if (fm >= 0) { try { text = await $.fs.read(root + '/' + FORM_FILE) } catch { text = null } reads += 1 }
494    pform = fm >= 0 ? readForm(text) : null
495    formBroken = fm >= 0 && !pform
496    formMtime = fm < 0 ? -1 : typeof text === 'string' ? fm : -2
497  }
498  s += FORM_FILE + ':' + formMtime + ';'
499  if (formHeld && formMtime !== formHeld.mtimeMs) {
500    if (formHeld.kind === 'cancel') createNote = 'Cancelled — nothing saved.'
501    formHeld = null
502  }
503  const live = new Map<string, Held>()
504  for (const r of next) for (const it of r.items) for (const q of it.questions) {
505    const id = it.slug + '/' + it.file + '#' + q.label, h = held.get(id)
506    if (h && (h.kind === 'later' ? h.laterMtime === laterMtime : h.mtimeMs === it.mtimeMs)) live.set(id, h)
507  }
508  held = live
509  if (creating) {
510    const made = next.find(r => r.autonomy && r.title === creating!.title && !creating!.slugs.has(r.slug))
511    if (made) {
512      createNote = 'Created "' + made.title + '". ' + (made.autonomy === 'yolo' ? 'Its first questions will appear here.' : 'It moves only as far as the operator approves.')
513      creating = null
514      formSkip = formMtime
515    } else if (formMtime !== creating.mtimeMs && pform && Object.keys(pform.errors).length) creating = null
516  }
517  const was = kind
518  kind = 'ok'; detail = ''; simple = next
519  if (s === sig && was === 'ok') return false
520  sig = s
521  return true
522}
523
524function taskPath(it: Item): string { return PROJECTS_DIR + '/' + it.slug + '/' + TASKS_DIR + '/' + it.file }
525// The one order rule, key for key with board-serve.sh: tasks sharing a timestamp (every
526// task one scaffold writes) must not interleave. Never a subtraction on qn: Infinity - Infinity is NaN.
527function order(a: { ts: number; qn: number; slug: string; file: string }, b: typeof a): number {
528  const ad = isNaN(a.ts), bd = isNaN(b.ts)
529  if (ad !== bd) return ad ? 1 : -1
530  if (!ad && a.ts !== b.ts) return a.ts < b.ts ? -1 : 1
531  if (a.slug !== b.slug) return a.slug < b.slug ? -1 : 1
532  if (a.file !== b.file) return a.file < b.file ? -1 : 1
533  return a.qn === b.qn ? 0 : a.qn < b.qn ? -1 : 1
534}
535function qn(q: Question): number { return q.label ? parseInt(q.label.slice(1), 10) : Infinity }
536// Every open question, in the order the inbox draws them: the rule above, then whatever
537// `later` deferred, in the order it was deferred.
538function inbox(): Entry[] {
539  const out: Entry[] = []
540  for (const p of simple) for (const it of p.items) for (const q of it.questions) {
541    const id = it.slug + '/' + it.file + '#' + q.label, h = held.get(id)
542    const at = q.label ? later.indexOf(taskPath(it) + '#' + q.label) : -1
543    out.push({ p, it, q, id, later: h && h.kind === 'later' ? later.length : at })
544  }
545  const key = (e: Entry) => ({ ts: e.it.ts, qn: qn(e.q), slug: e.it.slug, file: e.it.file })
546  return out.sort((a, b) => (a.later < 0) !== (b.later < 0) ? (a.later < 0 ? -1 : 1)
547    : a.later >= 0 && a.later !== b.later ? a.later - b.later : order(key(a), key(b)))
548}
549function tasks(pick: (it: Item) => boolean): { p: Simple; it: Item }[] {
550  const out: { p: Simple; it: Item }[] = []
551  for (const p of simple) for (const it of p.items) if (pick(it)) out.push({ p, it })
552  return out.sort((a, b) => order({ ts: a.it.ts, qn: 0, slug: a.it.slug, file: a.it.file }, { ts: b.it.ts, qn: 0, slug: b.it.slug, file: b.it.file }))
553}
554const helps = (it: Item) => it.status === 'blocked'
555const onIt = (it: Item) => (it.status === 'in-progress' || it.status === 'in-review') && it.stall >= 1
556
557function bar(done: number, total: number): string {
558  const w = 10, f = total > 0 ? Math.round((done / total) * w) : 0
559  return '█'.repeat(f) + '░'.repeat(w - f) + ' ' + done + '/' + total + ' done'
560}
561function why(err: unknown): string { return clean(err && (err as any).message ? (err as any).message : String(err)) || 'refused' }
562
563// One slash command per press, and none while another is queued: `sending` is set before
564// the first await, so a second key pressed in that window runs nothing.
565function run($: any, command: string, args: string, after: (err?: unknown) => void): void {
566  const fin = async (err?: unknown) => {
567    sending = ''; sendLine = ''
568    after(err)
569    try { await refreshSimple($) } catch { /* the next poll reads again */ }
570    try { $.ui.invalidate('ui.render') } catch { /* no surface to redraw */ }
571  }
572  let p: any = null
573  try { p = $.command.run({ command, args }) } catch (err) { void fin(err); return }
574  if (p && typeof p.then === 'function') p.then(() => fin(), (err: unknown) => fin(err ?? 'refused')); else void fin()
575  try { $.ui.invalidate('ui.render') } catch { /* no surface to redraw */ }
576}
577
578async function send($: any, e: Entry, reply: string): Promise<void> {
579  if (sending || !reply) return
580  const { p, it, q } = e
581  const code = q.label || 'the question'
582  sending = e.id
583  sendLine = reply === 'later' ? 'Moving ' + code + ' to the end…' : reply === 'more' ? 'Asking for more on ' + code + '…' : 'Sending your answer to ' + code + '…'
584  sendNote = ''
585  const lm = laterMtime
586  let at = 0
587  try { at = await $.clock.now() } catch { at = 0 }
588  run($, ANSWER, taskPath(it) + (q.label ? ' ' + q.label : '') + ' ' + reply, (err?: unknown) => {
589    if (err !== undefined) { sendNote = 'Could not send that answer: ' + why(err); return }
590    if (reply === 'more') { sendNote = 'More on ' + code + ' is in the conversation.'; return }
591    held.set(e.id, { kind: reply === 'later' ? 'later' : 'answer', mtimeMs: it.mtimeMs, laterMtime: lm, at, text: q.text })
592    sendNote = reply === 'later' ? '↷ ' + code + ' moved to the end. We\'ll bring it back after the others.'
593      : '✓ Sent your answer to ' + code + ' · ' + p.title + ' · ' + it.title
594  })
595}
596
597function unblock($: any, p: Simple, it: Item): void {
598  if (sending) return
599  sending = 'unblock:' + it.slug + '/' + it.file
600  sendLine = 'Opening "' + it.title + '" in the conversation…'
601  sendNote = ''
602  run($, UNBLOCK, taskPath(it), (err?: unknown) => {
603    sendNote = err !== undefined ? 'Could not start unblocking "' + it.title + '": ' + why(err)
604      : 'Unblocking "' + it.title + '" in ' + p.title + ' — answer in the conversation.'
605  })
606}
607
608function q(s: string): string { return '"' + s.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"' }
609
610// One /loopd:new-project run for the form: `sending` covers the press until it is queued,
611// `formHeld` (or `creating`, for submit) until the form file or the bundle moves.
612async function formRun($: any, kind: 'open' | 'fill' | 'cancel' | 'submit', args: string, n = 0, text = ''): Promise<void> {
613  if (sending || formHeld || creating) return
614  sending = 'form'
615  sendNote = ''; createNote = ''
616  let at = 0
617  try { at = await $.clock.now() } catch { at = 0 }
618  if (kind === 'submit') creating = { at, slugs: new Set(simple.map(p => p.slug)), title: pform ? pform.fields.title : '', mtimeMs: formMtime }
619  else formHeld = { kind, at, mtimeMs: formMtime, n, text }
620  run($, NEW_PROJECT, args, (err?: unknown) => {
621    if (err === undefined) return
622    formHeld = null; creating = null
623    createNote = (kind === 'submit' ? 'Could not create the project: ' : 'Could not reach the form: ') + why(err)
624  })
625}
626function fillFrom($: any, v: string): void {
627  const m = clean(v).match(/^([1-5])\s+(.*\S)$/)
628  if (!m) { createNote = 'Start with the field\'s number, 1 to 5, then the text.'; $.ui.invalidate('ui.render'); return }
629  void formRun($, 'fill', m[1] + ' ' + q(m[2]), parseInt(m[1], 10), m[2])
630}
631
632function drawForm($: any, e: any, rows: any[]): void {
633  const { Text, Button, Box, Input } = $.ui.resolve(e)
634  const line = (s: string, props: Record<string, unknown> = {}) => Text({ ...props, children: [s] })
635  if (!pform) {
636    rows.push(line('Could not read the new project form — Cancel removes it.', { dimColor: true }))
637  } else {
638    const filled = FIELDS.filter(([k]) => pform!.fields[k]).length, fix = Object.keys(pform.errors).length
639    rows.push(line('New project · ' + (fix ? fix + (fix === 1 ? ' thing' : ' things') + ' to fix' : filled + ' of ' + FIELDS.length + ' filled'), { bold: true, ...(fix ? NEEDS_YOU : {}) }))
640    rows.push(line('Type each answer in the box below, starting with its number, then press Enter.', { dimColor: true }))
641    FIELDS.forEach(([k, label, hint], i) => {
642      const saving = formHeld && formHeld.kind === 'fill' && formHeld.n === i + 1
643      const v = saving ? formHeld!.text + ' · saving…' : pform!.fields[k]
644      rows.push(line('  ' + (i + 1) + ' ' + label + ': ' + (v || 'e.g. ' + hint), v && !saving ? {} : { dimColor: true }))
645      if (pform!.errors[k] && !saving) rows.push(line('    ✗ ' + pform!.errors[k], NEEDS_YOU))
646    })
647  }
648  if (sending || formHeld || creating) { rows.push(line('  Waiting for the form to update…', { dimColor: true })); return }
649  if (pform && Input) rows.push(Input({ key: 'form-text', placeholder: 'e.g. 1 Newsletter signup', submitLabel: 'fill', onSubmit: (v: string) => fillFrom($, v) }))
650  rows.push(Box({ flexDirection: 'row', columnGap: 2, children: [
651    ...(pform ? [Button({ key: 'form-submit', label: 'Start the project', hotkey: 'y', onPress: () => formRun($, 'submit', 'submit') })] : []),
652    Button({ key: 'form-cancel', label: 'Cancel', hotkey: 'x', onPress: () => formRun($, 'cancel', 'cancel') }),
653  ] }))
654}
655
656function drawSimple($: any, e: any): any {
657  const { Box, Text, Button, Input } = $.ui.resolve(e)
658  const line = (s: string, props: Record<string, unknown> = {}) => Text({ ...props, children: [s] })
659  const rows: any[] = []
660  if (kind !== 'ok') {
661    rows.push(line(kind === 'unread' ? 'loopd: reading…' : detail, { dimColor: kind === 'unread' }))
662  } else {
663    if (sendNote) rows.push(line(sendNote, sendNote.startsWith('✓') ? DONE : { dimColor: true }))
664    if (createNote) rows.push(line(createNote, { dimColor: true }))
665    if ((pform || formBroken) && !creating && formMtime !== formSkip && !(formHeld && formHeld.kind === 'open')) {
666      drawForm($, e, rows)
667      rows.push(line(' '))
668      rows.push(Button({ key: 'refresh', label: 'Refresh', hotkey: 'r', onPress: async () => { await refreshSimple($); $.ui.invalidate('ui.render') } }))
669      return Box({ flexDirection: 'column', children: rows })
670    }
671
672    rows.push(line('Questions for you', { bold: true }))
673    const all = inbox()
674    const waiting = all.filter(x => !held.has(x.id) || held.get(x.id)!.kind === 'later')
675    const open = sending ? undefined : waiting.find(x => x.q.label || x.q.first)
676    if (sendLine) rows.push(line('  ' + sendLine, { dimColor: true }))
677    if (open) {
678      const { p, it, q } = open
679      rows.push(line(' '))
680      rows.push(line('  ' + (q.label ? q.label + ' · ' : '') + p.title + ' · ' + it.title, { dimColor: true }))
681      rows.push(line('  ' + q.text, { bold: true, ...NEEDS_YOU }))
682      q.options.forEach((o, i) => rows.push(Button({ key: 'open-opt' + (i + 1), label: i === 0 ? 'Recommended: ' + o : o,
683        ...(i < 9 ? { hotkey: String(i + 1) } : {}), onPress: () => send($, open, String(i + 1)) })))
684      if (Input) rows.push(Input({ key: 'open-text', placeholder: 'or type your own answer', submitLabel: 'send',
685        onSubmit: (v: string) => { const t = clean(v); if (t) send($, open, '--text ' + t) } }))
686      rows.push(Box({ flexDirection: 'row', columnGap: 2, children: [
687        Button({ key: 'open-more', label: 'More', hotkey: 'm', onPress: () => send($, open, 'more') }),
688        ...(q.label ? [Button({ key: 'open-later', label: 'Later', hotkey: 'l', onPress: () => send($, open, 'later') })] : []),
689      ] }))
690    }
691    const rest = waiting.filter(x => x !== open)
692    if (open && rest.length) rows.push(line('  ' + rest.length + ' more ' + (rest.length === 1 ? 'question' : 'questions') + ' after this', { dimColor: true }))
693    if (rest.length) rows.push(line(' '))
694    for (const x of rest) rows.push(line('  ' + (x.q.label ? x.q.label + ' · ' : '') + x.p.title + ' · ' + x.q.text + (x.later >= 0 ? ' · later' : ''), { dimColor: true }))
695    for (const p of simple) for (const it of p.items) if (it.unreadable) rows.push(line('  Could not read the questions in "' + it.title + '" (' + p.title + ').', { dimColor: true }))
696    if (all.length === 0) rows.push(line('No open questions.', { dimColor: true }))
697
698    const help = tasks(helps)
699    if (help.length) {
700      rows.push(line(' '))
701      rows.push(line('Stuck — you can help', { bold: true }))
702      help.forEach(({ p, it }, i) => {
703        rows.push(line('  Unblock "' + it.title + '" in ' + p.title + ': it cannot move until you do.', NEEDS_YOU))
704        if (!sending) rows.push(Button({ key: 'unblock-' + (i + 1), label: 'Unblock it', ...(i < STUCK_KEYS.length ? { hotkey: STUCK_KEYS[i] } : {}), onPress: () => unblock($, p, it) }))
705      })
706    }
707    const quiet = tasks(it => !helps(it) && onIt(it))
708    if (quiet.length) {
709      rows.push(line(' '))
710      rows.push(line('Stuck — we\'re on it', { bold: true }))
711      for (const { p, it } of quiet) rows.push(line('  "' + it.title + '" in ' + p.title + ': nothing for you to do, we\'re on it.', { dimColor: true }))
712    }
713
714    rows.push(line(' '))
715    rows.push(line('Progress', { bold: true }))
716    const made = [...simple].sort((a, b) => order({ ts: a.ts, qn: 0, slug: a.slug, file: '' }, { ts: b.ts, qn: 0, slug: b.slug, file: '' }))
717    if (made.length === 0) rows.push(line('No projects yet.', { dimColor: true }))
718    for (const p of made) if (!p.finished) rows.push(line('  ' + bar(p.done, p.total) + ' · ' + p.title))
719    const fin = made.filter(p => p.finished)
720    if (fin.length) rows.push(line('  ✓ Finished: ' + fin.map(p => p.title).join(', '), DONE))
721
722    rows.push(line(' '))
723    if (creating) rows.push(line('Creating "' + creating.title + '"…', { dimColor: true }))
724    else if (formHeld && formHeld.kind === 'open') rows.push(line('Opening the new project form…', { dimColor: true }))
725    else if (!sending) rows.push(Button({ key: 'new-project', label: simple.length ? 'New project' : 'Start your first project', hotkey: 'n', onPress: () => formRun($, 'open', '') }))
726  }
727  rows.push(line(' '))
728  rows.push(Button({ key: 'refresh', label: 'Refresh', hotkey: 'r', onPress: async () => { await refreshSimple($); $.ui.invalidate('ui.render') } }))
729  return Box({ flexDirection: 'column', children: rows })
730}
731
732// A main-loop turn that started after a held answer's press is that answer's turn (a plugin's
733// command runs once the session is idle); if it ends with the document unmoved, release it.
734async function settle($: any, e: any): Promise<void> {
735  if (MODE !== 'simple' || (held.size === 0 && !creating && !formHeld) || (e && e.agentId)) return
736  const started = (await $.clock.now()) - toint(e && e.durationMs)
737  await refreshSimple($)
738  if (creating && started >= creating.at) { creating = null; createNote = 'The project was not created — the conversation says why.' }
739  if (formHeld && started >= formHeld.at) { formHeld = null; createNote = 'The form did not change — see the conversation.' }
740  let dropped = ''
741  for (const [id, h] of held) if (started >= h.at) { held.delete(id); dropped = h.text }
742  if (dropped) sendNote = 'Your answer to "' + dropped + '" did not change the task — see the conversation, then answer again.'
743  $.ui.invalidate('ui.render')
744}
745
746function summarySimple(): string {
747  if (kind !== 'ok') return detail
748  return 'loopd: ' + simple.length + ' project(s) · ' + inbox().length + ' question(s) for you · ' + tasks(helps).length + ' blocked'
749}
750
751// ---------------------------------------------------------------- hooks
752// true when what the pane draws may have changed.
753async function reread($: any, force: boolean): Promise<boolean> {
754  if (MODE === 'simple') return refreshSimple($)
755  const before = reads; await refresh($, force); return reads !== before
756}
757
758export function register(on: any, options?: any) {
759  MODE = options && options.mode === 'simple' ? 'simple' : 'operator'
760  on('session.start', async ($: any, e: any, next: any) => {
761    // `immediate` so /pane opens while a turn is streaming. A taken name throws and
762    // would skip the rest of this hook, so it is caught and said once, where someone can see it.
763    try {
764      await $.command.register({ name: COMMAND, description: 'Draw this bundle\'s loopd board in a pane', immediate: true })
765    } catch (err: any) {
766      if (e && e.isInteractive === true) $.ui.log('/' + COMMAND + ' not registered: ' + clean(err && err.message ? err.message : String(err)))
767    }
768    return next(e)
769  })
770
771  on('command.run', { command: COMMAND }, async ($: any) => {
772    await reread($, true)
773    let placed = false
774    try { const r = await $.ui.open({ id: PANE, title: TITLE }); placed = !!(r && r.isPlaced === true) } catch { placed = false }
775    if (!timer) {
776      // The poll redraws only when a file it reads moved; it never runs or submits
777      // anything. It starts with the pane and ends with it (ui.close below).
778      try { timer = $.clock.every(POLL_MS, async () => { if (await reread($, false)) $.ui.invalidate('ui.render') }) } catch { timer = null }
779    }
780    // Where no surface draws a pane (a narrow terminal, a `-p` run), one transcript line.
781    if (!placed) $.ui.log(MODE === 'simple' ? summarySimple() : summary())
782    return {}
783  }).catch(async (_$: any, e: any, next: any) => next(e))   // fail OPEN: a broken pane never eats the command
784
785  on('turn.complete', async ($: any, e: any, next: any) => {
786    try { await settle($, e) } catch { /* the next poll reads again */ }
787    return next(e)
788  })
789
790  on('ui.close', { id: PANE }, async (_$: any, e: any, next: any) => {
791    if (timer) { try { timer.cancel() } catch { /* already gone */ } timer = null }
792    return next(e)
793  }).catch(async (_$: any, e: any, next: any) => next(e))   // fail OPEN: the pane still closes
794
795  on('ui.render', { component: 'Pane', requestId: PANE }, async ($: any, e: any) => {
796    if (kind === 'unread') {
797      // Drawn before /pane ran (a reload while the pane stayed up): read, then redraw.
798      reread($, true).then(() => $.ui.invalidate('ui.render'), () => $.ui.invalidate('ui.render'))
799    }
800    return MODE === 'simple' ? drawSimple($, e) : draw($, e)
801  })
802}
803