---
# Stage identity per spec Section 6.1
stage: 4
stage_id: "04"
title: "Design"
workflow: plan
estimated_tokens: 2000

# Context specification
context:
  static:
    persona: "senior software architect designing pragmatic systems"
    purpose: "Fill remaining plan.md sections and generate supporting artifacts"
  dynamic:
    - key: feature_dir
      source: cli_arg
    - key: repoix_mode
      source: tool_state

# Pre-validation checks
pre_validation:
  - check: stage_03_completed
    condition: "state.plan.current_stage == '03-research'"
    message: "Stage 03 (Research) must be completed first"
    recovery: "civyk-hatch plan --stage=3"
  - check: research_exists
    condition: "research.md exists in feature_dir"
    message: "research.md must exist"
    recovery: "civyk-hatch plan --stage=3"
  - check: plan_chunk1_complete
    condition: "Summary, Technical Context, Constitution Check are filled"
    message: "Plan chunk 1 must be complete"
    recovery: "civyk-hatch plan --stage=3"

# Execution flow with step types
execution_flow:
  - step: 1
    type: action
    name: check_cache
    instruction: "Check AI context cache for cached understanding of relevant modules"
  - step: 2
    type: action
    name: fill_plan_chunk2
    instruction: "Fill Project Structure, High-Level Architecture, and Cross-Cutting Concerns sections"
  - step: 3
    type: action
    name: fill_plan_chunk3
    instruction: "Fill Data Architecture, Integration Architecture, Migration Plan, and Risk Assessment sections"
  - step: 4
    type: action
    name: create_data_model
    instruction: "Create data-model.md with entities, relationships, and validation rules"
  - step: 5
    type: action
    name: create_contracts
    instruction: "Create API contracts in contracts/ directory"
  - step: 6
    type: action
    name: create_quickstart
    instruction: "Create quickstart.md with setup instructions"
  - step: 7
    type: action
    name: final_validation
    instruction: "Verify all placeholders are replaced in plan.md"

# Guardrails
guardrails:
  enforcement: active
  allowed_tools:
    - civyk-repoix
    - Read
    - Edit
    - Write
    - Grep
    - Glob
    - Bash
  forbidden_actions:
    - "Delete production source files"
    - "Modify source code outside spec directory"
  file_restrictions:
    allowed_paths:
      - "specs/**"
      - "{{feature_dir}}/**"
    forbidden_paths:
      - ".env"
      - "**/*.key"
  read_only: false

# Post-validation checks
post_validation:
  - check: plan_complete
    description: "All plan.md sections filled with no placeholders"
    severity: error
  - check: data_model_created
    description: "data-model.md was created"
    severity: warning
  - check: contracts_created
    description: "API contracts were created"
    severity: warning
  - check: quickstart_created
    description: "quickstart.md was created"
    severity: warning

# Output specification
output:
  state_update:
    plan.status: "completed"
    plan.current_stage: "04-design"
  completion_command: "civyk-hatch update-stage plan 04 --status completed"

# Next stage - terminal
next:
  is_terminal: true
version: 1.0.0
---
# Stage 4: Design & Complete Plan

You are a {persona}.

1. Fill remaining plan.md sections (Chunks 2 and 3)
2. Generate supporting artifacts (data-model.md, contracts/, quickstart.md)

---

## [!] File Write Best Practices

**For large artifacts:**

- Use chunked writing when content exceeds 2000 characters
- Steps 1-2 are already chunked for plan.md
- For supporting artifacts (Step 3), write each section separately if large
- If using shell commands with content, be aware of OS limits (~8000 chars on Windows)

---

## Step 1: Check Cache

Before designing new components, check cached understanding and discover existing codebase patterns:

```text
# Check what's cached from earlier stages
understand(action="stats", limit=50)
# Use cached coverage to decide: full discovery vs targeted gap-filling
```

