---

# Stage identity per spec Section 6.1
stage: 1
stage_id: "01"
title: "Deep Code Review"
workflow: review
estimated_tokens: 3000

# Context specification
context:
  static:
    persona: "senior engineer doing thorough PR review"
    purpose: "Find potential issues and potential enhancements through deep code review"
    severity_levels:
      CRITICAL: "Data loss, crashes, security breach, race conditions with data corruption"
      HIGH: "Production degradation - unhandled exceptions, resource leaks, incorrect logic"
      MEDIUM: "Resilience gaps - missing timeouts, retries, fallbacks, monitoring, graceful degradation"
      LOW: "Code quality - magic numbers, duplicated code, naming inconsistencies"
      ENHANCEMENT: "Nice-to-have - refactoring, performance optimizations (non-blocking)"
    severity_examples:
      - pattern: "Missing HTTP timeout"
        severity: "MEDIUM"
        rationale: "Production resilience issue - can hang indefinitely"
      - pattern: "No retry logic on transient failure"
        severity: "MEDIUM"
        rationale: "Resilience gap - reduces system availability"
      - pattern: "Unhandled exception in background task"
        severity: "HIGH"
        rationale: "Can crash worker, lose data"
      - pattern: "Magic number in calculation"
        severity: "LOW"
        rationale: "Code quality - maintainability concern"
  dynamic:
    - key: feature_dir
      source: cli_arg
    - key: user_args
      source: cli_arg
      default: ""
    - key: review_scope
      source: cli_arg
    - key: review_focus
      source: cli_arg
    - key: scope_files
      source: cli_arg
    - key: iterations
      source: cli_arg
    - key: max_agents
      source: cli_arg
      default: 5

# Sub-agent architecture for context efficiency (informational metadata, not parsed by engine)
# Actual sub-agent instructions are in the prompt body below
sub_agent:
  enabled: true
  purpose: "Analyze files in parallel, preserving main agent context"
  max_concurrent: "{max_agents}"
  checkpoint_after_batch: true
  sub_agent_receives:
    - file_path: "The file to analyze"
    - change_context: "What changed in this file (from delta pack)"
    - review_focus: "Focus area: security | correctness | integration | full"
    - related_files: "List of related files for cross-reference"
  sub_agent_returns:
    - file_path: "Analyzed file path"
    - issues: "List of issues found with severity"
    - enhancements: "List of potential improvements"
    - status: "success | partial | failed"
    - error: "Error message if failed"

# Pre-validation checks
pre_validation: []

# Execution flow with step types
execution_flow:
  - step: 1
    type: conditional
    name: check_mode
    instruction: "Determine if direct mode (args provided) or interactive mode (no args)"
    condition: "user_args is not empty and not '$SKIP'"
  - step: 2
    type: input_required
    id: scope_selection
    instruction: "Ask user what to review if no args provided"
    prompt: "What to review? (A) Feature branch, (B) Staged, (C) Last N commits, (D) Files, (E) Uncommitted"
    skip_condition: "direct mode detected"
  - step: 3
    type: action
    name: detect_repoix
    instruction: "Detect civyk-repoix mode (MCP or CLI)"
    output_variable: repoix_mode
  - step: 4
    type: action
    name: get_changes
    instruction: "Get changed files with civyk-repoix or git diff"
    output_variable: changed_files
  - step: 5
    type: action
    name: analyze_impact
    instruction: "Analyze impact of changes using civyk-repoix tools"
    output_variable: impact_analysis
  - step: 6
    type: action
    name: cross_reference
    instruction: "Cross-reference for consistency across similar files"
    output_variable: consistency_check
  - step: 6.5
    type: action
    name: build_review_context
    instruction: "Build architectural context before domain agents start"
    actions:
      - "understand(action=\"recall\", scope=project) for design patterns"
      - "architecture(action=\"components\") for system boundaries"
      - "quality(action=\"circular_deps\") for coupling"
      - "git(action=\"hotspots\", since=90d) for change-prone files"
      - "git(action=\"changes\", limit=50) for recurring patterns"
      - "Extract repo_guidelines from context if available"
    output_variable: review_context
  - step: 7
    type: parallel
    name: deep_analysis
    instruction: "Spawn sub-agents to analyze files in parallel (max {max_agents} concurrent)"
    max_concurrent: "{max_agents}"
    checkpoint: true
  - step: 8
    type: action
    name: aggregate_results
    instruction: "Collect results from sub-agents, aggregate findings"
    output_variable: findings
  - step: 9
    type: action
    name: cross_domain_synthesis
    instruction: "Merge findings, detect missed patterns, prioritize cascading fixes"
    actions:
      - "Merge overlapping findings (same file, related issues)"
      - "Extract finding types, search for similar patterns codebase-wide"
      - "Identify cascading fixes using quality(action=\"impact\")"
      - "Gap analysis - check finding density and domain coverage balance"
    output_variable: consolidated_findings
  - step: 10
    type: action
    name: report_findings
    instruction: "Report all findings with severity levels"
    output_variable: findings_report

# Guardrails
guardrails:
  enforcement: active
  allowed_tools:
    - civyk-repoix
    - Read
    - Grep
    - Glob
    - Bash  # Only for: git commands, civyk-hatch CLI
  forbidden_actions:
    - "Modify any source files during review stage"
    - "Delete any files"
    - "Make changes without user approval"
  read_only: true

# Post-validation checks
post_validation:
  - check: scope_identified
    description: "Review scope resolved (branch, staged, commits, or files)"
    severity: error
  - check: findings_reported
    description: "All findings reported with severity levels (critical/high/medium/low)"
    severity: error
  - check: understanding_cached
    description: "understand(action=\"store\") called for reviewed files"
    severity: info

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

# Next stage
next:
  stage: 2
  stage_id: "02"
  command: "civyk-hatch review --stage=2"
  auto_continue: true
  is_terminal: false
  condition: "findings.critical > 0 OR findings.high > 0"
version: 1.0.0
---

{{include:strict-execution-mode-lite.md}}

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

# Deep Code Review

Find **potential issues** and **potential enhancements**. Think like a senior engineer doing thorough PR review - cross-reference related files, check consistency, find what could go wrong.

---

## Direct Mode (Args Provided)

If `{user_args}` contains scope info (e.g., "last 5 commits", "staged changes", file paths):

1. Parse scope from args - NO user prompts needed
2. Jump directly to **Step 1: Analyze Changes**

Examples that trigger direct mode:

- `last 3 commits` -> `git diff HEAD~3..HEAD`
- `staged` -> `git diff --cached`
- `src/auth/` -> files in that path
- `feature branch` -> `git diff main...HEAD`

---

## Interactive Mode (No Args)

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

**[STOP: USER_INPUT_REQUIRED]**

What to review? (A) Feature branch, (B) Staged, (C) Last N commits, (D) Files, (E) Uncommitted

---

## Tools: civyk-repoix

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

**USE THESE TOOLS** (after mode detection):

| Task | Tool |
|------|------|
| Branch changes | `context(action="delta", include_symbols=true)` |
| Impact of change | `quality(action="impact", fqn="...", depth=2)` |
| Who calls this | `symbol(action="callers", fqn="...", depth=2)` |
| Find references | `symbol(action="references", fqn="...")` |
| Similar code | `symbol(action="similar", fqn="...")` or `quality(action="duplicates", source_only=true)` |
| File structure | `file(action="symbols", path="...")` |
| Hotspots | `git(action="hotspots", since="30d")` |

---

## Step 1: Get Changed Files with civyk-repoix

**FIRST: Detect mode** (run `status(action="check")` or `civyk-repoix query status --action check`)

**THEN: Get changes with context:**

```text
# MCP mode:
context(action="delta", include_symbols=true, token_budget=3000)

# CLI mode:
civyk-repoix query context --action delta --include-symbols true --token-budget 3000
```

This returns: changed files, modified symbols, affected callers - everything needed to understand the change scope.

**Also get git diff for line-level details:**

```bash
git diff {scope} --stat
git log {scope} --oneline  # Commit messages explain intent
```

---

## Step 2: Analyze Impact with civyk-repoix

For each significant changed function/class:

```text
# MCP mode:
quality(action="impact", fqn="path.to.function", depth=2, include_tests=true)
symbol(action="callers", fqn="path.to.function", depth=2)

# CLI mode:
civyk-repoix query quality --action impact --fqn "path.to.function" --depth 2 --include-tests true
civyk-repoix query symbol --action callers --fqn "path.to.function" --depth 2
```

**Questions to answer:**

- Who calls the changed code? Are callers affected?
- What tests cover this code? Do tests need updating?
- What's the blast radius of this change?

### Store Impact Analysis

```text
# [!] MANDATORY: Store understanding for each significant file analyzed
understand(action="store",
  scope="file",
  target="<file_path>",
  purpose="Impact analysis for <function/class>",
  importance="high",
  key_points=["callers: <list>", "tests: <coverage>", "blast_radius: <scope>"],
  gotchas=["<potential_issues>", "<breaking_changes>"],
  analysis="<file>: <change_summary>. Impact: <caller_count> callers affected. Tests: <status>."
)
```

---

## Step 3: Cross-Reference for Consistency

**CRITICAL: If a pattern was changed, check ALL similar files.**

```text
# Find similar code patterns:
# MCP mode:
quality(action="duplicates", source_only=true, similarity_threshold=0.7)
symbol(action="similar", fqn="path.to.changed.function", similarity_threshold=0.6)

# CLI mode:
civyk-repoix query quality --action duplicates --source-only true --similarity-threshold 0.7
civyk-repoix query symbol --action similar --fqn "path.to.changed.function" --similarity-threshold 0.6
```

**Also use grep for pattern consistency:**

```bash
# Example: if --source-only was fixed in one template
grep -rn "source-only" templates/  # Check ALL templates have same fix
```

**This step often finds MORE issues than the original scope.**

### Store Cross-Reference Findings

```text
# [!] MANDATORY: Store consistency findings
understand(action="store",
  scope="project",
  target="review-consistency",
  purpose="Cross-reference consistency analysis",
  importance="high",
  key_points=["patterns_checked: <count>", "inconsistencies: <list>", "files_affected: <list>"],
  gotchas=["<patterns_needing_fix>", "<files_missed>"],
  analysis="<N> patterns checked. <M> inconsistencies found across <K> files."
)
```

---

## Step 3.5: Pre-Review Context Building

**Before spawning domain agents, gather architectural context to share with all reviewers.**

This step ensures all domain agents start with a shared understanding of:

- System architecture and component boundaries
- Design patterns and conventions
- Known hotspots and problematic areas
- Recent changes and recurring issue patterns
- Repo-specific coding standards

### 3.5.1 Recall Project Understanding

```text
# Check cached architectural understanding from previous sessions
understand(action="recall", scope="project", target="project")

# If found and fresh: Use cached architecture knowledge
# If not found: Will build from scratch in next steps
```

### 3.5.2 Get Component Map

```text
# MCP mode:
architecture(action="components")

# CLI mode:
civyk-repoix query architecture --action components
```

**Extract:**

- Module boundaries (what talks to what)
- Public APIs vs internal implementation
- Cross-cutting concerns (logging, auth, data access)

### 3.5.3 Find Architectural Issues

```text
# MCP mode:
quality(action="circular_deps", level="file")

# CLI mode:
civyk-repoix query quality --action circular_deps --level file
```

**Flag any circular dependencies** - these are architectural violations that reviewers should watch for.

### 3.5.4 Identify Hotspots

```text
# MCP mode:
git(action="hotspots", since="90d", limit=20)

# CLI mode:
civyk-repoix query git --action hotspots --since 90d --limit 20
```

**Hotspots = files changed frequently** - these deserve extra scrutiny as they're risky/complex.

### 3.5.5 Analyze Recent Patterns

```text
# MCP mode:
git(action="changes", limit=50)

# CLI mode:
civyk-repoix query git --action changes --limit 50
```

**Look for recurring fix patterns:**

- Same issue fixed multiple times? Systemic problem.
- Frequent rollbacks? Test coverage gap.
- Repeated refactors? Unclear requirements.

### 3.5.6 Load Repo Guidelines

**Check if repo has coding standards:**

```text
# From context (loaded by context_loader.py):
{repo_guidelines}

# If repo_guidelines exists:
# - Extract key patterns (indent, naming, error handling)
# - Share with domain agents for consistency checks
```

**Common guideline sources:**

