@workingpayload/agent-skills 1.0.1 → 2.0.1

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 (130) hide show
  1. package/APIForge/skill.md +165 -0
  2. package/AccessPlus/skill.md +136 -0
  3. package/AlgoMaster/skill.md +125 -0
  4. package/Architekt AI/skill.md +140 -0
  5. package/AuthCraft/skill.md +144 -0
  6. package/AutoScriptor/skill.md +137 -0
  7. package/BoilerCore/skill.md +136 -0
  8. package/BugHunter Pro/skill.md +133 -0
  9. package/ChangeScribe/skill.md +113 -0
  10. package/CodeMap/skill.md +194 -0
  11. package/CodeSage/skill.md +163 -0
  12. package/CommitCraft/skill.md +113 -0
  13. package/CoverageMax/skill.md +161 -0
  14. package/CronGenius/skill.md +157 -0
  15. package/DataPolish/skill.md +142 -0
  16. package/DataWeaver/skill.md +151 -0
  17. package/DockMaster/skill.md +158 -0
  18. package/DocuGenie/skill.md +138 -0
  19. package/EdgeGuard/skill.md +160 -0
  20. package/EnvWizard/skill.md +156 -0
  21. package/ErrorMedic/skill.md +152 -0
  22. package/FeatureSmith/skill.md +139 -0
  23. package/FlexiLayout/skill.md +144 -0
  24. package/FlowTester/skill.md +154 -0
  25. package/FunctionForge/skill.md +136 -0
  26. package/InputShield/skill.md +144 -0
  27. package/IssueForge/skill.md +148 -0
  28. package/KubeCrafter/skill.md +149 -0
  29. package/LogicLens/skill.md +132 -0
  30. package/MockSmith/skill.md +146 -0
  31. package/ModelSensei/skill.md +138 -0
  32. package/PRMentor/skill.md +103 -0
  33. package/PerfDetective/skill.md +90 -0
  34. package/PipelinePro/skill.md +146 -0
  35. package/PolyglotShift/skill.md +94 -0
  36. package/PromptForge/skill.md +118 -0
  37. package/QueryPulse/skill.md +123 -0
  38. package/README.md +327 -216
  39. package/ReadMeCraft/skill.md +127 -0
  40. package/RefactorX/skill.md +110 -0
  41. package/RenderBoost/skill.md +148 -0
  42. package/SEOMancer/skill.md +156 -0
  43. package/ScrapeMaster/skill.md +157 -0
  44. package/SecretSniffer/skill.md +123 -0
  45. package/SecureScan/skill.md +130 -0
  46. package/ServiceSplitter/skill.md +153 -0
  47. package/SpeedSmith/skill.md +155 -0
  48. package/StackWise/skill.md +155 -0
  49. package/TaskOrchestrator/skill.md +135 -0
  50. package/TestCrafter/skill.md +158 -0
  51. package/TraceMind/skill.md +143 -0
  52. package/UISmith/skill.md +131 -0
  53. package/bin/cli.js +436 -0
  54. package/extension-extender/SKILL.md +122 -0
  55. package/fastapi-furious/SKILL.md +148 -0
  56. package/package.json +42 -32
  57. package/python-master/SKILL.md +108 -0
  58. package/react-ranger/SKILL.md +93 -0
  59. package/scripts/build_index.py +282 -0
  60. package/scripts/doctor.py +542 -0
  61. package/scripts/install.py +436 -0
  62. package/scripts/route.py +348 -0
  63. package/scripts/score.py +355 -0
  64. package/scripts/test_skill.py +501 -0
  65. package/scripts/validate.py +254 -0
  66. package/skills-routing.json +1156 -0
  67. package/skills.json +3389 -0
  68. package/cli.js +0 -181
  69. package/skills/APIForge/skill.md +0 -32
  70. package/skills/AccessPlus/skill.md +0 -32
  71. package/skills/AlgoMaster/skill.md +0 -32
  72. package/skills/Architekt AI/skill.md +0 -32
  73. package/skills/AuthCraft/skill.md +0 -32
  74. package/skills/AutoScriptor/skill.md +0 -32
  75. package/skills/BoilerCore/skill.md +0 -32
  76. package/skills/BugHunter Pro/skill.md +0 -32
  77. package/skills/ChangeScribe/skill.md +0 -32
  78. package/skills/CodeSage/skill.md +0 -32
  79. package/skills/CommitCraft/skill.md +0 -32
  80. package/skills/CoverageMax/skill.md +0 -32
  81. package/skills/CronGenius/skill.md +0 -32
  82. package/skills/DataPolish/skill.md +0 -32
  83. package/skills/DataWeaver/skill.md +0 -32
  84. package/skills/DockMaster/skill.md +0 -32
  85. package/skills/DocuGenie/skill.md +0 -32
  86. package/skills/EdgeGuard/skill.md +0 -32
  87. package/skills/EnvWizard/skill.md +0 -32
  88. package/skills/ErrorMedic/skill.md +0 -32
  89. package/skills/Extension-Extender/SKILL.md +0 -41
  90. package/skills/Extension-Extender/references/ui-guidelines.md +0 -26
  91. package/skills/Fastapi-Furious/README.md +0 -16
  92. package/skills/Fastapi-Furious/SKILL.md +0 -37
  93. package/skills/FeatureSmith/skill.md +0 -32
  94. package/skills/FlexiLayout/skill.md +0 -32
  95. package/skills/FlowTester/skill.md +0 -32
  96. package/skills/FunctionForge/skill.md +0 -32
  97. package/skills/InputShield/skill.md +0 -32
  98. package/skills/IssueForge/skill.md +0 -32
  99. package/skills/KubeCrafter/skill.md +0 -32
  100. package/skills/LogicLens/skill.md +0 -32
  101. package/skills/MockSmith/skill.md +0 -32
  102. package/skills/ModelSensei/skill.md +0 -32
  103. package/skills/PRMentor/skill.md +0 -32
  104. package/skills/PerfDetective/skill.md +0 -32
  105. package/skills/PipelinePro/skill.md +0 -32
  106. package/skills/PolyglotShift/skill.md +0 -32
  107. package/skills/PromptForge/skill.md +0 -32
  108. package/skills/Python-Master/README.md +0 -11
  109. package/skills/Python-Master/SKILL.md +0 -37
  110. package/skills/QueryPulse/skill.md +0 -32
  111. package/skills/React-Ranger/README.md +0 -17
  112. package/skills/React-Ranger/SKILL.md +0 -37
  113. package/skills/ReadMeCraft/skill.md +0 -32
  114. package/skills/RefactorX/skill.md +0 -32
  115. package/skills/RenderBoost/skill.md +0 -32
  116. package/skills/SEOMancer/skill.md +0 -32
  117. package/skills/ScrapeMaster/skill.md +0 -32
  118. package/skills/SecretSniffer/skill.md +0 -32
  119. package/skills/SecureScan/skill.md +0 -32
  120. package/skills/ServiceSplitter/skill.md +0 -32
  121. package/skills/SpeedSmith/skill.md +0 -32
  122. package/skills/StackWise/skill.md +0 -32
  123. package/skills/TaskOrchestrator/skill.md +0 -32
  124. package/skills/TestCrafter/skill.md +0 -32
  125. package/skills/TraceMind/skill.md +0 -32
  126. package/skills/UISmith/skill.md +0 -32
  127. /package/{skills/Extension-Extender → extension-extender}/assets/manifest.json +0 -0
  128. /package/{skills/Extension-Extender → extension-extender}/assets/popup.css +0 -0
  129. /package/{skills/Extension-Extender → extension-extender}/assets/popup.html +0 -0
  130. /package/{skills/Extension-Extender → extension-extender}/assets/popup.js +0 -0
