← Back to my notes

The factory: from idea to a change I can trust

The steps around my coding agents: what each one does, the problem it addresses, and what changed when I started using it.

The factory lifecycle Define the request and approve the design, then build, run an adversarial review, and prove the behavior. Resolve findings and failed checks before finishing the draft pull request. Prepare it for merge by handling base-branch changes, automated checks and comments. A person decides to merge. Repeated rule violations can become guards for future work. This is a simplified overview; checks also happen during implementation and a draft may open earlier for external review. From an idea to a change I’m ready to merge. THE FACTORY is the whole loop. Not just the coding bit. Define the request cases + wireframes Design the change I approve the plan Build the assignments agents + local checks Adversarial review a second perspective Prove the behavior tests + recordings Finish the draft PR a proposed code change Prepare for merge Greptile + checks + comments Human merges the decision stays here fix + review again failed check? repair A rule keeps breaking? Turn it into a guard: a type, lint rule, test… let the next run benefit from the correction
Swipe or scroll sideways to follow the diagram.The main path through my factory. Checks also happen during the build; a draft can open earlier for external review. Corrections send the work back through the relevant checks.

I wanted anyone on our team to ask for a product change and get back something I could review and merge. Getting a coding agent to produce code was only part of that problem. I also needed a way to agree on what we were building, challenge the implementation, and check that it behaved as intended.

The diagram shows the software factory workflow I use. Each box is a step around the coding agent, from defining the request to a person deciding whether to merge the change. Here’s what each step does and what I’m learning from it.

Based on spec-driven development (SDD), we define the expected behavior before implementation and use that spec to guide the build and its acceptance checks. Before asking an agent to write code, I want us to agree on what the product should do. The agent reads the existing code, then asks me about decisions the code can’t answer: who needs the change, what happens when it fails, and what we’re deliberately leaving out.

This conversation uses the approach from Matt Pocock’s grilling skill: ask questions in rounds, settle the decisions we can make now, then use those answers to uncover the next questions. In the factory, that conversation becomes a spec. These are the five sections I want to highlight.

What goes into the spec

Who has the problem, what happens today, and what it costs them. Considering using the VISION.md approach to align each requirement with the product’s long-term vision.
The outcome a person using the product should notice.
See the changes at a glance.
mandatory!
Given / When / Then, including failure paths. Each one becomes a test assertion.
~80% better quality
Approved screens and states. Plain HTML wireframes worked better for me. If no screen changes, say so. I tried design-tool integrations first.
What this change deliberately leaves out. YAGNI: You Aren’t Gonna Need It.

What this changes: a rough request becomes an agreement about success, failure, wording and scope. We can challenge that agreement before paying for an implementation built on assumptions.

I could just hand the spec to an implementation agent, say “Build it,” and leave the implementation details to it.

But too often, I found myself asking afterward: “Why did you create a new table?” or “Why did you introduce a new domain object?” By then, the agent had already built code around that new table or concept. Changing the decision meant redoing the implementation. That made me realize I needed to be explicit about the important decisions before the agent started building.

Now I ask the agent to propose the changes in a technical design document, and I review them while they are still proposals. We agree on what to reuse, what to add, and how the pieces fit together. Those decisions then go into an implementation plan for the agents doing the work.

The agent fills in a fixed template for each document. The sections below are required, so it has to work through the same questions every time. It must ground its answers in the spec and the code it inspected, and flag missing information as an open question instead of inventing an answer. This helps prevent hallucinations and gives me a consistent document to review.

Technical design document

This is the proposal I review before implementation starts. It explains how the change will work, what we can reuse, and what needs to change. I use it to question the important decisions while they are still easy to change.

