autosnippet 3.2.17 → 3.2.20

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 (184) hide show
  1. package/README.md +73 -104
  2. package/dashboard/dist/assets/{index-CKMy5LY6.js → index-DdvZE4Yd.js} +1 -1
  3. package/dashboard/dist/index.html +1 -1
  4. package/dist/bin/cli.js +88 -49
  5. package/dist/lib/agent/AgentEventBus.js +3 -3
  6. package/dist/lib/agent/AgentFactory.d.ts +3 -3
  7. package/dist/lib/agent/AgentFactory.js +4 -4
  8. package/dist/lib/agent/AgentMessage.d.ts +8 -8
  9. package/dist/lib/agent/AgentMessage.js +8 -8
  10. package/dist/lib/agent/AgentRuntime.js +2 -2
  11. package/dist/lib/agent/AgentState.js +4 -4
  12. package/dist/lib/agent/ConversationStore.d.ts +1 -1
  13. package/dist/lib/agent/ConversationStore.js +1 -1
  14. package/dist/lib/agent/PipelineStrategy.js +1 -1
  15. package/dist/lib/agent/context/ContextWindow.d.ts +2 -2
  16. package/dist/lib/agent/context/ContextWindow.js +7 -7
  17. package/dist/lib/agent/context/ExplorationTracker.js +9 -9
  18. package/dist/lib/agent/context/exploration/PlanTracker.js +2 -2
  19. package/dist/lib/agent/context/exploration/SignalDetector.d.ts +1 -1
  20. package/dist/lib/agent/context/exploration/SignalDetector.js +1 -1
  21. package/dist/lib/agent/core/LoopContext.d.ts +21 -21
  22. package/dist/lib/agent/core/LoopContext.js +21 -21
  23. package/dist/lib/agent/core/SystemPromptBuilder.js +4 -4
  24. package/dist/lib/agent/domain/EvidenceCollector.js +5 -5
  25. package/dist/lib/agent/memory/ActiveContext.js +1 -1
  26. package/dist/lib/agent/memory/MemoryRetriever.js +1 -1
  27. package/dist/lib/agent/memory/MemoryStore.js +2 -2
  28. package/dist/lib/agent/memory/SessionStore.js +3 -3
  29. package/dist/lib/agent/policies.d.ts +1 -1
  30. package/dist/lib/agent/policies.js +1 -1
  31. package/dist/lib/agent/strategies.d.ts +1 -1
  32. package/dist/lib/agent/strategies.js +4 -4
  33. package/dist/lib/agent/tools/_shared.d.ts +1 -1
  34. package/dist/lib/agent/tools/_shared.js +1 -1
  35. package/dist/lib/agent/tools/infrastructure.js +2 -2
  36. package/dist/lib/cli/SetupService.d.ts +25 -25
  37. package/dist/lib/cli/SetupService.js +28 -15
  38. package/dist/lib/cli/deploy/FileDeployer.d.ts +9 -2
  39. package/dist/lib/cli/deploy/FileDeployer.js +139 -46
  40. package/dist/lib/cli/deploy/FileManifest.d.ts +23 -39
  41. package/dist/lib/cli/deploy/FileManifest.js +22 -27
  42. package/dist/lib/core/AstAnalyzer.d.ts +2 -2
  43. package/dist/lib/core/AstAnalyzer.js +2 -2
  44. package/dist/lib/core/analysis/CallEdgeResolver.d.ts +7 -7
  45. package/dist/lib/core/analysis/CallEdgeResolver.js +9 -9
  46. package/dist/lib/core/analysis/CallGraphAnalyzer.d.ts +4 -4
  47. package/dist/lib/core/analysis/CallGraphAnalyzer.js +2 -2
  48. package/dist/lib/core/analysis/ImportPathResolver.d.ts +0 -2
  49. package/dist/lib/core/analysis/ImportPathResolver.js +2 -4
  50. package/dist/lib/core/ast/ProjectGraph.js +7 -7
  51. package/dist/lib/core/capability/CapabilityProbe.js +6 -14
  52. package/dist/lib/domain/knowledge/UnifiedValidator.js +2 -2
  53. package/dist/lib/domain/knowledge/values/Constraints.js +4 -4
  54. package/dist/lib/domain/knowledge/values/Content.js +6 -6
  55. package/dist/lib/domain/knowledge/values/Quality.js +5 -5
  56. package/dist/lib/domain/knowledge/values/Reasoning.js +5 -5
  57. package/dist/lib/domain/knowledge/values/Relations.js +1 -1
  58. package/dist/lib/domain/knowledge/values/Stats.js +6 -6
  59. package/dist/lib/domain/task/TaskIdGenerator.d.ts +4 -4
  60. package/dist/lib/domain/task/TaskIdGenerator.js +2 -2
  61. package/dist/lib/external/lark/LarkTransport.js +4 -4
  62. package/dist/lib/external/mcp/McpServer.d.ts +3 -7
  63. package/dist/lib/external/mcp/McpServer.js +9 -13
  64. package/dist/lib/external/mcp/handlers/bootstrap/ExternalSubmissionTracker.js +5 -5
  65. package/dist/lib/external/mcp/handlers/bootstrap/MissionBriefingBuilder.js +4 -3
  66. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/BootstrapSnapshot.d.ts +3 -3
  67. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/BootstrapSnapshot.js +3 -3
  68. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/IncrementalBootstrap.d.ts +1 -1
  69. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/IncrementalBootstrap.js +1 -1
  70. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/dimension-context.js +3 -3
  71. package/dist/lib/external/mcp/handlers/bootstrap/shared/dimension-sop.js +27 -14
  72. package/dist/lib/external/mcp/handlers/bootstrap-external.js +6 -0
  73. package/dist/lib/external/mcp/handlers/dimension-complete-external.js +55 -1
  74. package/dist/lib/external/mcp/handlers/skill.js +9 -31
  75. package/dist/lib/external/mcp/handlers/system.js +2 -2
  76. package/dist/lib/external/mcp/handlers/task.js +16 -1
  77. package/dist/lib/external/mcp/tools.d.ts +12 -10
  78. package/dist/lib/external/mcp/tools.js +97 -69
  79. package/dist/lib/http/HttpServer.js +15 -2
  80. package/dist/lib/http/utils/routeHelpers.d.ts +1 -1
  81. package/dist/lib/http/utils/routeHelpers.js +1 -1
  82. package/dist/lib/http/utils/sse-sessions.d.ts +1 -1
  83. package/dist/lib/http/utils/sse-sessions.js +1 -1
  84. package/dist/lib/infrastructure/cache/CacheService.js +1 -1
  85. package/dist/lib/infrastructure/vector/AsyncPersistence.js +8 -8
  86. package/dist/lib/infrastructure/vector/BatchEmbedder.d.ts +1 -1
  87. package/dist/lib/infrastructure/vector/BatchEmbedder.js +2 -2
  88. package/dist/lib/infrastructure/vector/HnswIndex.d.ts +4 -4
  89. package/dist/lib/infrastructure/vector/HnswIndex.js +5 -5
  90. package/dist/lib/infrastructure/vector/HnswVectorAdapter.js +8 -8
  91. package/dist/lib/infrastructure/vector/ScalarQuantizer.d.ts +1 -1
  92. package/dist/lib/infrastructure/vector/ScalarQuantizer.js +4 -4
  93. package/dist/lib/infrastructure/vector/VectorStore.d.ts +1 -1
  94. package/dist/lib/infrastructure/vector/VectorStore.js +1 -1
  95. package/dist/lib/injection/ServiceContainer.d.ts +1 -1
  96. package/dist/lib/injection/ServiceContainer.js +1 -1
  97. package/dist/lib/platform/NativeUi.d.ts +1 -1
  98. package/dist/lib/platform/NativeUi.js +1 -1
  99. package/dist/lib/platform/ios/spm/DependencyGraph.d.ts +1 -1
  100. package/dist/lib/platform/ios/spm/DependencyGraph.js +1 -1
  101. package/dist/lib/platform/ios/spm/PolicyEngine.d.ts +1 -1
  102. package/dist/lib/platform/ios/spm/PolicyEngine.js +1 -1
  103. package/dist/lib/platform/ios/spm/SpmDiscoverer.js +1 -1
  104. package/dist/lib/platform/ios/spm/SpmHelper.js +3 -3
  105. package/dist/lib/platform/ios/xcode/SaveEventFilter.js +2 -2
  106. package/dist/lib/platform/ios/xcode/XcodeIntegration.js +1 -1
  107. package/dist/lib/repository/base/BaseRepository.js +1 -1
  108. package/dist/lib/repository/task/TaskRepository.impl.d.ts +2 -2
  109. package/dist/lib/repository/task/TaskRepository.impl.js +1 -1
  110. package/dist/lib/repository/token/TokenUsageStore.js +1 -1
  111. package/dist/lib/service/automation/ActionPipeline.d.ts +1 -1
  112. package/dist/lib/service/automation/ActionPipeline.js +1 -1
  113. package/dist/lib/service/bootstrap/BootstrapEventEmitter.js +2 -2
  114. package/dist/lib/service/bootstrap/BootstrapTaskManager.d.ts +1 -1
  115. package/dist/lib/service/bootstrap/BootstrapTaskManager.js +2 -2
  116. package/dist/lib/service/bootstrap/DimensionCopyRegistry.d.ts +2 -2
  117. package/dist/lib/service/bootstrap/DimensionCopyRegistry.js +2 -2
  118. package/dist/lib/service/delivery/AgentInstructionsGenerator.d.ts +6 -15
  119. package/dist/lib/service/delivery/AgentInstructionsGenerator.js +53 -189
  120. package/dist/lib/service/delivery/CursorDeliveryPipeline.d.ts +6 -16
  121. package/dist/lib/service/delivery/CursorDeliveryPipeline.js +14 -19
  122. package/dist/lib/service/delivery/KnowledgeCompressor.d.ts +1 -1
  123. package/dist/lib/service/delivery/KnowledgeCompressor.js +1 -1
  124. package/dist/lib/service/delivery/RulesGenerator.d.ts +10 -3
  125. package/dist/lib/service/delivery/RulesGenerator.js +43 -3
  126. package/dist/lib/service/delivery/SkillsSyncer.d.ts +21 -7
  127. package/dist/lib/service/delivery/SkillsSyncer.js +46 -10
  128. package/dist/lib/service/delivery/TopicClassifier.d.ts +3 -6
  129. package/dist/lib/service/delivery/TopicClassifier.js +0 -3
  130. package/dist/lib/service/guard/ExclusionManager.d.ts +1 -1
  131. package/dist/lib/service/guard/ExclusionManager.js +1 -1
  132. package/dist/lib/service/guard/GuardCheckEngine.d.ts +3 -3
  133. package/dist/lib/service/guard/GuardCheckEngine.js +5 -5
  134. package/dist/lib/service/guard/GuardCrossFileChecks.d.ts +1 -1
  135. package/dist/lib/service/guard/GuardFeedbackLoop.d.ts +3 -3
  136. package/dist/lib/service/guard/GuardFeedbackLoop.js +3 -3
  137. package/dist/lib/service/guard/GuardPatternUtils.js +1 -1
  138. package/dist/lib/service/guard/GuardService.d.ts +1 -15
  139. package/dist/lib/service/guard/GuardService.js +0 -1
  140. package/dist/lib/service/guard/RuleLearner.d.ts +1 -1
  141. package/dist/lib/service/guard/RuleLearner.js +1 -1
  142. package/dist/lib/service/knowledge/CodeEntityGraph.d.ts +3 -3
  143. package/dist/lib/service/knowledge/CodeEntityGraph.js +3 -3
  144. package/dist/lib/service/knowledge/KnowledgeService.d.ts +0 -1
  145. package/dist/lib/service/knowledge/KnowledgeService.js +0 -1
  146. package/dist/lib/service/module/ModuleService.d.ts +1 -1
  147. package/dist/lib/service/module/ModuleService.js +2 -2
  148. package/dist/lib/service/search/HybridRetriever.d.ts +2 -2
  149. package/dist/lib/service/search/HybridRetriever.js +2 -2
  150. package/dist/lib/service/search/SearchEngine.d.ts +1 -3
  151. package/dist/lib/service/search/SearchEngine.js +1 -3
  152. package/dist/lib/service/search/contextBoost.d.ts +1 -1
  153. package/dist/lib/service/skills/EventAggregator.js +2 -2
  154. package/dist/lib/service/skills/SignalCollector.js +1 -1
  155. package/dist/lib/service/snippet/codecs/VSCodeCodec.js +1 -1
  156. package/dist/lib/service/task/TaskGraphService.d.ts +0 -3
  157. package/dist/lib/service/task/TaskGraphService.js +0 -3
  158. package/dist/lib/service/task/TaskKnowledgeBridge.d.ts +8 -27
  159. package/dist/lib/service/task/TaskKnowledgeBridge.js +0 -8
  160. package/dist/lib/service/task/TaskReadyEngine.d.ts +1 -2
  161. package/dist/lib/service/task/TaskReadyEngine.js +0 -1
  162. package/dist/lib/service/wiki/WikiRenderers.js +0 -1
  163. package/dist/lib/service/wiki/WikiUtils.js +2 -7
  164. package/dist/lib/shared/PathGuard.js +6 -6
  165. package/dist/lib/shared/schemas/mcp-tools.js +84 -43
  166. package/dist/scripts/install-vscode-copilot.js +14 -4
  167. package/package.json +1 -1
  168. package/skills/autosnippet-create/SKILL.md +131 -131
  169. package/skills/autosnippet-devdocs/SKILL.md +1 -2
  170. package/skills/autosnippet-guard/SKILL.md +20 -89
  171. package/skills/autosnippet-recipes/SKILL.md +35 -117
  172. package/skills/autosnippet-structure/SKILL.md +23 -55
  173. package/templates/cursor-rules/autosnippet-skills.mdc +17 -33
  174. package/templates/instructions/agent-static.md +24 -0
  175. package/templates/instructions/conventions.md +42 -0
  176. package/skills/autosnippet-analysis/SKILL.md +0 -169
  177. package/skills/autosnippet-candidates/SKILL.md +0 -367
  178. package/skills/autosnippet-coldstart/SKILL.md +0 -988
  179. package/skills/autosnippet-concepts/SKILL.md +0 -630
  180. package/skills/autosnippet-intent/SKILL.md +0 -55
  181. package/skills/autosnippet-lifecycle/SKILL.md +0 -100
  182. package/templates/copilot-instructions.md +0 -66
  183. package/templates/cursor-rules/autosnippet-conventions.mdc +0 -172
  184. package/templates/cursor-rules/autosnippet-workflow.mdc +0 -76
