femo-plugin 1.0.1 → 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.
Files changed (217) hide show
  1. package/FEMO_logo.svg +55 -0
  2. package/FEMO_logo_slogan.svg +29 -0
  3. package/_tmp/fallback/driver2.py +176 -0
  4. package/_tmp/fallback/events.jsonl +108 -0
  5. package/_tmp/fallback/gateway_ui.py +325 -0
  6. package/_tmp/fallback/outbox/j1553_human_[/347/234/213/347/211/214]_1.done +1 -0
  7. package/_tmp/fallback/outbox/r1.done +1 -0
  8. package/_tmp/fallback/outbox/r2.done +1 -0
  9. package/_tmp/fallback/outbox/r3.done +1 -0
  10. package/_tmp/fallback/outbox/r4.done +1 -0
  11. package/_tmp/fallback/outbox/r5.done +1 -0
  12. 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
  13. package/hostAdapter/dshAdapter/client/client-ui/composer.tsx +112 -9
  14. package/hostAdapter/dshAdapter/client/client-ui/styles.ts +17 -0
  15. package/hostAdapter/dshAdapter/client/fa-icons.tsx +3 -0
  16. package/hostAdapter/dshAdapter/host/engine-events.ts +4 -1
  17. package/hostAdapter/dshAdapter/host/index.ts +5 -0
  18. package/hostAdapter/dshAdapter/host/preset-install.ts +59 -0
  19. package/hostAdapter/dshAdapter/host/projection-input.ts +14 -6
  20. package/hostAdapter/dshAdapter/lib/client.js +124 -5
  21. package/hostAdapter/dshAdapter/lib/client.js.map +3 -3
  22. package/hostAdapter/dshAdapter/lib/index.js +58 -18
  23. package/hostAdapter/dshAdapter/lib/index.js.map +4 -4
  24. package/hostAdapter/dshAdapter/package.json +1 -5
  25. package/hostAdapter/dshAdapter/preset/agent.cordis.yml +220 -0
  26. package/hostAdapter/dshAdapter/preset/preset.yml +3 -0
  27. package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/gateway.port +1 -0
  28. package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-a-_40_52a9_624b.jsonl +3 -0
  29. package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-a-_40_6211.jsonl +10 -0
  30. package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-god.jsonl +11 -0
  31. package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-stage.jsonl +11 -0
  32. package/hostAdapter/zcodeAdapter/.zcode-plugin/plugin.json +23 -0
  33. package/hostAdapter/zcodeAdapter/README.md +61 -0
  34. package/hostAdapter/zcodeAdapter/commands/femo.md +9 -0
  35. package/hostAdapter/zcodeAdapter/femo-zcode-dist/.zcode-plugin/plugin.json +23 -0
  36. package/hostAdapter/zcodeAdapter/femo-zcode-dist/LICENSE +201 -0
  37. package/hostAdapter/zcodeAdapter/femo-zcode-dist/README.md +635 -0
  38. package/hostAdapter/zcodeAdapter/femo-zcode-dist/commands/femo.md +9 -0
  39. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/__init__.py +4 -0
  40. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/chronica.py +156 -0
  41. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/femo-chat.mjs +69 -0
  42. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/femo_debugger.py +1515 -0
  43. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femo_api.py +437 -0
  44. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femo_gen_api.jsx +77 -0
  45. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/ContextExample.py +555 -0
  46. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/MemoryExample.py +163 -0
  47. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/__init__.py +1 -0
  48. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/getDir/get_dir.py +56 -0
  49. 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
  50. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/llmBridge.py +247 -0
  51. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/llmProviders.py +308 -0
  52. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_CLIrenderer.py +198 -0
  53. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_config.py +35 -0
  54. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_errors.py +278 -0
  55. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_interpreter.py +163 -0
  56. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_normalizer.py +396 -0
  57. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_parser.py +2468 -0
  58. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_runtime.py +3630 -0
  59. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_scope_resolver.py +209 -0
  60. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/__init__.py +1 -0
  61. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/actor_resolver.py +86 -0
  62. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/block_collector.py +441 -0
  63. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/db_utils.py +485 -0
  64. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/femoAsync.py +401 -0
  65. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/host_manifest.py +68 -0
  66. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/job_manager.py +767 -0
  67. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/protocol.py +126 -0
  68. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/save_dialog.py +402 -0
  69. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/task_world.py +544 -0
  70. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/__init__.py +19 -0
  71. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/checkpoint.py +113 -0
  72. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/env.py +686 -0
  73. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/evaluator.py +567 -0
  74. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/join.py +303 -0
  75. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/merge.py +157 -0
  76. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/model.py +245 -0
  77. 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
  78. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +42 -0
  79. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +10 -0
  80. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/LuxFiat/luxfiat.femo +38 -0
  81. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/LuxFiat/wait.py +29 -0
  82. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +222 -0
  83. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/discussion.femo +70 -0
  84. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/goal-mode.femo +23 -0
  85. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//345/270/270/347/224/250/345/267/245/345/205/267python/wait.py +29 -0
  86. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils.py +205 -0
  87. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +324 -0
  88. 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
  89. 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
  90. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +683 -0
  91. 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
  92. 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
  93. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/after-tool.mjs +3 -0
  94. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/hooks.json +16 -0
  95. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/lib.mjs +59 -0
  96. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/prompt-state.mjs +3 -0
  97. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/session-start.mjs +3 -0
  98. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/stop-intent.mjs +3 -0
  99. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hostAdapter/dshAdapter/python/dev-bridge-test.py +43 -0
  100. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hostAdapter/dshAdapter/python/femo_bridge.py +533 -0
  101. package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/bridge-manager.mjs +192 -0
  102. package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/event-router.mjs +258 -0
  103. package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/femo-server.mjs +429 -0
  104. package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/gateway.mjs +163 -0
  105. package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/projection-writer.mjs +294 -0
  106. package/hostAdapter/zcodeAdapter/femo-zcode-dist/skills/femo/SKILL.md +93 -0
  107. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/bridge-smoke.mjs +26 -0
  108. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/event-router.test.mjs +157 -0
  109. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/gateway-smoke.mjs +107 -0
  110. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/integration-human.mjs +111 -0
  111. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/main-actor.mjs +107 -0
  112. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/mcp-smoke.mjs +130 -0
  113. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/projection-writer.test.mjs +144 -0
  114. package/hostAdapter/zcodeAdapter/femo-zcode-dist/zcode.host.manifest.json +5 -0
  115. 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
  116. package/hostAdapter/zcodeAdapter/femo-zcode-dist//350/257/255/346/263/225/346/226/207/346/241/243.md +1136 -0
  117. package/hostAdapter/zcodeAdapter/hooks/after-tool.mjs +3 -0
  118. package/hostAdapter/zcodeAdapter/hooks/hooks.json +16 -0
  119. package/hostAdapter/zcodeAdapter/hooks/lib.mjs +59 -0
  120. package/hostAdapter/zcodeAdapter/hooks/prompt-state.mjs +3 -0
  121. package/hostAdapter/zcodeAdapter/hooks/session-start.mjs +3 -0
  122. package/hostAdapter/zcodeAdapter/hooks/stop-intent.mjs +3 -0
  123. package/hostAdapter/zcodeAdapter/mcp/bridge-manager.mjs +192 -0
  124. package/hostAdapter/zcodeAdapter/mcp/event-router.mjs +258 -0
  125. package/hostAdapter/zcodeAdapter/mcp/femo-server.mjs +429 -0
  126. package/hostAdapter/zcodeAdapter/mcp/gateway.mjs +163 -0
  127. package/hostAdapter/zcodeAdapter/mcp/projection-writer.mjs +294 -0
  128. package/hostAdapter/zcodeAdapter/skills/femo/SKILL.md +93 -0
  129. package/hostAdapter/zcodeAdapter/tests/bridge-smoke.mjs +26 -0
  130. package/hostAdapter/zcodeAdapter/tests/event-router.test.mjs +157 -0
  131. package/hostAdapter/zcodeAdapter/tests/gateway-smoke.mjs +107 -0
  132. package/hostAdapter/zcodeAdapter/tests/integration-human.mjs +111 -0
  133. package/hostAdapter/zcodeAdapter/tests/main-actor.mjs +107 -0
  134. package/hostAdapter/zcodeAdapter/tests/mcp-smoke.mjs +130 -0
  135. package/hostAdapter/zcodeAdapter/tests/projection-writer.test.mjs +144 -0
  136. package/hostAdapter/zcodeAdapter/zcode.host.manifest.json +5 -0
  137. 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
  138. package/package.json +1 -1
  139. package/scripts/diag-find-redblue.mjs +38 -0
  140. package/scripts/diag-god-log.mjs +31 -0
  141. package/scripts/diag-god-log2.mjs +39 -0
  142. package/scripts/diag-god-log3.mjs +35 -0
  143. package/scripts/diag-god-log4.mjs +59 -0
  144. package/scripts/diag-god-log4b.mjs +39 -0
  145. package/scripts/diag-redblue-god.mjs +39 -0
  146. package/scripts/diag-redblue-log.mjs +37 -0
  147. package/scripts/diag-redblue-span.mjs +41 -0
  148. package/scripts/diag-stage-1017.mjs +63 -0
  149. package/scripts/dump_session.py +36 -0
  150. package/scripts/link-workspace.ps1 +51 -0
  151. package/scripts/list_souls.py +18 -0
  152. package/scripts/probe-composer-refresh.mjs +197 -0
  153. package/scripts/seed_story_souls.py +86 -0
  154. package/scripts/sync-zcode-dist.ps1 +55 -0
  155. package/scripts/theme-tokenize/color-extract.txt +288 -0
  156. package/scripts/theme-tokenize/round1-quoted.ps1 +149 -0
  157. package/scripts/theme-tokenize/round2-bare.ps1 +138 -0
  158. package/scripts/theme-tokenize/round3-shape.ps1 +110 -0
  159. package/tests/_diag_r4_join.femo +32 -0
  160. package/tests/conftest.py +95 -0
  161. package/tests/diag-subagent-dir-3081.mjs +101 -0
  162. package/tests/femoGenerator.test.mjs +3909 -0
  163. package/tests/femoParser.test.mjs +4813 -0
  164. package/tests/femogen_notice.test.mjs +109 -0
  165. package/tests/femoparser_validation.test.mjs +84 -0
  166. package/tests/main-delivery-queue.test.mjs +329 -0
  167. package/tests/pre-step-gate.test.mjs +282 -0
  168. package/tests/read-subagent-model.mjs +24 -0
  169. package/tests/run-script-tests.py +97 -0
  170. package/tests/safe-steer.test.mjs +59 -0
  171. package/tests/strip_comments.test.mjs +164 -0
  172. package/tests/test_actor_failed.py +92 -0
  173. package/tests/test_compile_warnings.py +99 -0
  174. package/tests/test_debug_log_bus.py +108 -0
  175. package/tests/test_debugger_module_mode.py +141 -0
  176. package/tests/test_error_buckets.py +117 -0
  177. package/tests/test_error_dispatcher.py +261 -0
  178. package/tests/test_exec_ai_retry.py +155 -0
  179. package/tests/test_exec_human_retry.py +159 -0
  180. package/tests/test_file_resolve.py +104 -0
  181. package/tests/test_flow_events.py +311 -0
  182. package/tests/test_flow_ref_validation.py +92 -0
  183. package/tests/test_func_dict_fallback.py +39 -0
  184. package/tests/test_job_lifecycle.py +236 -0
  185. package/tests/test_job_manager.py +424 -0
  186. package/tests/test_mind.py +99 -0
  187. package/tests/test_module_call_args.py +258 -0
  188. package/tests/test_module_visibility.py +238 -0
  189. package/tests/test_notice.py +143 -0
  190. package/tests/test_out_whitelist.py +83 -0
  191. package/tests/test_par_if_dispatch.py +64 -0
  192. package/tests/test_par_nested_for.py +78 -0
  193. package/tests/test_parser.py +494 -0
  194. package/tests/test_pause.py +102 -0
  195. package/tests/test_pause_contract.py +135 -0
  196. package/tests/test_protocol_transcript.py +158 -0
  197. package/tests/test_scope_self.py +202 -0
  198. package/tests/test_source_validate.py +113 -0
  199. package/tests/test_task_world.py +447 -0
  200. package/tests/test_town_structure.py +70 -0
  201. package/tests/test_v2_checkpoint.py +115 -0
  202. package/tests/test_v2_env.py +383 -0
  203. package/tests/test_v2_evaluator.py +227 -0
  204. package/tests/test_v2_join.py +315 -0
  205. package/tests/test_v2_join_wiring.py +429 -0
  206. package/tests/test_v2_merge.py +167 -0
  207. package/tests/test_v2_model.py +143 -0
  208. package/tests/test_v2_resume_e2e.py +472 -0
  209. package/tests/test_var_decls.py +271 -0
  210. package/tests/verify-model-functions.mjs +90 -0
  211. package/tests/verify-subagent-model-3081.mjs +153 -0
  212. 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
  213. 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
  214. 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
  215. 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
  216. 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
  217. 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,282 @@
