bmad-module-ultracode-goal 5.0.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,7 +19,7 @@
19
19
  "name": "bmad-module-ultracode-goal",
20
20
  "source": "./",
21
21
  "description": "Supercharges BMAD with Claude Code's Auto Mode, Auto Memory, and hooks: autonomous Epic execution to a machine-checked, TEA-gated Definition-of-Done. Execute Epics. Accumulate Knowledge. Deliver Outcomes.",
22
- "version": "5.0.0",
22
+ "version": "6.0.0",
23
23
  "author": {
24
24
  "name": "Armel"
25
25
  },
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  title: Stability and Public Contract
3
- description: "The 5.x stability posture: which CLI, config, JSON, and gate surfaces are the supported public contract, what a major costs, and everything that is @internal and free to change."
3
+ description: "The 6.x stability posture: which CLI, config, JSON, and gate surfaces are the supported public contract, what a major costs, and everything that is @internal and free to change."
4
4
  ---
5
5
 
6
- > **Status:** 5.x. The surfaces below are the public contract. Per [Semantic Versioning 2.0.0](https://semver.org/), a breaking change to any of them requires a MAJOR bump; everything marked `@internal` may change in any release. This document is what a consumer pins against.
6
+ > **Status:** 6.x. The surfaces below are the public contract. Per [Semantic Versioning 2.0.0](https://semver.org/), a breaking change to any of them requires a MAJOR bump; everything marked `@internal` may change in any release. This document is what a consumer pins against.
7
7
 
8
- This is the stability posture for `bmad-module-ultracode-goal` at `5.x`. It enumerates the surfaces a downstream consumer or automator may reasonably depend on, versus everything else, which is `@internal`.
8
+ This is the stability posture for `bmad-module-ultracode-goal` at `6.x`. It enumerates the surfaces a downstream consumer or automator may reasonably depend on, versus everything else, which is `@internal`.
9
9
 
10
10
  ## Public contract
11
11
 
@@ -130,4 +130,4 @@ flowchart LR
130
130
 
131
131
  ## Why the hooks live in settings.local.json
132
132
 
133
- The PreToolUse and Stop hooks are auto-merged into `{project-root}/.claude/settings.local.json` (machine-local, gitignored, honored after the workspace trust dialog), not into a committed settings file or memory. The reasoning: these hooks are **enforcement, not context**. A committed hook would impose this module's commit guard on every contributor and every unrelated session in the repo; a hook in memory would not block a commit at all. The machine-local file scopes enforcement to the machine actually running the unattended Epic, and the gitignore keeps it out of shared history. The skill re-merges them every run (idempotently) and asserts they are active before the run goes unattended; it does not assume a prior run left them in place. The guard's entry carries `"onFailure": "block"` (Claude Code 2.1.295 and later), so a guard that cannot start, crashes or times out refuses the tool call instead of letting it through: an enforcement layer that fails open when it breaks is no enforcement layer, and the price is that a broken guard stops the session until someone fixes it. Because the file is machine-local and executes on your machine, review what is merged; see [SECURITY.md](https://github.com/armelhbobdad/bmad-module-ultracode-goal/blob/main/SECURITY.md).
133
+ The PreToolUse and Stop hooks are auto-merged into `{project-root}/.claude/settings.local.json` (machine-local, gitignored, honored after the workspace trust dialog), not into a committed settings file or memory. The reasoning: these hooks are **enforcement, not context**. A committed hook would impose this module's commit guard on every contributor and every unrelated session in the repo; a hook in memory would not block a commit at all. The machine-local file scopes enforcement to the machine actually running the unattended Epic, and the gitignore keeps it out of shared history. The skill re-merges them every run (idempotently), checks the file, and then proves that the running session runs the guard before the run goes unattended, since Claude Code's file watcher can miss an edit made while a session runs; it does not assume a prior run left them in place. The guard's entry carries `"onFailure": "block"` (Claude Code 2.1.295 and later), so a guard that cannot start, crashes or times out refuses the tool call instead of letting it through: an enforcement layer that fails open when it breaks is no enforcement layer, and the price is that a broken guard stops the session until someone fixes it. Because the file is machine-local and executes on your machine, review what is merged; see [SECURITY.md](https://github.com/armelhbobdad/bmad-module-ultracode-goal/blob/main/SECURITY.md).
@@ -91,7 +91,7 @@ flowchart TD
91
91
 
92
92
  Each recall call is attempted once and never retried. A run whose recall turned off along the way says so in its report, with the tokens under [troubleshooting](#troubleshooting).
93
93
 
94
- **What a record holds.** The Epic, the run id, the repo fingerprint, the gate status and verdict, the root-cause signatures (each with a class from a fixed taxonomy and an artifact path), the count of deferred items, the advisories the run consumed with whether they recurred, the time, and the project's folder name for display. Free text is redacted before it is written. A run that blocked with no gate status (it escalated or handed off before a gate ran, or its gate could not be read) writes a record with gate status `NOT_EVALUATED` and verdict `blocked`, so the next run sees that it blocked; a `WAIVED` outcome is written too. A resume that stops because the story's escalation is still open names no root cause in its record: the run that raised the escalation recorded it, so stopping again on one unanswered decision does not count as recurring. `NOT_EVALUATED` with any other verdict writes no record.
94
+ **What a record holds.** The Epic, the run id, the repo fingerprint, the gate status and verdict, the root-cause signatures (each with a class from a fixed taxonomy and an artifact path), the count of deferred items, the advisories the run consumed, each named by the run id of the record it read, with whether that record's root cause recurred (`yes` when a root cause outside the `other` class is in both records, `no` when that record names one and this run shares none, `unknown` otherwise), the time, and the project's folder name for display. Free text is redacted before it is written. A run that blocked with no gate status (it escalated or handed off before a gate ran, or its gate could not be read) writes a record with gate status `NOT_EVALUATED` and verdict `blocked`, so the next run sees that it blocked; a `WAIVED` outcome is written too. A resume that stops because the story's escalation is still open names no root cause in its record: the run that raised the escalation recorded it, so stopping again on one unanswered decision does not count as recurring. `NOT_EVALUATED` with any other verdict writes no record.
95
95
 
96
96
  **When the store cannot take a record.** The record waits in `mem-outbox.<run_id>.jsonl` in the implementation artifacts folder, and the run logs `WARN mem-write-deferred`. The next run that reaches Finalize with a green latch drains it, keeping its original time. A deferred record older than 14 days is dropped, and one whose drain fails three times moves to `mem-outbox.dead.jsonl`, with `WARN mem-write-dead-lettered`. No drain replays that file.
97
97
 
@@ -70,7 +70,7 @@ This is the load-bearing gate, because after it the run goes unattended. The pos
70
70
  2. **Auto-remediation pass**: clear each remediable blocker, then re-run the check so `budget` reflects the fixes: create the Epic branch when the run started on a protected branch (it is a remediable, budget-counted blocker, so it has to clear here rather than at arming), scaffold the test framework (`bmad-testarch-framework`), scaffold the CI quality pipeline (`bmad-testarch-ci`, production only, strictly *after* the framework), generate missing acceptance criteria (`ucg-create-story`), pre-create the TEA output dirs, de-duplicate `project-context.md` when there is more than one (a missing one is logged, never generated), ensure `sprint-status.yaml` is present, force TEA **Create** mode, and prompt once (interactively) for any secrets.
71
71
  3. **Semantic intervention scan**: the part the script cannot do: read the PRD and ADR for undecided product/architecture decisions, contradictions, acceptance criteria that presuppose an unmade decision, or a story whose "done" is undefinable. Any such item is **RED** and cannot be auto-remediated, because the fix is a human decision.
72
72
 
73
- The run launches **only** when all hold: post-remediation `budget == 0`, the semantic scan found no RED, and ultracode session effort plus Auto Mode are on. Then the skill arms the environment: asserts the Epic branch off `epic_branch_prefix` (already created during remediation when the run started on a protected branch), merges the PreToolUse and Stop hooks into `.claude/settings.local.json` (asserting they are active, and injecting the resolved config into their env), and pre-populates the allowlist. On an attended run it prints the launch briefing and takes one soft confirm. See [`references/preflight.md`](https://github.com/armelhbobdad/bmad-module-ultracode-goal/blob/main/skills/ultracode-goal/references/preflight.md).
73
+ The run launches **only** when all hold: post-remediation `budget == 0`, the semantic scan found no RED, and ultracode session effort plus Auto Mode are on. Then the skill arms the environment: asserts the Epic branch off `epic_branch_prefix` (already created during remediation when the run started on a protected branch), merges the PreToolUse and Stop hooks into `.claude/settings.local.json` (checking the file, and injecting the resolved config into their env), pre-populates the allowlist, and then proves the session runs the hooks: one `git commit --dry-run`, which creates no commit, must be refused by the guard, or preflight stops. On an attended run it prints the launch briefing and takes one soft confirm. See [`references/preflight.md`](https://github.com/armelhbobdad/bmad-module-ultracode-goal/blob/main/skills/ultracode-goal/references/preflight.md).
74
74
 
75
75
  ### Stage 3: Define Done
76
76
 
@@ -78,7 +78,7 @@ Turn the Epic's acceptance criteria into **executable, red-phase acceptance test
78
78
 
79
79
  ### Stage 4: Execute
80
80
 
81
- Drive each in-scope story from its red-phase tests to a green, committed state. Execution is the **sequential `/goal` spine**; per story, in sprint order: set the current story (so the PreToolUse hook can find its marker) → `ucg-dev-story` implements the feature and un-skips the story's ATDD tests → run tests/lint/build and **print the raw output** as evidence → (production) `bmad-testarch-test-review` then `bmad-code-review` → check the commit message against the staged diff (`claim_check.py` lists each path it names that the commit does not touch) and soften any claim the diff's own new lines make that no evidence shows → commit at green (one implementation commit per green story; the gate's commits follow it: a test backfill when automate makes one, then the evidence) → **re-run the suite at this cycle's scope on the committed HEAD (a story only advances off a full-scope sweep)** and print it, because a story's new files are untracked until the commit, so a tracked-files conformance gate can only red once they land; a red here means the story is not done and must be remediated and re-committed before it advances. The conductor writes a per-story `/goal`-style condition that encodes the Definition-of-Done and carries the literal "…or stop after N turns" escape clause, and records it in the decision log. A live `/goal` runs only when you start one, on your own condition, because the conductor cannot start `/goal` itself. The Stop hook records a turn count, once per response, which the conductor reads before each story and each re-loop. The printed evidence keeps the run judgeable mid-flight, but **passing the `/goal` condition is not completion**; the authoritative verdict is Stage 5. As the spine advances it overwrites a `run-status.json` heartbeat for pollers. See [`references/execute.md`](https://github.com/armelhbobdad/bmad-module-ultracode-goal/blob/main/skills/ultracode-goal/references/execute.md).
81
+ Drive each in-scope story from its red-phase tests to a green, committed state. Execution is the **sequential `/goal` spine**; per story, in sprint order: set the current story (so the PreToolUse hook can find its marker) → `ucg-dev-story` implements the feature and un-skips the story's ATDD tests → run tests/lint/build and **print the raw output** as evidence → (production) `bmad-testarch-test-review` then `bmad-code-review` → check the commit message against the staged diff (`claim_check.py` lists each path it names that the commit does not touch) and soften any claim the diff's own new lines make that no evidence shows → commit at green (one implementation commit per green story; the gate's commits follow it: a test backfill when automate makes one, then the evidence) → **re-run the suite at this cycle's scope on the committed HEAD (a story only advances off a full-scope sweep)** and print it, because a story's new files are untracked until the commit, so a tracked-files conformance gate can only red once they land; a red here means the story is not done and must be remediated and re-committed before it advances, except that a red in a case outside the story's changes, whose cause shows inside that test, and that a second sweep at the same commit does not repeat, is logged as flaky and parked on the ledger, with nothing committed. The conductor writes a per-story `/goal`-style condition that encodes the Definition-of-Done and carries the literal "…or stop after N turns" escape clause, and records it in the decision log. A live `/goal` runs only when you start one, on your own condition, because the conductor cannot start `/goal` itself. The Stop hook records a turn count, once per response, which the conductor reads before each story and each re-loop. The printed evidence keeps the run judgeable mid-flight, but **passing the `/goal` condition is not completion**; the authoritative verdict is Stage 5. As the spine advances it overwrites a `run-status.json` heartbeat for pollers. See [`references/execute.md`](https://github.com/armelhbobdad/bmad-module-ultracode-goal/blob/main/skills/ultracode-goal/references/execute.md).
82
82
 
83
83
  ### Stage 5: Gate
84
84
 
@@ -48,6 +48,8 @@ flowchart TD
48
48
  - **Story skills not installed.** The run delegates story creation to `ucg-create-story` and implementation to `ucg-dev-story`, the story skills UCG ships in place of BMAD Method's deprecated `bmad-create-story` and `bmad-dev-story`. UCG's installer copies them beside the `ultracode-goal` skill, so a missing one means a partial or older UCG install, or an install from the plugin marketplace alone, which ships only the `ultracode-goal` skill. The `story_skills` blocker is non-remediable: the run neither installs them nor works around them. Its detail names the fix, `npx bmad-module-ultracode-goal update` from the project root (`install` where UCG was never installed there). BMAD's own shims, installed with `--shims`, do not satisfy it (see [Prerequisites](./getting-started.md#prerequisites)). The same check runs on every resume, so a story skill deleted mid-Epic, by hand or by an install interrupted while it re-copies the UCG skills, stops the next spawn instead of letting it improvise.
49
49
  - **TEA skills not installed.** The run delegates test design, acceptance tests, review and the gate to TEA's `bmad-testarch-*` skills. Production needs all eight. `--light` needs three: `bmad-testarch-framework`, `bmad-testarch-test-design` and `bmad-testarch-trace`. The `tea_skills` blocker is non-remediable: the run never installs TEA. UCG supports BMAD 6 with TEA 1.27.x, which BMAD Method 6.12.2 and later install. Add or repair TEA from the project root with `npx bmad-method install`, with the `tea` module selected, then re-run. If the detail says it found `bmad-tea-*` skills instead, the project has TEA 3.0 or later, which renamed the skills UCG calls. UCG does not support it yet: install TEA 1.27.x through BMAD 6 instead (see [Prerequisites](./getting-started.md#prerequisites)). Preflight checks skill names, not the TEA version. TEA 2.x moved to BMAD 7's module format but kept the `bmad-testarch-*` names, so preflight does not catch it, though UCG does not support it either. Preflight checks these skills at launch only. A TEA skill removed mid-Epic escalates the story that calls it.
50
50
 
51
+ - **This session does not run the hooks.** Preflight's last arming step proves that the session runs the hooks it wrote, and stops before the launch when it does not. See [Hooks not firing](#hooks-not-firing).
52
+
51
53
  The decision log carries the full blocker list with what each needs to clear. Read it, clear the items, re-run.
52
54
 
53
55
  ## gate_eval reports blocked / escalate on a missing gate-decision.json
@@ -75,12 +77,17 @@ A per-story gate can return `reloop` with a `PASS` gate status when a cap fired
75
77
 
76
78
  ## Hooks not firing
77
79
 
78
- **Symptom.** A commit lands on a protected branch, or a commit lands before a story's tests ran: the invariants the PreToolUse hook should enforce did not block.
80
+ **Symptom.** A commit lands on a protected branch, or a commit lands before a story's tests ran: the invariants the PreToolUse hook should enforce did not block. Or preflight stops before the launch, saying the hooks are in `.claude/settings.local.json` and this session does not run them.
79
81
 
80
82
  **What to check.**
81
83
 
82
84
  - **Older Claude Code.** The hook returns a `deny` decision in the hook JSON and *also* exits 2 with the reason on stderr precisely so older clients that ignore the JSON still block. If neither path fired, the client may not be honoring PreToolUse hooks at all. Update Claude Code.
83
- - **`settings.local.json` not merged.** The hooks are merged into `{project-root}/.claude/settings.local.json` at preflight, and the skill asserts they are active before going unattended. If the file wasn't merged (or the workspace trust dialog wasn't accepted), the hooks aren't loaded. Re-run preflight; verify the two hook entries are present in the resolved settings.
85
+ - **`settings.local.json` not merged.** The hooks are merged into `{project-root}/.claude/settings.local.json` at preflight. Before going unattended, preflight checks the file, then proves this session runs them with one `git commit --dry-run` that the guard must refuse. If the file wasn't merged (or the workspace trust dialog wasn't accepted), the hooks aren't loaded. Re-run preflight; verify the two hook entries are present in the resolved settings.
86
+ - **Hooks written while the session ran, and not loaded.** Preflight writes the hooks while Claude Code runs, and Claude Code's file watcher normally picks that edit up but can miss it. Preflight's probe catches this: its `git commit --dry-run` creates no commit, a guard the session runs refuses it with `Tests-ran guard: refusing` and `current story (unknown)`, and when it is not refused twice, preflight stops. Attended, it asks you to quit Claude Code and resume the conversation with ultracode effort and Auto Mode on, as you launched it, since a resumed session takes the effort and the mode its launch sets, and then to say continue: `claude --continue --effort ultracode --permission-mode auto` in the project resumes the most recent conversation, `claude --resume` with the same two flags lets you pick this one when another in the project is more recent, or reopen it in the desktop app. The resumed session reads the file as it starts. When either setting is off there, preflight names it and asks you to turn it on and say continue. A headless run stops with a RED blocker: invoke it again, since a new session reads the file as it starts. In the session, `/hooks` lists the hooks it loaded.
87
+ - **A setting that keeps the file's hooks from running.** When a resumed or a new session still does not refuse the probe, something other than the file watcher keeps the hooks from running: `disableAllHooks` set in another settings layer or in a `--settings` file, `allowManagedHooksOnly` in managed settings, a `--setting-sources` that leaves out `local`, or `--bare`, which skips hooks. Clear it, check that `/hooks` lists the guard, then invoke the run again.
88
+ - **A story set in Claude Code's environment.** A guard that runs can also let the probe through: with `ULTRACODE_STORY_ID` in the environment Claude Code runs hooks with, naming a story whose tests-ran marker is fresh, and something staged, the guard allows the call, and preflight reads that as a session that does not run the hooks. Unset the variable where you start Claude Code, start it again, then invoke the run again.
89
+ - **The probe refused for another reason.** Any guard reason other than `Tests-ran guard: refusing` with `current story (unknown)` means a guard runs but reads a story or a branch this run did not set: an `ULTRACODE_STORY_ID` in the environment Claude Code runs hooks with, or a guard from an earlier arming still loaded with another implementation-artifacts folder. For the variable, unset it where you start Claude Code, then start Claude Code again; for an earlier arming, quit and start Claude Code again so it loads the file this run wrote. Then invoke the run again.
90
+ - **A refusal from another hook.** A probe result that names another hook's command in brackets and holds no guard reason, such as `PreToolUse:Bash hook error: [<its command>]: <its stderr>`, is that hook's refusal, so the guard did not refuse the call. Check `/hooks` for the guard, as the bullets above say.
84
91
  - **A `customize.toml` override that silently no-ops.** Both hooks read config from env first and fall back to hardcoded defaults (`main`/`master`, `25`, `ultracode/epic-`). A `protected_branches` or turn-budget override in `customize.toml` only reaches the hook if preflight injected it into the hook env (`ULTRACODE_PROTECTED_BRANCHES`, etc.). If your custom protected branch isn't being guarded, the override didn't reach the enforcement layer. Confirm preflight passed it through.
85
92
 
86
93
  ## Every tool call is refused
@@ -95,7 +102,7 @@ A per-story gate can return `reloop` with a `PASS` gate status when a cap fired
95
102
  - **No Python `uv` can use.** `uv` cannot start a Python the script's header allows.
96
103
  - **The guard ran past its timeout.** Claude Code's default for a command hook is 600 seconds; the message then says `timed out`.
97
104
 
98
- A refusal the guard makes itself reads differently: it starts with the guard's own reason (`Commit/push guard: …`, `Protected-branch guard: …`, `UltraCode-Goal guard: …`) and names what to fix. That is the guard deciding, not failing.
105
+ A refusal the guard makes itself reads differently: in place of `[<command>]: failed; blocking`, it carries the guard's own reason (`Commit/push guard: …`, `Protected-branch guard: …`, `UltraCode-Goal guard: …`) and names what to fix. That is the guard deciding, not failing.
99
106
 
100
107
  **What you do.** Fix it from outside the session, since the session cannot run a tool:
101
108
 
@@ -21,7 +21,7 @@ UltraCode Goal answers each shortcut with a layer the model cannot override, exc
21
21
 
22
22
  **1. Deterministic gate truth.** Completion is decided by `scripts/gate_eval.py`, which reads TEA's `gate-decision.json` and maps its gate status to a routing verdict: `PASS`/`WAIVED` advance, `CONCERNS` defers, `FAIL` re-loops, `NOT_EVALUATED` escalates. The script never re-derives TEA's thresholds and never consults the transcript; it reads the artifact as given. The model produces evidence; the script reads the verdict. They are different things on purpose. See the [gate model](./gate-model.md).
23
23
 
24
- **2. Hooks as invariants.** The invariants that must hold (no commit on a protected branch, no commit before a story's tests have actually run green, and five more covering marker freshness, an empty staged index, un-skipped acceptance tests, and two for Cross-Session Recall) live in a **PreToolUse** hook, not in memory. The hook inspects each `git commit`/`git push`, and every other tool call while a run latch is present, and denies the call when any of them is violated. It is merged into `.claude/settings.local.json` at preflight and asserted active before the run goes unattended. A denied commit is enforcement; a remembered rule is not. See [architecture](./architecture.md).
24
+ **2. Hooks as invariants.** The invariants that must hold (no commit on a protected branch, no commit before a story's tests have actually run green, and five more covering marker freshness, an empty staged index, un-skipped acceptance tests, and two for Cross-Session Recall) live in a **PreToolUse** hook, not in memory. The hook inspects each `git commit`/`git push`, and every other tool call while a run latch is present, and denies the call when any of them is violated. It is merged into `.claude/settings.local.json` at preflight, and preflight proves that the running session runs it before the run goes unattended. A denied commit is enforcement; a remembered rule is not. See [architecture](./architecture.md).
25
25
 
26
26
  **3. Budget enforcement.** This is the one layer that rests on the conductor following a rule. A **Stop** hook tracks turns against `max_turns_per_story` and writes an escalation marker when it is breached, but it never blocks, and it counts once per response, so re-loops inside one response do not move it. The conductor reads that count before each story and each re-loop, and the gate's re-loop budget turns a `reloop` that would exceed it into an `escalate`. A story that passes its gate after an overrun is not escalated: the gate decides completion, and the overrun is logged as a sizing note. A `/goal` condition's literal "…or stop after N turns" clause binds only when an operator starts a `/goal` (the conductor cannot start one itself), and for `drive_epic.py` spawns a `--session-timeout` wall clock is the backstop. See [how it works](./how-it-works.md).
27
27
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "bmad-module-ultracode-goal",
4
- "version": "5.0.0",
4
+ "version": "6.0.0",
5
5
  "description": "BMAD module — Run a BMAD Epic autonomously to a machine-checked, TEA-gated Definition-of-Done.",
6
6
  "keywords": [
7
7
  "bmad",
@@ -47,7 +47,19 @@ recomputes the readiness verdict. Each verdict and remediation lands in
47
47
  for this Epic when one exists (appending a session entry), otherwise create
48
48
  `epic-<id>-<UTC yyyymmddThhmmssZ>` for this standalone check. That resolved path is
49
49
  what the Headless `decision_log` key carries, so two invocations over the same Epic
50
- cannot scatter their verdicts across two files.
50
+ cannot scatter their verdicts across two files. Append to the log with Write/Edit,
51
+ never a Bash heredoc: a heredoc puts the log's prose into a Bash command string, and the
52
+ PreToolUse guard's git gates read that string as commands
53
+ (`{ucg-root}/references/execute.md`, step 4, gives the reason). Once the log is too large
54
+ to Read affordably, do not Read it, since both file tools refuse a file this session has
55
+ not Read. Write the entry instead to a new file beside the log,
56
+ `<run folder>/dlog-slice-formalize-<n>.md`, where `<run folder>` is the resolved folder
57
+ above in full and `<n>` is one past the highest number a `dlog-slice-formalize-*.md` in
58
+ it already carries (`1` when there is none), so the name is new for every append. Then
59
+ append it in one Bash call, with both paths in full:
60
+ `cat "<run folder>/dlog-slice-formalize-<n>.md" >> "<run folder>/.decision-log.md"`. Keep
61
+ the slice rather than deleting it: it is the only copy of the entry if the append is
62
+ interrupted.
51
63
 
52
64
  ## On Activation
53
65
 
@@ -165,7 +177,8 @@ its `detail`: record it as a non-remediable blocker naming the kind and route to
165
177
  kind blocks loudly instead of being guessed at, and the halt catch-all below then covers
166
178
  the never-remediated case as well as the remediated-but-unfixed one.
167
179
 
168
- Log each remediation to `.decision-log.md` as you apply it. Never
180
+ Log each remediation to `.decision-log.md` as you apply it, appended the way Conventions
181
+ says. Never
169
182
  auto-remediate a `judgment_candidate`, and never auto-remediate a
170
183
  `remediable: false` mechanical gap (an unreadable artifact cannot be fixed from its
171
184
  own unreadable content).
@@ -226,7 +239,7 @@ one-line evidence fields:
226
239
  "candidate": "<only when this answers a seeded judgment candidate: its id, copied as given>"}],
227
240
  "concerns": [{"source": "<artifact path:line>", "note": "<cosmetic / non-blocking gap, one line>",
228
241
  "candidate": "<only when this answers a seeded judgment candidate: its id, copied as given>"}],
229
- "advisories_checked": [{"sig": "<advisory id>", "status": "recurred|not-observed|unknown"}]}
242
+ "advisories_checked": [{"sig": "<the recalled record's id, copied as given>", "status": "recurred|not-observed|unknown"}]}
230
243
  ```
231
244
 
232
245
  **Mint ids before mapping, and apply the operator's closes.** Hand the returned scan
@@ -38,7 +38,9 @@ more than a note-taker.
38
38
  `{project-root}/_bmad-output/ultracode-goal/<run folder>/.decision-log.md` — the module's
39
39
  default runs root, which no `customize.toml` scalar carries. Write to the folder whose
40
40
  Epic the enumerated artifacts belong to; ask the operator when more than one could be it,
41
- and when none exists append nothing rather than create a stray log.
41
+ and when none exists append nothing rather than create a stray log. Append to it with
42
+ Write/Edit, never a Bash heredoc, as section 3 says, which also covers a log too large to
43
+ Read.
42
44
 
43
45
  ## On Activation
44
46
 
@@ -78,8 +80,9 @@ and anything not written down is not a pending decision this surface can honor.
78
80
  genuinely still pending: the arming step deliberately does not purge `escalation-*.json`,
79
81
  so a decision an operator chose to leave open survives to this pass.
80
82
  2. **The preflight RED sidecar** — `{workflow.implementation_artifacts}/.preflight-reds.json`,
81
- shape `{"reds": [...]}`. **One** file holds every still-pending preflight RED. There is
82
- no second RED sidecar and no per-story one: a per-story or per-run RED file would carry
83
+ shape `{"reds": [...]}`. **One** file holds the REDs the last preflight left pending, from
84
+ whichever Epic ran it (section 2 says what that means for an entry no RED carries). There
85
+ is no second RED sidecar and no per-story one: a per-story or per-run RED file would carry
83
86
  an id that changed between scans, and an id that changes cannot carry an answer forward.
84
87
  3. **The deferred-work ledger** — `{workflow.deferred_work_path}`, restricted to its
85
88
  `decision:` rows. Those are the rows whose `source` column reads `decision` (as opposed
@@ -114,7 +117,8 @@ For a sidecar the three arguments are its own `kind`, `source` and `decision_nee
114
117
  fields, each passed verbatim: `<artifact path>` is the sidecar's `source` field, its
115
118
  `:line` suffix and all (the id layer strips it), never the path of the sidecar file
116
119
  itself. The resume also reads a close keyed by the sidecar file's own path as closed,
117
- since earlier passes keyed some that way, but never mint a new id from that path.
120
+ since earlier passes keyed some that way, but never key an answer by an id minted from
121
+ that path: section 2 mints those ids only to recognize an entry already recorded.
118
122
 
119
123
  It prints the id and touches nothing. **A ledger `decision:` row is keyed by the same
120
124
  call** — kind `decision`, the ledger path, and the row's reason — because the row's own
@@ -146,24 +150,56 @@ Re-asking a question the operator already **resolved** is the exact failure this
146
150
  exists to remove.
147
151
 
148
152
  An entry recorded with `action` `defer` is the opposite case: it is a parked question, not
149
- an answered one. Present it again, and replace its entry in place when the operator decides
150
- it, carrying its answer forward (section 3). Suppressing a deferred item would deadlock
151
- the run outright: `defer` clears nothing,
152
- so the next preflight still blocks on that RED (`{ucg-root}/references/preflight.md`,
153
- step 3, drops only the ids whose `action` is `close`), while this surface, the only one that
154
- can answer it, would never ask again. The scan blocks forever on a question the operator is
155
- no longer offered.
153
+ an answered one. Present it again while an item this pass enumerated carries its `id`, and
154
+ replace its entry in place when the operator decides it, carrying its answer forward
155
+ (section 3). Suppressing a deferred item would deadlock the run outright: `defer` clears
156
+ nothing, so the next preflight still blocks on that RED
157
+ (`{ucg-root}/references/preflight.md`, step 3, drops only the ids whose `action` is
158
+ `close`), while this surface, the only one that can answer it, would never ask again. The
159
+ scan blocks forever on a question the operator is no longer offered.
156
160
 
157
161
  An entry with no `action`, or with an `action` that is neither `close` nor `defer`, is
158
- pending as well. An earlier version of this surface wrote some entries that way, and
159
- preflight drops none of their ids, so their questions still block. Present it again, as
160
- you present a deferred one.
162
+ pending as well while an item this pass enumerated carries its `id`. An earlier version of
163
+ this surface wrote some entries that way, and preflight drops none of their ids, so that
164
+ item's question stays open. Present it again, as you present a deferred one.
165
+
166
+ **An item carries an entry's `id` only on an exact match, as written.** A RED carries the
167
+ `id` on its `reds` entry, and a ledger `decision:` row the id the id layer printed for it.
168
+ An escalation sidecar carries the id the id layer printed from its own fields, and one
169
+ more for each spelling of the sidecar file's own path the resume reads a close by
170
+ (`_sidecar_ids` in `{ucg-root}/scripts/preflight_check.py`): its path relative to
171
+ `{project-root}`, its absolute path, that absolute path with its folder's symlinks
172
+ resolved, and the resolved path relative to `{project-root}`, each written with forward
173
+ slashes and, on Windows, with backslashes too. Ask the id layer for each of those with the
174
+ sidecar's own `kind` and `decision_needed`. Mint them only to recognize an entry already
175
+ recorded, never to key an answer: an entry keyed by any of them belongs to that sidecar's
176
+ item.
161
177
 
162
178
  When an item you present already has an entry, show its `answer`, and each earlier answer
163
179
  its `history` holds (section 3), beside the decision needed. Such an answer can hold the
164
180
  operator's whole ruling: they decide on the record as it stands, and may find it already
165
181
  answers the question.
166
182
 
183
+ **An entry no enumerated item carries is orphaned, not pending.** That is an entry whose
184
+ `action` is anything but `close` and whose `id` no item of this pass carries: none of the
185
+ three sources holds its question at this pass, so there is no item to present it with.
186
+ List the orphaned entries after the pending items, apart from them, each with its `id`,
187
+ its `answer` and each earlier answer its `history` holds, and ask nothing about them; the
188
+ record keeps each one as it stands. Say beside that list that a later preflight can raise
189
+ an orphaned entry again and block on it. `.preflight-reds.json` is one project-wide file
190
+ that each preflight replaces, so it holds only the REDs of the last preflight, from
191
+ whichever Epic ran it: a RED one Epic's preflight raised can be gone from it after another
192
+ Epic's preflight, while that first Epic's next preflight can raise it again. An orphaned
193
+ entry whose `id` a later RED, sidecar or ledger row carries is pending again at that pass,
194
+ which asks it.
195
+
196
+ **When a source could not be read in full, call nothing orphaned.** That is an unreadable
197
+ `.preflight-reds.json`, an escalation sidecar that cannot be read or whose fields no id can
198
+ be minted from, or a ledger on disk that cannot be read, or is malformed or a bullet list,
199
+ so it yields no rows here. In that case present every entry that is not a `close` as
200
+ pending, with its `id`, its `answer` and its `history`, since an id that source would carry
201
+ cannot be ruled out.
202
+
167
203
  ## 3. Record the answer, then apply its disposition
168
204
 
169
205
  Every answer lands in `{workflow.implementation_artifacts}/.decisions.json`:
@@ -296,18 +332,39 @@ The two dispositions are genuinely different things, not two names for one:
296
332
  anything**. The artifact stays exactly where it is, the item stays pending, and the next
297
333
  preflight still blocks on it.
298
334
 
299
- Record each answer and its disposition in `.decision-log.md` as you apply it.
335
+ Record each answer and its disposition in `.decision-log.md` as you apply it, with
336
+ Write/Edit and never a Bash heredoc. A heredoc puts decision prose (commit and push verbs,
337
+ backticked names, apostrophes) into a Bash command string, and the PreToolUse guard's git
338
+ gates read that string as commands (`{ucg-root}/references/execute.md`, step 4, gives the
339
+ reason). Once the log is too large to Read affordably, do not Read it, since both file
340
+ tools refuse a file this session has not Read. Write the entry instead to a new file beside
341
+ the log, `{project-root}/_bmad-output/ultracode-goal/<run folder>/dlog-slice-resolve-<n>.md`,
342
+ with `<n>` one past the highest number a `dlog-slice-resolve-*.md` in that folder already
343
+ carries (`1` when there is none): the name has to be new for every append, or Write finds
344
+ the file on disk and asks for the Read again. Then append it in one Bash call, with both
345
+ paths in full:
346
+ `cat "{project-root}/_bmad-output/ultracode-goal/<run folder>/dlog-slice-resolve-<n>.md" >> "{project-root}/_bmad-output/ultracode-goal/<run folder>/.decision-log.md"`.
347
+ Keep the slice rather than deleting it: it is the only copy of the entry if the append is
348
+ interrupted. This holds for every entry the pass writes, the coupled-stories entry above
349
+ included.
300
350
 
301
351
  ## 4. Hand control back to the existing resume
302
352
 
303
353
  `/ucg-resolve` defines no resume of its own. Close the pass by stating what closed, what is
304
354
  still pending, and that anything still pending re-blocks at the next preflight. Name every
305
355
  entry this pass replaced, by `id`, with the earlier answer it carried into `history`, so
306
- the operator sees what the record held before this pass. **Hand back
356
+ the operator sees what the record held before this pass. List the orphaned entries apart
357
+ from both, by `id`, and say that a later preflight can raise any of them again and block
358
+ on it, and that the pass after that preflight asks it. **Hand back
307
359
  only when the pass closed at least one item, or when the operator asks for the resume**: a
308
360
  pass that deferred everything hands into a run blocked on the identical items, and an empty
309
361
  enumeration means the run stopped for a non-decision reason — say so, point at the read-only
310
- `/ucg-status`, and hand nothing back.
362
+ `/ucg-status`, and hand nothing back. A pass that found only orphaned entries is not an
363
+ empty enumeration, so do not say the run stopped for a non-decision reason: the run can
364
+ have stopped on a RED that another Epic's preflight has since dropped from
365
+ `.preflight-reds.json`, and its next preflight raises that RED again. Such a pass closed
366
+ nothing, so point at the read-only `/ucg-status`, as for an empty enumeration, and hand
367
+ back only when the operator asks for the resume.
311
368
 
312
369
  Otherwise hand back to the resume the module already has, which **routes by the last stage
313
370
  the blocked run reached**, not by story. Which branch applies is not a detail this surface
@@ -61,7 +61,7 @@ These exist because the documented mechanics make the intuitive shortcut wrong.
61
61
  | 6 | Finalize | Auto Memory capture, optional retrospective, decision-log audit, report | `references/finalize.md` |
62
62
  | 7 | Health Check | Terminal self-improvement audit — Finalize's close-out loads it; capture real workflow friction | `references/health-check.md` |
63
63
 
64
- Run the stages in order; each routes by the testable conditions stated in its file. The decision log is canonical memory — record scope, the preflight verdict, every gate outcome, and every deferral as you go.
64
+ Run the stages in order; each routes by the testable conditions stated in its file. The decision log is canonical memory: record scope, the preflight verdict, every gate outcome, and every deferral as you go. **Append it with Write/Edit, never a Bash heredoc**, from Stage 1 on: a heredoc puts the log's prose into a Bash command string, and the guard's git gates read that string as commands (`references/execute.md`, step 4, gives the reason). Once the log is too large to Read affordably, do not Read it: Write the entry to a new file beside the log, in the run folder that holds it, `<log folder>/dlog-slice-<label>-<n>.md`, where `<log folder>` is that folder's full path, `<label>` is the story's id for an entry about a story and `stage<k>` for one a stage writes outside a story (`stage1` for Ingest & Scope), and `<n>` is one past the highest number a `dlog-slice-<label>-*.md` there already carries, so the name is new for every append. Then append it in one Bash call, `cat "<log folder>/dlog-slice-<label>-<n>.md" >> "<log folder>/.decision-log.md"`, and keep the slice.
65
65
 
66
66
  ## Headless
67
67
 
@@ -4,11 +4,11 @@ Drive each in-scope story from its red-phase acceptance tests (generated in Stag
4
4
 
5
5
  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.)
6
6
 
7
- Preconditions (asserted, not assumed): you are on the Epic branch (`{workflow.epic_branch_prefix}…`, off a `{workflow.protected_branches}` branch), PreToolUse + Stop hooks are active 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`.
7
+ 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`.
8
8
 
9
9
  **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.
10
10
 
11
- **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. 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.
11
+ **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.
12
12
 
13
13
  **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.
14
14
 
@@ -22,7 +22,7 @@ Preconditions (asserted, not assumed): you are on the Epic branch (`{workflow.ep
22
22
 
23
23
  **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.
24
24
 
25
- **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, then re-gating it in Stage 5, whose trace counts the operator's records. 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").
25
+ **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. 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").
26
26
 
27
27
  **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`:
28
28
 
@@ -62,9 +62,9 @@ Then terminate as the work-bound section below describes for an invocation that
62
62
 
63
63
  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):
64
64
 
65
- 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 **deliberately**: step 5 re-runs the same declared-gate sweep on the committed tree, so a runner or harness built here is still needed there, and one deleted at step 4 gets re-authored verbatim at step 5 — a real, measured cost. **Remove the directory after step 5's re-verify goes green, before the story advances** — never earlier, and never later: the next story's step 0 must not find it.
65
+ 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.
66
66
 
67
- **Evidence never goes in scratch.** The scratch directory is removed before the story advances, while trace, the gate and the story record 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.
67
+ **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.
68
68
 
69
69
  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.)
70
70
  **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.
@@ -82,18 +82,20 @@ For each in-scope story, in sprint order, run this loop (leave out a decomposed
82
82
  - **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.**
83
83
  - **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.
84
84
 
85
- **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 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.
85
+ **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.
86
86
 
87
87
  **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.)
88
88
 
89
89
  **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.
90
90
 
91
+ **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.
92
+
91
93
  **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.
92
94
 
93
95
  **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.
94
96
 
95
97
  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.
96
- 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 in the run folder, `{workflow.implementation_artifacts}/dlog-slice-<story_id>-<n>.md`, where `<n>` 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, `cat <slice> >> .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. 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.
98
+ 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. 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.
97
99
 
98
100
  **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:
99
101
 
@@ -103,7 +105,7 @@ uv run {skill-root}/scripts/claim_check.py --message {workflow.implementation_ar
103
105
 
104
106
  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 or amend step 5 makes.
105
107
 
106
- 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 pre-commit run cannot see a **conformance gate scoped to *tracked* files** — a `git ls-files`-based ref/ownership/architecture-boundary check: a story's **new** files are still untracked at step 2, so the gate skips them and reports green, then reds the instant the commit tracks them (generated or `.gitignore`d files hide the same way). 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 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 — 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.
108
+ 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 pre-commit run cannot see a **conformance gate scoped to *tracked* files** (a `git ls-files`-based ref/ownership/architecture-boundary check): a story's **new** files are still untracked at step 2, so the gate skips them and reports green, then reds the instant the commit tracks them (generated or `.gitignore`d files hide the same way). 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.
107
109
 
108
110
  **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.
109
111
 
@@ -17,7 +17,7 @@ Interactive runs **offer** the retrospective at Epic close (skip it by default i
17
17
 
18
18
  ## Decision-log audit
19
19
 
20
- Walk every entry **this invocation wrote** (scope, preflight verdict, each gate verdict, each deferral, every assumption). On a fresh run that is the whole `.decision-log.md`; on a mature Epic it is not, and must not be — execute.md step 4 forbids Reading the log once it is too large to Read affordably, so the auditable unit there is this session's own `dlog-slice-*.md` files plus what is still in context. Entries from prior invocations were audited by the invocations that wrote them; say that in the accounting below rather than silently narrowing the walk, so a reader can tell a scoped audit from a skipped one. Each entry must resolve to one of three: **captured in the run report** (a primary decision or outcome the user takes away), **captured in the addendum** (a parked alternative or rejected option that needs a home but not the report), or **explicitly marked process noise** (set aside, not silently dropped). End with a shared accounting of how the run's reasoning was handled — not a one-sided polish.
20
+ Walk every entry **this invocation wrote** (scope, preflight verdict, each gate verdict, each deferral, every assumption). On a fresh run that is the whole `.decision-log.md`; on a mature Epic it is not, and must not be: execute.md step 4 forbids Reading the log once it is too large to Read affordably, so the auditable unit there is this session's own `dlog-slice-*.md` files, which sit beside the log in the run folder (never in `{workflow.implementation_artifacts}`), plus what is still in context. Entries from prior invocations were audited by the invocations that wrote them; say that in the accounting below rather than silently narrowing the walk, so a reader can tell a scoped audit from a skipped one. Each entry must resolve to one of three: **captured in the run report** (a primary decision or outcome the user takes away), **captured in the addendum** (a parked alternative or rejected option that needs a home but not the report), or **explicitly marked process noise** (set aside, not silently dropped). End with a shared accounting of how the run's reasoning was handled, not a one-sided polish.
21
21
 
22
22
  ## Run report
23
23
 
@@ -70,12 +70,14 @@ Whichever case applies, repeat in the run report a `NOTE recall-latch-visible` l
70
70
  uv run {skill-root}/scripts/mem_observation.py drain --impl-artifacts {workflow.implementation_artifacts} --store '{workflow.cross_session_recall_store}' --project-root {project-root}
71
71
  ```
72
72
 
73
- 2. **Write this run's record**: epic, run-id (this invocation's own, minted at Stage 1 or at a resume's re-entry and reused verbatim: the record file is named after it), gate-status, verdict, the deferred-work path, any root causes by taxonomy class, and the mechanical `recurred` yes/no for each Stage 1 advisory consumed. Pass no project name: the script takes it from the main worktree's directory, and the store tells repos apart by fingerprint alone. When the run stopped on a story that has no gate status (it escalated or handed off before that story's gate ran, or the gate came back `NOT_EVALUATED`), pass `--gate-status NOT_EVALUATED --verdict blocked`: the script writes that record like any other, so the next run's recall sees that this one blocked. Name a root cause for an escalation as for any blocked run, and none for a handoff. Name none either for a run that stopped on `decision-pending` (a resume that found the re-entry story's escalation still open, per `references/execute.md`): the run that raised that escalation recorded its root cause, and naming it again would make recall count one failure as recurring.
73
+ 2. **Write this run's record**: epic, run-id (this invocation's own, minted at Stage 1 or at a resume's re-entry and reused verbatim: the record file is named after it), gate-status, verdict, the deferred-work path, any root causes by taxonomy class, and one `--advisory` for each record this invocation's own Stage 1 filter call consumed, as the paragraph below the command says. Pass no project name: the script takes it from the main worktree's directory, and the store tells repos apart by fingerprint alone. When the run stopped on a story that has no gate status (it escalated or handed off before that story's gate ran, or the gate came back `NOT_EVALUATED`), pass `--gate-status NOT_EVALUATED --verdict blocked`: the script writes that record like any other, so the next run's recall sees that this one blocked. Name a root cause for an escalation as for any blocked run, and none for a handoff. Name none either for a run that stopped on `decision-pending` (a resume that found the re-entry story's escalation still open, per `references/execute.md`): the run that raised that escalation recorded its root cause, and naming it again would make recall count one failure as recurring.
74
74
 
75
75
  ```
76
- uv run {skill-root}/scripts/mem_observation.py write --impl-artifacts {workflow.implementation_artifacts} --store '{workflow.cross_session_recall_store}' --project-root {project-root} --epic <id> --run-id <run-id> --gate-status <status> --verdict <advance|blocked> --deferred {workflow.deferred_work_path} [--root-cause class=<taxonomy>,path=<artifact>]… [--advisory sig=<s>,recurred=<yes|no|unknown>]…
76
+ uv run {skill-root}/scripts/mem_observation.py write --impl-artifacts {workflow.implementation_artifacts} --store '{workflow.cross_session_recall_store}' --project-root {project-root} --epic <id> --run-id <run-id> --gate-status <status> --verdict <advance|blocked> --deferred {workflow.deferred_work_path} [--root-cause class=<taxonomy>,path=<artifact>]… [--advisory sig=<record-id>]…
77
77
  ```
78
78
 
79
+ Each `--advisory` names one record this invocation's own Stage 1 filter call consumed: `sig` is that record's `id`, the `run_id` of the run that wrote it, copied as given from the attributed advisory Stage 1 logged to `.decision-log.md` (the same `id` the record carries in `recall-filter-<run-id>.json`, when Stage 1 wrote that file). It is never a root-cause signature, a story id or this run's own run id. Pass no `recurred`: the script decides it from the store. It stores `yes` when a root cause whose class is not `other` is in both that record and this run (the same class and artifact path), `no` when that record names such a root cause and this run shares none of them, and `unknown` otherwise: the `id` is not a run id, that record cannot be read or is not this repo's, it names no root cause outside `other`, or this run did not advance and names no root cause (a handoff or a `decision-pending` stop). A matching gate status or verdict is not a recurrence, and preflight's `advisories_checked` status does not feed `recurred`. Pass no `--advisory` on a resume routed into Execute, which makes no filter call, nor when this invocation's filter call was skipped, refused or failed, or consumed no record.
80
+
79
81
  Each call prints one JSON object. Log every line in its `notes` to `.decision-log.md` and carry it into the run report: the `mem-` tokens belong to the write path (`WARN mem-write-deferred` when the store could not take the record and it waits in the outbox for a later drain, `WARN mem-write-dead-lettered` when a parked record failed its third write and moved to `mem-outbox.dead.jsonl`, which no drain replays, `NOTE mem-target-foreign`, `NOTE mem-run-id-invalid`, `NOTE mem-legacy-unconvertible`), and `NOTE recall-store-unset` means the store key is unset. Log the write's `status` the same way: `written`, or why no record landed (`skipped-existing`, `deferred`, `foreign-target`, `skip`, `no-fingerprint` or `store-unset`), since some of those print no note. Print the drain's `converted`, `legacy_unconvertible`, `dead_lettered` and `tombstones` counts in the run report too. If the permission layer refuses the drain or the write call, log `NOTE recall-write-refused`, do not retry it, and continue: a refused write never reaches the script, so nothing is parked. If the drain or the write call exits non-zero, log what it printed to `.decision-log.md` and the run report, do not retry it, and go on: to the write after a failed drain, and to the close-out below after a failed write. Recall is advisory, so a failed call never stops the run. The run report always lands; the record is best-effort.
80
82
 
81
83
  **Always, on every path above**, remove this run's latch as part of close-out, with the one command that may:
@@ -17,10 +17,10 @@ The gate reads artifacts TEA produces. In **production**, before running the gat
17
17
  **When automate backfills, commit the backfill before trace runs.** A test automate writes or changes lands in the main tree, as every assessor's output does ("Their OUTPUTS go home" below), so neither the commit under assessment nor the worktree made from it holds that test, and trace would count a test the commit does not contain. So never run trace, NFR or test review on that commit. While `.current-story` still names this story, log `gate-backfill-base: <sha>` in `.decision-log.md`, naming `HEAD`, the commit automate measured, then commit the backfill the way `references/execute.md` commits a story's paths, in this order:
18
18
 
19
19
  1. Stage the test files this pass's summary (`automation-summary-<story_id>-<sha>.md`, with `<sha>` the `gate-backfill-base:` commit; "Automate's summary records its rows" below) names as written or changed, by explicit path, in one call. `git status --porcelain --untracked-files=all` lists them: the plain `git status --porcelain` lists a new directory instead of the files in it, so a test in a new folder would look absent. A path it lists that the summary does not name is not part of the backfill and stays unstaged. A path the summary names that it lists is staged from the main tree, and the worktree's copy of that file, which automate ran the test's confirming rows against ("A backfill is confirmed in the pass that writes it" below), is not a test written into the worktree: the rebuild discards it. A path the summary names that it does not list has no change in the main tree, so look for the file in the worktree: at that path when the summary gives it under `<tmp-path>`, and otherwise at the same repo-relative path under `<tmp-path>`. When the file is there, automate wrote it into the worktree: copy it to its repo-relative path in the main tree before the rebuild destroys it, and list again. When git still lists no change at that path, or neither tree holds the file, the test the summary names was never written: leave the path out, and log a `gate-gap:` line for the gap that test was written for, as "A reported gap stays open until a later pass measures it closed" below describes, in place of any `unkilled` line logged for that gap. When this step stages nothing, there is no backfill: skip steps 2 through 5, and the commit under assessment stays the `gate-backfill-base:` commit.
20
- 2. With them staged, so that a gate reading git's file list sees a new test file, run the full three-axis sweep over the main tree, cache-defeated and printed, as `references/execute.md` step 5 runs it. A red that a change to the backfilled test files alone fixes (a lint or format error in one, a tracked-files gate that names one) is fixed there, staged, and re-run, at most twice in this backfill, a fix step 4 makes for a commit hook included. A red that needs a change to any other path, or that is still red after the second fix, is not the gate's to fix: commit nothing, and take "A red backfill sweep ends the cycle at a re-loop" below. A green sweep goes on to step 3, whatever `gate-gap:` lines this cycle has logged.
20
+ 2. With them staged, so that a gate reading git's file list sees a new test file, run the full three-axis sweep over the main tree, cache-defeated and printed, as `references/execute.md` step 5 runs it. A red `references/execute.md` 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 first. That step's second sweep for a red the story's changes do not explain is no fix, so it counts toward neither of the two fixes below, and when it shows no red, this sweep is green. A red that a change to the backfilled test files alone fixes (a lint or format error in one, a tracked-files gate that names one) is fixed there, staged, and re-run, at most twice in this backfill, a fix step 4 makes for a commit hook included. A red that needs a change to any other path, or that is still red after the second fix, is not the gate's to fix: commit nothing, and take "A red backfill sweep ends the cycle at a re-loop" below. A green sweep goes on to step 3, whatever `gate-gap:` lines this cycle has logged.
21
21
  3. Once the sweep is green, write a fresh `.tests-ran-<story_id>` marker as step 5 writes one: its `baseline=` line copied from `.baseline-<story_id>`, never re-derived, and `scope=full`.
22
22
  4. Run `references/execute.md` step 4's claim check on the commit message, then commit from the message file, in a call separate from the staging call, as step 4 requires. The guard allows this commit as it allows the evidence commit in "Route on the verdict": the story is still current, its marker was written in a prior call, and the index is not empty. A repo commit hook that rejects this commit is read as step 2's red, and `references/execute.md` step 4's own rule for a hook rejection does not apply to it: when a change to the backfilled test files alone answers the hook, make it there, stage it, and go back to step 2, whose sweep runs again before step 3 writes a fresh marker and this step retries the commit, all within step 2's budget of two fixes; when the hook needs a change to any other path, or rejects the commit again after the second fix, commit nothing, and take "A red backfill sweep ends the cycle at a re-loop" below. A `commit-msg` hook that rejects the message alone asks for no file change: Git runs it only once every `pre-commit` job has passed, so reword the message file, run the claim check again and retry the commit with the marker as it stands, re-running no sweep. That retry counts as one of step 2's two fixes, and a rejection after the second still takes "A red backfill sweep ends the cycle at a re-loop" below. A change a `pre-commit` job staged on its way there rides the retry as it would ride an accepted commit. A path the re-run claim check has you stage or edit is a file change, which takes the rule above. A rejection whose output does not show that a `commit-msg` hook made it is read as step 2's red, as above.
23
- 5. Refresh `.commit-<story_id>` from `HEAD`, log `gate-backfill: <sha>`, naming the new commit, in `.decision-log.md`, and remove `.scratch-<story_id>/` again: the claim check's message files recreated it, and `references/execute.md` step 0 has it removed before the story advances. The story's `evidence-<story_id>/` folder stays: no step removes it (`references/execute.md`, "Evidence never goes in scratch").
23
+ 5. Refresh `.commit-<story_id>` from `HEAD`, log `gate-backfill: <sha>`, naming the new commit, in `.decision-log.md`, and leave `.scratch-<story_id>/` in place, the claim check's message files included: `references/execute.md` step 0 keeps it until the story advances, since a cap-only re-loop or a re-gate of this story may still run its sweep. The story's `evidence-<story_id>/` folder stays: no step removes it (`references/execute.md`, "Evidence never goes in scratch").
24
24
 
25
25
  The new commit is now the commit under assessment: the worktree is rebuilt at it, trace, NFR and test review measure it, and the verdict's `assessed-commit` line names it. The backfill belongs to this gate cycle and is not a re-loop: it writes no `class:` line, spends no re-loop, and never meets the turn-ceiling check that runs before a re-loop, though its sweep spends turns like any wait (`references/execute.md`, "Waiting spends turns").
26
26
 
@@ -28,7 +28,7 @@ The new commit is now the commit under assessment: the worktree is rebuilt at it
28
28
 
29
29
  **A resume after a backfill does not run automate again.** When this story's `.decision-log.md` holds a `gate-backfill-base:` or a `gate-backfill:` line with no verdict logged after it (when it holds both for this cycle, the later one decides which bullet applies), `references/execute.md`'s fifth resume case sends the resume here, and it goes on from where the cycle stopped:
30
30
 
31
- - After `gate-backfill: <sha>` with `HEAD` still `<sha>`, remove `.scratch-<story_id>/` if it is still there, rebuild the worktree at that commit and run trace, NFR and test review on it.
31
+ - After `gate-backfill: <sha>` with `HEAD` still `<sha>`, rebuild the worktree at that commit and run trace, NFR and test review on it.
32
32
  - After `gate-backfill-base: <sha>`, when `git rev-parse HEAD` prints `<sha>`, the backfill is not committed yet: start again at step 1 above. When `git rev-parse HEAD~1` prints `<sha>`, it is committed: start at step 5.
33
33
  - At any other `HEAD`, the story is not in this case: take the route `preflight_check.py` reports.
34
34
 
@@ -179,7 +179,7 @@ Do not recompute TEA thresholds or re-judge `gate_status` — read it as given.
179
179
 
180
180
  - **`advance`** (gate_status PASS or WAIVED) → the story passes (an operator-evidence AC still owed its evidence is parked on the ledger first, as `defer` below says). **Sync the story's row in `sprint-status.yaml` to `done` before moving on**: set `development_status[<story_id>]` to `done`, preserving the file's comments and key order, and log the transition in `.decision-log.md`. This write is the run's own, not a sub-skill's: `ucg-dev-story` leaves the row at `review`, and `bmad-code-review` (production only; it does not run under `--light` at all) writes `done` **only** when nothing was left as an action item, so a story that legitimately `defer`s a non-critical finding is left at `in-progress`. Every downstream reader keys on `done`: Stage 1's in-scope rule (`references/ingest-and-scope.md` rule 3), the Epic-level trigger in this very sentence, and `scripts/drive_epic.py`'s progress check. So an advanced story whose row still says `review` is an advanced story the next reader re-drives, and an Epic whose last story advanced without this write never satisfies the Epic-level condition below. Sync it here, at the one place the authoritative verdict is known. In the same write, move the Epic's own `epic-<id>` row from `backlog` to `in-progress` when it still reads `backlog` (never backward, and only when the key exists): `bmad-build` makes that move when a story starts, but the story skills this run delegates to skip it when handed an explicit story key, so without it a finished Epic still reads `backlog`. If the Stop hook left a turn-budget marker for this story (`{workflow.implementation_artifacts}/.escalation-<story_id>.md`) and its count is still at or past the ceiling, do **not** promote it: log the sizing note `references/execute.md` describes under "Promoting the turn-budget marker", and leave the marker in place.
181
181
 
182
- **Commit the gate's evidence before the next story starts.** The `done` sync, this story's trace and gate files (`trace-<id>.md`, `gate-decision-<id>.json`, `e2e-trace-summary-<id>.json`, and in production its per-story NFR assessment and test review), its live results file when it has an operator-evidence AC, this gate's ledger rows and the decision log (with the first story, also Stage 3's test-design output) are tracked state written after Execute's commit-at-green. While `.current-story` still names this story, stage those of these paths that exist and are not ignored, by explicit path, in one call, and commit them in a second, before the next story's step 0. Before the commit call, write its message with Write to `{workflow.implementation_artifacts}/.scratch-<story_id>/message.txt`, recreating the folder Execute removed before the story advanced, or Reading the file first if an earlier session left it there, and commit from that file (`git commit -F`), as the story's own commits do. Never put the message in the Bash command. After a double-quoted `-m`, or in a heredoc whose delimiter is unquoted, bash runs a backticked name or a `$(...)` in it as a command while it builds the arguments, and the commit still exits 0 with the text that is left. A quoted heredoc keeps the text, but the guard reads its lines as commands (a line that opens with `Git runs` is read as a git command it does not know, which it counts as a commit and a push), and the `$(cat <<'EOF' ...)` form is a command substitution, which a harness that statically analyses Bash strings refuses (`references/execute.md` step 2). Once the commit is made, or the escalation below is written, remove `.scratch-<story_id>/` again, since the next story's step 0 must not find it (`references/execute.md` step 0). A resume that finds the folder left by a run that stopped after this commit removes it before the next story's step 0. For the story whose advance makes every story `done`, make this commit after the Epic-level gate below instead, so it also carries that gate's writes. The commit carries no source or test path, so the story's existing tests-ran marker covers it: reuse that marker as it stands and never rewrite it for this commit. A repo commit hook that rejects this commit is not `references/execute.md` step 4's case, whose rule for a hook rejection binds the story's own commits. Make a change the hook asks for only in a file the gate itself writes for this commit, `sprint-status.yaml` (its `done` sync) or `.decision-log.md`, then stage it and retry, with the marker as it stands, at most twice for this commit. When the hook asks for a change to any other path, such as a file TEA wrote (an edit there would make its provenance false) or a ledger row (the ledger schema below never rewrites one), or rejects the commit again after the second fix, commit nothing: log the rejection in `.decision-log.md`, write the typed escalation sidecar `escalation-<story_id>.json` (shape in `references/execute.md`, under "Escalation sidecar") with `kind` `evidence-commit-rejected` and a `decision_needed` that names the hook, its message, the paths left uncommitted and this run's id (so a rejection on a later run is a new decision, never one `/ucg-resolve` has closed already), write `.evidence-owed-<story_id>` beside it, listing those paths one per line, and stop before the next story's step 0, as the `escalate` route below stops. The story keeps the verdict it advanced on (`advance`, or `defer`, whose route advances anyway), and its evidence stays staged for the commit a resume makes. A `commit-msg` hook that rejects only this commit's message asks for no file change: the message is the gate's own, as the `done` sync and the decision log are, so reword `message.txt` and retry from it (`-F`), with the marker as it stands, and count that retry as one of this commit's two fixes, after which a rejection still takes the escalation above. Git runs that hook only once every `pre-commit` job has passed, so a change a `pre-commit` job staged on its way there rides the retry as it would ride an accepted commit. A rejection whose output does not show that a `commit-msg` hook made it keeps the rule above. Automate's backfill is not among its paths, because it was committed before trace ran ("When automate backfills", under "Backfill the gate evidence"). If it must carry an executable path all the same (a source or test file left uncommitted when trace ran, which this gate therefore never measured: log why), re-run the sweep and write a fresh marker per `references/execute.md` step 5 first. Then refresh `.commit-<story_id>` from `HEAD`, so this story's range in the gate trail includes the evidence commit. A path the project ignores is logged and left out, never forced in with `git add -f`; if nothing is staged, make no commit and leave `.commit-<story_id>` as it is. A resume that finds an advanced story's evidence still uncommitted makes this commit for it before the next story's step 0: point `.current-story` back at that story (its tests-ran marker still passes the guard), write the message file and commit from it as above, and refresh its `.commit-<story_id>`. While that story's `evidence-commit-rejected` escalation is still open, the resume commits nothing and stops on it instead (`references/execute.md`'s resume rule says how it reads one); once `/ucg-resolve` has closed it, the resume makes the commit, under the hook rule above. Once the commit is made, remove `.evidence-owed-<story_id>`: `/ucg-resolve` deletes the sidecar when it closes the escalation, so the marker is what tells a resume, and Stage 1's already-done short-circuit, that the commit is still owed. A resume that finds the marker with the sidecar gone and none of the paths it lists staged or different from `HEAD` (`git diff --quiet HEAD -- <paths>` exits 0 for them) finds the evidence committed already, by the operator or by a run that stopped between its commit and this removal: log the commit that holds it and remove the marker, making no commit. On the story whose advance makes every story `done`, this commit follows the Epic-level gate, so the `epic-<id>` row that gate's `advance` wrote stays staged with the rest, and the run ends `blocked` on that escalation all the same, because its evidence is not committed (`references/finalize.md`). While `.evidence-owed-<story_id>` is on disk, Stage 1's already-done short-circuit does not end that Epic's resume (`references/ingest-and-scope.md`, rule 4), nor does `scripts/drive_epic.py` report the Epic `all-done`: the resume waits on the escalation while it is open, makes the commit once it is closed, and then goes to Finalize with the Epic-level verdict the log holds, without running that gate again. Then move to the next story.
182
+ **Commit the gate's evidence before the next story starts.** The `done` sync, this story's trace and gate files (`trace-<id>.md`, `gate-decision-<id>.json`, `e2e-trace-summary-<id>.json`, and in production its per-story NFR assessment and test review), its live results file when it has an operator-evidence AC, this gate's ledger rows and the decision log (with the first story, also Stage 3's test-design output) are tracked state written after Execute's commit-at-green, and any `sweep` row this story's sweeps appended (`references/execute.md` step 2) is tracked state no commit of the story carries, since those stage only its source and test paths. While `.current-story` still names this story, stage those of these paths that exist and are not ignored, by explicit path, in one call, and commit them in a second, before the next story's step 0. Before the commit call, write its message with Write to `{workflow.implementation_artifacts}/.scratch-<story_id>/message.txt`, Reading the file first when one is there (step 4's claim check leaves one, as a backfill or an earlier session may) and creating the folder when it is gone, and commit from that file (`git commit -F`), as the story's own commits do. Never put the message in the Bash command. After a double-quoted `-m`, or in a heredoc whose delimiter is unquoted, bash runs a backticked name or a `$(...)` in it as a command while it builds the arguments, and the commit still exits 0 with the text that is left. A quoted heredoc keeps the text, but the guard reads its lines as commands (a line that opens with `Git runs` is read as a git command it does not know, which it counts as a commit and a push), and the `$(cat <<'EOF' ...)` form is a command substitution, which a harness that statically analyses Bash strings refuses (`references/execute.md` step 2). Once the commit is made, the escalation below is written, or nothing is staged, remove `.scratch-<story_id>/`: this is where `references/execute.md` step 0 has it removed, and the next story's step 0 must not find it. A resume that finds `.scratch-<story_id>/` for a story whose row is already `done` removes it before the next story's step 0. For the story whose advance makes every story `done`, make this commit after the Epic-level gate below instead, so it also carries that gate's writes. The commit carries no source or test path, so the story's existing tests-ran marker covers it: reuse that marker as it stands and never rewrite it for this commit. A repo commit hook that rejects this commit is not `references/execute.md` step 4's case, whose rule for a hook rejection binds the story's own commits. Make a change the hook asks for only in a file the gate itself writes for this commit, `sprint-status.yaml` (its `done` sync) or `.decision-log.md`, then stage it and retry, with the marker as it stands, at most twice for this commit. When the hook asks for a change to any other path, such as a file TEA wrote (an edit there would make its provenance false) or a ledger row (the ledger schema below never rewrites one), or rejects the commit again after the second fix, commit nothing: log the rejection in `.decision-log.md`, write the typed escalation sidecar `escalation-<story_id>.json` (shape in `references/execute.md`, under "Escalation sidecar") with `kind` `evidence-commit-rejected` and a `decision_needed` that names the hook, its message, the paths left uncommitted and this run's id (so a rejection on a later run is a new decision, never one `/ucg-resolve` has closed already), write `.evidence-owed-<story_id>` beside it, listing those paths one per line, and stop before the next story's step 0, as the `escalate` route below stops. The story keeps the verdict it advanced on (`advance`, or `defer`, whose route advances anyway), and its evidence stays staged for the commit a resume makes. A `commit-msg` hook that rejects only this commit's message asks for no file change: the message is the gate's own, as the `done` sync and the decision log are, so reword `message.txt` and retry from it (`-F`), with the marker as it stands, and count that retry as one of this commit's two fixes, after which a rejection still takes the escalation above. Git runs that hook only once every `pre-commit` job has passed, so a change a `pre-commit` job staged on its way there rides the retry as it would ride an accepted commit. A rejection whose output does not show that a `commit-msg` hook made it keeps the rule above. Automate's backfill is not among its paths, because it was committed before trace ran ("When automate backfills", under "Backfill the gate evidence"). If it must carry an executable path all the same (a source or test file left uncommitted when trace ran, which this gate therefore never measured: log why), re-run the sweep and write a fresh marker per `references/execute.md` step 5 first. Then refresh `.commit-<story_id>` from `HEAD`, so this story's range in the gate trail includes the evidence commit. A path the project ignores is logged and left out, never forced in with `git add -f`; if nothing is staged, make no commit and leave `.commit-<story_id>` as it is. A resume that finds an advanced story's evidence still uncommitted makes this commit for it before the next story's step 0: point `.current-story` back at that story (its tests-ran marker still passes the guard), write the message file and commit from it as above, and refresh its `.commit-<story_id>`. While that story's `evidence-commit-rejected` escalation is still open, the resume commits nothing and stops on it instead (`references/execute.md`'s resume rule says how it reads one); once `/ucg-resolve` has closed it, the resume makes the commit, under the hook rule above. Once the commit is made, remove `.evidence-owed-<story_id>`: `/ucg-resolve` deletes the sidecar when it closes the escalation, so the marker is what tells a resume, and Stage 1's already-done short-circuit, that the commit is still owed. A resume that finds the marker with the sidecar gone and none of the paths it lists staged or different from `HEAD` (`git diff --quiet HEAD -- <paths>` exits 0 for them) finds the evidence committed already, by the operator or by a run that stopped between its commit and this removal: log the commit that holds it and remove the marker, making no commit. On the story whose advance makes every story `done`, this commit follows the Epic-level gate, so the `epic-<id>` row that gate's `advance` wrote stays staged with the rest, and the run ends `blocked` on that escalation all the same, because its evidence is not committed (`references/finalize.md`). While `.evidence-owed-<story_id>` is on disk, Stage 1's already-done short-circuit does not end that Epic's resume (`references/ingest-and-scope.md`, rule 4), nor does `scripts/drive_epic.py` report the Epic `all-done`: the resume waits on the escalation while it is open, makes the commit once it is closed, and then goes to Finalize with the Epic-level verdict the log holds, without running that gate again. Then move to the next story.
183
183
 
184
184
  When **every story of the Epic is `done`**, run the Epic-level gate: pass the epic's own id via `--story`, **add `--epic-level`**, and read its `gate_status` **only**. TEA produces NFR and test-review **per story, not per epic**, so there is no epic-level aggregate to AND, and every story's own production gate already ANDed its signals before reaching `done`. With `--rollup` the epic id is the sprint-status grouping key and the verdict is a computation over the per-story record; only in the omit-`--rollup` fallback is `--story` resolved against an epic-named artifact (scoped per the `--story` note above) and the roll-up a pure trace read. When the Epic-level gate returns `advance`, or `defer` (whose route advances anyway), set the `epic-<id>` row to `done` (when the key exists), preserving comments and key order, log it, and carry it in the last story's evidence commit. BMAD Method 6.12 has no other writer of an epic row's `done`, and `bmad-retrospective` writes only the `epic-<id>-retrospective` row. Never write it on any other route: the work bound, `partial-complete`, a handoff, a block or an escalation.
185
185
 
@@ -201,7 +201,7 @@ uv run {skill-root}/scripts/gate_eval.py --trace-output {workflow.trace_output_d
201
201
  uv run {skill-root}/scripts/operator_owed.py --trace-output {workflow.trace_output_dir} --story <story_id> --story-file <story file> --profile production --nfr {nfr-assessment.md} --test-review {test-review.md} --tests-ran {workflow.implementation_artifacts}/.tests-ran-<story_id>
202
202
  ```
203
203
 
204
- - **`reloop`** (gate_status FAIL, or a production signal downgraded an advance, or a cap — sweep-scope or delta-profile) → **generalize before fixing.** Before `bmad-correct-course` writes any fix, take the verdict's `reasons` and the review's findings and, for each finding: (1) name, in ONE line, the defect CLASS the finding is an instance of; (2) state whether any earlier review of this story or this Epic already found that class — the previous gate artifacts and `{workflow.implementation_artifacts}/.class-ledger-<epic_id>.md` are the evidence, and they are already on disk, so this is a read, not a judgment call; (3) where the class is a repeat, the fix must close the CLASS — every sibling instance the same seam admits, not the one instance the reviewer demonstrated — and the log records why the class-level fix was not taken when the class was first named. A measured run spent five of six reviews re-finding one class ("an assertion that cannot go red") one seam over each time, with the class-killing move available from day one; the generalize step is what makes cycle N read cycle N-1 instead of re-buying it. Record one `class:` line per finding in this re-loop's `.decision-log.md` entry, and append any class not already present to `.class-ledger-<epic_id>.md` (create on first use; named for the Epic, so a later Epic starts a fresh ledger while this Epic's survives across its own invocations for exactly the resume case; one line per class, `- <class, one line> — first named <story_id>, cycle <n>`; **append-only** — Execute step 1 reads it before every story and re-loop, so a class named once is warned about everywhere after, including across stories, which no per-story artifact can do). **A score that does not move indicts the FIX STRATEGY, not the code:** when two consecutive gate evaluations of this story have moved `review_score` by less than 3 (production — under `--light` no review score exists, so the trigger there is two consecutive re-loops whose findings name any class already in the ledger), the generalize answers above are mandatory *in writing* before any further fix — a re-loop whose findings all name the same class as the previous re-loop's is a re-loop about to be spent badly. **A cap-only re-loop skips the ceremony.** When a cap alone produced the verdict — the `reasons` show only the sweep-scope cap, the delta-profile cap, or both, with no gate FAIL and no failed production signal — there is no finding to generalize and nothing to diagnose: re-run the full three-axis sweep where the sweep cap fired and refresh the marker with `scope=full`, then re-run the gate as the FULL instrument — **dropping `--cycle-profile`**, because the delta cap is lifted by the flag's absence and a re-gate that keeps it caps again forever — writing no `class:` lines, appending nothing to the ledger, and skipping `bmad-correct-course` entirely; such evaluations do not count toward the flat-score tripwire, and a capped CONCERNS keeps its findings for the next gate's own `defer` route — parking them is that gate's job, not this re-loop's. A cap-only re-gate re-measures without re-driving the story, so the turn-ceiling rule below never turns it into `escalate`. Otherwise, run `bmad-correct-course` to diagnose and adjust, then re-run the story (back through Execute, `references/execute.md`) — **within the remaining turn budget**. Re-run the gate after. If the re-loop would exceed `{workflow.max_turns_per_story}`, treat it as `escalate` instead; the count is the `turns` value the Stop hook records in `{workflow.implementation_artifacts}/.budget-<story_id>.json`. When the hook left a turn-budget marker for this story, that escalation's sidecar is the marker's promotion (`references/execute.md`, "Promoting the turn-budget marker").
204
+ - **`reloop`** (gate_status FAIL, or a production signal downgraded an advance, or a sweep-scope or delta-profile cap) → **generalize before fixing.** Before `bmad-correct-course` writes any fix, take the verdict's `reasons` and the review's findings and, for each finding: (1) name, in ONE line, the defect CLASS the finding is an instance of; (2) state whether any earlier review of this story or this Epic already found that class: the previous gate artifacts and `{workflow.implementation_artifacts}/.class-ledger-<epic_id>.md` are the evidence, and they are already on disk, so this is a read, not a judgment call; (3) where the class is a repeat, the fix must close the CLASS (every sibling instance the same seam admits, not the one instance the reviewer demonstrated), and the log records why the class-level fix was not taken when the class was first named. A measured run spent five of six reviews re-finding one class ("an assertion that cannot go red") one seam over each time, with the class-killing move available from day one; the generalize step is what makes cycle N read cycle N-1 instead of re-buying it. Record one `class:` line per finding in this re-loop's `.decision-log.md` entry, and append any class not already present to `.class-ledger-<epic_id>.md` (create on first use; named for the Epic, so a later Epic starts a fresh ledger while this Epic's survives across its own invocations for exactly the resume case; one line per class, `- <class, one line> (first named <story_id>, cycle <n>)`; **append-only**: Execute step 1 reads it before every story and re-loop, so a class named once is warned about everywhere after, including across stories, which no per-story artifact can do). **A score that does not move indicts the FIX STRATEGY, not the code:** when two consecutive gate evaluations of this story have moved `review_score` by less than 3 (production; under `--light` no review score exists, so the trigger there is two consecutive re-loops whose findings name any class already in the ledger), the generalize answers above are mandatory *in writing* before any further fix: a re-loop whose findings all name the same class as the previous re-loop's is a re-loop about to be spent badly. **A cap-only re-loop skips the ceremony.** When a cap alone produced the verdict (the `reasons` show only the sweep-scope cap, the delta-profile cap, or both, with no gate FAIL and no failed production signal), there is no finding to generalize and nothing to diagnose: re-run the full three-axis sweep where the sweep cap fired and refresh the marker with `scope=full`, then re-run the gate as the FULL instrument (**dropping `--cycle-profile`**, because the delta cap is lifted by the flag's absence and a re-gate that keeps it caps again forever), writing no `class:` lines, appending nothing to `.class-ledger-<epic_id>.md` and no row to `{workflow.deferred_work_path}` save the `sweep` row its re-sweep owes for a red the story's changes do not explain (`references/execute.md` step 2), and skipping `bmad-correct-course` entirely; such evaluations do not count toward the flat-score tripwire, and a capped CONCERNS keeps its findings for the next gate's own `defer` route: parking them is that gate's job, not this re-loop's. A cap-only re-gate re-measures without re-driving the story, so the turn-ceiling rule below never turns it into `escalate`. Otherwise, run `bmad-correct-course` to diagnose and adjust, then re-run the story (back through Execute, `references/execute.md`), **within the remaining turn budget**. Re-run the gate after. If the re-loop would exceed `{workflow.max_turns_per_story}`, treat it as `escalate` instead; the count is the `turns` value the Stop hook records in `{workflow.implementation_artifacts}/.budget-<story_id>.json`. When the hook left a turn-budget marker for this story, that escalation's sidecar is the marker's promotion (`references/execute.md`, "Promoting the turn-budget marker").
205
205
 
206
206
  **A red backfill sweep and the `gate-gap:` lines take this route their own way.** A re-loop that ended its cycle before trace ("A red backfill sweep ends the cycle at a re-loop", under "Backfill the gate evidence") takes the full route above, with its red and every open `gate-gap:` line of its cycle that is neither `unmeasured` nor `unkilled` as its findings, and the gate after it is a full one. On a `reloop` from `gate_eval.py` that is not cap-only, each open `gate-gap:` line that is neither `unmeasured` nor `unkilled` is among the findings the generalize step reads, though none of them is a reason for the verdict. An open `gate-gap:` line in a cycle whose re-loop is cap-only is not one of that re-loop's findings, so it gets no `class:` line and no ledger row here: like a capped CONCERNS's findings, it goes to the next gate, by its `gate-gap:` line ("A reported gap stays open until a later pass measures it closed", under the same section). No `gate-gap:` line, on any criterion, sends a story to this route: only the verdict or a red backfill sweep does.
207
207
 
@@ -225,7 +225,7 @@ Append to `{workflow.deferred_work_path}` (create on first use). One heading per
225
225
  | d1 | gate | low | <story-id> | <why parked> | <what to do later> | open |
226
226
  ```
227
227
 
228
- - `source` ∈ `gate` (CONCERNS, an operator-evidence AC's evidence still owed, or an open `gate-gap:` line: a coverage gap automate reported rather than backfilled, a risk on a P0 criterion it left unmeasured, a gap whose rows could not run, a backfilled test that was never written, or a backfilled test that did not kill its mutant), `code-review` (non-critical finding), `nfr` (non-FAIL finding), `decision` (parked decision).
228
+ - `source` ∈ `gate` (CONCERNS, an operator-evidence AC's evidence still owed, or an open `gate-gap:` line: a coverage gap automate reported rather than backfilled, a risk on a P0 criterion it left unmeasured, a gap whose rows could not run, a backfilled test that was never written, or a backfilled test that did not kill its mutant), `code-review` (non-critical finding), `nfr` (non-FAIL finding), `decision` (parked decision), `sweep` (a non-critical finding: a case outside the story's changes that went red in one sweep and green in the next at the same tree, `references/execute.md` step 2).
229
229
  - `severity` ∈ `low`, `med`, `high`. A `high` that maps to a gate FAIL or a P0/critical finding does **not** belong here: re-loop or escalate it. A row from an open `gate-gap:` line is always `med`: whatever its criterion's priority, it is neither a gate FAIL nor a P0/critical finding, so it belongs here and never re-loops or escalates the story.
230
230
  - `id` is unique within the Epic heading (append `d2`, `d3`, … ). Note that the id is unique only WITHIN its heading, so `d1` under two Epics is two different decisions; a project-wide reader must key them by more than the raw column (`/ucg-resolve` mints an id for exactly this reason).
231
231
  - `status` ∈ `open`, `resolved`. **This gate only ever appends rows, and never rewrites one** — but the column is not frozen forever: `/ucg-resolve` flips `open` to `resolved` when an operator closes a parked decision, and that single transition is the one sanctioned edit to an existing row. Everything else about a row is immutable once written: never restate its `id`, `source`, `severity`, `story`, `reason` or `suggested_action`, because the ledger is the durable account of what was parked and rewriting it loses the history the Epic close-out reads.
@@ -84,7 +84,7 @@ Log each supersession to `.decision-log.md`.
84
84
 
85
85
  **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.
86
86
 
87
- **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 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:
87
+ **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:
88
88
 
89
89
  - **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.
90
90
  - **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.
@@ -119,7 +119,7 @@ The subagent must return **ONLY this object — no prose, no document quotes bey
119
119
  "candidate": "<only when this answers a seeded judgment candidate: its id, copied as given>"}],
