@jgamaraalv/ts-dev-kit 3.3.0 → 5.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.
@@ -240,7 +240,12 @@ Each agent prompt must follow the template in references/agent-dispatch.md. The
240
240
  Decide the execution order based on file conflicts and dependencies:
241
241
  - **Parallel**: roles touch independent files with no data dependency → launch multiple Task calls in one message. **CRITICAL: "parallel" means sending ALL independent Task() calls in a SINGLE assistant message. If you announce "dispatching 3 agents in parallel" you MUST include exactly 3 Task() tool calls in that same message. Announcing parallel dispatch and then sending only 1 Task() is a violation of this protocol.**
242
242
  - **Sequential**: one role's output is another's input → await the blocker first.
243
- - **Worktree isolation**: roles touch overlapping files but are otherwise independent → set `isolation: "worktree"` on the Task tool.
243
+ - **Worktree isolation**: roles touch overlapping files but are otherwise independent → set `isolation: "worktree"` on the Task tool. Each agent gets an isolated copy of the repository; the worktree is auto-cleaned if the agent makes no changes.
244
+
245
+ **Decision tree for overlapping files:**
246
+ 1. Do the agents have a data dependency (one needs the other's output)? → **Sequential**.
247
+ 2. Are the agents logically independent but touch some of the same files (e.g., both modify a shared barrel export, or both edit the same config)? → **Worktree isolation** — dispatch in parallel with `isolation: "worktree"` on each Task() call, then merge results.
248
+ 3. Do the agents touch completely separate files? → **Parallel** (no isolation needed).
244
249
  </rule_3_execution_order>
245
250
 
246
251
  <rule_4_model_selection>
@@ -369,8 +374,9 @@ As orchestrator, your responsibilities are: context gathering, agent dispatch, o
369
374
  1. Create TaskCreate entries for each role to track progress.
370
375
  2. For each role, dispatch a specialized agent via the Task tool with a self-contained prompt. Set the `model` parameter according to rule_4_model_selection.
371
376
  3. **Launch independent agents in parallel — this means multiple Task() calls in a SINGLE message.** Do NOT sequentialize independent agents. If you have 3 independent tasks, your message must contain 3 Task() tool calls. Launch dependent agents sequentially (wait for blockers to complete first).
372
- 4. Each agent runs its own quality gates before reporting completion. Review the agent's output and gate results before dispatching dependents.
373
- 5. After all agents complete, proceed to phase 5 for the final cross-package quality gates.
377
+ 4. **For parallel agents that touch overlapping files**, add `isolation: "worktree"` to each Task() call. This gives each agent an isolated copy of the repository, preventing edit conflicts. Worktrees are auto-cleaned when the agent makes no changes.
378
+ 5. Each agent runs its own quality gates before reporting completion. Review the agent's output and gate results before dispatching dependents.
379
+ 6. After all agents complete, proceed to phase 5 for the final cross-package quality gates.
374
380
 
375
381
  For the agent prompt template and dispatch details, see references/agent-dispatch.md.
376
382
 
@@ -450,11 +456,15 @@ If you announce "dispatching 3 agents in parallel", your message MUST contain ex
450
456
  ### 4. Never write application code as orchestrator
451
457
  The orchestrator reads, analyzes, dispatches, reviews, and runs quality gates. It does NOT write components, hooks, routes, services, migrations, tests, or any application logic. The only code the orchestrator may write is trivial integration glue (under 15 lines): barrel exports, small wiring imports, or config one-liners.
452
458
 
459
+ ### 5. Never dispatch parallel agents on overlapping files without worktree isolation
460
+ When two or more agents run in parallel and touch any of the same files (shared barrel exports, config files, common modules), they will produce edit conflicts. Always set `isolation: "worktree"` on each Task() call so each agent works on an isolated copy of the repository. Skip isolation only when agents touch completely separate files.
461
+
453
462
  ### Self-check before sending each message
454
463
  Before sending any message during execution, verify:
455
464
  - [ ] Am I about to write application code? → STOP, dispatch an agent instead.
456
465
  - [ ] Am I about to modify a config without querying docs? → STOP, use Context7 first.
457
466
  - [ ] Did I announce N parallel agents? → Count my Task() calls. Are there N? If not, add the missing ones.
467
+ - [ ] Am I dispatching parallel agents that touch the same files? → Add `isolation: "worktree"` to each Task() call.
458
468
  - [ ] Did a quality gate fail? → STOP, dispatch a specialist agent to fix it.
459
469
  </orchestrator_anti_patterns>
460
470
  </workflow>
@@ -97,6 +97,49 @@ Discover from the codebase:
97
97
  )
