@zhushanwen/subagent-core 0.2.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 (347) hide show
  1. package/README.md +45 -2
  2. package/agents/analyst.md +60 -0
  3. package/agents/coder.md +69 -0
  4. package/agents/debugger.md +66 -0
  5. package/agents/doc-reviewer.md +49 -0
  6. package/agents/explorer.md +63 -0
  7. package/agents/general-purpose.md +32 -0
  8. package/agents/orchestrator.md +61 -0
  9. package/agents/planner.md +53 -0
  10. package/agents/researcher.md +67 -0
  11. package/agents/reviewer.md +73 -0
  12. package/dist/chunk-43ONBFZX.js +240 -0
  13. package/dist/chunk-APZY4IME.js +27 -0
  14. package/dist/chunk-V3VHZ2VX.js +59 -0
  15. package/dist/execution/engine/engines/zcode/constants.cjs +62 -9
  16. package/dist/execution/engine/engines/zcode/constants.d.cts +116 -12
  17. package/dist/execution/engine/engines/zcode/constants.d.ts +116 -12
  18. package/dist/execution/engine/engines/zcode/constants.js +39 -7
  19. package/dist/execution/engine/engines/zcode/reader.d.cts +2 -1
  20. package/dist/execution/engine/engines/zcode/reader.d.ts +2 -1
  21. package/dist/execution/engine/engines/zcode/reader.js +4 -234
  22. package/dist/execution/engine/paths.js +7 -19
  23. package/dist/index.cjs +18234 -1277
  24. package/dist/index.d.cts +5646 -673
  25. package/dist/index.d.ts +5646 -673
  26. package/dist/index.js +17828 -1277
  27. package/dist/{types-BxyAidGf.d.cts → types-Dv4QhSJ_.d.cts} +678 -112
  28. package/dist/{types-BxyAidGf.d.ts → types-Dv4QhSJ_.d.ts} +678 -112
  29. package/package.json +7 -4
  30. package/src/__tests__/agent-opts-resolver-schema-prompt.test.ts +0 -1
  31. package/src/__tests__/append-system-prompt-assembly.test.ts +8 -7
  32. package/src/__tests__/fr4-get-state-handshake.test.ts +2 -2
  33. package/src/__tests__/m2-append-content-probe.test.ts +0 -1
  34. package/src/__tests__/manifest-store.test.ts +10 -9
  35. package/src/__tests__/record-store-cache.test.ts +0 -2
  36. package/src/__tests__/record-store-index.test.ts +1 -2
  37. package/src/__tests__/review-fix-loop-script.test.ts +93 -3
  38. package/src/__tests__/review-fix-loop-utils.test.ts +31 -10
  39. package/src/__tests__/robustness-low-batch1.test.ts +6 -5
  40. package/src/__tests__/robustness-medium-batch1.test.ts +2 -2
  41. package/src/__tests__/robustness-medium-batch2.test.ts +17 -6
  42. package/src/__tests__/robustness-medium-batch4.test.ts +2 -2
  43. package/src/__tests__/session-runner.test.ts +1 -1
  44. package/src/__tests__/smoke.test.ts +9 -2
  45. package/src/core/__tests__/host-services.test.ts +2 -2
  46. package/src/core/__tests__/logger.test.ts +1 -1
  47. package/src/core/error-message.ts +9 -0
  48. package/src/core/host-services.ts +21 -5
  49. package/src/core/notify-ports.ts +18 -5
  50. package/src/execution/__tests__/agent-profile.test.ts +232 -0
  51. package/src/execution/__tests__/agent-registry.test.ts +370 -0
  52. package/src/execution/__tests__/agent-result-mapper.test.ts +18 -2
  53. package/src/execution/__tests__/agents-assembly.test.ts +219 -0
  54. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +6 -6
  55. package/src/execution/__tests__/chat-engine-routing.test.ts +136 -30
  56. package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +5 -4
  57. package/src/execution/__tests__/cold-resurrect.test.ts +283 -0
  58. package/src/execution/__tests__/create-concurrency-pool.test.ts +194 -0
  59. package/src/execution/__tests__/delivery-methods.test.ts +77 -62
  60. package/src/execution/__tests__/descendant-sweep-guards.test.ts +220 -0
  61. package/src/execution/__tests__/descendant-sweep.test.ts +269 -0
  62. package/src/execution/__tests__/dialog-queue.test.ts +199 -1
  63. package/src/execution/__tests__/engine-model-validation.test.ts +741 -0
  64. package/src/execution/__tests__/epipe-fallback.test.ts +31 -24
  65. package/src/execution/__tests__/execute-and-await-worktree.test.ts +21 -91
  66. package/src/execution/__tests__/execute-nesting.test.ts +34 -188
  67. package/src/execution/__tests__/execution-record.test.ts +217 -60
  68. package/src/execution/__tests__/execution-runtime-face.test.ts +272 -0
  69. package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +3 -3
  70. package/src/execution/__tests__/finalize-record.test.ts +278 -16
  71. package/src/execution/__tests__/gc-timer.test.ts +57 -2
  72. package/src/execution/__tests__/get-record-for-action-restart.test.ts +14 -12
  73. package/src/execution/__tests__/get-state-handshake.test.ts +127 -0
  74. package/src/execution/__tests__/helpers/mock-extension-api.ts +1 -1
  75. package/src/execution/__tests__/helpers/session-runner-mocks.ts +113 -0
  76. package/src/execution/__tests__/helpers/spawn-mock.ts +150 -3
  77. package/src/execution/__tests__/helpers/subagent-service-mocks.ts +137 -0
  78. package/src/execution/__tests__/keep-alive-no-progress.test.ts +280 -0
  79. package/src/execution/__tests__/kill-all-escalation.test.ts +196 -0
  80. package/src/execution/__tests__/lifecycle-manager-idle-timer-identity.test.ts +117 -0
  81. package/src/execution/__tests__/lifecycle-manager.test.ts +39 -0
  82. package/src/execution/__tests__/lifecycle-predicates.test.ts +1 -2
  83. package/src/execution/__tests__/manifest-parentid.test.ts +4 -4
  84. package/src/execution/__tests__/manifest-store-tmp-recovery.test.ts +99 -0
  85. package/src/execution/__tests__/max-turns-to-watchdog-ms.test.ts +113 -0
  86. package/src/execution/__tests__/model-resolver.test.ts +2 -2
  87. package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +23 -121
  88. package/src/execution/__tests__/nested-visibility.test.ts +2 -0
  89. package/src/execution/__tests__/notify-ledger.test.ts +1249 -0
  90. package/src/execution/__tests__/output-collector.test.ts +117 -6
  91. package/src/execution/__tests__/pi-invocation.test.ts +1 -1
  92. package/src/execution/__tests__/record-store-orphan-revive.test.ts +159 -0
  93. package/src/execution/__tests__/record-store.test.ts +89 -5
  94. package/src/execution/__tests__/records-cwd-isolation.test.ts +2 -2
  95. package/src/execution/__tests__/recursive-visibility-baseline.test.ts +29 -132
  96. package/src/execution/__tests__/recursive-visibility-env.test.ts +55 -179
  97. package/src/execution/__tests__/rpc-mode.test.ts +2 -2
  98. package/src/execution/__tests__/run-and-finalize-anchoring.test.ts +387 -0
  99. package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +19 -9
  100. package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +5 -4
  101. package/src/execution/__tests__/run-spawn-edges.test.ts +418 -26
  102. package/src/execution/__tests__/run-spawn-integration.test.ts +3 -3
  103. package/src/execution/__tests__/run-spawn-resume.test.ts +2 -2
  104. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +2 -2
  105. package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +16 -8
  106. package/src/execution/__tests__/service-kill-escalation.test.ts +91 -0
  107. package/src/execution/__tests__/session-context-resolver.test.ts +0 -2
  108. package/src/execution/__tests__/session-file-gc.test.ts +35 -0
  109. package/src/execution/__tests__/session-pending.test.ts +471 -0
  110. package/src/execution/__tests__/session-reconstructor.test.ts +366 -15
  111. package/src/execution/__tests__/session-runner-branch-cache-lru.test.ts +110 -0
  112. package/src/execution/__tests__/session-runner-close-prune.test.ts +181 -0
  113. package/src/execution/__tests__/session-runner-dispatch.test.ts +489 -0
  114. package/src/execution/__tests__/session-runner-epipe.test.ts +4 -3
  115. package/src/execution/__tests__/session-runner-heartbeat-idle-fallback.test.ts +227 -0
  116. package/src/execution/__tests__/session-runner-lifecycle-helpers.test.ts +290 -0
  117. package/src/execution/__tests__/session-runner-schema-env.test.ts +7 -5
  118. package/src/execution/__tests__/settled-watchdog.test.ts +524 -0
  119. package/src/execution/__tests__/spawn-args.test.ts +11 -10
  120. package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +26 -23
  121. package/src/execution/__tests__/spawn-event-adapter.test.ts +1 -1
  122. package/src/execution/__tests__/spawn-worktree-guidance.test.ts +5 -4
  123. package/src/execution/__tests__/spawned-children.test.ts +155 -11
  124. package/src/execution/__tests__/start-sync-model-guard.test.ts +4 -4
  125. package/src/execution/__tests__/stdin-writer.test.ts +6 -4
  126. package/src/execution/__tests__/stream-sink-retirement.test.ts +6 -6
  127. package/src/execution/__tests__/subagent-actions-core.test.ts +1017 -0
  128. package/src/execution/__tests__/subagent-service-message-close.test.ts +99 -35
  129. package/src/execution/__tests__/subagent-service-multiproc-guard.test.ts +174 -0
  130. package/src/execution/__tests__/subagent-service-notify-gate.test.ts +271 -0
  131. package/src/execution/__tests__/subagent-service-parent-guard.test.ts +33 -29
  132. package/src/execution/__tests__/subagent-service-recovery-bounds.test.ts +341 -0
  133. package/src/execution/__tests__/subagent-service.test.ts +37 -30
  134. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +88 -12
  135. package/src/execution/__tests__/subprocess-agent-runner-timeout.test.ts +75 -0
  136. package/src/execution/__tests__/subprocess-agent-runner.test.ts +22 -20
  137. package/src/execution/__tests__/temp-prompt.test.ts +1 -1
  138. package/src/execution/__tests__/timeout-integration.test.ts +13 -12
  139. package/src/execution/__tests__/turn-limiter-semantics.test.ts +1 -1
  140. package/src/execution/__tests__/turn-limiter.test.ts +1 -1
  141. package/src/execution/__tests__/ui-request-handler-factory.test.ts +107 -7
  142. package/src/execution/__tests__/ui-request-handler.test.ts +4 -3
  143. package/src/execution/__tests__/ui-request-queue.test.ts +167 -2
  144. package/src/execution/__tests__/worktree-git-ops.test.ts +571 -0
  145. package/src/execution/__tests__/worktree-manager.test.ts +14 -5
  146. package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +4 -3
  147. package/src/execution/__tests__/worktree-reconcile-aging.test.ts +204 -0
  148. package/src/execution/agent-registry.ts +298 -30
  149. package/src/execution/agent-result-mapper.ts +3 -0
  150. package/src/execution/agents-assembly.ts +88 -0
  151. package/src/execution/cold-resurrect.ts +199 -0
  152. package/src/execution/concurrency-pool.ts +71 -9
  153. package/src/execution/dialog-queue.ts +101 -3
  154. package/src/execution/engine/__tests__/common/capability-gate.test.ts +91 -0
  155. package/src/execution/engine/__tests__/common/data-dir.test.ts +1 -1
  156. package/src/execution/engine/__tests__/common/journal-wiring.test.ts +84 -0
  157. package/src/execution/engine/__tests__/common/kill-chain.test.ts +34 -7
  158. package/src/execution/engine/__tests__/common/persona-router.test.ts +4 -5
  159. package/src/execution/engine/__tests__/common/pool-manager.test.ts +211 -51
  160. package/src/execution/engine/__tests__/common/session-view-service-zcode-dbpath.test.ts +149 -0
  161. package/src/execution/engine/__tests__/common/session-view-service.test.ts +499 -0
  162. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +56 -99
  163. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +88 -15
  164. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +33 -7
  165. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +1 -1
  166. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +75 -54
  167. package/src/execution/engine/__tests__/conformance/zcode-appserver-harness.ts +128 -0
  168. package/src/execution/engine/__tests__/engine-discovery.test.ts +15 -3
  169. package/src/execution/engine/__tests__/model-prompt.test.ts +15 -3
  170. package/src/execution/engine/__tests__/registry.test.ts +94 -3
  171. package/src/execution/engine/__tests__/routing.test.ts +115 -6
  172. package/src/execution/engine/common/capability-gate.ts +92 -0
  173. package/src/execution/engine/common/journal-wiring.ts +97 -0
  174. package/src/execution/engine/common/kill-chain.ts +42 -10
  175. package/src/execution/engine/common/nesting-guard.ts +66 -0
  176. package/src/execution/engine/common/persona-router.ts +18 -8
  177. package/src/execution/engine/common/pool-manager.ts +332 -78
  178. package/src/execution/engine/common/session-view-service.ts +506 -0
  179. package/src/execution/engine/common/session-view-types.ts +125 -0
  180. package/src/execution/engine/engine-discovery.ts +12 -16
  181. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +174 -28
  182. package/src/execution/engine/engines/pi/__tests__/spawn-opts-direct.test.ts +257 -0
  183. package/src/execution/{argv-mirror.ts → engine/engines/pi/argv-mirror.ts} +43 -21
  184. package/src/execution/{get-state-handshake.ts → engine/engines/pi/get-state-handshake.ts} +86 -11
  185. package/src/execution/{output-collector.ts → engine/engines/pi/output-collector.ts} +108 -19
  186. package/src/execution/engine/engines/pi/pi-engine.ts +434 -38
  187. package/src/execution/{pi-invocation.ts → engine/engines/pi/pi-invocation.ts} +2 -2
  188. package/src/execution/engine/engines/pi/reader.ts +11 -0
  189. package/src/execution/engine/engines/pi/registration.ts +4 -2
  190. package/src/execution/engine/engines/pi/session-runner.ts +2840 -0
  191. package/src/execution/{spawn-event-adapter.ts → engine/engines/pi/spawn-event-adapter.ts} +75 -34
  192. package/src/execution/{stdin-writer.ts → engine/engines/pi/stdin-writer.ts} +10 -9
  193. package/src/execution/{temp-prompt.ts → engine/engines/pi/temp-prompt.ts} +2 -2
  194. package/src/execution/{turn-limiter.ts → engine/engines/pi/turn-limiter.ts} +1 -1
  195. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/fake-appserver.mjs +301 -0
  196. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-appserver.json +36 -0
  197. package/src/execution/engine/engines/zcode/__tests__/appserver-launcher.test.ts +321 -0
  198. package/src/execution/engine/engines/zcode/__tests__/connection.test.ts +473 -0
  199. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +7 -210
  200. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +6 -110
  201. package/src/execution/engine/engines/zcode/__tests__/session-channel-dispose-harvest.test.ts +247 -0
  202. package/src/execution/engine/engines/zcode/__tests__/session-channel-turn-timers.test.ts +451 -0
  203. package/src/execution/engine/engines/zcode/__tests__/session-channel.test.ts +792 -0
  204. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-appserver.test.ts +782 -0
  205. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-degrade.test.ts +168 -0
  206. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-dispose.test.ts +210 -0
  207. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-retry.test.ts +353 -0
  208. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-status.test.ts +282 -0
  209. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-timeout.test.ts +372 -0
  210. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +65 -47
  211. package/src/execution/engine/engines/zcode/appserver-launcher.ts +167 -0
  212. package/src/execution/engine/engines/zcode/connection.ts +598 -0
  213. package/src/execution/engine/engines/zcode/constants.ts +147 -14
  214. package/src/execution/engine/engines/zcode/golden-sample.ts +42 -34
  215. package/src/execution/engine/engines/zcode/parser.ts +12 -346
  216. package/src/execution/engine/engines/zcode/preparer.ts +22 -150
  217. package/src/execution/engine/engines/zcode/session-channel.ts +968 -0
  218. package/src/execution/engine/engines/zcode/zcode-engine.ts +1023 -250
  219. package/src/execution/engine/host-task-spec.ts +32 -36
  220. package/src/execution/engine/model-validation.ts +177 -0
  221. package/src/execution/engine/port.ts +65 -7
  222. package/src/execution/engine/registry.ts +53 -0
  223. package/src/execution/engine/routing.ts +75 -1
  224. package/src/execution/engine/types.ts +30 -103
  225. package/src/execution/execution-record.ts +222 -144
  226. package/src/execution/finalize-record.ts +181 -85
  227. package/src/execution/idle-gc.ts +28 -0
  228. package/src/execution/lifecycle-manager.ts +27 -3
  229. package/src/execution/lifecycle-predicates.ts +1 -1
  230. package/src/execution/manifest-store.ts +53 -62
  231. package/src/execution/notifier.ts +10 -10
  232. package/src/execution/notify-host.ts +212 -0
  233. package/src/execution/notify-ledger.ts +117 -16
  234. package/src/execution/record-entry.ts +8 -2
  235. package/src/execution/record-store.ts +148 -88
  236. package/src/execution/round-settlement.ts +93 -0
  237. package/src/execution/session-file-gc.ts +96 -62
  238. package/src/execution/session-pending.ts +213 -62
  239. package/src/execution/session-reconstructor.ts +256 -143
  240. package/src/execution/sessions-index.ts +127 -102
  241. package/src/execution/settled-watchdog.ts +311 -0
  242. package/src/execution/subagent-actions-core.ts +686 -0
  243. package/src/execution/subagent-service.ts +1106 -907
  244. package/src/execution/subprocess-agent-runner.ts +144 -97
  245. package/src/execution/types.ts +9 -0
  246. package/src/execution/ui-request-handler-factory.ts +126 -75
  247. package/src/execution/ui-request-queue.ts +50 -19
  248. package/src/execution/worktree-git-ops.ts +397 -0
  249. package/src/execution/worktree-manager.ts +72 -10
  250. package/src/execution/worktree-registry.ts +6 -12
  251. package/src/index.ts +542 -9
  252. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +42 -3
  253. package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +3 -5
  254. package/src/orchestration/__tests__/agent-call-stream.test.ts +2 -2
  255. package/src/orchestration/__tests__/args-meta.test.ts +358 -0
  256. package/src/orchestration/__tests__/args-validator.test.ts +14 -0
  257. package/src/orchestration/__tests__/error-recovery-rebuild-failure.test.ts +312 -0
  258. package/src/orchestration/__tests__/error-recovery-terminal-hardening.test.ts +384 -0
  259. package/src/orchestration/__tests__/execute-agent-call.test.ts +151 -11
  260. package/src/orchestration/__tests__/file-run-store-prune.test.ts +168 -0
  261. package/src/orchestration/__tests__/file-run-store-throttle.test.ts +168 -0
  262. package/src/orchestration/__tests__/file-run-store.test.ts +390 -0
  263. package/src/orchestration/__tests__/helpers/flush-microtasks.ts +13 -0
  264. package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +34 -0
  265. package/src/orchestration/__tests__/lifecycle-abort-broadcast-signal.test.ts +357 -0
  266. package/src/orchestration/__tests__/lifecycle-recover-crashed.test.ts +289 -0
  267. package/src/orchestration/__tests__/lifecycle-runid-injection.test.ts +3 -3
  268. package/src/orchestration/__tests__/lifecycle.test.ts +84 -5
  269. package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +1 -1
  270. package/src/orchestration/__tests__/run-snapshot.test.ts +356 -0
  271. package/src/orchestration/__tests__/script-generate.test.ts +314 -0
  272. package/src/orchestration/__tests__/script-lint.test.ts +17 -0
  273. package/src/orchestration/__tests__/test-mocks.ts +2 -0
  274. package/src/orchestration/__tests__/worker-exit-without-result.test.ts +7 -6
  275. package/src/orchestration/__tests__/worker-message-pump-finalize-run.test.ts +229 -0
  276. package/src/orchestration/__tests__/{error-recovery-handlers.test.ts → worker-message-pump-handlers.test.ts} +28 -27
  277. package/src/orchestration/__tests__/{error-recovery-postmessage-defense.test.ts → worker-message-pump-postmessage-defense.test.ts} +8 -8
  278. package/src/orchestration/__tests__/{error-recovery-serialize-failed-result.test.ts → worker-message-pump-serialize-failed-result.test.ts} +2 -2
  279. package/src/orchestration/__tests__/{error-recovery-workflow-call.test.ts → worker-message-pump-workflow-call.test.ts} +1 -1
  280. package/src/orchestration/__tests__/worker-pending-timeout-abort.test.ts +275 -0
  281. package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +78 -1
  282. package/src/orchestration/__tests__/worker-script-builder.test.ts +1 -1
  283. package/src/orchestration/__tests__/workflow-files.test.ts +186 -0
  284. package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +1 -1
  285. package/src/orchestration/__tests__/workflow-run-summary.test.ts +119 -0
  286. package/src/orchestration/__tests__/workflow-script-registry-impl.test.ts +124 -0
  287. package/src/orchestration/agent-opts-resolver.ts +8 -8
  288. package/src/orchestration/args-meta.ts +198 -0
  289. package/src/orchestration/args-validator.ts +53 -31
  290. package/src/orchestration/execute-agent-call.ts +25 -79
  291. package/src/orchestration/file-run-store.ts +327 -0
  292. package/src/orchestration/launcher.ts +160 -104
  293. package/src/orchestration/lifecycle.ts +371 -97
  294. package/src/orchestration/models/agent-call.ts +7 -7
  295. package/src/orchestration/models/budget.ts +5 -5
  296. package/src/orchestration/models/ports.ts +4 -4
  297. package/src/orchestration/models/run-runtime.ts +15 -15
  298. package/src/orchestration/models/trace.ts +9 -9
  299. package/src/orchestration/models/types.ts +111 -22
  300. package/src/orchestration/models/workflow-run.ts +28 -28
  301. package/src/orchestration/models/workflow-script.ts +4 -4
  302. package/src/orchestration/run-snapshot.ts +266 -0
  303. package/src/orchestration/script-generate.ts +154 -0
  304. package/src/orchestration/script-lint.ts +123 -90
  305. package/src/orchestration/worker-handle.ts +10 -10
  306. package/src/orchestration/worker-host.ts +10 -10
  307. package/src/orchestration/{error-recovery.ts → worker-message-pump.ts} +498 -221
  308. package/src/orchestration/worker-script-builder.ts +401 -346
  309. package/src/orchestration/workflow-files.ts +37 -11
  310. package/src/orchestration/workflow-run-summary.ts +69 -0
  311. package/src/orchestration/workflow-script-registry-impl.ts +31 -9
  312. package/src/shared/__tests__/agent-ref.test.ts +209 -2
  313. package/src/shared/__tests__/atomic-write.test.ts +267 -0
  314. package/src/shared/__tests__/bounded-serialize.test.ts +236 -0
  315. package/src/shared/__tests__/injection-render.test.ts +518 -0
  316. package/src/shared/__tests__/meta-parser.test.ts +151 -0
  317. package/src/shared/__tests__/resource-discovery-host-roots.test.ts +474 -0
  318. package/src/shared/__tests__/resource-discovery.test.ts +261 -217
  319. package/src/shared/agent-ref.ts +143 -2
  320. package/src/shared/atomic-write.ts +323 -0
  321. package/src/shared/bounded-serialize.ts +154 -0
  322. package/src/shared/injection-render.ts +279 -0
  323. package/src/shared/meta-parser.ts +182 -68
  324. package/src/shared/model-ref.ts +15 -2
  325. package/src/shared/resource-discovery.ts +97 -204
  326. package/src/shared/resource-meta.ts +14 -0
  327. package/src/shared/schema-jsonify.ts +1 -1
  328. package/src/shared/xml-injection.ts +9 -9
  329. package/workflows/README.md +9 -9
  330. package/workflows/chain.js +4 -2
  331. package/workflows/map-reduce.js +5 -3
  332. package/workflows/parallel.js +5 -3
  333. package/workflows/review-fix-loop-utils.cjs +165 -92
  334. package/workflows/review-fix-loop-utils.d.cts +287 -0
  335. package/workflows/review-fix-loop.js +18 -7
  336. package/workflows/scatter-gather.js +4 -2
  337. package/dist/chunk-3VOERJPJ.js +0 -22
  338. package/src/execution/__tests__/execute-options-mapper.test.ts +0 -200
  339. package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +0 -164
  340. package/src/execution/engine/engines/pi/task-spec-mapper.ts +0 -100
  341. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +0 -39
  342. package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +0 -150
  343. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +0 -580
  344. package/src/execution/engine/engines/zcode/launcher.ts +0 -161
  345. package/src/execution/execute-options-mapper.ts +0 -115
  346. package/src/execution/session-runner.ts +0 -1789
  347. package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +0 -288
