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