@zhushanwen/subagent-core 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (330) hide show
  1. package/README.md +114 -0
  2. package/dist/chunk-3VOERJPJ.js +22 -0
  3. package/dist/chunk-A4IVZWVX.js +31 -0
  4. package/dist/execution/engine/engines/zcode/constants.cjs +54 -0
  5. package/dist/execution/engine/engines/zcode/constants.d.cts +31 -0
  6. package/dist/execution/engine/engines/zcode/constants.d.ts +31 -0
  7. package/dist/execution/engine/engines/zcode/constants.js +22 -0
  8. package/dist/execution/engine/engines/zcode/reader.cjs +276 -0
  9. package/dist/execution/engine/engines/zcode/reader.d.cts +20 -0
  10. package/dist/execution/engine/engines/zcode/reader.d.ts +20 -0
  11. package/dist/execution/engine/engines/zcode/reader.js +239 -0
  12. package/dist/execution/engine/paths.cjs +55 -0
  13. package/dist/execution/engine/paths.d.cts +8 -0
  14. package/dist/execution/engine/paths.d.ts +8 -0
  15. package/dist/execution/engine/paths.js +26 -0
  16. package/dist/execution/relay-env.cjs +62 -0
  17. package/dist/execution/relay-env.d.cts +33 -0
  18. package/dist/execution/relay-env.d.ts +33 -0
  19. package/dist/execution/relay-env.js +20 -0
  20. package/dist/index.cjs +1852 -0
  21. package/dist/index.d.cts +1184 -0
  22. package/dist/index.d.ts +1184 -0
  23. package/dist/index.js +1810 -0
  24. package/dist/types-BxyAidGf.d.cts +875 -0
  25. package/dist/types-BxyAidGf.d.ts +875 -0
  26. package/package.json +99 -0
  27. package/src/__tests__/agent-opts-resolver-schema-prompt.test.ts +142 -0
  28. package/src/__tests__/append-system-prompt-assembly.test.ts +242 -0
  29. package/src/__tests__/builtin-workflows-structure.test.ts +180 -0
  30. package/src/__tests__/derive-closed-display-parity.test.ts +93 -0
  31. package/src/__tests__/fr4-get-state-handshake.test.ts +125 -0
  32. package/src/__tests__/fr8-orphan-recovery.test.ts +259 -0
  33. package/src/__tests__/m2-append-content-probe.test.ts +73 -0
  34. package/src/__tests__/manifest-store.test.ts +368 -0
  35. package/src/__tests__/record-store-cache.test.ts +335 -0
  36. package/src/__tests__/record-store-index.test.ts +560 -0
  37. package/src/__tests__/record-store-last-line.test.ts +129 -0
  38. package/src/__tests__/review-fix-loop-script.test.ts +288 -0
  39. package/src/__tests__/review-fix-loop-utils.test.ts +2377 -0
  40. package/src/__tests__/robustness-low-batch1.test.ts +286 -0
  41. package/src/__tests__/robustness-medium-batch1.test.ts +69 -0
  42. package/src/__tests__/robustness-medium-batch2.test.ts +65 -0
  43. package/src/__tests__/robustness-medium-batch3.test.ts +30 -0
  44. package/src/__tests__/robustness-medium-batch4.test.ts +358 -0
  45. package/src/__tests__/session-runner.test.ts +69 -0
  46. package/src/__tests__/smoke.test.ts +9 -0
  47. package/src/__tests__/stream-sink.test.ts +203 -0
  48. package/src/core/__tests__/host-services.test.ts +144 -0
  49. package/src/core/__tests__/logger.test.ts +78 -0
  50. package/src/core/__tests__/notify-ports.test.ts +104 -0
  51. package/src/core/host-services.ts +97 -0
  52. package/src/core/logger.ts +47 -0
  53. package/src/core/notify-ports.ts +126 -0
  54. package/src/execution/__tests__/__fixtures__/notifier-golden-snapshots.json +53 -0
  55. package/src/execution/__tests__/__fixtures__/truncline.snapshot.json +1 -0
  56. package/src/execution/__tests__/agent-result-mapper.test.ts +150 -0
  57. package/src/execution/__tests__/alive-store.test.ts +147 -0
  58. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +490 -0
  59. package/src/execution/__tests__/channel-registry-handshake.test.ts +242 -0
  60. package/src/execution/__tests__/chat-engine-routing.test.ts +610 -0
  61. package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +190 -0
  62. package/src/execution/__tests__/concurrency-pool.test.ts +250 -0
  63. package/src/execution/__tests__/config.test.ts +302 -0
  64. package/src/execution/__tests__/delivery-methods.test.ts +424 -0
  65. package/src/execution/__tests__/dialog-queue.test.ts +299 -0
  66. package/src/execution/__tests__/epipe-fallback.test.ts +241 -0
  67. package/src/execution/__tests__/execute-and-await-worktree.test.ts +243 -0
  68. package/src/execution/__tests__/execute-nesting.test.ts +323 -0
  69. package/src/execution/__tests__/execute-options-mapper.test.ts +200 -0
  70. package/src/execution/__tests__/execution-record.test.ts +1394 -0
  71. package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +171 -0
  72. package/src/execution/__tests__/finalize-record.test.ts +367 -0
  73. package/src/execution/__tests__/finalized-marker.test.ts +104 -0
  74. package/src/execution/__tests__/format-schema-instruction.test.ts +169 -0
  75. package/src/execution/__tests__/gc-timer.test.ts +184 -0
  76. package/src/execution/__tests__/get-record-for-action-restart.test.ts +254 -0
  77. package/src/execution/__tests__/helpers/mock-extension-api.ts +30 -0
  78. package/src/execution/__tests__/helpers/spawn-mock.ts +242 -0
  79. package/src/execution/__tests__/host-mode.test.ts +87 -0
  80. package/src/execution/__tests__/lifecycle-manager-lock.test.ts +211 -0
  81. package/src/execution/__tests__/lifecycle-manager.test.ts +383 -0
  82. package/src/execution/__tests__/lifecycle-predicates.test.ts +116 -0
  83. package/src/execution/__tests__/manifest-parentid.test.ts +117 -0
  84. package/src/execution/__tests__/model-resolver.test.ts +465 -0
  85. package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +287 -0
  86. package/src/execution/__tests__/nested-visibility.test.ts +325 -0
  87. package/src/execution/__tests__/output-collector.test.ts +358 -0
  88. package/src/execution/__tests__/path-encoding.test.ts +104 -0
  89. package/src/execution/__tests__/pi-invocation.test.ts +134 -0
  90. package/src/execution/__tests__/record-store.test.ts +1057 -0
  91. package/src/execution/__tests__/records-cwd-isolation.test.ts +91 -0
  92. package/src/execution/__tests__/recursive-visibility-baseline.test.ts +339 -0
  93. package/src/execution/__tests__/recursive-visibility-env.test.ts +273 -0
  94. package/src/execution/__tests__/relay-env.test.ts +42 -0
  95. package/src/execution/__tests__/resource-policy.test.ts +109 -0
  96. package/src/execution/__tests__/rpc-mode.test.ts +89 -0
  97. package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +267 -0
  98. package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +253 -0
  99. package/src/execution/__tests__/run-spawn-edges.test.ts +687 -0
  100. package/src/execution/__tests__/run-spawn-integration.test.ts +933 -0
  101. package/src/execution/__tests__/run-spawn-resume.test.ts +322 -0
  102. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +196 -0
  103. package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +199 -0
  104. package/src/execution/__tests__/session-context-resolver.test.ts +167 -0
  105. package/src/execution/__tests__/session-file-gc.test.ts +293 -0
  106. package/src/execution/__tests__/session-reconstructor.test.ts +379 -0
  107. package/src/execution/__tests__/session-runner-epipe.test.ts +178 -0
  108. package/src/execution/__tests__/session-runner-schema-env.test.ts +350 -0
  109. package/src/execution/__tests__/spawn-args.test.ts +445 -0
  110. package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +189 -0
  111. package/src/execution/__tests__/spawn-event-adapter.test.ts +167 -0
  112. package/src/execution/__tests__/spawn-worktree-guidance.test.ts +207 -0
  113. package/src/execution/__tests__/spawned-children.test.ts +92 -0
  114. package/src/execution/__tests__/start-sync-model-guard.test.ts +150 -0
  115. package/src/execution/__tests__/stdin-writer.test.ts +462 -0
  116. package/src/execution/__tests__/stream-sink-retirement.test.ts +261 -0
  117. package/src/execution/__tests__/subagent-service-abort.test.ts +60 -0
  118. package/src/execution/__tests__/subagent-service-message-close.test.ts +629 -0
  119. package/src/execution/__tests__/subagent-service-parent-guard.test.ts +180 -0
  120. package/src/execution/__tests__/subagent-service.test.ts +788 -0
  121. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +310 -0
  122. package/src/execution/__tests__/subprocess-agent-runner.test.ts +612 -0
  123. package/src/execution/__tests__/temp-prompt.test.ts +53 -0
  124. package/src/execution/__tests__/timeout-integration.test.ts +615 -0
  125. package/src/execution/__tests__/tombstone-store.test.ts +73 -0
  126. package/src/execution/__tests__/turn-limiter-semantics.test.ts +194 -0
  127. package/src/execution/__tests__/turn-limiter.test.ts +65 -0
  128. package/src/execution/__tests__/ui-channels.test.ts +187 -0
  129. package/src/execution/__tests__/ui-interaction-model.test.ts +67 -0
  130. package/src/execution/__tests__/ui-request-handler-factory.test.ts +369 -0
  131. package/src/execution/__tests__/ui-request-handler.test.ts +204 -0
  132. package/src/execution/__tests__/ui-request-observability.test.ts +113 -0
  133. package/src/execution/__tests__/ui-request-queue.test.ts +133 -0
  134. package/src/execution/__tests__/worktree-manager.test.ts +633 -0
  135. package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +229 -0
  136. package/src/execution/__tests__/worktree-reconcile.integration.test.ts +181 -0
  137. package/src/execution/__tests__/worktree-registry.test.ts +199 -0
  138. package/src/execution/agent-registry.ts +199 -0
  139. package/src/execution/agent-result-mapper.ts +90 -0
  140. package/src/execution/alive-store.ts +119 -0
  141. package/src/execution/argv-mirror.ts +113 -0
  142. package/src/execution/best-effort.ts +38 -0
  143. package/src/execution/channel-registry-access.ts +144 -0
  144. package/src/execution/concurrency-pool.ts +116 -0
  145. package/src/execution/config.ts +165 -0
  146. package/src/execution/dialog-queue.ts +330 -0
  147. package/src/execution/engine/__tests__/common/data-dir.test.ts +78 -0
  148. package/src/execution/engine/__tests__/common/errors.test.ts +132 -0
  149. package/src/execution/engine/__tests__/common/event-journal.test.ts +177 -0
  150. package/src/execution/engine/__tests__/common/kill-chain.test.ts +192 -0
  151. package/src/execution/engine/__tests__/common/nesting-guard.test.ts +81 -0
  152. package/src/execution/engine/__tests__/common/persona-router.test.ts +123 -0
  153. package/src/execution/engine/__tests__/common/pool-manager.test.ts +154 -0
  154. package/src/execution/engine/__tests__/common/schema-emulation.test.ts +128 -0
  155. package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +28 -0
  156. package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +141 -0
  157. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +109 -0
  158. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +101 -0
  159. package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +77 -0
  160. package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +104 -0
  161. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +201 -0
  162. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +76 -0
  163. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +79 -0
  164. package/src/execution/engine/__tests__/engine-discovery.test.ts +87 -0
  165. package/src/execution/engine/__tests__/model-prompt.test.ts +197 -0
  166. package/src/execution/engine/__tests__/paths.test.ts +39 -0
  167. package/src/execution/engine/__tests__/registry.test.ts +120 -0
  168. package/src/execution/engine/__tests__/routing.test.ts +231 -0
  169. package/src/execution/engine/common/data-dir.ts +66 -0
  170. package/src/execution/engine/common/errors.ts +183 -0
  171. package/src/execution/engine/common/event-journal.ts +254 -0
  172. package/src/execution/engine/common/journal-replay.ts +62 -0
  173. package/src/execution/engine/common/kill-chain.ts +221 -0
  174. package/src/execution/engine/common/nesting-guard.ts +50 -0
  175. package/src/execution/engine/common/persona-router.ts +108 -0
  176. package/src/execution/engine/common/pool-manager.ts +226 -0
  177. package/src/execution/engine/common/schema-emulation.ts +189 -0
  178. package/src/execution/engine/common/session-view-projection.ts +51 -0
  179. package/src/execution/engine/engine-discovery.ts +65 -0
  180. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +469 -0
  181. package/src/execution/engine/engines/pi/__tests__/reader.test.ts +155 -0
  182. package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +164 -0
  183. package/src/execution/engine/engines/pi/pi-engine.ts +415 -0
  184. package/src/execution/engine/engines/pi/reader.ts +48 -0
  185. package/src/execution/engine/engines/pi/registration.ts +35 -0
  186. package/src/execution/engine/engines/pi/task-spec-mapper.ts +100 -0
  187. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +39 -0
  188. package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +150 -0
  189. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +246 -0
  190. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +228 -0
  191. package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +210 -0
  192. package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +71 -0
  193. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +127 -0
  194. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +580 -0
  195. package/src/execution/engine/engines/zcode/constants.ts +43 -0
  196. package/src/execution/engine/engines/zcode/golden-sample.ts +39 -0
  197. package/src/execution/engine/engines/zcode/launcher.ts +161 -0
  198. package/src/execution/engine/engines/zcode/parser.ts +436 -0
  199. package/src/execution/engine/engines/zcode/preparer.ts +363 -0
  200. package/src/execution/engine/engines/zcode/reader.ts +381 -0
  201. package/src/execution/engine/engines/zcode/registration.ts +37 -0
  202. package/src/execution/engine/engines/zcode/zcode-engine.ts +658 -0
  203. package/src/execution/engine/host-task-spec.ts +47 -0
  204. package/src/execution/engine/model-prompt.ts +158 -0
  205. package/src/execution/engine/paths.ts +42 -0
  206. package/src/execution/engine/port.ts +153 -0
  207. package/src/execution/engine/registry.ts +133 -0
  208. package/src/execution/engine/routing.ts +218 -0
  209. package/src/execution/engine/types.ts +309 -0
  210. package/src/execution/execute-options-mapper.ts +115 -0
  211. package/src/execution/execution-record.ts +984 -0
  212. package/src/execution/finalize-record.ts +254 -0
  213. package/src/execution/finalized-marker.ts +70 -0
  214. package/src/execution/get-state-handshake.ts +104 -0
  215. package/src/execution/host-mode.ts +56 -0
  216. package/src/execution/idle-gc.ts +47 -0
  217. package/src/execution/lifecycle-manager.ts +513 -0
  218. package/src/execution/lifecycle-predicates.ts +65 -0
  219. package/src/execution/manifest-store.ts +256 -0
  220. package/src/execution/model-config-service.ts +250 -0
  221. package/src/execution/model-resolver.ts +248 -0
  222. package/src/execution/notifier.ts +372 -0
  223. package/src/execution/notify-ledger.ts +580 -0
  224. package/src/execution/output-collector.ts +228 -0
  225. package/src/execution/path-encoding.ts +60 -0
  226. package/src/execution/pi-invocation.ts +120 -0
  227. package/src/execution/record-entry.ts +132 -0
  228. package/src/execution/record-store.ts +1265 -0
  229. package/src/execution/relay-env.ts +37 -0
  230. package/src/execution/session-context-resolver.ts +64 -0
  231. package/src/execution/session-file-gc.ts +120 -0
  232. package/src/execution/session-pending.ts +170 -0
  233. package/src/execution/session-reconstructor.ts +678 -0
  234. package/src/execution/session-runner.ts +1789 -0
  235. package/src/execution/sessions-index.ts +304 -0
  236. package/src/execution/spawn-event-adapter.ts +363 -0
  237. package/src/execution/stdin-writer.ts +198 -0
  238. package/src/execution/stream-sink.ts +126 -0
  239. package/src/execution/subagent-service.ts +2268 -0
  240. package/src/execution/subprocess-agent-runner.ts +317 -0
  241. package/src/execution/temp-prompt.ts +62 -0
  242. package/src/execution/tombstone-store.ts +72 -0
  243. package/src/execution/turn-limiter.ts +102 -0
  244. package/src/execution/types.ts +1023 -0
  245. package/src/execution/ui-channels.ts +216 -0
  246. package/src/execution/ui-interaction-model.ts +48 -0
  247. package/src/execution/ui-request-handler-factory.ts +243 -0
  248. package/src/execution/ui-request-observability.ts +81 -0
  249. package/src/execution/ui-request-queue.ts +184 -0
  250. package/src/execution/worktree-manager.ts +688 -0
  251. package/src/execution/worktree-registry.ts +279 -0
  252. package/src/index.ts +87 -0
  253. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +349 -0
  254. package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +202 -0
  255. package/src/orchestration/__tests__/agent-call-stream.test.ts +152 -0
  256. package/src/orchestration/__tests__/args-validator.test.ts +143 -0
  257. package/src/orchestration/__tests__/config-loader.test.ts +503 -0
  258. package/src/orchestration/__tests__/error-recovery-handlers.test.ts +809 -0
  259. package/src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts +404 -0
  260. package/src/orchestration/__tests__/error-recovery-serialize-failed-result.test.ts +56 -0
  261. package/src/orchestration/__tests__/error-recovery-workflow-call.test.ts +166 -0
  262. package/src/orchestration/__tests__/execute-agent-call.test.ts +451 -0
  263. package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +600 -0
  264. package/src/orchestration/__tests__/lifecycle-runid-injection.test.ts +96 -0
  265. package/src/orchestration/__tests__/lifecycle.test.ts +659 -0
  266. package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +95 -0
  267. package/src/orchestration/__tests__/review-fix-loop-scriptpath-failfast.test.ts +183 -0
  268. package/src/orchestration/__tests__/script-lint.test.ts +831 -0
  269. package/src/orchestration/__tests__/skill-discovery.test.ts +210 -0
  270. package/src/orchestration/__tests__/test-mocks.ts +197 -0
  271. package/src/orchestration/__tests__/worker-exit-without-result.test.ts +368 -0
  272. package/src/orchestration/__tests__/worker-host.test.ts +120 -0
  273. package/src/orchestration/__tests__/worker-returnmeta-passthrough.test.ts +164 -0
  274. package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +563 -0
  275. package/src/orchestration/__tests__/worker-script-builder.test.ts +309 -0
  276. package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +129 -0
  277. package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +317 -0
  278. package/src/orchestration/__tests__/workflow-script-lint-memo.test.ts +110 -0
  279. package/src/orchestration/agent-opts-resolver.ts +174 -0
  280. package/src/orchestration/args-validator.ts +127 -0
  281. package/src/orchestration/config-loader.ts +316 -0
  282. package/src/orchestration/error-recovery.ts +1018 -0
  283. package/src/orchestration/execute-agent-call.ts +256 -0
  284. package/src/orchestration/launcher.ts +455 -0
  285. package/src/orchestration/lifecycle.ts +399 -0
  286. package/src/orchestration/models/__tests__/budget.test.ts +307 -0
  287. package/src/orchestration/models/agent-call.ts +83 -0
  288. package/src/orchestration/models/budget.ts +118 -0
  289. package/src/orchestration/models/ports.ts +164 -0
  290. package/src/orchestration/models/run-runtime.ts +104 -0
  291. package/src/orchestration/models/run-spec.ts +83 -0
  292. package/src/orchestration/models/run-state.ts +44 -0
  293. package/src/orchestration/models/trace.ts +183 -0
  294. package/src/orchestration/models/types.ts +301 -0
  295. package/src/orchestration/models/workflow-run.ts +254 -0
  296. package/src/orchestration/models/workflow-script-registry.ts +35 -0
  297. package/src/orchestration/models/workflow-script.ts +117 -0
  298. package/src/orchestration/script-lint.ts +766 -0
  299. package/src/orchestration/skill-discovery.ts +135 -0
  300. package/src/orchestration/worker-handle.ts +115 -0
  301. package/src/orchestration/worker-host.ts +98 -0
  302. package/src/orchestration/worker-script-builder.ts +421 -0
  303. package/src/orchestration/workflow-files.ts +85 -0
  304. package/src/orchestration/workflow-script-registry-impl.ts +133 -0
  305. package/src/shared/__tests__/agent-ref.test.ts +34 -0
  306. package/src/shared/__tests__/meta-parser.test.ts +304 -0
  307. package/src/shared/__tests__/model-ref.test.ts +306 -0
  308. package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +288 -0
  309. package/src/shared/__tests__/resource-discovery.test.ts +749 -0
  310. package/src/shared/__tests__/resource-meta.test.ts +51 -0
  311. package/src/shared/__tests__/schema-jsonify.test.ts +81 -0
  312. package/src/shared/__tests__/timer-delay.test.ts +61 -0
  313. package/src/shared/agent-event.ts +13 -0
  314. package/src/shared/agent-ref.ts +57 -0
  315. package/src/shared/meta-parser.ts +261 -0
  316. package/src/shared/model-ref.ts +286 -0
  317. package/src/shared/resource-discovery.ts +835 -0
  318. package/src/shared/resource-meta.ts +65 -0
  319. package/src/shared/schema-env.ts +44 -0
  320. package/src/shared/schema-jsonify.ts +58 -0
  321. package/src/shared/timer-delay.ts +54 -0
  322. package/src/shared/xml-injection.ts +35 -0
  323. package/workflows/README.md +81 -0
  324. package/workflows/_shared/agent-refs.cjs +40 -0
  325. package/workflows/chain.js +137 -0
  326. package/workflows/map-reduce.js +180 -0
  327. package/workflows/parallel.js +154 -0
  328. package/workflows/review-fix-loop-utils.cjs +1542 -0
  329. package/workflows/review-fix-loop.js +1605 -0
  330. package/workflows/scatter-gather.js +184 -0
