@softspark/ai-toolkit 2.11.0 → 3.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 (108) hide show
  1. package/AGENTS.md +21 -21
  2. package/CHANGELOG.md +62 -0
  3. package/README.md +16 -9
  4. package/app/.claude-plugin/plugin.json +1 -1
  5. package/app/agents/meta-architect.md +44 -0
  6. package/app/skills/agent-creator/SKILL.md +22 -6
  7. package/app/skills/analyze/SKILL.md +21 -1
  8. package/app/skills/api-patterns/SKILL.md +27 -0
  9. package/app/skills/app-builder/SKILL.md +24 -0
  10. package/app/skills/architecture-audit/SKILL.md +24 -0
  11. package/app/skills/architecture-decision/SKILL.md +24 -0
  12. package/app/skills/biz-scan/SKILL.md +24 -0
  13. package/app/skills/brand-voice/SKILL.md +36 -0
  14. package/app/skills/briefing/SKILL.md +41 -1
  15. package/app/skills/build/SKILL.md +24 -1
  16. package/app/skills/chaos/SKILL.md +22 -1
  17. package/app/skills/ci/SKILL.md +22 -1
  18. package/app/skills/ci-cd-patterns/SKILL.md +25 -0
  19. package/app/skills/command-creator/SKILL.md +31 -2
  20. package/app/skills/content-moderation-patterns/SKILL.md +25 -0
  21. package/app/skills/database-patterns/SKILL.md +25 -0
  22. package/app/skills/debug/SKILL.md +23 -1
  23. package/app/skills/design-engineering/SKILL.md +25 -0
  24. package/app/skills/docker-devops/SKILL.md +26 -0
  25. package/app/skills/ecommerce-patterns/SKILL.md +26 -0
  26. package/app/skills/evaluate/SKILL.md +22 -1
  27. package/app/skills/evolve/SKILL.md +25 -0
  28. package/app/skills/explain/SKILL.md +26 -1
  29. package/app/skills/explore/SKILL.md +25 -0
  30. package/app/skills/fix/SKILL.md +26 -1
  31. package/app/skills/git-mastery/SKILL.md +26 -0
  32. package/app/skills/grill-me/SKILL.md +22 -7
  33. package/app/skills/health/SKILL.md +22 -1
  34. package/app/skills/hipaa-validate/SKILL.md +25 -8
  35. package/app/skills/hook-creator/SKILL.md +107 -14
  36. package/app/skills/index/SKILL.md +22 -1
  37. package/app/skills/instinct-review/SKILL.md +25 -1
  38. package/app/skills/introspect/SKILL.md +26 -1
  39. package/app/skills/lint/SKILL.md +27 -1
  40. package/app/skills/mcp-builder/SKILL.md +27 -0
  41. package/app/skills/mem-search/SKILL.md +40 -0
  42. package/app/skills/migrate/SKILL.md +27 -1
  43. package/app/skills/migration-patterns/SKILL.md +26 -0
  44. package/app/skills/night-watch/SKILL.md +22 -1
  45. package/app/skills/observability-patterns/SKILL.md +26 -0
  46. package/app/skills/onboard/SKILL.md +22 -1
  47. package/app/skills/panic/SKILL.md +21 -1
  48. package/app/skills/performance-profiling/SKILL.md +34 -0
  49. package/app/skills/persona/SKILL.md +21 -4
  50. package/app/skills/plan/SKILL.md +26 -0
  51. package/app/skills/plan-writing/SKILL.md +26 -0
  52. package/app/skills/plugin-creator/SKILL.md +23 -6
  53. package/app/skills/pr/SKILL.md +24 -1
  54. package/app/skills/prd-to-issues/SKILL.md +22 -6
  55. package/app/skills/prd-to-plan/SKILL.md +22 -4
  56. package/app/skills/predict/SKILL.md +25 -0
  57. package/app/skills/qa-session/SKILL.md +23 -7
  58. package/app/skills/rag-patterns/SKILL.md +26 -0
  59. package/app/skills/refactor/SKILL.md +26 -0
  60. package/app/skills/refactor-plan/SKILL.md +23 -6
  61. package/app/skills/rollback/SKILL.md +27 -1
  62. package/app/skills/security-patterns/SKILL.md +27 -0
  63. package/app/skills/skill-audit/SKILL.md +22 -5
  64. package/app/skills/skill-creator/SKILL.md +58 -13
  65. package/app/skills/swift-patterns/SKILL.md +27 -107
  66. package/app/skills/swift-patterns/reference/frameworks.md +111 -0
  67. package/app/skills/test/SKILL.md +23 -1
  68. package/app/skills/testing-patterns/SKILL.md +26 -0
  69. package/app/skills/triage-issue/SKILL.md +22 -4
  70. package/app/skills/ubiquitous-language/SKILL.md +23 -8
  71. package/benchmarks/ecosystem-doctor-snapshot.json +395 -0
  72. package/kb/history/completed/deep-coverage-v3-20260423.md +160 -0
  73. package/kb/history/completed/ecosystem-deep-sweep-20260423.md +273 -0
  74. package/kb/procedures/ecosystem-sync-sop.md +255 -0
  75. package/kb/procedures/maintenance-sop.md +13 -2
  76. package/kb/procedures/release-preparation-sop.md +91 -12
  77. package/kb/procedures/release-verification-sop.md +24 -6
  78. package/kb/reference/global-install-model.md +15 -2
  79. package/kb/reference/supported-tools-registry.md +229 -0
  80. package/llms-full.txt +1105 -43
  81. package/llms.txt +4 -0
  82. package/manifest.json +1 -1
  83. package/package.json +4 -1
  84. package/scripts/ecosystem_doctor.py +348 -0
  85. package/scripts/ecosystem_tools.json +500 -0
  86. package/scripts/evaluate_skills.py +84 -0
  87. package/scripts/generate_aider_conf.py +26 -1
  88. package/scripts/generate_antigravity.py +77 -8
  89. package/scripts/generate_augment_agents.py +161 -0
  90. package/scripts/generate_augment_commands.py +160 -0
  91. package/scripts/generate_augment_hooks.py +162 -0
  92. package/scripts/generate_augment_skills.py +98 -0
  93. package/scripts/generate_cline_rules.py +96 -9
  94. package/scripts/generate_codex_hooks.py +13 -2
  95. package/scripts/generate_codex_skills.py +195 -0
  96. package/scripts/generate_copilot.py +296 -18
  97. package/scripts/generate_cursor_agents.py +144 -0
  98. package/scripts/generate_cursor_hooks.py +155 -0
  99. package/scripts/generate_cursor_mdc.py +20 -8
  100. package/scripts/generate_gemini_commands.py +158 -0
  101. package/scripts/generate_gemini_hooks.py +159 -0
  102. package/scripts/generate_gemini_skills.py +98 -0
  103. package/scripts/generate_roo_modes.py +42 -1
  104. package/scripts/generate_windsurf_hooks.py +143 -0
  105. package/scripts/generate_windsurf_rules.py +162 -10
  106. package/scripts/install.py +11 -2
  107. package/scripts/install_steps/ai_tools.py +120 -5
  108. package/scripts/validate.py +20 -3
