---
name: "step-09-finalize"
description: "Finalize the single-story pipeline run and output completion report."
nextStepFile: null
kind: "terminal"
---

# Step 9 of 9: Pipeline Finalization

**Goal:** Generate the final completion report for this single-story pipeline run.

**Role:** Pipeline Orchestrator

---

## EXECUTION SEQUENCE

### 1. Refresh Sprint Status

1. Load the FULL file: `{sprint_status}` (fresh read from disk — do NOT rely on in-memory state from earlier steps; step-08 may have updated multiple keys including the epic marker)
2. Read ALL lines from beginning to end — do not skip any content
3. Recount all stories by current status (exclude epic markers like `epic-{n}` and retrospective markers like `epic-{n}-retrospective` from story counts; tally them separately if useful):
   - `{backlog_count}` — Stories with status "backlog"
   - `{ready_count}` — Stories with status "ready-for-dev"
   - `{in_progress_count}` — Stories with status "in-progress"
   - `{review_count}` — Stories with status "review"
   - `{done_count}` — Stories with status "done"
4. Sanity check: verify the just-completed story `{current_story_key}` has status "done" in sprint-status.yaml. If it does NOT:
   - Output WARNING — "Sprint status for {current_story_key} is '{actual_status}', not 'done'. step-08 may not have synced. Manual review recommended."
   - Append to `{run_warnings}` with canonical prefix tag: `[step-09] Sprint status for {current_story_key} is '{actual_status}', not 'done' — step-08 sync may have failed`
   - Continue with report generation regardless.

### 2. Generate Final Report

Increment `{steps_completed}` to count step-09 itself as a distinct executed step file (mirrors the +1 pattern used by steps 02–08; without this line, a fresh run that executes all nine step files would display `8 / 9` instead of `9 / 9`, because step-09 would otherwise be silently uncounted):

- Set `{steps_completed}` = `{steps_completed}` + 1

**Note on `{steps_completed}` semantics:** `{steps_completed}` is the count of *distinct step files executed in THIS pipeline run*, not the total step count in the pipeline (which is always 9). A fresh run reaches 9 only when every step file executes exactly once. Common fresh runs legitimately finish below 9: a run where step-05 routes directly to step-07 skips step-06 (QA testing), and a run that needs no fixes skips step-07 (fix-and-retest) — both correctly display `8 / 9`. A value under 9 is therefore expected, not an error, because the counter tracks distinct step files actually executed. For a `resume` run (e.g., starting at step-04 because story status was "in-progress"), the value reflects only the steps actually loaded plus step-09 itself — display it relative to 9 so it is unambiguous.

Output:
```
Auto Story Pipeline — COMPLETE

Pipeline Summary:
- Mode: {pipeline_mode}
- Story Processed: {current_story_key}
- Steps Executed (this run): {steps_completed} / 9
- Fix Iterations: {fix_iteration} / {max_fix_iterations}
- Pipeline Status: finalized

Sprint Status (current):
- Backlog: {backlog_count} remaining
- Ready for Dev: {ready_count}
- In Progress: {in_progress_count}
- In Review: {review_count}
- Done: {done_count}

The automated story development pipeline has finished.
```

**IF `{epic_just_completed}` is set (signal from step-08 section 4):**
- Output: "Epic {epic_just_completed} is now fully complete. Recommended next action: run epic-retrospective (ER) to capture lessons learned before starting the next epic. Command: `/xiaoma-retrospective` (or `ER` from the Dev (xiaokai) menu)."

**IF `{backlog_count}` == 0 AND `{ready_count}` == 0 AND `{in_progress_count}` == 0 AND `{review_count}` == 0:**
- Output: "All stories in the sprint are complete! Consider running epic-retrospective (ER) to review the work."

**IF `{backlog_count}` > 0 OR `{ready_count}` > 0:**
- Output: "There are still {backlog_count + ready_count} pending stories. Run ASPB (`/xiaoma-auto-story-pipeline-batch`) to process all remaining stories in batch mode, or run ASP again to process the next story."

### 3. Generate Machine-Readable Status File

Write machine-readable status to: `{implementation_artifacts}/story-pipeline-status.json`

