@zhushanwen/pi-subagent-workflow 8.6.0 → 8.8.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 (364) hide show
  1. package/README.md +5 -11
  2. package/package.json +13 -20
  3. package/relay/relay.mjs +1 -1
  4. package/skills/workflow-script-format/SKILL.md +32 -13
  5. package/src/host/__tests__/pi-host.test.ts +235 -0
  6. package/src/host/pi-host.ts +163 -0
  7. package/src/index.ts +141 -138
  8. package/src/injectors/__tests__/engine-awareness.test.ts +292 -0
  9. package/src/injectors/__tests__/engine-section-stability.test.ts +343 -0
  10. package/src/injectors/__tests__/model-list-injector.test.ts +18 -21
  11. package/src/injectors/__tests__/subagent-list-injector.test.ts +59 -19
  12. package/src/injectors/__tests__/workflow-list-injector.test.ts +31 -17
  13. package/src/injectors/engine-awareness.ts +119 -0
  14. package/src/injectors/model-list-injector.ts +15 -58
  15. package/src/injectors/subagent-list-injector.ts +56 -114
  16. package/src/injectors/workflow-list-injector.ts +37 -70
  17. package/src/interface/__tests__/detectors.test.ts +48 -37
  18. package/src/interface/__tests__/subagent-tool-path-guard.test.ts +2 -2
  19. package/src/interface/__tests__/subagent-tool-prompt.test.ts +6 -3
  20. package/src/interface/__tests__/tool-workflow-run-builtin-name.test.ts +216 -0
  21. package/src/interface/__tests__/tool-workflow-script-generate.test.ts +17 -6
  22. package/src/interface/__tests__/tool-workflow-throw-paths.test.ts +38 -2
  23. package/src/interface/bg-notify-render.ts +7 -17
  24. package/src/interface/command-actions.ts +5 -15
  25. package/src/interface/commands.ts +4 -4
  26. package/src/interface/format.ts +17 -6
  27. package/src/interface/gui-mappers.ts +18 -22
  28. package/src/interface/helpers.ts +9 -130
  29. package/src/interface/list-component.ts +5 -5
  30. package/src/interface/list-shared.ts +3 -3
  31. package/src/interface/list-view.ts +3 -3
  32. package/src/interface/subagent-actions.ts +66 -439
  33. package/src/interface/subagent-tool-schema.ts +21 -17
  34. package/src/interface/subagent-tool.ts +12 -7
  35. package/src/interface/subagents.ts +4 -4
  36. package/src/interface/tool-render.ts +37 -15
  37. package/src/interface/tool-workflow-script.ts +34 -76
  38. package/src/interface/tool-workflow.ts +57 -94
  39. package/src/interface/views/WorkflowsView.ts +8 -16
  40. package/src/interface/views/__tests__/WorkflowsView-signature.test.ts +3 -3
  41. package/src/interface/views/__tests__/detail-content-session-file.test.ts +2 -2
  42. package/src/interface/views/detail-content.ts +4 -4
  43. package/src/interface/views/format.ts +23 -62
  44. package/src/{orchestration/jsonl-run-store.ts → jsonl-run-store.ts} +137 -225
  45. package/agents/analyst.md +0 -61
  46. package/agents/coder.md +0 -70
  47. package/agents/debugger.md +0 -67
  48. package/agents/doc-reviewer.md +0 -50
  49. package/agents/explorer.md +0 -64
  50. package/agents/general-purpose.md +0 -32
  51. package/agents/orchestrator.md +0 -63
  52. package/agents/planner.md +0 -54
  53. package/agents/researcher.md +0 -65
  54. package/agents/reviewer.md +0 -74
  55. package/src/execution/__tests__/__fixtures__/notifier-golden-snapshots.json +0 -53
  56. package/src/execution/__tests__/__fixtures__/truncline.snapshot.json +0 -1
  57. package/src/execution/__tests__/agent-registry.test.ts +0 -363
  58. package/src/execution/__tests__/agent-result-mapper.test.ts +0 -150
  59. package/src/execution/__tests__/alive-store.test.ts +0 -147
  60. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +0 -490
  61. package/src/execution/__tests__/before-agent-start-injection.test.ts +0 -132
  62. package/src/execution/__tests__/bg-notify-render.test.ts +0 -329
  63. package/src/execution/__tests__/channel-registry-handshake.test.ts +0 -243
  64. package/src/execution/__tests__/chat-engine-routing.test.ts +0 -601
  65. package/src/execution/__tests__/chatmode-first-round-closure-service.test.ts +0 -365
  66. package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +0 -190
  67. package/src/execution/__tests__/chatmode-round-notify-real-chain.test.ts +0 -215
  68. package/src/execution/__tests__/concurrency-pool.test.ts +0 -250
  69. package/src/execution/__tests__/config.test.ts +0 -110
  70. package/src/execution/__tests__/conversation-wiring.test.ts +0 -198
  71. package/src/execution/__tests__/crash-recovery.test.ts +0 -320
  72. package/src/execution/__tests__/delivery-methods.test.ts +0 -422
  73. package/src/execution/__tests__/dialog-queue.test.ts +0 -299
  74. package/src/execution/__tests__/epipe-fallback.test.ts +0 -241
  75. package/src/execution/__tests__/execute-and-await-worktree.test.ts +0 -243
  76. package/src/execution/__tests__/execute-nesting.test.ts +0 -323
  77. package/src/execution/__tests__/execute-options-mapper.test.ts +0 -200
  78. package/src/execution/__tests__/execution-record.test.ts +0 -1394
  79. package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +0 -171
  80. package/src/execution/__tests__/finalize-record.test.ts +0 -368
  81. package/src/execution/__tests__/finalized-marker.test.ts +0 -82
  82. package/src/execution/__tests__/format-schema-instruction.test.ts +0 -169
  83. package/src/execution/__tests__/format.test.ts +0 -458
  84. package/src/execution/__tests__/gc-timer.test.ts +0 -184
  85. package/src/execution/__tests__/get-record-for-action-restart.test.ts +0 -254
  86. package/src/execution/__tests__/gui-mode-dispatch.test.ts +0 -59
  87. package/src/execution/__tests__/helpers/mock-extension-api.ts +0 -30
  88. package/src/execution/__tests__/helpers/spawn-mock.ts +0 -242
  89. package/src/execution/__tests__/host-mode.test.ts +0 -87
  90. package/src/execution/__tests__/index-session-start-identity.test.ts +0 -371
  91. package/src/execution/__tests__/index-session-start.test.ts +0 -672
  92. package/src/execution/__tests__/lifecycle-manager-lock.test.ts +0 -211
  93. package/src/execution/__tests__/lifecycle-manager.test.ts +0 -383
  94. package/src/execution/__tests__/lifecycle-predicates.test.ts +0 -116
  95. package/src/execution/__tests__/list-component.test.ts +0 -401
  96. package/src/execution/__tests__/list-fields.test.ts +0 -140
  97. package/src/execution/__tests__/manifest-parentid.test.ts +0 -117
  98. package/src/execution/__tests__/model-resolver.test.ts +0 -465
  99. package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +0 -287
  100. package/src/execution/__tests__/nested-visibility.test.ts +0 -325
  101. package/src/execution/__tests__/notifier-flush.test.ts +0 -612
  102. package/src/execution/__tests__/notifier-golden-snapshot.test.ts +0 -261
  103. package/src/execution/__tests__/notify-ledger.test.ts +0 -826
  104. package/src/execution/__tests__/one-shot-upgrade.test.ts +0 -205
  105. package/src/execution/__tests__/output-collector.test.ts +0 -358
  106. package/src/execution/__tests__/parent-child-matrix.test.ts +0 -336
  107. package/src/execution/__tests__/path-encoding.test.ts +0 -104
  108. package/src/execution/__tests__/pi-invocation.test.ts +0 -134
  109. package/src/execution/__tests__/record-store.test.ts +0 -1057
  110. package/src/execution/__tests__/records-cwd-isolation.test.ts +0 -91
  111. package/src/execution/__tests__/recursive-visibility-baseline.test.ts +0 -339
  112. package/src/execution/__tests__/recursive-visibility-env.test.ts +0 -273
  113. package/src/execution/__tests__/relay-agent.test.ts +0 -448
  114. package/src/execution/__tests__/relay-env.test.ts +0 -42
  115. package/src/execution/__tests__/resource-policy.test.ts +0 -109
  116. package/src/execution/__tests__/rpc-mode.test.ts +0 -89
  117. package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +0 -267
  118. package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +0 -253
  119. package/src/execution/__tests__/run-spawn-edges.test.ts +0 -687
  120. package/src/execution/__tests__/run-spawn-integration.test.ts +0 -933
  121. package/src/execution/__tests__/run-spawn-resume.test.ts +0 -322
  122. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +0 -196
  123. package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +0 -199
  124. package/src/execution/__tests__/sdk-contract.test.ts +0 -273
  125. package/src/execution/__tests__/session-context-resolver.test.ts +0 -167
  126. package/src/execution/__tests__/session-file-gc.test.ts +0 -293
  127. package/src/execution/__tests__/session-pending.test.ts +0 -197
  128. package/src/execution/__tests__/session-reconstructor.test.ts +0 -379
  129. package/src/execution/__tests__/session-runner-epipe.test.ts +0 -178
  130. package/src/execution/__tests__/session-runner-schema-env.test.ts +0 -350
  131. package/src/execution/__tests__/session-start-reaper.test.ts +0 -233
  132. package/src/execution/__tests__/spawn-args.test.ts +0 -445
  133. package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +0 -189
  134. package/src/execution/__tests__/spawn-event-adapter.test.ts +0 -167
  135. package/src/execution/__tests__/spawn-worktree-guidance.test.ts +0 -207
  136. package/src/execution/__tests__/spawned-children.test.ts +0 -92
  137. package/src/execution/__tests__/start-sync-model-guard.test.ts +0 -150
  138. package/src/execution/__tests__/startup-config-declaration.test.ts +0 -35
  139. package/src/execution/__tests__/status-refactor.test.ts +0 -345
  140. package/src/execution/__tests__/stdin-writer.test.ts +0 -463
  141. package/src/execution/__tests__/stream-sink-retirement.test.ts +0 -261
  142. package/src/execution/__tests__/subagent-service-abort.test.ts +0 -60
  143. package/src/execution/__tests__/subagent-service-message-close.test.ts +0 -629
  144. package/src/execution/__tests__/subagent-service-parent-guard.test.ts +0 -180
  145. package/src/execution/__tests__/subagent-service.test.ts +0 -788
  146. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +0 -310
  147. package/src/execution/__tests__/subprocess-agent-runner.test.ts +0 -599
  148. package/src/execution/__tests__/temp-prompt.test.ts +0 -53
  149. package/src/execution/__tests__/timeout-integration.test.ts +0 -615
  150. package/src/execution/__tests__/tombstone-store.test.ts +0 -73
  151. package/src/execution/__tests__/tool-action.test.ts +0 -476
  152. package/src/execution/__tests__/truncline-snapshot.test.ts +0 -81
  153. package/src/execution/__tests__/turn-limiter-semantics.test.ts +0 -194
  154. package/src/execution/__tests__/turn-limiter.test.ts +0 -65
  155. package/src/execution/__tests__/ui-channels.test.ts +0 -187
  156. package/src/execution/__tests__/ui-interaction-model.test.ts +0 -67
  157. package/src/execution/__tests__/ui-request-handler-factory.test.ts +0 -370
  158. package/src/execution/__tests__/ui-request-handler.test.ts +0 -204
  159. package/src/execution/__tests__/ui-request-observability.test.ts +0 -114
  160. package/src/execution/__tests__/ui-request-queue.test.ts +0 -133
  161. package/src/execution/__tests__/worktree-manager.test.ts +0 -633
  162. package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +0 -229
  163. package/src/execution/__tests__/worktree-reconcile.integration.test.ts +0 -181
  164. package/src/execution/__tests__/worktree-registry.test.ts +0 -199
  165. package/src/execution/agent-registry.ts +0 -199
  166. package/src/execution/agent-result-mapper.ts +0 -90
  167. package/src/execution/alive-store.ts +0 -92
  168. package/src/execution/argv-mirror.ts +0 -113
  169. package/src/execution/best-effort.ts +0 -38
  170. package/src/execution/channel-registry-access.ts +0 -144
  171. package/src/execution/concurrency-pool.ts +0 -116
  172. package/src/execution/config.ts +0 -96
  173. package/src/execution/dialog-queue.ts +0 -330
  174. package/src/execution/engine/__tests__/common/data-dir.test.ts +0 -53
  175. package/src/execution/engine/__tests__/common/errors.test.ts +0 -132
  176. package/src/execution/engine/__tests__/common/event-journal.test.ts +0 -177
  177. package/src/execution/engine/__tests__/common/kill-chain.test.ts +0 -192
  178. package/src/execution/engine/__tests__/common/nesting-guard.test.ts +0 -81
  179. package/src/execution/engine/__tests__/common/persona-router.test.ts +0 -123
  180. package/src/execution/engine/__tests__/common/pool-manager.test.ts +0 -154
  181. package/src/execution/engine/__tests__/common/schema-emulation.test.ts +0 -128
  182. package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +0 -28
  183. package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +0 -141
  184. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +0 -109
  185. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +0 -101
  186. package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +0 -77
  187. package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +0 -104
  188. package/src/execution/engine/__tests__/conformance/contract.relay.test.ts +0 -342
  189. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +0 -201
  190. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +0 -76
  191. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +0 -79
  192. package/src/execution/engine/__tests__/engine-discovery.test.ts +0 -87
  193. package/src/execution/engine/__tests__/engines-declaration.test.ts +0 -36
  194. package/src/execution/engine/__tests__/model-prompt.test.ts +0 -85
  195. package/src/execution/engine/__tests__/paths.test.ts +0 -39
  196. package/src/execution/engine/__tests__/registry.test.ts +0 -120
  197. package/src/execution/engine/__tests__/routing.test.ts +0 -231
  198. package/src/execution/engine/common/data-dir.ts +0 -62
  199. package/src/execution/engine/common/errors.ts +0 -183
  200. package/src/execution/engine/common/event-journal.ts +0 -254
  201. package/src/execution/engine/common/journal-replay.ts +0 -62
  202. package/src/execution/engine/common/kill-chain.ts +0 -221
  203. package/src/execution/engine/common/nesting-guard.ts +0 -50
  204. package/src/execution/engine/common/persona-router.ts +0 -108
  205. package/src/execution/engine/common/pool-manager.ts +0 -226
  206. package/src/execution/engine/common/schema-emulation.ts +0 -189
  207. package/src/execution/engine/common/session-view-projection.ts +0 -51
  208. package/src/execution/engine/engine-discovery.ts +0 -65
  209. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +0 -469
  210. package/src/execution/engine/engines/pi/__tests__/reader.test.ts +0 -155
  211. package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +0 -164
  212. package/src/execution/engine/engines/pi/pi-engine.ts +0 -415
  213. package/src/execution/engine/engines/pi/reader.ts +0 -48
  214. package/src/execution/engine/engines/pi/registration.ts +0 -35
  215. package/src/execution/engine/engines/pi/task-spec-mapper.ts +0 -100
  216. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +0 -39
  217. package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +0 -150
  218. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +0 -246
  219. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +0 -228
  220. package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +0 -210
  221. package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +0 -64
  222. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +0 -127
  223. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +0 -580
  224. package/src/execution/engine/engines/zcode/constants.ts +0 -43
  225. package/src/execution/engine/engines/zcode/golden-sample.ts +0 -39
  226. package/src/execution/engine/engines/zcode/launcher.ts +0 -161
  227. package/src/execution/engine/engines/zcode/parser.ts +0 -436
  228. package/src/execution/engine/engines/zcode/preparer.ts +0 -363
  229. package/src/execution/engine/engines/zcode/reader.ts +0 -381
  230. package/src/execution/engine/engines/zcode/registration.ts +0 -37
  231. package/src/execution/engine/engines/zcode/zcode-engine.ts +0 -658
  232. package/src/execution/engine/host-task-spec.ts +0 -47
  233. package/src/execution/engine/model-prompt.ts +0 -59
  234. package/src/execution/engine/paths.ts +0 -42
  235. package/src/execution/engine/port.ts +0 -153
  236. package/src/execution/engine/registry.ts +0 -123
  237. package/src/execution/engine/routing.ts +0 -218
  238. package/src/execution/engine/types.ts +0 -309
  239. package/src/execution/execute-options-mapper.ts +0 -112
  240. package/src/execution/execution-record.ts +0 -965
  241. package/src/execution/finalize-record.ts +0 -251
  242. package/src/execution/finalized-marker.ts +0 -51
  243. package/src/execution/get-state-handshake.ts +0 -104
  244. package/src/execution/host-mode.ts +0 -56
  245. package/src/execution/idle-gc.ts +0 -47
  246. package/src/execution/lifecycle-manager.ts +0 -513
  247. package/src/execution/lifecycle-predicates.ts +0 -65
  248. package/src/execution/manifest-store.ts +0 -256
  249. package/src/execution/model-config-service.ts +0 -219
  250. package/src/execution/model-resolver.ts +0 -248
  251. package/src/execution/notifier.ts +0 -330
  252. package/src/execution/notify-ledger.ts +0 -580
  253. package/src/execution/output-collector.ts +0 -228
  254. package/src/execution/path-encoding.ts +0 -60
  255. package/src/execution/pi-invocation.ts +0 -120
  256. package/src/execution/record-entry.ts +0 -132
  257. package/src/execution/record-store.ts +0 -1234
  258. package/src/execution/relay-env.ts +0 -37
  259. package/src/execution/session-context-resolver.ts +0 -64
  260. package/src/execution/session-file-gc.ts +0 -120
  261. package/src/execution/session-pending.ts +0 -164
  262. package/src/execution/session-reconstructor.ts +0 -678
  263. package/src/execution/session-runner.ts +0 -1781
  264. package/src/execution/sessions-index.ts +0 -304
  265. package/src/execution/spawn-event-adapter.ts +0 -363
  266. package/src/execution/stdin-writer.ts +0 -198
  267. package/src/execution/stream-sink.ts +0 -126
  268. package/src/execution/subagent-service.ts +0 -2141
  269. package/src/execution/subprocess-agent-runner.ts +0 -317
  270. package/src/execution/temp-prompt.ts +0 -62
  271. package/src/execution/tombstone-store.ts +0 -72
  272. package/src/execution/turn-limiter.ts +0 -102
  273. package/src/execution/types.ts +0 -973
  274. package/src/execution/ui-channels.ts +0 -216
  275. package/src/execution/ui-interaction-model.ts +0 -48
  276. package/src/execution/ui-request-handler-factory.ts +0 -212
  277. package/src/execution/ui-request-observability.ts +0 -81
  278. package/src/execution/ui-request-queue.ts +0 -184
  279. package/src/execution/worktree-manager.ts +0 -688
  280. package/src/execution/worktree-registry.ts +0 -222
  281. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +0 -349
  282. package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +0 -202
  283. package/src/orchestration/__tests__/agent-call-stream.test.ts +0 -152
  284. package/src/orchestration/__tests__/args-validator.test.ts +0 -143
  285. package/src/orchestration/__tests__/config-loader.test.ts +0 -503
  286. package/src/orchestration/__tests__/error-recovery-handlers.test.ts +0 -809
  287. package/src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts +0 -405
  288. package/src/orchestration/__tests__/error-recovery-serialize-failed-result.test.ts +0 -56
  289. package/src/orchestration/__tests__/error-recovery-workflow-call.test.ts +0 -166
  290. package/src/orchestration/__tests__/execute-agent-call.test.ts +0 -451
  291. package/src/orchestration/__tests__/jsonl-run-store-corrupt-entry.test.ts +0 -150
  292. package/src/orchestration/__tests__/jsonl-run-store-loadall-sources.test.ts +0 -171
  293. package/src/orchestration/__tests__/jsonl-run-store-retention.test.ts +0 -202
  294. package/src/orchestration/__tests__/jsonl-run-store-session-file.test.ts +0 -1030
  295. package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +0 -600
  296. package/src/orchestration/__tests__/lifecycle-runid-injection.test.ts +0 -96
  297. package/src/orchestration/__tests__/lifecycle.test.ts +0 -659
  298. package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +0 -95
  299. package/src/orchestration/__tests__/review-fix-loop-e2e.test.ts +0 -2025
  300. package/src/orchestration/__tests__/script-lint.test.ts +0 -831
  301. package/src/orchestration/__tests__/skill-discovery.test.ts +0 -201
  302. package/src/orchestration/__tests__/test-mocks.ts +0 -197
  303. package/src/orchestration/__tests__/worker-exit-without-result.test.ts +0 -368
  304. package/src/orchestration/__tests__/worker-host.test.ts +0 -120
  305. package/src/orchestration/__tests__/worker-returnmeta-passthrough.test.ts +0 -164
  306. package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +0 -563
  307. package/src/orchestration/__tests__/worker-script-builder.test.ts +0 -309
  308. package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +0 -129
  309. package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +0 -317
  310. package/src/orchestration/__tests__/workflow-script-lint-memo.test.ts +0 -110
  311. package/src/orchestration/__tests__/workflows-e2e.test.ts +0 -537
  312. package/src/orchestration/agent-opts-resolver.ts +0 -174
  313. package/src/orchestration/args-validator.ts +0 -127
  314. package/src/orchestration/config-loader.ts +0 -315
  315. package/src/orchestration/error-recovery.ts +0 -1018
  316. package/src/orchestration/execute-agent-call.ts +0 -256
  317. package/src/orchestration/launcher.ts +0 -455
  318. package/src/orchestration/lifecycle.ts +0 -399
  319. package/src/orchestration/models/__tests__/budget.test.ts +0 -307
  320. package/src/orchestration/models/__tests__/trace.test.ts +0 -408
  321. package/src/orchestration/models/agent-call.ts +0 -83
  322. package/src/orchestration/models/budget.ts +0 -118
  323. package/src/orchestration/models/ports.ts +0 -164
  324. package/src/orchestration/models/run-runtime.ts +0 -104
  325. package/src/orchestration/models/run-spec.ts +0 -83
  326. package/src/orchestration/models/run-state.ts +0 -44
  327. package/src/orchestration/models/trace.ts +0 -183
  328. package/src/orchestration/models/types.ts +0 -301
  329. package/src/orchestration/models/workflow-run.ts +0 -254
  330. package/src/orchestration/models/workflow-script-registry.ts +0 -35
  331. package/src/orchestration/models/workflow-script.ts +0 -117
  332. package/src/orchestration/script-lint.ts +0 -766
  333. package/src/orchestration/skill-discovery.ts +0 -115
  334. package/src/orchestration/worker-handle.ts +0 -115
  335. package/src/orchestration/worker-host.ts +0 -98
  336. package/src/orchestration/worker-script-builder.ts +0 -421
  337. package/src/orchestration/workflow-files.ts +0 -85
  338. package/src/orchestration/workflow-script-registry-impl.ts +0 -133
  339. package/src/shared/__tests__/agent-ref.test.ts +0 -34
  340. package/src/shared/__tests__/meta-parser.test.ts +0 -304
  341. package/src/shared/__tests__/model-ref.test.ts +0 -306
  342. package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +0 -280
  343. package/src/shared/__tests__/resource-discovery.test.ts +0 -736
  344. package/src/shared/__tests__/resource-meta.test.ts +0 -51
  345. package/src/shared/__tests__/schema-jsonify.test.ts +0 -81
  346. package/src/shared/__tests__/timer-delay.test.ts +0 -61
  347. package/src/shared/agent-event.ts +0 -13
  348. package/src/shared/agent-ref.ts +0 -57
  349. package/src/shared/meta-parser.ts +0 -261
  350. package/src/shared/model-ref.ts +0 -286
  351. package/src/shared/resource-discovery.ts +0 -811
  352. package/src/shared/resource-meta.ts +0 -65
  353. package/src/shared/schema-env.ts +0 -44
  354. package/src/shared/schema-jsonify.ts +0 -58
  355. package/src/shared/timer-delay.ts +0 -54
  356. package/src/shared/xml-injection.ts +0 -35
  357. package/workflows/README.md +0 -81
  358. package/workflows/_shared/agent-refs.cjs +0 -40
  359. package/workflows/chain.js +0 -131
  360. package/workflows/map-reduce.js +0 -174
  361. package/workflows/parallel.js +0 -148
  362. package/workflows/review-fix-loop-utils.cjs +0 -1309
  363. package/workflows/review-fix-loop.js +0 -1404
  364. package/workflows/scatter-gather.js +0 -178