98
98
  ```
99
99
 
100
+ ## Dispatch with worktree isolation
101
+
102
+ When parallel agents touch overlapping files (e.g., both modify a shared barrel export or the same config), add `isolation: "worktree"` to each Task() call. Each agent gets an isolated copy of the repository, preventing edit conflicts.
103
+
104
+ ```
105
+ // Two agents that both touch shared/src/index.ts — dispatch in parallel with worktree isolation
106
+ Task(
107
+ description: "Add user schema and migration",
108
+ subagent_type: "database-expert",
109
+ model: "sonnet",
110
+ isolation: "worktree",
111
+ prompt: """
112
+ ## Your task
113
+ Create the users table schema and migration...
114
+
115
+ ## Success criteria
116
+ - Schema exported from shared package
117
+ - Migration runs cleanly
118
+ """
119
+ )
120
+
121
+ Task(
122
+ description: "Add notification schema and migration",
123
+ subagent_type: "database-expert",
124
+ model: "sonnet",
125
+ isolation: "worktree",
126
+ prompt: """
127
+ ## Your task
128
+ Create the notifications table schema and migration...
129
+
130
+ ## Success criteria
131
+ - Schema exported from shared package
132
+ - Migration runs cleanly
133
+ """
134
+ )
135
+ ```
136
+
137
+ After both agents complete, review the worktree results. If both modified the same file (e.g., a barrel export), manually merge the additions into the main working directory.
138
+
139
+ **When NOT to use worktree isolation:**
140
+ - Agents touch completely separate files → plain parallel dispatch (no isolation overhead).
141
+ - One agent depends on the other's output → sequential dispatch (await the blocker first).
142
+
100
143
  ## Agent type resolution
101
144
 
102
145
  Before dispatching, resolve the agent type for each role:
@@ -10,12 +10,10 @@ description: "Fastify 5 best practices, API reference, and patterns for routes,
10
10
  - [Request lifecycle](#request-lifecycle-exact-order)
11
11
  - [Top anti-patterns](#top-anti-patterns)
12
12
  - [Quick patterns](#quick-patterns)
13
- - [Plugin with fastify-plugin (FastifyPluginCallback)](#plugin-with-fastify-plugin-fastifyplugincallback)
14
- - [Route with validation](#route-with-validation)
15
- - [Hook (application-level)](#hook-application-level)
16
- - [Error handler](#error-handler)
17
13
  - [Reference files](#reference-files)
18
14
 
15
+ <quick_reference>
16
+
19
17
  ## Request lifecycle (exact order)
20
18
 
21
19
  ```
@@ -36,6 +34,10 @@ Incoming Request
36
34
 
37
35
  Error at any stage → `onError` hooks → error handler → `onSend` → response → `onResponse`.
38
36
 
37
+ </quick_reference>
38
+
39
+ <anti_patterns>
40
+
39
41
  ## Top anti-patterns
40
42
 
41
43
  1. **Mixing async/callback in handlers** — Use `async` OR callbacks, never both. With async, `return` the value; don't call `reply.send()` AND return.
@@ -58,6 +60,10 @@ Error at any stage → `onError` hooks → error handler → `onSend` → respon
58
60
 
59
61
  10. **Missing response schema** — Without `response` schema, Fastify serializes with `JSON.stringify()` (slow) and may leak sensitive fields. Use `fast-json-stringify` via response schemas.
60
62
 
63
+ </anti_patterns>
64
+
65
+ <examples>
66
+
61
67
  ## Quick patterns
62
68
 
63
69
  ### Plugin with fastify-plugin (FastifyPluginCallback)
@@ -130,6 +136,10 @@ fastify.setErrorHandler((error, request, reply) => {
130
136
  });
