SLOPSHOPPER

forge

Forge's board and machine views inside Claude Code.

panebandspinnercommandtoastprocess
★ 10v1.2.22MITupdated 2026-10-26knacklabs/symphony-forge/src/forge/mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · forge
│ ┃ Forge ✕ › fix the failing auth test and add an audit log call │ ┃ [ ● Board (b) ] [ Machine (m) ] │ ┃ ⏺ Read(src/auth.ts) │ ┃ Couldn't refresh: Malformed forge next ⎿ Read 6 lines │ ┃ output ⏺ 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 │ │ › /forge │ ⎿ forge: Couldn't refresh: Malformed forge next output │ │ Couldn't refresh: Malformed forge next output ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
Couldn't refresh: Malformed forge next output
Pane · Forge
[ ● Board (b) ] [ Machine (m) ] Couldn't refresh: Malformed forge next output
README

Symphony Forge

Forge takes a change from an idea to a merged pull request. An AI coding agent, Claude Code or Codex, does the work: it plans, writes the code, runs the tests and gets it reviewed. You stay in charge of the decisions: what gets built, which option to pick, and when it goes in.

A pull request is a proposed change to the code that gets checked before it is added. Merging it is the moment the change becomes part of the real project.

Highlights from the explainer; tap to watch it with sound

Where it comes from

In April 2026 OpenAI published *An open-source spec for Codex orchestration: Symphony* (openai/symphony). Its idea: the slow part of building with AI agents was never the agents, it was people watching them. So stop supervising agent sessions one by one and hand them whole pieces of work instead. The spec is a description of the idea, not a tool.

Symphony Forge is that idea made into a working tool. It keeps the core (you assign work, agents do it) and differs in three ways:

Symphony (the spec)Symphony Forge
Who runs itCodex onlyClaude Code or Codex plans with you; Codex workers build
Where the truth livesThe issue trackerThe repo: plans, specs, decisions and each change's state
Checks before a change goes inLeft open on purposeOne approval of the plan, an automatic review and green tests on every change

Who it's for

  • Developers: every change runs in its own branch, and it isn't ready until the tests pass and an automatic code review finds no serious problem. Nothing is committed straight to the main branch.
  • Product people who don't code: you approve a short plan written in plain English, and follow progress on a simple board page instead of in code.
  • Vibe coders who build with AI: you don't need to know git. Forge handles branches, commits and pull requests for your agent, and tells you the next step whenever you're unsure.
  • Salespeople starting a prototype: follow the Start a prototype checklist from an empty repo to a live customer demo.

How it works

After a new client's prototype is signed off, each story follows this loop:

  1. A short story doc. The agent writes one short page: what changes for you, why, when it's done, and the tasks.
  2. One independent read. A second AI agent, not the one that wrote the plan, reads it cold and points out problems. The plan is fixed once.
  3. You approve once. Nothing is built until you say yes.
  4. The work runs on its own. Each task gets its own branch (a separate line of work) and its own folder, so tasks don't get in each other's way. A Codex or Claude worker writes the code.
  5. Tests and review must pass. An automatic code review runs, and the tests must be green. Only then is the pull request marked ready.
  6. It merges. Before client sign-off, the agent merges ready prototype changes. After sign-off, you click merge by default. Set merge = "agent" in the project's forge.toml if you want the agent to run forge merge for each ready change instead.

There are two sizes of change:

  • Story: a bigger change, one that touches an interface or more than five code files. It gets the plan, the independent read and your approval.
  • Fix: a small change. It needs only a one-line reason and a "done when", but still gets its own branch, the tests and the review.

How Forge weighs a note

Two checks read your work before Forge ships it. The cold read reads the plan of a story before you approve it. The code review reads each change before it merges. Both checks use the same three scores and the same bar. Thus Forge judges a plan note and a code review note in the same way.

Three scores

The reader gives each note three scores from 1 to 5. The scores are a judgement. They are not a measurement.

Score135
Gain: how much the fix helpsthe words of a sentence, or a rare case that no one namedone case that the "Done when" names does not worksecurity, data loss, or the main case of a "Done when" does not work
Work: how much the fix costsone line, no new testone file and one test, less than one houra new module, a different platform, or a migration
Harm: what breaks if the problem staysno part breaks, and a revert removes the changea change that people can see, and a revert removes ita change that you cannot reverse: data, a migration, or a release that clients install

A note about security, data loss or a migration always gets Harm 4 or more. Forge sets this floor if the reader gave a lower Harm. Forge shows the reason, for example Harm 4 (floor: security).

The bar

WhenWhat occurs
Harm 4 or 5, or Gain 5The note stops the work. The worker fixes it now.
Gain 4, or Gain 3 with Harm 3, and Work 1 or 2The worker fixes it in this round.
Gain 4, or Gain 3 with Harm 3, and Work 3 or moreThe note becomes a follow-up fix. The work continues.
Other Gain 3 notesThe note becomes a follow-up fix, even at Work 1 or 2. The work continues.
Gain 1 or 2Forge keeps the note in its record and does not fix it.
Harm 3, and the note adds new scope or reverses your decisionThe agent asks you.

A Gain 1 or 2 note never stops the work. This is true also when the reader calls the note serious. Only Harm 4 or more can stop the work for such a note. The Harm 4 or 5 and Gain 5 stop rule comes first. Below that rule, Gain 3 holds work only at Harm 3 with Work 1 or 2.

A note with Case: rare never stops the work, whatever its scores. A note that stops work must name a case in normal use. A security hole or data loss that any user can reach is normal use.

From code review round two, the review checks each earlier finding and raises new findings only for P0s in normal use. A fix that breaks the main path is a P0. At the round limit, open findings below P0 need your choice. Accept puts them in Known issues as follow-ups with your reason.

A worker can decline a finding as "not worth the code" with a reason in a commit message. Forge records it as a follow-up, even if no code changed. A P0 stays open. Review rules and recorded owner decisions settle a question for later readers and reviewers.

Who decides

  • The reader gives the scores. The worker and the agent do not change a score.
  • Forge applies the bar. A plan passes its read, and a change is ready to merge, when no note is at the bar.
  • The agent decides small items. The agent decides each note with Harm 1 or 2 that a revert can remove. Then the agent tells you.
  • You decide the other items. The agent asks you about Harm 3 or more, about new scope outside the approved "Done when", about your approval and merge steps, and about a change to a decision that you made.

Forge keeps each note, and a settled note does not come back

  • Forge keeps each note below the bar. The read notes, the pull request and the record of the item on the default branch show each note with its scores. Thus you can find a known problem when a bug occurs later.
  • A settled note stays settled. You, the agent or Forge can settle a note. Each later read and review gets the settled note as known and accepted. A reader can show the note again only with new evidence of harm.
  • The cold read gives its decisions to the code review. If you accepted a plan note, the code review does not show that note again.

When a loop stops

A fix gets one review round. A story part gets two. At the limit, open findings below P0 stop the change. Forge asks: "One more round, split or accept?" Close, land and work show the same question until you answer.

One more round gives the worker one more attempt. Split moves the open findings to a follow-up fix. Accept puts them in Known issues as follow-ups with your reason. A merge of the default branch or a clean review does not clear an unanswered stop.

An open P0 returns to the worker. A P0 is a security hole, data loss or a broken main path. If the same P0 stays open for two worker rounds in a row, Forge stops with the stuck question. Work waits for your recorded choice of switch, same, narrow or split.

forge land runs at most one fix round, including across session handbacks. If findings, tests or checks still need a worker, land stops. A review stop exits with status 3 and prints the question. Record the choice with forge close <item> --resolve <more|split|accept> --reason "<human's choice>", then run land again.

A cold read stops after round two when notes below P0 are still open, or when P0 notes are open in two rounds in a row. Forge asks: "One more round, split or accept?" Forge waits for your choice and never starts a third round by itself. Record your choice with forge read <KEY or spec or decision> --resolve <accept|more|split> --reason "<human's choice>".

A note from an earlier release of Forge has no scores. Forge judges that note as before, until the next read or review gives new scores.

Three examples

  1. "The default test selection of close breaks Go repos." Gain 3, Work 4, Harm 2. The fix helps, but it needs the tools of a different language. The note becomes a follow-up fix, and the change merges.
  1. "The migration removes a column that contains data." The reader gave Harm 2. Forge sets Harm 4 (floor: migration). The note stops the merge until the worker fixes it.
  1. "This sentence in the plan is not clear." Gain 1, Work 1, Harm 1. Forge keeps the note in the read notes and does not fix it. The plan goes to you for approval.

From idea to production

This is the path for a new client project, from the first conversation to running in production. The agent starts as a forward deployed engineer (FDE): it learns the customer's problem and builds the smallest working prototype that tests it. A salesperson can start this work; a developer can take over using the discovery notes and answers page. To start one, follow the prototype checklist.

StageWhat happensWhoWhere it's kept
1. Find the problemThe agent interviews you (and, through you, the customer) about what really happens today, and writes it as a problem card: the job, today's workaround, what it costs, who feels itAgent asks, you answerdocs/product/DISCOVERY.md
2. Pick an optionTwo to four options, always including "don't build" and "smallest slice", each with an estimate of when it pays backAgent proposes, you chooseforge spec payback
3. Build the prototypeThe agent asks each question when it first affects the build, records the answer and who gave it, confirms specs as they emerge, and builds the smallest working slice through fixesAgent, with you and the customerdocs/product/BRIEF.md, docs/specs/, forge spec save, forge read, forge spec confirm, forge fix start, forge work, forge close
4. Demo and reviewThe customer tries the prototype; a strict review checks the whole prototype and its answers before sign-offClient and agentDemo address, forge decision accept
5. Client sign-offThe customer's named person approves the demo and answers; no client story or roadmap entry can be created before thisClient approves, agent recordsforge decision new client-signoff, forge decision accept
6. Plan the storiesStart from a problem in the plan's Why; the story's branch adds it to the roadmap. Specs stay optional. Build the smallest usable slice first, with no setup-only storiesAgent plans, one story read loop and one approvalforge story new, or forge roadmap add for a confirmed spec
7. BuildEach task runs in its own branch and folder, built by a Codex worker (or Claude, if the project chooses) with its testsAgentforge task start, forge work
8. CheckAn automatic review plus green tests; anything serious goes back to the workerAgentforge close
9. ShipThe pull request is merged, and the change goes out through your project's own deploymentYou merge, or the agent if you allow itGitHub, forge merge
10. Close the loopThe last task's merge records the story's outcome, and on the spec's check date its success measure is measured and recordedAgent, with your numbersforge merge --outcome, forge spec measure