@@ -0,0 +1,473 @@
1
+ // connection.test.ts —— R2 连接层测试:全部跑 __fixtures__/fake-appserver.mjs 子进程
2
+ // (移植自 zsw 仓 84b63a0^ fake-server 测试模式,vitest 形态改造),绝不 spawn 真
3
+ // zcode.cjs。覆盖验收条款:四帧型分发逐型 / 请求-应答 id 关联(并发不串)/
4
+ // requestRuntimePreferences 常量应答逐字段 / 未知反向回空 result / onClose 全部在途
5
+ // reject(含 stderr 尾 400 截断)/ 惰性启动与进程死后重建 / stderr tee 落盘 /
6
+ // protocol 自报忽略 / 无 jsonrpc 字段的帧收发(出站精确键集 = 对面 strict 拒未知键
7
+ // 的镜像义务)/ env 惯例 / 关闭原语幂等。
8
+
9
+ import { existsSync, mkdtempSync, readFileSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+
14
+ import { afterEach, describe, expect, it } from "vitest";
15
+
16
+ import { ZCODE_APPSERVER_STDERR_TAIL_CHARS } from "../constants.ts";
17
+ import {
18
+ AppServerConnection,
19
+ RUNTIME_PREFERENCES,
20
+ buildAppServerEnv,
21
+ isAppServerRpcError,
22
+ } from "../connection.ts";
23
+
24
+ const TMP = mkdtempSync(join(tmpdir(), "zcode-conn-"));
25
+ const FAKE_CLI = fileURLToPath(new URL("./__fixtures__/fake-appserver.mjs", import.meta.url));
26
+
27
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
28
+
29
+ /** fake 侧事件流水条目(JSONL:boot/env/recv/reverse-answer)。 */
30
+ interface StateEvent {
31
+ seq: number;
32
+ ev: string;
33
+ [key: string]: unknown;
34
+ }
35
+
36
+ function readState(file: string): StateEvent[] {
37
+ try {
38
+ return readFileSync(file, "utf8")
39
+ .trim()
40
+ .split("\n")
41
+ .filter(Boolean)
42
+ .map((l) => JSON.parse(l) as StateEvent);
43
+ } catch {
44
+ return [];
45
+ }
46
+ }
47
+
48
+ function isRecord(v: unknown): v is Record<string, unknown> {
49
+ return typeof v === "object" && v !== null && !Array.isArray(v);
50
+ }
51
+
52
+ /** 轮询等待 fake 侧异步效果可见(fake 异步处理 stdin,不能假设即时)。 */
53
+ async function waitFor(cond: () => boolean, ms = 5_000, step = 25): Promise<boolean> {
54
+ const end = Date.now() + ms;
55
+ while (Date.now() < end) {
56
+ if (cond()) return true;
57
+ await sleep(step);
58
+ }
59
+ return cond();
60
+ }
61
+
62
+ interface FakeHandle {
63
+ conn: AppServerConnection;
64
+ stateFile: string;
65
+ stderrLog: string;
66
+ cwd: string;
67
+ }
68
+
69
+ interface FakeOpts {
70
+ /** FAKE_STDERR=1:启动时往 stderr 写两行。 */
71
+ stderrLines?: boolean;
72
+ /** FAKE_EXTRA_KEYS=1:fake 应答/推送帧携带未知键(客户端宽容解析断言)。 */
73
+ extraKeys?: boolean;
74
+ /** FAKE_PROTOCOL_PUSH=1:协议自报走 {method:'protocol'} 推送形态。 */
75
+ protocolPush?: boolean;
76
+ /** 基 env 预置引擎原生嵌套标记(nesting guard 剥离断言)。 */
77
+ polluteNested?: boolean;
78
+ /** 注入故障反向 handler(fire-and-forget catch 断言)。 */
79
+ reverseHandlers?: Readonly<Record<string, (params: unknown) => unknown>>;
80
+ }
81
+
82
+ const CONNECTIONS: AppServerConnection[] = [];
83
+ let connSeq = 0;
84
+
85
+ /** 建一个连到 fake 的连接(env 面向子进程固化,测试间零共享状态)。 */
86
+ function makeConnection(opts: FakeOpts = {}): FakeHandle {
87
+ connSeq += 1;
88
+ const stateFile = join(TMP, `state-${connSeq}.jsonl`);
89
+ const stderrLog = join(TMP, `stderr-${connSeq}.log`);
90
+ const cwd = join(TMP, `cwd-${connSeq}`);
91
+ const base: NodeJS.ProcessEnv = {
92
+ PATH: process.env.PATH ?? "",
93
+ HOME: "/fake-host-home",
94
+ FAKE_STATE_FILE: stateFile,
95
+ ...(opts.stderrLines ? { FAKE_STDERR: "1" } : {}),
96
+ ...(opts.extraKeys ? { FAKE_EXTRA_KEYS: "1" } : {}),
97
+ ...(opts.protocolPush ? { FAKE_PROTOCOL_PUSH: "1" } : {}),
98
+ ...(opts.polluteNested ? { ZSW_NESTED: "1", CLAUDECODE: "1", PI_SUBAGENT_DEPTH: "2" } : {}),
99
+ };
100
+ const conn = new AppServerConnection({
101
+ cliPath: FAKE_CLI,
102
+ cwd,
103
+ env: buildAppServerEnv(base),
104
+ stderrLogPath: stderrLog,
105
+ ...(opts.reverseHandlers ? { reverseHandlers: opts.reverseHandlers } : {}),
106
+ });
107
+ CONNECTIONS.push(conn);
108
+ return { conn, stateFile, stderrLog, cwd };
109
+ }
110
+
111
+ afterEach(async () => {
112
+ await Promise.allSettled(CONNECTIONS.splice(0).map((c) => c.shutdown({ graceMs: 1_000 })));
113
+ });
114
+
115
+ // ------------------------------------------- 惰性启动与重建(D1 / 不变量 4)
116
+
117
+ describe("惰性启动与惰性重建", () => {
118
+ it("构造不 spawn:无流水、无 pid、alive=false(连接构建零成本)", async () => {
119
+ const { conn, stateFile } = makeConnection();
120
+ expect(conn.alive).toBe(false);
121
+ expect(conn.pid).toBeUndefined();
122
+ await sleep(80);
123
+ expect(existsSync(stateFile)).toBe(false);
124
+ expect(conn.pid).toBeUndefined();
125
+ });
126
+
127
+ it("首次请求才 spawn:boot 流水出现,argv 形态 = `app-server --cwd <dir>`(D10 基线,不带 --stdio/--surface)", async () => {
128
+ const { conn, stateFile, cwd } = makeConnection();
129
+ const r = await conn.request("test/echo", { marker: "first" });
130
+ expect(r).toEqual({ marker: "first" });
131
+ const boots = readState(stateFile).filter((e) => e.ev === "boot");
132
+ expect(boots).toHaveLength(1);
133
+ expect(boots[0].argv).toEqual(["app-server", "--cwd", cwd]);
134
+ expect(conn.pid).toBeGreaterThan(0);
135
+ expect(conn.alive).toBe(true);
136
+ }, 10_000);
137
+
138
+ it("进程死后下次请求自动重建(与惰性启动同路径):boot 两次、pid 变化", async () => {
139
+ const { conn, stateFile } = makeConnection();
140
+ await conn.request("test/echo", { n: 1 });
141
+ const pidBefore = conn.pid;
142
+ await expect(conn.request("test/suicide")).rejects.toThrow(/app-server/);
143
+ expect(await waitFor(() => !conn.alive)).toBe(true);
144
+ const r2 = await conn.request("test/echo", { n: 2 });
145
+ expect(r2).toEqual({ n: 2 });
146
+ const boots = readState(stateFile).filter((e) => e.ev === "boot");
147
+ expect(boots).toHaveLength(2);
148
+ expect(boots[1].pid).not.toBe(boots[0].pid);
149
+ expect(conn.pid).not.toBe(pidBefore);
150
+ }, 15_000);
151
+
152
+ it("spawn 失败(nodeBin ENOENT)走同一收割路径:请求 reject 带 spawn 失败语境,连接不悬挂", async () => {
153
+ const conn = new AppServerConnection({
154
+ cliPath: FAKE_CLI,
155
+ cwd: TMP,
156
+ nodeBin: join(TMP, "no-such-node-bin"),
157
+ env: { PATH: process.env.PATH ?? "" },
158
+ stderrLogPath: join(TMP, "enoent.log"),
159
+ });
160
+ CONNECTIONS.push(conn);
161
+ await expect(conn.request("test/echo", {})).rejects.toThrow(/spawn 失败/);
162
+ expect(await waitFor(() => !conn.alive)).toBe(true);
163
+ }, 10_000);
164
+ });
165
+
166
+ // ------------------------------------------- 四帧型分发(附录 A.1)
167
+
168
+ describe("四帧型分发(NDJSON,无 jsonrpc 字段)", () => {
169
+ it("客户端请求帧:出站精确键集 {id, method, params}——无 jsonrpc、无未知键(对面 strict 拒未知键)", async () => {
170
+ const { conn, stateFile } = makeConnection();
171
+ await conn.request("test/echo", { a: 1 });
172
+ const frames = readState(stateFile)
173
+ .map((e) => (e as Record<string, unknown>).frame)
174
+ .filter((f): f is Record<string, unknown> => isRecord(f) && f.method === "test/echo");
175
+ expect(frames).toHaveLength(1);
176
+ expect(Object.keys(frames[0]).sort()).toEqual(["id", "method", "params"]);
177
+ expect(typeof frames[0].id).toBe("number");
178
+ expect("jsonrpc" in frames[0]).toBe(false);
179
+ });
180
+
181
+ it("应答帧(result):resolve 应答值;帧级未知键宽容解析(我们是客户端,strict 校验是对面)", async () => {
182
+ const { conn } = makeConnection({ extraKeys: true });
183
+ const r = await conn.request<{ marker: string }>("test/echo", { marker: "lenient" });
184
+ expect(r).toEqual({ marker: "lenient" });
185
+ // 推送帧携带未知键同样不破坏分发
186
+ const received: unknown[] = [];
187
+ conn.onNotification("test/notification", (p) => received.push(p));
188
+ await conn.request("test/push", { pushMethod: "test/notification", pushParams: { delta: "hi" } });
189
+ expect(received).toEqual([{ delta: "hi" }]);
190
+ });
191
+
192
+ it("应答帧(error):code/message/data 挂到 reject Error(A.3 错误码通道,-32602 zod 诊断随 data 带出)", async () => {
193
+ const { conn } = makeConnection();
194
+ const err = await conn
195
+ .request("test/fail", {
196
+ code: -32602,
197
+ message: "Invalid params",
198
+ data: [{ path: ["model"], message: "not an object" }],
199
+ })
200
+ .then(
201
+ () => {
202
+ throw new Error("should reject");
203
+ },
204
+ (e: unknown) => e,
205
+ );
206
+ expect(isAppServerRpcError(err)).toBe(true);
207
+ if (isAppServerRpcError(err)) {
208
+ expect(err.code).toBe(-32602);
209
+ expect(err.data).toEqual([{ path: ["model"], message: "not an object" }]);
210
+ expect(err.message).toContain("[-32602]");
211
+ expect(err.message).toContain("Invalid params");
212
+ }
213
+ });
214
+
215
+ it("服务端推送帧:onNotification(method) 收到 params;handler 异常不拖死帧泵;退订生效", async () => {
216
+ const { conn } = makeConnection();
217
+ const received: unknown[] = [];
218
+ const receivedBoom: unknown[] = [];
219
+ const receivedOff: unknown[] = [];
220
+ conn.onNotification("test/notification", (params) => {
221
+ received.push(params);
222
+ });
223
+ conn.onNotification("test/notification", (params) => {
224
+ receivedBoom.push(params);
225
+ throw new Error("handler boom");
226
+ });
227
+ const off = conn.onNotification("test/notification", (params) => {
228
+ receivedOff.push(params);
229
+ });
230
+ off();
231
+ await conn.request("test/push", { pushMethod: "test/notification", pushParams: { delta: "hello" } });
232
+ await conn.request("test/push", { pushMethod: "test/notification", pushParams: { delta: "again" } });
233
+ expect(received).toEqual([{ delta: "hello" }, { delta: "again" }]);
234
+ expect(receivedBoom).toEqual([{ delta: "hello" }, { delta: "again" }]);
235
+ expect(receivedOff).toEqual([]);
236
+ // 抛过异常后连接仍可用
237
+ const r = await conn.request("test/echo", { ok: 1 });
238
+ expect(r).toEqual({ ok: 1 });
239
+ });
240
+ });
241
+
242
+ // ------------------------------------------- 请求-应答 id 关联
243
+
244
+ describe("请求-应答 id 关联", () => {
245
+ it("并发多请求不串线:3 个在途请求各自 resolve 自己的回显;id 自增互异", async () => {
246
+ const { conn, stateFile } = makeConnection();
247
+ const [a, b, c] = await Promise.all([
248
+ conn.request("test/delay-echo", { who: "a", delayMs: 60 }),
249
+ conn.request("test/delay-echo", { who: "b", delayMs: 30 }),
250
+ conn.request("test/echo", { who: "c" }),
251
+ ]);
252
+ expect(a).toEqual({ who: "a", delayMs: 60 });
253
+ expect(b).toEqual({ who: "b", delayMs: 30 });
254
+ expect(c).toEqual({ who: "c" });
255
+ const ids = readState(stateFile)
256
+ .map((e) => (e as Record<string, unknown>).frame)
257
+ .filter((f): f is { id: number } => isRecord(f) && typeof f.method === "string" && typeof f.id === "number")
258
+ .map((f) => f.id);
259
+ expect(ids).toHaveLength(3);
260
+ expect(new Set(ids).size).toBe(3);
261
+ expect([...ids].sort((x, y) => x - y)).toEqual([1, 2, 3]);
262
+ });
263
+
264
+ it("超时预算参数化:小预算 reject 超时,pending 清理后后续请求正常", async () => {
265
+ const { conn } = makeConnection();
266
+ await expect(conn.request("test/delay-echo", { delayMs: 5_000 }, { timeoutMs: 120 })).rejects.toThrow(/超时/);
267
+ const r = await conn.request("test/echo", { after: "timeout" });
268
+ expect(r).toEqual({ after: "timeout" });
269
+ }, 10_000);
270
+ });
271
+
272
+ // ------------------------------------------- 反向请求应答(D9)
273
+
274
+ describe("反向请求应答(D9)", () => {
275
+ it("session/requestRuntimePreferences → 常量表应答逐字段(真实协议:create 先发反向请求并等应答)", async () => {
276
+ const { conn, stateFile } = makeConnection();
277
+ const created = await conn.request<{ session: { sessionId: string } }>("session/create", {
278
+ workspace: { workspacePath: "/w", workspaceKey: "ws-x" },
279
+ mode: "yolo",
280
+ });
281
+ expect(typeof created.session.sessionId).toBe("string");
282
+ const answers = readState(stateFile).filter((e) => e.ev === "reverse-answer");
283
+ expect(answers).toHaveLength(1);
284
+ const result = (answers[0].answer as { result?: Record<string, unknown> }).result;
285
+ // 逐字段断言(D9 常量逐字来自旧实现实测)
286
+ expect(result).toEqual({ ...RUNTIME_PREFERENCES });
287
+ expect(result?.nativeSearchEnhancementsEnabled).toBe(true);
288
+ expect(result?.memoryEnabled).toBe(false);
289
+ expect(result?.askUserQuestionAutoResolutionEnabled).toBe(true);
290
+ expect(result?.modelContextBudgetStrategy).toBe("preflight-v1");
291
+ expect(Object.keys(result ?? {}).sort()).toEqual([
292
+ "askUserQuestionAutoResolutionEnabled",
293
+ "memoryEnabled",
294
+ "modelContextBudgetStrategy",
295
+ "nativeSearchEnhancementsEnabled",
296
+ ]);
297
+ // 反向应答帧出站精确键集 {id, result}(无 jsonrpc、无未知键)
298
+ const answerFrame = readState(stateFile)
299
+ .map((e) => (e as Record<string, unknown>).frame)
300
+ .find((f): f is Record<string, unknown> => isRecord(f) && typeof f.id === "string");
301
+ expect(answerFrame).toBeDefined();
302
+ expect(Object.keys(answerFrame!).sort()).toEqual(["id", "result"]);
303
+ });
304
+
305
+ it("未知反向请求 → 回 {id, result:{}}(不答会 15s 超时断连,旧实测 -32022)", async () => {
306
+ const { conn, stateFile } = makeConnection();
307
+ await conn.request("test/reverse", { reverseMethod: "permission/request", reverseParams: { tool: "Bash" } });
308
+ const answers = readState(stateFile).filter((e) => e.ev === "reverse-answer");
309
+ expect(answers).toHaveLength(1);
310
+ const answer = answers[0].answer as { result?: unknown; error?: unknown };
311
+ expect(answer.result).toEqual({});
312
+ expect(answer.error).toBeUndefined();
313
+ });
314
+
315
+ it("应答失败不拖死连接(fire-and-forget + catch):故障 handler → 回 error 帧,连接仍可用", async () => {
316
+ const { conn, stateFile } = makeConnection({
317
+ reverseHandlers: {
318
+ "session/requestRuntimePreferences": () => {
319
+ throw new Error("prefs boom");
320
+ },
321
+ },
322
+ });
323
+ const created = await conn.request("session/create", {});
324
+ expect(created).toBeTruthy();
325
+ const answers = readState(stateFile).filter((e) => e.ev === "reverse-answer");
326
+ expect(answers).toHaveLength(1);
327
+ const answer = answers[0].answer as { error?: { code?: number; message?: string } };
328
+ expect(answer.error?.code).toBe(-32000);
329
+ expect(answer.error?.message).toContain("prefs boom");
330
+ const r = await conn.request("test/echo", { still: "alive" });
331
+ expect(r).toEqual({ still: "alive" });
332
+ });
333
+ });
334
+
335
+ // ------------------------------------------- 崩溃收割(onClose)
336
+
337
+ describe("崩溃收割(onClose/exit)", () => {
338
+ it("进程意外退出:全部在途 reject,错误信息附 stderr 尾(400 字符截断)", async () => {
339
+ const { conn } = makeConnection();
340
+ await conn.request("test/echo", { warm: true });
341
+ const errors = await Promise.all(
342
+ [
343
+ conn.request("test/delay-echo", { who: "a", delayMs: 10_000 }),
344
+ conn.request("test/delay-echo", { who: "b", delayMs: 10_000 }),
345
+ conn.request("test/suicide"),
346
+ ].map((p) => p.then(
347
+ () => {
348
+ throw new Error("should reject");
349
+ },
350
+ (e: unknown) => e,
351
+ )),
352
+ );
353
+ expect(errors).toHaveLength(3);
354
+ for (const err of errors) {
355
+ expect(err).toBeInstanceOf(Error);
356
+ const msg = (err as Error).message;
357
+ expect(msg).toContain("app-server");
358
+ expect(msg).toContain("code=1");
359
+ expect(msg).toContain("CRASH-MARK-TAIL");
360
+ // 截断到常量值:600 个 A 只保留尾部(< 400),整段噪声不允许进错误信息
361
+ expect(msg).not.toMatch(new RegExp(`A{${ZCODE_APPSERVER_STDERR_TAIL_CHARS}}`));
362
+ }
363
+ expect(await waitFor(() => !conn.alive)).toBe(true);
364
+ }, 15_000);
365
+ });
366
+
367
+ // ------------------------------------------- stderr tee 落盘
368
+
369
+ describe("stderr tee 落盘", () => {
370
+ it("stderr 实时 append 到参数化路径(引擎数据目录注入点;测试用 tmp)", async () => {
371
+ const { conn, stderrLog } = makeConnection({ stderrLines: true });
372
+ await conn.request("test/echo", {});
373
+ const ok = await waitFor(() => {
374
+ try {
375
+ const text = readFileSync(stderrLog, "utf8");
376
+ return text.includes("fake-appserver stderr line A") && text.includes("fake-appserver stderr line B");
377
+ } catch {
378
+ return false;
379
+ }
380
+ });
381
+ expect(ok).toBe(true);
382
+ });
383
+ });
384
+
385
+ // ------------------------------------------- env 惯例(构造注入面)
386
+
387
+ describe("env 惯例(共享宿主 HOME 形态)", () => {
388
+ it("buildAppServerEnv:HOME 正向透传(共享宿主)+ 遥测关闭 + nesting guard 剥离/注入(fake 侧 env 快照)", async () => {
389
+ const { conn, stateFile } = makeConnection({ polluteNested: true });
390
+ await conn.request("test/echo", {});
391
+ const envEvents = readState(stateFile).filter((e) => e.ev === "env");
392
+ expect(envEvents).toHaveLength(1);
393
+ const snap = envEvents[0] as {
394
+ home?: string;
395
+ telemetry?: string;
396
+ nested?: string;
397
+ unifiedNested?: string;
398
+ };
399
+ // 共享宿主 HOME 契约(2026-09 起):base env 携带的宿主 HOME 值原样透传到子进程
400
+ // env(不覆写、不剥离——db/plugins/MCP 全继承宿主 HOME)
401
+ expect(snap.home).toBe("/fake-host-home");
402
+ expect(snap.telemetry).toBe("false");
403
+ expect(snap.nested).toBeUndefined();
404
+ expect(snap.unifiedNested).toBe("1");
405
+ });
406
+ });
407
+
408
+ // ------------------------------------------- 关闭原语(R4 dispose 的连接侧原语)
409
+
410
+ describe("关闭原语", () => {
411
+ it("close():同步 SIGTERM 面——进程随后死亡;幂等;只起过一代", async () => {
412
+ const { conn, stateFile } = makeConnection();
413
+ await conn.request("test/echo", {});
414
+ expect(conn.alive).toBe(true);
415
+ conn.close();
416
+ conn.close();
417
+ expect(await waitFor(() => !conn.alive)).toBe(true);
418
+ expect(readState(stateFile).filter((e) => e.ev === "boot")).toHaveLength(1);
419
+ }, 10_000);
420
+
421
+ it("shutdown():杀链走完进程退出;幂等;之后首个请求自动重建(不变量 4:与崩溃重建同路径)", async () => {
422
+ const { conn, stateFile } = makeConnection();
423
+ await conn.request("test/echo", {});
424
+ await conn.shutdown({ graceMs: 1_500 });
425
+ await conn.shutdown();
426
+ expect(await waitFor(() => !conn.alive)).toBe(true);
427
+ const r = await conn.request("test/echo", { reborn: true });
428
+ expect(r).toEqual({ reborn: true });
429
+ expect(readState(stateFile).filter((e) => e.ev === "boot")).toHaveLength(2);
430
+ }, 15_000);
431
+
432
+ it("close() 后调 shutdown():await close 发起的同一杀链,resolve 不早于进程退出(幂等——同一 promise)", async () => {
433
+ const { conn, stateFile } = makeConnection();
434
+ await conn.request("test/echo", {});
435
+ const pid = conn.pid;
436
+ conn.close();
437
+ let shutdownSettled = false;
438
+ const shutdownPromise = conn.shutdown().then(() => {
439
+ shutdownSettled = true;
440
+ });
441
+ await shutdownPromise;
442
+ expect(shutdownSettled).toBe(true);
443
+ // killChain 挂 exit 事件 resolve(Node exit 前已收尸)——shutdown resolve 时进程
444
+ // 必已退出:kill(0) 探活抛 ESRCH 即「resolve 不早于杀链完成」的机制性证据
445
+ expect(() => process.kill(pid ?? -1, 0)).toThrow(/ESRCH/);
446
+ // 幂等:再次 shutdown 复用同一 promise,无新杀链、无新进程
447
+ await conn.shutdown();
448
+ expect(readState(stateFile).filter((e) => e.ev === "boot")).toHaveLength(1);
449
+ }, 10_000);
450
+ });
451
+
452
+ // ------------------------------------------- protocol 自报与宽容解析
453
+
454
+ describe("protocol 自报与宽容解析", () => {
455
+ it("首帧 {protocol:{name,version}} 自报忽略不抛,protocolInfo 记录,连接可用", async () => {
456
+ const { conn } = makeConnection();
457
+ const r = await conn.request("test/echo", { ok: 1 });
458
+ expect(r).toEqual({ ok: 1 });
459
+ expect(conn.protocolInfo).toEqual({ name: "ZCode Protocol", version: 1 });
460
+ });
461
+
462
+ it("protocol 推送形态 {method:'protocol'} 同样收敛到 protocolInfo", async () => {
463
+ const { conn } = makeConnection({ protocolPush: true });
464
+ await conn.request("test/echo", {});
465
+ expect(conn.protocolInfo).toEqual({ name: "ZCode Protocol", version: 1 });
466
+ });
467
+
468
+ it("坏行跳过不断流:非 JSON 行之后正常应答", async () => {
469
+ const { conn } = makeConnection();
470
+ const r = await conn.request("test/malformed-first", {});
471
+ expect(r).toEqual({ survived: true });
472
+ });
473
+ });