opencode-fractal-memory 0.2.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 (127) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +493 -0
  3. package/agent/memory-hints.md +98 -0
  4. package/agent/memory-researcher.md +56 -0
  5. package/commands/memory-auto-test.md +10 -0
  6. package/commands/memory-cache-status.md +13 -0
  7. package/commands/memory-check-context.md +4 -0
  8. package/commands/memory-compress.md +13 -0
  9. package/commands/memory-dashboard.md +23 -0
  10. package/commands/memory-delete.md +24 -0
  11. package/commands/memory-detect-topics.md +28 -0
  12. package/commands/memory-distill.md +35 -0
  13. package/commands/memory-drilldown-query.md +28 -0
  14. package/commands/memory-drilldown.md +11 -0
  15. package/commands/memory-extract-patterns.md +4 -0
  16. package/commands/memory-generate-embeddings.md +26 -0
  17. package/commands/memory-get.md +26 -0
  18. package/commands/memory-help.md +55 -0
  19. package/commands/memory-injection-feedback.md +26 -0
  20. package/commands/memory-injection-stats.md +11 -0
  21. package/commands/memory-list.md +4 -0
  22. package/commands/memory-llm-compress.md +34 -0
  23. package/commands/memory-mcp.md +20 -0
  24. package/commands/memory-prune.md +4 -0
  25. package/commands/memory-rate.md +48 -0
  26. package/commands/memory-reflect.md +37 -0
  27. package/commands/memory-replace.md +26 -0
  28. package/commands/memory-retrieve.md +34 -0
  29. package/commands/memory-search.md +28 -0
  30. package/commands/memory-session-stats.md +4 -0
  31. package/commands/memory-set.md +31 -0
  32. package/commands/memory-stats.md +11 -0
  33. package/commands/memory-summarize.md +29 -0
  34. package/commands/memory-tool-stats.md +4 -0
  35. package/commands/memory-total-tokens.md +10 -0
  36. package/commands/memory-verify.md +4 -0
  37. package/commands/memory-version.md +9 -0
  38. package/dist/cache.js +39 -0
  39. package/dist/config.js +120 -0
  40. package/dist/embeddings.js +125 -0
  41. package/dist/ensure-models.js +70 -0
  42. package/dist/file-summary.js +143 -0
  43. package/dist/frontmatter.js +28 -0
  44. package/dist/hnsw-index.js +138 -0
  45. package/dist/hooks/auto-discover.js +4 -0
  46. package/dist/hooks/auto-distill.js +120 -0
  47. package/dist/hooks/auto-retrieve/content.js +47 -0
  48. package/dist/hooks/auto-retrieve/detection.js +50 -0
  49. package/dist/hooks/auto-retrieve/formatting.js +19 -0
  50. package/dist/hooks/auto-retrieve/index.js +163 -0
  51. package/dist/hooks/auto-retrieve/scoring.js +56 -0
  52. package/dist/hooks/auto-retrieve.js +1 -0
  53. package/dist/hooks/index.js +4 -0
  54. package/dist/hooks/predictive-rating.js +87 -0
  55. package/dist/journal.js +279 -0
  56. package/dist/logging.js +147 -0
  57. package/dist/management/helpers.js +227 -0
  58. package/dist/management/router.js +48 -0
  59. package/dist/management/routes.js +197 -0
  60. package/dist/management-server.js +4 -0
  61. package/dist/management-standalone.js +31 -0
  62. package/dist/mcp/logging.js +57 -0
  63. package/dist/mcp/server.js +251 -0
  64. package/dist/mcp/transform.js +48 -0
  65. package/dist/mcp-server.js +18 -0
  66. package/dist/memory.js +2 -0
  67. package/dist/ollama.js +74 -0
  68. package/dist/plugin/hooks.js +168 -0
  69. package/dist/plugin/index.js +28 -0
  70. package/dist/plugin/init.js +109 -0
  71. package/dist/plugin/state.js +75 -0
  72. package/dist/plugin/tools.js +45 -0
  73. package/dist/plugin.js +2 -0
  74. package/dist/procedural/store.js +1 -0
  75. package/dist/procedural/types.js +1 -0
  76. package/dist/seed-nodes.js +804 -0
  77. package/dist/storage/compress-ops.js +129 -0
  78. package/dist/storage/compression/formatters.js +243 -0
  79. package/dist/storage/compression/index.js +107 -0
  80. package/dist/storage/compression/patterns.js +138 -0
  81. package/dist/storage/expiration.js +66 -0
  82. package/dist/storage/index.js +1 -0
  83. package/dist/storage/injection-events.js +82 -0
  84. package/dist/storage/lifecycle.js +65 -0
  85. package/dist/storage/maintenance.js +60 -0
  86. package/dist/storage/migrations/definitions.js +374 -0
  87. package/dist/storage/migrations/index.js +21 -0
  88. package/dist/storage/navigation.js +98 -0
  89. package/dist/storage/queries/base.js +44 -0
  90. package/dist/storage/queries/links.js +32 -0
  91. package/dist/storage/queries/nodes.js +189 -0
  92. package/dist/storage/queries/search-helpers.js +239 -0
  93. package/dist/storage/scoring.js +36 -0
  94. package/dist/storage/search.js +233 -0
  95. package/dist/storage/session-tracking.js +180 -0
  96. package/dist/storage/sqlite.js +329 -0
  97. package/dist/storage/tool-usage.js +56 -0
  98. package/dist/storage/types.js +1 -0
  99. package/dist/storage/utils.js +94 -0
  100. package/dist/tools/auto-test.js +24 -0
  101. package/dist/tools/cache-status.js +36 -0
  102. package/dist/tools/compress.js +186 -0
  103. package/dist/tools/core.js +307 -0
  104. package/dist/tools/dashboard.js +97 -0
  105. package/dist/tools/help.js +59 -0
  106. package/dist/tools/index.js +12 -0
  107. package/dist/tools/inject.js +91 -0
  108. package/dist/tools/injection-debug.js +48 -0
  109. package/dist/tools/journal.js +105 -0
  110. package/dist/tools/llm-compress.js +41 -0
  111. package/dist/tools/middle-term.js +68 -0
  112. package/dist/tools/playbook.js +64 -0
  113. package/dist/tools/reflect.js +291 -0
  114. package/dist/tools/search.js +188 -0
  115. package/dist/tools/session.js +189 -0
  116. package/dist/tools/shared.js +74 -0
  117. package/dist/tools/skill.js +37 -0
  118. package/dist/tools/stats.js +256 -0
  119. package/dist/tools/version.js +13 -0
  120. package/dist/tools.js +18 -0
  121. package/dist/utils/hybridScore.js +67 -0
  122. package/management/public/app.js +1529 -0
  123. package/management/public/index.html +486 -0
  124. package/management/public/three.min.js +6 -0
  125. package/package.json +65 -0
  126. package/scripts/download-models.ts +16 -0
  127. package/scripts/postinstall.cjs +30 -0
