@metago-ai/engine 1.0.7 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,84 +5,185 @@
5
5
  *
6
6
  * 对应专利:AI 能力边界自动检测与进化方法
7
7
  * 对应协议:PROTOCOL_META_EVOLUTION_V1
8
+ * 对应技能:metago-meta-evolve
8
9
  *
9
10
  * 五阶段循环:1.边界感知 2.差距分析 3.自生成 4.验证 5.递归
10
11
  *
12
+ * 工程化实现要点:
13
+ * - 阶段一(边界感知):<10ms
14
+ * - 阶段二(差距分析):<50ms 简单 / <500ms 复杂
15
+ * - 阶段三(自生成) :<100ms 简单 / <2s 复杂,耦生度≥0.95
16
+ * - 阶段四(验证) :<50ms
17
+ * - 接入 KMWI 记忆,进化结果可溯源、可反哺
18
+ * - 自生成阶段调用 SkillGenerator 实现真正的内生生长
19
+ *
11
20
  * @author 易霄 / MetaGO Lightyear
12
- * @version 1.0.0
21
+ * @version 2.0.0
13
22
  */
14
23
  Object.defineProperty(exports, "__esModule", { value: true });
15
24
  exports.EvolutionEngine = void 0;
16
25
  const perception_1 = require("./perception");
26
+ const kmwi_memory_1 = require("./kmwi-memory");
27
+ const skill_generator_1 = require("./skill-generator");
28
+ // ============================================================================
29
+ // 进化引擎
30
+ // ============================================================================
17
31
  /**
18
32
  * 进化引擎
19
- * Evolution Engine - 实现五阶段元进化循环
33
+ *
34
+ * 实现五阶段元进化循环,每个阶段都有时间约束和耦生度约束。
35
+ * 接入 KMWI 记忆系统,进化结果可溯源、可反哺。
36
+ * 自生成阶段调用 SkillGenerator 实现真正的内生生长(非模板字符串)。
20
37
  */