@@ -0,0 +1,228 @@
1
+ // preparer.test.ts —— 池目录 SSOT / 原子写 / mtime 免重写 / 无 plugins 块 / 凭据与模型
2
+ // 前置错误(验收 3)。凭据源 = v2 config 单源(2026-08-25 拍板:不读
3
+ // ~/.zcode/cli/config.json——GUI 不管理该文件,可能残留历史验证配置)。
4
+
5
+ import * as fs from "node:fs";
6
+ import * as os from "node:os";
7
+ import * as path from "node:path";
8
+
9
+ import { beforeEach, describe, expect, it } from "vitest";
10
+
11
+ import { resolvePoolDir } from "../../../paths.ts";
12
+ import {
13
+ ZcodePrepareError,
14
+ computeZcodePoolKey,
15
+ listZcodeModels,
16
+ prepareZcodeHome,
17
+ resolveZcodeModelRef,
18
+ } from "../preparer.ts";
19
+
20
+ let tmpRoot: string;
21
+ let dataDir: string;
22
+ let v2Path: string;
23
+
24
+ function writeJson(p: string, v: unknown): void {
25
+ fs.mkdirSync(path.dirname(p), { recursive: true });
26
+ fs.writeFileSync(p, JSON.stringify(v, null, 2));
27
+ }
28
+
29
+ const PROVIDER_A = "builtin:bigmodel-coding-plan";
30
+ const PROVIDER_B = "e512d53e-test-provider";
31
+
32
+ function seedSources(): void {
33
+ writeJson(v2Path, {
34
+ provider: {
35
+ [PROVIDER_A]: { options: { apiKey: "key-a", baseURL: "https://a.example" }, models: { "GLM-5.3": {}, "GLM-5.2": {} } },
36
+ [PROVIDER_B]: { name: "test-router", options: { apiKey: "key-b", baseURL: "https://b.example" }, models: { "mimo-v2.5-pro": {} } },
37
+ "no-key-provider": { options: { baseURL: "https://x.example" }, models: { "M1": {} } },
38
+ },
39
+ });
40
+ }
41
+
42
+ beforeEach(() => {
43
+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "zcode-preparer-"));
44
+ dataDir = path.join(tmpRoot, "data");
45
+ v2Path = path.join(tmpRoot, "v2-config.json");
46
+ seedSources();
47
+ });
48
+
49
+ describe("resolveZcodeModelRef(v2 单源)", () => {
50
+ it("显式全名解析 + 规范化", () => {
51
+ expect(resolveZcodeModelRef(`${PROVIDER_B}/mimo-v2.5-pro`, { v2ConfigPath: v2Path })).toBe(
52
+ `${PROVIDER_B}/mimo-v2.5-pro`,
53
+ );
54
+ });
55
+
56
+ it("短名按默认 provider(builtin:bigmodel-coding-plan)解析", () => {
57
+ expect(resolveZcodeModelRef("GLM-5.3", { v2ConfigPath: v2Path })).toBe(
58
+ `${PROVIDER_A}/GLM-5.3`,
59
+ );
60
+ });
61
+
62
+ it("未指定时落官方兜底(不受任何本机 CLI 配置影响)", () => {
63
+ expect(resolveZcodeModelRef(undefined, { v2ConfigPath: v2Path })).toBe(
64
+ `${PROVIDER_A}/GLM-5.3`,
65
+ );
66
+ });
67
+
68
+ it("未知模型 → model_not_available(列该 provider 可用模型)", () => {
69
+ try {
70
+ resolveZcodeModelRef(`${PROVIDER_A}/nope`, { v2ConfigPath: v2Path });
71
+ expect.unreachable("should throw");
72
+ } catch (err) {
73
+ expect(err).toBeInstanceOf(ZcodePrepareError);
74
+ const e = err as ZcodePrepareError;
75
+ expect(e.code).toBe("model_not_available");
76
+ expect(e.message).toContain("GLM-5.3, GLM-5.2");
77
+ }
78
+ });
79
+
80
+ it("未知 provider → model_not_available(列带凭据 provider)", () => {
81
+ try {
82
+ resolveZcodeModelRef("ghost/m", { v2ConfigPath: v2Path });
83
+ expect.unreachable("should throw");
84
+ } catch (err) {
85
+ expect((err as ZcodePrepareError).code).toBe("model_not_available");
86
+ expect((err as ZcodePrepareError).message).toContain(PROVIDER_A);
87
+ expect((err as ZcodePrepareError).message).toContain(PROVIDER_B);
88
+ }
89
+ });
90
+
91
+ it("provider 存在但无 apiKey → engine_credential_missing", () => {
92
+ try {
93
+ resolveZcodeModelRef("no-key-provider/M1", { v2ConfigPath: v2Path });
94
+ expect.unreachable("should throw");
95
+ } catch (err) {
96
+ expect((err as ZcodePrepareError).code).toBe("engine_credential_missing");
97
+ }
98
+ });
99
+
100
+ it("v2 无任何带 apiKey 的 provider → engine_credential_missing(指向配置说明)", () => {
101
+ writeJson(v2Path, { provider: {} });
102
+ try {
103
+ resolveZcodeModelRef(undefined, { v2ConfigPath: v2Path });
104
+ expect.unreachable("should throw");
105
+ } catch (err) {
106
+ const e = err as ZcodePrepareError;
107
+ expect(e.code).toBe("engine_credential_missing");
108
+ expect(e.message).toContain("ZCode 桌面端");
109
+ expect(e.message).toContain("docs/research/agent-engine-zcode.md");
110
+ }
111
+ });
112
+ });
113
+
114
+ describe("listZcodeModels(U7 可发现性)", () => {
115
+ it("聚合 v2 带凭据 provider × models(含 name 拼接),无凭据/空清单过滤", () => {
116
+ const models = listZcodeModels({ v2ConfigPath: v2Path });
117
+ const ids = models.map((m) => m.id);
118
+ expect(ids).toContain(`${PROVIDER_A}/GLM-5.3`);
119
+ expect(ids).toContain(`${PROVIDER_A}/GLM-5.2`);
120
+ expect(ids).toContain(`${PROVIDER_B}/mimo-v2.5-pro`);
121
+ // 无凭据 provider 不进清单
122
+ expect(ids.some((id) => id.startsWith("no-key-provider/"))).toBe(false);
123
+ // name = "<provider.name> · <model>"(v2 有 name 字段时)
124
+ const withName = models.find((m) => m.id === `${PROVIDER_B}/mimo-v2.5-pro`);
125
+ expect(withName?.name).toBe("test-router · mimo-v2.5-pro");
126
+ });
127
+
128
+ it("v2 不可读 → 空清单(fail-safe)", () => {
129
+ expect(listZcodeModels({ v2ConfigPath: path.join(tmpRoot, "absent.json") })).toEqual([]);
130
+ });
131
+ });
132
+
133
+ describe("computeZcodePoolKey", () => {
134
+ it("provider 特殊字符安全化 + model 短名保留点号(zsub homePoolDir 同构)", () => {
135
+ expect(computeZcodePoolKey("builtin:bigmodel-coding-plan/GLM-5.3")).toBe(
136
+ "home-builtin-bigmodel-coding-plan-GLM-5.3",
137
+ );
138
+ expect(computeZcodePoolKey("router/mimo-v2.5-pro")).toBe("home-router-mimo-v2.5-pro");
139
+ });
140
+ });
141
+
142
+ describe("prepareZcodeHome(验收 3)", () => {
143
+ it("池目录 = resolvePoolDir SSOT,config.json 原子写且无 plugins 块", () => {
144
+ const prepared = prepareZcodeHome({
145
+ engineDataDir: dataDir,
146
+ modelRef: `${PROVIDER_A}/GLM-5.3`,
147
+ sources: { v2ConfigPath: v2Path },
148
+ });
149
+ expect(prepared.wroteConfig).toBe(true);
150
+ // 池目录必须与 paths.ts SSOT 同源(禁自拼)
151
+ expect(prepared.homeDir).toBe(resolvePoolDir(dataDir, "zcode", prepared.poolKey));
152
+ expect(prepared.poolKey).toBe("home-builtin-bigmodel-coding-plan-GLM-5.3");
153
+
154
+ const written = JSON.parse(fs.readFileSync(prepared.configPath, "utf8")) as Record<string, unknown>;
155
+ expect(written["model"]).toEqual({ main: `${PROVIDER_A}/GLM-5.3` });
156
+ expect(Object.keys(written["provider"] as Record<string, unknown>)).toEqual([PROVIDER_A]);
157
+ // 第二重门禁:刻意不写 plugins 块(防递归 + 不加载宿主插件)
158
+ expect("plugins" in written).toBe(false);
159
+ // 原子写:无 tmp 残留
160
+ const leftovers = fs.readdirSync(path.dirname(prepared.configPath)).filter((f) => f.includes(".tmp-"));
161
+ expect(leftovers).toEqual([]);
162
+ // 只写目标 provider(每池单 provider 单模型,凭据落盘面最小)
163
+ const providerEntry = (written["provider"] as Record<string, { options?: { apiKey?: string } }>)[PROVIDER_A]!;
164
+ expect(providerEntry.options?.apiKey).toBe("key-a");
165
+ });
166
+
167
+ it("mtime 比对免重写:源未变时第二次 prepare 零写入", () => {
168
+ const opts = {
169
+ engineDataDir: dataDir,
170
+ modelRef: `${PROVIDER_A}/GLM-5.3`,
171
+ sources: { v2ConfigPath: v2Path },
172
+ };
173
+ const first = prepareZcodeHome(opts);
174
+ expect(first.wroteConfig).toBe(true);
175
+ const statAfterFirst = fs.statSync(first.configPath);
176
+ const second = prepareZcodeHome(opts);
177
+ expect(second.wroteConfig).toBe(false);
178
+ expect(fs.statSync(second.configPath).mtimeMs).toBe(statAfterFirst.mtimeMs);
179
+ });
180
+
181
+ it("源 config 变新(mtime 推进)触发重写(凭据刷新传播)", async () => {
182
+ const opts = {
183
+ engineDataDir: dataDir,
184
+ modelRef: `${PROVIDER_A}/GLM-5.3`,
185
+ sources: { v2ConfigPath: v2Path },
186
+ };
187
+ prepareZcodeHome(opts);
188
+ // 源 mtime 推到未来(模拟桌面端刷新 apiKey)
189
+ const future = new Date(Date.now() + 10_000);
190
+ fs.utimesSync(v2Path, future, future);
191
+ const again = prepareZcodeHome(opts);
192
+ expect(again.wroteConfig).toBe(true);
193
+ });
194
+
195
+ it("池 config 损坏(torn write 形态)时重建", () => {
196
+ const opts = {
197
+ engineDataDir: dataDir,
198
+ modelRef: `${PROVIDER_A}/GLM-5.3`,
199
+ sources: { v2ConfigPath: v2Path },
200
+ };
201
+ const first = prepareZcodeHome(opts);
202
+ fs.writeFileSync(first.configPath, "{ torn", "utf8");
203
+ const again = prepareZcodeHome(opts);
204
+ expect(again.wroteConfig).toBe(true);
205
+ expect(() => JSON.parse(fs.readFileSync(again.configPath, "utf8"))).not.toThrow();
206
+ });
207
+
208
+ it("v2 注册表内非默认 provider(如自定义 UUID provider)也能建池", () => {
209
+ const prepared = prepareZcodeHome({
210
+ engineDataDir: dataDir,
211
+ modelRef: `${PROVIDER_B}/mimo-v2.5-pro`,
212
+ sources: { v2ConfigPath: v2Path },
213
+ });
214
+ const written = JSON.parse(fs.readFileSync(prepared.configPath, "utf8")) as {
215
+ provider: Record<string, { options?: { apiKey?: string } }>;
216
+ };
217
+ expect(written.provider[PROVIDER_B]!.options?.apiKey).toBe("key-b");
218
+ });
219
+
220
+ it("模型引用在 v2 不存在 → model_not_available", () => {
221
+ try {
222
+ prepareZcodeHome({ engineDataDir: dataDir, modelRef: "ghost/m", sources: { v2ConfigPath: v2Path } });
223
+ expect.unreachable("should throw");
224
+ } catch (err) {
225
+ expect((err as ZcodePrepareError).code).toBe("model_not_available");
226
+ }
227
+ });
228
+ });
@@ -0,0 +1,210 @@
1
+ // reader.test.ts —— sqlite 只读 SessionView(验收 4 的 mock 半边:真实 node:sqlite 建库
2
+ // → turns/usage/toolCalls 派生;db 缺失/表漂移 → 结构化错误供降级)。真机半边(实录池
3
+ // 内 db)在 zcode-engine.live.test.ts。
4
+
5
+ import * as fs from "node:fs";
6
+ import * as os from "node:os";
7
+ import * as path from "node:path";
8
+
9
+ import { beforeAll, beforeEach, describe, expect, it } from "vitest";
10
+
11
+ import { readZcodeSessionView, ZcodeReaderError } from "../reader.ts";
12
+
13
+ let tmpDir: string;
14
+ let dbPath: string;
15
+
16
+ // 建出与 zcode 0.16.5 同形的三表最小 schema(列裁剪到 reader 消费面)
17
+ async function createDb(file: string): Promise<void> {
18
+ const { DatabaseSync } = (await import("node:sqlite")) as { DatabaseSync: new (p: string) => unknown };
19
+ type Db = {
20
+ exec: (s: string) => void;
21
+ prepare: (s: string) => { run: (...a: unknown[]) => void };
22
+ close: () => void;
23
+ };
24
+ const db = new DatabaseSync(file) as unknown as Db;
25
+ db.exec(
26
+ "CREATE TABLE session (id TEXT PRIMARY KEY, time_created INTEGER);" +
27
+ "CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, sequence INTEGER, data TEXT);" +
28
+ "CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT, sequence INTEGER, data TEXT);",
29
+ );
30
+ const insertMessage = db.prepare("INSERT INTO message (id, session_id, sequence, data) VALUES (?, ?, ?, ?)");
31
+ const insertPart = db.prepare("INSERT INTO part (id, message_id, session_id, sequence, data) VALUES (?, ?, ?, ?, ?)");
32
+
33
+ // session 1(目标):user prompt + assistant 两轮(text/reasoning/tool/step-finish×2)
34
+ db.prepare("INSERT INTO session (id, time_created) VALUES (?, ?)").run("sess_target", 2000);
35
+ insertMessage.run("msg_user", "sess_target", 0, JSON.stringify({ role: "user" }));
36
+ insertPart.run("part_user_text", "msg_user", "sess_target", 0, JSON.stringify({ type: "text", text: "the task" }));
37
+
38
+ insertMessage.run("msg_asst", "sess_target", 1, JSON.stringify({ role: "assistant" }));
39
+ insertPart.run("p0", "msg_asst", "sess_target", 0, JSON.stringify({ type: "step-start" }));
40
+ insertPart.run("p1", "msg_asst", "sess_target", 1, JSON.stringify({ type: "reasoning", text: "thinking hard" }));
41
+ insertPart.run(
42
+ "p2",
43
+ "msg_asst",
44
+ "sess_target",
45
+ 2,
46
+ JSON.stringify({
47
+ type: "tool",
48
+ tool: "Bash",
49
+ state: JSON.stringify({ status: "completed", input: { command: "ls" }, output: "file-a\nfile-b" }),
50
+ }),
51
+ );
52
+ insertPart.run(
53
+ "p3",
54
+ "msg_asst",
55
+ "sess_target",
56
+ 3,
57
+ JSON.stringify({
58
+ type: "step-finish",
59
+ reason: "stop",
60
+ cost: 0,
61
+ tokens: { total: 110, input: 100, output: 10, reasoning: 0, cache: { read: 5, write: 0 } },
62
+ }),
63
+ );
64
+ // 第二轮(同 assistant message 内第二个 step 段)
65
+ insertPart.run("p4", "msg_asst", "sess_target", 4, JSON.stringify({ type: "text", text: "final answer" }));
66
+ insertPart.run(
67
+ "p5",
68
+ "msg_asst",
69
+ "sess_target",
70
+ 5,
71
+ JSON.stringify({
72
+ type: "step-finish",
73
+ reason: "stop",
74
+ cost: 0.5,
75
+ tokens: { total: 60, input: 50, output: 10, reasoning: 0, cache: { read: 0, write: 0 } },
76
+ }),
77
+ );
78
+
79
+ // session 2(更早):验证「缺省取最新」与定向读取互不干扰
80
+ db.prepare("INSERT INTO session (id, time_created) VALUES (?, ?)").run("sess_older", 1000);
81
+ insertMessage.run("msg_old", "sess_older", 0, JSON.stringify({ role: "assistant" }));
82
+ insertPart.run("part_old", "msg_old", "sess_older", 0, JSON.stringify({ type: "text", text: "old turn" }));
83
+ insertPart.run(
84
+ "part_old2",
85
+ "msg_old",
86
+ "sess_older",
87
+ 1,
88
+ JSON.stringify({ type: "step-finish", tokens: { input: 1, output: 1, cache: {} } }),
89
+ );
90
+ db.close();
91
+ }
92
+
93
+ beforeAll(async () => {
94
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "zcode-reader-"));
95
+ dbPath = path.join(tmpDir, "db.sqlite");
96
+ await createDb(dbPath);
97
+ });
98
+
99
+ describe("readZcodeSessionView:native 读取", () => {
100
+ it("turns 派生:两轮闭合、text/thinking/toolCalls/usage 齐备(验收 4)", async () => {
101
+ const view = await readZcodeSessionView(dbPath, "sess_target");
102
+ expect(view.engineId).toBe("zcode");
103
+ expect(view.source).toBe("native");
104
+ expect(view.sessionId).toBe("sess_target");
105
+ expect(view.turns).toHaveLength(2);
106
+
107
+ const [t1, t2] = view.turns!;
108
+ expect(t1!.text).toBe("");
109
+ expect(t1!.thinking).toBe("thinking hard");
110
+ expect(t1!.toolCalls).toHaveLength(1);
111
+ expect(t1!.toolCalls[0]!.toolName).toBe("Bash");
112
+ expect(t1!.toolCalls[0]!.args).toEqual({ command: "ls" });
113
+ expect(t1!.toolCalls[0]!.result).toEqual({ content: ["file-a\nfile-b"] });
114
+ expect(t1!.toolCalls[0]!.isError).toBeUndefined(); // status completed
115
+ expect(t1!.closed).toBe(true);
116
+
117
+ expect(t2!.text).toBe("final answer");
118
+ expect(t2!.closed).toBe(true);
119
+
120
+ // usage 聚合 = 两轮 usageDelta 之和(cost 累计第二段的 0.5)
121
+ expect(view.usage).toEqual({ input: 150, output: 20, cacheRead: 5, cacheWrite: 0, cost: 0.5, total: 175 });
122
+ });
123
+
124
+ it("缺省 sessionId 取池内最新 session(time_created DESC)", async () => {
125
+ const view = await readZcodeSessionView(dbPath);
126
+ expect(view.sessionId).toBe("sess_target");
127
+ });
128
+
129
+ it("tool 状态非 completed 标 isError", async () => {
130
+ // 单独建一个带失败工具调用的 session,避免污染上面的聚合断言
131
+ const failDb = path.join(tmpDir, "fail.sqlite");
132
+ await createDb(failDb);
133
+ const { DatabaseSync } = (await import("node:sqlite")) as { DatabaseSync: new (p: string) => unknown };
134
+ type Db = { prepare: (s: string) => { run: (...a: unknown[]) => void }; close: () => void };
135
+ const db = new DatabaseSync(failDb) as unknown as Db;
136
+ db.prepare("INSERT INTO session (id, time_created) VALUES (?, ?)").run("sess_fail", 3000);
137
+ db
138
+ .prepare("INSERT INTO message (id, session_id, sequence, data) VALUES (?, ?, ?, ?)")
139
+ .run("msg_f", "sess_fail", 0, JSON.stringify({ role: "assistant" }));
140
+ db
141
+ .prepare("INSERT INTO part (id, message_id, session_id, sequence, data) VALUES (?, ?, ?, ?, ?)")
142
+ .run(
143
+ "pf",
144
+ "msg_f",
145
+ "sess_fail",
146
+ 0,
147
+ JSON.stringify({
148
+ type: "tool",
149
+ tool: "Edit",
150
+ state: JSON.stringify({ status: "error", input: { file: "a" }, output: "conflict" }),
151
+ }),
152
+ );
153
+ db.close();
154
+ const view = await readZcodeSessionView(failDb, "sess_fail");
155
+ expect(view.turns[0]!.toolCalls[0]!.isError).toBe(true);
156
+ });
157
+ });
158
+
159
+ describe("readZcodeSessionView:结构化错误(供降级②③级,验收 4 负例)", () => {
160
+ beforeEach(() => {
161
+ // 无共享状态需重置;保留钩子位置说明负例组意图
162
+ });
163
+
164
+ it("db 文件缺失 → engine_session_read_failed(detail 含路径)", async () => {
165
+ const missing = path.join(tmpDir, "nope.sqlite");
166
+ try {
167
+ await readZcodeSessionView(missing, "sess_x");
168
+ expect.unreachable("should throw");
169
+ } catch (err) {
170
+ expect(err).toBeInstanceOf(ZcodeReaderError);
171
+ const e = err as ZcodeReaderError;
172
+ expect(e.code).toBe("engine_session_read_failed");
173
+ expect(e.detail).toContain(missing);
174
+ expect(e.message).toContain("降级");
175
+ }
176
+ });
177
+
178
+ it("表结构漂移(缺 part 表)→ 结构化错误含漂移提示", async () => {
179
+ const drifted = path.join(tmpDir, "drifted.sqlite");
180
+ const { DatabaseSync } = (await import("node:sqlite")) as { DatabaseSync: new (p: string) => unknown };
181
+ type Db = { exec: (s: string) => void; close: () => void };
182
+ const db = new DatabaseSync(drifted) as unknown as Db;
183
+ // 只建 session/message(zcode 升级把 part 改名的形态);塞一行 session 让定位
184
+ // 通过、失败必然发生在 part 查询(表缺失)
185
+ db.exec(
186
+ "CREATE TABLE session (id TEXT PRIMARY KEY, time_created INTEGER);" +
187
+ "CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, sequence INTEGER, data TEXT);" +
188
+ "INSERT INTO session (id, time_created) VALUES ('sess_d', 1);",
189
+ );
190
+ db.close();
191
+ try {
192
+ await readZcodeSessionView(drifted);
193
+ expect.unreachable("should throw");
194
+ } catch (err) {
195
+ const e = err as ZcodeReaderError;
196
+ expect(e.code).toBe("engine_session_read_failed");
197
+ expect(e.message).toContain("漂移");
198
+ expect(e.message).toContain("golden");
199
+ }
200
+ });
201
+
202
+ it("session 不存在 → 结构化错误(不静默空视图)", async () => {
203
+ try {
204
+ await readZcodeSessionView(dbPath, "sess_ghost");
205
+ expect.unreachable("should throw");
206
+ } catch (err) {
207
+ expect((err as ZcodeReaderError).detail).toContain("sess_ghost");
208
+ }
209
+ });
210
+ });
@@ -0,0 +1,71 @@
1
+ // registration.test.ts —— 注册表接线(验收 6):'zcode' 可经 getEngine 获取、幂等
2
+ // 覆盖、engineDataDir 默认走 common/data-dir SSOT。clearEngines 隔离全局注册表状态。
3
+
4
+ import { afterEach, describe, expect, it, vi } from "vitest";
5
+
6
+ // u0-data-discovery 注入化后 data-dir 回退值来自 HostServices.dataRoot() 端口——
7
+ // 用例内 configureCore 假宿主控制端口态,afterEach reset 防跨用例泄漏
8
+ import { configureCore, resetCoreForTests } from "../../../../../core/host-services.ts";
9
+
10
+ import { clearEngines, getEngine, hasEngine, listEngines } from "../../../registry.ts";
11
+ import { createZcodeEngine, registerZcodeEngine } from "../registration.ts";
12
+
13
+ const FAKE_DATA_ROOT = "/fake-registration-data-root";
14
+
15
+ afterEach(() => {
16
+ clearEngines();
17
+ resetCoreForTests();
18
+ vi.restoreAllMocks();
19
+ });
20
+
21
+ describe("registerZcodeEngine", () => {
22
+ it("登记后 getEngine('zcode') 可用,id/capabilities 正确", () => {
23
+ registerZcodeEngine(() => "/tmp/data");
24
+ expect(hasEngine("zcode")).toBe(true);
25
+ expect(listEngines()).toContain("zcode");
26
+ const engine = getEngine("zcode");
27
+ expect(engine.id).toBe("zcode");
28
+ expect(engine.capabilities().schemaEnforcement).toBe("emulated");
29
+ });
30
+
31
+ it("幂等:重复注册覆盖不堆积(listEngines 单条)", () => {
32
+ registerZcodeEngine(() => "/tmp/data");
33
+ registerZcodeEngine(() => "/tmp/data2");
34
+ expect(listEngines().filter((id) => id === "zcode")).toHaveLength(1);
35
+ // 覆盖后单例按新工厂重建(engineDataDir 已换)
36
+ expect(hasEngine("zcode")).toBe(true);
37
+ });
38
+
39
+ it("createZcodeEngine DI 工厂:deps 直达引擎", () => {
40
+ const engine = createZcodeEngine({ engineDataDir: () => "/tmp/x" });
41
+ expect(engine.id).toBe("zcode");
42
+ });
43
+ });
44
+
45
+ describe("engineDataDir 默认通道(common/data-dir SSOT)", () => {
46
+ it("缺省经 getEngineDataDir 解析:env 优先,缺失回落宿主数据根(warn 一次)", async () => {
47
+ // warn 断言走 getEngineDataDir 自带的 DI warn 参数——缺省 warn 通道是
48
+ // core logger facade(configureCore 后经 pi-host 桥接落文件,不经
49
+ // console.warn),spy console 永远收不到且会让 logger 落文件产生测试副作用。
50
+ const { getEngineDataDir, resetDataDirWarnForTests } = await import("../../../common/data-dir.ts");
51
+ const warns: string[] = [];
52
+ const prev = process.env["XYZ_AGENT_DATA_DIR"];
53
+ delete process.env["XYZ_AGENT_DATA_DIR"];
54
+ try {
55
+ resetCoreForTests();
56
+ configureCore({ dataRoot: () => FAKE_DATA_ROOT, log: () => {} });
57
+ resetDataDirWarnForTests();
58
+ // 回退分支:无 env → HostServices.dataRoot()(假宿主值)+ warn 一次
59
+ expect(getEngineDataDir(process.env, (m) => warns.push(m))).toBe(FAKE_DATA_ROOT);
60
+ expect(warns).toHaveLength(1);
61
+ expect(warns[0]).toContain("XYZ_AGENT_DATA_DIR");
62
+ // env 分支:显式注入即取 env 值(透传链证据见 common/data-dir.ts 文件头)
63
+ process.env["XYZ_AGENT_DATA_DIR"] = "/from-host";
64
+ expect(getEngineDataDir(process.env, (m) => warns.push(m))).toBe("/from-host");
65
+ expect(warns).toHaveLength(1);
66
+ } finally {
67
+ if (prev !== undefined) process.env["XYZ_AGENT_DATA_DIR"] = prev;
68
+ else delete process.env["XYZ_AGENT_DATA_DIR"];
69
+ }
70
+ });
71
+ });
@@ -0,0 +1,127 @@
1
+ // zcode-engine.live.test.ts —— 端到端真机门(验收 5):真实 zcode CLI + 真实凭据 +
2
+ // 真实 LLM 调用。手动门(设计 §3.3.8 conformance run 层同构):默认 skip,跑法:
3
+ //
4
+ // cd extensions/universal/subagent-workflow
5
+ // ENGINE_CONFORMANCE_LIVE=1 ZCODE_E2E_MODEL='<provider/model>' pnpm vitest run src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts
6
+ //
7
+ // ZCODE_E2E_MODEL 缺省值是采集 golden 样本的本机 provider(v2 config 实测带 apiKey、
8
+ // 公网可达);换机器跑时用 env 覆盖为本机可用模型。池数据落 /tmp(跑完由本文件
9
+ // afterAll 清理),不污染真实 ~/.zcode。
10
+
11
+ import { execFileSync } from "node:child_process";
12
+ import * as fs from "node:fs";
13
+ import * as os from "node:os";
14
+ import * as path from "node:path";
15
+
16
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
17
+
18
+ import { resolvePoolDir } from "../../../paths.ts";
19
+ import { ZcodeEngine } from "../zcode-engine.ts";
20
+
21
+ const LIVE = process.env["ENGINE_CONFORMANCE_LIVE"] === "1";
22
+ const E2E_MODEL = process.env["ZCODE_E2E_MODEL"] ?? "e512d53e-0bfc-4915-9081-860d4aa13cd0/mimo-v2.5-pro";
23
+ const DATA_ROOT = path.join(fs.realpathSync(os.tmpdir()), "zcode-p3-e2e-data");
24
+ const WORK_CWD = path.join(fs.realpathSync(os.tmpdir()), "zcode-p3-e2e-cwd");
25
+
26
+ describe.skipIf(!LIVE)("ZcodeEngine 端到端真机(真实 LLM 调用)", () => {
27
+ let engine: ZcodeEngine;
28
+
29
+ beforeAll(() => {
30
+ fs.mkdirSync(WORK_CWD, { recursive: true });
31
+ engine = new ZcodeEngine({ engineDataDir: () => DATA_ROOT });
32
+ });
33
+
34
+ afterAll(() => {
35
+ // 用完清理:池数据 + 任务 cwd(保持 /tmp 干净,实录/验证不留残留)
36
+ for (const dir of [DATA_ROOT, WORK_CWD]) {
37
+ try {
38
+ fs.rmSync(dir, { recursive: true, force: true });
39
+ } catch {
40
+ // 尽力清理
41
+ }
42
+ }
43
+ });
44
+
45
+ it("probe:二进制/版本/golden 三项全过", async () => {
46
+ const report = await engine.probe();
47
+ expect(report.ok).toBe(true);
48
+ expect(report.engineVersion).toMatch(/^0\.\d+\.\d+$/);
49
+ }, 60_000);
50
+
51
+ it("run:schema 任务全链成功(隔离 HOME 新 session + outcome + read①级)", async () => {
52
+ const { handle, outcome } = await engine.run(
53
+ {
54
+ task: 'Verify this arithmetic check: 2 + 2 = 4. If it is correct the verdict must be "ok", otherwise "bad".',
55
+ slug: "e2e-schema",
56
+ model: E2E_MODEL,
57
+ cwd: WORK_CWD,
58
+ schema: {
59
+ type: "object",
60
+ properties: { verdict: { type: "string", enum: ["ok", "bad"] } },
61
+ required: ["verdict"],
62
+ additionalProperties: false,
63
+ },
64
+ },
65
+ { taskId: "sa-live-schema", poolKey: "" },
66
+ );
67
+
68
+ // outcome 正确
69
+ expect(outcome.error).toBeUndefined();
70
+ expect(outcome.exitCode).toBe(0);
71
+ expect(outcome.content).toContain('"verdict"');
72
+ expect(outcome.usage).toBeDefined();
73
+ expect(outcome.usage!.input).toBeGreaterThan(0);
74
+ expect(outcome.sessionId).toMatch(/^sess_/);
75
+ // schema 仿真(D4 emulated 侧):公共层三级容错提取 + ajv 校验产出 parsedOutput
76
+ expect(outcome.parsedOutput).toEqual({ verdict: "ok" });
77
+
78
+ // 隔离 HOME 有新 session(db.sqlite 落池内,非真实 ~/.zcode)——路径经 resolvePoolDir
79
+ // SSOT(poolKey 里的 '.' 会被 sanitizeSeg 编码为 '-',手工 join 会拼错目录)
80
+ const dbPath = path.join(resolvePoolDir(DATA_ROOT, "zcode", handle.data.poolKey), ".zcode", "cli", "db", "db.sqlite");
81
+ expect(fs.existsSync(dbPath)).toBe(true);
82
+ expect(fs.statSync(dbPath).size).toBeGreaterThan(0);
83
+
84
+ // read(handle) 第①级可读:turns 非空(验收 5 的 read 断言)
85
+ const view = await engine.read(handle);
86
+ expect(view.source).toBe("native");
87
+ expect(view.sessionId).toBe(outcome.sessionId);
88
+ expect(view.turns.length).toBeGreaterThanOrEqual(1);
89
+ expect(view.turns[0]!.text).toContain("verdict");
90
+ }, 300_000);
91
+
92
+ it("abort:长任务中途取消 → 杀链合成终态、无僵尸进程", async () => {
93
+ const controller = new AbortController();
94
+ const runPromise = engine.run(
95
+ {
96
+ task:
97
+ "Write an extremely detailed 5000-word technical essay about distributed systems consistency models. Do not stop early.",
98
+ slug: "e2e-abort",
99
+ model: E2E_MODEL,
100
+ cwd: WORK_CWD,
101
+ },
102
+ { taskId: "sa-live-abort", poolKey: "", signal: controller.signal },
103
+ );
104
+ // 等 spawn 发生(prompt 已进 argv),再中途 abort
105
+ await new Promise((r) => setTimeout(r, 4_000));
106
+ controller.abort();
107
+ const { outcome } = await runPromise;
108
+
109
+ expect(outcome.exitCode).toBeNull();
110
+ expect(outcome.error).toContain("SIGTERM");
111
+ // 无僵尸进程:--cwd 指向本测试专用 tmp 目录的 zcode 进程应已消失
112
+ const leftovers = listZcodeProcessesForCwd(WORK_CWD);
113
+ expect(leftovers).toEqual([]);
114
+ }, 120_000);
115
+ });
116
+
117
+ /** 扫系统进程表:--cwd 锚定到指定目录的 zcode CLI 进程(僵尸检测)。 */
118
+ function listZcodeProcessesForCwd(cwd: string): string[] {
119
+ try {
120
+ const out = execFileSync("ps", ["-eo", "command"], { encoding: "utf8" });
121
+ return out
122
+ .split("\n")
123
+ .filter((line) => line.includes("zcode.cjs") && line.includes(`--cwd ${cwd}`));
124
+ } catch {
125
+ return [];
126
+ }
127
+ }