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,988 +0,0 @@
1
- ---
2
- name: autosnippet-coldstart
3
- description: Cold-start knowledge base initialization (V3). Full 9-dimension analysis workflow for external Agent. Call autosnippet_bootstrap (no params) → analyze code → submit_knowledge → dimension_complete.
4
- ---
5
-
6
- # AutoSnippet — Cold Start (知识库冷启动) V3
7
-
8
- > 首次接入项目 / 知识库重建 / 大版本升级后使用。目标:从零建立完整知识库,覆盖 9 大知识维度。
9
- > Self-check & Fallback: MCP 工具返回 JSON Envelope({ success, errorCode?, data?, meta })。失败时不在同一轮重试,缩小范围再试。
10
- > **DB 不可用不影响冷启动**: autosnippet_bootstrap 不依赖数据库(纯文件系统分析),可直接调用。
11
-
12
- ## Quick Decision
13
-
14
- | 情况 | 使用 |
15
- |------|------|
16
- | 首次接入 / "初始化知识库" / "冷启动" | **本 Skill**(完整冷启动) |
17
- | 已有知识库,查/用 Recipe | → autosnippet-recipes |
18
- | 只扫描单个文件/模块 | → autosnippet-candidates |
19
- | 只做 Guard 审计 | → autosnippet-guard |
20
- | 快速看看项目结构 | → autosnippet-structure(用 `autosnippet_structure(operation=targets)`) |
21
-
22
- ---
23
-
24
- ## Phase 0: 启动扫描
25
-
26
- 调用 `autosnippet_bootstrap`(**无参数**)获取 Mission Briefing:
27
-
28
- ```
29
- autosnippet_bootstrap()
30
- ```
31
-
32
- > 💡 Bootstrap 不依赖数据库,DB 不可用时也能正常工作。
33
-
34
- ### Mission Briefing 返回数据
35
-
36
- | 字段 | 内容 |
37
- |------|------|
38
- | `projectMeta` | 项目元数据(name, primaryLanguage, fileCount, projectType) |
39
- | `ast` | AST 分析摘要(classes, protocols, functions, imports) |
40
- | `codeEntityGraph` | 代码实体图谱(类/协议/函数之间的关系) |
41
- | `dependencyGraph` | `{ nodes, edges }` 模块间依赖关系 |
42
- | `guardFindings` | Guard 规则违规摘要 |
43
- | `targets` | 所有模块 Target(含 `inferredRole`: core/service/ui/networking/…) |
44
- | `dimensions` | 激活的分析维度任务列表(每个维度含 analysisGuide + evidenceStarters) |
45
- | `submissionSchema` | **提交格式定义 + 语言自适应 JSON 示例**(⚠️ 必须严格按此格式提交) |
46
- | `executionPlan` | 分 Tier 执行计划(Tier 1 → Tier 2 → Tier 3) |
47
- | `session` | Bootstrap 会话信息(session.id 供 dimension_complete 使用) |
48
-
49
- ### submissionSchema — 提交格式(关键!)
50
-
51
- Mission Briefing 的 `submissionSchema.example` 包含**完整的提交 JSON 示例**,按项目主语言自适应。
52
- **你必须严格按照该示例的字段格式提交知识**,特别注意:
53
- - `content` 是 JSON 对象:`{ "pattern": "...", "markdown": "...", "rationale": "..." }`
54
- - `reasoning` 是 JSON 对象:`{ "whyStandard": "...", "sources": [...], "confidence": 0.85 }`
55
- - `headers` 是数组:`["import Foundation"]`(无 import 时传 `[]`)
56
-
57
- ### dimensions — 维度任务
58
-
59
- 每个维度对象包含:
60
- - `id` — 维度标识
61
- - `label` — 维度名称
62
- - `analysisGuide` — 分析步骤指引(SOP)
63
- - `evidenceStarters` — 从 Phase 1-4 数据中提取的证据启发
64
- - `submissionSpec` — 提交规范(含 preSubmitChecklist)
65
-
66
- ### executionPlan — 分 Tier 执行
67
-
68
- ```
69
- Tier 1(项目特征/深度扫描/分类扫描)→ Tier 2(代码规范/架构/设计模式)→ Tier 3(事件流/最佳实践/开发指南)
70
- ```
71
-
72
- 每个维度的工作流:
73
- 1. 用原生能力(read_file/grep_search)阅读代码分析
74
- 2. 调用 `autosnippet_submit_knowledge_batch` 批量提交 3-5 条候选
75
- 3. 调用 `autosnippet_dimension_complete` 完成维度(传 referencedFiles + keyFindings)
76
-
77
- ---
78
-
79
- ## Phase 1: 架构分析(全局视角)
80
-
81
- **目标**: 提取 3-8 条架构级知识条目。
82
-
83
- **分析步骤**:
84
-
85
- 1. **查看 `targets`** — 每个 Target 的 `inferredRole` 告诉你它可能是什么
86
- 2. **查看 `dependencyGraph.edges`** — 理解模块间依赖关系
87
- 3. **查看各 Target 核心文件** — 确认架构模式(MVVM / MVC / Clean / 模块化 SPM 等)
88
- 4. **识别分层边界** — 哪些层可以调用哪些层?有无跨层调用?
89
-
90
- **输出类型**: `architecture` / `module-dependency` / `boundary-constraint`
91
-
92
- **架构候选模板**:
93
- ```json
94
- {
95
- "title": "分层架构: Presentation → Domain → Data",
96
- "trigger": "@layered-arch",
97
- "content": {
98
- "markdown": "## 分层架构\n\n项目采用三层架构...\n\n```\nPresentation (FeatureA, FeatureB)\n → Domain (UseCases, Entities)\n → Data (Repositories, API, Storage)\n```\n\n### 层级职责\n- **Presentation**: UI + ViewModel\n- **Domain**: UseCase + Entity\n- **Data**: Repository + API + Storage\n\n### 边界约束\n- View 层不直接 import Data 层\n- 所有数据访问通过 Domain 层 UseCase 中转",
99
- "pattern": "// Presentation → Domain → Data\nPresentation (FeatureA, FeatureB)\n → Domain (UseCases, Entities)\n → Data (Repositories, API, Storage)",
100
- "rationale": "项目采用三层架构,Presentation 不直接访问 Data 层。所有数据访问通过 Domain 层的 UseCase 中转,保证单向依赖。"
101
- },
102
- "description": "三层架构 Presentation → Domain → Data,禁止跨层访问",
103
- "language": "<primaryLanguage>",
104
- "headers": [],
105
- "category": "Service",
106
- "kind": "rule",
107
- "doClause": "Follow Presentation → Domain → Data layered architecture with no cross-layer access",
108
- "dontClause": "Never import Data layer modules directly from Presentation layer",
109
- "whenClause": "When creating new modules, reviewing code, or making architectural decisions",
110
- "coreCode": "// Presentation → Domain → Data\n// ✅ Presentation imports Domain\nimport DomainModule\n// ✅ Domain imports Data\nimport DataModule\n// ❌ Presentation must NOT import Data directly",
111
- "knowledgeType": "architecture",
112
- "usageGuide": "### 何时使用\n- 新建模块时确定放置层级\n- 代码审查检查跨层调用\n\n### 规则\n- View 层只调 Domain\n- Domain 层只调 Data\n- 禁止反向依赖",
113
- "difficulty": "intermediate",
114
- "scope": "project-specific",
115
- "steps": [
116
- { "title": "理解层级", "description": "Presentation 依赖 Domain, Domain 依赖 Data", "code": "" },
117
- { "title": "新模块规则", "description": "新功能模块放在 Presentation 层,公共逻辑放 Domain", "code": "" }
118
- ],
119
- "constraints": {
120
- "boundaries": ["View 层不直接 import Data 层模块"],
121
- "preconditions": []
122
- },
123
- "relations": {
124
- "dependsOn": [{ "target": "DomainModule", "description": "核心业务逻辑" }]
125
- },
126
- "reasoning": {
127
- "whyStandard": "项目全部模块遵循此分层,违反会导致循环依赖和测试困难",
128
- "sources": ["Package.swift", "dependencyGraph"],
129
- "confidence": 0.9
130
- }
131
- }
132
- ```
133
-
134
- ---
135
-
136
- ## Phase 2: 逐 Target 代码分析(8 维度)
137
-
138
- ### 分析优先级
139
-
140
- 按 `priority` 字段排序文件。推荐顺序:
141
-
142
- 1. **high priority** — 核心模块、Service 层、配置、协议定义
143
- 2. **medium priority** — 功能模块、Model、View
144
- 3. **low priority** — 工具类、扩展、测试
145
-
146
- ### 8 维度分析清单
147
-
148
- 对每个文件,系统性提取:
149
-
150
- | # | 维度 | 寻找什么 | knowledgeType | 示例 |
151
- |---|------|---------|---------------|------|
152
- | 1 | **代码规范** | 命名约定、注释风格、文件组织 | `code-standard` / `code-style` | "Manager 类统一以 Manager 结尾" |
153
- | 2 | **使用习惯** | 常用封装、工厂方法、API 调用方式 | `code-pattern` | "网络请求统一用 Result<T, Error>" |
154
- | 3 | **最佳实践** | 错误处理、并发、内存管理 | `best-practice` | "async 操作都用 Task { @MainActor in }" |
155
- | 4 | **调用链** | 关键业务路径、初始化链 | `call-chain` | "登录: View → AuthService → API → Token" |
156
- | 5 | **数据流** | 状态管理、响应式流 | `data-flow` | "Publisher 链: Network → VM → View" |
157
- | 6 | **代码关系** | 继承、协议实现 | `code-relation` / `inheritance` | "所有 VC 继承 BaseViewController" |
158
- | 7 | **Bug 修复** | 常见问题、defensive coding | `solution` + antiPattern | "避免在 deinit 中访问 weak self" |
159
- | 8 | **边界约束** | 访问限制、线程要求 | `boundary-constraint` | "UI 操作必须在主线程" |
160
-
161
- ### antiPattern 格式(Bug 修复维度专用)
162
-
163
- ```json
164
- {
165
- "antiPattern": {
166
- "bad": "DispatchQueue.main.async { self.update() }",
167
- "why": "在 Swift Concurrency 环境中可能造成数据竞争",
168
- "fix": "@MainActor func update() { ... }"
169
- }
170
- }
171
- ```
172
-
173
- ### relations 格式(知识关联)
174
-
175
- ```json
176
- {
177
- "relations": {
178
- "dependsOn": [{ "target": "NetworkModule", "description": "依赖网络层" }],
179
- "extends": [{ "target": "BaseService", "description": "扩展基础服务" }],
180
- "conflicts": [{ "target": "旧版 URLSession 直接调用", "description": "与新封装冲突" }]
181
- }
182
- }
183
- ```
184
-
185
- ---
186
-
187
- ## Phase 3: 项目库特征(Project Profile)
188
-
189
- 分析项目整体技术特征,提交 1 条汇总型候选:
190
-
191
- ```json
192
- {
193
- "title": "项目技术特征 — [ProjectName]",
194
- "trigger": "@projectProfile",
195
- "content": {
196
- "markdown": "## 技术栈全貌\n\n| 维度 | 值 |\n|------|------|\n| 主语言 | <language> |\n| 框架 | <framework1>, <framework2> |\n| 最低部署版本 | <platform version> |\n\n### 项目结构\n- 类型: <modular-spm|monorepo|workspace|...>\n- 核心模块: ModuleA(核心业务SDK), ModuleB(UI组件库)\n\n### 三方依赖\n- LibA: 用途\n- LibB: 用途",
197
- "pattern": "techStack:\n primaryLanguage: <language>\n frameworks: [<fw1>, <fw2>]\n projectStructure: <modular|monorepo|workspace>\n keyModules: [ModuleA, ModuleB]",
198
- "rationale": "项目技术栈全貌,新人 onboarding 和 Agent 理解项目的基础上下文"
199
- },
200
- "description": "项目技术栈全貌:语言、框架、模块结构、三方依赖",
201
- "language": "<primaryLanguage>",
202
- "headers": [],
203
- "category": "Architecture",
204
- "kind": "fact",
205
- "doClause": "Understand the project tech stack before making architectural decisions",
206
- "dontClause": "Do not introduce frameworks or patterns that conflict with the established tech stack",
207
- "whenClause": "When onboarding to the project or making technology choices",
208
- "coreCode": "// Project: [ProjectName]\n// Language: <language>\n// Frameworks: <fw1>, <fw2>\n// Structure: <modular|monorepo|workspace>\n// Key Modules: ModuleA, ModuleB",
209
- "knowledgeType": "architecture",
210
- "usageGuide": "### 何时查阅\n新人入职、技术选型、跨模块开发时参考\n### 注意事项\n版本升级时同步更新此条目",
211
- "reasoning": {
212
- "whyStandard": "项目技术选型摘要,所有开发决策的基础上下文",
213
- "sources": ["<project manifest: Package.swift / package.json / go.mod / pom.xml / etc.>", "projectMeta", "dependencyGraph"],
214
- "confidence": 0.95
215
- }
216
- }
217
- ```
218
-
219
- **分析要点**:
220
- - 从 `projectMeta` 获取主语言和项目类型
221
- - 从 `targets` 推断项目结构(单体/模块化)
222
- - 从 `dependencyGraph` 推断三方/自有模块依赖
223
- - 从代码中的 import 语句推断框架使用
224
-
225
- ---
226
-
227
- ## Phase 4: Agent 开发注意事项
228
-
229
- 提取 Agent(Cursor/Copilot)在本项目开发时**必须遵守的规则**。每条规则一个候选。
230
-
231
- ### 规则类别与严重级别
232
-
233
- | 类别 | severity | 示例 |
234
- |------|----------|------|
235
- | 命名 (naming) | `must` | "所有 ViewModel 以 VM 结尾" |
236
- | 线程 (threading) | `must` | "UI 更新必须在主线程/主 Actor" |
237
- | 内存 (memory) | `should` | "闭包/回调中注意循环引用" |
238
- | 架构 (architecture) | `must` | "View 层不直接访问 Repository" |
239
- | 安全 (security) | `must` | "不在代码中硬编码 API key" |
240
- | 性能 (performance) | `should` | "大列表使用虚拟化/懒加载" |
241
-
242
- ### Agent 注意事项候选模板
243
-
244
- ```json
245
- {
246
- "title": "[must] UI 更新必须在主线程",
247
- "trigger": "@agent-threading",
248
- "content": {
249
- "markdown": "## UI 线程安全\n\n所有 UI 更新操作必须在主线程/主 Actor 执行。\n\n### 各语言实现\n- **Swift**: `@MainActor func updateUI() { ... }`\n- **JS/TS**: 单线程无需处理,Web Worker 返回需 `postMessage`\n- **Python**: `loop.call_soon_threadsafe()` 或框架 API\n- **Go**: 使用 channel 或 sync 包\n- **Java/Kotlin**: `runOnUiThread { }` 或 `Dispatchers.Main`\n- **Rust**: `tokio::spawn` + channel 或 `Arc<Mutex<T>>`\n- **Dart**: `setState` 或 `WidgetsBinding.instance.addPostFrameCallback`\n\n### 反例\n在后台线程直接操作 UI 会导致崩溃或数据竞争。",
250
- "pattern": "// ✅ 正确 — 使用语言/框架提供的主线程机制\n// Swift: @MainActor func updateUI() { ... }\n// Kotlin: runOnUiThread { updateView() }\n\n// ❌ 错误 — 在后台线程直接操作 UI",
251
- "rationale": "UI 框架通常要求在主线程更新界面,违反会导致崩溃或数据竞争"
252
- },
253
- "description": "UI 更新必须在主线程/主 Actor 执行,违反会导致崩溃或数据竞争",
254
- "language": "<primaryLanguage>",
255
- "headers": [],
256
- "category": "Tool",
257
- "kind": "rule",
258
- "doClause": "Always dispatch UI updates to the main thread or main actor",
259
- "dontClause": "Never update UI elements from background threads or non-main dispatchers",
260
- "whenClause": "When writing code that updates UI after async operations or background tasks",
261
- "coreCode": "// Swift: @MainActor func updateUI() { ... }\n// Kotlin: runOnUiThread { updateView() }\n// JS/TS: postMessage from Worker\n// Python: loop.call_soon_threadsafe(callback)",
262
- "knowledgeType": "boundary-constraint",
263
- "usageGuide": "### 适用场景\n所有涉及 UI 更新的异步操作\n### 检查方式\n确认回调/闭包中的 UI 操作是否已切换到主线程",
264
- "reasoning": {
265
- "whyStandard": "项目 UI 层需在主线程操作,Agent 新写的代码也必须遵守",
266
- "sources": ["<relevant source files>"],
267
- "confidence": 0.9
268
- }
269
- }
270
- ```
271
-
272
- ---
273
-
274
- ## Phase 5: 批量提交
275
-
276
- 将所有分析结果通过 `autosnippet_submit_knowledge_batch` 批量提交(内置自动校验 + 去重):
277
-
278
- ```json
279
- {
280
- "items": [ /* Phase 1-4 的所有候选 */ ],
281
- "source": "bootstrap-external",
282
- "deduplicate": true
283
- }
284
- ```
285
-
286
- **建议**: 按维度分批提交,每批 10-20 条,避免单次请求过大。
287
-
288
- ### 预期产出(完整冷启动)
289
-
290
- | 维度 | 预期条数 |
291
- |------|---------|
292
- | 代码规范 (code-standard / code-style) | 15-30 |
293
- | 使用习惯 (code-pattern) | 20-40 |
294
- | 架构模式 (architecture) | 3-8 |
295
- | 最佳实践 (best-practice) | 10-20 |
296
- | 调用链 (call-chain) | 5-10 |
297
- | 数据流 (data-flow) | 3-8 |
298
- | Bug 修复 (solution + antiPattern) | 5-15 |
299
- | 项目特征 | 1 |
300
- | Agent 注意事项 | 5-15 |
301
- | 知识图谱边 | SPM 自动写入 |
302
-
303
- 总计: **70-150 条候选** → Dashboard 审核后成为正式 Recipe.
304
-
305
- ---
306
-
307
- ## 候选必填字段 Quick Reference
308
-
309
- 提交每条候选**必须**提供以下全部字段,缺失将被直接拒绝:
310
-
311
- | 字段 | 必填? | 说明 |
312
- |------|-------|------|
313
- | `title` | ★★★ 必填 | 简明标题(≤20字) |
314
- | `trigger` | ★★★ 必填 | @前缀触发词,如 `@swiftNaming` |
315
- | `content.markdown` | ★★★ 必填 | 项目特写 Markdown(≥200字) |
316
- | `content.pattern` | ★☆☆ 可选 | 核心代码片段(markdown 已含代码块时可省略) |
317
- | `content.rationale` | ★★★ 必填 | 设计原理(为什么这样做) |
318
- | `description` | ★★★ 必填 | 中文摘要 ≤80字 |
319
- | `language` | ★★★ 必填 | swift / objectivec / go / python / java / kotlin / dart / javascript / typescript 等 |
320
- | `headers` | ★★★ 必填 | import 语句数组,如 `["import Foundation"]`;无 import 时传 `[]` |
321
- | `category` | ★★★ 必填 | View / Service / Tool / Model / Network / Storage / UI / Utility |
322
- | `kind` | ★★★ 必填 | rule / pattern / fact |
323
- | `doClause` | ★★★ 必填 | 英文祈使句正向指令(≤60 tokens) |
324
- | `dontClause` | ★★★ 必填 | 英文反向约束(描述禁止的做法) |
325
- | `whenClause` | ★★★ 必填 | 英文触发场景(描述何时适用此规则) |
326
- | `coreCode` | ★★★ 必填 | 3-8行纯代码骨架(语法完整、括号配对、可直接复制) |
327
- | `knowledgeType` | ★★★ 必填 | 见 8 维度清单 |
328
- | `usageGuide` | ★★★ 必填 | 使用指南(### 章节格式) |
329
- | `reasoning.whyStandard` | ★★★ 必填 | 为什么值得沉淀 |
330
- | `reasoning.sources` | ★★★ 必填 | 来源文件路径 |
331
- | `reasoning.confidence` | ★★★ 必填 | 0-1 置信度 |
332
- | `difficulty` | ★★☆ 推荐 | beginner / intermediate / advanced |
333
- | `scope` | ★★☆ 推荐 | universal / project-specific / target-specific |
334
- | `steps` | ★★☆ 推荐 | 实施步骤 |
335
- | `constraints` | ★★☆ 推荐 | 前置条件/边界/副作用 |
336
- | `topicHint` | ★★☆ 推荐 | 主题分组(networking/ui/data/architecture/conventions) |
337
- | `relations` | ★★☆ 推荐 | 依赖/扩展/冲突关系 |
338
- | `antiPattern` | 条件必填 | 仅 Bug 修复维度 |
339
-
340
- ---
341
-
342
- ## Per-Dimension Industry Reference Templates
343
-
344
- > 以下是每个分析维度的**高质量候选模板**,基于业界最佳实践。分析时请以此为参考产出同等质量的候选。
345
- > **注意**: 每个维度提供多语言示例,实际分析时应使用项目的 `primaryLanguage` 和对应语言的代码示例。
346
-
347
- ### 维度 1: 代码规范 (code-standard) — 参考模板
348
-
349
- **Swift 示例:**
350
-
351
- ```json
352
- {
353
- "title": "命名约定: 类型用 UpperCamelCase, 变量/函数用 lowerCamelCase",
354
- "trigger": "@swift-naming",
355
- "content": {
356
- "markdown": "## Swift 命名约定\n\n遵循 Apple API Design Guidelines:\n\n```swift\n// ✅ 正确\nclass NetworkManager { }\nfunc fetchUserProfile() -> UserProfile { }\nlet currentUser: User\n\n// ❌ 错误\nclass network_manager { }\nfunc FetchUserProfile() -> UserProfile { }\nlet CURRENT_USER: User\n```\n\n### 规则\n- 类型名: UpperCamelCase\n- 变量/函数: lowerCamelCase\n- 缩写: URL/ID 在首位全大写,其他位置 lowerCamelCase\n\n### 反例\n```swift\nlet kMaxRetryCount = 3 // ❌ 匈牙利命名\nclass network_manager { } // ❌ 下划线\n```",
357
- "pattern": "// ✅ 正确\nclass NetworkManager { }\nfunc fetchUserProfile() -> UserProfile { }\nlet currentUser: User\n\n// ❌ 错误\nclass network_manager { }\nfunc FetchUserProfile() -> UserProfile { }",
358
- "rationale": "遵循 Apple API Design Guidelines 和 Google Swift Style Guide:类型名用 UpperCamelCase,变量/函数/参数用 lowerCamelCase,全局常量用 lowerCamelCase(不用 k 前缀或 SCREAMING_SNAKE_CASE)"
359
- },
360
- "description": "Swift 命名约定:类型 UpperCamelCase,变量/函数 lowerCamelCase",
361
- "language": "swift",
362
- "headers": ["import Foundation"],
363
- "category": "Tool",
364
- "kind": "rule",
365
- "doClause": "Use UpperCamelCase for types and lowerCamelCase for variables, functions, and parameters",
366
- "knowledgeType": "code-standard",
367
- "usageGuide": "### 何时使用\n- 新建类/结构体/枚举/协议时\n- 命名变量/函数/参数时\n\n### 规则\n- class/struct/enum/protocol: UpperCamelCase\n- 变量/函数/参数: lowerCamelCase\n- 缩写: URL/ID 首位全大写,其他位 lowerCamelCase",
368
- "difficulty": "beginner",
369
- "scope": "project-specific",
370
- "steps": [
371
- { "title": "类型命名", "description": "class/struct/enum/protocol 用 UpperCamelCase", "code": "struct UserProfile { }" },
372
- { "title": "函数命名", "description": "方法名以动词开头,参数标签读起来像句子", "code": "func insert(_ element: Element, at index: Int)" },
373
- { "title": "缩写处理", "description": "缩写作为整体大小写", "code": "let urlString = ...\nclass HTMLParser { }" }
374
- ],
375
- "antiPattern": {
376
- "bad": "let kMaxRetryCount = 3\nclass network_manager { }",
377
- "why": "匈牙利命名法 k 前缀和下划线命名不符合 Swift 惯例,降低可读性",
378
- "fix": "let maxRetryCount = 3\nclass NetworkManager { }"
379
- },
380
- "reasoning": {
381
- "whyStandard": "统一命名规范是代码可读性的基础,Apple 和 Google 风格指南均以此为核心准则",
382
- "sources": ["Apple API Design Guidelines", "Google Swift Style Guide"],
383
- "confidence": 0.95
384
- }
385
- }
386
- ```
387
-
388
- **Go 示例:**
389
-
390
- ```json
391
- {
392
- "title": "命名约定: 导出用 UpperCamelCase, 内部用 lowerCamelCase",
393
- "trigger": "@go-naming",
394
- "content": {
395
- "markdown": "## Go 命名约定\n\n遵循 Effective Go:\n\n```go\n// ✅ 正确 — 导出名大写开头,内部名小写开头\ntype NetworkManager struct { }\nfunc FetchUserProfile() (*UserProfile, error) { }\nvar currentUser *User\n\n// ❌ 错误\ntype network_manager struct { }\nfunc fetch_user_profile() { }\n```\n\n### 规则\n- 导出标识符: 首字母大写\n- 内部标识符: 首字母小写\n- 缩写: 保持全大写(HTTP、URL、ID)",
396
- "pattern": "// 导出用 UpperCamelCase\ntype NetworkManager struct { }\nfunc FetchUserProfile() (*UserProfile, error) { }\n// 内部用 lowerCamelCase\nvar currentUser *User",
397
- "rationale": "遵循 Effective Go:导出标识符首字母大写,内部小写;缩写保持全大写(HTTP、URL、ID)"
398
- },
399
- "description": "Go 命名约定:导出标识符大写开头,内部小写开头",
400
- "language": "go",
401
- "headers": [],
402
- "category": "Tool",
403
- "kind": "rule",
404
- "doClause": "Use UpperCamelCase for exported identifiers and lowerCamelCase for unexported ones",
405
- "knowledgeType": "code-standard",
406
- "usageGuide": "### 何时使用\n- 定义新的类型/函数/变量时\n\n### 规则\n- 导出(大写开头): 提供给外部包使用\n- 未导出(小写开头): 包内私有\n- 缩写全大写: HTTPClient, URL, ID",
407
- "antiPattern": {
408
- "bad": "type http_client struct { }\nfunc get_User() { }",
409
- "why": "下划线和混合大小写不符合 Go 惯例",
410
- "fix": "type HTTPClient struct { }\nfunc GetUser() { }"
411
- },
412
- "reasoning": {
413
- "whyStandard": "Go 用大小写控制可见性,统一命名是团队协作的基础",
414
- "sources": ["Effective Go", "Go Code Review Comments"],
415
- "confidence": 0.95
416
- }
417
- }
418
- ```
419
-
420
- **Python 示例:**
421
-
422
- ```json
423
- {
424
- "title": "命名约定: 类用 PascalCase, 函数/变量用 snake_case",
425
- "trigger": "@python-naming",
426
- "content": {
427
- "markdown": "## Python 命名规范 (PEP 8)\n\n### ✅ 正确示例\n```python\nclass NetworkManager:\n pass\n\ndef fetch_user_profile() -> UserProfile:\n pass\n\ncurrent_user: User\nMAX_RETRY_COUNT = 3 # 常量全大写\n```\n\n### ❌ 错误示例\n```python\nclass network_manager:\n pass\n\ndef FetchUserProfile():\n pass\n```\n\n### 规则总结\n- 类名:PascalCase(如 `NetworkManager`)\n- 函数/变量:snake_case(如 `fetch_user_profile`)\n- 常量:UPPER_SNAKE_CASE(如 `MAX_RETRY_COUNT`)\n- 模块名:全小写 snake_case",
428
- "pattern": "class NetworkManager:\n pass\n\ndef fetch_user_profile() -> UserProfile:\n pass\n\ncurrent_user: User\nMAX_RETRY_COUNT = 3",
429
- "rationale": "遵循 PEP 8:类名 PascalCase,函数/变量 snake_case,常量 UPPER_SNAKE_CASE。所有主流 Python 工具(pylint、flake8、black)均强制执行此规范。"
430
- },
431
- "description": "Python 命名规范:类 PascalCase,函数/变量 snake_case,常量 UPPER_SNAKE_CASE",
432
- "kind": "rule",
433
- "doClause": "Use PascalCase for classes, snake_case for functions and variables, UPPER_SNAKE_CASE for constants",
434
- "language": "python",
435
- "headers": [],
436
- "category": "Tool",
437
- "knowledgeType": "code-standard",
438
- "usageGuide": "### 使用场景\n在 Python 项目中创建新类、函数或变量时,触发 `@python-naming` 查阅命名约定,确保符合 PEP 8 标准。",
439
- "difficulty": "beginner",
440
- "scope": "project-specific",
441
- "antiPattern": {
442
- "bad": "class network_manager:\n def FetchData(self): pass",
443
- "why": "类名应 PascalCase,方法名应 snake_case,混用降低可读性",
444
- "fix": "class NetworkManager:\n def fetch_data(self): pass"
445
- },
446
- "reasoning": {
447
- "whyStandard": "PEP 8 是 Python 社区标准,所有主流工具(pylint、flake8、black)均强制执行",
448
- "sources": ["PEP 8", "Google Python Style Guide"],
449
- "confidence": 0.95
450
- }
451
- }
452
- ```
453
-
454
- **Dart (Flutter) 示例:**
455
-
456
- ```json
457
- {
458
- "title": "命名约定: 类用 UpperCamelCase, 变量/函数用 lowerCamelCase, 文件名 snake_case",
459
- "trigger": "@dart-naming",
460
- "content": {
461
- "markdown": "## Dart 命名规范 (Effective Dart)\n\n### ✅ 正确示例\n```dart\nclass NetworkManager { }\nvoid fetchUserProfile() { }\nfinal currentUser = User();\nconst defaultTimeout = Duration(seconds: 30);\n\n// 文件名: user_service.dart, home_page.dart\n// 私有成员: _isLoading, _controller\n```\n\n### ❌ 错误示例\n```dart\nconst MAX_RETRY_COUNT = 3; // Dart 不用 SCREAMING_CAPS\nclass user_service { } // 类名应 UpperCamelCase\nString UserName = ''; // 变量应 lowerCamelCase\n```\n\n### 规则总结\n- 类名: UpperCamelCase(如 `UserService`)\n- 变量/函数: lowerCamelCase(如 `fetchData`)\n- 常量: lowerCamelCase(如 `defaultTimeout`,不用 SCREAMING_CAPS)\n- 文件名: snake_case(如 `user_service.dart`)",
462
- "pattern": "class NetworkManager { }\nvoid fetchUserProfile() { }\nfinal currentUser = User();\nconst defaultTimeout = Duration(seconds: 30);",
463
- "rationale": "遵循 Effective Dart Style:类名 UpperCamelCase,变量/函数 lowerCamelCase,常量也用 lowerCamelCase(区别于 Java/C++),文件名 snake_case。dart analyze 会强制检查。"
464
- },
465
- "description": "Dart 命名规范:类 UpperCamelCase,变量/函数 lowerCamelCase,常量 lowerCamelCase,文件 snake_case",
466
- "kind": "rule",
467
- "doClause": "Use UpperCamelCase for types, lowerCamelCase for variables/functions/constants, snake_case for filenames",
468
- "language": "dart",
469
- "headers": [],
470
- "category": "Tool",
471
- "knowledgeType": "code-standard",
472
- "usageGuide": "### 使用场景\n在 Dart/Flutter 项目中创建新文件或标识符时,触发 `@dart-naming` 查阅 Effective Dart 命名约定。",
473
- "difficulty": "beginner",
474
- "scope": "project-specific",
475
- "antiPattern": {
476
- "bad": "const MAX_RETRY = 3;\nclass user_service { }",
477
- "why": "SCREAMING_CAPS 和下划线类名不符合 Dart 惯例,dart analyze 会警告",
478
- "fix": "const maxRetry = 3;\nclass UserService { }"
479
- },
480
- "reasoning": {
481
- "whyStandard": "Effective Dart Style 是 Dart 官方规范,dart analyze + flutter_lints 强制执行",
482
- "sources": ["Effective Dart - Style", "Dart Linter Rules"],
483
- "confidence": 0.95
484
- }
485
- }
486
- ```
487
-
488
- ### 维度 2: 使用习惯 (code-pattern) — 参考模板
489
-
490
- **Swift 示例:**
491
-
492
- ```json
493
- {
494
- "title": "单例模式: 使用 static let shared",
495
- "trigger": "@swift-singleton",
496
- "content": {
497
- "markdown": "## Swift 单例模式\n\n### ✅ 推荐模式\n```swift\nclass CacheManager {\n static let shared = CacheManager()\n private init() { }\n \n func store(_ data: Data, forKey key: String) { ... }\n}\n\n// 使用\nCacheManager.shared.store(data, forKey: \"user\")\n```\n\n### 要点\n- `static let` 天然线程安全(dispatch_once 语义)\n- `private init()` 防止外部实例化\n- 属性名通常用 `shared` 或 `default`",
498
- "pattern": "class CacheManager {\n static let shared = CacheManager()\n private init() { }\n}",
499
- "rationale": "Swift 的 static let 天然线程安全(dispatch_once 语义)。private init() 防止外部实例化。"
500
- },
501
- "description": "Swift 单例模式:static let shared + private init(),天然线程安全",
502
- "kind": "pattern",
503
- "doClause": "Implement singletons using static let shared with private init for thread safety",
504
- "language": "swift",
505
- "headers": ["import Foundation"],
506
- "category": "Service",
507
- "knowledgeType": "code-pattern",
508
- "usageGuide": "### 使用场景\n创建 Manager/Service 类的唯一实例时,触发 `@swift-singleton` 获取标准单例实现模式。",
509
- "difficulty": "beginner",
510
- "scope": "universal",
511
- "steps": [
512
- { "title": "声明", "description": "用 static let shared 暴露唯一实例", "code": "static let shared = MyService()" },
513
- { "title": "私有初始化", "description": "用 private init() 防止外部创建", "code": "private init() { }" },
514
- { "title": "命名", "description": "属性名通常用 shared 或 default", "code": "" }
515
- ],
516
- "reasoning": {
517
- "whyStandard": "项目中 Manager/Service 类全部采用此模式。static let 在 Swift 中自动 lazy + thread-safe",
518
- "sources": ["Google Swift Style Guide - Static and Class Properties"],
519
- "confidence": 0.9
520
- }
521
- }
522
- ```
523
-
524
- **TypeScript 示例:**
525
-
526
- ```json
527
- {
528
- "title": "单例模式: class + private constructor + getInstance()",
529
- "trigger": "@ts-singleton",
530
- "content": {
531
- "markdown": "## TypeScript 单例模式\n\n### ✅ 推荐模式\n```typescript\nclass CacheManager {\n private static instance: CacheManager;\n private constructor() { }\n\n static getInstance(): CacheManager {\n if (!CacheManager.instance) {\n CacheManager.instance = new CacheManager();\n }\n return CacheManager.instance;\n }\n\n store(key: string, data: unknown): void { /* ... */ }\n}\n\n// 使用\nCacheManager.getInstance().store('user', data);\n```\n\n### 要点\n- `private constructor` 阻止外部实例化\n- `getInstance()` 保证返回唯一实例\n- 也可用 ES Module 导出单实例对象作为替代",
532
- "pattern": "class CacheManager {\n private static instance: CacheManager;\n private constructor() { }\n static getInstance(): CacheManager { ... }\n}",
533
- "rationale": "TypeScript 用 private constructor 阻止外部实例化,getInstance() 保证唯一。也可用 ES Module 导出单实例对象。"
534
- },
535
- "description": "TypeScript 单例模式:private constructor + 静态 getInstance(),保证唯一实例",
536
- "kind": "pattern",
537
- "doClause": "Implement singletons using private constructor and static getInstance method",
538
- "language": "typescript",
539
- "headers": [],
540
- "category": "Service",
541
- "knowledgeType": "code-pattern",
542
- "usageGuide": "### 使用场景\n创建 TypeScript Manager/Service 单例时,触发 `@ts-singleton` 获取标准实现模式。",
543
- "difficulty": "beginner",
544
- "scope": "universal",
545
- "reasoning": {
546
- "whyStandard": "项目中 Manager/Service 类使用此模式或 module-level 单例",
547
- "sources": ["TypeScript Design Patterns"],
548
- "confidence": 0.9
549
- }
550
- }
551
- ```
552
-
553
- **Go 示例:**
554
-
555
- ```json
556
- {
557
- "title": "单例模式: sync.Once + 包级变量",
558
- "trigger": "@go-singleton",
559
- "content": {
560
- "markdown": "## Go 单例模式\n\n### ✅ 推荐模式\n```go\nvar (\n\tinstance *CacheManager\n\tonce sync.Once\n)\n\nfunc GetCacheManager() *CacheManager {\n\tonce.Do(func() {\n\t\tinstance = &CacheManager{}\n\t})\n\treturn instance\n}\n\ntype CacheManager struct { /* ... */ }\nfunc (c *CacheManager) Store(key string, data []byte) { /* ... */ }\n```\n\n### 要点\n- `sync.Once` 保证初始化函数只执行一次(并发安全)\n- 包级变量 + 导出函数暴露实例\n- 延迟初始化,首次调用时才创建",
561
- "pattern": "var (\n\tinstance *CacheManager\n\tonce sync.Once\n)\n\nfunc GetCacheManager() *CacheManager {\n\tonce.Do(func() { instance = &CacheManager{} })\n\treturn instance\n}",
562
- "rationale": "Go 使用 sync.Once 保证线程安全的延迟初始化,是标准单例实现方式。"
563
- },
564
- "description": "Go 单例模式:sync.Once 保证线程安全的延迟初始化",
565
- "kind": "pattern",
566
- "doClause": "Implement singletons using sync.Once with package-level variable for thread-safe lazy init",
567
- "language": "go",
568
- "headers": ["import \"sync\""],
569
- "category": "Service",
570
- "knowledgeType": "code-pattern",
571
- "usageGuide": "### 使用场景\n创建 Go 全局唯一实例时,触发 `@go-singleton` 获取 sync.Once 标准模式。",
572
- "difficulty": "beginner",
573
- "scope": "universal",
574
- "reasoning": {
575
- "whyStandard": "sync.Once 是 Go 标准库提供的并发安全初始化原语",
576
- "sources": ["Effective Go", "Go sync package documentation"],
577
- "confidence": 0.9
578
- }
579
- }
580
- ```
581
-
582
- **Dart (Flutter) 示例:**
583
-
584
- ```json
585
- {
586
- "title": "单例模式: private constructor + static final instance",
587
- "trigger": "@dart-singleton",
588
- "content": {
589
- "markdown": "## Dart 单例模式\n\n### ✅ 推荐模式\n```dart\nclass CacheManager {\n CacheManager._();\n static final CacheManager instance = CacheManager._();\n\n // 或使用 factory 构造函数\n factory CacheManager() => instance;\n\n void store(String key, dynamic data) { /* ... */ }\n}\n\n// 使用\nCacheManager.instance.store('user', data);\n// 或\nCacheManager().store('user', data);\n```\n\n### 要点\n- `ClassName._()` private 命名构造函数阻止外部实例化\n- `static final` 保证唯一实例,Dart 天然线程安全(单隔离区)\n- factory 构造函数可选,让调用更自然",
590
- "pattern": "class CacheManager {\n CacheManager._();\n static final CacheManager instance = CacheManager._();\n factory CacheManager() => instance;\n}",
591
- "rationale": "Dart 的 private 命名构造函数 + static final 是标准单例实现,单 Isolate 天然线程安全。"
592
- },
593
- "description": "Dart 单例模式:private constructor + static final instance",
594
- "kind": "pattern",
595
- "doClause": "Implement singletons using private named constructor with static final instance",
596
- "language": "dart",
597
- "headers": [],
598
- "category": "Service",
599
- "knowledgeType": "code-pattern",
600
- "usageGuide": "### 使用场景\n创建 Dart Manager/Service 单例时,触发 `@dart-singleton` 获取标准模式。",
601
- "difficulty": "beginner",
602
- "scope": "universal",
603
- "reasoning": {
604
- "whyStandard": "Dart 社区通用单例模式,factory 构造函数是语言特性",
605
- "sources": ["Effective Dart - Design", "Dart Language Tour - Constructors"],
606
- "confidence": 0.9
607
- }
608
- }
609
- ```
610
-
611
- ### 维度 3: 最佳实践 (best-practice) — 参考模板
612
-
613
- **Swift 示例:**
614
-
615
- ```json
616
- {
617
- "title": "错误处理: 用 typed Error enum + do-catch",
618
- "trigger": "@swift-error-handling",
619
- "content": {
620
- "markdown": "## Swift 错误处理最佳实践\n\n### ✅ 推荐:typed Error enum + do-catch\n```swift\nenum NetworkError: Error {\n case invalidURL\n case timeout\n case serverError(statusCode: Int)\n}\n\nfunc fetchData(from url: String) throws -> Data {\n guard let url = URL(string: url) else {\n throw NetworkError.invalidURL\n }\n // ...\n}\n\ndo {\n let data = try fetchData(from: endpoint)\n} catch NetworkError.timeout {\n showRetryAlert()\n} catch {\n log(error)\n}\n```\n\n### 要点\n- 用 typed enum Error 使调用者能精确 catch 不同错误类型\n- 避免 generic Error string\n- throws 优于 Result 混合模型(Google Swift Style Guide)",
621
- "pattern": "enum NetworkError: Error {\n case invalidURL\n case timeout\n case serverError(statusCode: Int)\n}\n\nfunc fetchData(from url: String) throws -> Data { ... }\n\ndo {\n let data = try fetchData(from: endpoint)\n} catch NetworkError.timeout {\n showRetryAlert()\n}",
622
- "rationale": "用 typed enum Error 使调用者能精确 catch 不同错误类型。避免 generic Error string。Google Swift Style Guide 明确推荐 throws 而非 Result 混合模型。"
623
- },
624
- "description": "Swift 错误处理:typed Error enum + do-catch 精确捕获不同错误类型",
625
- "kind": "pattern",
626
- "doClause": "Use typed Error enum with do-catch for precise error handling instead of generic errors",
627
- "language": "swift",
628
- "headers": ["import Foundation"],
629
- "category": "Service",
630
- "knowledgeType": "best-practice",
631
- "usageGuide": "### 使用场景\n在 Swift 中处理可能失败的操作时,触发 `@swift-error-handling` 获取标准错误处理模式。",
632
- "difficulty": "intermediate",
633
- "scope": "universal",
634
- "antiPattern": {
635
- "bad": "func fetchData() -> String? { return nil /* on error */ }",
636
- "why": "返回 nil 丢失错误信息,调用者无法区分'无数据'和'发生错误'",
637
- "fix": "func fetchData() throws -> Data { throw NetworkError.timeout }"
638
- },
639
- "reasoning": {
640
- "whyStandard": "Swift 的 throws/catch 机制强制调用者处理错误,编译器保证完整性",
641
- "sources": ["Google Swift Style Guide - Error Types", "Swift Language Guide"],
642
- "confidence": 0.95
643
- }
644
- }
645
- ```
646
-
647
- **Go 示例:**
648
-
649
- ```json
650
- {
651
- "title": "错误处理: 自定义 error 类型 + errors.Is/As",
652
- "trigger": "@go-error-handling",
653
- "content": {
654
- "markdown": "## Go 错误处理最佳实践\n\n### ✅ 推荐:自定义 error + fmt.Errorf %w + errors.Is/As\n```go\ntype NetworkError struct {\n\tStatusCode int\n\tMessage string\n}\n\nfunc (e *NetworkError) Error() string {\n\treturn fmt.Sprintf(\"network error %d: %s\", e.StatusCode, e.Message)\n}\n\nvar ErrTimeout = errors.New(\"request timeout\")\n\nfunc fetchData(url string) ([]byte, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fetch failed: %w\", err)\n\t}\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, &NetworkError{StatusCode: resp.StatusCode}\n\t}\n\treturn io.ReadAll(resp.Body)\n}\n\n// 调用端\ndata, err := fetchData(endpoint)\nif errors.Is(err, ErrTimeout) {\n\t// 重试\n} else if var ne *NetworkError; errors.As(err, &ne) {\n\tlog.Printf(\"server error: %d\", ne.StatusCode)\n}\n```\n\n### 要点\n- 自定义 error 类型实现 `Error()` 接口\n- `fmt.Errorf(\"%w\")` 包装错误链\n- `errors.Is/As` 解包判断错误类型",
655
- "pattern": "type NetworkError struct {\n\tStatusCode int\n\tMessage string\n}\nfunc (e *NetworkError) Error() string { ... }\nvar ErrTimeout = errors.New(\"request timeout\")\nfunc fetchData(url string) ([]byte, error) { ... }",
656
- "rationale": "Go 用自定义 error 类型 + fmt.Errorf %w 包装 + errors.Is/As 判断,是官方推荐的错误处理模式。"
657
- },
658
- "description": "Go 错误处理:自定义 error 类型 + fmt.Errorf %w 包装 + errors.Is/As",
659
- "kind": "pattern",
660
- "doClause": "Use custom error types with fmt.Errorf wrapping and errors.Is/As for structured error handling",
661
- "language": "go",
662
- "headers": ["import \"errors\"", "import \"fmt\"", "import \"net/http\""],
663
- "category": "Service",
664
- "knowledgeType": "best-practice",
665
- "usageGuide": "### 使用场景\n在 Go 项目中处理错误时,触发 `@go-error-handling` 获取标准错误处理模式。",
666
- "difficulty": "intermediate",
667
- "scope": "universal",
668
- "antiPattern": {
669
- "bad": "func fetchData() string { return \"\" /* on error */ }",
670
- "why": "返回空字符串丢失错误信息,调用者无法区分'空结果'和'出错'",
671
- "fix": "func fetchData() (string, error) { return \"\", fmt.Errorf(\"timeout\") }"
672
- },
673
- "reasoning": {
674
- "whyStandard": "Go 的多返回值 + error 接口是核心错误处理范式,errors.Is/As 支持错误链解包",
675
- "sources": ["Effective Go - Errors", "Go Blog: Working with Errors in Go 1.13"],
676
- "confidence": 0.95
677
- }
678
- }
679
- ```
680
-
681
- **Java 示例:**
682
-
683
- ```json
684
- {
685
- "title": "错误处理: 自定义异常层级 + 特定 catch",
686
- "trigger": "@java-error-handling",
687
- "content": {
688
- "markdown": "## Java 错误处理最佳实践\n\n### ✅ 推荐:自定义异常层级 + 特定 catch\n```java\npublic class NetworkException extends RuntimeException {\n private final int statusCode;\n public NetworkException(int statusCode, String message) {\n super(message);\n this.statusCode = statusCode;\n }\n public int getStatusCode() { return statusCode; }\n}\n\npublic class TimeoutException extends NetworkException {\n public TimeoutException() { super(408, \"Request Timeout\"); }\n}\n\n// 调用端\ntry {\n var data = fetchData(endpoint);\n} catch (TimeoutException e) {\n retryLater();\n} catch (NetworkException e) {\n log.error(\"Server error: {}\", e.getStatusCode());\n}\n```\n\n### 要点\n- 自定义异常继承层级,精确 catch\n- 避免 `catch (Exception e)` 一揽子处理\n- 携带业务信息(如 statusCode)",
689
- "pattern": "public class NetworkException extends RuntimeException {\n private final int statusCode;\n ...\n}\npublic class TimeoutException extends NetworkException { ... }\ntry { ... } catch (TimeoutException e) { ... } catch (NetworkException e) { ... }",
690
- "rationale": "用异常层级使调用者能精确 catch 不同错误类型,避免 catch (Exception e) 一揽子处理。"
691
- },
692
- "description": "Java 错误处理:自定义异常层级 + 特定 catch 精确处理",
693
- "kind": "pattern",
694
- "doClause": "Use custom exception hierarchy with specific catch blocks for precise error handling",
695
- "language": "java",
696
- "headers": [],
697
- "category": "Service",
698
- "knowledgeType": "best-practice",
699
- "usageGuide": "### 使用场景\n在 Java 项目中设计错误处理时,触发 `@java-error-handling` 获取自定义异常层级模式。",
700
- "difficulty": "intermediate",
701
- "scope": "universal",
702
- "reasoning": {
703
- "whyStandard": "Java 的 checked/unchecked exception 体系要求结构化的错误处理",
704
- "sources": ["Effective Java - Exceptions", "Google Java Style Guide"],
705
- "confidence": 0.95
706
- }
707
- }
708
- ```
709
-
710
- **Dart (Flutter) 示例:**
711
-
712
- ```json
713
- {
714
- "title": "错误处理: 自定义 Exception + on-catch + Result 模式",
715
- "trigger": "@dart-error-handling",
716
- "content": {
717
- "markdown": "## Dart 错误处理最佳实践\n\n### ✅ 推荐:自定义 Exception + on-catch\n```dart\nclass NetworkException implements Exception {\n final int statusCode;\n final String message;\n const NetworkException(this.statusCode, this.message);\n\n @override\n String toString() => 'NetworkException($statusCode): $message';\n}\n\nclass TimeoutException extends NetworkException {\n const TimeoutException() : super(408, 'Request timeout');\n}\n\nFuture<User> fetchUser(int id) async {\n try {\n return await _api.getUser(id);\n } on TimeoutException {\n return _cache.getUser(id) ?? rethrow;\n } on NetworkException catch (e) {\n _logger.warning('Network error: $e');\n rethrow;\n }\n}\n```\n\n### 要点\n- 自定义 Exception 携带业务信息(如 statusCode)\n- `on Type catch (e)` 精确捕获不同类型\n- `rethrow` 保留原始堆栈信息\n- 避免 `catch (_) { }` 吞掉所有错误",
718
- "pattern": "class NetworkException implements Exception {\n final int statusCode;\n final String message;\n const NetworkException(this.statusCode, this.message);\n}\n\ntry {\n ...\n} on TimeoutException {\n ...\n} on NetworkException catch (e) {\n rethrow;\n}",
719
- "rationale": "Dart 用 on .. catch 精确捕获不同异常类型,rethrow 保留原始堆栈。Effective Dart 推荐 implements Exception 而非 extends Error。"
720
- },
721
- "description": "Dart 错误处理:自定义 Exception + on-catch 精确捕获",
722
- "kind": "pattern",
723
- "doClause": "Use custom Exception types with on-catch blocks for structured error handling",
724
- "language": "dart",
725
- "headers": [],
726
- "category": "Service",
727
- "knowledgeType": "best-practice",
728
- "usageGuide": "### 使用场景\n在 Dart/Flutter 项目中设计错误处理时,触发 `@dart-error-handling` 获取自定义 Exception 模式。",
729
- "difficulty": "intermediate",
730
- "scope": "universal",
731
- "antiPattern": {
732
- "bad": "try { ... } catch (_) { } // 或 throw 'error string'",
733
- "why": "吞掉所有错误让 bug 难以排查;throw String 丢失堆栈信息",
734
- "fix": "自定义 Exception + on .. catch + rethrow"
735
- },
736
- "reasoning": {
737
- "whyStandard": "Effective Dart - Error handling; Dart 的 on-catch 支持按类型精确捕获",
738
- "sources": ["Effective Dart - Usage (Errors)", "Dart Language Tour - Exceptions"],
739
- "confidence": 0.95
740
- }
741
- }
742
- ```
743
-
744
- ### 维度 4: 调用链 (call-chain) — 参考模板
745
-
746
- **Swift 示例:**
747
-
748
- ```json
749
- {
750
- "title": "用户登录调用链: View → ViewModel → AuthService → API",
751
- "trigger": "@swift-login-chain",
752
- "content": {
753
- "markdown": "## Swift 用户登录调用链\n\n### 完整链路\n```\n1. LoginView: Button tap → viewModel.login()\n2. LoginViewModel: @MainActor func login()\n → authService.authenticate(email, password)\n3. AuthService: func authenticate() async throws → Token\n → apiClient.post(\"/auth/login\", body)\n4. APIClient: func post<T>() async throws → T\n → URLSession.shared.data(for: request)\n5. 返回链: Token → AuthService 存 Keychain → ViewModel 更新状态 → View 刷新\n```\n\n### 边界约束\n- AuthService 不直接 import View 层\n- Token 存取只通过 KeychainService",
754
- "pattern": "LoginView → LoginViewModel → AuthService → APIClient → URLSession\nToken → Keychain → ViewModel state → View refresh",
755
- "rationale": "登录是最核心的业务流程之一,新人必须理解完整链路才能修改认证逻辑。"
756
- },
757
- "description": "Swift 用户登录调用链:View → ViewModel → AuthService → API 四层链路",
758
- "kind": "fact",
759
- "doClause": "Follow the View to ViewModel to AuthService to API call chain for login flow",
760
- "language": "swift",
761
- "headers": ["import Foundation"],
762
- "category": "View",
763
- "knowledgeType": "call-chain",
764
- "usageGuide": "### 使用场景\n修改登录流程或认证逻辑时,触发 `@swift-login-chain` 查看完整调用链路。",
765
- "difficulty": "intermediate",
766
- "scope": "project-specific",
767
- "constraints": {
768
- "boundaries": ["AuthService 不直接 import View 层", "Token 存取只通过 KeychainService"],
769
- "preconditions": ["网络可用", "API endpoint 已配置"]
770
- },
771
- "reasoning": {
772
- "whyStandard": "登录流程涉及 4 层,任何一层修改都可能影响整个链路",
773
- "sources": ["Sources/Auth/LoginViewModel.swift", "Sources/Service/AuthService.swift"],
774
- "confidence": 0.85
775
- }
776
- }
777
- ```
778
-
779
- **TypeScript (React) 示例:**
780
-
781
- ```json
782
- {
783
- "title": "用户登录调用链: Component → Hook → Service → API",
784
- "trigger": "@ts-login-chain",
785
- "content": {
786
- "markdown": "## TypeScript/React 登录调用链\n\n### 完整链路\n```\n1. LoginPage: form submit → useAuth().login(email, password)\n2. useAuth hook: async login()\n → authService.authenticate(email, password)\n3. AuthService: authenticate() → fetch('/api/auth/login', { method: 'POST', body })\n4. API route: POST /api/auth/login → validate → JWT\n5. 返回链: Token → localStorage.setItem → hook setState → Component re-render\n```\n\n### 边界约束\n- Component 不直接调用 fetch\n- Token 存取只通过 AuthService",
787
- "pattern": "LoginPage → useAuth() hook → AuthService.authenticate() → fetch('/api/auth/login')\nToken → localStorage → hook setState → Component re-render",
788
- "rationale": "登录流程是前端核心链路,涉及 UI → Hook → Service → API 四层。"
789
- },
790
- "description": "TypeScript/React 登录调用链:Component → Hook → Service → API",
791
- "kind": "fact",
792
- "doClause": "Follow the Component to Hook to Service to API call chain for login flow",
793
- "language": "typescript",
794
- "headers": ["import { useState } from 'react'"],
795
- "category": "View",
796
- "knowledgeType": "call-chain",
797
- "usageGuide": "### 使用场景\n修改前端登录流程时,触发 `@ts-login-chain` 查看完整调用链路。",
798
- "difficulty": "intermediate",
799
- "scope": "project-specific",
800
- "constraints": {
801
- "boundaries": ["Component 不直接调用 fetch", "Token 存取只通过 AuthService"],
802
- "preconditions": ["API 服务可用", "CORS 配置正确"]
803
- },
804
- "reasoning": {
805
- "whyStandard": "前端登录流程涉及多层,清晰的链路文档帮助新人快速理解",
806
- "sources": ["src/pages/LoginPage.tsx", "src/services/authService.ts"],
807
- "confidence": 0.85
808
- }
809
- }
810
- ```
811
-
812
- ### 维度 7: Bug 修复 (solution + antiPattern) — 参考模板
813
-
814
- **Swift 示例:**
815
-
816
- ```json
817
- {
818
- "title": "[Bug] 闭包中循环引用导致内存泄漏",
819
- "trigger": "@swift-retain-cycle",
820
- "content": {
821
- "markdown": "## Swift 闭包循环引用修复\n\n### ❌ 内存泄漏\n```swift\nclass ViewModel {\n var onComplete: (() -> Void)?\n func start() {\n service.fetch { result in\n self.onComplete?() // strong capture → retain cycle\n }\n }\n}\n```\n\n### ✅ 修复:[weak self]\n```swift\nclass ViewModel {\n var onComplete: (() -> Void)?\n func start() {\n service.fetch { [weak self] result in\n self?.onComplete?()\n }\n }\n}\n```\n\n### 要点\n- 闭包默认 strong capture self\n- 如果 self 也持有 closure(直接或间接),形成 retain cycle\n- 用 `[weak self]` 打破循环",
822
- "pattern": "service.fetch { [weak self] result in\n self?.onComplete?()\n}",
823
- "rationale": "Swift 使用 ARC,闭包默认 strong capture。任何可能被持有的闭包都应使用 [weak self] 避免 retain cycle。"
824
- },
825
- "description": "Swift 闭包循环引用修复:[weak self] 避免 retain cycle 内存泄漏",
826
- "kind": "pattern",
827
- "doClause": "Use [weak self] in closures that may be retained to prevent retain cycle memory leaks",
828
- "language": "swift",
829
- "headers": ["import Foundation"],
830
- "category": "Tool",
831
- "knowledgeType": "solution",
832
- "usageGuide": "### 使用场景\n遇到 Swift 闭包中的 self 引用时,触发 `@swift-retain-cycle` 检查是否需要 weak capture。",
833
- "difficulty": "intermediate",
834
- "scope": "universal",
835
- "antiPattern": {
836
- "bad": "service.fetch { result in self.handle(result) }",
837
- "why": "closure 强引用 self,如果 self 也持有 closure(直接或间接),形成 retain cycle,对象永不释放",
838
- "fix": "service.fetch { [weak self] result in self?.handle(result) }"
839
- },
840
- "reasoning": {
841
- "whyStandard": "Swift 使用 ARC,闭包默认 strong capture。任何可能被持有的闭包都应使用 [weak self]",
842
- "sources": ["Memory Management Best Practices", "Apple ARC Documentation"],
843
- "confidence": 0.95
844
- }
845
- }
846
- ```
847
-
848
- **Go 示例:**
849
-
850
- ```json
851
- {
852
- "title": "[Bug] goroutine 泄漏: 未关闭的 channel 导致 goroutine 永久阻塞",
853
- "trigger": "@go-goroutine-leak",
854
- "content": {
855
- "markdown": "## Go goroutine 泄漏修复\n\n### ❌ goroutine 泄漏\n```go\nfunc fetchAll(urls []string) []string {\n\tch := make(chan string)\n\tfor _, url := range urls {\n\t\tgo func(u string) {\n\t\t\tresp, _ := http.Get(u)\n\t\t\tch <- resp.Status // 如果 fetchAll 提前返回,goroutine 永久阻塞\n\t\t}(url)\n\t}\n\t// 只读取部分结果...\n}\n```\n\n### ✅ 修复: buffered channel + context\n```go\nfunc fetchAll(ctx context.Context, urls []string) []string {\n\tch := make(chan string, len(urls)) // buffered\n\tfor _, url := range urls {\n\t\tgo func(u string) {\n\t\t\treq, _ := http.NewRequestWithContext(ctx, \"GET\", u, nil)\n\t\t\tresp, err := http.DefaultClient.Do(req)\n\t\t\tif err != nil { ch <- \"\"; return }\n\t\t\tch <- resp.Status\n\t\t}(url)\n\t}\n\tresults := make([]string, 0, len(urls))\n\tfor range urls {\n\t\tresults = append(results, <-ch)\n\t}\n\treturn results\n}\n```\n\n### 要点\n- unbuffered channel 在无接收者时阻塞发送方 goroutine\n- 用 buffered channel 或 context 取消避免泄漏",
856
- "pattern": "ch := make(chan string, len(urls)) // buffered\ngo func(u string) {\n\treq, _ := http.NewRequestWithContext(ctx, \"GET\", u, nil)\n\t...\n\tch <- resp.Status\n}(url)",
857
- "rationale": "Go goroutine 无自动回收机制,泄漏的 goroutine 会持续占用内存和 CPU。用 buffered channel + context 取消是标准解法。"
858
- },
859
- "description": "Go goroutine 泄漏修复:buffered channel + context 取消避免永久阻塞",
860
- "kind": "pattern",
861
- "doClause": "Use buffered channels and context cancellation to prevent goroutine leaks from blocking sends",
862
- "language": "go",
863
- "headers": ["import \"context\"", "import \"net/http\""],
864
- "category": "Tool",
865
- "knowledgeType": "solution",
866
- "usageGuide": "### 使用场景\n遇到 goroutine 泄漏或 channel 阻塞问题时,触发 `@go-goroutine-leak` 获取修复模式。",
867
- "difficulty": "intermediate",
868
- "scope": "universal",
869
- "antiPattern": {
870
- "bad": "ch := make(chan string)\ngo func() { ch <- result }()\n// caller 不再读取 → goroutine 永久阻塞",
871
- "why": "unbuffered channel 在无接收者时阻塞发送方 goroutine,造成泄漏",
872
- "fix": "ch := make(chan string, 1) // buffered,或用 context 取消"
873
- },
874
- "reasoning": {
875
- "whyStandard": "Go goroutine 无自动回收机制,泄漏的 goroutine 会持续占用内存和 CPU",
876
- "sources": ["Concurrency in Go", "Go Blog: Go Concurrency Patterns"],
877
- "confidence": 0.95
878
- }
879
- }
880
- ```
881
-
882
- **JavaScript 示例:**
883
-
884
- ```json
885
- {
886
- "title": "[Bug] async 函数中未 await 的 Promise 导致静默失败",
887
- "trigger": "@js-foreach-async",
888
- "content": {
889
- "markdown": "## JS forEach + async 陷阱修复\n\n### ❌ 静默失败 — 未 await\n```javascript\nasync function processItems(items) {\n items.forEach(async (item) => {\n await saveToDatabase(item); // forEach 不等待 async 回调!\n });\n console.log('Done'); // 实际上 save 还没完成\n}\n```\n\n### ✅ 修复: Promise.all + map\n```javascript\nasync function processItems(items) {\n await Promise.all(\n items.map(item => saveToDatabase(item))\n );\n console.log('Done'); // 所有 save 完成后才执行\n}\n```\n\n### 要点\n- `Array.forEach` 不处理 async 回调的返回值(Promise)\n- 导致并发不可控且错误被吞\n- 用 `Promise.all + map` 或 `for...of` 替代",
890
- "pattern": "await Promise.all(\n items.map(item => saveToDatabase(item))\n);",
891
- "rationale": "Array.forEach 不处理 async 回调的返回值(Promise),导致并发不可控且错误被吞。用 Promise.all + map 替代。"
892
- },
893
- "description": "JS forEach+async 陷阱修复:用 Promise.all + map 替代 forEach",
894
- "kind": "pattern",
895
- "doClause": "Replace forEach with Promise.all and map when iterating with async operations",
896
- "language": "javascript",
897
- "headers": [],
898
- "category": "Tool",
899
- "knowledgeType": "solution",
900
- "usageGuide": "### 使用场景\n遇到 forEach + async 组合时,触发 `@js-foreach-async` 获取正确的异步迭代模式。",
901
- "difficulty": "intermediate",
902
- "scope": "universal",
903
- "antiPattern": {
904
- "bad": "items.forEach(async (item) => { await doSomething(item); })",
905
- "why": "Array.forEach 不处理 async 回调的返回值(Promise),导致并发不可控且错误被吞",
906
- "fix": "await Promise.all(items.map(item => doSomething(item)))"
907
- },
908
- "reasoning": {
909
- "whyStandard": "forEach + async 是 JS 中最常见的异步陷阱之一,ESLint 有专门规则检测",
910
- "sources": ["MDN: Array.forEach", "ESLint: no-await-in-loop"],
911
- "confidence": 0.95
912
- }
913
- }
914
- ```
915
-
916
- **Dart (Flutter) 示例:**
917
-
918
- ```json
919
- {
920
- "title": "[Bug] BuildContext 跨越 async gap 导致引用已卸载的 Widget",
921
- "trigger": "@dart-context-async",
922
- "content": {
923
- "markdown": "## Flutter BuildContext 跨 async gap 修复\n\n### ❌ 错误: BuildContext 跨越 async gap\n```dart\nFuture<void> _handleTap(BuildContext context) async {\n final data = await fetchData();\n // ⚠️ await 后 context 可能已失效(Widget 已卸载)\n Navigator.of(context).push(...); // 可能崩溃\n ScaffoldMessenger.of(context).showSnackBar(...); // 可能崩溃\n}\n```\n\n### ✅ 修复: 在 await 前缓存所需对象\n```dart\nFuture<void> _handleTap(BuildContext context) async {\n final navigator = Navigator.of(context); // await 前缓存\n final messenger = ScaffoldMessenger.of(context);\n\n final data = await fetchData();\n\n navigator.push(...); // 安全\n messenger.showSnackBar(...); // 安全\n}\n\n// ✅ 或在 StatefulWidget 中检查 mounted\nFuture<void> _handleTap() async {\n final data = await fetchData();\n if (!mounted) return; // Widget 已卸载则退出\n Navigator.of(context).push(...);\n}\n```\n\n### 要点\n- `BuildContext` 绑定到 Widget Element,Widget 卸载后 context 失效\n- `await` 之后当前 Widget 可能已被 dispose\n- 在 `await` 前缓存 `Navigator.of(context)` 等引用,或在 `await` 后检查 `mounted`",
924
- "pattern": "final navigator = Navigator.of(context); // await 前缓存\nfinal data = await fetchData();\nnavigator.push(...); // 安全",
925
- "rationale": "Flutter 的 BuildContext 绑定到 Widget Element 生命周期,await 后 Widget 可能已卸载导致 context 失效。use_build_context_synchronously lint 规则检测此问题。"
926
- },
927
- "description": "Flutter BuildContext 跨 async gap 修复:await 前缓存或 await 后检查 mounted",
928
- "kind": "pattern",
929
- "doClause": "Cache context-dependent references before await or check mounted after await",
930
- "language": "dart",
931
- "headers": ["import 'package:flutter/material.dart';"],
932
- "category": "Tool",
933
- "knowledgeType": "solution",
934
- "usageGuide": "### 使用场景\n在 Flutter 中使用 BuildContext + async/await 时,触发 `@dart-context-async` 获取安全使用模式。",
935
- "difficulty": "intermediate",
936
- "scope": "universal",
937
- "antiPattern": {
938
- "bad": "await fetchData();\nNavigator.of(context).push(...);",
939
- "why": "await 后 Widget 可能已卸载,context 失效,导致运行时异常",
940
- "fix": "final nav = Navigator.of(context); await fetchData(); nav.push(...);"
941
- },
942
- "reasoning": {
943
- "whyStandard": "Flutter use_build_context_synchronously lint 规则;官方异步最佳实践",
944
- "sources": ["Flutter Lint: use_build_context_synchronously", "Effective Dart - Usage"],
945
- "confidence": 0.95
946
- }
947
- }
948
- ```
949
-
950
- ### 更多语言参考
951
-
952
- > 语言特有的最佳实践知识(典型模式、反模式、分析维度等)已内置于 Bootstrap 的 `languageExtension` 字段中,
953
- > 会随 Mission Briefing 自动返回,无需额外加载 Skill。
954
-
955
- ---
956
-
957
- ## Troubleshooting
958
-
959
- | 问题 | 解决 |
960
- |------|------|
961
- | 文件太多超出 context window | 减小 `maxFiles`,或先分析 high priority 文件 |
962
- | 分析维度太多一次做不完 | 分 Target 分批进行,每次分析 1-2 个 Target |
963
- | 分析质量不高 | 检查 submissionSchema 中的示例,确保字段格式严格匹配 |
964
- | Guard 违规太多 | 先处理 Guard 违规,再做知识分析 |
965
- | 提交后候选在哪里 | Dashboard → Candidates 页面审核 |
966
- | 不知道该语言的最佳实践 | Bootstrap 返回的 languageExtension 已包含语言特有知识 |
967
-
968
- ---
969
-
970
- ## MCP Tools Referenced
971
-
972
- | Tool | 用途 |
973
- |------|------|
974
- | `autosnippet_bootstrap` | 冷启动 Mission Briefing(无参数,返回项目分析 + 维度任务清单) |
975
- | `autosnippet_dimension_complete` | 维度分析完成通知(提交 recipe 后调用) |
976
- | `autosnippet_enrich_candidates` | 候选字段完整性诊断 |
977
- | `autosnippet_submit_knowledge_batch` | 批量提交候选 |
978
- | `autosnippet_submit_knowledge` | 提交单条候选(内置自动校验 + 去重检查) |
979
- | `autosnippet_search(mode=context)` | 查找已有知识(避免重复) |
980
- | `autosnippet_skill(operation=list)` | 列出可用 Skill 列表 |
981
- | `autosnippet_skill(operation=load)` | 加载指定 Skill 文档获取指引 |
982
-
983
- ## Related Skills
984
-
985
- - **autosnippet-analysis**: 语义字段补全 + 深度分析(用于增量分析)
986
- - **autosnippet-candidates**: 完整候选字段模型 + V3 Schema
987
- - **autosnippet-structure**: 项目结构发现 (targets / files / dependencies)
988
- - **autosnippet-guard**: Guard 规则详情