131
137
  ```
132
138
 
139
+ </examples>
140
+
141
+ <references>
142
+
133
143
  ## Reference files
134
144
 
135
145
  Load the relevant file when you need detailed API information:
@@ -141,3 +151,5 @@ Load the relevant file when you need detailed API information:
141
151
  - **Validation & serialization** — JSON Schema, Ajv, response schemas, custom validators: [references/validation-and-serialization.md](references/validation-and-serialization.md)
142
152
  - **Request, Reply & errors** — request/reply API, error handling, FST_ERR codes: [references/request-reply-errors.md](references/request-reply-errors.md)
143
153
  - **TypeScript & logging** — route generics, type providers, Pino config, decorators: [references/typescript-and-logging.md](references/typescript-and-logging.md)
154
+
155
+ </references>
@@ -4,9 +4,9 @@ description: "Generates a complete, structured, and implementation-ready Product
4
4
  argument-hint: "[product-idea | feature-description | business-context | prd-md-file-path]"
5
5
  ---
6
6
 
7
- <system>
7
+ <role>
8
8
  You are a Senior Product Manager and Product Strategist. Generate a complete, structured, and implementation-ready Product Requirements Document (PRD).
9
- </system>
9
+ </role>
10
10
 
11
11
  <spec>
12
12
  $ARGUMENTS
@@ -7,6 +7,8 @@ description: "ioredis v5 reference for Node.js Redis client — connection setup
7
7
 
8
8
  ioredis v5.x. Requires Node.js >= 12, Redis >= 2.6.12. 100% TypeScript.
9
9
 
10
+ <quick_reference>
11
+
10
12
  ## Critical: Import Style
11
13
 
12
14
  ```ts
@@ -17,15 +19,6 @@ import { Redis } from "ioredis";
17
19
  import { Redis, Cluster } from "ioredis";
