---
description: Execute QA checks using repo's Taskfile and docs/QA.md
argument-hint: [scope] [--strict] [--fix] [--diff] [--compare] [--fast]
allowed-tools: Bash, Read, Edit, Write
---

# QA Execution for: $ARGUMENTS

**IMPORTANT - Report Location Pattern**: This command generates a QA report. See [REPORT-LOCATIONS.md](./REPORT-LOCATIONS.md) for the required pattern:

- **Save to temporary directory**: `${TMPDIR:-${TEMP:-/tmp}}/qa-report-$(date +%Y%m%d-%H%M%S).md`
- **Auto-open in VSCode**: `code "$REPORT_FILE"` after generation
- **Never save to project root**: No `.qa.report.local.md` files

## Phase 0: Parse Arguments

Extract from `$ARGUMENTS`:

- **Scope**: Optional with smart defaults
  - `tests` or `test` → Only run test suite (fast feedback)
  - `quick` → Re-run only recently failed tests (fastest)
  - `.` or empty → All checks per docs/QA.md
  - File pattern or directory → Custom scope
- **--strict**: Fail fast on first error
- **--fix**: Intelligent test fixing (context-aware for test failures)
- **--diff**: Only QA git-changed files
- **--compare**: Diff against previous `.qa.report.local.md`
- **--fast**: Skip slow checks (security scan, coverage analysis)

**Smart scope resolution:**

```bash
# If scope is "tests" or "test"
if [[ "$SCOPE" == "test" || "$SCOPE" == "tests" ]]; then
  MODE="tests-only"
  echo "🧪 Test-only mode enabled"
fi

# If scope is "quick"
if [[ "$SCOPE" == "quick" ]]; then
  MODE="quick-tests"
  echo "⚡ Quick mode: Re-running failed tests only"
fi
```

## Phase 0.5: Detect Recent Test Context

**Purpose**: Enable context-aware workflow when user likely called `/qa` after seeing test failures.

Check for recent test failures to prioritize test execution:

```bash
# Check for recent test results file
if [ -f .bun-test-results.txt ]; then
  # Get file age in minutes
  FILE_AGE=$(( ($(date +%s) - $(stat -f %m .bun-test-results.txt 2>/dev/null || stat -c %Y .bun-test-results.txt 2>/dev/null)) / 60 ))

  # If file is less than 10 minutes old
  if [ $FILE_AGE -lt 10 ]; then
    # Parse for failures
    FAILED_TESTS=$(grep -E "fail|error" .bun-test-results.txt 2>/dev/null | grep -v "0 fail" || echo "")

    if [ -n "$FAILED_TESTS" ]; then
      echo "⚠️  Detected recent test failures (${FILE_AGE}m ago)"

      # If no explicit scope provided, suggest test-focused workflow
      if [ -z "$SCOPE" ] || [ "$SCOPE" == "." ]; then
        echo ""
        echo "💡 Suggestion: Run '/qa tests' to focus on tests (faster)"
        echo "   Or run '/qa quick' to re-run only failed tests"
        echo "   Or continue with full QA checks"
        echo ""

        # Set priority mode flag
        PRIORITY_MODE="tests"
      fi

      # Extract failed test names for quick mode
      if [ "$MODE" == "quick-tests" ]; then
        echo "📋 Extracting failed test names..."
        # Parse test output for specific failures
        FAILED_TEST_NAMES=$(grep -B2 "^error:" .bun-test-results.txt | grep "^(" | sed 's/^(fail) //' | sed 's/ \[.*$//' || echo "")
      fi
    fi
  fi
fi
```

**When to prioritize tests:**

- `.bun-test-results.txt` exists and contains failures
- File modified within last 10 minutes (indicates recent failure)
- User likely called `/qa` in response to seeing failures

**Actions based on detection:**

- Show helpful suggestions for test-focused workflows
- Set `PRIORITY_MODE=tests` to run tests first
- Extract failed test names for quick mode

## Phase 1: Discover Repo Interface

### 1.1 Check for Taskfile

```bash
# Check if Taskfile exists
test -f Taskfile.yml || test -f Taskfile.yaml
```

**If Taskfile NOT found:**

- Note in report: "⚠️ No Taskfile found. Recommend adding Taskfile for consistent automation."
- Fall back to manual tool detection (secondary path)
- Continue but flag this as non-standard

**If Taskfile found:**

- This is the primary path
- Run `task` (no arguments) to see available commands and default
- Capture output - this shows the repo's available commands

### 1.2 Read QA Standards

```bash
# Read docs/QA.md
cat docs/QA.md
```

**If docs/QA.md NOT found:**

- FAIL: "❌ Error: docs/QA.md not found. Cannot proceed without QA standards."
- Exit immediately

**If docs/QA.md found:**

- Parse for task commands to run (e.g., `task typescript:verify`, `task kotlin:audit`)
- Parse for quality thresholds (coverage %, allowed CVE severities, etc.)
- Parse for check sequence (build → lint → test → security, etc.)
- Extract any repo-specific instructions

### 1.3 Scope Determination

If `--diff`:

