SLOPSHOPPER

orchestra

A conductor agent and musician subagents for Claude Code, with a live ledger of who read and changed what, conflict and stale-read detection, and a coda built…

panebandspinnerrowsguardcommand
v0.2.0MITupdated 2026-10-13krzemienski/orchestra-cc/plugin
A shopper browsing a rack in a slop shop
Preview could not run: the mod kept running for 20s in the preview session (a hold loop or a long wait); no drawing was captured
README

Orchestra

A conductor agent and its musicians, inside Claude Code.

Orchestra is a Claude Code plugin. A conductor agent plans the work as a score, assigns parts to five musician subagents, runs independent parts in parallel, and presents a coda at the end. A Claude Code mod that ships in the same plugin watches the whole performance. It records every file each musician reads and writes into an append-only ledger with SHA-256 versions. It holds a write that would overwrite another musician's newer work and asks you what to do. It draws the ensemble beside your transcript.

MusicianSubagent typeRole
Violinorchestra:violinScout: maps code, writes notes, never edits source
Trumpetorchestra:trumpetImplementer: changes source code
Fluteorchestra:fluteScribe: writes documentation
Timpaniorchestra:timpaniTester: runs tests and commands, saves logs
Celloorchestra:celloReviewer: reports problems, never edits

Orchestra is a picture of how agents relate and nothing more. It makes no sound and no speech, has no voice or narration feature, makes no network call, needs no API key, starts no process, and has no browser or web surface. It draws only in the Claude Code terminal (and the Desktop app's Code tab), and it redraws only when an event arrives. Versions 0.1.4 to 0.1.7 added a narrated and spoken coda and animation; 0.2.0 removed both (see CHANGELOG.md).

The band with ten musicians playing at once, live in Claude Code at 160×48

The guide covers installing, running a performance, every surface Orchestra draws with screenshots, colours and your theme, keys, and troubleshooting. Every screenshot is a capture from a live Claude Code 2.1.296 session; the run that produced it is recorded in docs/verification.md.

What it can reach

The mod runs inside Claude Code's own process with your access to files and settings; mods are not sandboxed. claude plugin validate ./plugin prints the same list from the code.

  • Calls: $.clock (every, now), $.command.register, $.config.list, $.env.get, $.fs (exists, list, read, stat, write), $.session.cwd, $.session.id, and $.ui (ask, close, invalidate, log, open, resolve, status, toast). The one timer re-reads your theme every 2 seconds; it never redraws anything by itself.
  • Reach: reads and writes files in your project. It starts no process and makes no network call.
  • Sees: every prompt, every row added to the conversation, every subagent spawn, every tool call and its result, and the pane, the band above the prompt, the spinner, the question dialog and the Agent rows it draws into.
  • Environment: reads COLORTERM and TERM to choose colours; sets nothing.
  • State: nothing in $.state or $.store; the ledger is kept in files.

Threat model:

  1. Reads: during a performance, the project files the ledger tracks (hashed before and after tool calls); its own ledger under .orchestra/performances/; the theme setting; COLORTERM and TERM.
  2. Runs: nothing. Orchestra has no child process.
  3. Sends: nothing. Orchestra has no network access of its own and adds no account or key.
  4. Persists: in the session's working directory, during a performance: ledger segments .orchestra/performances/<session>.NNNN.jsonl, <session>-coda.md, and .orchestra/.gitignore (*). They stay until you delete them.
  5. Hostile input: a file or tool result only changes the hashes recorded, never anything run. A task notification quoted in a tool result or a pasted prompt is ignored; only one Claude Code itself delivers is acted on. A ledger is replayed only if its name starts with the current session id, and a malformed one is neither used nor overwritten. Text written by the model reaches the conflict dialog only as a part summary cut to 40 characters.

Install

Requires Claude Code 2.1.287 or later, the version that added mods. Tested with 2.1.296. Mods must be allowed on your machine: they are on by default, but managed settings such as allowManagedModsOnly, or --bare and --safe-mode, turn them off.

claude plugin marketplace add krzemienski/orchestra-cc
claude plugin install orchestra@orchestra-cc

To try it without installing, clone this repository and load the plugin directory for one session:

git clone https://github.com/krzemienski/orchestra-cc
claude --plugin-dir ./orchestra-cc/plugin --agent orchestra:conductor

Upgrading from 0.1.x: the five options narrateCoda, voiceCoda, voiceId, voiceLanguage and voiceModel and the /orchestra voice command no longer exist. Settings that name them are ignored.

Use

Start a session with the conductor as the main agent, then describe the work:

claude --agent orchestra:conductor

Installing the plugin does not change your other sessions' main agent. The mod records any session where subagents run, but the conductor only conducts when you start it.

CommandWhat it does
/orchestraOpens the Orchestra pane (tabs: Ensemble, Score, Artifacts, Coda)
/orchestra codaPrints the coda for this session from the ledger
/orchestra ledgerPrints the ledger's path, event count and status
/orchestra closeCloses the pane

Any other argument gets Unknown argument: <arg>. Use coda, ledger or close. and the pane stays shut; /orchestra voice answers orchestra: Unknown argument: voice. Use coda, ledger or close. (step-59), and the plugin has no options at all (P0-21).

What you see

Each surface below was captured live in run e2e-evidence/run-20261013T184754-v020-live (Claude Code 2.1.296, a clean config, ten parts started in one message). The captures are local to the build machine; docs/verification.md quotes them.

  • Ten at once, each by name (P0-12). The same instrument can play several parts; the second is Trumpet 2, the third Trumpet 3. A musician keeps its name on every surface for the whole session, and a replayed ledger gives the same names. The ten-part run showed Trumpet, Trumpet 2, Timpani, Violin, Violin 2, Cello, Trumpet 3, Timpani 2, Flute, Flute 2 with zero Guest and no name cut short (step-27).
  • What each musician is doing now (P0-13). Every row's second line is └ <tool> <target> [from vN] · <elapsed> while it plays, done · N measures · N reads · N writes · <time> when it finishes, and failed · <first error line> when it fails, for example └ failed · Bash ls config/missing.json: Exit code 1: ls: config/miss… (step-20, f0016). In the ten-part run every playing row matched the ledger's open call within one redraw, 213 of 213 rows over 35 frames (step-25).
  • Agent rows (P0-14). Every part has its own Agent row in the transcript, labelled <Name> · <Role> over the same second line, for example Trumpet · Implementer / └ ♪ Bash sleep 45 · 7s, redrawn as the part goes on. Claude Code draws several Agent calls made in one message as one block and keeps a mod's labels out of it, so the conductor starts each part in its own message when parts run in the background (the default in an interactive session); they still play at once. In the ten-part run all ten parts had a labelled row and no grouped block appeared (fix2 run, step-18).
  • The band above the prompt (P0-15). Line 1 is the rollup: 𝄐 Orchestra N playing · N waiting on you · N done · N failed, then ‼ N conflict and ⚠ N stale while any are open; zero counts are left out. Below it, one row per musician not yet done, in the order parts were assigned: glyph, name, tool, target, elapsed. Rows past the room Claude Code gives the band fold into … N more · /orchestra; with a single row, the fold joins line 1: 𝄐 Orchestra 1 playing · 8 done · 1 failed · ⚠ 6 stale · … 2 more · /orchestra (step-43, 100×20). Only the free text is ever cut, with …. When Claude Code gives the band no rows at all (a short terminal while it lists running agents, seen at 100×20), the status line under the prompt carries the rollup and the fold instead: orchestra: Orchestra · 2 playing · … 2 more · /orchestra (fix2 run, step-37: 78 of 78 frames showed one or the other).
  • The pane. It opens by itself on the first part, beside the transcript in a wide terminal, above the prompt in a narrow one. Keys 1–4 switch tabs.
  • Ensemble (P0-16): the rollup, the newest handoff (Violin → Trumpet 2 · config/limits.json v1), then every musician, conductor first, as <glyph> <Name> <Role> · <state> over └ <what it is doing>, with N measures · N reads · N writes and ⚠ stale read while open. Tab to a name and press Enter for its details: the part brief, every version it has seen (config/limits.json v0 (now v1)), its reads and writes with versions, its last calls with times, its answer, and full transcript: ← in Claude Code's agent view (step-34).
  • Score: one staff per musician over the newest ledger events (◆ ○ ● ← · ✓ ✕ ‼ ⚠ ?), with the legend. It is a still picture of the record.
  • Artifacts: every file touched, with its versions; Enter shows each version's author, base version, line delta and SHA-256, who read which version, and its conflicts.
  • Coda: who contributed what, artifacts changed, handoffs, conflicts, failures and stale reads, all from the ledger.
  • Key hints (P0-17): the pane's last row lists the keys of the tab you are on, for example 1-4 tabs · tab select · enter details · ↑↓ scroll · esc close on Ensemble and 1-4 tabs · ↑↓ scroll · esc close on Score (step-32).
  • The outcome line (P0-18). When the conductor's turn ends, one transcript line with the coda's own counts: 𝄐 Coda · 10 musicians · 5 files · 1 conflict · 1 failed · 1m 31s · /orchestra coda (step-22), which matches the coda file's contributors, artifacts, conflicts and failures.
  • Nothing moves by itself (P0-19). Orchestra has no animation and no frame timer. Rows redraw when the ledger records an event from the conductor or a musician, and elapsed times are measured at that event, so they advance only when something happens. With one musician silent in sleep 90 and a conflict question open, every row Orchestra drew was identical across 30 captures taken 2 s apart (step-51). Claude Code's own spinner keeps moving.
  • Colours follow your theme (P0-20). See Colours: a dark, light or 256-colour terminal gets colours measured at 4.5:1 or better against that background; an ANSI theme or an ANSI terminal gets 16-colour codes only. Under a theme Orchestra cannot name (auto, a custom theme), a docked pane is painted the theme's own inverseText instead of Claude Code's grey fill, black under a dark theme and white under a light one, and an inline pane is not painted at all (pane-fill run, step-23: 48;2;0;0;0 under auto).
  • The status line under the prompt carries the same counts: Orchestra · 9 done · 1 failed · 5 artifacts changed · 6 stale.
  • Toasts when a musician joins and rests, for handoffs (Orchestra · handoff: Timpani read .orchestra/notes/map.md v0 from Violin), stale reads, failures, each decided conflict, and when the coda is ready.
  • The spinner names who is playing what: 10 playing: Trumpet Bash sleep 45 · 5s · Trumpet 2 Bash sleep 25 · 5s +8.

Data model

Everything Orchestra shows is folded from one append-only ledger per session in .orchestra/performances/ in your project, written in segments of 500 events (<session-id>.0001.jsonl, …) so a crash can lose at most part of the newest segment. Orchestra also writes .orchestra/.gitignore so none of it is committed by accident.

Only observations are recorded:

EventRecorded when
part.assignedThe conductor's Agent call started a subagent. Carries the subagent's id, type, description and prompt.
tool.call, tool.resultA musician called a tool, and how it ended
artifact.readA musician read a file. Carries the file's SHA-256 at that moment.
write.attemptA write is about to run. Carries the SHA-256 of the file it is about to change.
artifact.writeThe write landed. Carries the new SHA-256 and lines added and removed.
conflict.resolvedYour decision on a conflict
part.done, part.failedThe subagent's turn ended
codaThe coda file was written

Everything else is derived from versions, never declared by the agents:

  • Conflict: a musician tries to write a file whose current version is not the one it last saw. Example: Trumpet read v0, Trumpet 2 wrote v1, and Trumpet now edits from v0. Orchestra holds the write and asks in Claude Code's own question dialog: Let it write, Send it back to re-read, or Show both versions, which draws the lines the other musician added and the held change directly above the question before asking again. Sending it back denies the edit and tells the musician to re-read and reapply its change. In a claude -p run nobody can answer, so the write is sent back.
  • Stale read: a musician produced other work after reading a version that someone has since replaced. It clears when that musician reads the current version. Revising the conductor's plan, .orchestra/score.md, never makes work stale.
  • Handoff: a musician read a version that another musician wrote.
  • Coda: written to .orchestra/performances/<session-id>-coda.md at the end of each conductor turn, from the ledger alone.

Design prototype (history)

prototype/ is the approved Stage 2 design artifact, frozen as it was approved. It is not a product surface, it is not used to verify the plugin, and nothing in plugin/ loads it.

Research

  • docs/orchestra-research-report.md covers Claude Code plugins, mods and modes; prior art; OpenCode, Pi and terminal UX with visual evidence; data-operation patterns; and open questions. Every claim is labelled and linked.
  • docs/orchestra-prototype-design.md gives the design rationale for the prototype.
  • docs/PRD-orchestra.md is the product requirements document (PRD v2) that 0.2.0 implements; docs/plan-0.2.0.md is its build plan.
  • docs/orchestra-prd.md is the original approved build spec, superseded by PRD v2 and kept for its line citations.
  • docs/orchestra-spec.md is the engineering specification: event flow, derivation rules and the verification plan.
  • docs/tui-research.md is the study of omp, OpenCode, Amp and Claude Code that the 0.2.0 interaction design follows.
  • docs/verification.md records how the plugin was verified in a real environment, screen by screen.

Limitations

  • Mod drawing appears only in the Claude Code terminal and the Desktop app's Code tab. In the VS Code extension, claude -p and cloud sessions, the ledger, conflict guard and coda still work, but nothing is drawn.
  • Agent calls in one message. If you tell the conductor to start several parts in one message, Claude Code draws them as one block that a mod cannot label; the band and the Ensemble tab still carry each musician's line.
  • Elapsed times are measured at the newest recorded event, so during a long silent call they hold still until something happens. Claude Code's own agent list shows a live elapsed time.
  • A change a musician makes with Bash (for example sed -i) to a file Orchestra already tracks is credited to that musician, marked "via Bash", and marked uncertain if another musician ran a tool that can change files at the same time, or had a command running in the background. Files created by Bash are not recorded, so the musicians are told to create files with Write and Edit.
  • A command that hides its own exit code (for example npm test; echo $?) is recorded as a success. The tester and conductor are instructed never to append anything to a command, but a model can still ignore that.
  • If one of Orchestra's own hooks fails, Claude Code skips it and the work goes on (fail open). claude plugin validate reports this as gating hook without .catch for session.append, config.set, prompt.submit, agent.spawn and ui.scroll. The exception is a write Orchestra could not check against the other musicians' work in time: the tool.call hook's .catch sends it back to be read again and retried, so it never lands unchecked.
  • Progress is counted in measures (completed tool calls), not as a fraction of a known total, because Claude Code exposes no step plan for a subagent.
  • Hot reload of the mod waits until the current turn ends. After a reload, or after claude --continue, the session's ledger is replayed, so the picture is rebuilt rather than lost.
  • The mods API is new: it was added in 2.1.287, and the events and methods may change between releases. This version was last tested against 2.1.296.
  • Agent teams (split-pane teammates in separate processes) were not tested.

License

MIT

Source 4 files
hooks/register.js 1499 lines
1// Orchestra's hooks module. It records what each agent loop reads and writes into a
2// per-session ledger, guards writes that would overwrite another musician's newer work,
3// and draws the ensemble on the surfaces a mod owns: a pane, the band above the prompt,
4// the status line, toasts, the spinner and the Agent tool rows.
5
6import { CONDUCTOR, instrumentDef, activity, apply, rollup, authorOf, closeLeftOpen, codaMarkdown, elapsed, emptyState, wouldConflict, plural, whoOf, fold, instrumentOf, INSTRUMENTS, isPerformance, lastCall, latest, lineDelta, musicians, nameOf, statusLine } from './ledger.js'
7import { TABS, agentRows, band, heldWrite, outcomeLine, pane, scrollPane } from './views.js'
8import { colorMode, ground, modeFor, paint, setColorMode } from './palette.js'
9
10const PANE = 'orchestra'
11const WRITE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
12const LET_IT_WRITE = 'Let it write'
13const SEND_IT_BACK = 'Send it back to re-read'
14const SHOW_BOTH = 'Show both versions'
15const SEGMENT_EVENTS = 500
16// Files one hook reads at once around a shell command. Reading every tracked file together could
17// run out of file handles in a large project.
18const SNAPSHOT_BATCH = 16
19// Tools whose calls are kept before a performance begins: the Agent call that begins it and the
20// conductor's writes (the score), which are recorded as artifacts anyway.
21const KEPT_EARLY = new Set(['Agent', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
22// Shell tools: their changes are found by hashing tracked files before and after the command.
23// PowerShell is the Windows shell tool.
24const SHELL_TOOLS = new Set(['Bash', 'PowerShell'])
25// Claude Code reads files up to this size; a larger one is versioned by its size and time.
26const READ_LIMIT = 4 * 1024 * 1024
27// Calls that can change a project file, so one running alongside a shell call makes that call's
28// changes uncertain. An MCP tool might write anything. Every other call (the Agent call that
29// waits on a subagent, reads, searches, dialogs, task waits, a Monitor that only watches) does
30// not count.
31const CHANGES_FILES = new Set([...SHELL_TOOLS, ...WRITE_TOOLS])
32const changesFiles = (tool) => CHANGES_FILES.has(tool) || String(tool).startsWith('mcp__')
33// Claude Code refuses more than 12 rows drawn around its question dialog. Every row Orchestra
34// draws there is truncated to one line: 1 status row + 3 headings + 3 lines per side = 10 rows.
35const DIALOG_LINES_PER_SIDE = 3
36
37/** @type {import('./ledger.js').State} */
38let state = emptyState()
39let cwd = ''
40let ledgerBase = ''
41let ledgerDir = ''
42let sessionId = ''
43let codaFile = ''
44let colorterm = ''
45let term = ''
46const THEME_RECHECK_MS = 2000
47const SPINNER_SHOWN = 2
48// A finished tool call gets its own toast only when it ran at least this long.
49const LONG_CALL_MS = 3000
50let seq = 0
51// The highest sequence number already written to a segment file.
52let persisted = 0
53let persisting = Promise.resolve()
54// Bumped whenever the session's paths and state are replaced, so a save queued by the previous
55// session can finish writing its own files without moving this session's `persisted`.
56let epoch = 0
57// Calls that can change a file, running now, per agent loop: a shell change is attributed with
58// certainty only when no other loop had one running. A write tool counts from when Orchestra
59// lets it through, so not while it waits for the file lock or the user's answer to a conflict.
60// The mod sees nothing between Claude Code's own permission prompt and the tool running, so a
61// call waiting on that prompt already counts.
62const inFlight = new Map()
63// Shell calls still running, one mark per call, so a loop's parallel shell calls each keep their
64// own. A call is marked overlapped when another loop runs a call that can change files while it
65// runs, including one that starts and ends entirely in the middle. The mark is read after the
66// command's own snapshots, so it stays until those finish.
67const bashRunning = new Set()
68// Shell commands left running in the background, by task id. Each is one shell command that
69// runs from its call until Claude Code's notification that it finished: it counts as overlap
70// for every other loop until then, so a change another loop's command sees meanwhile is
71// recorded as uncertain. At the end its changes not yet recorded are found against the
72// snapshot taken before it started, and credited to the loop that started it.
73/** @type {Map<string, { loop: string, endsWithAnswer: boolean, known: Record<string, any>|null, mark: { loop: string, overlapped: boolean } }>} */
74const background = new Map()
75// Writes Orchestra has let through and not yet recorded, by path: the loops writing them. A
76// shell command that sees such a file change has seen that write, not its own.
77/** @type {Map<string, Set<string>>} */
78const landing = new Map()
79
80// A loop starts something that can change files: every other loop's running shell call has now
81// overlapped with it.
82function overlapOthers(key) {
83  for (const other of bashRunning) if (other.loop !== key) other.overlapped = true
84}
85function startWriting(key) {
86  inFlight.set(key, (inFlight.get(key) || 0) + 1)
87  overlapOthers(key)
88}
89const stopWriting = (key) => inFlight.set(key, Math.max(0, (inFlight.get(key) || 1) - 1))
90// Whether another loop has a call that can change files running now, or a background command.
91const othersWriting = (key) => [...inFlight.entries()].some(([agent, n]) => agent !== key && n > 0)
92  || [...background.values()].some((b) => b.loop !== key)
93// One write to a file at a time. The guard checks the file's hash and the write lands later,
94// several steps apart, so without this a second musician's write can land in between and be
95// credited to the first. A write that finds the file busy is sent back at once rather than
96// waiting: a hook's waiting time counts against its 10-second budget, and a hook past its budget
97// is skipped, which would let the write land unchecked.
98/** @type {Map<string, symbol>} */
99const busyFiles = new Map()
100// Files whose write is waiting on the user's answer to a conflict question.
101const askingFiles = new Set()
102// Claims a file for one write; only the claim's own release frees it.
103const claimFile = (path) => {
104  if (busyFiles.has(path)) return null
105  const token = Symbol(path)
106  busyFiles.set(path, token)
107  return () => {
108    if (busyFiles.get(path) === token) busyFiles.delete(path)
109  }
110}
111// Background task ids whose notification arrived before their call's result was seen, with the
112// status the notification gave.
113/** @type {Map<string, string>} */
114const endedTasks = new Map()
115// A new session is started at most once at a time: concurrent hooks share it.
116/** @type {Promise<void>|null} */
117let starting = null
118// Musicians woken after their part ended only to hear that their background command finished.
119const wokenByTask = new Set()
120// The loop each already-ended background task belonged to, for a notification that arrives late.
121/** @type {Map<string, string>} */
122const endedTaskLoops = new Map()
123// The tab shown before Orchestra's first open conflict dialog switched it, restored after the last.
124/** @type {{ tab: string, selected: any }|null} */
125let restoreTo = null
126let codaWrites = Promise.resolve()
127/** @type {{ cancel: () => void } | null} */
128let themeTimer = null
129// Musicians the conductor sent more work after their part ended, until that part.resumed is recorded.
130const resumedByMessage = new Set()
131// Write tools let through and still landing: whether another loop's shell command ran meanwhile,
132// in which case the write's line counts may include that command's change.
133/** @type {Set<{ loop: string, overlapped: boolean }>} */
134const writesLanding = new Set()
135// Files found to be over the read limit, so they are not read again while still too large.
136/** @type {Map<string, number>} */
137const tooBig = new Map()
138// Failures already shown to the user in this session, by kind; each is toasted once.
139const warned = new Set()
140// Write tool calls still being checked, by tool_use_id, so a hook that runs out of time can be
141// answered for: a checked file's write is sent back, an untracked one passes.
142/** @type {Map<string, { key: string, target: string, isWrite: boolean, called: boolean }>} */
143const guarding = new Map()
144// The text of the latest version Orchestra saw of each project file, so a change found later can
145// be measured against the version it replaced.
146/** @type {Map<string, { hash: string, text: string }>} */
147const versionText = new Map()
148// The text each loop last read or wrote, in memory only (never in the ledger), so a held write
149// can show what changed since the writer's version.
150const lastText = new Map()
151const textKey = (agent, path) => `${agent}\u0000${path}`
152/**
153 * @typedef {{ tab: string, selected: { type: string, id: string }|null, codaPath: string|null,
154 *   held: { path: string, writer: string, against: string, tool: string, current: number, base: number|null,
155 *     changed: string[]|null, currentText: string|null, proposed: string }|null,
156 *   offset?: number, now: number, setTab: (tab: string) => void, select: (type: string, id: string) => void }} View
157 */
158// `now` is the time of the newest recorded event, so every elapsed time shown is measured at the
159// last event and nothing Orchestra draws changes until the next one arrives.
160/** @type {View} */
161const view = { tab: 'ensemble', selected: null, codaPath: null, held: null, now: 0, setTab: () => {}, select: () => {} }
162
163const segmentOf = (n) => Math.ceil(n / SEGMENT_EVENTS)
164const segmentFile = (n) => `${ledgerBase}.${String(n).padStart(4, '0')}.jsonl`
165
166const short = (text, n) => {
167  const s = String(text ?? '').replace(/\s+/g, ' ').trim()
168  return s.length > n ? `${s.slice(0, n - 1)}…` : s
169}
170
171// Paths are compared with forward slashes, so a Windows path matches the same way.
172const slashes = (p) => String(p).replace(/\\/g, '/')
173const isAbsolute = (p) => p.startsWith('/') || /^[A-Za-z]:[\\/]/.test(p) || p.startsWith('\\\\')
174// On macOS /tmp and /var are links into /private, so the session's folder and a tool's path can
175// name one place two ways. Both are compared without the prefix.
176const unprivate = (p) => (p.startsWith('/private/') ? p.slice('/private'.length) : p)
177// Windows drive letters and folder names ignore case.
178const sameRoot = (p, r) => (/^[A-Za-z]:\//.test(r) ? p.toLowerCase().startsWith(`${r.toLowerCase()}/`) : p.startsWith(`${r}/`))
179// The project's folder as the session names it and where it really lands, so a path through a
180// symbolic link to the project is recognised as inside it. Set at session start.
181/** @type {string[]} */
182let roots = []
183async function rootsOf($, dir) {
184  const real = (await $.fs.stat(dir, { resolve: true }).catch(() => undefined))?.realPath
185  return [...new Set([dir, real].filter(Boolean).map((r) => unprivate(slashes(r).replace(/\/$/, ''))))]
186}
187const relative = (path) => {
188  const p = unprivate(slashes(path || ''))
189  const root = roots.find((r) => sameRoot(p, r))
190  return root ? p.slice(root.length + 1) : slashes(path || '')
191}
192// Where a path really lands: the file if it exists, else its folder plus the name (a new file).
193async function realPathOf($, path) {
194  const own = await $.fs.stat(path, { resolve: true }).catch(() => undefined)
195  if (own?.realPath) return own.realPath
196  const cut = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'))
197  // The folder keeps its trailing separator, so a drive or file-system root stays that root.
198  const dir = await $.fs.stat(cut < 0 ? '.' : path.slice(0, cut + 1), { resolve: true }).catch(() => undefined)
199  return dir?.realPath ? `${slashes(dir.realPath).replace(/\/$/, '')}/${path.slice(cut + 1)}` : undefined
200}
201// A tool's file path as the ledger keys it: relative to the project wherever it really lands,
202// so two spellings of one file (a link, a different letter case where the disk ignores case)
203// are one file. A project file linked to somewhere outside keeps its project path, so it is
204// still guarded. Paths outside the project stay absolute.
205async function projectPath($, path) {
206  const p = String(path || '')
207  if (!isAbsolute(slashes(p))) return slashes(p)
208  const real = await realPathOf($, p)
209  const inside = real ? relative(real) : null
210  return inside && !isAbsolute(inside) ? inside : relative(p)
211}
212
213const loopOf = (e) => e.agentId || CONDUCTOR
214
215async function sha256(text) {
216  const bytes = new TextEncoder().encode(text)
217  const digest = await crypto.subtle.digest('SHA-256', bytes)
218  return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
219}
220
221async function targetOf($, e) {
222  const path = e.file_path || e.notebook_path
223  if (path) {
224    // Resolving the path is bookkeeping: if it fails, the path is used as written.
225    try {
226      return await projectPath($, path)
227    } catch (err) {
228      debug($, `Orchestra could not resolve ${path}: ${err instanceof Error ? err.message : String(err)}`)
229      return relative(path)
230    }
231  }
232  if (SHELL_TOOLS.has(e.tool)) return short(e.command, 80)
233  if (e.tool === 'TaskStop') return String(e.task_id || e.shell_id || '')
234  if (e.tool === 'SendMessage') return short(String(state.musicians[String(e.to)]?.name || e.to || ''), 60)
235  if (e.pattern) return short(e.pattern, 60)
236  if (e.tool === 'Agent') return short(e.description || e.subagent_type, 60)
237  return ''
238}
239
240// A file as it is now. `error` is set when the file exists but could not be read, so a caller
241// can tell a failed read from a missing file.
242async function snapshot($, path) {
243  // A file already found too large is only re-read once its size drops under the limit.
244  if (tooBig.has(path)) {
245    const st = await $.fs.stat(path).catch(() => undefined)
246    if (st && st.size > READ_LIMIT) return { text: null, hash: null, error: true, reason: 'over the read limit', stamp: `stat:${st.size}:${Math.round(st.mtimeMs)}` }
247    tooBig.delete(path)
248  }
249  try {
250    const text = await $.fs.read(path)
251    return { text, hash: await sha256(text), error: false, reason: '' }
252  } catch (err) {
253    const exists = await $.fs.exists(path).catch(() => true)
254    const st = exists ? await $.fs.stat(path).catch(() => undefined) : undefined
255    if (st && st.size > READ_LIMIT) tooBig.set(path, st.size)
256    return { text: null, hash: null, error: exists, reason: exists ? (err instanceof Error ? err.message : String(err)) : '', stamp: exists ? await stampOf($, path) : null }
257  }
258}
259
260// A file Orchestra cannot read (over the 4 MiB read limit, say) still gets a version: its size
261// and modification time stand in for the content hash, so its reads and writes are recorded.
262async function stampOf($, path) {
263  const st = await $.fs.stat(path).catch(() => undefined)
264  return st ? `stat:${st.size}:${Math.round(st.mtimeMs)}` : null
265}
266
267// Snapshots of many files, SNAPSHOT_BATCH at a time. The reads are calls to Claude Code, which do
268// not count against the hook's time budget.
269async function snapshotAll($, paths) {
270  const out = []
271  for (let i = 0; i < paths.length; i += SNAPSHOT_BATCH) out.push(...await Promise.all(paths.slice(i, i + SNAPSHOT_BATCH).map((path) => snapshot($, path))))
272  return out
273}
274
275// Remembers a project file's text at a version Orchestra recorded.
276function rememberText(path, snap) {
277  if (snap?.hash && snap.text !== null && !isAbsolute(path)) versionText.set(path, { hash: snap.hash, text: snap.text })
278}
279
280// The ledger is written in segments of SEGMENT_EVENTS events. Each save rewrites only the
281// segments holding events not yet saved: normally just the newest, and both sides of a segment
282// boundary when one is crossed between saves. A torn write can lose at most one segment.
283// Everything a save writes is captured when it is queued, so it always writes one session's own
284// events to that session's files, even if it runs after the next session has started.
285async function persist($) {
286  if (!isPerformance(state) || !ledgerBase) return
287  const mine = epoch
288  const pending = state.events.filter((x) => x.seq > persisted)
289  if (!pending.length) return persisting
290  const upTo = Math.max(...pending.map((x) => x.seq))
291  const gitignore = `${cwd}/.orchestra/.gitignore`
292  const writes = [...new Set(pending.map((x) => segmentOf(x.seq)))].map((segment) => ({
293    file: segmentFile(segment),
294    body: `${state.events.filter((x) => segmentOf(x.seq) === segment).map((x) => JSON.stringify(x)).join('\n')}\n`,
295  }))
296  persisting = persisting.then(async () => {
297    // The .gitignore only keeps the ledger out of commits; failing to write it must not stop the save.
298    try {
299      if (!(await $.fs.exists(gitignore))) await $.fs.write(gitignore, '*\n')
300    } catch (err) {
301      debug($, `Orchestra could not write ${gitignore}: ${err instanceof Error ? err.message : String(err)}`)
302    }
303    for (const w of writes) await $.fs.write(w.file, w.body)
304    if (epoch === mine) persisted = Math.max(persisted, upTo)
305  }).catch((err) => warn($, 'save', `could not save its ledger (${err instanceof Error ? err.message : String(err)}); events since the last save are only in memory`))
306  return persisting
307}
308
309// A debug-log line that never throws, for use inside error paths.
310// A failure the user should know about: always in the debug log, and the first of each kind in
311// a session also as a toast.
312function warn($, kind, text) {
313  debug($, text)
314  if (warned.has(kind)) return
315  warned.add(kind)
316  try {
317    $.ui.toast(`Orchestra: ${text}`, { timeoutMs: 8000 })
318  } catch {}
319}
320
321function debug($, text) {
322  try {
323    $.ui.log(text, { to: 'debug' })
324  } catch {}
325}
326
327async function loadLedger($, dir, id) {
328  if (!(await $.fs.exists(dir))) return []
329  const names = (await $.fs.list(dir)).map((x) => x.name)
330    .filter((n) => n.startsWith(`${id}.`) && /\.\d{4}\.jsonl$/.test(n)).sort()
331  // Every line must be an event in order; a damaged ledger is not used (and not overwritten).
332  const events = []
333  for (const [n, name] of names.entries()) {
334    const lines = (await $.fs.read(`${dir}/${name}`)).split('\n').filter(Boolean)
335    for (const [i, text] of lines.entries()) {
336      let e
337      try {
338        e = JSON.parse(text)
339      } catch {
340        // The last line of the last file cut short by a process that died while saving: the
341        // event is lost, and the next save writes the file whole again.
342        if (n === names.length - 1 && i === lines.length - 1) {
343          debug($, `Orchestra dropped a line cut short at the end of ${name}`)
344          continue
345        }
346        throw new Error(`line ${i + 1} of ${name} is not JSON`)
347      }
348      const last = events.length ? events[events.length - 1].seq : 0
349      if (!e || typeof e !== 'object' || typeof e.type !== 'string' || !Number.isInteger(e.seq) || e.seq <= last) {
350        throw new Error(`line ${i + 1} of ${name} is not an event in order`)
351      }
352      events.push(e)
353    }
354  }
355  return events
356}
357
358const ledgerPath = () => (ledgerBase ? relative(segmentFile(segmentOf(seq))) : '(not saved: the ledger could not be read)')
359
360// Every observation goes through here: append, fold, persist, then tell the user what changed.
361// The sequence number is assigned only after the clock returns. Assigning it before the await
362// let two hooks hold consecutive numbers while only the later one was applied, and the save
363// then marked the earlier one as already written. Events are now applied and saved in order.
364// `fields` is an event, several events, or a function that builds them synchronously right after
365// the clock (so their checks and the apply happen with no other hook in between); a null entry
366// is dropped. Events built together are applied together. `quiet` skips the toasts: the event is
367// one the user just decided, and its stale reads would push the decision's own toast off the
368// screen. Before a performance, tool calls and results are kept only for KEPT_EARLY tools: only
369// reads and writes matter then, and a long session without one would grow forever.
370// `at` is the epoch the caller started in: a hook that began before a session switch records
371// nothing into the session that replaced it. Most callers use `record`, which takes the epoch now;
372// a function that awaits across several steps binds its own (see the local `record`s).
373async function recordIn(at, $, fields, quiet = false) {
374  if (at !== epoch) return null
375  const ts = await $.clock.now()
376  if (at !== epoch) return null
377  const built = typeof fields === 'function' ? fields() : fields
378  const before = { stale: state.stale.length, handoffs: state.handoffs.length, conflicts: state.conflicts.length, failures: state.toolFailures.length }
379  /** @type {any} */
380  let event = null
381  /** @type {any[]} */
382  const applied = []
383  for (const x of Array.isArray(built) ? built : [built]) {
384    if (!x) continue
385    // Once the session has ended nothing more is recorded into it (a killed command's result
386    // arriving at exit, say), until a resume reopens it.
387    if (state.ended !== null && x.type !== 'session.resumed') continue
388    if (!isPerformance(state) && (x.type === 'tool.call' || x.type === 'tool.result') && !KEPT_EARLY.has(x.tool)) continue
389    const next = { seq: seq + 1, ts, ...x }
390    try {
391      apply(state, next)
392    } catch (err) {
393      debug($, `Orchestra could not record a ${x.type} event: ${err instanceof Error ? err.message : String(err)}`)
394      // The handler may have changed the state before it threw: rebuild it from the events kept,
395      // so what is shown matches what is saved.
396      state = fold(state.events)
397      continue
398    }
399    seq += 1
400    event = next
401    applied.push(next)
402  }
403  if (!event) return null
404  // Once the events are applied they stand. Telling the user about them must not undo a decision
405  // the caller is about to act on, so a failed toast or redraw is only logged.
406  try {
407    if (!quiet) toastNews($, before, applied)
408    // Not awaited: waiting on the save chain would spend this hook's time budget.
409    persist($).catch((err) => debug($, `Orchestra could not queue a save: ${err instanceof Error ? err.message : String(err)}`))
410    // Loops outside the roster (Claude Code's own forks, another plugin's agents) are recorded but
411    // never drawn, so their events neither move the time Orchestra shows nor redraw it.
412    if (applied.some((x) => !x.agent || x.agent === CONDUCTOR || state.musicians[x.agent]?.assigned)) {
413      view.now = ts
414      showStatus($)
415      $.ui.invalidate('ui.render')
416    }
417  } catch (err) {
418    debug($, `Orchestra could not show event ${event.seq}: ${err instanceof Error ? err.message : String(err)}`)
419  }
420  return event
421}
422
423const record = ($, fields, quiet = false) => recordIn(epoch, $, fields, quiet)
424
425// The rows Claude Code last gave the band. With none (a short terminal while it lists running
426// agents), the band cannot show, so the status line under the prompt carries its pointer.
427let bandRows = Infinity
428function showStatus($) {
429  if (!isPerformance(state)) return $.ui.status(undefined)
430  const inBand = musicians(state).filter((m) => m.state !== 'done').length
431  // The rollup's counts and the fold, short enough for a narrow terminal's one line.
432  if (bandRows < 1 && inBand) return $.ui.status(['Orchestra', ...rollup(state).map((x) => x.text), `… ${inBand} more · /orchestra`].join(' · '))
433  $.ui.status(statusLine(state))
434}
435
436// Toasts for what an event changed: stale reads, handoffs and failures.
437function toastNews($, before, applied = []) {
438  // A musician joining when the conductor assigns its part, and resting when the part ends, with
439  // what the ledger recorded for it.
440  for (const e of applied) {
441    const m = e.agent ? state.musicians[e.agent] : null
442    if (!m || m.key === CONDUCTOR) continue
443    if (e.type === 'part.assigned') $.ui.toast(`Orchestra · ${m.name} joins the ensemble as ${m.role}`)
444    else if (e.type === 'part.done') $.ui.toast(`Orchestra · ${m.name} rests: ${plural(m.measures, 'measure')}, ${plural(m.reads, 'read')}, ${plural(m.writes, 'write')}`)
445    else if (e.type === 'part.failed') $.ui.toast(`Orchestra · ${m.name} stopped: ${e.reason}`, { timeoutMs: 6000 })
446    // A finished call long enough to notice: what tool, on what file, for how long. Shorter calls
447    // show in the spinner and the pane, so the toasts stay for news.
448    else if (e.type === 'tool.result' && e.ok && m.assigned) {
449      const done = lastCall(state, m.key)
450      if (done && done.ms >= LONG_CALL_MS) $.ui.toast(`Orchestra · ${m.name} finished ${e.tool}${e.target ? ` ${e.target}` : ''} · ${elapsed(done.ms)}`)
451    }
452  }
453  for (const s of state.stale.slice(before.stale)) {
454    $.ui.toast(`Orchestra · stale read: ${nameOf(state, s.agent)} worked from v${s.readV} of ${s.path}; ${nameOf(state, s.writer)} wrote v${s.currentV}`, { timeoutMs: 6000 })
455  }
456  for (const h of state.handoffs.slice(before.handoffs)) {
457    const how = h.via === 'brief' ? 'was handed' : 'read'
458    $.ui.toast(`Orchestra · handoff: ${nameOf(state, h.to)} ${how} ${h.path} v${h.v} from ${nameOf(state, h.from)}`)
459  }
460  for (const f of state.toolFailures.slice(before.failures).filter((x) => x.agent !== CONDUCTOR && state.musicians[x.agent]?.assigned)) {
461    $.ui.toast(`Orchestra · ${nameOf(state, f.agent)}: ${f.tool} failed`, { timeoutMs: 6000 })
462  }
463}
464
465// Rewritten whenever a part, a background command or the conductor's turn ends, so whoever reads
466// the file mid-turn sees the performance so far. Only the end of the conductor's turn announces it.
467// The text is taken now and the writes are queued in order, so an older coda never lands last;
468// the queue is not awaited, which would spend the hook's time budget.
469async function writeCoda($, announce = false, at = epoch) {
470  if (at !== epoch || !isPerformance(state) || !codaFile) return
471  const settled = musicians(state).every((m) => m.state === 'done' || m.state === 'failed')
472    && Object.values(state.background).every((b) => b.status !== null)
473  const file = codaFile
474  const text = codaMarkdown(state, ledgerPath())
475  const start = state.events.find((x) => x.type === 'part.assigned')
476  const outcome = outcomeLine(state, start ? (state.events.at(-1)?.ts ?? start.ts) - start.ts : 0)
477  // The coda is announced only once its file is written.
478  codaWrites = codaWrites.then(async () => {
479    await $.fs.write(file, text)
480    if (settled && announce) {
481      $.ui.log(outcome)
482      $.ui.toast('Orchestra · coda ready: /orchestra and open the Coda tab', { timeoutMs: 6000 })
483    }
484  }).catch((err) => warn($, 'coda', `could not write the coda to ${relative(file)} (${err instanceof Error ? err.message : String(err)})`))
485  await recordIn(at, $, { type: 'coda', path: relative(file), settled })
486  view.codaPath = relative(file)
487}
488
489// The line of a failed call's output that says what went wrong. A failed shell call's output starts
490// with "Exit code N", so the line after it is added.
491function firstErrorLine(text) {
492  const [first = '', next] = String(text ?? '').split('\n').map((l) => l.trim()).filter(Boolean)
493  return short(/^Exit code \d+$/.test(first) && next ? `${first}: ${next}` : first, 160)
494}
495
496// Lines in `now` that are not in `then`, counted as a multiset.
497function addedLines(then, now) {
498  const left = new Map()
499  for (const l of String(then ?? '').split('\n')) left.set(l, (left.get(l) || 0) + 1)
500  return String(now ?? '').split('\n').filter((l) => {
501    const n = left.get(l) || 0
502    if (n > 0) {
503      left.set(l, n - 1)
504      return false
505    }
506    return l.trim() !== ''
507  })
508}
509
510function proposedText(e) {
511  if (e.tool === 'Write') return e.content
512  // An Edit's old and new text share their context lines: what it adds is what the user decides on.
513  if (e.tool === 'Edit') {
514    const added = addedLines(e.old_string, e.new_string).filter((l) => l.trim())
515    return added.length ? added.map((l) => `+ ${l}`).join('\n') : '(the Edit only removes lines)'
516  }
517  if (e.tool === 'MultiEdit') return (e.edits || []).map((x) => x.new_string).join('\n…\n')
518  if (e.tool === 'NotebookEdit') return e.new_source
519  return ''
520}
521
522// The file a write tool makes of `text`, or undefined when it cannot be worked out here.
523function writeResult(e, text) {
524  const edit = (t, x) => (x.replace_all ? t.split(x.old_string).join(x.new_string) : t.replace(x.old_string, () => x.new_string))
525  if (e.tool === 'Write') return e.content
526  if (e.tool === 'Edit') return edit(text, e)
527  if (e.tool === 'MultiEdit') return (e.edits || []).reduce(edit, text)
528  return undefined
529}
530
531// A write that would land on a version the writer never saw is held here and put to the user.
532// With nobody to ask (a -p run, or the dialog dismissed) it is sent back, the safe choice.
533// A write the musician has never read is also sent back without a question. Claude Code refuses
534// any Write or Edit of a file that loop has not read ("File has not been read yet"), and a mod
535// cannot record the read for it, so "Let it write" would fail every time. Sending it back makes
536// the musician read the file and reapply the change, which is the only path that succeeds.
537// Returns `{ deny }` to send the write back, or `{ base }`: the snapshot the write will replace.
538// `approved` is an earlier conflict on this write that the user let through before the file
539// moved on; it is settled here, once it is known whether the new version needs a question.
540/** @param {import('./ledger.js').Conflict|null} [approved] */
541async function guardWrite($, e, key, path, current, signal, approved = null, at = epoch) {
542  // The file changed after the user let the write go ahead: their answer is recorded as a re-ask
543  // when the new version is one more conflict, together with the new attempt, in one step.
544  const attempt = await recordIn(at, $, () => [
545    approved ? { type: 'conflict.resolved', id: approved.id, choice: wouldConflict(state, key, path, current.hash) ? 'reask' : 'overwrite' } : null,
546    { type: 'write.attempt', agent: key, tool: e.tool, path, hash: current.hash },
547  ])
548  const conflict = attempt ? state.conflicts.find((c) => c.seq === attempt.seq) : undefined
549  if (!conflict) {
550    if (!approved) return { base: current }
551    notify($, `Orchestra · conflict on ${path}: ${whoOf(state, key)} vs ${writerOf(path, approved)}, write allowed`)
552    return { base: current, allowedOver: { who: writerOf(path, approved), v: approved.current } }
553  }
554  const writer = whoOf(state, key)
555  const other = writerOf(path, conflict)
556  const neverRead = conflict.base === null
557  const seenText = neverRead ? `${writer} never read it` : `${writer} saw v${conflict.base}`
558  if (neverRead) {
559    await recordIn(at, $, { type: 'conflict.resolved', id: conflict.id, choice: 'reread', auto: true })
560    notify($, `Orchestra · conflict on ${path}: ${writer} vs ${other}, sent back to re-read`)
561    return { reason: 'never read it', deny: `Orchestra: ${other} wrote ${path} v${conflict.current} and you never read it. Read the file, then reapply your change on top of its current content.` }
562  }
563  const question = `Orchestra: ${other} wrote ${path} v${conflict.current} and ${seenText}. Let the ${e.tool} by ${writer} go ahead?`
564  let choice = 'reread'
565  // Whether the user made the choice, or Orchestra sent the write back on its own (the dialog
566  // could not be shown, the dispatch ended, or the file can no longer be read).
567  let decided = false
568  // Text the user typed instead of picking an option, passed to the musician with the send-back.
569  let said = ''
570  /** @type {any} */
571  let mine = null
572  askingFiles.add(path)
573  try {
574    // A dispatch that has already gone on without this hook (its time ran out, or the person
575    // interrupted) is not asked about: the write is sent back.
576    if (signal?.aborted) throw new Error('dispatch ended')
577    let label = await $.ui.ask(question, { header: 'Conflict', options: [LET_IT_WRITE, SEND_IT_BACK, SHOW_BOTH] })
578    if (label === SHOW_BOTH) {
579      const seenText = lastText.get(textKey(key, path))
580      mine = {
581        path, writer, against: other, tool: e.tool, current: conflict.current, base: conflict.base,
582        changed: seenText === undefined || current.text == null ? null : addedLines(seenText, current.text), currentText: current.text, proposed: proposedText(e),
583      }
584      view.held = mine
585      if (!restoreTo) restoreTo = { tab: view.tab, selected: view.selected }
586      view.tab = 'artifacts'
587      view.selected = { type: 'artifact', id: path }
588      await recordIn(at, $, { type: 'conflict.shown', id: conflict.id })
589      label = await $.ui.ask(`${question} The changes are shown above.`, { header: 'Conflict', options: [LET_IT_WRITE, SEND_IT_BACK] })
590    }
591    // Any answer is the user's decision; only Let it write lets the write go ahead.
592    decided = !signal?.aborted && typeof label === 'string' && label.length > 0
593    choice = label === LET_IT_WRITE && decided ? 'overwrite' : 'reread'
594    if (decided && label !== LET_IT_WRITE && label !== SEND_IT_BACK) said = short(label, 300)
595  } catch (err) {
596    choice = 'reread'
597    debug($, `Orchestra could not ask about the conflict on ${path}, so the write is sent back: ${err instanceof Error ? err.message : String(err)}`)
598  }
599  // The session changed while the user was being asked (/clear, a resume): the conflict belonged
600  // to the session that ended, so nothing about it is recorded here and the write is sent back.
601  if (at !== epoch) return { reason: 'session changed', deny: `Orchestra: the session changed while the user was being asked about ${path}. Read the file again and reapply your change.` }
602  askingFiles.delete(path)
603  if (mine && view.held === mine) view.held = null
604  if (askingFiles.size === 0 && restoreTo) {
605    Object.assign(view, restoreTo)
606    restoreTo = null
607  }
608  // Writes through Write and Edit wait on the file lock, but a Bash command or an edit outside
609  // Claude Code can change the file while the dialog is open. Then the approval was for an older
610  // version, so the write is attempted again against the version there now.
611  if (choice === 'overwrite') {
612    const mark = seq
613    const again = await snapshot($, path)
614    // A file that can no longer be read may have changed since the answer, so the approval does
615    // not cover it: the write is sent back.
616    if (again.error && !again.stamp) {
617      choice = 'reread'
618      decided = false
619    }
620    else if (versionOfSnap(again) !== current.hash) {
621      await claimForRunning($, path, again, mark, at)
622      return guardWrite($, e, key, path, { ...again, hash: versionOfSnap(again) }, signal, conflict, at)
623    }
624  }
625  await recordIn(at, $, { type: 'conflict.resolved', id: conflict.id, choice, ...(decided ? {} : { auto: true }), ...(said ? { said } : {}) })
626  notify($, `Orchestra · conflict on ${path}: ${writer} vs ${other}, ${choice === 'overwrite' ? 'write allowed' : 'sent back to re-read'}`)
627  if (choice === 'overwrite') return { base: current, allowedOver: { who: other, v: conflict.current } }
628  const note = said ? ` The user said: ${said}` : ''
629  return { reason: 'stale base', deny: `Orchestra: ${other} wrote ${path} v${conflict.current} and you last saw v${conflict.base}. Read the file again and reapply your change on top of its current content.${note}` }
630}
631
632// Who wrote the version a conflict is about: a musician with its part, someone outside, or for a
633// shell change no single musician made, the musicians whose commands could have.
634function writerOf(path, conflict) {
635  return conflict.against === 'shell' ? authorOf(state, state.artifacts[path]?.versions[conflict.current]) : whoOf(state, conflict.against)
636}
637
638// A conflict's outcome toast. Shown after the decision is recorded, and never allowed to throw.
639function notify($, text) {
640  try {
641    $.ui.toast(text, { timeoutMs: 8000 })
642  } catch (err) {
643    debug($, `Orchestra could not show a toast: ${err instanceof Error ? err.message : String(err)}`)
644  }
645}
646
647// Files the ledger already knows, read before and after a Bash call; any that changed is a
648// version written by whoever ran the command.
649async function snapshotKnown($) {
650  // Only while a performance is running, and only for files inside the project. Every Bash
651  // call reads and hashes these twice, so tracking the whole machine would stall the session.
652  if (!isPerformance(state)) return {}
653  const paths = Object.keys(state.artifacts).filter((path) =>
654    !path.startsWith('.orchestra/performances/') && !isAbsolute(path) && !path.split('/').includes('..'))
655  const snaps = await snapshotAll($, paths)
656  // A file that cannot be read is compared by size and time; one without even those is left out.
657  for (const [i, s] of snaps.entries()) if (s.error && !s.stamp) debug($, `Orchestra could not read ${paths[i]} before a shell command (${s.reason}), so a change to it is not attributed`)
658  return Object.fromEntries(paths.map((path, i) => [path, snaps[i]]).filter(([, s]) => !s.error || s.stamp))
659}
660
661
662async function attributeBash($, key, before, mark, at = epoch) {
663  // `mark.overlapped` is read here, after the snapshots, not before them. Another loop's call
664  // can start while the snapshots run, and that call can be what changed the file.
665  const entries = Object.entries(before)
666  const watermark = seq
667  const nows = await snapshotAll($, entries.map(([path]) => path))
668  mark.after = Object.fromEntries(entries.map(([path], i) => [path, nows[i]]))
669  for (const [i, [path, prev]] of entries.entries()) {
670    const now = nows[i]
671    if (!now) continue
672    if (now.error && !now.stamp) {
673      debug($, `Orchestra could not read ${path} after a shell command (${now.reason}), so a change to it may be missing from the ledger`)
674      continue
675    }
676    if (versionOfSnap(now) === versionOfSnap(prev)) continue
677    // Another loop's foreground command still running started from the same version of this file,
678    // so either could have made the change: it is credited to neither (a background command only
679    // makes this change uncertain, through the overlap mark). A command that is ending too counts
680    // unless its own after-snapshot already showed the file unchanged: then it did not make it.
681    const others = [...bashRunning].filter((m) => m !== mark && m.loop !== key && !m.background && m.known && path in m.known
682      && versionOfSnap(m.known[path]) === versionOfSnap(prev)
683      && !(m.after?.[path] && versionOfSnap(m.after[path]) === versionOfSnap(prev)))
684    const change = { key, prev, now, uncertain: mark.overlapped, watermark, loops: [key, ...new Set(others.map((m) => m.loop))] }
685    // A write to this file is landing: the change is most likely that write, which records itself.
686    // It is kept until the write's result: if the write fails, the change is the command's after all.
687    if (landing.get(path)?.size) {
688      holdForLanding(path, change)
689      continue
690    }
691    await recordShellChange($, key, path, prev, now, change.uncertain, watermark, change.loops, at)
692  }
693}
694
695// Shell changes seen while a write to the same file was landing, by path, until that write's result.
696/** @type {Map<string, any[]>} */
697const heldForLanding = new Map()
698function holdForLanding(path, change) {
699  heldForLanding.set(path, [...(heldForLanding.get(path) || []), change])
700}
701// The write to `path` has its result: when it failed, the changes held for it are recorded.
702async function settleHeld($, path, ok, at) {
703  const held = heldForLanding.get(path)
704  heldForLanding.delete(path)
705  if (ok || !held) return
706  for (const c of held) await recordShellChange($, c.key, path, c.prev, c.now, c.uncertain, c.watermark, c.loops, at)
707}
708
709// A snapshot's version key: the content hash, or size and time for a file too large to read.
710const versionOfSnap = (snap) => snap.hash ?? snap.stamp
711
712// A shell command's change to a project file. Decided right before the event is applied: a
713// hash the ledger already holds as its latest version was recorded by someone else; a version
714// recorded after this change was seen (`watermark`) makes this one an older state, dropped. The
715// lines are measured against the version it replaced: the latest recorded one when Orchestra
716// knows its text, else the command's own starting point when that is still the latest;
717// otherwise they are unknown, none are counted and the version is marked unchecked.
718async function recordShellChange($, key, path, prev, now, uncertain, watermark, loops = [key], at = epoch) {
719  const hash = versionOfSnap(now)
720  const rank = (k) => (state.order.indexOf(k) + 1 || Infinity)
721  const candidates = [...loops].sort((x, y) => rank(x) - rank(y))
722  const event = await recordIn(at, $, () => {
723    const last = state.artifacts[path] && latest(state.artifacts[path])
724    if (last && last.hash === hash) return null
725    if (last && last.seq > watermark) return null
726    const known = versionText.get(path)
727    const base = now.error || prev.error ? undefined
728      : !last || last.hash === prev.hash ? prev.text
729      : known && known.hash === last.hash ? known.text : undefined
730    const delta = base === undefined ? { unchecked: true } : lineDelta(base, now.text)
731    // Commands of more than one musician could have made it: a shell change credited to none.
732    if (candidates.length > 1) return { type: 'artifact.write', agent: 'shell', candidates, path, hash, via: 'bash', uncertain: true, ...delta }
733    return { type: 'artifact.write', agent: key, path, hash, via: 'bash', uncertain, ...delta }
734  })
735  if (event) rememberText(path, now)
736}
737
738// A file a running shell command covers changed and nobody recorded it: the commands that started
739// before the change are the likeliest authors, so the change is credited before a read or a write
740// attempt would record it as written outside the ensemble. One loop's commands: credited to it,
741// certain only when nothing else ran during them. Several loops' commands: credited to none of
742// them (a shell change by one of them). `watermark` is the sequence number taken before `snap`
743// was read, so a version recorded since is never followed by this older one.
744async function claimForRunning($, path, snap, watermark, at = epoch) {
745  const hash = snap && versionOfSnap(snap)
746  const a = state.artifacts[path]
747  // Already the latest version (an older one, a revert, is a change like any other).
748  if (!hash || (a && latest(a)?.hash === hash)) return
749  // A command that started from this very version did not make it: the change came before it.
750  const running = [...bashRunning].filter((m) => m.known && path in m.known && versionOfSnap(m.known[path]) !== hash)
751  if (!running.length) return
752  const m = running[running.length - 1]
753  const loops = [...new Set(running.map((x) => x.loop))]
754  const change = { key: m.loop, prev: m.known[path], now: snap, uncertain: loops.length > 1 || m.overlapped, watermark, loops }
755  // A write tool's change landing now records itself; if that write fails, this was the command's.
756  if (landing.get(path)?.size) {
757    holdForLanding(path, change)
758    return
759  }
760  await recordShellChange($, m.loop, path, change.prev, snap, change.uncertain, watermark, loops, at)
761}
762
763// Orchestra's own bookkeeping fails open: an error in it is logged and the tool still runs, and
764// the tool's real result is returned. Only the tool's own error reaches the musician.
765
766// Before the tool runs: snapshot tracked files around a shell command, record the call, and for
767// a write take the file lock and run the guard. The caller releases `out.release`.
768async function beforeTool($, e, key, target, isWrite, mark, untracked, signal, at = epoch) {
769  /** @type {{ known: Record<string, any>|null, base: any, readBefore: any, readBeforeSeq: number, at: number, allowedOver: { who: string, v: number }|null, refusal: { deny: string }|null, openConflict: string|null, reason: string, release: (() => void)|null, callRecorded: boolean }} */
770  const out = { known: null, base: null, readBefore: null, readBeforeSeq: 0, allowedOver: null, refusal: null, openConflict: null, reason: '', release: null, callRecorded: false, at }
771  /** @type {number|null} */
772  let guardFrom = null
773  let guarded = false
774  try {
775    if (mark) {
776      out.known = await snapshotKnown($)
777      mark.known = out.known
778      // A change another loop made while the snapshots were queued may be in some of them and not
779      // others, so overlap seen then still counts, as does anything running now.
780      mark.overlapped = mark.overlapped || othersWriting(key)
781    }
782    out.callRecorded = Boolean(await recordIn(at, $, { type: 'tool.call', agent: key, tool: e.tool, target }))
783    const g = e.tool_use_id ? guarding.get(e.tool_use_id) : undefined
784    if (g) g.called = out.callRecorded
785    // A Read is snapshotted before it runs too: if a write lands while it runs, the earlier
786    // version is the one recorded, so a later write from this view is still checked.
787    if (e.tool === 'Read' && e.file_path && !untracked) {
788      out.readBeforeSeq = seq
789      out.readBefore = await snapshot($, e.file_path)
790    }
791    // The dispatch went on without this hook (it ran out of time): nothing more is done for it.
792    if (!isWrite || signal?.aborted) return out
793    out.release = claimFile(target)
794    if (!out.release) {
795      out.reason = 'file busy'
796      out.refusal = { deny: askingFiles.has(target)
797        ? `Orchestra: another musician's write to ${target} is waiting for the user's decision. Do your other work first; when you come back to this file, read it again and reapply your change on top of its current content (if the decision is still pending you will be told again).`
798        : `Orchestra: another musician is writing ${target} right now. Read the file again and reapply your change on top of its current content.` }
799    } else {
800      await guardFile($, e, key, target, out, signal, () => { guardFrom = seq }, at)
801      guarded = true
802    }
803  } catch (err) {
804    const settle = refusalAfterError(key, target, guardFrom)
805    if (settle) {
806      out.refusal = { deny: settle.deny }
807      out.openConflict = settle.open
808      out.reason = 'conflict not settled'
809    }
810    // The guard failed after its snapshot: the write is not checked, so its lines are not counted.
811    else if (isWrite && !guarded) out.base = null
812    debug($, `Orchestra could not prepare ${e.tool} (${err instanceof Error ? err.message : String(err)}); the call runs, and what it changes may show as outside the ensemble`)
813  }
814  if (out.refusal) {
815    // A conflict the error left open is settled as sent back, which is what happens to the write.
816    const open = out.openConflict
817    await recordIn(at, $, [
818      open ? { type: 'conflict.resolved', id: open, choice: 'reread', auto: true } : null,
819      { type: 'tool.result', agent: key, tool: e.tool, target, ok: false, sentBack: true, error: `sent back by Orchestra: ${out.reason}` },
820    ])
821      .catch((err) => debug($, `Orchestra could not record a send-back: ${err instanceof Error ? err.message : String(err)}`))
822  }
823  return out
824}
825
826// The guard's part of beforeTool, once the file is claimed: snapshot it, credit a background
827// command's unrecorded change, then check the write against other musicians' work.
828async function guardFile($, e, key, target, out, signal, onGuard, at = epoch) {
829  out.baseSeq = seq
830  out.base = await snapshot($, e.file_path || e.notebook_path)
831  // A file too large to read is checked by its size and modification time; one whose size is
832  // unknown too cannot be checked, and the write goes ahead rather than being refused for good.
833  if (out.base.error && !out.base.stamp) {
834    debug($, `Orchestra could not read ${target} (${out.base.reason}), so ${e.tool} goes ahead without a conflict check`)
835    return
836  }
837  await claimForRunning($, target, out.base, out.baseSeq, at)
838  onGuard()
839  if (signal?.aborted) return
840  const guard = await guardWrite($, e, key, target, { ...out.base, hash: versionOfSnap(out.base) }, signal, null, at)
841  if (guard.deny) {
842    out.refusal = { deny: guard.deny }
843    out.reason = guard.reason
844  } else {
845    out.base = guard.base
846    out.allowedOver = guard.allowedOver ?? null
847  }
848}
849
850// If the guard had found a conflict on this write and failed before the user's "Let it write"
851// was recorded, the write is sent back rather than landing unasked or against the answer.
852function refusalAfterError(key, target, guardFrom) {
853  if (guardFrom === null) return null
854  const held = state.conflicts.filter((c) => c.agent === key && c.path === target && c.seq > guardFrom).at(-1)
855  if (!held || held.choice === 'overwrite') return null
856  return { deny: `Orchestra could not settle a conflict on ${target}. Read the file again and reapply your change on top of its current content.`, open: held.resolved ? null : held.id }
857}
858
859// After the tool ran: attribute shell changes, record a write or a read, and record the result.
860// Each step fails on its own, so the result is recorded whatever happened before it.
861async function afterTool($, e, key, target, isWrite, mark, before, result, untracked, wmark) {
862  const at = before.at
863  const ok = !(result && (result.isError || result.deny))
864  const output = /** @type {any} */ (result)?.result
865  const step = async (what, fn) => {
866    try {
867      await fn()
868    } catch (err) {
869      debug($, `Orchestra could not ${what} after ${e.tool}: ${err instanceof Error ? err.message : String(err)}`)
870    }
871  }
872  if (mark && output?.backgroundTaskId) await step('track the background command', () => startBackground($, String(output.backgroundTaskId), key, e, before, mark, output))
873  else if (mark && e.run_in_background) debug($, `Orchestra saw ${e.tool} run in the background with no task id, so it is not tracked`)
874  else if (before.known && mark) await step('attribute the shell command\'s changes', () => attributeBash($, key, before.known, mark, at))
875  if (ok && e.tool === 'TaskStop') await step('end the stopped task', () => stopBackground($, String(output?.task_id || e.task_id || e.shell_id || '')))
876  if (ok && isWrite) await step('record the write', () => recordWrite($, e, key, target, before, wmark))
877  if (isWrite) await step('settle shell changes held for the write', () => settleHeld($, target, ok, at))
878  if (ok && e.tool === 'Read' && e.file_path && !untracked) await step('record the read', () => recordRead($, e, key, target, before))
879  // A call made before the performance began is recorded with its result, so no result stands
880  // without its call.
881  await step('record the result', () => recordIn(at, $, [
882    before.callRecorded ? null : { type: 'tool.call', agent: key, tool: e.tool, target },
883    { type: 'tool.result', agent: key, tool: e.tool, target, ok, error: ok ? undefined : short(result?.text || result?.deny, 200), line: ok ? undefined : firstErrorLine(result?.text || result?.deny) },
884  ]))
885}
886
887async function recordWrite($, e, key, target, before, wmark) {
888  const at = before.at
889  const after = await snapshot($, e.file_path || e.notebook_path)
890  const hash = after.hash ?? after.stamp
891  if (!hash) debug($, `Orchestra could not read ${target} after ${e.tool} (${after.reason}), so the write is missing from the ledger`)
892  // Without a readable starting point or result (an unreadable file, or a guard that failed
893  // before its snapshot) the lines changed are unknown: none are counted, marked unchecked.
894  // Another loop's shell command ran while the write landed and may have changed the file too:
895  // the counts stand only when the file is exactly what this write alone makes of its base.
896  const alone = wmark?.overlapped && before.base?.text != null ? writeResult(e, before.base.text) : undefined
897  const mixed = wmark?.overlapped && (alone === undefined || alone !== after.text)
898  const unknown = !before.base || before.base.error || after.error || mixed
899  const delta = unknown ? { unchecked: true } : lineDelta(before.base.text, after.text)
900  // The bytes the write started from; 'none' for a file it created.
901  const from = before.base ? versionOfSnap(before.base) ?? 'none' : undefined
902  if (hash) await recordIn(at, $, { type: 'artifact.write', agent: key, path: target, hash, from, ...delta }, Boolean(before.allowedOver))
903  rememberText(target, after)
904  if (after.text !== null) lastText.set(textKey(key, target), after.text)
905}
906
907async function recordRead($, e, key, target, before) {
908  const at = before.at
909  const afterSeq = seq
910  const after = await snapshot($, e.file_path)
911  const seen = before.readBefore?.hash && before.readBefore.hash !== after.hash ? before.readBefore : after
912  const hash = seen.hash ?? seen.stamp
913  if (!hash) {
914    debug($, `Orchestra could not read ${target} after a Read (${after.reason}), so the read is missing from the ledger`)
915    return
916  }
917  await claimForRunning($, target, seen, seen === before.readBefore ? before.readBeforeSeq : afterSeq, at)
918  await recordIn(at, $, { type: 'artifact.read', agent: key, path: target, hash })
919  rememberText(target, seen)
920  if (seen.text !== null) lastText.set(textKey(key, target), seen.text)
921}
922
923// Each background task's notification in a message names the task and, once it has ended, its
924// status.
925// A status counts as the end only when one is given and it is not still running.
926// `trackedOnly`: the row may only quote a notification, so only tasks Orchestra tracks are ended.
927async function endBackground($, text, trackedOnly) {
928  for (const [block] of text.matchAll(/<task-notification>[\s\S]*?<\/task-notification>/g)) {
929    const id = /<task-id>([^<]+)<\/task-id>/.exec(block)?.[1]?.trim()
930    const status = /<status>([^<]+)<\/status>/.exec(block)?.[1]?.trim()
931    if (!id) continue
932    if (!status) debug($, `Orchestra read a notification for task ${id} with no status, so the task stays open`)
933    else if (status !== 'running' && status !== 'pending') await finishBackground($, id, status, trackedOnly)
934  }
935}
936
937// A shell command moved to the background: it is tracked until it ends. Its notification may
938// already have arrived, in which case it ends at once.
939async function startBackground($, id, key, e, before, mark, output) {
940  const at = before.at
941  mark.background = true
942  background.set(id, { loop: key, endsWithAnswer: Boolean(output.backgroundEndsWithFinalResponse), known: before.known, mark })
943  await recordIn(at, $, { type: 'background.started', agent: key, task: id, command: short(e.command, 120) })
944  debug($, `Orchestra is tracking background task ${id} from ${nameOf(state, key)}`)
945  overlapOthers(key)
946  const ended = endedTasks.get(id)
947  if (ended) {
948    endedTasks.delete(id)
949    await finishBackground($, id, ended, false, at)
950  } else await writeCoda($, false, at)
951}
952
953async function stopBackground($, id) {
954  if (id) await finishBackground($, id, 'killed')
955}
956
957// A background command ended: it stops counting as overlap, and its changes not yet recorded are
958// found and credited to the loop that started it.
959async function finishBackground($, id, status, tracked = false, at = epoch) {
960  const b = background.get(id)
961  if (!b) {
962    if (endedTaskLoops.has(id)) return
963    // A row that may only quote a notification ends nothing Orchestra is not tracking.
964    if (tracked) {
965      debug($, `Orchestra ignored a notification for background task ${id}, which it is not tracking`)
966      return
967    }
968    endedTasks.set(id, status)
969    if (endedTasks.size > 200) endedTasks.delete(endedTasks.keys().next().value ?? '')
970    return
971  }
972  background.delete(id)
973  endedTaskLoops.set(id, b.loop)
974  if (endedTaskLoops.size > 200) endedTaskLoops.delete(endedTaskLoops.keys().next().value ?? '')
975  debug($, `Orchestra: background task ${id} ended (${status})`)
976  // Each step fails on its own; the command covers its files until its changes are attributed
977  // (claimForRunning).
978  const step = async (what, fn) => {
979    try {
980      await fn()
981    } catch (err) {
982      debug($, `Orchestra could not ${what} for background task ${id}: ${err instanceof Error ? err.message : String(err)}`)
983    }
984  }
985  try {
986    await step('record the end', () => recordIn(at, $, { type: 'background.ended', task: id, status }))
987    if (b.known) await step('attribute the changes', () => attributeBash($, b.loop, b.known, b.mark, at))
988    await step('rewrite the coda', () => writeCoda($, false, at))
989  } finally {
990    bashRunning.delete(b.mark)
991  }
992}
993
994// Sets up a new performance for the session now running. Everything is read first; then the
995// paths, the state and the counters are replaced together with no await in between, so no hook
996// sees a half-started session, and a hook still running for the previous one (older epoch)
997// cannot save its events into this session's files. A ledger that cannot be read is never
998// overwritten: the session goes on unsaved.
999async function startSession($) {
1000  const dir = await $.session.cwd()
1001  const id = await $.session.id()
1002  const base = `${dir}/.orchestra/performances`
1003  const nextRoots = await rootsOf($, dir)
1004  let events = []
1005  let folded = emptyState()
1006  let readable = true
1007  try {
1008    events = await loadLedger($, base, id)
1009    if (events.length) folded = fold(events)
1010  } catch (err) {
1011    readable = false
1012    events = []
1013    folded = emptyState()
1014    debug($, `Orchestra could not read the ledger in ${base} (${err instanceof Error ? err.message : String(err)}), so this session's events are not saved`)
1015  }
1016  const ts = await $.clock.now()
1017  epoch += 1
1018  cwd = dir
1019  sessionId = id
1020  ledgerDir = base
1021  ledgerBase = readable ? `${base}/${id}` : ''
1022  codaFile = readable ? `${ledgerBase}-coda.md` : ''
1023  roots = nextRoots
1024  for (const m of [background, landing, inFlight, versionText, busyFiles, endedTasks, endedTaskLoops, heldForLanding]) m.clear()
1025  for (const s of [bashRunning, askingFiles, wokenByTask, resumedByMessage, writesLanding, warned]) s.clear()
1026  tooBig.clear()
1027  guarding.clear()
1028  lastText.clear()
1029  restoreTo = null
1030  Object.assign(view, { codaPath: null, held: null, selected: null, offset: 0 })
1031  state = folded
1032  seq = events.length ? events[events.length - 1].seq : 0
1033  persisted = seq
1034  if (!events.length) apply(state, { seq: ++seq, ts, type: 'session.start', session: sessionId, cwd })
1035  if (!readable) warn($, 'ledger', `could not read its ledger in ${relative(base)}, so this session is not being saved (the files are left as they are)`)
1036  if (events.length && isPerformance(state)) {
1037    // What the loaded ledger left open belonged to a process that has ended.
1038    const open = Object.entries(state.background).filter(([, b]) => b.status === null).map(([task]) => task)
1039    const closing = [...open.map((task) => ({ type: 'background.ended', task, status: 'session ended' })), ...closeLeftOpen(state)]
1040    await record($, [{ type: 'session.resumed', session: sessionId }, ...closing])
1041    if (closing.length) await writeCoda($)
1042  }
1043  if (state.codaSeq && codaFile) view.codaPath = relative(codaFile)
1044  showStatus($)
1045  $.ui.invalidate('ui.render')
1046}
1047
1048// Lets go of the session that ended: nothing more is saved into its files and nothing of it is
1049// shown. A hook still running for it holds an older epoch and records nothing.
1050function retireSession($) {
1051  epoch += 1
1052  sessionId = ''
1053  ledgerBase = ''
1054  codaFile = ''
1055  state = emptyState()
1056  seq = 0
1057  persisted = 0
1058  restoreTo = null
1059  askingFiles.clear()
1060  Object.assign(view, { codaPath: null, held: null, selected: null, offset: 0 })
1061  $.ui.status(undefined)
1062  $.ui.invalidate('ui.render')
1063}
1064
1065// Starts a new performance when the session running now is not the one Orchestra holds: at
1066// session.start, after a /clear or an in-process resume (which raise no session.start), and after
1067// a reload. Concurrent hooks share one start, and none compares ids while a start is running.
1068async function ensureSession($) {
1069  const id = await $.session.id()
1070  if (starting) await starting
1071  if (id === sessionId) return
1072  if (!starting) {
1073    starting = (async () => {
1074      // The session held now ended without its session.end reaching Orchestra (or before it did):
1075      // it is closed first, so its coda and ledger say how it ended.
1076      if (sessionId && isPerformance(state) && state.ended === null) await safely($, 'close the previous session', () => endSession($))
1077      await startSession($)
1078    })()
1079      .catch((err) => warn($, 'start', `could not start recording this session (${err instanceof Error ? err.message : String(err)})`))
1080      .finally(() => { starting = null })
1081  }
1082  await starting
1083}
1084
1085// A session ends: what it leaves open is closed (parts still playing fail as cut off, open
1086// conflicts are sent back, calls without a result are closed, the conductor's turn ends), running
1087// background commands are ended and their changes so far found, the end is recorded, and the coda
1088// is rewritten when anything happened since it was last written. Cheap records come first: the
1089// background attribution reads files and may not finish if the process is going away.
1090async function endSession($) {
1091  const at = epoch
1092  if (isPerformance(state) && state.ended === null) {
1093    await recordIn(at, $, closeLeftOpen(state))
1094    for (const id of [...background.keys()]) await finishBackground($, id, 'session ended', false, at)
1095    await recordIn(at, $, { type: 'session.ended', session: sessionId })
1096    const sinceCoda = state.events.filter((x) => x.seq > (state.codaSeq ?? 0) && x.type !== 'session.ended').length
1097    if (sinceCoda && at === epoch && codaFile) {
1098      // Written directly: the session has ended, so no coda event is added after its end marker.
1099      const text = codaMarkdown(state, ledgerPath())
1100      const file = codaFile
1101      codaWrites = codaWrites.then(() => $.fs.write(file, text))
1102        .catch((err) => warn($, 'coda', `could not write the coda to ${relative(file)} (${err instanceof Error ? err.message : String(err)})`))
1103    }
1104  } else {
1105    for (const id of [...background.keys()]) await finishBackground($, id, 'session ended', false, at)
1106  }
1107  await persisting
1108  await codaWrites
1109}
1110
1111// Runs Orchestra's bookkeeping for a hook so that a failure is logged, never thrown into the turn.
1112async function safely($, what, fn) {
1113  try {
1114    await fn()
1115  } catch (err) {
1116    debug($, `Orchestra could not ${what}: ${err instanceof Error ? err.message : String(err)}`)
1117  }
1118}
1119
1120async function toolCall($, e, next) {
1121  await safely($, 'start a new performance', () => ensureSession($))
1122  const mine = epoch
1123  const at = mine
1124  const key = loopOf(e)
1125  const target = await targetOf($, e)
1126  const path = e.file_path || e.notebook_path
1127  // Orchestra tracks the project's files only: a file outside it (Claude Code's own task output,
1128  // say) and Orchestra's own ledger and coda are recorded as calls, never as reads or writes, and
1129  // their writes are not guarded.
1130  const untracked = Boolean(path && (isAbsolute(target) || target.startsWith('.orchestra/performances/')))
1131  const isWrite = Boolean(WRITE_TOOLS.has(e.tool) && path && !untracked)
1132  if (next.signal?.aborted) return undefined
1133  if (e.tool_use_id) guarding.set(e.tool_use_id, { key, target, isWrite, called: false })
1134  // A finished musician working again was sent more work (SendMessage), unless it was woken only to
1135  // hear that its background command ended.
1136  const message = resumedByMessage.delete(key)
1137  if (state.musicians[key]?.finished && (message || !wokenByTask.has(key))) await safely($, 'record a resumed part', () => recordIn(at, $, { type: 'part.resumed', agent: key }))
1138  // A write tool counts as changing files only once it is let through (see `inFlight`).
1139  let counted = changesFiles(e.tool) && !isWrite && !(WRITE_TOOLS.has(e.tool) && untracked)
1140  if (counted) startWriting(key)
1141  const mark = SHELL_TOOLS.has(e.tool) ? { loop: key, overlapped: othersWriting(key), known: /** @type {Record<string, any>|null} */ (null), background: false } : null
1142  if (mark) {
1143    bashRunning.add(mark)
1144    for (const w of writesLanding) if (w.loop !== key) w.overlapped = true
1145  }
1146  /** @type {{ loop: string, overlapped: boolean }|null} */
1147  let wmark = null
1148  /** @type {(() => void)|null} */
1149  let release = null
1150  try {
1151    const before = await beforeTool($, e, key, target, isWrite, mark, untracked, next.signal, mine)
1152    release = before.release
1153    if (before.refusal) return before.refusal
1154    // The hook ran out of time or was interrupted: the dispatch has gone on without it (the
1155    // `.catch` answered for the call), so nothing more is recorded for it.
1156    if (next.signal?.aborted) {
1157      debug($, `Orchestra's check of ${e.tool} on ${target} did not finish in time; the call went on without being recorded`)
1158      return undefined
1159    }
1160    if (e.tool_use_id) guarding.delete(e.tool_use_id)
1161    if (isWrite) {
1162      counted = true
1163      startWriting(key)
1164      landing.set(target, (landing.get(target) || new Set()).add(key))
1165      wmark = { loop: key, overlapped: [...bashRunning].some((m) => m.loop !== key) }
1166      writesLanding.add(wmark)
1167    }
1168    const result = await next(e)
1169    if (mine === epoch) await afterTool($, e, key, target, isWrite, mark, before, result, untracked, wmark)
1170    return withContext(e, before, result)
1171  } finally {
1172    if (release) release()
1173    if (wmark) writesLanding.delete(wmark)
1174    if (e.tool_use_id) guarding.delete(e.tool_use_id)
1175    // A hook from a session that has since been replaced leaves the new session's maps alone.
1176    if (mine === epoch) {
1177      if (counted) stopWriting(key)
1178      if (isWrite && landing.get(target)?.delete(key) && !landing.get(target)?.size) landing.delete(target)
1179      // A backgrounded command's mark stays until the command ends (finishBackground).
1180      if (mark && ![...background.values()].some((b) => b.mark === mark)) bashRunning.delete(mark)
1181    }
1182  }
1183}
1184
1185// What the model is told beside a tool's result: that the user let a write go ahead over another
1186// musician's version, and an Agent call's musician name as Orchestra shows it.
1187function withContext(e, before, result) {
1188  const notes = []
1189  if (before.allowedOver && result && !result.isError && !result.deny) notes.push(`Orchestra: ${before.allowedOver.who} had written v${before.allowedOver.v} of this file since you last read it. The user let your write go ahead over it.`)
1190  const agent = e.tool === 'Agent' && e.tool_use_id ? state.rows[e.tool_use_id] : undefined
1191  if (agent && state.musicians[agent]) notes.push(`Orchestra shows this musician as ${state.musicians[agent].name}.`)
1192  if (!notes.length || !result || result.deny) return result
1193  return { ...result, context: [...(result.context || []), ...notes] }
1194}
1195
1196// /theme does not raise config.set, so a timer re-reads the theme every THEME_RECHECK_MS.
1197async function refreshTheme($) {
1198  const theme = (await $.config.list()).find((row) => row.key === 'theme')?.value
1199  const next = modeFor(theme, colorterm, term)
1200  if (next === colorMode()) return
hooks/ledger.js 746 lines
1// Orchestra's ledger: an append-only list of observations, and the state folded from it.
2// Only observations are recorded (a spawn, a tool call, the hash of a file read or written,
3// a user's decision). Conflicts, stale reads and handoffs are derived here from versions,
4// so replaying the same log always gives the same picture.
5
6/**
7 * @typedef {{ v: number, hash: string, agent: string, base: number|null, added: number, removed: number, seq: number, via?: string, uncertain?: boolean, unchecked?: boolean, observed?: boolean, candidates?: string[] }} Version
8 * @typedef {{ path: string, versions: Version[], reads: { agent: string, v: number, seq: number }[] }} Artifact
9 * @typedef {{ key: string, instrument: string, name: string, n: number, type: string, role: string, color: string, state: string, finished?: boolean,
10 *   assigned: boolean, part: string|null, prompt?: string, parent?: string, measures: number,
11 *   answer: string|null, failure?: string,
12 *   seen: Record<string, number>, readSeq: Record<string, number>, reads: number, writes: number, added: number, removed: number }} Musician
13 * @typedef {{ id: string, path: string, agent: string, tool?: string, against: string, base: number|null, current: number, seq: number,
14 *   resolved: boolean, choice: string|null, auto?: boolean, resolvedSeq?: number, shown?: number,
15 *   said?: string, landed?: boolean, refused?: string, redone?: boolean }} Conflict
16 * @typedef {{ agent: string, path: string, readV: number, currentV: number, writer: string, products: string[], seq: number,
17 *   cleared: boolean, clearedSeq?: number, clearedBy?: string }} Stale
18 * @typedef {{ from: string, to: string, path: string, v: number, seq: number, via: string }} Handoff
19 * @typedef {{ agent: string, tool: string, target: string, error?: string, line?: string, seq: number, recoveredSeq: number|null, recoveredBy?: string }} ToolFailure
20 * @typedef {Record<string, any> & { seq: number, ts: number, type: string }} LedgerEvent
21 * @typedef {{ session: string|null, cwd: string|null, task: string|null, events: LedgerEvent[],
22 *   musicians: Record<string, Musician>, order: string[], artifacts: Record<string, Artifact>,
23 *   conflicts: Conflict[], stale: Stale[], handoffs: Handoff[], toolFailures: ToolFailure[],
24 *   rows: Record<string, string>, codaSeq: number|null, requests: string[], ended: number|null,
25 *   background: Record<string, { agent: string, command: string, seq: number, status: string|null }>,
26 *   busySendBacks: { agent: string, target: string, seq: number }[] }} State
27 */
28
29/** @type {Record<string, { name: string, role: string }>} */
30export const INSTRUMENTS = {
31  conductor: { name: 'Conductor', role: 'Plans the score, assigns parts, presents the coda' },
32  violin: { name: 'Violin', role: 'Scout' },
33  trumpet: { name: 'Trumpet', role: 'Implementer' },
34  flute: { name: 'Flute', role: 'Scribe' },
35  timpani: { name: 'Timpani', role: 'Tester' },
36  cello: { name: 'Cello', role: 'Reviewer' },
37  guest: { name: 'Guest', role: 'Subagent outside the orchestra' },
38}
39
40export const CONDUCTOR = 'conductor'
41const GUEST = { name: 'Guest', role: 'Subagent outside the orchestra' }
42export const instrumentDef = (name) => INSTRUMENTS[name] ?? GUEST
43// Authors who are not musicians: the file as first seen, a change made outside the ensemble, and
44// a shell change that more than one musician's command could have made.
45const NOBODY = new Set(['repo', 'outside', 'shell'])
46// The conductor's plan, as recorded: paths inside the project are kept relative to it.
47// Revising it is the plan working, not stale work, so it is never an input to stale work and
48// never a product of it.
49// The same path is named in agents/conductor.md, step 1.
50const SCORE = '.orchestra/score.md'
51// Ledgers written before 0.1.3 can name the score by its absolute path.
52const isScore = (state, path) => path === SCORE || (state.cwd !== null && path === `${state.cwd}/${SCORE}`)
53
54/** @returns {State} */
55export function emptyState() {
56  return {
57    session: null,
58    cwd: null,
59    task: null,
60    events: [],
61    musicians: Object.assign(Object.create(null), { [CONDUCTOR]: newMusician(CONDUCTOR, 'conductor', instrumentDef('conductor').name, 'main loop') }),
62    order: [CONDUCTOR],
63    artifacts: Object.create(null),
64    conflicts: [],
65    stale: [],
66    handoffs: [],
67    toolFailures: [],
68    background: Object.create(null),
69    busySendBacks: [],
70    rows: Object.create(null),
71    requests: [],
72    ended: null,
73    codaSeq: null,
74  }
75}
76
77// `color` is a palette token (see palette.js), the instrument's own key.
78/** @returns {Musician} */
79function newMusician(key, instrument, name, type) {
80  return {
81    key, instrument, name, type, n: 1,
82    role: instrumentDef(instrument).role, color: instrument,
83    state: key === CONDUCTOR ? 'resting' : 'playing',
84    assigned: key === CONDUCTOR,
85    part: null, measures: 0, answer: null,
86    seen: Object.create(null), readSeq: Object.create(null),
87    reads: 0, writes: 0, added: 0, removed: 0,
88  }
89}
90
91export function instrumentOf(type) {
92  const name = String(type || '').replace(/^orchestra:/, '')
93  return INSTRUMENTS[name] && name !== 'conductor' && name !== 'guest' ? name : 'guest'
94}
95
96// A musician's name on every surface: its instrument, numbered from the second instance on
97// (`Trumpet`, `Trumpet 2`). The number is given once, when the musician's instrument becomes
98// known, as one more than the highest of that instrument so far, so a name never changes or
99// repeats within a session and replaying the ledger gives the same names.
100export function instanceName(state, key) {
101  const m = state.musicians[key]
102  if (!m) return key
103  const base = m.instrument === 'guest' ? `${GUEST.name} (${m.type})` : instrumentDef(m.instrument).name
104  return m.n > 1 ? `${base} ${m.n}` : base
105}
106
107function number(state, m) {
108  m.n = 1 + Math.max(0, ...state.order.filter((k) => k !== m.key && state.musicians[k].instrument === m.instrument).map((k) => state.musicians[k].n))
109  m.name = instanceName(state, m.key)
110}
111
112function ensureMusician(state, key, type = 'unknown') {
113  if (state.musicians[key]) return state.musicians[key]
114  const m = newMusician(key, instrumentOf(type), '', type)
115  state.musicians[key] = m
116  number(state, m)
117  state.order.push(key)
118  return m
119}
120
121// A loop first seen through a tool call is identified once its spawn is recorded.
122function identify(state, m, type) {
123  if (!type || m.type === type) return
124  const instrument = instrumentOf(type)
125  Object.assign(m, { type, instrument, role: instrumentDef(instrument).role, color: instrument })
126  number(state, m)
127}
128
129function ensureArtifact(state, path) {
130  if (!state.artifacts[path]) state.artifacts[path] = { path, versions: [], reads: [] }
131  return state.artifacts[path]
132}
133
134export const latest = (a) => a.versions[a.versions.length - 1]
135
136// Two version numbers of one file can hold the same bytes, for example after a revert.
137const sameContent = (a, v1, v2) => v1 === v2 || (a.versions[v1] !== undefined && a.versions[v1]?.hash === a.versions[v2]?.hash)
138
139// The version a hash belongs to. A hash never seen before is a version nobody in the
140// ensemble wrote: the file as it was at first sight, or a change made outside.
141function versionOf(state, path, hash, seq) {
142  const a = ensureArtifact(state, path)
143  const known = [...a.versions].reverse().find((x) => x.hash === hash)
144  if (known) return known
145  const v = { v: a.versions.length, hash, agent: a.versions.length ? 'outside' : 'repo', base: null, added: 0, removed: 0, seq, observed: true }
146  a.versions.push(v)
147  // A change made outside the ensemble replaces a version like any other: what was produced from
148  // the older one is now stale.
149  if (v.agent === 'outside') markStaleReaders(state, a, v, { path, agent: 'outside', seq })
150  return v
151}
152
153// Whether a write by `agent` over version `cur` of a file conflicts: the file changed since the
154// writer last saw it, or the writer never read it and another musician wrote it.
155function overwritesUnseen(state, agent, path, cur) {
156  const seen = state.musicians[agent]?.seen[path]
157  if (seen === undefined) return !NOBODY.has(cur.agent) && cur.agent !== agent
158  const a = state.artifacts[path]
159  return seen !== cur.v && a?.versions[seen]?.hash !== cur.hash
160}
161
162// Whether a write attempt over the file at `hash` would conflict, without recording anything.
163export function wouldConflict(state, agent, path, hash) {
164  // A file that is gone has no version to overwrite (the write.attempt fold skips it too).
165  if (hash === null || hash === undefined) return false
166  const a = state.artifacts[path]
167  const known = a && [...a.versions].reverse().find((x) => x.hash === hash)
168  const n = a ? a.versions.length : 0
169  return overwritesUnseen(state, agent, path, known ?? { v: n, hash, agent: n ? 'outside' : 'repo' })
170}
171
172// Anyone who used an older version of this file to produce something else is now stale.
173function markStaleReaders(state, a, ver, e) {
174  if (isScore(state, e.path)) return
175  for (const key of state.order) {
176    const other = state.musicians[key]
177    if (!other) continue
178    const readV = other.seen[e.path]
179    if (key === e.agent || key === CONDUCTOR || readV === undefined || readV >= ver.v || sameContent(a, readV, ver.v)) continue
180    const products = productsSince(state, key, other.readSeq[e.path]).filter((p) => p !== e.path)
181    if (!products.length) continue
182    if (state.stale.some((s) => s.agent === key && s.path === e.path && !s.cleared)) continue
183    state.stale.push({ agent: key, path: e.path, readV, currentV: ver.v, writer: e.agent, products, seq: e.seq, cleared: false })
184  }
185}
186
187function addHandoff(state, from, to, path, v, seq, via) {
188  if (NOBODY.has(from) || from === to) return
189  if (state.handoffs.some((h) => h.from === from && h.to === to && h.path === path && h.v === v)) return
190  state.handoffs.push({ from, to, path, v, seq, via })
191}
192
193export function artifactStatus(state, path) {
194  if (state.conflicts.some((c) => c.path === path && !c.resolved)) return 'conflict'
195  if (state.stale.some((s) => s.path === path && !s.cleared)) return 'stale'
196  return 'ok'
197}
198
199/** @type {Record<string, (state: State, e: LedgerEvent) => void>} */
200const handlers = {
201  'session.start'(state, e) {
202    state.session = e.session
203    state.cwd = e.cwd
204  },
205  // The task is the person's prompt the performance began under; prompts after that are later
206  // requests within it.
207  'prompt'(state, e) {
208    if (isPerformance(state)) state.requests.push(e.text)
209    else state.task = e.text
210  },
211  // The session went on in a new process (--continue, --resume): kept as a marker in the ledger.
212  'session.resumed'(state) {
213    state.ended = null
214  },
215  // The process holding the session ended (exit, /clear, a switch to another session).
216  'session.ended'(state, e) {
217    state.ended = e.seq
218  },
219  'turn.start'(state) {
220    ensureMusician(state, CONDUCTOR).state = 'playing'
221  },
222  'turn.end'(state) {
223    ensureMusician(state, CONDUCTOR).state = 'resting'
224  },
225  'part.assigned'(state, e) {
226    const m = ensureMusician(state, e.agent, e.subagentType)
227    identify(state, m, e.subagentType)
228    m.assigned = true
229    m.part = e.description || null
230    m.prompt = e.prompt
231    m.parent = e.parent || CONDUCTOR
232    m.state = 'playing'
233    m.finished = false
234    if (e.toolUseId) state.rows[e.toolUseId] = e.agent
235    // A brief that names a file another musician wrote hands that version over.
236    for (const path of e.mentions || []) {
237      const a = state.artifacts[path]
238      if (a && a.versions.length) addHandoff(state, latest(a).agent, e.agent, path, latest(a).v, e.seq, 'brief')
239    }
240  },
241  'tool.call'(state, e) {
242    const m = ensureMusician(state, e.agent)
243    // A finished musician woken only to read its background command's notification stays finished.
244    if (m.state !== 'waiting' && !m.finished) m.state = 'playing'
245  },
246  'tool.result'(state, e) {
247    const m = ensureMusician(state, e.agent)
248    m.measures += 1
249    if (!e.ok && e.sentBack) {
250      if (String(e.error).includes('file busy')) state.busySendBacks.push({ agent: e.agent, target: e.target, seq: e.seq })
251      return
252    }
253    // A call cut off when the session ended is not a failure of the tool.
254    if (!e.ok && e.error === 'session ended') return
255    if (!e.ok) {
256      // A write the user let go ahead that then failed (Claude Code's own check that the file is
257      // unchanged since it was read, say): the decision did not land.
258      const allowed = state.conflicts.filter((c) => c.agent === e.agent && c.path === e.target && (!c.tool || c.tool === e.tool) && c.choice === 'overwrite' && !c.landed && !c.refused).at(-1)
259      if (allowed) allowed.refused = String(e.error || 'the write failed')
260      state.toolFailures.push({ agent: e.agent, tool: e.tool, target: e.target, error: e.error, line: e.line, seq: e.seq, recoveredSeq: null })
261      return
262    }
263    // A failed call is recovered when any musician later runs the same call successfully.
264    for (const f of state.toolFailures) {
265      if (f.tool === e.tool && f.target === e.target && f.recoveredSeq === null) {
266        f.recoveredSeq = e.seq
267        f.recoveredBy = e.agent
268      }
269    }
270  },
271  'artifact.read'(state, e) {
272    const m = ensureMusician(state, e.agent)
273    const ver = versionOf(state, e.path, e.hash, e.seq)
274    ensureArtifact(state, e.path).reads.push({ agent: e.agent, v: ver.v, seq: e.seq })
275    m.reads += 1
276    m.seen[e.path] = ver.v
277    m.readSeq[e.path] = e.seq
278    for (const s of state.stale) {
279      if (s.agent === e.agent && s.path === e.path && !s.cleared && ver.v >= s.currentV) {
280        s.cleared = true
281        s.clearedSeq = e.seq
282        s.clearedBy = e.agent
283      }
284    }
285    addHandoff(state, ver.agent, e.agent, e.path, ver.v, e.seq, 'read')
286  },
287  // Seen just before a write runs: the hash of the file as the writer is about to change it.
288  'write.attempt'(state, e) {
289    const m = ensureMusician(state, e.agent)
290    if (e.hash === null) return
291    const cur = versionOf(state, e.path, e.hash, e.seq)
292    const seen = m.seen[e.path]
293    if (!overwritesUnseen(state, e.agent, e.path, cur)) return
294    state.conflicts.push({
295      id: `c${state.conflicts.length + 1}`, path: e.path, agent: e.agent, tool: e.tool, against: cur.agent,
296      base: seen ?? null, current: cur.v, seq: e.seq, resolved: false, choice: null,
297    })
298    m.state = 'waiting'
299  },
300  'conflict.shown'(state, e) {
301    const c = state.conflicts.find((x) => x.id === e.id)
302    if (c) c.shown = (c.shown || 0) + 1
303  },
304  'conflict.resolved'(state, e) {
305    const c = state.conflicts.find((x) => x.id === e.id)
306    if (!c) return
307    c.resolved = true
308    c.choice = e.choice
309    c.auto = Boolean(e.auto)
310    if (e.said) c.said = e.said
311    c.resolvedSeq = e.seq
312    const m = state.musicians[c.agent]
313    const stillHeld = state.conflicts.some((x) => x.agent === c.agent && !x.resolved)
314    // A finished musician woken to read its task's output stays finished once the write is settled.
315    if (m && m.state === 'waiting' && !stillHeld) m.state = m.finished ? (m.failure ? 'failed' : 'done') : 'playing'
316  },
317  'artifact.write'(state, e) {
318    const a = ensureArtifact(state, e.path)
319    const prev = latest(a)
320    // A shell change no single musician can be credited with: a version of nobody's, seen by none.
321    if (NOBODY.has(e.agent)) {
322      if (prev && prev.hash === e.hash) return
323      const ver = { v: a.versions.length, hash: e.hash, agent: e.agent, candidates: e.candidates, base: null, added: e.added, removed: e.removed, seq: e.seq, via: e.via, uncertain: true, unchecked: e.unchecked }
324      a.versions.push(ver)
325      markStaleReaders(state, a, ver, e)
326      return
327    }
328    const m = ensureMusician(state, e.agent)
329    for (const f of state.toolFailures) {
330      if (f.agent === e.agent && f.target === e.path && f.recoveredSeq === null) f.recoveredSeq = e.seq
331    }
332    for (const c of state.conflicts) {
333      if (c.agent !== e.agent || c.path !== e.path || c.choice !== 'overwrite') continue
334      if (!c.refused) c.landed = true
335      else c.redone = true
336    }
337    // Stale work is redone when its product is rewritten by someone who has seen the current input.
338    for (const s of state.stale) {
339      if (s.cleared || !s.products.includes(e.path)) continue
340      const art = ensureArtifact(state, s.path)
341      const input = latest(art)
342      const seenV = m.seen[s.path]
343      if (input && seenV !== undefined && (seenV >= input.v || sameContent(art, seenV, input.v))) {
344        s.cleared = true
345        s.clearedSeq = e.seq
346        s.clearedBy = e.agent
347      }
348    }
349    // The same bytes as the latest version: nothing changed, so nothing is counted. Unless that
350    // version was first seen by a read while this write was landing (the write changed the file,
351    // `from` its earlier bytes): then this write made it, and it is credited here.
352    if (prev && prev.hash === e.hash) {
353      const landedUnseen = prev.observed && (prev.agent === 'outside' || prev.agent === 'repo') && e.from && e.from !== e.hash
354      if (!landedUnseen) {
355        m.seen[e.path] = prev.v
356        return
357      }
358      a.versions.pop()
359      // What that first sight flagged as stale was blamed on a change from outside. This write is
360      // that change: its own check below flags the other readers again, against the real writer.
361      state.stale = state.stale.filter((s) => s.cleared || s.path !== e.path || s.currentV !== prev.v || s.writer !== prev.agent)
362    }
363    m.writes += 1
364    m.added += e.added ?? 0
365    m.removed += e.removed ?? 0
366    const ver = { v: a.versions.length, hash: e.hash, agent: e.agent, base: m.seen[e.path] ?? null, added: e.added, removed: e.removed, seq: e.seq, via: e.via, uncertain: e.uncertain, unchecked: e.unchecked }
367    a.versions.push(ver)
368    m.seen[e.path] = ver.v
369    m.readSeq[e.path] = e.seq
370    for (const r of a.reads) if (r.v === ver.v) addHandoff(state, e.agent, r.agent, e.path, ver.v, r.seq, 'read')
371    if (isScore(state, e.path)) return
372    markStaleReaders(state, a, ver, e)
373    // The other order: this writer read an input, someone else changed it, and only now does
374    // the writer produce from the version they first saw. The check above never sees that,
375    // because it runs when the input changes, before the product exists.
376    // The conductor is left out of both checks: it reads to plan, and its only product is the
377    // score, so an input changing under it is the plan working, not stale work.
378    if (e.agent === CONDUCTOR) return
379    for (const [input, readV] of Object.entries(m.seen)) {
380      if (input === e.path || isScore(state, input)) continue
381      const cur = latest(state.artifacts[input])
382      if (!cur || readV >= cur.v || sameContent(state.artifacts[input], readV, cur.v)) continue
383      if (state.stale.some((s) => s.agent === e.agent && s.path === input && !s.cleared)) continue
384      state.stale.push({ agent: e.agent, path: input, readV, currentV: cur.v, writer: cur.agent, products: [e.path], seq: e.seq, cleared: false })
385    }
386  },
387  // A finished musician the conductor sent more work (SendMessage) plays again.
388  'part.resumed'(state, e) {
389    const m = ensureMusician(state, e.agent)
390    m.finished = false
391    m.failure = undefined
392    m.state = 'playing'
393  },
394  'part.done'(state, e) {
395    const m = ensureMusician(state, e.agent)
396    m.finished = true
397    m.state = 'done'
398    m.answer = e.answer
399  },
400  'part.failed'(state, e) {
401    const m = ensureMusician(state, e.agent)
402    m.finished = true
403    m.state = 'failed'
404    m.answer = e.answer
405    m.failure = e.reason
406  },
407  'background.started'(state, e) {
408    ensureMusician(state, e.agent)
409    state.background[e.task] = { agent: e.agent, command: e.command, seq: e.seq, status: null }
410  },
411  'background.ended'(state, e) {
412    const b = state.background[e.task]
413    if (b) b.status = e.status
414  },
415  'coda'(state, e) {
416    state.codaSeq = e.seq
417  },
418}
419
420// Files a musician wrote after a given moment and that still hold its work (nobody rewrote them
421// since): the work that depends on what it had read then.
422function productsSince(state, key, sinceSeq) {
423  return Object.values(state.artifacts)
424    .filter((a) => !isScore(state, a.path) && latest(a)?.agent === key && a.versions.some((v) => v.agent === key && v.seq > (sinceSeq ?? 0)))
425    .map((a) => a.path)
426}
427
428// An event is kept only once its handler has applied it, so a handler that throws leaves no
429// half-recorded event behind to be saved.
430export function apply(state, e) {
431  const handle = handlers[e.type]
432  if (!handle) return state
433  handle(state, e)
434  state.events.push(e)
435  return state
436}
437
438// What a loaded ledger's process left open, as events that close it: that process is gone (it
439// exited, crashed, or the session was switched away from), so parts still playing or waiting end
440// as failed, conflicts still open are settled as sent back (the write never ran), and the
441// conductor's turn ends. Background commands still running are closed by the caller.
442export function closeLeftOpen(state) {
443  const open = state.conflicts.filter((c) => !c.resolved).map((c) => ({ type: 'conflict.resolved', id: c.id, choice: 'reread', auto: true }))
444  const calls = pairCalls(state).filter((c) => !c.result)
445    .map(({ call: c }) => ({ type: 'tool.result', agent: c.agent, tool: c.tool, target: c.target, ok: false, error: 'session ended' }))
446  const parts = musicians(state).filter((m) => !m.finished && (m.state === 'playing' || m.state === 'waiting'))
447    .map((m) => ({ type: 'part.failed', agent: m.key, reason: 'session ended', answer: null }))
448  const conductorState = state.musicians[CONDUCTOR]?.state
449  const conductor = conductorState === 'playing' || conductorState === 'waiting' ? [{ type: 'turn.end' }] : []
450  return [...open, ...calls, ...parts, ...conductor]
451}
452
453// Every tool call paired with its result, in call order. A result closes the oldest open call of
454// the same agent, tool and target; a call still running has no result. `agent` limits it to one loop.
455/** @returns {{ call: LedgerEvent, result: LedgerEvent|null }[]} */
456function pairCalls(state, agent = null) {
457  const pairs = []
458  const open = new Map()
459  for (const e of state.events) {
460    if ((e.type !== 'tool.call' && e.type !== 'tool.result') || (agent !== null && e.agent !== agent)) continue
461    const k = `${e.agent}\u0000${e.tool}\u0000${e.target}`
462    const list = open.get(k) || []
463    if (e.type === 'tool.call') {
464      const pair = { call: e, result: null }
465      pairs.push(pair)
466      list.push(pair)
467    } else {
468      const pair = list.shift()
469      if (pair) pair.result = e
470    }
471    open.set(k, list)
472  }
473  return pairs
474}
475
476// The call a musician is in now: its newest call without a result, or null.
477export const currentCall = (state, key) => pairCalls(state, key).filter((p) => !p.result).at(-1)?.call ?? null
478
479// A musician's last `n` calls, oldest first, each with how long it ran and how it ended; a call
480// still running has `ms` and `ok` null.
481export const lastCalls = (state, key, n) => pairCalls(state, key).slice(-n).map(({ call, result }) => ({
482  tool: call.tool, target: call.target, ts: call.ts, seq: call.seq,
483  ms: result ? result.ts - call.ts : null, ok: result ? Boolean(result.ok) : null, error: result?.error ?? null,
484}))
485
486// A duration as a person reads it: "4s", "1m 05s".
487export function elapsed(ms) {
488  const s = Math.max(0, Math.floor(ms / 1000))
489  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, '0')}s`
490}
491
492// What a musician is doing now and for how long: its open call and the time from the call's
493// start to `now`, the time of the newest recorded event. Null when it has no open call, or its part
494// has ended (a call cut off at the end leaves no result).
495export function activity(state, m, now) {
496  const call = m.finished ? null : currentCall(state, m.key)
497  if (!call) return null
498  return `${call.tool}${call.target ? ` ${call.target}` : ''}${now ? ` · ${elapsed(now - call.ts)}` : ''}`
499}
500
501// A musician's newest finished call, with how long it ran.
502export function lastCall(state, key) {
503  const done = pairCalls(state, key).findLast((p) => p.result)
504  const result = done?.result
505  return done && result ? { tool: done.call.tool, target: done.call.target, ms: result.ts - done.call.ts, ok: Boolean(result.ok) } : null
506}
507
508// The newest handoff while it is among the last HANDOFF_WINDOW events.
509const HANDOFF_WINDOW = 12
510export function liveHandoff(state) {
511  const h = state.handoffs[state.handoffs.length - 1]
512  const last = state.events[state.events.length - 1]
513  return h && last && last.seq - h.seq <= HANDOFF_WINDOW ? h : null
514}
515
516export function fold(events) {
517  return events.reduce(apply, emptyState())
518}
519
520// The roster: the conductor plus every loop it assigned a part to. Other loops (another
521// plugin's hook agents, the engine's own forks) stay in the ledger but are not musicians.
522export const roster = (state) => state.order.filter((k) => state.musicians[k].assigned)
523export const musicians = (state) => roster(state).filter((k) => k !== CONDUCTOR).map((k) => state.musicians[k])
524export const isPerformance = (state) => musicians(state).length > 0
525// A musician's name with its part, as the conflict dialog and toasts name it, so two trumpets can
526// be told apart.
527export const whoOf = (state, key) => {
528  const m = state.musicians[key]
529  return m && m.part ? `${m.name} (${m.part.length > 40 ? `${m.part.slice(0, 39)}…` : m.part})` : nameOf(state, key)
530}
531
532export const nameOf = (state, key) => (state.musicians[key] ? state.musicians[key].name
533  : key === 'outside' ? 'someone outside the ensemble' : key === 'shell' ? 'a shell command' : key)
534
535// Who wrote a version: a musician, or for a shell change no single musician made, the musicians
536// whose commands could have.
537export const authorOf = (state, v) => (v?.agent === 'shell' && v.candidates?.length
538  ? `a shell command run by ${v.candidates.map((k) => nameOf(state, k)).join(' or ')}`
539  : nameOf(state, v?.agent))
540
541// A musician's newest failed call that nobody has since run successfully, or null.
542export const openFailure = (state, key) => state.toolFailures.findLast((f) => f.agent === key && f.recoveredSeq === null) ?? null
543
544// The state every surface shows for a musician: a part that ended with one of its calls still
545// failed counts as failed, not done, so a failing command is never reported as a finished part.
546export const standing = (state, m) => (m.state === 'done' && openFailure(state, m.key) ? 'failed' : m.state)
547
548// What went wrong, in one line: the reason a part ended early, or the first line of its failed call.
549export function failureLine(state, m) {
550  if (m.state === 'failed') return m.failure || 'the part ended early'
551  const f = openFailure(state, m.key)
552  return f ? `${f.tool}${f.target ? ` ${f.target}` : ''}: ${f.line || f.error || 'failed'}` : ''
553}
554
555// How long a musician's part took, from its assignment to its end.
556export function partMs(state, key) {
557  const start = state.events.find((e) => e.agent === key && e.type === 'part.assigned')
558  const end = state.events.findLast((e) => e.agent === key && (e.type === 'part.done' || e.type === 'part.failed'))
559  return start && end ? end.ts - start.ts : null
560}
561
562export function counts(state) {
563  const ms = musicians(state)
564  const by = (s) => ms.filter((m) => standing(state, m) === s).length
565  return {
566    playing: by('playing'), waiting: by('waiting'), done: by('done'), failed: by('failed'),
567    changed: Object.values(state.artifacts).filter((a) => a.versions.some((v) => v.agent !== 'repo')).length,
568    openConflicts: state.conflicts.filter((c) => !c.resolved).length,
569    openStale: state.stale.filter((s) => !s.cleared).length,
570  }
571}
572
573// The counts a person needs at a glance, zero counts left out: playing, waiting on you, done,
574// failed, then the conflicts and stale reads still open. Each part has its palette token.
575export function rollup(state) {
576  const c = counts(state)
577  return [
578    c.playing ? { text: `${c.playing} playing`, token: 'ok' } : null,
579    c.waiting ? { text: `${c.waiting} waiting on you`, token: 'warn' } : null,
580    c.done ? { text: `${c.done} done`, token: null } : null,
581    c.failed ? { text: `${c.failed} failed`, token: 'danger' } : null,
582    c.openConflicts ? { text: `‼ ${plural(c.openConflicts, 'conflict')}`, token: 'danger', bold: true } : null,
583    c.openStale ? { text: `⚠ ${c.openStale} stale`, token: 'warn' } : null,
584  ].filter((x) => x !== null)
585}
586
587export const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`
588
589// The status line: the rollup's counts, zero counts left out, with the files changed.
590export function statusLine(state) {
591  const c = counts(state)
592  return [
593    'Orchestra',
594    c.playing ? `${c.playing} playing` : null,
595    c.waiting ? `${c.waiting} waiting on you` : null,
596    c.done ? `${c.done} done` : null,
597    c.failed ? `${c.failed} failed` : null,
598    `${plural(c.changed, 'artifact')} changed`,
599    c.openConflicts ? plural(c.openConflicts, 'conflict') : null,
600    c.openStale ? `${c.openStale} stale` : null,
601  ].filter(Boolean).join(' · ')
602}
603
604const rosterFailures = (state) => state.toolFailures.filter((f) => f.agent !== CONDUCTOR && state.musicians[f.agent]?.assigned)
605
606// Every sentence of the coda comes from ledger state, never from a musician's own prose.
607// A file's authors for the coda: musicians first, in the order they wrote, then anyone else.
608function authorsOf(state, versions) {
609  return [...new Set(versions.map((v) => authorOf(state, v)))]
610}
611
612// "a", "a and b", "a, b and c".
613export const listJoin = (items) => (items.length < 2 ? items.join('') : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`)
614
615// Why a part ended without its answer, in words.
616export const failureText = (reason) => (reason === 'session ended' ? 'the part was cut off when the session ended'
617  : reason ? `the part ended early (${reason})` : 'the part ended early')
618
619export function coda(state) {
620  // Every assigned musician, including one whose work left no recorded reads or writes (a
621  // reviewer that only answered); the conductor only when it touched files.
622  const contributions = roster(state).map((k) => state.musicians[k])
623    .filter((m) => m.key !== CONDUCTOR || m.writes > 0 || m.reads > 0)
624    .map((m) => {
625      const own = Object.values(state.artifacts).flatMap((a) => a.versions.filter((v) => v.agent === m.key))
626      return {
627        key: m.key, name: m.name, role: m.role, reads: m.reads, writes: m.writes, added: m.added, removed: m.removed,
628        failure: m.state === 'failed' ? m.failure || 'a failure' : null,
629        shell: own.filter((v) => v.via === 'bash').length,
630        uncertain: own.filter((v) => v.uncertain).length,
631        unchecked: own.filter((v) => v.unchecked).length,
632        shared: Object.values(state.artifacts).flatMap((a) => a.versions.filter((v) => v.agent === 'shell' && v.candidates?.includes(m.key)))
633          .flatMap((v) => v.candidates.filter((k) => k !== m.key).map((k) => nameOf(state, k))),
634        artifacts: Object.values(state.artifacts).filter((a) => a.versions.some((v) => v.agent === m.key)).map((a) => a.path),
635      }
636    })
637  // Every version after the file as first seen, the ones written outside the ensemble included.
638  const newVersions = (a) => a.versions.filter((v) => v.agent !== 'repo')
639  const changed = Object.values(state.artifacts)
640    .filter((a) => newVersions(a).length)
641    .map((a) => ({ path: a.path, versions: newVersions(a).length, authors: authorsOf(state, newVersions(a)), hash: latest(a).hash }))
642  const conflicts = [
643    ...state.conflicts.map((c) => ({
644      ...c,
645      text: c.base === null
646        ? `${nameOf(state, c.agent)}'s write to ${c.path} was sent back without asking: it had never read the file, and ${authorOf(state, state.artifacts[c.path]?.versions[c.current])} had written v${c.current}.`
647        : `${nameOf(state, c.agent)} tried to write ${c.path} over v${c.current}, written by ${authorOf(state, state.artifacts[c.path]?.versions[c.current])} (had seen v${c.base}). ${
648          !c.resolved ? 'Still open.'
649            : c.choice === 'overwrite' && c.refused ? `You let the write go ahead, but it then failed${
650              /modified since read/i.test(c.refused) ? ` (Claude Code refused it: the file had changed since ${nameOf(state, c.agent)} read it)` : ` (${c.refused.slice(0, 120)})`}.${
651              c.redone ? ` ${nameOf(state, c.agent)} redid it after reading the file again.` : ''}`
652            : c.choice === 'overwrite' ? 'You let the write go ahead.'
653            : c.choice === 'reask' ? 'You let the write go ahead, but the file changed before it landed, so you were asked again.'
654            : c.auto ? 'Orchestra sent the write back to re-read, without a decision from you.'
655            : c.said ? `You sent the write back to re-read, saying: "${c.said}".`
656            : 'You sent the write back to re-read.'}`,
657    })),
658    ...state.busySendBacks.map((b) => ({ seq: b.seq, text: `${nameOf(state, b.agent)}'s write to ${b.target} was sent back because another write to it was in progress.` })),
659  ].sort((x, y) => x.seq - y.seq)
660  const failures = [
661    ...musicians(state).filter((m) => m.state === 'failed').map((m) => `${m.name}: ${failureText(m.failure)}.`),
662    ...rosterFailures(state).map((f) => `${nameOf(state, f.agent)}: ${f.tool} ${f.target} failed${f.recoveredSeq ? `; ${nameOf(state, f.recoveredBy || f.agent)} later ran it successfully`
663      : state.musicians[f.agent]?.finished ? '; the part has ended' : '; not yet recovered'}.`),
664  ]
665  const stale = state.stale.map((s) => `${nameOf(state, s.agent)} produced ${s.products.join(', ')} from v${s.readV} of ${s.path}; ${nameOf(state, s.writer)} then wrote v${s.currentV}. ${
666    s.cleared ? `Redone from the current version by ${nameOf(state, s.clearedBy)}.` : 'Not redone.'}`)
667  const handoffs = state.handoffs.map((h) => `${nameOf(state, h.from)} → ${nameOf(state, h.to)}: ${h.path} v${h.v}${h.via === 'brief' ? ' (named in the brief)' : ''}`)
668  const ending = {
669    completed: 'it finished.', failed: 'it failed.', killed: 'it was stopped.',
670    'part ended': 'it was stopped when its part ended.',
671    'turn ended': "it was stopped when the conductor's turn ended.",
672    'session ended': 'it was still running when the session ended, so later changes it made are not recorded.',
673  }
674  const background = Object.entries(state.background).map(([task, b]) => `${nameOf(state, b.agent)} ran \`${b.command}\` in the background (task ${task}): ${
675    b.status === null ? 'still running when this was written.' : ending[b.status] ?? `it ended (${b.status}).`}`)
676  return { task: state.task, requests: state.requests, counts: counts(state), contributions, changed, conflicts, failures, stale, handoffs, background }
677}
678
679// One musician's line in every coda: the file, /orchestra coda and the pane's Coda tab.
680export function contributionText(x) {
681  const failed = x.failure ? `; ${failureText(x.failure)}` : ''
682  if (!x.reads && !x.writes) return `${x.name}: no file reads or writes recorded${failed}`
683  const notes = [
684    x.shell ? `${plural(x.shell, 'change')} by shell command${x.uncertain ? `, ${x.uncertain} uncertain because other musicians' commands or edits ran at the same time` : ''}` : null,
685    x.unchecked && x.unchecked < x.writes ? `line counts unknown for ${x.unchecked}` : null,
686    x.shared?.length ? `${plural(x.shared.length, 'shell change')} shared with ${listJoin([...new Set(x.shared)])}, credited to neither` : null,
687  ].filter(Boolean)
688  const wrote = x.artifacts.length ? `; wrote ${x.artifacts.join(', ')}` : ''
689  const lines = !x.writes ? '' : x.unchecked === x.writes ? ', line counts unknown' : `, +${x.added} −${x.removed}`
690  return `${x.name}: ${plural(x.reads, 'read')}, ${plural(x.writes, 'write')}${lines}${notes.length ? ` (${notes.join('; ')})` : ''}${wrote}${failed}`
691}
692
693// A version's hash as the pane shows it: short SHA-256, or "size/time" for a file too large to hash.
694export const hashLabel = (hash) => (String(hash).startsWith('stat:') ? 'size/time' : `sha256:${String(hash).slice(0, 12)}`)
695
696// A file's current version as the coda names it: its SHA-256, or its size when it was too large
697// for Orchestra to read and hash.
698const versionLabel = (hash) => {
699  const stat = /^stat:(\d+):/.exec(hash)
700  return stat ? `now ${stat[1]} bytes (too large to hash)` : `now sha256:${hash}`
701}
702
703// The coda's sections, the same in the coda file, /orchestra coda and the pane's Coda tab.
704export function codaSections(state, c = coda(state)) {
705  return [
706    ['Who contributed what', c.contributions.map(contributionText)],
707    ['Artifacts changed', c.changed.map((a) => `${a.path}: ${plural(a.versions, 'new version')} by ${a.authors.join(', then ')}; ${versionLabel(a.hash)}`)],
708    ['Handoffs', c.handoffs],
709    ['Conflicts', c.conflicts.map((x) => x.text)],
710    ['Failures', c.failures],
711    ['Stale reads', c.stale],
712    ['Background commands', c.background],
713  ]
714}
715
716export function codaMarkdown(state, sessionFile) {
717  const list = (items) => (items.length ? items.map((x) => `- ${x}`) : ['- none'])
718  return [
719    '# Orchestra coda',
720    '',
721    `Task: ${state.task || '(not recorded)'}`,
722    ...(state.requests.length ? [`Later requests: ${state.requests.join(' | ')}`] : []),
723    `Ledger: ${sessionFile}`,
724    `Status: ${statusLine(state)}`,
725    '',
726    ...codaSections(state).flatMap(([title, items]) => [`## ${title}`, ...list(items), '']),
727  ].join('\n')
728}
729
730// Lines added and removed between two texts, counted as a multiset of lines.
731export function lineDelta(before, after) {
732  const count = (text) => {
733    const m = new Map()
734    for (const line of String(text ?? '').split('\n')) m.set(line, (m.get(line) || 0) + 1)
735    return m
736  }
737  const a = count(before)
738  const b = count(after)
739  let added = 0
740  let removed = 0
741  for (const [line, n] of b) added += Math.max(0, n - (a.get(line) || 0))
742  for (const [line, n] of a) removed += Math.max(0, n - (b.get(line) || 0))
743  if (before === null || before === undefined) removed = 0
744  return { added, removed }
745}
746
hooks/views.js 453 lines
1// What Orchestra draws. Every function takes the element constructors the mod resolved
2// for the surface, the folded ledger state, and the pane's own view state.
3
4import { CONDUCTOR, artifactStatus, authorOf, coda, codaSections, counts, currentCall, elapsed, failureLine, hashLabel, lastCalls, liveHandoff, musicians, nameOf, partMs, plural, rollup, roster, standing, statusLine } from './ledger.js'
5import { ground, paint } from './palette.js'
6
7export const GLYPH = { resting: '·', playing: '♪', waiting: '‖', done: '✓', failed: '✕' }
8export const TABS = [['ensemble', 'Ensemble'], ['score', 'Score'], ['artifacts', 'Artifacts'], ['coda', 'Coda']]
9const STATE_TOKEN = { playing: 'ok', waiting: 'warn', done: null, failed: 'danger', resting: null }
10const SCORE_NAME_COLUMNS = 11
11const READS_SHOWN = 8
12const HELD_LINES = 14
13const BAR_EVENTS = 8
14const CALLS_SHOWN = 5
15const WRITE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
16// What a state is called where a row names it.
17const STATE_WORD = { resting: 'resting', playing: 'playing', waiting: 'waiting on you', done: 'done', failed: 'failed' }
18
19export const short = (text, n) => {
20  const s = String(text ?? '').replace(/\s+/g, ' ').trim()
21  return s.length > n ? `${s.slice(0, n - 1)}…` : s
22}
23
24const line = (el, parts) => el.Text({ wrap: 'truncate-end', children: parts })
25// Blank rows, remembered so the pane's window can drop the ones that would end a tab.
26const blanks = new WeakSet()
27const blank = (el) => {
28  const row = el.Text({ children: [' '] })
29  blanks.add(row)
30  return row
31}
32const dim = (el, text) => el.Text({ dimColor: true, children: [text] })
33const tone = (el, token, text, bold = false) => el.Text({ color: paint(token), bold, children: [text] })
34const who = (el, m) => tone(el, m.color, m.name, true)
35
36// Word-wraps text into lines of at most `cols` characters, splitting a longer word.
37function wrapLines(text, cols) {
38  const lines = []
39  let cur = ''
40  for (const word of String(text ?? '').split(/\s+/).filter(Boolean)) {
41    if (cur && cur.length + 1 + word.length <= cols) {
42      cur += ` ${word}`
43      continue
44    }
45    if (cur) lines.push(cur)
46    cur = word
47    while (cur.length > cols) {
48      lines.push(cur.slice(0, cols))
49      cur = cur.slice(cols)
50    }
51  }
52  return cur || !lines.length ? [...lines, cur] : lines
53}
54
55// A paragraph as one Text per row, every row indented, so wrapped lines keep the indent; `hang`
56// indents the rows after the first a little more, so a wrapped item does not read as a new one.
57const para = (el, text, indent, width, props = {}, hang = '') => wrapLines(text, Math.max(10, width - indent.length - hang.length))
58  .map((l, i) => el.Text({ ...props, wrap: 'truncate-end', children: [`${indent}${i ? hang : ''}${l}`] }))
59
60// Short items laid out on rows of at most `cols` characters, never split inside an item.
61const wrapItems = (items, cols) => items.reduce((rows, item) => {
62  const last = rows[rows.length - 1]
63  if (last && last.length + 2 + item.length <= cols) rows[rows.length - 1] = `${last}  ${item}`
64  else rows.push(item)
65  return rows
66}, /** @type {string[]} */ ([]))
67
68const LEGEND = ['─ rest', '┊ bar line', '○ read', '← used another\'s work', '● write', '· tool', '◆ assigned', '✓ done', '✕ failed', '‼ conflict', '⚠ stale', '? you decided']
69
70// What a musician is doing, as every row draws it: its state's glyph, the tool or word in the
71// second column, the free text, and the time. Elapsed times run to `now`, the time of the newest
72// recorded event, so they move only when an event arrives.
73export function doing(state, m, now) {
74  const st = standing(state, m)
75  const base = { state: st, glyph: GLYPH[st], token: STATE_TOKEN[st] }
76  if (st === 'done') {
77    const ms = partMs(state, m.key)
78    return { ...base, word: 'done', text: `${plural(m.measures, 'measure')} · ${plural(m.reads, 'read')} · ${plural(m.writes, 'write')}`, time: ms === null ? '' : elapsed(ms) }
79  }
80  if (st === 'failed') return { ...base, word: 'failed', text: failureLine(state, m), time: '' }
81  if (st === 'waiting') {
82    const c = state.conflicts.findLast((x) => x.agent === m.key && !x.resolved)
83    const by = c ? authorOf(state, state.artifacts[c.path]?.versions[c.current]) : ''
84    return { ...base, word: 'held', text: c ? `${c.path}: ${by} wrote v${c.current} ${c.base === null ? 'and you never read it' : `since you read v${c.base}`}` : 'waiting on you', time: '' }
85  }
86  const call = m.finished ? null : currentCall(state, m.key)
87  if (call) {
88    const seen = m.seen[call.target]
89    const from = WRITE_TOOLS.has(call.tool) && seen !== undefined ? ` from v${seen}` : ''
90    return { ...base, word: call.tool, text: `${call.target}${from}`, time: now ? elapsed(Math.max(0, now - call.ts)) : '' }
91  }
92  return { ...base, word: '', text: m.part || (m.key === CONDUCTOR ? 'Coordinating the ensemble' : m.role), time: '' }
93}
94
95// `doing` as one line: `Edit config/limits.json from v0 · 12s`, `done · 4 measures · … · 41s`,
96// `failed · <first error line>`.
97export const doingText = (d) => {
98  const what = d.state === 'done' || d.state === 'failed' ? `${d.word} · ${d.text}` : [d.word, d.text].filter(Boolean).join(' ')
99  return `${what}${d.time ? ` · ${d.time}` : ''}`
100}
101
102// The Agent row's two lines for a musician: who and in what role, then what it is doing.
103export function agentRows(state, m, now) {
104  const d = doing(state, m, now)
105  return { title: `${m.name} · ${m.role}`, detail: `└ ${d.glyph} ${doingText(d)}`, token: d.token }
106}
107
108function glyphOf(el, m, st) {
109  const g = GLYPH[st]
110  return STATE_TOKEN[st] ? tone(el, STATE_TOKEN[st], g) : el.Text({ children: [g] })
111}
112
113const rollupText = (el, state) => rollup(state).flatMap((x, i) => [i ? dim(el, ' · ') : '', x.token ? tone(el, x.token, x.text, x.bold) : el.Text({ children: [x.text] })])
114
115// Band and Ensemble rows keep the glyph, the name and the time where they are; only the free text
116// gives way, cut with `…`.
117const WORD_COLUMNS = 6
118function row(el, key, width, nameCols, m, d) {
119  return el.Box({ key, flexDirection: 'row', width, children: [
120    el.Box({ flexShrink: 0, width: 2, children: [glyphOf(el, m, d.state)] }),
121    el.Box({ flexShrink: 0, width: nameCols + 2, children: [who(el, m)] }),
122    el.Box({ flexShrink: 0, width: WORD_COLUMNS + 1, children: [d.token ? tone(el, d.token, d.word) : el.Text({ children: [d.word] })] }),
123    el.Box({ flexShrink: 1, children: [el.Text({ wrap: 'truncate-end', dimColor: d.state === 'resting', children: [d.text] })] }),
124    d.time ? el.Box({ flexShrink: 0, children: [dim(el, ` · ${d.time}`)] }) : '',
125  ].filter(Boolean) })
126}
127
128// The band: the rollup, then one row per musician not yet done, in the order parts were assigned.
129// Rows past `maxRows` fold into one `… N more · /orchestra` row, so the band never scrolls.
130export function band(el, state, width, now, maxRows = Infinity) {
131  const live = musicians(state).filter((m) => standing(state, m) !== 'done')
132  const title = [tone(el, 'conductor', '𝄐 Orchestra', true), '  ', ...rollupText(el, state)]
133  // With one row (a small terminal while Claude Code lists its agents) the fold joins line 1, so the
134  // rollup is still what shows.
135  if (maxRows < 2) return el.Box({ flexDirection: 'column', width, children: [line(el, [...title, live.length ? dim(el, ` · … ${live.length} more · /orchestra`) : ''])] })
136  const room = maxRows - 1
137  const shown = live.length > room ? live.slice(0, Math.max(0, room - 1)) : live
138  const nameCols = Math.max(0, ...shown.map((m) => m.name.length))
139  return el.Box({ flexDirection: 'column', width, children: [
140    line(el, title),
141    ...shown.map((m) => row(el, `band-${m.key}`, width, nameCols, m, doing(state, m, now))),
142    ...(shown.length < live.length ? [dim(el, `  … ${live.length - shown.length} more · /orchestra`)] : []),
143  ] })
144}
145
146// The pane's last row: the keys the focused tab answers to.
147const KEY_HINTS = {
148  ensemble: '1-4 tabs · tab select · enter details · ↑↓ scroll · esc close',
149  score: '1-4 tabs · ↑↓ scroll · esc close',
150  artifacts: '1-4 tabs · tab select · enter details · ↑↓ scroll · esc close',
151  coda: '1-4 tabs · ↑↓ scroll · esc close',
152}
153// While the tab scrolls, where the window is goes first on the same row, so a pane only a few rows
154// tall (inline in a short terminal) still shows its keys.
155export const keyHints = (el, tab, where = '') => dim(el, `${where ? `${where} · ` : ''}${KEY_HINTS[tab] ?? KEY_HINTS.ensemble}`)
156
157// The line logged when the conductor's turn ends: the same counts as the coda file.
158export function outcomeLine(state, ms) {
159  const c = coda(state)
160  return [
161    '𝄐 Coda',
162    plural(musicians(state).length, 'musician'),
163    plural(c.changed.length, 'file'),
164    plural(c.conflicts.length, 'conflict'),
165    `${c.counts.failed} failed`,
166    elapsed(ms),
167    '/orchestra coda',
168  ].join(' · ')
169}
170
171// The tab bar and the blank under it; the key hints take the last row.
172const HEADER_ROWS = 2
173const FOOTER_ROWS = 1
174
175/** @param {'dock'|'inline'} [placement] */
176export function pane(el, state, view, width, bodyRows, placement = 'dock') {
177  const render = { ensemble, score, artifacts, coda: codaTab }[view.tab]
178  const body = render(el, state, view, width)
179  // The body sits on the ground its colours were measured on, not on Claude Code's grey pane fill.
180  const { rows, where } = paneWindow(el, view, body, bodyRows)
181  // While the tab scrolls, the tree's last row is the hidden one (see paneWindow), so the key hints
182  // go just above it and stay the last row shown.
183  const hidden = view.maxOffset ? [blank(el)] : []
184  return el.Box({ flexDirection: 'column', width, backgroundColor: ground(placement), children: [tabBar(el, view), blank(el), ...rows, keyHints(el, view.tab, where), ...hidden] })
185}
186
187const tabBar = (el, view) => el.Box({
188  flexDirection: 'row', columnGap: 2,
189  children: TABS.map(([id, label], i) => el.Box({ flexDirection: 'row', children: [
190    view.tab === id ? tone(el, 'conductor', '▸', true) : el.Text({ children: [' '] }),
191    el.Button({ key: `tab-${id}`, label, hotkey: String(i + 1), plain: true, dimColor: view.tab !== id, onPress: () => view.setTab(id) }),
192  ] })),
193})
194
195// The pane draws its own window under the tab bar, so the tabs never scroll away; every
196// row of a tab is one element, so a slice of them is exactly the rows shown. The tree is
197// one row taller than the window (pane() adds that row last): the engine raises `ui.scroll`
198// for the arrows only while it has a row to scroll, and the pane's hook keeps it from moving,
199// so that row never shows.
200// Without `bodyRows` the whole tab is drawn and the engine scrolls it.
201function paneWindow(el, view, rows, bodyRows) {
202  let end = rows.length
203  while (end > 1 && blanks.has(rows[end - 1])) end -= 1
204  const body = rows.slice(0, end)
205  if (view.windowTab !== view.tab) Object.assign(view, { windowTab: view.tab, offset: 0 })
206  // Where the window is gets its own row, unless the pane is too short for that and a row of the
207  // tab (inline in a short terminal): then it goes on the key-hint row.
208  const tight = Boolean(bodyRows) && bodyRows - HEADER_ROWS - FOOTER_ROWS < 3
209  const shown = Math.max(1, (bodyRows || 0) - HEADER_ROWS - FOOTER_ROWS - (tight ? 0 : 1))
210  view.maxOffset = bodyRows && body.length > shown + 1 ? body.length - shown : 0
211  view.page = shown
212  view.offset = Math.min(view.offset || 0, view.maxOffset)
213  if (!view.maxOffset) return { rows: body, where: '' }
214  const below = body.length - view.offset - shown
215  const where = [view.offset ? `↑ ${view.offset} more above` : null, below ? `↓ ${below} more below` : 'end'].filter(Boolean).join(' · ')
216  const visible = body.slice(view.offset, view.offset + shown)
217  return tight ? { rows: visible, where } : { rows: [...visible, dim(el, where)], where: '' }
218}
219
220// Moves the pane's window for a `ui.scroll` hook on the pane. The engine sizes Home and End
221// (`contentRows`) and the page keys (`bodyRows`) by the tree it was given, not by the tab.
222/** @param {{ by: number, bodyRows: number, contentRows: number }} e the `ui.scroll` input */
223export function scrollPane(view, e) {
224  if (!e.by) return false
225  const rows = Math.abs(e.by) >= e.contentRows ? Infinity : Math.abs(e.by) === e.bodyRows ? view.page : Math.abs(e.by)
226  const next = Math.min(Math.max(0, (view.offset || 0) + Math.sign(e.by) * rows), view.maxOffset || 0)
227  if (next === (view.offset || 0)) return false
228  view.offset = next
229  return true
230}
231
232const detailsButton = (el, view, type, id) => el.Button({
233  key: `pick-${type}-${id}`, plain: true,
234  label: view.selected?.type === type && view.selected?.id === id ? '▾ details' : '▸ details',
235  onPress: () => view.select(type, id),
236})
237
238// The Ensemble tab: the rollup, the newest handoff, then every musician, conductor first, as a
239// two-line row with its counts; Enter on a name opens its details.
240function ensemble(el, state, view, width) {
241  return [line(el, rollupText(el, state)), ...handoffLine(el, state, width), blank(el), ...roster(state).flatMap((key) => seat(el, state, view, key, width))]
242}
243
244// The newest handoff, from the musician who wrote the version to the one who took it.
245function handoffLine(el, state, width) {
246  const h = liveHandoff(state)
247  if (!h) return []
248  const from = state.musicians[h.from]
249  const to = state.musicians[h.to]
250  return [line(el, [
251    from ? tone(el, from.color, from.name, true) : dim(el, nameOf(state, h.from)),
252    dim(el, ' → '),
253    to ? tone(el, to.color, to.name, true) : el.Text({ children: [nameOf(state, h.to)] }),
254    dim(el, ` · ${short(`${h.path} v${h.v}`, Math.max(8, width - 30))}`),
255  ])]
256}
257
258function seat(el, state, view, key, width) {
259  const m = state.musicians[key]
260  const d = doing(state, m, view.now)
261  const stale = state.stale.some((s) => s.agent === key && !s.cleared)
262  const open = view.selected?.type === 'musician' && view.selected.id === key
263  const done = d.state === 'done' || d.state === 'failed'
264  const what = done ? `${d.word} · ${d.text}` : [d.word, d.text].filter(Boolean).join(' ')
265  return [
266    // Glyph, name and state keep their width; only the role gives way.
267    el.Box({ key: `seat-${key}`, flexDirection: 'row', columnGap: 1, width, children: [
268      el.Box({ flexShrink: 0, children: [glyphOf(el, m, d.state)] }),
269      el.Box({ flexShrink: 0, children: [el.Button({ key: `pick-musician-${key}`, plain: true, onPress: () => view.select('musician', key), children: [who(el, m)] })] }),
270      el.Box({ flexShrink: 1, children: [el.Text({ dimColor: true, wrap: 'truncate-end', children: [` ${m.role}`] })] }),
271      el.Box({ flexShrink: 0, children: [d.token ? tone(el, d.token, `· ${STATE_WORD[d.state]}`) : dim(el, `· ${STATE_WORD[d.state]}`)] }),
272    ] }),
273    el.Box({ key: `seat-doing-${key}`, flexDirection: 'row', width, children: [
274      el.Box({ flexShrink: 1, children: [el.Text({ wrap: 'truncate-end', dimColor: true, children: [`  └ ${what}`] })] }),
275      d.time ? el.Box({ flexShrink: 0, children: [dim(el, ` · ${d.time}`)] }) : '',
276    ].filter(Boolean) }),
277    key === CONDUCTOR || d.state === 'done' ? null : line(el, [`  ${plural(m.measures, 'measure')} · ${plural(m.reads, 'read')} · ${plural(m.writes, 'write')}`, stale ? tone(el, 'warn', '   ⚠ stale read') : '']),
278    key !== CONDUCTOR && d.state === 'done' && stale ? line(el, [tone(el, 'warn', '  ⚠ stale read')]) : null,
279    ...(open ? musicianDetail(el, state, key, width) : []),
280    blank(el),
281  ].filter(Boolean)
282}
283
284// A musician's details: its part, every version it has seen, its reads and writes with versions,
285// its last calls with their times, its answer, and where its full transcript is.
286function musicianDetail(el, state, key, width) {
287  const m = state.musicians[key]
288  const seen = Object.entries(m.seen).map(([p, v]) => {
289    const now = state.artifacts[p].versions.length - 1
290    return line(el, [`      ${short(p, width - 20)} v${v}`, v < now ? tone(el, 'warn', ` (now v${now})`) : ''])
291  })
292  const touched = Object.values(state.artifacts).flatMap((a) => [
293    ...a.reads.filter((r) => r.agent === key).map((r) => ({ seq: r.seq, text: `read ${a.path} v${r.v}` })),
294    ...a.versions.filter((v) => v.agent === key).map((v) => ({ seq: v.seq, text: `wrote ${a.path} v${v.v}${v.base !== null && v.base !== undefined ? ` from v${v.base}` : ''}` })),
295  ]).sort((x, y) => x.seq - y.seq).map((x) => dim(el, `      ${short(x.text, width - 8)}`))
296  const calls = lastCalls(state, key, CALLS_SHOWN).map((c) => line(el, [
297    `      ${short(`${c.tool}${c.target ? ` ${c.target}` : ''}`, width - 26)}`,
298    c.ok === null ? dim(el, ' · running') : c.ok ? dim(el, ` · ${elapsed(c.ms ?? 0)} ✓`) : tone(el, 'danger', ` · ${elapsed(c.ms ?? 0)} ✕`),
299  ]))
300  return [
301    ...para(el, `Part: ${short(m.prompt || m.part || '(none recorded)', 300)}`, '    ', width, { dimColor: true }),
302    el.Text({ children: ['    Versions seen:'] }),
303    ...(seen.length ? seen : [dim(el, '      none yet')]),
304    el.Text({ children: ['    Reads and writes:'] }),
305    ...(touched.length ? touched : [dim(el, '      none yet')]),
306    el.Text({ children: ['    Last calls:'] }),
307    ...(calls.length ? calls : [dim(el, '      none yet')]),
308    ...(m.answer ? para(el, `Answer: ${short(m.answer, 400)}`, '    ', width, { dimColor: true }) : []),
309    dim(el, "    full transcript: ← in Claude Code's agent view"),
310  ]
311}
312
313// One staff per musician, the newest events on the right; glyphs coloured by meaning.
314function score(el, state, view, width) {
315  const cols = Math.max(10, width - SCORE_NAME_COLUMNS - 2)
316  const events = state.events.slice(-cols)
317  const conflictSeqs = new Set(state.conflicts.map((c) => c.seq))
318  const staleSeqs = new Set(state.stale.map((s) => `${s.seq}:${s.agent}`))
319  const handoffIn = new Set(state.handoffs.map((h) => `${h.seq}:${h.to}`))
320  const glyph = (e, key, color) => {
321    if (staleSeqs.has(`${e.seq}:${key}`)) return ['⚠', 'warn']
322    if (e.agent === key) {
323      if (e.type === 'write.attempt' && conflictSeqs.has(e.seq)) return ['‼', 'danger']
324      if (e.type === 'artifact.read') return [handoffIn.has(`${e.seq}:${key}`) ? '←' : '○', color]
325      if (e.type === 'part.assigned' && handoffIn.has(`${e.seq}:${key}`)) return ['←', color]
326      const g = { 'tool.call': ['·', color], 'artifact.write': ['●', color], 'part.assigned': ['◆', color], 'part.done': ['✓', 'ok'], 'part.failed': ['✕', 'danger'] }[e.type]
327      if (g) return g
328      if (e.type === 'tool.result' && !e.ok && !e.sentBack) return ['✕', 'danger']
329      return rest(e)
330    }
331    if (key === CONDUCTOR) {
332      if (e.type === 'part.assigned') return ['◆', color]
333      if (e.type === 'conflict.resolved') return ['?', 'warn']
334      if (e.type === 'coda') return ['𝄐', color]
335    }
336    return rest(e)
337  }
338  // An event that is not this musician's is a rest on its staff line, with a bar line every
339  // BAR_EVENTS events of the ledger, so the lanes read as staves of measures.
340  const rest = (e) => [e.seq % BAR_EVENTS === 0 ? '┊' : '─', 'staff']
341  const staff = (key, color) => {
342    const runs = []
343    for (const e of events) {
344      const [g, token] = glyph(e, key, color)
345      const last = runs[runs.length - 1]
346      if (last && last.token === token) last.text += g
347      else runs.push({ token, text: g })
348    }
349    return runs.map((r, i) => (r.token === 'staff' ? el.Text({ key: `r${i}`, dimColor: true, children: [r.text] })
350      : r.token ? el.Text({ key: `r${i}`, color: paint(r.token), children: [r.text] }) : el.Text({ key: `r${i}`, children: [r.text] })))
351  }
352  const lanes = roster(state).map((key) => {
353    const m = state.musicians[key]
354    return el.Box({ key: `lane-${key}`, flexDirection: 'row', children: [
355      el.Box({ width: SCORE_NAME_COLUMNS, children: [el.Text({ color: paint(m.color), wrap: 'truncate-end', children: [m.name] })] }),
356      el.Text({ wrap: 'truncate-end', children: staff(key, m.color) }),
357    ] })
358  })
359  const first = events.length ? events[0].seq : 0
360  const lastSeq = events.length ? events[events.length - 1].seq : 0
361  return [
362    dim(el, `Events ${first}–${lastSeq} of the ledger, newest on the right`),
363    ...lanes,
364    blank(el),
365    ...wrapItems(LEGEND, Math.max(10, width)).map((l) => dim(el, l)),
366  ]
367}
368
369const lastSeq = (a) => Math.max(0, ...a.versions.map((v) => v.seq), ...a.reads.map((r) => r.seq))
370
371function artifacts(el, state, view, width) {
372  const list = Object.values(state.artifacts).sort((a, b) => lastSeq(b) - lastSeq(a))
373  if (!list.length) return [dim(el, 'No artifacts touched yet.')]
374  return list.flatMap((a) => {
375    const status = artifactStatus(state, a.path)
376    const authors = a.versions.filter((v) => v.agent !== 'repo').map((v) => nameOf(state, v.agent))
377    const open = view.selected?.type === 'artifact' && view.selected.id === a.path
378    return [
379      el.Box({ key: `art-${a.path}`, flexDirection: 'row', columnGap: 1, children: [
380        el.Text({ wrap: 'truncate-end', children: [short(a.path, width - 26)] }),
381        status === 'conflict' ? tone(el, 'danger', 'conflict', true) : status === 'stale' ? tone(el, 'warn', 'stale') : dim(el, `v${a.versions.length - 1}`),
382        detailsButton(el, view, 'artifact', a.path),
383      ] }),
384      line(el, [dim(el, authors.length ? `  written by ${authors.join(' → ')} · ${plural(a.reads.length, 'read')}` : `  read only · ${plural(a.reads.length, 'read')}`)]),
385      ...(open ? artifactDetail(el, state, view, a.path, width) : []),
386      blank(el),
387    ]
388  })
389}
390
391function artifactDetail(el, state, view, path, width) {
392  const a = state.artifacts[path]
393  const versions = a.versions.map((v) => line(el, [
394    `    v${v.v} ${v.agent === 'repo' ? 'as first seen' : `by ${nameOf(state, v.agent)}`}`,
395    v.base !== null && v.base !== undefined ? ` from v${v.base}` : '',
396    v.agent === 'repo' || v.agent === 'outside' ? '' : v.unchecked || v.added === undefined ? ' lines unknown' : ` +${v.added} −${v.removed}`,
397    v.via === 'bash' ? dim(el, v.uncertain ? ' via Bash, attribution uncertain' : ' via Bash') : '',
398    dim(el, `  ${hashLabel(v.hash)}`),
399    v.base !== null && v.base !== undefined && v.base < v.v - 1 ? tone(el, 'danger', ` skipped v${v.v - 1}`) : '',
400  ]))
401  const reads = a.reads.slice(-READS_SHOWN).map((r) => dim(el, `    ${nameOf(state, r.agent)} read v${r.v} at event ${r.seq}`))
402  const conflicts = state.conflicts.filter((c) => c.path === path).map((c) => line(el, [
403    c.resolved ? tone(el, 'ok', '    ✓ ') : tone(el, 'danger', '    ‼ '),
404    `${nameOf(state, c.agent)} wrote from v${c.base ?? '-'} over ${nameOf(state, c.against)}'s v${c.current}${c.resolved ? ` · ${c.choice}` : ' · open'}`,
405  ]))
406  const held = view.held && view.held.path === path ? [blank(el), ...heldWrite(el, view.held, width)] : []
407  return [
408    el.Text({ children: ['    Versions:'] }), ...versions,
409    el.Text({ children: ['    Reads:'] }), ...(reads.length ? reads : [dim(el, '      none')]),
410    ...(conflicts.length ? [el.Text({ children: ['    Conflicts:'] }), ...conflicts] : []),
411    ...held,
412  ]
413}
414
415// Shown while a write is held: the file as it is now, beside what the writer is about to do.
416// `lines` caps each side; above the question dialog Claude Code allows at most 12 rows.
417// Every row is cut to one line, so the rows drawn are exactly the rows counted.
418export function heldWrite(el, held, width, lines = HELD_LINES) {
419  const clip = (items) => items.filter((l) => l.trim()).slice(0, lines)
420  // Cut to one row, keeping the indentation the file's own lines have.
421  const cut = (text, n) => {
422    const t = String(text).replace(/\t/g, '  ')
423    return t.length > n ? `${t.slice(0, Math.max(1, n - 1))}…` : t
424  }
425  const row = (key, text, props = {}) => el.Text({ key, ...props, wrap: 'truncate-end', children: [cut(text, width - 2)] })
426  const sinceSeen = held.changed !== null
427  const theirs = sinceSeen ? held.changed : String(held.currentText ?? '').split('\n')
428  const seen = held.base === null ? `${held.writer} never read it` : `${held.writer} saw v${held.base}`
429  return [
430    row('held', `Held write by ${held.writer} (${held.tool}) on ${held.path}`, { color: paint('warn'), bold: true }),
431    row('since', sinceSeen ? `v${held.current} by ${held.against}, added since ${seen}:` : `v${held.current} by ${held.against}:`, { dimColor: true }),
432    ...clip(theirs.length ? theirs : ['(no lines added; lines were only removed)']).map((l, i) => row(`cur${i}`, `  ${sinceSeen ? '+ ' : ''}${l}`)),
433    row('wants', `${held.writer} wants to ${held.tool === 'Write' ? 'write' : 'change'}:`, { dimColor: true }),
434    ...clip(String(held.proposed ?? '').split('\n')).map((l, i) => row(`new${i}`, `  ${l}`, { color: paint('warn') })),
435  ]
436}
437
438function codaTab(el, state, view, width) {
439  const c = coda(state)
440  const section = (title, items) => [
441    el.Text({ bold: true, children: [title] }),
442    ...(items.length ? items.flatMap((t) => para(el, `• ${t}`, '  ', width, {}, '  ')) : [dim(el, '  • none')]),
443  ]
444  return [
445    ...para(el, `Task: ${short(c.task || 'not recorded', width * 3)}`, '', width),
446    ...(c.requests?.length ? para(el, `Later requests: ${short(c.requests.join(' | '), width * 3)}`, '', width) : []),
447    ...para(el, `Status: ${statusLine(state)}`, '', width),
448    ...para(el, view.codaPath ? `Written to ${view.codaPath}` : 'The coda file is written when the conductor\'s turn ends.', '', width, { dimColor: true }),
449    blank(el),
450    ...codaSections(state, c).flatMap(([title, items]) => section(title, items)),
451  ]
452}
453
hooks/palette.js 112 lines
1// Colour tokens (PRD §6.4). The band, status line, spinner and toasts paint no background: they sit
2// on the terminal's own, and only the foreground is coloured. The pane is painted `ground()`, the
3// background the tokens were measured on, over Claude Code's grey pane fill. Each token has a value for
4// a dark terminal, measured against pure black, and one for a light terminal, measured against white;
5// both stay at least 4.5:1 (MIN_CONTRAST). A 256-colour terminal gets the xterm-256 cube entry nearest
6// the dark value, so what it draws is what was measured. Anything less, an ANSI theme, or a theme
7// Orchestra cannot read or name gets a Claude Code theme key (`ansi` below): the engine draws each
8// key in the person's own theme, which under an ANSI theme is a 16-colour code the terminal maps
9// through its palette (a colour name would be drawn as 24-bit). The keys chosen measure at least
10// 4.5:1 on the dark and light presets' `inverseText` (black, white), the ground an unknown theme's
11// docked pane is painted (see ground()).
12
13export const MIN_CONTRAST = 4.5
14export const BLACK = '#000000'
15export const WHITE = '#ffffff'
16
17export const TOKENS = {
18  conductor: { dark: '#c3a6ff', light: '#6b3fd4', ansi: 'planMode' },
19  violin: { dark: '#7eaaff', light: '#2457d6', ansi: 'remember' },
20  trumpet: { dark: '#f2b950', light: '#8a5a00', ansi: 'warning' },
21  flute: { dark: '#5fd3a8', light: '#1d7a4f', ansi: 'success' },
22  timpani: { dark: '#ff8c6e', light: '#b4441e', ansi: 'diffRemovedWord' },
23  cello: { dark: '#d78cff', light: '#8a2fb4', ansi: 'merged' },
24  guest: { dark: '#a8b3c7', light: '#4f5b70', ansi: 'inactive' },
25  ok: { dark: '#6bdc9a', light: '#1d7a4f', ansi: 'success' },
26  warn: { dark: '#ffc65c', light: '#8a5a00', ansi: 'warning' },
27  danger: { dark: '#ff6b6b', light: '#b42318', ansi: 'error' },
28}
29
30/** @param {string} hex @returns {number[]} */
31const rgb = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16))
32/** @param {number[]} c */
33const toHex = (c) => `#${c.map((x) => x.toString(16).padStart(2, '0')).join('')}`
34
35// WCAG 2 relative luminance and contrast ratio.
36const WEIGHTS = [0.2126, 0.7152, 0.0722]
37/** @param {string} hex */
38const luminance = (hex) => rgb(hex).reduce((sum, x, i) => {
39  const s = x / 255
40  return sum + (WEIGHTS[i] ?? 0) * (s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4)
41}, 0)
42/** @param {string} a @param {string} b */
43export function contrast(a, b) {
44  const la = luminance(a)
45  const lb = luminance(b)
46  return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05)
47}
48
49// The xterm-256 colour cube nearest a hex colour. Claude Code's renderer turns a hex into a cube
50// index by rounding each channel to sixths (round(v / 51)), not to the cube's own levels, so the
51// colour it would pick for the dark value is not the nearest one. `send` is built from k × 51 per
52// channel, which that rounding maps to exactly level k; `shown` is what the terminal then draws
53// for `index`, and is the colour the contrast is measured on.
54const LEVELS = [0, 95, 135, 175, 215, 255]
55/** @param {string} hex */
56export function xterm256(hex) {
57  const k = rgb(hex).map((v) => LEVELS.reduce((best, l, i) => (Math.abs(l - v) < Math.abs((LEVELS[best] ?? 0) - v) ? i : best), 0))
58  const [r = 0, g = 0, b = 0] = k
59  return { index: 16 + 36 * r + 6 * g + b, shown: toHex(k.map((i) => LEVELS[i] ?? 0)), send: toHex(k.map((i) => i * 51)) }
60}
61/** The cube index the renderer picks for a hex: what a 256-colour terminal is sent. @param {string} hex */
62export const rendererIndex = (hex) => {
63  const [r = 0, g = 0, b = 0] = rgb(hex).map((v) => Math.round(v / 51))
64  return 16 + 36 * r + 6 * g + b
65}
66
67export const XTERM = Object.fromEntries(Object.entries(TOKENS).map(([k, t]) => [k, xterm256(t.dark)]))
68
69let mode = 'dark'
70
71// 'dark', 'light', '256', 'ansi' or 'unknown'.
72export function setColorMode(next) {
73  mode = next
74}
75
76export const colorMode = () => mode
77
78// The pane's ground. Claude Code fills a docked pane with its own grey (xterm 235, `#262626`; the
79// theme's composerSidebarBackground, which a mod cannot clear),
80// which differs from the terminal's background beside it and lowers every token's contrast. The
81// pane body is painted the ground its tokens were measured on instead: black for a dark or
82// 256-colour terminal, white for a light one. With ANSI names the terminal maps colours through
83// its own palette and no hex is right, so the engine's fill is left alone. With a theme Orchestra
84// cannot name (`auto`, a custom theme, a failed read) a docked pane is painted the theme key
85// `inverseText`, which Claude Code resolves in the person's own theme: black under a dark one, white
86// under a light one, the same ground as above, so its grey fill does not show. An inline pane has
87// no fill, so there nothing is painted.
88export const THEME_GROUND = 'inverseText'
89/** @param {'dock'|'inline'|undefined} placement */
90export function ground(placement = 'dock') {
91  if (mode === 'ansi') return undefined
92  if (mode === 'unknown') return placement === 'dock' ? THEME_GROUND : undefined
93  return mode === 'light' ? WHITE : BLACK
94}
95
96export function paint(token) {
97  const key = TOKENS[token] ? token : 'guest'
98  if (mode === '256') return XTERM[key]?.send ?? TOKENS[key].dark
99  const t = TOKENS[key]
100  return mode === 'ansi' || mode === 'unknown' ? t.ansi : t[mode] || t.dark
101}
102
103// Claude Code's theme names include "dark", "light", "light-daltonized", "dark-ansi" and so on.
104// A theme that asks for ANSI, or a terminal with neither truecolor nor 256 colours, gets ANSI names.
105export function modeFor(theme, colorterm, term = '') {
106  const name = String(theme || '')
107  if (name.includes('ansi')) return 'ansi'
108  if (!name.startsWith('dark') && !name.startsWith('light')) return 'unknown'
109  if (!/truecolor|24bit/i.test(String(colorterm || ''))) return /256/.test(String(term || '')) && !name.startsWith('light') ? '256' : 'ansi'
110  return name.startsWith('light') ? 'light' : 'dark'
111}
112