Full-SDLC Claude Code plugin — plan → implement → QA → ship → CI → release, with root-cause debugging, incident response, and dependency care. Hook-enforced…

<img src=".github/images/orc-mark.svg" alt="orc" width="140" />
<h1 align="center">orc</h1>
<strong>"Zug zug."</strong> · <em>Let the orcs do the work.</em>
The senior-developer workflow as a Claude Code plugin: <em>plan → implement → QA → ship → CI → release</em>, with guardrails that keep it off <code>main</code>, out of your git attribution, and on your own machine.
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-2ea043.svg" alt="License: MIT"></a> <img src="https://img.shields.io/github/v/tag/HigorAlves/orc?filter=orc--v*&label=plugin&color=2ea043" alt="plugin version"> <img src="https://img.shields.io/badge/runs-100%25%20local-2ea043.svg" alt="runs 100% local"> <img src="https://img.shields.io/badge/telemetry-none-2ea043.svg" alt="no telemetry"> <img src="https://img.shields.io/badge/Claude%20Code-plugin-D97757.svg" alt="Claude Code plugin">
<a href="./docs/install.md"><strong>Install</strong></a> · <a href="./docs/commands.md"><strong>Commands</strong></a> · <a href="./docs/examples/README.md"><strong>Examples</strong></a> · <a href="./docs/safety.md"><strong>Is it safe?</strong></a> · <a href="./docs/README.md"><strong>All docs</strong></a>
orc is a full-SDLC workflow plugin for Claude Code: 88 curated skills, 30 composite slash commands, 14 specialist subagents, and 10 hook scripts. The hooks enforce the discipline the model would otherwise talk itself out of: no commits to main, no AI-attribution trailers, destructive git gated, dependencies pre-flighted, the rules injected at every session start. One command, /orc:flow, drives a feature from "I want X" to "PR merged", and /orc:ci, /orc:release, /orc:deps and /orc:incident cover what happens after.
It exists for one reason: every time a senior developer sits down, they already know how the next hour goes. Write the plan, watch the test fail, fix the cause, verify with evidence, ship the PR. orc encodes that loop.
curl -fsSL https://raw.githubusercontent.com/HigorAlves/orc/main/cli/install.sh | sh # 1. the orc CLI
orc doctor --fix # 2. runtime tools
orc install # 3. enable the plugin
Restart Claude Code, type /orc:, and the palette fills. Pin a version with orc install --ref orc--v0.27.0, or skip the CLI with /plugin marketplace add HigorAlves/orc. Checkpoints, requirements and the marketplace-only path: docs/install.md.
flowchart LR
plan["/orc:plan"] --> start["/orc:start"] --> impl["implement"] --> qa["/orc:qa"] --> ship["/orc:ship"] --> ci["/orc:ci"] --> cleanup["/orc:cleanup"]
cleanup -.->|"interrupted? /orc:resume"| plan
Run the steps yourself, or let /orc:flow run them with a gate at every phase and orc-implementer writing the code slice by slice. /orc:retro closes the loop by turning a session's friction into environment changes. The full catalog, the agents behind it and the skill library: docs/commands.md. Nineteen scenarios walked end to end: docs/examples.
ORC_FACTORY=1, orc runs as a stage worker for a controller such as Hardness: no AskUserQuestion, typed result.json, outward actions queued for approval. Stage packs, orc-stage and the contract: ADR 0009.Yes, and every claim is verifiable in this repo in minutes. No backend, no telemetry; network activity is GitHub for releases and the MCP servers you add. Every guardrail is a short shell script that Claude Code runs as a real hook, and the guard hooks fail closed. The eight iron rules, the guardrail table and the FAQ: docs/safety.md.
| Page | What it answers |
|---|---|
| docs/README.md | The index: start, use, operate, contribute, decide |
| docs/install.md | Zero to a verified setup, with checkpoints |
| docs/commands.md | Every command, agent and skill, and the CLI |
| docs/configuration.md | Settings, environment variables, the statusline |
| docs/architecture.md | Why the layout is what it is; hooks, state, phase modules |
| docs/contributing.md | Adding a surface under the authoring standard; releasing |
Decisions are recorded in docs/adr, terms in GLOSSARY.md, what is in and out of scope in SCOPE.md, and every release in CHANGELOG.md.
MIT. See LICENSE.
hooks/mod/register.ts 1354 lines1// The orc mod: in-process event hooks layered on top of orc's bash settings
2// hooks, which stay the safety floor. Nothing here replaces a guard — when
3// mods can't load (Claude Code < 2.1.287, --safe-mode, disableAllHooks, an
4// org policy) or `mod_enabled` is false, orc behaves exactly as without it.
5import type { EngineInterface, On, PluginOptions, RenderSurface } from 'claude-code'
6import { statusInfo } from './api'
7import { COMPANIONS_NONE, companionsOf, type Companions } from './companions'
8import { bandLine, pickBand, type BandRow } from './band'
9import { ciAlt, ciSvg, ciText } from './band/ci'
10import { fitSvg, px } from './draw/svg'
11import { classify } from './guard/classify'
12import { measurePlan, summarize, type GuardSummary } from './guard/measure'
13import { guardSvg } from './guard/svg'
14import { guardText } from './guard/text'
15import { isRich } from './draw/surface'
16import { LEASE_MS, POLL_MS, SETTLED_MS, alertFor, mayPoll, signature, statusLine, summarizeChecks, type CiRecord } from './ci'
17import {
18 EMPTY, contextChipSvg, currentSlice, isDone, cutDiff, diffSlice, digestOf, hintWithContext, parseDecisions, parseMeter, parseReport, parseSession, parseSize, parseSlices, parseUsage, plumbingLine, policyOf, profileOf, spinnerSuffix, summaryText, type SectionId, type Snapshot,
19} from './cockpit'
20import { parseFeatures, type Features } from './config'
21import { gateBadge } from './gates'
22import { LEDGER_INITIAL, dropAgent, finishAgent, recordStep, setStep, tagAgent } from './ledger'
23import { PANE, drawPane, type Els } from './pane'
24import { MAX_PROBED, countDependents, parseAffected, parseNames } from './radius/model'
25import { modelFor, parseProfile, type Profile } from './profiles'
26import { costOf } from './prices'
27import { agentRows, progressModel } from './progress/model'
28import { TOUCHED_INITIAL, applyNumstat, markCommitted, parseNumstat, relPath, touch, touchedRows, type TouchKind } from './touched/model'
29import { progressText } from './progress/text'
30import { progressAlt, progressSvg } from './progress/svg'
31import { COLD_MIN_TOKENS, cacheState, coldToast, isColdRewrite, parseDuration, pingEvery, pingGone, type CacheView } from './cache/model'
32import { cacheSvg } from './cache/svg'
33import { cacheAlt, cacheText } from './cache/text'
34import { openPlan, parseThumbs, pixelTerminal } from './qa/model'
35import { REPLAY_INITIAL, recordEdit, replayView, type ReplayState } from './replay/model'
36import { cleanRule, similarity } from './retro/clean'
37import { mayBeCorrection } from './retro/detect'
38import { HAIKU, RETRO_SYSTEM, parseRetro, retroPrompt, rulesSection, savedRules, wrap } from './retro/prompt'
39import { mergeCandidate, renderRules, spliceRules, type CandidateFile } from './retro/store'
40import { retroSvg } from './retro/svg'
41import { retroAlt, retroButtons, retroText, type RetroActions } from './retro/text'
42import { budgetCreep, outsideSlice, repeatedFailure, type SentinelNote } from './sentinel/checks'
43import { DIFF_CAP, SENTINEL_SYSTEM, parseSentinel, sentinelPrompt, type SentinelSlice } from './sentinel/prompt'
44import { sentinelAlt, sentinelSvg } from './sentinel/svg'
45import { sentinelText, type SentinelActions } from './sentinel/text'
46import { replayText } from './replay/text'
47import { replayAlt, replaySvg } from './replay/svg'
48import type { SentinelCard } from './state'
49import { DETAILS_INITIAL, LIVE_INITIAL, RADIUS_INITIAL, SECTIONS_INITIAL, ciBox, askBox, guardBox, isOrcStateWrite, latestReplayView, retroBox, sentinelBox, stepReplay, warmBox } from './state'
50
51// State refs: literals in this file, as the engine's scan requires.
52const SNAPSHOT_REF = { plugin: 'orc', key: 'snapshot' } as const
53const SECTIONS_REF = { plugin: 'orc', key: 'sections' } as const
54const LIVE_REF = { plugin: 'orc', key: 'live' } as const
55const DETAILS_REF = { plugin: 'orc', key: 'details' } as const
56const LEDGER_REF = { plugin: 'orc', key: 'ledger' } as const
57const TOUCHED_REF = { plugin: 'orc', key: 'touched' } as const
58const RADIUS_REF = { plugin: 'orc', key: 'radius' } as const
59const REPLAY_REF = { plugin: 'orc', key: 'replay' } as const
60const REPLAY_PANE = 'orc-replay'
61
62// Hooks run in parallel, so a get -> set on the ledger or the touched list loses updates. Every
63// read-modify-write goes through one promise chain per key. A write is only visible to other hooks
64// once its own hook returns, so the chain also keeps the latest value in module memory and reads
65// that (state.get only seeds it, after a reload or a new session).
66const chains: Record<'ledger' | 'touched', Promise<unknown>> = { ledger: Promise.resolve(), touched: Promise.resolve() }
67function in_chain<T>(key: 'ledger' | 'touched', job: () => Promise<T>): Promise<T> {
68 const run = chains[key].then(job)
69 chains[key] = run.catch(() => undefined)
70 return run
71}
72type Ledger = typeof LEDGER_INITIAL
73type TouchedList = typeof TOUCHED_INITIAL
74// `fn` returns the same object for "no change" (nothing is written then).
75const latest: { ledger: Ledger | null; touched: TouchedList | null } = { ledger: null, touched: null }
76function update_ledger($: EngineInterface, fn: (cur: Ledger) => Ledger): Promise<void> {
77 return in_chain('ledger', async () => {
78 const cur = latest.ledger ?? (await $.state.get(LEDGER_REF)).value ?? LEDGER_INITIAL
79 const next = fn(cur)
80 if (next !== cur) await $.state.set(LEDGER_REF, next)
81 latest.ledger = next
82 })
83}
84function update_touched($: EngineInterface, fn: (cur: TouchedList) => TouchedList): Promise<void> {
85 return in_chain('touched', async () => {
86 const cur = latest.touched ?? (await $.state.get(TOUCHED_REF)).value ?? TOUCHED_INITIAL
87 const next = fn(cur)
88 if (next !== cur) await $.state.set(TOUCHED_REF, next)
89 latest.touched = next
90 })
91}
92const read_touched = async ($: EngineInterface): Promise<TouchedList> => latest.touched ?? (await $.state.get(TOUCHED_REF)).value ?? TOUCHED_INITIAL
93
94let alertsSound = false
95
96export function register(on: On, options: PluginOptions) {
97 if (options.mod_enabled === false) return
98 alertsSound = options.alerts_sound === true
99 const features = parseFeatures(options)
100 latest.ledger = null
101 latest.touched = null
102 register_session(on, features)
103 register_attribution(on)
104 register_compaction(on)
105 register_agents(on, parseProfile(options.model_profile), features)
106 register_step_tool(on)
107 register_touched(on, features)
108 register_replay_close(on)
109 register_refresh(on, features)
110 register_cockpit(on, parseProfile(options.model_profile), features)
111 register_surfaces(on)
112 register_toolrows(on)
113 register_gates(on)
114 register_ask(on)
115 register_band(on, features)
116 register_steps(on, features)
117 register_prompt(on, features)
118 register_compose(on, features)
119 register_api(on)
120}
121
122// $.orc: the noun other mods read orc's state through. The method must not need
123// `$`, so the snapshot writer (refresh) keeps `lastSnapshot` current.
124let companions: Companions = COMPANIONS_NONE
125let lastSnapshot: Snapshot = EMPTY
126
127function register_api(on: On) {
128 on('engine.create', async (_$, e, next) => {
129 companions = companionsOf(e.plugins)
130 const built = await next(e)
131 return { ...built, orc: { status: async () => statusInfo(lastSnapshot) } }
132 })
133}
134
135// One session.start hook: add /orc, and in an interactive session start the CI watcher.
136function register_session(on: On, features: Features) {
137 on('session.start', async ($, e, next) => {
138 try {
139 await $.command.register({ name: 'orc', description: 'orc cockpit — phase, slices, QA, PR, agents, decisions (no model turn)', immediate: true })
140 } catch {
141 // name taken in this build: the markdown /orc:status stays the fallback
142 }
143 gitFacts = null
144 latest.ledger = null
145 latest.touched = null
146 retroBox.dir = null
147 retroBox.file = null
148 Object.assign(sentinelBox, { check: null, model: null, learn: null, inflight: false, history: [] })
149 sentinelBox.steps.clear()
150 // The step tool: orc subagents label their TDD steps for the progress view.
151 stepToolReady = false
152 learnInflight = false
153 try {
154 await $.tool.register({ name: 'step', description: STEP_DESC, inputSchema: STEP_SCHEMA })
155 stepToolReady = true
156 } catch {
157 // tools can't register in this build: agents just don't report steps
158 }
159 void refresh($).catch(() => undefined)
160 if (retroOn(features)) void retro_load($).then(f => { retroBox.file = f; $.ui.invalidate('ui.render') }).catch(() => undefined)
161 if (e.isInteractive) {
162 $.clock.every(POLL_MS, () => { void ci_tick($) })
163 if (features.cacheCliff === 'warn') $.clock.every(60_000, () => { void cache_tick($, features) })
164 }
165 await keepwarm_resume($, features).catch(() => undefined)
166 return next(e)
167 })
168}
169
170// Iron rule 5 at the source: blank the attribution text the model is told to
171// write into commits and PRs, so it never drafts a trailer that
172// pre-commit-no-ai-attribution.sh then has to deny. The engine's own gate
173// sentences (`exemption`, `remedy`) pass through; the bash deny stays as backstop.
174function register_attribution(on: On) {
175 on('attribution.text', { kind: ['commit', 'pr'] }, async ($, e, next) => {
176 if ((await $.env.get('ORC_ALLOW_AI_ATTRIBUTION')) === '1') return next(e)
177 return { text: '' }
178 })
179}
180
181// Compaction keeps orc's place: the summarizer is told the live session state
182// (`orc-state line` — command, phase, slices, policy) so the post-compact
183// transcript still knows where the flow is. The PreCompact bash hook writes the
184// same facts to checkpoint.md for /orc:resume; this covers the live session.
185// Speculative precomputes and subagent transcripts are left alone.
186function register_compaction(on: On) {
187 on('session.compact', { trigger: ['manual', 'auto'] }, async ($, e, next) => {
188 if (e.agentId) return next(e)
189 const line = await orc_state($, ['line'])
190 if (!line) return next(e)
191 const note = 'orc session state (authoritative, from orc-state): ' + line +
192 ' — keep the current phase, slice progress, and any pending gate decision in the summary.'
193 return next({ ...e, instructions: e.instructions ? e.instructions + '\n\n' + note : note })
194 })
195}
196
197// Every orc-state write the model runs through Bash re-reads .orc/ into state;
198// subscribed drawings redraw by themselves. (Main-loop turns refresh in the
199// turn.complete hook below — one registration per event without a matcher.)
200function register_refresh(on: On, features: Features) {
201 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
202 // 2.1.291 types the Bash call flat (`e.command`); older builds nested it under `input`.
203 const call = e as { command?: string; input?: { command?: string } }
204 const command = call.command ?? call.input?.command ?? ''
205 // Measured before the floor's dialog opens, so its notices can attach to it; never denies.
206 const measured = features.guardMeasure ? await guard_measure($, command) : null
207 const pending = next(e)
208 void pending.catch(() => undefined)
209 if (measured) {
210 const clear = () => { guardBox.current = null; $.ui.invalidate('ui.render') }
211 next.signal?.addEventListener('abort', clear)
212 guardBox.current = measured
213 $.ui.invalidate('ui.render')
214 for (const line of measured.lines) { try { $.ui.notice(e.tool_use_id, line) } catch { /* a notice never fails the call */ } }
215 try {
216 const result = await pending
217 clear()
218 return after_bash($, command, result)
219 } catch (err) {
220 clear()
221 throw err
222 }
223 }
224 return after_bash($, command, await pending)
225 })
226}
227
228async function after_bash($: EngineInterface, command: string, result: unknown) {
229 if (TEST_RUN.test(command)) sentinelBox.history = [...sentinelBox.history, { command: command.trim(), ok: !failed(result) }].slice(-5)
230 if (isOrcStateWrite(command)) await refresh($).catch(() => undefined)
231 if (GIT_COMMIT.test(command) && !failed(result)) await commit_touched($)
232 return result
233}
234
235// The read-only measure for a command the shell floor will confirm; null when
236// it is not one of those, or anything about measuring fails.
237async function guard_measure($: EngineInterface, command: string): Promise<{ summary: GuardSummary; lines: string[] } | null> {
238 try {
239 const hit = classify(command)
240 if (!hit || hit.cwd === '-') return null
241 const outputs: string[] = []
242 for (const argv of measurePlan(hit.kind, hit.args)) {
243 const scoped = hit.cwd ? [argv[0], '-C', hit.cwd, ...argv.slice(1)] : argv
244 const r = await $.process.run(scoped, { timeoutMs: 5000 })
245 if (r.exitCode !== 0) return null
246 outputs.push(r.stdout)
247 }
248 if (!outputs.length) return null
249 const summary = summarize(hit.kind, outputs, hit.args, hit.cwd)
250 const lines = guardText(summary)
251 const snap = await $.state.get(SNAPSHOT_REF).then(r => r.value ?? EMPTY, () => EMPTY)
252 const slice = snap.session ? currentSlice(snap.slices) : null
253 const t = await read_touched($)
254 if (slice && t.sliceId === slice.id && t.files.some(f => f.kind === 'edit')) lines.push(`slice ${slice.id} has edits not yet checkpointed`)
255 return { summary, lines }
256 } catch {
257 return null
258 }
259}
260
261// orc agents: model_profile picks the model when the Agent call named none
262// (never over an explicit one — an escalation step-up), and every finished orc
263// subagent run lands in the usage ledger (`orc-state usage add`) — the data the
264// routing is re-tuned from.
265const agentTypes = new Map<string, string>()
266// The brief names mcp__orc__step, so it is only appended once the tool registered.
267let stepToolReady = false
268
269function register_agents(on: On, profile: Profile, features: Features) {
270 // Both hooks gate the engine (a dispatch, a turn's end): orc's bookkeeping
271 // never fails them, so every state call here is guarded.
272 on('agent.spawn', async ($, e, next) => {
273 const snap = await $.state.get(SNAPSHOT_REF).then(r => r.value ?? EMPTY, () => EMPTY)
274 const model = e.model ? undefined : modelFor(profileOf(snap, profile), e.subagentType)
275 const brief = stepToolReady && /^(orc:)?orc-implementer$/.test(e.subagentType) && !e.prompt.includes('mcp__orc__step') ? { prompt: e.prompt + STEP_BRIEF } : null
276 const result = await next(model || brief ? { ...e, ...(model ? { model } : {}), ...brief } : e)
277 if (result.agentId && /^(orc:)?orc-/.test(e.subagentType)) {
278 agentTypes.set(result.agentId, e.subagentType.replace(/^orc:/, ''))
279 await $.state.set(LIVE_REF, { agent: e.subagentType.replace(/^orc:/, ''), since: await $.clock.now().catch(() => null) }).catch(() => undefined)
280 const agentId = result.agentId
281 await update_ledger($, cur => tagAgent(cur, agentId, e.subagentType.replace(/^orc:/, ''))).catch(() => undefined)
282 }
283 return result
284 })
285
286 on('turn.complete', async ($, e, next) => {
287 const result = await next(e)
288 if (!e.agentId) {
289 retroBox.prev = String(e.answer ?? '')
290 await refresh($).catch(() => undefined)
291 await sentinel_check($, features)
292 // Finished agent rows showed once; the next main-loop completion clears them.
293 await update_ledger($, cur => Object.keys(cur.agents).filter(id => !agentTypes.has(id)).reduce(dropAgent, cur)).catch(() => undefined)
294 }
295 const agent = e.agentId ? agentTypes.get(e.agentId) : undefined
296 if (agent) {
297 // Cleared on every finish — an abort or API error carries no usage but the agent is gone.
298 agentTypes.delete(e.agentId as string)
299 // An explicit finish stamp: the agent row stops reading as running.
300 const at = await $.clock.now().catch(() => 0)
301 await update_ledger($, cur => finishAgent(cur, e.agentId as string, at)).catch(() => undefined)
302 const remaining = [...agentTypes.values()].at(-1) ?? null
303 await $.state.set(LIVE_REF, remaining ? { agent: remaining, since: null } : LIVE_INITIAL).catch(() => undefined)
304 if (e.usage) {
305 await orc_state($, ['usage', 'add', '--agent', agent, '--model', e.usage.model,
306 '--in', String(e.usage.input_tokens), '--out', String(e.usage.output_tokens), '--ms', String(e.durationMs)])
307 }
308 }
309 return result
310 })
311}
312
313// The step tool (mcp__orc__step): orc subagents report "writing failing test 2/5";
314// the label feeds the cockpit's agent rows. A label for the user, not a gate.
315const STEP_DESC = 'Report the current step of your work for the user\'s progress view. Only orc subagents use this.'
316const STEP_SCHEMA = { type: 'object', properties: { label: { type: 'string' }, n: { type: 'integer' }, of: { type: 'integer' } }, required: ['label'] }
317const STEP_BRIEF = '\n\nProgress: at the start of each TDD step call mcp__orc__step with { label, n, of } (e.g. { label: \'writing failing test\', n: 2, of: 5 }). It is a label for the user\'s progress view, not a gate.'
318
319function register_step_tool(on: On) {
320 // Registered tools are mcp__-named, so the engine would defer them behind ToolSearch; pin it in the prompt list.
321 on('tool.describe', { tool: 'mcp__orc__step' }, async (_$, e, next) => {
322 const r = await next(e)
323 return { ...r, isDeferred: false }
324 })
325
326 on('tool.call', { tool: 'mcp__orc__step' }, async ($, e) => {
327 const call = e as { agentId?: string; label?: unknown; n?: unknown; of?: unknown }
328 if (!call.agentId) return { result: 'ignored: only orc subagents report steps' }
329 try {
330 const step = { label: String(call.label ?? '').slice(0, 80), n: Number(call.n) || 0, of: Number(call.of) || 0 }
331 const agentId = call.agentId
332 await update_ledger($, cur => setStep(cur, agentId, step))
333 } catch { /* a label never fails the agent */ }
334 return { result: 'ok' }
335 })
336}
337
338// --- Touched files -----------------------------------------------------------
339// What the session read, edited and committed during the current slice. Reads
340// and edits are recorded after the tool ran (a denied or errored call marks
341// nothing); a `git commit` through Bash promotes the slice's edits to committed.
342const GIT_COMMIT = /(^|[;&|]\s*)git\s+(-C\s+\S+\s+)?commit\b/
343const failed = (r: unknown) => { const x = r as { deny?: unknown; isError?: unknown }; return !!x.deny || !!x.isError }
344
345type GitFacts = { root: string; gitDir: string; mergeBase: string }
346let gitFacts: GitFacts | null = null
347
348// Repo root, git dir and the point the branch left the base: once per session (not cached when git can't answer).
349async function git_facts($: EngineInterface): Promise<GitFacts> {
350 if (gitFacts) return gitFacts
351 const run = (argv: string[]) => $.process.run(['git', ...argv], { timeoutMs: 5000 }).then(r => (r.exitCode === 0 ? r.stdout.trim() : ''), () => '')
352 const [root = '', gitDir = ''] = (await run(['rev-parse', '--show-toplevel', '--absolute-git-dir'])).split('\n')
353 const head = await run(['rev-parse', '--abbrev-ref', 'origin/HEAD'])
354 const base = head && head !== 'origin/HEAD' ? head : 'origin/main'
355 const facts = { root, gitDir, mergeBase: (await run(['merge-base', 'HEAD', base])) || base }
356 if (root) gitFacts = facts
357 return facts
358}
359
360async function touch_files($: EngineInterface, paths: string[], kind: TouchKind): Promise<void> {
361 try {
362 const snap = await $.state.get(SNAPSHOT_REF).then(r => r.value ?? EMPTY, () => EMPTY)
363 const slice = snap.session ? currentSlice(snap.slices) : null
364 if (!slice || !paths.length) return
365 const { root } = await git_facts($)
366 const at = await $.clock.now()
367 await update_touched($, cur => paths.reduce((t, p) => touch(t, { sliceId: slice.id, path: relPath(p, root), kind, at }), cur))
368 await touched_counts($)
369 } catch { /* bookkeeping never fails a tool call */ }
370}
371
372async function commit_touched($: EngineInterface): Promise<void> {
373 try {
374 const at = await $.clock.now()
375 await update_touched($, t => (t.files.some(f => f.kind === 'edit') ? markCommitted(t, at) : t))
376 await touched_counts($)
377 } catch { /* ignore */ }
378}
379
380// Line counts come from git, re-read only when the index or HEAD changed.
381// (State writes are refused while a drawing renders, so this runs from events, never from ui.render.)
382async function touched_counts($: EngineInterface): Promise<void> {
383 try {
384 if (!(await read_touched($)).files.length) return
385 const g = await git_facts($)
386 if (!g.gitDir) return
387 const stamp = (await Promise.all(['index', 'HEAD'].map(f => $.fs.stat(g.gitDir + '/' + f).then(st => st.mtimeMs, () => 0)))).join(':')
388 if (stamp === (await read_touched($)).stamp) return
389 const r = await $.process.run(['git', '-C', g.root, 'diff', '--numstat', g.mergeBase], { timeoutMs: 10000 })
390 const counts = r.exitCode === 0 ? parseNumstat(r.stdout) : new Map()
391 await update_touched($, fresh => applyNumstat(fresh, counts, stamp))
392 } catch { /* counts stay as they were */ }
393}
394
395function register_touched(on: On, features: Features) {
396 on('tool.call', { tool: 'Read' }, async ($, e, next) => {
397 const result = await next(e)
398 if (!failed(result)) await touch_files($, [String((e as { file_path?: string }).file_path ?? '')].filter(Boolean), 'read')
399 return result
400 })
401
402 on('tool.call', { tool: ['Grep', 'Glob'] }, async ($, e, next) => {
403 const result = await next(e)
404 if (failed(result)) return result
405 const names = (result as { result?: { filenames?: unknown } }).result?.filenames
406 if (Array.isArray(names)) await touch_files($, names.filter((n): n is string => typeof n === 'string').slice(0, 10), 'read')
407 return result
408 })
409
410 // The shared edit observer: each step runs after a successful edit (touch, then record).
411 on('tool.call', { tool: ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'] }, async ($, e, next) => {
412 // A Write replaces the whole file, so the old content is read before the write runs.
413 const before = features.replay ? await replay_before($, e) : null
414 const result = await next(e)
415 if (failed(result)) return result
416 const call = e as { file_path?: string; notebook_path?: string }
417 await touch_files($, [call.file_path ?? call.notebook_path ?? ''].filter(Boolean), 'edit')
418 if (features.replay) await record_edit($, e, before)
419 await sentinel_check($, features)
420 return result
421 })
422}
423
424// --- Slice replay ------------------------------------------------------------
425type EditCall = { tool?: string; file_path?: string; old_string?: string; new_string?: string; content?: string; edits?: { old_string?: string; new_string?: string }[] }
426
427async function replay_before($: EngineInterface, e: unknown): Promise<string | null> {
428 const call = e as EditCall
429 if (call.tool !== 'Write' || !call.file_path) return null
430 return $.fs.read(call.file_path).then(t => (typeof t === 'string' ? t : ''), () => '')
431}
432
433async function record_edit($: EngineInterface, e: unknown, before: string | null): Promise<void> {
434 try {
435 const call = e as EditCall
436 let old: string, now: string
437 if (call.tool === 'Edit') { old = call.old_string ?? ''; now = call.new_string ?? '' }
438 else if (call.tool === 'MultiEdit') { old = (call.edits ?? []).map(x => x.old_string ?? '').join('\n'); now = (call.edits ?? []).map(x => x.new_string ?? '').join('\n') }
439 else if (call.tool === 'Write') { old = before ?? ''; now = call.content ?? '' }
440 else return
441 if (!call.file_path) return
442 const snap = await $.state.get(SNAPSHOT_REF).then(r => r.value ?? EMPTY, () => EMPTY)
443 const slice = snap.session ? currentSlice(snap.slices) : null
444 const id = slice ? Number(slice.id) : 0
445 const sliceId = Number.isFinite(id) ? id : 0
446 const { root } = await git_facts($)
447 const at = await $.clock.now()
448 const cur = (await $.state.get(REPLAY_REF)).value ?? REPLAY_INITIAL
449 await $.state.set(REPLAY_REF, recordEdit(cur, { sliceId, path: relPath(call.file_path, root), tool: call.tool, old, new: now, at }))
450 } catch { /* bookkeeping never fails a tool call */ }
451}
452
453const replay_state = ($: EngineInterface) => $.state.get(REPLAY_REF).then(r => r.value ?? REPLAY_INITIAL, () => REPLAY_INITIAL)
454
455// Open the replay pane at the latest slice. False when nothing is recorded or the pane was refused.
456async function open_replay($: EngineInterface): Promise<boolean> {
457 const cur = await replay_state($)
458 if (!cur.edits.length) return false
459 await $.state.set(REPLAY_REF, { ...cur, view: latestReplayView(cur) })
460 try {
461 if (!(await $.ui.open({ id: REPLAY_PANE, title: 'replay', focus: true, closeOnEscape: true, rows: 18, columns: 64 })).isPlaced) return false
462 } catch {
463 return false
464 }
465 await $.ui.focus({ requestId: REPLAY_PANE, key: 'replay-next' }).catch(() => undefined)
466 return true
467}
468
469async function replay_command($: EngineInterface, features: Features): Promise<{ text?: string }> {
470 if (!features.replay) return { text: 'Slice replay is off (replay option).' }
471 const cur = await replay_state($)
472 const v = replayView(cur, latestReplayView(cur))
473 if (!v) return { text: 'No edits recorded yet in this session.' }
474 if ((await $.session.surfaces()).length && (await open_replay($))) return {}
475 return { text: `Slice ${v.sliceId} · ${v.tool} ${v.path} +${v.add} -${v.del}\n${v.diff}` }
476}
477
478function draw_replay($: EngineInterface, e: { surface: RenderSurface | null; props: { bodyColumns: number } }, els: Els, state: ReplayState) {
479 const { Box, Text, Button } = els
480 const v = replayView(state, state.view)
481 const walk = (delta: 1 | -1) => async () => {
482 try {
483 const cur = await replay_state($)
484 await $.state.set(REPLAY_REF, { ...cur, view: stepReplay(cur, delta) })
485 } catch { /* the view stays as drawn */ }
486 }
487 const buttons = Box({ flexDirection: 'row', columnGap: 2, children: [
488 Button({ key: 'replay-prev', hotkey: 'p', label: '◀ Prev', onPress: walk(-1) }),
489 Button({ key: 'replay-next', hotkey: 'n', label: 'Next ▶', onPress: walk(1) }),
490 Button({ key: 'replay-close', hotkey: 'c', role: 'dismiss', label: 'Close', onPress: async () => { await $.ui.close({ id: REPLAY_PANE }).catch(() => undefined); await reset_replay($) } }),
491 ] })
492 if (!v) return Box({ flexDirection: 'column', children: [Text({ dimColor: true, children: ['No edits recorded yet'] }), buttons] })
493 const source = isRich(e.surface) && 'Svg' in els ? replaySvg(v, e.props.bodyColumns) : null
494 const body = source && 'Svg' in els ? els.Svg({ source, alt: replayAlt(v), width: px(e.props.bodyColumns) }) : replayText(els, v)
495 return Box({ flexDirection: 'column', children: [body, buttons] })
496}
497
498async function reset_replay($: EngineInterface): Promise<void> {
499 try { await $.state.set(REPLAY_REF, { ...(await replay_state($)), view: REPLAY_INITIAL.view }) } catch { /* ignore */ }
500}
501
502// Closing the pane rewinds the view. The hook hears the person's close (Escape, close key); a plugin's own
503// $.ui.close skips its own hooks, so the Close button resets directly.
504function register_replay_close(on: On) {
505 on('ui.close', { id: REPLAY_PANE }, async ($, e, next) => {
506 const result = await next(e)
507 if (!failed(result)) await reset_replay($)
508 return result
509 })
510}
511
512// The only turn.step hook: every model request's usage lands in the ledger
513// (main loop, or the subagent named by agentId). Later slices extend the body.
514function register_steps(on: On, features: Features) {
515 on('turn.step', async function* ($, e, next) {
516 const startedAt = await $.clock.now().catch(() => 0)
517 const result = yield* next(e)
518 try {
519 const at = await $.clock.now()
520 await update_ledger($, cur => {
521 // A request that re-wrote the cache starts the clock over (the ping clock too).
522 if (!e.agentId && result?.usage && isColdRewrite(cur.main.lastContext, result.usage)) warmBox.pingedAt = null
523 return recordStep(cur, { agentId: e.agentId ?? null, usage: result?.usage ?? null, at, ms: at - startedAt })
524 })
525 if (e.agentId) sentinel_step($, features, e.agentId)
526 } catch { /* bookkeeping never fails a request */ }
527 return result
528 })
529}
530
531// orc outside the pane: the spinner's suffix, the idle prompt hint and the mode
532// footer. Each is a prop rewrite; the engine keeps drawing its own line.
533function register_surfaces(on: On) {
534 on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
535 const snap = await $.state.get(SNAPSHOT_REF).then(r => r.value ?? EMPTY, () => EMPTY)
536 const live = await $.state.get(LIVE_REF).then(r => r.value ?? LIVE_INITIAL, () => LIVE_INITIAL)
537 const suffix = spinnerSuffix(snap, live.agent)
538 return suffix ? next({ ...e, props: { ...e.props, suffix: e.props.suffix + suffix } }) : next(e)
539 })
540
541 on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
542 if (e.props.isWorking || e.props.isDraft) return next(e)
543 const snap = await $.state.get(SNAPSHOT_REF).then(r => r.value ?? EMPTY, () => EMPTY)
544 const usage = await $.session.usage().then(u => u, () => null)
545 const percent = parseMeter(usage)?.contextPercent ?? null
546 const trail = ((await $.state.get(LEDGER_REF).then(r => r.value, () => undefined)) ?? LEDGER_INITIAL).main.trail
547 const window = usage?.context?.window ?? 200_000
548 const hint = hintWithContext(snap, percent, trail, window)
549 if (!hint) return next(e)
550 const els = $.ui.resolve(e)
551 // Desktop: the ring and bars as a drawing, then the same words.
552 if (percent != null && isRich(e.surface) && 'Svg' in els) {
553 const source = fitSvg(contextChipSvg(percent, trail, window))
554 if (source) return els.Box({ flexDirection: 'row', columnGap: 1, children: [
555 els.Svg({ source, alt: `context ${percent}% used`, width: 72, height: 18 }),
556 els.Text({ dimColor: true, children: [hint] }),
557 ] })
558 }
559 return next({ ...e, props: { ...e.props, hint } })
560 })
561
562 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
563 const policy = policyOf(await $.state.get(SNAPSHOT_REF).then(r => r.value ?? EMPTY, () => EMPTY))
564 return policy && policy !== 'manual' ? next({ ...e, props: { ...e.props, modes: [...e.props.modes, 'orc ' + policy] } }) : next(e)
565 })
566}
567
568// ToolUse rows for orc's own plumbing (orc-state, orc-pr-size, orc-report,
569// gh pr checks) collapse to one dim line; errors and everything else keep the engine row.
570function register_toolrows(on: On) {
571 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
572 if (e.props.tool !== 'Bash' || e.props.isErrored || e.props.isInterrupted) return next(e)
573 const text = plumbingLine(e.props.input, e.props.isRunning)
574 if (!text) return next(e)
575 const { Text } = $.ui.resolve(e)
576 return Text({ dimColor: true, children: [text] })
577 })
578}
579
580// The dialog stays open for as long as the tool call is pending; the cache row reads it as "waiting on your answer".
581function register_ask(on: On) {
582 on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
583 askBox.open = true
584 $.ui.invalidate('ui.render')
585 try {
586 return await next(e)
587 } finally {
588 askBox.open = false
589 $.ui.invalidate('ui.render')
590 }
591 })
592}
593
594// Gate chrome: outward and escalation gates (orc:gates header chips) get a
595// badge above the engine's own dialog, which is kept exactly once.
596function register_gates(on: On) {
597 on('ui.render', { component: 'AskUserQuestion' }, async ($, e, next) => {
598 const badge = gateBadge(e.props.questions)
599 if (!badge) return next(e)
600 const { Box, Text } = $.ui.resolve(e)
601 return Box({ flexDirection: 'column', children: [Text({ bold: true, color: 'yellow', children: [badge] }), await next(e)] })
602 })
603}
604
605// --- Cache cliff and keep-warm -------------------------------------------------
606// The prompt cache lapses after the ttl without a request. The clock reads the main loop's last
607// request from the ledger (a keep-warm ping moves it forward); the band warns in the last 15 minutes,
608// a composer send past the ttl toasts what it will re-write, and /orc keepwarm pings to hold it.
609type CacheClock = CacheView & { lastAt: number }
610
611async function cache_view($: EngineInterface, features: Features): Promise<CacheClock | null> {
612 const main = ((await $.state.get(LEDGER_REF)).value ?? LEDGER_INITIAL).main
613 const lastAt = Math.max(main.lastAt ?? 0, warmBox.pingedAt ?? 0)
614 if (!lastAt || main.lastContext <= 0 || !main.model) return null
615 const now = await $.clock.now()
616 return { ...cacheState({ lastAt, lastContext: main.lastContext, model: main.model, now, ttlMs: features.cacheTtlMs }), lastAt }
617}
618
619async function cache_row($: EngineInterface, features: Features, idle: boolean): Promise<BandRow | null> {
620 if (features.cacheCliff !== 'warn' || !(idle || askBox.open)) return null
621 try {
622 const v = await cache_view($, features)
623 if (!v || v.phase !== 'cooling') return null
624 return { kind: 'cache', minutesLeft: v.minutesLeft, rewriteUsd: v.rewriteUsd, tokens: v.tokens, waitingOn: askBox.open ? 'your answer' : null }
625 } catch {
626 return null
627 }
628}
629
630// The prompt.submit step that warns before a send re-writes a cold cache. Never blocks or alters the prompt.
631async function cache_cold_toast($: EngineInterface, e: { origin: { kind: string } }, features: Features): Promise<void> {
632 if (features.cacheCliff !== 'warn' || e.origin.kind !== 'composer') return
633 try {
634 const v = await cache_view($, features)
635 if (v && v.phase === 'cold' && v.coldFor > 0 && v.tokens > COLD_MIN_TOKENS) $.ui.toast(coldToast(v.coldFor, v.tokens, v.rewriteUsd))
636 } catch { /* a warning never fails a send */ }
637}
638
639// The only prompt.submit hook; each step may inspect the prompt, none may drop it.
640function register_prompt(on: On, features: Features) {
641 on('prompt.submit', async ($, e, next) => {
642 await cache_cold_toast($, e, features)
643 const kept = next(e)
644 retro_defer($, e, features)
645 return kept
646 })
647}
648
649// --- Corrections -> retro store -------------------------------------------------
650// A composer prompt that reads like a correction is checked by Haiku after the send went through; the rule it
651// proposes becomes a candidate in <state root>/retro/candidates.json. Saved rules (rules.md) reach later sessions
652// through prompt.compose. $.fs.write creates parent directories, so no mkdir.
653const retroOn = (features: Features) => features.corrections && !companions.reflect
654
655function retro_defer($: EngineInterface, e: { text: string; origin: { kind: string } }, features: Features): void {
656 try {
657 if (!retroOn(features) || e.origin.kind !== 'composer' || !mayBeCorrection(e.text)) return
658 const text = e.text, prev = retroBox.prev
659 $.clock.after(0, () => { void retro_drain($, text, prev).catch(() => undefined) })
660 } catch { /* a check never fails a send */ }
661}
662
663async function retro_dir($: EngineInterface): Promise<string> {
664 if (retroBox.dir) return retroBox.dir
665 const env = await $.env.get('ORC_STATE_DIR').catch(() => undefined)
666 const root = env ? '' : (await git_facts($)).root
667 const dir = (env || (root ? root + '/.orc' : '.orc')) + '/retro'
668 if (env || root) retroBox.dir = dir
669 return dir
670}
671
672async function retro_read($: EngineInterface, name: string): Promise<string> {
673 return $.fs.read((await retro_dir($)) + '/' + name).then(t => (typeof t === 'string' ? t : ''), () => '')
674}
675
676// null = the file does not exist; a file that exists but cannot be read throws (it is never overwritten).
677async function retro_read_file($: EngineInterface, name: string): Promise<string | null> {
678 const path = (await retro_dir($)) + '/' + name
679 try {
680 const t = await $.fs.read(path)
681 return typeof t === 'string' ? t : ''
682 } catch (err) {
683 if (await $.fs.stat(path).then(() => true, () => false)) throw err
684 return null
685 }
686}
687
688const UNREADABLE = 'retro/candidates.json is unreadable — fix or delete it'
689
690// Missing -> empty. Present but unparseable -> throws, so no writer clobbers it.
691async function retro_load($: EngineInterface): Promise<CandidateFile> {
692 const raw = await retro_read_file($, 'candidates.json')
693 if (raw === null || raw.trim() === '') return { schema: 1, items: [] }
694 let f: CandidateFile | undefined
695 try { f = JSON.parse(raw) as CandidateFile } catch { /* falls to the throw below */ }
696 if (f && f.schema === 1 && Array.isArray(f.items)) return f
697 throw new Error(UNREADABLE)
698}
699
700// Writes run one at a time, each re-reading the file first, so two checks finishing together both land.
701function retro_serial<T>(job: () => Promise<T>): Promise<T> {
702 const run = retroBox.chain.then(job)
703 retroBox.chain = run.catch(() => undefined)
704 return run
705}
706
707async function retro_put($: EngineInterface, file: CandidateFile): Promise<void> {
708 await $.fs.write((await retro_dir($)) + '/candidates.json', JSON.stringify(file, null, 2) + '\n')
709 retroBox.file = file
710 $.ui.invalidate('ui.render')
711}
712
713async function retro_drain($: EngineInterface, text: string, prev: string): Promise<void> {
714 const r = await $.model.complete({ model: HAIKU, maxTokens: 300, system: RETRO_SYSTEM, prompt: retroPrompt(text, prev) })
715 if (!r.isAnswered) return
716 const v = parseRetro(r.text)
717 const rule = v && v.isCorrection && v.confidence >= 0.7 ? cleanRule(v.rule) : undefined
718 if (!rule) return
719 const at = await $.clock.now()
720 await retro_serial(async () => {
721 const f = await retro_load($)
722 const m = mergeCandidate(f.items, rule, { source: 'composer', at, saved: f.items.filter(i => i.status === 'saved').map(i => i.rule) })
723 if (!m.alreadySaved) await retro_put($, { schema: 1, items: m.items })
724 })
725}
726
727// Save a clean rule: mark its candidate saved (the card's id, else the closest one, else a new one) and splice rules.md.
728async function retro_save($: EngineInterface, raw: string, id?: string): Promise<string> {
729 const clean = cleanRule(raw)
730 if (!clean) return 'Rule not saved: it must be one line, under 200 characters, with no secrets.'
731 try {
732 return await retro_serial(async () => {
733 const f = await retro_load($)
734 const at = await $.clock.now()
735 let items = f.items
736 let hit = id ? items.findIndex(i => i.id === id) : -1
737 if (hit < 0) {
738 // The closest candidate (no seen bump: this is the person deciding), else a new one.
739 hit = items.reduce((best, c, i) => (similarity(c.rule, clean) > (best < 0 ? 0 : similarity(items[best].rule, clean)) ? i : best), -1)
740 if (hit < 0 || similarity(items[hit].rule, clean) < 0.6) { items = mergeCandidate(items, clean, { source: 'manual', at }).items; hit = items.length - 1 }
741 }
742 items = items.map((c, i) => (i === hit ? { ...c, rule: clean, status: 'saved' as const, at } : c))
743 // rules.md is the source of truth: its bullets stay, the saved rule is appended. A read failure on an existing file throws.
744 const current = await retro_read_file($, 'rules.md')
745 const rules = [...new Set([...savedRules(current ?? ''), clean])]
746 const out = current === null || current.trim() === '' ? renderRules(rules) : spliceRules(current, rules)
747 if (out === undefined) return 'Rule not saved: rules.md has no single orc:retro start/end markers, in that order. Fix or remove the file.'
748 await $.fs.write((await retro_dir($)) + '/rules.md', out)
749 await retro_put($, { schema: 1, items })
750 return 'Saved rule: ' + clean
751 })
752 } catch (err) {
753 return err instanceof Error && err.message === UNREADABLE ? 'Rule not saved: ' + UNREADABLE + '.' : 'Rule not saved: the retro files could not be written.'
754 }
755}
756
757async function retro_skip($: EngineInterface, id: string): Promise<void> {
758 await retro_serial(async () => {
759 const f = await retro_load($)
760 await retro_put($, { schema: 1, items: f.items.map(i => (i.id === id ? { ...i, status: 'skipped' as const } : i)) })
761 })
762}
763
764async function retro_command($: EngineInterface, arg: string): Promise<{ text: string }> {
765 const save = arg.match(/^save\s+([\s\S]+)$/)
766 if (save) return { text: await retro_save($, save[1].trim().replace(/^"([\s\S]*)"$/, '$1')) }
767 const loaded = await retro_load($).catch(() => null)
768 if (!loaded) return { text: UNREADABLE + '.' }
769 const items = loaded.items
770 const pending = items.filter(i => i.status === 'pending'), saved = items.filter(i => i.status === 'saved')
771 if (!pending.length && !saved.length) return { text: 'No retro candidates yet. Usage: /orc retro save "<rule>"' }
772 return { text: [
773 ...(pending.length ? [`${pending.length} pending:`, ...pending.map(i => `- "${i.rule}" · seen ${i.seen}×`)] : []),
774 ...(saved.length ? ['Saved:', ...saved.map(i => '- ' + i.rule)] : []),
775 ].join('\n') }
776}
777
778// Drawing reads the cached candidates only (loaded at session.start, kept current by every write): no IO per render.
779const retro_pending_items = (features: Features) => (retroOn(features) ? (retroBox.file?.items ?? []).filter(i => i.status === 'pending') : [])
780
781function retro_row(features: Features): BandRow | null {
782 const top = retro_pending_items(features).sort((a, b) => b.at - a.at)[0]
783 return top ? { kind: 'retro', id: top.id, rule: top.rule, seen: top.seen } : null
784}
785
786// --- Gate sentinel -----------------------------------------------------------------
787// Phase 5 only. Model-free checks (files outside the slice, budget pace, a test command failing 3x) run on every
788// main turn.complete and after every Edit/Write; with sentinel: model a Haiku review also runs every
789// `sentinel_every` requests of an orc agent, one at a time. Dismissed ids are remembered per branch in $.store.
790const TEST_RUN = /\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|\bpytest\b|\bvitest\b|\bjest\b|\bcargo\s+test\b|\bgo\s+test\b|\bplugin\s+test\b/
791const sentinelOn = (features: Features) => features.sentinel !== 'off' && !companions.youShouldKnow
792const dismissedKey = (branch: string) => 'sentinel:dismissed:' + branch
793const sentinel_card = (id: string) => (sentinelBox.check?.id === id ? sentinelBox.check : sentinelBox.model?.id === id ? sentinelBox.model : null)
794
795function sentinel_row(features: Features): BandRow | null {
796 const card = sentinelOn(features) ? sentinelBox.check ?? sentinelBox.model : null
797 return card ? { kind: 'sentinel', id: card.id, text: card.text } : null
798}
799
800// The current slice as the plan wrote it (touchpoints, acceptance), from <state root>/<branch>/files/slices.json.
801async function sentinel_plan($: EngineInterface, branch: string, id: string, title: string): Promise<SentinelSlice> {
802 const env = await $.env.get('ORC_STATE_DIR').catch(() => undefined)
803 const root = env || ((await git_facts($)).root || '.') + '/.orc'
804 try {
805 const json = JSON.parse(await $.fs.read(`${root}/${branch}/files/slices.json`) as string) as { slices?: { id: number | string; title?: string; touchpoints?: string[]; acceptance?: string[] }[] }
806 const hit = json.slices?.find(x => String(x.id) === id)
807 if (hit) return { id, title: hit.title ?? title, touchpoints: hit.touchpoints ?? [], acceptance: hit.acceptance ?? [] }
808 } catch { /* no plan file: the checks that need it stay quiet */ }
809 return { id, title, touchpoints: [], acceptance: [] }
810}
811
812async function sentinel_dismissed($: EngineInterface, branch: string): Promise<string[]> {
813 const v = await $.store.get(dismissedKey(branch)).catch(() => undefined)
814 return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []
815}
816
817async function sentinel_check($: EngineInterface, features: Features): Promise<void> {
818 if (!sentinelOn(features)) return
819 try {
820 const snap = await $.state.get(SNAPSHOT_REF).then(r => r.value ?? EMPTY, () => EMPTY)
821 const slice = snap.session && snap.session.phase === 5 ? currentSlice(snap.slices) : null
822 let card: SentinelCard | null = null
823 if (snap.session && slice) {
824 const plan = await sentinel_plan($, snap.session.branch, slice.id, slice.title)
825 const t = await read_touched($)
826 const done = snap.slices.filter(isDone).length
827 const running = snap.slices.filter(x => x.status === 'red' || x.status === 'green').length
828 const notes: (SentinelNote | null)[] = [
829 repeatedFailure(sentinelBox.history),
830 plan.touchpoints.length && t.sliceId === slice.id ? outsideSlice(t.files, plan.touchpoints) : null,
831 snap.size ? budgetCreep({ loc: snap.size.loc, budget: snap.size.budget, done, running, total: snap.slices.length }) : null,
832 ]
833 const dismissed = await sentinel_dismissed($, snap.session.branch)
834 const hit = notes.find(n => n && !dismissed.includes(n.id))
835 card = hit ? { ...hit, slice: slice.id } : null
836 }
837 // A model card belongs to the slice it reviewed: a new slice (or none) retires it.
838 const stale = !!sentinelBox.model && (!slice || sentinelBox.model.slice !== slice.id)
839 const changed = sentinelBox.check?.id !== card?.id || stale || (!card && !!sentinelBox.model && !slice)
840 sentinelBox.check = card
841 if (stale) sentinelBox.model = null
842 if (changed) $.ui.invalidate('ui.render')
843 } catch { /* a watcher never fails the turn */ }
844}
845
846// Called from the one turn.step hook: count an orc agent's requests, review on every Nth (never two at once).
847function sentinel_step($: EngineInterface, features: Features, agentId: string): void {
848 if (features.sentinel !== 'model' || !sentinelOn(features) || !agentTypes.has(agentId)) return
849 const n = (sentinelBox.steps.get(agentId) ?? 0) + 1
850 sentinelBox.steps.set(agentId, n)
851 if (n % features.sentinelEvery !== 0 || sentinelBox.inflight) return
852 sentinelBox.inflight = true
853 $.clock.after(0, () => { void sentinel_review($).catch(() => undefined).finally(() => { sentinelBox.inflight = false }) })
854}
855
856let learnInflight = false
857
858async function sentinel_review($: EngineInterface): Promise<void> {
859 const snap = await $.state.get(SNAPSHOT_REF).then(r => r.value ?? EMPTY, () => EMPTY)
860 const slice = snap.session && snap.session.phase === 5 ? currentSlice(snap.slices) : null
861 if (!snap.session || !slice) return
862 const plan = await sentinel_plan($, snap.session.branch, slice.id, slice.title)
863 const g = await git_facts($)
864 const diff = await $.process.run(['git', ...(g.root ? ['-C', g.root] : []), 'diff', '-U0', '--no-color', 'HEAD'], { timeoutMs: 10000 }).then(r => (r.exitCode === 0 ? r.stdout : ''), () => '')
865 if (!diff.trim()) return
866 const r = await $.model.complete({ model: HAIKU, maxTokens: 400, timeoutMs: 20_000, system: SENTINEL_SYSTEM, prompt: sentinelPrompt(plan, diff.slice(0, DIFF_CAP)) })
867 const v = r.isAnswered ? parseSentinel(r.text) : null
868 if (!v?.headsUp) return
869 const id = 'model:' + v.kind + ':' + v.headsUp.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 60)
870 if ((await sentinel_dismissed($, snap.session.branch)).includes(id)) return
871 sentinelBox.model = { id, text: v.headsUp, slice: slice.id }
872 $.ui.invalidate('ui.render')
873}
874
875async function sentinel_learn($: EngineInterface, id: string): Promise<void> {
876 const card = sentinel_card(id)
877 if (!card || learnInflight) return
878 learnInflight = true
879 try {
880 const r = await $.model.complete({ model: HAIKU, maxTokens: 250, timeoutMs: 20_000, system: SENTINEL_SYSTEM,
881 prompt: `A reviewer raised this heads-up about slice ${card.slice} of the current change:\n${wrap('card', card.text)}\nIn at most 120 words, explain what it means and how to check it. Plain text, no preamble.` })
882 if (!r.isAnswered) return
883 sentinelBox.learn = { id, text: r.text.trim().split(/\s+/).slice(0, 120).join(' ') }
884 $.ui.invalidate('ui.render')
885 } finally {
886 learnInflight = false
887 }
888}
889
890async function sentinel_dismiss($: EngineInterface, id: string): Promise<void> {
891 const snap = await $.state.get(SNAPSHOT_REF).then(r => r.value ?? EMPTY, () => EMPTY)
892 const branch = snap.session?.branch
893 if (branch) await $.store.set(dismissedKey(branch), [...new Set([...(await sentinel_dismissed($, branch)), id])]).catch(() => undefined)
894 if (sentinelBox.check?.id === id) sentinelBox.check = null
895 if (sentinelBox.model?.id === id) sentinelBox.model = null
896 if (sentinelBox.learn?.id === id) sentinelBox.learn = null
897 $.ui.invalidate('ui.render')
898}
899
900// Saved rules join the system prompt as one session section (after any shared ones), capped at 2,000 chars.
901function register_compose(on: On, features: Features) {
902 on('prompt.compose', async ($, e, next) => {
903 const result = await next(e)
904 if (!retroOn(features)) return result
905 try {
906 const text = rulesSection(savedRules(await retro_read($, 'rules.md')))
907 return text ? { sections: [...result.sections, { id: 'orc:retro-rules', text, scope: 'session' as const }] } : result
908 } catch {
909 return result
910 }
911 })
912}
913
914// Once a minute: redraw the band only when what it says would change.
915let lastCacheSig = ''
916async function cache_tick($: EngineInterface, features: Features): Promise<void> {
917 try {
918 const v = await cache_view($, features)
919 const sig = v && v.phase === 'cooling' ? 'cooling:' + v.minutesLeft : v ? v.phase : ''
920 if (sig === lastCacheSig) return
921 lastCacheSig = sig
922 $.ui.invalidate('ui.render')
923 } catch { /* the next tick tries again */ }
924}
925
926const keepwarmKey = (sid: string) => 'keepwarm:' + sid
927
928function keepwarm_schedule($: EngineInterface, features: Features, gen: number, delay: number): void {
929 warmBox.timer = $.clock.after(delay, () => { void keepwarm_ping($, features, gen) })
930}
931
932async function keepwarm_arm($: EngineInterface, features: Features, deadline: number, persist: boolean): Promise<void> {
933 warmBox.timer?.cancel()
934 const gen = ++warmBox.gen
935 warmBox.deadline = deadline
936 if (persist) await $.store.set(keepwarmKey(await $.session.id()), deadline).catch(() => undefined)
937 const every = pingEvery(features.cacheTtlMs)
938 // The first ping is due `every` after the cache was last touched, not after the command.
939 const v = await cache_view($, features).catch(() => null)
940 const now = await $.clock.now()
941 keepwarm_schedule($, features, gen, v && v.phase !== 'cold' ? Math.min(every, Math.max(5_000, v.lastAt + every - now)) : every)
942 $.ui.invalidate('ui.render')
943}
944
945async function keepwarm_stop($: EngineInterface, why: string | null): Promise<void> {
946 warmBox.gen++
947 warmBox.timer?.cancel()
948 warmBox.timer = null
949 warmBox.deadline = null
950 await $.store.set(keepwarmKey(await $.session.id()), null).catch(() => undefined)
951 if (why) $.ui.toast(why)
952 $.ui.invalidate('ui.render')
953}
954
955// A failed ping (state, clock, fork) stops keep-warm with a toast instead of dying silently.
956async function keepwarm_ping($: EngineInterface, features: Features, gen: number): Promise<void> {
957 try {
958 await keepwarm_ping_once($, features, gen)
959 } catch {
960 if (gen === warmBox.gen) await keepwarm_stop($, 'keep-warm stopped: the ping failed').catch(() => undefined)
961 }
962}
963
964async function keepwarm_ping_once($: EngineInterface, features: Features, gen: number): Promise<void> {
965 if (gen !== warmBox.gen) return
966 const now = await $.clock.now()
967 if (warmBox.deadline == null || now >= warmBox.deadline) return keepwarm_stop($, 'keep-warm finished')
968 const every = pingEvery(features.cacheTtlMs)
969 // The user is active: their own requests keep the cache warm, so wait out the rest of the interval.
970 const v = await cache_view($, features)
971 if (v && now - v.lastAt < every - 5_000) { keepwarm_schedule($, features, gen, v.lastAt + every - now); return }
972 const r = await $.model.fork({ prompt: 'Reply with the single word: warm' }).catch(() => null)
973 if (gen !== warmBox.gen) return
974 if (!r || !r.isAnswered) return keepwarm_stop($, 'keep-warm stopped: ' + (r ? 'nothing to keep warm yet' : 'the ping failed'))
975 if (pingGone(r.usage)) return keepwarm_stop($, 'keep-warm stopped: the cache was already gone')
976 warmBox.pingedAt = await $.clock.now()
977 if (warmBox.pingedAt + every >= warmBox.deadline) return keepwarm_stop($, 'keep-warm finished')
978 keepwarm_schedule($, features, gen, every)
979}
980
981// A hot reload cancels pending timers; the deadline in $.store re-arms them.
982async function keepwarm_resume($: EngineInterface, features: Features): Promise<void> {
983 const deadline = await $.store.get(keepwarmKey(await $.session.id()))
984 if (typeof deadline === 'number' && deadline > (await $.clock.now())) await keepwarm_arm($, features, deadline, false)
985}
986
987async function keepwarm_command($: EngineInterface, features: Features, arg: string): Promise<{ text: string }> {
988 if (arg === 'off') {
989 await keepwarm_stop($, null)
990 return { text: 'Keep-warm off.' }
991 }
992 if (arg === '') return { text: warmBox.deadline == null ? 'Keep-warm is off. Usage: /orc keepwarm <2h|90m|off>' : `Keep-warm is on for ${Math.max(1, Math.round((warmBox.deadline - (await $.clock.now())) / 60_000))} more minutes.` }
993 const ms = parseDuration(arg)
994 if (ms == null) return { text: 'Usage: /orc keepwarm <2h|90m|1h30m|off>' }
995 await keepwarm_arm($, features, (await $.clock.now()) + ms, true)
996 return { text: `Keep-warm on for ${arg}: a one-word ping about every ${Math.round(pingEvery(features.cacheTtlMs) / 60_000)} minutes keeps the prompt cache warm (cache reads, not re-writes).` }
997}
998
999// --- CI watcher (one poller across sessions, via a $.store lease) ----------
1000let ciBusy = false
1001
1002async function ci_tick($: EngineInterface): Promise<void> {
1003 if (ciBusy) return
1004 ciBusy = true
1005 try {
1006 const session = parseSession(await orc_state($, ['get']))
1007 const prs = (session?.linkedPRs ?? []).filter(p => p.url)
1008 if (!prs.length) return
1009 const sid = await $.session.id()
1010 for (const pr of prs) {
1011 const key = 'ci:' + pr.url
1012 const label = pr.number ?? (pr.url as string)
1013 const now = await $.clock.now()
1014 const rec = ((await $.store.get(key)) ?? {}) as CiRecord
1015 const settled = rec.summary && rec.summary.state !== 'pending' && rec.checkedAt !== undefined && now - rec.checkedAt < SETTLED_MS
1016 if (!mayPoll(rec.lease, sid, now) || settled) {
1017 if (rec.summary) $.ui.status(statusLine(label, rec.summary))
1018 continue
1019 }
1020 await $.store.set(key, { ...rec, lease: { sid, until: now + LEASE_MS } })
1021 // The URL resolves from any directory; a bare number needs the cwd's remote.
1022 const r = await $.process.run(['gh', 'pr', 'checks', String(pr.url ?? label), '--json', 'name,bucket'], { timeoutMs: 20000 })
1023 const summary = summarizeChecks(r.stdout)
1024 const fresh = ((await $.store.get(key)) ?? {}) as CiRecord
1025 const kind = alertFor(fresh.summary, summary, fresh.notified)
1026 await $.store.set(key, { lease: { sid, until: now + LEASE_MS }, summary, checkedAt: now, notified: kind ? signature(summary) : fresh.notified })
1027 $.ui.status(statusLine(label, summary))
1028 if (kind === 'red') {
1029 ciBox.alert = { pr: label, summary }
1030 $.ui.toast(`CI red on #${label}: ${summary.failing.join(', ')} — /orc:ci to diagnose`)
1031 await $.prompt.suggest({ text: '/orc:ci ' + label })
1032 if (alertsSound) await $.audio.play({ asset: 'hooks/mod/chime.wav' })
1033 } else if (kind === 'green') {
1034 ciBox.alert = null
1035 $.ui.toast(`CI green on #${label}`)
1036 if (alertsSound) await $.audio.play({ asset: 'hooks/mod/chime.wav' })
1037 }
1038 $.ui.invalidate('ui.render')
1039 }
1040 } catch {
1041 // gh missing, offline, not authenticated: stay quiet and try next tick
1042 } finally {
1043 ciBusy = false
1044 }
1045}
1046
1047// The one band above the prompt: orc offers rows, pickBand keeps the
1048// highest-priority one. No orc row (or a survey) leaves the engine's drawing alone.
1049function register_band(on: On, features: Features) {
1050 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1051 if (e.props.hasSurvey) return next(e)
1052 const ci: BandRow | null = ciBox.alert ? { kind: 'ci', pr: ciBox.alert.pr, failing: ciBox.alert.summary.failing } : null
1053 const progress = features.progressBand ? await progress_row($, features) : null
1054 const guard: BandRow | null = guardBox.current ? { kind: 'guard', summary: guardBox.current.summary.headline, detail: guardBox.current.summary } : null
1055 const retro = retro_row(features)
1056 const cache = await cache_row($, features, !e.props.isWorking)
1057 const row = pickBand([ci, guard, sentinel_row(features), retro, cache, progress])
1058 if (!row) return next(e)
1059 const below = await next(e)
1060 const els = $.ui.resolve(e)
1061 const mine = draw_band_row($, e, els, row)
1062 return els.Box({ flexDirection: 'column', children: [mine, below] })
1063 })
1064}
1065
1066async function progress_row($: EngineInterface, features: Features): Promise<BandRow | null> {
1067 const snap = await $.state.get(SNAPSHOT_REF).then(r => r.value ?? EMPTY, () => EMPTY)
1068 const ledger = await $.state.get(LEDGER_REF).then(r => r.value ?? LEDGER_INITIAL, () => LEDGER_INITIAL)
1069 const model = progressModel(snap, ledger)
1070 if (!model) return null
1071 const replay = features.replay && model.phase >= 6 && (await replay_state($)).edits.length > 0
1072 return { kind: 'progress', model, ...(replay ? { replay } : {}) }
1073}
1074
1075// A band Button label stays short so a docked cockpit (about 63 columns) never truncates it mid-word.
1076const BUTTON_MAX = 12
1077
1078// One row, drawn for the surface: SVG strip + real Buttons on rich surfaces, text elsewhere.
1079function draw_band_row($: EngineInterface, e: { surface: RenderSurface | null; props: { bodyColumns: number } }, els: Els, row: BandRow) {
1080 if (row.kind === 'ci') {
1081 const actions = {
1082 diagnose: () => { $.prompt.fill({ text: '/orc:ci ' + row.pr }).catch(() => undefined) },
1083 dismiss: () => { ciBox.alert = null; $.ui.invalidate('ui.render') },
1084 }
1085 if (isRich(e.surface) && 'Svg' in els) {
1086 return els.Box({ flexDirection: 'row', columnGap: 2, children: [
1087 els.Svg({ source: fitSvg(ciSvg(row, px(e.props.bodyColumns))) ?? '', alt: ciAlt(row), height: 28 }),
1088 els.Button({ key: 'ci-diagnose', label: 'Diagnose', onPress: actions.diagnose }),
1089 els.Button({ key: 'ci-dismiss', label: 'Dismiss', onPress: actions.dismiss }),
1090 ] })
1091 }
1092 return ciText(els, row, actions)
1093 }
1094 if (row.kind === 'guard') {
1095 const source = row.detail && isRich(e.surface) && 'Svg' in els ? guardSvg(row.detail, e.props.bodyColumns) : null
1096 return source && 'Svg' in els
1097 ? els.Svg({ source, alt: row.summary, width: px(e.props.bodyColumns) })
1098 : bandLine(els, '⚠ ' + row.summary, 'yellow', [])
1099 }
1100 if (row.kind === 'cache') {
1101 const warm = warmBox.deadline == null ? () => { $.prompt.fill({ text: '/orc keepwarm 1h' }).catch(() => undefined) } : null
1102 const source = isRich(e.surface) && 'Svg' in els ? fitSvg(cacheSvg(row, px(e.props.bodyColumns))) : null
1103 if (source && 'Svg' in els) {
1104 return els.Box({ flexDirection: 'row', columnGap: 2, children: [
1105 els.Svg({ source, alt: cacheAlt(row), height: 28 }),
1106 ...(warm ? [els.Button({ key: 'cache-warm', label: 'Keep warm', onPress: warm })] : []),
1107 ] })
1108 }
1109 return cacheText(els, row, warm)
1110 }
1111 if (row.kind === 'sentinel') {
1112 const note = { id: row.id, text: row.text }
1113 const expanded = sentinelBox.learn?.id === row.id ? sentinelBox.learn.text : null
1114 const actions: SentinelActions = {
1115 learn: () => { void sentinel_learn($, row.id).catch(() => undefined) },
1116 chat: () => { $.prompt.fill({ text: `Sentinel note on slice ${sentinel_card(row.id)?.slice ?? '?'}: ${row.text} — please check.` }).catch(() => undefined) },
1117 dismiss: () => { void sentinel_dismiss($, row.id).catch(() => undefined) },
1118 }
1119 const source = isRich(e.surface) && 'Svg' in els ? sentinelSvg(note, e.props.bodyColumns) : null
1120 if (!source || !('Svg' in els)) return sentinelText(els, note, actions, expanded)
1121 return els.Box({ flexDirection: 'column', children: [
1122 els.Box({ flexDirection: 'row', columnGap: 2, children: [
1123 els.Svg({ source, alt: sentinelAlt(note), height: 28 }),
1124 els.Button({ key: 'sentinel-learn', label: 'Learn more', onPress: actions.learn }),
1125 els.Button({ key: 'sentinel-chat', label: 'Chat in main session', onPress: actions.chat }),
1126 els.Button({ key: 'sentinel-dismiss', label: 'Dismiss', hotkey: 'x', onPress: actions.dismiss }),
1127 ] }),
1128 ...(expanded ? [els.Text({ dimColor: true, children: [expanded] })] : []),
1129 ] })
1130 }
1131 if (row.kind === 'retro') {
1132 const actions: RetroActions = {
1133 save: () => { void retro_save($, row.rule, row.id).then(m => $.ui.toast(m)).catch(() => undefined) },
1134 edit: () => { $.prompt.fill({ text: `/orc retro save "${row.rule}"` }).catch(() => undefined) },
1135 skip: () => { void retro_skip($, row.id).catch(err => { if (err instanceof Error && err.message === UNREADABLE) $.ui.toast(UNREADABLE) }) },
1136 }
1137 const source = isRich(e.surface) && 'Svg' in els ? fitSvg(retroSvg(row, px(e.props.bodyColumns))) : null
1138 if (source && 'Svg' in els) return els.Box({ flexDirection: 'row', columnGap: 2, children: [els.Svg({ source, alt: retroAlt(row), height: 28 }), ...retroButtons(els, actions)] })
1139 return retroText(els, row, actions)
1140 }
1141 if (row.kind === 'progress') {
1142 const m = row.model
1143 const next = m.next
1144 const go = next ? [els.Button({ key: 'orc-next', hotkey: '1', label: next.length > BUTTON_MAX ? next.slice(0, BUTTON_MAX - 1) + '…' : next, onPress: () => { $.prompt.fill({ text: next }).catch(() => undefined) } })] : []
1145 const source = isRich(e.surface) && 'Svg' in els ? fitSvg(progressSvg(m, px(e.props.bodyColumns))) : null
1146 const again = row.replay ? [els.Button({ key: 'orc-replay', hotkey: 'r', label: 'Replay', onPress: () => { open_replay($).catch(() => undefined) } })] : []
1147 if (!(source && 'Svg' in els)) return bandLine(els, progressText(m, e.props.bodyColumns), undefined, [...go, ...again])
1148 return els.Box({ flexDirection: 'row', columnGap: 2, children: [els.Svg({ source, alt: progressAlt(m), height: 28 }), ...go, ...again] })
1149 }
1150 return els.Text({ children: [] })
1151}
1152
1153// --- /orc cockpit -----------------------------------------------------------
1154// A dashboard pane drawn from $.state, no model turn: header strip, phase
1155// ladder beside the slice ledger. Where nothing can draw (VS Code, claude -p)
1156// it answers with a text summary.
1157function register_cockpit(on: On, fallbackProfile: Profile, features: Features) {
1158 on('command.run', { command: 'orc' }, async ($, e) => {
1159 await refresh($).catch(() => undefined)
1160 if (e.args.trim() === 'replay') return replay_command($, features)
1161 if (/^keepwarm(\s|$)/.test(e.args.trim())) return keepwarm_command($, features, e.args.trim().slice(8).trim())
1162 if (/^retro(\s|$)/.test(e.args.trim())) return retro_command($, e.args.trim().slice(5).trim())
1163 // `/orc radius` opens the cockpit with the ship-radius section already expanded.
1164 if (e.args.trim() === 'radius') {
1165 try {
1166 await $.state.set(SECTIONS_REF, { ...((await $.state.get(SECTIONS_REF)).value ?? SECTIONS_INITIAL), radius: true })
1167 await load_details($, 'radius')
1168 } catch { /* the pane opens with the section as it was */ }
1169 }
1170 const snap = await $.state.get(SNAPSHOT_REF).then(r => r.value ?? EMPTY, () => EMPTY)
1171 // A plain `claude -p` run has no surface (ui.open still reports "placed").
1172 if ((await $.session.surfaces()).length) {
1173 try {
1174 if ((await $.ui.open({ id: PANE, title: 'orc', focus: true, closeOnEscape: true, rows: 16, columns: 76 })).isPlaced) return {}
1175 } catch {
1176 // the pane was refused: fall through to the text answer
1177 }
1178 }
1179 return { text: summaryText(snap) }
1180 })
1181
1182 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
1183 if (e.requestId === REPLAY_PANE) return draw_replay($, e, $.ui.resolve(e), await replay_state($))
1184 if (e.requestId !== PANE) return next(e)
1185 const snap = (await $.state.get(SNAPSHOT_REF)).value ?? EMPTY
1186 const sections = (await $.state.get(SECTIONS_REF)).value ?? SECTIONS_INITIAL
1187 const details = (await $.state.get(DETAILS_REF)).value ?? DETAILS_INITIAL
1188 const ledger = (await $.state.get(LEDGER_REF)).value ?? LEDGER_INITIAL
1189 const now = await $.clock.now().catch(() => 0)
1190 const agents = agentRows(ledger, costOf, now)
1191 const radius = (await $.state.get(RADIUS_REF)).value ?? RADIUS_INITIAL
1192 const touched = touchedRows((await $.state.get(TOUCHED_REF)).value ?? TOUCHED_INITIAL, now)
1193 const shotMode = pixelTerminal(await $.env.get('TERM_PROGRAM').catch(() => undefined), await $.env.get('KITTY_WINDOW_ID').catch(() => undefined)) ? 'image' as const : 'raster' as const
1194 const model = { snap, sections, details, agents, touched, radius, shotMode, retroPending: retro_pending_items(features).length, rich: isRich(e.surface), ciAlert: ciBox.alert, profile: profileOf(snap, fallbackProfile), placement: e.props.placement, bodyColumns: e.props.bodyColumns }
1195 return drawPane($.ui.resolve(e), model, {
1196 resume: () => { $.prompt.fill({ text: snap.session ? '/orc:resume' : '/orc:flow ' }) },
1197 toggle: (id: SectionId) => async () => {
1198 try {
1199 const current = (await $.state.get(SECTIONS_REF)).value ?? SECTIONS_INITIAL
1200 await $.state.set(SECTIONS_REF, { ...current, [id]: !current[id] })hooks/mod/api.ts 18 lines1// The value behind $.orc.status(): a pure summary of the live snapshot.
2import type { OrcStatusInfo } from '../../types'
3import { isDone, policyOf, type Snapshot } from './cockpit'
4
5export function statusInfo(snap: Snapshot): OrcStatusInfo {
6 const s = snap.session
7 const pr = s?.linkedPRs?.[0]
8 return {
9 phase: s ? s.phase : null,
10 phaseLabel: s?.phaseLabel ?? null,
11 slicesDone: snap.slices.filter(isDone).length,
12 slicesTotal: snap.slices.length,
13 qa: snap.qa?.verdict ?? null,
14 pr: pr ? (pr.number ?? pr.url ?? null) : null,
15 policy: policyOf(snap) ?? null,
16 }
17}
18hooks/mod/companions.ts 9 lines1// Which companion mods are loaded, judged from the plugin names engine.create reports.
2export type Companions = { skins: boolean; filetree: boolean; reflect: boolean; youShouldKnow: boolean; terminalBrowser: boolean }
3export const COMPANIONS_NONE: Companions = { skins: false, filetree: false, reflect: false, youShouldKnow: false, terminalBrowser: false }
4const has = (names: readonly string[], re: RegExp) => names.some(n => re.test(n))
5export const companionsOf = (names: readonly string[]): Companions => ({
6 skins: has(names, /^(claude-)?skins$/), filetree: has(names, /filetree/), reflect: has(names, /^(claude-)?reflect(-mod)?$/),
7 youShouldKnow: has(names, /you-should-know/), terminalBrowser: has(names, /^terminal-browser$/),
8})
9hooks/mod/band.ts 36 lines1import type { GuardSummary } from './guard/measure'
2import type { ProgressModel } from './progress/model'
3import type { Els } from './pane'
4
5// The one orc row above the prompt: every feature offers a row, the highest
6// priority wins. Pure — register.ts draws it.
7export type BandRow =
8 | { kind: 'ci'; pr: number | string; failing: string[] }
9 | { kind: 'guard'; summary: string; detail?: GuardSummary }
10 | { kind: 'sentinel'; id: string; text: string }
11 | { kind: 'retro'; id: string; rule: string; seen: number }
12 | { kind: 'cache'; minutesLeft: number; rewriteUsd: number | null; tokens: number; waitingOn: string | null }
13 | { kind: 'progress'; model: ProgressModel; replay?: boolean }
14
15export const PRIORITY: BandRow['kind'][] = ['guard', 'ci', 'sentinel', 'retro', 'cache', 'progress']
16
17export function pickBand(rows: (BandRow | null | undefined)[]): BandRow | null {
18 const present = rows.filter((r): r is BandRow => !!r)
19 for (const kind of PRIORITY) {
20 const row = present.find(r => r.kind === kind)
21 if (row) return row
22 }
23 return null
24}
25
26// One terminal band line: the text truncates at the end and the buttons never
27// shrink, so a docked pane's narrow body never wraps the row or cuts a label.
28export function bandLine(els: Els, text: string, color: string | undefined, buttons: unknown[]) {
29 const { Box, Text } = els
30 // paddingRight keeps the buttons clear of the engine's own band control at the right edge.
31 return Box({ flexDirection: 'row', columnGap: 2, paddingRight: 4, children: [
32 Box({ flexShrink: 1, minWidth: 0, children: [Text({ wrap: 'truncate-end', ...(color ? { color } : {}), children: [text] })] }),
33 Box({ flexShrink: 0, flexDirection: 'row', columnGap: 2, children: buttons as never }),
34 ] })
35}
36hooks/mod/band/ci.ts 31 lines1// The red-CI band row: terminal text, or one SVG strip on rich surfaces. The
2// buttons stay real Buttons beside it (register.ts places them).
3import type { Els } from '../pane'
4import { bandLine } from '../band'
5import { doc, rect, text, textWidth } from '../draw/svg'
6import type { BandRow } from '../band'
7
8export type CiRow = Extract<BandRow, { kind: 'ci' }>
9export type CiActions = { diagnose: () => void; dismiss: () => void }
10
11export const ciLine = (row: CiRow) => `CI red on #${row.pr}: ${row.failing.join(', ')}`
12
13export function ciText(els: Els, row: CiRow, actions: CiActions) {
14 return bandLine(els, '⛔ ' + ciLine(row), 'red', [
15 els.Button({ key: 'ci-diagnose', label: 'Diagnose', onPress: actions.diagnose }),
16 els.Button({ key: 'ci-dismiss', label: 'Dismiss', onPress: actions.dismiss }),
17 ])
18}
19
20export const ciAlt = (row: CiRow) => ciLine(row)
21
22// A 28px strip: red dot, the line. Width is the text plus padding, capped at `width`.
23export function ciSvg(row: CiRow, width: number): string {
24 const line = ciLine(row)
25 const w = Math.min(width, textWidth(line, 13) + 40)
26 const body = rect({ x: 0, y: 2, w, h: 24, r: 12, slot: 'err', opacity: 0.12 }) +
27 `<circle cx="14" cy="14" r="4" class="f-err"/>` +
28 text({ x: 26, y: 18, s: line, size: 13, slot: 'err', weight: 600 })
29 return doc(w, 28, body)
30}
31hooks/mod/draw/svg.ts 37 lines1import { PALETTE, type Slot } from './palette'
2export const SVG_MAX = 131_072
3export const esc = (s: string) => s.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
4export const px = (columns: number) => Math.max(1, Math.round(columns * 8))
5export const textWidth = (s: string, size = 12) => Math.round(s.length * size * 7 / 12)
6const slots = Object.keys(PALETTE) as Slot[]
7const rules = (mode: 'light' | 'dark') => slots.map(k => `.f-${k}{fill:${PALETTE[k][mode]}}.s-${k}{stroke:${PALETTE[k][mode]}}`).join('')
8export const FONT = '-apple-system, BlinkMacSystemFont, Segoe UI, sans-serif'
9export function doc(w: number, h: number, body: string): string {
10 return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" font-family="${FONT}"><style>${rules('light')}@media (prefers-color-scheme: dark){${rules('dark')}}</style>${body}</svg>`
11}
12export const fitSvg = (s: string): string | null => (s.length <= SVG_MAX ? s : null)
13export const rect = (o: { x: number; y: number; w: number; h: number; r?: number; slot: Slot; opacity?: number }) =>
14 `<rect x="${o.x}" y="${o.y}" width="${Math.max(0, o.w)}" height="${o.h}" rx="${o.r ?? 3}" class="f-${o.slot}"${o.opacity != null ? ` opacity="${o.opacity}"` : ''}/>`
15export const text = (o: { x: number; y: number; s: string; size?: number; slot?: Slot; weight?: number; anchor?: 'start' | 'end' | 'middle' }) =>
16 `<text x="${o.x}" y="${o.y}" font-size="${o.size ?? 12}" class="f-${o.slot ?? 'ink'}"${o.weight ? ` font-weight="${o.weight}"` : ''}${o.anchor ? ` text-anchor="${o.anchor}"` : ''}>${esc(o.s)}</text>`
17export function bar(o: { x: number; y: number; w: number; h: number; value: number; slot?: Slot }) {
18 const v = Math.min(1, Math.max(0, o.value))
19 return rect({ x: o.x, y: o.y, w: o.w, h: o.h, slot: 'line' }) + rect({ x: o.x, y: o.y, w: Math.round(o.w * v), h: o.h, slot: o.slot ?? 'ok' })
20}
21export function segments(o: { x: number; y: number; w: number; h: number; done: number; running: number; total: number }) {
22 const n = Math.max(1, o.total), gap = 3, sw = (o.w - gap * (n - 1)) / n
23 return Array.from({ length: n }, (_, i) => rect({ x: Math.round(o.x + i * (sw + gap)), y: o.y, w: Math.round(sw), h: o.h,
24 slot: i < o.done ? 'ok' : i < o.done + o.running ? 'warn' : 'line', opacity: i >= o.done && i < o.done + o.running ? 0.75 : undefined })).join('')
25}
26export function ring(o: { cx: number; cy: number; r: number; value: number; slot?: Slot }) {
27 const v = Math.min(0.999, Math.max(0, o.value)), a = v * 2 * Math.PI
28 const x = o.cx + o.r * Math.sin(a), y = o.cy - o.r * Math.cos(a)
29 return `<circle cx="${o.cx}" cy="${o.cy}" r="${o.r}" fill="none" class="s-line" stroke-width="3"/>` +
30 `<path d="M${o.cx} ${o.cy - o.r}A${o.r} ${o.r} 0 ${v > 0.5 ? 1 : 0} 1 ${x.toFixed(2)} ${y.toFixed(2)}" fill="none" class="s-${o.slot ?? 'ok'}" stroke-width="3" stroke-linecap="round"/>`
31}
32export function chip(o: { x: number; y: number; label: string; tone: Slot }) {
33 const w = textWidth(o.label, 11) + 14
34 return rect({ x: o.x, y: o.y, w, h: 18, r: 9, slot: o.tone, opacity: 0.16 }) + text({ x: o.x + 7, y: o.y + 13, s: o.label, size: 11, slot: o.tone, weight: 600 })
35}
36export const chipWidth = (label: string) => textWidth(label, 11) + 14
37hooks/mod/guard/classify.ts 110 lines1// Pure command classifier for the measured guard. The recognised set matches
2// hooks/scripts/pre-destructive-git-check.sh in kinds, but not in reach: the
3// shell floor also sees through `bash -c '…'` and ssh quotes, while classify
4// treats quoted text as prose, so those commands get the floor's confirmation
5// without a measured summary, by design. The cd/pushd/git -C/
6// subshell scoping is adapted, with changes, from Blast Radius (Apache-2.0, see
7// THIRD-PARTY-LICENSES.md).
8export type GuardKind = 'reset' | 'clean' | 'branch' | 'push'
9export type Guarded = { kind: GuardKind; cwd: string | null; args: string[] }
10
11const SPLIT_PUNCT = new Set([';', '&', '|', '\n'])
12
13// Split on ; & | newline outside quotes; a quoted mention is prose, not a command.
14function splitSegments(cmd: string): string[] {
15 const out: string[] = []
16 let cur = '', quote: string | null = null
17 for (let i = 0; i < cmd.length; i++) {
18 const ch = cmd[i]
19 if (quote) {
20 cur += ch
21 if (ch === '\\' && quote === '"' && i + 1 < cmd.length) cur += cmd[++i]
22 else if (ch === quote) quote = null
23 } else if (ch === '"' || ch === "'") { quote = ch; cur += ch }
24 else if (ch === '\\' && i + 1 < cmd.length) { cur += ch + cmd[++i] }
25 else if (SPLIT_PUNCT.has(ch)) { out.push(cur); cur = '' }
26 else cur += ch
27 }
28 out.push(cur)
29 return out
30}
31
32function tokenize(text: string): string[] {
33 const words: string[] = []
34 const re = /"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+)/g
35 let m: RegExpExecArray | null
36 while ((m = re.exec(text)) !== null) words.push(m[1] ?? m[2] ?? m[3])
37 return words
38}
39
40// '-' = unknown: home (`cd`, `cd ~`, `cd ~/x`) and anything relative to an unknown dir.
41function joinDir(dir: string | null, arg: string | undefined): string {
42 if (arg === undefined || arg === '~' || arg.startsWith('~/')) return '-'
43 if (arg.startsWith('/')) return arg
44 if (dir === '-') return '-'
45 return dir ? `${dir.replace(/\/$/, '')}/${arg}` : arg
46}
47
48const ASSIGN = /^[A-Za-z_][A-Za-z0-9_]*=/
49
50function match(sub: string | undefined, rest: string[], cwd: string | null): Guarded | null {
51 if (sub === 'reset' && rest.includes('--hard')) return { kind: 'reset', cwd, args: rest }
52 if (sub === 'clean' && rest.some(a => /^-[a-eg-zA-Z]*f/.test(a) || a === '--force')) return { kind: 'clean', cwd, args: rest }
53 if (sub === 'branch' && (rest.includes('-D') || (rest.includes('--delete') && rest.includes('--force')))) return { kind: 'branch', cwd, args: rest }
54 if (sub === 'push' && rest.some(a => a === '--force' || a === '-f')) return { kind: 'push', cwd, args: rest }
55 return null
56}
57
58type Step = { hit: Guarded } | { cd: string | null } | null
59
60function segment(raw: string, dir: string | null, pushed: Array<string | null>): Step {
61 const words = tokenize(raw.trim().replace(/^[({]+\s*/, '').replace(/\s*[)}]+$/, ''))
62 while (words.length > 0 && (ASSIGN.test(words[0]) || words[0] === 'command' || words[0] === 'exec' || words[0] === 'then' || words[0] === 'do' || words[0] === '!')) words.shift()
63 const [first, ...args] = words
64 if (first === undefined) return null
65 if (first === 'cd') return { cd: args[0] === '-' ? '-' : joinDir(dir, args[0]) }
66 if (first === 'pushd') { pushed.push(dir); return { cd: joinDir(dir, args[0]) } }
67 if (first === 'popd') return { cd: pushed.length > 0 ? pushed.pop() ?? null : '-' }
68 if (first !== 'git') return null
69 let gitDir = dir, i = 0
70 while (i < args.length && args[i].startsWith('-')) {
71 if (args[i] === '-C' && i + 1 < args.length) { gitDir = joinDir(gitDir, args[i + 1]); i += 2 }
72 else if (args[i] === '-c' && i + 1 < args.length) i += 2
73 else i += 1
74 }
75 const hit = match(args[i], args.slice(i + 1), gitDir)
76 return hit ? { hit } : null
77}
78
79// Trailing `)` count after any trailing redirections: a backwards token scan
80// (a nested-quantifier regex here backtracked exponentially).
81const REDIR_ATTACHED = /^(?:\d*>>?|<)\S+$/, REDIR_OP = /^(?:\d*>>?|<)$/
82function closingParens(raw: string): number {
83 const trailing = (w: string) => { let n = 0; while (n < w.length && w[w.length - 1 - n] === ')') n++; return n }
84 const words = raw.trim().split(/\s+/)
85 const own = trailing(words[words.length - 1] ?? '') // a paren glued to the redirect target still closes
86 while (words.length > 0) {
87 const last = words[words.length - 1]
88 if (REDIR_ATTACHED.test(last)) words.pop()
89 else if (words.length > 1 && REDIR_OP.test(words[words.length - 2])) words.length -= 2
90 else break
91 }
92 return Math.max(own, trailing(words[words.length - 1] ?? ''))
93}
94
95export function classify(cmd: string): Guarded | null {
96 let dir: string | null = null
97 const scopes: Array<string | null> = []
98 const pushed: Array<string | null> = []
99 for (const raw of splitSegments(cmd)) {
100 const opens = raw.match(/^\s*\(+/)?.[0].trim().length ?? 0
101 const closes = closingParens(raw)
102 for (let k = 0; k < opens; k++) scopes.push(dir)
103 const step = segment(raw, dir, pushed)
104 if (step && 'hit' in step) return step.hit
105 if (step) dir = step.cd
106 for (let k = 0; k < closes && scopes.length > 0; k++) dir = scopes.pop() ?? null
107 }
108 return null
109}
110hooks/mod/guard/measure.ts 134 lines1// Read-only measure plans and summaries for the guarded git commands. Pure:
2// the caller runs the argv lists (paths as argv, never shell source) and feeds
3// the stdout strings back in plan order.
4import type { GuardKind } from './classify'
5
6export type GuardSummary = { headline: string; items: string[]; more: number; total: number; add?: number; del?: number }
7
8const ITEM_MAX = 10
9const branchOf = (args: string[]) => {
10 const i = args.indexOf('-D')
11 if (i >= 0) return args[i + 1]
12 return args.filter(a => !a.startsWith('-')).pop()
13}
14
15// `git push` args as [remote] [refspec]. Only the bare forms are measurable:
16// anything that changes what is pushed (--all, --mirror, --tags, --delete,
17// --repo, a refspec with ':' or a third positional) is unknown.
18const PUSH_UNKNOWN = new Set(['--all', '--mirror', '--tags', '--delete', '-d', '--prune', '--repo', '-o', '--push-option', '--receive-pack', '--exec'])
19function pushShape(args: string[]): { remote?: string; branch?: string } | null {
20 if (args.some(a => PUSH_UNKNOWN.has(a) || a.startsWith('--repo=') || a.startsWith('--receive-pack=') || a.startsWith('--exec='))) return null
21 const pos = args.filter(a => !a.startsWith('-'))
22 if (pos.length > 2 || (pos[1] !== undefined && /[:^~\s]/.test(pos[1]))) return null
23 return { remote: pos[0], branch: pos[1] }
24}
25
26const GIT = ['git', '--no-optional-locks']
27
28// `reset --hard <target>`: a plain revision, never an option.
29const resetTarget = (args: string[]) => args.find(a => !a.startsWith('-'))
30
31// Parsed `git clean` args: the -d/-x/-X flags, exclude patterns, and pathspecs.
32function cleanShape(args: string[]) {
33 const flags: string[] = [], excludes: string[] = [], paths: string[] = []
34 let rest = false
35 for (let i = 0; i < args.length; i++) {
36 const a = args[i]
37 if (rest) paths.push(a)
38 else if (a === '--') rest = true
39 else if (a === '--exclude' && i + 1 < args.length) excludes.push('--exclude', args[++i])
40 else if (a.startsWith('--exclude=')) excludes.push(a)
41 else if (/^-[a-zA-Z]+$/.test(a)) {
42 if (/d/.test(a) && !flags.includes('-d')) flags.push('-d')
43 if (/x/.test(a) && !flags.includes('-x')) flags.push('-x')
44 if (/X/.test(a) && !flags.includes('-X')) flags.push('-X')
45 if (a.endsWith('e') && i + 1 < args.length) excludes.push('-e', args[++i])
46 } else if (!a.startsWith('-')) paths.push(a)
47 }
48 return { flags, excludes, paths }
49}
50
51export function measurePlan(kind: GuardKind, args: string[] = []): string[][] {
52 switch (kind) {
53 case 'reset': {
54 const plan = [[...GIT, 'status', '--porcelain', '--untracked-files=no'], [...GIT, 'diff', '--shortstat', 'HEAD']]
55 const target = resetTarget(args)
56 if (target) plan.push(['git', 'rev-list', '--count', '--end-of-options', `${target}..HEAD`])
57 return plan
58 }
59 case 'clean': {
60 const { flags, excludes, paths } = cleanShape(args)
61 return [['git', 'clean', '-n', ...flags, ...excludes, ...(paths.length ? ['--', ...paths] : [])]]
62 }
63 case 'branch': {
64 // The name comes from the model's command: never let it reach git as an
65 // option (`--output=<file>` truncates files before the user is asked).
66 const name = branchOf(args)
67 if (!name || name.startsWith('-')) return []
68 const range = ['--not', 'HEAD', '--remotes', '--not', '--end-of-options', name]
69 return [['git', 'rev-list', '--count', ...range], ['git', 'log', '--oneline', '-n', String(ITEM_MAX), ...range]]
70 }
71 case 'push': {
72 const shape = pushShape(args)
73 if (!shape) return []
74 const plan = [['git', 'rev-parse', '--abbrev-ref', '@{u}'], ['git', 'rev-list', '--count', 'HEAD..@{u}'], ['git', 'log', '--oneline', '-n', String(ITEM_MAX), 'HEAD..@{u}']]
75 if (shape.branch !== undefined) plan.push(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
76 return plan
77 }
78 }
79}
80
81const lines = (s: string | undefined) => (s ?? '').split('\n').map(l => l.trimEnd()).filter(Boolean)
82const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? '' : 's'}`
83const summary = (headline: string, all: string[], total = all.length): GuardSummary =>
84 ({ headline, items: all.slice(0, ITEM_MAX), more: Math.max(0, total - ITEM_MAX), total })
85const UNKNOWN: GuardSummary = { headline: 'Could not measure what this would discard', items: [], more: 0, total: 0 }
86
87const baseOf = (dir: string) => dir.replace(/\/+$/, '').split('/').pop() ?? ''
88
89export function summarize(kind: GuardKind, outputs: string[], args: string[] = [], dir?: string | null): GuardSummary {
90 const out = summarizeKind(kind, outputs, args)
91 const where = dir && dir !== '-' ? baseOf(dir) : ''
92 return where ? { ...out, headline: `${out.headline} · in ${where}` } : out
93}
94
95function summarizeKind(kind: GuardKind, outputs: string[], args: string[]): GuardSummary {
96 switch (kind) {
97 case 'reset': {
98 const files = lines(outputs[0]).map(l => l.slice(3))
99 const stat = outputs[1] ?? ''
100 const out = files.length === 0
101 ? summary('Nothing uncommitted to discard', [])
102 : summary(`Would discard uncommitted changes in ${plural(files.length, 'file')}`, files)
103 const drop = parseInt((outputs[2] ?? '').trim(), 10)
104 if (drop > 0) out.headline += ` · would drop ${plural(drop, 'local commit')}`
105 const add = /(\d+) insertion/.exec(stat), del = /(\d+) deletion/.exec(stat)
106 if (add) out.add = Number(add[1])
107 if (del) out.del = Number(del[1])
108 return out
109 }
110 case 'clean': {
111 const paths = lines(outputs[0]).filter(l => !l.startsWith('Would skip ')).map(l => l.replace(/^Would remove /, ''))
112 return paths.length === 0 ? summary('No untracked paths to delete', []) : summary(`Would delete ${plural(paths.length, 'untracked path')}`, paths)
113 }
114 case 'branch': {
115 const name = branchOf(args), count = parseInt((outputs[0] ?? '').trim(), 10)
116 if (!name || Number.isNaN(count)) return UNKNOWN
117 return count > 0
118 ? summary(`${plural(count, 'commit')} only on ${name} would become unreachable`, lines(outputs[1]), count)
119 : summary(`Every commit on ${name} is reachable from HEAD or a remote`, [])
120 }
121 case 'push': {
122 const upstream = (outputs[0] ?? '').trim(), count = parseInt((outputs[1] ?? '').trim(), 10)
123 if (!upstream || Number.isNaN(count)) return UNKNOWN
124 const shape = pushShape(args)
125 if (!shape) return UNKNOWN
126 if (shape.remote !== undefined && !upstream.startsWith(shape.remote + '/')) return UNKNOWN
127 if (shape.branch !== undefined && (upstream !== `${shape.remote}/${shape.branch}` || (outputs[3] ?? '').trim() !== shape.branch)) return UNKNOWN
128 return count > 0
129 ? summary(`Would drop ${plural(count, 'commit')} from ${upstream}`, lines(outputs[2]), count)
130 : summary(`No remote commits would be lost on ${upstream}`, [])
131 }
132 }
133}
134hooks/mod/guard/svg.ts 25 lines1import { doc, fitSvg, px, rect, text, textWidth } from '../draw/svg'
2import type { GuardSummary } from './measure'
3
4const ROW = 16, SHOWN = 5
5
6const clip = (s: string, w: number) => (textWidth(s, 11) <= w ? s : s.slice(0, Math.max(1, Math.floor(w / (11 * 7 / 12)) - 1)) + '…')
7
8// A card: headline, an added/removed (or severity) change bar, a few items.
9export function guardSvg(s: GuardSummary, columns: number): string | null {
10 const w = px(columns), inner = w - 24
11 const shown = s.items.slice(0, SHOWN)
12 const h = 56 + shown.length * ROW + (s.total > shown.length ? ROW : 0)
13 let body = rect({ x: 0.5, y: 0.5, w: w - 1, h: h - 1, r: 8, slot: 'surface' }) + text({ x: 12, y: 22, s: clip(s.headline, inner), size: 13, weight: 600 })
14 const add = s.add ?? 0, del = s.del ?? 0, sum = add + del
15 if (sum > 0) {
16 const aw = Math.round(inner * add / sum)
17 body += rect({ x: 12, y: 32, w: aw, h: 6, r: 3, slot: 'ok' }) + rect({ x: 12 + aw, y: 32, w: inner - aw, h: 6, r: 3, slot: 'err' })
18 } else {
19 body += rect({ x: 12, y: 32, w: inner, h: 6, r: 3, slot: 'line' }) + rect({ x: 12, y: 32, w: Math.round(inner * Math.min(1, s.total / 20)), h: 6, r: 3, slot: 'err' })
20 }
21 shown.forEach((it, i) => { body += text({ x: 12, y: 56 + i * ROW, s: clip(it, inner), size: 11, slot: 'muted' }) })
22 if (s.total > shown.length) body += text({ x: 12, y: 56 + shown.length * ROW, s: `+${s.total - shown.length} more`, size: 11, slot: 'muted' })
23 return fitSvg(doc(w, h, body))
24}
25hooks/mod/guard/text.ts 10 lines1import type { GuardSummary } from './measure'
2
3// At most 4 notice lines: headline, change stat, then the items on one line.
4export function guardText(s: GuardSummary): string[] {
5 const out = [s.headline]
6 if (s.add != null || s.del != null) out.push(`+${s.add ?? 0} -${s.del ?? 0}`)
7 if (s.items.length > 0) out.push(s.items.slice(0, 5).join(', ') + (s.total > 5 ? ` (+${s.total - 5} more)` : ''))
8 return out.slice(0, 4)
9}
10hooks/mod/draw/surface.ts 3 lines1import type { RenderSurface } from 'claude-code'
2export const isRich = (surface: RenderSurface | null | undefined): boolean => surface != null && surface !== 'terminal'
3hooks/mod/ci.ts 46 lines1// CI watcher logic: summarize `gh pr checks --json name,bucket`, decide when a
2// change deserves an alert, and share one poller across sessions through a
3// lease in $.store (every session on the machine shares it).
4
5export type CiState = 'pass' | 'fail' | 'pending' | 'none'
6export type CiSummary = { state: CiState; failing: string[]; pending: number; total: number }
7export type Lease = { sid: string; until: number }
8export type CiRecord = { lease?: Lease; summary?: CiSummary; checkedAt?: number; notified?: string }
9
10export const POLL_MS = 60_000
11export const LEASE_MS = 90_000
12export const SETTLED_MS = 300_000 // a settled PR is re-checked every 5 minutes (a new push restarts CI)
13
14export function summarizeChecks(json: string): CiSummary {
15 let rows: { name?: string; bucket?: string }[] = []
16 try {
17 rows = JSON.parse(json)
18 } catch {
19 return { state: 'none', failing: [], pending: 0, total: 0 }
20 }
21 if (!Array.isArray(rows) || rows.length === 0) return { state: 'none', failing: [], pending: 0, total: 0 }
22 const failing = rows.filter(r => r.bucket === 'fail' || r.bucket === 'cancel').map(r => String(r.name)).sort()
23 const pending = rows.filter(r => r.bucket === 'pending').length
24 const state: CiState = failing.length ? 'fail' : pending ? 'pending' : 'pass'
25 return { state, failing, pending, total: rows.length }
26}
27
28export const signature = (s: CiSummary) => s.state + ':' + s.failing.join(',')
29
30// Another live session holds the lease: read its result instead of polling.
31export const mayPoll = (lease: Lease | undefined, sid: string, now: number) => !lease || lease.sid === sid || lease.until < now
32
33// Red: failing now, with a failure set not yet alerted. Green: passing after we saw it not pass.
34export function alertFor(prev: CiSummary | undefined, next: CiSummary, notified?: string): 'red' | 'green' | null {
35 if (next.state === 'fail' && notified !== signature(next)) return 'red'
36 if (next.state === 'pass' && prev && prev.state !== 'pass' && notified !== signature(next)) return 'green'
37 return null
38}
39
40export function statusLine(pr: number | string, s: CiSummary): string {
41 if (s.state === 'fail') return `CI #${pr}: ${s.failing.length} failing (${s.failing.join(', ')})`
42 if (s.state === 'pending') return `CI #${pr}: running (${s.pending}/${s.total} pending)`
43 if (s.state === 'pass') return `CI #${pr}: green`
44 return `CI #${pr}: no checks`
45}
46