What changes
A short description of the outcome. It keeps the review tied to what a person using the product should notice.
Open questions
Unresolved product decisions and contradictions between the spec and the code. Each needs an answer before I can approve the design.
Requirement flow
The actors, actions and branches in the requested behavior. Walking through the flow makes missing steps and failure paths easier to spot.I’m visual. BPMN helps me follow the flow faster.
Approach
How we will build it, why this approach, and what we deliberately leave out. This is where I challenge unnecessary tables, layers or extra work.
Solution components
The parts of the system involved and how they communicate. Marking what is new or changing shows how far the change reaches.Component + sequence diagrams help me see what changes.
Domain entities
Changes to the concepts the product works with, such as an order and its status. Defining each field’s meaning prevents different parts from interpreting it differently.
Database changes
The tables and columns affected, including what happens to existing records. I can review the consequences for stored data before a migration changes it.
HTTP contracts
The requests and responses exchanged with the server: fields, permissions and errors. Agreeing on these interfaces lets separate agents build compatible pieces.Agree on the interface, then frontend + backend agents can work in parallel.
UI
The proposed screens and states, compared with the spec’s references. When they differ, wireframes make the change visible before it is implemented.
Who does what
Assignments, their order, and the model capability each needs. This shows what can run in parallel and where shared files require work to happen in sequence.An orchestrator starts the agents, waits for their changes, then merges them into a shared branch.
Acceptance
Each agreed case, its impact, who checks it, and the evidence I will see. It connects the proposed solution to observable success, rather than a claim that it works.The evidence could be tests, logs or even a video. See more in Prove the behavior.
Risks
What could still go wrong after shipping, what triggers it, how we would notice, and what we would do. Each risk must be grounded in something the agent checked.

Implementation plan

This is the document the agents work from. Each implementing agent receives the shared rules and its own assignment, including the relevant contract and scenarios. The plan carries the details that would distract from reviewing the design.

Revision and checked code
The design revision this plan follows and the code version used to verify its scenarios. These establish which decisions and assumptions the build starts from.
Rules for every assignment
Shared limits on file ownership, isolated working copies, review and checks. Every agent receives these rules so parallel work does not overwrite another agent’s changes.
Contract
The agreed interface, with exact types and implementation details. Agents on either side build against the same definition instead of inventing incompatible versions.
Ticket texts
The exact labels, messages and other text the spec requires. Copying them here keeps implementation and assertions from drifting into different wording.
Decisions
The settled choices and the records or states they apply to. An agent can distinguish “failed orders with no reason” from every order with no reason.
Assignments
Each agent’s deliverable, model, dependencies, area, files, starting points, wireframes and assigned checks. It can start in the right place without repeating the coordinator’s search.
Acceptance
The full scenarios, who runs each check, how to create the starting state and observe the result, and which code it covers. This gives the builder a concrete check to implement.
Build log
A record filled in during the build: work started, review findings, checks, commits and pending decisions. A new session can resume from recorded progress rather than reconstructing the chat.

The two must stay in sync. When the design changes, the plan changes in the same revision. Changing an approved approach, interface or assignment requires another design approval. Adding a file within an assignment’s existing scope only updates the plan. This keeps the work tied to the decision I actually approved.

What I’ve noticed: with structured specifications, design review and visible test evidence, I almost never need to ask for reimplementation or correct the agent.

A coordinating agent gives each assignment to an agent in its own working copy. The agents implement their parts and run the relevant local checks; the coordinator combines the work.

A fresh reviewer challenges the combined change without reading the builder’s reasoning. It normally uses a different model provider. Its job is to look for mistakes the planned scenarios might miss, such as sending something twice or exposing one customer’s data to another.Save this for important changes, or your bill will hurt!

This is the step that gives me the confidence to merge. I can open a pull request—the proposed code change—go through the agreed scenarios, and inspect the evidence for each one. I can see what the application actually did.

The acceptance cases we defined at the start become the checks here. Each check sets up the agreed situation, performs the action, and verifies the expected result, including the failure paths. The evidence can take different forms:

  • A video lets me watch the running application: the action, the response, and what ends up on screen.
  • Test results show whether a specific rule holds, including behavior that is hard to demonstrate through the interface.
  • Logs let me inspect what happened behind the scenes and connect it to the outcome we expected.

The important part is the connection between the requirement and the evidence. If a scenario says someone should receive a notification, the check needs to show that person received it. A record existing somewhere in the database would leave the important question unanswered. The check also needs to catch the missing behavior: if it would pass before the change, it cannot demonstrate that we delivered it.

This makes the PR something I can work through, case by case: what we agreed should happen, what ran, and what the evidence shows. I can watch the recording, inspect the result, and question anything that does not match. That matters especially when agents wrote the implementation. It gives me a concrete way to judge their work without reconstructing every decision from the code.

The evidence must belong to the version I am reviewing. If a correction changes the behavior, the affected checks run again and their evidence gets refreshed.

For me, this is where the earlier work pays off. The spec gives us the cases, the design gives the agents a plan, and this step lets me see whether they delivered. I can open the PR, check the evidence, and trust my decision to merge.

example / dispatcherDemo replicated from a real PR

