SLOPSHOPPER

Factory loop

Draft, not yet shipped: the issue orchestrator as one deterministic code loop inside its Claude Code session. Every minute, or at once when an agent or the…

★ 3v0.99.1no licenseupdated 2026-10-25cbundy/dev-system/plugins/factory-loop
A shopper browsing a rack in a slop shop
Preview could not run: harness produced no result (120 | const r await run(ctx, ARGV.prReadArgv(pr), READ_MS) ^ warn: Import "prReadArgv" will always be undefined because there is no
README

factory-loop

The issue orchestrator as one deterministic code loop inside its Claude Code session. Every minute it reads the factory's whole state, computes what to do with a pure plan() function, and does it: claims, heartbeats, sweeps, agents, gate responses, guards, merges and the status title. The model is woken only for judgment (the hourly release review) and to talk to the owner; agents read the code.

State of this build

Both halves are built. In observe mode (the default) every pass reads the factory, plans, logs its decisions and shows its status in the session title, and executes nothing: every event its commands cause goes to a local sink. In act mode, once every safety rail passes (v2 SPEC 13.11.2), it also carries the plan out: it keeps a ledger of what it started, runs each action through its executor, starts its agents (its own, agents/), and wakes the model for judgment. The plugin is listed in the marketplace.

PieceFileState
The decision tablehooks/v2/ (the rules) and hooks/foundation.ts (what they share), puredone
Parsers, event derivation, state assemblyhooks/parse.ts, hooks/derive.ts, hooks/state.tsdone, pure
Observe adaptershooks/observe.tsdone; running as a shadow in spike-reconcile-mod
The pass driver: the store, the scheduler, the decision log, the hookshooks/register.tsdone
The act step and the ledgerhooks/act.ts, hooks/ledger.ts, hooks/exec.tsdone
Executors: commands, the rollout read, v2's effects and agent steps, prompts and reply parsershooks/act-cli.ts, hooks/act-merge.ts, hooks/v2/act-*.ts, hooks/v2/steps*.ts, hooks/prompts.tsdone
Wakes and the answer toolhooks/wake.tsdone
The loop's agent definitionsagents/done
The answer script and the contract it shares with the loop (a temporary workaround, D-74)bin/factory-answer, hooks/contract.mjsdone; not yet run by real agents
Safety railshooks/rails.tsdone
/factory and the control toolhooks/control.tsdone
The judge skillskills/judge/SKILL.mddrafted; not yet tried on a real wake
--once watcher modes, the loop event statefeatures/src/callum-tools/, images/base/callum-flow-event (repo root)done; ship in the next base image release
Teststests/scenarios with the plan's properties on every plan, parsers, each executor, the rails, the driver in the engine's test host, the answer contract the script shares, and one issue from claim to merge
Replay harnessscripts/factory-loop-replay.js (repo root)done; writes only to the --out folder it is given

Run it in observe mode

Load the folder with claude --plugin-dir plugins/factory-loop, or name it in CLAUDE_CODE_PLUGIN_DIRS, and set ${CLAUDE_CONFIG_DIR:-~/.claude}/factory-loop/config.json:

{ "mode": "observe", "repo": "cbundy/dev-system", "runSource": "events",
  "shadowDevice": "coder-dev-system-orchestrator", "checkout": "/path/to/dev-system" }

Decisions go to ${CLAUDE_CONFIG_DIR}/factory-loop/<owner>__<repo>/decisions-YYYY-MM-DD.jsonl. Each pass also rewrites settings.json beside them: the settings in force and where each came from. An acting pass also rewrites github.json: the GitHub API errors its commands met in the last hour, which the worker heartbeat reports. Owner directives go in control.json, best set with /factory (below). Create ${CLAUDE_CONFIG_DIR}/factory-loop/OFF to stop it within a minute.

Run it in act mode

Act mode replaces the released orchestrator; never run both on one repo. Load the plugin as above and set the workspace file:

{ "mode": "act", "repo": "<owner>/<repo>", "checkout": "/path/to/the/repo",
  "toolsDir": "/path/to/dev-system/features/src/callum-tools",
  "binDir": "/path/to/dev-system/images/base" }

toolsDir and binDir point at a checkout of this branch until a base image release carries the --once modes and the loop event state; without them the loop uses the image's tools. Then every pass checks, before it acts:

  • the checkout's origin is repo;
  • DEV_ROLE=orchestrator, or "allowActOutsideOrchestrator": true in the repo's .claude/factory-loop.json (for a testbed);
  • no orchestrator-watch.sh is armed for the repo, and none has been for 10 minutes;
  • no other orchestrator workspace on the repo has sent a heartbeat in the last 2 minutes, and this one has a DEV_MACHINE_NAME;
  • no other session in this workspace holds the act lock.

While any fails, the pass runs as observe mode does, the title says observe, and the decision log's rails field says why (executed says whether a pass acted). An armed old watcher or another orchestrator's heartbeat is also told to you, once each time it starts. /factory mode observe or the OFF file stops act mode at the next pass.

An acting pass also writes the claim queue it saw as a queue_snapshot event (when it changes, as a quarter-hour heartbeat otherwise, and at once on a pass that claims); it never waits on the write.

The /factory command

/factory <op> sets the loop's owner directives from any client, at once, even during a long wake turn; in chat, the model does the same through mcp__factory-loop__control when you ask. Each change is logged and asks for a pass at once. The ops:

  • status (or no op): the last pass and the directives in force; help lists the ops;
  • config: the settings the loop runs with, grouped, each with its source (default, repo, workspace, plugin or directive), read-only; "what is this factory's config?" is answered with it;
  • pause <N> / unpause <N>: no action at all on N, though its claim still renews;
  • skip <N> / noskip <N>: never claim N;
  • priority <N...>|off: claim these first, in order; the rest go by score (highest first), where the priorityLabel label (default priority) is one factor among bug, what it unblocks, its epic, waiting time and earlier failed lives (weights: queueScore); with intakeStamp on (off by default) an issue with a stamp also scores area-factory, needs-owner and overlap, and the loop stamps each ready issue once per body version (rule I1: a reader on intakeModel per issue, at most two at once, none for a version already tried, the edited body once more) and sets area:<area> and, when it needs the owner, needs-decision on it, the owner's own labels always winning: a label group the owner changed, or that the issue carried before the first stamp, is never touched again, and the loop removes only labels it set; each try writes one intake_stamp event with its token cost;
  • only <N...>|off: claim only these, in order (a tracker stands for its open sub-issues);
  • serial on|off: one issue in flight at a time;
  • new on|off: off starts no new claims, designs or implementations;
  • override <pct> <hours>|off: run past the usage tiers up to pct, for up to 168 hours;
  • resume <N...> ["note"]: unpark issues that are parked, with an optional note for their next step; on an issue that is not parked it changes nothing. See the owner ops for what each op does;
  • retry <N>: let N's exhausted actions run again;
  • update [<reason>]|off: winds down (up to windDownMinutes), then restarts this workspace (refused, with the reason, when the workspace cannot restart itself);
  • drop <N>: abandon N and stop its agents;
  • stamp <N>: dry-run the intake reader on N and report its answer when it ends; writes nothing (no label, comment, event, stamp or ledger change), and works with intakeStamp off and in observe mode;
  • note [<N>] <text>|off: an instruction the next agent prompts carry, for N or for all (a newer note replaces the older one; off clears it);
  • mode off|observe|act: written to the workspace file, from the next pass;
  • trace on|off: trace mode (below), written to the workspace file, from the next pass.

A malformed op changes nothing and answers with its usage.

Trace mode

Every decision-log line says what triggered its pass and how long it took (trigger, ms). For more, turn trace mode on: /factory trace on, "trace": true in the workspace file, or "trace": true in the repo's .claude/factory-loop.json (the workspace file wins). Each pass then writes one record to trace-YYYY-MM-DD.jsonl beside the decision log: each phase's time, every command with its time, exit and bytes, which sources came from the cache, each action's times, the wakes' latencies, and what each issue waits on and since when. The sweep, the heartbeat, the merge and the session title's rename run off the pass: their action row says off and the next record's offPass lists the commands that finished, with their time and exit (and, for a title rename that failed, its error). The trace files are kept under traceMaxBytes (100 MiB) in all: the oldest go first, and a day's file that alone fills the cap is cut short. v2 SPEC 13.12.1 explains each field, with jq examples.

How agents answer

The intended design is that the loop's agents answer through validated tools (mcp__factory-loop__verdict, design and handoff). But on Claude Code 2.1.296 and 2.1.299 an agent the loop spawns from its timer never reaches them (v2 SPEC 13.13). So, as a temporary workaround, agents record their answer with a checked script, bin/factory-answer: each prompt names the script and an answer file for that one attempt, the script checks the JSON against the same contract the tools use (hooks/contract.mjs) and names every problem (a design wait's conditions are also checked on GitHub, hooks/v2/wait-check.mjs), and the loop reads the file when the agent's turn ends (v2 SPEC 13.7.3a, DECISIONS D-74). Text stays the fallback, and the decision log says which way each answer came (script, tool, text, repair).

answerChannel picks the channel, in the repo's .claude/factory-loop.json or in the workspace file (which wins): script (the default, the workaround), tool (the tools), or text (the text contract alone). The tools stay registered and served whatever it says. Run the timer-spawn probe (docs/factory-loop/probes/timer-spawn-probe) on each Claude Code upgrade; once its timer-spawned agent reaches the tool, set answerChannel to tool and retire the script. answerTools, the setting it replaced, is no longer read.

Pinned Claude Code version

Proven on Claude Code 2.1.296, the version the spike tested in the orchestrators' exact launch mode. The mod API is early access and may change between releases. Before running the loop on a newer Claude Code:

  1. Run npm test: claude plugin validate and claude plugin test check this plugin against the new build's engine.
  2. Type-check against the new declarations: load the plugin-authoring skill, which writes them and names their path, then run tsc with the tsconfig.json from that file's header, including hooks/, types/ and tests/.
  3. Re-run the spike's five checks in a throwaway workspace (load, timer, title through /rename, agents in bypass mode, restart), as its README describes, and the wake probe (docs/factory-loop/probes/wake-probe/), which proves the judgment wake and its answers.
  4. Run the timer-spawn probe (docs/factory-loop/probes/timer-spawn-probe/, its header says how): once an agent spawned from a timer reaches the probe's tool, the answer script can give way to the tools (above).

Develop it

A test that drives the engine (async ($, on) =>) passes ENGINE_TEST from tests/host.ts as its second argument: the plugin loads afresh per test and the passes are CPU, so the kit's 5 s wall-clock default fails on a loaded machine. It is a budget, not a retry, and tests/factory-loop-test-timeouts.test.js fails npm test without it.

