femo-plugin 1.0.0 → 1.0.2
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/FEMO_logo.svg +55 -0
- package/FEMO_logo_slogan.svg +29 -0
- package/README.md +10 -2
- package/_tmp/fallback/driver2.py +176 -0
- package/_tmp/fallback/events.jsonl +108 -0
- package/_tmp/fallback/gateway_ui.py +325 -0
- package/_tmp/fallback/outbox/j1553_human_[/347/234/213/347/211/214]_1.done +1 -0
- package/_tmp/fallback/outbox/r1.done +1 -0
- package/_tmp/fallback/outbox/r2.done +1 -0
- package/_tmp/fallback/outbox/r3.done +1 -0
- package/_tmp/fallback/outbox/r4.done +1 -0
- package/_tmp/fallback/outbox/r5.done +1 -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 +3 -2
- package/hostAdapter/dshAdapter/client/client-ui/composer.tsx +112 -9
- package/hostAdapter/dshAdapter/client/client-ui/styles.ts +17 -0
- package/hostAdapter/dshAdapter/client/fa-icons.tsx +3 -0
- package/hostAdapter/dshAdapter/host/engine-events.ts +4 -1
- package/hostAdapter/dshAdapter/host/index.ts +5 -0
- package/hostAdapter/dshAdapter/host/preset-install.ts +59 -0
- package/hostAdapter/dshAdapter/host/projection-input.ts +14 -6
- package/hostAdapter/dshAdapter/lib/client.js +124 -5
- package/hostAdapter/dshAdapter/lib/client.js.map +3 -3
- package/hostAdapter/dshAdapter/lib/index.js +58 -18
- package/hostAdapter/dshAdapter/lib/index.js.map +4 -4
- package/hostAdapter/dshAdapter/package.json +1 -5
- package/hostAdapter/dshAdapter/preset/agent.cordis.yml +220 -0
- package/hostAdapter/dshAdapter/preset/preset.yml +3 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/gateway.port +1 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-a-_40_52a9_624b.jsonl +3 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-a-_40_6211.jsonl +10 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-god.jsonl +11 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-stage.jsonl +11 -0
- package/hostAdapter/zcodeAdapter/.zcode-plugin/plugin.json +23 -0
- package/hostAdapter/zcodeAdapter/README.md +61 -0
- package/hostAdapter/zcodeAdapter/commands/femo.md +9 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/.zcode-plugin/plugin.json +23 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/LICENSE +201 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/README.md +635 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/commands/femo.md +9 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/__init__.py +4 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/chronica.py +156 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/femo-chat.mjs +69 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/femo_debugger.py +1515 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femo_api.py +437 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femo_gen_api.jsx +77 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/ContextExample.py +555 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/MemoryExample.py +163 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/__init__.py +1 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/getDir/get_dir.py +56 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/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/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/llmBridge.py +247 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/llmProviders.py +308 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_CLIrenderer.py +198 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_config.py +35 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_errors.py +278 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_interpreter.py +163 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_normalizer.py +396 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_parser.py +2468 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_runtime.py +3630 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_scope_resolver.py +209 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/__init__.py +1 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/actor_resolver.py +86 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/block_collector.py +441 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/db_utils.py +485 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/femoAsync.py +401 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/host_manifest.py +68 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/job_manager.py +767 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/protocol.py +126 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/save_dialog.py +402 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/task_world.py +544 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/__init__.py +19 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/checkpoint.py +113 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/env.py +686 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/evaluator.py +567 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/join.py +303 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/merge.py +157 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/model.py +245 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/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/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +42 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +10 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/LuxFiat/luxfiat.femo +38 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/LuxFiat/wait.py +29 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +222 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/discussion.femo +70 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/goal-mode.femo +23 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//345/270/270/347/224/250/345/267/245/345/205/267python/wait.py +29 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils.py +205 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +324 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/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/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200.femo +331 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +683 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/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/hostAdapter/zcodeAdapter/femo-zcode-dist/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 +393 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/after-tool.mjs +3 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/hooks.json +16 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/lib.mjs +59 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/prompt-state.mjs +3 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/session-start.mjs +3 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/stop-intent.mjs +3 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hostAdapter/dshAdapter/python/dev-bridge-test.py +43 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hostAdapter/dshAdapter/python/femo_bridge.py +533 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/bridge-manager.mjs +192 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/event-router.mjs +258 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/femo-server.mjs +429 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/gateway.mjs +163 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/projection-writer.mjs +294 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/skills/femo/SKILL.md +93 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/bridge-smoke.mjs +26 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/event-router.test.mjs +157 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/gateway-smoke.mjs +107 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/integration-human.mjs +111 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/main-actor.mjs +107 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/mcp-smoke.mjs +130 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/projection-writer.test.mjs +144 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/zcode.host.manifest.json +5 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist//346/212/225/345/275/261/347/252/227/351/207/215/350/256/276/350/256/241-/350/256/250/350/256/272/347/250/277.md +113 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist//350/257/255/346/263/225/346/226/207/346/241/243.md +1136 -0
- package/hostAdapter/zcodeAdapter/hooks/after-tool.mjs +3 -0
- package/hostAdapter/zcodeAdapter/hooks/hooks.json +16 -0
- package/hostAdapter/zcodeAdapter/hooks/lib.mjs +59 -0
- package/hostAdapter/zcodeAdapter/hooks/prompt-state.mjs +3 -0
- package/hostAdapter/zcodeAdapter/hooks/session-start.mjs +3 -0
- package/hostAdapter/zcodeAdapter/hooks/stop-intent.mjs +3 -0
- package/hostAdapter/zcodeAdapter/mcp/bridge-manager.mjs +192 -0
- package/hostAdapter/zcodeAdapter/mcp/event-router.mjs +258 -0
- package/hostAdapter/zcodeAdapter/mcp/femo-server.mjs +429 -0
- package/hostAdapter/zcodeAdapter/mcp/gateway.mjs +163 -0
- package/hostAdapter/zcodeAdapter/mcp/projection-writer.mjs +294 -0
- package/hostAdapter/zcodeAdapter/skills/femo/SKILL.md +93 -0
- package/hostAdapter/zcodeAdapter/tests/bridge-smoke.mjs +26 -0
- package/hostAdapter/zcodeAdapter/tests/event-router.test.mjs +157 -0
- package/hostAdapter/zcodeAdapter/tests/gateway-smoke.mjs +107 -0
- package/hostAdapter/zcodeAdapter/tests/integration-human.mjs +111 -0
- package/hostAdapter/zcodeAdapter/tests/main-actor.mjs +107 -0
- package/hostAdapter/zcodeAdapter/tests/mcp-smoke.mjs +130 -0
- package/hostAdapter/zcodeAdapter/tests/projection-writer.test.mjs +144 -0
- package/hostAdapter/zcodeAdapter/zcode.host.manifest.json +5 -0
- package/hostAdapter/zcodeAdapter//346/212/225/345/275/261/347/252/227/351/207/215/350/256/276/350/256/241-/350/256/250/350/256/272/347/250/277.md +113 -0
- package/package.json +1 -1
- package/scripts/diag-find-redblue.mjs +38 -0
- package/scripts/diag-god-log.mjs +31 -0
- package/scripts/diag-god-log2.mjs +39 -0
- package/scripts/diag-god-log3.mjs +35 -0
- package/scripts/diag-god-log4.mjs +59 -0
- package/scripts/diag-god-log4b.mjs +39 -0
- package/scripts/diag-redblue-god.mjs +39 -0
- package/scripts/diag-redblue-log.mjs +37 -0
- package/scripts/diag-redblue-span.mjs +41 -0
- package/scripts/diag-stage-1017.mjs +63 -0
- package/scripts/dump_session.py +36 -0
- package/scripts/link-workspace.ps1 +51 -0
- package/scripts/list_souls.py +18 -0
- package/scripts/probe-composer-refresh.mjs +197 -0
- package/scripts/seed_story_souls.py +86 -0
- package/scripts/sync-zcode-dist.ps1 +55 -0
- package/scripts/theme-tokenize/color-extract.txt +288 -0
- package/scripts/theme-tokenize/round1-quoted.ps1 +149 -0
- package/scripts/theme-tokenize/round2-bare.ps1 +138 -0
- package/scripts/theme-tokenize/round3-shape.ps1 +110 -0
- package/tests/_diag_r4_join.femo +32 -0
- package/tests/conftest.py +95 -0
- package/tests/diag-subagent-dir-3081.mjs +101 -0
- package/tests/femoGenerator.test.mjs +3909 -0
- package/tests/femoParser.test.mjs +4813 -0
- package/tests/femogen_notice.test.mjs +109 -0
- package/tests/femoparser_validation.test.mjs +84 -0
- package/tests/main-delivery-queue.test.mjs +329 -0
- package/tests/pre-step-gate.test.mjs +282 -0
- package/tests/read-subagent-model.mjs +24 -0
- package/tests/run-script-tests.py +97 -0
- package/tests/safe-steer.test.mjs +59 -0
- package/tests/strip_comments.test.mjs +164 -0
- package/tests/test_actor_failed.py +92 -0
- package/tests/test_compile_warnings.py +99 -0
- package/tests/test_debug_log_bus.py +108 -0
- package/tests/test_debugger_module_mode.py +141 -0
- package/tests/test_error_buckets.py +117 -0
- package/tests/test_error_dispatcher.py +261 -0
- package/tests/test_exec_ai_retry.py +155 -0
- package/tests/test_exec_human_retry.py +159 -0
- package/tests/test_file_resolve.py +104 -0
- package/tests/test_flow_events.py +311 -0
- package/tests/test_flow_ref_validation.py +92 -0
- package/tests/test_func_dict_fallback.py +39 -0
- package/tests/test_job_lifecycle.py +236 -0
- package/tests/test_job_manager.py +424 -0
- package/tests/test_mind.py +99 -0
- package/tests/test_module_call_args.py +258 -0
- package/tests/test_module_visibility.py +238 -0
- package/tests/test_notice.py +143 -0
- package/tests/test_out_whitelist.py +83 -0
- package/tests/test_par_if_dispatch.py +64 -0
- package/tests/test_par_nested_for.py +78 -0
- package/tests/test_parser.py +494 -0
- package/tests/test_pause.py +102 -0
- package/tests/test_pause_contract.py +135 -0
- package/tests/test_protocol_transcript.py +158 -0
- package/tests/test_scope_self.py +202 -0
- package/tests/test_source_validate.py +113 -0
- package/tests/test_task_world.py +447 -0
- package/tests/test_town_structure.py +70 -0
- package/tests/test_v2_checkpoint.py +115 -0
- package/tests/test_v2_env.py +383 -0
- package/tests/test_v2_evaluator.py +227 -0
- package/tests/test_v2_join.py +315 -0
- package/tests/test_v2_join_wiring.py +429 -0
- package/tests/test_v2_merge.py +167 -0
- package/tests/test_v2_model.py +143 -0
- package/tests/test_v2_resume_e2e.py +472 -0
- package/tests/test_var_decls.py +271 -0
- package/tests/verify-model-functions.mjs +90 -0
- package/tests/verify-subagent-model-3081.mjs +153 -0
- package//346/226/275/345/267/245/346/270/205/345/215/225/node-notice-/346/226/275/345/267/245/346/270/205/345/215/225.md +395 -0
- package//346/226/275/345/267/245/346/270/205/345/215/225//344/270/244/344/270/252/345/276/205/350/247/243/345/206/263/347/232/204/351/227/256/351/242/230.MD +66 -0
- package//346/226/275/345/267/245/346/270/205/345/215/225//345/201/234/346/255/242/351/223/276/344/277/256/345/244/215-/346/226/275/345/267/245/346/270/205/345/215/225.md +475 -0
- package//346/226/275/345/267/245/346/270/205/345/215/225//345/217/230/351/207/217/344/270/216task/347/263/273/347/273/237/351/207/215/346/236/204-/346/226/275/345/267/245/346/270/205/345/215/225-v2.md +847 -0
- package//346/226/275/345/267/245/346/270/205/345/215/225//350/277/220/350/241/214/347/212/266/346/200/201/351/223/276/350/267/257/351/207/215/346/236/204-/346/226/275/345/267/245/346/270/205/345/215/225v4.md +654 -0
- package//346/226/275/345/267/245/346/270/205/345/215/225//351/224/231/350/257/257/346/263/250/345/205/245/347/273/255/350/201/212-/346/226/275/345/267/245/346/270/205/345/215/225.md +471 -0
|
@@ -0,0 +1,1515 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
femo_debugger.py — Femo 调试模式(FakeHost 假宿主)
|
|
5
|
+
====================================================
|
|
6
|
+
|
|
7
|
+
零 token 干跑 .femo 剧本:AI / human / mind 节点全部由调试器替答。
|
|
8
|
+
引擎本体一行不改——SET VARIABLE 提取、out 白名单校验、evaluator 解析、
|
|
9
|
+
resolve/@func 调用、变量帧(fork/join/for/par)、模块进出栈、落库,
|
|
10
|
+
全部走引擎真实管线。只有「LLM 思考」和「人类打字」被替换成合成值;
|
|
11
|
+
因此它测的不只是剧本 bug,引擎 bug 也能暴露。
|
|
12
|
+
|
|
13
|
+
原理(FakeHost):
|
|
14
|
+
引擎宿主模式下,AI 节点(_invoke_ai_llm)发 ai_request 事件后
|
|
15
|
+
wait_for_input(wait_key);human 节点(_exec_human)发 human_wait 事件后
|
|
16
|
+
wait_for_input(wait_key)。本模块伪装成宿主:监听事件 → ValueOracle
|
|
17
|
+
合成合法赋值 → engine.human_input.provide_input(wait_key, ...) 秒回。
|
|
18
|
+
femo_bridge.spawn_job_worker 就是这套协议的生产范本。
|
|
19
|
+
|
|
20
|
+
不落库的实现 = DB 沙盒(不是跳过):
|
|
21
|
+
context 收集(get_session_context)、save_dialog、init_database 全链路
|
|
22
|
+
依赖 DB 文件;硬跳过 = patch 一串引擎函数 = 另写一条链路,违背
|
|
23
|
+
「必须走引擎真实链路」的原则。因此把 FEMO_config._db_path 指到沙盒
|
|
24
|
+
目录的一次性库:引擎照常落库(行为与生产一致),生产的 Chronica.wor
|
|
25
|
+
一个字节不碰。沙盒目录只建不删(安全铁律:本文件零删除 API);
|
|
26
|
+
--keep-db 可指定保留位置查看台账,目录会随系统临时目录清理策略走。
|
|
27
|
+
|
|
28
|
+
用法:
|
|
29
|
+
python femo2host/femoToolcall/femo_debugger.py run femoExamples/goblin-mini.femo
|
|
30
|
+
python femo2host/femoToolcall/femo_debugger.py run a.femo --runs 3 --seed 42
|
|
31
|
+
python femo2host/femoToolcall/femo_debugger.py run a.femo --set player_choice=拒绝 --set @hero=@knight
|
|
32
|
+
python femo2host/femoToolcall/femo_debugger.py run a.femo --module BattleRound # 模块单测
|
|
33
|
+
python femo2host/femoToolcall/femo_debugger.py run a.femo --module Outer.Inner # 嵌套模块(点路径)
|
|
34
|
+
python femo2host/femoToolcall/femo_debugger.py run a.femo --assign-prob 0.7 # 概率赋值
|
|
35
|
+
python femo2host/femoToolcall/femo_debugger.py list a.femo / parse a.femo / coverage a.femo
|
|
36
|
+
|
|
37
|
+
模块单测(--module)语义:
|
|
38
|
+
- 合成 wrapper 主流程直接进被测模块(支持嵌套点路径),母链变量与全局
|
|
39
|
+
变量照常可见;模块形参可用 --set 形参名=值 注入(引擎对未传实参的
|
|
40
|
+
形参回退同名可见变量)。
|
|
41
|
+
- 持续循环型模块(无 [OUT]/[BREAK],或循环直到外部中断)跑满 max_steps
|
|
42
|
+
即停:报告标「可能是无限循环」,退出码 0——非错误(2026-09-12 拍板)。
|
|
43
|
+
无出口模块会被静态识别并在报告中注明。
|
|
44
|
+
|
|
45
|
+
实时调试日志(DebugLogBus,消费方接口):
|
|
46
|
+
跑动过程中每个节点的进出、每笔变量赋值(old→new)、每次合成发言的
|
|
47
|
+
var→值→来源,都以结构化记录实时发出。两种消费方式:
|
|
48
|
+
|
|
49
|
+
# ① 程序内订阅(测试代码 / 宿主 bridge / 任何 Python 消费方)
|
|
50
|
+
from femo_debugger import DebugLogBus, load_script, run_once
|
|
51
|
+
bus = DebugLogBus()
|
|
52
|
+
bus.subscribe(lambda rec: print(rec['kind'], rec)) # 实时回调,按序送达
|
|
53
|
+
result = run_once(load_script('a.femo'), seed=42, overrides={},
|
|
54
|
+
assign_prob=1.0, max_steps=200, quiet=True, bus=bus)
|
|
55
|
+
bus.snapshot() # 环形缓冲,事后取全部记录
|
|
56
|
+
|
|
57
|
+
# ② CLI 落盘(每条记录 flush,可 tail -f,也可由前端 SSE 转发)
|
|
58
|
+
python femo_debugger.py run a.femo --log-jsonl debug.jsonl
|
|
59
|
+
python femo_debugger.py run a.femo --log-jsonl d.jsonl --log-kinds assign,node_start
|
|
60
|
+
python femo_debugger.py run a.femo --log-console # 紧凑实时控制台流水
|
|
61
|
+
|
|
62
|
+
记录 schema:{seq, ts, run, seed, kind, ...kind 专属字段};
|
|
63
|
+
kind 全集与各字段见 DebugLogBus 类 docstring。
|
|
64
|
+
|
|
65
|
+
代码原则(项目铁律):不许 try 静默吞错。对引擎内部状态的读取做显式
|
|
66
|
+
getattr 防御但失败必须响亮报告;FakeHost / 日志订阅者回调异常打印
|
|
67
|
+
traceback(回调炸不能带崩引擎,但绝不静默)。
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
import argparse
|
|
71
|
+
import io
|
|
72
|
+
import json
|
|
73
|
+
import os
|
|
74
|
+
import random
|
|
75
|
+
import re
|
|
76
|
+
import sys
|
|
77
|
+
import threading
|
|
78
|
+
import time
|
|
79
|
+
import traceback
|
|
80
|
+
from collections import deque
|
|
81
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
82
|
+
|
|
83
|
+
# Windows GBK 控制台兼容(引擎 print 含 emoji/中文符号)——只在 CLI 入口做,
|
|
84
|
+
# 不在 import 时做:模块可能被测试/宿主进程导入,import 副作用会污染
|
|
85
|
+
# 调用方的 stdout(实测弄崩 pytest capture)。
|
|
86
|
+
def _force_utf8_stdio():
|
|
87
|
+
for stream_attr in ('stdout', 'stderr'):
|
|
88
|
+
s = getattr(sys, stream_attr, None)
|
|
89
|
+
if s and hasattr(s, 'buffer'):
|
|
90
|
+
try:
|
|
91
|
+
setattr(sys, stream_attr, io.TextIOWrapper(
|
|
92
|
+
s.buffer, encoding='utf-8', errors='replace',
|
|
93
|
+
line_buffering=True))
|
|
94
|
+
except Exception:
|
|
95
|
+
pass
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# ── 引擎导入路径:本脚本在 femo2host/femoToolcall/ 下,插件根是其祖父目录 ──
|
|
99
|
+
# 本脚本在 femo2host/femoToolcall/ 下,插件根需上溯三层(2026-09-13 迁入 femo2host/)
|
|
100
|
+
_HERE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
101
|
+
if _HERE not in sys.path:
|
|
102
|
+
sys.path.insert(0, _HERE)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# ════════════════════════════════════════════════════════════
|
|
106
|
+
# 实时调试日志总线(DebugLogBus)
|
|
107
|
+
# ════════════════════════════════════════════════════════════
|
|
108
|
+
|
|
109
|
+
class DebugLogBus:
|
|
110
|
+
"""调试日志总线:跑动过程中的节点 / 变量 / 值实时结构化流水。
|
|
111
|
+
|
|
112
|
+
采集点(全部在调试器侧,引擎零改动)与 kind 专属字段:
|
|
113
|
+
run_start {script, overrides}
|
|
114
|
+
node_start {node, node_type} —— 引擎 node_start 事件
|
|
115
|
+
edge {src, tgt} —— 引擎 _follow_next_edge
|
|
116
|
+
assign {node, var, old, new} —— VarFacade.apply_intent(引擎真实落值)
|
|
117
|
+
action_outs {node, node_type, exprs} —— @assign 赋值表达式 / @func 写回目标
|
|
118
|
+
func_result {node, func_input, output} —— @func 调用入参与结果(引擎事件)
|
|
119
|
+
ai_reply {node, values} —— FakeHost 合成 AI 赋值(var→{value,source})
|
|
120
|
+
human_input {node, variables} —— FakeHost 合成人类输入
|
|
121
|
+
retry {node, target, line, feedback}
|
|
122
|
+
silence {node, var} —— --assign-prob 概率沉默
|
|
123
|
+
flaky {node, var} —— --flaky 无效赋值
|
|
124
|
+
warning {msg} —— ValueOracle 猜值降级/兜底
|
|
125
|
+
flow_outcome {outcome, error}
|
|
126
|
+
run_end {outcome, elapsed}
|
|
127
|
+
|
|
128
|
+
公共字段:{seq, ts, run, seed}——run/seed 由 run_once 经 set_context
|
|
129
|
+
注入,多轮共用一条总线时靠它区分轮次。
|
|
130
|
+
|
|
131
|
+
消费方接口:
|
|
132
|
+
bus = DebugLogBus()
|
|
133
|
+
sub = bus.subscribe(fn) # 实时回调(同步、按 seq 序)
|
|
134
|
+
bus.unsubscribe(sub)
|
|
135
|
+
bus.snapshot() # 环形缓冲最近 history 条(默认 500)
|
|
136
|
+
|
|
137
|
+
铁律:订阅者回调异常打印 traceback 并拦截(回调炸不能带崩引擎,
|
|
138
|
+
但绝不静默);其余订阅者不受影响。
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
def __init__(self, history: int = 500):
|
|
142
|
+
self._lock = threading.Lock()
|
|
143
|
+
self._seq = 0
|
|
144
|
+
self._buf: deque = deque(maxlen=history)
|
|
145
|
+
self._subs: Dict[int, Any] = {}
|
|
146
|
+
self._sub_seq = 0
|
|
147
|
+
self._ctx: Dict[str, Any] = {}
|
|
148
|
+
|
|
149
|
+
def set_context(self, **ctx):
|
|
150
|
+
"""给后续记录附加运行上下文(run/seed 等)。"""
|
|
151
|
+
self._ctx.update(ctx)
|
|
152
|
+
|
|
153
|
+
def emit(self, kind: str, **fields) -> dict:
|
|
154
|
+
with self._lock:
|
|
155
|
+
self._seq += 1
|
|
156
|
+
rec = {'seq': self._seq, 'ts': round(time.time(), 3),
|
|
157
|
+
**self._ctx, 'kind': kind, **fields}
|
|
158
|
+
self._buf.append(rec)
|
|
159
|
+
subs = list(self._subs.values())
|
|
160
|
+
for fn in subs:
|
|
161
|
+
try:
|
|
162
|
+
fn(rec)
|
|
163
|
+
except Exception:
|
|
164
|
+
traceback.print_exc()
|
|
165
|
+
print(f"[debug] ⚠️ 日志订阅者异常(kind={kind}),已拦截继续",
|
|
166
|
+
file=sys.stderr)
|
|
167
|
+
return rec
|
|
168
|
+
|
|
169
|
+
def subscribe(self, fn) -> int:
|
|
170
|
+
with self._lock:
|
|
171
|
+
self._sub_seq += 1
|
|
172
|
+
self._subs[self._sub_seq] = fn
|
|
173
|
+
return self._sub_seq
|
|
174
|
+
|
|
175
|
+
def unsubscribe(self, sub_id: int):
|
|
176
|
+
with self._lock:
|
|
177
|
+
self._subs.pop(sub_id, None)
|
|
178
|
+
|
|
179
|
+
def snapshot(self) -> List[dict]:
|
|
180
|
+
return list(self._buf)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class JsonlLogSubscriber:
|
|
184
|
+
"""总线记录实时写 JSONL(每条 flush,可 tail -f / 供宿主 SSE 转发)。"""
|
|
185
|
+
|
|
186
|
+
def __init__(self, bus: DebugLogBus, path: str, kinds=None):
|
|
187
|
+
self._f = open(path, 'w', encoding='utf-8')
|
|
188
|
+
self._kinds = set(kinds) if kinds else None
|
|
189
|
+
self._sub = bus.subscribe(self)
|
|
190
|
+
|
|
191
|
+
def __call__(self, rec: dict):
|
|
192
|
+
if self._kinds and rec.get('kind') not in self._kinds:
|
|
193
|
+
return
|
|
194
|
+
self._f.write(json.dumps(rec, ensure_ascii=False, default=str) + '\n')
|
|
195
|
+
self._f.flush()
|
|
196
|
+
|
|
197
|
+
def close(self):
|
|
198
|
+
self._f.close()
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class ConsoleLogSubscriber:
|
|
202
|
+
"""总线记录的紧凑实时控制台渲染(不受 --quiet 影响——显式开启即想看)。"""
|
|
203
|
+
|
|
204
|
+
def __init__(self, bus: DebugLogBus, kinds=None):
|
|
205
|
+
self._kinds = set(kinds) if kinds else None
|
|
206
|
+
self._sub = bus.subscribe(self)
|
|
207
|
+
|
|
208
|
+
def __call__(self, rec: dict):
|
|
209
|
+
if self._kinds and rec.get('kind') not in self._kinds:
|
|
210
|
+
return
|
|
211
|
+
head = f"[log #{rec.get('run', '?')}] {rec['kind']}"
|
|
212
|
+
if rec.get('node'):
|
|
213
|
+
head += f" @ {rec['node']}"
|
|
214
|
+
body = {k: v for k, v in rec.items()
|
|
215
|
+
if k not in ('seq', 'ts', 'run', 'seed', 'kind', 'node')}
|
|
216
|
+
print(f"{head} {body if body else ''}")
|
|
217
|
+
|
|
218
|
+
def close(self):
|
|
219
|
+
pass
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
# ════════════════════════════════════════════════════════════
|
|
223
|
+
# DB 沙盒
|
|
224
|
+
# ════════════════════════════════════════════════════════════
|
|
225
|
+
|
|
226
|
+
class DBSandbox:
|
|
227
|
+
"""把 FEMO_config._db_path 指到沙盒库;退出时恢复原路径(不删任何文件)。
|
|
228
|
+
|
|
229
|
+
沙盒目录固定复用 cache/debug-sandbox/(相对插件根),每轮 run 用
|
|
230
|
+
独立库文件名(run-<时间戳>.wor)。旧沙库滚动保留最近 3 天,超期自动
|
|
231
|
+
清理(2026-09-12 由「只建不删」改制——只增不减的沙盒会无限长胖)。
|
|
232
|
+
"""
|
|
233
|
+
|
|
234
|
+
@staticmethod
|
|
235
|
+
def _sweep_old(sandbox_dir: str, keep_days: int = 3) -> int:
|
|
236
|
+
"""删除沙盒里 mtime 超过 keep_days 的旧文件,返回删除数。"""
|
|
237
|
+
cutoff = time.time() - keep_days * 86400
|
|
238
|
+
removed = 0
|
|
239
|
+
try:
|
|
240
|
+
for name in os.listdir(sandbox_dir):
|
|
241
|
+
fp = os.path.join(sandbox_dir, name)
|
|
242
|
+
try:
|
|
243
|
+
if os.path.isfile(fp) and os.path.getmtime(fp) < cutoff:
|
|
244
|
+
os.remove(fp)
|
|
245
|
+
removed += 1
|
|
246
|
+
except OSError:
|
|
247
|
+
pass
|
|
248
|
+
except OSError:
|
|
249
|
+
pass
|
|
250
|
+
return removed
|
|
251
|
+
|
|
252
|
+
def __init__(self, verbose: bool = True, label: str = 'run'):
|
|
253
|
+
self.verbose = verbose
|
|
254
|
+
self.label = label
|
|
255
|
+
self.db_path: Optional[str] = None
|
|
256
|
+
self._saved: Optional[str] = None
|
|
257
|
+
self._sandbox_dir = os.path.join(_HERE, 'cache', 'debug-sandbox')
|
|
258
|
+
|
|
259
|
+
def path(self) -> str:
|
|
260
|
+
return os.path.join(
|
|
261
|
+
self._sandbox_dir, f'{self.label}-{int(time.time() * 1000)}.wor')
|
|
262
|
+
|
|
263
|
+
def __enter__(self):
|
|
264
|
+
from femoCompiler import FEMO_config
|
|
265
|
+
self._saved = FEMO_config.get_db_path()
|
|
266
|
+
os.makedirs(self._sandbox_dir, exist_ok=True)
|
|
267
|
+
swept = self._sweep_old(self._sandbox_dir)
|
|
268
|
+
if self.verbose and swept:
|
|
269
|
+
print(f"[debug] 🧹 沙盒清理: 移除 {swept} 个超过 3 天的旧文件")
|
|
270
|
+
self.db_path = self.path()
|
|
271
|
+
FEMO_config.set_db_path(self.db_path)
|
|
272
|
+
if self.verbose:
|
|
273
|
+
print(f"[debug] 🔬 DB 沙盒: {self.db_path}")
|
|
274
|
+
return self
|
|
275
|
+
|
|
276
|
+
def __exit__(self, exc_type, exc, tb):
|
|
277
|
+
from femoCompiler import FEMO_config
|
|
278
|
+
if self._saved is not None:
|
|
279
|
+
FEMO_config.set_db_path(self._saved)
|
|
280
|
+
if self.verbose and self.db_path:
|
|
281
|
+
print(f"[debug] 📦 沙盒库保留在: {self._sandbox_dir}(可随时手动删除整个目录)")
|
|
282
|
+
return False
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
# ════════════════════════════════════════════════════════════
|
|
286
|
+
# 值合成:ValueOracle
|
|
287
|
+
# ═══════════════════════════════════════^^^^═════════════════
|
|
288
|
+
|
|
289
|
+
class ValueOracle:
|
|
290
|
+
"""为 out 变量按六层优先级合成值;随机全部经 rng(同种子可复现)。
|
|
291
|
+
|
|
292
|
+
L1 --set 用户覆盖(v1|v2 序列轮换)
|
|
293
|
+
L2 ASSIGN 型 out("refuse_count += 1")→ 语义已含在 out 文本,渲染层处理
|
|
294
|
+
L3 dropdown choices(引擎 evaluator 求值后 rng 挑选)
|
|
295
|
+
L4 prompt 线索(<<VAR = 示例>> 模板;@占位 → actor 名单挑真实演员)
|
|
296
|
+
L5 vars 声明初值类型反推(bool 翻转 / 数字保持 / @actor 挑人)
|
|
297
|
+
L6 兜底 "debug"(响亮记 warning)
|
|
298
|
+
"""
|
|
299
|
+
|
|
300
|
+
def __init__(self, runner, rng: random.Random,
|
|
301
|
+
overrides: Dict[str, List[str]]):
|
|
302
|
+
self.runner = runner # None 占位,run_once 里回填
|
|
303
|
+
self.rng = rng
|
|
304
|
+
self.overrides = overrides
|
|
305
|
+
self.seq_idx: Dict[str, int] = {}
|
|
306
|
+
self.guess_warnings: List[str] = []
|
|
307
|
+
self.bus: Optional[DebugLogBus] = None # run_once 里回填
|
|
308
|
+
|
|
309
|
+
def _warn(self, msg: str):
|
|
310
|
+
"""猜值降级/兜底告警:进终报 warnings,同时实时上总线。"""
|
|
311
|
+
self.guess_warnings.append(msg)
|
|
312
|
+
if self.bus is not None:
|
|
313
|
+
self.bus.emit('warning', msg=msg)
|
|
314
|
+
|
|
315
|
+
# ── out 声明遍历入口 ──
|
|
316
|
+
def resolve_action_outs(self, ad, prompt_rendered: str,
|
|
317
|
+
facade) -> List[Tuple[Any, str]]:
|
|
318
|
+
"""返回 [(value, source)],顺序与 ad.outs(过滤伪 out 后)一致。
|
|
319
|
+
ASSIGN 型 value=None 占位(语义在 out 文本里,由 render 处理)。"""
|
|
320
|
+
results = []
|
|
321
|
+
for od in (ad.outs or []):
|
|
322
|
+
if _is_field_noise(od):
|
|
323
|
+
continue
|
|
324
|
+
if _is_assign_out(od):
|
|
325
|
+
results.append((None, 'assign-op'))
|
|
326
|
+
continue
|
|
327
|
+
results.append(self._resolve_value(od, prompt_rendered, facade))
|
|
328
|
+
return results
|
|
329
|
+
|
|
330
|
+
def _resolve_value(self, od, prompt_rendered: str,
|
|
331
|
+
facade) -> Tuple[Any, str]:
|
|
332
|
+
var_name = od.var_name
|
|
333
|
+
|
|
334
|
+
# L1 用户覆盖
|
|
335
|
+
if var_name in self.overrides:
|
|
336
|
+
seq = self.overrides[var_name]
|
|
337
|
+
i = min(self.seq_idx.get(var_name, 0), len(seq) - 1)
|
|
338
|
+
raw = seq[i]
|
|
339
|
+
self.seq_idx[var_name] = i + 1
|
|
340
|
+
return _coerce(raw), 'set-override'
|
|
341
|
+
|
|
342
|
+
# L3 choices
|
|
343
|
+
if getattr(od, 'choices', None):
|
|
344
|
+
try:
|
|
345
|
+
expr = od.choices.strip()
|
|
346
|
+
if expr.startswith('{') and expr.endswith('}'):
|
|
347
|
+
expr = expr[1:-1].strip()
|
|
348
|
+
val = self.runner.evaluator.evaluate(expr, facade, strict=False)
|
|
349
|
+
if isinstance(val, (list, tuple)) and val:
|
|
350
|
+
return _coerce(self.rng.choice(list(val))), 'choices'
|
|
351
|
+
return _coerce(val), 'choices'
|
|
352
|
+
except Exception as e:
|
|
353
|
+
self._warn(
|
|
354
|
+
f"choices 求值失败({var_name}: {od.choices!r}: {e}),降级下层")
|
|
355
|
+
|
|
356
|
+
# L4 prompt 线索
|
|
357
|
+
clue = _prompt_clue(prompt_rendered, var_name)
|
|
358
|
+
if clue is not None:
|
|
359
|
+
op, text = clue
|
|
360
|
+
hit = _clue_to_value(op, text, self._pick_actor, facade,
|
|
361
|
+
self._warn)
|
|
362
|
+
if hit is not None:
|
|
363
|
+
return hit
|
|
364
|
+
|
|
365
|
+
# L5 声明初值类型
|
|
366
|
+
init = self._declared_initial(var_name, facade)
|
|
367
|
+
if init is not None:
|
|
368
|
+
hit = _from_initial(init, self._pick_actor)
|
|
369
|
+
if hit is not None:
|
|
370
|
+
return hit
|
|
371
|
+
|
|
372
|
+
# L6 兜底
|
|
373
|
+
self._warn(
|
|
374
|
+
f"变量 '{var_name}' 无值线索(无 --set/choices/prompt 模板/初值),"
|
|
375
|
+
f"用兜底值 \"debug\"——分支走向可能不反映真实行为")
|
|
376
|
+
return "debug", 'fallback'
|
|
377
|
+
|
|
378
|
+
# ── 存活名单快照(合成票只投活人)──
|
|
379
|
+
_ALIVE_KEY_RE = re.compile(r'alive|存活|players|roster', re.IGNORECASE)
|
|
380
|
+
|
|
381
|
+
def _alive_snapshot(self, facade) -> set:
|
|
382
|
+
"""从变量世界里找「存活玩家列表」变量的快照(找不到返回空集)。
|
|
383
|
+
|
|
384
|
+
识别口径:变量名含 alive/存活/players/roster(如 $alive、存活名单),
|
|
385
|
+
值里至少有一个 '@名'。多命中时取最长的那个(最可能是真正的存活表)。
|
|
386
|
+
"""
|
|
387
|
+
best: List[str] = []
|
|
388
|
+
try:
|
|
389
|
+
view = facade.visible_view() if hasattr(facade, 'visible_view') else {}
|
|
390
|
+
for name, v in (view or {}).items():
|
|
391
|
+
if not self._ALIVE_KEY_RE.search(str(name)):
|
|
392
|
+
continue
|
|
393
|
+
if isinstance(v, dict):
|
|
394
|
+
items = list(v.keys())
|
|
395
|
+
elif isinstance(v, (list, tuple, set)):
|
|
396
|
+
items = list(v)
|
|
397
|
+
else:
|
|
398
|
+
continue
|
|
399
|
+
names = [x for x in items if isinstance(x, str) and x.startswith('@')]
|
|
400
|
+
if len(names) > len(best):
|
|
401
|
+
best = names
|
|
402
|
+
except Exception as e:
|
|
403
|
+
self._warn(f"读取存活名单失败: {e}")
|
|
404
|
+
return set(best)
|
|
405
|
+
|
|
406
|
+
# ── actor 挑选(@占位 → 真实演员)──
|
|
407
|
+
def _pick_actor(self, placeholder: str, facade) -> Optional[str]:
|
|
408
|
+
candidates: List[str] = []
|
|
409
|
+
try:
|
|
410
|
+
for aname in (self.runner.script.actors or {}):
|
|
411
|
+
candidates.append(aname if aname.startswith('@') else f'@{aname}')
|
|
412
|
+
except Exception as e:
|
|
413
|
+
self._warn(f"读取 actors 定义失败: {e}")
|
|
414
|
+
try:
|
|
415
|
+
view = facade.visible_view() if hasattr(facade, 'visible_view') else {}
|
|
416
|
+
for _n, v in (view or {}).items():
|
|
417
|
+
if isinstance(v, list):
|
|
418
|
+
candidates.extend(
|
|
419
|
+
x for x in v if isinstance(x, str) and x.startswith('@'))
|
|
420
|
+
elif isinstance(v, dict):
|
|
421
|
+
candidates.extend(
|
|
422
|
+
k for k in v.keys() if isinstance(k, str) and k.startswith('@'))
|
|
423
|
+
except Exception as e:
|
|
424
|
+
self._warn(f"读取变量世界 actor 名单失败: {e}")
|
|
425
|
+
# 存活名单优先(2026-09-12):剧本里若有「存活玩家列表」变量($alive/存活名单
|
|
426
|
+
# /players 等),合成票只从**存活者**里挑——否则会投给已淘汰的人(干跑实测:
|
|
427
|
+
# 某 3 人出局的局,第 4 轮合成票还在投第 2 轮就出局的人),票一散就永远平票、
|
|
428
|
+
# 每轮进 PK,死循环跑不完(谁是卧底 8 人局干跑 180s 超时就是这么来的)。
|
|
429
|
+
alive = self._alive_snapshot(facade)
|
|
430
|
+
if alive:
|
|
431
|
+
filtered = [c for c in candidates if c in alive]
|
|
432
|
+
if filtered:
|
|
433
|
+
candidates = filtered
|
|
434
|
+
seen, uniq = set(), []
|
|
435
|
+
for c in candidates:
|
|
436
|
+
if c not in seen:
|
|
437
|
+
seen.add(c)
|
|
438
|
+
uniq.append(c)
|
|
439
|
+
if not uniq:
|
|
440
|
+
return None
|
|
441
|
+
if placeholder in uniq:
|
|
442
|
+
return placeholder
|
|
443
|
+
return self.rng.choice(uniq)
|
|
444
|
+
|
|
445
|
+
# ── L5 声明初值查询 ──
|
|
446
|
+
def _declared_initial(self, var_name: str, facade) -> Optional[Any]:
|
|
447
|
+
try:
|
|
448
|
+
table = self.runner.world.table
|
|
449
|
+
# def_chain 是 property(返回 tuple,不能加括号调用)
|
|
450
|
+
decl = table.lookup(var_name, facade.def_chain)
|
|
451
|
+
if decl is not None:
|
|
452
|
+
return decl.initial
|
|
453
|
+
except Exception as e:
|
|
454
|
+
self._warn(f"查声明初值失败({var_name}): {e}")
|
|
455
|
+
return None
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
# ── 模块级纯函数(供 FakeHost 复用)──────────────────────────
|
|
459
|
+
|
|
460
|
+
_ASSIGN_OUT_RE = re.compile(r'^[@$\w\u4e00-\u9fff\[\]]+\s*[+\-]?=')
|
|
461
|
+
|
|
462
|
+
# 引擎 parser 的 out: 续行收集会误吞同缩进二级字段(_FIELD_KEYWORDS 缺
|
|
463
|
+
# max_retries: 等,2026-09-08 调试器实测发现)——伪 out 的 var_name 形如
|
|
464
|
+
# 'max_retries: 2'。调试器侧过滤(引擎修复后无副作用)。
|
|
465
|
+
_ENGINE_FIELD_NOISE = re.compile(
|
|
466
|
+
r'^(max_retries|max_tries|timeout|fallback|resolve|memory|context|'
|
|
467
|
+
r'scope|prompt|showprompt|interrupt)\s*:')
|
|
468
|
+
|
|
469
|
+
def _is_assign_out(od) -> bool:
|
|
470
|
+
return bool(_ASSIGN_OUT_RE.match(od.var_name or ''))
|
|
471
|
+
|
|
472
|
+
def _is_field_noise(od) -> bool:
|
|
473
|
+
"""伪 out 识别:引擎 out 解析误吞的二级字段行。"""
|
|
474
|
+
return bool(_ENGINE_FIELD_NOISE.match(od.var_name or ''))
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _coerce(raw: Any) -> Any:
|
|
478
|
+
s = str(raw).strip()
|
|
479
|
+
if s.lower() == 'true':
|
|
480
|
+
return True
|
|
481
|
+
if s.lower() == 'false':
|
|
482
|
+
return False
|
|
483
|
+
if re.match(r'^-?\d+$', s):
|
|
484
|
+
return int(s)
|
|
485
|
+
if re.match(r'^-?\d+\.\d+$', s):
|
|
486
|
+
return float(s)
|
|
487
|
+
# dict / list 字面量(--set damage_report={"@knight": 25})
|
|
488
|
+
if s.startswith(('{', '[')):
|
|
489
|
+
import ast
|
|
490
|
+
try:
|
|
491
|
+
return ast.literal_eval(s)
|
|
492
|
+
except (ValueError, SyntaxError):
|
|
493
|
+
return s
|
|
494
|
+
return s
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
_CLUE_RE = re.compile(
|
|
498
|
+
r'(?:<<|《|〈|《《)\s*([@$\w\u4e00-\u9fff\[\]]+)\s*'
|
|
499
|
+
r'([+\-]?=)\s*(.+?)\s*(?:>>|》|〉|》》)')
|
|
500
|
+
|
|
501
|
+
def _prompt_clue(prompt: str, var_name: str) -> Optional[Tuple[str, str]]:
|
|
502
|
+
for m in _CLUE_RE.finditer(prompt or ''):
|
|
503
|
+
if m.group(1) == var_name:
|
|
504
|
+
return m.group(2), m.group(3)
|
|
505
|
+
return None
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _clue_to_value(op, text, pick_actor, facade,
|
|
509
|
+
warn) -> Optional[Tuple[Any, str]]:
|
|
510
|
+
text = text.strip()
|
|
511
|
+
if text.startswith('@'):
|
|
512
|
+
actor = pick_actor(text, facade)
|
|
513
|
+
if actor is not None:
|
|
514
|
+
return actor, 'prompt-clue'
|
|
515
|
+
warn(f"prompt 线索 {text!r} 找不到可用 actor,降级下层")
|
|
516
|
+
return None
|
|
517
|
+
if text.lower() in ('true', 'false'):
|
|
518
|
+
return (text.lower() == 'true'), 'prompt-clue'
|
|
519
|
+
if re.match(r'^-?\d+$', text):
|
|
520
|
+
return int(text), 'prompt-clue'
|
|
521
|
+
if re.match(r'^-?\d+\.\d+$', text):
|
|
522
|
+
return float(text), 'prompt-clue'
|
|
523
|
+
if len(text) >= 2 and text[0] == text[-1] and text[0] in ('"', "'", '“', '”'):
|
|
524
|
+
return text[1:-1], 'prompt-clue'
|
|
525
|
+
if text.startswith(('add(', 'remove(')):
|
|
526
|
+
return None
|
|
527
|
+
if re.match(r'^[\w\u4e00-\u9fff]+$', text):
|
|
528
|
+
return text, 'prompt-clue'
|
|
529
|
+
return None
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _from_initial(init: Any, pick_actor) -> Optional[Tuple[Any, str]]:
|
|
533
|
+
if isinstance(init, bool):
|
|
534
|
+
return (not init), 'declared-type' # 翻转,让流程有机会离开默认分支
|
|
535
|
+
if isinstance(init, (int, float)):
|
|
536
|
+
return init, 'declared-type'
|
|
537
|
+
if isinstance(init, str):
|
|
538
|
+
if init.startswith('@'):
|
|
539
|
+
actor = pick_actor(init, None)
|
|
540
|
+
if actor is not None:
|
|
541
|
+
return actor, 'declared-type'
|
|
542
|
+
if init:
|
|
543
|
+
return init, 'declared-type'
|
|
544
|
+
return None
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
# ════════════════════════════════════════════════════════════
|
|
548
|
+
# 覆盖率追踪
|
|
549
|
+
# ════════════════════════════════════════════════════════════
|
|
550
|
+
|
|
551
|
+
class CoverageTracker:
|
|
552
|
+
def __init__(self, bus: Optional[DebugLogBus] = None):
|
|
553
|
+
self.node_visits: Dict[str, int] = {}
|
|
554
|
+
self.node_order: List[str] = []
|
|
555
|
+
self.edges_taken: set = set()
|
|
556
|
+
self.var_snapshots: List[dict] = []
|
|
557
|
+
self.bus = bus # 实时日志总线(可选)
|
|
558
|
+
|
|
559
|
+
def _emit(self, kind: str, **fields):
|
|
560
|
+
if self.bus is not None:
|
|
561
|
+
self.bus.emit(kind, **fields)
|
|
562
|
+
|
|
563
|
+
def on_node(self, node_id: str, node_type: str):
|
|
564
|
+
self.node_visits[node_id] = self.node_visits.get(node_id, 0) + 1
|
|
565
|
+
tag = {'human': 'h', 'ai': 'a', 'mind': 'm'}.get(node_type, node_type[:1] if node_type else '?')
|
|
566
|
+
self.node_order.append(f"{node_id}({tag})")
|
|
567
|
+
self._emit('node_start', node=node_id, node_type=node_type)
|
|
568
|
+
|
|
569
|
+
def on_edge(self, src: str, tgt: str):
|
|
570
|
+
self.edges_taken.add(f"{src}->{tgt}")
|
|
571
|
+
self._emit('edge', src=src, tgt=tgt)
|
|
572
|
+
|
|
573
|
+
def on_assignment(self, node: str, var: str, old, new):
|
|
574
|
+
self.var_snapshots.append(
|
|
575
|
+
{'node': node, 'var': var, 'old': _safe_repr(old), 'new': _safe_repr(new)})
|
|
576
|
+
self._emit('assign', node=node, var=var,
|
|
577
|
+
old=_safe_repr(old), new=_safe_repr(new))
|
|
578
|
+
|
|
579
|
+
def cross_run_merge(self, other: 'CoverageTracker'):
|
|
580
|
+
for k, v in other.node_visits.items():
|
|
581
|
+
self.node_visits[k] = self.node_visits.get(k, 0) + v
|
|
582
|
+
self.edges_taken |= other.edges_taken
|
|
583
|
+
self.var_snapshots.extend(other.var_snapshots)
|
|
584
|
+
self.node_order.extend(other.node_order)
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def _safe_repr(v) -> str:
|
|
588
|
+
try:
|
|
589
|
+
r = repr(v)
|
|
590
|
+
return r if len(r) <= 120 else r[:117] + '...'
|
|
591
|
+
except Exception:
|
|
592
|
+
return '<unrepr>'
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
# ═══════════════交付物═══════════════════════════════════════
|
|
596
|
+
# FakeHost:替 AI / human 发言
|
|
597
|
+
# ════════════════════════════════════════════════════════════
|
|
598
|
+
|
|
599
|
+
class FakeHost:
|
|
600
|
+
"""监听引擎事件,替 AI / human 节点提供合成输入。
|
|
601
|
+
|
|
602
|
+
事件契约(与 FEMO_runtime._emit_event / FEMO_errors 源码一致):
|
|
603
|
+
ai_request {wait_key, node_name, ai_name, blocks, actor_info, source,...}
|
|
604
|
+
human_wait {wait_key, node_name, prompt, scope, out_vars, ...}
|
|
605
|
+
node_retry {node_name, wait_key, ai_name, feedback, attempt, target}
|
|
606
|
+
node_start {node_name, node_type, prompt?, scope}
|
|
607
|
+
回传:runner.engine.human_input.provide_input(wait_key, payload)
|
|
608
|
+
"""
|
|
609
|
+
|
|
610
|
+
def __init__(self, runner, oracle: ValueOracle, tracker: CoverageTracker,
|
|
611
|
+
assign_prob: float, quiet: bool, rng: random.Random,
|
|
612
|
+
flaky: float = 0.0, bus: Optional[DebugLogBus] = None):
|
|
613
|
+
self.runner = runner # None 占位,run_once 回填
|
|
614
|
+
self.oracle = oracle
|
|
615
|
+
self.tracker = tracker
|
|
616
|
+
self.assign_prob = assign_prob
|
|
617
|
+
self.flaky = flaky # 概率输出无效赋值(测重试/fallback)
|
|
618
|
+
self.quiet = quiet
|
|
619
|
+
self.rng = rng # 概率赋值独立 rng
|
|
620
|
+
self.bus = bus # 实时日志总线(可选)
|
|
621
|
+
self._node_prompt: Dict[str, str] = {} # node → 渲染后 prompt
|
|
622
|
+
self._retry_values: Dict[str, dict] = {} # wait_key → {values, idx}
|
|
623
|
+
self.silences: List[str] = []
|
|
624
|
+
self.flaky_fired: List[str] = []
|
|
625
|
+
|
|
626
|
+
def log(self, msg: str):
|
|
627
|
+
if not self.quiet:
|
|
628
|
+
print(f"[fakehost] {msg}")
|
|
629
|
+
|
|
630
|
+
def _emit(self, kind: str, **fields):
|
|
631
|
+
if self.bus is not None:
|
|
632
|
+
self.bus.emit(kind, **fields)
|
|
633
|
+
|
|
634
|
+
# ── 事件分发 ──
|
|
635
|
+
def on_event(self, event_type: str, data: dict):
|
|
636
|
+
handler = getattr(self, f'_on_{event_type}', None)
|
|
637
|
+
if handler is None:
|
|
638
|
+
return
|
|
639
|
+
try:
|
|
640
|
+
handler(data or {})
|
|
641
|
+
except Exception:
|
|
642
|
+
# 回调炸不能带崩引擎;但绝不静默(项目铁律)
|
|
643
|
+
traceback.print_exc()
|
|
644
|
+
print(f"[fakehost] ⚠️ 事件处理异常({event_type}),已拦截继续",
|
|
645
|
+
file=sys.stderr)
|
|
646
|
+
|
|
647
|
+
# ── node_start:记 prompt(ai 节点带渲染后的 prompt 字段)──
|
|
648
|
+
def _on_node_start(self, data: dict):
|
|
649
|
+
node = data.get('node_name') or ''
|
|
650
|
+
if not node:
|
|
651
|
+
return
|
|
652
|
+
ntype = data.get('node_type') or ''
|
|
653
|
+
self.tracker.on_node(node, ntype)
|
|
654
|
+
if data.get('prompt') is not None:
|
|
655
|
+
self._node_prompt[node] = data.get('prompt') or ''
|
|
656
|
+
# @assign/@func 节点:把 out 声明(赋值表达式/写回目标)上总线——
|
|
657
|
+
# 引擎对这两类节点只 print 不发事件,调试窗要显示它们的"输出"全靠这条。
|
|
658
|
+
if ntype in ('assign', 'func'):
|
|
659
|
+
ad = self._action_def_for(node)
|
|
660
|
+
outs = getattr(ad, 'outs', None) if ad is not None else None
|
|
661
|
+
exprs = [_display_name(od) for od in (outs or [])
|
|
662
|
+
if not _is_field_noise(od)]
|
|
663
|
+
if exprs:
|
|
664
|
+
self._emit('action_outs', node=node, node_type=ntype,
|
|
665
|
+
exprs=exprs)
|
|
666
|
+
|
|
667
|
+
# ── func_result:@func 调用结果(引擎自带事件:入参 kwargs + 写回后
|
|
668
|
+
# 的 out 值 / 无 out 时为返回值 repr——此前无人消费,这里接上)──
|
|
669
|
+
def _on_func_result(self, data: dict):
|
|
670
|
+
self._emit('func_result',
|
|
671
|
+
node=data.get('node_name') or '',
|
|
672
|
+
func_input=data.get('input') or {},
|
|
673
|
+
output=data.get('output'))
|
|
674
|
+
|
|
675
|
+
# ── ai_request:合成回复 ──
|
|
676
|
+
def _on_ai_request(self, data: dict):
|
|
677
|
+
wait_key = data.get('wait_key') or ''
|
|
678
|
+
node = data.get('node_name') or ''
|
|
679
|
+
if not wait_key:
|
|
680
|
+
print(f"[fakehost] ⚠️ ai_request 缺 wait_key(node={node})", file=sys.stderr)
|
|
681
|
+
return
|
|
682
|
+
blocks = data.get('blocks') or {}
|
|
683
|
+
prompt = blocks.get('prompt') or self._node_prompt.get(node, '')
|
|
684
|
+
ad = self._action_def_for(node)
|
|
685
|
+
lines: List[str] = []
|
|
686
|
+
if ad is not None:
|
|
687
|
+
facade = _current_facade(node)
|
|
688
|
+
outs_real = [od for od in (ad.outs or []) if not _is_field_noise(od)]
|
|
689
|
+
pairs = self.oracle.resolve_action_outs(ad, prompt, facade)
|
|
690
|
+
values_map: Dict[str, dict] = {}
|
|
691
|
+
for (od, (value, source)) in zip(outs_real, pairs):
|
|
692
|
+
if source != 'assign-op' and self.rng.random() >= self.assign_prob:
|
|
693
|
+
self.silences.append(f"{node}:{_display_name(od)}")
|
|
694
|
+
self.log(f"🎲 {node} 概率沉默(不赋值 {_display_name(od)})")
|
|
695
|
+
self._emit('silence', node=node, var=_display_name(od))
|
|
696
|
+
continue
|
|
697
|
+
# flaky:概率输出无效赋值(未声明变量)→ assign_error
|
|
698
|
+
# → node_retry → 换值重发(完整测试重试链路)
|
|
699
|
+
if self.flaky and self.rng.random() < self.flaky:
|
|
700
|
+
self.flaky_fired.append(f"{node}:{_display_name(od)}")
|
|
701
|
+
self.log(f"💥 {node} flaky 无效赋值(触发重试链路)")
|
|
702
|
+
self._emit('flaky', node=node, var=_display_name(od))
|
|
703
|
+
lines.append(
|
|
704
|
+
"SET VARIABLE: <<__flaky_undefined_var = 1>>")
|
|
705
|
+
continue
|
|
706
|
+
line = self._render_assignment(od, value)
|
|
707
|
+
if line:
|
|
708
|
+
lines.append(line)
|
|
709
|
+
values_map[_display_name(od)] = {
|
|
710
|
+
'value': _safe_repr(value), 'source': source}
|
|
711
|
+
self._emit('ai_reply', node=node, values=values_map)
|
|
712
|
+
self._prepare_retry_values(ad, node, wait_key, prompt, facade)
|
|
713
|
+
reply = "[debug-sim](FakeHost 模拟回复,未调用 LLM)"
|
|
714
|
+
if lines:
|
|
715
|
+
reply += "\n" + "\n".join(lines)
|
|
716
|
+
self.log(f"🤖 ai_request node={node} outs={len(lines)}条")
|
|
717
|
+
self.runner.engine.human_input.provide_input(wait_key, {
|
|
718
|
+
'output': reply, 'steps': [], 'model_id': 'fake-host'})
|
|
719
|
+
|
|
720
|
+
# ── human_wait:合成输入 ──
|
|
721
|
+
def _on_human_wait(self, data: dict):
|
|
722
|
+
wait_key = data.get('wait_key') or ''
|
|
723
|
+
node = data.get('node_name') or ''
|
|
724
|
+
if not wait_key:
|
|
725
|
+
print(f"[fakehost] ⚠️ human_wait 缺 wait_key(node={node})", file=sys.stderr)
|
|
726
|
+
return
|
|
727
|
+
ad = self._action_def_for(node)
|
|
728
|
+
variables: Dict[str, str] = {}
|
|
729
|
+
if ad is not None:
|
|
730
|
+
facade = _current_facade(node)
|
|
731
|
+
prompt = data.get('prompt') or ''
|
|
732
|
+
outs_real = [od for od in (ad.outs or []) if not _is_field_noise(od)]
|
|
733
|
+
pairs = self.oracle.resolve_action_outs(ad, prompt, facade)
|
|
734
|
+
for (od, (value, source)) in zip(outs_real, pairs):
|
|
735
|
+
if source == 'assign-op':
|
|
736
|
+
continue
|
|
737
|
+
if self.rng.random() >= self.assign_prob:
|
|
738
|
+
self.silences.append(f"{node}:{_display_name(od)}")
|
|
739
|
+
self.log(f"🎲 {node} 概率沉默(human 不赋值)")
|
|
740
|
+
self._emit('silence', node=node, var=_display_name(od))
|
|
741
|
+
continue
|
|
742
|
+
if self.flaky and self.rng.random() < self.flaky:
|
|
743
|
+
self.flaky_fired.append(f"{node}:{_display_name(od)}")
|
|
744
|
+
self.log(f"💥 {node} flaky 无效赋值(触发重试链路)")
|
|
745
|
+
self._emit('flaky', node=node, var=_display_name(od))
|
|
746
|
+
continue
|
|
747
|
+
variables[_display_name(od)] = _to_input_str(value)
|
|
748
|
+
self._prepare_retry_values(ad, node, wait_key, prompt, facade)
|
|
749
|
+
self.log(f"👤 human_wait node={node} vars={list(variables)}")
|
|
750
|
+
self._emit('human_input', node=node, variables=dict(variables))
|
|
751
|
+
self.runner.engine.human_input.provide_input(wait_key, {
|
|
752
|
+
'chat_text': "[debug-sim](FakeHost 模拟人类输入)",
|
|
753
|
+
'variables': variables})
|
|
754
|
+
|
|
755
|
+
# ── node_retry:换值重发(引擎 emit_request=False,等同一 wait_key)──
|
|
756
|
+
def _on_node_retry(self, data: dict):
|
|
757
|
+
wait_key = data.get('wait_key') or ''
|
|
758
|
+
node = data.get('node_name') or ''
|
|
759
|
+
feedback = str(data.get('feedback') or '')
|
|
760
|
+
target = data.get('target') or 'ai'
|
|
761
|
+
backup = self._retry_values.get(wait_key)
|
|
762
|
+
if backup is None:
|
|
763
|
+
self.log(f"⚠️ {node} node_retry 无备用值,不重发({feedback[:60]})")
|
|
764
|
+
return
|
|
765
|
+
idx = backup['idx']
|
|
766
|
+
if idx >= len(backup['values']):
|
|
767
|
+
self.log(f"⚠️ {node} 备用值用尽,不重发({feedback[:60]})")
|
|
768
|
+
return
|
|
769
|
+
line = backup['values'][idx]
|
|
770
|
+
backup['idx'] = idx + 1
|
|
771
|
+
self.log(f"🔁 {node} 重试换值 #{idx + 1}({feedback[:50]})")
|
|
772
|
+
self._emit('retry', node=node, target=target, line=line,
|
|
773
|
+
feedback=feedback[:120])
|
|
774
|
+
if target == 'human':
|
|
775
|
+
variables = {}
|
|
776
|
+
m = re.match(
|
|
777
|
+
r'SET\s+VARIABLE:\s*<<\s*([@\w\u4e00-\u9fff\[\].]+)\s*=\s*(.+?)\s*>>',
|
|
778
|
+
line)
|
|
779
|
+
if m:
|
|
780
|
+
variables[m.group(1)] = m.group(2)
|
|
781
|
+
self.runner.engine.human_input.provide_input(wait_key, {
|
|
782
|
+
'chat_text': f"[debug-sim] 重试 #{idx + 1}",
|
|
783
|
+
'variables': variables})
|
|
784
|
+
else:
|
|
785
|
+
self.runner.engine.human_input.provide_input(wait_key, {
|
|
786
|
+
'output': f"[debug-sim] 重试 #{idx + 1}\n{line}",
|
|
787
|
+
'steps': [], 'model_id': 'fake-host'})
|
|
788
|
+
|
|
789
|
+
# ── 备用值(resolve 拒绝时轮换)──
|
|
790
|
+
def _prepare_retry_values(self, ad, node: str, wait_key: str,
|
|
791
|
+
prompt: str, facade):
|
|
792
|
+
if ad is None or not wait_key:
|
|
793
|
+
return
|
|
794
|
+
lines: List[str] = []
|
|
795
|
+
for od in (ad.outs or []):
|
|
796
|
+
if _is_field_noise(od) or _is_assign_out(od):
|
|
797
|
+
continue
|
|
798
|
+
for alt in self._alternative_values(od, prompt, facade)[:2]:
|
|
799
|
+
lines.append(
|
|
800
|
+
f"SET VARIABLE: <<{od.var_name} = {_to_input_str(alt)}>>")
|
|
801
|
+
if lines:
|
|
802
|
+
self._retry_values[wait_key] = {'values': lines, 'idx': 0}
|
|
803
|
+
|
|
804
|
+
def _alternative_values(self, od, prompt: str, facade) -> List[Any]:
|
|
805
|
+
alts: List[Any] = []
|
|
806
|
+
if getattr(od, 'choices', None):
|
|
807
|
+
try:
|
|
808
|
+
expr = od.choices.strip()
|
|
809
|
+
if expr.startswith('{') and expr.endswith('}'):
|
|
810
|
+
expr = expr[1:-1].strip()
|
|
811
|
+
val = self.oracle.runner.evaluator.evaluate(expr, facade, strict=False)
|
|
812
|
+
if isinstance(val, (list, tuple)):
|
|
813
|
+
alts.extend(val)
|
|
814
|
+
except Exception:
|
|
815
|
+
pass
|
|
816
|
+
init = self.oracle._declared_initial(od.var_name, facade)
|
|
817
|
+
if isinstance(init, bool):
|
|
818
|
+
alts.extend([True, False])
|
|
819
|
+
elif isinstance(init, (int, float)):
|
|
820
|
+
alts.extend([init, type(init)(init + 1)])
|
|
821
|
+
elif isinstance(init, str) and init.startswith('@'):
|
|
822
|
+
actor = self.oracle._pick_actor(init, facade)
|
|
823
|
+
if actor:
|
|
824
|
+
alts.append(actor)
|
|
825
|
+
if not alts:
|
|
826
|
+
alts = ["debug", "debug-2"]
|
|
827
|
+
return alts
|
|
828
|
+
|
|
829
|
+
# ── node → action 定义(主查节点绑定,兜底同名;含模块内节点)──
|
|
830
|
+
def _action_def_for(self, node_name: str):
|
|
831
|
+
runner = self.runner
|
|
832
|
+
# 1) 剧本级 flow 节点绑定
|
|
833
|
+
node_obj = (runner.script.flow.nodes or {}).get(node_name)
|
|
834
|
+
if node_obj is not None and getattr(node_obj, 'action_name', None):
|
|
835
|
+
ad = (runner.script.actions or {}).get(node_obj.action_name)
|
|
836
|
+
if ad is not None:
|
|
837
|
+
return ad
|
|
838
|
+
# 2) 同名兜底(常见剧本节点名==action 名)
|
|
839
|
+
ad = (runner.script.actions or {}).get(node_name)
|
|
840
|
+
if ad is not None:
|
|
841
|
+
return ad
|
|
842
|
+
# 3) 模块内节点:当前模块帧栈顶的 actions
|
|
843
|
+
try:
|
|
844
|
+
from femoCompiler.FEMO_runtime import current_task_ctx
|
|
845
|
+
ctx = current_task_ctx()
|
|
846
|
+
if ctx is not None and getattr(ctx, 'module_frames', None):
|
|
847
|
+
top = ctx.module_frames[-1].name
|
|
848
|
+
mod = runner._resolve_module_def(top)
|
|
849
|
+
ad = (mod.actions or {}).get(node_name)
|
|
850
|
+
if ad is not None:
|
|
851
|
+
return ad
|
|
852
|
+
node_obj = (mod.flow.nodes or {}).get(node_name)
|
|
853
|
+
if node_obj is not None and getattr(node_obj, 'action_name', None):
|
|
854
|
+
return (mod.actions or {}).get(node_obj.action_name)
|
|
855
|
+
except Exception:
|
|
856
|
+
pass
|
|
857
|
+
return None
|
|
858
|
+
|
|
859
|
+
# ── 渲染 ──
|
|
860
|
+
def _render_assignment(self, od, value) -> Optional[str]:
|
|
861
|
+
if _is_assign_out(od):
|
|
862
|
+
return f"SET VARIABLE: <<{od.var_name}>>"
|
|
863
|
+
dk = getattr(od, 'dynamic_key', None)
|
|
864
|
+
if dk:
|
|
865
|
+
# 动态字典键 out(damage_report.@hero):引擎 AI 通道的
|
|
866
|
+
# _parse_single_assignment 正则(VAR_NAME_RE)不含点号,dotted
|
|
867
|
+
# lvalue 解析不了(引擎 bug #4,2026-09-08 调试器实测);human
|
|
868
|
+
# 通道走结构化 variables 无此问题。AI 侧改用引擎完全支持的
|
|
869
|
+
# 整字典赋值:读当前值 + 写入合成键,仍走真实解析管线。
|
|
870
|
+
try:
|
|
871
|
+
facade = _current_facade('')
|
|
872
|
+
key = self.runner.evaluator.evaluate(dk, facade, strict=False)
|
|
873
|
+
cur = facade.get(od.var_name)
|
|
874
|
+
if not isinstance(cur, dict):
|
|
875
|
+
cur = {}
|
|
876
|
+
merged = dict(cur)
|
|
877
|
+
merged[str(key)] = value
|
|
878
|
+
dict_lit = '{' + ', '.join(
|
|
879
|
+
f'"{k}": {json.dumps(v, ensure_ascii=False)}'
|
|
880
|
+
for k, v in merged.items()) + '}'
|
|
881
|
+
return f"SET VARIABLE: <<{od.var_name} = {dict_lit}>>"
|
|
882
|
+
except Exception as e:
|
|
883
|
+
print(f"[fakehost] ⚠️ 动态键 out 渲染失败({od.var_name}.{dk}): {e}",
|
|
884
|
+
file=sys.stderr)
|
|
885
|
+
return None
|
|
886
|
+
return f"SET VARIABLE: <<{od.var_name} = {_to_input_str(value)}>>"
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
def _display_name(od) -> str:
|
|
890
|
+
dk = getattr(od, 'dynamic_key', None)
|
|
891
|
+
return f"{od.var_name}.{dk}" if dk else od.var_name
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
def _to_input_str(value) -> str:
|
|
895
|
+
if isinstance(value, bool):
|
|
896
|
+
return 'true' if value else 'false'
|
|
897
|
+
return str(value)
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
def _current_facade(node_hint: str = ''):
|
|
901
|
+
from femoCompiler.FEMO_runtime import current_task_ctx
|
|
902
|
+
ctx = current_task_ctx()
|
|
903
|
+
if ctx is None:
|
|
904
|
+
raise RuntimeError(
|
|
905
|
+
f"FakeHost: 无 TaskContext(node={node_hint},事件回调线程未绑"
|
|
906
|
+
f"执行上下文)——引擎协议变更,请检查 FEMO_runtime.current_task_ctx")
|
|
907
|
+
return ctx.facade
|
|
908
|
+
|
|
909
|
+
|
|
910
|
+
# ════════════════════════════════════════════════════════════
|
|
911
|
+
# module 单测:合成 wrapper mainflow
|
|
912
|
+
# ════════════════════════════════════════════════════════════
|
|
913
|
+
|
|
914
|
+
def resolve_module_def(script, module_path: str):
|
|
915
|
+
"""按点路径逐段下钻解析模块定义——与引擎 FEMORunner._resolve_module_def
|
|
916
|
+
同一口径('Outer.Inner' → script.modules['Outer'].modules['Inner'])。
|
|
917
|
+
容忍 '&' 前缀(用户习惯 &Mod 引用)。解析失败响亮 ValueError(列出
|
|
918
|
+
顶层可用名)——调试器侧先拦住,别等引擎在跑动中途才炸。"""
|
|
919
|
+
raw = (module_path or '').strip().lstrip('&')
|
|
920
|
+
container = script.modules or {}
|
|
921
|
+
mod = None
|
|
922
|
+
for part in raw.split('.'):
|
|
923
|
+
mod = container.get(part)
|
|
924
|
+
if mod is None:
|
|
925
|
+
raise ValueError(
|
|
926
|
+
f"module '{module_path}' 未定义(解析失败于段 '{part}')。"
|
|
927
|
+
f"顶层可用: {sorted((script.modules or {}).keys()) or '(无)'}")
|
|
928
|
+
container = getattr(mod, 'modules', None) or {}
|
|
929
|
+
return mod
|
|
930
|
+
|
|
931
|
+
|
|
932
|
+
def wrap_module_test(script, module_path: str):
|
|
933
|
+
"""合成 mainflow:[START]→[MT_IN]→[MT_MOD:&Mod]→[MT_OUT]→[END]。
|
|
934
|
+
|
|
935
|
+
[MT_MOD] 的 module_ref 走引擎真实 _run_module:模块 local vars/形参按
|
|
936
|
+
module_initials 入帧(call_initials),母/姥姥模块变量与全局变量经
|
|
937
|
+
ScopeTable 声明链(def_chain 由内到外)天然可见。$shared 变量照常
|
|
938
|
+
全局一份。模块定义本身不动——被测的就是模块自己的 flow。
|
|
939
|
+
|
|
940
|
+
支持嵌套模块点路径('Outer.Inner',2026-09-12):引擎 _run_module 的
|
|
941
|
+
顶层点路径 fallback 按完整路径解析并入帧——帧键与 ScopeTable owner
|
|
942
|
+
同为点路径,module_initials/enter_module 天然一致。
|
|
943
|
+
"""
|
|
944
|
+
from femoCompiler.FEMO_parser import FlowNode, FlowEdge, FlowGraph
|
|
945
|
+
module_path = (module_path or '').strip().lstrip('&')
|
|
946
|
+
resolve_module_def(script, module_path) # 不存在即 ValueError,响亮
|
|
947
|
+
script.debug_module = module_path # run_start 记录带范围(前端/工具显示用)
|
|
948
|
+
g = FlowGraph()
|
|
949
|
+
g.add_node(FlowNode(id='[START]', type='start', label='START'))
|
|
950
|
+
g.add_node(FlowNode(id='[MT_IN]', type='start', label='MT_IN'))
|
|
951
|
+
g.add_node(FlowNode(id='[MT_MOD]', type='action', label=module_path,
|
|
952
|
+
module_ref=module_path))
|
|
953
|
+
g.add_node(FlowNode(id='[MT_OUT]', type='end', label='MT_OUT'))
|
|
954
|
+
g.add_node(FlowNode(id='[END]', type='end', label='END'))
|
|
955
|
+
g.add_edge('[START]', '[MT_IN]')
|
|
956
|
+
g.add_edge('[MT_IN]', '[MT_MOD]')
|
|
957
|
+
g.add_edge('[MT_MOD]', '[MT_OUT]')
|
|
958
|
+
g.add_edge('[MT_OUT]', '[END]')
|
|
959
|
+
script.flow = g
|
|
960
|
+
return script
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
# ════════════════════════════════════════════════════════════
|
|
964
|
+
# 编译与运行
|
|
965
|
+
#════════════════════════════════════════════════════════════
|
|
966
|
+
|
|
967
|
+
def load_script(femo_path: str, base_dir: Optional[str] = None):
|
|
968
|
+
"""编译剧本(沙库内进行,soul/user 查询落沙库)。
|
|
969
|
+
|
|
970
|
+
base_dir:覆盖 code: 相对引用的解析目录(默认=剧本所在目录)。
|
|
971
|
+
调试路由用:剧本文本暂存沙盒,引用按原剧本目录解析——与正式
|
|
972
|
+
运行同语义(否则 file:"xxx.py" 落在别处必 404)。
|
|
973
|
+
返回 (script, base_dir) 已并入 script——引擎 FEMORunner 的 base_dir
|
|
974
|
+
参数必须用它(code: 相对路径按它解析),Script 对象本身不带该信息。"""
|
|
975
|
+
from femoCompiler.FEMO_parser import parse_script
|
|
976
|
+
with open(femo_path, 'r', encoding='utf-8-sig') as f:
|
|
977
|
+
text = f.read()
|
|
978
|
+
base_dir = base_dir or os.path.dirname(os.path.abspath(femo_path))
|
|
979
|
+
script = parse_script(text, base_dir=base_dir)
|
|
980
|
+
script.debug_base_dir = base_dir
|
|
981
|
+
return script
|
|
982
|
+
|
|
983
|
+
|
|
984
|
+
def run_once(script, seed: int, overrides: Dict[str, List[str]],
|
|
985
|
+
assign_prob: float, max_steps: int, quiet: bool,
|
|
986
|
+
flaky: float = 0.0, run_index: Optional[int] = None,
|
|
987
|
+
bus: Optional[DebugLogBus] = None) -> dict:
|
|
988
|
+
"""单轮调试跑(沙库内)。返回报告数据。
|
|
989
|
+
|
|
990
|
+
bus:传入外部 DebugLogBus 即可实时订阅本轮全部结构化日志
|
|
991
|
+
(节点/边/变量赋值/合成发言/告警);不传则自建一条(随结果返回)。
|
|
992
|
+
"""
|
|
993
|
+
from femoCompiler.FEMO_runtime import FEMORunner
|
|
994
|
+
|
|
995
|
+
bus = bus or DebugLogBus()
|
|
996
|
+
bus.set_context(run=run_index, seed=seed)
|
|
997
|
+
rng = random.Random(seed)
|
|
998
|
+
flaky_rng = random.Random(seed ^ 0x5EED)
|
|
999
|
+
tracker = CoverageTracker(bus=bus)
|
|
1000
|
+
oracle = ValueOracle(None, rng, overrides)
|
|
1001
|
+
oracle.bus = bus
|
|
1002
|
+
fake = FakeHost(None, oracle, tracker, assign_prob, quiet, flaky_rng,
|
|
1003
|
+
flaky=flaky, bus=bus)
|
|
1004
|
+
flow_result = {'outcome': 'exception', 'error': None}
|
|
1005
|
+
t0 = time.time()
|
|
1006
|
+
bus.emit('run_start', script=script.meta.get('name', ''),
|
|
1007
|
+
overrides={k: list(v) for k, v in (overrides or {}).items()},
|
|
1008
|
+
module=getattr(script, 'debug_module', None))
|
|
1009
|
+
|
|
1010
|
+
def event_cb(event_type: str, data: dict):
|
|
1011
|
+
fake.on_event(event_type, data)
|
|
1012
|
+
if event_type == 'flow_done':
|
|
1013
|
+
flow_result['outcome'] = 'completed'
|
|
1014
|
+
bus.emit('flow_outcome', outcome='completed', error=None)
|
|
1015
|
+
elif event_type == 'flow_paused':
|
|
1016
|
+
flow_result['outcome'] = 'paused'
|
|
1017
|
+
bus.emit('flow_outcome', outcome='paused', error=None)
|
|
1018
|
+
elif event_type == 'flow_error':
|
|
1019
|
+
flow_result['outcome'] = 'error'
|
|
1020
|
+
flow_result['error'] = str((data or {}).get('error', ''))
|
|
1021
|
+
bus.emit('flow_outcome', outcome='error',
|
|
1022
|
+
error=flow_result['error'][:200])
|
|
1023
|
+
|
|
1024
|
+
runner = FEMORunner(
|
|
1025
|
+
script,
|
|
1026
|
+
base_dir=getattr(script, 'debug_base_dir', os.getcwd()),
|
|
1027
|
+
verbose=False,
|
|
1028
|
+
event_callback=event_cb,
|
|
1029
|
+
)
|
|
1030
|
+
runner._human_input_event = threading.Event()
|
|
1031
|
+
runner._host_ai_backend = True
|
|
1032
|
+
oracle.runner = runner
|
|
1033
|
+
fake.runner = runner
|
|
1034
|
+
|
|
1035
|
+
# ── --set 跑前直接注入变量世界(root task '__script__' 帧)──
|
|
1036
|
+
# 语义:定向设定初始状态,让条件边按指定方向走(比 L1 覆盖更早、更可控)。
|
|
1037
|
+
# 值解析:@actor → 引擎 actors 表真实演员名;数字/布尔/字符串直接入帧。
|
|
1038
|
+
if overrides:
|
|
1039
|
+
root_env = runner.world.envs.get('t0')
|
|
1040
|
+
if root_env is None:
|
|
1041
|
+
raise RuntimeError(
|
|
1042
|
+
"--set 注入失败:world.envs['t0'] 不存在(引擎装配变更?)")
|
|
1043
|
+
for k, seq in overrides.items():
|
|
1044
|
+
i = min(rng.randrange(len(seq)) if len(seq) > 1 else 0, len(seq) - 1)
|
|
1045
|
+
raw = seq[i]
|
|
1046
|
+
val = _coerce(raw)
|
|
1047
|
+
if isinstance(val, str) and val.startswith('@'):
|
|
1048
|
+
# @actor:验证存在性(响亮报错,不静默)
|
|
1049
|
+
aname = val
|
|
1050
|
+
if aname not in (runner.script.actors or {}):
|
|
1051
|
+
raise ValueError(
|
|
1052
|
+
f"--set {k}={raw}: actor '{aname}' 不在剧本 actors 中。"
|
|
1053
|
+
f"可用: {sorted(runner.script.actors.keys())}")
|
|
1054
|
+
root_env.frames['__script__'][k] = val
|
|
1055
|
+
print(f"[debug] 💉 --set 已注入: "
|
|
1056
|
+
f"{ {k: root_env.frames['__script__'].get(k) for k in overrides} }")
|
|
1057
|
+
|
|
1058
|
+
_patch_tracking(runner, tracker, flow_result, max_steps)
|
|
1059
|
+
|
|
1060
|
+
try:
|
|
1061
|
+
# 不传 max_steps:引擎 run_async 的 global_meta 只在 max_steps is None
|
|
1062
|
+
# 分支绑定,显式传参会 UnboundLocalError(引擎 bug,2026-09-08 调试器
|
|
1063
|
+
# 首跑卖修——bridge 生产路径不传参故未触发)。步数预算由上面的
|
|
1064
|
+
# _patch_tracking 补丁承担。
|
|
1065
|
+
runner.run()
|
|
1066
|
+
except Exception as e:
|
|
1067
|
+
if flow_result['outcome'] == 'exception':
|
|
1068
|
+
flow_result['error'] = f"{type(e).__name__}: {e}"
|
|
1069
|
+
if not quiet:
|
|
1070
|
+
traceback.print_exc()
|
|
1071
|
+
finally:
|
|
1072
|
+
try:
|
|
1073
|
+
import asyncio
|
|
1074
|
+
asyncio.run(runner.engine.shutdown())
|
|
1075
|
+
except Exception:
|
|
1076
|
+
pass
|
|
1077
|
+
|
|
1078
|
+
elapsed = round(time.time() - t0, 2)
|
|
1079
|
+
bus.emit('run_end', outcome=flow_result['outcome'],
|
|
1080
|
+
error=flow_result.get('error'), elapsed=elapsed)
|
|
1081
|
+
return {
|
|
1082
|
+
'outcome': flow_result['outcome'],
|
|
1083
|
+
'error': flow_result.get('error'),
|
|
1084
|
+
'seed': seed,
|
|
1085
|
+
'elapsed': elapsed,
|
|
1086
|
+
'tracker': tracker,
|
|
1087
|
+
'oracle': oracle,
|
|
1088
|
+
'fake': fake,
|
|
1089
|
+
'bus': bus,
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
|
|
1093
|
+
# 类级 patch 的运行上下文:VarFacade.apply_intent 是类级方法,只能包装一次
|
|
1094
|
+
# (每轮重装会层层嵌套);但 tracker / 当前节点归属必须按「当前轮」解析。
|
|
1095
|
+
# 早期实现用闭包捕获,第 2 轮起 _patch_tracking 早退,赋值记录泄漏进第 1 轮
|
|
1096
|
+
# tracker、节点名停在上一轮末节点(2026-09-08 实测)。改为模块级
|
|
1097
|
+
# threading.local,每轮 run_once 重挂当前 tracker,patch 内动态读取。
|
|
1098
|
+
_RUN_CTX = threading.local()
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
def _patch_tracking(runner, tracker: CoverageTracker, flow_result: dict,
|
|
1102
|
+
max_steps: int):
|
|
1103
|
+
"""侦听点(全部包装实例方法,不改引擎文件):
|
|
1104
|
+
- _execute_node_content:步数预算(死循环保险)
|
|
1105
|
+
- _follow_next_edge:边覆盖
|
|
1106
|
+
- VarFacade.apply_intent(类级,仅装一次):变量赋值 diff,归属读 _RUN_CTX
|
|
1107
|
+
"""
|
|
1108
|
+
step_count = [0]
|
|
1109
|
+
budget = [max_steps]
|
|
1110
|
+
|
|
1111
|
+
orig_exec = runner._execute_node_content
|
|
1112
|
+
|
|
1113
|
+
async def patched_exec(node, flow, extra_actions, *_args, **_kwargs):
|
|
1114
|
+
step_count[0] += 1
|
|
1115
|
+
if budget[0] and step_count[0] > budget[0]:
|
|
1116
|
+
flow_result['outcome'] = 'max_steps'
|
|
1117
|
+
raise RuntimeError(
|
|
1118
|
+
f"[debug] 步数预算耗尽({budget[0]} 步)仍未停——可能是无限循环"
|
|
1119
|
+
f"/持续循环型设计,已中止(max_steps 不算错误,退出码 0)")
|
|
1120
|
+
return await orig_exec(node, flow, extra_actions, *_args, **_kwargs)
|
|
1121
|
+
|
|
1122
|
+
runner._execute_node_content = patched_exec
|
|
1123
|
+
|
|
1124
|
+
orig_edge = runner._follow_next_edge
|
|
1125
|
+
|
|
1126
|
+
def patched_edge(node_id, flow):
|
|
1127
|
+
tgt = orig_edge(node_id, flow)
|
|
1128
|
+
if tgt is not None:
|
|
1129
|
+
tracker.on_edge(node_id, tgt)
|
|
1130
|
+
return tgt
|
|
1131
|
+
|
|
1132
|
+
runner._follow_next_edge = patched_edge
|
|
1133
|
+
|
|
1134
|
+
# 类级 patch apply_intent:记录 old→new(当前节点由每轮的
|
|
1135
|
+
# _emit_event 包装刷新进 _RUN_CTX——见 _RUN_CTX 注释)
|
|
1136
|
+
from femoCompiler.vars.env import VarFacade
|
|
1137
|
+
_RUN_CTX.tracker = tracker
|
|
1138
|
+
_RUN_CTX.node = '?'
|
|
1139
|
+
if not getattr(VarFacade, '_debug_patched', False):
|
|
1140
|
+
orig_apply = VarFacade.apply_intent
|
|
1141
|
+
|
|
1142
|
+
def patched_apply(self_facade, name, intent):
|
|
1143
|
+
old = _safe_get(self_facade, name)
|
|
1144
|
+
ret = orig_apply(self_facade, name, intent)
|
|
1145
|
+
new = _safe_get(self_facade, name)
|
|
1146
|
+
t = getattr(_RUN_CTX, 'tracker', None)
|
|
1147
|
+
if t is not None:
|
|
1148
|
+
t.on_assignment(getattr(_RUN_CTX, 'node', '?'), name, old, new)
|
|
1149
|
+
return ret
|
|
1150
|
+
|
|
1151
|
+
VarFacade.apply_intent = patched_apply
|
|
1152
|
+
VarFacade._debug_patched = True
|
|
1153
|
+
|
|
1154
|
+
orig_emit = runner._emit_event
|
|
1155
|
+
|
|
1156
|
+
def patched_emit(event_type, data=None):
|
|
1157
|
+
if event_type == 'node_start':
|
|
1158
|
+
_RUN_CTX.node = (data or {}).get('node_name') or '?'
|
|
1159
|
+
return orig_emit(event_type, data)
|
|
1160
|
+
|
|
1161
|
+
runner._emit_event = patched_emit
|
|
1162
|
+
|
|
1163
|
+
|
|
1164
|
+
def _safe_get(facade, name: str):
|
|
1165
|
+
try:
|
|
1166
|
+
return facade.get(name)
|
|
1167
|
+
except Exception:
|
|
1168
|
+
return '<unset>'
|
|
1169
|
+
|
|
1170
|
+
|
|
1171
|
+
# ════════════════════════════════════════════════════════════
|
|
1172
|
+
# 报告
|
|
1173
|
+
#════════════════════════════════════════════════════════════
|
|
1174
|
+
|
|
1175
|
+
# 结构节点(非作者编写的流程节点):未达判定不报它们。
|
|
1176
|
+
_STRUCTURAL_NODES = {'[START]', '[END]', '[IN]', '[OUT]', '[BREAK]',
|
|
1177
|
+
'[MT_IN]', '[MT_MOD]', '[MT_OUT]'}
|
|
1178
|
+
|
|
1179
|
+
|
|
1180
|
+
def _reached_nodes(merged) -> set:
|
|
1181
|
+
"""节点可达集:从边覆盖推导(空节点/模块节点不发 node_start 事件)。"""
|
|
1182
|
+
reached = set(merged.node_visits)
|
|
1183
|
+
for e in merged.edges_taken:
|
|
1184
|
+
src, _, tgt = e.partition('->')
|
|
1185
|
+
reached.add(src)
|
|
1186
|
+
reached.add(tgt)
|
|
1187
|
+
return reached
|
|
1188
|
+
|
|
1189
|
+
|
|
1190
|
+
def _module_flow(script, module_mode: Optional[str]):
|
|
1191
|
+
"""module 模式的判定用 flow:被测模块自己的 flow;整剧本模式 mainflow。
|
|
1192
|
+
(module 模式下 script.flow 已被 wrapper 换成合成主流程,不能用它做
|
|
1193
|
+
覆盖判定的分母/分子。)"""
|
|
1194
|
+
if not module_mode:
|
|
1195
|
+
return getattr(script, 'flow', None)
|
|
1196
|
+
mod = resolve_module_def(script, module_mode)
|
|
1197
|
+
return getattr(mod, 'flow', None)
|
|
1198
|
+
|
|
1199
|
+
|
|
1200
|
+
def _module_has_out(script, module_mode: Optional[str]) -> Optional[bool]:
|
|
1201
|
+
"""被测模块 flow 是否有 [OUT]/[BREAK] 出口(None=非 module 模式或无 flow)。
|
|
1202
|
+
无出口 = 持续循环型设计——max_steps 结局属预期(静态检测,回答
|
|
1203
|
+
「无限循环型模块能不能提前识别」:能识别的是这种无出口形态;带出口但
|
|
1204
|
+
条件永不满足的动态死循环只能靠步数预算在跑动中暴露)。"""
|
|
1205
|
+
if not module_mode:
|
|
1206
|
+
return None
|
|
1207
|
+
flow = _module_flow(script, module_mode)
|
|
1208
|
+
if flow is None:
|
|
1209
|
+
return None
|
|
1210
|
+
nodes = set((flow.nodes or {}).keys())
|
|
1211
|
+
return '[OUT]' in nodes or '[BREAK]' in nodes
|
|
1212
|
+
|
|
1213
|
+
|
|
1214
|
+
def _unreached_nodes(merged, script,
|
|
1215
|
+
module_mode: Optional[str] = None) -> List[str]:
|
|
1216
|
+
"""本场(多轮合并后)一次都没走到的作者节点——死分支/漏接线的证据。
|
|
1217
|
+
|
|
1218
|
+
2026-09-11 抽出:原先只在 print_report 里算(人看得见),JSON 终报
|
|
1219
|
+
(AI/工具消费方)看不到;femo-debug 工具要把「全部信息」回给主模型,
|
|
1220
|
+
未达节点必须进结构化终报。print_report 与 write_json_report 共用本函数,
|
|
1221
|
+
两处口径永远一致。
|
|
1222
|
+
|
|
1223
|
+
2026-09-12 修正 module 模式口径:原实现固定看 script.flow——但 module
|
|
1224
|
+
模式下它已被 wrapper 换成合成主流程(全是结构节点),模块自己的死分支
|
|
1225
|
+
永远报不出来;现按被测模块自己的 flow 算。
|
|
1226
|
+
|
|
1227
|
+
flow 为 None(解析没得到流程,如空/垃圾剧本)时返回空表:直接摸
|
|
1228
|
+
flow.nodes 会 AttributeError——那会在 print_report 里炸掉,连带后面的
|
|
1229
|
+
write_json_report 也不执行(-report 静默丢文件)。"""
|
|
1230
|
+
flow = _module_flow(script, module_mode)
|
|
1231
|
+
if flow is None:
|
|
1232
|
+
return []
|
|
1233
|
+
reached = _reached_nodes(merged)
|
|
1234
|
+
return [n for n in (flow.nodes or {})
|
|
1235
|
+
if n not in reached and n not in _STRUCTURAL_NODES
|
|
1236
|
+
and not n.startswith('__')]
|
|
1237
|
+
|
|
1238
|
+
|
|
1239
|
+
_OUTCOME_LABELS = {
|
|
1240
|
+
# max_steps = 跑满步数预算仍未停。持续循环型模块(如群聊回 [IN])这是
|
|
1241
|
+
# 预期结局;真死循环也在这暴露。按 2026-09-12 拍板:不算错误,退出码 0。
|
|
1242
|
+
'max_steps': 'max_steps(跑满步数预算仍未停——可能是无限循环,非错误)',
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
|
|
1246
|
+
def _outcome_label(outcome: str) -> str:
|
|
1247
|
+
return _OUTCOME_LABELS.get(outcome, outcome)
|
|
1248
|
+
|
|
1249
|
+
|
|
1250
|
+
def print_report(runs: List[dict], script, module_mode: Optional[str]):
|
|
1251
|
+
merged = runs[0]['tracker']
|
|
1252
|
+
for r in runs[1:]:
|
|
1253
|
+
merged.cross_run_merge(r['tracker'])
|
|
1254
|
+
outcomes = [r['outcome'] for r in runs]
|
|
1255
|
+
ok = sum(1 for o in outcomes if o == 'completed')
|
|
1256
|
+
loops = sum(1 for o in outcomes if o == 'max_steps')
|
|
1257
|
+
# 边覆盖率分母:module 模式看被测模块自己的 flow;整剧本看 mainflow
|
|
1258
|
+
total_edges = 0
|
|
1259
|
+
mflow = _module_flow(script, module_mode)
|
|
1260
|
+
if mflow is not None:
|
|
1261
|
+
total_edges = len(mflow.edges)
|
|
1262
|
+
print()
|
|
1263
|
+
print('═' * 62)
|
|
1264
|
+
title = f"Femo Debug — {script.meta.get('name', '')}"
|
|
1265
|
+
if module_mode:
|
|
1266
|
+
title += f" — module: {module_mode}"
|
|
1267
|
+
print(title)
|
|
1268
|
+
print('═' * 62)
|
|
1269
|
+
result = f"结果: {ok}/{len(runs)} 轮 completed"
|
|
1270
|
+
if loops:
|
|
1271
|
+
result += (f"({loops} 轮 max_steps:跑满步数预算未停——可能是无限循环"
|
|
1272
|
+
f"/持续循环型设计,非错误)")
|
|
1273
|
+
print(f"{result} 耗时: {sum(r['elapsed'] for r in runs):.1f}s "
|
|
1274
|
+
f"种子: {[r['seed'] for r in runs]}")
|
|
1275
|
+
for r in runs:
|
|
1276
|
+
line = f" seed={r['seed']}: {_outcome_label(r['outcome'])}"
|
|
1277
|
+
if r.get('error'):
|
|
1278
|
+
line += f" — {str(r['error'])[:110]}"
|
|
1279
|
+
print(line)
|
|
1280
|
+
print(f"节点执行: {' → '.join(merged.node_order[:36])}"
|
|
1281
|
+
+ (' …' if len(merged.node_order) > 36 else ''))
|
|
1282
|
+
cov = len(merged.edges_taken)
|
|
1283
|
+
pct = (cov / total_edges * 100) if total_edges else 0
|
|
1284
|
+
print(f"边覆盖: {cov}/{total_edges} ({pct:.0f}%)")
|
|
1285
|
+
if merged.var_snapshots:
|
|
1286
|
+
print("变量快照(diff):")
|
|
1287
|
+
for s in merged.var_snapshots[:12]:
|
|
1288
|
+
print(f" {s['node']:<16} {s['var']}: {s['old']} → {s['new']}")
|
|
1289
|
+
if len(merged.var_snapshots) > 12:
|
|
1290
|
+
print(f" … 共 {len(merged.var_snapshots)} 条")
|
|
1291
|
+
warn = []
|
|
1292
|
+
for r in runs:
|
|
1293
|
+
warn.extend(r['oracle'].guess_warnings)
|
|
1294
|
+
warn.extend(f"概率沉默: {s}" for s in r['fake'].silences)
|
|
1295
|
+
warn.extend(f"flaky 无效赋值: {s}" for s in r['fake'].flaky_fired)
|
|
1296
|
+
if warn:
|
|
1297
|
+
print(f"提示 ⚠ {len(warn)} 条:")
|
|
1298
|
+
for w in dict.fromkeys(warn):
|
|
1299
|
+
print(f" • {w}")
|
|
1300
|
+
unreached = _unreached_nodes(merged, script, module_mode)
|
|
1301
|
+
if unreached:
|
|
1302
|
+
print(f"未达节点: {unreached}")
|
|
1303
|
+
if module_mode and _module_has_out(script, module_mode) is False:
|
|
1304
|
+
print("ℹ 该模块 flow 没有 [OUT]/[BREAK] 出口——持续循环型设计,"
|
|
1305
|
+
"干跑跑满步数预算(max_steps)即停,属预期非错误")
|
|
1306
|
+
print('═' * 62)
|
|
1307
|
+
|
|
1308
|
+
|
|
1309
|
+
def write_json_report(path: str, runs: List[dict], script,
|
|
1310
|
+
module_mode: Optional[str]):
|
|
1311
|
+
merged = runs[0]['tracker']
|
|
1312
|
+
for r in runs[1:]:
|
|
1313
|
+
merged.cross_run_merge(r['tracker'])
|
|
1314
|
+
# 边覆盖率分母:module 模式看被测模块自己的 flow;整剧本看 mainflow
|
|
1315
|
+
total_edges = 0
|
|
1316
|
+
mflow = _module_flow(script, module_mode)
|
|
1317
|
+
if mflow is not None:
|
|
1318
|
+
total_edges = len(mflow.edges)
|
|
1319
|
+
data = {
|
|
1320
|
+
'script': script.meta.get('name', ''),
|
|
1321
|
+
'module_mode': module_mode,
|
|
1322
|
+
'runs': [{'seed': r['seed'], 'outcome': r['outcome'],
|
|
1323
|
+
'error': r.get('error'), 'elapsed': r['elapsed']}
|
|
1324
|
+
for r in runs],
|
|
1325
|
+
'node_visits': merged.node_visits,
|
|
1326
|
+
'node_order': merged.node_order,
|
|
1327
|
+
'edges_taken': sorted(merged.edges_taken),
|
|
1328
|
+
'total_edges': total_edges,
|
|
1329
|
+
'var_snapshots': merged.var_snapshots,
|
|
1330
|
+
'guess_warnings': sorted(set(
|
|
1331
|
+
w for r in runs for w in r['oracle'].guess_warnings)),
|
|
1332
|
+
'silences': [s for r in runs for s in r['fake'].silences],
|
|
1333
|
+
'flaky_fired': [s for r in runs for s in r['fake'].flaky_fired],
|
|
1334
|
+
# 未达节点(2026-09-11 起进终报):结构化消费方(femo-debug 工具)
|
|
1335
|
+
# 也能看到死分支——与 print_report 共用 _unreached_nodes,口径一致。
|
|
1336
|
+
# 2026-09-12 module 模式按被测模块自己的 flow 算。
|
|
1337
|
+
'unreached_nodes': _unreached_nodes(merged, script, module_mode),
|
|
1338
|
+
# module 模式静态检测:被测模块 flow 无 [OUT]/[BREAK] = 持续循环型
|
|
1339
|
+
# 设计,max_steps 结局属预期(None=非 module 模式或模块无 flow)。
|
|
1340
|
+
'module_has_out': _module_has_out(script, module_mode),
|
|
1341
|
+
}
|
|
1342
|
+
with open(path, 'w', encoding='utf-8') as f:
|
|
1343
|
+
json.dump(data, f, ensure_ascii=False, indent=2, default=str)
|
|
1344
|
+
print(f"[debug] 📄 JSON 报告: {os.path.abspath(path)}")
|
|
1345
|
+
|
|
1346
|
+
|
|
1347
|
+
# ════════════════════════════════════════════════════════════
|
|
1348
|
+
# CLI
|
|
1349
|
+
#════════════════════════════════════════════════════════════
|
|
1350
|
+
|
|
1351
|
+
def parse_set_args(set_args: List[str]) -> Dict[str, List[str]]:
|
|
1352
|
+
"""--set k=v / k=v1|v2 → {k: [v1, v2]}。支持 @actor、数字、布尔。"""
|
|
1353
|
+
overrides: Dict[str, List[str]] = {}
|
|
1354
|
+
for s in set_args or []:
|
|
1355
|
+
if '=' not in s:
|
|
1356
|
+
raise ValueError(f"--set 格式应为 k=v 或 k=v1|v2,收到: {s!r}")
|
|
1357
|
+
k, v = s.split('=', 1)
|
|
1358
|
+
k = k.strip()
|
|
1359
|
+
if not k:
|
|
1360
|
+
raise ValueError(f"--set 键为空: {s!r}")
|
|
1361
|
+
seq = [x.strip() for x in v.split('|')] if '|' in v else [v.strip()]
|
|
1362
|
+
overrides[k] = seq
|
|
1363
|
+
return overrides
|
|
1364
|
+
|
|
1365
|
+
|
|
1366
|
+
def cmd_run(args):
|
|
1367
|
+
overrides = parse_set_args(args.set)
|
|
1368
|
+
runs: List[dict] = []
|
|
1369
|
+
base_seed = (args.seed if args.seed is not None
|
|
1370
|
+
else random.randrange(1, 10 ** 6))
|
|
1371
|
+
# 一条总线贯穿所有轮(记录带 run/seed 区分轮次);订阅者按 CLI 装配
|
|
1372
|
+
bus = DebugLogBus()
|
|
1373
|
+
kinds = None
|
|
1374
|
+
if getattr(args, 'log_kinds', None):
|
|
1375
|
+
kinds = [k.strip() for k in args.log_kinds.split(',') if k.strip()]
|
|
1376
|
+
log_subs = []
|
|
1377
|
+
try:
|
|
1378
|
+
if getattr(args, 'log_jsonl', None):
|
|
1379
|
+
log_subs.append(JsonlLogSubscriber(bus, args.log_jsonl, kinds))
|
|
1380
|
+
print(f"[debug] 📡 实时日志 → {os.path.abspath(args.log_jsonl)}"
|
|
1381
|
+
+ (f"(kind 过滤: {kinds})" if kinds else ""))
|
|
1382
|
+
if getattr(args, 'log_console', False):
|
|
1383
|
+
log_subs.append(ConsoleLogSubscriber(bus, kinds))
|
|
1384
|
+
with DBSandbox(verbose=not args.quiet):
|
|
1385
|
+
for i in range(args.runs):
|
|
1386
|
+
seed = base_seed + i
|
|
1387
|
+
script = load_script(args.script, base_dir=args.base_dir) # 每轮重新编译(干净世界)
|
|
1388
|
+
if args.module:
|
|
1389
|
+
wrap_module_test(script, args.module)
|
|
1390
|
+
runs.append(run_once(script, seed, overrides,
|
|
1391
|
+
args.assign_prob, args.max_steps,
|
|
1392
|
+
args.quiet, flaky=args.flaky,
|
|
1393
|
+
run_index=i + 1, bus=bus))
|
|
1394
|
+
if not args.quiet:
|
|
1395
|
+
print(f"[debug] run {i + 1}/{args.runs} 完成(seed={seed}, "
|
|
1396
|
+
f"{runs[-1]['outcome']})")
|
|
1397
|
+
finally:
|
|
1398
|
+
for s in log_subs:
|
|
1399
|
+
s.close()
|
|
1400
|
+
script_ref = load_script(args.script, base_dir=args.base_dir)
|
|
1401
|
+
if args.module:
|
|
1402
|
+
wrap_module_test(script_ref, args.module)
|
|
1403
|
+
print_report(runs, script_ref, args.module)
|
|
1404
|
+
if args.report:
|
|
1405
|
+
write_json_report(args.report, runs, script_ref, args.module)
|
|
1406
|
+
return cli_exit_code(runs)
|
|
1407
|
+
|
|
1408
|
+
|
|
1409
|
+
def cli_exit_code(runs: List[dict]) -> int:
|
|
1410
|
+
"""CLI 退出码三档。completed 与 max_steps(跑满步数预算未停——可能是
|
|
1411
|
+
无限循环/持续循环型设计)都算「可接受结局」:max_steps 不再当失败
|
|
1412
|
+
(2026-09-12 拍板:持续循环型模块单测跑满预算即停是预期,退出码 0;
|
|
1413
|
+
真死循环在报告里响亮标注,不靠退出码表达)。error/exception/paused
|
|
1414
|
+
照旧:全好 0、部分好 2、全坏 1。"""
|
|
1415
|
+
good = sum(1 for r in runs if r['outcome'] in ('completed', 'max_steps'))
|
|
1416
|
+
return 0 if good == len(runs) else (2 if good else 1)
|
|
1417
|
+
|
|
1418
|
+
|
|
1419
|
+
def cmd_parse(args):
|
|
1420
|
+
with DBSandbox(verbose=False):
|
|
1421
|
+
script = load_script(args.script)
|
|
1422
|
+
print(f"✅ 编译通过: {script.meta.get('name', '')}")
|
|
1423
|
+
print(f" actions: {sorted(script.actions.keys())}")
|
|
1424
|
+
print(f" modules: {sorted(script.modules.keys())}")
|
|
1425
|
+
print(f" actors: {sorted(script.actors.keys())}")
|
|
1426
|
+
print(f" vars: {sorted(script.vars.keys())}")
|
|
1427
|
+
ws = getattr(script, 'warnings', None) or []
|
|
1428
|
+
if ws:
|
|
1429
|
+
print(f" 编译警告 {len(ws)} 条:")
|
|
1430
|
+
for w in ws:
|
|
1431
|
+
print(f" ⚠ {w}")
|
|
1432
|
+
return 0
|
|
1433
|
+
|
|
1434
|
+
|
|
1435
|
+
def cmd_list(args):
|
|
1436
|
+
with DBSandbox(verbose=False):
|
|
1437
|
+
script = load_script(args.script)
|
|
1438
|
+
print(f"剧本: {script.meta.get('name', '')}")
|
|
1439
|
+
mods = script.modules or {}
|
|
1440
|
+
print(f" modules: {sorted(mods) or '(无)'}")
|
|
1441
|
+
for mname, mdef in mods.items():
|
|
1442
|
+
params = ', '.join(mdef.params or []) or '(无参)'
|
|
1443
|
+
locals_ = ', '.join((mdef.locals or {}).keys()) or '(无)'
|
|
1444
|
+
subs = ', '.join((mdef.modules or {}).keys()) or '(无)'
|
|
1445
|
+
print(f" &{mname}({params}) vars: {locals_} 子模块: {subs}")
|
|
1446
|
+
print(f" actions: {sorted(script.actions.keys()) or '(无)'}")
|
|
1447
|
+
return 0
|
|
1448
|
+
|
|
1449
|
+
|
|
1450
|
+
def cmd_coverage(args):
|
|
1451
|
+
return cmd_run(args)
|
|
1452
|
+
|
|
1453
|
+
|
|
1454
|
+
def main(argv=None):
|
|
1455
|
+
ap = argparse.ArgumentParser(
|
|
1456
|
+
prog='femo_debugger',
|
|
1457
|
+
description='Femo 调试模式:零 token 干跑剧本(FakeHost 替 AI/人类发言)')
|
|
1458
|
+
sub = ap.add_subparsers(dest='cmd', required=True)
|
|
1459
|
+
|
|
1460
|
+
p_run = sub.add_parser('run', help='干跑剧本(可 --module 单测模块)')
|
|
1461
|
+
_add_common_args(p_run)
|
|
1462
|
+
p_run.add_argument('--runs', type=int, default=1, help='多轮跑(每轮换种子)')
|
|
1463
|
+
p_run.set_defaults(func=cmd_run)
|
|
1464
|
+
|
|
1465
|
+
p_cov = sub.add_parser('coverage', help='多轮换种子跑,汇总分支覆盖率')
|
|
1466
|
+
_add_common_args(p_cov)
|
|
1467
|
+
p_cov.add_argument('--runs', type=int, default=10)
|
|
1468
|
+
p_cov.set_defaults(func=cmd_coverage)
|
|
1469
|
+
|
|
1470
|
+
p_parse = sub.add_parser('parse', help='仅编译检查(不跑流程)')
|
|
1471
|
+
p_parse.add_argument('script', help='.femo 剧本路径')
|
|
1472
|
+
p_parse.set_defaults(func=cmd_parse)
|
|
1473
|
+
|
|
1474
|
+
p_list = sub.add_parser('list', help='列出剧本的 module / action 清单')
|
|
1475
|
+
p_list.add_argument('script', help='.femo 剧本路径')
|
|
1476
|
+
p_list.set_defaults(func=cmd_list)
|
|
1477
|
+
|
|
1478
|
+
args = ap.parse_args(argv)
|
|
1479
|
+
return args.func(args)
|
|
1480
|
+
|
|
1481
|
+
|
|
1482
|
+
def _add_common_args(p):
|
|
1483
|
+
p.add_argument('script', help='.femo 剧本路径')
|
|
1484
|
+
p.add_argument('--seed', type=int, default=None, help='随机种子(可复现)')
|
|
1485
|
+
p.add_argument('--set', action='append', default=[],
|
|
1486
|
+
help='定向注入变量值 k=v / k=v1|v2(可多次;@actor 可用)')
|
|
1487
|
+
p.add_argument('--module', default=None,
|
|
1488
|
+
help='单独测试某 module([IN]→[OUT],母链变量可见;嵌套模块'
|
|
1489
|
+
'用点路径如 Outer.Inner。持续循环型模块跑满 max_steps '
|
|
1490
|
+
'即停,报告标「可能是无限循环」,退出码 0 非错误)')
|
|
1491
|
+
p.add_argument('--base-dir', default=None,
|
|
1492
|
+
help='覆盖 code: 相对引用(file:"xxx.py")的解析目录;'
|
|
1493
|
+
'缺省=剧本所在目录')
|
|
1494
|
+
p.add_argument('--assign-prob', type=float, default=1.0,
|
|
1495
|
+
help='赋值概率 0~1(默认 1.0 总是赋值;<1 概率沉默,'
|
|
1496
|
+
'模拟 out 是权限不是义务——不赋值走引擎重试/fallback)')
|
|
1497
|
+
p.add_argument('--flaky', type=float, default=0.0,
|
|
1498
|
+
help='概率输出无效赋值 0~1(默认 0;>0 时按概率输出未声明'
|
|
1499
|
+
'变量赋值,触发 assign_error→node_retry 换值重发链路)')
|
|
1500
|
+
p.add_argument('--max-steps', type=int, default=200, help='步数预算(死循环保险)')
|
|
1501
|
+
p.add_argument('--report', default=None, help='JSON 报告输出路径')
|
|
1502
|
+
p.add_argument('--quiet', action='store_true', help='抑制引擎 print 日志')
|
|
1503
|
+
p.add_argument('--log-jsonl', default=None,
|
|
1504
|
+
help='实时调试日志 JSONL 输出路径(每条落盘即 flush,'
|
|
1505
|
+
'可 tail -f,或由宿主/前端转发)')
|
|
1506
|
+
p.add_argument('--log-kinds', default=None,
|
|
1507
|
+
help='逗号分隔的 kind 过滤(配合 --log-jsonl/--log-console),'
|
|
1508
|
+
'如: assign,node_start,retry')
|
|
1509
|
+
p.add_argument('--log-console', action='store_true',
|
|
1510
|
+
help='实时在控制台打印结构化日志流水(不受 --quiet 影响)')
|
|
1511
|
+
|
|
1512
|
+
|
|
1513
|
+
if __name__ == '__main__':
|
|
1514
|
+
_force_utf8_stdio()
|
|
1515
|
+
sys.exit(main())
|