Version dispatcher prompts without interrupting conversations #42

Openbuild-agent wants to merge 2 commits into main from prompt-versions

The video is from the real PR; names, code and logs are recreated.

build-agentbotcommented

Summary

Admins can publish a new dispatcher prompt without a deployment. Conversations in progress keep the version they started with; new conversations use the published version.

Acceptance

ScenarioEvidenceResult
Publish a saved versionWatch recordingPassed
Continue an existing conversationSecond-message checkPassed
Start a new conversationNew-conversation checkPassed
prompt-promotion.mp4Real acceptance recording · 5 seconds

Recorded in the local app with test data. The admin confirms promotion and version 8 becomes Live.

Read the video description

The dispatcher page starts with version 1 marked Live. The admin selects Promote for version 8. A dialog explains that new conversations will use it within a minute and ongoing conversations keep their version. The admin confirms; version 8 is then marked Live.

Evidence: the conversation keeps its version

Given a conversation started on version 1, when version 2 is published and a second message arrives, then the existing conversation still uses version 1.

second-message.log
PASS  existing conversation keeps its prompt

message-1 conversation-a prompt=v1 publish live prompt v1 → v2 message-2 conversation-a prompt=v1

assert message-2.id != message-1.id PASS assert conversation-a.promptVersion == 1 PASS

review-agentbotreviewed

The first test reused the original message ID. That did not prove what happens on the next message after publication. Send a distinct second message and assert the version it actually uses.

ResolvedThe check now sends a separate second message. Evidence refreshed.
All checks have passed3 successful checks
Show checks

Commits

Keep the prompt version on each conversationbuild-agent committede1a2b3c
Check a distinct second message after publicationbuild-agent committedf4d5e6a

All checks passed

Passed Publish version 2
Given: version 1 is live; version 2 is saved.
When:  an admin publishes version 2.
Then:  the live version is 2.

PASS publishedVersion == 2

Passed Existing conversation keeps version 1
Given: conversation-a started on version 1.
When:  version 2 is published; message-2 arrives.
Then:  the reply still uses version 1.

PASS message-2.id != message-1.id PASS reply.promptVersion == 1

Passed New conversation uses version 2
Given: version 2 is now live.
When:  conversation-b starts.
Then:  its first reply uses version 2.

PASS reply.promptVersion == 2

Files changed

acceptance/prompt-version.test.ts+2 −1
  await publishPrompt(version2);− await receiveMessage(firstMessage);+ const reply = await receiveMessage(newMessage);+ expect(reply.promptVersion).toBe(version1);

Greptile checks

Greptile adds another review on the pull request. It is an AI code reviewer that reads the changes with the surrounding codebase as context and leaves findings as PR comments.

It has caught issues in my changes, and I see it as a useful extra. But each finding still needs an agent with the context of the requirement, the design decisions and the code to decide whether it is a real issue. A review comment alone is not a reason to change the implementation.Save this for important changes too. It costs money!

That agent checks the findings, fixes the issues that apply, and explains why it disagrees with the others. If a fix changes the behavior, the affected checks run again so the evidence matches the change I will review.

This is the return loop in the diagram. When an agent breaks an existing rule that could be broken again in unrelated work, I record the trap so future agents can learn from it. The next step I want to explore is making those mistakes fail automatically: through a type, a structural constraint, a lint rule or a test.I keep traps in a Markdown file today. I’m considering deterministic guards—checks that fail automatically when a rule is broken.

I’m still figuring out which parts need more structure and which create unnecessary work. Which box would you add, remove or change in your own workflow?

A mistake worth sharing.

Working through something similar? Leave me a note on any part of this page.

Context: the prompt

Highlight any part of the prompt to leave a private note.

## Context
Who has the problem today, and what it costs them.
## 2. Read the code shallowly

Find the areas the ticket touches and how they behave today: the screens and their current copy, the states an entity can be in, and every number on the ticket's path (attempts, deadlines, limits). Read only enough to know what is true today; `factory-design` and the implementers read deeply later. Do this reading yourself.

What the code answers is a **fact**: the grill never asks the user for it. Where the user's idea and the code disagree (the ticket says one retry, the code also redials automatically, so the user sees two attempts), that is a decision, and it goes to the user.

What changes: the prompt

Highlight any part of the prompt to leave a private note.

## What changes
The goal in one or two sentences, as a person using the product will notice it.
The questions are about the product, in the user's terms. An engineering choice (an endpoint's shape, a table, how to split the work) is `factory-design`'s to make; leave it off the ticket.

