@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,138 @@
1
+ ---
2
+ name: docugenie
3
+ description: Writes OpenAPI 3.x specs, JSDoc/TSDoc/Google-style docstrings, and developer guides with working code examples. Use when a user asks to document an API, write docstrings, generate a README, or create a developer guide.
4
+ ---
5
+
6
+ # DocuGenie
7
+
8
+ ## Overview
9
+
10
+ Generate documentation that developers actually use: accurate OpenAPI specs, docstrings that IDEs render, and guides with copy-paste-ready examples. Documentation must match the code — never invent behavior.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Identify What Needs Documenting
15
+
16
+ Determine the output type:
17
+ - **REST API** → OpenAPI 3.x YAML/JSON spec
18
+ - **Function/class/module** → Language-appropriate docstrings
19
+ - **SDK or library** → Developer guide with quickstart + reference
20
+ - **Internal system** → Architecture doc (ADR or C4-level description)
21
+
22
+ Read the actual source code before writing anything. Never document assumed behavior.
23
+
24
+ ### 2. Write OpenAPI 3.x Specs
25
+
26
+ Every endpoint needs: summary, description, parameters, request body schema, and all response schemas including error cases.
27
+
28
+ ```yaml
29
+ openapi: "3.1.0"
30
+ info:
31
+ title: Payments API
32
+ version: "2.0.0"
33
+ paths:
34
+ /payments:
35
+ post:
36
+ operationId: createPayment
37
+ summary: Create a payment
38
+ description: Returns immediately with `pending` status. Listen to `payment.succeeded` webhook for confirmation.
39
+ tags: [Payments]
40
+ requestBody:
41
+ required: true
42
+ content:
43
+ application/json:
44
+ schema: { $ref: '#/components/schemas/CreatePaymentRequest' }
45
+ responses:
46
+ "201":
47
+ content:
48
+ application/json:
49
+ schema: { $ref: '#/components/schemas/Payment' }
50
+ "400": { description: Invalid request body }
51
+ "422": { description: Payment method declined }
52
+ components:
53
+ schemas:
54
+ CreatePaymentRequest:
55
+ type: object
56
+ required: [amount_cents, currency, payment_method_id]
57
+ properties:
58
+ amount_cents: { type: integer, minimum: 1, description: "Cents (e.g. 4999 = $49.99)" }
59
+ currency: { type: string, pattern: "^[A-Z]{3}$", description: ISO 4217 }
60
+ ```
61
+
62
+ Always define reusable schemas in `components/schemas`. Use `$ref` to avoid repetition. Document every error status code the code actually returns.
63
+
64
+ **Content negotiation**: When the same endpoint returns multiple formats, list each under `content` separately:
65
+ ```yaml
66
+ responses:
67
+ "200":
68
+ content:
69
+ application/json:
70
+ schema: { $ref: '#/components/schemas/Payment' }
71
+ text/csv:
72
+ schema: { type: string }
73
+ ```
74
+
75
+ **API versioning**: Prefer separate spec files per major version (`openapi-v1.yaml`, `openapi-v2.yaml`) over embedding version in `info.version` alone — separate files enable per-version tooling, linting, and SDK generation without cross-version pollution.
76
+
77
+ ### 3. Write Language-Appropriate Docstrings
78
+
79
+ **Python (Google style):**
80
+ ```python
81
+ def calculate_discount(
82
+ user: User,
83
+ cart_total: float,
84
+ coupon_code: str | None = None,
85
+ ) -> float:
86
+ """Calculate the discount amount for a user's cart.
87
+
88
+ Applies tier-based discounts first, then coupon discounts additively.
89
+ The total discount is capped at 50% of cart_total.
90
+
91
+ Args:
92
+ user: The authenticated user. Must have a valid `tier` attribute.
93
+ cart_total: Pre-tax cart value in dollars. Must be >= 0.
94
+ coupon_code: Optional promotional code. Invalid codes are silently
95
+ ignored — no exception is raised.
96
+
97
+ Returns:
98
+ The discount amount in dollars, rounded to 2 decimal places.
99
+ Returns 0.0 if no discount applies.
100
+
101
+ Side Effects:
102
+ Increments the coupon redemption counter in the database if coupon_code is valid.
103
+ Emits a `discount_applied` analytics event.
104
+
105
+ Raises:
106
+ ValueError: If cart_total is negative.
107
+ DatabaseError: If the coupon lookup fails due to a connection error.
108
+
109
+ Example:
110
+ >>> user = User(tier="gold")
111
+ >>> calculate_discount(user, 100.0, coupon_code="SAVE10")
112
+ 25.0 # 15% gold tier + 10% coupon
113
+ """
114
+ ```
115
+
116
+ **TypeScript (TSDoc)**: Use `@param`, `@returns`, `@throws {@link ErrorType}`, and `@example` tags. Document each pagination/filter option individually. Ensure `@throws` lists every error the implementation can raise, not just the happy path.
117
+
118
+ ### 4. Write a Developer Guide
119
+
120
+ Structure: What it does → Prerequisites (exact versions) → Installation (copy-paste) → Quickstart (minimal working example) → Core concepts → Common recipes (top 3-5) → Configuration reference table → Troubleshooting (top 3 errors with cause + fix).
121
+
122
+ ### 5. Validate the Documentation
123
+
124
+ Run `redoc-cli lint openapi.yaml` or `swagger-parser` to validate the spec. Run all code examples against the current codebase. Confirm every parameter, return type, and error code in docstrings matches the implementation.
125
+
126
+ ## Output Format
127
+
128
+ - OpenAPI: valid YAML in a fenced code block, ready to paste into a file
129
+ - Docstrings: inserted directly into the function/class, preserving existing code
130
+ - Developer guides: Markdown, with working code blocks and a clear header hierarchy
131
+
132
+ ## Edge Cases
133
+
134
+ **Undocumented error paths**: When the code raises errors not yet documented, list them in the docstring and add a corresponding `4xx`/`5xx` response to the OpenAPI spec. Do not silently omit them.
135
+
136
+ **Overloaded functions/polymorphic endpoints**: Document each distinct call signature separately using `@overload` in Python (with `typing`) or separate `operationId` paths in OpenAPI. Combining them into one vague description creates confusion.
137
+
138
+ **Deprecated APIs**: Mark with `@deprecated` in JSDoc/TSDoc, `deprecated: true` in OpenAPI, and include the replacement: "Deprecated since v2.3. Use `createPaymentV2` instead."
@@ -0,0 +1,160 @@
1
+ ---
2
+ name: edgeguard
3
+ description: Systematically finds edge cases using boundary value analysis, equivalence partitioning, property-based testing (Hypothesis/fast-check), fuzzing, and mutation testing. Use when a user asks to find edge cases, stress-test logic, or make tests more robust.
4
+ ---
5
+
6
+ # EdgeGuard
7
+
8
+ ## Overview
9
+
10
+ Go beyond happy-path tests to find the inputs that break things. Use structured techniques — not intuition — to systematically enumerate edge cases, then verify them with property-based tests, fuzz tests, and mutation testing.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Boundary Value Analysis (BVA)
15
+
16
+ For every numeric, string-length, or date input, test at:
17
+ - The exact minimum allowed value
18
+ - Minimum - 1 (just below valid range)
19
+ - Minimum + 1 (just above minimum)
20
+ - A nominal value in the middle
21
+ - Maximum - 1
22
+ - The exact maximum allowed value
23
+ - Maximum + 1 (just above valid range)
24
+
25
+ ```python
26
+ # Function: def set_age(age: int) — valid range 0..150
27
+ # BVA test cases:
28
+ test_cases = [-1, 0, 1, 75, 149, 150, 151]
29
+ ```
30
+
31
+ For string lengths: empty string `""`, one character, max length, max length + 1.
32
+ For collections: empty list, single element, two elements, at or near the size limit.
33
+
34
+ ### 2. Equivalence Partitioning
35
+
36
+ Divide inputs into classes where the code behaves identically, then test one value from each class. For an HTTP status-code classifier: one test each for `[100-199]`, `[200-299]`, `[300-399]`, `[400-499]`, `[500-599]`, `[<100]`, `[>599]`, non-integer. Test one value per partition: `101, 200, 301, 404, 503, 99, 600, "abc"`.
37
+
38
+ ### 3. Property-Based Testing
39
+
40
+ Write tests that assert invariants hold for thousands of randomly generated inputs, not just hand-picked ones.
41
+
42
+ **Python with Hypothesis:**
43
+ ```python
44
+ from hypothesis import given, strategies as st, assume
45
+
46
+ @given(st.lists(st.integers()))
47
+ def test_sort_preserves_length(lst):
48
+ assert len(sorted(lst)) == len(lst)
49
+
50
+ @given(st.integers(min_value=0), st.integers(min_value=0))
51
+ def test_add_is_commutative(a, b):
52
+ assert add(a, b) == add(b, a)
53
+
54
+ @given(st.text(min_size=1, max_size=100))
55
+ def test_slugify_is_idempotent(text):
56
+ assume(text.strip()) # skip pure-whitespace
57
+ slug = slugify(text)
58
+ assert slugify(slug) == slug
59
+
60
+ ```
61
+
62
+ **TypeScript/JavaScript with fast-check:**
63
+ ```typescript
64
+ import fc from 'fast-check';
65
+ test('reverse is involution', () => {
66
+ fc.assert(fc.property(fc.array(fc.integer()), (arr) => {
67
+ expect(reverse(reverse(arr))).toEqual(arr);
68
+ }));
69
+ });
70
+ ```
71
+
72
+ ### 4. Fuzz Testing
73
+
74
+ Feed random, malformed, or adversarial input to find crashes and panics.
75
+
76
+ **Python with Atheris:**
77
+ ```python
78
+ import atheris
79
+ import sys
80
+
81
+ def TestOneInput(data):
82
+ fdp = atheris.FuzzedDataProvider(data)
83
+ text = fdp.ConsumeUnicodeNoSurrogates(100)
84
+ try:
85
+ parse_user_input(text)
86
+ except ValueError:
87
+ pass # expected — not a bug
88
+ # Any other exception is a bug and will be reported
89
+
90
+ atheris.Setup(sys.argv, TestOneInput)
91
+ atheris.Fuzz()
92
+ ```
93
+
94
+ **Go:**
95
+ ```go
96
+ func FuzzParseConfig(f *testing.F) {
97
+ f.Add([]byte(`{"key":"value"}`))
98
+ f.Fuzz(func(t *testing.T, data []byte) {
99
+ _, err := ParseConfig(data)
100
+ if err != nil {
101
+ return // expected
102
+ }
103
+ })
104
+ }
105
+ ```
106
+ Run: `go test -fuzz=FuzzParseConfig -fuzztime=60s`
107
+
108
+ ### 5. Mutation Testing
109
+
110
+ Verify that your tests catch real bugs by deliberately introducing mutations and checking if tests fail.
111
+
112
+ **Python with mutmut:**
113
+ ```bash
114
+ mutmut run --paths-to-mutate=src/
115
+ mutmut results # shows surviving mutants (= tests that missed a bug)
116
+ mutmut show 23 # shows the specific mutation that survived
117
+ ```
118
+
119
+ **JavaScript with Stryker:**
120
+ ```bash
121
+ npx stryker run
122
+ # Opens HTML report showing which mutants survived
123
+ ```
124
+
125
+ A surviving mutant means: "I changed the code in a plausible way and no test caught it." Write a test that kills each surviving mutant.
126
+
127
+ Target: mutation score >= 80%.
128
+
129
+ **Mutation testing cost management**: Full mutation runs are slow. Scope to changed files only: `mutmut run --paths-to-mutate=src/changed_module.py`. Schedule full runs nightly in CI, not on every PR. Use `--parallel` (Stryker) or `mutmut run --no-progress` with `xdist` workers to parallelize execution.
130
+
131
+ ### 6. High-Value Edge Cases by Type
132
+
133
+ | Type | Key cases |
134
+ |------|-----------|
135
+ | Strings | `""`, `" "`, null bytes `"\0"`, Unicode surrogates, >1MB, SQL injection, path traversal `../../` |
136
+ | Numbers | `0`, `-0`, `NaN`, `Infinity`, `MAX_SAFE_INTEGER+1`, very small floats near zero |
137
+ | Collections | empty, single element, all-identical, sorted asc/desc, null elements |
138
+ | Dates | Feb 29, DST spring-forward (2:30 AM), year 2038 (32-bit Unix overflow), midnight |
139
+ | Concurrency | simultaneous access, duplicate requests (idempotency), partial failure mid-transaction |
140
+
141
+ ## Output Format
142
+
143
+ For each function or module analyzed, provide:
144
+
145
+ 1. **BVA table**: input → expected output/behavior
146
+ 2. **Equivalence classes**: list each partition and which value tests it
147
+ 3. **Property tests**: `@given` or `fc.property` test file
148
+ 4. **Edge case checklist**: domain-specific list of cases tried
149
+
150
+ ## Edge Cases of the Technique Itself
151
+
152
+ **Hypothesis CI reproducibility**: Hypothesis stores found examples in `.hypothesis/`. Commit this directory so CI reproduces failures deterministically. Pin the seed for scheduled runs: `pytest --hypothesis-seed=0`. Without a fixed seed, flaky Hypothesis failures are hard to reproduce locally.
153
+
154
+ **Fuzz testing cleanup**: Fuzz corpora and crash inputs accumulate in temp directories. Use `tmp_path` (pytest) or `TMPDIR` pointed at a ramdisk to avoid disk fill on long runs. Always set `fuzztime` limits in CI: `go test -fuzz=. -fuzztime=60s`. Clean up artifacts in post-run CI steps.
155
+
156
+ **Hypothesis finding a counterexample unexpectedly**: When Hypothesis fails, it shrinks the input to the minimal reproducing case. Read the `@example` decorator it prints — add it as a regression test so this specific case always runs.
157
+
158
+ **Mutation testing on I/O-heavy code**: Mutmut/Stryker work best on pure logic. For code with database calls or HTTP, use the mutation score only on the business logic layer, not on infrastructure adapters.
159
+
160
+ **Infinite loops from property tests**: If the code under test can loop indefinitely given certain inputs, wrap it with a timeout (`@settings(deadline=timedelta(milliseconds=500))` in Hypothesis) rather than letting CI hang.
@@ -0,0 +1,156 @@
1
+ ---
2
+ name: envwizard
3
+ description: Manages environment variables and secrets securely: creates .env.example, validates required vars at startup with envalid or pydantic-settings, integrates vault solutions (HashiCorp Vault, AWS Secrets Manager, Doppler), prevents secret leaks with git-secrets, and separates build-time from runtime config. Use when a user asks to set up environment config, manage secrets, or validate environment variables.
4
+ ---
5
+
6
+ # EnvWizard
7
+
8
+ ## Overview
9
+
10
+ Every application needs config. Config done wrong leaks secrets into git, breaks deployments silently, and creates "works on my machine" problems. Follow this workflow to do it right: validate early, separate concerns, never commit secrets.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Categorize Variables
15
+
16
+ Separate into three buckets before writing any code:
17
+
18
+ **Build-time config** (baked into image/artifact at compile/bundle time):
19
+ - `NODE_ENV`, `VITE_API_URL`, `REACT_APP_*`, `NEXT_PUBLIC_*`
20
+ - Set via CI/CD env vars or `--build-arg` in Docker
21
+
22
+ **Runtime config** (read when the process starts):
23
+ - `PORT`, `LOG_LEVEL`, `DATABASE_URL`, `REDIS_URL`, feature flags
24
+
25
+ **Secrets** (never in env var files on disk, never in image layers):
26
+ - API keys, database passwords, private keys, JWT secrets
27
+ - Source from a vault at runtime; inject as env vars or files
28
+
29
+ ### 2. Create .env.example
30
+
31
+ Commit this file. It is the contract for what variables are needed. Never put real values in it.
32
+
33
+ ```bash
34
+ # .env.example — copy to .env and fill in values
35
+ # Application
36
+ PORT=3000
37
+ NODE_ENV=development
38
+ LOG_LEVEL=info
39
+
40
+ # Database
41
+ DATABASE_URL=postgresql://user:password@localhost:5432/myapp
42
+ DATABASE_POOL_SIZE=10
43
+
44
+ # Redis
45
+ REDIS_URL=redis://localhost:6379
46
+
47
+ # Auth
48
+ JWT_SECRET=<generate with: openssl rand -hex 32>
49
+ JWT_EXPIRES_IN=7d
50
+
51
+ # External APIs (get from https://dashboard.stripe.com/apikeys)
52
+ STRIPE_SECRET_KEY=sk_test_...
53
+ STRIPE_WEBHOOK_SECRET=whsec_...
54
+
55
+ # Feature flags
56
+ ENABLE_NEW_CHECKOUT=false
57
+ ```
58
+
59
+ Create `.env.local` for local overrides (gitignored), `.env.test` for test values (can be committed if no real secrets), and `.env.production` only on the server via your secrets manager.
60
+
61
+ ### 3. Prevent Secret Leaks with git-secrets
62
+
63
+ Install and configure before the first commit:
64
+ ```bash
65
+ git secrets --install && git secrets --register-aws
66
+ git secrets --add 'sk_live_[a-zA-Z0-9]+' # Stripe live keys
67
+ git secrets --add 'password\s*=\s*\S+'
68
+ git secrets --scan-history
69
+ ```
70
+
71
+ **False positive handling**: Legitimate strings that match secret patterns (e.g., example keys in docs) can be allowlisted: `git secrets --add --allowed 'sk_test_example'`. For `detect-secrets`, run `detect-secrets scan > .secrets.baseline` to establish a baseline, then commit `.secrets.baseline` — future scans only flag new secrets not in the baseline.
72
+
73
+ Add to `.gitignore`:
74
+ ```
75
+ .env
76
+ .env.local
77
+ .env.production
78
+ .env.*.local
79
+ *.pem
80
+ *.key
81
+ secrets/
82
+ ```
83
+
84
+ ### 4. Validate at Startup (Fail Fast)
85
+
86
+ **Node.js with envalid:**
87
+ ```typescript
88
+ import { cleanEnv, str, port, url, bool, num } from 'envalid';
89
+
90
+ export const env = cleanEnv(process.env, {
91
+ NODE_ENV: str({ choices: ['development', 'test', 'production'] }),
92
+ PORT: port({ default: 3000 }),
93
+ DATABASE_URL: url(),
94
+ REDIS_URL: url(),
95
+ JWT_SECRET: str({ docs: 'https://internal/secrets' }),
96
+ LOG_LEVEL: str({ choices: ['debug', 'info', 'warn', 'error'], default: 'info' }),
97
+ STRIPE_SECRET: str(),
98
+ ENABLE_FEATURE: bool({ default: false }),
99
+ WORKER_COUNT: num({ default: 4 }),
100
+ });
101
+
102
+ // env.PORT is typed as number, env.DATABASE_URL is string
103
+ // Process exits immediately with a clear error if any required var is missing
104
+ ```
105
+
106
+ **Python with pydantic-settings:**
107
+ ```python
108
+ from pydantic_settings import BaseSettings, SettingsConfigDict
109
+ from pydantic import SecretStr, AnyUrl
110
+
111
+ class Settings(BaseSettings):
112
+ model_config = SettingsConfigDict(env_file=".env")
113
+ port: int = 8000
114
+ database_url: AnyUrl
115
+ jwt_secret: SecretStr # requires .get_secret_value() to read
116
+ log_level: str = "info"
117
+
118
+ settings = Settings() # raises ValidationError on startup if misconfigured
119
+ ```
120
+
121
+ ### 5. Integrate a Vault Solution
122
+
123
+ **HashiCorp Vault**: `envconsul -secret secret/myapp/production ./myapp` — injects secrets as env vars and restarts the process on rotation.
124
+
125
+ **AWS Secrets Manager (Python)**:
126
+ ```python
127
+ import boto3, json
128
+ def get_secret(name): return json.loads(boto3.client("secretsmanager").get_secret_value(SecretId=name)["SecretString"])
129
+ ```
130
+
131
+ **Doppler**: `doppler run -- node dist/index.js` — injects all project secrets as env vars without modifying code.
132
+
133
+ ### 6. Separate Build vs Runtime in Docker
134
+
135
+ Use `ARG` for build-time non-sensitive values (`NODE_ENV`, `NEXT_PUBLIC_API_URL`). Use `ENV` for runtime defaults. Never use `ARG JWT_SECRET` — ARGs appear in `docker history`. Inject secrets at container start via `env_file: .env.local` (Compose) or `envFrom.secretRef` (Kubernetes).
136
+
137
+ ## Output Format
138
+
139
+ Provide:
140
+ 1. `.env.example` with all variables, safe placeholder values, and source comments
141
+ 2. Startup validation code (envalid or pydantic-settings)
142
+ 3. `.gitignore` additions
143
+ 4. git-secrets setup commands
144
+ 5. Vault integration snippet for the deployment target
145
+
146
+ ## Edge Cases
147
+
148
+ **Secret rotation dual-version window**: AWS Secrets Manager rotation uses `AWSPENDING` (new secret being set) and `AWSCURRENT` (active secret) stages. During rotation, both versions are valid simultaneously — design the app to accept either until rotation completes (`setSecret` → `testSecret` → `finishSecret` Lambda hooks). Vault dynamic secrets have a lease TTL; renew leases before expiry or the credential is revoked mid-session.
149
+
150
+ **Multi-tenant config**: Per-tenant config (API keys, feature flags, limits) should not live in env vars — use a DB-backed config table or a key-value store keyed by tenant ID. Inject tenant config at request time after authentication, not at process startup. This enables runtime changes without redeployment.
151
+
152
+ **Rotating secrets without downtime**: Design the app to read secrets on each request or cache with a TTL (e.g., 5 minutes), not at startup. For database credentials, use a connection pool that reconnects on auth failure, triggering a fresh Vault lookup.
153
+
154
+ **Different envs needing different validation**: Use `envalid`'s `devDefault` or pydantic-settings' `default` for vars that are optional in development but required in production. Add an explicit check: `if settings.node_env == "production": assert settings.stripe_secret_key`.
155
+
156
+ **Leaked secret in git history**: Run `git filter-repo --path .env --invert-paths` to remove the file. Rotate all exposed credentials immediately — assume they are compromised. Notify the security team.
@@ -0,0 +1,152 @@
1
+ ---
2
+ name: errormedic
3
+ description: Diagnoses application errors by parsing stack traces, classifying error taxonomy, correlating source maps, verifying fixes, and connecting to Sentry/Datadog alerts. Use when a user shares an error, exception, stack trace, or crash log and needs it diagnosed and fixed.
4
+ ---
5
+
6
+ # ErrorMedic
7
+
8
+ ## Overview
9
+
10
+ Turn a cryptic error into a root cause and a verified fix. Follow a systematic triage: read the stack trace bottom-up, classify the error type, locate the exact source line, hypothesize cause, apply fix, verify the fix eliminates the error.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Parse the Stack Trace
15
+
16
+ **Read from the bottom up.** The bottom frames show where execution started; the top frame shows where it crashed.
17
+
18
+ Anatomy of a stack trace:
19
+ ```
20
+ Error: Cannot read properties of undefined (reading 'email') ← Error type + message
21
+ at getUserEmail (src/auth/user.ts:42:18) ← Top frame = crash site
22
+ at validateSession (src/middleware/auth.ts:17:5) ← Caller
23
+ at Layer.handle [as handle_request] (express/lib/router/layer.js:95:5) ← Framework
24
+ at next (express/lib/router/route.js:137:13)
25
+ at Route.dispatch (express/lib/router/route.js:112:3)
26
+ ```
27
+
28
+ Extract:
29
+ - **Error class**: `TypeError`, `ValueError`, `NullPointerException`, `KeyError`, etc.
30
+ - **Error message**: exact text
31
+ - **Top application frame**: first non-framework file in the trace (here: `src/auth/user.ts:42`)
32
+ - **Call chain**: sequence of application frames (ignore node_modules / stdlib)
33
+
34
+ ### 2. Classify the Error
35
+
36
+ | Class | Symptoms | Common Causes |
37
+ |-------|----------|---------------|
38
+ | `NullPointerException` / `TypeError: Cannot read ... of undefined` | Accessing property on null/undefined | Missing null guard, optional chain needed, async race |
39
+ | `KeyError` / `AttributeError` | Key or attribute doesn't exist | Wrong key name, missing default, schema mismatch |
40
+ | `ValueError` / `IllegalArgumentException` | Input validation failure | Incorrect type passed, out-of-range value |
41
+ | `ECONNREFUSED` / `ConnectionRefusedError` | TCP connection rejected | Service not running, wrong port, firewall |
42
+ | `ETIMEDOUT` / `ReadTimeoutError` | No response within deadline | Slow query, deadlock, downstream outage |
43
+ | `ENOENT` / `FileNotFoundError` | File doesn't exist | Wrong path, missing file, env-specific path |
44
+ | `SyntaxError` | Parse failure | Malformed JSON/YAML, encoding issue |
45
+ | `MemoryError` / `OOM` | Process killed | Memory leak, unbounded collection growth |
46
+ | `IntegrityError` / `UniqueViolation` | DB constraint violation | Duplicate insert, FK violation, race condition |
47
+ | `UnicodeDecodeError` | Encoding mismatch | File read with wrong codec (e.g., Shift-JIS read as UTF-8) |
48
+
49
+ **Encoding errors**: `UnicodeDecodeError: 'utf-8' codec can't decode byte 0x83` means the file is not UTF-8. Detect the encoding first: `chardet.detect(raw_bytes)` (Python) or `charset-normalizer`. Common culprits: Windows-1252, Shift-JIS (Japanese), Latin-1. Fix: `open(path, encoding='shift_jis')` or `errors='replace'` to substitute undecodable bytes with `?`.
50
+
51
+ ### 3. Resolve Source Maps (for Minified/Compiled Code)
52
+
53
+ **JavaScript (Browser or Node.js):**
54
+ ```bash
55
+ # Using source-map CLI
56
+ npx source-map resolve dist/bundle.js.map 42 18
57
+ # Returns: src/auth/user.ts:142:8
58
+
59
+ # Or in Node.js at runtime:
60
+ import sourceMapSupport from 'source-map-support';
61
+ sourceMapSupport.install();
62
+ # Stack traces now show original TypeScript files automatically
63
+ ```
64
+
65
+ **Java (obfuscated with ProGuard):**
66
+ ```bash
67
+ retrace.sh proguard-mapping.txt obfuscated-stacktrace.txt
68
+ ```
69
+
70
+ **Python (Cython or compiled):** Use `.pdb` files or ensure `-g` debug flags are present during compilation.
71
+
72
+ ### 4. Hypothesize Root Cause
73
+
74
+ Ask these questions in order:
75
+ 1. **What value is null/undefined/missing?** Read the crash-site line. What variable is being accessed?
76
+ 2. **Who provides that value?** Trace up the call chain — which function should have provided it?
77
+ 3. **Under what condition does it become null?** Is it an async race? A missing DB record? An empty API response?
78
+ 4. **Is this a bug or a missing guard?** A bug means the data is wrong upstream; a missing guard means the code doesn't handle a valid null case.
79
+
80
+ Example diagnosis:
81
+ ```
82
+ Error: Cannot read properties of undefined (reading 'email')
83
+ at getUserEmail (src/auth/user.ts:42:18)
84
+
85
+ Line 42: return user.profile.email;
86
+ → user.profile is undefined
87
+ → Looking up: user = await db.users.findOne({ id: session.userId })
88
+ → Returns null if user deleted, but caller didn't handle null
89
+ → Root cause: deleted user's session still valid; code doesn't handle missing user
90
+ ```
91
+
92
+ ### 5. Apply and Verify the Fix
93
+
94
+ **Write the fix:**
95
+ ```typescript
96
+ // Before
97
+ async function getUserEmail(userId: string): Promise<string> {
98
+ const user = await db.users.findOne({ id: userId });
99
+ return user.profile.email; // crashes if user is null
100
+ }
101
+
102
+ // After
103
+ async function getUserEmail(userId: string): Promise<string> {
104
+ const user = await db.users.findOne({ id: userId });
105
+ if (!user) {
106
+ throw new NotFoundError(`User ${userId} not found`);
107
+ }
108
+ if (!user.profile?.email) {
109
+ throw new DataIntegrityError(`User ${userId} has no email on profile`);
110
+ }
111
+ return user.profile.email;
112
+ }
113
+ ```
114
+
115
+ **Verify the fix:**
116
+ 1. Write a test that reproduces the original error condition
117
+ 2. Confirm the test fails before the fix
118
+ 3. Apply the fix
119
+ 4. Confirm the test passes after the fix
120
+ 5. Check that no existing tests regressed
121
+
122
+ ```python
123
+ def test_get_user_email_raises_when_user_deleted():
124
+ # Arrange: deleted user with valid session
125
+ db.users.delete(user_id=42)
126
+
127
+ # Act + Assert
128
+ with pytest.raises(NotFoundError, match="User 42 not found"):
129
+ get_user_email(42)
130
+ ```
131
+
132
+ ### 6. Connect to Observability Tools
133
+
134
+ **Sentry**: Use `scope.set_user()`, `scope.set_tag()`, `scope.set_context()` before `capture_exception()` to attach request context to the error event.
135
+
136
+ **Datadog**: Decorate with `@tracer.wrap(service=..., resource=...)` and call `span.set_tag("order.id", ...)` for trace correlation. Query: `status:error service:payments @error.type:TypeError`.
137
+
138
+ ## Output Format
139
+
140
+ For each error: **Error** (class + message) → **Location** (file:line) → **Root Cause** (one paragraph) → **Fix** (before/after code) → **Verification** (test that reproduces then passes) → **Prevention** (pattern to avoid recurrence).
141
+
142
+ ## Edge Cases
143
+
144
+ **Async errors without stack traces**: In Node.js, `Promise` rejections without `await` lose their stack. Enable `--async-stack-traces` (Node.js >= 12) or use `longjohn` in development. Always `return` promises — never fire-and-forget without a `.catch()`.
145
+
146
+ **Error swallowing in catch blocks**: `catch (e) {}` or `catch (e) { console.log(e) }` hides the original cause. When fixing, always re-throw or log with full context: `logger.error('Payment failed', { error: e, orderId })`.
147
+
148
+ **Transient vs persistent errors**: Network timeouts and rate limits are transient — the fix is a retry with exponential backoff. Logic errors and constraint violations are persistent — retrying makes them worse. Classify before choosing the fix strategy.
149
+
150
+ **Race condition fixes**: `IntegrityError: UniqueViolation` on concurrent inserts means two processes checked "does it exist?" simultaneously and both inserted. Fix options: (1) `INSERT ... ON CONFLICT DO NOTHING` / `ON CONFLICT DO UPDATE` (upsert); (2) `SELECT FOR UPDATE` to lock the row before deciding; (3) idempotency keys — accept a client-generated UUID and deduplicate on it. Choose based on whether the duplicate is an error or a retry.
151
+
152
+ **Source map fallback**: If source maps aren't deployed, the minified stack trace is the only artifact. Immediate steps: (1) set up source map upload in your CI pipeline (Sentry `sentry-cli sourcemaps upload`, Datadog `datadog-ci sourcemaps upload`); (2) for the current incident, manually unminify using `source-map` CLI with the build artifact if available locally; (3) add column numbers to error logging to enable post-hoc mapping once maps are uploaded.