@chongyan/autospec 1.0.1

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 (243) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +472 -0
  3. package/README.md +476 -0
  4. package/bin/autospec.js +3 -0
  5. package/knowledge/README.md +144 -0
  6. package/knowledge/checklists/code.md +182 -0
  7. package/knowledge/checklists/design.md +196 -0
  8. package/knowledge/checklists/release.md +70 -0
  9. package/knowledge/checklists/requirement.md +169 -0
  10. package/knowledge/checklists/test.md +46 -0
  11. package/knowledge/config/README.en.md +44 -0
  12. package/knowledge/config/README.md +44 -0
  13. package/knowledge/config/role-composition.yaml +98 -0
  14. package/knowledge/config/role-extensions.yaml +140 -0
  15. package/knowledge/config/skill-compositions.yaml +142 -0
  16. package/knowledge/config/team-stage.yaml +95 -0
  17. package/knowledge/config/team-tasks.yaml +139 -0
  18. package/knowledge/config/team-triggers.yaml +198 -0
  19. package/knowledge/config/validation-patterns.yaml +137 -0
  20. package/knowledge/domain/README.md +115 -0
  21. package/knowledge/domain/flows/README.md +194 -0
  22. package/knowledge/domain/glossary.md +143 -0
  23. package/knowledge/domain/rules.md +138 -0
  24. package/knowledge/environment/README.en.md +36 -0
  25. package/knowledge/environment/README.md +87 -0
  26. package/knowledge/environment/component-knowledge.md +316 -0
  27. package/knowledge/environment/detection-patterns.yaml +502 -0
  28. package/knowledge/environment/middleware-knowledge.md +237 -0
  29. package/knowledge/environment/template-registry.md +321 -0
  30. package/knowledge/guides/domain-driven-design.md +345 -0
  31. package/knowledge/guides/knowledge-management.md +369 -0
  32. package/knowledge/guides/requirement-engineering.md +329 -0
  33. package/knowledge/guides/stages/ai-effect-evaluator.md +93 -0
  34. package/knowledge/guides/stages/code-implementer.md +205 -0
  35. package/knowledge/guides/stages/code-reviewer.md +111 -0
  36. package/knowledge/guides/stages/consistency-checker.md +177 -0
  37. package/knowledge/guides/stages/design-planner.md +401 -0
  38. package/knowledge/guides/stages/design-reviewer.md +83 -0
  39. package/knowledge/guides/stages/integration-test-runner.md +105 -0
  40. package/knowledge/guides/stages/release-checker.md +205 -0
  41. package/knowledge/guides/stages/requirement-analyzer.md +195 -0
  42. package/knowledge/guides/stages/requirement-reviewer.md +83 -0
  43. package/knowledge/guides/stages/security-reviewer.md +89 -0
  44. package/knowledge/guides/stages/test-context-analyzer.md +250 -0
  45. package/knowledge/guides/stages/test-generator.md +241 -0
  46. package/knowledge/guides/stages/test-planner.md +183 -0
  47. package/knowledge/guides/stages/test-reviewer.md +76 -0
  48. package/knowledge/guides/stages/unit-test-runner.md +83 -0
  49. package/knowledge/guides/support/ai-agent-analyzer.md +362 -0
  50. package/knowledge/guides/support/ai-anomaly-analyzer.md +213 -0
  51. package/knowledge/guides/support/ai-artifact-evaluator.md +192 -0
  52. package/knowledge/guides/support/ai-capability-analyzer.md +193 -0
  53. package/knowledge/guides/support/ai-component-analyzer.md +169 -0
  54. package/knowledge/guides/support/ai-data-validator.md +276 -0
  55. package/knowledge/guides/support/ai-evaluation-planner.md +374 -0
  56. package/knowledge/guides/support/ai-path-evaluator.md +274 -0
  57. package/knowledge/guides/support/ai-pipeline-evaluator.md +219 -0
  58. package/knowledge/guides/support/ai-rag-analyzer.md +339 -0
  59. package/knowledge/guides/support/ai-task-assessor.md +418 -0
  60. package/knowledge/guides/support/ai-test-diagnostics.md +133 -0
  61. package/knowledge/guides/support/complexity-assessor.md +268 -0
  62. package/knowledge/guides/support/component-discovery.md +183 -0
  63. package/knowledge/guides/support/environment-scanner.md +207 -0
  64. package/knowledge/guides/support/environment-validator.md +207 -0
  65. package/knowledge/guides/support/knowledge-generator.md +234 -0
  66. package/knowledge/guides/support/methodology-extractor.md +55 -0
  67. package/knowledge/guides/support/pipeline-protocol.md +438 -0
  68. package/knowledge/guides/support/practice-logger.md +359 -0
  69. package/knowledge/guides/support/scope-inference.md +174 -0
  70. package/knowledge/guides/support/skill-distiller.md +91 -0
  71. package/knowledge/guides/support/skill-updater.md +45 -0
  72. package/knowledge/guides/support/skill-validator.md +72 -0
  73. package/knowledge/guides/support/team-orchestrator.md +323 -0
  74. package/knowledge/guides/support/tech-stack-analyzer.md +139 -0
  75. package/knowledge/guides/support/test-runner.md +254 -0
  76. package/knowledge/guides/system-design.md +352 -0
  77. package/knowledge/organization/ai-native-team.md +318 -0
  78. package/knowledge/organization/team-metrics.md +228 -0
  79. package/knowledge/principles/constitution.md +134 -0
  80. package/knowledge/principles/core-principles.md +368 -0
  81. package/knowledge/principles/design-philosophy.md +877 -0
  82. package/knowledge/principles/evolution.md +553 -0
  83. package/knowledge/process/01-requirement.md +113 -0
  84. package/knowledge/process/02-design.md +123 -0
  85. package/knowledge/process/03-implementation.md +90 -0
  86. package/knowledge/process/04-review.md +80 -0
  87. package/knowledge/process/05-testing.md +90 -0
  88. package/knowledge/process/06-delivery.md +88 -0
  89. package/knowledge/process/README.en.md +38 -0
  90. package/knowledge/process/README.md +48 -0
  91. package/knowledge/process/ai-sdlc.md +475 -0
  92. package/knowledge/process/overview.md +319 -0
  93. package/knowledge/standards/code-review.md +876 -0
  94. package/knowledge/standards/coding-style.md +940 -0
  95. package/knowledge/standards/data-consistency.md +1085 -0
  96. package/knowledge/standards/document-versioning.md +210 -0
  97. package/knowledge/standards/risk-detection.md +186 -0
  98. package/knowledge/templates/ai-evaluation.md +150 -0
  99. package/knowledge/templates/api-design.md +117 -0
  100. package/knowledge/templates/database-design.md +132 -0
  101. package/knowledge/templates/domain-driven-design.md +321 -0
  102. package/knowledge/templates/product-proposal.md +201 -0
  103. package/knowledge/templates/system-design.md +227 -0
  104. package/knowledge/templates/task-breakdown.md +107 -0
  105. package/knowledge/templates/test-case.md +170 -0
  106. package/package.json +53 -0
  107. package/plugins/.claude-plugin/plugin.json +134 -0
  108. package/plugins/agents/roles/ai-engineer.md +129 -0
  109. package/plugins/agents/roles/backend-engineer.md +165 -0
  110. package/plugins/agents/roles/ceo.md +94 -0
  111. package/plugins/agents/roles/data-engineer.md +135 -0
  112. package/plugins/agents/roles/devops-engineer.md +181 -0
  113. package/plugins/agents/roles/frontend-engineer.md +129 -0
  114. package/plugins/agents/roles/product-owner.md +98 -0
  115. package/plugins/agents/roles/quality-engineer.md +129 -0
  116. package/plugins/agents/roles/security-engineer.md +180 -0
  117. package/plugins/agents/roles/tech-lead.md +97 -0
  118. package/plugins/agents/support/blind-comparator.md +88 -0
  119. package/plugins/agents/support/consistency-checker.md +103 -0
  120. package/plugins/agents/support/failure-diagnostician.md +141 -0
  121. package/plugins/agents/support/independent-reviewer.md +80 -0
  122. package/plugins/agents/support/safety-auditor.md +121 -0
  123. package/plugins/agents/support/skill-benchmarker.md +86 -0
  124. package/plugins/agents/support/skill-forger.md +105 -0
  125. package/plugins/agents/support/stage-gate-evaluator.md +121 -0
  126. package/plugins/agents/support/test-coverage-reviewer.md +73 -0
  127. package/plugins/benchmarks/templates/README.md +44 -0
  128. package/plugins/benchmarks/templates/commands/explore-template.yaml +48 -0
  129. package/plugins/benchmarks/templates/pipeline/agile-template.yaml +84 -0
  130. package/plugins/benchmarks/templates/pipeline/waterfall-template.yaml +106 -0
  131. package/plugins/benchmarks/templates/skills/requirement-analyzer-template.yaml +48 -0
  132. package/plugins/commands/README.en.md +96 -0
  133. package/plugins/commands/README.md +96 -0
  134. package/plugins/commands/apply.md +191 -0
  135. package/plugins/commands/archive.md +76 -0
  136. package/plugins/commands/env-export.md +79 -0
  137. package/plugins/commands/env-sync.md +640 -0
  138. package/plugins/commands/env-template.md +223 -0
  139. package/plugins/commands/env-update.md +264 -0
  140. package/plugins/commands/env-validate.md +176 -0
  141. package/plugins/commands/env.md +79 -0
  142. package/plugins/commands/explore.md +76 -0
  143. package/plugins/commands/field-evolve.md +536 -0
  144. package/plugins/commands/memory.md +249 -0
  145. package/plugins/commands/project-evolve.md +821 -0
  146. package/plugins/commands/propose.md +93 -0
  147. package/plugins/commands/review.md +140 -0
  148. package/plugins/commands/run.md +224 -0
  149. package/plugins/commands/status.md +62 -0
  150. package/plugins/commands/validate.md +108 -0
  151. package/plugins/hooks/README.en.md +56 -0
  152. package/plugins/hooks/README.md +56 -0
  153. package/plugins/hooks/ai-project-guard.js +329 -0
  154. package/plugins/hooks/artifact-evaluation-hook.js +237 -0
  155. package/plugins/hooks/constitution-guard.js +211 -0
  156. package/plugins/hooks/environment-autocommit.js +264 -0
  157. package/plugins/hooks/environment-manager.js +778 -0
  158. package/plugins/hooks/execution-tracker.js +354 -0
  159. package/plugins/hooks/frozen-zone-guard.js +140 -0
  160. package/plugins/hooks/layer1-validator.js +423 -0
  161. package/plugins/hooks/lib/artifact-evaluator.js +414 -0
  162. package/plugins/hooks/lib/benchmarks/change-detector.js +390 -0
  163. package/plugins/hooks/lib/benchmarks/evaluator.js +605 -0
  164. package/plugins/hooks/lib/benchmarks/integration-example.js +169 -0
  165. package/plugins/hooks/lib/data-and-ai-detector.js +275 -0
  166. package/plugins/hooks/lib/detection-pattern-loader.js +865 -0
  167. package/plugins/hooks/lib/directory-discovery.js +395 -0
  168. package/plugins/hooks/lib/environment-config-loader.js +341 -0
  169. package/plugins/hooks/lib/environment-detector.js +553 -0
  170. package/plugins/hooks/lib/environment-evolver.js +564 -0
  171. package/plugins/hooks/lib/environment-registry.js +813 -0
  172. package/plugins/hooks/lib/execution-path.js +427 -0
  173. package/plugins/hooks/lib/hook-error-recorder.js +245 -0
  174. package/plugins/hooks/lib/hook-logger.js +538 -0
  175. package/plugins/hooks/lib/hook-runner.js +97 -0
  176. package/plugins/hooks/lib/hook-runner.sh +44 -0
  177. package/plugins/hooks/lib/hook-state-manager.js +480 -0
  178. package/plugins/hooks/lib/memory-extractor.js +377 -0
  179. package/plugins/hooks/lib/memory-manager.js +673 -0
  180. package/plugins/hooks/lib/metrics-analyzer.js +489 -0
  181. package/plugins/hooks/lib/project-evolution/auto-fixer.js +511 -0
  182. package/plugins/hooks/lib/project-evolution/memory-manager.js +346 -0
  183. package/plugins/hooks/lib/project-evolution/pattern-detector.js +476 -0
  184. package/plugins/hooks/lib/project-evolution/semantic-indexer.js +480 -0
  185. package/plugins/hooks/lib/project-structure-detector.js +326 -0
  186. package/plugins/hooks/lib/rollback-tracker.js +346 -0
  187. package/plugins/hooks/lib/source-code-scanner.js +596 -0
  188. package/plugins/hooks/lib/technology-stack-detector.js +374 -0
  189. package/plugins/hooks/lib/test-failure-analyzer.js +375 -0
  190. package/plugins/hooks/lib/test-failure-fixer.js +268 -0
  191. package/plugins/hooks/lib/trace-context.js +277 -0
  192. package/plugins/hooks/lib/validation-patterns.js +415 -0
  193. package/plugins/hooks/memory-sync.js +171 -0
  194. package/plugins/hooks/pipeline-observer.js +413 -0
  195. package/plugins/hooks/scope-sentinel.js +204 -0
  196. package/plugins/hooks/trace-initialization.js +169 -0
  197. package/plugins/memory/templates/code-quality.yaml +149 -0
  198. package/plugins/memory/templates/multi-system.yaml +155 -0
  199. package/plugins/memory/templates/team-habits.yaml +119 -0
  200. package/plugins/memory/templates/testing.yaml +121 -0
  201. package/plugins/skills/README.en.md +47 -0
  202. package/plugins/skills/README.md +104 -0
  203. package/plugins/skills/benchmark-executor/README.md +93 -0
  204. package/plugins/skills/benchmark-executor/SKILL.md +647 -0
  205. package/plugins/skills/benchmark-generator/SKILL.md +349 -0
  206. package/plugins/skills/delivery-stage/SKILL.md +203 -0
  207. package/plugins/skills/design-stage/SKILL.md +216 -0
  208. package/plugins/skills/evolution-process/SKILL.md +291 -0
  209. package/plugins/skills/exploration-phase/SKILL.md +133 -0
  210. package/plugins/skills/implementation-stage/SKILL.md +179 -0
  211. package/plugins/skills/layer1-validation/SKILL.md +79 -0
  212. package/plugins/skills/pending-dashboard/SKILL.md +109 -0
  213. package/plugins/skills/project-evolution/SKILL.md +847 -0
  214. package/plugins/skills/requirement-stage/SKILL.md +183 -0
  215. package/plugins/skills/skill-forge/SKILL.md +223 -0
  216. package/plugins/skills/skill-forge/references/description-guide.md +92 -0
  217. package/plugins/skills/skill-forge/references/quality-rubric.md +104 -0
  218. package/plugins/skills/skill-forge/references/skill-template.md +106 -0
  219. package/plugins/skills/startup-guard/SKILL.md +38 -0
  220. package/plugins/skills/testing-stage/SKILL.md +195 -0
  221. package/scripts/cli/global-init.js +288 -0
  222. package/scripts/cli/global.js +324 -0
  223. package/scripts/cli/index.js +55 -0
  224. package/scripts/cli/init.js +382 -0
  225. package/scripts/cli/list.js +69 -0
  226. package/scripts/cli/org.js +340 -0
  227. package/scripts/cli/update.js +44 -0
  228. package/scripts/config/commands.config.js +145 -0
  229. package/scripts/config/hooks.config.js +197 -0
  230. package/scripts/evolution/evolution-router.js +273 -0
  231. package/scripts/evolution/evolution-signal-collector.js +307 -0
  232. package/scripts/evolution/knowledge-loader.js +346 -0
  233. package/scripts/evolution/marketplace.js +317 -0
  234. package/scripts/evolution/version-manager.js +371 -0
  235. package/scripts/install/agents.js +106 -0
  236. package/scripts/install/commands.js +133 -0
  237. package/scripts/install/constants.js +424 -0
  238. package/scripts/install/hook-logger.js +536 -0
  239. package/scripts/install/hooks.js +110 -0
  240. package/scripts/install/index.js +39 -0
  241. package/scripts/install/skills.js +95 -0
  242. package/scripts/postinstall.js +25 -0
  243. package/scripts/state.js +376 -0
