@zhushanwen/subagent-core 0.4.0 → 0.5.1

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 (272) hide show
  1. package/dist/{chunk-4KN4TTG7.js → chunk-43ONBFZX.js} +1 -1
  2. package/dist/{chunk-X7SZ5HLQ.js → chunk-V3VHZ2VX.js} +20 -27
  3. package/dist/execution/engine/engines/zcode/constants.cjs +29 -41
  4. package/dist/execution/engine/engines/zcode/constants.d.cts +65 -53
  5. package/dist/execution/engine/engines/zcode/constants.d.ts +65 -53
  6. package/dist/execution/engine/engines/zcode/constants.js +17 -27
  7. package/dist/execution/engine/engines/zcode/reader.d.cts +2 -1
  8. package/dist/execution/engine/engines/zcode/reader.d.ts +2 -1
  9. package/dist/execution/engine/engines/zcode/reader.js +2 -2
  10. package/dist/index.cjs +16418 -14070
  11. package/dist/index.d.cts +5136 -4016
  12. package/dist/index.d.ts +5136 -4016
  13. package/dist/index.js +16343 -14048
  14. package/dist/{types-DpUO16pj.d.cts → types-Dv4QhSJ_.d.cts} +215 -112
  15. package/dist/{types-DpUO16pj.d.ts → types-Dv4QhSJ_.d.ts} +215 -112
  16. package/package.json +3 -3
  17. package/src/__tests__/agent-opts-resolver-schema-prompt.test.ts +0 -1
  18. package/src/__tests__/append-system-prompt-assembly.test.ts +8 -7
  19. package/src/__tests__/fr4-get-state-handshake.test.ts +2 -2
  20. package/src/__tests__/m2-append-content-probe.test.ts +0 -1
  21. package/src/__tests__/manifest-store.test.ts +10 -9
  22. package/src/__tests__/record-store-cache.test.ts +0 -2
  23. package/src/__tests__/record-store-index.test.ts +1 -2
  24. package/src/__tests__/review-fix-loop-script.test.ts +4 -2
  25. package/src/__tests__/review-fix-loop-utils.test.ts +10 -10
  26. package/src/__tests__/robustness-low-batch1.test.ts +6 -5
  27. package/src/__tests__/robustness-medium-batch1.test.ts +2 -2
  28. package/src/__tests__/robustness-medium-batch2.test.ts +17 -6
  29. package/src/__tests__/robustness-medium-batch4.test.ts +2 -2
  30. package/src/__tests__/session-runner.test.ts +1 -1
  31. package/src/core/__tests__/host-services.test.ts +2 -2
  32. package/src/core/__tests__/logger.test.ts +1 -1
  33. package/src/core/error-message.ts +9 -0
  34. package/src/core/host-services.ts +21 -5
  35. package/src/core/notify-ports.ts +18 -5
  36. package/src/execution/__tests__/agent-profile.test.ts +4 -4
  37. package/src/execution/__tests__/agent-registry.test.ts +370 -0
  38. package/src/execution/__tests__/agent-result-mapper.test.ts +18 -2
  39. package/src/execution/__tests__/agents-assembly.test.ts +2 -2
  40. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +6 -6
  41. package/src/execution/__tests__/chat-engine-routing.test.ts +68 -33
  42. package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +4 -4
  43. package/src/execution/__tests__/cold-resurrect.test.ts +283 -0
  44. package/src/execution/__tests__/delivery-methods.test.ts +75 -62
  45. package/src/execution/__tests__/descendant-sweep-guards.test.ts +220 -0
  46. package/src/execution/__tests__/descendant-sweep.test.ts +6 -6
  47. package/src/execution/__tests__/dialog-queue.test.ts +2 -2
  48. package/src/execution/__tests__/engine-model-validation.test.ts +741 -0
  49. package/src/execution/__tests__/epipe-fallback.test.ts +29 -24
  50. package/src/execution/__tests__/execute-and-await-worktree.test.ts +21 -91
  51. package/src/execution/__tests__/execute-nesting.test.ts +34 -188
  52. package/src/execution/__tests__/execution-record.test.ts +217 -60
  53. package/src/execution/__tests__/execution-runtime-face.test.ts +5 -5
  54. package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +3 -3
  55. package/src/execution/__tests__/finalize-record.test.ts +173 -17
  56. package/src/execution/__tests__/gc-timer.test.ts +55 -2
  57. package/src/execution/__tests__/get-record-for-action-restart.test.ts +12 -12
  58. package/src/execution/__tests__/get-state-handshake.test.ts +1 -1
  59. package/src/execution/__tests__/helpers/mock-extension-api.ts +1 -1
  60. package/src/execution/__tests__/helpers/session-runner-mocks.ts +113 -0
  61. package/src/execution/__tests__/helpers/spawn-mock.ts +150 -3
  62. package/src/execution/__tests__/helpers/subagent-service-mocks.ts +137 -0
  63. package/src/execution/__tests__/keep-alive-no-progress.test.ts +50 -148
  64. package/src/execution/__tests__/kill-all-escalation.test.ts +2 -2
  65. package/src/execution/__tests__/lifecycle-predicates.test.ts +1 -2
  66. package/src/execution/__tests__/manifest-parentid.test.ts +4 -4
  67. package/src/execution/__tests__/max-turns-to-watchdog-ms.test.ts +1 -1
  68. package/src/execution/__tests__/model-resolver.test.ts +2 -2
  69. package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +23 -121
  70. package/src/execution/__tests__/nested-visibility.test.ts +2 -0
  71. package/src/execution/__tests__/notify-ledger.test.ts +973 -18
  72. package/src/execution/__tests__/output-collector.test.ts +117 -6
  73. package/src/execution/__tests__/pi-invocation.test.ts +1 -1
  74. package/src/execution/__tests__/record-store.test.ts +10 -9
  75. package/src/execution/__tests__/records-cwd-isolation.test.ts +2 -2
  76. package/src/execution/__tests__/recursive-visibility-baseline.test.ts +29 -132
  77. package/src/execution/__tests__/recursive-visibility-env.test.ts +55 -179
  78. package/src/execution/__tests__/rpc-mode.test.ts +2 -2
  79. package/src/execution/__tests__/run-and-finalize-anchoring.test.ts +387 -0
  80. package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +15 -9
  81. package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +4 -4
  82. package/src/execution/__tests__/run-spawn-edges.test.ts +17 -15
  83. package/src/execution/__tests__/run-spawn-integration.test.ts +2 -2
  84. package/src/execution/__tests__/run-spawn-resume.test.ts +2 -2
  85. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +2 -2
  86. package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +4 -4
  87. package/src/execution/__tests__/service-kill-escalation.test.ts +7 -5
  88. package/src/execution/__tests__/session-context-resolver.test.ts +0 -2
  89. package/src/execution/__tests__/session-file-gc.test.ts +35 -0
  90. package/src/execution/__tests__/session-pending.test.ts +257 -14
  91. package/src/execution/__tests__/session-reconstructor.test.ts +366 -15
  92. package/src/execution/__tests__/session-runner-branch-cache-lru.test.ts +1 -1
  93. package/src/execution/__tests__/session-runner-close-prune.test.ts +2 -2
  94. package/src/execution/__tests__/session-runner-dispatch.test.ts +489 -0
  95. package/src/execution/__tests__/session-runner-epipe.test.ts +3 -3
  96. package/src/execution/__tests__/session-runner-heartbeat-idle-fallback.test.ts +5 -4
  97. package/src/execution/__tests__/session-runner-lifecycle-helpers.test.ts +290 -0
  98. package/src/execution/__tests__/session-runner-schema-env.test.ts +7 -5
  99. package/src/execution/__tests__/settled-watchdog.test.ts +282 -47
  100. package/src/execution/__tests__/spawn-args.test.ts +11 -10
  101. package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +26 -23
  102. package/src/execution/__tests__/spawn-event-adapter.test.ts +1 -1
  103. package/src/execution/__tests__/spawn-worktree-guidance.test.ts +5 -4
  104. package/src/execution/__tests__/spawned-children.test.ts +2 -1
  105. package/src/execution/__tests__/start-sync-model-guard.test.ts +4 -4
  106. package/src/execution/__tests__/stdin-writer.test.ts +6 -4
  107. package/src/execution/__tests__/stream-sink-retirement.test.ts +6 -6
  108. package/src/execution/__tests__/subagent-actions-core.test.ts +42 -22
  109. package/src/execution/__tests__/subagent-service-message-close.test.ts +29 -26
  110. package/src/execution/__tests__/subagent-service-multiproc-guard.test.ts +8 -8
  111. package/src/execution/__tests__/subagent-service-notify-gate.test.ts +27 -22
  112. package/src/execution/__tests__/subagent-service-parent-guard.test.ts +30 -29
  113. package/src/execution/__tests__/subagent-service-recovery-bounds.test.ts +45 -20
  114. package/src/execution/__tests__/subagent-service.test.ts +37 -30
  115. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +88 -12
  116. package/src/execution/__tests__/subprocess-agent-runner-timeout.test.ts +75 -0
  117. package/src/execution/__tests__/subprocess-agent-runner.test.ts +22 -20
  118. package/src/execution/__tests__/temp-prompt.test.ts +1 -1
  119. package/src/execution/__tests__/timeout-integration.test.ts +6 -5
  120. package/src/execution/__tests__/turn-limiter-semantics.test.ts +1 -1
  121. package/src/execution/__tests__/turn-limiter.test.ts +1 -1
  122. package/src/execution/__tests__/ui-request-handler-factory.test.ts +12 -6
  123. package/src/execution/__tests__/ui-request-handler.test.ts +4 -3
  124. package/src/execution/__tests__/ui-request-queue.test.ts +142 -2
  125. package/src/execution/__tests__/worktree-manager.test.ts +14 -5
  126. package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +4 -3
  127. package/src/execution/agent-registry.ts +74 -30
  128. package/src/execution/agent-result-mapper.ts +3 -0
  129. package/src/execution/cold-resurrect.ts +199 -0
  130. package/src/execution/engine/__tests__/common/capability-gate.test.ts +91 -0
  131. package/src/execution/engine/__tests__/common/data-dir.test.ts +1 -1
  132. package/src/execution/engine/__tests__/common/journal-wiring.test.ts +84 -0
  133. package/src/execution/engine/__tests__/common/kill-chain.test.ts +34 -7
  134. package/src/execution/engine/__tests__/common/persona-router.test.ts +4 -5
  135. package/src/execution/engine/__tests__/common/pool-manager.test.ts +211 -51
  136. package/src/execution/engine/__tests__/common/session-view-service-zcode-dbpath.test.ts +149 -0
  137. package/src/execution/engine/__tests__/common/session-view-service.test.ts +499 -0
  138. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +22 -112
  139. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +15 -28
  140. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +12 -12
  141. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +1 -1
  142. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +21 -82
  143. package/src/execution/engine/__tests__/conformance/zcode-appserver-harness.ts +4 -7
  144. package/src/execution/engine/__tests__/engine-discovery.test.ts +15 -3
  145. package/src/execution/engine/__tests__/model-prompt.test.ts +15 -3
  146. package/src/execution/engine/__tests__/registry.test.ts +4 -2
  147. package/src/execution/engine/__tests__/routing.test.ts +115 -6
  148. package/src/execution/engine/common/capability-gate.ts +92 -0
  149. package/src/execution/engine/common/journal-wiring.ts +97 -0
  150. package/src/execution/engine/common/kill-chain.ts +42 -10
  151. package/src/execution/engine/common/nesting-guard.ts +66 -0
  152. package/src/execution/engine/common/persona-router.ts +18 -8
  153. package/src/execution/engine/common/pool-manager.ts +332 -78
  154. package/src/execution/engine/common/session-view-service.ts +506 -0
  155. package/src/execution/engine/common/session-view-types.ts +125 -0
  156. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +174 -28
  157. package/src/execution/engine/engines/pi/__tests__/spawn-opts-direct.test.ts +257 -0
  158. package/src/execution/{argv-mirror.ts → engine/engines/pi/argv-mirror.ts} +43 -21
  159. package/src/execution/{get-state-handshake.ts → engine/engines/pi/get-state-handshake.ts} +1 -1
  160. package/src/execution/{output-collector.ts → engine/engines/pi/output-collector.ts} +108 -19
  161. package/src/execution/engine/engines/pi/pi-engine.ts +434 -38
  162. package/src/execution/{pi-invocation.ts → engine/engines/pi/pi-invocation.ts} +2 -2
  163. package/src/execution/engine/engines/pi/reader.ts +11 -0
  164. package/src/execution/engine/engines/pi/registration.ts +4 -2
  165. package/src/execution/{session-runner.ts → engine/engines/pi/session-runner.ts} +617 -412
  166. package/src/execution/{spawn-event-adapter.ts → engine/engines/pi/spawn-event-adapter.ts} +75 -34
  167. package/src/execution/{stdin-writer.ts → engine/engines/pi/stdin-writer.ts} +10 -9
  168. package/src/execution/{temp-prompt.ts → engine/engines/pi/temp-prompt.ts} +2 -2
  169. package/src/execution/{turn-limiter.ts → engine/engines/pi/turn-limiter.ts} +1 -1
  170. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/fake-appserver.mjs +54 -27
  171. package/src/execution/engine/engines/zcode/__tests__/appserver-launcher.test.ts +321 -0
  172. package/src/execution/engine/engines/zcode/__tests__/connection.test.ts +13 -12
  173. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +7 -210
  174. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +6 -110
  175. package/src/execution/engine/engines/zcode/__tests__/session-channel-dispose-harvest.test.ts +247 -0
  176. package/src/execution/engine/engines/zcode/__tests__/session-channel-turn-timers.test.ts +451 -0
  177. package/src/execution/engine/engines/zcode/__tests__/session-channel.test.ts +20 -8
  178. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-appserver.test.ts +77 -110
  179. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-degrade.test.ts +25 -319
  180. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-dispose.test.ts +210 -0
  181. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-retry.test.ts +353 -0
  182. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-status.test.ts +282 -0
  183. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-timeout.test.ts +372 -0
  184. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +48 -148
  185. package/src/execution/engine/engines/zcode/appserver-launcher.ts +167 -0
  186. package/src/execution/engine/engines/zcode/connection.ts +24 -11
  187. package/src/execution/engine/engines/zcode/constants.ts +75 -71
  188. package/src/execution/engine/engines/zcode/golden-sample.ts +8 -46
  189. package/src/execution/engine/engines/zcode/parser.ts +12 -346
  190. package/src/execution/engine/engines/zcode/preparer.ts +12 -143
  191. package/src/execution/engine/engines/zcode/session-channel.ts +351 -39
  192. package/src/execution/engine/engines/zcode/zcode-engine.ts +665 -760
  193. package/src/execution/engine/host-task-spec.ts +32 -36
  194. package/src/execution/engine/model-validation.ts +177 -0
  195. package/src/execution/engine/port.ts +24 -6
  196. package/src/execution/engine/routing.ts +75 -1
  197. package/src/execution/engine/types.ts +30 -103
  198. package/src/execution/execution-record.ts +222 -144
  199. package/src/execution/finalize-record.ts +131 -93
  200. package/src/execution/idle-gc.ts +28 -0
  201. package/src/execution/lifecycle-predicates.ts +1 -1
  202. package/src/execution/notify-host.ts +212 -0
  203. package/src/execution/record-store.ts +119 -73
  204. package/src/execution/round-settlement.ts +93 -0
  205. package/src/execution/session-file-gc.ts +96 -62
  206. package/src/execution/session-reconstructor.ts +256 -143
  207. package/src/execution/sessions-index.ts +117 -47
  208. package/src/execution/settled-watchdog.ts +264 -52
  209. package/src/execution/subagent-actions-core.ts +22 -22
  210. package/src/execution/subagent-service.ts +815 -963
  211. package/src/execution/subprocess-agent-runner.ts +144 -97
  212. package/src/execution/types.ts +9 -0
  213. package/src/execution/ui-request-handler-factory.ts +102 -74
  214. package/src/execution/ui-request-queue.ts +50 -19
  215. package/src/index.ts +442 -316
  216. package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +1 -1
  217. package/src/orchestration/__tests__/agent-call-stream.test.ts +2 -2
  218. package/src/orchestration/__tests__/args-validator.test.ts +14 -0
  219. package/src/orchestration/__tests__/error-recovery-rebuild-failure.test.ts +1 -1
  220. package/src/orchestration/__tests__/error-recovery-terminal-hardening.test.ts +11 -9
  221. package/src/orchestration/__tests__/execute-agent-call.test.ts +151 -11
  222. package/src/orchestration/__tests__/file-run-store.test.ts +7 -6
  223. package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +2 -2
  224. package/src/orchestration/__tests__/lifecycle-abort-broadcast-signal.test.ts +1 -1
  225. package/src/orchestration/__tests__/lifecycle-runid-injection.test.ts +3 -3
  226. package/src/orchestration/__tests__/lifecycle.test.ts +7 -5
  227. package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +1 -1
  228. package/src/orchestration/__tests__/run-snapshot.test.ts +8 -5
  229. package/src/orchestration/__tests__/script-lint.test.ts +17 -0
  230. package/src/orchestration/__tests__/test-mocks.ts +2 -0
  231. package/src/orchestration/__tests__/worker-exit-without-result.test.ts +7 -6
  232. package/src/orchestration/__tests__/worker-message-pump-finalize-run.test.ts +229 -0
  233. package/src/orchestration/__tests__/{error-recovery-handlers.test.ts → worker-message-pump-handlers.test.ts} +27 -19
  234. package/src/orchestration/__tests__/{error-recovery-postmessage-defense.test.ts → worker-message-pump-postmessage-defense.test.ts} +8 -8
  235. package/src/orchestration/__tests__/{error-recovery-serialize-failed-result.test.ts → worker-message-pump-serialize-failed-result.test.ts} +2 -2
  236. package/src/orchestration/__tests__/{error-recovery-workflow-call.test.ts → worker-message-pump-workflow-call.test.ts} +1 -1
  237. package/src/orchestration/__tests__/worker-pending-timeout-abort.test.ts +1 -1
  238. package/src/orchestration/__tests__/worker-script-builder.test.ts +1 -1
  239. package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +1 -1
  240. package/src/orchestration/agent-opts-resolver.ts +1 -1
  241. package/src/orchestration/args-validator.ts +53 -31
  242. package/src/orchestration/execute-agent-call.ts +19 -73
  243. package/src/orchestration/launcher.ts +128 -81
  244. package/src/orchestration/lifecycle.ts +43 -45
  245. package/src/orchestration/models/ports.ts +4 -4
  246. package/src/orchestration/models/run-runtime.ts +2 -2
  247. package/src/orchestration/models/trace.ts +1 -1
  248. package/src/orchestration/models/types.ts +111 -22
  249. package/src/orchestration/models/workflow-run.ts +1 -1
  250. package/src/orchestration/script-lint.ts +91 -58
  251. package/src/orchestration/{error-recovery.ts → worker-message-pump.ts} +157 -150
  252. package/src/shared/__tests__/meta-parser.test.ts +151 -0
  253. package/src/shared/__tests__/resource-discovery.test.ts +258 -215
  254. package/src/shared/atomic-write.ts +12 -9
  255. package/src/shared/meta-parser.ts +158 -84
  256. package/src/shared/model-ref.ts +15 -2
  257. package/src/shared/resource-discovery.ts +9 -183
  258. package/src/shared/schema-jsonify.ts +1 -1
  259. package/workflows/review-fix-loop-utils.cjs +151 -89
  260. package/workflows/review-fix-loop-utils.d.cts +287 -0
  261. package/src/execution/__tests__/execute-options-mapper.test.ts +0 -200
  262. package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +0 -164
  263. package/src/execution/engine/engines/pi/task-spec-mapper.ts +0 -100
  264. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +0 -39
  265. package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +0 -150
  266. package/src/execution/engine/engines/zcode/__tests__/preparer-appserver.test.ts +0 -387
  267. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +0 -710
  268. package/src/execution/engine/engines/zcode/appserver-home.ts +0 -442
  269. package/src/execution/engine/engines/zcode/appserver-probe.ts +0 -141
  270. package/src/execution/engine/engines/zcode/launcher.ts +0 -161
  271. package/src/execution/execute-options-mapper.ts +0 -115
  272. package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +0 -288