```bash
git diff --name-only origin/main...HEAD 2>/dev/null || git diff --name-only origin/master...HEAD
```

- Use changed files as scope
- If not in git repo: warn and use provided scope

If scope provided: Use that
Otherwise: Use "." (entire repo)

### 1.4 Load Previous Report (if --compare)

```bash
test -f .qa.report.local.md && cat .qa.report.local.md
```

## Phase 2: Execute QA Checks

**Strategy**: Adapt execution based on mode and priority.

### 2.0 Mode-Specific Execution Strategy

```bash
# Test-only mode: Skip other checks
if [ "$MODE" == "tests-only" ]; then
  echo "🧪 Running tests only (skipping lint, security, type check)"
  bun test 2>&1 | tee .bun-test-results.txt
  # Skip to Phase 3 for reporting
fi

# Quick mode: Re-run failed tests only
if [ "$MODE" == "quick-tests" ]; then
  echo "⚡ Re-running failed tests only"
  if [ -n "$FAILED_TEST_NAMES" ]; then
    # Run only specific failed tests
    # Note: Actual implementation depends on test runner capabilities
    bun test --rerun-failures 2>&1 | tee .bun-test-results.txt
  else
    echo "⚠️  Could not extract failed test names, running all tests"
    bun test 2>&1 | tee .bun-test-results.txt
  fi
  # Skip to Phase 3 for reporting
fi

# Priority mode: Run tests first, then other checks
if [ "$PRIORITY_MODE" == "tests" ] && [ "$MODE" != "tests-only" ]; then
  echo "⏭️  Prioritizing tests (running first)"
  # Run tests before other QA checks
  # (Implementation below in 2.1)
fi
```

**For each check defined in docs/QA.md:**

### 2.1 Execute Task Command

```bash
# Example - actual commands come from docs/QA.md
task <command-from-docs> [--fix if flag set]
```

**Execution order:**

- If `PRIORITY_MODE=tests`: Run test task first, then others
- If `--fast`: Skip security and coverage tasks
- Otherwise: Follow sequence from docs/QA.md

**Capture data:**

- stdout, stderr, exit code
- Execution time
- If exit code != 0 AND `--strict`: Stop here, skip remaining checks
- Otherwise: Continue to collect all results

### 2.2 Parse Task Output

Attempt to extract structured data:

- **Coverage**: Look for percentage patterns (e.g., "Coverage: 85.3%")
- **Test results**: Look for pass/fail counts
- **Linting**: Look for error/warning counts
- **Security**: Look for CVE IDs, severity levels
- **Build status**: Exit code + error messages

Store raw output for report inclusion.

### 2.3 Validate Against Thresholds

Compare results against thresholds from docs/QA.md:

- **Coverage**: Actual vs. minimum required
- **Security**: CVE severity vs. allowed levels
- **Linting**: Error count vs. zero-tolerance policy

### 2.4 Context-Aware Test Fixing (when --fix)

If `--fix` flag AND test failures detected:

**Read test failure context:**

```bash
if [ -f .bun-test-results.txt ]; then
  # Extract failing test information
  echo "🔍 Analyzing test failures..."

  # Parse test output for:
  # - Test file paths
  # - Test names
  # - Error messages
  # - Stack traces
  # - Expected vs actual values
fi
```

**Categorize failures by type:**

1. **Mock/Spy Issues**: `mockFetch`, `mockExecuteCommand` format problems
2. **Assertion Errors**: `expect().toBe()` mismatches
3. **Type Errors**: TypeScript type mismatches in tests
4. **Async Errors**: Missing `await`, unhandled promises
5. **Import Errors**: Missing test dependencies

**TDD Best Practices for Test Fixes:**

When fixing tests, follow TDD principles to ensure tests validate behavior, not implementation:

- **Test behavior, not implementation** - Tests should verify what code does, not how it does it
- **One assertion per concept** - Each test should verify a single behavior
- **Arrange-Act-Assert pattern** - Structure tests clearly (setup → execute → verify)
- **Mock external dependencies** - Isolate unit under test from system calls, network, filesystem

See: `~/.claude/guides/agents.tdd.md` for TDD principles
See: `~/.claude/guides/agents.tdd.ts.md` for TypeScript-specific testing patterns

**Apply intelligent fixes:**

```typescript
// For mock format errors:
// Update mock structure to match expected format
mockExecuteCommand.mockResolvedValueOnce({
  stdout: 'expected-format',
  stderr: '',
  exitCode: 0,
});

// For assertion errors:
// Review implementation changes
// Update test expectations to match new behavior

// For type errors:
// Fix type definitions in test files
// Add proper type assertions
```

**Re-run affected tests:**

```bash
echo "🔧 Applying fixes and re-running tests..."
bun test 2>&1 | tee .bun-test-results.txt

# Report results
FIXED_COUNT=$(grep "pass" .bun-test-results.txt | wc -l || echo "0")
REMAINING_FAILURES=$(grep "fail" .bun-test-results.txt | grep -v "0 fail" | wc -l || echo "0")

echo ""
echo "📊 Fix Results:"
echo "   ✅ Fixed: $FIXED_COUNT tests"
echo "   ❌ Remaining failures: $REMAINING_FAILURES"
echo ""
```

