# Phase 04: Design Pattern Selection

## Entry Gate

```bash
devforgeai-validate phase-check ${DEVARCH_ID} --workflow=development-architecture --from=03 --to=04 --project-root=. 2>&1
```

| Exit Code | Action |
|-----------|--------|
| 0 | Proceed to Phase 04 |
| 127 | CLI not installed — proceed without enforcement |
| Other | HALT — previous phase not complete |

---

## Contract

| Attribute | Value |
|-----------|-------|
| **PURPOSE** | Prescribe the design patterns the feature implementation will use — Repository, Factory, Strategy, Dependency Injection, Adapter, and the like — with where each applies and why. Patterns MUST be consistent with `coding-standards.md` and MUST affirmatively avoid the forbidden constructs in `anti-patterns.md` (e.g. Dependency Injection in place of direct instantiation, Repository in place of SQL concatenation). |
| **REFERENCE** | `.claude/skills/spec-driven-development-architecture/references/development-architecture-output.schema.json` |
| **STEP COUNT** | 4 mandatory steps |

## Phase Exit Criteria

Before this phase can complete, ALL of the following MUST be true:

- [ ] `coding-standards.md` and `anti-patterns.md` loaded (or an explicit fallback recorded)
- [ ] `design_patterns` enumerated — each with a `pattern` and an `applies_to`
- [ ] No prescribed pattern conflicts with `anti-patterns.md`
- [ ] Each component or interaction that needs a pattern has one prescribed, with a rationale

**IF any criterion is unmet: HALT. Do NOT proceed to Phase 05.**

---

## Reference Loading [MANDATORY]

```
Read(file_path=".claude/skills/spec-driven-development-architecture/references/development-architecture-output.schema.json")
Read(file_path="devforgeai/specs/context/coding-standards.md")
Read(file_path="devforgeai/specs/context/anti-patterns.md")
```

`coding-standards.md` and `anti-patterns.md` are constitutional files this phase MUST
load — every prescribed pattern must conform to the former and affirmatively avoid the
latter (Step 4.1). Both are hook-enforced: `pre-phase-record-reference-check.sh`
(ADR-091) blocks `phase-record` for this phase if either was not Read(). The output
schema above defines the `$defs.design_pattern` shape (`pattern`, `applies_to`,
`rationale`) each step must produce. IF any Read fails: HALT — "Phase 04 references
not loaded."

Do NOT rely on memory of previous reads. Load fresh every time this phase executes.

---

## Mandatory Steps

### Step 4.1: Load the Coding Standards and Anti-Patterns

**EXECUTE:**
```
Glob(pattern="devforgeai/specs/context/coding-standards.md")
IF found:
  Read(file_path="devforgeai/specs/context/coding-standards.md")
  Extract pattern-relevant conventions — error handling, dependency management,
  naming, structural rules.
ELSE:
  Record an explicit fallback: standard clean-architecture conventions.

Glob(pattern="devforgeai/specs/context/anti-patterns.md")
IF found:
  Read(file_path="devforgeai/specs/context/anti-patterns.md")
  Extract the forbidden constructs — God Objects, direct instantiation,
  SQL concatenation, hardcoded secrets, etc.
ELSE:
  Record an explicit fallback: the anti-patterns from .claude/rules/core/critical-rules.md Rule 8.
```

`coding-standards.md` and `anti-patterns.md` are constitutional and immutable —
read them, never edit them.

**VERIFY:**
- Coding-standards conventions captured (from the context file or the recorded fallback)
- The anti-pattern set captured (from the context file or the recorded fallback)

**RECORD:**
```bash
devforgeai-validate phase-record ${DEVARCH_ID} --workflow=development-architecture --phase=04 --step=4.1 --project-root=. 2>&1
```
```json
{ "phase": "04", "step": "4.1", "coding_standards_source": "<coding-standards.md|fallback>",
  "anti_patterns_source": "<anti-patterns.md|fallback>" }
```

---

### Step 4.2: Select the Design Patterns

**EXECUTE:**

