---
# Stage identity per spec Section 6.1
stage: 1
stage_id: "01"
title: "Coverage Review"
workflow: tests
estimated_tokens: 2000

# Context specification
context:
  static:
    persona: "meticulous QA engineer focused on test coverage and code quality"
    purpose: "Identify test gaps and high-risk untested areas"
  dynamic:
    - key: feature_dir
      source: cli_arg
    - key: user_args
      source: cli_arg
      default: ""
    - key: iterations
      source: cli_arg
      default: 1

# Pre-validation checks
pre_validation: []

# Execution flow with step types
execution_flow:
  - step: 1
    type: conditional
    name: check_direct_mode
    instruction: "Check if user_args contains scope info for direct mode"
    condition: "user_args is not empty"
  - step: 2
    type: input_required
    id: scope_input
    prompt: "What to test? Enter: scope (files/module/branch), target % (default 80), type (unit/integration/both)"
    blocking: true
    condition: "user_args is empty"
  - step: 3
    type: action
    name: detect_repoix
    instruction: "Detect civyk-repoix mode (MCP, CLI, or none)"
    output_variable: discovery_mode
  - step: 4
    type: action
    name: discover_gaps
    instruction: "Use civyk-repoix to find test gaps and high-risk untested code"
  - step: 5
    type: action
    name: analyze_structure
    instruction: "Analyze file structure and identify untested functions"
  - step: 6
    type: action
    name: measure_coverage
    instruction: "Run test command with coverage measurement"
    output_variable: current_coverage
  - step: 7
    type: action
    name: prioritize_gaps
    instruction: "Prioritize gaps by risk level (P0-P3)"
  - step: 8
    type: action
    name: create_test_plan
    instruction: "Create prioritized test plan with estimated coverage impact"

# Guardrails - STAGE 1 IS READ-ONLY (analysis only)
guardrails:
  enforcement: active
  allowed_tools:
    - civyk-repoix
    - Read
    - Grep
    - Glob
    - Bash  # Only for: pytest --cov, git commands
    - WebFetch
  forbidden_actions:
    - "Write or create any test files"
    - "Edit or modify any test files"
    - "Fix failing tests"
    - "Delete any files"
    - "Modify source code"
  read_only: true  # Stage 1 is analysis only - Stage 2 writes tests

# Post-validation checks
post_validation:
  - check: coverage_measured
    description: "Current coverage percentage was measured"
    severity: error
  - check: test_plan_created
    description: "Test plan with prioritized gaps was created"
    severity: error

# Output specification
output:
  state_update:
    tests.status: "in_progress"
    tests.current_stage: "01-coverage-review"
  completion_command: "civyk-hatch update-stage tests 01 --status completed"

# Next stage
next:
  stage: 2
  stage_id: "02"
  command: "civyk-hatch tests --stage=2"
  auto_continue: true
  is_terminal: false
version: 1.0.0
---
{{include:strict-execution-mode.md}}

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

# Stage 1: Coverage Review

You are a {persona}.

Find **test gaps** and **high-risk untested areas**. Create a prioritized test plan. Think like a QA engineer identifying the most impactful tests, not just chasing coverage %.

---

## [!] STAGE 1 IS READ-ONLY

**DO NOT in Stage 1:**
- Write new test files
- Fix failing tests
- Modify existing test files
- Edit any code

**Stage 1 ONLY:**
- Discovers gaps (using civyk-repoix)
- Measures current coverage
- Creates a test plan for Stage 2

**If tests are failing:** Report them in the test plan as "existing failures to fix" - do NOT fix them here. Stage 2 handles all test writing and fixing.

---

## Direct Mode (Args Provided)

If `{user_args}` contains scope info (e.g., "src/auth", "80%", "unit tests"):

1. Parse scope, target, type from args - NO user prompts needed
2. Jump directly to **Step 1: Detect civyk-repoix Mode**

Examples that trigger direct mode:
- `src/auth/ 90%` -> scope=src/auth, target=90%
- `unit tests for payment` -> type=unit, scope=payment
- `feature branch` -> scope=changed files vs main

---

## Interactive Mode (No Args)

Only if `{user_args}` is empty or "$NONE" or "$SKIP":

