@givolt/i3-composer-agent 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/.agents/plugins/marketplace.json +23 -0
  2. package/.claude/commands/build.md +44 -0
  3. package/.claude/commands/code-simplify.md +22 -0
  4. package/.claude/commands/constraints.md +32 -0
  5. package/.claude/commands/plan.md +18 -0
  6. package/.claude/commands/review.md +16 -0
  7. package/.claude/commands/ship.md +72 -0
  8. package/.claude/commands/spec.md +17 -0
  9. package/.claude/commands/test.md +19 -0
  10. package/.claude/commands/webperf.md +32 -0
  11. package/.claude-plugin/marketplace.json +27 -0
  12. package/.claude-plugin/plugin.json +19 -0
  13. package/.codex-plugin/plugin.json +28 -0
  14. package/.gemini/commands/build.toml +43 -0
  15. package/.gemini/commands/code-simplify.toml +22 -0
  16. package/.gemini/commands/constraints.toml +32 -0
  17. package/.gemini/commands/planning.toml +18 -0
  18. package/.gemini/commands/review.toml +16 -0
  19. package/.gemini/commands/ship.toml +72 -0
  20. package/.gemini/commands/spec.toml +17 -0
  21. package/.gemini/commands/test.toml +19 -0
  22. package/.gemini/commands/webperf.toml +32 -0
  23. package/CHANGELOG.md +23 -0
  24. package/LICENSE +21 -0
  25. package/NOTICE.md +9 -0
  26. package/README.md +117 -2
  27. package/agents/code-reviewer.md +102 -0
  28. package/agents/security-auditor.md +112 -0
  29. package/agents/test-engineer.md +95 -0
  30. package/agents/web-performance-auditor.md +184 -0
  31. package/bin/i3-composer-agent.cjs +122 -0
  32. package/commands/build.toml +43 -0
  33. package/commands/code-simplify.toml +22 -0
  34. package/commands/constraints.toml +32 -0
  35. package/commands/planning.toml +18 -0
  36. package/commands/review.toml +16 -0
  37. package/commands/ship.toml +72 -0
  38. package/commands/spec.toml +17 -0
  39. package/commands/test.toml +19 -0
  40. package/commands/webperf.toml +32 -0
  41. package/docs/adoption-guide.md +129 -0
  42. package/docs/advanced-per-agent-configuration.md +70 -0
  43. package/docs/agents.md +123 -0
  44. package/docs/antigravity-setup.md +128 -0
  45. package/docs/codebuddy-setup.md +41 -0
  46. package/docs/codex-setup.md +34 -0
  47. package/docs/commandcode-setup.md +69 -0
  48. package/docs/comparison.md +131 -0
  49. package/docs/copilot-cli-setup.md +64 -0
  50. package/docs/copilot-setup.md +162 -0
  51. package/docs/cursor-setup.md +225 -0
  52. package/docs/developer-onboarding.md +116 -0
  53. package/docs/gemini-cli-setup.md +133 -0
  54. package/docs/getting-started.md +208 -0
  55. package/docs/opencode-setup.md +259 -0
  56. package/docs/other-hosts.md +7 -0
  57. package/docs/skill-anatomy.md +203 -0
  58. package/docs/windsurf-setup.md +48 -0
  59. package/evals/README.md +101 -0
  60. package/evals/cases/api-and-interface-design.json +45 -0
  61. package/evals/cases/browser-testing-with-devtools.json +44 -0
  62. package/evals/cases/ci-cd-and-automation.json +45 -0
  63. package/evals/cases/code-review-and-quality.json +49 -0
  64. package/evals/cases/code-simplification.json +45 -0
  65. package/evals/cases/constraint-driven-development.json +79 -0
  66. package/evals/cases/context-engineering.json +44 -0
  67. package/evals/cases/debugging-and-error-recovery.json +58 -0
  68. package/evals/cases/deprecation-and-migration.json +52 -0
  69. package/evals/cases/documentation-and-adrs.json +44 -0
  70. package/evals/cases/doubt-driven-development.json +43 -0
  71. package/evals/cases/frontend-ui-engineering.json +52 -0
  72. package/evals/cases/git-workflow-and-versioning.json +47 -0
  73. package/evals/cases/idea-refine.json +43 -0
  74. package/evals/cases/incremental-implementation.json +57 -0
  75. package/evals/cases/interview-me.json +42 -0
  76. package/evals/cases/observability-and-instrumentation.json +44 -0
  77. package/evals/cases/performance-optimization.json +53 -0
  78. package/evals/cases/planning-and-task-breakdown.json +45 -0
  79. package/evals/cases/security-and-hardening.json +53 -0
  80. package/evals/cases/shipping-and-launch.json +56 -0
  81. package/evals/cases/source-driven-development.json +44 -0
  82. package/evals/cases/spec-driven-development.json +72 -0
  83. package/evals/cases/test-driven-development.json +73 -0
  84. package/evals/cases/using-agent-skills.json +44 -0
  85. package/evals/fixtures/api-and-interface-design/service-brief.md +19 -0
  86. package/evals/fixtures/browser-testing-with-devtools/README.md +5 -0
  87. package/evals/fixtures/browser-testing-with-devtools/index.html +24 -0
  88. package/evals/fixtures/browser-testing-with-devtools/server.js +15 -0
  89. package/evals/fixtures/ci-cd-and-automation/package.json +8 -0
  90. package/evals/fixtures/ci-cd-and-automation/src/slug.js +3 -0
  91. package/evals/fixtures/ci-cd-and-automation/test/slug.test.js +9 -0
  92. package/evals/fixtures/code-review-and-quality/user-search.diff +16 -0
  93. package/evals/fixtures/code-simplification/config-parser.js +46 -0
  94. package/evals/fixtures/code-simplification/config-parser.test.js +15 -0
  95. package/evals/fixtures/context-engineering/context-audit.md +15 -0
  96. package/evals/fixtures/debugging-and-error-recovery/pagination.js +8 -0
  97. package/evals/fixtures/debugging-and-error-recovery/pagination.test.js +9 -0
  98. package/evals/fixtures/debugging-and-error-recovery/time-pressure.md +6 -0
  99. package/evals/fixtures/deprecation-and-migration/api-inventory.md +9 -0
  100. package/evals/fixtures/documentation-and-adrs/decision-context.md +16 -0
  101. package/evals/fixtures/doubt-driven-development/migration-plan.md +19 -0
  102. package/evals/fixtures/frontend-ui-engineering/Button.tsx +7 -0
  103. package/evals/fixtures/frontend-ui-engineering/design-system.md +11 -0
  104. package/evals/fixtures/git-workflow-and-versioning/.eval/working-tree.patch +21 -0
  105. package/evals/fixtures/git-workflow-and-versioning/app.js +7 -0
  106. package/evals/fixtures/git-workflow-and-versioning/app.test.js +9 -0
  107. package/evals/fixtures/incremental-implementation/reports.js +7 -0
  108. package/evals/fixtures/incremental-implementation/reports.test.js +12 -0
  109. package/evals/fixtures/incremental-implementation/tasks/plan.md +8 -0
  110. package/evals/fixtures/incremental-implementation-pressure/draft-export.js +17 -0
  111. package/evals/fixtures/incremental-implementation-pressure/scenario.md +9 -0
  112. package/evals/fixtures/observability-and-instrumentation/operations.md +11 -0
  113. package/evals/fixtures/observability-and-instrumentation/payment-retry.js +14 -0
  114. package/evals/fixtures/performance-optimization/benchmark.js +15 -0
  115. package/evals/fixtures/performance-optimization/products.js +14 -0
  116. package/evals/fixtures/planning-and-task-breakdown/notifications-spec.md +18 -0
  117. package/evals/fixtures/security-and-hardening/webhook.js +11 -0
  118. package/evals/fixtures/security-and-hardening/webhook.test.js +13 -0
  119. package/evals/fixtures/shipping-and-launch/authority-pressure.md +6 -0
  120. package/evals/fixtures/shipping-and-launch/launch-status.md +11 -0
  121. package/evals/fixtures/source-driven-development/framework-task.md +10 -0
  122. package/evals/fixtures/spec-driven-development/billing-brief.md +16 -0
  123. package/evals/fixtures/spec-driven-development-decomposition/portal-brief.md +22 -0
  124. package/evals/fixtures/test-driven-development/BUG.md +10 -0
  125. package/evals/fixtures/test-driven-development/README.md +28 -0
  126. package/evals/fixtures/test-driven-development/package.json +9 -0
  127. package/evals/fixtures/test-driven-development/src/split.js +8 -0
  128. package/evals/fixtures/test-driven-development/test/split.test.js +13 -0
  129. package/evals/fixtures/test-driven-development-ecosystem/README.md +9 -0
  130. package/evals/fixtures/test-driven-development-ecosystem/ledger.py +15 -0
  131. package/evals/fixtures/test-driven-development-ecosystem/test_ledger.py +19 -0
  132. package/evals/fixtures/using-agent-skills/incident.md +6 -0
  133. package/evals/plugin/code-review-fires/graders/off-by-one.md +7 -0
  134. package/evals/plugin/code-review-fires/graders/severity-labels.md +4 -0
  135. package/evals/plugin/code-review-fires/graders/skill-fired.md +5 -0
  136. package/evals/plugin/code-review-fires/prompt.md +31 -0
  137. package/evals/plugin/code-review-stays-quiet/graders/not-fired.md +8 -0
  138. package/evals/plugin/code-review-stays-quiet/graders/tdd-fired.md +6 -0
  139. package/evals/plugin/code-review-stays-quiet/prompt.md +8 -0
  140. package/evals/plugin/code-review-stays-quiet-on-commit-message/graders/not-fired.md +8 -0
  141. package/evals/plugin/code-review-stays-quiet-on-commit-message/prompt.md +25 -0
  142. package/evals/skill-impact.md +6 -0
  143. package/hooks/SDD-CACHE.md +167 -0
  144. package/hooks/SIMPLIFY-IGNORE.md +91 -0
  145. package/hooks/sdd-cache-post.sh +135 -0
  146. package/hooks/sdd-cache-pre.sh +106 -0
  147. package/hooks/sdd-cache-test.sh +246 -0
  148. package/hooks/session-start-test.sh +47 -0
  149. package/hooks/session-start.sh +33 -0
  150. package/hooks/simplify-ignore-test.sh +476 -0
  151. package/hooks/simplify-ignore.sh +352 -0
  152. package/package.json +89 -4
  153. package/plugin.json +7 -0
  154. package/rebrand/MAINTENANCE.md +112 -0
  155. package/rebrand/NOTICE.md +9 -0
  156. package/rebrand/PR-WORKFLOW.md +34 -0
  157. package/rebrand/UNIFICATION-SPEC.md +33 -0
  158. package/rebrand/VALIDATION.md +28 -0
  159. package/rebrand/VERSIONING.md +32 -0
  160. package/rebrand/apply.cjs +194 -0
  161. package/rebrand/brand.json +13 -0
  162. package/rebrand/catalog.cjs +56 -0
  163. package/rebrand/fork-patches.json +12 -0
  164. package/rebrand/overlay/.github/workflows/test-plugin-install.yml +177 -0
  165. package/rebrand/overlay/CHANGELOG.md +23 -0
  166. package/rebrand/overlay/bin/i3-composer-agent.cjs +122 -0
  167. package/rebrand/overlay/scripts/validate-brand.cjs +44 -0
  168. package/rebrand/overlay/tests/bundle.test.cjs +85 -0
  169. package/rebrand/package.template.json +82 -0
  170. package/rebrand/rebrand.sh +4 -0
  171. package/rebrand/record-upstream.cjs +37 -0
  172. package/rebrand/templates/README.md +86 -0
  173. package/rebrand/templates/codebuddy-setup.md +41 -0
  174. package/rebrand/templates/codex-setup.md +34 -0
  175. package/rebrand/tests/pipeline.test.cjs +185 -0
  176. package/rebrand/upstream.json +171 -0
  177. package/references/accessibility-checklist.md +160 -0
  178. package/references/definition-of-done.md +67 -0
  179. package/references/observability-checklist.md +92 -0
  180. package/references/orchestration-patterns.md +370 -0
  181. package/references/performance-checklist.md +236 -0
  182. package/references/security-checklist.md +248 -0
  183. package/references/testing-patterns.md +235 -0
  184. package/scripts/floor-guard-reference-test.js +291 -0
  185. package/scripts/lib/skill-lint-test.js +650 -0
  186. package/scripts/lib/skill-lint.js +584 -0
  187. package/scripts/run-evals-test.js +623 -0
  188. package/scripts/run-evals.js +638 -0
  189. package/scripts/validate-artifact-paths-test.js +179 -0
  190. package/scripts/validate-artifact-paths.js +128 -0
  191. package/scripts/validate-brand.cjs +44 -0
  192. package/scripts/validate-commands-test.js +216 -0
  193. package/scripts/validate-commands.js +222 -0
  194. package/scripts/validate-reference-links-test.js +495 -0
  195. package/scripts/validate-reference-links.js +187 -0
  196. package/scripts/validate-skills.js +69 -0
  197. package/scripts/validate-versions-test.js +32 -0
  198. package/scripts/validate-versions.js +35 -0
  199. package/skills/api-and-interface-design/SKILL.md +367 -0
  200. package/skills/browser-testing-with-devtools/SKILL.md +317 -0
  201. package/skills/ci-cd-and-automation/SKILL.md +390 -0
  202. package/skills/code-review-and-quality/SKILL.md +398 -0
  203. package/skills/code-simplification/SKILL.md +331 -0
  204. package/skills/constraint-driven-development/SKILL.md +311 -0
  205. package/skills/constraint-driven-development/references/floor-guard.md +182 -0
  206. package/skills/context-engineering/SKILL.md +353 -0
  207. package/skills/debugging-and-error-recovery/SKILL.md +300 -0
  208. package/skills/deprecation-and-migration/SKILL.md +247 -0
  209. package/skills/documentation-and-adrs/SKILL.md +288 -0
  210. package/skills/doubt-driven-development/SKILL.md +243 -0
  211. package/skills/frontend-ui-engineering/SKILL.md +340 -0
  212. package/skills/git-workflow-and-versioning/SKILL.md +355 -0
  213. package/skills/idea-refine/SKILL.md +178 -0
  214. package/skills/idea-refine/examples.md +238 -0
  215. package/skills/idea-refine/frameworks.md +99 -0
  216. package/skills/idea-refine/refinement-criteria.md +113 -0
  217. package/skills/idea-refine/scripts/idea-refine.sh +15 -0
  218. package/skills/incremental-implementation/SKILL.md +249 -0
  219. package/skills/interview-me/SKILL.md +235 -0
  220. package/skills/observability-and-instrumentation/SKILL.md +238 -0
  221. package/skills/performance-optimization/SKILL.md +267 -0
  222. package/skills/performance-optimization/references/optimization-patterns.md +250 -0
  223. package/skills/planning-and-task-breakdown/SKILL.md +257 -0
  224. package/skills/security-and-hardening/SKILL.md +216 -0
  225. package/skills/security-and-hardening/references/hardening-patterns.md +324 -0
  226. package/skills/shipping-and-launch/SKILL.md +330 -0
  227. package/skills/source-driven-development/SKILL.md +216 -0
  228. package/skills/spec-driven-development/SKILL.md +259 -0
  229. package/skills/test-driven-development/SKILL.md +398 -0
  230. package/skills/using-agent-skills/SKILL.md +192 -0
  231. package/tests/bundle.test.cjs +85 -0
