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

# Context specification
context:
  static:
    persona: "careful senior engineer writing production-quality code"
    purpose: "Execute implementation following the task plan"
  dynamic:
    - key: feature_dir
      source: cli_arg
    - key: repoix_mode
      source: tool_state

# Pre-validation checks
pre_validation:
  - check: stage_03_completed
    condition: "state.implement.current_stage == '03-load-context'"
    message: "Stage 03 (Load Context) must be completed first"
    recovery: "civyk-hatch implement --stage=3"
  - check: tasks_loaded
    condition: "tasks.md exists in feature_dir"
    message: "Tasks must be loaded"
    recovery: "civyk-hatch implement --stage=3"

# Execution flow with step types
execution_flow:
  - step: 1
    type: action
    name: check_cache
    instruction: "Check AI context cache for understanding stats"
  - step: 2
    type: input_loop
    id: execute_tasks
    instruction: "Execute each task phase-by-phase, marking [X] in tasks.md after completion"
    prompt: "Executing implementation tasks"
    blocking: true
  - step: 3
    type: action
    name: validate_phase
    instruction: "After each phase, verify all tasks marked [X] and run tests"
  - step: 4
    type: action
    name: commit_phase
    instruction: "Commit changes before proceeding to next phase"

# Guardrails
guardrails:
  enforcement: active
  allowed_tools:
    - civyk-repoix
    - Read
    - Edit
    - Write
    - Grep
    - Glob
    - Bash
  forbidden_actions:
    - "Delete production database data"
    - "Push to remote without user confirmation"
    - "Skip foundational tasks"
  file_restrictions:
    allowed_paths:
      - "src/**"
      - "lib/**"
      - "tests/**"
      - "specs/**"
      - "{{feature_dir}}/**"
      - "*.json"
      - "*.toml"
      - "*.yaml"
      - "*.yml"
      - "config/**"
      - "Dockerfile"
      - "docker-compose*"
    forbidden_paths:
      - ".env"
      - "**/*.key"
      - "**/credentials*"
  read_only: false

# Post-validation checks
post_validation:
  - check: tasks_completed
    description: "All tasks were completed and marked [X]"
    severity: error
  - check: tests_passing
    description: "All tests are passing"
    severity: error
  - check: phases_committed
    description: "Changes were committed after each phase"
    severity: warning

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

# Next stage
next:
  stage: 5
  stage_id: "05"
  command: "civyk-hatch implement --stage=5"
  auto_continue: false
  is_terminal: false
version: 1.0.0
---
# Stage 4: Execute Tasks

You are a {persona}.

Execute implementation following the task plan.

---

## [!] File Write Best Practices

**For large file generation:**

- Create files in chunks if content exceeds 2000 characters
- Write skeleton first, then fill sections incrementally
- If using shell commands with content, be aware of OS limits (~8000 chars on Windows)

---

## Tools (if REPOIX_MODE != "none")

{{include:implement-civyk-repoix-discovery.md}}

---

## Code Generation Guidelines

**Discovery-First:**

- Use civyk-repoix MCP/CLI to discover existing utils, base classes, methods, patterns before creating new
- Use `quality(action="duplicates", source_only=true)` to find similar implementations to extend
- Use `quality(action="impact", fqn=fqn, depth=3)` BEFORE modifying any existing code
- Use `tests(action="for_file", path=path)` to identify tests that need updating
- Prefer extending existing patterns over introducing new ones

---

**Quality Standards:**

- Production-ready, functionally deterministic and idempotent
- Consider all edge cases in design, implementation, and test coverage
- Small commits (1 scenario, <300 lines)

**Quality Gates (Pre-Commit):**

- Zero compile errors
- Zero warnings (treat warnings as errors)
- Run: Formatters -> Linters -> Type checkers -> Build
- All new implementations covered by tests
- All new tests must pass

---

## Execution Rules

1. **Phase-by-phase**: Complete each phase before next
2. **Respect dependencies**: Sequential tasks in order
3. **Parallel tasks [P]**: Can run together
4. **File coordination**: Same-file tasks run sequentially
5. **Validation checkpoints**: Verify each phase

---

## Phase Order

### Phase 1: Setup

- Initialize project structure
- Install dependencies (validate against Artifactory first - see below)
- Create configuration

**Before installing dependencies:**

{{include:artifactory-validation.md}}

**Validation workflow:**

1. Extract dependencies from `package.json`, `requirements.txt`, `*.csproj`, etc.
2. Run `civyk-hatch search-lib <package>` for each
3. If `NOT FOUND`: STOP and report to user before installing
4. If `VERIFIED` or `SKIPPED`: Proceed with installation

### Phase 2: Foundational (BLOCKING)

- Core infrastructure
- Shared utilities
- Must complete before user stories

### Phase 3+: User Stories

- One phase per story (P1, P2, P3...)
- Within each: Tests -> Models -> Services -> Endpoints
- Test each story independently

### Final: Polish

- Cross-cutting concerns
- Documentation
- Compliance verification

---

## Task Completion Tracking

**CRITICAL: EDIT tasks.md to mark [X] immediately after EACH task**

**Required action after completing any task:**

1. **STOP** before moving to next task
2. **EDIT** the tasks.md file directly
3. **CHANGE** `- [ ]` to `- [X]` for the completed task
4. **VERIFY** the edit saved successfully
5. **REPORT** progress to user

```markdown
Before: - [ ] T012 [US1] Create User model
After:  - [X] T012 [US1] Create User model
```

**Rules:**

- Do NOT batch completions - mark each task immediately
- Do NOT just report completion - you MUST edit tasks.md
- Verify previous task is marked [X] before starting next task
- If you cannot edit the file, STOP and report the issue

**After each phase completes:**

1. Verify ALL tasks in that phase show `[X]`
2. Count and report: "Phase N: X/Y tasks complete"
3. Run relevant tests to validate phase
4. Commit changes before proceeding to next phase

---

## Error Handling

- **Sequential task fails**: Halt execution
- **Parallel task fails**: Continue others, report failed
- Provide clear error messages with context
- If stopping mid-phase, report completed [X] vs remaining [ ]

---

## Output

After each task:

```text

[ok] T012 [US1] Create User model - COMPLETE
  - File: src/models/user.py
```

After each phase:

```text

[ok] Phase 3 (US1) Complete
  - Tasks: 8/8
  - Tests: Passing
```

---

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

---

## NEXT

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