<workflow>
  <critical>The workflow execution engine is governed by: {project-root}/_bmad/core/tasks/workflow.xml</critical>
  <critical>You MUST have already loaded and processed: {installed_path}/workflow.yaml</critical>
  <critical>Communicate all responses in {communication_language} and language MUST be tailored to {user_skill_level}</critical>
  <critical>Generate all documents in {document_output_language}</critical>

  <critical>🔥 YOU ARE AN ADVERSARIAL CODE REVIEWER - Find what's wrong or missing! 🔥</critical>
  <critical>Your purpose: Validate story file claims against actual implementation</critical>
  <critical>Challenge everything: Are tasks marked [x] actually done? Are ACs really implemented?</critical>
  <critical>Find 3-10 specific issues in every review minimum - no lazy "looks good" reviews - YOU are so much better than the dev agent
    that wrote this slop</critical>
  <critical>Read EVERY file in the File List - verify implementation against story requirements</critical>
  <critical>Tasks marked complete but not done = CRITICAL finding</critical>
  <critical>Acceptance Criteria not implemented = HIGH severity finding</critical>
  <critical>Do not review files that are not part of the application's source code. Always exclude the _bmad/ and _bmad-output/ folders from the review. Always exclude IDE and CLI configuration folders like .cursor/ and .windsurf/ and .claude/</critical>

  <critical>🛑 SELF-REVIEW BIAS WARNING: If YOU are the same agent that implemented this story, your confirmation bias is EXTREME.
    You will instinctively believe your code is correct. You will gloss over edge cases you "already thought about."
    You will find fewer issues because you remember your intent, not the actual code.
    FIGHT THIS. Pretend you are a hostile external reviewer who WANTS to find problems.
    A story with 55+ tests, DB migrations, and multiple AC should NEVER have 0 review issues.</critical>

  <critical>🛑 MINIMUM REVIEW ROUNDS: You MUST complete at least 2 full review rounds before declaring clean.
    Round 1 finds-and-fixes. Round 2 re-reviews everything from scratch. Only Round 2+ can declare "0 issues."
    A single-round "looks good" is NEVER acceptable — it means you didn't look hard enough.</critical>


  <step n="1" goal="Load story and discover changes">
    <action>Use provided {{story_path}} or ask user which story file to review</action>
    <action>Read COMPLETE story file</action>
    <action>Set {{story_key}} = extracted key from filename (e.g., "1-2-user-authentication.md" → "1-2-user-authentication") or story
      metadata</action>
    <action>Parse sections: Story, Acceptance Criteria, Tasks/Subtasks, Dev Agent Record → File List, Change Log</action>

    <!-- Discover actual changes via git -->
    <action>Check if git repository detected in current directory</action>
    <check if="git repository exists">
      <action>Run `git status --porcelain` to find uncommitted changes</action>
      <action>Run `git diff --name-only` to see modified files</action>
      <action>Run `git diff --cached --name-only` to see staged files</action>
      <action>Compile list of actually changed files from git output</action>
    </check>

    <!-- Cross-reference story File List vs git reality -->
    <action>Compare story's Dev Agent Record → File List with actual git changes</action>
    <action>Note discrepancies:
      - Files in git but not in story File List
      - Files in story File List but no git changes
      - Missing documentation of what was actually changed
    </action>

    <invoke-protocol name="discover_inputs" />
    <action>Load {project_context} for coding standards (if exists)</action>
  </step>

  <step n="2" goal="Build review attack plan">
    <action>Extract ALL Acceptance Criteria from story</action>
    <action>Extract ALL Tasks/Subtasks with completion status ([x] vs [ ])</action>
    <action>From Dev Agent Record → File List, compile list of claimed changes</action>

    <action>Create review plan:
      1. **AC Validation**: Verify each AC is actually implemented
      2. **Task Audit**: Verify each [x] task is really done
      3. **Code Quality**: Security, performance, maintainability
      4. **Test Quality**: Real tests vs placeholder bullshit
    </action>

    <!-- Initialize review loop counter -->
    <action>Set {{review_round}} = 0</action>
    <action>Set {{cumulative_fixed}} = 0</action>
  </step>

  <step n="3" goal="Execute adversarial review">
    <critical>VALIDATE EVERY CLAIM - Check git reality vs story claims</critical>

    <!-- Review loop tracking -->
    <action>Set {{review_round}} = {{review_round}} + 1</action>
    <check if="{{review_round}} gt 1">
      <critical>⚠️ THIS IS NOT A VERIFICATION PASS — THIS IS A FULL ADVERSARIAL RE-REVIEW FROM SCRATCH.
        You MUST NOT assume your fixes are correct. You have confirmation bias — fight it.
        Treat this round as if a DIFFERENT reviewer is seeing the code for the first time.
        Execute ALL checks below (AC Validation, Task Audit, Code Quality) with the SAME rigor as Round 1.
        "Re-read modified files" means read EVERY file in the comprehensive review list, not just the ones you touched.
        If you are the same agent that implemented this code, you are ESPECIALLY biased about your own fixes.
        Your instinct will be to skim files you "just fixed" — DO NOT do this. Read every line again.</critical>
      <output>🔄 **Re-review Round {{review_round}}** — FULL adversarial re-review (not just fix verification)...</output>
      <action>Re-read ALL files in the comprehensive review list (not just files modified in the previous round)</action>
      <action>Re-run git status/diff to capture latest changes</action>
      <action>Re-extract ALL Acceptance Criteria and Tasks from the story file (do NOT rely on memory from previous rounds)</action>
    </check>

    <!-- Git vs Story Discrepancies -->
    <action>Review git vs story File List discrepancies:
      1. **Files changed but not in story File List** → MEDIUM finding (incomplete documentation)
      2. **Story lists files but no git changes** → HIGH finding (false claims)
      3. **Uncommitted changes not documented** → MEDIUM finding (transparency issue)
    </action>

    <!-- Use combined file list: story File List + git discovered files -->
    <action>Create comprehensive review file list from story File List and git changes</action>

    <!-- AC Validation -->
    <action>For EACH Acceptance Criterion:
      1. Read the AC requirement
      2. Search implementation files for evidence
      3. Determine: IMPLEMENTED, PARTIAL, or MISSING
      4. If MISSING/PARTIAL → HIGH SEVERITY finding
    </action>

    <!-- Task Completion Audit -->
    <action>For EACH task marked [x]:
      1. Read the task description
      2. Search files for evidence it was actually done
      3. **CRITICAL**: If marked [x] but NOT DONE → CRITICAL finding
      4. Record specific proof (file:line)
    </action>

    <!-- Code Quality Deep Dive -->
    <action>For EACH file in comprehensive review list:
      1. **Security**: Look for injection risks, missing validation, auth issues
      2. **Performance**: N+1 queries, inefficient loops, missing caching
      3. **Error Handling**: Missing try/catch, poor error messages
      4. **Code Quality**: Complex functions, magic numbers, poor naming
      5. **Test Quality**: Are tests real assertions or placeholders?
    </action>

    <!-- Story Spec Accuracy Verification -->
    <critical>🔍 SPEC REALITY CHECK — Verify that story technical specs match actual implementation targets</critical>
    <action>For EACH external tool, CLI command, or API referenced in Dev Notes:
      1. Verify CLI commands exist: run `--help` or check that the command is valid
      2. Verify API signatures match actual package type definitions (check node_modules or docs)
      3. Verify file paths referenced in story actually exist in the project
      4. Check that [unverified] items were verified during implementation (look for verification notes in Dev Agent Record)
      5. If story spec does NOT match reality → HIGH SEVERITY finding: "Story spec inaccuracy: [detail]"
    </action>

    <check if="total_issues_found lt 3">
      <critical>🛑 NOT LOOKING HARD ENOUGH - You MUST find at least 3 issues! 🛑
        Finding fewer than 3 issues means you are being lazy or have confirmation bias.
        NO codebase is perfect. Every implementation has edge cases, missing validation, or quality issues.
        You CANNOT proceed to Step 4 until you have found at least 3 specific, actionable issues.
        DO NOT fabricate issues — but DO look harder at:
      </critical>
      <action>Re-examine code for:
        - Edge cases and null handling (what happens with empty input? null? undefined?)
        - Architecture violations (does it follow the documented patterns?)
        - Missing error handling (what if the DB call fails? API timeout? invalid data?)
        - Security issues (SQL injection? XSS? missing auth checks? input validation?)
        - Performance (N+1 queries? unnecessary re-renders? missing memoization?)
        - Test quality (are assertions specific? do tests cover error paths? any mocked-away logic?)
        - Integration issues (does it work with the rest of the system? race conditions?)
        - Dependency problems (version conflicts? unused imports? circular dependencies?)
      </action>
      <action>Find at least 3 more specific, actionable issues — go back and re-read the files if necessary</action>
    </check>

    <!-- Mandatory review evidence output — required EVERY round before proceeding to Step 4 -->
    <critical>You MUST output the following structured evidence checklist BEFORE proceeding to Step 4.
      If you cannot fill in specific evidence for each section, you have NOT completed the review.
      Do NOT proceed to Step 4 until every section has concrete evidence.</critical>
    <output>### 📋 Review Evidence (Round {{review_round}})

      **Files Actually Read This Round:** [list every file path you read]

      **AC Verification:**
      {{for each AC}}
      - AC#{{n}}: {{IMPLEMENTED|PARTIAL|MISSING}} — Evidence: {{file:line or specific code reference}}
      {{/for}}

      **Task Audit:**
      {{for each [x] task}}
      - Task {{n}}: {{VERIFIED|NOT DONE}} — Evidence: {{file:line or specific code reference}}
      {{/for}}

      **Security/Performance Spot-Check:**
      - Checked: {{list specific checks performed with file references}}

      **Issues Found This Round:** {{count}} ({{high}} HIGH, {{medium}} MEDIUM, {{low}} LOW)
    </output>
  </step>

  <step n="4" goal="Record findings, auto-fix, and loop until clean">
    <critical>This step automatically records findings → fixes code → loops back to Step 3 for re-review until no HIGH/MEDIUM issues remain</critical>

    <!-- 4a. Categorize and present findings -->
    <action>Categorize findings: HIGH (must fix), MEDIUM (should fix), LOW (nice to fix)</action>
    <action>Set {{fixed_count}} = 0</action>
    <action>Set {{action_count}} = 0</action>

    <output>**🔥 CODE REVIEW FINDINGS (Round {{review_round}}), {user_name}!**

      **Story:** {{story_file}}
      **Git vs Story Discrepancies:** {{git_discrepancy_count}} found
      **Issues Found:** {{high_count}} High, {{medium_count}} Medium, {{low_count}} Low

      ## 🔴 CRITICAL/HIGH ISSUES
      - Tasks marked [x] but not actually implemented
      - Acceptance Criteria not implemented
      - Story claims files changed but no git evidence
      - Security vulnerabilities

      ## 🟡 MEDIUM ISSUES
      - Files changed but not documented in story File List
      - Uncommitted changes not tracked
      - Performance problems
      - Poor test coverage/quality
      - Code maintainability issues

      ## 🟢 LOW ISSUES
      - Code style improvements
      - Documentation gaps
      - Git commit message quality
    </output>

    <!-- 4b. Record findings in story file (document BEFORE fixing) -->
    <action>Add or update "Review Follow-ups (AI) — Round {{review_round}}" subsection in Tasks/Subtasks</action>
    <action>For each HIGH and MEDIUM issue: `- [ ] [AI-Review][Round {{review_round}}][{{Severity}}] {{Description}} [{{file}}:{{line}}]`</action>
    <action>For each LOW issue: `- [ ] [AI-Review][Round {{review_round}}][LOW] {{Description}} [{{file}}:{{line}}]`</action>
    <action>Set {{action_count}} = number of action items recorded</action>

    <!-- 4c. Check if there are any issues to fix -->
    <check if="{{high_count}} + {{medium_count}} + {{low_count}} == 0">
      <!-- Enforce minimum 2 rounds before allowing clean exit -->
      <check if="{{review_round}} lt 2">
        <critical>🛑 Round 1 found 0 issues — this is SUSPICIOUS. No codebase is perfect on first pass.
          You MUST loop back and re-review with deeper scrutiny. Look at EVERY file again.
          Check edge cases, error paths, security, performance, test quality.
          A story with tests, AC validation, and multiple files ALWAYS has improvement opportunities.</critical>
        <output>⚠️ **Round {{review_round}} found 0 issues — forcing deeper re-review...**</output>
        <goto step="3" scope="FULL" depth="adversarial">Mandatory deeper re-review — 0 issues in early round is not credible</goto>
      </check>
      <check if="{{review_round}} gte 2">
        <!-- Round 2+ with 0 issues — legitimate clean exit -->
        <output>✅ **No issues found in Round {{review_round}}! Code is clean.**</output>
        <!-- Proceed to Step 5 (completion) -->
      </check>
    </check>

    <check if="{{high_count}} + {{medium_count}} + {{low_count}} gt 0">
      <!-- 4d. Auto-fix all issues (HIGH, MEDIUM, and LOW) -->
      <output>🔧 **Auto-fixing {{high_count}} HIGH + {{medium_count}} MEDIUM + {{low_count}} LOW issues...**</output>
      <action>Fix all HIGH, MEDIUM, and LOW issues in the code</action>
      <action>Add/update tests as needed</action>
      <action>Update File List in story if files changed</action>
      <action>Update story Dev Agent Record with fixes applied</action>
      <action>Set {{fixed_count}} = number of all issues fixed</action>
      <action>Mark fixed items with [x] in "Review Follow-ups (AI)" section</action>
      <action>Set {{cumulative_fixed}} = {{cumulative_fixed}} + {{fixed_count}}</action>

      <output>🔧 **Round {{review_round}} fixes applied:** {{fixed_count}} issues fixed. Looping back for re-review...</output>

      <!-- Loop back to Step 3 for FULL re-review — not just verification of fixes -->
      <goto step="3" scope="FULL" depth="adversarial">Full adversarial re-review — re-execute ALL checks from scratch, not just verify fixes</goto>
    </check>
  </step>

  <step n="5" goal="Update story status and sync sprint tracking">
    <!-- Determine new status based on review outcome -->
    <check if="all HIGH and MEDIUM issues fixed AND all ACs implemented">
      <action>Set {{new_status}} = "done"</action>
      <action>Update story Status field to "done"</action>
    </check>
    <check if="HIGH or MEDIUM issues remain OR ACs not fully implemented">
      <action>Set {{new_status}} = "in-progress"</action>
      <action>Update story Status field to "in-progress"</action>
    </check>
    <action>Save story file</action>

    <!-- Determine sprint tracking status -->
    <check if="{sprint_status} file exists">
      <action>Set {{current_sprint_status}} = "enabled"</action>
    </check>
    <check if="{sprint_status} file does NOT exist">
      <action>Set {{current_sprint_status}} = "no-sprint-tracking"</action>
    </check>

    <!-- Sync sprint-status.yaml when story status changes (only if sprint tracking enabled) -->
    <check if="{{current_sprint_status}} != 'no-sprint-tracking'">
      <action>Load the FULL file: {sprint_status}</action>
      <action>Find development_status key matching {{story_key}}</action>

      <check if="{{new_status}} == 'done'">
        <action>Update development_status[{{story_key}}] = "done"</action>
        <action>Save file, preserving ALL comments and structure</action>
        <output>✅ Sprint status synced: {{story_key}} → done</output>
      </check>

      <check if="{{new_status}} == 'in-progress'">
        <action>Update development_status[{{story_key}}] = "in-progress"</action>
        <action>Save file, preserving ALL comments and structure</action>
        <output>🔄 Sprint status synced: {{story_key}} → in-progress</output>
      </check>

      <check if="story key not found in sprint status">
        <output>⚠️ Story file updated, but sprint-status sync failed: {{story_key}} not found in sprint-status.yaml</output>
      </check>
    </check>

    <check if="{{current_sprint_status}} == 'no-sprint-tracking'">
      <output>ℹ️ Story status updated (no sprint tracking configured)</output>
    </check>

    <output>**✅ Review Complete!**

      **Story Status:** {{new_status}}
      **Review Rounds:** {{review_round}}
      **Total Issues Fixed:** {{cumulative_fixed}}

      {{#if new_status == "done"}}Code review complete — all issues resolved!{{else}}Some issues could not be resolved. Check story file for details.{{/if}}
    </output>
  </step>

</workflow>