SLOPSHOPPER

Factory loop workspace

The factory loop's companion: starts each agent the loop runs in its worktree slot, confines its writes and pushes, gives its shell commands a 10-minute…

guardprocesstimeragents
★ 3v0.99.1no licenseupdated 2026-10-25cbundy/dev-system/plugins/factory-loop-workspace
A shopper browsing a rack in a slop shop
README

factory-loop-workspace

The factory loop's companion plugin. It is enabled beside factory-loop in the orchestrator-loop workspace, and does for each agent the loop starts what the loop cannot do itself (v2 SPEC section 10).

The engine never runs a plugin's hooks for anything that plugin's own code started, and the loop starts its agents from its timer, so its own hooks never see them (the spike notes). A second plugin's hooks do. That is why this is a plugin of its own.

What it does

It acts only on a spawn whose prompt opens with factory-slot: <absolute slot path>, which the loop gives every agent step. Every other agent is left alone.

HookWhat it does
agent.spawnReads the slot line and the step marker factory-step.json that factory-slot prepare wrote into the slot's git dir. Starts the agent in the slot when the marker is the loop's agent's (its name <step>-<N>-s<seq>-a<k> and its type factory-loop:*); refuses the spawn when the marker is missing or names another step. Keeps the agent's id, and its children's, in $.state.
tool.callThe write guard. A writer writes only inside its slot (or outside the repository, such as its scratch folder); a reader writes nowhere in the repository. Every loop agent is refused GitHub writes (PRs, issues, labels, re-runs), axi, a push to any remote but origin, any call in the background (Bash or Agent), and an isolated Agent call. A writer pushes only its branch, never by force, and creates no branch or worktree. A reader neither commits nor pushes. A Bash call with no timeout gets 10 minutes. A Bash call also runs with TMPDIR, TMP and TEMP set to the step marker's scratch folder (<loop dir>/scratch/<N>-<life>-s<seq>, made by factory-slot prepare), by an export line before the agent's own command; the guard judges the original command. A marker with no usable scratch, or a caller outside the map, leaves the command as it is. When the marker has gateConcurrency, a line before the agent's command also defines a shell function for each program among the gateCommands (npm() { ... }): when the words of its call are the rest of a gate command (npm test, npm run lint) it runs bin/factory-gate-slot (below) to take one of the container's gate slots first, and any other call (npm test -- <id>, npm ci) goes on to the program. A gate command with shell syntax or a path program is not wrapped. The agent waits max(0, timeout - gateTimeoutMs) for a slot (none at the defaults: a busy container refuses at once, telling it to run a subset or leave the full run to the stop gate).
classic.SubagentStopThe stop gate. When a writer finishes, it runs the repo's gateCommands in the slot, one after another, within gateTimeoutMs, after taking a turn: at most the marker's gateConcurrency gates run at once in the process, the rest wait in order (up to the marker's gateWaitTimeoutMs, then gate-unknown; the wait holds a host call, a short sleep, because the engine cuts a hook off after 10 s of its own budget, which host calls pause). While one fails, the finish is refused with the command, its exit code and the last 150 lines of its output. A gate that cannot run lets the agent finish and is logged. Before it asks for a turn it writes a gate-start line, so a restart that cuts the gate leaves a trace. Claude Code also ends an agent after 10 minutes without progress (CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS) and aborts its stop hook, so a queued gate (wait, then run) would die at 10 minutes in all: the agent.spawn hook raises that limit with $.env.set for a writer with gates, to the marker's gateWaitTimeoutMs + gateTimeoutMs + 5 minutes (v2 SPEC 10.6; proved by the gate-queue case of the workspace probe). A gate the engine cuts anyway is logged as gate-unknown saying the hook was cut off, with the wait and the run. With gateConcurrency each command also takes one of the container's gate slots (<loop dir>/gate-slots/<i>.lock, held through flock by bin/factory-gate-slot, shared with the agents' own gate-command runs) in probes of a few seconds, each its own host call; the time spent there is slotWaitMs, counted in waitMs and not in gateTimeoutMs, and a wait past the cap (gateWaitTimeoutMs less the turn's wait) is gate-unknown.
tool.checkPrompts nobody answers (v2 SPEC 10.10). Calls next(e) once; when the call is from a mapped loop agent (or its child) and Claude Code answered ask, it returns a deny instead, saying the call would wait on a person nobody watches, quoting Claude Code's reason, and telling the agent to find another way or end its step saying what it needed. Any other result, and any caller not in the map (the owner's own session), is returned unchanged.
classic.NotificationA permission_prompt (or worker_permission_prompt) notification from a mapped agent is written as a native prompt_waiting event. Returns next(e) always.
classic.SubagentStartLearns each agent's transcript path for the notes above.
session.startThe handshake: writes <CLAUDE_CONFIG_DIR>/factory-loop/workspace/<session>.json with the time and this process's id (its pid and start time, from /proc/self/stat), again every minute (the first row or turn starts the beat when a /reload-plugins added the plugin). The same beat starts the recovery of a cut gate (below), from its clock callback. The loop holds every agent step while this session's file is missing, names another process or is older than 3 minutes. The same beat writes the session's context window ($.session.usage().context.window) to DEV_CONTEXT_WINDOW_DIR/<session>, only when the session or the window changes; no window, or a failed read or write, writes nothing and never touches the handshake.

