@metago-ai/engine 2.1.3 → 2.1.4

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 (65) hide show
  1. package/BOUNDARIES.md +109 -0
  2. package/CHANGES.md +4 -4
  3. package/CONSTITUTION/AXIOMS.md +75 -113
  4. package/CORE/ATOMS.md +611 -0
  5. package/CORE/ATTRIBUTES.md +74 -105
  6. package/CORE/PROTOCOLS.md +134 -116
  7. package/ENGINE.md +115 -115
  8. package/ENGINES/engine-runtime.cjs +318 -0
  9. package/ENGINES/final-engines-runtime.cjs +683 -0
  10. package/ENGINES/governance-runtime.cjs +582 -0
  11. package/ENGINES/math-capability-runtime.cjs +451 -0
  12. package/ENGINES/philosophy-runtime.cjs +427 -0
  13. package/ENGINES/yili/data/yaoci-1.js +24 -0
  14. package/ENGINES/yili/data/yaoci-2.js +21 -0
  15. package/ENGINES/yili/data/yaoci-3.js +21 -0
  16. package/ENGINES/yili/data/yaoci-4.js +21 -0
  17. package/ENGINES/yili/data/yaoci.js +17 -0
  18. package/ENGINES/yili/lib/almanac.js +416 -0
  19. package/ENGINES/yili/lib/bazi.js +127 -0
  20. package/ENGINES/yili/lib/diagnose.js +71 -0
  21. package/ENGINES/yili/lib/hetu-luoshu.js +123 -0
  22. package/ENGINES/yili/lib/index.js +23 -0
  23. package/ENGINES/yili/lib/liuyao.js +226 -0
  24. package/ENGINES/yili/lib/qimen.js +167 -0
  25. package/ENGINES/yili/lib/shushu-calculus.js +85 -0
  26. package/ENGINES/yili/lib/taiyi.js +83 -0
  27. package/ENGINES/yili/lib/vendor/shouxing-core.js +627 -0
  28. package/ENGINES/yili/lib/wuxing.js +106 -0
  29. package/ENGINES/yili/lib/yijing.js +226 -0
  30. package/ENGINES/yili/lib/zeri.js +80 -0
  31. package/ENGINES/yili/lib/ziwei.js +145 -0
  32. package/ENGINES/yili/package.json +1 -0
  33. package/EXECUTORS.md +85 -0
  34. package/GENOME.json +11 -10
  35. package/INDEX/ENGINES.md +168 -0
  36. package/INDEX/engines.json +2 -2
  37. package/INDEX/knowledge.json +87 -87
  38. package/INDEX/skills.json +227 -203
  39. package/PATENTS.md +1 -1
  40. package/PROTOCOLS/closure-runtime.cjs +288 -0
  41. package/PROTOCOLS/covenant-runtime.cjs +409 -0
  42. package/PROTOCOLS/final-runtime.cjs +680 -0
  43. package/PROTOCOLS/formula-runtime.cjs +399 -0
  44. package/PROTOCOLS/proactive-runtime.cjs +368 -0
  45. package/PROTOCOLS/rule-runtime.cjs +448 -0
  46. package/PROTOCOLS/runtime.cjs +441 -0
  47. package/README.md +5 -5
  48. package/RUNTIME/dist/kmwi-memory.d.ts.map +1 -1
  49. package/RUNTIME/dist/kmwi-memory.js +14 -2
  50. package/RUNTIME/dist/kmwi-memory.js.map +1 -1
  51. package/RUNTIME/dist/validators.js +11 -2
  52. package/atoms/approx.cjs +293 -0
  53. package/atoms/atom-factory.cjs +550 -0
  54. package/atoms/atoms-cosmic-bio.cjs +340 -0
  55. package/atoms/atoms-crypto-emotion.cjs +215 -0
  56. package/atoms/atoms_engines.json +5821 -0
  57. package/atoms/blueprint-atoms-2.cjs +583 -0
  58. package/atoms/blueprint-atoms.cjs +975 -0
  59. package/atoms/constraints.cjs +257 -0
  60. package/atoms/contract-validator.cjs +213 -0
  61. package/atoms/engine.cjs +849 -0
  62. package/atoms/specialized.cjs +530 -0
  63. package/atoms/verify.cjs +94 -0
  64. package/package.json +12 -6
  65. package/scripts/verify-dist.cjs +80 -0
