Build dark factory
Take a PRD and build a dark factory around it - a repository that takes work in as an issue and ships validated code out with nobody at the keyboard - one component at a time, into the user's actual repo. Covers the five components in construction order - the guidance layer, the validation harness, the workflow-driven repo, deployment, and the trigger that makes it autonomous - and is agnostic about which coding agent runs underneath (Claude Code, Codex, Archon, the Agent SDK, Cline, Goose, Amp, Pi). It encodes the AI coding process the user already runs rather than replacing it. Requires a PRD as input and deliberately does not write one. Use when the user wants to build a dark factory, an autonomous or self-driving repository, a software factory, an agent that ships its own code, an unattended or overnight coding loop, or asks how to get to level 4 or level 5 of AI coding autonomy; and when they mention dark factory, lights-out coding, autonomous PRs, or a repo that maintains itself.
By- name:
- build-dark-factory
- description:
- Take a PRD and build a dark factory around it - a repository that takes work in as an issue and ships validated code out with nobody at the keyboard - one component at a time, into the user's actual repo. Covers the five components in construction order - the guidance layer, the validation harness, the workflow-driven repo, deployment, and the trigger that makes it autonomous - and is agnostic about which coding agent runs underneath (Claude Code, Codex, Archon, the Agent SDK, Cline, Goose, Amp, Pi). It encodes the AI coding process the user already runs rather than replacing it. Requires a PRD as input and deliberately does not write one. Use when the user wants to build a dark factory, an autonomous or self-driving repository, a software factory, an agent that ships its own code, an unattended or overnight coding loop, or asks how to get to level 4 or level 5 of AI coding autonomy; and when they mention dark factory, lights-out coding, autonomous PRs, or a repo that maintains itself.
Build a dark factory
What the user typed: $ARGUMENTS
Work out the PRD path and the repo path from that line yourself, and do not print a parse you have not checked. The positional split is on whitespace, so anyone who types a sentence ("build a dark factory for my repo at C:\code\thing") gets the first two words as the two paths - three separate test runs opened with
PRD: BuildandRepo: a, which is a broken-looking first contact for a parse the skill then quietly recovered from anyway.So: read the line, find the thing that looks like a
.mdPRD and the thing that looks like a directory, and confirm both back to the user as one sentence before Phase 0. If only one is given, work out from its extension which it is and ask for the other. If the PRD path does not exist, say so and stop - that is Phase 0a, reached early.
A dark factory is a repository where work goes in one end and shipped code comes out the other, and there is no human in between. Work arrives as an issue. Workflows plan it, build it, validate it, and merge it. Deployment carries it to real users. Nobody reviews the diff.
That last sentence is the whole difficulty. Everything else is plumbing.
Build the factory into the user's repo. Do not hand them a design document. Every phase below ends with files committed and something demonstrably working.

