@zhushanwen/pi-subagent-workflow 8.6.0 → 8.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (347) hide show
  1. package/package.json +9 -13
  2. package/relay/relay.mjs +1 -1
  3. package/src/host/__tests__/pi-host.test.ts +214 -0
  4. package/src/host/pi-host.ts +109 -0
  5. package/src/index.ts +89 -32
  6. package/src/injectors/__tests__/engine-awareness.test.ts +292 -0
  7. package/src/injectors/__tests__/engine-section-stability.test.ts +341 -0
  8. package/src/injectors/__tests__/subagent-list-injector.test.ts +5 -5
  9. package/src/injectors/__tests__/workflow-list-injector.test.ts +5 -5
  10. package/src/injectors/engine-awareness.ts +123 -0
  11. package/src/injectors/model-list-injector.ts +1 -1
  12. package/src/injectors/subagent-list-injector.ts +8 -8
  13. package/src/injectors/workflow-list-injector.ts +8 -8
  14. package/src/interface/__tests__/detectors.test.ts +3 -3
  15. package/src/interface/__tests__/subagent-tool-path-guard.test.ts +2 -2
  16. package/src/interface/__tests__/tool-workflow-script-generate.test.ts +2 -2
  17. package/src/interface/__tests__/tool-workflow-throw-paths.test.ts +1 -1
  18. package/src/interface/bg-notify-render.ts +4 -4
  19. package/src/interface/commands.ts +3 -3
  20. package/src/interface/format.ts +2 -2
  21. package/src/interface/helpers.ts +1 -1
  22. package/src/interface/list-component.ts +4 -4
  23. package/src/interface/list-shared.ts +2 -2
  24. package/src/interface/list-view.ts +2 -2
  25. package/src/interface/subagent-actions.ts +263 -11
  26. package/src/interface/subagent-tool-schema.ts +20 -13
  27. package/src/interface/subagent-tool.ts +11 -6
  28. package/src/interface/subagents.ts +3 -3
  29. package/src/interface/tool-render.ts +34 -2
  30. package/src/interface/tool-workflow-script.ts +4 -4
  31. package/src/interface/tool-workflow.ts +6 -6
  32. package/src/interface/views/WorkflowsView.ts +5 -5
  33. package/src/interface/views/__tests__/WorkflowsView-signature.test.ts +3 -3
  34. package/src/interface/views/__tests__/detail-content-session-file.test.ts +2 -2
  35. package/src/interface/views/detail-content.ts +4 -4
  36. package/src/interface/views/format.ts +4 -4
  37. package/src/{orchestration/jsonl-run-store.ts → jsonl-run-store.ts} +11 -11
  38. package/src/execution/__tests__/__fixtures__/notifier-golden-snapshots.json +0 -53
  39. package/src/execution/__tests__/__fixtures__/truncline.snapshot.json +0 -1
  40. package/src/execution/__tests__/agent-registry.test.ts +0 -363
  41. package/src/execution/__tests__/agent-result-mapper.test.ts +0 -150
  42. package/src/execution/__tests__/alive-store.test.ts +0 -147
  43. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +0 -490
  44. package/src/execution/__tests__/before-agent-start-injection.test.ts +0 -132
  45. package/src/execution/__tests__/bg-notify-render.test.ts +0 -329
  46. package/src/execution/__tests__/channel-registry-handshake.test.ts +0 -243
  47. package/src/execution/__tests__/chat-engine-routing.test.ts +0 -601
  48. package/src/execution/__tests__/chatmode-first-round-closure-service.test.ts +0 -365
  49. package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +0 -190
  50. package/src/execution/__tests__/chatmode-round-notify-real-chain.test.ts +0 -215
  51. package/src/execution/__tests__/concurrency-pool.test.ts +0 -250
  52. package/src/execution/__tests__/config.test.ts +0 -110
  53. package/src/execution/__tests__/conversation-wiring.test.ts +0 -198
  54. package/src/execution/__tests__/crash-recovery.test.ts +0 -320
  55. package/src/execution/__tests__/delivery-methods.test.ts +0 -422
  56. package/src/execution/__tests__/dialog-queue.test.ts +0 -299
  57. package/src/execution/__tests__/epipe-fallback.test.ts +0 -241
  58. package/src/execution/__tests__/execute-and-await-worktree.test.ts +0 -243
  59. package/src/execution/__tests__/execute-nesting.test.ts +0 -323
  60. package/src/execution/__tests__/execute-options-mapper.test.ts +0 -200
  61. package/src/execution/__tests__/execution-record.test.ts +0 -1394
  62. package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +0 -171
  63. package/src/execution/__tests__/finalize-record.test.ts +0 -368
  64. package/src/execution/__tests__/finalized-marker.test.ts +0 -82
  65. package/src/execution/__tests__/format-schema-instruction.test.ts +0 -169
  66. package/src/execution/__tests__/format.test.ts +0 -458
  67. package/src/execution/__tests__/gc-timer.test.ts +0 -184
  68. package/src/execution/__tests__/get-record-for-action-restart.test.ts +0 -254
  69. package/src/execution/__tests__/gui-mode-dispatch.test.ts +0 -59
  70. package/src/execution/__tests__/helpers/mock-extension-api.ts +0 -30
  71. package/src/execution/__tests__/helpers/spawn-mock.ts +0 -242
  72. package/src/execution/__tests__/host-mode.test.ts +0 -87
  73. package/src/execution/__tests__/index-session-start-identity.test.ts +0 -371
  74. package/src/execution/__tests__/index-session-start.test.ts +0 -672
  75. package/src/execution/__tests__/lifecycle-manager-lock.test.ts +0 -211
  76. package/src/execution/__tests__/lifecycle-manager.test.ts +0 -383
  77. package/src/execution/__tests__/lifecycle-predicates.test.ts +0 -116
  78. package/src/execution/__tests__/list-component.test.ts +0 -401
  79. package/src/execution/__tests__/list-fields.test.ts +0 -140
  80. package/src/execution/__tests__/manifest-parentid.test.ts +0 -117
  81. package/src/execution/__tests__/model-resolver.test.ts +0 -465
  82. package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +0 -287
  83. package/src/execution/__tests__/nested-visibility.test.ts +0 -325
  84. package/src/execution/__tests__/notifier-flush.test.ts +0 -612
  85. package/src/execution/__tests__/notifier-golden-snapshot.test.ts +0 -261
  86. package/src/execution/__tests__/notify-ledger.test.ts +0 -826
  87. package/src/execution/__tests__/one-shot-upgrade.test.ts +0 -205
  88. package/src/execution/__tests__/output-collector.test.ts +0 -358
  89. package/src/execution/__tests__/parent-child-matrix.test.ts +0 -336
  90. package/src/execution/__tests__/path-encoding.test.ts +0 -104
  91. package/src/execution/__tests__/pi-invocation.test.ts +0 -134
  92. package/src/execution/__tests__/record-store.test.ts +0 -1057
  93. package/src/execution/__tests__/records-cwd-isolation.test.ts +0 -91
  94. package/src/execution/__tests__/recursive-visibility-baseline.test.ts +0 -339
  95. package/src/execution/__tests__/recursive-visibility-env.test.ts +0 -273
  96. package/src/execution/__tests__/relay-agent.test.ts +0 -448
  97. package/src/execution/__tests__/relay-env.test.ts +0 -42
  98. package/src/execution/__tests__/resource-policy.test.ts +0 -109
  99. package/src/execution/__tests__/rpc-mode.test.ts +0 -89
  100. package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +0 -267
  101. package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +0 -253
  102. package/src/execution/__tests__/run-spawn-edges.test.ts +0 -687
  103. package/src/execution/__tests__/run-spawn-integration.test.ts +0 -933
  104. package/src/execution/__tests__/run-spawn-resume.test.ts +0 -322
  105. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +0 -196
  106. package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +0 -199
  107. package/src/execution/__tests__/sdk-contract.test.ts +0 -273
  108. package/src/execution/__tests__/session-context-resolver.test.ts +0 -167
  109. package/src/execution/__tests__/session-file-gc.test.ts +0 -293
  110. package/src/execution/__tests__/session-pending.test.ts +0 -197
  111. package/src/execution/__tests__/session-reconstructor.test.ts +0 -379
  112. package/src/execution/__tests__/session-runner-epipe.test.ts +0 -178
  113. package/src/execution/__tests__/session-runner-schema-env.test.ts +0 -350
  114. package/src/execution/__tests__/session-start-reaper.test.ts +0 -233
  115. package/src/execution/__tests__/spawn-args.test.ts +0 -445
  116. package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +0 -189
  117. package/src/execution/__tests__/spawn-event-adapter.test.ts +0 -167
  118. package/src/execution/__tests__/spawn-worktree-guidance.test.ts +0 -207
  119. package/src/execution/__tests__/spawned-children.test.ts +0 -92
  120. package/src/execution/__tests__/start-sync-model-guard.test.ts +0 -150
  121. package/src/execution/__tests__/startup-config-declaration.test.ts +0 -35
  122. package/src/execution/__tests__/status-refactor.test.ts +0 -345
  123. package/src/execution/__tests__/stdin-writer.test.ts +0 -463
  124. package/src/execution/__tests__/stream-sink-retirement.test.ts +0 -261
  125. package/src/execution/__tests__/subagent-service-abort.test.ts +0 -60
  126. package/src/execution/__tests__/subagent-service-message-close.test.ts +0 -629
  127. package/src/execution/__tests__/subagent-service-parent-guard.test.ts +0 -180
  128. package/src/execution/__tests__/subagent-service.test.ts +0 -788
  129. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +0 -310
  130. package/src/execution/__tests__/subprocess-agent-runner.test.ts +0 -599
  131. package/src/execution/__tests__/temp-prompt.test.ts +0 -53
  132. package/src/execution/__tests__/timeout-integration.test.ts +0 -615
  133. package/src/execution/__tests__/tombstone-store.test.ts +0 -73
  134. package/src/execution/__tests__/tool-action.test.ts +0 -476
  135. package/src/execution/__tests__/truncline-snapshot.test.ts +0 -81
  136. package/src/execution/__tests__/turn-limiter-semantics.test.ts +0 -194
  137. package/src/execution/__tests__/turn-limiter.test.ts +0 -65
  138. package/src/execution/__tests__/ui-channels.test.ts +0 -187
  139. package/src/execution/__tests__/ui-interaction-model.test.ts +0 -67
  140. package/src/execution/__tests__/ui-request-handler-factory.test.ts +0 -370
  141. package/src/execution/__tests__/ui-request-handler.test.ts +0 -204
  142. package/src/execution/__tests__/ui-request-observability.test.ts +0 -114
  143. package/src/execution/__tests__/ui-request-queue.test.ts +0 -133
  144. package/src/execution/__tests__/worktree-manager.test.ts +0 -633
  145. package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +0 -229
  146. package/src/execution/__tests__/worktree-reconcile.integration.test.ts +0 -181
  147. package/src/execution/__tests__/worktree-registry.test.ts +0 -199
  148. package/src/execution/agent-registry.ts +0 -199
  149. package/src/execution/agent-result-mapper.ts +0 -90
  150. package/src/execution/alive-store.ts +0 -92
  151. package/src/execution/argv-mirror.ts +0 -113
  152. package/src/execution/best-effort.ts +0 -38
  153. package/src/execution/channel-registry-access.ts +0 -144
  154. package/src/execution/concurrency-pool.ts +0 -116
  155. package/src/execution/config.ts +0 -96
  156. package/src/execution/dialog-queue.ts +0 -330
  157. package/src/execution/engine/__tests__/common/data-dir.test.ts +0 -53
  158. package/src/execution/engine/__tests__/common/errors.test.ts +0 -132
  159. package/src/execution/engine/__tests__/common/event-journal.test.ts +0 -177
  160. package/src/execution/engine/__tests__/common/kill-chain.test.ts +0 -192
  161. package/src/execution/engine/__tests__/common/nesting-guard.test.ts +0 -81
  162. package/src/execution/engine/__tests__/common/persona-router.test.ts +0 -123
  163. package/src/execution/engine/__tests__/common/pool-manager.test.ts +0 -154
  164. package/src/execution/engine/__tests__/common/schema-emulation.test.ts +0 -128
  165. package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +0 -28
  166. package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +0 -141
  167. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +0 -109
  168. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +0 -101
  169. package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +0 -77
  170. package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +0 -104
  171. package/src/execution/engine/__tests__/conformance/contract.relay.test.ts +0 -342
  172. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +0 -201
  173. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +0 -76
  174. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +0 -79
  175. package/src/execution/engine/__tests__/engine-discovery.test.ts +0 -87
  176. package/src/execution/engine/__tests__/engines-declaration.test.ts +0 -36
  177. package/src/execution/engine/__tests__/model-prompt.test.ts +0 -85
  178. package/src/execution/engine/__tests__/paths.test.ts +0 -39
  179. package/src/execution/engine/__tests__/registry.test.ts +0 -120
  180. package/src/execution/engine/__tests__/routing.test.ts +0 -231
  181. package/src/execution/engine/common/data-dir.ts +0 -62
  182. package/src/execution/engine/common/errors.ts +0 -183
  183. package/src/execution/engine/common/event-journal.ts +0 -254
  184. package/src/execution/engine/common/journal-replay.ts +0 -62
  185. package/src/execution/engine/common/kill-chain.ts +0 -221
  186. package/src/execution/engine/common/nesting-guard.ts +0 -50
  187. package/src/execution/engine/common/persona-router.ts +0 -108
  188. package/src/execution/engine/common/pool-manager.ts +0 -226
  189. package/src/execution/engine/common/schema-emulation.ts +0 -189
  190. package/src/execution/engine/common/session-view-projection.ts +0 -51
  191. package/src/execution/engine/engine-discovery.ts +0 -65
  192. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +0 -469
  193. package/src/execution/engine/engines/pi/__tests__/reader.test.ts +0 -155
  194. package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +0 -164
  195. package/src/execution/engine/engines/pi/pi-engine.ts +0 -415
  196. package/src/execution/engine/engines/pi/reader.ts +0 -48
  197. package/src/execution/engine/engines/pi/registration.ts +0 -35
  198. package/src/execution/engine/engines/pi/task-spec-mapper.ts +0 -100
  199. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +0 -39
  200. package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +0 -150
  201. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +0 -246
  202. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +0 -228
  203. package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +0 -210
  204. package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +0 -64
  205. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +0 -127
  206. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +0 -580
  207. package/src/execution/engine/engines/zcode/constants.ts +0 -43
  208. package/src/execution/engine/engines/zcode/golden-sample.ts +0 -39
  209. package/src/execution/engine/engines/zcode/launcher.ts +0 -161
  210. package/src/execution/engine/engines/zcode/parser.ts +0 -436
  211. package/src/execution/engine/engines/zcode/preparer.ts +0 -363
  212. package/src/execution/engine/engines/zcode/reader.ts +0 -381
  213. package/src/execution/engine/engines/zcode/registration.ts +0 -37
  214. package/src/execution/engine/engines/zcode/zcode-engine.ts +0 -658
  215. package/src/execution/engine/host-task-spec.ts +0 -47
  216. package/src/execution/engine/model-prompt.ts +0 -59
  217. package/src/execution/engine/paths.ts +0 -42
  218. package/src/execution/engine/port.ts +0 -153
  219. package/src/execution/engine/registry.ts +0 -123
  220. package/src/execution/engine/routing.ts +0 -218
  221. package/src/execution/engine/types.ts +0 -309
  222. package/src/execution/execute-options-mapper.ts +0 -112
  223. package/src/execution/execution-record.ts +0 -965
  224. package/src/execution/finalize-record.ts +0 -251
  225. package/src/execution/finalized-marker.ts +0 -51
  226. package/src/execution/get-state-handshake.ts +0 -104
  227. package/src/execution/host-mode.ts +0 -56
  228. package/src/execution/idle-gc.ts +0 -47
  229. package/src/execution/lifecycle-manager.ts +0 -513
  230. package/src/execution/lifecycle-predicates.ts +0 -65
  231. package/src/execution/manifest-store.ts +0 -256
  232. package/src/execution/model-config-service.ts +0 -219
  233. package/src/execution/model-resolver.ts +0 -248
  234. package/src/execution/notifier.ts +0 -330
  235. package/src/execution/notify-ledger.ts +0 -580
  236. package/src/execution/output-collector.ts +0 -228
  237. package/src/execution/path-encoding.ts +0 -60
  238. package/src/execution/pi-invocation.ts +0 -120
  239. package/src/execution/record-entry.ts +0 -132
  240. package/src/execution/record-store.ts +0 -1234
  241. package/src/execution/relay-env.ts +0 -37
  242. package/src/execution/session-context-resolver.ts +0 -64
  243. package/src/execution/session-file-gc.ts +0 -120
  244. package/src/execution/session-pending.ts +0 -164
  245. package/src/execution/session-reconstructor.ts +0 -678
  246. package/src/execution/session-runner.ts +0 -1781
  247. package/src/execution/sessions-index.ts +0 -304
  248. package/src/execution/spawn-event-adapter.ts +0 -363
  249. package/src/execution/stdin-writer.ts +0 -198
  250. package/src/execution/stream-sink.ts +0 -126
  251. package/src/execution/subagent-service.ts +0 -2141
  252. package/src/execution/subprocess-agent-runner.ts +0 -317
  253. package/src/execution/temp-prompt.ts +0 -62
  254. package/src/execution/tombstone-store.ts +0 -72
  255. package/src/execution/turn-limiter.ts +0 -102
  256. package/src/execution/types.ts +0 -973
  257. package/src/execution/ui-channels.ts +0 -216
  258. package/src/execution/ui-interaction-model.ts +0 -48
  259. package/src/execution/ui-request-handler-factory.ts +0 -212
  260. package/src/execution/ui-request-observability.ts +0 -81
  261. package/src/execution/ui-request-queue.ts +0 -184
  262. package/src/execution/worktree-manager.ts +0 -688
  263. package/src/execution/worktree-registry.ts +0 -222
  264. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +0 -349
  265. package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +0 -202
  266. package/src/orchestration/__tests__/agent-call-stream.test.ts +0 -152
  267. package/src/orchestration/__tests__/args-validator.test.ts +0 -143
  268. package/src/orchestration/__tests__/config-loader.test.ts +0 -503
  269. package/src/orchestration/__tests__/error-recovery-handlers.test.ts +0 -809
  270. package/src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts +0 -405
  271. package/src/orchestration/__tests__/error-recovery-serialize-failed-result.test.ts +0 -56
  272. package/src/orchestration/__tests__/error-recovery-workflow-call.test.ts +0 -166
  273. package/src/orchestration/__tests__/execute-agent-call.test.ts +0 -451
  274. package/src/orchestration/__tests__/jsonl-run-store-corrupt-entry.test.ts +0 -150
  275. package/src/orchestration/__tests__/jsonl-run-store-loadall-sources.test.ts +0 -171
  276. package/src/orchestration/__tests__/jsonl-run-store-retention.test.ts +0 -202
  277. package/src/orchestration/__tests__/jsonl-run-store-session-file.test.ts +0 -1030
  278. package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +0 -600
  279. package/src/orchestration/__tests__/lifecycle-runid-injection.test.ts +0 -96
  280. package/src/orchestration/__tests__/lifecycle.test.ts +0 -659
  281. package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +0 -95
  282. package/src/orchestration/__tests__/review-fix-loop-e2e.test.ts +0 -2025
  283. package/src/orchestration/__tests__/script-lint.test.ts +0 -831
  284. package/src/orchestration/__tests__/skill-discovery.test.ts +0 -201
  285. package/src/orchestration/__tests__/test-mocks.ts +0 -197
  286. package/src/orchestration/__tests__/worker-exit-without-result.test.ts +0 -368
  287. package/src/orchestration/__tests__/worker-host.test.ts +0 -120
  288. package/src/orchestration/__tests__/worker-returnmeta-passthrough.test.ts +0 -164
  289. package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +0 -563
  290. package/src/orchestration/__tests__/worker-script-builder.test.ts +0 -309
  291. package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +0 -129
  292. package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +0 -317
  293. package/src/orchestration/__tests__/workflow-script-lint-memo.test.ts +0 -110
  294. package/src/orchestration/__tests__/workflows-e2e.test.ts +0 -537
  295. package/src/orchestration/agent-opts-resolver.ts +0 -174
  296. package/src/orchestration/args-validator.ts +0 -127
  297. package/src/orchestration/config-loader.ts +0 -315
  298. package/src/orchestration/error-recovery.ts +0 -1018
  299. package/src/orchestration/execute-agent-call.ts +0 -256
  300. package/src/orchestration/launcher.ts +0 -455
  301. package/src/orchestration/lifecycle.ts +0 -399
  302. package/src/orchestration/models/__tests__/budget.test.ts +0 -307
  303. package/src/orchestration/models/__tests__/trace.test.ts +0 -408
  304. package/src/orchestration/models/agent-call.ts +0 -83
  305. package/src/orchestration/models/budget.ts +0 -118
  306. package/src/orchestration/models/ports.ts +0 -164
  307. package/src/orchestration/models/run-runtime.ts +0 -104
  308. package/src/orchestration/models/run-spec.ts +0 -83
  309. package/src/orchestration/models/run-state.ts +0 -44
  310. package/src/orchestration/models/trace.ts +0 -183
  311. package/src/orchestration/models/types.ts +0 -301
  312. package/src/orchestration/models/workflow-run.ts +0 -254
  313. package/src/orchestration/models/workflow-script-registry.ts +0 -35
  314. package/src/orchestration/models/workflow-script.ts +0 -117
  315. package/src/orchestration/script-lint.ts +0 -766
  316. package/src/orchestration/skill-discovery.ts +0 -115
  317. package/src/orchestration/worker-handle.ts +0 -115
  318. package/src/orchestration/worker-host.ts +0 -98
  319. package/src/orchestration/worker-script-builder.ts +0 -421
  320. package/src/orchestration/workflow-files.ts +0 -85
  321. package/src/orchestration/workflow-script-registry-impl.ts +0 -133
  322. package/src/shared/__tests__/agent-ref.test.ts +0 -34
  323. package/src/shared/__tests__/meta-parser.test.ts +0 -304
  324. package/src/shared/__tests__/model-ref.test.ts +0 -306
  325. package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +0 -280
  326. package/src/shared/__tests__/resource-discovery.test.ts +0 -736
  327. package/src/shared/__tests__/resource-meta.test.ts +0 -51
  328. package/src/shared/__tests__/schema-jsonify.test.ts +0 -81
  329. package/src/shared/__tests__/timer-delay.test.ts +0 -61
  330. package/src/shared/agent-event.ts +0 -13
  331. package/src/shared/agent-ref.ts +0 -57
  332. package/src/shared/meta-parser.ts +0 -261
  333. package/src/shared/model-ref.ts +0 -286
  334. package/src/shared/resource-discovery.ts +0 -811
  335. package/src/shared/resource-meta.ts +0 -65
  336. package/src/shared/schema-env.ts +0 -44
  337. package/src/shared/schema-jsonify.ts +0 -58
  338. package/src/shared/timer-delay.ts +0 -54
  339. package/src/shared/xml-injection.ts +0 -35
  340. package/workflows/README.md +0 -81
  341. package/workflows/_shared/agent-refs.cjs +0 -40
  342. package/workflows/chain.js +0 -131
  343. package/workflows/map-reduce.js +0 -174
  344. package/workflows/parallel.js +0 -148
  345. package/workflows/review-fix-loop-utils.cjs +0 -1309
  346. package/workflows/review-fix-loop.js +0 -1404
  347. package/workflows/scatter-gather.js +0 -178