npm test runs the plugin's tests through claude plugin test, and ten node tests at the repo root: tests/factory-loop-plan.test.js checks that foundation.ts and v2's planner stay pure; factory-loop-agents.test.js checks that every agent the loop spawns lists its answer tool, and that the loop's adjudicator and designer stay the callum-flow definitions but for tools: and the one sentence that lets the adjudicator run the answer script; factory-loop-safety.test.js scans every string in hooks/ and the answer script for a forbidden command, and the script's source for any write but its one answer file; factory-loop-answer.test.js runs the answer script for real: its exit codes, every problem it names (held to the same table of cases as the loop's own reading, tests/answer-cases.mjs), its atomic write and every path it must refuse, and runs the answer block of a rendered prompt through bash as an agent copies it; factory-loop-judge-skill.test.js checks the judge skill covers every wake, TELL kind and op; and factory-loop-prune.test.js and factory-loop-loop-events.test.js run the daily prune and every loop note for real, against scratch directories. foundation.ts also imports under plain Node, which the replay harness uses.

Source 91 files
hooks/register.ts 100 lines
1// factory-loop: the issue orchestrator as one code loop (docs/factory-loop/v2/SPEC.md 13).
2//
3// Every passEveryMs, or at once when pinged, a pass reads the factory (observe.ts) and plans
4// (v2/plan.ts). In act mode, once the safety rails pass (rails.ts: the act lock, the role, the old
5// watcher, another orchestrator's heartbeat), it runs plan's actions through their executors
6// (act.ts) and records each in the ledger (ledger.ts), which it keeps in $.store. In observe mode
7// (the default), or while a rail holds act mode back, it executes nothing and every command's
8// event writes go to a sink (v2 SPEC 13.11.1). Each pass appends one decision-log line and sets the
9// session title. The driver is this module and the driver-*.ts modules under it, the only ones
10// that hold $: this one wires the hooks; driver-state.ts holds the state they share (one holder,
11// `S`), driver-io.ts builds the engine calls, driver-store.ts keeps the ledger in $.store,
12// driver-pass.ts schedules and runs a pass (driver-pass-log.ts its trace), driver-between.ts feeds
13// the ledger between passes (agents' answers and their repair messages; wake turns) and
14// driver-controls.ts holds the owner's controls (/factory, the control and answer tools) and
15// ensure. The loop's own agent types (agents/) are kept from the model here. v2's records and the PR
16// heads it has seen live in the store beside the ledger (records:<repo>, heads:<repo>).
17import type { Register } from 'claude-code'
18
19import { agentTurnEnded, hook, mainTurnEnded, releaseLock, turnStarted } from './driver-between'
20import type { TurnEnded } from './driver-between'
21import { answer, ensure, ownerOp, toolInput } from './driver-controls'
22import { S, resuming } from './driver-state'
23import type { Options } from './driver-state'
24import { issueFromBranch } from './foundation'
25import { INTAKE_AGENT } from './v2/intake'
26import { STEP_AGENT } from './v2/types'
27import { BASH_TIMEOUT_MS } from './v2/workspace'
28
29export const register: Register = (on, opts) => {
30  S.options = opts as Options
31
32  on('session.start', async ($, e, next) => {
33    const result = await next(e)
34    // the 10-minute Bash timeout for every agent the loop starts (v2 SPEC 10.5)
35    await $.env.set('BASH_DEFAULT_TIMEOUT_MS', BASH_TIMEOUT_MS).catch(() => undefined)
36    await $.env.set('BASH_MAX_TIMEOUT_MS', BASH_TIMEOUT_MS).catch(() => undefined)
37    S.cwd = e.cwd
38    if (!e.isInteractive) S.headless = true
39    else await ensure($)
40    return result
41  })
42
43  // The note /rename leaves for the model is blanked as it is stored, so a title costs the
44  // conversation about 3 tokens (FINDINGS check 3). Any row also starts the loop if needed.
45  on('session.append', async ($, e, next) => {
46    if (!S.headless) void ensure($)
47    const isRenameNote =
48      e.door === 'prompt' && e.origin.kind === 'plugin' && JSON.stringify(e.message.content ?? '').includes('named this session')
49    return next(isRenameNote ? { ...e, message: { ...e.message, content: [] } } : e)
50  }).catch(($, e, next) => next(e))
51
52  // Turns feed the ledger after they are answered; what any turn returns is never changed.
53  on('turn.start', async ($, e, next) => {
54    const result = await next(e)
55    await hook(() => turnStarted($, e.text, e.turnId))
56    return result
57  }).catch(($, e, next) => next(e))
58
59  on('turn.complete', async ($, e, next) => {
60    const result = await next(e)
61    const ended: TurnEnded = { turnId: e.turnId, answer: e.answer, reason: e.reason }
62    const agentId = e.agentId
63    await hook(() => (agentId === undefined ? mainTurnEnded($, ended) : agentTurnEnded($, { ...ended, agentId })))
64    return result
65  }).catch(($, e, next) => next(e))
66
67  // session.end has one short bound for every hook: the lease goes first
68  on('session.end', async ($, e, next) => {
69    await releaseLock($, e.sessionId).catch(() => undefined)
70    return next(e)
71  }).catch(($, e, next) => next(e))
72
73  // /factory <op>: the owner's controls from any client (v2 SPEC 13.4.3)
74  on('command.run', { command: 'factory' }, async ($, e) => ({ text: (await ownerOp($, e.args, undefined, 'person')).text })).catch(() => ({
75    text: 'factory-loop: the op could not run; nothing was changed.',
76  }))
77
78  on('tool.call', { tool: 'mcp__factory-loop__control' }, async ($, e) => {
79    const r = await ownerOp($, toolInput(e), e.agentId, 'judge')
80    return r.ok ? { result: r.text } : { deny: r.text }
81  }).catch(($, e, next) => (next.called ? next(e) : { deny: 'factory-loop: the op could not run; nothing was changed.' }))
82
83  on('tool.call', { tool: 'mcp__factory-loop__answer' }, async ($, e) => {
84    const r = await answer($, toolInput(e), e.agentId)
85    return r.ok ? { result: r.text } : { deny: r.text }
86  }).catch(($, e, next) => (next.called ? next(e) : { deny: 'factory-loop: the answer could not be recorded.' }))
87
88  // the loop's own agent types (agents/) are its spawns alone: the model is
89  // never offered them, so it keeps to the callum-flow agents it knows. The engine asks too when a
90  // message resumes an agent, and resumes none of a type it does not offer: while the loop's own
91  // repair message to one is on its way (repairTo), its type is offered (#559)
92  // the loop's agent types (v2/types.ts STEP_AGENT and the intake agent), hidden as above
93  for (const agent of new Set([...Object.values(STEP_AGENT), INTAKE_AGENT])) {
94    on('agent.offer', { agent }, ($, e, next) => (resuming.has(e.agent) ? next(e) : { isOffered: false })).catch(($, e, next) => (next.called ? next(e) : { isOffered: false }))
95  }
96}
97
98// for the tests
99export const testing = { issueFromBranch }
100
hooks/driver-between.ts 275 lines
1// Between passes: the hooks that feed the ledger (agents' answers and their repair messages, wake
2// turns), the queue they run in, and the bound a tool hook answers within (#558).
3import type { EngineInterface } from 'claude-code'
4
5import { logLoop, transition } from './act'
6import type { ActEnv } from './act'
7import { completeOff } from './act-off'
8import type { OffDone } from './act-off'
9import { agentAnswered, intakeAnswered, keep, wakeEnded, wakeStarted } from './act-between'
10import type { Answered, Claim, Repair } from './act-between'
11import type { Runtime } from './observe'
12import { actLockPath, releaseActLock } from './rails'
13import { attemptOf } from './trace'
14import type { LedgerEntry } from './types'
15import { within } from './within'
16import { appendLine, killed, lockIo, lockOp, mayWrite, message, runtime } from './driver-io'
17import { stampEnded } from './driver-stamp'
18import { bareState, ensureLedger, hookEnv, persist } from './driver-store'
19import { SESSION_STOPPED, markHeld } from './session-hold'
20import { REPAIR_TIMEOUT_MS, S, TOOL_ANSWER_MS, between, delivered, live, ping, resuming } from './driver-state'
21import type { After } from './driver-state'
22
23// hook: hook work that reads and changes the ledger, one at a time and in the order the events
24// came (a wake's turn.start before its turn.complete). A tool call never waits here: it changes
25// the ledger in memory at once and leaves the rest to this queue (later, #558).
26export function hook(work: () => Promise<void>): Promise<void> {
27  const run = S.hooking.then(work)
28  S.hooking = run.catch(() => undefined)
29  return S.hooking
30}
31
32// ledgerFor: the runtime a hook works with, while the loop is in act mode with no kill switch
33// (v2 SPEC 13.11.1, 13.11.3: observe and off log no real event and keep no ledger), once the ledger is
34// loaded: by this module already, or now (an answer that comes before the first pass after a
35// reload).
36export async function ledgerFor($: EngineInterface): Promise<Runtime | null> {
37  if (S.headless) return null
38  const rt = S.lastRt ?? (await runtime($).catch(() => null))
39  if (rt === null || rt.repo === '' || rt.mode !== 'act' || (await killed($))) return null
40  if (live.loaded && live.repo === rt.repo) return rt
41  return (await ensureLedger($, rt, [])) ? rt : null
42}
43
44// held: the runtime a tool call is decided against, from memory alone (#558): the last pass's,
45// in act mode with no kill switch, with its ledger loaded. 'none': this session keeps no ledger
46// (observe, off, the kill switch, a session no person reaches); 'loading': it has not loaded one
47// yet (no pass since this module loaded, the store unread, the act lock another session's).
48// Nothing is loaded here, so a call never waits on ensureLedger.
49export async function held($: EngineInterface): Promise<Runtime | 'none' | 'loading'> {
50  if (S.headless) return 'none'
51  const rt = S.lastRt
52  if (rt === null) return 'loading'
53  if (rt.repo === '' || rt.mode !== 'act' || (await killed($))) return 'none'
54  return live.loaded && live.repo === rt.repo ? rt : 'loading'
55}
56
57// later: what a tool call leaves for once it has answered, in the hook queue behind the hook work
58// before it, with the $ the loop's timers run with (background), never the call's own, whose
59// dispatch has ended by then. A call that changed the ledger has it saved at once, outside the
60// hook queue (persist keeps its own order), so a reload or a crash before its turn in the queue
61// never loses it: its entry would be marked lost and its work redone.
62export function later($: EngineInterface, after: After) {
63  if (after.run !== undefined) {
64    if (S.saveNow !== null) S.saveNow(after.rt)
65    else void persist($, after.rt)
66  }
67  if (S.background !== null) S.background(after)
68  else void hook(() => afterwards($, after))
69}
70
71// afterwards: one After, in the hook queue.
72export async function afterwards($: EngineInterface, after: After) {
73  const env = hookEnv($, after.rt, await $.clock.now())
74  const notes = after.run === undefined ? [] : await after.run(env)
75  if (after.line !== undefined) await appendLine($, after.rt, after.line([...notes, ...env.problems]))
76  if (after.ping !== undefined) ping(after.ping)
77}
78
79// offPassDone: an off-pass command ended (act-off.ts): its completion runs in the hook queue, never in a
80// pass. It changes nothing and writes nothing unless this session still holds the loaded ledger and the
81// act lock; a completion for an attempt that already ended is dropped. One decision-log line names it,
82// the trace gets its row, a rate limit is left for the next pass's backoff, and a pass is pinged.
83export function offPassDone($: EngineInterface, rt: Runtime, done: OffDone): Promise<void> {
84  return hook(async () => {
85    let applied = false
86    if (live.loaded && live.repo === rt.repo) {
87      if (await mayWrite($, rt)) applied = await completeOff(hookEnv($, rt, await $.clock.now()), done)
88      else live.loaded = false
89    }
90    const failed = done.exec.status === 'failed'
91    const cli = done.exec.status === 'done' ? 0 : done.exec.status === 'failed' && done.exec.outcome?.kind === 'cli' ? done.exec.outcome.exit : -1
92    S.offFinished.push({ cmd: done.kind, key: done.key, ms: Math.round(done.ms * 10) / 10, exit: cli, endedAt: new Date(done.endedAt).toISOString() })
93    S.offFinished.splice(0, S.offFinished.length - 100)
94    if (applied && failed && done.exec.rateLimited === true) S.offRateLimited = true
95    await appendLine($, rt, { offPass: { key: done.key, kind: done.kind, status: done.exec.status, ms: Math.round(done.ms), summary: done.exec.summary, ...(applied ? {} : { dropped: true }) } })
96    ping(`off-pass ${done.key}`)
97  }).catch(() => undefined)
98}
99
100// kept: an After's ledger work for a transition a hook made at once: saved, then logged.
101export function kept(moved: readonly LedgerEntry[]) {
102  return async (env: ActEnv): Promise<string[]> => {
103    await keep(env, moved)
104    return []
105  }
106}
107
108// bounded: a tool hook's answer, from work that decides it, within TOOL_ANSWER_MS on $.clock
109// (#558); past it, `late`. The work calls claim() just before it changes anything, and changes
110// nothing when it returns false: the bound has passed, so a call answered late changed nothing. A
111// claimed call still unanswered at the bound (a write that hangs) answers `unsure`.
112export function bounded($: EngineInterface, work: (claim: Claim) => Promise<OpAnswer>, late: OpAnswer, unsure: OpAnswer = late): Promise<OpAnswer> {
113  let at: 'open' | 'claimed' | 'late' = 'open'
114  const claim = () => {
115    if (at === 'open') at = 'claimed'
116    return at === 'claimed'
117  }
118  return new Promise<OpAnswer>((resolve, reject) => {
119    const t = $.clock.after(TOOL_ANSWER_MS, () => {
120      if (at === 'open') at = 'late'
121      resolve(at === 'late' ? late : unsure)
122    })
123    work(claim).then(
124      r => {
125        t.cancel()
126        resolve(r)
127      },
128      err => {
129        t.cancel()
130        reject(err)
131      },
132    )
133  })
134}
135
136// actsNow: the loop may start something (a reminder): act mode, no kill switch, and no restart
137// asked for without a wind-down request (with one the loop keeps acting in wind-down).
138export async function actsNow($: EngineInterface, rt: Runtime): Promise<boolean> {
139  return rt.mode === 'act' && (S.restartAsked === null || S.restartRequestAt !== null) && !(await killed($))
140}
141
142// turn.start: a wake's own turn takes its turn id.
143export async function turnStarted($: EngineInterface, said: string, turnId: string) {
144  if (!/^(JUDGE|TASK|TELL) /m.test(said)) return
145  const rt = await ledgerFor($)
146  if (rt === null) return
147  const now = await $.clock.now()
148  if (!(await wakeStarted(hookEnv($, rt, now), said, turnId))) return
149  // when each wake's turn first started, for its trace row (#552)
150  for (const e of live.ledger) if (e.turnId === turnId && !delivered.has(attemptOf(e))) delivered.set(attemptOf(e), now)
151}
152
153export type TurnEnded = { turnId: string; answer: string; reason: 'answer' | 'aborted' | 'refusal' | 'error' }
154
155// turn.complete of the main loop: answers close their wakes, a tell's turn delivers it, and an
156// unanswered wake gets its one reminder (act.ts wakeEnded); then a ping.
157export async function mainTurnEnded($: EngineInterface, e: TurnEnded) {
158  const rt = await ledgerFor($)
159  if (rt === null) return
160  const env = hookEnv($, rt, await $.clock.now())
161  const out = await wakeEnded(env, e)
162  // never awaited here: a submitted prompt resolves once its turn starts, after this one ends
163  if (out.prompts.length > 0 && (await actsNow($, rt))) {
164    for (const p of out.prompts) void env.io.submit(p).catch(err => appendLine($, rt, { turn: e.turnId, problems: [`reminder not sent: ${message(err)}`] }))
165  }
166  const problems = [...out.problems, ...env.problems]
167  if (problems.length > 0) await appendLine($, rt, { turn: e.turnId, problems })
168  if (out.moved) {
169    const ids = live.ledger.flatMap(x => (x.turnId === e.turnId && x.wakeId !== undefined ? [x.wakeId] : []))
170    ping(ids.length > 0 ? `wake ${ids.join(' ')}` : `turn ${e.turnId}`)
171  }
172}
173
174// turn.complete of an agent of the loop: its answer recorded (act-between.ts agentAnswered), then a ping.
175// An unreadable one first gets its one repair message, while the loop may start things (#548). The
176// decision log says which path each answer took (answerLine).
177export async function agentTurnEnded($: EngineInterface, e: TurnEnded & { agentId: string }) {
178  // a dry-run stamp's reader (driver-stamp.ts) is no ledger entry: its notice goes out in any mode
179  if (await stampEnded($, e)) return
180  const rt = await ledgerFor($)
181  if (rt === null) return
182  const now = await $.clock.now()
183  const env = hookEnv($, rt, now)
184  // an intake reader of rule I1 (v2/act-intake.ts) is a ledger entry of its own kind: its answer is the stamp
185  const intake = await intakeAnswered(env, S.lastState ?? bareState(rt, now), { agentId: e.agentId, answer: e.answer, reason: e.reason })
186  if (intake !== null) {
187    const done = live.ledger.find(x => x.key === intake.key)
188    const line = intake.result === 'applied' ? { key: intake.key, intake: done?.status, summary: done?.summary } : { agent: e.agentId, intake: 'dropped', why: intake.why }
189    await appendLine($, rt, { ...line, problems: env.problems.length > 0 ? env.problems : undefined })
190    if (intake.result === 'applied') ping(`agent ${e.agentId}`)
191    return
192  }
193  const repair: Repair = (await actsNow($, rt)) ? (id, text, type) => repairTo($, id, text, type) : async () => 'the loop starts nothing until its restart'
194  const r = await agentAnswered(env, S.lastState ?? bareState(rt, now), { agentId: e.agentId, answer: e.answer, reason: e.reason }, between, repair)
195  const why = r.why === undefined || r.result === 'repair' ? [] : [r.result === 'dropped' ? `${r.why}: dropped` : r.why]
196  const problems = [...why, ...env.problems]
197  const path = answerLine(r)
198  if (path !== null || problems.length > 0) await appendLine($, rt, { agent: e.agentId, ...path, problems: problems.length > 0 ? problems : undefined })
199  if (r.result === 'applied') ping(`agent ${e.agentId}`)
200}
201
202// answerLine: the path an agent's answer at its turn's end took, for its decision-log line: read
203// from the file it recorded with the answer script ('script', #561), with how its entry ended, or
204// asked again ('repair', with why), or held for its stop gate line ('held'); afterRepair marks an answer that came after the repair
205// message, and repairRefused is why one was not delivered, whole (#559).
206export function answerLine(r: Answered): Record<string, unknown> | null {
207  if (r.key === undefined) return null
208  if (r.result === 'repair') return { key: r.key, answer: 'repair', why: r.why }
209  if (r.result === 'held') return { key: r.key, answer: 'held', why: 'its stop gate line is not in the companion log yet' }
210  if (r.result !== 'applied') return null
211  const e = live.ledger.find(x => x.key === r.key)
212  return {
213    key: r.key,
214    answer: 'script',
215    status: e?.status,
216    summary: e?.summary,
217    afterRepair: r.repaired === true ? true : undefined,
218    repairRefused: r.undelivered,
219  }
220}
221
222// repairTo: the one repair message to an agent of the loop, which resumes it with its transcript
223// once its turn has ended (#548); null once queued, else why not. The engine resumes an agent only
224// as a type it offers the model, and the loop hides its own (agent.offer below), so the agent's
225// type is offered while the message is on its way: hidden, the engine refused every repair of
226// testbed run 3 ("is not offered in this session", #559).
227export async function repairTo($: EngineInterface, agentId: string, text: string, type: `${string}:${string}`): Promise<string | null> {
228  const subagent = type
229  resuming.set(subagent, (resuming.get(subagent) ?? 0) + 1)
230  try {
231    const r = await within($, REPAIR_TIMEOUT_MS, $.session.send({ to: { agentId }, text }), 'repair message')
232    return r.isDelivered ? null : r.reason
233  } catch (err) {
234    return message(err)
235  } finally {
236    const left = (resuming.get(subagent) ?? 1) - 1
237    if (left > 0) resuming.set(subagent, left)
238    else resuming.delete(subagent)
239  }
240}
241
242// lateDrop: a wake prompt the engine dropped after it was taken as queued started no turn: it is
243// lost with its attempt given back, as a drop within the grace uses none (wake.ts), so plan asks
244// again; its loop event says so, since its start was logged. A wake whose turn already started is
245// left alone (a reminder's drop changes nothing).
246export async function lateDrop($: EngineInterface, prompt: string, why: string) {
247  const id = /\bid=(\S+)/.exec(prompt.split('\n', 1)[0] ?? '')?.[1]
248  if (id === undefined) return
249  await hook(async () => {
250    const rt = await ledgerFor($)
251    if (rt === null) return
252    const now = await $.clock.now()
253    if (SESSION_STOPPED.test(why)) markHeld(now, `${id}: ${why}`)
254    const moved = transition(live, l => {
255      const e = l.find(x => x.wakeId === id && x.status === 'running' && x.turnId === undefined)
256      if (e === undefined) return l
257      const given = { ...e, status: 'lost' as const, attempts: Math.max(0, e.attempts - 1), endedAt: now, summary: `submit ${why}`.slice(0, 200) }
258      return l.map(x => (x.key === e.key ? given : x))
259    })
260    if (moved.length === 0) return
261    await persist($, rt)
262    await logLoop(hookEnv($, rt, now), moved)
263  })
264}
265
266// releaseLock: at session.end this session's lease expires, so the next session acts at once.
267export async function releaseLock($: EngineInterface, sessionId: string) {
268  if (!S.heldLock || S.lastRt === null) return
269  const loopDir = S.lastRt.loopDir
270  await lockOp(async () => releaseActLock(lockIo($), actLockPath(loopDir), sessionId, await $.clock.now()))
271  S.heldLock = false
272}
273
274export type OpAnswer = { ok: boolean; text: string }
275
hooks/driver-controls.ts 157 lines
1// The owner's controls (v2 SPEC 13.4.3, D-38): /factory, the control tool and the answer tool, and
2// ensure, which starts the driver once per module load.
3import type { EngineInterface } from 'claude-code'
4
5import { commandOf } from './act'
6import type { ActEnv } from './act'
7import { retried, wakeAnswered } from './act-between'
8import type { Claim } from './act-between'
9import { DEFAULT_CONFIG } from './config'
10import { viewOf } from './config-view'
11import { CONTROL_TOOL, FACTORY_COMMAND, controlTool, issuesOf, retryText, runOp } from './control'
12import type { FileIo } from './control'
13import { armSummary } from './pass-summary'
14import { logOwnerOp } from './v2/act-events'
15import { opLanded, parkedOf } from './v2/ops'
16import { noteWritten, notingIo } from './v2/store'
17import { restartCheck } from './update-check'
18import { ANSWER_TOOL } from './wake'
19import { actIo, acting, configDir, fileIo, killed, runtime, v2StoreIo } from './driver-io'
20import { hookEnv, noteConfigOp, persist } from './driver-store'
21import { rearm, request } from './driver-pass'
22import { startStamp, stampJob } from './driver-stamp'
23import { afterwards, bounded, held, hook, kept, later, lateDrop } from './driver-between'
24import type { OpAnswer } from './driver-between'
25import { FIRST_PASS_AFTER_MS, S, live, liveV2 } from './driver-state'
26
27// the last pass's summary (types/index.d.ts): the engine's validator reads a state reference only
28// when it is a literal const of the file that uses it, so driver-pass.ts spells the same one
29const lastPassRef = { plugin: 'factory-loop', key: 'lastPass' } as const
30
31export const OP_LATE: OpAnswer = { ok: false, text: 'factory-loop: the op could not run in time; nothing was changed.' }
32
33export const OP_UNSURE: OpAnswer = { ok: false, text: 'factory-loop: the op was still being written when it had to answer; /factory status shows whether it took.' }
34
35// ownerOp: /factory <op> and the control tool, one at a time (control.json is read, changed and
36// written whole), answered within TOOL_ANSWER_MS (bounded, #558): the queue holds file reads and
37// writes alone, and an op answered late writes nothing. A change pings the loop and gets its own
38// decision-log line once it has its answer; retry clears the issue's exhausted entries in the
39// live ledger at once. An op that landed with the loop acting before or after it is an intervention of the
40// op's origin, person or judge (act-events.ts), and its writes the loop's (7.2).
41export function ownerOp($: EngineInterface, input: string | Record<string, unknown>, agentId: string | undefined, by: 'person' | 'judge'): Promise<OpAnswer> {
42  const work = (claim: Claim) => {
43    const run = S.ops.then(async (): Promise<OpAnswer> => {
44      const rt = S.lastRt ?? (await runtime($))
45      const paths = { loopDir: rt.loopDir, configDir: await configDir($) }
46      const now = await $.clock.now()
47      const last = (await $.state.get(lastPassRef)).value ?? null
48      const parked = parkedOf(S.lastState?.v2?.records)
49      const view = viewOf(rt, S.lastState?.v2?.interventions.gates)
50      const check = () => restartCheck((argv, opts) => $.process.run(argv, opts))
51      const from = agentId === undefined ? { last, parked, view, restartCheck: check } : { last, agentId, parked, view, restartCheck: check }
52      const fio = notingIo(claimedIo(fileIo($), claim), noteWritten(liveV2, v2StoreIo($), rt))
53      const reply = typeof input === 'string' ? await runOp(fio, paths, input, now, from) : await controlTool(fio, paths, input, now, from)
54      let said = reply.text
55      if (reply.retryIssue !== null) said = await retry($, reply.retryIssue, claim)
56      // a dry-run stamp answers at once and runs in the background (driver-stamp.ts); a late answer starts nothing
57      if (reply.ok && reply.op?.op === 'stamp') said = claim() ? startStamp(rt, reply.op.issue, now) : OP_LATE.text
58      // a setting a config op changed: the next pass's settings diff says who changed it (rule N1)
59      if (reply.logged !== null && reply.op?.op === 'config' && reply.op.change !== undefined && claim()) await noteConfigOp($, rt.repo, reply.op.change.key, by, now)
60      const landed = reply.op === null ? null : opLanded({ mode: rt.mode }, reply.op, reply.logged, issuesOf(reply.op), now, by)
61      const logOp = landed === null ? undefined : (env: ActEnv) => logOwnerOp(env, landed)
62      const line = (problems: string[]) => ({ control: reply.logged, by, text: said, problems: problems.length > 0 ? problems : undefined })
63      if (reply.ping && claim()) later($, { rt, run: logOp, line, ping: `${by === 'judge' ? 'judge' : 'owner'} ${reply.logged ?? ''}` })
64      // a refused update: a decision-log line and, in act mode, an intervention; no ping
65      if (reply.noted != null && claim()) {
66        const refusal = opLanded({ mode: rt.mode }, { op: 'update', reason: null }, reply.noted, [], now, by)
67        later($, { rt, run: refusal === null ? undefined : (env: ActEnv) => logOwnerOp(env, refusal), line: problems => ({ control: reply.noted, by, text: said, problems: problems.length > 0 ? problems : undefined }) })
68      }
69      return { ok: reply.ok, text: said }
70    })
71    S.ops = run.catch(() => undefined)
72    return run
73  }
74  return bounded($, work, OP_LATE, OP_UNSURE)
75}
76
77// claimedIo: file writes that go ahead only once the op claims its change (bounded), so an op
78// answered late writes nothing.
79export function claimedIo(io: FileIo, claim: Claim): FileIo {
80  return { readFile: io.readFile, writeFile: (path, body) => (claim() ? io.writeFile(path, body) : Promise.reject(new Error('the op ran out of time'))) }
81}
82
83// retry: `/factory retry <N>` in the live ledger (act.ts retried): cleared at once, saved and
84// logged once the op has its answer (#558).
85export async function retry($: EngineInterface, issue: number, claim: Claim): Promise<string> {
86  const rt = await held($)
87  if (rt === 'none') return `Retry #${issue}: this session holds no ledger (act mode keeps one), so nothing was cleared.`
88  if (rt === 'loading') return `Retry #${issue}: the ledger is not loaded yet (the next pass loads it), so nothing was cleared.`
89  if (!claim()) return OP_LATE.text
90  const r = retried({ live, rt }, issue)
91  later($, { rt, run: kept(r.moved) })
92  return retryText(issue, r.cleared)
93}
94
95export const NO_WAKE: OpAnswer = { ok: false, text: 'Not recorded: no wake of the factory loop is open in this session.' }
96
97export const WAKE_LOADING: OpAnswer = { ok: false, text: 'Not recorded: the factory loop has not loaded its ledger yet; give the ANSWER block in your reply instead.' }
98
99export const WAKE_LATE: OpAnswer = { ok: false, text: 'Not recorded: the factory loop could not check this answer in time; give the ANSWER block in your reply instead.' }
100
101// answer: mcp__factory-loop__answer (act.ts wakeAnswered), answered at once from the ledger in
102// memory (#558); the ledger saved, the wake's loop event and the ping follow once it has its
103// answer.
104export function answer($: EngineInterface, input: Record<string, unknown>, agentId: string | undefined): Promise<OpAnswer> {
105  const work = async (claim: Claim): Promise<OpAnswer> => {
106    const rt = await held($)
107    if (rt === 'none') return NO_WAKE
108    if (rt === 'loading') return WAKE_LOADING
109    const r = await wakeAnswered(hookEnv($, rt, await $.clock.now()), input, agentId, claim)
110    if (r.moved.length > 0) later($, { rt, run: kept(r.moved), ping: `wake ${typeof input.id === 'string' ? input.id : '?'}` })
111    return { ok: r.ok, text: r.text }
112  }
113  return bounded($, work, WAKE_LATE)
114}
115
116// toolInput: a tool call's own arguments, without the envelope the engine adds.
117export function toolInput(e: Record<string, unknown>): Record<string, unknown> {
118  const { tool: _tool, tool_use_id: _id, agentId: _agent, requestMeta: _meta, ...input } = e
119  return input
120}
121
122export async function registerControls($: EngineInterface) {
123  // the command's name is written out, so the validator reads its hook as one that answers its
124  // own command
125  const command = () =>
126    $.command.register({ name: 'factory', description: FACTORY_COMMAND.description, argumentHint: FACTORY_COMMAND.argumentHint, immediate: FACTORY_COMMAND.immediate })
127  for (const register of [command, () => $.tool.register(CONTROL_TOOL), () => $.tool.register(ANSWER_TOOL)]) {
128    try {
129      await register()
130    } catch {
131      // a host without the noun: the loop runs, the owner uses control.json
132    }
133  }
134}
135
136// ensure: start once per module load, from whichever hook fires first. session.start does not
137// fire for a plugin a /reload-plugins adds to a running session (the wake probe saw it).
138export function ensure($: EngineInterface) {
139  S.started ??= (async () => {
140    S.loadedAt = await $.clock.now()
141    S.lateDrop = (prompt, why) => void lateDrop($, prompt, why)
142    S.ask = (source, why) => void request($, source, why).catch(() => undefined)
143    S.background = after => void hook(() => afterwards($, after))
144    S.saveNow = rt => void persist($, rt)
145    // not in the hook queue: a spawn that hangs (up to SPAWN_TIMEOUT_MS) must not hold the turn ends behind it
146    S.stampJob = (rt, run) => void stampJob($, rt, run)
147    await registerControls($)
148    // the first pass after a load: a session start or a reload
149    $.clock.after(FIRST_PASS_AFTER_MS, () => void request($, 'timer', 'first').catch(() => undefined))
150    rearm($, DEFAULT_CONFIG.passEveryMs)
151    armSummary($, { rt: () => S.lastRt, killed: () => killed($), send: (rt, argv) => commandOf(actIo($), acting(rt), [])(argv, { timeoutMs: 60_000 }), run: (rt, argv, init) => commandOf(actIo($), acting(rt), [])(argv, init) })
152  })().catch(() => {
153    S.started = undefined
154  })
155  return S.started
156}
157
hooks/driver-state.ts 182 lines
1// The factory loop driver's state (register.ts and the driver-*.ts modules it wires): the constants
2// the driver runs by, and everything that lives for the module's life. A binding another module
3// reassigns cannot be imported by name, so every reassigned value is a field of the one holder,
4// `S`; the collections that are only mutated stay exported under their own names. Nothing here
5// imports another driver module, and `ping` reads only `S.ask`, so every driver module can use it.
6import type { EngineInterface } from 'claude-code'
7
8import type { ActEnv, Between, Live } from './act'
9import type { ViewInputs } from './config-view'
10import { emptyCache } from './observe'
11import type { ObserveSplit } from './observe-clock'
12import type { OffPassRow } from './trace'
13import type { TitleFlight } from './title-flight'
14import type { Runtime } from './observe'
15import { newScheduler } from './rails'
16import type { PassSource } from './rails'
17import type { AgentStatus, Ms, State } from './types'
18import type { StampRun } from './v2/intake'
19import { newV2Live } from './v2/store'
20import { newSettingsCache } from './v2/settings'
21
22export const HOUR = 3_600_000
23export const FIRST_PASS_AFTER_MS = 5_000
24export const STATE_KEEP_BYTES = 3_500_000
25// recorded states per day at most (observe mode writes one per changed digest): one every five
26// minutes on average, which the replay needs, while a churning digest cannot fill the disk
27export const STATES_PER_DAY = 288
28// v2 SPEC 13.6.1: stop-agent 30 s, title 10 s; the strict lib has no setTimeout, so $.clock times them
29export const STOP_TIMEOUT_MS = 30_000
30export const RENAME_TIMEOUT_MS = 10_000
31// $.agent.spawn resolves once the agent started; one that never does must not hold the pass
32export const SPAWN_TIMEOUT_MS = 60_000
33// $.session.send resolves once the repair message is queued (#548); one that hangs is undelivered
34export const REPAIR_TIMEOUT_MS = 10_000
35// $.prompt.submit resolves once its turn starts, which waits for the session to be idle: a wake
36// is taken as queued after this, so a busy session never holds a pass (a late drop still counts)
37export const SUBMIT_GRACE_MS = 5_000
38// three passes in a row that throw tell the owner (v2 SPEC 13.10 item 9)
39export const ERROR_PASSES = 3
40// The engine gives each hook a budget of its own time per dispatch (HookBudget, 10 s: awaiting
41// the hook queue counts, a $ call does not), and a tool call whose hook outruns it is left with
42// "no tool.call hook answered this call" (stage D run 3, #558). The loop's tool hooks decide
43// against what is in memory and answer at once; one whose own work is not done within this
44// bound refuses, asking for text.
45export const TOOL_ANSWER_MS = 2_000
46export const DEFAULT_TOOLS_DIR = '/usr/local/share/callum-tools'
47
48export const ASKED_MAX = 20
49
50// One row of $.agent.list(), as observe and the reconciling read it.
51export type AgentRow = { id: string; type: string; status: AgentStatus }
52
53// Options as the manifest's userConfig gives them; the workspace config file overrides them.
54export type Options = { mode?: unknown; repo?: unknown; shadowDevice?: unknown; runSource?: unknown }
55
56// What a tool call leaves for once it has answered (#558): its ledger work (act.ts keep, or an
57// answer's follow-up, with notes on what failed), then its decision-log line, given the problems
58// met, and its ping.
59// One stamp in progress, with the runtime it started under and the cancel of its 10-minute timer.
60export type Stamp = StampRun & { rt: Runtime; cancel: () => void }
61
62export type After = { rt: Runtime; run?: (env: ActEnv) => Promise<string[]>; line?: (problems: string[]) => Record<string, unknown>; ping?: string }
63
64// The values the modules reassign. Each is read and written as S.<name>.
65export const S = {
66  started: undefined as Promise<void> | undefined,
67  // a session no person reaches (a `-p` run, the SDK) never runs the loop: every Claude process in
68  // the workspace loads the plugin, the pipeline's own review runs included, and only the
69  // interactive session may observe or act (D-61)
70  headless: false,
71  // the current pass's observe split: cleared when a pass starts, set once its observe ends
72  passObserve: null as ObserveSplit | null,
73  // the off-pass commands (act-off.ts) that finished since the last trace record, and whether one met
74  // a GitHub rate limit since the last pass (the next acting pass sets the backoff)
75  offFinished: [] as OffPassRow[],
76  offRateLimited: false,
77  // the one title flight (title-flight.ts), built on the first rename, and the engine calls it renames and
78  // reads the clock with: refreshed by every call, so the flight never holds a stale engine
79  titleFlight: null as TitleFlight | null,
80  renamer: undefined as ((title: string) => Promise<void>) | undefined,
81  clockNow: undefined as (() => Promise<Ms>) | undefined,
82  loadedAt: 0,
83  cwd: '.',
84  passNo: 0,
85  lastTitle: null as string | null,
86  lastTitleAt: null as Ms | null,
87  lastDigest: null as string | null,
88  // states written today, and the day the loop dir was last pruned (YYYY-MM-DD)
89  statesToday: { day: '', count: 0 },
90  prunedDay: '',
91
92  // The pass scheduler (v2 SPEC 13.2): one pass at a time, 5 s apart, pings first, with the ping-storm
93  // breaker (D-39); the timer re-armed when config.passEveryMs changes.
94  sched: newScheduler(),
95  timer: null as { ms: Ms; cancel: () => void } | null,
96  // passes in a row that threw, since when, and whether the owner was told (v2 SPEC 13.10 item 9)
97  failures: 0,
98  failingSince: null as Ms | null,
99  errorTold: false,
100
101  // the last pass's runtime and state, for the hooks between passes
102  lastRt: null as (Runtime & ViewInputs) | null,
103  lastState: null as State | null,
104  // the main checkout the last pass read (any mode; null before the first)
105  checkout: null as State['checkout'],
106  // this session held the act lock at some pass, so session.end releases it
107  heldLock: false,
108  // what asked for the next pass, in the order it came: the decision log's trigger (#552)
109  asked: [] as string[],
110  // for the trace (#552): when each skip was first seen in a run of passes (trace.ts waitSince),
111  // the last pass's start, and the day and cap a trace file was cut short at
112  waits: new Map<string, Ms>(),
113  prevPassAt: 0 as Ms,
114  traceCut: null as string | null,
115  // the day and cap whose trace file this load has read for an earlier load's cut (writeTrace)
116  traceChecked: null as string | null,
117  lastWakeAt: 0,
118  // dev-restart-self returned (rule H4): the workspace is about to be replaced, so nothing more is
119  // started in this module's life, and the next load finds the update done (act.ts updateDone)
120  restartAsked: null as Ms | null,
121  // the request R2 wrote for that restart (a wind-down, v2 SPEC 10.11): the loop keeps acting in
122  // wind-down meanwhile and starts nothing; null once it is stale or when no request was written
123  restartRequestAt: null as Ms | null,
124  // the store refused the last ledger write (persist); null once one succeeds
125  saveProblem: null as string | null,
126  // serialized work: ledger saves, the act lock's writes, the hooks that change the ledger, and the
127  // owner's ops
128  saving: Promise.resolve() as Promise<void>,
129  locking: Promise.resolve() as Promise<unknown>,
130  loading: null as Promise<boolean> | null,
131  hooking: Promise.resolve() as Promise<void>,
132  ops: Promise.resolve() as Promise<unknown>,
133  options: {} as Options,
134
135  // Late-bound calls: each is set once per load by ensure (driver-controls.ts) with the $ the
136  // loop's timers run with, so a module lower in the import graph can reach what is built above it
137  // and a hook never runs a pass or its follow-up work on its own dispatch.
138  // ask: request a pass.
139  ask: null as ((source: PassSource, why: string) => void) | null,
140  // background: queue what a tool call leaves for later; saveNow saves the ledger at once.
141  background: null as ((after: After) => void) | null,
142  saveNow: null as ((rt: Runtime) => void) | null,
143  // lateDrop: a wake prompt the engine dropped after it was taken as queued (driver-between.ts)
144  lateDrop: null as ((prompt: string, why: string) => void) | null,
145  // a stopped main session holds agent starts and wakes (session-hold.ts): the hold in force, and
146  // one that ended and awaits its event in the next pass
147  held: null as import('./session-hold').Hold | null,
148  resumed: null as import('./session-hold').Resumed | null,
149  // stampJob: start a dry-run stamp's background job (driver-stamp.ts)
150  stampJob: null as ((rt: Runtime, run: Stamp) => void) | null,
151  // the dry-run stamps in progress, by issue (v2/intake.ts; `/factory stamp <N>`): in memory only
152  stamping: new Map<number, Stamp>(),
153}
154
155export const cache = emptyCache()
156
157// The ledger (v2 SPEC 13.7), loaded from $.store by the first act-mode pass or hook that needs it.
158// Every transition replaces live.ledger whole, synchronously (act.ts Live).
159// basis: the act lock as it stood when the store was loaded; a write goes back to the store only
160// while the lock names this session or still stands so (mayWrite)
161export const live: Live & { loaded: boolean; repo: string; basis: string | null } = { ledger: [], loaded: false, repo: '', basis: null }
162// v2's records and the heads it has seen, kept as the ledger is (v2/store.ts), and the repo-local
163// settings as origin's default branch holds them (v2/settings.ts)
164export const liveV2 = newV2Live()
165export const settingsCache = newSettingsCache()
166// when each wake attempt's turn started, and the ended wakes already reported (trace.ts)
167export const delivered = new Map<string, Ms>()
168export const reportedWakes = new Set<string>()
169// agents whose answer is being handled, when each was first listed with its turn ended (idle or
170// completed), and when each was sent its repair message (act.ts)
171export const between: Between = { answering: new Set(), completedSeen: new Map(), repairing: new Map(), gateHeld: new Map() }
172// the loop's own agent types with a repair message of the loop's on its way, and how many: the
173// engine resumes an agent only as a type it offers the model, so the loop offers its hidden types
174// for just that long (repairTo, #559)
175export const resuming = new Map<string, number>()
176
177// ping: an agent of the loop finished (`agent <id>`), a wake was answered (`wake <id>`), an owner
178// control arrived (`owner <op>` for /factory, `judge <op>` for the control tool).
179export function ping(why: string) {
180  S.ask?.('ping', why)
181}
182
hooks/foundation.ts 510 lines
1// The foundation's generic plan code (docs/factory-loop/v2/SPEC.md 2.2): the usage tier (tierOf),
2// the class matrix, gate and want, the generic admission filters (control, tier, GitHub backoff,
3// the breakers, the rate caps), one wake and the title frame, and the helpers the rest of the loop
4// shares (the live stages, the issue of a branch, the agent list's reading, the release review).
5// The v2 planner (v2/plan.ts) composes its rules with them.
6//
7// One addition of v2's: the executor breaker gains a bucket for step unknowns across issues
8// (v2 SPEC 5.3), which holds every start, develop and drive action for 30 minutes.
9//
10// Pure: no clock (state.now), no I/O, and nothing imported but types and v2's vocabulary.
11import type { Action, ActionClass, ActionKind, AgentStatus, AgentType, AgentView, Config, LedgerEntry, Ms, Skip, State, Tier, Usage } from './types'
12import { AGENT_STEPS } from './v2/types'
13
14const MIN = 60_000
15export const HOUR = 60 * MIN
16
17// The classes each tier allows (v2 SPEC 13.5.2; rails.ts TIER_CLASSES is the act step's copy).
18export const ALLOWED: Readonly<Record<Tier, readonly ActionClass[]>> = {
19  normal: ['free', 'owner', 'drive', 'develop', 'start'],
20  slow: ['free', 'owner', 'drive', 'develop', 'start'],
21  'stop-new': ['free', 'owner', 'drive'],
22  'stop-all': ['free', 'owner'],
23}
24
25export const WAKES: readonly ActionKind[] = ['judge', 'task', 'tell']
26
27// The kinds that write to GitHub (or read it heavily): held while GitHub rate-limits us (v2 SPEC
28// 13.10 item 2), by plan and, for the rest of a pass that met a limit, by the act step (act.ts runActions).
29export const GITHUB_V2: readonly ActionKind[] = [
30  'claim',
31  'heartbeat',
32  'sweep',
33  'rollout',
34  'close-issue',
35  'delete-branch',
36  'release-parent',
37  'milestone-later',
38  'label',
39  'comment',
40  'pr',
41  'split',
42  'upstream',
43  'link',
44  'close-tracker',
45  'ci-rerun',
46  'queue-update',
47  'queue-merge',
48  'queue-train',
49  'released',
50]
51
52// The executor breaker (v2 SPEC 13.11.4): three failures in a row of one kind hold that kind this long.
53export const BREAKER_MS = 30 * MIN
54
55// The step-unknown breaker (v2 SPEC 5.3): `trips` unexplained unknowns of agent steps, on at least
56// `records` issues, within `windowMs`, close the `classes` for `holdMs` from the newest of them.
57// Unexplained: not caused by a load, a usage limit or a lost slot (5.1).
58export const STEP_BREAKER = {
59  trips: 3,
60  records: 2,
61  windowMs: 15 * MIN,
62  holdMs: 30 * MIN,
63  classes: ['start', 'develop', 'drive'] as readonly ActionClass[],
64  explained: ['load', 'usage', 'slot'] as readonly string[],
65} as const
66
67export type Gate = 'go' | 'running' | 'done' | 'wait' | 'exhausted'
68
69// What a plan builds as its rules run, and what the admission filters read.
70// ownerTells: the notice kinds that are owner items (they count in the title and go
71// out first); github: the kinds held during a GitHub backoff.
72export type PlanCtx = {
73  state: State
74  config: Config
75  tier: Tier
76  overridden: boolean
77  out: Action[]
78  skipped: Skip[]
79  owner: Set<string>
80  exhausted: string[]
81  byKey: Map<string, LedgerEntry>
82  capped: string[]
83  atCap: boolean
84  ownerTells: readonly string[]
85  github: readonly ActionKind[]
86}
87
88// newCtx: an empty plan over this state, its tier read, the ledger by key (the latest start wins).
89export function newCtx(state: State, config: Config, tier: { tier: Tier; overridden: boolean }, ownerTells: readonly string[], github: readonly ActionKind[]): PlanCtx {
90  const byKey = new Map<string, LedgerEntry>()
91  for (const entry of [...state.ledger].sort((a, b) => a.startedAt - b.startedAt)) byKey.set(entry.key, entry)
92  return {
93    state,
94    config,
95    tier: tier.tier,
96    overridden: tier.overridden,
97    out: [],
98    skipped: [],
99    owner: new Set(),
100    exhausted: [],
101    byKey,
102    capped: [],
103    atCap: false,
104    ownerTells,
105    github,
106  }
107}
108
109export function skip(ctx: PlanCtx, rule: string, issue: number | null, why: string): void {
110  ctx.skipped.push({ rule, issue, why })
111}
112
113// --- gate and want ------------------------------------------------------------
114
115// maxAttemptsOf: the key's own cap when its action or entry carries one, else the kind's setting,
116// else 3.
117export function maxAttemptsOf(config: Config, kind: ActionKind | AgentType, cap?: number): number {
118  return cap ?? config.maxAttempts[kind] ?? 3
119}
120
121// cadenceOf: the interval of a kind that runs on a cadence. Heartbeat and sweep retry at their
122// next due time, so they are never used up (v2 SPEC 13.6.1). null: any other kind.
123export function cadenceOf(config: Config, kind: ActionKind | AgentType): Ms | null {
124  if (kind === 'heartbeat') return config.heartbeatEveryMs
125  if (kind === 'sweep') return config.sweepEveryMs
126  return null
127}
128
129// gate: whether the action under this key may run now (v2 SPEC 13.5.1 "blocked"): new keys go; a
130// running or done key is not planned again; a failed, timed-out or lost one runs again after its
131// backoff until its attempts are used up, and an agent's only once the agent list shows it ended.
132export function gate(ctx: PlanCtx, key: string, kind: ActionKind | AgentType, cap?: number): Gate {
133  const entry = ctx.byKey.get(key)
134  if (entry === undefined) return 'go'
135  if (entry.status === 'running') return 'running'
136  if (entry.status === 'done') return 'done'
137  if (entry.agentId !== undefined && listedLive(ctx.state.agents, entry.agentId)) return 'running'
138  const cadence = cadenceOf(ctx.config, kind)
139  if (cadence === null && entry.attempts >= maxAttemptsOf(ctx.config, kind, cap ?? entry.maxAttempts)) return 'exhausted'
140  if (entry.status === 'lost') return 'go'
141  const doubled = ctx.config.retryBackoffMs * 2 ** Math.max(0, entry.attempts - 1)
142  const backoff = cadence === null ? doubled : Math.min(doubled, cadence)
143  if (entry.endedAt !== null && ctx.state.now - entry.endedAt < backoff) return 'wait'
144  return 'go'
145}
146
147// want: plan the action unless its key is blocked, and say what blocked it. An owner notice counts
148// toward the title's owner items whether or not it goes out this pass. An exhausted key is named
149// in the decision log and kept in ctx.exhausted for its rule to tell; a cadenced kind that failed
150// its attempts in a row is kept there too, and keeps trying: a running retry counts, since the
151// ledger counts its attempt (attempts - 1 earlier ones), so the tell stays while the retry runs.
152export function want(ctx: PlanCtx, action: Action): Gate {
153  if (action.kind === 'tell' && ctx.ownerTells.includes(action.wake)) ctx.owner.add(action.key)
154  const kind = action.kind
155  const g = gate(ctx, action.key, kind, action.maxAttempts)
156  if (g === 'go') ctx.out.push(action)
157  const entry = ctx.byKey.get(action.key)
158  if (g === 'running' && entry !== undefined && entry.status !== 'running') {
159    skip(ctx, action.rule, action.issue, `${action.key}: its agent ${entry.agentId} still runs`)
160  }
161  if (g === 'exhausted') {
162    skip(ctx, action.rule, action.issue, `exhausted: ${action.key}`)
163    if (WAKES.includes(action.kind) && action.kind !== 'task') ctx.owner.add(action.key)
164    else ctx.exhausted.push(action.key)
165  } else if (cadenceOf(ctx.config, kind) !== null) {
166    if (entry !== undefined && entry.status !== 'done') {
167      const earlier = entry.status === 'running' ? entry.attempts - 1 : entry.attempts
168      if (earlier >= maxAttemptsOf(ctx.config, kind, entry.maxAttempts)) ctx.exhausted.push(action.key)
169    }
170  }
171  return g
172}
173
174// wake: a judge, task or tell action, its fields as text (an empty one dropped).
175export function wake(
176  kind: 'judge' | 'task' | 'tell',
177  name: string,
178  key: string,
179  rule: string,
180  issue: number | null,
181  fields: Record<string, string | number | null>,
182  context: string[] = [],
183  klass: ActionClass = kind === 'tell' ? 'owner' : 'drive',
184): Action {
185  const clean: Record<string, string> = {}
186  for (const [k, v] of Object.entries(fields)) if (v !== null) clean[k] = String(v)
187  return { kind, wake: name, key, class: klass, rule, reason: `${kind} ${name}`, issue, fields: clean, context }
188}
189
190// blindPass (G2): the factory source failed, so the pass plans nothing but the owner's notice
191// once it has failed for blindNoticeAfterMs.
192export function blindPass(ctx: PlanCtx): void {
193  const { state, config } = ctx
194  const since = state.sources.factory.at
195  skip(ctx, 'G2', null, `factory source unavailable${state.sources.factory.error ? `: ${state.sources.factory.error}` : ''}`)
196  if (since === null || state.now - since >= config.blindNoticeAfterMs) {
197    want(ctx, wake('tell', 'blind', `tell:blind:${since ?? 0}`, 'G2', null, { since: since ?? 'never', error: state.sources.factory.error?.slice(0, 300) ?? null }))
198  }
199}
200
201// --- the breakers (v2 SPEC 13.11.4, 5.3) -------------------------------------------------------
202
203// executorBreaker: the time the newest of this kind's last three ended entries ended, when all
204// three failed within BREAKER_MS of now; else null.
205export function executorBreaker(state: State, kind: ActionKind): Ms | null {
206  const ended = state.ledger
207    .filter(e => e.kind === kind && e.endedAt !== null && e.status !== 'running')
208    .sort((a, b) => (a.endedAt ?? 0) - (b.endedAt ?? 0))
209  const last3 = ended.slice(-3)
210  const newest = last3[last3.length - 1]
211  if (last3.length < 3 || newest === undefined || !last3.every(e => e.status === 'failed')) return null
212  const at = newest.endedAt ?? 0
213  return state.now - at < BREAKER_MS ? at : null
214}
215
216// An unexplained unknown of an agent step, as the transition that handled it recorded it: its
217// event is unknown or a running step's timeout, its step an agent's, its cause none of a load, a
218// usage limit or a lost slot. A transition lost to a reload counts by the facts it carries from
219// its start (ledger.ts start): either the store took it, or the record's next transition reuses
220// its key and replaces it, so nothing counts twice.
221function unexplained(e: LedgerEntry): boolean {
222  const o = e.outcome
223  if (e.kind !== 'transition' || (e.status !== 'done' && e.status !== 'lost') || o?.kind !== 'transition') return false
224  if (o.event !== 'unknown' && o.event !== 'timeout') return false
225  if (o.step === null || !(AGENT_STEPS as readonly string[]).includes(o.step)) return false
226  return o.cause === null || !STEP_BREAKER.explained.includes(o.cause)
227}
228
229// stepBreaker: when the step-unknown breaker is open (v2 SPEC 5.3): `since` is the newest of the
230// unknowns that tripped it, `until` when it closes. A trip is any `trips` unexplained unknowns, on
231// at least `records` issues, within `windowMs` of each other; it holds `holdMs` from the newest.
232// An unknown that ended while a trip held is the breaker's own (its cause is `breaker`, 5.1) and
233// counts toward no trip, so a trip neither extends itself nor moves its `since`, and is told once.
234// null when it is closed now.
235export function stepBreaker(ledger: readonly LedgerEntry[], now: Ms): { since: Ms; until: Ms } | null {
236  const seen = ledger.filter(unexplained).sort((a, b) => (a.endedAt ?? 0) - (b.endedAt ?? 0))
237  const counted: LedgerEntry[] = []
238  let open: { since: Ms; until: Ms } | null = null
239  for (const e of seen) {
240    const at = e.endedAt ?? 0
241    if (open !== null && at < open.until) continue
242    counted.push(e)
243    const window = counted.filter(x => at - (x.endedAt ?? 0) <= STEP_BREAKER.windowMs)
244    const issues = new Set(window.map(x => x.issue))
245    if (window.length >= STEP_BREAKER.trips && issues.size >= STEP_BREAKER.records) open = { since: at, until: at + STEP_BREAKER.holdMs }
246  }
247  return open !== null && now < open.until ? open : null
248}
249
250// --- admitting actions (the generic filters) ------------------------------------------
251
252// Rate-cap buckets per rolling hour (D-24). A v2 agent step spawns an agent.
253export type Bucket = 'start' | 'spawn' | 'wake'
254
255export function bucketOf(kind: ActionKind, klass: ActionClass): Bucket | null {
256  if (klass === 'start') return 'start'
257  if (kind === 'agent-step') return 'spawn'
258  if (WAKES.includes(kind)) return 'wake'
259  return null
260}
261
262// perIssueKind: what the per-issue rate cap counts an action or entry under: its kind, and a v2
263// agent step by its step kind (D-24, v2 appendix B).
264function perIssueKind(kind: ActionKind, step: string | undefined): string {
265  return kind === 'agent-step' && step !== undefined ? step : kind
266}
267
268// admit (G4): the planned actions, in order, through the generic filters: a paused issue (all but
269// its heartbeat), no new work (start and develop), the usage tier, the GitHub backoff, the
270// breakers, and the rate caps per bucket and per kind on one issue. Each held action has a skip
271// line naming the filter. A tripped cap or breaker tells the owner once (runaway, breaker); then
272// one wake at most (oneWake).
273export function admit(ctx: PlanCtx): Action[] {
274  const { state, config, tier } = ctx
275  const control = state.control
276  const recent = state.ledger.filter(e => e.startedAt > state.now - HOUR)
277  const counts: Record<Bucket, number> = { start: 0, spawn: 0, wake: 0 }
278  const perIssue = new Map<string, number>()
279  for (const entry of recent) {
280    const bucket = bucketOf(entry.kind, entry.class)
281    if (bucket !== null) counts[bucket] += 1
282    if (entry.issue !== null && bucket !== null) {
283      const k = `${perIssueKind(entry.kind, entry.step)}:${entry.issue}`
284      perIssue.set(k, (perIssue.get(k) ?? 0) + 1)
285    }
286  }
287  const caps: Record<Bucket, number> = config.rateCaps
288  const tripped = new Set<string>()
289  const breakers = new Map<string, Ms>()
290  const backoff = state.githubBackoffUntil !== null && state.now < state.githubBackoffUntil
291  const steps = stepBreaker(state.ledger, state.now)
292  // the step-unknown breaker is a fact of the ledger: the owner hears once it trips, whether or not
293  // this pass asks for anything it holds (v2 SPEC 5.3), and its tell logs the trip (7.2)
294  if (steps !== null) breakers.set('steps', steps.since)
295  const kept: Action[] = []
296  for (const action of ctx.out) {
297    const issue = action.issue
298    if (issue !== null && control.paused.includes(issue) && action.kind !== 'heartbeat') {
299      skip(ctx, action.rule, issue, `owner: paused (${action.kind})`)
300      continue
301    }
302    if (control.noNewWork && (action.class === 'start' || action.class === 'develop')) {
303      skip(ctx, action.rule, issue, `owner: no new work (${action.kind})`)
304      continue
305    }
306    if (!ALLOWED[tier].includes(action.class)) {
307      skip(ctx, action.rule, issue, `tier ${tier} (${action.kind})`)
308      continue
309    }
310    if (backoff && ctx.github.includes(action.kind)) {
311      skip(ctx, action.rule, issue, `GitHub rate limit (${action.kind})`)
312      continue
313    }
314    const breaker = executorBreaker(state, action.kind)
315    if (breaker !== null) {
316      breakers.set(action.kind, breaker)
317      skip(ctx, action.rule, issue, `breaker open (${action.kind})`)
318      continue
319    }
320    if (steps !== null && STEP_BREAKER.classes.includes(action.class)) {
321      skip(ctx, action.rule, issue, `breaker open: step unknowns (${action.kind})`)
322      continue
323    }
324    const bucket = bucketOf(action.kind, action.class)
325    if (bucket !== null && counts[bucket] >= caps[bucket]) {
326      tripped.add(bucket)
327      skip(ctx, action.rule, issue, `rate cap: ${bucket} ${counts[bucket]}/${caps[bucket]}`)
328      continue
329    }
330    if (issue !== null && bucket !== null) {
331      const name = perIssueKind(action.kind, action.kind === 'agent-step' ? action.step : undefined)
332      const k = `${name}:${issue}`
333      const n = perIssue.get(k) ?? 0
334      if (n >= config.rateCaps.perIssueKind) {
335        tripped.add(k)
336        skip(ctx, action.rule, issue, `rate cap: ${name} on #${issue} ${n}/${config.rateCaps.perIssueKind}`)
337        continue
338      }
339      perIssue.set(k, n + 1)
340    }
341    if (bucket !== null) counts[bucket] += 1
342    kept.push(action)
343  }
344  ctx.capped = [...tripped].sort()
345  const hour = Math.floor(state.now / HOUR)
346  for (const bucket of ctx.capped) {
347    const notice = wake('tell', 'runaway', `tell:runaway:${bucket}:${hour}`, 'O2', null, { cap: bucket })
348    if (gate(ctx, notice.key, 'tell') === 'go') kept.push(notice)
349  }
350  for (const [kind, at] of [...breakers.entries()].sort()) {
351    const notice = wake('tell', 'breaker', `tell:breaker:${kind}:${at}`, 'O2', null, { kind })
352    if (ctx.ownerTells.includes('breaker')) ctx.owner.add(notice.key)
353    if (gate(ctx, notice.key, 'tell') === 'go') kept.push(notice)
354  }
355  return oneWake(ctx, kept)
356}
357
358// oneWake (O2): at most one wake per pass, none while one is open; owner notices first, then a
359// judge, then a task, then any other notice.
360export function oneWake(ctx: PlanCtx, actions: readonly Action[]): Action[] {
361  const open = ctx.state.ledger.some(e => WAKES.includes(e.kind) && e.status === 'running')
362  const rank = (a: Action) => {
363    if (a.kind === 'tell') return ctx.ownerTells.includes(a.wake) ? 0 : 3
364    return a.kind === 'judge' ? 1 : 2
365  }
366  let chosen: Action | undefined
367  for (const action of actions) {
368    if (!WAKES.includes(action.kind)) continue
369    if (chosen === undefined || rank(action) < rank(chosen)) chosen = action
370  }
371  return actions.filter(action => {
372    if (!WAKES.includes(action.kind)) return true
373    if (!open && action === chosen) return true
374    skip(ctx, action.rule, action.issue, open ? 'a wake is open' : 'one wake per pass')
375    return false
376  })
377}
378
379// --- the title frame (O1; D-23, D-27) ---------------------------------------------------------------
380
381// What a title says: the repo's short name, the layer's counts (null on a blind pass, whose counts
382// are not to be trusted), and a word for each thing that needs attention. `before` and `after` are
383// the layer's own words, around the usage tier's: v2's parked count.
384export type TitleFrame = {
385  repo: string
386  counts: string | null
387  observe: boolean
388  blind: boolean
389  before: readonly string[]
390  tier: Tier
391  after: readonly string[]
392  atCap: boolean
393  capped: readonly string[]
394  backoff: boolean
395  owner: number
396  // when a stopped session began holding work (session-hold.ts)
397  held?: number | null
398}
399
400// titleDue: O1 is a throttle: a title goes out when it
401// differs from the last one and either none was set since the module loaded or titleEveryMs has passed.
402export function titleDue(state: State, config: Config, title: string): boolean {
403  return title !== state.lastTitle && (state.lastTitleAt === null || state.now - state.lastTitleAt >= config.titleEveryMs)
404}
405
406// titleOf: the session title's frame. No usage numbers: a usage tier shows only
407// when it holds work.
408export function titleOf(f: TitleFrame): string {
409  const name = f.repo.split('/')[1] ?? f.repo
410  const head = f.counts === null ? `🔄 ${name}` : `🔄 ${name} (${f.counts})`
411  const words: string[] = []
412  if (f.observe) words.push('observe')
413  if (f.blind) words.push('blind')
414  words.push(...f.before)
415  if (f.tier === 'stop-new') words.push('stop new')
416  if (f.tier === 'stop-all') words.push('stop all')
417  words.push(...f.after)
418  if (f.atCap) words.push('at cap')
419  for (const c of f.capped) words.push(`capped ${c}`)
420  if (f.backoff) words.push('gh wait')
421  if (f.owner > 0) words.push(`owner ${f.owner}`)
422  if (f.held != null) words.push(`held: session stopped since ${new Date(f.held).toISOString().slice(11, 16)}`)
423  return [head, ...words].join(' · ')
424}
425
426// --- shared helpers: the usage tier, the live stages, the agent list, the release review ----------
427
428
429// tierOf: the usage tier (rule G3, v2 SPEC 13.5.2). The higher of the two windows decides; a missing
430// reading is Normal (stop-new in API-key mode) (the skill fails open); an owner override keeps Normal below its pct.
431export function tierOf(
432  usage: Usage,
433  config: Config,
434  override: State['control']['usageOverride'],
435  now: number,
436): { tier: Tier; overridden: boolean } {
437  // API-key mode (spend.ts): spend against the budget is the one reading; a missing one stops new work and
438  // no override lifts it, because nothing then says how much was spent
439  const spend = usage.auth === 'api-key' ? (usage.unavailable ? null : (usage.spend ?? null)) : undefined
440  if (spend === null) return { tier: 'stop-new', overridden: false }
441  if (spend === undefined && (usage.unavailable || (usage.fiveHour === null && usage.sevenDay === null))) {
442    return { tier: 'normal', overridden: false }
443  }
444  const live = (pct: number | null, resetsAt: number | null) => (resetsAt !== null && now >= resetsAt ? 0 : (pct ?? 0))
445  const binding = spend !== undefined
446    ? live(Math.ceil((100 * spend.usd) / spend.budgetUsd), spend.resetsAt) // spend.ts spendPct
447    : Math.max(live(usage.fiveHour, usage.fiveHourResetsAt), live(usage.sevenDay, usage.sevenDayResetsAt))
448  const base: Tier =
449    binding >= config.usageStopAllPct
450      ? 'stop-all'
451      : binding >= config.usageStopNewPct
452        ? 'stop-new'
453        : binding >= config.usageSlowPct
454          ? 'slow'
455          : 'normal'
456  if (base !== 'normal' && override !== null && now < override.expiresAt && binding < override.untilPct) {
457    return { tier: 'normal', overridden: true }
458  }
459  return { tier: base, overridden: false }
460}
461
462// issueFromBranch: the issue number of a branch named by the convention issue-<N>-...
463export function issueFromBranch(branch: string): number | null {
464  const m = branch.match(/(?:^|[/_-])issue-(\d+)(?:-|$)/)
465  return m ? Number(m[1]) : null
466}
467
468// listedLive: an agent list shows this agent still at work (the stop-agent executor asks too):
469// listed, not failed or killed, and its turn not ended (turnEnded).
470export function listedLive(agents: readonly AgentView[], agentId: string): boolean {
471  const seen = agents.find(a => a.id === agentId)
472  return seen !== undefined && !turnEnded(seen.status) && seen.status !== 'failed' && seen.status !== 'killed'
473}
474
475// turnEnded: an agent of the loop listed past its turn: `completed`, or `idle`, which the engine
476// documents as between turns, until a message wakes it (AgentStatus). On Claude Code 2.1.299 an
477// agent that ended its turn is listed idle for 20 s or more before completed (#560). Nothing but
478// the loop's own repair message wakes one of its agents, and while that is on its way, or its
479// reply awaited, the entry is running and the reconciling read holds it at work (act.ts
480// reconcilable), so idle reads as ended here exactly as completed does.
481export function turnEnded(status: AgentStatus): boolean {
482  return status === 'completed' || status === 'idle'
483}
484
485// isoOf: a time as toISOString() writes it (UTC, to the millisecond), by calendar arithmetic: this
486// module reads no clock and builds no Date, so the plan stays pure (a year 1000 to 9999 only).
487export function isoOf(ms: Ms): string {
488  const day = Math.floor(ms / 86_400_000)
489  const left = ms - day * 86_400_000
490  const z = day + 719_468
491  const era = Math.floor(z / 146_097)
492  const doe = z - era * 146_097
493  const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36_524) - Math.floor(doe / 146_096)) / 365)
494  const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100))
495  const mp = Math.floor((5 * doy + 2) / 153)
496  const month = mp < 10 ? mp + 3 : mp - 9
497  const year = yoe + era * 400 + (month <= 2 ? 1 : 0)
498  const pad = (n: number, width = 2) => String(n).padStart(width, '0')
499  const date = `${pad(year, 4)}-${pad(month)}-${pad(doy - Math.floor((153 * mp + 2) / 5) + 1)}`
500  return `${date}T${pad(Math.floor(left / 3_600_000))}:${pad(Math.floor(left / 60_000) % 60)}:${pad(Math.floor(left / 1000) % 60)}.${pad(left % 1000, 3)}Z`
501}
502
503// releaseDue: the review's key and fields: one release task per UTC hour, keyed by tag and hour whatever the waiting set is. `waiting`: the issues waiting on a release tag: the review is then due while the milestone has open items or none closed, and its fields name them. A release task already started this hour (running or ended) makes it null: a wait that arrives later joins the running review or gets the next hour's. `newest`: the newest known tag (the tag view), when given it is the key's and field's tag and `oldest` is left out if it differs from the release read's (that read belongs to the older tag). `short` is config.ts's shortDuration (this module imports types only; foundation.test.ts holds them together)
504export function releaseDue({ milestone: m, release: r = null, sources, ledger, now }: State, config: Config, waiting: readonly number[] = [], newest: string | null = null) {
505  const hour = (at: number) => isoOf(at).slice(0, 13), tag = newest ?? (r === null ? 'unknown' : (r.tag ?? 'none')), short = (ms: Ms) => ms > 0 && ms % 3_600_000 === 0 ? `${ms / 3_600_000}h` : ms > 0 && ms % 60_000 === 0 ? `${ms / 60_000}m` : ms % 1000 === 0 ? `${ms / 1000}s` : `${ms}ms`
506  if (!sources.milestone.ok || m === null || (waiting.length === 0 && (m.open > 0 || m.closed === 0))) return null
507  if (ledger.some(e => e.kind === 'task' && e.wake === 'release' && hour(e.startedAt) === hour(now))) return null
508  return { key: `task:release:${tag}:${hour(now)}`, fields: { closed: m.closed, expected: m.expected, tag, oldest: r === null || r.oldest === null || (newest !== null && newest !== r.tag) ? null : isoOf(r.oldest), cadence: short(config.minimumReleaseCadenceMs), ...(waiting.length > 0 ? { waiting: [...waiting] } : {}) } }
509}
510
hooks/v2/intake.ts 108 lines
1// The intake reader's dry run (epic #995, issue #1151; #1152's real run reuses these functions
2// unchanged): reading the issue and the repo's top level for the reader's prompt, parsing the
3// reader's final message into a checked result (contracts-intake.mjs), and the plain notice the
4// owner reads. The driver's wiring (which holds $) is driver-stamp.ts. A dry run writes nothing.
5import type { RunResult } from '../exec'
6import type { Ms } from '../types'
7import { checkIntake } from './contracts-intake.mjs'
8import type { IntakeResult } from './contracts-intake.mjs'
9
10// the loop's own agent type for the reader (agents/intake.md), hidden from the model like the step agents
11export const INTAKE_AGENT = 'factory-loop:intake'
12
13// a reader that has not ended its turn by then is reported as failed, once (defined in stamps.ts, which the
14// pure planner may import; rule I1 settles a real run by it)
15export { STAMP_TIMEOUT_MS } from './stamps'
16
17// One stamp in progress: the issue, the model it runs on, when it started, and its agent once spawned.
18export type StampRun = { issue: number; model: string; startedAt: Ms; agentId: string | null }
19
20export type Run = (argv: string[]) => Promise<RunResult>
21
22export function startingText(issue: number, model: string): string {
23  return `Stamping #${issue} with ${model}, dry run: its answer follows when the reader ends.`
24}
25
26// readIssue: the issue and its comments by trusted authors only (callum-flow-issue-read drops the rest).
27export async function readIssue(run: Run, issue: number): Promise<{ ok: true; text: string } | { ok: false; why: string }> {
28  try {
29    const r = await run(['callum-flow-issue-read', String(issue), '--comments'])
30    if (r.exitCode !== 0) return { ok: false, why: `the issue could not be read (exit ${r.exitCode}: ${(r.stderr.trim() || r.stdout.trim()).slice(0, 200)})` }
31    return r.stdout.trim() === '' ? { ok: false, why: 'the issue read was empty' } : { ok: true, text: r.stdout }
32  } catch (err) {
33    return { ok: false, why: `the issue could not be read (${String(err).slice(0, 200)})` }
34  }
35}
36
37// topLevelListing: the top-level names of origin's default branch; null when it cannot be listed.
38export async function topLevelListing(run: Run, base: string): Promise<string[] | null> {
39  try {
40    const r = await run(['git', 'ls-tree', '--name-only', `origin/${base}`])
41    return r.exitCode === 0 ? r.stdout.split('\n').filter(l => l.trim() !== '') : null
42  } catch {
43    return null
44  }
45}
46
47// objectSpans: every top-level {...} span of a text, braces inside JSON strings not counted.
48function objectSpans(text: string): string[] {
49  const spans: string[] = []
50  let depth = 0
51  let start = 0
52  let inString = false
53  for (let i = 0; i < text.length; i++) {
54    const c = text[i]
55    if (inString) {
56      if (c === '\\') i++
57      else if (c === '"') inString = false
58    } else if (c === '"' && depth > 0) inString = true
59    else if (c === '{') {
60      if (depth === 0) start = i
61      depth++
62    } else if (c === '}' && depth > 0) {
63      depth--
64      if (depth === 0) spans.push(text.slice(start, i + 1))
65    }
66  }
67  return spans
68}
69
70const failed = (problem: string): IntakeResult => ({ kind: 'failed', area: null, needsOwner: null, reason: null, touches: null, dropped: [], problems: [problem] })
71
72// parseIntakeAnswer: the reader's final message: the whole text as JSON, else the one object (fenced
73// or bare) in it, then checkIntake. No object, or more than one, is a failed result; nothing is repaired.
74export function parseIntakeAnswer(text: string, areas: readonly string[]): IntakeResult {
75  try {
76    return checkIntake(JSON.parse(text.trim()), areas)
77  } catch {
78    // not JSON as a whole: look for the one object in it
79  }
80  const spans = objectSpans(text)
81  if (spans.length === 0) return failed('the answer holds no JSON object')
82  if (spans.length > 1) return failed(`the answer holds ${spans.length} JSON objects; one is expected`)
83  try {
84    return checkIntake(JSON.parse(spans[0] ?? ''), areas)
85  } catch {
86    return failed('the JSON object in the answer does not parse')
87  }
88}
89
90export type StampMeta = { issue: number; model: string; seconds: number }
91
92// stampNotice: the owner's one plain notice. A null result is a stamp that failed before it had an
93// answer, and `why` says why. It always ends by saying nothing was written.
94export function stampNotice(result: IntakeResult | null, meta: StampMeta, why = ''): string {
95  const head = `Stamp #${meta.issue} (${meta.model}, ${meta.seconds}s): `
96  const lines: string[] = []
97  if (result === null) lines.push(`${head}failed: ${why}`)
98  else {
99    lines.push(`${head}${result.kind}`)
100    const show = (v: unknown) => (v === null ? 'none' : Array.isArray(v) ? (v.length === 0 ? 'none' : v.join(', ')) : String(v))
101    lines.push(`area: ${show(result.area)}`, `needs_owner: ${show(result.needsOwner)}`, `reason: ${show(result.reason)}`, `touches: ${show(result.touches)}`)
102    if (result.dropped.length > 0) lines.push(`dropped: ${result.dropped.join(', ')}`)
103    for (const p of result.problems) lines.push(`problem: ${p}`)
104  }
105  lines.push('dry run: nothing written')
106  return lines.join('\n')
107}
108
hooks/v2/types.ts 600 lines
1// The v2 rule layer's vocabulary (docs/factory-loop/v2/SPEC.md): the issue record and its states
2// (section 3), the transition table's events and rows (4), the action kinds of appendix B with
3// their outcomes, the State fields v2 reads (2.4), the labels and notices of appendix D and the
4// rule ids of 14.1. Each closed list is a frozen array here, and its type is derived from it, so
5// a value read from text is checked against the same list the code is typed by. Types and
6// constants only: the pure planner imports this, so nothing here may run a command or read a
7// clock.
8import type { PlanCtx } from '../foundation'
9import type { Snapshot } from '../settings-snapshot'
10import type { ActionBase, ActionClass, Config, LedgerEntry, LedgerStatus, Ms, Source } from '../types'
11import type { V2Event } from './events'
12import type { CheckoutBase } from './reconcile'
13import type { InterventionFacts } from './sources-interventions'
14import type { PrsRead } from './sources-prs'
15import type { FactsShadow } from './sources-facts'
16import type { FlakesRead } from './sources-flakes'
17import type { RecordsShadow } from './sources-records'
18import type { WindDownRead } from './wind-down'
19import type { CapInfo } from './capacity'
20import type { WorkspaceRead } from './workspace'
21import type { StampOwned, StampTries, Stamps } from './stamps'
22import type { QueueView } from './queue-view'
23import type { MainReading } from './types-facts'
24import type { ReleasePrsRead } from './release-hold-types'
25import type { TrainAction, TrainDrop, TrainOutcome, TrainRead } from './train-types'
26
27export { LOOP_CAUSES, PERSON_CAUSES } from './types-facts'
28export type { InterventionWho, MainDeployment, MainReading, MainRun, MainWorkflow } from './types-facts'
29
30// --- states, steps and the record (v2 SPEC 3.1, 3.2) ------------------------------------------------
31
32export const ISSUE_STATES = ['queued', 'designing', 'building', 'reviewing', 'fixing', 'merge-queue', 'parked', 'waiting', 'closed'] as const
33export type IssueState = (typeof ISSUE_STATES)[number]
34
35export const STEP_KINDS = ['lease', 'design', 'build', 'review', 'fix', 'queue', 'triage'] as const
36export type StepKind = (typeof STEP_KINDS)[number]
37
38export const CLOSED_WHYS = ['merged', 'merged-by-hand', 'dropped', 'split', 'closed-on-github', 'claim-lost', 'done'] as const
39export type ClosedWhy = (typeof CLOSED_WHYS)[number]
40
41// The states that hold a slot and count in flight (3.1): designing to merge-queue.
42export const SLOT_STATES: readonly IssueState[] = ['designing', 'building', 'reviewing', 'fixing', 'merge-queue']
43
44// The step each state runs (4.2). Parked, waiting and closed run none; a merge-queue record runs `queue`
45// only while it is the queue's head (9.1).
46export const STATE_STEP: Readonly<Record<IssueState, StepKind | null>> = {
47  queued: 'lease',
48  designing: 'design',
49  building: 'build',
50  reviewing: 'review',
51  fixing: 'fix',
52  'merge-queue': 'queue',
53  parked: null,
54  waiting: null,
55  closed: null,
56}
57
58// The steps an agent runs (4.2), each in the issue's slot.
59export const AGENT_STEPS = ['design', 'build', 'review', 'fix', 'triage'] as const
60export type AgentStep = (typeof AGENT_STEPS)[number]
61
62// Writers may write only inside their slot and push only the record's branch; readers may not
63// write inside the repository (4.2, 10.4).
64export type Role = 'writer' | 'reader'
65export const STEP_ROLE: Readonly<Record<AgentStep, Role>> = { design: 'reader', build: 'writer', review: 'reader', fix: 'writer', triage: 'reader' }
66
67// The class of an agent step (appendix B): develop for design and build, drive for the rest.
68export const STEP_CLASS: Readonly<Record<AgentStep, ActionClass>> = { design: 'develop', build: 'develop', review: 'drive', fix: 'drive', triage: 'drive' }
69
70// The loop-owned agent type each step spawns (5.2, 8.3, 8.7). The model is never offered them
71// (register.ts agent.offer). designer-v2 is renamed designer at the delete wave.
72export const STEP_AGENT: Readonly<Record<AgentStep, `factory-loop:${string}`>> = {
73  design: 'factory-loop:designer-v2',
74  build: 'factory-loop:builder',
75  review: 'factory-loop:reviewer',
76  fix: 'factory-loop:fixer',
77  triage: 'factory-loop:triage',
78}
79
80// One condition a waiting record waits on (3.2, 8.7): an issue closed, a PR merged or a release
81// tag that carries a commit. A record waits until every one holds. `repo` (owner/name, lower-case) names
82// another repository for issue-closed and tag-contains; absent means the loop's own repo.
83export type WaitCondition = { kind: 'issue-closed'; issue: number; repo?: string } | { kind: 'pr-merged'; pr: number } | { kind: 'tag-contains'; sha: string; repo?: string }
84
85// The parts of a structured question for the owner (3.2, 11): what the agent gave before the loop
86// rendered them into `question`. `decision` is the one sentence; options are 2 to 6 closed, with a
87// null detail when none was given; `recommended` names one of the options, `recommendation` is why.
88export type OptionKey = 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
89export type ParkParts = {
90  decision: string
91  context: string | null
92  options: { key: OptionKey; title: string; detail: string | null }[] | null
93  recommended: OptionKey | null
94  recommendation: string | null
95}
96
97// The record (3.2). The slot is not a field: a record holds the slot whose lease holder is
98// `factory-loop:<N>:<life>` (10.1).
99export type IssueRecord = {
100  issue: number
101  // the claim's start time in base-36 seconds: unique per life (3.3, keys.ts lifeOf)
102  life: string
103  // +1 on every transition; part of every per-seq key
104  seq: number
105  // when this seq's transition happened
106  seqAt: Ms
107  state: IssueState
108  // when it entered this state
109  since: Ms
110  // queued: where a lease leads (default designing); parked and waiting: where a resume leads
111  resumeTo: IssueState | null
112  // fixed for the life (3.5)
113  branch: string
114  // adopted at claim, or set when reviewing ends (8.1)
115  pr: number | null
116  // the head a writer step last confirmed on origin
117  head: string | null
118  // the patch id the reviewer approved (8.4)
119  approvedPatch: string | null
120  // the design brief comment URL
121  brief: string | null
122  // the step this seq runs: the state's own, or 'triage'; null when waiting
123  step: StepKind | null
124  // attempt of that step: 1 or 2 (5.1)
125  attempt: number
126  // this attempt already had its one free re-run (row U1)
127  cut: boolean
128  // triage calls in this life, at most maxTriages
129  triages: number
130  // entries to fixing in this life for a round not caused by other merges, at most reviewFixCap
131  fixes: number
132  // entries to fixing in this life for a round caused by other merges (a conflict, or red CI in
133  // the merge queue), at most conflictFixCap
134  conflicts: number
135  // fixing: the environment-blocker reasons of the previous fix round in this life (one clipped line,
136  // at most 1000 characters), null when that round had none; a second round with one parks (T19, T20)
137  envBlocked: string | null
138  // entries to reviewing in this life
139  round: number
140  // parked: the question for the owner
141  question: string | null
142  // parked: the parts of that question when an agent structured it, else null (always null in any
143  // other state); `question` is their rendering
144  parts: ParkParts | null
145  // waiting: the conditions it waits on, every one of which must hold; null in any other state
146  wait: WaitCondition[] | null
147  // closed: why
148  why: ClosedWhy | null
149  // owner, triage and decline notes for the step of this seq
150  notes: string[]
151  // GitHub's closedAt of the newest hand close the record has handled (E4, P1)
152  prClosedAt: string | null
153  // this life's number among the issue's lives since its count last started (6.4, lives.ts): 1
154  // for the first claim, and again for the first claim after the owner lifts factory:rejected
155  lives: number
156}
157
158// A record's identity at one seq: what the transition executor compares before it stores (3.3).
159export type RecordRef = { issue: number; life: string; seq: number }
160
161// --- the table's input and rows (v2 SPEC 4.1, 4.6, 5) -------------------------------------------------
162
163export const EVENT_KINDS = ['ok', 'not-ok', 'unknown', 'triage', 'drop', 'cleared', 'unpark', 'issue-closed', 'pr-merged', 'pr-closed', 'claim-lost', 'timeout'] as const
164export type EventKind = (typeof EVENT_KINDS)[number]
165
166// The causes outside the issue that earn one free re-run per attempt (5.1, row U1).
167export const OUTSIDE_CAUSES = ['load', 'usage', 'breaker', 'slot'] as const
168export type OutsideCause = (typeof OUTSIDE_CAUSES)[number]
169
170// Why a step ended unknown (7.2, intervention `unknown:<why>`). rate-limited is an API rate limit
171// (a 429, or the usage window); api is any other API error (a 5xx, overloaded); stopped is a step
172// whose agent the loop itself stopped (a stop-agent names it) and that gave no answer: no free
173// re-run by itself, and not a death (agent-dead).
174export const UNKNOWN_WHYS = ['timeout', 'agent-dead', 'bad-answer', 'api', 'rate-limited', 'spawn', 'cli', 'github-wait', 'stopped'] as const
175export type UnknownWhy = (typeof UNKNOWN_WHYS)[number]
176
177// The outside cause an unknown's why is by itself (5.1): a rate limit is `usage`, a free re-run
178// that the step-unknown breaker does not count (5.3). Every other why is unexplained unless a fact
179// plan holds (the load, the tier, the breaker, the lease) says otherwise.
180export const WHY_CAUSE: Readonly<Partial<Record<UnknownWhy, OutsideCause>>> = { 'rate-limited': 'usage' }
181
182// The triage menu (5.2).
183export const TRIAGE_CHOICES = ['retry', 'fix', 'redesign', 'park', 'drop'] as const
184export type TriageChoice = (typeof TRIAGE_CHOICES)[number]
185
186// One event for a record (4.6): its kind and what the row's guard and change read.
187export type TableEvent = { kind: EventKind; reason?: string; cause?: OutsideCause; why?: UnknownWhy; choice?: TriageChoice; data?: unknown }
188
189// The reused event states a seq logs beside its `transition` (4.5, 7.1): a drop's `abandoned`.
190export const EMIT_STATES = ['abandoned'] as const
191export type EmitState = (typeof EMIT_STATES)[number]
192
193// One row of the table (4.6). `rowFor` in table.ts is the only lookup.
194export type Row = {
195  id: string
196  states: readonly IssueState[]
197  on: EventKind
198  // pure guard: the guards on one (state, step, event) are exclusive and exhaustive
199  when?: (r: IssueRecord, e: TableEvent, c: Config) => boolean
200  next: IssueState | 'same' | 'resumeTo'
201  // pure: the fields the row changes
202  change: (r: IssueRecord, e: TableEvent, now: Ms) => Partial<IssueRecord>
203  // the transition note's `via` code
204  via: string
205}
206
207// --- what a step reports (v2 SPEC 4.2, 5.1, 10.8) -----------------------------------------------------
208
209// A step's result, as steps.ts records it on the step's ledger entry and plan reads it: ok,
210// not-ok with a reason, or unknown with why. head: a writer's head, read on origin. choice: a
211// triage's. data: the checked answer the step's contract gave (contracts-*.mjs).
212export type StepResult = {
213  event: 'ok' | 'not-ok' | 'unknown'
214  reason: string | null
215  why: UnknownWhy | null
216  head: string | null
217  choice: TriageChoice | null
218  data: unknown
219}
220
221// unknownResult: a step's unknown, with why and a short reason.
222export function unknownResult(why: UnknownWhy, reason: string): StepResult {
223  return { event: 'unknown', reason: reason.length > 200 ? `${reason.slice(0, 197)}...` : reason, why, head: null, choice: null, data: null }
224}
225
226// The guard's FAIL classes in --patch mode (9.3, 9.4).
227export const GUARD_CLASSES = ['behind', 'conflict', 'checks', 'patch', 'linkage', 'read', 'policy'] as const
228export type GuardClass = (typeof GUARD_CLASSES)[number]
229
230export const SLOT_OPS = ['lease', 'prepare', 'kill', 'free'] as const
231export type SlotOp = (typeof SLOT_OPS)[number]
232
233// The outcomes the v2 executors record (one member of types.ts Outcome each).
234export type V2Outcome =
235  | { kind: 'step'; step: AgentStep; result: StepResult }
236  // what a transition did, so the breaker and the interventions read it from the ledger (5.3, 7.2)
237  | {
238      kind: 'transition'
239      row: string
240      event: EventKind
241      cause: OutsideCause | null
242      from: IssueState | null
243      to: IssueState
244      step: StepKind | null
245      // false from the entry's start until the executor stored the record (a lost entry may carry
246      // false: the seq is the record's when the store holds it at that seq)
247      stored: boolean
248      // the transition note's via code (table.ts viaOf), carried from the entry's start (ledger.ts
249      // start): the row's own code, with the detail its event gave where the row takes one:
250      // `free:<cause>` (U1), `unknown:<why>` (U2 to U4), `fix:<review|ci|conflict>` (T9),
251      // `triage:<choice>` (X1 to X5), `unpark:<op|label>` (P1). The seq's entry actions log it and
252      // the interventions read it (rules-interventions.ts), so nothing is inferred from other entries.
253      via: string
254    }
255  | { kind: 'pr'; pr: number; created: boolean; reopened: boolean }
256  | { kind: 'split'; child: number }
257  // an upstream request: the issue raised in another repo, made now or found by its marker
258  | { kind: 'upstream'; repo: string; issue: number; made: boolean }
259  // F1: the flake bug filed or found, with what its tell says (rules-flake-bugs.ts)
260  | { kind: 'flake-bug'; issue: number; made: boolean; ready: boolean; test: string; flakes: number; windowDays: number; firstFlakeAt: string; reason: string }
261  // a close-tracker check: the split parent found (null: the issue is no split child), whether it was closed, and the sub-issues still open
262  | { kind: 'close-tracker'; parent: number | null; closed: boolean; open: number[] }
263  // leftovers: the patch file a prepare or a free saved the slot's leftovers to (10.2): its uncommitted
264  // work and its commits not on origin, against the commit the next step starts from; a retry's
265  // prompt names it (5.1), and a resumed life finds a free's through rules-agent.ts leftoversOf; null
266  // when nothing would have been lost
267  | { kind: 'slot'; op: SlotOp; path: string | null; lease: string | null; head: string | null; killed: number | null; leftovers?: string | null }
268  // drop: a train merge that fell back to the queue's own path, with why (9.8); the try is not counted toward the unknown
269  | { kind: 'queue'; op: 'update' | 'merge'; merged: boolean; head: string | null; failClass: GuardClass | null; lines: string[]; drop?: TrainDrop }
270  | TrainOutcome
271  // an open PR adopted at claim (3.5)
272  | { kind: 'adopt'; branch: string; pr: number | null; others: number[] }
273
274// --- the action kinds (appendix B) ----------------------------------------------------------------
275
276// How deep trackers nest: observe reads sub-issues this many levels down, and a close-tracker chain
277// checks this many trackers up (state.ts re-exports it).
278export const TRACKER_DEPTH = 3
279
280export const V2_ACTION_KINDS = ['transition', 'label', 'comment', 'event', 'pr', 'split', 'agent-step', 'ci-rerun', 'queue-update', 'queue-merge', 'queue-train', 'slot', 'link', 'close-tracker', 'flake-bug', 'released', 'intake-stamp', 'upstream'] as const
281// What F1 asks of the flake-bug executor: the test and its hash (the marker's), the bug's title and
282// body (without its markers; flakeIds are the flakes it lists), whether `ready` is allowed, the epic to link under, and what the bug's tell records.
283export type FlakeBugSpec = { hash: string; test: string; title: string; body: string; flakeIds: string[]; ready: boolean; epic: number | null; flakes: number; windowDays: number; firstFlakeAt: string; reason: string }
284
285export type V2ActionKind = (typeof V2_ACTION_KINDS)[number]
286
287// What the transition executor re-checks against the live ledger and records before it stores
288// (3.3): the life's claim entry (row S0), a step's entry as plan saw it, or an owner or GitHub
289// fact (an edge whose time the record already carries).
290export type Trigger =
291  | { kind: 'claim'; key: string }
292  | { kind: 'entry'; key: string; status: LedgerStatus; startedAt: Ms }
293  | { kind: 'fact'; fact: string }
294
295// The step marker the slot carries in its git dir (10.2), which the companion reads.
296export type StepMarker = {
297  v: 1
298  repo: string
299  issue: number
300  life: string
301  seq: number
302  step: AgentStep
303  role: Role
304  branch: string
305  // the issue's PR, when it has one (the companion's notes carry it); an older marker has none
306  pr: number | null
307  gateCommands: string[]
308  gateTimeoutMs: Ms
309  loopDir: string
310  // the step attempt's scratch folder (keys.ts scratchOf), which the companion exports as TMPDIR; the
311  // slot executor fills it, like loopDir
312  scratch: string
313  // the stop gates the companion runs at once, resolved from the config and the CPU count by the slot
314  // executor (the planner does not know the CPUs); absent: no limit, as an older loop wrote it
315  gateConcurrency?: number
316  // the longest a finished writer waits for its gate's turn, set by the slot executor
317  gateWaitTimeoutMs?: Ms
318}
319
320// The four reasons of a designer's split (8.7; contracts-work.mjs REASON_KEYS).
321export type SplitReasons = { why_split: string; why_count: string; why_parts: string; why_order: string }
322
323// A child a designer's split asks for (8.7).
324export type SplitChild = { key: string; title: string; why: string; body: string; blockedBy: string[]; ready: boolean; decision: string | null; decisionParts?: ParkParts | null }
325
326export type V2Action =
327  // cause: the outside cause of an unknown (5.1), which the breaker reads; via: the note's code;
328  // fromState and fromStep: the state and step the record leaves, which the entry carries from its
329  // start (ledger.ts start), so a crash before it is saved done loses none of them (3.3)
330  | (ActionBase & {
331      kind: 'transition'
332      row: string
333      event: EventKind
334      from: RecordRef | null
335      next: IssueRecord
336      trigger: Trigger
337      cause?: OutsideCause | null
338      via?: string
339      fromState?: IssueState | null
340      fromStep?: StepKind | null
341    })
342  // set: add the state's label and remove the other six; ensure: create the eight; clear: remove
343  // the seven state labels (3.4); requeue: the seven off and `ready` on (ready: the repo's ready
344  // label); reject: the seven off and factory:rejected on (both R1's release, 6.4)
345  | (ActionBase & { kind: 'label'; op: LabelOp; label: FactoryLabel | null; ready?: string })
346  // the body carries the hidden key <!-- factory-loop:<ledger key> --> (4.5)
347  | (ActionBase & { kind: 'comment'; on: 'issue' | 'pr'; number: number; body: string })
348  // built only by events.ts (7.1); logged: the event log already holds it (events.ts logOnce), so
349  // the executor settles it done with no second write
350  | (ActionBase & { kind: 'event'; event: V2Event; logged?: true })
351  | (ActionBase & {
352      kind: 'pr'
353      op: 'ensure' | 'body'
354      branch: string
355      base: string
356      pr: number | null
357      title: string
358      summary: string
359      evidence: string | null
360      brief: string | null
361    })
362  // a waiting record's issue linked as blocked by an issue it waits on (blocker): the GitHub dependency
363  // link, once per condition; a closed blocker is skipped, a pull request is no blocker (act-split.ts)
364  | (ActionBase & { kind: 'link'; blocker: number })
365  // a merged split child's check upward: issue is the one to check from; its split parent is closed when every sub-issue is closed (act-tracker.ts)
366  | (ActionBase & { kind: 'close-tracker' })
367  // F1: one bug for a flaky test, found again by its hidden marker or filed; ready: the cap allowed `ready` (rules-flake-bugs.ts)
368  | (ActionBase & { kind: 'flake-bug'; bug: FlakeBugSpec })
369  // O4: log a release tag (callum-flow-released); source: the loop's own release task made it, or the workflow
370  | (ActionBase & { kind: 'released'; tag: string; source: 'loop' | 'workflow' })
371  // one child per action; blockedBy: the issue numbers it waits on: siblings made, or existing issues
372  | (ActionBase & { kind: 'split'; parent: number; child: SplitChild; blockedBy: number[] })
373  // a design's upstream request: one issue in target (a repo of UPSTREAM_REPOS), found by its marker or made (act-upstream.ts); authority: what the designer rested it on; fields: the decision log's view of it
374  | (ActionBase & { kind: 'upstream'; target: string; request: 'bug' | 'need'; title: string; body: string; marker: string; authority: { kind: 'owner' | 'bug'; source?: string }; fields: Record<string, string> })
375  // I1: the intake reader on one issue's body version. run: record the try, spawn the reader; settle: a run
376  // that timed out or was lost ends failed (why), its agent stopped. The key names the version (act-intake.ts)
377  | (ActionBase & { kind: 'intake-stamp'; op: 'run' | 'settle'; version: string; why?: string })
378  | (ActionBase & { kind: 'agent-step'; step: AgentStep; life: string; seq: number; attempt: number; branch: string; slot: string | null; notes: string[] })
379  | (ActionBase & { kind: 'ci-rerun'; pr: number; runId: string; round: number })
380  // base: main's head at plan time (the key's); head: the PR's head as observe read it
381  | (ActionBase & { kind: 'queue-update'; pr: number; base: string; head: string })
382  // testedTree: the tree the train's CI passed (callum-flow-merge --tested-tree); trainDropped: why the record's train was dropped (--train-dropped); at most one
383  | (ActionBase & { kind: 'queue-merge'; issue: number; pr: number; head: string; patch: string; testedTree?: string; trainDropped?: TrainDrop })
384  | TrainAction
385  | (ActionBase & { kind: 'slot'; op: SlotOp; life: string; path: string | null; lease: string | null; branch: string | null; marker: StepMarker | null; keepScratch: boolean })
386
387// --- labels and notices (appendix D) ---------------------------------------------------------------
388
389export const LABEL_OPS = ['set', 'ensure', 'clear', 'requeue', 'reject'] as const
390export type LabelOp = (typeof LABEL_OPS)[number]
391
392export const FACTORY_LABEL_PREFIX = 'factory:'
393
394export type FactoryLabel = `factory:${Exclude<IssueState, 'closed'>}`
395
396// Each state's label (closed has none), with its colour and description (appendix D).
397export const FACTORY_LABELS: Readonly<Record<Exclude<IssueState, 'closed'>, { name: FactoryLabel; color: string; description: string }>> = {
398  queued: { name: 'factory:queued', color: 'c5def5', description: 'Factory loop: claimed, waiting for a slot' },
399  designing: { name: 'factory:designing', color: 'bfd4f2', description: 'Factory loop: the designer is at work' },
400  building: { name: 'factory:building', color: '0e8a16', description: 'Factory loop: the implementer is at work' },
401  reviewing: { name: 'factory:reviewing', color: 'fbca04', description: 'Factory loop: review and CI on the PR' },
402  fixing: { name: 'factory:fixing', color: 'd93f0b', description: 'Factory loop: a fixer is at work' },
403  'merge-queue': { name: 'factory:merge-queue', color: '5319e7', description: 'Factory loop: approved and green, waiting to merge' },
404  parked: { name: 'factory:parked', color: 'b60205', description: 'Factory loop: waits on the owner; remove this label to resume' },
405  waiting: { name: 'factory:waiting', color: 'fef2c0', description: 'Factory loop: waits on a condition the loop checks; it resumes by itself' },
406}
407
408// resumeStep: how the owner resumes a parked issue (11), one text for every message that says so:
409// the park comment, its tell and reminders, and the triage prompt's park choice.
410export function resumeStep(issue: number): string {
411  return `answer on the issue and ${resumeAction(issue)}; a comment alone does not resume`
412}
413
414// resumeAction: the two things that resume, which the park comment's numbered list (park-text.ts)
415// says after its first step.
416export function resumeAction(issue: number): string {
417  return `remove the \`factory:parked\` label, or run \`/factory resume ${issue} "your answer"\``
418}
419
420// The label of an issue R1 released at its last life (6.4): not a state, since the issue is out of
421// the factory. S1 never claims an issue carrying it; the owner removing it and adding `ready`
422// brings the issue back with its life count started again.
423export const REJECTED_LABEL: { name: 'factory:rejected'; color: string; description: string } = {
424  name: 'factory:rejected',
425  color: '6a737d',
426  description: 'Factory loop: its last life ended without a merge; remove this label and add ready to try again',
427}
428
429// The owner's hold on a merge (9.1): set on the issue or its PR, the loop reads it and never makes,
430// adds or removes it, so it is not in ALL_FACTORY_LABELS. It is a hold, not a state.
431export const DONT_MERGE_LABEL = "don't-merge"
432
433// sameLabel: label names are equal ignoring case.
434export const sameLabel = (a: string, b: string): boolean => a.toLowerCase() === b.toLowerCase()
435
436// Every label the loop makes (op ensure): the seven state labels, then factory:rejected.
437export const ALL_FACTORY_LABELS: readonly { name: string; color: string; description: string }[] = [...Object.values(FACTORY_LABELS), REJECTED_LABEL]
438
439// labelOf: a state's label, or null for closed.
440export function labelOf(state: IssueState): FactoryLabel | null {
441  return state === 'closed' ? null : FACTORY_LABELS[state].name
442}
443
444// The notice (TELL) kinds v2 adds; the owner items (V2_OWNER_TELLS) go out before any other
445// wake (O2); blind, the foundation's own, is one of them under v2. The foundation's others (runaway, heartbeat-other, old-watcher, schema-behind, pass-error) stay.
446export const V2_OWNER_TELLS = ['parked', 'breaker', 'stalled', 'checkout', 'workspace', 'rejected', 'keep-open-blocks', 'reopened', 'records-shadow', 'facts-shadow', 'wait-unreadable', 'starved', 'actions-refused', 'blind', 'reader-behind', 'release-hold'] as const
447export const V2_TELLS = [...V2_OWNER_TELLS, 'waiting', 'task-timeout', 'wind-down-stale', 'done', 'flake-bug', 'actions-resumed', 'capacity'] as const
448export type V2Tell = (typeof V2_TELLS)[number]
449
450// --- rule ids (v2 SPEC 14.1) -------------------------------------------------------------------------
451
452export const V2_RULES = [
453  'G1', 'G2', 'G3', 'G4', 'H1', 'H2', 'R1', 'R2', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'Q1', 'Q2', 'Q3', 'W1', 'W2', 'O1', 'O2', 'O3', 'O4', 'O5', 'M1', 'F1', 'I1',
454] as const
455export type V2Rule = (typeof V2_RULES)[number]
456
457// --- what v2 reads (v2 SPEC 2.4) ---------------------------------------------------------------------
458
459// A pool slot's lease, by its holder (10.1): `factory-loop:<N>:<life>` names the loop's own.
460export type Lease = { path: string; lease: string; holder: string; issue: number | null; life: string | null; status: string; busy: boolean }
461
462// The newest issue read observe holds, and when it was taken: the parked label's absence in a
463// read newer than the park is the unpark signal (3.4).
464export type IssueRead = { at: Ms; open: boolean | null; labels: string[] | null }
465
466// One wait condition as the last successful read showed it, and when that read was taken (4.4).
467// `tag`: the release tag a tag-contains read compared against, so it is read again only when the tag changes.
468export type WaitRead = { at: Ms; held: boolean; tag?: string }
469
470// A condition the loop cannot read, since when: its read failed, or (tag-contains) its repo has no release tag.
471export type WaitUnread = { since: Ms; why: 'read-failed' | 'no-release' }
472
473// A trusted comment on an issue (callum-flow-issue-read --comments), for a resume's note (11).
474export type IssueComment = { body: string; at: Ms; url: string | null }
475
476// When observe first saw a PR head (2.4): it bounds the waits on GitHub (4.4).
477export type HeadSeen = { pr: number; at: Ms }
478
479export const V2_SOURCES = ['store', 'leases', 'prs', 'interventions', 'comments', 'dualWrite', 'releasePrs', 'main', 'flakes'] as const
480// What the new event log holds, read once per load when dual write is on (sources-dualwrite.ts): when it
481// was read and the "<issue>:<life>:<seq>" of this device's transitions it holds.
482export type DualWrite = { readAt: Ms; seen: ReadonlySet<string> }
483
484export type V2SourceName = (typeof V2_SOURCES)[number]
485
486// One issue of the blocker tree (sources-blockers.ts): what its single read showed. `blockers` are its
487// open blockers in this repo, `foreign` its open blockers elsewhere (`owner/name#N`, never read);
488// `read` is how its read ended: refused (an untrusted author, exit 3) or failed.
489export type BlockerNode = { open: boolean; labels: string[]; title: string | null; blockers: number[]; foreign: string[]; read: 'ok' | 'refused' | 'failed' }
490
491// The blockers of the queue's blocked issues, read for one starved spell and one 24 h period of it.
492// `nodes` are by issue number; a blocker that has no node was not read (the cap stopped the walk).
493export type BlockerTree = { since: Ms; period: number; readAt: Ms; nodes: Record<number, BlockerNode>; truncated: boolean; error: string | null }
494
495// What S1 says of a pass (rules-claim.ts): `starved` is true when the queue is not empty, nothing is
496// queued or in flight, no owner hold or stopping tier applies and every queue issue was skipped by a claim
497// filter; null when a source failed (unknown). `skips`: each queue issue's filter reason, `blocked`: those
498// skipped for their blockers.
499export type StarvedVerdict = { starved: boolean | null; skips: Map<number, string>; blocked: number[] }
500
501// The State fields v2 adds (2.4), as State.v2: observeV2 reads them every pass; absent in a state
502// built outside a pass.
503export type V2State = {
504  sources: Record<V2SourceName, Source>
505  // the newest release tag; null: the reads show no release; absent: no tag read held yet
506  tag?: string | null
507  records: IssueRecord[]
508  // where the records came from: the store (act mode's), the event log (a rebuild), or neither
509  recordsFrom: 'store' | 'events' | 'none'
510  // by head sha
511  heads: Record<string, HeadSeen>
512  leases: Lease[]
513  // the newest read of each issue observe holds, by issue number
514  reads: Record<number, IssueRead>
515  // trusted comments of parked records whose label a person removed, by issue number
516  comments: Record<number, IssueComment[]>
517  prs: PrsRead
518  // the conditions waiting records wait on, by key (`issue:57`, `pr:812`, `tag:35bb655`): the last read that
519  // showed one; a condition with no entry was not read, or its read failed, and stays open
520  waits?: Record<string, WaitRead>
521  // the conditions that cannot be read, by key, and since when; absent: none
522  waitsUnread?: Record<string, WaitUnread>
523  // the open release bump PRs (sources-release.ts) the merge queue holds for; absent: none read
524  releasePrs?: ReleasePrsRead
525  // the live trains' checks and the trees the rules compare (sources-train.ts); absent: none read
526  train?: TrainRead
527  // the default branch as the last read that succeeded showed it (sources-main.ts); absent: none this pass
528  main?: MainReading
529  // the flakes in the window and the open flake bugs (sources-flakes.ts); absent: not read this pass
530  flakes?: FlakesRead
531  // when the PR reads showed each issue's PR closed or merged (GitHub's closedAt), by issue number:
532  // an older read of the issue is due at once, and pr-closed waits for it (4.1)
533  changed: Record<number, Ms>
534  // the intake stamps and each live record's in-flight paths (null: the read failed); present only while intakeStamp is on
535  stamps?: Stamps
536  // the tries and the owner-owned label groups of the intake stamp (stamps.ts); present only while intakeStamp is on
537  stampTries?: StampTries
538  stampOwned?: StampOwned
539  inFlightPaths?: Record<number, string[] | null>
540  interventions: InterventionFacts
541  // the onceKeys (events.ts) of this device's events in the pass's read of the event log (the facts
542  // read, 2.4, or the rebuild's week): which facts are logged, when a wiped store lost their ledger
543  // keys (7.2)
544  logged: string[]
545  // the main checkout the tripwire last settled on, which R1 compares this pass's read with
546  // (10.7; reconcile.ts checkoutBaseOf); null before the first read that did not fail
547  checkoutBase: CheckoutBase | null
548  // the new log's transitions; null when dual write is off or not read (act mode, planner v2 only)
549  dualWrite: DualWrite | null
550  // the last compare of the record rebuild's two stores (sources-records.ts), as of the pass that made it; absent: none made this load
551  recordsShadow?: RecordsShadow
552  // the last compare of the facts' and ledger rebuild's two stores (sources-facts.ts); absent: none made this load
553  factsShadow?: FactsShadow
554  // the workspace rail: the companion's handshake for this session (10.9; workspace.ts); absent
555  // when not read, which holds nothing
556  workspace?: WorkspaceRead
557  // the container's memory in bytes (config.ts gateLimits); null: not readable; absent: not read (capacity.ts)
558  memoryBytes?: number | null
559  // the wind-down request, stop-now file and last status (10.11; wind-down.ts); absent when not read
560  windDown?: WindDownRead
561  // when the current starved spell began (the store's `starved:<repo>`); absent: no spell (S1)
562  starvedSince?: Ms
563  // the blocker tree read for the spell and its current period (sources-blockers.ts); absent: not read
564  blockers?: BlockerTree
565  // the settings in force now, the last snapshot kept in the store (null: none valid) and the config ops that landed since (rules-settings.ts); absent: not read
566  settings?: { now: Snapshot; nowAt: Ms; before: Snapshot | null; beforeAt: Ms | null; ops: SettingsOp[] }
567}
568
569// a config op that landed (driver-controls.ts), kept in the store until the snapshot after it
570export type SettingsOp = { key: string; by: 'person' | 'judge'; at: Ms }
571
572// The pure planner's context: the foundation's, with the v2 fields every rule reads.
573export type V2Ctx = PlanCtx & { v2: V2State; starved?: StarvedVerdict; cap?: CapInfo; queue?: QueueView }
574
575// --- what the executors may change beside the ledger (v2 SPEC 3.3, 4.6) -------------------------------
576
577// The live records: only the transition executor updates them, under the act lock. update applies
578// fn to the records as they are now (null: no change), saves them to the store, and resolves once
579// saved; changed is false when fn changed nothing or the store refused the write.
580export type V2Io = {
581  records: () => readonly IssueRecord[]
582  // the live ledger, which the transition executor re-checks its trigger against (3.3)
583  ledger?: () => readonly LedgerEntry[]
584  updateRecords: (fn: (records: readonly IssueRecord[]) => IssueRecord[] | null) => Promise<{ changed: boolean; saved: boolean }>
585  // stamps:<repo> changed by fn, which gets the value as the store holds it and returns the whole value to store
586  // (null: no change): a read-modify-write that keeps keys it does not know (stamps.ts withTry, withStamp, withOwned)
587  updateStamps?: (fn: (raw: unknown) => unknown) => Promise<{ changed: boolean; saved: boolean }>
588  // asks the driver for the next pass at once: a transition's next event is taken without delay
589  ping: (why: string) => void
590}
591
592// --- settings (appendix A) ------------------------------------------------------------------------
593
594// the model aliases the agent tool accepts; a setting named *Model takes one of them
595export const MODELS = ['sonnet', 'opus', 'haiku', 'fable'] as const
596export type Model = (typeof MODELS)[number]
597
598// The timeouts and tell periods of 4.4, by step and waiting state.
599export type StateTimeouts = { design: Ms; build: Ms; review: Ms; fix: Ms; triage: Ms; queued: Ms; queueWait: Ms; parked: Ms; waiting: Ms }
600
hooks/v2/workspace.ts 78 lines
1// The loop's side of the companion plugin `factory-loop-workspace` (docs/factory-loop/v2/SPEC.md
2// 10.3, 10.5, 10.9), pure: the slot line and folder each agent step's spawn carries, the Bash
3// timeout the loop sets for its session, and the workspace rail. The companion writes a handshake
4// for each session it runs in, again every minute; without a fresh one for this session, an agent
5// would start in the main checkout, unguarded, so every agent step is held with the skip line
6// `workspace`, and the owner is told once (tell(workspace)). sources-workspace.ts reads and judges
7// the handshake, observeV2 puts it in the State, and rules-state.ts and plan.ts hold and tell
8// from it.
9import { skip, wake, want } from '../foundation'
10import type { Ms } from '../types'
11import { AGENT_STEPS } from './types'
12import type { StepKind, V2Ctx } from './types'
13
14// The 10-minute Bash timeout (10.5): the loop's session.start sets BASH_DEFAULT_TIMEOUT_MS and
15// BASH_MAX_TIMEOUT_MS to it; the companion also gives a loop agent's Bash call with no timeout the
16// same value.
17export const BASH_TIMEOUT_MS = '600000'
18
19// The rail's owner notice waits this long after the module loaded, so the companion's own
20// session.start, which may finish after the loop's first pass, is not told as missing. The hold
21// starts at once.
22export const WORKSPACE_GRACE_MS = 2 * 60_000
23
24// withSlotLine: the spawn's prompt, opening with `factory-slot: <slot>`, which the companion reads
25// to start the agent in its slot (10.3). A prompt that opens with it already is kept; one that
26// opens with another slot's has that line replaced. No slot: the prompt as it is.
27export function withSlotLine(prompt: string, slot: string | undefined): string {
28  if (slot === undefined) return prompt
29  const line = `factory-slot: ${slot}`
30  const nl = prompt.indexOf('\n')
31  const first = nl === -1 ? prompt : prompt.slice(0, nl)
32  if (first === line) return prompt
33  if (first.startsWith('factory-slot: ')) return nl === -1 ? line : `${line}${prompt.slice(nl)}`
34  return `${line}\n${prompt}`
35}
36
37// handshakePath: where the companion says it runs in a session (its hooks/register.ts
38// handshakePath): one file per session under the loop's base directory.
39export function handshakePath(loopBase: string, session: string): string {
40  return `${loopBase}/workspace/${session.replace(/[^A-Za-z0-9._-]/g, '_')}.json`
41}
42
43// processIdOf: the process that /proc/<pid>/stat describes, by its pid and start time, as the
44// companion names its own in the handshake (its hooks/register.ts processIdOf). No other process
45// has it: not a child, not a later one given the same pid. undefined: no stat to read.
46export function processIdOf(stat: string | null): string | undefined {
47  const pid = stat?.split(' ', 1)[0] ?? ''
48  const start = stat?.slice(stat.lastIndexOf(') ') + 2).split(' ')[19] ?? ''
49  return /^\d+$/.test(pid) && /^\d+$/.test(start) ? `${pid}:${start}` : undefined
50}
51
52// What the rail read for this session and this process (null: its id is unknown): the handshake
53// is there, names both, and is fresh, or why not (sources-workspace.ts workspaceRead).
54export type WorkspaceRead = { session: string; process: string | null } & ({ ok: true; version: string | null } | { ok: false; why: string })
55
56// workspaceHold: why a record's step may not start: an agent step while the rail fails. null: it
57// may (the rail passed, or was not read).
58export function workspaceHold(ctx: V2Ctx, step: StepKind | null): string | null {
59  const w = ctx.v2.workspace
60  if (w === undefined || w.ok || step === null || !(AGENT_STEPS as readonly string[]).includes(step)) return null
61  return `workspace: ${w.why}; agent steps are held`
62}
63
64// workspaceTell: the owner told once per process the rail failed in, after the grace: the
65// supervisor resumes the same session in each new process, and each outage is told.
66export function workspaceTell(ctx: V2Ctx): void {
67  const w = ctx.v2.workspace
68  if (w === undefined || w.ok) return
69  const since: Ms = ctx.state.loadedAt
70  if (ctx.state.now - since < WORKSPACE_GRACE_MS) {
71    skip(ctx, 'O2', null, `workspace: told after ${WORKSPACE_GRACE_MS / 60_000} minutes without the companion: ${w.why}`)
72    return
73  }
74  const key = `tell:workspace:${`${w.session}/${w.process ?? 'unknown'}`.replace(/[^A-Za-z0-9._-]/g, '_')}`
75  const context = [w.why, 'Enable the factory-loop-workspace plugin beside factory-loop in this workspace, then restart the session. Until then no agent step starts.']
76  want(ctx, wake('tell', 'workspace', key, 'O2', null, { session: w.session }, context))
77}
78
hooks/act.ts 481 lines
1// The act step (v2 SPEC 13.2, 13.6, 13.7, 13.8, 13.10): the one dispatcher from an action's kind to its executor,
2// what an act-mode pass does once observe has read the factory (what the agent list proves,
3// wakes past their timeout, plan, then plan's actions in order: start each ledger entry,
4// pre-check usage for a token-spending class, run the executor, finish the entry with what it
5// reported), and what the hooks between passes do to the ledger (an agent's answer, in text or
6// through its answer tool, a wake's turn, the wake answer tool, `/factory retry`). Every entry
7// that moves gets its `loop` event, once.
8// register.ts holds $, builds the ActIo and keeps the store; everything here works through the
9// ActIo and the live ledger, so the tests drive whole passes, and the argv safety test every
10// executor, with a recording fake. The layer that plans is v2/plan.ts (v2 SPEC 2.3).
11import { cliExecutors } from './act-cli'
12import { isOffPass, launchOff, offPassExpired, sameAttempt } from './act-off'
13import type { OffPass } from './act-off'
14import { mergeExecutors } from './act-merge'
15import type { ActIo, Exec, ExecCtx, Executor, RunInit, RunResult } from './exec'
16import { GITHUB_V2, turnEnded } from './foundation'
17import { changedEntries, finish, loopEvent, reconcileAgents, start } from './ledger'
18import type { Runtime } from './observe'
19import { preCheck } from './rails'
20import type { Action, ActionKind, AgentStatus, Config, Control, LedgerEntry, Ms, PlanResult, State } from './types'
21import { planV2 } from './v2/plan'
22import { V2_EXECUTORS, executorOf } from './v2/registry'
23import { stepAnswers, stepRecorded } from './v2/steps'
24import { NO_TOKENS, readStepTokens } from './v2/step-tokens'
25import { gateHoldMs } from './v2/steps-gate'
26import { V2_ACTION_KINDS } from './v2/types'
27import { expireWakes, wakeExecutors } from './wake'
28import { readWakeCost } from './wake-cost'
29
30const SUMMARY_MAX = 200
31// callum-flow-event is one jq call and one append; a minute is ample
32const EVENT_TIMEOUT_MS = 60_000
33
34// Every kind's executor (v2 SPEC 13.6.1): the shared kinds', and v2's for its new kinds (v2/registry.ts).
35// act.test.ts checks that no ActionKind lacks one.
36export const EXECUTORS: Partial<Record<ActionKind, Executor>> = {
37  ...cliExecutors,
38  ...mergeExecutors,
39  ...wakeExecutors,
40  ...Object.fromEntries(V2_ACTION_KINDS.map(kind => [kind, V2_EXECUTORS[kind]])),
41}
42
43const WAKES: readonly ActionKind[] = ['judge', 'task', 'tell']
44
45// dispatch: the action's executor, v2's own for the kind first (a reused kind may have a v2
46// behaviour), run again after a GitHub blip (registry.ts). A kind with no executor, or an
47// executor that throws, is a failed attempt; neither is a reason to stop the pass.
48export async function dispatch(ctx: ExecCtx, action: Action): Promise<Exec> {
49  const run = executorOf(action.kind, EXECUTORS)
50  if (run === undefined) return { status: 'failed', summary: `no executor for ${action.kind}`, noRetry: true }
51  try {
52    return await run(ctx, action)
53  } catch (err) {
54    return { status: 'failed', summary: clip(`${action.kind}: the executor threw: ${message(err)}`) }
55  }
56}
57
58// --- commands and events (v2 SPEC 13.6.1, 13.7.4, 13.11.1) ---------------------------------------------------
59
60// commandOf: ExecCtx.cmd: the argv from the main checkout (or init.cwd) with the runtime's
61// environment, which carries the repo, the configured labels and, when not acting, the event
62// sink. stdin passes through as given, an empty string included. Each command joins the pass's
63// list for the decision log.
64export function commandOf(io: ActIo, rt: Runtime, log: string[]): ExecCtx['cmd'] {
65  return (argv: string[], init: RunInit): Promise<RunResult> => {
66    log.push(argv.join(' ').slice(0, 160))
67    const run: RunInit & { cwd: string; env: Record<string, string> } = { cwd: init.cwd ?? rt.cwd, env: init.env === undefined ? rt.env : { ...rt.env, ...init.env }, timeoutMs: init.timeoutMs }
68    if (init.stdin !== undefined) run.stdin = init.stdin
69    return io.run(argv, run)
70  }
71}
72
73// eventArgv: `callum-flow-event --type <type> --data <json> --issue N`.
74export function eventArgv(type: string, data: Record<string, unknown>, at: { issue: number }): string[] {
75  return ['callum-flow-event', '--type', type, '--data', JSON.stringify(data), '--issue', String(at.issue)]
76}
77
78// eventOf: ExecCtx.event. callum-flow-event exits non-zero only on a usage error (2); the error
79// carries the exit as `exitCode`, which the executors read to never retry it.
80export function eventOf(cmd: ExecCtx['cmd']): ExecCtx['event'] {
81  return async (type, data, at) => {
82    const r = await cmd(eventArgv(type, data, at), { timeoutMs: EVENT_TIMEOUT_MS })
83    if (r.exitCode === 0) return
84    const why = r.stderr.trim().split('\n').pop() ?? ''
85    throw Object.assign(new Error(`callum-flow-event ${type}: exit ${r.exitCode}${why === '' ? '' : `: ${why}`}`), { exitCode: r.exitCode })
86  }
87}
88
89// --- the live ledger ---------------------------------------------------------------------------
90
91// The ledger as the driver holds it: one array, replaced whole by every transition. The pass and
92// the hooks that fire during it (an agent's answer, a wake's turn) apply their transitions to the
93// array as it is then, with no await between the read and the write, so neither loses the other's.
94// logged: the loop event last logged for each key (logLoop); a ledger loaded from the store or the
95// event log starts it with loggedOf, since each of its entries was logged as it got there.
96export type Live = { ledger: LedgerEntry[]; logged?: Map<string, string> }
97
98// loggedOf: the loop event each entry of a loaded ledger already logged.
99export function loggedOf(ledger: readonly LedgerEntry[]): Map<string, string> {
100  const out = new Map<string, string>()
101  for (const entry of ledger) {
102    const argv = loopEvent(entry)
103    if (argv !== null) out.set(entry.key, JSON.stringify(argv))
104  }
105  return out
106}
107
108// transition: apply fn to the live ledger; the entries it changed, for their loop events.
109export function transition(live: Live, fn: (ledger: LedgerEntry[]) => LedgerEntry[]): LedgerEntry[] {
110  const before = live.ledger
111  live.ledger = fn(before)
112  return changedEntries(before, live.ledger)
113}
114
115// What an act step works with.
116export type ActEnv = {
117  io: ActIo
118  // the acting runtime: its env sends events to the real log
119  rt: Runtime
120  live: Live
121  // the pass's command list, for the decision log
122  commands: string[]
123  // a fresh wake id (v2 SPEC 13.8.1 `id=`)
124  wakeId: () => string
125  // $.session.id(): the session a wake it submits belongs to ('' when unknown)
126  session: string
127  // writes the live ledger to the store: an attempt's start before its executor runs, and every
128  // transition before its loop event, so a reload at any point finds what already happened;
129  // false when it was not written
130  save: () => Promise<boolean>
131  // this session still holds the act lock, renewed now; once it does not, the pass runs nothing
132  // more. Asked before every action.
133  holds: () => Promise<boolean>
134  // the kill switch is set (v2 SPEC 13.11.3): one stat, asked before every action but the title and
135  // before a notice goes out; once it is, the pass runs nothing more
136  killed: () => Promise<boolean>
137  // what went wrong outside any one action (a loop event not logged), for the decision log
138  problems: string[]
139  // where a command of an OFF_PASS kind (act-off.ts) ends; absent, it runs inline in the action
140  offPass?: OffPass
141}
142
143export function ctxOf(env: ActEnv, state: State, entry: LedgerEntry): ExecCtx {
144  const cmd = commandOf(env.io, env.rt, env.commands)
145  return { io: env.io, rt: env.rt, state, entry, cmd, event: eventOf(cmd), wakeId: env.wakeId }
146}
147
148// logLoop: the `loop` event of each entry a transition moved that logs one: agents, wakes and
149// owner notices (D-09, ledger.ts loopEvent), one per transition: an entry whose event would say
150// just what its key's last one said is not logged again. A wake's turn taking its id, its
151// reminder going out, and a turn that starts inside its submit (so turn.start moves the entry
152// before the executor finishes it) each change the entry but not its event (run 2, #536). A
153// failed log is noted, never retried.
154export async function logLoop(env: Pick<ActEnv, 'io' | 'rt' | 'commands' | 'problems' | 'live'>, entries: readonly LedgerEntry[]): Promise<void> {
155  const cmd = commandOf(env.io, env.rt, env.commands)
156  const logged = (env.live.logged ??= new Map())
157  for (const entry of entries) {
158    let argv = loopEvent(entry)
159    if (argv === null) continue
160    const said = JSON.stringify(argv)
161    if (logged.get(entry.key) === said) continue
162    logged.set(entry.key, said)
163    // an agent step's end carries its transcript's token totals, read once: only here, where the
164    // end is new (#657); no reading, no problem, where the runtime knows no config dir
165    if (entry.kind === 'agent-step' && entry.status !== 'running' && entry.agentId !== undefined && env.rt.configDir !== undefined && env.rt.sessionCwd !== undefined) {
166      const read = await readStepTokens(env.io, cmd, { configDir: env.rt.configDir, sessionCwd: env.rt.sessionCwd, session: entry.session ?? '', agentId: entry.agentId })
167      if (read.problem !== null) env.problems.push(clip(`loop event ${entry.key}: ${read.problem}`))
168      argv = loopEvent(entry, read.fields) ?? argv
169    }
170    // an ended task or tell carries the what-if cost of its window in its submitting session
171    if ((entry.kind === 'task' || entry.kind === 'tell') && entry.status !== 'running' && entry.session !== undefined && entry.session !== '' && entry.endedAt !== null && env.rt.configDir !== undefined && env.rt.sessionCwd !== undefined) {
172      const w = await readWakeCost(cmd, { configDir: env.rt.configDir, sessionCwd: env.rt.sessionCwd, session: entry.session }, entry.startedAt, entry.endedAt)
173      if (w.problem !== null) env.problems.push(clip(`loop event ${entry.key}: ${w.problem}`))
174      argv = loopEvent(entry, { ...NO_TOKENS, cost_usd: w.cost }) ?? argv
175    }
176    try {
177      const r = await cmd(argv, { timeoutMs: EVENT_TIMEOUT_MS })
178      if (r.exitCode !== 0) env.problems.push(clip(`loop event ${entry.key}: exit ${r.exitCode}`))
179    } catch (err) {
180      env.problems.push(clip(`loop event ${entry.key}: ${message(err)}`))
181    }
182  }
183  // a key the ledger no longer holds (pruned, or a notice a retry cleared) is forgotten
184  const held = new Set(env.live.ledger.map(e => e.key))
185  for (const key of logged.keys()) if (!held.has(key)) logged.delete(key)
186}
187
188// --- one pass's actions ------------------------------------------------------------------------
189
190// One action's result, for the decision log (v2 SPEC 13.12); at: when it started, for the trace (#552),
191// absent for an action held before it started.
192// off: the action's command runs off the pass (act-off.ts); ms is then its launch time.
193export type ActOutcome = { key: string; kind: ActionKind; status: Exec['status']; ms: Ms; summary: string; at?: Ms; off?: true }
194
195export type ActReport = {
196  outcomes: ActOutcome[]
197  // an executor met a GitHub rate limit: register sets the backoff (v2 SPEC 13.10 item 2)
198  rateLimited: boolean
199  // the kill switch stopped the pass between actions: register shows the loop off at once
200  killed: boolean
201}
202
203// runActions: plan's actions in plan's order (finish in-flight work before starting new work).
204// The kill switch is asked before each action but the title (bookkeeping only): an action
205// already running finishes, and once the switch is seen every action left is skipped (#557).
206export async function runActions(env: ActEnv, state: State, actions: readonly Action[]): Promise<ActReport> {
207  const report: ActReport = { outcomes: [], rateLimited: false, killed: false }
208  for (const action of actions) {
209    if (!report.killed && action.kind !== 'title' && (await env.killed())) report.killed = true
210    if (report.killed) {
211      report.outcomes.push({ key: action.key, kind: action.kind, status: 'skipped', ms: 0, summary: 'kill switch' })
212      continue
213    }
214    if (!(await env.holds())) {
215      report.outcomes.push({ key: action.key, kind: action.kind, status: 'skipped', ms: 0, summary: 'held: the act lock is no longer this session\'s' })
216      continue
217    }
218    if (report.rateLimited && GITHUB_V2.includes(action.kind)) {
219      report.outcomes.push({ key: action.key, kind: action.kind, status: 'skipped', ms: 0, summary: 'held: GitHub rate limit met this pass' })
220      continue
221    }
222    const out = await actOne(env, state, action)
223    report.outcomes.push(out.outcome)
224    if (out.exec.status === 'failed' && out.exec.rateLimited === true) report.rateLimited = true
225  }
226  return report
227}
228
229// actOne: one action through the ledger (v2 SPEC 13.7): start (a retry keeps the key and counts an
230// attempt), the usage pre-check for start, develop and drive (a refusal puts the entry back as
231// it stood, v2 SPEC 13.10 item 7), the running entry saved, the executor, then finish with its Exec and
232// { config, prev }. The title is compared, not keyed (v2 SPEC 13.5.8 O1), so it runs without an entry.
233export async function actOne(env: ActEnv, state: State, action: Action): Promise<{ outcome: ActOutcome; exec: Exec }> {
234  const t0 = await env.io.now()
235  const done = async (exec: Exec) => {
236    const ms = (await env.io.now()) - t0
237    return { exec, outcome: { key: action.key, kind: action.kind, status: exec.status, ms, summary: clip(exec.summary), at: t0, ...(action.kind === 'title' && exec.status === 'running' ? { off: true as const } : {}) } }
238  }
239  if (action.kind === 'title') return done(await dispatch(ctxOf(env, state, start([], action, t0).entry), action))
240
241  const s = start(env.live.ledger, action, t0, env.session)
242  // no loop event yet: the start and its finish are one transition, logged once
243  env.live.ledger = s.ledger
244  const opts = { config: env.rt.config, prev: s.prev }
245  const refused = await preCheck({ usage: env.io.usage, now: env.io.now }, action, env.rt.config, state.control.usageOverride)
246  if (refused !== null) {
247    const now = await env.io.now()
248    env.live.ledger = finish(env.live.ledger, action.key, refused, now, opts)
249    await env.save()
250    return done(refused)
251  }
252  // the entry is in the store, running, before anything happens: a reload, a crash or a restart
253  // (restart-self ends the session) mid-action finds it and marks it lost, so its attempt counts
254  // and its rule re-derives what to do (v2 SPEC 13.7.5). A ledger that cannot be saved starts nothing.
255  if (!(await env.save())) {
256    const held: Exec = { status: 'skipped', summary: 'held: the ledger was not saved, so nothing starts' }
257    env.live.ledger = finish(env.live.ledger, action.key, held, await env.io.now(), opts)
258    return done(held)
259  }
260  if (env.offPass !== undefined && isOffPass(action.kind)) {
261    // the command runs on, untraced, after the pass: its completion lands in the hook queue
262    const off = env.offPass
263    const ctx = ctxOf({ ...env, io: off.io, commands: [] }, state, s.entry)
264    await launchOff(off, () => env.io.now(), () => dispatch(ctx, action), { key: action.key, kind: action.kind, started: s.entry, ...opts })
265    const exec: Exec = { status: 'running', summary: 'running off the pass' }
266    const done = await env.io.now()
267    return { exec, outcome: { key: action.key, kind: action.kind, status: 'running', ms: done - t0, summary: exec.summary, at: t0, off: true } }
268  }
269  const exec = await dispatch(ctxOf(env, state, s.entry), action)
270  await record(env, action.key, s.entry, exec, opts)
271  return done(exec)
272}
273
274// record: finish the attempt with the executor's Exec, saved before its loop event, unless a hook
275// already ended it: a wake answered (or a tell delivered) before its submit returned stays
276// answered, and an entry a later attempt or a hook replaced is left alone (v2 SPEC 13.8.2, wake.ts
277// onTurnStart); the hook saved it.
278async function record(
279  env: ActEnv,
280  key: string,
281  started: LedgerEntry,
282  exec: Exec,
283  opts: { config: Runtime['config']; prev: LedgerEntry | null },
284): Promise<void> {
285  const now = await env.io.now()
286  const current = sameAttempt(env.live.ledger, started)
287  if (current === undefined) return
288  if (exec.status === 'running' && current.status !== 'running') return
289  const moved = transition(env.live, l => finish(l, key, exec, now, opts))
290  await env.save()
291  await logLoop(env, moved)
292}
293
294// --- notices from outside plan (v2 SPEC 13.9.2, 13.11.2, 13.11.4) --------------------------------------------
295
296// openWake: a judge, task or tell that is still running. Only one wake is open at a time (O2).
297export function openWake(ledger: readonly LedgerEntry[]): LedgerEntry | undefined {
298  return ledger.find(e => e.status === 'running' && WAKES.includes(e.kind))
299}
300
301// sendNotice: a tell that comes from outside plan (a rail, the ping breaker, failing passes) goes
302// out through the wake executor under its own key, once, and only while no wake is open: a key
303// the ledger holds was sent, unless it was lost (the engine dropped it before its turn); an open
304// wake keeps it waiting (the caller keeps it pending), as does the kill switch.
305export async function sendNotice(env: ActEnv, state: State, tell: Action): Promise<'sent' | 'waiting' | 'failed'> {
306  if (env.live.ledger.some(e => e.key === tell.key && e.status !== 'lost')) return 'sent'
307  if (openWake(env.live.ledger) !== undefined || (await env.killed())) return 'waiting'
308  const { exec } = await actOne(env, state, tell)
309  return exec.status === 'running' || exec.status === 'done' ? 'sent' : 'failed'
310}
311
312// passErrorTell: three passes in a row threw (v2 SPEC 13.10 item 9): the owner hears of it once per spell.
313export function passErrorTell(since: Ms, passes: number, error: string): Action {
314  return {
315    kind: 'tell',
316    wake: 'pass-error',
317    key: `tell:pass-error:${since}`,
318    class: 'owner',
319    rule: 'O2',
320    reason: 'tell pass-error',
321    issue: null,
322    fields: { passes: String(passes) },
323    context: [`last error: ${error.replace(/\s+/g, ' ').slice(0, 300)}`],
324  }
325}
326
327// --- what a reload and the agent list prove (v2 SPEC 13.3.3, 13.7.5, 13.10 item 4) --------------------------------
328
329export type ListedAgent = { id: string; status: AgentStatus }
330
331// How long an agent sent the repair message counts as at work while the list still shows its
332// turn ended, idle or completed (reconcilable): the engine resumes it from its transcript (#548),
333// and when the list shows that is not proven. Past it, the usual one pass of grace, then lost.
334export const REPAIR_GRACE_MS = 5 * 60_000
335
336// reconcilable: the agent list as reconcileAgents should judge it. An agent listed idle has ended
337// its turn as one listed completed has (foundation.ts turnEnded, #560), and each rule here reads them
338// alike. An agent whose answer is being handled counts as running, listed or not, so a pass in
339// between never marks it lost: that covers an agent whose repair message is on its way, since
340// agentAnswered holds it in `answering` until the engine answers the send. So does one whose
341// turn ended within REPAIR_GRACE_MS of its repair message being delivered (repairing: when each
342// went out, until its next turn.complete), for the loop awaits its reply; an agent first listed
343// with its turn ended counts as running for that pass, since its turn.complete may still be on
344// its way (seen: when each id was first so listed, idle then completed being one sighting). seen
345// and repairing are updated in place. So does a gated writer whose answer is held for its stop
346// gate line (gateHeld: since when), within holdMs, listed or not: the hold, not the list, says
347// when its step ends.
348export function reconcilable(
349  agents: readonly ListedAgent[],
350  answering: ReadonlySet<string>,
351  seen: Map<string, Ms>,
352  now: Ms,
353  repairing: Map<string, Ms>,
354  gateHeld: Map<string, Ms> = new Map(),
355  holdMs: Ms = 0,
356): ListedAgent[] {
357  for (const [id, at] of [...repairing]) if (now - at > REPAIR_GRACE_MS) repairing.delete(id)
358  // a hold past its bound counts for nothing here but stays in the map: gateRule (steps.ts) owns its
359  // start and takes the answer once the bound runs out, which a deleted hold would restart
360  const holding = (id: string): boolean => {
361    const at = gateHeld.get(id)
362    return at !== undefined && now - at <= holdMs
363  }
364  const out = agents.map(a => {
365    if (answering.has(a.id) || holding(a.id)) return { id: a.id, status: 'running' as AgentStatus }
366    if (!turnEnded(a.status)) return a
367    if (repairing.has(a.id)) return { id: a.id, status: 'running' as AgentStatus }
368    const first = seen.get(a.id)
369    if (first === undefined) seen.set(a.id, now)
370    return first === undefined || first === now ? { id: a.id, status: 'running' as AgentStatus } : a
371  })
372  for (const id of [...answering, ...[...gateHeld.keys()].filter(holding)]) if (!agents.some(a => a.id === id) && !out.some(a => a.id === id)) out.push({ id, status: 'running' })
373  for (const id of [...seen.keys()]) if (!agents.some(a => a.id === id && turnEnded(a.status))) seen.delete(id)
374  return out
375}
376
377// updateDone: rule H4's restart for this update ran and the workspace came back: its entry is
378// lost (the session restarted under it), or done before this module loaded. dev-restart-self
379// returns once Coder accepts the build, minutes before the container is replaced, so a restart
380// this module saw end is not done yet: the drain holds until the new session loads (D-15).
381// control.updateDue is then cleared, or the loop would drain forever. A failed restart ends the
382// update instead (driver-pass-log failUpdate), and the owner's notice lasts (rules-fleet restartTells).
383export function updateDone(ledger: readonly LedgerEntry[], control: Control, loadedAt: Ms): boolean {
384  const due = control.updateDue
385  if (due === null) return false
386  const restart = ledger.find(e => e.key === `restart:${due.at}`)
387  return restart?.status === 'lost' || (restart?.status === 'done' && (restart.endedAt ?? loadedAt) < loadedAt)
388}
389
390// --- one act-mode pass, from what observe read (v2 SPEC 13.2) --------------------------------------------
391
392// What the hooks between passes share with the pass: the agents whose answer is being handled,
393// when each agent was first listed with its turn ended (idle or completed), and when each was
394// sent its repair message (reconcilable), and since when each gated writer's answer has waited for
395// its stop gate line (steps-gate.ts).
396export type Between = { answering: Set<string>; completedSeen: Map<string, Ms>; repairing: Map<string, Ms>; gateHeld: Map<string, Ms> }
397
398// The pass's agent list: only a read that worked may mark agents lost.
399export type Listed = { ok: boolean; agents: ListedAgent[] }
400
401// planned: when plan handed its actions over and how long it took (performance.now()), for the
402// trace (#552)
403export type Acted = { state: State; result: PlanResult; report: ActReport; planned: { at: Ms; ms: number } }
404
405// planPass: the planner's plan (v2 SPEC 2.3).
406export function planPass(state: State, config: Config): PlanResult {
407  return planV2(state, config)
408}
409
410// finishAsRead: an answer read for an entry, applied only while the entry still runs as it was
411// read (its turn.complete may have finished it during the read); the entries it moved.
412function finishAsRead(env: ActEnv, was: LedgerEntry, exec: Exec, now: Ms): LedgerEntry[] {
413  const current = env.live.ledger.find(e => e.key === was.key)
414  if (current?.status !== 'running' || current.agentId !== was.agentId || current.startedAt !== was.startedAt) return []
415  return transition(env.live, l => finish(l, was.key, exec, now, { config: env.rt.config }))
416}
417
418// answeredBeforeLost: the agent entries the agent list would mark lost (gone from it, or its turn
419// ended with no answer read) whose agent recorded an answer with the answer script that passes its
420// checks (#561): each is finished with that answer, as its turn.complete would have finished it
421// (act-agents.ts scriptAnswered). An entry its turn.complete finished during the read is left
422// alone.
423async function answeredBeforeLost(env: ActEnv, state: State, agents: readonly ListedAgent[], now: Ms, between: Between): Promise<LedgerEntry[]> {
424  const before = env.live.ledger
425  // reconcileAgents keeps the ledger's order, entry for entry
426  const reconciled = reconcileAgents(before, agents, now)
427  const lost = before.filter((e, i) => e.status === 'running' && reconciled[i]?.status === 'lost')
428  const moved: LedgerEntry[] = []
429  for (const was of lost) {
430    // a gated writer with no settling gate line is held (gateHeld), not lost: reconcilable then counts it
431    const exec = await stepRecorded(ctxOf(env, state, was), was, true, undefined, between.gateHeld)
432    if (exec !== null) moved.push(...finishAsRead(env, was, exec, now))
433  }
434  return moved
435}
436
437// actPass: the act-mode pass once the rails passed and observe read the factory: what the agent
438// list proves (v2 SPEC 13.3.3, 13.10 item 4) and wakes past their timeout (v2 SPEC 13.8.2) go into the ledger first,
439// then plan reads the state with that ledger, and its actions run in plan's order.
440export async function actPass(env: ActEnv, observed: State, listed: Listed, between: Between): Promise<Acted> {
441  const now = observed.now
442  const moved: LedgerEntry[] = []
443  if (listed.ok) {
444    const holdMs = gateHoldMs(env.rt.config)
445    const of = () => reconcilable(listed.agents, between.answering, between.completedSeen, now, between.repairing, between.gateHeld, holdMs)
446    moved.push(...(await answeredBeforeLost(env, observed, of(), now, between)))
447    // an entry that ended, or whose agent is gone from the ledger, holds nothing
448    for (const id of [...between.gateHeld.keys()]) if (!env.live.ledger.some(e => e.agentId === id && e.status === 'running')) between.gateHeld.delete(id)
449    const agents = of()
450    moved.push(...transition(env.live, l => reconcileAgents(l, agents, now)))
451  }
452  for (const u of expireWakes(env.live.ledger, now, env.rt.config)) moved.push(...transition(env.live, l => finish(l, u.key, u, now)))
453  // an off-pass command that outlived its bound is timed out; its completion, if it ever comes, is dropped
454  for (const u of offPassExpired(env.live.ledger, now)) {
455    env.problems.push(`${u.key}: ${u.summary}`)
456    moved.push(...transition(env.live, l => finish(l, u.key, u, now)))
457  }
458  // a recorded answer ends its step when read (v2 SPEC 10.8)
459  for (const r of await stepAnswers(env.live.ledger, e => ctxOf(env, observed, e), undefined, between.gateHeld)) moved.push(...finishAsRead(env, r.entry, r.exec, now))
460  if (moved.length > 0) {
461    await env.save()
462    await logLoop(env, moved)
463  }
464  const state = { ...observed, ledger: env.live.ledger }
465  const from = performance.now()
466  const result = planPass(state, env.rt.config)
467  const planned = { ms: performance.now() - from, at: await env.io.now() }
468  const report = await runActions(env, state, result.actions)
469  return { state, result, report, planned }
470}
471
472// --- small helpers --------------------------------------------------------------------------------
473
474export function clip(text: string): string {
475  return text.length > SUMMARY_MAX ? `${text.slice(0, SUMMARY_MAX - 3)}...` : text
476}
477
478function message(err: unknown): string {
479  return err instanceof Error ? err.message : String(err)
480}
481
hooks/act-off.ts 103 lines
1// Actions that run off the pass (v2 SPEC 13.2, 13.7.5): a long command whose result nothing else in
2// the pass waits for starts inside the pass, with its running entry saved, and ends in the hook
3// queue between passes. The pass does not wait for it, so a 40 s sweep no longer makes a 40 s pass.
4// This module is free of the driver: act.ts hands it the pieces and register.ts' driver supplies the
5// completion's place (the hook queue) through ActEnv.offPass.
6import { CLI_TIMEOUT_MS } from './act-cli'
7import { MERGE_BOUND_MS } from './v2/act-queue'
8import type { ActEnv } from './act'
9import type { Exec } from './exec'
10import { finish } from './ledger'
11import type { Completion } from './ledger'
12import type { ActionKind, LedgerEntry, Ms } from './types'
13
14// The one list of kinds that run off the pass. A later kind joins by being added here.
15export const OFF_PASS: readonly ActionKind[] = ['heartbeat', 'sweep', 'queue-merge']
16
17// The engine ends a command at its own timeout (act-cli.ts CLI_TIMEOUT_MS, NO_EXIT) and offers no
18// kill handle, so the bound a pass marks is that timeout plus this margin, which covers the
19// command's exit and the hook queue before its completion lands.
20export const OFF_PASS_MARGIN_MS = 60_000
21
22// offPassBoundMs: how long an off-pass command may run before the margin: heartbeat and sweep end at
23// their CLI timeout; a merge at the executor's longest path (the merge command, then the PR read).
24export function offPassBoundMs(kind: ActionKind): number {
25  if (kind === 'queue-merge') return MERGE_BOUND_MS
26  return CLI_TIMEOUT_MS[kind as keyof typeof CLI_TIMEOUT_MS]
27}
28
29export function isOffPass(kind: ActionKind): boolean {
30  return OFF_PASS.includes(kind)
31}
32
33// One off-pass command that ended: what the completion applies, and what the trace reports.
34export type OffDone = {
35  key: string
36  kind: ActionKind
37  // the entry as the pass started it: the attempt the completion must still find
38  started: LedgerEntry
39  exec: Exec
40  // the command's own time, and when it ended
41  ms: Ms
42  endedAt: Ms
43  config: ActEnv['rt']['config']
44  prev: LedgerEntry | null
45}
46
47// What the driver gives an act step that may run a command off the pass.
48export type OffPass = {
49  // the engine calls of a command that outlives the pass: not the pass's traced io, whose tracer ended
50  io: ActEnv['io']
51  // the command ended: queue its completion (the hook queue); never awaited by the pass
52  done: (done: OffDone) => void
53}
54
55// sameAttempt: the ledger still holds the attempt `started` began (a retry keeps the key, not the
56// start), as a result applied later must find it.
57export function sameAttempt(ledger: readonly LedgerEntry[], started: LedgerEntry): LedgerEntry | undefined {
58  const current = ledger.find(e => e.key === started.key)
59  return current !== undefined && current.startedAt === started.startedAt && current.attempts === started.attempts ? current : undefined
60}
61
62// launchOff: start the command without waiting for it; its Exec and timing go to off.done when it
63// ends. `run` never rejects (act.ts dispatch turns a throw into a failed Exec); a rejection is
64// still caught, so no completion is lost silently.
65export async function launchOff(
66  off: OffPass,
67  now: () => Promise<Ms>,
68  run: () => Promise<Exec>,
69  at: Pick<OffDone, 'key' | 'kind' | 'started' | 'config' | 'prev'>,
70): Promise<void> {
71  const t0 = await now()
72  const finished = async (exec: Exec) => {
73    const endedAt = await now()
74    off.done({ ...at, exec, ms: endedAt - t0, endedAt })
75  }
76  void run().then(finished, (err: unknown) => finished({ status: 'failed', summary: `${at.kind}: ${err instanceof Error ? err.message : String(err)}`.slice(0, 200) })).catch(() => undefined)
77}
78
79// offPassExpired: the running off-pass entries that outlived their command's timeout and the
80// margin: each is timed out, and a completion that arrives later finds it ended and is dropped.
81export function offPassExpired(ledger: readonly LedgerEntry[], now: Ms): (Completion & { key: string })[] {
82  const out: (Completion & { key: string })[] = []
83  for (const e of ledger) {
84    if (e.status !== 'running' || !isOffPass(e.kind)) continue
85    const limit = offPassBoundMs(e.kind) + OFF_PASS_MARGIN_MS
86    if (now - e.startedAt <= limit) continue
87    out.push({ key: e.key, status: 'timed-out', summary: `timed out: no completion within ${Math.round(limit / 1000)} s` })
88  }
89  return out
90}
91
92// completeOff: apply a finished off-pass command to the live ledger, the way the inline run does
93// (act.ts record): only while the entry is still that attempt and still running, then saved. No
94// loop event: the off-pass kinds log none (ledger.ts LOOP_KINDS; act-off.test.ts checks it).
95// False when the completion was dropped: the attempt had ended (timed out, lost, retried) or is gone.
96export async function completeOff(env: ActEnv, done: OffDone): Promise<boolean> {
97  const current = sameAttempt(env.live.ledger, done.started)
98  if (current === undefined || current.status !== 'running') return false
99  env.live.ledger = finish(env.live.ledger, done.key, done.exec, done.endedAt, { config: done.config, prev: done.prev })
100  await env.save()
101  return true
102}
103
hooks/act-between.ts 202 lines
1// Between passes: the hooks that feed the ledger (v2 SPEC 13.2, 13.8.2, 13.10 item 4). What an agent's answer, a
2// wake's turn, the wake answer tool and `/factory retry` do to the live ledger. act.ts holds the
3// pass and the executors; this module reads them and is read by driver-between.ts alone, so nothing
4// here is imported back by act.ts.
5import { clip, ctxOf, logLoop, transition } from './act'
6import type { ActEnv, Between } from './act'
7import type { AgentAnswer } from './exec'
8import { finish, retryIssue } from './ledger'
9import type { LedgerEntry, State } from './types'
10import { intakeFinish } from './v2/act-intake'
11import { stepAnswered } from './v2/steps'
12import { answerTool, onTurnComplete, onTurnStart } from './wake'
13import type { TurnEnd } from './wake'
14
15// The one repair message to an agent of the loop, of the type it runs as (a step's agent type,
16// plugin:name): null once delivered, else why not, in the engine's own words.
17export type Repair = (agentId: string, text: string, type: `${string}:${string}`) => Promise<string | null>
18
19// What an agent's answer did: 'applied' (its entry finished; repaired when a repair message went
20// out before it), 'repair' (unreadable, so the agent was asked once more), 'recorded' (its tool
21// already answered), 'held' (a gated writer's answer waits for its stop gate line, the entry
22// running on), 'dropped' or 'not ours'. key: its entry; undelivered: why its repair message
23// was not delivered, whole, for the decision log (the entry's summary keeps a clipped copy, #559).
24export type Answered = {
25  result: 'applied' | 'repair' | 'held' | 'recorded' | 'dropped' | 'not ours'
26  why?: string
27  key?: string
28  repaired?: boolean
29  undelivered?: string
30}
31
32// agentAnswered: an agent step of the loop finished (its turn.complete): its answer is read by
33// steps.ts (the file it recorded with the answer script) and its entry finished. 'applied' asks
34// for a pass. An agent the ledger never held is 'not ours'; an answer for an entry that no longer
35// runs (a stop timed it out, a retry replaced it) is logged and dropped, never applied. An answer
36// that does not read first gets one repair message to the same agent, naming what was wrong and
37// asking again (#548, #561): the entry runs on with its attempt unspent, and only an answer still
38// unreadable after it, or a message that could not be delivered, fails the attempt as before.
39export async function agentAnswered(
40  env: ActEnv,
41  state: State,
42  answer: AgentAnswer,
43  between: Between,
44  repair: Repair = async () => 'the loop sends no messages from here',
45): Promise<Answered> {
46  const id = answer.agentId
47  const entry = env.live.ledger.find(e => e.agentId === id && e.kind === 'agent-step')
48  if (entry === undefined) return { result: 'not ours' }
49  if (entry.status === 'done') return { result: 'recorded', key: entry.key }
50  if (entry.status !== 'running') return { result: 'dropped', why: `late answer for ${entry.key} (${entry.status})` }
51  between.answering.add(id)
52  between.repairing.delete(id)
53  try {
54    // a v2 agent step's answer is read by steps.ts, and is never interim (v2 SPEC 10.8)
55    const step = await stepAnswered(ctxOf(env, state, entry), entry, answer, undefined, between.gateHeld, env.live.ledger)
56    // a gated writer's turn ended before its stop gate line: the entry runs on until a pass finds it
57    if (step.held === true) return { result: 'held', key: entry.key }
58    let exec = step.exec
59    const ours = (e: LedgerEntry | undefined): e is LedgerEntry => e !== undefined && e.agentId === id && e.startedAt === entry.startedAt
60    const still = () => {
61      const current = env.live.ledger.find(e => e.key === entry.key)
62      return ours(current) && current.status === 'running' ? current : null
63    }
64    // the attempt no longer runs: a stop or a retry ended it
65    const ended = (): Answered => {
66      const current = env.live.ledger.find(e => e.key === entry.key)
67      return ours(current) && current.status === 'done' ? { result: 'recorded', key: entry.key } : { result: 'dropped', why: `answer for ${entry.key} came after the entry ended` }
68    }
69    if (still() === null) return ended()
70    const at = await env.io.now()
71    const current = still()
72    if (current === null) return ended()
73    const repaired = current.reminded === true
74    let refused: string | undefined
75    if (step.repair !== null && !repaired) {
76      const problem = step.problem ?? 'no machine line'
77      // the repair is on the entry before it goes out, so a reload never sends a second one
78      const marked = transition(env.live, l => finish(l, entry.key, { status: 'running', reminded: true }, at))
79      await env.save()
80      await logLoop(env, marked)
81      // a v2 step's own repair asks for the script again
82      const undelivered = await repair(id, step.repair, step.subagentType)
83      if (undelivered === null) {
84        // listed idle or completed until the message resumes it, which the list may show late: the
85        // passes take it as at work for a while, then count that listing afresh
86        between.completedSeen.delete(id)
87        between.repairing.set(id, at)
88        return { result: 'repair', why: problem, key: entry.key }
89      }
90      refused = undelivered
91      exec = { ...exec, summary: clip(`${exec.summary}; the repair message was not delivered: ${undelivered}`) }
92    }
93    const now = await env.io.now()
94    if (still() === null) return ended()
95    const moved = transition(env.live, l => finish(l, entry.key, exec, now, { config: env.rt.config }))
96    await env.save()
97    await logLoop(env, moved)
98    const applied: Answered = { result: 'applied', key: entry.key, repaired }
99    if (refused !== undefined) applied.undelivered = refused
100    return applied
101  } finally {
102    between.answering.delete(id)
103  }
104}
105
106// intakeAnswered: the turn of an intake reader (rule I1, v2/act-intake.ts) ended: its answer is checked, the
107// try stored and its labels set (intakeFinish), and its entry finished. null when no running `intake-stamp`
108// entry of the ledger has this agent, so the turn is not ours (agentAnswered takes it). The reader has no
109// answer script and gets no repair message: whatever it ended with is the outcome.
110export async function intakeAnswered(env: ActEnv, state: State, answer: AgentAnswer): Promise<Answered | null> {
111  const entry = env.live.ledger.find(e => e.kind === 'intake-stamp' && e.agentId === answer.agentId && e.status === 'running')
112  if (entry === undefined) return null
113  const exec = await intakeFinish(ctxOf(env, state, entry), entry, answer)
114  const now = await env.io.now()
115  const current = env.live.ledger.find(e => e.key === entry.key)
116  // a settle or a retry ended the attempt while the answer was read
117  if (current === undefined || current.agentId !== entry.agentId || current.startedAt !== entry.startedAt || current.status !== 'running') {
118    return { result: 'dropped', why: `answer for ${entry.key} came after the entry ended`, key: entry.key }
119  }
120  const moved = transition(env.live, l => finish(l, entry.key, exec, now, { config: env.rt.config }))
121  await env.save()
122  await logLoop(env, moved)
123  return { result: 'applied', key: entry.key }
124}
125
126// The refusal of a tool call that could not be decided in time (#558): the agent answers in text.
127export const TOOL_LATE = 'Not recorded: the factory loop could not check this answer in time; reply with your text lines instead.'
128
129// Asked just before a tool call changes the ledger: false once the caller has answered the call
130// without it (register.ts bounded), and then nothing changes.
131export type Claim = () => boolean
132
133// keep: what follows a transition a hook made at once in the live ledger (#558): the ledger
134// saved, then the moved entries' loop events.
135export async function keep(env: ActEnv, moved: readonly LedgerEntry[]): Promise<void> {
136  if (moved.length === 0) return
137  await env.save()
138  await logLoop(env, moved)
139}
140
141const WAKE_HEAD = /^(JUDGE|TASK|TELL) /m
142
143// wakeStarted: a turn that opens with a wake's first line is that wake's turn (wake.ts
144// onTurnStart). A frame the engine puts before a plugin's prompt is skipped to that line.
145export async function wakeStarted(env: ActEnv, said: string, turnId: string): Promise<boolean> {
146  const at = said.search(WAKE_HEAD)
147  if (at < 0) return false
148  const now = await env.io.now()
149  const u = onTurnStart(env.live.ledger, said.slice(at), turnId)
150  if (u === null) return false
151  const moved = transition(env.live, l => finish(l, u.key, u, now))
152  await env.save()
153  await logLoop(env, moved)
154  return true
155}
156
157// wakeEnded: a main-loop turn ended (wake.ts onTurnComplete): its ANSWER blocks close their
158// wakes, a tell's own turn delivers it, an unanswered wake gets its one reminder. The caller
159// submits the prompts (never awaiting them inside the turn's own hook), logs the problems, and
160// pings when a wake moved.
161export async function wakeEnded(env: ActEnv, turn: TurnEnd): Promise<{ moved: boolean; prompts: string[]; problems: string[] }> {
162  const now = await env.io.now()
163  const out = onTurnComplete(env.live.ledger, turn, env.rt.repo)
164  const moved = out.updates.flatMap(u => transition(env.live, l => finish(l, u.key, u, now)))
165  if (moved.length > 0) {
166    await env.save()
167    await logLoop(env, moved)
168  }
169  return { moved: out.updates.length > 0, prompts: out.prompts, problems: out.problems }
170}
171
172// wakeAnswered: mcp__factory-loop__answer, checked as the ANSWER block is (wake.ts answerTool)
173// and recorded in the live ledger at once, with no await between the check and the change, as an
174// agent's tool was (#558); `moved` asks for keep, once the call has its answer. claim: asked
175// just before the ledger changes.
176export async function wakeAnswered(
177  env: ActEnv,
178  input: unknown,
179  agentId: string | undefined,
180  claim: Claim = () => true,
181): Promise<{ ok: boolean; text: string; moved: LedgerEntry[] }> {
182  const now = await env.io.now()
183  const r = answerTool(env.live.ledger, input, env.rt.repo, agentId === undefined ? {} : { agentId })
184  const update = r.update
185  if (update === null) return { ok: r.ok, text: r.text, moved: [] }
186  if (!claim()) return { ok: false, text: TOOL_LATE, moved: [] }
187  return { ok: r.ok, text: r.text, moved: transition(env.live, l => finish(l, update.key, update, now)) }
188}
189
190// retried: `/factory retry <N>` clears the issue's exhausted entries in the live ledger at once
191// (D-38, ledger.ts retryIssue): the keys it cleared, and the entries it moved, for keep once the
192// op has its answer (#558).
193export function retried(env: Pick<ActEnv, 'live' | 'rt'>, issue: number): { cleared: string[]; moved: LedgerEntry[] } {
194  let cleared: string[] = []
195  const moved = transition(env.live, l => {
196    const r = retryIssue(l, issue, env.rt.config)
197    cleared = r.cleared
198    return r.ledger
199  })
200  return { cleared, moved }
201}
202
hooks/observe.ts 534 lines
1// observe: run the read-only commands of v2 SPEC 13.3.3 and assemble the State plan takes. Thin on
2// purpose: every output goes straight to a pure parser (parse.ts, derive.ts) and buildState.
3// Cadences (config queueEveryMs, githubEveryMs, usageEveryMs, milestoneEveryMs) keep GitHub
4// reads well under the rate limit; a failed source keeps its last value with its old time, so
5// plan can see how stale it is. Every command runs from the main checkout with the runtime's
6// environment (rt.env), which in observe mode sends its event writes to the sink (v2 SPEC 13.11.1).
7// v2/observe.ts reads what v2 adds (v2 SPEC 2.4); the loop reads no pipeline runs and infers no
8// slot's issue from its reflog.
9import { EMPTY_CONTROL, controlFrom } from './config'
10import { deriveLedger, factsOf } from './derive'
11import type { FactoryEvent } from './derive'
12import { rateLimited } from './exec'
13import { choose } from './ledger'
14import { readIssues } from './observe-github'
15import { readQueue } from './observe-queue'
16import { newestTag, readMilestone, repoTags, tagRepos, waitsOnTag } from './observe-milestone'
17import type { LedgerSource } from './ledger'
18import {
19  parseBrief,
20  parseCheckout,
21  parseCsv,
22  derivedSkipError,
23  factoryStateError,
24  parseFactoryState,
25  parsePool,
26  parseSubIssues,
27  parseUsage,
28} from './parse'
29import type { Factory } from './parse'
30import { spendEventData, tallyStep, unavailableSpend, whatIfEnv, whatIfStep } from './spend'
31import type { ApiKeySettings, Tally } from './spend'
32import { listedLive } from './foundation'
33import { BUSY_STATES, LIVE_STATES } from './factory-state-map'
34import { TRACKER_DEPTH, buildState } from './state'
35import type { GithubIssue } from './state'
36import type { Checkout, Config, Control, LedgerEntry, Milestone, Pool, ReleaseInfo, Source, SourceName, State, Usage } from './types'
37import { exitFail, readFacts } from './v2/sources-facts'
38import type { FactsShadow } from './v2/sources-facts'
39import { emptyV2Cache, lastEnded, observeV2, readDue, readOrder } from './v2/observe'
40import type { V2Cache, V2Stored } from './v2/observe'
41import type { HeadSeen } from './v2/types'
42
43const GITHUB_READS_PER_PASS = 12
44const EVENT_DAYS = 3
45// a ledger rebuilt after a lost store reads a week of events: holds older than the facts
46// window (a pending decision, an escalation) must survive it, and entries are kept 7 days
47export const REBUILD_DAYS = 7
48// how long GitHub reads wait after a rate limit (v2 SPEC 13.10 item 2)
49export const GITHUB_BACKOFF_MS = 15 * 60_000
50
51// Runtime: what one pass runs as, from the plugin options and both settings files (v2 SPEC 13.4.1).
52export type Runtime = {
53  mode: 'off' | 'observe' | 'act'
54  repo: string
55  device: string
56  runSource: 'local' | 'events'
57  poolSize: number
58  cwd: string
59  loopDir: string
60  // where the step agents' transcripts are (v2/step-tokens.ts): the config dir and the cwd of this session, whose
61  // munged name is the project folder; absent in a test's Runtime: no token reading
62  configDir?: string
63  sessionCwd?: string
64  // this session and process, as v2's workspace rail checks the companion's handshake (v2 SPEC 10.9)
65  workspace?: { session: string; process?: string }
66  // the observe-mode event sink (v2 SPEC 13.11.1), null when acting; env carries it
67  sink: string | null
68  // the base environment of every command the loop runs, observe and act alike:
69  // CALLUM_FLOW_REPO, CALLUM_EVENTS_DIR=<sink> when not acting, and PATH with the workspace
70  // config's binDir in front (a testbed runs the branch's own CLIs before a release)
71  env: Record<string, string>
72  // where queue-watch.sh and usage-check.sh live (workspace config toolsDir)
73  toolsDir: string
74  // the plugin's own directory ($.plugin.root), where the answer script lives (#561)
75  pluginRoot: string
76  config: Config
77  // API-key mode (DEV_CLAUDE_AUTH=api-key): the budget settings from the environment, unparsed (spend.ts);
78  // absent: subscription mode, and in a test's Runtime
79  apiKey?: ApiKeySettings
80  // the container's CPU count (read once per process) and the stop gates the companion may run at once,
81  // resolved from config.gateConcurrency; absent in a test's Runtime: no limit
82  cpus?: number
83  gateConcurrency?: number
84  // the container's memory in bytes, read once per process (config.ts gateLimits); null: not readable, so no memory ceiling; absent in a test's Runtime
85  memoryBytes?: number | null
86  // what loadConfig left out of the repo-local settings, for the decision log
87  configProblems: string[]
88  // what the repo-local settings file says, no defaults (settings.ts repoLoaded); null: not read
89  repoSettings?: Record<string, unknown> | null
90}
91
92// Stored: what act mode keeps in $.store across passes and reloads. register.ts reads it
93// (`ledger:<repo>` through ledger.ts load, `backoff:<repo>`, `queue-known:<repo>`) and passes
94// none in observe mode, which keeps nothing of its own.
95export type Stored = {
96  // null: the store holds no ledger (a new device, a wiped config), so it is rebuilt from the log
97  ledger: LedgerEntry[] | null
98  // GitHub reads wait until then after a rate limit (v2 SPEC 13.10 item 2)
99  githubBackoffUntil: number | null
100  // the queue's last now= list, handed back to queue-watch.sh as --known (v2 SPEC 13.3.4)
101  queueKnown: number[] | null
102  // when the current starved spell began (S1, v2/rules-starved.ts); null: no spell
103  starvedSince?: number | null
104}
105
106type Timed<T> = { at: number; value: T }
107
108// Cache: what survives between passes in the module (a reload starts it over).
109export type Cache = {
110  // the repo it was filled for: a pass for another repo starts it over (resetFor)
111  repo?: string
112  queue?: Timed<number[]>
113  github: Map<number, Timed<GithubIssue>>
114  // trackers' direct open sub-issues, from their timelines (D-35)
115  timelines: Map<number, Timed<number[]>>
116  usage?: Timed<Usage>
117  // API-key mode: when the last usage event was written (a reload starts it over)
118  usageEvent?: Ms
119  milestone?: Timed<Milestone | null>
120  release?: Timed<ReleaseInfo>
121  // when the oldest closed issue of the milestone closed (observe-milestone.ts)
122  closed?: Timed<string | null>
123  factory?: Timed<Factory>
124  events?: Timed<FactoryEvent[]>
125  // the last compare of the facts' two stores (v2/sources-facts.ts); absent: none made this load
126  factsShadow?: FactsShadow
127  pool?: Timed<Pool>
128  // act mode: the last ledger rebuilt from the event log, and how many entries it found
129  rebuilt?: Timed<number>
130  v2: V2Cache
131}
132
133export function emptyCache(): Cache {
134  return { github: new Map(), timelines: new Map(), v2: emptyV2Cache() }
135}
136
137// resetFor: nothing read for one repo may stand in for another's (a queue, a milestone, issue
138// facts), so a cache filled for another repo, as when the workspace config names a new one
139// without a reload, is emptied in place before the pass reads anything.
140function resetFor(cache: Cache, repo: string) {
141  if (cache.repo === repo) return
142  delete cache.queue
143  delete cache.usage
144  delete cache.usageEvent
145  delete cache.milestone
146  delete cache.release
147  delete cache.closed
148  delete cache.factory
149  delete cache.events
150  delete cache.factsShadow
151  delete cache.pool
152  delete cache.rebuilt
153  cache.github.clear()
154  cache.timelines.clear()
155  cache.v2 = emptyV2Cache()
156  cache.repo = repo
157}
158
159export type Observation = {
160  state: State
161  commands: string[]
162  // queue-watch.sh's now= list when it read the queue this pass, for register to save as the
163  // next --known; null when it did not (the cadence, a failure, a backoff, observe mode): the
164  // stored list stands
165  queueKnown: number[] | null
166  // where the ledger came from, for the decision log: the store, the event log, or neither
167  ledgerSource: LedgerSource
168  // a command's stderr showed a GitHub rate limit: register sets the backoff (v2 SPEC 13.10 item 2)
169  rateLimited: boolean
170  // the PR heads v2 has seen (v2 SPEC 2.4), for act mode to keep; null when v2 read nothing
171  v2Heads: Record<string, HeadSeen> | null
172  // the tally after this pass's reading (API-key spend, or the subscription what-if total), for an acting pass to store; null: leave it
173  spend: Tally | null
174}
175
176// Io: the engine calls observe needs, built by register.ts (the only module that holds $).
177export type Io = {
178  now: () => Promise<number>
179  run: (argv: string[], init: { cwd: string; env: Record<string, string>; stdin?: string; timeoutMs: number }) => Promise<{ exitCode: number; stdout: string; stderr: string }>
180  readFile: (path: string) => Promise<string | null>
181  sessionLimits: () => Promise<{ kind: string; percentUsed: number; resetsAt?: string }[]>
182  // the process-wide cost in dollars (session usage cost.usd); null: none; absent in a test's Io
183  sessionCost?: () => Promise<number | null>
184  agents: () => Promise<{ id: string; type: string; status: State['agents'][number]['status'] }[]>
185}
186
187// observe: one pass's reads. `stored` is act mode's store (undefined in observe mode): it adds
188// the ledger, the GitHub backoff and the queue's known list. `v2Stored` is what the store holds
189// for v2.
190export async function observe(
191  io: Io,
192  rt: Runtime,
193  cache: Cache,
194  loadedAt: number,
195  lastTitle: string | null, lastTitleAt: number | null,
196  stored?: Stored,
197  v2Stored?: V2Stored,
198  spendStored?: unknown,
199): Promise<Observation> {
200  resetFor(cache, rt.repo)
201  const now = await io.now()
202  const cfg = rt.config
203  const commands: string[] = []
204  const sources = {} as Record<SourceName, Source>
205  let limited = false
206  const mark = (name: SourceName, ok: boolean, at: number | null, error?: string) => {
207    sources[name] = error === undefined ? { ok, at } : { ok, at, error }
208  }
209  const run = async (argv: string[], stdin?: string, timeoutMs = 60_000, env = rt.env) => {
210    commands.push(argv.join(' ').slice(0, 160))
211    const r = await io.run(argv, { cwd: rt.cwd, env, stdin, timeoutMs })
212    if (rateLimited(r.stderr)) limited = true
213    return r
214  }
215  const tool = (name: string) => `${rt.toolsDir}/${name}`
216  const fail = exitFail
217  // act mode: GitHub reads wait out a rate limit (v2 SPEC 13.10 item 2); old values stay, with their age
218  const until = stored?.githubBackoffUntil ?? null
219  const backoffUntil = until !== null && until > now ? until : null
220  const waiting = backoffUntil === null ? '' : `GitHub rate limit: waiting until ${new Date(backoffUntil).toISOString()}`
221
222  // factory: required; a failure makes the pass blind (rule G2)
223  try {
224    const r = await run(['callum-flow-factory-state', '--repo', rt.repo, '--format', 'json', '--github', 'off'], undefined, 90_000)
225    const parsed = r.exitCode === 0 ? parseFactoryState(r.stdout, rt.repo) : null
226    // a derivation that left out events the loop reads is blind (G2), and never cached
227    const behind = parsed === null ? null : derivedSkipError(parsed.skipped)
228    if (parsed !== null && behind === null) cache.factory = { at: now, value: parsed }
229    mark('factory', parsed !== null && behind === null, cache.factory?.at ?? null, parsed === null ? (r.exitCode === 0 ? factoryStateError(r.stdout, rt.repo) : fail(r)) : (behind ?? undefined))
230  } catch (err) {
231    mark('factory', false, cache.factory?.at ?? null, String(err))
232  }
233
234  // facts: the event log, one query, from the store `eventsSource` picks (v2/sources-facts.ts)
235  const factsRead = await readFacts({ now, rt, run }, EVENT_DAYS, cache)
236  if (factsRead.ok) cache.events = { at: now, value: factsRead.value }
237  mark('facts', factsRead.ok, cache.events?.at ?? null, factsRead.ok ? undefined : factsRead.error)
238  const factory = cache.factory?.value ?? null
239  const events = cache.events?.value ?? []
240  const facts = cache.events !== undefined ? factsOf(events) : null
241
242  // runs: the loop reads no pipeline runs. With runSource events (the shadow and the replay) the
243  // event log's view of them stands, so the source is as good as the facts.
244  if (rt.runSource === 'events') mark('runs', sources.facts.ok, sources.facts.at)
245  else mark('runs', false, null, 'not read: the loop has no pipeline runs')
246
247  // The ledger. Observe mode: what the device's own events prove (v2 SPEC 13.7.5). Act mode: the
248  // store's whenever it holds one; else it is rebuilt from a `week` of events (the facts window
249  // would lose older holds), where v2 reads its logged facts too (7.2). A rebuild that found nothing
250  // leaves it empty, and the week is not read every pass. Read before the queue and GitHub: a read
251  // older than a label write of the loop's own is due, so it sees what GitHub took.
252  let chosen: { ledger: LedgerEntry[]; source: LedgerSource }, week: FactoryEvent[] | null = null
253  if (stored === undefined) {
254    chosen = choose(null, factory !== null && facts !== null ? deriveLedger(events, rt.device) : null)
255  } else if (stored.ledger !== null && stored.ledger.length > 0) {
256    // the store holds it, so a later loss is rebuilt again
257    cache.rebuilt = undefined
258    chosen = choose(stored.ledger, null)
259  } else if (cache.rebuilt?.value === 0) {
260    chosen = choose(stored.ledger, null)
261  } else {
262    let derived: LedgerEntry[] | null = null
263    let problem = 'the factory source failed'
264    if (factory !== null) {
265      const weekRead = await readFacts({ now, rt, run }, REBUILD_DAYS)
266      if (weekRead.ok) {
267        week = weekRead.value
268        derived = deriveLedger(week, rt.device)
269        cache.rebuilt = { at: now, value: derived.length }
270      } else {
271        problem = weekRead.error
272      }
273    }
274    chosen = choose(stored.ledger, derived)
275    // a lost ledger the log could not rebuild: the event log is what failed, so say so there,
276    // and plan holds what needs it; the rebuild runs again next pass
277    if (derived === null) mark('facts', false, sources.facts.at, `the store holds no ledger and the event log could not rebuild it: ${problem}`)
278  }
279  const ledger = chosen.ledger
280  const agents = (await io.agents())
281    .filter(a => ledger.some(e => e.agentId === a.id))
282    .map(a => ({ id: a.id, type: a.type, status: a.status }))
283  const lastLabelWrite = (n?: number) => lastEnded(ledger, e => e.kind === 'label' && e.status === 'done' && (n === undefined || e.issue === n))
284
285  // queue: every queueEveryMs, and the pass after a label write. Act mode reads it through
286  // queue-watch.sh --once, which logs a `ready` event for each member the stored list lacks
287  // (v2 SPEC 13.3.4); observe mode keeps the plain reader, so the shadow logs no ready events of its own.
288  let queueKnown: number[] | null = null
289  if (backoffUntil !== null) {
290    mark('queue', false, cache.queue?.at ?? null, waiting)
291  } else if (readDue(cache.queue?.at, now, cfg.queueEveryMs, lastLabelWrite())) {
292    try {
293      const once = stored !== undefined
294      const known = stored?.queueKnown != null && stored.queueKnown.length > 0 ? stored.queueKnown.join(',') : 'none'
295      const argv = once
296        ? [tool('queue-watch.sh'), '--once', '--repo', rt.repo, '--label', cfg.readyLabel, '--known', known]
297        : ['callum-flow-issue-read', '--json', '--list', '--label', cfg.readyLabel]
298      const q = await readQueue({ argv, once, cache, now, readyLabel: cfg.readyLabel, run: a => run(a), fail })
299      queueKnown = q.known
300      mark('queue', q.source.ok, q.source.at, q.source.error)
301    } catch (err) {
302      mark('queue', false, cache.queue?.at ?? null, String(err))
303    }
304  } else {
305    mark('queue', true, cache.queue?.at ?? null)
306  }
307
308  // GitHub per issue, oldest reads first, and first of all the issues the loop may act on or
309  // counts as live, so a closed one is known before plan drives it (#556): those of its running
310  // work (an entry running, or an agent at work past its answer), this device's issues and every
311  // issue in a live stage, and those of a merged Run it that has not answered `done` (its closing
312  // ends rule M5's wait). A run is driven only for an issue this device holds, so the watcher's
313  // runs add none. Then the queue, and the issues `only` names with the sub-issues their trackers
314  // stand for (D-35). An issue known closed is not read again unless the queue, which lists open
315  // issues only, names it, or this device holds it (it may be reopened); a failed read keeps the
316  // last value. A read older than a label write of the loop's own or a PR's close is due at once.
317  const control = await readControl(io, rt)
318  const tracker = new RegExp(cfg.trackerTitle, 'i')
319  const isTracker = (n: number) => {
320    const facts = cache.github.get(n)?.value.facts
321    return facts !== null && facts !== undefined && ((facts.subIssues ?? 0) > 0 || tracker.test(facts.title))
322  }
323  // the trackers under `only` to read a timeline for (nested ones TRACKER_DEPTH deep), and every
324  // sub-issue they are known to stand for, from what the cache holds now
325  const walkTrackers = () => {
326    const trackers: number[] = []
327    const subIssues: number[] = []
328    const walk = (n: number, depth: number) => {
329      if (depth >= TRACKER_DEPTH || trackers.includes(n) || !isTracker(n)) return
330      trackers.push(n)
331      for (const sub of cache.timelines.get(n)?.value ?? []) {
332        if (!subIssues.includes(sub)) subIssues.push(sub)
333        walk(sub, depth + 1)
334      }
335    }
336    for (const n of control.only) walk(n, 0)
337    return { trackers, subIssues }
338  }
339  const mine = (factory?.issues ?? []).filter(i => !i.ended && i.holder === rt.device)
340  if (backoffUntil !== null) {
341    const ats = [...cache.github.values(), ...cache.timelines.values()].map(c => c.at)
342    mark('github', false, ats.length > 0 ? Math.max(...ats) : null, waiting)
343  } else {
344    const { subIssues } = walkTrackers()
345    const queue = cache.queue?.value ?? []
346    const working = ledger
347      .filter(e => e.status === 'running' || (e.agentId !== undefined && listedLive(agents, e.agentId)))
348      .flatMap(e => (e.issue === null ? [] : [e.issue]))
349    const live = (factory?.issues ?? []).filter(i => !i.ended && LIVE_STATES.includes(i.state)).map(i => i.number)
350    const runIts = ledger
351      .filter(e => e.key.startsWith('task:run-it:') && !(e.status === 'done' && e.outcome?.kind === 'wake' && e.outcome.decision === 'done'))
352      .flatMap(e => (e.issue === null ? [] : [e.issue]))
353    const held = mine.map(i => i.number)
354    // v2's records go first, in v2's read order (v2 SPEC 2.4); then the oldest reads
355    const first = readOrder(v2Stored?.records ?? [])
356    // the open issues the read issues block: read last, so a chain never starves the issues the loop acts on
357    const chain = [...cache.github.values()].flatMap(c => c.value.facts?.blockingList ?? [])
358    const named = new Set([...first, ...working, ...held, ...live, ...runIts, ...queue, ...control.only, ...subIssues])
359    const wanted = [...new Set([...named, ...chain])]
360    const rank = (n: number) => (first.includes(n) ? first.indexOf(n) - first.length : named.has(n) ? 0 : 1)
361    const due = wanted
362      .filter(n => {
363        const c = cache.github.get(n)
364        if (c !== undefined && c.value.facts?.open === false && !queue.includes(n) && !held.includes(n) && !first.includes(n)) return false
365        return readDue(c?.at, now, cfg.githubEveryMs, Math.max(lastLabelWrite(n), cache.v2.changed[n] ?? -Infinity))
366      })
367      .sort((a, b) => rank(a) - rank(b) || (cache.github.get(a)?.at ?? 0) - (cache.github.get(b)?.at ?? 0))
368      .slice(0, GITHUB_READS_PER_PASS)
369    const designing = new Set(mine.filter(i => i.state === 'designing').map(i => i.number))
370    let githubOk = await readIssues(run, due, { repo: rt.repo, cache: cache.github, now, designing, limited: () => limited })
371    // tracker timelines, in the reads left this pass, walked again so a tracker read just now counts
372    const timelinesDue = walkTrackers()
373      .trackers.filter(n => {
374        const c = cache.timelines.get(n)
375        return c === undefined || now - c.at >= cfg.githubEveryMs
376      })
377      .slice(0, Math.max(0, GITHUB_READS_PER_PASS - due.length))
378    for (const n of timelinesDue) {
379      if (limited) {
380        githubOk = false
381        break
382      }
383      try {
384        const r = await run(['callum-flow-issue-read', '--json', '--timeline', String(n)])
385        const subs = r.exitCode === 0 ? parseSubIssues(r.stdout, rt.repo) : null
386        if (subs === null) githubOk = false
387        else cache.timelines.set(n, { at: now, value: subs })
388      } catch {
389        githubOk = false
390      }
391    }
392    mark('github', githubOk, now, !githubOk && limited ? 'GitHub rate limit' : undefined)
393  }
394
395  // usage: usage-check.sh every usageEveryMs, and the session's own figures every pass. In API-key mode
396  // neither: the session's cost goes into the stored tally every pass (spend.ts) and the reading is spend.
397  let spend: Tally | null = null
398  let usage: Usage | null
399  if (rt.apiKey !== undefined) {
400    const apiKey = rt.apiKey
401    const cost = await (io.sessionCost?.() ?? Promise.resolve(null)).catch(() => null)
402    const step = tallyStep(spendStored, { costUsd: cost, process: rt.workspace?.process ?? '', session: rt.workspace?.session ?? '' }, now, apiKey)
403    spend = step.tally
404    // a cost that cannot be read keeps the last real reading until it is older than usageStaleMs
405    if (step.usage.reason !== 'spend:no-session-cost' || cache.usage?.value.spend == null) cache.usage = { at: now, value: step.usage }
406    const stale = now - cache.usage.at >= cfg.usageStaleMs
407    usage = stale ? unavailableSpend('spend:stale') : cache.usage.value
408    if (cache.usageEvent === undefined || now - cache.usageEvent >= cfg.usageEveryMs) {
409      cache.usageEvent = now
410      try {
411        await run(['callum-flow-event', '--type', 'usage', '--actor', 'watcher', '--data', JSON.stringify(spendEventData(usage))], undefined, 30_000)
412      } catch {
413        // best effort, as usage-check.sh's own event write
414      }
415    }
416  } else {
417    // the what-if total (API prices) folds in every pass; it rides on the usage event only, never the tier
418    const cost = await (io.sessionCost?.() ?? Promise.resolve(null)).catch(() => null)
419    const whatIf = whatIfStep(spendStored, { costUsd: cost, process: rt.workspace?.process ?? '', session: rt.workspace?.session ?? '' }, now)
420    spend = whatIf.tally
421    if (cache.usage === undefined || now - cache.usage.at >= cfg.usageEveryMs) {
422      try {
423        const r = await run([tool('usage-check.sh')], undefined, 30_000, { ...rt.env, ...whatIfEnv(whatIf) })
424        cache.usage = { at: now, value: parseUsage(r.stdout.trim()) }
425      } catch {
426        // unavailable: plan fails open as the skill says
427      }
428    }
429    // a reading older than usageStaleMs counts as unavailable (v2 SPEC 13.3.1)
430    const reading = cache.usage !== undefined && now - cache.usage.at < cfg.usageStaleMs ? cache.usage.value : null
431    usage = withSession(reading, await io.sessionLimits())
432  }
433  mark('usage', usage !== null && !usage.unavailable, cache.usage?.at ?? null)
434
435  // pool: the shadow cannot see the shadowed device's pool, so it is assumed from its load
436  let pool: Pool | null = null
437  let poolJson: string | null = null
438  if (rt.runSource === 'events') {
439    const busy = mine.filter(i => BUSY_STATES.includes(i.state)).length
440    pool = { free: Math.max(0, rt.poolSize - busy), total: rt.poolSize, slots: [] }
441    mark('pool', true, now)
442  } else {
443    try {
444      const r = await run(['treehouse', 'status', '--json'])
445      pool = r.exitCode === 0 ? parsePool(r.stdout, rt.poolSize) : null
446      if (pool !== null) poolJson = r.stdout
447      if (pool !== null) cache.pool = { at: now, value: pool }
448      mark('pool', pool !== null, cache.pool?.at ?? null, pool === null ? fail(r) : undefined)
449    } catch (err) {
450      mark('pool', false, cache.pool?.at ?? null, String(err))
451    }
452  }
453
454  // checkout: the main checkout's branch and tracked changes, every pass (rule G5, #544). Agents
455  // the loop starts begin there and designers read its code, so one an agent moved holds them.
456  // --no-optional-locks: the read never takes the index lock from under an agent's git command.
457  let checkout: Checkout
458  try {
459    const origin = await run(['git', 'symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], undefined, 10_000)
460    if (origin.exitCode !== 0) {
461      // --quiet: a ref that is not set exits 1 with nothing on stderr
462      const why = origin.stderr.trim() === '' ? `exit ${origin.exitCode}` : fail(origin)
463      checkout = { error: `no origin/HEAD (${why}); git remote set-head origin --auto sets it` }
464    } else {
465      const status = await run(['git', '--no-optional-locks', 'status', '--porcelain=v2', '--branch', '--untracked-files=no'], undefined, 30_000)
466      const read = status.exitCode === 0 ? parseCheckout(origin.stdout, status.stdout) : null
467      checkout = read ?? { error: status.exitCode === 0 ? 'git status did not read' : fail(status) }
468    }
469  } catch (err) {
470    checkout = { error: String(err) }
471  }
472
473  // milestone and, while it qualifies, the last release (observe-milestone.ts)
474  await readMilestone(cache, { now, every: cfg.milestoneEveryMs, repo: rt.repo, base: 'defaultBranch' in checkout ? checkout.defaultBranch : null, run, tagWanted: waitsOnTag(v2Stored?.records ?? []), tagRepos: tagRepos(v2Stored?.records ?? []), backoff: backoffUntil !== null })
475  mark('milestone', cache.milestone !== undefined, cache.milestone?.at ?? null)
476
477  // act mode holds GitHub writes and waits while the backoff lasts, and from the pass that met a
478  // limit: v2's reads below too, so a wait one of them could not read holds with no clock
479  const backoffOf = () => (stored !== undefined && limited ? Math.max(backoffUntil ?? 0, now + GITHUB_BACKOFF_MS) : backoffUntil)
480
481  const state = buildState({
482    now,
483    repo: rt.repo,
484    device: rt.device,
485    loadedAt,
486    sources,
487    factory,
488    facts,
489    runs: null,
490    queue: cache.queue?.value ?? null,
491    github: new Map([...cache.github].map(([n, c]) => [n, c.value])),
492    timelines: new Map([...cache.timelines].map(([n, c]) => [n, c.value])),
493    usage,
494    pool,
495    agents,
496    milestone: cache.milestone?.value == null || cache.closed === undefined ? (cache.milestone?.value ?? null) : { ...cache.milestone.value, oldestClosedAt: cache.closed.value },
497    release: cache.release?.value ?? null,
498    ledger,
499    control,
500    lastTitle, lastTitleAt,
501    githubBackoffUntil: backoffOf(),
502    trackerTitle: cfg.trackerTitle,
503    checkout,
504  })
505  const read = await observeV2({ io, rt, cache: cache.v2, run, state, tag: newestTag(cache), tags: repoTags(cache), stored: v2Stored, poolJson, github: cache.github, events: week ?? events, factsShadow: cache.factsShadow, backoff: backoffUntil !== null, limited: () => limited, starvedSince: stored?.starvedSince ?? null })
506  return { state: { ...state, githubBackoffUntil: backoffOf(), v2: read.v2 }, commands, queueKnown, ledgerSource: chosen.source, rateLimited: limited, v2Heads: read.heads, spend }
507}
508
509// withSession: the higher of usage-check.sh's reading and the session's own, per window.
510function withSession(reading: Usage | null, limits: { kind: string; percentUsed: number; resetsAt?: string }[]): Usage | null {
511  const session = (kind: string) => limits.find(l => l.kind === kind)
512  const five = session('five_hour')
513  const seven = session('seven_day')
514  if (reading === null && five === undefined && seven === undefined) return null
515  const base: Usage = reading ?? { fiveHour: null, sevenDay: null, fiveHourResetsAt: null, sevenDayResetsAt: null, unavailable: false }
516  const max = (a: number | null, b: number | undefined) => (b === undefined ? a : a === null ? b : Math.max(a, b))
517  return {
518    ...base,
519    fiveHour: max(base.fiveHour, five?.percentUsed),
520    sevenDay: max(base.sevenDay, seven?.percentUsed),
521    unavailable: base.unavailable && five === undefined && seven === undefined,
522  }
523}
524
525// readControl: control.json, field by field (controlFrom); missing or unreadable is no directive.
526async function readControl(io: Io, rt: Runtime): Promise<Control> {
527  try {
528    const text = await io.readFile(`${rt.loopDir}/control.json`)
529    return text === null ? EMPTY_CONTROL : controlFrom(JSON.parse(text))
530  } catch {
531    return EMPTY_CONTROL
532  }
533}
534