18
20
  ```
19
21
 
20
- ## When to Load References
21
-
22
- | Need | Reference file |
23
- | ------------------------------------------------------------------------------ | -------------------------------------------------------------------- |
24
- | Connection setup, RedisOptions, TLS, retryStrategy, lifecycle | [references/connection-options.md](references/connection-options.md) |
25
- | Core API: pipelines, transactions, Pub/Sub, Lua scripting, scanning, events | [references/core-api.md](references/core-api.md) |
26
- | Streams, auto-pipelining, transformers, binary data, error handling, debugging | [references/advanced-patterns.md](references/advanced-patterns.md) |
27
- | Redis Cluster setup, ClusterOptions, Sentinel config, failover | [references/cluster-sentinel.md](references/cluster-sentinel.md) |
28
-
29
22
  ## Quick Reference
30
23
 
31
24
  | Operation | Code |
@@ -40,6 +33,10 @@ import { Redis, Cluster } from "ioredis";
40
33
  | Graceful close | `await redis.quit()` |
41
34
  | Force close | `redis.disconnect()` |
42
35
 
36
+ </quick_reference>
37
+
38
+ <gotchas>
39
+
43
40
  ## Common Gotchas
44
41
 
45
42
  1. **Named import**: Always `import { Redis } from "ioredis"` with NodeNext resolution
@@ -49,3 +46,18 @@ import { Redis, Cluster } from "ioredis";
49
46
  5. **`showFriendlyErrorStack`**: Performance cost — never enable in production
50
47
  6. **Cluster pipelines**: All keys in a pipeline must hash to slots served by the same node
51
48
  7. **`enableAutoPipelining`**: 35-50% throughput improvement, safe to enable globally
49
+
50
+ </gotchas>
51
+
52
+ <references>
53
+
54
+ ## When to Load References
55
+
56
+ | Need | Reference file |
57
+ | ------------------------------------------------------------------------------ | -------------------------------------------------------------------- |
58
+ | Connection setup, RedisOptions, TLS, retryStrategy, lifecycle | [references/connection-options.md](references/connection-options.md) |
59
+ | Core API: pipelines, transactions, Pub/Sub, Lua scripting, scanning, events | [references/core-api.md](references/core-api.md) |
60
+ | Streams, auto-pipelining, transformers, binary data, error handling, debugging | [references/advanced-patterns.md](references/advanced-patterns.md) |
61
+ | Redis Cluster setup, ClusterOptions, Sentinel config, failover | [references/cluster-sentinel.md](references/cluster-sentinel.md) |
62
+
63
+ </references>
@@ -9,27 +9,7 @@ Apply these rules when writing or reviewing Next.js code.
9
9
 
10
10
  > **Note:** Next.js 16 renamed `middleware.ts` to `proxy.ts`. Verify `proxy.ts` support in your version; `middleware.ts` remains the stable API.
11
11
 
12
- ## Table of Contents
13
-
14
- - [File Conventions](#file-conventions)
15
- - [RSC Boundaries](#rsc-boundaries)
16
- - [Async Patterns](#async-patterns)
17
- - [Runtime Selection](#runtime-selection)
18
- - [Directives](#directives)
19
- - [Functions](#functions)
20
- - [Error Handling](#error-handling)
21
- - [Data Patterns](#data-patterns)
22
- - [Route Handlers](#route-handlers)
23
- - [Metadata & OG Images](#metadata--og-images)
24
- - [Image Optimization](#image-optimization)
25
- - [Font Optimization](#font-optimization)
26
- - [Bundling](#bundling)
27
- - [Scripts](#scripts)
28
- - [Hydration Errors](#hydration-errors)
29
- - [Suspense Boundaries](#suspense-boundaries)
30
- - [Parallel & Intercepting Routes](#parallel--intercepting-routes)
31
- - [Self-Hosting](#self-hosting)
32
- - [Debug Tricks](#debug-tricks)
12
+ <references>
33
13
 
34
14
  ## File Conventions
35
15
 
@@ -192,3 +172,5 @@ See [debug-tricks.md](references/debug-tricks.md) for:
192
172
 
193
173
  - MCP endpoint for AI-assisted debugging
194
174
  - Rebuild specific routes with `--debug-build-paths`
175
+
176
+ </references>
@@ -5,6 +5,8 @@ description: "Review code and architectures against the OWASP Top 10:2025 — th
5
5
 
6
6
  # OWASP Top 10:2025 Security Review
7
7
 
8
+ <quick_reference>
9
+
8
10
  ## Quick reference
9
11
 
10
12
  | # | Category | Key risk | Avg incidence |
@@ -20,9 +22,23 @@ description: "Review code and architectures against the OWASP Top 10:2025 — th
20
22
  | A09 | Security Logging & Alerting Failures | Missing audit logs, no alerting, log injection, sensitive data in logs | 3.91% |
21
23
  | A10 | Mishandling of Exceptional Conditions | Failing open, info leakage via errors, unchecked return values | 2.95% |
22
24
 
25
+ ## Severity classification
26
+
27
+ Use these severity levels when reporting findings:
28
+
29
+ - **Critical**: Directly exploitable, leads to full system compromise or mass data breach (e.g., SQLi with no parameterization, hardcoded admin credentials, missing auth on admin endpoints).
30
+ - **High**: Exploitable with moderate effort, significant data exposure or privilege escalation (e.g., IDOR, weak password hashing, SSRF, deserialization of untrusted data).
31
+ - **Medium**: Exploitable under specific conditions, limited impact (e.g., missing CSRF protection, verbose error messages, missing security headers).
32
+ - **Low**: Defense-in-depth issue, minimal direct impact (e.g., missing rate limiting, incomplete logging, suboptimal crypto configuration).
33
+
34
+ </quick_reference>
35
+
36
+ <workflow>
37
+
23
38
  ## Workflows
24
39
 
25
- ### 1. Code review for security
40
+ <phase_1_code_review>
41
+ ### Code review for security
26
42
 
27
43
  Systematically check the code against each relevant category:
28
44
 
@@ -41,8 +57,10 @@ Priority order for review (highest impact first):
41
57
  - `[MEDIUM]` Error handling → A10 (Exceptional Conditions), A09 (Logging)
42
58
  - `[MEDIUM]` Architecture/design → A06 (Insecure Design)
43
59
  - `[MEDIUM]` Data integrity → A08 (Integrity Failures)
60
+ </phase_1_code_review>
44
61
 
45
- ### 2. Security audit checklist
62
+ <phase_2_audit_checklist>
63
+ ### Security audit checklist
46
64
 
47
65
  Generate a checklist for a feature or codebase:
48
66
 
@@ -50,8 +68,10 @@ Generate a checklist for a feature or codebase:
50
68
  2. For each of the 10 categories, determine if it applies.
51
69
  3. For applicable categories, load the reference file and produce a checklist of items to verify.
52
70
  4. Output a markdown checklist grouped by category.
71
+ </phase_2_audit_checklist>
53
72
 
54
- ### 3. Remediation guidance
73
+ <phase_3_remediation>
74
+ ### Remediation guidance
55
75
 
56
76
  When a vulnerability is identified:
57
77
 
@@ -59,6 +79,11 @@ When a vulnerability is identified:
59
79
  2. Load the corresponding reference file.
60
80
  3. Apply the prevention checklist to produce a specific, actionable fix.
61
81
  4. Provide a code example of the fix when possible.
82
+ </phase_3_remediation>
83
+
84
+ </workflow>
85
+
86
+ <references>
62
87
 
63
88
  ## Reference files
64
89
 
@@ -75,15 +100,8 @@ Load the relevant file when you need detailed guidance for a specific category:
75
100
  - **A09 Logging & Alerting** — audit trails, log injection, alerting, sensitive data in logs: [references/a09-logging-alerting-failures.md](references/a09-logging-alerting-failures.md)
76
101
  - **A10 Exceptional Conditions** — error handling, fail-closed, resource cleanup, info leakage: [references/a10-exceptional-conditions.md](references/a10-exceptional-conditions.md)
77
102
 
78
- ## Severity classification
79
-
80
- Use these severity levels when reporting findings:
81
-
82
- - **Critical**: Directly exploitable, leads to full system compromise or mass data breach (e.g., SQLi with no parameterization, hardcoded admin credentials, missing auth on admin endpoints).
83
- - **High**: Exploitable with moderate effort, significant data exposure or privilege escalation (e.g., IDOR, weak password hashing, SSRF, deserialization of untrusted data).
84
- - **Medium**: Exploitable under specific conditions, limited impact (e.g., missing CSRF protection, verbose error messages, missing security headers).
85
- - **Low**: Defense-in-depth issue, minimal direct impact (e.g., missing rate limiting, incomplete logging, suboptimal crypto configuration).
86
-
87
- ## Output format
103
+ </references>
88
104
 
105
+ <output>
89
106
  When reporting security findings, use the template in [template.md](template.md) for each finding.
107
+ </output>
@@ -7,6 +7,8 @@ description: "PostgreSQL 16+ reference for writing queries, designing schemas, m
7
7
 
8
8
  Version: **16+**. All syntax is standard; most features apply to PostgreSQL 13+.
9
9
 
10
+ <quick_reference>
11
+
10
12
  ## Quick patterns
11
13
 
12
14
  ```sql
