armelhbobdad/bmad-module-ultracode-goal / skills/ultracode-goal
ultracode-goal
FlaggedRuns a BMAD Epic autonomously to a machine-checked Definition-of-Done. Use when the user requests to 'run an epic autonomously', 'execute this epic', 'ultracode goal', or 'autonomously deliver the epic'.
references/execute.md
View on GitHub# Stage 4 — Execute
Drive each in-scope story from its red-phase acceptance tests (generated in Stage 3) to a green, committed state. This stage **produces and prints evidence**; it does **not** decide completion. The completion verdict belongs to Stage 5 (`scripts/gate_eval.py` reading TEA's `gate-decision.json`) — never the `/goal` transcript evaluator, which can only see what you surface and cannot read the gate file. Run prose in `{communication_language}`.
One path: the **sequential `/goal` spine**, named for the `/goal`-style condition each story's drive is written against; the conductor cannot start a live `/goal` (see "Authoring the `/goal` condition"). (The experimental `--parallel` worktree fan-out is retired; the flag is still accepted so an old invocation does not error — see "Retired — `--parallel`" below.)
Preconditions (asserted, not assumed): you are on the Epic branch (`{workflow.epic_branch_prefix}…`, off a `{workflow.protected_branches}` branch), PreToolUse + Stop hooks are armed in `.claude/settings.local.json`, the allowlist is pre-populated, and (**in production**) every in-scope story has an `atdd-checklist-{story_key}.md` with `test.skip` acceptance tests. (Under `--light` there is no atdd-checklist by design; the story file's clear acceptance criteria are the Stage-5 trace oracle instead: see define-done.md's `--light` note. The clear-ACs precondition still holds. **On a stack whose ATDD generator cannot run** (the non-web case `references/gate.md`'s hand-authoring section carves out), there is no atdd-checklist either, and that is not a failed precondition: the checklist is replaced by a red phase established BY HAND, authored, RUN and captured before the story's first implementation edit, per gate.md's non-web section and step 1 below. Routing such a run back to an earlier stage cannot produce the artifact and never terminates.) If any is false, return to the stage that produces the missing piece: branch, hooks or allowlist to Stage 2 (on a resume, the hooks by re-merging them through Stage 2's step 5 **Hooks** bullet alone, as "A hooks reason is fixed in place" below says); a genuinely missing atdd-checklist to **Stage 3** (define-done, the only stage that generates it; Stage 2 cannot). Two legitimate ways a story reaches this stage checklist-less, neither of which is a bounce: a **decomposed child row** (created after Stage 3 ran: run `bmad-testarch-atdd` scoped to that story right after its step 0 (next paragraph), or hand-establish its red phase at step 1 where ATDD cannot run) and the **non-web stack** above. Record which case it was, and what replaced the checklist, in `.decision-log.md`.
**A decomposed child's ATDD run** (the precondition's case above) follows `references/define-done.md` step 2's rule for a decomposed child: under the child's own key, so the checklist the commit guard reads is the child's; the parent's story file read for the text of the parent ACs the child claims, never edited; and, on a halt over vague criteria, an escalation, never a `ucg-create-story` run for the child. The run is the child's own work: it comes after the child's step 0 (story loop, below) has written both the `.current-story` pointer and the child's baseline marker, and before step 1, so the Stop hook books its turns to the child. Step 0 is never split around it, pointer first and baseline after: the run commits nothing and leaves `HEAD` where it was, so the baseline step 0 records is the one the child starts from either way. Sizing still comes first ("Sizing: a story too large to drive" sizes the row ahead of step 0), so a child that is split again gets no run. In production, on a stack ATDD can run on, a resume that finds the child's `.baseline-<story_id>` still owes the run, before step 1, when `atdd-checklist-<child key>.md` is absent or a `generatedTestFiles` path it lists does not exist: an interrupted run can leave either.
**On resume, re-enter Execute at the first story whose last logged gate verdict is not advance; advanced stories are not re-run; re-assert (do not rebuild) the Epic branch, hooks, the allowlist, the `.mem-state.json` recall latch, and the in-flight story's baseline marker before continuing**, and read the story's recorded turn count before driving it ("Authoring the `/goal` condition" below says when a resumed count escalates instead). Before the next story's step 0, also check whether the last advanced story's gate evidence is still uncommitted, and if it is, make that evidence commit first, exactly as `references/gate.md`'s "Commit the gate's evidence before the next story starts" describes (and when that story advanced with its count at or past the turn ceiling and no sizing note was logged, log it now, per "Promoting the turn-budget marker"): a resume enters here, before Stage 5 is ever loaded, so this is where that rule has to be met. That story carries an `evidence-commit-rejected` escalation when a repo commit hook rejected that commit in a way the gate may not answer, so run the `--assert-armed` call below with `--story` naming that story first: while its `escalation` reads `open`, make no commit and take the `decision-pending` route below for that story, and once `/ucg-resolve` has closed it (its sidecar is gone, and `.evidence-owed-<story_id>` is still on disk), make the commit and remove that marker. Check every `.evidence-owed-<story_id>` of this Epic's stories this way, not only the last advanced story's: a marker whose evidence was committed some other way is removed as `references/gate.md` says, with no commit. When that story is the Epic's last, so every story reads `done`, no story is left to drive: after the commit go to Stage 6 (`references/finalize.md`) with the Epic-level verdict the log holds, and run neither a story nor the Epic-level gate again. Stage 1 resolved no in-scope story for that resume, so Finalize passes that story as its one `--story` to `scripts/gate_trail.py`, whose range then ends at the commit this resume made, and the run report names the route as the owed evidence commit made and the Epic complete. Before the next story's step 0, or before Stage 6 on that route, remove `.scratch-<story_id>/` of each story of this Epic whose row is already `done` (`references/gate.md`, "Commit the gate's evidence before the next story starts"): a run that stopped after that story's evidence commit, or with nothing staged for it, left the folder there. And "re-assert the hooks" means preflight step 5's assertion, not a presence check: both script paths appear in the resolved settings **and** the PreToolUse group's matcher is the all-tools form (`references/preflight.md`, "Arm the PreToolUse group with a matcher that covers EVERY tool"). A presence-only read passes on a prior run's `Bash`-only arming, and a resume that skips Stage 2 never meets the bullet where that requirement lives, so this is the one place it binds a resumed run, and without it the Cross-Session Recall invariant enforces nothing outside Bash for the whole session while every log line says the hooks are armed. The latch is *re-written* by re-running Stage 1's latch step (`references/ingest-and-scope.md`, its `mem_recall.py latch` command) with this invocation's own run id, minted first by Stage 1's convention and logged. A resume never reuses an id an earlier invocation logged: the run's record file is named after it and never rewritten, so a reused id turns this run's Finalize write into `skipped-existing` and loses its record. It is re-written because every terminal removes it with `mem_recall.py unlatch` (Stage 6 at every close-out), and the PreToolUse hook reads an absent latch as "no run active" and stops gating recall entirely. A latch already on disk whose `run_id` is not this run's is **another run's (or a spawning wrapper's) artifact, never evidence**: re-latch from this run's own measurement, which replaces it, and never inherit its `store_ok` colour, because an inherited green latch certifies a store this run never checked. Never delete that latch to make room for this run's: the guard refuses it while a latch is present, and the latch command is what replaces it. The baseline marker is the opposite of the latch, split by which case the resume is, and the test is simply whether `.baseline-<story_id>` exists. **Mid-story (it exists):** *re-read* and never regenerate: the story may already carry commits, and a rebuilt baseline silently re-anchors its evidence range to a mid-story HEAD. **Story boundary (it does not exist**, the NORMAL case under `--max-stories N`, where every invocation after the first resumes at a fresh story): there is nothing to re-read; write it fresh at `HEAD` exactly as step 0 does for a first-run story, because the PreToolUse marker-freshness gate fail-closes without it.
**The cursor passes over a decomposed parent.** A story whose row is `done` and whose split is recorded (its split record (`.split-<key>.json` beside `sprint-status.yaml`) names it, a child row cites the parent ACs it claims, or `.decision-log.md` names it and the ACs each child claims) never gets a gate verdict of its own: its children carry its contract, and on its split record the Epic-level roll-up reads their gates in its place (`references/gate.md`). So it is never "a story whose last logged gate verdict is not advance" in the sense above: pass over it and re-enter at the next story, and never drive it. This is the shape a sizing decomposition leaves (below): the invocation that split the row ends without a verdict, the next one re-enters at the first child, since the child rows sit above the parent's, and once every child has advanced the cursor reaches the parent's row and passes over it. A `done` row with no recorded split is not passed over on this rule; Stage 1 rule 3's `skipped-already-done` log is what keeps a fresh run from re-driving one.
**A resume owes the stall check first.** Before the re-assertions below, apply the per-step heartbeat's gap rule (the "Run-status heartbeat" section): when the in-flight story's `.heartbeat-<story_id>` exists and its last line is older than 30 minutes, write the `.stall-<story_id>` line before driving anything — the resume is the only reader positioned to see the gap while its cause is still nearby.
**The re-assertion sweep is one script call, not a tool action per fact.** Run `uv run {skill-root}/scripts/preflight_check.py --assert-armed --project-root {project-root} --impl-artifacts {workflow.implementation_artifacts} --epic-branch-prefix {workflow.epic_branch_prefix} --story <the story about to be driven> --run-id <this run's id> --trace-output {workflow.trace_output_dir}` (plus one `--protected-branch <name>` per protected branch, as Stage 2's step 1 passes them: the prefix and the protected list are resolved scalars, and omitting either would assert the branch against a default the operator may have overridden). Exit 0 asserts the branch, both hooks with the all-tools matcher and the guard item's `"onFailure": "block"`, each UCG hook command split by the shell into its injected values, `uv run` and its script, the five injected hook env vars, and that `ucg-create-story` and `ucg-dev-story` are still installed (a manual deletion, or a UCG install or update interrupted between removing the UCG skills and copying them back, between spawns, can leave a run without them), and that `claude --version` gives no version below 2.1.295, the release from which Claude Code honors the guard's `onFailure` (a version it cannot read is reported in `checks.cc_version` and fails nothing), in one read, and the `story` block returns the artifact-derived route this paragraph defines: `decision-pending` (the next paragraph), `story-boundary`, `mid-story`, or `gate-owed` (the committed-green-un-gated third case below, or the re-gate a closed `operator-evidence-owed` escalation owes, the fourth case after it; for the third case the script only ever returns it when `--trace-output` named the run's real, readable trace dir and the artifact evidence held in full, while an unverifiable location reads `unknown` and routes to the ordinary loop, so lack of evidence never skips steps 1 through 4). Three things the manifest deliberately does **not** cover: the latch is **reported, never certified** (whatever the JSON shows, re-latch from this run's own measurement exactly as above); a boundary story's fresh baseline is still written by step 0; and the **allowlist** is neither asserted nor reported (it lives in permission settings the script does not read), so re-assert it exactly as the list at the top of this paragraph requires. A non-zero exit is the resume's RED: fix what the `reasons` name before continuing, and never narrate around it. A fix that writes `.claude/settings.local.json` (a hook, its env, the allowlist) follows `references/preflight.md`'s "A refused settings write" rule if the write, or a call after it, is refused: stop, never work around it, and in headless take the escalation route below for the story about to be driven, naming the refused write. Two reasons are the operator's to fix, never a resume's. One is a skills failure (`checks.skills.ok: false`): installing UCG's story skills is the operator's call, so do not run the installer command that reason names, do not substitute another skill (`bmad-build`, `bmad-build-auto`, or BMAD's deprecated `bmad-create-story` and `bmad-dev-story`), and do not hand-author the story or the code. The other is a Claude Code below the minimum (`checks.cc_version.ok: false`): updating it is the operator's call too, and this session keeps the version it started with, so do not run `claude update`. For either, or both, take the sub-skill halt catch-all's route (below) for the story about to be driven: write `escalation-<story_id>.json` with `decision_needed` quoting each such reason the `reasons` name, then stop. When one stands beside other reasons, a hooks reason included, take this route first and fix none of the others: the run stops on the operator's reason either way, and a hooks re-merge writes a protected file that a headless session may be refused. The resume after the operator's fix meets the others again and fixes them then.
**A hooks reason is fixed in place, not by a return to Stage 2.** When the `reasons` name the hooks (a hook not armed, a matcher that is not the all-tools form, the guard not armed with `"onFailure": "block"`, a hook command the shell would not split as written, or injected env that is missing) and no reason that is the operator's to fix stands beside them (the paragraph above escalates that one first), apply `references/preflight.md` step 5's **Hooks** bullet alone, exactly as written there: re-merge both hooks into `.claude/settings.local.json` with this invocation's resolved scalars, first removing every inner item whose `command` names either script (replace, never append), and keep the allowlist entries the file already holds. A guard item without `"onFailure": "block"` is the one every run armed by UCG 3.x or earlier carries, so the first resume after an update meets this reason and re-arms here, unless a reason that is the operator's to fix (a skills failure, or a Claude Code below the minimum) stands beside it: the paragraph above takes the escalation route first, and the resume after the operator's fix re-arms here. Purge nothing: step 5's marker purge and its `.current-story` delete belong to an arming, and the turn counters this resume inherits are ones it must keep. Run none of preflight's checks, remediation or launch gate, and rebuild nothing else: the branch, the latch and the baseline marker keep the rules above. Then run the same `--assert-armed` call again, and drive the story only once it exits 0. A write that is refused takes the route the paragraph above gives (stop; headless, escalate for the story about to be driven, naming the write), so a drive by `scripts/drive_epic.py`, whose spawns run headless, stops at that spawn until an attended resume makes the write and `/ucg-resolve` closes that escalation, which the resume offers before it drives the story (the decision-pending paragraph below).
**A re-entry story with an open escalation is not re-entered.** The `story` block also reports `escalation`: `null` when no `escalation-<story_id>.json` exists, and otherwise its `state`. It reads `open` when the sidecar is on disk and the id `/ucg-resolve` keys its answer by (`red_ids.py`'s, minted from the sidecar's own `kind`, `source` and `decision_needed`; a close keyed by the sidecar file's own path, as earlier passes keyed some, counts too) is not closed in `.decisions.json`, or when the sidecar cannot be read or no id can be minted from its fields, and the route is then `decision-pending`, ahead of the other three. `/ucg-resolve` deletes the sidecar when it closes the decision and leaves it in place on a `defer`, so a sidecar still on disk is a decision nobody closed: an answer written anywhere else (the story file, a ruling, the ledger) has not closed it. On `decision-pending`, do not drive or gate the story and write no sidecar: the open one is the record, and the skills, Claude Code version, refused-write and turn-ceiling routes in this file each write `escalation-<story_id>.json` and would overwrite it. Attended, show the sidecar's `kind` and `decision_needed`, offer `/ucg-resolve`, and continue only once a fresh `--assert-armed` call no longer reads `decision-pending`. Headless, or when the operator leaves it open, end the invocation `blocked` as `references/gate.md`'s `escalate` does, handing the block's `escalation.blocker` to the headless adapter as the one blocker, so the envelope's `reason` names the sidecar. Two states never set the route: `handoff`, a `story-decomposed` or `defined-not-driven` sidecar, which hands this invocation work to pick up rather than a decision (an `operator-evidence-owed` sidecar is not one of them: `scripts/drive_epic.py` reports it as a handoff, but re-driving the story cannot record the evidence an operator owes, so it routes `decision-pending` until `/ucg-resolve` closes it); and `closed`, a sidecar whose id `/ucg-resolve` already closed, the residue of an answered decision that `/ucg-resolve` would not offer again.
**A third case: a story already committed, green and un-gated.** The routing above sorts stories into two classes — re-drive, and do not re-run — and a session that died between its commit and its gate belongs to neither. Recognise it by artifacts, never by prose: the row carries commits past its baseline marker **and** a `.tests-ran-<story_id>` marker whose `baseline=` line still matches that marker, **and** neither `trace-<story_id>.md` nor `gate-decision-<story_id>.json` exists under `{workflow.trace_output_dir}`. That story owes **evidence and a gate, not implementation**. Re-set the `.current-story` pointer (the pointer half of step 0 only — the baseline marker is still re-read, never rewritten), skip steps 1 through 4, and enter at **step 5**, re-measuring the committed HEAD rather than reading the tests-ran marker's numbers back — at FULL scope, since no step 2 ran this session to inherit from — and once green, rewrite the tests-ran marker fresh (same `baseline=` line, `scope=full`) **even on a green first try**: the inherited marker may predate the scope contract or carry a mid-loop `scope=scoped`, and the gate reads the marker THIS session leaves behind, not the dead one's; then continue into Stage 5 as normal. Trust the artifacts and the `sprint-status.yaml` row, never the story file's own prose: such a file routinely carries a close-out asserting a gate `PASS` that no artifact backs, which is precisely the claim this stage does not get to make. **The discriminator must hold in full.** A tests-ran marker with no commits, or commits with no marker, is a story that died before or during the sweep, and it takes the ordinary loop from step 0.
**A fourth case: a closed `operator-evidence-owed` story owes a re-gate, not a re-drive.** Its FAIL gate left `trace-<story_id>.md` and `gate-decision-<story_id>.json` on disk, so the third case never fires for it. When `/ucg-resolve` closes that escalation, it deletes the sidecar, resets the story's turn counter (waiting for operator evidence is not the story's work) and writes `{workflow.implementation_artifacts}/.regate-<story_id>`, holding `sha=` the assessed commit and `decision=` the closed id. The `story` block reports that marker as `regate`: `null` when there is none, otherwise its `state`. While it reads `fresh` (its `sha=` resolves to `HEAD`) and the baseline marker exists, the route is `gate-owed`: enter exactly as the third case does, re-setting the pointer, skipping step 0's turn-ceiling read and steps 1 through 4, re-measuring `HEAD` at step 5 with any runner or harness the escalated cycle built in `.scratch-<story_id>/` (step 0 keeps that directory until the story advances), then re-gating it in Stage 5, whose trace counts the operator's records and, for a story with a `{workflow.implementation_artifacts}/.moved-<story_id>` record, reads the main tree's story file and the sources that record lists, and whose check that trace scored no moved AC runs before `gate_eval.py` (`references/gate.md`, "After a move, check that trace scored no moved AC"). When that directory is gone (a run under an earlier rule removed it at step 5, or an operator did), re-author any runner or harness the story's declared gate set needs before step 5 runs. Check it against the gates the escalated cycle's step-5 capture in `evidence-<story_id>/` names, when that folder holds one, so the re-gate measures the gate set that cycle measured. Commit nothing before that gate while step 5's re-measure is green, since a commit past the assessed commit makes the records stale. On a red, take step 5's red route (remediate, write a fresh `.tests-ran-<story_id>` marker, re-commit): that commit moves `HEAD` past the assessed commit, so the records no longer count and the `.regate-<story_id>` marker is stale, and the re-gate at the new `HEAD` escalates `operator-evidence-owed` again at the new commit. A `stale` marker (one naming another commit, or no commit id) routes as if it were absent, normally `mid-story`: a later commit already made the records stale. On either route the gate deletes the marker once this story's verdict is logged (`references/gate.md`, "A logged verdict settles an owed re-gate").
**A fifth case: a gate stopped between automate and trace.** `preflight_check.py` reads no log, so its `story` block cannot see this case and reads such a story as `gate-owed` or `mid-story`; take this case instead of either, but never instead of `decision-pending`. It takes three forms, each read from the story's `.decision-log.md`:
- **A backfill with no verdict after it.** `references/gate.md`'s "When automate backfills" logs `gate-backfill-base:` once automate has finished with a backfill, and `gate-backfill:` once that backfill is committed. When the log holds either line with no verdict logged after it (when it holds both, the later one decides), the story owes the rest of that gate cycle: not a re-drive, and not a second automate pass. Re-set the `.current-story` pointer (the pointer half of step 0 only), skip step 0's turn-ceiling read and steps 1 through 5, and enter Stage 5 at gate.md's "A resume after a backfill does not run automate again", which says at which `HEAD` the case holds and sends a story at any other `HEAD` back to the route the script reports.
- **A re-loop that ended its cycle before trace.** gate.md's "A red backfill sweep ends the cycle at a re-loop" logs a `reloop` verdict whose JSON holds no `gate_status`, since no trace ran, beside an `assessed-commit:` line. When that is the story's last logged verdict and `HEAD` is still the commit its `assessed-commit:` line names, the re-loop has committed nothing yet, and the story owes that re-loop, not a gate: re-set the `.current-story` pointer (the pointer half of step 0 only), then resume gate.md's `reloop` route where the log stopped, its turn-ceiling check included (the generalize step when this re-loop's `class:` lines are not logged yet, then `bmad-correct-course`, then the story's re-run through the story loop below).
- **An automate pass with no verdict after it.** gate.md's "A summary already at that name is this cycle's own" logs `gate-automate: <sha>` right before it delegates automate, naming the commit automate measures. When the log holds a `gate-automate:` line with no verdict and no `gate-backfill-base:` or `gate-backfill:` line logged after it (a backfill line after it means the first form applies instead), and that line names the commit `git rev-parse HEAD` prints, the session ended while automate ran, or after it finished but before anything was committed, and the story owes the rest of that gate cycle, not a re-drive. Re-set the `.current-story` pointer (the pointer half of step 0 only), skip step 0's turn-ceiling read and steps 1 through 5, and enter Stage 5 at gate.md's "Backfill the gate evidence", whose paragraph "A summary already at that name is this cycle's own", read before automate is delegated, reuses the pass's summary when it is complete and runs automate again only when the summary is unfinished or absent. When that line names any other commit, the story is not in this form: take the route the script reports.
## Default — Sequential `/goal` spine
### Sizing: a story too large to drive
**Before step 0 writes any marker, size the row.** Count its acceptance criteria and tasks. **Take that set from the ROW, not from a neighbour's prose.** The `sprint-status.yaml` row is the authority on *which* acceptance criteria a story owes; the story file it cites (its own, or the parent it was split from) is only where those criteria's text lives. A decomposed child has no story file of its own by the convention below, so its contract exists solely as the criteria its row cites. A sibling's ledger entry, or a decision-log entry, names what that sibling **handed off** (a different set, with no reason to be complete), and a scope read from one undersizes the row here and under-delivers it at step 1. Nothing downstream catches that: the trace, the gate-decision file and the gate verdict are all written from this same reading, so they come out green over a missing criterion by construction. When the count is implausible against `{workflow.max_turns_per_story}`, **do not start the story**: decompose it into child rows and terminate the invocation. "Implausible" has a first-pass test, not just a judgment: **when the row's acceptance-criteria count reaches roughly half of `{workflow.max_turns_per_story}`, treat the row as implausible** (13 criteria at the default 25). Count the tasks too, as evidence for the tie-break and the override, but keep them out of the threshold: a task list is how its author sliced the work, and it also holds steps every row pays (reading the skills, running the gates, a step the operator owns). Criteria plus tasks flagged 25 of one real Epic's 30 rows and 4 of another's 5, and nearly every flagged row was then driven whole. The threshold sizes what the story owes; it is not a forecast of turns. The Stop hook counts one turn per response ("Waiting spends turns" below), so the turns a story spends follow how its drive waits, not how many criteria it closes: drives that ran each stage as one delegated workflow took rows of 9 and 13 criteria to their gates in 6 and 7 turns, a 3-criterion row whose sweeps and suite runs each cost turns passed the ceiling twice over, and a `scripts/drive_epic.py` spawn is usually one long response per story. Tie-break against this Epic's own record: the criteria counts of rows already driven cleanly versus rows already split; a row matching an already-split parent's shape is answered by that precedent. The tie-break reads no turn counts. The turns a row spends follow how its drive waits, as above, and no record holds the turns a driven row used: `/ucg-resolve` resets or deletes its `.budget-<story_id>.json` when it closes a `budget-overrun` or `operator-evidence-owed` escalation, and the Stop hook adds each response of a later session to the story `.current-story` still names, so that file, and a count logged from it beside a gate verdict, can hold fewer turns than the row used or more. The judgment word stays as the override in both directions (a count under the threshold can still be implausible when each AC owes an executed artifact; over it can be plausible when the ACs are one-line checklist items), but an override is a recorded reason in `.decision-log.md`, never the whole method: two conductors meeting the same row must be able to reach the same verdict.
Nothing else in this stage covers that case, and the two routes it seems to offer are both wrong. Driving it reaches the turn bound with a baseline marker and a tests-ran marker on disk and no commit, which is exactly the abandoned-mid-story outcome the work bound below exists to avoid. Escalating reaches the same conclusion having first spent the whole budget proving what an AC count showed in five minutes. **A decomposition writes no baseline and no tests-ran marker at all**, so the abandoned-story shape cannot arise from it.
**Decomposition is a legitimate terminal for an invocation**, not a failure and not a fallback. One Epic took this path seven times and re-derived the reasoning from scratch each time, because nothing here stated it.
Three conventions, and they are **properties of `scripts/drive_epic.py`** rather than taste:
- **Insert the child rows BEFORE the parent row in `sprint-status.yaml`.** The driver takes `pending[0]`, the first not-`done` row in FILE order, not the first by status. Children appended *after* the umbrella leave the driver watching a row no session will ever advance: the spawned session correctly drives the first child, the driver re-reads the parent, finds it unmoved, and halts with `no-progress` on its first lap. The readiness check reads the same order: to it, a fileless child row below its `done` parent's row is a story of its own, so the next run whose preflight runs reports it uncovered (a resume that goes straight to Execute does not run preflight).
- **Set the parent row to `done` once its children exist.** Same mechanism, one lap later: a parent left not-`done` sits ahead of nothing once the children are consumed, but it is still a not-`done` row the driver will select and no session will advance. The parent is now a container, and its contract lives in the child rows that cite it.
- **Do not edit the parent story file.** Each child row cites it by AC number. Editing it to match the split creates a second copy of the contract, and then two artifacts disagree about what the story owes.
Record the split in `.decision-log.md`: the parent, the children in order, and which parent ACs each child claims. **Check that mapping mechanically with `scripts/story_sizing.py`** — every parent AC claimed exactly once — never by eye and never with a parser written for the occasion. One improvised for this on a real run produced two false double-claims by matching the `1` inside `REQ-1`; the script compares whole ids, so `AC-1`, `REQ-1` and `1` are three ids and no substring makes them one:
```
uv run {skill-root}/scripts/story_sizing.py --parent '<the parent row's key>' --record {workflow.implementation_artifacts} --parent-acs '<the parent row's ACs>' --child '<child-row-id>=<ACs it claims>' --child '…' --tasks <n> --turn-ceiling {workflow.max_turns_per_story}
```
It exits 0 when the map reconciles and 1 when it does not, printing `unclaimed`, `double_claimed` and `unknown_claims` (an AC no parent row owns) either way, and **a non-zero exit means the split is wrong and must be fixed before the child rows are written**, not a warning to log past. Before the split, call it with no `--child`, `--parent` or `--record`: `uv run {skill-root}/scripts/story_sizing.py --parent-acs '<the row's ACs>' --tasks <n> --turn-ceiling {workflow.max_turns_per_story}`. A `--record` with no `--child` is a usage error (exit 2), since a record needs children. That call does the sizing half only, returning `ratio` (the criteria count over the ceiling) and `implausible` against the same threshold this section states, and it says `reconciled: false` rather than reporting a clean claim map it never checked. The judgment stays here: `implausible` is an override in both directions with a recorded reason, and which child owns which AC is an authoring decision the script never makes.
**The reconciling run records the split.** With `--parent` and `--record`, a run that exits 0 also writes `.split-<the parent row's key>.json` into the directory `--record` names: the parent, its children in the order given, and the claim map. It is the only evidence of the split the Epic-level `--rollup` reads, which reads the parent through its children's gates on it and refuses the parent without it (`references/gate.md`), so the record goes beside the `sprint-status.yaml` the Epic gate is given: `{workflow.implementation_artifacts}`, or on a flag-only isolated track (`references/ingest-and-scope.md` rule 6) the isolated track's own directory. Pass the sprint-status keys byte for byte, the parent's and each child's, once each, with the children in the order their rows take. A failing run writes no record and leaves an earlier one as it was. Exit 2 is a usage error with no record written: a `--child` row given twice, a record asked for with no `--parent-acs` or a child that claims none, a parent that is also a child, a missing directory, or a record the script cannot write. The sizing call before the split leaves both flags off, since a record needs children. A parent split before the record existed gets one the same way: one reconciling run for that split, with both flags.
Then terminate as the work-bound section below describes for an invocation that advanced no row. The Stage 6 gate trail still covers the in-scope set **as resolved at Stage 1** — the parent's id, never the just-created children: they were resolved by no Stage 1 and driven by nothing here, so they belong to the next invocation's trail (`references/finalize.md`, Gate trail).
### The story loop
For each in-scope story, in sprint order, run this loop (leave out a decomposed parent: one preflight step 2 set `done` as a container, or a `done` row whose split is recorded, as the resume cursor above passes over):
0. **Set the current story and record its baseline commit**: both **before any implementation**, before step 1 touches a single file. (First read the story's recorded turn count, per "Authoring the `/goal` condition" below: a resumed story already at or over the ceiling escalates instead.) First, so the PreToolUse hook can locate this story's marker: write the story id to `{workflow.implementation_artifacts}/.current-story`. Both hooks read the story id from `ULTRACODE_STORY_ID` when their own environment carries it, falling back to that `.current-story` file, and an `export` inside a Bash call never reaches their processes, so the file is the route that works. Skip the write and both hooks keep reading whatever the file last named: no story at all after preflight's purge, so the guard denies every commit and the Stop hook counts nothing, or the previous story, whose markers and counter then stand in for this one's. Then anchor the story: **if `{workflow.implementation_artifacts}/.baseline-<story_id>` is absent, write it now** with the output of `git rev-parse HEAD`: **exactly one newline-terminated line carrying the full 40-hex SHA**. This format is a contract, not a style choice: later stages bound this story's commit range from it and compare it as a verbatim whitespace-stripped string, so a `git rev-parse --short` abbreviation or a write with no trailing newline is a silent breakage, not a cosmetic one. **If the marker is already present, this story is a resume: read it and keep it, never overwrite it.** No later step refreshes it; a multi-commit story must keep the SHA it started from even after HEAD moves. **Scratch build space, if the story needs any.** A story that must build and run a throwaway program to produce a committed artifact puts it in `{workflow.implementation_artifacts}/.scratch-<story_id>/` and nowhere else. Not an improvised repo-root directory: that is one careless `git add` away from being committed, and only step 4's explicit per-path staging would catch it. Not `/tmp` either: it survives no audit, belongs to no run, and buys nothing the run folder does not. What this location buys is containment: the dot prefix and the run folder keep it out of every default source glob and out of the commit. What it does **not** buy is runnability: a headless permission layer gates on command **shape**, not path, so a compound `bash <scratch>/script.sh 2>&1 | tee …`, a `for` loop over gate names, or a `$(…)` substitution can each be refused wherever the file sits. Keep scratch work invocable as one simple command per call, and expect to run its steps as separate calls rather than through one orchestrating script. The directory outlives the step-4 commit and step 5 **deliberately**: step 5 re-runs the same declared-gate sweep on the committed tree, and the gate's backfill sweep, a cap-only re-loop's sweep and the step 5 a resume enters at (the third and fourth cases above) run it again without re-driving the story, so a runner or harness built here is still needed there, and one lost before then gets re-authored by hand, a real, measured cost that risks measuring a different gate set. **Remove the directory on the gate's advance route, once its evidence commit is made, its `evidence-commit-rejected` escalation is written, or nothing is staged for it** (`references/gate.md`, "Commit the gate's evidence before the next story starts"), never earlier, and never later: the next story's step 0 must not find it. A `reloop` or `escalate` verdict leaves it in place, since the story still owes a cycle or a re-gate that runs the sweep again.
**Evidence never goes in scratch.** The scratch directory is removed when the story advances, while the story record and the gate trail (`references/finalize.md`) cite their evidence after that, so the story's evidence has a folder of its own, `{workflow.implementation_artifacts}/evidence-<story_id>/`, which no step removes. The red-phase capture (step 1's, on a stack where Stage 3 could not generate the ATDD scaffold), a sweep log the record or the gate cites, a coupled-stories measurement and a planted-defect run (a case shown red against a defect planted for it) go there; a runner or harness built only to produce them stays in scratch. It holds captured output and the notes recorded on it (the red count `references/gate.md`'s non-web item 4 records beside a red-phase capture), nothing runnable: it has no dot prefix, so on a tracked tree a repo-wide tool can reach it. The mutation ledger keeps its own name-pinned path (step 2). Name each capture by the step that wrote it and the commit `HEAD` named when it ran (`sweep-step2-<short sha>.log`, `sweep-step5-<short sha>.log`, `sweep-backfill-<short sha>.log`), and give a name already taken the next free number (`-2`), so no capture overwrites another: step 2's sweep can run at the `HEAD` the cycle before it measured at step 5 (when that cycle's gate committed no backfill), and the backfill's sweep runs at the `HEAD` step 5 measured. A file already in the folder when step 0 writes a fresh baseline is an earlier run's, never cited as this run's. On a tracked artifact tree the folder stays untracked, as the mutation ledger does: the gate's evidence commit stages its own list of paths, and this folder is not on it.
1. `ucg-create-story` (if not already current) → `ucg-dev-story` implementing the feature and **un-skipping** the story's ATDD acceptance tests (remove `test.skip()`; **production only**): under `--light` there are no ATDD tests to un-skip, so the DoD is the story's acceptance criteria satisfied with lint and build green. The commit guard reads the story's acceptance-test files from the checklist's `generatedTestFiles` frontmatter, so a test file the story adds to hold acceptance cases (a scaffolded file split in two, say) goes into that list as a repo-relative path. **For a decomposed child row, skip `ucg-create-story` entirely**: the child has no story file and must never get one (running the sub-skill would duplicate the contract, which the sizing conventions above forbid); its owed criteria are its sprint-status row comment plus the parent story file it cites by AC number, and the parent file is read for the AC text only, with its Dev Notes as guidance. Pass both story skills `implementation_artifacts` set to `{workflow.implementation_artifacts}` on every call, so the story file and the sprint-status row they touch are the ones this run reads. Hand `ucg-dev-story` the child's input in place of a story path: `story_key` the child's row key, `parent_story_path` the parent's story file, and `claimed_acs` the parent AC ids the child's row claims, taken from the row as the sizing section above requires. On a re-loop, also hand it `review_findings`: the `reasons` of the gate verdict that sent the child back and the findings of that cycle's reviews, which no review can write into a story file the child does not have. Its "Decomposed Child" section keeps it to those ACs, has it write no story file, and has it move only the child's row (to `in-progress`, then `review`), so the parent's row stays `done` and the parent's file unedited. A halt there over a claimed AC takes the sub-skill halt catch-all's route below, naming the parent ACs concerned: never a `ucg-create-story` run for the child, and never an edit to the parent's file. **On a stack where Stage 3 could not generate the ATDD scaffold** (the non-web case), the story still owes a red phase and it is owed **now, before the first implementation edit**: author the acceptance cases with real assertions, RUN them, and capture that run's raw output to a file in `{workflow.implementation_artifacts}/evidence-<story_id>/` ("Evidence never goes in scratch", above). `references/gate.md`'s non-web section is the authority on the shape, but by the time that file is read at Stage 5 the window this rule governs has already closed. Before delegating, check the run's `.decision-log.md` for an **Operator notes** entry naming this story (a pre-launch hint like "watch the auth flow in story 3") and surface that note into the `ucg-dev-story` / review context for this story so the operator's last words actually reach the work. Read `{workflow.implementation_artifacts}/.class-ledger-<epic_id>.md` the same way when it exists (the defect classes this Epic's reviews have already caught, appended by the gate's re-loop route, `references/gate.md`) and surface it into the same context: a class named there is a class the reviewers will look for again, and code written blind to it is a re-loop pre-booked. (A story otherwise inherits nothing from its siblings' reviews: a measured run re-found the previous story's review finding on its very first cycle, so the ledger is the one artifact that crosses that boundary.)
**On a gitignored artifact tree** (`impl_artifacts_tracked: false`, which preflight step 1 reports and a resumed session reads in its `--assert-armed` manifest's `checks`), no test this story writes or un-skips may read a file under that tree, or any other path `git check-ignore` reports, at run time: it does not exist in CI. Point the test at a tracked fixture instead. Preflight step 2 states the rule ("A gitignored artifact tree"); a session that resumed straight into this stage may not have read it.
**An operator-evidence AC is not `ucg-dev-story`'s to satisfy.** When the story carries an AC tagged `**Gate-ability:** operator-evidence` (`references/define-done.md`, step 1), say so when you hand it the story: that AC is proven at the gate by a live result a person records (`references/gate.md`), so it builds nothing for it and does not hold the story's completion on it. An AC tagged plain `**Gate-ability:** operator` is not one: it is work `ucg-dev-story` builds like any other AC, which a person or a script then verifies.
**Get an AC narrowed in writing before committing a case that pins behaviour it forbids.** A stated bound (a case asserting an outcome an AC rules out, because the story keeps that behaviour on purpose) leaves the AC PARTIAL in trace, which reads the AC as written, and no re-loop changes the AC. Narrowing it is the operator's decision, so escalate for it as the sub-skill halt catch-all below does, naming the AC, the behaviour and the narrowing you propose, and commit the case only once the story file states the narrowed AC.
**Two stories green only together: move the clauses in writing, never share a commit.** A plan can couple two in-scope stories so that the earlier story's commit cannot be green alone: the earlier story owes a clause only the later story's build can satisfy, and the later story often turns the earlier story's cases red without them, so no order helps. Step 5 advances a story only on its own green commit. Do not commit them together, leave the earlier story uncommitted, or gate both at one commit: the tests-ran marker, the range from `.baseline-<story_id>` to `.commit-<story_id>`, and the trace and gate decision are each one story's, and two stories gated at one commit share one range, so neither shows its own work (step 4's END sha). Driving the two rows as one unit is not a route this run takes either: only the operator re-plans rows, outside the run (one story in place of the two, or another order). The route is to move each such clause forward, to the later story, which must be an in-scope, not-`done` story of this Epic. That narrows the earlier story's AC, so it is the operator's decision, as the narrowing above is: never move a clause on your own ruling. As soon as the plan, a story file's notes, a red at step 2 or step 5, or a re-loop's findings show the coupling, and before the earlier story's next commit, capture for each clause a run on the earlier story's tree, to a file in the earlier story's `{workflow.implementation_artifacts}/evidence-<story_id>/` ("Evidence never goes in scratch", above), showing that the code it needs exists only in the later story's build. Only a clause so measured moves. The operator's ruling takes one of two forms. An **Operator notes** entry given before launch (`references/ingest-and-scope.md`, "Operator notes") that names both stories and authorizes moving clauses from the earlier story to the later one is that ruling for each measured clause it covers, so where a move fits that clause (below), apply the move without escalating and cite that note. A note that does not name both stories is not that ruling, and neither is a general or standing delegation (to rule on AC wording, say), wherever it is written. Otherwise escalate for the earlier story as the sub-skill halt catch-all below does, with `kind` `coupled-stories`, `source` the measurement file, and `decision_needed` naming both story keys, each clause, its measurement and the wording you propose for both story files (for two decomposed children, the changed claim map); when the later story is outside this run's scope, propose only a re-plan. Once `/ucg-resolve` has closed it, take the ruling from the entry it logs in `.decision-log.md`, which holds your proposal beside the operator's answer; a re-plan leaves you nothing to apply. What the move writes depends on the pair, and all of it lands before the earlier story's next commit. When both stories have a story file, write the ruling into both story files, each citing it: the earlier story's AC states what its own build measures and names the later story's AC that now owns each moved clause, and the later story gains each clause as an AC of its own, with its verification and anti-vacuous twin. Between two decomposed children of one parent, which have no story file, only a whole claimed AC moves, and only when each of its clauses is so measured, while the parent's story file stays unedited: a new reconciling run records the split with the changed claim map ("The reconciling run records the split", above), and the same pass rewrites the AC citation in both child rows' comments in `sprint-status.yaml`, which step 1 takes `claimed_acs` from and the trace is written from, and the AC numbers in both children's `atdd-checklist-<child key>.md` frontmatter (`references/define-done.md`), so no record of the split still gives the earlier child the AC it handed on. An AC the earlier child claims that also holds a clause no run so measured has no move to apply: that clause may not move, and the AC cannot move without it. Any other pair (a decomposed child beside a story that has a file, or children of two parents) has no move to apply either: a child owns only whole ACs of its own parent's story file, and nothing on the other side can claim one. No note can authorize a move where none fits. Escalate for the earlier story as above, proposing only a re-plan, as for a later story outside this run's scope. Move each clause's scaffolded cases with it, out of every file the earlier story's checklist lists in `generatedTestFiles` and into one the later story's checklist lists, since the commit guard reads a skipped case in a listed file as unfinished work. A later child split off after Stage 3 has no checklist yet, since its own ATDD run comes after its step 0 ("A decomposed child's ATDD run", above), so there is no frontmatter of its own to rewrite and no file it lists to take the cases. For such a child the move writes no checklist: it rewrites the AC numbers in the earlier child's checklist alone, and it removes each moved clause's cases from every file the earlier child's checklist lists, instead of moving them, parking no copy for the later child to take up. A listed file the removal leaves with no case comes off `generatedTestFiles` first and is then deleted, in the same pass: a test file with no case fails Jest and Vitest, and a listed path that does not exist reads to a resume as an interrupted ATDD run (above) and to the commit guard as a listed file it cannot read from the index. When that leaves `generatedTestFiles` naming no test file, the guard reads every test path the checklist's text names in its place, so each deleted file's path is also taken out of the checklist's text. The later child's ATDD run after its step 0 then scaffolds the moved AC from its rewritten row, as it does every AC the row cites; on a stack ATDD cannot run on, the later child's step 1 establishes the moved AC's red phase from its rewritten row instead, as for every AC the row cites. The earlier child's evidence folder keeps what it captured (the measurement, any red-phase capture), never edited or made again, and the move's log entry names each case it took out. Log the move under both stories in `.decision-log.md`, with the changed claim map for two children. Each gate then reads its own story's ACs as written: the earlier story's gate counts no moved clause as a gap, and the later story's gate measures each one, its automate pass included.
2. Run the tests, lint, and build, and **PRINT the raw output** (pass/fail counts, lint result, build result) into the transcript. **In a monorepo, scope that test run wide enough to catch cross-package regressions** — run the full suite, or the changed package(s) plus everything downstream of them (e.g. an `--affected` set *and its dependents*), not just this story's own package. A story's change can regress a *sibling* package's conformance gate (a cross-package RBAC, ownership, or architecture-boundary check), and a run scoped to only this story's package reports green while that sibling gate is red — deferring the red (and its fix) to a later story or the Epic gate instead of catching it at the story that caused it. This printed evidence is what keeps the run judgeable mid-flight, and what a `/goal` evaluator reads when the operator started one — but it is *evidence*, not the gate. **Once all three go green, write the tests-ran marker** `{workflow.implementation_artifacts}/.tests-ran-<story_id>` — the PreToolUse guard denies the step-4 commit unless this marker exists for the current story, so write it only after a real green run. **That marker must carry a `baseline=<sha>` line** whose value is the verbatim, whitespace-stripped content of `{workflow.implementation_artifacts}/.baseline-<story_id>` written at step 0 — **copied, never re-derived from `git rev-parse HEAD`** at marker-write time. The guard compares the two strings character for character and denies the commit when they differ or when the line is missing, which is what stops a marker written against an older code state from being replayed to satisfy a later commit. Re-deriving the value here instead of copying it is the trap: on a story that commits more than once, HEAD has already moved past the baseline, so a re-derived line denies the story's own second commit. **Write that marker with the Write tool**, after Reading the baseline file and pasting its line unchanged — for the same reason step 4 writes the decision log with Write/Edit. The obvious Bash form, `printf 'baseline=%s\n' "$(cat …/.baseline-<story_id>)" > …/.tests-ran-<story_id>`, is a command substitution that a harness which statically analyses Bash strings refuses outright (the PreToolUse guard permits it; the refusal comes from above). Hand-retyping the forty hex characters instead is precisely the transcription error the freshness clause exists to catch, and its denial says only that the SHAs differ, never that one was mistyped. **The marker carries the sweep's scope beside its baseline** — two more lines, same file: `scope=<full|scoped>` naming which sweep form this green run was (the re-loop rule below is the only thing that ever writes `scoped`; a first pass writes `scope=full`), and — scoped only — `packages=<the resolved package list>` copied from the runner's own printout, never hand-typed. The gate reads the `scope=` line through `gate_eval.py --tests-ran` and caps a scoped cycle's verdict at `reloop` (`references/gate.md`, the sweep-scope AND), which is what stops a scoped sweep from impersonating a full one at the only place the distinction pays.
**Mark this story's new files intent-to-add before every sweep this step runs.** A conformance gate scoped to *tracked* files (a `git ls-files`-based ref, ownership or architecture-boundary check) skips a file git does not track, so an unmarked new file first reaches it at step 5, after the commit, where its red costs an amend and two more full sweeps. Before each sweep, a re-loop's and a resumed session's included, read `git status --porcelain --untracked-files=all` and take this story's own files from its `??` entries: the source and test paths step 4 will stage, the acceptance tests this story's checklist lists among them. Mark them in one call of its own, `git add -N -- <those paths>`, naming each file by its path. Without `-z`, any name git prints inside double quotes is C-quoted (a space, a double quote, a backslash or a control character in it, and under git's default `core.quotePath` a non-ASCII byte, which it writes as an octal escape: `"my file.ts"`, `"caf\303\251.ts"`): pass it as the name it stands for, its escapes decoded and quoted for the shell, never as printed, which matches no file. Never name a folder (git marks every file under it), a sibling story's red-phase tests, anything under `.scratch-<story_id>/` or `evidence-<story_id>/`, a run marker, or a path git ignores. A mark puts the path in the index with no content (the index holds an empty blob for it): a gate that lists git's files now sees the file, nothing of it is staged, and step 4 still stages each one in full. Marking a path the index already holds changes nothing, so a re-loop or a resume runs this again safely. A non-zero exit can leave some paths marked and others not: git refuses an ignored path and marks the rest, and a path that matches no file makes git exit 128 and mark none of the paths in the call. After any non-zero exit, read `git status --porcelain --no-renames --untracked-files=all` again, where a marked file shows as ` A`, and mark again, in one more call, every chosen path still listed `??` that git did not refuse as ignored. When that call fails too, mark nothing more: log the paths left unmarked in `.decision-log.md` and sweep, since step 5 runs the tracked-file gates on the commit. A mark on a path `HEAD` already holds (status `DA`) is cleared by staging the file in place, `git add -- <path>`, since moving it aside would stage its deletion. A marked new file the story will not ship (a sibling story's test marked by mistake, a mark another session left) is moved aside into `{workflow.implementation_artifacts}/.scratch-<story_id>/`, untracked in the run's own folder, then `git add -- <path>` clears its entry, and the file is moved back, where it is untracked again. Delete such a file instead only when nothing needs it. The guard refuses any commit while the index holds a mark (step 4). A gate that fails on any uncommitted change (`git diff --exit-code`, say) reads a mark as one, as it reads an edit to a tracked file. Its red is the state before the commit, and does not count against the tests-ran marker this step writes once all three go green, only when its output names no path but those this story changes or marks: any other path in it (a stale generated file the story never touched, say) makes it a red. State in the printed evidence that the red was read that way. Step 5 runs that gate on the committed tree, where a red is a red.
**Scope the sweep on three axes, not one.** Package breadth above is the first; the other two are how a green sweep is most often blind:
- **Language.** An aggregate task runner only runs the tasks packages *declare* to it, so in a polyglot repo the wide run can report every task green while an entire language's suite was never invoked. Read the runner's executed-task list against the languages actually present: a Rust crate with no `test` task simply does not appear in a turbo task count, and "8 of 8 tasks passed" says nothing about it. Run each uncovered language's suite explicitly (`cargo test`, `go test ./...`, `pytest`) and print those results alongside. **A task count is not a coverage claim.**
- **The repo's DECLARED gate set, not its default task.** Enumerate the quality tasks the repo actually declares (its `package.json` scripts, the turbo/nx pipeline, the CI workflow's jobs) and name, in the printed evidence, every one the default task excludes. A `test:storybook` or a `test:coverage`/coverage-ratchet that is a *sibling* task rather than a dependency of `test` is invisible to `run test`, and can sit red across an entire Epic while every sweep prints green. Run the excluded ones too, or state explicitly which you are not running and why.
**Defeat the build cache at least once.** In a content-addressed task runner (turbo, nx, bazel) a cache hit is precisely the state in which a sibling package's gate is *not* re-executed, which is the cross-package regression this step exists to catch. Run the authoritative sweep cache-defeating (turbo's `--force`, nx's `--skip-nx-cache`, bazel's `--nocache_test_results`, or the package's own runner directly) and **state in the printed evidence whether the run was cached**: a task count that is entirely cached, returning in under a second, is the signature of a replay (turbo prints a `FULL TURBO` line for it), and a run that is green cached and red forced is indistinguishable from a green one in the transcript. **The same rule binds any harness the story itself drives through the task runner** (mutation, fault injection, a twin-verification loop), and there the replay is worse than a false green: an unchanged task hash replays the pre-mutation GREEN for every mutation, so every mutation "survives" with zero failing cases, which reads as a devastating vacuity finding about the suite rather than as a cache hit. A subject **outside** the filtered package's tree (a repo-root script, a shared config, a generated artifact) never changes that package's task hash at all, so filter-plus-mutate is the specific combination that always needs the cache defeated. A string-replacement harness additionally owes its anchors a uniqueness assertion before mutating: an anchor that occurs more than once mutates a different site than it reports, and a `KILLED` earned against the wrong layer is the same silent inversion from the other side. **The module ships that harness: use it instead of hand-rolling one into scratch space.** `uv run {skill-root}/scripts/mutate_check.py --table <rows.json>` drives a JSON table of `{file, anchor, replacement, command, expect_red}` rows (an empty `replacement` deletes the anchor, the plainest mutation of a guard clause; the other four keys must be non-blank) with the properties every hand-rolled version eventually lost, built in as refusals: a green-baseline precheck (a mutation over a red baseline proves nothing, exit 2), per-row anchor uniqueness (0 occurrences reported distinctly as the formatter-reflow signature), an ATTRIBUTABLE red (the expected case named in the output, extra reds surfaced), and a byte-identical restore verification. Its generated ledger leads with GREEN survivors, because each green is a finding (a guard that cannot fail), and exit 1 on any green, misattributed red, or unheld anchor makes the runner gate-able. **Every guard or assertion this story adds or changes appears as a table row with an attributable red BEFORE the gate runs**, and the generated ledger is a story artifact the reviewers read: write it with `--output {workflow.implementation_artifacts}/mutation-ledger-<story_id>.md`, name-pinned per story like every artifact a later stage resolves, never scratch space (scratch dies at story end, which is exactly how the harness kept getting re-rolled), and surface it into the step-3 test-review context in production, citing it in the story record either way. The cache rule above binds the table's `command` verbatim: the runner cannot defeat the task-runner cache for you. A repo may substitute its own runner only when it meets the same properties.
**A re-loop iteration may scope the sweep; the cycle that expects to advance owes the full one.** The first pass through this loop runs the full three-axis sweep above. A story re-entered from a `reloop` verdict may instead run the affected set — the changed package(s) *and their dependents*, computed against the story's last recorded commit (`{workflow.implementation_artifacts}/.commit-<story_id>`, the previous cycle's end marker): e.g. turbo's `--filter=...[<that sha>]`, still cache-defeated, still with raw output printed. Two obligations keep the scoped form honest. **Print the resolved package list** — the runner computes it; copy its own output into the transcript and the marker's `packages=` line, because a wrong baseline ref narrows coverage *silently*, and the printed list is the only place a narrowing shows. And **write the marker with `scope=scoped`**, so the record says which form ran — a scoped sweep reported as a full one is the same class of false claim reviews keep finding elsewhere. When the re-loop believes its findings are closed and the next gate should advance, run the full sweep and write `scope=full`: the gate refuses to advance a story off a `scope=scoped` marker (`references/gate.md`, the sweep-scope AND), so a scoped cycle that unexpectedly goes fully green costs one extra full-sweep cycle rather than producing an advance nothing re-proved. When in doubt, run it full — `scope=full` is never wrong, only slower. (Measured, on a seven-cycle story: the whole-repo cache-defeated sweep re-proved untouched packages seven times, roughly six of every eight sweep minutes; this split is that cost's fix, at no loss of gate authority. A repo whose runner cannot compute an affected set simply keeps running the full sweep — the scoped form is an optimisation, never an obligation.)
**A wide sweep is also a loaded machine.** Running every language's suite plus the declared gate set, cache-defeating, means suites share a host with concurrent native builds — and a case bounded by a wall-clock timeout can fail from contention alone (measured: a 180-second-bounded case took 197s beside a concurrent `cargo test` + clippy + type-check, and 93s alone). A timeout in a wide sweep is therefore not yet a red: re-run that package in isolation before treating it as one, and where the two can be sequenced, do not schedule a long native build beside a wall-clock-bounded suite.
**A red the story's changes do not explain is not yet a red either.** In any wide sweep this file or `references/gate.md` runs (this step's, step 5's, and each sweep the gate runs as step 5 runs it), a failing case that is not a timeout (the paragraph above rules a timeout) is not yet this story's red when all three of these hold: its test file appears in neither `git diff --name-only --no-renames <the sha in .baseline-<story_id>>` (which lists both sides of a rename) nor `git status --porcelain --untracked-files=all`; its captured failure names no path either command lists; and the output shows the failure's cause inside that test, such as a random value the test draws that hit a string it asserts is absent, or a date or clock boundary. A failure that shows state another test left behind (the order the cases ran in, a shared fixture, a leftover file or port) does not qualify, since this story's own tests can leave that state. For a case that qualifies, keep that sweep's capture, change nothing, and run the same sweep once more at the same tree and scope, cache-defeated, captured under the next free number ("Evidence never goes in scratch", above). Running the case alone does not answer it: a case can pass alone and fail in the sweep on state another test leaves behind. When that second sweep shows no red at all, it is the step's green: log a `flaky:` line in `.decision-log.md` naming the case, its file, the `HEAD` both sweeps ran at (at step 2 the story's changes are uncommitted: they sit on that `HEAD`, untouched between the two sweeps), the cause the output shows and both captures; append a row for the case to `{workflow.deferred_work_path}`, worded as a non-critical finding (`references/gate.md`, "Deferred-work ledger schema"), with `source` `sweep`, `severity` `med`, `story` this story's id, a `reason` naming the case, its file and both captures, a `suggested_action` to fix the test outside this Epic's stories, and `status` `open`; and edit, skip or retry-wrap nothing in that file, which is not this story's to change. Step 2 then writes its marker from that second sweep, and a gate step that writes one after its sweep by its own rule (`references/gate.md`: the backfill's step 3 once its sweep is green, a cap-only re-loop's `scope=full` refresh) writes it from that second sweep too. At step 5 nothing has changed, so commit nothing (the guard refuses a commit whose staged index is empty): the marker stands as it does after a green first try. A timeout in the second sweep still takes the paragraph above first, as a timeout in any wide sweep does, before it is read as that sweep's red. When that package then passes in isolation, the timeout puts no red in the second sweep, and the `flaky:` line and the ledger row cite that isolation run's capture beside both sweeps' captures. Any red in the second sweep, in that case or in another, is a red, and takes its step's route.
**Capture, then slice: never pipe a long command through a filter.** `cmd 2>&1 | tail -50` buffers everything until the pipeline ends, so a cold build that is working and a genuine hang emit the same thing: nothing. Redirect to a file (`cmd > <log> 2>&1`) and read the summary out of it as a second call. A log the record or the gate will cite goes in `evidence-<story_id>/` ("Evidence never goes in scratch", above). The file also survives compaction, so the evidence outlives the turn, and the pipeline's exit status is the *filter's* rather than the command's. A 45-minute build has been killed on the suspicion it had hung; it had not.
**A repo with commit hooks carries gates this sweep structurally cannot see.** `lefthook` / `husky` / `.git/hooks/pre-commit` jobs — typos, formatters, staged-file linters, clippy — run against the staged index and are reachable from no script you can invoke here. So the step-4 commit attempt is itself part of verification rather than the end of it: a rejection there is expected traffic, not a failure of this sweep. What that rejection does to the tests-ran marker is step 4's problem, and it is not the obvious answer.
3. **Production profile only:** `bmad-testarch-test-review`, then `bmad-code-review`. A `CONCERNS`-grade or non-critical finding appends to `{workflow.deferred_work_path}` and the story proceeds. A **P0 / critical FAIL never defers** — re-loop within the turn budget or escalate.
4. **Commit at green** (one implementation commit per green story; the gate's evidence commit follows inside the same story boundary, per `references/gate.md`'s advance route, and when the gate's `bmad-testarch-automate` backfills a test, a commit of that backfill comes before it, per gate.md's "When automate backfills"). The PreToolUse hook blocks a commit on a protected branch, blocks a commit when no "tests-ran" marker exists for the current story, and (its marker-freshness clause) blocks a commit when that marker's `baseline=` line does not match the story's recorded baseline, so step 0 must have set the current story and step 2 must have actually run and written `{workflow.implementation_artifacts}/.tests-ran-<story_id>`, in the format step 2 pins, **in a prior, SEPARATE command**. The guard pre-evaluates the command *string* before it runs, so a marker written by a `printf`/`echo` in the SAME compound command as the commit (e.g. `printf … > .tests-ran-<id> && git commit …`) does not yet exist at hook-eval time and the commit is denied. Write the marker, then commit: two distinct tool calls. **A commit can also be rejected by something that is NOT the guard, and the marker rule inverts there.** A repo-side `pre-commit` hook (lefthook, husky, a plain `.git/hooks/pre-commit`) running clippy, rustfmt, typos or a staged-file linter rejects the commit without moving anything: HEAD is where it was, so the tests-ran marker's `baseline=` line still matches character for character and the guard will wave the retry straight through, carrying evidence collected *before* the fix. The freshness clause keys on the BASELINE, not on the code state, so it cannot see this case by construction. Treat a hook rejection exactly as step 5 treats a post-commit red: remediate, re-run the story's tests/lint/build to green, write a **fresh** `.tests-ran-<story_id>` (same `baseline=` line, still copied and never re-derived; `scope=`/`packages=` re-stated for what the re-run actually was), and only then retry the commit. This rule binds the story's own commits: this step's, and any re-commit or amend step 5 makes. The gate's two commits keep their own rules in `references/gate.md`: "When automate backfills" reads a hook rejection of its commit of a test `bmad-testarch-automate` backfilled as its backfill sweep's red, which it fixes only in the backfilled test files and otherwise ends the cycle at a re-loop, and the advance route says how to answer a hook rejection of its evidence commit. **A `commit-msg` hook that rejects the message alone takes a shorter route, on the story's own commits.** Git runs that hook only once every `pre-commit` job has passed, so such a rejection asks for no file change: reword `message.txt` ("Check the record's claims before the commit", below), run the claim check again, and retry the commit from the message file (`-F`) with the marker as it stands, re-running no sweep and writing no fresh marker. A change a `pre-commit` job staged on its way there (a formatter that rewrote and re-staged a file) rides the retry as it would ride an accepted commit, and step 5's re-verify measures it. A path the re-run claim check has you stage or edit is a file change, which takes the rule above. Reword at most twice for one commit: when the hook rejects the second rewording too, the message it wants may hold what the run does not have (a ticket id, say), so commit nothing and escalate for the story as the sub-skill halt catch-all below does, with a `decision_needed` that names the hook and the rule it applies. A rejection whose fix needs a file changed, or whose output does not show that a `commit-msg` hook made it, keeps the rule above. **Append `.decision-log.md` with Write/Edit, never a Bash heredoc.** Stages 4 and 6 require a log of what happened during the run, and what happened *is* commit behaviour, so the log quotes the verbs. The guard evaluates Bash command strings, and a heredoc carrying that prose is a Bash command string: a line leading with the verb is a verb-leading segment, and backticked identifiers or an apostrophe send the whole segment down the fail-closed matches-anywhere path. Its git gates read **Bash command strings alone**, so writing the log with the file tools removes the collision instead of phrasing around it, and keeps Bash for commands you actually mean to run. Said that way rather than "the guard never sees Write/Edit", because preflight arms the hook for EVERY tool: the hook IS invoked for a `Write`, and it does decide on file tools, but only through its Cross-Session Recall rules, which deny a file-tool call that names the recall store or would change the run latch (`references/preflight.md`). A decision-log append is neither, so the conclusion is unchanged, but a reader who believes the guard cannot see a `Write` and then meets the all-tools matcher will try to resolve the contradiction by narrowing the matcher back, and that leaves the recall rules enforcing nothing. **Once the log is too large to Read affordably, do not Read it.** It grows monotonically, one session's prose per invocation, and both file tools refuse a file that has not been Read in this session, so on a long-running Epic (288 KB by its eleventh invocation) the two sanctioned paths are both closed at once. Compose this session's entry with Write into a NEW sibling file beside the log, in the folder that holds `.decision-log.md` and never in `{workflow.implementation_artifacts}`, which is another folder: `<log folder>/dlog-slice-<story_id>-<n>.md`, where `<log folder>` is that folder's full path and `<n>` is one past the highest number a `dlog-slice-<story_id>-*.md` there already carries, so it increments per append: the name has to be unique per append, not per story, or a story's SECOND entry finds the slice already on disk and walks straight back into the Read it was escaping; then append it in one Bash call with both paths in full, `cat "<log folder>/dlog-slice-<story_id>-<n>.md" >> "<log folder>/.decision-log.md"`. That command's leading token is `cat`, it carries no backtick, no `$(`, and no verb-leading segment, so the guard makes no decision on it and the prose never enters a Bash command string at all. Keep the slice beside the log rather than deleting it: it is the only per-session copy if the append is ever interrupted. **Stage only the current story's paths.** In production, Stage 3 generated *every* in-scope story's red-phase tests up front, so a sibling story's still-skipped tests can co-reside in the same shared dirs as this story's (one `test/` package may hold two stories' acceptance specs before either commits). A blanket `git add -A` here sweeps those uncommitted sibling tests into this story's commit and pollutes the per-story boundary: stage this story's source + test paths explicitly (`git add <this story's paths>`) instead. Those paths take in every path step 2 marked intent-to-add, a marked file since deleted included (staging a deleted file's path drops its entry), and a mark on a path `HEAD` already holds is staged in place like the rest. A marked new file the story will not ship is moved aside into `.scratch-<story_id>/` before that call, so staging its path clears its entry the same way, and moved back after it, untracked again. Such a file is deleted instead only when nothing needs it. The guard refuses any commit while the index holds a mark, naming each one, because the commit would leave that file out while the index keeps it, or, for a mark on a path `HEAD` holds, delete `HEAD`'s file. The allowlist ships plain `git add` (a prefix covering both `-A` and a scoped `git add <paths>`) so the targeted add needs no extra approval. **Staging is itself a prior, SEPARATE tool call**: `git add <this story's paths>` as one call, then `git commit` as a second: the same two-distinct-tool-calls rule the marker follows, and for the same reason. The guard also denies a commit whose staged index is empty, and a chained `git add … && git commit` has staged nothing at the moment it pre-evaluates that command string, so the chained form is denied even though the add would have worked. `git commit -a` and commit-time pathspecs (`git commit <paths>`) are unsupported inside the story loop for exactly that reason. (Under `--light` no ATDD tests are generated, so the collision cannot arise.) **Once the commit lands, record the story's END sha.** Write `{workflow.implementation_artifacts}/.commit-<story_id>` with the output of `git rev-parse HEAD`, in exactly the format step 0 pins for the baseline: one newline-terminated line carrying the full 40-hex SHA. Unlike the baseline, **this marker is refreshed, not preserved**: step 5 rewrites it after any remediation re-commit or amend, the gate rewrites it after the commit of a test `bmad-testarch-automate` backfilled (gate.md's "When automate backfills"), and the gate's advance route rewrites it after its evidence commit, so it always names the story's last commit rather than its first. It exists to close the story's commit range explicitly: without it the evidence trail has to *infer* a range end from the NEXT story's baseline marker, and a later story anchored at this story's own SHA collapses that range to `X..X`, so a story that did commit renders as having committed nothing.
**Check the record's claims before the commit.** Gate reviews keep finding one shape of defect in the record: a commit message, a code comment or a story sentence that asserts a property the code does not hold, written by the author who just built it. A catch after the commit costs a re-loop, so check between the staging call and the commit call. Write the commit message with Write to `{workflow.implementation_artifacts}/.scratch-<story_id>/message.txt`, and the story-record notes this cycle added (completion notes, a re-loop's notes, File List entries; for a decomposed child, which has no record, the File List and completion notes from `ucg-dev-story`'s step 10 summary; an empty file when the cycle added none) to `record-notes.md` beside it, Reading either first if an earlier session left it, then run:
```
uv run {skill-root}/scripts/claim_check.py --message {workflow.implementation_artifacts}/.scratch-<story_id>/message.txt --message {workflow.implementation_artifacts}/.scratch-<story_id>/record-notes.md --project-root {project-root} --artifacts-root {workflow.implementation_artifacts} --artifacts-root {workflow.implementation_artifacts}/.scratch-<story_id> --artifacts-root {workflow.implementation_artifacts}/evidence-<story_id> --tea-config {workflow.tea_config_path}
```
The second `--message` is there because the record names files the message may only describe. Its `not_in_diff` lists the paths it reads as named in either text that the staged diff does not touch, each a claim about the tree that needs no judgment to refute; paths git ignores (the mutation ledger the record cites, a story file under an ignored artifact tree) are listed apart, in `ignored`, since no commit can carry them. A record names its own artifacts from the folder that holds them (`sweep.sh`, `red-phase/INDEX.md`), so the command names three folders with `--artifacts-root` (the run folder, this story's scratch folder and its evidence folder) and a fourth with `--tea-config`, the TEA test-artifacts root that holds `atdd-checklist-<story_id>.md`, resolved from the TEA config as preflight resolves it (`scripts/preflight_check.py`, `_tea_artifacts_root`), and such a name is read there: one that does not exist from `{project-root}` but exists in one of them lands in `ignored` when each copy that holds it is either ignored by git or outside the work tree, and in `not_in_diff` otherwise; one that exists from `{project-root}`, that a file the tree holds could be, or that is in none of them, is read from `{project-root}` as before. A file this commit claims and never wrote, named bare, under a folder the tree does not hold, or under an empty or ignored-only folder inside an untracked one (git lists only the topmost untracked folder), cannot be told from an artifact of that name, so a copy in one of the folders reads it as the copy: the hunk pass below, which finds the hunk for each edit the message or the notes say this commit makes, is what catches it. For each path in `not_in_diff`: stage it if this commit changed it; if the work tree shows no change there, the edit did not happen, so make it or remove the claim; and reword the message or correct the story record itself (not only its scratch copy) when the text says this commit changed a file it did not. A path under this story's `.scratch-<story_id>/` or `evidence-<story_id>/` is never staged, since both folders stay untracked: the record names it on purpose, as its own evidence, and it may stay listed. A text may name an unchanged file on purpose, if it says so. Run the check again until every path left in `not_in_diff` is one a text names on purpose and says so. Then make one pass over the claims the diff itself adds (its new comment and header lines, the story's new completion notes) and each line of the message, for a superlative or a property: "exactly", "every", "always", "cannot", "not X but Y", "composed", or a claim that something exists or does not exist yet. Each one either cites evidence this cycle already produced (a test, a mutation row, a printed measurement) or is softened to what that evidence shows; start no new run to back a sentence, since the usual fix is to weaken the sentence, not to strengthen the code. In the same pass, read `git diff --cached` once and find the hunk for each edit the message or the notes say this commit makes ("now says", "narrowed", "landed", "fixed"), path or no path: an edit described by its content has a path too, and an edit whose script failed leaves no hunk. And look for a claim this commit makes false without touching it: a forward reference to what it lands in a comment or doc elsewhere in the tree. Search the project's own files with the Grep tool, case-insensitive, for this story's id, "does not exist yet" and "owed by", and for the name of each file the commit adds, leaving out the installed skill, the run folder and this story's own record and tests; correct a hit only when it refers to what this commit lands, in this commit, staged with this story's paths, unless a sibling story's uncommitted edits share its file, in which case log it to `.decision-log.md` for that story instead. Re-stage every file this pass edited, in its own `git add` call, then commit from the message file (`-F`). Run the same check before any re-commit step 5 makes, and before an amend with `--amend` added, on every run for that amend, a reword's re-run included: it compares the texts with what the amend would commit (the index against `HEAD`'s first parent, or the empty tree at a root commit), so a path the amended commit already carries from `HEAD` stays out of `not_in_diff`, and for that amend the hunk pass reads `git diff --cached <base>`, with the `base` the check printed.
5. **Re-verify on the committed HEAD.** Re-run the authoritative suite (tests + lint + build, the same scope step 2 ran this cycle: all three axes including the declared gate set when full; the same resolved package set when this re-loop cycle legitimately ran scoped, per step 2's re-loop rule) on the just-committed, clean tree and **PRINT** the result before advancing. **Run it cache-defeating.** Committing changes a file's git *tracking state* and not one of its bytes, so a content-addressed cache key is unchanged and this re-run replays the pre-commit answer verbatim, observing nothing: eight of eight tasks reported cached, returning in 719ms immediately after a commit, is the whole failure. Pass `--force` (or invoke the package's runner directly), because the one thing this step must actually execute is the tracked-file gates against the newly tracked fileset. Step 2's marks show a story's **new** files to a **conformance gate scoped to *tracked* files** (a `git ls-files`-based ref/ownership/architecture-boundary check) before the commit, but three kinds of new file still hide from it there, so the gate skips them and reports green at step 2, then reds the instant the commit tracks them: a generated or `.gitignore`d file, which no mark can reach; a file created after step 2's last mark; and, for a gate that reads the staged content (one built on git grep --cached, say), every new file, since a mark holds an empty blob. This committed tree is the exact fileset CI and the Stage-5 gate will see, so a story that is green pre-commit but red here is a **false green** the pre-commit run and any transcript-only evaluator (a `/goal` an operator started, say) both miss. A red step 2 reads as not yet a red (a timeout on a loaded machine, or a red the story's changes do not explain) is read that way here too: a red the story's changes do not explain whose second sweep shows no red leaves this step green, with nothing committed. A red means the story is **not** done: remediate, write a fresh `.tests-ran-<story_id>` marker, and re-commit (amend or a follow-up within the story boundary) until the committed HEAD is green, and only then advance. **That fresh marker carries the same `baseline=<sha>` line as step 2's**: the verbatim, whitespace-stripped content of `{workflow.implementation_artifacts}/.baseline-<story_id>`, **copied, never re-derived from `git rev-parse HEAD`**. The story's baseline has not moved; HEAD has, because step 4 just committed. Re-deriving it here would re-anchor the story to that commit and quietly retire the freshness net for the rest of it, which is the very replayed-marker hole the line exists to close, and without the line the guard denies the re-commit outright, so a story that legitimately needs remediation could never close. The fresh marker also re-states `scope=` (and `packages=` when scoped) to match what THIS re-verify actually ran, because the `scope=` line the gate will read through `--tests-ran` is the one written here, not step 2's. **Rewrite `{workflow.implementation_artifacts}/.commit-<story_id>` from `git rev-parse HEAD` once this step's HEAD is green**, in step 4's format: every time, including when nothing was remediated, because an amend replaces the SHA step 4 recorded and a follow-up commit moves it. This marker is the one step-0 artifact whose rule is *refresh*, not *keep*: the baseline names where the story started and must never move, this one names where it ended and must never be stale. That re-commit carries the SAME staging rule as step 4: stage in a prior, SEPARATE tool call (`git add <this story's paths>`), then run the commit (or `git commit --amend`) as a second, distinct call. `git commit -a` and a chained `git add … && git commit` are unsupported here too: the staged index is still empty when the guard pre-evaluates the command string, so the re-commit is denied. When `{workflow.backfill_sweep}` is `scoped`, capture this step's sweep in `evidence-<story_id>/` as `sweep-step5-<short sha>.log` ("Evidence never goes in scratch", above): the gate's scoped backfill sweep builds on that capture and names it (`references/gate.md`, "A backfill of test files alone may scope its sweep"), and without it the gate runs the full sweep. No marker this file writes carries a `sweep=` line.
**Sub-skill halt catch-all.** If any orchestrated sub-skill blocks on interactive input mid-run, treat it as escalate for that story: write the typed escalation sidecar `{workflow.implementation_artifacts}/escalation-<story_id>.json` (shape below, under "Escalation sidecar") and stop; do not answer its prompt blind. A sub-skill that is not installed at all (the Skill tool does not know its name) takes the same route: escalate, and never substitute another skill (`bmad-build`, `bmad-build-auto`, or BMAD's deprecated `bmad-create-story` and `bmad-dev-story` for UCG's story skills) or hand-author the work it would have produced.
**Waiting spends turns.** The Stop hook counts one turn per response, whatever the response did. A background task's notification (a background command exiting, a background subagent or workflow reporting back, a watch's event) that lands while the session is idle starts a response of its own, so each such wake-up costs a turn even when all it does is say a sweep is still running. A notification that lands while a response is still working can be taken into that response at no cost. A full sweep can outlast a foreground command's time limit, and an attended session often cannot wait for a subagent in the foreground, so the waits in this loop (the step 2 sweep, the step 3 reviews, the step 5 re-verify, Stage 5's assessors) are real. What the run controls is how many wake-ups they cost:
- **Make each wait report once.** Start what the next step needs in one response and have it come back as one notification: concurrent commands as one subagent the session waits for, which runs each as its own simple command and reports every exit status in its one reply, and concurrent subagents as one workflow, or as calls the session waits for where it can (a `-p` run can). One compound shell command that starts them together and collects their exit statuses (`&`, `wait`, `$!`, `$?`) is not an option: under `scripts/drive_epic.py`'s default spawn mode, `acceptEdits`, with the default allowlist, Claude Code refuses it before it runs, as step 0 says of compound commands. Separate background tasks each wake the session when they end.
- **Watch for completion, not progress.** A watch that emits an event per log line or per stage wakes the session on every event. Add no background wait command beside a task that already reports when it ends, and schedule no wake-up only to check progress.
- **Spend a wake-up on work.** A wake-up while the next step still needs a running task is a turn spent whatever it does, so do in it the work that does not depend on that task (record the finished result, prepare the next command).
- **Keep another story's work off this story's count.** The hook books every Stop to the story `.current-story` names, so a background task for another story (refining the next one, say) started while this one is current spends this story's turns. Start such work in that story's own loop, once its step 0 has made it current. A decomposed child's ATDD run is such work: it runs after the child's own step 0, never while the story before it is current ("A decomposed child's ATDD run", above).
### The per-invocation work bound (`--max-stories N`)
When the operator passed `--max-stories N`, count the stories this **invocation** has taken all the way to a Stage-5 verdict, and once that count reaches N with in-scope stories still remaining, leave the spine and go to Stage 6. **Not "as if the Epic had run out of stories" — it has not.** The Epic-level trace gate is triggered by `references/gate.md`'s own condition (*every* story of the Epic is `done`), which a bounded stop leaves false, so that gate does not fire and Stage 6 must not author one: an Epic-level PASS over an Epic that still owes stories is precisely the misrepresentation `gate.md`'s partial-by-design exception exists to prevent. That sentence has one boundary case it must not swallow: **when the bounded lap drives the Epic's last in-scope story, the bound never fires** — its trigger is "N reached *with in-scope stories still remaining*", and none remain — so that invocation is an ordinary Epic completion: every story is `done`, `gate.md`'s own condition holds, and the Epic-level gate runs normally. Under `--max-stories 1` driving this is how every Epic ends, so reading this paragraph as "a bounded invocation never runs the epic gate" skips the roll-up on the one invocation that earned it.
**It bounds work, not scope.** In-scope is still every not-`done` story of the Epic (Stage 1 rule 3; headless never narrows it), so the remaining stories are not skipped, not deferred, and not logged as `skipped-already-done` — they are simply *not driven this time*. The next invocation's resume routing re-enters at the first story whose last logged gate verdict is not advance, which is precisely where this one stopped, so nothing about resume needs to know the bound existed. Log the bound and the carried-over story ids in `.decision-log.md` so the stop is reconstructable after compaction; an unexplained early exit and a crash look identical in a log.
**Check it at the story boundary and nowhere else.** The tempting place is wherever the count happens to tick over, and that is the trap: the loop above writes a baseline marker at step 0, a tests-ran marker at step 2, and commits at step 4, so a bound applied mid-story abandons a story with markers on disk and no commit. Evaluate it only after the story's Stage-5 verdict has landed, and after the advance route's evidence commit when one is owed, i.e. between laps, never inside one.
**A bounded stop is a completion, not an abort — Stage 6 still runs in full.** Auto Memory capture, the decision-log audit, the run report, the gate trail over the run's **in-scope** stories (finalize.md requires every in-scope id, so the ones this invocation did not drive render `n/a` under its fail-soft source rule rather than being omitted), and (headless) the terminal health check all happen exactly as they would on a full run, and the emit is the ordinary five-key envelope with `status` `complete`. The one thing that does *not* happen is the Epic-level gate, per the paragraph above, and for the same reason the `on_epic_complete` hook stays unfired: the Epic did not complete. Returning early *past* finalize would produce no report and, worse, no `run-result.json` at the pinned path — and the documented automator tests for that file's presence, so a bounded invocation that skipped the terminal would be indistinguishable from one that was killed. There is deliberately **no third status value**: `complete` here means "this invocation finished its work without blocking", and a caller that needs to know whether the Epic still owes stories re-reads sprint-status, never the status word.
**An invocation can also finish having done durable work and advanced no row** — it decomposed an oversized story (above), or spent its budget authoring a story definition a resume will drive next. Neither is `complete`: no story reached a Stage-5 verdict, and `complete` with zero rows advanced is indistinguishable in the envelope from a run that drove its story successfully. Neither is a failure either.
Emit **`blocked`**, and carry the distinction in the typed escalation sidecar rather than in a new status value: `kind` is `"story-decomposed"` for a split or `"defined-not-driven"` for an authored-but-undriven story, `decision_needed` names what the next invocation should pick up, and `evidence` names the artifacts written. `kind` is open vocabulary by design (see "Escalation sidecar"), so this invents nothing. `scripts/drive_epic.py` reads those two kinds, and `operator-evidence-owed` (`references/gate.md`), and reports the stop as a **handoff** rather than a bare halt. It still stops, and still exits non-zero, because a human does need to look at a decomposition, or record the evidence, before the drive continues.
`scripts/drive_epic.py` is the intended caller: it spawns one `claude -p` per story under `--max-stories 1`, deleting the pinned `run-result.json` before each spawn so the file's presence means *that* spawn reached a terminal, and it stops the drive if a session reports `complete` without its story having advanced to `done`. That last check is only sound because Stage 5's `advance` route **writes** the `done` row itself (`references/gate.md`) — the sub-skills leave a passing story at `review` or `in-progress`. If that sync is ever dropped, the driver's progress check goes with it: an unattended loop would read a healthy advance as no progress and halt.
**A spawn that dies in flight is its own condition, and once the driver's own retries are spent, re-spawning is not the route.** A spawned `claude -p` can abort mid-stream (a streaming error, a killed process) leaving no terminal envelope. Nothing is wrong with the story, so this is not an escalation and no decision is pending; no gate ran, so it is not a gate failure — neither documented route fits, and the driver already survives it and reports the tree the dead spawn left. `scripts/drive_epic.py` retries that `no-terminal` stop up to `--max-abort-retries` times (default 2; `0` disables it), and **only** over a tree its post-stop triage read as clean with HEAD unmoved, so a retry can never re-spawn over work in progress. Once those are exhausted the driver stops, and re-spawning by hand from there is the intuitive response that replays the same conditions that killed the first attempt (observed failing twice in a row on one story before succeeding in-session). The recovery that works then is to **drive the story directly** — in the current session, or attended. The dead spawn's on-disk residue needs no cleanup first — its markers and any commits are exactly what the resume routing at the top of this file classifies, so the direct drive enters through that routing like any resume.
### Authoring the `/goal` condition
**The conductor cannot start `/goal` itself.** It is a built-in slash command with no tool surface, so in an attended session, a `-H` session or a `drive_epic.py` spawn alike, a `/goal` is active only when the operator started one (typing `/goal <condition>`, or launching `claude -p "/goal …"`). Write the condition below either way, and record it in `.decision-log.md` at step 0 as the story's contract. When an operator did start a `/goal`, at launch or mid-session, that loop runs on the operator's own condition, not this one, and a turn clause in it bounds the session rather than the story. Keep it **under 4000 characters**, encoding the per-story Definition-of-Done as the success criterion with an explicit escape clause. The condition must:
- State the DoD in checkable terms: ATDD acceptance tests for the story un-skipped and **passing** (production) — or, under `--light`, the story's acceptance criteria demonstrably satisfied — plus lint clean, build green, and (production) test-review + code-review passed — mirroring the printed evidence so the transcript-only evaluator can corroborate it.
- Include the literal escape: **"…or stop after {workflow.max_turns_per_story} turns."** It belongs in the story's written contract, but it bounds nothing on its own, since no `/goal` runs on this condition. The only turn count every session keeps is the one the `budget_stop.py` Stop hook records in `{workflow.implementation_artifacts}/.budget-<story_id>.json` (`run-status.json` copies it into `budget_used.turns`, and when the two disagree the hook file wins). It advances once per Stop, that is once per response the session ends, so it cannot see re-loops spent inside a single response. It counts responses, not work: a response that only acknowledges a background task's notification counts the same as one that edits code, so a story's waits spend its ceiling too ("Waiting spends turns" in the story loop above says how to keep that small). Read it, never a count of your own, at two points. **Before a story's step 0** on the `story-boundary` and `mid-story` resume routes: a resume can inherit a counter already at or over `{workflow.max_turns_per_story}`, and then you escalate instead of driving that story (write `escalation-<story_id>.json` with `kind` `budget-overrun`, the kind `/ucg-resolve` resets the counter for, and end the invocation `blocked`, as `references/gate.md`'s `escalate` does). A `gate-owed` story is exempt and goes straight to step 5 and the gate, because its work is already committed, and so is a story the fifth resume case's first or third form (a backfill, or an automate pass, with no verdict after it) sends into Stage 5, whatever route the script reports for it, because its gate cycle is already under way. The fifth case's second form reads the count at its re-loop's turn-ceiling check instead. **Before each re-loop**, where `references/gate.md` turns a re-loop that would exceed the ceiling into `escalate` (a cap-only re-gate, which re-measures without re-driving, excepted). The hook itself only records and warns (a Stop hook **cannot force `/goal` to halt mid-condition**, and it never blocks), and the marker it writes on an overrun becomes an escalation only as described below: a story that then advances at its gate gets a sizing note instead. In a single attended or `-H` session with no operator `/goal`, nothing bounds re-loops spent inside one response; for `drive_epic.py` spawns, the `--session-timeout` wall clock is the backstop that holds whatever the count says (unless it is set to `0`). State the clause anyway.
- Make explicit that **passing the condition is not completion** — the authoritative verdict is Stage 5's `gate_eval.py`. The `/goal` condition gets a story to a *plausibly* done, evidence-printed state; the gate decides.
Keep it under the character limit by referencing the story's `atdd-checklist` (or, under `--light`, its acceptance criteria) and printed test output rather than restating ACs verbatim.
After the spine finishes (all stories committed-at-green, or a story hit its turn bound and wrote an escalation marker), proceed to Stage 5 for the deterministic per-story and epic-level gate.
**Escalation ping.** When a story's gate escalates it on the turn count (`references/gate.md`), before Stage 6, scan `{workflow.implementation_artifacts}` for the escalation markers *this* run produced. A `.escalation-<story_id>.md` is in scope only when it **both** names a story in this run's plan **and** was written after this run's start: both conjuncts, never either one alone. The story whose gate just escalated it on the count is in scope whatever its marker's age, since its count, not the marker's date, already shows the escalation is this run's. A marker naming an unplanned story belongs to another Epic escalating concurrently; a marker naming a planned story but predating this run's start is residue from an earlier run of the same Epic, and firing on either would tell an absent operator about an escalation nobody is having. A marker whose story the gate advanced is never promoted or pinged, as "Promoting the turn-budget marker" below says. On the first in-scope marker whose story the gate escalated on the turn count, promote it to the typed sidecar `{workflow.implementation_artifacts}/escalation-<story_id>.json` (see "Escalation sidecar" below) before firing anything, so a hook that reads the sidecar finds it already on disk. Then fire, **check-then-write** against `{workflow.implementation_artifacts}/.on-escalation-fired-<run-id>`, where `<run-id>` is this invocation's run id, minted at Stage 1 or at a resume's re-entry and carried forward verbatim, and never re-derived here, since re-minting that timestamp would produce a fresh marker on every read and defeat the dedup entirely. If that marker is already present, skip silently: the other fire site already pinged for this run. If it is absent, resolve `uv run --no-project {project-root}/_bmad/scripts/resolve_customization.py --skill {skill-root} --key workflow.on_escalation`; when the resolved value is non-empty, follow it as an instruction (a prompt to run or a shell command), stating alongside it **the escalating story id** and the path to that story's typed `escalation-<story_id>.json` sidecar as the context it carries, and only then write the fired-marker. A resolved-empty value is a silent no-op (nothing fires and no fired-marker is written), so an empty hook can never suppress a later real one.
### Escalation sidecar
Every escalation route — the sub-skill halt catch-all above, the gate's `escalate` verdict, and a story escalated on its turn count (at its gate, or at a resume already at the ceiling) — writes **one** typed sidecar at `{workflow.implementation_artifacts}/escalation-<story_id>.json`, on top of whatever it logs in prose. A status read and a resume both have to reconstruct *which* decision is pending, and the run that escalated is exactly the run whose transcript is no longer in front of anyone. Prose alone leaves them re-parsing a log; a typed file does not.
It is a single JSON object, exactly these four string fields and no fifth:
```json
{"source": "<the path:line, or marker file, the escalation came from>",
"kind": "<short slug naming the escalation's origin>",
"decision_needed": "<the exact decision a human must make>",
"evidence": "<one quoted line supporting it>"}
```
One object, never an array: the file is already named per story, so a list would only re-encode the story id inside a file that carries it in its name.
`kind` is **open vocabulary**. A reader renders whatever string it finds and never validates it against a fixed list, in particular never against the red-kind vocabulary the semantic scan returns in `references/preflight.md`, which classifies *planning-artifact* reds and has no term for anything that happens at run time. `budget-overrun` is a live `kind` and sits deliberately outside that vocabulary; a reader that validated against it would silently drop the most common escalation there is. `operator-evidence-owed` is a live `kind` too: the story is delivered and gated except evidence only a person can record (`references/gate.md`). So is `evidence-commit-rejected`: the story advanced, and a repo commit hook rejected its evidence commit in a way the gate may not answer, so that evidence waits, uncommitted, for the operator (`references/gate.md`'s advance route). So is `coupled-stories`: the earlier of two stories that are green only together owes clauses only the later story's build satisfies, and moving them narrows its AC, which only the operator may rule on (the story loop's "Two stories green only together").
**An escalated story keeps no gate build.** The gate carries its worktree's build folders into `<stash>` only for a story it will gate again (`references/gate.md`, the first caveat under "Measure the commit, not the working tree", which says what `<stash>` is), and an escalation stops the story instead, whatever route it came by. So whenever you are about to write this sidecar and `<stash>` holds a build folder, run `uv run {skill-root}/scripts/carry_build_cache.py drop --stash <stash>` right before you write it, so a session that ends between the two leaves no build behind a story it escalated. It deletes each folder `<stash>` holds, never through a link, and prints what it deleted, skipped and failed to delete; log that in `.decision-log.md` beside the escalation. The story's re-gate, once the operator answers, builds cold.
**Promoting the turn-budget marker.** The `budget_stop.py` Stop hook writes only its own markdown, `{workflow.implementation_artifacts}/.escalation-<story_id>.md`. It stays a recorder: it emits no JSON and starts no process, and its marker records a count without stopping the drive, so the story still goes on to its gate. **Execute is the sole promoter of that markdown, and the story's gate decides whether it promotes.** A marker counts only while the story's recorded count (`turns` in `{workflow.implementation_artifacts}/.budget-<story_id>.json`) is at or past `{workflow.max_turns_per_story}`: after `/ucg-resolve` closes a `budget-overrun` escalation and resets that counter, the marker left on disk is the answered escalation's residue, and nothing below applies to it. **When the gate advances the story (`advance`, or `defer`, whose route advances anyway), do not promote the marker.** The gate decides completion, and none of the decisions the marker asks for has anything left to act on once the story is done: in a real project, every overrun escalation written for a story that then passed its gate was left open and never answered. Log a sizing note in `.decision-log.md` instead, naming the story and the hook's count against `{workflow.max_turns_per_story}`; Finalize's run report carries it. The note records the turns the drive spent, and never says a row of this shape should be split: sizing reads a row's criteria, never its turns ("Sizing: a story too large to drive" above), and the turns follow how the drive waited. **When the gate escalates the story on the turn count** (a re-loop that would exceed the ceiling, which `references/gate.md` turns into `escalate`), promote the marker as that escalation's sidecar: read the `.escalation-<story_id>.md` the hook left behind and write the typed sidecar from it, mapping `source` to that markdown's path, `kind` to `budget-overrun`, `decision_needed` to the human decision the marker asks for (re-scope, split, or hand off), and `evidence` to one line quoted from the marker. The gate can escalate on the count before the hook has written a marker (a re-loop expected to take several responses, from a count still under the ceiling); write the same `budget-overrun` sidecar then from `{workflow.implementation_artifacts}/.budget-<story_id>.json`, with `source` that file's path and `evidence` its count, so `/ucg-resolve` still resets the counter when it closes it. A cap-only `reloop` (a sweep-scope or delta cap) is not that verdict: the full re-gate it leads to decides. A story that escalates for its own reason (a gate file that cannot be read, a sub-skill halt) keeps that reason's sidecar, and the marker's count goes into the decision log beside it. A resume that finds the count already at or past the ceiling escalates before step 0 with the same `kind`, as "Authoring the `/goal` condition" above says. Keeping promotion here means one code path produces the typed JSON whatever the escalation's origin, instead of two writers racing on a file three readers depend on.
**Leave the markdown in place — never delete it, never rewrite it.** It is the hook's own record of the count. For a story that advanced it is the sizing note's source, and for a story that escalates it is the residual that survives a session which died before this promotion, so consuming it could destroy the only evidence that an escalation happened at all.
## Retired — `--parallel`
The experimental `--parallel` worktree fan-out is retired; the sequential spine above is the only execution path. (`ROADMAP.md` carries why it was retired rather than promoted.)
**The flag is still accepted, and it does exactly what its old degradation branch did**: a run invoked with `--parallel` logs one line in `.decision-log.md` recording that the flag was accepted and ignored, then runs the sequential `/goal` spine. It never errors, never warns twice, and changes nothing else — an operator's old invocation keeps working, minus the mode. `{workflow.parallel_max_concurrency}` is likewise deprecated and no-op: still shipped, still resolving, read by nothing (`docs/_internal/STABILITY.md`).
## Record
Log to `.decision-log.md`: per-story turn-budget outcomes, the accepted-and-ignored note when a retired `--parallel` flag was passed, every commit-at-green, every deferral appended to `{workflow.deferred_work_path}`, and any escalation marker. The printed test/lint/build evidence stays in the transcript; the decision log carries the durable account across compaction.
## Run-status heartbeat
As the spine advances — each time you move to a new story, log a gate verdict, or spend a re-loop — write `{workflow.implementation_artifacts}/run-status.json` so an automator (or an anxious human) polling a long/headless run has something structured to read instead of prose. Overwrite it in place; it is a single live snapshot, not an append log:
```json
{"epic": "<epic id>",
"story": "<current story id>",
"index": <1-based position of the current story>,
"total": <in-scope story count>,
"last_verdict": "<advance|defer|reloop|escalate, or null before the first gate>",
"last_reasons": [<the reason strings from the gate result just read, empty before the first gate>],
"reloop_count": <re-loops spent so far this run>,
"stories": [{"story": "<story id>",
"phase": "<where the spine has this story>",
"verdict": "<that story's last gate verdict, or null before its gate>",
"dev_attempts": <implementation passes spent on this story>,
"reloop_count": <re-loops spent on this story>}],
"budget_used": {"turns": <turns spent on the current story>, "max_turns": <the resolved per-story turn ceiling>},
"profile": "production|light",
"updated": "<ISO-8601 timestamp>"}
```
`last_reasons` and `budget_used` are machine-derived, not narrated. `last_reasons` is the `reasons` array from the `gate_eval.py` result the spine just read, copied across unedited, so a poller sees *why* the last verdict landed instead of only the verdict word (after a re-loop `references/gate.md` logs before trace, in "A red backfill sweep ends the cycle at a re-loop", no `gate_eval.py` result exists, and it is the `reasons` array of the verdict object logged there); `stories` carries one entry per in-scope story on the same cadence, so an entry appears as soon as the spine reaches that story and its `verdict` stays null until the gate runs. The two `reloop_count`s are deliberately the same name at two nesting levels and are not duplicates: the top-level one is **run-scoped** (every re-loop spent this run), the one inside a `stories` entry is **story-scoped** (that story's own re-loops).
`budget_used` has exactly two sub-keys and no third: `turns`, copied from the `turns` value in `{workflow.implementation_artifacts}/.budget-<story>.json` that the Stop hook maintains, and `max_turns`, the resolved `{workflow.max_turns_per_story}` — the same value preflight already injects into the hook environment, so the ceiling reported here and the ceiling the hook enforces cannot drift apart.
When the prior snapshot's `budget_used.turns` and the current `.budget-<story>.json` disagree, the hook file wins: re-read it on every write and never carry the snapshot's own number forward, because the hook file is the only counter that observes every Stop event while a number already sitting in the snapshot is a stale copy written before the last turns landed.
Before the Stop hook has fired for a story, no `.budget-<story>.json` exists yet. That is a normal early-story state, not an error: render `budget_used` as `{"turns": 0, "max_turns": <the resolved ceiling>}` and write the snapshot anyway — an absent hook file is never a reason to skip the write, defer it, or leave the heartbeat partially written.
**A resume writes its first heartbeat at re-entry, before step 0 of the story it is about to drive** — `story` naming that story, its `stories` entry at `phase` `"resuming"`, `verdict` null. Until that write the file still holds the prior invocation's terminal snapshot, and everything a resume does before the loop — branch and hook re-assertion, the latch, recall, a grounding read — is real work during which a poller would otherwise be watching a stale terminal. `budget_used.turns` legitimately stays put through all of it (at `0` for a story not yet driven, at the inherited count for a mid-story resume), because the hook counts only Stops booked to the current story: an unmoved count beside a fresh `updated` is a conductor re-asserting the environment, not a stalled run. The poller's liveness signal is `updated` and `phase`, never `turns` alone.
This is the file the Stage 2 launch briefing points the operator at ("where to watch"); Stage 6 (finalize) records the terminal state into it when the run closes, carrying every key above forward rather than overwriting the file with a narrower object.
**The per-step heartbeat sidecar, and the stall marker its gaps earn.** `run-status.json` says where the spine IS; it cannot say how long nothing has happened, because it is overwritten on story/verdict cadence and a five-hour hole between two writes renders exactly like five busy minutes. So, additionally, append one line — the step name and a UTC timestamp — to `{workflow.implementation_artifacts}/.heartbeat-<story_id>` at every numbered story-loop boundary (step 0 through step 5, plus gate start and gate end). One command, no substitution, guard-inert: `date -u "+step-2 %FT%TZ" >> {workflow.implementation_artifacts}/.heartbeat-<story_id>` (the step label rides the format string). Append-only, observability only: the file is never gate evidence, is read by no guard, and is purged at fresh-run arming exactly as `.budget-*` is (`references/preflight.md`), so a prior run's gaps can never fire this run's stall rule. Everywhere else in this file, "the heartbeat" with no qualifier still means `run-status.json` — the attended ticker above rides ITS story/verdict cadence, never this sidecar's per-step one. Its consumer is the RESUME: on re-entry, when the story's heartbeat exists and the gap between its last line and now exceeds 30 minutes, append one line to `{workflow.implementation_artifacts}/.stall-<story_id>` recording the gap, the last step reached, and the best-known cause — a rate-limit message if one is in context, an operator pause if told, `unknown` otherwise — before driving anything. A measured story carried a five-hour zero-write hole between two gate cycles that no artifact explained, and the investigation had to reconstruct it from file mtimes; `unknown, 5h00m, after gate` would have made it a record instead. Leave both sidecars in place at story end — finalize does not remove them, and the run report may state active versus idle time from them honestly.
**Attended runs also get a ticker.** Each time you write the heartbeat, print one line into the transcript — `epic-7 ▸ story 3/6 — last verdict: advance` — so the watching human sees motion without opening a JSON file. Skip the ticker in headless (`-H`): the file is the interface there, and transcript prose has no reader.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |