[Debugging] Use when analyzing or optimizing performance bottlenecks: database queries, N+1 fan-out, indexing, API latency, memory, concurrency, algorithmic complexity (O(n²)), frontend rendering, caching, and distributed paths.
[IMPORTANT] MANDATORY MUST ATTENTION stay project-generic: discover local stack, conventions, query APIs, index definitions, metrics, and report paths before judging.
[IMPORTANT] MANDATORY MUST ATTENTION prove every performance claim with measurement or static evidence: file:line, query text/shape, row counts, query plan/explain output, trace, profile, or logs.
[IMPORTANT] MANDATORY MUST ATTENTION review performance one dimension at a time: over-fetching, filters, indexes, N+1 fan-out, batching, aggregation/join shape, materialization, writes, caching, in-process compute/algorithmic complexity, concurrency/pool saturation.
[IMPORTANT] MANDATORY MUST ATTENTION include in-process compute, not just I/O: flag O(n²)+ nested scans, linear membership lookups inside loops, ReDoS-prone regex, and per-iteration serialize/clone — CPU bottlenecks need the same evidence rigor as queries.
[IMPORTANT] MANDATORY MUST ATTENTION when an operation is fast but p95/p99 is high, suspect saturation not the query: measure pool/thread acquire-wait and queue depth, and size pools by Little's Law (in-use = arrival-rate × hold-time) × replica count.
Critical Thinking Mindset — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
Anti-hallucination: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
AI Mistake Prevention — Failure modes to avoid on every task:
Re-read files after context changes. Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
Verify generated content against source evidence. AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
Check downstream references before deleting or renaming. Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
Trace the full impact chain after edits. Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
Verify ALL affected outputs, not just the first. One green check is not all green checks; validate every output surface the change can affect.
Assume existing values are intentional — ask WHY before changing. Before changing a constant, limit, flag, wording, or pattern, read nearby context and history.
Surface ambiguity before acting — don't pick silently. Multiple valid interpretations require an explicit question or stated assumption with risk.
Keep shared guidance role-relevant. Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
[BLOCKING] Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.
[BLOCKING] Before each step/sub-skill call, update task tracking: set in_progress when step starts, completed when step ends.
[BLOCKING] Every completed/skipped step MUST include brief evidence or explicit skip reason.
[BLOCKING] If task tools unavailable, maintain equivalent step-by-step tracker with synchronized statuses.
Quick Summary
Goal: Ensure every shipped performance fix removes a measured (or static-risk-labeled) real bottleneck — across database waste (rows/columns, missing/unused indexes, query-in-loop fan-out, unbounded materialization, slow joins/aggregations, write amplification), in-process compute (O(n²) scans, wrong data structures, ReDoS, serialize/clone churn), and concurrency saturation (pool/queue acquire-wait sized by Little's Law) — while preserving behavior, authorization, and semantics, proven by before/after evidence, validated via /why-review before any fix, and confirmed by a clean full Phase-0 re-review — never a guess-driven change that hides waste or breaks correctness.
Summary:
Evidence is the gate, not intuition: capture a runtime baseline (query plan/explain, row counts, p95/p99, pool acquire-wait, microbench at worst-case N) or label the finding static risk with the exact verify command — never recommend below 60% confidence.
Walk dimensions ONE pass at a time (query shape → index/access path → N+1 → aggregation/join → materialization → write/locks → cache → API/distributed/frontend → compute/algorithmic), never all at once; reduce rows at the source before trimming columns or caching, and size pools by Little's Law (replica count × per-instance pool) when a fast op shows high p99.
No finding is fixable until /why-review --validate-findings confirms it (Phase 6); each validated fix then restarts the FULL review from Phase 0 over the whole target (Phase 7) — a targeted before/after check alone never earns a PASS.
Renamed: formerly /performance — that name no longer resolves as a slash command; use /performance-review.
Workflow:
Detect - Classify scope and bottleneck type.
Discover - Read local code, metrics, docs, query/index definitions, similar patterns.
Measure - Capture baseline or mark static-only risk.
Analyze - Run serial dimension passes with evidence.
Plan - Propose smallest fix preserving behavior.
Verify - Re-measure, run tests, and record evidence.
Validate Findings - Run /why-review --validate-findings <report-path> before any fix.
Fix + Full Re-Review - Fix only validated findings, then restart from Detect over the full target.
MANDATORY ALWAYS push row filters to data source before projection/caching; row-count reduction beats column trimming.
MANDATORY ALWAYS verify index usability with query shape/order, not index existence alone.
NEVER recommend caching until query shape, indexes, pagination, batching, and data volume are understood.
Findings are not eligible for fix until /why-review --validate-findings confirms them; every validated fix restarts the full performance review from Phase 0.
$ARGUMENTS
Phase 0: Detect Scope
Classify before analysis. Detection drives dimensions, evidence, sub-agent choice.
Scope
Signals
Primary evidence
DB read
slow query, full scan, sort spill, high rows examined
hot loop, nested iteration, quadratic scaling, regex stall, heavy serialize/clone
input N, operation count vs N, profiler/flame-graph sample, microbench
Skip reason allowed only when target explicitly narrows scope and evidence proves dimension irrelevant.
Architecture-Altitude Performance Review
When to apply: design/architecture reviews (e.g. via the architect agent) — judging performance as a structural property of the designbefore it ships, not a tactical query fix after a bottleneck is observed. The dimension passes below stay the tool for tactical work; this section is the design-level lens layered on top.
Evaluate the bottleneck layer model as a design concern, not just a symptom site:
Performance as architecture
├── Database — data access shape baked into the model (projection, paging, N+1 surface, index strategy)
├── API — serialization/processing cost, parallel tuple queries, response-DTO contracts
├── Network — payload size & call-count designed into the contract (batch endpoints vs chatty waterfalls)
├── Frontend — bundle/lazy-load topology, OnPush/track-by/virtual-scroll as default architecture
└── Background jobs — bounded parallelism (`ParallelAsync` with `maxConcurrent`) + batch (`UpdateManyAsync`) as the shape, not an afterthought
Architecture-altitude rules (decide at design time — cheapest to fix here):
Bound every result set and project only needed columns/fields in the contract itself — never design an unbounded read-all or SELECT * endpoint; unbounded reads spike memory and latency under real data volume.
Design out N+1 at the boundary — eager-load / batch-fetch is the default access pattern; per-item lookups are a design smell, not a tuning detail.
Caching is a design decision, not a patch — choose request-scope memoization vs bounded shared cache up front, with key dimensions (tenant/user/auth/version), TTL/invalidation, size limits, and privacy constraints specified; never cache to hide an unbounded query.
Async I/O is structural — never design a path that blocks threads with .Result; bounded parallelism for fan-out work is part of the design, with a fresh safe scope/context per worker.
Make the cost visible — design slow-operation logging and query logging in from the start so regressions are observable in production.
Size pools and parallelism, never default them — derive connection/thread/permit pool size from Little's Law (in-use = arrival-rate × hold-time) and state the assumptions; shrink hold-time (release the resource across non-DB / external-wait spans) before growing the pool; size a shared backend against fleet-aggregate demand (replica count × per-instance pool), not one instance — local per-instance tuning becomes a thundering herd on the shared dependency.
For database index strategy at design time, see the database-optimization skill (composite key order, covering/partial indexes, write-cost analysis). The tactical evidence gate (measure baseline, prove with plan/explain) in the phases below still applies to every recommendation made at this altitude.
Phase 1: Discover Local Context
MANDATORY discovery before findings (MUST ATTENTION):
search 3+ similar local query/API patterns before proposing a fix.
read target code and index/migration/schema files controlling the queried data.
map callers and frequency using available graph/call-trace/profiler tools; if none exist, use grep/import/call hierarchy. When .code-graph/graph.db exists, run a graph blast-radius pass (trace --direction downstream on the hot path) to size the fan-out before proposing a fix — see the Graph-Assisted Investigation gate below.
identify data shape: tenant/security-review filters, cardinality, expected max rows, selected columns/fields, sort, joins, aggregation/grouping, cache keys.
NEVER hardcode project names, repository paths, ID formats, DB engines, ORMs, or framework defaults; derive from discovered files.
Phase 2: Baseline Evidence
Prefer runtime proof. If unavailable, label finding static risk and include exact command/query needed to verify.
MANDATORY baseline for DB findings:
ALWAYS capture query source: file:line and generated SQL/query/ORM expression when available
ALWAYS capture resource hold-time vs total request time (a connection/lock/permit is held only for the fraction it is actually used, not the whole request)
ALWAYS capture pool state: size, active/idle/pending, and acquire-wait time / queue depth at the pool entrance
ALWAYS capture aggregate demand on shared dependencies: replica count × per-instance pool → total connections/cores the shared backend must serve
Confidence:
Confidence
Action
95%+
Recommend fix freely.
80-94%
Recommend with caveats and verification command.
60-79%
List unknowns first; gather more evidence before fix.
<60%
STOP. Do not recommend.
Phase 3: Serial Dimension Passes
MANDATORY apply one focused pass per dimension. NEVER scan all dimensions at once.
1. Query Shape And Data Minimization
Think: Which rows/columns load? Are filters, projection, sorting, and limits executed by data source before materialization?
MUST ATTENTION find:
unbounded list/read-all APIs without page, limit, cursor, or bounded business invariant
filter after materialization (ToList/array/load-all before Where/filter)
projection after materialization; full entity/document loaded for list/summary view
unused includes/joins/lookup data; large text/blob/json fields in list queries
client-side sort/group/distinct; offset pagination on very deep pages where cursor/keyset fits better
missing tenant/auth/status/date filters in hot-path queries
Prefer fixes: push predicates to data source, select only needed fields, bound result set, use cursor/keyset for deep sequential access, keep reusable predicates near domain/query-owner layer discovered locally.
2. Index And Access Path
Think: Can existing indexes satisfy equality/range filters, joins, sort, grouping, and projection in the actual query order?
Find:
no index for high-cardinality filters, joins, foreign keys, sort columns, or frequent group keys
composite index field order mismatched with equality -> range -> sort access pattern
index exists but plan ignores it because query wraps field in function/cast, uses incompatible type/collation, leading wildcard, broad OR, negative predicate, or low selectivity
sort spill/filesort because index order does not match filter + order by
covering/partial/filtered index opportunity for hot narrow query
index bloat from adding every field without write-cost analysis
Prefer fixes: add/adjust smallest useful index, reorder composite keys to match query, rewrite predicate to be sargable, verify with plan/explain before/after, include write-cost risk.
3. N+1 And Fan-Out
Think: Does work scale with item count instead of request/job count?
blob/file/large JSON fields loaded for lightweight responses
buffering entire export/report when streaming/chunking fits
accidental multiple enumeration re-running query
Prefer fixes: page/chunk/stream, use no-tracking/read-only mode when local stack supports it, project lightweight DTOs, move filter before load, memoize intentionally.
6. Write Path, Locks, And Transactions
Think: Does write work batch safely and keep locks/transactions small?
Find:
per-row save/update/delete inside loop
long transaction wrapping remote calls or heavy reads
unnecessary unique checks per row instead of bulk validation
lock escalation/hot-row contention/counter updates without batching
Prefer fixes: batch API, reduce payload, add backpressure, virtualize large lists, stabilize render keys, lazy-load cold assets/routes, measure browser/network trace.
9. Compute And Algorithmic Complexity
Think: Does in-process work grow super-linearly with input size, independent of any query or network call?
MUST ATTENTION find:
nested iteration over the same/related collection (O(n²)+): loop-in-loop, map inside map, repeated full re-scan
linear membership/lookup inside a loop — .find/.includes/.indexOf/in list/.contains where a Set/Map/dict gives O(1)
wrong data structure for the access pattern: array used as a keyed store; repeated .filter().length for existence
string built by concatenation in a loop; repeated JSON.parse/stringify/deep-clone/serialize per iteration
catastrophic-backtracking regex on user- or attacker-sized input (ReDoS — cross-link /security-review)
pure-CPU result recomputed every call when inputs are stable (memoization candidate, distinct from data cache)
redundant sort/re-sort, or sorting when a single-pass min/max/partition suffices
Prefer fixes: build a Set/Map/dict index once and look up in O(1); hoist invariant work out of the loop; accumulate into an array + single join instead of +=; precompute/memoize stable pure results; anchor/bound regex and cap input length; pick the data structure that matches the access pattern. Prove with a microbench/profiler sample at representative AND worst-case N — never reasoning alone.
preserve functional behavior, authorization, ordering, pagination semantics, consistency, and idempotency.
inspect affected tests/specs/docs when behavior, SLA, public contract, or limits change.
NEVER change query semantics only to improve speed unless user approves changed behavior.
NEVER add broad indexes/caches without write-cost, storage-cost, invalidation, and privacy analysis.
Spec-Loop Discipline (Dual-Feedback half — tailored). Performance is orthogonal to functional correctness, so the property/metamorphic generation and the MUTATION-SCORE assertion gate are scoped to functional core-logic and do NOT apply here — N/A. Apply only the dual-feedback half: when a finding establishes or moves a behavior-defining boundary — an SLA/latency budget (p95/p99 target), a result-set bound, a max-rows/page-size limit, a pool-size assumption — feed it BOTH (a) the spec — record the SLA/limit as a §5 invariant / documented constraint so the budget is intended contract, not an undocumented tuning value — AND (b) a guarding test — a benchmark/assertion that fails when the budget or bound regresses. A fix that improves the number but leaves the boundary undocumented OR unguarded is INCOMPLETE, never a code-only change.
Sub-Agent Routing
Use specialized help when available:
Detected focus
Sub-agent
DB/query/N+1/memory/backend hot path
performance-optimizer
Auth, PII, tenant isolation, sensitive cache keys
security-auditor first, then performance-optimizer
Sub-agent prompt MUST include target, detected scope, local context evidence, required dimensions, report path, and "return summary only; write full report incrementally."
Phase 6: Why-Review Findings Validation Gate (MANDATORY when findings exist)
Purpose: Validate performance findings before optimization work. Performance reports are easy to overstate when evidence is static-only, a plan lacks production-like scale, or a proposed index/cache changes write cost or data freshness risk.
Trigger: Any performance finding or optimization recommendation (Critical, High, Medium, Low, WARN, or static risk). Skip ONLY when the report's verdict is unconditional PASS with literally zero findings.
Protocol:
Read own finalized report from plans/reports/performance-{date}-{slug}.md or the exact report path written by the caller.
Read the validation verdict path returned by why-review, expected as plans/reports/why-review-validate-{date}.md.
If why-review demotes/removes any finding: update the performance report with revised severity, removed false positives, and a ## Why-Review Validation Notes section.
If why-review confirms all findings: append ## Why-Review Validation stating all findings were re-validated against measurement/static evidence.
If the report changed after validation: re-run this validation gate, maximum 2 validation passes, until the report's remaining findings are validated or zero findings remain.
Skip conditions (record explicit reason if skipping):
Verdict is unconditional PASS with zero findings.
Why-review skill itself is the active context.
Phase 7: Validated Fix + Full Performance Re-Review Loop (MANDATORY when validated findings remain)
Trigger: Phase 6 returns CLEAN/validated and the performance report still has one or more findings that must be fixed.
Protocol:
Create a fresh fix-cycle task list before editing. Do not reuse the review tasks.
Fix only findings that survived /why-review --validate-findings; if this skill is running inside a workflow, route implementation through the parent /plan + /feature-implement flow.
Re-measure or run the verification command named in the finding.
Restart the full /performance-review review from Phase 0 over the complete current target, not only the fixed files.
The restarted pass MUST create brand-new review tasks, re-detect scope, rediscover local context, rerun baseline/graph/profiler checks where applicable, and analyze all dimensions again from the beginning.
Repeat validate → fix → full performance re-review until a complete pass has zero findings.
If the same validated blocker repeats across 3 full invocations with no progress, stop and ask the user for a decision.
Non-negotiable rules:
Never fix a performance finding before /why-review --validate-findings validates it.
Never mark performance review clean after a targeted before/after check only; the clean verdict must come from a full Phase 0 restart.
Never review only fixed files during the recursive pass.
Never reuse old todo/task items for the recursive review pass.
Output
MANDATORY final report sections:
Scope and detected bottleneck type
Baseline evidence and unknowns
Findings ordered by severity
Optimization plan and rejected alternatives
Verification plan with before/after metrics
Test/spec/doc impact or explicit skip reason
Confidence and assumptions
If evidence insufficient, output: Insufficient evidence. Verified: [...]. Not verified: [...]. Next evidence needed: [...].
Graph-Assisted Investigation — MANDATORY when .code-graph/graph.db exists.
HARD-GATE: MUST ATTENTION run at least ONE graph command on key files before concluding any investigation.
Pattern: Grep finds files → trace --direction both reveals full system flow → Grep verifies details
Task
Minimum Graph Action
Investigation/Scout
trace --direction both on 2-3 entry files
Fix/Debug
callers_of on buggy function + tests_for
Feature/Enhancement
connections on files to be modified
Code Review
tests_for on changed functions
Blast Radius
trace --direction downstream
CLI:python .claude/scripts/code_graph {command} --json. Use --node-mode file first (10-30x less noise), then --node-mode function for detail.
Severity Rubric — Classify every finding by consequence, not by how easy it is to fix. One scale across all reviews so a "High" means the same thing everywhere.
Severity
Action
Definition
CRITICAL
Block merge
Silent runtime failure, data corruption, validation bypass, security hole
Score-based skills map their numeric scale onto these tiers — do not invent a parallel vocabulary:
0-2 criterion scoring (e.g. production-readiness-review): 0 = CRITICAL/HIGH (criterion unmet, blocks production readiness), 1 = MEDIUM (partial, should fix), 2 = pass (no finding).
Two-axis scoring (e.g. performance-review, impact × likelihood): map the resulting cell to the nearest tier — high-impact + high-likelihood → CRITICAL/HIGH; low-impact OR low-likelihood → MEDIUM/LOW.
A finding's tier drives the gate: CRITICAL/HIGH must be resolved or explicitly accepted by the owner before PASS; MEDIUM/LOW may ship with a tracked follow-up.
Category Review Thinking — A thinking framework for reviewing any category of changed files. NOT a fixed checklist — derive concerns from domain knowledge; the examples are starting points only. Your knowledge of the category exceeds any list here — trust it.
Step 1 — Understand the category's role. What is this category responsible for in the overall system? What invariants must it uphold? What are its consumer contracts (who depends on it, what do they expect)?
Step 2 — Read project conventions for this category. Search for reference docs, style guides, ADRs, or READMEs specific to this area. Grep 3+ existing similar files — extract naming conventions, structural patterns, shared base classes. If no docs exist, derive conventions empirically from existing code.
Step 3 — Derive concerns from first principles. Apply all that are relevant; expand beyond this list based on the actual category:
Correctness: Does the logic match the intent? Trace happy path AND error path.
Boundary contracts: Are interfaces/APIs/events/protocols honored? No implicit coupling introduced?
Project conventions: Does new code follow the patterns found in Step 2? Evidence-confirmed, not assumed.
Security: Auth enforced at every entry point? Input validated at boundaries? No secrets in the diff?
Maintainability: DRY? Single responsibility? Complexity within reason? Names reveal intent?
Test coverage: Are the changed paths covered by tests? Are existing tests still valid after the change?
Documentation: Do related docs, specs, or READMEs reflect the changes?
Step 4 — Create sub-tasks and execute. For each identified concern: create a TaskCreate sub-task, work through it with file:line evidence, mark done. No findings without proof.
Illustrative concern examples by category type (not exhaustive — trust your knowledge beyond this):
Client-side logic: component lifecycle management, resource cleanup (subscriptions, listeners, timers), state management patterns, API integration layer separation, reactive stream composition
Data/Schema: migration reversibility (rollback script), lock impact on table volume, backfill idempotency, index coverage for query patterns, deployment ordering
Configuration: present in ALL environments? No secrets in diff? App fails fast if config missing (not silently null)? Documented in setup guide?
Infrastructure: dev/prod parity? No hardcoded dev values (localhost, debug flags)? Pinned image/dependency versions? CI/CD secret requirements documented?
Styles/Assets: follows project naming conventions? Uses design variables/tokens (no hardcoded magic values)? Correct scope (no global side effects from component styles)?
Documentation: accurate? Links valid? Examples still match current code/behavior? Covers new scenarios?
Tests: assertions verify specific outcomes (not just "no exception")? Idempotent (repeatable N times)? Covers edge cases, not just happy path?
Security artifacts: all code paths reach the gate? Negative tests exist (unauthorized denied)? Both enforcement AND display control updated?
Build/Tooling: rule changes apply consistently? No exceptions that silently swallow violations? Impact on CI runtime documented?
MANDATORY Large changeset → batch by size cap (≤8 files OR ≤2000 diff-lines), one parallel sub-agent per batch; never review many files one-by-one.
MANDATORY > 6 categories OR > 40 files → add the hierarchical synthesis tier; each concern-synthesizer emits cross-concern interaction candidates and the orchestrator runs the cross-concern pass before concluding.
MANDATORY Classify findings Critical/High/Medium/Low by consequence; Critical/High block PASS until fixed or owner-accepted.
MANDATORY Score-based skills (sre 0-2, perf two-axis) map onto the same four tiers — no parallel severity vocabulary.
MANDATORY Derive review categories from file language + directory semantics + change nature; create a sub-task per category.
MANDATORY Derive each category's concerns from first principles with file:line evidence — never a fixed checklist.
Closing Reminders
IMPORTANT MUST ATTENTION Goal: Ensure every shipped performance fix removes a measured (or static-risk-labeled) bottleneck while preserving behavior, authorization, and semantics — proven by before/after evidence, validated via /why-review before any fix, and confirmed by a clean full Phase-0 re-review — never a guess-driven change that hides waste or breaks correctness.
Protocols in force (concise digest of the SYNC/shared blocks this skill carries):
Critical Thinking: Traced file:line proof per claim; NEVER present a guess as fact.
AI Mistake Prevention: verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
Graph-Assisted Investigation: ALWAYS run a graph trace on key files when graph.db exists.
Severity Rubric: Classify by consequence; Critical/High block PASS until resolved.
Category Review Thinking: Derive per-category concerns from first principles, NEVER a fixed checklist.
Systematic Batching: Large changeset → size-capped parallel batches, then reduce.
IMPORTANT MUST ATTENTION prove every performance claim with measurement or static evidence — file:line, query text/shape, row counts, query plan/explain, trace, profile, or logs; confidence >80% to act, 60-79% gather more, <60% STOP — why: a number without a measured baseline is a guess that ships unverified waste.
IMPORTANT MUST ATTENTION review performance one dimension at a time — over-fetching, filters, indexes, N+1 fan-out, batching, aggregation/join shape, materialization, writes, caching, in-process compute/algorithmic complexity, concurrency/pool saturation — why: split attention misses violations.
MANDATORY search 3+ similar local query/API patterns before proposing a fix, and read the index/migration/schema files controlling the data — why: local conventions override generic framework defaults; the closest example must match preconditions (base class, scope, cardinality) before you copy it.
MANDATORY ALWAYS measure before/after; static review findings need an explicit verification command attached.
MANDATORY ALWAYS verify index usability with actual query shape/order and plan/explain — index existence alone is not proof.
IMPORTANT MANDATORY MUST ATTENTION ALWAYS push row filters to the data source before projection/caching; row-count reduction beats column trimming — why: fewer columns from too many rows still scans the rows.
MANDATORY size pools/parallelism by Little's Law (in-use = arrival-rate × hold-time) × replica count, and shrink hold-time before growing the pool — why: a fast op with high p99 is saturation at the pool entrance, not a slow query.
MANDATORY Break work into small tracked tasks before starting; one in_progress at a time; mark each completed immediately after its evidence lands — why: compaction wipes memory and untracked review scope silently goes uncovered.
MANDATORY when a finding moves a behavior-defining boundary (SLA/p95 budget, result-set bound, page-size limit, pool-size assumption), feed it BOTH the spec (record as a §5 invariant) AND a guarding test/benchmark — why: a faster number left undocumented OR unguarded regresses silently.
MANDATORY add a final review task checking doc/test/spec staleness.
Anti-Rationalization:
Evasion
Rebuttal
"Bottleneck obvious, skip baseline"
No measurement = guess. Capture metric or label static risk with the verify command.
"Index exists, so query fine"
Show plan/explain and access path. Existing unused index proves nothing.
"Projection enough"
First reduce rows. Loading fewer columns from too many rows still wastes work.
Trace loops, serializers, resolvers, consumers, and retries. Fan-out often hides upstream.
"Loop is fine, the list is small"
Show N and worst-case N. O(n²) that's fine at 10 melts at 10k. Bench at real scale.
"Query is fast, so the endpoint is fast"
Measure pool acquire-wait and queue depth. A 2ms query behind a saturated pool still yields a 200ms p99 — the wait is at the pool entrance, not in the query.
"Found one similar pattern, good enough"
Grep 3+ and verify preconditions match. One nearby example ≠ a fit; cite file:line.
"Fix it where it errors/spikes"
Trace caller (wrong data) vs callee (wrong handling); fix at the layer owning the invariant, not the symptom site.
"Validated nothing, just fix the obvious one"
No fix until /why-review --validate-findings confirms it; then restart the FULL review from Phase 0.
[TASK-PLANNING] Break work into small tracked tasks before starting; update each status immediately.
IMPORTANT MUST ATTENTION prove every claim with measurement/static evidence + file:line (confidence >80% to act, <60% STOP).
IMPORTANT MUST ATTENTION push row filters to the data source before projection/caching; verify index usability via plan/explain, never existence alone.
IMPORTANT MUST ATTENTION no fix before /why-review --validate-findings; after every validated fix restart the full review from Phase 0 before claiming PASS.
Systematic Review Batching (map-reduce) — When a changeset is large, do NOT review files one-by-one. Partition into size-capped batches, fire one specialized sub-agent per batch in parallel, then reduce. This bounds EVERY context — each batch agent AND the orchestrator — so coverage stays complete as file count grows.
Trigger ladder (one ordered escalation — not competing thresholds):
categories > 6 OR files > 40 → additionally insert the hierarchical synthesis tier (below). Everything from rung 2 still applies.
Step 1 — Categorize. Group changed files into logical categories derived from the project's actual structure (not forced). Category is the concern axis; orient with these examples, derive what fits the repository:
Category Type
Example Groupings
Agent/Tooling
AI scripts, hooks, skill definitions, workflow configs, linting rules
Service/handler/controller source (infer from project structure)
Frontend logic
UI component/state/API source (infer from project structure)
Data/Schema
Migrations, schema files, seed data
Tests
Unit, integration, E2E test files
Infrastructure
Docker, k8s, CI/CD, cloud manifests
Step 2 — Size-capped batches. One sub-agent per batch of ≤8 files OR ≤2000 diff-lines, whichever hits first. Category stays the concern axis, but any category exceeding a cap splits into multiple size-capped batches (30 backend files → 4 batches). Size caps — not category caps — make "many files" safe: a category cap alone lets one giant category blow a single agent's context.
Step 2a — Sub-agent type per batch (match the batch's dominant concern):
Docs, plans, specs, configs, infra → general-purpose
Each batch sub-agent receives: its full file list; SYNC:category-review-thinking as its primary thinking model — derive each category's concerns from first principles, NOT a fixed checklist (if the consuming skill does not carry that block, apply category-first thinking directly); project reference docs relevant to its concern (discover via *patterns*, *conventions*, *style-guide*); cross-reference verification instructions (counts, tables, links). All batch agents run in parallel and write findings to plans/reports/ (per SYNC:task-tracking-external-report); reducers read from disk, never from memory.
Step 3 — Reduce.
Flat reduction (rung 2, ≤6 categories AND ≤40 files): the orchestrator collects each batch report, cross-references counts/tables/contracts ACROSS batches, detects gaps visible only across categories (feature in code but missing from docs; new API endpoint with no client call), and consolidates into one categorized holistic report.
Hierarchical reduction (rung 3, > 6 categories OR > 40 files): insert a mid-tier — each concern gets ONE synthesizer agent that reads only its own batch reports and emits a single concern-synthesis. The orchestrator reads the concern-syntheses (~5), never the raw batch reports — keeping the reducer's context O(#concerns), not O(#files).
Cross-concern interaction pass (mandatory at rung 3 — closes the synthesis-tier blind spot): concern-siloed synthesis can drop an interaction spanning two concerns AND two batches (tainted source in data-layer/batch 7 → sink in api/batch 3). So: (a) each concern-synthesizer MUST emit an explicit "cross-concern interaction candidates" list — entities/symbols/contracts it touched that plausibly bind to another concern (shared DTOs, event names, table/collection names, exported symbols); (b) the orchestrator MUST run the Step-3 cross-reference/gap step over those candidate lists across all concern-syntheses, not only within a batch, before concluding. Without this pass the tier trades completeness for context-bounding on exactly the large diffs it targets.
Step 4 — Holistic assessment. With all findings combined, judge: overall coherence as a unified intent; cross-category sync (docs match code? contracts match callers?); risk areas where categories interact; missing doc/spec updates for changed artifacts.
No silent truncation. If any cap forces sampling or a batch is dropped for budget, ANNOUNCE the dropped/sampled scope explicitly — bounded coverage must never read as complete coverage.
MUST ATTENTION apply critical + sequential thinking — every claim needs appropriate traced evidence (file:line for repo/code claims; source URL or artifact section for research, product, content, and docs claims); confidence >80% to act, <60% DO NOT recommend. Anti-hallucination: never present guess as fact, admit uncertainty freely, cross-reference independently, stay skeptical of own confidence.
MUST ATTENTION apply AI mistake prevention — verify generated content against evidence, trace downstream references before deleting or renaming, verify all affected outputs, re-read files after context loss, and surface ambiguity before acting.