# Phase 06: Cleanup

## Entry Gate

```bash
devforgeai-validate phase-check ${STORY_ID} --workflow=qa --from=05 --to=06 --project-root=.
# Exit 0: proceed | Exit 1: Phase 05 incomplete
```

## Contract

| | |
|---|---|
| **PURPOSE** | Release locks, invoke feedback hooks, display execution summary. |
| **REQUIRED SUBAGENTS** | none |
| **REQUIRED ARTIFACTS** | Execution summary displayed, feedback hooks invoked |
| **STEP COUNT** | 5 mandatory steps |

## CLI Consolidation (OPT-003)

Steps 6.1, 6.2, 6.5 are deterministic and replaceable by one CLI:
```bash
devforgeai-validate qa-cleanup ${STORY_ID} --result=${overall_status} --workflow=qa --project-root=.
# Exit 0: cleanup complete (JSON with lock_released, hooks_invoked, markers_cleaned)
# Exit 1: cleanup issue (gaps.json missing for FAILED result)
```

On exit 0, the orchestrator still MUST execute Steps 6.3 and 6.4 (execution summary requires LLM formatting). Extract cleanup status from JSON.

If CLI unavailable (exit 127) or fails, fall back to the manual steps below.

---

## Reference Loading

```
Read(file_path=".claude/skills/spec-driven-qa/references/phase-4-cleanup-workflow.md")
Read(file_path=".claude/skills/spec-driven-qa/references/feedback-hooks-workflow.md")
```

---

## Mandatory Steps

### Step 6.1: Release Lock File

EXECUTE: Delete the QA lock file acquired in Phase 01.
```
lock_file = "{story_paths.results_dir}/.qa-lock"
Glob(pattern=lock_file)
IF exists:
    Bash(command="rm {lock_file}")
    Display "Lock released for ${STORY_ID}"
ELSE:
    Display "Lock file not found (already released or not acquired)"
```
VERIFY: Lock file no longer exists.
```
Glob(pattern=lock_file)
IF still exists: Display "WARNING: Lock file removal failed"
```
RECORD: `devforgeai-validate phase-record ${STORY_ID} --workflow=qa --phase=06 --step=6.1 --project-root=.`

---

### Step 6.2: Invoke Feedback Hooks (Non-Blocking)

EXECUTE: Map QA result to hook status; invoke if available. Hook failures do NOT block QA completion.
```
IF overall_status == "PASSED":  STATUS = "success"
ELIF overall_status == "FAILED": STATUS = "failure"
ELSE:                            STATUS = "partial"

Bash(command="devforgeai-validate check-hooks --operation=qa --status=${STATUS} --project-root=. 2>&1")

IF exit_code == 0:
    Bash(command="devforgeai-validate invoke-hooks --operation=qa --story=${STORY_ID} --project-root=. 2>&1")
    Display "Feedback hooks: Invoked (status: ${STATUS})"
ELSE:
    Display "Feedback hooks: Not available or disabled"
# Non-blocking: continue regardless.
```
VERIFY: Hook check executed; invocation attempted if available; workflow continues regardless.
RECORD: `devforgeai-validate phase-record ${STORY_ID} --workflow=qa --phase=06 --step=6.2 --project-root=.`

---

### Step 6.3: Display Execution Summary (MANDATORY)

EXECUTE: Display phase-by-phase status — enforces visibility before completion.
```
Display:
"
======================================================================
                      QA EXECUTION SUMMARY
======================================================================
  Story: ${STORY_ID}
  Mode:  ${MODE}
----------------------------------------------------------------------
  PHASE EXECUTION STATUS:
  - [x] Phase 01: Setup           (Lock: YES, Type: ${DELIVERABLE_TYPE})
  - [x] Phase 02: Validation      (Traceability: {traceability_score}%)
  - [x] Phase 03: Diff Regression (Result: {phase_3_result})
  - [x] Phase 04: Analysis        (Validators: {success}/{total})
  - [x] Phase 05: Reporting       (Status: {overall_status})
  - [x] Phase 06: Cleanup         (Hooks: {hook_status})
----------------------------------------------------------------------
  Story File Updated: YES
  Result: {overall_status}
======================================================================
"
```

**Enforcement Logic:**
```
unchecked_count = count_unchecked_phases()

IF unchecked_count > 0:
    Display "WARNING: {unchecked_count} phases may have been skipped"
    AskUserQuestion: "Phases appear incomplete. Re-run skipped phases, Continue (NOT RECOMMENDED), or Abort?"
    IF "Re-run":  GOTO first skipped phase
    IF "Continue": Log warning
    IF "Abort":    HALT workflow

IF unchecked_count == 0:
    Display "All phases complete — no skipped steps detected"
```

VERIFY: Execution summary displayed; all phases marked complete (or user acknowledged incomplete state).
RECORD: `devforgeai-validate phase-record ${STORY_ID} --workflow=qa --phase=06 --step=6.3 --project-root=.`

---

### Step 6.4: Display Final QA Validation Summary

EXECUTE: Final formatted summary with metrics and next steps.
```
Display:
"
======================================================================
                    QA VALIDATION COMPLETE
======================================================================
  Story: ${STORY_ID}
  Mode:  ${MODE}
  Result: {overall_status}
----------------------------------------------------------------------
  Coverage:
    Business Logic: {biz}%    | Application: {app}%
    Infrastructure: {infra}% | Overall:     {overall}%
----------------------------------------------------------------------
  Violations: {critical} CRITICAL | {high} HIGH
              {medium} MEDIUM   | {low} LOW
----------------------------------------------------------------------
  Next Steps:
    [If PASSED] Ready for /release ${STORY_ID}
    [If FAILED] Run /dev ${STORY_ID} --fix for remediation
======================================================================
"
```
<!-- gaps.json verified in Phase 05 Step 5.3 — not re-checked here per optimization R-005 -->

VERIFY: Final summary displayed.
RECORD: `devforgeai-validate phase-record ${STORY_ID} --workflow=qa --phase=06 --step=6.4 --project-root=.`

---

### Step 6.5: Marker Cleanup (PASSED Only)

EXECUTE: Preserve qa-phase-state.json as permanent audit trail. Delete legacy markers only if PASSED.
```
IF overall_status == "PASSED":
    # PRESERVE: qa-phase-state.json (permanent audit trail — DO NOT DELETE)
    Glob(pattern="devforgeai/workflows/${STORY_ID}-qa-phase-state.json")
    IF found: Display "qa-phase-state.json preserved as permanent audit trail"
    ELSE:     Display "WARNING: qa-phase-state.json not found — audit trail missing"

    # DELETE: legacy .qa-phase-N.marker files (superseded by qa-phase-state.json)
    Glob(pattern="devforgeai/qa/reports/${STORY_ID}/.qa-phase-*.marker")
    FOR each marker_file: Bash(command="rm {marker_file}")
    Display "Legacy .qa-phase-N.marker files cleaned up"
ELSE:
    Display "QA FAILED — all files retained for debugging and resume capability"
```
VERIFY: If PASSED, qa-phase-state.json preserved + legacy markers deleted. If FAILED, all files retained.
RECORD: `devforgeai-validate phase-record ${STORY_ID} --workflow=qa --phase=06 --step=6.5 --project-root=.`

---

## Exit Gate

```bash
devforgeai-validate phase-complete ${STORY_ID} --workflow=qa --phase=06 --checkpoint-passed --project-root=.
# Exit 0: QA workflow complete | Exit 1: HALT
```

## Phase 06 Completion Display

```
Phase 06 Complete: Cleanup
  QA workflow complete — all 6 phase gates passed
  Result: {overall_status}
```
