@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,123 +0,0 @@
1
- // persona-router.test.ts —— persona 三策略路由 + argv 预算前置拦截。
2
- //
3
- // 三视角:①构建者——三通道产出物各归其位;②使用者——argv 超限时报
4
- // prompt_too_large 且文案含三条恢复建议;③观察者——估算口径含多字节字符与分隔符。
5
-
6
- import { describe, expect, it } from "vitest";
7
-
8
- import {
9
- applyPersona,
10
- assertArgvBudget,
11
- DEFAULT_ARGV_BUDGET_BYTES,
12
- estimateArgvBytes,
13
- } from "../../common/persona-router.ts";
14
- import { EngineError } from "../../common/errors.ts";
15
- import type { EngineCapabilities } from "../../types.ts";
16
-
17
- const CAPS_FILE: EngineCapabilities = {
18
- schemaEnforcement: "emulated", steer: "unsupported", conversation: "unsupported",
19
- personaInjection: "file", eventGranularity: "coarse", sandbox: "none",
20
- sessionRead: "partial", resume: "cold", interrupt: "kill-only", permissionMode: "native",
21
- };
22
- const CAPS_FLAG: EngineCapabilities = { ...CAPS_FILE, personaInjection: "flag" };
23
- const CAPS_PROMPT: EngineCapabilities = { ...CAPS_FILE, personaInjection: "prompt" };
24
-
25
- const persona = {
26
- agentRef: "reviewer",
27
- skillPath: "/skills/review.md",
28
- appendSystemPrompt: ["You are a careful code reviewer.", "Be terse."],
29
- };
30
-
31
- describe("applyPersona 三策略路由", () => {
32
- it("file 策略:人设全文进 fileCandidate(路径相对池目录),promptSegment 为空", () => {
33
- const routing = applyPersona(persona, CAPS_FILE);
34
- expect(routing.promptSegment).toBe("");
35
- expect(routing.fileCandidate).toBeDefined();
36
- expect(routing.fileCandidate?.suggestedPath).toBe("persona.md");
37
- expect(routing.fileCandidate?.content).toContain("# Agent: reviewer");
38
- expect(routing.fileCandidate?.content).toContain("/skills/review.md");
39
- expect(routing.fileCandidate?.content).toContain("You are a careful code reviewer.");
40
- });
41
-
42
- it("flag 策略:promptSegment 为纯人设正文(launcher 组 flag 直传),无 fileCandidate", () => {
43
- const routing = applyPersona(persona, CAPS_FLAG);
44
- expect(routing.fileCandidate).toBeUndefined();
45
- expect(routing.promptSegment).toContain("You are a careful code reviewer.");
46
- expect(routing.promptSegment).toContain("Be terse.");
47
- // 纯正文:不带 prompt 通道的结构头
48
- expect(routing.promptSegment).not.toContain("## Persona");
49
- });
50
-
51
- it("prompt 策略:promptSegment 为带结构头的人设段(拼进最终 prompt)", () => {
52
- const routing = applyPersona(persona, CAPS_PROMPT);
53
- expect(routing.promptSegment.startsWith("## Persona")).toBe(true);
54
- expect(routing.promptSegment).toContain("# Agent: reviewer");
55
- expect(routing.promptSegment).toContain("You are a careful code reviewer.");
56
- });
57
-
58
- it("空 persona(全字段缺省):三通道都产出空载体(白占 argv/prompt 无意义)", () => {
59
- expect(applyPersona({}, CAPS_FILE)).toEqual({ promptSegment: "" });
60
- expect(applyPersona({}, CAPS_FLAG)).toEqual({ promptSegment: "" });
61
- expect(applyPersona({}, CAPS_PROMPT)).toEqual({ promptSegment: "" });
62
- });
63
-
64
- it("仅 appendSystemPrompt:file 通道照常落文件(agentRef/skillPath 头部行缺省)", () => {
65
- const routing = applyPersona({ appendSystemPrompt: ["only body"] }, CAPS_FILE);
66
- expect(routing.fileCandidate?.content).toBe("only body");
67
- });
68
- });
69
-
70
- describe("estimateArgvBytes", () => {
71
- it("ASCII:字节数之和 + 每参数 1 个 NUL 分隔符", () => {
72
- // "ab"(2) + "cde"(3) + 2 个 NUL = 7
73
- expect(estimateArgvBytes(["ab", "cde"])).toBe(7);
74
- expect(estimateArgvBytes([])).toBe(0);
75
- });
76
-
77
- it("多字节字符按 UTF-8 计(中文 3 字节/字)——字符数口径会低估", () => {
78
- // "中"=3 字节 + 1 NUL = 4
79
- expect(estimateArgvBytes(["中"])).toBe(4);
80
- // "a中b" = 1+3+1 = 5 字节 + 1 = 6
81
- expect(estimateArgvBytes(["a中b"])).toBe(6);
82
- });
83
- });
84
-
85
- describe("assertArgvBudget", () => {
86
- it(`默认上限 ${DEFAULT_ARGV_BUDGET_BYTES} 字节(128KB)且预算内通过`, () => {
87
- expect(DEFAULT_ARGV_BUDGET_BYTES).toBe(128 * 1024);
88
- expect(() => assertArgvBudget(["--prompt", "short"])).not.toThrow();
89
- });
90
-
91
- it("超限抛 prompt_too_large:detail 含实际/上限字节数", () => {
92
- const bigArg = "x".repeat(1024);
93
- const argv = [bigArg, bigArg]; // 2KB,limit 1KB
94
- let caught: EngineError | undefined;
95
- try {
96
- assertArgvBudget(argv, 1024);
97
- expect.unreachable("should throw");
98
- } catch (err) {
99
- caught = err as EngineError;
100
- }
101
- expect(caught).toBeInstanceOf(EngineError);
102
- expect(caught?.code).toBe("prompt_too_large");
103
- expect(caught?.message).toContain("2050"); // 1024*2 + 2 NUL
104
- expect(caught?.message).toContain("1024");
105
- });
106
-
107
- it("错误恢复指引含三条建议:缩短 task / persona 移 file 通道 / 换 stdin 引擎", () => {
108
- try {
109
- assertArgvBudget(["y".repeat(3000)], 1024);
110
- expect.unreachable("should throw");
111
- } catch (err) {
112
- const e = err as EngineError;
113
- expect(e.recovery).toMatch(/shorten the task/i);
114
- expect(e.recovery).toMatch(/file channel/);
115
- expect(e.recovery).toMatch(/stdin/);
116
- }
117
- });
118
-
119
- it("limit 可配(调用方收紧到引擎实测限额)", () => {
120
- expect(() => assertArgvBudget(["a".repeat(100)], 50)).toThrowError(/prompt_too_large/);
121
- expect(() => assertArgvBudget(["a".repeat(100)], 101)).not.toThrow();
122
- });
123
- });
@@ -1,154 +0,0 @@
1
- // pool-manager.test.ts —— 池 acquire/release 引用计数 / 归零整池删除 / journal 保留
2
- // / 清理失败标记 / spawnedFiles 单次清理(D5 + §3.3.9)。
3
- //
4
- // 三视角:①构建者——计数归零才删、删除边界三硬规则逐条;②使用者——release 幂等
5
- // 安全(无引用 no-op);③观察者——清理失败有 .pool-cleanup-failed 标记(可观测)。
6
-
7
- import { mkdirSync, mkdtempSync, existsSync, readdirSync, rmSync, writeFileSync } from "node:fs";
8
- import { tmpdir } from "node:os";
9
- import { join } from "node:path";
10
-
11
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
12
-
13
- import {
14
- acquirePool,
15
- cleanupSpawnedFiles,
16
- POOL_CLEANUP_FAILED_MARKER,
17
- releasePoolRef,
18
- resetPoolRegistryForTests,
19
- } from "../../common/pool-manager.ts";
20
- import { resolvePoolDir } from "../../paths.ts";
21
-
22
- let tmpRoot: string;
23
-
24
- beforeEach(() => {
25
- tmpRoot = mkdtempSync(join(tmpdir(), "engine-pool-test-"));
26
- resetPoolRegistryForTests();
27
- });
28
-
29
- afterEach(() => {
30
- rmSync(tmpRoot, { recursive: true, force: true });
31
- });
32
-
33
- describe("acquirePool", () => {
34
- it("mkdir -p 返回池目录(路径经 resolvePoolDir 派生),重复 acquire 幂等", async () => {
35
- const dir1 = await acquirePool(tmpRoot, "zcode", "reviewer");
36
- const dir2 = await acquirePool(tmpRoot, "zcode", "reviewer");
37
- expect(dir1).toBe(resolvePoolDir(tmpRoot, "zcode", "reviewer"));
38
- expect(dir1).toBe(dir2);
39
- expect(existsSync(dir1)).toBe(true);
40
- });
41
-
42
- it("poolKey 经 sanitizeSeg 归一(脏字符不进文件系统路径)", async () => {
43
- const dir = await acquirePool(tmpRoot, "zcode", "weird/key..name");
44
- expect(dir).toBe(resolvePoolDir(tmpRoot, "zcode", "weird-key-name"));
45
- });
46
- });
47
-
48
- describe("releasePoolRef 引用计数与整池删除", () => {
49
- it("双引用:release 一次池仍在(原生状态未删),归零才整池删除", async () => {
50
- const poolDir = resolvePoolDir(tmpRoot, "zcode", "reviewer");
51
- await acquirePool(tmpRoot, "zcode", "reviewer");
52
- await acquirePool(tmpRoot, "zcode", "reviewer");
53
- mkdirSync(join(poolDir, "home"), { recursive: true });
54
- writeFileSync(join(poolDir, "home", "config.json"), "{}");
55
-
56
- await releasePoolRef(tmpRoot, "zcode", "reviewer");
57
- expect(existsSync(join(poolDir, "home"))).toBe(true); // 计数 1,不删
58
-
59
- await releasePoolRef(tmpRoot, "zcode", "reviewer"); // 归零
60
- expect(existsSync(join(poolDir, "home"))).toBe(false); // 原生状态已删
61
- });
62
-
63
- it("journal-*.jsonl 不随池删(生命周期跟随 record),目录保留", async () => {
64
- const poolDir = resolvePoolDir(tmpRoot, "zcode", "reviewer");
65
- await acquirePool(tmpRoot, "zcode", "reviewer");
66
- writeFileSync(join(poolDir, "journal-bg-1.jsonl"), "{}\n");
67
- mkdirSync(join(poolDir, "home"), { recursive: true });
68
-
69
- await releasePoolRef(tmpRoot, "zcode", "reviewer");
70
- expect(existsSync(join(poolDir, "journal-bg-1.jsonl"))).toBe(true);
71
- expect(existsSync(join(poolDir, "home"))).toBe(false);
72
- // 只剩 journal:目录本体保留(journal 还在用)
73
- expect(existsSync(poolDir)).toBe(true);
74
- expect(readdirSync(poolDir)).toEqual(["journal-bg-1.jsonl"]);
75
- });
76
-
77
- it("无引用的 release(进程重启后 GC)→ 保守 no-op 不删池", async () => {
78
- const poolDir = resolvePoolDir(tmpRoot, "zcode", "reviewer");
79
- mkdirSync(join(poolDir, "home"), { recursive: true });
80
- await releasePoolRef(tmpRoot, "zcode", "reviewer");
81
- expect(existsSync(join(poolDir, "home"))).toBe(true);
82
- });
83
-
84
- it("池目录不存在时 release 归零 → 无原生状态可清,视为成功不抛", async () => {
85
- await acquirePool(tmpRoot, "zcode", "ghost");
86
- // 归零但目录已被外部删除
87
- rmSync(resolvePoolDir(tmpRoot, "zcode", "ghost"), { recursive: true, force: true });
88
- await expect(releasePoolRef(tmpRoot, "zcode", "ghost")).resolves.toBeUndefined();
89
- });
90
-
91
- it("删除失败置 .pool-cleanup-failed 标记文件(可观测不静默),不 throw", async () => {
92
- const poolDir = resolvePoolDir(tmpRoot, "zcode", "reviewer");
93
- await acquirePool(tmpRoot, "zcode", "reviewer");
94
- mkdirSync(join(poolDir, "home"), { recursive: true });
95
- writeFileSync(join(poolDir, "journal-bg-1.jsonl"), "{}\n");
96
-
97
- // 注入失败 fs:rm 对 home 目录 reject(标记写入仍走真实 fs——失败要可观测)
98
- const realFs = await import("node:fs/promises");
99
- const injected = {
100
- mkdir: (p: string, o: { recursive: boolean }) => realFs.mkdir(p, o),
101
- readdir: (p: string) => realFs.readdir(p, { withFileTypes: true }),
102
- rm: async (p: string, o: { recursive: boolean; force: boolean }) => {
103
- if (p === join(poolDir, "home")) throw new Error("EACCES: permission denied");
104
- return realFs.rm(p, o);
105
- },
106
- rmdir: (p: string) => realFs.rmdir(p),
107
- writeFile: (p: string, d: string) => realFs.writeFile(p, d, "utf8"),
108
- };
109
-
110
- await expect(releasePoolRef(tmpRoot, "zcode", "reviewer", injected)).resolves.toBeUndefined();
111
- const markerPath = join(poolDir, POOL_CLEANUP_FAILED_MARKER);
112
- expect(existsSync(markerPath)).toBe(true);
113
- // 标记内容是失败清单 JSON(含失败条目与原因)
114
- const payload = JSON.parse(
115
- (await import("node:fs")).readFileSync(markerPath, "utf8"),
116
- ) as { failures: string[] };
117
- expect(payload.failures.length).toBe(1);
118
- expect(payload.failures[0]).toContain("home");
119
- expect(payload.failures[0]).toContain("EACCES");
120
- });
121
- });
122
-
123
- describe("cleanupSpawnedFiles(单次性产物)", () => {
124
- it("keepForResume=true → 全部保留(resume 续接原 session,不重写产物)", async () => {
125
- const f = join(tmpRoot, "prompt.txt");
126
- writeFileSync(f, "x");
127
- await cleanupSpawnedFiles([f], { keepForResume: true });
128
- expect(existsSync(f)).toBe(true);
129
- });
130
-
131
- it("keepForResume=false → 删除;目录产物递归删", async () => {
132
- const file = join(tmpRoot, "prompt.txt");
133
- const dir = join(tmpRoot, "persona");
134
- writeFileSync(file, "x");
135
- mkdirSync(dir, { recursive: true });
136
- writeFileSync(join(dir, "persona.md"), "y");
137
- await cleanupSpawnedFiles([file, dir], { keepForResume: false });
138
- expect(existsSync(file)).toBe(false);
139
- expect(existsSync(dir)).toBe(false);
140
- });
141
-
142
- it("不存在的路径幂等(ENOENT 忽略);单条失败不 throw 其余继续", async () => {
143
- const good = join(tmpRoot, "good.txt");
144
- writeFileSync(good, "x");
145
- // 真实 fs 下很难制造 rm 失败——用「父路径为文件」制造 ENOTDIR 失败:
146
- // rm(recursive, force) 对 «file/child» 形态报 ENOTDIR(force 只豁免 ENOENT)
147
- const blocked = join(tmpRoot, "plain-file", "child");
148
- writeFileSync(join(tmpRoot, "plain-file"), "not a dir");
149
- await expect(
150
- cleanupSpawnedFiles([blocked, good], { keepForResume: false }),
151
- ).resolves.toBeUndefined();
152
- expect(existsSync(good)).toBe(false);
153
- });
154
- });
@@ -1,128 +0,0 @@
1
- // schema-emulation.test.ts —— 三级容错提取逐级用例 + ajv 校验 + tail 载体。
2
- //
3
- // 三视角:①构建者——三级容错每级有独立触达用例(直接 parse / fence / 括号扫描);
4
- // ②使用者——ok:false 时 error 简述 + tail 足以构造重试 prompt;③观察者——prompt
5
- // 注入段含 schema 声明与输出约定(emulated 引擎拼进 prompt 后模型可遵循)。
6
-
7
- import { describe, expect, it } from "vitest";
8
-
9
- import {
10
- buildSchemaEmulationSegment,
11
- extractAndValidateStructuredOutput,
12
- SCHEMA_EMULATION_TAIL_CHARS,
13
- } from "../../common/schema-emulation.ts";
14
-
15
- const objectSchema = {
16
- type: "object",
17
- properties: { verdict: { type: "string" }, issues: { type: "array", items: { type: "string" } } },
18
- required: ["verdict"],
19
- } as const;
20
-
21
- describe("buildSchemaEmulationSegment", () => {
22
- it("注入段含 schema JSON 声明 + 输出格式约定(用户可见 prompt 断言)", () => {
23
- const segment = buildSchemaEmulationSegment(objectSchema);
24
- expect(segment).toContain("## Structured Output Requirement");
25
- expect(segment).toContain(JSON.stringify(objectSchema));
26
- expect(segment).toMatch(/```json/);
27
- expect(segment).toMatch(/ONLY the JSON value/);
28
- expect(segment).toMatch(/JSON Schema \(draft-07\)/);
29
- });
30
- });
31
-
32
- describe("extractAndValidateStructuredOutput 三级容错", () => {
33
- it("第 1 级:输出整体即合法 JSON → 直接 parse 通过 + ajv 通过", () => {
34
- const text = JSON.stringify({ verdict: "pass", issues: [] });
35
- const result = extractAndValidateStructuredOutput(text, objectSchema);
36
- expect(result).toEqual({ ok: true, parsed: { verdict: "pass", issues: [] } });
37
- });
38
-
39
- it("第 2 级:markdown code fence 包裹 → 剥 fence 后 parse 通过", () => {
40
- const text = "Here is my answer:\n```json\n{\"verdict\": \"fail\", \"issues\": [\"a\", \"b\"]}\n```\n";
41
- const result = extractAndValidateStructuredOutput(text, objectSchema);
42
- expect(result).toEqual({ ok: true, parsed: { verdict: "fail", issues: ["a", "b"] } });
43
- });
44
-
45
- it("第 2 级:无语言标注的裸 fence 也能剥", () => {
46
- const text = "```\n{\"verdict\": \"pass\"}\n```";
47
- const result = extractAndValidateStructuredOutput(text, objectSchema);
48
- expect(result).toEqual({ ok: true, parsed: { verdict: "pass" } });
49
- });
50
-
51
- it("第 3 级:前后杂文本包裹 → 首尾括号扫描提取", () => {
52
- const text = "Sure! The review result is:\n\n{\"verdict\": \"fail\", \"issues\": [\"x\"]}\n\nHope this helps.";
53
- const result = extractAndValidateStructuredOutput(text, objectSchema);
54
- expect(result).toEqual({ ok: true, parsed: { verdict: "fail", issues: ["x"] } });
55
- });
56
-
57
- it("第 3 级:array 根也支持(首个 '[' 到末个 ']')", () => {
58
- const arraySchema = { type: "array", items: { type: "string" } };
59
- const result = extractAndValidateStructuredOutput("prefix [\"a\",\"b\"] suffix", arraySchema);
60
- expect(result).toEqual({ ok: true, parsed: ["a", "b"] });
61
- });
62
-
63
- it("提取成功但 ajv 校验失败 → ok:false 含 ajv 错误明细与原始尾部", () => {
64
- // verdict 缺失(required)+ issues 类型错
65
- const text = '{"issues": "not-an-array"}';
66
- const result = extractAndValidateStructuredOutput(text, objectSchema);
67
- expect(result.ok).toBe(false);
68
- if (!result.ok) {
69
- expect(result.error).toContain("Schema validation failed");
70
- expect(result.error).toContain("verdict");
71
- expect(result.tail).toBe(text);
72
- }
73
- });
74
-
75
- it("三级提取全失败(无任何 JSON)→ ok:false 且 error 指明三级路径", () => {
76
- const result = extractAndValidateStructuredOutput("no json here at all", objectSchema);
77
- expect(result.ok).toBe(false);
78
- if (!result.ok) {
79
- expect(result.error).toContain("3-stage");
80
- expect(result.error).toContain("code-fence");
81
- expect(result.error).toContain("bracket scan");
82
- }
83
- });
84
-
85
- it("提取成功但 JSON 语法损坏(括号扫描后仍 parse 失败)→ ok:false", () => {
86
- const result = extractAndValidateStructuredOutput("result: {verdict: pass}", objectSchema);
87
- expect(result.ok).toBe(false);
88
- });
89
-
90
- it("ajv 编译失败(非法 schema)→ ok:false 指明 host 侧编译失败", () => {
91
- // type: "foo" 是 ajv 编译期拒绝的非法类型值
92
- const result = extractAndValidateStructuredOutput('{"a":1}', { type: "foo" });
93
- expect(result.ok).toBe(false);
94
- if (!result.ok) {
95
- expect(result.error).toContain("compilation failed");
96
- }
97
- });
98
- });
99
-
100
- describe("tail 载体(错误展示)", () => {
101
- it(`tail 截断到原始输出尾部 ${SCHEMA_EMULATION_TAIL_CHARS} 字`, () => {
102
- const head = "H".repeat(300);
103
- const tailPart = "T".repeat(400);
104
- const text = `${head}${tailPart}`; // 700 字,尾部 500 = 末段(100H + 400T)
105
- const result = extractAndValidateStructuredOutput(text, objectSchema);
106
- expect(result.ok).toBe(false);
107
- if (!result.ok) {
108
- expect(result.tail.length).toBe(SCHEMA_EMULATION_TAIL_CHARS);
109
- expect(result.tail).toBe("H".repeat(100) + "T".repeat(400));
110
- }
111
- });
112
-
113
- it("短输出 tail 为原文(不截断)", () => {
114
- const text = "short broken output";
115
- const result = extractAndValidateStructuredOutput(text, objectSchema);
116
- expect(result.ok).toBe(false);
117
- if (!result.ok) {
118
- expect(result.tail).toBe(text);
119
- }
120
- });
121
- });
122
-
123
- describe("D4 硬分流守护(静态断言)", () => {
124
- it("本模块的 ajv 只在 emulated 路径——native 引擎(pi-env 链路)不 import 本模块(由全仓 grep 守护,见任务报告)", () => {
125
- // 占位用例:硬分流是 import 约束,运行时无对应断言点;保留用例记录守护方式
126
- expect(typeof extractAndValidateStructuredOutput).toBe("function");
127
- });
128
- });
@@ -1,28 +0,0 @@
1
- {
2
- "_meta": {
3
- "engineId": "pi",
4
- "description": "pi 引擎 golden 事件序列(统一 AgentEvent 形态——spawn-event-adapter/session-runner 翻译后的 onEvent 出口序列,即 journal 落盘形态)",
5
- "source": "从 spawn-event-adapter.test.ts / session-runner 事件形状构造的典型流式序列:bash 工具调用(含 pendingTools 配对)→ 双段 text_delta → message_end(完整 usage)→ turn_end。字段形状与 handleSdkEvent 翻译产物逐一锚定(tool_start.toolName/args、tool_end.result/isError、text_delta.delta、message_end.usage 四项 token、turn_end)",
6
- "recordedAt": "2026-08-25",
7
- "usageMapping": "message_end.usage = pi SDK message.usage(input/output/cacheRead/cacheWrite 四项 + cost.total 投影为 cost)"
8
- },
9
- "events": [
10
- { "type": "tool_start", "toolName": "bash", "args": { "command": "ls -la /tmp/probe" } },
11
- {
12
- "type": "tool_end",
13
- "toolName": "bash",
14
- "args": { "command": "ls -la /tmp/probe" },
15
- "result": { "output": "total 0\ndrwxr-xr-x 2 user staff 64 Aug 25 10:00:00 ." },
16
- "isError": false
17
- },
18
- { "type": "thinking_delta", "delta": "目录为空,无需进一步检查。" },
19
- { "type": "text_delta", "delta": "Probe directory is empty. " },
20
- { "type": "text_delta", "delta": "Nothing to clean up." },
21
- {
22
- "type": "message_end",
23
- "usage": { "input": 12599, "output": 17, "cacheRead": 512, "cacheWrite": 0, "cost": 0.0001 }
24
- },
25
- { "type": "turn_end" }
26
- ],
27
- "content": "Probe directory is empty. Nothing to clean up."
28
- }
@@ -1,141 +0,0 @@
1
- // agent-event-invariants.ts —— AgentEvent 产出不变量断言器(conformance C3 的实现体)。
2
- //
3
- // 设计权威源:docs/architecture/subagent-engine-abstraction.md §3.3.7「AgentEvent 产出
4
- // 不变量」五条(全部引擎必须满足)。任何 adapter 的 conformance 套件(golden 回放层 /
5
- // 合成样本)都经本断言器校验——负例守护(A12「套件有牙」)靠注入坏序列证明它转红。
6
- //
7
- // 为什么独立成模块(非内联在测试文件):pi/zcode 两套 golden 回放 + 负例元测试共用
8
- // 同一断言逻辑;断言规则漂移会同步影响所有引擎的 conformance,单点维护。
9
-
10
- import type { AgentEvent, AgentUsage } from "../../../types.ts";
11
-
12
- /** 单条不变量违例。invariant 是规则编号("1"/"2a"...),detail 是定位信息。 */
13
- export interface InvariantFinding {
14
- invariant: string;
15
- detail: string;
16
- }
17
-
18
- /** 断言选项。granularity 决定不变量 3 走流式(byte 级拼接)还是 coarse 口径。 */
19
- export interface InvariantOptions {
20
- granularity: "stream" | "coarse";
21
- /** 流式引擎的终态 content(不变量 3a:text_delta 拼接 === content,byte 级)。 */
22
- content?: string;
23
- }
24
-
25
- /** 五条不变量的纯校验(不 throw,返回违例清单——元测试要拿清单做反证)。 */
26
- export function checkAgentEventInvariants(
27
- events: readonly AgentEvent[],
28
- opts: InvariantOptions,
29
- ): InvariantFinding[] {
30
- const findings: InvariantFinding[] = [];
31
- if (events.length === 0) {
32
- return [{ invariant: "0", detail: "事件序列为空——至少需要 turn_end 终态" }];
33
- }
34
-
35
- // 不变量 1:终态序唯一——最后一个非 error 事件必是 turn_end;message_end(若出现)
36
- // 必在其前(turn_end 之后不允许任何非 error 事件)
37
- const nonError = events.filter((e) => e.type !== "error");
38
- const last = nonError[nonError.length - 1];
39
- if (last === undefined || last.type !== "turn_end") {
40
- findings.push({
41
- invariant: "1",
42
- detail: `最后一个非 error 事件是 ${String(last?.type ?? "(none)")},必须唯一且为 turn_end`,
43
- });
44
- }
45
- const lastTurnEndIdx = findLastIndex(events, (e) => e.type === "turn_end");
46
- if (lastTurnEndIdx >= 0) {
47
- for (let i = lastTurnEndIdx + 1; i < events.length; i++) {
48
- const ev = events[i];
49
- if (ev !== undefined && ev.type !== "error") {
50
- findings.push({ invariant: "1", detail: `turn_end 之后出现非 error 事件 ${ev.type}(idx ${i})` });
51
- }
52
- }
53
- }
54
- const lastMessageEndIdx = findLastIndex(events, (e) => e.type === "message_end");
55
- if (lastMessageEndIdx >= 0 && lastTurnEndIdx >= 0 && lastMessageEndIdx > lastTurnEndIdx) {
56
- findings.push({ invariant: "1", detail: "message_end 出现在 turn_end 之后(必须在其前)" });
57
- }
58
-
59
- // 不变量 2:message_end.usage 出现时为完整 AgentUsage 形状——给不出完整 usage 时
60
- // 显式缺省整个字段,不给残缺对象(NaN/缺键 = 残缺)
61
- events.forEach((ev, idx) => {
62
- if (ev.type !== "message_end") return;
63
- if (ev.usage === undefined) return; // 显式缺省 = 合法
64
- if (!isCompleteUsage(ev.usage)) {
65
- findings.push({ invariant: "2", detail: `message_end(idx ${idx}).usage 残缺(四项 token 必须全为有限数)` });
66
- }
67
- });
68
-
69
- // 不变量 3a(流式):全部 text_delta 拼接 === content(byte 级)
70
- if (opts.granularity === "stream") {
71
- if (opts.content === undefined) {
72
- findings.push({ invariant: "3a", detail: "流式口径必须提供 content 供拼接比对" });
73
- } else {
74
- const joined = events.filter((e) => e.type === "text_delta").map((e) => (e as { delta: string }).delta).join("");
75
- if (Buffer.from(joined, "utf8").toString("hex") !== Buffer.from(opts.content, "utf8").toString("hex")) {
76
- findings.push({ invariant: "3a", detail: "text_delta 拼接与 content 不一致(byte 级比对失败)" });
77
- }
78
- }
79
- } else {
80
- // 不变量 3b(coarse):turn_end 前至少一个 message_end
81
- if (lastTurnEndIdx < 0 || !events.slice(0, lastTurnEndIdx).some((e) => e.type === "message_end")) {
82
- findings.push({ invariant: "3b", detail: "coarse 引擎 turn_end 前必须至少一个 message_end" });
83
- }
84
- }
85
-
86
- // 不变量 4:tool_start/tool_end 按名配对——终态前未配对的 tool_start 必须有配对
87
- // tool_end(isError 可)或后续 error 事件兜底
88
- const openTools: Array<{ toolName: string; idx: number }> = [];
89
- let errorSeen = false;
90
- events.forEach((ev, idx) => {
91
- if (ev.type === "error") {
92
- errorSeen = true;
93
- return;
94
- }
95
- if (ev.type === "tool_start") {
96
- openTools.push({ toolName: ev.toolName, idx });
97
- return;
98
- }
99
- if (ev.type === "tool_end") {
100
- const at = openTools.findIndex((t) => t.toolName === ev.toolName);
101
- if (at >= 0) openTools.splice(at, 1);
102
- return;
103
- }
104
- });
105
- for (const t of openTools) {
106
- if (!errorSeen) {
107
- findings.push({
108
- invariant: "4",
109
- detail: `tool_start(${t.toolName}, idx ${t.idx}) 终态前未配对(无 tool_end 也无 error 兜底)`,
110
- });
111
- }
112
- }
113
-
114
- return findings;
115
- }
116
-
117
- /** 断言形态(conformance 用例直接消费——违例 throw,测试转红)。 */
118
- export function assertAgentEventInvariants(events: readonly AgentEvent[], opts: InvariantOptions): void {
119
- const findings = checkAgentEventInvariants(events, opts);
120
- if (findings.length > 0) {
121
- const lines = findings.map((f) => ` [不变量 ${f.invariant}] ${f.detail}`).join("\n");
122
- throw new Error(`AgentEvent 不变量违例(§3.3.7 五条):\n${lines}`);
123
- }
124
- }
125
-
126
- /** AgentUsage 完整形状判定(四项 token 有限数;cost 可选)。 */
127
- function isCompleteUsage(u: AgentUsage): boolean {
128
- return (
129
- Number.isFinite(u.input) && Number.isFinite(u.output) &&
130
- Number.isFinite(u.cacheRead) && Number.isFinite(u.cacheWrite)
131
- );
132
- }
133
-
134
- /** Array.prototype.findLastIndex 的 ES2022 前兼容(node 18+ 有原生,防御口径手写)。 */
135
- function findLastIndex<T>(arr: readonly T[], pred: (v: T) => boolean): number {
136
- for (let i = arr.length - 1; i >= 0; i--) {
137
- const v = arr[i];
138
- if (v !== undefined && pred(v)) return i;
139
- }
140
- return -1;
141
- }