This brings parity with `auto-requirements-pipeline` (which writes `pipeline-status.json`) and enables downstream tools — including `auto-story-pipeline-batch` (ASPB) and `auto-full-pipeline` — to inspect per-story outcomes programmatically without re-parsing sprint-status.yaml.

**Warnings serialization:**

Read the accumulated `{run_warnings}` list and serialize it as-is into the `warnings` array — each entry MUST already carry its canonical `[step-NN]` prefix tag (see `auto-story-pipeline/workflow.md` → "Warning Prefix-Tag Convention" for the dictionary). Do NOT strip, reorder, or de-duplicate entries here; downstream consumers (ASPB scheduler, auto-full step-05-finalize) handle de-dup and 100-entry truncation in their own aggregation passes.

Common sources that contribute entries to `{run_warnings}` during a typical run:
- `[step-01]` — prerequisite probe (stale `pipeline-status.json`); incomplete story-file routing entry
- `[step-02]` — sprint-status / on-disk inconsistency; incomplete created story retry
- `[step-03]` — non-terminal validation iteration WARNING
- `[step-05]` — CRITICAL finding routed to step-07; auto-fix produced regression
- `[step-06]` — coverage threshold not enforced; type-C performance carve-out
- `[step-07]` — max fix iterations reached / escalation dispatched
- `[step-08]` — sprint-status write fallback; epic-completion check skipped due to unparseable story key
- `[step-09]` — sanity-check WARNING from section 1 item 4 above (this step). (Note: this step's section 1 contains 4 numbered items, not subsections; AW2 fixed an earlier "section 1.4" reference that implied a non-existent `### 1.4` heading.)

If `{run_warnings}` is empty, serialize as `[]`.

```json
{
  "pipeline": "auto-story-pipeline",
  "date": "{date}",
  "project": "{project_name}",
  "mode": "{pipeline_mode}",
  "story_key": "{current_story_key}",
  "story_path": "{current_story_path}",
  "final_status": "done",
  "steps_completed_this_run": {steps_completed},
  "pipeline_total_steps": 9,
  "fix_iterations_used": {fix_iteration},
  "max_fix_iterations": {max_fix_iterations},
  "epic_just_completed": "{epic_just_completed}",
  "sprint_snapshot": {
    "backlog": {backlog_count},
    "ready_for_dev": {ready_count},
    "in_progress": {in_progress_count},
    "review": {review_count},
    "done": {done_count}
  },
  "warnings": [
    "[step-NN] human-readable description (see workflow.md → Warning Prefix-Tag Convention)",
    "..."
  ]
}
```

If `{epic_just_completed}` is null, write `"epic_just_completed": null` (not the literal placeholder). If no warnings were captured, write `"warnings": []`. Each warning entry MUST retain its `[step-NN]` prefix tag as emitted by the source step — do not strip.

**Write strategy:** Write to a temp file in the same directory (e.g., `story-pipeline-status.json.tmp`), then rename to the final name. This avoids leaving a half-written status file if the process is interrupted between writes.

**HALT** — Pipeline complete.

---

## SUCCESS METRICS

- Final sprint status refreshed from disk
- Sanity check on `{current_story_key}` performed (warning emitted if not "done"; tagged `[step-09]` and appended to `{run_warnings}`)
- Comprehensive completion report generated, with `{steps_completed}` rendered as `N / 9` for clarity
- `{epic_just_completed}` signal consumed (ER recommendation emitted when set)
- `story-pipeline-status.json` written atomically with full run metadata
- `warnings[]` entries all carry canonical `[step-NN]` prefix tags (single-source-of-truth dictionary lives in `auto-story-pipeline/workflow.md` → "Warning Prefix-Tag Convention")
- User informed of remaining stories and next steps

## FAILURE MODES

- Not refreshing sprint status before generating report
- Skipping final report generation
- Writing `story-pipeline-status.json` without temp-file-then-rename (risk of half-written JSON if interrupted)
- Reporting `{steps_completed}` without the `/ 9` denominator (ambiguous in resume mode)
- Serializing `warnings[]` entries WITHOUT the `[step-NN]` prefix (breaks ASPB / auto-full-pipeline aggregation contract — single-story mode and batch mode would diverge in warning format)
