SLOPSHOPPER

zetetic-insights

The learning loop: every main turn is kept in a ledger across sessions (phase, effort, steps, failed tool calls, agents, advisor calls), joined with the…

guardcommandprompttimeragents
v0.9.1no licenseupdated 2026-10-23cdeust/claude-mods/mods/zetetic-insights
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · zetetic-insights
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ 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 › /calibrate ⎿ zetetic-insights: Ledger: 0 turns over 0 sessions (0 probe sessions kept out), 0 judged (0 by events, 0 by /insights, 0 disagree ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? 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 444 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, TurnUsage } from 'claude-code'
3
4import type { AgentRecord, Calibration, Design, Finding, InsightsState, ProbeCount, ProbeReason, TurnRecord, Verdict } from '../types'
5import { briefOf, mechanicalShare } from './brief'
6import { delegationStats } from './delegations'
7import { parseDesign } from './design'
8import { effectLine, effectsOf, movesOf, movesWith } from './effect'
9import { recurringIn, schedulePush, setServer } from './handover'
10import {
11  CALIBRATION_PATH,
12  FACETS_DIR,
13  FACET_SESSIONS_CAP,
14  GOALS_DIR,
15  type Outcome,
16  advisorStats,
17  agentStats,
18  applied,
19  emptyCalibration,
20  goalStatus,
21  outcomeOf,
22  parseCalibration,
23  withAgent,
24} from './learn'
25import { frictionsBySession } from './ledger'
26import { sessionModels } from './models'
27import { originStamp, observeCall, setOrigin, takeObserved } from './observe'
28import { combineOutcomes } from './outcome'
29import { type ProbeInfo, probesOf, withoutProbes } from './probes'
30import { inferred, withEscalation } from './reach'
31import { type Cell, cellsOf, decisions, phaseStats } from './rungs'
32import { cut, expandHome, INITIAL } from './shared'
33import { held, ledger, loadLedger, loaded, markEnded, markTranscript, note, saved } from './store-io'
34import { trends } from './trend'
35import type { BashResult } from './events'
36
37const insights = atom({ plugin: 'zetetic-insights', key: 'insights' } as const, INITIAL)
38
39// The dependencies' state, as their contracts declare it; literals, as the validator lists them.
40const AUTOPILOT_PHASES = { plugin: 'zetetic-autopilot', key: 'phases' } as const
41const AUTOPILOT_POLICY = { plugin: 'zetetic-autopilot', key: 'policy' } as const
42const GENIUS_STATE = { plugin: 'zetetic-genius', key: 'state' } as const
43
44// The ledger's insights state (shared.ts), written here: the turn records, the panel's statistics, the calibration.
45
46// Module state beside the held ledger (store-io.ts): what recompute reads, rebuilt at start.
47let outcomes = new Map<string, Outcome>()
48let pending: { agents: AgentRecord[]; dropped: number } = { agents: [], dropped: 0 }
49// Every session's probe decision, over the ledger as last computed (recompute).
50let probes = new Map<string, ProbeInfo>()
51// The outcome of each learning session and the runs of the learning sessions, as recompute last joined them (/calibrate apply freezes the moves from them).
52let verdicts = new Map<string, Verdict>()
53let runs: Cell[] = []
54
55// The design each spawned agent was dispatched under, by agentId, kept for the agent's lifetime (a
56// resumed agent completes more than one turn). Bounded: the oldest entry is dropped past the cap.
57export const DESIGN_MAP_CAP = 200 // source: own choice, far above the agents running at once, small enough to hold in memory
58const designs = new Map<string, Design | null>()
59// The steps and failed calls already recorded per agentId, and the row they belong to (the since of
60// its first run): loop.runs hold the agent's cumulative runs, a record keeps this turn's delta only.
61// A row the autopilot evicted and reopened starts again from empty, so its baseline is 0. Same cap.
62const recorded = new Map<string, { steps: number; errors: number; since: number | undefined }>()
63
64const bounded = <V,>(map: Map<string, V>, key: string, value: V): void => {
65  map.delete(key)
66  map.set(key, value)
67  while (map.size > DESIGN_MAP_CAP) {
68    const oldest = map.keys().next()
69    if (oldest.done === true) break
70    map.delete(oldest.value)
71  }
72}
73
74const remember = (agentId: string, design: Design | null): void => bounded(designs, agentId, design)
75
76const BRIEF_SECTION = 'zetetic-insights:self-calibration'
77
78
79// The outcomes /insights wrote for the ledger's last sessions. No facets folder is "never run",
80// not an error; an unreadable or malformed facet is skipped and named, the others are read.
81async function loadOutcomes($: EngineInterface): Promise<string | null> {
82  outcomes = new Map()
83  const sessions = [...new Set(ledger().map((r) => r.session))].slice(-FACET_SESSIONS_CAP)
84  const failed: string[] = []
85  let dir: string
86  try {
87    dir = await expandHome($, FACETS_DIR)
88    if (!(await $.fs.exists(dir))) return null
89  } catch (error) {
90    return cut(error)
91  }
92  for (const session of sessions) {
93    const path = `${dir}/${session}.json`
94    try {
95      if (await $.fs.exists(path)) outcomes.set(session, outcomeOf(await $.fs.read(path)))
96    } catch (error) {
97      failed.push(`${session}: ${cut(error)}`)
98    }
99  }
100  return failed.length === 0 ? null : `${failed.length} skipped, first ${failed[0]}`.slice(0, 160)
101}
102
103async function readGoals($: EngineInterface): Promise<{ goals: InsightsState['goals']; error: string | null }> {
104  try {
105    const dir = `${await $.session.cwd()}/${GOALS_DIR}`
106    if (!(await $.fs.exists(dir))) return { goals: [], error: null }
107    const files = (await $.fs.list(dir)).filter((f) => f.kind === 'file' && f.name.endsWith('.md'))
108    const goals = []
109    for (const f of files) goals.push({ name: f.name.replace(/\.md$/, ''), status: goalStatus(await $.fs.read(`${dir}/${f.name}`)) })
110    return { goals, error: null }
111  } catch (error) {
112    return { goals: [], error: cut(error) }
113  }
114}
115
116async function readCalibration($: EngineInterface): Promise<{ calibration: Calibration; error: string | null }> {
117  try {
118    const path = await expandHome($, CALIBRATION_PATH)
119    if (!(await $.fs.exists(path))) return { calibration: emptyCalibration(), error: null }
120    return { calibration: parseCalibration(await $.fs.read(path)), error: null }
121  } catch (error) {
122    return { calibration: emptyCalibration(), error: cut(error) }
123  }
124}
125
126async function writeCalibration($: EngineInterface, c: Calibration): Promise<void> {
127  await $.fs.write(await expandHome($, CALIBRATION_PATH), `${JSON.stringify(c, null, 2)}\n`)
128}
129
130// What the learning sessions' runs say under a calibration: the rows, the proposals, what held the others
131// back, and the measured effect of each applied move (the last move's credit gates undoing it).
132function evidenceOf(calibration: Calibration) {
133  const { effects, credits } = effectsOf(movesOf(calibration), runs, verdicts)
134  const { proposals, findings } = decisions(runs, verdicts, calibration, credits)
135  return { phases: phaseStats(runs, verdicts), proposals, findings, effects }
136}
137
138// Everything the panel shows, from the ledger and what was read beside it; enforced, a proposal
139// the evidence supports is written at once.
140async function recompute($: EngineInterface, extra: Partial<InsightsState> = {}): Promise<void> {
141  const at = await $.clock.now()
142  const s = { ...(await read($, insights)), ...extra }
143  const every = ledger()
144  // Probe sessions (hooks/probes.ts) are counted, never learned from: every statistic below reads `all`.
145  probes = probesOf(every, held.layout?.transcripts)
146  const all = withoutProbes(every, probes)
147  const joined = combineOutcomes(all, outcomes)
148  verdicts = joined.outcomes
149  runs = cellsOf(all)
150  let calibration = s.calibration
151  let ev = evidenceOf(calibration)
152  if (s.mode === 'enforce' && ev.proposals.length > 0) {
153    calibration = applied(calibration, ev.proposals, at, movesWith(calibration, ev.proposals, at, runs, verdicts))
154    await writeCalibration($, calibration)
155    ev = { ...evidenceOf(calibration), proposals: [] }
156  }
157  await update($, insights, () => ({
158    ...s,
159    turns: all.length,
160    sessions: new Set(all.map((r) => r.session)).size,
161    judgedSessions: [...joined.outcomes.values()].filter((o) => o !== 'unclear').length,
162    probes: probeCount(every, probes),
163    outcomeSources: joined.sources,
164    phases: ev.phases,
165    findings: ev.findings,
166    effects: ev.effects,
167    agents: agentStats(all),
168    advisor: advisorStats(all),
169    trends: trends(all, calibration.changes),
170    models: sessionModels(every, probes),
171    delegations: delegationStats(all),
172    mechanical: mechanicalShare(all),
173    calibration,
174    proposals: ev.proposals,
175    updatedAt: at,
176  }))
177}
178
179const probeCount = (records: readonly TurnRecord[], decided: ReadonlyMap<string, ProbeInfo>): ProbeCount => {
180  const byReason: Record<ProbeReason, number> = { 'temp-cwd': 0, 'non-interactive-1-step': 0, 'one-step-unknown': 0 }
181  let sessions = 0
182  for (const info of decided.values()) {
183    if (!info.probe || info.reason === null) continue
184    sessions += 1
185    byReason[info.reason] += 1
186  }
187  return { sessions, turns: records.filter((r) => decided.get(r.session)?.probe === true).length, byReason }
188}
189
190async function start($: EngineInterface, mode: InsightsState['mode']): Promise<void> {
191  pending = { agents: [], dropped: 0 }
192  recorded.clear()
193  note.frictionError = null
194  const ledgerError = await loadLedger($)
195  const facetsError = await loadOutcomes($)
196  const g = await readGoals($)
197  const c = await readCalibration($)
198  // The only place the brief is computed: recompute keeps it, so the system prompt stays the same
199  // within a start. /resume and fork call start() again: the resumed session gets fresh evidence, at
200  // the cost of one cache miss.
201  const frictions = held.layout === null ? undefined : new Map([...frictionsBySession(held.layout)].filter(([s]) => s !== held.ownSid))
202  const decided = probesOf(ledger(), held.layout?.transcripts)
203  const learning = withoutProbes(ledger(), decided)
204  const effects = effectsOf(movesOf(c.calibration), cellsOf(learning), combineOutcomes(learning, outcomes).outcomes).effects
205  const brief = briefOf(ledger(), frictions, decided, effects)
206  await recompute($, {
207    mode,
208    ledgerError,
209    facetsError,
210    goals: g.goals,
211    goalsError: g.error,
212    calibration: c.calibration,
213    calibrationError: c.error,
214    brief,
215    frictions: recurringIn(held.layout, ledger(), held.ownSid),
216  })
217  await schedulePush($, held.layout, ledgerError)
218}
219
220// source: zetetic-autopilot hooks/register.tsx DECISIONS_CAP, the decisions its policy keeps (the newest;
221// a mirror, a mod never imports across mods).
222const AUTOPILOT_DECISIONS_CAP = 50
223
224// Whether the autopilot's decision log may have dropped a decision taken since `since`: it keeps the
225// newest AUTOPILOT_DECISIONS_CAP in the order taken, so it lost one only when it is full, and one of the
226// turn only when its oldest kept decision is not older than the turn.
227const decisionsLost = (decisions: readonly { at: number }[], since: number): boolean =>
228  decisions.length >= AUTOPILOT_DECISIONS_CAP && (decisions[0]?.at ?? 0) >= since
229
230// One main turn, as the autopilot's phases and policy and the genius grade left it.
231async function recordTurn($: EngineInterface): Promise<void> {
232  const phases = (await $.state.get(AUTOPILOT_PHASES)).value
233  const main = phases?.loops.find((l) => l.id === 'main')
234  if (phases === undefined || main === undefined || main.runs.length === 0) return
235  const since = main.runs[0]?.since ?? 0
236  const grade = (await $.state.get(GENIUS_STATE)).value?.classified
237  const policy = (await $.state.get(AUTOPILOT_POLICY)).value
238  const uses = phases.advisor.uses.filter((u) => u.turnId === phases.turnId)
239  // Under the autopilot's observe mode nothing it logs is applied: no rung is the ceiling's, the pressure's or the escalation's.
240  const enforced = policy?.mode === 'enforce'
241  const stuck = enforced ? policy.decisions.filter((d) => d.kind === 'stuck' && d.applied && d.at >= since) : []
242  const graded = grade !== null && grade !== undefined && grade.turnId === phases.turnId ? grade : null
243  const sid = await $.session.id()
244  if (!(await loaded($, sid))) return
245  const seen = takeObserved()
246  // The autopilot's own count of the steps its stuck escalation raised (PhaseRun.escalated, 0.8.0) is read when the run has it.
247  const timed = main.runs.map((r) => ({
248    phase: r.phase,
249    effort: r.effort,
250    steps: r.steps,
251    errors: r.errors,
252    since: r.since,
253    ...(r.reads === undefined ? {} : { reads: r.reads }),
254    ...(r.escalated === undefined ? {} : { observed: r.escalated }),
255  }))
256  const record: TurnRecord = {
257    session: sid,
258    turnId: phases.turnId ?? '',
259    at: await $.clock.now(),
260    taskClass: graded?.taskClass ?? null,
261    ...(typeof graded?.effort === 'string' ? { base: graded.effort } : {}),
262    ...(enforced && (policy.pressure === 'quota' || policy.pressure === 'context') ? { pressured: true as const } : {}),
263    ...(enforced ? {} : { unenforced: true as const }),
264    // A lost decision matters only to a run placed by the time join; a run carrying the autopilot's count needs no decision.
265    ...(enforced && inferred(timed) && decisionsLost(policy.decisions, since) ? { decisionsLost: true as const } : {}),
266    main: withEscalation(timed, stuck),
267    mainModel: main.model,
268    agents: pending.agents,
269    ...(pending.dropped > 0 ? { agentsDropped: pending.dropped } : {}),
270    advisor: {
271      calls: uses.reduce((n, u) => n + u.calls, 0),
272      beforeWrite: uses.filter((u) => u.when === 'before-write').reduce((n, u) => n + u.calls, 0),
273      atCompletion: uses.filter((u) => u.when === 'at-completion').reduce((n, u) => n + u.calls, 0),
274    },
275    stuck: stuck.length,
276    ...originStamp(),
277    ...(seen.events.length > 0 ? { events: seen.events } : {}),
278    ...(seen.eventsDropped > 0 ? { eventsDropped: seen.eventsDropped } : {}),
279    frictions: seen.frictions,
280  }
281  pending = { agents: [], dropped: 0 }
282  await saved($, sid, [...held.own, record])
283}
284
285
286// A finished agent goes to main's current turn. When that turn already completed (an agent that
287// ran in the background past it), it joins that turn's record instead of the next turn's.
288async function recordAgent($: EngineInterface, agentId: string, usage: TurnUsage | undefined): Promise<void> {
289  const phases = (await $.state.get(AUTOPILOT_PHASES)).value
290  const loop = phases?.loops.find((l) => l.id === agentId)
291  if (phases === undefined || loop === undefined) return
292  const since = loop.runs[0]?.since
293  const total = { steps: loop.runs.reduce((n, r) => n + r.steps, 0), errors: loop.runs.reduce((n, r) => n + r.errors, 0) }
294  const known = recorded.get(agentId)
295  const before = known !== undefined && known.since === since ? known : { steps: 0, errors: 0 }
296  bounded(recorded, agentId, { ...total, since })
297  const agent: AgentRecord = {
298    agentId,
299    type: loop.type,
300    phase: loop.phase,
301    model: loop.model,
302    steps: Math.max(0, total.steps - before.steps),
303    errors: Math.max(0, total.errors - before.errors),
304    // Absent when the spawn was never seen (a reload); null when it carried no DESIGN block.
305    ...(designs.has(agentId) ? { design: designs.get(agentId) ?? null } : {}),
306    ...(usage === undefined
307      ? {}
308      : { tokensIn: usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens, tokensOut: usage.output_tokens }),
309  }
310  const sid = await $.session.id()
311  if (!(await loaded($, sid))) return
312  const last = held.own[held.own.length - 1]
313  if (last === undefined || phases.turnId === null || last.turnId !== phases.turnId) {
314    pending = withAgent(pending, agent)
315    return
316  }
317  const joined = withAgent({ agents: last.agents, dropped: last.agentsDropped ?? 0 }, agent)
318  const record = { ...last, agents: joined.agents, ...(joined.dropped > 0 ? { agentsDropped: joined.dropped } : {}) }
319  await saved($, sid, [...held.own.slice(0, -1), record])
320  await recompute($)
321}
322
323
324async function calibrate($: EngineInterface, args: string): Promise<string> {
325  const s = await read($, insights)
326  const at = await $.clock.now()
327  if (args === 'reset') {
328    await writeCalibration($, { ...emptyCalibration(), updatedAt: at })
329    await recompute($, { calibration: emptyCalibration(), calibrationError: null })
330    return 'Calibration reset: every phase runs its tool loop at the ladder default (medium).'
331  }
332  if (args === 'apply') {
333    if (s.proposals.length === 0) return 'No proposal: the evidence supports no change yet.'
334    const c = applied(s.calibration, s.proposals, at, movesWith(s.calibration, s.proposals, at, runs, verdicts))
335    await writeCalibration($, c)
336    await recompute($, { calibration: c, calibrationError: null })
337    return `Applied: ${s.proposals.map((p) => `${p.phase} ${p.from} → ${p.to}`).join(', ')}.`
338  }
339  const now = Object.entries(s.calibration.phases).map(([p, e]) => `${p} ${e}`)
340  return `Ledger: ${s.turns} turns over ${s.sessions} sessions (${s.probes.sessions} probe sessions kept out), ${s.judgedSessions} judged (${outcomeSourcesText(s)}). Calibration: ${now.length === 0 ? 'none (medium everywhere)' : now.join(', ')}. Proposals: ${
341    s.proposals.length === 0 ? 'none' : s.proposals.map((p) => `${p.phase} ${p.from} → ${p.to} (${p.evidence})`).join('; ')
342  }.${findingsText(s.findings)}${effectsText(s.effects)} /calibrate apply or /calibrate reset.`
343}
344
345const outcomeSourcesText = (s: InsightsState): string => `${s.outcomeSources.events} by events, ${s.outcomeSources.facets} by /insights, ${s.outcomeSources.disagree} disagreeing`
346const findingsText = (fs: readonly Finding[]): string => (fs.length === 0 ? '' : ` No move: ${fs.map((f) => `${f.phase} at ${f.effort} (${f.kind}: ${f.note})`).join('; ')}.`)
347const effectsText = (es: InsightsState['effects']): string => (es.length === 0 ? '' : ` Applied moves, measured: ${es.map(effectLine).join('; ')}.`)
348
349type On = Parameters<Register>[0]
350
351// Session lifecycle: the ledger is marked ended, loaded at start, reloaded after /clear, /resume and /branch.
352function onSession(on: On, mode: InsightsState['mode']): void {
353  on('classic.SessionEnd', async ($, e, next) => {
354    await markTranscript($, e.session_id, e.transcript_path)
355
356    return next(e)
357  }).catch(($, e, next) => next(e))
358
359  on('session.end', async ($, e, next) => {
360    await markEnded($, e.sessionId)
361
362    return next(e)
363  }).catch(($, e, next) => next(e))
364
365  on('session.start', async ($, e, next) => {
366    setOrigin(e.isInteractive, e.cwd, [await $.env.get('TMPDIR'), await $.env.get('TEMP'), await $.env.get('TMP')])
367    await start($, mode)
368    try {
369      await $.command.register({ name: 'calibrate', description: 'Show, apply or reset the per-phase effort the insights propose', argumentHint: 'apply|reset', immediate: true })
370    } catch (error) {
371      $.ui.toast(`/calibrate is taken by another plugin: ${cut(error).slice(0, 80)}`)
372    }
373
374    return next(e)
375  })
376
377  // /clear, /resume and /branch reset $.state and never fire session.start again.
378  on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
379    await start($, mode)
380
381    return next(e)
382  }).catch(($, e, next) => next(e))
383}
384
385// The turn: its record at turn.complete, and what its tool calls showed.
386function onTurn(on: On): void {
387  on('turn.complete', async ($, e, next) => {
388    if (e.agentId !== undefined) await recordAgent($, e.agentId, e.usage)
389    else {
390      await recordTurn($)
391      await recompute($)
392    }
393
394    return next(e)
395  })
396
397  // Observer: the outcome events and the frictions the turn shows, from the calls themselves (no
398  // transcript). The call's result is returned untouched; a failure to observe it is not the call's.
399  on('tool.call', async ($, e, next) => {
400    const ran = await next(e)
401    try {
402      await observeCall($, e as unknown as { tool: unknown; agentId?: string; command?: unknown }, ran as unknown as BashResult)
403    } catch {
404      // the observation failed: the turn simply shows fewer events, the call is unaffected
405    }
406
407    return ran
408  })
409}
410
411// What the model reads and what the user types: the frozen brief, the spawn's design, /calibrate.
412function onPrompt(on: On): void {
413  // Appends the frozen self-calibration section last, on the session side of the cache boundary; the
414  // engine's own sections are returned as they came. A state without a brief (older version, empty
415  // ledger) adds nothing. The id is unique in a list: an existing one is replaced, never doubled.
416  on('prompt.compose', async ($, e, next) => {
417    const r = await next(e)
418    const { brief } = await read($, insights)
419    if (typeof brief !== 'string') return r
420    const section = { id: BRIEF_SECTION, text: brief, scope: 'session' } as const
421
422    return { ...r, sections: [...r.sections.filter((x) => x.id !== BRIEF_SECTION), section] }
423  }).catch(($, e, next) => next(e))
424
425  // Observes only: the result is the spawn's own, returned untouched; a throw here never blocks it.
426  on('agent.spawn', async ($, e, next) => {
427    const r = await next(e)
428    if (r.agentId !== undefined) remember(r.agentId, parseDesign(e.prompt))
429
430    return r
431  }).catch(($, e, next) => next(e))
432
433  on('command.run', { command: 'calibrate' }, async ($, e) => ({ text: await calibrate($, (e.args ?? '').trim()) }))
434}
435
436export const register: Register = (on, options) => {
437  const mode: InsightsState['mode'] = options.learning_mode === 'enforce' ? 'enforce' : 'observe'
438  if (options.cortex_server !== undefined) setServer(String(options.cortex_server))
439  held.ownSid = null // a load or a hot reload: the module holds no ledger until it reads the store again
440  onSession(on, mode)
441  onTurn(on)
442  onPrompt(on)
443}
444
hooks/brief.ts 131 lines
1// The self-calibration text the model reads at the end of its system prompt: its own costly habits,
2// as the ledger measured them. Measured facts only, no advice; the model draws its own conclusions.
3// Pure, so the register and the tests share it. The register computes it once at session start and
4// freezes it: a system prompt that changed mid-session would void its prompt cache on every request.
5
6import type { DelegationStats, Effect, FrictionRow, MechanicalShare, ModelFamily, SessionModels, TurnRecord } from '../types'
7import { delegationStats } from './delegations'
8import { effectLine } from './effect'
9import { type Friction, recurringOver } from './friction'
10import { familyOf, sessionModels } from './models'
11import { type ProbeInfo, withoutProbes } from './probes'
12
13export const BRIEF_SESSIONS = 10 // source: own choice, the last sessions the mechanical share is measured over; recent habits, enough turns for a share
14export const BRIEF_MAX_LINES = 6 // source: own choice, a system-prompt section the model reads on every request stays short
15export const BRIEF_LINE_CAP = 200 // source: own choice, characters kept of a line; a long agent type or flag list must not grow the prompt
16
17// The one predicate of "mechanical work" is zetetic-autopilot's (phases.ts isFileReadStep): a step whose
18// every tool call is Read, Grep or Glob. The autopilot counts it per run (`reads`); this file only
19// sums the counts of main's steps on opus or fable. Not the analysis phase: that phase also holds
20// delegations, Cortex recalls, skills and read-only Bash.
21const HEAVY: readonly ModelFamily[] = ['opus', 'fable'] // source: delegations.ts overkill, the families a cheaper model could replace
22const isHeavy = (r: TurnRecord): boolean => HEAVY.includes(familyOf(r.mainModel ?? ''))
23
24// The order the families are listed in (models.ts ORDER).
25const ORDER: readonly ModelFamily[] = ['haiku', 'sonnet', 'opus', 'fable', 'other', 'unknown'] // source: models.ts ORDER
26
27// The one window of the brief: the records of the newest `sessions` sessions, by each one's newest
28// record, in ledger order. A session whose oldest turns the ledger trimmed counts what it still holds.
29export const windowOf = (records: readonly TurnRecord[], sessions: number = BRIEF_SESSIONS): { records: TurnRecord[]; sessions: number } => {
30  const newest = new Map<string, number>()
31  for (const r of records) newest.set(r.session, Math.max(newest.get(r.session) ?? r.at, r.at))
32  const keep = new Set(
33    [...newest.entries()]
34      .sort((a, b) => a[1] - b[1])
35      .slice(-sessions)
36      .map(([session]) => session),
37  )
38  return { records: records.filter((r) => keep.has(r.session)), sessions: keep.size }
39}
40
41// Main's file-read steps on opus or fable over the records' sessions (the newest `sessions` of them),
42// against the steps of the same records that were measured. A run without `reads` (recorded before it
43// was counted) is unmeasured: its steps are in `unmeasured`, never in heavySteps as zero reads.
44// heavySteps + unmeasured = all of main's steps on those models.
45export const mechanicalShare = (records: readonly TurnRecord[], sessions: number = BRIEF_SESSIONS): MechanicalShare => {
46  const window = windowOf(records, sessions)
47  let heavySteps = 0
48  let heavyReads = 0
49  let unmeasured = 0
50  for (const r of window.records) {
51    if (!isHeavy(r)) continue
52    for (const run of r.main) {
53      if (run.reads === undefined) unmeasured += run.steps
54      else {
55        heavySteps += run.steps
56        heavyReads += run.reads
57      }
58    }
59  }
60  return { sessions: window.sessions, heavyReads, heavySteps, unmeasured, share: heavySteps === 0 ? null : heavyReads / heavySteps }
61}
62
63// The delegations the outcome events judged, only when some are (merged with an approving review, reverted, closed): "; judged by events: 2 achieved, 1 not".
64const judgedText = (d: DelegationStats): string =>
65  d.outcomes.achieved + d.outcomes['not-achieved'] === 0 ? '' : `; judged by events: ${d.outcomes.achieved} achieved, ${d.outcomes['not-achieved']} not`
66
67const percent = (part: number, whole: number): string => {
68  const p = Math.round((100 * part) / whole)
69  return p === 0 ? '<1%' : `${p}%`
70}
71
72const stepsByModel = (models: readonly SessionModels[]): { total: number; line: string | null } => {
73  const by = new Map<ModelFamily, number>()
74  for (const s of models) for (const m of s.steps) by.set(m.family, (by.get(m.family) ?? 0) + m.steps)
75  const total = [...by.values()].reduce((n, v) => n + v, 0)
76  if (total === 0) return { total, line: null }
77  const parts = ORDER.flatMap((f) => ((by.get(f) ?? 0) > 0 ? [`${f} ${percent(by.get(f) ?? 0, total)}`] : []))
78  return { total, line: `- steps by model: ${parts.join(', ')}.` }
79}
80
81// At most BRIEF_MAX_LINES lines of BRIEF_LINE_CAP characters; null when nothing is measured: no
82// session with a step, no judged delegation, no share and no recurring friction. The friction line is
83// the last one: with the header and the four measures above it the brief is exactly BRIEF_MAX_LINES,
84// and were a line ever added, this is the one that yields (the slice cuts from the end).
85export const composeBrief = (o: { delegations: DelegationStats; models: readonly SessionModels[]; mechanical: MechanicalShare; frictions?: readonly FrictionRow[]; effects?: readonly Effect[] }): string | null => {
86  const { delegations: d, mechanical: m } = o
87  const top = o.frictions?.[0]
88  const steps = stepsByModel(o.models.filter((m) => !m.probe))
89  if (steps.total === 0 && d.total === 0 && m.share === null && top === undefined) return null
90  const lines = [`Self-calibration (zetetic-insights ledger, last ${m.sessions} sessions). Measured, not prescribed:`]
91  if (m.share !== null)
92    lines.push(
93      `- main thread on opus/fable: ${Math.round(100 * m.share)}% of its measured steps only read files (Read, Grep, Glob); those reads need no heavy model.${m.unmeasured > 0 ? ` (${m.unmeasured} older steps unmeasured)` : ''}`,
94    )
95  if (d.total > 0)
96    lines.push(
97      `- delegations: ${d.total} (${d.designed} with a DESIGN block); overkill ${d.flags.overkill}, underpowered ${d.flags.underpowered}, undesigned ${d.flags.undesigned}, rerouted ${d.flags.rerouted}${judgedText(d)}.`,
98    )
99  const last = d.recent[d.recent.length - 1]
100  if (last !== undefined)
101    lines.push(`- latest flagged: ${last.type} on ${last.model} (${last.effort ?? 'effort unset'}), ${last.steps} steps, ${last.errors} failed: ${last.flags.join(', ')}.`)
102  if (steps.line !== null) lines.push(steps.line)
103  const moved = [...(o.effects ?? [])].reverse().find((e) => e.credit === 'benefit' || e.credit === 'harm')
104  if (moved !== undefined) lines.push(`- calibration move, measured: ${effectLine(moved)}.`)
105  if (top !== undefined) lines.push(`- recurring friction: ${top.signature} (${top.kind}, ${top.sessions} sessions, ${top.count} times)`)
106
107  return lines
108    .slice(0, BRIEF_MAX_LINES)
109    .map((l) => l.slice(0, BRIEF_LINE_CAP))
110    .join('\n')
111}
112
113// The brief of a ledger: every line is computed from the same BRIEF_SESSIONS newest sessions, so the
114// header's count is true of all of them, the frictions' too (`frictions`: what was measured, by session).
115// The panel's own delegations and models stay on the whole ledger.
116export const briefOf = (records: readonly TurnRecord[], frictions: ReadonlyMap<string, readonly Friction[]> = new Map(), probes: ReadonlyMap<string, ProbeInfo> = new Map(), effects: readonly Effect[] = []): string | null => {
117  // Probe sessions (hooks/probes.ts) are not the model's habits: they take no slot of the window.
118  const w = windowOf(withoutProbes(records, probes))
119
120  return composeBrief({
121    delegations: delegationStats(w.records),
122    models: sessionModels(w.records, probes),
123    mechanical: mechanicalShare(w.records),
124    frictions: recurringOver(frictions, windowSessions(w.records)),
125    effects,
126  })
127}
128
129// The sessions of a window's records.
130export const windowSessions = (records: readonly TurnRecord[]): Set<string> => new Set(records.map((r) => r.session))
131
hooks/delegations.ts 112 lines
1// What the orchestrator asked of each delegation and what came of it: the DESIGN block its prompt
2// opened with (the dispatch-contract skill, parsed in design.ts), kept beside the agent's outcome, and four predicates
3// that question a delegation. Each predicate is written once, in flagsOf; pure, so the register and
4// the tests share it.
5
6import type { AgentRecord, DelegationFlag, DelegationRow, DelegationStats, TurnRecord } from '../types'
7import { familyOf } from './models'
8import { eventsBySession, judge } from './outcome'
9
10export const OVERKILL_STEPS = 5 // source: own choice, an opus or fable agent that took at most this many steps did a small job
11export const UNDERPOWERED_RATE = 0.25 // source: own choice, a flag on one small delegation, not a decision: one failed call in four (the old phase threshold; phases are now read with intervals, hooks/rungs.ts)
12export const UNDERPOWERED_MIN_STEPS = 4 // source: own choice, fewer steps than this is too small a sample for a failure rate
13export const RECENT_FLAGGED = 8 // source: own choice, the flagged delegations the panel can list
14
15const FLAGS: readonly DelegationFlag[] = ['undesigned', 'rerouted', 'overkill', 'underpowered']
16
17const REAL = new Set(['haiku', 'sonnet', 'opus', 'fable'])
18
19// The four predicates, the only place each concept is defined:
20//  - undesigned:   the prompt carried no DESIGN block (design === null). A record kept before the
21//                  design was (design absent) is legacy: no flag.
22//  - rerouted:     the design names a model of a real family, the model that ran is of a real family,
23//                  and the two families differ (the autopilot may lower a model under quota pressure).
24//  - overkill:     the model that ran is opus or fable and the agent took at most OVERKILL_STEPS steps.
25//  - underpowered: the model that ran is haiku, it took at least UNDERPOWERED_MIN_STEPS steps and
26//                  errors / steps >= UNDERPOWERED_RATE.
27export const flagsOf = (r: AgentRecord): DelegationFlag[] => {
28  const flags: DelegationFlag[] = []
29  const ran = familyOf(r.model)
30  if (r.design === null) flags.push('undesigned')
31  const wanted = r.design?.model == null ? null : familyOf(r.design.model)
32  if (wanted !== null && REAL.has(wanted) && REAL.has(ran) && wanted !== ran) flags.push('rerouted')
33  if ((ran === 'opus' || ran === 'fable') && r.steps <= OVERKILL_STEPS) flags.push('overkill')
34  if (ran === 'haiku' && r.steps >= UNDERPOWERED_MIN_STEPS && r.errors / r.steps >= UNDERPOWERED_RATE) flags.push('underpowered')
35  return flags
36}
37
38export const emptyDelegations = (): DelegationStats => ({
39  total: 0,
40  designed: 0,
41  outcomes: { achieved: 0, 'not-achieved': 0, unclear: 0 },
42  rounds: 0,
43  flags: { overkill: 0, underpowered: 0, undesigned: 0, rerouted: 0 },
44  recent: [],
45})
46
47// One delegation is one agentId: a resumed agent writes a record per turn, summed here and judged
48// once. A record without agentId (legacy) is its own delegation.
49type Delegation = { agent: AgentRecord; at: number; session: string }
50
51const delegationsOf = (records: readonly TurnRecord[]): Delegation[] => {
52  const out: Delegation[] = []
53  const byId = new Map<string, Delegation>()
54  for (const rec of records) {
55    for (const a of rec.agents) {
56      const seen = a.agentId === undefined ? undefined : byId.get(a.agentId)
57      if (seen === undefined) {
58        const d = { agent: { ...a }, at: rec.at, session: rec.session }
59        out.push(d)
60        if (a.agentId !== undefined) byId.set(a.agentId, d)
61        continue
62      }
63      const s = seen.agent
64      s.steps += a.steps
65      s.errors += a.errors
66      if (a.tokensIn !== undefined) s.tokensIn = (s.tokensIn ?? 0) + a.tokensIn
67      if (a.tokensOut !== undefined) s.tokensOut = (s.tokensOut ?? 0) + a.tokensOut
68      if (s.design === undefined && a.design !== undefined) s.design = a.design
69      s.model = a.model
70      seen.at = rec.at
71    }
72  }
73  return out
74}
75
76// Every delegation: `total` counts those that have a design field (null included), `designed` those
77// whose design is not null, `flags` each flag over the delegation's summed steps and errors, `recent`
78// the last RECENT_FLAGGED flagged rows, newest last. O(agents).
79export const delegationStats = (records: readonly TurnRecord[]): DelegationStats => {
80  const stats = emptyDelegations()
81  const events = eventsBySession(records)
82  for (const { agent: a, at, session } of delegationsOf(records)) {
83    if (a.design === undefined) continue
84    stats.total += 1
85    if (a.design !== null) stats.designed += 1
86    // The outcome the session's events show for this delegation; a legacy record (no agentId) has none to join.
87    const joined = events.get(session)
88    const judged = a.agentId === undefined ? undefined : judge(joined?.own ?? [], a.agentId, joined?.foreign)
89    if (judged !== undefined) {
90      stats.outcomes[judged.verdict] += 1
91      stats.rounds += judged.rounds
92    } else stats.outcomes.unclear += 1
93    const flags = flagsOf(a)
94    if (flags.length === 0) continue
95    for (const f of FLAGS) if (flags.includes(f)) stats.flags[f] += 1
96    const row: DelegationRow = {
97      at,
98      type: a.type,
99      model: a.model,
100      effort: a.design?.effort ?? null,
101      shape: a.design?.shape ?? null,
102      steps: a.steps,
103      errors: a.errors,
104      flags,
105      ...(judged === undefined ? {} : { outcome: judged.verdict }),
106    }
107    stats.recent.push(row)
108    if (stats.recent.length > RECENT_FLAGGED) stats.recent.shift()
109  }
110  return stats
111}
112
hooks/design.ts 42 lines
1// The DESIGN block an orchestrator opens a subagent's prompt with (the dispatch-contract skill): the one parser of it.
2// Shared, byte-identical, by zetetic-insights (which keeps the block beside the delegation's outcome) and
3// zetetic-autopilot (which applies its model and effort at the spawn): scripts/check-shared.sh keeps the copies equal.
4// Pure and self-contained: a mod cannot import a file from another mod.
5
6export type DesignBlock = { model: string | null; effort: string | null; shape: string | null }
7
8export const DESIGN_FIELD_CAP = 80 // source: own choice, characters kept of each design field; the block states a reason, not an essay
9
10const cap = (s: string): string | null => {
11  const t = s.trim().slice(0, DESIGN_FIELD_CAP)
12  return t === '' ? null : t
13}
14
15// The DESIGN block of a prompt: the lines after the first line that is exactly `DESIGN`, up to the
16// first blank line. `model: X` and `effort: Y` may share a line, separated by ` · `; `genius shape:`
17// takes the rest of its line. A field the block does not state is null; no block is null. Total.
18export const parseDesign = (prompt: string): DesignBlock | null => {
19  if (typeof prompt !== 'string') return null
20  const lines = prompt.split(/\r?\n/)
21  const start = lines.findIndex((l) => l.trim() === 'DESIGN')
22  if (start < 0) return null
23  const design: DesignBlock = { model: null, effort: null, shape: null }
24  for (const raw of lines.slice(start + 1)) {
25    const line = raw.trim()
26    if (line === '') break
27    const shape = /^genius shape:(.*)$/i.exec(line)
28    if (shape !== null) {
29      design.shape ??= cap(shape[1] ?? '')
30      continue
31    }
32    if (/^(task|check):/i.test(line)) continue
33    for (const part of line.split(' · ')) {
34      const m = /^(model|effort):(.*)$/i.exec(part.trim())
35      if (m === null) continue
36      const key = m[1]?.toLowerCase() === 'model' ? 'model' : 'effort'
37      design[key] ??= cap(m[2] ?? '')
38    }
39  }
40  return design
41}
42
hooks/effect.ts 122 lines
1// What an applied move did. Pure. A move of a phase's effort is credited only with a comparison of the
2// same phase, the same task classes and the same population before and after it: the steps its ceiling
3// decided (hooks/reach.ts: graded base at least the move's reach, not stuck-escalated, not under pressure),
4// the runs of the rung left, then of the rung moved to. The pre statistics are frozen into the move when it
5// is made, so trimming the ledger never discards them, and a phase's last move is never trimmed from the
6// file; the post statistics are frozen when a later move of the same phase supersedes it. The difference carries its Newcombe interval (hooks/stats.ts).
7
8import type { Calibration, Credit, DeltaInterval, Effect, Effort, Move, Phase, Proposal, Snapshot, Verdict } from '../types'
9import { governs } from './reach'
10import { type Cell } from './rungs'
11import { newcombe } from './stats'
12
13export const MOVES_CAP = 50 // source: own choice, the moves kept in the calibration file (~1 KB each): a phase moves a few times a week at most
14const KEY_LENGTH = 8 // source: own choice, characters of a session id kept in a snapshot (the ids are UUIDs: 8 hex digits are unique enough within one ledger)
15
16const key = (session: string): string => session.slice(0, KEY_LENGTH)
17
18// The runs of `phase` at `effort` in `cells` that a move from `from` to `to` governs, as a snapshot; each
19// session's outcome as given.
20export const snapshotOf = (cells: readonly Cell[], outcomes: ReadonlyMap<string, Verdict>, phase: Phase, effort: string, from: Effort, to: Effort): Snapshot => {
21  const snap: Snapshot = { byClass: {}, sessions: {} }
22  for (const c of cells) {
23    if (c.phase !== phase || c.effort !== effort || !governs(c, from, to)) continue
24    const row = snap.byClass[c.taskClass] ?? { steps: 0, errors: 0 }
25    snap.byClass[c.taskClass] = { steps: row.steps + c.steps, errors: row.errors + c.errors }
26    snap.sessions[key(c.session)] = outcomes.get(c.session) ?? 'unclear'
27  }
28  return snap
29}
30
31const emptySnapshot = (): Snapshot => ({ byClass: {}, sessions: {} })
32
33// The move made now: pre is the phase's runs at the rung left, up to now. The previous move of the same
34// phase, if still open, is closed with the runs it governed since.
35export const movesWith = (c: Calibration, ps: readonly Proposal[], at: number, cells: readonly Cell[], outcomes: ReadonlyMap<string, Verdict>): Move[] => {
36  const moves = c.moves.map((m) => (m.post === null && ps.some((p) => p.phase === m.phase) ? { ...m, post: snapshotOf(cells.filter((x) => x.at > m.at), outcomes, m.phase, m.to, m.from, m.to) } : m))
37  const added = ps.map((p) => ({ phase: p.phase, at, from: p.from, to: p.to, pre: snapshotOf(cells.filter((x) => x.at <= at), outcomes, p.phase, p.from, p.from, p.to), post: null }))
38  return trimmed([...moves, ...added])
39}
40
41// The newest MOVES_CAP moves, except that the last move of each phase is kept whatever its age: it is the
42// one the phase's undo is held to, and its `changes` entry stays in the file, so trimming it would make it
43// read as a 0.8.x move with no baseline (movesOf). Eight phases at most, so the cap is still a bound.
44const trimmed = (moves: readonly Move[]): Move[] => {
45  const last = new Set(Object.values(Object.fromEntries(moves.map((m, i) => [m.phase, i]))))
46  let excess = moves.length - MOVES_CAP
47  return moves.filter((_, i) => {
48    if (excess <= 0 || last.has(i)) return true
49    excess -= 1
50    return false
51  })
52}
53
54type Side = Effect['preSide']
55
56// One side's totals over the shared classes, and its judged / achieved sessions outside `drop` (the sessions on both sides).
57const sideOf = (s: Snapshot, shared: ReadonlySet<string>, drop: ReadonlySet<string>): Side => {
58  const side = { steps: 0, errors: 0, judged: 0, achieved: 0 }
59  for (const [k, row] of Object.entries(s.byClass)) {
60    if (!shared.has(k)) continue
61    side.steps += row.steps
62    side.errors += row.errors
63  }
64  for (const [k, o] of Object.entries(s.sessions)) {
65    if (drop.has(k) || (o !== 'achieved' && o !== 'not-achieved')) continue
66    side.judged += 1
67    if (o === 'achieved') side.achieved += 1
68  }
69  return side
70}
71
72const creditOf = (failed: DeltaInterval, outcome: DeltaInterval | null, pre: Side, post: Side, baseline: boolean): Credit => {
73  if (!baseline) return 'no-baseline'
74  if (pre.steps === 0 || post.steps === 0) return 'insufficient'
75  const harm = failed.lo > 0 || (outcome !== null && outcome.hi < 0)
76  const benefit = failed.hi < 0 || (outcome !== null && outcome.lo > 0)
77  return harm ? 'harm' : benefit ? 'benefit' : 'inconclusive'
78}
79
80// The effect of one move. `post` is the move's own frozen post when it has one, else the runs since it
81// at the rung moved to. Sessions with runs on both sides of the move are left out of the outcome
82// comparison (their outcome belongs to neither side), the failed-call comparison is on the shared classes.
83export const effectOf = (m: Move, cells: readonly Cell[], outcomes: ReadonlyMap<string, Verdict>): Effect => {
84  const post = m.post ?? snapshotOf(cells.filter((x) => x.at > m.at), outcomes, m.phase, m.to, m.from, m.to)
85  const shared = new Set(Object.keys(m.pre.byClass).filter((k) => k in post.byClass))
86  const both = new Set(Object.keys(m.pre.sessions).filter((k) => k in post.sessions))
87  const preSide = sideOf(m.pre, shared, both)
88  const postSide = sideOf(post, shared, both)
89  const failed = newcombe({ k: postSide.errors, n: postSide.steps }, { k: preSide.errors, n: preSide.steps })
90  const outcome = preSide.judged > 0 && postSide.judged > 0 ? newcombe({ k: postSide.achieved, n: postSide.judged }, { k: preSide.achieved, n: preSide.judged }) : null
91  return { phase: m.phase, at: m.at, from: m.from, to: m.to, classes: [...shared].sort(), preSide, postSide, failed, outcome, credit: creditOf(failed, outcome, preSide, postSide, Object.values(m.pre.byClass).some((row) => row.steps > 0)) }
92}
93
94// The moves a calibration holds: those it recorded, and, for a phase whose last change has no recorded move
95// (made under 0.8.x, whose file kept `changes` and no `moves`), a move with no pre statistics. Such a move
96// is credited `no-baseline` (nothing was frozen when it was made), so it is neither protected from being
97// undone nor unmeasured forever: the rung evidence decides, as for any proposal. Not written back: the next
98// move of the phase replaces its `changes` entry.
99export const movesOf = (c: Calibration): Move[] => [
100  ...c.moves,
101  ...Object.entries(c.changes).flatMap(([phase, ch]) => (ch === undefined || c.moves.some((m) => m.phase === phase && m.at === ch.at) ? [] : [emptyMove(phase as Phase, ch.at, ch.from, ch.to)])),
102]
103
104// The effect of each move, and the credit of each phase's last move (what undoing it is held to).
105export const effectsOf = (moves: readonly Move[], cells: readonly Cell[], outcomes: ReadonlyMap<string, Verdict>): { effects: Effect[]; credits: Map<Phase, Credit> } => {
106  const effects = moves.map((m) => effectOf(m, cells, outcomes))
107  const credits = new Map<Phase, Credit>()
108  for (const e of effects) credits.set(e.phase, e.credit)
109  return { effects, credits }
110}
111
112const signed = (x: number): string => `${x >= 0 ? '+' : ''}${Math.round(100 * x)}`
113
114// One line for the brief and /calibrate: the delta in points with its interval and the steps behind it.
115export const effectLine = (e: Effect): string => {
116  const failed = `failed calls ${signed(e.failed.d)} pts [${signed(e.failed.lo)}, ${signed(e.failed.hi)}] (${e.preSide.steps} -> ${e.postSide.steps} steps)`
117  const outcome = e.outcome === null ? '' : `, sessions achieved ${signed(e.outcome.d)} pts [${signed(e.outcome.lo)}, ${signed(e.outcome.hi)}] (${e.preSide.judged} -> ${e.postSide.judged})`
118  return `${e.phase} ${e.from} -> ${e.to}: ${failed}${outcome}; ${e.credit}`
119}
120
121export const emptyMove = (phase: Phase, at: number, from: Effort, to: Effort): Move => ({ phase, at, from, to, pre: emptySnapshot(), post: null })
122
hooks/handover.ts 233 lines
1import { atom, update } from 'claude-code'
2import type { EngineInterface } from 'claude-code'
3
4import type { InsightsState, TurnRecord } from '../types'
5import { windowOf, windowSessions } from './brief'
6import { type RememberOutcome, aggregateSummary, rememberOutcome } from './consumer'
7import { FRICTION_MAX_BYTES, type Unavailable, frictionsOf, recurringOver } from './friction'
8import {
9  AGGREGATE,
10  CLAIM,
11  type Claim,
12  ENDED,
13  FRICTIONS,
14  type Layout,
15  PUSHED,
16  type Pushed,
17  aggregateOf,
18  claimedByOther,
19  frictionTargets,
20  frictionsBySession,
21  handoverPlan,
22  keyOf,
23  newestAt,
24} from './ledger'
25import { probesOf, withoutProbes } from './probes'
26import { cut, recordsOf, INITIAL } from './shared'
27import { note, readLayout } from './store-io'
28
29const insights = atom({ plugin: 'zetetic-insights', key: 'insights' } as const, INITIAL)
30
31// The handoff to Cortex: one aggregate memory over the finished sessions, replacing itself. What it
32// covers lives in the store (it survives restarts; $.state is reset by /clear), one pushed:<sid> key
33// per session, and its head in the key `aggregate`. An update never runs in a hook that ends the
34// session (session.end has about 1.5 s in all, a Cortex remember was measured at 7.8 s): it is
35// scheduled at start, for the sessions finished by then.
36export const PUSH_DELAY_MS = 30_000 // source: own choice, the wait after start before the first remember; the session's own startup work goes first
37const REMEMBER_TAGS = ['archival', 'self-calibration', 'zetetic-insights'] // source: Cortex remember convention (agent-guidance: archival + agent_topic)
38
39// source: Cortex mcp_server/shared/write_class.py classify_write_class (source 'tool' already resolves to deliberate, ADR-0688) and mcp_server/core/write_gate.py determine_bypass (deliberate bypasses the write gate, ADR-0319): stated, not left to the default
40const REMEMBER_WRITE_CLASS = 'deliberate'
41const REMEMBER_SOURCE = 'tool' // source: Cortex mcp_server/handlers/remember_schema.py lines 205-226 (ADR-0442), `source` is an enum (session, tool, user, consolidation, import, distillation); the writer is named by origin_tool
42
43let server = 'plugin_hypermnesia-mcp_cortex' // source: mods/zetetic-insights/.claude-plugin/plugin.json userConfig cortex_server default
44let generation = 0
45let pushing = false
46
47const cortexOf = (pushed: number, pending: number, lastError: string | null, lastAt: number | null) => ({ pushed, pending, lastError, lastAt })
48const AGGREGATE_CLAIM = keyOf(CLAIM, AGGREGATE)
49
50async function setCortex($: EngineInterface, c: InsightsState['cortex']): Promise<void> {
51  await update($, insights, (s) => ({ ...s, cortex: c }))
52}
53
54// The finished sessions marked as in the aggregate, each up to its newest record as read now.
55async function cover($: EngineInterface, view: Layout, sessions: readonly string[], at: number): Promise<void> {
56  for (const s of sessions) await $.store.set(keyOf(PUSHED, s), { at, lastAt: newestAt(view.turns.get(s) ?? []) } satisfies Pushed)
57}
58
59// What one reply changes (consumer.ts rememberOutcome), and what is named in state.cortex. A merged
60// id is another memory, never recorded; a failure changes nothing and the next start retries.
61async function applyOutcome($: EngineInterface, view: Layout, finished: readonly string[], outcome: RememberOutcome): Promise<string | null> {
62  const at = await $.clock.now()
63  if (outcome.kind === 'failed') return outcome.failure
64  if (outcome.kind === 'merged') return `Cortex merged the aggregate into memory ${outcome.memoryId ?? '?'}, not ours: not recorded`
65  if (outcome.kind === 'rejected') return `not stored, rejected by Cortex: ${outcome.reason}; retried at the next start`
66  if (outcome.kind === 'cleared') {
67    await $.store.set(AGGREGATE, { at }) // the head is only ever an id we created: a foreign one is never adopted
68    return `${outcome.reason}: head cleared${outcome.foreignId === null ? '' : ` (Cortex named memory ${outcome.foreignId}, not ours)`}, the next start remembers a fresh head`
69  }
70  await $.store.set(AGGREGATE, { at, memoryId: outcome.memoryId })
71  await cover($, view, finished, at)
72  return null
73}
74
75// The aggregate updated once, after the delay: only while the claim is still exactly this one, over
76// the store as read now (a session resumed during the delay is live again, and left out).
77async function updateAggregate($: EngineInterface, mine: number, sid: string, claimAt: number): Promise<void> {
78  if (pushing || mine !== generation) return
79  pushing = true
80  try {
81    const claim = (await $.store.get(AGGREGATE_CLAIM)) as Claim | undefined
82    if (claim?.by !== sid || claim.at !== claimAt) return
83    const now = await $.clock.now()
84    const view = await readLayout($, await $.store.keys())
85    const plan = handoverPlan(view, sid, now)
86    if (plan.pending.length === 0) return
87    const decided = probesOf(recordsOf(view), view.transcripts)
88    const content = aggregateSummary(withoutProbes(plan.finished.flatMap((s) => view.turns.get(s) ?? []), decided), now, frictionsBySession(view))
89    let error: string | null = null
90    if (content === null) await cover($, view, plan.finished, now) // nothing measured: nothing to say
91    else {
92      const head = aggregateOf(await $.store.get(AGGREGATE))
93      const args = { content, tags: REMEMBER_TAGS, agent_topic: 'self-calibration', source: REMEMBER_SOURCE, origin_tool: 'zetetic-insights', write_class: REMEMBER_WRITE_CLASS, ...(head.memoryId === undefined ? {} : { supersedes_id: head.memoryId }) }
94      let outcome: RememberOutcome
95      try {
96        outcome = rememberOutcome(await $.mcp.call(server, 'remember', args))
97      } catch (error) {
98        outcome = { kind: 'failed', failure: cut(error) }
99      }
100      error = await applyOutcome($, view, plan.finished, outcome)
101    }
102    const after = handoverPlan(await readLayout($, await $.store.keys()), sid, now)
103    await setCortex($, cortexOf(after.finished.length - after.pending.length, after.pending.length, error?.slice(0, 120) ?? null, await $.clock.now()))
104  } finally {
105    pushing = false
106  }
107}
108
109// I3, at most one process updates the aggregate per claim window. claim:aggregate is re-read from the
110// store just before it is written (never from the start snapshot), skipped when another process holds
111// it within CLAIM_TTL_MS, written, then read back after PUSH_DELAY_MS: only a claim still exactly its
112// own goes on. Two processes both reach their remember only when one stalled PUSH_DELAY_MS (30 s) or
113// more between its re-read and its write: otherwise the later write lands within 30 s of the
114// earlier one, so the earlier one reads it back and skips, or the later one re-read the earlier
115// claim and never wrote.
116async function claimAggregate($: EngineInterface, sid: string, now: number): Promise<boolean> {
117  if (claimedByOther((await $.store.get(AGGREGATE_CLAIM)) as Claim | undefined, sid, now)) return false
118  await $.store.set(AGGREGATE_CLAIM, { by: sid, at: now } satisfies Claim)
119  return true
120}
121
122// The deferred work of one start, in this order: the frictions of the finished sessions are measured
123// first, so the aggregate (when this process holds its claim) says what they found. Neither runs in a
124// hook; each names its own failure and never stops the other.
125type Deferred = { mine: number; sid: string; claimAt: number; claimed: boolean; counts: { pushed: number; pending: number } }
126
127async function afterDelay($: EngineInterface, d: Deferred): Promise<void> {
128  await measureFrictions($, d.mine, d.sid)
129  if (!d.claimed) return
130  await updateAggregate($, d.mine, d.sid, d.claimAt).catch((error) => setCortex($, cortexOf(d.counts.pushed, d.counts.pending, cut(error), null)))
131}
132
133// The Cortex server the aggregate is remembered to (the mod's cortex_server option).
134export const setServer = (name: string): void => {
135  server = name
136}
137
138// Exactly once per change holds when no process stalls PUSH_DELAY_MS between its claim re-read and
139// write, an update ends within CLAIM_TTL_MS of its claim, and no process crashes between remember and
140// its keys (then the next start repeats the remember: at least once). A throw here (the session id,
141// the clock, the store, the state) is named in state.cortex and never fails start(); nothing the
142// timer runs can leave a rejection unhandled.
143export async function schedulePush($: EngineInterface, layout: Layout | null, loadError: string | null): Promise<void> {
144  generation += 1
145  const mine = generation
146  try {
147    const sid = await $.session.id()
148    const now = await $.clock.now()
149    const plan = layout === null ? { finished: [], pending: [] } : handoverPlan(layout, sid, now)
150    const counts = { pushed: plan.finished.length - plan.pending.length, pending: plan.pending.length }
151    await setCortex($, cortexOf(counts.pushed, counts.pending, layout === null ? (loadError ?? 'the ledger did not load') : null, null))
152    const claimed = plan.pending.length > 0 && (await claimAggregate($, sid, now))
153    const toMeasure = layout === null ? [] : frictionTargets(layout, windowSessions(windowOf(recordsOf(layout)).records), sid)
154    if (!claimed && toMeasure.length === 0) return
155    $.clock.after(PUSH_DELAY_MS, () => {
156      afterDelay($, { mine, sid, claimAt: now, claimed, counts })
157        .catch(() => undefined) // the state itself refused: there is nothing left to name it in
158    })
159  } catch (error) {
160    try {
161      await setCortex($, cortexOf(0, 0, `handover not scheduled: ${cut(error)}`.slice(0, 120), null))
162    } catch {
163      // the state itself refused: start() still completes, the next start schedules again
164    }
165  }
166}
167
168const FRICTION_NOT_MEASURED = 'frictions not measured'
169
170// The frictions recurring over the sessions of the brief's window (the own, live one is not measured).
171export const recurringIn = (view: Layout | null, records: readonly TurnRecord[], ownSid: string | null): InsightsState['frictions'] =>
172  view === null ? [] : recurringOver(frictionsBySession(view), [...windowSessions(windowOf(withoutProbes(records, probesOf(records, view.transcripts))).records)].filter((s) => s !== ownSid))
173
174// Reads the transcripts of at most FRICTION_BATCH finished sessions of the window, each at most once:
175// frictionsOf is a pure function of the file, so frictions:<s> holds the same value whichever process
176// writes it (ledger.ts, the exception to I1). A transcript that cannot be read is named in the state
177// and left unmarked, so the next start tries again. Only ever called from the deferred timer.
178async function measureFrictions($: EngineInterface, mine: number, sid: string): Promise<void> {
179  if (mine !== generation) return
180  try {
181    const view = await readLayout($, await $.store.keys())
182    const failed: string[] = []
183    const large: string[] = []
184    for (const t of frictionTargets(view, windowSessions(windowOf(recordsOf(view)).records), sid)) {
185      try {
186        // The session may resume while its transcript is read (its process deletes ended: and the
187        // frictions: it measured): nothing is written unless ended:<s> is exactly what it was when
188        // the measurement began, so a resumed session is measured afresh when it ends again.
189        const endedKey = keyOf(ENDED, t.session)
190        const began = JSON.stringify(await $.store.get(endedKey)) ?? ''
191        // The pre-check and the set are two awaits apart: a resume that runs entirely between them deletes ended: and
192        // frictions:, and the set would then land stale. So after the set the ended: is read again, and if it is absent
193        // or changed the frictions: just written is deleted. This bounds the stale window to the moments between the
194        // set and that delete; the next resume deletion or the next measurement corrects it.
195        const stillEnded = async (): Promise<boolean> => began !== '' && JSON.stringify(await $.store.get(endedKey)) === began
196        const write = async (value: unknown): Promise<void> => {
197          if (!(await stillEnded())) return
198          await $.store.set(keyOf(FRICTIONS, t.session), value)
199          if (!(await stillEnded())) await $.store.delete(keyOf(FRICTIONS, t.session))
200        }
201        if (!(await $.fs.exists(t.transcript))) await write({ unavailable: 'missing' } satisfies Unavailable) // gone for good: a fact, the same for every writer
202        else {
203          const { size } = await $.fs.stat(t.transcript)
204          if (size > FRICTION_MAX_BYTES) {
205            await write({ unavailable: 'too-large' } satisfies Unavailable)
206            large.push(`${t.session.slice(0, 8)} ${size} bytes`)
207          } else await write(frictionsOf(await $.fs.read(t.transcript)))
208        }
209      } catch (error) {
210        failed.push(`${t.session.slice(0, 8)}: ${cut(error)}`)
211      }
212    }
213    const named = [
214      ...(failed.length === 0 ? [] : [`${FRICTION_NOT_MEASURED}, retried at the next start: ${failed.join('; ')}`]),
215      ...(large.length === 0 ? [] : [`${FRICTION_NOT_MEASURED}, transcript over ${FRICTION_MAX_BYTES} bytes: ${large.join('; ')}`]),
216    ]
217    note.frictionError = named.length === 0 ? null : named.join(' | ').slice(0, 240)
218    const after = await readLayout($, await $.store.keys())
219    await update($, insights, (s) => ({
220      ...s,
221      frictions: recurringIn(after, recordsOf(after), sid),
222      ledgerError: note.frictionError ?? (s.ledgerError?.startsWith(FRICTION_NOT_MEASURED) === true ? null : s.ledgerError),
223    }))
224  } catch (error) {
225    note.frictionError = `${FRICTION_NOT_MEASURED}: ${cut(error)}`
226    try {
227      await update($, insights, (s) => ({ ...s, ledgerError: note.frictionError }))
228    } catch {
229      // the state itself refused: there is nothing left to name it in, and the aggregate must still run
230    }
231  }
232}
233
hooks/learn.ts 140 lines
1// Pure side of the learning loop: the turn records the ledger keeps, what they say per phase and
2// effort, the session outcomes /insights wrote, the goals' status, and the bounded change of one
3// phase's effort the evidence supports.
4
5import type { AgentRecord, AgentStat, Calibration, Effort, Proposal, TurnRecord } from '../types'
6
7export const LEDGER_CAP = 3000 // source: own choice, the turns the rates are read from
8// source: claude-code types, `$.store.set` "rejects ... a store over 4 MiB of JSON text in all"
9// (every key of the mod's store). The ledger, all turns:* keys together (ledger.ts), keeps 3 MiB of
10// it as the file writes it, the rest is margin.
11export const LEDGER_BYTES = 3 * 1024 * 1024
12// source: own choice, the agents one record keeps (~200 bytes each); the rest are counted.
13export const MAX_AGENTS = 50
14export const FACET_SESSIONS_CAP = 80 // source: own choice, the facets read at start are the last sessions'
15
16// source: Claude Code 2.1.299 binary: `/insights` writes `<config dir>/usage-data/facets/<session id>.json`
17// with `"outcome": "fully_achieved|mostly_achieved|partially_achieved|not_achieved|unclear_from_transcript"`.
18export const FACETS_DIR = '~/.claude/usage-data/facets'
19// The file the autopilot reads (its hooks/calibration.ts names the same path).
20export const CALIBRATION_PATH = '~/.claude/zetetic-insights/calibration.json'
21// source: zetetic-loop verify-goal skill: a goal file's last `status:` line is its state.
22export const GOALS_DIR = '.zetetic/goals'
23
24// source: zetetic-autopilot policy.ts effortFor: without calibration the tool loop runs at medium.
25export const LOOP_DEFAULT: Effort = 'medium'
26export const LADDER: readonly Effort[] = ['low', 'medium', 'high']
27
28export type Outcome = 'achieved' | 'not-achieved' | 'unclear'
29
30export const outcomeOf = (facetJson: string): Outcome => {
31  let raw: unknown
32  try {
33    raw = JSON.parse(facetJson)
34  } catch (error) {
35    throw new Error(`facet is not valid JSON (${error instanceof Error ? error.message : String(error)})`.slice(0, 120))
36  }
37  const o = (raw as { outcome?: unknown } | null)?.outcome
38  if (o === 'fully_achieved' || o === 'mostly_achieved') return 'achieved'
39  if (o === 'partially_achieved' || o === 'not_achieved') return 'not-achieved'
40  return 'unclear'
41}
42
43export const goalStatus = (md: string): string => {
44  const lines = md.split('\n').filter((l) => /^status:\s*\S/.test(l))
45  return (lines[lines.length - 1] ?? 'status: none').replace(/^status:\s*/, '').trim()
46}
47
48// UTF-8 length of a JSON text, what the store measures; a lone surrogate counts as 3 bytes, the
49// replacement character it is written as.
50export const utf8Bytes = (text: string): number => {
51  let n = 0
52  for (let i = 0; i < text.length; i++) {
53    const c = text.charCodeAt(i)
54    if (c < 0x80) n += 1
55    else if (c < 0x800) n += 2
56    else if (c >= 0xd800 && c <= 0xdbff && i + 1 < text.length && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
57      n += 4
58      i++
59    } else n += 3
60  }
61  return n
62}
63
64// A record's bytes as the store file holds it: the file is JSON indented by two spaces (read from
65// ~/.claude/plugins/store/zetetic-insights_*.json, 2026-10-14: 865 bytes against 474 compact), a
66// record sitting two levels deep under `{"turns": [...]}`. Whether the store's 4 MiB counts that
67// text or the compact one, this is the larger, so the cap holds under both.
68export const recordBytes = (r: TurnRecord): number => {
69  const text = JSON.stringify(r, null, 2)
70  let lines = 1
71  for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) lines++
72  return utf8Bytes(text) + 4 * lines + 2 // the indent of each line, then ",\n"
73}
74
75// The newest records that fit both caps, oldest dropped first. Each record is measured once:
76// O(n) in the records, whatever the ledger loaded from the store weighed.
77export const trimmed = (records: readonly TurnRecord[], maxBytes = LEDGER_BYTES, maxCount = LEDGER_CAP): TurnRecord[] => {
78  const sizes = records.map(recordBytes)
79  let total = sizes.reduce((a, b) => a + b, 1)
80  let from = Math.max(0, records.length - maxCount)
81  for (let i = 0; i < from; i++) total -= sizes[i]!
82  while (from < records.length && total > maxBytes) total -= sizes[from++]!
83  return records.slice(from)
84}
85
86// One finished agent added to a turn's list, past MAX_AGENTS counted instead of kept.
87export const withAgent = (
88  list: { agents: AgentRecord[]; dropped: number },
89  agent: AgentRecord,
90): { agents: AgentRecord[]; dropped: number } =>
91  list.agents.length < MAX_AGENTS ? { agents: [...list.agents, agent], dropped: list.dropped } : { agents: list.agents, dropped: list.dropped + 1 }
92
93export const agentStats = (records: readonly TurnRecord[]): AgentStat[] => {
94  const by = new Map<string, AgentStat>()
95  for (const r of records)
96    for (const a of r.agents) {
97      const row = by.get(a.type) ?? { type: a.type, runs: 0, steps: 0, errors: 0, models: [] }
98      by.set(a.type, {
99        ...row,
100        runs: row.runs + 1,
101        steps: row.steps + a.steps,
102        errors: row.errors + a.errors,
103        models: row.models.includes(a.model) ? row.models : [...row.models, a.model],
104      })
105    }
106  return [...by.values()].sort((a, b) => b.runs - a.runs)
107}
108
109export const emptyCalibration = (): Calibration => ({ version: 1, phases: {}, evidence: {}, changes: {}, moves: [], updatedAt: null })
110
111export const parseCalibration = (text: string): Calibration => {
112  const raw = JSON.parse(text) as Partial<Calibration>
113  if (raw.version !== 1 || typeof raw.phases !== 'object' || raw.phases === null)
114    throw new Error('calibration.json is not version 1 with a phases object')
115  return { version: 1, phases: raw.phases, evidence: raw.evidence ?? {}, changes: raw.changes ?? {}, moves: Array.isArray(raw.moves) ? raw.moves : [], updatedAt: raw.updatedAt ?? null }
116}
117
118export const applied = (c: Calibration, ps: readonly Proposal[], at: number, moves: Calibration['moves'] = c.moves): Calibration => ({
119  version: 1,
120  phases: { ...c.phases, ...Object.fromEntries(ps.map((p) => [p.phase, p.to])) },
121  evidence: { ...c.evidence, ...Object.fromEntries(ps.map((p) => [p.phase, `${p.from} → ${p.to}: ${p.evidence}`])) },
122  changes: { ...c.changes, ...Object.fromEntries(ps.map((p) => [p.phase, { at, from: p.from, to: p.to }])) },
123  moves,
124  updatedAt: at,
125})
126
127// The advisor against the grades: how often an analysis or critical turn consulted it before
128// writing, and how often a routine one called it at all.
129export const advisorStats = (records: readonly TurnRecord[]) => {
130  const heavy = records.filter((r) => r.taskClass === 'analysis' || r.taskClass === 'critical')
131  const light = records.filter((r) => r.taskClass === 'routine' || r.taskClass === 'planned')
132  return {
133    heavyTurns: heavy.length,
134    heavyBeforeWrite: heavy.filter((r) => r.advisor.beforeWrite > 0).length,
135    heavyAtCompletion: heavy.filter((r) => r.advisor.atCompletion > 0).length,
136    lightTurns: light.length,
137    lightWithAdvisor: light.filter((r) => r.advisor.calls > 0).length,
138  }
139}
140
hooks/ledger.ts 225 lines
1// The ledger's layout in the mod's store, one key per owner; pure. `$.store` is ONE JSON file
2// shared by every Claude process: writes to different keys merge, a read-modify-write of one shared
3// key was not shown safe (claude-mods/.claude/evidence/store-concurrency-2026-10-14.md). So each
4// process writes only keys it owns, and nothing reads, modifies and writes back a shared key.
5// I1: turns:<s>, ended:<s> and transcript:<s> are written by the process of session s only. Another process writes
6//   only pushed:<s> of the finished sessions an aggregate update covered and aggregate/claim:aggregate
7//   (I3), legacy:<s> and an absent pushed:<s> in the migration (I5), and deletes the keys of ended
8//   sessions (I2) and orphans.
9// I2: a process deletes another session's keys only when that session has ended:<s> (register.tsx
10//   saved states the one race left). Never a session without ended:, idle or crashed.
11// I3: the aggregate is updated by at most one process per claim window (register.tsx claimAggregate).
12// I4: the own write lands within LEDGER_BYTES, or is refused and named in ledgerError.
13// I5: the migration is idempotent and writes no key an owner writes.
14// The exception to I1, frictions:<s>: any process may write it, for any finished session whose ended:<s>
15//   and transcript:<s> exist. Its value is the pure function frictionsOf of that file (no clock, no writer
16//   in it, a total order on its rows), so two processes writing at once write the same value. The
17//   process of s deletes it when s resumes (its transcript grows again); eviction and orphans delete
18//   it as the other keys of s.
19
20import type { TurnRecord } from '../types'
21import { type Friction, isUnavailable, liveRowsOf, mergeFrictions, rowsOf } from './friction'
22import { LEDGER_BYTES, recordBytes, trimmed, utf8Bytes } from './learn'
23
24export const TURNS = 'turns:' // that session's records; only the process whose session id it is writes it
25export const LEGACY = 'legacy:' // that session's records moved from the legacy key; only the migration writes it
26export const ENDED = 'ended:' // { at }, set by that same process at session.end (also fired by /clear, old id); a value of 0.7.0 builds before the split may carry a transcript, honoured as legacy
27export const TRANSCRIPT = 'transcript:' // { path }, set by that same process at classic.SessionEnd and by nothing else: no hook's order is relied on, each hook writes its own key
28export const CLAIM = 'claim:' // { by, at }, set by the process about to hand the session over, then read back
29export const PUSHED = 'pushed:' // { at, lastAt }: that session is in the aggregate memory, up to its record lastAt
30export const AGGREGATE = 'aggregate' // { at, memoryId? }: the head of the one aggregate memory in Cortex; claim:aggregate guards it
31export const FRICTIONS = 'frictions:' // that session's frictions (friction.ts), measured from the transcript its ended: names; [] is measured, none found
32export const SESSION_PREFIXES = [TURNS, LEGACY, ENDED, PUSHED, CLAIM, TRANSCRIPT, FRICTIONS] as const // a deleted session loses all seven, records first
33export const LEGACY_TURNS = 'turns' // the single-key ledger of 0.5-0.6 (PR #13), every process rewriting it whole
34export const LEGACY_PUSHED = 'pushed' // the single-key handover list of PR #18 before this layout
35
36export const CLAIM_TTL_MS = 10 * 60_000 // source: own choice, far above one batch (30 s delay, then 5 remembers at 7.8 s measured 2026-10-14); an older claim is a process that died mid-handover
37export const FRICTION_BATCH = 3 // source: own choice, transcripts read per start; a transcript is megabytes, and the read is deferred (observer effect: the measure must not slow the session it measures)
38export const STALE_MS = 24 * 3_600_000 // source: own choice, a session with no turn for a day is finished for the handover: covers a crashed process that never fired session.end
39
40export type Claim = { by: string; at: number }
41export type Aggregate = { at: number; memoryId?: number }
42export const aggregateOf = (v: unknown): Aggregate => {
43  const o = (typeof v === 'object' && v !== null ? v : {}) as Record<string, unknown>
44  const id = o.memoryId
45  return { at: typeof o.at === 'number' ? o.at : 0, ...(Number.isSafeInteger(id) && (id as number) > 0 ? { memoryId: id as number } : {}) }
46}
47// What a handover recorded: when, and the newest record `at` it covered.
48export type Pushed = { at: number; lastAt: number }
49
50// A pushed: value without a numeric lastAt (the legacy { at: 0 }, or junk) is no handover: the
51// session is sent again, delivery stays at least once.
52export const pushedOf = (v: unknown): Pushed | undefined => {
53  const o = (typeof v === 'object' && v !== null ? v : {}) as Record<string, unknown>
54  return typeof o.lastAt === 'number' && Number.isFinite(o.lastAt) ? { at: typeof o.at === 'number' ? o.at : 0, lastAt: o.lastAt } : undefined
55}
56export const isCovered = (p: Pushed | undefined, newest: number): boolean => p !== undefined && newest <= p.lastAt
57
58export const keyOf = (prefix: string, session: string): string => `${prefix}${session}`
59export const sessionOfKey = (key: string, prefix: string): string | null => (key.startsWith(prefix) && key.length > prefix.length ? key.slice(prefix.length) : null)
60
61// What the store holds, by session: turns:<s> and legacy:<s> together, one record per turnId. A
62// value of either that is not a list is listed in `malformed`.
63export type Layout = {
64  turns: ReadonlyMap<string, readonly TurnRecord[]>
65  ended: ReadonlySet<string>
66  // The transcript each ended session named at its end; a session whose ended: has none (an older
67  // value, or classic hooks not run under managed settings) is not here: its frictions are not measured.
68  transcripts: ReadonlyMap<string, string>
69  frictions: ReadonlyMap<string, readonly Friction[]>
70  pushed: ReadonlyMap<string, Pushed>
71  claims: ReadonlyMap<string, Claim>
72  malformed: readonly string[]
73}
74
75// Two record lists of one session as one, in time order, a turnId kept once.
76export const unionOf = (a: readonly TurnRecord[], b: readonly TurnRecord[]): TurnRecord[] => {
77  const seen = new Set(a.map((r) => r.turnId))
78  return [...a, ...b.filter((r) => !seen.has(r.turnId))].sort((x, y) => x.at - y.at)
79}
80
81const isClaim = (v: unknown): v is Claim => typeof v === 'object' && v !== null && typeof (v as Claim).by === 'string' && typeof (v as Claim).at === 'number'
82
83export const layoutOf = (entries: ReadonlyMap<string, unknown>): Layout => {
84  const turns = new Map<string, readonly TurnRecord[]>()
85  const ended = new Set<string>()
86  const transcripts = new Map<string, string>()
87  const legacyTranscripts = new Map<string, string>()
88  const frictions = new Map<string, readonly Friction[]>()
89  const pushed = new Map<string, Pushed>()
90  const claims = new Map<string, Claim>()
91  const malformed: string[] = []
92  for (const [key, value] of entries) {
93    const t = sessionOfKey(key, TURNS) ?? sessionOfKey(key, LEGACY)
94    if (t !== null) {
95      if (Array.isArray(value)) turns.set(t, unionOf(turns.get(t) ?? [], value as TurnRecord[]))
96      else malformed.push(key)
97      continue
98    }
99    const e = sessionOfKey(key, ENDED)
100    if (e !== null) {
101      ended.add(e)
102      const legacy = typeof value === 'object' && value !== null ? (value as { transcript?: unknown }).transcript : undefined
103      if (typeof legacy === 'string' && legacy !== '') legacyTranscripts.set(e, legacy)
104    }
105    const tr = sessionOfKey(key, TRANSCRIPT)
106    const path = tr === null || typeof value !== 'object' || value === null ? undefined : (value as { path?: unknown }).path
107    if (tr !== null && typeof path === 'string' && path !== '') transcripts.set(tr, path)
108    const f = sessionOfKey(key, FRICTIONS)
109    if (f !== null && (Array.isArray(value) || isUnavailable(value))) frictions.set(f, rowsOf(value)) // an unavailable marker is measured, with no rows
110    const p = sessionOfKey(key, PUSHED)
111    const covered = p === null ? undefined : pushedOf(value)
112    if (p !== null && covered !== undefined) pushed.set(p, covered)
113    const c = sessionOfKey(key, CLAIM)
114    if (c !== null && isClaim(value)) claims.set(c, value)
115  }
116  for (const [s, legacy] of legacyTranscripts) if (!transcripts.has(s)) transcripts.set(s, legacy)
117  return { turns, ended, transcripts, frictions, pushed, claims, malformed }
118}
119
120// Every session's frictions as one view: the live events its records carry (seen at tool.call, no
121// transcript needed) and the transcript's rows when it was measured, the larger count of a row seen
122// by both. A session none of whose records carries `frictions` and with no transcript rows was not
123// measured: it is absent.
124export const frictionsBySession = (layout: Layout): Map<string, readonly Friction[]> => {
125  const out = new Map<string, readonly Friction[]>(layout.frictions)
126  for (const [session, records] of layout.turns) {
127    if (!records.some((r) => r.frictions !== undefined)) continue
128    out.set(session, mergeFrictions(liveRowsOf(records.map((r) => r.frictions)), layout.frictions.get(session) ?? []))
129  }
130  return out
131}
132
133export const newestAt = (records: readonly TurnRecord[]): number => records.reduce((m, r) => Math.max(m, r.at), Number.NEGATIVE_INFINITY)
134
135// Finished for the handover (never for eviction, I2): its process said so at session.end, or it has
136// had no turn for STALE_MS.
137export const isFinished = (session: string, ended: ReadonlySet<string>, newest: number, now: number): boolean => ended.has(session) || now - newest >= STALE_MS
138
139export const claimedByOther = (claim: Claim | undefined, own: string, now: number): boolean => claim !== undefined && claim.by !== own && now - claim.at < CLAIM_TTL_MS
140
141// The handover (I3): the finished sessions other than the own one, oldest first, and those of
142// them whose pushed: does not cover their newest record. The aggregate needs an update when that
143// second list is not empty; every finished session is in its text (register.tsx).
144export const handoverPlan = (layout: Layout, own: string, now: number): { finished: string[]; pending: string[] } => {
145  const finished = [...layout.turns.entries()]
146    .map(([session, records]) => ({ session, newest: newestAt(records) }))
147    .filter((s) => s.session !== own && isFinished(s.session, layout.ended, s.newest, now))
148    .sort((a, b) => a.newest - b.newest)
149  return { finished: finished.map((s) => s.session), pending: finished.filter((s) => !isCovered(layout.pushed.get(s.session), s.newest)).map((s) => s.session) }
150}
151
152// A records key's bytes in the store file: its records as recordBytes measures them (two levels
153// deep, as under the legacy key), plus the key's own line.
154export const keyBytes = (key: string, records: readonly TurnRecord[]): number => utf8Bytes(JSON.stringify(key)) + 8 + records.reduce((n, r) => n + recordBytes(r), 0)
155
156export type Sized = { session: string; bytes: number; newest: number; ended: boolean; pushed: boolean }
157
158// I4 and I2: the ended sessions the own write deletes, pushed (every record covered) first then
159// unpushed, each oldest first, until everything fits. A session without ended: is never chosen.
160// null: even with every ended session gone the own write does not fit, so it is refused and nothing
161// is deleted. An unpushed session evicted here is never handed to Cortex: its records are gone.
162export const evictions = (others: readonly Sized[], ownBytes: number, budget = LEDGER_BYTES): string[] | null => {
163  let rest = others.reduce((n, s) => n + s.bytes, 0)
164  const evict: string[] = []
165  const candidates = others.filter((s) => s.ended).sort((a, b) => (a.pushed === b.pushed ? a.newest - b.newest : a.pushed ? -1 : 1))
166  for (const s of candidates) {
167    if (rest + ownBytes <= budget) break
168    evict.push(s.session)
169    rest -= s.bytes
170  }
171  return rest + ownBytes <= budget ? evict : null
172}
173
174// The own records within the budget alone (and the record count cap), oldest dropped.
175export const ownWithin = (session: string, records: readonly TurnRecord[], room = LEDGER_BYTES): TurnRecord[] => trimmed(records, Math.max(0, room - keyBytes(keyOf(TURNS, session), []) + 1))
176
177// ended:, pushed:, claim:, transcript: and frictions: keys whose session has no records key (evicted while another
178// process claimed, pushed or measured it): deleted at the next own write. Never the own session's, never claim:aggregate.
179export const orphans = (keys: readonly string[], own: string): string[] => {
180  const held = new Set(keys.map((k) => sessionOfKey(k, TURNS) ?? sessionOfKey(k, LEGACY)).filter((s): s is string => s !== null))
181  return keys.filter((k) => {
182    for (const p of [ENDED, PUSHED, CLAIM, TRANSCRIPT, FRICTIONS]) {
183      const s = sessionOfKey(k, p)
184      if (s !== null) return s !== own && s !== AGGREGATE && !held.has(s)
185    }
186    return false
187  })
188}
189
190export type Migration = { sets: [string, unknown][]; deletes: string[]; malformed: boolean }
191
192// I5: legacy:<s> is a function of the legacy key alone, and no owner writes that family, so two
193// processes migrating at once, before or after an owner's write to turns:<s>, write the same value
194// beside it (I1 holds strictly). pushed:<s> is written only when absent: lastAt is the newest record
195// of s under the legacy key or turns:<s>; with no record, nothing. A second run finds nothing left.
196// The legacy ledger is trimmed as the old loader did on every load: what moves is what it kept.
197export const migrationPlan = (legacyTurns: unknown, legacyPushed: unknown, present: ReadonlySet<string>, held: (session: string) => readonly TurnRecord[] | undefined): Migration => {
198  const sets: [string, unknown][] = []
199  const deletes: string[] = []
200  const records = Array.isArray(legacyTurns) ? trimmed(legacyTurns as TurnRecord[]) : []
201  const bySession = new Map<string, TurnRecord[]>()
202  for (const r of records) bySession.set(r.session, [...(bySession.get(r.session) ?? []), r])
203  for (const [session, own] of bySession) if (!present.has(keyOf(LEGACY, session))) sets.push([keyOf(LEGACY, session), own])
204  const ids = Array.isArray(legacyPushed) ? legacyPushed.filter((x): x is string => typeof x === 'string') : []
205  for (const id of new Set(ids)) {
206    const newest = newestAt([...(bySession.get(id) ?? []), ...(held(id) ?? [])])
207    if (present.has(keyOf(PUSHED, id)) || !Number.isFinite(newest)) continue
208    sets.push([keyOf(PUSHED, id), { at: 0, lastAt: newest } satisfies Pushed])
209  }
210  if (legacyTurns !== undefined) deletes.push(LEGACY_TURNS)
211  if (legacyPushed !== undefined) deletes.push(LEGACY_PUSHED)
212  return { sets, deletes, malformed: legacyTurns !== undefined && !Array.isArray(legacyTurns) }
213}
214
215// The sessions of the brief's window to measure, newest first, at most `batch`: ended with a
216// transcript named (transcript:<s>, else a legacy ended: value's), no frictions: yet, not the own session. Without a transcript nothing is measured.
217export const frictionTargets = (layout: Layout, window: ReadonlySet<string>, own: string, batch = FRICTION_BATCH): { session: string; transcript: string }[] =>
218  [...layout.transcripts]
219    .filter(([session]) => session !== own && layout.ended.has(session) && window.has(session) && !layout.frictions.has(session))
220    .map(([session, transcript]) => ({ session, transcript, newest: newestAt(layout.turns.get(session) ?? []) }))
221    .sort((a, b) => b.newest - a.newest || (a.session < b.session ? -1 : 1))
222    .slice(0, batch)
223    .map(({ session, transcript }) => ({ session, transcript }))
224
225
hooks/models.ts 59 lines
1// Who did the steps: each ledger turn's main steps and its agents' steps, counted under one model
2// family, per session. The one counting procedure the panel shows; pure, so the register and the
3// tests share it.
4
5import type { ModelFamily, SessionModels, TurnRecord } from '../types'
6import type { ProbeInfo } from './probes'
7
8export const MODEL_SESSIONS = 12 // source: own choice, the sessions the panel shows, the newest last
9
10// The families a model id is matched against, in this order: a name carrying two of them is the first.
11const MATCH: readonly Exclude<ModelFamily, 'other' | 'unknown'>[] = ['fable', 'opus', 'sonnet', 'haiku']
12// The order the steps are listed in.
13const ORDER: readonly ModelFamily[] = ['haiku', 'sonnet', 'opus', 'fable', 'other', 'unknown']
14
15// A model id reduced to its family. Empty (or missing, passed as '') is unknown; a name matching
16// no family is other.
17export const familyOf = (model: string): ModelFamily => {
18  if (model === '') return 'unknown'
19  const name = model.toLowerCase()
20  for (const family of MATCH) if (name.includes(family)) return family
21  return 'other'
22}
23
24// Each session's steps by family, the newest MODEL_SESSIONS working sessions by their latest record, oldest
25// first, probes (hooks/probes.ts) flagged and not counted among them. Every main run and every agent step is added to exactly one family, so a session's family
26// steps sum to its main steps plus its agent steps. A main turn with no mainModel (a record kept
27// before it was) is unknown. The sums are O(records); the sessions are sorted by their latest turn.
28export const sessionModels = (records: readonly TurnRecord[], probes: ReadonlyMap<string, ProbeInfo> = new Map()): SessionModels[] => {
29  const by = new Map<string, { at: number; steps: Map<ModelFamily, number> }>()
30  const add = (session: string, at: number, family: ModelFamily, steps: number) => {
31    const row = by.get(session) ?? { at, steps: new Map<ModelFamily, number>() }
32    row.at = Math.max(row.at, at)
33    row.steps.set(family, (row.steps.get(family) ?? 0) + steps)
34    by.set(session, row)
35  }
36  for (const r of records) {
37    const main = familyOf(r.mainModel ?? '')
38    for (const run of r.main) add(r.session, r.at, main, run.steps)
39    for (const a of r.agents) add(r.session, r.at, familyOf(a.model), a.steps)
40  }
41  const rows: SessionModels[] = [...by.entries()]
42    .map(([session, row]) => ({
43      session,
44      at: row.at,
45      steps: ORDER.flatMap((family) => {
46        const steps = row.steps.get(family) ?? 0
47        return steps > 0 ? [{ family, steps }] : []
48      }),
49      probe: probes.get(session)?.probe === true,
50      probeReason: probes.get(session)?.reason ?? null,
51    }))
52    .sort((a, b) => a.at - b.at)
53  // The newest MODEL_SESSIONS working sessions, and the probes newer than the oldest of them: flagged,
54  // never filling a slot of the chart.
55  const work = rows.filter((r) => !r.probe).slice(-MODEL_SESSIONS)
56  const from = work[0]?.at ?? Number.POSITIVE_INFINITY
57  return rows.filter((r) => (r.probe ? r.at >= from : work.includes(r)))
58}
59
hooks/observe.ts 59 lines
1import type { EngineInterface } from 'claude-code'
2
3import type { LiveFriction, OutcomeEvent } from '../types'
4import { type BashResult, addFriction, eventsOfBash, foldEvent, liveFrictionOf } from './events'
5import { bodyFileOf } from './review'
6import { isUnderTemp } from './probes'
7import { expandHome } from './shared'
8
9// What the turn in progress showed at tool.call, main's and its agents': the outcome events and the
10// frictions, flushed into the turn's record at turn.complete (bounded: MAX_EVENTS, MAX_LIVE_FRICTIONS).
11let events: { events: OutcomeEvent[]; dropped: number } = { events: [], dropped: 0 }
12let frictions: LiveFriction[] = []
13// The origin of this session, stamped on every record: set at session.start (isInteractive, cwd), kept across /clear and /resume.
14let origin: { nonInteractive?: boolean; tmpCwd?: true } = {}
15
16export const setOrigin = (isInteractive: boolean, cwd: string, temps: readonly (string | undefined)[]): void => {
17  origin = {
18    nonInteractive: !isInteractive,
19    ...(isUnderTemp(cwd, temps.filter((t): t is string => typeof t === 'string')) ? { tmpCwd: true as const } : {}),
20  }
21}
22
23export const originStamp = (): { nonInteractive?: boolean; tmpCwd?: true } => origin
24
25// The turn's observations, handed to its record and cleared.
26export const takeObserved = (): { events: OutcomeEvent[]; eventsDropped: number; frictions: LiveFriction[] } => {
27  const out = { events: events.events, eventsDropped: events.dropped, frictions }
28  events = { events: [], dropped: 0 }
29  frictions = []
30  return out
31}
32
33const BODY_FILE_MAX = 64 * 1024 // source: own choice, bytes of a review body file read to find its verdict; a review is a few KB (the reviewer protocol posts one comment per verdict)
34
35// A review body kept in a file, read for its verdict: null when it cannot be read or is over BODY_FILE_MAX.
36async function readBody($: EngineInterface, path: string): Promise<string | null> {
37  try {
38    const full = path.startsWith('/') || path.startsWith('~') ? await expandHome($, path) : `${await $.session.cwd()}/${path}`
39    if (!(await $.fs.exists(full)) || (await $.fs.stat(full)).size > BODY_FILE_MAX) return null
40    return await $.fs.read(full)
41  } catch {
42    return null
43  }
44}
45
46// What one finished tool call shows (events.ts): its outcome events when it is a Bash call, its friction
47// when it errored or was refused. Never throws and never changes the call: a failure here is no event.
48export async function observeCall($: EngineInterface, e: { tool: unknown; agentId?: string; command?: unknown }, ran: BashResult): Promise<void> {
49  const f = liveFrictionOf(String(e.tool), ran)
50  if (f !== null) frictions = addFriction(frictions, f)
51  if (e.tool !== 'Bash' || typeof e.command !== 'string') return
52  const file = bodyFileOf(e.command)
53  const bodyFile = file === null || ran.isError === true || ran.deny !== undefined ? undefined : file.path === null ? null : await readBody($, file.path)
54  const at = await $.clock.now()
55  for (const ev of eventsOfBash({ command: e.command, at, ...(e.agentId === undefined ? {} : { agent: e.agentId }), res: ran, ...(bodyFile === undefined ? {} : { bodyFile }) }))
56    events = foldEvent(events, ev)
57}
58
59
hooks/outcome.ts 189 lines
1// The outcome model (docs/insights-outcome-model.md): what the outcome events of a session say about
2// a delegation or about the session. Pure. The events are joined at read time over the whole session,
3// not when they are written: the revert, the review verdict and the merge usually come later than
4// the commit or the `gh pr create`, from another agent or the main thread.
5
6import type { OutcomeEvent, OutcomeJudgement, OutcomeSources, TurnRecord, Verdict } from '../types'
7import { prKey, samePr } from './events'
8
9const inTimeOrder = (events: readonly OutcomeEvent[]): OutcomeEvent[] =>
10  events
11    .map((e, i) => ({ e, i }))
12    .sort((a, b) => a.e.at - b.e.at || a.i - b.i)
13    .map(({ e }) => e)
14
15// A call that named a pull request by number alone (`gh pr merge 24`) means the repository the session
16// named it with elsewhere (`o/r#24`), when that is one repository: the key is then qualified, so it can
17// be joined with another session's. A number two repositories share in the session stays bare.
18const qualified = (events: readonly OutcomeEvent[]): OutcomeEvent[] => {
19  const repos = new Map<string, Set<string>>()
20  for (const e of events) {
21    const [repo, n] = (e.pr ?? '').split('#')
22    if (repo !== undefined && repo !== '' && n !== undefined) repos.set(n, (repos.get(n) ?? new Set()).add(repo))
23  }
24  return events.map((e) => {
25    const [repo, n] = (e.pr ?? '').split('#')
26    const only = repo === '' && n !== undefined ? repos.get(n) : undefined
27    return only !== undefined && only.size === 1 ? { ...e, pr: prKey([...only][0]!, n!) } : e
28  })
29}
30
31// A session's events in time order (ties keep their order of writing), pull requests qualified.
32export const eventsOf = (records: readonly TurnRecord[]): OutcomeEvent[] => qualified(inTimeOrder(records.flatMap((r) => r.events ?? [])))
33
34const REVIEW_KINDS: readonly OutcomeEvent['kind'][] = ['verdict', 'pr-merge', 'pr-close']
35
36// Each session's own events, and the review, merge and close events other sessions wrote about the
37// pull requests it names (`owner/repo#N`: a number without its repository joins nothing across sessions).
38// The ledger is bounded by the store trim, so a session whose later events were trimmed away is judged
39// on what is kept. The join is read-time, so a later event re-judges an earlier session.
40export type SessionEvents = { own: OutcomeEvent[]; foreign: OutcomeEvent[] }
41export const eventsBySession = (records: readonly TurnRecord[]): Map<string, SessionEvents> => {
42  const by = new Map<string, TurnRecord[]>()
43  for (const r of records) by.set(r.session, [...(by.get(r.session) ?? []), r])
44  const own = new Map([...by].map(([session, rs]) => [session, eventsOf(rs)] as const))
45  const index = new Map<string, { session: string; e: OutcomeEvent }[]>()
46  for (const [session, events] of own)
47    for (const e of events) if (e.pr !== undefined && REVIEW_KINDS.includes(e.kind)) index.set(e.pr, [...(index.get(e.pr) ?? []), { session, e }])
48  const out = new Map<string, SessionEvents>()
49  for (const [session, events] of own) {
50    const keys = new Set(events.flatMap((e) => (e.pr === undefined || e.pr.startsWith('#') ? [] : [e.pr])))
51    const foreign = [...keys].flatMap((k) => (index.get(k) ?? []).filter((x) => x.session !== session).map((x) => x.e))
52    out.set(session, { own: events, foreign: inTimeOrder(foreign) })
53  }
54  return out
55}
56
57type Commit = { sha: string; at: number; agent: string | undefined; reverted: boolean; discarded: boolean }
58
59const prefixed = (a: string, b: string): boolean => a.startsWith(b) || b.startsWith(a)
60const count = (e: OutcomeEvent): number => e.n ?? 1
61
62// The commits the events show, each marked reverted (`git revert`), or possibly discarded (a
63// `git reset HEAD~n`), in the order they were made. An amend replaces the actor's latest live commit.
64const commitsOf = (events: readonly OutcomeEvent[]): Commit[] => {
65  const commits: Commit[] = []
66  for (const e of events) {
67    if (e.kind === 'commit' && e.ok !== false && e.sha !== undefined) {
68      const old = e.label === 'amended' ? [...commits].reverse().find((c) => c.agent === e.agent && !c.reverted) : undefined
69      if (old !== undefined) commits.splice(commits.indexOf(old), 1) // the old one is not a failure
70      commits.push({ sha: e.sha, at: e.at, agent: e.agent, reverted: false, discarded: false })
71    } else if (e.kind === 'revert' && e.sha !== undefined) {
72      const sha = e.sha
73      const target = sha === 'head' ? [...commits].reverse().find((c) => c.at <= e.at && !c.reverted) : commits.find((c) => prefixed(c.sha, sha))
74      if (target !== undefined) target.reverted = true
75    } else if (e.kind === 'reset' && e.back !== undefined) {
76      // `git reset HEAD~n` may have dropped the n latest live commits; with another target it is not readable which.
77      for (const c of [...commits].reverse().filter((c) => c.at <= e.at && !c.reverted && !c.discarded).slice(0, e.back)) c.discarded = true
78    }
79  }
80  return commits
81}
82
83type PrState = { rounds: number; approved: boolean; stale: boolean; closed: boolean; changes: boolean; unreviewedMerge: boolean; open: boolean }
84
85// What the verdicts, merges and closes say about the scope's pull requests: those it created, those whose
86// verdict cites one of its commits, and (for the whole session) every one reviewed. `foreign` holds the
87// review, merge and close events other sessions wrote about the same `owner/repo#N`. A merge or close
88// counts only when its call proved it (`ok` true).
89const prState = (events: readonly OutcomeEvent[], foreign: readonly OutcomeEvent[], scope: string | null, mine: readonly Commit[]): PrState => {
90  const live = mine.filter((c) => !c.reverted)
91  const lastCommitAt = live.reduce((m, c) => Math.max(m, c.at), Number.NEGATIVE_INFINITY)
92  const created = events.filter((e) => e.kind === 'pr-create' && e.ok !== false && e.pr !== undefined && (scope === null || e.agent === scope)).map((e) => e.pr!)
93  const verdicts = events.filter((e) => e.kind === 'verdict' && e.pr !== undefined)
94  const viaHead = verdicts.filter((v) => v.head !== undefined && mine.some((c) => prefixed(c.sha, v.head!))).map((v) => v.pr!)
95  // One entry per pull request: the same PR is named `o/r#24` by one call and `#24` by another.
96  const prs: string[] = []
97  for (const pr of [...created, ...viaHead, ...(scope === null ? verdicts.map((v) => v.pr!) : [])]) if (!prs.some((q) => samePr(q, pr))) prs.push(pr)
98  const st: PrState = { rounds: 0, approved: false, stale: false, closed: false, changes: false, unreviewedMerge: false, open: false }
99  for (const pr of prs) {
100    const about = inTimeOrder([...events.filter((e) => samePr(e.pr, pr)), ...foreign.filter((e) => e.pr === pr)])
101    const vs = about.filter((e) => e.kind === 'verdict' && e.verdict !== 'unknown')
102    st.rounds += vs.filter((v) => v.verdict === 'changes').reduce((n, v) => n + count(v), 0)
103    const last = vs[vs.length - 1]
104    const merged = about.some((e) => e.kind === 'pr-merge' && e.ok === true)
105    const closed = !merged && about.some((e) => e.kind === 'pr-close' && e.ok === true)
106    if (closed) st.closed = true
107    if (!merged && !closed) {
108      st.open = true
109      if (last?.verdict === 'changes') st.changes = true
110    }
111    if (merged && last?.verdict === 'changes') st.unreviewedMerge = true
112    if (!merged || last?.verdict !== 'approve') continue
113    const headOk = last.head === undefined || live.length === 0 || live.some((c) => prefixed(c.sha, last.head!))
114    if (last.at >= lastCommitAt && headOk) st.approved = true
115    else st.stale = true
116  }
117  return st
118}
119
120type TestState = { red: boolean; green: boolean; passed: number; failed: number }
121
122// The test runs of the scope that could be read: red when the final run of some label failed, green
123// when a label's final run passed after the last commit.
124const testState = (events: readonly OutcomeEvent[], scope: string | null, lastCommitAt: number): TestState => {
125  const tests = events.filter((e) => e.kind === 'test' && (scope === null || e.agent === scope) && e.ok !== null && e.ok !== undefined)
126  const finalByLabel = new Map<string, OutcomeEvent>()
127  for (const t of tests) finalByLabel.set(t.label ?? '', t)
128  const finals = [...finalByLabel.values()]
129  return {
130    red: finals.some((t) => t.ok === false),
131    green: finals.some((t) => t.ok === true && t.at >= lastCommitAt),
132    passed: tests.filter((t) => t.ok === true).reduce((n, t) => n + count(t), 0),
133    failed: tests.filter((t) => t.ok === false).reduce((n, t) => n + count(t), 0),
134  }
135}
136
137// The judgement of `scope`: a delegation's agentId, or null for the whole session (the main thread
138// and every agent). Total.
139export const judge = (events: readonly OutcomeEvent[], scope: string | null, foreign: readonly OutcomeEvent[] = []): OutcomeJudgement => {
140  const mine = commitsOf(events).filter((c) => scope === null || c.agent === scope)
141  const live = mine.filter((c) => !c.reverted)
142  const lastCommitAt = live.reduce((m, c) => Math.max(m, c.at), Number.NEGATIVE_INFINITY)
143  const pr = prState(events, foreign, scope, mine)
144  const t = testState(events, scope, lastCommitAt)
145  const reverted = mine.length - live.length
146  const base = { rounds: pr.rounds, commits: mine.length, reverted, possiblyDiscarded: live.filter((c) => c.discarded).length, testsPassed: t.passed, testsFailed: t.failed }
147  const done = (verdict: Verdict, reason: OutcomeJudgement['reason']): OutcomeJudgement => ({ verdict, reason, ...base })
148  if (reverted > 0) return done('not-achieved', 'reverted')
149  if (pr.approved) return done('achieved', 'merged-approved')
150  if (pr.stale) return done('unclear', 'approve-stale')
151  if (pr.closed) return done('not-achieved', 'closed')
152  // A merge after REQUEST-CHANGES with no later APPROVE: merged, but never reviewed good. Neither side.
153  if (pr.unreviewedMerge) return done('unclear', 'merged-unapproved')
154  // A pull request still open is not a failure: it is waiting for the next review, merge or close.
155  if (pr.changes || (scope !== null && pr.open)) return done('unclear', 'pending')
156  if (t.red && mine.length > 0) return done('not-achieved', 'tests-red')
157  // A delegation is achieved by its PR alone; a session with commits and a green run after the last of them is verified work.
158  if (scope === null && live.length > 0 && t.green && !t.red) return done('achieved', 'verified')
159  return done('unclear', 'no-signal')
160}
161
162// Each session's outcome: the events' judgement when they say (external, observed), else the
163// /insights facet when there is one. Both saying something different is counted in `disagree`, and the
164// events stand. `sources` counts the sessions given by where their outcome came from.
165export const combineOutcomes = (records: readonly TurnRecord[], facets: ReadonlyMap<string, Verdict>): { outcomes: Map<string, Verdict>; sources: OutcomeSources } => {
166  const by = new Map<string, TurnRecord[]>()
167  for (const r of records) by.set(r.session, [...(by.get(r.session) ?? []), r])
168  const outcomes = new Map<string, Verdict>()
169  const sources: OutcomeSources = { events: 0, facets: 0, both: 0, disagree: 0, unclear: 0 }
170  const joined = eventsBySession(records)
171  for (const session of by.keys()) {
172    const j = joined.get(session)
173    const fromEvents = judge(j?.own ?? [], null, j?.foreign).verdict
174    const fromFacet = facets.get(session) ?? 'unclear'
175    if (fromEvents !== 'unclear') {
176      outcomes.set(session, fromEvents)
177      if (fromFacet === 'unclear') sources.events += 1
178      else {
179        sources.both += 1
180        if (fromFacet !== fromEvents) sources.disagree += 1
181      }
182    } else if (fromFacet !== 'unclear') {
183      outcomes.set(session, fromFacet)
184      sources.facets += 1
185    } else sources.unclear += 1
186  }
187  return { outcomes, sources }
188}
189
hooks/probes.ts 51 lines
1// Which sessions are probes (a test of the harness, not work): kept out of learning, still counted.
2// Pure. One rule, written once here; the register stamps the origin on every record, the replay of an
3// old ledger reads the transcript path the store kept.
4
5import type { ProbeReason, TurnRecord } from '../types'
6
7// source: macOS and Linux temp roots (`/tmp` -> `/private/tmp`, `$TMPDIR` under /var/folders), the
8// directories `claude -p` probes and the harness's own scratch runs were found in (audit
9// 2026-10-15: 9 of 20 probe sessions under /private/tmp, the 6 others under a scratch path); the
10// caller adds the process's TMPDIR, TEMP and TMP.
11export const TEMP_ROOTS: readonly string[] = ['/tmp', '/private/tmp', '/var/tmp', '/private/var/tmp', '/var/folders', '/private/var/folders']
12
13const norm = (p: string): string => p.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
14
15export const isUnderTemp = (cwd: string, extraRoots: readonly string[] = []): boolean => {
16  const dir = norm(cwd)
17  return [...TEMP_ROOTS, ...extraRoots].map(norm).filter((r) => r !== '').some((r) => dir === r || dir.startsWith(`${r}/`))
18}
19
20// A transcript path is `<config>/projects/<cwd with / and . as ->/<session>.jsonl`: the folder name
21// is the working directory of the session. Only the temp roots' encodings are read from it.
22export const tempProjectDir = (transcript: string): boolean => {
23  const m = /\/projects\/([^/]+)\/[^/]+$/.exec(transcript.replace(/\\/g, '/'))
24  return m !== null && /^-(?:private-)?(?:tmp|var-tmp|var-folders)(?:-|$)/.test(m[1]!)
25}
26
27export type ProbeInfo = { probe: boolean; reason: ProbeReason | null; steps: number }
28
29// A session is a probe when (1) its working directory is under the OS temp dir (stamped on its
30// records, or read from its transcript path), whatever its length; or (2) it was non-interactive (a
31// `-p` run or the SDK) and took at most one main step; or (3) nothing is known of its origin
32// (records written before the origin was kept) and it is a single main step with no agent. The step
33// count is main's steps, not turns: a 1-turn session of 3 steps is work.
34export const probeOf = (records: readonly TurnRecord[], transcript?: string): ProbeInfo => {
35  const steps = records.reduce((n, r) => n + r.main.reduce((m, run) => m + run.steps, 0), 0)
36  const agents = records.some((r) => r.agents.length > 0)
37  const stamped = records.some((r) => r.nonInteractive !== undefined || r.tmpCwd === true)
38  if (records.some((r) => r.tmpCwd === true) || (transcript !== undefined && tempProjectDir(transcript))) return { probe: true, reason: 'temp-cwd', steps }
39  if (records.some((r) => r.nonInteractive === true) && steps <= 1) return { probe: true, reason: 'non-interactive-1-step', steps }
40  if (!stamped && steps <= 1 && !agents) return { probe: true, reason: 'one-step-unknown', steps }
41  return { probe: false, reason: null, steps }
42}
43
44export const probesOf = (records: readonly TurnRecord[], transcripts: ReadonlyMap<string, string> = new Map()): Map<string, ProbeInfo> => {
45  const by = new Map<string, TurnRecord[]>()
46  for (const r of records) by.set(r.session, [...(by.get(r.session) ?? []), r])
47  return new Map([...by].map(([s, rs]) => [s, probeOf(rs, transcripts.get(s))]))
48}
49
50export const withoutProbes = <T extends { session: string }>(records: readonly T[], probes: ReadonlyMap<string, ProbeInfo>): T[] => records.filter((r) => probes.get(r.session)?.probe !== true)
51