@@ -8,17 +8,17 @@
8
8
  *
9
9
  * 设计原则:
10
10
  * 1. 内容来源统一 — 从 _loadEntries() 已加载的知识条目中提取
11
- * 2. 格式差异化同一数据按目标工具特性适配输出
11
+ * 2. 互补不重复.mdc 处理行为规则,Channel F 处理项目知识
12
12
  * 3. 轻量索引 — 只输出摘要和规则,详细内容引导至 MCP 工具
13
13
  * 4. 幂等生成 — 每次 deliver 重写全部文件,不做增量 diff
14
14
  */
15
15
  import fs from 'node:fs';
16
16
  import path from 'node:path';
17
+ import { TEMPLATES_DIR } from '../../shared/package-root.js';
17
18
  import { checkWriteSafety, safeWriteFile } from './FileProtection.js';
18
19
  import { estimateTokens } from './TokenBudget.js';
19
20
  /**
20
21
  * Agent 指令文件 token 预算
21
- * AGENTS.md / CLAUDE.md 不受 Cursor 200K 限制,但需控制体积以便 Agent 快速消化
22
22
  */
23
23
  const AGENT_BUDGET = Object.freeze({
24
24
  MAX_RULES: 15,
@@ -28,6 +28,10 @@ const AGENT_BUDGET = Object.freeze({
28
28
  });
29
29
  /** MCP 工具清单 — 精简版(跟随实际 MCP handler 注册名称) */
30
30
  const MCP_TOOLS_SUMMARY = [
31
+ {
32
+ name: 'autosnippet_task',
33
+ desc: 'Task & decision management: prime (CALL FIRST every message) / create/claim/close/fail/defer/progress/decompose / record_decision/revise_decision',
34
+ },
31
35
  {
32
36
  name: 'autosnippet_search',
33
37
  desc: 'Search knowledge base (mode: auto/context/keyword/semantic)',
@@ -47,13 +51,9 @@ const MCP_TOOLS_SUMMARY = [
47
51
  { name: 'autosnippet_guard', desc: 'Code compliance check (single file or batch audit)' },
48
52
  { name: 'autosnippet_structure', desc: 'Project structure discovery (targets/files/metadata)' },
49
53
  { name: 'autosnippet_graph', desc: 'Knowledge graph query (query/impact/path/stats)' },
50
- { name: 'autosnippet_skill', desc: 'Skill management (list/load/create/update/delete/suggest)' },
54
+ { name: 'autosnippet_skill', desc: 'Skill management (list/load/create/update/delete)' },
51
55
  { name: 'autosnippet_save_document', desc: 'Save development document (auto-publish)' },
52
- { name: 'autosnippet_bootstrap', desc: 'Project cold-start & scan (knowledge/refine/scan)' },
53
- {
54
- name: 'autosnippet_task',
55
- desc: 'Unified task & decision management: prime (session entry, CALL FIRST) / create/claim/close/fail/defer/progress/decompose (task CRUD) / record_decision/revise_decision/unpin_decision/list_decisions (decisions)',
56
- },
56
+ { name: 'autosnippet_bootstrap', desc: 'Project cold-start & scan' },
57
57
  { name: 'autosnippet_health', desc: 'Service health & KB statistics' },
58
58
  { name: 'autosnippet_capabilities', desc: 'List all available MCP tools (self-discovery)' },
59
59
  ];
@@ -78,15 +78,18 @@ export class AgentInstructionsGenerator {
78
78
  const startTime = Date.now();
79
79
  // 构建共享内容块
80
80
  const sections = this._buildSections({ rules, patterns, skills });
81
- // 避免 IDE 上下文重复:
82
- // - 不自动生成 CLAUDE.md(用户自己维护)
83
- // - 如果项目已有 CLAUDE.md,跳过 AGENTS.md(避免两份文件同时注入 IDE 上下文)
81
+ // AGENTS.md CLAUDE.md 互斥(双向):
82
+ // CLAUDE.md → 走 CLAUDE.md 路线(跳过 AGENTS.md)
83
+ // 否则 AGENTS.md 路线(跳过 CLAUDE.md)
84
84
  const claudePath = path.join(this.projectRoot, 'CLAUDE.md');
85
- const hasClaudeMd = fs.existsSync(claudePath);
86
- const agents = hasClaudeMd
87
- ? { filePath: path.join(this.projectRoot, 'AGENTS.md'), tokensUsed: 0, skipped: true }
85
+ const agentsPath = path.join(this.projectRoot, 'AGENTS.md');
86
+ const useClaudeMode = fs.existsSync(claudePath);
87
+ const agents = useClaudeMode
88
+ ? { filePath: agentsPath, tokensUsed: 0, skipped: true }
88
89
  : this._writeAgentsMd(sections);
89
- const claude = { filePath: claudePath, tokensUsed: 0, skipped: true }; // 不自动生成
90
+ const claude = useClaudeMode
91
+ ? this._writeClaudeMd(sections)
92
+ : { filePath: claudePath, tokensUsed: 0, skipped: true };
90
93
  const copilot = this._writeCopilotInstructions(sections);
91
94
  const duration = Date.now() - startTime;
92
95
  const allResults = [agents, claude, copilot];
@@ -114,7 +117,6 @@ export class AgentInstructionsGenerator {
114
117
  // ─── 内容构建 ──────────────────────────────────────
115
118
  /**
116
119
  * 从知识条目构建共享内容段
117
- * @private
118
120
  */
119
121
  _buildSections({ rules, patterns, skills, }) {
120
122
  // 编码规则(Channel A 格式,一行一条)
@@ -157,103 +159,64 @@ export class AgentInstructionsGenerator {
157
159
  return { ruleLines, patternRows, skillLines, toolLines };
158
160
  }
159
161
  // ─── AGENTS.md ─────────────────────────────────────
160
- /** @private */
161
162
  _writeAgentsMd(sections) {
162
163
  const lines = [
163
164
  `# ${this.projectName} — Agent Instructions`,
164
165
  '',
165
- '> Auto-generated by [AutoSnippet](https://github.com/anthropic/autosnippet). Do not edit manually.',
166
- '> This file is regenerated when the knowledge base changes.',
167
- '',
168
- '## Project Knowledge Base',
169
- '',
170
- `This project uses **AutoSnippet** as its knowledge management system.`,
171
- `The knowledge base contains coding standards, architecture patterns, and best practices`,
172
- `accessible through MCP tools.`,
166
+ '> Auto-generated by [AutoSnippet](https://github.com/GxFn/AutoSnippet). Do not edit manually.',
173
167
  '',
174
- ...this._renderConstraints(),
168
+ 'This project uses **AutoSnippet** for knowledge management.',
169
+ 'Access the knowledge base through MCP tools.',
175
170
  '',
176
171
  ];
177
172
  // Coding Standards
178
173
  if (sections.ruleLines.length > 0) {
179
- lines.push('## Coding Standards', '');
180
- lines.push(...sections.ruleLines);
181
- lines.push('');
174
+ lines.push('## Coding Standards', '', ...sections.ruleLines, '');
182
175
  }
183
176
  // Architecture Patterns
184
177
  if (sections.patternRows.length > 0) {
185
- lines.push('## Architecture Patterns', '');
186
- lines.push('| Trigger | When | Do |');
187
- lines.push('|---------|------|----|');
188
- lines.push(...sections.patternRows);
189
- lines.push('');
178
+ lines.push('## Architecture Patterns', '', '| Trigger | When | Do |', '|---------|------|----|', ...sections.patternRows, '');
190
179
  }
191
180
  // MCP Tools
192
- lines.push('## MCP Tools (AutoSnippet)', '');
193
- lines.push('Use these MCP tools to access the full knowledge base:', '');
194
- lines.push(...sections.toolLines);
195
- lines.push('');
181
+ lines.push('## MCP Tools', '', ...sections.toolLines, '');
196
182
  // Skills
197
183
  if (sections.skillLines.length > 0) {
198
- lines.push('## Available Skills', '');
199
- lines.push('Load with `autosnippet_skill({ operation: "load", name: "<skill>" })`:', '');
200
- lines.push(...sections.skillLines);
201
- lines.push('');
184
+ lines.push('## Skills', '', 'Load with `autosnippet_skill({ operation: "load", name: "<skill>" })`:', '', ...sections.skillLines, '');
202
185
  }
203
- // Workflow
204
- lines.push(...this._renderWorkflow());
186
+ // Constraints
187
+ lines.push('## Constraints', '', '1. Do NOT modify knowledge base files directly (`AutoSnippet/recipes/`, `.autosnippet/`).', '2. Prefer Recipes as project standards; source code is supplementary.', '3. Create or update knowledge only through MCP tools.', '');
205
188
  const content = `${lines.join('\n')}\n`;
206
189
  const filePath = path.join(this.projectRoot, 'AGENTS.md');
207
190
  const result = safeWriteFile(filePath, content, { logger: this.logger });
208
191
  return { filePath, tokensUsed: estimateTokens(content), skipped: !result.written };
209
192
  }
210
193
  // ─── CLAUDE.md ─────────────────────────────────────
211
- /** @private */
212
194
  _writeClaudeMd(sections) {
213
195
  const lines = [
214
196
  `# ${this.projectName} — Claude Code Instructions`,
215
197
  '',
216
198
  '> Auto-generated by AutoSnippet. Regenerated when knowledge base changes.',
217
199
  '',
200
+ 'This project uses **AutoSnippet** for knowledge management.',
201
+ 'Access the knowledge base through MCP tools.',
202
+ '',
218
203
  ];
219
- // Constraints (Claude prefers clear bullet points)
220
- lines.push(...this._renderConstraints());
221
- lines.push('');
222
204
  // Coding Standards
223
205
  if (sections.ruleLines.length > 0) {
224
- lines.push('## Coding Standards', '');
225
- lines.push('These are mandatory project rules extracted from the knowledge base:', '');
226
- lines.push(...sections.ruleLines);
227
- lines.push('');
206
+ lines.push('## Coding Standards', '', ...sections.ruleLines, '');
228
207
  }
229
- // Patterns (Claude benefits from When/Do format)
208
+ // Patterns
230
209
  if (sections.patternRows.length > 0) {
231
- lines.push('## Key Patterns', '');
232
- lines.push('| Trigger | When | Do |');
233
- lines.push('|---------|------|----|');
234
- lines.push(...sections.patternRows);
235
- lines.push('');
210
+ lines.push('## Key Patterns', '', '| Trigger | When | Do |', '|---------|------|----|', ...sections.patternRows, '');
236
211
  }
237
212
  // MCP — Claude Code natively supports MCP
238
- lines.push('## MCP Integration', '');
239
- lines.push('This project has an AutoSnippet MCP server configured. ', 'Use the following tools to access project knowledge:', '');
240
- lines.push(...sections.toolLines);
241
- lines.push('');
242
- // Key tools highlight for Claude
243
- lines.push('### Task Workflow', '');
244
- lines.push('1. **Every message → `autosnippet_task({ operation: "prime" })`** — Load decisions + tasks + knowledge context (ALWAYS FIRST)');
245
- lines.push('2. **Create task for non-trivial work** — ≥2 files OR ≥10 lines → `create` → `claim` → code → `close`');
246
- lines.push('3. **User agrees/disagrees → `autosnippet_task({ operation: "record_decision" })`** — Persist decision immediately');
247
- lines.push('4. **Before writing code**: `autosnippet_search({ query: "<topic>" })` to find relevant patterns');
248
- lines.push('5. **Complete task**: `autosnippet_task({ operation: "close", id: "<id>", reason: "..." })`');
249
- lines.push('6. **Session end**: Close or defer ALL in_progress tasks — zero in_progress on exit');
250
- lines.push('');
213
+ lines.push('## MCP Tools', '', ...sections.toolLines, '');
251
214
  // Skills
252
215
  if (sections.skillLines.length > 0) {
253
- lines.push('## Skills', '');
254
- lines.push(...sections.skillLines);
255
- lines.push('');
216
+ lines.push('## Skills', '', ...sections.skillLines, '');
256
217
  }
218
+ // Constraints
219
+ lines.push('', '## Constraints', '', '1. Do NOT modify knowledge base files directly (`AutoSnippet/recipes/`, `.autosnippet/`).', '2. Prefer Recipes as project standards; source code is supplementary.', '3. Create or update knowledge only through MCP tools.', '');
257
220
  const content = `${lines.join('\n')}\n`;
258
221
  const filePath = path.join(this.projectRoot, 'CLAUDE.md');
259
222
  const result = safeWriteFile(filePath, content, { logger: this.logger });
@@ -262,50 +225,20 @@ export class AgentInstructionsGenerator {
262
225
  // ─── copilot-instructions.md ───────────────────────
263
226
  /**
264
227
  * 动态生成 copilot-instructions.md
265
- * 替代原有的静态模板复制
266
- * @private
228
+ * 读取 templates/instructions/conventions.md + HTML markers
267
229
  */
268
- _writeCopilotInstructions(sections) {
269
- const lines = [
270
- '# AutoSnippet Copilot Instructions',
230
+ _writeCopilotInstructions(_sections) {
231
+ const body = this._loadConventionsTemplate();
232
+ const content = [
233
+ '<!-- autosnippet:begin -->',
271
234
  '',
272
- '## Project Overview',
273
- `- Project: **${this.projectName}**`,
274
- '- Knowledge System: AutoSnippet V3 (ESM, SQLite, MCP)',
275
- '- Knowledge Base: `AutoSnippet/` directory (recipes, skills, constitution)',
235
+ '# AutoSnippet Conventions',
276
236
  '',
277
- ...this._renderConstraints(),
237
+ body,
278
238
  '',
279
- ];
280
- // Coding Standards
281
- if (sections.ruleLines.length > 0) {
282
- lines.push('## Coding Standards', '');
283
- lines.push(...sections.ruleLines);
284
- lines.push('');
285
- }
286
- // MCP Tools (compact for Copilot)
287
- lines.push('## MCP Tools', '');
288
- lines.push('Access the knowledge base through MCP:', '');
289
- // Copilot: show fewer, most essential tools
290
- const essentialTools = [
291
- '- `autosnippet_search` — Search knowledge (mode: auto/context/keyword/semantic)',
292
- '- `autosnippet_knowledge` — Browse/get recipes (operation: list/get/insights)',
293
- '- `autosnippet_submit_knowledge` — Submit candidate (strict validation, all fields required)',
294
- '- `autosnippet_guard` — Code compliance check',
295
- '- `autosnippet_skill` — Load project skills (list/load)',
296
- '- `autosnippet_health` — Service health & KB stats',
297
- ];
298
- lines.push(...essentialTools);
299
- lines.push('');
300
- // Knowledge Types
301
- lines.push('## Knowledge Types', '');
302
- lines.push('- **rule** — Coding standards, enforced by Guard');
303
- lines.push('- **pattern** — Reusable code patterns and architecture');
304
- lines.push('- **fact** — Structural knowledge (relations, data flow)');
305
- lines.push('');
306
- // Workflow
307
- lines.push(...this._renderWorkflow());
308
- const content = `${lines.join('\n')}\n`;
239
+ '<!-- autosnippet:end -->',
240
+ '',
241
+ ].join('\n');
309
242
  const destDir = path.join(this.projectRoot, '.github');
310
243
  const filePath = path.join(destDir, 'copilot-instructions.md');
311
244
  const { canWrite } = checkWriteSafety(filePath);
@@ -315,83 +248,14 @@ export class AgentInstructionsGenerator {
315
248
  const result = safeWriteFile(filePath, content, { logger: this.logger });
316
249
  return { filePath, tokensUsed: estimateTokens(content), skipped: !result.written };
317
250
  }
318
- // ─── 共享模板片段 ──────────────────────────────────
319
- /**
320
- * 核心约束(所有 Agent 共享)
321
- * @private
322
- */
323
- _renderConstraints() {
324
- return [
325
- "## CRITICAL: You Operate autosnippet_task — The User Doesn't",
326
- '',
327
- 'You are the task operator. Users speak naturally; you translate to task operations.',
328
- "DO NOT tell users to call autosnippet_task. That's YOUR job.",
329
- '',
330
- '- WRONG: "You can run autosnippet_task({ operation: \'create\' }) to create a task"',
331
- '- RIGHT: *(you run create yourself and tell the user "Created task asd-42: Fix login bug")*',
332
- '',
333
- '## Task Tracking Rules (MANDATORY)',
334
- '',
335
- '1. **MUST prime on EVERY message** — `autosnippet_task({ operation: "prime" })` BEFORE anything else. No exceptions.',
336
- '2. **MUST create task for non-trivial work** — ≥2 files OR ≥10 lines → create BEFORE starting.',
337
- '3. **MUST claim before coding** — `autosnippet_task({ operation: "claim", id })` then code.',
338
- '4. **MUST close when done** — `autosnippet_task({ operation: "close", id, reason })` with meaningful reason.',
339
- '5. **MUST handle unfinished tasks first** — If prime shows in-progress, ask user: Continue, Defer, Abandon? Do NOT auto-resume.',
340
- '6. **NEVER skip prime** — Even for follow-up messages.',
341
- '7. **NEVER start new work with open in-progress tasks** — Handle existing first.',
342
- '8. **NEVER leave tasks in in_progress when session ends** — Close or defer everything.',
343
- '9. **NEVER tell the user to run task commands** — You are the operator.',
344
- '',
345
- 'When in doubt → create a task. When idle → `autosnippet_task({ operation: "ready" })`.',
346
- '',
347
- '**When NOT to create**: Quick questions, single-file trivial fixes (<10 lines), code explanation, running tests.',
348
- '',
349
- '## Knowledge Rules',
350
- '',
351
- '1. **User agrees/disagrees with a plan → `autosnippet_task({ operation: "record_decision" })` immediately** — Persist team memory first.',
352
- '2. **Do NOT modify** knowledge base files directly (`AutoSnippet/recipes/`, `.autosnippet/`).',
353
- '3. **Prefer Recipes** as project standards; source code is supplementary.',
354
- '4. Use `autosnippet_search` for knowledge retrieval; do not retry on failure in the same turn.',
355
- '5. Skills handle semantics and workflow; MCP handles capabilities — do not hardcode URLs in Skills.',
356
- ];
357
- }
251
+ // ─── 模板读取 ──────────────────────────────────────
358
252
  /**
359
- * 推荐工作流(AGENTS.md 用)
360
- * @private
253
+ * 读取 templates/instructions/conventions.md — 唯一内容源
254
+ * .mdc、copilot-instructions.md、Channel F 动态版全部从这里读取
361
255
  */
362
- _renderWorkflow() {
363
- return [
364
- '## User Says → You Run',
365
- '',
366
- '| User Says | Your Action |',
367
- '|---|---|',
368
- '| "Fix this bug" / "帮我修 bug" | `create` → `claim` → code → `close` |',
369
- '| "Implement this" / "做功能" | `create` → `claim` → code → `close` |',
370
- '| "Continue" / "继续" | resume in-progress → code → `close` |',
371
- '| "Pause" / "先不做了" | `defer(id, reason)` |',
372
- '| "Abandon" / "不做了" | `fail(id, reason)` |',
373
- '| "Break it down" / "太大了" | `decompose(id, subtasks)` |',
374
- '| "What\'s next" / "有什么要做的" | `ready()` → present list |',
375
- '| "Agreed" / "就这么定了" | `record_decision(...)` |',
376
- '| Quick question (no code) | No task. Just answer. |',
377
- '',
378
- '## Session Closing Protocol',
379
- '',
380
- 'Before ending work, you MUST complete this checklist:',
381
- '',
382
- '- [ ] Close every claimed task with reason describing what was accomplished',
383
- '- [ ] Defer any incomplete tasks with notes on why and what remains',
384
- '- [ ] Verify zero tasks in in_progress state',
385
- '- [ ] If prime showed ready tasks, mention them to the user for next session',
386
- '',
387
- '**Work is not done until all tasks are closed or deferred.**',
388
- '',
389
- '## Context Pressure',
390
- '',
391
- '- `_contextHint: CONTEXT_PRESSURE:WARNING` → Summarize completed work, then continue',
392
- '- `_contextHint: CONTEXT_PRESSURE:CRITICAL` → Call `autosnippet_task({ operation: "prime" })` immediately',
393
- '',
394
- ];
256
+ _loadConventionsTemplate() {
257
+ const tplPath = path.join(TEMPLATES_DIR, 'instructions/conventions.md');
258
+ return fs.readFileSync(tplPath, 'utf8').trimEnd();
395
259
  }
396
260
  }
397
261
  export default AgentInstructionsGenerator;
@@ -91,12 +91,15 @@ export declare class CursorDeliveryPipeline {
91
91
  };
92
92
  channelC: {
93
93
  synced: number;
94
+ builtinSynced: number;
95
+ projectSynced: number;
94
96
  skipped: number;
95
97
  errors: number;
96
98
  details: {
97
99
  synced: string[];
98
100
  skipped: string[];
99
101
  errors: string[];
102
+ builtinSynced: string[];
100
103
  };
101
104
  };
102
105
  channelD: {
@@ -155,18 +158,15 @@ export declare class CursorDeliveryPipeline {
155
158
  }>;
156
159
  /**
157
160
  * 加载知识条目(active + high-confidence pending)
158
- * @private
159
161
  */
160
162
  _loadEntries(): Promise<KnowledgeEntryProps[]>;
161
163
  /**
162
164
  * 从 KnowledgeService.list() 返回值提取条目数组
163
- * @private
164
165
  */
165
166
  _extractItems(result: unknown): KnowledgeEntryProps[];
166
167
  /**
167
168
  * 按 kind 分类知识条目
168
169
  * dev-document 类型单独分流,不进入 Channel A/B 压缩
169
- * @private
170
170
  */
171
171
  _classify(entries: KnowledgeEntryProps[]): {
172
172
  rules: KnowledgeEntryProps[];
@@ -176,17 +176,14 @@ export declare class CursorDeliveryPipeline {
176
176
  };
177
177
  /**
178
178
  * 排序 — 质量分 + 统计使用量
179
- * @private
180
179
  */
181
180
  _rank(entries: KnowledgeEntryProps[]): KnowledgeEntryProps[];
182
181
  /**
183
182
  * 计算排名分
184
- * @private
185
183
  */
186
184
  _rankScore(entry: KnowledgeEntryProps): number;
187
185
  /**
188
186
  * Channel A 生成
189
- * @private
190
187
  */
191
188
  _generateChannelA(rules: KnowledgeEntryProps[]): {
192
189
  filePath: string;
@@ -201,7 +198,6 @@ export declare class CursorDeliveryPipeline {
201
198
  * Channel B 生成(patterns + facts)
202
199
  * @param patterns kind='pattern' 的知识条目
203
200
  * @param [facts=[]] kind='fact' 的知识条目
204
- * @private
205
201
  */
206
202
  _generateChannelB(patterns: KnowledgeEntryProps[], facts?: KnowledgeEntryProps[]): {
207
203
  topicCount: number;
@@ -217,7 +213,6 @@ export declare class CursorDeliveryPipeline {
217
213
  /**
218
214
  * Channel B+ — Call Graph Architecture Rules (Phase 5.2)
219
215
  * 从调用图拓扑分析架构分层,生成 architecture smart rule
220
- * @private
221
216
  * @returns |null}
222
217
  */
223
218
  _generateCallGraphArchitectureRules(): {
@@ -227,28 +222,28 @@ export declare class CursorDeliveryPipeline {
227
222
  } | null;
228
223
  /**
229
224
  * 从文件路径中提取层级目录 (第一或第二级有意义的目录)
230
- * @private
231
225
  */
232
226
  _extractLayerDir(filePath: string): string | null;
233
227
  /**
234
228
  * Channel C 生成
235
- * @private
236
229
  */
237
230
  _generateChannelC(): Promise<{
238
231
  synced: number;
232
+ builtinSynced: number;
233
+ projectSynced: number;
239
234
  skipped: number;
240
235
  errors: number;
241
236
  details: {
242
237
  synced: string[];
243
238
  skipped: string[];
244
239
  errors: string[];
240
+ builtinSynced: string[];
245
241
  };
246
242
  }>;
247
243
  /**
248
244
  * Channel D — Dev Documents 生成
249
245
  * 将 knowledgeType='dev-document' 的条目以原始 MD 写入
250
246
  * .cursor/skills/autosnippet-devdocs/references/ 目录
251
- * @private
252
247
  */
253
248
  _generateChannelD(documents: KnowledgeEntryProps[]): {
254
249
  documentsCount: number;
@@ -258,7 +253,6 @@ export declare class CursorDeliveryPipeline {
258
253
  /**
259
254
  * Channel F — Agent Instructions 生成
260
255
  * 生成 AGENTS.md / CLAUDE.md / .github/copilot-instructions.md
261
- * @private
262
256
  */
263
257
  _generateChannelF(rules: KnowledgeEntryProps[], patterns: KnowledgeEntryProps[]): {
264
258
  filesWritten: number;
@@ -279,24 +273,20 @@ export declare class CursorDeliveryPipeline {
279
273
  };
280
274
  /**
281
275
  * 文件名安全 slug 化
282
- * @private
283
276
  */
284
277
  _slugify(text: string): string;
285
278
  /**
286
279
  * 镜像 .cursor/ 交付物料到目标 IDE 目录(Qoder / Trae 等兼容 IDE)
287
280
  * 只复制 autosnippet- 前缀的文件/目录,不触碰用户自定义内容
288
281
  * @param targetDirName 目标目录名,如 '.qoder' 或 '.trae'
289
- * @private
290
282
  */
291
283
  _mirrorToIDE(targetDirName: string): void;
292
284
  /**
293
285
  * 递归复制目录
294
- * @private
295
286
  */
296
287
  _copyDirRecursive(src: string, dest: string): void;
297
288
  /**
298
289
  * 从项目路径推断项目名称
299
- * @private
300
290
  */
301
291
  _inferProjectName(projectRoot: string): string;
302
292
  }
@@ -88,6 +88,12 @@ export class CursorDeliveryPipeline {
88
88
  // ── Channel A: Always-On Rules ──
89
89
  const channelA = this._generateChannelA(rules);
90
90
  stats.channelA = channelA;
91
+ // ── Baseline: 零知识库时注入基础引导 ──
92
+ if (entries.length === 0 && channelA.rulesCount === 0) {
93
+ const baseline = this.rulesGenerator.writeBaselineRules();
94
+ stats.channelA = { rulesCount: 0, tokensUsed: baseline.tokensUsed };
95
+ this.logger.info?.('[CursorDelivery] Baseline rules written (zero knowledge entries)');
96
+ }
91
97
  // ── Channel B: Smart Rules (by topic) + Facts ──
92
98
  const channelB = this._generateChannelB(patterns, facts);
93
99
  stats.channelB = channelB;
@@ -132,7 +138,6 @@ export class CursorDeliveryPipeline {
132
138
  // ─── 内部方法 ───────────────────────────────────────
133
139
  /**
134
140
  * 加载知识条目(active + high-confidence pending)
135
- * @private
136
141
  */
137
142
  async _loadEntries() {
138
143
  const allEntries = [];
@@ -164,7 +169,6 @@ export class CursorDeliveryPipeline {
164
169
  }
165
170
  /**
166
171
  * 从 KnowledgeService.list() 返回值提取条目数组
167
- * @private
168
172
  */
169
173
  _extractItems(result) {
170
174
  if (Array.isArray(result)) {
@@ -182,7 +186,6 @@ export class CursorDeliveryPipeline {
182
186
  /**
183
187
  * 按 kind 分类知识条目
184
188
  * dev-document 类型单独分流,不进入 Channel A/B 压缩
185
- * @private
186
189
  */
187
190
  _classify(entries) {
188
191
  const rules = [], patterns = [], facts = [], documents = [];
@@ -204,7 +207,6 @@ export class CursorDeliveryPipeline {
204
207
  }
205
208
  /**
206
209
  * 排序 — 质量分 + 统计使用量
207
- * @private
208
210
  */
209
211
  _rank(entries) {
210
212
  return [...entries].sort((a, b) => {
@@ -215,7 +217,6 @@ export class CursorDeliveryPipeline {
215
217
  }
216
218
  /**
217
219
  * 计算排名分
218
- * @private
219
220
  */
220
221
  _rankScore(entry) {
221
222
  const qual = entry.quality;
@@ -233,7 +234,6 @@ export class CursorDeliveryPipeline {
233
234
  }
234
235
  /**
235
236
  * Channel A 生成
236
- * @private
237
237
  */
238
238
  _generateChannelA(rules) {
239
239
  const topRules = this._rank(rules).slice(0, BUDGET.CHANNEL_A_MAX_RULES);
@@ -250,7 +250,6 @@ export class CursorDeliveryPipeline {
250
250
  * Channel B 生成(patterns + facts)
251
251
  * @param patterns kind='pattern' 的知识条目
252
252
  * @param [facts=[]] kind='fact' 的知识条目
253
- * @private
254
253
  */
255
254
  _generateChannelB(patterns, facts = []) {
256
255
  const result = { topicCount: 0, patternsCount: 0, factsCount: 0, totalTokens: 0, topics: {} };
@@ -304,7 +303,6 @@ export class CursorDeliveryPipeline {
304
303
  /**
305
304
  * Channel B+ — Call Graph Architecture Rules (Phase 5.2)
306
305
  * 从调用图拓扑分析架构分层,生成 architecture smart rule
307
- * @private
308
306
  * @returns |null}
309
307
  */
310
308
  _generateCallGraphArchitectureRules() {
@@ -435,7 +433,6 @@ export class CursorDeliveryPipeline {
435
433
  }
436
434
  /**
437
435
  * 从文件路径中提取层级目录 (第一或第二级有意义的目录)
438
- * @private
439
436
  */
440
437
  _extractLayerDir(filePath) {
441
438
  if (!filePath) {
@@ -453,15 +450,17 @@ export class CursorDeliveryPipeline {
453
450
  }
454
451
  /**
455
452
  * Channel C 生成
456
- * @private
457
453
  */
458
454
  async _generateChannelC() {
459
455
  try {
460
456
  const syncResult = await this.skillsSyncer.sync();
461
- this.logger.info?.(`[CursorDelivery] Channel C: ${syncResult.synced.length} synced, ` +
457
+ this.logger.info?.(`[CursorDelivery] Channel C: ${syncResult.builtinSynced.length} builtin + ` +
458
+ `${syncResult.synced.length} project synced, ` +
462
459
  `${syncResult.skipped.length} skipped, ${syncResult.errors.length} errors`);
463
460
  return {
464
- synced: syncResult.synced.length,
461
+ synced: syncResult.builtinSynced.length + syncResult.synced.length,
462
+ builtinSynced: syncResult.builtinSynced.length,
463
+ projectSynced: syncResult.synced.length,
465
464
  skipped: syncResult.skipped.length,
466
465
  errors: syncResult.errors.length,
467
466
  details: syncResult,
@@ -471,9 +470,11 @@ export class CursorDeliveryPipeline {
471
470
  this.logger.error?.(`[CursorDelivery] Channel C error: ${err.message}`);
472
471
  return {
473
472
  synced: 0,
473
+ builtinSynced: 0,
474
+ projectSynced: 0,
474
475
  skipped: 0,
475
476
  errors: 1,
476
- details: { synced: [], skipped: [], errors: [err.message] },
477
+ details: { synced: [], skipped: [], builtinSynced: [], errors: [err.message] },
477
478
  };
478
479
  }
479
480
  }
@@ -481,7 +482,6 @@ export class CursorDeliveryPipeline {
481
482
  * Channel D — Dev Documents 生成
482
483
  * 将 knowledgeType='dev-document' 的条目以原始 MD 写入
483
484
  * .cursor/skills/autosnippet-devdocs/references/ 目录
484
- * @private
485
485
  */
486
486
  _generateChannelD(documents) {
487
487
  const result = { documentsCount: 0, filesWritten: 0, filePaths: [] };
@@ -554,7 +554,6 @@ export class CursorDeliveryPipeline {
554
554
  /**
555
555
  * Channel F — Agent Instructions 生成
556
556
  * 生成 AGENTS.md / CLAUDE.md / .github/copilot-instructions.md
557
- * @private
558
557
  */
559
558
  _generateChannelF(rules, patterns) {
560
559
  try {
@@ -594,7 +593,6 @@ export class CursorDeliveryPipeline {
594
593
  }
595
594
  /**
596
595
  * 文件名安全 slug 化
597
- * @private
598
596
  */
599
597
  _slugify(text) {
600
598
  return (text
@@ -607,7 +605,6 @@ export class CursorDeliveryPipeline {
607
605
  * 镜像 .cursor/ 交付物料到目标 IDE 目录(Qoder / Trae 等兼容 IDE)
608
606
  * 只复制 autosnippet- 前缀的文件/目录,不触碰用户自定义内容
609
607
  * @param targetDirName 目标目录名,如 '.qoder' 或 '.trae'
610
- * @private
611
608
  */
612
609
  _mirrorToIDE(targetDirName) {
613
610
  try {
@@ -650,7 +647,6 @@ export class CursorDeliveryPipeline {
650
647
  }
651
648
  /**
652
649
  * 递归复制目录
653
- * @private
654
650
  */
655
651
  _copyDirRecursive(src, dest) {
656
652
  fs.mkdirSync(dest, { recursive: true });
@@ -667,7 +663,6 @@ export class CursorDeliveryPipeline {
667
663
  }
668
664
  /**
669
665
  * 从项目路径推断项目名称
670
- * @private
671
666
  */
672
667
  _inferProjectName(projectRoot) {
673
668
  return path.basename(projectRoot);
@@ -65,7 +65,7 @@ export declare class KnowledgeCompressor {
65
65
  }[];
66
66
  /**
67
67
  * 将 Fact 压缩结果格式化为 Markdown 字符串
68
- * @param {Array<{ title: string, summary: string }>} factLines
68
+ * @param factLines
69
69
  */
70
70
  formatFactLines(factLines: Array<{
71
71
  title: string;
@@ -144,7 +144,7 @@ export class KnowledgeCompressor {
144
144
  }
145
145
  /**
146
146
  * 将 Fact 压缩结果格式化为 Markdown 字符串
147
- * @param {Array<{ title: string, summary: string }>} factLines
147
+ * @param factLines
148
148
  */
149
149
  formatFactLines(factLines) {
150
150
  if (factLines.length === 0) {