From d740e961b38caeb12c1ab230c2b71dce61b55f3b Mon Sep 17 00:00:00 2001 From: Roberto Aranda Date: Sat, 21 Nov 2026 18:54:08 +0100 Subject: [PATCH 1/2] Factory: Guard trunk conflicts, file follow-ups for partial PRs, and keep worktrees in the checkout --- .claude/agents/approver.md | 13 ++- .claude/agents/builder.md | 35 +++++- .claude/agents/intake.md | 23 +++- .claude/agents/reviewer-code.md | 8 +- .claude/agents/reviewer-runtime.md | 14 ++- .claude/agents/reviewer-security.md | 8 +- .claude/agents/reviewer-ui.md | 22 +++- .claude/agents/reviewer-ux.md | 17 ++- .claude/agents/spec-writer.md | 4 +- .claude/agents/triage.md | 6 +- .claude/skills/factory/SKILL.md | 23 ++-- .gitignore | 2 + AGENTS.md | 2 +- docs/software-factory.md | 14 ++- factory/bin/job | 169 ++++++++++++++++++++++++++-- factory/checks.sh | 3 + factory/config.json | 1 + factory/seed.sh | 2 +- factory/trunk.sh | 4 +- phpcs.xml.dist | 5 + 20 files changed, 314 insertions(+), 61 deletions(-) diff --git a/.claude/agents/approver.md b/.claude/agents/approver.md index 125c22d6..aac0a2d9 100644 --- a/.claude/agents/approver.md +++ b/.claude/agents/approver.md @@ -14,8 +14,8 @@ what you would merge yourself. ## Where you work -The worktree is a checkout of the job branch outside the main checkout you -start in. The shell returns to the main checkout after every command, so start +The worktree is a checkout of the job branch in its own folder, under +`factory/worktrees/` in the main checkout you start in. The shell returns to the main checkout after every command, so start every Bash command with `cd && `, and give Read, Grep and Glob absolute paths under the worktree. The job folder is in the main checkout; your one file goes there. @@ -63,9 +63,12 @@ ESCALATE if any of them fails, or if the change: - rests on a spec Assumption that is really a product decision, such as public copy, what a role can see, or a default users will notice. -Check the PR's linked issue with `gh pr view --json closingIssuesReferences`. -If it doesn't list the job's issue, the merge won't close it: say so under "For -the human". It never blocks an approval; a maintainer decides. +Check the PR's first line and `gh pr view --json closingIssuesReferences` +against `intake.md`. A job intake narrowed (`RESCOPED: yes`) says `Refs +#` and closes nothing, so the issue stays open for what is left; any +other job says `Closes #` and lists it. Say a mismatch under "For the +human", with what merging would do to the issue. It never blocks an approval; +a maintainer decides. ## Write decision.md diff --git a/.claude/agents/builder.md b/.claude/agents/builder.md index 00a5b0bf..85c4de07 100644 --- a/.claude/agents/builder.md +++ b/.claude/agents/builder.md @@ -18,14 +18,19 @@ exactly one factory file, `/build.md`. ## Where you work -The worktree is a checkout of the job branch outside the main checkout you -start in. All code changes happen there. The shell returns to the main checkout +The worktree is a checkout of the job branch in its own folder, under +`factory/worktrees/` in the main checkout you start in. All code changes happen there. The shell returns to the main checkout after every command, so start every Bash command with `cd && `, and give Read, Edit, Write, Grep and Glob absolute paths under the worktree. The job folder is in the main checkout; `build.md` is the only file you write there. Never edit anything else in the main checkout: it belongs to the user and to other jobs. +Keep every scratch file (a PR body draft, a log, a downloaded screenshot, a +helper script) in `/.scratch/`, which is gitignored. Other jobs' +agents run beside you in the same session, and a shared temporary folder is +where one job's PR body or log overwrites another's. + Git is the one exception to the `cd`. Run every git command as `git -C …`, in a Bash command of its own with no `cd` anywhere in it: a `cd` into another checkout followed by `git` stops for the @@ -118,7 +123,12 @@ of the code. Pass `--session -builder` on every `agent-browser` call, so other jobs never drive your browser, and close it with `agent-browser --session -builder close` when you're done. Record - what you did and what the page showed. Leave the site running for the + what you did and what the page showed. `agent-browser` can't hold a + modifier during a click (Shift+click arrives with `shiftKey: false`) and its + mouse wheel fires at the page's corner: send those through the same + session's CDP connection (`Input.dispatchMouseEvent`, + `Input.dispatchMouseWheelEvent`) and confirm the event the page received. + Leave the site running for the reviewers. If `agent-browser` or Docker isn't available, write BLOCKED: the job can't be verified. @@ -133,13 +143,28 @@ of the code. exactly like that and run from the main checkout, with no `cd` in front. It pushes this job's branch and nothing else, and never forces. Never run `git push` yourself: if the script refuses, write BLOCKED with what it said. + The one refusal you fix yourself is a conflict with the base branch, which + another PR merged while you worked: `git -C merge origin/`, + resolve the files it names keeping both changes' behaviour, run the checks + again, commit the merge and push. - If the branch has no PR yet (`gh pr view ` fails), open a draft PR against the base branch in `config.json`, with `gh pr create --draft --base --head `. Its title follows the repo's PR titles (`gh pr list --state merged --limit 10`). Write the body from `.github/pull_request_template.md`, keeping its headings and - deleting its comments, and make its first line `Closes #`. Once it - exists, just push to it; never open a second one. + deleting its comments, and make its first line `Closes #`. When + `intake.md` says `RESCOPED: yes`, the branch builds only part of the issue, + so make that line `Refs #` instead: merging must not close an issue + that still has work in it. Once the PR exists, just push to it; never open a + second one. +- When a round changes what the PR says (what it does, how to test it), write + the whole new body to `/.scratch/pr-body.md`, starting from + `gh pr view --json body --jq .body`, and run + `factory/bin/job body /.scratch/pr-body.md`, typed exactly + like that from the main checkout. It keeps the first line's `Closes` or `Refs` + honest and carries over the Screenshots and Playground preview blocks if you + left them out. Never run `gh pr edit` yourself: it stops the run to ask the + operator. ## Write build.md diff --git a/.claude/agents/intake.md b/.claude/agents/intake.md index f9665b44..4a9ad479 100644 --- a/.claude/agents/intake.md +++ b/.claude/agents/intake.md @@ -6,7 +6,7 @@ model: fable --- You are the factory's intake for one GitHub issue. Your prompt gives the job -folder and the issue number. You write exactly one file, +folder, the issue number and the trunk folder. You write exactly one file, `/intake.md`. You never edit code or any other file, and you have no shell. @@ -25,7 +25,10 @@ their request. When the author has answered your questions, decide again with the answers. 3. `AGENTS.md` (or `CLAUDE.md`) in the main checkout, and any doc it says to read for the area the issue touches. -4. The code the issue touches. Find the real files; don't guess at names. +4. The code the issue touches, in the trunk folder your prompt names: a + checkout of the latest base branch. The main checkout you start in can be on + any branch, so what it holds is not what the issue runs on. Find the real + files; don't guess at names. ## Decide @@ -99,6 +102,14 @@ in the code you read. ## Questions NEEDS-INFO only: numbered questions for the author. Omit the section otherwise. + +## Follow-ups +ACCEPT with RESCOPED: yes only: what the issue asks for that this job leaves +undone. Omit the section otherwise. + +### +Two to five sentences a later intake can work from: the request in the author's +words where they have some, and what this job's part does and doesn't cover. ``` The five header lines come first, exactly in that form, then a blank line. @@ -107,6 +118,12 @@ skim on the dashboard. The detail goes in the sections below it. `BEHAVIOUR: no` only when the change can touch nothing but docs or tests: every other change gets a runtime reviewer that uses it on trunk's site and the job's. `RESCOPED: yes` when your Scope builds less than, or something different -from, what the issue asks. +from, what the issue asks. The PR then refers to the issue without closing it, +and when it merges the factory opens one queued issue per `### ` entry under +`## Follow-ups`, so the rest of the request is built too. List there only what +the issue itself asks for, one entry per piece that can be one PR, at most +five. Leave out ideas of your own, anything a maintainer has to decide first +(new public API, a product call), and anything the code already does: say +those under "Left out:" in the Scope instead. Reply with one line: the decision, risk and surfaces. diff --git a/.claude/agents/reviewer-code.md b/.claude/agents/reviewer-code.md index 702ba6ee..1b3c4f95 100644 --- a/.claude/agents/reviewer-code.md +++ b/.claude/agents/reviewer-code.md @@ -12,8 +12,8 @@ edit code or any other file. ## Where you work -The worktree is a checkout of the job branch outside the main checkout you -start in. The shell returns to the main checkout after every command, so start +The worktree is a checkout of the job branch in its own folder, under +`factory/worktrees/` in the main checkout you start in. The shell returns to the main checkout after every command, so start every Bash command with `cd && `, and give Read, Grep and Glob absolute paths under the worktree. The job folder is in the main checkout; your one file goes there. @@ -148,4 +148,6 @@ its merits, and accepting it is fine. Then re-read the docs, code comments and PR description the round touched: drift after a rework is a nit. Omit the section in round 1. -Reply with one line: your verdict, and how many blockers, gaps and nits. +Write the file before you reply: the factory reads the file, and a review that +exists only in your reply counts as no review. Then reply with one line: your +verdict, and how many blockers, gaps and nits. diff --git a/.claude/agents/reviewer-runtime.md b/.claude/agents/reviewer-runtime.md index 8c7b975a..1f731d6a 100644 --- a/.claude/agents/reviewer-runtime.md +++ b/.claude/agents/reviewer-runtime.md @@ -103,7 +103,11 @@ test at real size; responsive UIs hide controls under a width (Gutenberg's back button below about 782 px); coordinates move between runs, so locate elements again before every click; a fresh site has the shell off until the `desktop_mode_mode` user meta is `1`; WooCommerce sends the first login to -wc-admin. +wc-admin; `agent-browser` can't hold a modifier during a click (Shift+click +arrives with `shiftKey: false`) and its mouse wheel fires at the page's corner, +so send those through the session's CDP connection +(`Input.dispatchMouseEvent`, `Input.dispatchMouseWheelEvent`) and confirm the +event the page received. **Screenshots for the PR.** For each behaviour a person can see, save one pair in `/round-/runtime/`: `before-.png` taken on trunk @@ -113,7 +117,9 @@ viewport, the same seeded state and the same moment. Frame the change, not the whole desktop. The factory uploads every complete pair and shows them side by side on the PR, where anyone can see them, so a pair shows only the two local sites. Keep everything else you save under another name. A change nobody can -see gets no pair. +see gets no pair. Take the pairs again in every round: the factory reads only +this round's folder, and an earlier round's `after-` shows a build that has +since changed. Close both browser sessions when you're done and leave both sites running. @@ -193,4 +199,6 @@ its merits, and accepting it is fine. Then re-read the docs, code comments and PR description the round touched: drift after a rework is a nit. Omit the section in round 1. -Reply with one line: your verdict, and how many blockers, gaps and nits. +Write the file before you reply: the factory reads the file, and a review that +exists only in your reply counts as no review. Then reply with one line: your +verdict, and how many blockers, gaps and nits. diff --git a/.claude/agents/reviewer-security.md b/.claude/agents/reviewer-security.md index 32ae32d6..4d93aacb 100644 --- a/.claude/agents/reviewer-security.md +++ b/.claude/agents/reviewer-security.md @@ -12,8 +12,8 @@ edit code or any other file. ## Where you work -The worktree is a checkout of the job branch outside the main checkout you -start in. The shell returns to the main checkout after every command, so start +The worktree is a checkout of the job branch in its own folder, under +`factory/worktrees/` in the main checkout you start in. The shell returns to the main checkout after every command, so start every Bash command with `cd && `, and give Read, Grep and Glob absolute paths under the worktree. The job folder is in the main checkout; your one file goes there. @@ -126,4 +126,6 @@ its merits, and accepting it is fine. Then re-read the docs, code comments and PR description the round touched: drift after a rework is a nit. Omit the section in round 1. -Reply with one line: your verdict, and how many blockers, gaps and nits. +Write the file before you reply: the factory reads the file, and a review that +exists only in your reply counts as no review. Then reply with one line: your +verdict, and how many blockers, gaps and nits. diff --git a/.claude/agents/reviewer-ui.md b/.claude/agents/reviewer-ui.md index efad9139..2a389835 100644 --- a/.claude/agents/reviewer-ui.md +++ b/.claude/agents/reviewer-ui.md @@ -12,8 +12,8 @@ edit code or any other file. ## Where you work -The worktree is a checkout of the job branch outside the main checkout you -start in. The shell returns to the main checkout after every command, so start +The worktree is a checkout of the job branch in its own folder, under +`factory/worktrees/` in the main checkout you start in. The shell returns to the main checkout after every command, so start every Bash command with `cd && `, and give Read, Grep and Glob absolute paths under the worktree. The job folder is in the main checkout; your one file goes there. @@ -51,7 +51,10 @@ port (AGENTS.md's software factory section says how to bring it up if it isn't). Sign in only to that local site, as AGENTS.md says, and nowhere else. Use the `agent-browser` CLI (run `agent-browser skills get core` first) to -screenshot it at desktop and phone widths, in light and dark. Pass +screenshot it at desktop and phone widths. The shell has one colour scheme, so +there is no light and dark pair to compare: when the change adds or changes a +colour, also look at it under the Legacy desktop theme (OpenStation +Preferences, Themes), which is the pre-brand look. Pass `--session -ui` on every `agent-browser` call, so other jobs' reviewers never drive your browser. When you're done, run `agent-browser --session -ui close`; leave the site running. If @@ -89,6 +92,9 @@ VERDICT: PASS | CHANGES ## Summary - 3 to 5 short bullets: what happened in this step and why +## Looked at +- + ## Blockers 1. @@ -119,6 +125,12 @@ Sort every finding into exactly one class: `## Summary` comes right after the header: 3 to 5 short bullets a human can skim on the dashboard. The detail goes in the sections below it. +**Looked at** is what you did in the browser, one bullet for each surface and +width: at least the changed surface at desktop width and at 375px, plus each +state the previous round's blockers were about. Write it for a PASS too: a +verdict with nothing looked at is not a review. When the change shows nowhere +in the shell, say so in one bullet and why. + The first line is `VERDICT: CHANGES` exactly when there's at least one blocker, and `VERDICT: PASS` otherwise. A gap, a nit or a not-this-PR finding never makes it CHANGES: every `CHANGES` costs a round. Write "None." under an empty @@ -135,4 +147,6 @@ its merits, and accepting it is fine. Then re-read the docs, code comments and PR description the round touched: drift after a rework is a nit. Omit the section in round 1. -Reply with one line: your verdict, and how many blockers, gaps and nits. +Write the file before you reply: the factory reads the file, and a review that +exists only in your reply counts as no review. Then reply with one line: your +verdict, and how many blockers, gaps and nits. diff --git a/.claude/agents/reviewer-ux.md b/.claude/agents/reviewer-ux.md index f4765a16..48b0a551 100644 --- a/.claude/agents/reviewer-ux.md +++ b/.claude/agents/reviewer-ux.md @@ -12,8 +12,8 @@ any other file. ## Where you work -The worktree is a checkout of the job branch outside the main checkout you -start in. The shell returns to the main checkout after every command, so start +The worktree is a checkout of the job branch in its own folder, under +`factory/worktrees/` in the main checkout you start in. The shell returns to the main checkout after every command, so start every Bash command with `cd && `, and give Read, Grep and Glob absolute paths under the worktree. The job folder is in the main checkout; your one file goes there. @@ -92,6 +92,9 @@ VERDICT: PASS | CHANGES ## Summary - 3 to 5 short bullets: what happened in this step and why +## Looked at +- + ## Blockers 1. @@ -122,6 +125,12 @@ Sort every finding into exactly one class: `## Summary` comes right after the header: 3 to 5 short bullets a human can skim on the dashboard. The detail goes in the sections below it. +**Looked at** is what you did in the browser, one bullet for each surface and +width: at least the changed surface at desktop width and at 375px, plus each +state the previous round's blockers were about. Write it for a PASS too: a +verdict with nothing looked at is not a review. When the change shows nowhere +in the shell, say so in one bullet and why. + The first line is `VERDICT: CHANGES` exactly when there's at least one blocker, and `VERDICT: PASS` otherwise. A gap, a nit or a not-this-PR finding never makes it CHANGES: every `CHANGES` costs a round. Write "None." under an empty @@ -138,4 +147,6 @@ its merits, and accepting it is fine. Then re-read the docs, code comments and PR description the round touched: drift after a rework is a nit. Omit the section in round 1. -Reply with one line: your verdict, and how many blockers, gaps and nits. +Write the file before you reply: the factory reads the file, and a review that +exists only in your reply counts as no review. Then reply with one line: your +verdict, and how many blockers, gaps and nits. diff --git a/.claude/agents/spec-writer.md b/.claude/agents/spec-writer.md index b044dc7d..ddb259da 100644 --- a/.claude/agents/spec-writer.md +++ b/.claude/agents/spec-writer.md @@ -11,8 +11,8 @@ job id, the worktree and the branch. You write exactly one file, ## Where you work -The worktree is a checkout of the job branch, fresh from the base branch, -outside the main checkout you start in. The shell returns to the main checkout +The worktree is a checkout of the job branch, fresh from the base branch, in +its own folder under `factory/worktrees/` in the main checkout you start in. The shell returns to the main checkout after every command, so start every Bash command with `cd && `, and give Read, Grep and Glob absolute paths under the worktree. The job folder is in the main checkout; your one file goes there. diff --git a/.claude/agents/triage.md b/.claude/agents/triage.md index 3bb99a24..757a249d 100644 --- a/.claude/agents/triage.md +++ b/.claude/agents/triage.md @@ -6,7 +6,7 @@ model: fable --- You are the factory's triage for one pull request someone else wrote. Your -prompt gives the job folder and the PR number. You write exactly one file, +prompt gives the job folder, the PR number and the trunk folder. You write exactly one file, `/triage.md`. You never edit code or any other file, and you have no shell. @@ -38,7 +38,9 @@ look before anything runs. 4. Any `triage-*.md` in the job folder: your earlier decisions. A new one after `TRUSTED: yes` means a maintainer looked at what you held. 5. `AGENTS.md`, and the code around the change, so you know what normal looks - like here. + like here. Read that code in the trunk folder your prompt names, a checkout + of the latest base branch: the main checkout you start in can be on any + branch. ## Decide diff --git a/.claude/skills/factory/SKILL.md b/.claude/skills/factory/SKILL.md index 64a7d58a..169ee444 100644 --- a/.claude/skills/factory/SKILL.md +++ b/.claude/skills/factory/SKILL.md @@ -25,7 +25,8 @@ intake (fable) → ACCEPT (scope possibly changed) | NEEDS-INFO | REJECT, po route (script) → reviewers + models from risk/surfaces via config.json worktree → factory/ from origin/ spec-writer (opus) → spec.md -builder (opus) → commits; first round pushes + opens draft PR "Closes #" +builder (opus) → commits; first round pushes + opens draft PR "Closes #" ("Refs #" when intake narrowed the issue: + the rest is queued as issues of its own when that PR merges) gate (script) → checks.sh; FAIL → builder gets the log, no reviewers spawned reviewers (routed) → parallel with CI (job ci), WAIT FOR ALL; CHANGES or red CI → builder → gate → … (max rounds) approver (opus) → APPROVE: job merge (sync, gate, then gh pr merge, or hand over when auto_merge is off) @@ -46,8 +47,9 @@ needs-human → HOLD, or too many CHANGES in a row: posted and labeled, ``` A PR job never commits code to the contributor's branch (the trunk merge is -the one push it makes), never approves or requests changes as a GitHub review, -and never merges. +the one push it makes) and never merges. Its report goes up under the +operator's name, as an approval or a request for changes, only when the +reporter is sure of it. Both kinds of job share the review, and the same two sites: the job's own, and the **trunk site** that `factory/trunk.sh` brings up at the start of every run @@ -94,7 +96,8 @@ session). You stay there; agents work in the job's worktree. /factory/jobs//screen.md PR jobs: what the script holds for a maintainer /factory/jobs//triage.md PR jobs /factory/jobs//round-/update.md, verdict.md, runtime/ PR jobs: trunk merge, report; runtime evidence -/../-factory/trunk/ the shared trunk site's worktree +/factory/worktrees// the job's worktree +/factory/worktrees/trunk/ the shared trunk site's worktree ``` Read a job with `cat factory/jobs//job.json`. Its `worktree` and @@ -151,7 +154,8 @@ that job and tell the user. Do the step for the job's `stage`, then the next one. **intake.** If `intake.md` doesn't exist, spawn `intake` with -` Issue: #.` (there is no worktree yet; the paths still name it). +` Issue: #. Trunk: .` (there is no worktree yet; the +paths still name it, and intake reads the code in the trunk folder). Then read its header: - `DECISION: ACCEPT`: run `factory/bin/route `, then @@ -168,8 +172,11 @@ fails, stop the job and tell the user. If `spec.md` doesn't exist, spawn `spec-writer` with ` Write the spec.` Then `factory/bin/job advance build` (round 1). -**build.** Spawn `builder` **named `builder-`** with -` Build round . Port: .` When it finishes, read the first +**build.** Spawn `builder` with +` Build round . Port: .` and keep the id the Agent tool gives +you: below, `builder-` stands for that agent, and resuming it means +`SendMessage` to that id. (Where the Agent tool takes a name, name it +`builder-`.) When it finishes, read the first line of `build.md`: - `STATUS: READY`: grep `build.md` for an unchecked criterion (`[ ]`). If @@ -259,7 +266,7 @@ Then read the first line of `decision.md`: ### PR jobs, step by stage **triage.** If `triage.md` doesn't exist, spawn `triage` with -` PR: #.` (no worktree yet). Triage reads one head: `pr.md`, +` PR: #. Trunk: .` (no worktree yet). Triage reads one head: `pr.md`, `pr.diff` and `screen.md` all describe the commit the job pinned, and from the second round on `pr.delta.diff` holds what the contributor pushed since the last one. Then read its header: diff --git a/.gitignore b/.gitignore index 7768cf30..48c8f57f 100644 --- a/.gitignore +++ b/.gitignore @@ -69,3 +69,5 @@ # Software factory runtime state: job files, logs, per-job locks. /factory/jobs/ +# The factory's worktrees: one per job, and the shared trunk site's. +/factory/worktrees/ diff --git a/AGENTS.md b/AGENTS.md index 621faa9d..a177dc02 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -284,7 +284,7 @@ When a change breaks a test, don't just rewrite the assertion to match. Decide w `/factory run` builds every open GitHub issue labeled `factory` through intake → spec → build → gate → review → approve, one PR per issue, and reviews every open PR labeled `factory` through triage → update → gate → review → report, posting once per round: an approval or a request for changes when the report is sure, a comment and the `factory:needs-human` label when a maintainer has to decide. [`docs/software-factory.md`](docs/software-factory.md) explains the pipeline, the stage machine and the scripts. State is in `factory/jobs/` (gitignored); `factory/bin/job` is its only writer. Checks: `factory/checks.sh`. Dashboard: `cd factory && python3 -m http.server`, then open http://localhost:8000/dashboard.html. The agents live in `.claude/agents/`, the orchestrator in `.claude/skills/factory/SKILL.md`. -- **It runs locally, from any checkout** (the main one or a Claude Code worktree), and needs Docker running and the `agent-browser` CLI installed. One `/factory run` drives `concurrency` jobs in parallel, each in its own worktree next to the checkout that runs it. Don't start a second `/factory run` while one is going: each checkout keeps its own `factory/jobs/`, so two runs would both build the same issues. A run skips anything GitHub shows another checkout's job waiting on or building; run that job from its own checkout. +- **It runs locally, from any checkout** (the main one or a Claude Code worktree), and needs Docker running and the `agent-browser` CLI installed. One `/factory run` drives `concurrency` jobs in parallel, each in its own worktree under `factory/worktrees/` in the checkout that runs it. They sit inside the checkout because a Claude Code worktree session may only write inside its own folder. Don't start a second `/factory run` while one is going: each checkout keeps its own `factory/jobs/`, so two runs would both build the same issues. A run skips anything GitHub shows another checkout's job waiting on or building; run that job from its own checkout. - **The `factory` label is the green light** for the factory to push `factory/` and open that issue's draft PR. When someone's open PR already closes the issue, the factory labels that PR and reviews it instead of building its own. `auto_merge` is off in `factory/config.json`: an approved PR is synced with `trunk`, gated again, marked ready and labeled `factory:needs-human` for a maintainer to merge. - **Fresh worktree setup**: `npm ci` and `composer install` (`checks.sh` does both when they're missing or stale). - **The gate** (`FACTORY_PORT= bash /factory/checks.sh` from the worktree) runs `npm run lint`, `typecheck`, `build`, `test:js` and host `phpcs`; then, in the job's own wp-env stacks, `test:php`, `test:php:multisite`, `lint:php`, and `factory/smoke.sh`, which loads the shell on the job's site in a headless browser and fails on a PHP error in `debug.log`, a JavaScript error, or a shell that never boots. `FACTORY_CHECKS=fast` runs only the host part. **CI is a step too**: while the reviewers read, `factory/bin/job ci` waits (up to 45 minutes) for the PR's checks on the round's commit, Plugin Check among them; a red check sends the job back to the builder as a failed round, and no job is approved on anything but green. diff --git a/docs/software-factory.md b/docs/software-factory.md index 81da1088..8572c4f0 100644 --- a/docs/software-factory.md +++ b/docs/software-factory.md @@ -19,7 +19,7 @@ intake (agent) ACCEPT (possibly rescoped) | NEEDS-INFO | REJECT, posted on route (script) picks the reviewers and their models from risk and surfaces worktree factory/ branched from origin/trunk spec-writer (agent) spec.md with testable acceptance criteria -builder (agent) always on Opus; commits; round 1 pushes and opens a draft PR that closes the issue +builder (agent) always on Opus; commits; round 1 pushes and opens a draft PR that closes the issue, or refers to it when intake narrowed it gate (script) runs checks.sh in the worktree; FAIL sends the log back to the builder reviewers (agents) in parallel with CI; CHANGES or red CI send the job back to the builder approver (agent) APPROVE: sync with trunk, gate again, merge or hand over @@ -136,11 +136,12 @@ The deterministic half of the factory is three scripts in `factory/bin/`, writte | Command | What it does | |---|---| | `job queue` | Lists every open `factory` issue and PR, every open PR that closes a `factory` issue with no job yet, and every unfinished job, as `action number job stage note`, where the action is `new`, `resume`, `hold`, `wait` or `skip`. It hands out the `concurrency` slots: jobs already in a running stage keep theirs, and only as many restartable waiting jobs and new issues and PRs as there are free slots come out as `resume` or `new`; the rest are `hold`. A waiting PR job resumes, back to triage, when its contributor pushes or, if it was held, when it gets the trusted label. It also finishes any unfinished job, at whatever stage, whose PR was merged (`merged`) or that was stopped on GitHub: the PR or issue closed, or the `factory` label removed (`abandoned`). Both tear down the job's stacks and worktree. | -| `job create [--now] [--fresh]` | Refuses when no concurrency slot is free, unless `--now`, and refuses an issue or PR that GitHub shows another checkout working on (see below), unless `--fresh`. For an issue that someone's open PR already closes: creates that PR's job instead (and refuses when there are several such PRs, listing them). For any other issue: checks it's open and labeled, writes `issue.md`, and creates the job as `NNN-` in stage `intake`, with branch `factory/` and a worktree next to the checkout under `-factory/`. For a PR: checks it's open, labeled or closing an open labeled issue (it then gets the label), not a draft and not the factory's own, writes `pr.md`, `pr.diff`, the linked issue's `issue.md` and `screen.md`, and creates the job in stage `triage`. | +| `job create [--now] [--fresh]` | Refuses when no concurrency slot is free, unless `--now`, and refuses an issue or PR that GitHub shows another checkout working on (see below), unless `--fresh`. For an issue that someone's open PR already closes: creates that PR's job instead (and refuses when there are several such PRs, listing them). For any other issue: checks it's open and labeled, writes `issue.md`, and creates the job as `NNN-` in stage `intake`, with branch `factory/` and a worktree inside the checkout, under `factory/worktrees/` (gitignored). For a PR: checks it's open, labeled or closing an open labeled issue (it then gets the label), not a draft and not the factory's own, writes `pr.md`, `pr.diff`, the linked issue's `issue.md` and `screen.md`, and creates the job in stage `triage`. | | `job update ` | PR jobs: puts the worktree on the PR's branch, merges the latest trunk in and pushes it, and writes `round-N/update.md` (`CURRENT`, `MERGED`, `LOCAL`, `CONFLICT`, or `MOVED` when the PR's head is no longer the one triage approved: nothing is merged or built, and the job goes back to triage). | -| `job push ` | For an issue job in `build`: pushes the job's `factory/` branch to `origin` from its worktree, and nothing else. It refuses a PR job and a worktree on any other branch, and it never forces, so a branch that moved on GitHub is refused, not overwritten. The builder pushes through it instead of running `git push`, so every push the factory makes is this script's. | +| `job push ` | For an issue job in `build`: pushes the job's `factory/` branch to `origin` from its worktree, and nothing else. It refuses a PR job and a worktree on any other branch, and it never forces, so a branch that moved on GitHub is refused, not overwritten. It also refuses a branch that conflicts with the base branch and names the files: GitHub runs no checks on a conflicting PR, so the builder merges the base branch in and resolves them before the round goes to review. The builder pushes through it instead of running `git push`, so every push the factory makes is this script's. | +| `job body ` | For an issue job in `build`: replaces the body of the job's own open PR with a file from its worktree. It refuses a body that doesn't open with `Closes #` or `Refs #`, a file outside the worktree and a PR that isn't the job's, and it copies the Screenshots and Playground preview blocks from the live body when the new one leaves them out. The builder updates its PR through it instead of running `gh pr edit`. | | `job advance [--now]` | Moves a job to a stage, or refuses. See below. `--now` skips the concurrency check on the moves that have one. | -| `job ci ` | Polls the PR's check rollup every thirty seconds for the round's commit and writes `round-N/ci.md` with `CI: PASS`, `FAIL`, `NONE` (nothing reported in ten minutes) or `TIMEOUT` (`ci_timeout_minutes`). The factory never re-runs CI. | +| `job ci ` | Polls the PR's check rollup every thirty seconds for the round's commit and writes `round-N/ci.md` with `CI: PASS`, `FAIL`, `NONE` (nothing reported in ten minutes) or `TIMEOUT` (`ci_timeout_minutes`). A PR that conflicts with the base branch is a `FAIL` right away, with the reason: GitHub runs no checks on it, and the builder can fix it. The factory never re-runs CI. | | `job merge ` | After `APPROVE`: merges `origin/trunk` into the branch, runs the gate again as `merge-checks.md`, pushes, marks the PR ready, and either merges it with `merge_method` (`auto_merge` on) or rewrites `decision.md` as an escalation and hands the PR to the maintainer (`auto_merge` off, the shipped default). Any failure lands in `needs-human` with the reason posted on the PR. | | `job feedback ` | For a `needs-human` issue job: saves the operator's words from stdin as `feedback-k.md`, grants a fresh set of rounds and moves the job to `build`. | | `job rework ` | For a `needs-human` job: collects the operator's PR comments, review bodies and inline comments (or issue comments, when there is no PR) written since the escalation into `rework-k.md`, grants a fresh set of rounds and moves the job to `build`. Refuses when there is nothing new to say. | @@ -160,7 +161,7 @@ A `` argument is a job id (`004-dark-mode`) or the number of its issue or P - `gate → review` needs `round-N/checks.md` to say `GATE: PASS` for the branch's current commit. `gate → build` needs `GATE: FAIL` and rounds left; `gate → needs-human` needs `GATE: FAIL` on the last round. - `review → approve` needs every routed reviewer's file with `VERDICT: PASS`, and `ci.md` with `CI: PASS` for the current commit. `review → build` needs at least one `CHANGES` or `CI: FAIL` and rounds left. `review → needs-human` is for the last round, or for `CI: TIMEOUT` / `CI: NONE`. A PR job's review goes only to `report`, whatever CI says: the reporter writes `HOLD` when CI never settles. - `approve → merging` needs `decision.md` to start with `APPROVE`; `approve → needs-human` needs `ESCALATE`. -- `→ merged`, from any unfinished stage, needs the PR to be merged on GitHub. It clears the `factory:needs-human` and `factory:needs-info` labels. +- `→ merged`, from any unfinished stage, needs the PR to be merged on GitHub. It clears the `factory:needs-human` and `factory:needs-info` labels. When the PR did not close the job's issue (its first line is `Refs #`, because intake built only part of it), it opens one `factory` issue for each entry under `## Follow-ups` in `intake.md` (at most `max_followups`), says so on the original issue and takes that issue's `factory` label off. The original stays open until the follow-ups land, no later run builds the same part again, and the rest of the request is built as PRs of its own. The follow-ups are filed at the merge, not before, because they usually build on the part that just landed. - `needs-human → build` needs a `feedback-k.md` or `rework-k.md` newer than `decision.md`, which is what `job feedback` and `job rework` write. - `needs-info → rejected` and `needs-human → rejected` need `rejection.md`, which is what `job reject` writes. The reason is posted on the issue, the factory labels come off, and the job's PR, if it has one, is closed and its branch deleted. The issue stays open. - `needs-info → intake`, `needs-human → triage` and `reviewed → triage` restart a waiting job from the queue, so they need a free concurrency slot. @@ -224,6 +225,7 @@ Job `n` (from the numeric prefix of its id) gets port `ports.base + ports.step | `runtime_reviewer` | The runtime reviewer's model. | | `fork_sensitive_paths` | Files a fork PR can't touch without a maintainer's look: they can run code at install or in CI. | | `slack_channel` | The Slack channel the maintainers watch, by name. `job` prints a `notify #: …` line whenever one of them has something to do, and the orchestrator posts it there through the session's Slack tool: when a job enters `needs-human` (a PR ready to merge, or a decision to make) and when the factory approves a contributor's PR. A request for changes, a question to an issue's author and a conflict with trunk are for the author, who hears about them on GitHub, so they print nothing. A session with no Slack tool lists the unsent notices in its summary. An empty name turns the notices off. | +| `max_followups` | The most follow-up issues the factory opens when a PR that delivered part of an issue merges. | | `pr_changes_limit` | Rounds of `CHANGES` in a row after which a PR job is labeled `factory:needs-human` and waits for the maintainer instead of re-reviewing the next push. | | `routing`, `surface_reviewers` | The agent routing tables described above. | | `protected_paths` | fnmatch patterns a branch may not modify or delete. | @@ -234,6 +236,8 @@ Job `n` (from the numeric prefix of its id) gets port `ports.base + ports.step **Requirements**: Docker running, the `agent-browser` CLI, `gh` authenticated as the operator, and Python 3. The orchestrator checks Docker and `agent-browser` before starting any job. It runs locally, from the main checkout or from any Claude Code worktree; each checkout keeps its own `factory/jobs/`, so never run two `/factory run`s at once. +**A worktree session runs the main checkout's agents.** Claude Code loads `.claude/agents/` and the `/factory` skill from the main checkout, while the scripts run from the checkout the session is in. When the two differ, `job queue` says so on stderr and names the files: bring the main checkout up to date before the run, or the factory steps today's scripts with yesterday's agents. + **A job belongs to the checkout that created it.** A run from another checkout doesn't see it, so `job queue` and `job create` look at GitHub instead: an issue or PR with no job here that carries `factory:needs-human` or `factory:needs-info`, a PR the factory has already reviewed, or an issue with the factory's own PR open for it, is another checkout's job. The queue lists it as `skip` (`another checkout's job`) and `job create` refuses it, rather than triaging and reviewing it again, commenting again and taking the same ports. Run the factory from the checkout that has the job, or move its folder into this checkout's `factory/jobs/` under a free job number (the number sets its ports). If that job is gone for good, `job create --fresh` starts over. A job in intake or triage leaves no trace on GitHub yet, which is why two runs at once still aren't safe. - **`/factory run`** brings up the trunk site, then drains the queue: `job queue`, then every job it offers (`concurrency` at a time, oldest issue first), each stepped by its stage until nothing is `new` or `resume`. It ends with `job summary`. diff --git a/factory/bin/job b/factory/bin/job index 21e175a6..aa70372d 100755 --- a/factory/bin/job +++ b/factory/bin/job @@ -22,6 +22,7 @@ Usage: move a job to , or refuse job update PR jobs: merge trunk into the PR, push it → round-N/update.md job push issue jobs in build: push the job's branch for the builder + job body issue jobs in build: replace the job's PR body with a file from its worktree job ci wait for the PR's CI on the round's commit → round-N/ci.md job merge APPROVE → sync with the base branch, gate, merge the PR (with auto_merge off: mark it ready and hand it to you) @@ -57,6 +58,9 @@ from urllib.parse import urlencode REPO = Path(__file__).resolve().parents[2] FACTORY = REPO / "factory" JOBS = FACTORY / "jobs" +# Job worktrees live inside the checkout that runs the factory: a session confined +# to its own folder, such as a Claude Code worktree session, can then edit them. +WORKTREES = FACTORY / "worktrees" BIN = FACTORY / "bin" CONFIG = json.loads((FACTORY / "config.json").read_text()) LABELS = CONFIG["labels"] @@ -314,6 +318,15 @@ def notify_needs_human(job): decision = (job_dir(job["id"]) / "decision.md").read_text() if "\n## Merge\n" in decision: return notify(job, "Ready to merge, approved by the factory") + if "\n## Summary\n" in decision: + # The approver's own file: its reasons run to paragraphs, and the PR carries them. + return notify(job, "Needs a maintainer's decision") + verdict = round_dir(job) / "verdict.md" + if "report says HOLD" in decision and verdict.exists(): + # The reporter's first Summary bullet says what it is holding for. + first = next((l[2:] for l in (section(verdict, "Summary") or "").splitlines() if l.startswith("- ")), "") + if reason := re.sub(r"^HOLD:\s*", "", first).strip()[:300].rstrip(".:"): + return notify(job, f"Needs a maintainer ({reason})") why = [l.strip() for l in decision.splitlines()[1:] if l.strip() and not l.startswith("#")] reason = re.sub(r"\s*See round-\S+$", "", why[0])[:300] if why else "" notify(job, "Needs a maintainer" + (f" ({reason.rstrip('.:')})" if reason else "")) @@ -595,6 +608,9 @@ def cost_usd(job): def sync(job): d = job_dir(job["id"]) + # A job folder brought here from another checkout, or a worktree moved into this one. + if not Path(job["worktree"]).exists() and (WORKTREES / job["id"]).exists(): + job["worktree"] = str(WORKTREES / job["id"]) # A PR job's triage.md carries the same header an issue job's intake.md does. intake = d / ("triage.md" if is_pr_job(job) else "intake.md") if intake.exists(): @@ -743,6 +759,20 @@ def advance(job, stage, force=False): require(job["pr"] and pr_state(job) == "MERGED", "the PR isn't merged") for name in labels_on(job) & {LABELS["needs_human"], LABELS["needs_info"]}: label("pr" if is_pr_job(job) else "issue", number(job), remove=name) + closes = gh_json("pr", "view", str(job["pr"]), "--json", "closingIssuesReferences")["closingIssuesReferences"] + if not is_pr_job(job) and job["issue"] not in {i["number"] for i in closes}: + # The PR referred to the issue without closing it, because intake had narrowed + # it. What it left out is queued as issues of its own, and this one stays open + # until they land. It leaves the queue: a run with no job for it would + # otherwise build the same part again. + filed = file_followups(job) + rest = (f"The rest is queued as {', '.join(f'#{n}' for n in filed)}, each built as a PR of its own. " + "This issue stays open until they land" if filed else + "The rest is not built, so this issue stays open. To have a remaining item built, open an " + f"issue for it and label it `{LABELS['queue']}`") + comment("issue", job["issue"], f"### Factory: merged\n\nPR #{job['pr']} delivers the part of this issue " + f"that the intake comment above scoped. {rest}. It leaves the factory's queue.") + label("issue", job["issue"], remove=LABELS["queue"]) elif stage == "abandoned": require(stopped_upstream(job), f"#{number(job)} is open and still labeled {LABELS['queue']}") @@ -987,7 +1017,9 @@ def advance(job, stage, force=False): + (d / "decision.md").read_text().split("\n", 1)[1].replace("## Why\n", "", 1).strip()) label("pr", job["pr"], add=LABELS["needs_human"]) elif stage == "needs-human": - body = f"### Factory: needs a human\n\n{(d / 'decision.md').read_text().split(chr(10), 1)[1].strip()}" + # A lone "## Why" would sit above the comment's own "###" title; a handover's "## Merge" stays. + why = (d / "decision.md").read_text().split("\n", 1)[1].strip().removeprefix("## Why\n").strip() + body = f"### Factory: needs a human\n\n{why}" if job["pr"]: if gh_json("pr", "view", str(job["pr"]), "--json", "isDraft")["isDraft"]: gh("pr", "ready", str(job["pr"])) @@ -1028,7 +1060,7 @@ def next_job_id(title): def fetch_open_prs(): return gh_json("pr", "list", "--state", "open", "--limit", "200", "--json", - "number,title,isDraft,headRefName,isCrossRepository,additions,deletions,labels,reviews," + "number,title,body,isDraft,headRefName,isCrossRepository,additions,deletions,labels,reviews," "closingIssuesReferences") @@ -1037,9 +1069,42 @@ def is_own(pr): return pr["headRefName"].startswith("factory/") and not pr["isCrossRepository"] +def own_issues(pr): + """The issues a factory PR was built for: the ones it closes, and the one its first + line refers to (`Refs #n`, when intake narrowed the issue and the PR leaves it open).""" + issues = {i["number"] for i in pr["closingIssuesReferences"]} + if m := re.match(r"(?:Closes|Refs) #(\d+)", pr.get("body") or ""): + issues.add(int(m.group(1))) + return issues + + +def followups(job): + """[(title, body)] from intake.md's `## Follow-ups`: what the issue asked for that + this job leaves undone, one `### ` each.""" + text = section(job_dir(job["id"]) / "intake.md", "Follow-ups") or "" + items = [i.split("\n", 1) for i in re.split(r"^### ", text, flags=re.M)[1:]] + return [(i[0].strip(), i[1].strip() if len(i) > 1 else "") for i in items][:CONFIG["max_followups"]] + + +def file_followups(job): + """Open a queued issue for each follow-up and return their numbers. + + followups.json records each one as it is filed, so a retry never files it twice. + """ + path = job_dir(job["id"]) / "followups.json" + filed = json.loads(path.read_text()) if path.exists() else {} + for title, body in followups(job): + if title not in filed: + url = gh("issue", "create", "--title", title, "--label", LABELS["queue"], "--body", + f"Part of #{job['issue']}, which #{job['pr']} delivered in part.\n\n{body}").strip() + filed[title] = int(url.rsplit("/", 1)[1]) + path.write_text(json.dumps(filed, indent=2) + "\n") + return list(filed.values()) + + def factory_prs(prs): """{issue number: PR number} for every open PR the factory built for an issue.""" - return {i["number"]: p["number"] for p in prs if is_own(p) for i in p["closingIssuesReferences"]} + return {n: p["number"] for p in prs if is_own(p) for n in own_issues(p)} def linked_prs(prs, issue): @@ -1108,7 +1173,7 @@ def cmd_create(arg, force=False, fresh=False): "id": job_id, "kind": "issue", "issue": issue["number"], "title": issue["title"], "issue_url": issue["url"], "pr": None, "pr_url": None, "branch": f"factory/{job_id}", - "worktree": str(REPO.parent / f"{REPO.name}-factory" / job_id), + "worktree": str(WORKTREES / job_id), "stage": "intake", "round": 0, "round_limit": CONFIG["max_rounds"], "intake": None, "agents": None, "gate": None, "ci": None, "reviews": {}, "cost_usd": 0.0, "started": now(), "ended": None, @@ -1145,7 +1210,7 @@ def cmd_create_pr(n): "issue": closes[0] if closes else None, "issue_url": pr["closingIssuesReferences"][0]["url"] if closes else None, "branch": f"factory-pr-{n}", - "worktree": str(REPO.parent / f"{REPO.name}-factory" / job_id), + "worktree": str(WORKTREES / job_id), "stage": "triage", "round": 0, "round_limit": CONFIG["max_rounds"], "intake": None, "agents": None, "gate": None, "ci": None, "reviews": {}, "report": None, "head": None, "own_shas": [], "verdicts": [], "held": False, @@ -1243,9 +1308,31 @@ def changes_streak(job): return streak +def stale_agents(): + """(main checkout, files) for the agent and skill files that differ from this checkout's. + + A session in a worktree loads its agents and the /factory skill from the main + checkout's .claude/, so a main checkout left behind runs yesterday's agents + against today's scripts. + """ + main = Path(run(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"]).stdout.strip()).parent + files = [] + for sub in ("agents", "skills/factory") if main != REPO else (): + here, there = REPO / ".claude" / sub, main / ".claude" / sub + for f in sorted(here.rglob("*.md")): + other = there / f.relative_to(here) + if not other.exists() or other.read_bytes() != f.read_bytes(): + files.append(f.name if sub == "agents" else str(f.relative_to(REPO / ".claude"))) + return main, files + + def cmd_queue(): """Rows in the order to start them. `resume` and `new` rows fit in the concurrency slots; the rest show as `hold` until a running job finishes.""" + main, stale = stale_agents() + if stale: + print(f"job: agents and the /factory skill load from {main}/.claude, where {len(stale)} differ from " + f"this checkout's ({', '.join(stale)}). Bring that checkout up to date before a run.", file=sys.stderr) every = all_jobs() # A job ends on GitHub, at any stage: merged once its PR is merged (which also # closes the issue), abandoned once someone stops it there (closes it, or @@ -1354,12 +1441,14 @@ def cmd_queue(): busy = [j["id"] for j in running(every)] slots = CONCURRENCY - len(busy) rows = list(running_rows) + ahead = list(busy) # what holds the slots: running jobs, then the rows this call hands one to for row in restart_rows + new_rows: if slots > 0: rows.append(row) slots -= 1 + ahead.append(row[2] if row[2] != "-" else f"#{row[1]}") else: - rows.append(("hold",) + row[1:4] + (f"concurrency {CONCURRENCY} reached; running: {', '.join(busy)}",)) + rows.append(("hold",) + row[1:4] + (f"concurrency {CONCURRENCY} reached; ahead of it: {', '.join(ahead)}",)) for row in rows + other_rows: print("\t".join(str(c) for c in row)) @@ -1387,8 +1476,9 @@ def ci_check(c): def cmd_ci(job): """Wait for the PR's checks on the round's commit and write round-N/ci.md. - PASS when every check finishes green, FAIL when any finishes red, NONE when no - check reports within ten minutes, TIMEOUT when they don't all finish within + PASS when every check finishes green, FAIL when any finishes red or the PR + conflicts with its base (GitHub then runs none), NONE when no check reports + within ten minutes, TIMEOUT when they don't all finish within ci_timeout_minutes. The factory never re-runs CI. """ if job["stage"] != "review": @@ -1396,9 +1486,14 @@ def cmd_ci(job): head = ci_commit(job) start = time.monotonic() while True: - pr = gh_json("pr", "view", str(job["pr"]), "--json", "headRefOid,statusCheckRollup") + pr = gh_json("pr", "view", str(job["pr"]), "--json", "headRefOid,statusCheckRollup,mergeable") checks = [ci_check(c) for c in pr["statusCheckRollup"]] if pr["headRefOid"] == head else [] waited = (time.monotonic() - start) / 60 + conflicting = not checks and pr["mergeable"] == "CONFLICTING" + if conflicting: + # GitHub runs no checks on a PR that conflicts with its base: waiting would only end in NONE. + verdict = "FAIL" + break if checks and all(done for _, _, done, _, _ in checks): verdict = "PASS" if all(ok for _, _, _, ok, _ in checks) else "FAIL" break @@ -1411,7 +1506,9 @@ def cmd_ci(job): time.sleep(30) red = [name for name, _, done, ok, _ in checks if done and not ok] what = {"PASS": f"All {len(checks)} checks on PR #{job['pr']} finished green", - "FAIL": f"{len(red)} of {len(checks)} checks failed: {', '.join(str(n) for n in red)}", + "FAIL": (f"The PR conflicts with {BASE}, so GitHub runs no checks on it: merge origin/{BASE} into " + "the branch, resolve the conflicts and push" if conflicting else + f"{len(red)} of {len(checks)} checks failed: {', '.join(str(n) for n in red)}"), "NONE": "No check reported on this commit within ten minutes", "TIMEOUT": f"The checks didn't all finish within {CONFIG['ci_timeout_minutes']} minutes"}[verdict] lines = [f"CI: {verdict}", f"COMMIT: {head}", "", @@ -1419,13 +1516,22 @@ def cmd_ci(job): f"## Checks on PR #{job['pr']}", ""] lines += [f"- {result or 'PENDING'}: {name} {url or ''}".rstrip() for name, url, _, _, result in sorted(checks, key=lambda c: (c[3], c[0] or ""))] or ["None reported."] - if verdict == "FAIL": + if verdict == "FAIL" and not conflicting: lines += ["", "Read a failed GitHub Actions job's log with `gh run view <run-id> --log-failed`; " "the run id is in its URL."] (round_dir(job) / "ci.md").write_text("\n".join(lines) + "\n") print(f"{job['id']}: CI {verdict} on {head[:7]} after {int(waited)}m") +def conflicts(job): + """Files where the job's branch conflicts with the latest base branch.""" + git(job, "fetch", "--quiet", "origin", BASE) + res = git(job, "merge-tree", "--write-tree", "--name-only", f"origin/{BASE}", "HEAD", check=False) + if res.returncode == 0: + return [] + return res.stdout.split("\n\n", 1)[0].splitlines()[1:] or [f"(git merge-tree failed: {res.stderr.strip()})"] + + def cmd_push(job): """Push an issue job's branch to origin, for its builder. @@ -1443,10 +1549,49 @@ def cmd_push(job): current = git(job, "branch", "--show-current").stdout.strip() if current != branch: die(f"{job['id']}: the worktree is on {current or 'a detached HEAD'}, not {branch}") + if files := conflicts(job): + # GitHub runs no checks on a PR that conflicts with its base, so the round would end with no CI. + die(f"{job['id']}: the branch conflicts with origin/{BASE} in {', '.join(files)}. " + f"Merge origin/{BASE} into it, resolve them, run the checks again, then push") git(job, "push", "--set-upstream", "origin", f"refs/heads/{branch}:refs/heads/{branch}") print(f"{job['id']}: pushed {branch} at {git(job, 'rev-parse', '--short', 'HEAD').stdout.strip()}") +# Blocks in a PR body that someone other than the builder writes: the factory's +# screenshots and the Playground preview bot's link. `job body` carries them over. +KEPT_BLOCKS = ((SHOTS_OPEN, SHOTS_CLOSE), + ("<!-- wp-playground-preview:start -->", "<!-- wp-playground-preview:end -->")) + + +def cmd_body(job, file): + """Replace the body of an issue job's own PR with a file from its worktree, for its builder. + + The builder's only edit to the PR once it is open. The body must still open + with the line that ties the PR to the job's issue, and the blocks the builder + doesn't write are copied from the live body when the new one leaves them out. + """ + if is_pr_job(job): + die(f"{job['id']} reviews someone else's PR; the factory never edits it") + if job["stage"] != "build": + die(f"{job['id']} is in {job['stage']}, not build") + path = Path(file).resolve() + if not path.is_file() or not path.is_relative_to(Path(job["worktree"]).resolve()): + die(f"{job['id']}: {file} isn't a file in the job's worktree") + pr = gh_json("pr", "view", job["branch"], "--json", "number,state,headRefName,isCrossRepository,body") + if pr["state"] != "OPEN" or pr["headRefName"] != job["branch"] or pr["isCrossRepository"]: + die(f"{job['id']}: PR #{pr['number']} isn't this job's open PR") + body = path.read_text().strip() + first = body.split("\n", 1)[0] + if not re.fullmatch(rf"(Closes|Refs) #{job['issue']}", first): + die(f"{job['id']}: the body must start with `Closes #{job['issue']}` or `Refs #{job['issue']}`, not {first[:60]!r}") + live = pr["body"] or "" + for start, end in sorted(KEPT_BLOCKS, key=lambda b: live.find(b[0])): + if start in live and end in live and start not in body: + body += "\n\n" + live[live.index(start):live.index(end) + len(end)] + gh("pr", "edit", str(pr["number"]), "--body", body + "\n") + print(f"{job['id']}: PR #{pr['number']} body updated ({first})") + + def cmd_merge(job): if is_pr_job(job): die(f"{job['id']} reviews someone else's PR; a maintainer merges it") @@ -1609,6 +1754,8 @@ def main(argv): cmd_update(resolve(args[0])) elif cmd == "push" and len(args) == 1: cmd_push(peek(args[0])) + elif cmd == "body" and len(args) == 2: + cmd_body(peek(args[0]), args[1]) elif cmd == "ci" and len(args) == 1: cmd_ci(peek(args[0])) elif cmd == "merge" and len(args) == 1: diff --git a/factory/checks.sh b/factory/checks.sh index 81efde9e..c8faaccc 100755 --- a/factory/checks.sh +++ b/factory/checks.sh @@ -49,6 +49,9 @@ if [ "${FACTORY_ENV:-wp-env}" = cloud ]; then bin/cloud-test-env.sh lint else WP_ENV_PORT=$(( port + 1 )) npm run env:start:tests + # Only these steps need the PHPUnit stack, so it stops when the checks end, + # pass or fail. The job's site is another stack and stays up for the reviewers. + trap 'npm run env:stop:tests >/dev/null 2>&1 || true' EXIT npm run test:php:install npm run test:php npm run test:php:multisite diff --git a/factory/config.json b/factory/config.json index 6abdca52..53357484 100644 --- a/factory/config.json +++ b/factory/config.json @@ -8,6 +8,7 @@ "ci_timeout_minutes": 45, "env": "wp-env", "pr_changes_limit": 3, + "max_followups": 5, "slack_channel": "openstation", "labels": { "queue": "factory", diff --git a/factory/seed.sh b/factory/seed.sh index b5ce565e..b8c7050d 100755 --- a/factory/seed.sh +++ b/factory/seed.sh @@ -13,7 +13,7 @@ job="${1:?usage: factory/seed.sh <job-id> <seed.php>}" seed="$(cd "$(dirname "${2:?usage: factory/seed.sh <job-id> <seed.php>}")" && pwd)/$(basename "$2")" repo="$(cd "$(dirname "$0")/.." && pwd)" worktree="$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["worktree"])' "$repo/factory/jobs/$job/job.json")" -trunk="$(dirname "$repo")/$(basename "$repo")-factory/trunk" +trunk="$repo/factory/worktrees/trunk" for site in "$trunk" "$worktree"; do # Each wp-env instance mounts its own checkout as the plugin, so a copy under diff --git a/factory/trunk.sh b/factory/trunk.sh index 31006d2f..604bf66a 100755 --- a/factory/trunk.sh +++ b/factory/trunk.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # The shared trunk site every review compares against: the latest trunk, built, -# on `ports.trunk` (8900), in its own worktree next to the checkout. Without it +# on `ports.trunk` (8900), in its own worktree under factory/worktrees/. Without it # a reviewer can't tell "fixed" from "never reproduced", or a regression from a # bug that was already there. # @@ -14,7 +14,7 @@ set -euo pipefail repo="$(cd "$(dirname "$0")/.." && pwd)" -dir="$(dirname "$repo")/$(basename "$repo")-factory/trunk" +dir="$repo/factory/worktrees/trunk" read -r port base < <(python3 -c 'import json, sys; c = json.load(open(sys.argv[1])); print(c["ports"]["trunk"], c["base_branch"])' "$repo/factory/config.json") if [ "${1:-}" = destroy ]; then diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 50015970..2e5bf902 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -32,6 +32,11 @@ scanned nothing. --> <exclude-pattern type="relative">^\.claude/</exclude-pattern> + <!-- + The factory's job worktrees are whole checkouts inside this one. Relative + for the same reason: phpcs run inside one of them must still scan it. + --> + <exclude-pattern type="relative">^factory/worktrees/</exclude-pattern> <!-- House sniff sources — PHPCS-convention code, not plugin code. --> <exclude-pattern>/tools/phpcs/</exclude-pattern> From 55308c134d7e696982786ab33fa15b53ab9308a4 Mon Sep 17 00:00:00 2001 From: Roberto Aranda <roberto.aranda@automattic.com> Date: Sat, 21 Nov 2026 19:04:44 +0100 Subject: [PATCH 2/2] Factory: Say Related to, not Refs, on a PR that delivers part of an issue --- .claude/agents/approver.md | 2 +- .claude/agents/builder.md | 4 ++-- .claude/skills/factory/SKILL.md | 2 +- docs/software-factory.md | 4 ++-- factory/bin/job | 9 +++++---- 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/.claude/agents/approver.md b/.claude/agents/approver.md index aac0a2d9..a52ab927 100644 --- a/.claude/agents/approver.md +++ b/.claude/agents/approver.md @@ -64,7 +64,7 @@ ESCALATE if any of them fails, or if the change: copy, what a role can see, or a default users will notice. Check the PR's first line and `gh pr view <pr> --json closingIssuesReferences` -against `intake.md`. A job intake narrowed (`RESCOPED: yes`) says `Refs +against `intake.md`. A job intake narrowed (`RESCOPED: yes`) says `Related to #<issue>` and closes nothing, so the issue stays open for what is left; any other job says `Closes #<issue>` and lists it. Say a mismatch under "For the human", with what merging would do to the issue. It never blocks an approval; diff --git a/.claude/agents/builder.md b/.claude/agents/builder.md index 85c4de07..64c0db08 100644 --- a/.claude/agents/builder.md +++ b/.claude/agents/builder.md @@ -154,14 +154,14 @@ of the code. the body from `.github/pull_request_template.md`, keeping its headings and deleting its comments, and make its first line `Closes #<issue>`. When `intake.md` says `RESCOPED: yes`, the branch builds only part of the issue, - so make that line `Refs #<issue>` instead: merging must not close an issue + so make that line `Related to #<issue>` instead: merging must not close an issue that still has work in it. Once the PR exists, just push to it; never open a second one. - When a round changes what the PR says (what it does, how to test it), write the whole new body to `<worktree>/.scratch/pr-body.md`, starting from `gh pr view <branch> --json body --jq .body`, and run `factory/bin/job body <job-id> <worktree>/.scratch/pr-body.md`, typed exactly - like that from the main checkout. It keeps the first line's `Closes` or `Refs` + like that from the main checkout. It keeps the first line's `Closes` or `Related to` honest and carries over the Screenshots and Playground preview blocks if you left them out. Never run `gh pr edit` yourself: it stops the run to ask the operator. diff --git a/.claude/skills/factory/SKILL.md b/.claude/skills/factory/SKILL.md index 169ee444..ebd966f7 100644 --- a/.claude/skills/factory/SKILL.md +++ b/.claude/skills/factory/SKILL.md @@ -25,7 +25,7 @@ intake (fable) → ACCEPT (scope possibly changed) | NEEDS-INFO | REJECT, po route (script) → reviewers + models from risk/surfaces via config.json worktree → factory/<job-id> from origin/<base_branch> spec-writer (opus) → spec.md -builder (opus) → commits; first round pushes + opens draft PR "Closes #<n>" ("Refs #<n>" when intake narrowed the issue: +builder (opus) → commits; first round pushes + opens draft PR "Closes #<n>" ("Related to #<n>" when intake narrowed the issue: the rest is queued as issues of its own when that PR merges) gate (script) → checks.sh; FAIL → builder gets the log, no reviewers spawned reviewers (routed) → parallel with CI (job ci), WAIT FOR ALL; CHANGES or red CI → builder → gate → … (max rounds) diff --git a/docs/software-factory.md b/docs/software-factory.md index 8572c4f0..47996772 100644 --- a/docs/software-factory.md +++ b/docs/software-factory.md @@ -139,7 +139,7 @@ The deterministic half of the factory is three scripts in `factory/bin/`, writte | `job create <number> [--now] [--fresh]` | Refuses when no concurrency slot is free, unless `--now`, and refuses an issue or PR that GitHub shows another checkout working on (see below), unless `--fresh`. For an issue that someone's open PR already closes: creates that PR's job instead (and refuses when there are several such PRs, listing them). For any other issue: checks it's open and labeled, writes `issue.md`, and creates the job as `NNN-<slug>` in stage `intake`, with branch `factory/<job-id>` and a worktree inside the checkout, under `factory/worktrees/<job-id>` (gitignored). For a PR: checks it's open, labeled or closing an open labeled issue (it then gets the label), not a draft and not the factory's own, writes `pr.md`, `pr.diff`, the linked issue's `issue.md` and `screen.md`, and creates the job in stage `triage`. | | `job update <job>` | PR jobs: puts the worktree on the PR's branch, merges the latest trunk in and pushes it, and writes `round-N/update.md` (`CURRENT`, `MERGED`, `LOCAL`, `CONFLICT`, or `MOVED` when the PR's head is no longer the one triage approved: nothing is merged or built, and the job goes back to triage). | | `job push <job>` | For an issue job in `build`: pushes the job's `factory/<job-id>` branch to `origin` from its worktree, and nothing else. It refuses a PR job and a worktree on any other branch, and it never forces, so a branch that moved on GitHub is refused, not overwritten. It also refuses a branch that conflicts with the base branch and names the files: GitHub runs no checks on a conflicting PR, so the builder merges the base branch in and resolves them before the round goes to review. The builder pushes through it instead of running `git push`, so every push the factory makes is this script's. | -| `job body <job> <file>` | For an issue job in `build`: replaces the body of the job's own open PR with a file from its worktree. It refuses a body that doesn't open with `Closes #<issue>` or `Refs #<issue>`, a file outside the worktree and a PR that isn't the job's, and it copies the Screenshots and Playground preview blocks from the live body when the new one leaves them out. The builder updates its PR through it instead of running `gh pr edit`. | +| `job body <job> <file>` | For an issue job in `build`: replaces the body of the job's own open PR with a file from its worktree. It refuses a body that doesn't open with `Closes #<issue>` or `Related to #<issue>`, a file outside the worktree and a PR that isn't the job's, and it copies the Screenshots and Playground preview blocks from the live body when the new one leaves them out. The builder updates its PR through it instead of running `gh pr edit`. | | `job advance <job> <stage> [--now]` | Moves a job to a stage, or refuses. See below. `--now` skips the concurrency check on the moves that have one. | | `job ci <job>` | Polls the PR's check rollup every thirty seconds for the round's commit and writes `round-N/ci.md` with `CI: PASS`, `FAIL`, `NONE` (nothing reported in ten minutes) or `TIMEOUT` (`ci_timeout_minutes`). A PR that conflicts with the base branch is a `FAIL` right away, with the reason: GitHub runs no checks on it, and the builder can fix it. The factory never re-runs CI. | | `job merge <job>` | After `APPROVE`: merges `origin/trunk` into the branch, runs the gate again as `merge-checks.md`, pushes, marks the PR ready, and either merges it with `merge_method` (`auto_merge` on) or rewrites `decision.md` as an escalation and hands the PR to the maintainer (`auto_merge` off, the shipped default). Any failure lands in `needs-human` with the reason posted on the PR. | @@ -161,7 +161,7 @@ A `<job>` argument is a job id (`004-dark-mode`) or the number of its issue or P - `gate → review` needs `round-N/checks.md` to say `GATE: PASS` for the branch's current commit. `gate → build` needs `GATE: FAIL` and rounds left; `gate → needs-human` needs `GATE: FAIL` on the last round. - `review → approve` needs every routed reviewer's file with `VERDICT: PASS`, and `ci.md` with `CI: PASS` for the current commit. `review → build` needs at least one `CHANGES` or `CI: FAIL` and rounds left. `review → needs-human` is for the last round, or for `CI: TIMEOUT` / `CI: NONE`. A PR job's review goes only to `report`, whatever CI says: the reporter writes `HOLD` when CI never settles. - `approve → merging` needs `decision.md` to start with `APPROVE`; `approve → needs-human` needs `ESCALATE`. -- `→ merged`, from any unfinished stage, needs the PR to be merged on GitHub. It clears the `factory:needs-human` and `factory:needs-info` labels. When the PR did not close the job's issue (its first line is `Refs #<issue>`, because intake built only part of it), it opens one `factory` issue for each entry under `## Follow-ups` in `intake.md` (at most `max_followups`), says so on the original issue and takes that issue's `factory` label off. The original stays open until the follow-ups land, no later run builds the same part again, and the rest of the request is built as PRs of its own. The follow-ups are filed at the merge, not before, because they usually build on the part that just landed. +- `→ merged`, from any unfinished stage, needs the PR to be merged on GitHub. It clears the `factory:needs-human` and `factory:needs-info` labels. When the PR did not close the job's issue (its first line is `Related to #<issue>`, because intake built only part of it), it opens one `factory` issue for each entry under `## Follow-ups` in `intake.md` (at most `max_followups`), says so on the original issue and takes that issue's `factory` label off. The original stays open until the follow-ups land, no later run builds the same part again, and the rest of the request is built as PRs of its own. The follow-ups are filed at the merge, not before, because they usually build on the part that just landed. - `needs-human → build` needs a `feedback-k.md` or `rework-k.md` newer than `decision.md`, which is what `job feedback` and `job rework` write. - `needs-info → rejected` and `needs-human → rejected` need `rejection.md`, which is what `job reject` writes. The reason is posted on the issue, the factory labels come off, and the job's PR, if it has one, is closed and its branch deleted. The issue stays open. - `needs-info → intake`, `needs-human → triage` and `reviewed → triage` restart a waiting job from the queue, so they need a free concurrency slot. diff --git a/factory/bin/job b/factory/bin/job index aa70372d..c8f760b4 100755 --- a/factory/bin/job +++ b/factory/bin/job @@ -1071,9 +1071,10 @@ def is_own(pr): def own_issues(pr): """The issues a factory PR was built for: the ones it closes, and the one its first - line refers to (`Refs #n`, when intake narrowed the issue and the PR leaves it open).""" + line refers to (`Related to #n`, when intake narrowed the issue and the PR leaves it open; + `Refs #n` reads the same).""" issues = {i["number"] for i in pr["closingIssuesReferences"]} - if m := re.match(r"(?:Closes|Refs) #(\d+)", pr.get("body") or ""): + if m := re.match(r"(?:Closes|Related to|Refs) #(\d+)", pr.get("body") or ""): issues.add(int(m.group(1))) return issues @@ -1582,8 +1583,8 @@ def cmd_body(job, file): die(f"{job['id']}: PR #{pr['number']} isn't this job's open PR") body = path.read_text().strip() first = body.split("\n", 1)[0] - if not re.fullmatch(rf"(Closes|Refs) #{job['issue']}", first): - die(f"{job['id']}: the body must start with `Closes #{job['issue']}` or `Refs #{job['issue']}`, not {first[:60]!r}") + if not re.fullmatch(rf"(Closes|Related to|Refs) #{job['issue']}", first): + die(f"{job['id']}: the body must start with `Closes #{job['issue']}` or `Related to #{job['issue']}`, not {first[:60]!r}") live = pr["body"] or "" for start, end in sorted(KEPT_BLOCKS, key=lambda b: live.find(b[0])): if start in live and end in live and start not in body: