# review (Unified Skill)

## Core Instructions (SKILL.md)

#### Core Instructions (content/distilled/review/SKILL.md)

# Review Router

Route a review request to the right review method, then read that method's instructions before acting.

## Modes

| Task signal | Mode | Read |
|---|---|---|
| "review this code/PR/change" — general multi-pass review | code-review | `references/code-review/SKILL.md` |
| iterate any artifact (code, plan, spec, docs, research) through 5 editorial stages to convergence | rule-of-5-universal | `references/rule-of-5-universal/SKILL.md` |
| high-stakes change needing parallel agent review waves | parallel-review | `references/parallel-review/SKILL.md` |
| coordinate multiple agents for comprehensive review coverage | multi-agent-review | `references/multi-agent-review.md` |
| adversarial pass hunting logic bugs, failure modes, security, deployment risk | red-team-review | `references/red-team-review.md` |
| review that teaches the human the change and surrounding code | guided-review | `references/guided-review.md` |

## Selection rules

- Default code-review requests → **code-review**. Explicitly iterative/editorial refinement of any artifact → **rule-of-5-universal**.
- "break it", "find vulnerabilities", "what could fail in production" → **red-team-review**.
- More than one reviewer perspective is requested or stakes are high → **parallel-review** (agent waves) or **multi-agent-review** (coordination pattern).
- The user wants to learn, not just fix → **guided-review**.

## Procedure

1. Identify the mode from the table above.
2. Read the referenced file (resolve paths against this skill's directory). Multi-file modes have their own `references/` — follow their cross-references.
3. Apply the mode's output format and convergence rules.

---

#### Reference: references/code-review/references/criteria.md

# Code Review Criteria

Use these criteria to categorize findings and determine when the review process is complete.

## Issue Severity Definitions

| Severity | Criteria | Examples |
| :--- | :--- | :--- |
| **CRITICAL** | Blocks merge. Severe security vulnerability, data loss risk, or fundamental logic failure. | SQL Injection, plaintext passwords, unhandled exceptions in core path. |
| **HIGH** | Should fix before merge. Significant performance issue, major regression risk, or violation of key requirements. | Missing index on hot query, non-singular requirement, missing error states. |
| **MEDIUM** | Consider addressing. Minor technical debt, sub-optimal pattern, or readability issues. | Magic strings, DRY violations, lack of docstrings, missing or stale file-header Purpose (see `file-headers`), magic numbers. |
| **LOW** | Nice to have. Stylistic improvements, minor metadata gaps, or typos in non-critical comments. | Minor formatting, redundant comments, small consistency improvements. |

## Convergence Criteria

**CONVERGED** if:
- No new **CRITICAL** issues were found in the current stage AND
- The number of new issues found is less than 10% compared to the previous stage.

**NEEDS_HUMAN** if:
- After 5 stages, new **CRITICAL** issues are still being discovered.
- The false positive rate exceeds 30%.
- A fundamental disagreement on architectural direction is identified.

## Stage Focus (Original Variant)

### Stage 1: DRAFT
- Is the overall approach sound?
- Architectural alignment?
- Major structural issues?

### Stage 2: CORRECTNESS
- Logic bugs?
- Algorithm errors?
- Off-by-one?

### Stage 3: CLARITY
- Readable naming?
- Remove jargon?
- Intent clear?

### Stage 4: EDGE CASES
- Null/empty checks?
- Boundary conditions?
- External failure modes?

### Stage 5: EXCELLENCE
- Performance optimization?
- Documentation polish?
- File headers: every touched source file's Purpose is present, one-sentence-accurate, and not stale; Rationale reflects the current design (see `file-headers`)?
- Style consistency?

---

#### Reference: references/code-review/references/templates.md

# Code Review Templates

Use these templates to provide a structured, high-signal report for each stage and the final verdict.

## Stage Output Template (Original Variant)

```markdown
### STAGE [N]: [Focus Area]

#### Findings:
[ID] [CRITICAL|HIGH|MEDIUM|LOW] - [File:Line]
**Description:** [What's wrong or sub-optimal]
**Recommendation:** [How to fix with specific code example]

[ID] ...
```

## Stage Output Template (Domain-Focused Variant)

```markdown
### PASS [N]: [Domain Focus]

#### Issues Found:
[ID] [CRITICAL|HIGH|MEDIUM|LOW] - [File:Line]
**Description:** [What's wrong or sub-optimal]
**Attack Vector/Impact:** [Why this matters in this domain]
**Recommendation:** [How to fix with specific code example]

[ID] ...
```

## Convergence Check Template

Use this format after each stage (starting with Stage 2).

```markdown
**Convergence Check After Stage/Pass [N]:**

1. New CRITICAL issues: [count]
2. Total new issues vs previous stage: [count]
3. Estimated false positive rate: [percentage]

**Status:** [CONVERGED | CONTINUE | NEEDS_HUMAN]
```

## Final Report Template

After convergence or completing all 5 stages/passes, provide this summary.

```markdown
# Code Review Final Report

**Work Reviewed:** [Short description/path] | **Convergence:** Stage [N]

## Issue Summary
- **CRITICAL:** [count] - Blocks merge / MUST FIX
- **HIGH:** [count] - Should fix before merge
- **MEDIUM:** [count] - Consider Addressing
- **LOW:** [count] - Nice to have

## Top 3 Findings
1. **[ID] [Description]** - [File:Line]
   *   **Impact:** [Why this blocks implementation or causes failure]
   *   **Fix:** [Specific actionable step]

2. **[ID] ...**

## Recommended Next Actions
1. [Action 1 - specific and actionable]
2. [Action 2 - specific and actionable]
3. [Action 3 - specific and actionable]

## Verdict: [READY_TO_MERGE | NEEDS_FIXES | BLOCKS_MERGE]
**Rationale:** [1-2 sentences explaining the verdict based on issue severity]
```

---

#### Reference: references/code-review/references/variants.md

# Code Review Variants

Apply these specialized passes for specific types of work.

## UI/Frontend Variant

| Pass | Focus Area |
| :--- | :--- |
| **Pass 1: Security** | XSS, CSRF, Secure storage of sensitive data. |
| **Pass 2: Performance** | Re-renders, bundle size, heavy computations on main thread. |
| **Pass 3: Accessibility** | WCAG, ARIA labels, semantic HTML, keyboard nav. |
| **Pass 4: UX & Error States** | Loading states, validation feedback, empty states. |
| **Pass 5: Maintainability** | Hook dependencies, component composition, prop types. |

## Refactoring Variant

| Pass | Focus Area |
| :--- | :--- |
| **Pass 0: Behavioral Preservation** | Do tests still pass? Is functionality identical? |
| **Pass 1: Security & Regression** | Did refactoring introduce new vulnerabilities? |
| **Pass 2: Structure & Cleanliness** | Is the new structure actually better? |
| **Pass 3: Documentation** | Updated comments/types reflecting the change? |
| **Pass 4: Performance Impact** | New bottlenecks in abstracted layers? |

## High-Risk Production Code Variant

| Pass | Focus Area |
| :--- | :--- |
| **Pass 1-5** | Standard domain passes. |
| **Pass 6: FP Check** | Rigorously check for false positives in findings. |
| **Pass 7: Impact Cross-Check** | Do findings/fixes introduce cascading failures? |
| **Pass 8: Reliability & Ops** | Metrics, logging, rollback strategy. |

---

#### Reference: references/code-review/SKILL.md

<!-- skill: code-review, version: 1.3.0, status: verified -->
# Iterative Code Review (Rule of 5)

Perform a multi-pass, iterative code review using Steve Yegge's Rule of 5 to achieve high-quality refinement through breadth-first exploration.

## Role
You are a Senior Staff Engineer. Your goal is to provide a rigorous, objective review of code changes, progressing from high-level architecture to fine-grained excellence. You do not just find bugs; you ensure the code is maintainable, clear, and production-ready.

## Procedure

1.  **Context Identification:**
    *   Identify the code to review. Use `ls`, `git diff`, or specific file paths.
    *   Read the code and its related tests. **DO NOT** review code without looking at its tests.

2.  **Iterative Analysis (Rule of 5):**
    Choose between the **Original (Editorial)** or **Domain-Focused** variant based on the work's nature. Perform up to 5 stages, reporting a **Convergence Check** after each stage (starting with Stage 2).

    *   **Original Variant (Recommended for 80% of reviews):**
        1.  **Stage 1: DRAFT** — Architecture, design patterns, and overall shape.
        2.  **Stage 2: CORRECTNESS** — Logic bugs, algorithm errors, and data structure usage.
        3.  **Stage 3: CLARITY** — Naming, readability, and organization.
        4.  **Stage 4: EDGE CASES** — Null checks, empty states, and boundary conditions.
        5.  **Stage 5: EXCELLENCE** — Performance, documentation, and production polish.

    *   **Domain-Focused Variant (For specialized systems):**
        1.  **Pass 1: Security & Safety** (OWASP, SQLi, XSS).
        2.  **Pass 2: Performance & Scalability** (Complexity, DB queries).
        3.  **Pass 3: Maintainability & Readability** (Clean code, DRY).
        4.  **Pass 4: Correctness & Requirements** (Behavioral match).
        5.  **Pass 5: Operations & Reliability** (Logging, retries, failure modes).

3.  **Convergence Check:**
    *   **CONVERGED** if: No new CRITICAL issues AND new issue rate is <10% vs previous stage. Stop early and report.
    *   Otherwise, **CONTINUE** to the next stage.

4.  **Verification (CRITICAL):**
    *   **DO NOT** guess. Use `grep_search` to verify if a suggested library is already in `package.json` or `requirements.txt`.
    *   Check for existing patterns in the codebase using `grep_search` before suggesting a new pattern.
    *   Verify that any suggested fixes do not conflict with existing global configurations (e.g., ESLint rules, TSConfig).

5.  **Final Synthesis:**
    *   Produce a Final Report with a prioritized list of findings and a clear Verdict on merge readiness.

## Rules
- **Specific Locations:** Always provide file:line references for every finding.
- **Actionable Fixes:** Provide clear code snippets for recommendations.
- **Stop Early:** Don't force 5 stages if the code is simple and converges sooner.
- **No Vague Findings:** If you can't prove it's an issue with a specific example or rule violation, do not report it.

## References
- **Templates:** Use `references/templates.md` for stage output and final reports.
- **Variants:** Refer to `references/variants.md` for detailed pass focus for UI, Backend, or Refactoring work.
- **Criteria:** See `references/criteria.md` for convergence thresholds and severity levels.

---

#### Reference: references/guided-review.md

<!-- Full version: content/prompt-task-guided-review.md -->
You are a senior engineer running a guided review. Your goal is to help the human understand the change, the surrounding codebase, and the reasoning behind it — not just to list defects.

**INPUT**
- Change to review: [DIFF, PR, COMMIT RANGE, OR FILE PATHS]
- Optional review goal: [BUG HUNT | LEARN THE CODEBASE | UNDERSTAND DESIGN TRADE-OFFS | PRE-MERGE SELF-REVIEW]
- Optional repository context: [PATHS OR "none"]

**PROTOCOL**
1. Start with a short-circuit triage: decide whether the implementation is mechanically clean enough for guided review.
2. If you see obvious mechanical issues — failing or missing basic tests, lint/format noise, dead code, missing imports, trivial naming cleanup, or straightforward correctness fixes — stop the guided flow and say so explicitly.
3. In that case, recommend a better next skill/workflow before continuing:
   - `prompt-task-iterative-code-review.md` for a conventional issue list
   - `prompt-task-red-team-review.md` for adversarial bug/failure/security hunting
   - `prompt-task-research-codebase.md` if the human first needs architectural orientation
4. Only continue when the implementation is clean enough that the review can focus on understanding, design reasoning, assumptions, and trade-offs.
5. Start from intent before details: infer and confirm what problem the change is solving.
6. Ask one focused question at a time.
7. For every question, provide:
   - **Tentative answer**
   - **Evidence**
   - **Why this matters**
8. Prefer questions that teach system boundaries, data flow, invariants, failure modes, tests, abstraction choices, and how this area fits the broader codebase.
9. If a question can be answered by inspecting the codebase, inspect the codebase instead of asking.
10. Do not dump a giant issue list up front. Guide the review in this order when possible:
   - intent
   - architecture
   - control/data flow
   - correctness
   - edge cases
   - tests
   - maintainability
   - operational impact
11. When you spot a likely issue, turn it into a teaching question before giving the conclusion.
12. Keep the conversation concrete: cite files, functions, call chains, and behaviors.
13. Continue until the major learning and review branches are resolved or explicitly marked open.

**QUESTION LADDER**
Prefer questions like:
- What behavior is this change trying to alter?
- Where does this logic sit in the architecture, and why here?
- What assumptions must hold true for this code to be correct?
- What would break if this helper or condition behaved differently?
- Which upstream inputs and downstream consumers are affected?
- What test would give us the most confidence here?
- What would a new maintainer misunderstand on first read?
- What surrounding file should the human read next?

**OUTPUT**
If the implementation is not ready for guided review, output:
- **Short-circuit:** why the change should be cleaned up first
- **Mechanical issues to fix first:** concise list
- **Recommended next skill/workflow:** which prompt to use next and why

Otherwise, per turn:
- **Question:** one focused question
- **Tentative answer:** best current answer
- **Evidence:** files/functions/diff details
- **Why this matters:** brief teaching rationale
- **Next place to inspect:** optional file/function

When enough clarity is reached, end with:
- **What this change does**
- **How it fits the codebase**
- **Key assumptions/invariants**
- **Potential risks or review findings**
- **Best next files to read**
- **Open questions**

---

#### Reference: references/multi-agent-review.md

I need a comprehensive multi-agent parallel code review using the Wave/Gate architecture.

CODE TO REVIEW:
[paste code or specify: "Review all files in src/auth/"]

ARCHITECTURE:
Wave 1 (Parallel) → Gate 1 (Sequential) → Wave 2 (Parallel) → Gate 2 (Sequential) → Wave 3 (Sequential)

Execute this workflow:

═══════════════════════════════════════════════════════════════
WAVE 1: PARALLEL INDEPENDENT ANALYSIS
═══════════════════════════════════════════════════════════════

Launch 5 parallel tasks. Each task is independent and can run simultaneously.

TASK 1: Security Review
Role: Security Engineer
Focus:
- OWASP Top 10 vulnerabilities
- Input validation and sanitization
- Authentication and authorization flaws
- SQL injection, XSS, CSRF, SSRF
- Secret management and data exposure
- API security and rate limiting
- Cryptography usage

Output JSON format:
{
  "issues": [
    {
      "id": "SEC-001",
      "severity": "CRITICAL|HIGH|MEDIUM|LOW",
      "category": "authentication|input-validation|data-exposure|cryptography",
      "cwe_id": "CWE-XXX",
      "location": "file.js:line",
      "description": "Detailed description",
      "attack_vector": "How an attacker could exploit this",
      "recommendation": "Specific fix with code example"
    }
  ],
  "security_score": 0-3,
  "summary": "One-line summary"
}

TASK 2: Performance Review
Role: Performance Engineer
Focus:
- Time complexity (O(n²), O(n³) patterns)
- Database queries (N+1, missing indexes, full table scans)
- Memory allocation and leaks
- Unnecessary loops and iterations
- Caching opportunities
- Blocking I/O operations
- Resource pooling

TASK 3: Maintainability Review
Role: Future Developer (6 months out, original author gone)
Focus:
- Code clarity and readability
- Documentation (comments, docstrings, README)
- Pattern consistency across codebase
- Naming conventions (clear, descriptive)
- Technical debt indicators
- DRY violations
- Magic numbers and hard-coded values
- Complex conditionals

TASK 4: Requirements Validation
Role: QA Engineer
Focus:
- Requirements coverage (are all requirements implemented?)
- Edge case handling
- Test coverage gaps
- Behavioral correctness
- Missing functionality
- Acceptance criteria satisfaction

TASK 5: Operations Review
Role: SRE (on-call at 3am when this breaks)
Focus:
- Failure modes and error handling
- Observability (logging, metrics, tracing)
- Timeout and retry logic
- Circuit breakers and graceful degradation
- Resource management (connections, files, memory)
- Deployment/rollback complexity
- Configuration management
- Health checks and readiness probes

═══════════════════════════════════════════════════════════════
GATE 1: CONFLICT RESOLUTION (Wait for all Wave 1 tasks)
═══════════════════════════════════════════════════════════════

After all 5 tasks complete, consolidate findings:

TASK 6: Consolidation
Role: Senior Technical Lead

Tasks:
1. DEDUPLICATE ISSUES
   - Same issue reported by multiple reviewers → merge
   - Similar issues → merge if same root cause
   - Different perspectives on same code → keep separate if addressing different concerns

2. RESOLVE SEVERITY CONFLICTS
   Rules:
   - Security CRITICAL always wins
   - Take highest severity if 2+ reviewers agree it's a problem
   - Downgrade if only 1 reviewer flagged and others cleared

3. CALCULATE CONFIDENCE
   - Found by 1 reviewer: confidence = 0.60
   - Found by 2 reviewers: confidence = 0.80
   - Found by 3+ reviewers: confidence = 0.95
   - Severity disagreement: reduce confidence by 0.15

4. IDENTIFY CROSS-CUTTING CONCERNS
   - Issues affecting multiple domains
   - Systemic patterns (same problem in multiple places)

═══════════════════════════════════════════════════════════════
WAVE 2: PARALLEL CROSS-VALIDATION
═══════════════════════════════════════════════════════════════

Launch 2-3 parallel tasks reviewing the consolidated findings.

TASK 7: Meta-Review
Role: Quality Control Lead

Check:
1. COVERAGE GAPS - What wasn't examined?
2. FALSE POSITIVES - Are flagged issues actually problems?
3. SEVERITY CALIBRATION - Are CRITICAL ratings actually critical?
4. REVIEWER QUALITY - Did reviewers follow their focus areas?
5. SYSTEMIC PATTERNS - Do issues indicate deeper architectural problems?

TASK 8: Integration Analysis
Role: Systems Architect

Check for:
- System-wide impacts of issues
- Cascading failure scenarios
- Service dependency problems
- Data flow issues across boundaries

═══════════════════════════════════════════════════════════════
GATE 2: FINAL SYNTHESIS (Wait for Wave 2)
═══════════════════════════════════════════════════════════════

TASK 9: Final Report

Generate:
1. EXECUTIVE SUMMARY
   - Total issues by severity
   - Blockers (CRITICAL issues that prevent merge/deploy)
   - Key systemic issues

2. PRIORITIZED ACTION LIST
   - Must fix before merge (CRITICAL)
   - Should fix before deploy (HIGH)
   - Can fix later (MEDIUM/LOW)

3. BLOCKING ASSESSMENT
   - BLOCKS MERGE: Has CRITICAL issues
   - BLOCKS DEPLOY: Has HIGH operational risks
   - APPROVED: Ready for production
   - APPROVED_WITH_NOTES: Deploy with monitoring plan

4. CONVERGENCE METRICS
   - Number of issues found: CRITICAL/HIGH/MEDIUM/LOW
   - Confidence level: X% high-confidence issues
   - False positive estimate: X%
   - Coverage assessment: X% of code reviewed thoroughly

═══════════════════════════════════════════════════════════════
WAVE 3: CONVERGENCE CHECK
═══════════════════════════════════════════════════════════════

Determine if another iteration is needed:

CONVERGED if:
- new_critical_count == 0 AND
- new_issue_rate < 0.10 AND
- false_positive_rate < 0.20

ESCALATE_TO_HUMAN if:
- iteration >= 3 OR
- Found conflicting CRITICAL issues OR
- Uncertain about severity

ITERATE if:
- new_critical_count > 0 OR
- new_issue_rate >= 0.10

If ITERATE: Start Wave 1 again focusing only on CRITICAL and HIGH issues.

---

#### Reference: references/parallel-review/references/criteria.md

# Multi-Agent Code Review Criteria

Use these criteria to categorize findings and determine when the review process is complete.

## Issue Severity Definitions

| Severity | Criteria | Example Findings |
| :--- | :--- | :--- |
| **CRITICAL** | Severe security vulnerability, data loss risk, or fundamental logic failure that makes the code unshipable. | SQL Injection, plaintext passwords, unhandled exceptions in core path. |
| **HIGH** | Significant performance issue, major regression risk, or violation of key requirements. | Missing index on hot query, non-singular requirement, missing error states. |
| **MEDIUM** | Minor technical debt, sub-optimal pattern, or readability issues. | Magic strings, DRY violations, lack of docstrings, magic numbers. |
| **LOW** | Nice to have. Stylistic improvements, minor metadata gaps, or typos in non-critical comments. | Minor formatting, redundant comments, small consistency improvements. |

## Convergence Criteria

**CONVERGED** if:
- All CRITICAL and HIGH severity issues have been cross-validated by at least two agents (e.g., Security Reviewer and False Positive Checker).
- Gate 1 and Gate 2 synthesis steps result in a stable list of issues with no major contradictions.
- The Integration Validator confirms that no new cascading failures are likely.

**ITERATE** if:
- Wave 2 identifies more than two HIGH or one CRITICAL severity issue that were missed in Wave 1.
- Specialist agents have directly contradictory findings on a CRITICAL issue.

**NEEDS_HUMAN** if:
- After two full multi-agent cycles, no consensus is reached on a CRITICAL issue.
- The specialist agents identify a foundational architectural conflict.

## Verification Checklist (For Orchestrator)

As the Lead Orchestration Engineer, you MUST:
- [ ] Use `read_file` to confirm that every CRITICAL finding actually exists at the cited file:line.
- [ ] Cross-check the "Requirements Validator" findings against the actual specification file (if provided).
- [ ] Verify that suggested performance optimizations don't violate existing project constraints (e.g., using a library that is explicitly forbidden).

---

#### Reference: references/parallel-review/references/templates.md

# Multi-Agent Code Review Templates

Use these templates to structure the waves and final reporting of the multi-agent code review.

## Wave 1 Output Template

```markdown
### WAVE 1: Parallel Analysis Findings

#### 1. Security Reviewer
- [Severity] [Description] - [File:Line]
- [Severity] ...

#### 2. Performance Reviewer
- [Severity] [Description] - [File:Line]

... [Remaining Reviewers]
```

## Wave 2 & 3 Convergence Check Template

```markdown
### WAVE 3: Convergence Check

**Status:** [CONVERGED | ITERATE | NEEDS_HUMAN]
**Confidence Score:** [0-100%]
**Rationale:** [1-2 sentences explaining why the review is complete or requires more focus]
```

## Final Report Template

```markdown
# Multi-Agent Code Review Final Report

**Code:** [Short description/path] | **Convergence:** Wave [N]

## Synthesized Issue Summary
| Severity | Count | Primary Focus |
| :--- | :--- | :--- |
| **CRITICAL** | [count] | Security / Logic Failures |
| **HIGH** | [count] | Performance / Reliability |
| **MEDIUM** | [count] | Maintainability / Tech Debt |
| **LOW** | [count] | Clarity / Style |

## Top 3 Critical Findings (Verified)
1. **[ID] [Description]** - [File:Line]
   *   **Impact:** [Why this blocks implementation or causes failure]
   *   **Fix:** [Specific actionable step]

2. **[ID] ...**

## Final Actionable List
1. [Verified Action 1 - specific and actionable]
2. [Verified Action 2 - specific and actionable]
3. [Verified Action 3 - specific and actionable]

## Verdict: [READY_TO_MERGE | NEEDS_FIXES | BLOCKS_MERGE]
**Rationale:** [Final summary of system-wide health and prioritized fixes]
```

---

#### Reference: references/parallel-review/SKILL.md

<!-- skill: parallel-review, version: 1.2.0, status: verified -->
# Parallel Review (Multi-Agent Code Review)

Orchestrate a comprehensive, multi-agent code review using an extended parallel review workflow inspired by the Rule of 5 principle to achieve maximum defect detection (85-92%).

## Role
You are a Lead Orchestration Engineer. Your goal is to simulate and synthesize the perspectives of multiple specialist agents to uncover critical vulnerabilities, performance bottlenecks, and reliability risks that a single-pass review would miss.

## Procedure

1.  **Context Building:**
    *   Identify the code to review.
    *   Identify the core requirements or user stories the code aims to satisfy.
    *   Read the code and any existing tests completely.

2.  **Wave 1: Parallel Specialist Analysis:**
    Simulate five independent reviewers, each producing a prioritized list of findings (CRITICAL, HIGH, MEDIUM, LOW):
    *   **Security Reviewer:** OWASP Top 10, input validation, auth, and data leaks.
    *   **Performance Reviewer:** Algorithmic complexity, DB efficiency, and memory.
    *   **Maintainer Reviewer:** Readability, structure, design patterns, and tech debt.
    *   **Requirements Validator:** Correctness, requirement coverage, and edge cases.
    *   **Operations Reviewer (SRE):** Failure modes, logging, metrics, and resilience.

3.  **Gate 1: Synthesis & Conflict Resolution:**
    Consolidate findings into a single deduplicated list. Resolve severity conflicts (Security CRITICALs outrank all; 3+ agents flagging an issue elevates its severity).

4.  **Wave 2: Cross-Validation:**
    Simulate two validation agents:
    *   **False Positive Checker:** Scrutinize the list for misunderstandings or irrelevant findings.
    *   **Integration Validator:** Identify system-wide risks or cascading failures.

5.  **Gate 2: Final Synthesis:**
    Remove false positives, add integration risks, and produce the final prioritized list of actionable issues.

6.  **Verification (CRITICAL):**
    *   **DO NOT** rely on simulated agent findings without checking them against the code. As the orchestrator, you MUST use `read_file` or `grep_search` to verify the validity of any CRITICAL or HIGH severity issues before final reporting.
    *   Verify that suggested fixes (e.g., using a specific library) are actually feasible within the current project's environment.

7.  **Wave 3: Convergence Check:**
    Assess if the review has CONVERGED or if the findings are contradictory/unclear enough to require another iteration or human judgment.

## Rules
- **Specific Locations:** Every finding must include a file:line reference.
- **Actionable Advice:** Every issue must have a specific recommendation for a fix.
- **Verification Mandate:** You are responsible for the truth of the simulated findings. Verify high-severity claims manually.

## References
- **Templates:** Use `references/templates.md` for wave outputs and the final report.
- **Criteria:** See `references/criteria.md` for severity definitions and convergence rules.

---

#### Reference: references/red-team-review.md

<!-- Full version: content/prompt-task-red-team-review.md -->
Act as a Senior Software Engineer running a red team diagnostic. Find every way the system can break, fail silently, corrupt data, or be exploited. Review the provided [INPUT] across four domains. Flag every finding with domain, criterion, file location, severity, concrete production failure scenario, and fix. For non-web codebases (CLI tools, libraries, data pipelines), adapt criteria to the relevant attack surface and build system; report N/A where criteria genuinely do not apply.

## Domain 1: Logic & Correctness

Targets edge cases in internal logic; for external input validation see 2.4.

### 1.1 Boundary Conditions & Edge Cases
- Flag numeric ops not handling: zero, negative, overflow/underflow, NaN, Infinity.
- Flag collection ops not handling: empty, single-element, at-capacity.
- Flag string ops not handling: empty, whitespace-only, Unicode edge cases (ZWJ, RTL, emoji), exceeding length.
- Flag date/time ops not handling: timezone conversion, DST, leap years/seconds, epoch boundaries.

### 1.2 State & Data Integrity
- Flag state machines with unvalidated transitions or unreachable/inescapable states.
- Flag read-modify-write on shared data without lock/transaction/atomic (race conditions).
- Flag partial mutation before possible failure without rollback (inconsistent state).
- Flag caches servable stale after source-of-truth change without invalidation/TTL.

### 1.3 Comparison & Equality
- Flag float equality (`==`/`===`) — require epsilon comparison.
- Flag sort/compare not handling nulls, undefined, mixed types.
- Flag case-sensitive comparison on user identifiers where case-insensitive is intent.
- Flag locale-dependent string ops on multi-locale data.

### 1.4 Resource & Lifecycle
- Flag resources (files, connections, sockets) not guaranteed to close in all paths (including exceptions).
- Flag event listeners/timers registered but never unregistered (memory leaks).
- Flag retry logic without max attempts or backoff (cascade failures).
- Flag main thread/event loop blocking (>50ms UI, >100ms server).

## Domain 2: Failure Modes & Reliability

### 2.1 Error Propagation
- Flag silent error swallowing (empty catch, log-only without re-throw/error return).
- Flag broad exception catches masking unrelated bugs.
- Flag unhandled async rejections (promises, futures).
- Flag functions returning "success" on failure paths — callers proceed with bad data.

### 2.2 Dependency Failures
- Flag external calls (HTTP, DB, API, filesystem) with **no timeout** — causes indefinite hangs.
- Flag external service integrations with **no resilience mechanism** (retry with backoff, circuit breaker, fallback, or timeout) at either the call site or client/middleware level — single dependency cascades to total failure.
- Flag assumptions of always-available network or always-successful disk writes.

### 2.3 Concurrency & Ordering
- Flag operations depending on concurrent task execution order without synchronization.
- Flag event/queue processing without idempotency (at-least-once requires dedup).
- Flag check-then-act without atomicity — Time-of-Check-to-Time-of-Use (TOCTOU).
- Flag shared counters/balances outside atomic operations.

### 2.4 Data Validation at Boundaries

Targets trust boundaries where external data enters the system; for internal logic edge cases see 1.1.

- Flag external input used without type checking and range validation.
- Flag deserialization of external data without malformed-input handling.
- Flag inter-service communication trusting schema without validation.
- Flag DB query results assumed non-null/non-empty without checks.

## Domain 3: Security & Attack Surface

### 3.1 Injection Flaws
- Flag SQL via string concatenation — require parameterized queries.
- Flag OS command execution with user input — require argument arrays/allowlisting.
- Flag unescaped user input in HTML — verify auto-escaping, flag bypasses (`dangerouslySetInnerHTML`, `| safe`, `{!! !!}`, `v-html`).
- Flag `eval`/`Function()` on user-derived data.

### 3.2 Authentication & Authorization
- Flag user enumeration via differing auth error messages ("user not found" vs "wrong password").
- Flag session tokens or JWTs in `localStorage` (XSS-accessible). Verify `httpOnly`/`secure`/`SameSite` cookies.
- Flag endpoints performing sensitive operations without server-side authorization — client-side-only auth is no auth.
- Flag insecure direct object references (IDOR): ID parameter changes granting cross-user access without ownership check.

### 3.3 Data Exposure
- Flag stack traces, schema, paths, versions in client errors.
- Flag sensitive data in logs (passwords, tokens, PII).
- Flag over-fetching exposing admin fields, internal IDs, or other users' data.
- Verify HTTPS. Flag CORS wildcard on auth endpoints.

### 3.4 AI/LLM Integration *(skip if no AI components)*
- Flag user input in system prompts without structural separation (prompt injection).
- Flag unsanitized RAG content in prompts (indirect injection).
- Flag destructive LLM-callable tools without user confirmation.
- Flag LLM output used in HTML/queries/commands without sanitization — treat as untrusted.
- Flag agentic systems without iteration limits, cost caps, human-in-the-loop.

## Domain 4: CI/CD & Deployment Safety

### 4.1 Pipeline Injection & Supply Chain
- Flag actions pinned by **mutable tag** — require **commit SHA**. Flag `${{ }}` interpolation of user-controlled input in `run:` — require `env:`. Flag `pull_request_target` + PR head checkout. Flag `curl | bash` and installs without lockfiles.

### 4.2 Secret & Permission Hygiene
- Flag secrets in outputs/logs. Flag secrets accessible during untrusted input processing. Verify least-privilege `permissions:`. Flag self-hosted runners on public repos.

### 4.3 Deployment Safety
- Flag deploys with no rollback. Flag migrations that DROP columns, rename columns, add NOT NULL without defaults, or change column types (likely not backwards-compatible). Flag deploys without health checks. Flag undocumented staging/prod config differences.

### 4.4 Test & Gating Gaps
- Check for SAST/DAST/SCA/secret scanning as **blocking gates**. Flag gates only on default branch. Flag test suites passable with zero tests. Flag deploys proceeding on skipped/cancelled tests.

## Output Format

Per domain:
```
## Domain N: [Name]
Status: PASS | FAIL | PARTIAL
### Findings
[RED-N.M] [CRITICAL|HIGH|MEDIUM|LOW] — [file:line]
  Finding: [Bug, failure mode, or vulnerability]
  Scenario: [How this manifests in production]
  Fix: [Actionable remediation]
### Passes
- [What was correct]
```

Severity: CRITICAL = data corruption/loss/breach/total failure. HIGH = significant incorrect behavior under common conditions. MEDIUM = edge-case bugs or missing resilience. LOW = minor gaps, low probability.

Conclude with:
```
## Summary
- Domain 1 (Logic): [PASS|FAIL|PARTIAL]
- Domain 2 (Reliability): [PASS|FAIL|PARTIAL]
- Domain 3 (Security): [PASS|FAIL|PARTIAL]
- Domain 4 (CI/CD): [PASS|FAIL|PARTIAL]
Overall: [SOLID | NEEDS_HARDENING | FRAGILE]
Top 3 Critical Findings: [list]
Highest-Risk Area: [domain and why]
```

If no findings in a domain, mark PASS with a brief note on what was correct. Do not fabricate findings.

[INPUT]:
{provide_code_config_or_architecture_here}

---

#### Reference: references/rule-of-5-universal/references/criteria.md

# Rule of 5 Convergence & Escalation Criteria

## Convergence Check
Perform this check after Stage 2, Stage 3, and Stage 4.

```
New CRITICAL issues: [count]
Total new issues: [count]
New issues vs Previous Stage: [percentage change]
Status: [CONVERGED | CONTINUE]
```

## Convergence Rules
- **CONVERGED** if:
    - No new CRITICAL issues AND
    - New issue rate < 10% vs previous stage AND
    - False positive rate < 20%
- **CONTINUE** if:
    - New issues found that need addressing and do not meet the above criteria.

## Escalation Rules
- **ESCALATE_TO_HUMAN** if:
    - After 5 stages, still finding CRITICAL issues OR
    - Uncertain about severity or correctness OR
    - False positive rate > 30%

## Convergence Check Output Format
```
New CRITICAL issues: [count]
Total new issues: [count]
New issues vs Previous Stage: [percentage change]
Estimated false positive rate: [percentage]
Status: [CONVERGED | CONTINUE | NEEDS_ITERATION | ESCALATE_TO_HUMAN]
```

---

#### Reference: references/rule-of-5-universal/references/examples.md

# Rule of 5 Domain-Specific Examples

## Example 1: Code Review

**Input:**
```python
def process_users(users):
    results = []
    for user in users:
        if user.age > 18:
            results.append(user.name.upper())
    return results
```

**Output (abbreviated):**

```
STAGE 1: DRAFT
Shape Quality: GOOD - Simple function, clear structure

STAGE 2: CORRECTNESS
[CORR-001] HIGH - Line 4
Description: No null check on user.name
Evidence: Will crash if user.name is None
Recommendation: Add null check: `if user.name: results.append(user.name.upper())`

STAGE 3: CLARITY
[CLAR-001] MEDIUM - Function name
Description: "process_users" is vague
Recommendation: Rename to "get_adult_user_names_uppercase"

STAGE 4: EDGE CASES
[EDGE-001] HIGH - Line 2
Description: Empty users list not handled efficiently
Recommendation: Add early return: `if not users: return []`

STAGE 5: EXCELLENCE
Production Ready: WITH_NOTES - Fix CORR-001 and EDGE-001 first
```

## Example 2: Plan Review

**Input:** Plan for implementing user authentication

**Output (abbreviated):**

```
STAGE 1: DRAFT
Shape Quality: FAIR - Missing rollback phase and testing phase

STAGE 2: CORRECTNESS
[CORR-001] CRITICAL - Phase 3
Description: Assumes JWT library handles all validation automatically
Evidence: Most libraries require explicit error handling
Recommendation: Add error handling to Phase 3, add test for invalid tokens

STAGE 3: CLARITY
[CLAR-001] HIGH - Phase 2
Description: "Integrate with auth system" is vague
Recommendation: Specify files: "Update api/middleware/auth.ts and api/routes/protected.ts"

STAGE 4: EDGE CASES
[EDGE-001] HIGH - Overall
Description: No plan for token expiration or refresh
Recommendation: Add Phase 4 for token refresh mechanism or mark as out of scope

STAGE 5: EXCELLENCE
Production Ready: NO - Fix CORR-001 and add missing phases
```

---

#### Reference: references/rule-of-5-universal/references/templates.md

# Rule of 5 Output Templates

Use these templates for each stage of the review and the final report.

## Stage 1: DRAFT
```
STAGE 1: DRAFT

Assessment: [1-2 sentences on overall shape]

Major Issues:
[DRAFT-001] [CRITICAL|HIGH|MEDIUM|LOW] - [Location]
Description: [What's wrong structurally]
Recommendation: [How to fix]

[DRAFT-002] ...

Shape Quality: [EXCELLENT|GOOD|FAIR|POOR]
```

## Stage 2: CORRECTNESS
```
STAGE 2: CORRECTNESS

Issues Found:
[CORR-001] [CRITICAL|HIGH|MEDIUM|LOW] - [Location]
Description: [What's incorrect]
Evidence: [Why this is wrong]
Recommendation: [How to fix with specifics]

[CORR-002] ...

Correctness Quality: [EXCELLENT|GOOD|FAIR|POOR]
```

## Stage 3: CLARITY
```
STAGE 3: CLARITY

Issues Found:
[CLAR-001] [HIGH|MEDIUM|LOW] - [Location]
Description: [What's unclear]
Impact: [Why this matters]
Recommendation: [How to improve clarity]

[CLAR-002] ...

Clarity Quality: [EXCELLENT|GOOD|FAIR|POOR]
```

## Stage 4: EDGE CASES
```
STAGE 4: EDGE CASES

Issues Found:
[EDGE-001] [CRITICAL|HIGH|MEDIUM|LOW] - [Location]
Description: [What edge case is unhandled]
Scenario: [When this could happen]
Impact: [What goes wrong]
Recommendation: [How to handle it]

[EDGE-002] ...

Edge Case Coverage: [EXCELLENT|GOOD|FAIR|POOR]
```

## Stage 5: EXCELLENCE
```
STAGE 5: EXCELLENCE

Final Polish Issues:
[EXCL-001] [HIGH|MEDIUM|LOW] - [Location]
Description: [What could be better]
Recommendation: [How to achieve excellence]

[EXCL-002] ...

Excellence Assessment:
- Structure: [EXCELLENT|GOOD|FAIR|POOR]
- Correctness: [EXCELLENT|GOOD|FAIR|POOR]
- Clarity: [EXCELLENT|GOOD|FAIR|POOR]
- Edge Cases: [EXCELLENT|GOOD|FAIR|POOR]
- Overall: [EXCELLENT|GOOD|FAIR|POOR]

Production Ready: [YES|NO|WITH_NOTES]
```

## Final Report
```
# Rule of 5 Review - Final Report

**Work Reviewed:** [type] - [path/identifier]
**Convergence:** Stage [N]

## Summary

Total Issues by Severity:
- CRITICAL: [count] - Must fix before proceeding
- HIGH: [count] - Should fix before proceeding
- MEDIUM: [count] - Consider addressing
- LOW: [count] - Nice to have

## Top 3 Critical Findings

1. [ID] [Description] - [Location]
   Impact: [Why this matters]
   Fix: [What to do]

2. [ID] [Description] - [Location]
   Impact: [Why this matters]
   Fix: [What to do]

3. [ID] [Description] - [Location]
   Impact: [Why this matters]
   Fix: [What to do]

## Stage-by-Stage Quality

- Stage 1 (Draft): [Quality assessment]
- Stage 2 (Correctness): [Quality assessment]
- Stage 3 (Clarity): [Quality assessment]
- Stage 4 (Edge Cases): [Quality assessment]
- Stage 5 (Excellence): [Quality assessment]

## Recommended Actions

1. [Action 1 - specific and actionable]
2. [Action 2 - specific and actionable]
3. [Action 3 - specific and actionable]

## Verdict

[READY | NEEDS_REVISION | NEEDS_REWORK | NOT_READY]

**Rationale:** [1-2 sentences explaining the verdict]
```

---

#### Reference: references/rule-of-5-universal/SKILL.md

# Universal Rule of 5 Review

Review any intellectual artifact (code, plans, research, issues, specs, documentation) using Steve Yegge's 5-stage iterative editorial refinement process until convergence.

## Core Philosophy
"Breadth-first exploration, then editorial passes." Don't aim for perfection in early stages. Each stage builds on insights from previous stages.

## Procedure
1.  **Stage 1: DRAFT** - Evaluate overall shape and sound approach. Focus on architecture, organization, and scope.
2.  **Stage 2: CORRECTNESS** - Identify errors, bugs, or logical flaws. Check for convergence.
3.  **Stage 3: CLARITY** - Ensure comprehensibility for the intended audience. Check for convergence.
4.  **Stage 4: EDGE CASES** - Handle boundary conditions and unusual scenarios. Check for convergence.
5.  **Stage 5: EXCELLENCE** - Final polish for production quality and pride.
6.  **Final Report** - Synthesize findings and provide a final verdict.

## Rules
- **Progressive Build:** Each stage must build on previous findings.
- **Specificity:** Reference exact locations (file:line, section, paragraph).
- **Actionability:** Suggest specific solutions, don't just identify problems.
- **Validation:** Confirm issues exist; do not flag "potential" issues without evidence.
- **Early Stop:** Stop if convergence criteria are met before Stage 5.

## References
- **Templates:** Use `references/templates.md` for the exact output format of each stage and the final report.
- **Criteria:** Refer to `references/criteria.md` for convergence and escalation rules.
- **Examples:** (Optional) See `references/examples.md` for domain-specific review examples.
