Delegate coding tasks to verified Claude workers: tiering, verification, background debrief and eval, dashboard

Delegate coding tasks to verified Claude workers.

chassis-delegation is a Claude Code mod for developers who want to hand off several coding tasks at once without losing track of what comes back. You describe a task; Claude writes it up as a task card, and one dispatch call turns the card into a git worktree and a worker on the model its tier names. When the worker hands back, the mod checks its report against git, gives you one verdict line, and shows what is running and what it costs.
Flowchart: you describe a task, the brain writes a card, dispatch makes a worktree and a worker, the verifier checks the hand-back against git, the verdict leads to a merge.
flowchart LR
you[You] --> brain[Brain]
brain --> card[Card]
card --> dispatch[Dispatch and worktree]
dispatch --> worker[Worker]
worker --> verifier[Verifier]
verifier --> verdict[Verdict]
verdict --> merge[Merge]
The flow in four diagrams, with what the verifier checks: docs/how-it-works.md.
Anthropic's own guidance recommends delegating to fresh-context subagents, writing self-contained briefs, asking for evidence rather than claims, and using cheaper models for cheaper work. The same guidance notes that a coordinating agent sometimes starts doing the work itself, and its remedy is an instruction telling it to wait. The output scan it describes does not judge truthfulness, and no published mechanism checks a worker's claims against git or caps what one interactive attempt may spend. This mod exists because the brain forgets to delegate and forgets to pick the right tier, so it turns those recommendations into checks that refuse, queue or refute.
Sources, and where the mod differs: docs/alignment.md.
Charts, data tables and lessons: docs/evidence.md.
git clone https://github.com/nelsben/chassis-delegation.git ~/chassis-delegation
claude --plugin-dir ~/chassis-delegation
# then, inside Claude Code, in your repo:
/delegation setup
To load it in VS Code, in the desktop app, or in every session, see docs/install.md.
/delegation setup checks./delegation update, and what to do at each version.Version 0.9.31, MIT.
hooks/register.ts 8030 lines1// chassis-delegation — brain-seat delegation for Claude Code: part 1 (SPEC v1 +
2// amendment 1), part 2 (the dispatch tool, quiet verdicts, the clean-stop
3// debrief, the eval trigger, compaction state, the scheduler) and part 5
4// (standalone: native verification, a built-in tier map, a per-repo config
5// file, `/delegation init`, portable briefs, a native git guard, a built-in
6// debrief). The hooks stay thin: every decision is a pure function in ./lib,
7// and every host command passes ./lib/allow.ts first. Nothing here calls the
8// chassis scripts: the mod works in a repo that has only agents/tasks/ cards.
9// MOD-12 (#22): the brain makes every worker's spawn with its own Agent tool;
10// the mod prepares it (brief, worktree, tier, the spawn block) and shapes it in
11// its agent.spawn hook, so every other hook here sees the worker too.
12import type { AgentSpawnResult, EngineInterface, PluginOptions, Register, TurnUsage } from 'claude-code'
13
14import type { BandItem, DelegationVerdict, DelegationWorker, QueuedSpawn } from './types'
15import { blocksFor, openItemLines } from './lib/dashboard'
16import { callKind, driveCall, driveLines, driveOutput, driveStep, driveTurn, emptyWatch, ranBefore, freshSessionRow, DRIVE_THRESHOLD_TOKENS, FRESH_SESSION_TOKENS, type DriveRecord, type Watch } from './lib/drive'
17import { saysWaiting, waitStep, WAIT_STALL_DEFAULT_MIN, type WaitState } from './lib/waitstate'
18import { bandTree, rationBandTree } from './lib/band'
19import { bashCommits, bashWrites, emptyBrain, brainEdit, brainFamily, brainLine, brainSummary, brainTurn, delegateDecision, DELEGATE_DENY, isRestricted, PREMIUM_POSTURE, toolPath, warnRow, WRITE_TOOLS, type BrainRecord, type BrainFamily } from './lib/brain'
20import { paneTree, type PaneTable, type PaneView } from './lib/pane'
21import { attempts as attemptsOf, dashboardText, isActive, liveView, pickScheme, sampleEvery, sessionRecords, spendSeries, workersUsd as workersUsdOf, type LiveView, type SpendPoint } from './lib/live'
22import { metricsFromRecords } from './lib/metrics'
23import { checkArgv, isSha, LOCK_REASON, refusedLine, type AllowConfig, type MergeCtx } from './lib/allow'
24import {
25 attemptsFor,
26 escalationSource,
27 holdSource,
28 judgedShas,
29 laneFields,
30 lineageResumes,
31 nextAttempt,
32 patchRecord,
33 patchReview,
34 priorRedHashes,
35 acceptRow,
36 ledgerHas,
37 retireDue,
38 retirePatch,
39 cardReadsMerged,
40 verifyTarget,
41 taskLabel,
42 type AttemptRecord,
43 type Lane,
44 isResumeAfterJudged,
45 readLine,
46 readRecord,
47 readVerdict,
48 isRetiredVerdict,
49 supersededBy,
50} from './lib/attempts'
51import { briefDrift, briefNames, briefRewrittenLine, briefStaleRefusal, type BriefDrift } from './lib/crossbrief'
52import {
53 amendNeedsApproval,
54 amendScopePaths,
55 scopeAmendHeld,
56 type ScopeAmends,
57 amendScopeInsideForbid,
58 amendInsideForbidLine,
59 forbidCovering,
60 scopeInsideForbidWarning,
61 scopeInsideForbid,
62 appendAmends,
63 budgetWarning,
64 effectiveList,
65 parseAmends,
66 type Amend,
67 extractAmendBlocks,
68 extractReport,
69 findBriefPath,
70 resolveBriefPath,
71 inlineHeaderMissing,
72 lacksLine,
73 noBriefLine,
74 parseBudget,
75 parseHeader,
76 setHeaderField,
77 parseReport,
78 resourcesOf,
79 scopeOverlap,
80 spendOf,
81 type BriefHeader,
82} from './lib/brief'
83import { addTurn, turnKey, ceilingState, liveWorker, overSpendDeny, overSpendLine, round4, spendCeiling, spendWarnRow, warnText, OVER_SPEND_NEXT, type Spend } from './lib/cost'
84import {
85 addFriction,
86 breadcrumbPath,
87 builtInDebriefPrompt,
88 splitModFindings,
89 cleanStop,
90 countLines,
91 debriefPathOf,
92 debriefPrompt,
93 debriefSkillPath,
94 debriefSource,
95 MARK_WATERMARK_MESSAGE,
96 debriefToast,
97 findingsFile,
98 findingsLines,
99 findingsPathOf,
100 proposalsLines,
101 openProposals,
102 parseProposals,
103 parseStatuses,
104 proposalDetail,
105 proposalInstruction,
106 proposalListLines,
107 settledLines,
108 SETTLED_ASK,
109 isoTime,
110 type ProposalStatus,
111 scrubbedFindings,
112 DEFAULT_DEBRIEF_AGENT,
113 DEFAULT_DEBRIEF_COOLDOWN_HOURS,
114 DEFAULT_DEBRIEF_IDLE_MINUTES,
115 DEFAULT_DEBRIEF_MIN_EVENTS,
116 DEFAULT_DEBRIEF_MIN_NEW_LINES,
117 boundaryOnly,
118 frictionFacts,
119 isCorrection,
120 nothingToDebrief,
121 parseWatermark,
122 verdictFacts,
123 watermarkPath,
124 windowFacts,
125 type FrictionEvent,
126} from './lib/cleanstop'
127import { resolveFindings, notFoundLine, expandHome } from './lib/debriefdir'
128import { noteFindings, noteFindingsName, notesPromptRow } from './lib/notes'
129import { checkDebrief, windowOf, userMessagesOf, userMessagesFromJsonl, transcriptPath, type DebriefWindow, type UserMessage } from './lib/debriefcheck'
130import { appendInstructions, compactBlock, composeSection, emptySnapshot, isEmptyState, owedRowsFrom, prsFrom, renderState, SECTION_ID, splitOwed, type RecentVerdict, type StateSnapshot } from './lib/compaction'
131import {
132 agentTypeFor,
133 branchName,
134 briefDirFor,
135 gateLineText,
136 briefFileName,
137 budgetAttempts,
138 cardMatches,
139 cardNamesFromLsTree,
140 checkDomain,
141 checkStatus,
142 currentBranchArgv,
143 defaultBriefDir,
144 DISPATCH_TOOL,
145 fetchArgv,
146 headShaArgv,
147 hereIgnore,
148 inlineBriefFileName,
149 inlineBriefText,
150 installStep,
151 lsTreeArgv,
152 cardDirPath,
153 overlapRefusal,
154 overlapWarning,
155 scopeSizeWarning,
156 tierHint,
157 hedgeHints,
158 parseCard,
159 parseDispatchArgs,
160 parseDispatchTool,
161 renderBriefChecked,
162 LESSONS_CAP,
163 lessonLineCount,
164 lessonsCapWarning,
165 lessonsPath,
166 renderHeader,
167 scopeLooksProse,
168 PROSE_SCOPE_STOP,
169 scratchpadFor,
170 showCardArgv,
171 spawnBlock,
172 spawnCall,
173 spawnDescription,
174 spawnPrompt,
175 TEMPLATE_FILES,
176 templatePath,
177 unrenderedRefusal,
178 liveBriefRefusal,
179 rewriteReasonsOf,
180 worktreeAddArgv,
181 worktreePath,
182 type BriefMode,
183 type Card,
184 type DispatchArgs,
185 type SpawnCall,
186} from './lib/dispatch'
187import {
188 DEFAULT_EVAL_IDLE_MINUTES,
189 DEFAULT_EVAL_LIVE_MAX_USD,
190 DEFAULT_SESSION_USD_CAP,
191 evalFailureRow,
192 evalRunnerPrompt,
193 evalToast,
194 extractEvalBlock,
195 failingLines,
196 liveEligible,
197 parseEvalBlock,
198 parseSha,
199 revParseArgv,
200 shouldEval,
201 type EvalTier,
202} from './lib/evaltrigger'
203import { EMPTY_GATE_KEY, engineLockDecision, gateCommandTemplates, gateForDelta, gateTemplatesOf, isEngineGate, readEngineLock, resolveGateRuns, waitedLine, type EngineLock } from './lib/gates'
204import { gitWrites, guardDeny, joinDir, mergeTargets, parseGuardBranches, taskOfBranch } from './lib/gitguard'
205import { handbackMessages, workerSaid } from './lib/handback'
206import { withIdentity } from './lib/identity'
207import { INIT_FILES, PLUGIN_MANIFEST, PLUGIN_CARD_DIR, cardsLocalLine, initPlan, initText } from './lib/init'
208import { CARD_TOOL, cardsFromFields, cardSummary, doneStatementCount, doneWhenOf, forbidCollisions, forbidFix, redTestWarnings, sayGo, type NewCard } from './lib/card'
209import { PATH_TOOLS, ROOT_MARKERS, SHADOWS, allRequiredHold, configLines, detectGate, foundOf, proposedSpend, handoverText, BRAIN_HANDOVER, scaffoldConfig, setupChecks, setupText, wouldSet, type SetupProbe } from './lib/setup'
210import { artefactsCheck, defaultScratch, expandTilde, globList, globRoot, isAbsolute, isNotWorkTree, noRepoVerdict, outdirOf, outsideCheck, OUTSIDE_WALK_CEILING, outsideRoots, reportArtefacts, reportFiles, reportMetrics, scopeCheck, workTreeArgv, type ArtefactStat, type OutsideInput, type RootListing } from './lib/norepo'
211import { noSuchAttempt, parseVerdictTool, POLL_MS, rowRaceOpen, stillVerifying, VERDICT_TOOL, verdictRule } from './lib/verdicttool'
212import { glyphIssues, modelGlyph, parseGlyphs, withGlyph, type GlyphMap } from './lib/glyph'
213import { prunedLine, refusedRow, refusedWritesLine, retentionPlan, storeBytes, storeLine, type StoreEntry } from './lib/retention'
214import { migratedLine, migrationPlan, scopedId, trimRepo } from './lib/taskkeys'
215import { fallbackLog, fallbackTail, fieldsOfRow, latestSpawnRow, ledgerJudgedLine, spawnRow, verdictAfter, withTail, type Fallback, type RowQuery } from './lib/storeloss'
216import { handedBackRow, postsRows, runningSection, startedRow, type RunningWorker, type StartKind } from './lib/rows'
217import { cardsHandedBack, nudgeDown, nudgeText, nudgeUp, type EffortNudge } from './lib/nudge'
218import { deliveryFor, parseVerbosity, quietLine, reviewLine, shortNext, type Rendered, type Verbosity } from './lib/quiet'
219import { DEFAULT_CARD_DIR, fillMergeCheck, ignoreWithCards, isGitRef, mergeCheckRefusal, mergeChecksFor, mergeConfig, parseRepoConfig, REPO_CONFIG_FILE, resolveIssueRepo, type Effective, type RepoConfig, type ReviewMode } from './lib/repoconfig'
220import { isRepoPath, normRepoPath, NOT_A_CHECKOUT, repoFolderName, repoPathCheck, sessionCardsFor, withRepoName } from './lib/paths'
221import {
222 parseReviewBlock,
223 parseReviewMarker,
224 refutedRows,
225 reviewAdvice,
226 reviewClause,
227 reviewDue,
228 reviewerDeny,
229 reviewerPick,
230 reviewPlan,
231 reviewResumeText,
232 reviewVerdictLine,
233 shownRefuted,
234 type ReviewMarker,
235} from './lib/review'
236import { alreadyQueuedDeny, countTiers, limitSourceText, maxWorkersSourcedText, enqueue, fallbackDelay, fallbackDue, fallbackKind, fallbackRow, hasSlot, isFinalDeny, isQueuedDeny, parseReadyFallbackMinutes, planQueue, promptKey, heldLine, queuedDeny, queuedIndex, queuedText, readyCount, readyLine, readyWaitLine, resourceBlock, resourceDeny, runningDeny, startingOthers, tierFree, tierFull, waitedMinutes, waitsText, type FallbackKind, type ResourceWait, type TierCounts, type Wanting } from './lib/scheduler'
237import {
238 aliasOf,
239 CLASSIFIER_LABELS,
240 classifierText,
241 effortFor,
242 effortText,
243 fableRequested,
244 finalAlias,
245 tierOf,
246 tierWarning,
247 needsClassifier,
248 noticeText,
249 pickTier,
250 tierPickLine,
251 type Alias,
252 type Effort,
253 type EffortSetting,
254 type Tier,
255 type TierPick,
256} from './lib/tier'
257import {
258 advise,
259 firstFailedClaim,
260 amendApprovalLine,
261 amendHeldLine,
262 amendedLine,
263 amendMalformedLine,
264 amendPendingLine,
265 branchDelta,
266 budgetDenyMessage,
267 contextBlock,
268 detectRateLimit,
269 filesPathFor,
270 isFailing,
271 isProveResume,
272 newestRed,
273 probeWork,
274 branchOnBase,
275 onBaseClause,
276 rateLimitedVerdict,
277 resumeText,
278 scratchFor,
279 syntheticReport,
280 verdictLine,
281 verifyAdvice,
282 workPresentDeny,
283 workPresentLine,
284 type Advice,
285 type Verdict,
286 type WorkPresent,
287} from './lib/verify'
288import { BASE_REFS, briefContract, briefWantsRed, verifyCardless, verifyNative, type RedEvidence } from './lib/verify-native'
289import { aliasLines, driftMessage, newAgentTypes, nextSighting, parseSighting, parseCandidateIds } from './lib/watch'
290import { allowance, bar, cellDay, dayIndex, dayKey, dayRecord, daySegments, inWindow, pace, parseRecord, rationKey, rationReport, rationText, resetsIn, segments, surplus, type DayRecord, type Window as RationWindow } from './lib/ration'
291import { MOD_VERSION } from './lib/version'
292import {
293 cardDiff,
294 cardKeptLocalClause,
295 notLandedIgnoredLine,
296 coAuthorTrailer,
297 commitArgv,
298 conflictLine,
299 defaultBranchOf,
300 dirtyWorktreeLine,
301 finishLines,
302 labelIsMerged,
303 lastLines,
304 latestVerdictRow,
305 mainBranchLine,
306 mergeTarget,
307 mainDirtyLine,
308 markMerged,
309 MERGE_TOOL,
310 mergedLines,
311 amendMergeLine,
312 amendSummary,
313 noWorktreeLine,
314 ownerRepoOf,
315 parseMergeArgs,
316 finishLeftovers,
317 finishStopLines,
318 parseMergeTool,
319 prBody,
320 pushLines,
321 readsMerged,
322 remoteBlock,
323 statusPaths,
324 touchesVersion,
325 twinIn,
326 VERSION_FILE,
327 versionOf,
328 verdictRefusal,
329 worktreeOf,
330 type GateResult,
331 type MergeArgs,
332 type MergedEntry,
333 type VerdictRow,
334} from './lib/mergecmd'
335import { configPlan, fieldAnswer, manifestFields, rowsByField, viewFields, type CfgRow, type CfgView, type Source } from './lib/configcmd'
336import { CONFIG_TABLE } from './lib/configtable'
337import { parseUserOptions, repoFileWith, resolveOptions, userFileWith, userOptionsPath, type Resolved } from './lib/configeff'
338import { askLine, AUTO_POST_CAP, capLine, coveredBy, issueNumberOf, parsePostArg, parsePostMode, postModeLine, REDACT_EMPTY, renderPost, survivingWord, type IssueRow, type PostFinding, type PostMode } from './lib/findings'
339import { dropLocalQuotes, gitConfigValue, parseRedactList, redact, type RedactRules } from './lib/redact'
340import { allowOf, missingBlocks, missingBlockRefusal, noLocalRefusal, renderLocal, trackedRefusal, unreadableRefusal } from './lib/brieflocal'
341import { abortedDeny, budgetDelay, decisionId, isStopped, outOfTimeDeny, stopper, turns, type Stopper } from './lib/serial'
342import { behindLine, changelogSlice, classifyRoot, codeSkewLine, folderVersion, inDevMods, migrateConfig, updateLine, upToDateLine } from './lib/update'
343
344type Host = EngineInterface
345
346const PLUGIN = 'chassis-delegation'
347const WORKERS = { plugin: 'chassis-delegation', key: 'workers' } as const
348const LAST_VERDICT = { plugin: 'chassis-delegation', key: 'lastVerdict' } as const
349const QUEUE = { plugin: 'chassis-delegation', key: 'queue' } as const
350const SPEND = { plugin: 'chassis-delegation', key: 'spend' } as const
351const BRAIN = { plugin: 'chassis-delegation', key: 'brain' } as const
352/** MOD-3: the last `git fetch` for the status line's behind count, at most one per ten minutes (in the store: the manifest names no new state key). */
353const UPDATE_CHECK = 'delegation.updateCheck'
354const UPDATE_CHECK_MS = 10 * 60 * 1000
355/** GH-112: the pane `/delegation dashboard` and the band's `[ details ]` open. */
356const DASH_PANE = 'delegation-dash'
357
358/**
359 * MOD-117 (#185, #184): every key below that takes a card id takes the card's repo too, `<id>@<repo>` (MOD-97's form for
360 * a card of another local repo, now for the session's own cards as well): card ids restart in each repo and the store
361 * is one per machine. The bare id is a session with no root. `taskRepo` and `mergePrep` are the session root's.
362 */
363const K = {
364 /** A task's attempt records in its card's repo. */
365 tasks: (task: string, repo = '') => `delegation.tasks.${scopedId(task, repo)}`,
366 adhoc: 'delegation.adhoc',
367 /** MOD-47: the brain's record for the conversation that started at `since`. */
368 brain: (since: number) => `delegation.brain.${since}`,
369 spawn: (key: string) => `delegation.spawn.${key}`,
370 agent: (agentId: string) => `delegation.agent.${agentId}`,
371 name: (name: string) => `delegation.agentName.${name}`,
372 alias: (alias: string) => `delegation.alias.${alias}`,
373 /** GH-114: the classifier's tier for a card, from its dry run. */
374 classifier: (task: string, repo = '') => `delegation.classifier.${scopedId(task, repo)}`,
375 /** MOD-12: where /dispatch prepared a brief's worker (its worktree, or the root for repo=here); the brain's Agent call names no folder. */
376 handoff: (briefPath: string) => `delegation.handoff.${briefPath}`,
377 agentTypes: 'delegation.agentTypes',
378 answered: 'delegation.models.answered',
379 replay: (briefPath: string) => `delegation.replay.${briefPath}`,
380 /** A worker's own spend this attempt, from its turn usage (GH-106). */
381 cost: (agentId: string) => `delegation.cost.${agentId}`,
382 /** MOD-13: the card's own `effort:`, written at /dispatch; it wins over effortByTier. */
383 effort: (task: string, repo = '') => `delegation.effort.${scopedId(task, repo)}`,
384 /** Set once an attempt's verdict row is posted to the conversation. */
385 posted: (attemptKey: string) => `delegation.posted.${attemptKey}`,
386 /** MOD-64: the text appended for an attempt's verdict (the row and any ready: lines), which the verdict tool returns. */
387 postedRow: (attemptKey: string) => `delegation.postedRow.${attemptKey}`,
388 /** This session's verdict lines, for the compaction block and the system prompt section (2E). */
389 recent: (sessionId: string) => `delegation.recent.${sessionId}`,
390 /** MOD-53: set once the fresh-session row is posted in a session. */
391 freshSession: (sessionId: string) => `delegation.freshSession.${sessionId}`,
392 /** MOD-137: when the last review-note prompt row was added or a note ingested, and the ingested findings file. */
393 notes: (sessionId: string) => `delegation.notes.${sessionId}`,
394 /** The background debrief of a session (2C). */
395 debrief: (sessionId: string) => `delegation.debrief.${sessionId}`,
396 /** MOD-31: the post-findings question a debrief left waiting for the person (count, repo). */
397 postAsk: (sessionId: string) => `delegation.postAsk.${sessionId}`,
398 /** The friction the mod saw in a session (5E): corrections, denials, refutes. */
399 friction: (sessionId: string) => `delegation.friction.${sessionId}`,
400 /** origin/main when the last T1 eval runner started (2D): never twice per sha. */
401 lastSha: 'delegation.eval.lastSha',
402 /** The eval runner that is out. */
403 evalInflight: 'delegation.eval.inflight',
404 /** The T2 run of a session: once a session. */
405 live: (sessionId: string) => `delegation.eval.live.${sessionId}`,
406 /** Every eval block the runners reported. */
407 evals: 'delegation.evals',
408 /** MOD-20: whose engine-suite gate (`claude plugin test`) is running; verifiers take turns on it. */
409 engineGate: 'delegation.engineGate',
410 /** MOD-22: the listing of a research card's absolute scope and forbid roots, taken at /dispatch. */
411 outside: (task: string, repo = '') => `delegation.outside.${scopedId(task, repo)}`,
412 /** MOD-44: the other local repo a task is for (its absolute path), so the id alone finds its card, brief and tree; MOD-117: in the session root's key space. */
413 taskRepo: (task: string, root = '') => `delegation.taskRepo.${scopedId(task, root)}`,
414 /** MOD-75: the tasks `/delegation merge --finish` merged in a session (task, sha, version), for the `merged:` lines. */
415 merged: (sessionId: string) => `delegation.merged.${sessionId}`,
416 /** MOD-75: what `/delegation merge <ID>` prepared (the head it pushed, the version it bumps), read again by --finish. */
417 mergePrep: (task: string, root = '') => `delegation.mergePrep.${scopedId(task, root)}`,
418}
419
420const PROBE_EVERY_MS = 24 * 60 * 60 * 1000
421const MIN_MS = 60 * 1000
422const HOUR_MS = 60 * MIN_MS
423const RECENT_CAP = 50
424/** An eval runner out longer than this is taken as gone (a T1 run takes minutes). */
425const EVAL_STALE_MS = 3 * HOUR_MS
426/** MOD-6: a debrief whose agent never handed back is not holding the one slot past this. */
427const DEBRIEF_STALE_MS = HOUR_MS
428const EVALS_CAP = 100
429/** The longest timeoutMs the host takes for one process run (10 minutes). */
430const HOST_MAX_TIMEOUT_MS = 600_000
431/** MOD-155 (#246): how long one gate command may run, read at the time of the run (repo option gateTimeoutMinutes, default 9). */
432const gateTimeoutMs = (): number => cfg.gateTimeoutMinutes * 60 * 1000
433/** MOD-143: the longest a card's merge check may run. */
434const MERGE_CHECK_TIMEOUT_MS = 10 * 60 * 1000
435/** The advice kinds that leave something for the brain (or the person) to do. */
436const OWED_KINDS = ['resume', 'respawn', 'verify', 'exhausted', 'check', 'fix-brief', 'review']
437const LEDGER_FILE = '.delegation/ledger.jsonl'
438
439/**
440 * `delegation.debrief.<session>`: the background debrief (2C, 5E). MOD-26: `skippedTo` is the breadcrumb line a
441 * boundary-only window ended at when the mod spawned nothing for it; the next window starts there (the mod never
442 * writes the `.done` mark, so the record is what moves).
443 */
444type DebriefRecord = { lastAt: number; watermark: number; lines: number; sessionId: string; mode?: 'breadcrumbs' | 'events'; builtIn?: boolean; agentId?: string; finishedAt?: number; path?: string; denied?: string; window?: DebriefWindow; prior?: DebriefRecord | null; skippedTo?: number; /** MOD-91 */ lastAttemptAt?: number; failedChecks?: { watermark: number; count: number } }
445/** `delegation.friction.<session>`: every friction event's count, and the last 100. */
446type FrictionRecord = { total: number; events: FrictionEvent[] }
447/** `delegation.eval.inflight`: the eval runner that is out (2D). */
448type EvalInflight = { agentId?: string; tier: EvalTier; sha: string; at: number; sessionId: string }
449/** One `delegation.evals` row. */
450type EvalEntry = { tier: EvalTier; sha: string; total?: number; pass?: number; fail?: number; result?: string; failing: string[]; at: number; agentId: string; sessionId: string }
451
452/**
453 * GH-16: what a repo=here attempt record carries besides the attempt: `here`,
454 * the checkout it shares (the session root), and `files`, the files= its
455 * hand-back claimed (written before the verify, so a sibling's verify sees them).
456 */
457type HereFields = { here?: string; files?: string[]; /** MOD-22: the report's metrics=, recorded and never judged. */ metrics?: Record<string, string> }
458/**
459 * GH-1: `requestedAlias: 'fable'` when fable was asked for and opus spawned
460 * (item 8); `adhoc: true` on the attempt a cardless hand-back recorded under
461 * its report's task= (item 2).
462 */
463type IssueOneFields = { requestedAlias?: Alias; adhoc?: true }
464/** GH-114: what the classifier said of the card at the dry run, on the card's first attempt record. */
465type ClassifierFields = { classifierTier?: Tier }
466type HereRecord = AttemptRecord & HereFields & IssueOneFields & ClassifierFields
467/** GH-16: another repo=here card in flight in the same checkout: a record without a verdict. */
468type InFlight = { label: string; scope: string[]; files: string[]; /** MOD-23: the resources its brief names. */ resources: string[] }
469
470/** What the mod keeps per spawned worker under `delegation.spawn.<key>` (key = the spawn's tool_use_id). */
471type SpawnRecord = {
472 key: string
473 task: string
474 subtask: string
475 adhoc: boolean
476 /** The worker's current attempt (a resume moves it on). */
477 attempt: number
478 lineage: number
479 tier: Tier
480 alias: string
481 budget: number
482 purpose: string
483 briefPath?: string
484 /** Why a spawn with no brief file has none (GH-6): what its inline header lacks, or why its brief could not be written. */
485 noBrief?: string
486 // MOD-89: no `prompt`: nothing read it back, and at about 1.4 KB a record it was most of the store (#157).
487 // A record written before keeps it; the brief path, the key (the tool_use_id) and the description are what is read.
488 description: string
489 subagentType: string
490 cwd?: string
491 agentId?: string
492 /** The model id the alias resolved to at spawn; a resume keeps it. */
493 resolvedModel?: string
494 usdAtStart?: number
495 /** GH-106: the brief's `spend=` ceiling in dollars (absent: none). */
496 spend?: number
497 /** MOD-23: the exclusive resources the brief's `resources=` names; the worker holds them while it runs. */
498 resources?: string[]
499 verdictAttempt?: number
500 verdictBlock?: string
501 lastFailed?: boolean
502 /** A `/dispatch --replay` run, from `base`. */
503 replay?: boolean
504 base?: string
505 /** ms since the epoch at spawn. */
506 at?: number
507 /** The one-line row of the last verdict (2B). */
508 verdictLine?: string
509 /** GH-16: a repo=here worker: the checkout it shares (the session root). */
510 here?: string
511 /** MOD-44: the other local repo this worker's task is for (its absolute path); absent for a task of the session's own repo. */
512 repo?: string
513 /**
514 * MOD-21: set on a reviewer's record. `attempt` is the attempt it reviews; `worker` is that worker's agent id
515 * (the resume goes to it), `sha` the commit under review. A reviewer is on no ladder, holds no slot, and edits nothing.
516 */
517 review?: { worker?: string; sha?: string }
518 /** MOD-94: set (never stored) on a record a hand-back or the verdict tool rebuilt because the store had none. */
519 fallback?: Fallback
520}
521
522const laneOf = (s: { replay?: boolean; base?: string }): Lane | undefined =>
523 s.replay ? { replay: true, ...(s.base ? { base: s.base } : {}) } : undefined
524
525/**
526 * `<task>:<lineage>:<attempt>` (the subtask, a replay lane and (MOD-97) another repo folded into the task) — one verdict per key.
527 * MOD-117: the card's repo is always folded in: another repo's (`s.repo`), else the session root given.
528 */
529const attemptKeyIn = (s: SpawnRecord, root: string): string =>
530 `${scopedId(taskLabel(s.task, s.subtask), s.repo || root)}${s.replay ? `@replay${s.base ? `-${s.base}` : ''}` : ''}:${s.review ? `review-${s.key}` : s.lineage}:${s.attempt}`
531/** MOD-117: an attempt's key, in its card's repo. */
532const attemptKey = async ($: Host, s: SpawnRecord): Promise<string> => attemptKeyIn(s, await sessionRootOf($))
533
534type Config = {
535 autoEscalate: boolean
536 applyAmends: boolean
537 scopeAmends: ScopeAmends
538 defaultBudget: number
539 probeModels: boolean
540 candidateIds: string[]
541 briefDir: string
542 verbosity: Verbosity
543 autoDebrief: boolean
544 /** MOD-137 */
545 debriefMode: 'notes' | 'transcript'
546 debriefIdleMs: number
547 debriefMinNewLines: number
548 debriefMinEvents: number
549 debriefCooldownMs: number
550 debriefAgent: string
551 /** MOD-6: the person's words the scrub replaces; /config only, never the (public) repo file. */
552 redact: string[]
553 /** On only with an evalCommand configured (5E). */
554 autoEval: boolean
555 evalLive: boolean
556 evalLiveMaxUsd: number
557 sessionUsdCap: number
558 evalIdleMs: number
559 evalAgent: string
560 ledgerFile: boolean
561 gitGuard: boolean
562 /** GH-112: the band above the prompt. MOD-128: off unless the option is true. */
563 dashboardBand: boolean
564 /** MOD-128: the rate-limit window the footer meter reads, or off. */
565 ration: 'seven_day' | 'five_hour' | 'off'
566 /** MOD-128: a fixed daily allowance in window points; 0 = pace to the reset. */
567 rationDaily: number
568 /** MOD-78: the glyph per model on every row: a map, or 'off'; `glyphsText` is the option as written. */
569 glyphs: GlyphMap | 'off'
570 glyphsText: string
571 /** GH-114: the card tool's dry run asks the classifier beside the card's tier. */
572 classifierSecondOpinion: boolean
573 guardBranches: string[]
574 // defaults < .chassis-delegation.json < settings (5B)
575 gateMap: Record<string, string>
576 /** MOD-98: gateMap entries the gate checker refused, id → why. */
577 refusedGates: Record<string, string>
578 /** MOD-143: gate id → the command merge runs before it rebases. */
579 mergeCheckMap: Record<string, string>
580 gateTemplates: string[][]
581 agentTypes: Record<string, string>
582 tierMap: Record<Tier, Alias>
583 evalCommand: string
584 evalLiveCommand: string
585 briefTemplate: string
586 briefExtra: string
587 /** MOD-124 (#188): the gitignored rules file copied into every brief. */
588 briefLocal: string
589 maxWorkers: number
590 /** MOD-155 (#246): whole minutes one gate command may run. */
591 gateTimeoutMinutes: number
592 /** MOD-131 (#219): the lower ceiling of each capped tier under maxWorkers. */
593 maxWorkersByTier: Partial<Record<Tier, number>>
594 domains: string[]
595 worktreeRoot: string
596 /** GH-12: the card folder, relative to the root. */
597 cardDir: string
598 /** GH-16: the delta's base when a brief names none ('' = origin/main → main → origin/master → master). */
599 baseRef: string
600 /** GH-16: globs always subtracted from a repo=here delta. */
601 ignore: string[]
602 /** GH-106: dollars one attempt may spend, per tier; 0 = no ceiling. */
603 spendByTier: Record<'economy' | 'standard' | 'frontier', number>
604 /** MOD-13: the effort a worker steps at, per tier; 0 or empty leaves the engine's default. */
605 effortByTier: Record<'economy' | 'standard' | 'frontier', EffortSetting>
606 /** MOD-114: the brain's effort nudge: the cards glob ('' = off) and the up and down words. */
607 effortNudge: EffortNudge
608 /** GH-113: what an opus or fable brain may do itself. */
609 delegateOnly: 'off' | 'warn' | 'deny'
610 /** MOD-7: owner/name /delegation debrief post files issues in; '' = posting is off. */
611 issueRepo: string
612 /** MOD-18: issueRepo is the mod's own repository, from the manifest (the repo file left it unset). */
613 issueRepoOwn: boolean
614 /** MOD-15: a verdict row is followed by a `$.prompt.submit`, a turn of the brain's own. MOD-64: off unless the option is true. */
615 wakeOnVerdict: boolean
616 /** MOD-31: ask | auto | off; /config only, never the (public, shared) repo file. */
617 postFindings: PostMode
618 /** MOD-15: how long a ready worktree row waits for the brain before the mod starts it itself; 0 = never. */
619 readyFallbackMs: number
620 /** MOD-99: minutes a waiting worker may wait before the mod says it is stalled; 0 = off. */
621 waitStallMs: number
622 /** MOD-48: the warn row for a command the brain keeps re-running or polling at a large context. */
623 driveWarn: boolean
624 /** MOD-48: the context, in tokens, from which that row speaks. */
625 driveWarnTokens: number
626 /** MOD-53: the brain context, in tokens, from which it is told once to start a fresh session; 0 = off. */
627 freshSessionTokens: number
628 /** MOD-21: a read-only reviewer after a consistent verdict: off, on, or on-frontier (frontier and premium cards only). */
629 review: ReviewMode
630 /** MOD-21: the reviewer's tier; '' = one below the worker's. */
631 reviewTier: Tier | ''
632}
633
634/**
635 * MOD-73: the config the mod runs with, out of four layers: the built-in defaults < the repo
636 * file < yours (the user options file) < the host's (`host`: the activation options, a listed
637 * /config row's value over them). `resolved` is the same values with the source of each: what
638 * `/delegation config` shows, so it never disagrees with what the mod does.
639 */
640function readConfig(host: Readonly<Record<string, unknown>>, repo: RepoConfig, user: Readonly<Record<string, unknown>> = {}, locked: ReadonlySet<string> = new Set()): { cfg: Config; errors: string[]; resolved: Resolved } {
641 const resolved = resolveOptions(host, user, repo, locked)
642 const o = { ...host, ...resolved.opts } as PluginOptions
643 const str = (k: string) => (typeof o[k] === 'string' ? (o[k] as string) : '')
644 const budget = typeof o.defaultBudget === 'number' && o.defaultBudget >= 1 ? Math.floor(o.defaultBudget) : 3
645 const num = (k: string, fallback: number): number => {
646 const v = o[k]
647 return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : fallback
648 }
649 const eff = resolved.eff
650 const issues = resolveIssueRepo(eff, modManifest ?? undefined)
651 return {
652 errors: resolved.errors,
653 resolved,
654 cfg: {
655 autoEscalate: o.autoEscalate === true,
656 applyAmends: o.applyAmends !== false,
657 scopeAmends: eff.scopeAmends,
658 defaultBudget: budget,
659 probeModels: o.probeModels === true,
660 candidateIds: parseCandidateIds(str('candidateIds')),
661 briefDir: str('briefDir'),
662 verbosity: parseVerbosity(o.verdictVerbosity),
663 autoDebrief: o.autoDebrief !== false,
664 debriefMode: o.debriefMode === 'transcript' ? 'transcript' : 'notes',
665 debriefIdleMs: num('debriefIdleMinutes', DEFAULT_DEBRIEF_IDLE_MINUTES) * MIN_MS,
666 debriefMinNewLines: Math.floor(num('debriefMinNewLines', DEFAULT_DEBRIEF_MIN_NEW_LINES)),
667 debriefMinEvents: Math.max(1, Math.floor(num('debriefMinEvents', DEFAULT_DEBRIEF_MIN_EVENTS))),
668 debriefCooldownMs: num('debriefCooldownHours', DEFAULT_DEBRIEF_COOLDOWN_HOURS) * HOUR_MS,
669 debriefAgent: str('debriefAgent') || DEFAULT_DEBRIEF_AGENT,
670 redact: parseRedactList(str('redact')),
671 autoEval: eff.autoEval && eff.evalCommand.trim() !== '',
672 evalLive: o.evalLive === true,
673 evalLiveMaxUsd: num('evalLiveMaxUsd', DEFAULT_EVAL_LIVE_MAX_USD),
674 sessionUsdCap: num('sessionUsdCap', DEFAULT_SESSION_USD_CAP),
675 evalIdleMs: num('evalIdleMinutes', DEFAULT_EVAL_IDLE_MINUTES) * MIN_MS,
676 evalAgent: str('evalAgent') || DEFAULT_DEBRIEF_AGENT,
677 ledgerFile: o.ledgerFile !== false,
678 gitGuard: o.gitGuard !== false,
679 dashboardBand: o.dashboardBand === true,
680 ration: o.ration === 'off' || o.ration === 'five_hour' ? o.ration : 'seven_day',
681 rationDaily: Math.min(100, num('rationDaily', 0)),
682 glyphs: parseGlyphs(str('modelGlyphs')),
683 glyphsText: str('modelGlyphs'),
684 classifierSecondOpinion: o.classifierSecondOpinion !== false,
685 guardBranches: parseGuardBranches(str('guardBranches')),
686 gateMap: eff.gateMap,
687 refusedGates: eff.refusedGates,
688 mergeCheckMap: eff.mergeCheckMap,
689 gateTemplates: gateTemplatesOf(eff.gateMap),
690 agentTypes: eff.agentTypes,
691 tierMap: eff.tierMap,
692 evalCommand: eff.evalCommand,
693 evalLiveCommand: eff.evalLiveCommand,
694 briefTemplate: eff.briefTemplate,
695 briefExtra: eff.briefExtra,
696 briefLocal: eff.briefLocal,
697 maxWorkers: eff.maxWorkers,
698 gateTimeoutMinutes: eff.gateTimeoutMinutes,
699 maxWorkersByTier: eff.maxWorkersByTier,
700 domains: eff.domains,
701 worktreeRoot: eff.worktreeRoot,
702 cardDir: eff.cardDir,
703 baseRef: eff.baseRef,
704 ignore: eff.ignore,
705 spendByTier: eff.spendByTier,
706 effortByTier: eff.effortByTier,
707 effortNudge: eff.effortNudge,
708 delegateOnly: eff.delegateOnly,
709 issueRepo: issues.repo,
710 issueRepoOwn: issues.own,
711 wakeOnVerdict: o.wakeOnVerdict === true,
712 postFindings: parsePostMode(o.postFindings),
713 readyFallbackMs: parseReadyFallbackMinutes(o.readyFallbackMinutes) * MIN_MS,
714 waitStallMs: num('waitStallMin', WAIT_STALL_DEFAULT_MIN) * MIN_MS,
715 driveWarn: o.driveWarn !== false,
716 driveWarnTokens: num('driveWarnTokens', DRIVE_THRESHOLD_TOKENS),
717 freshSessionTokens: num('freshSessionTokens', FRESH_SESSION_TOKENS),
718 review: eff.review,
719 reviewTier: eff.reviewTier,
720 },
721 }
722}
723
724// Module memory: a reload starts it over; the store and $.state stay.
725let options: PluginOptions = {}
726let repoLayer: RepoConfig = {}
727/** MOD-73: the user options file's text as last read (undefined = not read yet, null = none) and its values. */
728let userText: string | null | undefined
729let userOpts: Record<string, unknown> = {}
730/** MOD-73: the fields a locked /config row holds, as the last listing of the rows said. */
731let lockedFields: ReadonlySet<string> = new Set()
732/** MOD-73: every field's value and source, as the config was last made. */
733let resolvedNow: Resolved | undefined
734/** The repo file's text as last read: undefined = not read yet, null = no file. */
735let repoText: string | null | undefined
736/** MOD-18: the loaded copy's manifest as last read, which names the mod's own repository: undefined = not read yet, null = unreadable. */
737let modManifest: string | null | undefined
738let cfg: Config = readConfig({}, {}).cfg
739/** MOD-78: the glyph for an alias or model id ('' with modelGlyphs off). */
740const glyphOf = (alias: string | undefined): string => (cfg.glyphs === 'off' || !alias ? '' : modelGlyph(alias, cfg.glyphs))
741/** MOD-78: a description with the model's glyph in front, once; untouched with modelGlyphs off. */
742const glyphDescription = (description: string, alias: string | undefined): string => (cfg.glyphs === 'off' ? description : withGlyph(description, glyphOf(alias), cfg.glyphs))
743const glyphLogged = new Set<string>()
744/** MOD-78: a malformed modelGlyphs entry is named in the debug log, once. */
745function noteGlyphIssues($: Host): void {
746 for (const line of glyphIssues(cfg.glyphsText)) {
747 if (glyphLogged.has(line)) continue
748 glyphLogged.add(line)
749 debug($, line)
750 }
751}
752const waiting = new Set<string>() // Agent tool calls still awaiting their result
753const resumeCalls = new Map<string, string>() // MOD-97 (#155): an ad hoc Agent call that resumed a briefed worker -> that worker's spawn key
754const handbacks = new Map<string, string>() // agentId → a SubagentHandback message a tool.call hook saw (the transcript is the live source: GH-2)
755const verifying = new Map<string, SpawnRecord>() // MOD-74: the spawn behind each attempt key in `finalizing`, for the status section
756const finalizing = new Map<string, Promise<Rendered>>() // attempt key → its verify, so a second fire waits on the first
757const posted = new Set<string>() // attempt keys whose verdict row went to the conversation
758/**
759 * MOD-94 (#159, #157): the briefed workers this process saw start, by agent id, each as its spawn record was last
760 * written (every `delegation.spawn.*` write lands here too, refused or not). A running one whose verdict is still
761 * out is a live worker whether or not the store kept its record; it leaves the live set when its verdict lands.
762 * The store stays the source for a worker started in an earlier process.
763 */
764const remembered = new Map<string, SpawnRecord>()
765const REMEMBER_CAP = 500
766const offered = new Set<string>()
767let seedingTypes = false
768/** GH-106: the turn id a subagent's `turn.start` carried (the engine gives none today), by agentId. */
769const turnOf = new Map<string, string>()
770/** MOD-81: the newest session dollars any read of $.session.usage() gave the mod, with when: the band shows this. */
771let latestUsage: { usd: number; at: number } | undefined
772async function noteUsd($: Host, usd: number | undefined, at?: number): Promise<void> {
773 if (usd === undefined) return
774 latestUsage = { usd, at: at ?? (await now($)) }
775}
776let sampleTimer: { cancel: () => void } | undefined
777/** GH-112: `git worktree list --porcelain`, kept for 15 s so a redraw does not run git. */
778let worktreeCache: { at: number; text: string } | undefined
779/** GH-112: every task's attempt records, kept 15 s so a redraw does not read the whole store; the mod's own record writes clear it at once. */
780let recordsCache: { at: number; records: AttemptRecord[] } | undefined
781const RECORDS_TTL_MS = 15_000
782let probeTimer: { cancel: () => void } | undefined
783let spawnSeq = 0
784// Part 2: the main loop's turn state, the idle timers, the scheduler's slots.
785// A (re)load does not know whether a main turn is running, so it assumes one is
786// until the next main-loop turn.complete: nothing runs in the background before.
787let inTurn = true
788/** MOD-42: a main-loop turn is known to be open (turn.start seen, its turn.complete not yet): a verdict's wake is held for its end. */
789let turnOpen = false
790/** MOD-42: wakes held while the brain's turn is open; a consistent verdict's carries its spawn, re-checked for merged just before delivery. */
791/** MOD-62: `read` is set once a main-loop model step began after the entry was held: that step carried its row. */
792let heldWakes: { text: string; ready: string; spawn?: SpawnRecord; seq: number; read?: boolean }[] = []
793/** MOD-57: a counter ordering held wakes against delivered messages (the clock can tie); the last delivered message per agent id. */
794let wakeSeq = 0
795let messaged = new Map<string, { seq: number; at: number }>()
796let idleTimer: { cancel: () => void } | undefined
797let evalTimer: { cancel: () => void } | undefined
798let debriefBusy = false
799let evalBusy = false
800let slotSeq = 0
801const starting = new Map<number, string>() // slot token → the task label of a spawn holding a slot before $.agent.list shows it
802/** MOD-23: slot token → the resources that spawn names, held from the claim until $.agent.list shows the worker. */
803const startingResources = new Map<number, string[]>()
804/** MOD-131 (#219): slot token → the tier of that spawn, held from the claim until $.agent.list shows the worker. */
805const startingTiers = new Map<number, Tier>()
806/** MOD-12: the queued tasks the mod has said `ready:` for and that are still ready; each is said once. */
807const announced = new Set<string>()
808/** MOD-56: the last worker of this session stopped on a usage limit (at, as ms; resetsAt as the hand-back wrote it); cleared by the brain's next spawn. */
809let rateHeld: { at: number; resetsAt?: string } | undefined
810/** MOD-15: label → ms the queued row became ready (the fallback's clock); a row leaves with the queue or when it is no longer ready. */
811const readySince = new Map<string, number>()
812/** MOD-15: ready rows the fallback has looked at past their timeout and will not start (repo=here, repo=none, an unreadable brief). */
813const fallbackSkipped = new Set<string>()
814let fallbackTimer: { cancel: () => void } | undefined
815/** MOD-99: a briefed worker that is waiting without a hand-back, by agent id, and the timer that calls it stalled. */
816const waitStates = new Map<string, WaitState>()
817const waitTimers = new Map<string, { cancel: () => void }>()
818let fallbackBusy = false
819// promptKey → what to record once the spawn hook sees the agent id of a debrief or eval runner the mod started
820const runnerStarted = new Map<string, (agentId: string) => Promise<void>>()
821const selfDecided = new Set<string>() // promptKeys of spawns spawnSelf has decided: the hook passes them through
822const selfIds = new Map<string, string>() // promptKey → the agent id the hook saw for a spawnSelf spawn
823let lockTail: Promise<unknown> = Promise.resolve()
824let ledgerTail: Promise<unknown> = Promise.resolve()
825let frictionTail: Promise<unknown> = Promise.resolve()
826
827/**
828 * MOD-28: the mod's own templates (hooks/templates/*), read once and kept with the code that renders them. A pull
829 * under a running session moves the folder, never this copy, so old code can never meet a new template. A reload starts it over.
830 */
831type LoadedTemplates = { root: string; text: Map<string, string>; failed: Map<string, string> }
832let templatesLoad: Promise<LoadedTemplates> | undefined
833
834/** MOD-3: the folder this copy of the mod loaded from; the one dir `git merge --ff-only origin/main` may run in. */
835let loadedRoot = ''
836let sessionRoot = ''
837/** MOD-44: the tasks that work in another local repo, by id: the checkout, its own domains and the gate commands its tasks may run. Filled when a task is dispatched or judged. */
838const taskRepos = new Map<string, { path: string; domains: string[]; gateTemplates: string[][] }>()
839/** MOD-75: the task `/delegation merge` is working on, set only while that command runs (cleared in its finally); the allowlist's merge shapes pass for it alone. */
840let mergeCtx: MergeCtx | undefined
841/** MOD-143: the filled argv of the merge check running now (it passed the gate checker); the allowlist accepts exactly it, only while merge runs it. */
842let mergeCheckArgvs: string[][] = []
843const allowCfg = (): AllowConfig => ({ gateTemplates: [...(taskRepos.size > 0 ? [...cfg.gateTemplates, ...[...taskRepos.values()].flatMap(r => r.gateTemplates)] : cfg.gateTemplates), ...mergeCheckArgvs], ...(taskRepos.size > 0 ? { taskRepos: Object.fromEntries([...taskRepos.entries()].map(([id, r]) => [id, { path: r.path, domains: r.domains }])) } : {}), domains: cfg.domains, cardDir: cfg.cardDir, ...(cfg.issueRepo ? { issueRepo: cfg.issueRepo } : {}), ...(sessionRoot ? { root: sessionRoot } : {}), ...(cfg.worktreeRoot ? { worktreeRoot: cfg.worktreeRoot } : {}), ...(loadedRoot ? { pluginRoot: loadedRoot } : {}), ...(mergeCtx ? { merge: mergeCtx } : {}) })
844
845// ---- small host helpers (fail-open) ---------------------------------------
846function debug($: Host, text: string) {
847 try {
848 $.ui.log(`${PLUGIN}: ${text}`, { to: 'debug' })
849 } catch {
850 // nothing to do
851 }
852}
853/**
854 * MOD-28: the mod's templates, read the first time anything asks and never again until a reload. `register` is handed no `$`,
855 * so session.start asks first (the load); a session that reloads the mod mid-way asks at first use. A file that fails to
856 * load is named once, here, and by the feature that needs it when used.
857 */
858function loadedTemplates($: Host): Promise<LoadedTemplates> {
859 templatesLoad ??= readTemplates($)
860 return templatesLoad
861}
862async function readTemplates($: Host): Promise<LoadedTemplates> {
863 const root = $.plugin.root
864 const text = new Map<string, string>()
865 const failed = new Map<string, string>()
866 for (const name of TEMPLATE_FILES) {
867 try {
868 text.set(name, await $.fs.read(templatePath(root, name)))
869 } catch (err) {
870 failed.set(name, String(err))
871 }
872 }
873 if (failed.size > 0) {
874 const names = [...failed.keys()].join(', ')
875 debug($, `could not load ${names} from ${root}/hooks/templates: ${[...failed.values()].join('; ')}`)
876 try {
877 await $.ui.toast(`${PLUGIN}: could not load ${names} from ${root}/hooks/templates; the feature that needs ${failed.size === 1 ? 'it' : 'each'} will say so when used`)
878 } catch {
879 // the debug line stands
880 }
881 }
882 return { root, text, failed }
883}
884
885async function storeGet<T>($: Host, key: string): Promise<T | undefined> {
886 try {
887 return (await $.store.get(key)) as T | undefined
888 } catch {
889 return undefined
890 }
891}
892async function storeSet($: Host, key: string, value: unknown): Promise<void> {
893 // a task's attempt records changed: the dashboard's copy is stale (GH-112)
894 if (key.startsWith(K.tasks(''))) recordsCache = undefined
895 // MOD-94: a remembered worker's record follows every write of it, whether or not the store takes the write
896 if (key.startsWith(K.spawn(''))) rememberWrite(value)
897 try {
898 await $.store.set(key, value)
899 } catch (err) {
900 debug($, `store.set ${key} failed: ${String(err)}`)
901 await storeRefused($, key, err)
902 }
903}
904
905/**
906 * MOD-89 (#157): a refused set is said out loud. The first in a session is a toast and a row (a spawn record lost
907 * this way leaves its worker with no verdict); later ones are only counted, for `/delegation`.
908 */
909let refusedWrites: { count: number; last: string } = { count: 0, last: '' }
910async function storeRefused($: Host, key: string, err: unknown): Promise<void> {
911 refusedWrites = { count: refusedWrites.count + 1, last: key }
912 if (refusedWrites.count > 1) return
913 const reason = (err instanceof Error ? err.message : String(err)).split('\n')[0] ?? ''
914 const row = refusedRow(key, reason)
915 try {
916 $.ui.toast(`${PLUGIN}: ${row}`)
917 } catch {
918 // the row stands
919 }
920 await appendRow($, row)
921}
922
923/** Every key and value in the store, as `$.store` reads them (a key that fails to read is left out). */
924async function storeEntries($: Host): Promise<StoreEntry[]> {
925 const keys = await $.store.keys()
926 const out: StoreEntry[] = []
927 for (let i = 0; i < keys.length; i += 100) {
928 const read = await Promise.all(keys.slice(i, i + 100).map(async k => [k, await $.store.get(k)] as const).map(p => p.catch(() => undefined)))
929 for (const r of read) if (r && r[1] !== undefined) out.push(r)
930 }
931 return out
932}
933
934/**
935 * MOD-89 (#157, #159): the retention plan (hooks/lib/retention.ts), run at session.start and after each verdict,
936 * through `$.store.delete` only. The open tasks (a running worker, a pending verdict, a queued spawn) are never
937 * touched. One debug line when anything went, and at session.start one row.
938 */
939let pruning: Promise<void> | undefined
940function pruneStore($: Host, at: 'start' | 'verdict'): Promise<void> {
941 if (pruning) return pruning
942 pruning = pruneOnce($, at).finally(() => {
943 pruning = undefined
944 })
945 return pruning
946}
947async function pruneOnce($: Host, at: 'start' | 'verdict'): Promise<void> {
948 try {
949 const entries = await storeEntries($)
950 const live = await liveState($)
951 const open = [...live.workers.flatMap(w => [w.label, w.spawn.task]), ...live.pending.map(p => p.task), ...(await readQueue($)).map(q => q.task), ...finalizing.keys()]
952 const plan = retentionPlan({ entries, open, now: await now($) })
953 let n = 0
954 for (const key of plan.delete) {
955 try {
956 await $.store.delete(key)
957 n += 1
958 if (key.startsWith(K.tasks(''))) recordsCache = undefined
959 } catch (err) {
960 debug($, `store.delete ${key} failed: ${String(err)}`)
961 }
962 }
963 if (n === 0) return
964 const line = prunedLine(n, plan.before, plan.after)
965 debug($, line)
966 if (at === 'start') await appendRow($, line)
967 } catch (err) {
968 debug($, `store prune skipped: ${String(err)}`)
969 }
970}
971
972/** `/delegation`: the store's size, and the refused writes of this session when there were any. */
973async function storeStatusLines($: Host): Promise<string[]> {
974 let size: string[] = []
975 try {
976 size = [storeLine(storeBytes(await storeEntries($)))]
977 } catch (err) {
978 debug($, `store size not read: ${String(err)}`)
979 }
980 return [...size, ...(refusedWrites.count > 0 ? [refusedWritesLine(refusedWrites.count, refusedWrites.last)] : [])]
981}
982async function exists($: Host, path: string): Promise<boolean> {
983 try {
984 return await $.fs.exists(path)
985 } catch {
986 return false
987 }
988}
989async function now($: Host): Promise<number> {
990 try {
991 return await $.clock.now()
992 } catch {
993 return Date.now()
994 }
995}
996async function sessionUsd($: Host): Promise<number | undefined> {
997 try {
998 const usd = (await $.session.usage()).cost?.usd
999 await noteUsd($, usd)
1000 return usd
1001 } catch {
1002 return undefined
1003 }
1004}
1005
1006type RunOut = { ok: true; exitCode: number; stdout: string; stderr: string } | { ok: false; why: string }
1007
1008/** The ONLY way the mod runs a host command: a refused argv never reaches `$.process.run`. */
1009async function run($: Host, argv: string[], init?: { cwd?: string; env?: Record<string, string>; stdin?: string; timeoutMs?: number }): Promise<RunOut> {
1010 loadedRoot = $.plugin.root
1011 try {
1012 sessionRoot = (await $.session.root()).replace(/\/+$/, '')
1013 } catch {
1014 // no root: no issue form passes
1015 }
1016 const check = checkArgv(argv, allowCfg())
1017 if (!check.ok) {
1018 try {
1019 $.ui.log(refusedLine(argv, check.reason))
1020 } catch {
1021 // the refusal stands either way
1022 }
1023 return { ok: false, why: `refused: ${check.reason}` }
1024 }
1025 try {
1026 // MOD-155: the host refuses a timeoutMs over 600000, so a longer gate limit runs at the host's ceiling
1027 const r = await $.process.run(argv, init?.timeoutMs !== undefined && init.timeoutMs > HOST_MAX_TIMEOUT_MS ? { ...init, timeoutMs: HOST_MAX_TIMEOUT_MS } : init)
1028 return { ok: true, exitCode: r.exitCode, stdout: r.stdout, stderr: r.stderr }
1029 } catch (err) {
1030 return { ok: false, why: String(err) }
1031 }
1032}
1033
1034// ---- part 5B: the repo file ---------------------------------------------------
1035/** MOD-73: HOME, where the user options file lives; '' when the environment does not say. */
1036async function homeDir($: Host): Promise<string> {
1037 try {
1038 return (await $.env.get('HOME')) ?? ''
1039 } catch {
1040 return ''
1041 }
1042}
1043
1044/**
1045 * Reads `<root>/.chassis-delegation.json` and the user options file (when either changed) and
1046 * remakes the config: defaults < repo file < yours < the host's settings. `force` remakes it
1047 * though nothing changed (a /config row was just set).
1048 */
1049async function loadRepoConfig($: Host, force = false): Promise<void> {
1050 let root: string
1051 try {
1052 root = await $.session.root()
1053 } catch {
1054 return
1055 }
1056 const text = (await readText($, `${root}/${REPO_CONFIG_FILE}`)) ?? null
1057 const home = await homeDir($)
1058 const uText = home ? ((await readText($, userOptionsPath(home))) ?? null) : null
1059 // MOD-18: the manifest is read beside the repo file, so a moved issueRepo default (after an update) is seen
1060 let manifest: string | null = null
1061 try {
1062 manifest = (await readText($, `${$.plugin.root}/${PLUGIN_MANIFEST}`)) ?? null
1063 } catch {
1064 manifest = null
1065 }
1066 if (!force && text === repoText && manifest === modManifest && uText === userText) return
1067 const repoChanged = text !== repoText || manifest !== modManifest
1068 const userChanged = uText !== userText
1069 repoText = text
1070 modManifest = manifest
1071 const parsed = text === null ? { config: {}, errors: [] } : parseRepoConfig(text)
1072 repoLayer = parsed.config
1073 if (userChanged) {
1074 userText = uText
1075 const u = parseUserOptions(uText ?? undefined)
1076 userOpts = u.options
1077 // MOD-73: a malformed user file is said once (per change of its text), and ignored
1078 const where = userOptionsPath(home)
1079 for (const err of u.errors) debug($, `${where}: ${err}`)
1080 if (u.errors.length > 0) $.ui.toast(`${PLUGIN}: ${where}: ${u.errors[0]}${u.errors.length > 1 ? ` (+${u.errors.length - 1} more in the debug log)` : ''}`)
1081 }
1082 const next = readConfig(options, repoLayer, userOpts, lockedFields)
1083 cfg = next.cfg
1084 resolvedNow = next.resolved
1085 if (!repoChanged && !userChanged) return
1086 const errors = [...(repoChanged ? parsed.errors : []), ...next.errors]
1087 for (const err of errors) debug($, `${REPO_CONFIG_FILE}: ${err}`)
1088 if (errors.length > 0) $.ui.toast(`${PLUGIN}: ${REPO_CONFIG_FILE}: ${errors[0]}${errors.length > 1 ? ` (+${errors.length - 1} more in the debug log)` : ''}`)
1089}
1090
1091// ---- MOD-44: a task for another local repo ---------------------------------------------------------
1092/** What the mod needs of another local repo for the tasks that name it: its config (when it has one), else its detected gate. */
1093type Target = {
1094 path: string
1095 name: string
1096 /** It has its own .chassis-delegation.json. */
1097 hasConfig: boolean
1098 /** Its gate map: the config's, else `{ test: <detected command> }`; empty when it has neither. */
1099 gateMap: Record<string, string>
1100 /** MOD-98: its config's gateMap entries the gate checker refused, id → why. */
1101 refusedGates: Record<string, string>
1102 /** The gate map came from detection (no config, or a config with no gateMap). */
1103 detected: boolean
1104 domains: string[]
1105 cardDir: string
1106 spendByTier: Effective['spendByTier']
1107 baseRef: string
1108 /** MOD-95: its own config's briefExtra (empty with no config), never the session's. */
1109 briefExtra: string
1110 /** MOD-124: its own config's briefLocal. */
1111 briefLocal: string
1112}
1113
1114/** `repo` as a checkout of another local repo: its normalised path, or why it is refused. */
1115async function resolveRepo($: Host, value: string, root: string): Promise<{ path: string } | { error: string }> {
1116 const checked = repoPathCheck(value, await homeOf($), root)
1117 if ('error' in checked) return checked
1118 return (await exists($, `${checked.path}/.git`)) ? checked : { error: NOT_A_CHECKOUT }
1119}
1120
1121/** setup's detectGate on another folder: the test command it already has (package.json scripts.test, pytest, cargo, go), or undefined. */
1122async function detectGateIn($: Host, dir: string): Promise<string | undefined> {
1123 const markers: string[] = []
1124 for (const m of ROOT_MARKERS) if (await exists($, `${dir}/${m}`)) markers.push(m)
1125 const packageJson = markers.includes('package.json') ? await readText($, `${dir}/package.json`) : undefined
1126 let pyTests = false
1127 try {
1128 pyTests = (await $.fs.list(`${dir}/tests`)).some(e => /^test_.*\.py$/.test(e.name))
1129 } catch {
1130 pyTests = false
1131 }
1132 const onPath: string[] = []
1133 if (markers.includes('pyproject.toml') || pyTests) {
1134 let path = ''
1135 try {
1136 path = (await $.env.get('PATH')) ?? ''
1137 } catch {
1138 path = ''
1139 }
1140 for (const d of path.split(':').filter(x => x !== '')) {
1141 if (await exists($, `${d.replace(/\/+$/, '')}/pytest`)) {
1142 onPath.push('pytest')
1143 break
1144 }
1145 }
1146 }
1147 return detectGate({ markers, ...(packageJson !== undefined ? { packageJson } : {}), pyTests, onPath } as unknown as SetupProbe)?.command
1148}
1149
1150/** The checkout at `path` (already resolved): its config read fresh, its gate detected when the config names none. */
1151async function loadTarget($: Host, path: string): Promise<Target> {
1152 const text = await readText($, `${path}/${REPO_CONFIG_FILE}`)
1153 const parsed = text === undefined ? { config: {} as RepoConfig, errors: [] as string[] } : parseRepoConfig(text)
1154 for (const err of parsed.errors) debug($, `${path}/${REPO_CONFIG_FILE}: ${err}`)
1155 const eff = mergeConfig(parsed.config, {})
1156 let gateMap = eff.gateMap
1157 let detected = false
1158 if (Object.keys(gateMap).length === 0) {
1159 const found = await detectGateIn($, path)
1160 if (found) {
1161 gateMap = { test: found }
1162 detected = true
1163 }
1164 }
1165 return { path, name: repoFolderName(path), hasConfig: text !== undefined, gateMap, refusedGates: eff.refusedGates, detected, domains: eff.domains, cardDir: eff.cardDir, spendByTier: eff.spendByTier, baseRef: eff.baseRef, briefExtra: eff.briefExtra, briefLocal: eff.briefLocal }
1166}
1167
1168/** Where a target's cards are: its own cardDir when it has a config, else the session's .delegation/cards/<its folder name>/. */
1169const targetCardsDir = (root: string, t: Target): string => (t.hasConfig ? cardDirPath(t.path, t.cardDir) : sessionCardsFor(root, t.path))
1170
1171/** The gate a card names in a target's own terms: each id as its command, a one-off command as itself. */
1172const gateCommands = (t: Target, ids: readonly string[]): string => ids.map(g => t.gateMap[g] ?? g).join(', ')
1173
1174/** `repo: <path> (config: its own | none, gate: <cmd>)`: what the dry run prints. */
1175const repoLine = (t: Target, ids: readonly string[]): string => `repo: ${t.path} (config: ${t.hasConfig ? 'its own' : 'none'}, gate: ${gateCommands(t, ids) || '(none)'})`
1176
1177/** The commands a card's one-off gate entries name: those that are not ids in the target's gate map and pass the gate rules. */
1178const oneOffGates = (t: Target, ids: readonly string[]): string[][] =>
1179 ids.filter(g => t.gateMap[g] === undefined && /\s/.test(g)).flatMap(g => {
1180 const parsed = gateCommandTemplates(g)
1181 return 'templates' in parsed ? parsed.templates : []
1182 })
1183
1184/** Lets the allowlist see this task's repo: `git -C <path> worktree add` for the task, and the repo's gate commands. */
1185function registerTaskRepo(task: string, t: Target, gateIds: readonly string[]): void {
1186 const templates = [...gateTemplatesOf(t.gateMap), ...oneOffGates(t, gateIds)]
1187 taskRepos.set(task, { path: t.path, domains: t.domains, gateTemplates: templates })
1188}
1189
1190/**
1191 * MOD-44: the other repo a brief names (`repo=<abs path>`), loaded and registered with the allowlist; undefined for a
1192 * brief of the session's own repo (or `repo=here|none`). A brief written before MOD-44 may hold `repo=<worktree dir>`:
1193 * that is read as a checkout too, harmlessly (it only lets that task name that folder).
1194 */
1195async function adoptRepo($: Host, task: string, header: BriefHeader | undefined): Promise<Target | undefined> {
1196 const value = header?.repo
1197 if (!value || !value.startsWith('/')) return undefined
1198 let root = ''
1199 try {
1200 root = (await $.session.root()).replace(/\/+$/, '')hooks/lib/dashboard.ts 326 lines1// Part 4A/4B and 3D, the drawing's data: the band's lines, the pane's six
2// blocks and their sparklines, the open items, and the status tool's text.
3// The trees themselves are band.tsx and pane.tsx. Pure: no `$`.
4import type { BandItem, DashboardBlock } from '../types'
5import { usdText } from './cost'
6import { SERIES, type Metrics } from './metrics'
7import { verifyingTail } from './verdicttool'
8
9export type { BandItem } from '../types'
10
11const ARROW = '▸'
12
13/** `04:12` (mm:ss), `1:02:05` past the hour. */
14export function elapsed(ms: number): string {
15 const s = Math.max(0, Math.floor(ms / 1000))
16 const two = (n: number) => String(n).padStart(2, '0')
17 const h = Math.floor(s / 3600)
18 const m = Math.floor((s % 3600) / 60)
19 return h > 0 ? `${h}:${two(m)}:${two(s % 60)}` : `${two(m)}:${two(s % 60)}`
20}
21
22/** Cut to `columns` cells, the last one an ellipsis. */
23export function fit(text: string, columns: number): string {
24 const cells = [...text]
25 if (cells.length <= columns) return text
26 return columns <= 1 ? cells.slice(0, Math.max(0, columns)).join('') : `${cells.slice(0, columns - 1).join('')}…`
27}
28
29const ADVICE: Record<string, string> = {
30 resume: 'resume advised',
31 respawn: 'respawn advised',
32 exhausted: 'budget exhausted',
33 check: 'check by hand',
34 'fix-brief': 'fix the brief',
35}
36
37/**
38 * A verdict that waits on a decision, in one clause: the verdict with its
39 * claim (`refuted on scope`; a no-repo verdict keeps its why), then the
40 * advice, or that an amend needs approval.
41 */
42export function decisionText(r: { verdict: string; reason?: string; advice?: string; approval?: boolean; noRepo?: boolean }): string {
43 const claim = r.reason ? (r.noRepo ? `: ${r.reason}` : ` ${r.reason.replace(/ \(.*$/, '')}`) : ''
44 const verdict = `${r.verdict}${r.noRepo ? ' (no repo)' : ''}${claim}`
45 const advice = r.approval ? 'amend needs approval' : (r.advice && ADVICE[r.advice]) || r.advice
46 return advice ? `${verdict} · ${advice}` : verdict
47}
48
49/** MOD-78: a queued row may carry the alias it will run on (the host's type has none). */
50type QueuedItem = Extract<BandItem, { kind: 'queued' }> & { alias?: string; /** MOD-131 (#219): the tier whose own cap holds the row while the total has room. */ slotTier?: string }
51
52export type BandLine = { key: string; text: string; clear?: boolean }
53
54/** Room the band keeps at a line's end for its `[ clear ]`. */
55export const CLEAR_COLUMNS = 10
56
57/**
58 * One line per item, sized to the band's columns. The running workers'
59 * fields are padded to one another so the numbers line up.
60 */
61export function bandLines(items: readonly BandItem[], now: number, columns: number, glyphOf: (alias: string) => string = () => ''): BandLine[] {
62 const mark = (alias: string) => { const g = glyphOf(alias); return `${g ? `${g} ` : ''}${alias}` }
63 const running = items.filter((i): i is Extract<BandItem, { kind: 'running' }> => i.kind === 'running')
64 const width = (f: (i: Extract<BandItem, { kind: 'running' }>) => string) => Math.max(0, ...running.map(i => [...f(i)].length))
65 const taskW = width(i => i.task)
66 const tierW = width(i => `${i.tier}/${mark(i.alias)}`)
67 const timeW = width(i => elapsed(now - i.at))
68 const usdW = width(i => usdText(i.usd === undefined ? undefined : { usd: i.usd }))
69 return items.map((item, n): BandLine => {
70 switch (item.kind) {
71 case 'running': {
72 const cost = usdText(item.usd === undefined ? undefined : { usd: item.usd })
73 const text = [
74 `${ARROW} ${item.task.padEnd(taskW)}`,
75 `${item.tier}/${mark(item.alias)}`.padEnd(tierW),
76 elapsed(now - item.at).padStart(timeW),
77 cost.padEnd(usdW),
78 item.phase,
79 ].join(' · ')
80 return { key: `run-${item.task}-${n}`, text: fit(text, columns) }
81 }
82 case 'decision':
83 return { key: `decide-${item.task}-${n}`, text: fit(`${ARROW} ${item.task} · ${item.text}`, columns) }
84 case 'queued':
85 return { key: `queued-${item.task}-${n}`, text: fit(`${ARROW} queued: ${item.task} (pos ${item.position})${(item as QueuedItem).alias ? ` · ${mark((item as QueuedItem).alias as string)}` : ''}`, columns) }
86 case 'eval-failed': {
87 const score = item.total !== undefined && item.pass !== undefined ? ` ${item.pass}/${item.total}` : ' (no result block)'
88 return { key: 'eval-failed', text: fit(`${ARROW} eval ${item.tier}${score} — see transcript`, Math.max(1, columns - CLEAR_COLUMNS)), clear: true }
89 }
90 case 'runner':
91 return { key: `runner-${item.what}-${n}`, text: fit(`${ARROW} ${item.what} running · ${elapsed(now - item.at)}`, columns) }
92 }
93 })
94}
95
96/** The pane's "Open items": every band item with the exact next action. */
97export function openItemLines(items: readonly BandItem[], now: number, verdictTool = false, glyphOf: (alias: string) => string = () => ''): string[] {
98 const mark = (alias: string) => { const g = glyphOf(alias); return `${g ? `${g} ` : ''}${alias}` }
99 return items.map(item => {
100 switch (item.kind) {
101 case 'running':
102 return item.phase === 'verifying'
103 ? `${item.task}: verifying ${item.tier}/${mark(item.alias)} ${elapsed(now - item.at)} — ${verifyingTail(item.task, verdictTool)}`
104 : `${item.task}: running ${item.tier}/${mark(item.alias)} ${elapsed(now - item.at)} — wait for the hand-back`
105 case 'decision':
106 return `${item.task}: ${item.next}`
107 case 'queued':
108 // MOD-24: a row held up by a resource names it and who holds it; a row waiting for a slot reads as it did
109 return `${item.task}: queued (position ${item.position})${(item as QueuedItem).alias ? ` · ${mark((item as QueuedItem).alias as string)}` : ''} — ${item.waits ? `waits for ${item.waits.resource} (held by ${item.waits.holder})` : `starts when a ${(item as QueuedItem).slotTier ?? 'worker'} slot frees`}`
110 case 'eval-failed': {
111 const score = item.total !== undefined && item.pass !== undefined ? ` ${item.pass}/${item.total}` : ''
112 return `eval ${item.tier}${score} at ${item.sha.slice(0, 8)}: read the failing names in the transcript, then press clear in the band`
113 }
114 case 'runner':
115 return `${item.what}: running ${elapsed(now - item.at)} — nothing to do`
116 }
117 })
118}
119
120// ---- the pane's blocks ------------------------------------------------------------
121
122export type Block = DashboardBlock
123
124const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
125const STEPS_PER_DISPATCH = 10
126
127/**
128 * The six blocks: a heading, one line of numbers for this session, and the
129 * series over `history` (the last 14 sessions, oldest first, this one last).
130 */
131export function blocksFor(input: {
132 current: Metrics
133 history: readonly Metrics[]
134 rateLimits?: readonly { kind: string; percentUsed: number }[]
135 owedRows?: readonly string[]
136 /** MOD-48: the brain's calls by kind and its average context. */
137 driveLines?: readonly string[]
138}): Block[] {
139 const m = input.current
140 const series = (key: string) => {
141 const s = SERIES.find(x => x.key === key)
142 return s ? input.history.map(h => s.value(h)) : []
143 }
144 const window = input.rateLimits?.find(r => r.kind === 'five_hour') ?? input.rateLimits?.[0]
145 const v = m.verdicts
146 return [
147 {
148 key: 'steps',
149 heading: 'Steps saved',
150 number: `${plural(m.dispatches, 'dispatch', 'dispatches')} · ~${m.dispatches * STEPS_PER_DISPATCH} hand steps saved`,
151 detail: [],
152 series: series('steps'),
153 alt: 'dispatches per session',
154 },
155 {
156 key: 'verdicts',
157 heading: 'Verdicts',
158 number: `${v.consistent} consistent · ${v.unverified} unverified · ${v.refuted} refuted${v.falseRefuted > 0 ? ` (${v.falseRefuted} false)` : ''}`,
159 detail: [],
160 series: series('verdicts'),
161 alt: 'refuted share per session',
162 },
163 {
164 key: 'tiers',
165 heading: 'Tiers',
166 number: `haiku ${m.spawns.haiku} · sonnet ${m.spawns.sonnet} · opus ${m.spawns.opus} · resume ${m.escalations.resume} · respawn ${m.escalations.respawn}`,
167 detail: [],
168 series: series('tiers'),
169 alt: 'share of spawns on the cheapest tier that was consistent, per session',
170 },
171 {
172 key: 'owed',
173 heading: 'Owed work that ran itself',
174 number: `${plural(m.debriefs, 'debrief')} · ${plural(m.evals.run, 'eval')}${m.evals.failed > 0 ? ` (${m.evals.failed} failed)` : ''}`,
175 detail: [...(input.owedRows ?? [])],
176 series: series('owed'),
177 alt: 'debriefs and evals per session',
178 },
179 {
180 key: 'compaction',
181 heading: 'Compaction',
182 number: `${plural(m.compactions, 'compaction')} served, state block attached`,
183 detail: [],
184 series: series('compaction'),
185 alt: 'compactions per session',
186 },
187 {
188 key: 'spend',
189 heading: 'Spend',
190 number: `$${m.usd.toFixed(2)} on workers · ${window ? `${window.kind} window ${window.percentUsed}%` : 'window –'}`,
191 detail: [...(input.driveLines ?? [])],
192 series: series('spend'),
193 alt: 'worker dollars per session',
194 },
195 ]
196}
197
198// ---- sparklines ------------------------------------------------------------------
199
200export const SPARK_POINTS = 14
201export const SPARK_HEIGHT = 16
202/** CSS pixels per column the Svg takes, and the most columns it spans. */
203export const PX_PER_COLUMN = 8
204export const SPARK_MAX_COLUMNS = 60
205
206const r1 = (n: number) => Math.round(n * 10) / 10
207
208/** The values drawn: nulls dropped, the last 14 kept. */
209export const sparkValues = (values: readonly (number | null)[]): number[] =>
210 values.filter((v): v is number => v !== null && Number.isFinite(v)).slice(-SPARK_POINTS)
211
212/**
213 * The polyline's points over a `width` × `height` box, 1 px inside it: zero at
214 * the bottom, the largest value at the top; one value is a flat line across.
215 */
216export function sparkPoints(values: readonly (number | null)[], width: number, height: number): string {
217 const v = sparkValues(values)
218 if (v.length === 0) return ''
219 const pad = 1
220 const max = Math.max(0, ...v)
221 const y = (n: number) => r1(max > 0 ? pad + (1 - n / max) * (height - 2 * pad) : height - pad)
222 if (v.length === 1) return `${pad},${y(v[0] as number)} ${r1(width - pad)},${y(v[0] as number)}`
223 const step = (width - 2 * pad) / (v.length - 1)
224 return v.map((n, i) => `${r1(pad + i * step)},${y(n)}`).join(' ')
225}
226
227/**
228 * The Svg sparkline: one polyline, no fill, 2 px, stroked in the surface's
229 * foreground (`currentColor`, and the CSS system colour `CanvasText` where the
230 * markup's style is kept), the viewBox sized to the column. Undefined when
231 * there is nothing to draw.
232 */
233export function sparkSvg(values: readonly (number | null)[], columns: number): { source: string; width: number; height: number } | undefined {
234 const width = Math.max(1, Math.min(columns, SPARK_MAX_COLUMNS)) * PX_PER_COLUMN
235 const height = SPARK_HEIGHT
236 const points = sparkPoints(values, width, height)
237 if (!points) return undefined
238 const source =
239 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">` +
240 '<style>svg{color-scheme:light dark}polyline{stroke:CanvasText}</style>' +
241 `<polyline points="${points}" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>` +
242 '</svg>'
243 return { source, width, height }
244}
245
246const BLOCKS = '▁▂▃▄▅▆▇█'
247/** The terminal's default colour (bit 24 alone), foreground and background. */
248const DEFAULT_COLOUR = 0x01000000
249
250/** The Raster sparkline: one row of block glyphs, one per session, in the terminal's own colours. */
251export function sparkCells(values: readonly (number | null)[]): { cells: string; columns: number; rows: 1; glyphs: string } | undefined {
252 const v = sparkValues(values)
253 if (v.length === 0) return undefined
254 const max = Math.max(0, ...v)
255 const glyphs = v.map(n => BLOCKS[max > 0 ? Math.round((n / max) * (BLOCKS.length - 1)) : 0] as string)
256 const words = new Uint32Array(v.length * 3)
257 glyphs.forEach((g, i) => {
258 words[i * 3] = g.codePointAt(0) as number
259 words[i * 3 + 1] = DEFAULT_COLOUR
260 words[i * 3 + 2] = DEFAULT_COLOUR
261 })
262 return { cells: base64(littleEndian(words)), columns: v.length, rows: 1, glyphs: glyphs.join('') }
263}
264
265/** u32 words as little-endian bytes, whatever the host's order. */
266function littleEndian(words: Uint32Array): Uint8Array {
267 const bytes = new Uint8Array(words.length * 4)
268 words.forEach((w, i) => {
269 bytes[i * 4] = w & 0xff
270 bytes[i * 4 + 1] = (w >>> 8) & 0xff
271 bytes[i * 4 + 2] = (w >>> 16) & 0xff
272 bytes[i * 4 + 3] = (w >>> 24) & 0xff
273 })
274 return bytes
275}
276
277const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
278
279/** Standard padded base64 (the environment's Uint8Array may have no toBase64). */
280export function base64(bytes: Uint8Array): string {
281 let out = ''
282 for (let i = 0; i < bytes.length; i += 3) {
283 const a = bytes[i] as number
284 const b = bytes[i + 1]
285 const c = bytes[i + 2]
286 const n = (a << 16) | ((b ?? 0) << 8) | (c ?? 0)
287 out += B64[(n >> 18) & 63]
288 out += B64[(n >> 12) & 63]
289 out += b === undefined ? '=' : B64[(n >> 6) & 63]
290 out += c === undefined ? '=' : B64[n & 63]
291 }
292 return out
293}
294
295// ---- 3D: the status tool -----------------------------------------------------------
296
297export const STATUS_TOOL = {
298 name: 'status',
299 description:
300 'The chassis-delegation state, as the system prompt section renders it: running workers, pending verdicts, queued spawns and what is owed, then the last 10 verdict lines and the last eval and debrief. Call it instead of reading the store. Pass open: true only when the person asks to see the Delegation pane.',
301 inputSchema: {
302 type: 'object',
303 properties: {
304 open: { type: 'boolean', description: 'Also open the Delegation pane for the person (only when they asked to see it)' },
305 },
306 additionalProperties: false,
307 },
308} as const
309
310/** The name the model calls it by: `mcp__<plugin>__<name>`. */
311export const STATUS_TOOL_NAME = 'mcp__chassis-delegation__status'
312
313export const STATUS_VERDICTS = 10
314const NOTHING = 'Delegation state (chassis-delegation): nothing running, nothing owed.'
315
316/** The compose section's text (or that nothing runs), then the tails: 10 verdicts, the last eval, the last debrief. */
317export function statusToolText(section: string | undefined, tails: { verdicts: readonly string[]; eval?: string; debrief?: string }): string {
318 const verdicts = tails.verdicts.slice(-STATUS_VERDICTS)
319 return [
320 section ?? NOTHING,
321 ...(verdicts.length > 0 ? [`Last ${STATUS_VERDICTS} verdicts:`, ...verdicts.map(l => `- ${l}`)] : [`Last ${STATUS_VERDICTS} verdicts: none this session`]),
322 `Last eval: ${tails.eval ?? 'none'}`,
323 `Last debrief: ${tails.debrief ?? 'none this session'}`,
324 ].join('\n')
325}
326hooks/lib/drive.ts 175 lines1// MOD-48: what the brain's own driving costs it. Each main-loop tool call is
2// counted by what it did with the brain's context (run or poll, read, edit,
3// spawn), the brain's average context per call is kept, and a command it keeps
4// re-running or polling at a large context is named once a turn as worker work.
5// Pure: no `$`.
6import { priceFor, usdOf } from './cost'
7
8export type DriveKind = 'run' | 'read' | 'edit' | 'spawn'
9export type DriveRecord = {
10 run: number
11 read: number
12 edit: number
13 spawn: number
14 /** Input + cache-read tokens of the turns that made calls. */
15 ctxTokens: number
16 /** The calls those turns made. */
17 ctxCalls: number
18}
19
20export const emptyDrive = (): DriveRecord => ({ run: 0, read: 0, edit: 0, spawn: 0, ctxTokens: 0, ctxCalls: 0 })
21
22/** Default context, in tokens, from which the warn row speaks. */
23export const DRIVE_THRESHOLD_TOKENS = 200_000
24
25const EDIT_TOOLS = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit']
26const SPAWN_TOOLS = ['Agent', 'Task', 'SendMessage']
27const READ_COMMANDS = ['grep', 'egrep', 'fgrep', 'rg', 'sed', 'cat', 'ls', 'head', 'tail', 'find', 'wc', 'awk', 'cut', 'sort', 'jq', 'diff', 'stat', 'file', 'tree', 'less', 'cd', 'pwd', 'echo', 'test', 'which', 'tr', 'uniq', 'column']
28const SKIP_COMMANDS = ['git', 'gh']
29
30/** A command that waits on something: an until or while loop, or a sleep. */
31export const isPoll = (command: string): boolean => /(^|[\s;&|(])until\s/.test(command) || /(^|[\s;&|(])while\s[^]*\bsleep\b/.test(command) || /(^|[\s;&|(])sleep\s+\d/.test(command)
32
33const firstWord = (command: string): string => {
34 const words = command.trim().split(/\s+/)
35 const i = words.findIndex(w => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w))
36 return (i >= 0 ? words[i] : '').replace(/^.*\//, '')
37}
38
39/**
40 * The kind of a main-loop call, or undefined when it is none of the four.
41 * `writes`: a Bash command that writes into the root; `repeat`: the command already ran this turn.
42 */
43export function callKind(tool: string, input: { command?: unknown; run_in_background?: unknown }, writes = false, repeat = false): DriveKind | undefined {
44 if (EDIT_TOOLS.includes(tool)) return 'edit'
45 if (SPAWN_TOOLS.includes(tool)) return 'spawn'
46 if (tool === 'Read') return 'read'
47 if (tool !== 'Bash') return undefined
48 const command = typeof input.command === 'string' ? input.command : ''
49 if (input.run_in_background === true || isPoll(command) || repeat) return 'run'
50 if (writes) return 'edit'
51 const w = firstWord(command)
52 if (SKIP_COMMANDS.includes(w)) return undefined
53 if (READ_COMMANDS.includes(w)) return 'read'
54 return 'run'
55}
56
57export const driveCall = (r: DriveRecord | undefined, kind: DriveKind): DriveRecord => {
58 const prev = r ?? emptyDrive()
59 return { ...prev, [kind]: prev[kind] + 1 }
60}
61
62/** A finished main-loop turn that made `calls` calls: its input + cache-read tokens. */
63export const driveTurn = (r: DriveRecord | undefined, contextTokens: number, calls: number): DriveRecord => {
64 const prev = r ?? emptyDrive()
65 return calls > 0 ? { ...prev, ctxTokens: prev.ctxTokens + contextTokens, ctxCalls: prev.ctxCalls + calls } : prev
66}
67
68const tokText = (n: number): string => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}K` : String(n))
69
70/** `brain calls: 3 run-or-poll · 1 read · average context 100K per call`; none when nothing was counted. */
71export function driveLines(r: DriveRecord | undefined): string[] {
72 if (!r) return []
73 const parts: string[] = []
74 if (r.run > 0) parts.push(`${r.run} run-or-poll`)
75 if (r.read > 0) parts.push(`${r.read} read`)
76 if (r.edit > 0) parts.push(`${r.edit} edit`)
77 if (r.spawn > 0) parts.push(`${r.spawn} spawn`)
78 if (parts.length === 0) return []
79 if (r.ctxCalls > 0) parts.push(`average context ${tokText(Math.round(r.ctxTokens / r.ctxCalls))} per call`)
80 return [`brain calls: ${parts.join(' · ')}`]
81}
82
83// ---- the warn row ---------------------------------------------------------------------
84
85/** A key longer than this is cut and hashed, so the store stays small. */
86const KEY_MAX = 120
87
88const hashOf = (text: string): string => {
89 let h = 5381
90 for (let i = 0; i < text.length; i++) h = ((h * 33) ^ text.charCodeAt(i)) >>> 0
91 return h.toString(36)
92}
93
94const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|\S*)\s*(?:;|&&)?\s*/
95const CD = /^cd\s+(?:"[^"]*"|'[^']*'|\S+)\s*&&\s*/
96
97/**
98 * MOD-119 (#187): what "the same command" means. Leading NAME=value assignments (each optionally followed by `;` or
99 * `&&`) and a leading `cd <dir> &&` are dropped, whitespace is squeezed, and the whole remainder is the key (hashed
100 * when long). A command that is nothing but an assignment keeps its own text.
101 */
102export function commandKey(command: string): string {
103 const whole = command.trim().replace(/\s+/g, ' ')
104 let rest = whole
105 for (;;) {
106 const next = rest.replace(ASSIGNMENT, '').replace(CD, '')
107 if (next === rest) break
108 rest = next
109 }
110 const key = rest === '' ? whole : rest
111 return key.length > KEY_MAX ? `${key.slice(0, 80)}~${hashOf(key)}` : key
112}
113
114/** `runs`: per key, the runs that count toward the row and the hash of the last known output. */
115export type Watch = { commands: string[]; warned: boolean; runs?: Record<string, { count: number; out?: string }> }
116export const emptyWatch = (): Watch => ({ commands: [], warned: false, runs: {} })
117
118/** True when `command` has already run in the watch (this turn). */
119export const ranBefore = (w: Watch, command: string): boolean => w.commands.includes(commandKey(command))
120
121/**
122 * MOD-119: the output of a Bash call that has finished. A repeat whose output differs from the last same-key call is
123 * a command making progress, so it starts the count again; an unchanged output keeps counting.
124 */
125export function driveOutput(w: Watch, command: string, output: string): Watch {
126 const key = commandKey(command)
127 const runs = { ...(w.runs ?? {}) }
128 const prev = runs[key] ?? { count: w.commands.filter(c => c === key).length }
129 const out = hashOf(output)
130 runs[key] = { count: prev.out !== undefined && prev.out !== out ? 1 : prev.count, out }
131 return { ...w, runs }
132}
133
134/** MOD-99 (#165): the move the polling row names: card the resource it uses, wait with the verdict tool, else the guide section. */
135export function nudgeMove(command: string, resources: readonly string[] = [], waitingOnWorker = false): string {
136 const lower = command.toLowerCase()
137 const named = resources.find(r => r !== '' && lower.includes(r.toLowerCase()))
138 if (named !== undefined) return `Move: card it with resources: [${named}] so one worker drives it.`
139 if (waitingOnWorker) return 'Move: wait with the verdict tool (it returns when the worker hands back) instead of polling.'
140 return 'A standard card would drive this loop from a small context on a cheaper model; add resources for a one-client app so workers take turns (see docs/guide.md#one-client-resources).'
141}
142
143/**
144 * One Bash command of the brain's turn. The row speaks when the context is at or above the threshold and the
145 * command is the third run of the same command (see commandKey) whose output did not change, or polls; at most once a turn.
146 */
147export function driveStep(
148 w: Watch,
149 i: { command: string; context: number; threshold: number; model?: string; enabled: boolean; resources?: readonly string[]; waitingOnWorker?: boolean },
150): { state: Watch; row?: string } {
151 const key = commandKey(i.command)
152 const prev = w.runs?.[key]
153 const count = (prev ? prev.count : w.commands.filter(c => c === key).length) + 1
154 const state: Watch = { commands: [...w.commands, key], warned: w.warned, runs: { ...(w.runs ?? {}), [key]: { count, ...(prev?.out !== undefined ? { out: prev.out } : {}) } } }
155 const poll = isPoll(i.command)
156 if (!i.enabled || w.warned || i.context < i.threshold || !(count >= 3 || poll)) return { state }
157 const price = priceFor(i.model)
158 const cost = price ? ` (about $${usdOf({ in: 0, out: 0, cacheRead: i.context, cacheWrite: 0 }, price).toFixed(2)} a call at that context on ${i.model})` : ''
159 const what = poll && count < 3 ? `polled with "${key}"` : `ran "${key}" ${count} times this turn`
160 return { state: { ...state, warned: true }, row: `chassis-delegation: the brain ${what} at ${tokText(i.context)} context${cost}. ${nudgeMove(i.command, i.resources, i.waitingOnWorker)}` }
161}
162
163// ---- the fresh-session row (MOD-53) ---------------------------------------------------
164
165/** Default context, in tokens, from which the brain is told to start a fresh session. */
166export const FRESH_SESSION_TOKENS = 400_000
167
168const kText = (n: number): string => `${Math.round(n / 1000)}K`
169
170/** At or above `threshold` the row that says a fresh session is cheaper; none below it, or when `threshold` is 0 (off). */
171export function freshSessionRow(context: number, threshold: number): string | undefined {
172 if (!(threshold > 0) || context < threshold) return undefined
173 return `chassis-delegation: brain context ${kText(context)} (freshSessionTokens ${kText(threshold)}): start a fresh session at the next phase boundary; cards, the ledger and lessons carry over`
174}
175hooks/lib/waitstate.ts 50 lines1// MOD-99 (#161): a briefed worker that is waiting (its turn ended with no hand-back) wakes the brain once per
2// state, says what it waits on, and says it is stalled once past a ceiling. Pure: no `$`.
3import { extractReport } from './brief'
4import { detectRateLimit } from './verify'
5
6/** Default `waitStallMin`: minutes a worker may wait before the mod says it is stalled; 0 is off. */
7export const WAIT_STALL_DEFAULT_MIN = 20
8
9const MIN_MS = 60 * 1000
10
11/** What the mod remembers of one waiting worker. */
12export type WaitState = { since: number; stalled?: true }
13
14/** The resource a waiting worker's card names and the worker that holds it. */
15export type WaitOn = { resource: string; holder: string }
16
17const WAIT_NOW = /\b(?:waiting|(?:i['\u2019]?ll|i will|will|going to|still|now)\s+wait(?:ing)?)\s+(?:on|for)\s+(?:the\s+|a\s+|an\s+|my\s+|its\s+|another\s+)?(?:\w+\s+){0,3}?(?:background|job|task|process|render|build|lock|resource|agent|worker)/i
18
19/**
20 * A worker turn that ended with no report and whose last paragraph (at most its last 400 characters) says it is
21 * waiting now on a job, task, process, render, build, lock, resource or another agent. A usage-limit text
22 * (MOD-56) is never a wait; past tense or a bare "wait" elsewhere does not count.
23 */
24export function saysWaiting(text: string): boolean {
25 if (extractReport(text) !== undefined || detectRateLimit(text) !== undefined) return false
26 const paras = text.trim().split(/\n\s*\n/)
27 const last = (paras[paras.length - 1] ?? '').slice(-400)
28 return WAIT_NOW.test(last)
29}
30
31const minutes = (ms: number): number => Math.max(0, Math.round(ms / MIN_MS))
32
33/** `T-4 waiting on blender-live held by T-1`, else `T-4 waiting on its own background job (3 min)`. */
34export const waitText = (id: string, waited: number, on?: WaitOn): string =>
35 on ? `${id} waiting on ${on.resource} held by ${on.holder}` : `${id} waiting on its own background job (${minutes(waited)} min)`
36
37/** `T-4 stalled 20 min; resume or stop it`. */
38export const stallText = (id: string, waited: number): string => `${id} stalled ${minutes(waited)} min; resume or stop it`
39
40/**
41 * One sighting of a worker waiting. The first starts the state and speaks; a repeat in the same state is held;
42 * once the wait reaches `ceilingMin` (0 = off) the state speaks one more time, then holds again.
43 */
44export function waitStep(prev: WaitState | undefined, now: number, ceilingMin: number, id: string, on?: WaitOn): { state: WaitState; say?: string; held?: true } {
45 if (!prev) return { state: { since: now }, say: waitText(id, 0, on) }
46 const waited = now - prev.since
47 if (ceilingMin > 0 && !prev.stalled && waited >= ceilingMin * MIN_MS) return { state: { ...prev, stalled: true }, say: stallText(id, waited) }
48 return { state: prev, held: true }
49}
50hooks/lib/band.tsx 85 lines1// Part 4A, as GH-112 wires it: the band above the prompt, one row, drawn only
2// while a worker is live, a spawn is queued or a verdict is owed. The whole
3// band is a hover scope: hovering it reveals the card (the KPI tiles, the spend
4// chart, the worktree table) beneath the row. `[ details ]` opens the pane.
5// MOD-133: the ration health bar draws here too, alone or above the live row.
6// No `$` here: register.ts resolves the element table and hands in the handler.
7import type { RenderNode } from 'claude-code'
8
9import type { BandLine } from './dashboard'
10import { sparkCells, sparkSvg } from './dashboard'
11import { bandSummary, recentSpend, type LiveView, type Scheme } from './live'
12import { liveBlocks, rationBar, type PaneTable, type PaneView } from './pane'
13
14export const DASH_SCOPE = 'chassis-delegation-dash'
15
16/** MOD-81: columns the sparkline, the details button and the gaps take beside the summary text. */
17const BAND_RESERVED = 32
18
19/** Lines past the band's rows fold into one `… n more` line; the Button keeps the last row. */
20export function capLines(lines: readonly BandLine[], maxRows: number): BandLine[] {
21 const room = Math.max(1, maxRows - 1)
22 if (lines.length <= room) return [...lines]
23 const keep = Math.max(0, room - 1)
24 return [...lines.slice(0, keep), { key: 'more', text: `▸ … ${lines.length - keep} more — see details` }]
25}
26
27function sparkline(p: PaneTable, v: LiveView): RenderNode | null {
28 const values = recentSpend(v.series, v.now)
29 if (values.length < 2) return null
30 const { Box } = p.t
31 if (p.surface === 'terminal') {
32 const cells = sparkCells(values)
33 if (!cells) return null
34 const { Raster } = p.t
35 return (
36 <Box flexDirection="row">
37 <Raster key="band-spark" columns={cells.columns} rows={1} cells={cells.cells} />
38 </Box>
39 )
40 }
41 const svg = sparkSvg(values, 14)
42 if (!svg) return null
43 const { Svg } = p.t
44 return (
45 <Box flexDirection="row">
46 <Svg source={svg.source} alt={`Session spend, last 30 minutes: ${values.map(n => `$${n.toFixed(2)}`).join(', ')}`} width={svg.width} height={svg.height} />
47 </Box>
48 )
49}
50
51type Ration = NonNullable<PaneView['ration']>
52
53/** MOD-133: the coloured bar and `59% left · resets 2d 4h · today 6.2/8.4 · on pace`, the pane's own rationBar. */
54function rationRow(p: PaneTable, r: Ration, scheme: Scheme): RenderNode {
55 return rationBar(p, r, scheme, 0, r.tail ? `${r.text} · ${r.tail}` : r.text)
56}
57
58/** MOD-133: the band with the ration bar alone: the bar row, then `[ details ]`. No worker figures. */
59export function rationBandTree(p: PaneTable, r: Ration, scheme: Scheme, onDetails: () => void): RenderNode {
60 const { Box, Button } = p.t
61 return (
62 <Box key="dash-band" flexDirection="row" gap={1}>
63 {rationRow(p, r, scheme)}
64 <Button key="details" label="details" hotkey="d" variant="primary" onPress={onDetails} />
65 </Box>
66 )
67}
68
69export function bandTree(p: PaneTable, v: LiveView, scheme: Scheme, columns: number, onDetails: () => void, ration?: Ration): RenderNode {
70 const { Box, Text, Button } = p.t
71 return (
72 <Box key="dash-band" flexDirection="column" hover={{ scope: DASH_SCOPE }}>
73 {ration ? rationRow(p, ration, scheme) : null}
74 <Box flexDirection="row" gap={1} hover={{ scope: DASH_SCOPE }}>
75 <Text wrap="truncate-end">{bandSummary(v, Math.max(20, columns - BAND_RESERVED))} ·</Text>
76 {sparkline(p, v)}
77 <Button key="details" label="details" hotkey="d" variant="primary" onPress={onDetails} />
78 </Box>
79 <Box key="dash-card" flexDirection="column" display="none" hover={{ scope: DASH_SCOPE, display: 'flex' }}>
80 {liveBlocks(p, v, scheme, Math.max(10, columns - 2), false)}
81 </Box>
82 </Box>
83 )
84}
85hooks/lib/brain.ts 545 lines1// GH-113: the brain's own spend, kept apart from the workers', and the
2// delegate-only decision table. Every main-loop `turn.complete` with a usage
3// adds to one record (tokens, dollars by model, turns, the brain's own source
4// edits); the dashboard and /delegation read it. Pure: no `$`.
5import { addTurn, priceFor, round4, tokensOf, usdOf, type Tokens, type UsageLike } from './cost'
6
7export type BrainModel = { usd: number; tokens: number; turns: number }
8export type BrainRecord = {
9 tokens: Tokens
10 /** Dollars of the priced turns. */
11 usd: number
12 /** True once a turn ran on a model the price table lacks (its tokens count, its dollars cannot). */
13 unpriced: boolean
14 turns: number
15 /** The brain's own writes (Edit, Write, MultiEdit, NotebookEdit, a Bash write into the root), allowed or not. */
16 edits: number
17 byModel: Record<string, BrainModel>
18}
19
20export const emptyBrain = (): BrainRecord => ({ tokens: { in: 0, out: 0, cacheRead: 0, cacheWrite: 0 }, usd: 0, unpriced: false, turns: 0, edits: 0, byModel: {} })
21
22/** The record with one more main-loop turn. */
23export function brainTurn(acc: BrainRecord | undefined, u: UsageLike): BrainRecord {
24 const prev = acc ?? emptyBrain()
25 const t = tokensOf(u)
26 const price = priceFor(u.model)
27 const usd = price ? usdOf(t, price) : 0
28 const model = u.model || 'unknown'
29 const was = prev.byModel[model] ?? { usd: 0, tokens: 0, turns: 0 }
30 const sum = addTurn({ tokens: prev.tokens, usd: 0, turns: prev.turns, models: [] }, u)
31 return {
32 tokens: sum.tokens,
33 usd: round4(prev.usd + usd),
34 unpriced: prev.unpriced || price === undefined,
35 turns: prev.turns + 1,
36 edits: prev.edits,
37 byModel: { ...prev.byModel, [model]: { usd: round4(was.usd + usd), tokens: was.tokens + t.in + t.out + t.cacheRead + t.cacheWrite, turns: was.turns + 1 } },
38 }
39}
40
41/** The record with one more brain edit. */
42export const brainEdit = (acc: BrainRecord | undefined): BrainRecord => ({ ...(acc ?? emptyBrain()), edits: (acc?.edits ?? 0) + 1 })
43
44export type BrainFamily = 'fable' | 'opus' | 'sonnet' | 'haiku' | 'other'
45
46/** The family of a model alias or id. */
47export function brainFamily(model: string | undefined): BrainFamily {
48 const m = (model ?? '').toLowerCase()
49 for (const f of ['fable', 'opus', 'sonnet', 'haiku'] as const) if (m.includes(f)) return f
50 return 'other'
51}
52
53export type Split = { total: number; brain: number; workers: number; share: number }
54
55/** The three numbers and the brain's share of the total; the total is brain + workers where the session's is unknown. */
56export function brainSplit(sessionUsd: number | undefined, brainUsd: number, workersUsd: number, adhocUsd = 0): Split {
57 const total = sessionUsd !== undefined && Number.isFinite(sessionUsd) ? sessionUsd : brainUsd + workersUsd + adhocUsd
58 return { total: round4(total), brain: round4(brainUsd), workers: round4(workersUsd), share: total > 0 ? Math.min(1, brainUsd / total) : 0 }
59}
60
61/** MOD-37: the session's ad hoc Agent spawns (no brief header): their dollars and how many. */
62export type AdHoc = { usd: number; agents: number }
63
64export type BrainSummary = Split & {
65 /** MOD-37: ad hoc spawns this session. */
66 adhoc: AdHoc
67 /** MOD-37: the session total less brain, workers and ad hoc; 0 when the total is unknown or smaller. */
68 unattributed: number
69 /** The family of the model that spent most. */
70 family: BrainFamily
71 /** That model's id. */
72 model?: string
73 tokens: number
74 turns: number
75 edits: number
76 attempts: number
77 unpriced: boolean
78}
79
80/** What the lines and the dashboard show of a record, beside the workers' dollars and attempts. */
81export function brainSummary(rec: BrainRecord | undefined, workersUsd: number, attempts: number, sessionUsd?: number, adhoc: AdHoc = { usd: 0, agents: 0 }): BrainSummary {
82 const r = rec ?? emptyBrain()
83 const top = Object.entries(r.byModel).sort((a, b) => b[1].usd - a[1].usd || b[1].tokens - a[1].tokens)[0]
84 const tokens = r.tokens.in + r.tokens.out + r.tokens.cacheRead + r.tokens.cacheWrite
85 const split = brainSplit(sessionUsd, r.usd, workersUsd, adhoc.usd)
86 return {
87 ...split,
88 adhoc,
89 unattributed: sessionUsd !== undefined && Number.isFinite(sessionUsd) ? Math.max(0, round4(split.total - split.brain - split.workers - adhoc.usd)) : 0,
90 family: brainFamily(top?.[0]),
91 ...(top ? { model: top[0] } : {}),
92 tokens,
93 turns: r.turns,
94 edits: r.edits,
95 attempts,
96 unpriced: r.unpriced,
97 }
98}
99
100const money = (n: number): string => `$${n.toFixed(2)}`
101
102/**
103 * `brain: fable $2.25 over 2 turns · workers $0.75 (3 attempts) · ad hoc $1.00 (1 agents) · unattributed $0.50 · brain share 75%`
104 * (MOD-37: the ad hoc part shows once an ad hoc agent ran, the unattributed part from one cent).
105 */
106export const brainLine = (s: BrainSummary): string =>
107 [
108 `brain: ${s.family} ${money(s.brain)} over ${s.turns} turns`,
109 `workers ${money(s.workers)} (${s.attempts} attempts)`,
110 ...(s.adhoc.agents > 0 || s.adhoc.usd > 0 ? [`ad hoc ${money(s.adhoc.usd)} (${s.adhoc.agents} agents)`] : []),
111 ...(s.unattributed >= 0.01 ? [`unattributed ${money(s.unattributed)}`] : []),
112 `brain share ${Math.round(s.share * 100)}%`,
113 ].join(' · ')
114
115/** The KPI tile's value: `brain $2.25 / workers $0.75`. */
116export const brainTileText = (s: Pick<BrainSummary, 'brain' | 'workers'>): string => `brain ${money(s.brain)} / workers ${money(s.workers)}`
117
118// ---- delegate-only -------------------------------------------------------------------
119
120export type DelegateMode = 'off' | 'warn' | 'deny'
121export const DELEGATE_MODES: readonly DelegateMode[] = ['off', 'warn', 'deny']
122
123export const DELEGATE_DENY = 'chassis-delegation: delegateOnly is on: the brain does not edit source. Describe the task and call the card tool, or set delegateOnly off.'
124
125export const warnRow = (path: string): string => `chassis-delegation: the brain edited ${path} itself; a card would have delegated it (delegateOnly=warn)`
126
127/** The two lines a premium brain gets at the top of the delegation state. */
128export const PREMIUM_POSTURE: readonly string[] = [
129 'You are the brain on a premium model. Build work goes to workers through the card tool; you read the repo to write cards, verify hand-backs, and read diffs.',
130 'Do not edit source or run the test suite yourself.',
131]
132
133export const WRITE_TOOLS: readonly string[] = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit']
134
135/** Families delegateOnly restricts: the frontier and the premium. A Sonnet or Haiku brain is never restricted. */
136export const isRestricted = (f: BrainFamily): boolean => f === 'opus' || f === 'fable'
137
138const trimDir = (s: string) => s.replace(/^\/+|\/+$/g, '')
139
140/** The path relative to the root, or undefined when it is outside it. */
141export function relativeTo(root: string, path: string): string | undefined {
142 const r = root.replace(/\/+$/, '')
143 const parts: string[] = []
144 const abs = path.startsWith('/') ? path : `${r}/${path}`
145 for (const p of abs.split('/')) {
146 if (p === '' || p === '.') continue
147 if (p === '..') parts.pop()
148 else parts.push(p)
149 }
150 const full = `/${parts.join('/')}`
151 return full.startsWith(`${r}/`) ? full.slice(r.length + 1) : undefined
152}
153
154/** The card folder, `.delegation/`, the repo file, CHANGELOG.md and a docs/ folder: what the brain may write. */
155export function isAllowedPath(rel: string, cardDir: string): boolean {
156 const card = trimDir(cardDir)
157 if (card !== '' && (rel === card || rel.startsWith(`${card}/`))) return true
158 if (rel.startsWith('.delegation/')) return true
159 if (rel === '.chassis-delegation.json' || rel === 'CHANGELOG.md') return true
160 return rel.startsWith('docs/') || rel.includes('/docs/')
161}
162
163export type DelegateInput = {
164 mode: DelegateMode
165 brainFamily: BrainFamily
166 tool: string
167 /** The paths the call writes (absolute, or relative to the root). */
168 paths: readonly string[]
169 root: string
170 cardDir: string
171 /** A Bash command that commits (MOD-9: the flag alone never denies; the paths the commit takes are in `paths`). */
172 commit?: boolean
173}
174export type DelegateDecision = { action: 'allow' | 'warn' | 'deny'; edit: boolean; path?: string }
175
176/**
177 * The table. Not a write by the brain: allow, no edit. A write: an edit (it counts)
178 * whether or not it is allowed; allowed when the mode is off, the brain is not
179 * opus or fable, or every path in the root is on the allowlist; else warn or deny.
180 */
181export function delegateDecision(i: DelegateInput): DelegateDecision {
182 const isWrite = WRITE_TOOLS.includes(i.tool) || (i.tool === 'Bash' && i.paths.length > 0)
183 if (!isWrite) return { action: 'allow', edit: false }
184 const rels = i.paths.map(p => relativeTo(i.root, p)).filter((r): r is string => r !== undefined)
185 if (rels.length === 0) return { action: 'allow', edit: false } // wholly outside the repo
186 const offending = rels.find(r => !isAllowedPath(r, i.cardDir))
187 if (offending === undefined || i.mode === 'off' || !isRestricted(i.brainFamily)) return { action: 'allow', edit: true }
188 return { action: i.mode, edit: true, path: offending }
189}
190
191/** The path an Edit-family call writes. */
192export function toolPath(input: Record<string, unknown>): string[] {
193 const p = typeof input.file_path === 'string' ? input.file_path : typeof input.notebook_path === 'string' ? input.notebook_path : undefined
194 return p ? [p] : []
195}
196
197// ---- what a Bash command writes ------------------------------------------------------
198
199const SEPS = ['&&', '||', ';;', ';', '|&', '|', '&', '(', ')', '$(', '`']
200const ASSIGN = /^[A-Za-z_][A-Za-z0-9_]*=/
201const SKIP_TARGET = /^\/dev\/(null|stdout|stderr|tty)$/
202
203type Tok = { k: 'word' | 'sep' | 'out' | 'dup' | 'in'; t: string }
204
205/**
206 * Shell-like tokens: quotes and backslashes honoured; separators; an unquoted
207 * `>` / `>>` / `&>` as an `out` token (`>&` a `dup`, `<` an `in`) with its fd
208 * prefix dropped; comments and heredoc bodies skipped.
209 *
210 * MOD-20: a `$( )` or backtick substitution inside double quotes is a command
211 * of its own, read like any other (its separators, its redirects, its quotes):
212 * the quoted text round it stays quoted, and a `>` inside the substitution's
213 * own quotes is no redirect. The word before it is cut with a `$` on its end, so
214 * a target that holds a substitution stays unknown.
215 */
216function lex(text: string): Tok[] {
217 const toks: Tok[] = []
218 let word = ''
219 let inWord = false
220 // inside double quotes, as opposed to the command text round them
221 let dq = false
222 // what each open `(`, `$(` or backtick returns to when it closes: the double quotes it opened in, or command text
223 const open: { dq: boolean; tick: boolean }[] = []
224 const docs: { delim: string; dash: boolean }[] = []
225 const flush = () => {
226 if (inWord) toks.push({ k: 'word', t: word })
227 word = ''
228 inWord = false
229 }
230 const n = text.length
231 let i = 0
232 while (i < n) {
233 const c = text[i] as string
234 if (dq) {
235 if (c === '"') dq = false
236 else if (c === '\\' && i + 1 < n) {
237 word += text[i + 1]
238 i += 1
239 } else if ((c === '$' && text[i + 1] === '(') || c === '`') {
240 const sub = c === '`' ? '`' : '$('
241 word += '$'
242 flush()
243 toks.push({ k: 'sep', t: sub })
244 open.push({ dq: true, tick: c === '`' })
245 dq = false
246 i += sub.length
247 continue
248 } else word += c
249 i += 1
250 continue
251 }
252 if (c === '\\' && i + 1 < n) {
253 if (text[i + 1] !== '\n') {
254 word += text[i + 1]
255 inWord = true
256 }
257 i += 2
258 continue
259 }
260 if (c === "'") {
261 const end = text.indexOf("'", i + 1)
262 word += end < 0 ? text.slice(i + 1) : text.slice(i + 1, end)
263 inWord = true
264 i = end < 0 ? n : end + 1
265 continue
266 }
267 if (c === '"') {
268 dq = true
269 inWord = true
270 i += 1
271 continue
272 }
273 if (c === '#' && !inWord) {
274 while (i < n && text[i] !== '\n') i += 1
275 continue
276 }
277 if (c === '<' && text.startsWith('<<', i) && !text.startsWith('<<<', i)) {
278 flush()
279 let j = i + 2
280 const dash = text[j] === '-'
281 if (dash) j += 1
282 while (j < n && (text[j] === ' ' || text[j] === '\t')) j += 1
283 let delim = ''
284 while (j < n && !/[\s;&|()<>]/.test(text[j] as string)) {
285 const d = text[j] as string
286 if (d !== "'" && d !== '"' && d !== '\\') delim += d
287 j += 1
288 }
289 if (delim) docs.push({ delim, dash })
290 i = j
291 continue
292 }
293 if (c === '\n') {
294 flush()
295 toks.push({ k: 'sep', t: '\n' })
296 i += 1
297 while (docs.length > 0 && i <= n) {
298 const doc = docs.shift() as { delim: string; dash: boolean }
299 for (;;) {
300 if (i >= n) break
301 const end = text.indexOf('\n', i)
302 const line = end < 0 ? text.slice(i) : text.slice(i, end)
303 i = end < 0 ? n : end + 1
304 if ((doc.dash ? line.replace(/^\t+/, '') : line) === doc.delim) break
305 }
306 }
307 continue
308 }
309 if (c === ' ' || c === '\t' || c === '\r') {
310 flush()
311 i += 1
312 continue
313 }
314 if (c === '&' && text[i + 1] === '>') {
315 flush()
316 toks.push({ k: 'out', t: '>' })
317 i += text[i + 2] === '>' ? 3 : 2
318 continue
319 }
320 if (c === '>' || c === '<') {
321 // an fd number glued in front (2>) is part of the operator
322 if (inWord && /^\d+$/.test(word)) {
323 word = ''
324 inWord = false
325 } else flush()
326 const doubled = text[i + 1] === c
327 i += doubled ? 2 : 1
328 if (c === '>' && text[i] === '&') {
329 toks.push({ k: 'dup', t: '>&' })
330 i += 1
331 } else {
332 if (c === '>' && text[i] === '|') i += 1
333 toks.push({ k: c === '>' ? 'out' : 'in', t: c })
334 }
335 continue
336 }
337 const sep = SEPS.find(x => text.startsWith(x, i))
338 if (sep) {
339 flush()
340 toks.push({ k: 'sep', t: sep })
341 i += sep.length
342 // a closing ) or backtick goes back to the double quotes its substitution opened in
343 const closing = sep === ')' ? open.pop() : sep === '`' && open.at(-1)?.tick ? open.pop() : undefined
344 if (sep === '(' || sep === '$(' || (sep === '`' && !closing)) open.push({ dq: false, tick: sep === '`' })
345 if (closing?.dq) {
346 dq = true
347 inWord = true
348 }
349 continue
350 }
351 word += c
352 inWord = true
353 i += 1
354 }
355 flush()
356 return toks
357}
358
359/** A `git commit` that runs in the session's repo (MOD-9): where, and what it was told to commit. */
360export type CommitCall = { dir: string; all: boolean; amend: boolean; pathspecs: string[] }
361
362const RESERVED = new Set(['{', 'then', 'do', 'else', 'elif', 'if', 'while', 'until', '!', 'time'])
363const CD_OPT = /^(-[LPe@]+|--)$/
364/** A sed -i backup suffix given as its own word: empty, or dotted (`.bak`). */
365const BSD_SUFFIX = /^(\.[A-Za-z0-9._~-]*)?$/
366const COMMIT_VALUE_SHORT = 'mFCctS'
367const COMMIT_VALUE_LONG = new Set(['--message', '--file', '--author', '--date', '--reuse-message', '--reedit-message', '--fixup', '--squash', '--cleanup', '--template'])
368
369/** `/a/./b/../c` as `/a/c`. */
370function normAbs(path: string): string {
371 const parts: string[] = []
372 for (const p of path.split('/')) {
373 if (p === '' || p === '.') continue
374 if (p === '..') parts.pop()
375 else parts.push(p)
376 }
377 return `/${parts.join('/')}`
378}
379
380/**
381 * Reads a command the way a shell reads words (quotes whole, heredoc bodies skipped)
382 * and follows the working directory through it: the files it writes under the root
383 * (a `>` / `>>` redirection, `tee`, `sed -i`, `cp` / `mv` destination) and the
384 * `git commit`s it runs. An accident tripwire, not adversary-proof.
385 *
386 * A target is resolved first (MOD-8): `~`, `$HOME` (the `home` argument), `$PWD`
387 * (the working directory in force) and a `$NAME` assigned a literal earlier in the
388 * command. MOD-9: a relative target resolves against the folder a `cd` / `pushd`
389 * left (the root to begin with); a `cd` inside `( )` or `$( )` is undone at the
390 * closing parenthesis; a `cd` in a pipeline or run in the background does not
391 * move the later segments; a `cd` whose folder cannot be resolved makes every later
392 * relative target unknown. A target that stays unresolved is unknown and not counted.
393 */
394function scan(command: string, root: string, home?: string): { paths: string[]; commits: CommitCall[] } {
395 const toks = lex(command)
396 type Seg = { toks: Tok[]; before: string; after: string }
397 const segments: Seg[] = [{ toks: [], before: '', after: '' }]
398 for (const t of toks) {
399 if (t.k === 'sep') {
400 ;(segments.at(-1) as Seg).after = t.t
401 segments.push({ toks: [], before: t.t, after: '' })
402 } else (segments.at(-1) as Seg).toks.push(t)
403 }
404 const out: string[] = []
405 const commits: CommitCall[] = []
406 const prefix = root.replace(/\/+$/, '')
407 const homeDir = home ? home.replace(/\/+$/, '') : undefined
408 const vars = new Map<string, string>()
409 let cwd: string | undefined = normAbs(prefix)
410 const stack: (string | undefined)[] = []
411 let ticks = false
412 const resolve = (p: string): string | undefined => {
413 let t = p
414 if (t === '~' || t.startsWith('~/')) {
415 if (!homeDir) return undefined
416 t = homeDir + t.slice(1)
417 }
418 t = t.replace(/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g, (m, a, b) => {
419 const name = (a ?? b) as string
420 if (name === 'HOME') return homeDir ?? m
421 if (name === 'PWD') return cwd ?? m
422 return vars.get(name) ?? m
423 })
424 return /[$`]/.test(t) ? undefined : t
425 }
426 /** An absolute, normalised folder or file for a word, against `base`; undefined when unknown. */
427 const absOf = (raw: string, base: string | undefined): string | undefined => {
428 const p = resolve(raw)
429 if (p === undefined || p.startsWith('~')) return undefined
430 if (p.startsWith('/')) return normAbs(p)
431 return base === undefined ? undefined : normAbs(`${base}/${p}`)
432 }
433 const add = (raw: string | undefined, base: string | undefined) => {
434 if (!raw || SKIP_TARGET.test(raw)) return
435 const p = absOf(raw, base)
436 if (p === undefined || SKIP_TARGET.test(p)) return
437 const rel = relativeTo(root, p)
438 if (rel !== undefined && !out.includes(`${prefix}/${rel}`)) out.push(`${prefix}/${rel}`)
439 }
440 for (const seg of segments) {
441 // redirections anywhere in the segment, then the command's own words
442 const words: string[] = []
443 const redirs: (string | undefined)[] = []
444 for (let i = 0; i < seg.toks.length; i++) {
445 const tk = seg.toks[i] as Tok
446 if (tk.k === 'word') words.push(tk.t)
447 else {
448 const target = seg.toks[i + 1]?.k === 'word' ? (seg.toks[i + 1] as Tok).t : undefined
449 if (tk.k === 'out') redirs.push(target)
450 if (target !== undefined) i += 1
451 }
452 }
453 const opensSubst = seg.after === '$(' || seg.after === '`'
454 let k = 0
455 while (k < words.length && (ASSIGN.test(words[k] as string) || RESERVED.has(words[k] as string))) k++
456 const assigns = words.slice(0, k).filter(a => ASSIGN.test(a))
457 assigns.forEach((a, n) => {
458 const eq = a.indexOf('=')
459 const val = opensSubst && k === words.length && n === assigns.length - 1 ? undefined : resolve(a.slice(eq + 1))
460 if (val === undefined) vars.delete(a.slice(0, eq))
461 else vars.set(a.slice(0, eq), val)
462 })
463 for (const r of redirs) add(r, cwd)
464 const cmd = (words[k] ?? '').replace(/^.*\//, '')
465 const args = words.slice(k + 1)
466 const plain = args.filter(a => !a.startsWith('-'))
467 if (cmd === 'cd' || cmd === 'pushd' || cmd === 'popd') {
468 const subshell = seg.before === '|' || seg.before === '|&' || seg.after === '|' || seg.after === '|&' || seg.after === '&'
469 if (!subshell) {
470 const rest = args.filter(a => !CD_OPT.test(a))
471 if (cmd === 'popd' || opensSubst || rest[0] === '-') cwd = undefined
472 else if (rest.length === 0) cwd = homeDir ? normAbs(homeDir) : undefined
473 else cwd = absOf(rest[0] as string, cwd)
474 }
475 } else if (cmd === 'git') {
476 // the subcommand is the first word that is no option (nor the value of -C / -c); each -C moves this command's folder only
477 let dir = cwd
478 let j = 0
479 while (j < args.length && (args[j] as string).startsWith('-')) {
480 if (args[j] === '-C') dir = absOf(args[j + 1] ?? '', dir)
481 j += args[j] === '-C' || args[j] === '-c' ? 2 : 1
482 }
483 if (args[j] === 'commit' && dir !== undefined && (dir === normAbs(prefix) || relativeTo(root, dir) !== undefined)) {
484 const call: CommitCall = { dir, all: false, amend: false, pathspecs: [] }
485 let past = false
486 for (let m = j + 1; m < args.length; m++) {
487 const a = args[m] as string
488 if (past || !a.startsWith('-')) {
489 const p = absOf(a, dir)
490 if (p !== undefined) call.pathspecs.push(p)
491 } else if (a === '--') past = true
492 else if (a === '--all') call.all = true
493 else if (a === '--amend') call.amend = true
494 else if (COMMIT_VALUE_LONG.has(a)) m += 1
495 else if (!a.startsWith('--') && a.length > 1) {
496 for (let c = 1; c < a.length; c++) {
497 const ch = a[c] as string
498 if (ch === 'a') call.all = true
499 else if (COMMIT_VALUE_SHORT.includes(ch)) {
500 if (c === a.length - 1) m += 1
501 break
502 }
503 }
504 }
505 }
506 commits.push(call)
507 }
508 } else if (cmd === 'tee') {
509 for (const p of plain) add(p, cwd)
510 } else if (cmd === 'sed' || cmd === 'gsed') {
511 const inPlace = args.some(a => a.startsWith('--in-place') || /^-[A-Za-z]*i/.test(a))
512 if (inPlace) {
513 // BSD: `-i ''` / `-i .bak` take the next word as the backup suffix
514 const suffixAt = args.findIndex((a, n) => /^-[A-Za-z]*i$/.test(a) && n + 1 < args.length && BSD_SUFFIX.test(args[n + 1] as string))
515 const rest = args.filter((_, n) => suffixAt < 0 || n !== suffixAt + 1)
516 const restPlain = rest.filter(a => !a.startsWith('-'))
517 const scripted = rest.some(a => a === '-e' || a === '-f' || a.startsWith('--expression') || a.startsWith('--file'))
518 const eArg = rest.reduce<string[]>((acc, a, j) => (a === '-e' || a === '-f' ? [...acc, rest[j + 1] as string] : acc), [])
519 const files = restPlain.filter(a => !eArg.includes(a))
520 for (const p of scripted ? files : files.slice(1)) add(p, cwd)
521 }
522 } else if (cmd === 'cp' || cmd === 'mv' || cmd === 'install') {
523 const t = args.findIndex(a => a === '-t' || a === '--target-directory')
524 if (t >= 0) add(args[t + 1], cwd)
525 else add(plain.at(-1), cwd)
526 }
527 if (seg.after === '(' || seg.after === '$(') stack.push(cwd)
528 else if (seg.after === '`') {
529 if (ticks) cwd = stack.pop()
530 else stack.push(cwd)
531 ticks = !ticks
532 } else if (seg.after === ')' && stack.length > 0) cwd = stack.pop()
533 }
534 return { paths: out, commits }
535}
536
537/** The files a Bash command writes under the root, and whether it runs `git commit` in the root's repo. */
538export function bashWrites(command: string, root: string, home?: string): { paths: string[]; commit: boolean } {
539 const r = scan(command, root, home)
540 return { paths: r.paths, commit: r.commits.length > 0 }
541}
542
543/** MOD-9: the `git commit`s a command runs in the root's repo (the cwd in force after any cd, or the `-C` folder); one in a repo outside the root, or in an unknown folder, is not listed. */
544export const bashCommits = (command: string, root: string, home?: string): CommitCall[] => scan(command, root, home).commits
545hooks/lib/pane.tsx 310 lines1// Part 4B: the Delegation pane, as a tree. Opened only by the band's
2// `[ details ]`, `/delegation`, or the status tool with `open: true`. Six
3// blocks (a heading, this session's number line, a sparkline over the last 14
4// sessions), then "Open items", then `[ close ]`, the one control. Sparklines
5// are an Svg on vscode, desktop and mobile and a Raster on the terminal, which
6// has no Svg. No `$` here: register.ts resolves the table and hands in the
7// close handler.
8import type { Elements, RenderNode } from 'claude-code'
9
10import type { DashboardBlock } from '../types'
11import { sparkCells, sparkSvg, sparkValues } from './dashboard'
12import type { BrainSummary } from './brain'
13import { brainTileText } from './brain'
14import type { DaySegment } from './ration'
15import { brainModelLabel, chartCells, chartSvg, FABLE_COLOR, modelColor, modelLabel, tokText, verdictMark, type LiveView, type Scheme, type WorktreeRow } from './live'
16
17/** The surface's table, narrowed: the terminal draws a Raster, the rest an Svg. */
18export type PaneTable =
19 | { surface: 'terminal'; t: Elements['terminal'] }
20 | { surface: 'desktop'; t: Elements['desktop'] }
21 | { surface: 'vscode'; t: Elements['vscode'] }
22 | { surface: 'mobile'; t: Elements['mobile'] }
23
24export type PaneView = {
25 blocks: readonly DashboardBlock[]
26 /** Every item the band would show, with its next action. */
27 open: readonly string[]
28 /** The pane body's width in cells (`e.props.bodyColumns`). */
29 columns: number
30 /** GH-112: the live model; absent, the pane draws only the cross-session blocks. */
31 live?: LiveView
32 scheme?: Scheme
33 /** MOD-128: the rationing bar drawn under the Spend tile. `cells` is one entry per day of a seven-day window. */
34 ration?: { cells?: readonly DaySegment[]; text: string; bar: string; /** MOD-133: the `today 6.2/8.4 · on pace` clauses the band adds after `text`. */ tail?: string }
35}
36
37/** MOD-128: a day's colour in the ration bar: green under its share, yellow within 10% over, red over; the day in progress takes the scheme's accent. */
38export const RATION_COLOR = { under: '#0ca30c', near: '#fab219', over: '#d03b3b' } as const
39export const RATION_ACCENT: Record<Scheme, string> = { light: '#2f6fd6', dark: '#6ea2f0' }
40
41/** MOD-128: one Box per day, each three cells wide, then the words beside the bar. */
42export function rationBar(p: PaneTable, r: NonNullable<PaneView['ration']>, scheme: Scheme, indent = INDENT, text = r.text): RenderNode {
43 const { Box, Text } = p.t
44 return (
45 <Box key="dash-ration" flexDirection="row" gap={1} paddingLeft={indent}>
46 {r.cells ? (
47 <Box flexDirection="row">
48 {r.cells.map((c, i) => {
49 const key = `ration-cell-${i + 1}`
50 if (!c.known && c.state !== 'today' && c.state !== 'future') {
51 return (
52 <Box key={key} width={3}>
53 <Text dimColor>░?░</Text>
54 </Box>
55 )
56 }
57 if (c.state === 'future') {
58 return (
59 <Box key={key} width={3}>
60 <Text dimColor>███</Text>
61 </Box>
62 )
63 }
64 if (c.state === 'today') {
65 const filled = c.share > 0 ? Math.min(3, Math.max(0, Math.round((c.used / c.share) * 3))) : 0
66 return (
67 <Box key={key} width={3}>
68 <Text color={RATION_ACCENT[scheme]}>{'█'.repeat(filled) + '░'.repeat(3 - filled)}</Text>
69 </Box>
70 )
71 }
72 return (
73 <Box key={key} width={3}>
74 <Text color={RATION_COLOR[c.state]}>███</Text>
75 </Box>
76 )
77 })}
78 </Box>
79 ) : (
80 <Text>{r.bar}</Text>
81 )}
82 <Text wrap="truncate-end">{text}</Text>
83 </Box>
84 )
85}
86
87const INDENT = 2
88
89function spark(p: PaneTable, b: DashboardBlock, columns: number): RenderNode {
90 const { Text } = p.t
91 const shown = sparkValues(b.series)
92 if (shown.length === 0) return <Text>{' '.repeat(INDENT)}no sessions measured yet</Text>
93 const alt = `${b.alt}, last ${shown.length} session${shown.length === 1 ? '' : 's'}: ${shown.map(v => +v.toFixed(2)).join(', ')}`
94 if (p.surface === 'terminal') {
95 const cells = sparkCells(b.series)
96 if (!cells) return <Text>{' '.repeat(INDENT)}no sessions measured yet</Text>
97 const { Box, Raster } = p.t
98 return (
99 <Box flexDirection="row" paddingLeft={INDENT}>
100 <Raster key={`spark-${b.key}`} columns={cells.columns} rows={1} cells={cells.cells} />
101 </Box>
102 )
103 }
104 const svg = sparkSvg(b.series, Math.max(1, columns - INDENT))
105 if (!svg) return <Text>{' '.repeat(INDENT)}no sessions measured yet</Text>
106 const { Box, Svg } = p.t
107 return (
108 <Box flexDirection="row" paddingLeft={INDENT}>
109 <Svg source={svg.source} alt={alt} width={svg.width} height={svg.height} />
110 </Box>
111 )
112}
113
114// ---- GH-112: the live blocks, drawn by the band's card (the first three, compact) and the pane (all four) ----
115
116const pad = (text: string, w: number) => (text.length >= w ? text.slice(0, Math.max(0, w - 1)) + (text.length > w ? '…' : '') : text.padEnd(w))
117const usdCell = (n: number | undefined) => (n === undefined ? '$–' : `$${n.toFixed(2)}`)
118
119/** Stat tiles: live workers, queued, spend this session (the hero), consistent on first attempt. */
120function kpiRow(p: PaneTable, v: LiveView): RenderNode {
121 const { Box, Text } = p.t
122 const tile = (key: string, label: string, value: string, hero?: boolean) => (
123 <Box key={key} flexDirection="column" borderStyle="round" paddingX={1}>
124 <Text dimColor>{label}</Text>
125 <Text bold>{value}</Text>
126 {hero ? <Text dimColor>whole session</Text> : null}
127 </Box>
128 )
129 return (
130 <Box key="dash-kpis" flexDirection="row" gap={1}>
131 {tile('kpi-live', 'live', String(v.live))}
132 {tile('kpi-queued', 'queued', String(v.queued))}
133 {tile('kpi-spend', 'spend', `$${v.usd.toFixed(2)}`, true)}
134 {tile('kpi-first', 'consistent 1st try', `${v.firstTry.n} of ${v.firstTry.m}`)}
135 {v.brain ? tile('kpi-brain', 'spend split', brainTileText(v.brain)) : null}
136 </Box>
137 )
138}
139
140/** Cumulative session dollars over time: an Svg line on desktop, vscode and mobile; a Raster on the terminal. */
141function spendChart(p: PaneTable, v: LiveView, columns: number): RenderNode {
142 const { Box, Text } = p.t
143 const alt = `Session spend over time: $${v.usd.toFixed(2)} now, ${v.series.length} samples, ${v.events.length} spawn and verdict ticks`
144 let chart: RenderNode = <Text dimColor>collecting samples…</Text>
145 if (p.surface === 'terminal') {
146 const c = chartCells(v.series, v.events, v.now, Math.max(8, columns - 2))
147 if (c) {
148 const { Raster } = p.t
149 chart = <Raster key="spend-raster" columns={c.columns} rows={c.rows} cells={c.cells} />
150 }
151 } else {
152 const svg = chartSvg(v.series, v.events, v.now, Math.max(8, columns - 2))
153 if (svg) {
154 const { Svg } = p.t
155 chart = <Svg source={svg.source} alt={alt} width={svg.width} height={svg.height} isInteractive />
156 }
157 }
158 return (
159 <Box key="dash-spend" flexDirection="column">
160 <Text bold>Spend over time</Text>
161 <Text dimColor>cumulative dollars, this session · ticks: spawn ┬ verdict ┴ · hover for time, $ and event</Text>
162 {chart}
163 </Box>
164 )
165}
166
167function stateCell(p: PaneTable, r: WorktreeRow, w: number): RenderNode {
168 const { Box, Text } = p.t
169 const mark = verdictMark(r.verdict)
170 return (
171 <Box flexDirection="row" width={w}>
172 {mark ? <Text color={mark.color}>{mark.icon} </Text> : null}
173 <Text wrap="truncate-end">{r.state}</Text>
174 </Box>
175 )
176}
177
178/** One row per task: task · model (a chip in the model's colour, its name in ink) · state · worktree · tokens · cost · attempt. */
179function worktreeTable(p: PaneTable, v: LiveView, scheme: Scheme, columns: number, max: number): RenderNode {
180 const { Box, Text } = p.t
181 const rows = v.rows.slice(0, max)
182 const w = (f: (r: WorktreeRow) => string, floor: number, cap: number) => Math.min(cap, Math.max(floor, ...rows.map(r => [...f(r)].length)))
183 const taskW = w(r => r.task, 4, 14)
184 const modelW = w(r => (r.model === r.family || r.model === '–' ? r.family : `${r.family} ${r.model}`), 5, 28) + 2
185 const stateW = w(r => r.state, 5, 16) + 2
186 const folderW = w(r => (r.branch ? `${r.folder} ${r.branch}` : r.folder), 8, 40)
187 // MOD-23: a resource column appears while a worker holds a resource or a row waits for one
188 const anyRes = rows.some(r => r.resource !== undefined)
189 const resW = anyRes ? w(r => r.resource ?? '–', 8, 24) : 0
190 const wide = columns >= taskW + modelW + stateW + folderW + (anyRes ? resW + 1 : 0) + 26
191 return (
192 <Box key="dash-worktrees" flexDirection="column">
193 <Text bold>Worktrees</Text>
194 {rows.length === 0 ? <Text dimColor>no worker has run this session</Text> : null}
195 {rows.length > 0 ? (
196 <Box flexDirection="row">
197 <Text dimColor>{pad('task', taskW + 1)}</Text>
198 <Text dimColor>{pad('model', modelW + 1)}</Text>
199 <Text dimColor>{pad('state', stateW + 1)}</Text>
200 {wide ? <Text dimColor>{pad('worktree · branch', folderW + 1)}</Text> : null}
201 {anyRes ? <Text dimColor>{pad('resource', resW + 1)}</Text> : null}
202 <Text dimColor>{pad('tok', 7)}</Text>
203 <Text dimColor>{pad('cost', 8)}</Text>
204 <Text dimColor>att</Text>
205 </Box>
206 ) : null}
207 {rows.map(r => {
208 const c = modelColor(r.family, scheme)
209 const name = r.model === r.family || r.model === '–' ? r.family : `${r.family} ${r.model}`
210 return (
211 <Box flexDirection="row">
212 <Text wrap="truncate-end">{pad(r.task, taskW + 1)}</Text>
213 <Box flexDirection="row" width={modelW + 1}>
214 {c ? <Text color={c}>■ </Text> : <Text dimColor>■ </Text>}
215 <Text wrap="truncate-end">{name}</Text>
216 </Box>
217 {stateCell(p, r, stateW + 1)}
218 {wide ? <Text wrap="truncate-end">{pad(r.branch ? `${r.folder} ${r.branch}` : r.folder, folderW + 1)}</Text> : null}
219 {anyRes ? <Text wrap="truncate-end">{pad(r.resource ?? '–', resW + 1)}</Text> : null}
220 <Text>{pad(r.tokens === undefined ? '–' : tokText(r.tokens), 7)}</Text>
221 <Text>{pad(usdCell(r.usd), 8)}</Text>
222 <Text>{r.attempt}</Text>
223 </Box>
224 )
225 })}
226 {v.rows.length > max ? <Text dimColor>… {v.rows.length - max} more in the pane</Text> : null}
227 <Text dimColor>tokens and cost update when a run ends</Text>
228 </Box>
229 )
230}
231
232/** GH-113: the brain's own row, labelled `brain`, so a premium model's spend is never mistaken for a worker's. */
233function brainBar(p: PaneTable, b: BrainSummary, scheme: Scheme, top: number): RenderNode {
234 const { Box, Text } = p.t
235 const cells = b.brain > 0 ? Math.max(1, Math.round((b.brain / top) * 20)) : 0
236 const c = b.family === 'fable' ? FABLE_COLOR[scheme] : modelColor(b.family, scheme)
237 return (
238 <Box key="brain-row" flexDirection="row" gap={1}>
239 <Box width={20}>{c ? <Text color={c}>{'█'.repeat(cells)}</Text> : <Text dimColor>{'█'.repeat(cells)}</Text>}</Box>
240 <Text wrap="truncate-end">{brainModelLabel(b)}</Text>
241 </Box>
242 )
243}
244
245/** Up to three bars plus "other", each direct-labelled `sonnet · $3.10 · 412k tok · 4 consistent`. */
246function modelBars(p: PaneTable, v: LiveView, scheme: Scheme): RenderNode {
247 const { Box, Text } = p.t
248 const shown = v.byModel.filter(m => m.family !== 'other' || m.usd > 0 || m.tokens > 0)
249 const top = Math.max(0.0001, v.brain?.brain ?? 0, ...shown.map(m => m.usd))
250 return (
251 <Box key="dash-models" flexDirection="column">
252 <Text bold>Spend by model</Text>
253 {v.brain ? brainBar(p, v.brain, scheme, top) : null}
254 {shown.map(m => {
255 const c = modelColor(m.family, scheme)
256 const cells = m.usd > 0 ? Math.max(1, Math.round((m.usd / top) * 20)) : 0
257 return (
258 <Box flexDirection="row" gap={1}>
259 <Box width={20}>{c ? <Text color={c}>{'█'.repeat(cells)}</Text> : <Text dimColor>{'█'.repeat(cells)}</Text>}</Box>
260 <Text wrap="truncate-end">{modelLabel(m)}</Text>
261 </Box>
262 )
263 })}
264 </Box>
265 )
266}
267
268/** The card (compact: tiles, chart, worktrees) and the pane (all four) draw these. */
269export function liveBlocks(p: PaneTable, v: LiveView, scheme: Scheme, columns: number, full: boolean): RenderNode {
270 const { Box } = p.t
271 return (
272 <Box flexDirection="column" gap={1}>
273 {kpiRow(p, v)}
274 {spendChart(p, v, columns)}
275 {worktreeTable(p, v, scheme, columns, full ? 50 : 6)}
276 {full ? modelBars(p, v, scheme) : null}
277 </Box>
278 )
279}
280
281export function paneTree(p: PaneTable, view: PaneView, onClose: () => void): RenderNode {
282 const { Box, Text, Button } = p.t
283 const gap = ' '.repeat(INDENT)
284 return (
285 <Box flexDirection="column" gap={1}>
286 {view.live ? liveBlocks(p, view.live, view.scheme ?? 'dark', view.columns, true) : null}
287 <Text bold>Across sessions</Text>
288 {view.blocks.length === 0 ? <Text>No delegation measured yet.</Text> : null}
289 {view.blocks.map(b => (
290 <Box flexDirection="column">
291 <Text bold>{b.heading}</Text>
292 <Text wrap="truncate-end">{gap + b.number}</Text>
293 {b.detail.map(d => (
294 <Text wrap="truncate-end">{gap + d}</Text>
295 ))}
296 {spark(p, b, view.columns)}
297 {b.key === 'spend' && view.ration ? rationBar(p, view.ration, view.scheme ?? 'dark') : null}
298 </Box>
299 ))}
300 <Box flexDirection="column">
301 <Text bold>Open items</Text>
302 {view.open.length === 0 ? <Text>{gap}nothing open</Text> : view.open.map(o => <Text wrap="wrap">{gap + o}</Text>)}
303 </Box>
304 <Box flexDirection="row">
305 <Button key="close" label="close" role="dismiss" onPress={onClose} />
306 </Box>
307 </Box>
308 )
309}
310hooks/lib/live.ts 550 lines1// GH-112: the live delegation model behind the band and the pane. Pure: no `$`.
2// register.ts gathers the raw facts (the session cost, the attempt records, the
3// queue, `git worktree list --porcelain`) and hands them in; everything the
4// drawing shows is made here: the spend series, the events, the worktree rows,
5// spend by model, the chart geometry (an Svg source, or Raster cells).
6import type { AttemptRecord } from './attempts'
7import { taskLabel } from './attempts'
8import { base64, elapsed } from './dashboard'
9import { brainSummary, brainTileText, type AdHoc, type BrainRecord, type BrainSummary } from './brain'
10import { withRepoName, worktreePath } from './paths'
11
12// ---- the spend series -------------------------------------------------------------
13
14export type SpendPoint = { t: number; usd: number }
15export const SPEND_CAP = 240
16export const SAMPLE_LIVE_MS = 15_000
17export const SAMPLE_IDLE_MS = 60_000
18
19/** How often to sample the session's dollars: fast while a worker is live or queued, slow otherwise. */
20export const sampleEvery = (active: boolean): number => (active ? SAMPLE_LIVE_MS : SAMPLE_IDLE_MS)
21
22/** The series with one more sample, the last `cap` kept; a sample that is no finite number is dropped. */
23export function spendSeries(prev: readonly SpendPoint[] | undefined, point: SpendPoint, cap = SPEND_CAP): SpendPoint[] {
24 const list = Array.isArray(prev) ? prev : []
25 if (!Number.isFinite(point.usd) || !Number.isFinite(point.t)) return [...list]
26 return [...list, point].slice(-cap)
27}
28
29// ---- model families ---------------------------------------------------------------
30
31export type Family = 'haiku' | 'sonnet' | 'opus' | 'other'
32export const FAMILIES: readonly Family[] = ['haiku', 'sonnet', 'opus', 'other']
33
34/** The family of an alias or a resolved model id; anything not haiku, sonnet or opus is "other". */
35export function familyOf(model: string | undefined): Family {
36 const m = (model ?? '').toLowerCase()
37 if (m.includes('haiku')) return 'haiku'
38 if (m.includes('sonnet')) return 'sonnet'
39 if (m.includes('opus')) return 'opus'
40 return 'other'
41}
42
43const recordFamily = (r: Pick<AttemptRecord, 'alias' | 'resolvedModel'>): Family => {
44 const f = familyOf(r.alias)
45 return f === 'other' ? familyOf(r.resolvedModel) : f
46}
47
48const round4 = (n: number) => Math.round(n * 10000) / 10000
49
50export type ModelSpend = { family: Family; usd: number; tokens: number; consistent: number }
51
52/** Dollars and tokens per family from the records' own spend, and how many cards each came back consistent. */
53export function spendByModel(records: readonly AttemptRecord[]): ModelSpend[] {
54 const out = new Map<Family, { usd: number; tokens: number; cards: Set<string> }>(FAMILIES.map(f => [f, { usd: 0, tokens: 0, cards: new Set<string>() }]))
55 for (const r of records) {
56 const row = out.get(recordFamily(r)) as { usd: number; tokens: number; cards: Set<string> }
57 row.usd += r.usd ?? 0
58 row.tokens += r.tokens ?? 0
59 if (r.verdict === 'consistent') row.cards.add(taskLabel(r.task, r.subtask))
60 }
61 return FAMILIES.map(family => {
62 const row = out.get(family) as { usd: number; tokens: number; cards: Set<string> }
63 return { family, usd: round4(row.usd), tokens: row.tokens, consistent: row.cards.size }
64 })
65}
66
67/** MOD-37: who is asking: this session's id and root. */
68export type Who = { sessionId?: string; root?: string }
69
70/**
71 * Records of this session. With a session id: a record carries the id of the session that made it and is kept when it
72 * equals ours; one without (written before MOD-37) is kept only when its root is ours and it began at or after `since`.
73 * With no id known, the time alone decides.
74 */
75export function sessionRecords(records: readonly AttemptRecord[], since: number, who?: Who): AttemptRecord[] {
76 if (!who?.sessionId) return records.filter(r => r.at >= since)
77 return records.filter(r => {
78 if (r.sessionId !== undefined) return r.sessionId === who.sessionId
79 return r.at >= since && who.root !== undefined && who.root !== '' && (r.root ?? (r as { here?: string }).here) === who.root
80 })
81}
82
83// ---- events -----------------------------------------------------------------------
84
85export type LiveEvent = { t: number; kind: 'spawn' | 'verdict'; task: string; family: Family; verdict?: string }
86
87/** Spawn and verdict times this session, oldest first (a spawn before a verdict at the same time). */
88export function events(records: readonly AttemptRecord[], since: number): LiveEvent[] {
89 const out: LiveEvent[] = []
90 for (const r of records) {
91 if (r.at < since || r.kind === 'verify') continue
92 const task = taskLabel(r.task, r.subtask)
93 const family = recordFamily(r)
94 out.push({ t: r.at, kind: 'spawn', task, family })
95 if (r.verdict !== 'pending' && r.verdictAt !== undefined) out.push({ t: r.verdictAt, kind: 'verdict', task, family, verdict: r.verdict })
96 }
97 return out.sort((a, b) => a.t - b.t || (a.kind === b.kind ? 0 : a.kind === 'spawn' ? -1 : 1))
98}
99
100// ---- verdict marks and colours ----------------------------------------------------
101
102export type Scheme = 'light' | 'dark'
103
104/** Light or dark from what the render input reports of the surface; dark when it reports none. */
105export function pickScheme(e: unknown): Scheme {
106 const seen = (o: unknown): string | undefined => {
107 if (!o || typeof o !== 'object') return undefined
108 for (const k of ['colorScheme', 'theme', 'scheme', 'appearance']) {
109 const v = (o as Record<string, unknown>)[k]
110 if (typeof v === 'string') return v.toLowerCase()
111 }
112 return undefined
113 }
114 const v = seen(e) ?? seen((e as { props?: unknown } | undefined)?.props) ?? seen((e as { viewport?: unknown } | undefined)?.viewport)
115 return v?.includes('light') ? 'light' : 'dark'
116}
117
118/** A model family's chip colour; "other" has none (the surface's secondary ink). */
119export const MODEL_COLORS: Record<Exclude<Family, 'other'>, Record<Scheme, string>> = {
120 haiku: { light: '#2a78d6', dark: '#3987e5' },
121 sonnet: { light: '#eb6834', dark: '#d95926' },
122 opus: { light: '#1baf7a', dark: '#199e70' },
123}
124/** The brain's colour on a premium model (GH-113). */
125export const FABLE_COLOR: Record<Scheme, string> = { light: '#7c4dcc', dark: '#9a73e0' }
126export const modelColor = (family: Family, scheme: Scheme): string | undefined => (family === 'other' ? undefined : MODEL_COLORS[family][scheme])
127
128export const SURFACE: Record<Scheme, string> = { light: '#fcfcfb', dark: '#1a1a19' }
129
130export type Mark = { icon: string; color: string; word: string }
131
132/** Verdict status: an icon, a colour and the word, never a colour alone. Undefined for a state that is no verdict. */
133export function verdictMark(verdict: string | undefined): Mark | undefined {
134 switch (verdict) {
135 case 'consistent':
136 return { icon: '✓', color: '#0ca30c', word: 'consistent' }
137 case 'unverified':
138 case 'over-spend':
139 return { icon: '!', color: '#fab219', word: verdict }
140 case 'refuted':
141 case 'no-report':
142 case 'refused':
143 return { icon: '✗', color: '#d03b3b', word: verdict }
144 default:
145 return undefined
146 }
147}
148
149// ---- the worktree rows ------------------------------------------------------------
150
151export type RowKind = 'live' | 'queued' | 'verdict' | 'owed' | 'disk'
152export type WorktreeRow = {
153 task: string
154 family: Family
155 /** The resolved model id when the record has one, else the alias. */
156 model: string
157 state: string
158 kind: RowKind
159 verdict?: string
160 /** The worktree's folder name, or an en dash when it has none on disk. */
161 folder: string
162 branch: string
163 tokens?: number
164 usd?: number
165 /** `n/b`: the latest attempt over the budget. */
166 attempt: string
167 /** MOD-23: the resources a live worker holds (`blender-live`), or what a queued row waits for (`waits blender-live`); absent when neither. */
168 resource?: string
169}
170
171export type WorktreeInput = {
172 root: string
173 worktreeRoot?: string
174 /** `git worktree list --porcelain`. */
175 porcelain: string
176 /** This session's attempt records, all tasks. */
177 records: readonly AttemptRecord[]
178 /** Queued spawns, front first. */
179 queue: readonly { task: string; subtask?: string; /** MOD-44: the other local repo the queued task is for. */ repo?: string }[]
180 /** Task label to the ms since the epoch its live worker started or resumed. */
181 liveAt: Readonly<Record<string, number>>
182 now: number
183 /** The attempt budget shown after the slash. */
184 budget: number
185 /** MOD-23: task label to the resources its live worker holds. */
186 holds?: Readonly<Record<string, readonly string[]>>
187 /** MOD-23: task label to the resource a queued row waits for and who holds it. */
188 waits?: Readonly<Record<string, { resource: string; holder: string }>>
189}
190
191/** The worktrees `git worktree list --porcelain` names: path and branch. */
192export function parsePorcelain(text: string): { path: string; branch: string }[] {
193 const out: { path: string; branch: string }[] = []
194 for (const block of text.split(/\n\s*\n/)) {
195 let path = ''
196 let branch = ''
197 for (const line of block.split('\n')) {
198 if (line.startsWith('worktree ')) path = line.slice('worktree '.length).trim()
199 else if (line.startsWith('branch ')) branch = line.slice('branch '.length).trim().replace(/^refs\/heads\//, '')
200 }
201 if (path) out.push({ path, branch })
202 }
203 return out
204}
205
206const base = (p: string) => p.slice(p.lastIndexOf('/') + 1)
207
208/** One row per task this session, per queued task, and per worktree on disk under the mod's naming. */
209export function worktreeRows(input: WorktreeInput): WorktreeRow[] {
210 const prefix = worktreePath(input.root, '', false, input.worktreeRoot)
211 const disk = new Map<string, { path: string; branch: string }>()
212 for (const w of parsePorcelain(input.porcelain)) {
213 if (!w.path.startsWith(prefix) || w.path.length === prefix.length) continue
214 disk.set(w.path.slice(prefix.length).replace(/-replay$/, ''), w)
215 }
216 const byLabel = new Map<string, AttemptRecord[]>()
217 for (const r of [...input.records].sort((a, b) => a.at - b.at)) {
218 const label = taskLabel(r.task, r.subtask)
219 byLabel.set(label, [...(byLabel.get(label) ?? []), r])
220 }
221 const queued = input.queue.map(q => taskLabel(q.task, q.subtask ?? 'main'))
222 const queuedRepo = new Map(input.queue.filter(q => q.repo !== undefined).map(q => [taskLabel(q.task, q.subtask ?? 'main'), q.repo as string]))
223 const rows: WorktreeRow[] = []
224 const seen = new Set<string>()
225 const labels = [...byLabel.keys(), ...queued.filter(l => !byLabel.has(l))]
226 for (const label of labels) {
227 seen.add(label)
228 const recs = byLabel.get(label) ?? []
229 const latest = recs.reduce<AttemptRecord | undefined>((a, r) => (a === undefined || r.attempt >= a.attempt ? r : a), undefined)
230 const id = (latest?.task ?? label.split('/')[0]) as string
231 const wt = disk.get(id)
232 const usds = recs.flatMap(r => (r.usd === undefined ? [] : [r.usd]))
233 const toks = recs.flatMap(r => (r.tokens === undefined ? [] : [r.tokens]))
234 const resolved = [...recs].reverse().find(r => r.resolvedModel)?.resolvedModel
235 const q = queued.indexOf(label)
236 let state: string
237 let kind: RowKind
238 let verdict: string | undefined
239 if (input.liveAt[label] !== undefined) {
240 state = `live ${elapsed(input.now - (input.liveAt[label] as number))}`
241 kind = 'live'
242 } else if (q >= 0) {
243 state = `queued #${q + 1}`
244 kind = 'queued'
245 } else if (latest && latest.verdict !== 'pending') {
246 state = latest.verdict
247 kind = 'verdict'
248 verdict = state
249 } else {
250 state = 'verdict owed'
251 kind = 'owed'
252 }
253 // MOD-23: a live worker names the resources it holds; a queued row, the resource it waits for
254 const held = kind === 'live' ? (input.holds?.[label] ?? []) : []
255 const waiting = kind === 'queued' ? input.waits?.[label] : undefined
256 const resource = held.length > 0 ? held.join(', ') : waiting ? `waits ${waiting.resource}` : undefined
257 rows.push({
258 // MOD-44: a task for another local repo shows that repo's folder name beside it
259 task: withRepoName(label, latest?.root ?? queuedRepo.get(label), input.root),
260 family: latest ? recordFamily(latest) : 'other',
261 model: latest ? (resolved ?? latest.alias) : '–',
262 state,
263 kind,
264 ...(verdict ? { verdict } : {}),
265 folder: wt ? base(wt.path) : '–',
266 branch: wt?.branch ?? '',
267 ...(toks.length > 0 ? { tokens: toks.reduce((a, b) => a + b, 0) } : {}),
268 ...(usds.length > 0 ? { usd: round4(usds.reduce((a, b) => a + b, 0)) } : {}),
269 attempt: `${latest?.attempt ?? 0}/${input.budget}`,
270 ...(resource !== undefined ? { resource } : {}),
271 })
272 }
273 for (const [id, wt] of disk) {
274 if (seen.has(id) || [...seen].some(l => l.split('/')[0] === id)) continue
275 rows.push({ task: id, family: 'other', model: '–', state: 'on disk', kind: 'disk', folder: base(wt.path), branch: wt.branch, attempt: `0/${input.budget}` })
276 }
277 const rank: Record<RowKind, number> = { live: 0, owed: 1, queued: 2, verdict: 3, disk: 4 }
278 return rows.map((r, i) => ({ r, i })).sort((a, b) => rank[a.r.kind] - rank[b.r.kind] || a.i - b.i).map(x => x.r)
279}
280
281// ---- the view both drawings read --------------------------------------------------
282
283export type LiveView = {
284 now: number
285 live: number
286 queued: number
287 owed: number
288 usd: number
289 series: SpendPoint[]
290 events: LiveEvent[]
291 rows: WorktreeRow[]
292 byModel: ModelSpend[]
293 firstTry: { n: number; m: number }
294 /** GH-113: the brain's own spend beside the workers'; absent before the brain's first turn. */
295 brain?: BrainSummary
296 /** MOD-81: the live workers as the status line named them (`T-1 $0.42`), and the context percent; absent while unknown. */
297 labels?: string[]
298 ctx?: number
299}
300
301/** Cards judged on their first attempt this session: how many came back consistent. */
302export function firstTry(records: readonly AttemptRecord[]): { n: number; m: number } {
303 const first = new Map<string, AttemptRecord>()
304 for (const r of records) if (r.attempt === 1 && r.kind !== 'verify') first.set(taskLabel(r.task, r.subtask), r)
305 const judged = [...first.values()].filter(r => r.verdict !== 'pending')
306 return { n: judged.filter(r => r.verdict === 'consistent').length, m: judged.length }
307}
308
309export type ViewInput = WorktreeInput & { since: number; usd: number; series: readonly SpendPoint[]; owed: number; labels?: readonly string[]; ctx?: number; brain?: BrainRecord; sessionId?: string; adhoc?: AdHoc }
310
311export function liveView(i: ViewInput): LiveView {
312 const records = sessionRecords(i.records, i.since, { ...(i.sessionId ? { sessionId: i.sessionId } : {}), root: i.root })
313 return {
314 now: i.now,
315 live: Object.keys(i.liveAt).length,
316 queued: i.queue.length,
317 owed: i.owed,
318 ...(i.labels ? { labels: [...i.labels] } : {}),
319 ...(i.ctx !== undefined ? { ctx: i.ctx } : {}),
320 usd: i.usd,
321 series: [...i.series],
322 events: events(records, i.since),
323 rows: worktreeRows({ ...i, records }),
324 byModel: spendByModel(records),
325 firstTry: firstTry(records),
326 ...(i.brain && i.brain.turns > 0 ? { brain: brainSummary(i.brain, workersUsd(records), attempts(records), i.usd > 0 ? i.usd : undefined, i.adhoc) } : {}),
327 }
328}
329
330/** MOD-37: a hand-back with no card, recorded under its report's task: counted as ad hoc, not as a worker. */
331const isAdHoc = (r: AttemptRecord): boolean => (r as { adhoc?: boolean }).adhoc === true
332
333/** Dollars the session's worker attempts spent (the brain's own turns are not among them). */
334export const workersUsd = (records: readonly AttemptRecord[]): number => round4(records.filter(r => !isAdHoc(r)).reduce((a, r) => a + (r.usd ?? 0), 0))
335
336/** Worker attempts this session (a verify pass is no attempt). */
337export const attempts = (records: readonly AttemptRecord[]): number => records.filter(r => r.kind !== 'verify' && !isAdHoc(r)).length
338
339/** The band shows while a worker is live, a spawn is queued or a verdict is owed. */
340export const isActive = (v: Pick<LiveView, 'live' | 'queued' | 'owed'>): boolean => v.live + v.queued + v.owed > 0
341
342// ---- the band's line --------------------------------------------------------------
343
344const dollars = (n: number) => `$${n.toFixed(2)}`
345
346export const ctxText = (pct: number | undefined): string => (pct === undefined ? 'ctx –' : `ctx ${Math.round(pct)}%`)
347
348/**
349 * MOD-81: `delegation · 2 live: OPS-165, OPS-160 · 0 queued · $109.92 · ctx 11%`. When `room` (the columns the
350 * text may take) is short, the label list is cut with `…` first, so the dollars and the context stay.
351 */
352export function bandSummary(v: LiveView, room = Number.POSITIVE_INFINITY): string {
353 const tail = [`${v.queued} queued`, ...(v.owed > 0 ? [`${v.owed} owed`] : []), dollars(v.usd), ctxText(v.ctx)]
354 const head = (live: string) => ['delegation', live, ...tail].join(' · ')
355 const labels = (v.labels ?? []).join(', ')
356 if (v.live === 0 || !labels) return head(`${v.live} live`)
357 const full = head(`${v.live} live: ${labels}`)
358 if (full.length <= room) return full
359 const avail = room - head(`${v.live} live: `).length
360 return avail >= 2 ? head(`${v.live} live: ${labels.slice(0, avail - 1).trimEnd()}…`) : head(`${v.live} live`)
361}
362
363/** The last 30 minutes of cumulative dollars, thinned to at most `n` values: the band's sparkline. */
364export function recentSpend(series: readonly SpendPoint[], now: number, windowMs = 30 * 60_000, n = 14): number[] {
365 const inside = series.filter(p => p.t >= now - windowMs)
366 if (inside.length <= n) return inside.map(p => p.usd)
367 return Array.from({ length: n }, (_, i) => (inside[Math.round((i * (inside.length - 1)) / (n - 1))] as SpendPoint).usd)
368}
369
370/** `1.2k`, `412k`, `3.4M`. */
371export function tokText(n: number): string {
372 if (n >= 1_000_000) return `${+(n / 1_000_000).toFixed(1)}M`
373 if (n >= 1000) return `${Math.round(n / 100) / 10 >= 100 ? Math.round(n / 1000) : +(n / 1000).toFixed(1)}k`
374 return String(n)
375}
376
377/** `sonnet · $3.10 · 412k tok · 4 consistent`. */
378export const modelLabel = (m: ModelSpend): string => `${m.family} · ${dollars(m.usd)} · ${tokText(m.tokens)} tok · ${m.consistent} consistent`
379
380/** `brain · fable · $2.25 · 630k tok · 3 turns`: the brain's row of spend by model, labelled so Fable is never mistaken for a worker's. */
381export const brainModelLabel = (b: BrainSummary): string =>
382 `brain · ${b.family} · ${dollars(b.brain)}${b.unpriced ? '+' : ''} · ${tokText(b.tokens)} tok · ${b.turns} ${b.turns === 1 ? 'turn' : 'turns'}`
383
384// ---- the dashboard as text (a screen that shows no panes) --------------------------
385
386const BARS = '▁▂▃▄▅▆▇█'
387
388/** `▁▃▅█`: values scaled to eight glyph heights; empty under two values. */
389export function sparkText(values: readonly number[]): string {
390 if (values.length < 2) return ''
391 const lo = Math.min(...values)
392 const hi = Math.max(...values)
393 return values.map(v => BARS[hi === lo ? 0 : Math.round(((v - lo) / (hi - lo)) * 7)]).join('')
394}
395
396const cell = (s: string) => s.replace(/\|/g, '\\|')
397
398/**
399 * The dashboard as markdown, for a screen that shows no mod panes (the VS Code
400 * extension): the headline, the spend over the session, the worktree table and
401 * spend by model.
402 */
403export function dashboardText(v: LiveView): string {
404 const ft = v.firstTry.m > 0 ? ` · ${v.firstTry.n} of ${v.firstTry.m} consistent on the first attempt` : ''
405 const lines = [`**Delegation** · ${v.live} live · ${v.queued} queued${v.owed > 0 ? ` · ${v.owed} owed` : ''} · ${dollars(v.usd)} this session · ${ctxText(v.ctx)}${ft}`]
406 const series = v.series
407 if (series.length >= 2) {
408 const first = series[0] as SpendPoint
409 const mins = Math.max(1, Math.round((v.now - first.t) / 60_000))
410 lines.push(`Spend: ${dollars(first.usd)} → ${dollars(v.usd)} over the last ${mins} min ${sparkText(recentSpend(series, v.now, Number.MAX_SAFE_INTEGER, 24))}`)
411 }
412 lines.push('')
413 if (v.rows.length === 0) lines.push('No worktrees or tasks this session.')
414 else {
415 // MOD-23: a Resource column appears while a worker holds a resource or a row waits for one
416 const res = v.rows.some(r => r.resource !== undefined)
417 lines.push(`| Task | Model | State | Worktree |${res ? ' Resource |' : ''} Tokens | Cost | Attempt |`, `| --- | --- | --- | --- |${res ? ' --- |' : ''} --- | --- | --- |`)
418 for (const r of v.rows) {
419 const mark = r.verdict ? verdictMark(r.verdict) : undefined
420 const state = mark ? `${mark.icon} ${r.state}` : r.state
421 const where = r.folder === '–' ? '–' : `${r.folder}${r.branch ? ` · ${r.branch}` : ''}`
422 lines.push(`| ${cell(r.task)} | ${cell(r.family === 'other' ? r.model : `${r.family} (${r.model})`)} | ${cell(state)} | ${cell(where)} |${res ? ` ${cell(r.resource ?? '–')} |` : ''} ${r.tokens !== undefined ? tokText(r.tokens) : '–'} | ${r.usd !== undefined ? dollars(r.usd) : '–'} | ${r.attempt} |`)
423 }
424 }
425 if (v.brain) lines.push('', `Spend split: ${brainTileText(v.brain)}${v.brain.edits > 0 ? ` · ${v.brain.edits} brain ${v.brain.edits === 1 ? 'edit' : 'edits'}` : ''}`)
426 if (v.byModel.length > 0 || v.brain) lines.push(...(v.brain ? [] : ['']), `By model: ${[...(v.brain ? [brainModelLabel(v.brain)] : []), ...v.byModel.map(modelLabel)].join('; ')}`)
427 lines.push('', 'Tokens and cost for a worker update when its run ends.')
428 return lines.join('\n')
429}
430
431// ---- the spend chart --------------------------------------------------------------
432
433type Geo = { t0: number; t1: number; max: number }
434const geo = (series: readonly SpendPoint[], now: number): Geo | undefined => {
435 if (series.length === 0) return undefined
436 const t0 = (series[0] as SpendPoint).t
437 const t1 = Math.max(now, (series.at(-1) as SpendPoint).t, t0 + 1)
438 return { t0, t1, max: Math.max(0.01, ...series.map(p => p.usd)) }
439}
440
441const esc = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
442const r1 = (n: number) => Math.round(n * 10) / 10
443const agoText = (ms: number) => (ms < 60_000 ? 'now' : `${Math.round(ms / 60_000)}m ago`)
444
445/** The nearest event to `t`, within `within` ms. */
446export function nearestEvent(evs: readonly LiveEvent[], t: number, within = 30_000): LiveEvent | undefined {
447 let best: LiveEvent | undefined
448 for (const e of evs) if (Math.abs(e.t - t) <= within && (best === undefined || Math.abs(e.t - t) < Math.abs(best.t - t))) best = e
449 return best
450}
451
452export const CHART_HEIGHT = 96
453const TICKS = 10
454
455/**
456 * The Svg: cumulative session dollars as a 2 px line over a light area in the
457 * surface's text ink (CanvasText: the total is no model's colour), 1 px event
458 * ticks on the time axis (short for a spawn, long for a verdict), no second y
459 * axis. Interactive: a crosshair and a tooltip (time, dollars so far, the
460 * nearest event) at the pointer, by `:hover` and `<title>`.
461 */
462export function chartSvg(series: readonly SpendPoint[], evs: readonly LiveEvent[], now: number, columns: number): { source: string; width: number; height: number } | undefined {
463 const g = geo(series, now)
464 if (!g) return undefined
465 const width = Math.max(8, Math.min(columns, 120)) * 8
466 const height = CHART_HEIGHT
467 const top = 6
468 const base = height - TICKS - 2
469 const x = (t: number) => r1(1 + ((t - g.t0) / (g.t1 - g.t0)) * (width - 2))
470 const y = (usd: number) => r1(base - (usd / g.max) * (base - top))
471 const pts = series.map(p => `${x(p.t)},${y(p.usd)}`)
472 const line = series.length === 1 ? `1,${y((series[0] as SpendPoint).usd)} ${width - 1},${y((series[0] as SpendPoint).usd)}` : pts.join(' ')
473 const area = `M1,${base} L${line.replace(/ /g, ' L')} L${series.length === 1 ? width - 1 : x((series.at(-1) as SpendPoint).t)},${base} Z`
474 const ticks = evs
475 .filter(e => e.t >= g.t0 && e.t <= g.t1)
476 .map(e => `<line x1="${x(e.t)}" x2="${x(e.t)}" y1="${base}" y2="${base + (e.kind === 'verdict' ? TICKS : TICKS / 2)}" stroke="currentColor" stroke-width="1"/>`)
477 .join('')
478 const step = series.length > 1 ? (width - 2) / (series.length - 1) : width
479 const hits = series
480 .map((p, i) => {
481 const ev = nearestEvent(evs, p.t)
482 const tip = `${agoText(now - p.t)} · ${dollars(p.usd)} so far${ev ? ` · ${ev.kind} ${ev.task} ${ev.family}${ev.verdict ? ` ${ev.verdict}` : ''}` : ''}`
483 return `<g class="h"><rect x="${r1(x(p.t) - step / 2)}" y="0" width="${r1(step)}" height="${height}" fill="transparent"/><line class="x" x1="${x(p.t)}" x2="${x(p.t)}" y1="${top}" y2="${base}" stroke="currentColor" stroke-width="1"/><title>${esc(tip)}</title></g>`
484 })
485 .join('')
486 const source =
487 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" color="CanvasText">` +
488 '<style>svg{color-scheme:light dark}.h .x{opacity:0}.h:hover .x{opacity:.6}</style>' +
489 `<path d="${area}" fill="currentColor" fill-opacity="0.12" stroke="none"/>` +
490 `<polyline points="${line}" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>` +
491 `<line x1="1" x2="${width - 1}" y1="${base}" y2="${base}" stroke="currentColor" stroke-width="1" stroke-opacity="0.4"/>` +
492 ticks +
493 hits +
494 '</svg>'
495 return { source, width, height }
496}
497
498const BLOCKS = ' ▁▂▃▄▅▆▇█'
499const DEFAULT_COLOUR = 0x01000000
500
501/**
502 * The terminal's chart: a Raster, one column per `columns`, `rows` high, the
503 * area under the line filled with block glyphs in the terminal's own ink, and
504 * one row of event ticks beneath (`┬` a spawn, `┴` a verdict). No Svg here.
505 */
506export function chartCells(series: readonly SpendPoint[], evs: readonly LiveEvent[], now: number, columns: number, rows = 4): { cells: string; columns: number; rows: number; glyphs: string[] } | undefined {
507 const g = geo(series, now)
508 if (!g) return undefined
509 const cols = Math.max(4, Math.min(columns, 120))
510 const total = rows + 1
511 const valueAt = (c: number): number => {
512 const t = g.t0 + (c / (cols - 1)) * (g.t1 - g.t0)
513 let v = 0
514 for (const p of series) if (p.t <= t) v = p.usd
515 return series.length === 1 || t < (series[0] as SpendPoint).t ? (series[0] as SpendPoint).usd : v
516 }
517 const grid: string[][] = Array.from({ length: total }, () => Array.from({ length: cols }, () => ' '))
518 for (let c = 0; c < cols; c++) {
519 const eighths = Math.round((valueAt(c) / g.max) * rows * 8)
520 for (let r = 0; r < rows; r++) {
521 const fill = Math.max(0, Math.min(8, eighths - (rows - 1 - r) * 8))
522 ;(grid[r] as string[])[c] = BLOCKS[fill] as string
523 }
524 }
525 for (const e of evs) {
526 if (e.t < g.t0 || e.t > g.t1) continue
527 const c = Math.min(cols - 1, Math.round(((e.t - g.t0) / (g.t1 - g.t0)) * (cols - 1)))
528 const cur = (grid[rows] as string[])[c]
529 ;(grid[rows] as string[])[c] = e.kind === 'verdict' || cur === '┴' ? '┴' : '┬'
530 }
531 const glyphs = grid.map(r => r.join(''))
532 const words = new Uint32Array(cols * total * 3)
533 grid.forEach((row, r) =>
534 row.forEach((ch, c) => {
535 const i = (r * cols + c) * 3
536 words[i] = ch.codePointAt(0) as number
537 words[i + 1] = DEFAULT_COLOUR
538 words[i + 2] = DEFAULT_COLOUR
539 }),
540 )
541 const bytes = new Uint8Array(words.length * 4)
542 words.forEach((w, i) => {
543 bytes[i * 4] = w & 0xff
544 bytes[i * 4 + 1] = (w >>> 8) & 0xff
545 bytes[i * 4 + 2] = (w >>> 16) & 0xff
546 bytes[i * 4 + 3] = (w >>> 24) & 0xff
547 })
548 return { cells: base64(bytes), columns: cols, rows: total, glyphs }
549}
550hooks/lib/metrics.ts 221 lines1// Part 4C: the dashboard's per-session numbers, `delegation.metrics.<sessionId>`
2// in the store, updated by the hooks that already handle each event, and the
3// six series the pane's sparklines draw over the last 14 sessions. Pure: no `$`.
4import { RETIRED_VERDICT, readVerdict } from './attempts'
5import { aliasOf } from './tier'
6
7type ByAlias = { haiku: number; sonnet: number; opus: number }
8
9export type Metrics = {
10 /** ms since the epoch when this session first counted anything. */
11 firstSeen: number
12 /** Dispatches made through the `dispatch` tool or `/dispatch` (spawned or queued). */
13 dispatches: number
14 verdicts: { consistent: number; unverified: number; refuted: number; falseRefuted: number }
15 /** Briefed spawns by alias. */
16 spawns: ByAlias
17 escalations: { resume: number; respawn: number }
18 /** Background debriefs started. */
19 debriefs: number
20 evals: { run: number; failed: number }
21 /** `session.compact` hooks served (the state block attached). */
22 compactions: number
23 /** Dollars the briefed workers spent (3B), summed as their turns complete. */
24 usd: number
25 /** Consistent verdicts by alias: which tiers proved enough (the Tiers sparkline). */
26 consistentBy: ByAlias
27}
28
29export const emptyMetrics = (firstSeen: number): Metrics => ({
30 firstSeen,
31 dispatches: 0,
32 verdicts: { consistent: 0, unverified: 0, refuted: 0, falseRefuted: 0 },
33 spawns: { haiku: 0, sonnet: 0, opus: 0 },
34 escalations: { resume: 0, respawn: 0 },
35 debriefs: 0,
36 evals: { run: 0, failed: 0 },
37 compactions: 0,
38 usd: 0,
39 consistentBy: { haiku: 0, sonnet: 0, opus: 0 },
40})
41
42export type MetricEvent =
43 | { kind: 'dispatch' }
44 | { kind: 'spawn'; alias: string; respawn?: boolean }
45 | { kind: 'resume' }
46 | { kind: 'verdict'; verdict: string; alias: string; falseRefute?: boolean }
47 | { kind: 'debrief' }
48 | { kind: 'eval' }
49 | { kind: 'eval-failed' }
50 | { kind: 'compaction' }
51 | { kind: 'usd'; usd: number }
52
53const tierKey = (alias: string): keyof ByAlias | undefined => {
54 const a = aliasOf(alias)
55 return a === 'haiku' || a === 'sonnet' || a === 'opus' ? a : undefined
56}
57
58/** A metrics object written before the rename (MOD-19): its retired-word counts fold into `consistent`; an object already in the new shape is returned as it was. */
59function foldRetired(stored: unknown): unknown {
60 if (typeof stored !== 'object' || stored === null || Array.isArray(stored)) return stored
61 const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
62 const count = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
63 const BY = `${RETIRED_VERDICT}By`
64 const out: Record<string, unknown> = { ...(stored as Record<string, unknown>) }
65 const verdicts = out.verdicts
66 if (isRecord(verdicts) && RETIRED_VERDICT in verdicts) {
67 const { [RETIRED_VERDICT]: old, ...rest } = verdicts
68 out.verdicts = { ...rest, consistent: count(rest.consistent) + count(old) }
69 }
70 const by = out[BY]
71 if (by !== undefined) {
72 delete out[BY]
73 if (isRecord(by)) {
74 const now: Record<string, unknown> = isRecord(out.consistentBy) ? out.consistentBy : {}
75 const merged: Record<string, number> = {}
76 for (const k of new Set([...Object.keys(by), ...Object.keys(now)])) merged[k] = count(now[k]) + count(by[k])
77 out.consistentBy = merged
78 }
79 }
80 return out
81}
82
83/**
84 * A stored object read back whole: fields an older release did not write start
85 * at zero, and one written before the rename (MOD-19, see foldRetired) folds
86 * its counts into `consistent`.
87 */
88export function fillMetrics(stored: Partial<Metrics> | undefined, now: number): Metrics {
89 const m = foldRetired(stored) as Partial<Metrics> | undefined
90 const base = emptyMetrics(m?.firstSeen ?? now)
91 if (!m) return base
92 return {
93 ...base,
94 ...m,
95 verdicts: { ...base.verdicts, ...m.verdicts },
96 spawns: { ...base.spawns, ...m.spawns },
97 escalations: { ...base.escalations, ...m.escalations },
98 evals: { ...base.evals, ...m.evals },
99 consistentBy: { ...base.consistentBy, ...m.consistentBy },
100 }
101}
102
103/** One event applied to the session's metrics (created at `now` when absent). */
104export function applyMetric(prev: Partial<Metrics> | undefined, ev: MetricEvent, now: number): Metrics {
105 const m = fillMetrics(prev, now)
106 switch (ev.kind) {
107 case 'dispatch':
108 return { ...m, dispatches: m.dispatches + 1 }
109 case 'spawn': {
110 const k = tierKey(ev.alias)
111 const spawns = k ? { ...m.spawns, [k]: m.spawns[k] + 1 } : m.spawns
112 const escalations = ev.respawn ? { ...m.escalations, respawn: m.escalations.respawn + 1 } : m.escalations
113 return { ...m, spawns, escalations }
114 }
115 case 'resume':
116 return { ...m, escalations: { ...m.escalations, resume: m.escalations.resume + 1 } }
117 case 'verdict': {
118 const word = readVerdict(ev.verdict)
119 if (word !== 'consistent' && word !== 'unverified' && word !== 'refuted') return m
120 const verdicts = { ...m.verdicts, [word]: m.verdicts[word] + 1, falseRefuted: m.verdicts.falseRefuted + (ev.falseRefute ? 1 : 0) }
121 const k = tierKey(ev.alias)
122 const consistentBy = word === 'consistent' && k ? { ...m.consistentBy, [k]: m.consistentBy[k] + 1 } : m.consistentBy
123 return { ...m, verdicts, consistentBy }
124 }
125 case 'debrief':
126 return { ...m, debriefs: m.debriefs + 1 }
127 case 'eval':
128 return { ...m, evals: { ...m.evals, run: m.evals.run + 1 } }
129 case 'eval-failed':
130 return { ...m, evals: { ...m.evals, failed: m.evals.failed + 1 } }
131 case 'compaction':
132 return { ...m, compactions: m.compactions + 1 }
133 case 'usd':
134 return Number.isFinite(ev.usd) && ev.usd > 0 ? { ...m, usd: Math.round((m.usd + ev.usd) * 1e6) / 1e6 } : m
135 }
136}
137
138/**
139 * A refute that was false: a refuted attempt whose task later came back consistent at
140 * the SAME report sha (the code did not change; a resume or a re-verify by
141 * hand), or consistent because an amend made the difference.
142 */
143export function isFalseRefute(prev: { verdict: string; reportSha?: string } | undefined, cur: { verdict: string; reportSha?: string; amended: boolean }): boolean {
144 if (!prev || prev.verdict !== 'refuted' || cur.verdict !== 'consistent') return false
145 if (cur.amended) return true
146 return prev.reportSha !== undefined && prev.reportSha !== '' && prev.reportSha === cur.reportSha
147}
148
149/** `delegation.metricsIndex`: every session the metrics have counted, oldest first. */
150export type SessionIndex = { id: string; firstSeen: number }[]
151
152const INDEX_CAP = 200
153
154/** Notes a session once, in first-seen order (the oldest dropped past the cap). */
155export function noteSession(idx: SessionIndex, id: string, firstSeen: number): SessionIndex {
156 if (idx.some(s => s.id === id)) return idx
157 return [...idx, { id, firstSeen }].sort((a, b) => a.firstSeen - b.firstSeen).slice(-INDEX_CAP)
158}
159
160export const SPARK_SESSIONS = 14
161
162/** The ids of the last 14 sessions by first-seen time, oldest first. */
163export const lastSessions = (idx: SessionIndex, n = SPARK_SESSIONS): string[] =>
164 [...idx].sort((a, b) => a.firstSeen - b.firstSeen).slice(-n).map(s => s.id)
165
166const CHEAP_FIRST: (keyof ByAlias)[] = ['haiku', 'sonnet', 'opus']
167
168/**
169 * The six blocks' series, one value per session (`null` where the session
170 * has nothing to measure, so the line does not read a zero into it).
171 *
172 * Tiers: the share of the session's briefed spawns that went to the cheapest
173 * tier any of its verdicts were consistent on (all spawns on sonnet, sonnet
174 * consistent: 1; half on opus while sonnet was consistent: 0.5).
175 */
176export const SERIES: readonly { key: string; value: (m: Metrics) => number | null }[] = [
177 { key: 'steps', value: m => m.dispatches },
178 {
179 key: 'verdicts',
180 value: m => {
181 const total = m.verdicts.consistent + m.verdicts.unverified + m.verdicts.refuted
182 return total > 0 ? m.verdicts.refuted / total : null
183 },
184 },
185 {
186 key: 'tiers',
187 value: m => {
188 const cheapest = CHEAP_FIRST.find(k => m.consistentBy[k] > 0)
189 const total = m.spawns.haiku + m.spawns.sonnet + m.spawns.opus
190 return cheapest && total > 0 ? m.spawns[cheapest] / total : null
191 },
192 },
193 { key: 'owed', value: m => m.debriefs + m.evals.run },
194 { key: 'compaction', value: m => m.compactions },
195 { key: 'spend', value: m => m.usd },
196]
197
198/**
199 * GH-112: this session's numbers read from its attempt records (the dashboard's
200 * "Across sessions" blocks draw the current session from what the store holds).
201 */
202export function metricsFromRecords(
203 records: readonly { task: string; subtask: string; alias: string; kind: string; verdict: string; usd?: number }[],
204 firstSeen: number,
205): Metrics {
206 const m = emptyMetrics(firstSeen)
207 m.dispatches = new Set(records.map(r => `${r.task}/${r.subtask}`)).size
208 for (const r of records) {
209 const a = tierKey(r.alias)
210 if (r.kind === 'spawn' && a) m.spawns[a] += 1
211 if (r.kind === 'resume') m.escalations.resume += 1
212 m.usd += r.usd ?? 0
213 if (r.verdict === 'consistent') {
214 m.verdicts.consistent += 1
215 if (a) m.consistentBy[a] += 1
216 } else if (r.verdict === 'unverified') m.verdicts.unverified += 1
217 else if (r.verdict === 'refuted') m.verdicts.refuted += 1
218 }
219 return m
220}
221hooks/lib/allow.ts 345 lines1// The host-command allowlist. HARD RULE: `$.process.run` runs with no
2// permission prompt, so every argv the mod would run passes `checkArgv` first
3// and a refused argv never runs. Pure: no `$`.
4//
5// Allowed, and nothing else (part 5A: no chassis script is on the list):
6// git [-C <dir>] diff|merge-base|rev-parse|status|log … (no --output, --ext-diff, --textconv; the verifier's delta is `diff --name-status -M`)
7// git [-C <dir>] worktree list [--porcelain|-v|--verbose|-z]
8// git [-C <dir>] fetch [-q] origin main (exact)
9// git -C <plugin root> merge --ff-only origin/main (exact; <plugin root> is the loaded folder only; /delegation update)
10// git -C <dir> check-ignore -q -- <one path> (MOD-86: is the card git-ignored; exit 0 = ignored)
11// git -C <dir> ls-files --error-unmatch -- <one path> (MOD-124: is the briefLocal file tracked; exit 0 = tracked)
12// git -C <root> worktree add -q -b agent/<domain>/<id>[-replay] <worktree> <origin/main|7-40 hex sha>
13// (<domain>: the configured domains, by default
14// frontend|backend|ops|dispatcher|cross|shared;
15// <worktree>: <root>-<id>[-replay], or
16// <worktreeRoot>/<repo name>-<id>[-replay];
17// the literal -replay suffix on both or neither)
18// git -C <task repo> worktree add -q -b agent/<domain>/<id> <task repo>-<id> <origin/main|sha>
19// (MOD-44: <task repo> is the absolute path the task <id> names as its repo,
20// <domain>: that repo's own; with the session root known, no other -C passes)
21// git -C <root> worktree lock --reason 'chassis-delegation: verifier running; land after the verdict' <worktree>
22// git -C <root> worktree unlock <worktree>
23// (MOD-152: the worker's worktree is locked while the verifier judges it; exactly these two
24// shapes, one -C <root> under the same root rules as worktree add, <worktree> the path
25// worktreePath gives for a task id, and for lock exactly that --reason)
26// git -C <root> ls-tree --name-only <sha> agents/tasks/ (exact; /dispatch --replay)
27// git -C <root> show <sha>:agents/tasks/<id>-<name>.md (exact; /dispatch --replay)
28// the same two with origin/main for <sha> and the configured cardDir for agents/tasks
29// (MOD-4: is a task's card merged)
30// gh pr list|view … (no --web)
31// gh issue create|comment|list, for the configured issueRepo only (MOD-7; the body file under <root>/.delegation/debriefs/)
32// claude plugin validate|test <absolute folder> (exact; a no-repo brief's gate)
33// a gate-map command, word for word, `{files}`, `{worktree}` and `{outdir}` filled by absolute paths
34// (./gates.ts holds what a map may name)
35// <id> is a dispatchable task id, <PREFIX>-<number>[letter]: BE-101, OPS-195b.
36// Notably refused: sf, curl, git push|commit|reset|checkout, any other git
37// global option (-c, --exec-path, --git-dir …), gh pr merge|create, gh issue edit|close|delete, and any
38// script or package command the gate map does not name exactly.
39
40import { fillPlaceholders, gateCommandTemplates, matchesAnyTemplate } from './gates'
41import { worktreePath } from './paths'
42
43export const DEFAULT_DOMAINS = ['frontend', 'backend', 'ops', 'dispatcher', 'cross', 'shared'] as const
44
45export type Check = { ok: true } | { ok: false; reason: string }
46
47/** What the allowlist reads of the config: the gate templates (gateTemplatesOf(gateMap)), the domains, the worktree root. */
48/** MOD-44: a task that works in another local repo: the checkout's path, and that repo's own domains when it has them. */
49export type TaskRepo = { path: string; domains?: readonly string[] }
50
51export type AllowConfig = { /** MOD-44: the task ids that name another local repo as theirs, and that repo; `git -C <path> worktree add` passes for those tasks only. */ taskRepos?: Readonly<Record<string, TaskRepo>>; gateTemplates?: readonly (readonly string[])[]; domains?: readonly string[]; worktreeRoot?: string; /** MOD-3: the loaded plugin folder, the one dir `merge --ff-only origin/main` may run in. */ pluginRoot?: string; cardDir?: string; /** MOD-7: the one repo `gh issue` may name (owner/name); empty or absent = no issue form passes. */ issueRepo?: string; /** MOD-7: the session root, whose .delegation/debriefs/ holds the only body files. */ root?: string; /** MOD-75: set only while `/delegation merge` runs: its local git writes pass, exact shapes bound to this one task; a push, gh, curl, sf or wget never does. */ merge?: MergeCtx }
52
53const GIT_READ = ['diff', 'merge-base', 'rev-parse', 'status', 'log']
54const GIT_WRITEY_FLAGS = /^(--output(=|$)|--ext-diff$|--textconv$|-O)/
55const TASK_ID = /^[A-Z][A-Z0-9]*-\d+[a-z]?$/
56const TASK_ID_SRC = '[A-Z][A-Z0-9]*-\\d+[a-z]?'
57const SHA = /^[0-9a-f]{7,40}$/
58const SHOW_CARD = new RegExp(`^[0-9a-f]{7,40}:agents/tasks/${TASK_ID_SRC}-[A-Za-z0-9._-]+\\.md$`)
59const CARD_FILE = new RegExp(`^${TASK_ID_SRC}-[A-Za-z0-9._-]+\\.md$`)
60/** A relative folder, plain segments only (the configured cardDir). */
61const PLAIN_DIR = /^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/
62const cardDirOk = (d: string, allow: AllowConfig): boolean => {
63 const want = (allow.cardDir ?? '').replace(/^\/+|\/+$/g, '')
64 return PLAIN_DIR.test(d) && !d.split('/').some(seg => seg === '.' || seg === '..') && (d === 'agents/tasks' || (want !== '' && d === want))
65}
66const REPLAY = '-replay'
67
68const refuse = (reason: string): Check => ({ ok: false, reason })
69const ok: Check = { ok: true }
70
71export const isTaskId = (s: string): boolean => TASK_ID.test(s) && s.length <= 64
72export const isSha = (s: string): boolean => SHA.test(s)
73export const isBaseRef = (s: string): boolean => s === 'origin/main' || SHA.test(s)
74
75export function checkArgv(argv: readonly string[], allow: AllowConfig = {}): Check {
76 const [cmd, ...rest] = argv
77 if (cmd === undefined) return refuse('empty argv')
78 if (allow.merge) {
79 // MOD-75: while the merge command runs, the remote refusal comes ahead of everything, then its exact shapes
80 if (isRemoteArgv(argv)) return refuse('the merge command never pushes, nor runs gh, curl, sf or wget')
81 if (isMergeShape(argv, allow.merge)) return ok
82 }
83 if (cmd === 'git') return checkGit(rest, allow)
84 if (cmd === 'gh') return checkGh(rest, allow)
85 if (cmd === 'claude') return checkClaude(rest)
86 // MOD-72: the verdict tool's wait is a `sleep` process (a $.clock wait would spend the hook's budget); only `sleep <whole seconds, 1 to 600>`
87 if (cmd === 'sleep') return rest.length === 1 && /^[0-9]{1,3}$/.test(rest[0]!) && Number(rest[0]) >= 1 && Number(rest[0]) <= 600 ? ok : refuse('sleep takes one whole number of seconds, 1 to 600')
88 if (matchesAnyTemplate(argv, allow.gateTemplates ?? [])) return ok
89 return refuse(`${cmd} is not on the list (not git, gh, claude plugin, nor a gate-map command word for word)`)
90}
91
92function checkGit(args: readonly string[], allow: AllowConfig): Check {
93 let i = 0
94 const dirs: string[] = []
95 while (args[i] === '-C') {
96 const dir = args[i + 1]
97 if (!dir || dir.startsWith('-')) return refuse('git -C needs a directory')
98 dirs.push(dir)
99 i += 2
100 }
101 const sub = args[i]
102 if (sub === undefined) return refuse('git with no subcommand')
103 if (sub.startsWith('-')) return refuse(`git global option ${sub} is not on the list`)
104 const tail = args.slice(i + 1)
105 if (GIT_READ.includes(sub)) {
106 const bad = tail.find(a => GIT_WRITEY_FLAGS.test(a))
107 return bad ? refuse(`git ${sub} ${bad} is not on the list`) : ok
108 }
109 if (sub === 'check-ignore') {
110 // MOD-86: is this path git-ignored? Exactly `-q -- <one path>`; no other option, no second path.
111 const [q, dd, path, ...more] = tail
112 const exact = dirs.length === 1 && q === '-q' && dd === '--' && more.length === 0 && path !== undefined && path !== '' && !path.startsWith('-')
113 return exact ? ok : refuse(`git check-ignore ${tail.join(' ')} is not the exact shape (-C <dir> check-ignore -q -- <path>)`)
114 }
115 if (sub === 'ls-files') {
116 // MOD-124: is this path tracked? Exactly `-C <dir> ls-files --error-unmatch -- <one path>`; exit 0 = tracked.
117 const [flag, dd, path, ...more] = tail
118 const exact = dirs.length === 1 && flag === '--error-unmatch' && dd === '--' && more.length === 0 && path !== undefined && path !== '' && !path.startsWith('-')
119 return exact ? ok : refuse(`git ls-files ${tail.join(' ')} is not the exact shape (-C <dir> ls-files --error-unmatch -- <path>)`)
120 }
121 if (sub === 'ls-tree') {
122 const [flag, sha, path, ...more] = tail
123 const dir = (path ?? '').replace(/\/$/, '')
124 const exact =
125 dirs.length === 1 && flag === '--name-only' && more.length === 0 && (path ?? '').endsWith('/') &&
126 ((SHA.test(sha ?? '') && path === 'agents/tasks/') || (isBaseRef(sha ?? '') && cardDirOk(dir, allow)))
127 return exact ? ok : refuse(`git ls-tree ${tail.join(' ')} is not the exact shape (-C <root> ls-tree --name-only <sha> agents/tasks/)`)
128 }
129 if (sub === 'show') {
130 const spec = tail[0] ?? ''
131 const colon = spec.indexOf(':')
132 const ref = spec.slice(0, colon)
133 const file = spec.slice(colon + 1)
134 const slash = file.lastIndexOf('/')
135 const cardAtRef = colon > 0 && isBaseRef(ref) && slash > 0 && cardDirOk(file.slice(0, slash), allow) && CARD_FILE.test(file.slice(slash + 1))
136 const exact = dirs.length === 1 && tail.length === 1 && (SHOW_CARD.test(spec) || cardAtRef) && !spec.includes('..')
137 return exact ? ok : refuse(`git show ${tail.join(' ')} is not the exact shape (-C <root> show <sha>:agents/tasks/<id>-<name>.md)`)
138 }
139 if (sub === 'fetch') {
140 const exact = tail.join(' ')
141 return exact === '-q origin main' || exact === 'origin main' ? ok : refuse(`git fetch ${exact} is not the exact shape (fetch [-q] origin main)`)
142 }
143 if (sub === 'merge') {
144 const exact = dirs.length === 1 && allow.pluginRoot !== undefined && allow.pluginRoot !== '' && (dirs[0] as string).replace(/\/+$/, '') === allow.pluginRoot.replace(/\/+$/, '') && tail.join(' ') === '--ff-only origin/main'
145 return exact ? ok : refuse(`git merge ${tail.join(' ')} is not the exact shape (-C <the loaded plugin folder> merge --ff-only origin/main)`)
146 }
147 if (sub === 'worktree') {
148 const action = tail[0]
149 if (action === 'list') {
150 const bad = tail.slice(1).find(a => !['--porcelain', '-v', '--verbose', '-z'].includes(a))
151 return bad ? refuse(`git worktree list ${bad} is not on the list`) : ok
152 }
153 if (action === 'add') return checkWorktreeAdd(dirs, tail.slice(1), allow)
154 if (action === 'lock' || action === 'unlock') return checkWorktreeLock(action, dirs, tail.slice(1), allow)
155 return refuse(`git worktree ${action ?? ''} is not on the list`.trim())
156 }
157 return refuse(`git ${sub} is not on the list`)
158}
159
160function checkWorktreeAdd(dirs: readonly string[], args: readonly string[], allow: AllowConfig): Check {
161 if (dirs.length !== 1) return refuse('git worktree add needs exactly one -C <root>')
162 const root = (dirs[0] as string).replace(/\/+$/, '')
163 if (args.length !== 5 || args[0] !== '-q' || args[1] !== '-b') {
164 return refuse('git worktree add must be exactly: -q -b agent/<domain>/<id> <worktree> <base>')
165 }
166 const [, , branch, path, base] = args as [string, string, string, string, string]
167 const m = new RegExp(`^agent/([A-Za-z0-9_-]+)/(${TASK_ID_SRC})(${REPLAY})?$`).exec(branch)
168 // MOD-44: with the session root known, -C is that root, or the repo the task named by this branch names as its own
169 const session = (allow.root ?? '').replace(/\/+$/, '')
170 const taskRepo = m ? allow.taskRepos?.[m[2] as string] : undefined
171 const other = session !== '' && root !== session
172 if (other && !(taskRepo && taskRepo.path.replace(/\/+$/, '') === root && m?.[3] === undefined)) {
173 return refuse(`git -C ${root} worktree add is for the session's own repo, or for a task that names ${root} as its repo${m ? ` (${m[2]} ${taskRepo ? `names ${taskRepo.path}` : 'names no other repo'})` : ''}`)
174 }
175 const domains: readonly string[] = other ? (taskRepo?.domains && taskRepo.domains.length > 0 ? taskRepo.domains : DEFAULT_DOMAINS) : allow.domains && allow.domains.length > 0 ? allow.domains : DEFAULT_DOMAINS
176 if (!m || !domains.includes(m[1] as string)) return refuse(`branch ${branch} is not agent/<${domains.join('|')}>/<id>[-replay]`)
177 const want = worktreePath(root, m[2] as string, m[3] !== undefined, other ? undefined : allow.worktreeRoot)
178 if (path !== want) return refuse(`worktree path ${path} is not ${want}`)
179 if (!isBaseRef(base)) return refuse(`base ${base} is not origin/main or a 7-40 hex sha`)
180 return ok
181}
182
183/** MOD-152: the one reason a verify's lock carries. */
184export const LOCK_REASON = 'chassis-delegation: verifier running; land after the verdict'
185
186/**
187 * MOD-152: `-C <root> worktree lock --reason <LOCK_REASON> <worktree>` and `-C <root> worktree unlock <worktree>`, exactly.
188 * <worktree> is what worktreePath gives for a task id, under the root rules of `worktree add`.
189 */
190function checkWorktreeLock(action: 'lock' | 'unlock', dirs: readonly string[], args: readonly string[], allow: AllowConfig): Check {
191 const shape = action === 'lock' ? `-C <root> worktree lock --reason '${LOCK_REASON}' <worktree>` : '-C <root> worktree unlock <worktree>'
192 if (dirs.length !== 1) return refuse(`git worktree ${action} needs exactly one -C <root> (${shape})`)
193 const root = (dirs[0] as string).replace(/\/+$/, '')
194 if (action === 'lock') {
195 if (args.length !== 3 || args[0] !== '--reason') return refuse(`git worktree lock ${args.join(' ')} is not the exact shape (${shape})`)
196 if (args[1] !== LOCK_REASON) return refuse(`git worktree lock reason ${args[1]} is not '${LOCK_REASON}'`)
197 } else if (args.length !== 1) return refuse(`git worktree unlock ${args.join(' ')} is not the exact shape (${shape})`)
198 const path = args[args.length - 1] as string
199 const session = (allow.root ?? '').replace(/\/+$/, '')
200 const other = session !== '' && root !== session
201 for (let i = path.indexOf('-'); i >= 0; i = path.indexOf('-', i + 1)) {
202 const m = new RegExp(`^(${TASK_ID_SRC})(${REPLAY})?$`).exec(path.slice(i + 1))
203 if (!m) continue
204 const id = m[1] as string
205 const replay = m[2] !== undefined
206 const taskRepo = allow.taskRepos?.[id]
207 if (other && !(taskRepo && taskRepo.path.replace(/\/+$/, '') === root && !replay)) continue
208 if (path === worktreePath(root, id, replay, other ? undefined : allow.worktreeRoot)) return ok
209 }
210 return refuse(`git -C ${root} worktree ${action} ${path}: the path is not a task worktree of ${root}${other ? ' (a task that names it as its repo)' : ''}`)
211}
212
213function checkGh(args: readonly string[], allow: AllowConfig): Check {
214 if (args[0] === 'issue') return checkGhIssue(args.slice(1), allow)
215 if (args[0] !== 'pr' || (args[1] !== 'list' && args[1] !== 'view')) return refuse(`gh ${args.slice(0, 2).join(' ')} is not on the list`)
216 const bad = args.find(a => a === '--web' || a === '-w')
217 return bad ? refuse(`gh pr ${args[1]} ${bad} is not on the list`) : ok
218}
219
220const ISSUE_REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/
221/** A body file: absolute, under <root>/.delegation/debriefs/, plain segments. */
222function debriefBodyOk(path: string, root: string | undefined): boolean {
223 const r = (root ?? '').replace(/\/+$/, '')
224 const prefix = `${r}/.delegation/debriefs/`
225 return r !== '' && ABS_FOLDER.test(path) && path.startsWith(prefix) && path.length > prefix.length && !path.split('/').slice(1).some(seg => seg === '..' || seg === '.' || seg === '') && !path.endsWith('/')
226}
227
228/**
229 * MOD-7: gh issue, three exact shapes, the repo equal to the configured issueRepo:
230 * create --repo <r> --title <t> --body-file <path>
231 * comment <number> --repo <r> --body-file <path>
232 * list --repo <r> --state all --limit 200 --json number,title,body (read-only)
233 */
234function checkGhIssue(args: readonly string[], allow: AllowConfig): Check {
235 const repo = allow.issueRepo ?? ''
236 if (repo === '' || !ISSUE_REPO.test(repo)) return refuse('gh issue is not on the list: no issueRepo is configured')
237 const [verb, ...t] = args
238 const shape = (s: string): Check => refuse(`gh issue ${verb ?? ''} is not the exact shape (${s})`.replace(' ', ' '))
239 if (verb === 'create') {
240 const exact = t.length === 6 && t[0] === '--repo' && t[1] === repo && t[2] === '--title' && (t[3] ?? '') !== '' && !(t[3] as string).startsWith('-') && t[4] === '--body-file' && debriefBodyOk(t[5] as string, allow.root)
241 return exact ? ok : shape('create --repo <issueRepo> --title <title> --body-file <file under .delegation/debriefs/>')
242 }
243 if (verb === 'comment') {
244 const exact = t.length === 5 && /^\d{1,9}$/.test(t[0] as string) && t[1] === '--repo' && t[2] === repo && t[3] === '--body-file' && debriefBodyOk(t[4] as string, allow.root)
245 return exact ? ok : shape('comment <number> --repo <issueRepo> --body-file <file under .delegation/debriefs/>')
246 }
247 if (verb === 'list') {
248 const exact = t.join(' ') === `--repo ${repo} --state all --limit 200 --json number,title,body`
249 return exact ? ok : shape('list --repo <issueRepo> --state all --limit 200 --json number,title,body')
250 }
251 return refuse(`gh issue ${verb ?? ''} is not on the list`.replace(' ', ' '))
252}
253
254/** An absolute folder with no `..` segment and nothing a shell would read. */
255const ABS_FOLDER = /^\/[A-Za-z0-9._@%+=:,\/-]*$/
256
257/** `claude plugin validate <folder>` and `claude plugin test <folder>`, exactly, the folder absolute. */
258function checkClaude(args: readonly string[]): Check {
259 const [noun, verb, folder, ...more] = args
260 const shape = 'claude plugin validate|test <absolute folder>'
261 if (noun !== 'plugin' || (verb !== 'validate' && verb !== 'test')) return refuse(`claude ${args.slice(0, 2).join(' ')} is not on the list (only ${shape})`)
262 if (folder === undefined || more.length > 0) return refuse(`claude plugin ${verb} must be exactly: ${shape}`)
263 if (!ABS_FOLDER.test(folder) || folder.split('/').includes('..')) return refuse(`claude plugin ${verb} ${folder} is not an absolute folder`)
264 return ok
265}
266
267/** Whether a gate-map command may stand in the map at all (./gates.ts holds the rules). */
268export function checkGateCommand(cmd: string): Check {
269 const t = gateCommandTemplates(cmd)
270 return 'reason' in t ? refuse(t.reason) : ok
271}
272
273export const refusedLine = (argv: readonly string[], reason: string): string =>
274 `chassis-delegation: refused argv ${JSON.stringify(argv)} (${reason})`
275
276const SAMPLE_FILES = '/sample/.delegation/T-1/files.txt'
277const SAMPLE_TREE = '/sample/worktree'
278const SAMPLE_OUTDIR = '/sample/out'
279
280/**
281 * A gate-map entry at config load: the shape rules, then every part of it with
282 * `{files}`, `{worktree}` and `{outdir}` filled by a sample absolute path through the
283 * allowlist itself, so what would be refused at verify time is refused now.
284 */
285export function checkGateEntry(cmd: string): Check {
286 const t = gateCommandTemplates(cmd)
287 if ('reason' in t) return refuse(t.reason)
288 for (const words of t.templates) {
289 const argv = fillPlaceholders(words, SAMPLE_FILES, SAMPLE_TREE, SAMPLE_OUTDIR)
290 const c = checkArgv(argv, { gateTemplates: t.templates })
291 if (!c.ok) return refuse(`${c.reason.includes('not an absolute folder') ? `${c.reason}; write {worktree}` : c.reason}`)
292 }
293 return ok
294}
295
296// ---- MOD-75: the merge command's local git writes -----------------------------------------
297
298/** The one task `/delegation merge` works on: the session root, its worktree and branch, the base ref, the card's repo-relative path. */
299export type MergeCtx = { root: string; worktree: string; branch: string; baseRef: string; cardRel?: string; id: string }
300
301/** The subject of the merged-card commit, the only commit message that passes. */
302export const mergedSubject = (id: string): string => `cards: ${id} merged`
303
304/** An argv the merge command may never run: a push, gh, curl, sf or wget. */
305export const isRemoteArgv = (argv: readonly string[]): boolean => {
306 const [cmd = '', ...rest] = argv
307 const base = cmd.split('/').pop() ?? cmd
308 if (base === 'gh' || base === 'curl' || base === 'sf' || base === 'wget') return true
309 return base === 'git' && rest.includes('push')
310}
311
312/**
313 * The git writes `/delegation merge` runs, exactly, and only with `allow.merge` set:
314 * git -C <worktree> fetch origin git -C <root> fetch origin
315 * git -C <worktree> rebase <baseRef> git -C <worktree> rebase --abort
316 * git -C <worktree> add -- <card> git -C <worktree> commit -q -m 'cards: <ID> merged' [-m <Co-Authored-By trailer>]
317 * git -C <root> remote get-url origin git -C <root> clean -q -f -- <card>
318 * git -C <root> pull --ff-only git -C <root> worktree remove <worktree>
319 * git -C <root> branch -D <branch> git -C <root> worktree unlock <worktree> (MOD-152: finish frees a lock a crashed verify left)
320 * <worktree>, <branch> and <card> are the one task's; nothing else passes here.
321 */
322function isMergeShape(argv: readonly string[], c: MergeCtx): boolean {
323 if (argv[0] !== 'git' || argv[1] !== '-C' || argv.length < 4) return false
324 const dir = (argv[2] as string).replace(/\/+$/, '')
325 const root = c.root.replace(/\/+$/, '')
326 const wt = c.worktree.replace(/\/+$/, '')
327 const tail = argv.slice(3).join('\u0000')
328 const is = (...words: string[]) => tail === words.join('\u0000')
329 if (dir === wt) {
330 if (is('fetch', 'origin') || is('rebase', c.baseRef) || is('rebase', '--abort')) return true
331 if (c.cardRel && is('add', '--', c.cardRel)) return true
332 const [sub, q, m1, subj, m2, trailer, ...more] = argv.slice(3)
333 if (sub === 'commit' && q === '-q' && m1 === '-m' && subj === mergedSubject(c.id) && more.length === 0) {
334 if (m2 === undefined && trailer === undefined) return true
335 if (m2 === '-m' && /^Co-Authored-By: Claude [A-Za-z]+ [0-9.]+ <noreply@anthropic\.com>$/.test(trailer ?? '')) return true
336 }
337 return false
338 }
339 if (dir === root) {
340 if (is('fetch', 'origin') || is('remote', 'get-url', 'origin') || is('pull', '--ff-only') || is('worktree', 'remove', wt) || is('worktree', 'unlock', wt) || is('branch', '-D', c.branch)) return true
341 if (c.cardRel && is('clean', '-q', '-f', '--', c.cardRel)) return true
342 }
343 return false
344}
345hooks/lib/attempts.ts 303 lines1// Attempt records: what the mod keeps per task in `$.store` under
2// `delegation.tasks.<task-id>` (an array, appended per attempt). The eval's
3// data source. Pure: no `$`.
4/**
5 * The verdict word retired at MOD-19 (0.8.0). The one line that spells it is marked
6 * for tests/node/consistent.node.mjs, which skips exactly that line. A record or row
7 * written before the rename still holds it: it is read as `consistent` (once per
8 * occurrence, logged by the caller) and never written. The ledger keeps it as written.
9 */
10export const RETIRED_VERDICT = 'verified' // legacy word: read-only normaliser
11export const isRetiredVerdict = (v: unknown): boolean => v === RETIRED_VERDICT
12/** A stored verdict word as the mod reads it now. */
13export const readVerdict = <V extends string>(v: V): V | 'consistent' => (isRetiredVerdict(v) ? 'consistent' : v)
14/** An attempt record as the mod reads it now. */
15export const readRecord = (r: AttemptRecord): AttemptRecord => (isRetiredVerdict(r.verdict) ? { ...r, verdict: 'consistent' } : r)
16/** A recent-verdict row's line as the mod reads it now: the retired word in either old shape becomes `consistent`. */
17export const readLine = (line: string): string =>
18 line
19 .replace(new RegExp(`^(chassis-delegation: \\S+ attempt \\d+/\\d+ )${RETIRED_VERDICT}\\b`), '$1consistent')
20 .replace(new RegExp(`^(chassis-delegation: verdict=)${RETIRED_VERDICT}\\b`), '$1consistent')
21import type { Tier, TierSource } from './tier'
22
23/**
24 * `work-present` (GH-104): a respawn or an auto-resume found finished work in
25 * the worker's worktree (commits ahead of the base, a clean tree) and did not
26 * spawn; `/dispatch <id> --verify <sha>` judges it, and the record takes that
27 * verdict.
28 */
29/**
30 * `over-spend` (GH-106): the worker's own cost reached twice its brief's
31 * `spend=` before it handed back; work may be present in its worktree. Not a
32 * failing verdict: it never escalates the tier.
33 */
34/**
35 * `consistent` (MOD-19, renamed; see readRecord): every machine-checkable claim
36 * of the report matched git. A record written before the rename is read as consistent (see readRecord).
37 */
38export type AttemptVerdict = 'pending' | 'consistent' | 'unverified' | 'refuted' | 'no-report' | 'refused' | 'work-present' | 'over-spend' | 'reviewed'
39/**
40 * `verify` (GH-104): no worker ran; the attempt is the work found in the worktree, judged by `--verify`.
41 * `review` (MOD-21): a read-only reviewer read a consistent hand-back against the diff. It carries the number of
42 * the attempt it reviewed, is judged `reviewed`, and is not on the ladder: it is never counted against `budget=`
43 * (see `attemptsFor`), never numbered among the worker's attempts, and never patched by `patchRecord`.
44 */
45export type AttemptKind = 'spawn' | 'resume' | 'verify' | 'review'
46
47/** MOD-21: what a reviewer's `[[review]]` block counted. */
48export type ReviewResult = { confirmed: number; refuted: number; unverifiable: number }
49
50export type AttemptRecord = {
51 task: string
52 subtask: string
53 /** 1-based, counted per task + subtask across spawns and resumes. */
54 attempt: number
55 kind: AttemptKind
56 /** The attempt number of the spawn this attempt descends from (a resume keeps its spawn's). */
57 lineage: number
58 tier: Tier
59 alias: string
60 /** MOD-15: `fallback` when the mod started a ready worktree row itself after the brain left it unclaimed (readyFallbackMinutes). */
61 source?: TierSource | 'fallback'
62 resolvedModel?: string
63 verdict: AttemptVerdict
64 /** GH-115: a refuted attempt's first failed claim (branch, sha, scope, files, gate, red, pr). */
65 firstFailed?: string
66 /** MOD-56: the worker stopped on a usage limit (its hand-back had no report and named one). */
67 stop?: 'rate_limited'
68 /** MOD-56: the reset time the hand-back named, as written. */
69 resetsAt?: string
70 /** The report's own `gate=` claim. */
71 reportGate?: string
72 /**
73 * GH-104: the sha the attempt's report named (as written), or a
74 * `work-present` / `verify` attempt's branch head. A judged one is not new
75 * work: a respawn past it is not stopped by the look at the worktree.
76 */
77 sha?: string
78 /** MOD-21: a `review` attempt's counts; absent when its hand-back carried no (well-formed) review block. */
79 review?: ReviewResult
80 /** The red evidence the report named (`red=`, as written) and read in the worker's tree (GH-20). */
81 red?: string
82 /** sha-256 of that file's bytes: a later attempt naming the same bytes is refuted on red. */
83 redHash?: string
84 /** MOD-1: that attempt's red claim held, so its file is the task's one proof of red. */
85 redHeld?: true
86 /** The worker's own cost from its turn usage (GH-106); else the session's cost growth between spawn (or resume) and verdict, marked by `usdApprox`. */
87 usd?: number
88 /** True when `usd` is the session delta, not the worker's own cost. */
89 usdApprox?: true
90 tokens?: number
91 /** MOD-13: the effort the worker's steps were rewritten to (low … max); absent when the engine's default ran. */
92 effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max'
93 /** ms since the epoch at spawn (or resume). */
94 at: number
95 /** MOD-37: the id of the session whose brain made the spawn; absent on a record written before it. */
96 sessionId?: string
97 /** MOD-37: that session's root, so an old record can still be placed. */
98 root?: string
99 verdictAt?: number
100 agentId?: string
101 toolUseId?: string
102 briefPath?: string
103 purpose?: string
104 /** A `/dispatch --replay` run of an already-merged card, from `base`. */
105 replay?: true
106 base?: string
107 /** MOD-4: why this task's owed row is gone: its work reached the default branch (`merged`), or the brain closed it by hand (`accepted`). */
108 retired?: 'merged' | 'accepted'
109 /** MOD-4: `/delegation accept <id> [note]` — accepted by hand, with the note. */
110 accepted?: { note?: string; at: number }
111 /** MOD-4: when the retire check last ran (answered or not): it runs at most once per 15 minutes. */
112 retireTriedAt?: number
113 /** MOD-4: when a retire check last got an answer (not merged yet): the owed row has been looked at. */
114 retireCheckedAt?: number
115}
116
117/** Which attempts count together: real runs, or the replays from one base commit. */
118export type Lane = { replay?: boolean; base?: string }
119
120const inLane = (r: AttemptRecord, lane?: Lane): boolean =>
121 Boolean(r.replay) === Boolean(lane?.replay) && (!r.replay || (r.base ?? '') === (lane?.base ?? ''))
122
123const FAILING: readonly AttemptVerdict[] = ['refuted', 'no-report']
124
125/** The worker's attempts of a subtask, oldest first: the ladder. A reviewer's attempt (MOD-21) is not on it. */
126export const attemptsFor = (records: readonly AttemptRecord[], subtask: string, lane?: Lane): AttemptRecord[] =>
127 records.filter(r => r.kind !== 'review' && r.subtask === subtask && inLane(r, lane)).sort((a, b) => a.attempt - b.attempt)
128
129/** MOD-21: the reviewer attempts of a subtask (any attempt reviewed), oldest first. */
130export const reviewsFor = (records: readonly AttemptRecord[], subtask: string, lane?: Lane): AttemptRecord[] =>
131 records.filter(r => r.kind === 'review' && r.subtask === subtask && inLane(r, lane))
132
133/** MOD-51: the highest attempt of a subtask's lane numbered above `attempt`, whatever its verdict; undefined when none. */
134export const supersededBy = (records: readonly AttemptRecord[], subtask: string, attempt: number, lane?: Lane): number | undefined => {
135 const later = attemptsFor(records, subtask, lane).filter(r => r.attempt > attempt)
136 return later.length === 0 ? undefined : Math.max(...later.map(r => r.attempt))
137}
138
139export const nextAttempt = (records: readonly AttemptRecord[], subtask: string, lane?: Lane): number =>
140 attemptsFor(records, subtask, lane).reduce((n, r) => Math.max(n, r.attempt), 0) + 1
141
142export const lineageResumes = (records: readonly AttemptRecord[], subtask: string, lineage: number, lane?: Lane): number =>
143 attemptsFor(records, subtask, lane).filter(r => r.lineage === lineage && r.kind === 'resume').length
144
145export const recordFailed = (r: AttemptRecord): boolean => FAILING.includes(r.verdict) || r.reportGate === 'fail'
146
147/**
148 * GH-104: what earns a respawn the next tier: a refuted report, or a
149 * `gate=fail` the verifier confirmed (the verdict held it: consistent). A
150 * no-report is a reporting defect, not a capability one, and never escalates.
151 */
152export const escalatesOn = (verdict: string, reportGate?: string): boolean => verdict === 'refuted' || (verdict === 'consistent' && reportGate === 'fail')
153
154/** GH-115: the claims whose failure says the worker was out of its depth; the rest say the brief's globs or the base were wrong. */
155export const ESCALATING_CLAIMS: readonly string[] = ['sha', 'gate', 'red']
156
157/** GH-115: the claim a refuted attempt is held at its tier for (scope, files, branch, pr), else undefined (a record without `firstFailed` escalates). */
158export const heldClaim = (r: Pick<AttemptRecord, 'verdict' | 'firstFailed'>): string | undefined =>
159 r.verdict === 'refuted' && r.firstFailed !== undefined && !ESCALATING_CLAIMS.includes(r.firstFailed) ? r.firstFailed : undefined
160
161/**
162 * The tier a respawn escalates from: the last attempt's, when that attempt was
163 * refuted or confirmed gate=fail (GH-104), unless its first failed claim was
164 * scope, files, branch or pr (GH-115).
165 */
166export function escalationSource(records: readonly AttemptRecord[], subtask: string, lane?: Lane): Tier | undefined {
167 const last = attemptsFor(records, subtask, lane).at(-1)
168 return last && escalatesOn(last.verdict, last.reportGate) && heldClaim(last) === undefined ? last.tier : undefined
169}
170
171/**
172 * GH-104: the tier a respawn after a no-report is held at: that attempt's
173 * own, never one up (and never below it, should the brief's tier be lower).
174 * GH-115: a scope, files, branch or pr refute holds it the same way.
175 */
176export function holdSource(records: readonly AttemptRecord[], subtask: string, lane?: Lane): Tier | undefined {
177 const last = attemptsFor(records, subtask, lane).at(-1)
178 return last && (last.verdict === 'no-report' || heldClaim(last) !== undefined) ? last.tier : undefined
179}
180
181/** GH-104: the shas the verifier already judged for this task + subtask (pending and work-present attempts are not judged). */
182export const judgedShas = (records: readonly AttemptRecord[], subtask: string, lane?: Lane): string[] =>
183 attemptsFor(records, subtask, lane).flatMap(r => (r.sha && r.verdict !== 'pending' && r.verdict !== 'work-present' ? [r.sha] : []))
184
185/** The red hashes of the attempts before `attempt` (same subtask and lane): what a fresh red file must differ from. */
186export const priorRedHashes = (records: readonly AttemptRecord[], subtask: string, attempt: number, lane?: Lane): { attempt: number; hash: string; held?: boolean }[] =>
187 attemptsFor(records, subtask, lane).flatMap(r => (r.attempt < attempt && r.redHash ? [{ attempt: r.attempt, hash: r.redHash, ...(r.redHeld ? { held: true } : {}) }] : []))
188
189/** MOD-1: do two spellings of a sha (7-40 hex) name the same commit? One may be a prefix of the other. */
190const sameSha = (a: string, b: string): boolean => {
191 const x = a.trim().toLowerCase()
192 const y = b.trim().toLowerCase()
193 return x.length >= 7 && y.length >= 7 && (x.startsWith(y) || y.startsWith(x))
194}
195
196/**
197 * MOD-41: is a hand-back whose report names `sha` a new attempt? Yes when the last
198 * attempt was judged (not pending) at a sha other than this one: the brain resumed
199 * the worker after a verdict the mod had not advised a resume for. The same sha is
200 * the MOD-1 re-judge and a record that named no sha is left alone.
201 */
202export function isResumeAfterJudged(records: readonly AttemptRecord[], subtask: string, sha: string, lane?: Lane): boolean {
203 const last = attemptsFor(records, subtask, lane).at(-1)
204 return last !== undefined && last.verdict !== 'pending' && last.sha !== undefined && !sameSha(last.sha, sha)
205}
206
207/**
208 * MOD-1: which attempt `/dispatch <id> --verify <sha>` judges. The last attempt
209 * when it is a work-present one (GH-104), or when it was already judged at this
210 * very sha (`rejudge`: same attempt number, no new record, no budget spent);
211 * else the next attempt number.
212 */
213export function verifyTarget(records: readonly AttemptRecord[], subtask: string, sha: string, lane?: Lane): { attempt: number; rejudge: boolean } {
214 const last = attemptsFor(records, subtask, lane).at(-1)
215 if (last?.verdict === 'work-present') return { attempt: last.attempt, rejudge: false }
216 if (last && last.verdict !== 'pending' && last.sha !== undefined && sameSha(last.sha, sha)) return { attempt: last.attempt, rejudge: true }
217 return { attempt: nextAttempt(records, subtask, lane), rejudge: false }
218}
219
220/** Replaces the worker's record with the same subtask + attempt by `patch` applied to it (a reviewer's record never matches). */
221export function patchRecord(records: readonly AttemptRecord[], subtask: string, attempt: number, patch: Partial<AttemptRecord>, lane?: Lane): AttemptRecord[] {
222 return records.map(r => (r.kind !== 'review' && r.subtask === subtask && r.attempt === attempt && inLane(r, lane) ? { ...r, ...patch } : r))
223}
224
225/** MOD-21: replaces the reviewer attempt the spawn `toolUseId` made by `patch` applied to it. */
226export function patchReview(records: readonly AttemptRecord[], toolUseId: string, patch: Partial<AttemptRecord>): AttemptRecord[] {
227 return records.map(r => (r.kind === 'review' && r.toolUseId === toolUseId ? { ...r, ...patch } : r))
228}
229
230/** The fields a replay attempt carries. */
231export const laneFields = (lane?: Lane): Pick<AttemptRecord, 'replay' | 'base'> =>
232 lane?.replay ? { replay: true, ...(lane.base ? { base: lane.base } : {}) } : {}
233
234export const taskLabel = (task: string, subtask: string): string => (subtask === 'main' ? task : `${task}/${subtask}`)
235
236/** MOD-4: a task's retire check runs at most this often. */
237export const RETIRE_EVERY_MS = 15 * 60 * 1000
238
239/** MOD-4: is the retire check due for this subtask: its last attempt is not retired and was not tried in the last 15 minutes. */
240export function retireDue(records: readonly AttemptRecord[], subtask: string, now: number, lane?: Lane): boolean {
241 const last = attemptsFor(records, subtask, lane).at(-1)
242 if (!last || last.retired) return false
243 return last.retireTriedAt === undefined || now - last.retireTriedAt >= RETIRE_EVERY_MS
244}
245
246/** MOD-4: does a card's frontmatter read `status: merged` (MOD-101: or `landed`)? (A line in the body does not.) */
247export function cardReadsMerged(text: string): boolean {
248 const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)
249 return m !== null && /^status:\s*["']?(?:merged|landed)["']?\s*$/m.test(m[1] as string)
250}
251
252/**
253 * MOD-4: what one retire check leaves on the last attempt. `ancestor` is what
254 * `git merge-base --is-ancestor <sha> origin/main` said (undefined: it could not
255 * say), `picked` (MOD-101, #158) whether the sha's patch is already on the session's current branch
256 * (cherry-picked: no commit of it is left unmatched), `card` the card's text on origin/main (undefined: not read). Merged on
257 * either; with neither answered the row is left as it is (only the try is noted).
258 */
259export function retirePatch(probe: { ancestor?: boolean; picked?: boolean; card?: string }, now: number): Partial<AttemptRecord> {
260 if (probe.ancestor === true || probe.picked === true || (probe.card !== undefined && cardReadsMerged(probe.card))) return { retired: 'merged', retireTriedAt: now, retireCheckedAt: now }
261 if (probe.ancestor === undefined && probe.picked === undefined && probe.card === undefined) return { retireTriedAt: now }
262 return { retireTriedAt: now, retireCheckedAt: now }
263}
264
265/**
266 * MOD-35: the key one ledger row is written under. A spawn row (MOD-94, `event: spawn`) is one per
267 * spawn; an accept row is one per task
268 * attempt; a verdict row is one per (task, attempt, sha, verdict), so a hand-back
269 * that arrives twice (as a tool result and as a notification, or from a second
270 * copy of the mod) leaves one line. A row with neither a verdict nor a kind of
271 * accept has no key and is always written.
272 */
273export function ledgerRowKey(row: Record<string, unknown>): string | undefined {
274 const head = `${String(row.task ?? '')}|${String(row.subtask ?? 'main')}|${String(row.attempt ?? '')}`
275 // MOD-94: a spawn row is one per spawn (its tool_use_id, else its agent), and a replay's apart from a real run's
276 if (row.event === 'spawn') return `spawn|${head}|${row.replay ? `replay-${String(row.base ?? '')}` : ''}|${String(row.toolUseId ?? row.agentId ?? '')}`
277 if (row.kind === 'accept') return `accept|${head}`
278 if (typeof row.verdict !== 'string') return undefined
279 // a reviewer's rows are told apart by the spawn they came from; a worker's by (task, attempt, sha, verdict)
280 return `verdict|${head}|${String(row.sha ?? '')}|${row.verdict}${row.kind === 'review' ? `|${String(row.toolUseId ?? '')}` : ''}`
281}
282
283/** MOD-35: does this ledger text already hold a row under the same key as `row`? */
284export function ledgerHas(text: string, row: Record<string, unknown>): boolean {
285 const key = ledgerRowKey(row)
286 if (key === undefined || text === '') return false
287 for (const line of text.split('\n')) {
288 if (line.trim() === '') continue
289 try {
290 const parsed = JSON.parse(line) as unknown
291 if (parsed && typeof parsed === 'object' && ledgerRowKey(parsed as Record<string, unknown>) === key) return true
292 } catch {
293 // a line that is not JSON is not a row
294 }
295 }
296 return false
297}
298
299/** MOD-35: the accept row (`how`: the branch reached the default branch, or the brain accepted it). */
300export function acceptRow(rec: Pick<AttemptRecord, 'task' | 'subtask' | 'attempt' | 'sha'>, how: 'merged' | 'accepted', at: number): Record<string, unknown> {
301 return { kind: 'accept', task: rec.task, subtask: rec.subtask, attempt: rec.attempt, ...(rec.sha ? { sha: rec.sha } : {}), at, how }
302}
303hooks/lib/crossbrief.ts 56 lines1// MOD-95 (#154): when a brief already exists for a task, is it the brief this dispatch would write? Pure: no `$`.
2//
3// Three points decide it, and only these: the header's repo= (absent, here, none or an absolute path), the worktree
4// the brief names, and the card path it names. All three agree: the brief is reused as it is (an amended scope or a
5// hand edit stays). Any differs: it is rewritten, or, with an attempt of the task open, dispatch refuses.
6
7import { parseHeader } from './brief'
8
9/** What a brief says of the repo, the worktree and the card; a point the brief does not name is undefined (not compared). */
10export type BriefNames = { repo: string; worktree?: string; card?: string }
11
12/** The same three points, as this dispatch would write them (`repo` is '' for a worktree brief of the session's own repo). */
13export type BriefWants = { repo: string; worktree: string; card: string }
14
15export type BriefDrift = { points: string[]; was: string[] }
16
17/**
18 * The repo, worktree and card path a brief names. The worktree and the card come from the body, in the shipped
19 * template's lines (`Card: <path> (read-only…`, `Worktree|Checkout|Working folder: <path>, branch …`) or the
20 * one-line form (`Work in <path> on <branch>; card <path>.`).
21 */
22export function briefNames(text: string): BriefNames {
23 const header = parseHeader(text)
24 const body = header ? text.slice(text.indexOf(header.raw) + header.raw.length) : text
25 const card = /^Card: (\S.*?) \(read-only/m.exec(body)?.[1] ?? /^Work in \S+ on \S+; card (\S.*?)\.$/m.exec(body)?.[1]
26 const worktree =
27 /^(?:Worktree|Checkout): (\S+?),? branch /m.exec(body)?.[1] ?? /^Working folder: (\S+) \(repo=none/m.exec(body)?.[1] ?? /^Work in (\S+) on \S+; card /m.exec(body)?.[1]
28 return { repo: header?.repo ?? '', ...(worktree !== undefined ? { worktree } : {}), ...(card !== undefined ? { card } : {}) }
29}
30
31/** Where `have` and `want` differ on the three points: which, and what the brief had. Empty: the brief is the one to reuse. */
32export function briefDrift(have: BriefNames, want: BriefWants): BriefDrift {
33 const points: string[] = []
34 const was: string[] = []
35 if (have.repo !== want.repo) {
36 points.push('repo')
37 was.push(`repo ${have.repo || 'absent'}`)
38 }
39 if (have.worktree !== undefined && have.worktree !== want.worktree) {
40 points.push('worktree')
41 was.push(`worktree ${have.worktree}`)
42 }
43 if (have.card !== undefined && have.card !== want.card) {
44 points.push('card')
45 was.push(`card ${have.card}`)
46 }
47 return { points, was }
48}
49
50/** `2. brief <path> was written for <what it named>; rewritten for this card (<the points that differed>)` */
51export const briefRewrittenLine = (path: string, d: BriefDrift): string => `2. brief ${path} was written for ${d.was.join(', ')}; rewritten for this card (${d.points.join(', ')})`
52
53/** The one-line refusal when the brief differs and an attempt of the task is running or awaiting its verdict. */
54export const briefStaleRefusal = (id: string, path: string, d: BriefDrift, attempt: number): string =>
55 `/dispatch ${id}: refused — brief ${path} was written for ${d.was.join(', ')}, which differs from this dispatch (${d.points.join(', ')}), and attempt ${attempt} of ${id} is running or awaiting its verdict; nothing was written (let it finish, or remove the brief once it is judged)`
56