@runecraft/grimoire 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +21 -0
  3. package/catalog.json +9 -0
  4. package/dist/grimoire.js +1758 -0
  5. package/package.json +54 -0
  6. package/references/definition-of-done.md +67 -0
  7. package/references/testing-patterns.md +260 -0
  8. package/skills/code-review-and-quality/README.md +13 -0
  9. package/skills/code-review-and-quality/SKILL.md +389 -0
  10. package/skills/code-simplification/README.md +13 -0
  11. package/skills/code-simplification/SKILL.md +338 -0
  12. package/skills/debugging-and-error-recovery/README.md +13 -0
  13. package/skills/debugging-and-error-recovery/SKILL.md +343 -0
  14. package/skills/debugging-and-error-recovery/scripts/__pycache__/triage_state.cpython-314.pyc +0 -0
  15. package/skills/debugging-and-error-recovery/scripts/triage_state.py +206 -0
  16. package/skills/deprecation-and-migration/README.md +13 -0
  17. package/skills/deprecation-and-migration/SKILL.md +248 -0
  18. package/skills/deprecation-and-migration/scripts/__pycache__/migration_tracker.cpython-314.pyc +0 -0
  19. package/skills/deprecation-and-migration/scripts/migration_tracker.py +237 -0
  20. package/skills/doubt-driven-development/README.md +13 -0
  21. package/skills/doubt-driven-development/SKILL.md +251 -0
  22. package/skills/git-commit-learning/.skill-meta.json +14 -0
  23. package/skills/git-commit-learning/README.md +205 -0
  24. package/skills/git-commit-learning/SKILL.md +435 -0
  25. package/skills/git-commit-learning/references/commit-patterns.md +595 -0
  26. package/skills/git-worktree/README.md +13 -0
  27. package/skills/git-worktree/SKILL.md +220 -0
  28. package/skills/idea-refine/README.md +13 -0
  29. package/skills/idea-refine/SKILL.md +186 -0
  30. package/skills/interview-me/README.md +13 -0
  31. package/skills/interview-me/SKILL.md +233 -0
  32. package/skills/linkedin-audit/SKILL.md +98 -0
  33. package/skills/linkedin-audit/references/dashboard-spec.md +43 -0
  34. package/skills/memory-management/README.md +13 -0
  35. package/skills/memory-management/SKILL.md +198 -0
  36. package/skills/security-and-hardening/README.md +13 -0
  37. package/skills/security-and-hardening/SKILL.md +472 -0
  38. package/skills/shipping-and-launch/README.md +13 -0
  39. package/skills/shipping-and-launch/SKILL.md +317 -0
  40. package/skills/skill-forge/README.md +153 -0
  41. package/skills/skill-forge/SKILL.md +291 -0
  42. package/skills/skill-forge/assets/SKILL.template.md +73 -0
  43. package/skills/skill-forge/references/authoring-patterns.md +249 -0
  44. package/skills/skill-forge/references/description-optimization.md +171 -0
  45. package/skills/skill-forge/references/output-evaluation.md +276 -0
  46. package/skills/skill-forge/references/scripts-guide.md +232 -0
  47. package/skills/skill-forge/references/spec.md +175 -0
  48. package/skills/skill-forge/scripts/validate.py +536 -0
  49. package/skills/spec-driven/.skill-meta.json +14 -0
  50. package/skills/spec-driven/README.md +335 -0
  51. package/skills/spec-driven/SKILL.md +174 -0
  52. package/skills/spec-driven/references/code-analysis.md +98 -0
  53. package/skills/spec-driven/references/coding-principles.md +56 -0
  54. package/skills/spec-driven/references/context-limits.md +31 -0
  55. package/skills/spec-driven/references/design.md +199 -0
  56. package/skills/spec-driven/references/discuss.md +136 -0
  57. package/skills/spec-driven/references/implement.md +425 -0
  58. package/skills/spec-driven/references/lessons.md +113 -0
  59. package/skills/spec-driven/references/memory.md +126 -0
  60. package/skills/spec-driven/references/specify.md +210 -0
  61. package/skills/spec-driven/references/sub-agents.md +96 -0
  62. package/skills/spec-driven/references/tasks.md +484 -0
  63. package/skills/spec-driven/references/validate.md +350 -0
  64. package/skills/spec-driven/scripts/__pycache__/lessons.cpython-314.pyc +0 -0
  65. package/skills/spec-driven/scripts/lessons.py +370 -0
  66. package/skills/spec-loop/README.md +36 -0
  67. package/skills/spec-loop/SKILL.md +61 -0
  68. package/skills/test-driven-development/README.md +13 -0
  69. package/skills/test-driven-development/SKILL.md +388 -0
  70. package/skills/typescript-patterns/README.md +13 -0
  71. package/skills/typescript-patterns/SKILL.md +346 -0
  72. package/skills/using-agent-skills/README.md +13 -0
  73. package/skills/using-agent-skills/SKILL.md +187 -0