- CODING-STANDARDS.md, CONTRIBUTING.md
- .editorconfig (indent style, line length)
- pyproject.toml, package.json (tool configs)
- .prettierrc, tsconfig.json (language-specific)

### 3.5.7 Consolidate Review Context

**Build a shared context object to pass to all domain agents:**

```text
review_context = {
  "components": <component_map>,
  "circular_deps": <list_of_violations>,
  "hotspots": <frequently_changed_files>,
  "recent_patterns": <recurring_issues>,
  "repo_standards": <extracted_from_guidelines>,
  "architecture": <cached_project_understanding>
}
```

**This context will be shared with ALL domain agents in Step 4.**

---

## Step 4: Deep Analysis (Sub-Agent Pattern)

**CRITICAL: Use sub-agents to preserve main orchestrator context.**

The orchestrator (you) spawns sub-agents for each file. This saves context because:

- Main agent only tracks high-level progress
- Sub-agents handle the detailed file analysis
- Results are aggregated back to main agent

### 4.1 Group Files for Analysis

From impact analysis, group files by priority:

```text
Priority 1 (Changed directly):
  - src/auth/login.py
  - src/api/routes.py

Priority 2 (Affected callers):
  - src/services/user.py
  - src/handlers/session.py

Priority 3 (Cross-reference):
  - src/auth/register.py (similar pattern)
```

### 4.2 Spawn Sub-Agents in Parallel

For each file, spawn a sub-agent:

```text
# Orchestrator spawns sub-agents (max {max_agents} concurrent)
PARALLEL FOR file in files_to_analyze:
    spawn_sub_agent(
        prompt="""
        Analyze file for review: {file.path}
        Review focus: {REVIEW_FOCUS}
        Change context: {file.change_summary}
        Related files: {file.related}

        Instructions:
        1. Read the file content
        2. Check for issues (logic, security, consistency, integration, error handling)
        3. Find potential enhancements (simplification, robustness, performance)
        4. Return: issues[], enhancements[], severity_counts
        """,
        tools=[Read, Grep, Glob, Bash]
    )
```

### 4.3 Real-Time Progress (Orchestrator)

**After EACH sub-agent completes:**

```text
OUTPUT: "[{completed}/{total}] [ok] {file_path} - {status}"

# Example outputs:
"[1/8] [ok] src/auth/login.py - 2 issues, 1 enhancement"
"[2/8] [ok] src/api/routes.py - 0 issues"
"[3/8] [err] src/services/user.py - error: file not found"
```

**Update TODO for visual progress:**

```text
TodoWrite: "Analyzing files: {completed}/{total} ({pct}%)"
```

### 4.4 Checkpoint After Each Batch

```text
understand(action="store",
    scope="project",
    target="review-checkpoint",
    purpose="Review workflow checkpoint",
    importance="high",
    key_points=[
        "files_done: {completed}",
        "files_remaining: {remaining}",
        "issues_found: {total_issues}"
    ],
    gotchas=["Resume with: civyk-hatch review --stage=1 --resume"]
)
```

### 4.5 Sub-Agent Analysis Criteria

For each file (changed + related):

### Potential Issues

| Category | Questions |
|----------|-----------|
| **Logic** | Off-by-one? Null handling? Edge cases? |
| **Security** | Injection? Auth bypass? Secrets exposed? |
| **Consistency** | Same pattern everywhere? Naming consistent? |
| **Integration** | Callers updated? Contracts honored? |
| **Error handling** | All errors caught? Meaningful messages? |

### Potential Enhancements

| Category | Questions |
|----------|-----------|
| **Simplification** | Can code be simpler? Dead code? |
| **Robustness** | Missing validation? Better defaults? |
| **Performance** | N+1 queries? Unnecessary loops? |
| **Maintainability** | Magic numbers? Missing types? |

### Cross-File Pattern Detection (CRITICAL)

**After finding an issue in a file, check if it's systemic:**

1. **Extract the pattern:**
   - Identify root cause (e.g., "CancellationTokenSource not disposed")
   - Generalize to searchable pattern (e.g., "CancellationTokenSource usage")

