@zhushanwen/pi-subagent-workflow 8.6.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 (347) hide show
  1. package/package.json +9 -13
  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 +89 -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 +2 -2
  16. package/src/interface/__tests__/tool-workflow-script-generate.test.ts +2 -2
  17. package/src/interface/__tests__/tool-workflow-throw-paths.test.ts +1 -1
  18. package/src/interface/bg-notify-render.ts +4 -4
  19. package/src/interface/commands.ts +3 -3
  20. package/src/interface/format.ts +2 -2
  21. package/src/interface/helpers.ts +1 -1
  22. package/src/interface/list-component.ts +4 -4
  23. package/src/interface/list-shared.ts +2 -2
  24. package/src/interface/list-view.ts +2 -2
  25. package/src/interface/subagent-actions.ts +263 -11
  26. package/src/interface/subagent-tool-schema.ts +20 -13
  27. package/src/interface/subagent-tool.ts +11 -6
  28. package/src/interface/subagents.ts +3 -3
  29. package/src/interface/tool-render.ts +34 -2
  30. package/src/interface/tool-workflow-script.ts +4 -4
  31. package/src/interface/tool-workflow.ts +6 -6
  32. package/src/interface/views/WorkflowsView.ts +5 -5
  33. package/src/interface/views/__tests__/WorkflowsView-signature.test.ts +3 -3
  34. package/src/interface/views/__tests__/detail-content-session-file.test.ts +2 -2
  35. package/src/interface/views/detail-content.ts +4 -4
  36. package/src/interface/views/format.ts +4 -4
  37. package/src/{orchestration/jsonl-run-store.ts → jsonl-run-store.ts} +11 -11
  38. package/src/execution/__tests__/__fixtures__/notifier-golden-snapshots.json +0 -53
  39. package/src/execution/__tests__/__fixtures__/truncline.snapshot.json +0 -1
  40. package/src/execution/__tests__/agent-registry.test.ts +0 -363
  41. package/src/execution/__tests__/agent-result-mapper.test.ts +0 -150
  42. package/src/execution/__tests__/alive-store.test.ts +0 -147
  43. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +0 -490
  44. package/src/execution/__tests__/before-agent-start-injection.test.ts +0 -132
  45. package/src/execution/__tests__/bg-notify-render.test.ts +0 -329
  46. package/src/execution/__tests__/channel-registry-handshake.test.ts +0 -243
  47. package/src/execution/__tests__/chat-engine-routing.test.ts +0 -601
  48. package/src/execution/__tests__/chatmode-first-round-closure-service.test.ts +0 -365
  49. package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +0 -190
  50. package/src/execution/__tests__/chatmode-round-notify-real-chain.test.ts +0 -215
  51. package/src/execution/__tests__/concurrency-pool.test.ts +0 -250
  52. package/src/execution/__tests__/config.test.ts +0 -110
  53. package/src/execution/__tests__/conversation-wiring.test.ts +0 -198
  54. package/src/execution/__tests__/crash-recovery.test.ts +0 -320
  55. package/src/execution/__tests__/delivery-methods.test.ts +0 -422
  56. package/src/execution/__tests__/dialog-queue.test.ts +0 -299
  57. package/src/execution/__tests__/epipe-fallback.test.ts +0 -241
  58. package/src/execution/__tests__/execute-and-await-worktree.test.ts +0 -243
  59. package/src/execution/__tests__/execute-nesting.test.ts +0 -323
  60. package/src/execution/__tests__/execute-options-mapper.test.ts +0 -200
  61. package/src/execution/__tests__/execution-record.test.ts +0 -1394
  62. package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +0 -171
  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 -169
  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 -242
  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 -672
  75. package/src/execution/__tests__/lifecycle-manager-lock.test.ts +0 -211
  76. package/src/execution/__tests__/lifecycle-manager.test.ts +0 -383
  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 -140
  80. package/src/execution/__tests__/manifest-parentid.test.ts +0 -117
  81. package/src/execution/__tests__/model-resolver.test.ts +0 -465
  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 -612
  85. package/src/execution/__tests__/notifier-golden-snapshot.test.ts +0 -261
  86. package/src/execution/__tests__/notify-ledger.test.ts +0 -826
  87. package/src/execution/__tests__/one-shot-upgrade.test.ts +0 -205
  88. package/src/execution/__tests__/output-collector.test.ts +0 -358
  89. package/src/execution/__tests__/parent-child-matrix.test.ts +0 -336
  90. package/src/execution/__tests__/path-encoding.test.ts +0 -104
  91. package/src/execution/__tests__/pi-invocation.test.ts +0 -134
  92. package/src/execution/__tests__/record-store.test.ts +0 -1057
  93. package/src/execution/__tests__/records-cwd-isolation.test.ts +0 -91
  94. package/src/execution/__tests__/recursive-visibility-baseline.test.ts +0 -339
  95. package/src/execution/__tests__/recursive-visibility-env.test.ts +0 -273
  96. package/src/execution/__tests__/relay-agent.test.ts +0 -448
  97. package/src/execution/__tests__/relay-env.test.ts +0 -42
  98. package/src/execution/__tests__/resource-policy.test.ts +0 -109
  99. package/src/execution/__tests__/rpc-mode.test.ts +0 -89
  100. package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +0 -267
  101. package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +0 -253
  102. package/src/execution/__tests__/run-spawn-edges.test.ts +0 -687
  103. package/src/execution/__tests__/run-spawn-integration.test.ts +0 -933
  104. package/src/execution/__tests__/run-spawn-resume.test.ts +0 -322
  105. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +0 -196
  106. package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +0 -199
  107. package/src/execution/__tests__/sdk-contract.test.ts +0 -273
  108. package/src/execution/__tests__/session-context-resolver.test.ts +0 -167
  109. package/src/execution/__tests__/session-file-gc.test.ts +0 -293
  110. package/src/execution/__tests__/session-pending.test.ts +0 -197
  111. package/src/execution/__tests__/session-reconstructor.test.ts +0 -379
  112. package/src/execution/__tests__/session-runner-epipe.test.ts +0 -178
  113. package/src/execution/__tests__/session-runner-schema-env.test.ts +0 -350
  114. package/src/execution/__tests__/session-start-reaper.test.ts +0 -233
  115. package/src/execution/__tests__/spawn-args.test.ts +0 -445
  116. package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +0 -189
  117. package/src/execution/__tests__/spawn-event-adapter.test.ts +0 -167
  118. package/src/execution/__tests__/spawn-worktree-guidance.test.ts +0 -207
  119. package/src/execution/__tests__/spawned-children.test.ts +0 -92
  120. package/src/execution/__tests__/start-sync-model-guard.test.ts +0 -150
  121. package/src/execution/__tests__/startup-config-declaration.test.ts +0 -35
  122. package/src/execution/__tests__/status-refactor.test.ts +0 -345
  123. package/src/execution/__tests__/stdin-writer.test.ts +0 -463
  124. package/src/execution/__tests__/stream-sink-retirement.test.ts +0 -261
  125. package/src/execution/__tests__/subagent-service-abort.test.ts +0 -60
  126. package/src/execution/__tests__/subagent-service-message-close.test.ts +0 -629
  127. package/src/execution/__tests__/subagent-service-parent-guard.test.ts +0 -180
  128. package/src/execution/__tests__/subagent-service.test.ts +0 -788
  129. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +0 -310
  130. package/src/execution/__tests__/subprocess-agent-runner.test.ts +0 -599
  131. package/src/execution/__tests__/temp-prompt.test.ts +0 -53
  132. package/src/execution/__tests__/timeout-integration.test.ts +0 -615
  133. package/src/execution/__tests__/tombstone-store.test.ts +0 -73
  134. package/src/execution/__tests__/tool-action.test.ts +0 -476
  135. package/src/execution/__tests__/truncline-snapshot.test.ts +0 -81
  136. package/src/execution/__tests__/turn-limiter-semantics.test.ts +0 -194
  137. package/src/execution/__tests__/turn-limiter.test.ts +0 -65
  138. package/src/execution/__tests__/ui-channels.test.ts +0 -187
  139. package/src/execution/__tests__/ui-interaction-model.test.ts +0 -67
  140. package/src/execution/__tests__/ui-request-handler-factory.test.ts +0 -370
  141. package/src/execution/__tests__/ui-request-handler.test.ts +0 -204
  142. package/src/execution/__tests__/ui-request-observability.test.ts +0 -114
  143. package/src/execution/__tests__/ui-request-queue.test.ts +0 -133
  144. package/src/execution/__tests__/worktree-manager.test.ts +0 -633
  145. package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +0 -229
  146. package/src/execution/__tests__/worktree-reconcile.integration.test.ts +0 -181
  147. package/src/execution/__tests__/worktree-registry.test.ts +0 -199
  148. package/src/execution/agent-registry.ts +0 -199
  149. package/src/execution/agent-result-mapper.ts +0 -90
  150. package/src/execution/alive-store.ts +0 -92
  151. package/src/execution/argv-mirror.ts +0 -113
  152. package/src/execution/best-effort.ts +0 -38
  153. package/src/execution/channel-registry-access.ts +0 -144
  154. package/src/execution/concurrency-pool.ts +0 -116
  155. package/src/execution/config.ts +0 -96
  156. package/src/execution/dialog-queue.ts +0 -330
  157. package/src/execution/engine/__tests__/common/data-dir.test.ts +0 -53
  158. package/src/execution/engine/__tests__/common/errors.test.ts +0 -132
  159. package/src/execution/engine/__tests__/common/event-journal.test.ts +0 -177
  160. package/src/execution/engine/__tests__/common/kill-chain.test.ts +0 -192
  161. package/src/execution/engine/__tests__/common/nesting-guard.test.ts +0 -81
  162. package/src/execution/engine/__tests__/common/persona-router.test.ts +0 -123
  163. package/src/execution/engine/__tests__/common/pool-manager.test.ts +0 -154
  164. package/src/execution/engine/__tests__/common/schema-emulation.test.ts +0 -128
  165. package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +0 -28
  166. package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +0 -141
  167. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +0 -109
  168. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +0 -101
  169. package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +0 -77
  170. package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +0 -104
  171. package/src/execution/engine/__tests__/conformance/contract.relay.test.ts +0 -342
  172. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +0 -201
  173. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +0 -76
  174. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +0 -79
  175. package/src/execution/engine/__tests__/engine-discovery.test.ts +0 -87
  176. package/src/execution/engine/__tests__/engines-declaration.test.ts +0 -36
  177. package/src/execution/engine/__tests__/model-prompt.test.ts +0 -85
  178. package/src/execution/engine/__tests__/paths.test.ts +0 -39
  179. package/src/execution/engine/__tests__/registry.test.ts +0 -120
  180. package/src/execution/engine/__tests__/routing.test.ts +0 -231
  181. package/src/execution/engine/common/data-dir.ts +0 -62
  182. package/src/execution/engine/common/errors.ts +0 -183
  183. package/src/execution/engine/common/event-journal.ts +0 -254
  184. package/src/execution/engine/common/journal-replay.ts +0 -62
  185. package/src/execution/engine/common/kill-chain.ts +0 -221
  186. package/src/execution/engine/common/nesting-guard.ts +0 -50
  187. package/src/execution/engine/common/persona-router.ts +0 -108
  188. package/src/execution/engine/common/pool-manager.ts +0 -226
  189. package/src/execution/engine/common/schema-emulation.ts +0 -189
  190. package/src/execution/engine/common/session-view-projection.ts +0 -51
  191. package/src/execution/engine/engine-discovery.ts +0 -65
  192. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +0 -469
  193. package/src/execution/engine/engines/pi/__tests__/reader.test.ts +0 -155
  194. package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +0 -164
  195. package/src/execution/engine/engines/pi/pi-engine.ts +0 -415
  196. package/src/execution/engine/engines/pi/reader.ts +0 -48
  197. package/src/execution/engine/engines/pi/registration.ts +0 -35
  198. package/src/execution/engine/engines/pi/task-spec-mapper.ts +0 -100
  199. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +0 -39
  200. package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +0 -150
  201. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +0 -246
  202. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +0 -228
  203. package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +0 -210
  204. package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +0 -64
  205. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +0 -127
  206. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +0 -580
  207. package/src/execution/engine/engines/zcode/constants.ts +0 -43
  208. package/src/execution/engine/engines/zcode/golden-sample.ts +0 -39
  209. package/src/execution/engine/engines/zcode/launcher.ts +0 -161
  210. package/src/execution/engine/engines/zcode/parser.ts +0 -436
  211. package/src/execution/engine/engines/zcode/preparer.ts +0 -363
  212. package/src/execution/engine/engines/zcode/reader.ts +0 -381
  213. package/src/execution/engine/engines/zcode/registration.ts +0 -37
  214. package/src/execution/engine/engines/zcode/zcode-engine.ts +0 -658
  215. package/src/execution/engine/host-task-spec.ts +0 -47
  216. package/src/execution/engine/model-prompt.ts +0 -59
  217. package/src/execution/engine/paths.ts +0 -42
  218. package/src/execution/engine/port.ts +0 -153
  219. package/src/execution/engine/registry.ts +0 -123
  220. package/src/execution/engine/routing.ts +0 -218
  221. package/src/execution/engine/types.ts +0 -309
  222. package/src/execution/execute-options-mapper.ts +0 -112
  223. package/src/execution/execution-record.ts +0 -965
  224. package/src/execution/finalize-record.ts +0 -251
  225. package/src/execution/finalized-marker.ts +0 -51
  226. package/src/execution/get-state-handshake.ts +0 -104
  227. package/src/execution/host-mode.ts +0 -56
  228. package/src/execution/idle-gc.ts +0 -47
  229. package/src/execution/lifecycle-manager.ts +0 -513
  230. package/src/execution/lifecycle-predicates.ts +0 -65
  231. package/src/execution/manifest-store.ts +0 -256
  232. package/src/execution/model-config-service.ts +0 -219
  233. package/src/execution/model-resolver.ts +0 -248
  234. package/src/execution/notifier.ts +0 -330
  235. package/src/execution/notify-ledger.ts +0 -580
  236. package/src/execution/output-collector.ts +0 -228
  237. package/src/execution/path-encoding.ts +0 -60
  238. package/src/execution/pi-invocation.ts +0 -120
  239. package/src/execution/record-entry.ts +0 -132
  240. package/src/execution/record-store.ts +0 -1234
  241. package/src/execution/relay-env.ts +0 -37
  242. package/src/execution/session-context-resolver.ts +0 -64
  243. package/src/execution/session-file-gc.ts +0 -120
  244. package/src/execution/session-pending.ts +0 -164
  245. package/src/execution/session-reconstructor.ts +0 -678
  246. package/src/execution/session-runner.ts +0 -1781
  247. package/src/execution/sessions-index.ts +0 -304
  248. package/src/execution/spawn-event-adapter.ts +0 -363
  249. package/src/execution/stdin-writer.ts +0 -198
  250. package/src/execution/stream-sink.ts +0 -126
  251. package/src/execution/subagent-service.ts +0 -2141
  252. package/src/execution/subprocess-agent-runner.ts +0 -317
  253. package/src/execution/temp-prompt.ts +0 -62
  254. package/src/execution/tombstone-store.ts +0 -72
  255. package/src/execution/turn-limiter.ts +0 -102
  256. package/src/execution/types.ts +0 -973
  257. package/src/execution/ui-channels.ts +0 -216
  258. package/src/execution/ui-interaction-model.ts +0 -48
  259. package/src/execution/ui-request-handler-factory.ts +0 -212
  260. package/src/execution/ui-request-observability.ts +0 -81
  261. package/src/execution/ui-request-queue.ts +0 -184
  262. package/src/execution/worktree-manager.ts +0 -688
  263. package/src/execution/worktree-registry.ts +0 -222
  264. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +0 -349
  265. package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +0 -202
  266. package/src/orchestration/__tests__/agent-call-stream.test.ts +0 -152
  267. package/src/orchestration/__tests__/args-validator.test.ts +0 -143
  268. package/src/orchestration/__tests__/config-loader.test.ts +0 -503
  269. package/src/orchestration/__tests__/error-recovery-handlers.test.ts +0 -809
  270. package/src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts +0 -405
  271. package/src/orchestration/__tests__/error-recovery-serialize-failed-result.test.ts +0 -56
  272. package/src/orchestration/__tests__/error-recovery-workflow-call.test.ts +0 -166
  273. package/src/orchestration/__tests__/execute-agent-call.test.ts +0 -451
  274. package/src/orchestration/__tests__/jsonl-run-store-corrupt-entry.test.ts +0 -150
  275. package/src/orchestration/__tests__/jsonl-run-store-loadall-sources.test.ts +0 -171
  276. package/src/orchestration/__tests__/jsonl-run-store-retention.test.ts +0 -202
  277. package/src/orchestration/__tests__/jsonl-run-store-session-file.test.ts +0 -1030
  278. package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +0 -600
  279. package/src/orchestration/__tests__/lifecycle-runid-injection.test.ts +0 -96
  280. package/src/orchestration/__tests__/lifecycle.test.ts +0 -659
  281. package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +0 -95
  282. package/src/orchestration/__tests__/review-fix-loop-e2e.test.ts +0 -2025
  283. package/src/orchestration/__tests__/script-lint.test.ts +0 -831
  284. package/src/orchestration/__tests__/skill-discovery.test.ts +0 -201
  285. package/src/orchestration/__tests__/test-mocks.ts +0 -197
  286. package/src/orchestration/__tests__/worker-exit-without-result.test.ts +0 -368
  287. package/src/orchestration/__tests__/worker-host.test.ts +0 -120
  288. package/src/orchestration/__tests__/worker-returnmeta-passthrough.test.ts +0 -164
  289. package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +0 -563
  290. package/src/orchestration/__tests__/worker-script-builder.test.ts +0 -309
  291. package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +0 -129
  292. package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +0 -317
  293. package/src/orchestration/__tests__/workflow-script-lint-memo.test.ts +0 -110
  294. package/src/orchestration/__tests__/workflows-e2e.test.ts +0 -537
  295. package/src/orchestration/agent-opts-resolver.ts +0 -174
  296. package/src/orchestration/args-validator.ts +0 -127
  297. package/src/orchestration/config-loader.ts +0 -315
  298. package/src/orchestration/error-recovery.ts +0 -1018
  299. package/src/orchestration/execute-agent-call.ts +0 -256
  300. package/src/orchestration/launcher.ts +0 -455
  301. package/src/orchestration/lifecycle.ts +0 -399
  302. package/src/orchestration/models/__tests__/budget.test.ts +0 -307
  303. package/src/orchestration/models/__tests__/trace.test.ts +0 -408
  304. package/src/orchestration/models/agent-call.ts +0 -83
  305. package/src/orchestration/models/budget.ts +0 -118
  306. package/src/orchestration/models/ports.ts +0 -164
  307. package/src/orchestration/models/run-runtime.ts +0 -104
  308. package/src/orchestration/models/run-spec.ts +0 -83
  309. package/src/orchestration/models/run-state.ts +0 -44
  310. package/src/orchestration/models/trace.ts +0 -183
  311. package/src/orchestration/models/types.ts +0 -301
  312. package/src/orchestration/models/workflow-run.ts +0 -254
  313. package/src/orchestration/models/workflow-script-registry.ts +0 -35
  314. package/src/orchestration/models/workflow-script.ts +0 -117
  315. package/src/orchestration/script-lint.ts +0 -766
  316. package/src/orchestration/skill-discovery.ts +0 -115
  317. package/src/orchestration/worker-handle.ts +0 -115
  318. package/src/orchestration/worker-host.ts +0 -98
  319. package/src/orchestration/worker-script-builder.ts +0 -421
  320. package/src/orchestration/workflow-files.ts +0 -85
  321. package/src/orchestration/workflow-script-registry-impl.ts +0 -133
  322. package/src/shared/__tests__/agent-ref.test.ts +0 -34
  323. package/src/shared/__tests__/meta-parser.test.ts +0 -304
  324. package/src/shared/__tests__/model-ref.test.ts +0 -306
  325. package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +0 -280
  326. package/src/shared/__tests__/resource-discovery.test.ts +0 -736
  327. package/src/shared/__tests__/resource-meta.test.ts +0 -51
  328. package/src/shared/__tests__/schema-jsonify.test.ts +0 -81
  329. package/src/shared/__tests__/timer-delay.test.ts +0 -61
  330. package/src/shared/agent-event.ts +0 -13
  331. package/src/shared/agent-ref.ts +0 -57
  332. package/src/shared/meta-parser.ts +0 -261
  333. package/src/shared/model-ref.ts +0 -286
  334. package/src/shared/resource-discovery.ts +0 -811
  335. package/src/shared/resource-meta.ts +0 -65
  336. package/src/shared/schema-env.ts +0 -44
  337. package/src/shared/schema-jsonify.ts +0 -58
  338. package/src/shared/timer-delay.ts +0 -54
  339. package/src/shared/xml-injection.ts +0 -35
  340. package/workflows/README.md +0 -81
  341. package/workflows/_shared/agent-refs.cjs +0 -40
  342. package/workflows/chain.js +0 -131
  343. package/workflows/map-reduce.js +0 -174
  344. package/workflows/parallel.js +0 -148
  345. package/workflows/review-fix-loop-utils.cjs +0 -1309
  346. package/workflows/review-fix-loop.js +0 -1404
  347. package/workflows/scatter-gather.js +0 -178