Acceptance cases: the prompt

Highlight any part of the prompt to leave a private note.

## Acceptance cases
| # | Case | Given | When | Then |
|---|---|---|---|---|
| 1 | The case, in one line | The starting state, with the data that matters. | The event or the user's action. | What is seen or stored, with the exact copy. |
- **Given**: build only the data this scenario needs, scoped to records the check creates. Build times relative to the test's own clock (`two hours ago`), never as a calendar date. Use the setup the project's references describe; do not invent another way in.
- **When**: perform the scenario's event or action once, the way a person or the system would.
- **Then**: assert every part of it. Copy is asserted exactly as the plan quotes it. A `Then` that says something must not appear gets an assertion that it does not appear. A value is asserted where the scenario says it is: on screen for a `video`, in the response for a `black-box`, in the database or the returned value for `integration` and `unit`.
- **Fails without the change**: the check must fail on today's code. Assert what the ticket adds, not something the app already shows. If you cannot see how it would fail today, it does not prove the scenario.

UI references: the prompt

Highlight any part of the prompt to leave a private note.

## 4. Draw the wireframes

Draw them once the grill has settled what each screen shows: its data, states and copy. Skip this step when the ticket changes no screen, or when the user's references already show every changed screen and state.

1. Follow the "Wireframes" rules in the `factory-design` skill's `references/design-page.md`: built from the real screen and the project's design tokens, at 1440×900 inside its page, one file per screen and state, with the ticket's exact copy. Save them as `.context/factory/<ticket-id>/wireframes/<screen>-<state>.html`.
2. Show the user every wireframe as a link to its absolute path, and ask them to approve them. A change they ask for is a new revision of that wireframe; a change that alters behavior or copy goes back into the grill first.

The wireframes are approved when the user approves every one of them by name.

Out of scope: the prompt

Highlight any part of the prompt to leave a private note.

- **Scope.** What this ticket deliberately leaves out, so the design does not build it.
### Design the smallest change that passes

The change a user most often asks for after reading a design is to take something out. Take it out first. Test everything the design adds (a table, a column, an endpoint, a setting, a flag, a job, a layer) against one question: which acceptance case fails without it?

- **A case fails without it**: it stays. Be able to name the case.
- **No case does**: drop it.
- **Change what exists before adding beside it.** A new value in an existing column before an override column; an existing response before a new endpoint.
- **No rollout switch, feature flag, compatibility layer or configuration knob**, unless the ticket asks for one, or reverting the pull request could not undo the failure it guards against (rows already written, a message already sent).
- **No handling for a case the ticket does not name and the code cannot reach.**

Under "Approach", say in a line or two what the design leaves out on purpose and why ("no rollout switch: reverting the pull request undoes it"), so the user reads a decision and not an omission. When the ticket itself asks for more than its goal needs, do not trim it silently: that is an open question, with the lighter option as its proposal.

Define the request: the prompt

Highlight any part of the prompt to leave a private note.

## 3. Grill

Interview the user relentlessly until every section of the template in step 5 is settled. Map the work as a **design tree**: each decision branches into the decisions that hang off it.

Work in **rounds**. The **frontier** is every decision whose prerequisites are settled. Ask the whole frontier in one round, number each question, and give your recommended answer under it:

```
❓ **Q1** - **<title>**: <the question, with its choices>

➡️ <recommended answer>
```

Then wait for the answers. Each answer moves the frontier; recompute it and ask the next round. A question that depends on another one still open belongs to a later round.

The questions are about the product, in the user's terms. An engineering choice (an endpoint's shape, a table, how to split the work) is `factory-design`'s to make; leave it off the ticket. Press hardest where `factory-design` would otherwise stop:

- **Failure paths.** Every acceptance case has its unhappy paths: the provider rejects, the data is missing, the user cancels halfway, the action runs twice.
- **Numbers and behavior against the code.** Each count, deadline and state the ticket expects matches what the code does, or the user decides to change it.
- **Recovery actions.** A Retry, Restart or manual confirmation the ticket offers calls something that exists and accepts the case, or the ticket says it is new.
- **Exact copy.** Every label, message and empty state, word for word, in the language the screen shows.
- **UI references.** The images or design links the screen must match. Ask the user for them; when the ticket changes a screen and there are none, draw wireframes (step 4).
- **Scope.** What this ticket deliberately leaves out, so the design does not build it.
- **Dependencies.** Tickets this one waits for, or blocks. Find each one in the issue tracker.