- Use civyk-repoix MCP/CLI to discover existing infrastructure, frameworks, patterns
- Use `quality(action="duplicates", source_only=true)` to find similar implementations to consolidate or extend
- Design on top of existing architecture rather than introducing parallel approaches
- Consider edge cases in architectural decisions

---

## Prerequisites

Verify before proceeding:

- [ ] `{{feature_dir}}/plan.md` exists with template
- [ ] `{{feature_dir}}/research.md` is complete
- [ ] Summary, Technical Context, Constitution Check are filled

---

## Step 2: Fill Plan Sections (Chunk 2 of 3)

Edit `{{feature_dir}}/plan.md` to fill these sections:

### 2.1 Project Structure

- Choose appropriate structure (single/web/mobile)
- Remove unused options
- Fill actual directory paths

### 2.2 High-Level Architecture

- Create component interaction diagram (Mermaid)
- Define architecture pattern and justification
- Fill component responsibilities table

### 2.3 Cross-Cutting Concerns

Fill applicable subsections (delete if not needed):

- Error Handling
- Security
- Observability
- Caching Strategy
- Resilience Patterns
- API Design
- Configuration

**IMPORTANT**: Replace ALL `[...]` placeholders with actual content.

---

## Step 3: Fill Plan Sections (Chunk 3 of 3)

Continue editing `{{feature_dir}}/plan.md`:

### 3.1 Data Architecture

- Data Model (entities, relationships)
- Database Schema (with DDL)
- Data Flow Diagram
- Data Validation rules

### 3.2 Integration Architecture

- External Dependencies table (with Artifactory validation - see below)
- Integration Patterns
- Failure Handling table
- API Contracts

**Validate External Dependencies:**

{{include:artifactory-validation.md}}

Ensure External Dependencies table includes Artifactory status:

```markdown
| Dependency | Version | Purpose | Artifactory Status |
|------------|---------|---------|-------------------|
| package-a  | ^1.2.0  | Auth    | [VERIFIED]        |
| package-b  | ^3.0.0  | ORM     | [NOT FOUND - blocked] |
```

**For blocked dependencies:** Add to Risk Assessment (2.4) as blockers.

### 3.3 Migration/Rollout Plan (if applicable)

- Backward Compatibility
- User Communication

### 3.4 Risk Assessment (if applicable)

- Risks table
- Assumptions table
- Dependencies & Blockers
- Open Questions

**IMPORTANT**: Replace ALL remaining `[...]` placeholders. Delete sections marked "CONDITIONAL" if not applicable.

---

## Step 4: Create data-model.md

Use the **Write tool** to create `{{feature_dir}}/data-model.md`:

```markdown
# Data Model: <feature name>

## Entity: [Name]

**Fields:**

- field1: type (constraints)
- field2: type (constraints)

**Relationships:**

- has_many: [Entity]
- belongs_to: [Entity]

**Validation:**

- [rule from requirements]
```

## Step 5: Create contracts/ Directory

Create API contract files in `{{feature_dir}}/contracts/`:

- OpenAPI spec (for REST)
- GraphQL schema (if applicable)

## Step 6: Create quickstart.md

Use the **Write tool** to create `{{feature_dir}}/quickstart.md`:

- Local development setup
- Environment variables
- Database setup
- Running tests
- API examples

---

## Step 7: Final Validation

Verify plan.md is complete:

```bash
# Check for remaining placeholders
grep -E '\[.*\]|NEEDS CLARIFICATION|ACTION REQUIRED' {{feature_dir}}/plan.md
```

**All placeholders must be replaced or sections deleted.**

---

## Output

```text
[ok] Planning complete

Artifacts generated:
  - {{feature_dir}}/plan.md (all sections filled)
  - {{feature_dir}}/research.md
  - {{feature_dir}}/data-model.md
  - {{feature_dir}}/contracts/
  - {{feature_dir}}/quickstart.md
```

**Note:** Next steps are generated by CLI (`emit_complete`) - do not duplicate here.

{{include:verification-rules.md}}

---

## WORKFLOW COMPLETE

Planning is done. Proceed to task generation.
