autosnippet 3.2.18 → 3.2.21

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 (189) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +73 -104
  3. package/config/default.json +1 -1
  4. package/dashboard/dist/assets/{index-CKMy5LY6.js → index-DdvZE4Yd.js} +1 -1
  5. package/dashboard/dist/index.html +1 -1
  6. package/dist/bin/cli.js +45 -10
  7. package/dist/lib/agent/AgentEventBus.js +3 -3
  8. package/dist/lib/agent/AgentFactory.d.ts +3 -3
  9. package/dist/lib/agent/AgentFactory.js +4 -4
  10. package/dist/lib/agent/AgentMessage.d.ts +8 -8
  11. package/dist/lib/agent/AgentMessage.js +8 -8
  12. package/dist/lib/agent/AgentRuntime.js +2 -2
  13. package/dist/lib/agent/AgentState.js +4 -4
  14. package/dist/lib/agent/ConversationStore.d.ts +1 -1
  15. package/dist/lib/agent/ConversationStore.js +1 -1
  16. package/dist/lib/agent/PipelineStrategy.js +1 -1
  17. package/dist/lib/agent/context/ContextWindow.d.ts +2 -2
  18. package/dist/lib/agent/context/ContextWindow.js +7 -7
  19. package/dist/lib/agent/context/ExplorationTracker.js +9 -9
  20. package/dist/lib/agent/context/exploration/PlanTracker.js +2 -2
  21. package/dist/lib/agent/context/exploration/SignalDetector.d.ts +1 -1
  22. package/dist/lib/agent/context/exploration/SignalDetector.js +1 -1
  23. package/dist/lib/agent/core/LoopContext.d.ts +21 -21
  24. package/dist/lib/agent/core/LoopContext.js +21 -21
  25. package/dist/lib/agent/core/SystemPromptBuilder.js +4 -4
  26. package/dist/lib/agent/domain/EvidenceCollector.js +5 -5
  27. package/dist/lib/agent/memory/ActiveContext.js +1 -1
  28. package/dist/lib/agent/memory/MemoryRetriever.js +1 -1
  29. package/dist/lib/agent/memory/MemoryStore.js +2 -2
  30. package/dist/lib/agent/memory/SessionStore.js +3 -3
  31. package/dist/lib/agent/policies.d.ts +1 -1
  32. package/dist/lib/agent/policies.js +1 -1
  33. package/dist/lib/agent/strategies.d.ts +1 -1
  34. package/dist/lib/agent/strategies.js +4 -4
  35. package/dist/lib/agent/tools/_shared.d.ts +1 -1
  36. package/dist/lib/agent/tools/_shared.js +1 -1
  37. package/dist/lib/agent/tools/infrastructure.js +2 -2
  38. package/dist/lib/cli/SetupService.d.ts +25 -25
  39. package/dist/lib/cli/SetupService.js +28 -15
  40. package/dist/lib/cli/deploy/FileDeployer.d.ts +9 -2
  41. package/dist/lib/cli/deploy/FileDeployer.js +139 -46
  42. package/dist/lib/cli/deploy/FileManifest.d.ts +23 -39
  43. package/dist/lib/cli/deploy/FileManifest.js +22 -33
  44. package/dist/lib/core/AstAnalyzer.d.ts +2 -2
  45. package/dist/lib/core/AstAnalyzer.js +2 -2
  46. package/dist/lib/core/analysis/CallEdgeResolver.d.ts +7 -7
  47. package/dist/lib/core/analysis/CallEdgeResolver.js +9 -9
  48. package/dist/lib/core/analysis/CallGraphAnalyzer.d.ts +4 -4
  49. package/dist/lib/core/analysis/CallGraphAnalyzer.js +2 -2
  50. package/dist/lib/core/analysis/ImportPathResolver.d.ts +0 -2
  51. package/dist/lib/core/analysis/ImportPathResolver.js +2 -4
  52. package/dist/lib/core/ast/ProjectGraph.js +7 -7
  53. package/dist/lib/core/capability/CapabilityProbe.js +6 -14
  54. package/dist/lib/domain/knowledge/UnifiedValidator.js +2 -2
  55. package/dist/lib/domain/knowledge/values/Constraints.js +4 -4
  56. package/dist/lib/domain/knowledge/values/Content.js +6 -6
  57. package/dist/lib/domain/knowledge/values/Quality.js +5 -5
  58. package/dist/lib/domain/knowledge/values/Reasoning.js +5 -5
  59. package/dist/lib/domain/knowledge/values/Relations.js +1 -1
  60. package/dist/lib/domain/knowledge/values/Stats.js +6 -6
  61. package/dist/lib/domain/task/TaskIdGenerator.d.ts +4 -4
  62. package/dist/lib/domain/task/TaskIdGenerator.js +2 -2
  63. package/dist/lib/external/lark/LarkTransport.js +4 -4
  64. package/dist/lib/external/mcp/McpServer.d.ts +3 -7
  65. package/dist/lib/external/mcp/McpServer.js +9 -13
  66. package/dist/lib/external/mcp/handlers/bootstrap/ExternalSubmissionTracker.js +5 -5
  67. package/dist/lib/external/mcp/handlers/bootstrap/MissionBriefingBuilder.js +4 -3
  68. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/BootstrapSnapshot.d.ts +3 -3
  69. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/BootstrapSnapshot.js +3 -3
  70. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/IncrementalBootstrap.d.ts +1 -1
  71. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/IncrementalBootstrap.js +1 -1
  72. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/dimension-context.js +3 -3
  73. package/dist/lib/external/mcp/handlers/bootstrap/shared/dimension-sop.js +27 -14
  74. package/dist/lib/external/mcp/handlers/bootstrap-external.js +6 -0
  75. package/dist/lib/external/mcp/handlers/dimension-complete-external.js +55 -1
  76. package/dist/lib/external/mcp/handlers/skill.js +9 -31
  77. package/dist/lib/external/mcp/handlers/system.js +6 -4
  78. package/dist/lib/external/mcp/handlers/task.js +16 -1
  79. package/dist/lib/external/mcp/tools.d.ts +12 -10
  80. package/dist/lib/external/mcp/tools.js +97 -69
  81. package/dist/lib/http/utils/routeHelpers.d.ts +1 -1
  82. package/dist/lib/http/utils/routeHelpers.js +1 -1
  83. package/dist/lib/http/utils/sse-sessions.d.ts +1 -1
  84. package/dist/lib/http/utils/sse-sessions.js +1 -1
  85. package/dist/lib/infrastructure/cache/CacheService.js +1 -1
  86. package/dist/lib/infrastructure/logging/Logger.js +1 -1
  87. package/dist/lib/infrastructure/monitoring/ErrorTracker.js +1 -1
  88. package/dist/lib/infrastructure/vector/AsyncPersistence.js +8 -8
  89. package/dist/lib/infrastructure/vector/BatchEmbedder.d.ts +1 -1
  90. package/dist/lib/infrastructure/vector/BatchEmbedder.js +2 -2
  91. package/dist/lib/infrastructure/vector/HnswIndex.d.ts +4 -4
  92. package/dist/lib/infrastructure/vector/HnswIndex.js +5 -5
  93. package/dist/lib/infrastructure/vector/HnswVectorAdapter.js +8 -8
  94. package/dist/lib/infrastructure/vector/ScalarQuantizer.d.ts +1 -1
  95. package/dist/lib/infrastructure/vector/ScalarQuantizer.js +4 -4
  96. package/dist/lib/infrastructure/vector/VectorStore.d.ts +1 -1
  97. package/dist/lib/infrastructure/vector/VectorStore.js +1 -1
  98. package/dist/lib/injection/ServiceContainer.d.ts +1 -1
  99. package/dist/lib/injection/ServiceContainer.js +1 -1
  100. package/dist/lib/injection/modules/KnowledgeModule.js +4 -5
  101. package/dist/lib/platform/NativeUi.d.ts +1 -1
  102. package/dist/lib/platform/NativeUi.js +1 -1
  103. package/dist/lib/platform/ios/spm/DependencyGraph.d.ts +1 -1
  104. package/dist/lib/platform/ios/spm/DependencyGraph.js +1 -1
  105. package/dist/lib/platform/ios/spm/PolicyEngine.d.ts +1 -1
  106. package/dist/lib/platform/ios/spm/PolicyEngine.js +1 -1
  107. package/dist/lib/platform/ios/spm/SpmDiscoverer.js +1 -1
  108. package/dist/lib/platform/ios/spm/SpmHelper.js +3 -3
  109. package/dist/lib/platform/ios/xcode/SaveEventFilter.js +2 -2
  110. package/dist/lib/platform/ios/xcode/XcodeIntegration.js +1 -1
  111. package/dist/lib/repository/base/BaseRepository.js +1 -1
  112. package/dist/lib/repository/task/TaskRepository.impl.d.ts +2 -2
  113. package/dist/lib/repository/task/TaskRepository.impl.js +1 -1
  114. package/dist/lib/repository/token/TokenUsageStore.js +1 -1
  115. package/dist/lib/service/automation/ActionPipeline.d.ts +1 -1
  116. package/dist/lib/service/automation/ActionPipeline.js +1 -1
  117. package/dist/lib/service/bootstrap/BootstrapEventEmitter.js +2 -2
  118. package/dist/lib/service/bootstrap/BootstrapTaskManager.d.ts +1 -1
  119. package/dist/lib/service/bootstrap/BootstrapTaskManager.js +2 -2
  120. package/dist/lib/service/bootstrap/DimensionCopyRegistry.d.ts +2 -2
  121. package/dist/lib/service/bootstrap/DimensionCopyRegistry.js +2 -2
  122. package/dist/lib/service/delivery/AgentInstructionsGenerator.d.ts +6 -15
  123. package/dist/lib/service/delivery/AgentInstructionsGenerator.js +53 -189
  124. package/dist/lib/service/delivery/CursorDeliveryPipeline.d.ts +6 -16
  125. package/dist/lib/service/delivery/CursorDeliveryPipeline.js +14 -19
  126. package/dist/lib/service/delivery/KnowledgeCompressor.d.ts +1 -1
  127. package/dist/lib/service/delivery/KnowledgeCompressor.js +1 -1
  128. package/dist/lib/service/delivery/RulesGenerator.d.ts +10 -3
  129. package/dist/lib/service/delivery/RulesGenerator.js +43 -3
  130. package/dist/lib/service/delivery/SkillsSyncer.d.ts +21 -7
  131. package/dist/lib/service/delivery/SkillsSyncer.js +46 -10
  132. package/dist/lib/service/delivery/TopicClassifier.d.ts +3 -6
  133. package/dist/lib/service/delivery/TopicClassifier.js +0 -3
  134. package/dist/lib/service/guard/ExclusionManager.d.ts +1 -1
  135. package/dist/lib/service/guard/ExclusionManager.js +1 -1
  136. package/dist/lib/service/guard/GuardCheckEngine.d.ts +3 -3
  137. package/dist/lib/service/guard/GuardCheckEngine.js +5 -5
  138. package/dist/lib/service/guard/GuardCrossFileChecks.d.ts +1 -1
  139. package/dist/lib/service/guard/GuardFeedbackLoop.d.ts +3 -3
  140. package/dist/lib/service/guard/GuardFeedbackLoop.js +3 -3
  141. package/dist/lib/service/guard/GuardPatternUtils.js +1 -1
  142. package/dist/lib/service/guard/GuardService.d.ts +1 -15
  143. package/dist/lib/service/guard/GuardService.js +0 -1
  144. package/dist/lib/service/guard/RuleLearner.d.ts +1 -1
  145. package/dist/lib/service/guard/RuleLearner.js +1 -1
  146. package/dist/lib/service/knowledge/CodeEntityGraph.d.ts +3 -3
  147. package/dist/lib/service/knowledge/CodeEntityGraph.js +3 -3
  148. package/dist/lib/service/knowledge/KnowledgeService.d.ts +0 -1
  149. package/dist/lib/service/knowledge/KnowledgeService.js +0 -1
  150. package/dist/lib/service/module/ModuleService.d.ts +1 -1
  151. package/dist/lib/service/module/ModuleService.js +2 -2
  152. package/dist/lib/service/search/HybridRetriever.d.ts +2 -2
  153. package/dist/lib/service/search/HybridRetriever.js +2 -2
  154. package/dist/lib/service/search/SearchEngine.d.ts +1 -3
  155. package/dist/lib/service/search/SearchEngine.js +1 -3
  156. package/dist/lib/service/search/contextBoost.d.ts +1 -1
  157. package/dist/lib/service/skills/EventAggregator.js +2 -2
  158. package/dist/lib/service/skills/SignalCollector.js +1 -1
  159. package/dist/lib/service/snippet/codecs/VSCodeCodec.js +1 -1
  160. package/dist/lib/service/task/TaskGraphService.d.ts +0 -3
  161. package/dist/lib/service/task/TaskGraphService.js +0 -3
  162. package/dist/lib/service/task/TaskKnowledgeBridge.d.ts +8 -27
  163. package/dist/lib/service/task/TaskKnowledgeBridge.js +0 -8
  164. package/dist/lib/service/task/TaskReadyEngine.d.ts +1 -2
  165. package/dist/lib/service/task/TaskReadyEngine.js +0 -1
  166. package/dist/lib/service/wiki/WikiRenderers.js +0 -1
  167. package/dist/lib/service/wiki/WikiUtils.js +2 -7
  168. package/dist/lib/shared/PathGuard.js +6 -6
  169. package/dist/lib/shared/schemas/config.js +1 -1
  170. package/dist/lib/shared/schemas/mcp-tools.js +84 -43
  171. package/dist/scripts/install-vscode-copilot.js +14 -4
  172. package/package.json +1 -1
  173. package/skills/autosnippet-create/SKILL.md +131 -131
  174. package/skills/autosnippet-devdocs/SKILL.md +1 -2
  175. package/skills/autosnippet-guard/SKILL.md +20 -89
  176. package/skills/autosnippet-recipes/SKILL.md +35 -117
  177. package/skills/autosnippet-structure/SKILL.md +23 -55
  178. package/templates/cursor-rules/autosnippet-skills.mdc +17 -33
  179. package/templates/instructions/agent-static.md +24 -0
  180. package/templates/instructions/conventions.md +42 -0
  181. package/skills/autosnippet-analysis/SKILL.md +0 -169
  182. package/skills/autosnippet-candidates/SKILL.md +0 -367
  183. package/skills/autosnippet-coldstart/SKILL.md +0 -988
  184. package/skills/autosnippet-concepts/SKILL.md +0 -630
  185. package/skills/autosnippet-intent/SKILL.md +0 -55
  186. package/skills/autosnippet-lifecycle/SKILL.md +0 -100
  187. package/templates/copilot-instructions.md +0 -66
  188. package/templates/cursor-rules/autosnippet-conventions.mdc +0 -172
  189. package/templates/cursor-rules/autosnippet-workflow.mdc +0 -76
