armelhbobdad/bmad-module-ultracode-goal / skills/ultracode-goal
ultracode-goal
FlaggedRuns a BMAD Epic autonomously to a machine-checked Definition-of-Done. Use when the user requests to 'run an epic autonomously', 'execute this epic', 'ultracode goal', or 'autonomously deliver the epic'.
references/finalize.md
View on GitHub# Stage 6 — Finalize
**Goal:** Make the run pay off for the next one. Capture what was learned to the right durable store, optionally run a retrospective, audit the decision log, produce a run report, and surface the deferred-work ledger. This is the terminal stage — reached by one of five routes: after the Epic-level gate advanced; when a story escalated and the run is `blocked`; when the run did durable work and advanced **no row at all** — it decomposed an oversized story or authored a definition it had no budget to drive, a **handoff** that is also `blocked` and is distinguished from an escalation only by the sidecar's `kind` (`references/execute.md`); when the run hit its `--max-stories` **work bound** with in-scope stories still remaining (`references/execute.md` — a `complete` outcome carrying no Epic-level gate, because the Epic is not finished and this stage authors none it did not earn); or when the run completed its in-scope *strict subset* of a deliberately-partial Epic without an Epic-level gate (a **`partial-complete`** outcome — attended only). The last two look alike and are not: `partial-complete` narrows **in-scope** and is attended-only, while the work bound leaves in-scope untouched and simply drives fewer of it, so it keeps the ordinary `complete` envelope. The handoff route is the one a reader is most likely to mis-file: it looks like the work bound (the Epic still owes stories, and a later invocation continues) but it emits `blocked` rather than `complete`, because the work bound counts stories taken to a Stage-5 verdict and a handoff took **zero**. Say in the run report which of the two happened; a reader cannot tell a decomposition from a crash from the envelope alone, and prose is the only place that distinction currently lives. Headless never narrows in-scope, so a headless run that is *not* work-bounded still finishes the Epic and emits `complete`. Converse in `{communication_language}`; the run report and ledger are written in `{document_output_language}`.
## Capture to Auto Memory — deliberately
Auto Memory is passive by default; drive it on purpose so the learnings land in the right place and the next run starts sharper. Decide each learning's home:
- **Machine-local learnings** (this repo's build quirks, a flaky-test workaround, a path that differs from convention, a TEA config gotcha) → tell the session to **`remember X`** so it persists to Auto Memory. Keep `MEMORY.md` terse — a short index that points to per-topic files; put the detail in the topic file, not the index.
- **Team standards** (a convention every contributor and future run should follow — a lint rule, a commit-message shape, a forbidden pattern) → write to `{project-root}/CLAUDE.md` or `{project-root}/.claude/rules`, not to machine-local memory. CLAUDE.md is context the whole team and every agent inherits; Auto Memory is yours alone.
The split matters: a team standard buried in machine-local memory never reaches the team, and a machine-local quirk in CLAUDE.md pollutes shared context. Route each learning by who needs it.
## Optional retrospective (`--retro`)
Interactive runs **offer** the retrospective at Epic close (skip it by default if the user declines); headless runs it **only when `--retro` was passed**. When run, `bmad-retrospective` covers the Epic, and its lessons feed back through the capture step above: durable conclusions go to memory or CLAUDE.md by the same machine-local-vs-team split. It is additive, not required to close the run. A retrospective re-uses the Stage 1 filtered recall (its recurrence counts); it never reads the run store again.
## Decision-log audit
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). A `friction:` entry is left for the health check when `{workflow.health_check_repo}` is set, since the check reports it. When that is empty, the check is off, and the `disabled` marker it appends closes every `friction:` entry after the log's last `health-check:` marker unreported, so list each of those in the addendum: search `.decision-log.md` with the Grep tool for the regex `^\s*([-*]\s+)?(friction:|health-check: (disabled|clean|discarded|done)\b)` and take the `friction:` entries after the last marker it finds (all of them when there is none). End with a shared accounting of how the run's reasoning was handled, not a one-sided polish.
## Run report
Produce a report (write it as a peer of `.decision-log.md` in the run folder, e.g. `run-report.md`) covering the list below. **A prior invocation's report already sitting at that path is the NORMAL state, not a surprise**: under `--max-stories N` the run folder persists across invocations, the Write tool refuses a file that has not been Read this session, and on a mature Epic the prior report cannot be Read cheaply either. Do not Read it and do not improvise a name — archive it first with one Bash move to the next free `run-report-<n>.md` (`<n>` increments per archive; list the folder to find the free slot), then write this invocation's report at `run-report.md`. The latest account is always `run-report.md`; the archives are prior invocations' accounts, ordered by `<n>` — one scheme, stated here, instead of one invented per session.
- Epic and profile (production / `--light`), branch off `{workflow.epic_branch_prefix}`.
- **The terminal route this run took**: Epic complete, work-bounded, `partial-complete`, handoff, or escalated (the five named at the top of this stage). When the Epic still owes stories, give how many and their ids: under `--max-stories N` the conductor already logged the bound and the carried-over ids to `.decision-log.md` (`references/execute.md`), and a handoff names them in its escalation sidecar. The status word cannot carry this (a work-bounded run ends `complete`), so the report is where a returning reader learns whether the Epic is finished. An `operator-evidence-owed` escalation takes the escalated route even though `scripts/drive_epic.py` prints it as a handoff, because its story reached a Stage-5 verdict: say the story is delivered and gated except the evidence its sidecar names.
- Per-story outcome: gate_status and verdict (advance / defer / reloop / escalate), and any re-loops spent against budget. For a story that advanced with its count at or past the turn ceiling, its sizing note: the Stop hook's count against `{workflow.max_turns_per_story}`, which raised no escalation because the gate advanced the story, taken from `.decision-log.md`, or from `{workflow.implementation_artifacts}/.budget-<story_id>.json` when the session ended before the note was logged.
- **Gate provenance per story** — `tea` or `hand-authored`, copied from the `gate-provenance:` line Stage 5 logged (`references/gate.md`). Say it per story rather than once for the run: a mixed Epic is the common shape, and a reader who is told only "production profile" cannot tell which stories the model itself supplied the gate file for. If every story reads `hand-authored`, say that in one sentence — an Epic gated entirely on artifacts the run wrote for itself is the single most important caveat on its own report.
- The `epic-<id>` row's value in `sprint-status.yaml` at close: `done` only when the Epic-level gate advanced, on an `advance` or on a `defer`, whose route advances anyway (`references/gate.md`). BMAD Method 6.12 has no other writer of that `done`, so never tell the operator `bmad-retrospective` will close the row; it writes only the retrospective row.
- The Epic-level gate result — and when this run authored none (the work bound, a handoff, a `partial-complete`), say that in words: `no Epic-level gate — the Epic is not finished`. Never leave the line blank or omit it; a missing gate line reads as a pass.
- Turns the Stop hook counted per story (`{workflow.implementation_artifacts}/.budget-<story_id>.json`, `0` when the hook never fired for it), against `{workflow.max_turns_per_story}`.
- Learnings captured and where they went (memory vs CLAUDE.md).
- A pointer to the deferred-work ledger and its open-item count.
- Cross-Session Recall: consulted / wrote / skipped, every `recall-` and `mem-` token the run logged (from Stage 1's latch and filter calls and from the drain and write calls below), what any recall call that exited non-zero printed, and, when the drain ran, its `converted`, `legacy_unconvertible`, `dead_lettered` and `tombstones` counts. A run short of turns may drop prose; it may not drop a `recall-` token, because the report is the one place an operator learns that recall was off for this run.
## Gate trail
Write the per-story evidence trail as **`gate-trail.md`, a peer of `run-report.md`** in the run folder — the same folder that holds `.decision-log.md`, never `{workflow.implementation_artifacts}`. Where the run report is prose you compose, this one is synthesized by script from artifacts the run already wrote, so a reader can audit a green Epic without re-running it. Every story gets a section whose table traces five columns: acceptance criterion → planned test → result → gate verdict → commit.
```
uv run {skill-root}/scripts/gate_trail.py --run-dir <this run's folder> --profile <light|production> --impl-artifacts {workflow.implementation_artifacts} --trace-output <the trace artifacts dir> --story <id>… --repo {project-root}
```
**The run's in-scope story ids are required, not optional.** Pass `--story` once per in-scope story **in sprint order** (a repeated flag — `--story 4-1 --story 4-2` — never one space-separated list); the order is what turns the recorded baselines into commit ranges (each story's range ends at its own `.commit-<story_id>` when that marker names a commit, else at the next story's baseline, and at `HEAD` for the last one). The script prints the path it wrote; name that path in the run report. **Which set, when a decomposition rewrote `sprint-status.yaml` mid-run:** the trail covers the in-scope set **as resolved at Stage 1** — the ids this run actually acted on, the replaced parent among them. Child rows the decomposition created were resolved by no Stage 1 and driven by nothing here; they belong to the next invocation's trail (`references/execute.md` says the same at the decomposition terminal). Their cells would render `n/a` either way — the difference is whether the delivered evidence names rows that did not exist when the run began.
Naming no story (or a blank id) is refused: the script exits `2` with a usage line and writes nothing, rather than rendering a well-formed trail of zero sections that traces nothing and then gets named in the run report as delivered evidence. This does not contradict the fail-soft property below — `--story` is an **argument, not one of the sources**: an absent source is evidence the trail reports as `n/a`, while an absent story list is a malformed invocation, and there is nothing to render fail-soft *about*. That refusal is an **invocation error, not a gate verdict** — the same lane a missing `--run-dir` or `--profile` already occupies. It is never an escalation and never a reason to block a run that reached this stage: re-issue the command with the ids (you already hold them, in sprint order), **and either way continue through the remaining finalize steps** — the terminal `run-status.json` write, the headless emit and the health check must still run.
Two properties are load-bearing, so do not "improve" them:
- **It renders verdicts, it never forms one.** The verdict cell is the verdict the run already recorded, or the gate artifact's `gate_status` mapped through the gate's own table. A story whose escalation is still open (`escalation-<story_id>.json` on disk, neither closed nor a handoff, beside a `sprint-status.yaml` row that is not `done`) reads `escalate` instead, gate artifact or not, because the `escalate` route stops after logging the verdict it escalated from, the `reloop` of a story owed operator evidence or stopped at its turn ceiling; an `evidence-commit-rejected` escalation `/ucg-resolve` has not closed keeps the verdict the story advanced on (`advance`, or `defer`), whatever its row reads, and is named on its verdict-source line. The production AND ran once, when the gate decided; re-running it here would be a second, later judgment on the same story. A story whose verdict was not `advance` is shown as it was decided, never quietly green.
- **It fails soft.** Every source is optional: a missing or unreadable checklist, trace report, gate file or baseline renders `n/a` in its cell and the trail continues. This is the opposite of the gate, which fails closed, and deliberately so — the trail has no authority, and failing closed here would turn a reporting bug into a blocked run. Under `--light` there is no acceptance checklist by design, so those sections synthesize from the trace report (TEA-authored, or hand-authored where trace cannot run) and gate decision instead.
**Optional diff viewer — detect, then degrade to silence.** The trail's commit column names a sha per story and the run report names the Epic branch, but neither opens a diff. When `hunk` is detected on PATH (`which hunk`), the run report may point at what it already names: `hunk show <commit>` for one story's commit, `hunk diff <epic-branch>` for the run as a whole, so a reader auditing the evidence can open a diff without reconstructing the range by hand. Absent `hunk`, print nothing — no suggestion and no warning that it is missing, and both surfaces read exactly as they did before. It is a render affordance and nothing else: do not add it to `{workflow.allowlist_commands}`, do not add a preflight check for it, and never let it reach a machine surface — not the gate verdict JSON, not the headless envelope, not the terminal `run-status.json`. Those are parsed by callers that will not have it installed.
## Cross-Session Recall write (optional)
Read the latch, `{workflow.implementation_artifacts}/.mem-state.json`, with the Read tool (the guard allows reading it), and act only on what it says when it is this run's. Each recall call below is attempted once and never retried, and run exactly as written, with nothing added (no redirection, no `2>&1`, no pipe): the guard lets a recall call through only in that form.
- **No latch, an unreadable one, or a latch whose `run_id` is not this run's id** (the one minted at this invocation's Stage 1 or resume): log `NOTE recall-latch-missing` to `.decision-log.md` and the run report, whatever `{workflow.cross_session_recall}` says, and write nothing: no `drain` and no `write` call. Recall turned off somewhere in this run (a refused or failed Stage 1 latch call, or a latch replaced or removed since), and this line is where the report says it. Another run's latch, or an unreadable one, is left in place; the close-out `unlatch` below never removes it.
- **This run's latch, with `recall` `"off"`**: print the one-line notice and write nothing: *Cross-Session Recall is off; this run read no prior runs and wrote no record. Enable it with `cross_session_recall = "on"` and a `cross_session_recall_store` folder.*
- **This run's latch, with `recall` `"on"` and `store_ok` not `true`** (red): write nothing, and repeat the latch's `reason` and the notes Stage 1 logged in the run report (`NOTE recall-store-unset` when the store key is unset; a `reason` alone, such as `store-unwritable: ...` or `no-fingerprint`, otherwise).
- **This run's latch, green** (`recall` `"on"` and `store_ok` `true`): drain, then write.
Whichever case applies, repeat in the run report a `NOTE recall-latch-visible` line Stage 1 logged: git can still see the latch (git tracks it, or the repository's exclude file could not be written), so it reads as a change to the tree. Untracking it, or fixing the exclude file, is the person's change to make; the run never makes it.
1. **Drain the outbox**, so a record an earlier run parked when the store could not take it lands before this run's own:
```
uv run {skill-root}/scripts/mem_observation.py drain --impl-artifacts {workflow.implementation_artifacts} --store '{workflow.cross_session_recall_store}' --project-root {project-root}
```
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.
```
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>]…
```
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.
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.
**Always, on every path above**, remove this run's latch as part of close-out, with the one command that may:
```
uv run {skill-root}/scripts/mem_recall.py unlatch --impl-artifacts {workflow.implementation_artifacts} --run-id <run-id>
```
It removes the latch only when it carries this run's id, leaves another run's latch, an unreadable one and an absent one as they are, and prints `{"removed": ..., "reason": ...}`; log the reason when `removed` is `false`. When the call is refused, or its reason is `unreadable` or starts with `remove-failed`, also log `NOTE recall-unlatch-failed` with the latch path to `.decision-log.md` and the run report, so the person knows to delete it by hand. Run it once and never retry it, and never remove the latch any other way (`rm`, a file tool, a script of your own): while a latch is present the guard refuses that, and a latch left in place keeps it denying until the next Stage 1 replaces it or the person deletes it by hand. With no latch the guard stops gating recall, so the user's own tools are untouched between runs.
## Knowledge-graph refresh (optional)
Resolve the mode exactly as the hooks below resolve theirs:
`uv run --no-project {project-root}/_bmad/scripts/resolve_customization.py --skill {skill-root} --key workflow.graphify_integration`
Two values, and no others. `off` is the shipped default and a complete no-op — no probe, no delegation, no decision-log line, no output; there is nothing to read further in this section. `refresh` refreshes the project's knowledge graph on the way out, so the next session starts from a current one instead of a stale one.
**Probe first, and degrade to silence.** Two preconditions, both required: graphify resolves on PATH (`command -v graphify`), and a prior `graphify-out/graph.json` exists under `{project-root}` to update. If either is missing there is nothing to refresh: do nothing, print nothing, and write no `.decision-log.md` entry, so the run stays byte-identical to an `off` run. A "skipped it" log line is exactly the difference that would break that, so do not add one. Absence is silent; failure is logged. They are different events. **A probe the permission layer refuses to run is a THIRD state**, distinct from both, and the ordinary unattended one: neither precondition was *evaluated*, so "missing → silent" misfiles a refusal as a resolved absence, and the `WARN graphify-refresh-failed` below asserts a refresh that never started. Log one line, `NOTE graphify-probe-unavailable`, and skip the rest of the section, so the next reader can tell a stale graph from an intentionally ungraphed project.
The graph precondition is not defensive padding. Refresh means refresh: the step updates a graph the developer already has and never creates one. `graphify update` would build one from nothing, so the probe is what enforces that: whether a project gets a graph at all is the developer's call, not one a bounded step on the way out may make. A first-ever run in this mode therefore refreshes nothing and says nothing.
**With both preconditions met, delegate one incremental rebuild from `{project-root}`**: the `.` below is the current working directory, so the output lands in `{project-root}/graphify-out/` unless `GRAPHIFY_OUT` points elsewhere, which the probe above does not follow:
```
GRAPHIFY_NO_AUTO_REFRESH=1 timeout 300 graphify update .
```
`graphify update` is the subcommand that re-extracts the graph's **parsed layer** against what is on disk, with no LLM call: no API key, no token spend at the end of an unattended run, and no network unless the operator has set `GRAPHIFY_GOOGLE_WORKSPACE=1`, which makes graphify export Google Drive shortcuts on every refresh. Never a cold full build. That layer is everything graphify has a local parser for (tree-sitter for most source code, rule-based parsers for the Markdown family and package manifests): the source code plus the Markdown family (`.md`, `.mdx`, `.qmd`, `.skill`), so an Epic's new modules *and* the story and doc files it wrote are both picked up, except a Markdown file the last full build already gave an LLM-derived layer, which keeps that layer and is not re-parsed. What it does not run is the semantic pass: images, PDFs and papers, and any LLM-derived layer over a document, stay as the last full build left them (a source gone from disk or newly ignored still loses its nodes), because that path spends API budget and a bounded exit step may not take it unattended.
Deleting code shrinks the graph, and that is the correct outcome, not a failure: the rebuild accounts for sources that are gone from disk and writes the smaller graph, exit 0, no `WARN`. Narrowing the scan corpus is not a failure either: a file a new `.graphifyignore` rule matches, or an untracked file a new `.gitignore` rule matches, is pruned like a deletion, exit 0, and a `.gitignore` rule never reaches files git already tracks, so they stay. What graphify refuses is an **unexplained** loss, such as nodes from a source still on disk whose extraction failed this run, or a saved LLM-derived node whose file is still on disk. That refusal exits non-zero, so the `WARN` below records it and the graph is left untouched; whether to re-run with `--force` is a decision this step does not get to make.
Pass no other flags. Unlike `graphify extract`, this subcommand rejects an unknown option with a usage error instead of ignoring it, so a flag that stops being real fails loudly here rather than silently doing nothing.
Keep the `GRAPHIFY_NO_AUTO_REFRESH=1` assignment first on that line, exactly as written, and add no other variable to it. Before most commands, `graphify update` included, graphify runs housekeeping outside the graph: on the first command after a graphify upgrade it re-copies the skill files `graphify install` put in the home directory (such as `~/.claude/skills/graphify/`, keeping the old `SKILL.md` as `SKILL.md.bak`), and on any command it can replace an outdated graphify OpenCode plugin, or drop its stale `opencode.json` entry, under `.opencode/` in `{project-root}` or the home directory. The variable turns both off for this one command, so this step writes nothing outside the graph's output and never leaves a modified tracked file behind the last story commit in a project that commits `.opencode/`. The developer's own next graphify command does that housekeeping as usual. Until then, graphify still checks those skill files, so after a graphify upgrade this command prints a warning that the installed skill is out of date and names a `graphify install` command. That warning is expected: exit 0 is still a clean refresh with nothing logged, and neither that command nor any other command graphify's output suggests is this step's to run.
The delegation is hard time-boxed by the `timeout 300` wrapper above and is **not retried**. **Anything other than a clean exit 0 is the same event**: a non-zero exit, a timeout, or a refusal to execute at all (a permission or sandbox denial, which is the ordinary outcome on an unattended host that has not pre-approved the command). Log one `WARN graphify-refresh-failed` line to `.decision-log.md` and move on; never retry, and never stop to ask for approval. A denial is **not** the silent-absence branch above (both preconditions were met, so there is something to refresh), and it is **not a standing fact about the host**: probe and attempt once on every run rather than skipping the step because an earlier run was denied. An operator who wants this step to actually execute unattended should add the whole delegation line, `GRAPHIFY_NO_AUTO_REFRESH=1 timeout 300 graphify update .`, to their own `{workflow.allowlist_commands}`. An entry naming only the binary does not cover it, because Claude Code does not match an allow rule past a leading assignment of a variable it does not know. That entry leaves the refresh unapproved: under Auto Mode the permission classifier decides whether it runs, and a mode that asks first denies it on an unattended host, which is the denial above. The module does not ship the entry, because this integration is off by default.
**This never gates.** It is advisory-only in the same sense Cross-Session Recall is: it writes the developer's `graphify-out/` (or wherever `GRAPHIFY_OUT` points), and, with graphify's housekeeping turned off by the `GRAPHIFY_NO_AUTO_REFRESH=1` assignment, it can change nothing else. A graphify failure, timeout or absence **never changes the gate verdict** and **never changes the terminal envelope**: the run's outcome (complete, blocked or partial-complete), the recorded run-status and the emitted JSON are unchanged whether this step ran, failed, or never fired at all. This section is the only site that calls graphify: no preflight step, no per-story step and no gate step does.
## Record the terminal run-status
Execute maintains the heartbeat `{workflow.implementation_artifacts}/run-status.json` as the spine advances (shape: `{epic, story, index, total, last_verdict, last_reasons, reloop_count, stories, budget_used, profile, updated}`). At close, write its **terminal** state: the final story/index, the `last_verdict` (`advance` when the Epic completed, the escalating story's verdict when blocked, or the last in-scope story's `advance` for a `partial-complete` run, a deliberate strict subset of the Epic delivered with no Epic-level gate), and a fresh `updated` timestamp, so a poller reading the file after the run sees the settled outcome, not a stale mid-run snapshot. **Write the whole shape, not a subset.** This write overwrites the file, so a narrower object silently strips keys a poller was reading mid-run: carry `last_reasons` and `stories` through from the last heartbeat rather than dropping them off the artifact at the moment the run settles. Those two have no fresher source than the snapshot. **`budget_used` does have one, so it is re-derived, never carried**: re-read the final story's `{workflow.implementation_artifacts}/.budget-<story>.json` exactly as every heartbeat write does (execute.md's hook-file-wins rule: "never carry the snapshot's own number forward"). The terminal write is the write most likely to land after turns the last heartbeat never saw (this stage's own), and a carried-forward number under-reports precisely there, in the one direction that matters: a run that ran close to its ceiling reports headroom it did not have. **The enumerated keys are the whole shape.** This file is a single live snapshot, not an accumulating record: do not add a key the shape does not name, and do not carry one forward from an earlier run's write. Dropping an unenumerated key is not narrowing: narrowing loses a key this shape defines and a poller was reading, whereas an unenumerated key has no reader (`scripts/status_render.py` renders exactly these keys and ignores anything else) and no consumer may pin against it (`docs/_internal/STABILITY.md` places this file outside the consumable contract).
A run that stopped on an `evidence-commit-rejected` escalation keeps the verdict that story advanced on (`advance`, or `defer`) as `last_verdict`, since the story advanced, so its terminal `last_reasons` carries one reason naming that story's `escalation-<story_id>.json` and saying its gate evidence is not committed: without it, the last story's stop would read exactly like a completed Epic. The resume that later makes that commit replaces those reasons with one naming the commit it made, rather than carrying the blocked run's forward.
## Surface the deferred-work ledger
Show the user **this run's Epic heading** from the ledger at `{workflow.deferred_work_path}` — the open items under that one heading, their severity and suggested actions — so nothing parked during the run is invisible at handoff. The ledger holds one heading per Epic across runs; do not surface other Epics' parked work. If the file (or this Epic's heading) does not exist, say so plainly: nothing was deferred this run.
## Epic-complete hook
This hook fires **only when the Epic-level gate verdict was `advance`** (a `complete` run) and its evidence is committed. On a `blocked` run (a story escalated, so the Epic never advanced or the evidence commit of its last story waits on the operator), skip this step entirely; a "notify success" command must not fire on a blocked Epic.
When the Epic advanced, run: `uv run --no-project {project-root}/_bmad/scripts/resolve_customization.py --skill {skill-root} --key workflow.on_epic_complete`
If the resolved `{workflow.on_epic_complete}` is non-empty, follow it as the final terminal instruction (a prompt to run or a shell command) before exiting.
## Escalation hook
The mirror of the epic-complete hook at the opposite terminal. This hook fires **only on a `blocked` run** (a story escalated, so the Epic never advanced or the evidence commit of its last story waits on the operator) and never on a clean advance, so an operator who walked away learns that the run stopped being able to make progress on its own.
Execute may already have pinged when the gate escalated a story on its turn count, so this site is deduped against that same run-scoped marker, `{workflow.implementation_artifacts}/.on-escalation-fired-<run-id>`, **check-then-write**, at that byte-identical path, where `<run-id>` is this invocation's run id, minted at Stage 1 or at a resume's re-entry and carried forward verbatim. If the marker is already present, skip silently: the other fire site already pinged for this run. If it is absent, run: `uv run --no-project {project-root}/_bmad/scripts/resolve_customization.py --skill {skill-root} --key workflow.on_escalation`
When the resolved `{workflow.on_escalation}` is non-empty, follow it as an instruction (a prompt to run or a shell command), stating alongside it **the escalating story id** and the path to that story's typed `escalation-<story_id>.json` sidecar as the context it carries, and only then write the fired-marker. A resolved-empty value is a silent no-op — nothing fires and no fired-marker is written — so an empty hook can never suppress a later real one.
This is a side effect on the way out, never a gate on the exit: a hook that errors, hangs or is missing must not change the emitted JSON, the status, or the run-status already recorded.
## Headless output
In headless (`-H`), build the final JSON **through the `scripts/headless_envelope.py` adapter** (never hand-composed here), run the Workflow health check (below), then emit the JSON and stop. `status` is `complete` when the Epic-level gate advanced and its evidence is committed, or `blocked` when a story escalated, the last story's `evidence-commit-rejected` included, though the Epic-level gate advanced before it (`references/gate.md`), and the adapter has one entry point per shape:
```
build_complete_envelope(<path to this run's .decision-log.md>, report=<run-report.md path or None>, deferred_work=<{workflow.deferred_work_path} or None>, impl_artifacts={workflow.implementation_artifacts})
build_headless_envelope(<blocker list>, <path to this run's .decision-log.md>, report=<run-report.md path or None>, deferred_work=<{workflow.deferred_work_path} or None>, impl_artifacts={workflow.implementation_artifacts})
```
**Pick the entry point by SHAPE, not by name.** `build_headless_envelope` is the **blocked** adapter (it is also exported as `build_blocked_envelope`, which is the name to read for); `build_complete_envelope` is the complete one. Handing a complete-shaped mapping to the blocked adapter used to succeed silently: it read no blockers from it, synthesised a `formalize verdict is unreadable or missing` one, appended that fabrication to `.decision-log.md`, and wrote a `blocked` `run-result.json` over a successful run. It now raises instead, before either side effect.
**Both emits are also written to `{workflow.implementation_artifacts}/run-result.json` by `scripts/headless_envelope.py` itself, which is the writer of that file** — so an automator reads a file at a pinned path instead of scraping the transcript for the terminal verdict. The adapter serializes once and hands the same string to both sinks, so the file is byte-identical to what you emit on stdout: print exactly what it produced, do not re-serialize the dict yourself. The write is best-effort and never a gate on the exit — if it fails, the adapter logs `WARN run-result-write-failed` to `.decision-log.md` and the run still emits.
Two constraints on that file:
- **Headless only.** An attended run writes no `run-result.json`. An operator who found a stale one from an attended run would read it as a headless terminal, so do not "helpfully" write it in both modes.
- **Path-pinned and overwrite-in-place**, exactly like `run-status.json`: a second run against the same `{workflow.implementation_artifacts}` overwrites the first run's result.
The emitted object is the **same five-canonical-key shape every headless exit point honors** (Stage 1 first-touch / already-done blocks, Stage 2 preflight block, and this Stage 6 final emit): the five keys `status`/`skill`/`decision_log`/`report`/`deferred_work` are **always present** (`report` and `deferred_work` `null` when not produced), so a caller parsing them never raises a KeyError. A **complete** emit is those five; a **blocked** exit appends a sixth, `reason` (the one-line cause):
```json
{"status": "complete",
"skill": "ultracode-goal",
"decision_log": "<path to this run's .decision-log.md>",
"report": "<path to run-report.md, or null>",
"deferred_work": "<path to {workflow.deferred_work_path}, or null>"}
```
A blocked exit (a story escalated) emits the same five keys plus `reason` — the shape `references/preflight.md` and the `scripts/headless_envelope.py` adapter build (one shared envelope definition), and it lands in the same `run-result.json` the complete emit does.
**`report`/`deferred_work` are `null` only when the artifact was not produced, which is not the same as "blocked".** A run that blocked at Stage 1 or Stage 2 has no report, so both are `null`. A run that **escalated** reached Stage 6 and therefore *does* have a run report and a gate trail: pass them, exactly as the complete emit does. Hard-coding them null under-reports what is on disk for the one run most worth reading.
## Workflow health check (terminal)
After the run-status is settled and (in headless) the JSON is composed but **before** the final emit/exit, load `references/health-check.md`, read it fully and execute it, for a `complete` and a `blocked` (escalated) run alike, since both drove real work. It routes its own headless mode and **never blocks the emit**. Take no other action between this section and the health check: a turn that ends on the run report skips the check.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |