Agent Workflow Standards
Agent Workflow Standards
Section titled “Agent Workflow Standards”Governing principle: One task = one branch = one worktree = one PR — or, when the change is too large for one review, one task = one stack of focused PRs in one worktree (§8).
Every discrete piece of agent work follows the same end-to-end lifecycle: isolate, implement, verify, deliver via pull request. Work is not considered done until a PR exists.
1. End-to-End Agent Workflow
Section titled “1. End-to-End Agent Workflow”The Complete Lifecycle
Section titled “The Complete Lifecycle”Non-trivial work (a new feature, a change crossing architectural layers, a migration) starts before step 1 with a design spec and an implementation plan — see proc-01 §11 and the templates in templates/docs/. UI work adds a design pass (§7). Trivial fixes go straight to the worktree.
This standard is agent-neutral: the same lifecycle applies whichever agent runs it (Claude Code, Codex, Cursor, Copilot, Gemini CLI, Aider, Antigravity). {{WORKTREE_DIR}} below is the project’s worktree root — worktree_dir: in .standards.yml, default .claude/worktrees — and the assembled agent configs carry the resolved value, so every agent in a project names the same directory. Anything that exists only for one agent lives in that agent’s appendix under standards/agents/<agent>/ (see §5).
Every agent task MUST follow these steps in order:
-
Create worktree + branch — from the main checkout, never from inside another worktree.
Terminal window git worktree add {{WORKTREE_DIR}}/<branch-name> -b <branch-name>cd {{WORKTREE_DIR}}/<branch-name> -
Write tests first (TDD). Red → Green → Refactor. No implementation code before a failing test.
-
Implement. Write the minimum code to pass tests. Maintain ≥ 95% coverage in all modified modules. Python code must pass
mypy --strict. -
Run the project’s full local gate (
make ci). It must pass before proceeding, and it must mirror CI: every check CI runs is inmake ciand vice versa, so a local pass predicts the CI result. A gate that passes locally and fails in CI (or the reverse) is a bug in the gate — fix the gate rather than route around it. -
Push the branch.
Terminal window git push -u origin <branch-name> -
Create a pull request. Link to the relevant issue. Include
🤖 Generated with [Agent Name]in the PR body.Terminal window gh pr create --title "type(scope): description" --body "..." -
Clean up after merge. Remove worktree, delete local branch, delete remote branch:
Terminal window git worktree remove {{WORKTREE_DIR}}/<branch-name>git branch -D <branch-name>git push origin --delete <branch-name>
Workspace Isolation
Section titled “Workspace Isolation”- Requirement: AI agents MUST work in git worktrees, never the developer’s root checkout.
- Location: Every agent’s worktrees live under the one root
{{WORKTREE_DIR}}/(worktree_dir:in.standards.yml, default.claude/worktrees) — not a per-agent directory. A project that prefers.worktrees/or.codex/worktrees/declares it once and every assembled agent config follows. - Rationale: The root checkout is the developer’s active workspace. Agent modifications cause conflicts with IDE state (unsaved buffers, debug configurations, terminal sessions). Worktrees provide full isolation at near-zero cost.
- Never modify files in the root checkout from an automated agent session.
- Create a new worktree at the start of each feature/fix branch.
Branch Naming
Section titled “Branch Naming”Agent branches MUST use the same type/description convention as human branches. Opaque IDs or numeric suffixes alone are not acceptable:
feat/preview-scroll-optimization ✓ descriptivefix/sidebar-drag-crash ✓ descriptiveworktree-agent-a0939472 ✗ opaque, impossible to triagecopilot/sub-pr-7 ✗ meaningless without the PRPre-Work Hygiene
Section titled “Pre-Work Hygiene”Before starting new work, verify no stale agent worktrees or branches remain:
git worktree list # should only show root checkout + active workgit branch --no-merged main # audit for abandoned branchesWorktree Hygiene
Section titled “Worktree Hygiene”The root checkout is the human’s volatile workspace — it auto-pulls mainline and its branch gets switched out from under you. These rules keep agent work from landing on the wrong branch or failing on phantom errors:
- Do all multi-commit work in a worktree, never the root checkout. If you must
touch the root, run
git branch --show-currentimmediately before every commit — a background pull may have flipped HEAD tomainor another branch. gh pr createinfers the head branch from the current directory. Run it from inside the feature worktree, or pass--head <branch>explicitly. Running it from the root opens a PR for whatever branch the root is on — your title/body on the wrong diff, a silent outward-facing mistake. Verify after:gh pr view <n> --json headRefName. (gh pr merge <number>is safe — it takes an explicit PR number.)- Install from the lockfile in a fresh worktree before running gates. A new
worktree shares the repo but not
node_modules/target; a plain install can resolve versions that differ from the committed lock and produce phantom lint or type failures on files you never touched. Use the frozen/locked mode (pnpm install --frozen-lockfile,npm ci,cargo build --locked). When a gate fails on an untouched file, check the installed toolchain version against the lock before “fixing” the file. - Repair git hooks after switching worktrees. Hook installers can leave
.git/hooks/*pointing at a deleted worktree’s path. If hooks misbehave, run the repo’s hook-repair target (e.g.make hooks) to rewrite them for the current checkout.
One worktree root per repository
Section titled “One worktree root per repository”Worktree sprawl is a disk and correctness problem, not a tidiness one: a survey
of four consumer projects found 17 worktrees under one checkout (.claude/worktrees
8.8 GB, .Codex/worktrees 12 GB), a .worktrees/ tree of 37 GB, worktrees nested
two deep, a worktree accidentally committed as a submodule, and a linter that timed
out walking them. These rules keep worktrees cheap:
- Every worktree lives under one gitignored root. The root is
{{WORKTREE_DIR}}—worktree_dir:in.standards.yml(default.claude/worktrees);setup.shwrites the.gitignoreentry and installs a pre-commit guard (templates/pre-commit-worktree-guard.example) that refuses any commit staging a path under it — a worktree arriving as a gitlink (the shape of a submodule) is the failure this prevents. Worktrees found elsewhere (.worktrees/,.Codex/worktrees/, …) are strays:doctorreports them andworktree-gccollects them like any other. - Never create a worktree from inside a worktree.
git worktree addresolves a relative path against the current directory, so running it from inside{{WORKTREE_DIR}}/aproduces{{WORKTREE_DIR}}/a/{{WORKTREE_DIR}}/b: a nested tree that doubles the disk cost and is skipped by nothing. Create worktrees from the main checkout, or pass the absolute path under the root.doctorwarns on nesting. - A worktree has a lifetime: its PR. It is removed when the PR merges (step 7
above), and a worktree with no commit or checkout activity for 14 days is
idle and collected. Uncommitted work in an idle worktree is a warning, not a
blocker: the collector says what it is discarding and removes the worktree;
pass
--keep-dirtyto opt out. An unmerged branch keeps its ref — only the directory goes. - Collect with
make worktree-gc(scripts/worktree-gc.sh). It fetches with--prune, removes worktrees whose branch is merged into the base (deleting those branches) or whose upstream is gone (keeping the branch: “gone” alone does not prove the commits landed), removes idle worktrees, prunes registrations whose directory vanished, reports every remaining worktree with its idle age and size, and never touches the main checkout, the worktree it runs from, a locked worktree, or a worktree that still encloses other worktrees.--dry-runpreviews. Run it after every merge, and from a weekly reminder on long-lived machines. make doctorreports worktree count, oldest idle age and total size, and warns on nesting, strays outside the root, a root that is not gitignored, and worktrees past the idle limit.
Shared caches live outside the worktree
Section titled “Shared caches live outside the worktree”N worktrees must not mean N copies of target/, node_modules/ or
DerivedData/. Point every build cache at one location per repository — under
~/.cache/<repo>/, or $TMPDIR when the checkout is inside a synced folder such as
iCloud Drive or Dropbox — so a fresh worktree builds warm and a removed worktree
frees only source. Set them in one place every tool sees (.envrc via direnv, the
make ci environment, the runner service’s environment):
| Tool | Setting | Example |
|---|---|---|
| Cargo | CARGO_TARGET_DIR |
~/.cache/<repo>/target |
| pnpm | pnpm config set store-dir (content-addressable; node_modules/ are hard links into it) |
~/.cache/pnpm-store |
| npm / yarn | npm_config_cache / YARN_CACHE_FOLDER |
~/.cache/<repo>/npm |
| Turborepo | TURBO_CACHE_DIR (or cacheDir in turbo.json) |
~/.cache/<repo>/turbo |
| SwiftPM / Xcode | swift build --scratch-path, xcodebuild -derivedDataPath |
~/.cache/<repo>/swiftpm, ~/.cache/<repo>/DerivedData |
| Gradle | GRADLE_USER_HOME, org.gradle.caching=true |
~/.cache/<repo>/gradle |
| Go | GOCACHE, GOMODCACHE (already outside the tree by default) |
~/.cache/go-build |
| Python (uv / pip) | UV_CACHE_DIR / PIP_CACHE_DIR |
~/.cache/<repo>/uv |
Caches that cannot be relocated (a tool that insists on ./node_modules) are
re-created per worktree from the lockfile (see “Install from the lockfile” above);
their size is part of what worktree-gc reclaims.
Throwaway build output deletes itself
Section titled “Throwaway build output deletes itself”Shared caches are kept on purpose; per-run output is not. A build, test or capture
that writes outside the repository — an -derivedDataPath for one e2e run, an
archive or export staging directory, extracted APKs, screenshot captures, an
emulator AVD, a copied checkout — must remove that output when it finishes. A
survey of one developer Mac found /private/tmp refilling between cleanups with
folders like these (658 MB, 1.7 GB each), none referenced again after their run.
- Create it with
mktemp -d, never at a fixed/tmp/<name>path. Usemktemp -d "${TMPDIR:-/tmp}/<repo>-<purpose>.XXXXXX". A fixed path collides between parallel runs and outlives every one of them. - Register an
EXITtrap on the line after creating it, so it is removed on success, failure and Ctrl-C alike. If the script already has anEXITtrap, remove the directory from that handler — a secondtrap … EXITreplaces the first. In Python usetempfile.TemporaryDirectory(); in Node,fs.mkdtempwith afinallythat callsfs.rm(dir, { recursive: true, force: true }). - Copy out what a person needs before the trap runs. The shipped artifact, a
log, or the
.xcresultof a failed run goes to a named, documented place (a gitignored directory in the repo, or a path the script prints); everything else goes.KEEP_TMP=1may skip the deletion for debugging — print the kept path when it does. - Agents follow the same rule for ad-hoc commands. A one-off
xcodebuild -derivedDataPath,cargo build --target-dir, download or extraction goes in the session’s scratch directory or amktemp -dthat the same subshell removes with anEXITtrap, preserving the command’s exit status ((dir=$(mktemp -d …) || exit; trap 'rm -rf "$dir"' EXIT; …)). Before reporting a task finished, delete every temporary directory the task created that is not a shared cache, and say where anything deliberately kept lives. - Caches are the exception, not a loophole. A directory reused across runs
(the table above) belongs under
~/.cache/<repo>/, not/tmp, and is never per-run. Something under/tmpis per-run by definition.
Runners: disk-free preflight and post-job cleanup
Section titled “Runners: disk-free preflight and post-job cleanup”Self-hosted runners accumulate the same sprawl without anyone looking. Every job on a persistent runner:
- Starts with a disk-free preflight that fails fast below a threshold (20 GB by
default) rather than dying mid-build with a cryptic
ENOSPC— see theapplelane intemplates/ci-gate.yml.example. - Ends with a cleanup step that runs
if: always():git worktree prune,git clean -ffdxin the checkout, and removal of the job’s scratch under$RUNNER_TEMP. Shared caches (above) are deliberately left alone — they are the point of a persistent runner. - Keeps the runner’s
_workdirectory on a volume with headroom, and runsworktree-gcfrom a scheduled job when agents work on the runner host.
See arch-08 § 6 for the rest of the runner rules.
2. Project-Level AI Guide
Section titled “2. Project-Level AI Guide”Every project SHOULD have an agent guide at the repository root — CLAUDE.md, AGENTS.md, .gemini/GEMINI.md, or whichever file its agents read; setup.sh assembles one per declared agent from the same blocks. The guide is distinct from the behavioural rules in .cursorrules or .github/copilot-instructions.md — it documents project-specific context that evolves during development.
Shape: a map plus known traps
Section titled “Shape: a map plus known traps”An agent guide has two kinds of content, and nothing else:
- A map. Where things are and how they fit: the sections in the table below. The map is stable and short — it points at detailed docs rather than inlining them.
- Known traps. Project-specific pitfalls that have already cost a debugging session, kept as a table whose rows carry the issue number that documented the trap and the date it was recorded, so a reader can judge whether it is still live. A trap row without an issue and a date cannot be audited; one consumer carried a wrong trap for months because nobody could tell when it had been true. Add a row whenever a bug’s root cause was “the agent did not know this”; delete the row when the trap is engineered away, and say so in the issue.
## Known Traps
| Trap | Why it bites | Issue | Date ||------|--------------|-------|------|| Run `make ci` from the repo root, not a package directory | Sub-make targets resolve paths from the working directory and silently skip suites | #412 | 2026-03-02 |Subtree guides add only what is local. A guide in a subdirectory (apps/web/CLAUDE.md, crates/core/AGENTS.md) holds the map and traps of that subtree and nothing the root guide already says — no repeated workflow, no repeated conventions, no second copy of the worktree rules. An agent reads the root guide and the subtree guide together; duplication is where they drift apart (a consumer’s subtree guide had to be hand-corrected when it carried its own copy of the worktree directory).
Required Sections
Section titled “Required Sections”| Section | Purpose |
|---|---|
| Project Summary | One paragraph describing what the project does |
| Key Commands | make check, make lint, make test, make ci, make fmt, make ls |
| Workspace Layout | Directory tree with purpose annotations |
| Architecture Rules | Dependency direction, critical invariants, “never do X” items |
| Error Handling | Library vs. app error patterns |
| Testing | Structure, coverage baselines, per-package commands |
| Key Source Files | Table mapping files to responsibilities |
| Commit Message Format | Conventional Commits reference with project-specific scopes |
| Known Traps | The table above: trap, why it bites, issue, date |
| Agent Workflow | Worktree root ({{WORKTREE_DIR}}), permission model |
Guidelines
Section titled “Guidelines”- Keep it under 300 lines. Link to detailed docs rather than inlining everything.
- Include concrete examples of invariants and how they break.
- Update it as the project evolves — it is a living document, not a one-time artifact.
- Describe the local gate honestly:
make ciis “the project’s full local gate” only when it mirrors CI; if the project has no such target, say which commands CI runs instead of claiming one. - Make
CHANGELOG.mdguidance conditional: a project with release automation (release-drafter, semantic-release, release-please, Changesets) must not tell agents to hand-edit the changelog.
3. Agent Permission Models
Section titled “3. Agent Permission Models”Define what agents can do autonomously vs. what requires human confirmation.
Default Permission Tiers
Section titled “Default Permission Tiers”| Action | Permission |
|---|---|
| Read files, search code | Autonomous |
| Edit/create source files | Autonomous |
Run tests (make test, cargo test) |
Autonomous |
Run linters/formatters (make lint, make fmt) |
Autonomous |
Run full CI (make ci) |
Autonomous |
| Git commit (in worktree) | Autonomous |
| Git push | Requires confirmation |
| Git force push, reset –hard | Requires explicit approval |
| Delete files/branches | Requires confirmation |
| Modify CI/CD pipelines | Requires explicit approval |
| Send messages (PR comments, emails) | Requires confirmation |
Configuration
Section titled “Configuration”Permission models should be defined in agent-specific configuration files:
- Claude Code:
.claude/settings.json - Cursor:
.cursorrules - Copilot:
.github/copilot-instructions.md - Codex:
AGENTS.md(approval mode section) - Gemini CLI:
.gemini/settings.json - Aider:
.aiderrc
4. Devloop Pattern (UI Projects)
Section titled “4. Devloop Pattern (UI Projects)”For projects with a graphical interface, expose an HTTP API that enables agents to build, inspect, and iterate on the UI autonomously.
Required Endpoints
Section titled “Required Endpoints”| Endpoint | Purpose |
|---|---|
POST /rebuild |
Trigger a build, block until complete, return build status |
GET /snapshot |
Return screenshot (PNG base64) + widget/component tree (JSON) |
GET /snapshot?diff=true |
Same as above, plus diff from previous snapshot |
Widget Tree JSON
Section titled “Widget Tree JSON”The snapshot response should include a structured representation of the UI hierarchy:
- Element ID, type/kind, bounding rectangle, visibility
- Style properties (background color, font size, etc.)
- Interactive state (focused, hovered, selected)
This enables agents to reason about UI changes semantically rather than relying solely on pixel-level screenshot comparison.
Make Targets
Section titled “Make Targets”setup-devloop: ## Install devloop dependenciesdevloop: ## Start devloop HTTP server for agent-driven UI iteration5. Agent-Specific Appendices
Section titled “5. Agent-Specific Appendices”Everything above applies to every agent. Rules that exist only because of how one agent works live beside that agent’s base template under standards/agents/<agent>/, so the shared standard never carries one agent’s vocabulary:
| Agent | Appendix | Covers |
|---|---|---|
| Google Antigravity (via Gemini) | standards/agents/gemini/antigravity.md |
Mission Isolation: one Mission per feature, .gemini/active_mission.log, mission-set.sh / mission-clear.sh, the read protocol other agents follow when a Mission is active |
Skills (standards/skills/) are agent-neutral runbooks emitted in each agent’s own shape — Claude Code skill files, Cursor commands, Copilot prompt files, a “Skills” section in AGENTS.md, GEMINI.md and the Aider instructions — by scripts/assemble-skills.sh and scripts/assemble-config.sh. A skill never names one agent’s tooling where another agent would have to translate.
6. Agent-Generated Artifacts
Section titled “6. Agent-Generated Artifacts”Commit Conventions
Section titled “Commit Conventions”Agent-authored commits MUST include a Co-Authored-By trailer identifying the agent:
feat(core): add validation for email addresses
Co-Authored-By: Claude Opus 4.6 <[email protected]>Pull Request Conventions
Section titled “Pull Request Conventions”Agents MUST open a pull request for every discrete piece of completed work. Work is not considered done until a PR exists.
Agent-created PRs MUST:
- Include
🤖 Generated with [Agent Name]in the PR description. - Follow the same title/body format as human-authored PRs.
- Link to the relevant issue or design document (
Closes #N,Fixes #N, orPart of #N).
Work Tracking
Section titled “Work Tracking”Agents MUST create GitHub Issues (or the project’s configured tracker) when they:
- Discover bugs or failing edge cases during implementation.
- Identify tech debt or shortcuts taken to meet scope.
- Encounter out-of-scope work that should be addressed later.
- Add
TODOorFIXMEcomments to the codebase — every such comment MUST reference an issue number.
Agents must NOT silently defer work. If something needs to be done, it needs to be tracked. Check CLAUDE.md, README.md, or .github/CONTRIBUTING.md for the project’s configured tracking tool. Default is GitHub Issues.
7. UI Change Validation
Section titled “7. UI Change Validation”For projects with a graphical interface, agents that modify UI files MUST validate the rendered output against a reference design before claiming the change is complete. This complements the Devloop Pattern — devloop enables agents to iterate; UI Change Validation enforces that the iteration converges on design intent.
Design pass before code
Section titled “Design pass before code”A new or reshaped surface gets a design pass before its first UI commit: copy templates/docs/design-pass.md to docs/design/YYYY-MM-DD-<surface>.md and fill the identity prompts, hard constraints, deliverables table and state inventory (empty / loading / error / streaming / sync paused / runner unavailable / pending write). The reference designs in assets/designs/ are a deliverable of that pass; the validation below compares the build against them. No design pass means no reference, which means the PR needs human visual sign-off (see “UI PRs are not auto-mergeable” below). See proc-01 §11.
When the protocol triggers
Section titled “When the protocol triggers”Agents SHOULD apply this protocol when modifying files matching any of the following patterns:
| Stack | Patterns (globs) |
|---|---|
| Web | **/*.tsx, **/*.jsx, **/*.vue, **/*.svelte, **/*.html, **/*.css, **/*.scss |
| Mobile / desktop | **/*.dart, **/*.swift, **/*.kt (Compose), **/*.xaml |
| Style tokens / theme | **/tokens.json, **/theme.*, **/design-tokens/**, **/*.tokens.{json,yml,yaml} |
Patterns are globs evaluated against repo-relative file paths. For changes that don’t trip a pattern (e.g., copy edits in a Markdown-driven CMS that affect rendered UI), the PR author MAY opt in by writing ui-validation: required in the PR body.
The three-step workflow
Section titled “The three-step workflow”- Render. Spin up the dev server (or use the project’s
/rebuilddevloop endpoint). - Capture. Take a screenshot of the changed surface using the agent’s browser tool — see “Cross-agent invocation” below.
- Compare. Diff the screenshot against the reference design in
assets/designs/<route-or-component>/<state>.png.
Comparison criteria
Section titled “Comparison criteria”The agent surfaces the diff; a human approves whether intent is met. Pixel-diff alone is not gating: font rendering, anti-aliasing, sub-pixel layout, and OS-level smoothing produce noise that swamps real design changes. Use one of:
- Side-by-side: reference and rendered output adjacent. Best for layout-driven changes.
- Overlay: rendered output 50% opacity over reference. Best for spacing and alignment.
- Per-region delta: cropped diffs for changed components only. Best for token / theme changes that touch many pages.
The agent’s output is a diff artifact + a summary of what changed. Approval is human-gated unless the project explicitly opts into pixel-diff gating (rare; document the threshold in assets/designs/NOTES.md).
UI PRs are not auto-mergeable without sign-off
Section titled “UI PRs are not auto-mergeable without sign-off”When a UI change has no reference design for the surface (a brand-new view, an exploratory layout), the agent MUST open the PR, attach the rendered screenshots, and wait for human visual sign-off — even when CI is green. Do not auto-merge. This is an explicit exception to the otherwise-autonomous merge loop in proc-03_code_review_expectations.md §1. State it in the PR body (e.g. “UI — needs visual sign-off, do not auto-merge”).
Visual baselines are environment-specific
Section titled “Visual baselines are environment-specific”Visual-regression baselines must be regenerated on the CI runner, not locally.
Even a matching local container renders fractionally differently (font hinting,
anti-aliasing) from the CI host, so locally-generated baselines fail the CI visual
gate. Regenerate via the pipeline’s own mechanism (e.g. a workflow_dispatch with
an update_snapshots input), and have that job finish the fix: push the
regenerated baselines to the PR branch as a bot commit, or upload them together
with a git diff --binary patch and print the one-line apply command. A dispatch
that only uploads baselines for the agent to download and commit by hand does not
meet the auto-fix rule in
arch-06_monorepo_workspace_standards.md
§6. Visual changes remain human-gated.
Cross-platform UI scope
Section titled “Cross-platform UI scope”For products that ship the same UX on multiple platforms, a UI change is assumed
to apply to every platform unless scoped otherwise. Scope the issue/PR to cover
web and each native shell, and keep shared data/logic single-sourced in the core.
See arch-07_cross_platform_shared_core_standards.md
§4. When the project declares the ui-surface profile, validation also walks the
arch-11 §3 audit items for the
touched surface on the running build, and a project ruling beats any audit item.
Cross-agent invocation
Section titled “Cross-agent invocation”| Agent | Browser tool |
|---|---|
| Google Antigravity | Built-in Browser Agent |
| Claude Code | Playwright MCP server (@modelcontextprotocol/server-playwright) |
| Cursor | Built-in browser tool |
| Aider, Codex | No native browser — projects exposing the Devloop GET /snapshot endpoint normalize this across all agents |
assets/designs/ directory convention
Section titled “assets/designs/ directory convention”Reference designs live in assets/designs/<route-or-component>/<state>.{png,svg}. Each project SHOULD include a copy of the templates/assets-designs-README.md.example template at assets/designs/README.md to document its specific naming conventions and breakpoint coverage.
The directory is opt-in per project — setup.sh does not auto-create it. Add it manually when the project takes on UI work.
Updating the reference
Section titled “Updating the reference”When design intent changes (designer ships a new mock, accessibility audit changes spacing, etc.):
- Update the reference in the same PR as the UI change.
- Note the intentional reference change in the PR body so reviewers know the diff is expected.
- Update
assets/designs/NOTES.mdif the change requires explanation (e.g., “Reduced primary CTA size to meet WCAG 2.5.5 target-size requirements”).
8. Stacked PRs
Section titled “8. Stacked PRs”When a task is too large to review as one PR, deliver it as a stack of focused
PRs with gh stack (the GitHub CLI extension; gh extension install github/gh-stack).
The workflow, thresholds and commands live in
proc-02 §11; reviewer expectations in
proc-03 §9. This section is how an agent
behaves inside that workflow.
When to propose a stack
Section titled “When to propose a stack”- Decide at planning time. If the implementation plan (proc-01 §11) estimates a diff past the proc-02 §11 thresholds (~400 changed lines or ~15 files a reviewer must read) or has two or more dependent layers (schema → API → UI, standard → linter → docs), the plan proposes a stack: one row per layer with its branch, Conventional Commit PR title, and why it stands alone.
- State the decision where the human will see it — the plan and the bottom PR body — so it can be vetoed before layers exist. Do not open a mega-PR and offer to split it later, and do not quietly open an unlinked chain of PRs.
- A task that fits one PR stays one PR. A stack of one is a PR.
One worktree per stack
Section titled “One worktree per stack”-
Create one worktree for the stack, named for the task, and initialise the stack inside it:
Terminal window git fetch origingit worktree add {{WORKTREE_DIR}}/<task> -b <type>/<task>/01-<layer> origin/maincd {{WORKTREE_DIR}}/<task>gh stack init <type>/<task>/01-<layer>Name the trunk (
origin/main) explicitly: without it,-bbranches from the main checkout’s currentHEAD— which may be the human’s active feature branch — andgh stack initadopts that branch, commits and all, as the bottom of the stack. -
Move between layers with
gh stack up/down/bottom/top/checkout <branch>; add layers withgh stack add <type>/<task>/<NN>-<layer>. Do not create a worktree per layer:gh stacktracks the stack in the repository’s common git directory and needs the worktree that owns each branch clean and idle during a cascade rebase, and N worktrees per task multiply the sprawl §1 exists to prevent.gh stacknever creates, removes or switches worktrees itself. -
The worktree lives as long as the stack: remove it (§1 step 7) after the last layer merges, after
gh stack sync --prunehas deleted the merged branches.
Layer boundaries
Section titled “Layer boundaries”- One concern per layer, tests included. A layer is one architectural slice
or one logical step; the tests that cover its code are in the same layer, and
each layer passes the project’s full local gate (
make ci) on its own before it is pushed — run the gate on every layer you touched, not only the top. - A change belongs to the layer that owns the code. A bug found while writing
layer 3 that lives in layer 1’s code is fixed on layer 1
(
gh stack checkout), then cascaded:gh stack rebase, re-runmake cion every rebased layer (at minimum the top, which carries the whole tree — a lower-layer change can break an upper layer whose own diff did not move), thengh stack push. Never patch a lower layer’s defect in an upper layer, and never let a lower layer reference code that only exists higher up. - The bottom must be safe alone. It merges to
mainfirst; if the feature is incomplete until the top lands, the bottom ships dark or behind a flag. - Every layer’s PR body carries the stack-position line
(
Stack: n of m — #a → #b (this PR) → #c),Closes #Non the top layer only (it lands last, so the issue closes with the whole stack) andPart of #Non every layer below it, and the🤖 Generated with [Agent Name]line (§6). - Submit deterministically. An agent session has no editor, so
gh stack submitfalls back to generated titles and draft PRs, which never enter the review loop. Rungh stack submit --auto, then for every layergh pr edit <n> --title "<type>(<scope>): <subject>" --body-file <layer-body>.mdandgh pr ready <n>(proc-02 §11, “Create a stack”). A layer is not submitted until its title, body and ready state are correct.
Never rewrite a layer someone else is reviewing
Section titled “Never rewrite a layer someone else is reviewing”- Once a layer has a reviewer — a human review requested or in progress, or the
automated reviewer’s findings still open — append commits; never amend,
squash, reorder, drop or
gh stack modifythat layer. Rewriting the history under a reviewer invalidates their line comments and their mental diff. - The one exception is the cascade rebase forced by a fix to a lower layer or
by
mainmoving: run it, and say so in each affected PR (“cascade rebase after the #41 fix; this layer’s diff is unchanged”). GitHub keeps approvals on layers whose diff did not change. - Before
gh stack rebase,gh stack syncorgh stack modify, check the review state of every layer the operation will rewrite (gh pr view <n> --json reviewDecision,reviewRequests). If a reviewer is mid-review on one of them and the rebase is not forced, wait or coordinate. gh stack push,gh stack syncandgh stack submitforce-push with lease. They sit in the same “Git push — requires confirmation” tier as any push (§3).
Merge the stack bottom-up
Section titled “Merge the stack bottom-up”- Run the merge loop of proc-03 §1 per layer: every layer waits for its own automated review, resolves its own findings and goes green on its own checks.
- Merge with
gh stack merge --squash --yes <pr>, naming the highest layer that has completed its review loop — the bottom alone, or a contiguous group from the bottom. Without a target a non-interactive merge takes the whole stack, sweeping unreviewed layers in or failing the all-or-nothing operation on one unmergeable upper layer. Never bypass a protection rule to land a layer. Auto-merge is not available for stacked PRs. gh stack syncafter every partial merge, before touching the next layer: GitHub rebases and retargets the remaining layers on the server, and the worktree’s branches and stack metadata only follow when you sync.- If
gh stackis unavailable or the host has no stacks (GitLab, a GitHub Enterprise Server without the feature, a fork), hand-chain the layers with the same rules (proc-02 §11, “Without the extension, or without GitHub stacks”): PRs based on the layer below, bottom-up merge, retarget before deleting a merged base — and say so in the bottom PR. Do not fall back to a single oversized PR.
Context Handling Across Layers
Section titled “Context Handling Across Layers”When agent work spans multiple architectural layers:
- Reference specific file paths when discussing code (e.g.,
packages/domain/user.py). - Summarize changes in the current layer’s context before moving to the next layer.
- Keep conversation context focused: avoid loading full files when only a section is relevant.