What it writes

  • <loop dir>/companion.jsonl: one line per refusal (guard:write, guard:push, guard:command), per refused prompt (prompt-denied) and per gate run (gate-pass, gate-fail, gate-unknown, with the head, the duration, waitMs, concurrency, startedAt (when the gate asked for its turn, an ISO string), slotWaitMs (the part of waitMs spent waiting for a container gate slot; absent without gateConcurrency), queuedBehind (how many held a turn or waited ahead of it; 0 when none), clean (the slot's tree was clean and its head did not move; null: not known) and, for a failing command, the command and failedTests (the failing test names parsed from its output, null for none); a gate that ran also carries memStartBytes, memPeakBytes, memLimitBytes and memSamples (the container's cgroup memory.current when the gate started to run, the highest reading taken every 5 s while it ran and at its end, memory.max, and how many readings worked; null and 0 when the cgroup is unreadable; FACTORY_GATE_CGROUP_DIR names another cgroup directory, a test hook; a gate that waited out carries none); gate-wait when a gate waited for its turn), with the issue, life and seq. The loop logs each refusal, each prompt-denied and each gate-unknown, gate-rerun and gate-cut as an intervention; a gate that started, passed, failed or waited is not one. It also reads every gate line to write one gate_run event per run; the companion itself writes only the two prompt events below.
  • agent-gate (written by bin/factory-gate-slot when an agent's own gate command ends or is refused: command, waitMs, slot, exit, ms, refused; not an intervention, a gate result or a recovery candidate),
  • gate-start (before a gate asks for its turn: startedAt, which its settling line repeats, slot, gitDir and process, this process's pid:start-time from /proc/self/stat), and the recovery's lines. When a restart cuts a gate before it settles, the session that holds the loop dir's act.lock (its lease names the session and has not expired) reads, on a handshake beat and once per loop dir per process, the last 24 hours of the log. Each attempt whose newest line is a gate-start or gate-wait, whose start line's process is gone, and whose slot's factory-step.json still names it as a writer with gate commands gets a gate-rerun line, a run of the gate through the same turns and budget, and the usual settling line with rerun: true. Any other such attempt gets one gate-cut line saying why and runs nothing. The loop treats a re-run's pass or unknown as a settling line, and a re-run's fail as the end of the hold (the step ends lost and runs again free).
  • callum-flow-event --type prompt_denied (one per refused prompt) and --type prompt_waiting (one per prompt a mapped agent waits on), native events with --data (life, seq, step, attempt, agent_id, agent_type, tool_name, tool_input, ask_reason for a denial, slot, session, transcript, branch, pr; null when unknown) and --issue. An image whose callum-flow-event cannot write them still gets the deny and its companion.jsonl line. There is no prompt_answered: no hook shows the answer.
  • factory-gate.json in the slot's git dir: the last gate result (pass, fail or unknown) with the slot's HEAD and waitMs.
  • ${DEV_CONTEXT_WINDOW_DIR:-/tmp/dev-context-window}/<session>: the session's context window size as <integer>\n, which the worker heartbeat pushes as sessions[].context_window (the factory-hud mod writes the same file; sub-agents stay null).
  • The handshake file above. Files older than 7 days are pruned at session start.

The guard matches commands, not effects. A Bash write into another slot is not refused; each slot is reset at its next prepare, and callum-flow's main-checkout guard covers the main checkout.

Enable it

The orchestrator-loop Coder template lists it beside factory-loop (coder/push.sh). On any other machine:

/plugin install factory-loop-workspace@callum

From a shell instead: claude plugin install factory-loop-workspace@callum --scope user, then start a new session.

Gate commands are repo settings: gateCommands (for example ["npm run lint", "npm test"]) and gateTimeoutMs, gateConcurrency (a whole number or auto, one gate per 8 CPUs) and gateWaitTimeoutMs in the repo's .claude/factory-loop.json or the workspace config. Empty means no gate.

Develop it

npm test runs claude plugin test on this folder: tests/rules.test.ts holds the rules, tests/companion.test.ts drives each hook as the engine does for an agent the loop starts.

Re-run the workspace probe (docs/factory-loop/probes/workspace-probe/) on each Claude Code upgrade. Its companion case runs this plugin for real beside a stand-in loop.

Source 13 files
hooks/register.ts 651 lines
1// factory-loop-workspace: the factory loop's companion plugin (docs/factory-loop/v2/SPEC.md 10.3 to
2// 10.6, 10.9). The engine never runs a plugin's hooks for what that plugin's own code started, and
3// the loop starts its agents from its timer, so its own hooks never see them (docs/spikes/factory-loop-workspace/README.md). This
4// second plugin's hooks do, and carry what the loop needs around each agent it starts:
5//
6// - the folder (10.3): a spawn whose prompt opens with `factory-slot: <path>` is started in that
7//   slot, once the slot's step marker matches the spawn; a missing or mismatched marker refuses it;
8// - the map: the agent's id, and its children's, to its slot and marker, kept in $.state;
9// - the write guard (10.4): file writes and commands the agent's role may not make are refused,
10//   each refusal appended to <loop dir>/companion.jsonl, which the loop logs as an intervention;
11// - the timeout (10.5): a Bash call with no timeout gets 10 minutes;
12// - the stop gate (10.6): a writer may not finish while the repo's gate commands fail; a gate that
13//   cannot run lets it finish, logged as gate-unknown; every run is a line of companion.jsonl, the
14//   last also in factory-gate.json; a `gate-start` line says a gate began, and the session that holds the
15//   loop's act lock runs again, once per loop dir, a gate whose process is gone before it settled
16//   (a restart cut it), as `gate-rerun` and a settling line with `rerun: true`, or gives it up as `gate-cut`;
17// - prompts nobody answers (10.10): a call of a mapped agent that Claude Code would put to a person
18//   (tool.check answered `ask`) is denied instead, with a reason that tells the agent to find another
19//   way, and written as a native `prompt_denied` event and a `prompt-denied` line of companion.jsonl; a
20//   permission_prompt notification of a mapped agent is a native `prompt_waiting` event. A caller that is
21//   not in the map (the owner's own session) is never touched;
22// - the handshake (10.9): <CLAUDE_CONFIG_DIR>/factory-loop/workspace/<session>.json says this
23//   session has the companion, and in which process, written again every minute; the loop holds
24//   every agent step while its own is missing, from another process or stale.
25//
26// It acts only on spawns that carry the slot line, so the loop's v1 agents and every other agent
27// pass untouched.
28import type { EngineInterface, Register } from 'claude-code'
29import type { WorkspaceAgent } from '../types'
30import { DEFAULT_GATE_WAIT_MS, STALL_DEFAULT_MS, blockText, gateLine, gateRecord, oneLine, runGates, stallBoundMs, waitedOut } from './gate'
31import type { GateResult, Ran } from './gate'
32import { bootMs, gateEntries, isDead, judge, leaseHeld, openGates, pidOf, startMs } from './recover'
33import { DEFAULT_CGROUP_DIR, startMemorySampler } from './memory'
34import type { MemFields } from './memory'
35import { recordWindow } from './window'
36import { FILE_TOOLS, agentRefusal, backgroundRefusal, bashRefusal, fileRefusal, needsHead, normalize, within } from './guard'
37import type { Guarded, Refusal } from './guard'
38import type { Marker } from './marker'
39import { MARKER_FILE, mismatch, nameParts, parseMarker, slotLine } from './marker'
40import { PROMPT_NOTIFICATIONS, inputOf, promptData, promptReason, transcriptOf, whyOf } from './prompt'
41import type { Decided, PromptFields } from './prompt'
42import { withScratch } from './scratch'
43import { WRAPPER, agentWaitMs, gatePrelude, runSlotted, slotCommand, slotDir } from './slots'
44import type { SlotState } from './slots'
45import { createTurns } from './turns'
46import type { Turn } from './turns'
47
48const ME = 'factory-loop-workspace'
49const AGENTS = { plugin: 'factory-loop-workspace', key: 'agents' } as const
50export const BASH_TIMEOUT_MS = 600_000
51// the most a single $.process.run may take
52const RUN_MAX_MS = 600_000
53const QUICK_MS = 15_000
54// the handshake is written again this often: its `at` shows the companion runs now, and the loop
55// takes a handshake a few beats old as missing (factory-loop hooks/v2/sources-workspace.ts)
56export const HANDSHAKE_EVERY_MS = 60_000
57const HANDSHAKE_PRUNE_DAYS = 7
58// a queued gate always has a host call in flight, a sleep of this many seconds started again as each
59// ends: the engine gives a hook handler 10 s of budget, which host calls pause and clock ops do not
60const IDLE_S = 5
61// the stop gates' turns, one set for the whole process: every slot's writer shares it
62const turns = createTurns()
63
64// invocations the .catch has seen fail, by event: a handler the engine cut off still gets its turn later
65const cut = new WeakSet<object>()
66// cutOff: the engine's budget for this handler ran out (its signal aborted or no budget left), or the catch marked it
67function cutOff(e: object, next: unknown): boolean {
68  const n = next as { signal?: { aborted?: boolean }; budget?: { remainingMs?: number } } | undefined
69  return cut.has(e) || n?.signal?.aborted === true || n?.budget?.remainingMs === 0
70}
71
72// the catch's reason: the error's one line when one reached it
73function failedReason(err: unknown): string {
74  const m = typeof err === 'string' ? err : (err as { message?: unknown } | null | undefined)?.message
75  let text = typeof m === 'string' ? m : ''
76  if (text === '' && err !== undefined && err !== null) {
77    try {
78      text = JSON.stringify(err) ?? ''
79    } catch {
80      text = ''
81    }
82  }
83  return text === '' ? 'the stop gate hook failed' : `the stop gate hook failed (${oneLine(text)})`
84}
85
86// --- small helpers over $ ---------------------------------------------------------------------------
87
88async function run($: EngineInterface, argv: string[], opts: { cwd?: string; stdin?: string; timeoutMs?: number } = {}) {
89  return $.process.run(argv, { timeoutMs: QUICK_MS, ...opts })
90}
91
92async function readText($: EngineInterface, path: string): Promise<string | null> {
93  try {
94    return await $.fs.read(path)
95  } catch {
96    return null
97  }
98}
99
100// writeFile: written whole by rename, its folder made first.
101async function writeFile($: EngineInterface, path: string, text: string): Promise<void> {
102  const r = await run($, ['sh', '-c', 'mkdir -p "$(dirname "$1")" && cat > "$1.tmp.$$" && mv -f "$1.tmp.$$" "$1"', 'sh', path], { stdin: text })
103  if (r.exitCode !== 0) throw new Error(`${path}: ${oneLine(r.stderr)}`)
104}
105
106async function appendFile($: EngineInterface, path: string, text: string): Promise<void> {
107  const r = await run($, ['sh', '-c', 'mkdir -p "$(dirname "$1")" && cat >> "$1"', 'sh', path], { stdin: text })
108  if (r.exitCode !== 0) throw new Error(`${path}: ${oneLine(r.stderr)}`)
109}
110
111// configDir: CLAUDE_CONFIG_DIR, else ~/.claude, as the loop builds its own paths.
112async function configDir($: EngineInterface): Promise<string> {
113  const dir = (await $.env.get('CLAUDE_CONFIG_DIR')) || `${(await $.env.get('HOME')) || '~'}/.claude`
114  return dir.replace(/\/{2,}/g, '/').replace(/(.)\/$/, '$1')
115}
116
117// --- the handshake (10.9) ---------------------------------------------------------------------------
118
119// handshakePath: one file per session, so two sessions with the companion never write one file.
120export function handshakePath(configDir: string, session: string): string {
121  return `${configDir}/factory-loop/workspace/${session.replace(/[^A-Za-z0-9._-]/g, '_')}.json`
122}
123
124// processIdOf: the process that /proc/<pid>/stat describes, by its pid and start time, which no
125// other process has: not a child, which has its own, and not a later one given the same pid. Its
126// field 22 is counted after the command name, which may hold spaces. undefined: no stat to read.
127export function processIdOf(stat: string | null): string | undefined {
128  const pid = stat?.split(' ', 1)[0] ?? ''
129  const start = stat?.slice(stat.lastIndexOf(') ') + 2).split(' ')[19] ?? ''
130  return /^\d+$/.test(pid) && /^\d+$/.test(start) ? `${pid}:${start}` : undefined
131}
132
133// handshake: this session's file, written whole with this process's id and the time now (no id:
134// null, which the loop never takes).
135async function handshake($: EngineInterface): Promise<void> {
136  const session = await $.session.id()
137  // this process, as the loop, a plugin of the same process, reads it too
138  const proc = processIdOf(await readText($, '/proc/self/stat')) ?? null
139  const now = await $.clock.now()
140  const path = handshakePath(await configDir($), session)
141  const manifest = await readText($, `${$.plugin.root}/.claude-plugin/plugin.json`)
142  let version = 'unknown'
143  try {
144    const v = (JSON.parse(manifest ?? '{}') as { version?: unknown }).version
145    if (typeof v === 'string') version = v
146  } catch {
147    // the version is for people reading the file; the loop reads the rest
148  }
149  await writeFile($, path, `${JSON.stringify({ v: 1, session, process: proc, version, at: new Date(now).toISOString() })}\n`)
150}
151
152// beatOnce: the handshake, and the window beside it, each caught on its own.
153async function beatOnce($: EngineInterface): Promise<void> {
154  await Promise.all([handshake($).catch(() => undefined), recordWindow($).catch(() => undefined)])
155}
156
157let beat: { cancel: () => void } | null = null
158
159// beating: the handshake now and again every minute, so its `at` stays fresh, a /clear's new
160// session gets its own file, and a pruned or deleted one comes back.
161async function beating($: EngineInterface): Promise<void> {
162  beat?.cancel()
163  // the recovery runs from the clock's callback, never inside a hook handler, so its gate is not
164  // cut by a handler's budget
165  beat = $.clock.every(HANDSHAKE_EVERY_MS, () => {
166    void beatOnce($)
167    void recoverGates($).catch(() => undefined)
168  })
169  await beatOnce($)
170}
171
172async function pruneHandshakes($: EngineInterface): Promise<void> {
173  const dir = `${await configDir($)}/factory-loop/workspace`
174  await run($, ['find', dir, '-maxdepth', '1', '-name', '*.json', '-mtime', `+${HANDSHAKE_PRUNE_DAYS}`, '-delete'])
175}
176
177// --- the map ----------------------------------------------------------------------------------------
178
179async function agentOf($: EngineInterface, agentId: string): Promise<WorkspaceAgent | null> {
180  const { value } = await $.state.get({ ...AGENTS, id: agentId })
181  return value ?? null
182}
183
184async function keep($: EngineInterface, agentId: string, agent: WorkspaceAgent): Promise<void> {
185  await $.state.set({ ...AGENTS, id: agentId }, agent)
186}
187
188// --- the slot (10.3) --------------------------------------------------------------------------------
189
190// placeOf: the slot's git dir, real path and repository roots, or why it is no slot.
191async function placeOf($: EngineInterface, slot: string): Promise<{ gitDir: string; real: string; roots: string[] } | { deny: string }> {
192  let real: string
193  try {
194    const st = await $.fs.stat(slot, { resolve: true })
195    if (st.kind !== 'dir') return { deny: `${slot} is not a folder` }
196    real = st.realPath ?? slot
197  } catch {
198    return { deny: `${slot} does not exist` }
199  }
200  const r = await run($, ['git', '-C', slot, 'rev-parse', '--path-format=absolute', '--show-toplevel', '--absolute-git-dir', '--git-common-dir'])
201  const [top, gitDir, common] = r.stdout.trim().split('\n')
202  if (r.exitCode !== 0 || gitDir === undefined || common === undefined) return { deny: `${slot} is not a git checkout: ${oneLine(r.stderr)}` }
203  if (top !== real && top !== slot) return { deny: `${slot} is not the top of its checkout (${top})` }
204  const roots = [...new Set([slot, real, ...(common.endsWith('/.git') ? [common.slice(0, -'/.git'.length)] : [])])]
205  return { gitDir, real, roots }
206}
207
208// --- the guard (10.4) -------------------------------------------------------------------------------
209
210function guardedOf(a: WorkspaceAgent): Guarded {
211  return { slot: a.slot, role: a.role, branch: a.branch, roots: a.roots }
212}
213
214// placed: a path's real location, symlinks resolved through its nearest existing folder; null when
215// none can be read.
216async function placed($: EngineInterface, path: string): Promise<string | null> {
217  let rest = ''
218  let at = path
219  for (let i = 0; i < 64 && at !== ''; i++) {
220    const st = await $.fs.stat(at, { resolve: true }).catch(() => null)
221    if (st !== null && st.realPath !== undefined) return normalize(`${st.realPath}${rest}`, '/')
222    const cut = at.lastIndexOf('/')
223    rest = `${at.slice(cut)}${rest}`
224    at = at.slice(0, cut)
225  }
226  return null
227}
228
229async function headBranch($: EngineInterface, slot: string): Promise<string | null> {
230  const r = await run($, ['git', '-C', slot, 'symbolic-ref', '--quiet', '--short', 'HEAD']).catch(() => null)
231  return r !== null && r.exitCode === 0 ? r.stdout.trim() : null
232}
233
234async function refusalOf($: EngineInterface, a: WorkspaceAgent, e: Record<string, unknown>, tool: string): Promise<Refusal | null> {
235  const g = guardedOf(a)
236  const background = backgroundRefusal(tool, e)
237  if (background !== null) return background
238  if (tool === 'Agent') return agentRefusal(e)
239  if ((FILE_TOOLS as readonly string[]).includes(tool)) {
240    const raw = typeof e.file_path === 'string' ? e.file_path : typeof e.notebook_path === 'string' ? e.notebook_path : null
241    if (raw === null) return null
242    const path = normalize(raw, a.slot)
243    const lexical = fileRefusal(g, path)
244    if (lexical !== null) return lexical
245    // a symlink must not carry a write out of the slot, or into the repository for a reader
246    const real = await placed($, path)
247    if (real === null || real === path) return null
248    const refused = fileRefusal({ ...g, slot: within(path, a.slot) ? a.real : g.slot }, real)
249    return refused === null ? null : { ...refused, reason: `${raw} resolves to ${real}: ${refused.reason}` }
250  }
251  if (tool === 'Bash' && typeof e.command === 'string') {
252    const head = needsHead(e.command) ? await headBranch($, a.slot) : null
253    return bashRefusal(g, e.command, head)
254  }
255  return null
256}
257
258// logLine: one line of the companion's log, which the loop reads (v2/sources-interventions.ts).
259async function logLine($: EngineInterface, a: Pick<WorkspaceAgent, 'issue' | 'life' | 'seq' | 'loopDir'>, cause: string, reason: string, fields: Record<string, unknown> = {}): Promise<void> {
260  const line = { at: new Date(await $.clock.now()).toISOString(), issue: a.issue, life: a.life, seq: a.seq, cause, reason: oneLine(reason, 500), ...fields }
261  await appendFile($, `${a.loopDir}/companion.jsonl`, `${JSON.stringify(line)}\n`).catch(() => undefined)
262}
263
264// --- prompts nobody answers (10.10) -----------------------------------------------------------------
265
266// the transcripts SubagentStart reported before the agent was in the map, by agent id (the newest
267// 200); the map's own record has it once it is
268const transcripts = new Map<string, string>()
269const TRANSCRIPTS_KEPT = 200
270
271function transcriptSeen(agentId: string, a: WorkspaceAgent): string | null {
272  return a.transcript ?? transcripts.get(agentId) ?? null
273}
274
275// eventLine: one native factory event through `callum-flow-event --type`, in the issue's repository.
276// A failure (an image that cannot write it, a missing command) is swallowed: the caller has already
277// done what it must.
278async function eventLine($: EngineInterface, a: WorkspaceAgent, type: 'prompt_denied' | 'prompt_waiting', data: Record<string, unknown>): Promise<void> {
279  const argv = ['callum-flow-event', '--type', type, '--data', JSON.stringify(data), '--issue', String(a.issue), '--repo', a.repo]
280  await run($, argv, { cwd: a.slot }).catch(() => undefined)
281}
282
283// promptFields: the event's facts for this agent; what cannot be read is null.
284async function promptFields($: EngineInterface, a: WorkspaceAgent, agentId: string): Promise<PromptFields> {
285  const session = await $.session.id().catch(() => null)
286  return {
287    life: a.life,
288    seq: a.seq,
289    step: a.step,
290    attempt: a.attempt,
291    agent: agentId,
292    agent_type: a.agentType,
293    slot: a.slot,
294    session,
295    transcript: transcriptSeen(agentId, a),
296    branch: a.branch,
297    pr: typeof a.pr === 'number' ? a.pr : null,
298  }
299}
300
301// refusePrompt: the deny for a mapped agent's call that Claude Code answered `ask`, with its event
302// and its line. Whatever of those fails, the deny stands.
303async function refusePrompt($: EngineInterface, a: WorkspaceAgent, e: { tool: string; input?: unknown; agentId?: string }, decided: Decided): Promise<{ decision: 'deny'; reason: string }> {
304  const reason = promptReason(e.tool, e.input, decided)
305  try {
306    const data = promptData('prompt_denied', { ...(await promptFields($, a, e.agentId ?? '')), tool: e.tool, why: whyOf(decided), input: inputOf(e.tool, e.input) })
307    await eventLine($, a, 'prompt_denied', data)
308  } catch {
309    // the deny is what matters
310  }
311  await logLine($, a, 'prompt-denied', `${e.tool}: ${reason}`).catch(() => undefined)
312  return { decision: 'deny', reason }
313}
314
315// raiseStall: gives the writer about to start a stall limit that covers its gate's wait and run (10.6).
316// Claude Code reads the variable as the agent starts, so it is set before the spawn goes on. The
317// variable is the session's: a later agent of a smaller bound leaves it as it is. A failure to set
318// it is no reason to refuse the spawn; the gate then runs inside the engine's own limit.
319async function raiseStall($: EngineInterface, marker: Marker): Promise<void> {
320  const bound = stallBoundMs(marker)
321  try {
322    const now = Number(await $.env.get('CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS'))
323    if (bound <= Math.max(STALL_DEFAULT_MS, Number.isFinite(now) ? now : 0)) return
324    await $.env.set('CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS', String(bound))
325  } catch {
326    // the spawn goes on
327  }
328}
329
330// --- the stop gate (10.6) ---------------------------------------------------------------------------
331
332// the container's slots for one stop gate's commands: the wrapper, the dir, the limit and the wait they share
333type GateSlots = { wrapper: string; dir: string; capacity: number; state: SlotState }
334
335async function runIn($: EngineInterface, slot: string, command: string, budgetMs: number, slots?: GateSlots): Promise<Ran> {
336  try {
337    if (slots !== undefined) {
338      // each probe is its own host call (a wait of a short slice), so the handler's budget never runs
339      const sliceMs = IDLE_S * 1000
340      const text = slotCommand(command, { wrapper: slots.wrapper, dir: slots.dir, capacity: slots.capacity, sliceMs })
341      return await runSlotted(slots.state, sliceMs, async () => {
342        const r = await $.process.run(['sh', '-c', `exec 2>&1\n${text}`], { cwd: slot, timeoutMs: Math.min(budgetMs + sliceMs, RUN_MAX_MS) })
343        return { exitCode: r.exitCode, stdout: r.stdout }
344      })
345    }
346    const r = await $.process.run(['sh', '-c', `exec 2>&1\n${command}`], { cwd: slot, timeoutMs: Math.min(budgetMs, RUN_MAX_MS) })
347    return { exitCode: r.exitCode, output: r.stdout }
348  } catch (err) {
349    return { error: err instanceof Error ? err.message : String(err) }
350  }
351}
352
353async function headSha($: EngineInterface, slot: string): Promise<string | null> {
354  const r = await run($, ['git', '-C', slot, 'rev-parse', 'HEAD']).catch(() => null)
355  return r !== null && r.exitCode === 0 ? r.stdout.trim() : null
356}
357
358// slotClean: whether `git status --porcelain` ran and printed nothing (null: it could not run or failed).
359async function slotClean($: EngineInterface, slot: string): Promise<boolean | null> {
360  const r = await run($, ['git', '-C', slot, 'status', '--porcelain']).catch(() => null)
361  return r !== null && r.exitCode === 0 ? r.stdout.trim() === '' : null
362}
363
364// What a stop gate needs of an attempt: a writer's agent, or the marker of a slot whose gate a
365// restart cut.
366type GateTarget = Pick<WorkspaceAgent, 'slot' | 'gitDir' | 'issue' | 'life' | 'seq' | 'gateCommands' | 'gateTimeoutMs' | 'loopDir' | 'gateConcurrency' | 'gateWaitTimeoutMs'>
367
368// sampleMemory: the gate's memory sampler over the cgroup files; a failure anywhere gives a sampler
369// that read nothing, never an error (a measurement must not change a gate)
370async function sampleMemory($: EngineInterface): Promise<{ stop: () => Promise<MemFields> }> {
371  const none = { stop: async (): Promise<MemFields> => ({ memStartBytes: null, memPeakBytes: null, memLimitBytes: null, memSamples: 0 }) }
372  try {
373    const dir = (await $.env.get('FACTORY_GATE_CGROUP_DIR')) || DEFAULT_CGROUP_DIR
374    return await startMemorySampler({
375      read: async () => {
376        const [current, max] = await Promise.all([readText($, `${dir}/memory.current`), readText($, `${dir}/memory.max`)])
377        return { current, max }
378      },
379      every: (ms, fn) => $.clock.every(ms, fn),
380    })
381  } catch {
382    return none
383  }
384}
385
386// runStopGate: the one gate run of a stop (the writer's finish) and of the recovery (a re-run), so the two
387// cannot drift: a turn first (10.6; at most gateConcurrency gates run at once in this process, a marker
388// with no limit takes none), then the head and tree, the commands, factory-gate.json and the settling
389// line (with `rerun: true` for the recovery's). ran: false when `cut` said the engine ended the caller
390// while it waited, and no gate ran. A turn always goes back, so a stuck or crashed gate never blocks the others.
391export async function runStopGate($: EngineInterface, a: GateTarget, startedAt: string, opts: { rerun?: boolean; cut?: () => boolean } = {}): Promise<{ ran: true; result: GateResult } | { ran: false }> {
392  const rerun = opts.rerun === true
393  const limit = a.gateConcurrency
394  let turn: Extract<Turn, { ok: true }> | null = null
395  let waitMs = 0
396  let queuedBehind = 0
397  if (limit !== undefined) {
398    const cap = a.gateWaitTimeoutMs ?? DEFAULT_GATE_WAIT_MS
399    const got = await turns.acquire(limit, {
400      now: () => $.clock.now(),
401      after: (ms, fn) => $.clock.after(ms, fn),
402      maxWaitMs: cap,
403      idle: () => run($, ['sleep', String(IDLE_S)], { timeoutMs: IDLE_S * 1000 + QUICK_MS }),
404    })
405    waitMs = got.waitMs
406    queuedBehind = got.queuedBehind
407    if (!got.ok) {
408      const result = waitedOut(got.waitMs, cap, limit)
409      const head = await headSha($, a.slot)
410      await writeFile($, `${a.gitDir}/factory-gate.json`, `${JSON.stringify(gateRecord(result, head, await $.clock.now(), a.gateCommands, waitMs), null, 2)}\n`).catch(() => undefined)
411      const line = gateLine(result, head, waitMs, limit, startedAt, queuedBehind, null, rerun)
412      await logLine($, a, line.cause, line.reason, line.fields)
413      return { ran: true, result }
414    }
415    turn = got
416  }
417  // the engine cut the caller off while it waited: the loop has moved on, so it runs no gate
418  if (opts.cut?.() === true) {
419    turn?.release()
420    return { ran: false }
421  }
422  let sampler: { stop: () => Promise<MemFields> } | null = null
423  try {
424    if (turn !== null && turn.queuedBehind > 0) await logLine($, a, 'gate-wait', `the stop gate waited ${Math.round(waitMs / 1000)} s for a turn`, { waitMs, queuedBehind: turn.queuedBehind, concurrency: limit })
425    const headBefore = await headSha($, a.slot)
426    const cleanBefore = await slotClean($, a.slot)
427    sampler = await sampleMemory($)
428    const slots: GateSlots | undefined = limit === undefined ? undefined : { wrapper: `${$.plugin.root}/${WRAPPER}`, dir: slotDir(a.loopDir), capacity: limit, state: { capMs: Math.max(0, (a.gateWaitTimeoutMs ?? DEFAULT_GATE_WAIT_MS) - waitMs), waitedMs: 0 } }
429    const result = await runGates({ run: (command, budgetMs) => runIn($, a.slot, command, budgetMs, slots), now: () => $.clock.now(), ...(opts.cut === undefined ? {} : { cut: opts.cut }) }, a.gateCommands, a.gateTimeoutMs, waitMs)
430    const head = await headSha($, a.slot)
431    const mem = await sampler.stop()
432    // a head that moved during the run means the tree did too: never clean
433    const clean = cleanBefore === null ? null : head !== headBefore ? false : cleanBefore
434    const slotWaitMs = slots?.state.waitedMs
435    const record = gateRecord(result, head, await $.clock.now(), a.gateCommands, waitMs, clean, slotWaitMs)
436    await writeFile($, `${a.gitDir}/factory-gate.json`, `${JSON.stringify(record, null, 2)}\n`).catch(() => undefined)
437    const line = gateLine(result, head, waitMs, limit ?? null, startedAt, queuedBehind, clean, rerun, mem, slotWaitMs)
438    await logLine($, a, line.cause, line.reason, line.fields)
439    return { ran: true, result }
440  } finally {
441    await sampler?.stop().catch(() => undefined)
442    turn?.release()
443  }
444}
445
446// this process, as the handshake names it (undefined: no /proc/self/stat)
447async function ownProcess($: EngineInterface): Promise<string | undefined> {
448  return processIdOf(await readText($, '/proc/self/stat'))
449}
450
451// --- the recovery of a cut gate (10.6) --------------------------------------------------------------
452
453// the loop dirs whose recovery has run in this process, and those being looked at now
454const recovered = new Set<string>()
455const checking = new Set<string>()
456
457// recoverGates: on a handshake beat, until it has run for each loop dir: the loop dirs of the config dir
458// whose act lock this session holds. The owner's own sessions hold none, so they never run it.
459async function recoverGates($: EngineInterface): Promise<void> {
460  const session = await $.session.id()
461  const base = `${await configDir($)}/factory-loop`
462  const entries = await $.fs.list(base).catch(() => [])
463  for (const ent of entries) {
464    if (ent.kind !== 'dir' || ent.name === 'workspace') continue
465    const loopDir = `${base}/${ent.name}`
466    if (recovered.has(loopDir) || checking.has(loopDir)) continue
467    checking.add(loopDir)
468    try {
469      if (!leaseHeld(await readText($, `${loopDir}/act.lock`), session, await $.clock.now())) continue
470      recovered.add(loopDir)
471      await recoverDir($, loopDir).catch(() => undefined)
472    } finally {
473      checking.delete(loopDir)
474    }
475  }
476}
477
478// recoverDir: every gate of the loop dir's log that a restart cut (recover.ts), run again when its slot's
479// marker still names the attempt and given up otherwise, each one line (`gate-rerun` or `gate-cut`).
480async function recoverDir($: EngineInterface, loopDir: string): Promise<void> {
481  const open = openGates(gateEntries(await readText($, `${loopDir}/companion.jsonl`), await $.clock.now()))
482  if (open.length === 0) return
483  const ownStart = startMs(await readText($, '/proc/self/stat'), bootMs(await readText($, '/proc/stat')))
484  for (const g of open) {
485    const pid = pidOf(g.process)
486    const current = pid === null ? undefined : processIdOf(await readText($, `/proc/${pid}/stat`))
487    if (!isDead(g, current, ownStart)) continue
488    const marker = g.gitDir !== null && g.gitDir.startsWith('/') ? parseMarker(await readText($, `${g.gitDir}/${MARKER_FILE}`)) : null
489    const verdict = judge(g, marker)
490    const attempt = { issue: g.issue, life: g.life, seq: g.seq, loopDir }
491    const cutAt = g.startedAt ?? new Date(g.at).toISOString()
492    const fields = { cutStartedAt: g.startedAt, process: g.process, slot: g.slot, gitDir: g.gitDir, marker: marker === null ? null : { issue: marker.issue, life: marker.life, seq: marker.seq } }
493    if (!verdict.rerun || marker === null || g.slot === null || g.gitDir === null) {
494      await logLine($, attempt, 'gate-cut', `the stop gate started at ${cutAt} was cut by a restart and is not run again: ${verdict.rerun ? 'its marker did not read' : verdict.why}`, fields)
495      continue
496    }
497    await logLine($, attempt, 'gate-rerun', `the stop gate started at ${cutAt} was cut by a restart; it runs again, with no agent to refuse`, fields)
498    const target: GateTarget = { ...attempt, slot: g.slot, gitDir: g.gitDir, gateCommands: marker.gateCommands, gateTimeoutMs: marker.gateTimeoutMs, gateConcurrency: marker.gateConcurrency, gateWaitTimeoutMs: marker.gateWaitTimeoutMs }
499    try {
500      await runStopGate($, target, new Date(await $.clock.now()).toISOString(), { rerun: true })
501    } catch (err) {
502      // a gate that could not run is never passed silently
503      await logLine($, attempt, 'gate-unknown', failedReason(err), { rerun: true })
504    }
505  }
506}
507
508// --- the hooks --------------------------------------------------------------------------------------
509
510export const register: Register = on => {
511
512  on('session.start', async ($, e, next) => {
513    const r = await next(e)
514    await beating($)
515    await pruneHandshakes($).catch(() => undefined)
516    return r
517  })
518
519  // session.start does not fire for a plugin a /reload-plugins adds to a running session: the
520  // first row or turn after such a load starts the beat instead
521  on('session.append', async ($, e, next) => {
522    if (beat === null) void beating($).catch(() => undefined)
523    return next(e)
524  }).catch(($, e, next) => next(e))
525
526  on('turn.start', async ($, e, next) => {
527    if (beat === null) void beating($).catch(() => undefined)
528    return next(e)
529  }).catch(($, e, next) => next(e))
530
531  on('agent.spawn', async ($, e, next) => {
532    // a child of an agent in a slot: the same slot and rules, and its folder is inherited
533    if (e.parentAgentId !== undefined) {
534      const parent = await agentOf($, e.parentAgentId)
535      if (parent !== null) {
536        const r = await next(e)
537        // its own type; its transcript is its own too, learned when it starts
538        const { transcript: _t, ...inherited } = parent
539        if (r.agentId !== undefined) await keep($, r.agentId, { ...inherited, agentType: e.subagentType })
540        return r
541      }
542    }
543    const slot = slotLine(e.prompt)
544    if (slot === null) return next(e)
545    const place = await placeOf($, slot)
546    if ('deny' in place) return { deny: `${ME}: ${place.deny}` }
547    const marker = parseMarker(await readText($, `${place.gitDir}/${MARKER_FILE}`))
548    const why = mismatch(marker, e)
549    if (why !== null || marker === null) return { deny: `${ME}: ${why ?? 'no marker'}` }
550    if (marker.role === 'writer' && marker.gateCommands.length > 0) await raiseStall($, marker)
551    const r = await next({ ...e, cwd: slot })
552    if (r.agentId !== undefined) {
553      const { v: _v, ...fields } = marker
554      const attempt = nameParts(e.name)?.attempt
555      await keep($, r.agentId, { ...fields, root: r.agentId, slot, real: place.real, roots: place.roots, gitDir: place.gitDir, agentType: e.subagentType, ...(attempt === undefined ? {} : { attempt }) })
556    }
557    return r
558  }).catch(($, e, next) => (next.called ? next(e) : slotLine(e.prompt) !== null ? { deny: `${ME}: its spawn hook failed, so the agent was not started outside its slot` } : next(e)))
559
560  on('tool.call', async ($, e, next) => {
561    if (e.agentId === undefined) return next(e)
562    const a = await agentOf($, e.agentId)
563    if (a === null) return next(e)
564    const input = e as unknown as Record<string, unknown>
565    const refused = await refusalOf($, a, input, e.tool)
566    if (refused !== null) {
567      await logLine($, a, refused.cause, `${e.tool}: ${refused.reason}`)
568      return { deny: `${ME}: ${refused.reason}` }
569    }
570    if (e.tool === 'Bash') {
571      // the guard judged the agent's own command; what runs has the scratch folder exported first
572      // and, with the container's gate slots on, the gate commands among its words call the wrapper first
573      const scratched = a.scratch !== undefined && typeof input.command === 'string' ? withScratch(input.command, a.scratch) : undefined
574      const prelude = a.gateConcurrency !== undefined && typeof input.command === 'string'
575        ? gatePrelude(a.gateCommands, { wrapper: `${$.plugin.root}/${WRAPPER}`, dir: slotDir(a.loopDir), capacity: a.gateConcurrency, waitMs: agentWaitMs(e.timeout ?? BASH_TIMEOUT_MS, a.gateTimeoutMs), log: `${a.loopDir}/companion.jsonl`, issue: a.issue, life: a.life, seq: a.seq })
576        : null
577      const command = prelude === null ? scratched : `${prelude}\n${scratched ?? (input.command as string)}`
578      if (command !== undefined || e.timeout === undefined) {
579        return next({ ...input, ...(command === undefined ? {} : { command }), ...(e.timeout === undefined ? { timeout: BASH_TIMEOUT_MS } : {}) } as unknown as typeof e)
580      }
581    }
582    return next(e)
583  }).catch(($, e, next) => (next.called || e.agentId === undefined ? next(e) : { deny: `${ME}: its guard failed, so the call is refused` }))
584
585  // the call Claude Code would ask a person about: a mapped agent has nobody to ask
586  on('tool.check', async ($, e, next) => {
587    const r = await next(e)
588    if (r.decision !== 'ask' || e.agentId === undefined) return r
589    const a = await agentOf($, e.agentId)
590    if (a === null) return r
591    return refusePrompt($, a, e, r)
592  }).catch(async ($, e, next) => {
593    // a failure after `ask` came back, for a mapped agent, is still a deny
594    const r = await next(e)
595    if (r.decision !== 'ask' || e.agentId === undefined) return r
596    const a = await agentOf($, e.agentId).catch(() => null)
597    return a === null ? r : { decision: 'deny', reason: promptReason(e.tool, e.input, r) }
598  })
599
600  // a subagent's transcript is beside the session's: the hook's transcript_path is the session's
601  on('classic.SubagentStart', async ($, e, next) => {
602    const transcript = transcriptOf((e as { transcript_path?: unknown }).transcript_path, e.agent_id)
603    if (transcript !== null) {
604      transcripts.delete(e.agent_id)
605      transcripts.set(e.agent_id, transcript)
606      for (const old of [...transcripts.keys()].slice(0, Math.max(0, transcripts.size - TRANSCRIPTS_KEPT))) transcripts.delete(old)
607      const a = await agentOf($, e.agent_id)
608      if (a !== null) await keep($, e.agent_id, { ...a, transcript })
609    }
610    return next(e)
611  }).catch(($, e, next) => next(e))
612
613  // a mapped agent's permission prompt, waiting: written, never answered
614  on('classic.Notification', async ($, e, next) => {
615    const agentId = (e as { agent_id?: unknown }).agent_id
616    if (typeof agentId === 'string' && PROMPT_NOTIFICATIONS.includes(e.notification_type)) {
617      const a = await agentOf($, agentId)
618      if (a !== null) {
619        const data = promptData('prompt_waiting', { ...(await promptFields($, a, agentId)), input: e.message })
620        await eventLine($, a, 'prompt_waiting', data)
621      }
622    }
623    return next(e)
624  }).catch(($, e, next) => next(e))
625
626  on('classic.SubagentStop', async ($, e, next) => {
627    cut.delete(e)
628    const a = await agentOf($, e.agent_id)
629    if (a === null || a.root !== e.agent_id || a.role !== 'writer' || a.gateCommands.length === 0) return next(e)
630    // when the gate asked for its turn, before any wait, with or without a limit; the start line
631    // is written before it asks, so a restart that cuts the gate leaves a trace of it (recovery)
632    const startedAt = new Date(await $.clock.now()).toISOString()
633    const started = ownProcess($).then(process => logLine($, a, 'gate-start', 'the stop gate started', { startedAt, slot: a.slot, gitDir: a.gitDir, ...(process === undefined ? {} : { process }) }))
634    const out = await runStopGate($, a, startedAt, { cut: () => cutOff(e, next) }).finally(() => started.catch(() => undefined))
635    if (out.ran && out.result.result === 'fail') return { block: blockText(out.result, a.slot, a.gateCommands) }
636    return next(e)
637  }).catch(async ($, e, next) => {
638    cut.add(e)
639    // the engine hands the catch the error on its next
640    const err = (next as unknown as { error?: unknown }).error
641    // a gate that could not run is never passed silently
642    try {
643      const a = await agentOf($, e.agent_id)
644      if (a !== null && a.root === e.agent_id && a.role === 'writer' && a.gateCommands.length > 0) await logLine($, a, 'gate-unknown', failedReason(err))
645    } catch {
646      // nothing more can be said
647    }
648    return next(e)
649  })
650}
651
hooks/gate.ts 176 lines
1// The stop gate (docs/factory-loop/v2/SPEC.md 10.6): the repo's gate commands, run in the slot one
2// after another as `a && b` would run them, inside one total budget. A failing command refuses the
3// writer's finish with the command, its exit code and the last lines of its output; a gate that
4// cannot run (its budget spent, or a command that could not start) lets the agent finish and is
5// recorded as unknown, never as a pass. register.ts supplies how a command runs and the clock.
6
7export const TAIL_LINES = 150
8
9// the longest a finished writer waits for its gate's turn when its marker does not say (config.ts
10// gateWaitTimeoutMs)
11export const DEFAULT_GATE_WAIT_MS = 30 * 60_000
12
13// Claude Code ends an async agent that makes no progress for CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS
14// (600000 by default on 2.1.304), aborting the signal of the agent's stop hook, so a gate that waits
15// for its turn and then runs outlives its handler at 10 minutes in all (v2 SPEC 10.6; the gate-queue case
16// of docs/factory-loop/probes/workspace-probe). The companion raises the limit for a writer with gates.
17// (register.ts spells the variable out: the engine wants a literal name in $.env.get and $.env.set)
18// what Claude Code uses when the variable is unset
19export const STALL_DEFAULT_MS = 600_000
20// the room left past a gate's longest wait and run
21export const STALL_MARGIN_MS = 5 * 60_000
22
23// stallBoundMs: how long a writer's stop hook may live: the longest wait for a turn (none without a
24// concurrency limit), the gate's budget and a margin.
25export function stallBoundMs(m: { gateTimeoutMs: number; gateConcurrency?: number; gateWaitTimeoutMs?: number }): number {
26  const wait = m.gateConcurrency === undefined ? 0 : (m.gateWaitTimeoutMs ?? DEFAULT_GATE_WAIT_MS)
27  return wait + m.gateTimeoutMs + STALL_MARGIN_MS
28}
29
30// One command's run: its exit code and its output (standard output then standard error), or the
31// error that kept it from finishing (a timeout, a failure to start).
32// slotWaitMs: the time it waited for one of the container's gate slots first, which is not the gate's
33// own time (v2 SPEC 10.6).
34export type Ran = { exitCode: number; output: string; slotWaitMs?: number } | { error: string; slotWaitMs?: number }
35
36export type GateResult =
37  | { result: 'pass'; ms: number }
38  | { result: 'fail'; ms: number; command: string; exitCode: number; tail: string; failedTests: string[] | null }
39  | { result: 'unknown'; ms: number; why: string }
40
41export type GateIo = {
42  // runs one command in the slot within budgetMs
43  run: (command: string, budgetMs: number) => Promise<Ran>
44  now: () => Promise<number>
45  // whether the engine has cut the hook off (its signal aborted); absent: never known
46  cut?: () => boolean
47}
48
49// The least budget a command is started with; less than this left counts as the budget spent.
50const MIN_BUDGET_MS = 1_000
51
52// runGates: the commands in order, stopping at the first that fails or cannot run.
53// waitMs: the time the gate waited for its turn before runGates started, so a cut gate says how long
54// the engine let the hook live in all.
55export async function runGates(io: GateIo, commands: readonly string[], budgetMs: number, waitMs = 0): Promise<GateResult> {
56  const t0 = await io.now()
57  // the time spent waiting for a container slot is out of the budget
58  let slotWait = 0
59  const spent = async () => (await io.now()) - t0 - slotWait
60  for (const command of commands) {
61    const left = budgetMs - (await spent())
62    if (left < MIN_BUDGET_MS) return { result: 'unknown', ms: await spent(), why: `the gate's budget of ${Math.round(budgetMs / 1000)} s ran out before \`${command}\`` }
63    let ran: Ran
64    try {
65      ran = await io.run(command, left)
66    } catch (err) {
67      ran = { error: err instanceof Error ? err.message : String(err) }
68    }
69    slotWait += ran.slotWaitMs ?? 0
70    if ('error' in ran) {
71      const ms = await spent()
72      // the engine ended the hook (its bound, not the command's): say so, with the wait and the run
73      if (io.cut?.() === true || /\baborted\b/.test(ran.error)) return { result: 'unknown', ms, why: `\`${command}\` did not finish: ${cutReason(waitMs, ms)} (${oneLine(ran.error)})` }
74      return { result: 'unknown', ms, why: `\`${command}\` did not finish: ${oneLine(ran.error)}` }
75    }
76    if (ran.exitCode !== 0) return { result: 'fail', ms: await spent(), command, exitCode: ran.exitCode, tail: tail(ran.output), failedTests: failedTests(ran.output) }
77  }
78  return { result: 'pass', ms: await spent() }
79}
80
81// cutReason: the engine cut the hook off; the time since the gate started is the wait plus the run.
82export function cutReason(waitMs: number, runMs: number): string {
83  const s = (ms: number) => Math.round(ms / 1000)
84  return `the hook was cut off ${s(waitMs + runMs)} s after the gate started (${s(waitMs)} s waiting, ${s(runMs)} s running)`
85}
86
87const MAX_FAILED = 20
88const MAX_NAME = 200
89
90// failedTests: the names of the failing tests in a failed command's full output, or null for none.
91// It reads `FAIL <name>` (scripts/test-reporter.js) and `(fail) <name> [<n>ms]` lines (claude plugin
92// test) after the ANSI escapes and leading blanks are gone, and leaves the job wrappers of
93// scripts/test-job.sh and the test setup failures out; `FAIL test isolation: <what>` is kept.
94export function failedTests(output: string): string[] | null {
95  const names: string[] = []
96  for (const raw of output.split('\n')) {
97    // eslint-disable-next-line no-control-regex
98    const line = raw.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, '').trim()
99    let name: string | null = null
100    let m = /^FAIL (.+)$/.exec(line)
101    if (m !== null) {
102      const n = m[1]!.trim()
103      if (!/^test setup:/.test(n) && !/\(claude plugin validate \/ test\)$/.test(n) && !/^\S+\.test\.sh$/.test(n)) name = n
104    } else if ((m = /^\(fail\) (.+?)(?: \[[0-9.]+ ?m?s\])?$/.exec(line)) !== null) name = m[1]!
105    if (name === null || name === '') continue
106    name = name.slice(0, MAX_NAME)
107    if (!names.includes(name)) names.push(name)
108    if (names.length === MAX_FAILED) break
109  }
110  return names.length === 0 ? null : names
111}
112
113// tail: the last TAIL_LINES lines of an output, without its trailing blank lines.
114export function tail(output: string, lines = TAIL_LINES): string {
115  const all = output.replace(/\s+$/, '').split('\n')
116  return all.slice(-lines).join('\n')
117}
118
119export function oneLine(text: string, max = 300): string {
120  const line = text.replace(/\s+/g, ' ').trim()
121  return line.length > max ? `${line.slice(0, max - 3)}...` : line
122}
123
124// blockText: what the agent is told when the gate refuses its finish.
125export function blockText(r: Extract<GateResult, { result: 'fail' }>, slot: string, commands: readonly string[]): string {
126  return [
127    `The stop gate failed in your slot ${slot}: \`${r.command}\` exited ${r.exitCode}. The gates are ${commands.map(c => `\`${c}\``).join(' then ')}; your step cannot finish while one fails.`,
128    `Fix the failures, commit and push your branch, then finish again. The last ${TAIL_LINES} lines of its output:`,
129    '```',
130    r.tail,
131    '```',
132  ].join('\n')
133}
134
135// gateRecord: the result as factory-gate.json holds it in the slot's git dir, with the slot's HEAD
136// (null: not read), for the decision log and the triage's inputs.
137export function gateRecord(r: GateResult, head: string | null, at: number, commands: readonly string[], waitMs = 0, clean: boolean | null = null, slotWaitMs?: number): Record<string, unknown> {
138  const base = { v: 1, at: new Date(at).toISOString(), head, commands: [...commands], result: r.result, ms: r.ms, waitMs: waitMs + (slotWaitMs ?? 0), ...(slotWaitMs === undefined ? {} : { slotWaitMs }), clean }
139  if (r.result === 'fail') return { ...base, command: r.command, exitCode: r.exitCode, tail: r.tail, failedTests: r.failedTests }
140  if (r.result === 'unknown') return { ...base, why: r.why }
141  return base
142}
143
144// gateLine: every run as one line of the companion's log, which outlives factory-gate.json (the
145// next run overwrites it), so a step's gate runs can be audited. Only `gate-unknown` is an
146// intervention (v2 SPEC 7.2); the loop skips `gate-pass` and `gate-fail`, the gate doing its work.
147// clean: whether the slot's tree was clean when the gate started and its head did not move during it
148// (null: not known). waitMs is the time the gate waited for its turn, plus slotWaitMs, the time it waited for a slot
149// of the container's (absent: the marker has no limit), and concurrency the limit it ran under (null: none).
150// startedAt (ISO, 3 ms digits) is when it asked for its turn, before any wait, and queuedBehind how
151// many held a turn or waited ahead of it then (0: none); the loop writes `gate_run` from these.
152// rerun: the run is the recovery's, of a gate the loop's restart cut, with no agent left to refuse
153// (the field is written only then).
154export function gateLine(
155  r: GateResult,
156  head: string | null,
157  waitMs: number,
158  concurrency: number | null,
159  startedAt: string,
160  queuedBehind: number,
161  clean: boolean | null,
162  rerun = false,
163  mem?: { memStartBytes: number | null; memPeakBytes: number | null; memLimitBytes: number | null; memSamples: number },
164  slotWaitMs?: number,
165): { cause: string; reason: string; fields: Record<string, unknown> } {
166  const fields = { head, ms: r.ms, waitMs: waitMs + (slotWaitMs ?? 0), ...(slotWaitMs === undefined ? {} : { slotWaitMs }), concurrency, startedAt, queuedBehind, clean, ...(rerun ? { rerun: true } : {}), ...(mem === undefined ? {} : mem) }
167  if (r.result === 'pass') return { cause: 'gate-pass', reason: 'the stop gate passed', fields }
168  if (r.result === 'fail') return { cause: 'gate-fail', reason: `the stop gate refused the finish: \`${r.command}\` exited ${r.exitCode}`, fields: { ...fields, command: r.command, exitCode: r.exitCode, failedTests: r.failedTests } }
169  return { cause: 'gate-unknown', reason: `the stop gate could not run: ${r.why}`, fields }
170}
171
172// waitedOut: the result of a gate that never got a turn within the wait cap: unknown, never a pass.
173export function waitedOut(waitMs: number, capMs: number, concurrency: number): GateResult {
174  return { result: 'unknown', ms: 0, why: `it waited ${Math.round(waitMs / 1000)} s for a turn (the cap is ${Math.round(capMs / 1000)} s, ${concurrency} gate${concurrency === 1 ? '' : 's'} at once) and the gate never ran` }
175}
176
hooks/recover.ts 142 lines
1// Recovery of a stop gate the loop's restart cut (docs/factory-loop/v2/SPEC.md 10.6), pure: the reads
2// and the choices. The companion writes `gate-start` as a gate begins, so a log whose newest line for
3// an attempt is a start (or the wait after it) with no settling line, written by a process that is
4// gone, is a gate the restart cut. register.ts supplies the effects (reading files, running the gate,
5// writing the lines), as gate.ts does.
6import type { Marker } from './marker'
7
8// the log is read this far back
9export const RECOVER_WINDOW_MS = 24 * 3_600_000
10
11// the causes that end a gate attempt's open state: a settling line, a re-run or a given-up cut
12const CLOSING = ['gate-pass', 'gate-fail', 'gate-unknown', 'gate-rerun', 'gate-cut']
13
14// One line of the log that concerns a gate attempt, in file order.
15export type GateEntry = {
16  at: number
17  issue: number
18  life: string
19  seq: number
20  cause: string
21  startedAt: string | null
22  slot: string | null
23  gitDir: string | null
24  process: string | null
25}
26
27// A gate attempt still open: its newest line is a start or a wait.
28export type OpenGate = {
29  issue: number
30  life: string
31  seq: number
32  // the time of the start line (of the wait line when no start was written: a companion before
33  // `gate-start`), its startedAt, slot, git dir and process
34  at: number
35  startedAt: string | null
36  slot: string | null
37  gitDir: string | null
38  process: string | null
39}
40
41const natural = (v: unknown): number | null => (typeof v === 'number' && Number.isInteger(v) && v >= 0 ? v : null)
42const text = (v: unknown): string | null => (typeof v === 'string' && v !== '' ? v : null)
43
44// gateEntries: the log's gate lines within the window, in file order; a line that does not read, or names
45// no issue, life and seq, is skipped.
46export function gateEntries(log: string | null, now: number): GateEntry[] {
47  const out: GateEntry[] = []
48  for (const raw of (log ?? '').split('\n')) {
49    if (raw.trim() === '') continue
50    let o: Record<string, unknown>
51    try {
52      const v: unknown = JSON.parse(raw)
53      if (v === null || typeof v !== 'object' || Array.isArray(v)) continue
54      o = v as Record<string, unknown>
55    } catch {
56      continue
57    }
58    const at = typeof o.at === 'string' ? Date.parse(o.at) : typeof o.at === 'number' ? o.at : Number.NaN
59    const issue = natural(o.issue)
60    const seq = natural(o.seq)
61    const cause = text(o.cause)
62    if (!Number.isFinite(at) || now - at > RECOVER_WINDOW_MS || issue === null || issue === 0 || seq === null || cause === null) continue
63    if (cause !== 'gate-start' && cause !== 'gate-wait' && !CLOSING.includes(cause)) continue
64    if (typeof o.life !== 'string' || !/^[0-9a-z]+$/.test(o.life)) continue
65    out.push({ at, issue, life: o.life, seq, cause, startedAt: text(o.startedAt), slot: text(o.slot), gitDir: text(o.gitDir), process: text(o.process) })
66  }
67  return out
68}
69
70// openGates: each (issue, life, seq) whose newest line is `gate-start` or `gate-wait`: no settling line,
71// re-run or cut at or after the start. Its start is the newest `gate-start` of the attempt.
72export function openGates(entries: readonly GateEntry[]): OpenGate[] {
73  const newest = new Map<string, GateEntry>()
74  const starts = new Map<string, GateEntry>()
75  for (const e of entries) {
76    const key = `${e.issue}/${e.life}/${e.seq}`
77    newest.set(key, e)
78    if (e.cause === 'gate-start') starts.set(key, e)
79  }
80  const out: OpenGate[] = []
81  for (const [key, last] of newest) {
82    if (last.cause !== 'gate-start' && last.cause !== 'gate-wait') continue
83    const s = starts.get(key) ?? last
84    out.push({ issue: s.issue, life: s.life, seq: s.seq, at: s.at, startedAt: s.startedAt, slot: s.slot, gitDir: s.gitDir, process: s.process })
85  }
86  return out
87}
88
89// bootMs: the machine's boot time from /proc/stat's `btime` line (seconds), or null.
90export function bootMs(procStat: string | null): number | null {
91  const m = /^btime (\d+)$/m.exec(procStat ?? '')
92  return m === null ? null : Number(m[1]) * 1000
93}
94
95// startMs: when the process /proc/<pid>/stat describes started, from its field 22 (clock ticks since
96// boot, 100 a second) and the boot time; null when either does not read.
97export function startMs(stat: string | null, boot: number | null): number | null {
98  const start = stat?.slice(stat.lastIndexOf(') ') + 2).split(' ')[19] ?? ''
99  return boot !== null && /^\d+$/.test(start) ? boot + Number(start) * 10 : null
100}
101
102// isDead: whether the process that wrote an open gate's start is gone. `current` is the id
103// (`pid:start`) /proc/<pid>/stat gives now for its pid (undefined: no such process), so a pid given to
104// a later process is dead too. A line with no process (a companion before it) is dead only when it was
105// written before this process started (`ownStart`; null when not known: not dead).
106export function isDead(open: Pick<OpenGate, 'at' | 'process'>, current: string | undefined, ownStart: number | null): boolean {
107  if (open.process === null) return ownStart !== null && open.at < ownStart
108  return current !== open.process
109}
110
111// pidOf: the pid of a process id, or null when it is not `pid:start`.
112export function pidOf(process: string | null): string | null {
113  const m = /^(\d+):\d+$/.exec(process ?? '')
114  return m === null ? null : (m[1] as string)
115}
116
117export type Verdict = { rerun: true } | { rerun: false; why: string }
118
119// judge: whether a dead open gate is run again. Only when the slot's marker still names its issue, life and
120// seq as a writer with gate commands; the why says what else it found.
121export function judge(open: OpenGate, marker: Marker | null): Verdict {
122  if (open.slot === null || open.gitDir === null || !open.slot.startsWith('/') || !open.gitDir.startsWith('/')) return { rerun: false, why: 'its start line names no slot and git dir (a companion before gate-start)' }
123  if (marker === null) return { rerun: false, why: 'the slot has no readable step marker any more' }
124  if (marker.issue !== open.issue || marker.life !== open.life || marker.seq !== open.seq) return { rerun: false, why: `the slot's marker names #${marker.issue} life ${marker.life} seq ${marker.seq}, not this attempt` }
125  if (marker.role !== 'writer') return { rerun: false, why: `the slot's marker names a ${marker.role}, not a writer` }
126  if (marker.gateCommands.length === 0) return { rerun: false, why: "the slot's marker has no gate commands" }
127  return { rerun: true }
128}
129
130// leaseHeld: whether the act lock's text is a lease of this session that has not expired.
131export function leaseHeld(lock: string | null, session: string, now: number): boolean {
132  if (lock === null) return false
133  try {
134    const v: unknown = JSON.parse(lock)
135    if (v === null || typeof v !== 'object' || Array.isArray(v)) return false
136    const o = v as Record<string, unknown>
137    return o.session === session && typeof o.expiresAt === 'number' && o.expiresAt > now
138  } catch {
139    return false
140  }
141}
142
hooks/memory.ts 79 lines
1// The memory a stop gate adds, sampled from the container's cgroup (v2 SPEC 10.6; gate_run.v1
2// mem_* fields). A measurement only: nothing here throws, and a reading that fails counts no
3// sample. memory.peak is not used: it holds the container's lifetime peak, not this run's.
4
5// the cgroup directory unless FACTORY_GATE_CGROUP_DIR (a test hook, like heartbeat-loop's
6// HEARTBEAT_CGROUP_DIR) names another
7export const DEFAULT_CGROUP_DIR = '/sys/fs/cgroup'
8export const SAMPLE_EVERY_MS = 5_000
9
10// parseCurrent: memory.current's bytes, or null for anything that is not a non-negative safe integer.
11export function parseCurrent(text: string | null): number | null {
12  if (text === null) return null
13  const t = text.trim()
14  if (!/^[0-9]+$/.test(t)) return null
15  const n = Number(t)
16  return Number.isSafeInteger(n) ? n : null
17}
18
19// parseMax: memory.max's bytes; null for "max" (no limit) and for a missing or bad file.
20export const parseMax = parseCurrent
21
22export type MemReading = { current: string | null; max: string | null }
23export type MemFields = { memStartBytes: number | null; memPeakBytes: number | null; memLimitBytes: number | null; memSamples: number }
24
25export type MemoryIo = {
26  read: () => Promise<MemReading>
27  every: (ms: number, fn: () => void) => { cancel: () => void }
28}
29
30// startMemorySampler: reads once now, then every SAMPLE_EVERY_MS until stop(), which cancels the
31// timer, reads once more and returns the start, the peak, the limit and the sample count.
32export async function startMemorySampler(io: MemoryIo): Promise<{ stop: () => Promise<MemFields> }> {
33  let start: number | null = null
34  let peak: number | null = null
35  let limit: number | null = null
36  let samples = 0
37  let stopped = false
38  const sample = async (): Promise<void> => {
39    let r: MemReading | null
40    try {
41      // the engine bounds a host read itself; a throw is a reading that failed
42      r = await io.read()
43    } catch {
44      r = null
45    }
46    if (r === null) return
47    const cur = parseCurrent(r.current)
48    if (cur === null) return
49    samples++
50    if (start === null) start = cur
51    if (peak === null || cur > peak) peak = cur
52    limit = parseMax(r.max) ?? limit
53  }
54  await sample()
55  let timer: { cancel: () => void } | null = null
56  try {
57    timer = io.every(SAMPLE_EVERY_MS, () => {
58      if (!stopped) void sample()
59    })
60  } catch {
61    timer = null
62  }
63  let result: MemFields | null = null
64  return {
65    stop: async () => {
66      if (result !== null) return result
67      stopped = true
68      try {
69        timer?.cancel()
70      } catch {
71        // a timer that will not cancel must not fail the gate
72      }
73      await sample()
74      result = { memStartBytes: start, memPeakBytes: peak, memLimitBytes: limit, memSamples: samples }
75      return result
76    },
77  }
78}
79
hooks/window.ts 29 lines
1// The session's context window size (docs/metrics.md, images/base/heartbeat-state): one file per
2// session id in DEV_CONTEXT_WINDOW_DIR (else /tmp/dev-context-window), which the worker heartbeat
3// pushes with the session's liveness as sessions[].context_window. The factory-hud mod writes the
4// same file in the same format; a loop workspace always has this plugin, so it records it too.
5import type { EngineInterface } from 'claude-code'
6
7// windowText: the file's text for a window, or undefined when it is not a positive integer.
8export function windowText(window: unknown): string | undefined {
9  return typeof window === 'number' && Number.isInteger(window) && window > 0 ? `${window}\n` : undefined
10}
11
12let recorded = ''
13
14// recordWindow: written only when the session id or the window changes; a failed read or write is
15// dropped, so a missing window stays a gap in the fleet data.
16export async function recordWindow($: EngineInterface): Promise<void> {
17  try {
18    const text = windowText((await $.session.usage()).context?.window)
19    if (text === undefined) return
20    const id = await $.session.id()
21    if (recorded === `${id}=${text}`) return
22    const dir = (await $.env.get('DEV_CONTEXT_WINDOW_DIR')) || '/tmp/dev-context-window'
23    await $.fs.write(`${dir}/${id}`, text)
24    recorded = `${id}=${text}`
25  } catch {
26    // dropped
27  }
28}
29
hooks/guard.ts 238 lines
1// The write guard's rules (docs/factory-loop/v2/SPEC.md 10.4), pure: what a loop agent may not
2// do, by its role, with the reason the agent is told. register.ts applies them in its tool.call
3// hook to the agents the loop started in a slot, and to their children.
4//
5// - File tools: a writer writes inside its slot or outside the repository (a scratch file in
6//   the step's scratch folder); a reader writes nowhere in the repository. The repository is the slot and the main
7//   checkout, whose tree holds the pool's other slots.
8// - Every loop agent: no GitHub writes (the loop owns PRs, issues, labels and re-runs), no
9//   axi, no push to a remote but origin, no call in the background (Bash or
10//   Agent), no isolated Agent call.
11// - A writer pushes only its branch to origin, never by force, creates no branch and no worktree.
12// - A reader neither commits nor pushes.
13import { program, simpleCommands } from './shell'
14
15export type Role = 'writer' | 'reader'
16
17// What the guard knows of an agent: its slot, its role and branch (the step marker's), and the
18// repository's roots (the slot, and the main checkout when the slot is one of its worktrees).
19export type Guarded = { slot: string; role: Role; branch: string; roots: string[] }
20
21export type Cause = 'guard:write' | 'guard:push' | 'guard:command'
22export type Refusal = { cause: Cause; reason: string }
23
24export const FILE_TOOLS = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'] as const
25
26// --- paths ------------------------------------------------------------------------------------------
27
28// normalize: an absolute path with no `.`, `..` or doubled `/`; a relative one is resolved
29// against base first (Write's file_path can arrive relative).
30export function normalize(path: string, base: string): string {
31  const out: string[] = []
32  for (const part of (path.startsWith('/') ? path : `${base}/${path}`).split('/')) {
33    if (part === '' || part === '.') continue
34    if (part === '..') out.pop()
35    else out.push(part)
36  }
37  return `/${out.join('/')}`
38}
39
40export function within(path: string, root: string): boolean {
41  return root === '/' || path === root || path.startsWith(`${root}/`)
42}
43
44// fileRefusal: a file tool's write to path (absolute, normalized), or null when it may go ahead.
45export function fileRefusal(g: Guarded, path: string): Refusal | null {
46  const inRepo = within(path, g.slot) || g.roots.some(r => within(path, r))
47  if (g.role === 'writer') {
48    if (within(path, g.slot) || !inRepo) return null
49    return { cause: 'guard:write', reason: `${path} is outside your slot ${g.slot}: write only inside it` }
50  }
51  if (!inRepo) return null
52  return { cause: 'guard:write', reason: `${path} is in the repository, and this step reads only: write nowhere in ${g.slot} or another checkout (a scratch file outside the repository is fine)` }
53}
54
55// --- commands ---------------------------------------------------------------------------------------
56
57// The gh commands that write to GitHub, by group, aliases included (`gh pr new` is `gh pr
58// create`): the loop owns these (10.4). `*`: every subcommand of the group.
59const GH_WRITES: Record<string, readonly string[] | '*'> = {
60  pr: ['create', 'new', 'edit', 'merge', 'close', 'reopen', 'review', 'update-branch', 'comment', 'ready', 'revert', 'lock', 'unlock'],
61  issue: ['create', 'new', 'edit', 'close', 'comment', 'reopen', 'delete', 'transfer', 'lock', 'unlock', 'pin', 'unpin', 'develop'],
62  label: '*',
63  run: ['rerun', 'cancel', 'delete'],
64  workflow: ['run', 'enable', 'disable'],
65  release: ['create', 'new', 'edit', 'delete', 'upload', 'delete-asset'],
66  repo: ['create', 'new', 'edit', 'rename', 'archive', 'unarchive', 'delete', 'sync', 'fork', 'deploy-key'],
67  secret: '*',
68  variable: '*',
69  cache: ['delete'],
70  gist: ['create', 'new', 'edit', 'rename', 'delete'],
71}
72const GH_VALUED = ['-R', '--repo', '-H', '--header', '-q', '--jq', '-t', '--template', '-p', '--preview', '--hostname', '--cache']
73const WRITE_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE']
74const FIELD_FLAGS = ['-f', '-F', '--field', '--raw-field', '--input']
75const LOOP_TOOLS = ['axi']
76
77// The git options that come before the subcommand and take a value.
78const GIT_VALUED = ['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--config-env']
79
80// gitArgs: a git command's subcommand and its arguments, past git's own options; null when argv
81// runs no git subcommand.
82function gitArgs(argv: readonly string[]): string[] | null {
83  let i = 1
84  while (i < argv.length && (argv[i] ?? '').startsWith('-')) i += GIT_VALUED.includes(argv[i] ?? '') ? 2 : 1
85  return i < argv.length ? argv.slice(i) : null
86}
87
88function ghArgs(argv: readonly string[]): string[] {
89  const out: string[] = []
90  for (let i = 1; i < argv.length; i++) {
91    const a = argv[i] ?? ''
92    if (GH_VALUED.includes(a)) i++
93    else if (!a.startsWith('-')) out.push(a)
94  }
95  return out
96}
97
98// ghWrite: why a gh command writes to GitHub, or null.
99function ghWrite(argv: readonly string[]): string | null {
100  const [group, sub] = ghArgs(argv)
101  if (group === 'api') {
102    let method: string | null = null
103    let fields = false
104    for (let i = 1; i < argv.length; i++) {
105      const a = argv[i] ?? ''
106      if (a === '-X' || a === '--method') method = (argv[i + 1] ?? '').toUpperCase()
107      else if (/^-X./.test(a)) method = a.slice(2).toUpperCase()
108      else if (a.startsWith('--method=')) method = a.slice('--method='.length).toUpperCase()
109      else if (FIELD_FLAGS.includes(a) || FIELD_FLAGS.some(f => a.startsWith(`${f}=`)) || /^-[fF]./.test(a)) fields = true
110    }
111    if (method !== null && WRITE_METHODS.includes(method)) return `gh api with method ${method}`
112    if (fields && method !== 'GET') return 'gh api with field flags (a write)'
113    return null
114  }
115  const writes = group === undefined ? undefined : GH_WRITES[group]
116  if (writes === undefined) return null
117  if (writes === '*' || (sub !== undefined && writes.includes(sub))) return `gh ${group}${writes === '*' ? '' : ` ${sub}`}`
118  return null
119}
120
121// A push's parts: the remote (origin when none is named), its refspecs, and its flags.
122type Push = { remote: string; refspecs: string[]; flags: string[] }
123
124const PUSH_VALUED = ['-o', '--push-option', '--receive-pack', '--exec']
125const PUSH_OK_FLAGS = ['-u', '--set-upstream', '-v', '--verbose', '-q', '--quiet', '--porcelain', '--progress', '--no-progress', '-n', '--dry-run', '--no-verify', '--verify', '--atomic']
126
127function pushOf(args: readonly string[]): Push {
128  const flags: string[] = []
129  const rest: string[] = []
130  let remote: string | null = null
131  for (let i = 1; i < args.length; i++) {
132    const a = args[i] ?? ''
133    if (a.startsWith('--repo=')) remote = a.slice('--repo='.length)
134    else if (a === '--repo') remote = args[++i] ?? ''
135    else if (PUSH_VALUED.includes(a)) i++
136    else if (/^-[a-zA-Z]{2,}$/.test(a)) flags.push(...[...a.slice(1)].map(ch => `-${ch}`))
137    else if (a.startsWith('-')) flags.push(a)
138    else rest.push(a)
139  }
140  if (remote === null) remote = rest.shift() ?? 'origin'
141  return { remote, refspecs: rest, flags }
142}
143
144// pushRefusal: why a writer's push may not go ahead, or null. head is the slot's current branch
145// (null: unknown), read only when the push names no refspec or pushes HEAD.
146function pushRefusal(g: Guarded, p: Push, head: string | null): string | null {
147  const force = p.flags.find(f => f === '-f' || f === '--force' || f.startsWith('--force-with-lease') || f === '--force-if-includes')
148  if (force !== undefined) return `a force push (${force}) is refused: push your branch ${g.branch} without force`
149  const other = p.flags.find(f => !PUSH_OK_FLAGS.includes(f))
150  if (other !== undefined) return `git push ${other} is refused: push only your branch, as git push origin ${g.branch}`
151  const specs = p.refspecs.length === 0 ? [null] : p.refspecs
152  for (const spec of specs) {
153    if (spec !== null && spec.startsWith('+')) return `a force push (${spec}) is refused: push your branch ${g.branch} without force`
154    let dst = spec === null ? 'HEAD' : spec.includes(':') ? spec.slice(spec.indexOf(':') + 1) : spec
155    if (spec !== null && spec.startsWith(':')) return `deleting a remote ref (${spec}) is refused`
156    if (dst === 'HEAD') dst = head ?? 'HEAD'
157    dst = dst.replace(/^refs\/heads\//, '')
158    if (dst !== g.branch) return `a push to ${dst === 'HEAD' ? 'the current branch, which is not known' : dst} is refused: push only your branch, as git push origin ${g.branch}`
159  }
160  return null
161}
162
163// needsHead: whether a command's pushes need the slot's current branch to be judged.
164export function needsHead(command: string): boolean {
165  return simpleCommands(command).some(argv => {
166    if (program(argv) !== 'git') return false
167    const args = gitArgs(argv)
168    if (args === null || args[0] !== 'push') return false
169    const p = pushOf(args)
170    return p.refspecs.length === 0 || p.refspecs.some(s => s === 'HEAD' || s.endsWith(':HEAD'))
171  })
172}
173
174// The git branch options that read, delete or set an upstream rather than create a branch.
175const BRANCH_READS = ['-l', '--list', '-a', '--all', '-r', '--remotes', '-v', '-vv', '--verbose', '--show-current', '--contains', '--no-contains', '--merged', '--no-merged', '--points-at', '--format', '--sort', '-d', '-D', '--delete', '-u', '--set-upstream-to', '--unset-upstream', '--edit-description', '--column', '--no-column', '--color', '--no-color']
176const BRANCH_MAKES = ['-m', '-M', '-c', '-C', '--move', '--copy', '-f', '--force']
177
178// branchMade: the branch command a writer may not run (creating, renaming or copying a branch, or
179// a worktree), or null.
180function branchMade(args: readonly string[]): string | null {
181  const [sub, ...rest] = args
182  if (sub === 'switch' && rest.some(a => ['-c', '-C', '--create', '--force-create', '--orphan'].includes(a) || /^--(force-)?create=/.test(a))) return 'git switch -c'
183  if (sub === 'checkout' && rest.some(a => ['-b', '-B', '--orphan'].includes(a))) return 'git checkout -b'
184  if (sub === 'branch') {
185    if (rest.some(a => BRANCH_MAKES.includes(a))) return 'git branch -m/-c'
186    const named = rest.some(a => !a.startsWith('-'))
187    if (named && !rest.some(a => BRANCH_READS.includes(a) || BRANCH_READS.some(r => a.startsWith(`${r}=`)))) return 'git branch <name>'
188  }
189  if (sub === 'worktree' && rest[0] !== 'list') return `git worktree${rest[0] === undefined ? '' : ` ${rest[0]}`}`
190  return null
191}
192
193// bashRefusal: the first rule a Bash command breaks, or null. head: the slot's current branch,
194// which the hook reads when needsHead says a push needs it.
195export function bashRefusal(g: Guarded, command: string, head: string | null = null): Refusal | null {
196  for (const argv of simpleCommands(command)) {
197    const name = program(argv)
198    if (LOOP_TOOLS.includes(name)) return { cause: 'guard:command', reason: `${name} is not used by the factory loop's agents: the loop reviews, opens the PR and merges itself` }
199    if (name === 'gh') {
200      const write = ghWrite(argv)
201      if (write !== null) return { cause: 'guard:command', reason: `${write} is refused: the factory loop owns GitHub writes (PRs, issues, labels, re-runs); say what you need in your answer instead` }
202      continue
203    }
204    if (name !== 'git') continue
205    const args = gitArgs(argv)
206    if (args === null) continue
207    if (args[0] === 'push') {
208      const p = pushOf(args)
209      if (g.role === 'reader') return { cause: 'guard:push', reason: 'git push is refused: this step reads only' }
210      if (p.remote !== 'origin') return { cause: 'guard:push', reason: `a push to ${p.remote} is refused: push only to origin, as git push origin ${g.branch}` }
211      const why = pushRefusal(g, p, head)
212      if (why !== null) return { cause: 'guard:push', reason: why }
213      continue
214    }
215    if (g.role === 'reader' && args[0] === 'commit') return { cause: 'guard:command', reason: 'git commit is refused: this step reads only' }
216    if (g.role === 'writer') {
217      const made = branchMade(args)
218      if (made !== null) return { cause: 'guard:command', reason: `${made} is refused: work on your branch ${g.branch} in your slot ${g.slot}` }
219    }
220  }
221  return null
222}
223
224// backgroundRefusal: any call in the background, Bash or Agent, so an agent neither ends its turn
225// while work it started still runs (failures/F13) nor sits polling for it (R4-O4); a command runs
226// in the foreground under its 10-minute timeout (10.5).
227export function backgroundRefusal(tool: string, input: { run_in_background?: unknown }): Refusal | null {
228  if (input.run_in_background !== true) return null
229  return { cause: 'guard:command', reason: `${tool} in the background is refused: run it in the foreground and wait for it, a command with a timeout of up to 600000 ms` }
230}
231
232// agentRefusal: an Agent call with an isolation: `remote` always runs in the background, and
233// `worktree` makes a git worktree, which a writer may not.
234export function agentRefusal(input: { isolation?: unknown }): Refusal | null {
235  if (input.isolation === undefined || input.isolation === null) return null
236  return { cause: 'guard:command', reason: `an Agent call with isolation ${JSON.stringify(input.isolation)} is refused: leave isolation out, run it in the foreground in your own folder and wait for its answer` }
237}
238
hooks/marker.ts 104 lines
1// The spawn's slot line and the slot's step marker (docs/factory-loop/v2/SPEC.md 10.2, 10.3),
2// pure. The loop's prompt opens with `factory-slot: <absolute slot path>`; factory-slot prepare
3// wrote the marker `factory-step.json` into that slot's git dir. The companion starts the agent
4// there only when the two agree with the spawn: the marker's issue, seq and step are the ones the
5// agent's name carries (`<step>-<N>-s<seq>-a<attempt>`, D-11), and its type is the loop's.
6import { normalize } from './guard'
7import type { Role } from './guard'
8import { scratchOk } from './scratch'
9
10export const MARKER_FILE = 'factory-step.json'
11const STEPS = ['design', 'build', 'review', 'fix', 'triage'] as const
12export type Step = (typeof STEPS)[number]
13
14// The marker as the loop writes it (plugins/factory-loop/hooks/v2/types.ts StepMarker).
15export type Marker = {
16  v: 1
17  repo: string
18  issue: number
19  life: string
20  seq: number
21  step: Step
22  role: Role
23  branch: string
24  // the issue's PR, null when it has none or the loop that wrote the marker did not say
25  pr: number | null
26  gateCommands: string[]
27  gateTimeoutMs: number
28  loopDir: string
29  // the step attempt's scratch folder, under <loopDir>/scratch/; absent in an older marker, or when
30  // the one it names is not a usable path
31  scratch?: string
32  // the stop gates the companion runs at once, and the longest a finished writer waits for its turn;
33  // absent in an older marker, or when the value is not a whole number of at least 1: no limit, and
34  // the default wait
35  gateConcurrency?: number
36  gateWaitTimeoutMs?: number
37}
38
39// slotLine: the slot the prompt's first line names, or null when it names none. The path must be
40// absolute and plain (no `.` or `..` parts, no doubled or trailing `/`).
41export function slotLine(prompt: string): string | null {
42  const first = (prompt.split('\n', 1)[0] ?? '').replace(/\r$/, '')
43  const m = /^factory-slot: (\/.*\S)\s*$/.exec(first)
44  const path = m?.[1]
45  if (path === undefined) return null
46  return normalize(path, '/') === path ? path : null
47}
48
49const int = (v: unknown, min: number): v is number => typeof v === 'number' && Number.isInteger(v) && v >= min
50const str = (v: unknown): v is string => typeof v === 'string' && v !== ''
51
52// parseMarker: the marker file's text as a Marker; null when it does not read.
53export function parseMarker(text: string | null): Marker | null {
54  if (text === null) return null
55  let o: Record<string, unknown>
56  try {
57    const v: unknown = JSON.parse(text)
58    if (v === null || typeof v !== 'object' || Array.isArray(v)) return null
59    o = v as Record<string, unknown>
60  } catch {
61    return null
62  }
63  if (o.v !== 1 || !str(o.repo) || !int(o.issue, 1) || !str(o.life) || !/^[0-9a-z]+$/.test(o.life) || !int(o.seq, 0)) return null
64  if (!STEPS.includes(o.step as Step) || (o.role !== 'writer' && o.role !== 'reader') || !str(o.branch)) return null
65  if (!Array.isArray(o.gateCommands) || !o.gateCommands.every(c => typeof c === 'string')) return null
66  if (!int(o.gateTimeoutMs, 1) || !str(o.loopDir) || !o.loopDir.startsWith('/')) return null
67  const loopDir = o.loopDir.replace(/\/+$/, '')
68  return {
69    v: 1,
70    repo: o.repo,
71    issue: o.issue,
72    life: o.life,
73    seq: o.seq,
74    step: o.step as Step,
75    role: o.role,
76    branch: o.branch,
77    pr: int(o.pr, 1) ? o.pr : null,
78    gateCommands: (o.gateCommands as string[]).map(c => c.trim()).filter(c => c !== ''),
79    gateTimeoutMs: o.gateTimeoutMs,
80    loopDir,
81    ...(scratchOk(o.scratch, loopDir) ? { scratch: o.scratch } : {}),
82    ...(int(o.gateConcurrency, 1) ? { gateConcurrency: o.gateConcurrency } : {}),
83    ...(int(o.gateWaitTimeoutMs, 1) ? { gateWaitTimeoutMs: o.gateWaitTimeoutMs } : {}),
84  }
85}
86
87// nameParts: what the loop puts in an agent step's name (v2/steps.ts): `<step>-<N>-s<seq>-a<k>`.
88export function nameParts(name: string | undefined): { step: string; issue: number; seq: number; attempt: number } | null {
89  const m = /^([a-z]+)-(\d+)-s(\d+)-a(\d+)$/.exec(name ?? '')
90  return m === null ? null : { step: m[1] ?? '', issue: Number(m[2]), seq: Number(m[3]), attempt: Number(m[4]) }
91}
92
93// mismatch: why the marker does not belong to this spawn, or null when it does.
94export function mismatch(marker: Marker | null, spawn: { name?: string; subagentType: string }): string | null {
95  if (marker === null) return `the slot has no readable step marker (${MARKER_FILE} in its git dir)`
96  if (!spawn.subagentType.startsWith('factory-loop:')) return `${spawn.subagentType} is not one of the factory loop's agents`
97  const n = nameParts(spawn.name)
98  if (n === null) return `the agent's name ${spawn.name ?? '(none)'} does not say its step, issue and seq`
99  if (n.issue !== marker.issue || n.seq !== marker.seq || n.step !== marker.step) {
100    return `the slot is prepared for ${marker.step} of #${marker.issue} seq ${marker.seq}, not ${n.step} of #${n.issue} seq ${n.seq}`
101  }
102  return null
103}
104
hooks/prompt.ts 126 lines
1// Prompts nobody answers (docs/factory-loop/v2/SPEC.md 10.10), pure: the reason a refused call is
2// given, and the data of the native `prompt_denied` and `prompt_waiting` events (written with
3// `callum-flow-event --type`, docs/factory-events/schemas), so the rules test covers them without
4// the engine.
5import { oneLine } from './gate'
6
7// the most of a call's input an event carries (a Bash command, else the input as JSON)
8export const INPUT_CLIP = 2000
9const ME = 'factory-loop-workspace'
10
11// clip: at most `max` characters.
12export function clip(text: string, max = INPUT_CLIP): string {
13  return text.length > max ? text.slice(0, max) : text
14}
15
16// What Claude Code's own check said (the result of `next(e)` for a tool.check).
17export type Decided = { reason?: unknown; rule?: unknown; decider?: unknown }
18
19const say = (v: unknown): string | null => {
20  if (v === undefined || v === null || v === '') return null
21  return typeof v === 'string' ? v : JSON.stringify(v)
22}
23
24// whyOf: Claude Code's reason, rule and decider as one line; null when it said none.
25export function whyOf(d: Decided): string | null {
26  const parts = [say(d.reason), say(d.rule) === null ? null : `rule ${say(d.rule)}`, say(d.decider) === null ? null : `decided by ${say(d.decider)}`]
27  const text = parts.filter((p): p is string => p !== null).join('; ')
28  return text === '' ? null : oneLine(text, 500)
29}
30
31// inputOf: what the event says of the call: a Bash command, else the input as JSON; clipped.
32export function inputOf(tool: string, input: unknown): string {
33  const command = tool === 'Bash' && input !== null && typeof input === 'object' ? (input as Record<string, unknown>).command : undefined
34  if (typeof command === 'string') return clip(command)
35  try {
36    return clip(JSON.stringify(input) ?? '')
37  } catch {
38    return ''
39  }
40}
41
42// a `rm` of a glob under a variable that is not guarded with `:?`: if the variable is empty it is
43// `rm -f /*`. Group 1: the variable's name.
44const VARIABLE_GLOB = /\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))[^\s;|&]*[*?]/
45
46// unguardedGlob: the variable of a Bash command that removes a glob under an unguarded variable;
47// null for any other call.
48export function unguardedGlob(tool: string, input: unknown): string | null {
49  const command = inputOf(tool, input)
50  if (tool !== 'Bash' || !/\brm\b/.test(command)) return null
51  const m = VARIABLE_GLOB.exec(command)
52  return m === null ? null : (m[1] ?? m[2] ?? null)
53}
54
55// rmHint: the safe rewrite, with the command's own variable.
56export const rmHint = (name: string): string => `Never \`rm\` a glob under an unguarded variable: use \`"\${${name}:?}"/*\` or a literal path.`
57
58// promptReason: what the agent is told when its call is refused, because Claude Code would have
59// asked a person.
60export function promptReason(tool: string, input: unknown, decided: Decided): string {
61  const why = whyOf(decided)
62  const glob = unguardedGlob(tool, input)
63  return [
64    `${ME}: this ${tool} call would wait on a person nobody watches, so it is refused.`,
65    why === null ? null : `Claude Code's own reason: ${why}.`,
66    glob === null ? null : rmHint(glob),
67    'Find another way to do it or, failing that, end your step saying what you needed.',
68  ]
69    .filter((p): p is string => p !== null)
70    .join(' ')
71}
72
73// The facts of a prompt event, each null when unknown.
74export type PromptFields = {
75  life?: string | null
76  seq?: number | null
77  step?: string | null
78  attempt?: number | null
79  agent?: string | null
80  agent_type?: string | null
81  tool?: string | null
82  slot?: string | null
83  session?: string | null
84  transcript?: string | null
85  why?: string | null
86  input?: string | null
87  branch?: string | null
88  pr?: number | null
89}
90
91const orNull = <T>(v: T | null | undefined): T | null => (v === undefined || v === '' ? null : v)
92
93// promptData: the data of a `prompt_denied` or `prompt_waiting` event, under the schema's names,
94// with every required key of the type (an unknown value null, an empty agent id null). A waiting
95// prompt has no tool and no ask_reason: its message is the tool_input, clipped like a deny's.
96export function promptData(kind: 'prompt_denied' | 'prompt_waiting', f: PromptFields): Record<string, string | number | null> {
97  const denied = kind === 'prompt_denied'
98  const input = orNull(f.input)
99  return {
100    life: orNull(f.life) ?? null,
101    seq: orNull(f.seq) ?? null,
102    step: orNull(f.step) ?? null,
103    attempt: orNull(f.attempt) ?? null,
104    agent_id: orNull(f.agent) ?? null,
105    agent_type: orNull(f.agent_type) ?? null,
106    tool_name: denied ? (orNull(f.tool) ?? null) : null,
107    tool_input: input === null ? null : clip(input),
108    ...(denied ? { ask_reason: orNull(f.why) ?? null } : {}),
109    slot: orNull(f.slot) ?? null,
110    session: orNull(f.session) ?? null,
111    transcript: orNull(f.transcript) ?? null,
112    branch: orNull(f.branch) ?? null,
113    pr: orNull(f.pr) ?? null,
114  }
115}
116
117// transcriptOf: an agent's own transcript, beside the session's:
118// <session transcript without .jsonl>/subagents/agent-<id>.jsonl. null: the session's is not known.
119export function transcriptOf(sessionTranscript: unknown, agentId: string): string | null {
120  if (typeof sessionTranscript !== 'string' || sessionTranscript === '') return null
121  return `${sessionTranscript.replace(/\.jsonl$/, '')}/subagents/agent-${agentId}.jsonl`
122}
123
124// the notification types that mean a prompt waits on a person
125export const PROMPT_NOTIFICATIONS: readonly string[] = ['permission_prompt', 'worker_permission_prompt']
126
hooks/scratch.ts 24 lines
1// The step's scratch folder (docs/factory-loop/v2/SPEC.md 10.2, 10.5), pure. factory-slot prepare
2// makes <loop dir>/scratch/<N>-<life>-s<seq> and writes its path into the step marker as `scratch`;
3// the companion exports it as TMPDIR, TMP and TEMP into every Bash call of a mapped agent, because
4// `$.env.set` is session-wide and gives no agent a folder of its own.
5import { normalize } from './guard'
6
7// scratchOk: whether a marker's `scratch` is usable: absolute, normalized, and under
8// <loopDir>/scratch/ (below it, never the folder itself).
9export function scratchOk(scratch: unknown, loopDir: string): scratch is string {
10  if (typeof scratch !== 'string' || !scratch.startsWith('/') || normalize(scratch, '/') !== scratch) return false
11  const root = `${loopDir.replace(/\/+$/, '')}/scratch/`
12  return scratch.startsWith(root) && scratch.length > root.length
13}
14
15export const quoted = (s: string): string => `'${s.replace(/'/g, `'\\''`)}'`
16
17// withScratch: the Bash command, run with TMPDIR, TMP and TEMP set to the folder. The export is
18// its own line, so the command's text runs unchanged after it, here-documents and multi-line
19// commands included.
20export function withScratch(command: string, scratch: string): string {
21  const s = quoted(scratch)
22  return `export TMPDIR=${s} TMP=${s} TEMP=${s}\n${command}`
23}
24
hooks/slots.ts 115 lines
1// The container's gate slots (docs/factory-loop/v2/SPEC.md 10.6, "Turns"), pure. The in-process turns
2// limit the stop gates of one session; the slots are <loopDir>/gate-slots/<i>.lock files held through
3// flock(1) by bin/factory-gate-slot, so the stop gates and the writers' own gate-command runs share
4// one container-wide limit that the kernel frees when a holder dies.
5import { quoted } from './scratch'
6
7export const SLOT_DIR = 'gate-slots'
8export const WRAPPER = 'bin/factory-gate-slot'
9// the exit code of a refusal: no slot was free in time (sysexits EX_TEMPFAIL)
10export const BUSY_EXIT = 75
11
12export function slotDir(loopDir: string): string {
13  return `${loopDir.replace(/\/+$/, '')}/${SLOT_DIR}`
14}
15
16// agentWaitMs: how long an agent's gate command waits for a slot: what the call's own timeout leaves
17// past the gate's budget, so the wait and the run fit inside the call. At the defaults that is none.
18export function agentWaitMs(timeoutMs: number, gateTimeoutMs: number): number {
19  return Math.max(0, timeoutMs - gateTimeoutMs)
20}
21
22const PROGRAM = /^[A-Za-z_][A-Za-z0-9_]*$/
23const WORD = /^[A-Za-z0-9_.\/:=@%+,-]+$/
24
25export type PreludeOpts = {
26  // the wrapper's absolute path
27  wrapper: string
28  dir: string
29  capacity: number
30  waitMs: number
31  log: string
32  issue: number
33  life: string
34  seq: number
35}
36
37// gatePrelude: one shell line that defines a function for each program among the gate commands. The
38// function runs the wrapper when the words of its own call are the rest of a gate command (`npm test`),
39// and goes on to the program otherwise (`npm test -- x`). A function is called by command name only,
40// so quoted text never calls it. A gate command whose program is not a plain identifier, or that has
41// shell syntax in it, is left out; null when none is left.
42export function gatePrelude(gateCommands: readonly string[], o: PreludeOpts): string | null {
43  const byProgram = new Map<string, string[][]>()
44  for (const command of gateCommands) {
45    const words = command.split(/\s+/).filter(w => w !== '')
46    const [program, ...rest] = words
47    if (program === undefined || !PROGRAM.test(program) || !rest.every(w => WORD.test(w))) continue
48    byProgram.set(program, [...(byProgram.get(program) ?? []), rest])
49  }
50  if (byProgram.size === 0) return null
51  const run = [
52    'sh', quoted(o.wrapper), '--dir', quoted(o.dir), '--capacity', String(o.capacity), '--wait-ms', String(Math.trunc(o.waitMs)),
53    '--log', quoted(o.log), '--issue', String(o.issue), '--life', quoted(o.life), '--seq', String(o.seq),
54  ].join(' ')
55  const fns: string[] = []
56  for (const [program, calls] of byProgram) {
57    const cond = calls.map(rest => `{ [ "$#" -eq ${rest.length} ]${rest.map((w, i) => ` && [ "$${i + 1}" = ${quoted(w)} ]`).join('')}; }`).join(' || ')
58    fns.push(`${program}() { if ${cond}; then ${run} -- command ${program} "$@"; else command ${program} "$@"; fi; }`)
59  }
60  return fns.join('; ')
61}
62
63const SLOT_LINE = /^factory-gate-slot: slot (\d+) after (\d+) ms\n?/
64const BUSY_LINE = /^factory-gate-slot: busy: [^\n]*$/
65
66export type SlotLine = { kind: 'slot'; slot: number; ms: number; rest: string } | { kind: 'busy' } | { kind: 'none' }
67
68// parseSlotLine: the wrapper's first line off an output. `busy` only when the output is nothing but
69// the busy line.
70export function parseSlotLine(output: string): SlotLine {
71  const m = SLOT_LINE.exec(output)
72  if (m !== null) return { kind: 'slot', slot: Number(m[1]), ms: Number(m[2]), rest: output.slice(m[0].length) }
73  return BUSY_LINE.test(output.trim()) ? { kind: 'busy' } : { kind: 'none' }
74}
75
76// What the stop gate's commands share: the slot wait it may still spend and what it has spent.
77export type SlotState = { capMs: number; waitedMs: number }
78
79export type SlotRun = { exitCode: number; output: string; slotWaitMs: number } | { error: string; slotWaitMs: number }
80
81// slotCommand: the shell text that runs `command` (shell text) through the wrapper without a log, for
82// at most sliceMs of waiting.
83export function slotCommand(command: string, o: { wrapper: string; dir: string; capacity: number; sliceMs: number }): string {
84  return `sh ${quoted(o.wrapper)} --dir ${quoted(o.dir)} --capacity ${o.capacity} --wait-ms ${o.sliceMs} -- sh -c ${quoted(command)}`
85}
86
87// runSlotted: runs one command through the wrapper (once is one host call), again each time it says
88// busy, until it gets a slot or the state's cap is used up. The wait stays out of the command's own budget.
89export async function runSlotted(
90  state: SlotState,
91  sliceMs: number,
92  once: () => Promise<{ exitCode: number; stdout: string }>,
93): Promise<SlotRun> {
94  let waited = 0
95  for (;;) {
96    const r = await once()
97    // an output that is no text is none of the wrapper's
98    const p: SlotLine = typeof r.stdout === 'string' ? parseSlotLine(r.stdout) : { kind: 'none' }
99    if (p.kind === 'slot') {
100      waited += p.ms
101      state.waitedMs += p.ms
102      return { exitCode: r.exitCode, output: p.rest, slotWaitMs: waited }
103    }
104    if (p.kind === 'busy' && r.exitCode === BUSY_EXIT) {
105      waited += sliceMs
106      state.waitedMs += sliceMs
107      if (state.waitedMs >= state.capMs) {
108        return { error: `it waited ${Math.round(state.waitedMs / 1000)} s for a gate slot of the container (the cap is ${Math.round(state.capMs / 1000)} s) and the command never ran`, slotWaitMs: waited }
109      }
110      continue
111    }
112    return { exitCode: r.exitCode, output: r.stdout, slotWaitMs: waited }
113  }
114}
115
hooks/turns.ts 107 lines
1// The stop gate's turns (docs/factory-loop/v2/SPEC.md 10.6), pure: a FIFO semaphore that lets at most
2// `capacity` holders run at once. register.ts keeps one for the whole process, so every slot's writer
3// shares it. No I/O: the clock and the timer are injected (the strict lib has no setTimeout, so the
4// timer wraps $.clock.after).
5
6export type TurnIo = {
7  now: () => number | Promise<number>
8  // a timer that calls fn after ms; cancel stops it
9  after: (ms: number, fn: () => void) => { cancel: () => void }
10  // the longest a waiter waits for a turn
11  maxWaitMs: number
12  // optional: one slice of waiting that holds a host call, so the engine's handler budget (which host
13  // calls pause and clock ops do not) does not run while queued. The wait calls it again as each
14  // slice ends; a rejection ends the calls and the wait goes on with the grant alone. Absent: the
15  // wait is the grant and the cap timer only.
16  idle?: () => Promise<unknown>
17}
18
19// A turn taken (release gives it back, once: a second call does nothing), or the wait ran past its
20// cap and the waiter left the queue for good. queuedBehind: how many held a turn or waited ahead when it
21// asked, in both cases.
22export type Turn = { ok: true; waitMs: number; queuedBehind: number; release: () => void } | { ok: false; waitMs: number; queuedBehind: number }
23
24type Waiter = { capacity: number; grant: () => void }
25
26export type Turns = {
27  acquire: (capacity: number, io: TurnIo) => Promise<Turn>
28  // for a test: the turns held and the waiters queued
29  state: () => { held: number; waiting: number }
30}
31
32export function createTurns(): Turns {
33  let held = 0
34  const queue: Waiter[] = []
35
36  // admit: hands turns to the queue's head while it fits under its own capacity, in order
37  const admit = () => {
38    for (let w = queue[0]; w !== undefined && held < w.capacity; w = queue[0]) {
39      queue.shift()
40      held++
41      w.grant()
42    }
43  }
44
45  const releaser = () => {
46    let done = false
47    return () => {
48      if (done) return
49      done = true
50      held--
51      admit()
52    }
53  }
54
55  return {
56    state: () => ({ held, waiting: queue.length }),
57    async acquire(capacity, io) {
58      // the decision is made before anything is awaited, so arrivals keep their order
59      if (queue.length === 0 && held < capacity) {
60        held++
61        return { ok: true, waitMs: 0, queuedBehind: 0, release: releaser() }
62      }
63      const queuedBehind = held + queue.length
64      const t0 = Promise.resolve(io.now())
65      let settle: (granted: boolean) => void = () => undefined
66      const outcome = new Promise<boolean>(resolve => {
67        settle = resolve
68      })
69      const waiter: Waiter = { capacity, grant: () => settle(true) }
70      queue.push(waiter)
71      const timer = io.after(io.maxWaitMs, () => {
72        const at = queue.indexOf(waiter)
73        // already granted: its turn is held, the cap no longer applies
74        if (at < 0) return
75        queue.splice(at, 1)
76        settle(false)
77      })
78      let idle = io.idle
79      if (idle !== undefined) {
80        let over = false
81        const done = outcome.then(() => {
82          over = true
83        })
84        while (!over && idle !== undefined) {
85          try {
86            await Promise.race([done, idle()])
87          } catch {
88            // a failing slice must not spin: the rest of the wait is the grant alone
89            idle = undefined
90          }
91        }
92      }
93      const granted = await outcome
94      timer.cancel()
95      // a granted turn is held already: if reading the clock fails it goes back, never leaks
96      const release = granted ? releaser() : () => undefined
97      try {
98        const waitMs = Math.max(0, (await io.now()) - (await t0))
99        return granted ? { ok: true, waitMs, queuedBehind, release } : { ok: false, waitMs, queuedBehind }
100      } catch (err) {
101        release()
102        throw err
103      }
104    },
105  }
106}
107
hooks/shell.ts 315 lines
1// A Bash command line as the simple commands it runs, each as its words, for the write guard
2// (docs/factory-loop/v2/SPEC.md 10.4). Best effort by design: the guard matches commands, not
3// effects. It splits on the shell's separators (; & && | || newlines, subshells, $( ) and
4// backquotes), honours quotes and escapes, skips comments and here-document text, drops
5// redirections, and looks through the wrappers that run another command (env, sudo, timeout,
6// xargs, bash -c, eval and the like), so `cd x && FOO=1 timeout 60 git push -f` still reads as a
7// git push. A command substitution the shell runs inside double quotes or in an unquoted
8// here-document (`echo "$(git push -f)"`) is read as a command line of its own.
9
10// One word as read: its text, and whether any of it was quoted (a quoted `>` is no redirection).
11type Word = { text: string; quoted: boolean }
12
13const MAX_DEPTH = 3
14
15// simpleCommands: every simple command of a line, outermost first, each as its argv.
16export function simpleCommands(line: string, depth = 0): string[][] {
17  const out: string[][] = []
18  const { cmds, subs } = split(line)
19  for (const words of cmds) out.push(...unwrap(dropRedirects(words), depth))
20  for (const sub of subs) out.push(...simpleCommands(sub, depth + 1))
21  return out
22}
23
24// program: a command's program name, without its folder (`/usr/bin/git` is `git`).
25export function program(argv: readonly string[]): string {
26  return (argv[0] ?? '').replace(/^.*\//, '')
27}
28
29// --- splitting ------------------------------------------------------------------------------------
30
31// substEnd: the index of the `)` that closes a `$(` whose body starts at i, past nested
32// parentheses, quotes and backquotes; -1 when it never closes.
33function substEnd(s: string, i: number): number {
34  let depth = 1
35  while (i < s.length) {
36    const c = s[i]
37    if (c === '\\') i += 2
38    else if (c === "'") {
39      const close = s.indexOf("'", i + 1)
40      if (close === -1) return -1
41      i = close + 1
42    } else if (c === '"' || c === '`') {
43      const close = c === '"' ? dquoteEnd(s, i + 1) : backquoteEnd(s, i + 1)
44      if (close === -1) return -1
45      i = close + 1
46    } else {
47      if (c === '(') depth++
48      else if (c === ')' && --depth === 0) return i
49      i++
50    }
51  }
52  return -1
53}
54
55// backquoteEnd: the index of the backquote that closes one whose body starts at i; -1 when none.
56function backquoteEnd(s: string, i: number): number {
57  while (i < s.length) {
58    if (s[i] === '\\') i += 2
59    else if (s[i] === '`') return i
60    else i++
61  }
62  return -1
63}
64
65// dquoteEnd: the index of the `"` that closes a double-quoted string whose text starts at i, past
66// the substitutions in it (which may hold quotes of their own); -1 when none.
67function dquoteEnd(s: string, i: number): number {
68  while (i < s.length) {
69    const c = s[i]
70    if (c === '\\') i += 2
71    else if (c === '"') return i
72    else if (c === '$' && s[i + 1] === '(') {
73      const close = substEnd(s, i + 2)
74      if (close === -1) return -1
75      i = close + 1
76    } else if (c === '`') {
77      const close = backquoteEnd(s, i + 1)
78      if (close === -1) return -1
79      i = close + 1
80    } else i++
81  }
82  return -1
83}
84
85// expansions: text the shell expands (a double-quoted string's, or an unquoted here-document's) as
86// the word it reads as, and the bodies of the command substitutions in it, which the shell runs.
87// escapes: the characters a backslash escapes in this text.
88function expansions(text: string, escapes: string): { text: string; subs: string[] } {
89  let out = ''
90  const subs: string[] = []
91  let j = 0
92  while (j < text.length) {
93    const c = text[j] ?? ''
94    if (c === '\\' && escapes.includes(text[j + 1] ?? '')) {
95      if (text[j + 1] !== '\n') out += text[j + 1]
96      j += 2
97    } else if (c === '$' && text[j + 1] === '(') {
98      const close = substEnd(text, j + 2)
99      const stop = close === -1 ? text.length : close
100      subs.push(text.slice(j + 2, stop))
101      out += text.slice(j, stop + 1)
102      j = stop + 1
103    } else if (c === '`') {
104      const close = backquoteEnd(text, j + 1)
105      const stop = close === -1 ? text.length : close
106      // in backquotes a backslash escapes only $, ` and itself
107      subs.push(text.slice(j + 1, stop).replace(/\\([$`\\])/g, '$1'))
108      out += text.slice(j, stop + 1)
109      j = stop + 1
110    } else {
111      out += c
112      j++
113    }
114  }
115  return { text: out, subs }
116}
117
118// split: a line's simple commands as words, and the bodies of the command substitutions the shell
119// runs from inside double quotes or unquoted here-documents (an unquoted one splits in place).
120function split(line: string): { cmds: Word[][]; subs: string[] } {
121  const cmds: Word[][] = []
122  const subs: string[] = []
123  let words: Word[] = []
124  // the word being read, if any (a holder, so the closures below can change it)
125  const at: { word: Word | null } = { word: null }
126  // expand: an unquoted delimiter, so the body's substitutions run
127  const heredocs: { delim: string; strip: boolean; expand: boolean }[] = []
128  const add = (text: string, quoted = false) => {
129    at.word ??= { text: '', quoted: false }
130    at.word.text += text
131    if (quoted) at.word.quoted = true
132  }
133  const flush = () => {
134    if (at.word !== null) words.push(at.word)
135    at.word = null
136  }
137  const end = () => {
138    flush()
139    if (words.length > 0) cmds.push(words)
140    words = []
141  }
142  let i = 0
143  while (i < line.length) {
144    const c = line[i] ?? ''
145    const next = line[i + 1] ?? ''
146    if (c === '\n') {
147      end()
148      i++
149      // the here-documents opened on that line: their bodies are text, not commands, but an
150      // unquoted delimiter's body runs its substitutions
151      while (heredocs.length > 0) {
152        const h = heredocs.shift() as { delim: string; strip: boolean; expand: boolean }
153        const body: string[] = []
154        while (i < line.length) {
155          const nl = line.indexOf('\n', i)
156          const text = line.slice(i, nl === -1 ? line.length : nl)
157          i = nl === -1 ? line.length : nl + 1
158          if ((h.strip ? text.replace(/^\t+/, '') : text) === h.delim) break
159          body.push(text)
160        }
161        if (h.expand) subs.push(...expansions(body.join('\n'), '$`\\\n').subs)
162      }
163      continue
164    }
165    if (c === '#' && at.word === null) {
166      while (i < line.length && line[i] !== '\n') i++
167      continue
168    }
169    if (c === '\\') {
170      if (next === '\n') i += 2
171      else {
172        add(next, true)
173        i += 2
174      }
175      continue
176    }
177    if (c === "'") {
178      const close = line.indexOf("'", i + 1)
179      const stop = close === -1 ? line.length : close
180      add(line.slice(i + 1, stop), true)
181      i = stop + 1
182      continue
183    }
184    if (c === '"') {
185      const close = dquoteEnd(line, i + 1)
186      const stop = close === -1 ? line.length : close
187      const quoted = expansions(line.slice(i + 1, stop), '"\\$`\n')
188      add(quoted.text, true)
189      subs.push(...quoted.subs)
190      i = stop + 1
191      continue
192    }
193    if (c === ' ' || c === '\t') {
194      flush()
195      i++
196      continue
197    }
198    if (c === '<' && next === '<' && line[i + 2] !== '<') {
199      // a here-document: <<DELIM or <<-DELIM, the delimiter quoted or not
200      flush()
201      let j = i + 2
202      const strip = line[j] === '-'
203      if (strip) j++
204      while (line[j] === ' ' || line[j] === '\t') j++
205      let delim = ''
206      let expand = true
207      while (j < line.length && !' \t\n;&|()<>'.includes(line[j] ?? '')) {
208        if (line[j] !== "'" && line[j] !== '"' && line[j] !== '\\') delim += line[j]
209        else expand = false
210        j++
211      }
212      if (delim !== '') heredocs.push({ delim, strip, expand })
213      i = j
214      continue
215    }
216    if (c === '&') {
217      // part of a redirection (2>&1, >&2, &>file), else a separator (& and &&)
218      if (next === '>' || at.word?.text.endsWith('>') || at.word?.text.endsWith('<')) {
219        add(c)
220        i++
221        continue
222      }
223      end()
224      i += next === '&' ? 2 : 1
225      continue
226    }
227    if (c === ';' || c === '|' || c === '(' || c === ')' || c === '`') {
228      end()
229      i += c === '|' && (next === '|' || next === '&') ? 2 : 1
230      continue
231    }
232    if (c === '$' && next === '(') {
233      end()
234      i += 2
235      continue
236    }
237    add(c)
238    i++
239  }
240  end()
241  return { cmds, subs }
242}
243
244// dropRedirects: the words that are redirections (>f, 2>&1, < f, &>f), and the target that
245// follows an operator standing alone.
246function dropRedirects(words: Word[]): Word[] {
247  const out: Word[] = []
248  for (let i = 0; i < words.length; i++) {
249    const w = words[i]
250    if (w === undefined) continue
251    const m = w.quoted ? null : /^(\d*|&)(>>?|<|>&|<&|>\|)(.*)$/.exec(w.text)
252    if (m === null) out.push(w)
253    else if (m[3] === '') i++
254  }
255  return out
256}
257
258// --- wrappers ---------------------------------------------------------------------------------------
259
260// Words that open a compound command and run the command after them.
261const KEYWORDS = new Set(['{', '}', '!', 'if', 'then', 'else', 'elif', 'fi', 'do', 'done', 'while', 'until', 'time'])
262
263// The wrappers that run the command after their own options, and those options that take a value.
264const WRAPPERS: Record<string, { valued: string[]; positional: number }> = {
265  env: { valued: ['-u', '--unset', '-C', '--chdir', '-S', '--split-string'], positional: 0 },
266  sudo: { valued: ['-u', '-g', '-C', '-D', '-h', '-p', '-U', '-r', '-t'], positional: 0 },
267  command: { valued: [], positional: 0 },
268  exec: { valued: ['-a'], positional: 0 },
269  nohup: { valued: [], positional: 0 },
270  nice: { valued: ['-n', '--adjustment'], positional: 0 },
271  stdbuf: { valued: ['-i', '-o', '-e'], positional: 0 },
272  timeout: { valued: ['-s', '--signal', '-k', '--kill-after'], positional: 1 },
273  xargs: { valued: ['-I', '-i', '-n', '-P', '-d', '-L', '-l', '-s', '-a', '-E', '-e', '--max-args', '--max-procs', '--delimiter', '--arg-file', '--replace'], positional: 0 },
274}
275
276const SHELLS = new Set(['sh', 'bash', 'dash', 'zsh', 'ksh'])
277
278// unwrap: the command a simple command runs, through assignments, keywords and wrappers; a shell's
279// -c script and eval's words are read as command lines of their own.
280function unwrap(words: Word[], depth: number): string[][] {
281  let argv = words.map(w => w.text)
282  for (;;) {
283    while (argv.length > 0 && (KEYWORDS.has(argv[0] ?? '') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[0] ?? ''))) argv = argv.slice(1)
284    if (argv.length === 0) return []
285    const name = program(argv)
286    const wrapper = WRAPPERS[name]
287    if (wrapper !== undefined) {
288      let i = 1
289      let positional = wrapper.positional
290      while (i < argv.length) {
291        const a = argv[i] ?? ''
292        if (a === '--') {
293          i++
294          break
295        }
296        if (name === 'env' && /^[A-Za-z_][A-Za-z0-9_]*=/.test(a)) i++
297        else if (a.startsWith('-') && a.length > 1) i += wrapper.valued.includes(a) ? 2 : 1
298        else if (positional > 0) {
299          positional--
300          i++
301        } else break
302      }
303      argv = argv.slice(i)
304      continue
305    }
306    if (depth < MAX_DEPTH && SHELLS.has(name)) {
307      const at = argv.findIndex((a, i) => i > 0 && /^-[a-z]*c[a-z]*$/.test(a))
308      const script = at === -1 ? undefined : argv[at + 1]
309      if (script !== undefined) return simpleCommands(script, depth + 1)
310    }
311    if (depth < MAX_DEPTH && name === 'eval') return simpleCommands(argv.slice(1).join(' '), depth + 1)
312    return [argv]
313  }
314}
315