SLOPSHOPPER

zetetic-autopilot

Automatic effort and model, and a quota that limits how many agents run, not how well one runs. Every request runs at the effort its grade calls for…

guardtoastmodelagents
v0.11.0no licenseupdated 2026-10-23cdeust/claude-mods/mods/zetetic-autopilot
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · zetetic-autopilot
› fix the failing auth test and add an audit log call ╭────────────────────────────────────────────╮ │ zetetic-autopilot │ ⏺ Read(src/auth.ts) │ main ran Edit (owner rule 2026-10-15: │ ⎿ Read 6 lines │ implementation is a subagent's work) │ ⏺ Update(src/auth.ts) ╰────────────────────────────────────────────╯ ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

claude-mods

Claude Code mods and a separate Codex adapter for the ai-architect.tools harness. The Claude mods keep one concern per mod, state shared through dependencies:

ModOwnsDepends on
cortex-guardrefusals: wiki pages only through wiki_write, worktrees inside <repo>/.claude/worktrees/nothing
cortex-wiki/wiki <wiki/**.md> to PDFnothing
zetetic-geniusstate: the request grade (task class → effort), the genius patterns and skills it matchesnothing
zetetic-autopilotcontext, policy, phases: effort ladder, model routing (a subagent's call, then its own definition, then its prompt's DESIGN block, never lowered by pressure), the dispatch table (hooks/dispatch-table.ts): an inheriting subagent nobody designed runs at the model and effort of its task's class, graded by one classifier completion (cls/review on each spawn record the table decided, absent before 0.11.0), an inheriting subagent's effort from the turn's grade when its call names a model but no effort (effort on each spawn record, absent before 0.10.0), the quota's cap on the main loop's parallel subagents, offloaded tool results; the phase each loop is in, on each run the steps a stuck escalation raised (escalated, absent before 0.8.0), and the advisor callszetetic-genius
zetetic-insightsinsights: the turn ledger across sessions ($.store), joined with /insights session outcomes and .zetetic/goals; per-phase effort proposals, `/calibrate apply\reset`, the calibration file the autopilot readszetetic-autopilot, zetetic-genius
mission-controlrenderer; the /mission pane: the turn's lanes by phase (bar height = effort, advisor calls, failed calls), effort per phase, learning curves per phase. Pixels in kitty or Ghostty outside tmux, coloured cells elsewherezetetic-autopilot, zetetic-insights
harness-fleetfleet: the owner's plugins, installed vs offered version, open PRs with CI, open issues (a defect is taken and fixed, a feature request goes to the owner); /fleet. Reads only (gh pr list, gh issue list, git remote): every outward action is a button the owner presses, which puts a prompt in front of the modelguard, genius, autopilot
superpowersthird-party skills library (obra/superpowers, MIT), pinned to v7.0.0 bb92a77: listed here so it installs with the mods; which skills we keep is decided after measurementnothing

Audience

Each output of a mod has one reader, and the engine fixes the reader by the API the output goes through (there is no per-call option): $.ui.toast, $.ui.log, $.ui.status, panes and rows are the user's, and the model never sees them; a tool.call result's context, a prompt.submit context and prompt.compose sections are Claude's, and the user never sees them; a deny is the model's tool error (the transcript draws it too). A text is written for its reader, and one string is never sent to both. The mods that send to both say which text is whose:

  • zetetic-autopilot: the user reads a toast when main implements (what main ran) and when a subagent spawn is refused (which spawn, how many run, the cap and the window: no instruction); Claude reads, in the context of main's first implementing tool result of a turn, the rule to delegate to a subagent, and, as the Agent tool's error, the cap refusal with the way out (wait for a running agent to finish, spawn again).
  • cortex-guard: the user reads a toast for each refusal, for a worktree that was not registered, and for a guard that failed; Claude reads the refusal's rule and fix as the tool's error (the same error when the guard itself failed), and, in the context of the result of its git worktree add, that the worktree was not registered and its cleanup is not covered.
  • harness-fleet: the user reads the /fleet pane and its toasts; Claude reads only what a button the user presses puts in front of it (review, take an issue, draft an issue), as "The harness-fleet plugin sent a message: ..." in the plugin's own voice: the owner is "the owner" in it, never "me" or "I".

Developing

Each mod is validated, tested and type-checked on its own:

cd mods/<mod> && claude plugin validate . && claude plugin test && npx -y -p typescript tsc -p . --noEmit

tsc needs the engine to have loaded the mod once (it lays .claude-plugin/types/); keep --noEmit, since a plain tsc -p . writes .js files beside the sources. For hot reload in a session, link the mod into that session's ~/.claude/dev-mods/<session>/ folder; the engine watches the folder a link names.

A mod cannot import a file from another mod (the engine refuses it: "outside the plugin's folder"), so the few small pure files several mods need are copied into each of them: hooks/paths.ts (where ~/ lands: HOME, else USERPROFILE, CLAUDE_CONFIG_DIR for ~/.claude) in five mods, and hooks/design.ts (the one parser of a prompt's DESIGN block) in zetetic-insights and zetetic-autopilot, each with its test. After editing one, copy it over the others; this fails when a copy differs:

sh scripts/check-shared.sh

Installing

.claude-plugin/marketplace.json lists each mod as "source": "./mods/<mod>", so the repository is the marketplace. From another machine:

/plugin install <mod> --marketplace cdeust/claude-mods

y adds the marketplace, then the user scope. On this machine a folder marketplace reads the mods from the checkout, with no copy: claude plugin marketplace add <this folder>, then /plugin install <mod> and /reload-plugins after an edit.

Without write access to settings.json

claude plugin marketplace add and claude plugin install both write enabledPlugins and extraKnownMarketplaces into settings.json. Where that file cannot be changed, load the mods by directory instead: nothing is written, and each mod is registered for the session as <name>@inline.

MODS=/path/to/claude-mods/mods

# repeat --plugin-dir once per mod
claude \
  --plugin-dir $MODS/cortex-guard \
  --plugin-dir $MODS/cortex-wiki \
  --plugin-dir $MODS/zetetic-genius \
  --plugin-dir $MODS/zetetic-autopilot \
  --plugin-dir $MODS/zetetic-insights \
  --plugin-dir $MODS/mission-control \
  --plugin-dir $MODS/harness-fleet

# or one variable, colon separated
CLAUDE_CODE_PLUGIN_DIRS=$MODS/cortex-guard:$MODS/cortex-wiki:$MODS/zetetic-genius:$MODS/zetetic-autopilot:$MODS/zetetic-insights:$MODS/mission-control:$MODS/harness-fleet claude

# an alias in the shell profile: it sets MODS itself, because the alias body is single-quoted and
# is expanded each time it runs, not when the profile is read
alias claude-mods='MODS=/path/to/claude-mods/mods; CLAUDE_CODE_PLUGIN_DIRS=$MODS/cortex-guard:$MODS/cortex-wiki:$MODS/zetetic-genius:$MODS/zetetic-autopilot:$MODS/zetetic-insights:$MODS/mission-control:$MODS/harness-fleet claude'

Which form to prefer: an interactive session may ask for a login when CLAUDE_CONFIG_DIR points at an empty directory (seen once in an isolated directory, where headless claude -p did not ask). On the machine's own configuration directory, which is already logged in, that does not apply; use the repeated --plugin-dir or the alias there, and keep an isolated CLAUDE_CONFIG_DIR for tests only.

claude plugin list shows them under "Session-only plugins" with Status: loaded.

What then must hold:

  • The dependencies of a mod are resolved among the mods loaded in the same command, so load a mod together with what it names: zetetic-autopilot needs zetetic-genius; harness-fleet needs cortex-guard, zetetic-autopilot and zetetic-genius. A mod whose dependency is absent is listed disabled, with the error Dependency "<name>" is not installed.
  • Options cannot be set (they live in settings.json under pluginConfigs), so every default in a plugin.json has to be right on any machine:
ModOptionDefaultNotes
cortex-guardhygiene_script~/Developments/disk-hygiene/disk_hygiene.py~/ is the home of the user running the session, read at runtime. When the file is not there, one toast per session says hygiene script not found at <path>; worktrees are not registered; an empty value disables the registration without a toast. A python3 that fails to start gets one toast naming the cause, and no further worktree is registered for the session (no retry)
zetetic-geniusmode, classifier_modelobserve, haikuthe grade is one low-effort completion on the haiku alias
zetetic-autopilotpolicy_mode, quota_pressure_percent, max_parallel_agents, offload_threshold_chars, offload_preview_charsenforce, 80, 5, 30000, 2000the cap counts and refuses only the main loop's own spawns (a fork of main included): a subagent's nested spawn, a workflow script's agent() and a teammate are neither refused nor counted. A result past the threshold is written whole to a file in the session's tool-results directory (the engine's cleanupPeriodDays sweeps it, 30 days by default; the mod deletes nothing); the model reads the preview, the path and the size
mission-controlrendererautoauto draws pixels in kitty or Ghostty outside tmux (TMUX, TERM, TERM_PROGRAM, KITTY_WINDOW_ID), cells elsewhere; cells or pixels forces one
harness-fleetgithub_owner, refresh_on_startcdeust, truereads gh pr list, gh issue list and git remote
  • The machine must let the mods do what they ask: python3 (guard), gh and a route to api.github.com (fleet), the files under ~/.claude/plugins/ (fleet), pandoc and xelatex (wiki), and the model aliases (genius, autopilot).

Measured, on one Mac (Claude Code 2.1.293, no company sandbox): with a pristine settings.json holding {} and an isolated CLAUDE_CONFIG_DIR, loading the mods by CLAUDE_CODE_PLUGIN_DIRS lists them as loaded and leaves settings.json at {}; zetetic-autopilot loaded alone is disabled with the dependency error above.

Not measured: the managed-settings lock itself (it could not be reproduced), whether a company policy accepts --plugin-dir, any refusal of a real sandbox (blocked network, denied exec, unreadable ~/.claude), the model aliases, and whether /config lists the options of directory-loaded mods in an interactive session.

Source 25 files
hooks/register.tsx 498 lines
1import { atom, read, update } from 'claude-code'
2import type { AgentSpawnResult, EngineInterface, Hook, Register, TurnStepChunk, TurnStepResult } from 'claude-code'
3
4import type { ContextHealth, PhasesState, PolicyDecision, PolicyState, SpawnRoute } from '../types'
5import type { LoopCeilings } from './calibration'
6import { definitionOf, forgetDefinitions } from './definitions'
7import {
8  type Decided,
9  callEnded,
10  callOf,
11  callStarted,
12  carry,
13  decidedFor,
14  holdEffort,
15  resetEfforts,
16  resumed,
17  spawnAnswered,
18  spawnPending,
19  spawnsSettled,
20  stepEffort,
21  subagentEffort,
22} from './effort'
23import { readContext } from './measure'
24import { DEFAULT_PREVIEW_CHARS, DEFAULT_THRESHOLD_CHARS, offloadOptions } from './offload'
25import { type Sink, offloadBlocks } from './offloadrow'
26import { emptyPhases, erred, finished, isFileReadStep, isMainImplementation, spawned, startTurn, stepPhase, stepped } from './phases'
27import { crossed } from './context'
28import {
29  CHARS_PER_TOKEN,
30  OFFLOAD_TOOLS,
31  STUCK_ERRORS,
32  currentEffort,
33  defaultEffort,
34  effortFor,
35  escalate,
36  group,
37  pressureOf,
38} from './policy'
39import { type RouteFields, asWritten, keepRoute, marked, openRoutes, rewriteRoutes, routeOf } from './records'
40import { mainModelFor, routeAgentModel } from './route'
41import { checkConfig, gradeOf, readCeilings } from './reads'
42import { SPAWNS_CAP, clipped } from './spawns'
43import { dispatchOf, effortRowOf, modelRowOf } from './spawnrows'
44import { inBudget, maxParallelOption } from './concurrency'
45import { type GateSink, admit, configureGate, ended, released, resetGate, started } from './gate'
46
47const DECISIONS_CAP = 50 // source: bounds $.state size; a viewer shows the last rows only
48
49const context = atom({ plugin: 'zetetic-autopilot', key: 'context' } as const, null as ContextHealth | null)
50const policy = atom({ plugin: 'zetetic-autopilot', key: 'policy' } as const, {
51  mode: 'observe',
52  pressure: 'none',
53  quotaPercent: 80,
54  offloadThresholdChars: DEFAULT_THRESHOLD_CHARS,
55  offloadPreviewChars: DEFAULT_PREVIEW_CHARS,
56  decisions: [],
57  charsOffloaded: 0,
58  errorsInRow: 0,
59} as PolicyState)
60
61const phases = atom({ plugin: 'zetetic-autopilot', key: 'phases' } as const, emptyPhases() as PhasesState)
62
63const spawns = atom({ plugin: 'zetetic-autopilot', key: 'spawns' } as const, [] as SpawnRoute[])
64
65const decide = (p: PolicyState, d: PolicyDecision, charsOffloaded = 0): PolicyState => ({
66  ...p,
67  decisions: [...p.decisions, d].slice(-DECISIONS_CAP),
68  charsOffloaded: p.charsOffloaded + charsOffloaded,
69})
70
71// A failed read, logged once until its reason changes: the POLICY panel shows it, routing goes on
72// without what could not be read.
73async function note($: EngineInterface, subject: string, reason: string): Promise<void> {
74  const p = await read($, policy)
75  const last = p.decisions.findLast((d) => d.kind === 'unread' && d.subject === subject)
76  if (last?.to === reason) return
77  const at = await $.clock.now()
78  await update($, policy, (s) => decide(s, { at, kind: 'unread', subject, from: '', to: reason, applied: false }))
79}
80
81
82// The calibrated tool-loop rung per phase, read at each new main turn (reads.ts).
83let ceilings: LoopCeilings = {}
84
85// The full read, with the window broken down as /context does it: at start.
86async function refreshContext($: EngineInterface): Promise<void> {
87  const before = await read($, context)
88  const after = await readContext($, await $.session.usage({ breakdown: 'summary' }), before)
89  await update($, context, () => after)
90}
91
92// The step as it went out and what came back: its phase and its advisor calls, on its loop's row, and
93// whether the stuck escalation set its effort (`escalated`, counted on the run the step lands in).
94async function* tracked(
95  $: EngineInterface,
96  sent: { turnId: string; index: number; model: string; effort?: string | number; agentId?: string },
97  stream: AsyncGenerator<TurnStepChunk, TurnStepResult>,
98  escalated: boolean,
99): AsyncGenerator<TurnStepChunk, TurnStepResult> {
100  const r = yield* stream
101  const at = await $.clock.now()
102  const advisorCalls = (r.serverToolUses ?? []).filter((u) => u.name === 'advisor').length
103  // turn.start carries no loop id and fires for a subagent's turn too (measured 2026-10-14): main's
104  // row starts again at main's own first step of a new turn instead.
105  const isNewMainTurn = sent.agentId === undefined && (await read($, phases)).turnId !== sent.turnId
106  if (isNewMainTurn) await update($, phases, (s) => startTurn(s, sent.turnId, sent.model, at))
107  await update($, phases, (s) =>
108    stepped(s, {
109      loopId: sent.agentId ?? 'main',
110      model: r.usage?.model ?? sent.model,
111      // The effort the request ran at: the one sent, else the model's API default (policy.ts), so
112      // the insights ledger never keeps an effort it cannot calibrate.
113      effort: sent.effort === undefined ? defaultEffort(r.usage?.model ?? sent.model) : String(sent.effort),
114      phase: stepPhase(r.toolUses, r.answer),
115      fileRead: isFileReadStep(r.toolUses),
116      escalated,
117      advisorCalls,
118      at,
119    }),
120  )
121  return r
122}
123
124// A started subagent gets its row: the model the engine resolved, the phase its type names; and its
125// route, in $.state for the viewers and in $.store (`spawns:<start>:<session>`, spawns.ts) for whoever
126// reads the record after the session, so an outcome is attributed to the model that ran and the rule
127// that chose it.
128async function placed(
129  $: EngineInterface,
130  e: { subagentType: string; description: string },
131  r: AgentSpawnResult,
132  route: RouteFields,
133): Promise<AgentSpawnResult> {
134  if (r.deny !== undefined || r.agentId === undefined) return r
135  const at = await $.clock.now()
136  const id = r.agentId
137  await update($, phases, (s) => spawned(s, { id, type: e.subagentType, description: e.description, model: r.model, at }))
138  const record: SpawnRoute = clipped({ at, agentId: id, type: e.subagentType, ...route, ran: r.model })
139  await update($, spawns, (s) => [...s, asWritten(record)].slice(-SPAWNS_CAP))
140  await keepRoute($, record, (subject, reason) => note($, subject, reason))
141  return r
142}
143
144// The first step of an agent's run passed down the chain at its decided effort: its records say so, in state and store.
145async function markCarried($: EngineInterface, id: string): Promise<void> {
146  await update($, spawns, (s) => marked(s, id))
147  await rewriteRoutes($, (kept) => marked(kept, id), (subject, reason) => note($, subject, reason))
148}
149
150const onMeasure: Hook<'session.measure'> = async ($, e, next) => {
151  const before = await read($, context)
152  const after = await readContext($, e, before)
153  await update($, context, () => after)
154  await update($, policy, (p) => ({ ...p, pressure: pressureOf(after.rateLimits, p.quotaPercent, after.band) }))
155  const crossing = crossed(before, after)
156  if (crossing !== undefined)
157    $.ui.toast(
158      `context ${crossing}: ${group(after.tokens ?? 0)} tokens, the Stop guard will ${
159        crossing === 'hard' ? 'block the stop' : 'ask for a checkpoint'
160      }`,
161    )
162
163  return next(e)
164}
165
166// The turn main is in, set as its step goes out: the engine runs a step's tool calls, and so raises their spawns,
167// before the step's stream has ended, which is when its phases row records the turn (tracked).
168let mainTurnId: string | undefined
169
170// Main: the effort ladder from the graded rung, the stuck escalation, and the model under
171// quota. A subagent: the effort decided at its spawn (effort.ts), else as the engine sent it. Observed,
172// or applied under enforce. A generator, as the event streams.
173const onStep: Hook<'turn.step'> = async function* ($, e, next) {
174  if (e.agentId !== undefined) return yield* agentStep($, e, e.agentId, next)
175  mainTurnId = e.turnId
176  const p = await read($, policy)
177  const grade = await gradeOf($, (subject, reason) => note($, subject, reason))
178  const g = grade !== undefined && grade.turnId === e.turnId ? grade : undefined
179  const have = currentEffort(e.model, e.effort)
180  if (e.index === 0) ceilings = await readCeilings($, (subject, reason) => note($, subject, reason))
181  const phase = (await read($, phases)).loops.find((l) => l.id === 'main')?.phase
182  const loop = phase === undefined || phase === null || e.index === 0 ? undefined : ceilings[phase]
183  let target = effortFor(e.model, e.index, e.effort, p.pressure, g?.effort, loop) ?? have
184  let kind: PolicyDecision['kind'] = 'effort'
185  if (p.errorsInRow >= STUCK_ERRORS) {
186    const raised = escalate(target)
187    if (raised !== target) {
188      target = raised
189      kind = 'stuck'
190    }
191    await update($, policy, (s) => ({ ...s, errorsInRow: 0 }))
192  }
193  const model = mainModelFor(e.model, p.pressure)
194  // The escalation set this step's effort only when it is applied; that holds too when the raised effort
195  // is the one the step came with (it goes out unchanged, no row), since the ladder would have sent it lower.
196  const escalated = kind === 'stuck' && p.mode === 'enforce'
197  if (target === have && model === undefined) return yield* tracked($, e, next(e), escalated)
198  const applied = p.mode === 'enforce'
199  const at = await $.clock.now()
200  const who = `main step ${e.index} (${e.model})`
201  if (target !== have) {
202    const subject = g !== undefined && e.index === 0 ? `${who} · ${g.taskClass}` : loop !== undefined ? `${who} · ${phase} calibrated` : who
203    await update($, policy, (s) => decide(s, { at, kind, subject, from: String(e.effort ?? 'default'), to: target, applied }))
204  }
205  if (model !== undefined && e.index === 0)
206    await update($, policy, (s) =>
207      decide(s, { at, kind: 'model', subject: 'main · quota pressure', from: e.model, to: model, applied }),
208    )
209  if (!applied) return yield* tracked($, e, next(e), escalated)
210  const out = { ...e, ...(target !== have ? { effort: target } : {}), ...(model !== undefined ? { model } : {}) }
211  return yield* tracked($, out, next(out), escalated)
212}
213
214// A subagent's step: at the effort decided at its spawn under enforce, else as the engine sent it (effort.ts). The
215// decision's row was logged once, at the spawn, not on each step. A step of an agent with no decision while spawns
216// are in flight may belong to one of them (a background run starts before its spawn answers): it waits for their
217// answers, then reads again. An event, not a timer: the engine answers a spawn without waiting on the run.
218async function* agentStep(
219  $: EngineInterface,
220  e: Parameters<Hook<'turn.step'>>[1],
221  id: string,
222  next: Parameters<Hook<'turn.step'>>[2],
223): AsyncGenerator<TurnStepChunk, TurnStepResult> {
224  if ((await read($, policy)).mode !== 'enforce') return yield* tracked($, e, next(e), false)
225  const inFlight = decidedFor(id) === undefined ? spawnsSettled(id) : undefined
226  if (inFlight !== undefined) await inFlight
227  const effort = stepEffort(decidedFor(id), e.effort)
228  if (effort === undefined) return yield* tracked($, e, next(e), false)
229  const out = effort === e.effort ? e : { ...e, effort }
230  try {
231    return yield* tracked($, out, next(out), false)
232  } finally {
233    // The step was passed down at it, whether its stream then ended, failed or was let go: the run's record says so,
234    // once. The mark is bookkeeping: its failure is a row, never the step's outcome.
235    if (carry(id)) await markCarried($, id).catch((error: unknown) => note($, 'spawn records', `not marked: ${String(error).slice(0, 100)}`).catch(() => undefined))
236  }
237}
238
239// The cap's view of the mod: its rows go to the POLICY panel, an agent the engine says is gone closes its row.
240const gateSink = ($: EngineInterface): GateSink => ({
241  decide: async (d) => {
242    await update($, policy, (s) => decide(s, d))
243  },
244  note: (subject, reason) => note($, subject, reason),
245  gone: async (id, at) => {
246    await update($, phases, (s) => finished(s, id, at))
247  },
248})
249
250// Subagents: the model the call or the definition pinned stands, under any pressure; an inheriting
251// type runs on the family its kind and the turn's class call for. The quota's cap on how many run at
252// once comes first (admit), for the main loop's own spawns only (inBudget).
253const onSpawn: Hook<'agent.spawn'> = async ($, e, next) => {
254  const p = await read($, policy)
255  if (!inBudget(e)) return spawnRouted($, e, next, p)
256  const gate = await admit($, e, p, gateSink($))
257  if (gate.deny !== undefined) return { deny: gate.deny }
258  try {
259    const r = await spawnRouted($, e, next, p)
260    if (r.deny === undefined && r.agentId !== undefined) started(r.agentId)
261    return r
262  } finally {
263    released(gate.held)
264  }
265}
266
267async function spawnRouted(
268  $: EngineInterface,
269  e: Parameters<Hook<'agent.spawn'>>[1],
270  next: Parameters<Hook<'agent.spawn'>>[2],
271  p: PolicyState,
272): Promise<AgentSpawnResult> {
273  // The grade counts only for the main turn it was bound to: a later turn nobody graded (a slash
274  // command, a notification) routes without one, as turn.step does.
275  const grade = e.parentAgentId === undefined ? await gradeOf($, (subject, reason) => note($, subject, reason)) : undefined
276  const turnClass = grade !== undefined && grade.turnId !== null && grade.turnId === mainTurnId ? grade.taskClass : undefined
277  // Read whatever the call says: the record names the definition's model beside the call's. A fork has no
278  // definition: it runs as its parent, and the engine ignores a rewrite of its model or of a workflow agent's
279  // content (AgentSpawnInput.model, .workflow), so neither is sent one; nor is a teammate given DESIGN or the table.
280  const rewritable = !e.fork && e.workflow === undefined
281  const fixed = !rewritable || e.isTeammate === true
282  const found = e.fork ? {} : await definitionOf($, e.subagentType)
283  if ('unread' in found && e.model === undefined) await note($, `${e.subagentType} definition`, found.unread)
284  const definition = 'unread' in found ? undefined : found
285  const call = callOf(e.tool_use_id)
286  // A resume names its agent (2.1.304 `resume.agentId`): its new run has carried nothing, before that run can step.
287  const resuming = (e as { resume?: { agentId?: unknown } }).resume?.agentId
288  const d = await dispatchOf($, e, { fixed, seen: call !== undefined, resumed: typeof resuming === 'string', callModel: e.model, definition })
289  for (const [subject, why] of d.refused) await note($, subject, why)
290  const row = d.row
291  if (row !== undefined) await update($, policy, (s) => decide(s, row))
292  const steer = d.steer
293  const routed = routeAgentModel(e.model, definition, e.parentModel, steer)
294  const applied = p.mode === 'enforce' && routed.model !== undefined && rewritable
295  const from = e.model ?? definition?.model ?? `inherit ${e.parentModel}`
296  const to = routed.model
297  if (to !== undefined) {
298    const at = await $.clock.now()
299    await update($, policy, (s) => decide(s, modelRowOf(at, { type: e.subagentType, steer, from, to, applied })))
300  }
301  // The effort of its steps (effort.ts): decided before the spawn is passed on, held as soon as it answers.
302  const effort = subagentEffort({ fixed, call, definition, steer, grade: turnClass === undefined ? undefined : grade?.effort })
303  // Pending until held: a step of the agent that comes before the spawn answers waits for it (agentStep).
304  const settle = effort.effort === undefined ? undefined : spawnPending()
305  if (typeof resuming === 'string') resumed(resuming)
306  let r: AgentSpawnResult
307  try {
308    r = await next(applied ? { ...e, model: routed.model } : e)
309    // Held before the answer is announced: a step it releases reads the decision.
310    if (effort.effort !== undefined && r.deny === undefined && r.agentId !== undefined) holdEffort(r.agentId, effort.effort)
311    if (r.agentId !== undefined) spawnAnswered(r.agentId)
312  } finally {
313    settle?.()
314  }
315  const cls = steer.by === 'table' ? steer.cls : turnClass
316  if (effort.effort !== undefined && r.agentId !== undefined) {
317    const at = await $.clock.now()
318    await update($, policy, (s) => decide(s, effortRowOf(at, { type: e.subagentType, cls, effort, applied: p.mode === 'enforce' })))
319  }
320  // A resumed agent's record names the effort its steps keep, the one held since its first spawn; its run has
321  // carried nothing yet.
322  const held = effort.effort === undefined && r.agentId !== undefined ? decidedFor(r.agentId) : undefined
323  // An engine whose resume names no agent (2.1.292 types): the reset comes once the spawn answered.
324  if (held !== undefined && r.agentId !== undefined && typeof resuming !== 'string') resumed(r.agentId)
325  const kept: Decided = held === undefined ? effort : { effort: held, reason: 'resumed' }
326  return placed($, e, r, routeOf({ routed, applied, steer, effort: kept, enforce: p.mode === 'enforce' }))
327}
328
329// The turns main was last told in, each once a turn and not once a call: the user (a toast) and the model (a
330// reminder in the call's result). Reset with the session. The model's is given back when its call was refused,
331// so the next call of the turn carries it; the user's is not (a toast says what main did, and the refusal
332// is on the screen already).
333let toastedTurn: string | null | undefined
334let remindedTurn: string | null | undefined
335
336// What the model reads after the result of its first implementing call of a turn (the engine's declarations:
337// a tool.call result's `context` is "what the model reads after the tool's result and the user never sees").
338// It is the instruction; the user is told the fact in a toast and never this.
339const DELEGATE_REMINDER =
340  'zetetic-autopilot, owner rule 2026-10-15: implementation belongs to a subagent. This session\'s main loop just ran a ' +
341  'tool that changes files or state; delegate implementation to a subagent (Agent tool) and keep this loop for orchestration.'
342
343// Owner rule, 2026-10-15: no task runs in the global session, all is delegated. A call of the main loop
344// that writes code or changes things is the work a subagent is for: a row each time, a toast to the user and a
345// reminder to the model once a turn. It warns and never blocks: the call goes ahead. Answers whether the model
346// is owed its reminder on this call's result, and for which turn.
347async function nudgeMain($: EngineInterface, e: { tool: string }): Promise<{ turnId: string | null; remind: boolean }> {
348  const turnId = (await read($, phases)).turnId
349  const at = await $.clock.now()
350  await update($, policy, (s) =>
351    decide(s, { at, kind: 'work', subject: `main · ${e.tool}`, from: 'main loop', to: 'delegate to a subagent', applied: false }),
352  )
353  if (toastedTurn !== turnId) {
354    toastedTurn = turnId
355    $.ui.toast(`main ran ${e.tool} (owner rule 2026-10-15: implementation is a subagent's work)`)
356  }
357  const remind = remindedTurn !== turnId
358  if (remind) remindedTurn = turnId
359
360  return { turnId, remind }
361}
362
363// An Agent call is known to the spawn its tool raises by its tool_use_id, while the tool runs (effort.ts).
364const onToolCall: Hook<'tool.call'> = async ($, e, next) => {
365  const call = e as { tool: string; tool_use_id?: string; effort?: unknown }
366  const id = call.tool === 'Agent' ? call.tool_use_id : undefined
367  if (id === undefined) return toolCalled($, e, next)
368  callStarted(id, call.effort)
369  try {
370    return await toolCalled($, e, next)
371  } finally {
372    callEnded(id)
373  }
374}
375
376// The stuck signal: main's tool errors in a row, read by the next turn.step.
377const toolCalled: Hook<'tool.call'> = async ($, e, next) => {
378  const agentId = (e as { agentId?: string }).agentId
379  const nudge = agentId === undefined && isMainImplementation(e.tool, e) ? await nudgeMain($, e) : undefined
380  const ran = await next(e)
381  const isBlocked = ran.deny !== undefined || ran.isError === true
382  if (agentId === undefined) await update($, policy, (s) => ({ ...s, errorsInRow: isBlocked ? s.errorsInRow + 1 : 0 }))
383  if (isBlocked) await update($, phases, (s) => erred(s, agentId ?? 'main'))
384  if (nudge?.remind !== true) return ran
385  // A refused call has no `context` to carry it: the reminder is still owed to the turn's next call.
386  if (ran.deny !== undefined) {
387    if (remindedTurn === nudge.turnId) remindedTurn = undefined
388    return ran
389  }
390
391  // The result as core made it, whole (`ref` names its messages), with the reminder added to its context.
392  return { ...ran, context: [...(ran.context ?? []), DELEGATE_REMINDER] }
393}
394
395// Memory offload (offload.ts, offloadrow.ts): a stream tool's result past the threshold is written whole to a
396// file in the session's tool-results directory, which comes from the transcript path every classic SessionStart
397// carries; the engine's retention sweeps it (`cleanupPeriodDays`, 30 days by default) and this mod deletes
398// nothing. The stored row carries a preview, the path and the size; a result that cannot be written stays
399// whole, and a row says why.
400let transcriptPath: string | undefined
401
402const onAppend: Hook<'session.append'> = async ($, e, next) => {
403  const tool = e.origin.kind === 'tool' ? e.origin.tool : undefined
404  if (tool === undefined || !OFFLOAD_TOOLS.has(tool)) return next(e)
405  const p = await read($, policy)
406  const sink: Sink = {
407    note: (subject, reason) => note($, subject, reason),
408    offloaded: async (plan, applied) => {
409      const kept = plan.chars - plan.message.length
410      const d: PolicyDecision = {
411        at: await $.clock.now(),
412        kind: 'offload',
413        subject: tool,
414        from: `${group(plan.chars)} chars`,
415        to: `${plan.files[0]?.path} · about ${group(Math.round(kept / CHARS_PER_TOKEN))} tokens kept out of context`,
416        applied,
417      }
418      await update($, policy, (s) => decide(s, d, applied ? kept : 0))
419    },
420  }
421  const options = { thresholdChars: p.offloadThresholdChars, previewChars: p.offloadPreviewChars }
422  const content = await offloadBlocks($, e.uuid, tool, e.message.content, { options, enforce: p.mode === 'enforce', transcriptPath, sink })
423
424  return next(content === undefined ? e : { ...e, message: { ...e.message, content } })
425}
426
427// The stuck counter is a turn's own; main's ends with its turn.
428const onComplete: Hook<'turn.complete'> = async ($, e, next) => {
429  if (e.agentId === undefined) await update($, policy, (s) => ({ ...s, errorsInRow: 0 }))
430  else ended(e.agentId)
431  const at = await $.clock.now()
432  await update($, phases, (s) => finished(s, e.agentId ?? 'main', at))
433
434  return next(e)
435}
436
437// What a session starts from: no definition, phase or route known, this session's store key, the options
438// checked, the configured fields set afresh (a hot reload keeps $.state from the previous load).
439async function begin($: EngineInterface, mode: PolicyState['mode'], configured: (p: PolicyState) => PolicyState, capProblem?: string): Promise<void> {
440  forgetDefinitions()
441  resetGate()
442  resetEfforts()
443  mainTurnId = undefined
444  toastedTurn = undefined
445  remindedTurn = undefined
446  await update($, phases, () => emptyPhases())
447  await update($, spawns, () => [])
448  await openRoutes($, (subject, reason) => note($, subject, reason))
449  await checkConfig($, mode, (subject, reason) => note($, subject, reason))
450  await update($, policy, configured)
451  if (capProblem !== undefined) await note($, 'agent cap option', capProblem)
452  await refreshContext($)
453}
454
455export const register: Register = (on, options) => {
456  const mode: PolicyState['mode'] = options.policy_mode === 'enforce' ? 'enforce' : 'observe'
457  const quotaPercent = Number(options.quota_pressure_percent ?? 80)
458  const offload = offloadOptions(options.offload_threshold_chars, options.offload_preview_chars)
459  const cap = maxParallelOption(options.max_parallel_agents)
460  configureGate(cap.max)
461  // A hot reload keeps $.state from the previous load: the configured fields are set afresh.
462  const configured = (p: PolicyState): PolicyState => ({
463    ...p,
464    mode,
465    quotaPercent,
466    offloadThresholdChars: offload.options.thresholdChars,
467    offloadPreviewChars: offload.options.previewChars,
468  })
469
470  on('session.start', async ($, e, next) => {
471    await begin($, mode, configured, cap.problem)
472
473    return next(e)
474  })
475
476  // /clear, /resume and /branch reset $.state and never fire session.start again.
477  on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
478    await begin($, mode, configured, cap.problem)
479
480    return next(e)
481  })
482
483  // Every start, /clear, /resume and /branch included: the transcript names the tool-results directory.
484  on('classic.SessionStart', async ($, e, next) => {
485    transcriptPath = e.transcript_path
486    for (const problem of offload.problems) await note($, 'offload option', problem)
487
488    return next(e)
489  })
490
491  on('session.measure', onMeasure)
492  on('turn.step', onStep)
493  on('agent.spawn', onSpawn)
494  on('tool.call', onToolCall)
495  on('session.append', { door: 'tool-result' }, onAppend)
496  on('turn.complete', onComplete)
497}
498
hooks/calibration.ts 23 lines
1// The per-phase tool-loop effort the insights mod calibrated from its ledger, read from the file it
2// writes (a mod never reads another's store; the insights mod depends on this one, not the reverse).
3
4import type { Phase } from '../types'
5import type { Effort } from './policy'
6
7// source: zetetic-insights hooks/learn.ts CALIBRATION_PATH, the file it writes.
8export const CALIBRATION_PATH = '~/.claude/zetetic-insights/calibration.json'
9
10export type LoopCeilings = Partial<Record<Phase, Effort>>
11
12const LEVELS: readonly string[] = ['low', 'medium', 'high']
13
14// Version 1, a `phases` object of low/medium/high; anything else is refused with the reason.
15export const parseCeilings = (text: string): LoopCeilings => {
16  const raw = JSON.parse(text) as { version?: unknown; phases?: Record<string, unknown> }
17  if (raw.version !== 1 || typeof raw.phases !== 'object' || raw.phases === null)
18    throw new Error('calibration.json is not version 1 with a phases object')
19  const bad = Object.entries(raw.phases).find(([, e]) => typeof e !== 'string' || !LEVELS.includes(e))
20  if (bad !== undefined) throw new Error(`calibration.json: ${bad[0]} has effort ${String(bad[1])}, not low, medium or high`)
21  return raw.phases as LoopCeilings
22}
23
hooks/definitions.ts 68 lines
1// Reading agent definitions off the machine: where a `~/` path lands, and the definition file a subagent type
2// names (agents.ts holds the pure side). The engine's `$` is passed in; nothing here keeps state.
3
4import type { EngineInterface } from 'claude-code'
5
6import { type Definition, INHERITING_BUILT_INS, INSTALLED_PLUGINS_PATH, ancestors, definitionPaths, parseDefinition } from './agents'
7import { placePath } from './paths'
8
9export type Unread = { unread: string; absent: boolean }
10
11// Where a `~/` path lands on this machine: HOME, else USERPROFILE, and CLAUDE_CONFIG_DIR for what lives
12// in the engine's config directory (paths.ts). No home to place it is an error with that reason.
13export async function expandHome($: EngineInterface, path: string): Promise<string> {
14  if (!path.startsWith('~/')) return path
15  const placed = placePath(
16    { home: await $.env.get('HOME'), userProfile: await $.env.get('USERPROFILE'), configDir: await $.env.get('CLAUDE_CONFIG_DIR') },
17    path,
18  )
19  if ('reason' in placed) throw new Error(placed.reason)
20
21  return placed.path
22}
23
24// The folders whose `.claude/agents/` may hold a project agent: the working directory and each
25// folder above it up to the repository root (the first with a `.git`), so a session started in a
26// subdirectory finds the project's agents. No repository above: the working directory alone.
27async function projectDirs($: EngineInterface, cwd: string): Promise<string[]> {
28  const chain = ancestors(cwd)
29  for (const [i, dir] of chain.entries()) if (await $.fs.exists(`${dir}/.git`)) return chain.slice(0, i + 1)
30  return [cwd]
31}
32
33export async function readDefinition($: EngineInterface, type: string): Promise<Definition | Unread> {
34  try {
35    const claudeDir = (await expandHome($, '~/.claude')).replace(/\/$/, '')
36    const installed = type.includes(':') ? await $.fs.read(await expandHome($, INSTALLED_PLUGINS_PATH)) : undefined
37    const cwd = await $.session.cwd()
38    const paths = definitionPaths(type, installed, claudeDir, cwd, type.includes(':') ? [] : await projectDirs($, cwd))
39    for (const path of paths) {
40      // A file that exists and cannot be read throws: it is not "no such file".
41      if (await $.fs.exists(path)) return parseDefinition(String(await $.fs.read(path)))
42    }
43    return paths.length === 0
44      ? { unread: 'no installed plugin provides it', absent: true }
45      : { unread: `no file at ${paths.join(', ')}`, absent: true }
46  } catch (error) {
47    return { unread: String(error).slice(0, 120), absent: false }
48  }
49}
50
51// Agent definitions: what the type's file pins, or why it could not be read. A definition found, and
52// a file proven absent, or no installed plugin providing the type (`absent`: the records answered
53// "no such file" / "no such plugin"), are remembered for
54// the session; a read that failed, or a record that could not be read, is asked again at the next
55// spawn, so a transient error does not stand until /clear (issue #11). The built-ins measured to
56// inherit pin nothing and have no file.
57const definitions = new Map<string, Definition | Unread>()
58
59export async function definitionOf($: EngineInterface, type: string): Promise<Definition | Unread> {
60  const known = definitions.get(type)
61  if (known !== undefined) return known
62  const found = INHERITING_BUILT_INS.includes(type) ? {} : await readDefinition($, type)
63  if (!('unread' in found) || found.absent) definitions.set(type, found)
64  return found
65}
66
67export const forgetDefinitions = (): void => definitions.clear()
68
hooks/effort.ts 177 lines
1// A subagent's effort: who decides it, and what the mod keeps to apply it on each of the agent's steps.
2// source: ADR-9850 (the invariant I1-I4, and why the decision is made at agent.spawn and applied at turn.step); ADR-9851
3// (DESIGN and the dispatch table decide before the grade). agent.spawn can neither read nor set an effort; turn.step rewrites one, and the rewritten effort is the one in the
4// API request (measured 2026-10-19, ~/.claude/fleet/research/mods-auto-dispatch-gap.md § 2.2). The two maps below
5// live in this module's memory, as gate.ts's do, and are reset with the session.
6
7import { type Definition, pinnedModel } from './agents'
8import type { Steer } from './dispatch'
9import type { Effort } from './policy'
10import { ROUTES_PER_SESSION } from './spawns'
11
12// The codes under which another's effort stands and nothing is rewritten:
13//   call        the Agent call set an effort
14//   definition  the agent's definition sets an effort
15//   pinned      the definition pins a model: not an inheriting type, the engine's effort stands
16//   fixed       a fork, a workflow agent or a teammate: the engine runs it as its own
17type Stands = 'call' | 'definition' | 'pinned' | 'fixed'
18
19// The codes under which nothing could be decided, so the engine's effort stands too:
20//   unseen      no Agent call was seen for the spawn (a hook's $.agent.spawn, a resume): its effort is unknown
21//   unread      the definition could not be read: whether it sets an effort is unknown
22//   ungraded    no grade bound to main's turn, or the spawn is a subagent's own
23type Undecided = 'unseen' | 'unread' | 'ungraded'
24
25// Why an agent's steps run at the effort they run at, the short code kept in its spawn record. Decided here: `design`
26// the spawn prompt's DESIGN block, `table` the dispatch table's rung for the task's class (dispatch.ts), `grade` the
27// effort of the grade of main's turn (zetetic-genius, class -> effort); `resumed`, a spawn raised again for an agent
28// already held (a message resumed it): its steps keep the effort decided at its first spawn. `unclassified`: the table
29// was asked and the classifier gave no class, so the engine's effort stands (never the grade's in its place).
30export type EffortReason = 'design' | 'table' | 'grade' | 'resumed' | 'unclassified' | Stands | Undecided
31
32// What the spawn tells: `call` is the Agent call as tool.call saw it (undefined when none was seen), `definition`
33// what the agent's file sets (undefined when it could not be read), `steer` what DESIGN or the table say (dispatch.ts),
34// `grade` the effort of the grade bound to main's turn (undefined when there is none, or when a subagent spawns).
35export type SpawnFacts = {
36  fixed: boolean
37  call: { effort?: unknown } | undefined
38  definition: Definition | undefined
39  steer: Steer
40  grade: Effort | undefined
41}
42
43export type Decided = { effort: Effort | undefined; reason: EffortReason }
44
45// First match wins; every fact that makes the effort someone else's comes before DESIGN, the table and the grade.
46export const subagentEffort = (f: SpawnFacts): Decided => {
47  const none = (reason: EffortReason): Decided => ({ effort: undefined, reason })
48  if (f.fixed) return none('fixed')
49  if (f.call === undefined) return none('unseen')
50  if (f.call.effort !== undefined) return none('call')
51  if (f.definition === undefined) return none('unread')
52  if (f.definition.effort !== undefined) return none('definition')
53  if (pinnedModel(f.definition) !== undefined) return none('pinned')
54  if ((f.steer.by === 'design' || f.steer.by === 'table') && f.steer.effort !== undefined) return { effort: f.steer.effort, reason: f.steer.by }
55  if (f.steer.by === 'unclassified') return none('unclassified')
56  if (f.grade === undefined) return none('ungraded')
57  return { effort: f.grade, reason: 'grade' }
58}
59
60// source: own choice, the routes a session keeps (ROUTES_PER_SESSION): an agent the store no longer names is one this
61// map may forget too. Far above the agents one session runs at once (max_parallel_agents, 5 by default).
62export const EFFORTS_CAP = ROUTES_PER_SESSION
63
64// `key` is set last; past `cap` the oldest entries go. A Map iterates in insertion order.
65export const keep = <V>(m: Map<string, V>, key: string, value: V, cap: number): void => {
66  m.delete(key)
67  m.set(key, value)
68  for (const oldest of m.keys()) {
69    if (m.size <= cap) return
70    m.delete(oldest)
71  }
72}
73
74// The Agent calls running now, by tool_use_id, each with the effort it named, as it came: any value stands, one of the
75// five levels or not (2.1.304 also takes `lower`/`higher`). An entry lives while its tool runs: the Agent tool raises
76// agent.spawn from inside its call, with the tool_use_id the tool.call input carries.
77const calls = new Map<string, { effort?: unknown }>()
78
79// The decided effort of each agent the mod decided one for, by agent id, and whether a step of its current run was
80// passed down the chain at it. Kept past the agent's turn.complete: a message resumes an ended agent under the same id, and its resumed
81// run keeps its effort. Bounded by EFFORTS_CAP.
82const decided = new Map<string, { effort: Effort; carried: boolean }>()
83
84// The spawns in flight whose decision is not held yet (agent id unknown until the spawn answers). A background
85// launch starts the agent's run before its spawn answers (2.1.304), so a step may come first and waits for these.
86const pending = new Set<Promise<void>>()
87
88// The agents whose spawn answered (decided or not), by id: a step of one never waits, its decision is known. Bounded by
89// EFFORTS_CAP; a forgotten one only waits while spawns are pending.
90const answered = new Map<string, true>()
91
92// The steps parked on their own agent's answer, by agent id: its spawn answering releases them.
93const waiting = new Map<string, () => void>()
94
95export const isEffort = (v: unknown): v is Effort => v === 'low' || v === 'medium' || v === 'high' || v === 'xhigh' || v === 'max'
96
97export const callStarted = (toolUseId: string, effort: unknown): void => {
98  // JSON's null is a call that named none; any other value is the call's own, and stands.
99  keep(calls, toolUseId, effort === undefined || effort === null ? {} : { effort }, EFFORTS_CAP)
100}
101
102export const callEnded = (toolUseId: string): void => {
103  calls.delete(toolUseId)
104}
105
106// The Agent call a spawn belongs to, as tool.call saw it; undefined when none is running under that id.
107export const callOf = (toolUseId: string): { effort?: unknown } | undefined => calls.get(toolUseId)
108
109export const holdEffort = (agentId: string, effort: Effort): void => {
110  keep(decided, agentId, { effort, carried: false }, EFFORTS_CAP)
111}
112
113export const decidedFor = (agentId: string): Effort | undefined => decided.get(agentId)?.effort
114
115// A step was passed down the chain at the agent's decided effort; true the first time for its current run.
116export const carry = (agentId: string): boolean => {
117  const d = decided.get(agentId)
118  if (d === undefined || d.carried) return false
119  d.carried = true
120  return true
121}
122
123export const carried = (agentId: string): boolean => decided.get(agentId)?.carried === true
124
125// A resumed run has carried nothing yet.
126export const resumed = (agentId: string): void => {
127  const d = decided.get(agentId)
128  if (d !== undefined) d.carried = false
129}
130
131// A spawn whose decision will be held once it answers; the function returned settles it, held or not.
132export const spawnPending = (): (() => void) => {
133  let settle = (): void => undefined
134  const p = new Promise<void>((resolve) => (settle = resolve))
135  pending.add(p)
136  return () => {
137    pending.delete(p)
138    settle()
139  }
140}
141
142export const spawnAnswered = (agentId: string): void => {
143  keep(answered, agentId, true, EFFORTS_CAP)
144  waiting.get(agentId)?.()
145  waiting.delete(agentId)
146}
147
148// Its own spawn's answer, for a step parked on it: resolved by spawnAnswered, or let go once the step moved on.
149const ownAnswer = (agentId: string): { answered: Promise<void>; forget: () => void } => {
150  let release = (): void => undefined
151  const answeredNow = new Promise<void>((r) => (release = r))
152  waiting.set(agentId, release)
153  return { answered: answeredNow, forget: () => waiting.delete(agentId) }
154}
155
156// What a step of an agent whose spawn has not answered waits for: every pending spawn's answer; undefined when its
157// spawn answered or none is pending. The engine answers a spawn without waiting on the run (2.1.304), so it settles.
158// Whichever comes first: its own answer, or every pending spawn's (an agent no pending spawn will name).
159export const spawnsSettled = (agentId: string): Promise<void> | undefined => {
160  if (pending.size === 0 || answered.has(agentId)) return undefined
161  const own = ownAnswer(agentId)
162  return Promise.race([own.answered, Promise.all([...pending])]).then(own.forget)
163}
164
165export const resetEfforts = (): void => {
166  calls.clear()
167  decided.clear()
168  pending.clear()
169  answered.clear()
170  waiting.clear()
171}
172
173// The effort a subagent's step goes out at: the decided one, on a step that carries an effort level (absent: a model
174// without effort, which is not given one; a number is not a level). Undefined: the step goes out as it came.
175export const stepEffort = (designed: Effort | undefined, sent: unknown): Effort | undefined =>
176  designed !== undefined && isEffort(sent) ? designed : undefined
177
hooks/measure.ts 57 lines
1// The context window as the engine measures it, with the Stop guard's checkpoint thresholds beside it.
2
3import type { EngineInterface } from 'claude-code'
4
5import type { ContextHealth } from '../types'
6import { THRESHOLDS_PATH, band, matchThresholds, serversOf } from './context'
7import { expandHome } from './definitions'
8
9export type Measured = {
10  context: {
11    tokens?: number
12    window: number
13    percent?: number
14    breakdown?: {
15      categories: readonly { name: string; tokens: number }[]
16      mcpTools: readonly { serverName: string; tokens: number }[]
17    }
18  }
19  rateLimits: readonly { kind: string; percentUsed: number }[]
20  cost?: { usd: number }
21}
22
23// A measure carries no breakdown; the one read before is kept until the next full read.
24export async function readContext($: EngineInterface, m: Measured, before: ContextHealth | null): Promise<ContextHealth> {
25  const model = await $.session.model()
26  let warn: number | null = null
27  let hard: number | null = null
28  let source = THRESHOLDS_PATH
29  try {
30    const t = matchThresholds(await $.fs.read(await expandHome($, THRESHOLDS_PATH)), model)
31    if (t !== undefined) {
32      warn = t.warn
33      hard = t.hard
34    } else source = `${THRESHOLDS_PATH} has no match for ${model}`
35  } catch (error) {
36    // The file is the Stop guard's. A refusal, a missing file and a file that is not JSON all leave
37    // no thresholds; the viewer is told which, with the reason, instead of reading all three as absent.
38    source = `${THRESHOLDS_PATH} unreadable: ${(error instanceof Error ? error.message : String(error)).slice(0, 100)}`
39  }
40  const reading = { tokens: m.context.tokens ?? null, warn, hard }
41  return {
42    ...reading,
43    window: m.context.window,
44    percent: m.context.percent ?? null,
45    model,
46    thresholdsSource: source,
47    rateLimits: m.rateLimits.map((r) => ({ kind: r.kind, percentUsed: r.percentUsed })),
48    usd: m.cost?.usd ?? null,
49    categories:
50      m.context.breakdown?.categories.map((c) => ({ name: c.name, tokens: c.tokens })) ?? before?.categories ?? [],
51    mcpServers: m.context.breakdown === undefined ? (before?.mcpServers ?? []) : serversOf(m.context.breakdown.mcpTools),
52    band: band(reading),
53    readAt: await $.clock.now(),
54  }
55}
56
57
hooks/offload.ts 140 lines
1// Lossless offload: a stream tool's result past the threshold is written whole to a file in the
2// session's own tool-results directory, and the model reads a preview, the path, the size and an
3// instruction to Read or grep the file. The threshold and the preview bound what enters the
4// context; they never bound what is kept. Pure: the plan says what to write and what to show, the
5// register file does the writing.
6
7// source: Claude Code 2.1.300 persists a tool result past `ise(name, maxResultSizeChars, ceiling)`
8// itself: Bash 30000 (`bashOutputMaxChars` default), Grep 20000, Glob and WebSearch 50000 (their
9// 100000 is capped by the 50000 ceiling), WebFetch 50000 (read in the binary's strings, 2026-10-15;
10// docs: code.claude.com tools-reference). 30000 is the native Bash default, so a result the engine
11// already keeps (Grep past 20000, Bash past 30000) is never wrapped twice and Glob, WebFetch and
12// WebSearch gain the 30000..50000 band the engine leaves inline.
13export const DEFAULT_THRESHOLD_CHARS = 30000
14// source: the preview the engine leaves in context for a result it persisted (`oxe = 2000`).
15export const DEFAULT_PREVIEW_CHARS = 2000
16
17// source: the engine's file API rejects a write over 4 MiB (index.d.ts, `$.fs`); a UTF-16 code unit
18// is at most 3 UTF-8 bytes and a surrogate pair 4, so 1 000 000 units are at most 4 000 000 bytes.
19export const PART_CHARS = 1_000_000
20
21// The engine's own pointers to what it already keeps (`<persisted-output>`) or could not keep
22// (`<truncated-output>`): a result that starts with one is not wrapped again.
23const NATIVE_MARKERS = ['<persisted-output>', '<truncated-output>']
24const MARKER = 'zetetic-autopilot-offload'
25
26export type OffloadOptions = { thresholdChars: number; previewChars: number }
27
28export type OffloadFile = { path: string; text: string }
29export type OffloadPlan = { files: OffloadFile[]; message: string; chars: number; lines: number }
30
31const isCount = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v > 0
32
33// The options as the user set them, each checked: a value that is not a positive whole number is
34// named, and the default stands in its place. Left unchecked, NaN would make every result "past"
35// the threshold.
36export const offloadOptions = (
37  threshold: unknown,
38  preview: unknown,
39): { options: OffloadOptions; problems: string[] } => {
40  const problems: string[] = []
41  const pick = (name: string, value: unknown, fallback: number): number => {
42    if (value === undefined) return fallback
43    if (isCount(value)) return value
44    problems.push(`${name}=${JSON.stringify(value)} is not a positive whole number; using ${fallback}`)
45    return fallback
46  }
47  const thresholdChars = pick('offload_threshold_chars', threshold, DEFAULT_THRESHOLD_CHARS)
48  const asked = pick('offload_preview_chars', preview, DEFAULT_PREVIEW_CHARS)
49  // A preview as long as the result would only add the pointer's lines to it.
50  const previewChars = Math.min(asked, thresholdChars)
51  if (previewChars < asked) problems.push(`offload_preview_chars=${asked} is past the threshold; using ${previewChars}`)
52  return { options: { thresholdChars, previewChars }, problems }
53}
54
55// The directory the engine keeps this session's tool results in: the transcript
56// `<projects>/<project>/<session>.jsonl` names it `<projects>/<project>/<session>/tool-results`.
57// Undefined when the path is not that of the session `sessionId` (a /clear or a resume moved on).
58export const toolResultsDir = (transcriptPath: string | undefined, sessionId: string): string | undefined => {
59  if (transcriptPath === undefined || !transcriptPath.endsWith('.jsonl')) return undefined
60  const stem = transcriptPath.slice(0, -'.jsonl'.length)
61  const sep = stem.includes('/') || !stem.includes('\\') ? '/' : '\\'
62  const segments = stem.split(sep)
63  // The last segment must BE the session id, and no segment may climb out of the directory.
64  if (segments.includes('..') || segments[segments.length - 1] !== sessionId) return undefined
65  return `${stem}${sep}tool-results`
66}
67
68// A tool_use id is `toolu_...` or `call_...`; anything else a file name could not carry is replaced.
69const fileSafe = (id: string): string => id.replace(/[^A-Za-z0-9_-]/g, '_')
70
71// Splits at PART_CHARS, never between the two halves of a surrogate pair; the parts joined are the text.
72export const parts = (text: string): string[] => {
73  const out: string[] = []
74  let at = 0
75  while (at < text.length) {
76    let end = Math.min(at + PART_CHARS, text.length)
77    const last = text.charCodeAt(end - 1)
78    if (end < text.length && last >= 0xd800 && last <= 0xdbff) end -= 1
79    out.push(text.slice(at, end))
80    at = end
81  }
82  return out
83}
84
85// The start of the text to show: up to `limit` characters, cut at a line break when one falls in the
86// second half (the engine's own rule for its preview), never inside a surrogate pair.
87export const previewOf = (text: string, limit: number): string => {
88  let end = Math.min(limit, text.length)
89  const last = text.charCodeAt(end - 1)
90  if (end < text.length && last >= 0xd800 && last <= 0xdbff) end -= 1
91  const head = text.slice(0, end)
92  if (end === text.length) return head
93  const lineEnd = head.lastIndexOf('\n')
94  return lineEnd > end / 2 ? head.slice(0, lineEnd) : head
95}
96
97const count = (n: number): string => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ' ')
98
99// pre:  `dir` is the session's tool-results directory, `toolUseId` the block's id, `joined` says the
100//       text is several text blocks joined by a newline.
101// post: undefined when the text is within the threshold or is one of the engine's own pointers;
102//       otherwise `files` hold the text exactly (their texts joined are `text`, byte for byte) and
103//       `message` is the preview, the path or paths, the size in characters and lines, and the
104//       instruction to read the file. Nothing in it is a cut of the text except the preview, which
105//       is named as the start.
106export const planOffload = (
107  text: string,
108  toolUseId: string,
109  dir: string,
110  options: OffloadOptions,
111  joined = false,
112): OffloadPlan | undefined => {
113  if (text.length <= options.thresholdChars) return undefined
114  if (NATIVE_MARKERS.some((m) => text.startsWith(m))) return undefined
115  const sep = dir.includes('/') || !dir.includes('\\') ? '/' : '\\'
116  const pieces = parts(text)
117  const name = `autopilot-${fileSafe(toolUseId)}`
118  const files = pieces.map((piece, i) => ({
119    path: `${dir}${sep}${name}${pieces.length === 1 ? '' : `.${i + 1}`}.txt`,
120    text: piece,
121  }))
122  const lines = text.split('\n').length
123  const where =
124    files.length === 1
125      ? `Full output saved to: ${files[0]?.path}`
126      : `Full output saved in ${files.length} files of at most ${count(PART_CHARS)} characters, to be read in order:\n${files.map((f) => f.path).join('\n')}`
127  const preview = previewOf(text, options.previewChars)
128  const message = [
129    `<${MARKER}>`,
130    `Output too large (${count(text.length)} characters, ${count(lines)} lines). ${where}`,
131    ...(joined ? ['The file holds the result\'s text blocks joined by a newline.'] : []),
132    `Preview (the first ${count(preview.length)} characters):`,
133    preview,
134    'Nothing was removed: Read or grep the file for the rest.',
135    `</${MARKER}>`,
136  ].join('\n')
137
138  return { files, message, chars: text.length, lines }
139}
140
hooks/offloadrow.ts 125 lines
1// The offload as the engine sees it: the blocks of one stored tool-result row, the files written for
2// the long ones, the blocks the model will read. The plan itself is offload.ts (pure); this is the
3// part that writes and reports, with the policy state and its decision rows behind a `Sink`.
4import type { EngineInterface } from 'claude-code'
5
6import { type OffloadOptions, type OffloadPlan, planOffload, toolResultsDir } from './offload'
7import { resultText } from './policy'
8
9export type Block = { type: string; tool_use_id?: unknown; content?: unknown }
10
11// What the offload tells the rest of the mod: a result that stays whole and why, and one offloaded.
12export type Sink = {
13  note: (subject: string, reason: string) => Promise<void>
14  offloaded: (plan: OffloadPlan, applied: boolean) => Promise<void>
15}
16
17export type Context = { options: OffloadOptions; enforce: boolean; transcriptPath: string | undefined; sink: Sink }
18
19// The first plan whose files do not exist yet: `id`, then `id-2`, `id-3`... Nothing is ever overwritten.
20async function freshPlan(
21  $: EngineInterface,
22  text: string,
23  id: string,
24  dir: string,
25  ctx: Context,
26  joined: boolean,
27): Promise<OffloadPlan | undefined> {
28  for (let n = 1; ; n++) {
29    const plan = planOffload(text, n === 1 ? id : `${id}-${n}`, dir, ctx.options, joined)
30    if (plan === undefined) return undefined
31    let taken = false
32    for (const f of plan.files) taken = taken || (await $.fs.exists(f.path))
33    if (!taken) return plan
34  }
35}
36
37// Writes each file whole; the reason of the first failure (4 MiB cap, a refusal, a full disk), else undefined.
38async function writeAll($: EngineInterface, plan: OffloadPlan): Promise<string | undefined> {
39  try {
40    for (const f of plan.files) await $.fs.write(f.path, f.text)
41  } catch (error) {
42    return String(error).slice(0, 160)
43  }
44  return undefined
45}
46
47// The block the model will read in place of `block`: the pointer, as the string or the text block
48// the result came as.
49const pointer = <B extends Block>(block: B, message: string): B =>
50  typeof block.content === 'string' ? { ...block, content: message } : { ...block, content: [{ type: 'text', text: message }] }
51
52// pre:  `block` is a tool_result whose text is past the threshold (planOffload decides about the
53//       engine's own pointers); `dir` is the session's tool-results directory or undefined.
54// post: every block gets its own file name (the tool_use id, else `<row uuid>-<block index>`) and an
55//       existing file is never overwritten (the next free `-N` suffix is used); the block unchanged (and a note saying why) when the directory is unknown or the write was
56//       refused; under observe the block unchanged and nothing written; else the file(s) hold the
57//       text whole and the returned block is the pointer. Nothing is ever dropped.
58async function offloadOne<B extends Block>(
59  $: EngineInterface,
60  tool: string,
61  block: B,
62  text: string,
63  dir: string | undefined,
64  ctx: Context,
65  fallbackId: string,
66): Promise<B> {
67  const id = typeof block.tool_use_id === 'string' ? block.tool_use_id : fallbackId
68  const joined = Array.isArray(block.content) && block.content.length > 1
69  const first = planOffload(text, id, dir ?? '', ctx.options, joined)
70  if (first === undefined) return block
71  if (dir === undefined) {
72    await ctx.sink.note('tool-results directory', 'the session directory is not known; the result stays whole')
73    return block
74  }
75  // Under enforce the name is the first free one; under observe nothing is written, so the plan stands.
76  let plan = first
77  if (ctx.enforce) {
78    try {
79      plan = (await freshPlan($, text, id, dir, ctx, joined)) ?? first
80    } catch (error) {
81      await ctx.sink.note(`${tool} result`, `not written, stays whole: ${String(error).slice(0, 160)}`)
82      return block
83    }
84    const failure = await writeAll($, plan)
85    if (failure !== undefined) {
86      await ctx.sink.note(`${tool} result`, `not written, stays whole: ${failure}`)
87      return block
88    }
89  }
90  await ctx.sink.offloaded(plan, ctx.enforce)
91
92  return ctx.enforce ? pointer(block, plan.message) : block
93}
94
95// The row's blocks with the long results offloaded; undefined when none changed.
96export async function offloadBlocks<B extends Block>(
97  $: EngineInterface,
98  rowId: string,
99  tool: string,
100  blocks: readonly B[],
101  ctx: Context,
102): Promise<B[] | undefined> {
103  let dir: string | undefined
104  let known = false
105  let changed = false
106  const out: B[] = []
107  for (const [index, block] of blocks.entries()) {
108    const text = block.type === 'tool_result' ? resultText(block.content) : undefined
109    if (text === undefined || text.length <= ctx.options.thresholdChars) {
110      out.push(block)
111      continue
112    }
113    // Asked once, and only when a result is past the threshold: most results never need the directory.
114    if (!known) {
115      dir = toolResultsDir(ctx.transcriptPath, await $.session.id())
116      known = true
117    }
118    const next = await offloadOne($, tool, block, text, dir, ctx, `${rowId}-${index}`)
119    changed = changed || next !== block
120    out.push(next)
121  }
122
123  return changed ? out : undefined
124}
125
hooks/phases.ts 382 lines
1// Pure side of the phases: which phase a loop (main or a subagent) is in, read off what it does.
2// The owner's list (2026-10-14): planning, analysis, design, verification, test, review, report;
3// implementation is added for the steps that write code, which none of the seven names.
4
5import type { AdvisorUse, LoopPhases, Phase, PhaseRun, PhasesState } from '../types'
6import { type ShellCommand, shellCommands } from './shell'
7
8export const PHASES: readonly Phase[] = [
9  'planning',
10  'analysis',
11  'design',
12  'implementation',
13  'verification',
14  'test',
15  'review',
16  'report',
17]
18
19// source: ~/.claude/plugins/.../zetetic-team-subagents/commands/zetetic/engineering-loop.md, its
20// nine steps; the cycle ledger records these, the view shows the phases (reconcilable both ways).
21export const ENGINEERING_LOOP: Record<string, Phase> = {
22  check: 'planning',
23  recall: 'analysis',
24  refine: 'planning',
25  investigate: 'analysis',
26  implement: 'implementation',
27  verify: 'verification',
28  benchmark: 'test',
29  review: 'review',
30  remember: 'report',
31}
32
33// When one step does several things, the phase it is in is the furthest along this order.
34const RANK: Record<Phase, number> = {
35  analysis: 0,
36  planning: 1,
37  design: 2,
38  implementation: 3,
39  verification: 4,
40  test: 5,
41  review: 6,
42  report: 7,
43}
44
45// An agent type's own phase, from its role (the zetetic agents' descriptions); a type not listed
46// is placed by what it does, step by step.
47const BY_TYPE: [RegExp, Phase][] = [
48  [/(^|:)(Plan|orchestrator|dispatch)$/, 'planning'],
49  [/(^|:)(Explore|git-historian|research-scientist|data-scientist|professor)$/, 'analysis'],
50  [/(^|:)(architect|ux-designer)$/, 'design'],
51  [/(^|:)(test-engineer|experiment-runner)$/, 'test'],
52  [/(^|:)(code-reviewer|security-auditor|reviewer-academic|advisor)$/, 'review'],
53  [/(^|:)(memory-writer)$/, 'report'],
54  [/(^|:)(engineer|frontend-engineer|refactorer|simplifier|dba|devops-engineer|mlops|latex-engineer|paper-writer)$/, 'implementation'],
55]
56
57export const typePhase = (type: string): Phase | undefined => BY_TYPE.find(([re]) => re.test(type))?.[1]
58
59const PLANNING_TOOLS = new Set(['EnterPlanMode', 'ExitPlanMode', 'TaskCreate', 'TaskUpdate', 'TodoWrite'])
60const READING_TOOLS = new Set(['Read', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'LSP', 'ToolSearch'])
61const WRITING_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit'])
62// source: Claude Code tool names; the file reads any model can do. Not READING_TOOLS, which also holds
63// web and search tools, and not the analysis phase, which also holds delegations, recalls and skills.
64export const FILE_READ_TOOLS = new Set(['Read', 'Grep', 'Glob'])
65
66// The one definition of a mechanical step: it calls tools and every call is a file read.
67export const isFileReadStep = (uses: readonly { name: string }[]): boolean => uses.length > 0 && uses.every((u) => FILE_READ_TOOLS.has(u.name))
68
69// Each pattern names a command by its head, the first words of a segment (`a && b`, `a; b`, `a | b`),
70// so a word inside an argument (`grep pytest`, `git commit -m "fix tsc"`) names nothing.
71// An inline check (`python3 -c '...; assert ...'`) carries its own `;`: read on the whole line.
72const ASSERT_RUN = /(^|&&\s*)python3? -c .*\bassert\b/
73const TEST_RUN = /^(python3? -m (pytest|unittest)|pytest|(npm|pnpm|yarn|bun) (run )?test|claude plugin test|go test|cargo test|(npx (-y )?)?(jest|vitest)|(sh|bash) \S*(mutation_check|reproduce)\S*)/
74const CHECK_RUN = /^((uvx )?ruff\S*|(npx (-y )?(-p typescript )?)?tsc|mypy|pyright|(npx (-y )?)?eslint|claude plugin validate|python3? \S*check_craftsmanship|(sh|bash) \S*check-shared|python3? -m mcp_server\.doctor)\b/
75const REVIEW_RUN = /^gh pr (review|diff)\b|^gh pr comment\b.*ZETETIC-REVIEW/
76const DELIVER_RUN = /^(git (commit|push|tag)|gh pr (create|merge)|gh issue create)\b/
77const READ_RUN = /^(ls|cat|head|tail|sed -n|grep|rg|find|wc|git (log|show|status|blame|diff)|gh (pr|issue) (view|list)|which|pwd|echo)\b/
78const NEUTRAL_RUN = /^(cd|export|set|source|true)\b/
79const DESIGN_FILE = /(^|\/)(docs\/adr\/|wiki\/|design\/)|ADR-\d|\.(md|tex)$/
80const TEST_FILE = /(^|\/)(tests?|tests_py|__tests__)\/|\.(test|spec)\.[a-z]+$|_test\.[a-z]+$/
81
82const SKILLS: [RegExp, Phase][] = [
83  [/brainstorm|writing-plans|plan$/, 'planning'],
84  [/debugging|understand-codebase|recall|research/, 'analysis'],
85  [/design|architecture|adr|wiki-author/, 'design'],
86  [/test-driven|testing/, 'test'],
87  [/verif|integrity|provenance/, 'verification'],
88  [/review/, 'review'],
89]
90
91const CORTEX = /^mcp__plugin_hypermnesia-mcp_cortex__/
92const ARCH = /^mcp__plugin_ai-architect-mcp-codebase_ai-architect__/
93const PRD = /^mcp__plugin_ai-architect-mcp-spec_prd-gen__/
94
95const field = (input: unknown, name: string): string => {
96  const v = (input as Record<string, unknown> | null)?.[name]
97  return typeof v === 'string' ? v : ''
98}
99
100const segmentPhase = (segment: string): Phase | undefined => {
101  if (segment === '' || NEUTRAL_RUN.test(segment)) return undefined
102  if (REVIEW_RUN.test(segment)) return 'review'
103  if (TEST_RUN.test(segment)) return 'test'
104  if (CHECK_RUN.test(segment)) return 'verification'
105  if (DELIVER_RUN.test(segment)) return 'report'
106  return READ_RUN.test(segment) ? 'analysis' : 'implementation'
107}
108
109// The first line only (a heredoc's body is data); the furthest phase of its segments.
110const bashPhase = (command: string): Phase => {
111  const line = command.split('\n')[0] ?? ''
112  if (ASSERT_RUN.test(line)) return 'test'
113  return line
114    .split(/&&|\|\||;|\|/)
115    .map((s) => segmentPhase(s.trim().replace(/^([A-Z_]+=\S+\s+)+/, '')))
116    .filter((p): p is Phase => p !== undefined)
117    .reduce<Phase>((best, p) => (RANK[p] > RANK[best] ? p : best), 'analysis')
118}
119
120const mcpPhase = (name: string): Phase | undefined => {
121  if (CORTEX.test(name)) {
122    if (/__(remember|checkpoint|record_session_end)$/.test(name)) return 'report'
123    if (/__wiki_(write|adr)$/.test(name)) return 'design'
124    return 'analysis'
125  }
126  if (PRD.test(name)) return /validate|verification/.test(name) ? 'verification' : 'design'
127  if (ARCH.test(name)) return /verif|gates|semantic_diff|validate/.test(name) ? 'verification' : 'analysis'
128  return undefined
129}
130
131// The phase one tool call puts its loop in; undefined when the call says nothing about it.
132export const toolPhase = (name: string, input: unknown): Phase | undefined => {
133  if (PLANNING_TOOLS.has(name)) return 'planning'
134  if (READING_TOOLS.has(name)) return 'analysis'
135  if (WRITING_TOOLS.has(name)) {
136    const path = field(input, 'file_path') || field(input, 'notebook_path')
137    if (TEST_FILE.test(path)) return 'test'
138    return DESIGN_FILE.test(path) ? 'design' : 'implementation'
139  }
140  if (name === 'Bash') return bashPhase(field(input, 'command'))
141  if (name === 'Agent') return typePhase(field(input, 'subagent_type'))
142  if (name === 'Skill') return SKILLS.find(([re]) => re.test(field(input, 'skill')))?.[1]
143  return mcpPhase(name)
144}
145
146// Commands that run the repository, the host or the session's worktrees: orchestration, whatever bashPhase
147// calls an unrecognised head. A change to a source file is not made by these.
148// source: the orchestrator's own first turn (fetch, worktree add, hygiene register-worktree, mkdir)
149const PLUMBING_RUN = /^(git|gh|claude|mkdir|rmdir|sleep|python3? \S*disk_hygiene\S*)\b/
150
151// git verbs that rewrite files of the working tree, which the plumbing above does not otherwise do, behind
152// any of git's global options (`-C <dir>`, `-c <k=v>`, `--git-dir`, `--work-tree`).
153// source: git's own manuals for apply, am, restore, clean, mv, rm, cherry-pick, revert, merge, pull, rebase,
154// reset --hard, stash (bare, push, save, pop, apply, branch; not list or show) and `checkout [<tree-ish>] -- <path>`,
155// and git(1) for the global options; the review's probes P3 and N1 (2026-10-16) named the verbs and the options
156const GIT_OPTION = String.raw`\s+(?:-C\s+\S+|-c\s+\S+|--(?:git-dir|work-tree|namespace)(?:=|\s+)\S+|-P|--no-pager|--bare)`
157const GIT_VERB = String.raw`(?:(?:apply|am|restore|clean|mv|rm|cherry-pick|revert|merge|pull|rebase)(?=\s|$)|reset\s(?:.*\s)?--hard(?=\s|$)|stash(?:$|\s+-|\s+(?:push|save|pop|apply|branch)(?=\s|$))|checkout\b.*\s--(?=\s|$))`
158const GIT_CHANGE = new RegExp(String.raw`^git(?:${GIT_OPTION})*\s+${GIT_VERB}`)
159// Runs that read or check and write nothing: the repository's own gates (`node --test`, `node <script> --check`),
160// jq (it has no in-place mode), and inline Python, unless its code writes (PY_WRITES, read on the quoted text).
161const READ_ONLY_RUN = /^(node\b.*\s--(test|check)\b|jq\b)/
162const PY_INLINE = /^python3? -c\b/
163const PY_WRITES = /\.write(_text|_bytes)?\(|\bopen\([^)]*,\s*['"][wax+]/
164// source: own choice, the places a session keeps throwaway output (the null device, the system and session temp dirs)
165const SCRATCH = /^(\/dev\/|\/tmp\/|\/private\/tmp\/|\$\{?TMPDIR\b)/
166// What stands before a command's own head: an assignment (`CI=1 cmd`), and the shell's reserved words and grouping
167// (`if`, `then`, `do`, `{`, `!`...). A loop or case header (`for f in ...`) runs nothing itself.
168// source: XCU 2.4 Reserved Words, 2.9.1 Simple Commands (variable assignments before the command name)
169const ASSIGNMENT = /^[A-Za-z_]\w*=\S*(\s+|$)/
170const RESERVED = /^(!|\{|\}|if|then|else|elif|fi|do|done|while|until|esac|time)(\s+|$)/
171const HEADER = /^(for|select|case)\s/
172
173// A simple command's head and arguments, less what stands before the head.
174const headed = (bare: string): string => {
175  let s = bare
176  for (let prev = ''; prev !== s; ) {
177    prev = s
178    s = s.replace(ASSIGNMENT, '').replace(RESERVED, '')
179  }
180  return HEADER.test(s) ? '' : s
181}
182
183const commandChanges = (c: ShellCommand): boolean => {
184  if (c.targets.some((t) => !SCRATCH.test(t))) return true
185  const s = headed(c.bare)
186  if (s === '') return false
187  if (GIT_CHANGE.test(s)) return true
188  if (PY_INLINE.test(s)) return PY_WRITES.test(c.raw)
189  if (PLUMBING_RUN.test(s) || READ_ONLY_RUN.test(s)) return false
190  return segmentPhase(s) === 'implementation'
191}
192
193// Work the owner's rule hands to a subagent ("aucune tâche ne tourne en session globale"): a file the main
194// loop writes (code or test; a document is design, the orchestrator's own), or a shell command that changes
195// things in any of the commands the shell runs (shell.ts; a quoted span, a heredoc body or a comment is none):
196// a redirection into a file, a git verb that rewrites the working tree, or the implementation phase of
197// bashPhase less the plumbing and the read-only runs above. Reads, checks, tests and delivery are orchestration.
198export const isMainImplementation = (name: string, input: unknown): boolean => {
199  if (WRITING_TOOLS.has(name)) return toolPhase(name, input) !== 'design'
200  if (name !== 'Bash') return false
201  return shellCommands(field(input, 'command')).some(commandChanges)
202}
203
204// A step's phase: the furthest along of its calls; a step that calls nothing and answers is the
205// report. Undefined when nothing in it names a phase (the loop stays where it was).
206export const stepPhase = (uses: readonly { name: string; input: unknown }[], answer: string): Phase | undefined => {
207  if (uses.length === 0) return answer.trim() === '' ? undefined : 'report'
208  return uses
209    .map((u) => toolPhase(u.name, u.input))
210    .filter((p): p is Phase => p !== undefined)
211    .reduce<Phase | undefined>((best, p) => (best === undefined || RANK[p] > RANK[best] ? p : best), undefined)
212}
213
214export const LOOPS_CAP = 12 // source: own choice, the running agents and the last few done fit one pane
215
216export const emptyPhases = (): PhasesState => ({ turnId: null, loops: [], advisor: { session: 0, uses: [] } })
217
218// A loop keeps its place in the list; a new one goes last, the oldest finished ones make room.
219const withLoop = (s: PhasesState, loop: LoopPhases): PhasesState => {
220  if (s.loops.some((l) => l.id === loop.id)) return { ...s, loops: s.loops.map((l) => (l.id === loop.id ? loop : l)) }
221  const loops = [...s.loops, loop]
222  let excess = loops.length - LOOPS_CAP
223  return {
224    ...s,
225    loops: loops.filter((l) => {
226      if (excess <= 0 || l.status !== 'done' || l.id === 'main') return true
227      excess -= 1
228      return false
229    }),
230  }
231}
232
233// Main's row, reset at each turn: its phases are the turn's.
234export const startTurn = (s: PhasesState, turnId: string, model: string, at: number): PhasesState =>
235  withLoop({ ...s, turnId }, {
236    id: 'main',
237    type: 'main',
238    description: 'main loop',
239    model,
240    effort: null,
241    phase: null,
242    runs: [],
243    status: 'running',
244    advisorCalls: 0,
245    wrote: false,
246    updatedAt: at,
247  })
248
249// A count the runs carry since a version (`reads`, `escalated`): its sum when every run carries it; a
250// run recorded before it was counted leaves the sum absent.
251const summed = (runs: readonly PhaseRun[], key: 'reads' | 'escalated'): { reads?: number; escalated?: number } =>
252  runs.every((r) => r[key] !== undefined) ? { [key]: runs.reduce((n, r) => n + (r[key] ?? 0), 0) } : {}
253
254// The runs an agent made before its type was known, as one run of the type's phase.
255const merged = (runs: readonly PhaseRun[], phase: Phase, at: number): PhaseRun => ({
256  phase,
257  effort: runs[runs.length - 1]?.effort ?? null,
258  steps: runs.reduce((n, r) => n + r.steps, 0),
259  errors: runs.reduce((n, r) => n + r.errors, 0),
260  since: runs[0]?.since ?? at,
261  ...summed(runs, 'reads'),
262  ...summed(runs, 'escalated'),
263})
264
265// A started subagent's row. Its steps may come in before the spawn answers (the engine runs the
266// loop meanwhile): a row they opened is completed here, its runs and status kept.
267export const spawned = (
268  s: PhasesState,
269  a: { id: string; type: string; description: string; model: string; at: number },
270): PhasesState => {
271  const phase = typePhase(a.type) ?? null
272  const before = s.loops.find((l) => l.id === a.id)
273  if (before !== undefined)
274    return withLoop(s, {
275      ...before,
276      type: a.type,
277      description: a.description,
278      phase: phase ?? before.phase,
279      runs: phase === null ? before.runs : [merged(before.runs, phase, a.at)],
280    })
281  return withLoop(s, {
282    id: a.id,
283    type: a.type,
284    description: a.description,
285    model: a.model,
286    effort: null,
287    phase,
288    runs: phase === null ? [] : [{ phase, effort: null, steps: 0, errors: 0, since: a.at, reads: 0, escalated: 0 }],
289    status: 'running',
290    advisorCalls: 0,
291    wrote: false,
292    updatedAt: a.at,
293  })
294}
295
296const opened = (st: Step): LoopPhases => ({
297  id: st.loopId,
298  type: st.loopId === 'main' ? 'main' : 'agent',
299  description: st.loopId === 'main' ? 'main loop' : 'subagent',
300  model: st.model,
301  effort: st.effort,
302  phase: null,
303  runs: [],
304  status: 'running',
305  advisorCalls: 0,
306  wrote: false,
307  updatedAt: st.at,
308})
309
310export type Step = {
311  loopId: string
312  model: string
313  effort: string | null
314  phase: Phase | undefined
315  fileRead: boolean // isFileReadStep of the step's tool calls
316  escalated: boolean // the stuck escalation set the effort the step was sent at (PhaseRun.escalated)
317  advisorCalls: number
318  at: number
319}
320
321// A step joins the last run: each count the run carries grows by what the step is; a count the run was
322// recorded without stays absent, since its earlier steps were never counted.
323const joined = (last: PhaseRun, st: Step): PhaseRun => ({
324  ...last,
325  steps: last.steps + 1,
326  ...(last.reads === undefined ? {} : { reads: last.reads + (st.fileRead ? 1 : 0) }),
327  ...(last.escalated === undefined ? {} : { escalated: last.escalated + (st.escalated ? 1 : 0) }),
328})
329
330// An agent whose type names a phase stays in it (a reviewer reading files is still reviewing);
331// main and an unplaced type move with what each step does.
332export const stepped = (s: PhasesState, st: Step): PhasesState => {
333  const loop = s.loops.find((l) => l.id === st.loopId) ?? opened(st)
334  const fixed = loop.type !== 'main' && typePhase(loop.type) !== undefined
335  const phase = fixed ? loop.phase : (st.phase ?? loop.phase)
336  const last = loop.runs[loop.runs.length - 1]
337  const runs =
338    phase === null
339      ? loop.runs
340      : last !== undefined && last.phase === phase && last.effort === st.effort
341        ? [...loop.runs.slice(0, -1), joined(last, st)]
342        : [...loop.runs, { phase, effort: st.effort, steps: 1, errors: 0, since: st.at, reads: st.fileRead ? 1 : 0, escalated: st.escalated ? 1 : 0 }]
343  const advisor = loop.type === 'main' && st.advisorCalls > 0 ? adviced(s.advisor, s.turnId, loop, st) : s.advisor
344  return {
345    ...withLoop(s, {
346      ...loop,
347      model: st.model,
348      effort: st.effort,
349      phase,
350      runs,
351      advisorCalls: loop.advisorCalls + st.advisorCalls,
352      wrote: loop.wrote || st.phase === 'implementation' || st.phase === 'design' || st.phase === 'test',
353      updatedAt: st.at,
354    }),
355    advisor,
356  }
357}
358
359export const USES_CAP = 20 // source: own choice, the pane lists the last advisor calls only
360
361// The advisor (a server tool of the main loop) is counted with when it was called: before the
362// turn wrote anything, after, or in the step that answered.
363const adviced = (a: PhasesState['advisor'], turnId: string | null, loop: LoopPhases, st: Step): PhasesState['advisor'] => {
364  const when: AdvisorUse['when'] = st.phase === 'report' ? 'at-completion' : loop.wrote ? 'after-write' : 'before-write'
365  const use: AdvisorUse = { at: st.at, turnId, phase: loop.phase, when, calls: st.advisorCalls }
366  return { session: a.session + st.advisorCalls, uses: [...a.uses, use].slice(-USES_CAP) }
367}
368
369// A tool call of the loop failed or was refused: counted on the run it happened in, the evidence
370// the insights mod learns each phase's effort from.
371export const erred = (s: PhasesState, loopId: string): PhasesState => {
372  const loop = s.loops.find((l) => l.id === loopId)
373  const last = loop?.runs[loop.runs.length - 1]
374  if (loop === undefined || last === undefined) return s
375  return withLoop(s, { ...loop, runs: [...loop.runs.slice(0, -1), { ...last, errors: last.errors + 1 }] })
376}
377
378export const finished = (s: PhasesState, loopId: string, at: number): PhasesState => {
379  const loop = s.loops.find((l) => l.id === loopId)
380  return loop === undefined ? s : withLoop(s, { ...loop, status: 'done', updatedAt: at })
381}
382
hooks/context.ts 56 lines
1import type { ContextHealth } from '../types'
2
3// source: ~/.claude/ctxguard-thresholds.json, the file stop-context-guard.py (zetetic
4// plugin) reads: first substring match on the lowercased model wins, else `default`.
5export const THRESHOLDS_PATH = '~/.claude/ctxguard-thresholds.json'
6
7export type Thresholds = { warn: number; hard: number }
8
9type ThresholdsFile = {
10  models?: { match: string; warn: number; hard: number }[]
11  default?: Thresholds
12}
13
14export const matchThresholds = (fileText: string, model: string): Thresholds | undefined => {
15  let parsed: ThresholdsFile
16  try {
17    parsed = JSON.parse(fileText) as ThresholdsFile
18  } catch (error) {
19    throw new Error(`ctxguard-thresholds.json is not valid JSON (${error instanceof Error ? error.message : String(error)})`.slice(0, 160))
20  }
21  const m = model.toLowerCase()
22  const hit = (parsed.models ?? []).find((row) => m.includes(row.match.toLowerCase()))
23  return hit === undefined ? parsed.default : { warn: hit.warn, hard: hit.hard }
24}
25
26export type Band = ContextHealth['band']
27
28export const band = (c: Pick<ContextHealth, 'tokens' | 'warn' | 'hard'>): Band => {
29  if (c.tokens === null) return 'unknown'
30  if (c.hard !== null && c.tokens >= c.hard) return 'hard'
31  if (c.warn !== null && c.tokens >= c.warn) return 'warn'
32  return 'measured'
33}
34
35// MCP tool schemas grouped by server, largest first: what each server costs on every request.
36export const serversOf = (
37  tools: readonly { serverName: string; tokens: number }[],
38): { server: string; tools: number; tokens: number }[] => {
39  const by = new Map<string, { tools: number; tokens: number }>()
40  for (const t of tools) {
41    const row = by.get(t.serverName) ?? { tools: 0, tokens: 0 }
42    by.set(t.serverName, { tools: row.tools + 1, tokens: row.tokens + t.tokens })
43  }
44  return [...by.entries()]
45    .map(([server, row]) => ({ server, ...row }))
46    .sort((a, b) => b.tokens - a.tokens)
47}
48
49// A crossing is a transition into a worse band; the same band again says nothing.
50export const crossed = (before: ContextHealth | null, after: ContextHealth): Band | undefined => {
51  const b = after.tokens === null ? 'unknown' : band(after)
52  const a = before === null ? 'measured' : band(before)
53  const rank: Record<Band, number> = { unknown: 0, measured: 0, warn: 1, hard: 2 }
54  return rank[b] > rank[a] ? b : undefined
55}
56
hooks/policy.ts 99 lines
1// Pure policy: what the mod would change on a request, a subagent or a tool result.
2// Observed (logged) or enforced, the decision is the same function of the same facts.
3
4export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
5export type Pressure = 'none' | 'quota' | 'context'
6export type PolicyMode = 'observe' | 'enforce'
7
8// source: platform.claude.com/docs/en/models/haiku-5-5/overview § How it compares (read
9// 2026-10-07), the API's default effort per model: Fable 5.1 `high`, Opus 5.5 `medium`,
10// Sonnet 5.5 `high`, Haiku 5.5 `medium`. ~/.claude/reference/model-behavior.md § Effort agrees
11// on Fable and Opus (Opus `low`/`medium` strong; Sonnet respects effort strictly).
12const DEFAULT_EFFORT: { match: string; effort: Effort }[] = [
13  { match: 'fable', effort: 'high' },
14  { match: 'opus', effort: 'medium' },
15  { match: 'sonnet', effort: 'high' },
16  { match: 'haiku', effort: 'medium' },
17]
18const RANK: Record<Effort, number> = { low: 0, medium: 1, high: 2, xhigh: 3, max: 4 }
19
20const isEffort = (v: unknown): v is Effort => typeof v === 'string' && v in RANK
21
22export const defaultEffort = (model: string): Effort => {
23  const m = model.toLowerCase()
24  return DEFAULT_EFFORT.find((row) => m.includes(row.match))?.effort ?? 'medium'
25}
26
27// The owner's ladder (2026-10-07): the first request of a turn keeps its effort, the tool-loop
28// requests after it run at medium; under quota or context pressure the loop runs at low and the
29// first request drops to medium at most. `base` is the effort the request classifier chose for
30// this turn (classify.ts); it replaces the session setting as the rung the ladder starts from,
31// so a `routine` turn runs its whole loop at low and a `critical` one keeps high on its first
32// request. Without a base the ladder never raises. `loop` is the tool-loop rung the insights
33// calibrated for the phase main is in (calibration.ts); medium without one. It is a ceiling like
34// the rest: it never lifts a request above its base.
35export const effortFor = (
36  model: string,
37  index: number,
38  current: unknown,
39  pressure: Pressure,
40  base?: Effort,
41  loop: Effort = 'medium',
42): Effort | undefined => {
43  const have = isEffort(current) ? current : defaultEffort(model)
44  const now = base ?? have
45  const ceiling: Effort = index === 0 ? (pressure === 'none' ? now : 'medium') : pressure === 'none' ? loop : 'low'
46  const target = RANK[ceiling] < RANK[now] ? ceiling : now
47  return target === have ? undefined : target
48}
49
50// Pressure: the five-hour window past the threshold, else the context past its warn mark.
51export const pressureOf = (
52  rateLimits: readonly { kind: string; percentUsed: number }[],
53  quotaPercent: number,
54  contextBand: 'measured' | 'warn' | 'hard' | 'unknown',
55): Pressure => {
56  const fiveHour = rateLimits.find((r) => r.kind === 'five_hour')
57  if (fiveHour !== undefined && fiveHour.percentUsed >= quotaPercent) return 'quota'
58  if (contextBand === 'warn' || contextBand === 'hard') return 'context'
59  return 'none'
60}
61
62// A subagent is not touched by pressure: the model and the effort the orchestrator designed (the call's,
63// else the definition's) run as designed, whatever the quota or the context. Quota limits how many
64// subagents run at once instead (concurrency.ts).
65
66// Memory offload (offload.ts): a result of these tools past the threshold is written whole to a
67// file. Only tools whose output is a stream (not a document); a third-party tool's is not ours.
68export const OFFLOAD_TOOLS = new Set(['Bash', 'Grep', 'Glob', 'WebFetch', 'WebSearch'])
69
70// source: the rule of thumb the context breakdown uses, about four characters a token.
71export const CHARS_PER_TOKEN = 4
72
73// The effort a request carries now: its own setting, else the model's default.
74export const currentEffort = (model: string, current: unknown): Effort =>
75  isEffort(current) ? current : defaultEffort(model)
76
77// source: effort-calibration.md task table, "genuinely stuck / surprising result → high".
78export const STUCK_ERRORS = 3 // source: own choice, three tool errors in a row is a loop, not a slip
79const LADDER: readonly Effort[] = ['low', 'medium', 'high', 'xhigh', 'max']
80export const escalate = (effort: Effort): Effort => {
81  const i = LADDER.indexOf(effort)
82  return i < 0 || i >= LADDER.indexOf('high') ? effort : (LADDER[i + 1] ?? effort)
83}
84
85// A tool_result's content as the Messages API spells it: a string, or text blocks (joined here).
86export const resultText = (content: unknown): string | undefined => {
87  if (typeof content === 'string') return content
88  if (!Array.isArray(content)) return undefined
89  const texts = content
90    .map((b) => b as { type?: string; text?: string })
91    .filter((b) => b.type === 'text' && typeof b.text === 'string')
92    .map((b) => b.text as string)
93  return texts.length === content.length ? texts.join('\n') : undefined
94}
95
96// Exact counts, thousands grouped by a space: "119 304" (the design system's data surface).
97export const group = (n: number): string =>
98  String(Math.trunc(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ' ')
99
hooks/records.ts 85 lines
1// Each spawn's record: in $.state for the viewers and in $.store (`spawns:<start>:<session>`, spawns.ts) for whoever
2// reads it after the session, so an outcome is attributed to the model that ran and the rule that chose it.
3import type { EngineInterface } from 'claude-code'
4
5import type { SpawnRoute } from '../types'
6import type { Steer } from './dispatch'
7import { type Decided, carried } from './effort'
8import type { Routed } from './route'
9import { ROUTES_PER_SESSION, spawnsKey, staleSpawnKeys } from './spawns'
10
11// A failed store read or write, named as a row by the caller (register.tsx `note`).
12export type Note = (subject: string, reason: string) => Promise<void>
13type Change = (kept: SpawnRoute[]) => SpawnRoute[]
14
15export type RouteFields = Omit<SpawnRoute, 'at' | 'agentId' | 'type' | 'ran'>
16
17// `effortApplied` as the record is written: the effort was decided under enforce AND a step of the agent's run was
18// passed down the chain at it (effort.ts `carried`), as the model's `applied` means a rewrite was sent down. A hook
19// cannot see whether the engine then sent the request. A step that carries it later marks the record (markCarried).
20export const asWritten = (r: SpawnRoute): SpawnRoute => (r.effortApplied === true ? { ...r, effortApplied: carried(r.agentId) } : r)
21// Only the agent's newest record is its current run's: an older one (a run before a resume) keeps what it said.
22export const marked = (rows: SpawnRoute[], id: string): SpawnRoute[] => {
23  const i = rows.findLastIndex((r) => r.agentId === id)
24  const r = rows[i]
25  if (r === undefined || r.effortApplied !== false || r.effort === null || r.effort === undefined) return rows
26  return rows.map((row, j) => (j === i ? { ...row, effortApplied: true } : row))
27}
28
29// This session's key in $.store (spawns.ts), set when the session opens; a spawn before that, or after
30// a failure to open it, is kept in $.state only, and the failure is a named row.
31let routesKey: string | undefined
32
33export async function openRoutes($: EngineInterface, note: Note): Promise<void> {
34  routesKey = undefined
35  try {
36    const now = await $.clock.now()
37    const key = spawnsKey(now, await $.session.id())
38    for (const stale of staleSpawnKeys(await $.store.keys(), now)) await $.store.delete(stale)
39    routesKey = key
40  } catch (error) {
41    await note('spawn records', `not kept across sessions: ${String(error).slice(0, 100)}`)
42  }
43}
44
45// The store's reads and writes of this session's key, one at a time: a spawn's record and a step marking it would
46// otherwise read the same rows and the later write drop the other's change.
47let routeWrites: Promise<void> = Promise.resolve()
48
49export async function rewriteRoutes($: EngineInterface, change: Change, note: Note): Promise<void> {
50  const key = routesKey
51  if (key === undefined) return
52  const write = async (): Promise<void> => {
53    try {
54      const kept = ((await $.store.get(key)) ?? []) as SpawnRoute[]
55      await $.store.set(key, change(kept))
56    } catch (error) {
57      await note('spawn records', `not kept across sessions: ${String(error).slice(0, 100)}`)
58    }
59  }
60  const done = routeWrites.then(write)
61  // A write that failed fails its caller only: the next write still runs.
62  routeWrites = done.catch(() => undefined)
63  await done
64}
65
66export async function keepRoute($: EngineInterface, record: SpawnRoute, note: Note): Promise<void> {
67  await rewriteRoutes($, (kept) => [...kept, asWritten(record)].slice(-ROUTES_PER_SESSION), note)
68}
69
70// What the record says of the decision. The table's class and review flag ride only a record the table decided (its
71// rung is `decided`/`effort`).
72export type Decision = { routed: Routed; applied: boolean; steer: Steer; effort: Decided; enforce: boolean }
73
74export const routeOf = ({ routed, applied, steer, effort, enforce }: Decision): RouteFields => ({
75  requested: routed.requested,
76  definition: routed.definition,
77  decided: routed.model ?? routed.stands,
78  reason: routed.reason,
79  applied,
80  ...(steer.by === 'table' ? { cls: steer.cls, review: steer.review } : {}),
81  effort: effort.effort ?? null,
82  effortReason: effort.reason,
83  effortApplied: enforce && effort.effort !== undefined,
84})
85
hooks/route.ts 80 lines
1// Pure model routing across the four families (fable, opus, sonnet, haiku): which model a
2// subagent runs on, and whether main drops under quota. Families are matched by substring, so
3// an alias (`haiku`) and a full id of any release (4.5, 5.5) resolve the same way.
4
5import { type Definition, pinnedModel } from './agents'
6import type { Steer } from './dispatch'
7import type { Pressure } from './policy'
8
9// Mirrors the zetetic-genius contract (its types/index.d.ts): a mod never imports across mods,
10// so the class names are spelled here and checked where the state is read.
11export type TaskClass = 'routine' | 'planned' | 'bugfix' | 'analysis' | 'critical'
12
13// source: ~/.claude/reference/agent-reference/effort-calibration.md § Which model when.
14// Haiku: a task fully planned by a more capable model with mechanical execution, bounded
15// well-specified research. Sonnet: agile coding, agent planning and execution, efficient
16// research. Opus: code review and bug-finding, security, formal verification, deep multi-file
17// work. Fable: only when explicitly chosen, never the default upgrade path (twice the Opus rate).
18// source: platform.claude.com/docs/en/models/haiku-5-5/whats-new-haiku-5-5 (released
19// 2026-10-07): Haiku 5.5 is "built for high-volume, latency-sensitive work such as
20// classification, routing, extraction, and subagent tasks", takes the effort parameter with
21// adaptive thinking on by default, and has a 1M context window with 128k output (the 200K
22// ceiling that kept Haiku 4.5 off open searches no longer applies to it).
23export const FAMILIES = ['haiku', 'sonnet', 'opus', 'fable'] as const
24export type Family = (typeof FAMILIES)[number]
25
26export const familyOf = (model: string): Family | undefined => {
27  const m = model.toLowerCase()
28  return FAMILIES.find((f) => m.includes(f))
29}
30
31// Why a spawn runs on the model it runs on, the short code its record keeps (spawns.ts bounds a record's size):
32//   call, definition  the Agent call's `model`, else the agent file's, stands
33//   design            the spawn prompt's DESIGN block names the model (dispatch.ts)
34//   table             an inheriting type nobody designed: the dispatch table's rung for its task's class
35//   unclassified      the classifier gave no class: the parent's model; inherit: nothing decides, the parent's model
36//   unread            neither a call model nor a readable definition: nothing was decided
37export type RouteReason = 'call' | 'definition' | 'design' | 'table' | 'unclassified' | 'inherit' | 'unread'
38
39// What the router decided for one spawn, and the facts it decided from (SpawnRoute in types/index.d.ts
40// adds the agent, the clock and what the engine answered). `model` is the rewrite to send, undefined
41// when the call stands as it is; `stands` is the model the spawn runs on without a rewrite.
42export type Routed = {
43  model: string | undefined
44  requested: string | null
45  definition: string | null
46  stands: string
47  reason: RouteReason
48}
49
50// The model a subagent runs on, first match wins: the call's `model`, the definition's, then what DESIGN or the table
51// steer to (dispatch.ts), else the parent's. A model the call or the definition chose stands, always: no pressure,
52// quota or context changes it, and neither DESIGN nor the table rewrites it (owner rule 2026-10-15; ADR-9851).
53// `definition` undefined: the file could not be read, and with no call model nothing is decided (the row names why).
54export const routeAgentModel = (call: string | undefined, definition: Definition | undefined, parentModel: string, steer: Steer): Routed => {
55  const defined = definition === undefined ? undefined : pinnedModel(definition)
56  const facts = { requested: call ?? null, definition: defined ?? null, stands: call ?? defined ?? `inherit ${parentModel}` }
57  if (call === undefined && definition === undefined) return { ...facts, model: undefined, reason: 'unread' }
58  if (call !== undefined) return { ...facts, model: undefined, reason: 'call' }
59  if (defined !== undefined) return { ...facts, model: undefined, reason: 'definition' }
60  if ((steer.by === 'design' || steer.by === 'table') && steer.model !== undefined) return { ...facts, model: steer.model, reason: steer.by }
61  return { ...facts, model: undefined, reason: steer.by === 'unclassified' ? 'unclassified' : 'inherit' }
62}
63
64// The main step's `model` is sent to the Messages API as is, and the API knows full ids only:
65// the CLI aliases (`sonnet`) are resolved by Claude Code before a session starts, not here.
66// Sending `sonnet` made every main step fail over ("Switched to Opus 5 because sonnet is not
67// available", 2026-10-14). The Agent tool's `model` is the alias enum, so subagents keep
68// the aliases the dispatch table names (dispatch-table.ts).
69// source: Claude model ids, Sonnet 5.5 = 'claude-sonnet-5-5' (measured 2026-10-14:
70// `claude -p --model sonnet` reports modelUsage claude-sonnet-5-5)
71export const SONNET_MAIN_ID = 'claude-sonnet-5-5'
72
73// Main thread: a model switch forfeits the prompt cache (the engine's model-change event
74// carries `prompt_cache_warm` and `estimated_cache_write_usd` for that reason), so the lever
75// is pulled for quota pressure alone, never from a request's class. Owner's rule: heavy → sonnet.
76export const mainModelFor = (model: string, pressure: Pressure): string | undefined => {
77  const f = familyOf(model)
78  return pressure === 'quota' && (f === 'opus' || f === 'fable') ? SONNET_MAIN_ID : undefined
79}
80