@zhushanwen/subagent-core 0.2.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.
- package/README.md +114 -0
- package/dist/chunk-3VOERJPJ.js +22 -0
- package/dist/chunk-A4IVZWVX.js +31 -0
- package/dist/execution/engine/engines/zcode/constants.cjs +54 -0
- package/dist/execution/engine/engines/zcode/constants.d.cts +31 -0
- package/dist/execution/engine/engines/zcode/constants.d.ts +31 -0
- package/dist/execution/engine/engines/zcode/constants.js +22 -0
- package/dist/execution/engine/engines/zcode/reader.cjs +276 -0
- package/dist/execution/engine/engines/zcode/reader.d.cts +20 -0
- package/dist/execution/engine/engines/zcode/reader.d.ts +20 -0
- package/dist/execution/engine/engines/zcode/reader.js +239 -0
- package/dist/execution/engine/paths.cjs +55 -0
- package/dist/execution/engine/paths.d.cts +8 -0
- package/dist/execution/engine/paths.d.ts +8 -0
- package/dist/execution/engine/paths.js +26 -0
- package/dist/execution/relay-env.cjs +62 -0
- package/dist/execution/relay-env.d.cts +33 -0
- package/dist/execution/relay-env.d.ts +33 -0
- package/dist/execution/relay-env.js +20 -0
- package/dist/index.cjs +1852 -0
- package/dist/index.d.cts +1184 -0
- package/dist/index.d.ts +1184 -0
- package/dist/index.js +1810 -0
- package/dist/types-BxyAidGf.d.cts +875 -0
- package/dist/types-BxyAidGf.d.ts +875 -0
- package/package.json +99 -0
- package/src/__tests__/agent-opts-resolver-schema-prompt.test.ts +142 -0
- package/src/__tests__/append-system-prompt-assembly.test.ts +242 -0
- package/src/__tests__/builtin-workflows-structure.test.ts +180 -0
- package/src/__tests__/derive-closed-display-parity.test.ts +93 -0
- package/src/__tests__/fr4-get-state-handshake.test.ts +125 -0
- package/src/__tests__/fr8-orphan-recovery.test.ts +259 -0
- package/src/__tests__/m2-append-content-probe.test.ts +73 -0
- package/src/__tests__/manifest-store.test.ts +368 -0
- package/src/__tests__/record-store-cache.test.ts +335 -0
- package/src/__tests__/record-store-index.test.ts +560 -0
- package/src/__tests__/record-store-last-line.test.ts +129 -0
- package/src/__tests__/review-fix-loop-script.test.ts +288 -0
- package/src/__tests__/review-fix-loop-utils.test.ts +2377 -0
- package/src/__tests__/robustness-low-batch1.test.ts +286 -0
- package/src/__tests__/robustness-medium-batch1.test.ts +69 -0
- package/src/__tests__/robustness-medium-batch2.test.ts +65 -0
- package/src/__tests__/robustness-medium-batch3.test.ts +30 -0
- package/src/__tests__/robustness-medium-batch4.test.ts +358 -0
- package/src/__tests__/session-runner.test.ts +69 -0
- package/src/__tests__/smoke.test.ts +9 -0
- package/src/__tests__/stream-sink.test.ts +203 -0
- package/src/core/__tests__/host-services.test.ts +144 -0
- package/src/core/__tests__/logger.test.ts +78 -0
- package/src/core/__tests__/notify-ports.test.ts +104 -0
- package/src/core/host-services.ts +97 -0
- package/src/core/logger.ts +47 -0
- package/src/core/notify-ports.ts +126 -0
- package/src/execution/__tests__/__fixtures__/notifier-golden-snapshots.json +53 -0
- package/src/execution/__tests__/__fixtures__/truncline.snapshot.json +1 -0
- package/src/execution/__tests__/agent-result-mapper.test.ts +150 -0
- package/src/execution/__tests__/alive-store.test.ts +147 -0
- package/src/execution/__tests__/ask-user-transit-e2e.test.ts +490 -0
- package/src/execution/__tests__/channel-registry-handshake.test.ts +242 -0
- package/src/execution/__tests__/chat-engine-routing.test.ts +610 -0
- package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +190 -0
- package/src/execution/__tests__/concurrency-pool.test.ts +250 -0
- package/src/execution/__tests__/config.test.ts +302 -0
- package/src/execution/__tests__/delivery-methods.test.ts +424 -0
- package/src/execution/__tests__/dialog-queue.test.ts +299 -0
- package/src/execution/__tests__/epipe-fallback.test.ts +241 -0
- package/src/execution/__tests__/execute-and-await-worktree.test.ts +243 -0
- package/src/execution/__tests__/execute-nesting.test.ts +323 -0
- package/src/execution/__tests__/execute-options-mapper.test.ts +200 -0
- package/src/execution/__tests__/execution-record.test.ts +1394 -0
- package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +171 -0
- package/src/execution/__tests__/finalize-record.test.ts +367 -0
- package/src/execution/__tests__/finalized-marker.test.ts +104 -0
- package/src/execution/__tests__/format-schema-instruction.test.ts +169 -0
- package/src/execution/__tests__/gc-timer.test.ts +184 -0
- package/src/execution/__tests__/get-record-for-action-restart.test.ts +254 -0
- package/src/execution/__tests__/helpers/mock-extension-api.ts +30 -0
- package/src/execution/__tests__/helpers/spawn-mock.ts +242 -0
- package/src/execution/__tests__/host-mode.test.ts +87 -0
- package/src/execution/__tests__/lifecycle-manager-lock.test.ts +211 -0
- package/src/execution/__tests__/lifecycle-manager.test.ts +383 -0
- package/src/execution/__tests__/lifecycle-predicates.test.ts +116 -0
- package/src/execution/__tests__/manifest-parentid.test.ts +117 -0
- package/src/execution/__tests__/model-resolver.test.ts +465 -0
- package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +287 -0
- package/src/execution/__tests__/nested-visibility.test.ts +325 -0
- package/src/execution/__tests__/output-collector.test.ts +358 -0
- package/src/execution/__tests__/path-encoding.test.ts +104 -0
- package/src/execution/__tests__/pi-invocation.test.ts +134 -0
- package/src/execution/__tests__/record-store.test.ts +1057 -0
- package/src/execution/__tests__/records-cwd-isolation.test.ts +91 -0
- package/src/execution/__tests__/recursive-visibility-baseline.test.ts +339 -0
- package/src/execution/__tests__/recursive-visibility-env.test.ts +273 -0
- package/src/execution/__tests__/relay-env.test.ts +42 -0
- package/src/execution/__tests__/resource-policy.test.ts +109 -0
- package/src/execution/__tests__/rpc-mode.test.ts +89 -0
- package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +267 -0
- package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +253 -0
- package/src/execution/__tests__/run-spawn-edges.test.ts +687 -0
- package/src/execution/__tests__/run-spawn-integration.test.ts +933 -0
- package/src/execution/__tests__/run-spawn-resume.test.ts +322 -0
- package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +196 -0
- package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +199 -0
- package/src/execution/__tests__/session-context-resolver.test.ts +167 -0
- package/src/execution/__tests__/session-file-gc.test.ts +293 -0
- package/src/execution/__tests__/session-reconstructor.test.ts +379 -0
- package/src/execution/__tests__/session-runner-epipe.test.ts +178 -0
- package/src/execution/__tests__/session-runner-schema-env.test.ts +350 -0
- package/src/execution/__tests__/spawn-args.test.ts +445 -0
- package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +189 -0
- package/src/execution/__tests__/spawn-event-adapter.test.ts +167 -0
- package/src/execution/__tests__/spawn-worktree-guidance.test.ts +207 -0
- package/src/execution/__tests__/spawned-children.test.ts +92 -0
- package/src/execution/__tests__/start-sync-model-guard.test.ts +150 -0
- package/src/execution/__tests__/stdin-writer.test.ts +462 -0
- package/src/execution/__tests__/stream-sink-retirement.test.ts +261 -0
- package/src/execution/__tests__/subagent-service-abort.test.ts +60 -0
- package/src/execution/__tests__/subagent-service-message-close.test.ts +629 -0
- package/src/execution/__tests__/subagent-service-parent-guard.test.ts +180 -0
- package/src/execution/__tests__/subagent-service.test.ts +788 -0
- package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +310 -0
- package/src/execution/__tests__/subprocess-agent-runner.test.ts +612 -0
- package/src/execution/__tests__/temp-prompt.test.ts +53 -0
- package/src/execution/__tests__/timeout-integration.test.ts +615 -0
- package/src/execution/__tests__/tombstone-store.test.ts +73 -0
- package/src/execution/__tests__/turn-limiter-semantics.test.ts +194 -0
- package/src/execution/__tests__/turn-limiter.test.ts +65 -0
- package/src/execution/__tests__/ui-channels.test.ts +187 -0
- package/src/execution/__tests__/ui-interaction-model.test.ts +67 -0
- package/src/execution/__tests__/ui-request-handler-factory.test.ts +369 -0
- package/src/execution/__tests__/ui-request-handler.test.ts +204 -0
- package/src/execution/__tests__/ui-request-observability.test.ts +113 -0
- package/src/execution/__tests__/ui-request-queue.test.ts +133 -0
- package/src/execution/__tests__/worktree-manager.test.ts +633 -0
- package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +229 -0
- package/src/execution/__tests__/worktree-reconcile.integration.test.ts +181 -0
- package/src/execution/__tests__/worktree-registry.test.ts +199 -0
- package/src/execution/agent-registry.ts +199 -0
- package/src/execution/agent-result-mapper.ts +90 -0
- package/src/execution/alive-store.ts +119 -0
- package/src/execution/argv-mirror.ts +113 -0
- package/src/execution/best-effort.ts +38 -0
- package/src/execution/channel-registry-access.ts +144 -0
- package/src/execution/concurrency-pool.ts +116 -0
- package/src/execution/config.ts +165 -0
- package/src/execution/dialog-queue.ts +330 -0
- package/src/execution/engine/__tests__/common/data-dir.test.ts +78 -0
- package/src/execution/engine/__tests__/common/errors.test.ts +132 -0
- package/src/execution/engine/__tests__/common/event-journal.test.ts +177 -0
- package/src/execution/engine/__tests__/common/kill-chain.test.ts +192 -0
- package/src/execution/engine/__tests__/common/nesting-guard.test.ts +81 -0
- package/src/execution/engine/__tests__/common/persona-router.test.ts +123 -0
- package/src/execution/engine/__tests__/common/pool-manager.test.ts +154 -0
- package/src/execution/engine/__tests__/common/schema-emulation.test.ts +128 -0
- package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +28 -0
- package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +141 -0
- package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +109 -0
- package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +101 -0
- package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +77 -0
- package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +104 -0
- package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +201 -0
- package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +76 -0
- package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +79 -0
- package/src/execution/engine/__tests__/engine-discovery.test.ts +87 -0
- package/src/execution/engine/__tests__/model-prompt.test.ts +197 -0
- package/src/execution/engine/__tests__/paths.test.ts +39 -0
- package/src/execution/engine/__tests__/registry.test.ts +120 -0
- package/src/execution/engine/__tests__/routing.test.ts +231 -0
- package/src/execution/engine/common/data-dir.ts +66 -0
- package/src/execution/engine/common/errors.ts +183 -0
- package/src/execution/engine/common/event-journal.ts +254 -0
- package/src/execution/engine/common/journal-replay.ts +62 -0
- package/src/execution/engine/common/kill-chain.ts +221 -0
- package/src/execution/engine/common/nesting-guard.ts +50 -0
- package/src/execution/engine/common/persona-router.ts +108 -0
- package/src/execution/engine/common/pool-manager.ts +226 -0
- package/src/execution/engine/common/schema-emulation.ts +189 -0
- package/src/execution/engine/common/session-view-projection.ts +51 -0
- package/src/execution/engine/engine-discovery.ts +65 -0
- package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +469 -0
- package/src/execution/engine/engines/pi/__tests__/reader.test.ts +155 -0
- package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +164 -0
- package/src/execution/engine/engines/pi/pi-engine.ts +415 -0
- package/src/execution/engine/engines/pi/reader.ts +48 -0
- package/src/execution/engine/engines/pi/registration.ts +35 -0
- package/src/execution/engine/engines/pi/task-spec-mapper.ts +100 -0
- package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +39 -0
- package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +150 -0
- package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +246 -0
- package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +228 -0
- package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +210 -0
- package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +71 -0
- package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +127 -0
- package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +580 -0
- package/src/execution/engine/engines/zcode/constants.ts +43 -0
- package/src/execution/engine/engines/zcode/golden-sample.ts +39 -0
- package/src/execution/engine/engines/zcode/launcher.ts +161 -0
- package/src/execution/engine/engines/zcode/parser.ts +436 -0
- package/src/execution/engine/engines/zcode/preparer.ts +363 -0
- package/src/execution/engine/engines/zcode/reader.ts +381 -0
- package/src/execution/engine/engines/zcode/registration.ts +37 -0
- package/src/execution/engine/engines/zcode/zcode-engine.ts +658 -0
- package/src/execution/engine/host-task-spec.ts +47 -0
- package/src/execution/engine/model-prompt.ts +158 -0
- package/src/execution/engine/paths.ts +42 -0
- package/src/execution/engine/port.ts +153 -0
- package/src/execution/engine/registry.ts +133 -0
- package/src/execution/engine/routing.ts +218 -0
- package/src/execution/engine/types.ts +309 -0
- package/src/execution/execute-options-mapper.ts +115 -0
- package/src/execution/execution-record.ts +984 -0
- package/src/execution/finalize-record.ts +254 -0
- package/src/execution/finalized-marker.ts +70 -0
- package/src/execution/get-state-handshake.ts +104 -0
- package/src/execution/host-mode.ts +56 -0
- package/src/execution/idle-gc.ts +47 -0
- package/src/execution/lifecycle-manager.ts +513 -0
- package/src/execution/lifecycle-predicates.ts +65 -0
- package/src/execution/manifest-store.ts +256 -0
- package/src/execution/model-config-service.ts +250 -0
- package/src/execution/model-resolver.ts +248 -0
- package/src/execution/notifier.ts +372 -0
- package/src/execution/notify-ledger.ts +580 -0
- package/src/execution/output-collector.ts +228 -0
- package/src/execution/path-encoding.ts +60 -0
- package/src/execution/pi-invocation.ts +120 -0
- package/src/execution/record-entry.ts +132 -0
- package/src/execution/record-store.ts +1265 -0
- package/src/execution/relay-env.ts +37 -0
- package/src/execution/session-context-resolver.ts +64 -0
- package/src/execution/session-file-gc.ts +120 -0
- package/src/execution/session-pending.ts +170 -0
- package/src/execution/session-reconstructor.ts +678 -0
- package/src/execution/session-runner.ts +1789 -0
- package/src/execution/sessions-index.ts +304 -0
- package/src/execution/spawn-event-adapter.ts +363 -0
- package/src/execution/stdin-writer.ts +198 -0
- package/src/execution/stream-sink.ts +126 -0
- package/src/execution/subagent-service.ts +2268 -0
- package/src/execution/subprocess-agent-runner.ts +317 -0
- package/src/execution/temp-prompt.ts +62 -0
- package/src/execution/tombstone-store.ts +72 -0
- package/src/execution/turn-limiter.ts +102 -0
- package/src/execution/types.ts +1023 -0
- package/src/execution/ui-channels.ts +216 -0
- package/src/execution/ui-interaction-model.ts +48 -0
- package/src/execution/ui-request-handler-factory.ts +243 -0
- package/src/execution/ui-request-observability.ts +81 -0
- package/src/execution/ui-request-queue.ts +184 -0
- package/src/execution/worktree-manager.ts +688 -0
- package/src/execution/worktree-registry.ts +279 -0
- package/src/index.ts +87 -0
- package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +349 -0
- package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +202 -0
- package/src/orchestration/__tests__/agent-call-stream.test.ts +152 -0
- package/src/orchestration/__tests__/args-validator.test.ts +143 -0
- package/src/orchestration/__tests__/config-loader.test.ts +503 -0
- package/src/orchestration/__tests__/error-recovery-handlers.test.ts +809 -0
- package/src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts +404 -0
- package/src/orchestration/__tests__/error-recovery-serialize-failed-result.test.ts +56 -0
- package/src/orchestration/__tests__/error-recovery-workflow-call.test.ts +166 -0
- package/src/orchestration/__tests__/execute-agent-call.test.ts +451 -0
- package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +600 -0
- package/src/orchestration/__tests__/lifecycle-runid-injection.test.ts +96 -0
- package/src/orchestration/__tests__/lifecycle.test.ts +659 -0
- package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +95 -0
- package/src/orchestration/__tests__/review-fix-loop-scriptpath-failfast.test.ts +183 -0
- package/src/orchestration/__tests__/script-lint.test.ts +831 -0
- package/src/orchestration/__tests__/skill-discovery.test.ts +210 -0
- package/src/orchestration/__tests__/test-mocks.ts +197 -0
- package/src/orchestration/__tests__/worker-exit-without-result.test.ts +368 -0
- package/src/orchestration/__tests__/worker-host.test.ts +120 -0
- package/src/orchestration/__tests__/worker-returnmeta-passthrough.test.ts +164 -0
- package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +563 -0
- package/src/orchestration/__tests__/worker-script-builder.test.ts +309 -0
- package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +129 -0
- package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +317 -0
- package/src/orchestration/__tests__/workflow-script-lint-memo.test.ts +110 -0
- package/src/orchestration/agent-opts-resolver.ts +174 -0
- package/src/orchestration/args-validator.ts +127 -0
- package/src/orchestration/config-loader.ts +316 -0
- package/src/orchestration/error-recovery.ts +1018 -0
- package/src/orchestration/execute-agent-call.ts +256 -0
- package/src/orchestration/launcher.ts +455 -0
- package/src/orchestration/lifecycle.ts +399 -0
- package/src/orchestration/models/__tests__/budget.test.ts +307 -0
- package/src/orchestration/models/agent-call.ts +83 -0
- package/src/orchestration/models/budget.ts +118 -0
- package/src/orchestration/models/ports.ts +164 -0
- package/src/orchestration/models/run-runtime.ts +104 -0
- package/src/orchestration/models/run-spec.ts +83 -0
- package/src/orchestration/models/run-state.ts +44 -0
- package/src/orchestration/models/trace.ts +183 -0
- package/src/orchestration/models/types.ts +301 -0
- package/src/orchestration/models/workflow-run.ts +254 -0
- package/src/orchestration/models/workflow-script-registry.ts +35 -0
- package/src/orchestration/models/workflow-script.ts +117 -0
- package/src/orchestration/script-lint.ts +766 -0
- package/src/orchestration/skill-discovery.ts +135 -0
- package/src/orchestration/worker-handle.ts +115 -0
- package/src/orchestration/worker-host.ts +98 -0
- package/src/orchestration/worker-script-builder.ts +421 -0
- package/src/orchestration/workflow-files.ts +85 -0
- package/src/orchestration/workflow-script-registry-impl.ts +133 -0
- package/src/shared/__tests__/agent-ref.test.ts +34 -0
- package/src/shared/__tests__/meta-parser.test.ts +304 -0
- package/src/shared/__tests__/model-ref.test.ts +306 -0
- package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +288 -0
- package/src/shared/__tests__/resource-discovery.test.ts +749 -0
- package/src/shared/__tests__/resource-meta.test.ts +51 -0
- package/src/shared/__tests__/schema-jsonify.test.ts +81 -0
- package/src/shared/__tests__/timer-delay.test.ts +61 -0
- package/src/shared/agent-event.ts +13 -0
- package/src/shared/agent-ref.ts +57 -0
- package/src/shared/meta-parser.ts +261 -0
- package/src/shared/model-ref.ts +286 -0
- package/src/shared/resource-discovery.ts +835 -0
- package/src/shared/resource-meta.ts +65 -0
- package/src/shared/schema-env.ts +44 -0
- package/src/shared/schema-jsonify.ts +58 -0
- package/src/shared/timer-delay.ts +54 -0
- package/src/shared/xml-injection.ts +35 -0
- package/workflows/README.md +81 -0
- package/workflows/_shared/agent-refs.cjs +40 -0
- package/workflows/chain.js +137 -0
- package/workflows/map-reduce.js +180 -0
- package/workflows/parallel.js +154 -0
- package/workflows/review-fix-loop-utils.cjs +1542 -0
- package/workflows/review-fix-loop.js +1605 -0
- package/workflows/scatter-gather.js +184 -0
|
@@ -0,0 +1,659 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lifecycle — runWorkflow/abortRun/terminateRunningRuns/scheduleTimeBudget/evict 测试。
|
|
3
|
+
*
|
|
4
|
+
* 用真实 WorkflowRun(含真实状态机 + I1/I2 不变式守卫)+ mock RunRuntime(释放副作用
|
|
5
|
+
* 可控)+ mock LifecycleDeps(store/workerHost/eventBus 可观察)。这样能真正测到
|
|
6
|
+
* transition/assignRuntime/releaseRuntime 的状态机逻辑,而非全 mock 聚合根。
|
|
7
|
+
*
|
|
8
|
+
* 覆盖:
|
|
9
|
+
* - runWorkflow:spec → 创建 run + workerHost.start + store.save + emit pending:register
|
|
10
|
+
* - abortRun:done no-op / running→done + emit pending:unregister
|
|
11
|
+
* - terminateRunningRuns:session 切换/关闭时仅 running 被终止(done,failed 落盘)
|
|
12
|
+
* - scheduleTimeBudget:定时器到期 → abortRun(done,time_limited)(用 fake timers)
|
|
13
|
+
* - evictDoneRunsBeyondCap:done run 内存淘汰白名单/排序/tie
|
|
14
|
+
*/
|
|
15
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
abortRun,
|
|
19
|
+
evictDoneRunsBeyondCap,
|
|
20
|
+
MAX_RETAINED_DONE_RUNS,
|
|
21
|
+
runWorkflow,
|
|
22
|
+
scheduleTimeBudget,
|
|
23
|
+
terminateRunningRuns,
|
|
24
|
+
} from "../lifecycle.ts";
|
|
25
|
+
import { ArgsValidationError } from "../args-validator.ts";
|
|
26
|
+
import { Budget } from "../models/budget.ts";
|
|
27
|
+
import { RunRuntime } from "../models/run-runtime.ts";
|
|
28
|
+
import { Trace } from "../models/trace.ts";
|
|
29
|
+
import type { RunSpec } from "../models/run-spec.ts";
|
|
30
|
+
import type { LifecycleDeps } from "../models/ports.ts";
|
|
31
|
+
import { WorkflowRun } from "../models/workflow-run.ts";
|
|
32
|
+
|
|
33
|
+
// ── helpers ──────────────────────────────────────────────────
|
|
34
|
+
|
|
35
|
+
/** 构造一个最小 RunSpec(满足 WorkflowRun 构造的字段需求)。 */
|
|
36
|
+
function makeSpec(opts: {
|
|
37
|
+
budgetTimeMs?: number;
|
|
38
|
+
budgetTokens?: number;
|
|
39
|
+
parameters?: Record<string, unknown>;
|
|
40
|
+
args?: Record<string, unknown>;
|
|
41
|
+
} = {}): RunSpec {
|
|
42
|
+
return {
|
|
43
|
+
scriptSource: "execute() {}",
|
|
44
|
+
args: opts.args ?? {},
|
|
45
|
+
parameters: opts.parameters,
|
|
46
|
+
scriptName: "test-wf",
|
|
47
|
+
scriptPath: "/fake/test.js",
|
|
48
|
+
budgetTimeMs: opts.budgetTimeMs,
|
|
49
|
+
budgetTokens: opts.budgetTokens,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 构造一个 status="running" 的真实 WorkflowRun,注入 mock RunRuntime。
|
|
55
|
+
*
|
|
56
|
+
* 流程:new WorkflowRun(status=running,I1 构造期跳过)→ assignRuntime
|
|
57
|
+
* (注入 runtime,恢复 I1)。mock runtime 的 worker.terminate / controller.abort /
|
|
58
|
+
* release 均可观察。
|
|
59
|
+
*/
|
|
60
|
+
/** flush microtask 队列多次,让 void .then().catch() + async 链跑完。
|
|
61
|
+
*
|
|
62
|
+
* 注意:fake timers 下 setTimeout(resolve,0) 也会被拦截,故用 Promise.resolve()
|
|
63
|
+
* 走原生 microtask 队列(不被 fake timers 拦截)。 */
|
|
64
|
+
async function flushMicrotasks(times = 10): Promise<void> {
|
|
65
|
+
for (let i = 0; i < times; i++) {
|
|
66
|
+
await Promise.resolve();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function makeRunningRealRun(
|
|
71
|
+
runId: string,
|
|
72
|
+
opts: { budgetTimeMs?: number } = {},
|
|
73
|
+
): { run: WorkflowRun; terminate: ReturnType<typeof vi.fn>; abort: ReturnType<typeof vi.fn> } {
|
|
74
|
+
const spec = makeSpec(opts);
|
|
75
|
+
const run = new WorkflowRun(
|
|
76
|
+
runId,
|
|
77
|
+
spec,
|
|
78
|
+
{
|
|
79
|
+
status: "running",
|
|
80
|
+
budget: new Budget({ maxTokens: 1000 }),
|
|
81
|
+
calls: new Map(),
|
|
82
|
+
trace: new Trace(),
|
|
83
|
+
errorLogs: [],
|
|
84
|
+
},
|
|
85
|
+
{ startedAt: new Date().toISOString() },
|
|
86
|
+
);
|
|
87
|
+
const terminate = vi.fn(async () => {});
|
|
88
|
+
const controller = new AbortController();
|
|
89
|
+
const abort = vi.spyOn(controller, "abort");
|
|
90
|
+
const worker = { terminate, postMessage: vi.fn() } as unknown as Parameters<typeof RunRuntime.prototype.constructor>[0];
|
|
91
|
+
const runtime = new RunRuntime(
|
|
92
|
+
worker as never,
|
|
93
|
+
controller,
|
|
94
|
+
undefined,
|
|
95
|
+
);
|
|
96
|
+
run.assignRuntime(runtime);
|
|
97
|
+
return { run, terminate, abort };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** LifecycleDeps mock:store/workerHost/eventBus/onRunDone/log 可观察。 */
|
|
101
|
+
function makeDeps(): LifecycleDeps & {
|
|
102
|
+
store: { save: ReturnType<typeof vi.fn>; loadAll: ReturnType<typeof vi.fn> };
|
|
103
|
+
workerHost: { start: ReturnType<typeof vi.fn> };
|
|
104
|
+
eventBus: { emit: ReturnType<typeof vi.fn> };
|
|
105
|
+
onRunDone: ReturnType<typeof vi.fn>;
|
|
106
|
+
log: ReturnType<typeof vi.fn>;
|
|
107
|
+
} {
|
|
108
|
+
return {
|
|
109
|
+
store: { save: vi.fn(async () => {}), loadAll: vi.fn(async () => []) },
|
|
110
|
+
workerHost: { start: vi.fn(() => ({ postMessage: vi.fn(), terminate: vi.fn(async () => {}) })) },
|
|
111
|
+
runner: { run: vi.fn(async () => ({})) },
|
|
112
|
+
runs: new Map(),
|
|
113
|
+
eventBus: { emit: vi.fn() },
|
|
114
|
+
onRunDone: vi.fn(),
|
|
115
|
+
log: vi.fn(),
|
|
116
|
+
} as unknown as ReturnType<typeof makeDeps>;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
beforeEach(() => {
|
|
120
|
+
vi.useFakeTimers();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
afterEach(() => {
|
|
124
|
+
vi.useRealTimers();
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
// ── scheduleTimeBudget ───────────────────────────────────────
|
|
128
|
+
|
|
129
|
+
describe("scheduleTimeBudget", () => {
|
|
130
|
+
it("定时器到期 → abortRun(done,time_limited)", async () => {
|
|
131
|
+
const { run } = makeRunningRealRun("wf-budget-1");
|
|
132
|
+
const deps = makeDeps();
|
|
133
|
+
deps.runs.set("wf-budget-1", run);
|
|
134
|
+
|
|
135
|
+
const timer = scheduleTimeBudget("wf-budget-1", deps, 1000);
|
|
136
|
+
expect(timer).toBeDefined();
|
|
137
|
+
|
|
138
|
+
// 推进定时器到到期 + flush 让 abortRun async 链跑完
|
|
139
|
+
await vi.advanceTimersByTimeAsync(1000);
|
|
140
|
+
await flushMicrotasks();
|
|
141
|
+
|
|
142
|
+
expect(run.state.status).toBe("done");
|
|
143
|
+
expect(run.state.reason).toBe("time_limited");
|
|
144
|
+
expect(run.state.error).toContain("Time budget exceeded");
|
|
145
|
+
// 完成通知
|
|
146
|
+
expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:unregister", {
|
|
147
|
+
id: "wf-budget-1",
|
|
148
|
+
reason: "time_limited",
|
|
149
|
+
});
|
|
150
|
+
expect(deps.onRunDone).toHaveBeenCalledTimes(1);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("run 已 done 时 abortRun no-op(到期不重复 transition)", async () => {
|
|
154
|
+
const { run } = makeRunningRealRun("wf-budget-2");
|
|
155
|
+
// 先把 run 转 done(手动)
|
|
156
|
+
run.transition("done", "completed");
|
|
157
|
+
const deps = makeDeps();
|
|
158
|
+
deps.runs.set("wf-budget-2", run);
|
|
159
|
+
|
|
160
|
+
scheduleTimeBudget("wf-budget-2", deps, 500);
|
|
161
|
+
await vi.advanceTimersByTimeAsync(500);
|
|
162
|
+
await flushMicrotasks();
|
|
163
|
+
|
|
164
|
+
// 状态保持原 done/completed,未被 time_limited 覆盖
|
|
165
|
+
expect(run.state.reason).toBe("completed");
|
|
166
|
+
expect(deps.onRunDone).not.toHaveBeenCalled();
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("定时器 unref(不阻止 Node 退出)", () => {
|
|
170
|
+
const deps = makeDeps();
|
|
171
|
+
const timer = scheduleTimeBudget("wf-x", deps, 10000);
|
|
172
|
+
// unref 是 Node timer 的方法,fake timer 也支持——验证不抛错
|
|
173
|
+
expect(() => timer.unref()).not.toThrow();
|
|
174
|
+
timer.unref();
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
// [U1] setTimeout 2^31-1 溢出 fail-fast:溢出 budgetTimeMs 被 Node 置 1ms 立即触发
|
|
178
|
+
//(「不限时预算」变「立即超时」),arm 入口拦截且错误含上限值与恢复指引。
|
|
179
|
+
it("budgetTimeMs 溢出(>2^31-1)→ fail-fast throw(不挂 timer、不静默 clamp)", () => {
|
|
180
|
+
const deps = makeDeps();
|
|
181
|
+
expect(() => scheduleTimeBudget("wf-overflow", deps, 3_000_000_000)).toThrowError(/2147483647/);
|
|
182
|
+
expect(() => scheduleTimeBudget("wf-overflow", deps, Number.MAX_SAFE_INTEGER)).toThrowError(
|
|
183
|
+
/Recovery/,
|
|
184
|
+
);
|
|
185
|
+
});
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
// ── runWorkflow ──────────────────────────────────────────────
|
|
189
|
+
|
|
190
|
+
describe("runWorkflow", () => {
|
|
191
|
+
it("spec → 创建 run + 启动 worker + store.save + emit pending:register", async () => {
|
|
192
|
+
const deps = makeDeps();
|
|
193
|
+
const spec = makeSpec();
|
|
194
|
+
|
|
195
|
+
const runId = await runWorkflow(spec, deps);
|
|
196
|
+
|
|
197
|
+
expect(runId).toMatch(/^wf-/);
|
|
198
|
+
// run 注册到 deps.runs
|
|
199
|
+
expect(deps.runs.has(runId)).toBe(true);
|
|
200
|
+
const run = deps.runs.get(runId)!;
|
|
201
|
+
// status 为 running(assignRuntime 已绑定 runtime)
|
|
202
|
+
expect(run.state.status).toBe("running");
|
|
203
|
+
expect(run.runtime).toBeDefined();
|
|
204
|
+
// workerHost.start 被调
|
|
205
|
+
expect(deps.workerHost.start).toHaveBeenCalledTimes(1);
|
|
206
|
+
// store.save 持久化
|
|
207
|
+
expect(deps.store.save).toHaveBeenCalledTimes(1);
|
|
208
|
+
// pending:register 通知
|
|
209
|
+
expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:register", {
|
|
210
|
+
id: runId,
|
|
211
|
+
type: "workflow",
|
|
212
|
+
name: "test-wf",
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
it("创建即 running:构造即 running,runs.set 在 assignRuntime 后(I1 窗口对外不可见)", async () => {
|
|
217
|
+
const deps = makeDeps();
|
|
218
|
+
// worker.start 被调时探测 runs 注册状态——证明 runs.set 在 assignRuntime 之后
|
|
219
|
+
let runsSizeAtWorkerStart = -1;
|
|
220
|
+
deps.workerHost.start = vi.fn(() => {
|
|
221
|
+
runsSizeAtWorkerStart = deps.runs.size;
|
|
222
|
+
return { postMessage: vi.fn(), terminate: vi.fn(async () => {}) };
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
const runId = await runWorkflow(makeSpec(), deps);
|
|
226
|
+
|
|
227
|
+
// worker.start 执行时 run 尚未注册(I1 跳过窗口不外泄)
|
|
228
|
+
expect(runsSizeAtWorkerStart).toBe(0);
|
|
229
|
+
// 完成后已注册,且构造即 running + runtime 已注入(I1 成立)
|
|
230
|
+
expect(deps.runs.has(runId)).toBe(true);
|
|
231
|
+
const run = deps.runs.get(runId)!;
|
|
232
|
+
expect(run.state.status).toBe("running");
|
|
233
|
+
expect(run.runtime).toBeDefined();
|
|
234
|
+
// save 落盘的是恢复 I1 后的聚合(status running + runtime 已绑定)
|
|
235
|
+
const savedRun = deps.store.save.mock.calls[0]![0] as WorkflowRun;
|
|
236
|
+
expect(savedRun).toBe(run);
|
|
237
|
+
expect(savedRun.state.status).toBe("running");
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it("worker.start 抛错 → runWorkflow 拒绝且 runs 无孤儿注册", async () => {
|
|
241
|
+
const deps = makeDeps();
|
|
242
|
+
deps.workerHost.start = vi.fn(() => {
|
|
243
|
+
throw new Error("worker boot failed");
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
await expect(runWorkflow(makeSpec(), deps)).rejects.toThrow("worker boot failed");
|
|
247
|
+
|
|
248
|
+
// 无孤儿:启动失败时 run 未注册进 deps.runs(runs.set 在 start 之后)
|
|
249
|
+
expect(deps.runs.size).toBe(0);
|
|
250
|
+
expect(deps.store.save).not.toHaveBeenCalled();
|
|
251
|
+
expect(deps.eventBus.emit).not.toHaveBeenCalled();
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it("带 budgetTimeMs 时调度时间预算计时器(真实消费:挂载 + 到期 time_limited)", async () => {
|
|
255
|
+
const deps = makeDeps();
|
|
256
|
+
const spec = makeSpec({ budgetTimeMs: 3000 });
|
|
257
|
+
|
|
258
|
+
const runId = await runWorkflow(spec, deps);
|
|
259
|
+
const run = deps.runs.get(runId)!;
|
|
260
|
+
|
|
261
|
+
// 生产行为面①:budgetTimeMs>0 → RunRuntime.timeBudgetTimer 被真实挂载
|
|
262
|
+
//(scheduleTimeBudget 产出的 Node timer,非死代码 spy)
|
|
263
|
+
expect(run.runtime?.timeBudgetTimer).toBeDefined();
|
|
264
|
+
|
|
265
|
+
// 生产行为面②:到期后 abortRun(time_limited) 真实触发——run 转 done,
|
|
266
|
+
// reason/error/通知全部落位(文件级 beforeEach 已 fake timers)
|
|
267
|
+
await vi.advanceTimersByTimeAsync(3000);
|
|
268
|
+
await flushMicrotasks();
|
|
269
|
+
|
|
270
|
+
expect(run.state.status).toBe("done");
|
|
271
|
+
expect(run.state.reason).toBe("time_limited");
|
|
272
|
+
expect(run.state.error).toContain("Time budget exceeded");
|
|
273
|
+
expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:unregister", {
|
|
274
|
+
id: runId,
|
|
275
|
+
reason: "time_limited",
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it("未传 budgetTimeMs → 不挂时间预算计时器(对照:runtime.timeBudgetTimer undefined)", async () => {
|
|
280
|
+
const deps = makeDeps();
|
|
281
|
+
const runId = await runWorkflow(makeSpec(), deps);
|
|
282
|
+
const run = deps.runs.get(runId)!;
|
|
283
|
+
|
|
284
|
+
expect(run.runtime?.timeBudgetTimer).toBeUndefined();
|
|
285
|
+
|
|
286
|
+
// 无预算 → 不存在到期 abort:推进 10min 后 run 仍 running
|
|
287
|
+
await vi.advanceTimersByTimeAsync(10 * 60 * 1000);
|
|
288
|
+
await flushMicrotasks();
|
|
289
|
+
expect(run.state.status).toBe("running");
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
it("signal 已 abort → fail fast(抛错,不创建 run)", async () => {
|
|
293
|
+
const deps = makeDeps();
|
|
294
|
+
const spec = makeSpec();
|
|
295
|
+
const controller = new AbortController();
|
|
296
|
+
controller.abort();
|
|
297
|
+
|
|
298
|
+
await expect(runWorkflow(spec, deps, controller.signal)).rejects.toThrow(
|
|
299
|
+
"aborted before start",
|
|
300
|
+
);
|
|
301
|
+
expect(deps.runs.size).toBe(0);
|
|
302
|
+
expect(deps.workerHost.start).not.toHaveBeenCalled();
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
it("TC8: 参数校验失败 → throw ArgsValidationError + zero side effects(E9)", async () => {
|
|
306
|
+
const deps = makeDeps();
|
|
307
|
+
const controller = new AbortController();
|
|
308
|
+
const addSpy = vi.spyOn(controller.signal, "addEventListener");
|
|
309
|
+
const spec = makeSpec({
|
|
310
|
+
parameters: {
|
|
311
|
+
type: "object",
|
|
312
|
+
properties: { target: { type: "string" } },
|
|
313
|
+
required: ["target"],
|
|
314
|
+
},
|
|
315
|
+
args: {},
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
await expect(runWorkflow(spec, deps, controller.signal)).rejects.toThrow(ArgsValidationError);
|
|
319
|
+
expect(deps.runs.size).toBe(0);
|
|
320
|
+
expect(deps.workerHost.start).not.toHaveBeenCalled();
|
|
321
|
+
expect(deps.store.save).not.toHaveBeenCalled();
|
|
322
|
+
expect(deps.eventBus.emit).not.toHaveBeenCalled();
|
|
323
|
+
expect(addSpy).not.toHaveBeenCalled();
|
|
324
|
+
expect(deps.log).not.toHaveBeenCalled(); // 校验在 deps.log 前 throw(无日志痕迹)
|
|
325
|
+
});
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
// ── abortRun ─────────────────────────────────────────────────
|
|
329
|
+
|
|
330
|
+
describe("abortRun", () => {
|
|
331
|
+
it("running run → done,aborted:releaseRuntime + emit pending:unregister", async () => {
|
|
332
|
+
const { run, terminate } = makeRunningRealRun("wf-abort-1");
|
|
333
|
+
const deps = makeDeps();
|
|
334
|
+
deps.runs.set("wf-abort-1", run);
|
|
335
|
+
|
|
336
|
+
await abortRun("wf-abort-1", deps, "user cancelled");
|
|
337
|
+
|
|
338
|
+
expect(run.state.status).toBe("done");
|
|
339
|
+
expect(run.state.reason).toBe("aborted");
|
|
340
|
+
expect(run.state.error).toBe("user cancelled");
|
|
341
|
+
expect(terminate).toHaveBeenCalledTimes(1);
|
|
342
|
+
expect(run.runtime).toBeUndefined();
|
|
343
|
+
expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:unregister", {
|
|
344
|
+
id: "wf-abort-1",
|
|
345
|
+
reason: "aborted",
|
|
346
|
+
});
|
|
347
|
+
expect(deps.onRunDone).toHaveBeenCalledTimes(1);
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
it("done 状态 no-op(不重复 abort)", async () => {
|
|
351
|
+
const { run } = makeRunningRealRun("wf-abort-2");
|
|
352
|
+
run.transition("done", "completed");
|
|
353
|
+
const deps = makeDeps();
|
|
354
|
+
deps.runs.set("wf-abort-2", run);
|
|
355
|
+
|
|
356
|
+
await abortRun("wf-abort-2", deps, "late abort");
|
|
357
|
+
|
|
358
|
+
expect(run.state.reason).toBe("completed"); // 未被覆盖
|
|
359
|
+
expect(deps.onRunDone).not.toHaveBeenCalled();
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
it("自定义 doneReason(time_limited)", async () => {
|
|
363
|
+
const { run } = makeRunningRealRun("wf-abort-3");
|
|
364
|
+
const deps = makeDeps();
|
|
365
|
+
deps.runs.set("wf-abort-3", run);
|
|
366
|
+
|
|
367
|
+
await abortRun("wf-abort-3", deps, "timeout", "time_limited");
|
|
368
|
+
|
|
369
|
+
expect(run.state.reason).toBe("time_limited");
|
|
370
|
+
expect(run.state.error).toBe("timeout");
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
it("runId 不存在 → 抛错", async () => {
|
|
374
|
+
const deps = makeDeps();
|
|
375
|
+
await expect(abortRun("wf-missing", deps)).rejects.toThrow("not found");
|
|
376
|
+
});
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
// ── terminateRunningRuns ─────────────────────────────────────
|
|
380
|
+
|
|
381
|
+
describe("terminateRunningRuns", () => {
|
|
382
|
+
it("多 run 中仅 running 被终止(done run 不动)", async () => {
|
|
383
|
+
const { run: running1 } = makeRunningRealRun("wf-term-1");
|
|
384
|
+
const { run: running2 } = makeRunningRealRun("wf-term-2");
|
|
385
|
+
const { run: doneRun } = makeRunningRealRun("wf-term-done");
|
|
386
|
+
doneRun.transition("done", "completed");
|
|
387
|
+
const deps = makeDeps();
|
|
388
|
+
deps.runs.set("wf-term-1", running1);
|
|
389
|
+
deps.runs.set("wf-term-2", running2);
|
|
390
|
+
deps.runs.set("wf-term-done", doneRun);
|
|
391
|
+
|
|
392
|
+
await terminateRunningRuns(deps, "Session switched: run terminated");
|
|
393
|
+
|
|
394
|
+
// running 全部转 done,failed
|
|
395
|
+
expect(running1.state.status).toBe("done");
|
|
396
|
+
expect(running1.state.reason).toBe("failed");
|
|
397
|
+
expect(running2.state.status).toBe("done");
|
|
398
|
+
expect(running2.state.reason).toBe("failed");
|
|
399
|
+
// done run 不被重写(保留 completed)
|
|
400
|
+
expect(doneRun.state.reason).toBe("completed");
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
it("每个被终止的 run 发 pending:unregister(reason=failed)且不调 onRunDone", async () => {
|
|
404
|
+
const { run: r1 } = makeRunningRealRun("wf-term-3");
|
|
405
|
+
const { run: r2 } = makeRunningRealRun("wf-term-4");
|
|
406
|
+
const deps = makeDeps();
|
|
407
|
+
deps.runs.set("wf-term-3", r1);
|
|
408
|
+
deps.runs.set("wf-term-4", r2);
|
|
409
|
+
|
|
410
|
+
await terminateRunningRuns(deps, "Session shutdown: run terminated");
|
|
411
|
+
|
|
412
|
+
expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:unregister", {
|
|
413
|
+
id: "wf-term-3",
|
|
414
|
+
reason: "failed",
|
|
415
|
+
});
|
|
416
|
+
expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:unregister", {
|
|
417
|
+
id: "wf-term-4",
|
|
418
|
+
reason: "failed",
|
|
419
|
+
});
|
|
420
|
+
// 对齐 session_start 恢复先例:主 agent 已离开本 session,不发完成通知
|
|
421
|
+
expect(deps.onRunDone).not.toHaveBeenCalled();
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
it("state.error = reason、reason 字段 = failed、run 落盘(releaseRuntime 解绑 runtime)", async () => {
|
|
425
|
+
const { run, terminate } = makeRunningRealRun("wf-term-5");
|
|
426
|
+
const deps = makeDeps();
|
|
427
|
+
deps.runs.set("wf-term-5", run);
|
|
428
|
+
|
|
429
|
+
await terminateRunningRuns(deps, "Session switched: run terminated");
|
|
430
|
+
|
|
431
|
+
expect(run.state.error).toBe("Session switched: run terminated");
|
|
432
|
+
expect(run.state.reason).toBe("failed");
|
|
433
|
+
expect(run.runtime).toBeUndefined();
|
|
434
|
+
expect(terminate).toHaveBeenCalledTimes(1);
|
|
435
|
+
expect(deps.store.save).toHaveBeenCalledTimes(1);
|
|
436
|
+
expect(deps.store.save).toHaveBeenCalledWith(run);
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
it("单 run save 抛错不中断其余(其余 run 仍落盘 + unregister)", async () => {
|
|
440
|
+
const { run: bad } = makeRunningRealRun("wf-term-err");
|
|
441
|
+
const { run: good } = makeRunningRealRun("wf-term-ok");
|
|
442
|
+
const deps = makeDeps();
|
|
443
|
+
deps.runs.set("wf-term-err", bad);
|
|
444
|
+
deps.runs.set("wf-term-ok", good);
|
|
445
|
+
deps.store.save = vi.fn(async (r: WorkflowRun) => {
|
|
446
|
+
if (r.runId === "wf-term-err") throw new Error("disk full");
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
await terminateRunningRuns(deps, "Session shutdown: run terminated");
|
|
450
|
+
|
|
451
|
+
// 抛错的 run:transition 先于 save,状态已转 done,但 unregister 被 save 失败短路
|
|
452
|
+
expect(bad.state.status).toBe("done");
|
|
453
|
+
expect(bad.state.reason).toBe("failed");
|
|
454
|
+
expect(deps.eventBus.emit).not.toHaveBeenCalledWith("pending:unregister", {
|
|
455
|
+
id: "wf-term-err",
|
|
456
|
+
reason: "failed",
|
|
457
|
+
});
|
|
458
|
+
// 其余 run 正常走完落盘 + unregister(单 run 失败不中断批量终止)
|
|
459
|
+
expect(good.state.status).toBe("done");
|
|
460
|
+
expect(deps.store.save).toHaveBeenCalledWith(good);
|
|
461
|
+
expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:unregister", {
|
|
462
|
+
id: "wf-term-ok",
|
|
463
|
+
reason: "failed",
|
|
464
|
+
});
|
|
465
|
+
});
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
// ── evictDoneRunsBeyondCap ────────────────────────────────────
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* 构造可重水合的 WorkflowRun 快照(对齐 crash-recovery.test.ts makeRun 模式——
|
|
472
|
+
* WorkflowRun.reconstruct 与构造同语义:I1 构造期跳过,running 快照合法)。
|
|
473
|
+
*
|
|
474
|
+
* @param runId run 标识
|
|
475
|
+
* @param opts.completedAt 完成时刻 ISO 串(缺省=缺失场景,模拟旧格式/异常快照)
|
|
476
|
+
* @param opts.status 状态(默认 done;running 用于白名单验证)
|
|
477
|
+
*/
|
|
478
|
+
function makeEvictableRun(
|
|
479
|
+
runId: string,
|
|
480
|
+
opts: { completedAt?: string; status?: "running" | "done" } = {},
|
|
481
|
+
): WorkflowRun {
|
|
482
|
+
const status = opts.status ?? "done";
|
|
483
|
+
return WorkflowRun.reconstruct(
|
|
484
|
+
runId,
|
|
485
|
+
{
|
|
486
|
+
scriptSource: "execute() {}",
|
|
487
|
+
args: {},
|
|
488
|
+
scriptName: "test",
|
|
489
|
+
scriptPath: "/fake/test.js",
|
|
490
|
+
},
|
|
491
|
+
{
|
|
492
|
+
status,
|
|
493
|
+
reason: status === "done" ? "completed" : undefined,
|
|
494
|
+
budget: new Budget({ maxTokens: 1000 }),
|
|
495
|
+
calls: new Map(),
|
|
496
|
+
trace: new Trace(),
|
|
497
|
+
errorLogs: [],
|
|
498
|
+
},
|
|
499
|
+
{
|
|
500
|
+
startedAt: opts.completedAt ?? "2026-08-15T00:00:00.000Z",
|
|
501
|
+
...(opts.completedAt !== undefined ? { completedAt: opts.completedAt } : {}),
|
|
502
|
+
},
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** ISO 基准时刻(过去时刻),isoAt(n) = 基准 + n 分钟。 */
|
|
507
|
+
const EVICT_T0 = Date.parse("2020-01-01T00:00:00.000Z");
|
|
508
|
+
function isoAt(min: number): string {
|
|
509
|
+
return new Date(EVICT_T0 + min * 60_000).toISOString();
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
describe("evictDoneRunsBeyondCap(done run 内存淘汰,K=MAX_RETAINED_DONE_RUNS)", () => {
|
|
513
|
+
it("W3TC1: 状态白名单——仅 done 可淘汰,running 永不删", () => {
|
|
514
|
+
const runs = new Map<string, WorkflowRun>();
|
|
515
|
+
runs.set("wf-done-1", makeEvictableRun("wf-done-1", { completedAt: isoAt(1) }));
|
|
516
|
+
runs.set("wf-done-2", makeEvictableRun("wf-done-2", { completedAt: isoAt(2) }));
|
|
517
|
+
runs.set("wf-done-3", makeEvictableRun("wf-done-3", { completedAt: isoAt(3) }));
|
|
518
|
+
runs.set("wf-run-1", makeEvictableRun("wf-run-1", { status: "running" }));
|
|
519
|
+
runs.set("wf-run-2", makeEvictableRun("wf-run-2", { status: "running" }));
|
|
520
|
+
|
|
521
|
+
const evicted = evictDoneRunsBeyondCap(runs, 2);
|
|
522
|
+
|
|
523
|
+
// 3 done 超保留数 2 → 淘汰最旧 1 个
|
|
524
|
+
expect(evicted).toBe(1);
|
|
525
|
+
// running 全部仍在 Map(白名单外,即使 completedAt 缺失也不参与排序淘汰)
|
|
526
|
+
for (const id of ["wf-run-1", "wf-run-2"]) {
|
|
527
|
+
expect(runs.has(id)).toBe(true);
|
|
528
|
+
}
|
|
529
|
+
// done 仅剩 t2/t3 两个(t1 最旧被淘汰)
|
|
530
|
+
expect(runs.has("wf-done-1")).toBe(false);
|
|
531
|
+
expect(runs.has("wf-done-2")).toBe(true);
|
|
532
|
+
expect(runs.has("wf-done-3")).toBe(true);
|
|
533
|
+
expect(runs.size).toBe(4);
|
|
534
|
+
});
|
|
535
|
+
|
|
536
|
+
it("W3TC2: 按 meta.completedAt 升序淘汰最旧超限项 + 返回淘汰计数(非插入序)", () => {
|
|
537
|
+
const runs = new Map<string, WorkflowRun>();
|
|
538
|
+
// 插入序刻意与 completedAt 序无关:先倒序插入 t24→t0,再 delete+set 重排几个
|
|
539
|
+
// 中段条目(移到 Map 尾部)模拟一般性「完成序≠插入序」——若实现退化为按 Map
|
|
540
|
+
// 迭代首 excess 个淘汰,删的将不是 t0-t4,本用例失败
|
|
541
|
+
for (let i = 24; i >= 0; i--) {
|
|
542
|
+
runs.set(`wf-t${i}`, makeEvictableRun(`wf-t${i}`, { completedAt: isoAt(i) }));
|
|
543
|
+
}
|
|
544
|
+
for (const i of [5, 15, 20]) {
|
|
545
|
+
const run = runs.get(`wf-t${i}`)!;
|
|
546
|
+
runs.delete(`wf-t${i}`);
|
|
547
|
+
runs.set(`wf-t${i}`, run);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
const evicted = evictDoneRunsBeyondCap(runs, MAX_RETAINED_DONE_RUNS);
|
|
551
|
+
|
|
552
|
+
expect(evicted).toBe(5);
|
|
553
|
+
expect(runs.size).toBe(MAX_RETAINED_DONE_RUNS);
|
|
554
|
+
// 被删的恰是 completedAt 最小的 5 个(t0-t4)
|
|
555
|
+
for (let i = 0; i < 5; i++) {
|
|
556
|
+
expect(runs.has(`wf-t${i}`)).toBe(false);
|
|
557
|
+
}
|
|
558
|
+
for (let i = 5; i < 25; i++) {
|
|
559
|
+
expect(runs.has(`wf-t${i}`)).toBe(true);
|
|
560
|
+
}
|
|
561
|
+
});
|
|
562
|
+
|
|
563
|
+
it("W3TC3: 反序 fixture——创建最早、完成最晚的 run 不被淘汰(GAP-1 回归锚点)", () => {
|
|
564
|
+
// 嵌套 workflow 竞态背景:父 run 创建最早(Map 首元素)、完成最晚(completedAt
|
|
565
|
+
// 全局最新)。同 session 累计 21 个 done 时父 run 完成瞬间触发同步裁剪——若按
|
|
566
|
+
// Map 插入序淘汰,父 run 被淘汰,runAndWait 轮询窗口内 get 不到 → 误返
|
|
567
|
+
// "Run not found"。completedAt 排序结构性消除。
|
|
568
|
+
const runs = new Map<string, WorkflowRun>();
|
|
569
|
+
// 插入序 = 创建序:wf-parent 最先插入,completedAt=t100 全局最新(先创建后完成)
|
|
570
|
+
runs.set("wf-parent", makeEvictableRun("wf-parent", { completedAt: isoAt(100) }));
|
|
571
|
+
for (let i = 0; i < 20; i++) {
|
|
572
|
+
// child(i+1) 后插入,completedAt=t0..t19(父 run 之前完成)
|
|
573
|
+
runs.set(`wf-child${i + 1}`, makeEvictableRun(`wf-child${i + 1}`, { completedAt: isoAt(i) }));
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
const evicted = evictDoneRunsBeyondCap(runs, MAX_RETAINED_DONE_RUNS);
|
|
577
|
+
|
|
578
|
+
expect(evicted).toBe(1);
|
|
579
|
+
// 被淘汰的是 child1(completedAt 最旧 t0),非 Map 首元素 wf-parent
|
|
580
|
+
expect(runs.has("wf-child1")).toBe(false);
|
|
581
|
+
expect(runs.has("wf-parent")).toBe(true);
|
|
582
|
+
for (let i = 2; i <= 20; i++) {
|
|
583
|
+
expect(runs.has(`wf-child${i}`)).toBe(true);
|
|
584
|
+
}
|
|
585
|
+
});
|
|
586
|
+
|
|
587
|
+
it("W3TC4: completedAt 缺失 fallback 视为最旧(排序键空串字典序最小)", () => {
|
|
588
|
+
const runs = new Map<string, WorkflowRun>();
|
|
589
|
+
// 插入序 [runC, runA, runB]——缺失者 runA 居中,防「碰巧首元素」假通过
|
|
590
|
+
runs.set("wf-runC", makeEvictableRun("wf-runC", { completedAt: isoAt(2) }));
|
|
591
|
+
runs.set("wf-runA", makeEvictableRun("wf-runA"));
|
|
592
|
+
runs.set("wf-runB", makeEvictableRun("wf-runB", { completedAt: isoAt(1) }));
|
|
593
|
+
|
|
594
|
+
const evicted = evictDoneRunsBeyondCap(runs, 2);
|
|
595
|
+
|
|
596
|
+
// runA 缺失 completedAt = 空串排序键 → 字典序最小=最旧 → 先被淘汰
|
|
597
|
+
expect(evicted).toBe(1);
|
|
598
|
+
expect(runs.has("wf-runA")).toBe(false);
|
|
599
|
+
expect(runs.has("wf-runB")).toBe(true);
|
|
600
|
+
expect(runs.has("wf-runC")).toBe(true);
|
|
601
|
+
});
|
|
602
|
+
|
|
603
|
+
it("W3TC5: tie 稳定排序——同 completedAt 按 Map 插入序确定性淘汰", () => {
|
|
604
|
+
function buildTieFixture(): Map<string, WorkflowRun> {
|
|
605
|
+
const runs = new Map<string, WorkflowRun>();
|
|
606
|
+
const tie = isoAt(50);
|
|
607
|
+
for (const id of ["wf-w1", "wf-w2", "wf-w3", "wf-w4"]) {
|
|
608
|
+
runs.set(id, makeEvictableRun(id, { completedAt: tie }));
|
|
609
|
+
}
|
|
610
|
+
return runs;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
const runs = buildTieFixture();
|
|
614
|
+
const evicted = evictDoneRunsBeyondCap(runs, 2);
|
|
615
|
+
|
|
616
|
+
// tie 组内先插入者视为更旧先被淘汰
|
|
617
|
+
expect(evicted).toBe(2);
|
|
618
|
+
expect(runs.has("wf-w1")).toBe(false);
|
|
619
|
+
expect(runs.has("wf-w2")).toBe(false);
|
|
620
|
+
expect(runs.has("wf-w3")).toBe(true);
|
|
621
|
+
expect(runs.has("wf-w4")).toBe(true);
|
|
622
|
+
|
|
623
|
+
// 确定性:同 fixture 二次运行断言同一淘汰集合
|
|
624
|
+
const runs2 = buildTieFixture();
|
|
625
|
+
const evicted2 = evictDoneRunsBeyondCap(runs2, 2);
|
|
626
|
+
expect(evicted2).toBe(2);
|
|
627
|
+
expect(runs2.has("wf-w1")).toBe(false);
|
|
628
|
+
expect(runs2.has("wf-w2")).toBe(false);
|
|
629
|
+
expect(runs2.has("wf-w3")).toBe(true);
|
|
630
|
+
expect(runs2.has("wf-w4")).toBe(true);
|
|
631
|
+
});
|
|
632
|
+
|
|
633
|
+
it("W3TC6: done 数 <= keepDone 时 no-op 返回 0(恰好 K / 不足 K 两场景)", () => {
|
|
634
|
+
// 场景①:恰好 20 个 done(=K)
|
|
635
|
+
const exact = new Map<string, WorkflowRun>();
|
|
636
|
+
for (let i = 0; i < MAX_RETAINED_DONE_RUNS; i++) {
|
|
637
|
+
exact.set(`wf-ex-${i}`, makeEvictableRun(`wf-ex-${i}`, { completedAt: isoAt(i) }));
|
|
638
|
+
}
|
|
639
|
+
const evictedExact = evictDoneRunsBeyondCap(exact, MAX_RETAINED_DONE_RUNS);
|
|
640
|
+
expect(evictedExact).toBe(0);
|
|
641
|
+
expect(exact.size).toBe(MAX_RETAINED_DONE_RUNS);
|
|
642
|
+
for (let i = 0; i < MAX_RETAINED_DONE_RUNS; i++) {
|
|
643
|
+
expect(exact.has(`wf-ex-${i}`)).toBe(true);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// 场景②:5 个 done(<K)+ 混入 running
|
|
647
|
+
const under = new Map<string, WorkflowRun>();
|
|
648
|
+
for (let i = 0; i < 5; i++) {
|
|
649
|
+
under.set(`wf-un-${i}`, makeEvictableRun(`wf-un-${i}`, { completedAt: isoAt(i) }));
|
|
650
|
+
}
|
|
651
|
+
under.set("wf-un-run", makeEvictableRun("wf-un-run", { status: "running" }));
|
|
652
|
+
const evictedUnder = evictDoneRunsBeyondCap(under, MAX_RETAINED_DONE_RUNS);
|
|
653
|
+
expect(evictedUnder).toBe(0);
|
|
654
|
+
expect(under.size).toBe(6);
|
|
655
|
+
for (const id of ["wf-un-run"]) {
|
|
656
|
+
expect(under.has(id)).toBe(true);
|
|
657
|
+
}
|
|
658
|
+
});
|
|
659
|
+
});
|