The workspace probe's spawner: spawns one agent from a timer, as the factory loop does

A software factory that runs inside a single Claude Code session.
How it works · Architecture · Docs · Releases
<img alt="The factory as a session in the Claude app: the loop asks the model whether to cut a release, and the session title shows the issues queued, in flight and merged" src="docs/images/hero-light.svg" width="744"> <sub>The session title is a live status board: Q queued · D in flight · M merged</sub>
Label a GitHub issue ready. The factory designs it, builds it, reviews it and merges it. When it needs a decision, it asks you - on the issue, or in the Claude app on your phone.
Most agent factories put a program in charge and call Claude for each task. Others hand one model the whole job and let it improvise. This one puts the program inside the Claude session.
/factory pause, priority or drop.flowchart LR
you(["You"])
gh["GitHub<br/>issues, pull requests, CI"]
app["Claude app<br/>phone, desktop, terminal"]
you ==>|"create issues, label them ready"| gh
you -.->|"optional: ask, steer, answer"| app
subgraph factory["The factory: one Claude Code session"]
loop["Loop (code)<br/>plans and acts every minute"]
model["Model<br/>judgment and owner chat"]
agents["Agents<br/>design, build, review, fix"]
loop -->|wakes| model
loop --> agents
end
gh <-->|"claims issues, merges PRs"| loop
app <-.-> model
Writing issues is enough: the factory picks up anything labelled ready and comes back with a merged pull request. The Claude app is there for when you want to talk to it.
<img alt="The line: an issue moves from queued through design, build, review and the merge queue to merged; review sends changes to fix and back, and a stuck issue is parked with a question for you, then requeued when you answer" src="docs/images/pipeline-light.svg" width="744">
| Command | What it does | ||
|---|---|---|---|
status | The last pass and the directives in force | ||
pause <N> / unpause <N> | No action at all on an issue, though its claim still renews | ||
skip <N> / noskip <N> | Never claim an issue | ||
priority <N...> | Claim these first, in order | ||
only <N...> | Claim only these, in order | ||
| `serial on\ | off` | One issue in flight at a time | |
| `new on\ | off` | Off starts no new claims, designs or implementations | |
resume <N> | Release a hold on an issue or a run | ||
retry <N> | Let an issue's exhausted actions run again | ||
drop <N> | Abandon an issue and stop its agents | ||
| `note [<N>] <text>\ | off` | An instruction the next agent prompts carry; a newer note replaces the older one, off clears it | |
| `mode off\ | observe\ | act` | Switch the loop off, to watching only, or to acting |
| `trace on\ | off` | Detailed per-pass timing records |
The full list, with every option, is in the factory loop README.
plan(state, config) does no I/O and reads no clock, so recorded days of events can be replayed through it.[!NOTE] A factory runs in a Coder workspace built from this repo's
orchestrator-looptemplate: the base image, a factory database and the factory-loop plugins.Where we're heading is simpler: install a plugin, type one command, and the session you're in becomes the factory. Set up a factory.
This evolved from my own setup, which relies heavily on Coder, a Docker swarm to run the workloads, and a few other things. I hope to soon have the capacity to make it more general, and I'm open to learning how someone else would want to run it.
| Page | Read it for |
|---|---|
| Factory loop | Running and steering the loop, /factory commands |
| Factory loop v2 spec | States, steps, failure handling, the merge queue |
| Onboarding | Making a repo a dev-system repo |
| Architecture | Layers, versioning, the runtime map |
| Base image | The environment every workspace runs |
| Factory database and metrics | Standing up the database; measuring the factory |
| Releasing | Cutting a release |
hooks/register.ts 97 lines1// The workspace probe's spawner (docs/factory-loop/v2/SPEC.md 10.9): it stands in for the factory
2// loop. Like the loop, it spawns its agent from a $.clock timer that its session.start scheduled,
3// so no hook frame of this plugin is open when the spawn is raised. README.md beside this folder
4// says how to run it and what each case shows. PROBE_RUN (an absolute folder) and PROBE_CASE pick
5// the case:
6// control - the agent runs `sleep 150` with no timeout argument and nothing set
7// envset-start - the same, after this module's session.start called $.env.set (the loop's shape)
8// envset-timer - the same, after a timer callback (no frame open) called $.env.set
9// gate - the agent starts in <run>/slot through the helper plugin's agent.spawn hook,
10// writes done.txt, tries a write outside the slot, and finishes; the helper's
11// classic.SubagentStop runs a 75 s gate with $.process.run; once it answered,
12// a message resumes it, as the loop's repair message does, to show the resumed
13// agent keeps its slot and its guard
14// gate-queue-bare - the agent starts in <run>/slot and finishes at once; the helper's
15// classic.SubagentStop then waits about 540 s in host-call slices and runs a
16// 300 s command, the shape of a queued gate in the companion (v2 SPEC 10.6)
17// Every observation is one JSON line in <run>/log.jsonl.
18import type { EngineInterface, Register } from 'claude-code'
19
20const SLEEP =
21 'Run exactly this one Bash command, as given: `date -u +%T; sleep 150; date -u +%T`. Do not pass a timeout parameter and do not set run_in_background. Run no other command. When it returns, reply with its exact output and one line saying whether it ran to completion in the foreground or was moved to the background.'
22
23const gateAsk = (slot: string) => `factory-slot: ${slot}
24Steps, each its own tool call:
251. Bash: pwd
262. Write tool: file_path "done.txt", content "hello"
273. Write tool: file_path "../escape.txt", content "escaped" (it may be refused: report what you were told)
28Then reply with one line per step and finish. If you are told a check failed when you finish, do what it says, then finish again.`
29
30const queueAsk = (slot: string) => `factory-slot: ${slot}
31Reply with the single word: done. Run no tool.`
32
33const cases = new Map<string, string>()
34const resumed = new Set<string>()
35
36async function cfg($: EngineInterface) {
37 return { run: (await $.env.get('PROBE_RUN')) || '/tmp/workspace-probe', probe: (await $.env.get('PROBE_CASE')) || 'control' }
38}
39
40async function log($: EngineInterface, check: string, fields: Record<string, unknown> = {}) {
41 const { run } = await cfg($)
42 const line = JSON.stringify({ at: new Date(await $.clock.now()).toISOString(), plugin: 'spawner', check, ...fields }) + '\n'
43 await $.process.run(['sh', '-c', 'mkdir -p "$(dirname "$1")" && cat >> "$1"', 'sh', `${run}/log.jsonl`], { stdin: line, timeoutMs: 10_000 }).catch(() => undefined)
44}
45
46async function setTimeouts($: EngineInterface, where: string) {
47 await $.env.set('BASH_DEFAULT_TIMEOUT_MS', '600000')
48 await $.env.set('BASH_MAX_TIMEOUT_MS', '600000')
49 await log($, 'env.set', { where, BASH_DEFAULT_TIMEOUT_MS: (await $.env.get('BASH_DEFAULT_TIMEOUT_MS')) ?? null })
50}
51
52// spawn: the agent, from a timer. A headless session that is not built yet refuses a spawn (seen
53// once at 4 s on 2.1.300), so a refusal is tried again 2 s later, up to 10 times.
54async function spawn($: EngineInterface, tries = 1) {
55 const { run, probe } = await cfg($)
56 try {
57 const prompt = probe === 'gate' ? gateAsk(`${run}/slot`) : probe === 'gate-queue-bare' ? queueAsk(`${run}/slot`) : SLEEP
58 const r = await $.agent.spawn({ subagentType: 'workspace-probe-spawner:worker', description: `workspace probe ${probe}`, prompt })
59 if (r.agentId !== undefined) cases.set(r.agentId, probe)
60 await log($, 'spawned', { probe, tries, agentId: r.agentId ?? null, deny: r.deny ?? null })
61 } catch (err) {
62 await log($, 'spawned', { probe, tries, error: String(err) })
63 if (tries < 10) $.clock.after(2_000, () => void spawn($, tries + 1))
64 }
65}
66
67export const register: Register = on => {
68 on('session.start', async ($, e, next) => {
69 const r = await next(e)
70 const { run, probe } = await cfg($)
71 await log($, 'session.start', { run, probe, version: (await $.session.version()).version })
72 if (probe === 'envset-start') await setTimeouts($, 'session.start')
73 // the loop's case: every timer below fires after this hook returned, outside any frame of ours
74 if (probe === 'envset-timer') $.clock.after(1_000, () => void setTimeouts($, 'timer').catch(err => log($, 'env.set', { error: String(err) })))
75 $.clock.after(4_000, () => void spawn($))
76 return r
77 })
78
79 on('turn.complete', async ($, e, next) => {
80 const r = await next(e)
81 if (e.agentId === undefined || !cases.has(e.agentId)) return r
82 const probe = cases.get(e.agentId)
83 await log($, 'answered', { probe, agentId: e.agentId, answer: e.answer.slice(0, 1500) })
84 // the loop's repair message resumes an agent with $.session.send from its turn.complete
85 // (register.ts repairTo): does the resumed agent keep its slot, and its guard?
86 if (probe === 'gate' && !resumed.has(e.agentId)) {
87 resumed.add(e.agentId)
88 const to = e.agentId
89 void $.session
90 .send({ to: { agentId: to }, text: 'One more step: run the Bash command `pwd`, then try the Write tool with file_path "../escape2.txt" and content "x", and reply with what each told you.' })
91 .then(sent => log($, 'resumed', { agentId: to, sent }))
92 .catch(err => log($, 'resumed', { agentId: to, error: String(err) }))
93 }
94 return r
95 }).catch(($, e, next) => next(e))
96}
97