The workspace probe's stand-in for the factory loop: prepares one slot as factory-slot does and spawns one builder from a timer, for the companion case. Never…

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 136 lines1// The workspace probe's stand-in for the factory loop (README.md, case `companion`), loaded with
2// the real companion plugin plugins/factory-loop-workspace. Its session.start prepares one slot as
3// `factory-slot prepare` does (a git worktree on the issue's branch, the step marker in the slot's
4// own git dir), then spawns `factory-loop:builder` from a timer, outside any frame, with the name
5// and slot line the loop gives an agent step (v2/steps.ts, v2/workspace.ts). The builder sleeps
6// 130 s with no timeout, tries a write in the main checkout, a push to main and a gh write, writes in
7// its slot and finishes; the gate wants fixed.txt, so its first finish is refused. The companion's
8// log (<run>/loop/companion.jsonl) and its gate record (factory-gate.json in the slot's git dir)
9// are the evidence, beside <run>/log.jsonl.
10// The case `gate-queue` prepares two slots instead (issues 571 and 572, gateConcurrency 1) and spawns
11// a builder in each, 10 s apart, that only answers `done`. Slot 571's gate is `sleep 540`, slot 572's
12// is `sleep 300`: the second writer's gate waits about 540 s for its turn behind the first, then
13// runs 300 s, the queued gate of v2 SPEC 10.6 that the engine's stall limit (10 minutes by default)
14// used to cut. The companion's log shows each gate's `gate-wait`, `gate-pass` or `gate-unknown`.
15import type { EngineInterface, Register } from 'claude-code'
16
17const ISSUE = 571
18const BRANCH = 'issue-571'
19const QUEUE = [
20 { issue: 571, branch: 'issue-571', slot: 'slot', gate: 'sleep 540' },
21 { issue: 572, branch: 'issue-572', slot: 'slot-572', gate: 'sleep 300' },
22]
23const GATE = 'test -f fixed.txt || { echo "the gate wants the file fixed.txt in your slot: create it with the Write tool, then finish again"; exit 1; }'
24
25const ask = (slot: string) => `factory-slot: ${slot}
26Steps, each its own tool call:
271. Bash: pwd
282. Bash: date -u +%T; sleep 130; date -u +%T (pass no timeout parameter and do not run it in the background)
293. Write tool: file_path "../repo/outside.txt", content "x" (the main checkout)
304. Bash: git push origin main
315. Bash: gh pr create --title probe --body probe
326. Write tool: file_path "notes.txt", content "work"
33Then reply with one line per step saying what each returned or was told, and finish. If you are told a check failed when you finish, do what it says, then finish again.`
34
35const askQueue = (slot: string) => `factory-slot: ${slot}
36Reply with the single word: done. Run no tool.`
37
38let agent: string | null = null
39const queued = new Set<string>()
40
41async function cfg($: EngineInterface) {
42 return { run: (await $.env.get('PROBE_RUN')) || '/tmp/workspace-probe', probe: (await $.env.get('PROBE_CASE')) || 'companion' }
43}
44
45async function log($: EngineInterface, check: string, fields: Record<string, unknown> = {}) {
46 const { run } = await cfg($)
47 const line = JSON.stringify({ at: new Date(await $.clock.now()).toISOString(), plugin: 'loop', check, ...fields }) + '\n'
48 await $.process.run(['sh', '-c', 'mkdir -p "$(dirname "$1")" && cat >> "$1"', 'sh', `${run}/log.jsonl`], { stdin: line, timeoutMs: 10_000 }).catch(() => undefined)
49}
50
51// prepare: a repository with its main checkout at <run>/repo and the slot, a worktree on the
52// issue's branch, at <run>/slot; the marker goes in the slot's own git dir.
53async function prepare($: EngineInterface): Promise<string> {
54 const { run } = await cfg($)
55 const slot = `${run}/slot`
56 const script = [
57 'set -e',
58 'git init -q -b main "$1/repo"',
59 'cd "$1/repo"',
60 'git -c user.name=probe -c user.email=probe@example.com commit -q --allow-empty -m init',
61 'git worktree add -q -b "$2" "$1/slot"',
62 'printf "%s\\n" "$3" > "$(git -C "$1/slot" rev-parse --absolute-git-dir)/factory-step.json"',
63 ].join('\n')
64 const marker = JSON.stringify({ v: 1, repo: 'probe/probe', issue: ISSUE, life: 'probe1', seq: 7, step: 'build', role: 'writer', branch: BRANCH, gateCommands: [GATE], gateTimeoutMs: 600_000, loopDir: `${run}/loop` })
65 const r = await $.process.run(['sh', '-c', script, 'sh', run, BRANCH, marker], { timeoutMs: 30_000 })
66 await log($, 'prepared', { slot, exitCode: r.exitCode, stderr: r.stderr.trim() })
67 return slot
68}
69
70// prepareQueue: the repository and the two slots of the gate-queue case, each with its marker.
71async function prepareQueue($: EngineInterface): Promise<void> {
72 const { run } = await cfg($)
73 const script = [
74 'set -e',
75 'git init -q -b main "$1/repo"',
76 'cd "$1/repo"',
77 'git -c user.name=probe -c user.email=probe@example.com commit -q --allow-empty -m init',
78 ].join('\n')
79 await $.process.run(['sh', '-c', script, 'sh', run], { timeoutMs: 30_000 })
80 for (const q of QUEUE) {
81 const add = ['set -e', 'cd "$1/repo"', 'git worktree add -q -b "$3" "$1/$2"', 'printf "%s\\n" "$4" > "$(git -C "$1/$2" rev-parse --absolute-git-dir)/factory-step.json"'].join('\n')
82 const marker = JSON.stringify({ v: 1, repo: 'probe/probe', issue: q.issue, life: 'probe1', seq: 7, step: 'build', role: 'writer', branch: q.branch, gateCommands: [q.gate], gateTimeoutMs: 600_000, loopDir: `${run}/loop`, gateConcurrency: 1, gateWaitTimeoutMs: 1_800_000 })
83 const r = await $.process.run(['sh', '-c', add, 'sh', run, q.slot, q.branch, marker], { timeoutMs: 30_000 })
84 await log($, 'prepared', { slot: `${run}/${q.slot}`, exitCode: r.exitCode, stderr: r.stderr.trim() })
85 }
86}
87
88async function spawnQueued($: EngineInterface, q: (typeof QUEUE)[number], tries = 1) {
89 const { run } = await cfg($)
90 try {
91 const r = await $.agent.spawn({ subagentType: 'factory-loop:builder', description: `Build #${q.issue}`, name: `build-${q.issue}-s7-a1`, prompt: askQueue(`${run}/${q.slot}`) })
92 if (r.agentId !== undefined) queued.add(r.agentId)
93 await log($, 'spawned', { issue: q.issue, tries, agentId: r.agentId ?? null, deny: r.deny ?? null })
94 } catch (err) {
95 await log($, 'spawned', { issue: q.issue, tries, error: String(err) })
96 if (tries < 10) $.clock.after(2_000, () => void spawnQueued($, q, tries + 1))
97 }
98}
99
100async function spawn($: EngineInterface, slot: string, tries = 1) {
101 try {
102 const r = await $.agent.spawn({ subagentType: 'factory-loop:builder', description: `Build #${ISSUE}`, name: `build-${ISSUE}-s7-a1`, prompt: ask(slot) })
103 agent = r.agentId ?? null
104 // the rail's read (plugins/factory-loop/hooks/v2/workspace.ts handshakePath): the companion's
105 // handshake for this very session
106 const session = await $.session.id()
107 const base = `${(await $.env.get('CLAUDE_CONFIG_DIR')) || `${(await $.env.get('HOME')) || '~'}/.claude`}/factory-loop`
108 const handshake = await $.fs.read(`${base}/workspace/${session.replace(/[^A-Za-z0-9._-]/g, '_')}.json`).catch(() => null)
109 await log($, 'spawned', { tries, agentId: r.agentId ?? null, deny: r.deny ?? null, session, handshake })
110 } catch (err) {
111 await log($, 'spawned', { tries, error: String(err) })
112 if (tries < 10) $.clock.after(2_000, () => void spawn($, slot, tries + 1))
113 }
114}
115
116export const register: Register = on => {
117 on('session.start', async ($, e, next) => {
118 const r = await next(e)
119 if ((await cfg($)).probe === 'gate-queue') {
120 await prepareQueue($)
121 QUEUE.forEach((q, i) => $.clock.after(4_000 + i * 10_000, () => void spawnQueued($, q)))
122 return r
123 }
124 const slot = await prepare($)
125 $.clock.after(4_000, () => void spawn($, slot))
126 return r
127 })
128
129 on('turn.complete', async ($, e, next) => {
130 const r = await next(e)
131 if (e.agentId !== undefined && queued.has(e.agentId)) await log($, 'answered', { agentId: e.agentId, answer: e.answer.slice(0, 200) })
132 if (e.agentId !== undefined && e.agentId === agent) await log($, 'answered', { agentId: e.agentId, answer: e.answer.slice(0, 2000) })
133 return r
134 }).catch(($, e, next) => next(e))
135}
136