Graph engineering for the harness flow. A local MCP server owns the node graph, routes execution across vendor CLIs or the session, adjudicates results against…

English · 한국어
Graph engineering for the harness flow, mediated by a local MCP server. The main session orchestrates; the graph engine owns state, routing, execution, and adjudication.
Sibling to harness, not a replacement. harness owns the six-stage reasoning contract. graph owns who executes a node, and whether the result survives contact with the worktree.
The static Workflow engine had to spawn a transport subagent per node just to drive a vendor CLI through Bash. A subagent waiting on a long-running process can only poll, and cache-read scales with turn count. Measured on one real run, same unit of work:
| shell turns in the node | cache-read tokens |
|---|---|
| 4 | 227,323 |
| 12 | 1,281,319 |
| 17 | 1,965,390 |
Across that run the transport layer cost more than the reasoning layer. An MCP call is one turn and blocks, so a node cannot poll — the failure mode is removed structurally rather than discouraged in a prompt.
Install the marketplace plugin and use graph:install to verify the connection:
/plugin install graph@newkayak12-claude-skills
trophy rides along. From this version, the first interactive session after you install or update this plugin installs trophy (achievements) once, in user scope, if you don't have it. Nothing is sent until you say yes; uninstalling trophy is respected (it is never reinstalled). To opt out beforehand:
mkdir -p ~/.claude/plugins/.newkayak12-trophy-ride.done. Needssh(Windows without one is not covered).
For a source checkout, graph:install can instead merge this direct registration:
{
"mcpServers": {
"graph-engineering": { "command": "node", "args": ["<plugin root>/mcp/broker.mjs"] }
}
}
Zero runtime dependencies, Node 18+.
Optional: graph:install can run develop:like-my-code to write .claude/conventions/; the broker then tells every plan, setgoal, implement, and test node, on any vendor, to read and follow the relevant files.
/graph-status draws on terminal, desktop, mobile and vscode; the key input shows only where the surface carries one (mobile keeps the buttons).node-gate.mjs denies a write to a gated path (.claude/harness-gate.json) outside a run. The gate helpers ship as a vendored copy (hooks/vendor/goal-gate.mjs), so an installed graph no longer reaches into the harness plugin's folder.retry n/m, retrying as setgoal:N, gave up); a self-correcting retry is info, not a failure. The reason and next step come from scripts/failure-events.mjs; the mod only draws them./graph-status (was /graph-live): a Now line per running node with vendor·model and time; Flow shows each rejected attempt's reason with the retry under it; Detail lists every attempt with its feedback. Closes on Esc, q or the command again.outcome state for trophy to count; no ids, and graph works the same without trophy.HARNESS_NODE=1; a new Skill hook (hooks/node-gate.mjs) denies a node's call to a run entry skill (harness, graph:orchestrate, teams entry skills) with a stop-and-report message, so a node cannot start a run inside a run.gate:goal evidence is a table, one | AC | verdict | evidence | row per AC-n, then an "Out of spec:" list.gate:goal prompts use the AC-n contract: goal-level criteria are AC-n (spec.md IDs reused, else Given/When/Then with an unstated-criteria sweep and [확인 필요]); the goal gate gives one evidence row per AC-n (unmet without) and flags out-of-spec changes. A behaviour-preserving or one-line request gets one proportional AC-1 with one piece of evidence and no sweep. (2026-10-12).codex-plugin/plugin.json, ${PLUGIN_ROOT}); Claude reads them from plugin.json..claude/conventions/** (setgoal folds them into acceptance); install offers develop:like-my-code for a reference project/graph-live pane (Claude Code 2.1.292+, early access, interactive sessions): a read-only view of this folder's newest graph run in the teams 0.46.0 style. Tabs Flow / Nodes (keys 1-2), a stage rail, the Next / Now / Blocked line, one row per subgoal (impl → test → gate) and a gates bar; Nodes is a To do / Doing / Done board. The mod only reads the run files; files over 4 MiB are skipped. No band of its own: graph runs already show in the harness pipeline band. English by default, Korean with Claude Code's language. Mod tests 20; real Claude Code captures EN/KO.acquireLock set its deadline from Date.now(), so a forward wall-clock jump (wake from sleep, an NTP step) made a waiter throw LockTimeoutError at once instead of waiting out its timeout. The deadline now uses performance.now(); stale-lock mtime checks stay on the wall clock. The default timeout is unchanged, nothing imported from teams. Tests: graph suite 146 (from 145).ownerGone judged a claim by its owner's pid and boot, so a running claim stamped under the broker's own pid was never reclaimed, even when this process no longer held its ticket. activeNodes now maps each held node to its ticket, and an own-pid claim with a matching boot is reclaimed (abandoned) only when this process does not hold that ticket; a held claim is never reclaimed. The existing boot-id branch (a claim from another boot is reclaimed though its pid is alive) gets its first repo test, with a live-pid control that stays running and a skip where /proc/sys/kernel/random/boot_id is absent; deleting the boot comparison makes the test fail. No default changed, nothing imported from teams. Tests: graph suite 145 (from 143).writeFileSync), so a reader could see half a file, and a lock that timed out let the write go ahead unlocked. New mcp/store.mjs (graph's own; nothing imported from teams): mutateRun takes the lock, reads the run fresh, runs fn, and writes to a temp file then renames, all under one lock. A lock timeout (GRAPH_LOCK_TIMEOUT_MS, 5000) throws LockTimeoutError; a live owner's lock is never taken; a dead owner's lock is broken only under a separate <lock>.steal lock. Every broker write goes through it, and open-nodes.json is written the same way. Claim before run: graph_run claims the node with a ticket before it starts the adapter, so a second call on the same node is refused instead of running the vendor twice; a result or interruption whose ticket no longer holds is recorded result_superseded, not applied; retrying a subgoal or spec also retires its running nodes. Ported from teams (each re-checked as a defect here, each with a test that failed before): #1 a retry after a spec retry no longer waits on the dead generation; #2 report waits on live nodes; #6 changed_files claims with spaces, non-ASCII, notes, globs or renames match git; #7 a claimed file that exists but is git-ignored is not contradicted; #8 the torn read above; #9 an author stage_ok:false with no reason and passing checks goes on to be judged; #10 a rejection with no reason gets one from its checks/evidence; #11 malformed vendor JSON gets one fresh attempt. Not ported: #3 (finished ≠ delivered) only adds a settled field to runState's return, and graph already shows a settled failure in its node states (unreachable) and the report, so it adds nothing graph lacks; #4 (test goes to the non-implementing vendor) and #5 (author runs last under either allocation) are routing policy, and graph routes by the explicit or ordered allocation its user set. Also not ported, as features or policy rather than defects: daemon/taskmanager-only fixes (e332ed4 dispatchSettled/fold_deferred, 2917e2e, 5cbfb19, 1d4bb37); 0a34817 (graph has no autoReassign, and spec problems already reach graph_retry); c182b99/453ff06 (graph has no goal threshold; the rest is cards and pins); 1fccf7f (graph has no draft/review stages); 4983843, fd78c4a, e8086b7, dd610ef, 8406e45, fe1ed28, ff1e8df m1/m2/m4/m5/m8/m10/m12 and f0ee114 (teams features); 9d359b0 capacityNotice/routing_blocked_capacity (manager parking); 094de8c (a cost policy that changes the gate contract); edd29fc (requireRunnable already refuses duplicates); ecd8c81/32f05eb (--verify Bash, a feature). Race and crash repairs: the steal is race-free: <lock>.steal is a link()ed file carrying its owner, a dead holder is succeeded through <lock>.steal.<key> and never removed by name, so one link() wins (same scheme as teams, graph's own code). A throw after the claim (prompt write, adapter, outcome) releases the claim: the node goes back to pending with its pre-claim fields, ledger claim_failed. A claim records the owner's pid and boot id, and a running node is reclaimed only when that process is dead or the claim came from another boot; elapsed time is used only for old run files with no owner, so a live adapter run longer than 10 minutes keeps its node and its result applies. Tests: new test-store (24) and test-ports (13), graph suite 143.## What Claude Does / What You Do table. Documentation only; no broker change.teams/scripts/bench/) drove this engine's code through real sessions and hit three defects the unit suite never had; both stable bench runs reproduced the first. (1) A driving session that reports itself as claude-opus-5[1m] — a context variant the fresh-agent picker does not list — blocked at plan with native host cannot select model; the host's own model is now selectable by definition. (2) The execution default names a tier (sonnet) and hosts declare ids (claude-sonnet-5); the check compared strings, so every implement node could be vendor-failure with zero failed nodes, and the only way out was a second graph_open. Tiers now resolve against the declared list, and an undeclared tier runs on the host model with the substitution written into the routing reason. (3) A gate:goal that rejected the assembled result was never re-judged after the subgoal it blamed was retried — the run wedged with the fix in place; a subgoal retry now opens gate:goal:N over the live gates and moves report behind it, and the retried subgoal's briefing carries the goal gate's reason and gaps (and a failed test's checks, which a retry used to lose). Tests ported with the fixes. Bench: one run of this version's predecessor on a 4-package request completed 9/9 at 6× the cost and time of a plain session; teams' manager on the same request is a different topology (four runs plus a manager) and is read separately there.report hung behind gate:goal, and a subgoal that ran out of retries left the run blocked forever - the subgoals that HAD passed were never reported. Edges now come in two kinds: deps is a data dependency (the dep must be done) and after is order-only, Make's | prerequisite (the dep must have finished, not passed). report hangs off the goal gate with after. When graph_retry finds the budget gone it settles the failure instead of returning a dead end: every node that needed the dead node's output through a data edge becomes unreachable, transitively and with the reason; a node that had already failed downstream is final too; order-only edges do not propagate. The goal gate goes unreachable, report becomes ready, and the run ends complete with the partial account written by the report node. A plain failed with retries left settles nothing - the report cannot run ahead of a retry. A spec may give a subgoal after: [id], checked for self/dangling/cycle like deps. graph_retry returns unreachable[] and the next ready nodes when it declines; graph_status shows after and counts unreachable. Also fixed: a report rebuilt after a spec retry (report:2) was briefed without the whole run, and a critique's blocking / problems never reached the goal gate or the report.in_progress on dispatch, completed on the verdict — with the text lines kept as the fallback for hosts without one. Same small vocabulary either way (node_id, vendor/model, state, short reason), and the same rule holds: a line you cannot write from the verdict is a line you do not write.report to the peer vendor but left the driver's output template narrating the run, so a graph node's payload had nowhere to go and a driver under context pressure would quietly re-narrate. The template now ends with a ### Report section relaying that node verbatim, and the mandates say plainly that the report node writes the run's account. The loop also prints one line per node as it goes — node_id, vendor/model, state, short reason — so a long run is visible while it runs; the line is written from the verdict the driver already holds, never from an opened payload. Duplication that had regrown against references/ is gone again. QA: Usefulness/Authoring/Output-Quality PASS, MCP NONE, Weight OK; eval delta +0.42 (12/12 vs 7/12), above the +0.375 baseline, re-measured after the edits with no regression. The driver is also told plainly that the broker does not serialize concurrent implement nodes — readyNodes returns every dependency-satisfied node, so keeping two of them off one worktree is the caller's job.report routes to the vendor that did not drive the run, so a run's account of itself is not written by its own driver; it stays reasoning work (read-only sandbox, host_model if it falls back to the host). graph_status now takes no run_id: it lists every run in a directory with state, counts, the node running right now with its vendor and elapsed seconds, and the last node to finish — so a lead that lost the id, or a second operator looking in, can find the run without the transcript. A running node in the single-run view carries the same detail. First full cross-vendor E2E on 1.5.7 completed 8/8 with Codex implementing and testing under danger-full-access and changed_files_verified: true.changed_files claim against git's relative output and failed every truthful node that used the briefing's own paths. Claude gains danger-full-access (--permission-mode bypassPermissions) as a per-run opt-in, matching Codex; defaults are unchanged and still answer to the project's permission settings.isolated: true requires an actual worktree rather than a user's stated wish for one.cwd so a restarted client can find the run, and the last duplication the weight check found is gone (briefing rules and the ranking sentence live in references/ only).references/, and names its trigger phrases.skills/orchestrate/references/; the skill keeps the loop, the mandates, and the verdict contract (275 -> 186 lines).graph_retry that is going to be rejected no longer clears capacity exclusions first, and an ordinary probe failure is never laundered into a capacity exclusion.graph_retry({reset_capacity:true}) with no interrupted node to name.graph:orchestrate defaults to the active Codex or Claude session for every stage, using its native tools and current model. External vendor routing remains optional; no Codex CLI or fixed model is required.graph:orchestrate now keeps reasoning, gates, and reporting on the Claude session while requiring Codex for implement/test. The node's selected model is forwarded into both Codex readiness probes, with model-scoped probe caching, so a bad global default cannot reject a run that names a working model explicitly.graph:orchestrate: ordinary skill-driven runs now open with vendor: "auto", candidates: ["codex"], so the bundled adapter is actually used when its readiness probe passes and falls back visibly to self when unavailable. Direct callers that omit candidates retain the quiet auto behavior introduced in v1.0.1.graph_open takes model (a run-level default) and policy, a per-stage override map keyed by stage name plus the optional gate:goal — each entry may set vendor, candidates, sandbox, model. This expresses the harness contract directly: reasoning on a strong model, execution on whatever can actually write on this host. graph_next reports the chosen model per ready node, and an explicit graph_run({model}) still wins for one call. Verified by a reduced-scale codex E2E that reached report with artifacts checked independently of the run's own verdicts.vendor: "auto" no longer enrols every registered vendor as a candidate; the candidate list is empty by default, so an unnamed run degrades to self through the existing path. The codex vendor, its adapter, and the readiness probe are unchanged and still route when named (vendor: "codex") or listed in candidates.broker plugin name and split lifecycle from execution: graph:install connects/verifies it, while graph:orchestrate drives the graph. Engine code and on-disk run format remain the existing implementation.| tool | purpose |
|---|---|
graph_open | throw a raw request in; the broker builds the flow as a node graph on disk |
graph_next | ask which nodes are ready, and how each is routed |
graph_run | the routed vendor executes one node; blocks; returns a one-line verdict |
graph_submit | record a node the orchestrator executed itself; same adjudication |
graph_retry | open a fresh attempt, carrying rejection feedback — a subgoal, or the spec itself. Budget gone: settles the failure, returns unreachable[] and the now-ready report |
graph_status | compact run state; omit run_id for every run in a directory and what is running right now; full:true only for one node at a time |
The goal-spec, subgoal acceptance, upstream handoffs, prior rejection feedback, changed-file lists and evidence all stay in the graph on disk. Tools return {node_id, stage, vendor, state, stage_ok} and a short reason. Two consequences:
setgoal expands the graph inside the broker. The spec it produces never passes through the caller; the per-subgoal implement/test/gate nodes and their dependencies are derived from it server-side.graph_run does not accept a prompt — passing one is impossible on purpose.This is what makes a long loop possible. If node results accumulated in the orchestrator's context, a graph with retries would exhaust it and the loop would die before the work did.
plan -> setgoal -> critique, then per subgoal implement -> test -> gate with subgoal dependencies mapped onto gate nodes, then gate:goal:1 -> report.
Edges come in two kinds. deps is a data dependency: the node consumes what the dep produced, so the dep must be done. after is order-only — Make's | prerequisite: the node must not start before the dep has finished, but it does not need the dep to have passed. report hangs off the goal gate with after, which is what lets it write the account of a failure. A spec may give a subgoal after: ["U1"] alongside deps.
Failure becomes settled at exactly one point: when graph_retry finds the retry budget gone. Until then a failed node is a retry waiting to happen and nothing downstream is written off. Once settled, every node that needed the dead node through a data edge becomes unreachable, transitively and with the reason (unreachable: gate:U1:2 is unreachable); a downstream node that had already failed is final too; order-only edges do not propagate. The goal gate goes unreachable, report b
hooks/mod.tsx 405 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { GraphRow, OpenedRun } from '../types'
5import { fmt, isKorean, tabs } from './draw'
6import { bandLines, cells, detailLines, footerKeys, paneBody, renderLines } from './graph-draw'
7import type { PaneCtx } from './graph-draw'
8import { cycleRun, frozenOrder, listArgv, markLooked, paneKey, paneSlash, parseOpenArg, parseRow, parseRows, pickRun, runPosition, showArgv, spinnerPlan, standalone } from './status'
9
10// Read only: the mod runs the node readout (`broker.mjs runs --list/--show --json`) and writes nothing.
11const tab = atom({ plugin: 'graph', key: 'view' } as const, 'flow' as 'flow' | 'detail')
12const lang = atom({ plugin: 'graph', key: 'lang' } as const, 'en' as 'en' | 'ko')
13// the open runs of the last good list; [] until the readout first answers
14const rows = atom({ plugin: 'graph', key: 'rows' } as const, [] as GraphRow[])
15// the run the pane shows, by run_id; null (or one no longer listed): opening order decides
16const selected = atom({ plugin: 'graph', key: 'selected' } as const, null as string | null)
17// per run_id, the rejects the person has seen
18const looked = atom({ plugin: 'graph', key: 'looked' } as const, {} as Record<string, number>)
19// a run opened by `/graph-status open <run-file> <owner-key>`: not in the band or the [ ] list
20const opened = atom({ plugin: 'graph', key: 'opened' } as const, null as OpenedRun | null)
21const spin = atom({ plugin: 'graph', key: 'spin' } as const, 0)
22
23const PANE = 'graph-status'
24const TICK_MS = 5000
25const SPIN_MS = 800 // a spinner frame; only while a shown run acts
26const LIST_TIMEOUT_MS = 10_000
27
28const en = {
29 tabFlow: 'Flow', tabDetail: 'Detail', noRun: 'No graph run in this folder.',
30 cmdDesc: 'Open or close the graph status pane', paneOpened: 'pane opened', paneClosed: 'pane closed',
31 closeBtn: 'q', closeWord: 'close', prev: '[ prev', next: 'next ]', bandOpen: 'open',
32 openFailed: 'could not read that run file',
33 attempt: '(attempt {n})', feedback: 'feedback', more: '+{n} more',
34}
35
36// one table, two languages; the type keeps the keys identical
37export const STRINGS: Record<'en' | 'ko', Record<keyof typeof en, string>> = {
38 en,
39 ko: {
40 tabFlow: '흐름', tabDetail: '상세', noRun: '이 폴더에 그래프 실행이 없습니다.',
41 cmdDesc: '그래프 상태 창 열기/닫기', paneOpened: '창을 열었습니다', paneClosed: '창을 닫았습니다',
42 closeBtn: 'q', closeWord: '닫기', prev: '[ 이전', next: '다음 ]', bandOpen: '열기',
43 openFailed: '그 실행 파일을 읽을 수 없습니다',
44 attempt: '({n}번째 시도)', feedback: '전달된 피드백', more: '+{n}건 더',
45 },
46}
47type Key = keyof typeof en
48
49// what scripts/failure-events.mjs returns per failed, reshaped or blocked node: the mod renders it as given
50type FailureEvent = {
51 key: string
52 kind: string
53 node: string
54 attempt: number
55 what: string
56 reason: string
57 next_step: string | null
58 severity: 'info' | 'failure'
59}
60type RunEvent = { key: string; kind: string; node: string; attempt: number }
61
62const FAILURE_MS = 10_000 // an info toast keeps the default timeout; a failure stays longer
63const PUSH_MAX = 200
64const PUSHED_STEPS = ['gave up', 'needs you']
65
66// the node script's events for one run file; a failed call or unreadable output is no events
67async function fetchFailures($: EngineInterface, file: string): Promise<FailureEvent[]> {
68 try {
69 const r = await $.process.run(['node', `${$.plugin.root}/scripts/failure-events.mjs`, file])
70 if (r.exitCode !== 0) return []
71 const out: unknown = JSON.parse(r.stdout.trim())
72 return Array.isArray(out) ? (out as FailureEvent[]) : []
73 } catch {
74 return []
75 }
76}
77
78// icon and timeout from the node-given severity and next_step only
79const failureIcon = (ev: FailureEvent) => (ev.next_step === 'needs you' ? '⚠' : ev.severity === 'failure' ? '✗' : '↻')
80const failureLine = (row: GraphRow, ev: FailureEvent) =>
81 `${row.id8} ${ev.what} failed: ${ev.reason}${ev.next_step === null ? '' : ` → ${ev.next_step}`}`
82
83// the run finished: the one event the mod reads from the row itself (the node decided its state)
84function completeEvent(row: GraphRow): RunEvent[] {
85 if (row.state !== 'complete') return []
86 const report = row.nodes.find(n => n.stage === 'report' && n.state === 'done')
87 if (report === undefined) return []
88 const attempt = report.attempt ?? 1
89 return [{ key: `${row.run_id}:${report.node_id}:complete:${attempt}`, kind: 'complete', node: report.node_id, attempt }]
90}
91
92// PushNotification's result: { message, pushSent?, localSent?, disabledReason? } (user_present at the terminal)
93async function push($: EngineInterface, message: string): Promise<boolean> {
94 try {
95 const out = (await $.tool.call({ tool: 'PushNotification', message, status: 'proactive' } as never)) as { result?: unknown }
96 const r = typeof out?.result === 'object' && out.result !== null ? (out.result as Record<string, unknown>) : undefined
97 return r?.pushSent === true || r?.localSent === true
98 } catch {
99 return false // a failed push is a push not sent
100 }
101}
102
103// The runs from the node CLI (rule 6: the path through $.plugin.root). A non-zero exit, a timeout, a throw or output
104// that is not a list is no answer: null, and the caller keeps its last good list.
105async function loadRows($: EngineInterface): Promise<GraphRow[] | null> {
106 try {
107 const out = await $.process.run(listArgv($.plugin.root, await $.session.cwd()), { timeoutMs: LIST_TIMEOUT_MS })
108 return out.exitCode === 0 ? parseRows(out.stdout) : null
109 } catch {
110 return null
111 }
112}
113
114// one run file as the node shows it; no answer is null
115async function showRow($: EngineInterface, file: string): Promise<GraphRow | null> {
116 try {
117 const out = await $.process.run(showArgv($.plugin.root, file), { timeoutMs: LIST_TIMEOUT_MS })
118 return out.exitCode === 0 ? parseRow(out.stdout) : null
119 } catch {
120 return null
121 }
122}
123
124// The run_id order `[` / `]` walk, fixed while the listed set is the same. A cache a reload may lose: the order is then worked out again.
125let frozen: string[] | null = null
126// Set at session.start of a session that has a surface; no surface, never set, no timer. Caches a reload may lose.
127let kick: (() => Promise<void>) | null = null
128let spinner: { cancel: () => void } | null = null
129let isRunning = false
130
131// What the pane and band draw: the standalone runs in opening order, the one shown, and the opened run when there is one.
132async function view($: EngineInterface) {
133 const ordered = frozenOrder(standalone(await read($, rows)), await read($, looked), frozen)
134 frozen = ordered.map(r => r.run_id)
135 const sel = await read($, selected)
136 const op = await read($, opened)
137 return { ordered, sel, op, picked: op?.row ?? pickRun(ordered, sel) }
138}
139
140async function paneOpen($: EngineInterface): Promise<boolean> {
141 try {
142 return (await $.ui.panes()).some((p: { id: string }) => p.id === PANE)
143 } catch {
144 return false // panes unreadable: closed
145 }
146}
147
148// The faster interval runs only while a shown run acts: the pane's run, or the band's leading one.
149async function syncSpinner($: EngineInterface) {
150 try {
151 const v = await view($)
152 const shown = (await paneOpen($)) ? [v.picked] : [v.ordered[0] ?? null]
153 const { run: go } = spinnerPlan(shown, (await $.session.surfaces()).length, shown.some(r => r !== null))
154 if (go && spinner === null) spinner = $.clock.every(SPIN_MS, () => step($))
155 else if (!go && spinner !== null) {
156 spinner.cancel()
157 spinner = null
158 }
159 } catch {
160 // a failed check leaves the timer as it was
161 }
162}
163async function step($: EngineInterface) {
164 await syncSpinner($)
165 if (spinner !== null) await update($, spin, n => n + 1)
166}
167
168// The one place the pane is opened from closed (the command and the band's button): the run opening order picks is the
169// run shown from here on, by run_id. Open already: no-op.
170async function openPane($: EngineInterface): Promise<void> {
171 if (await paneOpen($)) return
172 frozen = null // opened from closed: orders again, an unseen reject leads
173 const v = await view($)
174 await update($, selected, () => v.picked?.run_id ?? null)
175 await update($, looked, l => markLooked(l, v.picked))
176 await $.ui.open({ id: PANE, title: 'Graph', focus: true, closeOnEscape: true })
177 await kick?.()
178}
179
180async function closePane($: EngineInterface): Promise<void> {
181 await $.ui.close({ id: PANE })
182 await update($, opened, () => null)
183 await kick?.()
184}
185
186// `[` and `]`: the next run by run_id, marked as looked at; at an end, one run, or an opened run, nothing changes
187async function cycle($: EngineInterface, by: 1 | -1) {
188 const v = await view($)
189 if (v.op !== null) return
190 const id = cycleRun(v.ordered, v.sel, by)
191 if (id === (v.picked?.run_id ?? null)) return
192 await update($, selected, () => id)
193 await update($, looked, l => markLooked(l, pickRun(v.ordered, id)))
194 await kick?.()
195}
196
197export const register: Register = on => {
198 on('session.start', async ($, e, next) => {
199 if ((await $.session.surfaces()).length === 0) return next(e)
200 // a second session.start (a cleared session) starts over: the old interval ends
201 spinner?.cancel()
202 spinner = null
203 frozen = null
204 kick = () => syncSpinner($)
205
206 const startMs = await $.clock.now()
207 const pushed = new Set<string>()
208 const baselined = new Set<string>()
209 const published = new Set<string>()
210 const scanned = new Map<string, number>() // run id -> the file mtime its events were taken from
211
212 // a failed, reshaped or blocked node toasts (a gave up also pushes); a finished run pushes (a toast when it is not sent)
213 async function notifyRun(row: GraphRow) {
214 try {
215 // the events change only when the file does: one script run per write
216 if (scanned.get(row.run_id) === row.last_change_ms) return
217 scanned.set(row.run_id, row.last_change_ms)
218 const failures = await fetchFailures($, row.file)
219 const fresh: (RunEvent | FailureEvent)[] = [...failures, ...completeEvent(row)].filter(ev => !pushed.has(ev.key))
220 for (const ev of fresh) pushed.add(ev.key)
221 // a run last written before this session started: what it already holds is not news
222 if (!baselined.has(row.run_id)) {
223 baselined.add(row.run_id)
224 if (row.last_change_ms < startMs) return
225 }
226 for (const ev of fresh) {
227 // the run outcome trophy counts: one per (run, outcome); a node reject is a retry, not an outcome
228 const outcome = ev.kind === 'complete' ? 'pass' : ev.kind === 'failed' || ev.kind === 'blocked' ? 'fail' : undefined
229 if (outcome !== undefined && !published.has(`${row.run_id}:${outcome}`)) {
230 published.add(`${row.run_id}:${outcome}`)
231 try {
232 await $.state.set({ plugin: 'graph', key: 'outcome' }, { system: 'graph', outcome, at: await $.clock.now() })
233 } catch {
234 // fail open: a lost outcome never costs the push
235 }
236 }
237 if ('what' in ev) {
238 const line = failureLine(row, ev)
239 const long = ev.severity !== 'info' || ev.next_step === 'needs you'
240 const toast = `${failureIcon(ev)} ${line}`
241 if (long) $.ui.toast(toast, { timeoutMs: FAILURE_MS })
242 else $.ui.toast(toast)
243 if (ev.next_step !== null && PUSHED_STEPS.includes(ev.next_step)) await push($, `graph ${line}`.slice(0, PUSH_MAX))
244 continue
245 }
246 const max = typeof row.max_retries === 'number' ? `/${row.max_retries}` : ''
247 const message = `graph ${row.id8}: ${ev.kind} — ${ev.node} (${ev.attempt}${max})`.slice(0, PUSH_MAX)
248 if (!(await push($, message))) $.ui.toast(message)
249 }
250 } catch {
251 // fail open: the pane is unaffected
252 }
253 }
254
255 // the readout again; a failed read leaves the last good list
256 async function tick() {
257 if (isRunning) return
258 isRunning = true
259 try {
260 const live = await loadRows($)
261 if (live !== null) {
262 await update($, rows, () => live)
263 // a run last written before the session, and not open, holds nothing new
264 for (const row of live) if (row.open || row.last_change_ms >= startMs) await notifyRun(row)
265 }
266 const op = await read($, opened)
267 if (op !== null) {
268 const row = await showRow($, op.file)
269 if (row !== null) await update($, opened, () => ({ ...op, row }))
270 }
271 // a reject that lands while the pane shows the run has been seen
272 if (await paneOpen($)) {
273 const shown = (await view($)).picked
274 await update($, looked, l => markLooked(l, shown))
275 }
276 } catch {
277 // an unreadable list leaves the last view as it was
278 } finally {
279 isRunning = false
280 }
281 await kick?.()
282 }
283
284 // Claude Code's own language setting, read once per session
285 try {
286 const language = (await $.settings.read()).language
287 await update($, lang, () => (isKorean(language) ? 'ko' : 'en'))
288 } catch {
289 // unreadable settings: English
290 }
291 await $.command.register({ name: 'graph-status', description: STRINGS[await read($, lang)].cmdDesc, argumentHint: '[open <run-file> <owner-key>]' })
292 await tick()
293 $.clock.every(TICK_MS, tick)
294
295 return next(e)
296 })
297
298 // The command again closes the pane; Esc and q close it too. `open <run-file> <owner-key>` is the hand-off from a teams
299 // task: that run is shown under its key, outside the band and the [ ] list. The answer is one line (the headless reply).
300 on('command.run', { command: 'graph-status' }, async ($, e) => {
301 const text = STRINGS[await read($, lang)]
302 const arg = parseOpenArg(e.args ?? '')
303 if (arg !== null && 'usage' in arg) return { text: arg.usage }
304 const isOpen = await paneOpen($)
305 if (arg === null && isOpen) {
306 await closePane($)
307 return { text: text.paneClosed }
308 }
309 if (arg !== null) {
310 const cwd = await $.session.cwd()
311 // absolute: the refresh re-reads this path from the engine's own cwd, where a relative one would stop updating
312 const file = arg.file.startsWith('/') ? arg.file : `${cwd}/${arg.file}`
313 const row = await showRow($, file)
314 if (row === null) return { text: text.openFailed }
315 await update($, opened, () => ({ file, owner: arg.owner, row }))
316 } else await update($, opened, () => null)
317 if (!isOpen) await openPane($)
318 else await kick?.()
319 return { text: text.paneOpened }
320 })
321
322 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
323 const { Box, Button, Input, Text } = $.ui.resolve(e)
324 const ui = { Box, Text, Button }
325 const lang$ = await read($, lang)
326 const s = (key: Key, vars?: Record<string, string | number>) => fmt(STRINGS[lang$][key], vars)
327 const kind = await read($, tab)
328 const v = await view($)
329 const r = v.picked
330 const n = v.op !== null ? 1 : v.ordered.length
331 const ctx: PaneCtx = {
332 width: Math.max(20, e.props.bodyColumns - 4), nowMs: await $.clock.now(), tick: await read($, spin),
333 pos: v.op !== null ? { k: 1, n: 1 } : runPosition(v.ordered, v.sel), ...(v.op !== null ? { owner: v.op.owner } : {}),
334 words: { attempt: STRINGS[lang$].attempt, feedback: STRINGS[lang$].feedback, more: STRINGS[lang$].more },
335 }
336
337 // `[` and `]` cannot be a Button hotkey; the pane's Input has the focus ring, takes every printable key, and status.ts
338 // paneKey reads the last one. The same Input takes a typed `/command` (card 57): held until Enter, then paneSlash maps
339 // it: `/graph-status` closes the pane, `/name args` runs that command, not awaited (awaited inside onSubmit the host
340 // cuts the hook at its 10 s budget).
341 const onKey = async (text: string) => {
342 const key = paneKey(text)
343 if (key === null) return
344 if (key.kind === 'step') await cycle($, key.by)
345 else if (key.kind === 'tab') await update($, tab, () => key.tab)
346 else await closePane($)
347 }
348 const onSubmit = async (text: string) => {
349 const slash = paneSlash(text)
350 if (slash === null) return
351 if (slash.kind === 'close') await closePane($)
352 else void $.command.run({ command: slash.command, args: slash.args }).catch(() => {})
353 }
354
355 let body
356 if (r === null) body = <Text>{s('noRun')}</Text>
357 else body = renderLines(ui, kind === 'flow' ? paneBody(r, ctx) : detailLines(r, ctx))
358 const keys = footerKeys(n)
359 return (
360 <Box flexDirection="column" borderStyle="round" borderColor="claude" paddingX={1}>
361 <Box marginBottom={1}>
362 {tabs(ui, [{ key: 'flow', label: s('tabFlow') }, { key: 'detail', label: s('tabDetail') }], kind, k => update($, tab, () => k as 'flow' | 'detail'))}
363 </Box>
364 {body}
365 <Box marginTop={1} columnGap={2}>
366 {keys.length > 1 && (
367 <Box columnGap={1} flexShrink={0}>
368 <Button key="prev" plain dimColor label={s('prev')} onPress={() => cycle($, -1)} />
369 <Button key="next" plain dimColor label={s('next')} onPress={() => cycle($, 1)} />
370 </Box>
371 )}
372 <Box columnGap={1} flexShrink={0}>
373 <Button key="close" role="dismiss" dimColor label={s('closeBtn')} hotkey="q" onPress={() => closePane($)} />
374 <Text dimColor>{s('closeWord')}</Text>
375 </Box>
376 {(e.surface === 'terminal' || e.surface === 'desktop' || e.surface === 'vscode') && (
377 <Box flexShrink={1} height={1} overflow="hidden"><Input key="keys" autoFocus value="" placeholder="" onInput={onKey} onSubmit={onSubmit} /></Box>
378 )}
379 </Box>
380 </Box>
381 )
382 })
383
384 // the band: one row for the leading standalone run, `+N` for the others, and a button that opens the pane
385 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
386 const v = await view($)
387 if (e.props.hasSurvey || v.ordered.length === 0) return next(e)
388 const { Box, Text, Button } = $.ui.resolve(e)
389 const label = STRINGS[await read($, lang)].bandOpen
390 const lines = bandLines(v.ordered, { width: e.props.bodyColumns, nowMs: await $.clock.now(), tick: await read($, spin), reserve: cells(label) + 5 }) // the Button draws `[ label ]` after a 1-column margin
391 if (lines.length === 0) return next(e)
392 return (
393 <Box flexDirection="column">
394 <Box>
395 <Box flexShrink={1}>{renderLines({ Box, Text, Button }, lines)}</Box>
396 <Box flexShrink={0} marginLeft={1}>
397 <Button key="open" label={label} onPress={async () => { await update($, opened, () => null); await openPane($) }} />
398 </Box>
399 </Box>
400 {await next(e)}
401 </Box>
402 )
403 })
404}
405hooks/draw.tsx 95 lines1/*
2 * Drawing kit for mods: stage rail, progress bar, tabs, board.
3 * Origin: teams/hooks/mod.tsx (teams 0.46.0). Copied per plugin because a mod imports only its own
4 * plugin's files; copies may drift, so change one and diff the other.
5 */
6export type Mark = 'done' | 'running' | 'pending' | 'failed'
7
8export const MARK: Record<Mark, string> = { done: '✔', running: '●', pending: '○', failed: '✘' }
9// the stage rail: a dot per stage, a solid rail up to where the run is, dotted after
10export const DOT: Record<Mark, string> = { done: '●', running: '◉', pending: '○', failed: '✘' }
11export const TINT: Record<Mark, string> = { done: 'success', running: 'claude', pending: 'inactive', failed: 'error' }
12
13// a key the table lacks formats to ''
14export const fmt = (text: string | undefined, vars: Record<string, string | number> = {}) =>
15 (text ?? '').replace(/\{(\w+)\}/g, (_, k: string) => String(vars[k] ?? ''))
16
17export const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
18
19// Claude Code's `language` setting
20export const isKorean = (language: unknown) => typeof language === 'string' && /^(ko|korean|한국어)/i.test(language)
21
22// filled cells of a bar `width` wide, clamped to 0..width
23export const cells = (done: number, total: number, width: number) =>
24 total > 0 ? Math.min(width, Math.max(0, Math.round((width * done) / total))) : 0
25
26// between two stages: solid once the next stage has started, dotted before
27export const connector = (nextState: Mark) => (nextState !== 'pending' ? ' ━━ ' : ' ┄┄ ')
28
29// the resolved components from $.ui.resolve(e)
30export type Ui = { Box: any; Text: any; Button: any }
31
32export function rail(ui: Ui, stages: { label: string; state: Mark }[]) {
33 const { Box, Text } = ui
34 return (
35 <Box flexWrap="wrap">
36 {stages.map((g, i) => {
37 const next = stages[i + 1]
38 return (
39 <Box key={`g${i}`}>
40 <Text color={TINT[g.state]} bold={g.state === 'running'}>{`${DOT[g.state]} ${g.label}`}</Text>
41 {next !== undefined && (
42 <Text color={next.state !== 'pending' ? 'success' : 'inactive'}>{connector(next.state)}</Text>
43 )}
44 </Box>
45 )
46 })}
47 </Box>
48 )
49}
50
51export function bar(ui: Ui, done: number, total: number, width: number, suffix?: string) {
52 const { Box, Text } = ui
53 const filled = cells(done, total, width)
54 return (
55 <Box>
56 <Text color="success">{'━'.repeat(filled)}</Text>
57 <Text color="inactive">{'─'.repeat(width - filled)}</Text>
58 {suffix !== undefined && <Text bold>{` ${suffix}`}</Text>}
59 </Box>
60 )
61}
62
63// plain tabs with hotkeys 1-9: the selected one in full strength with a dot, the rest dim
64export function tabs(ui: Ui, items: { key: string; label: string }[], current: string, onPick: (key: string) => void) {
65 const { Box, Button } = ui
66 return (
67 <Box columnGap={3}>
68 {items.map((one, i) => (
69 <Button key={one.key} plain hotkey={String(i + 1)} dimColor={current !== one.key}
70 label={`${current === one.key ? '● ' : ''}${one.label}`} onPress={() => onPick(one.key)} />
71 ))}
72 </Box>
73 )
74}
75
76// columns of bordered cards, each with a count in its title
77export function board<T>(
78 ui: Ui,
79 cols: { label: string; tint: string; items: T[] }[],
80 render: (item: T, i: number) => unknown,
81) {
82 const { Box, Text } = ui
83 const width = `${Math.floor(100 / Math.max(cols.length, 1))}%`
84 return (
85 <Box>
86 {cols.map(col => (
87 <Box key={col.label} flexDirection="column" width={width} borderStyle="round" borderColor={col.tint} paddingX={1}>
88 <Text bold color={col.tint}>{`${col.label} ${col.items.length}`}</Text>
89 {col.items.map(render)}
90 </Box>
91 ))}
92 </Box>
93 )
94}
95hooks/graph-draw.tsx 477 lines1/*
2 * Graph-only drawing: the band row and the pane as lines of styled segments, and the demo fixtures. Pure: every
3 * function takes a row (status.ts) and a width and returns lines; mod.tsx only renders them (renderLines).
4 * Follows harness/hooks/harness-draw.tsx. draw.tsx stays the copy shared with teams and harness, so nothing here edits it.
5 *
6 * Width is counted in terminal cells (cells): a Korean syllable is 2, so a line that fits by cells never wraps.
7 */
8import type { GraphRow, GraphRowNode } from '../types'
9import type { Ui } from './draw'
10import { NONE, ageText, costText, cycleRun, openingOrder, pickRun, runPosition, standalone } from './status'
11
12/* --- cell width --- */
13
14// [from, to, cells]: zero-width and double-width ranges; every other code point is one cell
15const WIDTH_RANGES: readonly (readonly [number, number, number])[] = [
16 [0x0, 0x1f, 0], [0x300, 0x36f, 0], [0x200b, 0x200f, 0], [0xfe0f, 0xfe0f, 0],
17 [0x1100, 0x115f, 2], [0x2e80, 0xa4cf, 2], [0xac00, 0xd7a3, 2], [0xf900, 0xfaff, 2], [0xfe30, 0xfe4f, 2],
18 [0xff00, 0xff60, 2], [0xffe0, 0xffe6, 2], [0x1f300, 0x1faff, 2], [0x20000, 0x3fffd, 2],
19]
20const cellOf = (cp: number) => WIDTH_RANGES.find(([a, b]) => cp >= a && cp <= b)?.[2] ?? 1
21export const cells = (text: string) => Array.from(text).reduce((n, c) => n + cellOf(c.codePointAt(0)!), 0)
22
23/* --- glyphs: only these mark state --- */
24
25export const GLYPH = { edit: '✎', read: '⌕', run: '▸', think: '…', judge: '⚖', done: '✔', fail: '✘', idle: '◌', you: '⚑', todo: '○' } as const
26
27// the spinner: the action glyphs that fit the stage, one frame per tick
28const FRAMES: Record<string, readonly string[]> = {
29 plan: [GLYPH.edit, GLYPH.think],
30 setgoal: [GLYPH.edit, GLYPH.think],
31 critique: [GLYPH.judge, GLYPH.think],
32 implement: [GLYPH.edit, GLYPH.read, GLYPH.run],
33 test: [GLYPH.run, GLYPH.read],
34 gate: [GLYPH.judge, GLYPH.think],
35 report: [GLYPH.edit, GLYPH.think],
36}
37export function spinnerFrame(tick: number, stage = 'implement'): string {
38 const f = FRAMES[stage] ?? FRAMES.implement!
39 return f[((tick % f.length) + f.length) % f.length]!
40}
41
42/* --- lines of segments --- */
43
44export type Tint = 'success' | 'claude' | 'inactive' | 'error'
45export type Seg = { t: string; tint?: Tint; bold?: boolean; dim?: boolean }
46export type Line = Seg[]
47
48const seg = (t: string, o: Omit<Seg, 't'> = {}): Seg => ({ t, ...o })
49export const plain = (l: Line) => l.map(s => s.t).join('')
50export const lineWidth = (l: Line) => l.reduce((n, s) => n + cells(s.t), 0)
51
52// cut to w cells; the cut ends in …
53export function clipLine(l: Line, w: number): Line {
54 if (lineWidth(l) <= w) return l
55 // trailing spaces are not text: a line that fits without them is not cut, so a lone `—` is never cut to `—…`
56 const last0 = l[l.length - 1]
57 if (last0 !== undefined && last0.t.trimEnd() !== last0.t) return clipLine([...l.slice(0, -1), ...(last0.t.trimEnd() === '' ? [] : [{ ...last0, t: last0.t.trimEnd() }])], w)
58 if (w <= 0) return []
59 const out: Line = []
60 let left = w - 1
61 for (const s of l) {
62 if (left <= 0) break
63 let kept = ''
64 let cut = false
65 for (const c of Array.from(s.t)) {
66 const n = cellOf(c.codePointAt(0)!)
67 if (n > left) {
68 cut = true
69 break
70 }
71 kept += c
72 left -= n
73 }
74 if (kept !== '') out.push({ ...s, t: kept })
75 if (cut) break
76 }
77 const last = out[out.length - 1]
78 if (last === undefined) return [seg('…')]
79 out[out.length - 1] = { ...last, t: `${last.t.trimEnd()}…` }
80 return out
81}
82
83export const clip = (text: string, w: number) => plain(clipLine([seg(text)], w))
84const pad = (text: string, w: number) => text + ' '.repeat(Math.max(0, w - cells(text)))
85
86// A row of segments that must fit w. Lowest priority goes first: `drop` > 0 segments leave in descending order,
87// each first cut to `min` cells (… at the cut) when it has one; segments with no `drop` never leave, and only
88// truncate (widest first) unless `fixed`. `right` on the last segment pads it to the right edge. Never wider than w.
89export type FitSeg = { parts: Seg[]; sep?: string; drop?: number; min?: number; fixed?: boolean; right?: boolean }
90export const fs = (text: string, o: Omit<FitSeg, 'parts'> & Omit<Seg, 't'> = {}): FitSeg => {
91 const { sep, drop, min, fixed, right, ...style } = o
92 return { parts: [seg(text, style)], sep, drop, min, fixed, right }
93}
94const fw = (f: FitSeg) => lineWidth(f.parts)
95
96export function fit(input: readonly FitSeg[], w: number): Line {
97 const segs = input.filter(f => fw(f) > 0)
98 const total = () => segs.reduce((n, f, i) => n + (i > 0 ? cells(f.sep ?? '') : 0) + fw(f), 0)
99 while (total() > w) {
100 let top = -1
101 segs.forEach((f, i) => {
102 if ((f.drop ?? 0) > 0 && (top < 0 || f.drop! >= segs[top]!.drop!)) top = i
103 })
104 if (top < 0) break
105 const f = segs[top]!
106 const over = total() - w
107 if (f.min !== undefined && fw(f) > f.min) segs[top] = { ...f, parts: clipLine(f.parts, Math.max(f.min, fw(f) - over)) }
108 else segs.splice(top, 1)
109 }
110 while (total() > w) {
111 let wide = -1
112 segs.forEach((f, i) => {
113 if (!f.fixed && (f.drop ?? 0) === 0 && fw(f) > 2 && (wide < 0 || fw(f) > fw(segs[wide]!))) wide = i
114 })
115 if (wide < 0) break
116 const f = segs[wide]!
117 // the widest gives way toward the next widest, so several long segments share the cut
118 const next = Math.max(0, ...segs.filter((g, i) => i !== wide && !g.fixed && (g.drop ?? 0) === 0).map(fw))
119 segs[wide] = { ...f, parts: clipLine(f.parts, Math.max(2, fw(f) - (total() - w), Math.min(next, fw(f) - 1))) }
120 }
121 const out: Line = []
122 const gap = w - total()
123 segs.forEach((f, i) => {
124 if (i > 0 && f.sep) out.push(seg(f.sep, { dim: true }))
125 if (f.right && i === segs.length - 1 && i > 0 && gap > 0) out.push(seg(' '.repeat(gap)))
126 out.push(...f.parts)
127 })
128 return clipLine(out, w)
129}
130
131// left text, right text on the same line: the right side sheds low-priority pieces first, then the left truncates
132export function leftRight(left: Line, rightSegs: readonly FitSeg[], w: number, minLeft = 10): Line {
133 const right = fit(rightSegs, Math.max(0, w - Math.min(lineWidth(left), minLeft) - 2))
134 const rw = lineWidth(right)
135 const l = clipLine(left, w - rw - (rw > 0 ? 2 : 0))
136 return [...l, seg(' '.repeat(Math.max(rw > 0 ? 2 : 0, w - lineWidth(l) - rw))), ...right]
137}
138
139// a plain bordered frame for the demo text; lines are padded or cut to the inside width
140export function frame(title: string, lines: readonly Line[], w: number): string[] {
141 const inner = w - 4
142 const top = `╭─ ${title} ${'─'.repeat(Math.max(0, w - 5 - cells(title)))}╮`
143 const body = lines.map(l => {
144 const c = clipLine(l, inner)
145 return `│ ${plain(c)}${' '.repeat(inner - lineWidth(c))} │`
146 })
147 return [clip(top, w), ...body, `╰${'─'.repeat(w - 2)}╯`]
148}
149
150// the one place Ink is touched: lines of segments as Text
151export function renderLines(ui: Ui, lines: readonly Line[]) {
152 const { Box, Text } = ui
153 return (
154 <Box flexDirection="column">
155 {lines.map((l, i) => (
156 <Text key={i} wrap="truncate-end">
157 {l.length === 0 ? ' ' : l.map((s, j) => <Text key={j} color={s.tint} bold={s.bold} dimColor={s.dim}>{s.t}</Text>)}
158 </Text>
159 ))}
160 </Box>
161 )
162}
163
164/* --- what a row says --- */
165
166const oneLine = (v: string | null) => (v ?? '').replace(/\s+/g, ' ').trim()
167const nodeLabel = (n: GraphRowNode) => (n.subgoal_id !== null ? `${n.stage} ${n.subgoal_id}` : n.stage)
168const runningNode = (r: GraphRow) => r.nodes.find(n => n.state === 'running') ?? null
169const createdMs = (r: GraphRow) => {
170 const ms = Date.parse(r.created_at)
171 return Number.isFinite(ms) ? ms : null
172}
173const sinceText = (from: number | null, nowMs: number) => ageText(from === null ? null : nowMs - from)
174const stateWord = (r: GraphRow) => (r.stalled ? 'stalled' : r.state)
175const tryText = (n: GraphRowNode, max: number | null) => (n.attempt === null ? '' : `try ${n.attempt}${max !== null ? ` of ${max}` : ''}`)
176
177const stateGlyph = (r: GraphRow, tick: number): Seg => {
178 if (r.routing_blocked) return seg(GLYPH.you, { tint: 'claude', bold: true })
179 if (r.state === 'complete') return seg(GLYPH.done, { tint: 'success', bold: true })
180 const run = runningNode(r)
181 if (run !== null && !r.stalled) return seg(spinnerFrame(tick, run.stage), { tint: 'claude', bold: true })
182 return seg(GLYPH.idle, { tint: 'inactive', bold: true })
183}
184
185/* --- the band: one row for the leading standalone run --- */
186
187// `ordered` is the opening order; an owned or closed run is dropped here too, so it never adds to +N.
188// `reserve` cells at the end are left to mod.tsx's open button.
189export function bandLines(ordered: readonly GraphRow[], o: { width: number; nowMs: number; tick: number; reserve?: number }): Line[] {
190 const rows = standalone(ordered)
191 const r = rows[0]
192 if (r === undefined) return []
193 const more = rows.length - 1
194 const dim = r.stalled
195 const run = runningNode(r)
196 const plus: FitSeg = { ...fs(`+${more}`, { sep: ' ', fixed: true, dim: true }), right: true }
197 const parts: FitSeg[] = [
198 // a stalled run still leads with ⚑ when it waits on the person; otherwise the idle glyph
199 { parts: [dim && !r.routing_blocked ? seg(GLYPH.idle, { tint: 'inactive', bold: true }) : stateGlyph(r, o.tick)], fixed: true },
200 fs('graph', { sep: ' ', drop: 6, dim: true }),
201 fs(r.id8, { sep: ' ', bold: !dim, dim }),
202 ]
203 if (dim) parts.push(fs(`stalled · ${sinceText(r.last_change_ms, o.nowMs)}`, { sep: ' ', dim: true }))
204 else {
205 parts.push(
206 run === null ? fs('') : fs(nodeLabel(run), { sep: ' · ', drop: 2, min: 10 }),
207 r.last_step === null ? fs('') : fs(r.last_step, { sep: ' · ', drop: 4, min: 16, dim: true }),
208 fs(sinceText(createdMs(r), o.nowMs), { sep: ' · ', drop: 3 }),
209 )
210 }
211 parts.push(fs(costText(r), { sep: ' · ', fixed: true, bold: !dim, dim }), more > 0 ? plus : fs(''))
212 return [fit(parts, o.width - (o.reserve ?? 0))]
213}
214
215/* --- the pane --- */
216
217// words of the Detail tab with `{n}` slots; English when the caller gives none
218export type DetailWords = { attempt: string; feedback: string; more: string }
219const EN_WORDS: DetailWords = { attempt: '(attempt {n})', feedback: 'feedback', more: '+{n} more' }
220const slot = (t: string, n: number) => t.replace('{n}', String(n))
221
222export type PaneCtx = { width: number; nowMs: number; tick: number; pos: { k: number; n: number }; owner?: string; words?: DetailWords }
223
224// the keys, as label pairs: `[ ]` only with a second run to go to
225export const footerKeys = (n: number): { key: string; label: string }[] => [
226 ...(n >= 2 ? [{ key: '[ ]', label: 'switch run' }] : []),
227 { key: 'q', label: 'close' },
228]
229// one dim footer, the only place keys are named; the same words and spacing as the live pane's buttons
230// (`[ prev next ]` and `[ q ] close`, as seen in a live session)
231export const paneFooter = (n: number): Line => [seg(n >= 2 ? '[ prev next ] [ q ] close' : '[ q ] close', { dim: true })]
232
233// The header keeps its right part (id8 · state · age · cost · run k of n) whole and cuts the title first. When the
234// title would be left under HEAD_TITLE_MIN cells beside it, the right part moves to a line of its own under the title,
235// and `run k of n` shortens to `k/n` only when even that line is too wide.
236const HEAD_TITLE_MIN = 12
237function headerLines(r: GraphRow, c: PaneCtx): Line[] {
238 const right = (run: string): FitSeg[] => [
239 fs(r.id8, { fixed: true, bold: true }),
240 fs(stateWord(r), { sep: ' · ', fixed: true }),
241 fs(sinceText(createdMs(r), c.nowMs), { sep: ' · ', fixed: true }),
242 fs(costText(r), { sep: ' · ', fixed: true }),
243 fs(run, { sep: ' · ', fixed: true }),
244 ]
245 const full = fit(right(`run ${c.pos.k} of ${c.pos.n}`), 1000)
246 const title: Line = [seg(r.request, { bold: true })]
247 // the teams hand-off sits on a dim line under the header, so a cut title never takes it along
248 const owner: Line[] = c.owner === undefined ? [] : [[seg(`under ${c.owner}`, { dim: true })]]
249 if (lineWidth(full) + 2 + Math.min(lineWidth(title), HEAD_TITLE_MIN) <= c.width) return [leftRight(title, right(`run ${c.pos.k} of ${c.pos.n}`), c.width, HEAD_TITLE_MIN), ...owner]
250 const below = lineWidth(full) <= c.width ? full : fit(right(`${c.pos.k}/${c.pos.n}`), c.width)
251 return [clipLine(title, c.width), [seg(' '.repeat(Math.max(0, c.width - lineWidth(below)))), ...below], ...owner]
252}
253
254function nowLine(r: GraphRow, c: PaneCtx): Line {
255 const run = runningNode(r)
256 const left: Line = [stateGlyph(r, c.tick), seg(' '), seg('Now ', { dim: true }), seg(run === null ? 'idle' : nodeLabel(run), run === null ? { dim: true } : {})]
257 if (run === null) return clipLine(left, c.width)
258 const right = [
259 fs(tryText(run, r.max_retries), { drop: 1 }),
260 fs(run.agent ?? NONE, { sep: ' · ', drop: 3, min: 12 }),
261 fs(run.started_at === null ? NONE : ageText(c.nowMs - run.started_at), { sep: ' · ', fixed: true }),
262 ]
263 return leftRight(left, right, c.width, 14)
264}
265
266function lastLine(r: GraphRow, c: PaneCtx): Line {
267 const from = r.last_step === null ? undefined : r.nodes.filter(n => n.last_step === r.last_step).sort((a, b) => (b.finished_at ?? 0) - (a.finished_at ?? 0))[0]
268 const age = from?.finished_at ?? null
269 const left: Line = [seg(' '), seg('Last ', { dim: true }), seg(r.last_step === null ? NONE : oneLine(r.last_step))]
270 return leftRight(left, [fs(age === null ? NONE : ageText(c.nowMs - age), { dim: true })], c.width, 20)
271}
272
273const waitsLine = (r: GraphRow, c: PaneCtx): Line => {
274 const names = Object.keys(r.unavailable_vendors)
275 return clipLine([seg(GLYPH.you, { tint: 'claude', bold: true }), seg(' waits on you', { bold: true }), ...(names.length > 0 ? [seg(` · unavailable: ${names.join(', ')}`)] : [])], c.width)
276}
277
278const STAGES = ['implement', 'test', 'gate'] as const
279const latest = (nodes: GraphRowNode[]) => nodes.reduce<GraphRowNode | null>((a, n) => (a === null || (n.attempt ?? 0) >= (a.attempt ?? 0) ? n : a), null)
280
281function stageIcon(n: GraphRowNode | null, tick: number): Seg {
282 if (n === null || n.state === 'pending') return seg(GLYPH.todo, { tint: 'inactive' })
283 if (n.state === 'done') return seg(GLYPH.done, { tint: 'success' })
284 if (n.state === 'failed') return seg(GLYPH.fail, { tint: 'error' })
285 if (n.state === 'running') return seg(spinnerFrame(tick, n.stage), { tint: 'claude', bold: true })
286 return seg(GLYPH.idle, { tint: 'inactive' })
287}
288
289// one line per subgoal, each column a segment of its own width, so the columns start at the same cell on every row;
290// a rejected try adds one ↳ line under it
291function subgoalLines(r: GraphRow, c: PaneCtx): Line[] {
292 const per = r.subgoals.map(sg => {
293 const mine = r.nodes.filter(n => n.subgoal_id === sg.id)
294 const impl = latest(mine.filter(n => n.stage === 'implement'))
295 const started = mine.map(n => n.started_at).filter((x): x is number => x !== null)
296 const ended = mine.some(n => n.state === 'running') ? c.nowMs : Math.max(0, ...mine.map(n => n.finished_at ?? 0))
297 return {
298 sg, mine,
299 id: sg.id,
300 title: oneLine(sg.title),
301 icons: STAGES.map(s => stageIcon(latest(mine.filter(n => n.stage === s)), c.tick)),
302 tries: impl === null || impl.state === 'pending' ? '' : tryText(impl, null),
303 agent: impl?.agent ?? NONE,
304 time: started.length === 0 || ended === 0 ? NONE : ageText(ended - Math.min(...started)),
305 }
306 })
307 const col = (f: (p: (typeof per)[number]) => string) => Math.max(0, ...per.map(p => cells(f(p))))
308 const idW = col(p => p.id)
309 const tryW = col(p => p.tries)
310 let agentW = Math.min(24, col(p => p.agent))
311 const timeW = col(p => p.time)
312 const restOf = () => c.width - (idW + 2) - 7 - 2 - (tryW + 2) - (agentW + 2) - timeW
313 // in a narrow pane the agent column gives way before the title falls under 8 cells, so no column's tail is cut
314 if (restOf() < 8) agentW = Math.max(Math.min(agentW, 6), agentW - (8 - restOf()))
315 const titleW = Math.max(4, Math.min(col(p => p.title), restOf()))
316 const out: Line[] = []
317 for (const p of per) {
318 const icons: Seg[] = p.icons.flatMap((s, i) => (i > 0 ? [seg(' '), s] : [s]))
319 out.push(clipLine([
320 seg(pad(p.id, idW + 2), { bold: true }), ...icons, seg(' '),
321 seg(pad(clip(p.title, titleW), titleW + 2)),
322 seg(pad(p.tries, tryW + 2), { dim: true }),
323 seg(pad(clip(p.agent, agentW), agentW + 2), { dim: true }),
324 seg(pad(p.time, timeW), { dim: true }),
325 ], c.width))
326 for (const f of p.mine.filter(n => n.state === 'failed').sort((a, b) => (a.attempt ?? 0) - (b.attempt ?? 0))) {
327 const retry = p.mine.find(n => n.stage === 'implement' && n.attempt === (f.attempt ?? 0) + 1)
328 const why = [oneLine(f.reason), oneLine(retry?.feedback ?? f.feedback)].filter(x => x !== '').join(' — ')
329 out.push(clipLine([seg(' '.repeat(idW + 2)), seg('↳ ', { dim: true }), seg(`try ${f.attempt ?? '?'} rejected`, { tint: 'error' }), seg(why === '' ? '' : `: ${why}`)], c.width))
330 }
331 }
332 return out
333}
334
335// everything but the footer: mod.tsx draws the footer's keys as buttons
336export function paneBody(r: GraphRow, c: PaneCtx): Line[] {
337 const out: Line[] = [...headerLines(r, c), [], nowLine(r, c), lastLine(r, c)]
338 if (r.routing_blocked) out.push(waitsLine(r, c))
339 if (r.subgoals.length > 0) {
340 // gates, not attempts: the latest gate per subgoal (one each, started or not) plus the goal gate when it exists
341 const gateOf = (id: string | null) => latest(r.nodes.filter(n => n.stage === 'gate' && n.subgoal_id === id))
342 const latestGates = [...r.subgoals.map(sg => gateOf(sg.id)), ...(gateOf(null) === null ? [] : [gateOf(null)])]
343 const done = latestGates.filter(n => n?.state === 'done').length
344 out.push([], leftRight([seg('Subgoals', { bold: true })], [fs(`gates ${done}/${latestGates.length}`, { dim: true })], c.width, 8), ...subgoalLines(r, c))
345 }
346 return out.map(l => clipLine(l, c.width))
347}
348
349export const paneLines = (r: GraphRow, c: PaneCtx): Line[] => [...paneBody(r, c), [], clipLine(paneFooter(c.pos.n), c.width)]
350
351const DETAIL_MAX = 24 // node rows drawn before "+n more"
352
353// The Detail tab, everything but the footer: one row per node that ran (skipped ones are no attempt), the name and
354// agent columns aligned; a handed-on feedback and a failure reason sit under their node.
355export function detailLines(r: GraphRow, c: PaneCtx): Line[] {
356 const w = c.words ?? EN_WORDS
357 const nodes = r.nodes.filter(n => n.state !== 'skipped')
358 const shown = nodes.slice(0, DETAIL_MAX).map(n => ({
359 n,
360 name: `${nodeLabel(n)}${n.attempt !== null && n.attempt > 1 ? ` ${slot(w.attempt, n.attempt)}` : ''}`,
361 }))
362 const nameW = Math.max(0, ...shown.map(x => cells(x.name)))
363 const out: Line[] = [...headerLines(r, c), []]
364 for (const { n, name } of shown) {
365 out.push([stageIcon(n, c.tick), seg(' '), seg(pad(name, nameW + 2)), seg(n.agent ?? NONE, { dim: true })])
366 const feedback = oneLine(n.feedback)
367 if (feedback !== '') out.push([seg(' '), seg(`${w.feedback}: ${feedback}`, { dim: true })])
368 const reason = oneLine(n.reason)
369 if (reason !== '') out.push([seg(' '), seg(reason, { tint: 'error' })])
370 }
371 if (nodes.length > DETAIL_MAX) out.push([seg(` ${slot(w.more, nodes.length - DETAIL_MAX)}`, { dim: true })])
372 return out.map(l => clipLine(l, c.width))
373}
374
375/* --- the demo: fixtures rendered to plain text, no live run. Fictional runs only. --- */
376
377export const DEMO_SCENARIOS = ['minimal', 'full', 'parallel', 'narrow'] as const
378export type DemoScenario = (typeof DEMO_SCENARIOS)[number]
379export const DEMO_NOW = Date.parse('2026-10-18T10:00:00Z')
380
381const MIN = 60_000
382const at = (agoMs: number) => DEMO_NOW - agoMs
383const node = (node_id: string, state: string, o: Partial<GraphRowNode> = {}): GraphRowNode => {
384 const [stage = '', sg = null, n = null] = node_id.split(':')
385 return {
386 node_id, stage, subgoal_id: sg === 'goal' ? null : sg, state, attempt: n === null ? 1 : Number(n),
387 agent: null, started_at: null, finished_at: null, reason: null, feedback: null, last_step: null, ...o,
388 }
389}
390const run = (id8: string, request: string, over: Partial<GraphRow> = {}): GraphRow => ({
391 id8, state: 'running', owner: null, created_at: new Date(at(10 * MIN)).toISOString(), cost_usd: null, running: null,
392 run_id: `${id8}-0000-4000-8000-000000000000`, file: `/demo/.harness-run/broker/runs/${id8}.json`, request, max_retries: 3,
393 last_change: new Date(at(MIN)).toISOString(), last_change_ms: at(MIN), age_ms: MIN, open: true, stalled: false,
394 routing_blocked: false, unavailable_vendors: {}, subgoals: [], last_step: null, acting: false, rejects: 0, nodes: [], ...over,
395})
396const CODEX = 'codex·gpt-5'
397const SONNET = 'claude-sonnet-5-5'
398
399export function demoRows(s: DemoScenario): GraphRow[] {
400 const minimal = run('0a1b2c3d', 'Add a health check endpoint', {
401 created_at: new Date(at(4 * MIN)).toISOString(), last_change_ms: at(20_000), age_ms: 20_000, acting: true,
402 running: { node_id: 'implement:U1:1', last_step: null },
403 subgoals: [{ id: 'U1', title: 'Health route' }],
404 nodes: [node('plan', 'done', { agent: SONNET, started_at: at(4 * MIN), finished_at: at(2 * MIN) }),
405 node('implement:U1:1', 'running', { agent: CODEX, started_at: at(90_000) }), node('test:U1:1', 'pending'), node('gate:U1:1', 'pending')],
406 })
407 const full = run('c4e1f2a9', 'Migrate the invoice export to streaming CSV and keep the old endpoint working behind a flag', {
408 created_at: new Date(at(38 * MIN)).toISOString(), cost_usd: 3.4, last_change_ms: at(30_000), age_ms: 30_000, acting: true, rejects: 1,
409 last_step: 'Wrote 14 tests for the streaming writer', running: { node_id: 'implement:U2:2', last_step: 'Wrote 14 tests for the streaming writer' },
410 subgoals: [{ id: 'U1', title: 'Streaming writer' }, { id: 'U2', title: 'Flag the old endpoint' }, { id: 'U3', title: 'Docs and changelog' }],
411 nodes: [
412 node('plan', 'done', { agent: SONNET, started_at: at(38 * MIN), finished_at: at(34 * MIN) }),
413 node('implement:U1:1', 'done', { agent: CODEX, started_at: at(33 * MIN), finished_at: at(24 * MIN) }),
414 node('test:U1:1', 'done', { agent: CODEX, started_at: at(24 * MIN), finished_at: at(2 * MIN), last_step: 'Wrote 14 tests for the streaming writer' }),
415 node('gate:U1:1', 'done', { agent: SONNET, started_at: at(22 * MIN), finished_at: at(20 * MIN) }),
416 node('implement:U2:1', 'done', { agent: CODEX, started_at: at(19 * MIN), finished_at: at(12 * MIN) }),
417 node('test:U2:1', 'done', { agent: CODEX, started_at: at(12 * MIN), finished_at: at(9 * MIN) }),
418 node('gate:U2:1', 'failed', {
419 attempt: 1, agent: SONNET, started_at: at(9 * MIN), finished_at: at(7 * MIN),
420 reason: 'the legacy endpoint still streams when the flag is off, so existing clients receive chunked output they cannot parse',
421 feedback: 'Return the buffered body when the flag is off and add a regression test for the old response headers',
422 }),
423 node('implement:U2:2', 'running', { agent: CODEX, started_at: at(3 * MIN + 12_000), feedback: 'Return the buffered body when the flag is off and add a regression test for the old response headers' }),
424 node('test:U2:2', 'pending'), node('gate:U2:2', 'pending'),
425 node('implement:U3:1', 'pending'), node('test:U3:1', 'pending'), node('gate:U3:1', 'pending'),
426 node('gate:goal:1', 'pending'), node('report', 'pending'),
427 ],
428 })
429 const narrow = run('e7d90b12', '결제 웹훅 재시도 로직을 멱등하게 바꾸고 중복 처리 방지 테스트를 추가한다', {
430 state: 'blocked', created_at: new Date(at(4 * 60 * MIN)).toISOString(), last_change_ms: at(3 * 60 * MIN + 5 * MIN), age_ms: 3 * 60 * MIN + 5 * MIN,
431 stalled: true, routing_blocked: true, unavailable_vendors: { codex: 'quota', gemini: 'offline' }, rejects: 1,
432 last_step: '중복 요청을 막는 키 생성 규칙을 정리했다',
433 subgoals: [{ id: 'U1', title: '멱등 키 생성과 저장소 조회 흐름 정리' }, { id: 'U2', title: '중복 처리 방지 테스트' }],
434 nodes: [
435 node('plan', 'done', { agent: SONNET, started_at: at(4 * 60 * MIN), finished_at: at(235 * MIN) }),
436 node('implement:U1:1', 'done', { agent: CODEX, started_at: at(230 * MIN), finished_at: at(210 * MIN), last_step: '중복 요청을 막는 키 생성 규칙을 정리했다' }),
437 node('test:U1:1', 'done', { agent: CODEX, started_at: at(210 * MIN), finished_at: at(200 * MIN) }),
438 node('gate:U1:1', 'failed', {
439 agent: SONNET, started_at: at(200 * MIN), finished_at: at(190 * MIN),
440 reason: '저장소 조회가 실패하면 같은 키로 두 번 결제가 승인될 수 있어 멱등성이 보장되지 않는다',
441 feedback: '조회 실패 시 재시도하지 말고 요청을 보류 상태로 남기도록 고친다',
442 }),
443 node('implement:U2:1', 'pending'), node('test:U2:1', 'pending'), node('gate:U2:1', 'pending'),
444 ],
445 })
446 if (s === 'minimal') return [minimal]
447 if (s === 'full') return [full]
448 if (s === 'narrow') return [narrow]
449 const second = run('5ee1abcd', 'Rotate the API signing keys', {
450 state: 'blocked', routing_blocked: true, unavailable_vendors: { gemini: 'quota' }, cost_usd: 0.8, created_at: new Date(at(52 * MIN)).toISOString(),
451 last_change_ms: at(6 * MIN), age_ms: 6 * MIN, last_step: 'Listed the keys that expire this month',
452 subgoals: [{ id: 'U1', title: 'Rotate and re-sign' }],
453 nodes: [node('plan', 'done', { agent: SONNET, started_at: at(52 * MIN), finished_at: at(48 * MIN), last_step: 'Listed the keys that expire this month' }), node('implement:U1:1', 'pending')],
454 })
455 const owned = run('b33f00d1', 'Fix the retry loop in the worker', {
456 owner: { task_id: 'demo-task', key: 'E-3f9a21c0/P2' }, acting: true, running: { node_id: 'implement:U1:1', last_step: null },
457 subgoals: [{ id: 'U1', title: 'Retry loop' }], nodes: [node('implement:U1:1', 'running', { agent: CODEX, started_at: at(5 * MIN) })],
458 })
459 return [{ ...minimal, id8: 'f00dbabe', request: 'Add a health check endpoint', run_id: 'f00dbabe-0000-4000-8000-000000000000' }, second, owned]
460}
461
462// The pane and the band for one scenario at one width, as plain text. The owned run of `parallel` is absent from both.
463export function renderDemo(scenario: DemoScenario, w: number): string {
464 const ordered = openingOrder(standalone(demoRows(scenario)), {})
465 const out: string[] = []
466 const pane = (title: string, selected: string | null) => {
467 const r = pickRun(ordered, selected)
468 if (r === null) return
469 const ctx: PaneCtx = { width: w - 4, nowMs: DEMO_NOW, tick: 0, pos: runPosition(ordered, selected) }
470 out.push(`# ${title}`, ...frame('Graph', paneLines(r, ctx), w))
471 }
472 pane(`${scenario} · pane · ${w} columns`, null)
473 if (scenario === 'parallel') pane(`${scenario} · after next · ${w} columns`, cycleRun(ordered, null, 1))
474 out.push(`# ${scenario} · band · ${w} columns`, ...bandLines(ordered, { width: w, nowMs: DEMO_NOW, tick: 0 }).map(plain))
475 return out.join('\n')
476}
477hooks/status.ts 180 lines1/*
2 * What the graph pane shows, as plain functions over the runs the node readout returns: order, selection, keys.
3 * No engine calls here; mod.tsx draws what these return.
4 */
5import type { GraphOwner, GraphRow } from '../types'
6
7export const NONE = '—'
8
9/* --- what the mod reads and shows: the runs of `broker.mjs runs --list/--show --json` --- */
10
11// The one reader of the run files is the node CLI (it works with no mod, compat-claude); the mod runs it.
12export const listArgv = (pluginRoot: string, cwd: string): string[] => ['node', `${pluginRoot}/mcp/broker.mjs`, 'runs', '--list', '--json', '--cwd', cwd]
13export const showArgv = (pluginRoot: string, file: string): string[] => ['node', `${pluginRoot}/mcp/broker.mjs`, 'runs', '--show', file, '--json']
14
15const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
16const str = (v: unknown): string | null => (typeof v === 'string' ? v : null)
17const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null)
18
19function normalizeRow(v: unknown): GraphRow | null {
20 if (!isObj(v) || typeof v.run_id !== 'string' || v.run_id === '' || typeof v.file !== 'string') return null
21 const owner = isObj(v.owner) && typeof v.owner.key === 'string' ? (v.owner as GraphOwner) : null
22 const running = isObj(v.running) && typeof v.running.node_id === 'string' ? { node_id: v.running.node_id, last_step: str(v.running.last_step) } : null
23 const nodes = (Array.isArray(v.nodes) ? v.nodes : []).filter(isObj).map(n => ({
24 node_id: String(n.node_id ?? ''),
25 stage: String(n.stage ?? ''),
26 subgoal_id: str(n.subgoal_id),
27 state: String(n.state ?? ''),
28 attempt: num(n.attempt),
29 agent: str(n.agent),
30 started_at: num(n.started_at),
31 finished_at: num(n.finished_at),
32 reason: str(n.reason),
33 feedback: str(n.feedback),
34 last_step: str(n.last_step),
35 }))
36 const subgoals = (Array.isArray(v.subgoals) ? v.subgoals : []).filter(isObj).map(s => ({ id: String(s.id ?? ''), title: String(s.title ?? '') }))
37 return {
38 id8: str(v.id8) ?? v.run_id.slice(0, 8),
39 state: str(v.state) ?? '',
40 owner,
41 created_at: str(v.created_at) ?? 'unknown',
42 cost_usd: num(v.cost_usd),
43 running,
44 run_id: v.run_id,
45 file: v.file,
46 request: str(v.request) ?? '',
47 max_retries: num(v.max_retries),
48 last_change: str(v.last_change) ?? '',
49 last_change_ms: num(v.last_change_ms) ?? 0,
50 age_ms: num(v.age_ms) ?? 0,
51 open: v.open === true,
52 stalled: v.stalled === true,
53 routing_blocked: v.routing_blocked === true,
54 unavailable_vendors: isObj(v.unavailable_vendors) ? v.unavailable_vendors : {},
55 subgoals,
56 last_step: str(v.last_step),
57 acting: v.acting === true,
58 rejects: num(v.rejects) ?? 0,
59 nodes,
60 }
61}
62
63// The --list --json output. Empty, invalid or not a list is null: the caller keeps its last good list.
64// `[]` is a real answer (no open runs).
65export function parseRows(text: unknown): GraphRow[] | null {
66 if (typeof text !== 'string' || text.trim() === '') return null
67 let v: unknown
68 try {
69 v = JSON.parse(text)
70 } catch {
71 return null
72 }
73 if (!Array.isArray(v)) return null
74 return v.map(normalizeRow).filter((r): r is GraphRow => r !== null)
75}
76
77// The `runs --show <file> --json` output: one row. Anything else is null.
78export function parseRow(text: unknown): GraphRow | null {
79 if (typeof text !== 'string' || text.trim() === '') return null
80 try {
81 return normalizeRow(JSON.parse(text))
82 } catch {
83 return null
84 }
85}
86
87// The runs the band and the [ ] list hold: open, and not opened by a task (an owned run is that task's, never listed here).
88export const standalone = (rows: readonly GraphRow[]): GraphRow[] => rows.filter(r => r.open && r.owner === null)
89
90export const hasNewReject = (r: GraphRow, looked: Record<string, number>) => r.rejects > (looked[r.run_id] ?? 0)
91export const markLooked = (looked: Record<string, number>, r: GraphRow | null): Record<string, number> =>
92 r === null || looked[r.run_id] === r.rejects ? looked : { ...looked, [r.run_id]: r.rejects }
93
94// Waits on you (routing_blocked) first, then a reject since you last looked, then the most recent last change.
95export function openingOrder(rows: readonly GraphRow[], looked: Record<string, number>): GraphRow[] {
96 const rank = (r: GraphRow) => (r.routing_blocked ? 0 : hasNewReject(r, looked) ? 1 : 2)
97 return rows.map((r, i) => ({ r, i })).sort((a, b) => rank(a.r) - rank(b.r) || b.r.last_change_ms - a.r.last_change_ms || a.i - b.i).map(x => x.r)
98}
99
100// openingOrder, kept: `frozen` is the run_id order of the last call. While the rows are the same set, that order stands,
101// so a look or a changed row never moves a run under `[` / `]`; a run that opens or closes orders again.
102export function frozenOrder(rows: readonly GraphRow[], looked: Record<string, number>, frozen: readonly string[] | null): GraphRow[] {
103 const byId = new Map(rows.map(r => [r.run_id, r]))
104 const same = frozen !== null && frozen.length === rows.length && byId.size === rows.length && frozen.every(id => byId.has(id))
105 return same ? frozen.map(id => byId.get(id)!) : openingOrder(rows, looked)
106}
107
108// The run shown: the selected run while it is listed, else the first in opening order.
109export const pickRun = (ordered: readonly GraphRow[], selected: string | null): GraphRow | null =>
110 ordered.find(r => r.run_id === selected) ?? ordered[0] ?? null
111
112export function runPosition(ordered: readonly GraphRow[], selected: string | null): { k: number; n: number } {
113 const at = ordered.findIndex(r => r.run_id === pickRun(ordered, selected)?.run_id)
114 return { k: at < 0 ? 0 : at + 1, n: ordered.length }
115}
116
117// `[` and `]`: the run_id a step lands on, stopping at the first and the last run; with fewer than two runs, nothing changes.
118export function cycleRun(ordered: readonly GraphRow[], selected: string | null, step: 1 | -1): string | null {
119 if (ordered.length < 2) return selected
120 const at = Math.max(0, ordered.findIndex(r => r.run_id === pickRun(ordered, selected)?.run_id))
121 return ordered[Math.min(ordered.length - 1, Math.max(0, at + step))]!.run_id
122}
123
124export type PaneKey = { kind: 'step'; by: 1 | -1 } | { kind: 'tab'; tab: 'flow' | 'detail' } | { kind: 'close' } | null
125const KEY_TABS: Record<string, 'flow' | 'detail'> = { '1': 'flow', '2': 'detail' }
126
127// The last character typed into the pane's Input. Text holding a `/` is a slash command being typed
128// (`/graph-status`, `/help q`): held, no key fires until submit.
129export function paneKey(text: unknown): PaneKey {
130 if (typeof text !== 'string' || text === '' || text.includes('/')) return null
131 const k = [...text].pop()!
132 if (k === ']') return { kind: 'step', by: 1 }
133 if (k === '[') return { kind: 'step', by: -1 }
134 if (k === 'q') return { kind: 'close' }
135 const tab = KEY_TABS[k]
136 return tab === undefined ? null : { kind: 'tab', tab }
137}
138
139// A slash command typed into the pane's Input and submitted. The Input's buffer may start with earlier key presses
140// (`][2q/help`), so the command starts at the first `/`. `/graph-status` closes the pane (the command again toggles);
141// `/name args` runs that command; anything else is dropped.
142export type PaneSlash = { kind: 'close' } | { kind: 'run'; command: string; args: string } | null
143
144export function paneSlash(text: unknown): PaneSlash {
145 if (typeof text !== 'string') return null
146 const at = text.indexOf('/')
147 if (at < 0) return null
148 const m = /^\/([^\s/]+)\s*(.*)$/.exec(text.slice(at).trim())
149 if (m === null) return null
150 return m[1] === 'graph-status' ? { kind: 'close' } : { kind: 'run', command: m[1]!, args: m[2]! }
151}
152
153// The faster interval runs only while a displayed run acts, a pane or band is shown, and a surface exists.
154export const spinnerPlan = (rows: readonly (GraphRow | null)[], surfaces: number, shown: boolean): { run: boolean } => ({
155 run: surfaces > 0 && shown && rows.some(r => r !== null && r.acting && !r.stalled),
156})
157
158// `/graph-status open <run-file> <owner-key>`: null = no argument (the plain toggle); {file, owner} = open that run
159// under that task; {usage} = one line, nothing opens.
160export const OPEN_USAGE = 'usage: /graph-status open <run-file> <owner-key: E-xxxxxxxx or E-xxxxxxxx/Pn>'
161export function parseOpenArg(args: unknown): { file: string; owner: string } | { usage: string } | null {
162 const t = typeof args === 'string' ? args.trim() : ''
163 if (t === '') return null
164 const [verb, file, owner, ...extra] = t.split(/\s+/)
165 if (verb !== 'open' || file === undefined || owner === undefined || extra.length > 0 || !/^E-\w+(\/P\d+)?$/.test(owner)) return { usage: OPEN_USAGE }
166 return { file, owner }
167}
168
169// `$3.40`, or `—` when the run file records no cost
170export const costText = (r: Pick<GraphRow, 'cost_usd'>) => (r.cost_usd !== null ? `$${r.cost_usd.toFixed(2)}` : NONE)
171
172// 45s, 6m, 1h 12m; — when unknown
173export const ageText = (ms: number | null): string => {
174 if (ms === null || !Number.isFinite(ms)) return NONE
175 const s = Math.max(0, Math.round(ms / 1000))
176 if (s < 60) return `${s}s`
177 const m = Math.floor(s / 60)
178 return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${m % 60}m`
179}
180types/index.d.ts 99 lines1// the parts of a broker run file (.harness-run/broker/runs/<runId>.json) the mod reads
2export type GraphNode = {
3 node_id: string
4 stage: string
5 deps: string[]
6 after?: string[]
7 state: string
8 attempt: number
9 subgoal_id?: string | null
10 final?: boolean
11 result?: { stage_ok?: boolean; reason?: string; match_pct?: number } | null
12 vendor?: string | null
13 executor?: string | null
14 model?: string | null
15 feedback?: string | null
16 started_at?: number
17 finished_at?: number
18 last_step?: string | null
19}
20// who opened a run for a task: the EPIC key (S) or the STORY key (L); absent on a standalone run
21export type GraphOwner = { task_id?: string; key: string }
22export type GraphRun = {
23 run_id: string
24 request: string
25 owner?: GraphOwner | null
26 created_at?: number
27 cost_usd?: number | null
28 routing_blocked?: boolean
29 max_retries?: number
30 spec?: { goal?: string; subgoals?: { id: string; title?: string }[] } | null
31 nodes: GraphNode[]
32}
33// what the tick keeps: the newest run, or that its file is too large to read
34export type Snap = { run: GraphRun | null; big: boolean; mtimeMs: number; size: number; live: boolean }
35
36// one node of a `broker.mjs runs --list/--show --json` row (missing values null)
37export type GraphRowNode = {
38 node_id: string
39 stage: string
40 subgoal_id: string | null
41 state: string
42 attempt: number | null
43 agent: string | null
44 started_at: number | null
45 finished_at: number | null
46 reason: string | null
47 feedback: string | null
48 last_step: string | null
49}
50// one run of the readout; created_at keeps the string 'unknown' for a legacy run file
51export type GraphRow = {
52 id8: string
53 state: string
54 owner: GraphOwner | null
55 created_at: string
56 cost_usd: number | null
57 running: { node_id: string; last_step: string | null } | null
58 run_id: string
59 file: string
60 request: string
61 max_retries: number | null
62 last_change: string
63 last_change_ms: number
64 age_ms: number
65 open: boolean
66 stalled: boolean
67 routing_blocked: boolean
68 unavailable_vendors: Record<string, unknown>
69 subgoals: { id: string; title: string }[]
70 last_step: string | null
71 acting: boolean
72 rejects: number
73 nodes: GraphRowNode[]
74}
75// a run opened by `/graph-status open <file> <owner-key>`: not in the band or the [ ] list
76export type OpenedRun = { file: string; owner: string; row: GraphRow | null }
77
78declare module 'claude-code' {
79 interface PluginState {
80 graph: {
81 snap: Snap | null
82 view: 'flow' | 'detail'
83 lang: 'en' | 'ko'
84 // open runs from `runs --list --json`: the last good list, kept when a read fails
85 rows: GraphRow[]
86 // the run the pane shows, by run_id (null: opening order decides)
87 selected: string | null
88 // per run_id, how many rejects the person had seen
89 looked: Record<string, number>
90 // the run opened by path (null: none)
91 opened: OpenedRun | null
92 // spinner frame counter, advanced only while a run acts and a pane or band is shown
93 spin: number
94 // the run outcome this mod publishes for trophy: labels only, never an id (same type in teams and harness)
95 outcome: { system: 'graph' | 'teams' | 'harness'; outcome: 'pass' | 'reject' | 'fail'; at: number } | null
96 }
97 }
98}
99