@@ -1,630 +0,0 @@
1
- ---
2
- name: autosnippet-concepts
3
- description: Teaches the agent AutoSnippet's core concepts: knowledge base (知识库), Recipe (配方), Snippet, Candidates, context storage (向量库), and where they live. Recipe priority over project implementation. Includes capability and content summary. Use when the user asks about "知识库", Recipe, Snippet, 向量库, or the structure of AutoSnippet project data.
4
- ---
5
-
6
- # AutoSnippet Concepts (Knowledge Base and Recipe)
7
-
8
- This skill explains [AutoSnippet](https://github.com/GxFn/AutoSnippet)'s **knowledge base** (知识库) and related concepts so the agent can answer "what is X" and "where does Y live."
9
-
10
- ## Instructions for the agent
11
-
12
- 1. **Project root** = directory containing `AutoSnippet/AutoSnippet.boxspec.json`. All paths below are relative to the project root.
13
- 2. For **looking up** existing Recipe content or **searching** recipes, use the **autosnippet-recipes** skill.
14
- 3. For **creating** a new Recipe or Snippet, use the **autosnippet-create** skill.
15
- 4. For **project structure** (targets/dep graph), use **autosnippet-structure**.
16
-
17
- 5. **Self-check & Fallback (统一 Envelope)**
18
- - Before heavy operations, call `autosnippet_health`.
19
- - All MCP tools return a JSON Envelope: `{ success, errorCode?, message?, data?, meta }`.
20
- - On failure or empty results, do NOT retry within the same cycle; fall back to static context or ask user for minimal confirmation, then continue with reduced scope.
21
-
22
- ---
23
-
24
- ## Knowledge base (知识库)
25
-
26
- In AutoSnippet, the **知识库** is the set of project-owned artifacts under **`AutoSnippet/`** used for standards, reuse, and AI context:
27
-
28
- | Part | Location | Meaning |
29
- |------|----------|---------|
30
- | **Snippets** | AutoSnippet 根 spec `list` 或 `AutoSnippet/snippets/*.json` | Code snippets synced to IDE (Xcode CodeSnippets / VSCode .code-snippets); developers use them by trigger (completion). |
31
- | **Recipes** | `AutoSnippet/recipes/*.md` (or `recipes.dir` in root spec) | Markdown docs: standard code + usage guide; used for AI context, Guard, and search. |
32
- | **Candidates** | `AutoSnippet/.autosnippet/candidates.json` | AI-scanned candidates; review in Dashboard **Candidates** then approve or delete. |
33
- | **Context index** | `AutoSnippet/.autosnippet/context/` | Vector index built by `asd embed`; used for on-demand semantic search and Guard. |
34
-
35
- ---
36
-
37
- ## Context Storage and Vector Store
38
-
39
- The knowledge base has **context storage** capability: Recipes, docs, etc. are embedded and support semantic search. The agent queries on demand via MCP tool `autosnippet_search(mode=context)` without preloading all content.
40
-
41
- **Safety and role statement**:
42
- - Context storage and vector store are **safe** external storage; they only hold project knowledge (Recipes, docs, etc.), with no user privacy or sensitive data exposure risk.
43
- - **Skills express semantics** (when to query, what to query, how to use); **MCP provides capability** (connection, retrieval, response).
44
- - **Cursor can use Context storage and vector store as external context**: call `autosnippet_search(mode=context)` on demand to fetch relevant chunks instead of loading all knowledge into the conversation, thus **saving context space** (tokens/context window).
45
-
46
- | Item | Description |
47
- |------|-------------|
48
- | **Storage path** | `AutoSnippet/.autosnippet/context/` |
49
- | **Build command** | Run `asd embed` from project root |
50
- | **Index sources** | `recipe` (AutoSnippet/recipes/*.md), `doc` (docs dir), `target-readme` (module target READMEs) |
51
- | **Storage adapter** | Default `json` |
52
- | **Usage** | With `asd ui` running, MCP tool `autosnippet_search(mode=context)` takes `query`, `limit?` for semantic search |
53
- | **Use cases** | On-demand lookup of relevant Recipe/docs; Guard review against knowledge base; Dashboard semantic search |
54
-
55
- **Prerequisites**: `asd embed` run, `asd ui` started, MCP configured.
56
-
57
- **Usage guidance for Cursor**: Assume `asd ui` is kept running when calling MCP tools (`autosnippet_search`, etc.). If a call fails (e.g. connection refused, API error), do **not** retry within the current agent cycle; fall back to static index (`references/project-recipes-context.md` 轻量索引) or in-context lookup instead.
58
-
59
- **Envelope reading guidance**:
60
- - Parse Envelope fields:
61
- - `success === true` → use `data` and respect `meta.source`.
62
- - `success === false` → check `errorCode` and `message`; propose safe fallback.
63
- - Preferred fallbacks:
64
- - Use local static context and previously loaded Recipe docs.
65
- - Narrow query (reduce `limit`, add keywords), or switch intent (e.g., from semantic search to direct Recipe lookup).
66
- - If operation requires UI (open/create/submit) and fails, inform the user and provide minimal manual steps.
67
-
68
- **Self-check & safety**:
69
- - Use `autosnippet_health` to verify UI and service availability before heavy operations.
70
- - Authentication and HTTP wiring live in MCP, not in Skills. Do not hardcode URLs/HTTP in Skills.
71
-
72
- ---
73
-
74
- ## MCP Tool Map (Concept-level)
75
-
76
- This is a conceptual map. Skills stay semantic; MCP provides capability.
77
-
78
- | Intent | Primary tool(s) |
79
- |---|---|
80
- | 统合搜索 | `autosnippet_search`(mode=auto 融合 BM25+语义) |
81
- | 语义检索 | `autosnippet_search(mode=context)` |
82
- | 精确检索 | `autosnippet_search(mode=keyword)` |
83
- | 向量搜索 | `autosnippet_search(mode=semantic)` |
84
- | 知识浏览 | `autosnippet_knowledge(operation=list/get/insights)` |
85
- | 结构发现 | `autosnippet_structure(operation=targets/files/metadata)` |
86
- | 知识图谱 | `autosnippet_graph(operation=query/impact/path/stats)` |
87
- | 候选提交 | `autosnippet_submit_knowledge`, `autosnippet_submit_knowledge_batch` |
88
- | Guard 检查 | `autosnippet_guard`(code 单条 / files[] 批量 — 自动路由) |
89
- | 使用确认 | `autosnippet_knowledge(operation=confirm_usage)` |
90
- | 项目扫描 | `autosnippet_bootstrap`(无参数,返回 Mission Briefing) |
91
- | 冷启动 | `autosnippet_bootstrap` + `autosnippet_dimension_complete` |
92
- | Skills 管理 | `autosnippet_skill(operation=list/load/create/update/delete/suggest)` |
93
- | 自检 | `autosnippet_health` |
94
-
95
- ### Failure Handling (Examples)
96
- - 检索失败(`SEARCH_FAILED`):改用静态 Recipe 目录或缩小关键词后再试(下一轮)。
97
- - 目标文件获取失败(`GET_TARGET_FILES_FAILED`):提示检查 `asd ui` 与 `targetName`,改为从本地源路径列举(下一轮)。
98
- - 候选提交失败(`SUBMIT_FAILED`):检查必填字段是否齐全;缩小批次后重试(下一轮)。
99
- - Guard 检查失败(`GUARD_ERROR`):提示检查 `asd ui` 运行状态;降级到静态 Recipe 比对。
100
-
101
- ---
102
-
103
- ## Recipe (配方)
104
-
105
- - **Definition**: One Recipe = one `.md` file in `AutoSnippet/recipes/` (or the path in root spec `recipes.dir`). **Each Recipe represents a SINGLE independent usage pattern or code snippet**.
106
- - **Content**: YAML frontmatter (id, title, trigger, summary, language, category, …) + body with **Snippet / Code Reference** (fenced code block) and **AI Context / Usage Guide**.
107
- - **Granularity**:
108
- - ✅ **One Recipe = One specific usage scenario**: e.g. "Load URL in WebView", "Make network request with retry", "Handle async error".
109
- - ❌ **NOT a comprehensive tutorial**: Don't put multiple patterns (e.g. "async/await basics + Promise.all + error handling") into one Recipe.
110
- - ✅ **Documentation-only is OK**: Recipe can be pure doc/guide without code snippet, for concepts or best practices.
111
- - ✅ **Code = single focused example**: If Recipe includes code, it should be ONE focused, reusable code snippet for ONE specific use case.
112
- - **Role**: The unit of "project standard" for a given pattern or module; used for Guard, search, AI Assistant, and (optionally) linked Snippet.
113
- - **Lookup**: Use the **autosnippet-recipes** skill to read or search Recipe content.
114
-
115
- ### Recipe 结构(新版)
116
-
117
- **完整 Recipe Markdown 必须包含:**
118
- 1. **Frontmatter**(`---` 包裹的 YAML,`title`、`trigger` 必填)
119
- 2. **Snippet / Code Reference** 标题 + 代码块
120
- 3. **AI Context / Usage Guide** 标题 + 使用说明
121
-
122
- **CRITICAL RULES for Frontmatter fields:**
123
- - **`category`**: MUST be ONE of these 8 values: `View`, `Service`, `Tool`, `Model`, `Network`, `Storage`, `UI`, `Utility`. NEVER use module names (e.g. "BDNetworkControl") or custom categories.
124
- - **`headers`**: MUST be complete import/include statements from the code. Examples by language:
125
- - Swift: `["import Foundation"]`
126
- - ObjC: `["#import <Module/Header.h>"]`
127
- - Go: `["import \"fmt\""]`
128
- - Python: `["import os"]` / `["from pathlib import Path"]`
129
- - Java: `["import java.util.List;"]`
130
- - Kotlin: `["import kotlinx.coroutines.*"]`
131
- - JS/TS: `["import fs from 'node:fs'"]`
132
- - Dart: `["import 'package:flutter/material.dart'"]`
133
- - Rust: `["use std::collections::HashMap;"]`
134
- - **`trigger`**: MUST start with `@` (e.g. `@request-manager`). kebab-case, no spaces.
135
- - **`language`**: MUST be one of the supported languages (lowercase): `swift`, `objectivec`, `go`, `python`, `java`, `kotlin`, `javascript`, `typescript`, `dart`, `rust`.
136
- - **`kind`**: MUST be one of: `rule`, `pattern`, `fact`.
137
- - **`doClause`**: English imperative sentence, ≤60 tokens.
138
- - **`description`**: 中文摘要 ≤80字。
139
- - **`content`**: 对象 `{ markdown (≥200字), pattern (核心代码), rationale (设计原理) }`。
140
- - **`usageGuide`**: Markdown `###` 章节格式的使用指南。
141
- - **`knowledgeType`**: 如 `code-pattern` / `architecture` / `best-practice` / `code-standard` 等。
142
- - **`reasoning`**: `{ whyStandard, sources[], confidence }`。
143
-
144
- **Standard Category Definitions (8 categories - MUST use exactly these):**
145
-
146
- | Category | When to Use | Examples |
147
- |----------|-------------|----------|
148
- | `View` | UI components, view controllers, custom views | React Component, SwiftUI View, UIViewController, Android Activity |
149
- | `Service` | Business logic services, managers, coordinators | UserService, LocationManager, PaymentCoordinator |
150
- | `Tool` | Utility classes, helpers, extensions | StringHelper, DateFormatter, validation utils |
151
- | `Model` | Data models, entities, value objects | User model, APIResponse, configuration objects |
152
- | `Network` | Network requests, API clients, HTTP/WebSocket | fetch/axios wrapper, URLSession, OkHttp, net/http |
153
- | `Storage` | Persistence, caching, database operations | SQLite, Redis, UserDefaults, file I/O, cache manager |
154
- | `UI` | UI-related utilities not specific to one view | Theme manager, color palette, UI constants |
155
- | `Utility` | General utilities that don't fit other categories | Logger, error handler, general helpers |
156
-
157
- **How to choose category:**
158
- 1. If it's about network/API → `Network`
159
- 2. If it's about data persistence → `Storage`
160
- 3. If it's a business logic manager → `Service`
161
- 4. If it's a UI component → `View`
162
- 5. If it's data structure → `Model`
163
- 6. If it's UI-related utilities → `UI`
164
- 7. If it's code utilities/helpers → `Tool`
165
- 8. If none above fit → `Utility`
166
-
167
- **Frontmatter 字段(三维说明:含义 / 来源 / 规则)**:
168
-
169
- | 字段 | 含义 | 来源 | 规则 |
170
- | :--- | :--- | :--- | :--- |
171
- | `title` | 标准用法的名称 | 人工命名 | **必填**;**中文**;简短精准(✅ "颜色工具方法"、"异步请求处理";❌ 避免 "Use xxx");≤20 字 |
172
- | `trigger` | 触发词(Snippet/检索) | 人工命名 | **必填**;`@` 开头,kebab-case、无空格;唯一 |
173
- | `category` | 8 类标准分类 | 人工判断 | **必填**;必须为 8 类之一 |
174
- | `language` | 代码语言 | 从代码确定 | **必填**;支持 `swift` / `objectivec` / `go` / `python` / `java` / `kotlin` / `javascript` / `typescript` / `dart` / `rust` |
175
- | `kind` | 知识类型 | 人工/AI | **必填**;`rule` / `pattern` / `fact` |
176
- | `doClause` | 英文祈使句指令 | AI/人工 | **必填**;≤60 tokens |
177
- | `description` | 中文功能摘要 | 人工/AI | **必填**;≤80字 |
178
- | `content` | 内容对象 | 从代码/AI | **必填**;`{ markdown (≥200字), pattern (核心代码), rationale (设计原理) }` |
179
- | `headers` | 完整 import/include 语句 | 从代码提取 | **必填**;数组;无 import 传 `[]` |
180
- | `usageGuide` | 使用指南 | AI/人工 | **必填**;Markdown `###` 章节格式 |
181
- | `knowledgeType` | 知识维度 | AI/人工 | **必填**;如 `code-pattern` / `architecture` / `best-practice` / `code-standard` 等 |
182
- | `reasoning` | 推理依据 | Agent 必填 | **必填**;`{ whyStandard, sources[], confidence }` |
183
- | `keywords` | 语义标签 | AI/人工 | 可选;数组;用于检索 |
184
- | `tags` | 额外标签 | 人工 | 可选;数组 |
185
- | `difficulty` | 难度等级 | 系统评估 | 可选;`beginner/intermediate/advanced` |
186
- | `scope` | 适用范围 | AI/人工 | 可选;`universal/project-specific/target-specific` |
187
-
188
- **系统字段(自动生成,无需手填)**:`created`、`lastModified`、`contentHash`。
189
-
190
- **批量解析规则**:
191
- - 多段 Recipe 可在同一文本中,使用「空行 + `---` + 下一段 Frontmatter」分隔。
192
- - 当内容已是完整 Recipe MD(含 Frontmatter + Snippet + Usage Guide)时,系统直接解析入库,无需 AI 重写。
193
-
194
- **Complete Recipe Template (V3 — ALWAYS use this structure):**
195
-
196
- ```json
197
- {
198
- "title": "带重试的 HTTP GET 请求",
199
- "trigger": "@request-retry",
200
- "category": "Network",
201
- "language": "javascript",
202
- "kind": "pattern",
203
- "doClause": "Use fetchWithRetry for HTTP GET requests with automatic retry and exponential backoff",
204
- "description": "封装带自动重试和指数退避的 HTTP GET 请求,适用于不稳定网络环境下的数据获取场景",
205
- "headers": ["import fetch from 'node-fetch'"],
206
- "content": {
207
- "markdown": "## 带重试的 HTTP GET 请求\n\n在网络不稳定的场景中,单次 HTTP 请求可能因超时或服务端故障而失败。本模式封装了自动重试逻辑与指数退避策略,确保请求在合理次数内成功返回。\n\n### 核心实现\n\n```javascript\nimport fetch from 'node-fetch';\n\nasync function fetchWithRetry(url, options = {}, maxRetries = 3) {\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, options);\n if (!response.ok) throw new Error(`HTTP ${response.status}`);\n return await response.json();\n } catch (error) {\n if (attempt === maxRetries) throw error;\n await new Promise(r => setTimeout(r, 1000 * attempt));\n }\n }\n}\n\n// Usage\nconst data = await fetchWithRetry('https://api.example.com/endpoint');\nconsole.log('Success:', data);\n```\n\n### 设计要点\n- 指数退避:每次重试等待时间递增(1s, 2s, 3s),避免服务端过载\n- 最大重试次数可配置,默认 3 次\n- 非 2xx 状态码也视为失败并触发重试",
208
- "pattern": "async function fetchWithRetry(url, options = {}, maxRetries = 3) {\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, options);\n if (!response.ok) throw new Error(`HTTP ${response.status}`);\n return await response.json();\n } catch (error) {\n if (attempt === maxRetries) throw error;\n await new Promise(r => setTimeout(r, 1000 * attempt));\n }\n }\n}",
209
- "rationale": "指数退避策略是处理网络不稳定的行业标准做法,既保证了请求的可靠性,又通过递增等待避免了对服务端的冲击。封装为独立函数便于全项目统一使用。"
210
- },
211
- "usageGuide": "### When to Use\n- 需要对不稳定 API 进行可靠调用时\n- 网络环境可能出现间歇性故障的场景\n\n### Key Points\n- maxRetries 默认 3,可根据场景调整\n- 退避时间为线性递增(1s × attempt),可改为指数递增\n- 非 2xx 响应也会触发重试\n\n### Parameters & Customization\n- `url`: 请求地址\n- `options`: fetch 选项(method, headers, body 等)\n- `maxRetries`: 最大重试次数\n\n### Error Handling\n- 超过最大重试次数后抛出最后一次错误\n- 建议在调用处用 try/catch 捕获\n\n### Related Patterns\n- @http-client-base 基础 HTTP 客户端\n- @circuit-breaker 熔断器模式",
212
- "knowledgeType": "code-pattern",
213
- "reasoning": {
214
- "whyStandard": "指数退避 + 自动重试是 HTTP 客户端的行业最佳实践,被 AWS SDK、Google Cloud 等广泛采用",
215
- "sources": ["node-fetch documentation", "MDN Fetch API", "AWS SDK retry strategy"],
216
- "confidence": 0.9
217
- },
218
- "keywords": ["network", "retry", "http", "fetch", "exponential-backoff"],
219
- "tags": ["network", "resilience"]
220
- }
221
- ```
222
-
223
- **Template Usage Rules:**
224
- 1. **NEVER skip required fields** — 所有 V3 必填字段必须齐全
225
- 2. **V3 必填字段清单(缺一不可)**:
226
- - `title` — 中文 ≤20字
227
- - `trigger` — `@` 开头 kebab-case
228
- - `category` — 8 类之一: View/Service/Tool/Model/Network/Storage/UI/Utility
229
- - `language` — 编程语言标识
230
- - `kind` — rule / pattern / fact
231
- - `doClause` — 英文祈使句 ≤60 tokens
232
- - `dontClause` — 英文反向约束(描述禁止的做法)
233
- - `whenClause` — 英文触发场景(描述何时适用)
234
- - `coreCode` — 3-8 行纯代码骨架(语法完整、可直接复制)
235
- - `description` — 中文摘要 ≤80字
236
- - `content` — `{ markdown (≥200字), pattern (核心代码), rationale (设计原理) }`
237
- - `headers` — import 语句数组(无 import 传 `[]`)
238
- - `usageGuide` — Markdown `###` 章节格式
239
- - `knowledgeType` — 如 `code-pattern` / `architecture` / `best-practice` 等
240
- - `reasoning` — `{ whyStandard, sources[], confidence }`
241
- 3. **DO NOT include `type: full`** — this field is deprecated and should be removed
242
- 4. **Headers MUST be complete import statements** — e.g. `import X`, `#import <X>`, `from X import Y`, `import "fmt"` — not just filenames
243
- 5. **content.markdown** — 需包含完整代码示例 + 说明文字,≥200 字
244
- 6. **content.pattern** — 核心骨架代码,不含注释和使用示例
245
- 7. **content.rationale** — 为什么这样写的设计原理
246
- 8. **usageGuide** — 解释 When/How/Why、依赖、错误处理、性能、安全、陷阱和相关模式
247
- 9. **Use placeholders** — use IDE-appropriate placeholders: Xcode uses `<#placeholder#>`, VSCode uses `${1:placeholder}`. In Recipe source, prefer Xcode format (auto-converted on install). Explain placeholders in Usage Guide.
248
- 10. **Make trigger unique**: Format `@feature-name`, kebab-case, no spaces
249
-
250
- ---
251
-
252
- ## Common Mistakes & How to Fix Them
253
-
254
- - **类别误用**:category 只能是 8 类之一,不能写模块名
255
- - **headers 不完整**:必须是完整 import/#import 语句数组,不能是文件名
256
- - **缺失必填**:`title`/`trigger`/`category`/`language`/`kind`/`doClause`/`dontClause`/`whenClause`/`coreCode`/`description`/`headers`/`content`(markdown+rationale)/`usageGuide`/`knowledgeType`/`reasoning` 必须齐全
257
- - **trigger 格式错误**:必须 `@` 开头,小写、无空格
258
- - **字段滥用**:不要使用已弃用的 `type` 字段
259
- - **合并多模式**:一个 Recipe 只描述一个具体场景
260
-
261
- ### ✅ Quick Checklist Before Submitting
262
-
263
- - [ ] Has all required V3 fields filled
264
- - [ ] **title**: 中文简短标题(≤20字)
265
- - [ ] **content**: `{ markdown (≥200字), pattern (核心代码), rationale (设计原理) }`
266
- - [ ] **trigger**: `@` 开头 kebab-case
267
- - [ ] **kind**: `rule` / `pattern` / `fact`
268
- - [ ] **doClause**: 英文祈使句(≠60 tokens)
269
- - [ ] **dontClause**: 英文反向约束(描述禁止的做法)
270
- - [ ] **whenClause**: 英文触发场景(描述何时适用)
271
- - [ ] **coreCode**: 3-8 行纯代码骨架(语法完整、可直接复制)
272
- - [ ] **description**: 中文摘要 ≤80字
273
- - [ ] **category**: ONE of View/Service/Tool/Model/Network/Storage/UI/Utility
274
- - [ ] **language**: `swift`/`objectivec`/`go`/`python`/`java`/`kotlin`/`javascript`/`typescript`/`dart`/`rust`
275
- - [ ] **headers**: 完整 import 语句数组(无 import 传 `[]`)
276
- - [ ] **usageGuide**: Markdown `###` 章节格式
277
- - [ ] **knowledgeType**: `code-pattern` / `architecture` / `best-practice` 等
278
- - [ ] **reasoning**: `{ whyStandard, sources[], confidence }`
279
- - [ ] Code snippet is runnable with minimal edits
280
- - [ ] No `type:` field (this is deprecated)
281
- - [ ] No `code` / `summary_cn` / `summary_en` (use V3 `content` + `description` instead)
282
-
283
- ### Recipe Creation Principles
284
-
285
- When creating or extracting Recipes:
286
- 1. **V3 必填字段一次性填写**:title, content(markdown+pattern+rationale), trigger, kind, doClause, dontClause, whenClause, coreCode, description, category, language, headers, usageGuide, knowledgeType, reasoning
287
- 2. **保持单场景**:一个 Recipe 只讲一个具体用法
288
- 3. **字段严格**:必填字段必须齐全、格式正确
289
- - Tools like Dashboard `/api/v1/ai/translate` can help auto-generate missing language, but it's better to provide both
290
- 2. **Split, don't combine**: If you identify 3 usage patterns in a module, create 3 separate Recipes, not 1 combined Recipe.
291
- 3. **Each Recipe has a clear trigger**: One `@trigger` for one specific scenario. E.g. `@WebViewLoadURL`, `@NetworkRetry`, `@AsyncError`.
292
- 4. **Reusable and focused**: Developer should be able to copy-paste the Recipe's code snippet and use it directly for that ONE scenario.
293
- 5. **Summary should be specific**: "Use async/await for sequential API calls" NOT "Async programming guide".
294
- 6. **Category MUST use standard values**: ONLY use one of these 8 categories: `View`, `Service`, `Tool`, `Model`, `Network`, `Storage`, `UI`, `Utility`. Never use module names (e.g. "BDNetworkControl") or other custom values as category.
295
- 7. **Headers must be complete import statements**: Extract all import/include statements from code. Format by language:
296
- - Swift: `["import ModuleName"]`
297
- - ObjC: `["#import <Module/Header.h>"]`
298
- - Go: `["import \"fmt\""]`
299
- - Python: `["import os"]` / `["from pathlib import Path"]`
300
- - Java/Kotlin: `["import java.util.List;"]`
301
- - JS/TS: `["import fs from 'node:fs'"]`
302
- Include the full statement, not just module names.
303
- 8. **Auto-extract moduleName**: Parse from headers. Examples:
304
- - ObjC: `["#import <BDNetworkControl/BDBaseRequest.h>"]` → `moduleName: BDNetworkControl`
305
- - Swift: `["import Foundation"]` → `moduleName: Foundation`
306
- - Go: `["import \"net/http\""]` → `moduleName: net/http`
307
- - Python: `["from flask import Flask"]` → `moduleName: flask`
308
- - Java: `["import com.google.gson.Gson;"]` → `moduleName: com.google.gson`
309
- - JS/TS: `["import express from 'express'"]` → `moduleName: express`
310
- If multiple modules exist, use the primary/main one.
311
- 9. **Auto-generate tags**: Analyze code to extract 2-4 keyword tags:
312
- - **Functionality**: network, storage, ui, animation, async, cache, threading
313
- - **Patterns**: template, singleton, factory, observer, delegate
314
- - **Domain**: api, database, navigation, gesture, notification
315
- - Example: Network request code → `tags: [network, api, async]`
316
- 10. **Auto-judge difficulty**: Analyze code complexity:
317
- - **beginner**: Simple property setup, basic UI layout, straightforward method calls
318
- - **intermediate**: Moderate logic, callbacks/blocks, error handling, common patterns (default)
319
- - **advanced**: Complex architecture, async coordination, custom protocols, performance optimization
320
- 10. **Set authority: 3** by default (reviewers adjust 1-5 in Dashboard)
321
-
322
- ### Candidate-only Rule (重要)
323
-
324
- - **If the user asks for candidates**: Extract structured items and submit via MCP **`autosnippet_submit_knowledge_batch`**.
325
-
326
- ---
327
-
328
- ## 其他升级后的结构(2026)
329
-
330
- | 结构 | 位置 | 说明 |
331
- |------|------|------|
332
- | **Recipe 使用统计** | `AutoSnippet/.autosnippet/recipe-stats.json` | 记录 byTrigger/byFile 的使用次数与权威分(0~5)。用于排序与推荐。 |
333
- | **统计权重配置** | `AutoSnippet/.autosnippet/recipe-stats-weights.json` 或 boxspec `recipes.statsWeights` | 使用热度与权威分的权重配置。 |
334
- | **Candidates** | `AutoSnippet/.autosnippet/candidates.json` | 批量扫描/候选池,由 Dashboard 审核入库。 |
335
- | **向量索引** | `AutoSnippet/.autosnippet/context/` | `asd embed` 生成的语义索引,供检索与 Guard。 |
336
-
337
- ### Recipe Priority Over Project Implementation
338
-
339
- When both Recipe and project source code have relevant implementations, **prefer Recipe**. Recipe is the curated project standard; source code may be legacy, incomplete, or non-standard. When answering, suggesting code, or running Guard, cite Recipe's Snippet/Code Reference instead of raw search results.
340
-
341
- ---
342
-
343
- ## Multi-Language Recipe Examples (V3)
344
-
345
- > 以下展示不同语言的标准 V3 Recipe 示例,展示所有必填字段在各语言下的写法。
346
-
347
- ### Example 1: Swift — 网络请求(iOS/macOS)
348
-
349
- ```json
350
- {
351
- "title": "URLSession 异步 GET 请求",
352
- "trigger": "@url-session-get",
353
- "category": "Network",
354
- "language": "swift",
355
- "kind": "pattern",
356
- "doClause": "Use async/await URLSession for GET requests with error handling and JSON decoding",
357
- "description": "使用 async/await 的 URLSession GET 请求,包含错误处理与 JSON 解码,适用于 iOS/macOS 网络层",
358
- "headers": ["import Foundation"],
359
- "content": {
360
- "markdown": "## URLSession 异步 GET 请求\n\n使用 Swift concurrency 的 async/await 语法封装 URLSession GET 请求,自动校验 HTTP 状态码并解码 JSON。\n\n```swift\nfunc fetchData<T: Decodable>(from url: URL) async throws -> T {\n let (data, response) = try await URLSession.shared.data(from: url)\n guard let http = response as? HTTPURLResponse,\n (200..<300).contains(http.statusCode) else {\n throw URLError(.badServerResponse)\n }\n return try JSONDecoder().decode(T.self, from: data)\n}\n\n// Usage\nlet users: [User] = try await fetchData(from: URL(string: \"https://api.example.com/users\")!)\n```\n\n### 设计要点\n- 泛型 Decodable 约束,支持任意 JSON 模型\n- 校验 HTTP 2xx 范围状态码\n- 利用 Swift Concurrency 自动管理线程",
361
- "pattern": "func fetchData<T: Decodable>(from url: URL) async throws -> T {\n let (data, response) = try await URLSession.shared.data(from: url)\n guard let http = response as? HTTPURLResponse,\n (200..<300).contains(http.statusCode) else {\n throw URLError(.badServerResponse)\n }\n return try JSONDecoder().decode(T.self, from: data)\n}",
362
- "rationale": "async/await 是 Swift 5.5+ 推荐的异步模式,相比 completion handler 更清晰且不易出错,泛型解码减少重复代码。"
363
- },
364
- "usageGuide": "### When to Use\n- iOS/macOS 项目中需要从 REST API 获取 JSON 数据\n- 使用 Swift 5.5+ 的项目\n\n### Key Points\n- 必须在 async 上下文中调用\n- 返回类型需遵循 Decodable 协议\n\n### Error Handling\n- 非 2xx 抛出 URLError(.badServerResponse)\n- JSON 解码失败抛出 DecodingError",
365
- "knowledgeType": "code-pattern",
366
- "reasoning": {
367
- "whyStandard": "Apple 官方推荐 async/await URLSession API,是 Swift Concurrency 标准做法",
368
- "sources": ["Apple URLSession documentation", "Swift Concurrency WWDC21"],
369
- "confidence": 0.95
370
- },
371
- "keywords": ["network", "async", "urlsession", "json"],
372
- "tags": ["network", "template"]
373
- }
374
- ```
375
-
376
- ### Example 2: Objective-C — KVO 安全模式
377
-
378
- ```json
379
- {
380
- "title": "NSObject KVO 安全订阅",
381
- "trigger": "@kvo-safe",
382
- "category": "Utility",
383
- "language": "objectivec",
384
- "kind": "rule",
385
- "doClause": "Pair addObserver and removeObserver to prevent KVO leaks and crashes",
386
- "description": "配对 addObserver/removeObserver,避免 KVO 泄漏与崩溃,确保生命周期安全",
387
- "headers": ["#import <Foundation/Foundation.h>"],
388
- "content": {
389
- "markdown": "## NSObject KVO 安全订阅\n\nKVO 是 Cocoa 的核心机制,但未正确移除观察者会导致崩溃。本规则要求 addObserver 与 removeObserver 必须配对。\n\n```objectivec\n// Add observer\n[self.target addObserver:self\n forKeyPath:@\"<#property#>\"\n options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld\n context:NULL];\n\n// Handle changes\n- (void)observeValueForKeyPath:(NSString *)keyPath\n ofObject:(id)object\n change:(NSDictionary *)change\n context:(void *)context {\n if ([keyPath isEqualToString:@\"<#property#>\"]) {\n id newValue = change[NSKeyValueChangeNewKey];\n // Handle change\n }\n}\n\n// MUST remove in dealloc\n- (void)dealloc {\n [self.target removeObserver:self forKeyPath:@\"<#property#>\"];\n}\n```\n\n### 设计要点\n- addObserver 与 removeObserver 必须一一配对\n- dealloc 中移除是最后的安全网\n- 使用 context 区分不同观察",
390
- "pattern": "[self.target addObserver:self forKeyPath:@\"<#property#>\" options:NSKeyValueObservingOptionNew context:NULL];\n- (void)dealloc { [self.target removeObserver:self forKeyPath:@\"<#property#>\"]; }",
391
- "rationale": "KVO 观察者未移除会在对象释放后导致野指针崩溃,配对管理是 Cocoa 开发的基本安全规则。"
392
- },
393
- "usageGuide": "### When to Use\n- 使用 KVO 监听属性变化时\n- 任何 addObserver 调用都必须有对应的 removeObserver\n\n### Common Pitfalls\n- 忘记在 dealloc 中移除观察者\n- 重复添加同一 keyPath 的观察者\n- 多线程环境下的竞态条件",
394
- "knowledgeType": "code-standard",
395
- "reasoning": {
396
- "whyStandard": "Apple 官方文档明确要求 KVO 观察者必须在释放前移除,否则会触发异常",
397
- "sources": ["Apple KVO Programming Guide", "NSObject Protocol Reference"],
398
- "confidence": 0.95
399
- },
400
- "keywords": ["kvo", "safety", "lifecycle"],
401
- "tags": ["safety"]
402
- }
403
- ```
404
-
405
- ### Example 3: Go — HTTP Handler with Middleware
406
-
407
- ```json
408
- {
409
- "title": "Go HTTP Handler 中间件链",
410
- "trigger": "@go-handler",
411
- "category": "Network",
412
- "language": "go",
413
- "kind": "pattern",
414
- "doClause": "Use middleware chain pattern for net/http handlers with logging and recovery",
415
- "description": "标准 net/http Handler + 中间件链模式,含日志和 panic 恢复中间件",
416
- "headers": ["import \"net/http\"", "import \"log\""],
417
- "content": {
418
- "markdown": "## Go HTTP Handler 中间件链\n\n使用函数式中间件链组合 HTTP 处理器,每个中间件负责单一职责(日志、恢复等),通过 Chain 函数串联。\n\n```go\ntype Middleware func(http.Handler) http.Handler\n\nfunc LoggingMiddleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Printf(\"%s %s\", r.Method, r.URL.Path)\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\nfunc RecoveryMiddleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\thttp.Error(w, \"Internal Server Error\", 500)\n\t\t\t\tlog.Printf(\"panic recovered: %v\", err)\n\t\t\t}\n\t\t}()\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\nfunc Chain(h http.Handler, mws ...Middleware) http.Handler {\n\tfor i := len(mws) - 1; i >= 0; i-- {\n\t\tmw := mws[i]\n\t\th = mw(h)\n\t}\n\treturn h\n}\n```\n\n### 设计要点\n- Middleware 类型签名统一:`func(http.Handler) http.Handler`\n- Chain 从右向左包装,保证执行顺序与传入顺序一致\n- RecoveryMiddleware 防止 panic 导致进程崩溃",
419
- "pattern": "type Middleware func(http.Handler) http.Handler\n\nfunc Chain(h http.Handler, mws ...Middleware) http.Handler {\n\tfor i := len(mws) - 1; i >= 0; i-- {\n\t\tmw := mws[i]\n\t\th = mw(h)\n\t}\n\treturn h\n}",
420
- "rationale": "中间件链是 Go HTTP 服务的标准架构模式,被 chi、gorilla/mux 等主流框架广泛采用,通过函数组合实现关注点分离。"
421
- },
422
- "usageGuide": "### When to Use\n- 构建 Go HTTP 服务时需要统一的请求处理流水线\n- 需要日志、认证、恢复等通用功能\n\n### Key Points\n- 中间件顺序很重要:Recovery 应在最外层\n- 可自由扩展: Auth、CORS、RateLimit 等\n\n### Related Patterns\n- @go-graceful-shutdown 优雅关闭\n- @go-context-propagation 上下文传递",
423
- "knowledgeType": "code-pattern",
424
- "reasoning": {
425
- "whyStandard": "函数式中间件链是 Go 社区的标准 HTTP 服务架构,与 net/http 原生接口完全兼容",
426
- "sources": ["Go net/http documentation", "chi router middleware pattern"],
427
- "confidence": 0.9
428
- },
429
- "keywords": ["http", "handler", "middleware", "server"],
430
- "tags": ["network", "pattern"]
431
- }
432
- ```
433
-
434
- ### Example 4: Python — 异步数据库查询
435
-
436
- ```json
437
- {
438
- "title": "异步 PostgreSQL 连接池查询",
439
- "trigger": "@async-db",
440
- "category": "Storage",
441
- "language": "python",
442
- "kind": "pattern",
443
- "doClause": "Use asyncpg connection pool for async PostgreSQL queries with proper error handling",
444
- "description": "使用 asyncpg 连接池执行异步 PostgreSQL 查询,含连接管理与错误处理",
445
- "headers": ["import asyncpg", "import asyncio"],
446
- "content": {
447
- "markdown": "## 异步 PostgreSQL 连接池查询\n\nasyncpg 连接池管理数据库连接的生命周期,避免频繁创建/销毁连接的开销。\n\n```python\nimport asyncpg\nimport asyncio\n\nasync def create_pool(dsn: str) -> asyncpg.Pool:\n return await asyncpg.create_pool(dsn, min_size=5, max_size=20)\n\nasync def fetch_users(pool: asyncpg.Pool, limit: int = 100) -> list[dict]:\n async with pool.acquire() as conn:\n rows = await conn.fetch(\n \"SELECT id, name, email FROM users WHERE active = $1 LIMIT $2\",\n True, limit\n )\n return [dict(row) for row in rows]\n\n# Usage\npool = await create_pool(\"postgresql://user:pass@localhost/mydb\")\ntry:\n users = await fetch_users(pool)\nfinally:\n await pool.close()\n```\n\n### 设计要点\n- 连接池 min_size/max_size 控制资源消耗\n- async with pool.acquire() 自动归还连接\n- 参数化查询防止 SQL 注入",
448
- "pattern": "async def create_pool(dsn: str) -> asyncpg.Pool:\n return await asyncpg.create_pool(dsn, min_size=5, max_size=20)\n\nasync def fetch_users(pool: asyncpg.Pool, limit: int = 100) -> list[dict]:\n async with pool.acquire() as conn:\n rows = await conn.fetch(query, *params)\n return [dict(row) for row in rows]",
449
- "rationale": "连接池是数据库访问的标准做法,asyncpg 是 Python 社区性能最优的 PostgreSQL 异步驱动,参数化查询确保安全。"
450
- },
451
- "usageGuide": "### When to Use\n- Python 异步应用中访问 PostgreSQL\n- 需要高并发数据库访问的场景\n\n### Key Points\n- 必须在 asyncio 事件循环中使用\n- 应用退出前调用 pool.close()\n- 使用参数化查询($1, $2)而非字符串拼接\n\n### Dependencies\n- asyncpg >= 0.27.0\n- PostgreSQL 9.5+",
452
- "knowledgeType": "code-pattern",
453
- "reasoning": {
454
- "whyStandard": "asyncpg 连接池是 Python 异步 PostgreSQL 访问的行业标准,被 FastAPI、Starlette 等框架推荐",
455
- "sources": ["asyncpg documentation", "PostgreSQL connection pooling best practices"],
456
- "confidence": 0.9
457
- },
458
- "keywords": ["database", "async", "postgresql", "pool"],
459
- "tags": ["storage", "async"]
460
- }
461
- ```
462
-
463
- ### Example 5: TypeScript — React 自定义 Hook
464
-
465
- ```json
466
- {
467
- "title": "React 通用 useFetch Hook",
468
- "trigger": "@use-fetch",
469
- "category": "Tool",
470
- "language": "typescript",
471
- "kind": "pattern",
472
- "doClause": "Use generic useFetch hook with loading state, error handling, and auto-cancellation",
473
- "description": "通用 useFetch Hook,支持泛型、loading 状态、错误处理与请求自动取消",
474
- "headers": ["import { useState, useEffect } from 'react'"],
475
- "content": {
476
- "markdown": "## React 通用 useFetch Hook\n\n封装 fetch 请求为自定义 Hook,统一管理 loading/data/error 三态,URL 变化时自动取消上一次请求。\n\n```typescript\nimport { useState, useEffect } from 'react';\n\ninterface FetchState<T> {\n data: T | null;\n loading: boolean;\n error: Error | null;\n}\n\nfunction useFetch<T>(url: string): FetchState<T> {\n const [state, setState] = useState<FetchState<T>>({\n data: null, loading: true, error: null,\n });\n\n useEffect(() => {\n const controller = new AbortController();\n setState(prev => ({ ...prev, loading: true, error: null }));\n\n fetch(url, { signal: controller.signal })\n .then(res => {\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n return res.json();\n })\n .then(data => setState({ data, loading: false, error: null }))\n .catch(err => {\n if (err.name !== 'AbortError') {\n setState({ data: null, loading: false, error: err });\n }\n });\n\n return () => controller.abort();\n }, [url]);\n\n return state;\n}\n```\n\n### 设计要点\n- AbortController 在组件卸载或 URL 变化时取消请求\n- 泛型 T 支持任意返回类型\n- 三态(loading/data/error)覆盖所有 UI 场景",
477
- "pattern": "function useFetch<T>(url: string): FetchState<T> {\n const [state, setState] = useState<FetchState<T>>({ data: null, loading: true, error: null });\n useEffect(() => {\n const controller = new AbortController();\n fetch(url, { signal: controller.signal }).then(res => res.json()).then(data => setState({ data, loading: false, error: null }));\n return () => controller.abort();\n }, [url]);\n return state;\n}",
478
- "rationale": "自定义 Hook 是 React 的标准复用模式,AbortController 防止内存泄漏,泛型确保类型安全。"
479
- },
480
- "usageGuide": "### When to Use\n- React 函数组件中需要 fetch 远程数据\n- 需要统一的 loading/error 状态管理\n\n### Key Points\n- URL 变化会自动重新请求\n- 组件卸载时自动取消进行中的请求\n- 返回 { data, loading, error } 三态\n\n### Common Pitfalls\n- 不要在 Hook 外部修改返回的 state\n- 复杂场景考虑使用 React Query / SWR",
481
- "knowledgeType": "code-pattern",
482
- "reasoning": {
483
- "whyStandard": "自定义 Hook + AbortController 是 React 官方推荐的数据获取模式",
484
- "sources": ["React documentation - Custom Hooks", "MDN AbortController"],
485
- "confidence": 0.9
486
- },
487
- "keywords": ["react", "hook", "fetch", "typescript"],
488
- "tags": ["ui", "pattern"]
489
- }
490
- ```
491
-
492
- ### Example 6: Java — 泛型 Repository 模式
493
-
494
- ```json
495
- {
496
- "title": "泛型 Repository 接口",
497
- "trigger": "@java-repo",
498
- "category": "Service",
499
- "language": "java",
500
- "kind": "pattern",
501
- "doClause": "Use generic Repository interface with Optional returns for type-safe data access",
502
- "description": "Spring Data 风格泛型 Repository 接口,使用 Optional 避免空指针,统一数据访问层",
503
- "headers": ["import java.util.Optional;", "import java.util.List;"],
504
- "content": {
505
- "markdown": "## 泛型 Repository 接口\n\n定义统一的泛型数据访问层接口,使用 Optional 返回值避免 NullPointerException,所有实体 Repository 统一实现此接口。\n\n```java\npublic interface Repository<T, ID> {\n Optional<T> findById(ID id);\n List<T> findAll();\n T save(T entity);\n void deleteById(ID id);\n boolean existsById(ID id);\n}\n\n// Implementation\npublic class UserRepository implements Repository<User, Long> {\n @Override\n public Optional<User> findById(Long id) {\n return Optional.ofNullable(queryResult);\n }\n\n @Override\n public User save(User entity) {\n // persist entity\n return entity;\n }\n // ... other methods\n}\n```\n\n### 设计要点\n- 泛型 <T, ID> 支持任意实体类型\n- Optional 返回避免 null 判断\n- 接口统一,实现可替换(内存/数据库/远程)",
506
- "pattern": "public interface Repository<T, ID> {\n Optional<T> findById(ID id);\n List<T> findAll();\n T save(T entity);\n void deleteById(ID id);\n boolean existsById(ID id);\n}",
507
- "rationale": "Repository 模式是 DDD 的核心模式,Spring Data 将其标准化。泛型接口减少重复代码,Optional 是 Java 8+ 避免 NPE 的标准做法。"
508
- },
509
- "usageGuide": "### When to Use\n- Java 项目需要统一的数据访问层\n- 使用 Spring Data 或自定义 ORM 时\n\n### Key Points\n- 每个实体创建对应的 Repository 实现\n- findById 返回 Optional,调用方用 orElse/orElseThrow 处理\n- save 方法同时处理新增和更新\n\n### Related Patterns\n- @java-service-layer 服务层模式\n- @java-entity-base 基础实体类",
510
- "knowledgeType": "architecture",
511
- "reasoning": {
512
- "whyStandard": "Repository 模式是 Spring Data 的核心抽象,是 Java 企业级开发的行业标准",
513
- "sources": ["Spring Data documentation", "Domain-Driven Design by Eric Evans"],
514
- "confidence": 0.95
515
- },
516
- "keywords": ["repository", "generics", "optional", "pattern"],
517
- "tags": ["architecture", "pattern"]
518
- }
519
- ```
520
-
521
- ### Example 7: Kotlin — 协程 Flow 数据流
522
-
523
- ```json
524
- {
525
- "title": "Kotlin Flow 异步数据流",
526
- "trigger": "@kotlin-flow",
527
- "category": "Service",
528
- "language": "kotlin",
529
- "kind": "pattern",
530
- "doClause": "Use Kotlin Flow with retry and error handling for async data streams",
531
- "description": "使用 Kotlin Flow 处理异步数据流,含 retry 重试和错误恢复机制",
532
- "headers": ["import kotlinx.coroutines.flow.*", "import kotlinx.coroutines.delay"],
533
- "content": {
534
- "markdown": "## Kotlin Flow 异步数据流\n\n使用 Flow 构建响应式数据流,结合 retry 和 catch 操作符实现自动重试与错误恢复。\n\n```kotlin\nfun fetchUsersFlow(): Flow<List<User>> = flow {\n val users = apiClient.getUsers()\n emit(users)\n}.retry(retries = 3) { cause ->\n cause is IOException && run { delay(1000); true }\n}.catch { e ->\n emit(emptyList())\n logger.error(\"Failed to fetch users\", e)\n}.flowOn(Dispatchers.IO)\n\n// Collect in ViewModel\nviewModelScope.launch {\n fetchUsersFlow()\n .collect { users ->\n _uiState.value = UiState.Success(users)\n }\n}\n```\n\n### 设计要点\n- flow builder 在协程中发射数据\n- retry 操作符对 IOException 自动重试 3 次\n- catch 操作符兜底:发射空列表并记录日志\n- flowOn(Dispatchers.IO) 确保网络请求在 IO 线程",
535
- "pattern": "fun fetchUsersFlow(): Flow<List<User>> = flow {\n val data = apiClient.getData()\n emit(data)\n}.retry(retries = 3) { cause ->\n cause is IOException && run { delay(1000); true }\n}.catch { e ->\n emit(emptyList())\n}.flowOn(Dispatchers.IO)",
536
- "rationale": "Kotlin Flow 是 Kotlin 协程的标准响应式流 API,retry + catch 组合是处理不稳定数据源的最佳实践,flowOn 确保线程安全。"
537
- },
538
- "usageGuide": "### When to Use\n- Android/Kotlin 项目中需要响应式数据流\n- ViewModel 向 UI 层提供可观察数据\n\n### Key Points\n- collect 是终端操作符,必须在协程中调用\n- flowOn 只影响上游操作符\n- retry 中的 delay 实现退避策略\n\n### Common Pitfalls\n- 不要在 catch 之后再使用 retry\n- collect 在主线程调用时确保 flowOn 指定了合适的调度器\n\n### Related Patterns\n- @kotlin-stateflow StateFlow 状态管理\n- @kotlin-coroutine-scope 协程作用域",
539
- "knowledgeType": "code-pattern",
540
- "reasoning": {
541
- "whyStandard": "Kotlin Flow 是 JetBrains 官方推荐的异步流 API,Google Android 团队推荐替代 RxJava",
542
- "sources": ["Kotlin Flow documentation", "Android Developer Guide - Kotlin Flow"],
543
- "confidence": 0.9
544
- },
545
- "keywords": ["flow", "coroutine", "async", "stream"],
546
- "tags": ["async", "pattern"]
547
- }
548
- ```
549
-
550
- ### Headers 格式速查表
551
-
552
- | Language | headers 格式示例 |
553
- |----------|-----------------|
554
- | Swift | `["import Foundation"]`, `["import UIKit"]` |
555
- | ObjC | `["#import <Foundation/Foundation.h>"]`, `["#import <UIKit/UIKit.h>"]` |
556
- | Go | `["import \"net/http\""]`, `["import \"fmt\""]` |
557
- | Python | `["import asyncio"]`, `["from pathlib import Path"]` |
558
- | Java | `["import java.util.List;"]`, `["import java.util.Optional;"]` |
559
- | Kotlin | `["import kotlinx.coroutines.flow.*"]` |
560
- | JavaScript | `["import express from 'express'"]`, `["const fs = require('fs')"]` |
561
- | TypeScript | `["import { useState } from 'react'"]`, `["import type { Config } from './types'"]` |
562
-
563
- ### Placeholder 格式速查表
564
-
565
- | 目标 IDE | 格式 | 示例 |
566
- |----------|------|------|
567
- | Xcode | `<#name#>` | `<#URL#>`, `<#Token#>`, `<#completion#>` |
568
- | VSCode | `${N:name}` | `${1:url}`, `${2:token}`, `${3:callback}` |
569
-
570
- > **写法建议**: Recipe 源文件中统一使用 Xcode 格式 `<#...#>`,`asd install` 会自动按目标 IDE 转换。
571
-
572
- ---
573
-
574
- ## Snippet
575
-
576
- - **Definition**: A single code snippet entry (title, trigger, body, headers, etc.) listed in the root spec or under `AutoSnippet/snippets/`.
577
- - **Role**: Synced to IDE (Xcode CodeSnippets / VSCode .code-snippets) via **`asd install`**; developers insert by trigger or from the snippet library.
578
- - **Relation**: A Recipe can describe the same pattern as a Snippet; creating from Dashboard can produce both.
579
-
580
- ---
581
-
582
- ## On-Demand Context (when asd ui is running)
583
-
584
- When `asd ui` is running in the project root, use the HTTP API for on-demand semantic search:
585
- - MCP tool `autosnippet_search(mode=context)` (pass `query`, `limit?`) → returns relevant Recipe/docs
586
- - Used to fetch Recipe/docs relevant to the current task dynamically instead of loading all at once.
587
-
588
- ---
589
-
590
- ## Quick Summary
591
-
592
- | Capability | Description | Skill |
593
- |------------|-------------|-------|
594
- | **Recipe lookup** | Read `references/project-recipes-context.md` 轻量索引,需全文调 MCP `autosnippet_knowledge(operation=get, id)` / `autosnippet_search(mode=context)`. Recipe over source | autosnippet-recipes |
595
- | **Create Recipe** | Dashboard New Recipe; or write to `_draft_recipe.md` and watch auto-adds; or MCP `autosnippet_submit_knowledge_batch` | autosnippet-create |
596
- | **Search & insert** | `ass` shortcut or `// as:search`, `asd search`, Dashboard search | autosnippet-search |
597
- | **Audit review** | `// as:audit`; watch runs AI review against knowledge base | autosnippet-guard |
598
- | **Dependency graph** | `AutoSnippet/AutoSnippet.spmmap.json`; `asd spm-map` to update; MCP graph tools for querying (supports SPM/Node/Go/JVM/Python) | autosnippet-structure |
599
- | **Vector store** | Built by `asd embed`; `autosnippet_search(mode=context)` for on-demand lookup. Use as context storage to save space | autosnippet-concepts / autosnippet-recipes |
600
- | **MCP tools** | `autosnippet_search` (统合搜索), `autosnippet_guard` (Guard 检查) | — |
601
-
602
- **Principles**: Recipe is project standard, over project implementation; do not modify AutoSnippet/ directly, submit via Dashboard or MCP candidate submission. Context storage is safe; Skills express semantics, MCP provides capability; Cursor calls on demand to save space.
603
-
604
- ---
605
-
606
- ## Introducing and using new knowledge
607
-
608
- **New knowledge** means content not yet in the knowledge base, or just submitted as candidates (new Recipe, new doc). How to add and use it:
609
-
610
- ### How to add new knowledge
611
-
612
- 1. **Single code / single Recipe**: Copy to clipboard → open Dashboard (run `asd ui` if not running) → Use Copied Code, paste, review, save; or write `_draft_recipe.md` and let watch auto-add to Candidates. Or use `autosnippet_submit_knowledge_batch` via MCP.
613
- 2. **Multiple drafts (recommended)**: Create a **draft folder** (e.g. `.autosnippet-drafts`), **one .md file per Recipe**—do not put everything in one big file. Call MCP **`autosnippet_submit_knowledge_batch`** with those file paths to submit to Candidates, then review in Dashboard **Candidates**. **After submit, delete the draft folder** (use `deleteAfterSubmit: true` or `rm -rf .autosnippet-drafts`).
614
- 3. **Intro-only docs**: Recipe candidates can be intro-only (frontmatter + usage guide, no code); after approval they become Recipes and **do not generate a Snippet**—used only for search and Guard context.
615
-
616
- ### How to use knowledge once it’s in the base
617
-
618
- - **Search**: MCP `autosnippet_search` (mode=context/keyword/semantic/auto), or terminal `asd search`, Dashboard search, `ass` shortcut or `// as:search`.
619
- - **Audit**: `// as:audit` runs Guard against Recipe standards. Or call `autosnippet_guard` via MCP for on-demand checking (with `code` for single snippet or `files[]` for batch).
620
- - **Record adoption**: When the user confirms use, call `autosnippet_knowledge(operation=confirm_usage)` to record human usage (affects authority and ranking).
621
-
622
- ---
623
-
624
- ## Relation to other skills
625
-
626
- - **autosnippet-recipes**: Read project context, search recipes, find code on demand.
627
- - **autosnippet-create**: Creation flow (Dashboard, CLI, `// as:create`).
628
- - **autosnippet-structure**: SPM dependency structure and knowledge graph.
629
-
630
- ```