@@ -78,3 +78,29 @@ git cherry-pick --continue
78
78
  | "One big commit is simpler" | Big commits are impossible to review, bisect, or revert — keep them atomic |
79
79
  | "Merge conflicts mean someone else's problem" | Conflicts mean you diverged too long — rebase frequently to stay aligned |
80
80
  | "Commit messages don't matter" | Messages are documentation — future you needs to understand why, not just what |
81
+
82
+ ## Rules
83
+
84
+ - **MUST** use `--force-with-lease` instead of `--force` for any force operation on a shared branch
85
+ - **MUST** create a backup branch before interactive rebase, reset --hard, or filter-repo: `git branch backup/<name>-pre-rebase`
86
+ - **NEVER** force-push to `main`, `master`, or `develop` — these are shared trunk branches by convention
87
+ - **NEVER** rewrite history that has already been pushed AND consumed by others — you will orphan their clones
88
+ - **CRITICAL**: the reflog is a 90-day safety net (`gc.reflogExpire`) — tag anything you want to keep longer. Do not rely on reflog for multi-month recovery.
89
+ - **MANDATORY**: commit messages follow Conventional Commits (`feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`) — drift defeats automated changelog and release tooling
90
+
91
+ ## Gotchas
92
+
93
+ - `git bisect` relies on each commit being testable. Flaky tests corrupt the bisection silently — a flaky "bad" mark sends `bisect` down the wrong half. Run the test 3× at the boundary commits if flakiness is known.
94
+ - `git cherry-pick <sha>` of a merge commit fails without `--mainline 1` (or 2). The error is cryptic ("commit is a merge but no -m option was given"); the fix is simple but non-obvious.
95
+ - `git reflog` entries expire by default in 90 days (`gc.reflogExpire`) and unreferenced commits get garbage-collected after 30 days (`gc.reflogExpireUnreachable`). Long-term recovery of "lost" commits from reflog is not guaranteed.
96
+ - `git rebase -i --root` is supposed to include the very first commit, but on **shallow clones** (`--depth N`) the "root" is the shallow boundary, not the actual initial commit. Run `git fetch --unshallow` before rebasing --root.
97
+ - `git filter-branch` is **deprecated** and slow (shell-based, re-forks per commit). Use `git filter-repo` for history rewriting — it is a separate tool (`pip install git-filter-repo`) but 100× faster and endorsed by the Git maintainers.
98
+ - `git pull --rebase` on a branch with unpushed merge commits rewrites those merges into linear history, silently losing the merge metadata. If a merge was intentional (e.g., to preserve feature-branch context), use `git pull --no-rebase` or set `pull.ff=only` globally.
99
+
100
+ ## When NOT to Load
101
+
102
+ - For simple commits on a ready branch — use `/commit`
103
+ - For opening a PR after commits are clean — use `/pr`
104
+ - For a specific failed operation needing root-cause analysis — use `/debug` on the git output
105
+ - For CI-specific git behavior (shallow clones, LFS on runners) — use `/ci-cd-patterns`
106
+ - For the in-repo `.git/hooks/*` content — this skill is user-facing Git; hook mechanics live in `/hook-creator` and `install_git_hooks.py`
@@ -29,10 +29,25 @@ Interview relentlessly about every aspect of the plan until reaching shared unde
29
29
 
30
30
  ## Rules
31
31
 
32
- - Ask questions **one at a time**
33
- - For each question, provide your **recommended answer**
34
- - If a question can be answered by **exploring the codebase**, explore instead of asking
35
- - Resolve dependencies between decisionsdon't skip ahead
36
- - Be relentless don't settle for vague or hand-wavy answers
37
- - Challenge assumptions, not just surface decisions
38
- - Apply Devil's Advocate critique to every major decision
32
+ - **MUST** ask questions one at a time — batching defeats the Socratic process
33
+ - **MUST** provide a recommended answer with every question so the user can accept, refine, or reject
34
+ - **NEVER** settle for vague or hand-wavy answers press for specifics ("what does 'scale' mean here — 10k req/s or 10M?")
35
+ - **NEVER** skip ahead before the current branch is resolved dependencies between decisions matter
36
+ - **CRITICAL**: if a question can be answered by **exploring the codebase**, explore instead of asking. Do not outsource verifiable facts to the user.
37
+ - **MANDATORY**: apply Devil's Advocate critique to every major decision — the default answer ("let's ship it") is almost always the one that needs challenging
38
+
39
+ ## Gotchas
40
+
41
+ - Grilling can feel adversarial. Frame questions as "what if X happens" not "your plan is wrong because X" — the goal is shared understanding, not winning.
42
+ - Fatigue kicks in around 10 questions deep. For larger plans, pause and summarize every ~7 questions so the user can reorient before continuing.
43
+ - Some disagreements cannot be resolved by argument — they need data. If a question loops (user defends A, grill defends B, repeat), recommend a spike or experiment instead of more questions.
44
+ - The user's "final answer" after heavy grilling may be reluctant compliance, not genuine agreement. Watch for hedging language ("I guess", "sure, fine") and probe once more.
45
+ - Grilling a plan that is already detailed and well-vetted produces diminishing returns and annoyance. Know when to stop — exit condition is "shared understanding", not "exhaustive coverage".
46
+
47
+ ## When NOT to Use
48
+
49
+ - For **implementation** — use `/plan`, `/refactor-plan`, or `/prd-to-plan`
50
+ - For code review after the code is written — use `/review`
51
+ - For architecture decisions with 2-3 named options — use `/architecture-decision` (structured trade-off) rather than open-ended grilling
52
+ - When the plan is crystal-clear and the user just needs a sanity check — grilling overkills trivial decisions
53
+ - In a production incident — use `/workflow incident-response`, speed beats thoroughness there
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: health
3
- description: "Report service and infrastructure health status"
3
+ description: "Report service and infrastructure health status via liveness/readiness checks, resource usage, and quick diagnostics. Use when the user asks whether services are up or degraded — not for deep debugging of a known error."
4
4
  effort: medium
5
5
  disable-model-invocation: true
6
6
  argument-hint: "[service]"