Before sign-off, the prototype uses fixes even when the work is larger than an ordinary fix. Each still goes through tests, review and a pull request. The agent confirms specs during this work, then adds them to the roadmap after sign-off. See decision 0095 for why this order replaces the earlier roadmap-before-sign-off order.

What you do vs what the agent does

You do three things:

  • Approve a story's plan.
  • Choose between options when the agent asks.
  • Merge the finished pull request after client sign-off, unless you let the agent do it (merge = "agent"). The agent merges ready prototype changes before sign-off.

The agent does everything else: the plan, the code, the tests, fixing what the review finds, and keeping Forge's settings file up to date.

Not sure where things stand? Run forge next, or just ask your agent "what's next?". It says where things are in one sentence and gives the exact next step.

Get started

What you need

  • git, which keeps track of changes.
  • GitHub CLI (gh), signed in with gh auth login.
  • uv, a tool that installs Python programs. Get it from docs.astral.sh/uv.
  • Python 3.11 or later. uv can install it for you.
  • Claude Code and Codex. You talk to either one. Forge uses the other one for the independent read.

Install

uv tool install --python 3.11 "git+https://github.com/knacklabs/symphony-forge@v1.2.22"

Check it worked with forge --version. Each project pins the Forge version it uses, and Forge prints the exact install line if yours doesn't match.

Set up a project

  • A new project: create an empty repository on GitHub (no files yet), clone it, and run forge init inside it. It writes Forge's settings, a starter docs folder and the agent instructions, makes the first commit and protects the main branch.
  • A project with an older, copied-in Forge: run forge migrate. It moves you over in one pull request.
  • Every new copy of a project on your machine: run forge sync once, then forge doctor to check your setup. Doctor prints a fix for each problem it finds.

Upgrade a project

Tell your agent "upgrade Forge". It asks which release, recommending the newest, then runs forge upgrade <release> from the main branch with nothing uncommitted. That one command installs the release, has it refresh Forge's files for Claude Code and Codex (your own text and settings stay), and opens the upgrade's pull request, which merges like any other change. If it stops, its Next: line says what to do; running it again picks up where it stopped.

Start working

Open Claude Code or Codex in the project and ask "what's next?", or run forge next yourself. Then describe the change you want.

Contributing

Clone this repository, then run uv sync and uv run pytest to run the tests. The Codex SDK is not needed for the tests. Start fixes with forge fix start "<why>" --done "<done when>" so the pull request uses a Forge branch; the pull-request check accepts only Forge branches.

Forge's own CI balances its test groups using the committed .test_durations file. Refresh it from the repository root after changes to slow tests:

uv run --python 3.11 pytest tests -q -n auto -o faulthandler_timeout=120 --timeout=150 --timeout-method=thread --store-durations --clean-durations

Commit the refreshed file after the full run passes. Check the latest CI run on all three platforms: each group, including setup, must finish within seven minutes on Ubuntu and macOS, and fourteen minutes on Windows (70% of its job limit). These settings affect only Forge's own repository; new and existing client repositories get no change.

Commands you'll see

Your agent runs these for you. You'll see them in its messages.

CommandWhat it does
forge start "<idea>"Chooses a fix, a plan, discovery or the idea list
forge nextSays where things stand and gives the exact next step
forge boardOpens a plain-English page showing the work and its progress
forge story newStarts a new story and its plan
forge readRuns the one independent read of a plan
forge task startStarts one task of an approved story in its own branch and folder
forge fix startStarts a small fix in its own branch and folder
forge workHas the worker build a task or fix, or fix what the review found
forge closeRuns the review, waits for the tests, and marks the pull request ready
forge mergeMerges a ready pull request, when the project allows the agent to merge
forge askAsks Codex a quick read-only question about the code
forge doctorChecks your setup and says how to fix each problem

The full command list is in the Forge guide.

Learn more

  • Forge guide: installing, every command, the two sizes of change, closing, upgrading and releasing.
  • Standards: the engineering rules every worker follows.
  • Specs: the detailed designs behind how Forge behaves, starting with Forge v1.
