# Code Audit Skill

Perform systematic code audits to find anti-patterns, hidden errors, security issues, and architecture violations.

## Usage

```
/code-audit [category] [path]
```

**Categories:**
- `errors` - Silent failures, swallowed exceptions, hidden errors
- `security` - Input validation, auth checks, data exposure
- `architecture` - DI violations, import boundaries, coupling
- `all` - Run all audit categories (default)

**Path:** Optional path to audit (defaults to `backend/app/`)

## Examples

```
/code-audit                     # Full audit of backend/app/
/code-audit errors              # Just error handling patterns
/code-audit security services/  # Security audit of services/
```

## Instructions

When this skill is invoked:

1. **Load Pattern Definitions**
   Read the YAML files in `patterns/` directory for the requested category.

2. **Search Codebase**
   For each pattern, use Grep with the specified regex to find matches.
   Focus on production code (skip test files unless pattern specifies otherwise).

3. **Analyze Context**
   For each match, read surrounding code to determine verdict:
   - **ISSUE**: Code should be changed (explain why)
   - **WARNING**: Potential problem, needs review
   - **OK**: Pattern detected but implementation is correct (explain why)

4. **Generate Report**
   Output structured report with:
   - Summary stats (issues/warnings/ok by category)
   - Detailed findings with file:line references
   - Recommendations for each issue

## Verdict Guidelines

### Error Handling

**ISSUE** when:
- Exception caught, logged, but execution continues with corrupted/partial state
- `None` returned for error condition without documentation
- Error logged but caller has no way to detect failure

**OK** when:
- Error logged AND exception re-raised with context
- Method returns explicit failure indicator (False, Result type) that caller checks
- Graceful degradation is intentional and documented

### Security

**ISSUE** when:
- User input used directly without validation
- Auth check missing on endpoint that modifies data
- Sensitive data (passwords, tokens) logged or exposed in errors

**OK** when:
- Input validated at API boundary before reaching service
- Auth handled by dependency injection (get_current_user)
- Sensitive fields excluded from serialization

### Architecture

**ISSUE** when:
- `app/core/` imports from `app/services/` or `app/api/`
- Service directly accesses ORM models instead of repository
- Global state modified without DI support for testing

**OK** when:
- Import is type-only (`if TYPE_CHECKING:`)
- Cross-layer access is through injected dependency
- Global has DI override capability in constructor

## Pattern File Format

```yaml
name: Category Name
description: What this category audits

patterns:
  - id: unique-pattern-id
    description: Human-readable description
    grep_pattern: 'regex pattern for Grep tool'
    file_glob: '*.py'           # Optional, defaults to *.py
    exclude_tests: true         # Optional, defaults to true
    multiline: false            # Optional, for cross-line patterns
    context_lines: 3            # Lines to read around match
    verdict_hints:
      ISSUE_IF: "condition that makes this an issue"
      OK_IF: "condition that makes this acceptable"
```

## Output Format

```markdown
# Code Audit Report

**Scope:** backend/app/
**Categories:** errors, security, architecture
**Date:** YYYY-MM-DD

## Summary

| Category | Issues | Warnings | OK |
|----------|--------|----------|-----|
| Errors | 2 | 1 | 5 |
| Security | 0 | 2 | 3 |
| Architecture | 1 | 0 | 4 |

## Issues (Fix Required)

### [ISSUE] error-hiding.log-and-continue
**File:** app/services/card_service.py:209
**Pattern:** Log and continue on error

```python
except Exception as e:
    logger.error(f"Failed to load card: {e}")
    return None  # Caller silently gets None
```

**Problem:** Caller has no way to detect failure. Cards silently missing.
**Recommendation:** Raise exception or return Result type with error info.

---

## Warnings (Review Needed)

...

## OK (Verified Correct)

...
```