@@ -89,3 +89,24 @@ services:
89
89
  memory: XMB
90
90
  notes: "any issues"
91
91
  ```
92
+
93
+ ## Rules
94
+
95
+ - **MUST** report measured values — never mark a service healthy without a successful probe
96
+ - **NEVER** restart a degraded service without the user's explicit go-ahead
97
+ - **CRITICAL**: separate liveness (process up) from readiness (accepting traffic) in the report
98
+ - **MANDATORY**: if a health endpoint times out, classify as `degraded`, not `healthy`
99
+
100
+ ## Gotchas
101
+
102
+ - `docker compose ps` shows `Up` even when a container is **crash-looping** via restart policy — look at the `STATUS` column for `(unhealthy)` or `Restarting` rather than trusting "Up" alone.
103
+ - Many `/health` endpoints return 200 as long as the web server answers, even when the DB connection is down. If the service exposes a `/ready` or `/healthz?deep=true` endpoint, prefer it — shallow health is a lie.
104
+ - `pg_isready` reports success the moment Postgres accepts TCP, which happens seconds before the DB is actually query-ready after a restart. Chain it with a trivial `SELECT 1`.
105
+ - `docker stats --no-stream` needs cgroups v2 access; on older hosts or LXC containers it returns 0% CPU/memory silently instead of erroring. Verify at least one non-zero value before trusting the report.
106
+
107
+ ## When NOT to Use
108
+
109
+ - To debug a specific failing service — use `/debug` after the health check narrows it down
110
+ - For performance bottlenecks — use `/performance-profiling`
111
+ - For a production incident with page/alert — use `/workflow incident-response`
112
+ - For CI pipeline status — use `/ci`
@@ -346,14 +346,31 @@ This distinction helps compliance officers prioritize immediate remediation (def
346
346
 
347
347
  ## Rules
348
348
 
349
- - **Read-only**: Never modify any files. Report findings only.
350
- - **HIPAA rule citation**: Every finding must reference a specific HIPAA section (§ number).
351
- - **Skip non-source files**: Binary files, lock files (`*.lock`, `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`), vendored directories (`node_modules/`, `vendor/`, `.git/`, `dist/`, `build/`, `out/`, `.next/`).
352
- - **Respect `.hipaaignore`**: Honor exclusion patterns in the project's `.hipaaignore` file.
353
- - **No false confidence**: Clearly label heuristic findings as `POTENTIAL` and mark confidence as `heuristic`.
354
- - **Context before identifiers**: Always run the healthcare keyword context gate before applying PHI identifier regex patterns (Category 4) to avoid false positives.
355
- - **Warn on missing secrets management**: Flag PHI-adjacent config files without `.env` or secret manager references.
356
- - **No auto-fix in v1**: Auto-fixing HIPAA issues requires project-specific knowledge of logging/audit infrastructure. Planned for v2.
349
+ - **MUST** remain read-only never modify any file. This skill reports findings only.
350
+ - **MUST** cite a specific HIPAA rule section (§ number) for every finding — uncited findings are not actionable
351
+ - **MUST** run the healthcare keyword context gate before applying PHI identifier regex (Category 4) without it, false-positive rate is ~90%
352
+ - **NEVER** label a heuristic finding as "definitive" clearly mark `POTENTIAL` and `confidence: heuristic`
353
+ - **NEVER** scan binary files, lock files (`*.lock`, `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`), or vendored dirs (`node_modules/`, `vendor/`, `.git/`, `dist/`, `build/`, `out/`, `.next/`) — noise and zero signal
354
+ - **CRITICAL**: respect `.hipaaignore` exclusion patterns teams use it to mark known-safe data fixtures
355
+ - **MANDATORY**: flag PHI-adjacent config files without `.env` or secret-manager references as a WARN category, even when no PHI pattern matches
356
+ - **NEVER** auto-fix in this version. Auto-fixing requires project-specific knowledge of logging and audit infrastructure that regex alone cannot provide.
357
+
358
+ ## Gotchas
359
+
360
+ - Test fixtures and seed data often contain **synthetic** PHI that looks real (SSN-shaped IDs, formatted phone numbers, sample email addresses). Flag them but lower severity — production code handling the same patterns is the actual risk.
361
+ - HIPAA §164.312(b) requires audit logging but does not specify a format. "Logs exist" is not evidence of compliance — the logs must capture WHO (authenticated user), WHAT (action), WHEN (timestamp), WHERE (resource), and they must be immutable (append-only or write-once storage).
362
+ - Encryption-at-rest varies silently by storage layer. RDS auto-encrypts new volumes since 2017, but older DB snapshots may not be; S3 bucket policies can override instance-level encryption. Treat "encryption enabled" as a claim to verify with the cloud provider, not a state to trust.
363
+ - PHI identifiers 1-18 differ from HIPAA's "limited data set" rules — date of service and city are permitted in a limited dataset but not in full PHI. Do not auto-flag any date as PHI without context; check for surrounding patient-name or diagnosis proximity.
364
+ - PHI detection via regex misses data encoded in BLOBs, base64-embedded JSON, or encrypted-at-application-layer columns. A clean regex scan does not prove absence of PHI — document this explicitly in the report.
365
+ - Healthcare keyword context gate has dialect drift: "patient" in a veterinary codebase is a dog, not a person under HIPAA. Review context before escalating findings from multi-tenant or vertical-adjacent codebases.
366
+
367
+ ## When NOT to Use
368
+
369
+ - For generic security patterns (XSS, SQLi, CSRF) — use `/security-patterns`
370
+ - For dependency vulnerabilities — use `/cve-scan`
371
+ - For non-healthcare compliance regimes (PCI-DSS, SOC2, GDPR) — this skill is HIPAA-specific
372
+ - For **legal interpretation** of compliance — this skill flags technical controls; only a QSA or attorney interprets compliance status
373
+ - For PII/GDPR outside the HIPAA scope — overlapping but distinct; HIPAA covers PHI specifically
357
374
 
358
375
  ## Reference Documents
359
376
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: hook-creator
3
- description: "Creates new Claude Code hooks with guided workflow, strict conventions, and validation"
3
+ description: "Create a new Claude Code lifecycle hook (PreToolUse, PostToolUse, Stop, SessionStart, etc.) with a bash script and hooks.json registration. Use when the user wants automated behavior tied to a specific event — not for one-off commands."
4
4
  effort: high
5
5
  disable-model-invocation: true
6
6
  argument-hint: "[hook event or description]"
@@ -15,19 +15,90 @@ Create a new Claude Code hook following ai-toolkit conventions.
15
15
 
16
16
  ## Supported Hook Events
17
17
 
18
+ ### Core lifecycle
19
+
18
20
  | Event | Fires When | Matcher | Typical Use |
19
21
  |-------|-----------|---------|-------------|
20
- | `SessionStart` | Session begins or resumes after compact | `startup\|compact` | Context injection, rules reminder |
22
+ | `SessionStart` | Session begins, resumes, or clears | `startup\|resume\|clear` | Context injection, rules reminder |
23
+ | `SessionEnd` | Session is closing | any | Flush logs, save transcripts |
24
+ | `UserPromptSubmit` | User submits a prompt | any | Prompt governance, usage tracking |
21
25
  | `Notification` | Claude sends a notification | any | OS alerts, Slack pings |
22
- | `PreToolUse` | Before a tool executes | tool name (e.g. `Bash`) | Safety guards, validation |
23
- | `PostToolUse` | After a tool executes | tool name | Feedback loops, logging |
26
+
27
+ ### Tool lifecycle
28
+
29
+ | Event | Fires When | Matcher | Typical Use |
30
+ |-------|-----------|---------|-------------|
31
+ | `PreToolUse` | Before a tool executes | tool name (e.g. `Bash`) or `if:` rule | Safety guards, validation, `"defer"` for headless |
32
+ | `PostToolUse` | After a tool executes | tool name | Feedback loops, logging, format-on-save |
33
+
34
+ ### Turn lifecycle
35
+
36
+ | Event | Fires When | Matcher | Typical Use |
37
+ |-------|-----------|---------|-------------|
24
38
  | `Stop` | Claude finishes responding | any | Quality checks, session save |
25
- | `PreCompact` | Before context compaction | any | Context preservation |
39
+ | `StopFailure` | Turn ends due to an API error (rate limit, auth) | any | Alerting, fallback behavior |
40
+
41
+ ### Subagent lifecycle
42
+
43
+ | Event | Fires When | Matcher | Typical Use |
44
+ |-------|-----------|---------|-------------|
45
+ | `SubagentStart` | Subagent launches | any | Observability |
26
46
  | `SubagentStop` | Subagent completes | any | Result validation |
27
- | `UserPromptSubmit` | User submits a prompt | any | Prompt governance |
28
- | `TaskCompleted` | Agent Teams task done | any | Lint, type check |
47
+
48
+ ### Compaction
49
+
50
+ | Event | Fires When | Matcher | Typical Use |
51
+ |-------|-----------|---------|-------------|
52
+ | `PreCompact` | Before context compaction; can block with exit 2 or `{"decision":"block"}` | any | Context preservation |
53
+ | `PostCompact` | After compaction completes | any | Re-inject state that was summarized away |
54
+
55
+ ### Permissions & elicitation
56
+
57
+ | Event | Fires When | Matcher | Typical Use |
58
+ |-------|-----------|---------|-------------|
59
+ | `PermissionRequest` | Tool awaiting permission; can return `updatedInput` | any | Headless approval flows |
60
+ | `PermissionDenied` | Auto-mode classifier denied a tool call; return `{retry: true}` to allow retry | any | Coach the model, log denials |
61
+ | `Elicitation` | MCP `elicitation/create` request arrives | any | Intercept / override MCP UI prompts |
62
+ | `ElicitationResult` | Elicitation response ready to be sent back | any | Validate / transform elicitation replies |
63
+
64
+ ### Agent Teams
65
+
66
+ | Event | Fires When | Matcher | Typical Use |
67
+ |-------|-----------|---------|-------------|
68
+ | `TaskCreated` | New task registered via `TaskCreate` | any | Audit, assignment routing |
69
+ | `TaskCompleted` | Agent Teams task finished | any | Lint, type check, notify |
29
70
  | `TeammateIdle` | Agent Teams member idle | any | Completeness reminder |
30
71
 
72
+ ### Worktrees & environment
73
+
74
+ | Event | Fires When | Matcher | Typical Use |
75
+ |-------|-----------|---------|-------------|
76
+ | `WorktreeCreate` | Worktree is being created; `type: "http"` can return `hookSpecificOutput.worktreePath` | any | Provision worktree dirs |
77
+ | `WorktreeRemove` | Worktree is being removed | any | Cleanup |
78
+ | `CwdChanged` | Working directory changes during a session | any | Reactive env management (e.g., direnv) |
79
+ | `FileChanged` | Tracked file is modified on disk | any | Re-lint, reload config |
80
+ | `ConfigChange` | Settings / config file changed | any | Re-validate, warn on drift |
81
+
82
+ ### Setup / bootstrap
83
+
84
+ | Event | Fires When | Matcher | Typical Use |
85
+ |-------|-----------|---------|-------------|
86
+ | `Setup` | First-run / initialization | any | Project bootstrap |
87
+ | `InstructionsLoaded` | CLAUDE.md / AGENTS.md loaded into context | any | Verify presence of mandatory rules |
88
+
89
+ ## Hook Handler Types
90
+
91
+ Claude Code supports four handler `type` values in `hooks.json`:
92
+
93
+ | Type | Purpose | Required fields |
94
+ |------|---------|-----------------|
95
+ | `command` | Run a shell script / binary | `command` (path + args) |
96
+ | `prompt` | Inject a prompt to the fast inline model and use its verdict | Handler-managed |
97
+ | `agent` | Spawn a full subagent to evaluate the event (must target `Stop` / `SubagentStop`) | `agent` (agent name) |
98
+ | `mcp_tool` | Invoke an MCP tool directly (no subprocess) | `server`, `tool`, `arguments` |
99
+
100
+ `command` remains the default and ai-toolkit's hook entries all use it. The other types are documented here so you can author them by hand when needed.
101
+
31
102
  ## Workflow
32
103
 
33
104
  1. **Capture intent** -- ask: what should the hook do? Which lifecycle event?
@@ -66,8 +137,13 @@ Create a new Claude Code hook following ai-toolkit conventions.
66
137
  Required fields:
67
138
  - `_source`: always `"ai-toolkit"` (used by merge/strip logic)
68
139
  - `matcher`: tool name or regex for Pre/PostToolUse, empty string for global events
69
- - `hooks[].type`: always `"command"`
70
- - `hooks[].command`: path to script using `$HOME/.softspark/ai-toolkit/hooks/` prefix
140
+ - `hooks[].type`: `"command"`, `"prompt"`, `"agent"`, or `"mcp_tool"` (ai-toolkit uses `"command"`)
141
+ - `hooks[].command`: path to script using `$HOME/.softspark/ai-toolkit/hooks/` prefix (for `type: command`)
142
+
143
+ Optional fields (read from Claude Code docs, not emitted by ai-toolkit by default):
144
+ - `hooks[].timeout`: seconds to wait before killing the hook (global default applies if omitted)
145
+ - `hooks[].if`: permission-rule filter (e.g. `"Bash(git push*)"`) to reduce process spawning
146
+ - `hooks[].statusMessage`: short message surfaced in the UI while the hook runs
71
147
 
72
148
  ## Script Template
73
149
 
@@ -89,11 +165,20 @@ exit 0
89
165
 
90
166
  ## Rules
91
167
 
92
- - One script per hook entry (no inline multi-line commands)
93
- - Script filename must use kebab-case matching the event purpose
94
- - Pre* hooks can block operations -- keep them fast and deterministic
95
- - Never write secrets or credentials to stdout (output goes to LLM context)
96
- - Test the script standalone before registering: `bash app/hooks/{name}.sh`
168
+ - **MUST** use one script per hook entry no inline multi-line commands inside `hooks.json`
169
+ - **MUST** keep `Pre*` hooks fast and deterministic — they gate every matching tool call, slow hooks throttle the whole agent
170
+ - **NEVER** write secrets, tokens, or credentials to stdout hook output is injected into LLM context and can be extracted
171
+ - **NEVER** exit non-zero from a `Post*` or `Stop` hook unless you intend to block further processing; exit 0 is the safe default
172
+ - **CRITICAL**: respect the `TOOLKIT_HOOK_PROFILE` env var. Profile `minimal` must be a no-op for non-essential hooks.
173
+ - **MANDATORY**: test the script standalone (`bash app/hooks/{name}.sh`) before adding it to `hooks.json`
174
+
175
+ ## Gotchas
176
+
177
+ - `PreToolUse` hooks that exit non-zero **block** the tool call. A slow or flaky hook (network call, lock contention) becomes a DoS against Claude's own workflow. Keep Pre hooks to pure-bash checks of local state.
178
+ - Hook output (stdout) is injected verbatim into the model's context. A hook that runs `git log --all` prints hundreds of lines the model then has to wade through — be surgical, print only what matters.
179
+ - The path in `hooks.json` is resolved relative to the user's machine, not the ai-toolkit repo. Use `$HOME/.softspark/ai-toolkit/hooks/<name>.sh` as the canonical location (installer symlinks there).
180
+ - `SessionStart` with matcher `startup|compact` fires on both fresh starts AND after context compaction. Hooks that assume "new session" will mis-fire after compaction — check for explicit context markers if the distinction matters.
181
+ - Bash hooks on Windows (without WSL) will not run. If the hook must work cross-platform, wrap it in a Node or Python script and call from the bash stub — or flag the hook as `posix-only` in the description.
97
182
 
98
183
  ## Validation Checklist
99
184
 
@@ -105,3 +190,11 @@ After creating the hook:
105
190
  - [ ] `scripts/validate.py` passes
106
191
  - [ ] Script runs without errors: `bash app/hooks/{name}.sh`
107
192
  - [ ] Hook count in README.md and docs updated if needed
193
+
194
+ ## When NOT to Use
195
+
196
+ - For a **skill** (slash command) — use `/skill-creator`
197
+ - For an **agent** definition — use `/agent-creator`
198
+ - For a git pre-commit hook (not a Claude Code hook) — use `/git-mastery` or `scripts/install_git_hooks.py`
199
+ - For one-off automation that is not tied to a Claude Code event — use a plain shell script outside the toolkit
200
+ - To modify an existing toolkit hook — edit the file directly; this skill is create-only
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: index
3
- description: "Index codebase into the knowledge base"
3
+ description: "Reindex the knowledge base for semantic search via the configured vector store (e.g., Qdrant). Use only when the user explicitly asks to reindex — never trigger speculative rebuilds."
4
4
  effort: low
5
5
  disable-model-invocation: true
6
6
  argument-hint: "[path or scope]"
@@ -72,3 +72,24 @@ last_updated: "YYYY-MM-DD"
72
72
  | Missing documents | Verify frontmatter is valid |
73
73
  | Slow indexing | Check embedding service performance |
74
74
  | No vector store | Set up Qdrant or compatible vector DB |
75
+
76
+ ## Rules
77
+
78
+ - **MUST** require explicit user permission before running `make index` or `make index-full` — never self-trigger
79
+ - **NEVER** trigger a full rebuild to "clean up" unless the user asked for it
80
+ - **CRITICAL**: validate KB frontmatter before indexing — abort on invalid documents rather than indexing a broken state
81
+ - **MANDATORY**: respect change-detection hashes; do not force reindexing of unchanged documents
82
+
83
+ ## Gotchas
84
+
85
+ - Content-hash change detection keys on the file's content AND path. A **moved** document (same content, new path) looks new to the indexer — both the old path vector and the new one will exist until a full rebuild. Plan a full rebuild after mass reorganizations.
86
+ - Deleting a document on disk does not automatically remove its vectors from Qdrant; the indexer emits tombstones only if run with a directory scan. Without `--delete-missing`, orphan vectors stay for weeks.
87
+ - Embedding providers rate-limit by requests-per-minute AND by tokens-per-minute. A reindex of 1000+ docs hits the token cap first and stalls silently — watch for 429s in the indexer log before concluding "slow indexing".
88
+ - `make index-full` truncates the collection before re-embedding; if the embedding job crashes mid-way, the collection is left partially populated with no query-time indicator of the gap.
89
+
90
+ ## When NOT to Use
91
+
92
+ - For searching the KB — use `/search` or call `smart_query()` via the rag-mcp tool
93
+ - For fixing indexing bugs — use `/debug` on the indexer pipeline
94
+ - To evaluate RAG quality after reindexing — use `/evaluate`
95
+ - When no vector store is configured — document the gap, do not invent one
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: instinct-review
3
- description: "Review and manage learned instincts from past sessions"
3
+ description: "Review, promote, or remove learned instincts extracted from past sessions (`.claude/instincts/*.md`). Use when the user wants to curate the instinct list — not to extract new instincts or edit memory."
4
4
  effort: low
5
5
  user-invocable: true
6
6
  argument-hint: "[--list | --promote <id> | --remove <id> | --clear]"
@@ -75,3 +75,27 @@ Last seen: 2026-03-25
75
75
  - `--clear`: delete all files in `.claude/instincts/`
76
76
  - no args: interactive review of each instinct
77
77
  4. Report summary of changes made
78
+
79
+ ## Rules
80
+
81
+ - **MUST** list instincts with their source (session ID or date) so the user can judge provenance — anonymous instincts cannot be curated
82
+ - **MUST** confirm before `--clear` — this action is irreversible without a backup
83
+ - **NEVER** invent or edit instinct content — this skill curates existing files, it does not generate new ones
84
+ - **NEVER** promote an instinct with confidence < 0.7 without explicit user approval — low-confidence patterns are often one-off noise
85
+ - **CRITICAL**: the user owns the instinct list. Propose changes in interactive mode; apply silently only for explicit `--promote`, `--remove`, `--clear` flags.
86
+ - **MANDATORY**: after any destructive operation, print the deleted or modified filenames so the user has an audit trail
87
+
88
+ ## Gotchas
89
+
90
+ - Instincts live in **project-local** `.claude/instincts/`, not in `~/.softspark/ai-toolkit/`. Running this skill in a different project sees a different set — do not treat the list as global state.
91
+ - The Stop hook that extracts instincts may write draft files even when no meaningful pattern was observed. A `.claude/instincts/` with 40 files is usually 35 noise + 5 signal — curate ruthlessly.
92
+ - Promoted instincts (confidence = 1.0) load into every session's context, costing tokens. Too many pinned instincts bloat startup. Keep ≤10 pinned.
93
+ - Instinct files are plain markdown but the extraction format may evolve between ai-toolkit versions. A `--clear` after a version bump is often cleaner than trying to migrate old formats.
94
+ - The filename (`<pattern-name>.md`) is the identity used by `--promote` and `--remove`. Renaming files manually breaks those flags until the user reopens the review UI.
95
+
96
+ ## When NOT to Use
97
+
98
+ - To **extract** new instincts — extraction is automatic via the Stop hook
99
+ - To search past session memory — use `/mem-search`
100
+ - To edit global toolkit memory files — those live in `~/.claude/projects/*/memory/` and are managed by the auto-memory system, not this skill
101
+ - To permanently disable the instinct system — edit `settings.json` to remove the Stop hook; `--clear` only wipes current state, extraction continues on the next session
@@ -99,7 +99,24 @@ Output exactly this format:
99
99
 
100
100
  ---
101
101
 
102
- ## Self-Correction Rules
102
+ ## Rules
103
+
104
+ - **MUST** name a specific failure pattern (Loop / Drift / Assumption Error / Tool Misuse / Context Overflow / Wrong Abstraction / Missing Information) — vague self-diagnosis is useless
105
+ - **MUST** ground the diagnosis in concrete evidence (action traces, error messages, tool outputs) — not in feelings or hunches
106
+ - **NEVER** retry the exact same action. If it failed once, it will fail again. Change something.
107
+ - **NEVER** continue a loop "hoping it will work this time". Hope is not a strategy.
108
+ - **CRITICAL**: after 3 failed attempts, escalate to the user with a concrete report of what was tried, what failed, and what you need — do not keep flailing
109
+ - **MANDATORY**: the recovery action is ONE concrete next step, not a multi-phase plan. If you need a plan, use `/plan`.
110
+
111
+ ## Gotchas
112
+
113
+ - "Introspection" invoked mid-task can itself become a procrastination loop — spending effort diagnosing instead of acting. If the report takes longer to write than the next concrete action, skip the report and just change approach.
114
+ - Context overflow is often invisible from inside the session — the model cannot reliably detect its own forgetting. External signals (user frustration, repeated explanations of the same fact) are the real diagnostic.
115
+ - "Wrong abstraction" is frequently misdiagnosed as "Missing information". If adding data does not unlock the next step but simplifying the code does, the abstraction is the problem.
116
+ - Ask-the-user is the escape hatch but it has a cost: user context-switching, latency, fatigue. Use it when you truly cannot proceed, not as a habit to avoid commitment.
117
+ - The "fresh start" thought experiment works best when written down. Articulating "if starting over, my first action would be X" out loud often reveals the current approach's sunk-cost fallacy.
118
+
119
+ ## Self-Correction Checklist
103
120
 
104
121
  These rules are non-negotiable during recovery:
105
122
 
@@ -111,6 +128,14 @@ These rules are non-negotiable during recovery:
111
128
  6. **Check if the goal is still correct** before optimizing the approach. Sometimes the task itself needs clarification.
112
129
  7. **If stuck for more than 3 attempts, escalate.** Tell the user what you tried, what failed, and what you need.
113
130
 
131
+ ## When NOT to Use
132
+
133
+ - For debugging user code (not agent self-debugging) — use `/debug`
134
+ - For analyzing past sessions to find patterns — use `/mem-search` or `/instinct-review`
135
+ - For writing a recovery **plan** that spans multiple steps — use `/plan`
136
+ - When the user has already described the failure — respond directly, skip the structured introspection
137
+ - As a procrastination mechanism — if the next action is obvious, take it instead of writing a report
138
+
114
139
  ---
115
140
 
116
141
  ## Quick Self-Check (Use Before Retrying Anything)
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: lint
3
- description: "Lint code with auto-detected tools and fix suggestions"
3
+ description: "Run the project's linter and type-checker with auto-detected toolchain (ruff/mypy, eslint/tsc, phpstan, golangci-lint, clippy, dart analyze). Use when the user asks for static-analysis feedback — not to run tests or refactor."
4
4
  effort: low
5
5
  disable-model-invocation: true
6
6
  argument-hint: "[path]"
@@ -101,3 +101,29 @@ docker exec {container} make typecheck
101
101
  | Unused imports | Remove or use `# noqa: F401` |
