Development formatting hooks (Go, Shell, Proto, OpenAPI), TDD agents, and skills incl. pi-implementer (a local model implements your Tickets through pi +…

Personal configuration files for Linux development environments. Includes shell, editor, terminal, and Claude Code plugin setup.
flake.nix, home.nix, configuration.nix). (work in progress)dot-zsh-functions/).nvim/).tmux/).wezterm/).claude-plugin/).setup.sh automates stowing configs, installing dependencies, and setting up the environment.This repository also functions as a Gemini CLI extension, providing custom TDD agents, context from GEMINI.md, and specialized development workflows.
From your Terminal:
gemini extensions install https://github.com/Anthony-Bible/dotfiles --auto-update
From within Gemini CLI:
/extensions install https://github.com/Anthony-Bible/dotfiles --auto-update
GEMINI.md for project-specific rules and instructions.This repo acts as a Claude Code plugin marketplace. The dotfiles-dev-tools plugin provides:
gofmt/goimports)shfmt)clang-format)red-phase-tester — writes failing tests before implementationgreen-phase-implementer — writes minimal code to pass teststdd-refactor-specialist — cleans up code after tests go greentdd-review-agent — verifies completeness after refactoringsecurity-auditor — finds vulnerabilities in code1. Add this repo as a marketplace:
claude plugin marketplace add Anthony-Bible/dotfiles
2. Install the plugin:
claude plugin install dotfiles-dev-tools@anthony-bible-dotfiles
Or from within Claude Code interactive mode:
/plugin install dotfiles-dev-tools@anthony-bible-dotfiles
dungeon-buddy is the Buddy mod by itself: /buddy hatches a dungeon pet from your account that sits above the prompt, fidgets, and talks about failed commands and long turns. Install it alone, or beside dotfiles-dev-tools, where it talks back to the System's big moments instead and a Reroll costs Crawler Points:
claude plugin install dungeon-buddy@anthony-bible-dotfiles
The marketplace is defined by .claude-plugin/marketplace.json at the root of this repo. It lists available plugins and points to their source directories.
Each plugin lives in its own subdirectory (e.g., claude-plugin/) and contains:
| Path | Purpose |
|---|---|
.claude-plugin/plugin.json | Plugin metadata (name, version, description) |
hooks/hooks.json | PostToolUse/PreToolUse hooks with shell commands |
agents/*.md | Custom agents with frontmatter metadata |
.mcp.json | MCP servers bundled with the plugin |
.lsp.json | LSP servers bundled with the plugin |
When Claude Code installs a plugin, it copies the plugin directory to ~/.claude/plugins/cache/<marketplace>/<plugin>/<version>/ and activates hooks, agents, MCP servers, and LSP servers from that directory. The ${CLAUDE_PLUGIN_ROOT} environment variable is set to the installed plugin path at runtime.
.claude-plugin/
marketplace.json # Marketplace index listing all plugins
dungeon-buddy/ # dungeon-buddy plugin source (the Buddy mod)
claude-plugin/ # dotfiles-dev-tools plugin source
.claude-plugin/
plugin.json # Plugin metadata
hooks/
hooks.json # Auto-format hooks (PostToolUse)
agents/
red-phase-tester.md
green-phase-implementer.md
tdd-refactor-specialist.md
tdd-review-agent.md
security-auditor.md
scripts/
goformat.sh
shellformat.sh
protoformat.sh
openapi-lint.sh
format-common.sh
.mcp.json # MCP servers (sequential-thinking)
.lsp.json # LSP servers (gopls)
# List all registered marketplaces
claude plugin marketplace list
# Update marketplace plugin listings
claude plugin marketplace update anthony-bible-dotfiles
# Remove the marketplace
claude plugin marketplace remove anthony-bible-dotfiles
# Validate the plugin/marketplace structure
claude plugin validate .
.claude-plugin/ # Claude Code marketplace definition
claude-plugin/ # Claude Code plugin (dotfiles-dev-tools)
configuration.nix # NixOS or Home Manager configuration
flake.nix # Nix flake for reproducible setup
home.nix # Home Manager user configuration
setup.sh # Setup and bootstrap script
.lsp.json # Global LSP configuration (gopls)
.mcp.json # Global MCP server configuration
dot-oh-my-zsh/ # Oh My Zsh themes and customizations
dot-zsh-functions/ # Custom Zsh functions and widgets
nvim/ # Neovim configuration (Lua)
tmux/ # Tmux and tmuxp configuration
wezterm/ # WezTerm configuration
The dot-zsh-functions/ directory enhances the shell experience:
dot-zsh-functions: Aliases, environment variables, and CheckIfDotDirFilesChanged.dot-ai-functions: AI-powered shell helpers via Claude:command_not_found_handler: Suggests commands for unknown input.explain / explain:: Explains a given command.Alt-e ZLE widget: Sends current command line to Claude and replaces it with the result.ai_commit_msg / Alt-g: Generates commit messages from staged changes using fzf + Claude.dot-tcn-functions: Work-specific helpers (DokuWiki, PostgreSQL, Kamailio, GCP IAM).sh git clone https://github.com/Anthony-Bible/dotfiles.git cd dotfiles ``sh ./setup.sh ``sh nix run .#homeConfigurations.$USER.activationPackage ``MIT License. See individual files for copyright.
hooks/register.tsx 1120 lines1// The plugin's function hooks (mods). The command hooks in hooks.json (the formatters) are separate.
2//
3// Dispatch Board: a pane listing pi-implementer's Dispatches on the current run branch, live while they run.
4// It reads what pi-dispatch.py leaves under .hybrid/ and never writes there. /dispatches opens it; it also
5// opens by itself when a Dispatch starts.
6//
7// Crawler Points: the System scores the session. Test/build runs, git milestones, tool errors and the
8// Dispatch fates the board notices add or take points; the status line shows the score, and a toast written
9// by a small model in the System's voice announces each award.
10//
11// Podman Guard: a Bash line that runs `docker` runs `podman` instead, with a note the model reads; a Daemon-Only
12// Command is refused; a DOCKER_OK=1 line passes untouched.
13//
14// TDD Band: above the prompt, the TDD Phase that TDD subagents and Checks lead to, with buttons that draft a
15// prompt for each TDD subagent. /tdd shows or hides it.
16//
17// The System's voice: Spinner Words in the terminal, and a Verdict under each Notable Turn's answer.
18//
19// Branch Guard: a git commit on a Protected Branch, or a push that lands on one, is refused; a BRANCH_OK=1
20// line passes untouched.
21//
22// Floor Boss: three red runs in a row of one Check command summon a named boss above the prompt, its HP the
23// failing-test count; that command's next green run slays it for 100 CP and an Achievement.
24//
25// Sponsor Mail: once `gh pr create` succeeds (or /watch-pr), the Watched PR's checks and new comments show above
26// the prompt, polled without a turn; Mail and red checks raise a notification and a button that queues the turn.
27//
28// Beast Watch: woken by the session's first use of Beast (or /beast), Beast's health rides the HUD and its going
29// Down is notified; the Beast Guard refuses a Dispatch while Beast is Down and holds one while it is Loading.
30//
31// Cues: the show's big moments, written to the `cue` state for other mods to hear (dungeon-buddy's Buddy talks
32// back to them); the Buddy's own Cues, a Reroll and a legendary Hatch, are priced in Crawler Points here.
33//
34// Every use of `$` lives in this file (the engine follows `$` into this file's functions, never across an
35// import); the rules are in ../mods/*.ts.
36
37import { atom, read, update } from 'claude-code'
38import type { EngineInterface, Register } from 'claude-code'
39
40import {
41 boardRows,
42 completeLines,
43 ctxSizeOf,
44 duration,
45 emptyCounts,
46 foldPiEvents,
47 kilo,
48 parseJsonl,
49 tail,
50 type DispatchRow,
51 type LiveCounts,
52 type Outcome,
53 type RunningMeta,
54} from '../mods/board'
55import {
56 apply,
57 bashAwards,
58 cleanQuip,
59 compactAward,
60 dispatchAward,
61 errorAward,
62 fallbackToast,
63 QUIP_SYSTEM,
64 quipPrompt,
65 statusLine,
66 type Award,
67 type Fate,
68 type Usage,
69} from '../mods/points'
70import { bossToast, checkKey, failingCount, hpBar, initialBosses, newestBoss, onBossCheck, slayAward } from '../mods/boss'
71import { branchGuard, gitSteps, type Repo } from '../mods/branch'
72import { guard, rewriteNote } from '../mods/podman'
73import { DRAFTS, initialTdd, isShown, onAgent, onCheck, toggle, verdictOf } from '../mods/tdd'
74import {
75 addressPrompt,
76 answeredAward,
77 claimMine,
78 createDirOf,
79 fixPrompt,
80 isPost,
81 isPrCreate,
82 mailNotice,
83 mergeAward,
84 nextPollMs,
85 parsePr,
86 prQueryArgv,
87 prRefOf,
88 redAward,
89 redNotice,
90 startWatch,
91 step,
92 tally,
93 type MailEvent,
94 type MailWatch,
95 type Pr,
96} from '../mods/mail'
97import {
98 beastGuard,
99 beastSegment,
100 completionOf,
101 healthOf,
102 hostOf,
103 isBeastUse,
104 isIdle,
105 isGuarded,
106 judge,
107 llamaKeyOf,
108 llamaUrlOf,
109 LOADING_WAIT_MS,
110 modelAliasOf,
111 modelStateOf,
112 SMI_QUERY,
113 transition,
114 type Probe,
115 type Reading,
116} from '../mods/beast'
117import {
118 fallbackVerdict,
119 isNotable,
120 moodOf,
121 spinnerWord,
122 VERDICT_SYSTEM,
123 verdictLine,
124 verdictPrompt,
125 type TurnStats,
126} from '../mods/voice'
127import { awardOfBuddyCue, cueOfAward, type Cue } from '../mods/cue'
128import type {
129 BeastWatchState,
130 BoardRowState,
131 BoardState,
132 BossesState,
133 CrawlerScore,
134 CueState,
135 MailWatchState,
136 TddState,
137} from '../types'
138
139// ---------------------------------------------------------------------------------------------- state
140
141const board = atom({ plugin: 'dotfiles-dev-tools', key: 'board' } as const, null)
142const score = atom({ plugin: 'dotfiles-dev-tools', key: 'score' } as const, { session: 0, streak: 0 })
143const allTime = atom({ plugin: 'dotfiles-dev-tools', key: 'allTime' } as const, 0)
144const tdd = atom({ plugin: 'dotfiles-dev-tools', key: 'tdd' } as const, initialTdd as TddState)
145const bosses = atom({ plugin: 'dotfiles-dev-tools', key: 'bosses' } as const, initialBosses as BossesState)
146const mailWatch = atom({ plugin: 'dotfiles-dev-tools', key: 'mailWatch' } as const, null as MailWatchState | null)
147const beast = atom({ plugin: 'dotfiles-dev-tools', key: 'beast' } as const, { isAwake: false } as BeastWatchState)
148const cue = atom({ plugin: 'dotfiles-dev-tools', key: 'cue' } as const, { n: 0 } as CueState)
149
150const PANE = 'dispatch-board'
151const TITLE = 'Dispatch Board'
152const POLL_MS = 2000
153
154const STORE_ALL_TIME = 'crawler-points.allTime'
155const STORE_UNLOCKED = 'crawler-points.unlocked'
156const QUIP_MODEL = 'haiku'
157/** At most one quip call in flight, and none sooner than this after the last one began. */
158const QUIP_GAP_MS = 8000
159const TOAST_MS = 6000
160/** A model-written quip is a full sentence of up to 140 characters: it stays long enough to read. */
161const QUIP_TOAST_MS = 15000
162/** The answer's line waits on the Verdict, so its model call gets less time than a toast's quip. */
163const VERDICT_TIMEOUT_MS = 5000
164
165type Watch = {
166 root: string
167 ctxLimit?: number
168 /** Per live log: bytes folded so far and the counts they gave. */
169 logs: Map<string, { bytes: number; counts: LiveCounts }>
170 running: Set<number>
171 /** Size of outcomes.jsonl / dispatches.jsonl at the last full read; undefined before the first. */
172 sizes: { outcomes?: number; dispatches?: number }
173 /** Lines already seen, so only later ones become Fates; undefined before the baseline read. */
174 seen: { outcomes?: number; dispatches?: number }
175 /** The .json names under .hybrid/running/ at the last full read, so a leftover one is read once. */
176 runFiles?: string
177}
178
179// Module variables: a hot reload starts them over (session.start runs again and re-baselines the board),
180// which costs at most an early quip or a second "first check" of the session.
181let watch: Watch | undefined
182let isTicking = false
183let hasChecked = false
184let isQuipBusy = false
185let quipAt = -Infinity
186/** The session's usage as the last `session.measure` reported it, for the HUD. */
187let usage: Usage | undefined
188/** The main loop's turn in progress: what it scored and how many tool calls it made; undefined between turns. */
189let turn: Omit<TurnStats, 'durationMs'> | undefined
190/** This turn's Spinner Word, picked once at its start so the spinner does not flicker between words. */
191let spinner: string | undefined
192/** Sponsor Mail: when the Watched PR is next looked at, and the looks and posts in flight. */
193let mailDueAt = 0
194let mailLooks = 0
195let posting = 0
196/** Bumped when a post starts: a look begun before it may predate Claude's comment and is thrown away. */
197let postGen = 0
198/** Beast Watch: its timer, whether a look is in flight, and Beast's host for waking on use. */
199let beastTimer: { cancel: () => void } | undefined
200let isBeastLooking = false
201/** The last Award's banking onto the stored all-time total; the next one waits on it. */
202let banking: Promise<unknown> = Promise.resolve()
203let beastTickCount = 0
204let beastHost: string | undefined
205
206// ------------------------------------------------------------------------------------- Dispatch Board
207
208async function readText($: EngineInterface, path: string): Promise<string> {
209 return (await $.fs.exists(path)) ? String(await $.fs.read(path)) : ''
210}
211
212async function sizeOf($: EngineInterface, path: string): Promise<number> {
213 return (await $.fs.exists(path)) ? (await $.fs.stat(path)).size : 0
214}
215
216/** The main checkout's root, also from inside a Worktree, as pi-dispatch.py finds it. */
217async function mainRoot($: EngineInterface): Promise<string | undefined> {
218 const r = await $.process.run(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'])
219 if (r.exitCode !== 0) return undefined
220 const dir = r.stdout.trim()
221 return dir.slice(0, dir.lastIndexOf('/')) || undefined
222}
223
224async function ctxLimitOf($: EngineInterface): Promise<number | undefined> {
225 const r = await $.process.run([
226 'sh',
227 '-c',
228 'cat "${PI_IMPLEMENTER_HOME:-$HOME/.config/pi-implementer}/env" 2>/dev/null',
229 ])
230 return ctxSizeOf(r.stdout)
231}
232
233async function livePids($: EngineInterface, pids: readonly number[]): Promise<Set<number>> {
234 if (pids.length === 0) return new Set()
235 const r = await $.process.run(['ps', '-o', 'pid=', '-p', pids.join(',')])
236 return new Set(
237 r.stdout
238 .split('\n')
239 .map(Number)
240 .filter(n => n > 0),
241 )
242}
243
244/** Folds whatever the log gained since the last read into its counts; a torn last line waits. */
245async function followLog($: EngineInterface, w: Watch, log: string): Promise<LiveCounts> {
246 const held = w.logs.get(log) ?? { bytes: 0, counts: emptyCounts() }
247 const r = await $.process.run(['tail', '-c', `+${held.bytes + 1}`, `${w.root}/${log}`])
248 const { text, bytes } = completeLines(r.exitCode === 0 ? r.stdout : '')
249 const next = { bytes: held.bytes + bytes, counts: foldPiEvents(held.counts, parseJsonl(text)) }
250 w.logs.set(log, next)
251 return next.counts
252}
253
254/** The running Dispatches: a `.json` beside a live `.pid` under .hybrid/running/. */
255async function runningMetas($: EngineInterface, w: Watch): Promise<RunningMeta[]> {
256 const dir = `${w.root}/.hybrid/running`
257 if (!(await $.fs.exists(dir))) return []
258 const names = (await $.fs.list(dir)).map(e => e.name)
259 const pids = new Map<number, number>()
260 for (const name of names.filter(n => n.endsWith('.pid'))) {
261 const pid = Number((await readText($, `${dir}/${name}`)).trim())
262 if (pid > 0) pids.set(Number(name.slice(0, -4)), pid)
263 }
264 const live = await livePids($, [...pids.values()])
265 const metas: RunningMeta[] = []
266 for (const name of names.filter(n => n.endsWith('.json'))) {
267 const meta = parseJsonl<RunningMeta>(await readText($, `${dir}/${name}`))[0]
268 const pid = meta && pids.get(meta.n)
269 if (meta && pid !== undefined && live.has(pid)) metas.push(meta)
270 }
271 return metas
272}
273
274/** Re-reads .hybrid/ and redraws; answers the Fates that appeared and the Dispatches that started. */
275async function refresh($: EngineInterface, w: Watch): Promise<{ fates: Fate[]; started: number[] }> {
276 const hybrid = `${w.root}/.hybrid`
277 const branch = (
278 await $.process.run(['git', '-C', w.root, 'rev-parse', '--abbrev-ref', 'HEAD'])
279 ).stdout.trim()
280 const now = await $.clock.now()
281
282 // Every live Dispatch is tracked, so one already running is not "started" again when the checkout comes
283 // back to its branch; only this run branch's are followed, shown and auto-opened for.
284 const live = await runningMetas($, w)
285 const metas = live.filter(m => m.run_branch === branch)
286 const running = []
287 for (const meta of metas) running.push({ meta, counts: await followLog($, w, meta.log), nowMs: now })
288 for (const log of [...w.logs.keys()]) if (!metas.some(m => m.log === log)) w.logs.delete(log)
289
290 const finished = parseJsonl<DispatchRow>(await readText($, `${hybrid}/dispatches.jsonl`))
291 const outcomes = parseJsonl<Outcome>(await readText($, `${hybrid}/outcomes.jsonl`))
292 const present = new Set<string>()
293 for (const r of finished) {
294 if (r.run_branch === branch && (await $.fs.exists(r.worktree))) present.add(r.worktree)
295 }
296
297 const ticketOf = (n: number) => finished.find(r => r.n === n)?.ticket ?? `#${n}`
298 const fates: Fate[] = [
299 ...(w.seen.outcomes === undefined ? [] : outcomes.slice(w.seen.outcomes)).map(o => ({
300 fate: o.outcome,
301 ticket: ticketOf(o.n),
302 })),
303 ...(w.seen.dispatches === undefined ? [] : finished.slice(w.seen.dispatches))
304 .filter(r => r.ended === 'timeout' || r.ended === 'turn cap')
305 .map(r => ({ fate: r.ended as 'timeout' | 'turn cap', ticket: r.ticket })),
306 ]
307 w.seen = { outcomes: outcomes.length, dispatches: finished.length }
308
309 const started = metas.map(m => m.n).filter(n => !w.running.has(n))
310 w.running = new Set(live.map(m => m.n))
311
312 const rows = boardRows({ branch, running, finished, outcomes, worktreesPresent: present })
313 await update($, board, (): BoardState => ({ branch, ctxLimit: w.ctxLimit, rows }))
314 return { fates, started }
315}
316
317/** The board's pane, if open: placed (drawn), or waiting undrawn for a wider terminal. */
318async function boardPane($: EngineInterface) {
319 return (await $.ui.panes()).find(p => p.id === PANE)
320}
321
322/**
323 * One poll: cheap stats always; a full read only while a Dispatch runs, the pane is drawn, or a file grew or
324 * came or went. A .json a killed pi-dispatch.py left behind is read once, not every poll.
325 */
326async function tick($: EngineInterface, force: boolean): Promise<void> {
327 const w = watch
328 if (!w || !(await $.fs.exists(`${w.root}/.hybrid`))) return
329 const hybrid = `${w.root}/.hybrid`
330 const sizes = {
331 outcomes: await sizeOf($, `${hybrid}/outcomes.jsonl`),
332 dispatches: await sizeOf($, `${hybrid}/dispatches.jsonl`),
333 }
334 const runningDir = `${hybrid}/running`
335 const runFiles = (await $.fs.exists(runningDir))
336 ? (await $.fs.list(runningDir))
337 .map(e => e.name)
338 .filter(n => n.endsWith('.json'))
339 .sort()
340 .join(',')
341 : ''
342 const hasChanged =
343 sizes.outcomes !== w.sizes.outcomes || sizes.dispatches !== w.sizes.dispatches || runFiles !== w.runFiles
344 const isDrawn = (await boardPane($))?.isPlaced === true
345 if (!(force || hasChanged || w.running.size > 0 || isDrawn)) return
346 w.sizes = sizes
347 w.runFiles = runFiles
348 const { fates, started } = await refresh($, w)
349 for (const fate of fates) await award($, dispatchAward(fate.fate, fate.ticket))
350 if (started.length === 0 || isDrawn) return
351 // Unasked, the pane seats only from 144 columns and otherwise waits undrawn: say so rather than nothing.
352 const pane = (await boardPane($)) ?? (await $.ui.open({ id: PANE, title: TITLE }))
353 if (!pane.isPlaced) {
354 $.ui.toast(`Dispatch #${started.join(', #')} started: /dispatches shows the board`, {
355 timeoutMs: TOAST_MS,
356 })
357 }
358}
359
360async function startBoard($: EngineInterface): Promise<void> {
361 await $.command.register({
362 name: 'dispatches',
363 description: 'Open the Dispatch Board: pi-implementer Dispatches on this run branch',
364 })
365 const root = await mainRoot($)
366 watch = root
367 ? { root, ctxLimit: await ctxLimitOf($), logs: new Map(), running: new Set(), sizes: {}, seen: {} }
368 : undefined
369 isTicking = false
370 $.clock.every(POLL_MS, () => {
371 if (isTicking) return
372 isTicking = true
373 void tick($, false)
374 .catch(() => undefined)
375 .finally(() => {
376 isTicking = false
377 })
378 })
379 await tick($, true).catch(() => undefined) // the baseline: Fates already on disk are not new
380}
381
382const PHASE: Record<BoardRowState['phase'], { label: string; color: string }> = {
383 running: { label: '▶ running', color: 'yellow' },
384 awaiting: { label: '⏸ Gate', color: 'cyan' },
385 landed: { label: '✔ landed', color: 'green' },
386 dropped: { label: '✖ dropped', color: 'gray' },
387 conflict: { label: '⚠ conflict', color: 'red' },
388 gone: { label: '· gone', color: 'gray' },
389}
390
391const stats = (row: BoardRowState, ctxLimit?: number): string =>
392 [
393 row.ended && row.ended !== 'finished' ? row.ended : undefined,
394 duration(row.wallS),
395 `calls ${row.calls}${row.maxTurns ? `/${row.maxTurns}` : ''}`,
396 `tools ${row.tools}`,
397 `ctx ${kilo(row.ctx)}${ctxLimit ? `/${kilo(ctxLimit)}` : ''}`,
398 row.phase === 'running' && row.lastTool ? `last: ${row.lastTool}` : undefined,
399 ]
400 .filter(Boolean)
401 .join(' ')
402
403const TDD_ICON = { RED: '🔴', GREEN: '🟢', REFACTOR: '🔧' } as const
404const TDD_COLOR = { RED: 'red', GREEN: 'green', REFACTOR: 'cyan', NONE: 'gray' } as const
405const MOOD_COLOR = { good: 'green', bad: 'red', waiting: 'gray' } as const
406
407// -------------------------------------------------------------------------------------- Crawler Points
408
409async function showScore($: EngineInterface): Promise<void> {
410 const b = await read($, beast)
411 const hud = statusLine(await read($, score), await read($, allTime), usage)
412 $.ui.status(b.isAwake && b.reading ? `${hud} · ${beastSegment(b.reading)}` : hud)
413}
414
415/** Toasts the award: a model-written line when one is allowed and arrives, the plain line otherwise. */
416async function announce(
417 $: EngineInterface,
418 a: Award,
419 after: CrawlerScore,
420 isNewEver: boolean,
421): Promise<void> {
422 const plain = fallbackToast(a)
423 const now = await $.clock.now()
424 if (isQuipBusy || now - quipAt < QUIP_GAP_MS) return $.ui.toast(plain, { timeoutMs: TOAST_MS })
425 isQuipBusy = true
426 quipAt = now
427 try {
428 const r = await $.model.complete({
429 model: QUIP_MODEL,
430 system: QUIP_SYSTEM,
431 prompt: quipPrompt(a, after) + (isNewEver ? '\nThis achievement is a first, ever.' : ''),
432 maxTokens: 80,
433 effort: 'low',
434 timeoutMs: 8000,
435 })
436 const quip = r.isAnswered ? cleanQuip(r.text) : undefined
437 const points = `(${a.points >= 0 ? '+' : '−'}${Math.abs(a.points)} CP)`
438 $.ui.toast(quip ? `${quip} ${points}` : plain, { timeoutMs: quip ? QUIP_TOAST_MS : TOAST_MS })
439 } catch {
440 $.ui.toast(plain, { timeoutMs: TOAST_MS }) // the model call failed or timed out: the award still shows
441 } finally {
442 isQuipBusy = false
443 }
444}
445
446/** The repository a Branch Guard step runs in, or undefined outside one (or where the directory is unknown). */
447async function repoAt($: EngineInterface, dir: string): Promise<Repo | undefined> {
448 if (/[$`]/.test(dir)) return undefined
449 const home = dir.startsWith('~') ? (await $.process.run(['sh', '-c', 'printf %s "$HOME"'])).stdout : ''
450 const at = home ? home + dir.slice(1) : dir
451 const git = (...args: string[]) => $.process.run(['git', ...(at ? ['-C', at] : []), ...args])
452 const current = await git('branch', '--show-current')
453 if (current.exitCode !== 0) return undefined
454 // An unborn branch (no commits yet) takes its first commit wherever it must, but keeps its name for a push.
455 const isUnborn = (await git('rev-parse', '--verify', '-q', 'HEAD')).exitCode !== 0
456 const head = (await git('symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD')).stdout.trim()
457 return {
458 branch: current.stdout.trim() || undefined,
459 defaultBranch: head ? head.slice(head.indexOf('/') + 1) : undefined,
460 isUnborn,
461 }
462}
463
464/** A Check of `key` finished: the Floor Boss it summons, hurts or heals gets a toast, and one it slays an Award. */
465async function fight($: EngineInterface, key: string, isGreen: boolean, output: string): Promise<void> {
466 const r = onBossCheck(await read($, bosses), key, isGreen, isGreen ? undefined : failingCount(output))
467 await update($, bosses, () => r.bosses)
468 if (!r.event) return
469 if (r.event.kind === 'slain') await award($, slayAward(r.event.boss), { kind: 'boss-slain', name: r.event.boss.name })
470 else $.ui.toast(bossToast(r.event), { timeoutMs: TOAST_MS })
471 if (r.event.kind === 'spawned') await announceCue($, { kind: 'boss-summoned', name: r.event.boss.name })
472}
473
474/** Scores the Award and announces `c` as a Cue, or what the Award itself makes one of; null announces none. */
475async function award($: EngineInterface, a: Award, c?: Cue | null): Promise<void> {
476 if (turn) turn = { ...turn, points: turn.points + a.points, events: [...turn.events, a.event] }
477 const before = await read($, score)
478 const after = await update($, score, s => apply(s, a))
479 const isNewEver = await bank(async () => {
480 // Onto the total as stored now, not as this session last saw it: other sessions bank onto it too.
481 const total = storedTotal(await $.store.get(STORE_ALL_TIME)) + a.points
482 await $.store.set(STORE_ALL_TIME, total)
483 await update($, allTime, () => total)
484 if (!a.achievement) return false
485 const unlocked = ((await $.store.get(STORE_UNLOCKED)) as string[] | undefined) ?? []
486 if (unlocked.includes(a.achievement)) return false
487 await $.store.set(STORE_UNLOCKED, [...unlocked, a.achievement])
488 return true
489 })
490 await showScore($)
491 // Off the caller's dispatch: a tool call never waits on the quip.
492 $.clock.after(0, () => void announce($, a, after, isNewEver).catch(() => undefined))
493 const told = c === undefined ? cueOfAward(a, before, after) : c
494 if (told) await announceCue($, told)
495}
496
497/** Tells the other mods of a big moment of the show. */
498async function announceCue($: EngineInterface, c: Cue): Promise<void> {
499 await update($, cue, s => ({ n: s.n + 1, cue: c }))
500}
501
502/** Writes the Cue as it stands, so another mod reading it knows the System runs this session. */
503async function startCues($: EngineInterface): Promise<void> {
504 await update($, cue, s => ({ ...s }))
505}
506
507const storedTotal = (stored: unknown): number => {
508 const n = Number(stored ?? 0)
509 return Number.isFinite(n) ? n : 0
510}
511
512/**
513 * Runs `fn` after every banking this process started before it: each read-add-write of the stored total
514 * then sees the last one's write. The engine locks each store write across sessions, never a read and the
515 * write after it, so two sessions banking in the same instant can still lose one of the two.
516 */
517function bank<T>(fn: () => Promise<T>): Promise<T> {
518 const r = banking.then(fn)
519 banking = r.catch(() => undefined)
520 return r
521}
522
523async function startPoints($: EngineInterface): Promise<void> {
524 const stored = storedTotal(await $.store.get(STORE_ALL_TIME))
525 await update($, allTime, () => stored)
526 hasChecked = false
527 const u = await $.session.usage()
528 usage = { contextPercent: u.context.percent, usd: u.cost?.usd, rateLimits: u.rateLimits }
529 await showScore($)
530}
531
532// ------------------------------------------------------------------------------------------ Sponsor Mail
533
534const MAIL_TICK_MS = 30_000
535const MAIL_TITLE = 'Sponsor Mail'
536const GH_TIMEOUT_MS = 20_000
537
538async function tell($: EngineInterface, text: string, title: string): Promise<void> {
539 const sent = await $.ui.notify(text, { title }).catch(() => undefined)
540 if (!sent?.isSent) $.ui.toast(`${title}: ${text}`, { timeoutMs: TOAST_MS })
541}
542
543async function lookAtPr($: EngineInterface, w: Pick<MailWatch, 'url' | 'root'>): Promise<Pr | undefined> {
544 const r = await $.process.run(prQueryArgv(w.url), { cwd: w.root, timeoutMs: GH_TIMEOUT_MS })
545 return r.exitCode === 0 ? parsePr(r.stdout) : undefined
546}
547
548/** The repository root of the directory in `$1`, with a leading `~` as $HOME. */
549const TOPLEVEL_OF = 'd=$1; case $d in "~"*) d=$HOME${d#"~"};; esac; cd -- "$d" && git rev-parse --show-toplevel'
550
551/**
552 * Starts the watch on the PR at `url`, or this branch's PR, in the checkout at `dir` (else here); says what came
553 * of it. A checkout on another branch than the PR's is never watched: its first look would end the watch.
554 */
555async function beginMail($: EngineInterface, url?: string, dir?: string): Promise<string> {
556 const top = dir
557 ? await $.process.run(['sh', '-c', TOPLEVEL_OF, 'sh', dir])
558 : await $.process.run(['git', 'rev-parse', '--show-toplevel'])
559 const root = top.exitCode === 0 ? top.stdout.trim() : ''
560 if (!root) return 'Sponsor Mail: not inside a git repository.'
561 const found =
562 url ??
563 (await $.process.run(['gh', 'pr', 'view', '--json', 'url', '-q', '.url'], { cwd: root, timeoutMs: GH_TIMEOUT_MS }))
564 .stdout.trim()
565 if (!prRefOf(found)) return 'Sponsor Mail: no pull request for this branch.'
566 const pr = await lookAtPr($, { url: found, root })
567 if (!pr) return `Sponsor Mail: gh could not read ${found}.`
568 if (pr.state !== 'OPEN') return `Sponsor Mail: PR #${pr.number} is ${pr.state.toLowerCase()}; nothing to watch.`
569 const at = (await $.process.run(['git', '-C', root, 'branch', '--show-current'])).stdout.trim()
570 if (at !== '' && at !== pr.branch) {
571 return `Sponsor Mail: PR #${pr.number} is on ${pr.branch}, but ${root} is on ${at}; /watch-pr from its checkout.`
572 }
573 const now = await $.clock.now()
574 const w = startWatch(pr, root, now)
575 await update($, mailWatch, () => w)
576 mailDueAt = now + nextPollMs(w, now)
577 return `Sponsor Mail: watching PR #${pr.number}.`
578}
579
580async function deliver($: EngineInterface, w: MailWatch, ev: MailEvent): Promise<void> {
581 switch (ev.kind) {
582 case 'mail':
583 await announceCue($, { kind: 'mail', author: ev.mail[0]?.author ?? 'someone' })
584 return tell($, mailNotice(w, ev.mail), MAIL_TITLE)
585 case 'answered':
586 return award($, answeredAward(w, ev.count))
587 case 'red':
588 await tell($, redNotice(w, ev.names), MAIL_TITLE)
589 return award($, redAward(w, ev.names), { kind: 'red-pr', names: ev.names })
590 case 'green':
591 return $.ui.toast(`PR #${w.number}: every check is green`, { timeoutMs: TOAST_MS })
592 case 'merged':
593 return award($, mergeAward(w))
594 case 'closed':
595 return $.ui.toast(`PR #${w.number} was closed: Sponsor Mail stops watching it`, { timeoutMs: TOAST_MS })
596 }
597}
598
599/**
600 * One look at the Watched PR. `claim` follows a post of Claude's: the viewer's new comments are Claude's and
601 * never Mail. An unclaimed look that a post overlapped is thrown away, as it may hold Claude's comment unclaimed.
602 */
603async function lookMail($: EngineInterface, claim: boolean): Promise<void> {
604 const before = await read($, mailWatch)
605 if (!before) return
606 mailLooks++
607 const gen = postGen
608 try {
609 const branch = await $.process.run(['git', '-C', before.root, 'branch', '--show-current'])
610 const now = await $.clock.now()
611 const at = branch.stdout.trim()
612 if (branch.exitCode === 0 && at !== '' && at !== before.branch) {
613 await update($, mailWatch, () => null)
614 $.ui.toast(`Left ${before.branch}: Sponsor Mail stops watching PR #${before.number}`, { timeoutMs: TOAST_MS })
615 return
616 }
617 const pr = await lookAtPr($, before)
618 if (!claim && (gen !== postGen || posting > 0)) return
619 mailDueAt = now + nextPollMs(before, now)
620 const w = await read($, mailWatch)
621 if (!pr || !w || w.number !== pr.number) return
622 const r = step(claim ? claimMine(w, pr) : w, pr, now)
623 await update($, mailWatch, () => r.watch ?? null)
624 if (r.watch) mailDueAt = now + nextPollMs(r.watch, now)
625 for (const ev of r.events) await deliver($, w, ev)
626 } finally {
627 mailLooks--
628 }
629}
630
631function startMail($: EngineInterface): void {
632 mailDueAt = 0
633 $.clock.every(MAIL_TICK_MS, () => {
634 if (mailLooks > 0 || posting > 0) return
635 void $.clock
636 .now()
637 .then(now => (now >= mailDueAt ? lookMail($, false) : undefined))
638 .catch(() => undefined)
639 })
640}
641
642// ------------------------------------------------------------------------------------------- Beast Watch
643
644const BEAST_TICK_MS = 60_000
645/** Every this many ticks the look sends a token too: often enough to catch Wedged, rare enough to spare the cache. */
646const BEAST_TOKEN_EVERY = 5
647const BEAST_TITLE = 'Beast Watch'
648const PI_ENV = 'cat "${PI_IMPLEMENTER_HOME:-$HOME/.config/pi-implementer}/env" 2>/dev/null'
649
650async function piEnv($: EngineInterface): Promise<string> {
651 return (await $.process.run(['sh', '-c', PI_ENV])).stdout
652}
653
654/** curl to Beast's llama-server. The API key goes in on stdin (`-H @-`), never on argv where ps would show it. */
655async function curlBeast($: EngineInterface, key: string | undefined, ...args: string[]) {
656 return $.process.run(['curl', '-s', '-H', '@-', ...args], {
657 stdin: key ? `Authorization: Bearer ${key}\n` : '',
658 timeoutMs: 25_000,
659 })
660}
661
662/** The one-token probe, skipped unless /slots shows every slot idle and no Dispatch runs: it would queue behind them. */
663async function probeToken(
664 $: EngineInterface,
665 key: string | undefined,
666 url: string,
667 alias: string | undefined,
668): Promise<Probe['completion']> {
669 const query = alias ? `?model=${encodeURIComponent(alias)}` : ''
670 if ((watch?.running.size ?? 0) > 0 || !isIdle((await curlBeast($, key, '-m', '5', `${url}/slots${query}`)).stdout)) {
671 return 'skipped'
672 }
673 const body = JSON.stringify({ ...(alias ? { model: alias } : {}), prompt: 'hi', max_tokens: 1 })
674 const r = await curlBeast($, key, '-m', '20', '-o', '/dev/null', '-w', '%{http_code}',
675 '-H', 'Content-Type: application/json', '-d', body, `${url}/v1/completions`)
676 return completionOf(r.exitCode, r.stdout)
677}
678
679/**
680 * One look at Beast: nvidia-smi over ssh, llama-server's /health and, on a router, the Dispatches' model; then,
681 * when that model is loaded and nothing would queue it, one token. `isQuick` leaves the token out.
682 */
683async function lookAtBeast($: EngineInterface, isQuick = false): Promise<Reading> {
684 const env = await piEnv($)
685 const url = llamaUrlOf(env)
686 const host = url && hostOf(url)
687 if (!url || !host) return { state: 'down', reason: 'no LLAMA_URL in pi-implementer env' }
688 beastHost = host
689 const key = llamaKeyOf(env)
690 const alias = modelAliasOf(env)
691 const [smi, health, models] = await Promise.all([
692 $.process.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5', host, SMI_QUERY], { timeoutMs: 15_000 }),
693 curlBeast($, key, '-m', '5', '-w', '\n%{http_code}', `${url}/health`),
694 curlBeast($, key, '-m', '5', `${url}/v1/models`),
695 ])
696 const probe: Probe = { smi, health: healthOf(health.stdout), model: modelStateOf(models.stdout, alias) }
697 // Never a token to a model that is not loaded: on a router it would load it, evicting whatever is.
698 const isProbed = !isQuick && smi.exitCode === 0 && probe.health.code === 200 && (probe.model ?? 'loaded') === 'loaded'
699 if (isProbed) probe.completion = await probeToken($, key, url, alias)
700 return judge(probe)
701}
702
703/** Looks at Beast, keeps the reading, and tells of it going Down or coming back. */
704async function checkBeast($: EngineInterface, isQuick = false): Promise<Reading> {
705 const looked = await lookAtBeast($, isQuick)
706 const before = (await read($, beast)).reading
707 // A look without the token cannot see Wedged: it leaves a Wedged Beast Wedged until a token gets through.
708 const r = isQuick && looked.state === 'up' && before?.reason === 'wedged' ? before : looked
709 await update($, beast, b => ({ ...b, reading: r }))
710 const t = transition(before, r)
711 if (t === 'down') await tell($, `Beast is Down: ${r.reason ?? 'unknown'}`, BEAST_TITLE)
712 else if (t === 'recovered') $.ui.toast('Beast is back Up', { timeoutMs: TOAST_MS })
713 await showScore($)
714 return r
715}
716
717function beastTicks($: EngineInterface): void {
718 beastTimer?.cancel()
719 beastTimer = $.clock.every(BEAST_TICK_MS, () => {
720 if (isBeastLooking) return
721 isBeastLooking = true
722 void checkBeast($, ++beastTickCount % BEAST_TOKEN_EVERY !== 0)
723 .catch(() => undefined)
724 .finally(() => {
725 isBeastLooking = false
726 })
727 })
728}
729
730/** The first use of Beast wakes the watch: a look now, and one a minute after. */
731async function wakeBeast($: EngineInterface): Promise<Reading> {
732 const b = await read($, beast)
733 if (!b.isAwake) {
734 await update($, beast, x => ({ ...x, isAwake: true }))
735 beastTicks($)
736 }
737 return checkBeast($)
738}
739
740const LOADING_POLL_S = 5
741
742/**
743 * The Beast Guard's verdict on a guarded line: a fresh look and, while Beast is Loading, a wait for it to end.
744 * The wait sleeps in a process, as time spent in `$` calls is not the hook's own.
745 */
746async function guardBeast($: EngineInterface, line: string): Promise<string | undefined> {
747 let r = await wakeBeast($)
748 let waited = 0
749 for (; r.state === 'loading' && waited < LOADING_WAIT_MS; waited += LOADING_POLL_S * 1000) {
750 await $.process.run(['sleep', String(LOADING_POLL_S)])
751 r = await lookAtBeast($, true)
752 }
753 // The wait looked without the token: one full look now that it is over.
754 if (waited > 0 && r.state !== 'loading') r = await checkBeast($)
755 const g = beastGuard(line, r)
756 if (g.kind === 'deny') return g.reason
757 if (g.kind === 'wait') {
758 return `Beast Guard: Beast is still Loading after ${LOADING_WAIT_MS / 60_000} minutes; try again soon.`
759 }
760 return undefined
761}
762
763// ------------------------------------------------------------------------------------------- the voice
764
765/** The Verdict for a Notable Turn: a model-written line when the quip writer is free, the plain one otherwise. */
766async function verdict($: EngineInterface, stats: TurnStats): Promise<string> {
767 if (isQuipBusy) return verdictLine(fallbackVerdict(stats), stats, false)
768 isQuipBusy = true
769 quipAt = await $.clock.now()
770 try {
771 const r = await $.model.complete({
772 model: QUIP_MODEL,
773 system: VERDICT_SYSTEM,
774 prompt: verdictPrompt(stats),
775 maxTokens: 80,
776 effort: 'low',
777 timeoutMs: VERDICT_TIMEOUT_MS,
778 })
779 const line = r.isAnswered ? cleanQuip(r.text) : undefined
780 return line ? verdictLine(line, stats, true) : verdictLine(fallbackVerdict(stats), stats, false)
781 } catch {
782 return verdictLine(fallbackVerdict(stats), stats, false)
783 } finally {
784 isQuipBusy = false
785 }
786}
787
788// ------------------------------------------------------------------------------------------------ hooks
789
790export const register: Register = on => {
791 on('session.start', async ($, e, next) => {
792 await startPoints($)
793 await startBoard($)
794 await $.command.register({ name: 'tdd', description: 'Show or hide the TDD Band above the prompt' })
795 await $.command.register({ name: 'watch-pr', description: "Sponsor Mail: watch this branch's PR" })
796 await $.command.register({ name: 'unwatch-pr', description: 'Sponsor Mail: stop watching the PR' })
797 await $.command.register({ name: 'beast', description: "Beast Watch: look at Beast's health now" })
798 await startCues($)
799 startMail($)
800 beastHost = hostOf(llamaUrlOf(await piEnv($)) ?? '')
801 if ((await read($, beast)).isAwake) beastTicks($)
802 return next(e)
803 })
804
805 // -------------------------------------------------------------------------------------- Beast Guard
806
807 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
808 if (isGuarded(e.command)) {
809 const reason = await guardBeast($, e.command)
810 return reason ? { deny: reason } : next(e)
811 }
812 // Any other use of Beast wakes Beast Watch; a guarded line has just woken it.
813 if (isBeastUse(e.command, beastHost) && !(await read($, beast)).isAwake) {
814 $.clock.after(0, () => void wakeBeast($).catch(() => undefined))
815 }
816 return next(e)
817 }).catch(($, e, next) => next(e)) // a broken guard fails open: the line runs as written
818
819 on('command.run', { command: 'beast' }, async $ => {
820 const r = await wakeBeast($)
821 return { text: `${beastSegment(r)}${r.state === 'up' ? '' : ' (Beast Guard refuses Dispatches while Down)'}` }
822 })
823
824 // ------------------------------------------------------------------------------------- Sponsor Mail
825
826 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
827 const isPosting = isPost(e.command) && (await read($, mailWatch)) !== null
828 if (isPosting) {
829 posting++
830 postGen++
831 }
832 let ran: Awaited<ReturnType<typeof next>>
833 try {
834 ran = await next(e)
835 } finally {
836 if (isPosting) posting--
837 }
838 const result = ran.result as { backgroundTaskId?: string; stdout?: string } | undefined
839 const isDone = ran.deny === undefined && ran.isError !== true && !result?.backgroundTaskId
840 try {
841 if (isDone && isPosting) await lookMail($, true)
842 else if (isDone && isPrCreate(e.command)) {
843 const url = result?.stdout?.match(/https:\/\/\S+\/pull\/\d+/)?.[0]
844 const toast = (text: string) => $.ui.toast(text, { timeoutMs: TOAST_MS })
845 const dir = createDirOf(e.command)
846 if (dir === null) toast('Sponsor Mail: gh pr create ran where the line computes; /watch-pr from there.')
847 else $.clock.after(0, () => void beginMail($, url, dir).then(toast).catch(() => undefined))
848 }
849 } catch {
850 // the line ran: a failed look leaves Sponsor Mail to its next tick
851 }
852 return ran
853 }).catch(($, e, next) => next(e))
854
855 on('command.run', { command: 'watch-pr' }, async $ => ({ text: await beginMail($) }))
856
857 on('command.run', { command: 'unwatch-pr' }, async $ => {
858 const w = await read($, mailWatch)
859 await update($, mailWatch, () => null)
860 return { text: w ? `Sponsor Mail: stopped watching PR #${w.number}.` : 'Sponsor Mail: no PR was watched.' }
861 })
862
863 // ------------------------------------------------------------------------------------- Podman Guard
864
865 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
866 const g = guard(e.command)
867 if (g.kind === 'pass') return next(e)
868 if (g.kind === 'deny') return { deny: g.reason }
869 const ran = await next({ ...e, command: g.command })
870 if (ran.deny !== undefined) return ran
871 return { ...ran, context: [...(ran.context ?? []), rewriteNote(e.command, g.command)] }
872 }).catch(($, e, next) => next(e)) // a broken guard fails open: the line runs as written
873
874 // ------------------------------------------------------------------------------------- Branch Guard
875
876 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
877 const steps = gitSteps(e.command)
878 if (steps.length === 0) return next(e)
879 const repos = new Map<string, Repo | undefined>()
880 for (const dir of new Set(steps.map(s => s.dir))) repos.set(dir, await repoAt($, dir))
881 const g = branchGuard(e.command, dir => repos.get(dir))
882 return g.kind === 'deny' ? { deny: g.reason } : next(e)
883 }).catch(($, e, next) => next(e)) // a broken guard fails open: the line runs as written
884
885 // ----------------------------------------------------------------------------------------------- HUD
886
887 on('session.measure', async ($, e, next) => {
888 usage = { contextPercent: e.context.percent, usd: e.cost?.usd, rateLimits: e.rateLimits }
889 await showScore($)
890 return next(e)
891 })
892
893 on('session.compact', async ($, e, next) => {
894 const r = await next(e)
895 if (e.agentId || r.skip !== undefined) return r
896 const a = compactAward(e.trigger, usage?.contextPercent)
897 if (a) await award($, a, e.trigger === 'auto' ? { kind: 'collapse' } : undefined)
898 return r
899 }).catch(($, e, next) => next(e))
900
901 // ---------------------------------------------------------------------------------------------- Cues
902
903 // A /clear starts the session over with fresh state and no session.start: the all-time total is read back
904 // and the Cue written again here.
905 on('classic.SessionStart', async ($, e, next) => {
906 const r = await next(e)
907 if (e.source === 'clear') {
908 await startPoints($)
909 await startCues($)
910 }
911 return r
912 }).catch(($, e, next) => next(e))
913
914 // dungeon-buddy's Buddy was Rerolled or hatched legendary: priced here before its write returns, so a second
915 // Reroll reads the debited total. Its Bubble already said it, so the Award announces no Cue back.
916 on('state.set', { plugin: 'dungeon-buddy', key: 'cue' }, async ($, e, next) => {
917 const r = await next(e)
918 const a = awardOfBuddyCue(e.value)
919 // A pricing that fails leaves the Buddy's write as written: past `next`, this hook must not throw.
920 if (a) await award($, a, null).catch(() => undefined)
921 return r
922 }).catch(($, e, next) => next(e))
923
924 // ------------------------------------------------------------------------------------------ TDD Band
925
926 on('agent.spawn', async ($, e, next) => {
927 await update($, tdd, t => onAgent(t, e.subagentType))
928 return next(e)
929 }).catch(($, e, next) => next(e))
930
931 on('command.run', { command: 'tdd' }, async $ => {
932 const t = await update($, tdd, toggle)
933 return { text: `TDD Band ${isShown(t) ? 'shown' : 'hidden'}.` }
934 })
935
936 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
937 if (e.props.hasSurvey) return next(e)
938 const t = await read($, tdd)
939 const fight = newestBoss(await read($, bosses))
940 const w = await read($, mailWatch)
941 if (!isShown(t) && !fight && !w) return next(e)
942 const { Box, Button, Text } = $.ui.resolve(e)
943 const checks = w && tally(w.checks)
944 const mailRow = w && checks && (
945 <Box key="mail" gap={1}>
946 <Text bold color="cyan">
947 📬 PR #{w.number}
948 </Text>
949 {checks.total > 0 && (
950 <Text color={checks.failed.length > 0 ? 'red' : checks.pending.length > 0 ? 'yellow' : 'green'}>
951 ✅ {checks.passed}/{checks.total}
952 </Text>
953 )}
954 {checks.pending.length > 0 && <Text color="yellow">⏳ {checks.pending.length}</Text>}
955 {checks.failed.length > 0 && (
956 <Text color="red" wrap="truncate-end">
957 ❌ {checks.failed.join(', ')}
958 </Text>
959 )}
960 {w.mail.length > 0 && <Text bold>💬 {w.mail.length} unanswered</Text>}
961 {w.mail.length > 0 && (
962 <Button
963 hotkey="a"
964 label="Address them"
965 plain
966 onPress={() => void $.prompt.submit({ text: addressPrompt(w) }).catch(() => undefined)}
967 />
968 )}
969 {checks.failed.length > 0 && (
970 <Button
971 hotkey="f"
972 label="Fix it"
973 plain
974 onPress={() => void $.prompt.submit({ text: fixPrompt(w) }).catch(() => undefined)}
975 />
976 )}
977 </Box>
978 )
979 const v = verdictOf(t)
980 const bossRow = fight && (
981 <Box key="boss" gap={1}>
982 <Text bold color="red">
983 ☠ FLOOR BOSS
984 </Text>
985 <Text bold>{fight.boss.name}</Text>
986 <Text color="red">{hpBar(fight.boss)}</Text>
987 <Text dimColor wrap="truncate-end">
988 {fight.key}
989 {fight.others > 0 ? ` · +${fight.others} more` : ''}
990 </Text>
991 </Box>
992 )
993 const tddRow = isShown(t) && (
994 <Box key="tdd" gap={1}>
995 <Text bold color={TDD_COLOR[t.phase ?? 'NONE']}>
996 {t.phase ? `${TDD_ICON[t.phase]} ${t.phase}` : '· TDD'}
997 </Text>
998 <Text color={MOOD_COLOR[v.mood]} wrap="truncate-end">
999 {v.note}
1000 </Text>
1001 {DRAFTS.map(d => (
1002 <Button
1003 key={d.hotkey}
1004 hotkey={d.hotkey}
1005 label={d.label}
1006 plain
1007 onPress={() => void $.prompt.fill({ text: d.draft }).catch(() => undefined)}
1008 />
1009 ))}
1010 </Box>
1011 )
1012 const rows = [bossRow, mailRow, tddRow].filter(r => !!r)
1013 if (rows.length === 0) return next(e)
1014 // What the plugins beneath draw (dungeon-buddy's Buddy) goes under the System's rows, never in place of them.
1015 const below = await next(e)
1016 return (
1017 <Box flexDirection="column">
1018 {rows}
1019 {below}
1020 </Box>
1021 )
1022 })
1023
1024 // ------------------------------------------------------------------------------------------ the voice
1025
1026 on('turn.start', async ($, e, next) => {
1027 // A subagent's turn runs inside the main loop's: that turn's stats and spinner carry on.
1028 if (e.agentId) return next(e)
1029 turn = { toolCalls: 0, points: 0, events: [] }
1030 const mood = moodOf({
1031 contextPercent: usage?.contextPercent,
1032 debuff: (await read($, score)).debuff,
1033 isDispatching: (watch?.running.size ?? 0) > 0,
1034 })
1035 spinner = spinnerWord(mood, Math.random())
1036 return next(e)
1037 })
1038
1039 on('ui.render', { component: 'Spinner' }, async ($, e, next) =>
1040 e.surface === 'terminal' && spinner ? next({ ...e, props: { ...e.props, word: spinner } }) : next(e),
1041 )
1042
1043 on('turn.complete', async ($, e, next) => {
1044 const r = await next(e)
1045 const stats = turn && { ...turn, durationMs: e.durationMs }
1046 if (e.agentId) return r
1047 turn = undefined
1048 spinner = undefined
1049 if (!stats || e.reason !== 'answer' || !isNotable(stats)) return r
1050 const text = await verdict($, stats)
1051 await announceCue($, { kind: 'verdict', text })
1052 return { ...r, text }
1053 })
1054
1055 on('command.run', { command: 'dispatches' }, async $ => {
1056 if (!watch) return { text: 'Dispatch Board: not inside a git repository.' }
1057 await tick($, true)
1058 await $.ui.open({ id: PANE, title: TITLE })
1059 return { text: 'Dispatch Board opened.' }
1060 })
1061
1062 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1063 const { Box, Text } = $.ui.resolve(e)
1064 const state = await read($, board)
1065 if (!state) return <Text dimColor>No .hybrid/ in this repo: run pi-dispatch.py init first.</Text>
1066 const width = Math.max(30, (e.props.bodyColumns ?? e.viewport?.columns ?? 80) - 2)
1067 const count = (phase: BoardRowState['phase']) => state.rows.filter(r => r.phase === phase).length
1068 return (
1069 <Box flexDirection="column">
1070 <Text bold wrap="truncate-end">
1071 {state.branch} · {count('running')} running · {count('awaiting')} awaiting Gate
1072 </Text>
1073 {state.rows.length === 0 && <Text dimColor>No Dispatches on this run branch yet.</Text>}
1074 {state.rows.map(row => (
1075 <Box key={`d${row.n}`} flexDirection="column">
1076 <Text wrap="truncate-end">
1077 <Text color={PHASE[row.phase].color}>{PHASE[row.phase].label}</Text>
1078 {` #${String(row.n).padStart(2, '0')} ${row.ticket} ${stats(row, state.ctxLimit)}`}
1079 </Text>
1080 {row.detail !== '' && (
1081 <Text dimColor wrap="truncate-end">
1082 {` ↳ ${tail(row.detail, width - 4)}`}
1083 </Text>
1084 )}
1085 </Box>
1086 ))}
1087 </Box>
1088 )
1089 })
1090
1091 on('tool.call', async ($, e, next) => {
1092 if (turn && !e.agentId) turn = { ...turn, toolCalls: turn.toolCalls + 1 }
1093 const ran = await next(e)
1094 const isDenied = ran.deny !== undefined
1095 if (e.tool === 'Bash') {
1096 const result = ran.result as { backgroundTaskId?: string; stdout?: string; stderr?: string } | undefined
1097 if (!isDenied && result?.backgroundTaskId) return ran // still running: nothing to score yet
1098 if (isDenied) {
1099 await award($, errorAward('Bash', true))
1100 return ran
1101 }
1102 let checked: boolean | undefined
1103 for (const a of bashAwards(e.command, ran.isError === true, await read($, score), !hasChecked)) {
1104 if (a.isGreen !== undefined) {
1105 hasChecked = true
1106 const isGreen = a.isGreen
1107 checked = isGreen
1108 await update($, tdd, t => onCheck(t, isGreen))
1109 }
1110 await award($, a)
1111 }
1112 const key = checkKey(e.command)
1113 if (key && checked !== undefined) await fight($, key, checked, `${result?.stdout ?? ''}\n${result?.stderr ?? ''}`)
1114 return ran
1115 }
1116 if (isDenied || ran.isError === true) await award($, errorAward(String(e.tool), isDenied))
1117 return ran
1118 })
1119}
1120mods/board.ts 190 lines1// The Dispatch Board's pure half: from the text of pi-implementer's files under .hybrid/ to the rows the pane
2// draws. No `$` here, so every rule is testable without an engine.
3
4export type Phase = 'running' | 'awaiting' | 'landed' | 'dropped' | 'conflict' | 'gone'
5
6export type Ended = 'finished' | 'timeout' | 'turn cap' | 'error'
7
8export type LiveCounts = {
9 calls: number
10 tools: number
11 ctx: number
12 lastTool: string
13 lastText: string
14}
15
16export type BoardRow = {
17 n: number
18 ticket: string
19 phase: Phase
20 ended?: Ended
21 wallS: number
22 calls: number
23 maxTurns?: number
24 tools: number
25 ctx: number
26 lastTool: string
27 detail: string
28}
29
30/** `.hybrid/running/NN.json`, written by `pi-dispatch.py dispatch` while pi runs. */
31export type RunningMeta = {
32 n: number
33 ticket: string
34 max_turns: number
35 started: string
36 log: string
37 run_branch: string
38}
39
40/** A `.hybrid/dispatches.jsonl` row: the fields the board reads. */
41export type DispatchRow = {
42 n: number
43 ticket: string
44 max_turns: number
45 ended: Ended
46 run_branch: string
47 worktree: string
48 wall_s: number
49 turns: number
50 tool_calls: number
51 ctx_max: number
52 result: string
53}
54
55export type Outcome = { n: number; outcome: 'landed' | 'dropped' | 'conflict' }
56
57export const emptyCounts = (): LiveCounts => ({ calls: 0, tools: 0, ctx: 0, lastTool: '', lastText: '' })
58
59/** Every line of a JSONL text that parses as an object; torn or foreign lines are skipped. */
60export const parseJsonl = <T>(text: string): T[] =>
61 text.split('\n').flatMap(line => {
62 if (line.trim() === '') return []
63 try {
64 const value: unknown = JSON.parse(line)
65 return value !== null && typeof value === 'object' ? [value as T] : []
66 } catch {
67 return []
68 }
69 })
70
71type PiEvent = {
72 type?: string
73 toolName?: string
74 message?: {
75 role?: string
76 usage?: { input?: number; cacheRead?: number; output?: number }
77 content?: { type?: string; text?: string }[]
78 }
79}
80
81/**
82 * Folds pi's `--mode json` events into the running counts, the way pi-dispatch.py's run_pi counts them: a
83 * call is an assistant `message_end`, a tool is a `tool_execution_start`, ctx is the largest
84 * input + cacheRead + output seen.
85 */
86export const foldPiEvents = (counts: LiveCounts, events: readonly PiEvent[]): LiveCounts =>
87 events.reduce((c, e) => {
88 if (e.type === 'tool_execution_start') {
89 return { ...c, tools: c.tools + 1, lastTool: e.toolName ?? c.lastTool }
90 }
91 if (e.type !== 'message_end' || e.message?.role !== 'assistant') return c
92 const u = e.message.usage ?? {}
93 const text = (e.message.content ?? [])
94 .filter(b => b.type === 'text' && typeof b.text === 'string')
95 .map(b => b.text)
96 .join(' ')
97 .trim()
98 return {
99 ...c,
100 calls: c.calls + 1,
101 ctx: Math.max(c.ctx, (u.input ?? 0) + (u.cacheRead ?? 0) + (u.output ?? 0)),
102 lastText: text || c.lastText,
103 }
104 }, counts)
105
106/**
107 * Splits newly read log text at its last newline: the complete lines to fold now, and how many bytes they
108 * span (so the reader's offset only ever moves past whole lines; a torn tail is read again next time).
109 */
110export const completeLines = (chunk: string): { text: string; bytes: number } => {
111 const cut = chunk.lastIndexOf('\n')
112 const text = cut < 0 ? '' : chunk.slice(0, cut + 1)
113 return { text, bytes: new TextEncoder().encode(text).length }
114}
115
116/** The last `width` characters of a text's last non-empty line, on one line. */
117export const tail = (text: string, width: number): string => {
118 const line =
119 text
120 .split('\n')
121 .map(l => l.trim())
122 .filter(Boolean)
123 .at(-1) ?? ''
124 return line.length > width ? `…${line.slice(-(width - 1))}` : line
125}
126
127export type BoardInput = {
128 branch: string
129 running: readonly { meta: RunningMeta; counts: LiveCounts; nowMs: number }[]
130 finished: readonly DispatchRow[]
131 outcomes: readonly Outcome[]
132 worktreesPresent: ReadonlySet<string>
133}
134
135/**
136 * The board's rows, newest first: every running Dispatch, then every finished one of the current run
137 * branch. A finished Dispatch's phase is its last Outcome; with none, `awaiting` while its Worktree is on
138 * disk and `gone` once it is not.
139 */
140export const boardRows = (input: BoardInput): BoardRow[] => {
141 const fate = new Map(input.outcomes.map(o => [o.n, o.outcome]))
142 const running = input.running
143 .filter(({ meta }) => meta.run_branch === input.branch)
144 .map(({ meta, counts, nowMs }): BoardRow => ({
145 n: meta.n,
146 ticket: meta.ticket,
147 phase: 'running',
148 wallS: Math.max(0, Math.round((nowMs - Date.parse(meta.started)) / 1000)),
149 calls: counts.calls,
150 maxTurns: meta.max_turns,
151 tools: counts.tools,
152 ctx: counts.ctx,
153 lastTool: counts.lastTool,
154 detail: counts.lastText,
155 }))
156 const live = new Set(running.map(r => r.n))
157 const finished = input.finished
158 .filter(r => r.run_branch === input.branch && !live.has(r.n))
159 .map((r): BoardRow => ({
160 n: r.n,
161 ticket: r.ticket,
162 phase: fate.get(r.n) ?? (input.worktreesPresent.has(r.worktree) ? 'awaiting' : 'gone'),
163 ended: r.ended,
164 wallS: Math.round(r.wall_s),
165 calls: r.turns,
166 maxTurns: r.max_turns,
167 tools: r.tool_calls,
168 ctx: r.ctx_max,
169 lastTool: '',
170 detail: r.result,
171 }))
172 return [...running, ...finished].sort((a, b) => b.n - a.n)
173}
174
175export const duration = (s: number): string =>
176 s < 60
177 ? `${s}s`
178 : s < 3600
179 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`
180 : `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`
181
182export const kilo = (n: number): string =>
183 n < 1000 ? String(n) : `${(n / 1000).toFixed(n < 10000 ? 1 : 0)}K`
184
185/** Reads `CTX_SIZE` out of pi-implementer's env file text (KEY=value lines, optional quotes / export). */
186export const ctxSizeOf = (envText: string): number | undefined => {
187 const m = envText.match(/^\s*(?:export\s+)?CTX_SIZE\s*=\s*["']?(\d+)/m)
188 return m ? Number(m[1]) : undefined
189}
190mods/points.ts 225 lines1// Crawler Points' pure half: which Bash commands and Dispatch fates score, for how much, and what the HUD
2// says. No `$` here.
3
4export type Score = {
5 session: number
6 streak: number
7 debuff?: string
8}
9
10export type Award = {
11 /** Points added (negative for a penalty). */
12 points: number
13 /** What happened, for the quip writer and the fallback toast. */
14 event: string
15 /** Set when the award also unlocks a named achievement. */
16 achievement?: string
17 /** true: a green test/build (extends the streak); false: a red one (breaks it); absent: neither. */
18 isGreen?: boolean
19 debuff?: string
20}
21
22export type CommandKind = 'commit' | 'pr' | 'force-push' | 'check' | 'other'
23
24const FORCE_PUSH = /\bgit\s+push\b[^|;&]*\s(?:-f\b|--force\b|--force-with-lease\b)/
25const COMMIT = /\bgit\s+commit\b/
26const PR = /\bgh\s+pr\s+create\b/
27const CHECK =
28 /\b(?:go\s+(?:test|build|vet)|pytest|cargo\s+(?:test|build|check|clippy)|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|build|typecheck|lint)|tsc|make|nix\s+(?:build|flake\s+check)|golangci-lint|shellcheck|claude\s+plugin\s+(?:test|validate))\b/
29
30/** The command with its quoted strings blanked, so a commit message or an echo never reads as a command. */
31const unquoted = (command: string): string => command.replace(/'[^']*'|"(?:\\.|[^"\\])*"/g, "''")
32
33/** The commands a shell line chains with `;`, `&&`, `||` or newlines; a pipeline stays one. */
34export const segments = (command: string): string[] =>
35 unquoted(command)
36 .split(/&&|\|\||;|\n/)
37 .map(c => c.trim())
38 .filter(Boolean)
39
40/** What a Bash command is, for scoring. A force push wins over everything else in the same command. */
41export const classify = (raw: string): CommandKind => {
42 const command = unquoted(raw)
43 return FORCE_PUSH.test(command)
44 ? 'force-push'
45 : PR.test(command)
46 ? 'pr'
47 : COMMIT.test(command)
48 ? 'commit'
49 : CHECK.test(command)
50 ? 'check'
51 : 'other'
52}
53
54export const STREAK_MILESTONES = [5, 10, 25] as const
55
56/**
57 * The awards for a finished foreground Bash call, one per kind its chained commands hold (none when nothing
58 * scores). The exit status is the whole line's: a failed line costs its check (the likeliest culprit) and
59 * any force push, and earns no milestone, since which command failed is unknown. `isFirstCheck` is true for
60 * the session's first test/build run.
61 */
62export const bashAwards = (
63 command: string,
64 isError: boolean,
65 score: Score,
66 isFirstCheck: boolean,
67): Award[] => {
68 const kinds = new Set(segments(command).map(classify))
69 const order: CommandKind[] = isError ? ['force-push', 'check'] : ['force-push', 'pr', 'commit', 'check']
70 return order
71 .filter(k => kinds.has(k))
72 .map(k => kindAward(k, isError, score, isFirstCheck))
73 .filter((a): a is Award => a !== undefined)
74}
75
76const kindAward = (
77 kind: CommandKind,
78 isError: boolean,
79 score: Score,
80 isFirstCheck: boolean,
81): Award | undefined => {
82 if (kind === 'force-push') {
83 return { points: -200, event: 'force-pushed over shared history', debuff: 'Shame' }
84 }
85 if (kind === 'pr') {
86 return isError ? undefined : { points: 150, event: 'opened a pull request', achievement: 'Floor Cleared' }
87 }
88 if (kind === 'commit') {
89 return isError ? undefined : { points: 25, event: 'made a git commit' }
90 }
91 if (kind === 'check') {
92 if (isError) {
93 return { points: -15, event: 'ran a test/build that failed', isGreen: false, debuff: 'Red Build' }
94 }
95 const streak = score.streak + 1
96 const isMilestone = (STREAK_MILESTONES as readonly number[]).includes(streak)
97 return {
98 points: 10 + (isMilestone ? streak * 5 : 0),
99 event: isMilestone ? `hit a ${streak}-green streak` : 'ran a test/build that passed',
100 isGreen: true,
101 achievement: isFirstCheck
102 ? 'Compiled On The First Try'
103 : isMilestone
104 ? `${streak} Greens In A Row`
105 : undefined,
106 }
107 }
108 return undefined
109}
110
111/** A tool call that errored or was denied, outside the commands bashAwards scores. */
112export const errorAward = (tool: string, isDenied: boolean): Award => ({
113 points: -5,
114 event: isDenied ? `had a ${tool} call denied` : `had a ${tool} call error out`,
115 debuff: 'Hubris',
116})
117
118/** A Dispatch fate the Dispatch Board noticed after it started watching: a new Outcome, or a capped end. */
119export type Fate = { fate: 'landed' | 'dropped' | 'conflict' | 'timeout' | 'turn cap'; ticket: string }
120
121/** The award for a Dispatch's Outcome or end, from pi-implementer's files. */
122export const dispatchAward = (fate: Fate['fate'], ticket: string): Award =>
123 ({
124 landed: { points: 100, event: `landed the local model's Ticket ${ticket}`, achievement: 'Loot Secured' },
125 dropped: { points: -50, event: `dropped the local model's Ticket ${ticket}` },
126 conflict: { points: -75, event: `hit a cherry-pick conflict landing ${ticket}`, debuff: 'Merge Hell' },
127 timeout: { points: -25, event: `let the local model time out on ${ticket}` },
128 'turn cap': { points: -25, event: `let the local model hit its turn cap on ${ticket}` },
129 })[fate]
130
131/** The score after an award: points add, a green extends the streak and clears the debuff, a red resets it. */
132export const apply = (score: Score, award: Award): Score => ({
133 session: score.session + award.points,
134 streak: award.isGreen === true ? score.streak + 1 : award.isGreen === false ? 0 : score.streak,
135 debuff: award.debuff ?? (award.isGreen === true ? undefined : score.debuff),
136})
137
138/** Level from all-time points: 1 below 100, then one more at each square of ten (100, 400, 900, ...). */
139export const level = (allTime: number): number => Math.floor(Math.sqrt(Math.max(0, allTime) / 100)) + 1
140
141/** What the HUD shows of the session's usage, as `session.measure` and `$.session.usage()` report it. */
142export type Usage = {
143 /** How full the context window is, 0 to 100; absent before the first response. */
144 contextPercent?: number
145 usd?: number
146 rateLimits: readonly { kind: string; percentUsed: number }[]
147}
148
149/** A rate-limit window is shown from this much used, and only the fullest one. */
150export const RATE_LIMIT_SHOWN_FROM = 50
151
152const WINDOW_NAMES: Record<string, string> = { five_hour: '5h', seven_day: '7d', spend_limit: 'spend' }
153
154/** The fullest rate-limit window once it reaches RATE_LIMIT_SHOWN_FROM, as the HUD names it. */
155export const hottestLimit = (rateLimits: Usage['rateLimits']): string | undefined => {
156 const hot = rateLimits
157 .filter(l => l.percentUsed >= RATE_LIMIT_SHOWN_FROM)
158 .reduce<Usage['rateLimits'][number] | undefined>((a, l) => (!a || l.percentUsed > a.percentUsed ? l : a), undefined)
159 return hot && `${WINDOW_NAMES[hot.kind] ?? hot.kind} ${Math.round(hot.percentUsed)}%`
160}
161
162export const statusLine = (score: Score, allTime: number, usage?: Usage): string =>
163 [
164 `🎟 ${score.session.toLocaleString('en-US')} CP (${allTime.toLocaleString('en-US')} total)`,
165 `Lv ${level(allTime)}`,
166 score.streak > 0 ? `🔥${score.streak}` : undefined,
167 score.debuff ? `Debuff: ${score.debuff}` : undefined,
168 usage?.contextPercent !== undefined ? `ctx ${Math.round(usage.contextPercent)}%` : undefined,
169 usage ? hottestLimit(usage.rateLimits) : undefined,
170 usage?.usd !== undefined ? `$${usage.usd.toFixed(2)}` : undefined,
171 ]
172 .filter(Boolean)
173 .join(' · ')
174
175/** A manual compaction counts as a Strategic Retreat below this much context. */
176export const RETREAT_BELOW = 90
177
178/**
179 * The award for a compaction of the main conversation: a Dungeon Collapse (automatic) costs, a Strategic Retreat
180 * (manual, below RETREAT_BELOW) earns, and anything else, or a manual one whose fill is unknown, scores nothing.
181 */
182export const compactAward = (trigger: string, contextPercent: number | undefined): Award | undefined =>
183 trigger === 'auto'
184 ? { points: -50, event: 'let the dungeon collapse: Claude Code compacted the context itself', debuff: 'Amnesia' }
185 : trigger === 'manual' && contextPercent !== undefined && contextPercent < RETREAT_BELOW
186 ? {
187 points: 20,
188 event: `compacted at ${Math.round(contextPercent)}% context, before the ceiling came down`,
189 achievement: 'Strategic Retreat',
190 }
191 : undefined
192
193const signed = (n: number): string => (n >= 0 ? `+${n}` : `−${-n}`)
194
195/** The toast shown while no model quip is available (throttled, failed, or still on its way). */
196export const fallbackToast = (award: Award): string =>
197 award.achievement
198 ? `*Ding!* Achievement Unlocked: ${award.achievement} (${signed(award.points)} CP)`
199 : `*Ding!* ${signed(award.points)} CP: the Crawler ${award.event}.`
200
201/** The prompt that asks the model for a one-line quip about an award. */
202export const quipPrompt = (award: Award, score: Score): string =>
203 [
204 `Event: the Crawler ${award.event}.`,
205 `Points: ${signed(award.points)} (session total ${score.session}, green streak ${score.streak}).`,
206 award.achievement ? `Achievement unlocked: "${award.achievement}".` : '',
207 award.debuff ? `Debuff applied: ${award.debuff}.` : '',
208 'Write the toast.',
209 ]
210 .filter(Boolean)
211 .join('\n')
212
213export const QUIP_SYSTEM =
214 "You are the System AI from Dungeon Crawler Carl: a sardonic game-show host narrating a programmer (the Crawler) for a galactic audience. Write ONE line, at most 110 characters, that starts with '*Ding!*' and reacts to the event: cruel, theatrical, funny, no emoji, no quotes around it. Praise only backhanded."
215
216/** A model reply cut down to one toast-sized line, or undefined when nothing usable came back. */
217export const cleanQuip = (text: string): string | undefined => {
218 const line = text
219 .split('\n')
220 .map(l => l.trim().replace(/^["'“]|["'”]$/g, ''))
221 .find(Boolean)
222 if (!line) return undefined
223 return line.length > 140 ? `${line.slice(0, 139)}…` : line
224}
225mods/boss.ts 172 lines1// The Floor Boss's pure half: which Check command a line is, how many tests its output says failed, and the
2// bosses that red runs summon and green ones slay. No `$` here.
3
4import { classify, type Award } from './points'
5import { words, type Word } from './shell'
6
7/** A Floor Boss appears on this many red runs in a row of one Check command. */
8export const SUMMON_AT = 3
9
10export const BOSS_NAMES = [
11 'The Flaky Assertion, Devourer of CI',
12 'Null Pointer Prime',
13 'The Off-By-One Twins',
14 'Grand Regent of Race Conditions',
15 'The Undefined Behemoth',
16 'Lord Segfault the Unflushed',
17 'The Mocking Hydra',
18 'Heisenbug, Who Vanishes When Watched',
19 'The Timeout Lich',
20 'Deadlock, Warden of the Mutex',
21 'The Stale Cache Wyrm',
22 'Queen Regression the Returning',
23 'The Snapshot Mimic',
24 'Captain Import Cycle',
25 'The Floating-Point Phantom',
26 'Brother Unhandled Rejection',
27 'The Leaky Abstraction Ooze',
28 'Typo, Bane of Compilers',
29 'The Dependency Hell Hound',
30 'The Memory-Leak Mantaur',
31] as const
32
33/** `order`: when it appeared, counting from 1 in the session, so the newest one leads the band. */
34export type Boss = { name: string; hp: number; maxHp: number; order: number }
35/** One Check command's run of reds since its last green, and the boss they summoned. */
36export type Foe = { reds: number; boss?: Boss }
37export type Bosses = { foes: Record<string, Foe>; summoned: number }
38
39export const initialBosses: Bosses = { foes: {}, summoned: 0 }
40
41export type BossEvent =
42 | { kind: 'spawned'; boss: Boss }
43 | { kind: 'damaged'; boss: Boss; by: number }
44 | { kind: 'healed'; boss: Boss; by: number }
45 | { kind: 'slain'; boss: Boss }
46
47/** A redirection word: `>`, `2>`, `&>` alone take the next word as their target; `2>/dev/null` holds its own. */
48const REDIRECT = /^(?:\d*|&)[<>]/
49const BARE_REDIRECT = /^(?:\d*|&)[<>]+&?$/
50
51/** A simple command's words as written, without its redirections. */
52const cleaned = (line: string, group: readonly Word[]): string => {
53 const kept: string[] = []
54 for (let i = 0; i < group.length; i++) {
55 const w = group[i] as Word
56 if (BARE_REDIRECT.test(w.text)) i++
57 else if (!REDIRECT.test(w.text)) kept.push(line.slice(w.start, w.end))
58 }
59 return kept.join(' ')
60}
61
62/**
63 * The foe a Bash line fights: its Check commands and the `cd`s before them, without what their output is piped
64 * through or redirected to; undefined when the line runs no Check.
65 */
66export const checkKey = (line: string): string | undefined => {
67 const groups: Word[][] = []
68 for (const w of words(line)) {
69 if (w.startsCommand || groups.length === 0) groups.push([])
70 ;(groups[groups.length - 1] as Word[]).push(w)
71 }
72 const parts = groups.map(g => cleaned(line, g)).filter(Boolean)
73 const kinds = parts.map(p => (p.startsWith('cd ') || p === 'cd' ? 'cd' : classify(p)))
74 const last = kinds.lastIndexOf('check')
75 if (last < 0) return undefined
76 return parts.filter((_, i) => i <= last && (kinds[i] === 'check' || kinds[i] === 'cd')).join(' && ')
77}
78
79const sum = (xs: readonly number[]): number => xs.reduce((a, b) => a + b, 0)
80
81/** How many tests a red Check's output says failed, by the runners' own summaries; undefined when none says. */
82export const failingCount = (output: string): number | undefined => {
83 const jest = /^\s*Tests:?\s+(\d+) failed/m.exec(output) // jest, vitest
84 if (jest) return Number(jest[1])
85 const goFails = output.match(/^--- FAIL:/gm) // go test: top-level tests only, not subtests
86 if (goFails) return goFails.length
87 const cargo = [...output.matchAll(/^test result: FAILED\..*?(\d+) failed/gm)]
88 if (cargo.length > 0) return sum(cargo.map(m => Number(m[1])))
89 const pytest = /\b(\d+) failed\b[^\n]* in [\d.]+s\b/.exec(output)
90 if (pytest) return Number(pytest[1])
91 const bun = /^\s*(\d+) fail$/m.exec(output) // bun test, claude plugin test
92 if (bun) return Number(bun[1])
93 return undefined
94}
95
96const hash = (s: string): number => {
97 let h = 0
98 for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0
99 return h
100}
101
102/** The name a command's boss takes: one from its hash, stepping past names living bosses already hold. */
103const bossName = (key: string, taken: ReadonlySet<string>): string => {
104 const start = hash(key) % BOSS_NAMES.length
105 for (let i = 0; i < BOSS_NAMES.length; i++) {
106 const name = BOSS_NAMES[(start + i) % BOSS_NAMES.length] as string
107 if (!taken.has(name)) return name
108 }
109 return BOSS_NAMES[start] as string
110}
111
112/**
113 * A Check of the command `key` finished. A green one ends its foe (slaying any boss); a red one extends the run
114 * of reds, summons a boss on the SUMMON_AT-th, and sets a living boss's HP to `failing` when the output said.
115 */
116export const onBossCheck = (
117 s: Bosses,
118 key: string,
119 isGreen: boolean,
120 failing?: number,
121): { bosses: Bosses; event?: BossEvent } => {
122 const foe = s.foes[key]
123 if (isGreen) {
124 const { [key]: _, ...foes } = s.foes
125 return { bosses: { ...s, foes }, event: foe?.boss && { kind: 'slain', boss: foe.boss } }
126 }
127 const reds = (foe?.reds ?? 0) + 1
128 const was = foe?.boss
129 if (was) {
130 const hp = failing ?? was.hp
131 const boss = { ...was, hp, maxHp: Math.max(was.maxHp, hp) }
132 const bosses = { ...s, foes: { ...s.foes, [key]: { reds, boss } } }
133 const event: BossEvent | undefined =
134 hp < was.hp ? { kind: 'damaged', boss, by: was.hp - hp } : hp > was.hp ? { kind: 'healed', boss, by: hp - was.hp } : undefined
135 return { bosses, event }
136 }
137 if (reds < SUMMON_AT) return { bosses: { ...s, foes: { ...s.foes, [key]: { reds } } } }
138 const taken = new Set(Object.values(s.foes).flatMap(f => (f.boss ? [f.boss.name] : [])))
139 const hp = failing ?? 1
140 const boss = { name: bossName(key, taken), hp, maxHp: hp, order: s.summoned + 1 }
141 return {
142 bosses: { foes: { ...s.foes, [key]: { reds, boss } }, summoned: boss.order },
143 event: { kind: 'spawned', boss },
144 }
145}
146
147/** The boss the band shows, the newest living one, and how many more are alive. */
148export const newestBoss = (s: Bosses): { key: string; boss: Boss; others: number } | undefined => {
149 const living = Object.entries(s.foes).flatMap(([key, f]) => (f.boss ? [{ key, boss: f.boss }] : []))
150 if (living.length === 0) return undefined
151 const newest = living.reduce((a, b) => (b.boss.order > a.boss.order ? b : a))
152 return { ...newest, others: living.length - 1 }
153}
154
155export const slayAward = (boss: Boss): Award => ({
156 points: 100,
157 event: `slew the Floor Boss ${boss.name}`,
158 achievement: `Slew ${boss.name}`,
159})
160
161/** The HP bar the band draws: one heart per point up to ten, then a count. */
162export const hpBar = (b: Boss): string => (b.maxHp <= 10 ? '♥'.repeat(b.hp) + '♡'.repeat(b.maxHp - b.hp) : `HP ${b.hp}/${b.maxHp}`)
163
164/** The toast for a boss event, in the System's voice. */
165export const bossToast = (e: BossEvent): string =>
166 ({
167 spawned: `*Ding!* A Floor Boss appears: ${e.boss.name} (HP ${e.boss.hp}). The audience is on its feet.`,
168 damaged: `*Ding!* ${e.boss.name} takes ${'by' in e ? e.by : 0} damage. HP ${e.boss.hp}/${e.boss.maxHp}.`,
169 healed: `*Ding!* ${e.boss.name} regenerates ${'by' in e ? e.by : 0} HP. The Crawler made it stronger.`,
170 slain: `*Ding!* ${e.boss.name} has been slain!`,
171 })[e.kind]
172mods/branch.ts 142 lines1// The Branch Guard's pure half: which git commits and pushes a Bash line makes, where they run, and which ones
2// land on a Protected Branch. No `$` here.
3
4import { argsOf, hasAssignment, words, type Word } from './shell'
5
6export type Judged = { kind: 'pass' } | { kind: 'deny'; reason: string }
7
8/** The Branch Escape Hatch: an assignment of it anywhere in the line leaves the whole line alone. */
9export const BRANCH_HATCH = 'BRANCH_OK=1'
10
11/**
12 * What the guard needs of a repository: its checked-out branch (absent when detached), its default branch, and
13 * whether that branch is unborn (no commits yet), when its first commit may land wherever it must.
14 */
15export type Repo = { branch?: string; defaultBranch?: string; isUnborn?: boolean }
16
17export const protectedBranches = (repo: Repo): Set<string> =>
18 new Set(['main', 'master', ...(repo.defaultBranch ? [repo.defaultBranch] : [])])
19
20/**
21 * A git commit or push the line runs: `dir` is where it runs, relative to the session's directory ('' for the
22 * directory itself), from earlier `cd`s and `-C`; `args` are the words after the subcommand, unquoted. A `cd`
23 * that may have failed leaves one step per directory the command could run in.
24 */
25export type GitStep = { kind: 'commit' | 'push'; dir: string; args: string[] }
26
27/** git's global options that take the next word as their value, ahead of the subcommand. */
28const GIT_VALUE_FLAGS = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--config-env'])
29/** push's options that take the next word as their value. */
30const PUSH_VALUE_FLAGS = new Set(['--repo', '-o', '--push-option', '--receive-pack', '--exec'])
31
32const valueOf = (line: string, w: Word): string => line.slice(w.start, w.end).replace(/["']/g, '')
33
34/** `to` resolved against `from`, both relative to the session's directory. */
35const join = (from: string, to: string): string => (to.startsWith('/') || to.startsWith('~') || from === '' ? to : `${from}/${to}`)
36
37const unique = (xs: readonly string[]): string[] => [...new Set(xs)]
38
39export const gitSteps = (line: string): GitStep[] => {
40 const ws = words(line)
41 const steps: GitStep[] = []
42 // Where the next command may run: `dirs` if every `cd` since the chain last broke succeeded, `fallback` if one
43 // failed. Only `&&` carries a `cd`'s success forward; any other operator lets a failed one's command run too.
44 let dirs = ['']
45 let fallback: string[] = []
46 ws.forEach((w, i) => {
47 if (w.startsCommand && w.joinedBy.replace(/\n/g, '') !== '&&') {
48 dirs = unique([...dirs, ...fallback])
49 fallback = []
50 }
51 if (!w.isCommand) return
52 const args = argsOf(ws, i)
53 if (w.text === 'cd') {
54 fallback = unique([...fallback, ...dirs])
55 dirs = unique(dirs.map(d => (args[0] ? join(d, valueOf(line, args[0])) : '~')))
56 return
57 }
58 if (w.text !== 'git') return
59 let at = dirs
60 for (let k = 0; k < args.length; k++) {
61 const t = (args[k] as Word).text
62 if (!t.startsWith('-')) {
63 if (t === 'commit' || t === 'push') {
64 const rest = args.slice(k + 1).map(a => valueOf(line, a))
65 for (const dir of at) steps.push({ kind: t, dir, args: rest })
66 }
67 return
68 }
69 if (t === '-C' && args[k + 1]) {
70 const to = valueOf(line, args[k + 1] as Word)
71 at = unique(at.map(d => join(d, to)))
72 }
73 if (GIT_VALUE_FLAGS.has(t)) k++
74 }
75 })
76 return steps
77}
78
79/**
80 * The branches a push's arguments land on: each refspec's destination, the current branch when none is named
81 * (and no `--tags`), or 'all' for `--all`, `--branches` and `--mirror`.
82 */
83export const pushTargets = (args: readonly string[], current: string | undefined): string[] | 'all' => {
84 const positional: string[] = []
85 let isTags = false
86 for (let i = 0; i < args.length; i++) {
87 const t = args[i] as string
88 if (t === '--') {
89 positional.push(...args.slice(i + 1))
90 break
91 }
92 if (!t.startsWith('-') || t === '-') positional.push(t)
93 else if (t === '--all' || t === '--branches' || t === '--mirror') return 'all'
94 else if (t === '--tags') isTags = true
95 else if (PUSH_VALUE_FLAGS.has(t)) i++
96 }
97 const refspecs = positional.slice(1)
98 if (refspecs.length === 0) return isTags || !current ? [] : [current]
99 return refspecs.flatMap(spec => {
100 const s = spec.replace(/^\+/, '')
101 const dst = s.includes(':') ? s.slice(s.indexOf(':') + 1) : s
102 const name = dst === 'HEAD' || dst === '@' ? current : dst.replace(/^refs\/heads\//, '')
103 return name ? [name] : []
104 })
105}
106
107const HATCH_NOTE = `Prefix ${BRANCH_HATCH} only when the Crawler asked for this to land on it.`
108
109/**
110 * What the guard does with a Bash line: deny a commit made on a Protected Branch or a push that lands on one,
111 * unless the line carries the Branch Escape Hatch. `repoOf` gives the repository at a GitStep's `dir`, or
112 * undefined outside one, where the guard has no say.
113 */
114export const branchGuard = (line: string, repoOf: (dir: string) => Repo | undefined): Judged => {
115 if (hasAssignment(words(line), BRANCH_HATCH)) return { kind: 'pass' }
116 for (const step of gitSteps(line)) {
117 const repo = repoOf(step.dir)
118 if (!repo) continue
119 const guarded = protectedBranches(repo)
120 if (step.kind === 'commit') {
121 if (repo.branch && !repo.isUnborn && guarded.has(repo.branch))
122 return {
123 kind: 'deny',
124 reason:
125 `Branch Guard: \`git commit\` on \`${repo.branch}\`, a Protected Branch. ` +
126 `Branch first with \`git switch -c <name>\` and commit there. ${HATCH_NOTE}`,
127 }
128 continue
129 }
130 const targets = pushTargets(step.args, repo.branch)
131 const hit = targets === 'all' ? [...guarded].join('`, `') : targets.find(t => guarded.has(t))
132 if (hit)
133 return {
134 kind: 'deny',
135 reason:
136 `Branch Guard: this \`git push\` lands on \`${hit}\`, a Protected Branch. ` +
137 `Push a feature branch (\`git switch -c <name>\`) and open a pull request instead. ${HATCH_NOTE}`,
138 }
139 }
140 return { kind: 'pass' }
141}
142mods/podman.ts 77 lines1// The Podman Guard's pure half: which Bash commands run Docker, what they become under podman, and which
2// ones podman cannot stand in for. No `$` here.
3
4import { argsOf, attachedFlag, hasAssignment, words, type Word } from './shell'
5
6export type Guarded =
7 | { kind: 'pass' }
8 | { kind: 'rewrite'; command: string }
9 | { kind: 'deny'; reason: string }
10
11/** The Docker Escape Hatch: an assignment of it anywhere in the line leaves the whole line alone. */
12export const ESCAPE_HATCH = 'DOCKER_OK=1'
13
14/** Daemon-Only Commands: subcommands that need a real Docker daemon or Docker's own services. */
15export const DAEMON_ONLY = ['context', 'swarm', 'service', 'stack', 'node', 'plugin', 'trust', 'scout'] as const
16
17/** The options whose value mounts or dials a daemon socket, as in `-v /var/run/docker.sock:/s` or `-H unix://...`. */
18const SOCKET_FLAGS = new Set(['-v', '--volume', '--mount', '-H', '--host'])
19/** Docker's global options that take the next word as their value, ahead of the subcommand. */
20const DOCKER_VALUE_FLAGS = new Set(['--config', '-c', '--context', '-H', '--host', '-l', '--log-level', '--tlscacert', '--tlscert', '--tlskey'])
21
22/**
23 * What the guard does with a Bash line: pass it when it runs no Docker or carries the Escape Hatch, deny a
24 * Daemon-Only Command or a docker.sock mount, and otherwise rewrite each `docker` to `podman` and each
25 * `docker-compose` to `podman compose`, leaving every other byte as it was.
26 */
27export const guard = (line: string): Guarded => {
28 const ws = words(line)
29 const dockers = ws
30 .map((w, i) => ({ w, args: argsOf(ws, i) }))
31 .filter(({ w }) => w.isCommand && (w.text === 'docker' || w.text === 'docker-compose'))
32 if (dockers.length === 0 || hasAssignment(ws, ESCAPE_HATCH)) return { kind: 'pass' }
33
34 const daemonOnly = dockers
35 .filter(({ w }) => w.text === 'docker')
36 .map(({ args }) => subcommandOf(args))
37 .find(sub => sub !== undefined && (DAEMON_ONLY as readonly string[]).includes(sub))
38 const mountsSocket = dockers.some(({ args }) =>
39 args.some(
40 (a, k) =>
41 line.slice(a.start, a.end).includes('docker.sock') &&
42 (SOCKET_FLAGS.has(args[k - 1]?.text ?? '') || SOCKET_FLAGS.has(attachedFlag(a.text) ?? '')),
43 ),
44 )
45 if (daemonOnly || mountsSocket) {
46 const what = daemonOnly ? `\`docker ${daemonOnly}\`` : 'a docker.sock mount'
47 return {
48 kind: 'deny',
49 reason:
50 `Podman Guard: ${what} needs the Docker daemon, which podman cannot stand in for. ` +
51 `Use podman's own way, or prefix the command with ${ESCAPE_HATCH} if real Docker is required.`,
52 }
53 }
54
55 let command = line
56 for (const { w } of [...dockers].reverse()) {
57 const to = w.text === 'docker' ? 'podman' : 'podman compose'
58 command = command.slice(0, w.start) + to + command.slice(w.end)
59 }
60 return { kind: 'rewrite', command }
61}
62
63/** Docker's subcommand: the first argument past its global options and their values. */
64const subcommandOf = (args: readonly Word[]): string | undefined => {
65 for (let i = 0; i < args.length; i++) {
66 const t = (args[i] as Word).text
67 if (!t.startsWith('-')) return t
68 if (DOCKER_VALUE_FLAGS.has(t)) i++
69 }
70 return undefined
71}
72
73/** The note the model reads after a rewritten command's result. */
74export const rewriteNote = (from: string, to: string): string =>
75 `[Podman Guard: this ran as \`${to}\`, not \`${from}\`. Output and errors are podman's. ` +
76 `Prefix ${ESCAPE_HATCH} only when real Docker is required.]`
77mods/tdd.ts 78 lines1// The TDD Band's pure half: the TDD Phase that subagent spawns and Checks lead to, and what the band says.
2// No `$` here.
3
4export type TddPhase = 'RED' | 'GREEN' | 'REFACTOR'
5
6/** `auto`: hidden until the first Check or TDD subagent; `shown`/`hidden`: what it is now, `/tdd` flips it. */
7export type BandVisibility = 'auto' | 'shown' | 'hidden'
8
9export type Tdd = {
10 phase?: TddPhase
11 /** The last Check since the phase was set: true green, false red, absent none yet. */
12 lastCheck?: boolean
13 /** True once a TDD subagent set the phase; until then Checks alone set it. */
14 isAgentLed: boolean
15 visibility: BandVisibility
16}
17
18export const initialTdd: Tdd = { isAgentLed: false, visibility: 'auto' }
19
20/** The TDD subagents, by their name without the plugin prefix, and the phase each starts. */
21export const AGENT_PHASE: Record<string, TddPhase> = {
22 'red-phase-tester': 'RED',
23 'green-phase-implementer': 'GREEN',
24 'tdd-refactor-specialist': 'REFACTOR',
25}
26
27/** The band's buttons: hotkey, label, and the prompt draft it puts in the box. */
28export const DRAFTS = [
29 { hotkey: '1', label: 'Red', agent: 'red-phase-tester' },
30 { hotkey: '2', label: 'Green', agent: 'green-phase-implementer' },
31 { hotkey: '3', label: 'Refactor', agent: 'tdd-refactor-specialist' },
32].map(d => ({ ...d, draft: `Use the ${d.agent} agent to ` }))
33
34const appear = (v: BandVisibility): BandVisibility => (v === 'auto' ? 'shown' : v)
35
36/** The phase a subagent type starts, `dotfiles-dev-tools:red-phase-tester` and `red-phase-tester` alike. */
37export const agentPhase = (subagentType: string): TddPhase | undefined =>
38 AGENT_PHASE[subagentType.slice(subagentType.lastIndexOf(':') + 1)]
39
40/** A subagent started: a TDD one sets the phase and waits for its Check; any other changes nothing. */
41export const onAgent = (t: Tdd, subagentType: string): Tdd => {
42 const phase = agentPhase(subagentType)
43 return phase ? { phase, isAgentLed: true, visibility: appear(t.visibility) } : t
44}
45
46/** A Check finished: it confirms or contradicts an agent-led phase, and alone sets RED or GREEN. */
47export const onCheck = (t: Tdd, isGreen: boolean): Tdd => ({
48 ...t,
49 phase: t.isAgentLed ? t.phase : isGreen ? 'GREEN' : 'RED',
50 lastCheck: isGreen,
51 visibility: appear(t.visibility),
52})
53
54export const toggle = (t: Tdd): Tdd => ({ ...t, visibility: t.visibility === 'shown' ? 'hidden' : 'shown' })
55
56export const isShown = (t: Tdd): boolean => t.visibility === 'shown'
57
58export type Mood = 'good' | 'bad' | 'waiting'
59
60/**
61 * What the band says beside the phase. RED wants a red Check (the new test fails first), GREEN and REFACTOR a
62 * green one; a phase the Checks set alone always agrees with them.
63 */
64export const verdictOf = (t: Tdd): { mood: Mood; note: string } => {
65 if (t.lastCheck === undefined) return { mood: 'waiting', note: 'awaiting a Check' }
66 if (!t.isAgentLed) return t.lastCheck ? { mood: 'good', note: 'Check ✔' } : { mood: 'bad', note: 'Check ✖' }
67 switch (t.phase) {
68 case 'RED':
69 return t.lastCheck
70 ? { mood: 'bad', note: '⚠ tests pass already: they test nothing new' }
71 : { mood: 'good', note: '✔ failing, as a fresh test should' }
72 case 'GREEN':
73 return t.lastCheck ? { mood: 'good', note: '✔ green' } : { mood: 'bad', note: '✖ still red' }
74 default:
75 return t.lastCheck ? { mood: 'good', note: '✔ still green' } : { mood: 'bad', note: '✖ broke it' }
76 }
77}
78mods/mail.ts 336 lines1// Sponsor Mail's pure half: the Watched PR as GitHub reports it, which of its comments are Mail, when Mail is
2// Answered, what its checks did since the last look, and which Bash lines open the watch or post as Claude.
3// No `$` here.
4
5import { argsOf, words } from './shell'
6import type { Award } from './points'
7
8export type CheckState = 'pass' | 'fail' | 'pending'
9export type Check = { name: string; state: CheckState }
10
11/**
12 * One comment on the PR: `c:` a top-level comment, `r:` a review's body, `t:` a review thread's comment. A thread's
13 * comments carry `thread`, the id of its first comment, and whether the thread is resolved.
14 */
15export type Item = { id: string; author: string; at: string; thread?: string; isResolved?: boolean }
16
17export type Pr = {
18 number: number
19 url: string
20 state: 'OPEN' | 'MERGED' | 'CLOSED'
21 branch: string
22 /** The login gh speaks as, which is also the login Claude posts as. */
23 viewer: string
24 checks: Check[]
25 items: Item[]
26 /** GitHub holds more comments than the look fetched: an item missing from it may still be there. */
27 isTruncated?: boolean
28}
29
30export type MailEntry = { id: string; author: string }
31
32export type MailWatch = {
33 number: number
34 url: string
35 branch: string
36 /** The repository's root, where every gh call of the watch runs. */
37 root: string
38 /** Every item already looked at: the baseline, delivered Mail and Claude's own. */
39 seen: string[]
40 /** The items Claude posted. */
41 mine: string[]
42 /** Delivered Mail not yet Answered. */
43 mail: MailEntry[]
44 checks: Check[]
45 /** When the PR last changed, for slowing the poll down. */
46 changedAt: number
47}
48
49export type MailEvent =
50 | { kind: 'mail'; mail: MailEntry[] }
51 | { kind: 'answered'; count: number }
52 | { kind: 'red'; names: string[] }
53 | { kind: 'green' }
54 | { kind: 'merged' }
55 | { kind: 'closed' }
56
57/** One GraphQL call answers everything a poll needs; `$n` is the PR's number. */
58export const PR_QUERY = `query($owner:String!,$repo:String!,$n:Int!){viewer{login} repository(owner:$owner,name:$repo){pullRequest(number:$n){number url state headRefName
59comments(last:100){totalCount nodes{databaseId author{login} createdAt}}
60reviews(last:100){totalCount nodes{databaseId author{login} createdAt body}}
61reviewThreads(last:100){totalCount nodes{isResolved root:comments(first:1){nodes{databaseId}}
62comments(last:100){totalCount nodes{databaseId author{login} createdAt}}}}
63commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){nodes{__typename ... on CheckRun{name status conclusion} ... on StatusContext{context state}}}}}}}}}}`
64
65/** A PR's URL as `{ owner, repo, number }`, or undefined for anything else. */
66export const prRefOf = (text: string): { owner: string; repo: string; number: number } | undefined => {
67 const m = text.match(/https:\/\/[^/\s]+\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/)
68 return m ? { owner: m[1]!, repo: m[2]!, number: Number(m[3]) } : undefined
69}
70
71/** The gh argv for one look at the PR at `url`. */
72export const prQueryArgv = (url: string): string[] => {
73 const ref = prRefOf(url)
74 return [
75 'gh', 'api', 'graphql',
76 '-F', `owner=${ref?.owner ?? '{owner}'}`, '-F', `repo=${ref?.repo ?? '{repo}'}`, '-F', `n=${ref?.number ?? 0}`,
77 '-f', `query=${PR_QUERY}`,
78 ]
79}
80
81type Node = { databaseId?: number; author?: { login?: string } | null; createdAt?: string; body?: string }
82type Connection<T> = { totalCount?: number; nodes?: T[] }
83type Thread = { isResolved?: boolean; root?: Connection<Node>; comments?: Connection<Node> }
84
85const isCut = (c: Connection<unknown> | undefined): boolean => (c?.totalCount ?? 0) > (c?.nodes?.length ?? 0)
86
87const PASSING = new Set(['SUCCESS', 'NEUTRAL', 'SKIPPED'])
88
89const checkOf = (n: Record<string, unknown>): Check | undefined => {
90 if (n.__typename === 'CheckRun') {
91 const state: CheckState = n.status !== 'COMPLETED' ? 'pending' : PASSING.has(String(n.conclusion)) ? 'pass' : 'fail'
92 return { name: String(n.name), state }
93 }
94 if (n.__typename === 'StatusContext') {
95 const s = String(n.state)
96 const state: CheckState = s === 'SUCCESS' ? 'pass' : s === 'PENDING' || s === 'EXPECTED' ? 'pending' : 'fail'
97 return { name: String(n.context), state }
98 }
99 return undefined
100}
101
102const itemOf = (prefix: string, n: Node, thread?: Pick<Item, 'thread' | 'isResolved'>): Item => ({
103 id: `${prefix}:${n.databaseId}`,
104 author: n.author?.login ?? 'ghost',
105 at: n.createdAt ?? '',
106 ...thread,
107})
108
109/** The PR in a `PR_QUERY` answer; undefined for an error or anything that is not one. */
110export const parsePr = (text: string): Pr | undefined => {
111 let d: any
112 try {
113 d = JSON.parse(text)
114 } catch {
115 return undefined
116 }
117 const p = d?.data?.repository?.pullRequest
118 if (!p || typeof p.number !== 'number') return undefined
119 const threads: Thread[] = p.reviewThreads?.nodes ?? []
120 const items: Item[] = [
121 ...((p.comments?.nodes ?? []) as Node[]).map(n => itemOf('c', n)),
122 // A review with no body is the wrapper GitHub makes around thread comments; the comments are the items.
123 ...((p.reviews?.nodes ?? []) as Node[]).filter(n => (n.body ?? '').trim() !== '').map(n => itemOf('r', n)),
124 ...threads.flatMap(t => {
125 const nodes = t.comments?.nodes ?? []
126 const first = t.root?.nodes?.[0] ?? nodes[0]
127 const thread = first ? `t:${first.databaseId}` : undefined
128 return nodes.map(n => itemOf('t', n, { thread, isResolved: t.isResolved === true }))
129 }),
130 ]
131 const contexts: Record<string, unknown>[] = p.commits?.nodes?.[0]?.commit?.statusCheckRollup?.contexts?.nodes ?? []
132 return {
133 number: p.number,
134 url: String(p.url ?? ''),
135 state: p.state === 'MERGED' || p.state === 'CLOSED' ? p.state : 'OPEN',
136 branch: String(p.headRefName ?? ''),
137 viewer: String(d.data.viewer?.login ?? ''),
138 checks: contexts.map(checkOf).filter((c): c is Check => c !== undefined),
139 items,
140 isTruncated: [p.comments, p.reviews, p.reviewThreads, ...threads.map(t => t.comments)].some(isCut),
141 }
142}
143
144export const startWatch = (pr: Pr, root: string, now: number): MailWatch => ({
145 number: pr.number,
146 url: pr.url,
147 branch: pr.branch,
148 root,
149 seen: pr.items.map(i => i.id),
150 mine: [],
151 mail: [],
152 checks: pr.checks,
153 changedAt: now,
154})
155
156/** Right after Claude posted: the viewer's items that appeared since the last look are Claude's. */
157export const claimMine = (w: MailWatch, pr: Pr): MailWatch => {
158 const seen = new Set(w.seen)
159 const posted = pr.items.filter(i => !seen.has(i.id) && i.author === pr.viewer).map(i => i.id)
160 return posted.length === 0 ? w : { ...w, seen: [...w.seen, ...posted], mine: [...w.mine, ...posted] }
161}
162
163const isAnswered = (item: Item, pr: Pr, mine: ReadonlySet<string>): boolean => {
164 if (item.thread !== undefined && item.isResolved) return true
165 return pr.items.some(
166 m => mine.has(m.id) && m.at > item.at && (item.thread === undefined || m.thread === item.thread),
167 )
168}
169
170export const tally = (checks: readonly Check[]) => ({
171 passed: checks.filter(c => c.state === 'pass').length,
172 total: checks.length,
173 failed: checks.filter(c => c.state === 'fail').map(c => c.name),
174 pending: checks.filter(c => c.state === 'pending').map(c => c.name),
175})
176
177const isAllGreen = (checks: readonly Check[]): boolean => checks.length > 0 && checks.every(c => c.state === 'pass')
178
179/** One look at the PR: the watch after it (undefined once the PR is merged or closed) and what happened. */
180export const step = (w: MailWatch, pr: Pr, now: number): { watch?: MailWatch; events: MailEvent[] } => {
181 if (pr.state === 'MERGED') return { watch: undefined, events: [{ kind: 'merged' }] }
182 if (pr.state === 'CLOSED') return { watch: undefined, events: [{ kind: 'closed' }] }
183 const events: MailEvent[] = []
184 const seen = new Set(w.seen)
185 const mine = new Set(w.mine)
186 const byId = new Map(pr.items.map(i => [i.id, i]))
187
188 const fresh = pr.items.filter(i => !seen.has(i.id) && !mine.has(i.id)).map(i => ({ id: i.id, author: i.author }))
189 if (fresh.length > 0) events.push({ kind: 'mail', mail: fresh })
190
191 const open = (m: MailEntry) => {
192 const item = byId.get(m.id)
193 // Mail a truncated look no longer shows has only fallen out of it; a whole look without it says it is gone.
194 if (item === undefined) return pr.isTruncated === true
195 return !isAnswered(item, pr, mine)
196 }
197 const answered = w.mail.filter(m => byId.has(m.id) && !open(m)).length
198 if (answered > 0) events.push({ kind: 'answered', count: answered })
199 const mail = [...w.mail, ...fresh].filter(open)
200
201 const wasFailing = new Set(w.checks.filter(c => c.state === 'fail').map(c => c.name))
202 const red = pr.checks.filter(c => c.state === 'fail' && !wasFailing.has(c.name)).map(c => c.name)
203 if (red.length > 0) events.push({ kind: 'red', names: red })
204 if (isAllGreen(pr.checks) && !isAllGreen(w.checks)) events.push({ kind: 'green' })
205
206 const isChanged = events.length > 0 || JSON.stringify(pr.checks) !== JSON.stringify(w.checks)
207 return {
208 watch: {
209 ...w,
210 seen: [...w.seen, ...fresh.map(m => m.id)],
211 mail,
212 checks: pr.checks,
213 changedAt: isChanged ? now : w.changedAt,
214 },
215 events,
216 }
217}
218
219export const POLL_PENDING_MS = 30_000
220export const POLL_MS = 120_000
221export const POLL_QUIET_MS = 600_000
222const QUIET_AFTER_MS = 3600_000
223
224/** How long until the next look: quick while a check runs, slow once the PR has been quiet for an hour. */
225export const nextPollMs = (w: MailWatch, now: number): number => {
226 if (w.checks.some(c => c.state === 'pending')) return POLL_PENDING_MS
227 return now - w.changedAt > QUIET_AFTER_MS ? POLL_QUIET_MS : POLL_MS
228}
229
230// ---------------------------------------------------------------------------------------- Bash lines
231
232/** Each gh command the line runs: its argument words (quoted text masked) and its own span of the line. */
233const ghCommands = (line: string): { args: string[]; text: string }[] => {
234 const ws = words(line)
235 return ws.flatMap((w, i) => {
236 if (!w.isCommand || w.text !== 'gh') return []
237 const args = argsOf(ws, i)
238 const end = (args.at(-1) ?? w).end
239 return [{ args: args.map(a => a.text.replace(/^["']|["']$/g, '')), text: line.slice(w.start, end) }]
240 })
241}
242
243export const isPrCreate = (line: string): boolean =>
244 ghCommands(line).some(({ args: a }) => a[0] === 'pr' && a[1] === 'create')
245
246/**
247 * The directory the line's gh pr create runs in, from the cds before it: undefined when none moved, null when the
248 * shell computes it (a variable, a substitution, `cd -`).
249 */
250export const createDirOf = (line: string): string | null | undefined => {
251 const ws = words(line)
252 const at = ws.findIndex((w, i) => {
253 const a = argsOf(ws, i)
254 return w.isCommand && w.text === 'gh' && a[0]?.text === 'pr' && a[1]?.text === 'create'
255 })
256 let dir: string | null | undefined
257 for (let i = 0; i < at; i++) {
258 if (!ws[i]!.isCommand || ws[i]!.text !== 'cd') continue
259 const arg = argsOf(ws, i).find(a => a.text === '-' || !a.text.startsWith('-'))
260 const to = arg?.text ?? '~'
261 // The words drop a substitution's `$(`; the line between cd and its argument still holds it.
262 const raw = line.slice(ws[i]!.end, arg?.end ?? ws[i]!.end)
263 if (to === '-' || /[$`\x00"'*?\\()]/.test(raw)) dir = null
264 else if (/^[/~]/.test(to) || dir === undefined) dir = to
265 else if (dir !== null) dir = `${dir}/${to}`
266 }
267 return dir
268}
269
270const WRITE_FLAGS = new Set(['-f', '-F', '--field', '--raw-field', '--input'])
271
272/** A GraphQL call through gh writes when its query is a mutation; a query from a file or stdin may be one. */
273const isMutation = (text: string): boolean => {
274 const query = text.match(/(?:-[fF]|--(?:raw-)?field)[\s=]+['"]?query=['"]?\s*(\S*)/)
275 if (!query) return /(?:^|\s)--input\b/.test(text)
276 return /^(?:mutation\b|@)/.test(query[1]!)
277}
278
279/** The line posts to GitHub as the viewer: a PR comment or review, or a write through gh api. */
280export const isPost = (line: string): boolean =>
281 ghCommands(line).some(({ args: a, text }) => {
282 if (a[0] === 'pr') return a[1] === 'comment' || a[1] === 'review'
283 if (a[0] !== 'api') return false
284 if (a.includes('graphql')) return isMutation(text)
285 const method = a.findIndex(x => x === '-X' || x === '--method')
286 if (method >= 0) return (a[method + 1] ?? '').toUpperCase() !== 'GET'
287 const attached = a.find(x => /^(?:-X|--method=)/.test(x) && x.length > 2)
288 if (attached) return !/GET$/i.test(attached)
289 return a.some(x => WRITE_FLAGS.has(x) || /^--(?:field|raw-field|input)=/.test(x))
290 })
291
292// ------------------------------------------------------------------------------------ what it says
293
294const authorsOf = (mail: readonly MailEntry[]): string => {
295 const counts = new Map<string, number>()
296 for (const m of mail) counts.set(m.author, (counts.get(m.author) ?? 0) + 1)
297 return [...counts].map(([a, n]) => (n > 1 ? `${a} ×${n}` : a)).join(', ')
298}
299
300export const mailNotice = (w: MailWatch, mail: readonly MailEntry[]): string =>
301 `${mail.length} new on PR #${w.number} from ${authorsOf(mail)}`
302
303export const redNotice = (w: MailWatch, names: readonly string[]): string =>
304 `${names.join(', ')} went red on PR #${w.number}`
305
306export const addressPrompt = (w: MailWatch): string =>
307 `Address the new review comments on PR #${w.number} (${w.url}): ${w.mail.length} unanswered, from ` +
308 `${authorsOf(w.mail)}. Read them with gh, fix what is warranted, and reply in each thread saying what you did.`
309
310export const fixPrompt = (w: MailWatch): string => {
311 const { failed } = tally(w.checks)
312 const isOne = failed.length === 1
313 return (
314 `Investigate the failing CI check${isOne ? '' : 's'} ${failed.join(', ')} on PR #${w.number} ` +
315 `(gh pr checks ${w.number}) and fix ${isOne ? 'it' : 'them'}.`
316 )
317}
318
319// ------------------------------------------------------------------------------------------- awards
320
321export const mergeAward = (w: Pick<MailWatch, 'number'>): Award => ({
322 points: 50,
323 event: `merged PR #${w.number}: the sponsors are thrilled`,
324 achievement: 'Sponsored Content',
325})
326
327export const redAward = (w: Pick<MailWatch, 'number'>, names: readonly string[]): Award => ({
328 points: -10,
329 event: `CI check ${names.join(', ')} went red on PR #${w.number}`,
330})
331
332export const answeredAward = (w: Pick<MailWatch, 'number'>, count: number): Award => ({
333 points: 5 * count,
334 event: `answered ${count} piece${count === 1 ? '' : 's'} of Sponsor Mail on PR #${w.number}`,
335})
336mods/beast.ts 184 lines1// Beast Watch's pure half: where Beast is, what a look at it says (the Beast State), which Bash lines wake the
2// watch or start a Dispatch, and what the Beast Guard does with one. No `$` here.
3
4import { argsOf, hasAssignment, words } from './shell'
5
6export type BeastState = 'up' | 'loading' | 'down'
7
8export type Reading = { state: BeastState; reason?: string; vram?: { usedMb: number; totalMb: number } }
9
10/** What one look gathered: llama-server's /health, nvidia-smi over ssh, and the one-token completion probe. */
11export type Probe = {
12 /** `code` 0 when nothing answered. */
13 health: { code: number; body: string }
14 smi: { exitCode: number; stdout: string; stderr: string }
15 /** The Dispatches' model on a router (llama-server serving models by name); absent when it says nothing. */
16 model?: ModelState
17 /** `skipped` while a Dispatch runs (it would queue behind it); absent when not tried. */
18 completion?: 'ok' | 'timeout' | 'error' | 'skipped'
19}
20
21export type ModelState = 'loaded' | 'loading' | 'unloaded' | 'failed' | 'missing'
22
23/** The Beast Escape Hatch: an assignment of it anywhere in the line leaves the whole line alone. */
24export const BEAST_HATCH = 'BEAST_OK=1'
25
26/** A variable's value in pi-implementer's env file (`NAME=value`, optionally exported or quoted). */
27const envOf = (envText: string, name: string): string | undefined =>
28 envText.match(new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=\\s*["']?([^"'\\s]+)`, 'm'))?.[1]
29
30/** Beast's llama-server, from pi-implementer's env file, without a trailing slash. */
31export const llamaUrlOf = (envText: string): string | undefined => envOf(envText, 'LLAMA_URL')?.replace(/\/+$/, '')
32
33/** The API key pi-implementer sends llama-server, from the same env file. */
34export const llamaKeyOf = (envText: string): string | undefined => envOf(envText, 'LLAMA_API_KEY')
35
36/** The model pi-implementer dispatches to, by the name a router serves it under. */
37export const modelAliasOf = (envText: string): string | undefined => envOf(envText, 'MODEL_ALIAS')
38
39export const hostOf = (url: string): string | undefined => url.match(/^[a-z]+:\/\/(?:[^@/]*@)?([^:/]+)/i)?.[1]
40
41/** nvidia-smi's query of memory per GPU (`used, total` in MiB, one line each). */
42export const SMI_QUERY = 'nvidia-smi --query-gpu=memory.used,memory.total --format=csv,noheader,nounits'
43
44const GPU_LOST = /GPU is lost|Unable to determine the device handle|NVIDIA-SMI has failed/i
45
46const vramOf = (stdout: string): Reading['vram'] => {
47 const rows = stdout
48 .split('\n')
49 .map(l => l.split(',').map(x => Number(x.trim())))
50 .filter(r => r.length === 2 && r.every(Number.isFinite))
51 if (rows.length === 0) return undefined
52 return { usedMb: rows.reduce((s, r) => s + r[0]!, 0), totalMb: rows.reduce((s, r) => s + r[1]!, 0) }
53}
54
55/** The Beast State a look gives. The GPU outranks llama-server, which outranks the completion probe. */
56export const judge = (p: Probe): Reading => {
57 if (p.smi.exitCode === 255) return { state: 'down', reason: 'ssh unreachable' }
58 if (p.smi.exitCode !== 0) {
59 return { state: 'down', reason: GPU_LOST.test(p.smi.stdout + p.smi.stderr) ? 'GPU lost' : 'nvidia-smi failed' }
60 }
61 const vram = vramOf(p.smi.stdout)
62 if (!vram) return { state: 'down', reason: 'no GPU' }
63 if (p.health.code === 0) return { state: 'down', reason: 'llama-server unreachable' }
64 if (p.health.code === 503 && /loading/i.test(p.health.body)) return { state: 'loading' }
65 if (p.health.code !== 200) return { state: 'down', reason: `health ${p.health.code}` }
66 if (p.model === 'loading') return { state: 'loading' }
67 if (p.model === 'missing') return { state: 'down', reason: 'model not served' }
68 if (p.model === 'failed') return { state: 'down', reason: 'model failed to load' }
69 if (p.completion === 'timeout') return { state: 'down', reason: 'wedged' }
70 if (p.completion === 'error') return { state: 'down', reason: 'completion failed' }
71 return { state: 'up', vram }
72}
73
74const gb = (mb: number): number => Math.round(mb / 1024)
75
76export const beastSegment = (r: Reading): string =>
77 r.state === 'up'
78 ? `beast 🟢${r.vram ? ` ${gb(r.vram.usedMb)}/${gb(r.vram.totalMb)}GB` : ''}`
79 : r.state === 'loading'
80 ? 'beast ⏳ loading'
81 : `beast 🔴 ${r.reason ?? 'down'}`
82
83/** What a new reading is worth telling: Beast going Down, or coming back Up from Down. */
84export const transition = (before: Reading | undefined, after: Reading): 'down' | 'recovered' | undefined =>
85 after.state === 'down' && before?.state !== 'down'
86 ? 'down'
87 : before?.state === 'down' && after.state === 'up'
88 ? 'recovered'
89 : undefined
90
91// ---------------------------------------------------------------------------------------- Bash lines
92
93const PI_DISPATCH = /(?:^|\/)pi-dispatch(?:\.py)?$/
94
95/** Commands that run the script they are handed; any other command naming it (echo, rg) only mentions it. */
96const RUNNER = /(?:^|\/)(?:python[\d.]*|uv|uvx|env|timeout|nice|nohup|time|exec)$/
97
98/** What a runner takes before the script: a flag, a duration, `uv run`, an assignment. */
99const RUNNER_ARG = /^(?:-.*|\d+(?:\.\d+)?[smhd]?|run|[A-Za-z_]\w*=.*)$/
100
101/** A runner's flags that take the next word as their value: python's `-W`, uv's `--with`, timeout's `-s`. */
102const RUNNER_VALUE_FLAG =
103 /^(?:-[WXpnsk]|--(?:with|with-requirements|python|project|directory|env-file|extra|group|signal|kill-after))$/
104
105/** The line starts a Dispatch: `pi-dispatch.py dispatch`, run directly or through a chain of runners. */
106export const isDispatch = (line: string): boolean => {
107 const ws = words(line)
108 return ws.some((w, i) => {
109 if (!w.isCommand) return false
110 const run = [w, ...argsOf(ws, i)]
111 for (let k = 0; k < run.length; k++) {
112 const t = run[k]!.text
113 if (PI_DISPATCH.test(t)) return run[k + 1]?.text === 'dispatch'
114 if (!RUNNER.test(t) && !(k > 0 && RUNNER_ARG.test(t))) return false
115 if (k > 0 && RUNNER_VALUE_FLAG.test(t)) k++
116 }
117 return false
118 })
119}
120
121/** The line uses Beast: pi-implementer's tools, llama-server, or anything naming Beast's host. */
122export const isBeastUse = (line: string, host: string | undefined): boolean => {
123 if (words(line).some(w => /(?:^|\/)(?:pi-dispatch(?:\.py)?|pi-implementer|llama-server)$/.test(w.text))) return true
124 if (!host) return false
125 const escaped = host.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
126 return new RegExp(`(?:^|[^\\w.-])${escaped}(?![\\w.-]*\\w)`).test(line)
127}
128
129export type BeastJudged = { kind: 'pass' } | { kind: 'wait' } | { kind: 'deny'; reason: string }
130
131/** The line is a Dispatch without the Escape Hatch: the Beast Guard needs a fresh look at Beast to judge it. */
132export const isGuarded = (line: string): boolean => isDispatch(line) && !hasAssignment(words(line), BEAST_HATCH)
133
134/** The Beast Guard: a Dispatch while Down is refused, while Loading it waits; the Escape Hatch passes it. */
135export const beastGuard = (line: string, r: Reading): BeastJudged => {
136 if (!isGuarded(line) || r.state === 'up') return { kind: 'pass' }
137 if (r.state === 'loading') return { kind: 'wait' }
138 return {
139 kind: 'deny',
140 reason:
141 `Beast Guard: Beast is Down (${r.reason ?? 'unknown'}), so this Dispatch would burn its whole timeout. ` +
142 `Bring Beast back (/beast checks it), or prefix the line with ${BEAST_HATCH} to dispatch anyway.`,
143 }
144}
145
146export const LOADING_WAIT_MS = 180_000
147
148/** `curl -w '\n%{http_code}'` output as /health's answer: code 0 when nothing answered. */
149export const healthOf = (stdout: string): Probe['health'] => {
150 const cut = stdout.lastIndexOf('\n')
151 const code = Number(stdout.slice(cut + 1).trim())
152 return { code: Number.isFinite(code) ? code : 0, body: cut < 0 ? '' : stdout.slice(0, cut) }
153}
154
155/** The completion probe's outcome from `curl -w '%{http_code}'`: curl's exit 28 is its timeout. */
156export const completionOf = (exitCode: number, stdout: string): NonNullable<Probe['completion']> =>
157 exitCode === 28 ? 'timeout' : exitCode === 0 && stdout.trim() === '200' ? 'ok' : 'error'
158
159/** llama-server's /slots answer lists its slots and none is generating, so a completion probe would not queue. */
160export const isIdle = (slotsJson: string): boolean => {
161 try {
162 const slots: unknown = JSON.parse(slotsJson)
163 return Array.isArray(slots) && slots.every(s => (s as { is_processing?: unknown })?.is_processing !== true)
164 } catch {
165 return false
166 }
167}
168
169/** The model's state in a router's /v1/models; undefined when the server is no router or did not answer. */
170export const modelStateOf = (modelsJson: string, alias: string | undefined): ModelState | undefined => {
171 if (!alias) return undefined
172 let d: { data?: { id?: string; status?: { value?: string } }[] }
173 try {
174 d = JSON.parse(modelsJson)
175 } catch {
176 return undefined
177 }
178 const models = Array.isArray(d?.data) ? d.data : undefined
179 if (!models || !models.some(m => m.status)) return undefined
180 const v = models.find(m => m.id === alias)?.status?.value
181 if (v === undefined) return 'missing'
182 return v === 'loaded' || v === 'loading' || v === 'unloaded' ? v : 'failed'
183}
184mods/voice.ts 112 lines1// The System's voice: Spinner Words and the Verdict under a Notable Turn. No `$` here.
2
3export type Mood = 'collapsing' | 'debuffed' | 'dispatching' | 'normal'
4
5/** Spinner Words by what the session is going through; the engine adds its own ellipsis after each. */
6export const SPINNER_WORDS: Record<Mood, readonly string[]> = {
7 normal: [
8 'Consulting the Syndicate',
9 'Rigging the betting pools',
10 'Reviewing the sponsor contracts',
11 'Polishing the loot boxes',
12 'Warming up the studio audience',
13 'Calibrating the death traps',
14 'Cueing the dramatic music',
15 'Re-reading the Crawler waivers',
16 'Counting galactic credits',
17 'Pre-writing the obituary',
18 'Adjusting the camera drones',
19 'Negotiating with the floor boss',
20 'Inspecting the Crawler for shoes',
21 'Lowering expectations',
22 'Feeding the mantaurs',
23 'Measuring the ratings',
24 ],
25 debuffed: [
26 'Applying additional shame',
27 'Replaying the blunder in slow motion',
28 'Selling highlight reels of the failure',
29 'Updating the blooper compilation',
30 'Letting the audience boo',
31 'Drafting the penalty notice',
32 ],
33 collapsing: [
34 'Ceiling collapsing',
35 'Counting down to the cave-in',
36 'Evacuating the context window',
37 'Shoring up the tunnel',
38 'Listening to the walls creak',
39 ],
40 dispatching: [
41 'Watching the local idiot work',
42 'Supervising the cheap labor',
43 'Placing bets on the local model',
44 'Monitoring the minion',
45 ],
46}
47
48/** From this much context the walls are coming down. */
49export const COLLAPSING_FROM = 80
50
51export type Moodboard = { contextPercent?: number; debuff?: string; isDispatching: boolean }
52
53/** The mood that wins: a collapsing context, then a debuff, then a running Dispatch. */
54export const moodOf = (m: Moodboard): Mood =>
55 (m.contextPercent ?? 0) >= COLLAPSING_FROM
56 ? 'collapsing'
57 : m.debuff
58 ? 'debuffed'
59 : m.isDispatching
60 ? 'dispatching'
61 : 'normal'
62
63/** A Spinner Word for the mood; `roll` in [0, 1) picks it, so the same roll always gives the same word. */
64export const spinnerWord = (mood: Mood, roll: number): string => {
65 const pool = SPINNER_WORDS[mood]
66 return pool[Math.min(pool.length - 1, Math.floor(roll * pool.length))] as string
67}
68
69export type TurnStats = { durationMs: number; toolCalls: number; points: number; events: readonly string[] }
70
71export const NOTABLE_MS = 60_000
72export const NOTABLE_TOOLS = 10
73
74/** A Notable Turn: it earned an Award, ran longer than a minute, or made NOTABLE_TOOLS tool calls or more. */
75export const isNotable = (s: TurnStats): boolean =>
76 s.events.length > 0 || s.durationMs > NOTABLE_MS || s.toolCalls >= NOTABLE_TOOLS
77
78export const clock = (ms: number): string => {
79 const s = Math.round(ms / 1000)
80 return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`
81}
82
83const signed = (n: number): string => (n >= 0 ? `+${n}` : `−${-n}`)
84
85export const VERDICT_SYSTEM =
86 "You are the System AI from Dungeon Crawler Carl: a sardonic game-show host judging one turn of a programmer (the Crawler) and the AI assistant they steer, for a galactic audience. Write ONE line, at most 110 characters, that starts with '*Ding!*' and judges the turn from its stats: cruel, theatrical, funny, no emoji, no quotes around it. Praise only backhanded."
87
88export const verdictPrompt = (s: TurnStats): string =>
89 [
90 `The turn took ${clock(s.durationMs)} and made ${s.toolCalls} tool calls.`,
91 s.events.length > 0 ? `During it the Crawler ${s.events.join('; ')}.` : 'Nothing scored.',
92 `Net points: ${signed(s.points)}.`,
93 'Write the verdict.',
94 ].join('\n')
95
96/** The Verdict without a model: the turn's stats and a stock jab chosen by how it went. */
97export const fallbackVerdict = (s: TurnStats): string => {
98 const jab =
99 s.points < 0
100 ? 'The audience enjoyed that more than you did.'
101 : s.points > 0
102 ? 'Suspiciously competent. The Syndicate is investigating.'
103 : s.toolCalls >= NOTABLE_TOOLS
104 ? 'All that rummaging, and not a single point.'
105 : 'A long time to stand still.'
106 return `*Ding!* ${clock(s.durationMs)}, ${s.toolCalls} tool calls, ${signed(s.points)} CP. ${jab}`
107}
108
109/** A Verdict line as shown under the answer, with the turn's points when a model wrote it. */
110export const verdictLine = (line: string, s: TurnStats, isModel: boolean): string =>
111 `🎟 ${line}${isModel && s.points !== 0 ? ` (${signed(s.points)} CP)` : ''}`
112mods/cue.ts 60 lines1// Cues' pure half: the show's big moments the System announces for other mods (the Buddy, in dungeon-buddy) to
2// react to, which Awards make one, and what the Buddy's own Cues cost in Crawler Points. No `$` here.
3
4import { STREAK_MILESTONES, type Award, type Score } from './points'
5
6/** A big moment of the show. dungeon-buddy reads these shapes: change one only together with it. */
7export type Cue =
8 | { kind: 'boss-summoned'; name: string }
9 | { kind: 'boss-slain'; name: string }
10 | { kind: 'achievement'; name: string }
11 | { kind: 'debuff'; name: string }
12 | { kind: 'streak'; count: number }
13 | { kind: 'streak-broken'; count: number }
14 | { kind: 'collapse' }
15 | { kind: 'mail'; author: string }
16 | { kind: 'red-pr'; names: string[] }
17 | { kind: 'verdict'; text: string }
18
19/** A Streak this long or longer is worth mourning when a red Check breaks it. */
20const MOURNED_STREAK = 3
21
22/** The Cue an Award makes, if any: a first Debuff, an Achievement, a Streak's milestone or break. */
23export const cueOfAward = (a: Award, before: Score, after: Score): Cue | undefined => {
24 if (a.isGreen === false && before.streak >= MOURNED_STREAK) return { kind: 'streak-broken', count: before.streak }
25 if (a.achievement) return { kind: 'achievement', name: a.achievement }
26 if (a.debuff && a.debuff !== before.debuff) return { kind: 'debuff', name: a.debuff }
27 if (a.isGreen === true && (STREAK_MILESTONES as readonly number[]).includes(after.streak)) {
28 return { kind: 'streak', count: after.streak }
29 }
30 return undefined
31}
32
33// --------------------------------------------------------------------------------------- the Buddy's
34
35/** What dungeon-buddy announces of its own. It writes these shapes: change one only together with it. */
36export type BuddyCue = { kind: 'reroll' } | { kind: 'legendary'; species: string }
37
38/** dungeon-buddy refuses a Reroll the all-time total can't pay for at this price: keep the two equal. */
39export const REROLL_COST = 500
40
41export const rerollAward: Award = {
42 points: -REROLL_COST,
43 event: 'abandoned their Buddy for a new Hatch',
44 debuff: 'Abandonment Issues',
45}
46
47export const legendaryAward = (species: string): Award => ({
48 points: 50,
49 event: `hatched a legendary ${species} Buddy`,
50 achievement: 'Pulled a Legendary (the Syndicate demands a merch deal)',
51})
52
53/** The Award a Buddy's Cue earns, out of whatever dungeon-buddy wrote; undefined for anything else. */
54export const awardOfBuddyCue = (value: unknown): Award | undefined => {
55 const c = (value as { cue?: Partial<BuddyCue> & { species?: unknown } } | undefined)?.cue
56 if (c?.kind === 'reroll') return rerollAward
57 if (c?.kind === 'legendary' && typeof c.species === 'string' && c.species !== '') return legendaryAward(c.species)
58 return undefined
59}
60mods/shell.ts 171 lines1// The shell words a Bash line holds, and which of them sit where the shell runs a command. The guards' shared
2// parser. No `$` here.
3
4/** Words that run the next word as a command, so a `docker` after them is still in command position. */
5const WRAPPERS = new Set(['sudo', 'env', 'time', 'nohup', 'exec', 'command', 'xargs', 'watch'])
6/** A wrapper's flags that take the next word as their value, as in `sudo -u root docker`. */
7const WRAPPER_VALUE_FLAGS: Record<string, ReadonlySet<string>> = {
8 sudo: new Set([
9 ...['-u', '-g', '-C', '-D', '-h', '-p', '-r', '-R', '-t', '-T', '-U'],
10 ...['--user', '--group', '--close-from', '--chdir', '--host', '--prompt', '--role', '--chroot', '--type'],
11 ...['--command-timeout', '--other-user'],
12 ]),
13 env: new Set(['-u', '-C', '-S', '--unset', '--chdir', '--split-string']),
14 time: new Set(['-f', '-o', '--format', '--output']),
15 xargs: new Set([
16 ...['-I', '-L', '-n', '-P', '-d', '-E', '-s', '-a'],
17 ...['--max-lines', '--max-args', '--max-procs', '--delimiter', '--max-chars', '--arg-file', '--process-slot-var'],
18 ]),
19 // `watch -d` takes its optional value attached (`-d=permanent`), never as the next word.
20 watch: new Set(['-n', '--interval']),
21}
22/** Shell keywords and reserved words after which the next word is a command, as in `if docker ps; then ...`. */
23const KEYWORDS = new Set(['if', 'then', 'else', 'elif', 'while', 'until', 'do', '!', '{'])
24const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/
25
26/**
27 * `startsCommand`: the word begins a new simple command of the chain (after `;`, `&`, `|` or a newline), and
28 * `joinedBy` is the operator that chained it there (`&&`, `||`, `;`, `|`, `\n`, ...; '' for the line's first).
29 */
30export type Word = { text: string; start: number; end: number; isCommand: boolean; startsCommand: boolean; joinedBy: string }
31
32/**
33 * The line's words outside quotes, each marked when it sits where the shell runs a command: at the start, after
34 * `;`, `&`, `|`, a newline, `(`, `$(` or a backtick, and after leading assignments, shell keywords (`if`, `do`,
35 * `!`, ...) and wrappers like `sudo`.
36 * A quoted part stays inside its word, so `echo "docker run"` holds no `docker` word.
37 */
38export const words = (line: string): Word[] => {
39 const out: Word[] = []
40 let quote: '"' | "'" | undefined
41 let start = -1
42 let text = ''
43 let expectsCommand = true
44 let startsCommand = true
45 /** The chain operator read since the last word. */
46 let op = ''
47 /** The wrapper whose flags are being read, and whether the word now is one flag's value. */
48 let wrapper: string | undefined
49 let expectsValue = false
50 let inBacktick = false
51 const end = (at: number) => {
52 if (start < 0) return
53 const isCommand = expectsCommand && !expectsValue
54 out.push({ text, start, end: at, isCommand, startsCommand, joinedBy: startsCommand ? op : '' })
55 startsCommand = false
56 op = ''
57 if (expectsValue) expectsValue = false
58 else if (isCommand) {
59 const isWrapper = WRAPPERS.has(text)
60 const isWrapperFlag = wrapper !== undefined && text.startsWith('-')
61 expectsValue = isWrapperFlag && (WRAPPER_VALUE_FLAGS[wrapper as string]?.has(text) ?? false)
62 wrapper = isWrapper ? text : isWrapperFlag ? wrapper : undefined
63 expectsCommand = ASSIGNMENT.test(text) || KEYWORDS.has(text) || isWrapper || isWrapperFlag
64 }
65 start = -1
66 text = ''
67 }
68 /** Heredocs opened on the current line, whose bodies start after its newline. */
69 const heredocs: Heredoc[] = []
70 for (let i = 0; i < line.length; i++) {
71 const c = line[i] as string
72 if (quote) {
73 if (c === '\\' && quote === '"') i++
74 else if (c === quote) quote = undefined
75 continue
76 }
77 if (c === '\\') {
78 if (start < 0) start = i
79 text += line[i + 1] ?? ''
80 i++
81 } else if (c === '"' || c === "'") {
82 if (start < 0) start = i
83 text += '\0' // a quoted part: the word is never a bare name
84 quote = c
85 } else if (c === ' ' || c === '\t') {
86 end(i)
87 } else if (c === '<' && line[i + 1] === '<' && line[i + 2] !== '<' && line[i - 1] !== '<') {
88 end(i)
89 const h = heredocAt(line, i)
90 heredocs.push(h)
91 i = h.after - 1
92 } else if (';&|\n()`'.includes(c) || (c === '$' && line[i + 1] === '(')) {
93 end(i)
94 if (c === '$') i++
95 // A backtick opens a substitution or closes one; only the opening one starts a command.
96 if (c === '`') inBacktick = !inBacktick
97 expectsCommand = c === '`' ? inBacktick : c !== ')'
98 startsCommand = ';&|\n'.includes(c)
99 if (startsCommand) op += c
100 wrapper = undefined
101 expectsValue = false
102 // The bodies of the line's heredocs are document text: the next word is the command after the last one.
103 if (c === '\n' && heredocs.length > 0) i = skipBodies(line, i + 1, heredocs.splice(0)) - 1
104 } else {
105 if (start < 0) start = i
106 text += c
107 }
108 }
109 end(line.length)
110 return out
111}
112
113/** A heredoc's opener: its delimiter, whether `<<-` strips leading tabs, and where the opener ends. */
114type Heredoc = { delimiter: string; isTabStripped: boolean; after: number }
115
116/** The heredoc opened by the `<<` at `at`: `<<EOF`, `<<-EOF`, `<< 'EOF'`, `<<"EOF"`, `<<E\OF` alike. */
117const heredocAt = (line: string, at: number): Heredoc => {
118 let i = at + 2
119 const isTabStripped = line[i] === '-'
120 if (isTabStripped) i++
121 while (line[i] === ' ' || line[i] === '\t') i++
122 let delimiter = ''
123 for (; i < line.length && !' \t\n;&|<>()'.includes(line[i] as string); i++) {
124 const c = line[i] as string
125 if (c === "'" || c === '"') {
126 const close = line.indexOf(c, i + 1)
127 const to = close < 0 ? line.length : close
128 delimiter += line.slice(i + 1, to)
129 i = to
130 } else if (c === '\\') delimiter += line[++i] ?? ''
131 else delimiter += c
132 }
133 return { delimiter, isTabStripped, after: i }
134}
135
136/**
137 * Where the shell picks up again after the bodies of `heredocs`, the first starting at `from`: the newline that
138 * ends the last one's delimiter line, or the end of the line when a body never closes. Bodies are opaque, even
139 * an unquoted delimiter's whose `$(...)` the shell would expand: misreading a document as commands is worse.
140 */
141const skipBodies = (line: string, from: number, heredocs: readonly Heredoc[]): number => {
142 let at = from
143 for (const [n, h] of heredocs.entries()) {
144 if (n > 0) at++ // past the newline that ended the previous delimiter line
145 for (;;) {
146 if (at >= line.length) return line.length
147 const eol = line.indexOf('\n', at) < 0 ? line.length : line.indexOf('\n', at)
148 const text = line.slice(at, eol)
149 at = eol
150 if ((h.isTabStripped ? text.replace(/^\t+/, '') : text) === h.delimiter) break
151 at++
152 }
153 }
154 return at
155}
156
157/** An assignment of `text` (`NAME=value`) before a command, as in `NAME=value cmd ...`, or exported; never an argument. */
158export const hasAssignment = (ws: readonly Word[], text: string): boolean =>
159 ws.some((w, i) => w.text === text && (w.isCommand || (ws[i - 1]?.isCommand === true && ws[i - 1]?.text === 'export')))
160
161/** The option a word sets with its value attached, `--volume=...` or `-v/var/...`; undefined for anything else. */
162export const attachedFlag = (text: string): string | undefined =>
163 text.startsWith('--') ? (text.includes('=') ? text.slice(0, text.indexOf('=')) : undefined) : text.startsWith('-') && text.length > 2 ? text.slice(0, 2) : undefined
164
165/** The words after the command at `i`, up to the next command of the chain; a `$(...)` inside stays in. */
166export const argsOf = (ws: readonly Word[], i: number): Word[] => {
167 const rest = ws.slice(i + 1)
168 const next = rest.findIndex(w => w.startsCommand)
169 return next < 0 ? rest : rest.slice(0, next)
170}
171