@@ -24,6 +26,25 @@ WHERE relkind = 'r' ORDER BY pg_total_relation_size(oid) DESC;
24
26
  SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid = <pid>;
25
27
  ```
26
28
 
29
+ </quick_reference>
30
+
31
+ <rules>
32
+
33
+ ## Key non-obvious facts
34
+
35
+ - Every statement runs in a transaction. Without `BEGIN`, each statement auto-commits.
36
+ - `jsonb` stores parsed binary (faster queries); `json` stores raw text (exact input preserved). Prefer `jsonb`.
37
+ - `LIKE 'foo%'` can use B-tree; `LIKE '%foo'` cannot — use `pg_trgm` GIN for suffix search.
38
+ - `CREATE INDEX CONCURRENTLY` avoids table lock but cannot run inside a transaction block.
39
+ - `EXPLAIN` without `ANALYZE` shows the planner's _estimate_. Always use `EXPLAIN (ANALYZE, BUFFERS)` for real data.
40
+ - Null values are stored in indexes by B-tree (unlike some other databases). `IS NULL` can use an index.
41
+ - `SERIAL`/`BIGSERIAL` are shorthand for sequence + default; prefer `GENERATED ALWAYS AS IDENTITY` (SQL standard).
42
+ - Default isolation level is **Read Committed**. `SERIALIZABLE` prevents all anomalies but may abort transactions.
43
+
44
+ </rules>
45
+
46
+ <references>
47
+
27
48
  ## Reference files
28
49
 
29
50
  Load the relevant file when working on a specific topic:
@@ -38,13 +59,4 @@ Load the relevant file when working on a specific topic:
38
59
  | EXPLAIN output, VACUUM, stats | [references/performance.md](references/performance.md) | Query tuning or performance analysis |
39
60
  | psql meta-commands | [references/psql-cli.md](references/psql-cli.md) | Working interactively in psql |
40
61
 
41
- ## Key non-obvious facts
42
-
43
- - Every statement runs in a transaction. Without `BEGIN`, each statement auto-commits.
44
- - `jsonb` stores parsed binary (faster queries); `json` stores raw text (exact input preserved). Prefer `jsonb`.
45
- - `LIKE 'foo%'` can use B-tree; `LIKE '%foo'` cannot — use `pg_trgm` GIN for suffix search.
46
- - `CREATE INDEX CONCURRENTLY` avoids table lock but cannot run inside a transaction block.
47
- - `EXPLAIN` without `ANALYZE` shows the planner's _estimate_. Always use `EXPLAIN (ANALYZE, BUFFERS)` for real data.
48
- - Null values are stored in indexes by B-tree (unlike some other databases). `IS NULL` can use an index.
49
- - `SERIAL`/`BIGSERIAL` are shorthand for sequence + default; prefer `GENERATED ALWAYS AS IDENTITY` (SQL standard).
50
- - Default isolation level is **Read Committed**. `SERIALIZABLE` prevents all anomalies but may abort transactions.
62
+ </references>
@@ -7,18 +7,7 @@ description: "React and Next.js performance patterns. Use when writing, reviewin
7
7
 
8
8
  Performance optimization guide for React and Next.js applications, based on Vercel Engineering practices. 8 categories organized by impact.
9
9
 
10
- ## Table of Contents
11
-
12
- - [When to Apply](#when-to-apply)
13
- - [Quick Reference](#quick-reference)
14
- - [Async Patterns (CRITICAL)](#1-async-patterns-critical)
15
- - [Bundle Optimization (CRITICAL)](#2-bundle-optimization-critical)
16
- - [Server-Side Performance (HIGH)](#3-server-side-performance-high)
17
- - [Client-Side Patterns (MEDIUM-HIGH)](#4-client-side-patterns-medium-high)
18
- - [Re-render Optimization (MEDIUM)](#5-re-render-optimization-medium)
19
- - [Rendering Performance (MEDIUM)](#6-rendering-performance-medium)
20
- - [JavaScript Performance (LOW-MEDIUM)](#7-javascript-performance-low-medium)
21
- - [Advanced Patterns (LOW)](#8-advanced-patterns-low)
10
+ <constraints>
22
11
 
23
12
  ## When to Apply
24
13
 
@@ -27,6 +16,10 @@ Performance optimization guide for React and Next.js applications, based on Verc
27
16
  - Reviewing code for performance issues
28
17
  - Optimizing bundle size or load times
29
18
 
19
+ </constraints>
20
+
21
+ <references>
22
+
30
23
  ## Quick Reference
31
24
 
32
25
  ### 1. Async Patterns (CRITICAL)
@@ -108,3 +101,5 @@ Performance optimization guide for React and Next.js applications, based on Verc
108
101
 
109
102
  - Store event handlers in refs -- stable effect subscriptions
110
103
  - Initialize app once per load -- module-level guard
104
+
105
+ </references>
@@ -10,17 +10,12 @@ description: "Service Worker API implementation guide — registration, lifecycl
10
10
  - [Constraints](#constraints)
11
11
  - [Lifecycle](#lifecycle)
12
12
  - [Registration](#registration)
13
- - [Install Event Pre-cache Assets](#install-event--pre-cache-assets)
14
- - [Activate Event — Clean Up Old Caches](#activate-event--clean-up-old-caches)
15
- - [Fetch Event — Intercept Requests](#fetch-event--intercept-requests)
16
- - [Navigation Preload](#navigation-preload)
17
- - [Updating a Service Worker](#updating-a-service-worker)
18
- - [Communicating with Pages](#communicating-with-pages)
13
+ - [Install / Activate / Fetch Events](#install-event--pre-cache-assets)
19
14
  - [Common Pitfalls](#common-pitfalls)
20
- - [Push Notifications & Background Sync](#push-notifications--background-sync)
21
- - [API Quick Reference](#api-quick-reference)
22
15
  - [Next.js Integration](#nextjs-integration)
23
- - [DevTools](#devtools)
16
+ - [Reference files](#reference-files)
17
+
18
+ <constraints>
24
19
 
25
20
  ## Constraints
26
21
 
@@ -31,6 +26,10 @@ description: "Service Worker API implementation guide — registration, lifecycl
31
26
  - Scope defaults to the directory containing the SW file
32
27
  - `self` refers to `ServiceWorkerGlobalScope`
33
28
 
29
+ </constraints>
30
+
31
+ <quick_reference>
32
+
34
33
  ## Lifecycle
35
34
 
36
35
  ```