102
102
  | Line too long | Break line or disable for that line |
103
103
  | Import order | Let linter fix with `--fix` |
104
+
105
+ ## Rules
106
+
107
+ - **MUST** auto-detect the linter from project config (`pyproject.toml`, `package.json`, `.eslintrc.*`, `composer.json`, `go.mod`, `Cargo.toml`, `pubspec.yaml`) — do not assume
108
+ - **MUST** show the diff before applying any `--fix` run; the user owns the decision to accept auto-fixes
109
+ - **NEVER** suppress lint errors with blanket `# noqa` or `eslint-disable-next-line` without naming the specific rule and a reason
110
+ - **NEVER** run the formatter (ruff format, prettier, dprint) inside a lint pass unless the project has that wired explicitly — formatting and linting are separate concerns
111
+ - **CRITICAL**: report the error count **before and after** any auto-fix — delta visibility is what makes the run trustworthy
112
+ - **MANDATORY**: respect the project's lint config (`.ruff.toml`, `eslint.config.js`, `phpstan.neon`) — overriding project rules on the fly produces arguments during code review
113
+
114
+ ## Gotchas
115
+
116
+ - `ruff check .` and `ruff format .` are **separate** commands in modern ruff (>0.1.0). Running only `ruff check` misses formatting drift; some repos expect both as part of "lint".
117
+ - `mypy` without `--strict` has a permissive default: missing annotations count as `Any`, so the type checker silently accepts untyped functions. Check whether the project pins `strict = true` in `pyproject.toml` before declaring "0 type errors".
118
+ - `eslint` follows `eslint.config.js` (flat config, ESLint 9+) OR `.eslintrc.*` (legacy). Mixing produces mysterious "no rules applied" errors. Check ESLint version first (`npx eslint --version`).
119
+ - `phpstan` levels (0-10) silently affect which rules apply. A repo at level 5 has different expectations than level 9; report the level alongside the error count.
120
+ - `golangci-lint` composes many linters; disabling one at the project level may still show its warnings if invoked with `--enable-all` flag. Check `.golangci.yml` before treating a warning as a new regression.
121
+ - Dart analyze reports on **all** files including generated `*.g.dart`. Some projects expect generated files to be excluded via `analysis_options.yaml`; without it, lint noise dominates real issues.
122
+
123
+ ## When NOT to Use
124
+
125
+ - To **fix** the errors — use `/fix` after this skill surfaces them
126
+ - To run tests — use `/test`
127
+ - For code review of logic and design — use `/review`
128
+ - For security-specific static analysis (SAST) — use `/cve-scan` or `/security-patterns`
129
+ - For project-specific rule authoring — edit the linter's config directly
@@ -130,6 +130,33 @@ Claude Desktop: same JSON, placed in `~/Library/Application Support/Claude/claud
130
130
  | `exit 1` on transient errors | Retry with exponential backoff, surface final error |
131
131
  | Stdout pollution (MCP stdio) | All logs go to **stderr**, stdout is JSON-RPC only |
132
132
 
133
+ ## Rules
134
+
135
+ - **MUST** pick 5-15 workflow-oriented tools, not a 1:1 API mirror. The model routes by task, not by endpoint.
136
+ - **MUST** use strict input schemas (Zod for TS, Pydantic for Python). `additionalProperties: true` lets the model invent fields and drift.
137
+ - **MUST** set correct tool annotations: `readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint` — the host uses these for safety UIs and auto-approval policies
138
+ - **NEVER** expose an MCP server on a public network without auth. MCP clients default to trusting the transport — attackers reach tools directly.
139
+ - **NEVER** log API keys, tokens, or env vars in error messages. A verbose error thrown at the model becomes a stored credential in the conversation.
140
+ - **CRITICAL**: with `stdio` transport, **all** logs go to stderr. Any stdout write that is not a JSON-RPC message breaks the client.
141
+ - **MANDATORY**: every server ships with a README documenting env vars, required scopes, rate limits, and a minimal invocation example.
142
+
143
+ ## Gotchas
144
+
145
+ - `stdio` transport sends the server's stdout directly to the client as protocol frames. A stray `print()` or `console.log()` crashes the client with a parse error and no clear diagnostic. Route all logs through a logger that writes to stderr.
146
+ - MCP tool descriptions are the only thing the LLM sees when routing. `description: "calls POST /api/v2/tickets"` tells the model nothing about intent. Describe **when to use**, not what it does at the HTTP level.
147
+ - Annotations (`readOnlyHint`, etc.) are optional in the spec but some hosts (Claude Desktop, Cursor) gate auto-approval on them. Missing `destructiveHint: true` on a delete tool may cause the client to run it silently.
148
+ - `streamable-http` with SSE requires the server to handle client reconnects with a `Last-Event-ID` header. Many quick-start templates skip this and drop events on flaky networks.
149
+ - Pagination cursors must be opaque from the client's perspective but stable across retries. A timestamp cursor that advances on every poll fails if the client retries the same cursor after a transient error.
150
+ - Claude Desktop caches server capabilities on first connection. After changing tool schemas, users must explicitly reload the server (quit + reopen or remove/re-add the server) — simply restarting the server process is not enough.
151
+
152
+ ## When NOT to Use
153
+
154
+ - For **in-toolkit skills** (slash commands, knowledge docs) — use `/skill-creator`
155
+ - For **agents** inside ai-toolkit — use `/agent-creator`
156
+ - For plugin packs bundling multiple agents/skills — use `/plugin-creator`
157
+ - For protocol-level MCP theory and transport trade-offs — use `/mcp-patterns` (knowledge skill)
158
+ - For conformance/integration testing of an MCP server — delegate to the `mcp-testing-engineer` agent
159
+
133
160
  ## Related
134
161
 
135
162
  - `mcp-patterns` — protocol reference (auto-loaded knowledge skill)
@@ -68,3 +68,43 @@ This skill queries the SQLite FTS5 full-text search index at `~/.softspark/ai-to
68
68
  - FTS5 supports prefix matching: `migrat*` matches "migration", "migrate"