The grill is done when every section of the template is filled with an answer the user gave or confirmed (or says explicitly that it does not apply), every acceptance case has its failure paths, and every difference between the ticket and today's code is one the user chose: a change of behavior the ticket asks for, never a discrepancy left unnoticed. Then ask the user to confirm you share the same understanding, and wait for it.

Design the change: the prompt

Highlight any part of the prompt to leave a private note.

Takes one ticket and produces two documents:

- **The design page** (`design.html`), which the user opens in a browser, reads and approves, written in Spanish. It shows the open questions, the requirement's flow, the solution's components, the changes to domain entities, database models and HTTP contracts, wireframes when the UI departs from the ticket, and who does what: how many subagents will run, in what order, and what each one does.
- **The working plan** (`plan.md`), which only the agents read. It holds each assignment's files, entry points and the coordinator's notes, so implementers do not search the code again.

Nothing is implemented until the user approves the design page, and the page cannot be approved while it has an open question.
### Design the smallest change that passes

The change a user most often asks for after reading a design is to take something out. Take it out first. Test everything the design adds (a table, a column, an endpoint, a setting, a flag, a job, a layer) against one question: which acceptance case fails without it?

- **A case fails without it**: it stays. Be able to name the case.
- **No case does**: drop it.
- **Change what exists before adding beside it.** A new value in an existing column before an override column; an existing response before a new endpoint.
- **No rollout switch, feature flag, compatibility layer or configuration knob**, unless the ticket asks for one, or reverting the pull request could not undo the failure it guards against (rows already written, a message already sent).
- **No handling for a case the ticket does not name and the code cannot reach.**

Under "Approach", say in a line or two what the design leaves out on purpose and why ("no rollout switch: reverting the pull request undoes it"), so the user reads a decision and not an omission. When the ticket itself asks for more than its goal needs, do not trim it silently: that is an open question, with the lighter option as its proposal.

Build the assignments: the prompt

Highlight any part of the prompt to leave a private note.

## 3. Run the rounds

Run the plan's rounds in order. Start every assignment of a round at once; start a round only when every assignment of the previous one is combined (step 5).

For each assignment:

1. Create its worktree from the ticket's branch: `git worktree add .context/factory/<ticket-id>/worktrees/<id> -b factory/<ticket-id>-<id>`. Git cannot keep `factory/<ticket-id>/<id>` beside the ticket's branch, hence the dash.
2. Record what it is planned to run on: `npm exec -- tokenwise plan <ticket-id> <id> --tier <tier> --planned-model <model>`, with the model the tier table maps its tier to (`references/tiers.md` in the `factory-design` skill). Then spawn its subagent with that model, set explicitly, in that worktree. If the runtime cannot set the model, stop and tell the user. Start its description with the assignment id, such as `2a: reason and rejection`: the cost report names the subagent after it, and matches it to the plan you recorded.
3. Hand it, verbatim, the plan's rules, the contract, its own assignment section, the scenarios it runs and its wireframes, plus:
   - its run id, `<ticket-id>-<id>` in lowercase, and the evidence directory's absolute path;
   - the steps below, which it follows in order, and the absolute paths of the `factory-check` and `factory-no-comments` skills installed in this worktree: it reads the first before writing a check and follows the second before its commit. Projects may keep installed skills out of Git, so the assignment's worktree may not have its own copy.

   Its scenarios are the `unit` and `integration` ones the plan gives it. A `video` or `black-box` scenario is never an assignment's, even when its behavior is.

Adversarial review: the prompt

Highlight any part of the prompt to leave a private note.

The acceptance checks prove each scenario works in the running app. This review covers what they cannot see: data reaching the wrong tenant, unsafe migrations, sends that can happen twice, paths no scenario reaches, the contract, cost on hot paths, and whether each check really proves its scenario. Two problems a check would never have caught: a delivered order reporting a failure, because no scenario had a delivered order; and a card with two Retry buttons.

It runs before the coordinator's acceptance checks, so a fix it asks for lands before the evidence is recorded, and no receipt goes stale because of it.

## Who reviews

A fresh process from a different model provider than the coordinator's, using that provider's strong model, read-only. When that provider gives no answer for any reason (its command is missing, it is not signed in, it is out of quota, it timed out), the same provider reviews in a fresh process instead. The reviewer reads the change, the plan, the project's instructions and the receipts; never the coordinator's reasoning or the subagents' reports, so it judges the work rather than the story about it.

