---

# Stage identity per spec Section 6.1
stage: 3
stage_id: "03"
title: "Load Context"
workflow: implement
estimated_tokens: 2800

# Context specification
context:
  static:
    persona: "careful senior engineer writing production-quality code"
    purpose: "Load design documents and verify project structure"
  dynamic:
    - key: feature_dir
      source: cli_arg
    - key: repoix_mode
      source: tool_state

# Pre-validation checks
pre_validation:
  - check: stage_02_completed
    condition: "state.implement.current_stage == '02-setup'"
    message: "Stage 02 (Setup) must be completed first"
    recovery: "civyk-hatch implement --stage=2"

# Execution flow with step types
execution_flow:
  - step: 1
    type: action
    name: check_cache
    instruction: "Check AI context cache for cached feature understanding"
  - step: 2
    type: action
    name: load_docs
    instruction: "Load design documents (tasks.md, plan.md, data-model.md, contracts/, etc.)"
    output_variable: tasks_loaded
  - step: 3
    type: action
    name: store_understanding
    instruction: "Store feature understanding in AI context cache"
  - step: 4
    type: action
    name: verify_structure
    instruction: "Create/verify ignore files based on tech stack"
    output_variable: structure_verified
  - step: 5
    type: action
    name: parse_tasks
    instruction: "Parse task structure from tasks.md (phases, dependencies, execution flow)"

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

# Post-validation checks
post_validation:
  - check: tasks_loaded
    description: "Tasks were loaded from tasks.md"
    severity: error
  - check: structure_verified
    description: "Project structure was verified"
    severity: warning
  - check: context_cached
    description: "Feature context was stored in AI cache"
    severity: info

# Output specification
output:
  state_update:
    implement.current_stage: "03-load-context"
  completion_command: "civyk-hatch update-stage implement 03 --status completed"

# Next stage
next:
  stage: 4
  stage_id: "04"
  command: "civyk-hatch implement --stage=4"
  is_terminal: false
version: 1.0.0
---

{{include:ai-cache-enforcement.md}}

# Stage 3: Load Context

You are a {persona}.

Load design documents and verify project structure.

---

## Step 1: Load Design Documents (with AI Context Cache)

**FIRST:** Check cached understanding from prior sessions:

```text
# IF REPOIX_MODE != "none":
# Check what's cached from earlier stages
understand(action="stats", limit=50)

# Recall cached feature understanding
understand(action="recall", target="{{feature_dir}}")
# IF error (MCP connection failed): Load documents manually
# IF found AND fresh: Use cached context, verify key points still apply
# IF not found OR stale: Load documents below and store understanding

# IF REPOIX_MODE == "none":
# Cache unavailable — load all documents directly below
```

From FEATURE_DIR:

- **REQUIRED**: `tasks.md` - Complete task list
- **REQUIRED**: `plan.md` - Tech stack, architecture
- **IF EXISTS**: `data-model.md` - Entities
- **IF EXISTS**: `contracts/` - API specs
- **IF EXISTS**: `research.md` - Decisions
- **IF EXISTS**: `quickstart.md` - Integration scenarios

**AFTER loading:** Store feature understanding for cross-session recall:

```text
# IF REPOIX_MODE != "none":
# [!] MANDATORY: Store understanding after loading feature context
understand(action="store",
  scope="module",
  target="{{feature_dir}}",
  purpose="Feature implementation context for <feature_name>",
  importance="high",
  key_points=["<tech_stack>", "<key_entities>", "<main_tasks>"],
  gotchas=["<constraints>", "<dependencies>"],
  analysis="<detailed_logic_and_flow_explanation>",
  related_to=["<spec.md>", "<plan.md>", "<tasks.md>"]
)

# IF REPOIX_MODE == "none":
# Cache unavailable — retain loaded context in session memory for this run
```

---

## Step 2: Verify Project Setup

Create/verify ignore files based on tech stack:

**Detection:**

- `git rev-parse --git-dir` -> create .gitignore
- `Dockerfile*` exists -> create .dockerignore
- `.eslintrc*` exists -> create .eslintignore

**Common Patterns by Stack:**

- **Node.js**: `node_modules/`, `dist/`, `*.log`, `.env*`
- **Python**: `__pycache__/`, `.venv/`, `*.pyc`
- **Java**: `target/`, `*.class`, `build/`
- **.NET**: `bin/`, `obj/`, `*.user`
- **Universal**: `.DS_Store`, `.idea/`, `.vscode/`

**If file exists**: Append missing critical patterns only
**If missing**: Create with full pattern set

**Error handling**: If file write fails (permission denied, read-only), log warning and continue. Ignore file failures are non-blocking.

---

## Step 3: Parse Task Structure

From tasks.md extract:

- **Phases**: Setup, Tests, Core, Integration, Polish
- **Dependencies**: Sequential vs parallel rules
- **Details**: ID, description, file paths, `[P]` markers
- **Execution flow**: Order and dependency requirements

---

## Output

```text

[ok] Context loaded
  - Tasks: [N] across [N] phases
  - Tech stack: [detected]
  - Ignore files: [verified / created]

  AI Cache Status:
    - Feature context cached: [yes/no]
    - Design docs read: <count_read>
    - Understanding stored: <count_stored>
    - Compliance: <count_stored>/<count_read> = <percentage>%
```

**AI Cache Compliance Check:**

Before proceeding to execute, verify:

1. Feature context stored via `understand(action="store", scope="module", target="{{feature_dir}}")`
2. Each design doc read has corresponding understanding stored
3. If compliance < 100%, go back and store missing understandings

> **IF REPOIX_MODE == "none":** Skip this compliance check entirely. Cache operations are unavailable. Report compliance as "N/A (no repoix)" and proceed.

---

## NEXT

```bash
civyk-hatch implement --stage=4 --feature-dir="{FEATURE_DIR}"
```