1
+ // pre-step 门卫回归测试(2026-09-11)——真 AgentLoop + 脚本化假模型驱动,
2
+ // 零 token、零宿主。复现并锁死「剧本运行中于主窗口说话,主模型只调得动一轮
3
+ // 工具」的根因(门卫按「步」裁决:轮首步放行后,工具续跑所在的后继步被
4
+ // reject → 整个 turn 以 blocked 收场)。
5
+ // 运行:node tests/pre-step-gate.test.mjs(在 femo-plugin 根目录)
6
+ //
7
+ // 口径来源:dsh-agent-loop 自家 tests/interception.spec.ts 断言工具续跑步的
8
+ // claim 批次为空(`[{turn:1,step:1,messages:1},{turn:1,step:2,messages:0}]`),
9
+ // 且 `if (decision.kind === 'reject') { turnEnds = {kind:'blocked'}; return false }`
10
+ // = 整轮结束。本文件用同一套挂载方式(LlmRuntime/SessionStore/SystemPrompt/
11
+ // ToolRuntime/AgentRegistry/AgentLoop)在真循环上验证门卫。
12
+ import { build } from 'esbuild'
13
+ import { mkdtempSync, rmSync } from 'node:fs'
14
+ import { tmpdir } from 'node:os'
15
+ import { join } from 'node:path'
16
+ import { pathToFileURL } from 'node:url'
17
+
18
+ import { Context } from '@deepseek-ai/cordis'
19
+ import LlmRuntime, { CallId, LlmAdapter, createUserMessage } from '@deepseek-ai/dsh-llm'
20
+ import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
21
+ import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
22
+ import ToolRuntime, { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
23
+ import AgentRegistry from '@deepseek-ai/dsh-agent'
24
+ import AgentLoop from '@deepseek-ai/dsh-agent-loop'
25
+
26
+ let pass = 0
27
+ let fail = 0
28
+ const ok = (name, cond, detail = '') => {
29
+ if (cond) {
30
+ console.log(`✅ PASS ${name}`)
31
+ pass++
32
+ } else {
33
+ console.log(`❌ FAIL ${name}${detail ? ': ' + detail : ''}`)
34
+ fail++
35
+ }
36
+ }
37
+
38
+ // ── 源码同步:esbuild 打包 src/pre-step-gate.ts(零依赖纯函数,同 safe-steer.test 写法)──
39
+ const dir = mkdtempSync(join(tmpdir(), 'femo-pre-step-gate-'))
40
+ const outfile = join(dir, 'pre-step-gate.mjs')
41
+ await build({
42
+ entryPoints: ['hostAdapter/dshAdapter/host/pre-step-gate.ts'],
43
+ bundle: true, format: 'esm', platform: 'node', outfile, logLevel: 'error',
44
+ })
45
+ const { gatePreStep } = await import(pathToFileURL(outfile).href)
46
+
47
+ // ── 假模型:脚本化响应(自 dsh-agent-loop tests/mock-adapter.ts 移植)───────
48
+ function textResponse(text) {
49
+ return [
50
+ { type: 'block-start', index: 0, blockType: 'text' },
51
+ ...Array.from(text, (char) => ({ type: 'text-delta', index: 0, text: char })),
52
+ { type: 'block-end', index: 0, block: { type: 'text', text } },
53
+ { type: 'usage', usage: { inputTokens: 10, outputTokens: text.length } },
54
+ { type: 'finish', reason: { kind: 'stop' } },
55
+ ]
56
+ }
57
+ function toolCallResponse(rawCallId, name, args) {
58
+ const callId = CallId(rawCallId)
59
+ const argumentsJson = JSON.stringify(args)
60
+ return [
61
+ { type: 'block-start', index: 0, blockType: 'tool-call' },
62
+ { type: 'tool-call-delta', index: 0, id: callId, name, argumentsDelta: argumentsJson.slice(0, 5) },
63
+ { type: 'tool-call-delta', index: 0, id: callId, name, argumentsDelta: argumentsJson.slice(5) },
64
+ { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name, arguments: argumentsJson } },
65
+ { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
66
+ { type: 'finish', reason: { kind: 'tool-calls' } },
67
+ ]
68
+ }
69
+ class ScriptAdapter extends LlmAdapter {
70
+ requests = []
71
+ #script
72
+ constructor(script) { super(); this.#script = script }
73
+ resolveModel(provider, model) {
74
+ return Promise.resolve({ provider, id: model, name: model })
75
+ }
76
+ async *stream(options) {
77
+ this.requests.push(options)
78
+ const entry = this.#script.shift()
79
+ if (entry === undefined) throw new Error('ScriptAdapter: script exhausted')
80
+ for (const chunk of entry) yield chunk
81
+ }
82
+ }
83
+
84
+ // ── 挂载真循环(与 dsh-agent-loop 自家 spec 同款顺序)──────────────────────
85
+ async function harness(script) {
86
+ const adapter = new ScriptAdapter(script)
87
+ const ctx = new Context()
88
+ await ctx.plugin(LlmRuntime)
89
+ await ctx.plugin(SessionStore)
90
+ await ctx.plugin(SystemPrompt)
91
+ await ctx.plugin(ToolRuntime)
92
+ await ctx.plugin(AgentRegistry)
93
+ await ctx.plugin(AgentLoop, { agents: [] })
94
+ ctx.llm.registerAdapter(['mock'], adapter)
95
+ return { ctx, adapter }
96
+ }
97
+
98
+ /** echo 工具:把入参原样回成结果(工具续跑的产生源);onExecute 供用例在
99
+ * 工具执行期(=step1 与 step2 之间)向主会话投消息。 */
100
+ function registerEcho(ctx, onExecute) {
101
+ ctx.tools.register(defineContentToolFixture({
102
+ name: 'echo',
103
+ description: 'echo',
104
+ parameters: { text: { type: 'string', required: true } },
105
+ async execute({ text }) {
106
+ onExecute?.()
107
+ return [{ type: 'text', text: `echo:${text}` }]
108
+ },
109
+ }))
110
+ }
111
+
112
+ /** 门卫接线:与 dshAdapter/host/engine-events.ts 的 pre-step 钩子同构(真 gatePreStep +
113
+ * 两个事实源用可变对象模拟)。 */
114
+ function installGate(ctx, facts) {
115
+ ctx.on('agent/pre-step', async ({ messages, step }, next) => {
116
+ const decision = await next()
117
+ if (decision === undefined) return decision
118
+ if (decision.kind !== 'enter') return decision
119
+ return gatePreStep({ messages: decision.messages, step, tag: 'test-session', ...facts })
120
+ })
121
+ }
122
+
123
+ /** 旧口径(2026-09-05 f0fde2f ~ 2026-09-11):按「步」判定——仅当本步批次里
124
+ * 有真实用户输入才放行。用于在本测试内复现 bug,证明用例对根因敏感。 */
125
+ function installLegacyGate(ctx, facts) {
126
+ ctx.on('agent/pre-step', async ({ messages }, next) => {
127
+ const decision = await next()
128
+ if (decision === undefined) return decision
129
+ if (decision.kind !== 'enter') return decision
130
+ const admitted = decision.messages.filter((m) => !(m.source?.kind === 'subagent-settled'
131
+ && typeof m.source?.senderSessionId === 'string' && m.source.senderSessionId.startsWith('femo-actor-')))
132
+ if (admitted.length !== decision.messages.length && admitted.length === 0) return { kind: 'reject' }
133
+ if (facts.mainAnswerPending) return { ...decision, messages: admitted }
134
+ if (!facts.running) return { ...decision, messages: admitted }
135
+ if (admitted.some((m) => m.source.kind === 'user')) return { ...decision, messages: admitted }
136
+ return { kind: 'reject' }
137
+ })
138
+ }
139
+
140
+ const user = (text) => createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } })
141
+ const plugin = (text) => createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'plugin', plugin: 'femo-plugin' } })
142
+ const actorNoise = (text) => createUserMessage({
143
+ content: [{ type: 'text', text }],
144
+ source: { kind: 'subagent-settled', senderSessionId: 'femo-actor-j775-x' },
145
+ })
146
+ const reasonsOf = (agent) => agent.session.events
147
+ .filter((e) => e.type === 'turn/end')
148
+ .map((e) => e.data.reason.kind)
149
+ const userTexts = (agent) => agent.session.events
150
+ .filter((e) => e.type === 'user/message')
151
+ .map((e) => e.data.content.map((b) => (b.type === 'text' ? b.text : '')).join(''))
152
+ const assistantCount = (agent) => agent.session.events.filter((e) => e.type === 'assistant/message').length
153
+
154
+ async function runGateCase(name, { running, script, send, expect }) {
155
+ const { ctx, adapter } = await harness(script)
156
+ const agent = ctx.agentLoop.create(SessionId(name), { provider: 'mock', model: 'mock' })
157
+ registerEcho(ctx, expect.onExecute ? () => expect.onExecute(agent) : undefined)
158
+ installGate(ctx, { mainAnswerPending: false, running })
159
+ send(agent)
160
+ await agent.whenIdle()
161
+ const facts = {
162
+ requests: adapter.requests.length,
163
+ reasons: reasonsOf(agent),
164
+ userTexts: userTexts(agent),
165
+ assistant: assistantCount(agent),
166
+ }
167
+ expect.check(ok, facts)
168
+ await ctx.dispose?.()
169
+ return facts
170
+ }
171
+
172
+ // ═══ 1. 根因复现:旧口径按「步」裁决 → 运行中主窗口说话只调得动一轮工具 ═══
173
+ {
174
+ const { ctx, adapter } = await harness([toolCallResponse('c1', 'echo', { text: 'hi' }), textResponse('done')])
175
+ const agent = ctx.agentLoop.create(SessionId('legacy-root-cause'), { provider: 'mock', model: 'mock' })
176
+ registerEcho(ctx)
177
+ installLegacyGate(ctx, { mainAnswerPending: false, running: true })
178
+ agent.followup(user('顺便帮我查个东西'))
179
+ await agent.whenIdle()
180
+ ok('legacy: 根因复现——工具只跑一轮、整轮 blocked', adapter.requests.length === 1 && reasonsOf(agent).join() === 'blocked',
181
+ `requests=${adapter.requests.length} reasons=${reasonsOf(agent).join()}`)
182
+ }
183
+
184
+ // ═══ 2. 运行中:User 找主模型说话 → 完整一轮(工具续跑步不被砍)═══════════
185
+ await runGateCase('running-user-multistep', {
186
+ running: true,
187
+ script: [toolCallResponse('c1', 'echo', { text: 'hi' }), textResponse('done')],
188
+ send: (agent) => agent.followup(user('顺便帮我查个东西')),
189
+ expect: {
190
+ check: (ok, f) => {
191
+ ok('running+user: 模型被调用两次(工具续跑拿到模型请求)', f.requests === 2, `requests=${f.requests}`)
192
+ ok('running+user: turn 以 completed 收场(不再 blocked)', f.reasons.join() === 'completed', `reasons=${f.reasons.join()}`)
193
+ ok('running+user: 用户消息落盘可见', f.userTexts.includes('顺便帮我查个东西'), JSON.stringify(f.userTexts))
194
+ ok('running+user: 两段模型回答都落盘', f.assistant === 2, `assistant=${f.assistant}`)
195
+ },
196
+ },
197
+ })
198
+
199
+ // ═══ 3. 运行中:轮中插话(落在续跑步的 user 消息)被主模型看到 ═══
200
+ await runGateCase('running-midturn-interjection', {
201
+ running: true,
202
+ script: [toolCallResponse('c1', 'echo', { text: 'hi' }), textResponse('done')],
203
+ send: (agent) => agent.followup(user('开场问题')),
204
+ expect: {
205
+ onExecute: (agent) => agent.steer(user('插入一句:先看 A 文件')),
206
+ check: (ok, f) => {
207
+ ok('running+插话: 整轮跑完(completed)', f.reasons.join() === 'completed', `reasons=${f.reasons.join()}`)
208
+ ok('running+插话: 插话进了对话流', f.userTexts.includes('插入一句:先看 A 文件'), JSON.stringify(f.userTexts))
209
+ ok('running+插话: 续跑步照常请求模型', f.requests === 2, `requests=${f.requests}`)
210
+ },
211
+ },
212
+ })
213
+
214
+ // ═══ 4. 运行中:演员噪音落在续跑步 → 不再把整轮改判 blocked ═══
215
+ await runGateCase('running-noise-on-continuation', {
216
+ running: true,
217
+ script: [toolCallResponse('c1', 'echo', { text: 'hi' }), textResponse('done')],
218
+ send: (agent) => agent.followup(user('开场问题')),
219
+ expect: {
220
+ onExecute: (agent) => agent.inject(actorNoise('Background subagent femo-actor… finished')),
221
+ check: (ok, f) => {
222
+ ok('running+噪音: 噪音不落盘、整轮 completed', f.reasons.join() === 'completed' && !f.userTexts.some((t) => t.includes('Background subagent')),
223
+ `reasons=${f.reasons.join()} users=${JSON.stringify(f.userTexts)}`)
224
+ ok('running+噪音: 工具续跑照常请求模型', f.requests === 2, `requests=${f.requests}`)
225
+ },
226
+ },
227
+ })
228
+
229
+ // ═══ 5. 运行中:轮首步的 plugin 注入仍被拦(引擎拥有会话的安全网保留)═══════
230
+ await runGateCase('running-plugin-turnstart-rejected', {
231
+ running: true,
232
+ script: [textResponse('不应发生')],
233
+ send: (agent) => agent.followup(plugin('引擎内部通告')),
234
+ expect: {
235
+ check: (ok, f) => {
236
+ ok('running+plugin: 模型零请求(不唤醒)', f.requests === 0, `requests=${f.requests}`)
237
+ ok('running+plugin: turn 以 blocked 收场', f.reasons.join() === 'blocked', `reasons=${f.reasons.join()}`)
238
+ ok('running+plugin: 注入不落盘', f.userTexts.length === 0, JSON.stringify(f.userTexts))
239
+ },
240
+ },
241
+ })
242
+
243
+ // ═══ 6. 空闲:原生多步照旧(对照组,门卫不得改坏原生路径)═══════════════
244
+ await runGateCase('idle-user-multistep', {
245
+ running: false,
246
+ script: [toolCallResponse('c1', 'echo', { text: 'hi' }), textResponse('done')],
247
+ send: (agent) => agent.followup(user('查一下')),
248
+ expect: {
249
+ check: (ok, f) => {
250
+ ok('idle+user: 模型被调用两次', f.requests === 2, `requests=${f.requests}`)
251
+ ok('idle+user: turn completed', f.reasons.join() === 'completed', `reasons=${f.reasons.join()}`)
252
+ },
253
+ },
254
+ })
255
+
256
+ // ═══ 7. 纯函数裁决面(不依赖循环)═══════════════════════════════════════
257
+ {
258
+ const g = (facts) => gatePreStep({ mainAnswerPending: false, running: true, tag: 't', ...facts })
259
+ ok('gate: step>1 空批次放行', g({ messages: [], step: 2 }).kind === 'enter')
260
+ ok('gate: step>1 只滤噪音后放行', (() => {
261
+ const d = g({ messages: [actorNoise('x')], step: 2 })
262
+ return d.kind === 'enter' && d.messages.length === 0
263
+ })())
264
+ ok('gate: step1 运行中 plugin 注入 reject', g({ messages: [plugin('x')], step: 1 }).kind === 'reject')
265
+ ok('gate: step1 运行中 user 消息放行', g({ messages: [user('x')], step: 1 }).kind === 'enter')
266
+ ok('gate: step1 user+噪音 只放行 user', (() => {
267
+ const d = g({ messages: [actorNoise('n'), user('x')], step: 1 })
268
+ return d.kind === 'enter' && d.messages.length === 1 && d.messages[0].source.kind === 'user'
269
+ })())
270
+ ok('gate: step1 整批噪音 reject', g({ messages: [actorNoise('n')], step: 1 }).kind === 'reject')
271
+ ok('gate: 运行中 step1 空批次(纯上下文)reject', g({ messages: [], step: 1 }).kind === 'reject')
272
+ ok('gate: 未跑放行(原生聊天)', gatePreStep({
273
+ messages: [plugin('x')], step: 1, mainAnswerPending: false, running: false, tag: 't',
274
+ }).kind === 'enter')
275
+ ok('gate: main 在飞整轮放行(含 step1 plugin 注入)', gatePreStep({
276
+ messages: [plugin('x')], step: 1, mainAnswerPending: true, running: true, tag: 't',
277
+ }).kind === 'enter')
278
+ }
279
+
280
+ rmSync(dir, { recursive: true, force: true })
281
+ console.log(`\n${fail === 0 ? '✅' : '❌'} pre-step-gate: ${pass} passed, ${fail} failed`)
282
+ process.exit(fail === 0 ? 0 : 1)
@@ -0,0 +1,24 @@
1
+ // 解析 3081 子代理会话的 request/header 模型(验证脚本配套)
2
+ import fs from 'node:fs';
3
+ import zlib from 'node:zlib';
4
+
5
+ const ROOT = 'D:/myFiles/dsh/dsh-home/sessions/--D-myFiles-dsh-dsh-meow--';
6
+ const ids = process.argv.slice(2);
7
+ for (const id of ids) {
8
+ const p = `${ROOT}/${id}/session.jsonl.zstd`;
9
+ if (!fs.existsSync(p)) { console.log(id, 'NOT FOUND'); continue; }
10
+ const t = zlib.zstdDecompressSync(fs.readFileSync(p)).toString('utf8');
11
+ const ms = [...t.matchAll(/"type":"request\/header"[\s\S]*?"config":\s*\{([\s\S]*?)\}/g)];
12
+ console.log(id, 'header count:', ms.length);
13
+ for (const m of ms) {
14
+ const cfg = m[1];
15
+ const prov = cfg.match(/"provider":"([^"]+)"/)?.[1];
16
+ const model = cfg.match(/"model":"([^"]+)"/)?.[1];
17
+ const eff = cfg.match(/"reasoningEffort":"([^"]+)"/)?.[1];
18
+ console.log(' config:', JSON.stringify({ provider: prov, model, reasoningEffort: eff }));
19
+ }
20
+ if (ms.length === 0) {
21
+ const all = [...t.matchAll(/"model":"([^"]+)"/g)].map(x => x[1]);
22
+ console.log(' any model refs:', JSON.stringify([...new Set(all)].slice(0, 8)));
23
+ }
24
+ }
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env python3
2
+ """剧本语法测试 runner:依次跑三个测试剧本,断言事件流与变量结果。
3
+
4
+ 用法:python tests/run-script-tests.py
5
+ (零 LLM 调用——全部 @assign 逻辑,不烧 token)
6
+ """
7
+ import subprocess
8
+ import sys
9
+ import json
10
+ import time
11
+ import os
12
+ import threading
13
+
14
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
15
+
16
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17
+ BRIDGE = os.path.join(ROOT, "hostAdapter", "dshAdapter", "python", "femo_bridge.py")
18
+
19
+ SCRIPTS = [
20
+ ("test-if-fork-join.femo", "if 条件分支 + fork + join(all)"),
21
+ ("test-for-if.femo", "for 顺序循环 + if"),
22
+ ("test-par.femo", "par 并发循环"),
23
+ ]
24
+
25
+ def run_script(femo_path):
26
+ """跑一个剧本并收集事件。必须实时读取 stdout——桥的 stdout 是管道,
27
+ 引擎 print 洪流 + 事件会在 64KB 缓冲区写满后阻塞 write(不读就卡死)。"""
28
+ p = subprocess.Popen(
29
+ [sys.executable, BRIDGE, "--fe4m", ROOT],
30
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
31
+ text=True, encoding="utf-8", errors="replace", bufsize=1,
32
+ )
33
+ events = []
34
+ done = threading.Event()
35
+
36
+ def drain():
37
+ try:
38
+ for line in p.stdout:
39
+ line = line.strip()
40
+ if not line:
41
+ continue
42
+ try:
43
+ obj = json.loads(line)
44
+ except json.JSONDecodeError:
45
+ continue
46
+ if obj.get("type") == "event":
47
+ events.append(obj)
48
+ finally:
49
+ done.set()
50
+
51
+ t = threading.Thread(target=drain, daemon=True)
52
+ t.start()
53
+
54
+ def send(obj):
55
+ p.stdin.write(json.dumps(obj) + "\n")
56
+ p.stdin.flush()
57
+ femo = open(femo_path, encoding="utf-8").read()
58
+ send({"id": 1, "cmd": "run", "args": {"femo": femo, "base_dir": os.path.dirname(femo_path)}})
59
+ # 轮询直到 flow_done / flow_error / bridge_run_ended,或超时
60
+ deadline = time.time() + 30
61
+ while time.time() < deadline:
62
+ if any(e["event"] in ("flow_done", "flow_error", "bridge_run_ended") for e in events):
63
+ break
64
+ time.sleep(0.1)
65
+ send({"id": 2, "cmd": "shutdown", "args": {}})
66
+ time.sleep(0.5)
67
+ p.stdin.close()
68
+ try:
69
+ p.wait(timeout=10)
70
+ except subprocess.TimeoutExpired:
71
+ p.kill()
72
+ return events
73
+
74
+ passed = 0
75
+ for fname, desc in SCRIPTS:
76
+ path = os.path.join(ROOT, "femoExamples", fname)
77
+ print(f"\n===== {fname} — {desc} =====")
78
+ events = run_script(path)
79
+ types = [e["event"] for e in events]
80
+ print("事件序列:", " -> ".join(types))
81
+ # 断言:必须 flow_done 且无 flow_error
82
+ if "flow_error" in types:
83
+ err = next((e["data"] for e in events if e["event"] == "flow_error"), {})
84
+ print(f"❌ FAIL: flow_error: {err}")
85
+ continue
86
+ if "flow_done" not in types:
87
+ print(f"❌ FAIL: 未见 flow_done(事件: {types})")
88
+ continue
89
+ # 打印 assign_result 看变量
90
+ for e in events:
91
+ if e["event"] == "assign_result":
92
+ print(f" assign_result[{e['data'].get('node_name')}]: {e['data'].get('output')}")
93
+ print(f"✅ PASS: flow_done")
94
+ passed += 1
95
+
96
+ print(f"\n===== 结果: {passed}/{len(SCRIPTS)} 通过 =====")
97
+ sys.exit(0 if passed == len(SCRIPTS) else 1)
@@ -0,0 +1,59 @@
1
+ // safe-steer 回归测试(2026-09-10,零 token、零宿主):内部用 esbuild 打包 src
2
+ // 保证与源码同步(同 meow-memory 的 tests 写法)。
3
+ // 运行:node tests/safe-steer.test.mjs(在 femo-plugin 根目录)
4
+ import { build } from 'esbuild'
5
+ import { mkdtempSync, rmSync } from 'node:fs'
6
+ import { tmpdir } from 'node:os'
7
+ import { join } from 'node:path'
8
+ import { pathToFileURL } from 'node:url'
9
+
10
+ let pass = 0
11
+ let fail = 0
12
+ const ok = (name, cond, detail = '') => {
13
+ if (cond) {
14
+ console.log(`✅ PASS ${name}`)
15
+ pass++
16
+ } else {
17
+ console.log(`❌ FAIL ${name}${detail ? ': ' + detail : ''}`)
18
+ fail++
19
+ }
20
+ }
21
+
22
+ const dir = mkdtempSync(join(tmpdir(), 'femo-safe-steer-'))
23
+ const outfile = join(dir, 'safe-steer.mjs')
24
+ await build({ entryPoints: ['hostAdapter/dshAdapter/host/safe-steer.ts'], bundle: true, format: 'esm', platform: 'node', outfile, logLevel: 'error' })
25
+ const { safeSteer } = await import(pathToFileURL(outfile).href)
26
+
27
+ // ── 1. 正常路径:投递成功返回 true,消息原样交给 steer ──────────────────────
28
+ const seen = []
29
+ ok('normal: returns true', safeSteer({ steer: (m) => seen.push(m) }, { text: 'hi' }, 't') === true)
30
+ ok('normal: message delivered once', seen.length === 1 && seen[0].text === 'hi')
31
+
32
+ // ── 2. dsh 0.1.5 场景:steer 抛(inbox 投影未激活)→ false 且不往上抛 ───────
33
+ const throwing = {
34
+ steer: () => {
35
+ throw new Error('agent "x" cannot read inbox state: its projection registration is not active')
36
+ },
37
+ }
38
+ let propagated = null
39
+ let result = null
40
+ try {
41
+ result = safeSteer(throwing, { text: 'hi' }, 'throwing-agent')
42
+ } catch (error) {
43
+ propagated = error
44
+ }
45
+ ok('0.1.5 throw: swallowed (no propagation to caller)', propagated === null, String(propagated))
46
+ ok('0.1.5 throw: returns false', result === false)
47
+
48
+ // ── 3. 无 steer 方法 / 非对象 target → false,不炸 ─────────────────────────
49
+ ok('missing steer: returns false', safeSteer({}, { text: 'hi' }, 'no-steer') === false)
50
+ ok('undefined target: returns false', safeSteer(undefined, { text: 'hi' }, 'undefined') === false)
51
+ ok('non-object target: returns false', safeSteer('nope', { text: 'hi' }, 'string') === false)
52
+
53
+ // ── 4. 旧版本兼容:0.1.1 的 steer 永不抛 → 行为与改动前逐字节一致 ──────────
54
+ const legacySeen = []
55
+ ok('legacy (0.1.1) path unchanged', safeSteer({ steer: (m) => legacySeen.push(m) }, { text: 'x' }, 'legacy') === true && legacySeen.length === 1)
56
+
57
+ rmSync(dir, { recursive: true, force: true })
58
+ console.log(`\n${pass} passed, ${fail} failed`)
59
+ process.exit(fail === 0 ? 0 : 1)
@@ -0,0 +1,164 @@
1
+ // 全局注释剥离专项测试:内存版 stripComments / stripLineComments
2
+ import fs from 'node:fs';
3
+ import { stripComments, stripLineComments, parseFEMO, extractHashSketch } from './femoParser.test.mjs';
4
+
5
+ let pass = 0, fail = 0;
6
+ function check(name, actual, expect) {
7
+ if (actual === expect) { console.log(`✅ PASS ${name}`); pass++; }
8
+ else { console.log(`❌ FAIL ${name}:\n 期望: ${JSON.stringify(expect)}\n 实际: ${JSON.stringify(actual)}`); fail++; }
9
+ }
10
+
11
+ // ── 行级剥离 ──
12
+ check('行内 # 注释', stripLineComments('player_choice = "" # 这是注释'), 'player_choice = "" ');
13
+ check('行内 // 注释', stripLineComments('name = "x" // comment'), 'name = "x" ');
14
+ check('整行 # 注释', stripLineComments('# ---------- 1. 元信息 ----------'), '');
15
+ check('整行 // 注释', stripLineComments('// comment line'), '');
16
+ check('引号内 # 保留', stripLineComments('name = "a#b"'), 'name = "a#b"');
17
+ check('引号内 // 保留', stripLineComments('msg = "http://x"'), 'msg = "http://x"');
18
+ check('引号后 # 截断', stripLineComments('name = "a" # tail'), 'name = "a" ');
19
+ check('单引号内 # 保留', stripLineComments("msg = 'a#b'"), "msg = 'a#b'");
20
+ check('魔法注释按普通注释剥离(特性已废弃)', stripLineComments('# for loop -> [ASK] while true'), '');
21
+ check('无注释原样', stripLineComments(' scope: [@a, @b]'), ' scope: [@a, @b]');
22
+ check('保留行首缩进', stripLineComments(' out: x += 1 # 注释'), ' out: x += 1 ');
23
+
24
+ // ── 整篇剥离(prompt 块豁免)──
25
+ const sample = `# 顶层注释
26
+ meta:
27
+ name = "哥布林 # 名字" # 行内注释
28
+ version = 1.0
29
+ system_safety = |
30
+ 禁止 # 血腥。
31
+ 这里 // 也是内容。
32
+ output_style = "a#b"
33
+
34
+ action opening @ai(@guildmaster):
35
+ prompt: |
36
+ 说到 # 话题和 // 斜杠都在。
37
+ http://example.com 保留。
38
+ scope: [@guildmaster, @player] // 尾部注释
39
+ mainflow:
40
+ [START] -> [END]
41
+ `;
42
+ const stripped = stripComments(sample.split('\n'));
43
+ check('顶层注释行清空', stripped[0], '');
44
+ check('行内注释清除但引号内保留', stripped[2], ' name = "哥布林 # 名字" ');
45
+ check('prompt 块内 # 保留', stripped[5], ' 禁止 # 血腥。');
46
+ check('prompt 块内 // 保留', stripped[6], ' 这里 // 也是内容。');
47
+ check('引号内 # 保留(meta)', stripped[7], ' output_style = "a#b"');
48
+ check('prompt 多行 # 保留', stripped[11], ' 说到 # 话题和 // 斜杠都在。');
49
+ check('prompt 多行 URL 保留', stripped[12], ' http://example.com 保留。');
50
+ check('scope 行尾 // 清除', stripped[13], ' scope: [@guildmaster, @player] ');
51
+ check('flow 行原样', stripped[15], ' [START] -> [END]');
52
+
53
+ // ── 完整解析验证(剥离后能正常编译)──
54
+ const script = `# 带注释的完整剧本
55
+ meta:
56
+ name = "test # comments"
57
+ session = new
58
+
59
+ vars:
60
+ @m = "" # 循环变量
61
+ members = [@a, @b]
62
+
63
+ actors:
64
+ ai @a = soul:1
65
+ ai @b = soul:2
66
+
67
+ action mark @assign:
68
+ out: count += 1
69
+
70
+ mainflow:
71
+ # for loop -> [ASK] while true (魔法注释回边)
72
+ [START] -> for @m in members:
73
+ -> [C]:mark ->
74
+ -> [END]
75
+ `;
76
+ try {
77
+ const r = parseFEMO(script);
78
+ check('带注释完整剧本解析', `actors=${r.actors.length} actions=${r.actions.length}`, 'actors=2 actions=1');
79
+ } catch (e) {
80
+ check('带注释完整剧本解析', '抛错: ' + e.message, 'actors=2 actions=1');
81
+ }
82
+
83
+ // ── 原文不可变验证 ──
84
+ const original = '# 注释\nmeta:\n name = "x#y"\n';
85
+ stripComments(original.split('\n'));
86
+ check('原文不被修改', original, '# 注释\nmeta:\n name = "x#y"\n');
87
+
88
+ // ═══ #sketch 注释块还原(编译第零步)═══
89
+
90
+ // 单元:extractHashSketch 还原行为
91
+ const skRaw = [
92
+ 'mainflow:',
93
+ ' [START] -> [A] ->',
94
+ '#sketch:',
95
+ '# [A] = 100, 50',
96
+ '# [B] = 200, 0',
97
+ '',
98
+ ' -> [END]',
99
+ ];
100
+ const skRestored = extractHashSketch(skRaw).join('\n');
101
+ check(
102
+ 'extractHashSketch 还原 #sketch 块',
103
+ skRestored,
104
+ 'mainflow:\n [START] -> [A] ->\nsketch:\n [A] = 100, 50\n [B] = 200, 0\n\n -> [END]'
105
+ );
106
+ check(
107
+ 'extractHashSketch 不动普通行',
108
+ extractHashSketch(['# 普通注释', 'meta:', ' name = "x"']).join('\n'),
109
+ '# 普通注释\nmeta:\n name = "x"'
110
+ );
111
+
112
+ // 集成:顶层 #sketch 注释块 → mainflow.layout
113
+ const skScript = `meta:
114
+ name = "sketch-test"
115
+ mainflow:
116
+ [START] -> [A] -> [END]
117
+ #sketch:
118
+ # [A] = 100, 50
119
+ # [B] = 200, 0
120
+ `;
121
+ {
122
+ const r = parseFEMO(skScript);
123
+ check('顶层 #sketch 块解析出 layout', JSON.stringify(r.mainflow.layout), JSON.stringify({ '[A]': { dx: 100, dy: 50 }, '[B]': { dx: 200, dy: 0 } }));
124
+ }
125
+
126
+ // 集成:模块内 #sketch 注释块(生成端格式:# 在行首 + 原缩进)→ 模块 layout
127
+ const skModule = `meta:
128
+ name = "mod-sketch"
129
+ module 子流程:
130
+ flow:
131
+ [IN] -> [M1] -> [OUT]
132
+ # sketch:
133
+ # [M1] = 30, 40
134
+ mainflow:
135
+ [START] -> &子流程 -> [END]
136
+ `;
137
+ {
138
+ const r = parseFEMO(skModule);
139
+ const mod = r.modules.find((m) => m.name === '子流程');
140
+ check('模块内 #sketch 块解析出 layout', JSON.stringify(mod && mod.layout), JSON.stringify({ '[M1]': { dx: 30, dy: 40 } }));
141
+ }
142
+
143
+ // 集成:块内手写 # 注释(剥一个 # 后残余)被正常去注释,不污染 layout
144
+ const skInnerComment = `meta:
145
+ name = "sketch-comment"
146
+ mainflow:
147
+ [START] -> [A] -> [END]
148
+ #sketch:
149
+ # [A] = 1, 2
150
+ # # 这是块内手写注释
151
+ `;
152
+ {
153
+ const r = parseFEMO(skInnerComment);
154
+ check('块内手写注释不污染 layout', JSON.stringify(r.mainflow.layout), JSON.stringify({ '[A]': { dx: 1, dy: 2 } }));
155
+ }
156
+
157
+ // 集成:无 sketch 时 layout 为空对象
158
+ {
159
+ const r = parseFEMO('meta:\n name = "no-sketch"\nmainflow:\n [START] -> [END]\n');
160
+ check('无 sketch 块时 layout 为空', JSON.stringify(r.mainflow.layout), '{}');
161
+ }
162
+
163
+ console.log(`\n===== 结果: ${pass}/${pass + fail} 通过 =====`);
164
+ process.exit(fail === 0 ? 0 : 1);