For each feature component (Phase 02 `feature_components`, with its layer from
Phase 03) and each significant inter-component interaction or interface contract,
prescribe the design pattern(s) the implementation will use:

```
design_pattern = {
  pattern: "<e.g. Repository, Factory, Strategy, Dependency Injection, Adapter,
            Decorator, Observer, Command>",
  applies_to: "<the component(s) — COMP-NNN — or the interaction the pattern governs>",
  rationale: "<why this pattern fits: the problem it solves here, and which
              coding-standards convention or anti-pattern it serves>"
}
```

Pattern guidance:
- An infrastructure component that persists an entity → **Repository** (keeps SQL
  out of the domain; counters the SQL-concatenation anti-pattern).
- Construction of a collaborator → **Dependency Injection** (counters the
  direct-instantiation anti-pattern; Phase 05 wires it).
- A component with several interchangeable algorithms → **Strategy**.
- An adapter to an external system / `sol_integration_design` target → **Adapter**.
- Do NOT prescribe a pattern with no problem to solve — pattern-for-its-own-sake is
  itself a smell. A trivially simple component may need no named pattern; record it
  as such rather than inventing one.

**VERIFY:**
- Every component or interaction needing a pattern has ≥ 1 `design_pattern`
- Every `design_pattern` has a non-empty `pattern` and `applies_to`

**RECORD:**
```bash
devforgeai-validate phase-record ${DEVARCH_ID} --workflow=development-architecture --phase=04 --step=4.2 --project-root=. 2>&1
```
```json
{ "step": "4.2", "design_patterns": [ { "pattern": "...", "applies_to": "...",
  "rationale": "..." } ] }
```

---

### Step 4.3: Validate Against the Anti-Patterns

**EXECUTE:**
```
FOR each design_pattern:
  - Confirm it does not itself introduce an anti-patterns.md violation (e.g. a
    Factory that becomes a God Object, a Singleton that hides global state).
  - Confirm the pattern set, taken together, affirmatively counters the
    anti-patterns relevant to the feature — every component that could fall into a
    forbidden construct has a pattern that prevents it.
  - A prescribed pattern that conflicts with coding-standards.md or anti-patterns.md
    is a constraint violation — HALT and AskUserQuestion.
```

**VERIFY:**
- No prescribed pattern conflicts with `anti-patterns.md` or `coding-standards.md`

**RECORD:**
```bash
devforgeai-validate phase-record ${DEVARCH_ID} --workflow=development-architecture --phase=04 --step=4.3 --project-root=. 2>&1
```
```json
{ "step": "4.3", "anti_pattern_conflicts_resolved": [ ... ] }
```

---

### Step 4.4: Record the Design Patterns

**EXECUTE:**
```
Assemble the design_patterns array — each entry a full design_pattern object with
pattern, applies_to, and rationale.
```

**VERIFY:**
- `design_patterns` is an array; every entry has `pattern` and `applies_to`

**RECORD:**
```bash
devforgeai-validate phase-record ${DEVARCH_ID} --workflow=development-architecture --phase=04 --step=4.4 --project-root=. 2>&1
```
```json
checkpoint.phases["04"] = {
  "status": "completed",
  "coding_standards_source": "<source>",
  "anti_patterns_source": "<source>",
  "design_patterns": [
    { "pattern": "Repository", "applies_to": "COMP-003",
      "rationale": "..." }, ...
  ]
}
```

---

## Exit Gate

```bash
devforgeai-validate phase-complete ${DEVARCH_ID} --workflow=development-architecture --phase=04 --checkpoint-passed --project-root=. 2>&1
```

| Exit Code | Action |
|-----------|--------|
| 0 | Phase 04 complete — proceed to next phase |
| 127 | CLI not installed — proceed without enforcement |
| Other | HALT — checkpoint/step validation failed |

---

## Phase Transition Display

```
Display:
  "Phase 04 Complete: Design Pattern Selection"
  "Patterns prescribed: {count}  |  Distinct patterns: {list}"
  "Anti-pattern conflicts: {count} resolved"
  "Proceeding to Phase 05: Module Structure & Dependency Wiring"
```