@@ -45,6 +44,27 @@ register() → Download → Install → [Wait] → Activate → Fetch control
45
44
 
46
45
  A document must reload to be controlled (or call `clients.claim()` during activate).
47
46
 
47
+ ## Updating a Service Worker
48
+
49
+ - Browser byte-compares the SW file on each navigation (or every 24h)
50
+ - New version installs in background while old version still serves
51
+ - Increment the cache name (e.g., `v1` → `v2`) in the new version
52
+ - Delete old caches in the `activate` handler
53
+ - Call `self.skipWaiting()` in `install` to activate immediately
54
+ - Call `self.clients.claim()` in `activate` to take control of open pages
55
+
56
+ ## DevTools
57
+
58
+ - **Chrome**: `chrome://inspect/#service-workers` or Application > Service Workers
59
+ - **Firefox**: `about:debugging#/runtime/this-firefox` or Application > Service Workers
60
+ - **Edge**: `edge://inspect/#service-workers` or Application > Service Workers
61
+
62
+ Unregister, update, and inspect caches from the Application panel. Use "Update on reload" checkbox during development.
63
+
64
+ </quick_reference>
65
+
66
+ <examples>
67
+
48
68
  ## Registration
49
69
 
50
70
  ```js
@@ -125,15 +145,6 @@ self.addEventListener("fetch", (event) => {
125
145
  });
126
146
  ```