@@ -1,451 +0,0 @@
1
- // src/orchestration/__tests__/execute-agent-call.test.ts
2
- //
3
- // U2: executeAgentCall 透传 stream 给 runner.run
4
- // U3: executeAgentCall retry 递归也透传 stream(不丢、不重建)
5
-
6
- import { describe, expect, it, vi } from "vitest";
7
-
8
- import {
9
- DETERMINISTIC_SCHEMA_FAILURE_PREFIX,
10
- executeAgentCall,
11
- isDeterministicSchemaFailureMsg,
12
- isStaleContextErrorMsg,
13
- STALE_CONTEXT_PATTERNS,
14
- } from "../execute-agent-call.ts";
15
- import { AgentCall } from "../models/agent-call.ts";
16
- import { Budget } from "../models/budget.ts";
17
- import type { AgentRunner } from "../models/ports.ts";
18
- import { describeMissingParsedOutput } from "../../execution/output-collector.ts";
19
- import type { ToolCall } from "../../execution/types.ts";
20
- import { Trace } from "../models/trace.ts";
21
- import type { ExecutionTraceNode } from "../models/types.ts";
22
- import type { AgentCallOpts, AgentResult } from "../models/types.ts";
23
-
24
- // ── 测试辅助 ──
25
-
26
- function makeMockResult(overrides: Partial<AgentResult> = {}): AgentResult {
27
- return {
28
- content: "OK",
29
- durationMs: 100,
30
- error: undefined,
31
- toolCalls: [],
32
- ...overrides,
33
- };
34
- }
35
-
36
- function makeBaseOpts(): AgentCallOpts {
37
- return {
38
- prompt: "test task",
39
- agent: "worker",
40
- cwd: "/some/path",
41
- } as AgentCallOpts;
42
- }
43
-
44
- /** 构造一个 traceNode(ExecutionTraceNode 最小子集) */
45
- function makeTraceNode(stepIndex = 0): ExecutionTraceNode {
46
- return {
47
- stepIndex,
48
- agent: "test-agent",
49
- task: "test task",
50
- model: "default",
51
- status: "pending",
52
- };
53
- }
54
-
55
- /** 构造 AgentCall + 关联的 Trace(call.id 与 trace 节点 stepIndex 对齐) */
56
- function makeAgentCallAndTrace(): { call: AgentCall; trace: Trace } {
57
- const trace = new Trace();
58
- const traceNode = makeTraceNode(0);
59
- trace.append(traceNode);
60
- const call = new AgentCall(0, makeBaseOpts(), traceNode);
61
- return { call, trace };
62
- }
63
-
64
- /** 创建 mock AgentRunner(只实现 run) */
65
- function createMockRunner(impl?: ReturnType<typeof vi.fn>): AgentRunner & { run: ReturnType<typeof vi.fn> } {
66
- const run = impl ?? vi.fn().mockResolvedValue(makeMockResult());
67
- return { run } as unknown as AgentRunner & { run: ReturnType<typeof vi.fn> };
68
- }
69
-
70
- // ── U2: executeAgentCall 透传 stream 给 runner.run ──
71
-
72
- describe("U2: executeAgentCall 透传 stream", () => {
73
- it("executeAgentCall 传 stream → runner.run 第 4 参收到同一 stream", async () => {
74
- let capturedStream: unknown;
75
- const runner = createMockRunner(
76
- vi.fn().mockImplementation((_opts, _sig, _onEvt, stream) => {
77
- capturedStream = stream;
78
- return Promise.resolve(makeMockResult());
79
- }),
80
- );
81
-
82
- const fakeStream = { onDelta: vi.fn(), dispose: vi.fn() };
83
- const { call, trace } = makeAgentCallAndTrace();
84
- const budget = new Budget();
85
-
86
- await executeAgentCall(call, runner, budget, new AbortController().signal, trace, undefined, fakeStream as never);
87
-
88
- expect(capturedStream).toBe(fakeStream);
89
- });
90
-
91
- it("executeAgentCall 不传 stream → runner.run 第 4 参为 undefined", async () => {
92
- let capturedStream: unknown = "sentinel";
93
- const runner = createMockRunner(
94
- vi.fn().mockImplementation((_opts, _sig, _onEvt, stream) => {
95
- capturedStream = stream;
96
- return Promise.resolve(makeMockResult());
97
- }),
98
- );
99
-
100
- const { call, trace } = makeAgentCallAndTrace();
101
- const budget = new Budget();
102
-
103
- await executeAgentCall(call, runner, budget, new AbortController().signal, trace);
104
-
105
- expect(capturedStream).toBeUndefined();
106
- });
107
- });
108
-
109
- // ── U1: finalizeCall 透传 sessionFile 到 trace 节点(方案 A)──
110
-
111
- describe("U1: finalizeCall sessionFile → trace 节点", () => {
112
- it("runner.run 返回带 sessionFile 的 result → trace 节点携带 sessionFile", async () => {
113
- const sessionFilePath = "/abs/.pi/agent/subagents/enc/sessions/2026-07-15T_session-abc.jsonl";
114
- const runner = createMockRunner(
115
- vi.fn().mockResolvedValue(
116
- makeMockResult({ sessionId: "session-abc", sessionFile: sessionFilePath }),
117
- ),
118
- );
119
- const { call, trace } = makeAgentCallAndTrace();
120
- const budget = new Budget();
121
-
122
- await executeAgentCall(call, runner, budget, new AbortController().signal, trace);
123
-
124
- const node = trace.find(0);
125
- expect(node).toBeDefined();
126
- expect(node!.sessionFile).toBe(sessionFilePath);
127
- expect(node!.sessionId).toBe("session-abc");
128
- });
129
-
130
- it("runner.run 返回无 sessionFile 的 result → trace 节点 sessionFile undefined", async () => {
131
- const runner = createMockRunner(
132
- vi.fn().mockResolvedValue(makeMockResult({ sessionId: "session-xyz" })),
133
- );
134
- const { call, trace } = makeAgentCallAndTrace();
135
- const budget = new Budget();
136
-
137
- await executeAgentCall(call, runner, budget, new AbortController().signal, trace);
138
-
139
- const node = trace.find(0);
140
- expect(node).toBeDefined();
141
- expect(node!.sessionFile).toBeUndefined();
142
- });
143
- });
144
-
145
- // ── U3: retry 递归也透传 stream ──
146
-
147
- describe("U3: executeAgentCall retry 透传 stream", () => {
148
- it("首次 runner.run 返回 error → retry 时第 4 参仍是同一 stream", async () => {
149
- vi.useFakeTimers();
150
-
151
- const capturedStreams: unknown[] = [];
152
- const runner = createMockRunner(
153
- vi.fn().mockImplementation((_opts, _sig, _onEvt, stream) => {
154
- capturedStreams.push(stream);
155
- // 首次 error,第二次成功
156
- if (capturedStreams.length === 1) {
157
- return Promise.resolve(makeMockResult({ error: "transient error" }));
158
- }
159
- return Promise.resolve(makeMockResult());
160
- }),
161
- );
162
-
163
- const fakeStream = { onDelta: vi.fn(), dispose: vi.fn() };
164
- const { call, trace } = makeAgentCallAndTrace();
165
- const budget = new Budget();
166
-
167
- const promise = executeAgentCall(call, runner, budget, new AbortController().signal, trace, undefined, fakeStream as never);
168
- // 推进 retry 退避定时器(BACKOFF_BASE_MS = 1000,首退避 1s)
169
- await vi.advanceTimersByTimeAsync(2000);
170
- await promise;
171
-
172
- expect(runner.run).toHaveBeenCalledTimes(2);
173
- // 两次调用的第 4 参都是同一 stream 对象
174
- expect(capturedStreams[0]).toBe(fakeStream);
175
- expect(capturedStreams[1]).toBe(fakeStream);
176
-
177
- vi.useRealTimers();
178
- });
179
- });
180
-
181
- // ── isOrphaned 守卫(OB2:S7 残留瞬时污染根除) ──
182
- //
183
- // 谓词为 true 时 finalizeCall 跳过 trace.update,但 markDone 与
184
- // sessionId/sessionFile 同步保留。U4 锁定不传谓词时的现状回归。
185
-
186
- describe("isOrphaned 守卫", () => {
187
- it("U1: 谓词 () => true + 终态成功路径 → trace.update 0 次,markDone 保留(status done + result 已设置)", async () => {
188
- const { call, trace } = makeAgentCallAndTrace();
189
- const updateSpy = vi.spyOn(trace, "update");
190
- const runner = createMockRunner(); // 默认成功 result
191
- const budget = new Budget();
192
-
193
- await executeAgentCall(call, runner, budget, new AbortController().signal, trace, undefined, undefined, () => true);
194
-
195
- expect(updateSpy).not.toHaveBeenCalled();
196
- expect(call.status).toBe("done");
197
- expect(call.result).toBeDefined();
198
- expect(call.result?.content).toBe("OK");
199
- });
200
-
201
- it("U2: 谓词 true + stale-context 失败路径 → trace.update 0 次,markDone 保留(覆盖 stale finalize 调用点)", async () => {
202
- const { call, trace } = makeAgentCallAndTrace();
203
- const updateSpy = vi.spyOn(trace, "update");
204
- const runner = createMockRunner(
205
- vi.fn().mockResolvedValue(makeMockResult({ error: "context canceled" })),
206
- );
207
- const budget = new Budget();
208
-
209
- await executeAgentCall(call, runner, budget, new AbortController().signal, trace, undefined, undefined, () => true);
210
-
211
- expect(updateSpy).not.toHaveBeenCalled();
212
- expect(call.status).toBe("done");
213
- expect(call.result?.error).toBe("context canceled");
214
- });
215
-
216
- it("U3: 谓词 true + 信号 abort 路径 → trace.update 0 次,markDone 保留(覆盖 abort finalize 调用点)", async () => {
217
- const { call, trace } = makeAgentCallAndTrace();
218
- const updateSpy = vi.spyOn(trace, "update");
219
- // 错误文案不含 stale 模式词,确保走 signal.aborted 分支而非 stale 分支
220
- const runner = createMockRunner(
221
- vi.fn().mockResolvedValue(makeMockResult({ error: "old generation failure" })),
222
- );
223
- const controller = new AbortController();
224
- controller.abort();
225
- const budget = new Budget();
226
-
227
- await executeAgentCall(call, runner, budget, controller.signal, trace, undefined, undefined, () => true);
228
-
229
- expect(updateSpy).not.toHaveBeenCalled();
230
- expect(call.status).toBe("done");
231
- expect(call.result?.error).toBe("old generation failure");
232
- });
233
-
234
- it("U4: 谓词 undefined(不传)→ trace.update 恰被调用 1 次(现状回归锁定)", async () => {
235
- const { call, trace } = makeAgentCallAndTrace();
236
- const updateSpy = vi.spyOn(trace, "update");
237
- const runner = createMockRunner();
238
- const budget = new Budget();
239
-
240
- await executeAgentCall(call, runner, budget, new AbortController().signal, trace);
241
-
242
- expect(updateSpy).toHaveBeenCalledTimes(1);
243
- expect(trace.find(0)?.status).toBe("completed");
244
- expect(call.status).toBe("done");
245
- });
246
-
247
- it("U5: 递归重试透传——可重试失败后成功,谓词 true → 重试后终态 trace.update 仍 0 次", async () => {
248
- vi.useFakeTimers();
249
- try {
250
- const { call, trace } = makeAgentCallAndTrace();
251
- const updateSpy = vi.spyOn(trace, "update");
252
- const runner = createMockRunner(
253
- vi.fn()
254
- .mockResolvedValueOnce(makeMockResult({ error: "transient error" }))
255
- .mockResolvedValueOnce(makeMockResult()),
256
- );
257
- const budget = new Budget();
258
-
259
- const promise = executeAgentCall(call, runner, budget, new AbortController().signal, trace, undefined, undefined, () => true);
260
- // 推进首退避 1s(BACKOFF_BASE_MS = 1000)
261
- await vi.advanceTimersByTimeAsync(2000);
262
- await promise;
263
-
264
- expect(runner.run).toHaveBeenCalledTimes(2);
265
- expect(call.attempts).toBe(2);
266
- // 谓词穿透递归层:重试后终态也不写 trace
267
- expect(updateSpy).not.toHaveBeenCalled();
268
- expect(call.status).toBe("done");
269
- expect(call.result?.error).toBeUndefined();
270
- } finally {
271
- vi.useRealTimers();
272
- }
273
- });
274
- });
275
-
276
- // ── W4b: STALE_CONTEXT_PATTERNS 对齐 pi 真实文案(stale 分诊) ──
277
- //
278
- // pi 0.84.x 真实 stale 文案(extensions/runner.ts:531,dist runner.js:567):
279
- // "This extension ctx is stale after session replacement or reload. Do not use
280
- // a captured pi or command ctx after ctx.newSession(), ..."
281
- // 旧 patterns("stale context"/"stalecontext")与该文案零匹配(词序相反),
282
- // stale 错误曾退化为普通错误照常重试 3 次——W4b 词序修正 + 对齐 scheduler
283
- // 已验证 marker 'stale after session replacement'(runtime.ts STALE_CTX_MARKER)。
284
-
285
- /** pi 真实 stale 文案前半(含 marker 全文前缀,锚定真实串而非自造缩写)。 */
286
- const PI_REAL_STALE_MESSAGE =
287
- "This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload().";
288
-
289
- describe("W4b: stale 分诊对齐 pi 真实文案", () => {
290
- it("真实文案全文 → isStaleContextErrorMsg true('ctx is stale' 词序 + scheduler marker 双命中)", () => {
291
- expect(isStaleContextErrorMsg(PI_REAL_STALE_MESSAGE)).toBe(true);
292
- });
293
-
294
- it("patterns 含 scheduler 已验证 marker 'stale after session replacement'", () => {
295
- expect(STALE_CONTEXT_PATTERNS).toContain("stale after session replacement");
296
- expect(STALE_CONTEXT_PATTERNS).toContain("ctx is stale");
297
- });
298
-
299
- it("真实文案 → executeAgentCall 不重试(runner.run 恰 1 次)+ markDone failed", async () => {
300
- const { call, trace } = makeAgentCallAndTrace();
301
- const runner = createMockRunner(
302
- vi.fn().mockResolvedValue(makeMockResult({ error: PI_REAL_STALE_MESSAGE })),
303
- );
304
- const budget = new Budget();
305
-
306
- await executeAgentCall(call, runner, budget, new AbortController().signal, trace);
307
-
308
- expect(runner.run).toHaveBeenCalledTimes(1);
309
- expect(call.status).toBe("done");
310
- expect(call.result?.error).toBe(PI_REAL_STALE_MESSAGE);
311
- expect(trace.find(0)?.status).toBe("failed");
312
- });
313
-
314
- it("普通 transient 错误 → 不命中 stale(照常进入重试路径,现状回归)", () => {
315
- expect(isStaleContextErrorMsg("transient network error")).toBe(false);
316
- expect(isStaleContextErrorMsg(undefined)).toBe(false);
317
- });
318
- });
319
-
320
- // ── MF-1: 确定性 schema 失败不重试 ──
321
- //
322
- // 回归背景(第五轮实测):gate 终止子进程后 collectResult F-1 置归因 error →
323
- // executeAgentCall 判非 stale 走可重试分支 → 不可满足 schema 下循环至
324
- // MAX_ATTEMPTS=3(实测 attempts=3、4 子进程、235s vs 修复前 67.3s)。
325
- // 修复:归因 error 带机器标记(SSOT = DETERMINISTIC_SCHEMA_FAILURE_PREFIX),
326
- // 分诊短路。用真实链路产物(describeMissingParsedOutput)作 error 输入,锁定
327
- // collectResult → executeAgentCall 全链路分诊行为。
328
- //
329
- // 三态可重试性矩阵(完整锁定在 output-collector.test 的 MF-1 describe):
330
- // 态① 从未调用 SO → 不可重试;态② isError(gate 终止/不可满足 schema)→ 不可重试;
331
- // 态③ 调用过但无 details → 可重试(保留既有重试语义)。
332
-
333
- /** 构造态②真实产物(isError SO 调用,schema 校验失败——gate 终止回归场景)。 */
334
- function state2Attribution(): string {
335
- const soCalls: ToolCall[] = [
336
- {
337
- toolName: "structured-output",
338
- isError: true,
339
- result: { details: {}, content: [{ type: "text", text: "Schema validation failed: /target is required" }] },
340
- },
341
- ];
342
- const msg = describeMissingParsedOutput(soCalls);
343
- expect(msg).toBeDefined();
344
- return msg!;
345
- }
346
-
347
- describe("MF-1: 确定性 schema 失败不重试", () => {
348
- it("态②真实产物(gate 终止/schema 校验失败归因)→ runner.run 恰 1 次 + 终态 failed", async () => {
349
- const attribution = state2Attribution();
350
- expect(isDeterministicSchemaFailureMsg(attribution)).toBe(true);
351
-
352
- const { call, trace } = makeAgentCallAndTrace();
353
- const runner = createMockRunner(
354
- vi.fn().mockResolvedValue(makeMockResult({ error: attribution })),
355
- );
356
- const budget = new Budget();
357
-
358
- await executeAgentCall(call, runner, budget, new AbortController().signal, trace);
359
-
360
- // 修复前:循环至 MAX_ATTEMPTS=3(4 次子进程);修复后:恰 1 次
361
- expect(runner.run).toHaveBeenCalledTimes(1);
362
- expect(call.attempts).toBe(1);
363
- expect(call.status).toBe("done");
364
- expect(trace.find(0)?.status).toBe("failed");
365
- });
366
-
367
- it("态①真实产物(never called,缺 extension 环境确定性)→ 同样不重试", async () => {
368
- const attribution = describeMissingParsedOutput([])!;
369
- const { call, trace } = makeAgentCallAndTrace();
370
- const runner = createMockRunner(
371
- vi.fn().mockResolvedValue(makeMockResult({ error: attribution })),
372
- );
373
- const budget = new Budget();
374
-
375
- await executeAgentCall(call, runner, budget, new AbortController().signal, trace);
376
-
377
- expect(runner.run).toHaveBeenCalledTimes(1);
378
- expect(call.attempts).toBe(1);
379
- expect(trace.find(0)?.status).toBe("failed");
380
- });
381
-
382
- it("MF-2 计数不再低估:retry 不发生 → usage consume 恰一次、totalCallCount=1", async () => {
383
- const attribution = state2Attribution();
384
- const { call, trace } = makeAgentCallAndTrace();
385
- const runner = createMockRunner(
386
- vi.fn().mockResolvedValue(
387
- makeMockResult({ error: attribution, usage: { input: 100, output: 50, cost: 0.01 } }),
388
- ),
389
- );
390
- const budget = new Budget();
391
-
392
- await executeAgentCall(call, runner, budget, new AbortController().signal, trace);
393
-
394
- // 修复前:3 attempts → consume×3(usedTokens×3);修复后:恰一次加权消耗
395
- // (input×1 + output×2 = 100 + 100 = 200,权重见 budget.ts)
396
- expect(budget.usedTokens).toBe(200);
397
- expect(budget.usedCost).toBeCloseTo(0.01);
398
- expect(budget.totalCallCount).toBe(1);
399
- });
400
-
401
- it("MF-3 归因不再混合:终态 error 保持归因原文(不被重试轮次覆盖)", async () => {
402
- const attribution = state2Attribution();
403
- const { call, trace } = makeAgentCallAndTrace();
404
- const runner = createMockRunner(
405
- vi.fn().mockResolvedValue(makeMockResult({ error: attribution })),
406
- );
407
- const budget = new Budget();
408
-
409
- await executeAgentCall(call, runner, budget, new AbortController().signal, trace);
410
-
411
- expect(call.result?.error).toBe(attribution);
412
- });
413
-
414
- it("态③(no details,无标记)→ 照常重试(可重试语义保留)", async () => {
415
- vi.useFakeTimers();
416
- try {
417
- // 态③真实文案(不带确定性标记)——矩阵执行面锁定:无标记 = 可重试
418
- const msg = describeMissingParsedOutput([
419
- { toolName: "structured-output", result: { content: [] } },
420
- ])!;
421
- expect(isDeterministicSchemaFailureMsg(msg)).toBe(false);
422
-
423
- const { call, trace } = makeAgentCallAndTrace();
424
- const runner = createMockRunner(
425
- vi.fn()
426
- .mockResolvedValueOnce(makeMockResult({ error: msg }))
427
- .mockResolvedValueOnce(makeMockResult()),
428
- );
429
- const budget = new Budget();
430
-
431
- const promise = executeAgentCall(call, runner, budget, new AbortController().signal, trace);
432
- await vi.advanceTimersByTimeAsync(2000);
433
- await promise;
434
-
435
- expect(runner.run).toHaveBeenCalledTimes(2);
436
- expect(call.status).toBe("done");
437
- } finally {
438
- vi.useRealTimers();
439
- }
440
- });
441
-
442
- it("分诊交叉锁定:标记词不命中任何 STALE_CONTEXT_PATTERNS(stale 分诊在前也不误吞)", () => {
443
- const lower = DETERMINISTIC_SCHEMA_FAILURE_PREFIX.toLowerCase();
444
- for (const pattern of STALE_CONTEXT_PATTERNS) {
445
- expect(lower.includes(pattern)).toBe(false);
446
- }
447
- // 两个分诊只命中确定性分支,互不污染
448
- expect(isStaleContextErrorMsg(DETERMINISTIC_SCHEMA_FAILURE_PREFIX)).toBe(false);
449
- expect(isDeterministicSchemaFailureMsg(DETERMINISTIC_SCHEMA_FAILURE_PREFIX)).toBe(true);
450
- });
451
- });
@@ -1,150 +0,0 @@
1
- // src/orchestration/__tests__/jsonl-run-store-corrupt-entry.test.ts
2
- //
3
- // [SO-DATA-2] collectRecordRun 的 per-entry 隔离:1 条残缺 workflow-record entry
4
- // 不得让整个 loadAll 返回空。
5
- //
6
- // 防的 bug:deserializeRun 在 v guard 之后直接读 snapshot.state.budget 等嵌套字段,
7
- // 残缺 entry(截断/手改/跨版本半写)抛 TypeError 会沿 collectEntrySources 穿透
8
- // loadAll 的 catch → 返回空——单条损坏让全部 run 不可见(读序优先 entry,state
9
- // 文件兜底也不再走)。修复:collectRecordRun 单条 try/catch,损坏 entry 跳过 +
10
- // logger.warn 留证(含 entry 索引与原因),其余 entry 正常重建。
11
- //
12
- // 好坏对照:2 条好 entry 经真实 save 通路产出(快照形态可信,与
13
- // jsonl-run-store-loadall-sources.test.ts 同一搭建方式),1 条坏 entry 手工构造
14
- //(模拟损坏正是本用例的目的——绕开 schema 契约即 corruption 的本质)。
15
-
16
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
17
-
18
- const { loggerMock } = vi.hoisted(() => ({
19
- loggerMock: {
20
- debug: vi.fn(),
21
- info: vi.fn(),
22
- warn: vi.fn(),
23
- error: vi.fn(),
24
- },
25
- }));
26
- vi.mock("@zhushanwen/pi-extension-logger", () => ({ getLogger: () => loggerMock }));
27
-
28
- import * as fs from "node:fs";
29
- import * as os from "node:os";
30
- import * as path from "node:path";
31
-
32
- import type { CustomEntry } from "@earendil-works/pi-coding-agent";
33
-
34
- import { Budget } from "../models/budget.ts";
35
- import { Trace } from "../models/trace.ts";
36
- import type { RunSpec } from "../models/run-spec.ts";
37
- import type { ExecutionTraceNode } from "../models/types.ts";
38
- import { WorkflowRun } from "../models/workflow-run.ts";
39
- import { JsonlRunStore, SNAPSHOT_VERSION, WORKFLOW_RECORD_CUSTOM_TYPE } from "../jsonl-run-store.ts";
40
- import { mkCtx, mkPi } from "./test-mocks.ts";
41
-
42
- function makeSpec(): RunSpec {
43
- return {
44
- scriptSource: "module.exports = async () => {};",
45
- args: {},
46
- scriptName: "test-script",
47
- scriptPath: "/tmp/test.js",
48
- description: "test",
49
- };
50
- }
51
-
52
- function makeTraceNode(stepIndex: number): ExecutionTraceNode {
53
- return { stepIndex, agent: "worker", task: "do thing", model: "default", status: "pending" };
54
- }
55
-
56
- function makeRunningRun(runId: string): WorkflowRun {
57
- const trace = new Trace();
58
- trace.append(makeTraceNode(0));
59
- return WorkflowRun.reconstruct(runId, makeSpec(), {
60
- status: "running",
61
- budget: new Budget(),
62
- calls: new Map(),
63
- trace,
64
- errorLogs: [],
65
- }, { startedAt: new Date().toISOString() });
66
- }
67
-
68
- /** running → done 的完整生命周期 save(终态快照可被 deserializeRun 重建)。 */
69
- async function saveDoneRun(
70
- sessionDir: string,
71
- entries: CustomEntry[],
72
- runId: string,
73
- ): Promise<void> {
74
- const store = new JsonlRunStore({ sessionDir, pi: mkPi(entries) });
75
- const run = makeRunningRun(runId);
76
- await store.save(run);
77
- run.transition("done", "completed");
78
- await store.save(run);
79
- }
80
-
81
- /** 手工构造残缺 record entry:v1 guard 通过,但 snapshot.state 缺全部必读嵌套字段
82
- * → deserializeRun 读 snapshot.state.budget.maxTokens 抛 TypeError。 */
83
- function corruptRecordEntry(runId: string): CustomEntry {
84
- return {
85
- type: "custom",
86
- customType: WORKFLOW_RECORD_CUSTOM_TYPE,
87
- data: {
88
- v: 1,
89
- snapshot: { v: SNAPSHOT_VERSION, runId, state: {} },
90
- updatedAt: new Date().toISOString(),
91
- },
92
- id: `seed-corrupt-${runId}`,
93
- parentId: null,
94
- timestamp: new Date().toISOString(),
95
- };
96
- }
97
-
98
- describe("SO-DATA-2: 残缺 record entry 的 per-entry 隔离", () => {
99
- let tmpDir: string;
100
-
101
- beforeEach(() => {
102
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "wf-corrupt-entry-"));
103
- loggerMock.warn.mockClear();
104
- });
105
-
106
- afterEach(() => {
107
- fs.rmSync(tmpDir, { recursive: true, force: true });
108
- });
109
-
110
- it("3 条 entry(2 好 1 坏)→ 返回 2 条 + warn 留证(含 entry 索引与原因)", async () => {
111
- const entries: CustomEntry[] = [];
112
- await saveDoneRun(tmpDir, entries, "run-a");
113
- await saveDoneRun(tmpDir, entries, "run-b");
114
- const corrupt = corruptRecordEntry("run-corrupt");
115
- const seedEntries: CustomEntry[] = [...entries, corrupt];
116
-
117
- const store = new JsonlRunStore({ sessionDir: tmpDir, ctx: mkCtx(seedEntries) });
118
- const loaded = await store.loadAll();
119
-
120
- // 损坏 entry 只跳过自身,其余 run 全部可见
121
- expect(loaded.map((r) => r.runId).sort()).toEqual(["run-a", "run-b"]);
122
- // warn 留证:entry 索引 + 损坏原因
123
- expect(loggerMock.warn).toHaveBeenCalledTimes(1);
124
- const warnMsg = String(loggerMock.warn.mock.calls[0]?.[0] ?? "");
125
- expect(warnMsg).toContain(`entry #${seedEntries.indexOf(corrupt)}`);
126
- expect(warnMsg).toContain("corrupted");
127
- });
128
-
129
- it("全部 entry 均损坏 → 返回空(不再抛 TypeError 穿透)+ 每条各留一条 warn", async () => {
130
- const seedEntries: CustomEntry[] = [
131
- corruptRecordEntry("run-corrupt-1"),
132
- corruptRecordEntry("run-corrupt-2"),
133
- ];
134
- const store = new JsonlRunStore({ sessionDir: tmpDir, ctx: mkCtx(seedEntries) });
135
- const loaded = await store.loadAll();
136
- expect(loaded).toEqual([]);
137
- expect(loggerMock.warn).toHaveBeenCalledTimes(2);
138
- });
139
-
140
- it("损坏 entry 位于同 runId 好 entry 之前 → 后写覆盖语义不受影响(好快照胜出)", async () => {
141
- const corrupt = corruptRecordEntry("run-x");
142
- const entries: CustomEntry[] = [corrupt];
143
- await saveDoneRun(tmpDir, entries, "run-x");
144
-
145
- const store = new JsonlRunStore({ sessionDir: tmpDir, ctx: mkCtx(entries) });
146
- const loaded = await store.loadAll();
147
- expect(loaded.map((r) => r.runId)).toEqual(["run-x"]);
148
- expect(loaded[0]?.state.status).toBe("done");
149
- });
150
- });