The review runner makes that choice, runs the reviewer and records who actually reviewed. Do not review the change yourself in its place: a review by the session that built it is not independent.

Prove the behavior: the prompt

Highlight any part of the prompt to leave a private note.

## 1. Write it

One file per scenario, under `.context/factory/<ticket-id>/checks/` in the worktree that runs it, named `<scenario number>-<short slug>` with the extension the project's references give. Never in the project's test folders, and never committed. Its test name is the scenario's title, exactly as the plan gives it.

- **Given**: build only the data this scenario needs, scoped to records the check creates. Build times relative to the test's own clock (`two hours ago`), never as a calendar date. Use the setup the project's references describe; do not invent another way in.
- **When**: perform the scenario's event or action once, the way a person or the system would.
- **Then**: assert every part of it. Copy is asserted exactly as the plan quotes it. A `Then` that says something must not appear gets an assertion that it does not appear. A value is asserted where the scenario says it is: on screen for a `video`, in the response for a `black-box`, in the database or the returned value for `integration` and `unit`.
- **Fails without the change**: the check must fail on today's code. Assert what the ticket adds, not something the app already shows. If you cannot see how it would fail today, it does not prove the scenario.

Finish the draft PR: the prompt

Highlight any part of the prompt to leave a private note.

## 10. Open the draft pull request

1. Confirm that the last review's `reviewer.json` has the branch's `HEAD` as its `head`. Checks are never committed, so a later commit is product code nobody reviewed: review it first, as "Fixes after the review" says.
2. Push the ticket's branch, `factory/<ticket-id>`, and open a draft pull request against the base branch, following the project's own pull request instructions (template, title, language). When step 7 already opened it, push once and replace its title and description (`gh pr edit`) instead of opening another. Never mark it ready and never merge it.
3. Its description says what the ticket changes for a person using the product, links the ticket, and lists each scenario with its `Given` / `When` / `Then` as the plan words them, its impact, its evidence and whether it passed; who reviewed the change and what became of each finding; and the tests that ran, with any failure that is not the ticket's, and what is left to the pull request's CI. The checks and receipts are never committed. When the project's instructions or the `factory.references` give a way to publish recordings to a pull request, publish every `video` scenario's recording with it, after the push, so the description shows them. Only when the project has none, name the recordings in the evidence folder for the user to attach; a path on this machine is not evidence a reviewer can open.

Prepare for merge: the prompt

Highlight any part of the prompt to leave a private note.

`factory-build` ends at a draft pull request. After that the base branch moves, the project's CI fails, and reviewers comment. This skill handles the three together, in an order that keeps pushes and reruns few, and stops where a person's decision begins.

Every push to a pull request can start the project's CI and a paid review, and every code change can make a scenario's evidence stale. So the rule is: collect everything first, fix it once, push once. One trip through steps 2 to 7 is a **pass**.

Human merges: the prompt

Highlight any part of the prompt to leave a private note.

## What this skill never does

It never marks the pull request ready, merges it, force-pushes, dismisses a review or asks the automated reviewer for another review. An approval that is missing is a wait, not something to fix. It edits the ticket only after showing the user the exact change and getting a yes.

Turn repeated mistakes into guards: the prompt

Highlight any part of the prompt to leave a private note.

A trap is a **standing rule** an agent broke: something that was already true before the session (a documented convention, an invariant, a fact about how the system behaves), that lint, CI, the coder self-check and the code-reviewer let through, and that would plausibly recur in unrelated future work.

The fix for a trap is a guard that fails when the rule is broken: a structure that leaves one way to do it, a type, a lint rule, a test. Written advice is the last resort. Nothing fails when an agent skips it, and catalog entries cost attention whenever agents load them. An entry is for the residue only: a rule that needs judgment and that no guard can express.
### 3. Fix it at the highest level that works
Try each level in order, and stop at the first that holds. Say in the report why each higher level did not work.