@@ -0,0 +1,425 @@
1
+ # Execute
2
+
3
+ **Goal**: Implement ONE task at a time. Surgical changes. Verify. Commit. Repeat.
4
+
5
+ This is where code gets written. Every task follows the same cycle: plan → implement → verify → commit. Verification is built into every task, not a separate phase.
6
+
7
+ ---
8
+
9
+ ## MANDATORY: Before Starting Any Implementation
10
+
11
+ **Read [coding-principles.md](coding-principles.md) and state:**
12
+
13
+ 1. **Assumptions** - What am I assuming? Any uncertainty?
14
+ 2. **Files to touch** - List ONLY files this task requires
15
+ 3. **Success criteria** - How will I verify this works?
16
+
17
+ ⚠️ **Do not proceed without stating these explicitly.**
18
+
19
+ ---
20
+
21
+ ## Process
22
+
23
+ **Phase worker context:** When this task is executed as part of a phase sub-agent, the worker
24
+ receives the full phase task definitions, coding principles, the generated Test Coverage Matrix
25
+ and Gate Check Commands from tasks.md, and relevant spec/design context. The worker executes ALL
26
+ tasks in its assigned phase in order — each task follows every step below (implement → gate →
27
+ atomic commit) before moving to the next task in the phase. After all tasks in the phase are
28
+ complete, the worker reports a compact phase summary (tasks done, commit hashes, test counts,
29
+ deviations/blockers) to the orchestrator. See [sub-agents.md](sub-agents.md) for the full
30
+ model.
31
+
32
+ ### Before implementing: assess sub-agent delegation (MANDATORY — before the first task)
33
+
34
+ Before implementing anything, if a formal `tasks.md` with an Execution Plan exists, **count its phases**. If there are **more than 3 phases**, you MUST present the per-phase sub-agent offer to the user (see [sub-agents.md](sub-agents.md)) and wait for their choice before starting Execute — do not silently proceed inline. For 3 or fewer phases (or if the user declines), execute inline. Skip this check only when you are already a phase worker executing a delegated phase (the orchestrator already made the delegation decision).
35
+
36
+ ### 0. List Atomic Steps (MANDATORY when Tasks phase was skipped)
37
+
38
+ If there is no `tasks.md` for this feature, you MUST list atomic steps before writing any code. This is non-negotiable — it prevents the agent from losing focus and doing too many things at once.
39
+
40
+ ```
41
+ ## Execution Plan
42
+
43
+ 1. [Step] → files: [list] → verify: [how] → commit: [message]
44
+ 2. [Step] → files: [list] → verify: [how] → commit: [message]
45
+ 3. [Step] → files: [list] → verify: [how] → commit: [message]
46
+ ```
47
+
48
+ **Each step must be:**
49
+
50
+ - ONE deliverable (one component, one function, one endpoint, one file change)
51
+ - Independently verifiable (can prove it works before moving on)
52
+ - Independently committable (gets its own atomic git commit)
53
+
54
+ If listing steps reveals >5 steps or complex dependencies, STOP and create a formal `tasks.md` instead. The Tasks phase was wrongly skipped.
55
+
56
+ ### 1. Pick Task
57
+
58
+ From tasks.md (if exists) or from the execution plan above. User specifies ("implement T3") or suggest next available.
59
+
60
+ ### 2. Verify Dependencies
61
+
62
+ If tasks.md exists, check dependencies. If using inline plan, follow the order listed.
63
+
64
+ ❌ If blocked: "T3 depends on T2 which isn't done. Should I do T2 first?"
65
+
66
+ ### 3. State Implementation Plan
67
+
68
+ Before writing code:
69
+
70
+ ```
71
+ Files: [list]
72
+ Approach: [brief description]
73
+ Success: [how to verify]
74
+ ```
75
+
76
+ ### 4. Write Tests (derived from spec, not from implementation)
77
+
78
+ If the task includes tests (per the Tests field and **Test Coverage Matrix** in tasks.md):
79
+
80
+ 1. Write the test file(s) covering the task's acceptance criteria.
81
+ 2. Tests MUST be derived from the task's "Done when" criteria and `spec.md` ACs — **not** from the implementation. Each test encodes what the spec requires; never write tests by reading the code and asserting what it currently does.
82
+ 3. Each acceptance criterion from "Done when" maps to at least one test assertion whose asserted value matches the **spec-defined expected outcome**. Where the spec does not define a precise outcome, note it as a **spec-precision gap** rather than writing a vague assertion and passing silently.
83
+ 4. Edge cases from spec.md that apply to this task get test cases too.
84
+
85
+ **HARD CONSTRAINTS (test integrity — never violate):**
86
+
87
+ - Do NOT weaken assertions (making them less specific to pass more easily)
88
+ - Do NOT delete or skip test cases
89
+ - Do NOT use the test framework's skip/disable/pending mechanism to bypass failing tests
90
+
91
+ If a test is genuinely wrong (tests the wrong behavior per spec), STOP and ask the user
92
+ before modifying it. Never silently change a test.
93
+
94
+ If the task does NOT include tests (e.g., entity-only, config-only), skip to Step 4b.
95
+
96
+ ### 4b. Implement
97
+
98
+ Write the minimum implementation needed to satisfy the task's success criteria: pass all relevant tests (when present) and meet the defined verification/gate checks when there are no direct tests.
99
+
100
+ **HARD CONSTRAINTS:**
101
+
102
+ - Do NOT modify tests except to fix a genuinely wrong assertion (ask the user first). The tests are the spec — implementation conforms to them.
103
+ - Do NOT weaken assertions (making them less specific to pass more easily)
104
+ - Do NOT delete or skip test cases
105
+ - Do NOT use the test framework's skip/disable/pending mechanism to bypass failing tests
106
+ - Minimum code to pass — save structural improvements for a refactor task
107
+
108
+ Follow [coding-principles.md](coding-principles.md):
109
+
110
+ - Simplest code that works
111
+ - Touch ONLY listed files
112
+ - No scope creep
113
+
114
+ ### 5. Gate Check (VERIFY)
115
+
116
+ Run the gate check command from the task definition. This is MANDATORY — not "if applicable."
117
+
118
+ 1. Look up the command for the task's Gate level (quick/full/build) in the **Gate Check Commands** section of tasks.md, then run it
119
+ 2. Non-zero exit code = STOP. Fix the failure. Re-run. Do not proceed until it passes.
120
+ 3. Confirm the test count matches expectations (no tests were silently deleted or skipped)
121
+
122
+ **Tiered gates (from the Gate Check Commands section of tasks.md):**
123
+
124
+ | Task includes | Gate level | What runs |
125
+ | -------------------------------- | ---------- | ------------------------ |
126
+ | Unit tests only | Quick | Unit test command |
127
+ | E2E or integration tests | Full | Unit + E2E commands |
128
+ | Last task in a phase | Build | Build + lint + all tests |
129
+ | No tests (config, entities, etc) | Build | Build + lint only |
130
+
131
+ The gate check is deterministic. The test runner decides if the code is correct,
132
+ not the agent's self-assessment.
133
+
134
+ ### 6. Post-Gate Review
135
+
136
+ After the gate check passes:
137
+
138
+ 1. Verify test count: Are there at least as many test cases as before? (prevents silent deletion)
139
+ 2. Verify no SPEC_DEVIATION: If implementation diverged from spec/design, add a marker:
140
+
141
+ ```
142
+ // SPEC_DEVIATION: [what diverged]
143
+ // Reason: [why the deviation was necessary]
144
+ ```
145
+
146
+ 3. Quick complexity check: "Would senior engineer flag this as overcomplicated?"
147
+ - Yes → Simplify, re-run gate
148
+ - No → Proceed
149
+
150
+ 4. **Test Adequacy Review (MANDATORY — hard gate).**
151
+
152
+ A task cannot be committed or marked done until all four checks below pass. Tests must be both **necessary** (every test traces to a requirement) and **sufficient** (every requirement is covered). The scope boundary is the feature spec — do not test beyond it.
153
+
154
+ **Check A — Sufficient coverage (per-layer depth).** Build and output this table:
155
+
156
+ | Done-when criterion / spec AC / listed edge case | `file:line` + assertion expression | Spec-defined outcome | Covered? |
157
+ | ------------------------------------------------- | ---------------------------------- | -------------------- | -------- |
158
+ | [criterion from task or spec] | `path/to/test.ts:42` — `expect(result.field).toBe(expected)` | [expected value from spec] | ✅ Yes / ❌ No / ⚠️ Spec-precision gap |
159
+
160
+ **Evidence-or-zero rule:** Each covered cell MUST cite the exact `file:line` where the assertion lives AND reproduce the assertion expression (not just the `describe`/`it` name). A criterion with no located `file:line` evidence counts as **NOT covered**; the task cannot be marked done. Do not declare a criterion absent without first searching the test files — show the search before concluding it is missing (mirror: evidence or zero, never a guess).
161
+
162
+ **Spec-anchored outcome check:** For each covered criterion, derive the expected outcome from `spec.md` (or the task's "Done when" field) and confirm the test's asserted value matches it — not just that an assertion exists. Where the spec defines a precise outcome (e.g., a specific status code, a specific field value, a specific error message), the test assertion MUST target that exact outcome. Where the spec does not define a precise outcome, mark the cell as **⚠️ Spec-precision gap** and add a note; do NOT silently pass a vague assertion as if it were covered.
163
+
164
+ Every "Done when" criterion, every spec.md acceptance criterion, and every listed edge case that applies to this task must map to at least one concrete test assertion. Enforce the layer's Coverage Expectation from the Test Coverage Matrix:
165
+
166
+ - Domain / service layer: assertions map 1:1 to spec ACs; every listed edge case has a dedicated test.
167
+ - Route / controller / e2e layer: every route the task adds or modifies must have a happy-path test, a test for each listed edge case, and a test for each documented error/failure path.
168
+
169
+ No criterion left unverified.
170
+
171
+ **Check B — Non-shallow litmus.** Reject each of the following shallow patterns:
172
+ - Assertion-free tests or `expect(true)` / `expect(1).toBe(1)` style tautologies
173
+ - "No error thrown" as the only assertion — unless not-throwing IS the specified behavior
174
+ - Asserting only on mock call counts when the actual output/state is what the criterion demands
175
+ - Happy-path only when the task's "Done when" or spec.md lists edge cases
176
+
177
+ **Payload/conjunction rule.** For each named field in an emitted event, returned object, or persisted record, apply a separate check:
178
+ 1. Open the constructed object at its `file:line` and confirm the field is present in the assertion.
179
+ 2. Confirm the assertion targets the field's **value or state**, not just the call that produced it.
180
+ 3. A present `emit(...)` / `return ...` / `save(...)` call does NOT prove the field — only an assertion on the result does.
181
+ 4. Asserting a method was called (spy/mock) != asserting the resulting state. Both may be needed; neither substitutes for the other.
182
+
183
+ Apply this check to every payload-bearing criterion before marking it covered.
184
+
185
+ **Stack-agnostic litmus:** An assertion is shallow if it would still pass under a plausible *wrong* implementation. If so, strengthen it before committing.
186
+
187
+ **Check C — Necessary (no tests beyond the spec).** Reverse-map every test back to a spec AC, a listed edge case, or a "Done when" criterion. Build this table:
188
+
189
+ | `file:line` + assertion expression | Maps to (AC / edge case / Done-when criterion) | Keep? |
190
+ | ---------------------------------- | ---------------------------------------------- | ----- |
191
+ | `path/to/test.ts:42` — `expect(result.field).toBe(expected)` | [requirement ID or criterion text] | ✅ Keep / ❌ Remove |
192
+
193
+ Any test that maps to nothing → remove it. A test with no requirement is scope creep — it proves nothing about the feature and expands scope beyond the spec. Do not write speculative "what if" tests, do not test framework or library behavior, and do not duplicate an assertion that is already covered at another layer for the same scenario.
194
+
195
+ **Check D — Guideline conformance.** If project quality/testing guidelines were found in step 0 of tasks.md step 1.5, verify this task's tests conform to them (naming conventions, file locations, coverage thresholds, etc.). Note the guideline file followed.
196
+
197
+ **Bound:** Tests prove the work; they do not expand it. Thoroughness is scoped to the feature + spec. Repo depth is a floor (never less thorough than existing tests for the same layer); the spec is the ceiling. Do not invent requirements or tests that have no spec anchor.
198
+
199
+ **Anti-patterns — known verification cheats (treat any of these as an automatic Check failure):**
200
+
201
+ | Anti-pattern | Why it fails |
202
+ | ------------ | ------------ |
203
+ | Committing before the gate check passes | Skips the deterministic verifier — the gate is not optional |
204
+ | Asserting call count / spy invocation instead of the resulting state | Proves the method ran, not that it did the right thing |
205
+ | Marking a criterion covered without a `file:line` citation | Violates evidence-or-zero; suspicion of coverage is not coverage |
206
+ | Weakening an assertion (making it less specific) to force a pass | Moves the goalposts instead of fixing the code |
207
+ | Deleting or skipping a test to make the suite pass | Destroys coverage permanently; a failing test is a signal, not noise |
208
+ | "Tested elsewhere" deferral without citing where | Coverage gaps hide behind vague claims; cite the file:line or it doesn't count |
209
+ | Speculative "what if" tests with no spec anchor | Expands scope beyond the ceiling; remove them in Check C |
210
+ | Testing framework or library behavior | Tests a dependency, not the feature; remove them in Check C |
211
+
212
+ **On any failure** → rewrite or remove the affected test(s), re-run the gate, then re-run this review.
213
+
214
+ *Honest caveat:* This is an inspection-based review (model judgment), complementary to — not a replacement for — the deterministic gate. The gate confirms the test suite runs; the feature-level discrimination sensor (step 10) confirms the tests can detect regressions. This review confirms the suite is meaningful and bounded.
215
+
216
+ Add the two mapping tables and a one-line adequacy verdict to the Execution Template's Post-Gate section.
217
+
218
+ ### 7. Atomic Git Commit
219
+
220
+ Each task gets its own commit immediately after verification. Never batch multiple tasks into one commit.
221
+
222
+ **Format ([Conventional Commits 1.0.0](https://www.conventionalcommits.org/en/v1.0.0/)):**
223
+
224
+ ```
225
+ <type>(<scope>): <description>
226
+
227
+ [optional body]
228
+
229
+ [optional footer(s)]
230
+ ```
231
+
232
+ **Types:**
233
+
234
+ | Type | When to use |
235
+ | ---------- | ------------------------------------------------------- |
236
+ | `feat` | New feature or capability |
237
+ | `fix` | Bug fix |
238
+ | `refactor` | Code change that neither fixes a bug nor adds a feature |
239
+ | `docs` | Documentation only |
240
+ | `test` | Adding or correcting tests |
241
+ | `style` | Formatting, missing semicolons, etc. (no code change) |
242
+ | `perf` | Performance improvement |
243
+ | `build` | Build system or external dependencies |
244
+ | `ci` | CI configuration files and scripts |
245
+ | `chore` | Maintenance tasks that don't modify src or test files |
246
+
247
+ **Scope:** Feature name or module area, lowercase, e.g., `auth`, `cart`, `api`
248
+
249
+ **Description rules:**
250
+
251
+ - Imperative mood ("add", not "added" or "adds")
252
+ - Lowercase first letter
253
+ - No period at the end
254
+ - Complete the sentence: "If applied, this commit will _[your description]_"
255
+
256
+ **Breaking changes:** Append `!` after type/scope AND add `BREAKING CHANGE:` footer:
257
+
258
+ ```
259
+ feat(api)!: change authentication endpoint response format
260
+
261
+ BREAKING CHANGE: login endpoint now returns JWT in body instead of cookie
262
+ ```
263
+
264
+ **Examples:**
265
+
266
+ ```
267
+ feat(auth): add email validation to login form
268
+ ```
269
+
270
+ ```
271
+ fix(cart): prevent negative quantity on item decrement
272
+ ```
273
+
274
+ ```
275
+ refactor(api): extract token refresh logic into service
276
+
277
+ Move token refresh from inline handler to dedicated AuthTokenService
278
+ for reuse across multiple endpoints.
279
+ ```
280
+
281
+ **Rules:**
282
+
283
+ - One task = one commit
284
+ - Description references what was DONE, not what was planned
285
+ - Include only files listed in the task — never sneak in "while I'm here" changes
286
+ - If tests are part of the task, include them in the same commit
287
+
288
+ ### 8. Scope Guardrail
289
+
290
+ During implementation, you will notice things that could be improved, refactored, or added. **Do not act on them.** Instead:
291
+
292
+ - If it's a bug: surface it to the user (or capture it as a separate task)
293
+ - If it's an improvement: add it to the feature's `context.md` under "Deferred Ideas" (or surface it to the user if there is no `context.md`)
294
+ - If it's related to the current task: only include it if it's in the "Done when" criteria
295
+
296
+ **The heuristic:** "Is this in my task definition?" If no, don't touch it.
297
+
298
+ ### 9. Update Task Status
299
+
300
+ Mark task complete in tasks.md. Update requirement traceability in spec.md if requirement IDs are used.
301
+
302
+ ### 10. Feature-Level Validation (after the LAST task — MANDATORY, always runs)
303
+
304
+ When the task you just completed is the **last task of the feature** (or of a priority group being delivered on its own, e.g. all P1 tasks), you MUST run feature-level validation before reporting the work as done. **This is not optional and is never prompted — it runs automatically.** Do not stop at the final task's commit.
305
+
306
+ **Author ≠ verifier rationale.** The implementer (you, or the phase worker) is the author of the code and tests. An author checking their own work applies the same mental model that may have produced any gaps. The Verifier is a fresh sub-agent that re-derives coverage from the spec independently — it does not inherit the author's assumptions. This separation is the quality gate, not just a style preference.
307
+
308
+ **Layering:**
309
+ - Per-task adequacy self-check (steps 5–6): cheap, always runs, author does it, confirms each task in isolation.
310
+ - Feature-level validation (step 10): one trustworthy independent gate at completion, always-on, Verifier sub-agent does it.
311
+
312
+ **How to delegate to the Verifier:**
313
+ Dispatch a fresh sub-agent following the **Verifier** role described in [sub-agents.md](sub-agents.md). Provide it with:
314
+ - `spec.md` (ACs = source of truth)
315
+ - The git diff surface for this feature (commit range)
316
+ - The test files in scope
317
+ - `validate.md` as its operating checklist
318
+
319
+ **What the Verifier does (full description in [validate.md](validate.md) and [sub-agents.md](sub-agents.md)):**
320
+ 1. **Spec-anchored coverage check** — re-derives coverage evidence-or-zero; confirms each test's asserted value matches the spec-defined outcome; flags spec-precision gaps.
321
+ 2. **Discrimination sensor** — injects a small behavior-level fault (flip a condition, change a return value, off-by-one) in a scratch/throwaway state (git stash or temp copy), runs the relevant tests, confirms they kill the mutant, then discards the mutation. Reports killed/survived; surviving mutants become fix tasks.
322
+ 3. **Persisted report** — writes `.specs/features/[feature]/validation.md` with PASS/FAIL, per-AC evidence (`file:line` + assertion + spec outcome), gate exit results, sensor result, and the diff/commit range covered.
323
+ 4. **Chat return** — returns a compact verdict + ranked gap list to the orchestrator in chat; the orchestrator surfaces it and routes gaps to fix tasks.
324
+
325
+ The Verifier runs read-only over the real implementation tree (mutations run in a scratch state only). It does NOT fix.
326
+
327
+ If the Verifier returns FAIL, the orchestrator routes the ranked gaps back to an implementer as fix tasks, then re-dispatches the Verifier — bounded to a max of **3 fix→re-verify iterations** before escalating to the user.
328
+
329
+ If you are unsure whether more tasks remain, check `tasks.md`: if every task is marked complete, dispatch the Verifier now.
330
+
331
+ ---
332
+
333
+ ## Execution Template
334
+
335
+ ```markdown
336
+ ## Implementing T[X]: [Task Title]
337
+
338
+ **Reading**: task definition from tasks.md
339
+ **Dependencies**: [All done? ✅ | Blocked by: TY]
340
+ **Tests**: [unit/e2e/integration/none]
341
+ **Gate**: [quick/full/build]
342
+
343
+ ### Pre-Implementation (MANDATORY)
344
+
345
+ - **Assumptions**: [state explicitly]
346
+ - **Files to touch**: [list ONLY these]
347
+ - **Success criteria**: [how to verify]
348
+
349
+ ### Tests: Write tests derived from spec ACs
350
+
351
+ - Test file(s): [paths]
352
+ - Test count: [N test cases]
353
+ - Spec-derived: each test's asserted value maps to spec-defined outcome (or gap flagged)
354
+
355
+ ### Implement
356
+
357
+ [Write minimum code to pass tests]
358
+
359
+ - Tests modified: None
360
+ - Tests skipped/deleted: None
361
+
362
+ ### VERIFY: Gate Check
363
+
364
+ - Command: [gate check command]
365
+ - Result: [X passed, 0 failed]
366
+ - Test count: [N — matches planned test count]
367
+
368
+ ### Post-Gate
369
+
370
+ - [x] No SPEC_DEVIATION (or markers added)
371
+ - [x] No unnecessary changes made
372
+ - [x] Matches existing patterns
373
+
374
+ **Test Adequacy Review:**
375
+
376
+ *Check A — Sufficient (coverage mapping):*
377
+
378
+ | Done-when criterion / spec AC / listed edge case | `file:line` + assertion expression | Spec-defined outcome | Covered? |
379
+ | ------------------------------------------------- | ---------------------------------- | -------------------- | -------- |
380
+ | [criterion] | `path/to/test.ts:42` — `expect(result.field).toBe(expected)` | [spec value] | ✅ Yes / ⚠️ Gap |
381
+
382
+ *Check C — Necessary (reverse mapping):*
383
+
384
+ | `file:line` + assertion expression | Maps to (AC / edge case / Done-when criterion) | Keep? |
385
+ | ---------------------------------- | ---------------------------------------------- | ----- |
386
+ | `path/to/test.ts:42` — `expect(result.field).toBe(expected)` | [requirement or criterion text] | ✅ Keep |
387
+
388
+ - [ ] Check A: every criterion covered with `file:line` evidence; spec-defined outcomes matched or gap flagged; per-layer depth met
389
+ - [ ] Check B: no shallow assertions; payload/conjunction rule applied to every payload-bearing criterion
390
+ - [ ] Check C: every test maps to a requirement — no speculative or unclaimed tests
391
+ - [ ] Check D: guideline conformance — [guideline file followed, or "none — strong defaults applied"]
392
+
393
+ **Verdict**: [All criteria covered, spec outcomes matched, no shallow assertions, all tests necessary] / [Rewritten: describe what was fixed]
394
+
395
+ **Status**: ✅ Complete | ❌ Blocked | ⚠️ Partial
396
+ ```
397
+
398
+ **After the LAST task:** dispatch the Verifier sub-agent (see step 10 and [sub-agents.md](sub-agents.md)) for independent feature-level validation, including the spec-anchored check and discrimination sensor. Validation always runs automatically — never prompted. Execute is not done until the Verifier reports PASS and the validation report is written.
399
+
400
+ ---
401
+
402
+ ## Tips
403
+
404
+ - **One task at a time** — Focus prevents errors
405
+ - **Tools matter** — Wrong MCP = wrong approach
406
+ - **Reuses save tokens** — Copy patterns, don't reinvent
407
+ - **Check before commit** — Verify all criteria, then commit
408
+ - **Stay surgical** — Touch only what's necessary
409
+ - **Commit per task** — Clean git history enables bisect and rollback
410
+ - **Never "while I'm here"** — Scope creep during implementation is the #1 quality killer
411
+ - **Learn from mistakes** — If something goes wrong, surface it to the user so it informs the next task
412
+ - **Don't stop at the last commit** — Feature-level validation (step 10) is the final step of Execute, not optional
413
+
414
+ ---
415
+
416
+ ## Pause / End of Session
417
+
418
+ When work is interrupted, paused, or a session ends before the feature is complete:
419
+
420
+ 1. Open `.specs/STATE.md`.
421
+ 2. Locate the `## Handoff` section.
422
+ 3. **Replace only that section's body** with the current snapshot (feature, phase/task, completed, in-progress `file:line`, next step, blockers, uncommitted files, branch). See [memory.md](memory.md) for the exact format.
423
+ 4. Do NOT touch the `## Decisions` section above it — decisions are written only during Design.
424
+
425
+ **Section-scoped write (critical):** Replace the content between the `## Handoff` header and the next `##` header (or end of file). Never overwrite the full file — doing so silently destroys the Decisions log.
@@ -0,0 +1,113 @@
1
+ # Lessons — Self-Improving Layer
2
+
3
+ **Purpose**: Turn verification failures into reusable, project-local guidance that actually changes future behavior — without the lessons file rotting into a dead log.
4
+
5
+ **The split that keeps it alive**: the agent (you) supplies *judgment* — read the failure, phrase the lesson, cite its grounding. The script `scripts/lessons.py` owns everything *mechanical* — IDs, recurrence counting across distinct features, candidate→confirmed promotion, pruning, demotion, and rendering. Hand-kept bookkeeping is exactly what rots, so it is not your job; the script's job.
6
+
7
+ **What feeds it**: only the execution signals already produced by the Verifier in [validate.md](validate.md) and written to `.specs/features/[feature]/validation.md`. No signal → no lesson. This is the hard gate: a lesson with no grounding in a real verification outcome is an opinion, and the script refuses it.
8
+
9
+ **Scope discipline (critical)**: this layer captures *execution* lessons that are project-local and grounded in a signal. It does **NOT** capture methodology opinions about the SDD process itself ("we should always discuss earlier"). Those are maintainer decisions that ship in a version bump — never auto-written. If a candidate lesson is really about how to run the skill rather than about this codebase, do not record it.
10
+
11
+ ---
12
+
13
+ ## Files
14
+
15
+ | File | Owner | Purpose |
16
+ | ---- | ----- | ------- |
17
+ | `.specs/lessons.json` | script | Canonical machine state. Never hand-edit. |
18
+ | `.specs/LESSONS.md` | script (rendered) | Human/agent-readable playbook. Read it; never write it by hand. |
19
+ | `scripts/lessons.py` | package | The only way to mutate lessons. |
20
+
21
+ `confirmed` lessons are the playbook the agent loads. `candidate` lessons are tracked but NOT trusted until corroborated across `promote_threshold` distinct features (default 2). `quarantined` lessons failed when applied and are ignored.
22
+
23
+ ---
24
+
25
+ ## WRITE — distill lessons (runs inside Execute, after validation)
26
+
27
+ This is **not a new phase**. It is the final action of the Verifier step in [validate.md](validate.md), grafted onto a step that already always runs. Do it immediately after `validation.md` is written, before reporting completion.
28
+
29
+ ### When to write
30
+
31
+ Walk the just-written `validation.md`. For each **grounded** signal, record one lesson:
32
+
33
+ | validation.md signal | `--signal` value |
34
+ | -------------------- | ---------------- |
35
+ | An acceptance criterion failed or had no evidence | `ac_gap` |
36
+ | A discrimination-sensor mutant survived (weak test) | `surviving_mutant` |
37
+ | A criterion flagged ⚠️ Spec-precision gap | `spec_precision_gap` |
38
+ | A `// SPEC_DEVIATION` marker was added during implement | `spec_deviation` |
39
+ | The build-level gate check failed | `gate_fail` |
40
+
41
+ If `validation.md` is a clean PASS with no surviving mutants, no spec-precision gaps, and no deviations → **write nothing**. A clean run produces no lessons. This is correct, not a miss.
42
+
43
+ ### How to write
44
+
45
+ For each signal, phrase the lesson as **one terse, actionable, codebase-general sentence** — a rule a future feature could apply, not a restatement of this bug. Then call the script:
46
+
47
+ ```bash
48
+ python3 scripts/lessons.py add \
49
+ --feature "[feature folder name]" \
50
+ --signal "[signal value from table above]" \
51
+ --source "[file:line | AC id | mutant id | SPEC_DEVIATION ref from validation.md]" \
52
+ --text "[the one-sentence lesson]" \
53
+ --scope "[optional: path/layer/tag, e.g. billing, routes, repo-layer]"
54
+ ```
55
+
56
+ **Phrasing rules** (they make recurrences actually merge — dedup is exact-after-normalization, not semantic):
57
+
58
+ - Write the general rule, not the incident. ✅ `"Assert the exact persisted status value, not just that a status field exists"` ❌ `"The subscription test on line 88 was too weak"`.
59
+ - Be canonical and terse. Two lessons that mean the same thing must read the same way, or the script counts them as different and neither gets promoted.
60
+ - One lesson per signal. Don't bundle.
61
+
62
+ `--source` is **mandatory**. The script exits non-zero if it is empty — that is the grounding gate working, not an error to route around.
63
+
64
+ ### Self-check (do not skip)
65
+
66
+ After distilling, if `validation.md` contained any FAIL, surviving mutant, spec-precision gap, or SPEC_DEVIATION but you recorded zero lessons, state plainly in chat: *"Validation had signal X but no lesson was recorded — recording now / here's why it's out of scope."* Silent skipping is how the file dies.
67
+
68
+ ### Demotion
69
+
70
+ If a `confirmed` lesson was loaded for this feature (see READ below) and the *same* failure recurred anyway, the guidance is not working:
71
+
72
+ ```bash
73
+ python3 scripts/lessons.py penalize --id L-NNN
74
+ ```
75
+
76
+ Two penalties quarantine it. Use sparingly and only on real repeats.
77
+
78
+ ---
79
+
80
+ ## READ — load lessons (runs at Specify and Design)
81
+
82
+ A lessons file nobody reads is dead by definition. Loading is **mandatory**, not optional.
83
+
84
+ At the start of **Specify** (and again at **Design** for Large/Complex), load the confirmed lessons relevant to this feature:
85
+
86
+ ```bash
87
+ # All confirmed lessons:
88
+ python3 scripts/lessons.py list --status confirmed
89
+
90
+ # Or filter by the area this feature touches:
91
+ python3 scripts/lessons.py list --status confirmed --scope billing
92
+ python3 scripts/lessons.py list --status confirmed --query "idempotency"
93
+ ```
94
+
95
+ Apply the returned lessons as guidance while writing the spec / design. Do **not** load `candidate` or `quarantined` lessons as guidance — they are not trusted. Keep the loaded set small; this runs inside the <40k token budget.
96
+
97
+ ---
98
+
99
+ ## Fallback when code execution is unavailable
100
+
101
+ Some harnesses cannot run Python. Only then: maintain `.specs/LESSONS.md` by hand, following the exact same rules — grounded entries only, candidate→confirmed after 2 distinct features, prune stale candidates. **This path is degraded**: hand bookkeeping is the failure mode this layer exists to avoid, so prefer the script wherever a code tool exists. State once in chat that you are in the no-script fallback so the user knows accounting is best-effort.
102
+
103
+ ---
104
+
105
+ ## Disable
106
+
107
+ This layer is additive and self-gating (no signal → no write). To turn it off for a project, delete `.specs/lessons.json` and `.specs/LESSONS.md` and skip the WRITE/READ steps. The core Specify→Design→Tasks→Execute flow is unaffected.
108
+
109
+ ---
110
+
111
+ ## Known limitation
112
+
113
+ Deduplication is exact-after-normalization (lowercase, punctuation-stripped) — there are no embeddings (stdlib-only, zero-dependency by design). Near-duplicate lessons phrased differently will not merge and will each sit as separate candidates that never promote. Mitigation: follow the phrasing rules above. A future version may add embedding-based dedup.
@@ -0,0 +1,126 @@
1
+ # Memory Layer
2
+
3
+ **File:** `.specs/STATE.md`
4
+
5
+ A single file with two section-scoped parts. Each section has its own lifecycle; writes are always targeted — never whole-file overwrites.
6
+
7
+ ---
8
+
9
+ ## Sections
10
+
11
+ ### `## Decisions` — append-only log
12
+
13
+ Records **project-level** decisions only: conventions, patterns, constraints, or cross-cutting technology choices that future features must follow or supersede.
14
+
15
+ **Not project-level → stays in the feature's `design.md` Tech Decisions table.**
16
+ Heuristic: would a different feature need to know about this? If yes → project-level. If no → feature-local.
17
+
18
+ **Format** (one entry per decision):
19
+
20
+ ```markdown
21
+ ## Decisions
22
+
23
+ ### AD-001
24
+ - **Decision**: [what was decided — one sentence]
25
+ - **Reason**: [why this option was chosen]
26
+ - **Trade-off**: [what was given up]
27
+ - **Scope**: [which features / packages / layers this governs]
28
+ - **Date**: YYYY-MM-DD
29
+ - **Status**: active | superseded by AD-NNN
30
+ ```
31
+
32
+ **Supersession rule:** When a new decision replaces an old one, append a new `AD-NNN` entry and update the old entry's `status` field to `superseded by AD-NNN`. Never delete old entries — the history is the audit trail.
33
+
34
+ ---
35
+
36
+ ### `## Handoff` — pause snapshot (~500 tokens, overwritten each pause)
37
+
38
+ Captures mid-task / in-flight state so work can resume without re-reading the full task history. This is the sole position tracker; it complements `tasks.md` by recording state that `tasks.md` does not capture.
39
+
40
+ **Format:**
41
+
42
+ ```markdown
43
+ ## Handoff
44
+
45
+ - **Feature**: [feature name / .specs path]
46
+ - **Phase / Task**: [e.g., Phase 2 / T4 — implement repository layer]
47
+ - **Completed**: [comma-separated task IDs or "none"]
48
+ - **In-progress** (file:line): [e.g., `src/billing/subscription.service.ts:88` — mid-write]
49
+ - **Next step**: [one sentence — exactly what to do next]
50
+ - **Blockers**: [none | description]
51
+ - **Uncommitted files**: [list or "none"]
52
+ - **Branch**: [git branch name]
53
+ ```
54
+
55
+ ---
56
+
57
+ ## File shape
58
+
59
+ ```markdown
60
+ # STATE
61
+
62
+ ## Decisions
63
+
64
+ [AD-NNN entries…]
65
+
66
+ ## Handoff
67
+
68
+ [latest snapshot…]
69
+ ```
70
+
71
+ If the file does not yet exist, create it with both section headers and empty bodies.
72
+
73
+ ---
74
+
75
+ ## Read / Write Triggers
76
+
77
+ | Trigger | Section | Operation |
78
+ | ------- | ------- | --------- |
79
+ | Design phase, Step 1 (Load Context) | `## Decisions` | **Read** — conform to active decisions or supersede |
80
+ | Design phase, Tech Decisions step | `## Decisions` | **Append** — only for project-level decisions |
81
+ | Pause work / end of session | `## Handoff` | **Replace** — overwrite Handoff section only |
82
+ | Resume work / start of session | `## Handoff` | **Read** — load snapshot, propose next step |
83
+ | Resume work / start of session | `## Decisions` | **Read** — re-confirm active constraints before designing |
84
+
85
+ ---
86
+
87
+ ## Section-scoped write rule (critical)
88
+
89
+ One file holds two lifecycles. Writes MUST target their section only:
90
+
91
+ - **Design appends** to `## Decisions`. It MUST NOT touch `## Handoff`.
92
+ - **Pause replaces** `## Handoff`. It MUST NOT rewrite, reorder, or drop any entry in `## Decisions`.
93
+
94
+ The correct technique: locate the target section header, replace only the content between it and the next `##` header (or end of file). Never overwrite the full file.
95
+
96
+ Violating this rule causes one of two failures:
97
+ 1. A pause write clobbers the decisions log → decisions are silently lost.
98
+ 2. A design append touches the handoff snapshot → mid-task state is corrupted.
99
+
100
+ Both are silent data loss. The section-scoped write rule is the single correctness invariant of this memory layer.
101
+
102
+ ---
103
+
104
+ ## Pause / Resume Procedure
105
+
106
+ ### Pause
107
+
108
+ 1. Locate the `## Handoff` section in `.specs/STATE.md`.
109
+ 2. Replace its body (everything between `## Handoff` and the next `##` or EOF) with the current snapshot.
110
+ 3. Do NOT modify anything above or before `## Handoff`.
111
+ 4. Commit or stash outstanding changes as appropriate.
112
+
113
+ ### Resume
114
+
115
+ 1. Read `.specs/STATE.md` — both sections.
116
+ 2. Re-confirm active decisions from `## Decisions` — nothing superseded since last session?
117
+ 3. Read `## Handoff` — identify feature, phase/task, next step, blockers, uncommitted files, branch.
118
+ 4. Propose the next step to the user before writing any code.
119
+
120
+ ---
121
+
122
+ ## AD-NNN numbering
123
+
124
+ - Numbers are sequential, project-scoped, and permanent — never reused.
125
+ - The counter starts at `AD-001`. Check existing entries before assigning the next number.
126
+ - If `.specs/STATE.md` does not exist, the first decision is `AD-001`.