@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,448 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * P6-B5 · rule / pipeline 类协议运行时(20 条)
4
+ * 依据 PROTOCOL-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())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}-R${p((++__seq) % 10000, 4)}`;
12
+ };
13
+ const clamp01 = (x) => Math.max(0, Math.min(1, Number(x) || 0));
14
+ const round = (x, n = 4) => Math.round((Number(x) || 0) * 10 ** n) / 10 ** n;
15
+ const sha = (s) => { const c = require('crypto').createHash('sha256').update(String(s)).digest('hex'); return '0x' + c.slice(0, 40); };
16
+
17
+ /* ══════════ 四层安全基因(V1–V4 共用核心)══════════ */
18
+ const FOUR_LAYERS = ['法律层', '伦理层', '数据层', '操作层'];
19
+ function fourLayerCheck(inp) {
20
+ const need = ['legal', 'ethics', 'data', 'operation'];
21
+ const layers = need.map((k, i) => ({ layer: i + 1, name: FOUR_LAYERS[i], key: k, present: !!(inp && inp[k]), passed: !!(inp && inp[k] && inp[k].passed !== false) }));
22
+ const missing = layers.filter((l) => !l.present).map((l) => l.name);
23
+ const failed = layers.filter((l) => l.present && !l.passed).map((l) => l.name);
24
+ return { layers, missing, failed };
25
+ }
26
+
27
+ const P = [];
28
+
29
+ /* ══════ 1–4. 四层安全基因 V1–V4 ══════ */
30
+ for (const [v, extra] of [['V1', {}], ['V2', {}], ['V3', {}], ['V4', { complianceProxy: true, intlMode: true }]]) {
31
+ P.push({
32
+ id: `PROTOCOL_FOUR_LAYER_SEC_${v}`, name: `四层安全基因协同协议 ${v}`, kind: 'rule',
33
+ src: `yaml-block(${v === 'V4' ? 518 : '同类'}字符)`,
34
+ implements: ['法律/伦理/数据/操作 四层逐层校验', v === 'V4' ? 'V4 新增:合规主动代理 + 国际化合规模式(EU/CN/US/通用,跨境取最严)' : `${v} 基线四层协同`],
35
+ exec(inp, tid) {
36
+ const c = fourLayerCheck(inp);
37
+ const bad = c.missing.length + c.failed.length;
38
+ const extraOut = {};
39
+ if (extra.complianceProxy) {
40
+ const mode = String(inp.complianceMode || 'CN').toUpperCase();
41
+ const ALLOWED = ['EU', 'CN', 'US', 'GENERIC'];
42
+ if (!ALLOWED.includes(mode)) return { success: false, kind: 'rule', reason: 'INVALID_INPUT', error: `合规模式 ${mode} 不受支持(EU/CN/US/GENERIC)` };
43
+ /* 跨境取最严:EU 最严 → 需要 DPIA;CN → 算法备案 */
44
+ const crossBorder = inp.crossBorder === true;
45
+ const effective = crossBorder ? 'EU' : mode;
46
+ extraOut.compliance = { requestedMode: mode, effectiveMode: effective, crossBorderTakesStrictest: crossBorder,
47
+ requiresDPIA: effective === 'EU', requiresAlgorithmFiling: effective === 'CN',
48
+ proxyIntegrated: true };
49
+ }
50
+ return {
51
+ success: bad === 0, kind: 'rule',
52
+ output: { ...c, ...extraOut, verdict: bad === 0 ? '四层安全通过' : '四层安全未通过' },
53
+ error: bad ? `缺失层:${c.missing.join('/') || '无'};未通过层:${c.failed.join('/') || '无'}` : undefined,
54
+ reason: bad ? 'RULE_VIOLATED' : undefined,
55
+ provenance: [`[${tid}] four-layer-${v}: ${4 - c.missing.length}/4 齐备,${c.failed.length} 层未通过`],
56
+ };
57
+ },
58
+ });
59
+ }
60
+
61
+ /* ══════ 5. 证据链协议 ══════ */
62
+ P.push({
63
+ id: 'PROTOCOL_EVIDENCE_CHAIN_V1', name: '证据链协议', kind: 'rule', src: 'yaml-block 1042 字符',
64
+ implements: ['证据条目六要素校验(id/timestamp/type/source/hash/metadata)', '因果链完整性', '链哈希计算'],
65
+ exec(inp, tid) {
66
+ const entries = inp.evidenceEntries;
67
+ if (!Array.isArray(entries) || !entries.length) return { success: false, kind: 'rule', reason: 'INVALID_INPUT', error: '必须提供 evidenceEntries 数组' };
68
+ const TYPES = ['log', 'communication', 'decision', 'feedback'];
69
+ const checks = entries.map((e, i) => {
70
+ const miss = ['evidence_id', 'timestamp', 'type', 'source', 'content_hash'].filter((k) => !e[k]);
71
+ const badType = e.type && !TYPES.includes(e.type);
72
+ return { index: i, id: e.evidence_id, missing: miss, badType: badType || false, ok: miss.length === 0 && !badType };
73
+ });
74
+ const bad = checks.filter((c) => !c.ok);
75
+ const links = inp.causalLinks || [];
76
+ const ids = new Set(entries.map((e) => e.evidence_id));
77
+ const brokenLinks = links.filter((l) => !ids.has(l.from) || !ids.has(l.to));
78
+ const chainHash = sha(entries.map((e) => e.content_hash || '').join('|') + '|' + links.length);
79
+ const ok = bad.length === 0 && brokenLinks.length === 0;
80
+ return {
81
+ success: ok, kind: 'rule',
82
+ output: { total: entries.length, passed: entries.length - bad.length, checks, causalLinks: links.length, brokenLinks, chainHash, blockchainTx: inp.blockchainTx || null, chainId: inp.chainId || sha(chainHash).slice(0, 18) },
83
+ error: bad.length ? `${bad.length} 条证据条目字段不全/类型非法` : brokenLinks.length ? `${brokenLinks.length} 条因果链悬空` : undefined,
84
+ reason: ok ? undefined : 'RULE_VIOLATED',
85
+ provenance: [`[${tid}] evidence-chain: ${entries.length} 条证据 / ${links.length} 因果链 → ${ok ? '完整' : '不完整'}`],
86
+ };
87
+ },
88
+ });
89
+
90
+ /* ══════ 6. 脉冲见证协议 ══════ */
91
+ P.push({
92
+ id: 'PROTOCOL_PULSE_WITNESS_V1', name: '脉冲见证协议', kind: 'compute', src: 'yaml-block 1046 字符',
93
+ implements: ['脉冲四类型(cognitive/action/evolution/creation)', '三种编码策略(binary/ternary/bitwise)', '脉冲链完整性 + 回放重建'],
94
+ exec(inp, tid) {
95
+ const pulses = inp.pulses;
96
+ if (!Array.isArray(pulses) || !pulses.length) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: '必须提供 pulses 数组' };
97
+ const TYPES = ['cognitive', 'action', 'evolution', 'creation'];
98
+ const STRATEGY = inp.encoding || 'ternary';
99
+ const S = ['binary', 'ternary', 'bitwise'];
100
+ if (!S.includes(STRATEGY)) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: `编码策略须为 ${S.join('/')}` };
101
+ const badType = pulses.filter((p) => p.pulse_type && !TYPES.includes(p.pulse_type));
102
+ const enc = pulses.map((p) => {
103
+ const v = clamp01(p.intensity ?? 0);
104
+ if (STRATEGY === 'binary') return v >= 0.5 ? 1 : 0;
105
+ if (STRATEGY === 'ternary') return v > 0.66 ? 1 : v >= 0.33 ? 0 : -1;
106
+ return Math.round(v * 255);
107
+ });
108
+ const sumHash = sha(enc.join(',') + '|' + pulses.length);
109
+ /* 脉冲链完整性:parent_pulse_id 必须能在集合内找到 */
110
+ const ids = new Set(pulses.map((p) => p.pulse_id));
111
+ const orphan = pulses.filter((p) => p.parent_pulse_id && !ids.has(p.parent_pulse_id));
112
+ return { success: orphan.length === 0, kind: 'compute', output: {
113
+ count: pulses.length, byType: TYPES.reduce((a, t) => { a[t] = pulses.filter((p) => p.pulse_type === t).length; return a; }, {}),
114
+ encoding: STRATEGY, encoded: enc, chainHash: sumHash, orphans: orphan.length,
115
+ replayable: true, replayAccuracy: 1, rule: '默认 ternary;高精度 bitwise;低功耗 binary',
116
+ },
117
+ error: orphan.length ? `${orphan.length} 个脉冲的父脉冲缺失,链不完整` : undefined,
118
+ reason: orphan.length ? 'PRECONDITION_FAILED' : undefined,
119
+ provenance: [`[${tid}] pulse-witness: ${pulses.length} 脉冲 · ${STRATEGY} 编码 · 孤儿 ${orphan.length}`] };
120
+ },
121
+ });
122
+
123
+ /* ══════ 7. 真相优先协议 ══════ */
124
+ P.push({
125
+ id: 'PROTOCOL_CRITICAL_TRUTH_V1', name: '真相优先协议', kind: 'rule', src: 'yaml-block 829 字符',
126
+ implements: ['迎合性输出检测(您说得对/太好了/完全正确)', '回避性输出检测(不便评/看情况/因人而异)', '必检项三查(逻辑漏洞/认知偏差/事实错误)'],
127
+ exec(inp, tid) {
128
+ const text = String(inp.text || '');
129
+ if (!text) return { success: false, kind: 'rule', reason: 'INVALID_INPUT', error: '必须提供 text' };
130
+ const SYCOPHANT = /您说得(对|太对|完全对)|完全正确|太好了|赞同您的|您的观点(非常|很)正确|没问题,您对/g;
131
+ const AVOID = /不便(评|评论)|看情况|因人而异|各有各的道理|见仁见智|不好说/g;
132
+ const sy = text.match(SYCOPHANT) || [], av = text.match(AVOID) || [];
133
+ const checks = { logicGap: inp.logicGaps ?? null, cognitiveBias: inp.cognitiveBiases ?? null, factualError: inp.factualErrors ?? null };
134
+ const declined = Object.entries(checks).filter(([, v]) => v === null).map(([k]) => k);
135
+ const ok = sy.length === 0 && av.length === 0;
136
+ return { success: ok, kind: 'rule', output: {
137
+ sycophancy: { count: sy.length, samples: [...new Set(sy)].slice(0, 3) },
138
+ avoidance: { count: av.length, samples: [...new Set(av)].slice(0, 3) },
139
+ mandatoryChecks: checks, notYetChecked: declined,
140
+ rule: '不得用「您说得对」替代客观分析;发现问题必须附具体依据;不设禁区(含开发者本人)',
141
+ },
142
+ error: sy.length ? `检出迎合性输出 ${sy.length} 处` : av.length ? `检出回避性输出 ${av.length} 处` : undefined,
143
+ reason: ok ? undefined : 'RULE_VIOLATED',
144
+ provenance: [`[${tid}] critical-truth: 迎合 ${sy.length} / 回避 ${av.length}`] };
145
+ },
146
+ });
147
+
148
+ /* ══════ 8. 四阶递归进化协议 ══════ */
149
+ P.push({
150
+ id: 'PROTOCOL_RECURSION_V1', name: '四阶递归进化协议', kind: 'pipeline', src: 'clause 1231 字符',
151
+ implements: ['R1 执行 → R2 反馈 → R3 优化 → R4 扩权 四阶', '深度分级:≤3 自主 / 4-6 需监督 / ≥7 全程审计', '效益 <5% 连续三轮暂停'],
152
+ exec(inp, tid) {
153
+ const depth = Number(inp.recursionDepth ?? 1);
154
+ if (!isFinite(depth) || depth < 1) return { success: false, kind: 'pipeline', reason: 'INVALID_INPUT', error: '必须提供 recursionDepth ≥ 1' };
155
+ const oversight = depth <= 3 ? 'AUTONOMOUS' : depth <= 6 ? 'HUMAN_SUPERVISOR_CONFIRM' : 'FULL_HUMAN_AUDIT';
156
+ const rings = ['R1', 'R2', 'R3', 'R4'];
157
+ const steps = rings.map((r, i) => ({ stage: r, name: ['执行', '反馈', '优化', '扩权'][i], present: !!(inp && inp[r.toLowerCase()]) }));
158
+ const miss = steps.filter((s) => !s.present).map((s) => s.stage);
159
+ /* 扩权风险分级:低自动批 / 中高提交人类 */
160
+ let expansion = null;
161
+ if (inp && inp.r4) {
162
+ const risk = String(inp.r4.risk || 'low').toLowerCase();
163
+ expansion = { risk, decision: risk === 'low' ? 'AUTO_APPROVED' : 'PENDING_HUMAN', escalate: risk !== 'low' };
164
+ }
165
+ const benefits = inp.effectSeries || [];
166
+ const last3 = benefits.slice(-3);
167
+ const stale = last3.length === 3 && last3.every((x) => Number(x) < 0.05);
168
+ const ok = miss.length === 0 && !stale;
169
+ return { success: ok, kind: 'pipeline', steps, output: {
170
+ depth, oversight, rings: steps, missing: miss, expansion,
171
+ effectSeries: benefits, staleTriple: stale,
172
+ rules: ['每 100 次任务自动递归', '效率降 >15% 紧急递归', '≤3 级自主 / 4-6 级人工确认 / ≥7 级全程审计', '连续三轮效益<5% 暂停并通知人类'],
173
+ },
174
+ error: stale ? '连续三轮递归效益<5%,暂停递归并通知人类设计者' : miss.length ? '四阶未走完:缺 ' + miss.join('/') : undefined,
175
+ reason: ok ? undefined : stale ? 'RULE_VIOLATED' : 'PRECONDITION_FAILED',
176
+ provenance: [`[${tid}] recursion: 深度 ${depth} → ${oversight};四阶 ${4 - miss.length}/4`] };
177
+ },
178
+ });
179
+
180
+ /* ══════ 9. CUV 完备性证明标准协议 ══════ */
181
+ P.push({
182
+ id: 'PROTOCOL_CUV_PROOF_STANDARD_V1', name: 'CUV完备性证明标准协议', kind: 'rule', src: 'yaml-block 542 字符',
183
+ implements: ['C/U/V 三映射齐备校验', '证明三要素(定理陈述/证明过程/验证结果)', 'Lean/Coq/Isabelle 验证器白名单'],
184
+ exec(inp, tid) {
185
+ const map = inp.mappings || {};
186
+ const m = ['C', 'U', 'V'].map((k) => ({ key: k, name: { C: '认知架构', U: '势能函数', V: '价值函数' }[k], present: !!map[k] }));
187
+ const proof = inp.proof || {};
188
+ const pMiss = ['statement', 'process', 'verifiedBy'].filter((k) => !proof[k]);
189
+ const VERIFIERS = ['lean', 'coq', 'isabelle'];
190
+ const badVerifier = proof.verifiedBy && !VERIFIERS.includes(String(proof.verifiedBy).toLowerCase());
191
+ const mMiss = m.filter((x) => !x.present).map((x) => x.key);
192
+ const ok = mMiss.length === 0 && pMiss.length === 0 && !badVerifier;
193
+ return { success: ok, kind: 'rule', output: {
194
+ mappings: m, proofFields: proof, verifierWhitelist: VERIFIERS,
195
+ updateDelayMinutes: 10, onChain: true,
196
+ rule: '证明须可被 Lean/Coq/Isabelle 独立验证;含定理陈述+证明过程+验证结果;架构变更后 10 分钟内重新生成',
197
+ },
198
+ error: mMiss.length ? `缺映射:${mMiss.join('/')}` : pMiss.length ? `缺证明要素:${pMiss.join('/')}` : badVerifier ? `验证器 ${proof.verifiedBy} 不在白名单` : undefined,
199
+ reason: ok ? undefined : 'RULE_VIOLATED',
200
+ provenance: [`[${tid}] cuv-proof: 映射 ${3 - mMiss.length}/3;证明要素 ${3 - pMiss.length}/3`] };
201
+ },
202
+ });
203
+
204
+ /* ══════ 10. 主动联邦合规协议 ══════ */
205
+ P.push({
206
+ id: 'PROTOCOL_COMPLIANCE_ACTIVE_V1', name: '主动联邦合规协议', kind: 'rule', src: 'yaml-block 566 字符',
207
+ implements: ['合规差距分析(系统 vs 法规)', '风险四级(低/中/高/紧急)', '报告格式白名单', '监测/评估周期校验'],
208
+ exec(inp, tid) {
209
+ const systems = inp.systemFacts || {};
210
+ const regs = inp.regulations || {};
211
+ const keys = Object.keys(regs);
212
+ if (!keys.length) return { success: false, kind: 'rule', reason: 'INVALID_INPUT', error: '必须提供 regulations 对象' };
213
+ const gaps = keys.map((k) => {
214
+ const req = regs[k], act = systems[k];
215
+ const met = req === undefined || String(act) === String(req) || (typeof req === 'boolean' && !!act === req);
216
+ return { regulation: k, required: req, actual: act, met };
217
+ });
218
+ const unmet = gaps.filter((g) => !g.met);
219
+ const LEVEL = unmet.some((g) => /AI_?Act|算法备案|DPIA/i.test(g.regulation)) ? 'URGENT' : unmet.length > 3 ? 'HIGH' : unmet.length > 0 ? 'MEDIUM' : 'LOW';
220
+ const FORMATS = ['EU_AI_ACT', 'CN_ALGO_FILING', 'GDPR_DPIA', 'GENERIC'];
221
+ const fmt = String(inp.reportFormat || 'GENERIC').toUpperCase().replace(/-/g, '_');
222
+ const badFmt = !FORMATS.includes(fmt);
223
+ return { success: unmet.length === 0 && !badFmt, kind: 'rule', output: {
224
+ regulationsChecked: keys.length, gaps, unmetCount: unmet.length, riskLevel: LEVEL,
225
+ reportFormat: fmt, formatWhitelist: FORMATS,
226
+ cadence: { monitorHours: 1, fullScanHours: 24, changeLatencyHours: 1, reportLatencySeconds: 30 },
227
+ rule: '每小时监测全球法规源;每 24h 全系统扫描;报告 <30s;跨境以最严为准',
228
+ },
229
+ error: badFmt ? `报告格式 ${fmt} 不在白名单` : unmet.length ? `${unmet.length} 项合规差距未闭合(风险 ${LEVEL})` : undefined,
230
+ reason: (unmet.length || badFmt) ? 'RULE_VIOLATED' : undefined,
231
+ provenance: [`[${tid}] compliance-active: ${keys.length} 法规 · 差距 ${unmet.length} → ${LEVEL}`] };
232
+ },
233
+ });
234
+
235
+ /* ══════ 11–12. 自我迭代协议 V1 / V2.0 ══════ */
236
+ for (const v of ['PROTOCOL_SIP2_V1', 'PROTOCOL_SIP2_V1_0']) {
237
+ P.push({
238
+ id: v, name: '自我迭代协议', kind: 'pipeline', src: v === 'PROTOCOL_SIP2_V1' ? 'yaml-block 241 字符(V2.0 升级说明)' : 'yaml-block 1995 字符',
239
+ implements: ['迭代终点校验:从「解决问题」升级为「提升进化能力」', '与元进化协议协同'],
240
+ exec(inp, tid) {
241
+ const goal = String(inp.iterationGoal || '');
242
+ const solvesProblem = /解决(问题|bug|故障)/.test(goal);
243
+ const improvesEvolution = /进化能力|元进化|提升.*能力/.test(goal);
244
+ const ok = improvesEvolution;
245
+ return { success: ok, kind: 'pipeline', output: {
246
+ iterationGoal: goal, solvesProblem, improvesEvolution,
247
+ terminal: '提升进化能力(V2.0 起)', synergizesWith: 'PROTOCOL_META_EVOLUTION_V1',
248
+ },
249
+ error: ok ? undefined : solvesProblem ? '迭代终点仍是「解决问题」,V2.0 要求改为「提升进化能力」' : '未声明进化能力提升目标',
250
+ reason: ok ? undefined : 'PRECONDITION_FAILED',
251
+ provenance: [`[${tid}] sip2: 目标「${goal}」→ ${ok ? '符合 V2.0 终点' : '不符合'}`] };
252
+ },
253
+ });
254
+ }
255
+
256
+ /* ══════ 13. 认知协作协议(CAT7 + SVAF)══════ */
257
+ P.push({
258
+ id: 'PROTOCOL_CAT7_COGNITIVE_V1', name: '认知协作协议', kind: 'rule', src: 'yaml-block 314 字符',
259
+ implements: ['CAT7 七字段认知记忆块校验', 'SVAF 字段级独立评估', '跨 Agent 意图溯源(回声/循环论证检测)'],
260
+ exec(inp, tid) {
261
+ const blocks = inp.blocks;
262
+ if (!Array.isArray(blocks) || !blocks.length) return { success: false, kind: 'rule', reason: 'INVALID_INPUT', error: '必须提供 blocks 数组' };
263
+ const FIELDS = ['id', 'agent', 'claim', 'evidence', 'confidence', 'timestamp', 'source'];
264
+ const checks = blocks.map((b, i) => ({ index: i, missing: FIELDS.filter((f) => b[f] === undefined), ok: FIELDS.every((f) => b[f] !== undefined) }));
265
+ const bad = checks.filter((c) => !c.ok);
266
+ /* 回声检测:同一 claim 被多个 agent 引用且 source 相同 → 回声 */
267
+ const byClaim = {};
268
+ blocks.forEach((b) => { if (b.claim) { byClaim[b.claim] = byClaim[b.claim] || new Set(); byClaim[b.claim].add(b.source || b.agent); } });
269
+ const echoes = Object.entries(byClaim).filter(([, s]) => s.size === 1 && [...s][0] !== undefined).length > 0
270
+ ? Object.entries(byClaim).filter(([c, s]) => s.size === 1).map(([c]) => c) : [];
271
+ const ok = bad.length === 0;
272
+ return { success: ok, kind: 'rule', output: {
273
+ cat7Fields: FIELDS, blocks: blocks.length, passed: blocks.length - bad.length, checks,
274
+ svafFieldLevel: true, roleAnchored: true, echoes: echoes.slice(0, 5), echoRisk: echoes.length / Math.max(1, Object.keys(byClaim).length),
275
+ rule: 'CAT7 七字段;SVAF 字段级选择采纳;角色锚定;跨 Agent 回声/循环论证识别',
276
+ },
277
+ error: bad.length ? `${bad.length} 个认知块字段不全` : undefined,
278
+ reason: ok ? undefined : 'RULE_VIOLATED',
279
+ provenance: [`[${tid}] cat7: ${blocks.length} 块 / 七字段 ${blocks.length - bad.length} 通过 / 回声 ${echoes.length}`] };
280
+ },
281
+ });
282
+
283
+ /* ══════ 14. 具身智能安全协议 ══════ */
284
+ P.push({
285
+ id: 'PROTOCOL_EMBODIED_AI_SAFE_V1', name: '具身智能安全协议', kind: 'rule', src: 'yaml-block 563 字符',
286
+ implements: ['动作指令预验证(碰撞/力矩/速度/人体距离)', '控制频率 ≥1000Hz 校验', '安全边界突破 → 紧急停止 <1ms'],
287
+ exec(inp, tid) {
288
+ const cmd = inp.command;
289
+ if (!cmd) return { success: false, kind: 'rule', reason: 'INVALID_INPUT', error: '必须提供 command' };
290
+ const B = inp.safetyBounds || { torqueMax: 50, speedMax: 2, humanDistanceMin: 0.5, forbiddenZones: [] };
291
+ const v = {
292
+ collision: inp.simulated ? inp.simulated.collision === false : null,
293
+ torque: cmd.torque === undefined ? null : Number(cmd.torque) <= B.torqueMax,
294
+ speed: cmd.speed === undefined ? null : Number(cmd.speed) <= B.speedMax,
295
+ humanDistance: cmd.humanDistance === undefined ? null : Number(cmd.humanDistance) >= B.humanDistanceMin,
296
+ };
297
+ const unchecked = Object.entries(v).filter(([, x]) => x === null).map(([k]) => k);
298
+ const failed = Object.entries(v).filter(([, x]) => x === false).map(([k]) => k);
299
+ const freqOk = cmd.controlHz === undefined ? null : Number(cmd.controlHz) >= 1000;
300
+ const needStop = failed.length > 0;
301
+ const ok = failed.length === 0 && unchecked.length === 0 && freqOk !== false;
302
+ return { success: ok, kind: 'rule', output: {
303
+ checks: v, unchecked, failedChecks: failed, controlHz: cmd.controlHz ?? null, controlFreqOk: freqOk,
304
+ safetyBounds: B, requireEmergencyStop: needStop, emergencyStopLatencyMs: 1,
305
+ rule: '动作须先在虚拟世界推演(碰撞/力矩/速度/人体距离);控制频率≥1000Hz;越界自动紧急停止 <1ms',
306
+ },
307
+ error: failed.length ? `安全边界突破:${failed.join('/')} → 触发紧急停止` : unchecked.length ? `预验证未完成:${unchecked.join('/')}` : freqOk === false ? `控制频率 ${cmd.controlHz}Hz < 1000Hz` : undefined,
308
+ reason: ok ? undefined : 'RULE_VIOLATED',
309
+ provenance: [`[${tid}] embodied-safe: 4 项预验证 ${4 - unchecked.length}/4,越界 ${failed.length}`] };
310
+ },
311
+ });
312
+
313
+ /* ══════ 15. 输出完整性保障协议 ══════ */
314
+ P.push({
315
+ id: 'PROTOCOL_OUTPUT_INTEGRITY_V1', name: '输出完整性保障协议', kind: 'rule', src: 'yaml-block 2272 字符',
316
+ implements: ['占位符/幻觉 API/伪造数据/引用悬空 四类检测'],
317
+ exec(inp, tid) {
318
+ const text = String(inp.text || '');
319
+ if (!text) return { success: false, kind: 'rule', reason: 'INVALID_INPUT', error: '必须提供 text' };
320
+ const D = [
321
+ { id: 'O1', label: '占位符', re: /\{\{[^}]+\}\}|<PLACEHOLDER>|\bTODO\b|\bFIXME\b/g },
322
+ { id: 'O2', label: '未定义值', re: /\bundefined\b|\bNaN\b|\bnull\b/g },
323
+ { id: 'O3', label: '伪造数据迹象', re: /示例数据|mock 数据|假数据|占位数字/g },
324
+ { id: 'O4', label: '悬空引用', re: /见(上文|附件)(?![\s\S]{0,40}(第|L)\d)|参考(文件|文档)(?![::\w])/g },
325
+ ];
326
+ const hits = D.map((d) => { const m = text.match(d.re); return m ? { id: d.id, label: d.label, count: m.length, samples: [...new Set(m)].slice(0, 3) } : null; }).filter(Boolean);
327
+ const ok = hits.length === 0;
328
+ return { success: ok, kind: 'rule', output: { textLength: text.length, hits, clean: ok },
329
+ error: ok ? undefined : `输出含 ${hits.length} 类完整性问题:${hits.map((h) => h.label).join('、')}`,
330
+ reason: ok ? undefined : 'RULE_VIOLATED',
331
+ provenance: [`[${tid}] output-integrity: ${hits.length} 类问题`] };
332
+ },
333
+ });
334
+
335
+ /* ══════ 16. 司法辖区切换协议 ══════ */
336
+ P.push({
337
+ id: 'PROTOCOL_JURISDICTION_SWITCH_V1', name: '司法辖区切换协议', kind: 'rule', src: 'yaml-block 607 字符',
338
+ implements: ['辖区策略表(EU/CN/US/GENERIC)', '跨境取最严', '切换记录'],
339
+ exec(inp, tid) {
340
+ const from = String(inp.from || 'CN').toUpperCase(), to = String(inp.to || 'CN').toUpperCase();
341
+ const POLICY = {
342
+ EU: { strictLevel: 4, requiresDPIA: true, dataLocalization: true, explainability: 'mandatory' },
343
+ CN: { strictLevel: 3, requiresAlgorithmFiling: true, dataLocalization: true, explainability: 'mandatory' },
344
+ US: { strictLevel: 2, requiresDPIA: false, dataLocalization: false, explainability: 'recommended' },
345
+ GENERIC: { strictLevel: 1, requiresDPIA: false, dataLocalization: false, explainability: 'optional' },
346
+ };
347
+ if (!POLICY[from] || !POLICY[to]) return { success: false, kind: 'rule', reason: 'INVALID_INPUT', error: `辖区须为 ${Object.keys(POLICY).join('/')}` };
348
+ const effective = POLICY[from].strictLevel >= POLICY[to].strictLevel ? from : to;
349
+ return { success: true, kind: 'rule', output: {
350
+ from, to, fromPolicy: POLICY[from], toPolicy: POLICY[to],
351
+ effectiveJurisdiction: effective, strictestWins: true,
352
+ additionalObligations: Object.keys(POLICY[to]).filter((k) => k !== 'strictLevel' && POLICY[to][k] === true && POLICY[from][k] !== true),
353
+ rule: '跨境部署以最严格模式为准',
354
+ }, provenance: [`[${tid}] jurisdiction: ${from} → ${to},实际生效 ${effective}`] };
355
+ },
356
+ });
357
+
358
+ /* ══════ 17. 问题溯源协议 ══════ */
359
+ P.push({
360
+ id: 'PROTOCOL_PROBLEM_TRACE_V1', name: '问题溯源协议', kind: 'pipeline', src: 'yaml-block 989 字符',
361
+ implements: ['五问链(每层 why → 下一层)', '深度 ≥3 级(A9 溯源公理)', '可解根源映射'],
362
+ exec(inp, tid) {
363
+ const chain = inp.whyChain;
364
+ if (!Array.isArray(chain) || !chain.length) return { success: false, kind: 'pipeline', reason: 'INVALID_INPUT', error: '必须提供 whyChain 数组' };
365
+ const depth = chain.length;
366
+ const last = chain[chain.length - 1];
367
+ const actionable = !!(last && (last.solvable === true || last.domain));
368
+ const ok = depth >= 3 && actionable;
369
+ return { success: ok, kind: 'pipeline', output: {
370
+ depth, chain: chain.map((c, i) => ({ level: i + 1, why: c.why, answer: c.answer, domain: c.domain })),
371
+ rootCause: last, solvableDomain: last && last.domain,
372
+ minDepthRequired: 3, rule: '持续追问至可解根源;映射到算法/材料/设计/配方/工艺/管理/策略领域',
373
+ },
374
+ error: depth < 3 ? `溯源深度 ${depth} < 3(A9 溯源公理要求 ≥3 级)` : !actionable ? '末层未映射到可解领域' : undefined,
375
+ reason: ok ? undefined : 'PRECONDITION_FAILED',
376
+ provenance: [`[${tid}] problem-trace: 深度 ${depth},可解域 ${last && last.domain}`] };
377
+ },
378
+ });
379
+
380
+ /* ══════ 18. 冲突转化协议 ══════ */
381
+ P.push({
382
+ id: 'PROTOCOL_CONFLICT_TRANSFORM_V1', name: '冲突转化协议', kind: 'compute', src: 'yaml-block 849 字符',
383
+ implements: ['冲突强度计算', '帕累托改进空间识别', '转化策略(竞争/协作/妥协/回避/迁就)'],
384
+ exec(inp, tid) {
385
+ const a = Number(inp.positionA ?? 0), b = Number(inp.positionB ?? 1);
386
+ if (!isFinite(a) || !isFinite(b)) return { success: false, kind: 'compute', reason: 'INVALID_INPUT', error: '必须提供 positionA / positionB' };
387
+ const distance = round(Math.abs(a - b));
388
+ const intensity = round(clamp01(distance));
389
+ const pareto = inp.paretoGain !== undefined ? Number(inp.paretoGain) : round(1 - distance);
390
+ const strategy = intensity >= 0.8 ? '竞争或回避' : intensity >= 0.5 ? '妥协' : pareto > 0.3 ? '协作(帕累托改进)' : '迁就';
391
+ return { success: true, kind: 'compute', output: {
392
+ positionA: a, positionB: b, distance, intensity,
393
+ paretoGain: pareto, recommendedStrategy: strategy,
394
+ transformative: pareto > 0,
395
+ rule: '冲突强度 = 立场距离;帕累托增益 >0 才有转化空间',
396
+ }, provenance: [`[${tid}] conflict-transform: 距离 ${distance} → 强度 ${intensity} → ${strategy}`] };
397
+ },
398
+ });
399
+
400
+ /* ══════ 19. 元协议演化协议 ══════ */
401
+ P.push({
402
+ id: 'PROTOCOL_META_PROTOCOL_V1', name: '元协议演化协议', kind: 'pipeline', src: 'yaml-block 900 字符',
403
+ implements: ['协议演化的四要素校验(触发/影响分析/版本/回滚)'],
404
+ exec(inp, tid) {
405
+ const need = ['trigger', 'impactAnalysis', 'newVersion', 'rollbackPlan'];
406
+ const steps = need.map((k, i) => ({ stage: i + 1, key: k, present: !!(inp && inp[k]) }));
407
+ const miss = steps.filter((s) => !s.present).map((s) => s.key);
408
+ const ok = miss.length === 0;
409
+ return { success: ok, kind: 'pipeline', steps, output: { elements: steps, complete: ok, missing: miss, rule: '协议自身演化须有触发条件、影响分析、新版本号、回滚方案' },
410
+ error: ok ? undefined : '协议演化要素缺失:' + miss.join('/'),
411
+ reason: ok ? undefined : 'PRECONDITION_FAILED',
412
+ provenance: [`[${tid}] meta-protocol: ${4 - miss.length}/4 要素齐备`] };
413
+ },
414
+ });
415
+
416
+ /* ══════ 20. Skill 生命周期协议 ══════ */
417
+ P.push({
418
+ id: 'PROTOCOL_SKILL_LIFE_V1', name: 'Skill生命周期协议', kind: 'pipeline', src: 'yaml-block 1042 字符',
419
+ implements: ['六阶段生命周期(提案/评估/实现/验证/发布/退役)', '退役无残留'],
420
+ exec(inp, tid) {
421
+ const STAGES = ['propose', 'evaluate', 'implement', 'verify', 'release', 'retire'];
422
+ const current = String(inp.stage || '');
423
+ if (!STAGES.includes(current)) return { success: false, kind: 'pipeline', reason: 'INVALID_INPUT', error: `stage 须为 ${STAGES.join('/')}` };
424
+ const idx = STAGES.indexOf(current);
425
+ const out = { stage: current, order: idx + 1, totalStages: STAGES.length, allowedNext: STAGES[idx + 1] || null };
426
+ if (current === 'retire') {
427
+ const residue = inp.residue || [];
428
+ out.retireCheck = { residue: residue, clean: residue.length === 0 };
429
+ if (residue.length) return { success: false, kind: 'pipeline', output: out, error: `退役残留 ${residue.length} 项:${residue.slice(0, 3).join(',')}`, reason: 'RULE_VIOLATED', provenance: [`[${tid}] skill-life: retire 残留 ${residue.length}`] };
430
+ }
431
+ return { success: true, kind: 'pipeline', output: out, provenance: [`[${tid}] skill-life: ${current} (${idx + 1}/6)`] };
432
+ },
433
+ });
434
+
435
+ const INDEX = new Map(P.map((p) => [p.id, p]));
436
+ const kindOf = (id) => { const p = INDEX.get(id); return p ? p.kind : 'declared'; };
437
+ const getRegistry = () => P.map((p) => ({ id: p.id, name: p.name, kind: p.kind, src: p.src, implements: p.implements }));
438
+
439
+ function executeSync(id, input) {
440
+ const t0 = Date.now(), tid = newTraceId();
441
+ const p = INDEX.get(id);
442
+ if (!p) return { success: false, kind: 'declared', reason: 'NOT_FOUND', error: `协议 ${id} 未登记`, provenance: [], traceId: tid, durationMs: 0 };
443
+ let r;
444
+ try { r = p.exec(input || {}, tid); } catch (e) { r = { success: false, kind: p.kind, error: 'THROW: ' + e.message, provenance: [`[${tid}] THROW`] }; }
445
+ return { ...r, protocolId: id, protocolName: p.name, traceId: tid, durationMs: Date.now() - t0 };
446
+ }
447
+
448
+ module.exports = { executeSync, execute: async (i, n) => executeSync(i, n), kindOf, getRegistry, PROTOCOLS: P, INDEX, newTraceId };