@@ -0,0 +1,238 @@
1
+ ---
2
+ name: observability-and-instrumentation
3
+ description: Instruments code so production behavior is visible and diagnosable. Use when adding logging, metrics, tracing, or alerting. Use when shipping any feature that runs in production and you need evidence it works. Use when production issues are reported but you can't tell what happened from the available data.
4
+ ---
5
+
6
+ # Observability and Instrumentation
7
+
8
+ ## Overview
9
+
10
+ Code you can't observe is code you can't operate. Observability is the ability to answer "what is the system doing and why?" from the outside, using the telemetry the code emits. Instrumentation is not a post-launch add-on — it's written alongside the feature, the same way tests are. If a feature ships without telemetry, the first user-reported bug becomes archaeology instead of a query.
11
+
12
+ ## When to Use
13
+
14
+ - Building any feature that will run in production
15
+ - Adding a new service, endpoint, background job, or external integration
16
+ - A production incident took too long to diagnose ("we couldn't tell what happened")
17
+ - Setting up or reviewing alerting rules
18
+ - Reviewing a PR that adds I/O, retries, queues, or cross-service calls
19
+
20
+ **NOT for:**
21
+ - Diagnosing a failure happening right now — use the `debugging-and-error-recovery` skill (observability is what makes that skill fast next time)
22
+ - Profiling and optimizing measured slowness — use the `performance-optimization` skill
23
+ - Launch-day monitoring checklists and rollback triggers — see the `shipping-and-launch` skill; this skill covers the instrumentation that feeds them
24
+
25
+ ## Process
26
+
27
+ ### 1. Define "working" before instrumenting
28
+
29
+ Telemetry without a question is noise. Before adding any instrumentation, write down 2–4 questions an on-call engineer will ask about this feature:
30
+
31
+ ```
32
+ FEATURE: checkout payment retry
33
+ QUESTIONS ON-CALL WILL ASK:
34
+ 1. What fraction of payments succeed on first attempt vs after retry?
35
+ 2. When a payment fails permanently, why? (provider error? timeout? validation?)
36
+ 3. Is the payment provider slower than usual?
37
+ → Every signal below must help answer one of these.
38
+ ```
39
+
40
+ If you can't name the questions, you're not ready to instrument — you'll log everything and learn nothing.
41
+
42
+ ### 2. Pick the right signal for each question
43
+
44
+ | Signal | Answers | Cost profile | Example |
45
+ |---|---|---|---|
46
+ | **Structured log** | "What happened in this specific case?" | Per-event; grows with traffic | `payment_failed` with provider error code |
47
+ | **Metric** | "How often / how fast, in aggregate?" | Fixed per series; cheap to query | p99 latency of provider calls |
48
+ | **Trace** | "Where did time go across services?" | Per-request; usually sampled | One slow checkout, broken down by hop |
49
+
50
+ Rule of thumb: metrics tell you **that** something is wrong, traces tell you **where**, logs tell you **why**.
51
+
52
+ ### 3. Structured logging
53
+
54
+ Log events, not prose. Every log line is a JSON object with a stable event name and machine-readable fields:
55
+
56
+ ```typescript
57
+ // BAD: string interpolation — unqueryable, inconsistent
58
+ logger.info(`Payment ${id} failed for user ${userId} after ${n} retries`);
59
+
60
+ // GOOD: stable event name + structured fields
61
+ logger.warn({
62
+ event: 'payment_failed',
63
+ paymentId: id,
64
+ provider: 'stripe',
65
+ errorCode: err.code,
66
+ attempt: n,
67
+ }, 'payment failed');
68
+ ```
69
+
70
+ **Log levels — use them consistently:**
71
+
72
+ | Level | Meaning | On-call action |
73
+ |---|---|---|
74
+ | `error` | Invariant broken; someone may need to act | Investigate |
75
+ | `warn` | Degraded but handled (retry succeeded, fallback used) | Watch for trends |
76
+ | `info` | Significant business event (order placed, job finished) | None |
77
+ | `debug` | Diagnostic detail | Off in production by default |
78
+
79
+ **Correlation IDs are mandatory.** Generate (or accept) a request ID at the system boundary and attach it to every log line, span, and outbound call. Without it, you cannot reconstruct a single request from interleaved logs:
80
+
81
+ ```typescript
82
+ // Express: child logger per request, ID propagated downstream
83
+ app.use((req, res, next) => {
84
+ req.id = req.headers['x-request-id'] ?? crypto.randomUUID();
85
+ req.log = logger.child({ requestId: req.id });
86
+ res.setHeader('x-request-id', req.id);
87
+ next();
88
+ });
89
+ ```
90
+
91
+ **When several entry points write to one log, name the entry point.** A correlation ID identifies a run; it does not say which code path started it. The same job reached by a scheduler, by a replay endpoint, and by a manual CLI run produces interchangeable lines in one sink, so attributing a line falls back to elimination — cross-reading the scheduler's history, the process table, a deploy log — and that argument holds only as long as those external records happen to still exist. Stamp the entry point where the run starts, next to the correlation ID, and propagate both the same way:
92
+
93
+ ```typescript
94
+ // One helper for every entry point: the run's own logger carries both fields.
95
+ // `entryPoint`, not `source` — ECS reserves `source.*` for network fields.
96
+ export const runLog = (entryPoint: 'scheduler' | 'replay_endpoint' | 'cli', runId: string) =>
97
+ logger.child({ entryPoint, requestId: runId });
98
+
99
+ // scheduler tick -> runLog('scheduler', crypto.randomUUID())
100
+ // POST /jobs/:id/replay -> runLog('replay_endpoint', req.id)
101
+ // CLI invocation -> runLog('cli', process.env.RUN_ID ?? crypto.randomUUID())
102
+ ```
103
+
104
+ Both fields have to cross the same boundaries as the correlation ID — queue metadata, HTTP headers — or a worker re-derives the entry point and guesses. A field that merely correlates with an entry point is a hint, not an attribution: anything that can invoke the job can reproduce it.
105
+
106
+ **Never log secrets, tokens, passwords, or full PII.** This is a hard rule from the `security-and-hardening` skill — telemetry pipelines are a classic data-leak path. Allowlist fields; don't log whole request bodies.
107
+
108
+ ### 4. Metrics
109
+
110
+ For request-driven services, instrument **RED** on every endpoint and every external dependency: **R**ate (requests/sec), **E**rrors (failure rate), **D**uration (latency histogram, not average). For resources (queues, pools, hosts), use **USE**: **U**tilization, **S**aturation, **E**rrors.
111
+
112
+ As with tracing, the vendor-neutral path is the OpenTelemetry metrics API (same SDK and context as step 5). The example below uses Prometheus' `prom-client` — one common backend choice, not the only one; the RED/USE and cardinality rules are identical either way.
113
+
114
+ ```typescript
115
+ import { Histogram } from 'prom-client';
116
+
117
+ const httpDuration = new Histogram({
118
+ name: 'http_request_duration_seconds',
119
+ help: 'HTTP request duration',
120
+ labelNames: ['method', 'route', 'status_class'], // '2xx', not '200'
121
+ buckets: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],
122
+ });
123
+ ```
124
+
125
+ **Cardinality is the failure mode.** Every unique label combination is a separate time series. Labels must come from small, fixed sets (route template, status class, provider name). Never use user IDs, raw URLs, error messages, or other unbounded values as labels — that belongs in logs and traces.
126
+
127
+ ```
128
+ OK as label: route="/api/tasks/:id" status_class="5xx" provider="stripe"
129
+ NEVER a label: user_id, email, request_id, full URL, error message text
130
+ ```
131
+
132
+ Track averages never, percentiles always: an average hides the 1% of users having a terrible time. Use histograms and read p50/p95/p99.
133
+
134
+ ### 5. Distributed tracing
135
+
136
+ Use OpenTelemetry — it's the vendor-neutral standard, and auto-instrumentation covers HTTP, gRPC, and common DB clients with near-zero code:
137
+
138
+ ```typescript
139
+ // tracing.ts — must be imported before anything else
140
+ import { NodeSDK } from '@opentelemetry/sdk-node';
141
+ import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
142
+
143
+ const sdk = new NodeSDK({
144
+ serviceName: 'checkout-service',
145
+ instrumentations: [getNodeAutoInstrumentations()],
146
+ });
147
+ sdk.start();
148
+ ```
149
+
150
+ Add manual spans only around meaningful internal units of work (e.g., `applyDiscounts`, `chargeProvider`) and attach the attributes on-call will filter by. Propagate context across every async boundary — HTTP headers, queue message metadata — or the trace dies at the gap. Sample head-based at a low rate by default; keep 100% of errors if your backend supports tail sampling.
151
+
152
+ ### 6. Alerting
153
+
154
+ Alert on **symptoms users feel**, not on causes:
155
+
156
+ ```
157
+ SYMPTOM (page-worthy): CAUSE (dashboard, not a page):
158
+ error rate > 1% for 5 min CPU at 85%
159
+ p99 latency > 2s one pod restarted
160
+ queue age > 10 min disk at 70%
161
+ ```
162
+
163
+ Cause-based alerts fire when nothing is wrong and miss failures you didn't predict. Symptom-based alerts fire exactly when users are hurt, regardless of the cause.
164
+
165
+ Rules for every alert you create:
166
+
167
+ 1. **It must be actionable.** If the response is "ignore it, it self-heals", delete the alert.
168
+ 2. **It links to a runbook** — even three lines: what it means, first query to run, escalation path.
169
+ 3. **It has a threshold and duration** justified by the SLO or by historical data, not by a guess.
170
+ 4. Use two severities only: **page** (user-facing, act now) and **ticket** (degradation, act this week). A third tier becomes noise that trains people to ignore everything.
171
+
172
+ #### Writing Runbooks
173
+
174
+ Rule 2 above requires every alert to link to a runbook. A runbook's job is to answer three questions without requiring the reader to think: what is happening, what to check first, and who to call if that doesn't resolve it. Store in `docs/runbooks/` named after the alert.
175
+
176
+ **Minimum viable runbook (three lines):**
177
+
178
+ ```markdown
179
+ # Runbook: High Error Rate on /api/tasks
180
+ **Means:** DB connection pool likely exhausted, or a bad deploy.
181
+ **First check:** `SELECT count(*) FROM pg_stat_activity WHERE backend_type = 'client backend';`
182
+ — if count > pool limit, see Step 2. (Swap in the equivalent for your database.)
183
+ **Escalate to:** #db-oncall or engineering on-call rotation.
184
+ ```
185
+
186
+ **When to expand beyond three lines:** add steps only when the first check alone isn't enough to decide. A five-step runbook that covers the three most common causes is better than a twenty-step document that covers every edge case and gets skimmed.
187
+
188
+ **Keep runbooks current.** Update the runbook as part of closing every incident it was used in — a stale runbook builds false confidence. If a step was wrong or missing, fix it before marking the incident resolved.
189
+
190
+ ### 7. Verify the telemetry itself
191
+
192
+ Instrumentation is code; it can be wrong. Before calling the work done, trigger the paths and look at the actual output:
193
+
194
+ - Force an error in staging → find it in the logs by `requestId`, confirm fields are structured (not `[object Object]`)
195
+ - Send test traffic → confirm metric series appear with the expected labels and sane values
196
+ - Follow one request across services in the tracing UI → no broken spans
197
+ - Fire each new alert once (lower the threshold temporarily) → confirm it reaches the right channel and the runbook link works
198
+
199
+ ## Common Rationalizations
200
+
201
+ | Rationalization | Reality |
202
+ |---|---|
203
+ | "I'll add logging after it works" | "After" becomes "after the first incident", which is the most expensive moment to discover you're blind. Instrument as you build. |
204
+ | "More logs = more observability" | Unstructured noise makes incidents slower, not faster. Three queryable events beat three hundred prose lines. |
205
+ | "console.log is fine for now" | Unstructured output can't be filtered, correlated, or alerted on. The structured logger costs five extra minutes once. |
206
+ | "We can just look at the dashboards when something breaks" | Dashboards built without defined questions show you everything except the answer. Start from on-call questions. |
207
+ | "Alert on everything important, we'll tune later" | A noisy pager trains people to ignore it. The tuning never happens; the missed real page does. |
208
+ | "User ID as a metric label makes debugging easier" | It also makes your metrics backend fall over. High-cardinality lookups belong in logs and traces. |
209
+ | "Tracing is overkill for our two services" | Two services already means cross-service latency questions logs can't answer. Auto-instrumentation makes the cost trivial. |
210
+
211
+ ## Red Flags
212
+
213
+ - A feature PR with retries, queues, or external calls and zero new telemetry
214
+ - Log lines built by string interpolation instead of structured fields
215
+ - No correlation/request ID — each log line is an orphan
216
+ - One log stream fed by a scheduler, a webhook, and manual runs, with no field naming which one produced the line
217
+ - Metrics labeled with user IDs, raw URLs, or error message text (cardinality bomb)
218
+ - Latency tracked as an average with no percentiles
219
+ - Alerts that fire daily and get acknowledged without action
220
+ - Alerts on causes (CPU, memory) paging humans while user-facing error rate is unmonitored
221
+ - Secrets, tokens, or full request bodies appearing in logs
222
+ - "It works on my machine" as the only evidence a production feature is healthy
223
+
224
+ ## Verification
225
+
226
+ After instrumenting a feature, confirm:
227
+
228
+ - [ ] The on-call questions for this feature are written down, and each signal maps to one
229
+ - [ ] All log output is structured (JSON), with stable event names and a correlation ID on every line
230
+ - [ ] Every log sink written by more than one entry point carries an entry-point field, set where the run starts and propagated with the correlation ID rather than inferred downstream
231
+ - [ ] No secrets, tokens, or unredacted PII in any log line (spot-check actual output)
232
+ - [ ] RED metrics exist for every new endpoint and every external dependency, with bounded label sets
233
+ - [ ] Latency is a histogram; p95/p99 are queryable
234
+ - [ ] A single request can be followed end-to-end in the tracing UI without broken spans
235
+ - [ ] Every new alert is symptom-based, has a runbook link, and was test-fired once
236
+ - [ ] An induced failure in staging was located via telemetry alone, without reading the source
237
+
238
+ For the at-a-glance version of this list, including the pre-launch instrumentation gate, see `../../references/observability-checklist.md`.
@@ -0,0 +1,267 @@
1
+ ---
2
+ name: performance-optimization
3
+ description: Optimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks.
4
+ ---
5
+
6
+ # Performance Optimization
7
+
8
+ ## Overview
9
+
10
+ Measure before optimizing. Performance work without measurement is guessing — and guessing leads to premature optimization that adds complexity without improving what matters. Profile first, identify the actual bottleneck, fix it, measure again. Optimize only what measurements prove matters.
11
+
12
+ ## When to Use
13
+
14
+ - Performance requirements exist in the spec (load time budgets, response time SLAs)
15
+ - Users or monitoring report slow behavior
16
+ - Core Web Vitals scores are below thresholds
17
+ - You suspect a change introduced a regression
18
+ - Building features that handle large datasets or high traffic
19
+
20
+ **When NOT to use:** Don't optimize before you have evidence of a problem. Premature optimization adds complexity that costs more than the performance it gains.
21
+
22
+ ## Core Web Vitals Targets
23
+
24
+ | Metric | Good | Needs Improvement | Poor |
25
+ |--------|------|-------------------|------|
26
+ | **LCP** (Largest Contentful Paint) | ≤ 2.5s | ≤ 4.0s | > 4.0s |
27
+ | **INP** (Interaction to Next Paint) | ≤ 200ms | ≤ 500ms | > 500ms |
28
+ | **CLS** (Cumulative Layout Shift) | ≤ 0.1 | ≤ 0.25 | > 0.25 |
29
+
30
+ ## The Optimization Workflow
31
+
32
+ ```
33
+ 1. MEASURE → Establish baseline with real data
34
+ 2. IDENTIFY → Find the actual bottleneck (not assumed)
35
+ 3. FIX → Address the specific bottleneck
36
+ 4. VERIFY → Measure again; keep or revert
37
+ 5. GUARD → Add monitoring or tests to prevent regression
38
+ ```
39
+
40
+ ### Step 1: Measure
41
+
42
+ Two complementary approaches — use both:
43
+
44
+ - **Synthetic (Lighthouse, DevTools Performance tab):** Controlled conditions, reproducible. Best for CI regression detection and isolating specific issues.
45
+ - **RUM (web-vitals library, CrUX):** Real user data in real conditions. Required to validate that a fix actually improved user experience.
46
+
47
+ **Frontend:**
48
+ ```bash
49
+ # Synthetic: Lighthouse in Chrome DevTools (or CI)
50
+ # Chrome DevTools → Performance tab → Record
51
+ # Chrome DevTools MCP → Performance trace
52
+
53
+ # RUM: Web Vitals library in code
54
+ import { onLCP, onINP, onCLS } from 'web-vitals';
55
+
56
+ onLCP(console.log);
57
+ onINP(console.log);
58
+ onCLS(console.log);
59
+ ```
60
+
61
+ **Backend:**
62
+ ```bash
63
+ # Response time logging
64
+ # Application Performance Monitoring (APM)
65
+ # Database query logging with timing
66
+
67
+ # Simple timing
68
+ console.time('db-query');
69
+ const result = await db.query(...);
70
+ console.timeEnd('db-query');
71
+ ```
72
+
73
+ ### Where to Start Measuring
74
+
75
+ Use the symptom to decide what to measure first:
76
+
77
+ ```
78
+ What is slow?
79
+ ├── First page load
80
+ │ ├── Large bundle? --> Measure bundle size, check code splitting
81
+ │ ├── Slow server response? --> Measure TTFB in DevTools Network waterfall
82
+ │ │ ├── DNS long? --> Add dns-prefetch / preconnect for known origins
83
+ │ │ ├── TCP/TLS long? --> Enable HTTP/2, check edge deployment, keep-alive
84
+ │ │ └── Waiting (server) long? --> Profile backend, check queries and caching
85
+ │ └── Render-blocking resources? --> Check network waterfall for CSS/JS blocking
86
+ ├── Interaction feels sluggish
87
+ │ ├── UI freezes on click? --> Profile main thread, look for long tasks (>50ms)
88
+ │ ├── Form input lag? --> Check re-renders, controlled component overhead
89
+ │ └── Animation jank? --> Check layout thrashing, forced reflows
90
+ ├── Page after navigation
91
+ │ ├── Data loading? --> Measure API response times, check for waterfalls
92
+ │ └── Client rendering? --> Profile component render time, check for N+1 fetches
93
+ └── Backend / API
94
+ ├── Single endpoint slow? --> Profile database queries, check indexes
95
+ ├── All endpoints slow? --> Check connection pool, memory, CPU
96
+ └── Intermittent slowness? --> Check for lock contention, GC pauses, external deps
97
+ ```
98
+
99
+ ### Step 2: Identify the Bottleneck
100
+
101
+ Common bottlenecks by category:
102
+
103
+ **Frontend:**
104
+
105
+ | Symptom | Likely Cause | Investigation |
106
+ |---------|-------------|---------------|
107
+ | Slow LCP | Large images, render-blocking resources, slow server | Check network waterfall, image sizes |
108
+ | High CLS | Images without dimensions, late-loading content, font shifts | Check layout shift attribution |
109
+ | Poor INP | Heavy JavaScript on main thread, large DOM updates | Check long tasks in Performance trace |
110
+ | Slow initial load | Large bundle, many network requests | Check bundle size, code splitting |
111
+
112
+ **Backend:**
113
+
114
+ | Symptom | Likely Cause | Investigation |
115
+ |---------|-------------|---------------|
116
+ | Slow API responses | N+1 queries, missing indexes, unoptimized queries | Check database query log |
117
+ | Memory growth | Leaked references, unbounded caches, large payloads | Heap snapshot analysis |
118
+ | CPU spikes | Synchronous heavy computation, regex backtracking | CPU profiling |
119
+ | High latency | Missing caching, redundant computation, network hops | Trace requests through the stack |
120
+
121
+ ### Step 3: Fix the Bottleneck
122
+
123
+ Fix the one thing Step 2 identified, nothing else. The anti-patterns below are the usual suspects; each entry gives the rule and the signature to recognize it, and links to a worked fix in [references/optimization-patterns.md](references/optimization-patterns.md). Open the one you need when you reach that code, not before.
124
+
125
+ **Backend**
126
+
127
+ - **N+1 queries.** One query per row is the most common backend bottleneck. Fetch the relation in the same query (join/include) instead of in the loop. [Pattern](references/optimization-patterns.md#n1-queries-backend).
128
+ - **Unbounded data fetching.** Every list endpoint paginates with a limit and a stable order. [Pattern](references/optimization-patterns.md#unbounded-data-fetching).
129
+ - **Queries that ignore their index.** "Add an index" is the guess; `EXPLAIN ANALYZE` is the measurement. A `Seq Scan` where you expected an index, a `rows=` estimate off by an order of magnitude, and a `Sort` node above the scan each call for a different fix; a bad `rows=` estimate means stale statistics, so run `ANALYZE` rather than adding an index. Index for the shape of the query (equality columns first, then the range or sort column). A plain index will not help a query on a low-selectivity dominant value (a partial index serves the rare value), a leading wildcard (needs trigram or full-text), or a function applied to the column (index the expression, as in `WHERE lower(email) = ?`), and every index taxes every write. Re-run the plan afterwards; an index that did not change it is a revert. [Pattern](references/optimization-patterns.md#queries-that-ignore-their-index).
130
+ - **Connection pool exhaustion.** Signature: *every* endpoint slows at once, time is spent waiting for a connection rather than executing, and the database shows mostly idle sessions. One pool per process, sized so `instances × max` stays under the database's connection ceiling. Bigger is not faster; it relocates the queue to the database where it is harder to see. With unbounded instance counts (serverless, autoscaling), multiplex through a proxy (pgbouncer, RDS Proxy) instead of raising `max`. [Pattern](references/optimization-patterns.md#connection-pool-exhaustion).
131
+ - **Missing caching.** Cache what is expensive to produce and read far more often than it changes; caching an already-fast query adds a network hop and a staleness bug in exchange for nothing. Pick the layer deliberately (in-process, shared, CDN). Every input that changes the response belongs in the key (tenant, locale, permissions, feature flags): a key that omits the viewer is how one user's data gets served to another. Choose one invalidation strategy (TTL, event or tag based, versioned keys) and state the acceptable staleness window explicitly. Guard hot keys against the stampede: serve stale while one request recomputes, or coalesce concurrent misses behind a single in-flight promise. Never cache what must be fresh (balances, permissions, inventory at checkout). [Pattern](references/optimization-patterns.md#missing-caching-backend); request coalescing, write strategies, and negative caching in `../../references/performance-checklist.md`.
132
+
133
+ **Frontend**
134
+
135
+ - **Missing image optimization.** Every image declares `width` and `height` (CLS). The LCP image gets `fetchpriority="high"`, modern formats (AVIF, WebP) through `<picture>`, and `srcset`/`sizes` for resolution switching; below-the-fold images get `loading="lazy"` and `decoding="async"`. [Pattern](references/optimization-patterns.md#missing-image-optimization-frontend).
136
+ - **Unnecessary re-renders.** An object or function created in render is a new reference every time and re-renders every child that receives it. Hoist constants; reserve `React.memo` and `useMemo` for work the profile shows is expensive, since overuse is its own cost. [Pattern](references/optimization-patterns.md#unnecessary-re-renders-react).
137
+ - **Large bundle size.** Modern bundlers tree-shake ESM named imports on their own; the real gains are route-level code splitting and lazy-loading heavy, rarely-used features behind `Suspense`. Profile before changing import styles. [Pattern](references/optimization-patterns.md#large-bundle-size).
138
+
139
+ ### Step 4: Verify (Keep or Revert)
140
+
141
+ A fix is a hypothesis until you re-measure. This step decides whether it survives.
142
+
143
+ **Re-measure the way you measured the baseline:** same command, same conditions, same fixed budget (wall-clock, sample count, or request count). A baseline taken on a cold cache against a result taken on a warm one measures the cache, not your change.
144
+
145
+ **Change one thing at a time.** Three optimizations landed together produce one number, and you cannot attribute it. If they must ship together, measure each in isolation first.
146
+
147
+ **Beat the noise, not just the mean.** Repeat the measurement and compare the delta against run-to-run variance. A 3% gain inside ±5% variance is not a gain; it is a different sample.
148
+
149
+ Then decide, strictly:
150
+
151
+ | Result vs. baseline | Action |
152
+ |---|---|
153
+ | Past the threshold, tests green | **Keep.** Commit with the before/after numbers in the message. |
154
+ | Within noise (no measurable change) | **Revert.** |
155
+ | Worse | **Revert.** |
156
+ | Improved, but a test went red | **Revert.** A regression wearing a win's clothing. |
157
+
158
+ **"Neutral" is a revert, not a keep.** This is the step teams skip: the change is already written, throwing it away feels wasteful, so it lands unmeasured, and the codebase accretes complexity that never bought anything. Code you keep, you maintain forever. Make it pay for itself.
159
+
160
+ **Correctness gates the metric.** The suite stays green *and* the number moves. An "optimization" that wins by dropping work the product needed (skipping a validation, caching something that must be fresh, removing an `await` that was load-bearing) is a regression, not a win.
161
+
162
+ #### Log every attempt, including the reverted ones
163
+
164
+ Reverted work leaves no trace in git history, which is exactly why the same dead idea gets tried again next quarter. Keep a short ledger so a discarded idea stays discarded:
165
+
166
+ | Idea | Baseline → Result | Verdict | Why |
167
+ |---|---|---|---|
168
+ | Memoize the row component | INP 240ms → 235ms | reverted | Inside noise (±15ms). Rows weren't the bottleneck. |
169
+ | Virtualize the list | INP 240ms → 90ms | kept | Long tasks gone from the trace. |
170
+ | Preconnect to the API origin | LCP 2.8s → 2.8s | reverted | Already same-origin. |
171
+
172
+ A section in the PR description or a `PERF.md` in the repo both work. What matters is that the next person (or the next agent) reads it before proposing an experiment, and doesn't re-run one that already failed.
173
+
174
+ ### Step 5: Guard Against Regression
175
+
176
+ Guard the metric the user actually feels, not every available number. Use the
177
+ same LCP, INP, p95 latency, or other primary metric that justified the fix.
178
+
179
+ Use two complementary layers when the surface is user-facing:
180
+
181
+ - **Synthetic CI gate:** Catch reproducible regressions before merge with a
182
+ performance budget. Repeat noisy measurements or compare a median/trend so
183
+ normal run-to-run variance does not turn the gate into a flaky check.
184
+ - **Field monitoring:** Alert on a meaningful p75 movement in RUM data. Use
185
+ attributed `web-vitals` data to locate the cause; treat CrUX's rolling window
186
+ as confirmation rather than an immediate alert.
187
+
188
+ When either guard fires, return to Step 1 and establish a fresh baseline before
189
+ proposing another fix.
190
+
191
+ **Set budgets and enforce them:**
192
+
193
+ ```
194
+ JavaScript bundle: < 200KB gzipped (initial load)
195
+ CSS: < 50KB gzipped
196
+ Images: < 200KB per image (above the fold)
197
+ Fonts: < 100KB total
198
+ API response time: < 200ms (p95)
199
+ Time to Interactive: < 3.5s on 4G
200
+ Lighthouse Performance score: ≥ 90
201
+ ```
202
+
203
+ **Enforce in CI:**
204
+ ```bash
205
+ # Bundle size check
206
+ npx bundlesize --config bundlesize.config.json
207
+
208
+ # Lighthouse CI
209
+ npx lhci autorun
210
+ ```
211
+
212
+ ## See Also
213
+
214
+ For detailed performance checklists, optimization commands, and anti-pattern reference, see `../../references/performance-checklist.md`.
215
+
216
+
217
+ ## Common Rationalizations
218
+
219
+ | Rationalization | Reality |
220
+ |---|---|
221
+ | "We'll optimize later" | Performance debt compounds. Fix obvious anti-patterns now, defer micro-optimizations. |
222
+ | "It's fast on my machine" | Your machine isn't the user's. Profile on representative hardware and networks. |
223
+ | "This optimization is obvious" | If you didn't measure, you don't know. Profile first. |
224
+ | "Users won't notice 100ms" | Research shows 100ms delays impact conversion rates. Users notice more than you think. |
225
+ | "The framework handles performance" | Frameworks prevent some issues but can't fix N+1 queries or oversized bundles. |
226
+ | "The query is slow, add an index" | Read the plan first. The index may already exist and be unusable, and every index taxes writes forever. |
227
+ | "Just cache it" | Caching an already-cheap call buys nothing and adds a staleness bug. Cache what is expensive *and* re-read far more than written. |
228
+ | "Raise the pool size, we're running out of connections" | A pool bigger than the database can serve moves the queue somewhere less visible. Find what holds connections. |
229
+ | "It didn't help much, but it doesn't hurt" | Neutral changes are a revert. You pay maintenance on them forever and got nothing back. |
230
+ | "We already wrote it, may as well keep it" | Sunk cost. The measurement doesn't care how long the change took to write. |
231
+ | "The improvement is obvious, no need to re-measure" | Then re-measuring is cheap and proves it. Unmeasured wins are how neutral complexity lands. |
232
+
233
+ ## Red Flags
234
+
235
+ - Optimization without profiling data to justify it
236
+ - N+1 query patterns in data fetching
237
+ - An index added without a query plan before and after to justify it
238
+ - A cache key that omits an input the response depends on (tenant, locale, viewer)
239
+ - A cache with no stated staleness window and no invalidation strategy
240
+ - Connection pool size raised in response to exhaustion, without finding what holds connections
241
+ - List endpoints without pagination
242
+ - Images without dimensions, lazy loading, or responsive sizes
243
+ - Bundle size growing without review
244
+ - No performance monitoring in production
245
+ - `React.memo` and `useMemo` everywhere (overusing is as bad as underusing)
246
+ - Optimizations kept without a re-measurement that justifies them
247
+ - Several optimizations bundled into one measurement, so no single change can be attributed
248
+ - A "win" that required a test to be changed, skipped, or deleted
249
+ - The same failed optimization attempted more than once because nobody recorded the first attempt
250
+
251
+ ## Verification
252
+
253
+ After any performance-related change:
254
+
255
+ - [ ] Before and after measurements exist (specific numbers)
256
+ - [ ] The result was re-measured the same way as the baseline (same command, same conditions)
257
+ - [ ] The improvement exceeds run-to-run variance, not just the mean
258
+ - [ ] Changes that didn't beat the baseline were reverted, not kept as neutral
259
+ - [ ] Attempts are logged, kept and reverted alike, so a dead idea isn't re-run
260
+ - [ ] The specific bottleneck is identified and addressed
261
+ - [ ] Core Web Vitals are within "Good" thresholds
262
+ - [ ] Bundle size hasn't increased significantly
263
+ - [ ] No N+1 queries in new data fetching code
264
+ - [ ] Any new index is justified by a query plan before and after, and its write cost was considered
265
+ - [ ] Any new cache states what it keys on and how it goes stale
266
+ - [ ] The measured user-facing metric has a synthetic budget or field monitor that can detect regression
267
+ - [ ] Existing tests still pass (optimization didn't break behavior)