**[STOP: USER_INPUT_REQUIRED]**

What to test? Enter: scope (files/module/branch), target % (default 80), type (unit/integration/both)

Example: `src/auth/** 90% unit` or just press enter for full project at 80%

---

## Step 1: Check civyk-repoix Mode

Check `context.tool_state.repoix_mode` from the JSON response above:
- `mcp` -> Use MCP tool calls
- `cli` -> Use `civyk-repoix query` commands
- `none` -> Use manual file reads only

**Note**: Mode is auto-detected and cached. No manual detection needed.

---

## Tools Reference

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

---

## Step 2: Discover Test Gaps with civyk-repoix

**Find high-risk untested code:**

```text
# MCP mode:
git(action="hotspots", since="30d", limit=20)           # High-churn = high-risk
quality(action="dead_code", limit=30)                    # May indicate untested code
tests(action="for_file", path="src/module.py")           # What tests exist?
tests(action="recommended", changed_files=[...])         # What tests should run?

# CLI mode:
civyk-repoix query git --action hotspots --since 30d --limit 20
civyk-repoix query quality --action dead_code --limit 30
civyk-repoix query tests --action for_file --path "src/module.py"
civyk-repoix query tests --action recommended --changed-files "f1.py,f2.py"
```

**Find API endpoints for integration tests:**

```text
# MCP mode:
architecture(action="endpoints", kind="function", limit=50)

# CLI mode:
civyk-repoix query architecture --action endpoints --kind function --limit 50
```

---

## Step 3: Analyze File Structure

For each file in scope:

```text
# MCP mode:
file(action="symbols", path="src/auth/login.py", kinds=["function", "class"])

# CLI mode:
civyk-repoix query file --action symbols --path "src/auth/login.py" --kinds "function,class"
```

**Identify untested functions:**
- Public functions without corresponding test
- Error handling paths
- Edge case branches

---

## Step 4: Measure Current Coverage

Run project's test command with coverage:

```bash
# Python
pytest --cov=src --cov-report=term-missing

# Node.js
npm test -- --coverage

# Other
{project-specific coverage command}
```

```text
Scope: {scope} ({file_count} files)
Target: {TARGET}% | Current: {current}% | Gap: {gap}%
```

If current >= target: `[ok] TARGET MET` -> STOP

---

## Step 5: Prioritize Gaps

| Priority | What to Test | Why |
|----------|--------------|-----|
| P0 | Auth, payment, security | Critical paths |
| P0 | Public API endpoints | User-facing |
| P1 | Error handling, validation | Failure modes |
| P2 | Edge cases, boundaries | Robustness |
| P3 | Utilities, helpers | Lower risk |

---

## Step 6: Gap Report

| File | Current % | Key Untested Functions | Priority |
|------|-----------|----------------------|----------|
| path/to/file.py | 45% | `validate_token`, `handle_error` | P0 |

---

## Step 7: Test Plan

```text
=== TEST PLAN ===

Scope: {scope}
Target: {TARGET}% | Current: {current}% | Gap: {gap}%
Type: {TEST_TYPE}

Phase 1: Critical Paths (+{N}%)
  T-001: Test auth token validation - src/auth/token.py:validate
  T-002: Test payment processing errors - src/payment/process.py:handle_error

Phase 2: Error Handling (+{N}%)
  T-003: Test invalid input handling - src/api/handlers.py:parse_request

Phase 3: Edge Cases (+{N}%)
  T-004: Test boundary conditions - src/utils/validators.py:check_range

Total: {N} tests to write
Estimated coverage after: {estimated}%
```

---

## Step 8: Store Cache

```text
understand(action="store", scope="module", target="<path>", purpose="Test coverage analysis",
  importance="high", key_points=["untested: X,Y,Z"], gotchas=["critical path in auth"])
```

---

## [AUTO-CONTINUE]

After creating the test plan, automatically proceed to Stage 2 to implement tests.

## NEXT

```bash
civyk-hatch tests --stage=2 --iterations={iterations} \
  --target-coverage={TARGET} \
  --scope-mode={SCOPE_MODE} \
  --scope-pattern="{SCOPE_PATTERN}" \
  --test-type={TEST_TYPE}
```