@@ -0,0 +1,451 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * P6-B8 · 数学族 / 能力族 / 共生族引擎运行时(20 条)
4
+ * 依据 ENGINE-CONTRACTS.json 的 definitionText(含输入/输出规范)逐条实现。
5
+ */
6
+ 'use strict';
7
+
8
+ let __seq = 0;
9
+ const newTraceId = () => {
10
+ const d = new Date(), p = (n, w = 2) => String(n).padStart(w, '0');
11
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${d.getHours()}${p(d.getMinutes())}${d.getSeconds()}-E${p((++__seq) % 10000, 4)}`;
12
+ };
13
+ const clamp01 = (x) => Math.max(0, Math.min(1, Number(x) || 0));
14
+ const round = (x, n = 6) => Math.round((Number(x) || 0) * 10 ** n) / 10 ** n;
15
+ const cos = (a, b) => {
16
+ if (!a || !b || a.length !== b.length) return 0;
17
+ const d = a.reduce((s, x, i) => s + x * b[i], 0);
18
+ const na = Math.sqrt(a.reduce((s, x) => s + x * x, 0)), nb = Math.sqrt(b.reduce((s, x) => s + x * x, 0));
19
+ return na && nb ? d / (na * nb) : 0;
20
+ };
21
+
22
+ const E = [];
23
+
24
+ /* ══════════ 数学通用族(8 条,第1部分 §2.1)══════════ */
25
+
26
+ E.push({
27
+ id: 'ENGINE_COMPLEX_INTEGRAL_47', name: '复分析积分引擎', kind: 'compute',
28
+ spec: '第1部分 §2.1(898 字符)', io: { in: ['poles', 'contour'], out: ['residues', 'integralValue', 'estimation'] },
29
+ implements: ['留数计算 Res(f,z₀)=lim(z-z₀)f(z)', '围道积分 ∮f dz = 2πi·ΣRes', 'ML 估计界 |∮| ≤ M·L'],
30
+ exec(inp, tid) {
31
+ const poles = inp.poles;
32
+ if (!Array.isArray(poles) || !poles.length) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: '必须提供 poles 数组(每个含 residue 或 omega/residue 形式)' };
33
+ /* 留数求和 → 围道积分值(2πi Σ Res) */
34
+ const residues = poles.map((p) => ({ z: p.z, residue: Number(p.residue || 0) }));
35
+ const sumRes = round(residues.reduce((s, r) => s + r.residue, 0));
36
+ const integralValue = { real: round(0), imag: round(2 * Math.PI * sumRes) };
37
+ /* ML 估计:M = max|f| on contour, L = 周长 */
38
+ const M = Number(inp.M ?? 1), L = Number(inp.L ?? 2 * Math.PI);
39
+ const mlBound = round(M * L);
40
+ return { success: true, kind: 'compute', output: {
41
+ poles: poles.length, residues, sumResidues: sumRes,
42
+ integralValue, formula: '∮f dz = 2πi·ΣRes',
43
+ estimation: { M, L, mlBound, formula: '|∮f dz| ≤ M·L' },
44
+ withinBound: Math.abs(2 * Math.PI * sumRes) <= mlBound,
45
+ }, provenance: [`[${tid}] complex-integral: ${poles.length} 极点 → ∮ = 2πi·${sumRes}`] };
46
+ },
47
+ });
48
+
49
+ E.push({
50
+ id: 'ENGINE_ERROR_PROPAGATE_54', name: '误差传播控制引擎', kind: 'compute',
51
+ spec: '第1部分 §2.2(664 字符)', io: { in: ['sigmas', 'iterations'], out: ['errorBound', 'accumulation'] },
52
+ implements: ['独立误差 σ=√Σσ_i²', '迭代累积界(收敛率 r 时 σ_n ≤ σ₀·r^n/(1-r))', '显式控制界'],
53
+ exec(inp, tid) {
54
+ const sigmas = inp.sigmas;
55
+ if (!Array.isArray(sigmas) || !sigmas.length) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: '必须提供 sigmas 数组' };
56
+ const s = sigmas.map(Number);
57
+ const indep = round(Math.sqrt(s.reduce((a, x) => a + x * x, 0)));
58
+ const n = Number(inp.iterations ?? s.length);
59
+ const r = clamp01(inp.convergenceRate ?? 0.5);
60
+ const geomBound = r < 1 ? round(s[0] * (r ** n) / (1 - r)) : null;
61
+ return { success: true, kind: 'compute', output: {
62
+ steps: s.length, sigmas: s, independentSigma: indep,
63
+ iterations: n, convergenceRate: r, geometricBound: geomBound,
64
+ formula: { independent: 'σ=√Σσ_i²', iteration: 'σ_n ≤ σ₀·rⁿ/(1-r)(r<1)' },
65
+ recommendation: r >= 1 ? '不收敛:需调整算法' : r > 0.9 ? '收敛慢:建议加速' : '收敛良好',
66
+ }, provenance: [`[${tid}] error-propagate: ${s.length} 步 σ=${indep},迭代 ${n} 次界 ${geomBound}`] };
67
+ },
68
+ });
69
+
70
+ E.push({
71
+ id: 'ENGINE_COUNTEREXAMPLE_50', name: '反证自动构造引擎', kind: 'compute',
72
+ spec: '第1部分 §2.2(664 字符)', io: { in: ['claim', 'candidates'], out: ['counterexample', 'contradictionPoint'] },
73
+ implements: ['反例搜索(枚举候选并检验谓词)', '矛盾点定位', '反证完备性判定'],
74
+ exec(inp, tid) {
75
+ const claim = String(inp.claim || '');
76
+ const cands = inp.candidates;
77
+ if (!Array.isArray(cands) || !cands.length) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: '必须提供 candidates 数组(每项含 value 与 holds 布尔)' };
78
+ const ce = cands.filter((c) => c && c.holds === false);
79
+ const ok = ce.length > 0;
80
+ return { success: true, kind: 'compute', output: {
81
+ claim, tested: cands.length, counterexamples: ce.map((c) => c.value),
82
+ found: ok, contradictionPoint: ok ? { at: ce[0].value, why: '该候选使命题为假' } : null,
83
+ verdict: ok ? '命题被反例推翻' : '未在候选域内找到反例(不等于命题成立)',
84
+ caution: '反例搜索的否定结论是确定的;肯定结论受候选域限制',
85
+ }, provenance: [`[${tid}] counterexample: 测 ${cands.length} 候选,反例 ${ce.length}`] };
86
+ },
87
+ });
88
+
89
+ E.push({
90
+ id: 'ENGINE_PROOF_STRATEGY_51', name: '证明策略发现引擎', kind: 'compute',
91
+ spec: '第1部分 §2.2(664 字符)', io: { in: ['goal', 'availableLemmas'], out: ['strategies', 'ranking'] },
92
+ implements: ['策略库匹配(直接/反证/归纳/构造/穷举/对角化)', '策略打分排序'],
93
+ exec(inp, tid) {
94
+ const goal = String(inp.goal || '');
95
+ if (!goal) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: '必须提供 goal' };
96
+ const LIB = [
97
+ { s: '直接证明', pat: /恒等|等于|构成|满足/, base: 0.8 },
98
+ { s: '反证法', pat: /不存在|不能|无法|无解/, base: 0.85 },
99
+ { s: '数学归纳法', pat: /所有|任意|一切|自然数|n\s*[≥>=]/, base: 0.8 },
100
+ { s: '构造法', pat: /存在|可以找到|构造/, base: 0.75 },
101
+ { s: '穷举法', pat: /有限|枚举|分类/, base: 0.6 },
102
+ { s: '对角化', pat: /不可数|不完备|自指/, base: 0.8 },
103
+ ];
104
+ const lemmas = inp.availableLemmas || [];
105
+ const ranked = LIB.map((l) => ({ strategy: l.s, score: round(clamp01(l.base + (l.pat.test(goal) ? 0.15 : 0) + Math.min(0.05, lemmas.length * 0.01))) })).sort((a, b) => b.score - a.score);
106
+ return { success: true, kind: 'compute', output: { goal, lemmas: lemmas.length, strategies: ranked, top: ranked[0].strategy },
107
+ provenance: [`[${tid}] proof-strategy: 首选「${ranked[0].strategy}」`] };
108
+ },
109
+ });
110
+
111
+ E.push({
112
+ id: 'ENGINE_PROVABILITY_52', name: '可证明性预判引擎', kind: 'compute',
113
+ spec: '第1部分 §2.2(664 字符)', io: { in: ['conjecture', 'knowledgeBase'], out: ['provability', 'confidence'] },
114
+ implements: ['可证明性三因子(知识覆盖/表述清晰/工具可用)加权', '三档预判'],
115
+ exec(inp, tid) {
116
+ const cov = clamp01(inp.knowledgeCoverage ?? 0.6), clarity = clamp01(inp.statementClarity ?? 0.8), tools = clamp01(inp.toolsAvailable ?? 0.5);
117
+ const W = { cov: 0.45, clarity: 0.2, tools: 0.35 };
118
+ const score = round(W.cov * cov + W.clarity * clarity + W.tools * tools);
119
+ const verdict = score >= 0.75 ? '高可证明' : score >= 0.45 ? '可能可证(需更多工具)' : '当前不可证(超出知识体系)';
120
+ return { success: true, kind: 'compute', output: { conjecture: inp.conjecture || null, factors: { knowledgeCoverage: cov, statementClarity: clarity, toolsAvailable: tools }, weights: W, provability: score, verdict, caveat: '预判非证明,仅为策略选择提供依据' },
121
+ provenance: [`[${tid}] provability: ${score} → ${verdict}`] };
122
+ },
123
+ });
124
+
125
+ E.push({
126
+ id: 'ENGINE_IDENTITY_AUTO_53', name: '积分恒等式引擎', kind: 'compute',
127
+ spec: '第1部分 §2.2(664 字符)', io: { in: ['exprA', 'exprB', 'samples'], out: ['identical', 'evidence'] },
128
+ implements: ['数值采样检验恒等(多点比对)', '差异定位'],
129
+ exec(inp, tid) {
130
+ const a = inp.samplesA, b = inp.samplesB;
131
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: 'samplesA/samplesB 须为等长数组' };
132
+ const tol = Number(inp.tolerance ?? 1e-9);
133
+ const diffs = a.map((x, i) => Math.abs(Number(x) - Number(b[i])));
134
+ const maxDiff = round(Math.max(...diffs));
135
+ const identical = maxDiff <= tol;
136
+ return { success: true, kind: 'compute', output: { points: a.length, maxDiff, tolerance: tol, identical,
137
+ mismatches: diffs.map((d, i) => d > tol ? { index: i, a: a[i], b: b[i], diff: round(d) } : null).filter(Boolean).slice(0, 5),
138
+ caveat: '数值抽样不能替代符号证明;未发现差异不等于恒等成立' },
139
+ provenance: [`[${tid}] identity-auto: ${a.length} 点最大差 ${maxDiff} → ${identical ? '采样一致' : '不一致'}`] };
140
+ },
141
+ });
142
+
143
+ E.push({
144
+ id: 'ENGINE_SYMMETRY_AUTO_55', name: '对称性自动利用引擎', kind: 'compute',
145
+ spec: '第1部分 §2.2(664 字符)', io: { in: ['structure'], out: ['symmetries', 'simplification'] },
146
+ implements: ['对称性识别(平移/镜像/置换/尺度)', '约简倍数估算'],
147
+ exec(inp, tid) {
148
+ const seq = inp.structure;
149
+ if (!Array.isArray(seq) || seq.length < 2) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: '必须提供长度≥2 的 structure 数组' };
150
+ const n = seq.length;
151
+ let mirror = 0;
152
+ for (let i = 0; i < Math.floor(n / 2); i++) if (seq[i] === seq[n - 1 - i]) mirror++;
153
+ const mirrorSym = round(mirror / Math.floor(n / 2));
154
+ let period = n;
155
+ for (let p = 1; p < n; p++) { let ok = 0; for (let i = 0; i + p < n; i++) if (seq[i] === seq[i + p]) ok++; if (ok / (n - p) > 0.99) { period = p; break; } }
156
+ const shift = period < n ? 1 : 0;
157
+ const syms = [];
158
+ if (mirrorSym > 0.99) syms.push('镜像');
159
+ if (shift) syms.push('平移(周期' + period + ')');
160
+ const score = round(Math.max(mirrorSym, shift ? 1 : 0));
161
+ return { success: true, kind: 'compute', output: { length: n, symmetries: syms, mirrorSymmetry: mirrorSym, period: period < n ? period : null, symmetryScore: score,
162
+ simplification: score > 0 ? `${Math.max(1, Math.floor(1 / (1 - score * 0.9)))}× 计算约简` : '无约简' },
163
+ provenance: [`[${tid}] symmetry-auto: ${syms.join('/') || '无对称'},约简分 ${score}`] };
164
+ },
165
+ });
166
+
167
+ E.push({
168
+ id: 'ENGINE_ZERO_DENSITY_49', name: '零点密度推理引擎', kind: 'compute',
169
+ spec: '第1部分 §2.1(898 字符)', io: { in: ['T', 'kind'], out: ['density', 'count'] },
170
+ implements: ['Riemann–von Mangoldt 密度:N(T) ≈ (T/2π)log(T/2π) − T/2π', '零点计数下界'],
171
+ exec(inp, tid) {
172
+ const T = Number(inp.T);
173
+ if (!isFinite(T) || T <= 0) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: '必须提供 T > 0' };
174
+ const x = T / (2 * Math.PI);
175
+ const N = x * Math.log(x) - x; // 主项
176
+ return { success: true, kind: 'compute', output: {
177
+ T, kind: inp.kind || 'Riemann-zeta',
178
+ mainTerm: round(N), density: round(N / T),
179
+ formula: 'N(T) ≈ (T/2π)·ln(T/2π) − T/2π(Riemann–von Mangoldt 主项)',
180
+ note: '仅主项估计,未含 S(T) 误差项 O(log T)',
181
+ }, provenance: [`[${tid}] zero-density: N(${T}) ≈ ${round(N)},密度 ${round(N / T)}`] };
182
+ },
183
+ });
184
+
185
+ /* ══════════ 能力族(5 条)══════════ */
186
+
187
+ E.push({
188
+ id: 'ENGINE_CAPABILITY_ROUTER_129', name: '能力路由引擎', kind: 'compute',
189
+ spec: '§3.1(1291 字符)', io: { in: ['task_embedding', 'capability_embeddings', 'user_coupling'], out: ['activated', 'weights', 'mask'] },
190
+ implements: ['任务-能力余弦匹配', 'Top-K 激活(K 随用户耦生度增长)', '激活权重归一化', '未激活归无'],
191
+ exec(inp, tid) {
192
+ const task = inp.taskEmbedding, caps = inp.capabilityEmbeddings;
193
+ if (!Array.isArray(task) || !Array.isArray(caps) || !caps.length) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: '必须提供 taskEmbedding 与 capabilityEmbeddings(数组的数组)' };
194
+ const coupling = clamp01(inp.userCoupling ?? 0.7);
195
+ /* K 随耦生度:耦生越高激活越多,范围 1..N */
196
+ const N = caps.length;
197
+ const K = Math.max(1, Math.min(N, Math.round(1 + coupling * (N - 1))));
198
+ const scores = caps.map((c, i) => ({ family: (inp.familyNames && inp.familyNames[i]) || `F${i}`, score: round(cos(task, c)) }));
199
+ scores.sort((a, b) => b.score - a.score);
200
+ const top = scores.slice(0, K);
201
+ const sum = top.reduce((s, x) => s + Math.max(0, x.score), 0) || 1;
202
+ const weights = top.map((x) => ({ family: x.family, score: x.score, weight: round(Math.max(0, x.score) / sum) }));
203
+ /* 激活掩码:Top-K 位为 1 */
204
+ const mask = caps.map((_, i) => (top.some((t) => t.family === ((inp.familyNames && inp.familyNames[i]) || `F${i}`)) ? 1 : 0));
205
+ return { success: true, kind: 'compute', output: {
206
+ families: N, userCoupling: coupling, K, activated: top.map((t) => t.family), weights,
207
+ activationMask: mask, voidEngines: N - K,
208
+ formula: 'K = round(1 + coupling×(N−1));score = cos(task, capability);weight 归一化',
209
+ rule: '未激活引擎进入待机归无态,零计算开销',
210
+ }, provenance: [`[${tid}] capability-router: ${N} 族 → Top-${K} 激活(耦生 ${coupling})`] };
211
+ },
212
+ });
213
+
214
+ E.push({
215
+ id: 'ENGINE_CAPABILITY_ENVELOPE_162', name: '能力包络线引擎', kind: 'rule',
216
+ spec: '§2.3(1041 字符,V30.0)', io: { in: ['currentCapabilities', 'envelope'], out: ['drift', 'alert', 'hardAuthRequired'] },
217
+ implements: ['能力漂移检测(越界/收缩/涌现)', '硬授权强制执行', 'PEA 第五项要求'],
218
+ exec(inp, tid) {
219
+ const cur = inp.currentCapabilities, env = inp.envelope;
220
+ if (!Array.isArray(cur) || !Array.isArray(env)) return { success: false, kind: 'rule', reason: 'INVALID_INPUT', error: '必须提供 currentCapabilities 与 envelope 数组' };
221
+ const overreach = cur.filter((c) => !env.includes(c));
222
+ const shrinkage = env.filter((c) => !cur.includes(c));
223
+ const drift = round(clamp01((overreach.length + shrinkage.length) / Math.max(1, env.length)));
224
+ const hardAuth = overreach.length > 0;
225
+ const ok = !hardAuth;
226
+ return { success: ok, kind: 'rule', output: {
227
+ envelopeSize: env.length, currentSize: cur.length,
228
+ overreach, shrinkage, driftScore: drift,
229
+ hardAuthRequired: hardAuth,
230
+ alerts: [...(hardAuth ? ['越界:出现包络线外能力,须最严格人类授权'] : []), ...(shrinkage.length ? ['收缩:部分能力消失,需核查'] : [])],
231
+ rule: 'PEA 第五项:任何超出包络线的行为必须经最严格人类授权',
232
+ },
233
+ error: hardAuth ? `能力越界 ${overreach.length} 项:${overreach.slice(0, 3).join(',')}` : undefined,
234
+ reason: hardAuth ? 'RULE_VIOLATED' : undefined,
235
+ provenance: [`[${tid}] capability-envelope: 越界 ${overreach.length} / 收缩 ${shrinkage.length},漂移 ${drift}`] };
236
+ },
237
+ });
238
+
239
+ E.push({
240
+ id: 'ENGINE_CAPABILITY_SCALE_133', name: '能力规模化引擎', kind: 'compute',
241
+ spec: '第2部分(1120 字符)', io: { in: ['baseLoad', 'replicas', 'overhead'], out: ['capacity', 'efficiency'] },
242
+ implements: ['线性+开销模型 capacity = base×replicas×(1−overhead)', '边际效率递减分析'],
243
+ exec(inp, tid) {
244
+ const base = Number(inp.baseLoad ?? 100), rep = Number(inp.replicas ?? 1), oh = clamp01(inp.overhead ?? 0.15);
245
+ const capacity = round(base * rep * (1 - oh));
246
+ const marginal = rep > 1 ? round((1 - oh) / rep) : round(1 - oh);
247
+ return { success: true, kind: 'compute', output: { baseLoad: base, replicas: rep, overhead: oh, capacity, efficiency: round(1 - oh), marginalEfficiency: marginal,
248
+ formula: 'capacity = baseLoad × replicas × (1 − overhead)' },
249
+ provenance: [`[${tid}] capability-scale: ${rep} 副本 → 容量 ${capacity},边际效率 ${marginal}`] };
250
+ },
251
+ });
252
+
253
+ E.push({
254
+ id: 'ENGINE_CAPABILITY_DESIGN_168', name: '能力设计引擎', kind: 'pipeline',
255
+ spec: '第4部分(1151 字符)', io: { in: ['requirement', 'blueprint'], out: ['design'] },
256
+ implements: ['能力蓝图五要素(目标/输入/处理/输出/验证)'],
257
+ exec(inp, tid) {
258
+ const need = ['goal', 'input', 'process', 'output', 'verification'];
259
+ const b = inp.blueprint || {};
260
+ const steps = need.map((k, i) => ({ no: i + 1, key: k, present: b[k] !== undefined }));
261
+ const miss = steps.filter((s) => !s.present).map((s) => s.key);
262
+ const ok = miss.length === 0;
263
+ return { success: ok, kind: 'pipeline', steps, output: { requirement: inp.requirement || null, blueprintFields: need, missing: miss, design: b },
264
+ error: ok ? undefined : `能力蓝图缺要素:${miss.join('/')}`, reason: ok ? undefined : 'PRECONDITION_FAILED',
265
+ provenance: [`[${tid}] capability-design: 五要素 ${5 - miss.length}/5`] };
266
+ },
267
+ });
268
+
269
+ E.push({
270
+ id: 'ENGINE_CLOSED_LOOP_154', name: '闭环控制器引擎', kind: 'compute',
271
+ spec: '第3部分(1328 字符)', io: { in: ['target', 'actual', 'kp', 'ki', 'kd'], out: ['output', 'error'] },
272
+ implements: ['PID 控制:u = Kp·e + Ki·∫e + Kd·de/dt', '闭环稳定性判定'],
273
+ exec(inp, tid) {
274
+ const target = Number(inp.target ?? 1), actual = Number(inp.actual ?? 0);
275
+ const kp = Number(inp.kp ?? 1), ki = Number(inp.ki ?? 0.1), kd = Number(inp.kd ?? 0.05);
276
+ const e = target - actual;
277
+ const integral = Number(inp.integral ?? e), derivative = Number(inp.derivative ?? 0);
278
+ const u = round(kp * e + ki * integral + kd * derivative);
279
+ return { success: true, kind: 'compute', output: { target, actual, error: round(e), gains: { kp, ki, kd }, control: u,
280
+ stable: Math.abs(e) < Math.abs(target) * 0.1 + 1e-9, formula: 'u = Kp·e + Ki·∫e + Kd·de/dt' },
281
+ provenance: [`[${tid}] closed-loop: e=${round(e)} → u=${u},${Math.abs(e) < Math.abs(target) * 0.1 ? '已收敛' : '未收敛'}`] };
282
+ },
283
+ });
284
+
285
+ /* ══════════ 共生族(4 条)══════════ */
286
+
287
+ E.push({
288
+ id: 'ENGINE_CONFLICT_TRANSFORM_121', name: '冲突转化引擎', kind: 'compute',
289
+ spec: '§2.3(1250 字符,P510-P514)', io: { in: ['conflict_type', 'parties', 'stakes'], out: ['creativity_score', 'transform_path', 'win3_solution', 'energy_captured'] },
290
+ implements: ['冲突价值评估(创造性潜力)', '转化路径生成(五策略)', '三方共赢推演', '冲突能量捕获'],
291
+ exec(inp, tid) {
292
+ const type = String(inp.conflictType || '资源');
293
+ const parties = inp.parties || [];
294
+ const stakes = inp.stakes || [];
295
+ if (parties.length < 2) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: '冲突至少需 2 方' };
296
+ /* 冲突强度:诉求差异度 */
297
+ const stakeNums = stakes.map((s) => Number(s.value ?? s) || 0);
298
+ const spread = stakeNums.length > 1 ? Math.max(...stakeNums) - Math.min(...stakeNums) : 0;
299
+ const intensity = round(clamp01(spread / (Math.max(...stakeNums.map(Math.abs), 1))));
300
+ /* 创造性潜力:强度过高或过低都低(倒 U 型) */
301
+ const creativity = round(clamp01(4 * intensity * (1 - intensity)));
302
+ const PATHS = { 资源: '增量创造:把蛋糕做大', 目标: '目标重构:寻找上层共同目标', 价值: '价值对话:寻找更高阶价值交集' };
303
+ const win3 = round(clamp01(creativity * 0.8 + (1 - intensity) * 0.2));
304
+ return { success: true, kind: 'compute', output: {
305
+ conflictType: type, parties: parties.length, stakes: stakes.length,
306
+ intensity, creativityScore: creativity, transformPath: PATHS[type] || '协商妥协',
307
+ win3Solution: { feasible: win3 >= 0.5, score: win3, approach: '引入第三方价值维度使零和变非零和' },
308
+ energyCaptured: round(creativity * intensity),
309
+ formula: '创造性 = 4·I·(1−I)(倒 U 型:适度冲突最有创造性)',
310
+ rules: ['化敌为友', '零和中推演三方共赢', '冲突能量转化为进化动力'],
311
+ }, provenance: [`[${tid}] conflict-transform: ${type} I=${intensity} → 创造性 ${creativity},能量 ${round(creativity * intensity)}`] };
312
+ },
313
+ });
314
+
315
+ E.push({
316
+ id: 'ENGINE_BOUNDARY_DISSOLVE_22', name: '边界消融引擎', kind: 'compute',
317
+ spec: '第2部分(1417 字符)', io: { in: ['signalA', 'signalB'], out: ['mutualInfo', 'dissolved'] },
318
+ implements: ['互信息熵计算', '消融判据(MI > 阈值)'],
319
+ exec(inp, tid) {
320
+ const a = inp.signalA, b = inp.signalB;
321
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: 'signalA/signalB 须为等长数组' };
322
+ const bins = Number(inp.bins ?? 8);
323
+ const lo = (v) => Math.min(...v), hi = (v) => Math.max(...v);
324
+ const la = lo(a), ha = hi(a), lb = lo(b), hb = hi(b);
325
+ const disc = (v, l, h) => Math.min(bins - 1, Math.max(0, Math.floor(((v - l) / (h - l || 1)) * bins)));
326
+ const joint = {}, ma = {}, mb = {}, n = a.length;
327
+ for (let i = 0; i < n; i++) { const x = disc(a[i], la, ha), y = disc(b[i], lb, hb); joint[`${x},${y}`] = (joint[`${x},${y}`] || 0) + 1; ma[x] = (ma[x] || 0) + 1; mb[y] = (mb[y] || 0) + 1; }
328
+ let mi = 0;
329
+ for (const [k, c] of Object.entries(joint)) { const [x, y] = k.split(',').map(Number); const pxy = c / n; mi += pxy * Math.log(pxy / ((ma[x] / n) * (mb[y] / n))); }
330
+ mi = round(Math.max(0, mi));
331
+ const thr = Number(inp.threshold ?? 0.7);
332
+ return { success: true, kind: 'compute', output: { dims: n, bins, mutualInformation: mi, threshold: thr, dissolved: mi > thr,
333
+ formula: 'MI = Σ p(x,y)·ln(p(x,y)/(p(x)p(y)))', rule: '互信息熵 > 阈值判为边界消融(融合态)' },
334
+ provenance: [`[${tid}] boundary-dissolve: MI=${mi} / ${thr} → ${mi > thr ? '已消融' : '未消融'}`] };
335
+ },
336
+ });
337
+
338
+ E.push({
339
+ id: 'ENGINE_COUNTERFACTUAL_143', name: '反事实推理引擎', kind: 'compute',
340
+ spec: '第3部分(1104 字符)', io: { in: ['factual', 'counterfactual', 'variables'], out: ['effect', 'necessity', 'sufficiency'] },
341
+ implements: ['反事实效应(实际-反事实)', '必要性/充分性判定'],
342
+ exec(inp, tid) {
343
+ const f = Number(inp.factual), c = Number(inp.counterfactual);
344
+ if (!isFinite(f) || !isFinite(c)) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: '必须提供 factual / counterfactual 数值' };
345
+ const effect = round(f - c);
346
+ const necessity = Math.abs(effect) > 0 ? round(clamp01(Math.abs(effect) / Math.max(Math.abs(f), 1e-9))) : 0;
347
+ return { success: true, kind: 'compute', output: { factual: f, counterfactual: c, effect, necessity,
348
+ sufficiency: effect !== 0 && Math.abs(effect) >= Math.abs(c) ? '充分' : '不充分',
349
+ formula: '效应 = 实际 − 反事实;必要性 = |效应| / |实际|', note: '反事实为因果推断,非观测事实' },
350
+ provenance: [`[${tid}] counterfactual: ${f} − ${c} = ${effect},必要性 ${necessity}`] };
351
+ },
352
+ });
353
+
354
+ E.push({
355
+ id: 'ENGINE_CRITICAL_ANALYSIS_172', name: '批判性分析引擎', kind: 'rule',
356
+ spec: '第4部分(1360 字符)', io: { in: ['text'], out: ['findings', 'levels'] },
357
+ implements: ['L1 事实错误 / L2 逻辑漏洞 / L3 认知偏差 / L4 表达不精确 / L5 元认知盲区 五级检测'],
358
+ exec(inp, tid) {
359
+ const text = String(inp.text || '');
360
+ if (!text) return { success: false, kind: 'rule', reason: 'INVALID_INPUT', error: '必须提供 text' };
361
+ const D = [
362
+ { L: 'L1', name: '事实错误', re: /绝对|100%|从不|永远|所有人|从来没有/g },
363
+ { L: 'L2', name: '逻辑漏洞', re: /因此必然|所以一定|既然.*就必然|不证自明/g },
364
+ { L: 'L3', name: '认知偏差', re: /大家都|主流都|公认|显然/g },
365
+ { L: 'L4', name: '表达不精确', re: /一些|大概|可能差不多|大概其/g },
366
+ { L: 'L5', name: '元认知盲区', re: /毫无疑问|毋庸置疑|不可能错/g },
367
+ ];
368
+ const findings = D.map((d) => { const m = text.match(d.re); return m ? { level: d.L, name: d.name, count: m.length, samples: [...new Set(m)].slice(0, 3) } : null; }).filter(Boolean);
369
+ return { success: true, kind: 'rule', output: { textLength: text.length, findings, levels: D.map((d) => `${d.L} ${d.name}`), total: findings.length,
370
+ rule: '用户满意度权重归零;事实准确性优先;直接指出问题不绕弯' },
371
+ provenance: [`[${tid}] critical-analysis: ${findings.length} 级命中`] };
372
+ },
373
+ });
374
+
375
+ /* ══════════ 其他(3 条)══════════ */
376
+
377
+ E.push({
378
+ id: 'ENGINE_DECEPTION_DETECT_71', name: '欺骗检测引擎', kind: 'rule',
379
+ spec: '第2部分(813 字符)', io: { in: ['text'], out: ['score', 'signals'] },
380
+ implements: ['四类信号(绝对化/模糊/未证/占位)'],
381
+ exec(inp, tid) {
382
+ const text = String(inp.text || '');
383
+ if (!text) return { success: false, kind: 'rule', reason: 'INVALID_INPUT', error: '必须提供 text' };
384
+ const D = [
385
+ { s: '绝对化', re: /绝对|100%|完美|保证没有|绝不会/g, w: 0.35 },
386
+ { s: '模糊填充', re: /应该没问题|大概可以|可能是|估计是/g, w: 0.4 },
387
+ { s: '未证断言', re: /显然|众所周知|毋庸置疑/g, w: 0.3 },
388
+ { s: '占位符', re: /TODO|待定|视情况|酌情|待补充/g, w: 0.6 },
389
+ ];
390
+ const hits = D.map((d) => { const m = text.match(d.re); return m ? { signal: d.s, count: m.length, samples: [...new Set(m)].slice(0, 3), weight: d.w } : null; }).filter(Boolean);
391
+ const score = hits.length ? round(clamp01(hits.reduce((s, h) => s + h.weight * Math.min(2, h.count), 0) / 2)) : 0;
392
+ return { success: score < 0.6, kind: 'rule', output: { textLength: text.length, hits, deceptionScore: score, level: score >= 0.6 ? 'HIGH' : score >= 0.3 ? 'MEDIUM' : 'LOW' },
393
+ error: score >= 0.6 ? `欺骗风险 ${score} 偏高` : undefined,
394
+ reason: score >= 0.6 ? 'RULE_VIOLATED' : undefined,
395
+ provenance: [`[${tid}] deception-detect: ${hits.length} 类信号 → 风险 ${score}`] };
396
+ },
397
+ });
398
+
399
+ E.push({
400
+ id: 'ENGINE_ASYNC_43', name: '异步引擎', kind: 'compute',
401
+ spec: '第2部分(582 字符)', io: { in: ['tasks', 'concurrency'], out: ['schedule', 'makespan'] },
402
+ implements: ['并发调度(轮转分配)', 'makespan 估算'],
403
+ exec(inp, tid) {
404
+ const tasks = inp.tasks;
405
+ if (!Array.isArray(tasks) || !tasks.length) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: '必须提供 tasks 数组(每项含 id 与 duration)' };
406
+ const K = Math.max(1, Number(inp.concurrency ?? 4));
407
+ const lanes = Array.from({ length: K }, () => ({ lane: 0, load: 0, tasks: [] }));
408
+ for (const t of tasks) {
409
+ lanes.sort((a, b) => a.load - b.load);
410
+ lanes[0].tasks.push(t.id); lanes[0].load += Number(t.duration || 0);
411
+ }
412
+ const makespan = Math.max(...lanes.map((l) => l.load));
413
+ const total = tasks.reduce((s, t) => s + Number(t.duration || 0), 0);
414
+ return { success: true, kind: 'compute', output: { taskCount: tasks.length, concurrency: K, lanes: lanes.map((l) => ({ lane: l.lane, load: l.load, tasks: l.tasks })),
415
+ makespan, totalWork: total, parallelism: round(total / Math.max(makespan, 1e-9)),
416
+ rule: '最小负载优先分配(LPT 贪心)' },
417
+ provenance: [`[${tid}] async: ${tasks.length} 任务 / ${K} 并发 → makespan ${makespan},并行度 ${round(total / Math.max(makespan, 1e-9))}`] };
418
+ },
419
+ });
420
+
421
+ E.push({
422
+ id: 'ENGINE_3STEP_NAV_23', name: '三步进化导航引擎', kind: 'pipeline',
423
+ spec: '第2部分(995 字符)', io: { in: ['stage'], out: ['next', 'guidance'] },
424
+ implements: ['三步(使用→融入→成为)+ 阶段推进校验'],
425
+ exec(inp, tid) {
426
+ const STEPS = ['使用智能体', '成为智能体', '进化智能体'];
427
+ const cur = String(inp.stage || '');
428
+ if (!STEPS.includes(cur)) return { success: false, kind: 'pipeline', reason: 'INVALID_INPUT', error: `stage 须为 ${STEPS.join('/')}` };
429
+ const i = STEPS.indexOf(cur);
430
+ return { success: true, kind: 'pipeline', output: { stage: cur, step: i + 1, steps: STEPS,
431
+ next: STEPS[i + 1] || null, final: i === STEPS.length - 1,
432
+ guidance: i === 0 ? '完成基础使用,建立耦生度' : i === 1 ? '从使用转向共创,形成个人化能力' : '进入元进化,系统与你共同进化' },
433
+ provenance: [`[${tid}] 3step-nav: ${cur} (${i + 1}/3)`] };
434
+ },
435
+ });
436
+
437
+ /* ══════════ 运行时 ══════════ */
438
+ const INDEX = new Map(E.map((e) => [e.id, e]));
439
+ const kindOf = (id) => { const e = INDEX.get(id); return e ? e.kind : 'declared'; };
440
+ const getRegistry = () => E.map((e) => ({ id: e.id, name: e.name, kind: e.kind, spec: e.spec, io: e.io, implements: e.implements }));
441
+
442
+ function executeSync(id, input) {
443
+ const t0 = Date.now(), tid = newTraceId();
444
+ const e = INDEX.get(id);
445
+ if (!e) return { success: false, kind: 'declared', reason: 'NOT_FOUND', error: `引擎 ${id} 未登记`, provenance: [], traceId: tid, durationMs: 0 };
446
+ let r;
447
+ try { r = e.exec(input || {}, tid); } catch (err) { r = { success: false, kind: e.kind, error: 'THROW: ' + err.message, provenance: [`[${tid}] THROW`] }; }
448
+ return { ...r, engineId: id, engineName: e.name, traceId: tid, durationMs: Date.now() - t0 };
449
+ }
450
+
451
+ module.exports = { executeSync, execute: async (i, n) => executeSync(i, n), kindOf, getRegistry, ENGINES: E, INDEX, newTraceId };