2. **Search entire codebase:**

   ```text
   # MCP mode:
   search(action="code", pattern="CancellationTokenSource", kind="identifier")

   # CLI mode:
   civyk-repoix query search --action code --pattern "CancellationTokenSource" --kind identifier
   ```

3. **Verify each instance:**
   - Read each file containing the pattern
   - Check if same issue exists
   - Use `file(action="symbols")` for quick structure scan

4. **Report systemic findings:**

   ```text
   ### [MEDIUM] CancellationTokenSource not disposed (systemic)

   **Files affected:** 3 of 5 instances
   - src/services/worker.py:42 (ISSUE - not disposed)
   - src/api/background.py:89 (ISSUE - not disposed)
   - src/tasks/scheduler.py:156 (OK - properly disposed)
   - src/handlers/async.py:201 (ISSUE - not disposed)
   - tests/mock_service.py:78 (OK - test code)

   **Pattern:** Found in 1 file during review, searched 5 total instances
   **Fix:** Apply same disposal pattern to all 3 affected files
   ```

**Example patterns to check systematically:**

| Found Issue | Search Pattern | Tool |
|-------------|---------------|------|
| Missing timeout | `HttpClient.*GetAsync` | search(action="code") |
| SQL injection risk | `SELECT.*{` | search(action="code") |
| Resource leak | `CancellationTokenSource\|IDisposable` | search(action="code") |
| Null dereference | Function name | symbol(action="callers") + check usage |
| Missing validation | Parameter name | symbol(action="references") |

**This often finds 2-5x more issues than single-file review.**

---

## Step 5: Cross-Domain Synthesis

**After all domain agents complete, merge findings and detect missed patterns.**

This synthesis step often finds additional issues missed by individual domain reviews.

### 5.1 Merge Overlapping Findings

**Combine findings for the same file/location from multiple domains:**

```text
Example before merge:
- [Security] src/auth/login.py:42 - CancellationTokenSource not disposed (resource leak)
- [Correctness] src/auth/login.py:42 - Thread safety issue with shared CTS

Example after merge:
- [HIGH] src/auth/login.py:42 - CancellationTokenSource resource leak + thread safety
  - Security: Resource leak can DoS service
  - Correctness: Shared instance has race condition
  - Fix: Use using statement + create per-request instance
```

**Benefits:**

- Single actionable fix instead of two separate findings
- Shows full impact (security + correctness)
- Prevents duplicate work in remediation

### 5.2 Detect Missed Patterns

**Extract all finding types and search for similar instances:**

```text
# From all findings, extract patterns:
finding_patterns = [
  "missing timeout on HTTP call",
  "CancellationTokenSource not disposed",
  "magic number in calculation",
  "missing null check on parameter"
]

# For EACH pattern, search codebase-wide:
FOR pattern IN finding_patterns:
    # Find all potential instances
    search(action="code", pattern=<pattern_keywords>)

    # Check each instance for same issue
    # Report if found

# Example output:
"Found 3 'missing timeout' issues in review, searched entire codebase:
 - Found 10 total HTTP calls
 - 7 missing timeout (4 new, 3 already flagged)
 - Adding 4 new findings"
```

**Tools to use:**

```text
# MCP mode:
search(action="code", pattern="HttpClient", kind="identifier")
quality(action="duplicates", source_only=true, similarity_threshold=0.7)

# CLI mode:
civyk-repoix query search --action code --pattern "HttpClient" --kind identifier
civyk-repoix query quality --action duplicates --source-only true --similarity-threshold 0.7
```

### 5.3 Prioritize Cascading Fixes

**Identify fixes that will break tests or require coordinated changes:**

```text
# For each HIGH/CRITICAL finding with significant impact:
FOR finding IN high_severity_findings:
    # Get impact analysis
    quality(action="impact", fqn=<changed_symbol>, depth=3, include_tests=true)

    # Check test coverage
    tests(action="for_file", path=<file>, include_indirect=true)

    # Flag cascading changes needed
    IF impact.affected_count > 5 OR impact.test_count > 3:
        finding.cascading = true
        finding.blast_radius = impact.affected_count
        finding.mitigation_plan = <list_of_files_to_update>
```

**Example cascading finding:**