69
69
  - Boolean operators: `database AND NOT test`
70
70
  - Column filters: `tool_name:Edit` to search only Edit tool observations
71
+
72
+ ## Example
73
+
74
+ ```bash
75
+ /mem-search "postgres migration rollback"
76
+ ```
77
+
78
+ Typical output:
79
+
80
+ ```
81
+ ## Memory Search: "postgres migration rollback"
82
+ Found 3 results across 2 sessions.
83
+
84
+ | # | Session | Project | Tool | Time | Preview |
85
+ |---|---------|------------------|------|------------|--------------------------------------|
86
+ | 1 | abc123 | magento2-os | Edit | 2026-03-12 | Rolled back 0042_add_tax_col... |
87
+ | 2 | def456 | magento2-b2b | Bash | 2026-02-28 | pg_dump before schema migration... |
88
+ | 3 | abc123 | magento2-os | Read | 2026-03-12 | Reviewed migration safety checklist |
89
+ ```
90
+
91
+ ## Rules
92
+
93
+ - **MUST** escape single quotes in queries by doubling (`it''s`) — SQL injection into the FTS5 call will break the query
94
+ - **NEVER** return the raw database path — treat `~/.softspark/ai-toolkit/memory.db` as internal
95
+ - **CRITICAL**: if the database does not exist, initialize it silently and return zero results — do not fail the skill
96
+ - **MANDATORY**: present Stage 1 (summary table) first; only expand to Stage 2 on follow-up
97
+
98
+ ## Gotchas
99
+
100
+ - FTS5 `MATCH` is picky: hyphens, slashes, and dots are parsed as operator separators and will reject queries like `mem-search api/v1` with a cryptic `malformed MATCH expression`. Wrap multi-token phrases with double-quotes: `"api/v1"` or `"mem-search"`.
101
+ - Results are ordered by `rank` (FTS5 relevance), **not** by `created_at`. A stale but high-ranked match outranks a fresh but weak one — include the `created_at` column and consider `ORDER BY rank, created_at DESC` for time-sensitive queries.
102
+ - The database path is static at `~/.softspark/ai-toolkit/memory.db`. If the user runs from a container, `~` resolves to the container's home, not the host's — the observation list will look empty. Check the env var `SOFTSPARK_HOME` before assuming the DB is missing.
103
+ - `observations_fts` is a separate virtual table; when observations are deleted directly (not via the SDK) the FTS index can drift. If counts between `observations` and `observations_fts` differ, rebuild with `INSERT INTO observations_fts(observations_fts) VALUES('rebuild');`.
104
+
105
+ ## When NOT to Use
106
+
107
+ - To search the KB or documentation — use `/search` or `smart_query()`
108
+ - To find a specific commit — use `git log --grep` or `/git-mastery`
109
+ - To list agent tasks — use `TaskList` or `/plan`
110
+ - When memory-pack hooks are not installed — direct the user to install them first
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: migrate
3
- description: "Run database migrations with backup verification"
3
+ description: "Run or create database migrations with the detected tool (Alembic, Prisma, Laravel, Django, Flyway, Drizzle) and verify backups exist first. Use when the user asks to apply, roll back, or generate a migration — not for general schema design."
4
4
  effort: medium