Source 7 files
hooks/register.ts 44 lines
1import type { CoreEngineInterface, On } from 'claude-code'
2import { createCore } from './forge.ts'
3import { text } from './summary.ts'
4import { addTab, registerPane } from './pane.ts'
5import { registerEvents } from './events.ts'
6import { registerApproval } from './approval.ts'
7import { registerMachine } from './machine.ts'
8
9const REFRESH_INTERVAL_MS = 10000
10const REFRESH_TIMEOUT_MS = 60000
11
12async function refresh($: CoreEngineInterface, core: ReturnType<typeof createCore>) {
13  const cwd = await $.session.cwd()
14  return core.refresh(
15    command => $.process.run(['forge', command, '--json'], { cwd, timeoutMs: REFRESH_TIMEOUT_MS }),
16    () => $.clock.now(),
17    () => $.ui.invalidate('ui.render'),
18  )
19}
20
21export function register(on: On) {
22  const core = createCore()
23  const { data } = core
24  let loaded = false
25  registerEvents(on, data)
26  on('session.start', async ($, e, next) => {
27    if (!loaded) {
28      loaded = true
29      await $.command.register({ name: 'forge', description: 'Show the Forge board', immediate: true })
30      $.clock.every(REFRESH_INTERVAL_MS, () => { void refresh($, core) })
31    }
32    await refresh($, core)
33    return next(e)
34  })
35  on('command.run', { command: 'forge' }, async $ => {
36    await $.ui.open({ id: 'forge', title: 'Forge', focus: true })
37    const now = await $.clock.now()
38    return { text: [text(data, now), data.machineText?.(now)].filter(Boolean).join('\n') }
39  })
40  registerPane(on, data)
41  registerApproval(on, data)
42  registerMachine(on, data, addTab)
43}
44
hooks/forge.ts 88 lines
1import type { ProcessRunResult } from 'claude-code'
2
3export type Stage = { name: string; status?: string | null; started_at?: string | null; ended_at?: string | null; seconds?: number | null }
4export type Item = {
5  title: string; id?: string; kind?: string; stage?: string | null
6  worker?: { kind: string; model: string | null; started_at: string | null } | null
7  pr?: { number: number | null; checks: string; checked_at?: string | null } | null
8  findings?: { count: number; titles: string[] }
9  round?: number | null; total_seconds?: number | null; stages?: Stage[]
10  children?: Item[]; [key: string]: unknown
11}
12export type Board = { version: string; repo_root: string; items: Item[]; team?: Record<string, unknown> | null }
13export type Next = { version: string; repo_root: string; next: { command: string | null; line: string } }
14export type Data = {
15  board: Board | null; next: Next | null; lanes: Record<string, unknown> | null
16  error: string | null; refreshedAt: number | null
17  onUpdate(fn: () => void): () => void
18  machineText?: (now: number) => string
19}
20
21export const TOO_OLD = "This repo's Forge is too old for the pane: upgrade Forge here."
22const object = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
23const nullable = (v: unknown, kind: string) => v == null || typeof v === kind
24const timestamp = (v: unknown) => v == null || (typeof v === 'string' && Number.isFinite(Date.parse(v)))
25
26function item(v: unknown): v is Item {
27  if (!object(v) || typeof v.title !== 'string' || !nullable(v.stage, 'string')) return false
28  if (v.worker != null && (!object(v.worker) || typeof v.worker.kind !== 'string' || !nullable(v.worker.model, 'string') || !nullable(v.worker.started_at, 'string') || !timestamp(v.worker.started_at))) return false
29  if (v.pr != null && (!object(v.pr) || !nullable(v.pr.number, 'number') || !timestamp(v.pr.checked_at) || !['pass', 'fail', 'running', 'unknown'].includes(String(v.pr.checks)))) return false
30  if (v.findings != null && (!object(v.findings) || typeof v.findings.count !== 'number' || !Array.isArray(v.findings.titles) || !v.findings.titles.every(t => typeof t === 'string'))) return false
31  if (!nullable(v.round, 'number') || !nullable(v.total_seconds, 'number')) return false
32  if (v.stages != null && (!Array.isArray(v.stages) || !v.stages.every(s => object(s) && typeof s.name === 'string' && nullable(s.status, 'string') && timestamp(s.started_at) && timestamp(s.ended_at) && nullable(s.seconds, 'number')))) return false
33  return v.children == null || (Array.isArray(v.children) && v.children.every(item))
34}
35
36function parse(text: string, command: string): Record<string, unknown> {
37  let v: unknown
38  try { v = JSON.parse(text) } catch { throw new Error(`Malformed forge ${command} output`) }
39  if (!object(v)) throw new Error(`Malformed forge ${command} output`)
40  return v
41}
42
43export function createCore() {
44  const listeners = new Set<() => void>()
45  const data: Data = {
46    board: null, next: null, lanes: null, error: null, refreshedAt: null,
47    onUpdate(fn) { listeners.add(fn); return () => { listeners.delete(fn) } },
48  }
49  let running = false
50  // Claude's loader forbids passing $ to imported helpers. register.ts keeps
51  // the literal host calls and supplies only these operations.
52  const refresh = async (run: (command: string) => Promise<ProcessRunResult>, now: () => Promise<number>, invalidate: () => void) => {
53    if (running) return
54    running = true
55    try {
56      const results = await Promise.allSettled(['next', 'lanes'].map(async command => {
57        const result = await run(command)
58        if (result.exitCode !== 0) {
59          const error = result.stderr || result.stdout || `forge ${command} failed`
60          if (command === 'lanes' && /invalid choice: ['"]lanes['"]/.test(error)) return null
61          if (/unrecognized arguments: --json/.test(error)) throw new Error(TOO_OLD)
62          throw new Error(error)
63        }
64        return parse(result.stdout, command)
65      }))
66      const failed = results.find(r => r.status === 'rejected')
67      if (failed?.status === 'rejected') throw failed.reason
68      const [next, lanes] = results.map(r => r.status === 'fulfilled' ? r.value : null)
69      if (!next || typeof next.version !== 'string' || typeof next.repo_root !== 'string' || !Array.isArray(next.items) || !next.items.every(item) || !object(next.next) || typeof next.next.line !== 'string' || !nullable(next.next.command, 'string')) throw new Error('Malformed forge next output')
70      if (lanes && typeof lanes.version !== 'string') throw new Error('Malformed forge lanes output')
71      const refreshedAt = await now()
72      data.board = next as Board
73      data.next = next as Next
74      data.lanes = lanes ?? null
75      data.refreshedAt = refreshedAt
76      data.error = null
77    } catch (error) {
78      data.error = String(error instanceof Error ? error.message : error).split(/\r?\n/)[0] ?? ''
79    } finally {
80      running = false
81      // All reads complete before the snapshot is published.
82      for (const fn of listeners) fn()
83      invalidate()
84    }
85  }
86  return { data, refresh }
87}
88
hooks/summary.ts 265 lines
1import type { Data, Item, Stage } from './forge.ts'
2import { TOO_OLD } from './forge.ts'
3
4// Python's round(): halves go to the even number, as time_records.plain rounds.
5const half = (x: number) => { const r = Math.round(x); return r - x === 0.5 && r % 2 ? r - 1 : r }
6
7// Rounds like time_records.plain, in short units: 2m, never 1m 30s.
8export function seconds(value: number): string {
9  const n = Math.max(0, half(value)), minutes = half(n / 60)
10  return n < 60 ? `${n}s` : minutes < 60 ? `${minutes}m` : minutes < 1440 ? `${Math.floor(minutes / 60)}h${minutes % 60 ? ` ${minutes % 60}m` : ''}` : `${half(n / 86400)}d`
11}
12
13export function elapsed(start: string, now: number): number {
14  return Math.max(0, (now - Date.parse(start)) / 1000)
15}
16
17export function rows(items: Item[]): Item[] {
18  return items.flatMap(i => [i, ...(i.children ?? [])])
19}
20
21export const record = (v: unknown): Record<string, unknown> => v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : {}
22const list = (v: unknown): Record<string, unknown>[] => Array.isArray(v) ? v.map(record) : []
23
24export function stages(i: Item): Stage[] {
25  return ['Build', 'Tests', 'Review', 'CI', 'Merge'].map(name => i.stages?.find(s => s.name === name) ?? { name })
26}
27
28export function duration(value: unknown): string {
29  if (typeof value !== 'number' || !Number.isFinite(value) || half(value) <= 0) return ''
30  const n = half(value)
31  return n < 60 ? `${n}s` : n < 3600 ? `${Math.floor(n / 60)}m${n % 60 ? ` ${n % 60}s` : ''}` : seconds(n)
32}
33
34export function stageText(s: Stage, now: number): string {
35  if (s.status == null) return s.name
36  if (s.status === 'skipped') return `${s.name} –`
37  const symbol = s.status === 'pass' ? '✓' : s.status === 'fail' ? '✗' : s.status === 'running' ? '●' : ''
38  const time = s.status === 'running' ? (s.started_at ? duration(elapsed(s.started_at, now)) : '') : duration(s.seconds)
39  return [s.name, symbol, time].filter(Boolean).join(' ')
40}
41
42export function total(i: Item, now: number): string {
43  if (i.time_breakdown != null) return duration(i.total_seconds)
44  // Build includes the worker's own tests; concurrent stages must not double time.
45  const live = Math.max(0, ...stages(i).filter(s => s.status === 'running' && s.started_at).map(s => elapsed(s.started_at!, now)))
46  return i.total_seconds == null ? '' : duration(i.total_seconds + live)
47}
48
49export function itemStatus(i: Item, now: number, state?: string): string {
50  const stage = stages(i).find(s => s.status === 'running'), w = record(i.worker), a = record(i.activity)
51  const start = stage?.started_at ?? (typeof w.started_at === 'string' ? w.started_at : null)
52  const status = state ?? DOING[stage?.name ?? String(w.kind ?? a.action)] ?? (typeof i.state === 'string' ? upper(i.state) : 'In progress')
53  const worker = [typeof w.tool === 'string' ? upper(w.tool) : '', w.model, w.effort].filter(v => typeof v === 'string' && v && v !== 'unknown').join(' ')
54  return [status, typeof i.round === 'number' && i.round > 0 ? `round ${i.round}` : '', worker, start ? duration(elapsed(start, now)) : ''].filter(Boolean).join(' · ')
55}
56
57export function activeRows(data: Data): Item[] {
58  return rows(data.board?.items ?? []).filter(running)
59}
60
61const running = (i: Item) => !!i.worker || record(i.activity).status === 'running' || stages(i).some(s => s.status === 'running')
62
63export function laneCounts(data: Data) {
64  const agents = record(data.lanes?.agents), tests = record(data.lanes?.tests)
65  const agentsRunning = list(agents.entries).filter(e => e.started_at != null).length
66  const agentsWaiting = list(agents.entries).filter(e => e.started_at === null).length
67  const testsWaiting = list(tests.entries).filter(e => e.started_at === null).length
68  const testsRunning = list(tests.entries).filter(e => e.started_at != null).length
69  const test = list(tests.entries).find(e => e.started_at != null)
70  const testTitle = test && data.board && test.repo_root === data.board.repo_root ? rows(data.board.items).find(i => i.id === test.item)?.title : undefined
71  return { agentsRunning, agentsWaiting, testsRunning, testsWaiting, test, testTitle, size: agents.size ?? '?', testSize: tests.size ?? '?' }
72}
73
74export function itemTime(i: Item, now: number): string {
75  return `${i.title} · ${itemStatus(i, now)}`
76}
77
78// Before a first good refresh: loading, or why that refresh failed.
79export const pending = (data: Data) => data.error ? `Couldn't refresh: ${data.error}` : 'Loading Forge…'
80
81// The command and every drawn surface use the same facts and live clock.
82export function summary(data: Data, now: number, working = false): string[] {
83  if (data.error === TOO_OLD) return [TOO_OLD]
84  const active = activeRows(data)
85  const n = laneCounts(data)
86  const next = !working && data.next?.next.command ? `1: ${data.next.next.command}` : data.next?.next.line ?? pending(data)
87  const step = data.lanes && record(active.find(i => typeof record(i.worker).step === 'string')?.worker).step
88  return [
89    `${data.lanes ? `Agents ${n.agentsRunning}/${n.size} (${n.agentsWaiting} waiting) · Tests ${n.testsRunning}/${n.testSize} (${n.testsWaiting} waiting) · ${n.testTitle ?? n.test?.item ?? 'idle'} · ` : ''}${next}${step ? ` · ${step}` : ''}`,
90    ...active.slice(0, active.length > 2 ? 1 : 2).map(i => itemTime(i, now)),
91    ...(active.length > 2 ? [`+${active.length - 1} more · /forge for all`] : []),
92  ]
93}
94
95const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
96const day = (iso: string) => { const d = new Date(Date.parse(iso)); return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}` }
97const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
98
99// Rounds like time_records.plain, in the pane's short words.
100export function ago(value: number): string {
101  const n = Math.max(0, half(value)), minutes = half(n / 60)
102  return n < 60 ? 'under a minute' : minutes < 60 ? `${minutes} min` : minutes < 1440 ? `${Math.floor(minutes / 60)} h${minutes % 60 ? ` ${minutes % 60} min` : ''}` : plural(half(n / 86400), 'day')
103}
104
105export type Row = { title: string; key?: string; state?: string; next?: string; item: Item }
106export type Group = { name: string; rows: Row[]; more: number }
107export type View = { summary: string | null; sentence: string | null; totals: string[]; groups: Group[]; waiting: Row[] }
108
109const DOING: Record<string, string> = { Build: 'Building', build: 'Building', work: 'Building', worker: 'Building', Tests: 'Tests running', test: 'Tests running', Review: 'Review running', review: 'Review running', CI: 'Checks running', ci: 'Checks running', read: 'Plan read running', Merge: 'Merging' }
110const ASKS: Record<string, string> = { 'review loop': 'The builder is stuck.', merge: 'Ready for you to merge.', conflict: 'Its branch conflicts with the main branch.', 'worker question': 'The builder asked a question.', 'blocked plan': 'The plan read found a problem.' }
111const CHECKS: Record<string, string> = { pass: 'checks green', fail: 'checks failing', running: 'checks running' }
112const LIMIT = 5
113const upper = (w: string) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`
114const LABELS: Record<string, string> = { finished_last_7_days: 'Finished in the last 7 days' }
115
116// The board page's labelled totals, one line per kind, in its own words.
117export function totals(counts: Record<string, unknown>): string[] {
118  return Object.entries(counts).map(([kind, by]) => `${LABELS[kind] ?? upper(kind)} — ${Object.entries(record(by)).map(([name, n]) => `${upper(name)}: ${n}`).join('; ')}`)
119}
120
121// The owner's Board tab: summary, then Needs you, Stuck, Moving, Ready to merge, then waiting.
122// When the board gives its team lists, the groups are exactly those lists in the board's order
123// (Moving and Ready to merge split the board's In progress); an older Forge uses each row's flags.
124export function board(data: Data, now: number): View {
125  const team = record(record(data.board).team), counts = record(team.counts)
126  const facts = Array.isArray(team.needs_you) && Array.isArray(team.blocked) && Array.isArray(team.in_progress)
127  const asked = new Map(list(team.needs_you).map(e => [e.id, e]))
128  const groups: Record<string, Row[]> = { 'NEEDS YOU': [], STUCK: [], MOVING: [], 'READY TO MERGE': [] }
129  const waiting: Row[] = []
130  // Every item's row and the group the row flags put it in, in the order they are walked.
131  const found = new Map<unknown, { row: Row; group: string; top: boolean }>()
132  const walk = (i: Item, key?: string) => {
133    const own = i.kind === 'story' ? i.id : key
134    for (const child of i.children ?? []) walk(child, own)
135    const next = record(i.next), command = typeof next.command === 'string' ? next.command : null
136    // `step` is forge next's Next text even when it is not one runnable command; older Forge lacks it.
137    const step = typeof next.step === 'string' ? next.step : command ?? undefined
138    const approval = i.state === 'waiting for approval' || i.stage === 'waiting for approval'
139    const ask = asked.get(i.id) ?? (facts ? undefined : approval ? { reason: 'approval' } : i.needs_person === true ? { reason: '' } : undefined)
140    const row: Row = { title: i.title, key: own, item: i, next: step }
141    const put = (group: string) => found.set(i.id, { row, group, top: key === undefined })
142    if (i.state === 'done' || i.stage === 'done') return
143    if (ask) {
144      const problems = i.findings?.count ? `Review found ${plural(i.findings.count, 'problem')}. ` : ''
145      const reason = String(ask.reason ?? '')
146      row.state = problems + (reason === 'approval' ? 'The plan is ready for your approval.' : ASKS[reason] ?? (reason ? `${upper(reason)}.` : problems ? 'The builder is stuck.' : 'The builder is waiting for your answer.')).trim()
147      row.next = step && (step.startsWith('forge ') ? `decide: ${step}` : step)
148      put('NEEDS YOU')
149    } else if (i.children?.length) {
150      row.state = typeof i.state === 'string' ? upper(i.state) : undefined
151      put('story') // its parts show the work when the board has no team lists
152    } else if (i.stalled === true) {
153      const stage = typeof i.stage === 'string' ? upper(i.stage) : ''
154      row.state = [stage, i.idle_since ? `last activity ${day(String(i.idle_since))}` : ''].filter(Boolean).join(' · ')
155      put('STUCK')
156    } else if (record(i.activity).status !== 'queued' && running(i)) {
157      const stage = stages(i).find(s => s.status === 'running'), w = record(i.worker), a = record(i.activity)
158      row.state = DOING[stage?.name ?? String(w.kind ?? a.action)] ?? 'Running'
159      put('MOVING')
160    } else if (i.state === 'ready to merge' || i.stage === 'ready') {
161      row.state = ['Ready to merge', CHECKS[String(i.pr?.checks)]].filter(Boolean).join(' · ')
162      // With no step (another machine's item, or an older Forge), forge next's own line says who merges.
163      row.next = step ?? (typeof next.line === 'string' ? next.line : 'see forge next')
164      put('READY TO MERGE')
165    } else {
166      const word = record(i.activity).status === 'queued' ? 'waiting in line' : typeof i.state === 'string' ? i.state : i.stage
167      row.state = word ? upper(word) : undefined
168      put('waiting')
169    }
170  }
171  for (const i of data.board?.items ?? []) walk(i)
172  if (facts) {
173    // One row per entry, as the board's page lists them; a part not started yet has no item row.
174    const entry = (e: Record<string, unknown>, state?: string): Row => {
175      const known = found.get(e.id)?.row
176      const key = known?.key ?? (typeof e.id === 'string' && e.id.includes('/') ? e.id.split('/')[0] : undefined)
177      return { title: String(e.title), key, state, next: known?.next, item: known?.item ?? { id: String(e.id), title: String(e.title) } as Item }
178    }
179    // Each wait and block carries the age the page shows, in the pane's short units; unknown stays out.
180    const aged = (state: string | undefined, age: unknown, words = '') => [state, duration(age) ? `${words}${duration(age)}` : ''].filter(Boolean).join(' · ') || undefined
181    for (const e of list(team.needs_you)) {
182      const known = found.get(e.id)
183      const row = known?.group === 'NEEDS YOU' ? { ...known.row } : entry(e, ASKS[String(e.reason)] ?? (e.reason ? `${upper(String(e.reason))}.` : undefined))
184      groups['NEEDS YOU']!.push({ ...row, state: aged(row.state, e.waited_seconds, 'waiting ') })
185    }
186    for (const e of list(team.blocked)) groups.STUCK!.push(entry(e, aged(typeof e.detail === 'string' ? e.detail : undefined, e.seconds)))
187    for (const e of list(team.in_progress)) {
188      const known = found.get(e.id)
189      groups[e.state === 'ready to merge' ? 'READY TO MERGE' : 'MOVING']!.push(known?.row ?? entry(e, typeof e.state === 'string' ? upper(e.state) : undefined))
190    }
191    const listed = new Set([...list(team.needs_you), ...list(team.blocked), ...list(team.in_progress)].map(e => e.id))
192    for (const [id, f] of found) if (f.top && !listed.has(id) && f.group !== 'NEEDS YOU') waiting.push(f.row)
193  } else {
194    for (const f of found.values()) if (f.group === 'waiting') waiting.push(f.row)
195      else if (f.group !== 'story') groups[f.group]!.push(f.row)
196  }
197  const count = (kind: string) => Number(record(counts[kind])['in progress'] ?? 0)
198  const live = record(team.go_live), when = (v: unknown) => typeof v === 'string' && Number.isFinite(Date.parse(v)) ? day(v) : null
199  const golive = live.status === 'range' && when(live.earliest) && when(live.latest) ? `go-live ${when(live.earliest)} – ${when(live.latest)}` : live.status === 'about' && when(live.earliest) ? `go-live about ${when(live.earliest)}` : ''
200  const summary = data.board && 'team' in data.board ? [
201    team.counts && count('parts') + count('fixes') ? `${count('parts') + count('fixes')} in progress` : '',
202    groups['NEEDS YOU']!.length ? `${groups['NEEDS YOU']!.length} needs you` : '',
203    groups.STUCK!.length ? `${groups.STUCK!.length} stuck` : '',
204    golive,
205  ].filter(Boolean).join(' · ') || [
206    // Nothing in progress, asking or stuck: count the rows the tab shows, in its group words.
207    // With no rows this is empty and the board says Nothing in progress. on its own.
208    groups.MOVING!.length ? `${groups.MOVING!.length} moving` : '',
209    groups['READY TO MERGE']!.length ? `${groups['READY TO MERGE']!.length} ready to merge` : '',
210    waiting.length ? `${waiting.length} waiting` : '',
211  ].filter(Boolean).join(' · ') || null : null
212  const idle = facts ? Math.max(0, ...list(team.blocked).flatMap(e => e.reason === 'stalled' && typeof e.seconds === 'number' ? [e.seconds] : []))
213    : Math.max(0, ...groups.STUCK!.flatMap(r => r.item.idle_since ? [elapsed(String(r.item.idle_since), now)] : []))
214  // The board page's own sentence and labelled totals come with the release that writes the sentence.
215  const sentence = typeof team.sentence === 'string' ? team.sentence : null
216  return {
217    summary, sentence, totals: sentence ? totals(counts) : [],
218    groups: Object.entries(groups).filter(([, rows]) => rows.length).map(([name, rows]) => ({
219      name: name === 'STUCK' && idle >= 86400 ? `STUCK (no progress ${ago(idle)})` : name, rows: rows.slice(0, LIMIT), more: Math.max(0, rows.length - LIMIT),
220    })),
221    waiting,
222  }
223}
224
225// The pane and text command share the same item blocks.
226export function rowLines(r: Row, now: number): string[] {
227  const i = r.item, gates = record(i.gates), pr = record(i.pr)
228  const gate = (name: string) => {
229    const value = record(gates[name]).status
230    return typeof value === 'string' && value && value !== 'unknown' ? value : 'none'
231  }
232  const failures = list(pr.failures).map(f => f.job).filter(v => typeof v === 'string' && v.trim())
233  const ci = gate('ci'), failed = ci === 'red' || pr.checks === 'fail'
234  const ciText = [failed ? `failed${failures.length ? `: ${failures.join(', ')}` : ''}` : ci === 'green' ? 'passed' : ci,
235    typeof pr.number === 'number' ? `(PR #${pr.number})` : ''].filter(Boolean).join(' ')
236  const findings = record(i.findings)
237  const counts = [typeof findings.count === 'number' && findings.count > 0 ? plural(findings.count, 'open finding') : '',
238    typeof findings.dismissed === 'number' && findings.dismissed > 0 ? `${findings.dismissed} dismissed` : ''].filter(Boolean).join(' · ')
239  const time = total(i, now)
240  return [
241    `${r.title}${r.key ? `  ${r.key}` : ''}`, `  ${itemStatus(i, now, r.state)}`, '',
242    `  ${stages(i).map(s => stageText(s, now)).join(' → ')}`, ...(time ? [`  Total ${time}`] : []), '',
243    `  Plan read  ${gate('plan_read')}`, `  Review     ${gate('review')}`, `  CI         ${ciText}`,
244    ...(counts ? [`  ${counts}`] : []), ...(r.next ? ['', `  Next: ${r.next}`] : []),
245  ]
246}
247
248export function teamLines(data: Data, now: number): string[] {
249  const b = board(data, now), blocks: string[][] = []
250  if (b.summary) blocks.push([b.summary])
251  if (b.sentence) blocks.push([b.sentence, ...b.totals])
252  for (const g of b.groups) blocks.push([g.name, ...g.rows.flatMap((r, n) => [...(n ? [''] : []), ...rowLines(r, now).map(l => l ? `  ${l}` : '')]), ...(g.more ? [`  and ${g.more} more · forge board for all`] : [])])
253  if (b.waiting.length) blocks.push([`WAITING OR NOT STARTED (${b.waiting.length}) · forge board for all`])
254  if (data.board && !b.groups.length && !b.waiting.length) blocks.push(['Nothing in progress.'])
255  return blocks.flatMap((block, n) => n ? ['', ...block] : block)
256}
257
258export function text(data: Data, now: number): string {
259  if (data.error === TOO_OLD) return TOO_OLD
260  if (!data.board) return pending(data)
261  const lines = teamLines(data, now)
262  if (data.error) lines.push('', `Couldn't refresh: ${data.error}`)
263  return lines.join('\n')
264}
265
hooks/pane.ts 172 lines
1import type { Elements, On, RenderInput, RenderNode, Timer } from 'claude-code'
2import type { Data, Item, Next } from './forge.ts'
3import { TOO_OLD } from './forge.ts'
4import type { Row } from './summary.ts'
5import { activeRows, board, itemTime, laneCounts, pending, record, rowLines, stageText, stages, summary, total } from './summary.ts'
6
7type Tab = (e: RenderInput<'Pane'>, t: Elements['terminal'] | Elements['desktop'], now: number) => RenderNode
8const tabs = new Map<string, Tab>()
9const actions = new Map<string, ((item: Item, e: RenderInput<'Pane'>) => RenderNode)[]>()
10const MIN_TITLE_COLUMNS = 4
11
12export function addTab(name: string, render: Tab) {
13  tabs.set(name, render)
14}
15
16export function addItemAction(kind: string, render: (item: Item, e: RenderInput<'Pane'>) => RenderNode) {
17  actions.set(kind, [...(actions.get(kind) ?? []), render])
18}
19
20export function registerPane(on: On, data: Data) {
21  let selected = 'Board', showWaiting = false, working = false, cwd = '', repaint: Timer | undefined
22  on('session.start', { isInteractive: true }, async ($, e, next) => {
23    cwd = e.cwd
24    await $.ui.open({ id: 'forge', title: 'Forge' })
25    // Drawing ticks never fetch state; CORE owns the only refresh schedule.
26    repaint?.cancel()
27    repaint = $.clock.every(1000, () => { $.ui.invalidate('ui.render') })
28    return next(e)
29  })
30  on('session.end', (_$, e, next) => {
31    if (e.reason !== 'clear' && e.reason !== 'resume') repaint?.cancel()
32    return next(e)
33  })
34  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
35    if (e.requestId !== 'forge' || (e.surface !== 'terminal' && e.surface !== 'desktop')) return next(e)
36    const t = $.ui.resolve(e)
37    const now = await $.clock.now()
38    const children: RenderNode[] = []
39    if (tabs.size) children.push(t.Box({ flexDirection: 'row', gap: 1, children: ['Board', ...tabs.keys()].map(name => t.Button({ key: `tab-${name}`, hotkey: name === 'Board' ? 'b' : 'm', label: `${selected === name ? '● ' : ''}${name} (${name === 'Board' ? 'b' : 'm'})`, onPress: () => { selected = name; $.ui.invalidate('ui.render') } })) }))
40    const tab = tabs.get(selected)
41    if (tab) children.push(tab(e, t, now))
42    else if (data.error === TOO_OLD) children.push(t.Text({ children: TOO_OLD }))
43    else {
44      if (!data.board) children.push(t.Text({ dimColor: true, children: pending(data) }))
45      else {
46        const view = board(data, now)
47        const draw = (row: Row): RenderNode[] => {
48          const title = [row.title, ...(row.key ? [t.Text({ dimColor: true, children: `  ${row.key}` })] : [])]
49          const lines: RenderNode[] = [
50            t.Text({ wrap: 'wrap', children: title }),
51            ...rowLines(row, now).slice(1).map(line => t.Text({ wrap: 'wrap', children: line || ' ' })),
52            ...(actions.get(row.item.kind ?? '') ?? []).map(render => render(row.item, e)),
53          ]
54          return [t.Box({ flexDirection: 'column', children: lines })]
55        }
56        if (view.summary) children.push(t.Text({ bold: true, wrap: 'wrap', children: view.summary }))
57        if (view.sentence) children.push(t.Box({ flexDirection: 'column', children: [view.sentence, ...view.totals].map(line => t.Text({ wrap: 'wrap', children: line })) }))
58        if (!view.groups.length && !view.waiting.length) children.push(t.Text({ children: 'Nothing in progress.' }))
59        for (const group of view.groups) {
60          const lines: RenderNode[] = [t.Text({ bold: true, children: group.name })]
61          for (const row of group.rows) lines.push(...draw(row))
62          if (group.more) lines.push(t.Text({ dimColor: true, children: `and ${group.more} more · forge board for all` }))
63          children.push(t.Box({ flexDirection: 'column', children: [lines[0]!, t.Box({ flexDirection: 'column', gap: 1, paddingLeft: 2, children: lines.slice(1) })] }))
64        }
65        if (view.waiting.length) {
66          children.push(t.Button({ key: 'waiting', label: `${showWaiting ? 'Hide' : 'Show'} waiting or not started (${view.waiting.length})`, onPress: () => { showWaiting = !showWaiting; $.ui.invalidate('ui.render') } }))
67          if (showWaiting) children.push(t.Box({ flexDirection: 'column', gap: 1, paddingLeft: 2, children: view.waiting.flatMap(draw) }))
68        }
69      }
70    }
71    if (data.board && data.error && data.error !== TOO_OLD) children.push(t.Text({ dimColor: true, children: `Couldn't refresh: ${data.error}` }))
72    return t.Box({ flexDirection: 'column', gap: 1, children })
73  })
74  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
75    working = e.props.isWorking
76    if (e.props.hasSurvey || e.props.maxRows < 1) return next(e)
77    const t = $.ui.resolve(e), now = await $.clock.now()
78    const command = data.error === TOO_OLD || working ? null : data.next?.next.command
79    const narrow = e.props.bodyColumns < 80 || e.props.maxRows === 1
80    let lines = summary(data, now, working)
81    let compact: { title: string, counts: string, timing: string, tail: string } | undefined
82    if (narrow && !data.lanes) lines = lines.slice(0, 1)
83    else if (narrow && data.error !== TOO_OLD) {
84      const n = laneCounts(data), first = activeRows(data)[0]
85      const stage = first && stages(first).find(s => s.status === 'running')
86      const counts = data.lanes ? `${n.agentsRunning + n.testsRunning} running, ${n.agentsWaiting}+${n.testsWaiting} waiting · Tests ${n.testsRunning}/${n.testSize} · ` : ''
87      const step = record(first?.worker).step
88      lines = [`${counts}${command ? `1: ${command}` : data.next?.next.line ?? pending(data)}${typeof step === 'string' ? ` · ${step}` : ''}`]
89      compact = { title: first?.title ?? '', counts, timing: first ? ` · ${stage ? stageText(stage, now) : first.stage ?? 'In progress'}${total(first, now) ? ` (${total(first, now)})` : ''} · ` : '', tail: `${data.next?.next.line ?? pending(data)}${typeof step === 'string' ? ` · ${step}` : ''}` }
90    }
91    if ((e.viewport?.columns ?? e.props.bodyColumns) < 144 && data.error !== TOO_OLD) {
92      lines[0] += ' · /forge for the board'
93      if (compact) compact.tail += ' · /forge for the board'
94    }
95    const children: RenderNode[] = []
96    const firstChildren: RenderNode[] = []
97    const first = lines[0] ?? ''
98    const lanes = laneCounts(data)
99    const counts = !narrow && data.lanes && data.error !== TOO_OLD ? `Agents ${lanes.agentsRunning}/${lanes.size} (${lanes.agentsWaiting} waiting) · Tests ${lanes.testsRunning}/${lanes.testSize} (${lanes.testsWaiting} waiting) · ` : ''
100    const testTitle = `${lanes.testTitle ?? lanes.test?.item ?? 'idle'} · `
101    const titleWidth = Math.min(testTitle.length, Math.max(0, e.props.bodyColumns - counts.length - MIN_TITLE_COLUMNS))
102    const nextWidth = Math.max(0, e.props.bodyColumns - counts.length - titleWidth)
103    let tailColumns = compact?.tail.length ?? 0
104    if (command) {
105      const [prefix, suffix = ''] = first.split(`1: ${command}`)
106      tailColumns = command.length + 3 + suffix.length
107      firstChildren.push(
108        t.Text({ children: prefix ?? '', wrap: 'truncate-end' }),
109        t.Button({ key: 'next-step', hotkey: '1', plain: true, label: counts && command.length + 3 > nextWidth ? `${Array.from(command).slice(0, Math.max(0, nextWidth - 4)).join('')}…` : command, onPress: async () => {
110          if (working) return
111          let updated: Next
112          try {
113            const result = await $.process.run(['forge', 'next', '--json'], { cwd: cwd || data.board?.repo_root, timeoutMs: 20000 })
114            if (result.exitCode !== 0) throw new Error((result.stderr || result.stdout || 'Forge did not answer').split(/\r?\n/)[0])
115            const value: unknown = JSON.parse(result.stdout)
116            const root = record(value), following = record(root.next)
117            if (typeof root.version !== 'string' || typeof root.repo_root !== 'string' || typeof following.line !== 'string' || !(following.command === null || typeof following.command === 'string')) throw new Error('Malformed forge next output')
118            updated = value as Next
119          } catch (error) {
120            $.ui.toast(`Couldn't check the next step: ${error instanceof Error ? error.message : String(error)}`)
121            return
122          }
123          data.next = updated
124          $.ui.invalidate('ui.render')
125          if (updated.next.command !== command || working) return
126          try {
127            // The published declarations lag the documented asUser option.
128            const submission = { text: command, asUser: true }
129            const result = await $.prompt.submit(submission)
130            if (result.drop !== undefined) $.ui.toast(`Couldn't run the next step: ${result.drop || 'Prompt unavailable'}`)
131          } catch (error) {
132            $.ui.toast(`Couldn't run the next step: ${error instanceof Error ? error.message : String(error)}`)
133          }
134        } }),
135        t.Text({ children: suffix, wrap: 'truncate-end' }),
136      )
137    } else firstChildren.push(t.Text({ wrap: 'truncate-end', children: first }))
138    if (compact) {
139      const fixed = compact.counts.length + compact.timing.length
140      const tailWidth = Math.min(tailColumns, Math.max(0, e.props.bodyColumns - fixed - MIN_TITLE_COLUMNS))
141      children.push(t.Box({ flexDirection: 'row', width: e.props.bodyColumns, children: [
142        t.Box({ width: compact.counts.length, flexShrink: 0, children: t.Text({ children: compact.counts }) }),
143        t.Box({ width: Math.max(0, e.props.bodyColumns - fixed - tailWidth), minWidth: 0, children: t.Text({ wrap: 'truncate-end', children: compact.title }) }),
144        t.Box({ width: compact.timing.length, flexShrink: 0, children: t.Text({ children: compact.timing }) }),
145        t.Box({ width: tailWidth, flexShrink: 0, overflow: 'hidden', flexDirection: 'row', children: command ? firstChildren.slice(1) : t.Text({ wrap: 'truncate-end', children: compact.tail }) }),
146      ] }))
147    } else if (counts) {
148      const step = record(activeRows(data).find(i => typeof record(i.worker).step === 'string')?.worker).step
149      const tail = `${data.next?.next.line ?? pending(data)}${step ? ` · ${step}` : ''}${(e.viewport?.columns ?? e.props.bodyColumns) < 144 ? ' · /forge for the board' : ''}`
150      children.push(t.Box({ flexDirection: 'row', width: e.props.bodyColumns, children: [
151        t.Box({ width: counts.length, flexShrink: 0, children: t.Text({ children: counts }) }),
152        t.Box({ width: titleWidth, minWidth: 0, children: t.Text({ wrap: 'truncate-end', children: testTitle }) }),
153        t.Box({ width: nextWidth, flexShrink: 0, overflow: 'hidden', flexDirection: 'row', children: command ? firstChildren.slice(1) : t.Text({ wrap: 'truncate-end', children: tail }) }),
154      ] }))
155    } else children.push(command ? t.Box({ flexDirection: 'row', children: firstChildren }) : firstChildren[0]!)
156    const active = activeRows(data)
157    for (const [n, line] of lines.slice(1, Math.min(3, e.props.maxRows)).entries()) {
158      const item = active.length > 2 && n === 1 ? undefined : active[n]
159      const timing = item ? itemTime(item, now).slice(item.title.length + 3) : undefined
160      let status = timing ?? line
161      // Reserve the timing cells; the native surface truncates only the title.
162      if (timing && status.length >= e.props.bodyColumns) status = status.replaceAll(' ', '')
163      const text = t.Text({ wrap: 'truncate-end', children: status.split('✗').flatMap((part, n) => n ? [t.Text({ color: 'red', children: '✗' }), part] : [part]) })
164      children.push(item && timing ? t.Box({ flexDirection: 'row', width: e.props.bodyColumns, children: [
165        t.Box({ width: Math.max(0, e.props.bodyColumns - status.length), minWidth: 0, children: t.Text({ wrap: 'truncate-end', children: `${item.title} · ` }) }),
166        t.Box({ width: status.length, flexShrink: 0, children: text }),
167      ] }) : text)
168    }
169    return t.Box({ flexDirection: 'column', children })
170  })
171}
172
hooks/events.ts 184 lines
1import type { On } from 'claude-code'
2import type { Data, Item } from './forge.ts'
3
4const KINDS = new Set(['review_findings', 'checks_failed', 'ready_to_merge', 'worker_question', 'run_finished'])
5// shortcut: retain 1,024 absent ids; use a durable cursor if older events can reappear.
6const MAX_SEEN_EVENTS = 1024
7const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value)
8
9type Pending = { item: string; title: string; checksAt?: string | null }
10const itemKey = (item: Item) => item.id ?? item.title
11
12function occurrences(items: Item[]): Map<string, Pending> {
13  const lines = new Map<string, Pending>()
14  for (const item of items) {
15    if (item.stage === 'merged' || item.stage === 'done') continue
16    if (Array.isArray(item.occurrences)) {
17      for (const event of item.occurrences) {
18        if (object(event) && typeof event.id === 'string' && event.id && typeof event.kind === 'string'
19          && KINDS.has(event.kind) && typeof event.title === 'string') {
20          lines.set(event.id, { item: itemKey(item), title: event.title,
21            ...(event.id.startsWith('workflow:') && typeof event.conclusion === 'string' && event.conclusion !== 'SUCCESS'
22              ? { checksAt: item.pr?.checked_at ?? null } : {}) })
23        }
24      }
25    }
26    for (const [id, line] of occurrences(item.children ?? [])) lines.set(id, line)
27  }
28  return lines
29}
30
31export function registerEvents(on: On, data: Data) {
32  let eligibility = Promise.resolve(false)
33  let key: string | null = null
34  let endedSession: string | null = null
35  const pending = new Map<string, Pending>()
36  let drain = async () => {}
37  let unsubscribe = () => {}
38  on('session.start', { isInteractive: true }, async ($, e, next) => {
39    unsubscribe()
40    drain = async () => {}
41    key = null
42    endedSession = null
43    pending.clear()
44    // Turn hooks must share this decision while the reload refresh is pending.
45    eligibility = (async () => await $.env.get('FORGE_WORKER') !== '1'
46      && (await $.session.surfaces()).some(s => s === 'terminal' || s === 'desktop'))()
47    const started = await next(e)
48    if (!await eligibility) return started
49    let running = false
50    let observed = new Set<string>()
51    let heldSaved = false
52    drain = async () => {
53      if (running) return
54      running = true
55      try {
56        const repo = await $.session.repo()
57        const session = await $.session.id()
58        if (session === endedSession) return
59        const currentKey = repo ? JSON.stringify([repo.root, session]) : null
60        const baseline = key !== currentKey || key === null
61        if (baseline) {
62          key = null
63          pending.clear()
64        }
65        if (!repo || data.error || data.board?.repo_root !== repo.root
66          || await $.env.get('FORGE_WORKER') === '1'
67          || !(await $.session.surfaces()).some(s => s === 'terminal' || s === 'desktop')) return
68        const seenKey = JSON.stringify([repo.root, session])
69        const saved = await $.store.get(seenKey)
70        const seen = new Set(Array.isArray(saved) ? saved.filter((id): id is string => typeof id === 'string') : [])
71        const current = occurrences(data.board.items)
72        const heldKey = JSON.stringify([repo.root, session, 'forge-held-checks'])
73        const saveHeld = async () => {
74          const held = [...pending].filter(([, event]) => event.checksAt !== undefined)
75            .map(([id, event]) => [id, event.checksAt])
76          if (held.length) await $.store.set(heldKey, held)
77          else if (heldSaved) await $.store.delete(heldKey)
78          heldSaved = held.length > 0
79        }
80        if (baseline) {
81          const held = await $.store.get(heldKey)
82          heldSaved = Array.isArray(held) && held.length > 0
83          for (const entry of Array.isArray(held) ? held : []) {
84            if (!Array.isArray(entry) || typeof entry[0] !== 'string' || !entry[0].startsWith('workflow:')
85              || !(entry[1] === null || typeof entry[1] === 'string' && Number.isFinite(Date.parse(entry[1])))) continue
86            const event = current.get(entry[0])
87            if (event && !seen.has(entry[0])) pending.set(entry[0], { ...event, checksAt: entry[1] })
88          }
89          for (const id of current.keys()) if (!pending.has(id)) seen.add(id)
90          await $.store.set(seenKey, [...seen].slice(-MAX_SEEN_EVENTS))
91          observed = new Set(current.keys())
92          key = seenKey
93          if (!pending.size) {
94            await saveHeld()
95            return
96          }
97        }
98        for (const [id, line] of current) if (!seen.has(id) && (!observed.has(id) || pending.has(id))) {
99          pending.set(id, { ...line, checksAt: pending.get(id)?.checksAt ?? line.checksAt })
100        }
101        // The current snapshot suppresses visible history even after its saved ids expire.
102        observed = new Set(current.keys())
103        if (!pending.size) return
104        if (await $.store.get(JSON.stringify(['forge-active-turn', session]))) {
105          for (const [id, line] of current) if (pending.has(id)) pending.set(id, line)
106          await saveHeld()
107          return
108        }
109        // The host can change identity while the asynchronous reads finish.
110        if ((await $.session.repo())?.root !== repo.root || await $.session.id() !== session) return
111        // Keep the occurrence, but derive its advice only when the host can accept it.
112        const items = new Map<string, Item>()
113        const collect = (rows: Item[]) => {
114          for (const item of rows) {
115            items.set(itemKey(item), item)
116            collect(item.children ?? [])
117          }
118        }
119        collect(data.board.items)
120        const latest = occurrences(data.board.items)
121        const batch: [string, string][] = []
122        for (const [id, event] of pending) {
123          const item = items.get(event.item)
124          if (!item || item.stage === 'merged' || item.stage === 'done'
125            || id.startsWith('workflow:') && !latest.has(id)) {
126            pending.delete(id)
127            continue
128          }
129          // A cached failure cannot tell us whether its workflow has started again.
130          if (event.checksAt !== undefined && (!event.checksAt || !item.pr?.checked_at
131            || Date.parse(item.pr.checked_at) <= Date.parse(event.checksAt))) continue
132          if (event.checksAt !== undefined) event.checksAt = item.pr?.checked_at ?? null
133          const command = object(item.next) && typeof item.next.command === 'string' ? item.next.command : 'forge next'
134          batch.push([id, `${item.title.replace(/[\r\n]+/g, ' ')}: ${event.title.replace(/[\r\n]+/g, ' ')} Next: ${command}`])
135        }
136        await saveHeld()
137        if (!batch.length) return
138        const result = await $.prompt.submit({ text: batch.map(([, line]) => line).join('\n') })
139        if (result.drop !== undefined || session === endedSession) return
140        for (const [id] of batch) seen.add(id)
141        await $.store.set(seenKey, [...seen].slice(-MAX_SEEN_EVENTS))
142        for (const [id] of batch) pending.delete(id)
143        await saveHeld()
144      } catch {
145        // A failed host call leaves occurrences unseen for the next refresh.
146      } finally {
147        running = false
148      }
149    }
150    unsubscribe = data.onUpdate(() => { void drain() })
151    await drain()
152    return started
153  })
154  on('session.end', {}, async ($, e, next) => {
155    endedSession = e.sessionId
156    key = null
157    pending.clear()
158    if (await eligibility) {
159      // Held-check bookmarks use three-part keys so a resumed session can finish delivery.
160      for (const savedKey of await $.store.keys()) {
161        let parts: unknown
162        try { parts = JSON.parse(savedKey) } catch { continue }
163        if (Array.isArray(parts) && parts.length === 2 && parts[1] === e.sessionId) {
164          await $.store.delete(savedKey)
165        }
166      }
167    }
168    return next(e)
169  })
170  on('turn.start', async ($, e, next) => {
171    if (await eligibility) await $.store.set(JSON.stringify(['forge-active-turn', await $.session.id()]), e.turnId)
172    return next(e)
173  })
174  on('turn.complete', async ($, e, next) => {
175    const result = await next(e)
176    if (!e.agentId && await eligibility) {
177      const activeKey = JSON.stringify(['forge-active-turn', await $.session.id()])
178      if (await $.store.get(activeKey) === e.turnId) await $.store.set(activeKey, null)
179      await drain()
180    }
181    return result
182  })
183}
184
hooks/approval.ts 7 lines
1import type { On } from 'claude-code'
2import type { Data } from './forge.ts'
3
4// Claude strips caller-supplied ExitPlanMode plan text and reads its session
5// plan file instead. Keep this seam empty: approval stays in Plan Mode.
6export function registerApproval(_on: On, _data: Data) {}
7
hooks/machine.ts 207 lines
1import type { On, RenderNode } from 'claude-code'
2import type { Data, Item } from './forge.ts'
3import type { addTab } from './pane.ts'
4import { elapsed, record, rows, seconds } from './summary.ts'
5
6type Entry = {
7  id: string; repo_root: string; checkout_root: string; repo_name: string; item: string | null; title?: string | null; kind: string
8  model: string | null; effort: string | null; joined_at: string; started_at: string | null
9  output_path: string | null; progress: { done: number | null; total: number | null } | null
10  place: number; elapsed: number
11}
12type Lanes = { agents: { size: number; entries: Entry[] }; tests: { size: number; entries: Entry[] }; machine: { load: number[] | null; cores: number | null } }
13const entries = (lanes: Lanes) => [...lanes.agents.entries, ...lanes.tests.entries]
14const testLane = (lanes: Lanes) => `Tests ${lanes.tests.entries.filter(run => run.started_at !== null).length}/${lanes.tests.size} (${lanes.tests.entries.filter(run => run.place > 0).length} waiting)`
15const escape = (value: string) => value.replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' })[c]!)
16
17function valid(value: unknown): value is Lanes {
18  const root = record(value), machine = record(root.machine)
19  return (machine.cores === null || (typeof machine.cores === 'number' && machine.cores > 0)) &&
20    (machine.load === null || (Array.isArray(machine.load) && machine.load.length === 3 && machine.load.every(n => typeof n === 'number' && Number.isFinite(n) && n >= 0))) &&
21    ['agents', 'tests'].every(name => {
22      const lane = record(root[name])
23      return typeof lane.size === 'number' && lane.size > 0 && Array.isArray(lane.entries) && lane.entries.every(value => {
24        const e = record(value), p = record(e.progress)
25        return ['id', 'repo_root', 'checkout_root', 'repo_name', 'kind', 'joined_at'].every(k => typeof e[k] === 'string') && Number.isFinite(Date.parse(String(e.joined_at))) &&
26          ['item', 'model', 'effort', 'output_path'].every(k => e[k] === null || typeof e[k] === 'string') &&
27          (e.title == null || typeof e.title === 'string') &&
28          (e.started_at === null || (typeof e.started_at === 'string' && Number.isFinite(Date.parse(e.started_at)))) &&
29          Number.isInteger(e.place) && Number(e.place) >= 0 && typeof e.elapsed === 'number' && Number.isFinite(e.elapsed) && e.elapsed >= 0 &&
30          (e.progress === null || ((p.done === null || (Number.isInteger(p.done) && Number(p.done) >= 0)) &&
31            (p.total === null || (Number.isInteger(p.total) && Number(p.total) >= 0)) &&
32            (p.done === null || p.total === null || Number(p.done) <= Number(p.total))))
33      })
34    })
35}
36function local(data: Data, entry: Entry): Item | undefined {
37  return data.board && path(entry.repo_root) === path(data.board.repo_root) ? rows(data.board.items).find(i => i.id === entry.item) : undefined
38}
39function path(value: string): string {
40  const normal = value.replaceAll('\\', '/').replace(/\/$/, '')
41  return /^[a-z]:/i.test(normal) || normal.startsWith('//') ? normal.toLowerCase() : normal
42}
43function title(data: Data, entry: Entry): string {
44  return local(data, entry)?.title ?? entry.title ?? entry.kind
45}
46function worker(data: Data, entry: Entry): Record<string, unknown> {
47  const current = record(local(data, entry)?.worker)
48  const kind = entry.kind === 'work' || entry.kind === 'worker' ? 'build' : entry.kind
49  return entry.started_at !== null && current.kind === kind ? current : {}
50}
51function color(data: Data, entry: Entry): string {
52  const tool = worker(data, entry).tool
53  return entry.kind === 'test' ? 'yellow' : tool === 'codex' ? 'blue' : tool === 'claude' ? 'green' : 'gray'
54}
55function label(data: Data, entry: Entry, now: number): string {
56  const current = worker(data, entry)
57  const tool = typeof current.tool === 'string' ? current.tool : ''
58  const symbol = entry.kind === 'test' ? '■' : tool === 'codex' ? '◆' : tool === 'claude' ? '●' : '◇'
59  const reported = entry.progress
60  const p = reported?.done != null && reported.total != null ? { done: reported.done, total: reported.total } : null
61  const filled = p && p.total > 0 ? Math.floor(p.done / p.total * 10) : 0
62  const bar = p ? ` [${'█'.repeat(filled)}${'░'.repeat(10 - filled)}] ${p.done}/${p.total}` : ''
63  const model = current.model ?? entry.model, effort = current.effort ?? entry.effort
64  return `${symbol} ${entry.repo_name} · ${title(data, entry)} · ${entry.kind}${tool ? ` · ${tool}` : ''}${model ? ` · ${model}` : ''}${effort ? ` · ${effort}` : ''}${current.round != null ? ` · round ${current.round}` : ''} · ${seconds(elapsed(entry.started_at ?? entry.joined_at, now))}${entry.started_at === null ? entry.place > 0 ? ` · waiting #${entry.place}` : ' · starting' : ''}${bar}${current.step ? ` · ${current.step}` : ''}`
65}
66function gates(data: Data, now: number): string[] {
67  return rows(data.board?.items ?? []).flatMap(item => {
68    if (item.stage === 'done' || item.stage === 'merged') return []
69    const g = record(item.gates)
70    const facts = [['plan_read', 'Plan read'], ['review', 'Review'], ['ci', 'CI']].flatMap(([key, title]) => {
71      const gate = record(g[key!])
72      const live = gate.status === 'running' ? Math.max(0, (now - (data.refreshedAt ?? now)) / 1000) : 0
73      return gate.status && gate.status !== 'none' ? [`${title}: ${gate.status}${gate.count != null ? ` (${gate.count} findings)` : ''}${typeof gate.elapsed === 'number' ? ` · ${seconds(gate.elapsed + live)}` : ''}`] : []
74    })
75    return facts.length ? [`${item.title} · ${facts.join(' · ')}`] : []
76  })
77}
78
79export function registerMachine(on: On, data: Data, add: typeof addTab) {
80  let snapshot: Lanes | null = null, error = '', selected = ''
81  let showLog = false, outputPath: string | null = null, output: string | null = null, status = '', confirming = false
82  const samples: number[] = []
83  let invalidate = () => {}
84  let openOutput: ((run: Entry) => Promise<void>) | undefined, stop: ((run: Entry) => Promise<void>) | undefined
85  data.onUpdate(() => {
86    if (data.error) { error = data.error; return }
87    if (!valid(data.lanes)) { error = data.lanes === null ? 'Upgrade Forge in this repo to use the Machine tab.' : 'Malformed forge lanes output. Run forge lanes to check, then refresh.'; return }
88    snapshot = data.lanes
89    error = ''
90    if (snapshot.machine.load?.[0] != null) {
91      samples.push(snapshot.machine.load[0]); if (samples.length > 30) samples.shift()
92    }
93    if (!entries(snapshot).some(e => e.id === selected)) selected = entries(snapshot)[0]?.id ?? ''
94  })
95  add('Machine', (e, t, now) => {
96    const runs = snapshot ? entries(snapshot) : []
97    const selectedRun = runs.find(run => run.id === selected)
98    const descriptions = runs.map(run => label(data, run, now))
99    const children: RenderNode[] = []
100    if (snapshot) children.push(t.Text({ children: testLane(snapshot) }))
101    const tree: RenderNode[] = []
102    if (e.surface === 'desktop' && 'Svg' in t) {
103      let y = 50
104      const boxes = runs.map((run, n) => {
105        const fill = { yellow: '#92400e', blue: '#1d4ed8', green: '#166534', gray: '#374151' }[color(data, run)]
106        const lines = descriptions[n]!.match(/.{1,90}/gu) ?? [], height = Math.max(44, lines.length * 16 + 16), top = y
107        y += height + 10
108        return `<g><title>${escape(descriptions[n]!)}</title><path d="M20 44 V${top + 20} H40" fill="none" stroke="#6b7280"/><rect x="40" y="${top}" width="710" height="${height}" rx="4" fill="${fill}"/><text x="50" y="${top + 20}" fill="white" font-size="12">${lines.map((line, j) => `<tspan x="50" dy="${j ? 16 : 0}">${escape(line)}</tspan>`).join('')}</text></g>`
109      }).join('')
110      const source = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 ${y + 10}"><rect x="4" y="4" width="750" height="40" rx="4" fill="#374151"/><text x="16" y="30" fill="white" font-size="14">This session · plans + decides</text>${boxes}</svg>`
111      tree.push(t.Svg({ source, alt: ['This session · plans + decides', ...descriptions].join('\n'), isInteractive: true }))
112    } else {
113      tree.push(t.Text({ bold: true, children: 'This session · plans + decides' }))
114      for (const run of runs.filter(run => run.place === 0)) tree.push(t.Text({ color: color(data, run), wrap: 'wrap', children: `${e.props.bodyColumns >= 100 ? '└─ ' : ''}${label(data, run, now)}` }))
115    }
116    if (!runs.length) tree.push(t.Text({ children: snapshot ? 'Nothing running' : 'Loading machine…' }))
117    const gateLines = gates(data, now)
118    children.push(t.Box({ flexDirection: e.props.bodyColumns >= 100 ? 'row' : 'column', gap: 2, children: [
119      t.Box({ flexDirection: 'column', flexGrow: 1, minWidth: 0, children: tree }),
120      ...(gateLines.length ? [t.Box({ flexDirection: 'column', flexGrow: 1, minWidth: 0, children: [t.Text({ bold: true, children: 'Gates' }), ...gateLines.map(line => t.Text({ wrap: 'wrap', children: line }))] })] : []),
121    ] }))
122    for (const name of ['agents', 'tests'] as const) {
123      const waiting = snapshot?.[name].entries.filter(e => e.place > 0) ?? []
124      if (waiting.length) children.push(t.Text({ bold: true, children: `Waiting next · ${name}` }))
125      if (e.surface === 'desktop' && waiting.length) {
126        const cells = waiting.map(run => label(data, run, now).replaceAll('\\', '\\\\').replaceAll('|', '\\|').replace(/[\r\n]/g, ' ').replaceAll('<', '&lt;').replaceAll('>', '&gt;'))
127        children.push(t.Markdown({ text: `| Waiting next |\n| --- |\n${cells.map(cell => `| ${cell} |`).join('\n')}` }))
128      } else for (const run of waiting) children.push(t.Text({ color: color(data, run), wrap: 'wrap', children: label(data, run, now) }))
129    }
130    children.push(t.Text({ children: '◆ Codex (blue) · ● Claude (green) · ◇ Agent (grey) · ■ Tests (amber)' }))
131    const load = snapshot?.machine.load?.[0], cores = snapshot?.machine.cores
132    if (load != null) {
133      children.push(t.Text({ color: cores != null && load > cores ? 'yellow' : undefined, children: `Load ${load} · ${cores ?? 'unknown'} cores` }))
134      if (e.surface === 'terminal' && 'Raster' in t && samples.length) {
135        const max = Math.max(cores ?? 1, ...samples), bytes = new Uint8Array(samples.length * 12), view = new DataView(bytes.buffer)
136        samples.forEach((value, n) => {
137          view.setUint32(n * 12, '▁▂▃▄▅▆▇█'.charCodeAt(Math.min(7, Math.floor(value / max * 7))), true)
138          view.setUint32(n * 12 + 4, cores != null && value > cores ? 0xfbbf24 : 0x93c5fd, true)
139          view.setUint32(n * 12 + 8, 0x01000000, true)
140        })
141        // Claude exposes this standard method; the pinned ES2023 types lag it.
142        const cells = (bytes as Uint8Array & { toBase64(): string }).toBase64()
143        children.push(t.Raster({ key: 'machine-load', columns: samples.length, rows: 1, cells }))
144      }
145    }
146    for (const run of runs) children.push(t.Button({ key: `machine-run-${run.id}`, label: `${run.id === selected ? '› ' : ''}${title(data, run)} · ${run.kind} · ${run.repo_name}`, onPress: () => { selected = run.id; status = ''; invalidate() } }))
147    children.push(t.Box({ flexDirection: 'row', gap: 1, children: [
148      ...(selectedRun ? [t.Button({ key: 'machine-output', hotkey: 'o', label: 'Open output', onPress: () => openOutput?.(selectedRun) }),
149        t.Button({ key: 'machine-stop', hotkey: 's', label: 'Stop run', onPress: () => stop?.(selectedRun) })] : []),
150      t.Button({ key: 'machine-log', hotkey: 'l', label: showLog ? 'Hide events' : 'Show events', onPress: () => { showLog = !showLog; invalidate() } }),
151    ] }))
152    if (showLog) {
153      const events = record(data.board).events
154      for (const value of Array.isArray(events) ? events.slice(-20) : []) {
155        const event = record(value)
156        if (typeof event.time === 'string' && typeof event.line === 'string') children.push(t.Text({ wrap: 'wrap', children: `${event.time} · ${event.line}` }))
157      }
158    }
159    if (status) children.push(t.Text({ wrap: 'wrap', children: status }))
160    if (error) children.push(t.Text({ wrap: 'wrap', children: `Couldn't refresh: ${error}` }))
161    return t.Box({ flexDirection: 'column', gap: 1, children })
162  })
163  on('session.start', { isInteractive: true }, async ($, e, next) => {
164    if (e.surface !== 'terminal' && e.surface !== 'desktop') return next(e)
165    invalidate = () => { $.ui.invalidate('ui.render') }
166    openOutput = async run => {
167      outputPath = run.output_path
168      output = null
169      await $.ui.open({ id: 'forge-output', title: 'Run output', focus: true })
170      $.ui.invalidate('ui.render')
171    }
172    stop = async run => {
173      if (confirming) return
174      confirming = true
175      try {
176        if (await $.ui.ask(`Stop ${run.kind} run for ${title(data, run)} in ${run.repo_name}?`, ['Stop', 'Keep running']) !== 'Stop') return
177        const fresh = await $.process.run(['forge', 'lanes', '--json'], { cwd: e.cwd, timeoutMs: 20000 })
178        if (fresh.exitCode !== 0) throw new Error(fresh.stderr || fresh.stdout || 'Forge did not answer. Refresh and try again.')
179        const lanes: unknown = JSON.parse(fresh.stdout)
180        if (!valid(lanes)) throw new Error('Malformed forge lanes output. Refresh and try again.')
181        if (!entries(lanes).some(entry => entry.id === run.id)) status = 'That run ended or was replaced. Refresh to choose the current run.'
182        else {
183          const result = await $.process.run(['forge', 'stop', '--id', run.id], { cwd: e.cwd, timeoutMs: 20000 })
184          status = result.exitCode === 0 ? result.stdout.trim() : `Could not stop the run: ${result.stderr || result.stdout || 'Refresh and try again.'}`
185        }
186      } catch (error) { status = `Could not stop the run: ${error instanceof Error ? error.message : String(error)}` }
187      finally { confirming = false; $.ui.invalidate('ui.render') }
188    }
189    return next(e)
190  })
191  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
192    if (e.requestId !== 'forge-output') return next(e)
193    if (outputPath) {
194      try { output = (await $.fs.read(outputPath)).replace(/\r?\n$/, '').split(/\r?\n/).slice(-200).join('\n') }
195      catch { output = null }
196    }
197    const t = $.ui.resolve(e)
198    return t.Text({ wrap: 'wrap', children: output ?? 'Output not available. Choose another run or try again after it starts.' })
199  })
200  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
201    const cwd = path(await $.session.cwd())
202    const run = snapshot && entries(snapshot).find(entry => entry.place > 0 && (path(entry.repo_root) === cwd || path(entry.checkout_root) === cwd))
203    return run ? next({ ...e, props: { ...e.props, suffix: `${e.props.suffix} · in line #${run.place} (${run.kind === 'test' ? 'tests' : 'agents'})` } }) : next(e)
204  })
205  data.machineText = (now: number) => snapshot ? ['Machine · this session plans + decides', testLane(snapshot), ...(entries(snapshot).length ? entries(snapshot).map(e => label(data, e, now)) : ['Nothing running']), ...gates(data, now), ...(snapshot.machine.load ? [`Load ${snapshot.machine.load[0]} · ${snapshot.machine.cores ?? 'unknown'} cores`] : []), ...(error ? [`Couldn't refresh: ${error}`] : [])].join('\n') : ''
206}
207