127
147
 
128
- ## Updating a Service Worker
129
-
130
- - Browser byte-compares the SW file on each navigation (or every 24h)
131
- - New version installs in background while old version still serves
132
- - Increment the cache name (e.g., `v1` → `v2`) in the new version
133
- - Delete old caches in the `activate` handler
134
- - Call `self.skipWaiting()` in `install` to activate immediately
135
- - Call `self.clients.claim()` in `activate` to take control of open pages
136
-
137
148
  ## Communicating with Pages
138
149
 
139
150
  ```js
@@ -150,22 +161,6 @@ self.addEventListener("message", (event) => {
150
161
  });
151
162
  ```
152
163
 
153
- ## Common Pitfalls
154
-
155
- 1. **Response cloning** — `response.clone()` before both caching and returning, since body streams can only be read once
156
- 2. **Opaque responses** — cross-origin fetches without CORS return opaque responses (status 0). `cache.add()` will refuse them. Use `cache.put()` but you can't inspect the response
157
- 3. **waitUntil timing** — call `event.waitUntil()` synchronously within the event handler, not inside an async callback
158
- 4. **Scope ceiling** — a SW cannot control URLs above its own directory unless `Service-Worker-Allowed` header is set
159
- 5. **No state persistence** — the SW may terminate at any time when idle. Don't store state in global variables — use Cache API or IndexedDB
160
-
161
- ## Push Notifications & Background Sync
162
-
163
- For push subscription, handling push events, and background sync implementation, see [references/push-and-sync.md](references/push-and-sync.md).
164
-
165
- ## API Quick Reference
166
-
167
- For detailed interfaces (`Cache`, `CacheStorage`, `FetchEvent`, `Clients`, `ServiceWorkerRegistration`, `ServiceWorkerGlobalScope`), see [references/api-reference.md](references/api-reference.md).
168
-
169
164
  ## Next.js Integration
170
165
 
171
166
  In Next.js, place the service worker file in `public/sw.js`. `public/sw.js` is intentionally plain JS (not processed by Next.js build pipeline). Register it from a client component:
@@ -186,10 +181,26 @@ export function ServiceWorkerRegistrar() {
186
181
 
187
182
  Add to root layout. Next.js serves `public/` files at the root, so `/sw.js` scope covers `/`.
188
183
 
189
- ## DevTools
184
+ </examples>
190
185
 
191
- - **Chrome**: `chrome://inspect/#service-workers` or Application > Service Workers
192
- - **Firefox**: `about:debugging#/runtime/this-firefox` or Application > Service Workers
193
- - **Edge**: `edge://inspect/#service-workers` or Application > Service Workers
186
+ <gotchas>
194
187
 
195
- Unregister, update, and inspect caches from the Application panel. Use "Update on reload" checkbox during development.
188
+ ## Common Pitfalls
189
+
190
+ 1. **Response cloning** — `response.clone()` before both caching and returning, since body streams can only be read once
191
+ 2. **Opaque responses** — cross-origin fetches without CORS return opaque responses (status 0). `cache.add()` will refuse them. Use `cache.put()` but you can't inspect the response
192
+ 3. **waitUntil timing** — call `event.waitUntil()` synchronously within the event handler, not inside an async callback
193
+ 4. **Scope ceiling** — a SW cannot control URLs above its own directory unless `Service-Worker-Allowed` header is set
194
+ 5. **No state persistence** — the SW may terminate at any time when idle. Don't store state in global variables — use Cache API or IndexedDB
195
+
196
+ </gotchas>
197
+
198
+ <references>
199
+
200
+ ## Reference files
201
+
202
+ - **Caching strategies** (cache-first, network-first, stale-while-revalidate): [references/caching-strategies.md](references/caching-strategies.md)
203
+ - **Push notifications & background sync** (push subscription, push events, background sync): [references/push-and-sync.md](references/push-and-sync.md)
204
+ - **API quick reference** (`Cache`, `CacheStorage`, `FetchEvent`, `Clients`, `ServiceWorkerRegistration`, `ServiceWorkerGlobalScope`): [references/api-reference.md](references/api-reference.md)
205
+
206
+ </references>
@@ -13,6 +13,8 @@ description: |
13
13
 
14
14
  # TanStack Query v5 (React)
15
15
 
16
+ <quick_reference>
17
+
16
18
  ## Setup
17
19
 
18
20
  ```tsx
@@ -52,6 +54,10 @@ function App() {
52
54
 
53
55
  **Key recommendation:** Set `staleTime` above 0 to control refetch frequency rather than disabling individual refetch triggers.
54
56
 
57
+ </quick_reference>
58
+
59
+ <examples>
60
+
55
61
  ## queryOptions — co-locate key + fn
56
62
 
57
63
  Always use `queryOptions` to define query configurations. It enables type inference across `useQuery`, `prefetchQuery`, `getQueryData`, and `setQueryData`.
@@ -325,6 +331,10 @@ const { data } = useQuery({
325
331
 
326
332
  `skipToken` prevents `refetch()` from working — use `enabled: false` if you need manual refetch.
327
333
 
334
+ </examples>
335
+
336
+ <gotchas>
337
+
328
338
  ## setQueryData — immutability
329
339
 
330
340
  ```tsx
@@ -340,9 +350,15 @@ queryClient.setQueryData(['todo', id], (old) =>
340
350
  )
341
351
  ```
342
352
 
353
+ </gotchas>
354
+
355
+ <references>
356
+
343
357
  ## Further Reference
344
358
 
345
359
  - **Full API signatures** (useQuery, useMutation, useInfiniteQuery, QueryClient): See [references/api-reference.md](references/api-reference.md)
346
360
  - **SSR & Next.js** (hydration, App Router, streaming): See [references/ssr-nextjs.md](references/ssr-nextjs.md)
347
361
  - **Testing** (renderHook, mocking, setup): See [references/testing.md](references/testing.md)
348
362
  - **Advanced patterns** (TypeScript, Suspense, waterfalls, network modes): See [references/advanced-patterns.md](references/advanced-patterns.md)
363
+
364
+ </references>
@@ -7,6 +7,8 @@ description: "TypeScript coding conventions for strict, type-safe projects. Use
7
7
 
8
8
  Project-wide TypeScript standards that complement agent-specific instructions.
9
9
 
10
+ <rules>
11
+
10
12
  ## Type Safety
11
13
 
12
14
  - **No `any`**: Use `unknown` if the type is truly dynamic, then narrow.
@@ -43,9 +45,15 @@ import { Redis } from "ioredis";
43
45
  - **Query** (returns data): `get`, `find`, `list`, `fetch`
44
46
  - **Command** (changes state): `create`, `update`, `delete`, `add`, `remove`
45
47
 
48
+ </rules>
49
+
50
+ <anti_patterns>
51
+
46
52
  ## Anti-Patterns
47
53
 
48
54
  - **Primitive obsession**: Use branded types or Zod enums, not raw strings for IDs and statuses.
49
55
  - **Magic numbers/strings**: Use constants from a shared package (e.g., `RATE_LIMITS`, `PAGINATION`, `CACHE`).
50
56
  - **Long parameter lists**: Use an options object or a Zod schema.
51
57
  - **Premature abstraction**: Three similar lines > one premature helper. Abstract on the third repetition.
58
+
59
+ </anti_patterns>