1. **Make it impossible by structure.** One owner for the state, one supported way to do the task. Hide the internals so the wrong import fails. Replace two lists kept in step by hand with one source of truth. Delete the old way, and the dead example an agent would copy.
2. **Make it fail to compile or to lint.** A type that cannot hold the bad state. Where bad code still compiles, a lint rule or a check in the project's check directory whose error names the file, type or function to use instead. When the pattern is already common in the code, fail only when a change adds another occurrence, so the guard lands without a sweep.
3. **Test the behavior.** A test that fails when the rule is broken and keeps passing when only the internals change. Fix or delete a test that passes while the behavior it checks is broken.
4. **Write it down**, only when the rule needs judgment that none of the above can express. That is the catalog entry of step 5.

Technical design document: the prompt

Highlight any part of the prompt to leave a private note.

# Design page rules

The design page is `design.html`, built from [the skeleton](design-page.html). The user opens it in a browser, reads it and approves it. Write it for a person who knows the product but has not read the code. Keep each section short; the detail an implementer needs goes in the plan.
## The page itself

- Start from the skeleton and keep its stylesheet. The page's font is Lato, loaded from Google Fonts, with a system fallback when offline.
- Replace every `{{placeholder}}`. Keep every section, in the skeleton's order.
- Every section is always present. When it does not apply, write `No changes.` so the reader knows it was considered, not forgotten.
- Wrap every entity, table, column, field and endpoint name in `<code>`. Never put one in a narrow table column, where it wraps mid-word; give each entity or table its own card instead, as the skeleton does.
- No file lists. The only file names on the page are files two assignments share.
- The page builds a left-hand index from its `h2` headings, so every section heading appears in it. Keep sections as `h2` and the subsections inside them as `h3`.

## The ticket beside the design

The page carries the ticket in the panel beside the design, so the reader can check each section against what was asked without switching windows. Copy the ticket's description word for word, converted to HTML: its headings as `h2` and `h3`, its tables as tables, its links as links, and its images saved under `references/` and shown as `img`. Do not summarize, reorder, translate or correct it; a mistake in the ticket is an open question, not an edit. Fill in when it was read. Whenever the design reads the ticket again, after an answer changed it, copy it again.

The panel's headings stay out of the section index: the index lists the design's `h2` headings only.
## Open questions

Open questions come right after "What changes", where the reader sees them first.

- **What is a question.** The ticket contradicts the code, itself, or a ticket it depends on; the ticket leaves a product decision unmade; or an acceptance case cannot be produced or observed as written with the project's seed data, simulator and test tooling. An engineering choice is not a question: the design makes it and says why under "Approach".
- **Each question** says what it asks, why it blocks (what the ticket says against what the code does), and a proposal when there is a reasonable one.
- **While any question has no answer**, the status is `blocked: open questions`. The page cannot be approved in that state, and nothing downstream may start from it.
- **An answer** records the user's words, the date, and what changed because of it. When the answer changes what the ticket asks (behavior, copy, acceptance cases), the ticket is updated first and the design reads it again; the page never carries requirements the ticket lacks.
- With no questions left, the section says `None.` and the status becomes `pending approval`.
## 6. Write the documents

Save them under `.context/factory/<ticket-id>/`:

- `design.html`, copied from [the design page skeleton](references/design-page.html) and filled in following [the design page rules](references/design-page.md).
- `plan.md`, following [the working plan template](references/working-plan.md).
- `wireframes/*.html`, one per screen and state the UI section proposes, following the wireframe rules in the design page rules.

The design page is written in Spanish, with technical and medical concepts kept in English. Every section in the template is always present; one that does not apply says `No changes.` The UI section shows wireframes only when the proposal departs from the ticket's UI references, or when the ticket has none. Wireframes are HTML files built from the real screen and the project's design tokens, so read the component they change before drawing them.

The design page carries no file lists. The only file names on it are files two assignments share, because those change the order of work. File lists, entry points and notes go in the plan.

The agents work from the plan, not the design page: each one receives the rules and its own assignment, in English, with the files and entry points the page leaves out. Everything they act on is copied into the plan: the contract, every acceptance scenario with its `Given` / `When` / `Then`, impact, evidence and who runs it, and every table or text from the ticket an implementer must reproduce (screen copy, messages, labels), verbatim. The one exception is the wireframes, which the plan links from the assignment that builds that screen. Whenever the page changes, update the plan in the same revision.

Every recovery action the design names (a Retry, a Restart, a manual confirmation) must exist in the code, or be built by an assignment: name the endpoint or service it calls, after checking it accepts the case. A button that calls something the system refuses is found only when it is pressed.

Implementation plan: the prompt

Highlight any part of the prompt to leave a private note.

# Working plan template