@@ -1,736 +0,0 @@
1
- // src/shared/__tests__/resource-discovery.test.ts
2
- //
3
- // 统一资源发现模块测试(ADR-031)。
4
- // 验证:扫描源覆盖、优先级合并、manifest 校验、约定目录 fallback。
5
- import * as fs from "node:fs";
6
- import * as os from "node:os";
7
- import * as path from "node:path";
8
-
9
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
10
-
11
- // 隔离真实用户全局目录:resource-discovery 用 homedir() 推导 user-agents 源
12
- // (~/.agents/agents/),测试环境可能存在真实 agent 文件(如 tech-design-review.md),
13
- // 不 mock 会导致「期望空列表/精确列表」用例被环境污染(2026-08 实测 4 个失败)。
14
- // 用真实 tmpdir 下的子目录作 mock homedir(macOS SIP 禁止 mkdir /nonexistent-*)。
15
- const mockHomeDir = vi.hoisted(() => {
16
- const fs = require("node:fs");
17
- const os = require("node:os");
18
- const path = require("node:path");
19
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "res-disc-home-"));
20
- return dir;
21
- });
22
-
23
- vi.mock("node:os", async (importOriginal) => {
24
- const actual = await importOriginal<typeof import("node:os")>();
25
- return { ...actual, homedir: () => mockHomeDir };
26
- });
27
-
28
- import {
29
- discoverResources,
30
- discoverResourcesSync,
31
- findWorkspaceRoot,
32
- processPackageSync,
33
- getCachedFile,
34
- getCachedFileContent,
35
- __testResetShadowDedup,
36
- __testInjectShadowDedupKey,
37
- isMachineSource,
38
- getCachedParsed,
39
- clearFileCache,
40
- } from "../resource-discovery.ts";
41
- import { getLogger } from "@zhushanwen/pi-extension-logger";
42
-
43
- // ============================================================
44
- // helpers
45
- // ============================================================
46
-
47
- function tmpWorkspace(): string {
48
- return fs.mkdtempSync(path.join(os.tmpdir(), "res-disc-test-"));
49
- }
50
-
51
- function writeFile(dir: string, name: string, content: string): string {
52
- fs.mkdirSync(dir, { recursive: true });
53
- const filePath = path.join(dir, name);
54
- fs.writeFileSync(filePath, content, "utf-8");
55
- return filePath;
56
- }
57
-
58
- function writePackageJson(pkgDir: string, pi: Record<string, unknown>): void {
59
- fs.mkdirSync(pkgDir, { recursive: true });
60
- fs.writeFileSync(
61
- path.join(pkgDir, "package.json"),
62
- JSON.stringify({ name: "test-pkg", pi }),
63
- "utf-8",
64
- );
65
- }
66
-
67
- // ============================================================
68
- // findWorkspaceRoot
69
- // ============================================================
70
-
71
- describe("findWorkspaceRoot", () => {
72
- it("returns cwd when no marker found", () => {
73
- const ws = tmpWorkspace();
74
- expect(findWorkspaceRoot(ws)).toBe(ws);
75
- fs.rmSync(ws, { recursive: true, force: true });
76
- });
77
-
78
- it("finds .git root", () => {
79
- const ws = tmpWorkspace();
80
- fs.mkdirSync(path.join(ws, ".git"));
81
- const sub = path.join(ws, "sub", "deep");
82
- fs.mkdirSync(sub, { recursive: true });
83
- expect(findWorkspaceRoot(sub)).toBe(ws);
84
- fs.rmSync(ws, { recursive: true, force: true });
85
- });
86
- });
87
-
88
- // ============================================================
89
- // discoverResourcesSync — 扫描源覆盖 + 优先级
90
- // ============================================================
91
-
92
- describe("discoverResourcesSync", () => {
93
- let ws: string;
94
- let agentDir: string;
95
-
96
- beforeEach(() => {
97
- ws = tmpWorkspace();
98
- agentDir = path.join(ws, ".fake-agent");
99
- });
100
- afterEach(() => {
101
- fs.rmSync(ws, { recursive: true, force: true });
102
- });
103
-
104
- it("discovers agents from project .pi/agents/", () => {
105
- writeFile(path.join(ws, ".pi", "agents"), "worker.md", "body");
106
- const result = discoverResourcesSync({ kind: "agents", workspaceRoot: ws, agentDir });
107
- // 按 source 过滤断言——用户全局目录(~/.agents/agents/)可能有真实 agent 文件,
108
- // 测试不假设环境为空(2026-08:环境新增 tech-design-review.md 暴露此脆弱性)
109
- const project = result.filter((r) => r.source === "project-pi");
110
- expect(project.map((r) => path.basename(r.path))).toEqual(["worker.md"]);
111
- expect(project[0]?.available).toBe(true);
112
- });
113
-
114
- it("discovers workflows from project .pi/workflows/", () => {
115
- writeFile(path.join(ws, ".pi", "workflows"), "build.js", "const meta={name:'build'};");
116
- const result = discoverResourcesSync({ kind: "workflows", workspaceRoot: ws, agentDir });
117
- expect(result.map((r) => path.basename(r.path))).toEqual(["build.js"]);
118
- });
119
-
120
- it("project .agents overrides project .pi on name clash (priority)", () => {
121
- writeFile(path.join(ws, ".pi", "agents"), "worker.md", "pi-body");
122
- writeFile(path.join(ws, ".agents", "agents"), "worker.md", "agents-body");
123
- const result = discoverResourcesSync({ kind: "agents", workspaceRoot: ws, agentDir });
124
- const project = result.filter((r) => r.source === "project-agents");
125
- expect(project).toHaveLength(1);
126
- expect(project[0]?.source).toBe("project-agents");
127
- });
128
-
129
- it("includes tmp source for workflows when includeTmp=true", () => {
130
- writeFile(path.join(ws, ".pi", "workflows", ".tmp"), "temp.js", "const meta={name:'temp'};");
131
- const result = discoverResourcesSync({
132
- kind: "workflows",
133
- workspaceRoot: ws,
134
- agentDir,
135
- includeTmp: true,
136
- });
137
- expect(result.map((r) => path.basename(r.path))).toEqual(["temp.js"]);
138
- expect(result[0]?.source).toBe("project-pi-tmp");
139
- });
140
-
141
- it("excludes tmp source when includeTmp omitted", () => {
142
- writeFile(path.join(ws, ".pi", "workflows", ".tmp"), "temp.js", "x");
143
- const result = discoverResourcesSync({ kind: "workflows", workspaceRoot: ws, agentDir });
144
- expect(result).toEqual([]);
145
- });
146
-
147
- it("ignores _ prefix and .chain.md files", () => {
148
- const dir = path.join(ws, ".pi", "agents");
149
- writeFile(dir, "real.md", "body");
150
- writeFile(dir, "_skip.md", "ignored");
151
- writeFile(dir, "trace.chain.md", "ignored");
152
- const result = discoverResourcesSync({ kind: "agents", workspaceRoot: ws, agentDir });
153
- const project = result.filter((r) => r.source === "project-pi");
154
- expect(project.map((r) => path.basename(r.path))).toEqual(["real.md"]);
155
- });
156
-
157
- it("nonexistent directories are silently skipped", () => {
158
- const result = discoverResourcesSync({ kind: "agents", workspaceRoot: ws, agentDir });
159
- // 用户全局目录可能有真实文件——只断言 project 源为空
160
- expect(result.filter((r) => r.source === "project-pi" || r.source === "project-agents")).toEqual([]);
161
- });
162
- });
163
-
164
- // ============================================================
165
- // processPackageSync — manifest 校验
166
- // ============================================================
167
-
168
- describe("processPackageSync", () => {
169
- let pkgDir: string;
170
-
171
- beforeEach(() => {
172
- pkgDir = tmpWorkspace();
173
- });
174
- afterEach(() => {
175
- fs.rmSync(pkgDir, { recursive: true, force: true });
176
- });
177
-
178
- it("loads from manifest directory declaration", () => {
179
- writeFile(path.join(pkgDir, "agents"), "worker.md", "body");
180
- writePackageJson(pkgDir, { agents: ["./agents"] });
181
- const result = processPackageSync(pkgDir, "agents");
182
- expect(result).toHaveLength(1);
183
- expect(result[0]?.available).toBe(true);
184
- });
185
-
186
- it("loads from manifest file declaration", () => {
187
- writeFile(pkgDir, "worker.md", "body");
188
- writePackageJson(pkgDir, { agents: ["./worker.md"] });
189
- const result = processPackageSync(pkgDir, "agents");
190
- expect(result).toHaveLength(1);
191
- expect(result[0]?.available).toBe(true);
192
- });
193
-
194
- it("manifest path not exists → available=false, no fallback", () => {
195
- writePackageJson(pkgDir, { agents: ["./nonexistent"] });
196
- const result = processPackageSync(pkgDir, "agents");
197
- expect(result).toHaveLength(1);
198
- expect(result[0]?.available).toBe(false);
199
- // 不 fallback 到约定目录
200
- writeFile(path.join(pkgDir, "agents"), "hidden.md", "body");
201
- const result2 = processPackageSync(pkgDir, "agents");
202
- expect(result2).toHaveLength(1);
203
- expect(result2[0]?.available).toBe(false);
204
- });
205
-
206
- it("no manifest → fallback to convention dir", () => {
207
- writeFile(path.join(pkgDir, "agents"), "worker.md", "body");
208
- // 无 package.json 或无 pi.agents
209
- const result = processPackageSync(pkgDir, "agents");
210
- expect(result).toHaveLength(1);
211
- expect(result[0]?.available).toBe(true);
212
- });
213
-
214
- it("no manifest and no convention dir → empty", () => {
215
- writePackageJson(pkgDir, { extensions: ["./index.ts"] });
216
- const result = processPackageSync(pkgDir, "agents");
217
- expect(result).toEqual([]);
218
- });
219
- });
220
-
221
- // ============================================================
222
- // discoverResources (async) — 基本冒烟
223
- // ============================================================
224
-
225
- describe("discoverResources (async)", () => {
226
- let ws: string;
227
-
228
- beforeEach(() => {
229
- ws = tmpWorkspace();
230
- });
231
- afterEach(() => {
232
- fs.rmSync(ws, { recursive: true, force: true });
233
- __testResetShadowDedup();
234
- });
235
-
236
- it("discovers agents from project .pi/agents/ (async)", async () => {
237
- writeFile(path.join(ws, ".pi", "agents"), "worker.md", "body");
238
- const result = await discoverResources({
239
- kind: "agents",
240
- workspaceRoot: ws,
241
- agentDir: path.join(ws, ".fake-agent"),
242
- });
243
- expect(result).toHaveLength(1);
244
- expect(result[0]?.available).toBe(true);
245
- });
246
-
247
- it("discovers workflows with tmp source (async)", async () => {
248
- writeFile(path.join(ws, ".pi", "workflows"), "build.js", "x");
249
- writeFile(path.join(ws, ".pi", "workflows", ".tmp"), "temp.js", "x");
250
- const result = await discoverResources({
251
- kind: "workflows",
252
- workspaceRoot: ws,
253
- agentDir: path.join(ws, ".fake-agent"),
254
- includeTmp: true,
255
- });
256
- expect(result).toHaveLength(2);
257
- });
258
- });
259
-
260
- // ============================================================
261
- // user-extension-paths (XYZ_EXTENSION_PATHS) — dev-link 扩展发现
262
- // ============================================================
263
-
264
- describe("user-extension-paths (XYZ_EXTENSION_PATHS)", () => {
265
- let ws: string;
266
- let agentDir: string;
267
- let savedEnv: string | undefined;
268
-
269
- beforeEach(() => {
270
- ws = tmpWorkspace();
271
- agentDir = path.join(ws, ".fake-agent");
272
- savedEnv = process.env.XYZ_EXTENSION_PATHS;
273
- });
274
- afterEach(() => {
275
- if (savedEnv === undefined) delete process.env.XYZ_EXTENSION_PATHS;
276
- else process.env.XYZ_EXTENSION_PATHS = savedEnv;
277
- fs.rmSync(ws, { recursive: true, force: true });
278
- __testResetShadowDedup();
279
- });
280
-
281
- it("discovers agents from XYZ_EXTENSION_PATHS via pi.agents manifest", () => {
282
- const pkgDir = path.join(ws, "my-ext");
283
- writePackageJson(pkgDir, { agents: ["./agents"] });
284
- writeFile(path.join(pkgDir, "agents"), "custom.md", "body");
285
- process.env.XYZ_EXTENSION_PATHS = pkgDir;
286
- const result = discoverResourcesSync({ kind: "agents", workspaceRoot: ws, agentDir });
287
- const ext = result.filter((r) => r.source === "user-extension-paths");
288
- expect(ext.map((r) => path.basename(r.path))).toEqual(["custom.md"]);
289
- expect(ext[0]?.source).toBe("user-extension-paths");
290
- });
291
-
292
- it("discovers agents via convention dir (no manifest)", () => {
293
- const pkgDir = path.join(ws, "my-ext");
294
- writeFile(path.join(pkgDir, "agents"), "conv.md", "body");
295
- process.env.XYZ_EXTENSION_PATHS = pkgDir;
296
- const result = discoverResourcesSync({ kind: "agents", workspaceRoot: ws, agentDir });
297
- const ext = result.filter((r) => r.source === "user-extension-paths");
298
- expect(ext.map((r) => path.basename(r.path))).toEqual(["conv.md"]);
299
- expect(ext[0]?.source).toBe("user-extension-paths");
300
- });
301
-
302
- it("multiple paths separated by delimiter", () => {
303
- const pkg1 = path.join(ws, "ext1");
304
- const pkg2 = path.join(ws, "ext2");
305
- writeFile(path.join(pkg1, "agents"), "a1.md", "body");
306
- writeFile(path.join(pkg2, "agents"), "a2.md", "body");
307
- process.env.XYZ_EXTENSION_PATHS = `${pkg1}${path.delimiter}${pkg2}`;
308
- const result = discoverResourcesSync({ kind: "agents", workspaceRoot: ws, agentDir });
309
- const ext = result.filter((r) => r.source === "user-extension-paths");
310
- expect(ext.map((r) => path.basename(r.path)).sort()).toEqual(["a1.md", "a2.md"]);
311
- });
312
-
313
- it("overrides npm on name clash (priority: user-extension-paths > npm)", () => {
314
- const npmPkg = path.join(agentDir, "npm", "node_modules", "test-pkg");
315
- writePackageJson(npmPkg, { agents: ["./agents"] });
316
- writeFile(path.join(npmPkg, "agents"), "shared.md", "npm-body");
317
- const devPkg = path.join(ws, "dev-ext");
318
- writePackageJson(devPkg, { agents: ["./agents"] });
319
- writeFile(path.join(devPkg, "agents"), "shared.md", "dev-body");
320
- process.env.XYZ_EXTENSION_PATHS = devPkg;
321
- const result = discoverResourcesSync({ kind: "agents", workspaceRoot: ws, agentDir });
322
- const shared = result.find((r) => path.basename(r.path) === "shared.md");
323
- expect(shared?.source).toBe("user-extension-paths");
324
- });
325
-
326
- it("project-agents overrides user-extension-paths (project wins)", () => {
327
- const devPkg = path.join(ws, "dev-ext");
328
- writePackageJson(devPkg, { agents: ["./agents"] });
329
- writeFile(path.join(devPkg, "agents"), "x.md", "dev-body");
330
- writeFile(path.join(ws, ".agents", "agents"), "x.md", "project-body");
331
- process.env.XYZ_EXTENSION_PATHS = devPkg;
332
- const result = discoverResourcesSync({ kind: "agents", workspaceRoot: ws, agentDir });
333
- const x = result.find((r) => path.basename(r.path) === "x.md");
334
- expect(x?.source).toBe("project-agents");
335
- });
336
-
337
- it("empty/unset env → no user-extension-paths source", () => {
338
- delete process.env.XYZ_EXTENSION_PATHS;
339
- const result = discoverResourcesSync({ kind: "agents", workspaceRoot: ws, agentDir });
340
- expect(result.filter((r) => r.source === "user-extension-paths")).toEqual([]);
341
- });
342
-
343
- it("async discoverResources also scans user-extension-paths", async () => {
344
- const pkgDir = path.join(ws, "my-ext");
345
- writePackageJson(pkgDir, { agents: ["./agents"] });
346
- writeFile(path.join(pkgDir, "agents"), "async.md", "body");
347
- process.env.XYZ_EXTENSION_PATHS = pkgDir;
348
- const result = await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
349
- const ext = result.filter((r) => r.source === "user-extension-paths");
350
- expect(ext.map((r) => path.basename(r.path))).toEqual(["async.md"]);
351
- expect(ext[0]?.source).toBe("user-extension-paths");
352
- });
353
-
354
- it("async: overrides npm on name clash (priority: user-extension-paths > npm)", async () => {
355
- const npmPkg = path.join(agentDir, "npm", "node_modules", "test-pkg");
356
- writePackageJson(npmPkg, { agents: ["./agents"] });
357
- writeFile(path.join(npmPkg, "agents"), "shared.md", "npm-body");
358
- const devPkg = path.join(ws, "dev-ext");
359
- writePackageJson(devPkg, { agents: ["./agents"] });
360
- writeFile(path.join(devPkg, "agents"), "shared.md", "dev-body");
361
- process.env.XYZ_EXTENSION_PATHS = devPkg;
362
- const result = await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
363
- const shared = result.find((r) => path.basename(r.path) === "shared.md");
364
- expect(shared?.source).toBe("user-extension-paths");
365
- });
366
-
367
- it("async: project-agents overrides user-extension-paths (project wins)", async () => {
368
- const devPkg = path.join(ws, "dev-ext");
369
- writePackageJson(devPkg, { agents: ["./agents"] });
370
- writeFile(path.join(devPkg, "agents"), "x.md", "dev-body");
371
- writeFile(path.join(ws, ".agents", "agents"), "x.md", "project-body");
372
- process.env.XYZ_EXTENSION_PATHS = devPkg;
373
- const result = await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
374
- const x = result.find((r) => path.basename(r.path) === "x.md");
375
- expect(x?.source).toBe("project-agents");
376
- });
377
-
378
- it("async: 4 源混合 fixture——输出序 + 优先级 + 与串行版快照等价", async () => {
379
- // 源优先级低→高:npm < user-extension-paths < project-pi < project-agents
380
- const npmPkg = path.join(agentDir, "npm", "node_modules", "test-pkg");
381
- writePackageJson(npmPkg, { agents: ["./agents"] });
382
- writeFile(path.join(npmPkg, "agents"), "shared.md", "npm-body");
383
- const devPkg = path.join(ws, "dev-ext");
384
- writePackageJson(devPkg, { agents: ["./agents"] });
385
- writeFile(path.join(devPkg, "agents"), "dev.md", "dev-body");
386
- writeFile(path.join(ws, ".pi", "agents"), "pi.md", "pi-body");
387
- writeFile(path.join(ws, ".agents", "agents"), "shared.md", "project-body");
388
- writeFile(path.join(ws, ".agents", "agents"), "proj.md", "proj-body");
389
- process.env.XYZ_EXTENSION_PATHS = devPkg;
390
- const config = { kind: "agents" as const, workspaceRoot: ws, agentDir };
391
-
392
- const asyncResult = await discoverResources(config);
393
-
394
- // 输出序:stem 首次插入位置固定(低优先级源先入 Map),同名后续覆盖值不移位
395
- expect(asyncResult.map((r) => path.basename(r.path))).toEqual([
396
- "shared.md", // 首现于 npm(最低源),位置固定
397
- "dev.md", // user-extension-paths
398
- "pi.md", // project-pi
399
- "proj.md", // project-agents
400
- ]);
401
- // 优先级:shared.md 两源同名,project-agents(高)last-writer-wins
402
- expect(asyncResult.find((r) => path.basename(r.path) === "shared.md")?.source).toBe(
403
- "project-agents",
404
- );
405
- // 快照等价:源级并行 async 版与串行 sync 版输出逐项一致(含序与 source 标签)
406
- expect(asyncResult).toEqual(discoverResourcesSync(config));
407
- });
408
-
409
- it("async: 同名遮蔽时机器源×机器源降 debug 不产生 warn(D8d 分级)", async () => {
410
- const npmPkg = path.join(agentDir, "npm", "node_modules", "test-pkg");
411
- writePackageJson(npmPkg, { agents: ["./agents"] });
412
- const npmFile = writeFile(path.join(npmPkg, "agents"), "dup.md", "npm-body");
413
- const projFile = writeFile(path.join(ws, ".agents", "agents"), "dup.md", "project-body");
414
- const warnSpy = vi.spyOn(getLogger("subagents"), "warn");
415
- const debugSpy = vi.spyOn(getLogger("subagents"), "debug");
416
-
417
- try {
418
- const result = await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
419
-
420
- // 遮蔽仍生效(last-writer-wins 语义不变)
421
- expect(result.find((r) => path.basename(r.path) === "dup.md")?.source).toBe("project-agents");
422
- // npm 与 project-agents 均为机器源 → 降级 debug,不产生 warn
423
- expect(warnSpy).not.toHaveBeenCalled();
424
- expect(debugSpy).toHaveBeenCalledTimes(1);
425
- const [msg, data] = debugSpy.mock.calls[0];
426
- expect(String(msg)).toContain('duplicate agents "dup"');
427
- expect(String(msg)).toContain("project-agents shadows npm");
428
- expect(data).toMatchObject({ shadowed: npmFile, kept: projFile });
429
- } finally {
430
- warnSpy.mockRestore();
431
- debugSpy.mockRestore();
432
- }
433
- });
434
-
435
- it("(a) 机器源×用户源降 debug:npm vs user-pi 不产生 warn", async () => {
436
- // npm 源(机器源)与 user-pi 源(用户源)——任一侧为机器源即降 debug
437
- const npmPkg = path.join(agentDir, "npm", "node_modules", "test-pkg");
438
- writePackageJson(npmPkg, { agents: ["./agents"] });
439
- writeFile(path.join(npmPkg, "agents"), "dup.md", "npm-body");
440
- // user-pi 源 = agentDir/<kind>/(agentDir 是独立于 homedir mock 的入参,
441
- // mockHomeDir 由 vi.hoisted mkdtempSync 创建真实 tmpdir)
442
- writeFile(path.join(agentDir, "agents"), "dup.md", "user-pi-body");
443
- const warnSpy = vi.spyOn(getLogger("subagents"), "warn");
444
- const debugSpy = vi.spyOn(getLogger("subagents"), "debug");
445
-
446
- try {
447
- await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
448
-
449
- expect(warnSpy).not.toHaveBeenCalled();
450
- expect(debugSpy).toHaveBeenCalled();
451
- const [msg] = debugSpy.mock.calls[0];
452
- expect(String(msg)).toContain('duplicate agents "dup"');
453
- } finally {
454
- warnSpy.mockRestore();
455
- debugSpy.mockRestore();
456
- }
457
- });
458
-
459
- it("(a) npm vs user-extension-paths 机器源×机器源降 debug", async () => {
460
- // 两个机器源同名(npm 包 vs XYZ_EXTENSION_PATHS 注入的 dev 包,后者 source 标签为 user-extension-paths)
461
- const npmPkg = path.join(agentDir, "npm", "node_modules", "test-pkg");
462
- writePackageJson(npmPkg, { agents: ["./agents"] });
463
- writeFile(path.join(npmPkg, "agents"), "shared.md", "npm-body");
464
- const devPkg = path.join(ws, "dev-ext");
465
- writePackageJson(devPkg, { agents: ["./agents"] });
466
- writeFile(path.join(devPkg, "agents"), "shared.md", "dev-body");
467
- process.env.XYZ_EXTENSION_PATHS = devPkg;
468
- const warnSpy = vi.spyOn(getLogger("subagents"), "warn");
469
- const debugSpy = vi.spyOn(getLogger("subagents"), "debug");
470
-
471
- try {
472
- await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
473
-
474
- expect(warnSpy).not.toHaveBeenCalled();
475
- expect(debugSpy).toHaveBeenCalled();
476
- } finally {
477
- warnSpy.mockRestore();
478
- debugSpy.mockRestore();
479
- }
480
- });
481
-
482
- it("(b) 双用户源重复产生 warn 且同进程第二次 discoverResources 不重复(去重生效)", async () => {
483
- // user-pi 与 user-agents 都是用户源——需要构造两个源都有同名文件
484
- // user-pi = agentDir/agents/(buildScanTargets 第一个 target)
485
- // user-agents = mockHomeDir/.agents/agents/(vi.hoisted 创建的真实 tmpdir)
486
- const userAgentsDir = path.join(mockHomeDir, ".agents", "agents");
487
- fs.mkdirSync(userAgentsDir, { recursive: true });
488
- try {
489
- // user-pi: agentDir/agents/dup.md
490
- writeFile(path.join(agentDir, "agents"), "dup.md", "user-pi-body");
491
- // user-agents: mockHomeDir/.agents/agents/dup.md
492
- fs.writeFileSync(path.join(userAgentsDir, "dup.md"), "user-agents-body", "utf-8");
493
-
494
- const warnSpy = vi.spyOn(getLogger("subagents"), "warn");
495
-
496
- try {
497
- // 第一次调用——应产生 warn(双用户源)
498
- await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
499
- expect(warnSpy).toHaveBeenCalledTimes(1);
500
- const [msg] = warnSpy.mock.calls[0];
501
- expect(String(msg)).toContain('duplicate agents "dup"');
502
-
503
- // 第二次调用——同进程去重,不再报
504
- warnSpy.mockClear();
505
- await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
506
- expect(warnSpy).not.toHaveBeenCalled();
507
- } finally {
508
- warnSpy.mockRestore();
509
- }
510
- } finally {
511
- fs.rmSync(userAgentsDir, { recursive: true, force: true });
512
- }
513
- });
514
-
515
- it("(c) path 变化(新 key)重新报 warn", async () => {
516
- const userAgentsDir = path.join(mockHomeDir, ".agents", "agents");
517
- fs.mkdirSync(userAgentsDir, { recursive: true });
518
- try {
519
- writeFile(path.join(agentDir, "agents"), "dup.md", "user-pi-body");
520
- fs.writeFileSync(path.join(userAgentsDir, "dup.md"), "user-agents-body", "utf-8");
521
-
522
- const warnSpy = vi.spyOn(getLogger("subagents"), "warn");
523
-
524
- try {
525
- // 第一次调用——报 warn
526
- await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
527
- expect(warnSpy).toHaveBeenCalledTimes(1);
528
-
529
- // 第二次调用——同 key 去重,不报
530
- warnSpy.mockClear();
531
- await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
532
- expect(warnSpy).not.toHaveBeenCalled();
533
-
534
- // 真实 path 变化产生新 key:双用户目录各加一个不同 stem(dup2.md)
535
- // → 新遮蔽对(新 stem 新 path)→ 新 key → 重新报
536
- writeFile(path.join(agentDir, "agents"), "dup2.md", "user-pi-body-2");
537
- fs.writeFileSync(path.join(userAgentsDir, "dup2.md"), "user-agents-body-2", "utf-8");
538
- warnSpy.mockClear();
539
- await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
540
- expect(warnSpy).toHaveBeenCalledTimes(1);
541
- const [newMsg] = warnSpy.mock.calls[0];
542
- expect(String(newMsg)).toContain('duplicate agents "dup2"');
543
- } finally {
544
- warnSpy.mockRestore();
545
- }
546
- } finally {
547
- fs.rmSync(userAgentsDir, { recursive: true, force: true });
548
- }
549
- });
550
-
551
- it("分级穷举:全部 8 个 ResourceSource 的机器/用户归属与 D3 一致", () => {
552
- // 封闭枚举逐值断言,防止未来新增/修改枚举值时分级边界漂移
553
- const machine: ResourceSource[] = ["npm", "npm-dev", "user-extension-paths", "project-pi", "project-pi-tmp", "project-agents"];
554
- const user: ResourceSource[] = ["user-pi", "user-agents"];
555
- for (const s of machine) expect(isMachineSource(s), `${s} 应为机器源`).toBe(true);
556
- for (const s of user) expect(isMachineSource(s), `${s} 应为用户源`).toBe(false);
557
- });
558
-
559
- it("(d) cap 清空行为:超限后 clear 再 add,之前报过的 key 可重新报", async () => {
560
- const userAgentsDir = path.join(mockHomeDir, ".agents", "agents");
561
- fs.mkdirSync(userAgentsDir, { recursive: true });
562
- try {
563
- writeFile(path.join(agentDir, "agents"), "dup.md", "user-pi-body");
564
- fs.writeFileSync(path.join(userAgentsDir, "dup.md"), "user-agents-body", "utf-8");
565
-
566
- const warnSpy = vi.spyOn(getLogger("subagents"), "warn");
567
-
568
- try {
569
- // 步骤 1:首次调用——报 warn,dedup key 加入 set
570
- await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
571
- expect(warnSpy).toHaveBeenCalledTimes(1);
572
- warnSpy.mockClear();
573
-
574
- // 步骤 2:重置 set,注入 1024 个虚拟 key(不含 dedup key)
575
- // 使 set.size = MAX,dedup key 不在 set 中
576
- __testResetShadowDedup();
577
- for (let i = 0; i < 1024; i++) {
578
- __testInjectShadowDedupKey(`fake|key${i}|/a|/b`);
579
- }
580
-
581
- // 步骤 3:第二次调用——dedup key 不在 set → 进 else 分支 →
582
- // size(1024) >= MAX(1024) → clear() → set 空 → add dedup key → warn
583
- await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
584
- expect(warnSpy).toHaveBeenCalledTimes(1);
585
- warnSpy.mockClear();
586
-
587
- // 步骤 4:第三次调用——dedup key 在 set 中 → 去重跳过 warn
588
- await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
589
- expect(warnSpy).not.toHaveBeenCalled();
590
-
591
- // 步骤 5:再次填充到 cap——重置 + 注入 1024 个虚拟 key
592
- // dedup key(步骤 3 add 的)已被 reset 清除
593
- __testResetShadowDedup();
594
- for (let i = 0; i < 1024; i++) {
595
- __testInjectShadowDedupKey(`fake2|key${i}|/a|/b`);
596
- }
597
-
598
- // 步骤 6:第四次调用——cap 再次触发 clear → dedup key 重新报
599
- await discoverResources({ kind: "agents", workspaceRoot: ws, agentDir });
600
- expect(warnSpy).toHaveBeenCalledTimes(1);
601
- } finally {
602
- warnSpy.mockRestore();
603
- __testResetShadowDedup();
604
- }
605
- } finally {
606
- fs.rmSync(userAgentsDir, { recursive: true, force: true });
607
- }
608
- });
609
- });
610
-
611
- // ── m5 TC4/TC5: 统一 mtime 缓存层(P-cache / P-cache-invalidation) ──
612
-
613
- describe("m5: 统一 mtime 缓存层", () => {
614
- it("TC4a: P-cache——文件未变时二次读取命中同一缓存条目(对象引用)", () => {
615
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "m5-cache-"));
616
- const f = path.join(dir, "a.md");
617
- fs.writeFileSync(f, "---\nname: x\ndescription: y\n---\nbody", "utf-8");
618
- try {
619
- // ESM 下 node:fs 不可 spy(vitest 限制)——命中断言用对象引用:
620
- // getCachedFile 命中时返回缓存条目对象本身(非新建)
621
- const first = getCachedFile(f);
622
- const second = getCachedFile(f);
623
- expect(first?.content).toBe("---\nname: x\ndescription: y\n---\nbody");
624
- expect(second).toBe(first); // 同引用 = 命中缓存(未重 read)
625
- } finally {
626
- fs.rmSync(dir, { recursive: true, force: true });
627
- }
628
- });
629
-
630
- it("TC4b: P-cache——两处消费方(getCachedFile/getCachedFileContent)共享同一缓存条目", () => {
631
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "m5-cache2-"));
632
- const f = path.join(dir, "a.md");
633
- fs.writeFileSync(f, "---\nname: x\ndescription: y\n---\nbody", "utf-8");
634
- try {
635
- const a = getCachedFile(f);
636
- const b = getCachedFileContent(f);
637
- // 内容一致性(命中语义由 TC4a 的对象引用断言覆盖——此处验证两 API 一致)
638
- expect(a?.content).toBe(b);
639
- } finally {
640
- fs.rmSync(dir, { recursive: true, force: true });
641
- }
642
- });
643
-
644
- it("TC5: P-cache-invalidation——改内容(mtime 变)后重读新内容;删文件后驱逐", () => {
645
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "m5-cache3-"));
646
- const f = path.join(dir, "a.md");
647
- fs.writeFileSync(f, "v1", "utf-8");
648
- try {
649
- expect(getCachedFileContent(f)).toBe("v1");
650
- fs.writeFileSync(f, "v2", "utf-8");
651
- expect(getCachedFileContent(f)).toBe("v2"); // mtime 变 → 重读
652
- // 删除 → 驱逐(不再返回旧内容)
653
- fs.rmSync(f);
654
- expect(getCachedFileContent(f)).toBeNull();
655
- } finally {
656
- fs.rmSync(dir, { recursive: true, force: true });
657
- }
658
- });
659
- });
660
-
661
- // ── KV-cache 稳定性改造:解析结果缓存 getCachedParsed ──
662
-
663
- describe("getCachedParsed(mtime 级解析缓存)", () => {
664
- beforeEach(() => {
665
- clearFileCache();
666
- });
667
-
668
- it("mtime 未变时 parse 只跑一次(缓存解析结果)", () => {
669
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "parsed-cache-"));
670
- const f = path.join(dir, "a.md");
671
- fs.writeFileSync(f, "---\nname: x\ndescription: y\n---", "utf-8");
672
- try {
673
- const parse = vi.fn((content: string) => (content.includes("name: x") ? "OK" : "BAD"));
674
- const first = getCachedParsed(f, parse);
675
- const second = getCachedParsed(f, parse);
676
- expect(first).toBe("OK");
677
- expect(second).toBe("OK");
678
- expect(parse).toHaveBeenCalledTimes(1); // 第二次命中缓存,不重 parse
679
- } finally {
680
- fs.rmSync(dir, { recursive: true, force: true });
681
- }
682
- });
683
-
684
- it("mtime 变后重新 parse;文件删除后返回 null 并驱逐", () => {
685
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "parsed-cache2-"));
686
- const f = path.join(dir, "a.md");
687
- fs.writeFileSync(f, "v1", "utf-8");
688
- try {
689
- const parse = (content: string) => content;
690
- expect(getCachedParsed(f, parse)).toBe("v1");
691
- fs.writeFileSync(f, "v2", "utf-8");
692
- expect(getCachedParsed(f, parse)).toBe("v2"); // mtime 变 → 重新 parse
693
- fs.rmSync(f);
694
- expect(getCachedParsed(f, parse)).toBeNull(); // 删除 → null
695
- } finally {
696
- fs.rmSync(dir, { recursive: true, force: true });
697
- }
698
- });
699
-
700
- it("clearFileCache 同时清空解析缓存", () => {
701
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "parsed-cache3-"));
702
- const f = path.join(dir, "a.md");
703
- fs.writeFileSync(f, "content", "utf-8");
704
- try {
705
- const parse = vi.fn(() => "OK");
706
- getCachedParsed(f, parse);
707
- clearFileCache();
708
- getCachedParsed(f, parse);
709
- expect(parse).toHaveBeenCalledTimes(2); // 缓存被清 → 重新 parse
710
- } finally {
711
- fs.rmSync(dir, { recursive: true, force: true });
712
- }
713
- });
714
-
715
- it("同一 path 的不同 parse 各自独立缓存(缓存键含 parse 身份,防跨 parse 污染)", () => {
716
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "parsed-cache4-"));
717
- const f = path.join(dir, "a.md");
718
- fs.writeFileSync(f, "shared-content", "utf-8");
719
- try {
720
- // 模拟真实双 parse 场景:parseAgentFrontmatter vs parseWorkflowMeta 对同一
721
- // path(agent 与 workflow 发现源理论上可命中同一路径)各自解析
722
- const parseA = (content: string) => ({ kind: "agent" as const, content });
723
- const parseW = (content: string) => ({ kind: "workflow" as const, len: content.length });
724
- const a1 = getCachedParsed(f, parseA);
725
- // 修复前:缓存键只有 path,这里会命中 parseA 的缓存条目并 as T 断言返回
726
- // {kind:"agent"}——w1 被污染成错误类型
727
- const w1 = getCachedParsed(f, parseW);
728
- const a2 = getCachedParsed(f, parseA);
729
- expect(a1).toEqual({ kind: "agent", content: "shared-content" });
730
- expect(w1).toEqual({ kind: "workflow", len: 14 });
731
- expect(a2).toEqual({ kind: "agent", content: "shared-content" });
732
- } finally {
733
- fs.rmSync(dir, { recursive: true, force: true });
734
- }
735
- });
736
- });