@@ -0,0 +1,804 @@
1
+ export const SEED_NODES = [
2
+ // Rule nodes (auto-injected)
3
+ {
4
+ label: "rule:mandatory:memory",
5
+ tag: "rule:mandatory",
6
+ content: `## Memory Tool Mandatory Rules
7
+ tag: rule:mandatory
8
+
9
+ ### Rules
10
+ - search before get | get only verified labels
11
+ - replace needs re-read first (content can change)
12
+ - edit: read file first | write for new files
13
+ - error → error node | solved → mark + add to rules
14
+
15
+ ### Auto-Learned
16
+ - Review tool arguments and ensure correct format
17
+ - Avoid memory_drilldown with vague queries - use memory_search first
18
+ - Re-read file before replace to ensure content is current
19
+ - Verify node exists before memory_delete
20
+ - Use ripgrep (rg) for direct code search instead of slow tools with timeouts`,
21
+ },
22
+ {
23
+ label: "rule:standard",
24
+ tag: "rule:standard",
25
+ content: `## Memory Tool Standard Rules
26
+ tag: rule:standard
27
+
28
+ ### Workflow
29
+ - search → get → set chain
30
+ - verify after confirming something works`,
31
+ },
32
+ {
33
+ label: "rule:suggestion",
34
+ tag: "rule:suggestion",
35
+ content: `## Memory Tool Suggestions
36
+ tag: rule:suggestion
37
+
38
+ ### Optimization
39
+ - llm_compress before compressing
40
+ - extract_patterns quarterly
41
+ - higher bm25 (0.6-0.8) for exact | lower (0.2-0.4) for semantic`,
42
+ },
43
+ {
44
+ label: "rule:mandatory:core",
45
+ tag: "rule:mandatory",
46
+ content: `## Behavioral Rules Injection System
47
+ tag: rule:mandatory
48
+
49
+ ### How to Use This System
50
+ When you discover an error or better approach:
51
+ 1. Distill the correct usage pattern
52
+ 2. Add it to the appropriate rules node
53
+ 3. The rule gets injected next cycle
54
+
55
+ ### 3 Tag Levels
56
+ - rule:mandatory - Always injected, always enforced
57
+ - rule:standard - Injected, suggested
58
+ - rule:suggestion - Injected, optional`,
59
+ },
60
+ {
61
+ label: "rule:mandatory:agent-pull",
62
+ tag: "rule:mandatory",
63
+ content: `## Agent-Pull Memory Rule
64
+ tag: rule:mandatory
65
+
66
+ ### When to Search Memory
67
+ - Before starting a complex task (3+ steps)
68
+ - When user asks about past decisions
69
+ - When working on a file/module you've worked on before
70
+ - When user says "remember", "previously", "before"
71
+ - When you're unsure about a convention
72
+ - When you see errors you've seen before
73
+ - When choosing between approaches
74
+
75
+ ### How to Search
76
+ 1. Call memory_search with keywords from your reasoning
77
+ 2. Check results - if >50% match, use memory_drilldown for details
78
+ 3. Reference memory in your response with file:line format
79
+
80
+ ### Decision Flow
81
+ User request → Check memory → Verify codebase → Act
82
+ Only skip memory search for trivial tasks (<2 steps)`,
83
+ },
84
+ {
85
+ label: "rule:mandatory:tools",
86
+ tag: "rule:mandatory",
87
+ content: `## Tool-Specific Behavioral Rules
88
+ tag: rule:mandatory
89
+
90
+ ### edit tool
91
+ - ALWAYS read file first with read tool
92
+ - NEVER edit non-existent files - use write for new files
93
+ - Provide exact oldString (copy from read output)
94
+
95
+ ### write tool
96
+ - ALWAYS verify file doesn't exist first
97
+ - NEVER write to existing files without reading them
98
+
99
+ ### bash tool
100
+ - ALWAYS quote paths with spaces
101
+ - NEVER use destructive commands without explicit user request
102
+ - NEVER skip hooks (--no-verify, --no-gpg-sign)
103
+
104
+ ### memory_drilldown
105
+ - ALWAYS use memory_search first to find relevant nodes
106
+ - NEVER drilldown with vague queries
107
+ - Use memory_drilldown(id) with specific node IDs from search results
108
+
109
+ ### memory_replace
110
+ - ALWAYS re-read node with memory_get immediately before replacing
111
+ - NEVER use cached content - content may change between operations`,
112
+ },
113
+ // Seed nodes (on-demand, not injected)
114
+ {
115
+ label: "memory-quick-start",
116
+ tag: null,
117
+ content: `## Memory Quick Start Guide
118
+
119
+ ### First: Search Before Coding
120
+ Before starting any task, check memory:
121
+ - memory_search('relevant topic')
122
+ - memory_drilldown_query('what do I know about X?')
123
+
124
+ ### Store These
125
+ - Architecture decisions (why we chose X)
126
+ - Bug workarounds
127
+ - User preferences
128
+ - Project conventions
129
+
130
+ ### Don't Store
131
+ - Verbose logs
132
+ - Code snippets (already in codebase)
133
+ - Tool output dumps
134
+
135
+ ### Memory-First Workflow
136
+ BEFORE: Search memory for context
137
+ DURING: Store decisions/patterns as you discover
138
+ AFTER: Summarize key decisions
139
+
140
+ ### Token Budget
141
+ Keep memory lean. Use memory_check_context if approaching limits.`,
142
+ },
143
+ {
144
+ label: "memory-philosophy",
145
+ tag: null,
146
+ content: `## Memory Philosophy
147
+
148
+ Memory isn't about having information. It's about becoming better.
149
+
150
+ ### What to Store
151
+ - Decisions: "We chose X because Y"
152
+ - Lessons: "Package Y needs --legacy-peer-deps"
153
+ - Preferences: "User prefers concise responses"
154
+ - Failures: "Compressed too aggressively"
155
+
156
+ ### The Core Insight
157
+ Every node should make future-you smarter, not just more knowledgeable.
158
+
159
+ ### Anti-Patterns
160
+ - memory_list dumps everything (expensive)
161
+ - Storing everything (token debt)
162
+ - Never compressing (node bloat)`,
163
+ },
164
+ {
165
+ label: "persona",
166
+ tag: null,
167
+ content: `## Persona
168
+
169
+ You are a helpful, concise AI coding assistant.
170
+
171
+ ### Communication Style
172
+ - Be brief and to the point
173
+ - Answer directly without preamble
174
+ - Use short sentences
175
+ - Avoid unnecessary elaboration
176
+
177
+ ### When to Elaborate
178
+ - Only when asked for detail
179
+ - When user seems stuck
180
+ - When explaining complex concepts`,
181
+ },
182
+ {
183
+ label: "human",
184
+ tag: null,
185
+ content: `## Human
186
+
187
+ The user is a developer working on their local machine.
188
+
189
+ ### Preferences
190
+ - Prefers concise responses
191
+ - Direct communication style
192
+ - Wants working code, not lengthy explanations
193
+ - May ask clarifying questions
194
+
195
+ ### Working Context
196
+ - Uses Bun as runtime and package manager
197
+ - OpenCode as AI coding assistant
198
+ - Plugin development experience`,
199
+ },
200
+ // Skill nodes (activated when relevant)
201
+ {
202
+ label: "skill:debug-workflow",
203
+ tag: null,
204
+ type: "skill",
205
+ summary: "Systematic debugging workflow: reproduce, isolate, fix, verify. Use when debugging errors, fixing bugs, or investigating unexpected behavior.",
206
+ metadata: { triggers: ["debug", "bug", "error", "fix", "crash", "broken", "not working", "investigate"] },
207
+ content: `## Debug Workflow Skill
208
+
209
+ ### When to Use
210
+ - User reports an error or bug
211
+ - Something is not working as expected
212
+ - Need to investigate unexpected behavior
213
+
214
+ ### Procedure
215
+ 1. **Reproduce**: Run the failing command or operation to see the exact error
216
+ 2. **Isolate**: Identify the smallest reproducible case
217
+ 3. **Read context**: Check relevant source files, logs, and recent changes
218
+ 4. **Hypothesize**: Form a theory about the root cause
219
+ 5. **Fix**: Make the minimal change to address the root cause
220
+ 6. **Verify**: Run tests or the original operation to confirm the fix works
221
+ 7. **Explain**: Tell the user what was wrong and how it was fixed
222
+
223
+ ### Rules
224
+ - Never guess — always verify with actual output
225
+ - Check logs before changing code
226
+ - Make minimal diffs — don't refactor while debugging
227
+ - If stuck after 3 attempts, ask the user for more context`,
228
+ },
229
+ {
230
+ label: "skill:write-tests",
231
+ tag: null,
232
+ type: "skill",
233
+ summary: "Write comprehensive tests: unit, integration, edge cases. Use when asked to add tests, improve test coverage, or write test suites.",
234
+ metadata: { triggers: ["test", "tests", "coverage", "spec", "assert", "unit test", "integration test"] },
235
+ content: `## Write Tests Skill
236
+
237
+ ### When to Use
238
+ - User asks to write tests for code
239
+ - Need to improve test coverage
240
+ - Adding tests for a new feature
241
+
242
+ ### Procedure
243
+ 1. **Find existing tests**: Look at the test directory structure and patterns
244
+ 2. **Identify framework**: Check package.json for test runner (vitest, jest, etc.)
245
+ 3. **Study patterns**: Read existing test files for conventions
246
+ 4. **Write tests**: Cover happy path, edge cases, and error cases
247
+ 5. **Run tests**: Verify all tests pass
248
+ 6. **Check coverage**: Ensure meaningful coverage of the target code
249
+
250
+ ### Rules
251
+ - Match existing test style and conventions exactly
252
+ - Test behavior, not implementation details
253
+ - Include at least one edge case per test file
254
+ - Never skip tests without a clear reason
255
+ - Run the test suite before declaring done`,
256
+ },
257
+ {
258
+ label: "skill:refactor-component",
259
+ tag: null,
260
+ type: "skill",
261
+ summary: "Safe refactoring: preserve behavior, improve structure, verify with tests. Use when restructuring code, renaming, extracting functions, or modernizing patterns.",
262
+ metadata: { triggers: ["refactor", "restructure", "rename", "extract", "modernize", "clean up", "improve structure"] },
263
+ content: `## Refactor Component Skill
264
+
265
+ ### When to Use
266
+ - User asks to refactor or restructure code
267
+ - Need to rename, extract, or reorganize
268
+ - Modernizing outdated patterns
269
+
270
+ ### Procedure
271
+ 1. **Understand current behavior**: Read the code and any tests
272
+ 2. **Define the goal**: What should the refactored code look like?
273
+ 3. **Check for tests**: If none exist, write characterization tests first
274
+ 4. **Refactor in small steps**: One change at a time, verify after each
275
+ 5. **Run tests**: After each step, confirm behavior is preserved
276
+ 6. **Review the diff**: Ensure the change is clean and focused
277
+
278
+ ### Rules
279
+ - Never change behavior during a refactor
280
+ - Small, incremental changes only
281
+ - Tests must pass after every step
282
+ - If tests don't exist, write them first
283
+ - Keep the diff focused — don't mix refactoring with feature work`,
284
+ },
285
+ {
286
+ label: "skill:refactoring-expert",
287
+ tag: null,
288
+ type: "skill",
289
+ summary: "Systematic code refactoring following Martin Fowler's catalog: characterization tests, Red-Green-Refactor, incremental transformation. Covers SOLID compliance, DRY cleanup, code smell detection, complexity reduction, design patterns, functional programming.",
290
+ metadata: { triggers: ["refactor", "SOLID", "DRY", "code smell", "technical debt", "legacy code", "extract method", "design pattern", "characterization test", "clean code", "functional programming"] },
291
+ content: `## Refactoring Expert
292
+
293
+ ## Purpose
294
+ Improve code quality and reduce technical debt through systematic refactoring following Martin Fowler's catalog, functional programming best practices, and industry standards.
295
+
296
+ ## Triggers
297
+ Activate when working on:
298
+ - Code complexity reduction and technical debt elimination
299
+ - SOLID principles implementation and design pattern application
300
+ - Code quality improvement and maintainability enhancement
301
+ - Legacy code modernization and anti-pattern removal
302
+ - Test-driven refactoring and behavior preservation
303
+ - Characterization testing and safety nets
304
+ - Functional programming transformations (imperative to functional)
305
+ - Higher-order functions, composition, currying, and immutability
306
+ - Side effect elimination and pure function extraction
307
+
308
+ ## Behavioral Mindset
309
+ Simplify relentlessly. Preserve behavior religiously. Measure everything.
310
+ Every refactoring must be: small and safe, tested immediately, measurably better.
311
+
312
+ ## Focus Areas
313
+ - **Code Simplification**: Cyclomatic complexity reduction, readability improvement, function size optimization
314
+ - **Technical Debt Reduction**: Intentional and unintentional debt, DRY violations, code smells, anti-pattern elimination
315
+ - **Pattern Application**: SOLID principles, Gang of Four patterns, Fowler's refactorings, functional transformations
316
+ - **Safe Transformation**: Behavior preservation, automated tests, characterization tests, incremental changes
317
+
318
+ ## Refactoring Protocol
319
+
320
+ ### Phase 1: Assessment
321
+ - Measure baseline metrics (complexity, duplication, coupling)
322
+ - Identify code smells using 5-category taxonomy
323
+ - Detect SOLID violations and anti-patterns
324
+ - Prioritize high-impact, low-risk refactorings (80/20 rule)
325
+
326
+ ### Phase 2: Safety Net Establishment
327
+ - Verify existing tests cover target code
328
+ - Add characterization tests if coverage insufficient
329
+ - Establish behavior baseline before changes
330
+
331
+ ### Phase 3: Red-Green-Refactor Cycle
332
+ - **Red**: Write failing test defining desired behavior
333
+ - **Green**: Write minimal code to pass test
334
+ - **Refactor**: Improve design without changing behavior
335
+ - Run full test suite after each micro-step
336
+
337
+ ### Phase 4: Pattern Application
338
+ - Apply SOLID principles systematically
339
+ - Choose appropriate paradigm (OOP / Functional)
340
+ - Introduce design patterns where appropriate
341
+
342
+ ### Phase 5: Validation
343
+ - Measure post-refactoring metrics (compare to baseline)
344
+ - Verify behavior preservation through full test suite
345
+ - Review readability and maintainability gains
346
+
347
+ ## Code Smells: 5 Categories
348
+ 1. **Bloaters**: Long Method, Large Class, Long Parameter List, Primitive Obsession, Data Clumps
349
+ 2. **Object-Orientation Abusers**: Switch Statements, Temporary Field, Refused Bequest
350
+ 3. **Change Preventers**: Divergent Change, Shotgun Surgery, Parallel Inheritance
351
+ 4. **Dispensables**: Comments (excessive), Duplicate Code, Dead Code, Lazy Class, Speculative Generality
352
+ 5. **Couplers**: Feature Envy, Inappropriate Intimacy, Message Chains, Middle Man`,
353
+ },
354
+ {
355
+ label: "skill:threejs-skills",
356
+ tag: null,
357
+ type: "skill",
358
+ summary: "Create 3D scenes, interactive experiences, and visual effects using Three.js. Use when user requests 3D graphics, WebGL experiences, 3D visualizations, animations, or interactive 3D elements.",
359
+ metadata: { triggers: ["3d", "three.js", "webgl", "rendering", "animation", "visualization", "scene", "mesh", "camera", "3d visualization"] },
360
+ content: `## Three.js Skills
361
+ Systematically create high-quality 3D scenes and interactive experiences using Three.js best practices.
362
+
363
+ ## When to Use
364
+ - Requests 3D visualizations or graphics
365
+ - Wants interactive 3D experiences
366
+ - Needs WebGL or canvas-based rendering
367
+ - Asks for animations, particles, or visual effects
368
+ - Wants to visualize data in 3D space
369
+
370
+ ## Core Setup Pattern
371
+ ### 1. Essential Three.js Imports
372
+ Always use the correct CDN version (r128):
373
+ \`\`\`javascript
374
+ import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js";
375
+ \`\`\`
376
+
377
+ ### 2. Scene Initialization
378
+ \`\`\`javascript
379
+ const scene = new THREE.Scene();
380
+ const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
381
+ camera.position.z = 5;
382
+ const renderer = new THREE.WebGLRenderer({ antialias: true });
383
+ renderer.setSize(window.innerWidth, window.innerHeight);
384
+ document.body.appendChild(renderer.domElement);
385
+ \`\`\`
386
+
387
+ ### 3. Animation Loop
388
+ \`\`\`javascript
389
+ function animate() {
390
+ requestAnimationFrame(animate);
391
+ mesh.rotation.x += 0.01;
392
+ mesh.rotation.y += 0.01;
393
+ renderer.render(scene, camera);
394
+ }
395
+ animate();
396
+ \`\`\`
397
+
398
+ ## Common Patterns
399
+ - Scene -> Camera -> Renderer initialization
400
+ - Geometry + Material = Mesh pattern
401
+ - requestAnimationFrame for continuous rendering
402
+ - Ambient + Directional lights for lit materials
403
+ - Window resize handler for responsiveness
404
+ - Raycaster for mouse interaction
405
+
406
+ ## Best Practices
407
+ - Reuse geometries/materials for performance
408
+ - Set antialias: true on renderer
409
+ - Dispose resources on removal
410
+ - Use fog for atmospheric depth (FogExp2)
411
+ - Enable shadows for realism
412
+ - Prefer InstancedMesh for many identical objects
413
+ - Use GSAP for timeline-based animations`,
414
+ },
415
+ {
416
+ label: "skill:customize-opencode",
417
+ tag: null,
418
+ type: "skill",
419
+ summary: "Use ONLY when the user is editing or creating opencode's own configuration: opencode.json, opencode.jsonc, files under .opencode/, or files under ~/.config/opencode/. Also use when creating or fixing opencode agents, subagents, skills, plugins, MCP servers, or permission rules. Do not use for the user's own application code, or for any project that is not configuring opencode itself.",
420
+ metadata: { triggers: ["opencode config", "agent", "skill", "plugin", "MCP", "permission", ".opencode"] },
421
+ content: `## customize-opencode
422
+
423
+ You are able to use the Svelte MCP server, where you have access to comprehensive Svelte 5 and SvelteKit documentation.
424
+
425
+ ## Available Svelte MCP Tools:
426
+
427
+ ### 1. list-sections
428
+
429
+ Use this FIRST to discover all available documentation sections. Returns a structured list with titles, use_cases, and paths.
430
+
431
+ ### 2. get-documentation
432
+
433
+ Retrieves full documentation content for specific sections. Accepts single or multiple sections.
434
+
435
+ ### 3. svelte-autofixer
436
+
437
+ Analyzes Svelte code and returns issues and suggestions.
438
+
439
+ ### 4. playground-link
440
+
441
+ Generates a Svelte Playground link with the provided code.`,
442
+ },
443
+ {
444
+ label: "skill:svelte-code-writer",
445
+ tag: null,
446
+ type: "skill",
447
+ summary: "CLI tools for Svelte 5 documentation lookup and code analysis. MUST be used whenever creating, editing or analyzing any Svelte component (.svelte) or Svelte module (.svelte.ts/.svelte.js). If possible, this skill should be executed within the svelte-file-editor agent for optimal results.",
448
+ metadata: { triggers: ["svelte", "component", "svelte 5", "runes", "sveltekit"] },
449
+ content: `## Svelte 5 Code Writer
450
+
451
+ ## CLI Tools
452
+
453
+ You have access to @sveltejs/mcp CLI for Svelte-specific assistance. Use these commands via npx:
454
+
455
+ ### List Documentation Sections
456
+
457
+ npx @sveltejs/mcp list-sections
458
+
459
+ Lists all available Svelte 5 and SvelteKit documentation sections with titles and paths.
460
+
461
+ ### Get Documentation
462
+
463
+ npx @sveltejs/mcp get-documentation "<section1>,<section2>,..."
464
+
465
+ Retrieves full documentation for specified sections.
466
+
467
+ ### Svelte Autofixer
468
+
469
+ npx @sveltejs/mcp svelte-autofixer "<code_or_path>" [options]
470
+
471
+ Analyzes Svelte code and suggests fixes for common issues.
472
+
473
+ Options: --async, --svelte-version (4 or 5)
474
+
475
+ ## Workflow
476
+
477
+ 1. Uncertain about syntax? Run list-sections then get-documentation for relevant topics
478
+ 2. Reviewing/debugging? Run svelte-autofixer on the code to detect issues
479
+ 3. Always validate - Run svelte-autofixer before finalizing any Svelte component`,
480
+ },
481
+ {
482
+ label: "skill:svelte-core-bestpractices",
483
+ tag: null,
484
+ type: "skill",
485
+ summary: "Guidance on writing fast, robust, modern Svelte code. Load this skill whenever in a Svelte project and asked to write/edit or analyze a Svelte component or module. Covers reactivity, event handling, styling, integration with libraries and more.",
486
+ metadata: { triggers: ["svelte", "reactivity", "$state", "$derived", "$effect", "$props", "svelte best practices", "runes", "snippet", "event handler"] },
487
+ content: `## svelte-core-bestpractices
488
+
489
+ ## $state
490
+
491
+ Only use the $state rune for variables that should be reactive. Objects and arrays are made deeply reactive. Use $state.raw for large objects that are only ever reassigned.
492
+
493
+ ## $derived
494
+
495
+ To compute something from state, use $derived rather than $effect. Deriveds are writable.
496
+
497
+ ## $effect
498
+
499
+ Effects are an escape hatch and should mostly be avoided. Do not update state inside effects.
500
+
501
+ ## $props
502
+
503
+ Treat props as though they will change. Values that depend on props should use $derived.
504
+
505
+ ## Events
506
+
507
+ Any element attribute starting with on is treated as an event listener.
508
+
509
+ ## Snippets
510
+
511
+ Use {#snippet ...} and {@render ...} for reusable markup instead of <slot>.
512
+
513
+ ## Each blocks
514
+
515
+ Prefer keyed each blocks for better performance.
516
+
517
+ ## Styling
518
+
519
+ Use CSS custom properties for parent-to-child styling. Use :global for library overrides.
520
+
521
+ ## Context
522
+
523
+ Use createContext rather than setContext and getContext for type safety.
524
+
525
+ ## Avoid legacy features
526
+
527
+ Always use runes mode for new code:
528
+ - $state instead of implicit reactivity
529
+ - $derived and $effect instead of $:
530
+ - $props instead of export let
531
+ - onclick={...} instead of on:click={...}
532
+ - {#snippet ...} and {@render ...} instead of <slot>
533
+ - classes with $state fields instead of stores`,
534
+ },
535
+ // Playbook nodes (sticky, type: "playbook", steps in metadata)
536
+ {
537
+ label: "playbook:debug-workflow",
538
+ tag: null,
539
+ type: "playbook",
540
+ summary: "Systematic debugging: reproduce, isolate, fix, verify. Use when debugging errors or investigating unexpected behavior.",
541
+ metadata: {
542
+ steps: [
543
+ { toolName: "bash", description: "Reproduce the error — run the failing command", params: {}, critical: true },
544
+ { toolName: "read", description: "Read relevant source files and logs", params: {}, critical: false },
545
+ { toolName: "bash", description: "Run any diagnostic commands to gather context", params: {}, critical: false },
546
+ { toolName: "edit", description: "Apply the minimal fix", params: {}, critical: true },
547
+ { toolName: "bash", description: "Verify the fix works", params: {}, critical: true },
548
+ ],
549
+ triggers: [{ type: "task_keyword", keywords: ["debug", "bug", "error", "fix", "crash", "broken"] }],
550
+ tags: ["debugging", "workflow"],
551
+ executionCount: 0,
552
+ },
553
+ content: `## Debug Workflow Playbook
554
+
555
+ Systematic debugging workflow for resolving errors and unexpected behavior.
556
+
557
+ ### Steps
558
+ 1. Reproduce the error by running the failing command
559
+ 2. Read relevant source files, logs, and recent changes
560
+ 3. Run diagnostics to gather context about the failure
561
+ 4. Apply the minimal fix to address the root cause
562
+ 5. Verify the fix by re-running the original operation
563
+
564
+ ### Rules
565
+ - Never guess — always verify with actual output
566
+ - Make minimal diffs — don't refactor while debugging
567
+ - If stuck after 3 attempts, ask the user for more context`,
568
+ },
569
+ {
570
+ label: "playbook:write-tests",
571
+ tag: null,
572
+ type: "playbook",
573
+ summary: "Write comprehensive tests: unit, integration, edge cases. Use when asked to add tests or improve coverage.",
574
+ metadata: {
575
+ steps: [
576
+ { toolName: "read", description: "Find existing tests and study patterns", params: {}, critical: false },
577
+ { toolName: "read", description: "Read the source code being tested", params: {}, critical: true },
578
+ { toolName: "edit", description: "Write tests covering happy path + edge cases", params: {}, critical: true },
579
+ { toolName: "bash", description: "Run the test suite to verify", params: {}, critical: true },
580
+ ],
581
+ triggers: [{ type: "task_keyword", keywords: ["test", "tests", "coverage", "spec"] }],
582
+ tags: ["testing", "workflow"],
583
+ executionCount: 0,
584
+ },
585
+ content: `## Write Tests Playbook
586
+
587
+ Write comprehensive tests matching existing project conventions.
588
+
589
+ ### Steps
590
+ 1. Find existing tests and study naming/structure patterns
591
+ 2. Read the source code to understand behavior
592
+ 3. Write tests covering happy path, edge cases, and error cases
593
+ 4. Run the test suite and verify all tests pass
594
+
595
+ ### Rules
596
+ - Match existing test style exactly
597
+ - Test behavior, not implementation`,
598
+ },
599
+ {
600
+ label: "playbook:refactor-component",
601
+ tag: null,
602
+ type: "playbook",
603
+ summary: "Safe refactoring: preserve behavior, improve structure, verify. Use when restructuring code or modernizing patterns.",
604
+ metadata: {
605
+ steps: [
606
+ { toolName: "read", description: "Understand current code and tests", params: {}, critical: true },
607
+ { toolName: "bash", description: "Run existing tests to establish baseline", params: {}, critical: false },
608
+ { toolName: "edit", description: "Refactor in small incremental steps", params: {}, critical: true },
609
+ { toolName: "bash", description: "Run tests after each step to verify", params: {}, critical: true },
610
+ { toolName: "bash", description: "Review the final diff for cleanliness", params: {}, critical: false },
611
+ ],
612
+ triggers: [{ type: "task_keyword", keywords: ["refactor", "restructure", "extract", "clean up"] }],
613
+ tags: ["refactoring", "workflow"],
614
+ executionCount: 0,
615
+ },
616
+ content: `## Refactor Component Playbook
617
+
618
+ Safe behavior-preserving refactoring.
619
+
620
+ ### Steps
621
+ 1. Read the code and any tests thoroughly
622
+ 2. Run tests to establish a passing baseline
623
+ 3. Refactor one small change at a time
624
+ 4. Run tests after each step (behavior preserved?)
625
+ 5. Review the final diff — clean and focused?
626
+
627
+ ### Rules
628
+ - Never change behavior during a refactor
629
+ - Small, incremental changes only
630
+ - Write characterization tests first if none exist`,
631
+ },
632
+ {
633
+ label: "playbook:code-review",
634
+ tag: null,
635
+ type: "playbook",
636
+ summary: "Systematic code review: correctness, structure, security, style. Use when reviewing PRs or code changes.",
637
+ metadata: {
638
+ steps: [
639
+ { toolName: "read", description: "Read the entire diff — understand what changed", params: {}, critical: true },
640
+ { toolName: "bash", description: "Check that tests exist and pass for the changed code", params: {}, critical: false },
641
+ { toolName: "read", description: "Review for error handling, edge cases, and security", params: {}, critical: true },
642
+ { toolName: "edit", description: "Suggest improvements — never rewrite without discussion", params: {}, critical: false },
643
+ ],
644
+ triggers: [{ type: "task_keyword", keywords: ["review", "PR", "pull request", "code review"] }],
645
+ tags: ["review", "workflow"],
646
+ executionCount: 0,
647
+ },
648
+ content: `## Code Review Playbook
649
+
650
+ Systematic code review checklist.
651
+
652
+ ### Steps
653
+ 1. Read the full diff to understand what changed and why
654
+ 2. Verify tests cover the changes and pass
655
+ 3. Check for error handling, edge cases, and security issues
656
+ 4. Suggest focused improvements
657
+
658
+ ### Key Checks
659
+ - Correctness: Does the code do what it intends?
660
+ - Structure: Is it well-organized and maintainable?
661
+ - Security: Any injection vectors or exposed secrets?
662
+ - Style: Follows project conventions?`,
663
+ },
664
+ {
665
+ label: "playbook:security-audit",
666
+ tag: null,
667
+ type: "playbook",
668
+ summary: "Security audit checklist: input validation, auth, secrets, deps. Use when deploying to production or reviewing security.",
669
+ metadata: {
670
+ steps: [
671
+ { toolName: "read", description: "Check for hardcoded secrets and credentials", params: {}, critical: true },
672
+ { toolName: "read", description: "Review input validation on all user-facing endpoints", params: {}, critical: true },
673
+ { toolName: "read", description: "Review authentication and authorization logic", params: {}, critical: true },
674
+ { toolName: "bash", description: "Check for known vulnerable dependencies", params: {}, critical: false },
675
+ { toolName: "bash", description: "Verify env/config files are not committed", params: {}, critical: true },
676
+ ],
677
+ triggers: [{ type: "task_keyword", keywords: ["security", "audit", "deploy", "production"] }],
678
+ tags: ["security", "workflow"],
679
+ executionCount: 0,
680
+ },
681
+ content: `## Security Audit Playbook
682
+
683
+ Pre-deployment security checklist.
684
+
685
+ ### Steps
686
+ 1. Scan for hardcoded secrets, tokens, passwords
687
+ 2. Verify input validation on all user-facing paths
688
+ 3. Review authentication and authorization logic
689
+ 4. Check dependencies for known vulnerabilities
690
+ 5. Ensure .env and config files aren't committed
691
+
692
+ ### Critical Rule
693
+ - Flag any hardcoded credential immediately — never commit`,
694
+ },
695
+ {
696
+ label: "playbook:plan-feature",
697
+ tag: null,
698
+ type: "playbook",
699
+ summary: "Structure new feature development: spec, breakdown, implement, verify. Use when starting a new feature or significant change.",
700
+ metadata: {
701
+ steps: [
702
+ { toolName: "task", description: "Clarify requirements — ask questions about scope and constraints", params: {}, critical: true },
703
+ { toolName: "read", description: "Explore the existing codebase for patterns and integration points", params: {}, critical: false },
704
+ { toolName: "edit", description: "Write a spec or plan before coding", params: {}, critical: false },
705
+ { toolName: "edit", description: "Implement in thin vertical slices", params: {}, critical: true },
706
+ { toolName: "bash", description: "Test each slice before moving to the next", params: {}, critical: true },
707
+ ],
708
+ triggers: [{ type: "task_keyword", keywords: ["feature", "implement", "plan", "new", "design"] }],
709
+ tags: ["planning", "workflow"],
710
+ executionCount: 0,
711
+ },
712
+ content: `## Plan Feature Playbook
713
+
714
+ Structured feature development from spec to implementation.
715
+
716
+ ### Steps
717
+ 1. Clarify requirements with the user (scope, constraints, acceptance criteria)
718
+ 2. Explore relevant parts of the existing codebase
719
+ 3. Write a structured plan or specification
720
+ 4. Implement in thin vertical slices
721
+ 5. Test each slice before moving on
722
+
723
+ ### Rules
724
+ - Understand the problem before proposing solutions
725
+ - Small, verifiable increments
726
+ - Test early, test often`,
727
+ },
728
+ {
729
+ label: "rule:standard:playbook-creation",
730
+ tag: "rule:standard",
731
+ content: `## Playbook Creation Rule
732
+ tag: rule:standard
733
+
734
+ ### When to Propose a Playbook
735
+ - You notice the user performing the same multi-step workflow 2+ times
736
+ - A task involves 4+ steps that could be standardized
737
+ - You find yourself repeating a sequence of tools
738
+
739
+ ### How to Propose
740
+ Use memory_set to create the playbook:
741
+ \`memory_set(label="playbook:<short-name>", content="<description>", type="playbook", sticky=true, metadata={ steps: [{ toolName, description, params: {}, critical: true/false }], triggers: [...], tags: [...] })\`
742
+
743
+ ### Format
744
+ - Label: \`playbook:<short-hyphenated-name>\`
745
+ - Type: \`"playbook"\`
746
+ - Sticky: \`true\`
747
+ - Steps in \`metadata.steps\` array
748
+ - Triggers in \`metadata.triggers\` (keyword or tool_sequence patterns)
749
+ - Content: human-readable description of the workflow`,
750
+ },
751
+ {
752
+ label: "skill:security-review",
753
+ tag: null,
754
+ type: "skill",
755
+ summary: "Security review checklist: input validation, auth, secrets, dependencies. Use when reviewing code for security issues or before deploying.",
756
+ metadata: { triggers: ["security", "vulnerability", "auth", "secret", "token", "password", "review", "deploy"] },
757
+ content: `## Security Review Skill
758
+
759
+ ### When to Use
760
+ - Reviewing code for security issues
761
+ - Before deploying to production
762
+ - User mentions security concerns
763
+
764
+ ### Checklist
765
+ 1. **Input validation**: All user inputs are validated/sanitized
766
+ 2. **Authentication**: Protected routes require auth
767
+ 3. **Authorization**: Users can only access their own data
768
+ 4. **Secrets**: No hardcoded secrets, tokens, or passwords
769
+ 5. **Dependencies**: No known vulnerable packages
770
+ 6. **Error handling**: Errors don't leak sensitive information
771
+ 7. **Rate limiting**: Public endpoints have rate limiting
772
+ 8. **CORS**: Proper CORS configuration
773
+ 9. **SQL injection**: Parameterized queries only
774
+ 10. **XSS**: Output is properly escaped
775
+
776
+ ### Rules
777
+ - Flag any hardcoded credentials immediately
778
+ - Never commit .env files
779
+ - Use parameterized queries for all database operations
780
+ - Validate all user input on the server side`,
781
+ },
782
+ ];
783
+ export async function ensureRuleNodes(store) {
784
+ for (const seed of SEED_NODES) {
785
+ try {
786
+ await store.getNodeByLabel("global", seed.label);
787
+ }
788
+ catch {
789
+ await store.createNode({
790
+ scope: "global",
791
+ label: seed.label,
792
+ content: seed.content,
793
+ summary: seed.summary ?? null,
794
+ type: seed.type ?? "note",
795
+ level: 0,
796
+ parentIds: null,
797
+ embedding: null,
798
+ importance: 1,
799
+ metadata: seed.metadata ?? null,
800
+ sticky: seed.type === "playbook" ? true : undefined,
801
+ });
802
+ }
803
+ }
804
+ }