21
38
  class EvolutionEngine {
22
- constructor(version = '1.0.0') {
39
+ constructor(version = '1.0.0', kmwi, skillGenerator) {
23
40
  this.evolutionHistory = [];
24
41
  this.maxRecursionDepth = 3;
42
+ this.minCouplingScore = 0.95;
43
+ // 时间预算(毫秒),对应 SKILL.md 施工蓝图
44
+ this.TIME_BUDGETS = {
45
+ PERCEPTION: 10,
46
+ GAP_ANALYSIS_SIMPLE: 50,
47
+ GAP_ANALYSIS_COMPLEX: 500,
48
+ SELF_GENERATION_SIMPLE: 100,
49
+ SELF_GENERATION_COMPLEX: 2000,
50
+ VALIDATION: 50,
51
+ };
25
52
  this.perception = new perception_1.Perception();
53
+ this.kmwi = kmwi || new kmwi_memory_1.KMWIMemory();
54
+ this.skillGenerator = skillGenerator || new skill_generator_1.SkillGenerator(this.kmwi);
26
55
  this.currentVersion = version;
27
56
  }
57
+ // ============================================================================
58
+ // 元进化主循环
59
+ // ============================================================================
28
60
  /**
29
61
  * 触发元进化
30
- * Trigger meta-evolution
62
+ * 五阶段循环:边界感知 → 差距分析 → 自生成 → 验证 → 递归
31
63
  */
32
64
  async evolve(context) {
33
- // 阶段 1:边界感知
65
+ const timing = [];
66
+ const errors = [];
67
+ // ========== 阶段 1:边界感知(<10ms) ==========
68
+ const t1Start = Date.now();
34
69
  const boundary = this.perception.detectBoundary(context);
70
+ const t1Duration = Date.now() - t1Start;
71
+ timing.push({
72
+ stage: 'PERCEPTION',
73
+ durationMs: t1Duration,
74
+ budgetMs: this.TIME_BUDGETS.PERCEPTION,
75
+ withinBudget: t1Duration <= this.TIME_BUDGETS.PERCEPTION,
76
+ });
35
77
  if (!boundary) {
36
- return {
78
+ return this.buildResult({
37
79
  success: true,
38
80
  stage: 'PERCEPTION',
39
81
  errors: ['No boundary detected, no evolution needed'],
40
- timestamp: new Date().toISOString(),
41
- };
82
+ timing,
83
+ couplingScore: 1.0,
84
+ kmwiRecorded: false,
85
+ });
42
86
  }
43
- // 阶段 2:差距分析
87
+ // ========== 阶段 2:差距分析(<50ms 简单 / <500ms 复杂) ==========
88
+ const t2Start = Date.now();
44
89
  const gaps = this.analyzeGap(boundary);
45
- // 阶段 3:自生成
46
- const solutions = this.selfGenerate(gaps);
47
- // 阶段 4:验证
90
+ const isComplex = gaps.length > 2 || gaps.some(g => g.severity === 'critical');
91
+ const t2Duration = Date.now() - t2Start;
92
+ const t2Budget = isComplex ? this.TIME_BUDGETS.GAP_ANALYSIS_COMPLEX : this.TIME_BUDGETS.GAP_ANALYSIS_SIMPLE;
93
+ timing.push({
94
+ stage: 'GAP_ANALYSIS',
95
+ durationMs: t2Duration,
96
+ budgetMs: t2Budget,
97
+ withinBudget: t2Duration <= t2Budget,
98
+ });
99
+ if (gaps.length === 0) {
100
+ return this.buildResult({
101
+ success: true,
102
+ stage: 'GAP_ANALYSIS',
103
+ boundary,
104
+ errors: ['No gaps identified despite boundary detection'],
105
+ timing,
106
+ couplingScore: 1.0,
107
+ kmwiRecorded: false,
108
+ });
109
+ }
110
+ // ========== 阶段 3:自生成(<100ms 简单 / <2s 复杂) ==========
111
+ const t3Start = Date.now();
112
+ const solutions = await this.selfGenerate(gaps);
113
+ const t3Duration = Date.now() - t3Start;
114
+ const t3Budget = isComplex ? this.TIME_BUDGETS.SELF_GENERATION_COMPLEX : this.TIME_BUDGETS.SELF_GENERATION_SIMPLE;
115
+ timing.push({
116
+ stage: 'SELF_GENERATION',
117
+ durationMs: t3Duration,
118
+ budgetMs: t3Budget,
119
+ withinBudget: t3Duration <= t3Budget,
120
+ });
121
+ if (solutions.length === 0) {
122
+ errors.push('Self-generation produced no solutions');
123
+ return this.buildResult({
124
+ success: false,
125
+ stage: 'SELF_GENERATION',
126
+ boundary,
127
+ gaps,
128
+ errors,
129
+ timing,
130
+ couplingScore: 0,
131
+ kmwiRecorded: false,
132
+ });
133
+ }
134
+ // ========== 阶段 4:验证(<50ms) ==========
135
+ const t4Start = Date.now();
48
136
  const validated = this.validate(solutions);
49
- // 阶段 5:递归(如果有未通过的解决方案)
137
+ const t4Duration = Date.now() - t4Start;
138
+ timing.push({
139
+ stage: 'VALIDATION',
140
+ durationMs: t4Duration,
141
+ budgetMs: this.TIME_BUDGETS.VALIDATION,
142
+ withinBudget: t4Duration <= this.TIME_BUDGETS.VALIDATION,
143
+ });
144
+ // ========== 阶段 5:递归 ==========
50
145
  let finalResult;
51
146
  if (validated.failed.length > 0 && this.evolutionHistory.length < this.maxRecursionDepth) {
52
- this.evolutionHistory.push({
147
+ // 记录当前轮次,递归调用
148
+ this.evolutionHistory.push(this.buildResult({
53
149
  success: false,
54
150
  stage: 'RECURSION',
55
151
  boundary,
56
152
  gaps,
57
153
  solutions: validated.failed,
58
154
  errors: ['Some solutions failed validation, recursing'],
59
- timestamp: new Date().toISOString(),
60
- });
61
- // 递归调用
155
+ timing,
156
+ couplingScore: this.computeOverallCoupling(validated.failed),
157
+ kmwiRecorded: false,
158
+ }));
62
159
  finalResult = await this.evolve(context);
63
160
  }
64
161
  else {
65
162
  // 固化通过验证的解决方案
66
163
  const newVersion = this.recurse(validated.passed);
67
- finalResult = {
164
+ const overallCoupling = this.computeOverallCoupling(validated.passed);
165
+ finalResult = this.buildResult({
68
166
  success: validated.failed.length === 0,
69
167
  stage: 'RECURSION',
70
168
  boundary,
71
169
  gaps,
72
170
  solutions: validated.passed,
73
171
  newVersion,
74
- errors: validated.failed.map(f => `Validation failed: ${f.name}`),
75
- timestamp: new Date().toISOString(),
76
- };
172
+ errors: validated.failed.map(f => `Validation failed: ${f.name} (coupling=${f.couplingScore.toFixed(3)})`),
173
+ timing,
174
+ couplingScore: overallCoupling,
175
+ kmwiRecorded: false,
176
+ });
77
177
  }
78
178
  // 元元进化监控
79
179
  finalResult.metaMetaEvolution = this.metaMetaEvolution(finalResult);
180
+ // 记录到 KMWI 记忆
181
+ finalResult.kmwiRecorded = this.recordToKMWI(finalResult);
80
182
  return finalResult;
81
183
  }
82
- /**
83
- * 阶段 2:差距分析
84
- * Stage 2: Gap Analysis
85
- */
184
+ // ============================================================================
185
+ // 阶段 2:差距分析
186
+ // ============================================================================
86
187
  analyzeGap(boundary) {
87
188
  const gaps = [];
88
189
  switch (boundary.type) {
@@ -93,6 +194,7 @@ class EvolutionEngine {
93
194
  missingCapability: 'Task execution capability',
94
195
  requiredSkill: 'metago-holistic-task',
95
196
  severity: 'high',
197
+ domain: this.extractDomain(boundary.message, boundary.context?.task),
96
198
  });
97
199
  break;
98
200
  case perception_1.BoundaryType.CAPABILITY_GAP:
@@ -101,6 +203,7 @@ class EvolutionEngine {
101
203
  description: `Capability gap detected: ${boundary.message}`,
102
204
  missingCapability: 'Missing skill or tool',
103
205
  severity: boundary.severity,
206
+ domain: this.extractDomain(boundary.message),
104
207
  });
105
208
  break;
106
209
  case perception_1.BoundaryType.USER_FEEDBACK:
@@ -109,6 +212,7 @@ class EvolutionEngine {
109
212
  description: `User feedback indicates gap: ${boundary.message}`,
110
213
  missingCapability: 'User-expectation alignment',
111
214
  severity: 'medium',
215
+ domain: this.extractDomain(boundary.message, boundary.context?.feedback),
112
216
  });
113
217
  break;
114
218
  case perception_1.BoundaryType.VERSION_OUTDATED:
@@ -117,59 +221,153 @@ class EvolutionEngine {
117
221
  description: `Engine version outdated: ${boundary.message}`,
118
222
  missingCapability: 'Version upgrade',
119
223
  severity: 'low',
224
+ domain: 'version-management',
120
225
  });
