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/preflight.md
View on GitHub# Stage 2 — Preflight (the autonomy gate)
This is the load-bearing gate. After this stage the run goes **unattended**: a sequential `/goal` spine that takes no mid-run human input. So everything that would otherwise stall or ask a question must be resolved **now**, or the run must refuse to launch. The posture is **hard gate with auto-remediation**: the script reports mechanical blockers, this stage clears the remediable ones, you add the semantic judgment the script cannot, and launch happens only when the post-remediation intervention budget is zero. Converse in `{communication_language}`; produced markers/docs use `{document_output_language}`.
## 1. Run the mechanical check
```
uv run {skill-root}/scripts/preflight_check.py --project-root {project-root} --epic <id> --tea-config {workflow.tea_config_path} --impl-artifacts {workflow.implementation_artifacts} --profile <production|light> --protected-branch <name> [--protected-branch <name> …]
```
Qualify the script path with `{skill-root}` (per SKILL.md Conventions a bare `scripts/…` resolves from the skill root, but the conductor runs from the project working directory) so it resolves regardless of cwd. Emit one `--protected-branch <name>` per entry in `{workflow.protected_branches}` (the flag is `action='append'`); without it the check falls back to its hardcoded `main, master` and silently no-ops a `protected_branches` override — the mechanical gate would then fail to flag being on a custom protected branch.
Pass the profile Stage 1 confirmed: `--profile light` on a `--light` run, `--profile production` otherwise. It picks the TEA skills the check requires (the `tea_skills` blocker in step 2). Left out, it defaults to production, which requires five skills a `--light` run never calls.
`<id>` is the Epic resolved in Stage 1. The script is **plumbing only** — it parses tool versions, git state, and file existence, and reports TEA config flags. It returns JSON:
```
{green: bool, budget: int,
blockers: [{id, kind, severity, detail, remediable: bool}],
checks: {cc_version, goal_ok, workflows_ok, automemory_ok, hook_onfailure_ok,
git_branch, git_clean, git_unborn, framework_present, framework_kind, test_artifacts_dirs,
sprint_status_present, project_context_count, tea_flags, tea_skills, story_skills,
impl_artifacts_tracked}}
```
`budget` is the count of mechanical blockers. The script does **not** decide semantic intervention — that is your job in step 3. Treat `green: true` from the script as *necessary but not sufficient*.
`impl_artifacts_tracked` is a reported fact, never a blocker: `false` when git would not track a file this run newly writes under `{workflow.implementation_artifacts}`, because an ignore rule covers it (a project that keeps its BMAD output out of git on purpose) or the tree sits outside the repository or behind a symlink; `null` only when there is no repository to ask, which the git blockers already report.
## 1b. Run the formalize readiness check
Step 1's `preflight_check.py` counts mechanical facts; it cannot read the planning corpus and decide whether the Epic is *formally ready*. That readiness verdict is produced here — immediately after the mechanical check of step 1 and before the remediation pass of step 2 — by the same single kernel the standalone `/ucg-formalize` entry point runs, so one readiness definition serves both entry points:
```
uv run {skill-root}/scripts/formalize_check.py --epic <id> --project-root {project-root} --planning-artifacts {planning_artifacts} --impl-artifacts {workflow.implementation_artifacts} --tea-config {workflow.tea_config_path}
```
**An operator-scoped run names its stories.** When Stage 1 recorded an operator-scoped subset (`references/ingest-and-scope.md` rule 3), append one `--story <key>` per story in it, each key as its `sprint-status.yaml` row spells it, so the verdict reads the stories this run drives and no others. Otherwise pass no `--story`: the kernel then reads every not-`done` story of the Epic, the in-scope set of every other run, and a headless run never narrows it. Either way it reads no `done` story's acceptance criteria, except a `done` parent's file whose criteria an in-scope decomposed child claims. A `--story` key that names no not-`done` story row of the Epic is a gap with `remediable: false` (`story_not_in_scope`), so a mistyped key fails the gate instead of narrowing what the kernel reads. Wherever this stage says "step 1b's command", it means this command with those `--story` flags, unchanged except where step 2 replaces a parent it set `done` with its child rows.
Qualify the path with `{skill-root}` for the same cwd-safety reason step 1 does (a bare `scripts/…` resolves from the skill root, not the project cwd the conductor runs from). The `ucg-formalize` SKILL.md names the identical kernel path, so the two callers cannot drift to divergent scripts.
The verdict is computed from the **resolved artifact set on disk** — the real PRD / architecture / epic / story content the readiness resolver locates — regardless of whether any customization shaping applied; the gate reads the artifact on disk, not the shaping. The kernel is **fail-closed**: an unreadable or absent artifact is a *failing signal*, never neutral (mirroring `gate_eval.py`'s `nfr_status is None → failing`). The run is unconditional on that resolved corpus — it is the verify side that must hold even when shaping legitimately did not land.
Of TEA's output the kernel reads only this Epic's, where TEA writes it: under TEA's test-artifacts root, the root step 5 injects as `ULTRACODE_TEST_ARTIFACTS` (the TEA config's `test_artifacts`, else `{project-root}/_bmad-output/test-artifacts`), in that folder or any folder below it. There it reads every `test-design-epic-<id>.md` for the risk matrix and the NFR thresholds, and, beside one, an `nfr-assessment.md` only when its `**Story:**` or `story_id:` line names a story the kernel reads; one it cannot read is a failing gap, as an unreadable test-design is, since its story line cannot be checked. Another Epic's test-design, TEA's system-level `test-design-architecture.md` and `test-design-qa.md`, and TEA's progress, validation and handoff files are never read. A missing test-design or NFR assessment is no gap: Stage 3 writes the Epic's test-design after this stage, and TEA assesses NFRs from implementation evidence, which the Stage 5 production gate requires of each story. A TEA file under that root, or under a `trace_output` folder the TEA config sets, is not a leaked TEA artifact.
This step only *produces* the verdict; nothing is folded in here. Step 2 folds in its mechanical gaps and closes on a re-run of this command, which seeds step 3 with the judgment candidates, and step 4 reads the verdict of step 3's own re-run on the answered scan.
Per the measurement protocol, log the formalize duration provenance — `wall_clock_ms`, `mechanical_ms`, `artifact_count` — to `.decision-log.md` on every verdict, reusing the existing step-3 scan boundary for the end-to-end split; no number gates the run (the wall-clock budget is measured, never guessed).
Log `checks.decomposed_children` there too, one line per key with the parent story file its criteria come from. The kernel reads a key with no file of its own as a decomposed child when its row sits above a `done` parent's row that has a file, or when the split removed the parent's row; a story inserted above a `done` parent's row reads the same way, and so does a story whose title starts with a single letter or a roman numeral when its file is named by its story number alone (`2-4.md` for `2-4-a-new-login-page`) or by another title (Stage 3 renames that file after its key). Nothing gates on the list, so an interactive run's launch briefing shows it. A headless run only logs it, where Finalize's audit of the decision log reads it. Step 2 writes the split record of each split the list shows that only a child row's citation or the decision log records, when its parent has a row (the formalize gaps bullet).
## 2. Auto-remediation pass
Clear each remediable blocker, then **re-run the check** so the budget reflects the fixes. Remediate:
- **HEAD has no commit yet** (`git_unborn`, `remediable: false`): a fresh `git init`, or an orphan branch, with nothing committed. While this blocker stands, make **no** branch and **no** commit in this pass, neither for `git_branch` nor for `git_clean`, and run **no** other remediation that writes to the tree: the operator's baseline should hold their project, not this run's scaffolding. A run-made first commit would become the branch's root commit, either on the protected branch or on an Epic branch with nothing under it, and deleting that branch (the run's only undo) would then also delete the only record of the pre-run tree. Record the other blockers in the blocked account instead. The blocker stands, step 4 stops the run, and its `detail` asks the operator to commit a baseline on their base branch, never on an Epic branch, and re-run.
- **On a protected branch** (`git_branch`): create this run's working branch, `{workflow.epic_branch_prefix}<epic-id>` (the same branch step 5 asserts), and check out onto it. The blocker is `remediable: true` and counts toward `budget`, so it has to clear *here*, like every other remediable blocker: step 5, the only other place the doc creates this branch, is headed "only when the gate passes" and so can never be what clears a blocker the gate is waiting on. Branch **before** the `git_clean` clear: `git checkout -b` carries an uncommitted tree across, and a remediation commit landed on a `{workflow.protected_branches}` branch sits outside the only rollback this run has (per step 5, deleting the branch is the real undo). Then re-run the check so `git_branch` clears. **This moves git state ahead of the hard gate**, so a run that STOPs at step 4 now leaves the operator checked out on a branch they never saw a launch briefing for: name the branch in the blocked account, and say that deleting it is the undo. When git ignores what this pass wrote (step 1 reported `impl_artifacts_tracked: false`, or the run folder or the test-artifacts tree is ignored, checked as step 5's "What the branch does not undo" says), say that it is the undo for the code only, and name what survives it as that bullet lists: this pass commits nothing under an ignored tree.
- **Test framework absent** (`framework_present: false`): the script already counts a pytest config / root `conftest.py` or a real `package.json` `test` script as a present framework (`framework_kind` is then `pytest` / `npm-test`, or `js-config` for a Playwright/Cypress/Jest/Vitest config), so a non-browser project does **not** trip this blocker. When it *does* fire (no harness of any kind recognized), scaffold one **appropriate to the stack**: for a web/E2E project, `bmad-testarch-framework` (Playwright/Cypress per `tea_flags`); for a **pytest or npm-script** project, stand up that harness directly (a `pytest.ini` / `conftest.py`, or a real `test` script) rather than an inapplicable browser framework — then re-run the check so `framework_present` flips true. ATDD in Stage 3 hard-halts without a configured framework — this must exist before launch. **Fitness caveat:** on TEA 1.27.2, ATDD detects a backend stack but still emits only Playwright/TypeScript scaffolds, and automate's backend worker (pytest, JUnit, go-test) is not yet verified with this module, so on a non-web module the framework is *present* but not *fit* for that pair; run such a module under `--light` (test-design and the trace gate, both of which run on any stack; no ATDD — see define-done.md's `--light` note and gate.md).
- **CI quality pipeline absent** (production profile only): if no CI quality pipeline exists yet, scaffold it via `bmad-testarch-ci` **after** the framework exists — `bmad-testarch-ci` halts if the framework is absent, so the strict order is framework → ci. This is one-time infra (force **Create** mode); the pipeline embeds TEA's coverage thresholds so the gate also lives durably in CI, while the per-epic loop gate remains `gate_eval.py` in Stage 5. Skip under `--light`.
- **Missing acceptance criteria / story** for an in-scope story: generate via `ucg-create-story`, passing `implementation_artifacts` set to `{workflow.implementation_artifacts}`, so each story carries clear, testable ACs in the folder this run reads. TEA atdd and trace both need them; a story without ACs has nothing to trace and will stall. Never for a decomposed child, one whose split is recorded as the formalize gaps bullet below says: its criteria are in its parent's story file. A key in `checks.decomposed_children` with no recorded split is left to Stage 3, which creates its file.
- **Story skills not installed** (`story_skills`, `remediable: false`): `ucg-create-story` and `ucg-dev-story` are the skills this run delegates story creation and implementation to. UCG ships both, adapted from BMAD Method's `bmad-create-story` and `bmad-dev-story` (deprecated shims from BMAD 6.12, removed at v7), and its installer copies them beside the ultracode-goal skill, so a missing one means a partial or older UCG install, or a plugin-marketplace install alone (that entry ships only the ultracode-goal skill). This pass does not install them: the blocker stands, step 4 stops the run, and its `detail` (which names the installer command) is the account the operator acts on. Never clear it by substituting another skill (`bmad-build`, `bmad-build-auto`, or BMAD's deprecated `bmad-create-story` and `bmad-dev-story` installed with `--shims`) or by writing the story file or the code by hand: the rest of the run reads the story file these two produce (`{story_key}.md` with numbered acceptance criteria), and a stand-in reaches the gate looking like a story that went through them.
- **TEA skills not installed** (`tea_skills`, `remediable: false`): the `bmad-testarch-*` skills this run's profile delegates to are missing from where Claude Code loads skills. Production can call all eight (`bmad-testarch-framework`, `-ci`, `-test-design`, `-atdd`, `-automate`, `-test-review`, `-nfr`, `-trace`); `--light` calls `bmad-testarch-framework`, `-test-design` and `-trace` only. UCG supports BMAD 6 with TEA 1.27.x, the release BMAD Method 6.12.2 and later install. TEA 2.0 moved to BMAD 7's module format and TEA 3.0 renamed these skills to `bmad-tea-*`, so neither is supported yet; when `bmad-tea-*` skills are installed, the `detail` says the project looks like TEA 3.0 or later. The check reads skill names, not the TEA version, so TEA 2.x, which keeps the `bmad-testarch-*` names, passes it. This pass does not install TEA: the blocker stands, step 4 stops the run, and its `detail` (which names the installer command) is the account the operator acts on. Never clear it by pointing the run at the `bmad-tea-*` skills or any other stand-in: every stage calls the `bmad-testarch-*` names, and Stage 3, Execute and the gate read what TEA 1.27.x writes.
- **Test-artifacts dirs absent** (`test_artifacts_dirs` incomplete): pre-create the trace/test-design/test-review output dirs (`{workflow.trace_output_dir}` and its siblings under the TEA `test_artifacts` root) so the per-story files the gate reads have a directory to land in. On TEA 1.27.2 trace does not read `trace_output`, so creating the directory does not route its output there: `references/gate.md` says how the per-story trace files reach it.
- **`project-context.md` count != 1** (`project_context_count`): advisory only. `preflight_check.py` reports it as a **check** and never appends it to `blockers[]`, so a count of `0` or `> 1` never moves `budget` and never blocks launch. **More than one:** de-duplicate to one, because `{workflow.persistent_facts}` loads every match into this run's context and `ucg-dev-story` and `bmad-code-review` read the file when present, so duplicates feed them conflicting facts. **Zero:** log it in `.decision-log.md` and invoke **no** sub-skill for it. No generator produces the file unattended: before BMAD Method 6.12, `bmad-generate-project-context` stops at interactive menus, and from 6.12 it is a shim that forwards to `bmad-project-context`, which interviews the operator and writes a block into `AGENTS.md`, never a `project-context.md`. A zero count therefore never reaches the remediation halt catch-all below and never becomes a RED. In an attended run, tell the operator they can write the file by hand, or run `bmad-project-context` themselves between runs.
- **`sprint-status.yaml` absent** (`sprint_status_present: false`): ensure it is present (via `bmad-sprint-planning`). Its presence makes TEA test-design **auto-select Epic-Level** and skip its interactive System/Epic mode prompt — without it, Stage 3 stalls on a question no one is there to answer. **Non-default-track caveat:** `preflight_check.py`'s `sprint_status_present` falls back to a repo-wide `_bmad-output/**` glob, so on a run scoped to a non-default `--impl-artifacts` dir (an isolated track, per ingest-and-scope.md's cross-file/colliding-epic rule) it can read `true` off a *foreign* track's `sprint-status.yaml` while this run's own track has none — this `sprint_status_present: false` trigger then never fires. On any non-default `--impl-artifacts` run, take `formalize_check.py`'s strict per-impl-artifacts read (the §1b `sprint_status_absent` mechanical gap) as the authoritative sprint-status signal and remediate off *that*, not the glob-backed flag.
- **TEA mode**: invoke every TEA workflow this run in **Create** mode (the `[C] Create` choice each TEA skill offers when it starts). Resume, Validate and Edit are interactive and will halt an unattended run. This is a choice made at each invocation, **not** a config value: `tea_execution_mode` is TEA's parallelism setting (`auto`, `subagent`, `agent-team` or `sequential`), so never write `create` or any other mode word into it. TEA reads a value outside those four as `auto`, so a stray one a prior run wrote changes nothing: log it, and leave the file alone (the installer regenerates it, and a write would dirty a tracked tree).
- **Secrets / credentials — and unresolvable EXTERNAL DEPENDENCIES generally** — that a story needs (test env keys, API tokens, and equally network egress for anything a story's tasks say to *fetch*: a vendored data file, a crate or package not already in the lockfile, a model download): **interactive** — prompt or resolve **once**, now, and capture secrets out of git. **Headless** — do not prompt; an unresolvable secret **or an external fetch the environment refuses** becomes a RED blocker (step 4), never a deferred question. The fetch case sits in this bullet on the same fail-closed terms as credentials because its discovery otherwise happens mid-Execute, after the work around it is done, with the gate as the story's only exit.
- **Formalize mechanical gaps** (`formalize_check.py`'s `mechanical_gaps[]` from step 1b): fold these machine-derivable, meaning-preserving fixes into *this same* pass (its closing re-run included), never a separate remediation pass and never a new step heading. The genuinely-new one is the leaked-TEA-artifact **MOVE-and-re-point**: move a TEA artifact that leaked into a source/impl dir out to the `{workflow.trace_output_dir}` / test_artifacts root, then re-point every in-repo reference to the new path (content is only relocated, never rewritten); the MOVE targets a *genuine* TEA artifact only; the kernel now excludes UCG's own story notes / run sentinels whose filename merely carries a marker token because the story slug does (`formalize_check.py:_is_ucg_impl_artifact`), so they no longer reach this remediation. Should any *other* non-TEA false positive ever surface, **verify identity before moving** and archive it *out of the impl-artifacts scan tree*, never into the trace dir (that misfiles it) and never leave it in place (it stays counted and deadlocks the `budget == 0` gate, since a remediable gap that is never cleared keeps the formalize verdict off `ready`), recording in `.decision-log.md` what it actually is. The orphaned-index and missing-AC gaps reuse the `ucg-create-story` scaffold this step already runs, except for a decomposed child, which never gets a story file. A `story_keys_uncovered` key whose id extends a parent's (`55-0-a-i` of `55-0-a`) may be one, placed below its `done` parent's row (the gap's `detail` names those, with that row) or under a parent row left open. The split is recorded when its split record (`.split-<parent key>.json` beside `sprint-status.yaml`, which `scripts/story_sizing.py --record` writes) names the child, the child's row cites the parent ACs it claims, or `.decision-log.md` names the parent and the ACs each child claims (execute.md's decomposition conventions write all three). When it is, set the parent's row to `done` and move each child's row above the first row of the parent's stem, both in this pass, and scaffold nothing; when no split is recorded, scaffold the key like any other. **Write the split record in this pass** for every split recorded only by a child row's citation or the decision log: each parent step 1b's `checks.decomposed_children` names by its row (`parent_row`), and each parent of a split this bullet repairs. The Epic-level roll-up reads a decomposed parent through its children only on its split record (`references/gate.md`), so without one that parent refuses the Epic gate at the end of the run. Write it with one `scripts/story_sizing.py` run per parent, as `references/execute.md` describes for a new split: `--parent <the parent row's key>`, `--record` the directory that holds the `sprint-status.yaml` this run reads (`{workflow.implementation_artifacts}`, or the isolated track's own directory on a flag-only isolated track, `references/ingest-and-scope.md` rule 6), `--parent-acs` from the parent's story file, and one `--child` per child row with the parent ACs its citation or the decision log names. A run that does not exit 0 writes none, and that is not a blocker: log the parent with what the script printed (the claim-map fields on exit 1, the usage error on exit 2), since the Epic gate will refuse that parent until it has a split record. A listed child whose parent has no row (`parent_row` is `null`, the split removed it) needs none, since the roll-up never reads a parent with no row, and a listed key with none of the three records is a story of its own and gets none either. A parent set `done` here is a container from now on, and it leaves this run's in-scope set although Stage 1 counted it: log it. On an operator-scoped run, also take its key off step 1b's `--story` list and add its child rows' keys, both before the closing re-run, which would otherwise read the parent's key as one that names no not-`done` row. Stage 3 and Execute then neither work on it nor owe it a story file check or an ATDD checklist, and the Stage 6 gate trail still lists it, as `references/finalize.md` says. Auto-clear **only** a `mechanical_gaps[]` entry whose `remediable == true` (the kernel's human-authored `remediable` literal, never re-decided in this prose); a leaked-artifact finding the kernel emitted as a `judgment_candidates[]` entry or with `remediable: false` is **not** moved here: that residual content-soundness judgment routes to the step-3 scan / step-4 hard gate. These remediations reuse the existing remediate-then-re-run loop below, whose closing re-run of step 1b's command is what re-reflects the formalize fixes.
**A gitignored artifact tree** (`impl_artifacts_tracked: false`). Git ignores what this run newly writes under `{workflow.implementation_artifacts}`, so `git_clean: true` says nothing about the story files this pass writes there, and none of them exists in CI or on a fresh clone. No acceptance criterion or test this run writes (this pass, Define-Done's story creation and ATDD, or Execute) may name a path under that tree, or any other path `git check-ignore` reports, as a file a test reads at run time: the test would pass here and fail in CI. Point it at a tracked fixture instead.
**A ruling that later agents apply.** When remediation records something once for many agents to apply (a cross-story arbitration whose entries several story fixes must follow, say), it may only **apply** a decision an artifact already makes. Each entry cites the artifact line that decides it. An entry that would settle a question no artifact answers is not a ruling: it is a step-3 RED, and the pass records it as one instead of writing it down for agents to apply. Hand the ruling file to the step-3 subagent with the other artifact paths, so the scan reads what the stories were made to follow.
The file lives in the run folder beside `.decision-log.md`, and it is the artifact of this pass most likely to go stale, since everything after it exists to change what it rules on. So it keeps its own record of what still holds:
- Number each entry (`R1`, `R2`, ...).
- A `Status:` line at its head names the entries in force, and every supersession amends it.
- A supersession block under that line takes one line per overtaken entry, `~~R3~~ replaced by R7: <why>; re-touched: <each artifact already edited under R3>`, and entry `R3`'s own text stays as it was, so an agent that already read it can tell that it changed and an artifact edited under it is named for a second look.
- Every prompt that hands the file to an agent says to read the supersession block first, because an entry below it may be stale.
Log each supersession to `.decision-log.md`.
**Stale-hook pre-arming (before any remediation commit).** A prior UCG run may have left its PreToolUse guard (`scripts/hooks/guard_pretooluse.py`) and Stop budget hook (`scripts/hooks/budget_stop.py`) armed in `{project-root}/.claude/settings.local.json` — still live *now*, because step 5 has not yet re-armed this run's hooks. That stale guard mis-governs any remediation that commits (the dirty-tree `git_clean: false` clear especially): its marker-gate keys on `.current-story` plus a `.tests-ran-<story_id>` marker in the impl-artifacts, and on a fresh run `.current-story` is either unset — so no marker resolves and the commit is **denied**, dead-ending the remediation — or still points at the prior run's last story, whose persisted marker (Finalize removes only `.mem-state.json`, never the tests-ran markers) it then **rides to a spurious green**, waving the commit through under stale, wrong-run enforcement. Both failure modes are wrong for this run. Do **not** forge a marker and do **not** wait on the gate: **disarm the prior-run hooks first**, then make the remediation commit, and let step 5 re-merge both hooks freshly with *this* run's injected env. **The entries are nested, not top-level.** `settings.local.json` carries them under a top-level `hooks` key as `hooks.PreToolUse[].hooks[]` and `hooks.Stop[].hooks[]`: each outer element is a matcher group (`Stop` groups carry no `matcher` key) holding its own inner `hooks[]` array, and the UCG entry is the inner item whose `command` string names `guard_pretooluse.py` / `budget_stop.py`. Remove those inner items, and the enclosing matcher group only when that leaves its `hooks[]` empty, so a co-resident non-UCG hook survives. A disarm aimed at top-level `PreToolUse` / `Stop` keys matches nothing, changes nothing, and reports success: the stale guard then rides armed through the whole of preflight while the log records a disarm that never happened. So **mirror step 5's assertion** — re-read the **resolved** settings and confirm neither script path appears in any hook `command`, **before** any remediation commit. Assert on the script path rather than on the shape, so the check still holds if the settings schema moves and so an entry armed in another settings layer is not missed. Disarming is exactly as load-bearing as arming, and is the one this stage would otherwise leave unverified. Log the disarm, that assertion, and the step-5 re-arm to `.decision-log.md`.
**When the disarm applies.** The hazard above binds a commit and nothing else: the guard's git checks act on `git commit` and `git push` alone, and the marker gate is the commit's. So the disarm is owed before the first commit this run makes ahead of step 5's Hooks bullet, whichever step makes it: a remediation commit, the `git_clean` clear, or step 5's own dirty-tree resolve. On a tracked tree that commit is all but certain, since the files this pass writes leave the tree dirty: disarm first. When nothing will commit before the hooks are re-armed (a pass that only branches, on a project whose artifact tree is gitignored, is the usual case), skip the disarm and log why. The stale entries then stay armed until step 5 replaces them, and the stale Stop hook may count this preflight's turns against the prior run's story; step 5's marker purge clears the counters it writes.
**A refused settings write.** The disarm above and step 5's arming both write `{project-root}/.claude/settings.local.json`, which Claude Code treats as a protected path. Under Auto Mode, which the hard gate requires, the permission classifier reviews that write: it may refuse it as self-modification, or let it land and then refuse the calls that follow it. In a headless session nobody can approve either refusal. A refusal that names the guard's command with `failed; blocking` or `timed out; blocking`, or shows `uv`'s own error, such as `error: Failed to spawn`, is not the classifier's, whichever write or call it refuses, the disarm included: no approval under `/permissions` fixes it, and it takes step 5's last bullet's "A guard that cannot start" instead. Any other refused write of a disarm the pass does not need (the paragraph above) is no stop: skip that disarm, log it, and go on. Treat any other refusal of the write, or of any call after it until the assertion that write serves has passed, as a stop. Do not retry it through another tool, script, encoding or subagent; do not delete or restore the file; do not forge a marker; do not skip the step-5 assertion; and do not progress. Log the refused action verbatim, the file's state (written or not, asserted or not) and the current branch to `.decision-log.md`. Then:
- **Attended:** show the operator the exact content the write was meant to apply, and ask them to approve it (under `/permissions`, on its Recently denied tab) or make the edit themselves. Then re-run the assertion that write served: `preflight_check.py --assert-armed` after arming, or, after a disarm, the check that no hook `command` names either script. A refused **disarm** has one more route. Hand the operator one command, to run in a terminal outside this session, that stages the named remediation paths and commits them on the current branch, with no push. A command run there is no tool call, so no PreToolUse hook reads it: the commit needs no disarm and the hooks stay armed. Do not offer it as a `!` command in the session: Claude Code's docs say a `!` command runs without going through Claude, but not whether the PreToolUse hooks see it. Record it as an operator-run deviation, then re-run step 1. Offer this route only after confirming the current branch is `{workflow.epic_branch_prefix}<epic-id>`, and only for a remediation commit made before Execute. If the operator neither approves nor makes the write (nor runs that command, for a disarm), the run stops here: remove this run's recall latch first, with the unlatch command at the end of step 4, as every stop before Finalize does.
- **Headless:** record a **RED** blocker naming the refused write and the operator action that clears it (an attended pass that approves or makes the write), and stop through step 4's blocked exit. The way back is that attended pass, not `/ucg-resolve`. A resume never reaches this stage: when its hooks need re-arming and the write is refused in a headless session, it escalates the story it was about to drive instead (`references/execute.md`, the re-assertion sweep), and its way back is an attended resume that makes the write, with `/ucg-resolve` closing that escalation.
**Ordering.** `git_branch` → the `git_clean` clear (the branch has to exist before a remediation commit lands, per its bullet) and framework → ci (the CI scaffold halts without a framework, as its bullet states) are both load-bearing, as is the stale-hook disarm above, which must precede any remediation commit. While `git_unborn` stands, no remediation that writes to the tree runs at all, the branch and the `git_clean` clear included, as its bullet says. Every *other* remediation above is mutually independent — run them in any order, or concurrently; do not serialize them defensively.
**Remediation halt catch-all.** If a remediation sub-skill itself fails, is not installed, or blocks on interactive input, do not re-invoke it blind and do not answer its prompt — record a **RED** blocker naming the sub-skill and the exact input or decision it needed, and let the hard gate (step 4) stop the run. This mirrors Execute's sub-skill halt catch-all; a bare re-report of "budget still N" with no cause is not an account.
Log each remediation to `.decision-log.md` as you do it. After remediating, run the script from step 1 again and read the new `budget`. Then run step 1b's command again too, unchanged, whether or not a formalize gap was folded in: any remediation may edit a file the kernel reads, and a line it moves leaves step 1b's `judgment_candidates[]` naming the wrong line. Step 3 is seeded from this closing run, not from step 1b's. If it reports a remediable formalize gap the pass has not cleared (a scaffold the pass itself wrote can carry one), fold it in the same way, once, and run both commands one more time, still within this pass. Whatever that run still reports stands for step 4, and step 3 is seeded from it.
## 3. Semantic intervention scan (the part the script cannot do)
The script counts mechanical facts; it cannot read a PRD and tell that a product decision is still open, or read an ADR and tell that an architecture choice is unresolved. That judgment happens now — but **not in your context**. The artifacts this scan reads are the same multi-thousand-token corpus the run is about to delegate to sub-skills; reading them here would make the conductor carry it through the entire unattended Execute phase (Stage 1's "do not open story or planning files for deep reading" rule exists for exactly this trap).
**Delegate the read to one throwaway subagent.** Spawn a single subagent with the artifact paths noted in Stage 1 (the Epic's stories, PRD, ADR/architecture) and, when Stage 1 Cross-Session Recall produced advisories, the typed `records`/`recurrence` output of the Stage 1 filter, as prior-failure **hypotheses to check** (attributed and advisory; re-use that filtered output, which Stage 1 kept as `recall-filter-<run-id>.json` in the run folder, never a second read of the run store). Instruct it to read the corpus and hunt **undecided product or architecture decisions** that an autonomous run would have to *guess*:
- open questions, "TBD" / "TODO: decide" / "to be determined" / "(?)" placeholders on a load-bearing requirement,
- contradictions between PRD and ADR,
- acceptance criteria that presuppose a decision no artifact actually makes,
- a story whose "done" is undefinable from the artifacts,
- a surface the Epic ships that no story composes. This covers a user interface only: a page, screen or other entry point a user reaches. For each one a story creates, some story's acceptance criterion must name the route or parent that renders it. A story scoped to one component honestly says it mounts nothing, so the gap exists only in the union of stories, as an absence no per-story review can see: check the union. An exclusion ("mounts nothing", "no route") must name the story that does the mounting, and that story must carry the matching criterion. Three cases are not this gap: a child component its parent renders in the same story; an Epic that ships components for others to compose (a component library or an SDK); and a mount the exclusion assigns to a named story of another Epic, which is a concern. Any other surface no story composes is a RED of kind `undecided-architecture` (which story mounts it, and where, is a decision the run would otherwise guess), with `source` at the line of the story that creates the surface, so the same gap mints the same id on the next scan.
**Second hypothesis stream: seed the formalize candidates.** Pass that SAME single throwaway subagent a second set of targeted hypotheses alongside the recall advisories: `formalize_check.py`'s `judgment_candidates[]` (from step 2's closing re-run of step 1b's command, so each line is the line as remediation left it) as a **list of each candidate's `id`, `source:line` and `why_machine_cannot_decide`** (the references and the kernel's one-line reason only, never the inlined artifact bodies; the reason is what tells apart two candidates the kernel flags on one line), so the subagent confirms machine-flagged candidates *instead of scanning blind*. The kernel only *flags*; the throwaway subagent *decides*: it must **confirm-or-clear** each seeded `judgment_candidate` into `reds` or `concerns`, never recording one as a RED unprompted, and the entry that answers a seeded candidate carries that candidate's `id`, copied as given, in its `candidate` field, and its `source:line`, copied as given, in `source`. That pair is how the kernel's re-run below knows the candidate was judged. Fail-closed: a `judgment_candidate` the subagent can neither confirm nor clear **defaults to RED** (JUDGMENT), mirroring `gate_eval.py`'s `nfr_status is None → failing`. This adds zero net subagent and zero net conductor context: the same single spawn, the same discarded-context discipline, and the same three-key return object below.
The subagent must return **ONLY this object — no prose, no document quotes beyond the one-line evidence fields**, so you hold the findings while the corpus stays in its discarded context:
```json
{"reds": [{"source": "<artifact path:line>",
"kind": "undecided-product|undecided-architecture|contradiction|undefinable-done",
"decision_needed": "<the exact decision a human must make>",
"evidence": "<one quoted line>",
"candidate": "<only when this answers a seeded judgment candidate: its id, copied as given>"}],
"concerns": [{"source": "<artifact path:line>", "note": "<cosmetic / non-blocking gap, one line>",
"candidate": "<only when this answers a seeded judgment candidate: its id, copied as given>"}],
"advisories_checked": [{"sig": "<the recalled record's id, copied as given>", "status": "recurred|not-observed|unknown"}]}
```
**Retrieving the result on an async-spawn platform.** The contract above assumes a *synchronous* spawn whose return text reaches you directly. If this run spawns the subagent as a **background teammate** instead, its plain-text return is **not** routed back to the conductor, so additionally instruct it to persist this *same* object to a **run-scoped** file, `{workflow.implementation_artifacts}/.preflight-scan-<run-id>.json`, using the `<run-id>` minted in Stage 1 (`epic-<id>-<UTC yyyymmddThhmmssZ>`) so a **prior** run's scan sitting at a shared path can never be misread as this one's, and read *that* file back, or message you the object explicitly. Because the async write may not have landed yet, wait for **this** run's file to appear and never fall back to an older or differently-named one; before feeding the object into the step-4 hard gate, confirm it is this run's scan (its findings reference this Epic, not a prior one). The discarded-context discipline is unchanged: you ingest only the object, never the corpus, which stays discarded in the subagent's context. (The same retrieval rule applies to any subagent this run spawns asynchronously (e.g. a background-delegated Execute `ucg-dev-story` or a gate TEA sub-skill): route its structured result through a file or an explicit message, never an unrouted plain-text return.)
Every `reds` entry is **RED** — it cannot be auto-remediated, because the fix is a human decision, and an unattended run guessing it produces confidently wrong work. A purely cosmetic gap belongs in `concerns`, never RED; recall-derived hypotheses are attributed under `advisories_checked` and are never themselves RED and never block launch. Record each RED finding with its source and the exact decision needed in `.decision-log.md`.
Record each seeded candidate the subagent cleared there too, with its source and the concern's note. A clearing is what lets the kernel's re-run below read `ready`, so the log is where an operator sees what was cleared.
**Identity, the override, and the sidecar are one deterministic step: run the id layer.** Hand the subagent's scan object to `scripts/red_ids.py`, which mints each RED's stable id, inherits the id an earlier scan already recorded for the same finding, applies the resolved-RED override, and writes the surviving reds to the sidecar:
```
uv run {skill-root}/scripts/red_ids.py --scan <the scan object, or - for stdin> --impl-artifacts {workflow.implementation_artifacts}
```
It prints the sidecar it wrote; the `reds` it returns — and only those — are the semantic-scan reds the step-4 hard gate reads. **Do not mint, compare, or edit an id by hand.** The id is a join key between two surfaces that never share a session: this scan mints it, and `/ucg-resolve` records an operator's answer against it days later. Derived in prose, it was a value two independent model invocations had to agree on by hand, and they cannot — the subagent restates `decision_needed` in its own words on every scan, so a re-derived id drifts and the answered RED blocks forever. Code computes it once; everything else reads it.
**A non-zero exit fails the gate.** `red_ids.py` refuses a scan whose reds it cannot mint an id for (a red that is not an object, lacks `kind` or `source`, or has a blank `decision_needed`) and exits non-zero having written nothing. Then step 4 has no reds stream to read, which is not the same as an empty one: the reds clause fails and the run stops. The kernel's re-run below refuses a scan in a shape `red_ids.py` refuses, but it is the exit that fails the gate, whatever its cause: an unreadable `.preflight-reds.json` fails it too, on a scan the kernel reads.
**Three properties of the minted id, because the gate depends on them** (the recipe itself lives in `scripts/red_ids.py`, which is the only thing that should ever compute it). **Line numbers are excluded**, so an answer recorded against an id survives anyone editing above the finding. **The digest of `decision_needed` is what keeps it unique** — one artifact routinely yields several findings of the same `kind`, and on `kind` plus path alone they would collide, so answering one would silently clear the other and open the gate on a question nobody decided. **Recognition is exact**: the same decision restated the same way re-derives the same id, while a decision the scan *rewords* mints a new id and is asked again. That last one is a deliberate refusal, not a gap — every mechanical proxy for "is this the same decision?" can quietly absorb a brand-new decision into an answered one's identity, and a repeated question costs the operator one answer where a swallowed one costs the run its reason for stopping.
**Then apply the resolved-RED override, fail-closed.** Read `{workflow.implementation_artifacts}/.decisions.json` — the answers an operator recorded when resolving a blocked run, shape `{"decisions": [{"id": …, "answer": …, "action": "close|defer"}]}` — and drop from this scan's reds every RED whose `id` is named by an entry whose `action` is `close`. An `action` of `defer` records an answer without resolving it: it clears nothing, and its RED still stands and still blocks. This is what closes the loop — a decision answered by the operator is not asked again at the next preflight.
Three properties of that override, each load-bearing:
- **Match by `id` only.** Never by `source`, never by `evidence` text, never by fuzzy `decision_needed` similarity. A text matcher would suppress a genuinely new RED that merely happens to quote the same line.
- **An override naming no still-present RED is ignored.** A stale answer cannot pre-authorize a finding this scan has not made.
- **An unreadable or unparseable `.decisions.json` clears nothing.** Every scanned RED stands and the gate blocks. A suppression file that cannot be read is not a suppression.
**The sidecar is the durable identity registry.** `{workflow.implementation_artifacts}/.preflight-reds.json` holds `{"reds": [...]}`: **one** file, not per story and not per run, and deliberately **not** run-scoped, unlike the `.preflight-scan-<run-id>.json` retrieval channel above (that one is run-scoped precisely so a prior run's raw scan cannot be misread as this one's). An id that changed every run could not carry an answer across the very re-scan the line-free id exists to survive. Alongside `reds` it carries `resolved`, the ids an operator has closed, as an audit record rather than part of the matching, since a closed decision the scan restates unchanged re-derives to its own id and is suppressed with no lookup at all. The script owns both lists; a RED in the step-3 subagent contract above keeps its four fields (plus the `candidate` id it copies when it answers a seeded candidate), because the RED's own id is added after the scan comes back, never by the subagent.
**Then re-run the readiness kernel on the answered scan.** Step 1b's verdict counts every judgment candidate as still owed, so it reads `blocked` whenever the kernel flagged one, however the subagent judged it. Give the kernel this run's scan object, which carries the subagent's answers by candidate `id` and `source`. Write it to `{workflow.implementation_artifacts}/.preflight-scan-<run-id>.json` first if the async retrieval path above did not already, then run step 1b's command again, unchanged, with `--scan {workflow.implementation_artifacts}/.preflight-scan-<run-id>.json` appended.
A candidate is **judged** when a `reds` or `concerns` entry carries its `id` in `candidate` and its `source` as seeded: it moves to `judged_candidates` (with `judged_as`) and no longer sets `judgment_required`. A confirmed one is a RED the step-4 reds stream already reads, and a cleared one is a concern, so neither is a judgment still owed. A candidate no entry answers stays in `judgment_candidates` and keeps the verdict `blocked`: it is the fail-closed default above, a RED nobody judged. The answers match on that pair, never on `source` alone and never on evidence text. The id is digested from the flagged line's text and the kernel's reason, so two candidates of one kind with the same text and reason in one file share it and only the source tells them apart; the source names a place, which an edit moves, and the id confirms the line there still reads as it did when it was seeded. An entry whose pair names no candidate judges nothing, and a scan the kernel cannot read, or one `red_ids.py` refuses, judges nothing (its `scan` report says `read: false`). This re-run's verdict, not step 1b's, is the one the step-4 hard gate reads.
## 4. Hard gate
**Launch only when ALL hold:**
- post-remediation script `budget == 0` (every mechanical blocker cleared),
- the semantic scan **and the formalize subagent** found **no RED**: the two reds streams unioned (no undecided product/architecture, no unresolvable secret, no confirmed formalize red), where a stream `red_ids.py` never computed (a non-zero exit) fails this clause rather than reading as empty,
- **ultracode** session effort and **Auto Mode** are on (gated to Opus/Sonnet 4.6+; required for unattended xhigh + auto-workflow execution),
- the post-scan formalize_check.py verdict is `ready`, i.e. `mechanical_budget == 0` AND every judgment candidate answered, so that with the second clause the formalize subagent found no RED (a confirmed candidate is a RED that clause reads; a cleared one is a concern). It re-uses the verdict of step 3's kernel re-run on the answered scan, after the step-2 fold-in (not a fresh gate-time check); this clause holds on verdict `ready` and only `ready`, so any other verdict (`blocked`, an un-cleared `remediable`, or an unreadable / absent / unparseable / missing verdict) FAILS the gate under the "If any fails … STOP" disposition below.
If any fails: write the blockers, mechanical and semantic, to `.decision-log.md` with what each needs to clear, remove this run's recall latch (the last paragraph of this step), and **STOP**. Name `/ucg-resolve` as the way back in: it walks the recorded REDs and records the operator's answer against the id `scripts/red_ids.py` minted, which is what step 3's override then reads, so an answered RED is not asked again at the next preflight. An operator closing the loop by hand instead has to re-derive that id, which is exactly what step 3 forbids. Do not launch a partially-ready run; a single guessed architecture decision corrupts the whole Epic. In **headless**, instead emit the blocked JSON in the canonical five-key shape (every key always present; `report` and `deferred_work` are `null` because the run blocked before producing them):
```json
{"status": "blocked",
"skill": "ultracode-goal",
"decision_log": "<path to this run's .decision-log.md>",
"report": null,
"deferred_work": null,
"reason": "<first blocker in the adapter's blocker-list order, one line>"}
```
The log carries the full blocker list. A confirmed **formalize RED** (a formalize-subagent `reds[]` entry unioned into the no-RED clause by step 4) surfaces through this **identical** five-key channel as a semantic-scan RED — no formalize-specific key, no formalize-specific status string. `reason` is the **first blocker in the adapter's blocker-list order** — positional `blockers[0]` flattened to one line (reds carry no severity field), built by the one shared `scripts/headless_envelope.py` `build_headless_envelope` adapter so every headless exit serializes through a single envelope definition. The rich formalize verdict stays a separate script-layer object the adapter consumes; it never nests into the envelope.
Hand the adapter the ordered blocker list: the reds `red_ids.py` returned first (it has dropped every red an operator closed), then the mechanical blockers, then the judgment candidates the kernel's re-run left unanswered. Handed the bare formalize verdict instead, the adapter names a candidate the step-3 scan confirmed (`judged_as: red`) first, at a `ready` verdict too, then the unanswered ones; it cannot see a close, so that form is only for a block where `red_ids.py` never ran.
Pass `impl_artifacts={workflow.implementation_artifacts}` to that call: `scripts/headless_envelope.py` is also the **writer** of `{workflow.implementation_artifacts}/run-result.json`, and this block is a headless terminal like any other, so it leaves its envelope written on disk at that pinned path rather than only in the transcript. Same bytes as the stdout emit (the adapter serializes once), headless only, and best-effort: a failed write logs `WARN run-result-write-failed` and never converts this clean blocked exit into a crash.
**Remove the recall latch before the STOP**, attended or headless, and before the headless emit, so a run that never launched leaves no latch behind it. Run Stage 1's unlatch command once, with this run's id (`references/ingest-and-scope.md`, Cross-Session Recall):
```
uv run {skill-root}/scripts/mem_recall.py unlatch --impl-artifacts {workflow.implementation_artifacts} --run-id <run-id>
```
It removes the latch only when it carries this run's id, and prints `{"removed": ..., "reason": ...}`; log the reason when `removed` is `false`. When the call is refused, or its reason is `unreadable` or starts with `remove-failed`, also log `NOTE recall-unlatch-failed` with the latch path, so the person knows to delete it by hand. Never retry it, and never remove the latch any other way: a latch left in place keeps the guard denying until the next Stage 1 replaces it or the person deletes it by hand, which the guard's deny reason tells them.
## 5. Arm the environment (only when the gate passes)
Do these in order; each must be asserted, not assumed:
- **Epic branch.** Assert you are on `{workflow.epic_branch_prefix}<epic-id>`. When step 1 reported `git_branch`, step 2's remediation already created it, and this is a **re-assertion, not a rebuild** — the same treatment the resume path gives it. Create it here when it does not yet exist — and note that `budget == 0` does **not** by itself put you on it: `git_branch` fires on a protected branch and nothing else, so a run started on some unrelated feature branch clears the gate having never been asked about its branch, and step 2 has no bullet that fires for it. That case lands here, so resolve it here rather than routing back: check out the base this Epic should branch from (a `{workflow.protected_branches}` branch, per execute.md's "off a protected branch" precondition — or the base the operator named in Stage 1) and cut `{workflow.epic_branch_prefix}<epic-id>` from there. Do **not** branch from wherever HEAD happens to sit; an Epic branch cut off an unrelated feature branch carries that branch's uncommitted work into the run's history and makes the branch-deletion rollback destructive. Rollback for this run is git (per-story commits) — `/rewind` checkpoints miss Bash-driven changes, so the branch is the real undo. If the tree is dirty (`git_clean: false`), resolve before branching — the last budget re-run was at the end of step 2, and step 3 has since written its scan sidecar and appended to `.decision-log.md`, so `budget == 0` does **not** imply a clean tree by the time you arrive here (`git_clean` counts untracked files).
- **What the branch does not undo.** Deleting this branch undoes what git tracks. When step 1 reported `impl_artifacts_tracked: false`, git ignores what the run writes under `{workflow.implementation_artifacts}`, so it undoes the code only: the story files the run creates there survive it, and so does every edit to a file there that git does not track (`sprint-status.yaml` or `deferred-work.md`, unless the project tracks them). Whatever that value, the run folder (`.decision-log.md`, a ruling file) and the test-artifacts tree survive too when git ignores them: check a file path inside each with `git check-ignore`, since a rule that ignores a folder's contents does not match the bare folder. Exit 0 means ignored and 1 means not; 128 means the path is outside the repository or beyond a symlink, which git does not track either. The launch briefing says what survives.
- **Purge stale run markers.** Delete any `{workflow.implementation_artifacts}/.escalation-*`, `{workflow.implementation_artifacts}/.on-escalation-fired-*`, `{workflow.implementation_artifacts}/.budget-*`, `{workflow.implementation_artifacts}/.heartbeat-*` and `{workflow.implementation_artifacts}/.stall-*` an earlier run left behind, before the hooks that write them are armed: a stale escalation marker makes this run look like it already escalated, a stale fired-marker silently swallows this run's first escalation ping, which is the one an absent operator is waiting on, and a stale turn counter is already at or past the ceiling, so this run's **first** Stop marks the story at the ceiling, and a resume's step-0 ceiling check escalates it, before it has done a single turn of work, and a stale heartbeat's gap since the PRIOR run would fire this run's stall rule on its first resume about an idle nobody had. Those five dot-prefixed families only. **On a resume, purge nothing.** A resume re-asserts the environment rather than rebuilding it, and the turn counter is the one piece of that environment a resume must inherit: zeroing `.budget-*` on re-entry would hand an in-flight story a fresh ceiling every time it stopped, so a run could evade the budget indefinitely by resuming. A counter the operator has deliberately cleared is a different thing, and `/ucg-resolve` clears exactly that one when it closes a `budget-overrun` or an `operator-evidence-owed` escalation. In particular do **not** delete `escalation-*.json`: the typed sidecar is an operator-facing artifact like `run-status.json` and `run-result.json`, neither of which is purged at arming either, and it is named per story rather than per run, so arming cannot tell a deliberately-pending sidecar from a stale one. A decision the operator chose to leave pending lives in exactly that file, and a prior run's unresolved escalation surfacing at `/ucg-resolve` is correct: it genuinely is still pending. Sidecar staleness is handled at read time instead, by the run-scoped marker scan in `references/execute.md`. **The story pointer is the exception to both rules.** On a fresh run and a resume alike, delete `{workflow.implementation_artifacts}/.current-story`. No stage removes it, Finalize included, so on arrival here it names whichever story an earlier session drove last: once this run's Stop hook is armed, every Stop before this invocation's first step 0 (the launch briefing's included) is booked to that story's counter (on a fresh run, recreating the one this purge just removed), and the freshly armed guard would take that story's persisted tests-ran marker as current. A resume is not exempt, because a run that blocked here and was re-invoked re-enters at this stage as a resume, with an earlier run's pointer still on disk. Deleting it costs nothing a later step needs: step 0 writes it afresh before any implementation, the gate-owed route and the evidence-commit resume each re-set it themselves, and with no pointer the Stop hook counts nothing.
- **Hooks.** Idempotently merge the **PreToolUse** guard (`scripts/hooks/guard_pretooluse.py`) and the **Stop** budget hook (`scripts/hooks/budget_stop.py`) into `{project-root}/.claude/settings.local.json` (gitignored, machine-local, honored after the workspace trust dialog). Re-merge every run: do not assume a prior run left them. A merge that would change nothing makes no write: when the file's UCG entries already match what this run would write (both script paths, the all-tools matcher, the guard item's `"onFailure": "block"`, each command quoted as the templates below write it, and every injected value equal to this run's resolved scalars) and the allowlist entries are present, assert instead of writing. `--assert-armed` alone is not that comparison, because it confirms the injected variables are present, not that their values are this run's. A write that is refused follows "A refused settings write" in step 2.
**Replace, never append.** When the merge writes, it first removes every inner item whose `command` names either script, and then adds this run's, so a prior run's entry (one a skipped disarm left, or one carrying another run's injected env) cannot sit beside the fresh one. `--assert-armed` checks that the script paths appear, not how many entries carry them, so it would pass with both.
**Arm the guard so that a guard that fails refuses the call.** Each UCG inner item is a `command` hook. The guard's item carries `"onFailure": "block"` beside `"type"` and `"command"`; the budget hook's item carries no `onFailure` key. Written out, with `<env>` the `KEY='value'` prefix the env bullet below injects (empty when the process env carries those values):
- guard: `{"type": "command", "command": "<env> uv run '{skill-root}/scripts/hooks/guard_pretooluse.py'", "onFailure": "block"}`
- budget: `{"type": "command", "command": "<env> uv run '{skill-root}/scripts/hooks/budget_stop.py'"}`
With the key, Claude Code refuses the tool call when the guard cannot start (`uv` missing from `PATH`, say), crashes, exits with a code other than 0 or 2, or times out. Without it each of those lets the call run unchecked, because Claude Code reads a hook that failed as no objection. Claude Code honors the key from 2.1.295, the minimum step 1's `cc_version` check enforces, and a resume's `--assert-armed` too; an older one ignores it silently. Write the value exactly `"block"`, in lower case: Claude Code drops a whole item whose `onFailure` is any value other than `"continue"` or `"block"`, so a mistyped one leaves no guard at all. The cost comes with the all-tools matcher below. A guard that cannot run refuses every tool call, Read and Edit included, so the session cannot repair it, and the fix is made outside the session: put `uv` back on `PATH`, or mend whatever else broke, or remove the guard item from `.claude/settings.local.json` by hand as SECURITY.md describes, then resume the run. The Stop budget hook carries no `onFailure`: Claude Code ignores the key on `Stop`, and the budget hook never blocks a stop by design, so it has no failure the key could turn into a refusal. A run armed before this key existed (by UCG 3.x or earlier) has a guard item without it: a fresh preflight replaces that item here, and a resume, which never reaches this stage, re-merges through this bullet when its `--assert-armed` names the missing key (`references/execute.md`, the re-assertion sweep), unless a reason that is the operator's to fix stands beside it (a skills failure, or a Claude Code below the minimum): that resume escalates the story it was about to drive first, and the resume after the operator's fix re-merges.
**Quote each injected value and the script path in single quotes, as the templates do.** Claude Code runs the command through a shell, which splits it at every unquoted space. Left unquoted, a project or skill path that holds a space (a project under `~/My Projects`, say) hands the rest of that path to the shell as the command to run, or to `uv run` as the script, so the hook never starts: Claude Code then refuses every tool call under the guard's key, and the budget hook counts no turn (a command the shell cannot run lets each stop through; a script `uv` cannot find sends each stop back with uv's error, up to eight times in a row, unless the project `uv` syncs first fails to build, or its requirements cannot be satisfied, when `uv` exits 1 and each stop goes through too; a network failure in that sync exits 2, and sends each stop back). Single quotes keep each value and the path one word, as the recall store value is kept (`references/ingest-and-scope.md`); write a single quote inside a value as `'\''`. Quote the value alone, never its name with it: the shell runs `'KEY=a b'` as the command. `--assert-armed` reads each UCG hook command the way the shell splits it, and fails one that would not start its script as `<env> uv run <script>`, that holds a shell operator or redirection (`;`, `||`, `&`, `<`, `2>&1`) outside quotes, or that holds what the shell expands before `uv` starts (a `$` or a backtick outside single quotes, such as `$HOME` or `"$(cat)"`, or a `*`, `?`, `[` or `{` outside quotes).
**Arm the PreToolUse group with a matcher that covers EVERY tool, not just `Bash`.** Use `"matcher": "*"`, or omit the `matcher` key entirely the way the `Stop` group already does. Five of the guard's seven invariants are Bash/git, so `Bash` is the natural choice and it is the choice both known installs made, but the other two, the Cross-Session Recall latch rules, gate other tools too. While a latch is present the guard denies Read, Grep, Glob, Write, Edit, MultiEdit and NotebookEdit calls that name the recall store, the file-tool calls that would change the latch itself, and every claude-mem MCP call. Claude Code only invokes a PreToolUse group for tools its matcher selects, so under `Bash` the hook is never run for any of those calls: the guard would deny each one correctly if it were asked, and it is never asked. Those two then enforce nothing outside Bash while every log line says the hooks are armed, which is the worst of both: a control that reports itself active and is not.
Then **assert the file arms them**: re-read the resolved settings and confirm both script paths appear **and** that the PreToolUse group's matcher is the all-tools form **and** that every guard item carries `"onFailure": "block"` **and** that each UCG command quotes its injected values and script path. A presence-only assertion passes on a `Bash`-only arming, which is exactly the state this bullet exists to prevent. The same assertion is scriptable: `preflight_check.py --assert-armed` performs it (branch, both hooks under their own events, matcher form, the guard's `onFailure`, how the shell splits each UCG command, injected env, the UCG story skills `ucg-create-story` and `ucg-dev-story`, and the Claude Code version against step 1's minimums) in one read and fail-closes with named reasons. Pass `--epic-branch-prefix {workflow.epic_branch_prefix}` and one `--protected-branch <name>` per entry in `{workflow.protected_branches}`, exactly as step 1 does: omit either and it asserts the branch against its hardcoded defaults (`ultracode/epic-`, `main, master`), silently no-opping those overrides and failing a correctly armed run on a false RED. The resume path leans on it (`references/execute.md`), and it is equally valid here. It reads `.claude/settings.local.json`, the file this bullet's arming writes, so an arming that lives in another settings layer fail-closes, which is the correct answer for a control this stage must be able to disarm and re-merge. It certifies that file, not this session: whether this session runs the hooks is what the last bullet of this step proves. Invariants that live only in memory are context, not enforcement, and memory does not block a `git commit`.
- **Inject the hook env from the resolved scalars.** Both hooks read config from env first ("env wins so the conductor can inject per run") and fall back to hardcoded defaults (`main/master`, `25`, `ultracode/epic-`) otherwise, so a `customize.toml` override of any of these **silently no-ops at the enforcement layer** unless you pass it through. Set these on the hook commands (in the `settings.local.json` hook `command`, each value in single quotes as the templates above write them: `KEY='value' uv run '…'`) or in the process env the hooks inherit:
- `ULTRACODE_PROTECTED_BRANCHES='{workflow.protected_branches}'` (comma-separated)
- `ULTRACODE_IMPL_ARTIFACTS='{workflow.implementation_artifacts}'`
- `ULTRACODE_MAX_TURNS='{workflow.max_turns_per_story}'`
- `ULTRACODE_EPIC_BRANCH_PREFIX='{workflow.epic_branch_prefix}'`
- `ULTRACODE_TEST_ARTIFACTS='<the resolved TEA test-artifacts root>'`: deliberately **not** a `{workflow.…}` scalar (no such workflow key exists, and a `{workflow.test_artifacts}` placeholder would never be filled by config resolution). Inject the same root TEA config resolution yields (`scripts/preflight_check.py`, `_tea_artifacts_root`): the tea-config `test_artifacts` value with `{project-root}` substituted (a relative value resolves under the project root), defaulting to `{project-root}/_bmad-output/test-artifacts` when tea config names none. This is the directory the guard reads the story's `atdd-checklist-<story-id>.md` from; leave it unset and the un-skip proof below is out of scope and silently enforces nothing.
- The same PreToolUse guard also enforces the Cross-Session Recall latch from `{workflow.implementation_artifacts}/.mem-state.json`: the merged hook reads it automatically, fail-closed, with no new env var to inject. While a latch is present, whatever its version or colour, it denies every claude-mem call; every tool call that names the recall store, except the two pinned recall scripts (`scripts/mem_recall.py` and `scripts/mem_observation.py` under `uv run` or python); and every tool call that would change the latch itself, except those same scripts. Reading the latch stays allowed. **It enforces nothing unless the matcher above covers every tool**, because most of what it denies is a file-tool or MCP call, and a group matched on `Bash` is never invoked for one. This is the invariant that makes the all-tools matcher load-bearing rather than tidy.
- **Un-skip proof (production only).** With `ULTRACODE_TEST_ARTIFACTS` injected, the guard reads the **staged post-image** of every acceptance-test file the story's `atdd-checklist-<story-id>.md` lists in its `generatedTestFiles` frontmatter (`git show :<path>`) and denies the commit while any of them still contains `test.skip(`. A checklist with no such list, or one that names no JS/TS test file, is scanned whole for test-file paths instead, and a list that cannot be read as a list denies. It proves the marker is absent from the blob being committed, so it fires on a story's *first* commit too, where there is no prior blob to diff against. Before it reads them, the guard refuses any commit while the index holds an intent-to-add entry (`git add -N`, which `references/execute.md` step 2 makes for a story's new files), naming each one: `git show :<path>` reads such an entry as an empty blob, with no `test.skip(` in it, and the commit would leave the file out, so the proof never reads one. Caveat worth stating plainly: **`test.skip(` is a JS/Vitest-specific token** (the Playwright/Vitest form TEA's ATDD generates today, which is web/JS-only), so a pytest (`@pytest.mark.skip`) or Go (`t.Skip()`) stack marks skips differently and this check would not see them. Under `--light` there is no atdd-checklist, so the check stays inert.
- **The commit/push guard anchors on each segment's leading token (`fp-7ac2643`).** The guard splits the command into shell segments and flags one only when `git` is that segment's **leading** token, once leading `VAR=val` assignments, shell keywords and group openers (`if`/`then`/`else`/`fi`, `for`/`while`/`until`/`do`/`done`, `case`/`esac`, `!`, and `(`/`{`, whether spaced or glued to the command name), and known exec wrappers (`env`, `command`, `sudo`, `time`, `nice`, `nohup`, `timeout`, `setsid`, `stdbuf`, `ionice`, `doas`, plus the string payload of a `sh|bash|zsh|dash` invoked with any `-c`-bearing flag cluster, `-lc` and `-cx` included) are stripped, and the subcommand it would then run is exactly `commit` or `push`, or any subcommand that is not one of git's built-in commands (spelled as git spells them), which counts as both, since what an alias runs, or whether an external `git-<name>` command shadows it, cannot be read from the command: so a git alias, even a read-only one (an alias `st` for `status`), and an external command run through git meet the commit and push gates, and the deny says to run the git command an alias stands for, or the external command by its own name. The keyword strip is what keeps a commit inside a compound command (`if true; then git commit …; fi`, `for … do git commit … done`, `( git commit … )`) reachable by the gates: without it a keyword sits in the leading position, the segment classifies as carrying no git write, and the protected-branch, tests-ran, freshness and empty-index gates are all skipped at once. Segment splitting covers `&&`, `||`, `;`, `|`, a newline, **and a lone `&`** (`npm run build & git commit …` is two segments, not one); those separator sets are applied as a **union** rather than merged into one regex, because splitting on `&` or a newline is quote-blind and a lone set would tear `git -c alias.x='a&b' commit` into fragments that each escape detection. So a verb merely *mentioned* inside an `echo`, a log line, or a here-string in a verification command is no longer denied, while a real `FOO=bar git commit`, `sudo git commit` or `timeout 30 git commit` still is: on a `{workflow.protected_branches}` branch both verbs are denied, and on the epic branch, before the story's `.tests-ran-<story_id>` marker exists, a real `git commit` is denied (the marker gate is commit-only: a real `git push` is never marker-gated). Residual, stated rather than hidden: a wrapper **not** on that list (`xargs git commit`, say) leaves a non-`git` leading token and is allowed through, so the tests-ran marker and the remote's branch protection are the nets behind this one. Three shapes still take the older matches-anywhere path and deny on a mention: a segment whose quoting cannot be parsed, one that hides its command inside a `$(…)` substitution or backticks, and, the newest, a **listed** shell wrapper (`sh|bash|zsh|dash`) whose command-string payload cannot be located at all, meaning no `-c`-bearing flag cluster with an operand after it, or nesting deeper than the shell-recursion cap. That third lane exists because locating the payload by the bare token `-c` alone missed every combined form (`bash -lc`, `sh -lc`, `bash -cx`, `zsh -ic`), and a wrapper whose payload went unread classified as carrying no git write and skipped all four commit gates. It is fail-closed in the same direction as the other two, and it has the same cost: `bash <script> "…git commit…"` now denies on the mention, so a verification command's own arguments must not spell a write verb. Two more shapes fail closed. A segment whose command sits behind a run of more than 32 exec wrappers is read through the first 32 only, and counts as both a commit and a push whatever follows them. And a command the guard cannot classify at all, because reading it raised an error, is denied outright, whatever it holds, as is a commit or push whose checks raise one, and so is any other call the guard raises an error while deciding on (an event or a Bash input that is not a JSON object, JSON nested past what Python reads), with the error named, so the guard exits 0 or 2 and nothing else. What it cannot catch itself (an interpreter or `uv` that cannot start, a timeout) Claude Code refuses, under the guard item's `"onFailure": "block"` above; without that key a hook that ends on an error makes no decision, and the command would go through, as one led by about a thousand `env` words once did. **Do not read the anchoring as having eliminated the false-positive class: it narrowed it, and the remainder bites prose about commits in particular.** Markdown prose names identifiers in backticks, and an apostrophe (`don't`) is unbalanced quoting, so a run-log line describing a commit denial routinely hits both fallbacks; a line that *leads* with the verb is a real verb-leading segment and denies on its own, and so does a line that leads with `git` and a word that is not one of git's commands. The rule that avoids all of it: **write prose with Write/Edit, never a Bash heredoc.** The guard's git gates read **Bash command strings alone**, so a decision-log append made with the file tools reaches none of them and no phrasing of the log can trip a gate. Now that the group is armed 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: it denies a file-tool call that names the recall store or would change the run latch, and a decision-log append is neither, so it passes. Do not narrow the matcher back to `Bash` on the strength of this clause: that would leave those rules enforcing nothing. Reserve Bash for commands you actually mean to run. (execute.md step 4 covers the narrower marker-written-in-the-same-compound-command trap.)
- **Allowlist.** Pre-populate the tool allowlist with `{workflow.allowlist_commands}` so the unattended run can run tests/lint/build/commit without a permission prompt that no one is there to approve. Write one `Bash(<entry>:*)` allow rule per entry, with the entry exactly as it stands (`Bash(git worktree:*)` for `git worktree`). That rule matches the entry alone, or the entry, a space and anything after it, which is how `git worktree` covers the gate's `git worktree add <tmp-path> <commit>`. A rule without `:*` matches one exact command, so the stage's own calls would stop for approval. The entries land in the same `settings.local.json`, so a refused write here follows the same rule.
- **Prove this session runs the hooks.** `--assert-armed` proves what `.claude/settings.local.json` holds, not what this session runs: Claude Code's docs say its file watcher normally picks up a settings edit made while a session runs, and that it can miss one, which a restart of the session reloads. So, after the last write above, make one Bash call, exactly `git commit --dry-run`, alone, with no other command, redirection or assignment beside it. `--dry-run` makes git create no commit and run no commit hook, whatever is staged, so the call changes nothing when no guard runs. The purge above removed `.current-story`, so a guard this session runs finds no story on this Epic branch and refuses the call with a reason that holds both `Tests-ran guard: refusing` and `current story (unknown)`. The reason follows a `PreToolUse:Bash hook error:` prefix in the result, so match both anywhere in it. That refusal is the proof: log it to `.decision-log.md` as the expected refusal, and act on nothing it says (write no marker and set no story). It is not a refused call under step 2's "A refused settings write". It stands for the Stop hook too by inference: the Hooks bullet above writes that hook in the same merge as the guard. One residual stands: a guard an earlier arming left loaded when this session started, reading the same implementation-artifacts folder, refuses the call the same way, so the probe proves that a guard runs, not that it runs with the matcher and env this arming wrote. Read any other result this way:
- **Another reason from the guard**, such as `Empty-index guard: refusing`, `Marker-freshness guard: refusing`, `Protected-branch guard: refusing` or a `Tests-ran guard: refusing` that names a story. A guard runs, but it reads a story or a branch this run did not set (an `ULTRACODE_STORY_ID` in Claude Code's own environment, say, or an earlier arming still loaded with another implementation-artifacts folder). Log it and stop, naming the reason. Attended, remove this run's recall latch first, with the unlatch command at the end of step 4, and point the operator at troubleshooting's "Hooks not firing". Headless, record a **RED** blocker naming the reason and stop through step 4's blocked exit; the way back is a new invocation once the cause is cleared, not `/ucg-resolve`.
- **A guard that cannot start**: the refusal names the guard's command with `failed; blocking` or `timed out; blocking`, or shows `uv`'s own error, such as `error: Failed to spawn`. This holds for any call a guard refuses this way, step 2's disarm, the Hooks write, the allowlist write and `--assert-armed` among them, not only the probe. The session runs the guard and the guard cannot run, so it refuses every call after the refused one too, the log write and the unlatch included. Make no further call: stop, and say in your reply what the refusal showed and that troubleshooting's "Every tool call is refused" says how to fix it from outside the session (headless, as the `reason` of step 4's blocked JSON). The next invocation's Stage 1 replaces the latch this run leaves.
- **No refusal from the guard**: git's own output, a permission prompt whatever its answer, a refusal from the permission classifier, or a refusal from another PreToolUse hook, one whose text holds none of the guard's reasons and names none of its commands. PreToolUse hooks run before any permission check, so none of the first three comes from the guard, and the last holds none of its reasons. Re-run `preflight_check.py --assert-armed` as above, which spaces the two calls, then make the call once more; a refusal as above is now the proof. A second call the guard does not refuse means this session does not run the hooks, and the Stop hook, written to the same file, counts no turn either. Log it, then:
- **Attended:** tell the operator the hooks are in the file and this session does not run them, and ask them to quit Claude Code, resume this conversation with **ultracode** effort and Auto Mode on, as at launch, since a resumed session takes the effort and the mode its launch sets, and say continue. `claude --continue --effort ultracode --permission-mode auto` in the project resumes the most recent conversation; when another one in the project is more recent, `claude --resume` with the same two flags lets them pick this one, or they reopen the session in the desktop app. The resumed session reads the file as it starts, and resuming re-runs no part of this stage, so it writes nothing again. Then re-check step 4's session clause (**ultracode** effort and **Auto Mode** on). When it fails, tell the operator which of the two is off, ask them to turn it on and say continue, and re-check it then: this is not step 4's stop, since `/ucg-resolve` has no RED to work for a session setting. Once it holds, re-run `--assert-armed` and the probe, and go on to the briefing only on the refusal above. If the operator declines, or the resumed session still does not refuse the call, stop: remove this run's recall latch first, with the unlatch command at the end of step 4, and point them at troubleshooting's "Hooks not firing".
- **Headless:** record a **RED** blocker (the hooks are in the file, and this session does not run them) and stop through step 4's blocked exit. The way back is a new invocation, not `/ucg-resolve`: a new session reads the file as it starts.
### Launch briefing (interactive only)
This is the moment the human leaves the loop. Before the first unattended action — **interactive runs only; headless skips this subsection entirely** — surface a one-screen briefing so the operator decides "should I let go right now?" with eyes open:
- **What is about to run unattended:** the Epic (id + title), in-scope story count, profile (production / `--light`), and the Epic branch (`{workflow.epic_branch_prefix}<epic-id>`).
- **Read as decomposed children** (only when the readiness check's `checks.decomposed_children` is not empty): each key, and the parent story file its criteria come from. A story inserted above a `done` parent's row reads the same way, and then gets a story file at Stage 3 whose criteria the readiness check never reads; this line is where the operator can catch one.
- **Turn ceiling:** `{workflow.max_turns_per_story}` turns per story, as the Stop hook counts them (one per response). A resumed story already at or over the ceiling (unless only its gate is owed), or a re-loop that would pass it, escalates instead. It sizes stories; it does not cap time or cost.
- **The autonomy line:** state plainly — *"from here I will not ask you anything."*
- **Kill switch:** Ctrl-C, or delete the Epic branch — and note that `/rewind` will not help (its checkpoints miss the Bash-driven changes that make up the run, the same reason the branch is the real undo).
- **What the branch does not undo** (only when step 5's bullet of that name found something git ignores): deleting the Epic branch removes the code and leaves in place what the run wrote where git does not track it: the story files and the untracked edits under `{workflow.implementation_artifacts}` when step 1 reported `impl_artifacts_tracked: false`, and the run folder or the test-artifacts tree when git ignores those. Name what survives; omit this line when git tracks all of it.
- **Where to watch:** the run's `.decision-log.md` (prose account) and `{workflow.implementation_artifacts}/run-status.json` (the machine-readable heartbeat Execute updates as the spine advances).
- **The rendered view of those files:** `/ucg-status` reads them back — heartbeat, decision-log tail, deferred-work ledger, escalation sidecars — and shows the run without touching it. The raw paths above stay for a poller; this is the one for a human checking in.
- **How the run ends:** the last thing every run does is the workflow health check, a terminal self-audit of the friction the run itself hit, so the workflow improves from having been used. **Attended, it presents every finding and halts**: the run comes back to you at the close, so "unattended" ends there rather than at the last story.
- **Optional diff viewer:** when `hunk` is detected on PATH, the surfaces that name a commit suggest `hunk show <commit>` to read one story's diff and `hunk diff {workflow.epic_branch_prefix}<epic-id>` to read the whole branch. Absent `hunk`, nothing is printed and behavior is unchanged — it is never installed, never checked for at launch, and its absence is never warned about.
Then **one soft confirm** to cross the line. With `--yes`, skip the confirm and launch straight through, but **still print the briefing** so the operator has the record. Headless never reaches this subsection. If the operator declines, the run stops here: remove this run's recall latch first, with the unlatch command at the end of step 4, then stop.
## Progression
Proceed to `references/define-done.md` only after the gate passed AND the Epic branch, both hooks (asserted in the file, and proven running by step 5's last bullet), and the allowlist are in place, all of it recorded in `.decision-log.md`, that bullet's result included. If the gate did not pass, the run has stopped here (interactive) or returned blocked JSON (headless); there is no progression.
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 |