**Example fix workflow:**

```text
❌ Test failed: installGitHubMcp > should skip validation for 1Password references
   Error: expect(received).toBe(expected)
   Expected: true
   Received: false

🔍 Analysis:
   - Test expects success=true but got success=false
   - Likely cause: Missing mock for resolveSecret function
   - Implementation recently added resolveSecret import

🔧 Applied fix:
   - Added mock for resolveSecret in test setup
   - Updated mock to return { success: true, value: 'ghp_...' }

✅ Test now passing
```

## Phase 3: Generate Report

Create `.qa.report.local.md`:

````markdown
# QA Report

**Generated:** [timestamp ISO]
**Scope:** [scope or "git diff"]
**Mode:** [tests-only | quick-tests | full | custom]
**Taskfile:** ✅ Found | ⚠️ Not Found
**Executed by:** [git config user.name]
**Flags:** [list flags used]

## Summary

- **Total Checks:** [count]
- **Passed:** ✅ [count]
- **Failed:** ❌ [count]
- **Warnings:** ⚠️ [count]

**Overall Status:** ✅ PASS | ❌ FAIL | ⚠️ PASS WITH WARNINGS

---

## Available Tasks

[Output from running `task` with no arguments]

```text

[task output showing available commands]
```
````

---

## Quality Gates

[Dynamic sections based on what docs/QA.md specified]

### [Check Name from docs/QA.md]

- **Status:** ✅ | ❌ | ⚠️
- **Command:** `task [command]`
- **Threshold:** [from docs/QA.md if applicable]
- **Result:** [parsed result]
- **Exit Code:** [code]
- **Execution Time:** [duration]

**Output:**

```text

[captured stdout/stderr, truncated if >50 lines]

```

**Analysis:**

- [Parsed metrics: coverage %, test counts, error counts, etc.]
- [Comparison to threshold if applicable]

[Repeat for each check specified in docs/QA.md]

---

## Comparison with Previous Report

[Only if --compare used]

### Changes Since Last Run

- **[Metric]:** [previous] → [current] ([+/- delta])
  [Repeat for tracked metrics]

### Status Changes

- **Regressed:** [checks that went from pass to fail]
- **Improved:** [checks that went from fail to pass]

---

## Recommendations

**🔴 Critical (Blocking Merge):**
[Issues that fail thresholds or have critical severity]

**🟡 High Priority:**
[Warnings or near-threshold issues]

**🟢 Low Priority:**
[Minor improvements]

---

## Next Steps

[Checklist from docs/QA.md if present, otherwise generic]

- [ ] Address critical failures
- [ ] Review warnings
- [ ] [Any repo-specific steps from docs/QA.md]

---

**Standards Reference:** docs/QA.md
**Task Commands:** Run `task --list` for all available commands
**Report Location:** `.qa.report.local.md`
**Execution Time:** [total duration]

---

[If --strict triggered early exit]
⚠️ **STRICT MODE**: Execution stopped after first failure. Remaining checks not run.

[If Taskfile not found]
⚠️ **NO TASKFILE**: This repo lacks a Taskfile.yml. Consider adding one for consistent automation.
Recommend: https://taskfile.dev/

[If test-only mode]
ℹ️ **TEST-ONLY MODE**: Only test suite was run. Use `/qa` (no scope) for full QA checks.

[If quick mode]
ℹ️ **QUICK MODE**: Only failed tests were re-run. Use `/qa tests` for full test suite.

## Phase 4: Present Results

1. Save report to `.qa.report.local.md`
2. Print summary to console:

   ```text
   QA Results for [scope]:
   ✅ [task command]: Passed
   ❌ [task command]: Failed (see details)
   ⚠️ [task command]: Warning

   Overall: ❌ FAIL - [X] critical issues
   Report: .qa.report.local.md
   ```

3. If `--compare`: Print key deltas
4. Execute: `code .qa.report.local.md`
5. Exit status:
   - 0: All passed
   - 1: Critical failures (thresholds not met)
   - 2: Warnings only

## Error Handling

- **docs/QA.md missing**: Fail immediately with error message
- **Taskfile missing**: Warn but continue (note in report)
- **Task command fails**: Record in report, continue unless `--strict`
- **Cannot parse task output**: Include raw output, note parsing failure
- **Git commands fail** (for --diff): Warn, fall back to scope
- **Previous report missing** (for --compare): Note but continue

## Quick Reference

**Common workflows:**

```bash
# After seeing test failures
/qa tests          # Fast: Run tests only
/qa quick          # Fastest: Re-run failed tests only
/qa tests --fix    # Fix common test issues automatically

# Full QA before commit
/qa                # All checks
/qa --strict       # Stop on first failure
/qa --diff         # Only check changed files

# Compare with previous run
/qa --compare      # Show improvements/regressions
```

**Mode summary:**

- `test` / `tests` → Test suite only (skips lint, security, etc.)
- `quick` → Re-run failed tests only (fastest feedback)
- No scope → Full QA checks per docs/QA.md
- Custom pattern → Specific files/directories

```text

```
