# Phase 01.10: Story Complexity Analysis [INFORMATIONAL] (STORY-172)

**Purpose:** Warn user about potentially oversized stories that may require multiple TDD iterations.

**When to execute:** After Phase 01.9.5 (Load Structured Gap Data), before proceeding to Phase 02.

**Token Cost:** ~500 tokens

---

## Metrics to Analyze

```
dod_count = count(DoD items in story)
ac_count = count(Acceptance Criteria)
tech_spec_lines = count(lines in Technical Specification section)
files_touched = count(files mentioned in tech spec)
```

**Extraction Logic:**

```
# Extract metrics from story file
story_content = Read(file_path="devforgeai/specs/Stories/${STORY_ID}.story.md")

# Count DoD items (checkbox pattern in Definition of Done section)
dod_count = Grep(pattern="^\\s*-\\s*\\[[ x]\\]", path=story_file, output_mode="count")

# Count Acceptance Criteria (### AC# headers)
ac_count = Grep(pattern="^###\\s*AC#", path=story_file, output_mode="count")

# Count Technical Specification lines
tech_spec_lines = count_lines_in_section("## Technical Specification", story_content)

# Count files mentioned in tech spec
files_touched = Grep(pattern="\\.(md|py|ts|js|sh|json|yaml)\\b", path=story_file, output_mode="count")
```

---

## Complexity Thresholds

**Centralized Threshold Definitions:**

```
THRESHOLDS = {
  "dod": { "high": 20, "very_high": 30 },
  "ac": { "high": 5, "very_high": 8 },
  "tech_spec": { "high": 100, "very_high": 200 },
  "files": { "high": 10, "very_high": 20 }
}

COMPLEXITY_LEVELS = {
  "very_high": 4,  # score >= 4
  "high": 2,       # score >= 2
  "medium": 1,     # score >= 1
  "normal": 0      # score < 1
}
```

**Scoring Summary:**

| Metric | High Threshold | Very High Threshold | Points |
|--------|----------------|---------------------|--------|
| DoD items | >20 | >30 | 1 + 1 = 2 max |
| AC count | >5 | >8 | 1 + 1 = 2 max |
| Tech spec lines | >100 | >200 | 1 + 1 = 2 max |
| Files touched | >10 | >20 | 1 + 1 = 2 max |
| **Total Possible Score** | | | **0-8** |

---

## Complexity Scoring Logic

```
FUNCTION calculate_complexity_score(metrics):
  """
  Calculate complexity score by checking each metric against thresholds.
  Maximum score: 8 (all dimensions at very high)
  """
  score = 0

  score += (metrics.dod_count > THRESHOLDS.dod.high) ? 1 : 0
  score += (metrics.dod_count > THRESHOLDS.dod.very_high) ? 1 : 0

  score += (metrics.ac_count > THRESHOLDS.ac.high) ? 1 : 0
  score += (metrics.ac_count > THRESHOLDS.ac.very_high) ? 1 : 0

  score += (metrics.tech_spec_lines > THRESHOLDS.tech_spec.high) ? 1 : 0
  score += (metrics.tech_spec_lines > THRESHOLDS.tech_spec.very_high) ? 1 : 0

  score += (metrics.files_touched > THRESHOLDS.files.high) ? 1 : 0
  score += (metrics.files_touched > THRESHOLDS.files.very_high) ? 1 : 0

  RETURN score
END FUNCTION

FUNCTION get_complexity_level(score):
  normalized_score = MAX(0, MIN(8, score))

  IF normalized_score >= 4:
    RETURN "VERY HIGH"
  ELSIF normalized_score >= 2:
    RETURN "HIGH"
  ELSIF normalized_score >= 1:
    RETURN "MEDIUM"
  ELSE:
    RETURN "NORMAL"
  END IF
END FUNCTION
```

---

## Warning Display (if score >= 2)

```
IF complexity_score >= 2:
    Display: ""
    Display: "⚠️  STORY COMPLEXITY ASSESSMENT"
    Display: "================================"
    Display: ""
    Display: "Complexity Level: {complexity_level}"
    Display: ""

    # Display metrics exceeding thresholds
    IF dod_count > THRESHOLDS.dod.high:
        Display: "  • DoD items: {dod_count} (threshold: 20)"
    IF ac_count > THRESHOLDS.ac.high:
        Display: "  • Acceptance Criteria: {ac_count} (threshold: 5)"
    IF tech_spec_lines > THRESHOLDS.tech_spec.high:
        Display: "  • Tech spec size: {tech_spec_lines} lines (threshold: 100)"
    IF files_touched > THRESHOLDS.files.high:
        Display: "  • Files to modify: {files_touched} (threshold: 10)"

    Display: ""
    Display: "⚠️  Recommendation: This story may require 2-3+ TDD iterations"
    Display: ""
```

