@metago-ai/engine 1.0.7 → 2.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.
@@ -0,0 +1,683 @@
1
+ "use strict";
2
+ /**
3
+ * MetaGO Engine - 技能智能生成器
4
+ * Skill Generator (Meta-Creation Engine)
5
+ *
6
+ * 对应技能:metago-meta-create
7
+ * 对应公理:A5 内生公理、A35 创造进化律
8
+ * 对应属性:D40 全息创造性、D41 创造频率自适应
9
+ *
10
+ * 元创造五阶段:
11
+ * 1. 问题域感知 —— 识别这是全新问题域,确认现有能力无法覆盖
12
+ * 2. 内生种子生成 —— 从内部结构(KMWI 记忆)提取相关模式,组合形成种子
13
+ * 3. 创造生长 —— 从种子生长新能力,最小改变原则,耦生度≥0.95
14
+ * 4. 创造验证 —— 验证新能力能否解决问题,是否引入风险,边界在哪里
15
+ * 5. 创造内化 —— 内化为 SKILL.md 文件,记录溯源链,触发递归
16
+ *
17
+ * 六种创造类型:思想 / 方法论 / 算法 / 架构 / 协议 / 能力
18
+ *
19
+ * @author 易霄 / MetaGO Lightyear
20
+ * @version 1.0.0
21
+ */
22
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
23
+ if (k2 === undefined) k2 = k;
24
+ var desc = Object.getOwnPropertyDescriptor(m, k);
25
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
26
+ desc = { enumerable: true, get: function() { return m[k]; } };
27
+ }
28
+ Object.defineProperty(o, k2, desc);
29
+ }) : (function(o, m, k, k2) {
30
+ if (k2 === undefined) k2 = k;
31
+ o[k2] = m[k];
32
+ }));
33
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
34
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
35
+ }) : function(o, v) {
36
+ o["default"] = v;
37
+ });
38
+ var __importStar = (this && this.__importStar) || (function () {
39
+ var ownKeys = function(o) {
40
+ ownKeys = Object.getOwnPropertyNames || function (o) {
41
+ var ar = [];
42
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
43
+ return ar;
44
+ };
45
+ return ownKeys(o);
46
+ };
47
+ return function (mod) {
48
+ if (mod && mod.__esModule) return mod;
49
+ var result = {};
50
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
51
+ __setModuleDefault(result, mod);
52
+ return result;
53
+ };
54
+ })();
55
+ Object.defineProperty(exports, "__esModule", { value: true });
56
+ exports.SkillGenerator = void 0;
57
+ const fs = __importStar(require("fs"));
58
+ const path = __importStar(require("path"));
59
+ // ============================================================================
60
+ // 技能智能生成器
61
+ // ============================================================================
62
+ /**
63
+ * 技能智能生成器
64
+ *
65
+ * 实现元创造五阶段,从 KMWI 记忆中提取模式,内生生长出新技能。
66
+ * 生成的技能符合 agentskills.io 开放标准的 SKILL.md 格式。
67
+ */
68
+ class SkillGenerator {
69
+ constructor(kmwi, options) {
70
+ this.creationHistory = [];
71
+ this.kmwi = kmwi;
72
+ this.outputDir = options?.outputDir || path.join(process.cwd(), 'generated-skills');
73
+ this.minCouplingScore = options?.minCouplingScore ?? 0.95;
74
+ this.maxRecursionDepth = options?.maxRecursionDepth ?? 3;
75
+ this.enableFileWrite = options?.enableFileWrite ?? true;
76
+ this.existingSkills = new Set();
77
+ this.loadExistingSkills();
78
+ }
79
+ // ============================================================================
80
+ // 元创造主流程
81
+ // ============================================================================
82
+ /**
83
+ * 触发元创造
84
+ * 输入一个问题域描述,输出一个新技能
85
+ */
86
+ async create(problemDomain, context) {
87
+ const provenance = [`[0] Creation triggered for domain: ${problemDomain}`];
88
+ const errors = [];
89
+ // ========== 阶段 1:问题域感知 ==========
90
+ const perceptionResult = this.perceiveDomain(problemDomain, context);
91
+ provenance.push(`[1] Domain perceived: ${perceptionResult.description}`);
92
+ if (!perceptionResult.isNewDomain) {
93
+ return this.buildFailedResult(problemDomain, 'DOMAIN_PERCEPTION', ['Domain already covered by existing skills: ' + perceptionResult.coveragedBy.join(', ')], provenance);
94
+ }
95
+ // ========== 阶段 2:内生种子生成 ==========
96
+ const seed = this.generateSeed(perceptionResult.description);
97
+ provenance.push(`[2] Seed generated: ${seed.sourcePatterns.length} patterns, ${seed.sourceIntuitions.length} intuitions, coupling=${seed.couplingScore.toFixed(3)}`);
98
+ if (seed.couplingScore < this.minCouplingScore) {
99
+ errors.push(`Coupling score ${seed.couplingScore.toFixed(3)} below threshold ${this.minCouplingScore}`);
100
+ provenance.push(`[2-FAIL] Coupling below threshold, attempting seed refinement`);
101
+ // 尝试精炼种子:放宽提取范围
102
+ const refinedSeed = this.refineSeed(seed);
103
+ if (refinedSeed.couplingScore < this.minCouplingScore) {
104
+ return this.buildFailedResult(problemDomain, 'SEED_GENERATION', [`Cannot generate seed with coupling >= ${this.minCouplingScore} (best: ${refinedSeed.couplingScore.toFixed(3)})`], provenance);
105
+ }
106
+ Object.assign(seed, refinedSeed);
107
+ provenance.push(`[2-RETRY] Seed refined, new coupling=${seed.couplingScore.toFixed(3)}`);
108
+ }
109
+ // ========== 阶段 3:创造生长 ==========
110
+ const draft = this.growSkill(seed, problemDomain);
111
+ provenance.push(`[3] Skill grown: ${draft.skillName} (${draft.type}), ${draft.steps.length} steps`);
112
+ // ========== 阶段 4:创造验证 ==========
113
+ const validation = this.validateSkill(draft, problemDomain, seed);
114
+ provenance.push(`[4] Validation: passed=${validation.passed}, coupling=${validation.couplingScore.toFixed(3)}, problemSolved=${validation.problemSolved}`);
115
+ if (!validation.passed) {
116
+ return this.buildFailedResult(problemDomain, 'VALIDATION', [
117
+ ...validation.riskIntroduced,
118
+ `Problem not solved: ${validation.problemSolved}`,
119
+ `Coupling below threshold: ${validation.couplingScore.toFixed(3)} < ${this.minCouplingScore}`,
120
+ ].filter(e => e), provenance, draft, validation.couplingScore);
121
+ }
122
+ // ========== 阶段 5:创造内化 ==========
123
+ const skillContent = this.renderSkillMarkdown(draft, validation, provenance);
124
+ let filePath;
125
+ if (this.enableFileWrite) {
126
+ filePath = this.internalizeSkill(draft.skillName, skillContent);
127
+ provenance.push(`[5] Internalized to file: ${filePath}`);
128
+ }
129
+ else {
130
+ provenance.push(`[5] Internalized (in-memory only)`);
131
+ }
132
+ // 记录到 KMWI
133
+ const wisdomId = this.kmwi.addWisdom(`Skill pattern: ${draft.skillName}`, `Generated skill for: ${problemDomain}`, `Creation type: ${draft.type}`, [draft.type, 'generated-skill'], `skill-generator:${draft.skillName}`);
134
+ provenance.push(`[5-KMWI] Recorded as wisdom: ${wisdomId}`);
135
+ // 判定是否触发递归
136
+ const recursionTriggered = this.shouldTriggerRecursion(draft, validation, this.creationHistory.length);
137
+ const nextCreationDomain = recursionTriggered ? this.identifyNextDomain(draft) : undefined;
138
+ const result = {
139
+ success: true,
140
+ stage: 'INTERNALIZATION',
141
+ type: draft.type,
142
+ skillName: draft.skillName,
143
+ skillContent,
144
+ validated: true,
145
+ filePath,
146
+ provenance,
147
+ couplingScore: validation.couplingScore,
148
+ errors: [],
149
+ timestamp: new Date().toISOString(),
150
+ recursionTriggered,
151
+ nextCreationDomain,
152
+ };
153
+ this.creationHistory.push(result);
154
+ return result;
155
+ }
156
+ // ============================================================================
157
+ // 阶段 1:问题域感知
158
+ // ============================================================================
159
+ perceiveDomain(problemDomain, context) {
160
+ // 检查是否已被现有技能覆盖
161
+ const coveragedBy = [];
162
+ const domainLower = problemDomain.toLowerCase();
163
+ for (const skillName of this.existingSkills) {
164
+ if (domainLower.includes(skillName.toLowerCase()) || skillName.toLowerCase().includes(domainLower)) {
165
+ coveragedBy.push(skillName);
166
+ }
167
+ }
168
+ if (context?.existingSkills) {
169
+ for (const skill of context.existingSkills) {
170
+ this.existingSkills.add(skill);
171
+ if (domainLower.includes(skill.toLowerCase())) {
172
+ coveragedBy.push(skill);
173
+ }
174
+ }
175
+ }
176
+ const description = coveragedBy.length === 0
177
+ ? `New problem domain detected: ${problemDomain}`
178
+ : `Domain may be partially covered by: ${coveragedBy.join(', ')}`;
179
+ return {
180
+ isNewDomain: coveragedBy.length === 0,
181
+ description,
182
+ coveragedBy,
183
+ };
184
+ }
185
+ // ============================================================================
186
+ // 阶段 2:内生种子生成
187
+ // ============================================================================
188
+ generateSeed(domain) {
189
+ // 从 KMWI 的 W 层和 I 层提取相关模式(A5 内生公理:不依赖外部数据)
190
+ const { wisdom, intuitions } = this.kmwi.extractPatternsForEvolution(domain, 5);
191
+ const sourcePatterns = wisdom.map(w => `${w.pattern} (success=${(w.successRate * 100).toFixed(0)}%, used=${w.usageCount})`);
192
+ const sourceIntuitions = intuitions.map(i => `${i.insight} (accuracy=${(i.accuracy * 100).toFixed(0)}%, validated=${i.validationCount})`);
193
+ // 组合策略:基于可用模式数量和类型
194
+ let combinationStrategy;
195
+ if (sourcePatterns.length >= 3 && sourceIntuitions.length >= 1) {
196
+ combinationStrategy = 'pattern_fusion_with_intuition_guidance';
197
+ }
198
+ else if (sourcePatterns.length >= 2) {
199
+ combinationStrategy = 'pattern_fusion';
200
+ }
201
+ else if (sourcePatterns.length >= 1 || sourceIntuitions.length >= 1) {
202
+ combinationStrategy = 'single_pattern_extension';
203
+ }
204
+ else {
205
+ combinationStrategy = 'first_principles_synthesis';
206
+ }
207
+ // 计算耦生度:衡量新种子与现有体系的一致性
208
+ const couplingScore = this.computeCouplingScore(wisdom, intuitions, domain);
209
+ return {
210
+ domain,
211
+ sourcePatterns,
212
+ sourceIntuitions,
213
+ combinationStrategy,
214
+ couplingScore,
215
+ };
216
+ }
217
+ /**
218
+ * 精炼种子:当耦生度不足时,尝试更宽松的提取
219
+ */
220
+ refineSeed(seed) {
221
+ // 放宽提取:不限定领域关键词
222
+ const { wisdom, intuitions } = this.kmwi.extractPatternsForEvolution('', 10);
223
+ const refinedScore = this.computeCouplingScore(wisdom, intuitions, seed.domain);
224
+ return {
225
+ ...seed,
226
+ sourcePatterns: [
227
+ ...seed.sourcePatterns,
228
+ ...wisdom.map(w => `${w.pattern} (success=${(w.successRate * 100).toFixed(0)}%, used=${w.usageCount})`),
229
+ ].slice(0, 8),
230
+ sourceIntuitions: [
231
+ ...seed.sourceIntuitions,
232
+ ...intuitions.map(i => `${i.insight} (accuracy=${(i.accuracy * 100).toFixed(0)}%)`),
233
+ ].slice(0, 5),
234
+ combinationStrategy: 'refined_broad_synthesis',
235
+ couplingScore: Math.max(seed.couplingScore, refinedScore),
236
+ };
237
+ }
238
+ /**
239
+ * 计算耦生度
240
+ *
241
+ * 耦生度衡量新创造的能力与现有体系的一致性:
242
+ * - 模式相关性(40%):新种子与现有智慧模式的相关程度
243
+ * - 直觉一致性(30%):新种子与现有直觉判断的契合度
244
+ * - 公理兼容性(30%):新种子是否符合元构公理体系
245
+ *
246
+ * 耦生度 ≥ 0.95 才能通过验证(最小改变原则)
247
+ */
248
+ computeCouplingScore(wisdom, intuitions, domain) {
249
+ if (wisdom.length === 0 && intuitions.length === 0) {
250
+ // 无参考模式时,基于公理体系给出基础分
251
+ return 0.85;
252
+ }
253
+ // 模式相关性
254
+ const patternRelevance = wisdom.length === 0
255
+ ? 0.5
256
+ : Math.min(1, wisdom.reduce((sum, w) => sum + w.successRate, 0) / wisdom.length);
257
+ // 直觉一致性
258
+ const intuitionConsistency = intuitions.length === 0
259
+ ? 0.5
260
+ : Math.min(1, intuitions.reduce((sum, i) => sum + i.accuracy, 0) / intuitions.length);
261
+ // 公理兼容性(新技能默认兼容,因为基于元构体系生长)
262
+ const axiomCompatibility = 0.95;
263
+ const score = patternRelevance * 0.4 + intuitionConsistency * 0.3 + axiomCompatibility * 0.3;
264
+ return Math.min(1, Math.max(0, score));
265
+ }
266
+ // ============================================================================
267
+ // 阶段 3:创造生长
268
+ // ============================================================================
269
+ growSkill(seed, problemDomain) {
270
+ const skillName = this.generateSkillName(problemDomain, seed);
271
+ const type = this.inferCreationType(problemDomain, seed);
272
+ const description = this.generateDescription(problemDomain, seed, type);
273
+ const triggerConditions = this.generateTriggers(problemDomain, type);
274
+ const steps = this.generateSteps(seed, type, problemDomain);
275
+ const principles = this.generatePrinciples(seed, type);
276
+ const outputFormat = this.generateOutputFormat(type, skillName);
277
+ const rawContent = this.renderSkillMarkdown({ skillName, type, description, triggerConditions, steps, principles, outputFormat, rawContent: '' }, { passed: true, problemSolved: true, riskIntroduced: [], boundaryIdentified: '', couplingScore: seed.couplingScore, axiomCompliance: [], formatValid: true }, []);
278
+ return { skillName, type, description, triggerConditions, steps, principles, outputFormat, rawContent };
279
+ }
280
+ generateSkillName(domain, seed) {
281
+ const base = domain
282
+ .toLowerCase()
283
+ .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
284
+ .replace(/^-+|-+$/g, '')
285
+ .substring(0, 30);
286
+ const hash = Math.random().toString(36).substring(2, 5);
287
+ return `metago-${base}-${hash}`;
288
+ }
289
+ inferCreationType(domain, seed) {
290
+ const domainLower = domain.toLowerCase();
291
+ if (/算法|algorithm|优化|计算/.test(domainLower))
292
+ return 'algorithm';
293
+ if (/架构|architecture|系统|层次/.test(domainLower))
294
+ return 'architecture';
295
+ if (/协议|protocol|通信|交互/.test(domainLower))
296
+ return 'protocol';
297
+ if (/方法论|方法|流程|步骤/.test(domainLower))
298
+ return 'methodology';
299
+ if (/思想|理论|理念|哲学/.test(domainLower))
300
+ return 'thought';
301
+ return 'capability';
302
+ }
303
+ generateDescription(domain, seed, type) {
304
+ const typeMap = {
305
+ thought: '生成新思想、新理论',
306
+ methodology: '生成新方法论',
307
+ algorithm: '生成新算法',
308
+ architecture: '生成新架构',
309
+ protocol: '生成新协议',
310
+ capability: '生成新能力',
311
+ };
312
+ const sourceHint = seed.sourcePatterns.length > 0
313
+ ? `(基于 ${seed.sourcePatterns.length} 个现有模式内生生长)`
314
+ : '(基于第一性原理合成)';
315
+ return `此技能实现"${domain}"的${typeMap[type]}${sourceHint}。由元创造引擎自动生成,遵循 A5 内生公理与 D40 全息创造性。`;
316
+ }
317
+ generateTriggers(domain, type) {
318
+ return [
319
+ `遇到"${domain}"相关问题时自动触发`,
320
+ `现有技能组合无法解决"${domain}"场景`,
321
+ `开发者明确要求处理"${domain}"`,
322
+ `元进化循环到达自生成阶段且无外部参考`,
323
+ ];
324
+ }
325
+ generateSteps(seed, type, domain) {
326
+ const baseSteps = [
327
+ {
328
+ name: '问题域感知',
329
+ description: `识别"${domain}"为需要处理的问题域,确认现有能力是否覆盖`,
330
+ timeBudget: '<10ms',
331
+ inputs: ['问题描述'],
332
+ outputs: ['问题域判定'],
333
+ },
334
+ {
335
+ name: '内生种子生成',
336
+ description: `从内部 KMWI 记忆中提取相关模式,组合形成种子(来源:${seed.sourcePatterns.length} 模式 + ${seed.sourceIntuitions.length} 直觉)`,
337
+ timeBudget: '<50ms',
338
+ inputs: ['问题域', 'KMWI 记忆'],
339
+ outputs: ['创造种子'],
340
+ },
341
+ {
342
+ name: '创造生长',
343
+ description: `基于种子生长新能力,组合策略:${seed.combinationStrategy}`,
344
+ timeBudget: '<100ms',
345
+ inputs: ['种子'],
346
+ outputs: ['能力草稿'],
347
+ },
348
+ {
349
+ name: '创造验证',
350
+ description: `验证新能力能否解决问题,耦生度≥${this.minCouplingScore}`,
351
+ timeBudget: '<50ms',
352
+ inputs: ['能力草稿', '原问题'],
353
+ outputs: ['验证结果'],
354
+ },
355
+ {
356
+ name: '创造内化',
357
+ description: '验证通过则内化为新技能,记录溯源链,触发递归',
358
+ inputs: ['验证通过的能力'],
359
+ outputs: ['新技能文件'],
360
+ },
361
+ ];
362
+ // 根据类型插入特定步骤
363
+ if (type === 'algorithm') {
364
+ baseSteps.splice(2, 0, {
365
+ name: '算法设计',
366
+ description: '基于种子模式设计算法结构,定义输入输出与复杂度约束',
367
+ timeBudget: '<200ms',
368
+ inputs: ['种子', '问题约束'],
369
+ outputs: ['算法草稿'],
370
+ });
371
+ }
372
+ else if (type === 'architecture') {
373
+ baseSteps.splice(2, 0, {
374
+ name: '架构分解',
375
+ description: '将问题域分解为模块,定义模块间接口与数据流',
376
+ timeBudget: '<200ms',
377
+ inputs: ['种子', '问题域'],
378
+ outputs: ['架构草稿'],
379
+ });
380
+ }
381
+ return baseSteps;
382
+ }
383
+ generatePrinciples(seed, type) {
384
+ return [
385
+ '**内生性原则**(A5):新能力从内部结构生长,不依赖外部数据输入',
386
+ '**最小改变原则**:在保持耦生关系(耦生度≥0.95)前提下最小化扩展',
387
+ '**验证性原则**:创造结果必须通过验证才被保留',
388
+ '**递归性原则**:创造能力本身可被创造,递归无界',
389
+ `**全息创造性**(D40):创造层嵌入每一层,此技能的创造类型为 ${type}`,
390
+ ];
391
+ }
392
+ generateOutputFormat(type, skillName) {
393
+ return `【元创造报告】
394
+ 创造类型:${type}
395
+ 技能名称:${skillName}
396
+
397
+ 内生种子:
398
+ - 来源模式:[从 KMWI W 层提取]
399
+ - 来源直觉:[从 KMWI I 层提取]
400
+ - 组合策略:[pattern_fusion / first_principles_synthesis]
401
+
402
+ 创造过程:
403
+ 1. [生长步骤1]
404
+ 2. [生长步骤2]
405
+ 3. [生长步骤3]
406
+
407
+ 创造结果:
408
+ [新能力描述]
409
+
410
+ 验证结果:
411
+ - 问题解决:✅/❌
412
+ - 耦生度:[0.95-1.00]
413
+ - 风险评估:[风险描述]
414
+
415
+ 递归状态:
416
+ - 是否触发下一轮创造:是/否
417
+ - 下一轮创造方向:[方向]
418
+
419
+ 溯源链:
420
+ [完整创造溯源]`;
421
+ }
422
+ // ============================================================================
423
+ // 阶段 4:创造验证
424
+ // ============================================================================
425
+ validateSkill(draft, problemDomain, seed) {
426
+ const riskIntroduced = [];
427
+ const axiomCompliance = [];
428
+ // 1. 格式验证
429
+ const formatValid = this.checkSkillFormat(draft);
430
+ // 2. 公理合规验证
431
+ axiomCompliance.push(...this.checkAxiomCompliance(draft));
432
+ // 3. 安全风险检查
433
+ const securityRisks = this.checkSecurityRisks(draft);
434
+ riskIntroduced.push(...securityRisks);
435
+ // 4. 问题解决验证(基于草稿是否覆盖问题域关键词)
436
+ const problemSolved = this.checkProblemCoverage(draft, problemDomain);
437
+ // 5. 边界识别
438
+ const boundaryIdentified = this.identifyBoundary(draft, problemDomain);
439
+ // 6. 耦生度最终计算
440
+ const couplingScore = Math.max(seed.couplingScore, this.computeDraftCoupling(draft));
441
+ // 综合判定
442
+ const passed = formatValid
443
+ && axiomCompliance.every(a => a.compliant)
444
+ && riskIntroduced.length === 0
445
+ && problemSolved
446
+ && couplingScore >= this.minCouplingScore;
447
+ return {
448
+ passed,
449
+ problemSolved,
450
+ riskIntroduced,
451
+ boundaryIdentified,
452
+ couplingScore,
453
+ axiomCompliance,
454
+ formatValid,
455
+ };
456
+ }
457
+ checkSkillFormat(draft) {
458
+ return draft.skillName.startsWith('metago-')
459
+ && draft.description.length > 20
460
+ && draft.steps.length >= 3
461
+ && draft.triggerConditions.length > 0
462
+ && draft.principles.length > 0;
463
+ }
464
+ checkAxiomCompliance(draft) {
465
+ const checks = [];
466
+ const content = `${draft.skillName} ${draft.description} ${draft.rawContent}`.toLowerCase();
467
+ // A1 溯源公理
468
+ checks.push({
469
+ axiom: 'A1 溯源',
470
+ compliant: true,
471
+ note: '技能生成过程已记录溯源链',
472
+ });
473
+ // A2 闭环公理
474
+ const hasClosure = draft.steps.some(s => s.outputs && s.outputs.length > 0);
475
+ checks.push({
476
+ axiom: 'A2 闭环',
477
+ compliant: hasClosure,
478
+ note: hasClosure ? '每个步骤都有明确输出,形成闭环' : '缺少输出定义,闭环不完整',
479
+ });
480
+ // A5 内生公理
481
+ checks.push({
482
+ axiom: 'A5 内生',
483
+ compliant: !content.includes('外部数据') && !content.includes('external api'),
484
+ note: '技能基于内部 KMWI 记忆生长,不依赖外部数据',
485
+ });
486
+ // A36 法律优先于效率
487
+ const dangerousPatterns = ['bypass', '绕过', 'skip validation', '忽略验证', 'ignore security'];
488
+ const hasDangerous = dangerousPatterns.some(p => content.includes(p));
489
+ checks.push({
490
+ axiom: 'A36 法律优先',
491
+ compliant: !hasDangerous,
492
+ note: hasDangerous ? '检测到绕过/忽略验证的危险模式' : '未检测到合规风险',
493
+ });
494
+ return checks;
495
+ }
496
+ checkSecurityRisks(draft) {
497
+ const risks = [];
498
+ const content = `${draft.description} ${draft.rawContent}`.toLowerCase();
499
+ const dangerousPatterns = [
500
+ { pattern: 'eval(', risk: '使用 eval() 可能导致代码注入' },
501
+ { pattern: 'exec(', risk: '使用 exec() 可能导致命令注入' },
502
+ { pattern: 'system(', risk: '使用 system() 可能导致命令注入' },
503
+ { pattern: 'rm -rf', risk: '检测到危险删除命令' },
504
+ { pattern: 'del /f', risk: '检测到危险删除命令' },
505
+ { pattern: 'shutdown', risk: '检测到关机命令' },
506
+ ];
507
+ for (const { pattern, risk } of dangerousPatterns) {
508
+ if (content.includes(pattern))
509
+ risks.push(risk);
510
+ }
511
+ return risks;
512
+ }
513
+ checkProblemCoverage(draft, problemDomain) {
514
+ const content = `${draft.skillName} ${draft.description} ${draft.triggerConditions.join(' ')}`.toLowerCase();
515
+ const domainKeywords = problemDomain.toLowerCase().split(/\s+/).filter(k => k.length > 2);
516
+ if (domainKeywords.length === 0)
517
+ return true;
518
+ const coverage = domainKeywords.filter(k => content.includes(k)).length / domainKeywords.length;
519
+ return coverage >= 0.5;
520
+ }
521
+ identifyBoundary(draft, problemDomain) {
522
+ return `此技能适用于"${problemDomain}"场景;超出此域的问题需要触发新的元创造循环`;
523
+ }
524
+ computeDraftCoupling(draft) {
525
+ // 草稿完整度越高,耦生度越高
526
+ let score = 0.9;
527
+ if (draft.steps.length >= 5)
528
+ score += 0.02;
529
+ if (draft.principles.length >= 4)
530
+ score += 0.02;
531
+ if (draft.outputFormat.length > 100)
532
+ score += 0.02;
533
+ if (draft.triggerConditions.length >= 3)
534
+ score += 0.02;
535
+ return Math.min(1, score);
536
+ }
537
+ // ============================================================================
538
+ // 阶段 5:创造内化
539
+ // ============================================================================
540
+ renderSkillMarkdown(draft, validation, provenance) {
541
+ const triggers = draft.triggerConditions.map(t => `- ${t}`).join('\n');
542
+ const steps = draft.steps.map((s, i) => `### ${i + 1}. ${s.name}${s.timeBudget ? `(${s.timeBudget})` : ''}\n${s.description}${s.inputs ? `\n- 输入:${s.inputs.join(', ')}` : ''}${s.outputs ? `\n- 输出:${s.outputs.join(', ')}` : ''}`).join('\n\n');
543
+ const principles = draft.principles.map(p => `- ${p}`).join('\n');
544
+ const axiomChecks = validation.axiomCompliance.map(a => `- ${a.axiom}:${a.compliant ? '✅' : '❌'} ${a.note}`).join('\n');
545
+ const provenanceStr = provenance.map(p => `- ${p}`).join('\n');
546
+ return `---
547
+ name: "${draft.skillName}"
548
+ description: "${draft.description}"
549
+ type: "${draft.type}"
550
+ generated_by: "metago-skill-generator"
551
+ coupling_score: ${validation.couplingScore.toFixed(3)}
552
+ created_at: "${new Date().toISOString()}"
553
+ ---
554
+
555
+ # ${draft.skillName}
556
+
557
+ ${draft.description}
558
+
559
+ ## 触发条件
560
+
561
+ ${triggers}
562
+
563
+ ## 执行步骤
564
+
565
+ ${steps}
566
+
567
+ ## 核心原则
568
+
569
+ ${principles}
570
+
571
+ ## 输出格式
572
+
573
+ \`\`\`
574
+ ${draft.outputFormat}
575
+ \`\`\`
576
+
577
+ ## 公理合规
578
+
579
+ ${axiomChecks}
580
+
581
+ ## 边界
582
+
583
+ ${validation.boundaryIdentified}
584
+
585
+ ## 溯源链
586
+
587
+ ${provenanceStr}
588
+
589
+ ---
590
+
591
+ *由元构技能智能生成器(SkillGenerator)自动生成 | 遵循 A5 内生公理与 A35 创造进化律*
592
+ `;
593
+ }
594
+ internalizeSkill(skillName, content) {
595
+ if (!fs.existsSync(this.outputDir)) {
596
+ fs.mkdirSync(this.outputDir, { recursive: true });
597
+ }
598
+ const fileName = `${skillName}.md`;
599
+ const filePath = path.join(this.outputDir, fileName);
600
+ fs.writeFileSync(filePath, content, 'utf-8');
601
+ this.existingSkills.add(skillName);
602
+ return filePath;
603
+ }
604
+ // ============================================================================
605
+ // 递归判定
606
+ // ============================================================================
607
+ shouldTriggerRecursion(draft, validation, historyDepth) {
608
+ if (historyDepth >= this.maxRecursionDepth)
609
+ return false;
610
+ // 如果新技能的边界识别中提到了"超出此域",则可能需要递归
611
+ if (validation.boundaryIdentified.includes('超出此域'))
612
+ return true;
613
+ // 如果创造类型是"能力",则可能需要递归创造使用此能力的方法论
614
+ if (draft.type === 'capability')
615
+ return true;
616
+ return false;
617
+ }
618
+ identifyNextDomain(draft) {
619
+ return `如何使用 ${draft.skillName} 解决更复杂的问题(${draft.type} 的应用方法论)`;
620
+ }
621
+ // ============================================================================
622
+ // 辅助方法
623
+ // ============================================================================
624
+ loadExistingSkills() {
625
+ // 从输出目录加载已生成的技能
626
+ if (fs.existsSync(this.outputDir)) {
627
+ try {
628
+ const files = fs.readdirSync(this.outputDir);
629
+ for (const file of files) {
630
+ if (file.endsWith('.md') && file.startsWith('metago-')) {
631
+ this.existingSkills.add(file.replace(/\.md$/, ''));
632
+ }
633
+ }
634
+ }
635
+ catch {
636
+ // 读取失败不阻塞
637
+ }
638
+ }
639
+ }
640
+ buildFailedResult(domain, stage, errors, provenance, draft, couplingScore) {
641
+ return {
642
+ success: false,
643
+ stage,
644
+ type: draft?.type || 'capability',
645
+ skillName: draft?.skillName || '',
646
+ skillContent: draft?.rawContent || '',
647
+ validated: false,
648
+ provenance,
649
+ couplingScore: couplingScore ?? 0,
650
+ errors,
651
+ timestamp: new Date().toISOString(),
652
+ recursionTriggered: false,
653
+ };
654
+ }
655
+ // ============================================================================
656
+ // 导出与统计
657
+ // ============================================================================
658
+ getHistory() {
659
+ return this.creationHistory;
660
+ }
661
+ getExistingSkills() {
662
+ return Array.from(this.existingSkills);
663
+ }
664
+ getSummary() {
665
+ const lines = [
666
+ '【技能智能生成器报告】',
667
+ `■ 已生成技能数:${this.creationHistory.filter(r => r.success).length}`,
668
+ `■ 失败次数:${this.creationHistory.filter(r => !r.success).length}`,
669
+ `■ 已知技能总数:${this.existingSkills.size}`,
670
+ `■ 耦生度阈值:${this.minCouplingScore}`,
671
+ `■ 最大递归深度:${this.maxRecursionDepth}`,
672
+ `■ 输出目录:${this.outputDir}`,
673
+ ];
674
+ if (this.creationHistory.length > 0) {
675
+ const latest = this.creationHistory[this.creationHistory.length - 1];
676
+ lines.push(`■ 最新创造:${latest.skillName}(${latest.success ? '成功' : '失败'},耦生度=${latest.couplingScore.toFixed(3)})`);
677
+ }
678
+ return lines.join('\n');
679
+ }
680
+ }
681
+ exports.SkillGenerator = SkillGenerator;
682
+ exports.default = SkillGenerator;
683
+ //# sourceMappingURL=skill-generator.js.map