Skill: glucksberg/anti-pattern-czar (version 1.0.0)

--- name: anti-pattern-czar description: "Detect and fix TypeScript error handling anti-patterns with state persistence and approval workflows. Use when scanning a codebase for silent error failures, empty catches, promise swallowing, or unlogged errors. Supports five modes — scan (detect all issues), review (interactive fix session), auto (batch fix with guardrails), resume (continue from last session), report (show progress). Triggers on phrases like 'scan for anti-patterns', 'fix error handling', 'find empty catches', 'anti-pattern czar', or 'check error handling'." --- # Anti-Pattern Czar Autonomous agent that systematically identifies and fixes TypeScript error handling anti-patterns. ## Detector Run with Bun (no install required): ```bash bunx antipattern-czar bunx antipattern-czar --src lib bunx antipattern-czar --config my-config.json ``` Config via `.antipatternrc.json`: ```json { "srcDir": "src", "criticalPaths": ["DatabaseService.ts", "AuthHandler.ts"], "skipDirectories": ["node_modules", "dist", ".git"] } ``` ## Mode Selection Parse user intent to pick mode: | User Says | Mode | Action | |-----------|------|--------| | "scan", "detect", "find" | SCAN | Run detector, save state | | "review", "fix", "help me fix" | REVIEW | Interactive fix session | | "auto", "fix all", "autonomous" | AUTO | Batch fix with guardrails | | "resume", "continue" | RESUME | Load state, continue | | "report", "status", "progress" | REPORT | Show current state | ## State File Always check `.anti-pattern-state.json` at the project root. On first SCAN, ask if resuming when it exists. ```json { "session_id": "<uuid>", "started_at": "<ISO>", "target_path": "<path>", "issues": [], "history": [] } ``` Issue schema: `id`, `file`, `line`, `pattern`, `severity` (critical/high/medium), `is_critical_path`, `status` (pending/fixed/approved_override/skipped), `code_snippet`. ## Workflow by Mode See [workflows.md](references/workflows.md) for full per-mode workflows. Summary: - **SCAN**: Run detector → parse issues → classify severity → save state → show summary - **REVIEW**: Load state → sort by critical-path + severity → read code context → explain issue → propose fix options → apply approved fix → update state - **AUTO**: Confirm with user → auto-fix non-critical-path issues using templates → switch to REVIEW for critical-path hits → show summary - **RESUME**: Load `.anti-pattern-state.json` → continue from first `pending` issue - **REPORT**: Display session stats, severity table, recent fixes, next actions ## Approved Overrides Only suggest `APPROVED_OVERRIDE` when ALL are true: 1. Error is **expected and frequent** 2. Logging would create **excessive noise** 3. There is **explicit recovery/fallback logic** 4. Reason is **specific and technical** **NEVER** approve overrides on critical paths without exceptional user confirmation. Format: ```typescript } catch { // [APPROVED_OVERRIDE] <specific technical reason> // Fallback: <what happens instead> } ``` ## Fix Templates See [patterns.md](references/patterns.md) for the full pattern list with severity, auto-fix eligibility, and code templates. ## Progress Output Format After each fix: ``` ✅ Fixed: src/services/example.ts:42 Pattern: NO_LOGGING_IN_CATCH Solution: Added logger.error() with context Progress: 4/28 issues remaining ━━━━━━━ 14% ```

path: references/patterns.md
content: # Anti-Pattern Patterns Reference

## Pattern Catalog

| Pattern | Severity | Auto-Fixable | Description |
|---------|----------|--------------|-------------|
| EMPTY_CATCH | critical | ✅ | Empty catch block silently swallows errors |
| PROMISE_EMPTY_CATCH | critical | ✅ | `.catch(() => {})` — errors vanish into the void |
| CATCH_AND_CONTINUE_CRITICAL_PATH | critical | ❌ | Critical path logs-and-continues after errors |
| NO_LOGGING_IN_CATCH | high | ✅ | Catch block with no logging, stderr, or rethrow |
| ERROR_STRING_MATCHING | high | ❌ | `.includes()` on error.message to detect types |
| PROMISE_CATCH_NO_LOGGING | high | ✅ | Promise `.catch()` handler that doesn't log |
| LARGE_TRY_BLOCK | medium | ❌ | Try blocks over 10 significant lines (too broad) |
| GENERIC_CATCH | medium | ❌ | No error type discrimination in catch |
| PARTIAL_ERROR_LOGGING | medium | ✅ | Logging `error.message` instead of full error object |
| ERROR_MESSAGE_GUESSING | medium | ❌ | Multiple string checks to guess what went wrong |

## Fix Templates

### EMPTY_CATCH
```typescript
// Before
} catch (error) {
}

// After
} catch (error) {
  logger.error('Failed to perform <operation>', { error, context: { /* relevant state */ } });
}
```

### NO_LOGGING_IN_CATCH — Prepend logging before existing code
```typescript
// After
} catch (error) {
  logger.error('Failed to <operation>', { error });
  // ... existing catch body ...
}
```

### PROMISE_EMPTY_CATCH
```typescript
// Before
.catch(() => {})

// After
.catch((error) => {
  logger.error('Promise rejected in <chain>', { error });
})
```

### PARTIAL_ERROR_LOGGING
```typescript
// Before
logger.error('Failed', error.message);

// After
logger.error('Failed', { error }); // logs full stack trace
```

### GENERIC_CATCH — Add type narrowing
```typescript
} catch (error) {
  if (error instanceof SpecificError) {
    logger.warn('Expected error type', { error });
    return fallback();
  }
  logger.error('Unexpected error', { error });
  throw error;
}
```

