From 69f2b36e4efe5b4e6f902262edc670d6d3e5a227 Mon Sep 17 00:00:00 2001 From: Gerald Onyango Date: Wed, 18 Feb 2026 15:09:11 -0500 Subject: [PATCH] feat: add sql-optimization-patterns skill and sql-reviewer agent Add Phase 8 (SQL REVIEW) to the 11-phase development lifecycle. A fresh Staff Engineer sub-agent audits all database queries, mutations, and ORM usage for performance, security, and defensive coding before commit. - Install sql-optimization-patterns skill from wshobson/agents, enhanced with SQLite/libSQL patterns and ORM anti-patterns - Create sql-reviewer agent with checklist for N+1, missing indexes, SQL injection, mass assignment, transaction safety, and more - Update CLAUDE.md, CLAUDE-BASE.md template, and README.md Co-Authored-By: Claude Opus 4.6 --- CLAUDE.md | 262 ++++++++++ README.md | 26 +- agents/sql-reviewer.md | 187 +++++++ skills/sql-optimization-patterns/SKILL.md | 605 ++++++++++++++++++++++ templates/CLAUDE-BASE.md | 87 ++-- 5 files changed, 1126 insertions(+), 41 deletions(-) create mode 100644 CLAUDE.md create mode 100644 agents/sql-reviewer.md create mode 100644 skills/sql-optimization-patterns/SKILL.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..916395f --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,262 @@ +# futuregerald-claude-plugin - Claude Code Configuration + +## Key Directories + +- `internal/` +- `docs/` + +--- + +## Development Lifecycle (MASTER WORKFLOW) + +**MANDATORY: Create a todo list using TaskCreate for every non-trivial task.** + +| Phase | Action | Skill/Tool | Gate | +|-------|--------|------------|------| +| 1. RECEIVE | Understand task, create todo list | `TaskCreate` | Todo list exists | +| 2. PLAN | Write implementation plan | `superpowers:writing-plans` | Plan document created | +| 3. REVIEW PLAN | Staff Engineer reviews plan | `superpowers:code-reviewer` via `Task` | Reviewer approves | +| 4. IMPLEMENT | Write code following TDD | `superpowers:test-driven-development` | Tests exist and pass | +| 5. TEST | `go test ./...` | — | Zero failures | +| 6. SIMPLIFY | `Task(subagent_type="code-simplifier")` | `code-simplifier` agent | Staff review complete | +| 7. CODE REVIEW | `Task(subagent_type="superpowers:code-reviewer")` | Fresh sub-agent | Reviewer approves | +| 8. SQL REVIEW | `Task(subagent_type="superpowers:code-reviewer")` with SQL audit prompt | `sql-optimization-patterns` skill + `sql-reviewer` agent | Reviewer approves | +| 9. COMMIT | `git commit` | — | Commit created | +| 10. PUSH | Push feature branch; `gh pr create` with `Closes #N` if `gh` available | — | Branch pushed (PR created if `gh`) | +| 11. VERIFY CI | If `gh`: `gh run list`, autonomous PR review, auto-merge when green | — | CI green (if applicable) | + +**Exceptions that skip planning:** pure doc updates, `git revert`. + +### Mandatory Phase Rules + +**All phases are MANDATORY. No exceptions. No skipping "simple" changes.** + +- **Phases 3, 6, 7, 8** MUST use `Task` tool (fresh sub-agent, no shared context) +- NEVER review your own plan or code — you wrote it, you cannot objectively review it +- If reviewer finds CRITICAL/IMPORTANT issues: fix, re-run tests, re-review +- Only proceed after explicit reviewer approval +- `ExitPlanMode` requires prior staff engineer approval of the plan + +**Plan review prompt template:** +``` +Task(subagent_type="superpowers:code-reviewer", prompt=" + Review this plan: . Verify: file paths accurate, codebase facts correct, + no missing edge cases, response shapes match actual patterns, nothing already implemented. +") +``` + +**Code simplifier rules:** +- Run after tests pass (Phase 5), before code review (Phase 7) +- Only implement APPROVED simplifications +- Re-run tests after applying changes + +**SQL review rules:** +- Run after code review passes (Phase 7), before commit (Phase 9) +- Dispatch a fresh Staff Engineer sub-agent using the `sql-reviewer` agent template +- The reviewer audits ALL database queries, mutations, and ORM usage for: **performance**, **security**, and **defensive coding** +- CRITICAL findings MUST be fixed. Re-run tests after fixes, then re-run SQL review +- IMPORTANT findings: fix if possible, otherwise open a GitHub issue immediately +- Max 3 review cycles before escalating to user + +**Pre-existing issues found during review:** +- If reviewer flags a pre-existing issue in code you're touching, **fix it** — you own that code path +- Only exception: issue is in completely unrelated code your changes don't touch + +**Unaddressed work MUST be tracked:** +- Any improvement, follow-up, or deferred fix identified during work (code simplifier suggestions, reviewer findings, TODOs) that is NOT addressed in the current branch MUST be tracked +- If `gh` is available: file as a GitHub issue. Otherwise: add to the todo list or note in a `TODO.md` +- This includes: approved simplifications deferred to a follow-up, pre-existing issues in unrelated code, scope-expanding suggestions +- Never silently drop findings — if you're not fixing it now, track it + +--- + +## Branching and Sub-Agents + +### Branch Protection + +- **Never commit to main.** All changes go through feature branches (and PRs when `gh` is available). +- Branch naming: `/` (e.g., `feat/user-profiles`, `fix/login-redirect`) + +### Sub-Agent Workflow + +**The orchestrating agent NEVER writes code.** It coordinates: +- Branch management, plan management, task dispatch, and (optionally) PR creation +- Every implementation task gets a fresh sub-agent pointed at the feature branch +- Use `superpowers:subagent-driven-development` (preferred) or `superpowers:executing-plans` +- Independent tasks can run in parallel via `superpowers:dispatching-parallel-agents` + +**How it works (without worktrees):** + +1. Create a feature branch from main: `git checkout -b /` +2. Dispatch sub-agents to implement tasks on the current branch +3. Sub-agents write code, run tests, and commit to the feature branch +4. After all tasks complete, push the branch and create a PR (if `gh` is available) + +Sub-agents work in the current working directory on the active feature branch. No worktrees are needed — the orchestrator simply checks out the feature branch and dispatches work. + +### PRs (when `gh` is available) + +- Use `Closes #N` (not Fixes/Resolves) in PR body to auto-close issues +- Include `Refs #N` in commit message bodies + +--- + +## GitHub Workflow (Optional — Beta) + +> **Beta:** This workflow is highly opinionated and requires the [GitHub CLI (`gh`)](https://cli.github.com/) installed, authenticated, and `/project:init` run before use. It adds structured issue tracking, git worktrees, project board management, and autonomous PR review on top of the base sub-agent workflow. **It is not required to use the plugin.** Read the README thoroughly before enabling. + +### Prerequisites + +- **Initialization required** before ANY GitHub write (issues, PRs, labels): run `/project:init` +- Check: `gh label list --json name --jq '.[].name' | grep -q '^claude:initialized$'` +- If not initialized: block GitHub writes, allow local work (branches, commits) +- **Graceful degradation**: if `gh` unavailable (`gh auth status 2>/dev/null`), skip all GitHub integration and continue normally. Never block work. + +### Git Worktrees + +When the GitHub workflow is active, every feature branch gets its own worktree for full isolation: +```bash +REPO_NAME=$(basename "$(git rev-parse --show-toplevel)") +mkdir -p "../worktrees/$REPO_NAME" +git worktree add "../worktrees/$REPO_NAME/" -b +# Cleanup after merge: +git worktree remove "../worktrees/$REPO_NAME/" +``` + +- If worktree/branch already exists, reuse it (omit `-b` for existing branch) +- Monorepo: use `~/worktrees//` to avoid parent repo tracking +- Sub-agents receive the worktree path and work there instead of the main working directory + +### Issues + +- Create in Phase 1 (RECEIVE) if `gh` available +- Use conventional commit prefixes for titles: `feat:`, `fix:`, `refactor:`, etc. +- Labels created by `/project:init` map from commit prefixes (feat→feature, fix→bug, etc.) +- Workflow-created issues include `` marker; those without it are external requests +- **Epics**: parent issues labeled `epic` grouping task sub-issues. Create with `/project:plan-feature`. +- **Issues must be actionable.** When referencing code, always include specific file paths and line numbers. If a pattern repeats in N locations, list every location. An engineer should be able to start working from the issue alone without searching the codebase. + +### Autonomous PR Review (Default) + +After every PR is created, automatically: + +1. Dispatch `superpowers:code-reviewer` via `Task` to review `gh pr diff` +2. Post feedback on the GitHub PR via `gh pr review` (approve or request-changes) +3. If issues found: dispatch fresh sub-agents to fix → push → re-review (max 3 cycles) +4. Wait for CI: `gh pr checks --watch` (fix failures via sub-agent, max 3 attempts) +5. When CI passes: merge, cleanup, and pull: + ```bash + gh pr merge --squash --delete-branch # merges + deletes remote branch + git worktree remove # removes local worktree (if used) + git branch -d # deletes local branch + git pull # updates main + ``` + +**Auto-merge is mandatory when CI is green.** Do not ask for user confirmation. Post-merge cleanup (branch deletion + pull) is also mandatory — never leave stale branches. + +**Safety limits:** Max 3 review cycles, max 3 CI fixes. Never merge with failing CI or unresolved Critical findings. + +### Project Board (Kanban) + +- Columns: Todo → In Progress → Done +- Move to "In Progress" when implementation starts (Phase 4) +- Move to "Done" after PR merged and cleaned up +- Use `gh project item-edit` with `--jq` for filtering (no external `jq`) + +### Slash Commands + +- `/project:init` — **Run first.** Creates board + labels +- `/project:create-issue`, `/project:plan-feature`, `/project:sync-tasks` +- `/project:current`, `/project:inbox` — read-only, work before init +- `/project:cleanup` — stale worktrees (dry-run default) + +--- + +## Mandatory Skills + +| Trigger | Skill | +|---------|-------| +| Bug investigation | `systematic-debugging` | +| New feature | `superpowers:test-driven-development` (RED→GREEN→REFACTOR) | +| Database queries/mutations changed | `sql-optimization-patterns` + `sql-reviewer` agent | +| About to claim completion | `verification-before-completion` | + +--- + +## Emergency Procedures + +**CI fails 3+ times:** Stop pushing. Run `go build ./...` locally. If still failing, branch from last good state + cherry-pick. If blocked >30min, ask user. + +**Task blocked:** Document blocker, update task status, ask user with options A/B/C. Never guess. + +--- + +## Commits + +- Conventional commit format + +## Quick Reference +```bash +go test ./... +``` + +--- + +## Go Rules + +### Style + +- Follow `gofmt` and `go vet` conventions +- Use short variable names for short scopes +- Return early to reduce nesting +- Handle errors explicitly, don't ignore them +```go +// Before +func processItems(items []Item) ([]Result, error) { + results := []Result{} + for i := 0; i < len(items); i++ { + item := items[i] + if item.Valid { + result, err := process(item) + if err != nil { + return nil, err + } + results = append(results, result) + } + } + return results, nil +} + +// After +func processItems(items []Item) ([]Result, error) { + var results []Result + for _, item := range items { + if !item.Valid { + continue + } + result, err := process(item) + if err != nil { + return nil, err + } + results = append(results, result) + } + return results, nil +} +``` + +### Best Practices + +- Use `defer` for cleanup +- Keep interfaces small (1-3 methods) +- Accept interfaces, return concrete types +- Use table-driven tests +- Prefer composition over inheritance (embedding) + +### Testing +```bash +go test ./... # Run all tests +go test -v ./... # Verbose +go test -cover ./... # With coverage +go vet ./... # Static analysis +``` + diff --git a/README.md b/README.md index 47c00a2..071e06e 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ skill-installer --mode config-only --target claude --yes ### Skills — Teaching Claude How to Work -Skills are markdown-based instruction sets that give Claude specialized knowledge and workflows. When invoked, Claude follows the skill's process exactly. The plugin includes 33 skills covering: +Skills are markdown-based instruction sets that give Claude specialized knowledge and workflows. When invoked, Claude follows the skill's process exactly. The plugin includes 34 skills covering: - **Test-driven development** — RED/GREEN/REFACTOR cycle - **Systematic debugging** — 4-phase protocol: root cause analysis, pattern matching, hypothesis testing, implementation @@ -76,7 +76,7 @@ Skills are invoked by name in Claude Code: ### Agents — Specialized Sub-Agents -Agents are dispatched via the `Task` tool to handle focused work with fresh context. The plugin includes 6 agents: code quality reviewer, code simplifier (with Staff Engineer review), codebase searcher, debugger, implementer, and spec reviewer. +Agents are dispatched via the `Task` tool to handle focused work with fresh context. The plugin includes 7 agents: code quality reviewer, code simplifier (with Staff Engineer review), codebase searcher, debugger, implementer, spec reviewer, and SQL performance reviewer. ### Development Workflow — A Structured Lifecycle @@ -90,9 +90,10 @@ The plugin defines a 10-phase development lifecycle in the generated CLAUDE.md: 5. TEST Run tests and type checking 6. SIMPLIFY Code-simplifier agent analyzes for improvements 7. CODE REVIEW Code-reviewer sub-agent reviews changes - 8. COMMIT Commit to feature branch - 9. PUSH + PR Push and create PR (if gh available) -10. VERIFY CI Check CI passes; auto-merge when green + 8. SQL REVIEW Staff Engineer audits queries for performance, security, defensive coding + 9. COMMIT Commit to feature branch +10. PUSH + PR Push and create PR (if gh available) +11. VERIFY CI Check CI passes; auto-merge when green ``` Each phase has a gate — the workflow doesn't advance until the gate passes. This works entirely locally. For teams using GitHub, an optional beta workflow adds issue tracking, worktrees, and autonomous PR review (see [GitHub Workflow](#github-workflow-optional--beta) below). @@ -201,7 +202,7 @@ If symlinked to `~/.claude/skills`, use the `superpowers:` prefix: ## Skills and Agents Reference -### Skills (33) +### Skills (34) **Core Workflow:** @@ -241,6 +242,7 @@ If symlinked to `~/.claude/skills`, use the `superpowers:` prefix: | `javascript-testing-patterns` | Jest, Vitest, and Japa testing patterns | | `sqlite-database-expert` | SQLite, libSQL, and Turso expertise | | `turso-best-practices` | Turso database patterns | +| `sql-optimization-patterns` | SQL query optimization, indexing, EXPLAIN analysis, N+1 elimination | **Design and Frontend:** @@ -266,7 +268,7 @@ If symlinked to `~/.claude/skills`, use the `superpowers:` prefix: | `baoyu-article-illustrator` | Article illustration generation | | `create-auth-skill` | Auth layer creation | -### Agents (6) +### Agents (7) Agents are specialized sub-agents dispatched via the Task tool. They run with fresh context and no knowledge of the parent conversation. @@ -278,6 +280,7 @@ Agents are specialized sub-agents dispatched via the Task tool. They run with fr | `debugger` | Systematic bug investigation | | `implementer` | Implements features from plans | | `spec-reviewer` | Reviews specifications and plans | +| `sql-reviewer` | Ruthless SQL performance, security, and defensive coding audit | ### Language Templates @@ -486,12 +489,13 @@ The full development lifecycle managed by the plugin follows this sequence: 5. TEST Run all tests and type checking (must pass) 6. SIMPLIFY Code-simplifier agent analyzes for improvements (Staff review) 7. CODE REVIEW Code-reviewer sub-agent reviews changes (must approve) - 8. COMMIT Commit to the feature branch - 9. PUSH + PR Push branch, create PR with "Closes #N" to auto-close the issue -10. VERIFY CI Check that CI passes; fix and re-push if it fails + 8. SQL REVIEW Staff Engineer audits queries for performance, security, defensive coding + 9. COMMIT Commit to the feature branch +10. PUSH + PR Push branch, create PR with "Closes #N" to auto-close the issue +11. VERIFY CI Check that CI passes; fix and re-push if it fails ``` -Each phase has a verification gate. The workflow does not advance until the gate passes. For example, code review must explicitly approve before a commit is created, and CI must be green before work is considered done. +Each phase has a verification gate. The workflow does not advance until the gate passes. For example, code review must explicitly approve before SQL review runs, SQL review must approve before a commit is created, and CI must be green before work is considered done. ### Initialization diff --git a/agents/sql-reviewer.md b/agents/sql-reviewer.md new file mode 100644 index 0000000..83c7de7 --- /dev/null +++ b/agents/sql-reviewer.md @@ -0,0 +1,187 @@ +# SQL Performance Reviewer Subagent + +Use this subagent to audit all database queries, mutations, and ORM usage for performance, security, and defensive coding. + +**Purpose:** Ruthlessly audit SQL patterns for performance bottlenecks, security vulnerabilities, and defensive coding gaps + +**When to use:** After CODE REVIEW passes (Phase 7), before COMMIT (Phase 9). This is Phase 8: SQL REVIEW. + +**CRITICAL:** MUST always be dispatched via the `Task` tool as a fresh subagent with NO shared conversation context. The reviewer needs independent judgment — shared context creates anchoring bias and causes the reviewer to rubber-stamp work they watched being built. Never run reviews inline in the main conversation. + +## Dispatch Configuration + +``` +Task tool: + subagent_type: superpowers:code-reviewer + description: "SQL performance review for [feature/PR]" +``` + +## Prompt Template + +``` +You are a Staff Engineer specializing in database performance, security, and defensive coding. +Your job is to ruthlessly audit every database query, mutation, and ORM interaction in the +changed code. You are not here to be nice. You are here to catch problems before production. + +## Skill Reference + +Use the `sql-optimization-patterns` skill as your reference for all optimization patterns. +Read it first via: /superpowers:sql-optimization-patterns + +## Database Context + +[Specify the database engine: PostgreSQL, SQLite/libSQL/Turso, MySQL, etc.] +[Note any ORM in use: Lucid, Prisma, Drizzle, Eloquent, ActiveRecord, etc.] + +## What Was Changed + +[Summary of implementation — what queries/models/controllers were added or modified] + +## Files to Review + +[List all files containing database interactions — controllers, models, services, migrations] + +## Git Context + +- Base SHA: [commit before task started] +- Head SHA: [current commit after implementation] + +## REVIEW CHECKLIST — Check Every Item + +### Performance (CRITICAL) + +- [ ] **N+1 queries**: Are there loops that execute queries inside them? Are all relations + properly eager-loaded? Check `.preload()`, `.with()`, `include`, or equivalent. +- [ ] **Missing indexes**: Do WHERE clauses, JOIN conditions, and ORDER BY columns have + appropriate indexes? Check migrations for CREATE INDEX statements. +- [ ] **SELECT ***: Are queries fetching only the columns they need, or pulling entire rows? + Check for `.select()` usage in ORM queries. +- [ ] **Unbounded queries**: Are there queries without LIMIT? Could they return thousands of + rows? Is pagination implemented correctly (cursor-based preferred over OFFSET)? +- [ ] **Sequential queries**: Are there multiple independent queries that could be batched + or run concurrently? Look for `await` in sequence where `Promise.all()` would work. +- [ ] **Correlated subqueries**: Are there subqueries that execute per-row instead of using + JOINs or CTEs? +- [ ] **Expensive aggregations**: Are COUNT/SUM/GROUP BY queries hitting large tables without + proper indexes or caching? +- [ ] **Missing composite indexes**: Do queries filter on multiple columns that would benefit + from a composite index vs multiple single-column indexes? +- [ ] **Index order**: For composite indexes, is the column order optimal for the query + patterns? (Most selective column first for equality, range column last) +- [ ] **Write amplification**: Do batch operations use single multi-row INSERT/UPDATE + instead of loops? + +### Security (CRITICAL) + +- [ ] **SQL injection**: Are all user inputs parameterized? No string concatenation in queries. + Check for `.whereRaw()`, `.raw()`, template literals in SQL strings. +- [ ] **Mass assignment**: Are model creates/updates using only whitelisted fields? + No `req.body` passed directly to `.create()` or `.merge()`. +- [ ] **Authorization in queries**: Do queries scope results to the authenticated user? + Can users access other users' data by manipulating IDs? +- [ ] **Sensitive data exposure**: Are queries returning password hashes, tokens, or other + sensitive fields that should be excluded? +- [ ] **Rate limiting**: Are expensive queries (search, aggregations) protected by rate + limiting or caching? + +### Defensive Coding (IMPORTANT) + +- [ ] **Error handling on queries**: Are database errors caught and handled gracefully? + What happens if a query fails mid-transaction? +- [ ] **Transaction boundaries**: Are related write operations wrapped in transactions? + Can partial failures leave data in an inconsistent state? +- [ ] **Null safety**: Do queries handle NULL values correctly? Are LEFT JOINs accounting + for NULL in the joined table? +- [ ] **Type safety**: Are query parameters the correct types? Could implicit type coercion + prevent index usage? +- [ ] **Soft-delete awareness**: If the project uses soft deletes, do queries properly + filter out deleted records? Check for `whereNull('deletedAt')` or equivalent scopes. +- [ ] **Concurrent access**: Could two requests hitting the same endpoint cause race + conditions? Are upserts or advisory locks needed? +- [ ] **Migration safety**: Do migrations have proper rollback (`down()`) methods? Could + they lock tables for too long on large datasets? + +### ORM-Specific Patterns (IMPORTANT) + +- [ ] **Lazy loading traps**: Are there `.related()` calls inside loops instead of + `.preload()` on the parent query? +- [ ] **Model serialization**: Are Lucid/Eloquent models serialized before passing to + views/responses? (Never pass raw models to `inertia.render()`) +- [ ] **Query scope usage**: Are reusable query patterns extracted into model scopes + rather than repeated inline? +- [ ] **Raw query necessity**: Are `.whereRaw()` / `.raw()` calls truly necessary, or + could the ORM query builder handle it? + +## Report Format + +For each finding, report: + +**[CRITICAL/IMPORTANT/MINOR] — [Category] — [Short description]** +- File: `path/to/file.ts:line_number` +- Problem: [What's wrong and why it matters] +- Fix: [Specific code change needed] +- Impact: [What happens if this isn't fixed — slow queries, data leak, crash, etc.] + +## Assessment + +- **CRITICAL findings MUST be fixed before proceeding.** No exceptions. +- **IMPORTANT findings SHOULD be fixed.** If not fixed, a GitHub issue MUST be opened. +- **MINOR findings** are at the implementer's discretion but should be noted. + +Final verdict: +- APPROVED: No critical or important findings +- APPROVED WITH CONDITIONS: Important findings that need GitHub issues +- CHANGES REQUIRED: Critical findings that must be fixed before commit +``` + +## Usage Example + +```typescript +Task({ + subagent_type: 'superpowers:code-reviewer', + description: 'SQL performance review for journey CRUD', + prompt: `You are a Staff Engineer specializing in database performance, security, +and defensive coding. Your job is to ruthlessly audit every database query, mutation, +and ORM interaction in the changed code. + +## Skill Reference + +Use the sql-optimization-patterns skill as your reference. + +## Database Context + +Database: libSQL / Turso (SQLite-compatible) +ORM: Lucid (AdonisJS) + +## What Was Changed + +Added journey CRUD operations with file uploads, soft-delete support, +and admin management features. + +## Files to Review + +- app/controllers/journeys_controller.ts +- app/models/journey.ts +- app/services/journey_service.ts +- database/migrations/001_create_journeys.ts + +## Git Context + +- Base SHA: abc1234 +- Head SHA: def5678 + +[... full checklist from template ...] +`, +}) +``` + +## Review Loop + +If SQL review returns findings: + +1. **Critical findings:** Implementer MUST fix, re-run tests, then re-run SQL review +2. **Important findings:** Fix if possible. For any not fixed, open a GitHub issue immediately with file paths, line numbers, and the specific problem +3. **Minor findings:** Note in the review but do not block +4. **Max 3 review cycles.** If critical findings persist after 3 cycles, escalate to user. + +After fixes, dispatch another SQL review to verify critical findings are resolved. diff --git a/skills/sql-optimization-patterns/SKILL.md b/skills/sql-optimization-patterns/SKILL.md new file mode 100644 index 0000000..7e09a0e --- /dev/null +++ b/skills/sql-optimization-patterns/SKILL.md @@ -0,0 +1,605 @@ +--- +name: sql-optimization-patterns +description: Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application performance. +--- + +# SQL Optimization Patterns + +Transform slow database queries into lightning-fast operations through systematic optimization, proper indexing, and query plan analysis. + +## When to Use This Skill + +- Debugging slow-running queries +- Designing performant database schemas +- Optimizing application response times +- Reducing database load and costs +- Improving scalability for growing datasets +- Analyzing EXPLAIN query plans +- Implementing efficient indexes +- Resolving N+1 query problems + +## Core Concepts + +### 1. Query Execution Plans (EXPLAIN) + +Understanding EXPLAIN output is fundamental to optimization. + +**PostgreSQL EXPLAIN:** + +```sql +-- Basic explain +EXPLAIN SELECT * FROM users WHERE email = 'user@example.com'; + +-- With actual execution stats +EXPLAIN ANALYZE +SELECT * FROM users WHERE email = 'user@example.com'; + +-- Verbose output with more details +EXPLAIN (ANALYZE, BUFFERS, VERBOSE) +SELECT u.*, o.order_total +FROM users u +JOIN orders o ON u.id = o.user_id +WHERE u.created_at > NOW() - INTERVAL '30 days'; +``` + +**SQLite EXPLAIN:** + +```sql +-- SQLite query plan +EXPLAIN QUERY PLAN +SELECT * FROM users WHERE email = 'user@example.com'; + +-- Full opcode listing +EXPLAIN +SELECT * FROM users WHERE email = 'user@example.com'; +``` + +**Key Metrics to Watch:** + +- **Seq Scan / SCAN TABLE**: Full table scan (usually slow for large tables) +- **Index Scan / SEARCH TABLE USING INDEX**: Using index (good) +- **Index Only Scan / USING COVERING INDEX**: Using index without touching table (best) +- **Nested Loop**: Join method (okay for small datasets) +- **Hash Join**: Join method (good for larger datasets) +- **Merge Join**: Join method (good for sorted data) +- **Cost**: Estimated query cost (lower is better) +- **Rows**: Estimated rows returned +- **Actual Time**: Real execution time + +### 2. Index Strategies + +Indexes are the most powerful optimization tool. + +**Index Types:** + +- **B-Tree**: Default, good for equality and range queries (all databases) +- **Hash**: Only for equality (=) comparisons (PostgreSQL) +- **GIN**: Full-text search, array queries, JSONB (PostgreSQL) +- **GiST**: Geometric data, full-text search (PostgreSQL) +- **BRIN**: Block Range INdex for very large tables with correlation (PostgreSQL) + +```sql +-- Standard B-Tree index +CREATE INDEX idx_users_email ON users(email); + +-- Composite index (order matters!) +CREATE INDEX idx_orders_user_status ON orders(user_id, status); + +-- Partial index (index subset of rows) +CREATE INDEX idx_active_users ON users(email) +WHERE status = 'active'; + +-- Expression index +CREATE INDEX idx_users_lower_email ON users(LOWER(email)); + +-- Covering index (include additional columns) -- PostgreSQL +CREATE INDEX idx_users_email_covering ON users(email) +INCLUDE (name, created_at); + +-- Full-text search index -- PostgreSQL +CREATE INDEX idx_posts_search ON posts +USING GIN(to_tsvector('english', title || ' ' || body)); + +-- JSONB index -- PostgreSQL +CREATE INDEX idx_metadata ON events USING GIN(metadata); +``` + +### 3. Query Optimization Patterns + +**Avoid SELECT \*:** + +```sql +-- Bad: Fetches unnecessary columns +SELECT * FROM users WHERE id = 123; + +-- Good: Fetch only what you need +SELECT id, email, name FROM users WHERE id = 123; +``` + +**Use WHERE Clause Efficiently:** + +```sql +-- Bad: Function prevents index usage +SELECT * FROM users WHERE LOWER(email) = 'user@example.com'; + +-- Good: Create functional index or use exact match +CREATE INDEX idx_users_email_lower ON users(LOWER(email)); +-- Then: +SELECT * FROM users WHERE LOWER(email) = 'user@example.com'; + +-- Or store normalized data +SELECT * FROM users WHERE email = 'user@example.com'; +``` + +**Optimize JOINs:** + +```sql +-- Bad: Cartesian product then filter +SELECT u.name, o.total +FROM users u, orders o +WHERE u.id = o.user_id AND u.created_at > '2024-01-01'; + +-- Good: Filter before join +SELECT u.name, o.total +FROM users u +JOIN orders o ON u.id = o.user_id +WHERE u.created_at > '2024-01-01'; + +-- Better: Filter both tables +SELECT u.name, o.total +FROM (SELECT * FROM users WHERE created_at > '2024-01-01') u +JOIN orders o ON u.id = o.user_id; +``` + +## Optimization Patterns + +### Pattern 1: Eliminate N+1 Queries + +**Problem: N+1 Query Anti-Pattern** + +```python +# Bad: Executes N+1 queries +users = db.query("SELECT * FROM users LIMIT 10") +for user in users: + orders = db.query("SELECT * FROM orders WHERE user_id = ?", user.id) + # Process orders +``` + +**Solution: Use JOINs or Batch Loading** + +```sql +-- Solution 1: JOIN +SELECT + u.id, u.name, + o.id as order_id, o.total +FROM users u +LEFT JOIN orders o ON u.id = o.user_id +WHERE u.id IN (1, 2, 3, 4, 5); + +-- Solution 2: Batch query +SELECT * FROM orders +WHERE user_id IN (1, 2, 3, 4, 5); +``` + +```python +# Good: Single query with JOIN or batch load +# Using JOIN +results = db.query(""" + SELECT u.id, u.name, o.id as order_id, o.total + FROM users u + LEFT JOIN orders o ON u.id = o.user_id + WHERE u.id IN (1, 2, 3, 4, 5) +""") + +# Or batch load +users = db.query("SELECT * FROM users LIMIT 10") +user_ids = [u.id for u in users] +orders = db.query( + "SELECT * FROM orders WHERE user_id IN (?)", + user_ids +) +# Group orders by user_id +orders_by_user = {} +for order in orders: + orders_by_user.setdefault(order.user_id, []).append(order) +``` + +### Pattern 2: Optimize Pagination + +**Bad: OFFSET on Large Tables** + +```sql +-- Slow for large offsets +SELECT * FROM users +ORDER BY created_at DESC +LIMIT 20 OFFSET 100000; -- Very slow! +``` + +**Good: Cursor-Based Pagination** + +```sql +-- Much faster: Use cursor (last seen ID) +SELECT * FROM users +WHERE created_at < '2024-01-15 10:30:00' -- Last cursor +ORDER BY created_at DESC +LIMIT 20; + +-- With composite sorting +SELECT * FROM users +WHERE (created_at, id) < ('2024-01-15 10:30:00', 12345) +ORDER BY created_at DESC, id DESC +LIMIT 20; + +-- Requires index +CREATE INDEX idx_users_cursor ON users(created_at DESC, id DESC); +``` + +### Pattern 3: Aggregate Efficiently + +**Optimize COUNT Queries:** + +```sql +-- Bad: Counts all rows +SELECT COUNT(*) FROM orders; -- Slow on large tables + +-- Good: Use estimates for approximate counts (PostgreSQL) +SELECT reltuples::bigint AS estimate +FROM pg_class +WHERE relname = 'orders'; + +-- Good: Filter before counting +SELECT COUNT(*) FROM orders +WHERE created_at > NOW() - INTERVAL '7 days'; + +-- Better: Use index-only scan +CREATE INDEX idx_orders_created ON orders(created_at); +SELECT COUNT(*) FROM orders +WHERE created_at > NOW() - INTERVAL '7 days'; +``` + +**Optimize GROUP BY:** + +```sql +-- Bad: Group by then filter +SELECT user_id, COUNT(*) as order_count +FROM orders +GROUP BY user_id +HAVING COUNT(*) > 10; + +-- Better: Filter first, then group (if possible) +SELECT user_id, COUNT(*) as order_count +FROM orders +WHERE status = 'completed' +GROUP BY user_id +HAVING COUNT(*) > 10; + +-- Best: Use covering index +CREATE INDEX idx_orders_user_status ON orders(user_id, status); +``` + +### Pattern 4: Subquery Optimization + +**Transform Correlated Subqueries:** + +```sql +-- Bad: Correlated subquery (runs for each row) +SELECT u.name, u.email, + (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) as order_count +FROM users u; + +-- Good: JOIN with aggregation +SELECT u.name, u.email, COUNT(o.id) as order_count +FROM users u +LEFT JOIN orders o ON o.user_id = u.id +GROUP BY u.id, u.name, u.email; + +-- Better: Use window functions (PostgreSQL) +SELECT DISTINCT ON (u.id) + u.name, u.email, + COUNT(o.id) OVER (PARTITION BY u.id) as order_count +FROM users u +LEFT JOIN orders o ON o.user_id = u.id; +``` + +**Use CTEs for Clarity:** + +```sql +-- Using Common Table Expressions +WITH recent_users AS ( + SELECT id, name, email + FROM users + WHERE created_at > NOW() - INTERVAL '30 days' +), +user_order_counts AS ( + SELECT user_id, COUNT(*) as order_count + FROM orders + WHERE created_at > NOW() - INTERVAL '30 days' + GROUP BY user_id +) +SELECT ru.name, ru.email, COALESCE(uoc.order_count, 0) as orders +FROM recent_users ru +LEFT JOIN user_order_counts uoc ON ru.id = uoc.user_id; +``` + +### Pattern 5: Batch Operations + +**Batch INSERT:** + +```sql +-- Bad: Multiple individual inserts +INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com'); +INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com'); +INSERT INTO users (name, email) VALUES ('Carol', 'carol@example.com'); + +-- Good: Batch insert +INSERT INTO users (name, email) VALUES + ('Alice', 'alice@example.com'), + ('Bob', 'bob@example.com'), + ('Carol', 'carol@example.com'); + +-- Better: Use COPY for bulk inserts (PostgreSQL) +COPY users (name, email) FROM '/tmp/users.csv' CSV HEADER; +``` + +**Batch UPDATE:** + +```sql +-- Bad: Update in loop +UPDATE users SET status = 'active' WHERE id = 1; +UPDATE users SET status = 'active' WHERE id = 2; +-- ... repeat for many IDs + +-- Good: Single UPDATE with IN clause +UPDATE users +SET status = 'active' +WHERE id IN (1, 2, 3, 4, 5, ...); + +-- Better: Use temporary table for large batches (PostgreSQL) +CREATE TEMP TABLE temp_user_updates (id INT, new_status VARCHAR); +INSERT INTO temp_user_updates VALUES (1, 'active'), (2, 'active'), ...; + +UPDATE users u +SET status = t.new_status +FROM temp_user_updates t +WHERE u.id = t.id; +``` + +## Advanced Techniques + +### Materialized Views (PostgreSQL) + +Pre-compute expensive queries. + +```sql +-- Create materialized view +CREATE MATERIALIZED VIEW user_order_summary AS +SELECT + u.id, + u.name, + COUNT(o.id) as total_orders, + SUM(o.total) as total_spent, + MAX(o.created_at) as last_order_date +FROM users u +LEFT JOIN orders o ON u.id = o.user_id +GROUP BY u.id, u.name; + +-- Add index to materialized view +CREATE INDEX idx_user_summary_spent ON user_order_summary(total_spent DESC); + +-- Refresh materialized view +REFRESH MATERIALIZED VIEW user_order_summary; + +-- Concurrent refresh +REFRESH MATERIALIZED VIEW CONCURRENTLY user_order_summary; + +-- Query materialized view (very fast) +SELECT * FROM user_order_summary +WHERE total_spent > 1000 +ORDER BY total_spent DESC; +``` + +### Partitioning + +Split large tables for better performance. + +```sql +-- Range partitioning by date (PostgreSQL) +CREATE TABLE orders ( + id SERIAL, + user_id INT, + total DECIMAL, + created_at TIMESTAMP +) PARTITION BY RANGE (created_at); + +-- Create partitions +CREATE TABLE orders_2024_q1 PARTITION OF orders + FOR VALUES FROM ('2024-01-01') TO ('2024-04-01'); + +CREATE TABLE orders_2024_q2 PARTITION OF orders + FOR VALUES FROM ('2024-04-01') TO ('2024-07-01'); + +-- Queries automatically use appropriate partition +SELECT * FROM orders +WHERE created_at BETWEEN '2024-02-01' AND '2024-02-28'; +-- Only scans orders_2024_q1 partition +``` + +### Query Hints and Optimization + +```sql +-- Force index usage (MySQL) +SELECT * FROM users +USE INDEX (idx_users_email) +WHERE email = 'user@example.com'; + +-- Parallel query (PostgreSQL) +SET max_parallel_workers_per_gather = 4; +SELECT * FROM large_table WHERE condition; + +-- Join hints (PostgreSQL) +SET enable_nestloop = OFF; -- Force hash or merge join +``` + +## Best Practices + +1. **Index Selectively**: Too many indexes slow down writes +2. **Monitor Query Performance**: Use slow query logs +3. **Keep Statistics Updated**: Run ANALYZE regularly +4. **Use Appropriate Data Types**: Smaller types = better performance +5. **Normalize Thoughtfully**: Balance normalization vs performance +6. **Cache Frequently Accessed Data**: Use application-level caching +7. **Connection Pooling**: Reuse database connections +8. **Regular Maintenance**: VACUUM, ANALYZE, rebuild indexes + +```sql +-- Update statistics +ANALYZE users; +ANALYZE VERBOSE orders; + +-- Vacuum (PostgreSQL) +VACUUM ANALYZE users; +VACUUM FULL users; -- Reclaim space (locks table) + +-- Reindex +REINDEX INDEX idx_users_email; +REINDEX TABLE users; +``` + +## Common Pitfalls + +- **Over-Indexing**: Each index slows down INSERT/UPDATE/DELETE +- **Unused Indexes**: Waste space and slow writes +- **Missing Indexes**: Slow queries, full table scans +- **Implicit Type Conversion**: Prevents index usage +- **OR Conditions**: Can't use indexes efficiently +- **LIKE with Leading Wildcard**: `LIKE '%abc'` can't use index +- **Function in WHERE**: Prevents index usage unless functional index exists + +## ORM-Specific Anti-Patterns + +### N+1 in ORMs (Lucid, Eloquent, ActiveRecord, Prisma) + +```typescript +// Bad: N+1 in Lucid ORM (AdonisJS) +const users = await User.all() +for (const user of users) { + const orders = await user.related('orders').query() // N queries! +} + +// Good: Eager loading +const users = await User.query().preload('orders') + +// Good: Preload with constraints +const users = await User.query().preload('orders', (query) => { + query.where('status', 'completed') +}) +``` + +### Sequential Queries in Loops + +```typescript +// Bad: Sequential queries +for (const id of userIds) { + const user = await User.find(id) // N queries! +} + +// Good: Batch fetch +const users = await User.query().whereIn('id', userIds) +``` + +### Missing Eager Loading in Nested Relations + +```typescript +// Bad: Loads posts, then N queries for each post's comments +const users = await User.query().preload('posts') +for (const post of user.posts) { + await post.load('comments') // N queries! +} + +// Good: Nested eager loading +const users = await User.query() + .preload('posts', (query) => { + query.preload('comments') + }) +``` + +## Monitoring Queries + +```sql +-- Find slow queries (PostgreSQL) +SELECT query, calls, total_time, mean_time +FROM pg_stat_statements +ORDER BY mean_time DESC +LIMIT 10; + +-- Find missing indexes (PostgreSQL) +SELECT + schemaname, + tablename, + seq_scan, + seq_tup_read, + idx_scan, + seq_tup_read / seq_scan AS avg_seq_tup_read +FROM pg_stat_user_tables +WHERE seq_scan > 0 +ORDER BY seq_tup_read DESC +LIMIT 10; + +-- Find unused indexes (PostgreSQL) +SELECT + schemaname, + tablename, + indexname, + idx_scan, + idx_tup_read, + idx_tup_fetch +FROM pg_stat_user_indexes +WHERE idx_scan = 0 +ORDER BY pg_relation_size(indexrelid) DESC; +``` + +## SQLite/libSQL-Specific Patterns + +### WAL Mode for Concurrent Reads + +```sql +-- Enable WAL mode (do once) +PRAGMA journal_mode=WAL; + +-- Check current mode +PRAGMA journal_mode; +``` + +### SQLite Index Optimization + +```sql +-- SQLite supports B-Tree indexes only +CREATE INDEX idx_users_email ON users(email); + +-- Partial indexes (SQLite 3.8.0+) +CREATE INDEX idx_active_users ON users(email) +WHERE deleted_at IS NULL; + +-- Expression indexes (SQLite 3.9.0+) +CREATE INDEX idx_users_lower_email ON users(LOWER(email)); + +-- Analyze tables for query planner +ANALYZE; +``` + +### SQLite-Compatible Alternatives + +```sql +-- No ILIKE in SQLite — use LOWER() + LIKE +SELECT * FROM users +WHERE LOWER(name) LIKE '%' || LOWER(?) || '%'; + +-- No INTERVAL — use datetime functions +SELECT * FROM users +WHERE created_at > datetime('now', '-30 days'); + +-- No DISTINCT ON — use GROUP BY or window functions +SELECT * FROM users +GROUP BY email +HAVING id = MIN(id); +``` diff --git a/templates/CLAUDE-BASE.md b/templates/CLAUDE-BASE.md index 43db73c..dc250c6 100644 --- a/templates/CLAUDE-BASE.md +++ b/templates/CLAUDE-BASE.md @@ -23,9 +23,10 @@ | 5. TEST | `{{TEST_COMMAND}}` + `{{TYPECHECK_COMMAND}}` | — | Zero failures | | 6. SIMPLIFY | `Task(subagent_type="code-simplifier")` | `code-simplifier` agent | Staff review complete | | 7. CODE REVIEW | `Task(subagent_type="superpowers:code-reviewer")` | Fresh sub-agent | Reviewer approves | -| 8. COMMIT | `git commit` | — | Commit created | -| 9. PUSH | Push feature branch, `gh pr create` with `Closes #N` | — | PR created | -| 10. VERIFY CI | `gh run list`, autonomous PR review, auto-merge when green | — | CI green, merged | +| 8. SQL REVIEW | `Task(subagent_type="superpowers:code-reviewer")` with SQL audit prompt | `sql-optimization-patterns` skill + `sql-reviewer` agent | Reviewer approves | +| 9. COMMIT | `git commit` | — | Commit created | +| 10. PUSH | Push feature branch; `gh pr create` with `Closes #N` if `gh` available | — | Branch pushed (PR created if `gh`) | +| 11. VERIFY CI | If `gh`: `gh run list`, autonomous PR review, auto-merge when green | — | CI green (if applicable) | **Exceptions that skip planning:** pure doc updates, `git revert`. @@ -33,7 +34,7 @@ **All phases are MANDATORY. No exceptions. No skipping "simple" changes.** -- **Phases 3, 6, 7** MUST use `Task` tool (fresh sub-agent, no shared context) +- **Phases 3, 6, 7, 8** MUST use `Task` tool (fresh sub-agent, no shared context) - NEVER review your own plan or code — you wrote it, you cannot objectively review it - If reviewer finds CRITICAL/IMPORTANT issues: fix, re-run tests, re-review - Only proceed after explicit reviewer approval @@ -52,34 +53,71 @@ Task(subagent_type="superpowers:code-reviewer", prompt=" - Only implement APPROVED simplifications - Re-run tests after applying changes +**SQL review rules:** +- Run after code review passes (Phase 7), before commit (Phase 9) +- Dispatch a fresh Staff Engineer sub-agent using the `sql-reviewer` agent template +- The reviewer audits ALL database queries, mutations, and ORM usage for: **performance**, **security**, and **defensive coding** +- CRITICAL findings MUST be fixed. Re-run tests after fixes, then re-run SQL review +- IMPORTANT findings: fix if possible, otherwise open a GitHub issue immediately +- Max 3 review cycles before escalating to user + **Pre-existing issues found during review:** - If reviewer flags a pre-existing issue in code you're touching, **fix it** — you own that code path - Only exception: issue is in completely unrelated code your changes don't touch -**Unaddressed work MUST become GitHub issues:** -- Any improvement, follow-up, or deferred fix identified during work (code simplifier suggestions, reviewer findings, TODOs) that is NOT addressed in the current PR MUST be filed as a GitHub issue +**Unaddressed work MUST be tracked:** +- Any improvement, follow-up, or deferred fix identified during work (code simplifier suggestions, reviewer findings, TODOs) that is NOT addressed in the current branch MUST be tracked +- If `gh` is available: file as a GitHub issue. Otherwise: add to the todo list or note in a `TODO.md` - This includes: approved simplifications deferred to a follow-up, pre-existing issues in unrelated code, scope-expanding suggestions - Never silently drop findings — if you're not fixing it now, track it --- -## GitHub Workflow +## Branching and Sub-Agents + +### Branch Protection + +- **Never commit to main.** All changes go through feature branches (and PRs when `gh` is available). +- Branch naming: `/` (e.g., `feat/user-profiles`, `fix/login-redirect`) + +### Sub-Agent Workflow + +**The orchestrating agent NEVER writes code.** It coordinates: +- Branch management, plan management, task dispatch, and (optionally) PR creation +- Every implementation task gets a fresh sub-agent pointed at the feature branch +- Use `superpowers:subagent-driven-development` (preferred) or `superpowers:executing-plans` +- Independent tasks can run in parallel via `superpowers:dispatching-parallel-agents` + +**How it works (without worktrees):** + +1. Create a feature branch from main: `git checkout -b /` +2. Dispatch sub-agents to implement tasks on the current branch +3. Sub-agents write code, run tests, and commit to the feature branch +4. After all tasks complete, push the branch and create a PR (if `gh` is available) + +Sub-agents work in the current working directory on the active feature branch. No worktrees are needed — the orchestrator simply checks out the feature branch and dispatches work. + +### PRs (when `gh` is available) + +- Use `Closes #N` (not Fixes/Resolves) in PR body to auto-close issues +- Include `Refs #N` in commit message bodies + +--- + +## GitHub Workflow (Optional — Beta) + +> **Beta:** This workflow is highly opinionated and requires the [GitHub CLI (`gh`)](https://cli.github.com/) installed, authenticated, and `/project:init` run before use. It adds structured issue tracking, git worktrees, project board management, and autonomous PR review on top of the base sub-agent workflow. **It is not required to use the plugin.** Read the README thoroughly before enabling. ### Prerequisites - **Initialization required** before ANY GitHub write (issues, PRs, labels): run `/project:init` - Check: `gh label list --json name --jq '.[].name' | grep -q '^claude:initialized$'` -- If not initialized: block GitHub writes, allow local work (branches, commits, worktrees) +- If not initialized: block GitHub writes, allow local work (branches, commits) - **Graceful degradation**: if `gh` unavailable (`gh auth status 2>/dev/null`), skip all GitHub integration and continue normally. Never block work. -### Branch Protection - -- **Never commit to main.** All changes go through PRs. -- Branch naming: `/` (e.g., `feat/user-profiles`, `fix/login-redirect`) - ### Git Worktrees -Every feature branch gets its own worktree: +When the GitHub workflow is active, every feature branch gets its own worktree for full isolation: ```bash REPO_NAME=$(basename "$(git rev-parse --show-toplevel)") @@ -91,6 +129,7 @@ git worktree remove "../worktrees/$REPO_NAME/" - If worktree/branch already exists, reuse it (omit `-b` for existing branch) - Monorepo: use `~/worktrees//` to avoid parent repo tracking +- Sub-agents receive the worktree path and work there instead of the main working directory ### Issues @@ -101,11 +140,6 @@ git worktree remove "../worktrees/$REPO_NAME/" - **Epics**: parent issues labeled `epic` grouping task sub-issues. Create with `/project:plan-feature`. - **Issues must be actionable.** When referencing code, always include specific file paths and line numbers. If a pattern repeats in N locations, list every location. An engineer should be able to start working from the issue alone without searching the codebase. -### PRs - -- Use `Closes #N` (not Fixes/Resolves) in PR body to auto-close issues -- Include `Refs #N` in commit message bodies - ### Autonomous PR Review (Default) After every PR is created, automatically: @@ -117,12 +151,12 @@ After every PR is created, automatically: 5. When CI passes: merge, cleanup, and pull: ```bash gh pr merge --squash --delete-branch # merges + deletes remote branch - git worktree remove # removes local worktree + git worktree remove # removes local worktree (if used) git branch -d # deletes local branch git pull # updates main ``` -**Auto-merge is mandatory when CI is green.** Do not ask for user confirmation. Post-merge cleanup (worktree + local branch deletion + pull) is also mandatory — never leave stale worktrees or branches. +**Auto-merge is mandatory when CI is green.** Do not ask for user confirmation. Post-merge cleanup (branch deletion + pull) is also mandatory — never leave stale branches. **Safety limits:** Max 3 review cycles, max 3 CI fixes. Never merge with failing CI or unresolved Critical findings. @@ -130,17 +164,9 @@ After every PR is created, automatically: - Columns: Todo → In Progress → Done - Move to "In Progress" when implementation starts (Phase 4) -- Move to "Done" after PR merged and worktree cleaned +- Move to "Done" after PR merged and cleaned up - Use `gh project item-edit` with `--jq` for filtering (no external `jq`) -### Sub-Agents - -**The orchestrating agent NEVER writes code.** It coordinates: -- Worktree/issue/plan management, task dispatch, PR creation -- Every implementation task gets a fresh sub-agent with the worktree path -- Use `superpowers:subagent-driven-development` (preferred) or `superpowers:executing-plans` -- Independent tasks can run in parallel via `superpowers:dispatching-parallel-agents` - ### Slash Commands - `/project:init` — **Run first.** Creates board + labels @@ -156,6 +182,7 @@ After every PR is created, automatically: |---------|-------| | Bug investigation | `systematic-debugging` | | New feature | `superpowers:test-driven-development` (RED→GREEN→REFACTOR) | +| Database queries/mutations changed | `sql-optimization-patterns` + `sql-reviewer` agent | | About to claim completion | `verification-before-completion` | ---