120
120
  "concerns": [{"source": "<artifact path:line>", "note": "<cosmetic / non-blocking gap, one line>",
121
121
  "candidate": "<only when this answers a seeded judgment candidate: its id, copied as given>"}],
122
- "advisories_checked": [{"sig": "<advisory id>", "status": "recurred|not-observed|unknown"}]}
122
+ "advisories_checked": [{"sig": "<the recalled record's id, copied as given>", "status": "recurred|not-observed|unknown"}]}
123
123
  ```
124
124
 
125
125
  **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.)
@@ -210,7 +210,7 @@ Do these in order; each must be asserted, not assumed:
210
210
 
211
211
  **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.
212
212
 
213
- Then **assert they are active**: 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. Invariants that live only in memory are context, not enforcement, and memory does not block a `git commit`.
213
+ 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`.
214
214
  - **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:
215
215
  - `ULTRACODE_PROTECTED_BRANCHES='{workflow.protected_branches}'` (comma-separated)
216
216
  - `ULTRACODE_IMPL_ARTIFACTS='{workflow.implementation_artifacts}'`
@@ -221,6 +221,12 @@ Do these in order; each must be asserted, not assumed:
221
221
  - **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. 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.
222
222
  - **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.)
223
223
  - **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.
224
+ - **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:
225
+ - **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`.
226
+ - **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.
227
+ - **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:
228
+ - **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".
229
+ - **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.
224
230
 
225
231
  ### Launch briefing (interactive only)
226
232
 
@@ -241,4 +247,4 @@ Then **one soft confirm** to cross the line. With `--yes`, skip the confirm and
241
247
 
242
248
  ## Progression
243
249
 
244
- Proceed to `references/define-done.md` only after the gate passed AND the Epic branch, both hooks (asserted active), and the allowlist are in place — all recorded in `.decision-log.md`. If the gate did not pass, the run has stopped here (interactive) or returned blocked JSON (headless); there is no progression.
250
+ 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.
@@ -13,6 +13,10 @@ Enforces invariants that must NOT live in memory (context, not enforcement):
13
13
  for now (it errs toward denying), but it is the reason a legitimate commit
14
14
  in an unrelated checkout can be refused.
15
15
  2. No `git commit` until a "tests-ran" marker exists for the current story.
16
+ A `git commit --dry-run` meets this check and every other commit check,
17
+ as a commit does: preflight step 5's probe relies on that, since with no
18
+ story set a guard the session runs refuses it here
19
+ (references/preflight.md).
16
20
  3. Marker freshness: no `git commit` unless that marker carries a
17
21
  `baseline=<sha>` line matching, character for character, the SHA the story
18
22
  recorded when it started. A bare existence check accepts a marker replayed
@@ -36,6 +36,7 @@ Contents:
36
36
  - validate_record / classify_record per-record validation
37
37
  - write_run_record the immutable per-run writer
38
38
  - iter_store_records / read_store the reader over a list of roots
39
+ - read_run_record one run's record, by its run_id
39
40
  - probe_store the write probe the latch runs
40
41
  - is_legacy_payload / legacy_payload_to_record outbox migration
41
42
  - build_latch_v2 / measure_latch_v2 / latch_view latch v2
@@ -1336,6 +1337,35 @@ def read_store(
1336
1337
  return records, dropped
1337
1338
 
1338
1339
 
1340
+ def read_run_record(
1341
+ store_root: str | os.PathLike[str] | None, fingerprint: str | None, run_id: object
1342
+ ) -> dict | None:
1343
+ """The record of one run, read from ``<store>/<fingerprint-dir>/runs/<run_id>.jsonl``, or None.
1344
+
1345
+ The record is returned only when classify_record() reads it as RECORD_OK
1346
+ for ``fingerprint`` and it names ``run_id`` itself. Anything else is None:
1347
+ an unset root, a run_id that fails valid_run_id(), a fingerprint with no
1348
+ directory name, a file that is absent, is not a regular file or cannot be
1349
+ read, and one that holds something else (unparseable bytes, the wrong
1350
+ shape, a newer schema, another repo's record or another run's). It never
1351
+ raises on a bad value or an OSError, and it never writes.
1352
+ """
1353
+ if store_root is None:
1354
+ return None
1355
+ try:
1356
+ path = run_file_path(store_root, fingerprint, run_id)
1357
+ except ValueError:
1358
+ return None
1359
+ try:
1360
+ raw = _read_run_file(path)
1361
+ except OSError:
1362
+ return None
1363
+ record = None if raw is None else _parse_run_file_bytes(raw)
1364
+ if record is None or classify_record(record, fingerprint) != RECORD_OK:
1365
+ return None
1366
+ return record if record["run_id"] == run_id else None
1367
+
1368
+
1339
1369
  # ---------------------------------------------------------------------------
1340
1370
  # Health: the latch's write probe
1341
1371
  # ---------------------------------------------------------------------------
@@ -29,7 +29,17 @@ write
29
29
  byte-identical; a foreign or unparseable target is never touched and the
30
30
  entry is dead-lettered with ``NOTE mem-target-foreign``; an OSError spills
31
31
  the record to ``<impl>/mem-outbox.<run_id>.jsonl`` with
32
- ``WARN mem-write-deferred``.
32
+ ``WARN mem-write-deferred``. Each ``--advisory sig=<record id>`` names a
33
+ record Stage 1 consumed by its ``id`` (the run_id of the run that wrote
34
+ it). A sig that passes the run_id check is stored as given, as ``run_id``
35
+ is; any other sig is redacted. With no ``recurred`` given, write reads that
36
+ record from this repo's store folder and stores ``yes`` when a root-cause
37
+ signature whose class is not ``other`` is in both records, ``no`` when that
38
+ record has one and this run shares none, and ``unknown`` otherwise (a sig
39
+ that is no run_id, a record it cannot read, one with no such signature, or
40
+ a run that did not advance and names no root cause). An explicit
41
+ ``recurred`` is stored as given, any value but yes, no or unknown as
42
+ unknown.
33
43
 
34
44
  drain --store
35
45
  Replays each spilled record through the same write and removes it once it
@@ -191,13 +201,68 @@ def _count_deferred(deferred_path: Path | None, epic: str) -> int:
191
201
  return sum(1 for line in section if line.lstrip().startswith("- "))
192
202
 
193
203
 
194
- def _build_payload(args: argparse.Namespace, gate_status: str) -> dict:
204
+ _RECURRED_VALUES = ("yes", "no", "unknown")
205
+
206
+
207
+ def _recurrence_signatures(signatures: object) -> set[str]:
208
+ """The signatures of a record's root causes that can recur: every class but
209
+ ``other``, the rule mem_recall's recurrence count applies."""
210
+ if not isinstance(signatures, list):
211
+ return set()
212
+ return {
213
+ entry["sig"]
214
+ for entry in signatures
215
+ if isinstance(entry, dict)
216
+ and isinstance(entry.get("sig"), str)
217
+ and entry["sig"]
218
+ and mc.canonical_class(entry.get("class")) != "other"
219
+ }
220
+
221
+
222
+ def _computed_recurred(
223
+ store: Path | None,
224
+ fingerprint: str | None,
225
+ record_id: str,
226
+ *,
227
+ run_id: str,
228
+ verdict: str,
229
+ signatures: list[dict],
230
+ ) -> str:
231
+ """Whether the root cause of the record an advisory names recurred in this run.
232
+
233
+ ``record_id`` is the consumed record's ``id``: the run_id of the run that
234
+ wrote it, read from this repo's folder of the store. ``yes`` when a
235
+ root-cause signature whose class is not ``other`` is in both that record
236
+ and this run (the same class and artifact path), ``no`` when that record
237
+ names such a root cause and this run shares none of them, and ``unknown``
238
+ otherwise: the id is not a run_id or is this run's own, the record cannot
239
+ be read or is not this repo's record of that run, it names no root cause
240
+ outside ``other``, or this run did not advance and names no root cause
241
+ (a handoff or a ``decision-pending`` stop observed nothing). A matching
242
+ gate status or verdict is not a recurrence. Never raises.
243
+ """
244
+ if record_id == run_id or not mc.valid_run_id(record_id):
245
+ return "unknown"
246
+ if not signatures and verdict.lower() != "advance":
247
+ return "unknown"
248
+ record = mc.read_run_record(store, fingerprint, record_id)
249
+ if record is None:
250
+ return "unknown"
251
+ prior = _recurrence_signatures(record.get("signatures"))
252
+ if not prior:
253
+ return "unknown"
254
+ return "yes" if prior & _recurrence_signatures(signatures) else "no"
255
+
256
+
257
+ def _build_payload(args: argparse.Namespace, gate_status: str, store: Path | None = None) -> dict:
195
258
  """The structured run payload write stores, after adding
196
259
  ``created_at_epoch`` and ``project`` (mc.store_record).
197
260
 
198
261
  It is the shape the removed ``build`` embedded in its claude-mem
199
262
  ``{text,title,project}`` wrapper, so a legacy outbox entry drain converts
200
- becomes the same record.
263
+ becomes the same record. An advisory that passes no ``recurred`` has it
264
+ computed against ``store`` (_computed_recurred); one that passes it keeps
265
+ it, any value but yes, no or unknown read as unknown.
201
266
  """
202
267
  fingerprint = mc.repo_fingerprint(args.cwd or ".").get("value")
203
268
 
@@ -207,13 +272,25 @@ def _build_payload(args: argparse.Namespace, gate_status: str) -> dict:
207
272
  sig = _signature(parsed["class"], parsed["path"], fingerprint)
208
273
  signatures.append({"class": parsed["class"], "path": parsed["path"], "sig": sig})
209
274
 
275
+ verdict = mc.redact(args.verdict).strip() or "blocked"
276
+
210
277
  advisories = []
211
278
  for raw in args.advisory or []:
212
279
  fields = _parse_kv(raw)
213
- sig = mc.redact(fields.get("sig", ""))
214
- recurred = fields.get("recurred", "unknown")
215
- if recurred not in ("yes", "no", "unknown"):
216
- recurred = "unknown"
280
+ sig = fields.get("sig", "")
281
+ # A record id is kept as given, as the record's own run_id is: redact's
282
+ # `sk-` key pattern would turn epic-desk-booking-<stamp> into
283
+ # epic-de[redacted], which names no record. Any other sig is redacted.
284
+ if not mc.valid_run_id(sig):
285
+ sig = mc.redact(sig)
286
+ if "recurred" in fields:
287
+ recurred = fields["recurred"]
288
+ if recurred not in _RECURRED_VALUES:
289
+ recurred = "unknown"
290
+ else:
291
+ recurred = _computed_recurred(
292
+ store, fingerprint, sig, run_id=args.run_id, verdict=verdict, signatures=signatures
293
+ )
217
294
  advisories.append({"sig": sig, "recurred": recurred})
218
295
 
219
296
  deferred_path = Path(args.deferred) if args.deferred else None
@@ -224,8 +301,6 @@ def _build_payload(args: argparse.Namespace, gate_status: str) -> dict:
224
301
  "date": args.valid_until_date if args.valid_until_date else mc.utc_now_iso(),
225
302
  }
226
303
 
227
- verdict = mc.redact(args.verdict).strip() or "blocked"
228
-
229
304
  payload = {
230
305
  "ucg": 1,
231
306
  "schema_version": mc.UCG_SCHEMA_VERSION,
@@ -426,7 +501,7 @@ def cmd_write(args: argparse.Namespace) -> int:
426
501
 
427
502
  cwd = args.cwd or "."
428
503
  created_at_epoch = mc.utc_now_epoch_ms()
429
- payload = _build_payload(args, gate_status)
504
+ payload = _build_payload(args, gate_status, store)
430
505
  if mc.fingerprint_dir(payload["fingerprint"]) is None:
431
506
  # No commit yet (or not a git repo): the record could never name its
432
507
  # folder, now or on a later drain, so nothing is written or spilled.
@@ -20,6 +20,13 @@ Table (JSON array; every key a string, all five required, ``note`` optional):
20
20
  "expect_red": "test_depth_guard_fires",
21
21
  "note": "AC-3 twin"}]
22
22
 
23
+ Every key but ``replacement`` must be non-blank: neither empty nor only
24
+ whitespace, since a blank ``command`` exits 0 and a blank ``expect_red`` names
25
+ no test. An empty ``replacement`` deletes the anchor, the plainest mutation of
26
+ a guard clause. Delete whole statements: a deletion that leaves a block with no
27
+ body breaks the module, and reads as any mutant that breaks a module does (see
28
+ the collection errors below).
29
+
23
30
  Per row, in order: assert the anchor occurs EXACTLY once (0 occurrences is
24
31
  reported distinctly as STALE - the formatter-reflow signature - and more than
25
32
  one as NOT UNIQUE, because a duplicated anchor mutates a different site than it
@@ -445,8 +452,22 @@ def _load_table(path: Path) -> list[dict]:
445
452
  if not isinstance(row, dict):
446
453
  raise _refuse(f"row {index} is not an object")
447
454
  for key in REQUIRED_KEYS:
448
- if not isinstance(row.get(key), str) or not row[key]:
455
+ if not isinstance(row.get(key), str):
449
456
  raise _refuse(f"row {index} is missing required string key {key!r}")
457
+ # An empty replacement is a deletion of the anchor, and the anchor
458
+ # is never blank, so the mutation always changes the file; a blank
459
+ # replacement is an ordinary mutation. Any other key left empty or
460
+ # only whitespace would run a row that proves nothing: a blank file
461
+ # names no source, a blank anchor occurs everywhere or mutates
462
+ # whitespace rather than code, a blank command exits 0 and reports
463
+ # a false GREEN survivor, and a blank expect_red names no test (one
464
+ # space reads KILLED, since attribution is a substring match that
465
+ # any failure line holding a space satisfies).
466
+ if not row[key].strip() and key != "replacement":
467
+ raise _refuse(
468
+ f"row {index} has an empty or blank {key!r} - only 'replacement' "
469
+ "may be empty, which deletes the anchor"
470
+ )
450
471
  if row["anchor"] == row["replacement"]:
451
472
  raise _refuse(
452
473
  f"row {index} anchor and replacement are identical - "
@@ -101,7 +101,10 @@ a .regate-<story> marker naming HEAD), or mid-story.
101
101
  Exit 0 iff branch+hooks+env+skills are armed and the Claude Code version is
102
102
  not below a minimum; the latch, the tracked fact and
103
103
  the story block never move the exit code, because they inform model-owned actions rather than certify
104
- them.
104
+ them. `armed` certifies what `.claude/settings.local.json` holds, not that
105
+ the running Claude Code session loaded those hooks, which no script can see:
106
+ preflight step 5's last bullet proves that with a `git commit --dry-run` the
107
+ guard must refuse (references/preflight.md).
105
108
 
106
109
  uv run preflight_check.py --assert-armed --project-root <path> \
107
110
  --impl-artifacts <path> [--story <id>] [--run-id <rid>] \