# Phase 07: Specification Validation

**Purpose:** Comprehensive validation of generated UI specification with user-driven issue resolution.

**Core Principle:** "Ask, Don't Assume" — Never auto-fix. All issues presented to user for resolution.

**Pre-Flight:** Verify Phase 06 completed.

---

## Reference Loading [MANDATORY]

```
Read(file_path=".claude/skills/spec-driven-ui/references/specification-validation.md")
Read(file_path=".claude/skills/spec-driven-ui/references/design-source-of-truth-schema.md")
Read(file_path="devforgeai/specs/context/tech-stack.md")
Read(file_path="devforgeai/specs/context/dependencies.md")
Read(file_path="devforgeai/specs/context/anti-patterns.md")
```

IF any Read fails: HALT -- "Phase 07 reference files not loaded."

---

## Step 7.1: Load Specification Validation Reference

**EXECUTE:**
```
Read(file_path=".claude/skills/spec-driven-ui/references/specification-validation.md")
```

**VERIFY:**
- File content loaded into context
- Content contains validation checklist

**RECORD:**
```
Bash(command="devforgeai-validate phase-record ${IDENTIFIER} ${WORKFLOW_FLAG} --phase=07 --step=7.1 --project-root=. 2>&1")
```

---

## Step 7.2: Completeness Check

**EXECUTE:**
Read the generated spec and validate these 10 required sections exist:
1. Component hierarchy
2. Props/API documented
3. State management approach
4. Styling approach
5. Accessibility considerations
6. Responsive behavior
7. Test strategy
8. Usage examples
9. Integration instructions
10. Dependencies listed

Record which sections are present and which are missing.

**VERIFY:**
- All 10 sections checked
- Missing sections list compiled

**RECORD:**
```
Bash(command="devforgeai-validate phase-record ${IDENTIFIER} ${WORKFLOW_FLAG} --phase=07 --step=7.2 --project-root=. 2>&1")
```

---

## Step 7.3: Placeholder Detection

**EXECUTE:**
```
Grep(pattern="TODO|TBD|FILL IN|PLACEHOLDER|FIXME", path="${OUTPUT_PATH}", output_mode="content")
```

Record all placeholders with line numbers.