@@ -1,659 +0,0 @@
1
- /**
2
- * lifecycle — runWorkflow/abortRun/terminateRunningRuns/scheduleTimeBudget/evict 测试。
3
- *
4
- * 用真实 WorkflowRun(含真实状态机 + I1/I2 不变式守卫)+ mock RunRuntime(释放副作用
5
- * 可控)+ mock LifecycleDeps(store/workerHost/eventBus 可观察)。这样能真正测到
6
- * transition/assignRuntime/releaseRuntime 的状态机逻辑,而非全 mock 聚合根。
7
- *
8
- * 覆盖:
9
- * - runWorkflow:spec → 创建 run + workerHost.start + store.save + emit pending:register
10
- * - abortRun:done no-op / running→done + emit pending:unregister
11
- * - terminateRunningRuns:session 切换/关闭时仅 running 被终止(done,failed 落盘)
12
- * - scheduleTimeBudget:定时器到期 → abortRun(done,time_limited)(用 fake timers)
13
- * - evictDoneRunsBeyondCap:done run 内存淘汰白名单/排序/tie
14
- */
15
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
16
-
17
- import {
18
- abortRun,
19
- evictDoneRunsBeyondCap,
20
- MAX_RETAINED_DONE_RUNS,
21
- runWorkflow,
22
- scheduleTimeBudget,
23
- terminateRunningRuns,
24
- } from "../lifecycle.ts";
25
- import { ArgsValidationError } from "../args-validator.ts";
26
- import { Budget } from "../models/budget.ts";
27
- import { RunRuntime } from "../models/run-runtime.ts";
28
- import { Trace } from "../models/trace.ts";
29
- import type { RunSpec } from "../models/run-spec.ts";
30
- import type { LifecycleDeps } from "../models/ports.ts";
31
- import { WorkflowRun } from "../models/workflow-run.ts";
32
-
33
- // ── helpers ──────────────────────────────────────────────────
34
-
35
- /** 构造一个最小 RunSpec(满足 WorkflowRun 构造的字段需求)。 */
36
- function makeSpec(opts: {
37
- budgetTimeMs?: number;
38
- budgetTokens?: number;
39
- parameters?: Record<string, unknown>;
40
- args?: Record<string, unknown>;
41
- } = {}): RunSpec {
42
- return {
43
- scriptSource: "execute() {}",
44
- args: opts.args ?? {},
45
- parameters: opts.parameters,
46
- scriptName: "test-wf",
47
- scriptPath: "/fake/test.js",
48
- budgetTimeMs: opts.budgetTimeMs,
49
- budgetTokens: opts.budgetTokens,
50
- };
51
- }
52
-
53
- /**
54
- * 构造一个 status="running" 的真实 WorkflowRun,注入 mock RunRuntime。
55
- *
56
- * 流程:new WorkflowRun(status=running,I1 构造期跳过)→ assignRuntime
57
- * (注入 runtime,恢复 I1)。mock runtime 的 worker.terminate / controller.abort /
58
- * release 均可观察。
59
- */
60
- /** flush microtask 队列多次,让 void .then().catch() + async 链跑完。
61
- *
62
- * 注意:fake timers 下 setTimeout(resolve,0) 也会被拦截,故用 Promise.resolve()
63
- * 走原生 microtask 队列(不被 fake timers 拦截)。 */
64
- async function flushMicrotasks(times = 10): Promise<void> {
65
- for (let i = 0; i < times; i++) {
66
- await Promise.resolve();
67
- }
68
- }
69
-
70
- function makeRunningRealRun(
71
- runId: string,
72
- opts: { budgetTimeMs?: number } = {},
73
- ): { run: WorkflowRun; terminate: ReturnType<typeof vi.fn>; abort: ReturnType<typeof vi.fn> } {
74
- const spec = makeSpec(opts);
75
- const run = new WorkflowRun(
76
- runId,
77
- spec,
78
- {
79
- status: "running",
80
- budget: new Budget({ maxTokens: 1000 }),
81
- calls: new Map(),
82
- trace: new Trace(),
83
- errorLogs: [],
84
- },
85
- { startedAt: new Date().toISOString() },
86
- );
87
- const terminate = vi.fn(async () => {});
88
- const controller = new AbortController();
89
- const abort = vi.spyOn(controller, "abort");
90
- const worker = { terminate, postMessage: vi.fn() } as unknown as Parameters<typeof RunRuntime.prototype.constructor>[0];
91
- const runtime = new RunRuntime(
92
- worker as never,
93
- controller,
94
- undefined,
95
- );
96
- run.assignRuntime(runtime);
97
- return { run, terminate, abort };
98
- }
99
-
100
- /** LifecycleDeps mock:store/workerHost/eventBus/onRunDone/log 可观察。 */
101
- function makeDeps(): LifecycleDeps & {
102
- store: { save: ReturnType<typeof vi.fn>; loadAll: ReturnType<typeof vi.fn> };
103
- workerHost: { start: ReturnType<typeof vi.fn> };
104
- eventBus: { emit: ReturnType<typeof vi.fn> };
105
- onRunDone: ReturnType<typeof vi.fn>;
106
- log: ReturnType<typeof vi.fn>;
107
- } {
108
- return {
109
- store: { save: vi.fn(async () => {}), loadAll: vi.fn(async () => []) },
110
- workerHost: { start: vi.fn(() => ({ postMessage: vi.fn(), terminate: vi.fn(async () => {}) })) },
111
- runner: { run: vi.fn(async () => ({})) },
112
- runs: new Map(),
113
- eventBus: { emit: vi.fn() },
114
- onRunDone: vi.fn(),
115
- log: vi.fn(),
116
- } as unknown as ReturnType<typeof makeDeps>;
117
- }
118
-
119
- beforeEach(() => {
120
- vi.useFakeTimers();
121
- });
122
-
123
- afterEach(() => {
124
- vi.useRealTimers();
125
- });
126
-
127
- // ── scheduleTimeBudget ───────────────────────────────────────
128
-
129
- describe("scheduleTimeBudget", () => {
130
- it("定时器到期 → abortRun(done,time_limited)", async () => {
131
- const { run } = makeRunningRealRun("wf-budget-1");
132
- const deps = makeDeps();
133
- deps.runs.set("wf-budget-1", run);
134
-
135
- const timer = scheduleTimeBudget("wf-budget-1", deps, 1000);
136
- expect(timer).toBeDefined();
137
-
138
- // 推进定时器到到期 + flush 让 abortRun async 链跑完
139
- await vi.advanceTimersByTimeAsync(1000);
140
- await flushMicrotasks();
141
-
142
- expect(run.state.status).toBe("done");
143
- expect(run.state.reason).toBe("time_limited");
144
- expect(run.state.error).toContain("Time budget exceeded");
145
- // 完成通知
146
- expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:unregister", {
147
- id: "wf-budget-1",
148
- reason: "time_limited",
149
- });
150
- expect(deps.onRunDone).toHaveBeenCalledTimes(1);
151
- });
152
-
153
- it("run 已 done 时 abortRun no-op(到期不重复 transition)", async () => {
154
- const { run } = makeRunningRealRun("wf-budget-2");
155
- // 先把 run 转 done(手动)
156
- run.transition("done", "completed");
157
- const deps = makeDeps();
158
- deps.runs.set("wf-budget-2", run);
159
-
160
- scheduleTimeBudget("wf-budget-2", deps, 500);
161
- await vi.advanceTimersByTimeAsync(500);
162
- await flushMicrotasks();
163
-
164
- // 状态保持原 done/completed,未被 time_limited 覆盖
165
- expect(run.state.reason).toBe("completed");
166
- expect(deps.onRunDone).not.toHaveBeenCalled();
167
- });
168
-
169
- it("定时器 unref(不阻止 Node 退出)", () => {
170
- const deps = makeDeps();
171
- const timer = scheduleTimeBudget("wf-x", deps, 10000);
172
- // unref 是 Node timer 的方法,fake timer 也支持——验证不抛错
173
- expect(() => timer.unref()).not.toThrow();
174
- timer.unref();
175
- });
176
-
177
- // [U1] setTimeout 2^31-1 溢出 fail-fast:溢出 budgetTimeMs 被 Node 置 1ms 立即触发
178
- //(「不限时预算」变「立即超时」),arm 入口拦截且错误含上限值与恢复指引。
179
- it("budgetTimeMs 溢出(>2^31-1)→ fail-fast throw(不挂 timer、不静默 clamp)", () => {
180
- const deps = makeDeps();
181
- expect(() => scheduleTimeBudget("wf-overflow", deps, 3_000_000_000)).toThrowError(/2147483647/);
182
- expect(() => scheduleTimeBudget("wf-overflow", deps, Number.MAX_SAFE_INTEGER)).toThrowError(
183
- /Recovery/,
184
- );
185
- });
186
- });
187
-
188
- // ── runWorkflow ──────────────────────────────────────────────
189
-
190
- describe("runWorkflow", () => {
191
- it("spec → 创建 run + 启动 worker + store.save + emit pending:register", async () => {
192
- const deps = makeDeps();
193
- const spec = makeSpec();
194
-
195
- const runId = await runWorkflow(spec, deps);
196
-
197
- expect(runId).toMatch(/^wf-/);
198
- // run 注册到 deps.runs
199
- expect(deps.runs.has(runId)).toBe(true);
200
- const run = deps.runs.get(runId)!;
201
- // status 为 running(assignRuntime 已绑定 runtime)
202
- expect(run.state.status).toBe("running");
203
- expect(run.runtime).toBeDefined();
204
- // workerHost.start 被调
205
- expect(deps.workerHost.start).toHaveBeenCalledTimes(1);
206
- // store.save 持久化
207
- expect(deps.store.save).toHaveBeenCalledTimes(1);
208
- // pending:register 通知
209
- expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:register", {
210
- id: runId,
211
- type: "workflow",
212
- name: "test-wf",
213
- });
214
- });
215
-
216
- it("创建即 running:构造即 running,runs.set 在 assignRuntime 后(I1 窗口对外不可见)", async () => {
217
- const deps = makeDeps();
218
- // worker.start 被调时探测 runs 注册状态——证明 runs.set 在 assignRuntime 之后
219
- let runsSizeAtWorkerStart = -1;
220
- deps.workerHost.start = vi.fn(() => {
221
- runsSizeAtWorkerStart = deps.runs.size;
222
- return { postMessage: vi.fn(), terminate: vi.fn(async () => {}) };
223
- });
224
-
225
- const runId = await runWorkflow(makeSpec(), deps);
226
-
227
- // worker.start 执行时 run 尚未注册(I1 跳过窗口不外泄)
228
- expect(runsSizeAtWorkerStart).toBe(0);
229
- // 完成后已注册,且构造即 running + runtime 已注入(I1 成立)
230
- expect(deps.runs.has(runId)).toBe(true);
231
- const run = deps.runs.get(runId)!;
232
- expect(run.state.status).toBe("running");
233
- expect(run.runtime).toBeDefined();
234
- // save 落盘的是恢复 I1 后的聚合(status running + runtime 已绑定)
235
- const savedRun = deps.store.save.mock.calls[0]![0] as WorkflowRun;
236
- expect(savedRun).toBe(run);
237
- expect(savedRun.state.status).toBe("running");
238
- });
239
-
240
- it("worker.start 抛错 → runWorkflow 拒绝且 runs 无孤儿注册", async () => {
241
- const deps = makeDeps();
242
- deps.workerHost.start = vi.fn(() => {
243
- throw new Error("worker boot failed");
244
- });
245
-
246
- await expect(runWorkflow(makeSpec(), deps)).rejects.toThrow("worker boot failed");
247
-
248
- // 无孤儿:启动失败时 run 未注册进 deps.runs(runs.set 在 start 之后)
249
- expect(deps.runs.size).toBe(0);
250
- expect(deps.store.save).not.toHaveBeenCalled();
251
- expect(deps.eventBus.emit).not.toHaveBeenCalled();
252
- });
253
-
254
- it("带 budgetTimeMs 时调度时间预算计时器(真实消费:挂载 + 到期 time_limited)", async () => {
255
- const deps = makeDeps();
256
- const spec = makeSpec({ budgetTimeMs: 3000 });
257
-
258
- const runId = await runWorkflow(spec, deps);
259
- const run = deps.runs.get(runId)!;
260
-
261
- // 生产行为面①:budgetTimeMs>0 → RunRuntime.timeBudgetTimer 被真实挂载
262
- //(scheduleTimeBudget 产出的 Node timer,非死代码 spy)
263
- expect(run.runtime?.timeBudgetTimer).toBeDefined();
264
-
265
- // 生产行为面②:到期后 abortRun(time_limited) 真实触发——run 转 done,
266
- // reason/error/通知全部落位(文件级 beforeEach 已 fake timers)
267
- await vi.advanceTimersByTimeAsync(3000);
268
- await flushMicrotasks();
269
-
270
- expect(run.state.status).toBe("done");
271
- expect(run.state.reason).toBe("time_limited");
272
- expect(run.state.error).toContain("Time budget exceeded");
273
- expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:unregister", {
274
- id: runId,
275
- reason: "time_limited",
276
- });
277
- });
278
-
279
- it("未传 budgetTimeMs → 不挂时间预算计时器(对照:runtime.timeBudgetTimer undefined)", async () => {
280
- const deps = makeDeps();
281
- const runId = await runWorkflow(makeSpec(), deps);
282
- const run = deps.runs.get(runId)!;
283
-
284
- expect(run.runtime?.timeBudgetTimer).toBeUndefined();
285
-
286
- // 无预算 → 不存在到期 abort:推进 10min 后 run 仍 running
287
- await vi.advanceTimersByTimeAsync(10 * 60 * 1000);
288
- await flushMicrotasks();
289
- expect(run.state.status).toBe("running");
290
- });
291
-
292
- it("signal 已 abort → fail fast(抛错,不创建 run)", async () => {
293
- const deps = makeDeps();
294
- const spec = makeSpec();
295
- const controller = new AbortController();
296
- controller.abort();
297
-
298
- await expect(runWorkflow(spec, deps, controller.signal)).rejects.toThrow(
299
- "aborted before start",
300
- );
301
- expect(deps.runs.size).toBe(0);
302
- expect(deps.workerHost.start).not.toHaveBeenCalled();
303
- });
304
-
305
- it("TC8: 参数校验失败 → throw ArgsValidationError + zero side effects(E9)", async () => {
306
- const deps = makeDeps();
307
- const controller = new AbortController();
308
- const addSpy = vi.spyOn(controller.signal, "addEventListener");
309
- const spec = makeSpec({
310
- parameters: {
311
- type: "object",
312
- properties: { target: { type: "string" } },
313
- required: ["target"],
314
- },
315
- args: {},
316
- });
317
-
318
- await expect(runWorkflow(spec, deps, controller.signal)).rejects.toThrow(ArgsValidationError);
319
- expect(deps.runs.size).toBe(0);
320
- expect(deps.workerHost.start).not.toHaveBeenCalled();
321
- expect(deps.store.save).not.toHaveBeenCalled();
322
- expect(deps.eventBus.emit).not.toHaveBeenCalled();
323
- expect(addSpy).not.toHaveBeenCalled();
324
- expect(deps.log).not.toHaveBeenCalled(); // 校验在 deps.log 前 throw(无日志痕迹)
325
- });
326
- });
327
-
328
- // ── abortRun ─────────────────────────────────────────────────
329
-
330
- describe("abortRun", () => {
331
- it("running run → done,aborted:releaseRuntime + emit pending:unregister", async () => {
332
- const { run, terminate } = makeRunningRealRun("wf-abort-1");
333
- const deps = makeDeps();
334
- deps.runs.set("wf-abort-1", run);
335
-
336
- await abortRun("wf-abort-1", deps, "user cancelled");
337
-
338
- expect(run.state.status).toBe("done");
339
- expect(run.state.reason).toBe("aborted");
340
- expect(run.state.error).toBe("user cancelled");
341
- expect(terminate).toHaveBeenCalledTimes(1);
342
- expect(run.runtime).toBeUndefined();
343
- expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:unregister", {
344
- id: "wf-abort-1",
345
- reason: "aborted",
346
- });
347
- expect(deps.onRunDone).toHaveBeenCalledTimes(1);
348
- });
349
-
350
- it("done 状态 no-op(不重复 abort)", async () => {
351
- const { run } = makeRunningRealRun("wf-abort-2");
352
- run.transition("done", "completed");
353
- const deps = makeDeps();
354
- deps.runs.set("wf-abort-2", run);
355
-
356
- await abortRun("wf-abort-2", deps, "late abort");
357
-
358
- expect(run.state.reason).toBe("completed"); // 未被覆盖
359
- expect(deps.onRunDone).not.toHaveBeenCalled();
360
- });
361
-
362
- it("自定义 doneReason(time_limited)", async () => {
363
- const { run } = makeRunningRealRun("wf-abort-3");
364
- const deps = makeDeps();
365
- deps.runs.set("wf-abort-3", run);
366
-
367
- await abortRun("wf-abort-3", deps, "timeout", "time_limited");
368
-
369
- expect(run.state.reason).toBe("time_limited");
370
- expect(run.state.error).toBe("timeout");
371
- });
372
-
373
- it("runId 不存在 → 抛错", async () => {
374
- const deps = makeDeps();
375
- await expect(abortRun("wf-missing", deps)).rejects.toThrow("not found");
376
- });
377
- });
378
-
379
- // ── terminateRunningRuns ─────────────────────────────────────
380
-
381
- describe("terminateRunningRuns", () => {
382
- it("多 run 中仅 running 被终止(done run 不动)", async () => {
383
- const { run: running1 } = makeRunningRealRun("wf-term-1");
384
- const { run: running2 } = makeRunningRealRun("wf-term-2");
385
- const { run: doneRun } = makeRunningRealRun("wf-term-done");
386
- doneRun.transition("done", "completed");
387
- const deps = makeDeps();
388
- deps.runs.set("wf-term-1", running1);
389
- deps.runs.set("wf-term-2", running2);
390
- deps.runs.set("wf-term-done", doneRun);
391
-
392
- await terminateRunningRuns(deps, "Session switched: run terminated");
393
-
394
- // running 全部转 done,failed
395
- expect(running1.state.status).toBe("done");
396
- expect(running1.state.reason).toBe("failed");
397
- expect(running2.state.status).toBe("done");
398
- expect(running2.state.reason).toBe("failed");
399
- // done run 不被重写(保留 completed)
400
- expect(doneRun.state.reason).toBe("completed");
401
- });
402
-
403
- it("每个被终止的 run 发 pending:unregister(reason=failed)且不调 onRunDone", async () => {
404
- const { run: r1 } = makeRunningRealRun("wf-term-3");
405
- const { run: r2 } = makeRunningRealRun("wf-term-4");
406
- const deps = makeDeps();
407
- deps.runs.set("wf-term-3", r1);
408
- deps.runs.set("wf-term-4", r2);
409
-
410
- await terminateRunningRuns(deps, "Session shutdown: run terminated");
411
-
412
- expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:unregister", {
413
- id: "wf-term-3",
414
- reason: "failed",
415
- });
416
- expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:unregister", {
417
- id: "wf-term-4",
418
- reason: "failed",
419
- });
420
- // 对齐 session_start 恢复先例:主 agent 已离开本 session,不发完成通知
421
- expect(deps.onRunDone).not.toHaveBeenCalled();
422
- });
423
-
424
- it("state.error = reason、reason 字段 = failed、run 落盘(releaseRuntime 解绑 runtime)", async () => {
425
- const { run, terminate } = makeRunningRealRun("wf-term-5");
426
- const deps = makeDeps();
427
- deps.runs.set("wf-term-5", run);
428
-
429
- await terminateRunningRuns(deps, "Session switched: run terminated");
430
-
431
- expect(run.state.error).toBe("Session switched: run terminated");
432
- expect(run.state.reason).toBe("failed");
433
- expect(run.runtime).toBeUndefined();
434
- expect(terminate).toHaveBeenCalledTimes(1);
435
- expect(deps.store.save).toHaveBeenCalledTimes(1);
436
- expect(deps.store.save).toHaveBeenCalledWith(run);
437
- });
438
-
439
- it("单 run save 抛错不中断其余(其余 run 仍落盘 + unregister)", async () => {
440
- const { run: bad } = makeRunningRealRun("wf-term-err");
441
- const { run: good } = makeRunningRealRun("wf-term-ok");
442
- const deps = makeDeps();
443
- deps.runs.set("wf-term-err", bad);
444
- deps.runs.set("wf-term-ok", good);
445
- deps.store.save = vi.fn(async (r: WorkflowRun) => {
446
- if (r.runId === "wf-term-err") throw new Error("disk full");
447
- });
448
-
449
- await terminateRunningRuns(deps, "Session shutdown: run terminated");
450
-
451
- // 抛错的 run:transition 先于 save,状态已转 done,但 unregister 被 save 失败短路
452
- expect(bad.state.status).toBe("done");
453
- expect(bad.state.reason).toBe("failed");
454
- expect(deps.eventBus.emit).not.toHaveBeenCalledWith("pending:unregister", {
455
- id: "wf-term-err",
456
- reason: "failed",
457
- });
458
- // 其余 run 正常走完落盘 + unregister(单 run 失败不中断批量终止)
459
- expect(good.state.status).toBe("done");
460
- expect(deps.store.save).toHaveBeenCalledWith(good);
461
- expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:unregister", {
462
- id: "wf-term-ok",
463
- reason: "failed",
464
- });
465
- });
466
- });
467
-
468
- // ── evictDoneRunsBeyondCap ────────────────────────────────────
469
-
470
- /**
471
- * 构造可重水合的 WorkflowRun 快照(对齐 crash-recovery.test.ts makeRun 模式——
472
- * WorkflowRun.reconstruct 与构造同语义:I1 构造期跳过,running 快照合法)。
473
- *
474
- * @param runId run 标识
475
- * @param opts.completedAt 完成时刻 ISO 串(缺省=缺失场景,模拟旧格式/异常快照)
476
- * @param opts.status 状态(默认 done;running 用于白名单验证)
477
- */
478
- function makeEvictableRun(
479
- runId: string,
480
- opts: { completedAt?: string; status?: "running" | "done" } = {},
481
- ): WorkflowRun {
482
- const status = opts.status ?? "done";
483
- return WorkflowRun.reconstruct(
484
- runId,
485
- {
486
- scriptSource: "execute() {}",
487
- args: {},
488
- scriptName: "test",
489
- scriptPath: "/fake/test.js",
490
- },
491
- {
492
- status,
493
- reason: status === "done" ? "completed" : undefined,
494
- budget: new Budget({ maxTokens: 1000 }),
495
- calls: new Map(),
496
- trace: new Trace(),
497
- errorLogs: [],
498
- },
499
- {
500
- startedAt: opts.completedAt ?? "2026-08-15T00:00:00.000Z",
501
- ...(opts.completedAt !== undefined ? { completedAt: opts.completedAt } : {}),
502
- },
503
- );
504
- }
505
-
506
- /** ISO 基准时刻(过去时刻),isoAt(n) = 基准 + n 分钟。 */
507
- const EVICT_T0 = Date.parse("2020-01-01T00:00:00.000Z");
508
- function isoAt(min: number): string {
509
- return new Date(EVICT_T0 + min * 60_000).toISOString();
510
- }
511
-
512
- describe("evictDoneRunsBeyondCap(done run 内存淘汰,K=MAX_RETAINED_DONE_RUNS)", () => {
513
- it("W3TC1: 状态白名单——仅 done 可淘汰,running 永不删", () => {
514
- const runs = new Map<string, WorkflowRun>();
515
- runs.set("wf-done-1", makeEvictableRun("wf-done-1", { completedAt: isoAt(1) }));
516
- runs.set("wf-done-2", makeEvictableRun("wf-done-2", { completedAt: isoAt(2) }));
517
- runs.set("wf-done-3", makeEvictableRun("wf-done-3", { completedAt: isoAt(3) }));
518
- runs.set("wf-run-1", makeEvictableRun("wf-run-1", { status: "running" }));
519
- runs.set("wf-run-2", makeEvictableRun("wf-run-2", { status: "running" }));
520
-
521
- const evicted = evictDoneRunsBeyondCap(runs, 2);
522
-
523
- // 3 done 超保留数 2 → 淘汰最旧 1 个
524
- expect(evicted).toBe(1);
525
- // running 全部仍在 Map(白名单外,即使 completedAt 缺失也不参与排序淘汰)
526
- for (const id of ["wf-run-1", "wf-run-2"]) {
527
- expect(runs.has(id)).toBe(true);
528
- }
529
- // done 仅剩 t2/t3 两个(t1 最旧被淘汰)
530
- expect(runs.has("wf-done-1")).toBe(false);
531
- expect(runs.has("wf-done-2")).toBe(true);
532
- expect(runs.has("wf-done-3")).toBe(true);
533
- expect(runs.size).toBe(4);
534
- });
535
-
536
- it("W3TC2: 按 meta.completedAt 升序淘汰最旧超限项 + 返回淘汰计数(非插入序)", () => {
537
- const runs = new Map<string, WorkflowRun>();
538
- // 插入序刻意与 completedAt 序无关:先倒序插入 t24→t0,再 delete+set 重排几个
539
- // 中段条目(移到 Map 尾部)模拟一般性「完成序≠插入序」——若实现退化为按 Map
540
- // 迭代首 excess 个淘汰,删的将不是 t0-t4,本用例失败
541
- for (let i = 24; i >= 0; i--) {
542
- runs.set(`wf-t${i}`, makeEvictableRun(`wf-t${i}`, { completedAt: isoAt(i) }));
543
- }
544
- for (const i of [5, 15, 20]) {
545
- const run = runs.get(`wf-t${i}`)!;
546
- runs.delete(`wf-t${i}`);
547
- runs.set(`wf-t${i}`, run);
548
- }
549
-
550
- const evicted = evictDoneRunsBeyondCap(runs, MAX_RETAINED_DONE_RUNS);
551
-
552
- expect(evicted).toBe(5);
553
- expect(runs.size).toBe(MAX_RETAINED_DONE_RUNS);
554
- // 被删的恰是 completedAt 最小的 5 个(t0-t4)
555
- for (let i = 0; i < 5; i++) {
556
- expect(runs.has(`wf-t${i}`)).toBe(false);
557
- }
558
- for (let i = 5; i < 25; i++) {
559
- expect(runs.has(`wf-t${i}`)).toBe(true);
560
- }
561
- });
562
-
563
- it("W3TC3: 反序 fixture——创建最早、完成最晚的 run 不被淘汰(GAP-1 回归锚点)", () => {
564
- // 嵌套 workflow 竞态背景:父 run 创建最早(Map 首元素)、完成最晚(completedAt
565
- // 全局最新)。同 session 累计 21 个 done 时父 run 完成瞬间触发同步裁剪——若按
566
- // Map 插入序淘汰,父 run 被淘汰,runAndWait 轮询窗口内 get 不到 → 误返
567
- // "Run not found"。completedAt 排序结构性消除。
568
- const runs = new Map<string, WorkflowRun>();
569
- // 插入序 = 创建序:wf-parent 最先插入,completedAt=t100 全局最新(先创建后完成)
570
- runs.set("wf-parent", makeEvictableRun("wf-parent", { completedAt: isoAt(100) }));
571
- for (let i = 0; i < 20; i++) {
572
- // child(i+1) 后插入,completedAt=t0..t19(父 run 之前完成)
573
- runs.set(`wf-child${i + 1}`, makeEvictableRun(`wf-child${i + 1}`, { completedAt: isoAt(i) }));
574
- }
575
-
576
- const evicted = evictDoneRunsBeyondCap(runs, MAX_RETAINED_DONE_RUNS);
577
-
578
- expect(evicted).toBe(1);
579
- // 被淘汰的是 child1(completedAt 最旧 t0),非 Map 首元素 wf-parent
580
- expect(runs.has("wf-child1")).toBe(false);
581
- expect(runs.has("wf-parent")).toBe(true);
582
- for (let i = 2; i <= 20; i++) {
583
- expect(runs.has(`wf-child${i}`)).toBe(true);
584
- }
585
- });
586
-
587
- it("W3TC4: completedAt 缺失 fallback 视为最旧(排序键空串字典序最小)", () => {
588
- const runs = new Map<string, WorkflowRun>();
589
- // 插入序 [runC, runA, runB]——缺失者 runA 居中,防「碰巧首元素」假通过
590
- runs.set("wf-runC", makeEvictableRun("wf-runC", { completedAt: isoAt(2) }));
591
- runs.set("wf-runA", makeEvictableRun("wf-runA"));
592
- runs.set("wf-runB", makeEvictableRun("wf-runB", { completedAt: isoAt(1) }));
593
-
594
- const evicted = evictDoneRunsBeyondCap(runs, 2);
595
-
596
- // runA 缺失 completedAt = 空串排序键 → 字典序最小=最旧 → 先被淘汰
597
- expect(evicted).toBe(1);
598
- expect(runs.has("wf-runA")).toBe(false);
599
- expect(runs.has("wf-runB")).toBe(true);
600
- expect(runs.has("wf-runC")).toBe(true);
601
- });
602
-
603
- it("W3TC5: tie 稳定排序——同 completedAt 按 Map 插入序确定性淘汰", () => {
604
- function buildTieFixture(): Map<string, WorkflowRun> {
605
- const runs = new Map<string, WorkflowRun>();
606
- const tie = isoAt(50);
607
- for (const id of ["wf-w1", "wf-w2", "wf-w3", "wf-w4"]) {
608
- runs.set(id, makeEvictableRun(id, { completedAt: tie }));
609
- }
610
- return runs;
611
- }
612
-
613
- const runs = buildTieFixture();
614
- const evicted = evictDoneRunsBeyondCap(runs, 2);
615
-
616
- // tie 组内先插入者视为更旧先被淘汰
617
- expect(evicted).toBe(2);
618
- expect(runs.has("wf-w1")).toBe(false);
619
- expect(runs.has("wf-w2")).toBe(false);
620
- expect(runs.has("wf-w3")).toBe(true);
621
- expect(runs.has("wf-w4")).toBe(true);
622
-
623
- // 确定性:同 fixture 二次运行断言同一淘汰集合
624
- const runs2 = buildTieFixture();
625
- const evicted2 = evictDoneRunsBeyondCap(runs2, 2);
626
- expect(evicted2).toBe(2);
627
- expect(runs2.has("wf-w1")).toBe(false);
628
- expect(runs2.has("wf-w2")).toBe(false);
629
- expect(runs2.has("wf-w3")).toBe(true);
630
- expect(runs2.has("wf-w4")).toBe(true);
631
- });
632
-
633
- it("W3TC6: done 数 <= keepDone 时 no-op 返回 0(恰好 K / 不足 K 两场景)", () => {
634
- // 场景①:恰好 20 个 done(=K)
635
- const exact = new Map<string, WorkflowRun>();
636
- for (let i = 0; i < MAX_RETAINED_DONE_RUNS; i++) {
637
- exact.set(`wf-ex-${i}`, makeEvictableRun(`wf-ex-${i}`, { completedAt: isoAt(i) }));
638
- }
639
- const evictedExact = evictDoneRunsBeyondCap(exact, MAX_RETAINED_DONE_RUNS);
640
- expect(evictedExact).toBe(0);
641
- expect(exact.size).toBe(MAX_RETAINED_DONE_RUNS);
642
- for (let i = 0; i < MAX_RETAINED_DONE_RUNS; i++) {
643
- expect(exact.has(`wf-ex-${i}`)).toBe(true);
644
- }
645
-
646
- // 场景②:5 个 done(<K)+ 混入 running
647
- const under = new Map<string, WorkflowRun>();
648
- for (let i = 0; i < 5; i++) {
649
- under.set(`wf-un-${i}`, makeEvictableRun(`wf-un-${i}`, { completedAt: isoAt(i) }));
650
- }
651
- under.set("wf-un-run", makeEvictableRun("wf-un-run", { status: "running" }));
652
- const evictedUnder = evictDoneRunsBeyondCap(under, MAX_RETAINED_DONE_RUNS);
653
- expect(evictedUnder).toBe(0);
654
- expect(under.size).toBe(6);
655
- for (const id of ["wf-un-run"]) {
656
- expect(under.has(id)).toBe(true);
657
- }
658
- });
659
- });