5
5
  disable-model-invocation: true
6
6
  argument-hint: "[direction]"
@@ -88,3 +88,29 @@ Returns JSON with: `tool`, `config_file`, `migrations_dir`, `total_migrations`,
88
88
 
89
89
  ## Reference Skill
90
90
  Use `migration-patterns` skill for zero-downtime strategies and best practices.
91
+
92
+ ## Rules
93
+
94
+ - **MUST** verify a recent backup exists (or confirmed in-progress) before any forward migration on production
95
+ - **MUST** show the generated SQL (dry-run / `--pretend` / `--sql`) before applying — the user approves the diff, not just the command
96
+ - **NEVER** run destructive migrations (DROP TABLE/COLUMN, NOT NULL on existing column, type change) without a tested rollback path
97
+ - **NEVER** mix schema changes and data backfill in the same migration — they fail differently and roll back differently
98
+ - **CRITICAL**: large-table operations use the concurrent/online variant (`ALTER TABLE ... ALGORITHM=INPLACE`, `CREATE INDEX CONCURRENTLY`) — table locks in production cause outages, not slowdowns
99
+ - **MANDATORY**: migrations test on a non-production environment first with representative data volume
100
+
101
+ ## Gotchas
102
+
103
+ - `alembic upgrade head` silently skips migrations with `branches` if the branch head is not explicit. Multi-head migrations need `alembic upgrade <revision>@head` or a merge migration first.
104
+ - Prisma's `prisma migrate dev` auto-generates migrations AND applies them AND reseeds the dev database. Running it on a production-connected config destroys data. Always use `prisma migrate deploy` in non-dev.
105
+ - Laravel's `migrate` command without `--force` refuses to run in `APP_ENV=production`. Scripts that blindly run `migrate` hang on interactive prompts in prod — always use `artisan migrate --force` in automation.
106
+ - Django's `migrate --fake` marks a migration as applied **without running it**. Intended for manual data fixes, but accidentally using it skips real schema changes and silently diverges production from code.
107
+ - `CREATE INDEX CONCURRENTLY` (Postgres) cannot run inside a transaction. Alembic wraps each migration in a transaction by default — concurrent index creation needs `op.execute()` with `autocommit_block()` or a manual `COMMIT`.
108
+ - Rolling back a forward migration that added a NOT NULL column deletes the column; data in that column is gone. "Rollback" is not "undo" if the column held user data during the forward window.
109
+
110
+ ## When NOT to Use
111
+
112
+ - For **zero-downtime schema evolution** strategy (expand-contract, double-write) — use `/migration-patterns`
113
+ - For designing the schema from scratch — use `/database-patterns`
114
+ - For application-layer rollback (deploying previous code) — use `/rollback`
115
+ - For CI-triggered migrations — use `/ci` or `/deploy`
116
+ - When no migration tool is detected — propose one from `/app-builder` instead of ad-hoc SQL
@@ -259,3 +259,29 @@ docker service rollback api
259
259
  - Not testing rollback path
