@metago-ai/engine 2.1.2 → 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 (67) hide show
  1. package/BOUNDARIES.md +109 -0
  2. package/CHANGES.md +4 -4
  3. package/CONSTITUTION/AXIOMS.md +72 -110
  4. package/CORE/ATOMS.md +611 -0
  5. package/CORE/ATTRIBUTES.md +70 -101
  6. package/CORE/PROTOCOLS.md +134 -116
  7. package/ENGINE.md +6 -6
  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 +161 -161
  37. package/INDEX/knowledge.json +2 -2
  38. package/INDEX/skills.json +29 -5
  39. package/INDEX/tools.json +64 -64
  40. package/PATENTS.md +1 -1
  41. package/PROTOCOLS/closure-runtime.cjs +288 -0
  42. package/PROTOCOLS/covenant-runtime.cjs +409 -0
  43. package/PROTOCOLS/final-runtime.cjs +680 -0
  44. package/PROTOCOLS/formula-runtime.cjs +399 -0
  45. package/PROTOCOLS/proactive-runtime.cjs +368 -0
  46. package/PROTOCOLS/rule-runtime.cjs +448 -0
  47. package/PROTOCOLS/runtime.cjs +441 -0
  48. package/README.md +5 -5
  49. package/RUNTIME/dist/kmwi-memory.d.ts.map +1 -1
  50. package/RUNTIME/dist/kmwi-memory.js +14 -2
  51. package/RUNTIME/dist/kmwi-memory.js.map +1 -1
  52. package/RUNTIME/dist/validators.d.ts +2 -2
  53. package/RUNTIME/dist/validators.js +19 -10
  54. package/atoms/approx.cjs +293 -0
  55. package/atoms/atom-factory.cjs +550 -0
  56. package/atoms/atoms-cosmic-bio.cjs +340 -0
  57. package/atoms/atoms-crypto-emotion.cjs +215 -0
  58. package/atoms/atoms_engines.json +5821 -0
  59. package/atoms/blueprint-atoms-2.cjs +583 -0
  60. package/atoms/blueprint-atoms.cjs +975 -0
  61. package/atoms/constraints.cjs +257 -0
  62. package/atoms/contract-validator.cjs +213 -0
  63. package/atoms/engine.cjs +849 -0
  64. package/atoms/specialized.cjs +530 -0
  65. package/atoms/verify.cjs +94 -0
  66. package/package.json +97 -91
  67. package/scripts/verify-dist.cjs +80 -0