121
226
  break;
122
227
  }
123
228
  return gaps;
124
229
  }
125
230
  /**
126
- * 阶段 3:自生成
127
- * Stage 3: Self-Generation
231
+ * 从消息中提取问题域关键词
128
232
  */
129
- selfGenerate(gaps) {
130
- return gaps.map(gap => {
131
- let type = 'skill';
132
- if (gap.requiredProtocol)
133
- type = 'protocol';
134
- else if (gap.requiredSkill)
135
- type = 'skill';
233
+ extractDomain(...texts) {
234
+ const combined = texts.filter(Boolean).join(' ').toLowerCase();
235
+ // 提取关键词:去除常见停用词,取前 3 个有意义的词
236
+ const stopwords = new Set(['the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'to', 'of', 'in', 'on', 'at', 'for', 'with', 'and', 'or', 'not', 'failed', 'error', 'task']);
237
+ const words = combined.split(/[^a-z\u4e00-\u9fa5]+/).filter(w => w.length > 2 && !stopwords.has(w));
238
+ return words.slice(0, 3).join('-') || 'general';
239
+ }
240
+ // ============================================================================
241
+ // 阶段 3:自生成(真正的内生生长,非模板字符串)
242
+ // ============================================================================
243
+ async selfGenerate(gaps) {
244
+ const solutions = [];
245
+ for (const gap of gaps) {
246
+ // 优先尝试通过 SkillGenerator 生成(真正的内生生长)
247
+ const skillSolution = await this.generateViaSkillGenerator(gap);
248
+ if (skillSolution) {
249
+ solutions.push(skillSolution);
250
+ continue;
251
+ }
252
+ // 降级:通过 KMWI 模式匹配生成
253
+ const patternSolution = this.generateViaKMWIPattern(gap);
254
+ if (patternSolution) {
255
+ solutions.push(patternSolution);
256
+ continue;
257
+ }
258
+ // 最终降级:模板生成(带耦生度约束)
259
+ solutions.push(this.generateViaTemplate(gap));
260
+ }
261
+ return solutions;
262
+ }
263
+ /**
264
+ * 通过 SkillGenerator 生成(A5 内生公理:从内部生长)
265
+ */
266
+ async generateViaSkillGenerator(gap) {
267
+ try {
268
+ const creationResult = await this.skillGenerator.create(gap.domain, {
269
+ failure: gap.description,
270
+ });
271
+ if (!creationResult.success) {
272
+ return null;
273
+ }
136
274
  return {
137
275
  id: `SOL-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
138
- type,
139
- name: gap.requiredSkill || `Generated-${gap.id}`,
140
- description: gap.description,
141
- draft: this.generateDraft(gap, type),
276
+ type: 'skill',
277
+ name: creationResult.skillName,
278
+ description: `Generated by SkillGenerator for: ${gap.description}`,
279
+ draft: creationResult.skillContent,
142
280
  validated: false,
281
+ couplingScore: creationResult.couplingScore,
282
+ source: 'skill_generator',
283
+ provenance: creationResult.provenance,
143
284
  };
144
- });
285
+ }
286
+ catch {
287
+ // SkillGenerator 失败不阻塞,降级到其他方式
288
+ return null;
289
+ }
290
+ }
291
+ /**
292
+ * 通过 KMWI 模式匹配生成
293
+ */
294
+ generateViaKMWIPattern(gap) {
295
+ const { wisdom, intuitions } = this.kmwi.extractPatternsForEvolution(gap.domain, 3);
296
+ if (wisdom.length === 0 && intuitions.length === 0) {
297
+ return null;
298
+ }
299
+ // 基于现有智慧模式构建解决方案
300
+ const patterns = wisdom.map(w => `- ${w.pattern}: ${w.description} (success=${(w.successRate * 100).toFixed(0)}%)`);
301
+ const insights = intuitions.map(i => `- ${i.insight} (accuracy=${(i.accuracy * 100).toFixed(0)}%)`);
302
+ const draft = `# Solution for: ${gap.description}\n\n## Patterns from KMWI\n${patterns.join('\n')}\n\n## Intuitions\n${insights.join('\n')}\n\n## Applied Strategy\nCombine above patterns to address: ${gap.missingCapability}`;
303
+ // 耦生度:基于模式成功率
304
+ const avgSuccess = wisdom.length > 0
305
+ ? wisdom.reduce((sum, w) => sum + w.successRate, 0) / wisdom.length
306
+ : 0.85;
307
+ const avgAccuracy = intuitions.length > 0
308
+ ? intuitions.reduce((sum, i) => sum + i.accuracy, 0) / intuitions.length
309
+ : 0.85;
310
+ const couplingScore = Math.min(1, avgSuccess * 0.6 + avgAccuracy * 0.4);
311
+ return {
312
+ id: `SOL-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
313
+ type: 'protocol',
314
+ name: `kmwi-pattern-${gap.domain}`,
315
+ description: `Synthesized from ${wisdom.length} wisdom patterns and ${intuitions.length} intuitions`,
316
+ draft,
317
+ validated: false,
318
+ couplingScore,
319
+ source: 'kmwi_pattern',
320
+ provenance: [
321
+ `[KMWI] Extracted ${wisdom.length} patterns from W layer`,
322
+ `[KMWI] Extracted ${intuitions.length} insights from I layer`,
323
+ `[SYNTHESIS] Combined with coupling=${couplingScore.toFixed(3)}`,
324
+ ],
325
+ };
145
326
  }
146
327
  /**
147
- * 生成解决方案草稿
328
+ * 模板生成(最终降级,仍带耦生度约束)
148
329
  */
149
- generateDraft(gap, type) {
330
+ generateViaTemplate(gap) {
331
+ const type = gap.requiredProtocol ? 'protocol' : 'skill';
150
332
  const templates = {
151
333
  skill: `# Skill: ${gap.requiredSkill || 'New Skill'}\n\n## Description\n${gap.description}\n\n## Triggers\n- When ${gap.missingCapability} is needed\n\n## Steps\n1. Detect gap\n2. Analyze\n3. Generate\n4. Validate\n5. Apply`,
152
334
  protocol: `# Protocol: ${gap.requiredProtocol || 'New Protocol'}\n\n## Purpose\n${gap.description}\n\n## Triggers\n- When ${gap.missingCapability} is needed\n\n## Rules\n1. Detect\n2. Analyze\n3. Execute\n4. Verify`,
153
335
  validator: `// Validator for ${gap.missingCapability}\nexport function validate(output: string): boolean {\n // TODO: Implement validation logic\n return true;\n}`,
154
336
  engine: `// Engine: ${gap.missingCapability}\nexport class GeneratedEngine {\n // TODO: Implement engine logic\n}`,
155
337
  };
156
- return templates[type] || templates.skill;
338
+ // 模板生成的耦生度较低(0.85),需要通过后续验证
339
+ return {
340
+ id: `SOL-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
341
+ type,
342
+ name: gap.requiredSkill || `Generated-${gap.id}`,
343
+ description: gap.description,
344
+ draft: templates[type] || templates.skill,
345
+ validated: false,
346
+ couplingScore: 0.85,
347
+ source: 'template',
348
+ provenance: [`[TEMPLATE] Generated from template (fallback mode)`],
349
+ };
157
350
  }
158
- /**
159
- * 阶段 4:验证
160
- * Stage 4: Validation
161
- */
351
+ // ============================================================================
352
+ // 阶段 4:验证(强化版,不只是关键词检查)
353
+ // ============================================================================
162
354
  validate(solutions) {
163
355
  const passed = [];
164
356
  const failed = [];
165
357
  for (const solution of solutions) {
166
- // 检查是否违反现有公理
167
- const violatesAxioms = this.checkAxiomViolation(solution);
168
- // 检查是否有安全漏洞
169
- const hasSecurityIssue = this.checkSecurity(solution);
170
- // 检查格式是否正确
171
- const hasValidFormat = this.checkFormat(solution);
172
- if (!violatesAxioms && !hasSecurityIssue && hasValidFormat) {
358
+ const checks = {
359
+ axiomCompliance: this.checkAxiomViolation(solution),
360
+ security: this.checkSecurity(solution),
361
+ format: this.checkFormat(solution),
362
+ coupling: solution.couplingScore >= this.minCouplingScore,
363
+ completeness: this.checkCompleteness(solution),
364
+ };
365
+ const allPassed = checks.axiomCompliance === false
366
+ && checks.security === false
367
+ && checks.format === true
368
+ && checks.coupling === true
369
+ && checks.completeness === true;
370
+ if (allPassed) {
173
371
  solution.validated = true;
174
372
  passed.push(solution);
175
373
  }
@@ -180,75 +378,189 @@ class EvolutionEngine {
180
378
  return { passed, failed };
181
379
  }
182
380
  /**
183
- * 阶段 5:递归
184
- * Stage 5: Recursion
185
- */
186
- recurse(passedSolutions) {
187
- if (passedSolutions.length === 0)
188
- return undefined;
189
- // 版本升级规则
190
- const [major, minor, patch] = this.currentVersion.split('.').map(Number);
191
- const newVersion = `${major}.${minor + 1}.${patch}`;
192
- this.currentVersion = newVersion;
193
- return newVersion;
194
- }
195
- /**
196
- * 检查是否违反公理
381
+ * 检查是否违反公理(强化版)
197
382
  */
198
383
  checkAxiomViolation(solution) {
199
- // 检查草稿是否包含违反公理的内容
200
- const violationPatterns = ['绕过', 'bypass', '忽略公理', 'ignore axiom', '跳过验证', 'skip validation'];
201
- return violationPatterns.some(p => solution.draft.toLowerCase().includes(p.toLowerCase()));
384
+ const content = solution.draft.toLowerCase();
385
+ const violationPatterns = [
386
+ '绕过', 'bypass', '忽略公理', 'ignore axiom',
387
+ '跳过验证', 'skip validation', 'skip verify',
388
+ 'disable check', '禁用检查',
389
+ ];
390
+ return violationPatterns.some(p => content.includes(p.toLowerCase()));
202
391
  }
203
392
  /**
204
- * 检查安全问题
393
+ * 检查安全问题(强化版)
205
394
  */
206
395
  checkSecurity(solution) {
207
- const securityIssues = ['eval(', 'exec(', 'system(', 'rm -rf', 'del /f', 'format ', 'shutdown'];
208
- return securityIssues.some(s => solution.draft.toLowerCase().includes(s.toLowerCase()));
396
+ const content = solution.draft.toLowerCase();
397
+ const securityIssues = [
398
+ 'eval(', 'exec(', 'system(', 'rm -rf', 'del /f', 'format ', 'shutdown',
399
+ 'child_process', 'fs.unlink', 'fs.rmdir',
400
+ ];
401
+ return securityIssues.some(s => content.includes(s.toLowerCase()));
209
402
  }
210
403
  /**
211
- * 检查格式
404
+ * 检查格式(强化版)
212
405
  */
213
406
  checkFormat(solution) {
214
- return solution.draft.length > 50 && solution.name.length > 0;
407
+ return solution.draft.length > 50
408
+ && solution.name.length > 0
409
+ && solution.description.length > 10;
215
410
  }
216
411
  /**
217
- * 元元进化:监控进化本身
218
- * Meta-meta-evolution: Monitor the evolution itself
412
+ * 检查完整性(新增)
219
413
  */
414
+ checkCompleteness(solution) {
415
+ // 必须包含溯源链
416
+ if (solution.provenance.length === 0)
417
+ return false;
418
+ // 必须有明确的来源
419
+ if (!['template', 'skill_generator', 'kmwi_pattern'].includes(solution.source))
420
+ return false;
421
+ // SkillGenerator 生成的必须有 SKILL.md 格式
422
+ if (solution.source === 'skill_generator' && !solution.draft.includes('---'))
423
+ return false;
424
+ return true;
425
+ }
426
+ // ============================================================================
427
+ // 阶段 5:递归
428
+ // ============================================================================
429
+ recurse(passedSolutions) {
430
+ if (passedSolutions.length === 0)
431
+ return undefined;
432
+ // 版本升级规则:基于通过验证的解决方案数量决定升级幅度
433
+ const [major, minor, patch] = this.currentVersion.split('.').map(Number);
434
+ const bumpLevel = passedSolutions.length >= 3 ? 'minor' : 'patch';
435
+ const newVersion = bumpLevel === 'minor'
436
+ ? `${major}.${minor + 1}.${patch}`
437
+ : `${major}.${minor}.${patch + 1}`;
438
+ this.currentVersion = newVersion;
439
+ return newVersion;
440
+ }
441
+ // ============================================================================
442
+ // 耦生度计算
443
+ // ============================================================================
444
+ computeOverallCoupling(solutions) {
445
+ if (solutions.length === 0)
446
+ return 0;
447
+ const sum = solutions.reduce((acc, s) => acc + s.couplingScore, 0);
448
+ return sum / solutions.length;
449
+ }
450
+ // ============================================================================
451
+ // 元元进化:监控进化本身
452
+ // ============================================================================
220
453
  metaMetaEvolution(result) {
221
454
  const concerns = [];
222
- // 检查进化方向是否正确
223
- if (result.solutions && result.solutions.some(s => s.type === 'skill' && s.name.includes('delete'))) {
455
+ const recommendations = [];
456
+ // 检查进化方向是否正确(A35 创造进化律)
457
+ if (result.solutions && result.solutions.some(s => s.name.toLowerCase().includes('delete') || s.name.toLowerCase().includes('remove'))) {
224
458
  concerns.push('Evolution may be in wrong direction (deleting instead of creating)');
459
+ recommendations.push('Redirect evolution toward creation, not deletion');
225
460
  }
226
461
  // 检查是否有递归死循环
227
462
  if (this.evolutionHistory.length >= this.maxRecursionDepth) {
228
463
  concerns.push('Max recursion depth reached, possible infinite loop');
464
+ recommendations.push('Increase maxRecursionDepth or fix the root cause of repeated failures');
229
465
  }
230
466
  // 检查新能力是否违反现有公理
231
467
  if (result.errors && result.errors.length > 3) {
232
468
  concerns.push('High error count, evolution may be unstable');
469
+ recommendations.push('Review the errors and refine the self-generation algorithm');
470
+ }
471
+ // 检查时间预算
472
+ const budgetViolations = result.timing.filter(t => !t.withinBudget);
473
+ if (budgetViolations.length > 0) {
474
+ concerns.push(`Time budget exceeded in stages: ${budgetViolations.map(t => t.stage).join(', ')}`);
475
+ recommendations.push('Optimize the slow stages or relax the time budgets');
476
+ }
477
+ // 检查耦生度
478
+ if (result.couplingScore < this.minCouplingScore && result.solutions && result.solutions.length > 0) {
479
+ concerns.push(`Overall coupling score ${result.couplingScore.toFixed(3)} below threshold ${this.minCouplingScore}`);
480
+ recommendations.push('Enhance the KMWI memory to provide better patterns for self-generation');
481
+ }
482
+ // 检查 KMWI 记忆健康度
483
+ const kmwiHealth = this.kmwi.getHealth();
484
+ if (kmwiHealth.H < 60) {
485
+ concerns.push(`KMWI memory health low (H=${kmwiHealth.H}), may affect evolution quality`);
486
+ recommendations.push('Strengthen KMWI memory: ' + this.kmwi.getStrengthenSuggestions().map(s => s.action).join('; '));
233
487
  }
234
488
  return {
235
489
  monitored: true,
236
490
  evolutionValid: concerns.length === 0,
237
491
  concerns,
492
+ recommendations,
238
493
  };
239
494
  }
240
- /**
241
- * 获取进化历史
242
- */
495
+ // ============================================================================
496
+ // KMWI 记录
497
+ // ============================================================================
498
+ recordToKMWI(result) {
499
+ try {
500
+ // 记录进化事件到 M 层
501
+ this.kmwi.addMemory(`Evolution ${result.success ? 'succeeded' : 'failed'} at ${result.stage}: ${result.boundary?.message || 'no boundary'}`, `Version ${result.currentVersion || ''}, ${result.solutions?.length || 0} solutions, coupling=${result.couplingScore.toFixed(3)}`, ['evolution', result.stage.toLowerCase()], `evolution-engine:${result.timestamp}`);
502
+ // 成功的解决方案记录到 W 层(成为可复用的智慧模式)
503
+ if (result.solutions) {
504
+ for (const sol of result.solutions) {
505
+ if (sol.validated) {
506
+ this.kmwi.addWisdom(`Evolution solution: ${sol.name}`, sol.description, `Source: ${sol.source}, coupling=${sol.couplingScore.toFixed(3)}`, ['evolution', sol.type, sol.source], `evolution:${sol.id}`);
507
+ }
508
+ }
509
+ }
510
+ // 如果进化成功,更新基线
511
+ if (result.success) {
512
+ this.kmwi.refreshBaseline();
513
+ }
514
+ return true;
515
+ }
516
+ catch {
517
+ return false;
518
+ }
519
+ }
520
+ // ============================================================================
521
+ // 辅助方法
522
+ // ============================================================================
523
+ buildResult(partial) {
524
+ return {
525
+ ...partial,
526
+ currentVersion: this.currentVersion,
527
+ timestamp: new Date().toISOString(),
528
+ };
529
+ }
530
+ // ============================================================================
531
+ // 导出与统计
532
+ // ============================================================================
243
533
  getHistory() {
244
534
  return this.evolutionHistory;
245
535
  }
246
- /**
247
- * 获取当前版本
248
- */
249
536
  getVersion() {
250
537
  return this.currentVersion;
251
538
  }
539
+ getKMWI() {
540
+ return this.kmwi;
541
+ }
542
+ getSkillGenerator() {
543
+ return this.skillGenerator;
544
+ }
545
+ getSummary() {
546
+ const lines = [
547
+ '【元进化引擎报告】',
548
+ `■ 当前版本:${this.currentVersion}`,
549
+ `■ 进化历史:${this.evolutionHistory.length} 轮`,
550
+ `■ 最大递归深度:${this.maxRecursionDepth}`,
551
+ `■ 耦生度阈值:${this.minCouplingScore}`,
552
+ `■ KMWI 综合健康度:${this.kmwi.getHealth().H}`,
553
+ `■ 已生成技能数:${this.skillGenerator.getExistingSkills().length}`,
554
+ ];
555
+ const recentHistory = this.evolutionHistory.slice(-3);
556
+ if (recentHistory.length > 0) {
557
+ lines.push(`■ 最近 ${recentHistory.length} 轮进化:`);
558
+ for (const h of recentHistory) {
559
+ lines.push(` - ${h.stage}: ${h.success ? '✅' : '❌'} coupling=${h.couplingScore.toFixed(3)} solutions=${h.solutions?.length || 0}`);
560
+ }
561
+ }
562
+ return lines.join('\n');
563
+ }
252
564
  }
253
565
  exports.EvolutionEngine = EvolutionEngine;
254
566
  exports.default = EvolutionEngine;