The document the subagents work from. The user approves the design page, not this file, so it can carry every detail an implementer needs. Each assignment section is handed to its subagent together with the rules at the top.

# <ticket title>: working plan

Matches design revision <n>. Ticket: <ticket ID>. Proven at: <the commit whose code the scenarios' `Proof:` lines were confirmed against>

## Rules for every assignment

- Files owned by an assignment running at the same time as yours are off limits. If you need a change there, stop and report it to the coordinator.
- Your file list is the coordinator's best guess. You may change other files inside your area that no running assignment owns; list them in your report.
- You work in your own git worktree, with your own run (database, ports and simulator). Leave both in place when you finish: the coordinator may send findings back, and removes them once your commit is on the ticket's branch.
- Anything outside your area goes in your report, not in your diff.
- Before you commit, read your own diff against the project's written rules for code (its instruction files) and fix what breaks them, then follow the `factory-no-comments` skill on it, from the path the coordinator gives you. Do both before your checks run: a file changed afterwards makes them run again.
- You run only the `unit` and `integration` scenarios listed under "Runs scenarios". The coordinator writes and runs every `video` and `black-box` check after combining the work.
- Write one check per scenario you run, following the `factory-check` skill, under `.context/factory/<ticket-id>/checks/` in your worktree. It asserts everything the scenario's `Then` says, never less. Checks are never committed.
- Commit your product code as one commit, then run each check once with the check runner, passing the scenario's `Covers:` paths as `--covers`; it writes its receipt to the coordinator's evidence directory. A check run any other way does not count, and a scenario without a receipt leaves the assignment unfinished, whatever its impact. If you believe a scenario cannot be checked as written, say so in your report.

## Contract

<The same contract as the design page, plus anything an implementer needs that the page left out: exact type names, where the generated client lands, how placeholder data looks.>

## Ticket texts

<Every table or text from the ticket an implementer reproduces, verbatim: screen copy, messages, labels, with the ticket's own variables. Write "none" when the ticket has none.>

## Decisions

<Each decision taken in the design, with the records or states it applies to, and the user's words and date when it came from a question.>

## Assignment <id>: <name>

Tier: <tier>, because <one-line reason> Model: <the model tiers.md maps this tier to, set explicitly when spawning> Waits for: <assignment ids | nothing> Delivers: <what exists when it is done> Runs scenarios: <the `unit` and `integration` numbers from the Acceptance section below | none> Wireframes: <`wireframes/<file>.html` for each screen this assignment builds | none> Area: <the area in plain words>

Files, best guess:
- `<path>`: <why it changes>

Off limits while this runs:
- `<path>`: owned by assignment <id>

Start here:
- <entry points, functions and what the coordinator found there>

## Acceptance

<Every scenario from the design page, in its numbering. The coordinator writes and runs the `video`, `black-box` and other end-to-end ones after combining the work, and reads the rest from the assignments' receipts.>

### <n>. <the case, as the ticket states it>

Impact: <high | medium | low>: <what happens to the ticket's goal if this case fails> Run by: <assignment id, for unit and integration | coordinator, after combining> Given <the starting state> When <the event or the user's action> Then <what is seen or stored, with the exact copy> Evidence: <video | test · unit | test · integration | test · black-box>: <how to produce the case and what the evidence shows; for a test, why the running app cannot produce it> Proof: <filled in by the design before the page is approved: the concrete way the `Given` is reached and the `Then` observed (seed records or setup, simulator behavior, how the clock moves)> Covers: <filled in by the design with `Proof:`: the feature folders, in every app, that the `Given`, `When` and `Then` pass through, and the shared files they reach (contract, schema, migrations, shared helpers); every check of this scenario passes them as `--covers`> Check: written by whoever runs it, during the build, under `.context/factory/<ticket-id>/checks/`

## Build log

<Written by the build, one line per event, as it happens and never afterwards: this log and the files it points to are all a coordinator has when it picks the build up after a stop. Each line starts with the date and time, then what happened:
- the user's go-ahead for the build, in their words;
- each step of `factory-build` started and finished, by its number;
- each assignment spawned (its worktree and branch), judged, sent back with its findings, combined (its commit on the ticket's branch) and archived;
- each review run (its folder) and every finding's decision: who raised it, accept, reject or ask, and why, with a pull request comment's `id` when it has one;
- each check of the coordinator's written, run and judged, and each receipt refreshed;
- each push, and the pull request's number;
- anything waiting on the user, and their answer once it comes.>