```text
### [HIGH] Change signature of authenticate() - CASCADING

**File:** src/auth/service.py:89
**Issue:** Missing timeout parameter
**Impact:** 12 callers + 8 tests will break
**Mitigation plan:**
  1. Add optional timeout param with default
  2. Update these callers in same PR:
     - src/api/login.py:156
     - src/handlers/oauth.py:234
     - src/services/user.py:78
     (+ 9 more)
  3. Update tests to use new signature
**Estimated effort:** 30 min coordinated fix
```

### 5.4 Gap Analysis

**Check review thoroughness:**

```text
# Finding density check (sanity check, not strict rule)
files_reviewed = <count>
total_findings = <count>
density = total_findings / files_reviewed

# Typical density: ~1-2 findings per 150-200 lines of code
# If density << 1, might be missing issues - spot check high-risk files

# Domain balance check
domains = ["security", "correctness", "integration", "consistency"]
FOR domain IN domains:
    findings_for_domain = <count>
    files_for_domain = <count>

    # If one domain has unusually low findings relative to files:
    # - Re-review that domain's files
    # - May indicate domain agent missed patterns

Example red flag:
- Security: 20 findings across 5 files (good coverage)
- Correctness: 2 findings across 8 files (suspiciously low - re-review)
```

### 5.5 Consolidate Output

**Produce final consolidated findings list:**

```text
consolidated_findings = {
  "critical": [<merged_findings>],
  "high": [<merged_findings + cascading_fixes>],
  "medium": [<merged_findings + systemic_issues>],
  "low": [<merged_findings>],
  "enhancements": [<merged_suggestions>],
  "metadata": {
    "total_files_reviewed": <N>,
    "cross_file_patterns_checked": <N>,
    "systemic_issues_found": <N>,
    "cascading_fixes": <N>,
    "finding_density": <N>,
    "gap_analysis": <status>
  }
}
```

**This becomes the input to Step 6 (Report Findings).**

---

## Step 6: Report Findings

### Issues Found

```text
### [CRITICAL/HIGH/MEDIUM/LOW] Brief title

**File:** path/to/file.ext:LINE
**Issue:** What's wrong
**Impact:** What could happen
**Fix:** How to fix it
```

### Enhancements Found

```text
### [ENHANCEMENT] Brief title

**File:** path/to/file.ext:LINE
**Current:** What exists now
**Suggestion:** What would be better
**Rationale:** Why it's better
```

### Cross-Reference Findings

```text
### [CONSISTENCY] Brief title

**Pattern:** What should be consistent
**Files checked:** N files
**Issues:** Which files have inconsistency
**Fix:** Apply same fix to all
```

### Store Review Summary

```text
# [!] MANDATORY: Store complete review findings for Stage 2
understand(action="store",
  scope="project",
  target="code-review",
  purpose="Deep code review findings",
  importance="critical",
  key_points=["critical: <N>", "high: <N>", "enhancements: <N>", "consistency: <N>"],
  gotchas=["<top_issues>", "<blocking_items>"],
  analysis="Review complete. <scope>: <N> files. Issues: <critical>C/<high>H/<medium>M/<low>L. Enhancements: <N>."
)
```

---

## Step 7: Summary

```text
=== REVIEW COMPLETE ===

Scope: {description}
Files reviewed: {N} (direct) + {M} (cross-referenced)

ISSUES:
- Critical: {N}
- High: {N}
- Medium: {N}
- Low: {N}

ENHANCEMENTS: {N}
CONSISTENCY ISSUES: {N}

{If issues found: List top 3 most important to fix}
```

---

## Gate

**PASS** if: Critical=0 AND High=0
**NEEDS_ATTENTION** if: Critical=0 AND High>0
**FAIL** if: Critical>0

If FAIL or NEEDS_ATTENTION -> Stage 2 (remediation)

---

## [AUTO-CONTINUE]

**MANDATORY**: If issues found (FAIL or NEEDS_ATTENTION), **immediately proceed to Stage 2 without asking the user**. Do NOT ask "Would you like me to proceed?" or similar questions - just execute the next stage.

## NEXT

```bash
civyk-hatch review --stage=2 --iterations={iterations} \
  --review-scope={REVIEW_SCOPE} \
  --review-focus={REVIEW_FOCUS} \
  --scope-files="{SCOPE_FILES}"
```
