@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,164 +0,0 @@
1
- /**
2
- * Workflow Extension — Engine Ports + 编排层共享类型
3
- *
4
- * 3 个注入 Port(AgentRunner / RunStore / WorkerHost)——Engine 定义、Infra 实现,
5
- * 是真需要 mock 测试的依赖(子进程/文件系统/线程)。
6
- *
7
- * 编排层共享类型(WorkerHandlers / LifecycleDeps)——打破 lifecycle ↔
8
- * error-recovery 循环依赖:2 个 engine 函数文件各自独立,共用同一组
9
- * 依赖签名(D-12)。
10
- *
11
- * 层归属:Engine。零 infra 依赖(AC-1)。
12
- */
13
- import type { StreamSink, SubagentStream } from "../../execution/stream-sink.ts";
14
- import type { AgentEvent } from "../../shared/agent-event.ts";
15
- import type { WorkerHandle } from "../worker-handle.ts";
16
- import type { RunSpec } from "./run-spec.ts";
17
- import type { AgentCallOpts, AgentResult } from "./types.ts";
18
- import type { WorkflowRun } from "./workflow-run.ts";
19
-
20
- // ── Port 1: AgentRunner ───────────────────────────────────────
21
-
22
- /**
23
- * Agent 子进程执行 port。Infra 实现:SubprocessAgentRunner。
24
- *
25
- * run 执行单次 agent 调用(委托 SubagentService.executeAndAwait),返回结构化结果。
26
- * signal 用于 abort 传播。
27
- *
28
- * onEvent(可选):强类型 AgentEvent 回调,供调用方实时更新 live record 供 TUI 展示进度。
29
- * 不传则不回调(向后兼容;现有调用点不传不受影响)。
30
- *
31
- * D-005: onEvent 签名从 raw Record<string,unknown> 升级为 AgentEvent——委托后不再有
32
- * raw JSONL 中间层(executeAndAwait 直接出 AgentEvent,session-runner handleSdkEvent 出口)。
33
- */
34
- export interface AgentRunner {
35
- run(opts: AgentCallOpts, signal: AbortSignal, onEvent?: (event: AgentEvent) => void, stream?: SubagentStream): Promise<AgentResult>;
36
- }
37
-
38
- // ── Port 2: RunStore ──────────────────────────────────────────
39
-
40
- /**
41
- * WorkflowRun 持久化 port。Infra 实现:JsonlRunStore。
42
- *
43
- * save 在每次状态变更后持久化整个 WorkflowRun(聚合根);
44
- * loadAll 在 session_start 时重水合(D-5:JSONL 不向后兼容旧 session,旧格式返回空)。
45
- * stateFilePath 返回 run 状态文件的绝对路径(供 overlay/GUI 暴露给用户)。
46
- */
47
- export interface RunStore {
48
- save(run: WorkflowRun): Promise<void>;
49
- loadAll(): Promise<WorkflowRun[]>;
50
- /** 返回 run 状态快照文件的绝对路径:<sessionDir>/workflow-state/<runId>.jsonl */
51
- stateFilePath(runId: string): string;
52
- }
53
-
54
- // ── Port 3: WorkerHost ────────────────────────────────────────
55
-
56
- /**
57
- * Worker 线程启动 port。Infra 实现:WorkerHostImpl。
58
- *
59
- * start 创建一个 Worker thread 运行 workflow 脚本,返回 WorkerHandle。
60
- * handlers 绑定 message/error/exit 回调(见 WorkerHandlers)。
61
- */
62
- export interface WorkerHost {
63
- start(
64
- spec: RunSpec,
65
- args: Record<string, unknown>,
66
- handlers: WorkerHandlers,
67
- ): WorkerHandle;
68
- }
69
-
70
- // ── 编排层共享类型 1: WorkerHandlers ───────────────────────────
71
-
72
- /**
73
- * Worker 线程事件回调集合——WorkerHost.start 的入参,由 lifecycle
74
- * 构造并注入。2 个 engine 文件(lifecycle / error-recovery)共用此签名,
75
- * 避免各自定义形状不一致的 handler bag(打破循环依赖)。
76
- *
77
- * 所有回调返回 Promise——允许 engine 层在回调内做 await persistState 等异步操作。
78
- */
79
- export interface WorkerHandlers {
80
- /** Worker → Main 的业务消息(agent-call / return / error / log)。 */
81
- onMessage(raw: unknown): Promise<void>;
82
- /** Worker 线程 uncaught error。 */
83
- onError(err: Error): Promise<void>;
84
- /** Worker 线程 exit(含 code,用于区分正常退出 vs 崩溃)。handle 用于竞态防护 G-025。 */
85
- onExit(code: number, handle: WorkerHandle): Promise<void>;
86
- }
87
-
88
- // ── 编排层共享类型 2: LifecycleDeps ────────────────────────────
89
-
90
- /**
91
- * lifecycle / error-recovery 2 个 engine 函数文件的共同依赖 bag。
92
- *
93
- * 取代旧 4 个 Context factory(errorHandlerContext / agentCallContext /
94
- * budgetCallbacks / 旧 terminate bag,AC-2 目标)。函数签名 `(deps: LifecycleDeps, ...)`
95
- * 让每个 free function 自包含依赖,无需 God Facade 中介。
96
- *
97
- * - store: 持久化(RunStore port)
98
- * - workerHost: 启动 worker(WorkerHost port)
99
- * - runner: 执行 agent(AgentRunner port)
100
- * - runs: 内存中的活动 run 聚合根索引(runId → WorkflowRun),替代旧 6 张并行 map
101
- * - onRunDone?: run 到达 done 终态时的回调(C-4 修复,可选)。由 Interface 层
102
- * factory 注入(notifyDone —— 唤醒 parent agent 消费结果)。Engine 层不依赖
103
- * Pi SDK,通过 callback 把完成信号外推到 Interface 层。所有 transition("done", ...)
104
- * 路径(handleReturn / handleWorkerError / handleScriptError / abortRun /
105
- * dispatchAgentCall budget 终止)调完 transition + save 后触发本回调。
106
- */
107
- export interface LifecycleDeps {
108
- store: RunStore;
109
- workerHost: WorkerHost;
110
- runner: AgentRunner;
111
- runs: Map<string, WorkflowRun>;
112
- /** run 到达 done 终态时的回调(C-4 修复,可选)。Interface 层注入 notifyDone。 */
113
- onRunDone?: (run: WorkflowRun) => void;
114
- /**
115
- * 跨扩展事件总线(pending-notifications register/unregister 信号灯)。
116
- *
117
- * runWorkflow 启动时 emit pending:register;所有 transition("done") 路径 emit
118
- * pending:unregister。两处均通过本端口(Engine 不直接依赖 Pi SDK)。可选——
119
- * 无 pending-notifications 扩展时 no-op(向后兼容)。
120
- */
121
- eventBus?: { emit(channel: string, data: unknown): void };
122
- /**
123
- * 调试日志端口(Engine 不直接依赖 Pi SDK)。Interface 层注入实现。
124
- * 关键路径记录 run 启动、保存、pending 注册/注销,便于排查异步操作状态。
125
- */
126
- log?: (level: "debug" | "info" | "warn" | "error", component: string, message: string, data?: unknown) => void;
127
- /**
128
- * D-12 regression fix (round-2 #2):rebuildRuntime 重新调度 run 级墙钟预算计时器。
129
- *
130
- * worker/script 错误重试走 replaceRuntime,旧 RunRuntime 的 release 会 clearTimeout
131
- * 旧计时器(run-runtime.release)。新 runtime 必须重排 scheduleTimeBudget,否则带
132
- * budgetTimeMs 的 run 命中一次错误重试后时间预算静默失效(直到下次 pause/resume 才重排)。
133
- * 由 Interface 层 factory 注入——闭包捕获 deps,内部调 lifecycle.scheduleTimeBudget。
134
- *
135
- * 可选——旧测试 deps 不注入时 rebuildRuntime 不重排计时器(兼容,不影响无时间预算的 run)。
136
- */
137
- scheduleTimeBudget?: (
138
- runId: string,
139
- budgetTimeMs: number,
140
- ) => ReturnType<typeof setTimeout> | undefined;
141
- /**
142
- * workflow() 嵌套调用回调(可选)。Worker 脚本内调 workflow(name, args) 时触发。
143
- *
144
- * 由 Interface 层 makeDeps 注入(闭包捕获 registry + deps)。Engine 层的
145
- * error-recovery.handleWorkerMessage 收到 workflow-call 消息后调本回调,
146
- * 拿到子 workflow 执行结果后 postMessage(workflow-result) 回 worker。
147
- *
148
- * 不注入时 workflow() 返回 error result(向后兼容,不影响非嵌套场景)。
149
- */
150
- onWorkflowCall?: (
151
- name: string,
152
- args: Record<string, unknown>,
153
- parentRun: WorkflowRun,
154
- ) => Promise<unknown>;
155
- /**
156
- * UI streaming sink(ctx.ui.setWidget),workflow agent call 创建 SubagentStream 用。
157
- *
158
- * 由 Interface 层 makeDeps 注入(从 SubagentService.getStreamSink() 取)。
159
- * dispatchAgentCall 用它创建 SubagentStream(widgetKey=subagent-stream-<runId>-<stepIndex>),
160
- * 使 workflow agent call 的 text_delta 走与 background subagent 相同的 streaming 链路。
161
- * 可选——无 UI 模式(TUI/RPC 无 setWidget)时为 undefined,dispatchAgentCall 不创建 stream。
162
- */
163
- streamSink?: StreamSink;
164
- }
@@ -1,89 +0,0 @@
1
- /**
2
- * Workflow Extension — Run Runtime
3
- *
4
- * 聚合内运行时资源(仅 status==="running" 时存在)。技术资源聚合,
5
- * Engine 层类型,持 WorkerHandle / ConcurrencyGate 具体类(D-12 不造 interface)。
6
- *
7
- * 职责:封装一次 running-segment 的所有技术资源(worker 线程 + 并发信号量 +
8
- * abort controller),统一 release 入口(AC-2:单 release 替代多 boolean flag)。
9
- *
10
- * 一次性生命周期(G3-001):runtime 释放后不再复用——AbortController 一次性
11
- * 语义决定 controller 无法跨释放复用,gate 队列也在 worker 重跑脚本 +
12
- * callCache replay 时清空无影响,所以整个 RunRuntime 重建。唯一注入路径:
13
- * assignRuntime(runWorkflow 创建)与 replaceRuntime(error-recovery 崩溃重试)。
14
- *
15
- * 参考:domain-models.md §10、clarification.md G3-001。
16
- */
17
-
18
- import { ConcurrencyGate } from "../concurrency-gate.ts";
19
- import { WorkerHandle } from "../worker-handle.ts";
20
-
21
- /**
22
- * release mode 枚举——调用方表达意图。
23
- *
24
- * 一次性生命周期后唯一语义:terminal(终局释放,worker + controller 全释放,
25
- * runtime 即被调用方丢弃)。原 "pause" 值已随 pause/resume 生命周期删除(F8)
26
- * ——release 后不存在「保留待恢复」的中间形态。
27
- */
28
- export type ReleaseMode = "terminal";
29
-
30
- // ── RunRuntime ───────────────────────────────────────────────
31
-
32
- export class RunRuntime {
33
- /** Worker 线程句柄。 */
34
- readonly worker: WorkerHandle;
35
- /** 并发信号量。 */
36
- readonly gate: ConcurrencyGate;
37
- /** per-running-segment AbortController(一次性,无法复用——G3-001)。 */
38
- readonly controller: AbortController;
39
- /** Run 级墙钟时间预算计时器(spec.budgetTimeMs > 0 时由 lifecycle 调度,
40
- * 到期 abortRun time_limited)。release 时清理,避免 abort/replaceRuntime
41
- * 后孤儿计时器仍触发(rebuildRuntime 会重排一个全新的计时器,旧的不应残留)。 */
42
- readonly timeBudgetTimer?: ReturnType<typeof setTimeout>;
43
- /** 防止 release 重复执行(幂等)。 */
44
- private released = false;
45
-
46
- constructor(
47
- worker: WorkerHandle,
48
- gate: ConcurrencyGate,
49
- controller: AbortController,
50
- timeBudgetTimer?: ReturnType<typeof setTimeout>,
51
- ) {
52
- this.worker = worker;
53
- this.gate = gate;
54
- this.controller = controller;
55
- this.timeBudgetTimer = timeBudgetTimer;
56
- }
57
-
58
- /**
59
- * 释放所有资源:terminate worker + abort controller。
60
- *
61
- * 幂等——重复调用安全(第二次起 no-op,released flag 守卫)。
62
- * 调用后此 RunRuntime 应被调用方丢弃(WorkflowRun.runtime = undefined),
63
- * 崩溃重试时由 replaceRuntime 注入新实例(G3-001)。
64
- *
65
- * worker.terminate 本身幂等,controller.abort 本身幂等
66
- * (重复 abort 无副作用),但 released flag 让本方法语义更明确:
67
- * 「释放过一次的 runtime 不再释放第二次」。
68
- *
69
- * @param mode terminal —— 终局释放(唯一值,保留参数为调用方语义显式化)
70
- */
71
- release(_mode: ReleaseMode): void {
72
- if (this.released) return;
73
- this.released = true;
74
- // 清理 run 级时间预算计时器——abort/terminate/replaceRuntime 后它不应再触发
75
- // (rebuildRuntime 会重排全新计时器;孤儿触发会把已终态的 run 误转 done)。
76
- if (this.timeBudgetTimer) clearTimeout(this.timeBudgetTimer);
77
- // worker.terminate 异步但幂等——不 await(release 是同步签名,调用方
78
- // 不应被底层线程关闭阻塞;worker 收到 terminate 后自行清理)。
79
- void this.worker.terminate();
80
- // controller.abort 触发 listener(kill agent subprocess、中止在飞调用)。
81
- // 一次性语义——已 aborted 的 controller 重复 abort 无副作用。
82
- this.controller.abort();
83
- }
84
-
85
- /** 是否已 release(测试 + 诊断用)。 */
86
- get isReleased(): boolean {
87
- return this.released;
88
- }
89
- }
@@ -1,83 +0,0 @@
1
- /**
2
- * Workflow Extension — RunSpec 值对象
3
- *
4
- * 单次 workflow run 的不可变规格(domain-models.md §2)。
5
- *
6
- * 设计:
7
- * - 全部字段 readonly——run 一旦创建,规格不可改(状态变化走 RunState)
8
- * - scriptSource 是已 strip `export const meta` 的可执行源(WorkflowScript.toExecutable)
9
- * - budgetTokens/budgetTimeMs 是上限(可选,未设 = 不限制)
10
- *
11
- * 层归属:Engine。
12
- *
13
- * 参考:domain-models.md §2。
14
- */
15
-
16
- import type { Budget } from "./budget.ts";
17
-
18
- /**
19
- * RunSpec——一次 workflow run 的不可变输入规格。
20
- *
21
- * 作为 RunStore 持久化的一部分(WorkflowRun.spec),崩溃恢复重水合后
22
- * 需要 scriptSource/args 重建 worker(G3-001)。
23
- */
24
- export interface RunSpec {
25
- /** 已 strip export 的可执行源(WorkflowScript.toExecutable 产物)。 */
26
- readonly scriptSource: string;
27
- /**
28
- * 参数契约(JSON Schema draft-07,来自 script.meta.parameters 整对象透传,m3 DM2)。
29
- *
30
- * undefined = 不校验(安全退化——漏拷 parameters 退化是「不校验」非「校验错」)。
31
- * 由调用方(actionRun/runAndWait/executeNestedWorkflow)从 script.meta.parameters 拷贝。
32
- * lifecycle.runWorkflow 首行经 validateRunArgs 校验 spec.args(coerceTypes 原地规范化
33
- * args 对象内容,字段引用不变;worker 启动与崩溃重建共用同一对象)。
34
- */
35
- readonly parameters?: Record<string, unknown>;
36
- /** 调用方传入的参数(worker 内通过 $ARGS 访问)。 */
37
- readonly args: Record<string, unknown>;
38
- /**
39
- * Run 级 model override(Option B:经 workerData → worker global $MODEL → agent() fallback)。
40
- *
41
- * undefined = 继承主 agent 模型(零配置默认)。设置时该 run 内所有 agent() 调用默认继承
42
- * (除非 per-call 显式指定 model)。注意:不 merge 进 args(对称单路径注入),
43
- * 而是经 worker-script-builder 注入为 $MODEL worker global。
44
- */
45
- readonly model?: string;
46
- /**
47
- * Run 级 thinkingLevel override(Option B:经 workerData → worker global $THINKING_LEVEL)。
48
- *
49
- * undefined = 继承主 agent thinkingLevel。取值范围由 THINKING_ORDER SSOT 派生(含 max)。
50
- */
51
- readonly thinkingLevel?: string;
52
- /** Token 预算上限(未设或 0 = 不限制,见 Budget 守卫)。 */
53
- readonly budgetTokens?: number;
54
- /** 时间预算上限(ms,wall-clock,由 lifecycle.scheduleTimeBudget 调度)。 */
55
- readonly budgetTimeMs?: number;
56
- /**
57
- * 父 Budget 共享引用(嵌套 workflow() 时由 executeNestedWorkflow 传入)。
58
- *
59
- * 设置时 lifecycle.runWorkflow 直接复用此 Budget 实例,而非 new 一个独立 Budget——
60
- * 子 run 的 consume 直接反映到父 Budget,消除并行嵌套下的超支窗口(F-7 方案 B)。
61
- * 顶层 run 无此字段(budgetTokens 走独立 Budget 构造)。
62
- */
63
- readonly budgetRef?: Budget;
64
- /** 脚本名(meta.name 或文件名 stem)。 */
65
- readonly scriptName: string;
66
- /**
67
- * Run 级简短标签(≤20 字符),区别于 scriptName(脚本身份名)。
68
- * 区分同脚本的不同 run 实例(如 'migrate-users-batch1' vs 'migrate-users-batch2')。
69
- * 旧持久化 run 缺失时为 undefined,渲染时回落 scriptName。
70
- */
71
- readonly slug?: string;
72
- /** 脚本文件绝对路径(用于诊断/日志)。 */
73
- readonly scriptPath: string;
74
- /** 人类可读描述(meta.description)。 */
75
- readonly description?: string;
76
- /**
77
- * 父 workflow 调用链(嵌套 workflow() 时自动填充,循环检测用)。
78
- *
79
- * 顶层 run 无此字段。子 run 的 chain = [...parentChain, parentScriptName]。
80
- * executeNestedWorkflow 检查目标 name 是否已在 chain 中,防止 A→B→A 死循环。
81
- */
82
- readonly parentWorkflowChain?: readonly string[];
83
- }
@@ -1,44 +0,0 @@
1
- /**
2
- * Workflow Extension — RunState 值对象
3
- *
4
- * 单次 workflow run 的可持久化状态(domain-models.md §3)。
5
- *
6
- * 设计:
7
- * - status/reason/budget/calls/trace/errorLogs 是可变字段(运行中持续更新)
8
- * - error/scriptResult 仅终态有值(done 时)
9
- * - 与 RunSpec 的区别:RunSpec 不可变(输入),RunState 可变(执行快照)
10
- *
11
- * 层归属:Engine。
12
- *
13
- * 参考:domain-models.md §3。
14
- */
15
-
16
- import type { AgentCall } from "./agent-call.ts";
17
- import type { Budget } from "./budget.ts";
18
- import type { Trace } from "./trace.ts";
19
- import type { DoneReason, RunStatus, WorkerLogEntry } from "./types.ts";
20
-
21
- /**
22
- * RunState——一次 run 的可持久化执行状态。
23
- *
24
- * 持久化由 RunStore.save(WorkflowRun) 触发(WorkflowRun 持 RunState)。
25
- * 跨进程重启时 RunState 从 JSONL 重水合(callCache 保留,worker 由崩溃恢复重建)。
26
- */
27
- export interface RunState {
28
- /** 当前状态(running/done)。 */
29
- status: RunStatus;
30
- /** 终态原因(done 时必有)。 */
31
- reason?: DoneReason;
32
- /** Token/cost 预算(含 usedTokens/usedCost 累积)。 */
33
- budget: Budget;
34
- /** 按 callId 索引的 agent 调用集合(含 result,跨 runtime 重建存活——callCache replay)。 */
35
- calls: Map<number, AgentCall>;
36
- /** 执行追踪事件流(唯一来源 D-10)。 */
37
- trace: Trace;
38
- /** Worker console.* 捕获条目(run 级诊断,仅展示在 TUI widget)。 */
39
- errorLogs: WorkerLogEntry[];
40
- /** done && reason !== completed 时可有(失败/中止/预算超限的原因)。 */
41
- error?: string;
42
- /** done && reason === completed 时有(脚本 execute 返回值)。 */
43
- scriptResult?: unknown;
44
- }
@@ -1,183 +0,0 @@
1
- /**
2
- * Workflow Extension — Trace 值对象
3
- *
4
- * 执行追踪事件流(D-10 单一来源)。纯 append-only + 单字段 update。
5
- *
6
- * 设计:
7
- * - trace 节点存储 + 变更逻辑收敛为值对象(外部不能直接打洞 nodes 数组)。
8
- * - update 只改单个 node 的 status/result/error/completedAt/sessionId(TracePatch)。
9
- * - callId 不存在时 update no-op(防御性,避免 race 下抛错)。
10
- * - 持久化(appendEntry)与事件通知(emit)不在本值对象内——它们由 engine 函数
11
- * 在调用 update 前后负责(值对象只管数据形状,不管 IO)。
12
- *
13
- * 层归属:Engine。
14
- *
15
- * 参考:domain-models.md §6(字段/不变式)。
16
- */
17
- import type { AgentResult, ExecutionTraceNode, TracePatch } from "./types.ts";
18
-
19
- // ── result.content 裁剪 ────────────────────────────────────────
20
-
21
- /**
22
- * trace 节点 result.content 裁剪上限(严格大于才裁)。
23
- *
24
- * export 供测试边界构造(对齐 budget.ts export 常量先例)。
25
- * 只裁 trace 节点侧——AgentCall.result 不裁(markDone 存全量在前,
26
- * worker cached replay 数据源保真)。
27
- */
28
- export const TRACE_RESULT_MAX_CHARS = 8000;
29
-
30
- /**
31
- * 裁剪保留的头/尾长度(各半)。
32
- *
33
- * 耦合声明:TRIM_HEAD_CHARS + TRIM_TAIL_CHARS === TRACE_RESULT_MAX_CHARS
34
- * (各半相等)是 doc 示例「8001 → 裁后 8000+标记 ≈ 8057」的前提
35
- * (rt-w1-design.json W1C2 / trimTraceResult 注释同款表述)——改 MAX 时
36
- * 需同步检查 head/tail 是否仍各半,及上述注释/文档示例数字。
37
- * 比例钉死在 trace.test.ts 断言中;变更需复查 detail-content.ts
38
- * 尾 5 行消费点(TUI 尾部预览依赖 tail 段)。
39
- */
40
- const TRIM_HEAD_CHARS = 4000;
41
- const TRIM_TAIL_CHARS = 4000;
42
-
43
- /**
44
- * 裁剪 trace result 的 content(Trace 私有纯函数)。
45
- *
46
- * - undefined 透传;未超限原引用透传(零拷贝,不超限路径行为与无裁剪时一致)。
47
- * - 超限返回新对象:head + 含原始长度的标记 + tail(只裁 content,
48
- * result 其他字段浅拷贝保留)。节点持裁剪副本,与传入对象脱钩。
49
- * - 边界附近(如 8001 字符)裁后总长 8000 + 标记长度 > 原始长度属
50
- * 既定语义(head/tail 固定比例下净增长有界),禁止自行缩短 head/tail。
51
- */
52
- function trimTraceResult(result: AgentResult | undefined): AgentResult | undefined {
53
- if (result === undefined) return result;
54
- const { content } = result;
55
- if (content.length <= TRACE_RESULT_MAX_CHARS) return result;
56
- const trimmed =
57
- content.slice(0, TRIM_HEAD_CHARS) +
58
- `\n…[trace result truncated, original ${content.length} chars]…\n` +
59
- content.slice(-TRIM_TAIL_CHARS);
60
- return { ...result, content: trimmed };
61
- }
62
-
63
- /**
64
- * Trace 值对象(事件流,唯一来源 D-10)。
65
- *
66
- * 不变式:
67
- * - nodes 只增不改索引顺序(append-only)
68
- * - update 只改单个 node 的 status/result/error/completedAt/sessionId
69
- * - byIndex 与 nodes 恒一致(每个 append/remove 同步维护,无惰性重建);
70
- * Map 值与数组元素引用共享(非拷贝),nodes 仍是持久化与 TUI 投影 SSOT
71
- * - 不含 verifyStrategy(G-020 删除,不迁移)
72
- */
73
- export class Trace {
74
- private readonly nodes: ExecutionTraceNode[] = [];
75
- /** stepIndex 倒排索引(查询加速 O(1);值与 nodes 元素引用共享)。 */
76
- private readonly byIndex = new Map<number, ExecutionTraceNode>();
77
-
78
- /**
79
- * 从已有节点数组重建 Trace(用于 RunStore 反序列化重水合)。
80
- *
81
- * 防御性拷贝——传入数组不被持有,外部 mutation 不影响 Trace。
82
- * 不验证节点顺序/唯一性(调用方保证快照来源可信)。
83
- * 不做裁剪——落盘快照已是 write 路径裁剪后形态,旧版本未裁剪长
84
- * content 重水合保持原样(read 路径无二次信息损失)。
85
- * 重水合后 call.traceNode(来自快照 calls[].traceNode,
86
- * jsonl-run-store.ts:156 直接传入)与 Trace.nodes 副本非同引用——
87
- * D-10 引用共享仅 live append 路径成立。
88
- */
89
- static fromArray(nodes: readonly ExecutionTraceNode[]): Trace {
90
- const trace = new Trace();
91
- for (const node of nodes) {
92
- const copy = { ...node };
93
- trace.nodes.push(copy);
94
- trace.byIndex.set(copy.stepIndex, copy); // 重复 stepIndex last-wins
95
- }
96
- return trace;
97
- }
98
-
99
- /**
100
- * Append a trace node(append-only,不改已有节点)。
101
- *
102
- * 入口裁剪:超长 result.content 先 mutate 入参节点的 result 字段,
103
- * 再 push 原节点引用(禁止 push 副本——保持 AgentCall.traceNode 与
104
- * Trace.nodes 共享同一引用的 D-10 不变式)。
105
- */
106
- append(node: ExecutionTraceNode): void {
107
- node.result = trimTraceResult(node.result);
108
- this.nodes.push(node);
109
- this.byIndex.set(node.stepIndex, node);
110
- }
111
-
112
- /**
113
- * Update a trace node by stepIndex (callId) with a partial patch.
114
- *
115
- * 只改 patch 中提供的字段(status/result/error/completedAt/sessionId)。
116
- * stepIndex 不存在时 no-op(防御性——agent 完成/失败回调可能晚于 run 终止到达)。
117
- */
118
- update(stepIndex: number, patch: TracePatch): void {
119
- const node = this.findByStepIndex(stepIndex);
120
- if (!node) return; // no-op: 不存在不抛错(D-10 防御性)
121
-
122
- if (patch.status !== undefined) node.status = patch.status;
123
- // 入口裁剪:节点持裁剪副本,与 patch.result 脱钩为两个对象
124
- // (call.result 保留全量——replay 数据源保真)。patch.result 未提供不动。
125
- if (patch.result !== undefined) node.result = trimTraceResult(patch.result);
126
- if (patch.error !== undefined) node.error = patch.error;
127
- if (patch.completedAt !== undefined) node.completedAt = patch.completedAt;
128
- if (patch.sessionId !== undefined) node.sessionId = patch.sessionId;
129
- if (patch.sessionFile !== undefined) node.sessionFile = patch.sessionFile;
130
- }
131
-
132
- /**
133
- * 查找指定 stepIndex 的节点(byIndex O(1),trace 中 stepIndex 应唯一)。
134
- *
135
- * 语义差异声明(旧线性扫 first-match → Map last-wins):仅在破坏
136
- * stepIndex 唯一性的违规使用下可见,两组场景——
137
- * 1. 重复 append 同 stepIndex 且未 remove:返回最后一个节点(last-wins;
138
- * 旧线性扫 first-match 会返回第一个)。
139
- * 2. 重复 append 后 removeByStepIndex:remove 的 findIndex 命中首个旧节点
140
- * splice,而 byIndex.delete 把整个 stepIndex 键删掉——nodes 残留第二个
141
- * 节点成为孤儿(find/update 不可达,length/toArray 仍可见)。
142
- * 合法路径无差异:唯一性由 discard 先 remove 再 append 保证(W1TC12 锚定)。
143
- */
144
- private findByStepIndex(stepIndex: number): ExecutionTraceNode | undefined {
145
- return this.byIndex.get(stepIndex);
146
- }
147
-
148
- /** 按节点引用删除(仅用于测试或 run 重建场景;正常运行不调用)。 */
149
- find(stepIndex: number): ExecutionTraceNode | undefined {
150
- return this.findByStepIndex(stepIndex);
151
- }
152
-
153
- /**
154
- * 按 stepIndex 移除节点(崩溃重建清理在飞 call 用)。
155
- *
156
- * 正常运行不调用(append-only 不变式)。仅 error-recovery 的 discardInFlightCalls
157
- * (rebuildRuntime 内,F2)清理被旧 runtime abort 的在飞 call 时用——移除其 trace
158
- * 节点,让重跑重发 agent-call 时 append 全新节点走全新执行路径(避免 stale
159
- * "running" 节点残留 + trace.update 命中旧节点导致新节点 orphan)。
160
- * stepIndex 不存在时 no-op(防御性)。
161
- */
162
- removeByStepIndex(stepIndex: number): void {
163
- // 先 findIndex 判存在再删,避免 byIndex 与 nodes 漂移
164
- const idx = this.nodes.findIndex((n) => n.stepIndex === stepIndex);
165
- if (idx === -1) return;
166
- this.nodes.splice(idx, 1);
167
- this.byIndex.delete(stepIndex);
168
- }
169
-
170
- /**
171
- * readonly 视图——返回内部 nodes 数组引用(仅类型级 readonly,运行时无
172
- * 防御)。消费方禁止结构化 mutate(push/splice/重排/覆盖元素):byIndex
173
- * 引入后外部结构化 mutate 会使 nodes 与倒排索引 desync。字段级变更走 update()。
174
- */
175
- toArray(): readonly ExecutionTraceNode[] {
176
- return this.nodes;
177
- }
178
-
179
- /** 当前节点数。 */
180
- get length(): number {
181
- return this.nodes.length;
182
- }
183
- }