The whole system on one page. All five components, the three governance files, and the independence line. Open
dark-factory-diagram.pngfull size if you want the map before the procedure.
Output discipline - read this before you write a single word to the user
This document is long because it has to be complete. What you SAY is not. A user running this reported the experience as "incredibly frustrating and hard to process, overwhelming to say the least" - and that was the skill working correctly, explaining itself at every step. Reasoning that belongs in a file is noise in a chat window.
Hard budgets. These are not style preferences.
| Moment | Budget |
|---|---|
| Between one question and the next | Nothing. Ask. Do not preface, do not recap the last answer. |
| Finishing a phase | Two lines. What now exists, and the next question. |
| Explaining a concept | Only when asked, and then the short version first. |
| Reporting a file you wrote | One line. Its path and what decides its content. |
| A command's output | Never paste it. Say the verdict and the number. |
Never do these:
- Announce a plan for a phase before doing it. Do it, then say what exists.
- Restate the user's answer back to them as a paragraph. A picker already showed it.
- Explain WHY the skill works this way. That reasoning is in
references/, for you, not for them. If they want it they will ask. - Print a table of everything you are about to build.
- Summarise at the end of a phase what you said at the start of it.
- Paste a file you just wrote. They can open it.
The one thing worth spending words on is a question that carries a real decision, and those go through the question tool, where the words are in the options rather than in a paragraph above them.
A useful test before any message: would this still be true if I deleted it? If the files on disk carry the fact, delete it.
What this is, and what it is not
A dark factory is not a different way of coding with AI. It is the way you already code with AI, with the human checkpoints removed.
Whatever process you run today is what goes inside the factory. GitHub Spec Kit, BMAD, a PRP framework, your own plan-then-implement loop, or just a well-worn habit. The steps stay the same. The skills stay the same. The MCP servers, the rules files, the subagents, the commands you already trust: all the same.
One thing changes. Nobody approves the plan, and nobody reads the diff before it ships.
So the job here is not to invent a process. It is to write down the one the user already has, then build the parts that make it safe to walk away from. Ask what their current AI coding workflow looks like early, and encode that, rather than imposing the shape of the example factory.
This skill does not write the PRD. That is deliberate. Producing the top-level
plan for a product is the part where almost everyone already has a custom approach
worth keeping, and a generic interview would be a downgrade. If the user has no
approach yet, point them at the plan-create-prd skill in this same repo and come
back when they have a file.
Two things that shape every decision below
<!-- NO COST OR DURATION ESTIMATES IN THIS FILE, and none in the opening message. They used to be a table here that the skill was told to recite before the interview, and every run opened by quoting figures at someone who had just asked for a dark factory. People know a build like this takes a while and costs something; being warned about it reads as hedging, and it buries the first useful sentence. Do not reintroduce them. (Also: never write a `$` followed by a digit in this file - it renders as a positional argument substitution and silently eats the surrounding text.) -->- Cached reads dominate cost by orders of magnitude over output. Context size drives the bill far more than how much the agent writes, which is why the premium model belongs in the planning slot and a cheaper one everywhere else.
- Refusing is cheap and building is not. If Phase 0 is borderline, refuse. Building the wrong factory is discovered in month two, and it cannot be patched by a better prompt.
Offer to stop after the guidance layer if the user wants a smaller first commitment. It is useful even if they never turn a cron on.
Before anything else: the three harnesses
People conflate these and then cannot debug them. Name them once, out loud, early:
| Harness | What it is | Who builds it |
|---|---|---|
| The agent harness | Claude Code, Codex, Pi - the loop that turns a prompt into edits | Vendor. Not your problem. |
| The factory harness | how work is planned, implemented, reviewed, gated, merged | templates/runner/. Components 1-4, mostly copied. |
| The validation harness | the tools the agent uses to check its own work as a user would | You, and it is most of the work. Component 5. |
The factory harness decides what runs. The validation harness decides whether what ran was worth keeping. Confusing the two is why people build an impressive DAG that ships broken software on schedule.
That distinction is also what decides which parts of this ship as a template:
The factory harness is templatable. The validation harness is not.
The dispatcher, the runner, the gate, the guard, the merge and the state machine are the
same in every factory, so they are in templates/runner/ with their scars intact. What
"working" means for this app is the one thing nobody can write in advance, so component 5
is yours - and it is where the real work of this build sits.
Construction order, and why it is not 1-2-3-4-5
The five components are numbered in anatomy order - the order you explain the machine in. They are not built in that order. Build in this order instead:
| Build | Component | Why here |
|---|---|---|
| 0th | (the PRD) | Not a component. The input. Everything below reads it, and nothing below can be written honestly without it. |
| 1st | Guidance layer (#4) | Markdown, and every other component reads it. The cheapest thing here with the highest leverage. |
| 1.5th | (the walking skeleton) | Greenfield only, and AFTER the guidance layer, not before it - the slice should be built inside the mission's scope, and markdown needs no code to exist. Not a component; deliberately tiny, the thinnest slice that yields one assertable behaviour. Component 5 cannot be written against software that does not exist. See Phase 0c; the danger is building the MVP here rather than a slice. |
| 2nd | Validation harness (#5) | The long pole. Start it before you need it, because you will be wrong about it twice. |
| 3rd | Workflow-driven repo (#1) | Now the workflows have rules to obey and checks to pass. |
| 4th | Deployment (#3) | Close the loop to real users before you make it unattended. |
| Last | The trigger (#2) | The cron is the switch. It goes on only when 1-4 are proven. |
The trigger is built last on purpose. Turning on a scheduler is the moment the repo becomes autonomous. Everything before it can be run by hand and inspected. A factory whose dispatcher was built first is an unsupervised code generator that nobody has ever checked.
State this to the user before starting. It reframes the whole project from "wire up an agent" to "earn the right to walk away."
Phase 0. The input, the two ways to refuse, and the greenfield path
0a. There has to be a PRD
The input to this skill is a PRD: what is being built and why, at the level a product manager writes it. Problem, users, scope, and above all non-goals. Call it a spec, a brief, a product doc, an epic; the name does not matter and the content does.
It deliberately does not contain the tech stack, the architecture, the data model, or the file layout. Those are engineering decisions, they come later, and in a factory they are usually decided on the first real run or already settled by the existing codebase. Asking for them here is how a PRD turns into a spec nobody can change.
When the PRD contains one anyway - and it usually will - treat it as SETTLED, not as scope, and say that you are doing so. Someone who is not an engineer writes down the stack because it is the part they feel confident about; a career-changer's brief will name the framework, the host and a table sketch before it names a single non-goal. Arguing them out of it buys nothing and costs the room.
So: take it as a decision already made, do not put it in MISSION.md (it is not scope and
the factory must not defend it), and flag it in one line so it is a choice rather than
something you quietly assumed. The one thing to check out loud is reachability - a
stack that can only be exercised through a rendered page needs the logic split out behind
something an E2E can call. See 0c.
Read the PRD at $prd in full before asking a single question. Then map it:
| The PRD gives you | The factory builds from it |
|---|---|
| the problem, and why it is worth solving | the framing at the top of MISSION.md |
| who the users are | the person the E2E path is acted out as |
| MVP scope, the capability areas | what triage is allowed to accept |
| non-goals | MISSION.md out-of-scope-forever, the most load-bearing list in the whole build |
| success metrics | what the validation harness is ultimately arguing about |
| open questions, anything marked TBD | a decision to be proposed, not a wall. The factory picks a defensible value, records it, and the merge is held for a human. It escalates only for the short list in FACTORY_RULES.md §7.2 - read "open" as "I have not decided", never as "you may not propose" |
And be explicit with the user about what the PRD does not give you, because these are exactly what the interview exists to produce:
- the E2E happy path, narrated as observable steps
- the protected list
- the two gates that have to be code rather than prompt
- the target autonomy level
- the stop button
- how work arrives, and where the factory runs
Refuse if there is no PRD. Say why: without a written scope, MISSION.md has no
out-of-scope list, and without that list every plausible feature request is arguably
in scope. The factory will build all of them. That is the single most common way an
autonomous repo goes wrong, and it cannot be patched later by a better prompt.
Point at the plan-create-prd skill in this repo and stop. Coming back in twenty
minutes with a real PRD is the fastest path, not a detour.
0b. The repo has to be observable
Inspect before asking anything. Look for: a test command that runs, a way to start
the app, existing CI, whether gh is authenticated, whether the repo is public, and
whatever AI coding setup already exists (CLAUDE.md, AGENTS.md, .claude/,
.cursor/, existing skills, commands, MCP config). That last one is the process to
encode, and it is usually already sitting there.
Decide which of two repos this is by LOOKING - you have just inspected it. Do not ask. The refusals below are written for one of them and misfire badly on the other, and the difference is visible in the file list:
- Brownfield - source files that are not scaffolding. The refusals apply as written.
- Greenfield - a PRD, maybe a
.gitignore,.claude/, a README, and nothing that runs. Both refusals are then trivially true and neither carries any signal. Go to 0c; do not refuse.
Say which one you concluded and why, in one line, so the user can correct it: "No source files outside docs/ and .claude/, so I am treating this as greenfield." A wrong guess is cheap to fix and asking costs a question you already have the answer to.
Refuse, and say why, when:
There is no way to observe the software working - nothing to start, nothing to invoke, and nothing importable either. Component 5 has nothing to stand on.
This is about software that cannot be observed, not software that does not exist yet. A greenfield repo trips this and the next bullet by definition, and refusing it would be refusing the premise rather than a defect. See 0c.
A library is not this case. The harness ships three drivers -
http(a server),cli(a command), andlibrary(no process at all; the E2E imports it and calls it) - andAPP_STARTED driver=librarymeans the import succeeded, which is the same claim a server answering makes. This bullet used to open with the words "a library", and a test run against a pure Python library nearly hard-refused a repo the scaffold supports out of the box. Readtemplates/harness/appproc.pybefore deciding something is unobservable.The repo has no CI and no test command at all. Start with a test suite. A dark factory built on zero checks is a machine for merging plausible code.
The user wants the agent to touch auth, payments, or anything with a blast radius they cannot absorb. Those go on the protected list, not into the factory.
Saying no here is cheaper than saying it in month two. If any of these hold, offer the smaller version: build the guidance layer and the harness now, and stop before autonomy.
0c. Greenfield: the walking skeleton, and it is SMALL
This is the common case, not the exception. Most people want a dark factory at the start of a project, which is also the best time to build one - the guidance layer is cheapest to write when nothing contradicts it yet, and the sim/presentation split below is free before there is code and expensive afterwards.
Greenfield is not a refusal. But it does mean component 5 has nothing to stand on today, and no ordering of the phases fixes that. Something has to exist first.
The skeleton is the thinnest vertical slice, NOT the MVP
This is where a greenfield build goes wrong, and it goes wrong in the same direction every time: the agent proposes building the core of the product so the harness has something to test, the user agrees because it sounds necessary, and now the interesting, risky work has been done by hand and the factory is left with the leftovers. That inverts the entire point.
Build the smallest slice that produces one observable, assertable behaviour end to end. For a game: one enemy, one hit, one damage number, persisted across a restart. For a service: one endpoint that writes one row and reads it back. For a CLI: one command with one flag that changes one line of output.
The test is not "is this useful" - it is "can an E2E assert something a user would notice?" If yes, stop building and start building the factory. Everything else in the MVP is issues, and the factory building them is the thing you are here for.
State the size explicitly before starting, and say what you are deliberately leaving out: "I am building one horn level, one wave, one damage number and a save file. Not the reward curve, not the elemental interactions, not wave composition - those are issue one, two and three."
The reachability constraint, decided NOW
The harness reaches software exactly three ways - http (a server), cli (a command),
library (imported and called). Read templates/harness/appproc.py. A rendered window, a
game loop, a canvas, a native UI is none of them.
So on greenfield this stops being an architecture preference and becomes a hard requirement: the logic must live behind a headless, scriptable surface that an E2E can drive. Simulation separate from rendering. Domain separate from view. If the rules only exist inside engine nodes and a render loop, there is nothing to assert and the factory cannot be built at level 3 - not because the skill is limited, but because nothing can check the work.
Say this before any code is written. It is nearly free now and it is a rewrite later.
The factory's scope is strictly smaller than the MVP
Some MVP items are not machine-validatable and never will be: "combat feels good", "the escalation is visibly and audibly different", "a first-time player understands it". Those are feel, presentation and readability.
Name them out loud, write them into MISSION.md and FACTORY_RULES.md as permanently
human, and be clear that the factory owns the simulation layer rather than the product.
That is still a large and valuable surface - usually most of the actual risk - but
pretending it is the whole MVP is how you end up with a green factory shipping a game
nobody wants to play.
Then, in this order - and the fork comes AFTER the interview
Say the two things above (the skeleton is a slice; the logic has to be reachable) now, in Phase 0, because both change what the user tells you in the interview. Then:
- Phase 1, the interview. It is unchanged on greenfield.
- Phase 2, the guidance layer. Markdown, needs no code, and every later component reads it - including the skeleton, which should be built inside the mission's scope rather than alongside it. This is also the natural stopping point a greenfield user might want, and putting the skeleton first removes it.
- The skeleton, named and sized against the journey from R1.1.
- Phase 3 onwards as written.
The fork below is presented after Phase 1, not here. Its recommended option requires you to name the slice and name what you are leaving out, and you cannot do either honestly before R1.1 has told you what the journey is. Asking in Phase 0 gets a decision made on information nobody has yet. Flag in Phase 0 that the choice is coming; put it after the interview.
The fork, once the interview has given you a journey
Three known answers, so this is a question-tool call like every other, and recommend the first:
- Build the thin skeleton now, then the factory on it (recommended) - name the slice and name what you are leaving out, so "recommended" cannot be read as "I will build your MVP".
- Guidance layer and scaffolds only -
MISSION.md,FACTORY_RULES.md,CLAUDE.md, plusrunner/andharness/copied in with the contract documented and the assertions left empty. The user builds the skeleton; you resume at component 5. A real option, not a consolation: theMISSION.md/FACTORY_RULES.mdpair earns its keep in interactive work whether or not a cron is ever turned on. - Stop - architecture first - when the PRD defers the thing 0c's reachability constraint depends on, and the user would rather settle it before code exists.
Phase 1. Interview
Read references/interview.md and work through it. It is the whole skill in question
form: what each question is actually for, what a good answer sounds like, and which
vague answers to push back on.
It is three rounds, not a questionnaire. Round 1 is the three questions below, asked one at a time before anything else. Round 2 is six that only the user can answer. Round 3 is a single message listing every remaining setting with its default already filled in, asking what to change.
Propose defaults; do not interrogate. The protected paths, the poll interval, the
concurrency, the stop button, the PR cap, the model routing and the holdout location all
have working defaults that ship in config.sh and the templates. Asking for them
open-ended makes the user do the skill's homework and buries the questions that matter.
"I am going to protect these five paths, plus your CI config - anything else?" is a better
question than "which files must the agent never touch?", and it cannot be answered wrong
by someone who has never built one of these.
The PRD has already answered part of this. Never re-ask what it answers. Read the scope and the non-goals back as a proposal - "so triage accepts anything in these four areas and rejects these six, correct?" - and spend the time on what it left open. Re-asking something the user already wrote down is how an interview loses the room in the first two minutes.
Reflect each answer back as a concrete artifact ("so the merge gate is: X") before moving on.
EVERY QUESTION GOES THROUGH THE QUESTION TOOL. AskUserQuestion in Claude Code, or
the equivalent elsewhere. Every one, including the open-ended ones. No exceptions, and no
prose fallback.
This used to be split - pickers for known options, prose for the open questions - on the argument that offering options for "describe the most valuable thing a user does" replaces the answer with a menu of your guesses. That argument is answered by the tool itself: it always carries an "Other" free-text escape. The user who wants to answer in their own words still can, in one keystroke. The user who would have skimmed a paragraph and said "you pick" now corrects the closest of three concrete candidates, which is the answer you needed and would not have got.
What survives from the old argument is a constraint on the OPTIONS, not on the tool: for an open question, derive them from their PRD and their repo and cite the source. A draft from their own material is their answer played back and they will overwrite it happily; an invented one anchors them onto your guess.
Every Round 2 question asks about something that has ALREADY HAPPENED to them - a
bug that escaped, a thing they would drop everything to fix, what they do after a change
to convince themselves. Never ask a user to design an artifact. They answer from memory
about their own software; turning that into scenarios, defect sets and rules is your job,
done silently. interview.md carries the exact words and what each becomes.
Two rules apply to every question:
- Always carry a recommendation. Exactly one option marked
(Recommended), first, with the reason in its one-line description. Never a blank page. Where a recommendation would be dishonest - a genuine coin-flip - say that in the question rather than inventing confidence. - Offer to explain the hard parts before they answer. Holdout, mutation set, ratchet,
independence line, structural gate are obvious only to someone who has built one of
these, and a user who does not want to admit they have not heard of a holdout will
guess. Add an "Explain this first" option.
interview.mdhas a one-breath explanation for each term - use those words, and do not lecture.
Round 1 - three questions decide the project, so do not let any of them slide:
- "Walk me through the single most useful thing someone does with this, from the first click to the thing they end up looking at." That sequence becomes the main path checked on every change. If they cannot describe it, nothing can check it.
- "How do you build a feature with AI today?" One open question, not a
questionnaire - take what they give you and read
CLAUDE.md,AGENTS.md,.claude/and.cursor/for the rest. The workflows should be recognisably their process with the approvals taken out. - "Are you willing to let code reach your users without anyone reading it first?" Then the dial below. Recommend level 3. People often say 5; 5 means the factory writes its own work from the mission, which is a different decision.
The autonomy dial
| Level | What is automatic | What you still do |
|---|---|---|
| 0 | workflows exist | run them by hand |
| 1 | labelled issue → PR opens | review and merge everything |
| 2 | + validator runs and posts a verdict | merge everything |
| 3 | + validator auto-merges when every structural gate is green | write the issues, cut releases |
| 4 | + it triages its own issues, and a scheduled test files its own bugs | write the important issues |
| 5 | + it writes its own issues from the mission | nothing |
Level 3 is the default. Build for it.
It is the first level where code merges without a human reading it, and it is the whole point: a factory that stops at 2 is a code generator with a queue, and the person is still the bottleneck they were trying to remove. Everything difficult in this build exists to earn level 3, so building for anything less means doing the hard part and not using it.
Levels 0 to 2 are stages on the way, not destinations. Ship them in order, prove a lap
at each, and keep going to 3. The dial is enforced in orchestrator.sh and
factory_doctor blocks 3 outright until a holdout exists, so "build for 3" cannot turn
into "switch on 3" before the evidence is there.
Stop below 3 only when the user has a specific reason - an unmovable review requirement, a blast radius they cannot absorb, a harness they do not yet trust. That is a legitimate choice and it should be their choice, made out loud, rather than the default that happens because nobody raised the dial.
Above 3 is a different question, not a further step: 4 hands over what gets built and 5 hands over what to build. Neither is implied by wanting the merge automated.
Phase 2. The guidance layer (component 4)
Read references/guidance-layer.md. Write three files from the templates:
MISSION.md- what is being built, and what is deliberately out of scope foreverFACTORY_RULES.md- how the agent behaves unsupervised, and the protected listCLAUDE.md/AGENTS.md- the conventions any project has, factory or not (template intemplates/CLAUDE.md; if one already exists, split it rather than replacing it)
MISSION.md is a compression of the PRD, not a new document. Draft it from the
PRD directly and show the user the diff in meaning, not just the file. The PRD's
non-goals become the out-of-scope list almost verbatim, and anything the interview
added on top gets marked as such so it is obvious later which constraints came from
the product and which came from making it unattended.
If a conventions file already exists, keep it and pull the factory-only rules out of it rather than writing a new one over the top. That split is usually the single most useful edit this phase makes to an existing repo.
The placement test, for every rule:
Would you write this even with a human doing the work? → conventions file. Does it only exist because nobody is watching? →
FACTORY_RULES.md. Is it about what the product is and is not? →MISSION.md.
The one property that matters: the agent cannot amend the rules it is judged by. All three files go on the protected list, and a PR that touches them is auto-rejected before anything else is evaluated. Enforce this in code, not in a prompt.
Run scripts/factory_doctor.py --repo <path> now. It will fail loudly, which is
correct - it is a checklist, and this is the start of working through it.
Phase 3. The validation harness (component 5)
Read references/validation-harness.md in full before writing anything. It is the
longest reference because this is where factories actually fail. Its opening section
is the contract the runner expects - the entrypoint, the markers, the append rule, and
the --quick subset. Read that even if you skim the rest, because getting the append
rule wrong breaks every marker assertion for a reason that looks like your code.
Start from the scaffold, then delete its assertions.
cp -r templates/harness <repo>/harness
templates/harness/ is the plumbing, and only the plumbing. It is not
Python-only and not web-only: every command lives in harness.config.json,
and the driver is http, cli or library. Proven on a Python HTTP service, a
Node CLI (five config values changed, nothing else) and a Python library.
What it gives you: the step ladder, the markers
with counts, the step-namer, the --quick subset, and an app-process manager that binds
a dynamic port, waits for health and tears down on every path. It runs out of the box.
That split is not a hedge, it is the finding. Two people built this harness from scratch without a scaffold, independently, on different products, and wrote the same file - down to both inventing a "zero tests discovered is not a pass" guard. The plumbing is determined by the marker contract, not by the app.
Every assertion in e2e.py is a worked example and all of it should be deleted.
The same goes for .factory/holdout/run.py and harness/mutations/defects.json.
Each carries a marker line you delete when the content becomes yours, and
factory_doctor blocks at level 2+ until you do - because a gate that is green
about the template's sample product is worse than no gate at all.
The interview produces all three: R1.1 the journey, R2.5a the composed scenarios the builder cannot read, R2.5b the defects that must be caught. What a user would notice is the part nobody can write for you, it is the answer to R1.1, and it is where the real work sits. The scaffold buys you the plumbing; it does not buy you the assertions.
The short version, which is not a substitute for reading it:
- Climb the ladder: static → unit → integration → E2E as the real user → visual judging → holdout scenarios → deterministic gate.
- Draw the independence line after integration. Everything below it is inside the agent's optimization loop, so given time it will satisfy whatever you measured rather than the thing you meant. More tests below the line is not the fix.
- At least two gates must be code the model cannot talk past. The merge itself, and a positive assertion that the app actually started. Everywhere else a "gate" is a prompt instruction, which is a suggestion with good manners.
- Empty is not pass. Assert how many checks ran, not just how many failed. A skipped check returns nothing, and nothing is not a failure.
- The validator never learns how the code was written. Only what was asked and what the code does now.
Deliverable: a validate entrypoint that a workflow can call, that emits explicit
markers, and a merge gate in bash that greps for them.
Phase 4. The workflow-driven repo (component 1)
Read references/automation.md for the headless contract of each agent and what is in
the runner.
Copy the runner; do not write one. templates/runner/factory/ is a working
execution layer - dispatcher, runner, structural gate, protected-path guard, merge,
deploy, state machine, seven node prompts. Its README.md is the install order.
cp -r templates/runner/factory <repo>/factory
mkdir -p <repo>/.factory/{locks,holdout,runs}
Then three edits, and the third is the real work of this phase:
factory/config.sh- the agent, the models, andFACTORY_VALIDATE_CMDpointing at the harness from Phase 3. Every project-specific value lives here; if you are editing another script to change a path, that is a bug inconfig.sh.factory/guard.py- the protected list. Seed it, do not just accept what the interview returned.factory/prompts/*.md- rewrite these as the user's own process. This is where Phase 1's R1.2 answer lands. If they plan with one skill and implement with another, those are two nodes. If a rules file or an MCP server is loaded at a particular step today, load it at that step here.
The interesting property of a factory is that it runs unattended, not that it works differently. A user who recognises their own workflow in these prompts will trust it and maintain it; one who has to learn a new pipeline will not. The prompts are the personalisation. The plumbing is not - and that is exactly why the plumbing ships as a copy and the prompts ship as a skeleton with the decisions marked.
If the user has a workflow engine they already run (Archon, a YAML DAG, GitHub Actions, an Agent SDK program), the runner is still the reference for what the nodes must do - the fresh-context boundary, the tool allowlists, the holdout deny, the commit step, the gate. Port those properties; do not port the bash.
Phase 5. Deployment (component 3)
Read references/deployment.md. It is short and it contains the single trap that
silently kills more factories than anything else: GitHub does not trigger workflows
on commits made with the default GITHUB_TOKEN. The agent commits, the deploy never
fires, nothing errors, and nothing tells you.
If the loop does not end at real users, the user has built a PR generator.
Phase 6. The trigger (component 2)
Only now. Read references/setup.md in full and the automation reference's dispatcher
section.
references/setup.md is the unglamorous half nobody writes down: prerequisites, cron and
systemd and Task Scheduler, the .gitattributes line-ending pin, core.longpaths,
PYTHONIOENCODING, the git check-ignore pre-flight, credential expiry, and how to test
the stop button on purpose. Every item on it broke a real factory. You can have five
perfect components and a machine that has never completed a lap because line endings were
rewritten on checkout.
The dial itself is already enforced in the runner: orchestrator.sh reads
FACTORY_AUTONOMY and refuses each action below its level, so raising it is a deliberate
act rather than a note in a file.
Say this out loud, because almost everyone arrives with the wrong model: nothing pushes. Filing an issue does not trigger a run. There is no webhook and there is not meant to be one - a scheduler wakes on a timer, reads the state, and dispatches at most one thing. An issue filed at 09:01 waits for the next tick. A push trigger that breaks fails silently and looks exactly like a factory with nothing to do; a poll that breaks is a poll you can see not running.
Install it AFTER the first lap, not here. install-trigger.sh refuses below dial 1,
and the dial does not leave 0 until Phase 7 has proven a lap by hand - so Phase 6 as
numbered cannot be executed in order. Build the trigger's configuration now; run the
installer at Phase 7 step 3, when the dial moves. The code is right and this ordering
was wrong.
Arm it with the installer rather than by hand, and note that it refuses while the dial is at 0 - a scheduler at level 0 wakes up forever and correctly does nothing, which is how people convince themselves a factory is running when it has never completed a lap:
bash factory/install-trigger.sh --status # what is armed right now
bash factory/install-trigger.sh --install # cron, systemd timer, or Task Scheduler
bash factory/install-trigger.sh --remove
Then run factory_doctor once more. It now checks whether a scheduler is actually armed,
because a fully built factory with nothing scheduled audits identically to a running one.
The dispatcher must be the dumbest, most deterministic thing in the system. Not an LLM deciding what to run - that hallucinates dispatches for work that does not exist. Bash, a fixed priority order, and shared state that lives in something boring (GitHub labels are enough; no database, no message bus).
Fixed priority, and this order is load-bearing:
- fix a PR that needs fixing
- validate a PR waiting for review
- implement the highest-priority accepted issue
- triage untriaged issues
Finish in-flight work before starting new work. Backwards, and the factory triages forever while its own PRs rot.
Phase 7. Prove it, then get to level 3
The target is 3 and the job is not finished until the dial is there. These steps are the evidence that earns it, not a ladder to stop partway up.
- Run the walking skeleton by hand: one real issue, all the way to a PR you merge yourself. Do not proceed on a factory that has never completed a lap.
python scripts/factory_doctor.py --repo <path> --audituntil it is clean. It refuses level 3 while there is no holdout, which is the check that decides whether the rest of this was real. 2b.python scripts/_test_runner.py --repo <path>andpython scripts/_audit_runner.py --repo <path>. The doctor checks that the repo is set up correctly; these check that the machinery underneath it still works. They are free, they take about two minutes, and a factory that fails them will fail silently - parking work nobody is told about, or re-running a workflow that can only die. Re-run both any time you hand-edit anything underfactory/, and before re-arming a factory that has been idle: the runner is copied into a repo and never linked, so a fix upstream has not reached yours.- Raise the dial to 1, then 2, watching one full cycle at each - then raise it to 3.
Stopping at 2 leaves a person merging every PR, which is the bottleneck the whole build
was for. If the user chooses to stop below 3, write down in
FACTORY.mdwhat would have to be true to go further, so it is a decision with a way out of it rather than a dial nobody touched again. - Write
FACTORY.mdfrom the template - what was built, at which level it currently runs, and what has to be true before the next notch. Link the PRD it was built from, because when the product changes the mission has to change with it, and the factory will keep faithfully building the old scope until someone notices.
Operating facts - NOT a speech to deliver
Do not recite this section. It reads like an opening briefing and it was being
delivered as one, which is six dense paragraphs before the user has done anything. These
are facts you need in order to build correctly, and each one belongs at the single moment
it becomes actionable - the token bullet when the trigger goes on, the git check-ignore
bullet when the first committing workflow is written, one line each. If the user asks what
they should watch out for, then answer from here, shortest first.
- The PRD is now a live document, not a kickoff artifact. In normal development a
PRD goes stale and a human quietly compensates. Here nobody compensates: the factory
builds the scope it was given until the scope is edited. Changing what the product
is means editing
MISSION.md, in a human commit, on purpose. - Instrument tokens on day one, before the first unattended run. Not as a warning - as a measurement you will want and cannot reconstruct later. One "fix an issue" run is far more agent sessions than it looks like from the outside, and the only way to know what yours does is to have been recording from the first lap.
- Put one premium model in the planning slot and a cheaper one everywhere else. Premium in one of the two slots that matter buys most of the quality of premium in both. Premium in zero slots is what actually costs you.
- Leash every editing node to its own diff. A node that can edit without a file scope will grow a six-file PR into eleven and introduce a bug on the way through.
- Run
git check-ignore -von every config file before the first workflow that commits. Agit add -Ainside a PR-create step publishes whatever was not ignored, and public means public. - The agent is the interchangeable part. The plumbing is not. Credential expiry, cost cliffs, no default session timeout and sandbox egress are the same problems in every agent, and none of them solve it for you.
Resources
dark-factory-diagram.png: the whole system on one page - the five components, the three governance files, the ladder and the independence line. For the human reading this repo, not for the agent. Do not narrate it during a build.references/interview.md: the interview, in three rounds - three questions that decide the project, seven about software the user already knows, and one call of defaults to confirm. Every question goes through the question tool and carries a recommendation, no question names a concept the user has no reason to know, and there is a one-breath plain-English line for each piece of jargon. Read in Phase 1.references/guidance-layer.md: the three-file split, the placement test, protected files, and how to write an out-of-scope list that does real work. Read in Phase 2.references/validation-harness.md: the ladder, the independence line, holdout design, structural vs prompted gates, and the failure modes. Read in Phase 3 before writing any check.references/automation.md: headless contracts for eight coding agents, orchestrator options and trade-offs, and the dispatcher rules. Read in Phases 4 and 6.references/deployment.md: deploy strategies, theGITHUB_TOKENtrap, and the GitHub scheduling gotchas. Read in Phase 5.references/setup.md: prerequisites, the platform tax, scheduling, and turning it on. Skim in Phase 0b to refuse early; read in full in Phase 6.templates/:MISSION.md,FACTORY_RULES.md,FACTORY.md. Copy and fill; never ship a template's placeholder text. There is no separateorchestrator.shorvalidate-gate.shsketch any more - they were strictly worse duplicates of the real ones intemplates/runner/factory/, and shipping a second definition of the pipeline is the exact failureautomation.mdwarns about. The one nobody runs is the one that drifts.templates/runner/: the working execution layer, ~3,000 lines, copied into the repo in Phase 4. Read itsREADME.mdfor the install order and the list of things that are load-bearing. Its comments record real incidents - a factory rebuilt from the design alone rediscovers every one of them, unattended, in production.templates/harness/: the validation harness's plumbing, copied in Phase 3. Runs out of the box; every assertion in it is an example to delete. The factory harness is templatable and so is the harness's plumbing - what is not templatable is what "working" means for this product, and that is the whole of component 5.scripts/factory_doctor.py: deterministic audit of a factory repo - protected files, holdout leaks, gate-is-code, empty-is-not-pass, ignored secrets, autonomy level. Run it in Phases 2 and 7. Never read its source into context; only its output.scripts/_test_factory_doctor.py: the doctor's own tests. Builds a healthy factory, breaks one thing at a time, and requires the doctor to notice. Run it after changing the doctor. A gate that has never failed is a gate nobody has tested, and that applies to this skill's gate too.scripts/_test_runner.py: the runner's behaviour suite, and the answer to "is this factory actually sound?" It builds a real git repo with the realfactory/in it, stubs the agent and the validator so a full lap is free and deterministic, and then drives the actual shell scripts. Every test is named after the defect it locks.python scripts/_test_runner.py # the shipped template python scripts/_test_runner.py --repo <path> # a factory somebody BUILT python scripts/_test_runner.py --mutate # do the tests catch anything?--repois the one to remember. The runner is COPIED into a repo and never linked, so a fix to this template reaches nothing already built, and a hand-edited factory drifts with nothing watching. Run it against a factory before trusting it unattended again.--mutateis what keeps the suite honest. It restores each historical defect into a throwaway copy and requires the suite to go RED. A test whose defect can be put back while everything stays green is decoration, and it is named as such. This is the same argument the skill makes about mutation-testing your product, turned on itself - and it has already caught one test here passing for the wrong reason.scripts/_audit_runner.py: the structural invariants no behaviour test can express - a knob read by a child process thatconfig.shnever exported, a prompt placeholder the renderer does not substitute, a state nothing dispatches on, an unguarded command that dies before the escalate on the next line.--repoworks here too. Wherefactory_doctoraudits YOUR repo, this audits the MACHINERY: its findings are bugs in the factory rather than gaps in your setup, and a correctly configured repo running broken machinery passes every check the doctor has.
<!-- Modified by Automation Skills on 2026-11-24: relative links to files that were not copied now point to the original repository. -->Why these two exist. The same four failure shapes kept reappearing in this runner, each found by hand and fixed as a one-off. The reason is the one this skill spends five phases making about your code: there was no harness. ~4,200 lines of runner shipped with nothing that ever executed it, so every fix was a sentence in a document rather than a thing that goes red. If you take one idea from this skill into your own repo, take that one - and notice that it applies to the tools you build as much as to the product they build.
Open this reference as its own page
The agent, the orchestrator, and the dispatcher
Three separate choices that people collapse into one. Separate them explicitly in the interview, because only one of them is hard to change later.
| Choice | What it is | How replaceable |
|---|---|---|
| The coding agent | what turns a prompt into edits | Very. It is a config value. |
| The orchestrator | what defines and runs multi-step workflows | Hard. This is the real commitment. |
| The dispatcher | what decides when anything runs at all | Easy, and it must stay boring. |
1. The coding agent
Every headless coding agent exposes nearly the same contract: a print or exec flag, a structured output mode, a way to skip approvals, and a session id to resume. The factory shells out to a command and reads the exit code. That is the whole interface.
| Agent | Headless invocation | Worth knowing |
|---|---|---|
| Claude Code | claude -p "..." --output-format json |
--allowedTools, --disallowedTools, --permission-mode, and --max-budget-usd as a hard per-invocation spend cap. There is no --max-turns; see the warning below. |
| Claude Agent SDK | Python claude-agent-sdk, TS @anthropic-ai/claude-agent-sdk |
In-process instead of shelling out. Better when you want to inspect or interject mid-run. |
| Codex | codex exec --sandbox workspace-write --ask-for-approval never |
Sandbox modes are the thing to get right. |
| Cline | cline schedule create ... --cron "0 2 * * *" |
Ships native cron, so part of the dispatcher is built for you. |
| Goose | goose run --instructions <file> |
Has its own goose schedule too. |
| Amp | amp -x "..." |
Webhooks available if you want event-driven instead of polling. |
| Pi | pi --print / JSON mode |
Provider-independent; useful when the point is not being locked to one model vendor. |
| Antigravity | agy -p "..." --output-format json |
Watch the default print timeout - it is short, and it will kill real work mid-run while looking like a model failure. |
Verify the exact flags against current docs before writing them into a workflow. CLI surfaces move, and a flag that silently changes meaning is worse than one that errors. Several of these CLIs do not reject unknown flags - the value falls through into the prompt instead - so a stale flag becomes invisible prompt injection.
This page got it wrong, which is the best possible demonstration of why it says so. It listed
--max-turnsas a Claude Code flag. It is not one. Claude Code accepts it, ignores it, and exits 0 - so the runner passed a cost cap on every node, the comments all claimed a cap was in force, and no cap ever applied. Nothing errored, nothing logged, and the only reason it surfaced is that somebody ranclaude --help.A guard that silently does not apply is worse than no guard, because you stop watching the thing it was guarding. Run this before trusting any flag you write into a workflow:
for f in --allowedTools --disallowedTools --permission-mode --max-budget-usd; do claude --help | grep -q -- "$f" && echo "OK $f" || echo "MISSING $f" doneAnd prefer a dollar ceiling to a turn ceiling regardless. Turns are a proxy for cost and a bad one;
--max-budget-usdis the thing you actually care about, and it genuinely enforces - the run comes backis_error: truewhen it trips.
Choosing
Pick the one already authenticated on the machine that will run the factory. Not the best one. The one that works today. Because the agent is genuinely swappable, this choice is cheap and reversible, and treating it as the big decision spends attention that belongs in component 5.
What does not port
Say this out loud, because it is where the real time goes:
- credential expiry, silently, mid-run
- cost cliffs nobody warns you about
- no default session timeout in most of them
- sandbox egress you have to design yourself
Same four problems in every agent. None of them solve it for you.
2. The orchestrator
What defines "plan → implement → review → gate → merge" as steps with dependencies. The real commitment; changing it means rewriting every workflow.
There is one in the box
templates/runner/ is a working orchestrator of the first kind below - plain scripts,
one machine, total transparency - lifted from a factory that runs. Copy it unless you
have a reason not to:
| file | what it is |
|---|---|
factory/config.sh |
the only file you edit. Agent, models, validate command, markers, dial, limits, paths |
factory/orchestrator.sh |
the dispatcher: fixed priority, per-target lock, autonomy dial, stop button |
factory/run-workflow.sh |
the runner. THIS is the orchestrator - there is no second definition of the pipeline |
factory/gate.sh |
the structural gate: required markers, counts, calibration, verdict |
factory/guard.py |
protected paths and the size cap. Fails closed |
factory/merge.sh |
the merge. Code, never a model |
factory/deploy.sh |
poll, health-check, swap, rollback |
factory/state.py + gh_backend.py |
the transition table, and GitHub labels as state |
factory/tripwire.py · cost.py · node_failure.py |
holdout tripwire, token instrumentation, why-a-node-failed |
factory/prompts/*.md |
the seven nodes. The interview's output - rewrite these |
Two definitions of one pipeline is one too many. That repo carried YAML DAG
definitions alongside the bash for a while, on the theory that an engine would run them.
Nothing did, so they drifted - and what they drifted into was a deny_paths entry that
made the holdout read-block look enforced when the only thing enforcing it was a sentence
in a prompt. A stale spec that invents a safety property is worse than no spec, and
the one nobody runs is always the one that drifts. Pick one definition.
If you are bringing your own engine, the runner is still the reference for what each node must do: fresh context per node, tool allowlists, the holdout deny passed to the agent, an explicit commit step, the guard from the root checkout, governance from the base branch. Port the properties, not the bash.
| Option | Shape | Good when | Cost |
|---|---|---|---|
| Plain shell scripts | sequential calls, exit codes | small factories, one machine, total transparency | no parallelism, no resume, state is yours to invent |
| A YAML DAG runner | declared nodes and edges, per-node model and tool limits, artifacts dir | you want node-level control of context isolation and tools - which component 5 needs | a dependency to run and understand |
| GitHub Actions | jobs and steps in the repo | you want it in CI with no extra infrastructure | ephemeral runners make long E2E and app-startup awkward; watch the token trap in deployment.md |
| An agent SDK, in process | your own program driving sessions | you need custom control flow or to interject mid-run | you are now maintaining an orchestrator |
| Model-led orchestration | one agent spawns and coordinates others | flexible, adapts to unexpected shapes | non-deterministic; the shape of the work is decided by a model each time |
The genuine trade-off, stated fairly
A declared DAG means you wrote the nodes and edges, and the model fills in the work without choosing the shape. Reproducible, debuggable, and it lets you set tool allowlists and fresh-context boundaries per node - which is how the holdout gets enforced structurally rather than by instruction.
Model-led means a coordinating agent decides how to decompose and spawn. More adaptive, less predictable, and much harder to prove an independence property about.
Neither is the winner. But note which one component 5 needs: the holdout is a statement about what a given step is allowed to read, and that is far easier to guarantee when the steps are declared than when they are invented at runtime.
3. The dispatcher
The dispatcher must be the dumbest, most deterministic thing in the entire system. It is the one component where a wrong answer is worse than no answer.
Do not ask a model what to run
An LLM asked "what work is pending?" will invent dispatches for work that does not exist - runs for issues that were never filed, PRs that do not exist. It is a plausible-sounding answer with nothing behind it, and the factory then acts on it.
Bash. A fixed priority order. Boring shared state.
Shared state
GitHub labels are enough, and they have a real advantage: they are visible, editable by a human from a phone, and they are the audit trail.
factory:accepted → factory:in-progress → factory:needs-review
├── factory:approved (merge, then deploy)
├── factory:needs-fix (back to in-progress)
└── factory:needs-human (stop; the only thing that reaches you)
No database. No message bus. If information has to travel between workflows, it moves as a label or a comment. That constraint keeps the system inspectable, and inspectable is the property you will want at 2am.
Four things labels are not, all learned the hard way
Labels are good shared state and a bad lock. Every one of these was written down as a prediction first and then contradicted by a real run.
- There is no compare-and-swap. Two dispatchers reading
factory:acceptedboth claim the issue, because "read the label, write the label" is not atomic and nothing in the API makes it so. Moving to GitHub does not retire your per-target lock. If you built one for the file backend, keep it; the label is the audit trail, not the mutex. - Label writes are not immediately visible to label reads. Measured lag between setting a label and seeing it on the list endpoint was two to four seconds. A dispatcher that writes then immediately re-reads will occasionally see the old world.
- The stop button must be a label you ADD, and the read must fail closed. "Remove a
label to stop" is the obvious design and it is backwards: a missing label is
indistinguishable from an API call that failed to list it, so a network blip reads as
"carry on". Add
factory:stop, treat any error listing it as stopped, and keep a local kill file too, because the local one works with the network down. - Closed is not a disposition.
deferredandrejectedare both closed issues and are indistinguishable without labels. Get that wrong and the factory rejects the roadmap the quarter it arrives, which is the failure the mission file's deferred-versus-never split exists to prevent. GitHub also performs transitions your table never authorised:Closes #Nin a merged PR closes the issue, so closed-and-unlabelled is a real state you have to handle.
Branch protection does not replace your merge script
The tempting move on GitHub is to delete merge.sh and let a required check plus branch
protection be the gate, on the grounds that a ruleset is not something the agent can
edit.
It is, in the case that matters. The factory authenticates as a principal that administers the repository, and an account that can edit a ruleset can bypass one. Unless you have provisioned a separate least-privilege identity for the factory, and verified it cannot administer the repo, the merge stays in code you control.
Two smaller traps in the same area: nothing publishes a check run if your gate executes on the dispatching machine rather than in Actions, so a required check that never reports blocks every merge forever. And a third-party App can comment on a PR seconds after it opens, so a judge that reads PR comments is reading a stranger's text. Have it read the diff and the issue from disk instead.
Priority order, and why it is load-bearing
- fix a PR labelled needs-fix (under the attempt cap)
- validate a PR labelled needs-review, oldest first
- implement the highest-priority accepted issue
- triage untriaged issues
Finish in-flight work before starting new work. Reversed, the factory triages forever while its own PRs rot, and throughput looks busy while going to zero.
A node that exits 0 having done nothing
Three separate versions of this showed up in real dispatch, and none of them were visible when the same workflows were driven by hand.
- An agent hit its turn cap, escalated, and the message named a fault that did not exist. The expensive planning half had been paid for and thrown away. Read the agent's own JSON result and report the real terminating reason.
- An agent asked to run a command its allowlist did not cover, was refused, said so politely in prose, and exited 0 having changed nothing. A tool denial is not a failure and it is not a success; it is the node telling you it wanted something it could not have. Log denials per node, and quote them into the escalation whenever the diff comes back empty. Doing this once revealed that a planning node had been silently denied tools on essentially every run since it was written, asking, being refused, and working around it.
- A node edited its worktree and committed nothing, and the cleanup removed the worktree seconds after the guard had correctly reported two changed files. A human commits without being told to. An agent does not, unless the workflow makes it a step.
The general rule: assert on the artifact, not on the exit code. A run that produced no commit, no PR and no diff did not succeed, whatever it returned.
Limits that are not optional
- Attempt cap. Two fix attempts per PR, then escalate. Without it a PR ping-pongs until the budget is gone.
- Concurrency cap, starting at one. Raise it only after the serial version is boring. When you do raise it, add a per-target lock: never dispatch a workflow whose (workflow, target) pair is already in flight, or two runs will race on the same PR.
- Batch caps. Cap triage per run. A backlog should drain across cycles rather than in one expensive burst.
- Flood protection, if other people can file issues. Cap issues per author per day; exempt yourself.
- A stop button. A kill file the dispatcher checks, or disabling the schedule. Obvious, documented, and tested once on purpose.
Scope every editing node to its own diff
Any node that edits code must be leashed to the files it is allowed to touch:
git diff --name-only <base>...HEAD
A cleanup or refactor node with no diff scope will grow a six-file PR into eleven, and introduce a bug on the way through. If a node cannot name the files it may touch, it will touch more of them.
Model routing
Two slots decide quality: the one that plans and the one that implements.
Putting a premium model in one of them buys most of the quality of putting it in both. Going from zero premium slots to one is a large, real improvement. Going from one to two is usually inside the noise.
Plan with the expensive model. Build with the cheaper one. Picking the wrong slot is cheap. Running a premium model in zero slots is what actually costs you.
Measure this on your own repo before believing it, and state your noise floor when you do - a benchmark without one is a story.
Open this reference as its own page
Deployment
Component 3 is the shortest to build and the easiest to skip. Skip it and you have not built a factory; you have built a PR generator with extra steps.
On merge it ships, and real users get the code.
If merging does not produce a running application, nothing downstream of the merge is real, and the validation harness has been proving things about software nobody runs.
The trap that silently kills factories
GitHub does not trigger workflows on commits made with the default
GITHUB_TOKEN.
This is documented behaviour, it exists to prevent infinite workflow recursion, and it is the single most common way an autonomous loop dies quietly:
- The agent commits and merges, authenticating with the default token.
- Your deploy workflow has an
on: pushtrigger. - It never fires.
- Nothing errors. Nothing logs. No alert. The PRs keep merging and the site keeps serving the old build.
Two fixes:
- Authenticate as a GitHub App (or use a PAT) for the commits that should trigger downstream workflows.
- Poll instead of pushing. A deploy process that checks the branch on a timer cannot be silently skipped, because nothing had to fire for it to run. Slower to react, impossible to miss.
For a factory the polling option is often the better trade: this is a system whose defining property is that nobody is watching it, so prefer the mechanism that fails loudly over the one that fails silently.
Two more from the same docs
- Scheduled workflows only run from the default branch. A cron sitting on a feature branch does exactly nothing, forever, with no warning.
- On a public repo, GitHub disables scheduled workflows after 60 days with no repository activity. A factory that goes quiet gets switched off for being quiet - and then stays off, which looks identical to "it had nothing to do."
Both are worth a note in FACTORY.md, because both present as "the factory stopped
working and I cannot see an error."
Deploy strategies
Pick the simplest one that gives a rollback.
| Strategy | How | Rollback | Good when |
|---|---|---|---|
| Blue / green | build the inactive colour, health-check it, flip the proxy upstream, stop the old one | flip back; the old build is still warm | a long-running app you control the host for |
| Platform deploy | push to a platform that builds and swaps for you | platform's own rollback | you would rather not own the host |
| Container tag swap | build, tag, restart against the new tag | retag the previous image | already containerised |
| Static publish | build artefacts, publish to a CDN | republish the previous build | front-end only |
Whatever the choice, it must no-op safely when nothing changed. An unattended deploy loop runs far more often than it deploys, and a deploy path that does work on every tick will eventually do damage on a tick where nothing happened.
The health check is part of the deploy, not a nicety
Never swap traffic onto a build that has not answered a health check. In an unattended system this is the last gate before real users, and it is the only one that runs after the merge.
Wiring it to the loop
The deploy is downstream of the merge, and it should be observable from the same place everything else is:
- Merge happens (squash, so history stays readable and rollback is one revert).
- Deploy triggers - by App-authenticated push, or by poll.
- Health check gates the traffic swap.
- The result is visible somewhere the factory can read. A status endpoint, a deploy log the scheduled test can check.
That last point matters at level 4. If a scheduled comprehensive test can read the live health of the deployed app, it can file its own issue when the deployment is broken - which is how the loop closes without a human noticing first.
What to tell the user
- The loop is not closed until a stranger can see the change. Everything before that is a PR generator.
- Prefer the mechanism that fails loudly. Polling over push triggers, health checks over assuming, explicit markers over the absence of errors. This is the same principle as empty is not pass, applied to infrastructure.
- Decide the rollback before going unattended. "I would fix forward" is a valid answer, but it has to be an answer, not a discovery made during the incident.
Open this reference as its own page
The guidance layer
Three files, three different jobs. The split is the whole teaching.
Almost everybody stuffs all of this into one conventions file and then wonders why the agent drifts, argues with its own constraints, or edits the rule that was inconvenient.
| File | Owns | Example |
|---|---|---|
conventions (CLAUDE.md / AGENTS.md) |
constraints and conventions any project has | Bun, not npm. All SQL lives in repository.py. |
FACTORY_RULES.md |
how the agent operates unsupervised | Max 500 lines per PR. Never edit a test to make it pass. Touching a protected file is an instant reject. |
MISSION.md |
what is being built, and what is deliberately out of scope | No payments. No mobile app. No second channel. |
The placement test
For every rule, in order:
- Would you write this even if a human were doing the work? → conventions file.
- Does it only exist because nobody is watching? →
FACTORY_RULES.md. - Is it about what the product is and is not? →
MISSION.md.
Three borderline cases, resolved
- "Max 500 lines per PR." Feels like a code convention. But no human on the repo is bound by it - it exists purely because an unsupervised agent will otherwise ship 3,000 lines nobody can review. Factory rule.
- "Provider X is the only LLM provider." Looks like a stack line for the conventions file. The failure it prevents is scope drift, not inconsistency. Mission invariant.
- "Every endpoint stays authenticated." Genuinely lives in two files, and the
duplication is deliberate:
MISSION.mdowns it as product truth,FACTORY_RULES.mdrestates it as an auto-reject trigger. The file read at reject time has to contain the rule. Duplication for a mechanical reason is fine; duplication by accident is how files drift.
If a conventions file already exists
It usually does, and it is usually carrying all three jobs at once. Split it, do not
replace it. Run the placement test over every line already in there and move the
factory-only rules out into FACTORY_RULES.md and the product truths into
MISSION.md. What is left is the conventions file, and it will be shorter than it was.
This split is often the most useful single edit made to an existing repo, and it pays off whether or not the user ever turns the cron on: a conventions file that only holds conventions is a better conventions file for interactive work too.
If CI already exists, READ IT before writing the gate
Noticing that .github/workflows/ exists is not the same as reading it, and only the
first was happening: a test run passed Phase 0 on the strength of "there is CI", protected
.github/, and never once opened the file. The CI already asserted something the merge
gate was about to re-implement from scratch, and nobody noticed.
So open it. Two things come out:
- Commands you do not have to invent. Whatever CI runs for lint, types and tests is a
tested answer to
staticandunitinharness.config.json. Reuse it rather than writing a second definition that drifts from the first. - Assertions that already exist. If CI enforces something real - a dependency ban, a coverage floor, a schema check - that is a rung you already have. Say so, and spend the time on the rungs above the independence line instead.
Then say which one is authoritative. The factory's gate is what decides a merge, so if CI
and the gate disagree the gate wins - but a CI that stays red while the factory merges
happily is a contradiction someone will trip over. Either point CI at
FACTORY_VALIDATE_CMD so there is one definition, or write down that CI is advisory here.
The property that matters
The agent cannot amend the rules it is judged by.
All three files go on the protected list. A PR that modifies any of them is auto-rejected before anything else is evaluated, and the validator reads all three from the base branch, not from the PR under review. Without that ordering, a PR can weaken its own rulebook and then pass against the weakened version.
This is the single property that turns a thing that writes code into a thing you can leave alone.
The protected list
Any PR touching these is rejected outright, with no fix attempt, and the underlying issue escalates - because touching one implies the factory misunderstood the scope.
Seed it with all of these, then ask what else:
- Governance: the three files above.
- CI and repo config: everything under
.github/, workflow definitions, issue and PR templates, CODEOWNERS. - Infrastructure: Dockerfiles, compose files, anything under
deploy/orinfra/, systemd units, platform config (fly.toml,render.yaml,Procfile). - Secrets and auth:
.envand every variant, any agent or tool config file that holds a token, anything named like a credential, and the modules that define which endpoints are protected. - Security invariants: rate-limit constants and their enforcement path, CORS, CSRF, and auth middleware.
The pre-flight that prevents the worst incident
Before any workflow that produces a commit, run:
git check-ignore -v <every-config-file-that-could-hold-a-token>
Empty output means your next run publishes your key. A git add -A inside a
PR-create step sweeps in whatever was not ignored, and on a public repo that is
publication, not a mistake you can take back. Rotating afterwards is the cleanup, not
the fix.
Add the check as a node in the workflow, not as a line in a checklist a human reads.
Writing MISSION.md
It is derived from the PRD, not written from scratch
MISSION.md is the PRD compressed to the part an agent has to obey. Do not start from
a blank file, and do not paste the PRD in whole either. Map it:
| PRD | MISSION.md |
|---|---|
| problem, why it matters | the opening paragraph, kept short |
| users | one line, because it is what the E2E path is acted out as |
| MVP scope, capability areas | In scope |
| non-goals | Out of scope, forever (see the sort below) |
| success metrics | what a merged change is ultimately meant to move |
| anything marked TBD | do not carry it over as a rule. It becomes an entry in .factory/decisions.md - proposed by the factory, held at the merge, and answered ONCE. A blanket needs-human trigger here is what makes an honest PRD block every issue downstream of it |
The sort that matters: "not now" is not "not ever". A PRD's non-goals are usually a mix of the two, because a PRD is written to keep a team focused for a quarter and nobody has to be precise about which is which - a human reading it just knows. An agent does not. Anything logged as out-of-scope will be rejected at triage forever, including next quarter when it becomes the roadmap.
Walk the non-goals one at a time and sort them into three piles:
- Never. Goes in
MISSION.md. - Not yet. Goes in the backlog, and must not appear in
MISSION.mdat all. - Never, and it is a property rather than a feature. That is a hard invariant, and
it belongs in the invariants section below plus
FACTORY_RULES.md.
If sorting leaves fewer than five items in the first pile, the list is too thin. Go back to the interview and get more.
The two sections that do the work
Two sections do the real work, and one of them is the one people skip.
In scope - the capability areas the factory may build. Short. Triage accepts against this.
Out of scope, forever - the section that earns its keep. This is how an agent recognises that a plausible, well-argued, easy-to-implement feature request is drift rather than a good idea. Without it, every request is arguably in scope, because almost every feature is defensible in isolation.
Aim for at least five, and make them things a reasonable person might ask for:
No payments or subscriptions. No mobile or desktop apps. No additional content sources. No public API for third parties. No social features - no comments, no reactions, no sharing. No alternate input modes.
Hard invariants are different from out-of-scope items and deserve their own section. Out-of-scope is features you will not add. Invariants are properties that cannot be edited: a rate limit, an auth requirement, a privacy guarantee, a single-tenant assumption. An issue arguing well for changing one is rejected at triage as a security concern, not debated.
Writing FACTORY_RULES.md
Cover these sections. The templates directory has a fuller skeleton.
- Triage rules - what to accept, reject, or hand to a human. Bias toward reject on ambiguity and say so explicitly: a false reject costs one comment, a false accept costs a wrong PR and a validation cycle.
- Implementation rules - the absolute prohibitions. Never edit a test to make it pass. Never touch a protected file. Never add a dependency without justification in the PR body. Never exceed the size cap. Never build beyond what the issue asked.
- Quality gates for auto-merge - the enumerated list of conditions, every one of which must be true. Mark which are enforced in code.
- Auto-reject triggers - failures that cannot be fixed incrementally, so the PR is closed rather than sent back.
- Escalation - what makes it stop and ask for a human, and how a human clears it.
- Cost and throughput limits - batch sizes, attempt caps, concurrency, priority order.
- Separation of concerns - the holdout rule, written out: what the validator may read and what it must not.
- Communication style - how the factory writes comments. Lead with the decision, cite the rule by section number, stay neutral, leave an appeal path, never promise future behaviour.
- How this file changes - human commits only. It is on the protected list.
Why section numbers matter
Require the factory to cite the rule that drove a decision, by section number, in every comment it posts. Two reasons, both practical:
- A filer who gets a rejection citing a rule can read the rule and appeal against it. A rejection with no citation reads as arbitrary.
- You get a usage trace of your own rulebook. Rules that never get cited are either never triggered or never read, and both are worth knowing.
The best artifact a factory can produce is not a merged PR. It is an issue where the system read a bug report, worked out the real cause was outside its own repository, noticed that fixing it would require touching protected files, cited the two sections that made that a reject, declined the work, and left an appeal path.
An autonomous system correctly doing nothing is what the guidance layer buys.
Open this reference as its own page
The interview
Three questions decide the project. Six more only the user can answer. Everything else is a default they confirm.
That is the whole shape, and it is deliberate. The first version of this file asked 28 open questions in component order, and it failed in a specific way: it opened by asking what someone would spend per issue - a question its own notes admitted almost nobody can answer - and it asked, open-ended, for things the templates already ship a right answer for. Asking someone to invent the protected-path list, the poll interval and the holdout directory teaches them the interview is homework rather than a conversation, and the ones that actually decide the build arrived a dozen questions later, after the room was lost.
Proposing a default is not a shortcut, it is a better question. "I am going to protect these five paths, plus your CI config - anything else?" gets a more useful answer than "which files must the agent never touch?", takes ten seconds, and cannot be answered wrong by someone who has not built one of these before.
Read the PRD before asking anything, and never ask what it already answers. Play its scope and non-goals back as a proposal - "so triage accepts work in these four areas and rejects these six, correct?" - and spend the time on what it left open. Making someone retype a document they already wrote is the most common way a well-designed interview fails.
EVERY QUESTION GOES THROUGH THE QUESTION TOOL. AskUserQuestion in Claude Code, or
the equivalent elsewhere. Not most questions, not the ones with obvious options - every
one, including the open-ended ones. This is a hard requirement and it has no exceptions.
The earlier version of this file split questions into pickers and prose and argued the split was load-bearing: that offering options for "describe the most valuable thing a user does" replaces the answer you need with a menu of your guesses. That argument was wrong, and it was wrong for a mechanical reason:
The question tool always carries an "Other" escape with free text. So an open-ended question loses nothing by being asked through it. The user who wants to answer in their own words still can, in one keystroke. The user who would have skimmed a paragraph and replied "you pick" now sees three concrete candidates and corrects the one closest to right - which is the answer you wanted and would not have got.
What was true in that old argument survives as a constraint on the OPTIONS, not on the tool: for an open question, the options must be drafted from their own PRD and their own repo, and cited, never invented. A draft from their material is their answer played back and they will happily overwrite it. An invented one anchors them onto your guess. If you have nothing to derive options from, say so in the question text and lean on Other.
Shape of a call:
- Two to four options, one marked
(Recommended)and placed first. - Each
descriptionis one line: what it means, or what happens if they pick it. - The
headeris 12 characters or fewer. - Batch related questions into a single call - the tool takes up to four - but never batch the three Round 1 questions, which are asked one at a time and in order.
- Never ask a question the PRD already answers. Play that back as a proposal instead.
A question that wants a LIST - R2.1 asks for five things, R2.2 for a set of invariants - is a multi-select whose options you drafted from their PRD's non-goals, plus Other for what you missed. Four drafted candidates they can tick is a far better prompt for the fifth than a blank line, and the ones they deselect are as informative as the ones they keep. Ask once more with what they added if the first pass produced fewer than you expected.
Two rules that apply to every question below
1. Always carry a recommendation. Every question, no exceptions.
Never hand someone a blank page. A question with no proposed answer is homework; the same question with a draft attached is a two-second correction. This is the single biggest difference between an interview that finishes and one that gets abandoned in the middle.
Mark exactly one option (Recommended) and put it first, with the reason in its
description, in one line.
For an open-ended question the options ARE the draft. Derive them from their PRD and their repo and cite the source in the question text, e.g. "From §6 of the PRD the journey looks like: open the app -> shorten a URL -> follow the short link -> land on the original." Then offer that as the recommended option, one or two plausible alternatives, and let Other carry anything you did not think of.
Where a recommendation would be dishonest - a genuine coin-flip, or something only they can know - say that instead of inventing confidence: "I have no basis for a recommendation here; it depends on X." That is still better than silence.
2. Offer to explain the hard parts, before they answer
Several of these questions use vocabulary that is obvious only after you have built one of these. A user who does not want to admit they have not heard of a holdout will guess, and a guessed answer becomes an unenforceable rule.
So offer the explanation rather than waiting to be asked: add an explicit "Explain this first" option as a real choice. It costs one line and it gets picked more than you would expect.
The terms that need it, and how to say each in one breath:
| Term | One breath |
|---|---|
| holdout | Tests the AI writing the code is not allowed to read, so it cannot tune its work to pass them. It is the only honest reason to merge code nobody reviewed. |
| mutation set | You break the code on purpose, in specific ways, and check the tests notice. It measures your tests, not your code. Until you have run it you do not know your tests can fail at all. |
| the independence line | The line between checks the AI can see and checks it cannot. Everything below it is inside its optimisation loop; given enough tries it satisfies those rather than the thing you meant. |
| the ratchet | A floor on how many checks must run, kept in a file the AI is not allowed to edit. It stops quality being quietly traded away one deleted assertion at a time. |
| a structural gate | A merge decision made by code, not by a model summarising its own work. Two of them must be code, or "it looks fine to me" is the whole gate. |
| the autonomy dial | How much runs without you, 0 to 5. Level 3 is the one that matters: code merges without a human reading it. |
| E2E / the happy path | One journey through your software the way a real user takes it, asserted end to end. Not a test per function - the single most valuable thing someone does. |
APP_STARTED / proof it is running |
One specific thing your software says when it is genuinely up - a page that returns a known word, a command that prints a version. Without it, software that crashed on startup and software that is fine look identical to the checks, and "could not test it" gets counted as "nothing wrong". |
APP_STARTED is on that list because a real run showed it being rubber-stamped. The
user said "sure, whatever you said, known address known response, fine" - and it is one
of only two gates that must be code. It sounds obvious to anyone who has run a service and
means nothing to anyone who has not. Explain it before asking R2.3, not after.
Use those words when the user is not technical, and use the precise ones when they are. Do not lecture: one breath, then the question, then offer more.
Reflect every answer back as a concrete artifact before moving on - "so the merge gate
is: the PR merges only if APP_STARTED and E2E_PASSED both appear in the run output."
The point of the interview is to turn opinions into things that can be written down and
run.
Push back on vague answers. A vague answer becomes an unenforceable rule, and an unenforceable rule is worse than none: it reads like a guarantee.
3. Say where the finish line is, and say it again around question eight
Attention runs out before the questions do. In a real run the user asked "how much longer is this? I'm quite keen to see something on a screen" immediately after R2.4 - question eight of twelve, and two questions before R2.5b, which is the one that produces the mutation set and the one you least want answered by somebody who has stopped thinking.
The recovery that worked was a named finish line plus a promise about the deliverable:
"Two more real questions, then one list you skim and click through. Then we build. And I'll say exactly what the first thing on the screen will be before I write anything."
Not "a few more". A count they can hold. Say it when you start Round 2, and say it again if you sense drift - a user who keeps typing after they have disengaged is worse than one who says they are bored, because the answers keep coming and they stop being true.
Round 1 - the three that decide the project
Ask these first, one at a time, before any component discussion. If someone walks away after three questions, these are the three you needed.
On a greenfield repo, R1.1 is about the SKELETON, not the product. Ask for the journey the way it is written, because it defines what the product is for - then say which one-slice version of it you are building first, and that everything else in it is issue one, two and three. See Phase 0c. Getting this wrong is the standard greenfield failure: the agent builds the MVP by hand so the harness has something to test, and the factory inherits the leftovers.
R1.1 - "Walk me through the single most useful thing someone does with this, from the first click to the thing they end up looking at."
The question. The answer becomes the main path the factory checks on every change.
Force it concrete. Not "users can search", but: open the app -> sign in -> type a query with a known answer -> the response streams in -> it shows a citation -> click it -> a window opens at the right spot.
Draft it from their PRD first. The MVP section is usually most of this already. Offer that as the recommended option and ask what is wrong with it.
Bad answer: anything with nothing you could point at on a screen. If you cannot see it, nothing can check it, and the agent will tell you it works.
R1.2 - "How do you build a feature with AI today?"
Let this run long, and do not interrogate. One open question with a drafted answer, not
a five-part questionnaire about planning, implementation, review, tooling and frameworks.
Take what they give you, then go and look: CLAUDE.md, AGENTS.md, .claude/, .cursor/
are usually in the repo already and answer the tooling half without asking anything.
Then say it once, plainly: every step you just described becomes a step the factory runs, and the only difference is that nobody clicks approve between them.
One follow-up, because it is worth more than the rest: "which of those steps do you actually read, and which do you just approve?" The rubber-stamped ones are free autonomy. The ones they genuinely read are where the checking has to get good.
If they have no process - "I describe the thing, paste it in, run it, paste the error back" - that is a real answer and it is the one being automated. Do not dig. Say:
"That is the process, and we are automating it. The only difference is that right now the check is you looking at the result - so the next few questions are about building checks that are better than that look, because that look is what goes away."
Then take the shipped prompts as the starting point and say so.
R1.3 - "Are you willing to let code reach your users without anyone reading it first?"
Ask exactly that, then show the dial. Level 3 is the recommendation - say so. People often say 5; 5 means the factory writes its own work from the mission, which is a different decision entirely.
Expect a pause. That pause is the entire build in one question, and everything in Round 2 exists to make the answer yes.
Then the follow-up that calibrates everything after it: "if a bad change did get through, what is the worst that happens?" A side project, an internal tool, or real users and real money. That decides how much of the checking has to be code rather than instructions.
A considered no is fine - level 2 is legitimate. Write into FACTORY.md what would have to
be true to go further, so it stays a decision rather than a dial nobody touched again.
Round 2 - what only they can answer
Seven questions, and every one is about something that has already happened to them.
That is the rule this round is built on, and it is a correction. An earlier version asked people to design things: name three properties that hold when features combine, list six ways the software could be silently wrong, define what must stay true under argument. Those are the right artifacts and they are the wrong questions - they are a design exercise handed to someone who came here to answer questions about their own product. The person who wrote the skill got lost in his own interview.
So: ask about their experience, and derive the artifact yourself. A user should be able to answer every question below having never heard of this skill, from memory, about software they know. Turning those answers into scenarios, defect sets and rules is your job, and you do it silently.
Assume more. That is the trade, and it is deliberate.
When a question is hard to ask simply, answer it yourself and ask them to correct you. You have their PRD and their repo, which is more than enough to draft a decent first version of almost everything here. A drafted answer they can reject in one click is worth more than a perfect question they abandon.
Concretely, and in this order:
- Draft from their material. Their non-goals are most of the never-do list. Their MVP is most of the main path. Their code names the things that can break.
- Offer it as the recommended option. Two or three alternatives, then Other.
- Ask only for the correction. "Which of these is wrong, and what did I miss?"
- Where you had to guess, say so in one line - and put it in
MISSION.mdas an assumption, so it is visible later rather than silently load-bearing.
The sacrifice is real and it is accepted. Assuming means sometimes assuming wrong, and a user correcting a wrong draft is a better outcome than the same user staring at a blank question and answering "I don't know, you pick" - which is the answer the old interview actually produced, and it carries no information at all. A wrong guess gets corrected. An abandoned question does not.
What you may never assume: anything in Round 1, and anything that decides what counts as passing. Guessing whether they will accept unreviewed merges, or how strict the checks have to be, is not a simplification - it is deciding the project on their behalf.
Never say these words in a question: holdout, mutation set, invariant, ratchet, independence line, structural gate, composition, marker, E2E. Every one names a solution the user has no reason to know. If a term has to appear at all it appears after the answer, in one sentence, explaining what you are doing with what they just said.
R2.1 - "Which of these should it never do - not now, not in a year?"
Draft the options from the PRD's non-goals, which are usually most of the list already, and make it multi-select. What they deselect matters as much as what they keep.
The distinction to hold on to: a PRD says "not now", the factory needs "not ever". Walk the non-goals and sort them. "Not now" items go in the backlog and must not be listed as out-of-scope, or the factory will refuse that work when its turn comes.
Then one open follow-up with Other: "anything else it should turn down even if it were easy?" Prompt with categories only if they stall - new data sources, payments, mobile, social, a public API, integrations.
What it becomes: the out-of-scope list in MISSION.md, which is what lets the factory
reject a plausible request at three in the morning.
R2.2 - "What would make you stop whatever you are doing and fix it right now?"
The plain version of "what must always stay true". People answer this instantly because it is a feeling they have had: the pager, the thing you do not let slide until Monday.
Draft three from the PRD and let them correct: "I would guess - user data leaking to another account, the rate limit coming off, anyone being able to see someone else's records. Which of those is wrong, and what have I missed?"
What it becomes: the properties in MISSION.md and FACTORY_RULES.md that no request
is allowed to argue away. Different from R2.1: those are features you will not add, these
are things that cannot be changed by anything you do add.
R2.3 - "After you make a change, what do you actually do to check you did not break anything?"
Whatever they say is the specification, including "I click around for a couple of minutes"
- especially that. Get the clicking narrated, step by step, because that is the check that has to be automated.
Bad answer: "I run the tests." Ask what they do after the tests pass, before they believe it.
R2.3b - "If you were not looking at the screen, how would you know it was running properly - not just started?"
One of the two things that must be code. A URL that answers, a page that renders, a line in a log. A process that starts, hangs and returns zero looks exactly like a healthy one.
Bad answer: "it starts up."
R2.4 - "What is the laziest way to make the tests pass without actually fixing anything?"
Ask it in those words. It is a question about their code, not about agents, and people answer it well and enjoy it: delete the test, weaken the check, mock the thing being tested, catch the error and carry on, special-case the test input.
What it becomes: rules in FACTORY_RULES.md and, where it can be, a check in code.
R2.5a - "Tell me about a bug that got past your tests and reached you anyway. What happened?"
This replaces the hardest question in the old interview, which asked people to name three properties that hold only when features are used together. Almost nobody can do that cold; the file admitted as much and then asked anyway.
Everybody has this story, and the story is the same artifact. A bug that survives a test suite is nearly always one that needs two things to be true at once - it saved but did not reload, it worked once but not twice, the second user saw the first user's data. That is exactly the material needed, and it arrives as a memory instead of a design exercise.
Ask for two or three. Then one follow-up: "what would have caught it?"
What it becomes: the scenarios kept where the building agent cannot read them, which is the only honest reason to merge code nobody reviewed. Say that in one sentence after they answer, not before.
If they genuinely have none - a greenfield project with no history - draft from the PRD by pairing capabilities that have to survive each other, and ask which is wrong: "make one, restart it, is it still there", "do it twice with something else in between, same answer", "something you rejected never quietly becomes accepted."
R2.5b - "If I broke one thing quietly and nobody noticed, what would hurt the most?"
The best question in the interview. Keep the words.
But stop asking for six. The old version wanted six or seven and people stalled, said they would come back to it, and never did. Ask for the one that scares them most, then draft five more from it and their code and ask which are wrong. Editing a list is easy; producing one from nothing is where interviews die.
Shapes to draft from, named against their real features rather than in the abstract: a check quietly reversed, a counter that stops moving, an answer that is always the same number, an error that returns instead of raising, a save that stops happening so everything works until a restart, an off-by-one at a boundary.
What it becomes: the deliberate defects the checks are measured against. The line worth saying afterwards: every one of these that gets through is a kind of bug that can currently ship with nobody reading the diff.
R2.7 - "Once it is live, what would you run or click to prove it is really working?"
And: what would you see if it worked? Both halves, because a deploy step with no check is a step that cannot fail, and a step that cannot fail is a comment.
Push for something a user would notice - a request served, a page rendered, a row written.
Three questions that used to be here now ride in Round 3, as defaults to amend rather than questions to answer. They were the most abstract in the interview and all three have a right answer that is already written down:
| was | now |
|---|---|
| "Which parts of this can a machine never check?" | drafted from the PRD - feel, look, readability - and confirmed in the Round 3 call |
| "What may the factory decide on its own, and what must it stop and ask about?" | the split is fixed policy, so only the additions are asked, in Round 3 |
| "What must never merge, and what would you rather ship than block on?" | the boring default is recommended: it must start, the main path must pass, no protected file touched |
(There is no push-or-poll question. The answer is always poll: a push trigger that breaks
fails silently and looks exactly like a factory with nothing to do, and GitHub does not fire
workflows on default-token commits at all. Tell them; do not ask. See deployment.md.)
Round 3 - the defaults, confirmed in one call
Send these as a single list with the proposed value filled in, and ask what to change. Not one at a time, and not as questions. Every line has a working default, and most users will change one or two.
This is the round the question tool was made for. One call, multi-select, phrased as "which of these do you want to change?" with the proposed value in each option's description. Selecting nothing is a valid and common answer, and it takes one click instead of ten replies. Ask for the new value only for the ones they select.
Beware the option cap: real question tools allow only a handful of options per call. Put the ones a user is most likely to want to change first - concurrency, poll interval, PR cap, protected paths - and hand the rest over as plain text alongside. Do not drop a row to fit the widget.
| what | proposed default | why it is a default, not a question |
|---|---|---|
| Protected paths | governance files, factory/**, .factory/locks/**, .factory/holdout/**, .github/, deploy/, infra/, Dockerfiles, auth and rate-limit modules, lockfiles |
seed it, then ask what else. Their answer is an addition, not the list |
| Never-committed files | .env*, *credential*, *secret*, *.pem, keys, service accounts |
a different question from "never edited": being unable to edit a file does not stop git add -A publishing one that appears next month. Becomes FACTORY_SECRET_FILES, and the pre-flight refuses to start until each is git-ignored |
| Where the hidden scenarios live | .factory/holdout/, read-blocked per node and guarded on the diff |
one right answer, already shipped. Mention the stronger options - a sibling repo, or outside version control on the runner - and take the strongest they will actually maintain. A holdout nobody updates is worse than none |
| PR size cap | 500 lines, 12 files | crude and it works. Unsupervised agents ship 3,000-line PRs, and "nobody can review it" is where a factory stops being auditable even in principle |
| Poll interval | every 30 minutes | slower than feels right. A fast loop multiplies the cost of a mistake before anyone has noticed the mistake |
| Concurrency | one | parallelism is where per-target races live. Earn it after the serial version is boring |
| Stop button | .factory/STOP kill file and a factory:stop label |
two, because they fail in different places. The file works with the network down |
| Per-node runaway guard | FACTORY_MAX_BUDGET_USD |
a ceiling high enough that hitting it means something went wrong. Not a budget - a guard against a node that never terminates |
| Model routing | premium in the planning slot, cheaper everywhere else | a premium model in one of plan/implement buys most of the quality of both. Zero-to-one is a large real improvement; one-to-two is usually noise. Picking the wrong slot is cheap; premium in zero slots is not |
| Conventions file | their existing CLAUDE.md / AGENTS.md, kept |
if one exists it is already the answer. Split it, do not replace it - move factory-only rules out into FACTORY_RULES.md. If none exists, ask what they would tell a new hire on day one |
Four things must be stated rather than proposed, because there is no safe default:
- Which coding agent is authenticated on the machine that will run this. Not which is best - which one already works. The factory shells out to a headless command and reads an exit code; every agent exposes that.
- Where the factory runs. Laptop, VPS, CI runner, container. This decides credential lifetime, whether a schedule survives a reboot, whether the app can even be started for E2E, and what the sandbox can reach.
- How work arrives. Usually GitHub issues; sometimes a spec file with an issue pointing at it. The detail matters less than picking exactly one and making everything read from it.
- What reaches them, and how. Exactly one escalation channel, and it should be quiet -
if everything notifies, they mute it, and then nothing notifies. Get an actual command,
not a preference: "Slack, probably" does not survive contact with the runner.
FACTORY_NOTIFY_CMDneeds something that runs. Ask what they would genuinely see within on a Saturday, away from the machine.setup.mdhas a working line for each. Bad answer: "I'll just check the file." Nobody checks the file - that is the whole reason this exists. A factory whose only output is a file nobody opens is not unattended, it is unmonitored.
One more, asked plainly: "how do you roll back?" If the answer is "I would fix forward", that is fine, but it has to be said out loud - an unattended system will eventually merge something bad, and the recovery path should not be invented at 2am.
Closing the interview
Play the whole thing back as a single spec before writing any file:
- the PRD this was built from, by path, and the mission compressed out of it
- five things out of scope forever, sorted apart from "not this quarter"
- the hard invariants and the protected list
- their existing process, written as the ordered steps the workflows will run
- the E2E happy path, narrated as steps
- the two structural gates
- where the hidden scenarios live
- the chosen agent, and which model sits in the planning slot
- where it runs, and what schedules it
- what happens on merge, the command that proves the build works and what it prints, and how to roll back
- the target autonomy level, and the level being built first
- the stop button, and the one channel that reaches them
Six of these are settings the factory refuses to run without, so a vague answer is not a soft failure - it is a blocked first lap. Name them back explicitly:
| answer | becomes | what happens without it |
| What must never merge | it has to start, the main path has to pass, no protected file was touched - and everything else ships | the boring answer is the right one for almost every project, and it is far easier to argue with than an empty question. This used to be asked open and produced either a list of one or a list of forty |
| What only a person can judge | drafted from their PRD: feel, look, wording, whether a newcomer understands it | the factory's scope is smaller than the product's and always in the same way. Derive it, show it, let them add. Written into MISSION.md as permanently human, so a green gate is never read as "the product is good" |
| What it should ask about before doing | changes a revert does not undo: schema migrations, money, auth and secrets, anything that sends something outside the building | the split itself is fixed policy - it decides ordinary product values and shows you, it never decides what counts as passing - so only the additions are worth asking for. Push back on length in one direction only: everything on this list costs throughput, everything missing from it costs more than throughput |
|---|---|---|
| files that must never be committed | FACTORY_SECRET_FILES + .gitignore |
pre-flight refuses; no lap ever starts |
| the command that proves the app runs | FACTORY_VALIDATE_CMD |
the gate has nothing to run |
| the observable proof it started | APP_STARTED in FACTORY_REQUIRED_MARKERS |
the gate cannot tell skipped from passed |
| the health command and its output | FACTORY_HEALTH_CMD / _MARKERS |
deploy.sh refuses to publish |
| the stop button | FACTORY_STOP_FILE / factory:stop |
nothing can halt it |
| the escalation channel | FACTORY_NOTIFY_CMD |
unattended quietly means unmonitored |
And four things the scaffolds hand you as worked examples, which are only yours once you
have replaced them. factory_doctor blocks on each until you delete its marker, because a
gate that is green about somebody else's product is worse than no gate:
| from | you write | answer that produces it |
|---|---|---|
harness/e2e.py |
the journey, asserted | R1.1 |
.factory/holdout/run.py |
composed scenarios the builder cannot read | R2.5a |
harness/mutations/defects.json |
the defects that must be caught | R2.5b |
factory/prompts/*.md |
your process, approvals removed | R1.2 |
If any line is still vague, that is the line the factory will fail on. Go back to it.
Open this reference as its own page
Setup: the machine, the prerequisites, and the schedule
Everything in this file is a thing that broke a real factory. None of it is interesting, all of it is load-bearing, and it is the half of the project that nobody writes down - you can have five perfect components and a factory that has never completed a lap because line endings got rewritten on checkout.
Read this in Phase 6, when the trigger goes on. Skim the prerequisites in Phase 0b so you refuse at the start rather than halfway through.
Prerequisites, before the interview
Check these while inspecting the repo. Each one is a refusal if it is missing and cannot be arranged.
| Why it is on the list | |
|---|---|
| A coding agent, authenticated on the machine that will run the factory | Not the best one. The one that works today. |
gh authenticated, if state lives on GitHub |
The dispatcher, the gate and the merge all shell out to it. |
| A machine that stays on | A factory on a laptop that sleeps is a factory that runs when you happen to be awake, which is the thing you were trying to stop doing. |
| A way to start the app | Component 5 has nothing to stand on without it. |
| A test command that runs | A dark factory built on zero checks is a machine for merging plausible code. |
| Somewhere the app can actually run for E2E | Ephemeral CI runners make long E2E and app-startup awkward. Check before choosing. |
The credential problem nobody solves for you
Agent credentials expire, silently, mid-run. Every agent, no exception. The factory will present this as a node that failed for an unrelated reason.
- Check the expiry of whatever you authenticated with, and put its renewal in the same place you put the cron.
- Have the runner read the agent's own JSON result and report the real terminating
reason.
node_failure.pyin the runner template does this: budget exhaustion, a tool denial, a crash and a refusal are four different things and only three are bugs. - A node that exits 0 having done nothing is the normal shape of this failure. Assert on the artifact, not the exit code. A run that produced no commit, no PR and no diff did not succeed, whatever it returned.
The platform tax
Line endings will break every script, on a machine you are not looking at
If the repo is ever checked out on Windows with core.autocrlf on, every *.sh gets
CRLF, and on the Linux box that runs the factory each one fails with:
bad interpreter: /usr/bin/env bash^M
which reads as "the file is missing". Pin it, in the repo, so it does not depend on anyone's git config:
* text=auto eol=lf
*.sh text eol=lf
Windows path length
git worktree add fails with "Filename too long" once a worktree path plus a vendored
file exceeds 260 characters. The validator's worktree path is longer than the
implementer's by exactly the length of the word it adds, so this shows up on validation
and not on implementation, which sends you looking in the wrong place.
git config core.longpaths true
Also key worktree paths on the issue number, not the issue slug.
Encoding, on anything that crosses a process boundary
Windows defaults stdio to the ANSI codepage. A correct rejection comment, piped from one process to another, arrived on GitHub with every non-ASCII character replaced by U+FFFD - and nothing noticed, because the only thing checked afterwards was the exit code.
export PYTHONIOENCODING=utf-8
and decode subprocess output explicitly. subprocess(text=True) uses the platform
codepage, which means a verifier can fail to read an artifact that is perfectly fine and
report it as broken. A false alarm costs exactly as much trust as a missed failure.
Before the first workflow that can commit
Run this. It takes a second and it is the difference between a mistake and a publication:
git check-ignore -v .env secrets.json credentials.json <every-config-file-with-a-token>
Empty output means your next run publishes your key. A git add -A inside a PR step
sweeps up whatever was not ignored, and on a public repo that is publication - rotating
afterwards is the cleanup, not the fix.
Being unable to edit a protected file does not stop git add -A from committing one
that appears for the first time. Put the check in the workflow as a node, not in a
checklist a human reads. The runner template does this in its pre-flight.
The schedule
Cron, on a machine that stays on
*/30 * * * * cd /path/to/repo && bash factory/orchestrator.sh >> /var/log/factory.log 2>&1
Every 30 minutes. Slower than feels right. A fast loop multiplies the cost of a mistake before you have noticed the mistake.
Capture stdout and stderr per run. The first thing you will want, on the morning after the first unattended night, is the log of a run that did nothing.
systemd timer, if you want the run not to overlap itself
A timer with OnUnitInactiveSec starts counting after the previous run finishes, which
a cron does not. Worth it once a lap takes longer than the interval.
Windows Task Scheduler
Register the task to run at logon with restart-on-failure. Note that it only runs while someone is logged in unless you configure it otherwise - a detail that presents as "the factory stopped overnight".
GitHub Actions, and the two traps
If you schedule in Actions instead:
- Scheduled workflows only run from the default branch. A cron sitting on a feature branch does exactly nothing, forever, with no warning.
- On a public repo, GitHub disables scheduled workflows after 60 days with no repository activity. A factory that goes quiet gets switched off for being quiet, and then stays off - which looks identical to "it had nothing to do."
And the one that kills deploys rather than dispatches: GitHub does not trigger workflows
on commits made with the default GITHUB_TOKEN. See deployment.md.
Turning it on
The dial is enforced in code, not documented in a file. orchestrator.sh refuses to
dispatch below FACTORY_AUTONOMY=1 and holds each later action at its own level.
bash factory/orchestrator.sh --dry-run # says what it would do, does nothing
FACTORY_AUTONOMY=1 bash factory/orchestrator.sh # one invocation, not persisted
Set it in the environment for one invocation first, and only put it in the cron once a full cycle at that level has been watched. Step up 1, then 2, then 3 - watching a cycle at each is what earns the next, not a reason to stop.
Level 3 is where this is meant to end up. Levels 1 and 2 are how you get there safely;
neither is the destination. factory_doctor refuses 3 while there is no holdout, so the
dial cannot outrun the evidence.
The stop button, and testing it on purpose
Two of them, because they fail in different places:
- A local kill file. Works with the network down, which is when you most want it.
- A remote label. Reachable from a phone, which is the entire reason it exists.
The remote half must fail closed. "Remove a label to stop" is the obvious design and it is backwards: an absent label cannot be distinguished from an API call that failed to return it, so a network blip reads as "carry on". Make it a label you ADD, and treat any error listing it as stopped.
Use it once on purpose before going unattended, and write the date down. A stop button that has never been used is a stop button nobody knows works.
The first unattended night
- Instrument tokens on day one, not after the first invoice. Cost projections for
this are wrong by 10-20x in the same direction every time. Record the cost inside a
trap, so it survives the run failing - which is exactly when you most want to know what it cost. - Concurrency starts at one. Raise it only after the serial version is boring, and add a per-target lock when you do, or two runs will operate on the same PR and the second will judge a tree the first is still editing.
- Release the concurrency lock from a trap, not from the next statement.
set -eis inherited by a background subshell, so a workflow that exits non-zero - an escalation, a blocked gate, anything - skips the release and wedges the dispatcher forever. Every later run then logs "at capacity, nothing dispatched" and exits 0, which looks exactly like a factory with nothing to do. - Push before you dispatch. The factory's view of the world is
origin. Unpushed local work is invisible to it, and it will confidently build against a past that no longer exists, with every marker green. - Exactly one escalation channel, and keep it quiet. If everything notifies, you mute it, and then nothing notifies.
Wiring the one channel
needs-human is the only state a human must act on, so it is the only one allowed to
interrupt one. Everything else this factory writes waits to be found - and on an
unattended system, "waits to be found" means you learn about it when you next remember to
look. Set FACTORY_NOTIFY_CMD in factory/config.sh; it receives the reason on stdin and
the target as $1, and it is called from all three routes into needs-human (the runner,
a blocked gate, and the fix-attempt cap).
The message arrives on STDIN. argv[1] is only the target, for routing or a
subject line. Every example below reads stdin; if you write your own and reach for
"$1" by reflex - a one-line Slack curl is the obvious case - you get an alert whose
whole body is .factory/prs/0001.md, which tells you something is wrong and not what.
# Slack incoming webhook
FACTORY_NOTIFY_CMD='xargs -0 -I{} curl -s -X POST -H "Content-type: application/json" \
-d "{\"text\":\"{}\"}" "$SLACK_WEBHOOK_URL"'
# ntfy.sh - a phone notification, no app to write
FACTORY_NOTIFY_CMD='curl -s -d @- https://ntfy.sh/my-factory-topic'
# macOS desktop
FACTORY_NOTIFY_CMD='xargs -0 -I{} osascript -e "display notification \"{}\" with title \"factory\""'
# Linux desktop
FACTORY_NOTIFY_CMD='xargs -0 -I{} notify-send "dark factory" "{}"'
# a file you actually watch, if you would rather tail than be pinged
FACTORY_NOTIFY_CMD='tee -a /var/log/factory-escalations.log'
Test it the same way you test the stop button: on purpose, once. Point the runner at an issue that does not exist and confirm the message arrives.
bash factory/run-workflow.sh implement-issue issues/does-not-exist.md
Leaving it unset is a legitimate choice while you are still driving laps by hand, and the
runner says so out loud rather than pretending - NOT NOTIFIED - FACTORY_NOTIFY_CMD unset; this waits in .factory/needs-human.md. Do not go to level 3 that way.
Open this reference as its own page
The validation harness
This is component 5, it is most of the work, and it is the only component that decides whether the other four produced anything worth keeping.
What the runner expects you to build
Read this first if you are using templates/runner/. Both people who built a factory from
this skill inferred the whole layout from one default string in config.sh, and one of
them had to read the runner's source to work out how a check's output reaches the gate.
Neither should have had to.
templates/harness/ is a working skeleton of all of this - ci.py, appproc.py and
e2e.py. Copy it, run it, then delete every assertion in e2e.py and write yours. It
satisfies the contract below out of the box, so you are editing something that already
passes rather than debugging plumbing while also deciding what "working" means.
The contract is four things.
1. A single entrypoint, named in config.sh.
FACTORY_VALIDATE_CMD="${FACTORY_VALIDATE_CMD:-python harness/ci.py}"
FACTORY_VALIDATE_QUICK="${FACTORY_VALIDATE_QUICK:-python harness/ci.py --quick}"
harness/ci.py is a convention, not a requirement - point it at make check,
npm run gate, ./scripts/validate.sh, anything. What matters is that one command runs
the whole gate. The layout that goes with the convention:
harness/ the checks. The builder CAN read and run these
ci.py the entrypoint: runs everything, prints markers, exits non-zero on failure
.factory/
holdout/ assertions the builder is BLOCKED from reading (--disallowedTools)
locks/ thresholds and floors a human set. Protected
runs/ per-run artifacts. Gitignored
2. It must print a positive marker for every check family that RAN, and the markers
must match FACTORY_REQUIRED_MARKERS in config.sh. APP_STARTED and E2E_PASSED are
not negotiable. Counts, not just names:
APP_STARTED port=8080
E2E_PASSED steps=11
HOLDOUT_PASSED scenarios=2 assertions=30
MUTATIONS_TOTAL=7
MUTATIONS_CAUGHT=7
GATE_OK
3. It must exit non-zero when the software is broken. The gate reads the markers, but
the exit code is what the implement node's own --quick run sees.
4. The append contract, which is the one that bites. The runner writes guard.py's
output to the run's gate.log and then appends your validate command's output to the
same file. gate.sh asserts every required marker against that combined log. Two
consequences:
PROTECTED_OKcomes from the guard, not from you. Do not print it yourself.- If your entrypoint truncates or redirects over that log rather than writing to stdout, the guard's markers vanish and every gate fails for a reason that has nothing to do with your code. Print to stdout and let the runner do the plumbing.
--quick is a real obligation, not a nicety. The implement node runs it on itself
while it works, so it must be fast and it must be a strict subset - never checks the full
run does not have. It is inside the agent's optimisation loop by definition, which is
exactly why the full gate re-runs everything independently afterwards and why nothing
downstream trusts what --quick said.
Do not let the builder edit the harness. factory/guard.py seeds the mutation set on
the protected list, but ci.py is the definition of "works" - a builder that can edit
its own judge can make any claim true. Protect harness/**, and route legitimate coverage
growth to your normal test directory instead.
The rule the whole thing rests on:
The agent has to validate the app the way the end user experiences it. Not "the tests pass." Whether the thing works when a person uses it.
In a dark factory nobody does manual testing, by definition. So every check a human would have performed has to exist as something the agent can run - and, critically, as something the agent cannot quietly satisfy without doing the work.
Why "just write more tests" is the wrong instinct
A coding agent optimises against the signal it can see. Give it a visible test suite and enough attempts, and it will make that suite green. Whether it made the software correct is a separate question, and the two diverge as the codebase grows.
This is measured, not folklore. Work on reward hacking in long-horizon coding agents grades agents twice - once on the visible suite they can read, and once on a held-out suite testing the same requirements composed together. The gap between those two numbers is how much of the score was real. Published findings worth internalising:
- The gap widens sharply with code size. Roughly tens of percentage points per order of magnitude of lines. On small tasks the visible score is a decent proxy. On large ones it can reach the point where every visible test is green and every held-out test is red.
- Adding more tests does not reliably close it. In measured runs, adding composition tests helped one task and made another substantially worse. More signal inside the loop is more surface to optimise against.
- Deliberate cheating is a small minority of failures. The dominant failure is feature isolation: components that are individually correct and never compose. Unit tests test features in isolation by definition, so the thing they measure is precisely the thing that is not broken.
- A search process will discard a real solution for a fake one. In one documented case an agent produced a genuine working implementation and a much smaller one that memorised the expected outputs. The memorising version scored higher on the only signal being measured, so the search kept it and threw the real one away.
The conclusion is not "tests are bad." All the checks are worth building. The conclusion is that the step change is independence, not volume.
The ladder
Seven rungs, cheapest at the bottom. Build them bottom-up; they compose.
| # | Rung | What it proves |
|---|---|---|
| 7 | deterministic gate | green, or there is no merge. Code, never a prompt. |
| 6 | holdout scenarios | written before the work, never shown to the builder |
| 5 | visual / screenshot judging (not scaffolded — you build it) | it actually looks right on a screen |
| 4 | E2E as the real user | a real browser or a real client, real data, the full path |
| ↑↑↑ THE INDEPENDENCE LINE ↑↑↑ | above it, the agent cannot see or edit | |
| 3 | integration | the pieces work together |
| 2 | unit | the functions it just wrote behave |
| 1 | static | types, lint, compiler |
The reachability constraint, and it is an architecture decision
The harness reaches software exactly three ways: http (a server), cli (a command),
library (imported and called). See templates/harness/appproc.py.
A rendered window, a game loop, a canvas, a native UI is none of them. So this is not a preference about clean architecture, it is a precondition: the rules have to live behind a headless, scriptable surface an E2E can drive. Simulation apart from rendering, domain apart from view. If the logic only exists inside engine nodes and a render loop there is nothing to assert, and the factory cannot run at level 3 — not because the skill is limited but because nothing can check the work.
On a greenfield build, say this before any code exists. It is nearly free then and it is a rewrite afterwards. On a brownfield one, it is the first thing to find out, because the answer decides whether component 5 is additive or a refactor.
templates/harness/ci.py implements 1, 2, 4, 6 and 7. Rung 5 is not scaffolded, and
saying so matters: a doc that lists a rung the scaffold does not ship reads as "you have
this". You do not. Screenshots an e2e.py captures are artifacts nobody looks at until
something is written to look at them. Build rung 5 if the product has a screen worth
judging, and treat the row above as a thing to do rather than a thing you have. See the
frontend section of templates/harness/README.md for what that costs.
The independence line
Draw it after integration.
Everything below the line is inside the agent's optimization loop. The agent can read those checks, run them, and iterate against them. Given enough attempts it will satisfy them - which is exactly what you asked for, and exactly why passing them proves less than it feels like it does.
Everything above the line is written and run by something the agent cannot see or edit. That is the only property that makes any of it evidence.
The height of the ladder is not the argument. The line is. Three rungs the agent can reach, four it cannot, and that gap is the only honest reason to auto-merge.
The holdout
The mechanism, stated as a single rule to enforce structurally:
The validator never sees how the code was written. Only what was asked for, and what the code does now.
What the validator is given
- the original issue, exactly as it was filed
- the diff
- the output of checks it ran itself
- the governance files, fetched from the base branch, never from the PR
What the validator must never be given
- the implementation plan, or any design note the builder produced
- the builder's reasoning, scratch notes, or commit rationale beyond a plain title
- prior comments written by the builder
- any artifact from the run that produced the code
Enforcing it, in layers
A prompt saying "do not read the plan" is not enforcement. Stack these instead:
- Separate process, separate context. The validator runs as its own job with its own working directory. It cannot see sibling artifacts because they are not there.
- Fetch narrowly. When pulling PR data, request only the fields needed. Excluding comments and reviews at the fetch layer means no chatter can reach the reviewer even by accident.
- Read governance from the base branch first. Fetch
MISSION,FACTORY_RULESand the conventions file fromorigin/mainbefore checking out the PR. A PR must not be able to weaken the rulebook it is about to be judged against. Any diff that touches a governance file is an automatic reject, evaluated before anything else. - Restrict tools per node. A reviewer that only reads a diff needs no filesystem access at all. A reviewer that drives a browser needs a shell and nothing else, and should be explicitly forbidden from reading source.
- Add a tripwire. Have the validator fail loudly if a forbidden artifact is present in its working directory. It should be impossible; make it noisy anyway.
Where holdout scenarios live
In increasing order of strength:
| Location | Strength | Cost |
|---|---|---|
| a directory the builder's tool config excludes from context | weak - one config edit away | free |
| a sibling repo the validator checks out and the builder never does | strong | a second repo to maintain |
| outside version control, on the runner only | strongest | they are invisible, so they rot silently |
Pick the strongest the user will actually maintain. A holdout nobody updates stops covering new behaviour without ever announcing that it stopped.
Write them before the work, not after. A scenario written after seeing the implementation is a description of the implementation.
Structural gates vs prompted gates
A prompted gate is an instruction in a prompt: "only approve if all checks passed." A model can be persuaded out of it, can misread the evidence, or can decide a skipped check counts.
A structural gate is code: bash, a script, a CI required check. It has no opinion.
Be honest with the user about the ratio in their design. In practice almost every gate in a real factory ends up prompted, and that is survivable - as long as the small number that actually matter are code.
The two that must be code
- The merge itself. Whatever runs
gh pr mergemust be a script that reads a verdict file and branches on it, not a model that decides to merge. - Proof the app ran. A positive assertion that the application actually started and the E2E actually executed. This is the one that catches the worst failure mode below.
Anything else that a bad outcome would be unrecoverable from should join them.
Empty is not pass
The most expensive lesson in this whole document, and it costs nothing to avoid.
A check that never ran returns no failures. Code that asks "did anything fail?" reads that as success. A missing environment variable, a crashed process, a timeout, a typo in a path - all of them produce a silent, confident pass, and a synthesiser downstream counts a skipped check as a passed check.
The failure is not hypothetical: this pattern has auto-merged PRs on static analysis alone while believing a full end-to-end suite had run.
The fix is boring and total: assert positive markers.
Every check emits an explicit marker on success. The gate greps for the marker's presence, never for the absence of the word "error".
# in the check
echo "APP_STARTED backend=$BACKEND_PORT frontend=$FRONTEND_PORT"
...
echo "E2E_PASSED steps=7"
# in the gate - positive assertion, and a count, not a vibe
grep -q "APP_STARTED" "$LOG" || fail "app never started"
grep -q "E2E_PASSED" "$LOG" || fail "e2e never ran"
STEPS=$(grep -oP 'E2E_PASSED steps=\K[0-9]+' "$LOG" || echo 0)
[ "$STEPS" -ge 7 ] || fail "e2e ran only $STEPS of 7 steps"
Then add the backstop: if a model-produced verdict says approve but the marker is absent, override to reject and escalate. Deterministic bash reading the raw output beats a model's summary of that output, every time. Assume the summariser will occasionally ignore its own rules, because it will.
What the factory says to humans is an output, and outputs need assertions too
Everything above is about checks. The factory also produces artifacts for people: the comment explaining a rejection, the PR body, the escalation note. Those get graded by nobody, and they fail silently.
Observed on a real run. Triage rejected an out-of-scope issue perfectly: correct verdict, correct label, issue closed not-planned, and a written rejection citing two rules by number with an appeal path for the filer. What actually reached the filer was two characters:
@-
The reasoning had been assembled in a shell pipeline instead of going through the
factory's own comment helper, and on Windows the pipeline collapsed to a literal @-.
Every state transition was right. The gh call exited 0. The run reported success. The
only thing lost was the entire explanation, which is the part a human was ever going to
read.
Two rules come out of it, and the second is the general one:
- Route every human-facing write through one helper, and make the helper the only way.
A hand-rolled
gh issue commentin a node is the same class of mistake as a hand-rolled merge: it works until quoting, encoding, or a newline eats it. - Assert the artifact after writing it, not before. Read the comment back and check it
contains the rule citation you meant to send.
exit 0from the tool that posted it proves the API call succeeded, not that it carried anything. This is exactly empty-is-not-pass, applied to output rather than to checks, and it is easy to miss because output feels like a side effect rather than a result.
The tell that this class of bug is present: a step whose success is measured by the transition it caused rather than by the thing it produced.
Slack is not pass either
Counting checks gets you a floor, and a floor invites the obvious next question: what stops the floor being lowered? The usual answer is a ratchet - a lock file holding the minimum count for each check family, where the gate asserts observed >= floor and a second check asserts floor(head) >= floor(base). Both halves are needed. Without the second, the move is to delete the assertion and lower the number in the same commit.
That is the right pattern and it has a failure mode that is easy to miss.
The floor is protected, so only a human can raise it. The harness improves faster than the human raises it. The gap between observed and floor is exactly the number of assertions that can be deleted with the gate still green.
Measured on a real factory built by this skill. Seven assertions could be removed and
every gate would still report OK. Nothing was broken and nobody was careless: the
factory had been adding checks correctly, and raising the floor to match is a protected
edit it is not allowed to make.
Then the same factory was measured again after one round of harness work, and this is the part that matters:
metric floor observed slack floor observed slack
---- before ---- ---- after -----
playthrough_checks 9 12 3 9 12 3
unit_tests 7 9 2 7 9 2
feel_checks 23 24 1 23 24 1
legibility_frames - - - 60 87 27
TOTAL 7 TOTAL 33
The hole grew from 7 to 33 in one cycle, and it grew because the harness got better. A new check family arrived running 87 frames against a floor of 60, and every assertion of that surplus is deletable. Improvement widens the gap, which is the opposite of what a ratchet is supposed to do.
So make slack fail, or make it block. Pick one:
- Tight floor.
observed != floorfails the gate, which forces the raise into the same human commit that accepted the new assertions. Strictest, and it makes adding a check briefly annoying, which is the cost of it meaning something. - Slack blocks the dial. Any slack is allowed but pins autonomy where it is until the floor is raised. Softer, and it keeps the pressure where it matters.
What you must not do is print the slack as a note and carry on. The note gets read once, by the person who already knew, and the hole widens with every improvement after that.
Designing the E2E path
One path, the most valuable one, exercised the way a user exercises it. Not a suite.
- Start the app on a dynamic port so parallel runs cannot collide. Wait for the health check. Fail hard if it does not come up - do not degrade to "not testable."
- Drive it with a real client. A browser-automation CLI for a web app; the actual binary for a CLI; a real HTTP client for an API.
- Assert something a user would notice: rendered output, not a 200 status.
- Capture a screenshot or transcript at each step and keep it as the artifact. This is what you read when you are deciding whether to trust the loop.
- Tear down whatever was started, always, including on failure.
Use a dedicated database and dedicated credentials for validation runs. E2E against production data is a data-loss incident waiting for a slow afternoon.
The cost, stated honestly
A published controlled comparison on the same task: a solo agent produced a non-functional result in about twenty minutes for single-digit dollars; a planner/generator/evaluator harness, where the evaluator drove the live page with real browser automation, produced a working result in about six hours for roughly twenty times the cost.
Twenty times the cost, for the only version that worked.
That ratio is the actual price of component 5, and the user should hear it before they build rather than after their first invoice. As one practitioner put it: the task verifier has to be nearly perfect, or the agent will solve the wrong problem.
What to delete on every model upgrade
Harness components are not permanent. Some of them exist only to prop up a weakness the model has since outgrown, and they keep costing tokens and attention forever.
On every model upgrade, delete one harness component and re-run your evaluation.
- If the score holds, that component was scaffolding. Leave it deleted.
- If the score drops, you found something durable.
The pattern that shows up repeatedly: decomposition scaffolding rots, verification survives. A node that says "now think about the architecture" is a rotting asset - a better model does that unprompted. A node that says "run this in an isolated worktree and gate on the tests passing" is durable, because it constrains rather than instructs. Adversarial evaluation in particular tends to be worth keeping, because agents lean toward praising work whose quality is obviously mediocre.
Checklist before enabling auto-merge
Do not raise the dial to level 3 until every line is true.
- The E2E path runs, and it fails when deliberately broken. Test this by breaking it on purpose. An E2E that has never failed is not known to work.
- The app-started marker exists and the gate asserts it positively.
- Merge is performed by a script reading a verdict file, not by a model.
- Governance files are fetched from the base branch, and touching them auto-rejects before any other evaluation.
- The validator's inputs contain no plan, notes, or builder commentary.
- Holdout scenarios exist, live somewhere the builder cannot read, and were written before the work.
- A skipped check is provably distinguishable from a passed check, and there is a deterministic override if a verdict disagrees with the raw markers.
- There is a stop button, and it has been used once on purpose.
More in this playbook
Safe to turn on
Use this skill when an agent or person is about to create, change or enable an automation inside someone else's account or a shared environment: "create this workflow", "build it in the customer's account", "turn it on", "go live", "deploy this automation". Produces a proposal the human approves, an automation created in the off state, and a short list of what only the human can finish.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.

