@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,229 +0,0 @@
1
- // src/execution/__tests__/worktree-pid-registration.integration.test.ts
2
- //
3
- // [worktree-reaper-fix] 端到端集成测试:验证 worktree pid 注册链路(接线层)。
4
- //
5
- // 背景:2026-08-11 生产事故——reaper 误清活 worktree。根因:pid 补全代码唯一生产调用点
6
- // 挂在 session-runner 的 header 分支(RPC mode 永不触发),注册表 pid 恒为 0,超
7
- // SPAWN_GRACE_MS(60s) 后任意 session_start 触发的 scan() 必然误删活 worktree。
8
- // 修复:spawn() 返回后同步补 pid。
9
- //
10
- // 为什么用真实 spawn(而非现有 run-spawn-* 的 FakeChild mock):
11
- // 现有测试全 mock registerPid(session-start-reaper/crash-recovery/index-session-start/
12
- // stream-sink-guard),验证的是「mock 了补全回调后的 reaper 行为」,从未验证
13
- // 「真实调用链中补全回调是否被调用」——接线错误零检测能力(结构性盲区)。
14
- // 本测试走真实链路:真实 git repo + 真实 worktree 创建 + 真实 spawn node 子进程 +
15
- // 真实注册表文件,仅 mock ./pi-invocation.ts(把 pi 二进制替换为 node -e 脚本)。
16
- //
17
- // mock 最小化原则:
18
- // - node:child_process 不 mock(真实 spawn / spawnSync git)
19
- // - node:fs 不 mock(真实目录/文件:worktree checkout、注册表 JSON)
20
- // - alive-store 不 mock(真实 process.kill(pid, 0) 探活)
21
- // - 仅 vi.mock("./pi-invocation.ts"):getPiInvocation 返回 node -e 脚本
22
- // - fake timers 仅 toFake: ["Date"]:推进注册表宽限判定用,不干扰真实 I/O 事件
23
-
24
- import { spawnSync } from "node:child_process";
25
- import * as fs from "node:fs";
26
- import * as os from "node:os";
27
- import * as path from "node:path";
28
-
29
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
30
-
31
- // vi.hoisted:vi.mock 工厂体内不能引用顶层 let/const(提升限制),脚本字符串必须放这。
32
- // scriptHolder 是可变对象:getPiInvocation 每次调用时读它(工厂函数体在运行时执行),
33
- // 用例内可切换长驻/短命脚本。
34
- const { scriptHolder, LONG_RUNNING_SCRIPT, SHORT_LIVED_SCRIPT } = vi.hoisted(() => {
35
- const scriptHolder: { script: string } = { script: "process.exit(0)" };
36
- return {
37
- scriptHolder,
38
- // 长驻脚本:90s 后退出(测试在 61s scan 时它必须还活着,验证「活 worktree 不被清」)
39
- LONG_RUNNING_SCRIPT:
40
- "setTimeout(() => process.exit(0), 90000);",
41
- // 短命脚本:立即退出(模拟快速完成的子 agent,验证「真孤儿被回收」)
42
- SHORT_LIVED_SCRIPT: "process.exit(0)",
43
- };
44
- });
45
-
46
- vi.mock("./pi-invocation.ts", () => ({
47
- getPiInvocation: (userArgs: string[]) => ({
48
- command: process.execPath,
49
- args: ["-e", scriptHolder.script, ...userArgs],
50
- }),
51
- }));
52
-
53
- import { WorktreeManager } from "../worktree-manager.ts";
54
- import { WorktreeRegistry, SPAWN_GRACE_MS } from "../worktree-registry.ts";
55
- import { runSpawn } from "../session-runner.ts";
56
- import type { WorktreeHandle } from "../types.ts";
57
- import { makeCtx, makeOpts, makeRecord } from "./helpers/spawn-mock.ts";
58
-
59
- // ── 测试夹具:临时 git repo + 临时 agentDir(避免污染 ~/.pi/agent)──
60
-
61
- let tmpRoot: string;
62
- let repoDir: string;
63
- let agentDir: string;
64
- let wtm: WorktreeManager;
65
- let registry: WorktreeRegistry;
66
- let handle: WorktreeHandle | undefined;
67
- let spawnedPid: number | undefined;
68
-
69
- function git(args: string[], cwd: string): string {
70
- const r = spawnSync("git", args, { cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
71
- return (r.stdout ?? "").trim();
72
- }
73
-
74
- /** 初始化临时 git repo(至少一个 commit,worktreeManager.create 需要 clean tree + HEAD)。 */
75
- function initRepo(): void {
76
- repoDir = path.join(tmpRoot, "repo");
77
- fs.mkdirSync(repoDir, { recursive: true });
78
- git(["init", "-b", "main"], repoDir);
79
- git(["config", "user.email", "test@test.local"], repoDir);
80
- git(["config", "user.name", "test"], repoDir);
81
- git(["commit", "--allow-empty", "-m", "init"], repoDir);
82
- }
83
-
84
- /** 从注册表文件读指定 branch 的条目(真实文件,轮询用)。 */
85
- function readEntry(branch: string): { pid: number; createdAt: number } | undefined {
86
- return registry.load().find((e) => e.branch === branch);
87
- }
88
-
89
- /** 轮询注册表直到 pid 补全(真实 fs 读 + 真实 setTimeout 轮询)。 */
90
- async function waitForPid(branch: string, timeoutMs = 5000): Promise<number> {
91
- const start = Date.now();
92
- while (Date.now() - start < timeoutMs) {
93
- const entry = readEntry(branch);
94
- if (entry && entry.pid !== 0) return entry.pid;
95
- await new Promise((r) => setTimeout(r, 20));
96
- }
97
- throw new Error(`pid not registered within ${timeoutMs}ms (branch=${branch})`);
98
- }
99
-
100
- /** 清理:kill 子进程 + worktree cleanup + 删除临时目录。 */
101
- async function cleanup(): Promise<void> {
102
- if (spawnedPid) {
103
- try {
104
- process.kill(spawnedPid, "SIGKILL");
105
- } catch {
106
- // 已退出
107
- }
108
- spawnedPid = undefined;
109
- }
110
- if (handle) {
111
- try {
112
- await wtm.cleanup(handle);
113
- } catch (err) {
114
- // best-effort:git worktree remove 失败不阻断测试清理
115
- // eslint-disable-next-line no-console
116
- console.warn("worktree cleanup failed in test teardown", err);
117
- }
118
- handle = undefined;
119
- }
120
- try {
121
- fs.rmSync(tmpRoot, { recursive: true, force: true });
122
- } catch {
123
- // best-effort
124
- }
125
- }
126
-
127
- beforeEach(() => {
128
- tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "wt-reaper-it-"));
129
- agentDir = path.join(tmpRoot, "agent");
130
- initRepo();
131
- wtm = new WorktreeManager(agentDir);
132
- registry = new WorktreeRegistry(agentDir);
133
- });
134
-
135
- afterEach(async () => {
136
- vi.useRealTimers();
137
- await cleanup();
138
- });
139
-
140
- // ── 用例 ──
141
-
142
- // [HISTORICAL] 2026-08-20 PR #185:真实 spawn node 子进程 + 真实 git worktree + 注册表
143
- // 文件锁集成用例显式超时——整包满并行 + 系统余载下真实子进程链路超 vitest 默认 5s
144
- // testTimeout(对齐本包 worktree-registry D5a / process-shutdown-hook 口径)。
145
- describe("worktree pid 注册链路(真实 spawn 集成)", { timeout: 30_000 }, () => {
146
- it("正向:spawn 返回后注册表 pid 同步补全,活 worktree 超宽限不被 scan 误清", async () => {
147
- // 0. 长驻脚本(子进程 90s 内不退出,模拟长跑子 agent)
148
- scriptHolder.script = LONG_RUNNING_SCRIPT; // 1. 真实创建 worktree(pid=0 占位)
149
- handle = await wtm.create(repoDir, "rec-1");
150
- expect(readEntry(handle.branch)).toMatchObject({ pid: 0 });
151
-
152
- // 2. runSpawn 挂后台(不 await——长驻子进程 close 不触发,await 会挂死),
153
- // ctx.onWorktreePid 接真实 registerPid(模拟 subagent-service 接线)
154
- const ctx = makeCtx({
155
- agentDir,
156
- cwd: repoDir,
157
- mainCwd: repoDir,
158
- rootCwd: repoDir,
159
- onWorktreePid: (branch: string, pid: number) => wtm.registerPid(branch, pid),
160
- });
161
- const runPromise = runSpawn(
162
- makeRecord(),
163
- "test task",
164
- makeOpts({ worktree: handle }),
165
- ctx,
166
- );
167
-
168
- // 3. 断言 spawn 后 pid 已补全(真实注册表文件轮询)——修复前此步超时红
169
- spawnedPid = await waitForPid(handle.branch);
170
- expect(spawnedPid).toBeGreaterThan(0);
171
-
172
- // 4. 推进时钟超 SPAWN_GRACE_MS(仅 fake Date,不干扰真实 I/O)
173
- vi.useFakeTimers({ toFake: ["Date"] });
174
- vi.setSystemTime(Date.now() + SPAWN_GRACE_MS + 1000);
175
-
176
- // 5. scan():活 worktree 必须不被清(修复前:pid=0 超宽限 → 误删 → 红)
177
- await wtm.scan();
178
- expect(fs.existsSync(handle.path)).toBe(true);
179
-
180
- // 6. 收尾:真实时钟恢复 + kill 子进程让 runPromise settle
181
- vi.useRealTimers();
182
- try {
183
- process.kill(spawnedPid, "SIGTERM");
184
- } catch {
185
- // 已退出
186
- }
187
- await runPromise;
188
-
189
- // 7. 反向:进程死后 scan 回收真孤儿
190
- await wtm.scan();
191
- expect(fs.existsSync(handle.path)).toBe(false);
192
- const entryAfter = readEntry(handle.branch);
193
- expect(entryAfter).toBeUndefined();
194
- }, 15000);
195
-
196
- it("反向:短命子进程退出后,pid>0 且进程死 → scan 立即回收", async () => {
197
- // 0. 短命脚本(子进程立即退出,模拟快速完成的子 agent)
198
- scriptHolder.script = SHORT_LIVED_SCRIPT;
199
- // 1. 真实创建 worktree
200
- handle = await wtm.create(repoDir, "rec-2");
201
-
202
- // 2. 短命脚本子进程:spawn 后同步补 pid(修复前 pid=0,且未超宽限 → 不回收 → 红)
203
- const ctx = makeCtx({
204
- agentDir,
205
- cwd: repoDir,
206
- mainCwd: repoDir,
207
- rootCwd: repoDir,
208
- onWorktreePid: (branch: string, pid: number) => wtm.registerPid(branch, pid),
209
- });
210
- const result = await runSpawn(
211
- makeRecord(),
212
- "test task",
213
- makeOpts({ worktree: handle }),
214
- ctx,
215
- );
216
- expect(result.status).not.toBe("error"); // 进程正常退出(exit 0),非 spawn 失败
217
-
218
- // 3. pid 已补全(短命进程退出后 pid 仍有效,registerPid 同步执行不受退出影响)
219
- const entry = readEntry(handle.branch);
220
- expect(entry).toBeDefined();
221
- expect(entry!.pid).toBeGreaterThan(0);
222
- spawnedPid = entry!.pid;
223
-
224
- // 4. scan:pid>0 且进程死 → 立即判孤儿回收(无需等宽限)
225
- await wtm.scan();
226
- expect(fs.existsSync(handle.path)).toBe(false);
227
- expect(readEntry(handle.branch)).toBeUndefined();
228
- }, 15000);
229
- });
@@ -1,181 +0,0 @@
1
- // src/__tests__/worktree-reconcile.integration.test.ts
2
- //
3
- // D5b 对账双向 diff 集成测试:真实 git repo + 真实 tmpdir(不 mock fs/execFile)。
4
- //
5
- // 隔离手段:TMPDIR env 重定向到测试私有目录——WorktreeManager 的物理面扫描
6
- // 根 = os.tmpdir()/pi-subagents(跟随 TMPDIR),避免扫到本机其他进程的真实残留。
7
- //
8
- // 覆盖四个收敛方向(判据见 worktree-manager.ts reconcileWithPhysical):
9
- // 1. 物理有 + 注册无 + 无活 pid + 超 grace → 清分支与目录
10
- // 2. 物理有 + 注册无 + 恰好 1 活 pid + 1 残留 → 补写回注册表(自愈)
11
- // 3. 注册有(pid 活)+ 物理无 → 移除幻影条目
12
- // 4. 多活 pid / 多残留(对应歧义)→ 跳过不动(宁延迟勿误删)
13
-
14
- import { execFileSync, spawn } from "node:child_process";
15
- import * as fs from "node:fs";
16
- import * as os from "node:os";
17
- import * as path from "node:path";
18
-
19
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
20
-
21
- import { encodeCwd } from "../path-encoding.ts";
22
- import { WorktreeRegistry } from "../worktree-registry.ts";
23
- import { WorktreeManager } from "../worktree-manager.ts";
24
-
25
- /** 原始 TMPDIR(beforeEach 重定向、afterEach 还原)。 */
26
- const ORIG_TMPDIR = os.tmpdir();
27
-
28
- /** git 辅助:repo 内执行(输出 trim)。 */
29
- function git(repo: string, ...args: string[]): string {
30
- return execFileSync("git", ["-C", repo, ...args], { encoding: "utf-8" }).trim();
31
- }
32
-
33
- // [HISTORICAL] 2026-08-20 PR #185:真实 git 子进程 + 注册表文件锁集成用例显式超时——
34
- // 每用例多次 git init/worktree add/branch -D 真实子进程调用,整包满并行 + 系统余载下
35
- // 超 vitest 默认 5s testTimeout(对齐本包 worktree-registry D5a / process-shutdown-hook 口径)。
36
- describe("WorktreeManager.scan 物理面对账(D5b)", { timeout: 30_000 }, () => {
37
- let baseDir: string;
38
- let agentDir: string;
39
- let repo: string;
40
- let enc: string;
41
- let registry: WorktreeRegistry;
42
- let mgr: WorktreeManager;
43
- /** 真实系统 tmp 下的测试根(TMPDIR 重定向目标)。 */
44
- let outerDir: string;
45
-
46
- beforeEach(() => {
47
- outerDir = fs.mkdtempSync(path.join(ORIG_TMPDIR, "wt-reconcile-it-"));
48
- // 物理面扫描根重定向:os.tmpdir() 跟随 TMPDIR env(darwin/linux 均如此)
49
- process.env.TMPDIR = outerDir;
50
- baseDir = outerDir;
51
-
52
- agentDir = path.join(baseDir, "agent");
53
- repo = path.join(baseDir, "repo");
54
- fs.mkdirSync(repo, { recursive: true });
55
- git(repo, "init", "-q");
56
- git(repo, "config", "user.email", "test@test.local");
57
- git(repo, "config", "user.name", "test");
58
- fs.writeFileSync(path.join(repo, "a.txt"), "init\n", "utf-8");
59
- git(repo, "add", "-A");
60
- git(repo, "commit", "-q", "-m", "init");
61
-
62
- enc = encodeCwd(repo);
63
- registry = new WorktreeRegistry(agentDir);
64
- mgr = new WorktreeManager(agentDir);
65
- });
66
-
67
- afterEach(() => {
68
- process.env.TMPDIR = ORIG_TMPDIR;
69
- fs.rmSync(outerDir, { recursive: true, force: true });
70
- });
71
-
72
- /** 建一个物理 worktree(按 create() 的真实路径布局,绕过 WorktreeManager.create 的脏树校验)。 */
73
- function makePhysicalWorktree(branch: string): string {
74
- const checkout = path.join(baseDir, "pi-subagents", enc, branch);
75
- git(repo, "worktree", "add", "-q", "-b", branch, checkout, "HEAD");
76
- return checkout;
77
- }
78
-
79
- /** 在 <agentDir>/subagents/<enc>/sessions/ 下写一个 .alive marker。 */
80
- function writeAliveMarker(sessionId: string, pid: number): void {
81
- const sessions = path.join(agentDir, "subagents", enc, "sessions");
82
- fs.mkdirSync(sessions, { recursive: true });
83
- fs.writeFileSync(
84
- path.join(sessions, `${sessionId}.jsonl.alive`),
85
- JSON.stringify({ pid, id: sessionId, startedAt: Date.now() }),
86
- "utf-8",
87
- );
88
- }
89
-
90
- /** 把目录 mtime 设到 grace 之前(对账判据的 createdAt 近似)。 */
91
- function ageBeyondGrace(dir: string): void {
92
- const past = new Date(Date.now() - 120_000);
93
- fs.utimesSync(dir, past, past);
94
- }
95
-
96
- it("物理有 + 注册无 + 无活 pid + 超 grace → 清分支与目录", async () => {
97
- const checkout = makePhysicalWorktree("pi-sub-t1");
98
- ageBeyondGrace(checkout);
99
-
100
- await mgr.scan();
101
-
102
- expect(fs.existsSync(checkout)).toBe(false);
103
- expect(git(repo, "branch", "--list", "pi-sub-*")).toBe("");
104
- expect(registry.load()).toEqual([]);
105
- });
106
-
107
- it("物理有 + 注册无 + 未超 grace(create 窗口)→ 跳过不删", async () => {
108
- const checkout = makePhysicalWorktree("pi-sub-t2");
109
- // mtime 保持「现在」——另一进程 worktree add 完成到 registry.add 落盘之间的窗口
110
-
111
- await mgr.scan();
112
-
113
- expect(fs.existsSync(checkout)).toBe(true);
114
- expect(git(repo, "branch", "--list", "pi-sub-t2")).not.toBe("");
115
- });
116
-
117
- it("物理有 + 注册无 + 恰好 1 活 pid + 1 残留 → 补写回注册表(自愈)", async () => {
118
- const checkout = makePhysicalWorktree("pi-sub-t3");
119
- // 活 pid 用本测试进程(isProcessAlive 真实调用必活)
120
- writeAliveMarker("s-t3", process.pid);
121
-
122
- await mgr.scan();
123
-
124
- const entries = registry.load();
125
- expect(entries).toHaveLength(1);
126
- expect(entries[0].branch).toBe("pi-sub-t3");
127
- expect(entries[0].pid).toBe(process.pid);
128
- expect(entries[0].checkout).toBe(checkout);
129
- // 物理资源未被删(自愈而非只删)
130
- expect(fs.existsSync(checkout)).toBe(true);
131
- });
132
-
133
- it("注册有(pid 活)+ 物理无 → 移除幻影条目", async () => {
134
- // pid 活(本进程)使阶段一孤儿清理跳过,隔离方向一的独立语义
135
- await registry.add({
136
- repo,
137
- branch: "pi-sub-ghost",
138
- checkout: path.join(baseDir, "pi-subagents", enc, "pi-sub-ghost"),
139
- pid: process.pid,
140
- createdAt: Date.now(),
141
- });
142
-
143
- await mgr.scan();
144
-
145
- expect(registry.load()).toEqual([]);
146
- });
147
-
148
- it("多残留 + 多活 pid(对应歧义)→ 跳过不动", async () => {
149
- const c1 = makePhysicalWorktree("pi-sub-m1");
150
- const c2 = makePhysicalWorktree("pi-sub-m2");
151
- ageBeyondGrace(c1);
152
- ageBeyondGrace(c2);
153
- // 第二个「活 pid」用真实 sleep 子进程(与 process.pid 不同值)
154
- const sleeper = spawn("sleep", ["60"]);
155
- try {
156
- expect(sleeper.pid).toBeTruthy();
157
- writeAliveMarker("s-m1", process.pid);
158
- writeAliveMarker("s-m2", sleeper.pid as number);
159
-
160
- await mgr.scan();
161
-
162
- // 歧义 → 本周期全部跳过(宁延迟勿误删),下周期活 pid 消失后收敛
163
- expect(fs.existsSync(c1)).toBe(true);
164
- expect(fs.existsSync(c2)).toBe(true);
165
- expect(registry.load()).toEqual([]);
166
- } finally {
167
- sleeper.kill("SIGKILL");
168
- }
169
- });
170
-
171
- it("幂等:连续两次 scan 结果一致(无重复动作)", async () => {
172
- const checkout = makePhysicalWorktree("pi-sub-idem");
173
- ageBeyondGrace(checkout);
174
-
175
- await mgr.scan();
176
- await mgr.scan();
177
-
178
- expect(fs.existsSync(checkout)).toBe(false);
179
- expect(git(repo, "branch", "--list", "pi-sub-*")).toBe("");
180
- });
181
- });
@@ -1,199 +0,0 @@
1
- // src/__tests__/worktree-registry.test.ts
2
- //
3
- // WorktreeRegistry 单元测试。
4
- // 用真实 tmpdir 做文件 IO(不 mock fs),验证:
5
- // - add/updatePid/remove/load 语义
6
- // - 同 branch 覆盖(去重)
7
- // - 文件不存在 / 损坏 / IO 错误的降级
8
- // - 原子写(.tmp → rename)
9
-
10
- import * as fs from "node:fs";
11
- import * as os from "node:os";
12
- import * as path from "node:path";
13
-
14
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
15
-
16
- import { SPAWN_GRACE_MS, type WorktreeEntry,WorktreeRegistry } from "../worktree-registry.ts";
17
-
18
- const REPO_A = "/home/user/repo-a";
19
- const REPO_B = "/home/user/repo-b";
20
-
21
- function makeEntry(overrides: Partial<WorktreeEntry> = {}): WorktreeEntry {
22
- return {
23
- repo: REPO_A,
24
- branch: "pi-sub-bg-1",
25
- checkout: path.join(os.tmpdir(), "pi-sub-bg-1"),
26
- pid: 0,
27
- createdAt: Date.now(),
28
- ...overrides,
29
- };
30
- }
31
-
32
- describe("WorktreeRegistry", () => {
33
- let tmpAgentDir: string;
34
- let registry: WorktreeRegistry;
35
- let registryFile: string;
36
-
37
- beforeEach(() => {
38
- tmpAgentDir = fs.mkdtempSync(path.join(os.tmpdir(), "wt-registry-test-"));
39
- registry = new WorktreeRegistry(tmpAgentDir);
40
- registryFile = path.join(tmpAgentDir, "subagents", "worktrees.json");
41
- });
42
-
43
- afterEach(() => {
44
- fs.rmSync(tmpAgentDir, { recursive: true, force: true });
45
- });
46
-
47
- describe("add + load", () => {
48
- it("add 后 load 能读到", async () => {
49
- const entry = makeEntry();
50
- await registry.add(entry);
51
- const loaded = registry.load();
52
- expect(loaded).toHaveLength(1);
53
- expect(loaded[0]).toEqual(entry);
54
- });
55
-
56
- it("多条目跨 repo 共存", async () => {
57
- const entryA = makeEntry({ repo: REPO_A, branch: "pi-sub-bg-1" });
58
- const entryB = makeEntry({ repo: REPO_B, branch: "pi-sub-bg-2" });
59
- await registry.add(entryA);
60
- await registry.add(entryB);
61
- const loaded = registry.load();
62
- expect(loaded).toHaveLength(2);
63
- });
64
-
65
- it("同 branch add 覆盖(去重)", async () => {
66
- const entry = makeEntry({ pid: 0 });
67
- await registry.add(entry);
68
- // 同 branch 再次 add(覆盖)
69
- const updated = makeEntry({ pid: 999 });
70
- await registry.add(updated);
71
- const loaded = registry.load();
72
- expect(loaded).toHaveLength(1);
73
- expect(loaded[0].pid).toBe(999);
74
- });
75
- });
76
-
77
- describe("updatePid", () => {
78
- it("补全 pid(create 占位 → first header 补全)", async () => {
79
- await registry.add(makeEntry({ branch: "pi-sub-bg-1", pid: 0 }));
80
- await registry.updatePid("pi-sub-bg-1", 12345);
81
- const loaded = registry.load();
82
- expect(loaded[0].pid).toBe(12345);
83
- });
84
-
85
- it("branch 不存在时忽略(幂等)", async () => {
86
- await registry.add(makeEntry({ branch: "pi-sub-bg-1" }));
87
- await registry.updatePid("pi-sub-nonexistent", 12345);
88
- const loaded = registry.load();
89
- expect(loaded).toHaveLength(1);
90
- expect(loaded[0].pid).toBe(0); // 原条目未变
91
- });
92
-
93
- it("update 不改变其他字段", async () => {
94
- const entry = makeEntry({ branch: "pi-sub-bg-1", repo: REPO_A, checkout: "/tmp/x" });
95
- await registry.add(entry);
96
- await registry.updatePid("pi-sub-bg-1", 999);
97
- const loaded = registry.load();
98
- expect(loaded[0].repo).toBe(REPO_A);
99
- expect(loaded[0].checkout).toBe("/tmp/x");
100
- expect(loaded[0].branch).toBe("pi-sub-bg-1");
101
- });
102
- });
103
-
104
- describe("remove", () => {
105
- it("移除指定 branch", async () => {
106
- await registry.add(makeEntry({ branch: "pi-sub-bg-1" }));
107
- await registry.add(makeEntry({ branch: "pi-sub-bg-2" }));
108
- await registry.remove("pi-sub-bg-1");
109
- const loaded = registry.load();
110
- expect(loaded).toHaveLength(1);
111
- expect(loaded[0].branch).toBe("pi-sub-bg-2");
112
- });
113
-
114
- it("branch 不存在时忽略(幂等)", async () => {
115
- await registry.add(makeEntry({ branch: "pi-sub-bg-1" }));
116
- await registry.remove("pi-sub-nonexistent");
117
- expect(registry.load()).toHaveLength(1);
118
- });
119
-
120
- it("空注册表 remove 不报错", async () => {
121
- await expect(registry.remove("pi-sub-anything")).resolves.not.toThrow();
122
- });
123
- });
124
-
125
- describe("降级与健壮性", () => {
126
- it("文件不存在时 load 返回空数组", async () => {
127
- expect(registry.load()).toEqual([]);
128
- });
129
-
130
- it("损坏 JSON 时 load 返回空数组", async () => {
131
- fs.mkdirSync(path.dirname(registryFile), { recursive: true });
132
- fs.writeFileSync(registryFile, "{ not valid json }}}", "utf-8");
133
- expect(registry.load()).toEqual([]);
134
- });
135
-
136
- it("entries 字段缺失时 load 返回空数组", async () => {
137
- fs.mkdirSync(path.dirname(registryFile), { recursive: true });
138
- fs.writeFileSync(registryFile, '{"other": 123}', "utf-8");
139
- expect(registry.load()).toEqual([]);
140
- });
141
-
142
- it("save 创建不存在的父目录", async () => {
143
- // registryFile 在 tmpAgentDir/subagents/ 下,subagents 目录不存在
144
- expect(fs.existsSync(path.dirname(registryFile))).toBe(false);
145
- await registry.add(makeEntry());
146
- expect(fs.existsSync(registryFile)).toBe(true);
147
- });
148
-
149
- it("save 后无残留 .tmp 文件(原子写)", async () => {
150
- await registry.add(makeEntry());
151
- const tmpFile = `${registryFile}.tmp`;
152
- expect(fs.existsSync(tmpFile)).toBe(false);
153
- });
154
- });
155
-
156
- describe("SPAWN_GRACE_MS 常量", () => {
157
- it("值为 60s", async () => {
158
- expect(SPAWN_GRACE_MS).toBe(60_000);
159
- });
160
- });
161
-
162
- describe("D5a 锁互斥(两写方并发不丢条目)", () => {
163
- // [HISTORICAL] 2026-08-20 PR #185:真实 proper-lockfile 文件锁 RMW 用例显式超时——
164
- // 单跑 >1s,整包满并行 + 系统余载下 100/31 次持锁 load→mutate→save 超过 vitest
165
- // 默认 5s testTimeout(隔离跑通过,纯环境饿死),对齐本包 record-store-index 口径。
166
- it("两个 registry 实例(模拟两 pi 进程写方)并发各 add 50 条,零丢失", { timeout: 30_000 }, async () => {
167
- // 失败模式 G 的复现形态:无锁时两实例 load→mutate→save 交错,后写者覆盖
168
- // 先写者 → 条目丢失。锁内 RMW 应保证 100 条全部落盘。
169
- const r1 = new WorktreeRegistry(tmpAgentDir);
170
- const r2 = new WorktreeRegistry(tmpAgentDir);
171
- const tasks: Promise<void>[] = [];
172
- for (let i = 0; i < 50; i++) {
173
- tasks.push(r1.add(makeEntry({ branch: `pi-sub-w1-${i}` })));
174
- tasks.push(r2.add(makeEntry({ branch: `pi-sub-w2-${i}` })));
175
- }
176
- await Promise.all(tasks);
177
- const loaded = r1.load();
178
- expect(loaded).toHaveLength(100);
179
- // 两写方的条目都在(非「后写者全量覆盖」形态)
180
- expect(loaded.filter((e) => e.branch.startsWith("pi-sub-w1-"))).toHaveLength(50);
181
- expect(loaded.filter((e) => e.branch.startsWith("pi-sub-w2-"))).toHaveLength(50);
182
- });
183
-
184
- it("并发 add + remove 交错:remove 只删自己的 branch", { timeout: 30_000 }, async () => {
185
- const r1 = new WorktreeRegistry(tmpAgentDir);
186
- const r2 = new WorktreeRegistry(tmpAgentDir);
187
- await r1.add(makeEntry({ branch: "pi-sub-keep" }));
188
- const tasks: Promise<void>[] = [];
189
- for (let i = 0; i < 30; i++) {
190
- tasks.push(r2.add(makeEntry({ branch: `pi-sub-n-${i}` })));
191
- }
192
- tasks.push(r1.remove("pi-sub-keep"));
193
- await Promise.all(tasks);
194
- const loaded = r1.load();
195
- expect(loaded).toHaveLength(30);
196
- expect(loaded.find((e) => e.branch === "pi-sub-keep")).toBeUndefined();
197
- });
198
- });
199
- });