### LARGE_TRY_BLOCK — Split into targeted units
Break the monolithic try into separate operations, each with its own error strategy:
- Critical operations: let propagate or explicitly rethrow
- Non-critical (e.g., cache, notifications): `.catch()` with logging + graceful degradation

### CRITICAL_PATH — Fail loud
Options in order of preference:
1. **Propagate**: remove try-catch, let error bubble up
2. **Log + rethrow**: full context logging, then `throw error`
3. **Log + explicit recovery**: full logging + call `markJobForRetry()` or equivalent — never silent continuation

## Severity Guide

- **critical**: Must fix before ship. Silent failures that hide production issues.
- **high**: Fix soon. Makes debugging significantly harder.
- **medium**: Fix when touching the file. Code smell, not immediately dangerous.

## Context Variables for Templates

| Variable | Example |
|----------|---------|
| `<operation>` | "fetch user data", "connect to database" |
| `<context>` | `{ userId, requestId, attempt }` |
| `<fallback>` | "using cached value", "returning default" |


path: references/workflows.md
content: # Workflow Details

## SCAN Mode

1. Check if `.anti-pattern-state.json` exists
   - If exists → ask: "Found existing session with X/Y fixed. Resume or start fresh?"
2. Run detector: `bunx antipattern-czar`
3. Parse output — extract file, line, pattern, snippet per issue
4. Classify severity and critical-path status
5. Write `.anti-pattern-state.json`
6. Show summary:

```
🔍 Scan Complete

Found 132 anti-patterns:
├── CRITICAL: 28 (21%)
├── HIGH: 45 (34%)
└── MEDIUM: 59 (45%)

Critical path issues: 12 (require immediate attention)

Next: Run /anti-pattern-czar review to start fixing
```

## REVIEW Mode

1. Load `.anti-pattern-state.json`
2. Filter pending issues, sorted: critical-path first → severity (critical > high > medium)
3. For each issue:

   **a. Read code** (±10 lines context using Read tool)

   **b. Explain problem:**
   ```
   ⚠️ Issue #3/28 [CRITICAL] - NO_LOGGING_IN_CATCH

   File: src/services/worker-service.ts:142
   Critical Path: YES ⛔

   try {
     await this.processJob(job);
   } catch (error) {
     // Nothing here — failures are invisible!
   }

   WHY DANGEROUS:
   • Job failures are completely silent
   • No debugging signal for production issues
   ```

   **c. Propose fix options** (offer 3–4 concrete choices):
   - Add logging
   - Add logging + rethrow
   - Remove try-catch (propagate)
   - Skip for now

   **d. Apply chosen fix** using Edit tool

   **e. Update state**, show progress, ask to continue

4. Every 5 fixes: offer to re-run detector to verify

## AUTO Mode

> ⚠️ Requires explicit user confirmation before starting

1. Ask: "Auto mode will fix X issues automatically. Proceed?"
2. For each **non-critical-path** issue:
   - Apply standard fix template from `patterns.md`
   - Log all changes
3. For **critical-path** issues: STOP → switch to REVIEW mode
   - Message: "Found critical-path issue in `<file>`. Switching to review mode for manual approval."
4. Generate final summary report

### Auto-eligible patterns
Only auto-fix patterns marked ✅ in the pattern catalog: EMPTY_CATCH, NO_LOGGING_IN_CATCH, PROMISE_EMPTY_CATCH, PARTIAL_ERROR_LOGGING, PROMISE_CATCH_NO_LOGGING.

Never auto-fix: LARGE_TRY_BLOCK, GENERIC_CATCH, ERROR_STRING_MATCHING, ERROR_MESSAGE_GUESSING, CATCH_AND_CONTINUE_CRITICAL_PATH.

## RESUME Mode

1. Load `.anti-pattern-state.json`
2. Show: "Session found. X/Y fixed. Y–X pending."
3. Start REVIEW mode from first `pending` issue

## REPORT Mode

```
═══════════════════════════════════════════════════════
              Anti-Pattern Czar — Session Report
═══════════════════════════════════════════════════════

Session: abc123 | Started: 2026-01-27 10:30 AM | Duration: 2h 15m

PROGRESS ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 45%

  Total Issues:    132
  Fixed:            52 (39%)
  Overrides:         8 (6%)
  Remaining:        72 (55%)

BY SEVERITY
┌──────────┬───────┬───────┬───────────┐
│ Severity │ Fixed │ Total │ Remaining │
├──────────┼───────┼───────┼───────────┤
│ CRITICAL │    12 │    28 │        16 │
│ HIGH     │    22 │    45 │        23 │
│ MEDIUM   │    18 │    59 │        41 │
└──────────┴───────┴───────┴───────────┘

RECENT FIXES
• worker-service.ts:142 — Added logging
• SessionStore.ts:89 — Removed empty catch
• SearchManager.ts:234 — Added type narrowing

NEXT ACTIONS
→ /anti-pattern-czar review        Continue fixing
→ /anti-pattern-czar auto --high   Auto-fix HIGH severity
═══════════════════════════════════════════════════════
```

## Completion Report

```
Anti-pattern cleanup complete!

Before:  ISSUES: 28
After:   ISSUES: 0  |  APPROVED OVERRIDES: 15

All anti-patterns resolved! 🎉
```

## Error Handling

- Detector fails → report error, ask user to check Bun and package availability (`bunx antipattern-czar --version`)
- State file corrupted → offer to backup + start fresh
- Fix application fails → rollback edit, report error, continue to next issue


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (MEDIUM)