femo-plugin 1.0.0
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.
- package/LICENSE +201 -0
- package/README.md +627 -0
- package/femo2host/__init__.py +4 -0
- package/femo2host/femoToolcall/chronica.py +156 -0
- package/femo2host/femoToolcall/femo-chat.mjs +69 -0
- package/femo2host/femoToolcall/femo_debugger.py +1515 -0
- package/femo2host/femo_api.py +437 -0
- package/femo2host/femo_gen_api.jsx +77 -0
- package/femoBridges/ContextExample.py +555 -0
- package/femoBridges/MemoryExample.py +163 -0
- package/femoBridges/__init__.py +1 -0
- package/femoBridges/getDir/get_dir.py +56 -0
- package/femoBridges/getDir//344/275/240/345/217/257/344/273/245/350/256/276/345/256/232/344/273/273/346/204/217/346/226/207/344/273/266/345/244/271/344/270/272/347/224/250/346/210/267/346/225/260/346/215/256/346/226/207/344/273/266/345/244/271.txt +10 -0
- package/femoBridges/llmBridge.py +247 -0
- package/femoBridges/llmProviders.py +308 -0
- package/femoCompiler/FEMO_CLIrenderer.py +198 -0
- package/femoCompiler/FEMO_config.py +35 -0
- package/femoCompiler/FEMO_errors.py +278 -0
- package/femoCompiler/FEMO_interpreter.py +163 -0
- package/femoCompiler/FEMO_normalizer.py +396 -0
- package/femoCompiler/FEMO_parser.py +2468 -0
- package/femoCompiler/FEMO_runtime.py +3630 -0
- package/femoCompiler/FEMO_scope_resolver.py +209 -0
- package/femoCompiler/__init__.py +1 -0
- package/femoCompiler/actor_resolver.py +86 -0
- package/femoCompiler/block_collector.py +441 -0
- package/femoCompiler/db_utils.py +485 -0
- package/femoCompiler/femoAsync.py +401 -0
- package/femoCompiler/host_manifest.py +68 -0
- package/femoCompiler/job_manager.py +767 -0
- package/femoCompiler/protocol.py +126 -0
- package/femoCompiler/save_dialog.py +402 -0
- package/femoCompiler/task_world.py +544 -0
- package/femoCompiler/vars/__init__.py +19 -0
- package/femoCompiler/vars/checkpoint.py +113 -0
- package/femoCompiler/vars/env.py +686 -0
- package/femoCompiler/vars/evaluator.py +567 -0
- package/femoCompiler/vars/join.py +303 -0
- package/femoCompiler/vars/merge.py +157 -0
- package/femoCompiler/vars/model.py +245 -0
- package/femoExamples/AI/345/211/252/350/247/206/351/242/221/AI/345/211/252/350/247/206/351/242/221.femo +192 -0
- package/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +42 -0
- package/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +10 -0
- package/femoExamples/LuxFiat/luxfiat.femo +38 -0
- package/femoExamples/LuxFiat/wait.py +29 -0
- package/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +222 -0
- package/femoExamples/discussion.femo +70 -0
- package/femoExamples/goal-mode.femo +23 -0
- package/femoExamples//345/270/270/347/224/250/345/267/245/345/205/267python/wait.py +29 -0
- package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils.py +205 -0
- package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +324 -0
- package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200-/350/255/246/351/225/277/347/211/210.femo +544 -0
- package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200.femo +331 -0
- package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +683 -0
- package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225-/350/217/234/345/270/202/345/234/272/345/261/200.femo +348 -0
- package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225.femo +392 -0
- package/femoGen/document_ch.html +2352 -0
- package/femoGen/document_en.html +2279 -0
- package/femoGen/index.html +19 -0
- package/femoGen/intro_ch.html +942 -0
- package/femoGen/intro_en.html +932 -0
- package/femoGen/package-lock.json +1698 -0
- package/femoGen/package.json +19 -0
- package/femoGen/public/character_need.ttf +0 -0
- package/femoGen/public/favicon.ico +0 -0
- package/femoGen/public/femo-logo-slogan.svg +83 -0
- package/femoGen/public/femo-logo.svg +55 -0
- package/femoGen/public/logo-fullsize.ico +0 -0
- package/femoGen/src/FemoWorAuto.jsx +5444 -0
- package/femoGen/src/actionModal.jsx +358 -0
- package/femoGen/src/bubbleOverlay.jsx +701 -0
- package/femoGen/src/canvasNodes.jsx +608 -0
- package/femoGen/src/common.jsx +715 -0
- package/femoGen/src/debugPanel.jsx +530 -0
- package/femoGen/src/faIcons.jsx +84 -0
- package/femoGen/src/femoDiagnostics.js +122 -0
- package/femoGen/src/femoFileList.jsx +357 -0
- package/femoGen/src/femoGenerator.jsx +1198 -0
- package/femoGen/src/femoLog.js +107 -0
- package/femoGen/src/femoParser.jsx +2255 -0
- package/femoGen/src/femoPreview.jsx +297 -0
- package/femoGen/src/graphBuilder.jsx +358 -0
- package/femoGen/src/libPanel.jsx +519 -0
- package/femoGen/src/main.jsx +22 -0
- package/femoGen/src/mobileView.jsx +2796 -0
- package/femoGen/src/projectPanel.jsx +529 -0
- package/femoGen/src/soulModal.jsx +162 -0
- package/femoGen/src/styles/font.css +10 -0
- package/femoGen/src/themes.js +465 -0
- package/femoGen/src/useCanvasInteraction.jsx +319 -0
- package/femoGen/vite.config.js +28 -0
- package/femoGen//347/222/207/345/255/230/346/247/221.txt +15 -0
- package/hostAdapter/dshAdapter/README.md +68 -0
- package/hostAdapter/dshAdapter/build.mjs +75 -0
- package/hostAdapter/dshAdapter/client/client-ui/chat-node.tsx +339 -0
- package/hostAdapter/dshAdapter/client/client-ui/composer.tsx +997 -0
- package/hostAdapter/dshAdapter/client/client-ui/editor-page.tsx +726 -0
- package/hostAdapter/dshAdapter/client/client-ui/editor-view.tsx +88 -0
- package/hostAdapter/dshAdapter/client/client-ui/femo-stream-live.tsx +264 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/frame-router.ts +282 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/index.ts +44 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/ledger.ts +329 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/turn-view.tsx +211 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/window-id.ts +28 -0
- package/hostAdapter/dshAdapter/client/client-ui/stream-store.ts +550 -0
- package/hostAdapter/dshAdapter/client/client-ui/styles.ts +144 -0
- package/hostAdapter/dshAdapter/client/client-ui/view-button.tsx +572 -0
- package/hostAdapter/dshAdapter/client/client-ui/view-state.ts +61 -0
- package/hostAdapter/dshAdapter/client/client.tsx +518 -0
- package/hostAdapter/dshAdapter/client/fa-icons.tsx +112 -0
- package/hostAdapter/dshAdapter/client/femo-reasoning-row.tsx +103 -0
- package/hostAdapter/dshAdapter/client/lineage-fork-native.jsx +624 -0
- package/hostAdapter/dshAdapter/client/lineage-fork.jsx +585 -0
- package/hostAdapter/dshAdapter/cordis.patch.yml +8 -0
- package/hostAdapter/dshAdapter/dshPatch/DSH-0.1.2-fork/344/277/256/346/224/271/351/234/200/346/261/202.md +184 -0
- package/hostAdapter/dshAdapter/dshPatch/MEOW_MODIFICATIONS.md +3105 -0
- package/hostAdapter/dshAdapter/dshPatch/patch-dsh-0.1.2-alpha.1.py +313 -0
- package/hostAdapter/dshAdapter/host/api-retry.ts +141 -0
- package/hostAdapter/dshAdapter/host/bridge.ts +224 -0
- package/hostAdapter/dshAdapter/host/config.ts +124 -0
- package/hostAdapter/dshAdapter/host/debug-log.ts +29 -0
- package/hostAdapter/dshAdapter/host/debug-run.ts +793 -0
- package/hostAdapter/dshAdapter/host/diag-feed.ts +56 -0
- package/hostAdapter/dshAdapter/host/engine-events.ts +891 -0
- package/hostAdapter/dshAdapter/host/engine-transcript.ts +122 -0
- package/hostAdapter/dshAdapter/host/femo-files.ts +210 -0
- package/hostAdapter/dshAdapter/host/god-mirror.ts +234 -0
- package/hostAdapter/dshAdapter/host/host-log.ts +101 -0
- package/hostAdapter/dshAdapter/host/http.ts +66 -0
- package/hostAdapter/dshAdapter/host/index.ts +633 -0
- package/hostAdapter/dshAdapter/host/list-cache.ts +183 -0
- package/hostAdapter/dshAdapter/host/main-actor.ts +853 -0
- package/hostAdapter/dshAdapter/host/main-delivery-queue.ts +115 -0
- package/hostAdapter/dshAdapter/host/native-state.ts +21 -0
- package/hostAdapter/dshAdapter/host/node-retry.ts +246 -0
- package/hostAdapter/dshAdapter/host/persona.ts +146 -0
- package/hostAdapter/dshAdapter/host/pre-step-gate.ts +95 -0
- package/hostAdapter/dshAdapter/host/proj-trace.ts +49 -0
- package/hostAdapter/dshAdapter/host/projection-input.ts +238 -0
- package/hostAdapter/dshAdapter/host/projection.ts +742 -0
- package/hostAdapter/dshAdapter/host/routes.ts +1196 -0
- package/hostAdapter/dshAdapter/host/run-control.ts +641 -0
- package/hostAdapter/dshAdapter/host/safe-steer.ts +33 -0
- package/hostAdapter/dshAdapter/host/section-gate.ts +108 -0
- package/hostAdapter/dshAdapter/host/session-events.ts +45 -0
- package/hostAdapter/dshAdapter/host/state-files.ts +301 -0
- package/hostAdapter/dshAdapter/host/stream-frames.ts +229 -0
- package/hostAdapter/dshAdapter/host/subagent-native.ts +997 -0
- package/hostAdapter/dshAdapter/host/subagent.ts +1205 -0
- package/hostAdapter/dshAdapter/host/tools.ts +486 -0
- package/hostAdapter/dshAdapter/host/windowing-native.ts +294 -0
- package/hostAdapter/dshAdapter/host.manifest.json +6 -0
- package/hostAdapter/dshAdapter/lib/client.js +19161 -0
- package/hostAdapter/dshAdapter/lib/client.js.map +7 -0
- package/hostAdapter/dshAdapter/lib/index.js +8173 -0
- package/hostAdapter/dshAdapter/lib/index.js.map +7 -0
- package/hostAdapter/dshAdapter/package-lock.json +500 -0
- package/hostAdapter/dshAdapter/package.json +55 -0
- package/hostAdapter/dshAdapter/pnpm-lock.yaml +596 -0
- package/hostAdapter/dshAdapter/pnpm-workspace.yaml +2 -0
- package/hostAdapter/dshAdapter/python/dev-bridge-test.py +43 -0
- package/hostAdapter/dshAdapter/python/femo_bridge.py +533 -0
- package/hostAdapter/dshAdapter/tsconfig.host.json +9 -0
- package/hostAdapter/dshAdapter/tsconfig.json +21 -0
- package/package.json +40 -0
- package//350/257/255/346/263/225/346/226/207/346/241/243.md +1136 -0
|
@@ -0,0 +1,1198 @@
|
|
|
1
|
+
// ════════════════════════════════════════
|
|
2
|
+
// ═══════. femoGenerator.jsx ═════════
|
|
3
|
+
// ════════════════════════════════════════
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
import { findBackEdges, findAllCycleEdges, TYPES, SPECIAL_COLORS } from './common';
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
// ═══ 自动 vars 规划(图 → 文本)═══
|
|
10
|
+
// action modal 里的 in / out / resolve 参数 / 执行人@ 用到的变量,生成剧本时
|
|
11
|
+
// 自动补 vars 声明(引擎要求变量先声明后赋值,否则运行时报错):
|
|
12
|
+
// - action 定义在主画布(path=['mainflow'])→ 补进剧本级 vars:
|
|
13
|
+
// - action 定义在模块里 → 补进该模块 vars:
|
|
14
|
+
// - 变量跨作用域出现(≥2 个模块,或主画布+模块)→ 升级到剧本级 vars,
|
|
15
|
+
// 并把各模块里的同名声明拿掉——模块 local 帧会遮蔽全局(帧栈:循环帧 >
|
|
16
|
+
// 模块帧 > __script__),跨作用域的变量留模块副本会让模块内赋值出模块即丢。
|
|
17
|
+
|
|
18
|
+
// 提取标识符时跳过的词:逻辑/字面量保留词、out 类型与标签字段、列表操作函数、
|
|
19
|
+
// resolve 自动模式的特有参数(这些位置出现的词不是剧本变量)
|
|
20
|
+
const AUTOVAR_SKIP = new Set([
|
|
21
|
+
'and', 'or', 'not', 'in', 'is',
|
|
22
|
+
'True', 'False', 'None', 'true', 'false', 'TRUE', 'FALSE',
|
|
23
|
+
'string', 'int', 'float', 'bool', 'boolean', 'enum', 'dropdown',
|
|
24
|
+
'object', 'array', 'dict', 'list', 'str', 'num', 'choices', 'label',
|
|
25
|
+
'add', 'remove', 'len',
|
|
26
|
+
'SET_VARIABLE', 'prompt', 'llm_output',
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
// 变量身份:剥 $ 前缀(shared 与否不影响是不是同一个变量),@ 是名字的一部分
|
|
30
|
+
// (与 femoParser._declName / 编译器 split_spec_name 一致)
|
|
31
|
+
function _varIdentity(raw) {
|
|
32
|
+
return raw.startsWith('$') ? raw.slice(1) : raw;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// 表达式里的变量引用:剥引号字符串 → 提取标识符 → 取点路径主干(hp.@wolf → hp)
|
|
36
|
+
function _identRefs(expr) {
|
|
37
|
+
const noStr = String(expr).replace(/"[^"]*"|'[^']*'|“[^”]*”/g, '');
|
|
38
|
+
const out = [];
|
|
39
|
+
(noStr.match(/@?[\w\u4e00-\u9fff]+(?:\.[\w\u4e00-\u9fff]+)*/g) || []).forEach((ident) => {
|
|
40
|
+
const dot = ident.indexOf('.');
|
|
41
|
+
const main = dot >= 0 ? ident.slice(0, dot) : ident;
|
|
42
|
+
if (AUTOVAR_SKIP.has(main)) return;
|
|
43
|
+
if (/^\d+(\.\d+)?$/.test(main)) return;
|
|
44
|
+
out.push(main);
|
|
45
|
+
});
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 括号/引号感知的单字符分割(out 行 "a(string, \"x\"), b += 1" → 两项)
|
|
50
|
+
function _splitTopLevel(s, sep) {
|
|
51
|
+
const items = [];
|
|
52
|
+
let depth = 0;
|
|
53
|
+
let cur = '';
|
|
54
|
+
let q = null;
|
|
55
|
+
for (const ch of String(s)) {
|
|
56
|
+
if (q) { cur += ch; if (ch === q) q = null; continue; }
|
|
57
|
+
if (ch === '"' || ch === "'") { q = ch; cur += ch; continue; }
|
|
58
|
+
if (ch === '(' || ch === '[' || ch === '{') depth += 1;
|
|
59
|
+
else if (ch === ')' || ch === ']' || ch === '}') depth -= 1;
|
|
60
|
+
if (ch === sep && depth <= 0) { items.push(cur); cur = ''; continue; }
|
|
61
|
+
cur += ch;
|
|
62
|
+
}
|
|
63
|
+
if (cur.trim()) items.push(cur);
|
|
64
|
+
return items;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// 单个 action 用到的变量:[{ raw(拼写照抄,$/@ 保留), dv(推断初值,'' = 未知)}]
|
|
68
|
+
function collectActionVarUses(a) {
|
|
69
|
+
const uses = [];
|
|
70
|
+
const push = (raw, dv = '') => { if (raw) uses.push({ raw, dv }); };
|
|
71
|
+
|
|
72
|
+
// 1) out 变量(每行可逗号分隔多个):
|
|
73
|
+
// name(type, "标签") / dict.@key(type, "") / name = v / name += N / name = add(x)
|
|
74
|
+
String(a.outVars || '').split('\n').forEach((line) => {
|
|
75
|
+
_splitTopLevel(line, ',').forEach((item) => {
|
|
76
|
+
const t = item.trim().replace(/^,+|,+$/g, '');
|
|
77
|
+
if (!t) return;
|
|
78
|
+
const root = (t.match(/^([$@]?[\w\u4e00-\u9fff]+)/) || [])[1];
|
|
79
|
+
if (!root) return;
|
|
80
|
+
const am = t.match(/^([$@]?[\w\u4e00-\u9fff]+)\s*([+\-]?=)\s*(.+)$/);
|
|
81
|
+
if (am) {
|
|
82
|
+
// 赋值形态:按用途推断初值——+= / -= 是数字、add/remove 是列表、
|
|
83
|
+
// 字面量(引号字符串/数字/布尔)直接沿用为初值
|
|
84
|
+
let dv = '';
|
|
85
|
+
if (am[2] === '+=' || am[2] === '-=') dv = '0';
|
|
86
|
+
else if (/^\s*(add|remove)\s*\(/.test(am[3])) dv = '[]';
|
|
87
|
+
else {
|
|
88
|
+
const lit = am[3].trim();
|
|
89
|
+
if (/^("[^"]*"|'[^']*'|“[^”]*”)$/.test(lit) || /^\d+(\.\d+)?$/.test(lit) || /^(true|false)$/.test(lit)) dv = lit;
|
|
90
|
+
}
|
|
91
|
+
push(root, dv);
|
|
92
|
+
_identRefs(am[3]).forEach((r) => push(r));
|
|
93
|
+
} else {
|
|
94
|
+
// 声明形态:括号内是类型/标签不是变量,只有 choices={...} 里是引用
|
|
95
|
+
push(root);
|
|
96
|
+
const cm = t.match(/choices\s*=\s*{([^}]*)}/);
|
|
97
|
+
if (cm) _identRefs(cm[1]).forEach((r) => push(r));
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
// 2) in 映射:左边是函数参数名 / prompt 别名(不是 FEMO 变量,不声明),
|
|
103
|
+
// 右边表达式引用的全局变量要已声明;无 '=' 的裸项参数名即变量名
|
|
104
|
+
String(a.inMappings || '').split('\n').forEach((line) => {
|
|
105
|
+
_splitTopLevel(line, ',').forEach((seg) => {
|
|
106
|
+
const s = seg.trim().replace(/^,+|,+$/g, '');
|
|
107
|
+
if (!s) return;
|
|
108
|
+
const eq = s.indexOf('=');
|
|
109
|
+
_identRefs(eq >= 0 ? s.slice(eq + 1) : s).forEach((r) => push(r));
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
// 3) resolve 参数:引擎要求在全局 vars / 本 action in: / SET_VARIABLE 之一
|
|
114
|
+
String(a.resolveArgs || '').split(',').forEach((s) => {
|
|
115
|
+
const t = s.trim();
|
|
116
|
+
if (t && !AUTOVAR_SKIP.has(t)) push(t);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
// 4) 发言人@:ai/human/mind 的执行者不在 actors: 里就是 @actor 型变量
|
|
120
|
+
if (['ai', 'human', 'mind'].includes(a.executorType) &&
|
|
121
|
+
a.executorActor && a.executorActor.startsWith('@')) {
|
|
122
|
+
push(a.executorActor);
|
|
123
|
+
}
|
|
124
|
+
return uses;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// 汇总所有 action 的变量需求 → { globalExtra(补进剧本级 vars),
|
|
128
|
+
// moduleVarsById(对应模块调整后的 vars 数组:去掉被提升的、补进新增的)}
|
|
129
|
+
function planAutoVars(proj, libActions, libModules) {
|
|
130
|
+
const actions = libActions || [];
|
|
131
|
+
const modules = libModules || [];
|
|
132
|
+
if (!actions.length) return { globalExtra: [], moduleVarsById: new Map() };
|
|
133
|
+
|
|
134
|
+
const actorNames = new Set();
|
|
135
|
+
(proj.actors || []).forEach((x) => {
|
|
136
|
+
if (!x.name) return;
|
|
137
|
+
actorNames.add(x.name.startsWith('@') ? x.name : `@${x.name}`);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
const moduleByScope = new Map();
|
|
141
|
+
modules.forEach((m) => moduleByScope.set((m.path || []).join('/'), m));
|
|
142
|
+
|
|
143
|
+
// 1) 变量 → 出现过的作用域集合(scopeKey:'mainflow' 或模块 path.join('/'))
|
|
144
|
+
const varScopes = new Map(); // identity → Map(scopeKey → {raw, dv})
|
|
145
|
+
actions.forEach((a) => {
|
|
146
|
+
const p = a.path || ['mainflow'];
|
|
147
|
+
const scope = (p.length === 1 && p[0] === 'mainflow') ? 'mainflow' : p.join('/');
|
|
148
|
+
collectActionVarUses(a).forEach(({ raw, dv }) => {
|
|
149
|
+
// actors: 里的实体是角色不是变量
|
|
150
|
+
if (raw.startsWith('@') && actorNames.has(raw)) return;
|
|
151
|
+
const id = _varIdentity(raw);
|
|
152
|
+
if (!varScopes.has(id)) varScopes.set(id, new Map());
|
|
153
|
+
const m = varScopes.get(id);
|
|
154
|
+
const prev = m.get(scope);
|
|
155
|
+
if (!prev) m.set(scope, { raw, dv });
|
|
156
|
+
else if (!prev.dv && dv) m.set(scope, { raw, dv }); // 优先记能推断出初值的写法
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
if (!varScopes.size) return { globalExtra: [], moduleVarsById: new Map() };
|
|
160
|
+
|
|
161
|
+
// 2) 已有声明索引
|
|
162
|
+
const declaredGlobal = new Set((proj.vars || []).map((v) => _varIdentity(v.name)));
|
|
163
|
+
const declaredInMod = new Map(); // modId → Set(identity)
|
|
164
|
+
modules.forEach((m) =>
|
|
165
|
+
declaredInMod.set(m.id, new Set((m.vars || []).map((v) => _varIdentity(v.name)))));
|
|
166
|
+
|
|
167
|
+
const globalExtra = [];
|
|
168
|
+
const globalAdded = new Set();
|
|
169
|
+
const moduleAdd = new Map(); // modId → Map(identity → decl)
|
|
170
|
+
const moduleRemove = new Map(); // modId → Set(identity)
|
|
171
|
+
|
|
172
|
+
const removeModuleDecl = (modId, id) => {
|
|
173
|
+
if (!declaredInMod.get(modId)?.has(id)) return;
|
|
174
|
+
if (!moduleRemove.has(modId)) moduleRemove.set(modId, new Set());
|
|
175
|
+
moduleRemove.get(modId).add(id);
|
|
176
|
+
};
|
|
177
|
+
const addGlobal = (decl, id) => {
|
|
178
|
+
if (declaredGlobal.has(id) || globalAdded.has(id)) return;
|
|
179
|
+
globalAdded.add(id);
|
|
180
|
+
globalExtra.push(decl);
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
// 3) 逐变量归类
|
|
184
|
+
varScopes.forEach((scopeMap, id) => {
|
|
185
|
+
const isMain = scopeMap.has('mainflow');
|
|
186
|
+
const modScopes = [...scopeMap.keys()].filter((k) => k !== 'mainflow');
|
|
187
|
+
const crossScope = isMain || scopeMap.size >= 2;
|
|
188
|
+
|
|
189
|
+
if (!crossScope) {
|
|
190
|
+
// 只在一个模块里用到
|
|
191
|
+
const mod = moduleByScope.get(modScopes[0]);
|
|
192
|
+
if (!mod) return; // 所在模块已不存在(悬空路径),不生成
|
|
193
|
+
if (declaredGlobal.has(id)) return; // 全局已声明,模块内可见
|
|
194
|
+
if (declaredInMod.get(mod.id)?.has(id)) return; // 本模块已声明
|
|
195
|
+
const owner = modules.find((m) => m.id !== mod.id && declaredInMod.get(m.id)?.has(id));
|
|
196
|
+
if (owner) {
|
|
197
|
+
// 名字已出现在别的模块 → 跨模块出现,升级全局并把那边的副本拿掉
|
|
198
|
+
const hit = (owner.vars || []).find((v) => _varIdentity(v.name) === id);
|
|
199
|
+
addGlobal({ name: hit.name, defaultValue: hit.defaultValue ?? '""' }, id);
|
|
200
|
+
removeModuleDecl(owner.id, id);
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
if (!moduleAdd.has(mod.id)) moduleAdd.set(mod.id, new Map());
|
|
204
|
+
const info = scopeMap.get(modScopes[0]);
|
|
205
|
+
moduleAdd.get(mod.id).set(id, { name: info.raw, defaultValue: info.dv || '""' });
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// 跨作用域(主画布参与,或 ≥2 个模块):升级到剧本级 vars,模块副本一律拿掉
|
|
210
|
+
if (!declaredGlobal.has(id)) {
|
|
211
|
+
// 优先沿用某模块里已有声明的拼写和初值(用户可能已给过有意义的初值)
|
|
212
|
+
let decl = null;
|
|
213
|
+
for (const m of modules) {
|
|
214
|
+
const hit = (m.vars || []).find((v) => _varIdentity(v.name) === id);
|
|
215
|
+
if (hit) { decl = { name: hit.name, defaultValue: hit.defaultValue ?? '""' }; break; }
|
|
216
|
+
}
|
|
217
|
+
if (!decl) {
|
|
218
|
+
let dv = '';
|
|
219
|
+
let raw = '';
|
|
220
|
+
scopeMap.forEach((v) => {
|
|
221
|
+
if (!dv && v.dv) { dv = v.dv; raw = v.raw; }
|
|
222
|
+
if (!raw) raw = v.raw;
|
|
223
|
+
});
|
|
224
|
+
decl = { name: raw, defaultValue: dv || '""' };
|
|
225
|
+
}
|
|
226
|
+
addGlobal(decl, id);
|
|
227
|
+
}
|
|
228
|
+
modules.forEach((m) => removeModuleDecl(m.id, id));
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
// 4) 组装各模块调整后的 vars
|
|
232
|
+
const moduleVarsById = new Map();
|
|
233
|
+
modules.forEach((m) => {
|
|
234
|
+
const rm = moduleRemove.get(m.id);
|
|
235
|
+
const add = moduleAdd.get(m.id);
|
|
236
|
+
if (!rm && !add) return;
|
|
237
|
+
const kept = (m.vars || []).filter((v) => !(rm && rm.has(_varIdentity(v.name))));
|
|
238
|
+
const keptIds = new Set(kept.map((v) => _varIdentity(v.name)));
|
|
239
|
+
if (add) add.forEach((decl, id2) => { if (!keptIds.has(id2)) kept.push(decl); });
|
|
240
|
+
moduleVarsById.set(m.id, kept);
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
return { globalExtra, moduleVarsById };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
// ═══ FEMO GENERATOR ═══
|
|
248
|
+
|
|
249
|
+
function buildFEMO(nodes, edges, proj, mode, modName, libModules, libActions) {
|
|
250
|
+
// 文件头原文(meta: 之前的注释)最先回写——parseFEMO 捕获、graphBuilder 透传。
|
|
251
|
+
// 空画布也要保住它:用户导入的剧本哪怕一个节点都没摆,头注释不能丢。
|
|
252
|
+
const preamble = (typeof proj?.preamble === 'string' ? proj.preamble : '').replace(/\s+$/, '');
|
|
253
|
+
if (!nodes.length) {
|
|
254
|
+
return preamble ? `${preamble}\n\n# 空画布,请添加节点` : '# 空画布,请添加节点';
|
|
255
|
+
}
|
|
256
|
+
const cycleEdgesMap = findAllCycleEdges(nodes, edges);
|
|
257
|
+
const back = findBackEdges(nodes, edges);
|
|
258
|
+
const nm = new Map(nodes.map((n) => [n.id, n]));
|
|
259
|
+
|
|
260
|
+
// 根据 actionId 查找 name
|
|
261
|
+
const actionMap = new Map();
|
|
262
|
+
(libActions || []).forEach(a => actionMap.set(a.id, a.name));
|
|
263
|
+
|
|
264
|
+
// 自动 vars 规划:action 用到但未声明的变量补进对应 vars 区(见上方说明)
|
|
265
|
+
const varPlan = planAutoVars(proj, libActions, libModules);
|
|
266
|
+
|
|
267
|
+
const lines = [];
|
|
268
|
+
|
|
269
|
+
function emitAction(a, indent) {
|
|
270
|
+
const pfx = ' '.repeat(indent);
|
|
271
|
+
let actorStr;
|
|
272
|
+
if (a.executorType === 'func') {
|
|
273
|
+
actorStr = a.executorActor ? `@func(${a.executorActor})` : `@func`;
|
|
274
|
+
} else if (a.executorType === 'assign') {
|
|
275
|
+
actorStr = '@assign';
|
|
276
|
+
} else if (a.executorType === 'notice') {
|
|
277
|
+
// 公告无发言者:恒生成裸 @notice,剥掉误填的执行者参数(后端也整体忽略)
|
|
278
|
+
actorStr = '@notice';
|
|
279
|
+
} else {
|
|
280
|
+
actorStr = a.executorActor
|
|
281
|
+
? `@${a.executorType}(${a.executorActor})`
|
|
282
|
+
: `@${a.executorType}`;
|
|
283
|
+
}
|
|
284
|
+
lines.push(`${pfx}action ${a.name} ${actorStr}:`);
|
|
285
|
+
if (a.inMappings) {
|
|
286
|
+
lines.push(`${pfx} in:`);
|
|
287
|
+
a.inMappings
|
|
288
|
+
.split('\n')
|
|
289
|
+
.filter(Boolean)
|
|
290
|
+
.forEach((l) => lines.push(`${pfx} ${l.trim()}`));
|
|
291
|
+
}
|
|
292
|
+
if (a.prompt) {
|
|
293
|
+
lines.push(`${pfx} prompt: |`);
|
|
294
|
+
a.prompt.split('\n').forEach((l) => lines.push(`${pfx} ${l}`));
|
|
295
|
+
}
|
|
296
|
+
if (a.showprompt) {
|
|
297
|
+
lines.push(`${pfx} showprompt: |`);
|
|
298
|
+
a.showprompt.split('\n').forEach((l) => lines.push(`${pfx} ${l}`));
|
|
299
|
+
}
|
|
300
|
+
if (a.scope) lines.push(`${pfx} scope: ${a.scope}`);
|
|
301
|
+
if (a.outVars) {
|
|
302
|
+
lines.push(`${pfx} out:`);
|
|
303
|
+
a.outVars.split('\n').forEach((v) => {
|
|
304
|
+
const vt = v.trim();
|
|
305
|
+
if (vt) lines.push(`${pfx} ${vt}`);
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
if (a.resolve) {
|
|
309
|
+
const args = a.resolveArgs ? `(${a.resolveArgs})` : '';
|
|
310
|
+
lines.push(`${pfx} resolve: ${a.resolve}${args}`);
|
|
311
|
+
}
|
|
312
|
+
if (a.interrupt) lines.push(`${pfx} interrupt: ${a.interrupt}`);
|
|
313
|
+
if (a.fallback) lines.push(`${pfx} fallback: ${a.fallback}`);
|
|
314
|
+
if (a.maxRetries) lines.push(`${pfx} max_retries: ${a.maxRetries}`);
|
|
315
|
+
if (a.memory) lines.push(`${pfx} memory: ${a.memory}`);
|
|
316
|
+
if (a.context) lines.push(`${pfx} context: ${a.context}`);
|
|
317
|
+
lines.push('');
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// ── 文件头原文 ──
|
|
321
|
+
if (preamble) {
|
|
322
|
+
preamble.split('\n').forEach((l) => lines.push(l));
|
|
323
|
+
lines.push('');
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// ── meta section ──
|
|
327
|
+
lines.push('meta:');
|
|
328
|
+
if (proj.id) lines.push(` id = ${proj.id}`);
|
|
329
|
+
if (proj.name) lines.push(` name = ${proj.name}`);
|
|
330
|
+
if (proj.version) lines.push(` version = ${proj.version}`);
|
|
331
|
+
if (proj.owner) lines.push(` owner = ${proj.owner}`);
|
|
332
|
+
if (proj.database) lines.push(` database = ${proj.database}`);
|
|
333
|
+
if (proj.session) lines.push(` session = ${proj.session}`);
|
|
334
|
+
if (proj.delay != null) lines.push(` delay = ${proj.delay}`);
|
|
335
|
+
|
|
336
|
+
if (proj.system_safety) {
|
|
337
|
+
if (typeof proj.system_safety === 'string' && proj.system_safety.includes('\n')) {
|
|
338
|
+
lines.push(` system_safety = |`);
|
|
339
|
+
proj.system_safety.split('\n').forEach((l) => lines.push(` ${l}`));
|
|
340
|
+
} else {
|
|
341
|
+
lines.push(` system_safety = ${JSON.stringify(proj.system_safety)}`);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
if (proj.output_style) {
|
|
345
|
+
if (typeof proj.output_style === 'string' && proj.output_style.includes('\n')) {
|
|
346
|
+
lines.push(` output_style = |`);
|
|
347
|
+
proj.output_style.split('\n').forEach((l) => lines.push(` ${l}`));
|
|
348
|
+
} else {
|
|
349
|
+
lines.push(` output_style = ${JSON.stringify(proj.output_style)}`);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const knownKeys = new Set(['id', 'name', 'version', 'owner', 'database', 'session', 'delay', 'system_safety', 'output_style', 'vars', 'code', 'actors']);
|
|
354
|
+
for (const [key, value] of Object.entries(proj)) {
|
|
355
|
+
if (knownKeys.has(key)) continue;
|
|
356
|
+
if (value === undefined || value === null || value === '') continue;
|
|
357
|
+
if (typeof value === 'string' && value.includes('\n')) {
|
|
358
|
+
lines.push(` ${key} = |`);
|
|
359
|
+
value.split('\n').forEach((l) => lines.push(` ${l}`));
|
|
360
|
+
} else {
|
|
361
|
+
lines.push(` ${key} = ${JSON.stringify(value)}`);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
lines.push('');
|
|
365
|
+
|
|
366
|
+
// ── actors ──
|
|
367
|
+
if (proj.actors?.length) {
|
|
368
|
+
lines.push('actors:');
|
|
369
|
+
proj.actors.forEach((a) => {
|
|
370
|
+
const name = a.name?.startsWith('@') ? a.name : `@${a.name}`;
|
|
371
|
+
const parts = [];
|
|
372
|
+
// 仅在显式设置 soul 时输出;裸 actor(无 soul)保持裸写法——
|
|
373
|
+
// 数字兜底('1'/'0')会产出编译期「soul 不存在」的文本,已废除。
|
|
374
|
+
if (a.soul) parts.push(`soul:${a.soul}`);
|
|
375
|
+
if (a.source) parts.push(`source:${a.source}`);
|
|
376
|
+
// thinking 档位(仅 AI actor):空串=未声明(Default 语义,不输出),
|
|
377
|
+
// 非空输出 thinking:<档位>,与 Python 编译器的 thinking: 解析对齐
|
|
378
|
+
if (a.type === 'ai' && a.thinking) parts.push(`thinking:${a.thinking}`);
|
|
379
|
+
if (a.type === 'ai' && a.tools === false) {
|
|
380
|
+
parts.push('tools: false');
|
|
381
|
+
} else if (a.type === 'ai' && a.tools === true) {
|
|
382
|
+
parts.push('tools: true');
|
|
383
|
+
} else if (a.type === 'ai' && Array.isArray(a.tools) && a.tools.length) {
|
|
384
|
+
parts.push(`tools = [${a.tools.join(', ')}]`);
|
|
385
|
+
} else if (a.type === 'ai' && Array.isArray(a.tools)) {
|
|
386
|
+
// 显式空白名单 ≡ 明确禁用(语义对齐 Python 编译器;「不写」才是宿主默认全开)
|
|
387
|
+
parts.push('tools: false');
|
|
388
|
+
}
|
|
389
|
+
// 无任何属性时输出纯裸写法(不残留悬空的 "="),round-trip 对裸 actor 无损
|
|
390
|
+
lines.push(parts.length > 0 ? ` ${a.type} ${name} = ${parts.join(', ')}` : ` ${a.type} ${name}`);
|
|
391
|
+
});
|
|
392
|
+
lines.push('');
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// ── code ──
|
|
396
|
+
if (proj.code && proj.code.length) {
|
|
397
|
+
lines.push('code:');
|
|
398
|
+
proj.code.forEach((c) => {
|
|
399
|
+
const val = c.value ? `file:"${c.value}"` : '""';
|
|
400
|
+
lines.push(` ${c.name} = ${val}`);
|
|
401
|
+
});
|
|
402
|
+
lines.push('');
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// ── global vars ──
|
|
406
|
+
// proj.vars 之后追加自动补齐的声明(主画布 action / 跨作用域变量的落点)
|
|
407
|
+
const allGlobalVars = [...(proj.vars || []), ...varPlan.globalExtra];
|
|
408
|
+
if (allGlobalVars.length) {
|
|
409
|
+
lines.push('vars:');
|
|
410
|
+
allGlobalVars.forEach(v => {
|
|
411
|
+
if (v.name) lines.push(` ${v.name} = ${v.defaultValue}`);
|
|
412
|
+
});
|
|
413
|
+
lines.push('');
|
|
414
|
+
}
|
|
415
|
+
// ── global actions ──
|
|
416
|
+
(libActions || [])
|
|
417
|
+
.filter((a) => a.path && a.path.length === 1 && a.path[0] === 'mainflow')
|
|
418
|
+
.forEach((a) => emitAction(a, 0));
|
|
419
|
+
|
|
420
|
+
// ── recursive module output ──
|
|
421
|
+
const _emitVisited = new Set();
|
|
422
|
+
function emitModule(mod, indentLevel) {
|
|
423
|
+
if (_emitVisited.has(mod.id)) return;
|
|
424
|
+
_emitVisited.add(mod.id);
|
|
425
|
+
const pfx = ' '.repeat(indentLevel);
|
|
426
|
+
lines.push(`${pfx}module ${mod.name}:`);
|
|
427
|
+
|
|
428
|
+
// ═══ 修复 1:module 内部 meta 格式与项目级保持一致 ═══
|
|
429
|
+
if (mod.meta && Object.keys(mod.meta).length) {
|
|
430
|
+
lines.push(`${pfx} meta:`);
|
|
431
|
+
for (const [k, v] of Object.entries(mod.meta)) {
|
|
432
|
+
if (v === undefined || v === null || v === '') continue;
|
|
433
|
+
if (typeof v === 'string' && v.includes('\n')) {
|
|
434
|
+
lines.push(`${pfx} ${k} = |`);
|
|
435
|
+
v.split('\n').forEach((l) => lines.push(`${pfx} ${l}`));
|
|
436
|
+
} else {
|
|
437
|
+
lines.push(`${pfx} ${k} = ${JSON.stringify(v)}`);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
lines.push('');
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
if (mod.code && mod.code.length) {
|
|
444
|
+
lines.push(`${pfx} code:`);
|
|
445
|
+
mod.code.forEach((c) => lines.push(`${pfx} ${c.name} = ${c.value}`));
|
|
446
|
+
lines.push('');
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
const internalActions = (libActions || []).filter(
|
|
450
|
+
(a) =>
|
|
451
|
+
a.path &&
|
|
452
|
+
a.path.length === mod.path.length &&
|
|
453
|
+
a.path.every((seg, i) => seg === mod.path[i])
|
|
454
|
+
);
|
|
455
|
+
|
|
456
|
+
// 模块 vars:用规划后的数组(拿掉被提升全局的、补进模块内 action 需要的)
|
|
457
|
+
const modVars = varPlan.moduleVarsById.get(mod.id) ?? mod.vars;
|
|
458
|
+
if (modVars?.length) {
|
|
459
|
+
lines.push(`${pfx} vars:`);
|
|
460
|
+
modVars.forEach(v => {
|
|
461
|
+
if (v.name) lines.push(`${pfx} ${v.name} = ${v.defaultValue}`);
|
|
462
|
+
});
|
|
463
|
+
lines.push('');
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
internalActions.forEach((a) => emitAction(a, indentLevel + 1));
|
|
467
|
+
|
|
468
|
+
const daughterModules = (libModules || []).filter(
|
|
469
|
+
(m) =>
|
|
470
|
+
m.path &&
|
|
471
|
+
m.path.length === mod.path.length + 1 &&
|
|
472
|
+
mod.path.every((seg, i) => seg === m.path[i])
|
|
473
|
+
);
|
|
474
|
+
daughterModules.forEach((m) => emitModule(m, indentLevel + 1));
|
|
475
|
+
|
|
476
|
+
lines.push(`${pfx} flow:`);
|
|
477
|
+
(mod.nodes || [])
|
|
478
|
+
.filter((n) => n.type !== 'special' && n.type !== 'for_out' && n.type !== 'par_out')
|
|
479
|
+
.forEach((n) => {
|
|
480
|
+
const ref =
|
|
481
|
+
n.type === 'module'
|
|
482
|
+
? `&${n.modRef || 'Module'}`
|
|
483
|
+
: n.type === 'position'
|
|
484
|
+
? ''
|
|
485
|
+
: actionMap.get(n.actionId) || 'unnamed';
|
|
486
|
+
lines.push(`${pfx} ${n.label}: ${ref}`);
|
|
487
|
+
});
|
|
488
|
+
lines.push('');
|
|
489
|
+
const modCycleMap = findAllCycleEdges(mod.nodes || [], mod.edges || []);
|
|
490
|
+
const modBack = findBackEdges(mod.nodes || [], mod.edges || []);
|
|
491
|
+
console.log('[emitModule] 模块:', mod.name, 'cycleEdges:', modCycleMap.size, 'back:', modBack.size);
|
|
492
|
+
emitFlowLines(mod.nodes || [], mod.edges || [], indentLevel + 2, lines, modCycleMap, modBack);
|
|
493
|
+
lines.push('');
|
|
494
|
+
// ── sketch(节点排版位置,相对于 IN 锚点;注释形式,后端忽略)──
|
|
495
|
+
const modAnchor = (mod.nodes || []).find(
|
|
496
|
+
n => n.type === 'special' && (n.specialType === 'IN' || n.specialType === 'START')
|
|
497
|
+
);
|
|
498
|
+
const modSketchNodes = (mod.nodes || []).filter(
|
|
499
|
+
n => n.id !== modAnchor?.id && n.type !== 'for_out'
|
|
500
|
+
);
|
|
501
|
+
if (modAnchor && modSketchNodes.length > 0) {
|
|
502
|
+
lines.push(`#${pfx} sketch:`);
|
|
503
|
+
modSketchNodes.forEach(n => {
|
|
504
|
+
lines.push(`#${pfx} ${n.label} = ${Math.round(n.x - modAnchor.x)}, ${Math.round(n.y - modAnchor.y)}`);
|
|
505
|
+
});
|
|
506
|
+
lines.push('');
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const topModules = (libModules || []).filter(
|
|
511
|
+
(m) => m.path && m.path.length === 2 && m.path[0] === 'mainflow'
|
|
512
|
+
);
|
|
513
|
+
topModules.forEach((m) => emitModule(m, 0));
|
|
514
|
+
|
|
515
|
+
// ── mainflow ──
|
|
516
|
+
lines.push('mainflow:');
|
|
517
|
+
const mainNodes = nodes.filter((n) => n.type !== 'special' && n.type !== 'for_out' && n.type !== 'par_out');
|
|
518
|
+
mainNodes.forEach((n) => {
|
|
519
|
+
const ref =
|
|
520
|
+
n.type === 'module'
|
|
521
|
+
? `&${n.modRef || 'Module'}`
|
|
522
|
+
: n.type === 'position'
|
|
523
|
+
? ''
|
|
524
|
+
: actionMap.get(n.actionId) || 'unnamed';
|
|
525
|
+
lines.push(` ${n.label}: ${ref}`);
|
|
526
|
+
});
|
|
527
|
+
lines.push('');
|
|
528
|
+
//console.log('[buildFEMO] 主流程 emitFlowLines, 传入 back:', back.size, '边');
|
|
529
|
+
emitFlowLines(nodes, edges, 1, lines, cycleEdgesMap, back);
|
|
530
|
+
|
|
531
|
+
// ── mainflow sketch(节点排版位置,相对于 START 锚点;注释形式,后端忽略)──
|
|
532
|
+
const mainAnchor = nodes.find(n => n.type === 'special' && n.specialType === 'START');
|
|
533
|
+
const mainSketchNodes = nodes.filter(n => n.id !== mainAnchor?.id && n.type !== 'for_out');
|
|
534
|
+
if (mainAnchor && mainSketchNodes.length > 0) {
|
|
535
|
+
lines.push('\n#sketch:');
|
|
536
|
+
mainSketchNodes.forEach(n => {
|
|
537
|
+
lines.push(`# ${n.label} = ${Math.round(n.x - mainAnchor.x)}, ${Math.round(n.y - mainAnchor.y)}`);
|
|
538
|
+
});
|
|
539
|
+
lines.push('');
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
return lines.join('\n');
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function emitFlowLines(nodes, edges, baseIndent, lines, cycleEdgesMap, back) {
|
|
546
|
+
if (!back) {
|
|
547
|
+
console.log('[emitFlowLines] back 未传入, 重新计算, nodes:', nodes.length, 'edges:', edges.length);
|
|
548
|
+
back = findBackEdges(nodes, edges);
|
|
549
|
+
} else {
|
|
550
|
+
//console.log('[emitFlowLines] 使用传入的 back, 边数:', back.size);
|
|
551
|
+
}
|
|
552
|
+
const nm = new Map(nodes.map((n) => [n.id, n]));
|
|
553
|
+
const pfx = ' '.repeat(baseIndent);
|
|
554
|
+
|
|
555
|
+
const adj = new Map();
|
|
556
|
+
const inAdj = new Map();
|
|
557
|
+
edges.forEach((e) => {
|
|
558
|
+
if (!adj.has(e.src)) adj.set(e.src, []);
|
|
559
|
+
adj.get(e.src).push(e);
|
|
560
|
+
if (!inAdj.has(e.tgt)) inAdj.set(e.tgt, []);
|
|
561
|
+
inAdj.get(e.tgt).push(e);
|
|
562
|
+
});
|
|
563
|
+
|
|
564
|
+
// ═══ 1. 提取所有指向 FOR/PAR 节点的入口边,并从 adj 中移除,防止 walk 输出普通连线 ═══
|
|
565
|
+
const specialEntryEdgesMap = new Map(); // src -> [edge]
|
|
566
|
+
for (const [src, edgeList] of adj.entries()) {
|
|
567
|
+
const specialEdges = edgeList.filter(e => {
|
|
568
|
+
const tgtNode = nm.get(e.tgt);
|
|
569
|
+
return tgtNode && tgtNode.type === 'special' &&
|
|
570
|
+
(tgtNode.specialType === 'FOR' || tgtNode.specialType === 'PAR');
|
|
571
|
+
});
|
|
572
|
+
if (specialEdges.length > 0) {
|
|
573
|
+
specialEntryEdgesMap.set(src, specialEdges);
|
|
574
|
+
adj.set(src, edgeList.filter(e => !specialEdges.includes(e)));
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// ── 自动将新加入的入边归入 joinEntries 的 all 组 ──
|
|
579
|
+
nodes.forEach(node => {
|
|
580
|
+
if (node.joinEntries && node.joinEntries.length > 0) {
|
|
581
|
+
const allIncoming = (inAdj.get(node.id) || [])
|
|
582
|
+
.filter(e => !back.has(e.id))
|
|
583
|
+
.map(e => {
|
|
584
|
+
const lbl = nm.get(e.src)?.label || '';
|
|
585
|
+
return lbl.replace(/^\[|\]$/g, ''); // 去括号,与 joinEntries 的 sources 一致
|
|
586
|
+
})
|
|
587
|
+
.filter(Boolean);
|
|
588
|
+
const coveredSources = new Set();
|
|
589
|
+
node.joinEntries.forEach(entry => entry.sources.forEach(s => coveredSources.add(s)));
|
|
590
|
+
const newSources = allIncoming.filter(s => !coveredSources.has(s));
|
|
591
|
+
if (newSources.length > 0) {
|
|
592
|
+
let allEntry = node.joinEntries.find(e => e.param === 'all');
|
|
593
|
+
if (!allEntry) {
|
|
594
|
+
allEntry = { param: 'all', sources: [] };
|
|
595
|
+
node.joinEntries.push(allEntry);
|
|
596
|
+
}
|
|
597
|
+
allEntry.sources.push(...newSources);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
const emittedFors = new Set();
|
|
603
|
+
|
|
604
|
+
// ★ 统一连接符:一处定义,四处复用
|
|
605
|
+
function flowConnector(cond) {
|
|
606
|
+
return cond ? `-> if (${cond}) ->` : '->';
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
function emitForBlock(forNodeId, indentLevel) {
|
|
610
|
+
const forNode = nm.get(forNodeId);
|
|
611
|
+
const isPar = forNode.specialType === 'PAR';
|
|
612
|
+
const condition = forNode.forCondition || '@item in collection';
|
|
613
|
+
const ipfx = ' '.repeat(indentLevel);
|
|
614
|
+
|
|
615
|
+
// 上游节点 label
|
|
616
|
+
const incomingEdges = inAdj.get(forNodeId) || [];
|
|
617
|
+
const upstreamEdge = incomingEdges.find(e => !back.has(e.id));
|
|
618
|
+
const upstreamLabel = upstreamEdge ? nm.get(upstreamEdge.src)?.label : '?';
|
|
619
|
+
|
|
620
|
+
const keyword = isPar ? 'par' : 'for';
|
|
621
|
+
lines.push(`${ipfx}${upstreamLabel} -> ${keyword} ${condition}:`);
|
|
622
|
+
|
|
623
|
+
const cycleEdgeSet = cycleEdgesMap.get(forNodeId) || new Set();
|
|
624
|
+
|
|
625
|
+
// 出口节点(for_out / par_out)
|
|
626
|
+
const exitType = isPar ? 'par_out' : 'for_out';
|
|
627
|
+
const forOutNode = nodes.find(n => n.type === exitType && n.forNodeId === forNodeId);
|
|
628
|
+
const forOutNodeId = forOutNode?.id;
|
|
629
|
+
|
|
630
|
+
// 收集环内边
|
|
631
|
+
const entryEdges = [];
|
|
632
|
+
const backEdges = [];
|
|
633
|
+
const internalEdges = [];
|
|
634
|
+
|
|
635
|
+
const stack = [forNodeId];
|
|
636
|
+
const visitedForBody = new Set();
|
|
637
|
+
|
|
638
|
+
while (stack.length > 0) {
|
|
639
|
+
const cur = stack.pop();
|
|
640
|
+
for (const e of adj.get(cur) || []) {
|
|
641
|
+
if (!cycleEdgeSet.has(e.id)) continue;
|
|
642
|
+
if (visitedForBody.has(e.id)) continue;
|
|
643
|
+
visitedForBody.add(e.id);
|
|
644
|
+
|
|
645
|
+
if (cur === forNodeId) {
|
|
646
|
+
entryEdges.push(e);
|
|
647
|
+
} else if (e.tgt === forNodeId || (forOutNodeId && e.tgt === forOutNodeId)) {
|
|
648
|
+
backEdges.push(e);
|
|
649
|
+
} else {
|
|
650
|
+
internalEdges.push({ src: cur, tgt: e.tgt, cond: e.cond || '' });
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
if (e.tgt !== forNodeId && e.tgt !== forOutNodeId) {
|
|
654
|
+
stack.push(e.tgt);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
const bodyIndent = indentLevel + 1;
|
|
660
|
+
const bp = ' '.repeat(bodyIndent);
|
|
661
|
+
|
|
662
|
+
const entryVisited = new Set();
|
|
663
|
+
|
|
664
|
+
for (const ee of entryEdges) {
|
|
665
|
+
const startTgt = nm.get(ee.tgt);
|
|
666
|
+
if (!startTgt || entryVisited.has(ee.tgt)) continue;
|
|
667
|
+
entryVisited.add(ee.tgt);
|
|
668
|
+
|
|
669
|
+
const chainParts = [];
|
|
670
|
+
if (ee.cond) {
|
|
671
|
+
chainParts.push(`if (${ee.cond}) -> ${startTgt.label}`);
|
|
672
|
+
} else {
|
|
673
|
+
chainParts.push(startTgt.label);
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
let current = ee.tgt;
|
|
677
|
+
const localVisited = new Set([ee.id, ee.tgt]);
|
|
678
|
+
|
|
679
|
+
while (true) {
|
|
680
|
+
const outs = internalEdges.filter(e => e.src === current);
|
|
681
|
+
if (outs.length === 1) {
|
|
682
|
+
const nextEdge = outs[0];
|
|
683
|
+
if (forOutNode && nextEdge.tgt === forOutNode.id) break;
|
|
684
|
+
if (localVisited.has(nextEdge.tgt)) break;
|
|
685
|
+
const tgtNode = nm.get(nextEdge.tgt);
|
|
686
|
+
if (!tgtNode) break;
|
|
687
|
+
|
|
688
|
+
if (nextEdge.cond) {
|
|
689
|
+
chainParts.push(`if (${nextEdge.cond}) -> ${tgtNode.label}`);
|
|
690
|
+
} else {
|
|
691
|
+
chainParts.push(tgtNode.label);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
localVisited.add(nextEdge.tgt);
|
|
695
|
+
current = nextEdge.tgt;
|
|
696
|
+
} else {
|
|
697
|
+
break;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// 3)如果最后一步连到出口节点,加箭头(出口侧)
|
|
702
|
+
const endsAtExit = forOutNode && (adj.get(current) || []).some(e => e.tgt === forOutNode.id);
|
|
703
|
+
const endsAtFor = edges.some(e => e.src === current && e.tgt === forNodeId);
|
|
704
|
+
const chainStr = chainParts.join(' -> ');
|
|
705
|
+
|
|
706
|
+
// ★ 检测回指边:当前节点是否有指向 localVisited 中已访问节点的 cinrcleEdge 出边
|
|
707
|
+
const loopBackEdges = internalEdges.filter(e =>
|
|
708
|
+
e.src === current && localVisited.has(e.tgt) && nm.has(e.tgt)
|
|
709
|
+
);
|
|
710
|
+
|
|
711
|
+
// ★ 检测额外出边:当前节点是否有不在 localVisited 中的 cycleEdge 出边(排除 forOutNode)
|
|
712
|
+
const extraEdges = internalEdges.filter(e =>
|
|
713
|
+
e.src === current && !localVisited.has(e.tgt) &&
|
|
714
|
+
e.tgt !== current && !(forOutNode && e.tgt === forOutNode.id)
|
|
715
|
+
);
|
|
716
|
+
|
|
717
|
+
if (loopBackEdges.length > 0 || extraEdges.length > 0) {
|
|
718
|
+
// 主链照常输出(含退出标记)
|
|
719
|
+
const arrowSuffix = (endsAtExit || endsAtFor) ? ' ->' : '';
|
|
720
|
+
lines.push(`${bp}-> ${chainStr}${arrowSuffix}`);
|
|
721
|
+
console.log('[emitForBlock] 回指边输出, current:', nm.get(current)?.label, 'loopBack:', loopBackEdges.map(e => `${nm.get(e.src)?.label}->${nm.get(e.tgt)?.label}`), 'extra:', extraEdges.map(e => `${nm.get(e.src)?.label}->${nm.get(e.tgt)?.label}`));
|
|
722
|
+
|
|
723
|
+
// 回指边和额外出边:作为独立行输出(不以 -> 开头)
|
|
724
|
+
const seenTgt = new Set();
|
|
725
|
+
for (const lb of loopBackEdges) {
|
|
726
|
+
const tgtLabel = nm.get(lb.tgt)?.label;
|
|
727
|
+
if (!tgtLabel || seenTgt.has(lb.tgt)) continue;
|
|
728
|
+
seenTgt.add(lb.tgt);
|
|
729
|
+
const srcLabel = nm.get(lb.src)?.label || '?';
|
|
730
|
+
lines.push(`${bp}${srcLabel} ${flowConnector(lb.cond)} ${tgtLabel}`);
|
|
731
|
+
}
|
|
732
|
+
for (const ef of extraEdges) {
|
|
733
|
+
const tgtLabel = nm.get(ef.tgt)?.label;
|
|
734
|
+
if (!tgtLabel || seenTgt.has(ef.tgt)) continue;
|
|
735
|
+
seenTgt.add(ef.tgt);
|
|
736
|
+
const srcLabel = nm.get(ef.src)?.label || '?';
|
|
737
|
+
lines.push(`${bp}${srcLabel} ${flowConnector(ef.cond)} ${tgtLabel}`);
|
|
738
|
+
}
|
|
739
|
+
} else {
|
|
740
|
+
const arrowSuffix = (endsAtExit || endsAtFor) ? ' ->' : '';
|
|
741
|
+
lines.push(`${bp}-> ${chainStr}${arrowSuffix}`);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
// 出口行
|
|
753
|
+
if (forOutNode) {
|
|
754
|
+
const exitEdges = adj.get(forOutNode.id) || [];
|
|
755
|
+
if (exitEdges.length > 0) {
|
|
756
|
+
const exitTarget = nm.get(exitEdges[0].tgt);
|
|
757
|
+
if (exitTarget) {
|
|
758
|
+
lines.push(`${ipfx}-> ${exitTarget.label}`);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
emittedFors.add(forNodeId);
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
function emitParBlock(parNodeId, indentLevel) {
|
|
767
|
+
const parNode = nm.get(parNodeId);
|
|
768
|
+
const condition = parNode.forCondition || '@item in collection';
|
|
769
|
+
const ipfx = ' '.repeat(indentLevel);
|
|
770
|
+
|
|
771
|
+
// 找上游节点 label
|
|
772
|
+
const incomingEdges = inAdj.get(parNodeId) || [];
|
|
773
|
+
const upstreamEdge = incomingEdges.find(e => !back.has(e.id));
|
|
774
|
+
const upstreamLabel = upstreamEdge ? nm.get(upstreamEdge.src)?.label : '?';
|
|
775
|
+
lines.push(`${ipfx}${upstreamLabel} -> par ${condition}:`);
|
|
776
|
+
|
|
777
|
+
const bp = ' '.repeat(indentLevel + 1);
|
|
778
|
+
const parOutNode = nodes.find(n => n.type === 'par_out' && n.forNodeId === parNodeId);
|
|
779
|
+
const parOutId = parOutNode?.id;
|
|
780
|
+
|
|
781
|
+
// 每条分支从 PAR 出发,向前追踪到 PAR_OUT
|
|
782
|
+
const branchEdges = adj.get(parNodeId) || [];
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
for (const be of branchEdges) {
|
|
794
|
+
const startNode = nm.get(be.tgt);
|
|
795
|
+
if (!startNode) continue;
|
|
796
|
+
//console.log('[emitParBlock] 分支起点:', startNode.label, 'cond:', be.cond || '(无)');
|
|
797
|
+
|
|
798
|
+
const chainParts = be.cond
|
|
799
|
+
? [`if (${be.cond}) -> ${startNode.label}`]
|
|
800
|
+
: [startNode.label];
|
|
801
|
+
|
|
802
|
+
let current = be.tgt;
|
|
803
|
+
const localVisited = new Set([parNodeId, be.tgt]);
|
|
804
|
+
|
|
805
|
+
// ★ 追踪过程中逐步收集所有中间节点的回边和额外出边
|
|
806
|
+
const collectedLoopBacks = [];
|
|
807
|
+
const collectedExtras = [];
|
|
808
|
+
|
|
809
|
+
while (true) {
|
|
810
|
+
//console.log('[emitParBlock] while 追踪, current:', nm.get(current)?.label, 'localVisited:', [...localVisited].map(id => nm.get(id)?.label).join(','));
|
|
811
|
+
|
|
812
|
+
// ★ 每次迭代:检查当前节点是否有指向 localVisited 中已访问节点的回边
|
|
813
|
+
const curLoopBacks = (adj.get(current) || []).filter(e =>
|
|
814
|
+
localVisited.has(e.tgt) && nm.has(e.tgt) && e.tgt !== parNodeId
|
|
815
|
+
);
|
|
816
|
+
if (curLoopBacks.length > 0) {
|
|
817
|
+
//console.log('[emitParBlock] 发现回边:', curLoopBacks.map(e => `${nm.get(e.src)?.label}->${nm.get(e.tgt)?.label}`).join(', '));
|
|
818
|
+
}
|
|
819
|
+
for (const e of curLoopBacks) collectedLoopBacks.push(e);
|
|
820
|
+
|
|
821
|
+
// 前向出边(排除 parOut、parNode、已访问节点、back 边)
|
|
822
|
+
const nexts = (adj.get(current) || []).filter(e =>
|
|
823
|
+
e.tgt !== parOutId && e.tgt !== parNodeId && !localVisited.has(e.tgt) && !back.has(e.id)
|
|
824
|
+
);
|
|
825
|
+
//console.log('[emitParBlock] nexts:', nexts.map(e => `${nm.get(e.src)?.label}->${nm.get(e.tgt)?.label}`).join(', '), 'nexts.length:', nexts.length);
|
|
826
|
+
|
|
827
|
+
// ★ 分叉检测:有回边 OR 前向边数量不是 1 → break
|
|
828
|
+
if (curLoopBacks.length > 0 || nexts.length !== 1) {
|
|
829
|
+
// 当前节点剩余的前向出边收集为额外出边
|
|
830
|
+
for (const e of nexts) collectedExtras.push(e);
|
|
831
|
+
if (curLoopBacks.length > 0) {
|
|
832
|
+
//console.log('[emitParBlock] 回边触发 fork, 当前节点', nm.get(current)?.label, '收集前向边:', nexts.map(e => e.tgt).map(id => nm.get(id)?.label).join(', '));
|
|
833
|
+
} else {
|
|
834
|
+
console.log('[emitParBlock] 非回边 fork/dead-end, nexts.length:', nexts.length);
|
|
835
|
+
}
|
|
836
|
+
break;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// 单条前向边 → 继续追踪
|
|
840
|
+
const nextEdge = nexts[0];
|
|
841
|
+
const tgtNode = nm.get(nextEdge.tgt);
|
|
842
|
+
if (!tgtNode) { console.log('[emitParBlock] tgtNode 为空, break'); break; }
|
|
843
|
+
//console.log('[emitParBlock] 追踪前进:', nm.get(current)?.label, '->', tgtNode.label, 'cond:', nextEdge.cond || '(无)');
|
|
844
|
+
chainParts.push(nextEdge.cond
|
|
845
|
+
? `if (${nextEdge.cond}) -> ${tgtNode.label}`
|
|
846
|
+
: tgtNode.label);
|
|
847
|
+
localVisited.add(nextEdge.tgt);
|
|
848
|
+
current = nextEdge.tgt;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
// 主链出口判断
|
|
852
|
+
const toParOut = parOutId && (adj.get(current) || []).some(e => e.tgt === parOutId);
|
|
853
|
+
const chainStr = chainParts.join(' -> ');
|
|
854
|
+
//console.log('[emitParBlock] 追踪结束, current:', nm.get(current)?.label, 'toParOut:', toParOut, 'collectedLoopBacks:', collectedLoopBacks.length, 'collectedExtras:', collectedExtras.length);
|
|
855
|
+
|
|
856
|
+
// 输出主链(含出口箭头)
|
|
857
|
+
const arrowSuffix = toParOut ? ' ->' : '';
|
|
858
|
+
const mainLine = `${bp}-> ${chainStr}${arrowSuffix}`;
|
|
859
|
+
lines.push(mainLine);
|
|
860
|
+
//console.log('[emitParBlock] 输出主链:', mainLine);
|
|
861
|
+
|
|
862
|
+
// 输出所有收集到的回边(独立行)
|
|
863
|
+
const seenBackTgt = new Set();
|
|
864
|
+
for (const lb of collectedLoopBacks) {
|
|
865
|
+
const tgtLabel = nm.get(lb.tgt)?.label;
|
|
866
|
+
if (!tgtLabel || seenBackTgt.has(lb.tgt)) continue;
|
|
867
|
+
seenBackTgt.add(lb.tgt);
|
|
868
|
+
const srcLabel = nm.get(lb.src)?.label || '?';
|
|
869
|
+
const line = `${bp}${srcLabel} ${flowConnector(lb.cond)} ${tgtLabel}`;
|
|
870
|
+
lines.push(line);
|
|
871
|
+
//console.log('[emitParBlock] 输出回边:', line);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
// 输出所有收集到的额外出边(独立行,检查目标是否有到 parOut 的出口)
|
|
875
|
+
const seenExtraTgt = new Set();
|
|
876
|
+
for (const ef of collectedExtras) {
|
|
877
|
+
const tgtLabel = nm.get(ef.tgt)?.label;
|
|
878
|
+
if (!tgtLabel || seenExtraTgt.has(ef.tgt)) continue;
|
|
879
|
+
seenExtraTgt.add(ef.tgt);
|
|
880
|
+
// ★ 额外出边的目标节点如果直接连到 parOut,追加出口箭头
|
|
881
|
+
const tgtHasParOut = parOutId && (adj.get(ef.tgt) || []).some(e2 => e2.tgt === parOutId);
|
|
882
|
+
const srcLabel = nm.get(ef.src)?.label || '?';
|
|
883
|
+
const extraArrow = tgtHasParOut ? ' ->' : '';
|
|
884
|
+
const line = `${bp}${srcLabel} ${flowConnector(ef.cond)} ${tgtLabel}${extraArrow}`;
|
|
885
|
+
lines.push(line);
|
|
886
|
+
//console.log('[emitParBlock] 输出额外出边:', line, 'tgtHasParOut:', tgtHasParOut);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// PAR 出口行
|
|
891
|
+
if (parOutNode) {
|
|
892
|
+
const exitEdges = adj.get(parOutNode.id) || [];
|
|
893
|
+
if (exitEdges.length > 0) {
|
|
894
|
+
const exitTarget = nm.get(exitEdges[0].tgt);
|
|
895
|
+
if (exitTarget) lines.push(`${ipfx}-> ${exitTarget.label}`);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
emittedFors.add(parNodeId);
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
|
|
903
|
+
// ═══ 修复 3:position 节点不参与 join 阻塞 ═══
|
|
904
|
+
// 【2026-09-07 二次修复】不再把"多入边合流"自动当成 join:
|
|
905
|
+
// 普通多线合流(互斥分支汇入同一点)的语义是"到即走",与 join(all) 的
|
|
906
|
+
// "等全部到齐"完全不同——自动生成 join(all) 会在互斥分支场景永久死等
|
|
907
|
+
// (实锤:警长版 DayPhase 的 [get_order] 有三条互斥入边,被自动 join(all)
|
|
908
|
+
// 后等永不运行的 [移交警徽],一局卡死)。
|
|
909
|
+
// 只有源文本里显式写了 join(...): 的节点(解析期记入 node.joinEntries)
|
|
910
|
+
// 才按 join 序列化;普通合流一律输出普通边([A] -> [next] 逐条)。
|
|
911
|
+
const joinNodes = new Map();
|
|
912
|
+
inAdj.forEach((eds, nodeId) => {
|
|
913
|
+
const node = nm.get(nodeId);
|
|
914
|
+
if (node && node.type === 'position') return;
|
|
915
|
+
if (node && node.type === 'par_out') return;
|
|
916
|
+
if (node && Array.isArray(node.joinEntries) && node.joinEntries.length > 0) {
|
|
917
|
+
const normal = eds.filter((e) => !back.has(e.id));
|
|
918
|
+
if (normal.length > 1) joinNodes.set(nodeId, normal.length);
|
|
919
|
+
}
|
|
920
|
+
});
|
|
921
|
+
|
|
922
|
+
const startNode = nodes.find(
|
|
923
|
+
(n) =>
|
|
924
|
+
n.type === 'special' &&
|
|
925
|
+
(n.specialType === 'START' || n.specialType === 'IN')
|
|
926
|
+
);
|
|
927
|
+
|
|
928
|
+
if (startNode) {
|
|
929
|
+
const visited = new Set();
|
|
930
|
+
const joinReached = new Map();
|
|
931
|
+
|
|
932
|
+
function walk(id) {
|
|
933
|
+
const node = nm.get(id);
|
|
934
|
+
if (!node) return;
|
|
935
|
+
|
|
936
|
+
if ((node.specialType === 'FOR' || node.specialType === 'PAR') && (!cycleEdgesMap || !cycleEdgesMap.has(id))) {
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
// ═══ 2. 遍历入口边,生成 for/par 块 ═══
|
|
941
|
+
const specialEntries = specialEntryEdgesMap.get(id) || [];
|
|
942
|
+
for (const se of specialEntries) {
|
|
943
|
+
const tgtNode = nm.get(se.tgt);
|
|
944
|
+
if (!tgtNode || emittedFors.has(se.tgt)) continue;
|
|
945
|
+
// ★ 区分 FOR 和 PAR:PAR 必须走 emitParBlock,否则回边场景会丢出口箭头
|
|
946
|
+
if (tgtNode.specialType === 'PAR') {
|
|
947
|
+
//console.log('[walk] specialEntry→PAR, id:', id, 'label:', tgtNode.label, '→ emitParBlock');
|
|
948
|
+
emitParBlock(se.tgt, baseIndent);
|
|
949
|
+
} else {
|
|
950
|
+
//console.log('[walk] specialEntry→FOR, id:', id, 'label:', tgtNode.label, '→ emitForBlock');
|
|
951
|
+
emitForBlock(se.tgt, baseIndent);
|
|
952
|
+
}
|
|
953
|
+
const exitType = tgtNode.specialType === 'PAR' ? 'par_out' : 'for_out';
|
|
954
|
+
const forOutNode = nodes.find(n => n.type === exitType && n.forNodeId === se.tgt);
|
|
955
|
+
if (forOutNode) {
|
|
956
|
+
const exitEdges = adj.get(forOutNode.id) || [];
|
|
957
|
+
if (exitEdges.length > 0) walk(exitEdges[0].tgt);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
if (joinNodes.has(id) || (node.joinEntries && node.joinEntries.length > 0)) {
|
|
962
|
+
// 如果节点有 joinEntries,使用其中定义的参数和源列表;
|
|
963
|
+
// 否则是自动检测的汇聚,生成 join(all)
|
|
964
|
+
if (node.joinEntries && node.joinEntries.length > 0) {
|
|
965
|
+
// 等待所有入边都就位(如果该节点在 joinNodes 中)
|
|
966
|
+
if (joinNodes.has(id)) {
|
|
967
|
+
const cnt = (joinReached.get(id) || 0) + 1;
|
|
968
|
+
joinReached.set(id, cnt);
|
|
969
|
+
if (cnt < joinNodes.get(id)) return;
|
|
970
|
+
}
|
|
971
|
+
for (const entry of node.joinEntries) {
|
|
972
|
+
lines.push(`${pfx}join(${entry.param}):`);
|
|
973
|
+
for (const srcLabel of entry.sources) {
|
|
974
|
+
const clean = String(srcLabel).replace(/^\[|\]$/g, '');
|
|
975
|
+
lines.push(`${pfx} [${clean}] ->`);
|
|
976
|
+
}
|
|
977
|
+
lines.push(`${pfx}to ${node.label}`);
|
|
978
|
+
}
|
|
979
|
+
} else if (joinNodes.has(id)) {
|
|
980
|
+
const cnt = (joinReached.get(id) || 0) + 1;
|
|
981
|
+
joinReached.set(id, cnt);
|
|
982
|
+
if (cnt < joinNodes.get(id)) return;
|
|
983
|
+
const sources = inAdj.get(id).filter((e) => !back.has(e.id));
|
|
984
|
+
// 自动生成 joinEntries 的 all 条目,方便后续新增边归入
|
|
985
|
+
if (!node.joinEntries) node.joinEntries = [];
|
|
986
|
+
node.joinEntries.push({ sources: sources.map(e => nm.get(e.src)?.label).filter(Boolean), param: 'all' });
|
|
987
|
+
lines.push(`${pfx}join(all):`);
|
|
988
|
+
sources.forEach((e) =>
|
|
989
|
+
lines.push(`${pfx} ${nm.get(e.src)?.label} ->`)
|
|
990
|
+
);
|
|
991
|
+
lines.push(`${pfx}to ${node.label}`);
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
// PAR 节点:分支向前汇聚,不走 cycleEdgesMap,单独处理
|
|
996
|
+
if (node.specialType === 'PAR') {
|
|
997
|
+
if (!emittedFors.has(id)) {
|
|
998
|
+
emitParBlock(id, baseIndent);
|
|
999
|
+
const parOutNode = nodes.find(n => n.type === 'par_out' && n.forNodeId === id);
|
|
1000
|
+
if (parOutNode) {
|
|
1001
|
+
const exitEdges = adj.get(parOutNode.id) || [];
|
|
1002
|
+
if (exitEdges.length > 0) walk(exitEdges[0].tgt);
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
if (!visited.has(id)) visited.add(id);
|
|
1006
|
+
return;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
// ═══ 修复 4:FOR 节点必须标记 visited,防止重复 emit 和断链 ═══
|
|
1010
|
+
if (node.specialType === 'FOR' && cycleEdgesMap && cycleEdgesMap.has(id)) {
|
|
1011
|
+
if (!emittedFors.has(id)) {
|
|
1012
|
+
emitForBlock(id, baseIndent);
|
|
1013
|
+
const forOutNode = nodes.find(n => n.type === 'for_out' && n.forNodeId === id);
|
|
1014
|
+
if (forOutNode) {
|
|
1015
|
+
const exitEdges = adj.get(forOutNode.id) || [];
|
|
1016
|
+
if (exitEdges.length > 0) walk(exitEdges[0].tgt);
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
if (!visited.has(id)) visited.add(id);
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
if (visited.has(id)) return;
|
|
1024
|
+
visited.add(id);
|
|
1025
|
+
|
|
1026
|
+
const outs = (adj.get(id) || []).filter((e) => {
|
|
1027
|
+
if (back.has(e.id)) return false;
|
|
1028
|
+
const tgtNode = nm.get(e.tgt);
|
|
1029
|
+
if (tgtNode && tgtNode.specialType === 'FOR' && !cycleEdgesMap?.has(e.tgt)) return false;
|
|
1030
|
+
return true;
|
|
1031
|
+
});
|
|
1032
|
+
|
|
1033
|
+
const backOuts = (adj.get(id) || []).filter((e) => back.has(e.id));
|
|
1034
|
+
|
|
1035
|
+
if (backOuts.length) {
|
|
1036
|
+
if (outs.length > 0 || backOuts.some(e => e.cond)) {
|
|
1037
|
+
// 带条件的回边 + 前向边 → 统一生成 fork:
|
|
1038
|
+
const allEdges = [...backOuts, ...outs];
|
|
1039
|
+
lines.push(`${pfx}${node.label} -> fork:`);
|
|
1040
|
+
const seenForkTgt = new Set();
|
|
1041
|
+
allEdges.forEach((e) => {
|
|
1042
|
+
const tgt = nm.get(e.tgt);
|
|
1043
|
+
if (!tgt || seenForkTgt.has(tgt.id)) return;
|
|
1044
|
+
seenForkTgt.add(tgt.id);
|
|
1045
|
+
const cond = e.cond ? ` if (${e.cond}) ->` : '';
|
|
1046
|
+
lines.push(`${pfx} ->${cond} ${tgt.label}`);
|
|
1047
|
+
});
|
|
1048
|
+
outs.forEach((e) => walk(e.tgt));
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
// 纯无条件回边(简单 for 循环):输出显式边(不再生成 # for loop 注释)
|
|
1052
|
+
backOuts.forEach((e) => {
|
|
1053
|
+
lines.push(`${pfx}${node.label} -> ${nm.get(e.tgt)?.label}`);
|
|
1054
|
+
});
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
// 过滤掉指向 PAR 的边(由 emitParBlock 统一处理)
|
|
1058
|
+
const outsWithoutPar = outs.filter(e => {
|
|
1059
|
+
const tgtNode = nm.get(e.tgt);
|
|
1060
|
+
return !(tgtNode && tgtNode.specialType === 'PAR');
|
|
1061
|
+
});
|
|
1062
|
+
|
|
1063
|
+
if (outsWithoutPar.length === 0) {
|
|
1064
|
+
// 只剩 PAR 出口,交给 emitParBlock(如果还没处理)
|
|
1065
|
+
outs.forEach(e => {
|
|
1066
|
+
const tgtNode = nm.get(e.tgt);
|
|
1067
|
+
if (tgtNode && tgtNode.specialType === 'PAR' && !emittedFors.has(e.tgt)) {
|
|
1068
|
+
emitParBlock(e.tgt, baseIndent);
|
|
1069
|
+
const parOutNode = nodes.find(n => n.type === 'par_out' && n.forNodeId === e.tgt);
|
|
1070
|
+
if (parOutNode) {
|
|
1071
|
+
const exitEdges = adj.get(parOutNode.id) || [];
|
|
1072
|
+
if (exitEdges.length > 0) walk(exitEdges[0].tgt);
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
});
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
if (outsWithoutPar.length === 1) {
|
|
1080
|
+
const e = outsWithoutPar[0];
|
|
1081
|
+
const tgt = nm.get(e.tgt);
|
|
1082
|
+
if (tgt && tgt.specialType === 'FOR' && cycleEdgesMap?.has(e.tgt)) {
|
|
1083
|
+
walk(e.tgt);
|
|
1084
|
+
} else if (tgt && tgt.specialType === 'PAR' && !emittedFors.has(e.tgt)) {
|
|
1085
|
+
emitParBlock(e.tgt, baseIndent);
|
|
1086
|
+
const parOutNode = nodes.find(n => n.type === 'par_out' && n.forNodeId === e.tgt);
|
|
1087
|
+
if (parOutNode) {
|
|
1088
|
+
const exitEdges = adj.get(parOutNode.id) || [];
|
|
1089
|
+
if (exitEdges.length > 0) walk(exitEdges[0].tgt);
|
|
1090
|
+
}
|
|
1091
|
+
} else if (tgt && !joinNodes.has(e.tgt)) {
|
|
1092
|
+
const cond = e.cond ? ` if (${e.cond}) ->` : '';
|
|
1093
|
+
lines.push(`${pfx}${node.label} ->${cond} ${tgt.label}`);
|
|
1094
|
+
walk(e.tgt);
|
|
1095
|
+
} else {
|
|
1096
|
+
walk(e.tgt);
|
|
1097
|
+
}
|
|
1098
|
+
} else {
|
|
1099
|
+
// 分离 PAR 出口和普通出口
|
|
1100
|
+
const parOuts = [];
|
|
1101
|
+
const normalOuts = [];
|
|
1102
|
+
outs.forEach(e => {
|
|
1103
|
+
const tgtNode = nm.get(e.tgt);
|
|
1104
|
+
if (tgtNode && tgtNode.specialType === 'PAR') {
|
|
1105
|
+
parOuts.push(e);
|
|
1106
|
+
} else {
|
|
1107
|
+
normalOuts.push(e);
|
|
1108
|
+
}
|
|
1109
|
+
});
|
|
1110
|
+
|
|
1111
|
+
// 先处理 PAR 出口(不打印普通边)
|
|
1112
|
+
parOuts.forEach(e => {
|
|
1113
|
+
if (!emittedFors.has(e.tgt)) {
|
|
1114
|
+
emitParBlock(e.tgt, baseIndent);
|
|
1115
|
+
const parOutNode = nodes.find(n => n.type === 'par_out' && n.forNodeId === e.tgt);
|
|
1116
|
+
if (parOutNode) {
|
|
1117
|
+
const exitEdges = adj.get(parOutNode.id) || [];
|
|
1118
|
+
if (exitEdges.length > 0) walk(exitEdges[0].tgt);
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
});
|
|
1122
|
+
|
|
1123
|
+
// 普通出口正常打印 fork
|
|
1124
|
+
if (normalOuts.length > 0) {
|
|
1125
|
+
lines.push(`${pfx}${node.label} -> fork:`);
|
|
1126
|
+
const seenTgt = new Set();
|
|
1127
|
+
normalOuts.forEach((e) => {
|
|
1128
|
+
const tgt = nm.get(e.tgt);
|
|
1129
|
+
if (!tgt || seenTgt.has(tgt.id)) return;
|
|
1130
|
+
seenTgt.add(tgt.id);
|
|
1131
|
+
const cond = e.cond ? ` if (${e.cond}) ->` : '';
|
|
1132
|
+
lines.push(`${pfx} ->${cond} ${tgt.label}`);
|
|
1133
|
+
});
|
|
1134
|
+
normalOuts.forEach((e) => walk(e.tgt));
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
// ═══ 3. 处理 START/IN 直连特殊节点的情况 ═══
|
|
1140
|
+
const startSpecialEntries = specialEntryEdgesMap.get(startNode.id) || [];
|
|
1141
|
+
for (const se of startSpecialEntries) {
|
|
1142
|
+
const tgtNode = nm.get(se.tgt);
|
|
1143
|
+
if (!tgtNode || emittedFors.has(se.tgt)) continue;
|
|
1144
|
+
// ★ 区分 FOR 和 PAR
|
|
1145
|
+
if (tgtNode.specialType === 'PAR') {
|
|
1146
|
+
//console.log('[walk:START] specialEntry→PAR, label:', tgtNode.label, '→ emitParBlock');
|
|
1147
|
+
emitParBlock(se.tgt, baseIndent);
|
|
1148
|
+
} else {
|
|
1149
|
+
//console.log('[walk:START] specialEntry→FOR, label:', tgtNode.label, '→ emitForBlock');
|
|
1150
|
+
emitForBlock(se.tgt, baseIndent);
|
|
1151
|
+
}
|
|
1152
|
+
const exitType = tgtNode.specialType === 'PAR' ? 'par_out' : 'for_out';
|
|
1153
|
+
const forOutNode = nodes.find(n => n.type === exitType && n.forNodeId === se.tgt);
|
|
1154
|
+
if (forOutNode) {
|
|
1155
|
+
const exitEdges = adj.get(forOutNode.id) || [];
|
|
1156
|
+
if (exitEdges.length > 0) walk(exitEdges[0].tgt);
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
const startOuts = (adj.get(startNode.id) || []).filter((e) => {
|
|
1161
|
+
if (back.has(e.id)) return false;
|
|
1162
|
+
const tgtNode = nm.get(e.tgt);
|
|
1163
|
+
if (tgtNode && tgtNode.specialType === 'FOR' && !cycleEdgesMap?.has(e.tgt)) return false;
|
|
1164
|
+
return true;
|
|
1165
|
+
});
|
|
1166
|
+
|
|
1167
|
+
if (startOuts.length === 1) {
|
|
1168
|
+
const tgt = nm.get(startOuts[0].tgt);
|
|
1169
|
+
if (tgt) {
|
|
1170
|
+
if (tgt.specialType === 'FOR' && cycleEdgesMap?.has(tgt.id)) {
|
|
1171
|
+
walk(startOuts[0].tgt);
|
|
1172
|
+
} else {
|
|
1173
|
+
lines.push(`${pfx}${startNode.label} -> ${tgt.label}`);
|
|
1174
|
+
walk(startOuts[0].tgt);
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
} else if (startOuts.length > 1) {
|
|
1178
|
+
lines.push(`${pfx}${startNode.label} -> fork:`);
|
|
1179
|
+
const seenStartTgt = new Set();
|
|
1180
|
+
startOuts.forEach((e) => {
|
|
1181
|
+
const tgt = nm.get(e.tgt);
|
|
1182
|
+
if (!tgt || seenStartTgt.has(tgt.id)) return;
|
|
1183
|
+
seenStartTgt.add(tgt.id);
|
|
1184
|
+
const cond = e.cond ? ` if (${e.cond}) ->` : '';
|
|
1185
|
+
lines.push(`${pfx} ->${cond} ${tgt.label}`);
|
|
1186
|
+
});
|
|
1187
|
+
startOuts.forEach((e) => walk(e.tgt));
|
|
1188
|
+
}
|
|
1189
|
+
} else {
|
|
1190
|
+
const hasIncoming = new Set(edges.map((e) => e.tgt));
|
|
1191
|
+
const starts = nodes.filter((n) => !hasIncoming.has(n.id));
|
|
1192
|
+
lines.push(
|
|
1193
|
+
`${pfx}[START] -> ${starts.map((n) => n.label).join(', ') || '[END]'}`
|
|
1194
|
+
);
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
export { buildFEMO, emitFlowLines, planAutoVars };
|