**VERIFY:**
- Grep completed (even if no matches)
- Placeholder list compiled (may be empty — that's valid)

**RECORD:**
```
Bash(command="devforgeai-validate phase-record ${IDENTIFIER} ${WORKFLOW_FLAG} --phase=07 --step=7.3 --project-root=. 2>&1")
```

---

## Step 7.4: Framework Constraint Validation

**EXECUTE:**
Read and validate against context files:
```
Read(file_path="devforgeai/specs/context/tech-stack.md")
Read(file_path="devforgeai/specs/context/source-tree/governance.json")
Read(file_path="devforgeai/specs/context/dependencies.md")
Read(file_path="devforgeai/specs/context/anti-patterns.md")
```

Check:
- Technology used matches tech-stack.md approved list
- File location matches source-tree/ patterns
- Dependencies are in dependencies.md approved list
- No forbidden anti-patterns present (God Objects, hardcoded values, etc.)

Compile validation summary with severity levels: HIGH / MEDIUM / LOW.

**VERIFY:**
- All 4 context files read
- Validation summary compiled with severity ratings

**RECORD:**
```
Bash(command="devforgeai-validate phase-record ${IDENTIFIER} ${WORKFLOW_FLAG} --phase=07 --step=7.4 --project-root=. 2>&1")
```

---

## Step 7.5: User Resolution of Issues

**EXECUTE:**
For each category of issues found, present to user via AskUserQuestion:

**Missing sections (if any):**
```
AskUserQuestion:
  Question: "The following spec sections are missing: [list]. How should I handle them?"
  Header: "Missing Sections"
  Options:
    - label: "Add with defaults"
      description: "I'll generate reasonable defaults for missing sections"
    - label: "Accept as-is"
      description: "Proceed without these sections (PARTIAL status)"
    - label: "Regenerate"
      description: "Regenerate the component with all sections"
  multiSelect: false
```

**Placeholders (if any):**
```
AskUserQuestion:
  Question: "Found ${COUNT} placeholders in the generated code. How should I handle them?"
  Header: "Placeholders"
  Options:
    - label: "Resolve now"
      description: "I'll help fill in each placeholder"
    - label: "Accept as-is"
      description: "Leave placeholders for manual resolution later"
  multiSelect: false
```

**Framework violations (if any):**
```
AskUserQuestion:
  Question: "Found constraint violations: [summary]. How should I proceed?"
  Header: "Violations"
  Options:
    - label: "Fix now"
      description: "Apply fixes to resolve violations"
    - label: "Show detailed report"
      description: "Display full violation details"
    - label: "Accept with warnings"
      description: "Proceed with PARTIAL status"
  multiSelect: false
```

Apply user decisions.

**VERIFY:**
- All issue categories presented to user (or skipped if no issues)
- User decisions captured and applied

**RECORD:**
```
Bash(command="devforgeai-validate phase-record ${IDENTIFIER} ${WORKFLOW_FLAG} --phase=07 --step=7.5 --project-root=. 2>&1")
```

---

## Step 7.6: Design Source of Truth Validation

**EXECUTE:**

1. Check if design.md was generated:
```
design_exists = Glob(pattern="devforgeai/specs/ui/design.md")
```

IF design.md exists:

2. Load schema reference:
```
Read(file_path=".claude/skills/spec-driven-ui/references/design-source-of-truth-schema.md")
```

3. **Metadata validation:**
```
Grep(pattern="schema_version:", path="devforgeai/specs/ui/design.md", output_mode="content")
Grep(pattern="document_type:", path="devforgeai/specs/ui/design.md", output_mode="content")
```
Verify: schema_version = "1.0", document_type = "ui-design-source-of-truth"

4. **Template placeholder check:**
```
Grep(pattern="\\$\\{", path="devforgeai/specs/ui/design.md", output_mode="count")
```
IF count > 0: Record as WARNING — unpopulated template variables remain

5. **Required token validation:**
Check these minimum required tokens exist (not null/empty):
- colors.background, colors.surface, colors.text_primary, colors.primary, colors.error, colors.success, colors.border
- spacing.unit = "8px"
- typography.font_family.primary
- At least 4 typography scale entries

6. **Component inventory validation:**
```
Grep(pattern="id: \"COMP-", path="devforgeai/specs/ui/design.md", output_mode="count")
```
Verify: At least 1 COMP-NNN entry exists

7. **Cross-reference validation (ALL reference sources):**
Extract all COMP-NNN IDs from components section (the master inventory).
Extract all COMP-NNN references from EVERY source:
  - `layouts[].regions[].components[]` — layout region assignments
  - `interactions[].steps[].component` — interaction flow step targets
  - `interactions[].steps[].state_changes[].component` — state change targets
  - `components[].children[]` — parent-child hierarchy
  - `components[].parent` — parent references (except "root")
  - `animations[].target` — animation targets

For each reference: verify it exists in the components section master inventory.
Report any dangling references with severity CRITICAL (RCA-003: internally inconsistent design.md means an AI would encounter undefined components).

```
dangling_refs = []
FOR each ref_source in [layouts, interactions, children, parent, animations]:
  FOR each COMP-NNN reference in ref_source:
    IF COMP-NNN NOT in master inventory:
      dangling_refs.append({ source: ref_source, id: COMP-NNN })

IF len(dangling_refs) > 0:
  Display: "CRITICAL: ${len(dangling_refs)} dangling COMP references found (RCA-003)"
  FOR each ref in dangling_refs:
    Display: "  - ${ref.id} referenced in ${ref.source} but not in component inventory"
```

8. **Token Reference Audit:**
```
# Check that component visual sections use token references, not raw values.
# Extract all unique values from component visual.appearance and visual.spacing sections.
# Cross-reference each value against the tokens section.

raw_value_count = 0
token_ref_count = 0

FOR each component in design.md:
  FOR each visual property (background, border, shadow, padding, margin, gap, border_radius):
    value = property value
    IF value starts with "colors." or "spacing." or "borders." or "shadows." or "motion.":
      token_ref_count += 1
    ELIF value matches hex (#XXXXXX), rgba(), or px pattern:
      # Check if this raw value exists in Section 2 tokens
      IF value matches any token.value in Section 2:
        raw_value_count += 1
        FLAG: "LOW: Raw value '${value}' in ${component.name} should be '${matching_token_name}'"

normalization_pct = token_ref_count / (token_ref_count + raw_value_count) * 100
Display: "Token normalization: ${normalization_pct}%"

IF normalization_pct < 70:
  WARNING: "LOW: Token normalization below 70% — ${raw_value_count} raw values could use token references"
```

9. **Accessibility completeness:**
```
Grep(pattern="wcag_level:", path="devforgeai/specs/ui/design.md", output_mode="content")
```
Verify: wcag_level is set (not placeholder)

IF design.md does NOT exist:
- This is valid for older invocations or when Phase 06 Step 6.2.5 was not executed
- Record as INFO, not error — design.md generation is an enhancement

Compile design.md validation results:
- CRITICAL issues: Missing schema_version, zero components, dangling COMP references
- WARNING issues: Template placeholders, missing optional tokens, incomplete accessibility
- INFO: design.md not generated (backward compatibility)

**VERIFY:**
- All validation checks executed
- Results compiled with severity levels

**RECORD:**
```
Bash(command="devforgeai-validate phase-record ${IDENTIFIER} ${WORKFLOW_FLAG} --phase=07 --step=7.6 --project-root=. 2>&1")
```

---

## Step 7.7: Design Source of Truth User Resolution

**EXECUTE:**

IF design.md validation found CRITICAL or WARNING issues:

```
AskUserQuestion:
  Question: "Design Source of Truth (design.md) validation found issues: [summary]. How should I handle them?"
  Header: "design.md"
  Options:
    - label: "Fix now"
      description: "Resolve all issues in design.md"
    - label: "Accept with warnings"
      description: "Proceed — issues will be noted but not block completion"
    - label: "Regenerate design.md"
      description: "Re-run Phase 06 Step 6.2.5 to regenerate the document"
  multiSelect: false
```

Apply user's chosen resolution.

IF no issues: Skip this step.

**VERIFY:**
- User decision captured and applied (or no issues to resolve)

**RECORD:**
```
Bash(command="devforgeai-validate phase-record ${IDENTIFIER} ${WORKFLOW_FLAG} --phase=07 --step=7.7 --project-root=. 2>&1")
```

---

## Step 7.8: Determine Final Validation Status

**EXECUTE:**
Based on ALL validation results (spec completeness + placeholder + framework constraints + design.md) and user decisions:

```
IF no issues OR all issues resolved:
    STATUS = "SUCCESS"
ELIF user accepted warnings / partial completion:
    STATUS = "PARTIAL"
ELIF critical violations remain unresolved:
    STATUS = "FAILED"
    HALT — "Specification validation failed. Critical issues remain unresolved."
```

Display final status to user, including design.md status:
- design.md generated: YES/NO
- design.md validation: PASSED/WARNING/FAILED/N-A

**VERIFY:**
- STATUS is one of: SUCCESS, PARTIAL, FAILED
- If FAILED: Workflow halts with error message

**RECORD:**
```
Bash(command="devforgeai-validate phase-record ${IDENTIFIER} ${WORKFLOW_FLAG} --phase=07 --step=7.8 --project-root=. 2>&1")
```

---

## Phase 07 Completion

**EXECUTE:**
```
Bash(command="devforgeai-validate phase-complete ${IDENTIFIER} ${WORKFLOW_FLAG} --phase=07 --project-root=. 2>&1")
```

**VERIFY:**
- Exit code 0 or 2 (backward compatibility)

**NEXT:** Proceed to Phase 08 (Feedback & Completion).