@@ -0,0 +1,480 @@
1
+ /**
2
+ * Project-Evolve Semantic Indexer
3
+ * 语义索引器 - 负责代码语义向量生成、相似度计算、语义搜索
4
+ */
5
+
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const crypto = require('crypto');
9
+
10
+ class SemanticIndexer {
11
+ constructor(projectRoot) {
12
+ this.projectRoot = projectRoot;
13
+ this.indexPath = path.join(projectRoot, '.autospec', 'memory', 'embeddings');
14
+ this.index = new Map();
15
+ }
16
+
17
+ /**
18
+ * 初始化索引
19
+ */
20
+ init() {
21
+ if (!fs.existsSync(this.indexPath)) {
22
+ fs.mkdirSync(this.indexPath, { recursive: true });
23
+ }
24
+
25
+ this.loadIndex();
26
+ return this;
27
+ }
28
+
29
+ /**
30
+ * 加载索引
31
+ */
32
+ loadIndex() {
33
+ const indexFile = path.join(this.indexPath, 'index.json');
34
+
35
+ if (fs.existsSync(indexFile)) {
36
+ const data = JSON.parse(fs.readFileSync(indexFile, 'utf8'));
37
+
38
+ for (const [key, value] of Object.entries(data)) {
39
+ this.index.set(key, value);
40
+ }
41
+ }
42
+ }
43
+
44
+ /**
45
+ * 保存索引
46
+ */
47
+ saveIndex() {
48
+ const indexFile = path.join(this.indexPath, 'index.json');
49
+ const data = Object.fromEntries(this.index);
50
+ fs.writeFileSync(indexFile, JSON.stringify(data, null, 2));
51
+ }
52
+
53
+ /**
54
+ * 生成代码语义向量(简化版)
55
+ * 实际项目中应使用 CodeBERT、GraphCodeBERT 等模型
56
+ */
57
+ generateCodeEmbedding(code, options = {}) {
58
+ // 简化实现:基于代码特征的哈希向量
59
+ // 实际应调用模型API或本地模型
60
+
61
+ const features = this.extractCodeFeatures(code, options);
62
+ const embedding = this.featuresToVector(features);
63
+
64
+ return embedding;
65
+ }
66
+
67
+ /**
68
+ * 提取代码特征
69
+ */
70
+ extractCodeFeatures(code, options = {}) {
71
+ const features = {
72
+ // 结构特征
73
+ has_functions: /function\s+\w+\s*\(/.test(code),
74
+ has_classes: /class\s+\w+/.test(code),
75
+ has_async: /\basync\b/.test(code),
76
+ has_await: /\bawait\b/.test(code),
77
+ has_imports: /\bimport\b/.test(code) || /\brequire\(/.test(code),
78
+ has_exports: /\bexport\b/.test(code) || /\bmodule\.exports\b/.test(code),
79
+
80
+ // 控制流特征
81
+ has_if: /\bif\s*\(/.test(code),
82
+ has_switch: /\bswitch\s*\(/.test(code),
83
+ has_for: /\bfor\s*\(/.test(code),
84
+ has_while: /\bwhile\s*\(/.test(code),
85
+ has_try: /\btry\s*\{/.test(code),
86
+ has_catch: /\bcatch\s*\(/.test(code),
87
+
88
+ // 数据操作特征
89
+ has_map: /\.map\s*\(/.test(code),
90
+ has_filter: /\.filter\s*\(/.test(code),
91
+ has_reduce: /\.reduce\s*\(/.test(code),
92
+ has_async_map: /Promise\.all\s*\(/.test(code),
93
+
94
+ // API特征
95
+ has_http: /\b(fetch|axios|request)\b/.test(code),
96
+ has_db: /\b(find|findOne|findMany|create|update|delete)\b/.test(code),
97
+ has_cache: /\b(cache|redis|memcached)\b/.test(code),
98
+
99
+ // 错误处理特征
100
+ has_error_handling: /\b(try|catch|throw|Error)\b/.test(code),
101
+ has_logging: /\b(console\.|log|debug|info|warn|error)\b/.test(code),
102
+
103
+ // 复杂度特征
104
+ nesting_depth: this.calculateNestingDepth(code),
105
+ function_count: (code.match(/function\s+\w+/g) || []).length,
106
+ line_count: code.split('\n').length
107
+ };
108
+
109
+ return features;
110
+ }
111
+
112
+ /**
113
+ * 计算嵌套深度
114
+ */
115
+ calculateNestingDepth(code) {
116
+ let maxDepth = 0;
117
+ let currentDepth = 0;
118
+
119
+ for (const char of code) {
120
+ if (char === '{' || char === '(' || char === '[') {
121
+ currentDepth++;
122
+ maxDepth = Math.max(maxDepth, currentDepth);
123
+ } else if (char === '}' || char === ')' || char === ']') {
124
+ currentDepth--;
125
+ }
126
+ }
127
+
128
+ return maxDepth;
129
+ }
130
+
131
+ /**
132
+ * 特征转换为向量(简化版)
133
+ */
134
+ featuresToVector(features) {
135
+ // 将特征对象转换为固定维度的向量
136
+ // 实际项目中应使用模型生成的高维向量
137
+
138
+ const vector = [];
139
+ const keys = Object.keys(features).sort();
140
+
141
+ for (const key of keys) {
142
+ const value = features[key];
143
+
144
+ if (typeof value === 'boolean') {
145
+ vector.push(value ? 1 : 0);
146
+ } else if (typeof value === 'number') {
147
+ // 归一化
148
+ vector.push(Math.min(value / 100, 1));
149
+ }
150
+ }
151
+
152
+ // 填充到固定维度(简化版128维)
153
+ while (vector.length < 128) {
154
+ vector.push(0);
155
+ }
156
+
157
+ return vector.slice(0, 128);
158
+ }
159
+
160
+ /**
161
+ * 生成文本语义向量
162
+ */
163
+ generateTextEmbedding(text) {
164
+ // 简化实现:基于词频的向量
165
+ // 实际应使用 BERT、Sentence-BERT 等模型
166
+
167
+ const words = text.toLowerCase().split(/\s+/);
168
+ const wordFreq = {};
169
+
170
+ for (const word of words) {
171
+ wordFreq[word] = (wordFreq[word] || 0) + 1;
172
+ }
173
+
174
+ // 转换为固定维度向量
175
+ const vector = new Array(128).fill(0);
176
+ const keys = Object.keys(wordFreq).sort();
177
+
178
+ for (let i = 0; i < Math.min(keys.length, 128); i++) {
179
+ vector[i] = wordFreq[keys[i]] / words.length;
180
+ }
181
+
182
+ return vector;
183
+ }
184
+
185
+ /**
186
+ * 计算余弦相似度
187
+ */
188
+ cosineSimilarity(vec1, vec2) {
189
+ if (vec1.length !== vec2.length) {
190
+ throw new Error('Vectors must have same dimension');
191
+ }
192
+
193
+ let dotProduct = 0;
194
+ let norm1 = 0;
195
+ let norm2 = 0;
196
+
197
+ for (let i = 0; i < vec1.length; i++) {
198
+ dotProduct += vec1[i] * vec2[i];
199
+ norm1 += vec1[i] * vec1[i];
200
+ norm2 += vec2[i] * vec2[i];
201
+ }
202
+
203
+ if (norm1 === 0 || norm2 === 0) {
204
+ return 0;
205
+ }
206
+
207
+ return dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2));
208
+ }
209
+
210
+ /**
211
+ * 索引代码文件
212
+ */
213
+ indexCodeFile(filePath, options = {}) {
214
+ const absolutePath = path.isAbsolute(filePath)
215
+ ? filePath
216
+ : path.join(this.projectRoot, filePath);
217
+
218
+ if (!fs.existsSync(absolutePath)) {
219
+ return null;
220
+ }
221
+
222
+ const content = fs.readFileSync(absolutePath, 'utf8');
223
+ const embedding = this.generateCodeEmbedding(content, options);
224
+
225
+ const entry = {
226
+ path: filePath,
227
+ type: 'code',
228
+ embedding: embedding,
229
+ indexed_at: new Date().toISOString(),
230
+ size: content.length,
231
+ hash: this.calculateHash(content)
232
+ };
233
+
234
+ this.index.set(filePath, entry);
235
+
236
+ return entry;
237
+ }
238
+
239
+ /**
240
+ * 索引记忆
241
+ */
242
+ indexMemory(memory) {
243
+ const embedding = this.generateTextEmbedding(
244
+ `${memory.meta.name} ${memory.meta.description}`
245
+ );
246
+
247
+ const entry = {
248
+ id: memory.id,
249
+ type: 'memory',
250
+ embedding: embedding,
251
+ indexed_at: new Date().toISOString(),
252
+ category: memory.meta.category
253
+ };
254
+
255
+ this.index.set(memory.id, entry);
256
+
257
+ return entry;
258
+ }
259
+
260
+ /**
261
+ * 语义搜索
262
+ */
263
+ search(query, options = {}) {
264
+ const queryEmbedding = typeof query === 'string'
265
+ ? this.generateTextEmbedding(query)
266
+ : query;
267
+
268
+ const results = [];
269
+ const threshold = options.threshold || 0.5;
270
+ const limit = options.limit || 10;
271
+
272
+ for (const [key, entry] of this.index) {
273
+ const similarity = this.cosineSimilarity(queryEmbedding, entry.embedding);
274
+
275
+ if (similarity >= threshold) {
276
+ results.push({
277
+ key: key,
278
+ type: entry.type,
279
+ similarity: similarity,
280
+ ...entry
281
+ });
282
+ }
283
+ }
284
+
285
+ // 按相似度排序
286
+ results.sort((a, b) => b.similarity - a.similarity);
287
+
288
+ return results.slice(0, limit);
289
+ }
290
+
291
+ /**
292
+ * 查找相似代码
293
+ */
294
+ findSimilarCode(code, options = {}) {
295
+ const codeEmbedding = this.generateCodeEmbedding(code, options);
296
+ return this.search(codeEmbedding, { ...options, type: 'code' });
297
+ }
298
+
299
+ /**
300
+ * 查找相关记忆
301
+ */
302
+ findRelatedMemories(memoryId, options = {}) {
303
+ const memory = this.index.get(memoryId);
304
+
305
+ if (!memory) {
306
+ return [];
307
+ }
308
+
309
+ const results = this.search(memory.embedding, {
310
+ ...options,
311
+ type: 'memory'
312
+ });
313
+
314
+ // 排除自身
315
+ return results.filter(r => r.key !== memoryId);
316
+ }
317
+
318
+ /**
319
+ * 聚类分析
320
+ */
321
+ cluster(options = {}) {
322
+ const clusters = new Map();
323
+ const threshold = options.threshold || 0.8;
324
+
325
+ // 简单的基于相似度的聚类
326
+ for (const [key, entry] of this.index) {
327
+ let assigned = false;
328
+
329
+ for (const [clusterId, cluster] of clusters) {
330
+ const centroid = this.calculateCentroid(cluster);
331
+ const similarity = this.cosineSimilarity(entry.embedding, centroid);
332
+
333
+ if (similarity >= threshold) {
334
+ cluster.push(entry);
335
+ assigned = true;
336
+ break;
337
+ }
338
+ }
339
+
340
+ if (!assigned) {
341
+ clusters.set(key, [entry]);
342
+ }
343
+ }
344
+
345
+ return Array.from(clusters.values());
346
+ }
347
+
348
+ /**
349
+ * 计算聚类中心
350
+ */
351
+ calculateCentroid(cluster) {
352
+ const dimension = cluster[0].embedding.length;
353
+ const centroid = new Array(dimension).fill(0);
354
+
355
+ for (const entry of cluster) {
356
+ for (let i = 0; i < dimension; i++) {
357
+ centroid[i] += entry.embedding[i];
358
+ }
359
+ }
360
+
361
+ for (let i = 0; i < dimension; i++) {
362
+ centroid[i] /= cluster.length;
363
+ }
364
+
365
+ return centroid;
366
+ }
367
+
368
+ /**
369
+ * 计算哈希
370
+ */
371
+ calculateHash(content) {
372
+ return crypto.createHash('sha256').update(content).digest('hex');
373
+ }
374
+
375
+ /**
376
+ * 批量索引目录
377
+ */
378
+ indexDirectory(dirPath, options = {}) {
379
+ const patterns = options.patterns || ['**/*.js', '**/*.ts', '**/*.jsx', '**/*.tsx'];
380
+ const results = [];
381
+
382
+ // 简化实现:递归遍历目录
383
+ const files = this.listFiles(dirPath, patterns);
384
+
385
+ for (const file of files) {
386
+ try {
387
+ const entry = this.indexCodeFile(file, options);
388
+ if (entry) {
389
+ results.push(entry);
390
+ }
391
+ } catch (error) {
392
+ console.error(`Failed to index ${file}:`, error.message);
393
+ }
394
+ }
395
+
396
+ this.saveIndex();
397
+
398
+ return results;
399
+ }
400
+
401
+ /**
402
+ * 列出文件
403
+ */
404
+ listFiles(dirPath, patterns) {
405
+ const files = [];
406
+
407
+ const traverse = (currentPath) => {
408
+ const entries = fs.readdirSync(currentPath, { withFileTypes: true });
409
+
410
+ for (const entry of entries) {
411
+ const fullPath = path.join(currentPath, entry.name);
412
+ const relativePath = path.relative(this.projectRoot, fullPath);
413
+
414
+ if (entry.isDirectory()) {
415
+ // 跳过 node_modules 等目录
416
+ if (['node_modules', '.git', 'dist', 'build', 'coverage'].includes(entry.name)) {
417
+ continue;
418
+ }
419
+ traverse(fullPath);
420
+ } else if (entry.isFile()) {
421
+ // 检查是否匹配模式
422
+ if (this.matchesPatterns(relativePath, patterns)) {
423
+ files.push(relativePath);
424
+ }
425
+ }
426
+ }
427
+ };
428
+
429
+ traverse(path.join(this.projectRoot, dirPath));
430
+
431
+ return files;
432
+ }
433
+
434
+ /**
435
+ * 检查文件是否匹配模式
436
+ */
437
+ matchesPatterns(filePath, patterns) {
438
+ for (const pattern of patterns) {
439
+ // 简化实现:只支持简单的 glob 模式
440
+ const regex = new RegExp(
441
+ pattern
442
+ .replace(/\*\*/g, '<<<DOUBLESTAR>>>')
443
+ .replace(/\*/g, '[^/]*')
444
+ .replace(/<<<DOUBLESTAR>>>/g, '.*')
445
+ );
446
+
447
+ if (regex.test(filePath)) {
448
+ return true;
449
+ }
450
+ }
451
+
452
+ return false;
453
+ }
454
+
455
+ /**
456
+ * 获取索引统计
457
+ */
458
+ getStats() {
459
+ const stats = {
460
+ total: this.index.size,
461
+ by_type: {}
462
+ };
463
+
464
+ for (const entry of this.index.values()) {
465
+ stats.by_type[entry.type] = (stats.by_type[entry.type] || 0) + 1;
466
+ }
467
+
468
+ return stats;
469
+ }
470
+
471
+ /**
472
+ * 清除索引
473
+ */
474
+ clear() {
475
+ this.index.clear();
476
+ this.saveIndex();
477
+ }
478
+ }
479
+
480
+ module.exports = SemanticIndexer;