@@ -1,710 +0,0 @@
1
- // zcode-engine.test.ts —— EnginePort 四面单测(fake launcher/源 config,不依赖真机
2
- // CLI 与真凭据;真机链路见 zcode-engine.live.test.ts 的手动门)。覆盖验收 6 的
3
- // capabilities/probe 部分 + run 错误语义三条(§3.3.5)。
4
- // [R4] 本文件钉扎 spawn 单轮路径(processEnv 显式 XYZ_ZCODE_MODE=spawn——D2 兜底
5
- // 行为零改动回归;缺省已切 app-server 常驻,见 zcode-engine-appserver.test.ts)。
6
-
7
- import { spawn, type ChildProcess } from "node:child_process";
8
- import * as fs from "node:fs";
9
- import * as os from "node:os";
10
- import * as path from "node:path";
11
- import { PassThrough } from "node:stream";
12
- import { fileURLToPath } from "node:url";
13
-
14
- import { beforeEach, describe, expect, it, vi } from "vitest";
15
-
16
- import type { RunContext } from "../../../port.ts";
17
- import type { AgentEvent, AgentTaskSpec, EngineHandle } from "../../../types.ts";
18
- import { getLogger } from "../../../../../core/logger.ts";
19
- import { HOST_TIMEOUT_ABORT_REASON } from "../../../common/kill-chain.ts";
20
- import { ZCODE_GOLDEN_STDOUT } from "../golden-sample.ts";
21
- import type { ZcodeLaunchedProcess } from "../launcher.ts";
22
- import { ZcodeEngine, type ZcodeEngineDeps } from "../zcode-engine.ts";
23
-
24
- const PROVIDER = "test-provider";
25
-
26
- /** 与 zcode-engine.ts 同一 facade 单例引用(spy 它的方法即拦截引擎的 warn 出声)。 */
27
- const subagentsLogger = getLogger("subagents");
28
-
29
- let tmpRoot: string;
30
- let dataDir: string;
31
- let v2Path: string;
32
-
33
- function writeJson(p: string, v: unknown): void {
34
- fs.mkdirSync(path.dirname(p), { recursive: true });
35
- fs.writeFileSync(p, JSON.stringify(v, null, 2));
36
- }
37
-
38
- beforeEach(() => {
39
- tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "zcode-engine-"));
40
- dataDir = path.join(tmpRoot, "data");
41
- v2Path = path.join(tmpRoot, "v2.json");
42
- writeJson(v2Path, {
43
- provider: { [PROVIDER]: { options: { apiKey: "k", baseURL: "https://t.example" }, models: { m1: {} } } },
44
- });
45
- });
46
-
47
- // ── fake launcher ──
48
-
49
- interface FakeLaunchOpts {
50
- stdout?: string;
51
- exitCode?: number | null;
52
- signal?: string;
53
- preKilled?: boolean;
54
- }
55
-
56
- /** fake 句柄的 child(立即退出的真实 node 短进程——满足 ChildProcess 类型与 D10 记账形态)。 */
57
- function fakeChild(): ChildProcess {
58
- return spawn(process.execPath, ["-e", ""]);
59
- }
60
-
61
- function makeFakeLaunch(fake: FakeLaunchOpts) {
62
- const calls: Array<{ cliPath: string; args: string[]; env: NodeJS.ProcessEnv }> = [];
63
- /** 每次 launch 创建的 child 句柄(D10 onChildSpawned 断言的 identity 数据源)。 */
64
- const children: ChildProcess[] = [];
65
- let killed = fake.preKilled === true;
66
- const launch = (o: { cliPath: string; args: string[]; env: NodeJS.ProcessEnv }): ZcodeLaunchedProcess => {
67
- calls.push(o);
68
- const child = fakeChild();
69
- children.push(child);
70
- const stdout = new PassThrough();
71
- stdout.end(fake.stdout ?? "");
72
- const stderr = new PassThrough();
73
- stderr.end("");
74
- return {
75
- child,
76
- pid: 4242,
77
- stdout,
78
- stderr,
79
- abort: async () => {
80
- killed = true;
81
- },
82
- exited: Promise.resolve({ code: fake.exitCode ?? 0, signal: fake.signal }),
83
- killedByUs: () => killed,
84
- };
85
- };
86
- return { launch, calls, children };
87
- }
88
-
89
- function makeEngine(overrides?: Partial<ZcodeEngineDeps>): ZcodeEngine {
90
- return new ZcodeEngine({
91
- engineDataDir: () => dataDir,
92
- sources: { v2ConfigPath: v2Path },
93
- // [R4] 钉扎 spawn 模式(缺省已是 appserver 常驻——本文件是 spawn 兜底路径的回归)
94
- processEnv: { PATH: "/usr/bin", XYZ_ZCODE_MODE: "spawn" },
95
- ...overrides,
96
- });
97
- }
98
-
99
- function makeTask(overrides?: Partial<AgentTaskSpec>): AgentTaskSpec {
100
- return { task: "Reply with the single word: ok", slug: "s", model: `${PROVIDER}/m1`, ...overrides };
101
- }
102
-
103
- function makeCtx(overrides?: Partial<RunContext>): RunContext {
104
- return { taskId: "sa-test", poolKey: "", ...overrides };
105
- }
106
-
107
- // ── capabilities ──
108
-
109
- describe("capabilities(D3 声明,验收 6;R4 D5:eventGranularity 升 stream)", () => {
110
- it("zcode 十项声明(spawn 路径钉扎下声明同为 stream——能力位是引擎级,不随模式分派)", () => {
111
- expect(makeEngine().capabilities()).toEqual({
112
- schemaEnforcement: "emulated",
113
- steer: "unsupported",
114
- conversation: "unsupported",
115
- personaInjection: "prompt",
116
- eventGranularity: "stream",
117
- sandbox: "none",
118
- sessionRead: "full",
119
- resume: "cold",
120
- interrupt: "kill-only",
121
- permissionMode: "native",
122
- });
123
- });
124
- });
125
-
126
- // ── probe ──
127
-
128
- describe("probe(D7:二进制/版本/golden 干跑,验收 6)", () => {
129
- it("三项 check 全过 + 版本进 engineVersion", async () => {
130
- const engine = makeEngine({
131
- cliPath: fileURLToPath(import.meta.url), // 存在的文件过 binary check
132
- probeVersion: async () => "0.16.5",
133
- });
134
- const report = await engine.probe();
135
- expect(report.ok).toBe(true);
136
- expect(report.engineVersion).toBe("0.16.5");
137
- expect(report.checks.map((c) => c.name)).toEqual(["binary", "version", "golden-regression"]);
138
- expect(report.error).toBeUndefined();
139
- });
140
-
141
- it("golden 样本回归:对实录样本解析出 sessionId/usage(探针干跑通过)", async () => {
142
- const engine = makeEngine({ cliPath: fileURLToPath(import.meta.url), probeVersion: async () => "x" });
143
- const report = await engine.probe();
144
- const golden = report.checks.find((c) => c.name === "golden-regression");
145
- expect(golden?.ok).toBe(true);
146
- expect(golden?.detail).toContain("0.16.5");
147
- });
148
-
149
- it("二进制缺失 → ok=false + 恢复指引(版本命令/探针重跑/文档路径)", async () => {
150
- const engine = makeEngine({ cliPath: "/nonexistent/zcode.cjs" });
151
- const report = await engine.probe();
152
- expect(report.ok).toBe(false);
153
- expect(report.error?.code).toBe("engine_probe_failed");
154
- expect(report.error?.recovery).toContain("--version");
155
- expect(report.error?.recovery).toContain("probe");
156
- expect(report.error?.recovery).toContain("docs/research/agent-engine-zcode.md");
157
- });
158
-
159
- it("结果缓存:非 force 二次探针不重跑版本命令", async () => {
160
- const probeVersion = vi.fn(async () => "0.16.5");
161
- const engine = makeEngine({ cliPath: fileURLToPath(import.meta.url), probeVersion });
162
- await engine.probe();
163
- await engine.probe();
164
- expect(probeVersion).toHaveBeenCalledTimes(1);
165
- await engine.probe({ force: true });
166
- expect(probeVersion).toHaveBeenCalledTimes(2);
167
- });
168
- });
169
-
170
- // ── run:错误语义三条(§3.3.5)──
171
-
172
- describe("run ① prepare 期错误:进程创建前 reject、不产生 handle", () => {
173
- it("凭据缺失 → engine_credential_missing", async () => {
174
- writeJson(v2Path, { provider: {} });
175
- const engine = makeEngine({ launch: makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT }).launch });
176
- await expect(engine.run(makeTask(), makeCtx())).rejects.toThrowError(/engine_credential_missing/);
177
- });
178
-
179
- it("模型不可解析 → model_not_available(列可用模型)", async () => {
180
- const engine = makeEngine({ launch: makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT }).launch });
181
- await expect(engine.run(makeTask({ model: `${PROVIDER}/ghost` }), makeCtx())).rejects.toThrowError(
182
- /model_not_available/,
183
- );
184
- });
185
-
186
- it("argv 超限 → prompt_too_large(不调 launch)", async () => {
187
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
188
- const engine = makeEngine({ launch: fake.launch });
189
- await expect(engine.run(makeTask({ task: "x".repeat(200 * 1024) }), makeCtx())).rejects.toThrowError(
190
- /prompt_too_large/,
191
- );
192
- expect(fake.calls).toHaveLength(0);
193
- });
194
-
195
- it("conversation 任务标志 → engine_capability_unsupported(A11:无进程创建)", async () => {
196
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
197
- const engine = makeEngine({ launch: fake.launch });
198
- await expect(engine.run(makeTask({ conversation: true }), makeCtx())).rejects.toThrowError(
199
- /engine_capability_unsupported/,
200
- );
201
- expect(fake.calls).toHaveLength(0);
202
- });
203
-
204
- it("fork(pi 专属)→ engine_capability_unsupported", async () => {
205
- const engine = makeEngine();
206
- await expect(engine.run(makeTask({ fork: true }), makeCtx())).rejects.toThrowError(
207
- /engine_capability_unsupported/,
208
- );
209
- });
210
-
211
- it("maxTurns(pi 专属)→ engine_capability_unsupported,不调 launch(U4:静默丢弃会造成假上限)", async () => {
212
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
213
- const engine = makeEngine({ launch: fake.launch });
214
- await expect(engine.run(makeTask({ maxTurns: 10 }), makeCtx())).rejects.toThrowError(
215
- /engine_capability_unsupported/,
216
- );
217
- // 恢复指引:去掉 maxTurns 或改用 pi 引擎
218
- await expect(engine.run(makeTask({ maxTurns: 10 }), makeCtx())).rejects.toThrowError(
219
- /maxTurns|engine: 'pi'/,
220
- );
221
- expect(fake.calls).toHaveLength(0);
222
- });
223
- });
224
-
225
- describe("run ② 成功路径:golden stdout → outcome/handle/事件合成", () => {
226
- it("content/usage/sessionId 正确,事件序 = message_end → turn_end(不变量 5)", async () => {
227
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
228
- const engine = makeEngine({ launch: fake.launch });
229
- const events: AgentEvent[] = [];
230
- const { handle, outcome } = await engine.run(makeTask(), makeCtx({ onEvent: (e) => events.push(e) }));
231
-
232
- expect(outcome.error).toBeUndefined();
233
- expect(outcome.engineId).toBe("zcode");
234
- expect(outcome.content).toBe("ok");
235
- // 终态层 usage(orchestration 版):cost=0 显式缺省、contextTokens/turns 来自 projection
236
- expect(outcome.usage).toEqual({
237
- input: 12599,
238
- output: 17,
239
- cacheRead: 512,
240
- cacheWrite: 0,
241
- cost: 0,
242
- contextTokens: 12616,
243
- turns: 1,
244
- });
245
- expect(outcome.sessionId).toBe("sess_35852a0f-1302-4e20-9e48-87f47527abe3");
246
- expect(outcome.exitCode).toBe(0);
247
- expect(outcome.durationMs).toBeGreaterThanOrEqual(0);
248
- // 事件:message_end(带完整 usage)在前、turn_end 最后
249
- expect(events).toHaveLength(2);
250
- expect(events[0]).toEqual({ type: "message_end", usage: { input: 12599, output: 17, cacheRead: 512, cacheWrite: 0 } });
251
- expect(events[1]).toEqual({ type: "turn_end" });
252
-
253
- // handle:自描述(poolKey/dbPath 相对池目录/sessionId)
254
- expect(handle.data.engineId).toBe("zcode");
255
- expect(handle.data.poolKey).toBe(`home-${PROVIDER}-m1`);
256
- expect(handle.data.sessionRef["dbPath"]).toBe(".zcode/cli/db/db.sqlite");
257
- expect(handle.data.sessionRef["sessionId"]).toBe("sess_35852a0f-1302-4e20-9e48-87f47527abe3");
258
- expect(handle.data.adapterVersion).toBe("1.0.0");
259
- });
260
-
261
- it("launcher 收到隔离 HOME env + XYZ_AGENT_SUBAGENT + denylist flag + 完整 prompt", async () => {
262
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
263
- const engine = makeEngine({ launch: fake.launch });
264
- await engine.run(
265
- makeTask({
266
- task: "TASK BODY",
267
- persona: { appendSystemPrompt: ["PERSONA A", "PERSONA B"] },
268
- denyTools: ["bash"],
269
- cwd: "/work/dir",
270
- }),
271
- makeCtx(),
272
- );
273
- expect(fake.calls).toHaveLength(1);
274
- const call = fake.calls[0]!;
275
- expect(call.env["HOME"]).toBe(path.join(dataDir, "engines", "zcode", `home-${PROVIDER}-m1`));
276
- expect(call.env["XYZ_AGENT_SUBAGENT"]).toBe("1");
277
- expect(call.env["PATH"]).toBe("/usr/bin");
278
- expect(call.args).toContain("--cwd");
279
- expect(call.args[call.args.indexOf("--cwd") + 1]).toBe("/work/dir");
280
- expect(call.args).toContain("--disallowed-tools");
281
- // prompt = persona 段在前 + task 正文在后(personaInjection: 'prompt')。
282
- // [S5] persona 段现经 common/persona-router.applyPersona 统一拼装(## Persona
283
- // 结构头 + appendSystemPrompt 正文 join "\n")——旧断言 "PERSONA A\n\nPERSONA B"
284
- // 锚定的是被本次接线推翻的手拼形态。
285
- const promptIdx = call.args.indexOf("--prompt");
286
- expect(call.args[promptIdx + 1]).toBe("## Persona\nPERSONA A\nPERSONA B\n\nTASK BODY");
287
- });
288
-
289
- it("persona 的 agentRef/skillPath 引用行拼进 prompt(S5:prompt 通道不再丢弃,zcode 无 --skill flag)", async () => {
290
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
291
- const engine = makeEngine({ launch: fake.launch });
292
- await engine.run(
293
- makeTask({
294
- task: "TASK BODY",
295
- persona: { agentRef: "reviewer", skillPath: "/skills/review.md", appendSystemPrompt: ["RULE X"] },
296
- }),
297
- makeCtx(),
298
- );
299
- const promptIdx = fake.calls[0]!.args.indexOf("--prompt");
300
- expect(fake.calls[0]!.args[promptIdx + 1]).toBe(
301
- "## Persona\n# Agent: reviewer\nSkill context: /skills/review.md\nRULE X\n\nTASK BODY",
302
- );
303
- });
304
-
305
- it("persona 全空:prompt 不带 Persona 段(applyPersona 空载体不拼空段)", async () => {
306
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
307
- const engine = makeEngine({ launch: fake.launch });
308
- await engine.run(makeTask({ task: "BARE TASK", persona: {} }), makeCtx());
309
- const promptIdx = fake.calls[0]!.args.indexOf("--prompt");
310
- expect(fake.calls[0]!.args[promptIdx + 1]).toBe("BARE TASK");
311
- });
312
-
313
- it("preparer 池 config 已落盘(无 plugins 块)", async () => {
314
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
315
- const engine = makeEngine({ launch: fake.launch });
316
- await engine.run(makeTask(), makeCtx());
317
- const poolConfig = path.join(dataDir, "engines", "zcode", `home-${PROVIDER}-m1`, ".zcode/cli/config.json");
318
- const written = JSON.parse(fs.readFileSync(poolConfig, "utf8")) as Record<string, unknown>;
319
- expect(written["model"]).toEqual({ main: `${PROVIDER}/m1` });
320
- expect("plugins" in written).toBe(false);
321
- });
322
- });
323
-
324
- // ── prepare 期可见信号(F15b/F16b:spawn 路径 effort 丢弃 / ctxModel 忽略留痕)──
325
-
326
- describe("run prepare 期可见信号(F15b/F16b)", () => {
327
- it("F15b: effort 在 spawn 路径被忽略并出声(文案含 effort 值与不支持语义,不阻断任务)", async () => {
328
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
329
- const engine = makeEngine({ launch: fake.launch });
330
- const warns: string[] = [];
331
- const warnSpy = vi.spyOn(subagentsLogger, "warn").mockImplementation(((msg: string) => {
332
- warns.push(msg);
333
- }) as typeof subagentsLogger.warn);
334
- try {
335
- const { outcome } = await engine.run(makeTask({ effort: "high" }), makeCtx());
336
- expect(outcome.error).toBeUndefined(); // 信号只留痕,不改变任务结论
337
- const hit = warns.find((m) => m.includes("effort"));
338
- expect(hit).toBeDefined();
339
- expect(hit).toContain("effort=high");
340
- expect(hit).toContain("zcode spawn 不支持");
341
- } finally {
342
- warnSpy.mockRestore();
343
- }
344
- });
345
-
346
- it("F15b: effort 未传/空白 → 零 effort 信号(避免噪音)", async () => {
347
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
348
- const engine = makeEngine({ launch: fake.launch });
349
- const warns: string[] = [];
350
- const warnSpy = vi.spyOn(subagentsLogger, "warn").mockImplementation(((msg: string) => {
351
- warns.push(msg);
352
- }) as typeof subagentsLogger.warn);
353
- try {
354
- await engine.run(makeTask({ effort: " " }), makeCtx());
355
- await engine.run(makeTask(), makeCtx());
356
- expect(warns.filter((m) => m.includes("effort"))).toHaveLength(0);
357
- } finally {
358
- warnSpy.mockRestore();
359
- }
360
- });
361
-
362
- it("F16b: task.model 缺省 + ctx.ctxModel 存在 → 出声留痕(含被忽略的 ctx 模型与实际引擎缺省模型)", async () => {
363
- // v2 config 补缺省模型 provider 条目——ZCODE_FALLBACK_DEFAULT_MODEL 的解析链才可校验通过
364
- writeJson(v2Path, {
365
- provider: {
366
- [PROVIDER]: { options: { apiKey: "k", baseURL: "https://t.example" }, models: { m1: {} } },
367
- "builtin:bigmodel-coding-plan": { options: { apiKey: "k" }, models: { "GLM-5.3": {} } },
368
- },
369
- });
370
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
371
- const engine = makeEngine({ launch: fake.launch });
372
- const warns: string[] = [];
373
- const warnSpy = vi.spyOn(subagentsLogger, "warn").mockImplementation(((msg: string) => {
374
- warns.push(msg);
375
- }) as typeof subagentsLogger.warn);
376
- try {
377
- const { outcome } = await engine.run(
378
- makeTask({ model: undefined }),
379
- makeCtx({ ctxModel: { id: "main-model", name: "Main", provider: "p", reasoning: false } }),
380
- );
381
- expect(outcome.error).toBeUndefined(); // 信号只留痕,不改变任务结论
382
- const hit = warns.find((m) => m.includes("ctxModel"));
383
- expect(hit).toBeDefined();
384
- expect(hit).toContain("main-model");
385
- expect(hit).toContain("builtin:bigmodel-coding-plan/GLM-5.3");
386
- } finally {
387
- warnSpy.mockRestore();
388
- }
389
- });
390
-
391
- it("F16b: 显式 task.model 或 ctx 无 ctxModel → 零 ctxModel 信号(只在「ctx 有模型但被忽略」时出声)", async () => {
392
- // 第二段 run(model 缺省)走引擎缺省链——v2 config 需含 ZCODE_FALLBACK_DEFAULT_MODEL 的 provider
393
- writeJson(v2Path, {
394
- provider: {
395
- [PROVIDER]: { options: { apiKey: "k", baseURL: "https://t.example" }, models: { m1: {} } },
396
- "builtin:bigmodel-coding-plan": { options: { apiKey: "k" }, models: { "GLM-5.3": {} } },
397
- },
398
- });
399
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
400
- const engine = makeEngine({ launch: fake.launch });
401
- const warns: string[] = [];
402
- const warnSpy = vi.spyOn(subagentsLogger, "warn").mockImplementation(((msg: string) => {
403
- warns.push(msg);
404
- }) as typeof subagentsLogger.warn);
405
- try {
406
- // 显式 task.model + ctxModel:走正常解析链,不出声
407
- await engine.run(
408
- makeTask(),
409
- makeCtx({ ctxModel: { id: "main-model", name: "Main", provider: "p", reasoning: false } }),
410
- );
411
- // model 缺省 + ctx 无 ctxModel:预期缺省链,不出声
412
- await engine.run(makeTask({ model: undefined }), makeCtx());
413
- expect(warns.filter((m) => m.includes("ctxModel"))).toHaveLength(0);
414
- } finally {
415
- warnSpy.mockRestore();
416
- }
417
- });
418
- });
419
-
420
- // ── D10 终止链路径①(C-ext-17 回归):spawn 成功后同步回调 onChildSpawned ──
421
-
422
- describe("run D10:onChildSpawned(宿主终止链记账钩子)", () => {
423
- it("spawn 成功 → ctx.onChildSpawned 收到 launcher 的 child 句柄,先于任何终态事件(同步口径)", async () => {
424
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
425
- const engine = makeEngine({ launch: fake.launch });
426
- const seen: Array<{ child: ChildProcess; eventsBefore: number }> = [];
427
- let eventCount = 0;
428
- const { outcome } = await engine.run(
429
- makeTask(),
430
- makeCtx({
431
- onChildSpawned: (child) => seen.push({ child, eventsBefore: eventCount }),
432
- onEvent: () => {
433
- eventCount++;
434
- },
435
- }),
436
- );
437
- expect(outcome.error).toBeUndefined();
438
- // 回调恰好一次,句柄即 launch 返回的 child(宿主 registerSpawnedChildForRecord 数据源)
439
- expect(seen).toHaveLength(1);
440
- expect(seen[0]?.child).toBe(fake.children[0]);
441
- // 同步回调(port.ts 契约):zcode coarse 事件在终态后合成,回调时事件数为 0
442
- expect(seen[0]?.eventsBefore).toBe(0);
443
- });
444
-
445
- it("ctx 未提供回调时静默跳过(可选钩子,run 正常完成)", async () => {
446
- const fake = makeFakeLaunch({ stdout: ZCODE_GOLDEN_STDOUT });
447
- const engine = makeEngine({ launch: fake.launch });
448
- const { outcome } = await engine.run(makeTask(), makeCtx());
449
- expect(outcome.error).toBeUndefined();
450
- expect(outcome.content).toBe("ok");
451
- });
452
- });
453
-
454
- describe("run schema 仿真接线(D4 emulated 侧:common/schema-emulation 公共层)", () => {
455
- const VERDICT_SCHEMA = {
456
- type: "object",
457
- properties: { verdict: { type: "string", enum: ["ok", "bad"] } },
458
- required: ["verdict"],
459
- additionalProperties: false,
460
- };
461
-
462
- function terminalStdout(response: string, sessionId: string): string {
463
- return JSON.stringify({
464
- sessionId,
465
- response,
466
- usage: { inputTokens: 10, outputTokens: 5, cacheReadTokens: 0, cacheWriteTokens: 0 },
467
- projection: { turnCount: 1, contextUsed: 15 },
468
- });
469
- }
470
-
471
- it("合法输出 → parsedOutput = ajv 校验产物;prompt 尾部拼了仿真段", async () => {
472
- const fake = makeFakeLaunch({ stdout: terminalStdout('{"verdict":"ok"}', "sess_s1") });
473
- const engine = makeEngine({ launch: fake.launch });
474
- const { outcome } = await engine.run(makeTask({ schema: VERDICT_SCHEMA }), makeCtx());
475
- expect(outcome.error).toBeUndefined();
476
- expect(outcome.parsedOutput).toEqual({ verdict: "ok" });
477
- // 仿真段拼进 prompt 尾部(buildSchemaEmulationSegment 的输出特征)
478
- const prompt = fake.calls[0]!.args[fake.calls[0]!.args.indexOf("--prompt") + 1]!;
479
- expect(prompt).toContain("Structured Output Requirement");
480
- expect(prompt).toContain("verdict");
481
- expect(prompt.endsWith("the first complete JSON value is extracted.")).toBe(true);
482
- });
483
-
484
- it("markdown fence 包裹的输出也过(三级容错提取)", async () => {
485
- const fake = makeFakeLaunch({ stdout: terminalStdout('```json\n{"verdict":"ok"}\n```', "sess_s2") });
486
- const engine = makeEngine({ launch: fake.launch });
487
- const { outcome } = await engine.run(makeTask({ schema: VERDICT_SCHEMA }), makeCtx());
488
- expect(outcome.parsedOutput).toEqual({ verdict: "ok" });
489
- });
490
-
491
- it("首轮校验失败 → 强化 prompt 重试一次,二次通过 → parsedOutput 产出", async () => {
492
- const stdouts = [terminalStdout("I think everything is fine.", "sess_r1"), terminalStdout('{"verdict":"ok"}', "sess_r2")];
493
- const launches: string[] = [];
494
- const launch = (o: { cliPath: string; args: string[]; env: NodeJS.ProcessEnv }): ZcodeLaunchedProcess => {
495
- const stdout = stdouts[launches.length] ?? "";
496
- launches.push(o.args[o.args.indexOf("--prompt") + 1]!);
497
- const s = new PassThrough();
498
- s.end(stdout);
499
- const e = new PassThrough();
500
- e.end("");
501
- return {
502
- child: fakeChild(),
503
- pid: 1,
504
- stdout: s,
505
- stderr: e,
506
- abort: async () => undefined,
507
- exited: Promise.resolve({ code: 0, signal: undefined }),
508
- killedByUs: () => false,
509
- };
510
- };
511
- const engine = makeEngine({ launch });
512
- const { outcome } = await engine.run(makeTask({ schema: VERDICT_SCHEMA }), makeCtx());
513
- expect(launches).toHaveLength(2);
514
- // 重试 prompt 带强化指令 + 首战失败原因回灌
515
- expect(launches[1]).toContain("Retry: Structured Output Failed");
516
- expect(launches[1]).toContain("could not extract JSON");
517
- expect(outcome.parsedOutput).toEqual({ verdict: "ok" });
518
- expect(outcome.error).toBeUndefined();
519
- // sessionId 取末轮(最终响应所在 session);usage 两轮累计
520
- expect(outcome.sessionId).toBe("sess_r2");
521
- expect(outcome.usage).toEqual({ input: 20, output: 10, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 15, turns: 1 });
522
- });
523
-
524
- it("两轮均失败 → schema_emulation_failed(含原始输出尾部与恢复指引)", async () => {
525
- const fake = makeFakeLaunch({ stdout: terminalStdout("no json at all, just prose", "sess_f1") });
526
- const engine = makeEngine({ launch: fake.launch });
527
- const events: AgentEvent[] = [];
528
- const { outcome } = await engine.run(
529
- makeTask({ schema: VERDICT_SCHEMA }),
530
- makeCtx({ onEvent: (e) => events.push(e) }),
531
- );
532
- expect(outcome.parsedOutput).toBeUndefined();
533
- expect(outcome.error).toContain("schema_emulation_failed");
534
- expect(outcome.error).toContain("no json at all");
535
- expect(outcome.error).toContain("engine: pi");
536
- // content 保留末轮原始输出(record 可追溯)
537
- expect(outcome.content).toContain("no json at all");
538
- expect(events[0]).toEqual({ type: "error", message: outcome.error });
539
- });
540
- });
541
-
542
- describe("run ② 运行中失败:不 reject——error outcome + 正常 handle(record 收尾)", () => {
543
- it("非零退出:engine_run_failed 含 stdout 尾部 + exit code + 恢复指引", async () => {
544
- const fake = makeFakeLaunch({ stdout: "Error: cannot connect\n", exitCode: 3 });
545
- const engine = makeEngine({ launch: fake.launch });
546
- const events: AgentEvent[] = [];
547
- const { handle, outcome } = await engine.run(makeTask(), makeCtx({ onEvent: (e) => events.push(e) }));
548
- expect(outcome.error).toContain("engine_run_failed");
549
- expect(outcome.error).toContain("exit code: 3");
550
- expect(outcome.error).toContain("Error: cannot connect");
551
- expect(outcome.error).toContain("engine: pi");
552
- expect(outcome.exitCode).toBe(3);
553
- expect(outcome.content).toBe("");
554
- expect(events).toEqual([{ type: "error", message: outcome.error }]);
555
- // handle 仍返回(sessionId 缺失但 dbPath/poolKey 齐备)
556
- expect(handle.data.sessionRef["dbPath"]).toBe(".zcode/cli/db/db.sqlite");
557
- expect(handle.data.sessionRef["sessionId"]).toBeUndefined();
558
- });
559
-
560
- it("exit 0 但 stdout 损坏(格式漂移):parseReason 进错误", async () => {
561
- const fake = makeFakeLaunch({ stdout: "not a json" });
562
- const engine = makeEngine({ launch: fake.launch });
563
- const { outcome } = await engine.run(makeTask(), makeCtx());
564
- expect(outcome.error).toContain("engine_run_failed");
565
- expect(outcome.error).toContain("不是 JSON");
566
- });
567
- });
568
-
569
- describe("run ③ abort:杀链合成终态(exitCode=null + 杀链标记)", () => {
570
- it("pre-aborted signal → abort 被调、killedByUs 判定、无 engine 自身失败语义", async () => {
571
- const fake = makeFakeLaunch({ stdout: "", exitCode: 143 });
572
- const engine = makeEngine({ launch: fake.launch });
573
- const controller = new AbortController();
574
- controller.abort();
575
- const { outcome } = await engine.run(makeTask(), makeCtx({ signal: controller.signal }));
576
- expect(outcome.exitCode).toBeNull();
577
- expect(outcome.error).toContain("SIGTERM");
578
- expect(outcome.error).toContain("5000");
579
- });
580
-
581
- it("运行中 abort(listener 触发形态)", async () => {
582
- let killed = false;
583
- const stdout = new PassThrough();
584
- const stderr = new PassThrough();
585
- const launch = (): ZcodeLaunchedProcess => ({
586
- child: fakeChild(),
587
- pid: 99,
588
- stdout,
589
- stderr,
590
- abort: async () => {
591
- killed = true;
592
- stdout.end();
593
- },
594
- exited: new Promise((resolve) => {
595
- const t = setTimeout(() => {
596
- killed = true;
597
- stdout.end();
598
- resolve({ code: null, signal: "SIGTERM" });
599
- }, 50);
600
- void t;
601
- }),
602
- killedByUs: () => killed,
603
- });
604
- const engine = makeEngine({ launch });
605
- const controller = new AbortController();
606
- const runPromise = engine.run(makeTask(), makeCtx({ signal: controller.signal }));
607
- controller.abort();
608
- const { outcome } = await runPromise;
609
- expect(outcome.exitCode).toBeNull();
610
- expect(outcome.error).toContain("杀链");
611
- });
612
-
613
- it("宿主超时 abort(reason 标记)→ engine_timeout 公共合成终态(对齐点④)", async () => {
614
- const fake = makeFakeLaunch({ stdout: "partial output", exitCode: 143 });
615
- const engine = makeEngine({ launch: fake.launch });
616
- const controller = new AbortController();
617
- controller.abort(HOST_TIMEOUT_ABORT_REASON); // mergeTimeoutSignal 超时链的 abort 形态
618
- const { outcome } = await engine.run(makeTask(), makeCtx({ signal: controller.signal }));
619
- expect(outcome.exitCode).toBeNull();
620
- expect(outcome.error).toContain("engine_timeout");
621
- expect(outcome.error).toContain("partial output"); // stdout 尾部保留(错误规格第 6 行)
622
- expect(outcome.error).toContain("engine: pi"); // 重跑建议
623
- });
624
- });
625
-
626
- // ── interact ──
627
-
628
- describe("interact:A11 同步拒绝(不创建进程)", () => {
629
- it("engine_capability_unsupported + 可操作建议(换单次调用 / engine: pi)", async () => {
630
- const engine = makeEngine();
631
- const handle: EngineHandle = {
632
- data: { v: 1, engineId: "zcode", sessionRef: {}, poolKey: "p", adapterVersion: "1.0.0" },
633
- };
634
- const res = await engine.interact(handle, { kind: "message", payload: "next" });
635
- expect(res.ok).toBe(false);
636
- if (res.ok) return;
637
- expect(res.code).toBe("engine_capability_unsupported");
638
- expect(res.message).toContain("单次");
639
- expect(res.message).toContain("engine: 'pi'");
640
- });
641
- });
642
-
643
- // ── read ──
644
-
645
- describe("read:第①级 + 降级 outcome-only", () => {
646
- async function seedDb(poolKey: string, sessionId: string): Promise<void> {
647
- const dbFile = path.join(
648
- dataDir,
649
- "engines",
650
- "zcode",
651
- poolKey,
652
- ".zcode",
653
- "cli",
654
- "db",
655
- "db.sqlite",
656
- );
657
- fs.mkdirSync(path.dirname(dbFile), { recursive: true });
658
- const { DatabaseSync } = (await import("node:sqlite")) as { DatabaseSync: new (p: string) => unknown };
659
- type Db = {
660
- exec: (s: string) => void;
661
- prepare: (s: string) => { run: (...a: unknown[]) => void };
662
- close: () => void;
663
- };
664
- const db = new DatabaseSync(dbFile) as unknown as Db;
665
- db.exec(
666
- "CREATE TABLE session (id TEXT PRIMARY KEY, time_created INTEGER);" +
667
- "CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, sequence INTEGER, data TEXT);" +
668
- "CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT, sequence INTEGER, data TEXT);",
669
- );
670
- db.prepare("INSERT INTO session (id, time_created) VALUES (?, ?)").run(sessionId, 1);
671
- db
672
- .prepare("INSERT INTO message (id, session_id, sequence, data) VALUES (?, ?, ?, ?)")
673
- .run("m1", sessionId, 0, JSON.stringify({ role: "assistant" }));
674
- db
675
- .prepare("INSERT INTO part (id, message_id, session_id, sequence, data) VALUES (?, ?, ?, ?, ?)")
676
- .run("p1", "m1", sessionId, 0, JSON.stringify({ type: "text", text: "answer" }));
677
- db
678
- .prepare("INSERT INTO part (id, message_id, session_id, sequence, data) VALUES (?, ?, ?, ?, ?)")
679
- .run("p2", "m1", sessionId, 1, JSON.stringify({ type: "step-finish", tokens: { input: 5, output: 2 } }));
680
- db.close();
681
- }
682
-
683
- function makeHandle(sessionRef: Record<string, string>, poolKey: string): EngineHandle {
684
- return { data: { v: 1, engineId: "zcode", sessionRef, poolKey, adapterVersion: "1.0.0" } };
685
- }
686
-
687
- it("①级:池内 db 经相对 dbPath 定位,native 视图 turns 非空", async () => {
688
- await seedDb("home-p-m", "sess_read1");
689
- const engine = makeEngine();
690
- const view = await engine.read(makeHandle({ sessionId: "sess_read1", dbPath: ".zcode/cli/db/db.sqlite" }, "home-p-m"));
691
- expect(view.source).toBe("native");
692
- expect(view.turns).toHaveLength(1);
693
- expect(view.turns[0]!.text).toBe("answer");
694
- });
695
-
696
- it("sessionId 缺失 → outcome-only(共享池 db 无法定位 session)", async () => {
697
- const engine = makeEngine();
698
- const view = await engine.read(makeHandle({ dbPath: ".zcode/cli/db/db.sqlite" }, "home-p-m"));
699
- expect(view.source).toBe("outcome-only");
700
- expect(view.turns).toEqual([]);
701
- });
702
-
703
- it("db 缺失(结构化读取失败)→ 降级 outcome-only 不 throw", async () => {
704
- const engine = makeEngine();
705
- const view = await engine.read(
706
- makeHandle({ sessionId: "sess_ghost", dbPath: ".zcode/cli/db/db.sqlite" }, "home-empty"),
707
- );
708
- expect(view.source).toBe("outcome-only");
709
- });
710
- });