---

## User Decision Point

```
IF complexity_score >= 2:
    AskUserQuestion:
        Question: "How would you like to proceed?"
        Header: "Complexity"
        Options:
            - "Continue - I understand this is a large story"
            - "Show me what could be split out"
            - "Stop - I'll break this into smaller stories first"
        multiSelect: false

    SWITCH user_response:

        CASE "Continue - I understand this is a large story":
            Display: "✓ Proceeding with large story development"
            Display: "  Note: Consider checkpointing progress frequently"
            # Continue to Phase 02

        CASE "Show me what could be split out":
            # Invoke Split Suggestion Logic (see below)
            INVOKE: Split Suggestion Analysis
            # Re-ask after showing suggestions

        CASE "Stop - I'll break this into smaller stories first":
            Display: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
            Display: "  WORKFLOW HALTED - Break Into Smaller Stories"
            Display: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
            Display: ""
            Display: "Recommended approach:"
            Display: "  1. Review the DoD items and group by logical boundaries"
            Display: "  2. Create 2-3 smaller stories from the groups"
            Display: "  3. Run /dev on each smaller story"
            HALT workflow

ELSE:
    # complexity_score < 2 (NORMAL or MEDIUM)
    Display: "✓ Story complexity: {complexity_level} (within normal range)"
    # Continue to Phase 02
```

---

## Split Suggestion Logic

```
FUNCTION build_split_suggestions(metrics):
  suggestions = []

  IF metrics.dod_count > THRESHOLDS.dod.high:
    half_point = CEILING(metrics.dod_count / 2)
    suggestions.append({
      header: "DoD Grouping (by implementation phase)",
      items: [
        "Items 1-{half_point} → STORY-A (core functionality)",
        "Items {half_point+1}-{dod_count} → STORY-B (features + edge cases)"
      ]
    })

  IF metrics.ac_count > THRESHOLDS.ac.high:
    ac_split = CEILING(metrics.ac_count / 2)
    suggestions.append({
      header: "AC Grouping (by acceptance boundary)",
      items: [
        "AC#1 to AC#{ac_split} → STORY-A (happy path)",
        "AC#{ac_split+1} to AC#{ac_count} → STORY-B (edge cases)"
      ]
    })

  IF metrics.files_touched > THRESHOLDS.files.high:
    suggestions.append({
      header: "File Grouping (by architectural layer)",
      items: [
        "Domain/Model layer files → STORY-A",
        "Application/API layer files → STORY-B",
        "Infrastructure files → STORY-C"
      ]
    })

  RETURN suggestions
END FUNCTION

# Display suggestions
Display: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
Display: "  STORY SPLIT SUGGESTIONS"
Display: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
Display: ""

FOR suggestion IN suggestions:
    Display: "  {suggestion.header}:"
    FOR item IN suggestion.items:
        Display: "    • {item}"
    Display: ""

# Re-ask user after showing suggestions
AskUserQuestion:
    Question: "After reviewing split suggestions, how would you like to proceed?"
    Options:
        - "Continue - I understand this is a large story"
        - "Stop - I'll break this into smaller stories first"
```

---

## Complexity Quick Reference

```
Complexity Level Mapping:

  NORMAL:     score 0-1   (story is appropriately sized, proceed normally)
  MEDIUM:     score 1     (story is larger than typical, may need 2+ iterations)
  HIGH:       score 2-3   (story is large, likely 2-3+ iterations, warn user)
  VERY HIGH:  score 4-8   (story is very large, likely 3-5+ iterations, urgent warning)

User Actions by Level:

  NORMAL/MEDIUM:  Display checkmark, proceed to Phase 02
  HIGH/VERY HIGH: Display warning, prompt user for decision:
                  - Continue (understand implications)
                  - Show split suggestions (architectural grouping)
                  - Stop and break into smaller stories
```

---

## Logging for Retrospective

```
# After development workflow completes
complexity_log = {
    "story_id": STORY_ID,
    "assessed_complexity": complexity_level,
    "complexity_score": complexity_score,
    "metrics": { dod_count, ac_count, tech_spec_lines, files_touched },
    "actual_iterations": count_tdd_iterations(),
    "user_decision": user_response,
    "timestamp": current_timestamp()
}

Write(
    file_path="devforgeai/feedback/complexity-assessments/${STORY_ID}.json",
    content=json_stringify(complexity_log)
)
```

**Framework Learning:**
- Actual iterations vs predicted complexity allows threshold calibration
- High-iteration stories predicted as NORMAL suggest threshold adjustment needed