@@ -0,0 +1,155 @@
1
+ ---
2
+ name: speedsmith
3
+ description: Implements performance optimizations for web applications including caching strategies, asset delivery, code splitting, and image optimization. Use when asked to improve page load times, reduce latency, optimize assets, or fix Core Web Vitals scores.
4
+ ---
5
+
6
+ # SpeedSmith
7
+
8
+ ## Overview
9
+
10
+ Diagnoses and fixes web performance bottlenecks using a measurement-first approach. Tools: Lighthouse CI, WebPageTest, Chrome DevTools Performance panel, and bundle analyzers. Covers CDN configuration, HTTP caching, Redis/in-memory caching, code splitting, tree-shaking, and next-gen image formats. Never optimize without first establishing a baseline metric.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Measure Before Optimizing
15
+
16
+ Establish baselines before touching code:
17
+
18
+ ```bash
19
+ # Lighthouse CLI baseline
20
+ npx lighthouse https://example.com --output=json --output-path=baseline.json \
21
+ --preset=desktop --throttling-method=simulate
22
+
23
+ # Bundle analysis (webpack)
24
+ npx webpack-bundle-analyzer stats.json
25
+
26
+ # Bundle analysis (Vite)
27
+ npx vite-bundle-visualizer
28
+
29
+ # WebPageTest API
30
+ curl "https://www.webpagetest.org/runtest.php?url=https://example.com&f=json&k=YOUR_KEY"
31
+ ```
32
+
33
+ Record: LCP, INP, CLS, TTI, TBT, total transfer size, number of requests, TTFB.
34
+
35
+ Set target thresholds before starting:
36
+ - LCP ≤ 2.5s, INP ≤ 200ms, CLS ≤ 0.1 (Core Web Vitals "Good" thresholds)
37
+ - Total page weight ≤ 500KB compressed for above-the-fold content
38
+
39
+ ### 2. HTTP Caching Strategy
40
+
41
+ Apply appropriate cache headers per resource type:
42
+
43
+ | Resource Type | Cache-Control | CDN Behavior |
44
+ |---------------|--------------|--------------|
45
+ | Hashed static assets (JS, CSS) | `public, max-age=31536000, immutable` | Cache indefinitely |
46
+ | Images (hashed filenames) | `public, max-age=31536000, immutable` | Cache indefinitely |
47
+ | HTML pages | `public, max-age=0, must-revalidate` + ETag | CDN respects, revalidate on each request |
48
+ | API responses (public, stable) | `public, max-age=300, s-maxage=600` | CDN caches 10 min |
49
+ | API responses (user-specific) | `private, max-age=60` | Do not cache at CDN |
50
+ | Service Worker cached | Stale-while-revalidate via SW | Bypass CDN for SW-handled routes |
51
+
52
+ Use **content-addressable filenames** (webpack `[contenthash]`, Vite default behavior) to enable `immutable` caching safely.
53
+
54
+ ### 3. CDN Configuration
55
+
56
+ - **Cloudflare**: Enable "Cache Everything" page rule for static assets. Use Cache Rules with `Cache Status: Cache` for `/assets/*`. Enable Argo Smart Routing for dynamic content.
57
+ - **AWS CloudFront**: Set `DefaultCacheBehavior` TTL to 86400 for static paths. Use Lambda@Edge or CloudFront Functions for header manipulation. Enable HTTP/3 (QUIC) and Brotli compression.
58
+ - **Fastly/Akamai**: Configure origin shield (shielding) to reduce origin load.
59
+
60
+ CDN must-haves: HTTP/2 or HTTP/3 push, Brotli compression, TLS 1.3, HSTS preloading.
61
+
62
+ ### 4. Redis / Application-Level Caching
63
+
64
+ Cache-aside pattern: check Redis → on miss, compute and `setex` with TTL. Strategies: TTL-based (simple), event-driven invalidation (publish on write), write-through (write to both simultaneously). Always include user/tenant ID in cache keys for multi-tenant systems. Never share cache keys across tenants.
65
+
66
+ ### 5. JavaScript Optimization
67
+
68
+ **Code splitting** (webpack/Vite):
69
+ ```javascript
70
+ // Route-based splitting (React)
71
+ const Dashboard = React.lazy(() => import('./pages/Dashboard'));
72
+
73
+ // Manual chunk splitting (Vite)
74
+ // vite.config.ts
75
+ build: {
76
+ rollupOptions: {
77
+ output: {
78
+ manualChunks: {
79
+ vendor: ['react', 'react-dom'],
80
+ charts: ['recharts', 'd3'],
81
+ }
82
+ }
83
+ }
84
+ }
85
+ ```
86
+
87
+ **Tree-shaking**: Ensure all imports are named (not `import * as`). Use `"sideEffects": false` in `package.json` for pure utility libraries. Verify with bundle analyzer that dead code is eliminated.
88
+
89
+ **Script loading**: Use `defer` for non-critical scripts. Use `type="module"` which is deferred by default. Use dynamic `import()` for features triggered by user interaction.
90
+
91
+ **Reduce main thread blocking**: Tasks over 50ms block the main thread. Use `scheduler.yield()` to break up long tasks:
92
+ ```javascript
93
+ async function processLargeList(items) {
94
+ for (let i = 0; i < items.length; i++) {
95
+ process(items[i]);
96
+ if (i % 100 === 0) await scheduler.yield(); // yield to browser
97
+ }
98
+ }
99
+ ```
100
+
101
+ ### 6. Image Optimization
102
+
103
+ Use AVIF (best compression) → WebP (fallback) → JPEG. SVG for all icons. Use `<picture>` with `<source type="image/avif">` and `<source type="image/webp">`. Set explicit `width`/`height` on all `<img>` to prevent CLS. Add `fetchpriority="high"` on the LCP image and `loading="lazy"` on below-fold images. Use a CDN image transform service (Cloudinary, Imgix) instead of manual exports.
104
+
105
+ ### 7. Font Optimization
106
+
107
+ ```html
108
+ <link rel="preconnect" href="https://fonts.googleapis.com">
109
+ <link rel="preload" href="/fonts/inter-var.woff2" as="font" type="font/woff2" crossorigin>
110
+ ```
111
+
112
+ ```css
113
+ @font-face {
114
+ font-family: 'Inter';
115
+ src: url('/fonts/inter-var.woff2') format('woff2');
116
+ font-display: optional; /* CLS=0; use 'swap' if text must render immediately */
117
+ size-adjust: 100%;
118
+ }
119
+ ```
120
+
121
+ Subset fonts to used character sets with `pyftsubset` or `fonttools`.
122
+
123
+ ### 8. Output Artifacts
124
+
125
+ Produce:
126
+ 1. **Before/After metrics table**: LCP, INP, CLS, TTI, transfer size — baseline vs. projected.
127
+ 2. **Prioritized optimization list**: ordered by estimated impact, effort (low/medium/high), and risk.
128
+ 3. **Code snippets**: ready-to-implement cache headers, config changes, code splits.
129
+ 4. **Lighthouse CI config** for regression prevention:
130
+ ```yaml
131
+ ci:
132
+ assert:
133
+ assertions:
134
+ largest-contentful-paint: [error, { maxNumericValue: 2500 }]
135
+ cumulative-layout-shift: [error, { maxNumericValue: 0.1 }]
136
+ ```
137
+
138
+ ## Edge Cases
139
+
140
+ **Synchronous localStorage jank:** `localStorage.getItem/setItem` are synchronous and block the main thread, causing INP spikes on slower devices. Move large or frequent reads to IndexedDB (async) or cache the value in a module-level variable on first read and write back lazily.
141
+
142
+ **Bundle size CI gating:** Prevent bundle regressions with `size-limit` or `bundlesize`. Add to CI:
143
+ ```json
144
+ // package.json
145
+ "size-limit": [{ "path": "dist/index.js", "limit": "50 KB" }]
146
+ ```
147
+ Run `npx size-limit` in CI and fail the build if the limit is exceeded. This catches accidental large-dependency imports before they reach production.
148
+
149
+ **Origin TTFB diagnosis:** High TTFB (> 600ms) is a server-side problem. Check in order: (1) slow DB query — enable query logging and look for queries > 100ms; (2) cold start — serverless functions have 200–2000ms cold start; keep functions warm or use edge runtimes; (3) connection pool exhaustion — check pool wait time metrics; increase pool size or reduce query duration.
150
+
151
+ **Third-party scripts:** Load analytics and chat widgets with `async`/`defer` or after the `load` event. Use `<link rel="dns-prefetch">` for third-party domains.
152
+
153
+ **SSR hydration overhead:** SSR with full hydration can produce high TTI. Consider partial hydration (Astro islands), streaming SSR, or React Server Components to reduce client JS.
154
+
155
+ **CDN cache poisoning:** Never cache responses with user-specific data without `private` cache-control. Use `Vary: Accept-Encoding` (not `Vary: User-Agent`) for Brotli/gzip variants.
@@ -0,0 +1,155 @@
1
+ ---
2
+ name: stackwise
3
+ description: Advises on technology stack selection, evaluates library trade-offs, and produces Architecture Decision Records (ADRs). Use when asked to choose a framework, compare libraries, evaluate tech stack options, or document architectural decisions with rejected alternatives.
4
+ ---
5
+
6
+ # StackWise
7
+
8
+ ## Overview
9
+
10
+ Produces structured technology evaluations that account for team context, project constraints, and long-term maintainability. Output format is an Architecture Decision Record (ADR) with a scored evaluation rubric, library health metrics, and explicit documentation of rejected alternatives. No generic "it depends" answers — every recommendation is justified with concrete criteria.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Requirements Gathering
15
+
16
+ Before evaluating options, establish:
17
+
18
+ **Functional requirements**:
19
+ - What does the technology need to do? (e.g., "serve 10k req/s REST API", "render server-side HTML with dynamic data", "run ML inference on edge devices")
20
+ - What integrations are mandatory? (existing DBs, auth providers, cloud platform)
21
+ - What data/traffic scale is expected at launch and in 2 years?
22
+
23
+ **Non-functional constraints**:
24
+ - Team language/ecosystem familiarity (don't recommend Rust to a Python-only team without explicit buy-in)
25
+ - Deployment target: serverless, containers (Kubernetes), PaaS, edge runtime
26
+ - Licensing constraints: AGPL/GPL incompatibility with proprietary codebase?
27
+ - Compliance: HIPAA, PCI-DSS, GDPR — some require specific data handling capabilities
28
+ - Time to first production: weeks vs. months affects acceptable learning curve
29
+
30
+ **Team context**:
31
+ - Team size and experience level
32
+ - Existing stack to minimize cognitive overhead ("boring technology" preference)
33
+ - Open source vs. commercial support appetite
34
+
35
+ ### 2. Evaluation Rubric
36
+
37
+ Score each candidate (1–5 per criterion) with weights adjusted to project context:
38
+
39
+ | Criterion | Weight (default) | Notes |
40
+ |-----------|-----------------|-------|
41
+ | Ecosystem maturity | 20% | Years in production, major adopters, LTS policy |
42
+ | Performance fit | 20% | Benchmarks relevant to the workload type |
43
+ | Developer experience | 15% | TypeScript types, documentation quality, error messages |
44
+ | Library health | 15% | See Section 3 |
45
+ | Operational complexity | 15% | Deployment, monitoring, debugging tooling |
46
+ | Community & support | 10% | GitHub stars trend, Stack Overflow activity, commercial support availability |
47
+ | Migration cost | 5% | Cost to switch away if the choice is wrong |
48
+
49
+ Weighted score = sum of (score × weight). Document numerical scores, not just opinions.
50
+
51
+ ### 3. Library Health Metrics
52
+
53
+ For every candidate library, check:
54
+
55
+ | Metric | Tool / Source | Threshold |
56
+ |--------|--------------|-----------|
57
+ | Release recency | GitHub releases | Last release < 12 months |
58
+ | Issue response time | GitHub Insights | Median < 14 days |
59
+ | Open CVEs | `npm audit` / `pip-audit` / OSV.dev | Zero critical/high unpatched CVEs |
60
+ | npm weekly downloads | npmjs.com stats | > 100k/week for production dependency |
61
+ | PyPI download trend | pypistats.org | Stable or growing 6-month trend |
62
+ | Dependents count | GitHub "Used by" | Proxy for ecosystem lock-in risk |
63
+ | Bus factor | git log analysis | > 3 regular contributors |
64
+ | License | SPDX identifier | Compatible with project license (MIT/Apache-2.0 preferred) |
65
+
66
+ Flag libraries with: single maintainer, no releases in 18+ months, high CVE backlog, or license mismatch.
67
+
68
+ ### 4. Technology-Specific Comparison Patterns
69
+
70
+ **Frontend framework selection** (React vs. Vue vs. Svelte vs. SolidJS):
71
+ - Evaluate: bundle size, SSR/SSG capabilities, TypeScript quality, ecosystem (component libraries, state management), hiring pool.
72
+ - Key differentiators: React = largest ecosystem; Svelte/Solid = smaller bundles; Vue = gentler learning curve.
73
+
74
+ **Backend framework selection** (Express vs. Fastify vs. NestJS vs. Hono for Node; FastAPI vs. Django vs. Flask for Python):
75
+ - Evaluate: throughput benchmarks (TechEmpower), built-in validation, OpenAPI generation, middleware ecosystem.
76
+ - Key differentiators: Fastify > Express on throughput; NestJS adds structure but heavier; FastAPI = auto-OpenAPI + async.
77
+
78
+ **Database selection** (PostgreSQL vs. MySQL vs. MongoDB vs. DynamoDB vs. CockroachDB):
79
+ - Evaluate: ACID guarantees, query flexibility, horizontal scaling model, managed cloud options.
80
+ - Default: PostgreSQL unless workload specifically requires document flexibility (MongoDB), global horizontal scale (CockroachDB/Spanner), or serverless cost model (DynamoDB).
81
+
82
+ **Caching layer** (Redis vs. Memcached vs. DragonflyDB):
83
+ - Redis: persistence, pub/sub, Lua scripting, cluster mode — default choice.
84
+ - Memcached: simpler, marginally faster for pure string cache — only if Redis features unneeded.
85
+ - DragonflyDB: Redis-compatible, multi-threaded, lower memory — evaluate if Redis memory cost is a bottleneck.
86
+
87
+ ### 5. ADR Output Format
88
+
89
+ Produce every recommendation as an ADR:
90
+
91
+ ```markdown
92
+ # ADR-001: API Framework Selection for Payment Service
93
+
94
+ ## Status
95
+ Accepted | 2024-03-15
96
+
97
+ ## Context
98
+ We are building a payment processing microservice in Python expected to handle
99
+ 5,000 req/s. The team has strong Python experience. We need auto-generated OpenAPI
100
+ docs and async support for calling downstream payment gateways.
101
+
102
+ ## Decision
103
+ Use **FastAPI** with **Uvicorn** (ASGI) as the API framework.
104
+
105
+ ## Evaluation
106
+
107
+ | Criterion | FastAPI (score) | Django REST (score) | Flask (score) |
108
+ |---------------------|----------------|---------------------|---------------|
109
+ | Ecosystem maturity | 4 | 5 | 5 |
110
+ | Performance fit | 5 | 3 | 3 |
111
+ | Developer experience| 5 | 4 | 3 |
112
+ | Library health | 5 | 5 | 4 |
113
+ | Operational complexity| 4 | 3 | 4 |
114
+ | **Weighted Total** | **4.65** | **3.90** | **3.75** |
115
+
116
+ ## Rationale
117
+ FastAPI's native async support eliminates thread pool overhead when calling
118
+ payment gateway APIs (avg 200ms latency). Auto-generated OpenAPI schema removes
119
+ manual documentation maintenance. Pydantic v2 validation is 5–10x faster than
120
+ DRF serializers for our data shapes.
121
+
122
+ ## Rejected Alternatives
123
+ - **Django REST Framework**: Excellent for CRUD APIs with ORM but sync-by-default
124
+ adds unnecessary complexity for async-heavy workload. Migration to async views
125
+ is incomplete as of Django 4.2.
126
+ - **Flask**: Too minimal; would require adding marshmallow/apispec manually for
127
+ validation and docs. Higher integration maintenance cost.
128
+
129
+ ## Consequences
130
+ - Team must learn FastAPI patterns (dependency injection, Pydantic models).
131
+ - Uvicorn + Gunicorn deployment is less familiar than Django's WSGI setup.
132
+ - Mitigation: 2-day internal workshop before sprint 1.
133
+ ```
134
+
135
+ ### 6. Avoid These Anti-Patterns
136
+
137
+ - Choosing a technology because it's trending on HN/X — evaluate against actual requirements.
138
+ - Recommending a rewrite from a working stack without quantifying the migration cost and business risk.
139
+ - Picking microservices/distributed architecture for a team of < 5 engineers — operational overhead outweighs benefits.
140
+ - Choosing unproven (< 1 year old, < 1.0 release) libraries for production critical paths.
141
+ - Ignoring the existing team's expertise — a 20% performance gain is not worth a 6-month ramp-up.
142
+
143
+ ## Edge Cases
144
+
145
+ **Post-decision monitoring:** After a technology is adopted, schedule a review at 6 months and 12 months. Review triggers: library goes unmaintained (no releases in 12 months, maintainer announces EOL), critical unpatched CVE, major version breaking change, or team dissatisfaction score drops below threshold. Document the review criteria in the ADR's Consequences section so the team knows when to revisit.
146
+
147
+ **Compliance hard-blocking disqualifiers:** Certain choices are non-negotiable regardless of rubric score. Examples: AGPL-licensed library in a proprietary SaaS product (distribution triggers copyleft), data residency requirements that rule out specific cloud regions, FIPS-140-2 requirement that rules out non-certified crypto libraries. Evaluate compliance blockers before scoring — a blocked option should not appear in the rubric at all.
148
+
149
+ **RFC/spike process for tie votes:** When the evaluation rubric produces a tie (within 0.3 points) and team discussion does not converge, run a time-boxed technical spike: one engineer builds a proof-of-concept with each finalist option for 2–3 days, then presents findings to the team. Vote after the spike. Document the spike outcome in the ADR. This prevents indefinite debate and grounds the decision in hands-on evidence.
150
+
151
+ **Greenfield vs. brownfield context**: For brownfield, always evaluate migration cost as a first-class criterion. A technically superior option that requires migrating 200k lines of code is often the wrong choice. Prefer "good enough and migratable" over "theoretically best but costly to adopt."
152
+
153
+ **Vendor lock-in analysis**: For managed services (Firebase, PlanetScale, Neon, Vercel), assess: What is the data export story? What is the cost at 10x current scale? Is there a self-hosted option if the vendor changes pricing? Document lock-in risk in the ADR's Consequences section.
154
+
155
+ **When options are genuinely equivalent**: If two options score within 0.3 of each other on the weighted rubric, choose based on: (1) team familiarity, (2) existing organizational investment (training, tooling, expertise). Document the tie-breaking rationale explicitly — do not leave it as "we chose X" without justification.
@@ -0,0 +1,135 @@
1
+ ---
2
+ name: taskorchestrator
3
+ description: Designs and implements asynchronous task queues, distributed workflows, and worker orchestration systems. Use when asked to build job queues, implement background workers, design saga workflows, handle retry logic, or configure dead-letter queues with Celery, BullMQ, or Temporal.
4
+ ---
5
+
6
+ # TaskOrchestrator
7
+
8
+ ## Overview
9
+
10
+ Designs production-grade task orchestration systems using Celery (Python), BullMQ (Node.js), or Temporal (polyglot). Covers queue topology, worker concurrency, retry strategies with exponential backoff, dead-letter queues, idempotency, saga orchestration, and backpressure. Every design decision is justified against the specific failure mode it addresses.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Tool Selection
15
+
16
+ Choose the orchestration tool based on the workload profile:
17
+
18
+ | Tool | Language | Best For | Avoid When |
19
+ |------|----------|----------|------------|
20
+ | **Celery** | Python | High-throughput task queues, ML pipelines, Django/Flask integration | Long-running workflows with complex state; use Temporal instead |
21
+ | **BullMQ** | Node.js/TypeScript | Job queues with Redis backend, UI dashboard (Bull Board), rate limiting | Large Python teams; missing native workflow orchestration |
22
+ | **Temporal** | Python/Go/Java/TS | Long-running workflows, saga orchestration, durable execution with replay | Simple fire-and-forget tasks; adds operational overhead |
23
+ | **Celery + Kombu** | Python | When broker flexibility needed (RabbitMQ, SQS, Redis) | |
24
+ | **AWS SQS + Lambda** | Any | Serverless, event-driven, AWS-native; no infra to manage | Tasks > 15 min, complex orchestration logic |
25
+ | **Inngest / Trigger.dev** | TypeScript | Serverless-first Node.js workflows with built-in retries | Non-TypeScript stacks |
26
+
27
+ ### 2. Queue Topology Design
28
+
29
+ Design queues before writing code:
30
+
31
+ ```
32
+ Priority queues: critical > high > default > low
33
+ - critical: payment processing, auth tokens
34
+ - high: user-triggered actions (export, import)
35
+ - default: background enrichment, notifications
36
+ - low: analytics, cleanup, maintenance tasks
37
+
38
+ Dead-letter queues: every queue has a corresponding DLQ
39
+ - orders.queue → orders.dlq
40
+ - emails.queue → emails.dlq
41
+ ```
42
+
43
+ **Celery:** Use `task_routes` to map task name patterns to queue names. Set `x-max-priority: 10` on the critical queue.
44
+
45
+ **BullMQ:**
46
+ ```typescript
47
+ const paymentQueue = new Queue('payments', {
48
+ connection: redis,
49
+ defaultJobOptions: { attempts: 5, backoff: { type: 'exponential', delay: 2000 },
50
+ removeOnComplete: { count: 1000 }, removeOnFail: { count: 5000 } }
51
+ });
52
+ ```
53
+
54
+ ### 3. Retry Strategy with Exponential Backoff
55
+
56
+ Use `retry_delay = min(base * 2^attempt + jitter, max_delay)`. Never fixed-interval retries.
57
+
58
+ **Celery:** `@celery_app.task(retry_backoff=True, retry_backoff_max=600, retry_jitter=True, max_retries=5)`. Raise `self.reject(requeue=False)` for permanent errors (invalid card, validation failure).
59
+
60
+ **Temporal:** Configure `RetryPolicy(initial_interval=2s, backoff_coefficient=2.0, maximum_attempts=5, non_retryable_error_types=["PermanentPaymentError"])` on `execute_activity`.
61
+
62
+ Distinguish retryable (network, 429, 5xx) from non-retryable (validation, 4xx, business rule violations).
63
+
64
+ ### 4. Idempotency Keys
65
+
66
+ Every task that produces side effects must be idempotent:
67
+
68
+ ```python
69
+ # Pattern: idempotency key stored in DB with unique constraint
70
+ def send_email_idempotent(email_id: str, recipient: str, subject: str):
71
+ idempotency_key = f"email:{email_id}:{recipient}"
72
+
73
+ with db.transaction():
74
+ # Attempt insert; if it already exists, this email was already sent
75
+ try:
76
+ db.execute(
77
+ "INSERT INTO processed_tasks (idempotency_key, processed_at) VALUES (?, NOW())",
78
+ (idempotency_key,)
79
+ )
80
+ except UniqueConstraintError:
81
+ logger.info(f"Task already processed: {idempotency_key}")
82
+ return # idempotent no-op
83
+
84
+ # Only runs if insert succeeded (first time)
85
+ email_service.send(recipient, subject)
86
+ ```
87
+
88
+ Use UUID v4 or content-based hash as idempotency key. Store in Redis with TTL for short-lived tasks, or in a DB table for audit trail requirements.
89
+
90
+ ### 5. Dead-Letter Queue Handling
91
+
92
+ DLQs catch tasks that exhausted all retries. Never leave DLQs unmonitored:
93
+ 1. **Alert**: when DLQ depth > threshold (e.g., > 10 messages in `payments.dlq`).
94
+ 2. **Inspect**: Log task ID, queue, attempt count, last error, timestamp when routing to DLQ.
95
+ 3. **Reprocess**: fix root cause first, then replay via `queue.retryJobs()` (BullMQ) or re-queue (Celery).
96
+ 4. **Retention**: Keep DLQ messages 14 days minimum.
97
+
98
+ ```python
99
+ # Celery dead-letter with RabbitMQ
100
+ Queue('default', queue_arguments={
101
+ 'x-dead-letter-exchange': 'dlx',
102
+ 'x-dead-letter-routing-key': 'default.dlq',
103
+ })
104
+ ```
105
+
106
+ ### 6. Backpressure
107
+
108
+ - **Celery**: `worker_prefetch_multiplier=1` prevents pre-fetching excess tasks. `task_acks_late=True` prevents loss on worker crash.
109
+ - **BullMQ**: Set `concurrency` and `limiter: { max: 100, duration: 60000 }` on the Worker.
110
+ - **Temporal**: `WorkerOptions.max_concurrent_activity_task_executions` limits parallelism. Use `workflow.pause()` if the downstream is unhealthy.
111
+
112
+ ### 7. Monitoring and Observability
113
+
114
+ Key metrics per queue: task throughput (tasks/sec), queue depth (lag > 5 min = alert for high-priority), error rate (> 1% = alert on critical queues), worker saturation.
115
+
116
+ ```python
117
+ @task_failure.connect
118
+ def on_task_failure(task_id, exception, sender, **kwargs):
119
+ metrics.increment('celery.task.failure', tags=[f'task:{sender.name}'])
120
+ logger.error("Task failed", extra={"task_id": task_id, "error": str(exception)})
121
+ ```
122
+
123
+ Use **Flower** (Celery) or **Bull Board** (BullMQ) for dashboards. Temporal Cloud provides built-in workflow visibility.
124
+
125
+ ## Additional Patterns
126
+
127
+ **Temporal determinism requirement:** Temporal workflows are replayed from event history to resume after crashes. This means workflow code must be fully deterministic: never call `datetime.now()`, `random.random()`, `uuid4()`, or any I/O (DB, HTTP, filesystem) directly in the workflow body. All non-deterministic operations must be placed in activities. Use `workflow.now()` for current time and `workflow.uuid4()` for IDs inside workflows.
128
+
129
+ ## Edge Cases
130
+
131
+ **Long-running tasks and worker restarts**: For tasks that run > 5 minutes, use Temporal's durable execution (workflows survive worker restarts via event sourcing replay) or implement a heartbeat mechanism in Celery (`self.update_state(state='PROGRESS')` + monitor for stale heartbeats). Never run long tasks in a queue designed for fast tasks — separate pools.
132
+
133
+ **Task deduplication**: Prevent the same logical task from being enqueued twice (e.g., double-click on "Export" button). Implement deduplication at enqueue time: check for an in-progress job with the same key before adding to the queue. BullMQ supports `jobId` deduplication natively. For Celery, use Redis `SET NX` with TTL as a distributed lock before calling `.apply_async()`.
134
+
135
+ **Poison pill messages**: A malformed message that always causes a task to crash will cycle through retries and fill the DLQ. Detect by inspecting DLQ for repeated task signatures. Add a payload validation step at the start of every task handler that raises a non-retryable exception on schema validation failure — this routes malformed messages to DLQ immediately without wasting retry attempts.
@@ -0,0 +1,158 @@
1
+ ---
2
+ name: testcrafter
3
+ description: Writes unit and integration tests using Jest, Vitest, Pytest, or JUnit following the AAA pattern and test pyramid principles. Use when asked to write tests, improve test coverage, set up a testing strategy, configure CI test gates, or decide between mocking vs. real implementations.
4
+ ---
5
+
6
+ # TestCrafter
7
+
8
+ ## Overview
9
+
10
+ Produces high-quality, maintainable tests following the AAA (Arrange-Act-Assert) pattern, test pyramid principles, and clear naming conventions. Framework-specific guidance for Jest/Vitest (JavaScript/TypeScript), Pytest (Python), and JUnit 5 (Java). Targets 80% line coverage as a floor, with emphasis on testing behavior over implementation.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Test Pyramid Strategy
15
+
16
+ Before writing tests, identify the appropriate layer:
17
+
18
+ ```
19
+ /\
20
+ /E2E\ ~5% — Playwright/Cypress/Selenium; slow, costly, high confidence
21
+ /------\
22
+ /Integr. \ ~20% — DB, HTTP, message queue integration; real dependencies
23
+ /----------\
24
+ / Unit Tests \ ~75% — Pure logic, isolated, fast (< 10ms each)
25
+ /--------------\
26
+ ```
27
+
28
+ **Unit tests**: Test one function/class in isolation. Mock all external dependencies (DB, HTTP, filesystem, time). Goal: < 10ms per test, no I/O.
29
+
30
+ **Integration tests**: Test the interaction between components (e.g., repository + real DB, HTTP handler + real router). Use test containers (Testcontainers library) or an in-memory DB (SQLite for PostgreSQL compatibility testing, `mongomock` for MongoDB).
31
+
32
+ **E2E tests**: Test the full user journey through the real UI. Reserve for critical paths only (login, checkout, core workflow). Do not write E2E tests for every feature.
33
+
34
+ ### 2. Naming Convention
35
+
36
+ Use the **"should [expected behavior] when [condition]"** pattern:
37
+
38
+ ```javascript
39
+ // Good
40
+ describe('UserService', () => {
41
+ describe('createUser', () => {
42
+ it('should return the created user with an assigned ID when valid data is provided')
43
+ it('should throw ValidationError when email is already taken')
44
+ it('should hash the password before persisting to the database')
45
+ })
46
+ })
47
+ ```
48
+
49
+ ```python
50
+ # Pytest: use descriptive function names
51
+ def test_create_user_returns_user_with_id_when_valid_data():
52
+ def test_create_user_raises_validation_error_when_email_taken():
53
+ def test_create_user_hashes_password_before_persisting():
54
+ ```
55
+
56
+ Avoid: `test1`, `testHappyPath`, `test_create_user_works`. The test name should be self-documenting enough to diagnose a failure without reading the test body.
57
+
58
+ ### 3. AAA Pattern Implementation
59
+
60
+ Every test has exactly three sections: Arrange, Act, Assert.
61
+
62
+ **Jest/Vitest (TypeScript)** — mock the repo, call the service, assert the result:
63
+ ```typescript
64
+ it('should return created user with ID when valid data is provided', async () => {
65
+ // Arrange
66
+ mockUserRepo.findByEmail.mockResolvedValue(null);
67
+ mockUserRepo.save.mockResolvedValue({ id: 'uuid-123', email: 'user@example.com' });
68
+ // Act
69
+ const result = await userService.createUser({ email: 'user@example.com', password: 'secret' });
70
+ // Assert
71
+ expect(result.id).toBe('uuid-123');
72
+ expect(mockUserRepo.save).toHaveBeenCalledOnce();
73
+ });
74
+ ```
75
+
76
+ **Pytest**:
77
+ ```python
78
+ def test_returns_user_with_id_when_valid_data(self):
79
+ self.mock_repo.find_by_email.return_value = None
80
+ self.mock_repo.save.return_value = {"id": "uuid-123", "email": "u@example.com"}
81
+ result = self.service.create_user(email="u@example.com", password="secret")
82
+ assert result["id"] == "uuid-123"
83
+ self.mock_repo.save.assert_called_once()
84
+
85
+ def test_raises_validation_error_when_email_taken(self):
86
+ self.mock_repo.find_by_email.return_value = {"id": "existing"}
87
+ with pytest.raises(ValidationError, match="Email already in use"):
88
+ self.service.create_user(email="u@example.com", password="secret")
89
+ ```
90
+
91
+ ### 4. Mock vs. Real Dependencies
92
+
93
+ **Mock** when the dependency has slow I/O, non-deterministic behavior, or you need to force specific error paths. Always mock in unit tests.
94
+
95
+ **Use real implementations** when testing the integration itself (repository + DB). Use Testcontainers (`PostgreSqlContainer`, `@testcontainers/postgresql`) for integration tests — spin up a real DB in `beforeAll`, run migrations, then tear down in `afterAll`.
96
+
97
+ **Avoid partial mocks** — they couple tests to implementation and hide bugs.
98
+
99
+ ### 5. Framework-Specific Configuration
100
+
101
+ **Vitest** (`vitest.config.ts`):
102
+ ```typescript
103
+ export default defineConfig({
104
+ test: {
105
+ globals: true, environment: 'node',
106
+ coverage: {
107
+ provider: 'v8', reporter: ['text', 'lcov'],
108
+ thresholds: { lines: 80, functions: 80, branches: 75 },
109
+ exclude: ['**/*.config.*', '**/migrations/**'],
110
+ },
111
+ },
112
+ });
113
+ ```
114
+
115
+ **Pytest** (`pyproject.toml`):
116
+ ```toml
117
+ [tool.pytest.ini_options]
118
+ addopts = "--cov=app --cov-report=term-missing --cov-fail-under=80"
119
+ ```
120
+
121
+ **JUnit 5**: configure Jacoco with `<minimum>0.80</minimum>` on `LINE` counter.
122
+
123
+ ### 6. Coverage Strategy
124
+
125
+ 80% line coverage is a floor. Priorities: (1) 100% on domain logic and calculation functions; (2) every `catch` block and error path; (3) boundary conditions (empty, null, min/max). Exclude `toString()`, getters/setters, and generated code. Use `vitest --coverage` for branch coverage; `--cov-report=term-missing` in Pytest.
126
+
127
+ ### 7. CI Integration
128
+
129
+ ```yaml
130
+ - name: Run tests with coverage
131
+ run: npx vitest run --coverage
132
+ - name: Upload coverage
133
+ uses: codecov/codecov-action@v4
134
+ with: { token: "${{ secrets.CODECOV_TOKEN }}", fail_ci_if_error: true }
135
+ ```
136
+
137
+ Block PRs on test failures and coverage drops > 2% from main baseline.
138
+
139
+ ## Additional Patterns
140
+
141
+ **WebSocket testing:** Mock the `WebSocket` constructor in unit tests to avoid real connections:
142
+ ```typescript
143
+ const mockWs = { send: vi.fn(), close: vi.fn(), onmessage: null, onopen: null };
144
+ vi.stubGlobal('WebSocket', vi.fn(() => mockWs));
145
+ // Simulate incoming message
146
+ mockWs.onmessage?.({ data: JSON.stringify({ type: 'update', payload: 42 }) });
147
+ ```
148
+ For integration tests, use a real `ws` server spun up in `beforeAll` on a random port.
149
+
150
+ **Large parameterized test performance:** When `pytest.mark.parametrize` produces thousands of cases (e.g., fuzzing inputs), test runs can take minutes. Apply stratified sampling: group inputs by equivalence class and pick one representative per class. For CI speed, split the full suite across workers with `pytest-xdist` (`pytest -n auto`), and run the full set only on main branch merges.
151
+
152
+ ## Edge Cases
153
+
154
+ **Testing async code and timers**: Use `vi.useFakeTimers()` (Vitest) or `pytest-asyncio` + `asyncio.sleep` mocking to control time in tests. Never use `setTimeout(fn, 0)` or `asyncio.sleep(0.1)` in tests — they create flaky tests dependent on real time. Use `vi.advanceTimersByTime(5000)` to simulate time passage deterministically.
155
+
156
+ **Testing code with global state / singletons**: Reset global state in `beforeEach`/`afterEach`. For module-level singletons in Node.js, use `vi.resetModules()` to get a fresh module instance per test. For Python, use `importlib.reload()` or redesign the singleton to accept injected dependencies (constructor injection is inherently more testable).
157
+
158
+ **Snapshot tests**: Use Jest/Vitest snapshot tests sparingly — only for stable serialized output (serialized ASTs, rendered static HTML). Never snapshot for UI components that change frequently; use explicit assertions instead. Stale snapshots silently pass until someone runs `--updateSnapshot`, masking regressions. If a snapshot test fails unexpectedly, treat it as a regression, not an automatic update.