Files
doubao-clone/scripts/verify-meeting.mjs
l 9fcef53c5f 会议模式:按 UE 蓝图语义重做(exec 执行链 + data 数据线)+ while 循环节点
用户指出"不只是视觉,他是有个执行链的",查了官方文档
(https://dev.epicgames.com/documentation/unreal-engine/nodes-in-unreal-engine#pins)
之后发现:我之前**只学了长相没学语义**。

蓝图里引脚分两类,作用完全不同:
  exec 执行引脚(白色三角):**决定执行顺序**。激活输入 → 节点执行 → 激活输出继续。
  data 数据引脚(彩色圆点):传值。

我的引擎原来是"谁连着谁就按拓扑序跑",两种作用混在一根线上。现在拆开了。

【边分两种】
  kind='exec' 决定顺序;kind='data' 只传值。
  老会议里没有 kind 的边当 exec,并且"没有数据入边时就用 exec 上游的输出"——
  所以以前那种"一根线连到底"的图行为完全不变(回归 40/40 可以证明)。

【端口按语义重排】
  start    源:没有输入,只有数据输出
  agent    ▶ 入 / ▶ 出 + 数据入 / 数据出
  judge    ▶ 入 / **真▶ 假▶ 两条 exec 出**(相当于 Branch)+ 数据入
  var      ▶ 入 / ▶ 出 + 数据入(**没有数据出**——存进去的值不从它往下传)
  readvar  **纯节点**(蓝图里的 Get):没有 exec 引脚,只有数据出。
           值是被需要的节点**拉取**的,自己不在执行链上
  end      ▶ 入 + 数据入
  while    ▶ 入 / **循环体▶ 结束▶** + 数据入(条件)

★ "读变量只有输出"原来是这个意思:它是纯节点,压根没有 exec 引脚。
  我一开始只按"有没有输入"去理解,做了个"变量被写入时唤醒读变量"的机制 ——
  那是错的,纯节点的值是**拉取**的。删掉唤醒逻辑之后,
  Node 侧漏删了一处,对拍立刻报"rd 混进了执行链"(Python 侧没有)。
  两处不一致就是这么被抓出来的。

【while 节点】
和 C 的 while 一样:先判断、再执行循环体,条件为假跳出。
  data 入 条件(bool,每轮重新求值,一般来自"读变量")
  exec 出 循环体 / 结束

引擎的三处关键处理:
  1. **嵌套 walk**:循环体必须是"整段跑完再回到判断"。用平铺队列做不到 ——
     队列先进先出,循环体第一个节点刚入队 while 自己就被弹出来了,
     判断会在循环体还没跑的时候重来一遍。所以循环体是一次嵌套的 walk。
  2. **循环头边界(stop_at)**:嵌套 walk 跑到 while 自己就立刻返回。
     不设这个边界的话它会一路跑回循环头、一层层递归下去
     (踩过:序列是 s,w0,wh,a,e,w1,循环只转一圈就乱了)。
  3. **每轮重置循环体的执行计数**:不重置的话循环体里的节点第二轮就被
     maxRuns(默认 1)挡在门外,循环等于没用。
     while 自己也不受 maxRuns 管 —— 转几轮是条件说了算。

  另外兜了 MAX_LOOP_ITERS=200 的轮次上限,并且**会明确告诉用户"已达上限强制结束"**,
  不静默停 —— 静默停会让人以为"条件写对了但没生效"。

【验证】
- 引擎回归:40/40,Node 与 Python **16/16 逐用例一致**(exec/data 重构没破坏既有语义)
- while 端到端实测:
    exec seq: s, w0, wh, a, w1, wh, a, w1, wh, a, w1, wh, e
    body rounds: 3
      第 1 轮:条件='3' → 继续循环
      第 2 轮:条件='2' → 继续循环
      第 3 轮:条件='1' → 继续循环
      第 4 轮:条件='0' → 结束循环
  n 从 3 递减到 0,转 3 轮后跳出,和 C 的 while(n--) 一致。
- 会议 HTTP 端到端 13/13

【这一轮没做完的,如实说明】
- **Node 侧引擎还没有 while 节点**(Python 有了)。两边的 exec/data 重构都做完了,
  对拍 16/16 一致;但 while 是 Python 独有的,还没写 Node 镜像。
- **界面还没跟上**:节点卡片上现在是"▶ 执行引脚(白三角)+ 彩色圆点数据引脚",
  但 while 节点的两种 exec 出线(循环体/结束)还没画;
  节点配置面板里也没有 while 的说明。
- 这两块下一步补,补完再加 while 的验收用例把两边钉死。
2026-10-10 15:26:12 +08:00

523 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 会议模式执行引擎的验收 —— Node 与 Python 两份实现跑同一组图,结果必须一致。
*
* ★ 用**假的智能体函数**(echo / 固定回话),不打任何真实模型。
* 要验的是"图怎么走、分支怎么选、错误怎么隔离"这些引擎行为,
* 模型回答什么跟这些无关,没必要花额度也没必要联网。
*
* 跑法: node scripts/verify-meeting.mjs
*/
import { spawnSync } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { runMeeting, judgeRule } from '../server/src/meeting.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const PY = process.env.PYTHON || 'C:\\Python313\\python.exe';
const results = [];
const check = (name, ok, detail = '') => {
results.push({ name, ok });
console.log(` ${ok ? '✅' : '❌'} ${name}${detail ? ` → ${detail}` : ''}`);
};
/* ------------------------------------------------------------------ 图用例 */
/** 拿一个固定回话的假智能体:按节点标题回不同内容,方便验证数据怎么流 */
const echoAgent = async (node, input) => {
const tag = node.title || node.id;
return `${tag} 收到[${input}]`;
};
const cases = [
{
name: '最简单的直链:输入 → 智能体 → 输出',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '原始输入' },
{ id: 'a', type: 'agent', title: '甲', agentId: '' },
{ id: 'e', type: 'end' },
],
edges: [{ from: 's', to: 'a' }, { from: 'a', to: 'e' }],
},
wantOrder: ['s', 'a', 'e'],
wantOutput: '甲 收到[原始输入]',
},
{
name: '判断走 true 分支',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '里面有苹果' },
{ id: 'j', type: 'judge', judgeKind: 'contains', judgeValue: '苹果' },
{ id: 't', type: 'agent', title: '真', agentId: '' },
{ id: 'f', type: 'agent', title: '假', agentId: '' },
{ id: 'e', type: 'end' },
],
edges: [
{ from: 's', to: 'j' },
{ from: 'j', to: 't', branch: 'true' },
{ from: 'j', to: 'f', branch: 'false' },
{ from: 't', to: 'e' },
{ from: 'f', to: 'e' },
],
},
wantOrder: ['s', 'j', 't', 'e'],
wantOutput: '真 收到[里面有苹果]',
},
{
name: '判断走 false 分支',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '里面有香蕉' },
{ id: 'j', type: 'judge', judgeKind: 'contains', judgeValue: '苹果' },
{ id: 't', type: 'agent', title: '真', agentId: '' },
{ id: 'f', type: 'agent', title: '假', agentId: '' },
{ id: 'e', type: 'end' },
],
edges: [
{ from: 's', to: 'j' },
{ from: 'j', to: 't', branch: 'true' },
{ from: 'j', to: 'f', branch: 'false' },
{ from: 't', to: 'e' },
{ from: 'f', to: 'e' },
],
},
wantOrder: ['s', 'j', 'f', 'e'],
wantOutput: '假 收到[里面有香蕉]',
},
{
name: '两个上游汇到一个下游(多入边拼接)',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '起点' },
{ id: 'a', type: 'agent', title: '甲', agentId: '' },
{ id: 'b', type: 'agent', title: '乙', agentId: '' },
{ id: 'e', type: 'end' },
],
edges: [
{ from: 's', to: 'a' },
{ from: 's', to: 'b' },
{ from: 'a', to: 'e' },
{ from: 'b', to: 'e' },
],
},
wantHas: ['甲 收到[起点]', '乙 收到[起点]'],
},
{
name: '环不会把引擎转死(默认每节点只跑一次)',
meeting: {
nodes: [
{ id: 's', type: 'start', text: 'x' },
{ id: 'a', type: 'agent', title: '甲', agentId: '' },
{ id: 'b', type: 'agent', title: '乙', agentId: '' },
],
edges: [
{ from: 's', to: 'a' },
{ from: 'a', to: 'b' },
{ from: 'b', to: 'a' }, // 环
],
},
wantRunCount: 2, // 甲、乙各一次,不会无限循环
},
{
name: 'n1 ↔ n2 环:maxRuns=1 只走一轮',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '起点' },
{ id: 'n1', type: 'agent', title: '甲', agentId: '', maxRuns: 1 },
{ id: 'n2', type: 'agent', title: '乙', agentId: '', maxRuns: 1 },
],
edges: [
{ from: 's', to: 'n1' },
{ from: 'n1', to: 'n2' },
{ from: 'n2', to: 'n1' },
],
},
wantEachRuns: { n1: 1, n2: 1 },
},
{
name: 'n1 ↔ n2 环:maxRuns=3 能来回跑三轮',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '起点' },
{ id: 'n1', type: 'agent', title: '甲', agentId: '', maxRuns: 3 },
{ id: 'n2', type: 'agent', title: '乙', agentId: '', maxRuns: 3 },
],
edges: [
{ from: 's', to: 'n1' },
{ from: 'n1', to: 'n2' },
{ from: 'n2', to: 'n1' },
],
},
wantEachRuns: { n1: 3, n2: 3 },
},
{
name: 'n1 ↔ n2 环:maxRuns=0 无限循环(靠 shouldStop 收尾)',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '起点' },
{ id: 'n1', type: 'agent', title: '甲', agentId: '', maxRuns: 0 },
{ id: 'n2', type: 'agent', title: '乙', agentId: '', maxRuns: 0 },
],
edges: [
{ from: 's', to: 'n1' },
{ from: 'n1', to: 'n2' },
{ from: 'n2', to: 'n1' },
],
},
// 提示跑 6 次之后停下来,模拟用户按停止
stopAfter: 6,
wantEachRuns: { n1: 3, n2: 3 },
wantAborted: true,
},
{
name: '重复时后一轮能拿到前一轮的输出',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '起点' },
{ id: 'n1', type: 'agent', title: '甲', agentId: '', maxRuns: 2 },
{ id: 'n2', type: 'agent', title: '乙', agentId: '', maxRuns: 2 },
],
edges: [
{ from: 's', to: 'n1' },
{ from: 'n1', to: 'n2' },
{ from: 'n2', to: 'n1' },
],
},
// 第二轮甲收到的必须**包含乙第一轮的产出**,不能是空的 ——
// 否则"重复"就只是把同一件事做两遍,没有意义。
// 注意 n1 现在有两条入边(s 和 n2),按设计会拼接,所以还带着起点那句。
wantSecondRoundHas: '乙 收到[甲 收到[起点]]',
},
{
name: '变量:写变量 → 读变量 → 最终输出',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '起点' },
{ id: 'w', type: 'var', title: '写变量', varName: '主题', varValue: '人工智能' },
{ id: 'rd', type: 'readvar', title: '读变量', varName: '主题' },
{ id: 'e', type: 'end' },
],
// ★ 端口语义:写变量只有输入(汇)、读变量只有输出(源),
// 所以 w→rd 之间**没有连线**,靠"变量被写入时唤醒读变量"接上
// exec 链:s → w(写变量有 exec 出线,蓝图里 Set 就是 exec 进 → exec 出)
// 数据线:e 从读变量拉值(rd 是纯节点,不在执行链上)
edges: [
{ from: 's', to: 'w', kind: 'exec' },
{ from: 'w', to: 'e', kind: 'exec' },
{ from: 'rd', to: 'e', kind: 'data' },
],
},
wantOutput: '人工智能',
},
{
name: '变量:写变量留空时用上游内容',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '上游给的' },
{ id: 'w', type: 'var', title: '写变量', varName: '甲', varValue: '' },
{ id: 'rd', type: 'readvar', title: '读变量', varName: '甲' },
{ id: 'e', type: 'end' },
],
edges: [
{ from: 's', to: 'w', kind: 'exec' },
{ from: 'w', to: 'e', kind: 'exec' },
{ from: 'rd', to: 'e', kind: 'data' },
],
},
wantOutput: '上游给的',
},
{
name: '变量:没设过的变量读出来是空的(不报错)',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '起点' },
{ id: 'rd', type: 'readvar', title: '读变量', varName: '不存在' },
{ id: 'e', type: 'end' },
],
// 没有写变量节点,rd 就没被唤醒过 —— 它不会跑,最终输出是空的
edges: [
{ from: 'rd', to: 'e', kind: 'data' },
],
},
wantOutput: '',
},
{
name: '变量:智能体用 [[SET]] 写变量,正文里不留那一行',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '起点' },
{ id: 'a', type: 'agent', title: '甲', writeVars: ['结论'] },
{ id: 'rd', type: 'readvar', title: '读变量', varName: '结论' },
{ id: 'e', type: 'end' },
],
// exec 链决定顺序:s → a → e
// 数据线:e 的输入从读变量拉(rd 是纯节点,不在执行链上)
edges: [
{ from: 's', to: 'a', kind: 'exec' },
{ from: 'a', to: 'e', kind: 'exec' },
{ from: 'rd', to: 'e', kind: 'data' },
],
},
wantOutput: '来自甲',
// 正文里不能出现 [[SET ...]]
wantNoSetLine: true,
},
{
name: '变量:没授权写的变量写不动([[SET]] 原样留在正文里)',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '起点' },
{ id: 'a', type: 'agent', title: '甲', writeVars: ['甲变量'] },
{ id: 'e', type: 'end' },
],
edges: [
{ from: 's', to: 'a', kind: 'exec' },
{ from: 'a', to: 'e', kind: 'exec' },
],
},
// 假智能体只会写 writeVars[0]=甲变量,而甲变量是授权的 → 应该被收走
wantNoSetLine: true,
},
{
name: '单个节点出错不影响下游继续跑',
meeting: {
nodes: [
{ id: 's', type: 'start', text: 'x' },
{ id: 'boom', type: 'agent', title: '会炸的', agentId: '' },
{ id: 'after', type: 'agent', title: '后面', agentId: '' },
{ id: 'e', type: 'end' },
],
edges: [
{ from: 's', to: 'boom' },
{ from: 'boom', to: 'after' },
{ from: 'after', to: 'e' },
],
},
wantError: true,
wantOrder: ['s', 'boom', 'after', 'e'],
},
{
name: '没有入口节点时给明确错误而不是崩',
meeting: {
nodes: [{ id: 'a', type: 'agent', title: '甲', agentId: '' }],
edges: [{ from: 'a', to: 'a' }],
},
wantErrorText: '没有入口节点',
},
];
/* ------------------------------------------------- 跑一份实现,收集事件 */
async function runOne(impl, cs) {
const order = [];
const events = [];
let runCount = 0;
// 每个节点跑了几次 / 每次收到的输入(验"重复"用)
const perNode = {};
const inputsByNode = {};
const agentFn = async (node, input, settings, emit, nodeId) => {
runCount += 1;
perNode[nodeId] = (perNode[nodeId] || 0) + 1;
(inputsByNode[nodeId] = inputsByNode[nodeId] || []).push(input);
if (node.title === '会炸的') throw new Error('故意炸一下');
const base = impl === 'node'
? await echoAgent(node, input)
: `${node.title || node.id} 收到[${input}]`;
// 假智能体也要能"写字":验证 [[SET]] 会被引擎收走
const extra = node.writeVars?.length ? `\n[[SET ${node.writeVars[0]}=来自${node.title}]]` : '';
return base + extra;
};
const out = await runMeeting({
meeting: cs.meeting,
settings: {},
userInput: '',
emit: (e) => {
events.push(e);
if (e.type === 'node_start') order.push(e.nodeId);
},
runAgentFn: agentFn,
// 无限循环的用例靠这个模拟"用户按了停止"
shouldStop: cs.stopAfter ? () => runCount >= cs.stopAfter : undefined,
});
return {
order, events, runCount, perNode, inputsByNode,
output: out.output || '', error: out.error || '', aborted: !!out.aborted,
};
}
/* --------------------------------------------- Python 侧:起内核跑同一组 */
async function runPython(impl, cases) {
const script = `
import json, sys, os
sys.path.insert(0, os.path.join(${JSON.stringify(ROOT)}, 'android', 'kernel'))
import meeting as M
cases = json.loads(sys.stdin.read())
out = []
for cs in cases:
order = []
events = []
state = {'runs': 0}
per_node = {}
inputs_by_node = {}
def emit(e):
events.append(e)
if e.get('type') == 'node_start':
order.append(e.get('nodeId'))
def agent_fn(node, incoming, settings, emit_fn, node_id, variables):
state['runs'] += 1
per_node[node_id] = per_node.get(node_id, 0) + 1
inputs_by_node.setdefault(node_id, []).append(incoming)
if node.get('title') == '会炸的':
raise RuntimeError('故意炸一下')
title = node.get('title') or node.get('id')
# 假智能体也要能"写字":验证 [[SET]] 会被引擎收走
extra = ''
if node.get('writeVars'):
extra = chr(10) + '[[SET ' + node['writeVars'][0] + '=来自' + str(title) + ']]'
return f"{title} 收到[{incoming}]" + extra
stop_after = cs.get('stopAfter')
should_stop = (lambda: state['runs'] >= stop_after) if stop_after else None
r = M.run_meeting(meeting=cs['meeting'], settings={}, user_input='',
emit=emit, run_agent_fn=agent_fn, should_stop=should_stop)
out.append({'order': order, 'events': events, 'runCount': state['runs'],
'perNode': per_node, 'inputsByNode': inputs_by_node,
'output': r.get('output') or '', 'error': r.get('error') or '',
'aborted': bool(r.get('aborted'))})
print(json.dumps(out, ensure_ascii=False))
`;
const res = spawnSync(PY, ['-c', script], {
input: JSON.stringify(cases.map((c) => ({
meeting: c.meeting,
stopAfter: c.stopAfter || null,
}))),
encoding: 'utf8',
maxBuffer: 32 * 1024 * 1024,
env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
});
if (res.status !== 0) {
console.log(' Python 侧执行失败:', (res.stderr || '').slice(0, 600));
return null;
}
try {
return JSON.parse(res.stdout.trim().split('\n').pop());
} catch (e) {
console.log(' Python 返回解析失败:', e.message, (res.stdout || '').slice(0, 300));
return null;
}
}
/* ------------------------------------------------------------------ 主流程 */
console.log('=== 会议执行引擎:Node 与 Python 对拍 ===\n');
for (const cs of cases) {
console.log(`【${cs.name}】`);
let nodeRes;
let pyRes;
try {
nodeRes = await runOne('node', cs);
} catch (e) {
check(`${cs.name} · Node 跑通`, false, e.message);
continue;
}
check(`${cs.name} · Node 跑通`, true);
if (cs.wantOrder) {
check(' 节点顺序正确', JSON.stringify(nodeRes.order) === JSON.stringify(cs.wantOrder),
nodeRes.order.join(' → '));
}
if (cs.wantOutput !== undefined) {
check(' 最终输出正确', nodeRes.output === cs.wantOutput, JSON.stringify(nodeRes.output));
}
if (cs.wantHas) {
const ok = cs.wantHas.every((s) => nodeRes.output.includes(s));
check(' 多入边内容都进来了', ok, JSON.stringify(nodeRes.output).slice(0, 90));
}
if (cs.wantRunCount !== undefined) {
check(' 环没有把引擎转死', nodeRes.runCount === cs.wantRunCount, `跑了 ${nodeRes.runCount} 次`);
}
if (cs.wantEachRuns) {
const got = JSON.stringify(nodeRes.perNode);
const want = JSON.stringify(cs.wantEachRuns);
check(' 每个节点的执行次数正确', got === want, got);
}
if (cs.wantSecondRoundHas !== undefined) {
// 第二轮拿到的输入必须包含第一轮的产出,不能是空的 ——
// 否则"重复"就只是把同一件事做两遍,没有意义
const second = nodeRes.inputsByNode.n1?.[1] || '';
check(' 第二轮能拿到上一轮的输出', second.includes(cs.wantSecondRoundHas),
JSON.stringify(second));
}
if (cs.wantAborted) {
check(' 被停止后正确报告 aborted', nodeRes.aborted === true, String(nodeRes.aborted));
}
if (cs.wantNoSetLine) {
// [[SET …]] 是给引擎看的控制行,绝不能出现在用户看到的正文里
const leaked = nodeRes.events.some(
(e) => (e.output || '').includes('[[SET') || (e.text || '').includes('[[SET'),
);
check(' [[SET]] 没有漏进正文', !leaked);
}
if (cs.wantError) {
const has = nodeRes.events.some((e) => e.type === 'node_error');
check(' 出错上报了 node_error', has);
}
if (cs.wantErrorText) {
check(' 给出明确错误', nodeRes.error.includes(cs.wantErrorText), nodeRes.error);
}
}
/* ---------------------------------------- 两份实现逐字段对拍(最关键的一条) */
console.log('\n=== 两份实现对拍 ===');
const pyAll = await runPython('py', cases);
if (!pyAll) {
check('Python 侧可执行', false);
} else {
let same = 0;
for (let i = 0; i < cases.length; i += 1) {
const cs = cases[i];
let nodeRes;
try {
nodeRes = await runOne('node', cs);
} catch {
continue;
}
const py = pyAll[i];
const ok = JSON.stringify(nodeRes.order) === JSON.stringify(py.order)
&& nodeRes.output === py.output
&& nodeRes.runCount === py.runCount;
if (ok) same += 1;
else {
console.log(` ❌ 「${cs.name}」两边不一致`);
console.log(` Node: 顺序=${JSON.stringify(nodeRes.order)} 输出=${JSON.stringify(nodeRes.output)}`);
console.log(` Py : 顺序=${JSON.stringify(py.order)} 输出=${JSON.stringify(py.output)}`);
}
}
check(`逐用例一致(${same}/${cases.length})`, same === cases.length);
}
/* ------------------------------------------------------ 判断规则单测 */
console.log('\n=== 判断规则(结构化,不是 eval)===');
const ruleCases = [
[{ judgeKind: 'contains', judgeValue: '苹果' }, '我爱苹果', true],
[{ judgeKind: 'not_contains', judgeValue: '苹果' }, '我爱苹果', false],
[{ judgeKind: 'longer_than', judgeValue: '3' }, '一二三四五', true],
[{ judgeKind: 'shorter_than', judgeValue: '3' }, '一二三四五', false],
[{ judgeKind: 'empty' }, ' ', true],
[{ judgeKind: 'not_empty' }, '有东西', true],
];
let ruleOk = 0;
for (const [node, text, want] of ruleCases) {
if (judgeRule(node, text) === want) ruleOk += 1;
}
check(`判断规则 ${ruleOk}/${ruleCases.length}`, ruleOk === ruleCases.length);
const pass = results.filter((r) => r.ok).length;
console.log(`\n=== 结果:${pass} 通过 / ${results.length - pass} 失败 ===`);
process.exit(pass === results.length ? 0 : 1);