[Documentation] Use when generating, smart-merging or refactoring the root AI context (CLAUDE.md, AGENTS.md) and its Claude/Codex projections. Config file only: project-config.
The English summary is being prepared. Showing the original description.
[Debugging] Use when a workflow step or the user asks for performance bottleneck analysis and validated fixes: queries, memory, network, rendering and concurrency.
The English summary is being prepared. Showing the original description.
See how to installReview the instructions the agent will receive before you install.
Review modes: For review/audit work, standalone defaults to
--review-only(--report-onlyalias);--fix-loopenables review → validate → authorized fix → fresh re-review, default cap 3.--fix-loop --loop-owner=callerreturns a read-only pass to the caller that owns fixes/re-review. Create triage, review, validation and re-review todo tasks first; apply the carriedreview-policycontract for LOW deferral and user-approved bounded extensions. Non-review modes and terminal findings validation keep their own dispatch.
Goal: Ensure every shipped performance fix removes a measured or static-risk-labeled bottleneck across data access, compute, runtime/GC, network, client delivery, and concurrency/resilience; calibrate every number against a known anchor, preserve behavior/authorization/semantics, prove before/after evidence, pass /why-review before any fix, and complete a clean full Phase-0 re-review — never hide waste or break correctness.
Summary:
--report-only: read-only leaf mode for a caller that owns every fix — Phases 0–6 only, no nested sub-agents, no writer beyond the report; see Report-Only Mode.Workflow: Detect scope → discover local patterns → measure or label static risk → run 12 serial dimension passes → findings and severity → plan → validate findings → fix → run a full re-review.
Key Rules: Evidence beats intuition; calibrate numbers against the local performance reference; bound rows, memory, queues, and concurrency; Round 1 fixes every open validated severity (LOW deferral), while Round 2 fixes only CRITICAL/HIGH/MEDIUM and defers LOW-only findings; failed binary gates always block.
[IMPORTANT] MANDATORY MUST ATTENTION stay project-generic: discover local stack, conventions, query APIs, index definitions, metrics, and report paths before judging.
AI surface? Only if the change creates or changes a model call, prompt, agent, tool/MCP, retrieval or eval (see
node .claude/scripts/ai-signal-scan.cjs): applyAE-4,AE-5(context budget, caching layout, timeouts, cost caps) from.claude/skills/shared/protocols/ai-engineering-gate.mdand route depth to/ai-engineering-review; otherwise skip this line. [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 — ALL 12: (1) query shape/over-fetching, (2) index/access path/data topology, (3) N+1 fan-out, (4) aggregation/join shape, (5) materialization/memory, (6) write path/locks/transactions, (7) caching, (8) API payload/frontend delivery/Core Web Vitals, (9) in-process compute/algorithmic complexity, (10) network/protocol round trips, (11) runtime/memory/GC pauses, (12) distributed resilience/load management (timeouts, retries, queue bounds). NEVER stop at 9 — 10-12 are the layers a code-only reading habitually never opens. [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, investigate saturation: measure pool/thread acquire-wait and queue depth. Little's Law estimates average demand at the measured pool boundary; validate burst/wait behavior and the sum of per-instance connection budgets against shared-backend limits. [IMPORTANT] MANDATORY MUST ATTENTION calibrate every number against a known anchor before assigning severity — latency ladder, utilization knee, Core Web Vitals thresholds, hit-ratio math (references/performance-knowledge.md); a breached anchor is a HYPOTHESIS to verify with local evidence, NEVER a finding on its own.
[PERFORMANCE-FIRST PRINCIPLES — three non-negotiable checks on every hot path, OOM first]
- [MOST IMPORTANT] Hunt every OOM / out-of-memory bad practice. Unbounded read-all /
SELECT */ no page bound, full materialization before paging/filtering, buffering a whole export/report instead of streaming/chunking, loading blobs / large JSON / tracked entities for list views, accidental multiple enumeration, unbounded caches / accumulators / queues / in-memory joins. Triage row COUNT before row SIZE, reduce rows AT THE SOURCE — a fast query pulling millions of rows still OOMs the process. Bound EVERY result set with a page/limit/cursor or proven business invariant.- Right data structure & algorithm for the stack. Match the structure to the access pattern via the runtime's efficient primitive — O(1)
Set/Map/dict/hash lookup instead of a linearfind/includes/contains/in listscan inside a loop; no O(n²) where O(n log n) / O(n) / O(1) exists; single-pass min/max/partition instead of redundant re-sort. Prove the complexity class at worst-case N, never by intuition.- Batch once, or parallelize — never serial fan-out. Collapse per-item query / API / cache calls into ONE batched call (
IN/ bulk / aggregate / prefetch dictionary); where independent calls remain, run bounded-parallel with a fresh safe resource per worker instead of sequential awaits — always preserving ordering, authorization, idempotency.
[BLOCKING] Query Scan Gate — no search or query scans rows on large data. Every query, search or filter the change adds or alters on data that can grow large (no proven small, invariant-bounded size) reaches its rows through an index-backed, sargable access path and returns a bounded result (page, limit or cursor). A full table or collection scan, a leading-wildcard
LIKE, unanchored regex orcontainssearch, a non-sargable predicate (dimension 2), or an unindexed filter, join, sort or group key on such data is at least a HIGH finding and blocks the verdict; free-text search needs a full-text or search index, not a scan. Evidence: the serving index (file:linein the schema or migration) and, when available, plan/explain output at realistic volume. A scan stays only when the data is provably bounded (state the bound) or the plan is shown cheap at production volume. This gate sets the severity floor for these patterns; the scale-evidence rule under severity governs every other finding.
<!-- PROTOCOL-GUIDES:START -->Performance Knowledge (calibration constants & domain laws) — the anchors severity depends on:
- Latency ladder
1 ns → 100 ns → 100 µs → 10 ms → 100 ms(L1 → RAM → SSD → disk seek → intercontinental), each rung ~100-1000×; ~1 ms RTT per 100 km of fiber is a hard floor no code fix beats.- Measure the local SLO knee — M/M/1 illustrates mean queue wait
service_time × ρ/(1−ρ): 80%→4×, 90%→9×, 95%→19× under its assumptions, not a universal CPU limit. Little's LawL = λ × Westimates average in-flight work, not a pool-size floor. Tail amplification — fan-out to 100 backends hits a p99 ~63% of the time, so a backend p99 becomes the user's median.- Core Web Vitals LCP ≤2.5 s · INP ≤200 ms · CLS ≤0.1 · TTFB ≤800 ms, measured at p75 of real users (field), never a lab score alone.
- Cache hit-ratio math — 90%→99% cuts origin load 10×; percentiles are NEVER averageable.
MANDATORY MUST ATTENTION [BLOCKING at the severity/anchor moment] READ
references/performance-knowledge.md— full ladder, universal laws, symptom→cause triage matrix, and deep tables for network/protocol, DB engine + isolation + sharding, caching, web/CWV, memory/GC, distributed resilience, measurement rigor. The read is REQUIRED — never optional — before you assign a severity or quote/compare any anchor constant; NEVER assign a severity or cite an anchor from memory or from the 4-bullet digest above. A scope-narrowed review that assigns no severity and quotes no constant may proceed on the digest alone. — why: the digest orders hypotheses but only the body carries the thresholds severity depends on, and quoting a constant without measuring THIS system is the guess-as-fact failure this skill exists to prevent.
Protocol guides — Apply each protocol only when its read-when condition holds. If a protocol's text is not in your context, read its file below before you act on it.
category-review-thinking — Derive review concerns per category of changed files from domain knowledge; reviewing a changeset that spans several file categories → .claude/skills/shared/protocols/category-review-thinking.mdgoal-contract-satisfaction-loop — Save the goal in a file and loop until every saved criterion passes; executing work against a user goal → .claude/skills/shared/protocols/goal-contract-satisfaction-loop.mdgraph-assisted-investigation — Optional hint: a code-graph query can add callers and dependents when grep may miss a high-risk blast radius, and it can be stale; a high-risk change where grep and reading alone may miss the blast radius → .claude/skills/shared/protocols/graph-assisted-investigation.mdmeasured-capacity-engineering — Model demand, reduce measured work safely and prove capacity before scaling; planning, building, testing or reviewing hot paths, caches or capacity → .claude/skills/shared/protocols/measured-capacity-engineering.mdreview-decision-autonomy — Choose supported review decisions and ask before extending the round budget; running any review or audit skill or mode → .claude/skills/shared/protocols/review-decision-autonomy.mdreview-policy — Review-only or a three-round fix loop with explicit extension and fresh post-fix evidence; deciding round eligibility, blocking findings or review state → .claude/skills/shared/protocols/review-policy.mdreview-principle-awareness — Classify the change context first, then apply the current principles that fit it; starting any review → .claude/skills/shared/protocols/review-principle-awareness.mdscenario-stress-eval — Judge the system under concrete failure and load scenarios; evaluating resilience or production readiness → .claude/skills/shared/protocols/scenario-stress-eval.mdseverity-rubric — One consequence-based Critical, High, Medium, Low scale for every finding and gate; classifying a finding or deciding whether a review round passes → .claude/skills/shared/protocols/severity-rubric.mdsystematic-review-batching — Triage all files and plan adaptive review with complete coverage and no fixed size caps; choosing review assignments or handling working-set overflow → .claude/skills/shared/protocols/systematic-review-batching.mdtrade-off-interrogation-gate — Three trade-off questions before any verdict, score or recommendation; rendering a verdict or recommending an option → .claude/skills/shared/protocols/trade-off-interrogation-gate.md<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->[BLOCKING] Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval. Inside a workflow run,
/start-workflow→ Workflow-step mode bounds this rule. [BLOCKING] Before each step/sub-skill call, update todo tracking: setin_progresswhen step starts,completedwhen 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.
--report-only)Read Architecture-Altitude Performance Review when judging a design; apply the same evidence gate before recommendations. Before recommending caching, understand query shape, indexes, pagination, batching and data volume; completion requires measured hit ratio and a bound.
<target>$ARGUMENTS</target>
--report-only)Use when a caller runs this skill as a read-only leaf — e.g. a workflow parallel review barrier over a plan or design, or a review batch — and another step owns every fix.
--report-onlyin$ARGUMENTSselects it; review-only is the default; standalone--fix-loopalone runs repair/restart phases.MANDATORY — when
--report-onlyis passed, read.claude/skills/workflow-review-changes/references/caller-mode.md§--report-onlyin full FIRST. It holds the rules every read-only leaf shares (no fix or restart, scope from the caller's brief, no nested fan-out, no user questions, write only the report, return contract); the rules below are this skill's own.
- Run Phases 0–6 only. A plan or design target uses the Architecture-Altitude lens with
static risklabels. Phase 5 becomes the report's recommended optimization plan — no code, plan, or artifact edit. Phase 6/why-review --validate-findingsstill validates every finding. Phase 7 does not run: return the validated report; the caller owns fixes and any re-review. — why: two writers of one artifact inside a barrier race each other.- No nested fan-out. Skip Sub-Agent Routing and size-capped batching; review sequentially in this context.
For this mode the declared step order ends at Phase 6; stopping there is the mode's contract, not a skipped step.
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 | query text/ORM expression, row count, plan/explain, indexes |
| DB write | slow save, lock waits, per-row updates, transaction bloat | write loop, batch size, lock/deadlock logs, transaction scope |
| N+1/fan-out | loop with query/API call, lazy loading, per-item lookup | caller trace, query count, loop source |
| API latency | high p95/p99, timeout, slow endpoint/job | trace/profile/logs, call chain |
| Saturation/Queueing | high p99 while the operation itself is fast, pool exhausted/timeout, threads blocked on acquire | pool active/idle/pending, acquire-wait time, threads/workers vs pool size, replica count × pool |
| Memory/OOM | large materialization, blobs, no paging, buffering | allocation profile, result size, collection loads |
| Frontend | slow render, huge bundle, repeated fetch, DOM churn | browser profile, network waterfall, component/render trace |
| Distributed | message lag, cross-service waterfall, retry storm | trace spans, queue metrics, consumer/producer chain |
| Compute/CPU | hot loop, nested iteration, quadratic scaling, regex stall, heavy serialize/clone | input N, operation count vs N, profiler/flame-graph sample, microbench |
| Network/protocol | chatty call count, per-request handshake, no keep-alive, large payload, cross-region hop | call count × RTT, connection reuse state, TLS/DNS timing, payload size, HTTP version |
| Runtime/GC | latency spikes uncorrelated with load, pauses, RSS growth, blocked event loop | GC log/pause histogram, allocation rate, RSS vs heap, thread states, event-loop lag |
| Resilience/load | retry storm, no timeout, unbounded queue, cold-start blip, one tenant degrades all | timeout/retry config, queue depth AND age, breaker state, per-tenant rate limits |
Check applicability for all 12 dimensions; skip a dimension when project configuration and inspected paths prove its surface absent or outside the selected scope. Record the evidence; do not invent dependencies or setup to fill an inapplicable dimension.
Triage accelerator (symptom → usual cause). MUST ATTENTION use the symptom→cause matrix in references/performance-knowledge.md §3 to pick the FIRST evidence to pull — it maps signatures AI habitually misreads, e.g. p99 bad + p50 fine → GC pause / lock contention / fan-out tail / cold cache (NOT a slow query); latency scales with result size → N+1; sudden cliff at some load → utilization knee or pool exhaustion; degrades over days, fine after restart → leak/bloat/connection leak; slow for one tenant only → hot key/partition skew. NEVER let the matrix replace evidence — it orders the hypotheses, Phase 2 proves one.
When to apply: design/architecture reviews (e.g.
architectagent) — judge performance as a structural property of the design BEFORE it ships, not a tactical query fix after a bottleneck appears. Dimension passes stay the tactical tool; this section is the design-level lens.
Evaluate the layer model as a design concern, not a symptom site:
Performance as architecture
├── Database — data access shape baked into the model (projection, paging, N+1 surface, index strategy, partition/shard key)
├── API — serialization/processing cost, batched vs per-item queries, response-DTO contracts
├── Network — payload size & call-count designed into the contract (batch endpoints vs chatty waterfalls), endpoint placement vs RTT budget
├── Frontend — bundle/lazy-load topology, change-detection/list-keying/virtual-scroll as default architecture
├── Runtime — allocation profile & collector choice, event-loop discipline, pool sizing, working-set target
└── Background jobs — bounded parallelism (local concurrency-limited primitive) + bulk write (local batch API) as the shape, not an afterthought
Architecture-altitude rules (decide at design time — cheapest to fix here):
SELECT * endpoint; unbounded reads spike memory/latency under real data volume..Result; bounded parallelism for fan-out is part of the design, with a fresh safe scope/context per worker.call count × RTT for every designed interaction and place the endpoint (edge/region/replica) against the latency budget; ~1 ms RTT per 100 km and a 2-RTT TCP+TLS handshake are floors no later optimization removes, so a chatty contract or a distant endpoint is a permanent design cost, not a tuning detail.DB index strategy at design time → dimension 2 below (composite key order, covering/partial indexes, write-cost analysis). The tactical evidence gate (measure baseline, prove with plan/explain) still applies to every recommendation at this altitude.
MANDATORY discovery before findings (MUST ATTENTION):
performance, index, query, pagination, projection, database, profiling, cache, timeout, retry, pool, contributing, style guide..code-graph/graph.db exists, a graph blast-radius pass (trace --direction downstream on the hot path) can hint at the fan-out (it may be stale — verify by reading) — see the Graph-Assisted Investigation advice below.references/performance-knowledge.md.For capacity/load or cache-placement work, apply SYNC:measured-capacity-engineering: disclose workload and offered/achieved demand, attribute resource pressure, preserve cache correctness, and verify cold-state/overload recovery. Read references/performance-knowledge.md §10.1 and §6.1 when designing those experiments.
Prefer runtime proof. If unavailable, label finding static risk and include exact command/query needed to verify.
MANDATORY baseline for DB findings:
file:line and generated SQL/query/ORM expression when availableMANDATORY baseline for compute/CPU findings:
file:lineconsole.time / profiler or flame-graph sample at representative AND worst-case NMANDATORY baseline for saturation/pooling findings:
MANDATORY calibration + measurement rigor on EVERY baseline (references/performance-knowledge.md §1-2, §10):
Confidence:
| Confidence | Action |
|---|---|
| 95%+ | Recommend fix freely. |
| 80-94% | Recommend with caveats and verification command. |
| 70-79% | List unknowns first; gather more evidence before fix. |
| <70% | STOP. Do not recommend. |
MANDATORY apply one focused pass per dimension. NEVER scan all dimensions at once. 12 dimensions — 1-9 are the in-process/data-access core, 10-12 cover the layers a code-only reading habitually skips (network round trips, runtime/GC, resilience under load). references/performance-knowledge.md carries deep tables for network/protocol (§4), database (§5), caching (§6), web/CWV (§7), memory/GC (§8), and distributed resilience (§9); the remaining dimensions calibrate against the ladder, universal laws, and triage matrix (§1-3) instead of a dedicated table.
Think: Which rows/columns load? Are filters, projection, sorting, and limits executed by data source before materialization?
MUST ATTENTION find:
ToList/array/load-all before Where/filter)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.
Think: Can existing indexes satisfy equality/range filters, joins, sort, grouping, and projection in the actual query order? Sargability first: for EVERY filter/join predicate, is the indexed COLUMN left bare, or is it wrapped in a function/transformation that the DB must compute per row (killing the index)? Then: does the query reach the data through the right partition/shard/replica?
MUST ATTENTION — Non-sargable predicate spot-check (any ORM/SQL). A function, cast, concatenation, date extraction, or leading-wildcard predicate on a column can prevent an ordinary index seek; expression indexes and optimizer support depend on the actual database. Inspect the translated query and actual collation/normalization rules before proposing a rewrite. For case-insensitive comparisons, use a database-supported collation/operator or a normalized indexed column/expression index only after proving equivalent results. Moving normalization to the parameter alone or listing a few casing variants does not preserve arbitrary mixed-case or Unicode matches. Preserve tenant/auth filters, null behavior, locale, Unicode normalization and result sets with representative fixtures before measuring performance. Verify improvement separately with
EXPLAIN/the query plan and representative load; a sequential scan can be optimal for low selectivity and is not by itself proof of a defect.
Find:
OR, negative predicate, or low selectivityPrefer fixes: add/adjust smallest useful index, reorder composite keys to match query, rewrite predicate to be sargable, refresh statistics, carry the partition/shard key into the predicate, salt or re-key a hot partition, route lag-sensitive reads to primary (or a sticky/LSN-aware window), verify with plan/explain before/after, include write-cost risk. Escalate in order — tune query/index → cache → vertical → read replicas → partition → shard; NEVER propose sharding before the earlier rungs are proven exhausted (why: resharding and cross-shard joins are the most expensive reversal in the ladder).
Think: Does work scale with item count instead of request/job count?
Find:
IN/batch/group queryPrefer fixes: batch IDs once, join/include only needed fields, prefetch dictionaries, aggregate counts in one query, use bounded concurrency, preserve ordering/authorization semantics.
Think: Does the pipeline reduce data before expensive join/unwind/group/sort/window stages?
Find:
Prefer fixes: filter early, project early, aggregate at source, reduce join cardinality, use existence/count queries, repeat necessary post-expansion filters when array/child semantics require it.
Think: What enters memory? Is it bounded, streamed, and tracking-free when read-only?
Find:
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.
Think: Does write work batch safely and keep locks/transactions small?
Find:
UPDATENOT VALID constraint → validate; concurrent index build; expand/contract)Prefer fixes: bulk write, chunk, shorten transaction, move remote calls outside transaction, use idempotent commands, create fresh safe scope/context per parallel worker, pick the isolation level the invariant needs (or an explicit FOR UPDATE/version column), make write conflicts atomic in one statement, order lock acquisition consistently and retry deadlocks, use the online migration pattern for large tables.
Think: Is repeated expensive work stable, safe to reuse, and invalidated correctly?
Find:
Prefer fixes: request-scope memoization first, then bounded shared cache with explicit key, TTL/invalidation, size limits, privacy constraints, and hit/miss metrics. Add single-flight + TTL jitter for hot keys, stale-while-revalidate where staleness is acceptable, negative caching (or a Bloom filter) for absent keys, a version segment in the key, and an eviction policy matched to the access skew (LRU default, LFU/W-TinyLFU for skewed). NEVER treat "we added a cache" as a completed fix without the measured hit ratio and the bound.
Think: Does the user-perceived time come from payload size, render/interaction work on the main thread, or asset delivery? Judge against the Core Web Vitals thresholds at p75 of real users, never a single lab run.
Find:
references/performance-knowledge.md §7)transform/opacitywidth/height/aspect-ratio); FOIT from missing font-display<head>; critical CSS not inlinedVary incorrect (cache poisoning), no Brotli/gzip on textpreconnect saves DNS+TCP+TLS, preload for late-discovered critical assets, fetchpriority)Prefer fixes: shape the payload to the view, batch/aggregate server-side, break or yield long tasks, batch DOM reads then writes, animate compositor-only properties, reserve space for media, defer third-party and cold routes, virtualize long lists, stabilize keys, hash+immutable asset caching with correct Vary, Brotli text compression, AVIF/WebP + srcset + lazy below-fold. ALWAYS confirm with a browser profile/network waterfall AND field (RUM/CrUX) data — a lab score locates the cause, field data defines the truth.
Think: Does in-process work grow super-linearly with input size, independent of any query or network call?
MUST ATTENTION find:
map inside map, repeated full re-scan.find/.includes/.indexOf/in list/.contains where a Set/Map/dict gives O(1).filter().length for existenceJSON.parse/stringify/deep-clone/serialize per iteration/security-audit)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.
Think: How many round trips does this path cost, and what is the RTT floor it can never beat? Count calls × RTT before optimizing anything inside a single call.
MUST ATTENTION find:
TCP_NODELAYTIME_WAIT accumulation, conntrack table, NAT/SNAT ports: these present as "random" latency or errors, never as a slow functionPrefer fixes: reuse connections (keep-alive + pooled clients), collapse chatty calls into one batch/aggregate endpoint, move the endpoint closer (edge/CDN/regional replica) when RTT is the floor, compress and shrink payloads, enable the protocol version that matches the path, raise/verify the OS and infra limits, and configure LB algorithm + health checks + slow-start. ALWAYS quantify as call count × RTT before and after — why: a faster handler behind 12 avoidable round trips is not a fix.
Think: Does the runtime itself inject latency the code cannot see — collector pauses, allocation pressure, a blocked event loop, memory that never returns?
MUST ATTENTION find:
.Result/.await-blocking on a thread-pool threadcores × (1 + wait/compute))Prefer fixes: cut allocation rate before tuning the collector, right-size the heap with headroom, bound every cache and unregister every listener, measure RSS not heap against the container limit, disable swap for latency-critical services, move CPU work off the event loop, size pools by workload class, reduce lock granularity, and restore sequential access order. Prove with GC-pause histogram, allocation profile, RSS trend, event-loop lag, or off-CPU flame graph — NEVER from code reading alone.
Think: Under load or partial failure, does this path degrade gracefully — or amplify the failure? Performance and resilience share the same queues, so a missing timeout is a latency defect.
MUST ATTENTION find:
Prefer fixes: set a decreasing timeout budget per hop, add backoff+jitter with a retry budget and idempotency keys, add breaker + bulkhead + load shedding, bound every queue and propagate backpressure, reduce fan-out or hedge it, replace dual writes with an outbox, order events by logical clock and fence leaders, autoscale on a leading indicator with headroom, and enforce per-tenant quotas. Prove with timeout/retry config file:line + queue depth AND age + breaker state + per-tenant limits — why: these defects are invisible at low load and only surface as the outage they cause.
Finding format:
- [Severity] [file:line] [dimension] Problem. Evidence: metric/plan/query count. Impact: user/system effect. Fix: smallest behavior-preserving change. Verify: command/query/metric.
Severity:
NEVER inflate severity without production-like scale/frequency evidence.
Before code changes (MUST ATTENTION):
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.
Use specialized help when available (never under --report-only):
| 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 |
| Cross-service architecture, caching policy, capacity/SLO trade-off | architecture/performance specialist |
| Frontend render/bundle/CWV/network waterfall | frontend or performance specialist |
| Runtime/GC pauses, allocation profile, pool + event-loop sizing | performance-optimizer (runtime evidence: GC log, allocation profile, RSS trend, off-CPU profile) |
| Timeouts/retries/breakers/queue bounds, resilience under load | performance-optimizer with the resilience config in scope; escalate design-level gaps to architect |
Sub-agent prompt MUST include target, detected scope, local context evidence, required dimensions, the calibration anchors in play (references/performance-knowledge.md), report path, and "return summary only; write full report incrementally."
Purpose: Validate performance findings before optimization work. Performance reports overstate easily 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. Also skip when called with --loop-owner=caller: the caller validates the merged report once (/start-workflow → Workflow-step mode).
Protocol:
tmp/reports/performance-{date}-{slug}.md or the exact report path written by the caller./why-review --validate-findings <performance-report-path>.tmp/reports/why-review-validate-{date}.md.## Why-Review Validation Notes section.## Why-Review Validation stating all findings were re-validated against measurement/static evidence.Skip conditions (record explicit reason if skipping):
--loop-owner=caller → log "Skipped — the caller validates the merged report once".Trigger: Phase 6 returns CLEAN/validated and the performance report still has one or more findings that must be fixed. Under --report-only this phase never runs — the validated report is returned to the caller.
Protocol:
/why-review --validate-findings; if this skill is running inside a workflow, route implementation through the caller's fix step; standalone, apply it with /fix --target=review./performance-review review from Phase 0 over the complete current target, not only the fixed files.Non-negotiable rules:
/why-review --validate-findings validates it.MANDATORY final report sections:
If evidence insufficient, output: Insufficient evidence. Verified: [...]. Not verified: [...]. Next evidence needed: [...].
Optional performance-test handoff: when missing repeatable workload/query/memory evidence would benefit this scope, include a hint to /performance-test --mode=write <scope>. Read the handoff contract when offering it: an interactive owner may ask whether to write tests; report-only/caller-owned leaves only return the suggestion. An affirmative authorizes writing plus static review, never execution. Do not automatically initialize, write or verify tests from a review.
MUST ATTENTION Triage all files, write a short review plan and create review/validation/fix/re-review tasks first. Choose inline work or authorized specialists from risk, relationships and context headroom; no fixed file/line/byte caps. Persist coverage, reconcile interactions and validate findings before fixes or PASS.
<!-- /SYNC:systematic-review-batching:reminder --> <!-- SYNC:severity-rubric:reminder -->NOT VERIFIABLE only when the concern would be MEDIUM or higher (an observation otherwise) — never a speculative LOW.file:line evidence — never a fixed checklist.IMPORTANT MUST ATTENTION scenario-stress gate: reuse the scale tier T0–T3 AND derive business-criticality B0–B3 from evidence first — apply the criticality-signal floor (regulated/PII/financial/health data · money movement · auth/identity · legal-compliance → at least B2 even absent SLA docs; do NOT default to B3). Select only the scenarios the B/T combination warrants, then walk each (simulate → trace → failure signature → self-heal/MTTR → trade-off) and assign WITHSTANDS/DEGRADES-GRACEFULLY/FAILS-HARD/N/A-by-business/OVER-HARDENED. Anti-over-engineering is first-class (a lean system that needs no HA/DR is a PASS) AND symmetric (never under-harden a B2+ system for low traffic). ADVICE-ONLY — emit the Scenario Stress Matrix as guidance; NEVER mutate any score, verdict band, or gate pass/fail. Full catalog → .claude/docs/scenario-stress-catalog.md (authoritative for scenarios/verdicts/business-tiers — on any change update the catalog FIRST, then re-run inject_scenario_stress_gate.py; scale tier stays single-sourced in scale-technique-catalog.md).
goal.md → <plans root>/goals/{YYMMDD-HHmm}-{slug}/goal.md, plans root default plans and overridable via a docsRoots.plans.path entry in docs/project-config.json → create from current request) and read saved success criteria before editing.Review/audit invocations: follow SYNC:review-decision-autonomy for every decision prompt; choose supported recommendations without asking, preserve round-extension approval and actual authority.
ask user question tool BEFORE the verdict.ask user question tool reaches only the main interactive agent, so a sub-agent or a terminal/verdict-only mode cannot ask. There the duty is REDIRECTED, not waived: still name the trade-off, still decide materiality, record confirmed? = NO — cannot ask from this context, and state the unconfirmed MATERIAL trade-off in your RETURNED verdict so the CALLER escalates it (a note only in an on-disk report is not a handoff); never emit an unqualified PASS. If you CAN ask, you MUST ask.IMPORTANT MUST ATTENTION Every review first checks the change context and routes only applicable principles to their detailed protocols: scale-ready foundation, test intent in the project's native format (GWT is one option), AI-agent-as-user access, and UI/component design when relevant. Record evidence-backed apply/adapt/defer/N/A/block/unverified status with owner and next step; do not invent unrelated findings or expand scope.
<!-- /SYNC:review-principle-awareness:reminder --> <!-- SYNC:measured-capacity-engineering:reminder -->MUST ATTENTION capacity work: model demand/SLO and distinguish sessions from RPS/in-flight work; disclose load model and offered vs achieved demand; reduce measured work at a safe owner; preserve cache authorization/freshness/bounds; prove cold-state, overload recovery and justified headroom before scaling. Static review returns a verification plan, not invented throughput. Retain the hosting skill's scores, gates and authority.
<!-- /SYNC:measured-capacity-engineering:reminder --> <!-- SYNC:review-decision-autonomy:reminder -->MUST ATTENTION Decide supported review choices and recommendations, record the rationale, and finish without routine user questions. Keep round-limit extension, indispensable facts and actual action authority; preserve source coverage, validation, tests, read-only boundaries and budgets. Review decisions do not accept open risks or make a failed gate pass.
<!-- /SYNC:review-decision-autonomy:reminder -->IMPORTANT MUST ATTENTION Goal: Ensure every shipped performance fix removes a measured or static-risk-labeled bottleneck across data access, compute, runtime/GC, network, client delivery, and concurrency/resilience; calibrate every number against a known anchor, preserve behavior/authorization/semantics, prove before/after evidence, pass /why-review before any fix, and complete a clean full Phase-0 re-review — never hide waste or break correctness.
IMPORTANT MUST ATTENTION — Main steps: Detect scope and symptom→cause triage → discover local context and 3+ patterns → baseline evidence and calibrate anchors → run 12 serial dimension passes → order findings by severity → plan the smallest behavior-preserving optimization → validate findings with /why-review --validate-findings → fix only validated findings that block the current round and restart the full Phase-0 review (Round 1: all severities; Round 2: CRITICAL/HIGH/MEDIUM; LOW-only deferred; binary gates always block).
static risk with an exact verification command. Read references/performance-knowledge.md before severity or anchor comparisons; local SLA/spec wins. An anchor breach is a hypothesis requiring local proof. Apply the confidence table in Phase 2./why-review --validate-findings before fixing. Restart the full Phase-0 review over the complete target after current-round blocking fixes; retain the LOW deferral exception. Under --report-only, return the validated report after Phase 6; the caller owns fixes/re-review.--report-only forbids fan-out.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. |
| "Just cache it" | Fix query shape/index/bounds first. Cache can hide stale, unsafe, unbounded work. |
| "Only one query in code" | 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 fix only the current round's blocking severities and restart the FULL review from Phase 0. Round 2 LOW-only findings are deferred. |
| "Every handler is fast, so the path is fast" | Count call count × RTT and check connection reuse. 12 avoidable round trips beat any handler micro-optimization. |
| "Latency is high, optimize the code" | Check the RTT/geography floor first (~1 ms per 100 km) — physics and handshakes are not fixable in code; only moving the endpoint is. |
| "Spikes are random / just noise" | Correlate against GC pauses, cold cache, deploys, and pool wait before calling anything random. Uncorrelated-with-load spikes are usually the runtime. |
| "Added a cache, that's the fix" | Show the measured hit ratio AND the size/TTL bound. Hit ratio alone does not establish value; unbounded is a leak. |
| "Resilience is not a performance concern" | A missing timeout, jitterless retry, or unbounded queue IS a latency defect — same queues, and it converts partial failure into total. |
| "Lighthouse score is green" | CWV verdicts come from field p75 (RUM/CrUX). Lab locates causes; field defines truth. |
| "Only 9 dimensions matter, 10-12 are infra" | 10-12 (network, runtime/GC, resilience) are where code-only reviews are blindest. NEVER drop a dimension without an evidence-backed skip reason. |
| "Anchor says it's slow, that's the finding" | An anchor breach is a hypothesis. Promote it with file:line + measurement or an explicit static risk label and verify command. |
| "Digest is enough, skip the references body" | The digest orders hypotheses; only the body carries the thresholds. NEVER assign a severity or quote an anchor constant from memory or the digest — read it. |
[TASK-PLANNING] Break work into small tracked tasks before starting; keep one in_progress, mark each completed after evidence, and include the final doc/test/spec review.
MUST ATTENTION Triage all targets, plan and create review/validation/fix/fresh re-review tasks first. Review-only reports without edits; fix-loop freshly reviews every repair under one fixing owner. Default cap three rounds: disclose deferred LOWs, ask and wait before a bounded extension for MEDIUM+ or failed required checks. Preserve scope, coverage and actual operation authority.
<!-- /SYNC:review-policy:reminder -->No reviews yet. Tell others what you thought.
No login needed. Share how it worked for you, ask a question, or note where it did not run.
No comments yet. Be the first to write one.
[Documentation] Use when generating, smart-merging or refactoring the root AI context (CLAUDE.md, AGENTS.md) and its Claude/Codex projections. Config file only: project-config.
The English summary is being prepared. Showing the original description.
[Code Quality] Use when a workflow step or the user asks for AI code or plan review: LLM calls, prompts, agents, RAG, evals and guardrails. --mode={code|plan}; --report-only is read-only.
The English summary is being prepared. Showing the original description.
[Architecture] Use when a workflow step or the user asks for architecture design, compliance review, scalability grading or whole-project audit via --mode={design|review|scalability|full}.
The English summary is being prepared. Showing the original description.
[Content] Use when a workflow step or the user asks for product/feature ideation with ranked opportunities and validation tests. --mode={roadmap|scope}.
The English summary is being prepared. Showing the original description.
[Content] Use when a workflow step or the user asks for business viability: Business Model Canvas, financials, risks and go-to-market recommendation.
The English summary is being prepared. Showing the original description.
[Code Quality] Use when a workflow step or the user asks for a focused code-change review: staged, unstaged, branch diff or simple pull request. --fix-loop fixes and re-reviews. Complex pull request: workflow-review-changes; rationale: why-review.
The English summary is being prepared. Showing the original description.