260
260
  - Deploying code before migration completes
261
261
  - Dropping columns before removing code references
262
+
263
+ ## Rules
264
+
265
+ - **MUST** use **expand-contract** for any column rename, type change, or NOT NULL addition in production — single-step migrations block deploys
266
+ - **MUST** test the **rollback** migration on staging with production-like data — an untested rollback is a wish, not a plan
267
+ - **NEVER** drop a column while code still references it — the deploy window overlaps and some requests will fail
268
+ - **NEVER** backfill in one big transaction on a large table — batch with explicit progress tracking and resumability
269
+ - **CRITICAL**: schema changes deploy **before** the code that uses them. Code deploys before the schema means 500 errors until both complete.
270
+ - **MANDATORY**: any migration that affects >1M rows or takes >30 seconds on staging runs behind a feature flag — not a schema lock
271
+
272
+ ## Gotchas
273
+
274
+ - `ALTER TABLE ... ADD COLUMN NOT NULL DEFAULT <value>` in Postgres rewrites the whole table before version 11 (fast since 11 for non-volatile defaults). On older versions this locks the table for minutes. Add as NULL + default, backfill, then apply NOT NULL.
275
+ - `CREATE INDEX CONCURRENTLY` cannot run inside a transaction, which means many migration tools (Alembic default, Rails) need an override to use it. Check the tool's docs for non-transactional migrations.
276
+ - Double-write strategies need explicit reconciliation. "Write to both old and new, then cut over" leaves stale data in the old store unless you schedule a reconciliation pass before the cutover.
277
+ - Feature flags for migration safety must be **per-row** or **per-tenant**, not global. A global flag gates the whole deploy; a per-row flag lets a small cohort validate before full rollout.
278
+ - Rolling back an expand-contract migration mid-transition is ambiguous — the reverse direction depends on which phase was partially applied. Document the allowed rollback points in the migration itself.
279
+ - ORM query caches may retain the old schema shape. After an additive migration, services often need a cache flush or restart to see the new column — plan this into the deploy sequence.
280
+
281
+ ## When NOT to Load
282
+
283
+ - For executing a migration with the detected tool — use `/migrate`
284
+ - For **schema design** from scratch — use `/database-patterns`
285
+ - For pipeline migrations outside the database (config, file formats) — generic patterns here do not apply; use `/refactor-plan`
286
+ - For zero-downtime **application** deploys (blue-green, canary) — use `/ci-cd-patterns`
287
+ - When the database is small and can tolerate downtime — simpler single-step migrations are fine; expand-contract is overhead for tables with <100k rows and no concurrent writers