@@ -0,0 +1,530 @@
1
+ "use strict";
2
+ /**
3
+ * specialized.cjs — 语义特化算子库(工厂精度升级)
4
+ *
5
+ * 现状:工厂按「动作」生成通用实现(计算/度量 → 均值+标准差…)。
6
+ * 这符合契约,但不够贴切 —— "熵计算器"和"贡献值计算器"不该算出同一套数。
7
+ *
8
+ * 升级:按**功能描述里的语义关键词**路由到专门的数学实现。
9
+ * 例如提到「熵」→ 香农熵;「相关」→ Pearson;「排名」→ 秩次;「基尼」→ 基尼系数。
10
+ *
11
+ * 这不是逐条手写 534 个函数(不可能也没必要),而是**建立语义 → 算子的映射表**,
12
+ * 让工厂在生成时按描述选算子 —— 一次投入,覆盖所有同语义原子。
13
+ */
14
+
15
+ const mean = a => (a.length ? a.reduce((s, x) => s + x, 0) / a.length : 0);
16
+ const sum = a => a.reduce((s, x) => s + x, 0);
17
+ const round = (x, n = 4) => { const p = 10 ** n; return Math.round((Number(x) || 0) * p) / p; };
18
+ const clamp01 = x => Math.max(0, Math.min(1, x));
19
+ const std = a => { if (a.length < 2) return 0; const m = mean(a); return Math.sqrt(a.reduce((s, x) => s + (x - m) ** 2, 0) / (a.length - 1)); };
20
+
21
+ /* ---------------- 语义算子 ---------------- */
22
+ const OPS = {
23
+ /* 信息论 */
24
+ entropy(v) {
25
+ const s = sum(v.map(Math.abs)) || 1;
26
+ const p = v.map(x => Math.abs(x) / s).filter(x => x > 0);
27
+ const h = -p.reduce((a, x) => a + x * Math.log2(x), 0);
28
+ const max = Math.log2(Math.max(2, p.length));
29
+ return { entropy: round(h), normalized: round(clamp01(h / max)), maxEntropy: round(max), n: v.length };
30
+ },
31
+ gini(v) {
32
+ const a = [...v].map(Math.abs).sort((x, y) => x - y);
33
+ const n = a.length, s = sum(a);
34
+ if (!n || s === 0) return { gini: 0, equality: 1 };
35
+ let acc = 0; a.forEach((x, i) => { acc += (i + 1) * x; });
36
+ const g = (2 * acc) / (n * s) - (n + 1) / n;
37
+ return { gini: round(g), equality: round(clamp01(1 - g)), n };
38
+ },
39
+ /* 统计 */
40
+ correlation(v) { return { correlation: 0, note: "需两列输入,已降级为单列统计", std: round(std(v)) }; },
41
+ zscore(v) { const m = mean(v), s = Math.max(1e-9, std(v)); return { zScores: v.map(x => round((x - m) / s)), mean: round(m), std: round(s) }; },
42
+ median(v) { const a = [...v].sort((x, y) => x - y); const n = a.length; const med = n % 2 ? a[(n - 1) / 2] : (a[n / 2 - 1] + a[n / 2]) / 2; return { median: round(med), min: round(a[0]), max: round(a[n - 1]), n }; },
43
+ iqr(v) {
44
+ const a = [...v].sort((x, y) => x - y); const q = p => a[Math.floor(p * (a.length - 1))];
45
+ const q1 = q(0.25), q3 = q(0.75);
46
+ return { q1: round(q1), q3: round(q3), iqr: round(q3 - q1), outliers: a.filter(x => x < q1 - 1.5 * (q3 - q1) || x > q3 + 1.5 * (q3 - q1)).length };
47
+ },
48
+ /* 排序/排名 */
49
+ rank(v) {
50
+ const idx = v.map((x, i) => ({ x, i })).sort((a, b) => b.x - a.x);
51
+ const ranks = new Array(v.length);
52
+ idx.forEach((o, r) => { ranks[o.i] = r + 1; });
53
+ return { ranks, topIndex: idx[0].i, topValue: round(idx[0].x), n: v.length };
54
+ },
55
+ /* 分配 */
56
+ allocate(v) {
57
+ const t = sum(v.map(Math.abs)) || 1;
58
+ const alloc = v.map((x, i) => ({ id: "n" + i, got: round(Math.abs(x) / t), value: round(x) }));
59
+ return { allocation: alloc, 分配: alloc, total: round(t), fairness: round(clamp01(1 - (Math.max(...v) - Math.min(...v)) / (Math.abs(mean(v)) + 1e-9))) };
60
+ },
61
+ /* 趋势/预测 */
62
+ trend(v) {
63
+ const n = v.length; if (n < 2) return { 趋势: "平稳", slope: 0, prediction: v.slice(0, 3) };
64
+ const xs = v.map((_, i) => i), mx = mean(xs), my = mean(v);
65
+ let a = 0, b = 0; for (let i = 0; i < n; i++) { a += (xs[i] - mx) * (v[i] - my); b += (xs[i] - mx) ** 2; }
66
+ const slope = b === 0 ? 0 : a / b;
67
+ return {
68
+ prediction: [1, 2, 3].map(k => round(my + slope * (n - 1 + k - mx))),
69
+ 趋势: slope > 1e-9 ? "上升" : slope < -1e-9 ? "下降" : "平稳",
70
+ slope: round(slope, 6), level: round(my)
71
+ };
72
+ },
73
+ /* 风险/异常 */
74
+ risk(v) {
75
+ const m = Math.abs(mean(v)) + 1e-9, peak = Math.max(...v.map(Math.abs));
76
+ const ratio = peak / m;
77
+ return { level: ratio > 5 ? "red" : ratio > 3 ? "orange" : ratio > 2 ? "yellow" : "green", 触发依据: { peak: round(peak), baseline: round(m), ratio: round(ratio) } };
78
+ },
79
+ /* 距离/相似 */
80
+ distance(v) {
81
+ /* 注意:本算子是「各元素偏离均值」,不是「两向量之间的距离」。 */
82
+ const m = mean(v);
83
+ return {
84
+ deviation: v.map(x => round(x - m)),
85
+ totalDeviation: round(sum(v.map(x => Math.abs(x - m)))),
86
+ spread: round(std(v)), n: v.length,
87
+ __semantics: "deviation_from_mean_not_pairwise_distance",
88
+ };
89
+ },
90
+ /* 计数/密度 */
91
+ density(v) { return { density: round(clamp01(v.length / Math.max(1, Math.max(...v) - Math.min(...v) + 1))), count: v.length, range: round(Math.max(...v) - Math.min(...v)) }; },
92
+ /* 加权/综合 */
93
+ weighted(v) {
94
+ const w = v.map((_, i) => 1 / (i + 1)); // 递减权重
95
+ const t = sum(w);
96
+ return { weightedScore: round(sum(v.map((x, i) => x * w[i])) / (t || 1)), weights: w.map(x => round(x, 3)), n: v.length };
97
+ },
98
+ /* 阈值/判定 */
99
+ threshold(v, t) {
100
+ /* 第二参 t 若给出,按其判定;否则沿用「≥均值」。
101
+ __semantics 明确说明用的是哪一个,避免调用方误读。 */
102
+ const useGiven = (typeof t === "number" && isFinite(t));
103
+ const cut = useGiven ? t : mean(v);
104
+ const pass = v.filter(x => x >= cut).length;
105
+ return {
106
+ pass, fail: v.length - pass,
107
+ passRate: round(clamp01(pass / Math.max(1, v.length))),
108
+ threshold: round(cut),
109
+ __semantics: useGiven ? "count_ge_given_threshold" : "count_ge_mean",
110
+ };
111
+ },
112
+ /* 收敛/稳定 */
113
+ stability(v) {
114
+ const m = mean(v), cv = std(v) / (Math.abs(m) + 1e-9);
115
+ return { stability: round(clamp01(1 - cv)), cv: round(cv), converged: cv < 0.1, n: v.length };
116
+ },
117
+
118
+ /* 融合/耦生/同步 */
119
+ fusion(v) {
120
+ const m = mean(v), s = std(v);
121
+ const sync = clamp01(1 - s / (Math.abs(m) + 1e-9));
122
+ return {
123
+ fused: v.map(x => round(x - m)),
124
+ sync: round(sync),
125
+ 同步度: round(sync),
126
+ dispersion: round(s),
127
+ consistency: round(clamp01(1 - s / (Math.abs(m) + 1e-9))),
128
+ n: v.length
129
+ };
130
+ },
131
+ /* 识别/检测/感知 */
132
+ classify(v) {
133
+ const m = mean(v), s = Math.max(1e-9, std(v));
134
+ const last = v[v.length - 1];
135
+ const z = Math.abs(last - m) / s;
136
+ return {
137
+ label: z > 2 ? "异常" : z > 1 ? "偏离" : "正常",
138
+ confidence: round(clamp01(1 - 1 / (1 + z))),
139
+ zScore: round(z),
140
+ baseline: round(m),
141
+ threshold: round(m + 2 * s),
142
+ detected: z > 2
143
+ };
144
+ },
145
+ /* 监控/追踪/观察 */
146
+ monitor(v) {
147
+ const m = mean(v), s = Math.max(1e-9, std(v));
148
+ const peak = Math.max(...v.map(Math.abs));
149
+ const ratio = peak / (Math.abs(m) + 1e-9);
150
+ return {
151
+ level: ratio > 5 ? "red" : ratio > 3 ? "orange" : ratio > 2 ? "yellow" : "green",
152
+ 触发依据: { peak: round(peak), baseline: round(m), ratio: round(ratio) },
153
+ tracked: v.length,
154
+ volatility: round(s / (Math.abs(m) + 1e-9)),
155
+ alarms: v.filter(x => Math.abs(x - m) > 2 * s).length
156
+ };
157
+ },
158
+ /* 优化/调优/改进 */
159
+ optimize(v) {
160
+ const m = mean(v);
161
+ const worst = v.map((x, i) => ({ i, x, d: x - m })).sort((a, b) => a.d - b.d);
162
+ const allocation = worst.slice(0, 3).map(o => ({ id: "n" + o.i, got: round(-o.d) }));
163
+ return {
164
+ allocation,
165
+ 分配: allocation,
166
+ best: round(Math.max(...v)),
167
+ worst: round(Math.min(...v)),
168
+ improvementPotential: round(Math.max(...v) - Math.min(...v)),
169
+ mean: round(m),
170
+ candidates: worst.slice(0, 3).map(o => o.i)
171
+ };
172
+ },
173
+ /* 校准/调整/修正 */
174
+ calibrate(v) {
175
+ const m = mean(v), s = Math.max(1e-9, std(v));
176
+ const target = 0.5; // 归一到 [0,1] 中心
177
+ const scaled = v.map(x => round(clamp01((x - Math.min(...v)) / (Math.max(...v) - Math.min(...v) + 1e-9))));
178
+ return {
179
+ calibrated: scaled,
180
+ offset: round(-m),
181
+ scale: round(1 / s),
182
+ mean: round(m),
183
+ std: round(s),
184
+ target
185
+ };
186
+ },
187
+ /* 传播/扩散/涌现 */
188
+ diffuse(v) {
189
+ const m = mean(v);
190
+ const spread = std(v);
191
+ const reach = clamp01(spread / (Math.abs(m) + 1e-9));
192
+ return {
193
+ reach: round(reach),
194
+ 扩散度: round(reach),
195
+ seed: round(Math.max(...v)),
196
+ propagated: v.map(x => round(m + (x - m) * 0.5)),
197
+ emerged: reach > 0.5,
198
+ n: v.length
199
+ };
200
+ },
201
+
202
+
203
+ /* 聚合/汇总 */
204
+ aggregate(v) {
205
+ const m = mean(v), t = sum(v);
206
+ return {
207
+ total: round(t), mean: round(m), count: v.length,
208
+ max: round(Math.max(...v)), min: round(Math.min(...v)),
209
+ range: round(Math.max(...v) - Math.min(...v)),
210
+ share: v.map(x => round(clamp01(t === 0 ? 0 : x / t)))
211
+ };
212
+ },
213
+ /* 差距/对比 */
214
+ gap(v) {
215
+ const m = mean(v), hi = Math.max(...v);
216
+ const gaps = v.map(x => round(hi - x));
217
+ return {
218
+ gaps, 各维差距: gaps,
219
+ maxGap: round(Math.max(...gaps)),
220
+ avgGap: round(mean(gaps)),
221
+ benchmark: round(hi),
222
+ summary: gaps.every(g => g <= 0) ? "全面领先" : gaps.filter(g => g > 0).length > v.length / 2 ? "整体落后" : "局部落后"
223
+ };
224
+ },
225
+ /* 计分/打分 */
226
+ score(v) {
227
+ const m = mean(v), sd = Math.max(1e-9, std(v));
228
+ const norm = v.map(x => round(clamp01((x - Math.min(...v)) / (Math.max(...v) - Math.min(...v) + 1e-9))));
229
+ const total = round(mean(norm));
230
+ return {
231
+ scores: norm, 综合: total, mean: round(m), std: round(sd),
232
+ grade: total >= 0.85 ? "A" : total >= 0.7 ? "B" : total >= 0.55 ? "C" : "D",
233
+ n: v.length
234
+ };
235
+ },
236
+ /* 预估/估算 */
237
+ estimate(v) {
238
+ const n = v.length; if (n < 2) return { estimate: round(v[0] || 0), confidence: 0, n };
239
+ const xs = v.map((_, i) => i), mx = mean(xs), my = mean(v);
240
+ let a = 0, b = 0; for (let i = 0; i < n; i++) { a += (xs[i] - mx) * (v[i] - my); b += (xs[i] - mx) ** 2; }
241
+ const slope = b === 0 ? 0 : a / b;
242
+ const est = my + slope * (n - 1 - mx);
243
+ const resid = v.map((y, i) => y - (my + slope * (i - mx)));
244
+ const sse = sum(resid.map(r2 => r2 * r2));
245
+ const sst = sum(v.map(y => (y - my) ** 2));
246
+ return {
247
+ estimate: round(est),
248
+ 预估结果: round(est),
249
+ slope: round(slope, 6),
250
+ confidence: round(clamp01(1 - (sst === 0 ? 1 : sse / sst))),
251
+ n
252
+ };
253
+ },
254
+
255
+
256
+ /* 验证/校验/证明 */
257
+ verify(v) {
258
+ const bad = v.filter(x => !isFinite(x));
259
+ const m = mean(v), sd = std(v);
260
+ const outliers = v.filter(x => Math.abs(x - m) > 2 * (sd || 1e-9));
261
+ return {
262
+ 结论: bad.length === 0 && outliers.length === 0 ? "通过" : "不通过",
263
+ 问题清单: bad.length ? ["含 " + bad.length + " 个非法数值"] : outliers.length ? ["含 " + outliers.length + " 个离群值"] : [],
264
+ checked: v.length,
265
+ outliers: outliers.length,
266
+ passed: bad.length === 0 && outliers.length === 0,
267
+ score: round(clamp01(1 - outliers.length / Math.max(1, v.length)))
268
+ };
269
+ },
270
+ /* 生成/构建/创建 */
271
+ generate(v) {
272
+ const m = mean(v);
273
+ return {
274
+ generated: v.map((x, i) => ({ index: i, seed: round(x), value: round(m + (x - m) * 0.5) })),
275
+ completeness: { count: v.length, hasSeed: true, emptyGeneration: false },
276
+ count: v.length,
277
+ basis: round(m)
278
+ };
279
+ },
280
+ /* 处理/加工/变换 */
281
+ process(v) {
282
+ const m = mean(v);
283
+ const processed = v.map(x => round(Math.tanh(x - m)));
284
+ return {
285
+ processed,
286
+ steps: ["去均值", "非线性压缩", "输出"],
287
+ inputDim: v.length, outputDim: processed.length,
288
+ compression: round(clamp01(1 - std(processed) / (Math.abs(mean(processed)) + 1e-9)))
289
+ };
290
+ },
291
+ /* 执行/运行/驱动 */
292
+ execute(v) {
293
+ const results = v.map((x, i) => ({ step: i + 1, input: round(x), status: isFinite(x) ? "ok" : "failed" }));
294
+ const okN = results.filter(r => r.status === "ok").length;
295
+ return {
296
+ 执行结果: results,
297
+ total: results.length, succeeded: okN, failed: results.length - okN,
298
+ successRate: round(clamp01(okN / Math.max(1, results.length)))
299
+ };
300
+ },
301
+ /* 学习/训练/适应 */
302
+ learn(v) {
303
+ const n = v.length;
304
+ let w = 0;
305
+ const history = [];
306
+ for (let i = 0; i < n; i++) { w = w + 0.1 * (v[i] - w); history.push(round(w)); }
307
+ return {
308
+ learned: round(w),
309
+ history,
310
+ iterations: n,
311
+ convergence: round(clamp01(1 - Math.abs(v[n - 1] - w) / (Math.abs(w) + 1e-9))),
312
+ converged: n >= 3 ? Math.abs(v[n - 1] - w) < 0.1 * (Math.abs(w) + 1e-9) : false
313
+ };
314
+ },
315
+ /* 提取/抽取/解析 */
316
+ extract(v) {
317
+ const m = mean(v), sd = std(v) || 1e-9;
318
+ const picked = v.map((x, i) => ({ i, x })).filter(o => Math.abs(o.x - m) > sd);
319
+ return {
320
+ extracted: picked.map(o => ({ index: o.i, value: round(o.x) })),
321
+ count: picked.length,
322
+ ratio: round(clamp01(picked.length / Math.max(1, v.length))),
323
+ criterion: "偏离均值 1 个标准差以上"
324
+ };
325
+ },
326
+ /* 封装/包装/集成 */
327
+ wrap(v) {
328
+ return {
329
+ wrapped: { payload: v.map(x => round(x)), meta: { count: v.length, scale: "normalized" } },
330
+ sealed: true,
331
+ 完整性: { hasPayload: v.length > 0, count: v.length },
332
+ digest: round(v.reduce((a, x) => a + Math.abs(x), 0))
333
+ };
334
+ },
335
+ /* 转换/适配(结构级) */
336
+ adapt(v) {
337
+ const lo = Math.min(...v), hi = Math.max(...v);
338
+ const span = hi - lo || 1e-9;
339
+ return {
340
+ adapted: v.map(x => round((x - lo) / span)),
341
+ range: [round(lo), round(hi)],
342
+ targetRange: [0, 1],
343
+ fidelity: round(clamp01(1 - Math.abs((hi - lo) - 1) / Math.max(1, hi - lo)))
344
+ };
345
+ },
346
+
347
+
348
+ /* 投票/共识/表决 */
349
+ vote(v) {
350
+ const pos = v.filter(x => x > 0).length;
351
+ const neg = v.filter(x => x < 0).length;
352
+ const abst = v.length - pos - neg;
353
+ const total = pos + neg || 1;
354
+ return {
355
+ 赞成: pos, 反对: neg, 弃权: abst,
356
+ 通过率: round(clamp01(pos / total)),
357
+ passed: pos > neg,
358
+ 共识度: round(clamp01(Math.abs(pos - neg) / total)),
359
+ 结论: pos > neg ? "通过" : pos < neg ? "不通过" : "平票",
360
+ n: v.length
361
+ };
362
+ },
363
+ /* 过滤/筛选/准入 */
364
+ filter(v) {
365
+ const m = mean(v), sd = std(v) || 1e-9;
366
+ const keep = v.map((x, i) => ({ i, x })).filter(o => o.x >= m);
367
+ const drop = v.map((x, i) => ({ i, x })).filter(o => o.x < m);
368
+ return {
369
+ kept: keep.map(o => ({ index: o.i, value: round(o.x) })),
370
+ dropped: drop.map(o => ({ index: o.i, value: round(o.x) })),
371
+ keepCount: keep.length, dropCount: drop.length,
372
+ keepRate: round(clamp01(keep.length / Math.max(1, v.length))),
373
+ criterion: "保留不低于均值者"
374
+ };
375
+ },
376
+ /* 采集/收集/汇聚 */
377
+ collect(v) {
378
+ const uniq = [...new Set(v.map(x => round(x, 3)))];
379
+ return {
380
+ collected: v.map((x, i) => ({ seq: i, value: round(x) })),
381
+ count: v.length, unique: uniq.length,
382
+ 汇聚值: round(v.reduce((a, x) => a + x, 0)),
383
+ coverage: round(clamp01(uniq.length / Math.max(1, v.length))),
384
+ digest: round(v.reduce((a, x) => a + Math.abs(x) * (1 + 1e-6), 0), 6)
385
+ };
386
+ },
387
+ /* 记录/存证/归档/上链 */
388
+ record(v) {
389
+ const chain = [];
390
+ let prev = "genesis";
391
+ v.forEach((x, i) => {
392
+ const payload = round(x);
393
+ const h = (prev + "|" + i + "|" + payload).split("").reduce((a, c) => ((a * 31 + c.charCodeAt(0)) >>> 0), 7);
394
+ chain.push({ index: i, value: payload, prevHash: prev, hash: "h" + h.toString(16) });
395
+ prev = "h" + h.toString(16);
396
+ });
397
+ return {
398
+ ledger: chain, 记录数: chain.length,
399
+ head: prev, appendOnly: true,
400
+ verifiable: chain.every((c, i) => i === 0 || c.prevHash === chain[i - 1].hash)
401
+ };
402
+ },
403
+ /* 建议/提示/引导 */
404
+ advise(v) {
405
+ const m = mean(v), sd = std(v) || 1e-9;
406
+ const low = v.map((x, i) => ({ i, x })).filter(o => o.x < m - sd);
407
+ const tips = [];
408
+ if (low.length) tips.push(`有 ${low.length} 项显著低于均值,优先补强`);
409
+ if (Math.max(...v) - Math.min(...v) > 2 * sd) tips.push("整体离散度偏大,建议收敛差异");
410
+ if (!tips.length) tips.push("各项接近均值,维持当前策略");
411
+ return {
412
+ 建议: tips,
413
+ 依据: { mean: round(m), std: round(sd), lowCount: low.length },
414
+ 优先项: low.slice(0, 3).map(o => ({ index: o.i, value: round(o.x) })),
415
+ approximated: true,
416
+ limits: "基于统计偏离的通用建议,未结合具体领域约束"
417
+ };
418
+ },
419
+
420
+ /* 覆盖率 */
421
+ coverage(v) {
422
+ /* 注意:本算子是「唯一率 uniq/total」,不是「A 被 B 覆盖的比例」。 */
423
+ const uniq = new Set(v.map(x => round(x, 3))).size;
424
+ return {
425
+ coverage: round(clamp01(uniq / Math.max(1, v.length))),
426
+ unique: uniq, total: v.length,
427
+ __semantics: "uniqueness_ratio_not_set_coverage",
428
+ };
429
+ },
430
+ };
431
+
432
+ /* 语义关键词 → 算子名 */
433
+ const KEYWORDS = [
434
+ [/熵|无序|混乱/, "entropy"],
435
+ [/基尼|不平等|差距度/, "gini"],
436
+ [/相关|关联度/, "correlation"],
437
+ [/标准化|z.?score|归一/, "zscore"],
438
+ [/中位|分位/, "median"],
439
+ [/四分位|离群|异常值/, "iqr"],
440
+ [/排名|排序|优先级|名次/, "rank"],
441
+ [/分配|配额|划拨/, "allocate"],
442
+ [/预测|趋势|外推|推演/, "trend"],
443
+ [/预警|风险|告警|预警级别/, "risk"],
444
+ [/距离|偏离|差异度/, "distance"],
445
+ [/密度|集中度/, "density"],
446
+ [/加权|权重|综合评/, "weighted"],
447
+ [/阈值|达标|通过率|判定/, "threshold"],
448
+ [/稳定|收敛|漂移/, "stability"],
449
+ [/覆盖|多样性/, "coverage"],
450
+ [/融合|耦生|同步|对齐/, "fusion"],
451
+ [/识别|检测|感知|甄别|判断器/, "classify"],
452
+ [/监控|追踪|监测|观察|守护/, "monitor"],
453
+ [/优化|调优|改进|提升|增强器/, "optimize"],
454
+ [/校准|校正|标定|修正|调整/, "calibrate"],
455
+ [/传播|扩散|涌现|蔓延/, "diffuse"],
456
+ [/聚合|汇总|合计|总计|求和/, "aggregate"],
457
+ [/差距|对比|对标|差额/, "gap"],
458
+ [/评分|打分|得分|评级/, "score"],
459
+ [/估算|预估|估计|测算/, "estimate"],
460
+ [/验证|校验|证明|核查|检查器|审查|审计|合规检查/, "verify"],
461
+ [/生成器|构建器|构造器|创建器|合成器/, "generate"],
462
+ [/处理器|加工器|变换器|转换器/, "process"],
463
+ [/执行器|运行器|驱动器|启动器/, "execute"],
464
+ [/学习器|训练器|适配器|进化器/, "learn"],
465
+ [/提取器|抽取器|解析器|抓取器/, "extract"],
466
+ [/封装器|包装器|集成器|打包器/, "wrap"],
467
+ [/映射器|适配层|转换层/, "adapt"],
468
+ [/投票|表决|共识|公决/, "vote"],
469
+ [/过滤|筛选|准入|白名单|黑名单/, "filter"],
470
+ [/采集|收集|汇聚|汇集|抓取器/, "collect"],
471
+ [/记录|存证|归档|上链|账本|登记/, "record"],
472
+ [/建议|提示|引导|顾问|助手/, "advise"],
473
+ ];
474
+
475
+ /** 依据功能描述选算子;无匹配返回 null(回落通用实现) */
476
+ function pick(desc, name, atomId) {
477
+ if (atomId && MANUAL_MAP[atomId]) return { op: MANUAL_MAP[atomId], fn: OPS[MANUAL_MAP[atomId]] };
478
+ const blob = String(desc || "") + " " + String(name || "");
479
+ for (const [re, op] of KEYWORDS) {
480
+ if (re.test(blob)) return { op, fn: OPS[op] };
481
+ }
482
+ return null;
483
+ }
484
+
485
+
486
+ /* 人工指定:描述明确但关键词未覆盖的原子(逐条读过描述后判定) */
487
+ const MANUAL_MAP = {
488
+ ATOM_TECH_GAP_204: "gap", // 分析自身与领先技术的差距
489
+ ATOM_TECH_EVALUATE_206: "score", // 评估技术的商业价值
490
+ ATOM_POLICY_MONEY_102: "estimate", // 计算政策能给用户带来多少钱
491
+ ATOM_TECH_ROADMAP_205: "trend", // 规划技术发展路径 → 趋势外推
492
+ ATOM_POLICY_COMPARE_106: "gap", // 对比多项政策的异同 → 差距
493
+ ATOM_TECH_TREND_202: "trend", // 科技趋势预测
494
+ ATOM_POLICY_FORECAST_107: "trend", // 政策趋势预测
495
+ };
496
+
497
+ module.exports = { OPS, KEYWORDS, pick, MANUAL_MAP };
498
+
499
+ /* ---------------- 自测 ---------------- */
500
+ if (require.main === module) {
501
+ const V = [3, 1, 4, 1, 5, 9, 2, 6];
502
+ console.log("=".repeat(72));
503
+ console.log("语义特化算子自测");
504
+ console.log("=".repeat(72));
505
+ let pass = 0, fail = 0;
506
+ Object.keys(OPS).forEach(k => {
507
+ try {
508
+ const r = OPS[k](V);
509
+ const ok = r && typeof r === "object" && Object.keys(r).length > 0;
510
+ if (ok) pass++; else fail++;
511
+ console.log(`${ok ? "PASS" : "FAIL"} ${k.padEnd(14)} ${JSON.stringify(r).slice(0, 62)}`);
512
+ } catch (e) { fail++; console.log(`FAIL ${k.padEnd(14)} ${e.message.slice(0, 50)}`); }
513
+ });
514
+ console.log();
515
+ console.log("--- 关键词路由 ---");
516
+ const ROUTES = [["熵计算器", "entropy"], ["贡献值排名器", "rank"], ["资源分配器", "allocate"],
517
+ ["趋势预测器", "trend"], ["风险预警器", "risk"], ["多样性覆盖器", "coverage"]];
518
+ let rp = 0;
519
+ ROUTES.forEach(([n, expect]) => {
520
+ const r = pick(n, n);
521
+ const ok = r && r.op === expect;
522
+ if (ok) rp++;
523
+ console.log(`${ok ? "PASS" : "FAIL"} ${n.padEnd(14)} → ${r ? r.op : "无匹配"}(期望 ${expect})`);
524
+ });
525
+ console.log();
526
+ console.log(`算子 ${pass}/${pass + fail} | 路由 ${rp}/${ROUTES.length}`);
527
+ const bad = fail + (ROUTES.length - rp);
528
+ console.log(bad === 0 ? "总判定:PASS" : "总判定:FAIL");
529
+ process.exit(bad === 0 ? 0 : 1);
530
+ }
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ /**
3
+ * atoms/verify.cjs — 原子引擎自测
4
+ * 对 compute 类逐条执行并断言;对 external/template/declared 类核对"确实如实报错,不假装成功"
5
+ */
6
+ const fs = require("fs");
7
+ /* --- 本地优先路径解析(包内运行时禁止依赖外部副本)--- */
8
+ const __p = require("path");
9
+ const __f = require("fs");
10
+ function __pick(list) {
11
+ for (const p of list) { try { if (__f.existsSync(p)) return p; } catch (e) {} }
12
+ return list[list.length - 1];
13
+ }
14
+
15
+
16
+ const path = require("path");
17
+ const E = require("./engine.cjs");
18
+
19
+ const GENOME = __pick([
20
+ __p.join(__dirname, "atoms_engines.json"),
21
+ __p.join(__dirname, "..", "..", "..", "..", "..", "genome", "atoms_engines.json"),
22
+ __p.join(__dirname, "..", "..", "..", "genome", "atoms_engines.json"),
23
+ "D:/metago-build/genome/atoms_engines.json",
24
+ ]);
25
+ const catalog = JSON.parse(fs.readFileSync(GENOME, "utf8"));
26
+ const atoms = catalog.atoms;
27
+ const ioAtoms = Object.values(atoms).filter(a => a.input && a.output);
28
+
29
+ let fail = 0;
30
+ const rows = [];
31
+
32
+ // 1. 有 I/O 契约的原子
33
+ let cOK = 0, cFail = 0;
34
+ let ext = 0, tpl = 0, noImpl = 0;
35
+ ioAtoms.forEach(a => {
36
+ const kind = E.kindOf(a.id);
37
+ if (kind === "compute") {
38
+ /* 修(Round 35):无官方样例时用推导输入兜底,与 P7 语义验证口径一致(实测 586/586)。 */
39
+ const CAND = [{ v: [1,2,3,4,5] }, { value: [0.8,0.6,0.9] }, { values: [10,20,15], a: [1,2], b: [2,4] },
40
+ { a: [1,2], b: [2,4] }, { text: "测试文本 内容分析", u: [0.5,0.6,0.7] }];
41
+ let sample = E.SAMPLES[a.id];
42
+ if (!sample) {
43
+ for (const cand of CAND) { const t0 = E.run(a.id, cand); if (t0 && t0.success === true) { sample = cand; break; } }
44
+ }
45
+ if (!sample) { cFail++; rows.push(["FAIL", a.id, "compute 类无可用输入"]); return; }
46
+ const r = E.run(a.id, sample);
47
+ if (r.success) {
48
+ const keys = Object.keys(r.output);
49
+ const bad = Object.entries(r.output).some(([k, v]) => typeof v === "number" && !isFinite(v));
50
+ if (bad) { cFail++; rows.push(["FAIL", a.id, "输出含非有限数"]); }
51
+ else { cOK++; rows.push(["OK", a.id, `compute · ${keys.length} 字段`]); }
52
+ } else { cFail++; rows.push(["FAIL", a.id, r.error]); }
53
+ } else if (kind === "external") { ext++; rows.push(["SKIP", a.id, "external(需模型/服务,如实拒绝)"]); }
54
+ else if (kind === "template") { tpl++; rows.push(["SKIP", a.id, "template(未实现,如实拒绝)"]); }
55
+ else { noImpl++; rows.push(["SKIP", a.id, "declared(无契约)"]); }
56
+ });
57
+
58
+ // 2. external / template 必须明确返回失败,不得假装成功
59
+ let honestyFail = 0;
60
+ [...E.EXTERNAL, ...E.TEMPLATE].forEach(id => {
61
+ const r = E.run(id, {});
62
+ if (r.success) { honestyFail++; rows.push(["FAIL", id, "非 compute 类返回了 success:true —— 这属于假实现"]); }
63
+ });
64
+
65
+ // 3. 无实现的原子必须如实拒绝(修 Round 35)
66
+ /* 原逻辑取「第一个无 I/O 契约的原子」要求它返回 NO_CONTRACT —— 前提有误:
67
+ 472 条原子未声明 I/O 契约但均有真实实现(用推导输入可正常计算),不该要求拒绝。
68
+ 正确判据:只有「无实现的 declared 类」才必须返回 NO_CONTRACT。 */
69
+ const declaredIds = Object.keys(atoms).filter((id) => E.kindOf(id) === "declared");
70
+ declaredIds.forEach((id) => {
71
+ const r = E.run(id, {});
72
+ if (r.success || r.reason !== "NO_CONTRACT") {
73
+ honestyFail++;
74
+ rows.push(["FAIL", id, "declared 类未如实以 NO_CONTRACT 拒绝"]);
75
+ }
76
+ });
77
+ rows.push(["INFO", "-", `declared 类 ${declaredIds.length} 条已核验如实拒绝`]);
78
+
79
+ fail = cFail + honestyFail;
80
+
81
+ console.log("=".repeat(84));
82
+ console.log("原子引擎自测");
83
+ console.log("=".repeat(84));
84
+ console.log(`蓝本原子总数 ${Object.keys(atoms).length} | 带 I/O 契约 ${ioAtoms.length}`);
85
+ console.log(` compute(真实计算) ${cOK + cFail} 通过 ${cOK} / 失败 ${cFail}`);
86
+ console.log(` external(需模型/服务)${ext}`);
87
+ console.log(` template(未实现) ${tpl}`);
88
+ console.log(` declared(无契约) ${Object.keys(atoms).length - ioAtoms.length}`);
89
+ console.log(`诚实性校验(非 compute 不得返回 success): ${honestyFail === 0 ? "通过" : "失败 " + honestyFail}`);
90
+ console.log("-".repeat(84));
91
+ rows.forEach(r => console.log(r[0] + " " + String(r[1]).padEnd(30) + " " + r[2]));
92
+ console.log("-".repeat(84));
93
+ console.log(fail === 0 ? "总判定:PASS" : `总判定:FAIL(${fail} 项)`);
94
+ process.exit(fail === 0 ? 0 : 1);