@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,171 @@
|
|
|
1
|
+
// 显式 agent ref 失败必须报错(非静默降级)——三通道对称审查修复的 agent 通道验收。
|
|
2
|
+
//
|
|
3
|
+
// 修复背景:resolveIdentity 旧实现 getAgentConfig(loadByPath 无 require)对相对
|
|
4
|
+
// 路径/裸名/文件缺失一律返回 undefined → agentConfig undefined → resolveModel 静默
|
|
5
|
+
// 回落 override→主 agent model——用户点名 agent 却拿到无 systemPrompt/无工具白名单
|
|
6
|
+
// 的 general-purpose 形态,零反馈。修复后显式 ref 失败抛错(require:true 语义,
|
|
7
|
+
// 错误含 <available_subagents> 恢复指引,对齐 workflow name not found 反馈风格)。
|
|
8
|
+
//
|
|
9
|
+
// 本文件锁住:
|
|
10
|
+
// 1. 裸名/相对路径 agent ref → execute 同步 reject(Invalid agent ref),无 spawn、
|
|
11
|
+
// 无子 session、record 不落盘(buildSpawnArgs/spawn/appendEntry 零触达)
|
|
12
|
+
// 2. 绝对路径但文件不存在 → reject(not found or unreadable)
|
|
13
|
+
// 3. 对照:不传 agent(默认 general-purpose)与合法绝对路径 ref 均不误伤
|
|
14
|
+
//
|
|
15
|
+
// harness 复用 start-sync-model-guard.test.ts(真实 SubagentService + tmpdir +
|
|
16
|
+
// mock spawn),保证守卫位于同步裁决期、spawn 前置的结构性证据可断言。
|
|
17
|
+
|
|
18
|
+
import { spawn } from "node:child_process";
|
|
19
|
+
import * as fs from "node:fs";
|
|
20
|
+
import * as os from "node:os";
|
|
21
|
+
import * as path from "node:path";
|
|
22
|
+
|
|
23
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
24
|
+
|
|
25
|
+
vi.mock("node:child_process", async () => {
|
|
26
|
+
const actual = await import("node:child_process");
|
|
27
|
+
return {
|
|
28
|
+
...actual,
|
|
29
|
+
spawn: vi.fn(() => {
|
|
30
|
+
throw new Error("spawn must not be called on agent-ref rejection");
|
|
31
|
+
}),
|
|
32
|
+
};
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
// buildSpawnArgs 包装为 spy(保留真实实现)——「显式 ref 拒单不触达 spawn 参数组装」的承重断言。
|
|
36
|
+
vi.mock("../session-runner.ts", async (importOriginal) => {
|
|
37
|
+
const actual = await importOriginal<typeof import("../session-runner.ts")>();
|
|
38
|
+
return { ...actual, buildSpawnArgs: vi.fn(actual.buildSpawnArgs) };
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
import { ModelConfigService } from "../model-config-service.ts";
|
|
42
|
+
import type { ModelInfo, ModelRegistryLike } from "../model-resolver.ts";
|
|
43
|
+
import { buildSpawnArgs } from "../session-runner.ts";
|
|
44
|
+
import type { PiLike } from "../subagent-service.ts";
|
|
45
|
+
import { SubagentService } from "../subagent-service.ts";
|
|
46
|
+
|
|
47
|
+
const mockSpawn = vi.mocked(spawn);
|
|
48
|
+
const mockBuildSpawnArgs = vi.mocked(buildSpawnArgs);
|
|
49
|
+
|
|
50
|
+
// ── 工具(start-sync-model-guard 同款)──
|
|
51
|
+
|
|
52
|
+
function makeModel(over: Partial<ModelInfo> = {}): ModelInfo {
|
|
53
|
+
return {
|
|
54
|
+
id: over.id ?? "GLM-5.3-Flash",
|
|
55
|
+
name: over.name ?? "GLM 5.3 Flash",
|
|
56
|
+
provider: over.provider ?? "zai-coding-cn",
|
|
57
|
+
reasoning: over.reasoning ?? false,
|
|
58
|
+
...over,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function makeRegistry(models: ModelInfo[]): ModelRegistryLike {
|
|
63
|
+
return {
|
|
64
|
+
getAvailable: () => models,
|
|
65
|
+
find: (provider, modelId) => models.find((m) => m.provider === provider && m.id === modelId),
|
|
66
|
+
hasConfiguredAuth: () => true,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function makePi(): PiLike {
|
|
71
|
+
return {
|
|
72
|
+
appendEntry: vi.fn(),
|
|
73
|
+
events: { emit: vi.fn() },
|
|
74
|
+
sendMessage: vi.fn(),
|
|
75
|
+
} as unknown as PiLike;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
describe("显式 agent ref 失败报错(非静默降级 general-purpose)", () => {
|
|
79
|
+
let tmpDir: string;
|
|
80
|
+
let service: SubagentService;
|
|
81
|
+
let pi: PiLike;
|
|
82
|
+
|
|
83
|
+
beforeEach(() => {
|
|
84
|
+
vi.clearAllMocks();
|
|
85
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "sw-agent-ref-guard-"));
|
|
86
|
+
const modelService = new ModelConfigService({ agentDir: tmpDir, cwd: tmpDir });
|
|
87
|
+
modelService.initModel({
|
|
88
|
+
modelRegistry: makeRegistry([makeModel()]),
|
|
89
|
+
sessionId: "agent-ref-guard-session",
|
|
90
|
+
});
|
|
91
|
+
service = new SubagentService({ cwd: tmpDir, modelService });
|
|
92
|
+
pi = makePi();
|
|
93
|
+
service.initSession({ pi, sessionId: "agent-ref-guard-session" });
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
afterEach(() => {
|
|
97
|
+
vi.restoreAllMocks();
|
|
98
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// ── 拒绝路径:显式 ref 失败 → 同步 reject + spawn 链路零触达 ──
|
|
102
|
+
|
|
103
|
+
it("裸名 agent ref('worker')→ execute 同步 reject(Invalid agent ref + 恢复指引)", async () => {
|
|
104
|
+
await expect(
|
|
105
|
+
service.execute({ task: "probe task", slug: "ref-guard", agent: "worker" }),
|
|
106
|
+
).rejects.toThrow(/Invalid agent ref: worker.*<available_subagents>/s);
|
|
107
|
+
|
|
108
|
+
// spawn 链路零触达 + record 未创建——非静默降级的结构性证据:
|
|
109
|
+
// 旧行为(静默 undefined)会继续走 record 创建(appendEntry 被调)后启动子进程。
|
|
110
|
+
expect(mockBuildSpawnArgs).not.toHaveBeenCalled();
|
|
111
|
+
expect(mockSpawn).not.toHaveBeenCalled();
|
|
112
|
+
expect(pi.appendEntry).not.toHaveBeenCalled();
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("相对路径 agent ref → 同样 reject(引用唯一形态 = 绝对路径)", async () => {
|
|
116
|
+
await expect(
|
|
117
|
+
service.execute({ task: "probe task", slug: "ref-guard", agent: "./agents/worker.md" }),
|
|
118
|
+
).rejects.toThrow(/Invalid agent ref/);
|
|
119
|
+
|
|
120
|
+
expect(mockBuildSpawnArgs).not.toHaveBeenCalled();
|
|
121
|
+
expect(pi.appendEntry).not.toHaveBeenCalled();
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("绝对路径但文件不存在 → reject(not found or unreadable),非静默降级", async () => {
|
|
125
|
+
const missing = path.join(tmpDir, "no-such-agent.md");
|
|
126
|
+
await expect(
|
|
127
|
+
service.execute({ task: "probe task", slug: "ref-guard", agent: missing }),
|
|
128
|
+
).rejects.toThrow(/not found or unreadable.*<available_subagents>/s);
|
|
129
|
+
|
|
130
|
+
expect(mockBuildSpawnArgs).not.toHaveBeenCalled();
|
|
131
|
+
expect(mockSpawn).not.toHaveBeenCalled();
|
|
132
|
+
expect(pi.appendEntry).not.toHaveBeenCalled();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
// ── 放行对照:两类合法语义不误伤 ──
|
|
136
|
+
|
|
137
|
+
it("不传 agent(默认 general-purpose 语义)→ 不触发 agent ref 守卫", async () => {
|
|
138
|
+
const promise = service.execute({
|
|
139
|
+
task: "probe task",
|
|
140
|
+
slug: "ref-default-ok",
|
|
141
|
+
ctxModel: makeModel(),
|
|
142
|
+
});
|
|
143
|
+
// 默认语义下 identity 解析必须放行(execute 可能因 mock 环境子进程收尾而 reject,
|
|
144
|
+
// 但错误不能是 agent ref 拒绝);record 已创建(appendEntry 发生)。
|
|
145
|
+
try {
|
|
146
|
+
await promise;
|
|
147
|
+
} catch (e) {
|
|
148
|
+
expect((e as Error).message).not.toMatch(/Invalid agent ref/);
|
|
149
|
+
expect((e as Error).message).not.toMatch(/not found or unreadable/);
|
|
150
|
+
}
|
|
151
|
+
expect(pi.appendEntry).toHaveBeenCalled();
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it("显式合法绝对路径 agent .md → 守卫零误伤,identity 放行", async () => {
|
|
155
|
+
const agentFile = path.join(tmpDir, "worker.md");
|
|
156
|
+
fs.writeFileSync(agentFile, "You are a test worker agent.");
|
|
157
|
+
const promise = service.execute({
|
|
158
|
+
task: "probe task",
|
|
159
|
+
slug: "ref-valid-ok",
|
|
160
|
+
agent: agentFile,
|
|
161
|
+
ctxModel: makeModel(),
|
|
162
|
+
});
|
|
163
|
+
try {
|
|
164
|
+
await promise;
|
|
165
|
+
} catch (e) {
|
|
166
|
+
expect((e as Error).message).not.toMatch(/Invalid agent ref/);
|
|
167
|
+
expect((e as Error).message).not.toMatch(/not found or unreadable/);
|
|
168
|
+
}
|
|
169
|
+
expect(pi.appendEntry).toHaveBeenCalled();
|
|
170
|
+
});
|
|
171
|
+
});
|
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
// doFinalizeRecord — manifest status 透传测试(M3: 4 态方案)。
|
|
2
|
+
//
|
|
3
|
+
// 验证 finalize-record.ts 的 status 映射:done→completed, failed→failed, cancelled→cancelled
|
|
4
|
+
// (cancelled 不再归并 failed)。crashed 不进 finalize 入参(TS 签名锁定 done/failed/cancelled)。
|
|
5
|
+
//
|
|
6
|
+
// 测试策略:record 不带 sessionFile/worktreeHandle,跳过 Step 0 (collectPatch) 和 Step 3
|
|
7
|
+
// (finalized/tombstone/aliveMarker/worktree cleanup) 的文件操作,聚焦 Step 4 writeManifest
|
|
8
|
+
// 的 status 产出。FinalizeDeps 用 stub 注入(manifestStore 为真实实例,指向 tmpDir)。
|
|
9
|
+
|
|
10
|
+
import * as fs from "node:fs";
|
|
11
|
+
import * as os from "node:os";
|
|
12
|
+
import * as path from "node:path";
|
|
13
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
14
|
+
|
|
15
|
+
// Mock 共享 logger,让 logger.error 可被 spy(源码已从 console.error 改为 logger.error)
|
|
16
|
+
const { loggerMock } = vi.hoisted(() => ({
|
|
17
|
+
loggerMock: {
|
|
18
|
+
debug: vi.fn(),
|
|
19
|
+
warn: vi.fn(),
|
|
20
|
+
error: vi.fn(),
|
|
21
|
+
},
|
|
22
|
+
}));
|
|
23
|
+
vi.mock("../../core/logger.ts", () => ({
|
|
24
|
+
getLogger: () => loggerMock,
|
|
25
|
+
}));
|
|
26
|
+
|
|
27
|
+
import { doFinalizeRecord, doFinalizeRoundToIdle } from "../finalize-record.ts";
|
|
28
|
+
import { ManifestStore } from "../manifest-store.ts";
|
|
29
|
+
import type { AgentResult, ExecutionRecord } from "../types.ts";
|
|
30
|
+
|
|
31
|
+
function makeMinimalRecord(overrides: Partial<ExecutionRecord> = {}): ExecutionRecord {
|
|
32
|
+
return {
|
|
33
|
+
id: "finalize-test",
|
|
34
|
+
agent: "worker",
|
|
35
|
+
model: "test/model",
|
|
36
|
+
thinkingLevel: undefined,
|
|
37
|
+
mode: "background",
|
|
38
|
+
task: "test",
|
|
39
|
+
slug: "test",
|
|
40
|
+
startedAt: 1000,
|
|
41
|
+
rootSessionId: "session-main",
|
|
42
|
+
parentRecordId: undefined,
|
|
43
|
+
depth: 0,
|
|
44
|
+
status: "running",
|
|
45
|
+
turns: [],
|
|
46
|
+
turnCount: 0,
|
|
47
|
+
totalTokens: 0,
|
|
48
|
+
lastError: undefined,
|
|
49
|
+
endedAt: undefined,
|
|
50
|
+
result: undefined,
|
|
51
|
+
error: undefined,
|
|
52
|
+
agentResult: undefined,
|
|
53
|
+
sessionFile: undefined,
|
|
54
|
+
controller: undefined,
|
|
55
|
+
...overrides,
|
|
56
|
+
} as ExecutionRecord;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function makeMinimalResult(): AgentResult {
|
|
60
|
+
return {
|
|
61
|
+
text: "done",
|
|
62
|
+
turns: 1,
|
|
63
|
+
durationMs: 100,
|
|
64
|
+
success: true,
|
|
65
|
+
sessionId: "sess-1",
|
|
66
|
+
toolCalls: [],
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
describe("doFinalizeRecord — manifest status 透传 (M3 4 态)", () => {
|
|
71
|
+
let tmpDir: string;
|
|
72
|
+
let manifestStore: ManifestStore;
|
|
73
|
+
|
|
74
|
+
beforeEach(() => {
|
|
75
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "finalize-test-"));
|
|
76
|
+
manifestStore = new ManifestStore(tmpDir);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
afterEach(() => {
|
|
80
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
/** 构造最小 FinalizeDeps:record 无 sessionFile/worktreeHandle,跳过 Step 0/3 文件操作。 */
|
|
84
|
+
function makeDeps() {
|
|
85
|
+
return {
|
|
86
|
+
manifestStore,
|
|
87
|
+
worktreeManager: {} as never,
|
|
88
|
+
store: { archive: vi.fn(), reportRecordTransition: vi.fn() } as never,
|
|
89
|
+
modelService: {} as never,
|
|
90
|
+
pi: { appendEntry: vi.fn() },
|
|
91
|
+
emitUnregister: vi.fn(),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
it("status=closed + cancelled reason → manifest 写 closed(v4 B-1:cancelled 折入 closed)", async () => {
|
|
96
|
+
const record = makeMinimalRecord({ id: "rec-cancelled" });
|
|
97
|
+
await doFinalizeRecord(makeDeps(), record, makeMinimalResult(), "closed", "cancelled");
|
|
98
|
+
|
|
99
|
+
const manifest = await manifestStore.readManifest("rec-cancelled");
|
|
100
|
+
expect(manifest).not.toBeNull();
|
|
101
|
+
// 关键断言:v4 B-1 manifest status 恒写 closed(cancelled 区分靠 tombstone sidecar)
|
|
102
|
+
expect(manifest?.status).toBe("closed");
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it("status=closed + user-close → manifest 写 closed", async () => {
|
|
106
|
+
const record = makeMinimalRecord({ id: "rec-done" });
|
|
107
|
+
await doFinalizeRecord(makeDeps(), record, makeMinimalResult(), "closed", "user-close");
|
|
108
|
+
|
|
109
|
+
const manifest = await manifestStore.readManifest("rec-done");
|
|
110
|
+
expect(manifest?.status).toBe("closed");
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("status=closed + gc → manifest 写 closed", async () => {
|
|
114
|
+
const record = makeMinimalRecord({ id: "rec-failed" });
|
|
115
|
+
await doFinalizeRecord(makeDeps(), record, makeMinimalResult(), "closed", "gc");
|
|
116
|
+
|
|
117
|
+
const manifest = await manifestStore.readManifest("rec-failed");
|
|
118
|
+
expect(manifest?.status).toBe("closed");
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("manifest write 抛错时 cleanup-first 顺序仍执行(Step 3 before Step 4 throw)", async () => {
|
|
122
|
+
// record 带 sessionFile 让 Step 3 finalized/aliveMarker 走真实路径;
|
|
123
|
+
// 不设 worktreeHandle → Step 0 (collectPatch) 和 Step 3 worktree cleanup 都跳过。
|
|
124
|
+
const sessionFile = path.join(tmpDir, "session.jsonl");
|
|
125
|
+
const record = makeMinimalRecord({ id: "rec-cleanup-first", sessionFile });
|
|
126
|
+
|
|
127
|
+
// 预写 .alive marker(让 removeAliveMarker 真实生效;不预写因 ENOENT 静默也 OK,
|
|
128
|
+
// 但预写后用 fs.existsSync 验证更直观)。
|
|
129
|
+
fs.writeFileSync(
|
|
130
|
+
`${sessionFile}.alive`,
|
|
131
|
+
`${JSON.stringify({ pid: 99999, id: "rec-cleanup-first", startedAt: 1000 })}\n`,
|
|
132
|
+
"utf-8",
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
// mock writeManifest 抛错(模拟 disk full)。在 mock 内捕获「writeManifest 被调用时
|
|
136
|
+
// finalized marker 是否已存在」——这是 cleanup-first 顺序的关键断言:若有人把
|
|
137
|
+
// manifest write 前移到 cleanup 之前,本标志会是 false([Critical #1] 反例)。
|
|
138
|
+
const finalizedBeforeManifestWrite = { value: false };
|
|
139
|
+
vi.spyOn(manifestStore, "writeManifest").mockImplementation(async () => {
|
|
140
|
+
finalizedBeforeManifestWrite.value = fs.existsSync(`${sessionFile}.finalized`);
|
|
141
|
+
throw new Error("disk full");
|
|
142
|
+
});
|
|
143
|
+
loggerMock.error.mockClear();
|
|
144
|
+
|
|
145
|
+
const deps = makeDeps();
|
|
146
|
+
|
|
147
|
+
// ── 核心 claim 1:不抛错(cleanup-first → manifest write 失败不 throw)──
|
|
148
|
+
await expect(
|
|
149
|
+
doFinalizeRecord(deps, record, makeMinimalResult(), "closed"),
|
|
150
|
+
).resolves.toBeUndefined();
|
|
151
|
+
|
|
152
|
+
// ── 核心 claim 2:Step 3 cleanup 先执行 —— finalized marker 真实写入 ──
|
|
153
|
+
expect(fs.existsSync(`${sessionFile}.finalized`)).toBe(true);
|
|
154
|
+
|
|
155
|
+
// ── 核心 claim 3:Step 3 aliveMarker 被移除(预写的 .alive 不再存在)──
|
|
156
|
+
expect(fs.existsSync(`${sessionFile}.alive`)).toBe(false);
|
|
157
|
+
|
|
158
|
+
// ── 核心 claim 4:pending-notifications 注销仍触发(emitUnregister)──
|
|
159
|
+
expect(deps.emitUnregister).toHaveBeenCalledWith("rec-cleanup-first", "closed");
|
|
160
|
+
|
|
161
|
+
// ── 核心 claim 5:manifest 写失败被 logger.error 记录(含 record id + error)──
|
|
162
|
+
expect(loggerMock.error).toHaveBeenCalledWith(expect.stringContaining("manifest 写入失败"));
|
|
163
|
+
const errMsg = loggerMock.error.mock.calls[0]?.[0];
|
|
164
|
+
expect(errMsg).toContain("rec-cleanup-first");
|
|
165
|
+
expect(errMsg).toContain("disk full");
|
|
166
|
+
|
|
167
|
+
// ── 核心 claim 6:pi.appendEntry 记录 "subagent:manifest-write-failed" 事件 ──
|
|
168
|
+
expect(deps.pi.appendEntry).toHaveBeenCalledWith(
|
|
169
|
+
"subagent:manifest-write-failed",
|
|
170
|
+
expect.objectContaining({ id: "rec-cleanup-first", error: "disk full" }),
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
// ── 核心 claim 7:manifest 实际未写入(writeManifest 抛错被吞咽)──
|
|
174
|
+
expect(await manifestStore.readManifest("rec-cleanup-first")).toBeNull();
|
|
175
|
+
|
|
176
|
+
// ── 核心 claim 8:[Critical #1] cleanup 在 manifest 写之前 —— 顺序锁定 ──
|
|
177
|
+
// 若有人把 manifest write 前移到 cleanup 之前,本标志会是 false(mock 捕获时刻
|
|
178
|
+
// .finalized 尚未被 Step 3 写入),保护 Critical #1 时序不变量。
|
|
179
|
+
expect(finalizedBeforeManifestWrite.value).toBe(true);
|
|
180
|
+
|
|
181
|
+
// 清理 mock 调用记录防污染
|
|
182
|
+
loggerMock.error.mockClear();
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
// ============================================================
|
|
187
|
+
// doFinalizeRoundToIdle — chatMode 轮次完成进 idle(M2-A)
|
|
188
|
+
// ============================================================
|
|
189
|
+
|
|
190
|
+
describe("doFinalizeRoundToIdle — chatMode 轮次完成进 idle (M2-A)", () => {
|
|
191
|
+
let tmpDir: string;
|
|
192
|
+
let manifestStore: ManifestStore;
|
|
193
|
+
|
|
194
|
+
beforeEach(() => {
|
|
195
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "finalize-idle-test-"));
|
|
196
|
+
manifestStore = new ManifestStore(tmpDir);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
afterEach(() => {
|
|
200
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
/** 构造 FinalizeDeps:worktreeManager.cleanup / store.archive 为 vi.fn 以断言「不调」。 */
|
|
204
|
+
function makeDeps() {
|
|
205
|
+
return {
|
|
206
|
+
manifestStore,
|
|
207
|
+
worktreeManager: { cleanup: vi.fn(), collectPatch: vi.fn() } as never,
|
|
208
|
+
store: { archive: vi.fn(), reportRecordTransition: vi.fn() } as never,
|
|
209
|
+
modelService: {} as never,
|
|
210
|
+
pi: { appendEntry: vi.fn() } as never,
|
|
211
|
+
emitUnregister: vi.fn(),
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
it("record 带 sessionFile → 删 .alive + record.status=running + round 0→1", async () => {
|
|
216
|
+
const sessionFile = path.join(tmpDir, "session.jsonl");
|
|
217
|
+
// 预写 .alive marker(验证 doFinalizeRoundToIdle 删除它——进程已回收)
|
|
218
|
+
fs.writeFileSync(
|
|
219
|
+
`${sessionFile}.alive`,
|
|
220
|
+
`${JSON.stringify({ pid: 99999, id: "rec-idle", startedAt: 1000 })}\n`,
|
|
221
|
+
"utf-8",
|
|
222
|
+
);
|
|
223
|
+
const record = makeMinimalRecord({ id: "rec-idle", sessionFile, chatMode: true, round: 0 });
|
|
224
|
+
// tryTransition 已把 status 设为 done,模拟 runAndFinalize 调用前的状态
|
|
225
|
+
record.status = "closed";
|
|
226
|
+
|
|
227
|
+
await doFinalizeRoundToIdle(makeDeps(), record, makeMinimalResult());
|
|
228
|
+
|
|
229
|
+
// 状态机(v4 B-1:旧 idle 折入 running,finalizeRoundToIdle 设 running)
|
|
230
|
+
expect(record.status).toBe("running");
|
|
231
|
+
expect(record.round).toBe(1);
|
|
232
|
+
// .alive marker 被删(进程已 SIGTERM 回收)
|
|
233
|
+
expect(fs.existsSync(`${sessionFile}.alive`)).toBe(false);
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
it("W16: 轮终上报 reportRecordTransition(record-store 类外恢复写点迁移落 entry)", async () => {
|
|
237
|
+
const deps = makeDeps();
|
|
238
|
+
const record = makeMinimalRecord({ id: "rec-report", chatMode: true, round: 2 });
|
|
239
|
+
record.status = "closed";
|
|
240
|
+
await doFinalizeRoundToIdle(deps, record, makeMinimalResult());
|
|
241
|
+
expect(deps.store.reportRecordTransition).toHaveBeenCalledTimes(1);
|
|
242
|
+
// 上报发生在 round 推进之后(entry 携带新轮计数,重建源不滞后)
|
|
243
|
+
expect(record.round).toBe(3);
|
|
244
|
+
expect(record.status).toBe("running");
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
it("record.round 已为 N → round 变 N+1", async () => {
|
|
248
|
+
const record = makeMinimalRecord({ id: "rec-round", round: 3 });
|
|
249
|
+
record.status = "closed";
|
|
250
|
+
await doFinalizeRoundToIdle(makeDeps(), record, makeMinimalResult());
|
|
251
|
+
expect(record.round).toBe(4);
|
|
252
|
+
expect(record.status).toBe("running");
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
it("不调 store.archive(record 留内存,getMutable 仍可查)", async () => {
|
|
256
|
+
const deps = makeDeps();
|
|
257
|
+
const record = makeMinimalRecord({ id: "rec-noarchive" });
|
|
258
|
+
record.status = "closed";
|
|
259
|
+
await doFinalizeRoundToIdle(deps, record, makeMinimalResult());
|
|
260
|
+
expect(deps.store.archive).not.toHaveBeenCalled();
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
it("不 cleanup worktree(即使 record 带 worktreeHandle——保留对话模式工作目录)", async () => {
|
|
264
|
+
const deps = makeDeps();
|
|
265
|
+
const record = makeMinimalRecord({
|
|
266
|
+
id: "rec-noworktree",
|
|
267
|
+
worktreeHandle: { path: "/tmp/x", branch: "b", baseCommit: "c", mainCwd: "/tmp" } as never,
|
|
268
|
+
});
|
|
269
|
+
record.status = "closed";
|
|
270
|
+
await doFinalizeRoundToIdle(deps, record, makeMinimalResult());
|
|
271
|
+
expect(deps.worktreeManager.cleanup).not.toHaveBeenCalled();
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
it("emitUnregister 被调(status=running,进程已死从 pending 活跃差集移除)", async () => {
|
|
275
|
+
const deps = makeDeps();
|
|
276
|
+
const record = makeMinimalRecord({ id: "rec-emit" });
|
|
277
|
+
record.status = "closed";
|
|
278
|
+
await doFinalizeRoundToIdle(deps, record, makeMinimalResult());
|
|
279
|
+
expect(deps.emitUnregister).toHaveBeenCalledWith("rec-emit", "running");
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
it("不调 completeRecord:record 不冻结(endedAt / agentResult 仍 undefined)", async () => {
|
|
283
|
+
const record = makeMinimalRecord({ id: "rec-nofreeze" });
|
|
284
|
+
record.status = "closed";
|
|
285
|
+
await doFinalizeRoundToIdle(makeDeps(), record, makeMinimalResult());
|
|
286
|
+
expect(record.endedAt).toBeUndefined();
|
|
287
|
+
expect(record.agentResult).toBeUndefined();
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
it("不写 manifest(idle 非终态,manifest 是终态诊断辅助)", async () => {
|
|
291
|
+
const record = makeMinimalRecord({ id: "rec-nomanifest" });
|
|
292
|
+
record.status = "closed";
|
|
293
|
+
await doFinalizeRoundToIdle(makeDeps(), record, makeMinimalResult());
|
|
294
|
+
const manifest = await manifestStore.readManifest("rec-nomanifest");
|
|
295
|
+
expect(manifest).toBeNull();
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
it("MF-2: record.result 设为 result.text(否则 notifier idle 回复恒为 (empty),G1/G2 不成立)", async () => {
|
|
299
|
+
const record = makeMinimalRecord({ id: "rec-result" });
|
|
300
|
+
record.status = "closed";
|
|
301
|
+
const result = makeMinimalResult();
|
|
302
|
+
result.text = "review done, found 3 issues";
|
|
303
|
+
await doFinalizeRoundToIdle(makeDeps(), record, result);
|
|
304
|
+
// MF-2:record.result 被 result.text 填充,notifier idle 分支读取后携带回复正文
|
|
305
|
+
expect(record.result).toBe("review done, found 3 issues");
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
it("MF-2 兑底:失败轮次 result.text 为空时用 result.error 填 record.result(MF-6 回退 idle 路径)", async () => {
|
|
309
|
+
const record = makeMinimalRecord({ id: "rec-result-err" });
|
|
310
|
+
record.status = "closed";
|
|
311
|
+
const result = makeMinimalResult();
|
|
312
|
+
result.text = "";
|
|
313
|
+
result.success = false;
|
|
314
|
+
result.error = "spawn timeout";
|
|
315
|
+
await doFinalizeRoundToIdle(makeDeps(), record, result);
|
|
316
|
+
// 失败轮次的 notify 需可读:result.text 空 → 兑底用 error
|
|
317
|
+
expect(record.result).toBe("round did not complete: spawn timeout");
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
it("C1TC10: chatMode 空增量轮占位——record.result 固定 (no output this round),不含上一轮文本(D5)", async () => {
|
|
321
|
+
const record = makeMinimalRecord({ id: "rec-increment-empty", chatMode: true });
|
|
322
|
+
record.status = "closed";
|
|
323
|
+
// 预置上一轮通知文本(模拟增量语义前的 record.result 残留)
|
|
324
|
+
record.result = "PREV-ROUND-TEXT";
|
|
325
|
+
const result = makeMinimalResult();
|
|
326
|
+
result.text = "";
|
|
327
|
+
result.success = true;
|
|
328
|
+
result.error = undefined;
|
|
329
|
+
await doFinalizeRoundToIdle(makeDeps(), record, result);
|
|
330
|
+
// 空增量轮通知不含上一轮文本:沿用旧值会让父 agent 误读为原样重复回复(D5 判定)
|
|
331
|
+
expect(record.result).toBe("(no output this round)");
|
|
332
|
+
expect(record.result).not.toContain("PREV-ROUND-TEXT");
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
it("C1TC11 [R2-1]: one-shot 首轮空文本成功完成 → record.result 补占位「(empty)」(非 undefined)", async () => {
|
|
336
|
+
const record = makeMinimalRecord({ id: "rec-oneshot-empty", chatMode: false });
|
|
337
|
+
record.status = "closed";
|
|
338
|
+
// one-shot 成功空文本完成路径(collectResult getFullText 返回 ""、success=true):
|
|
339
|
+
// result 前值 undefined
|
|
340
|
+
record.result = undefined;
|
|
341
|
+
const result = makeMinimalResult();
|
|
342
|
+
result.text = "";
|
|
343
|
+
result.success = true;
|
|
344
|
+
result.error = undefined;
|
|
345
|
+
await doFinalizeRoundToIdle(makeDeps(), record, result);
|
|
346
|
+
// [R2-1] 轮终信号优先:占位非 undefined 是 renderer hasRunning 排除轮终 running 的
|
|
347
|
+
// 判据——保持 undefined 会让完成注入后末位 turn 永久「工作中」
|
|
348
|
+
expect(record.result).toBe("(empty)");
|
|
349
|
+
// notifier buildLlmContent 的 record.result ?? "(empty)" 兜底同款措辞:
|
|
350
|
+
// 通知文案逐字节产出 "completed. Result:\n(empty)"(G4 保持)
|
|
351
|
+
expect(record.result ?? "(empty)").toBe("(empty)");
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
it("C1TC11b [R2-1]: one-shot 续轮空文本 → 沿用前值(one-shot 无增量语义,不覆盖为占位)", async () => {
|
|
355
|
+
const record = makeMinimalRecord({ id: "rec-oneshot-cont", chatMode: false });
|
|
356
|
+
record.status = "closed";
|
|
357
|
+
// 上一轮真实产出(续轮 record.result 前值)
|
|
358
|
+
record.result = "first round output";
|
|
359
|
+
const result = makeMinimalResult();
|
|
360
|
+
result.text = "";
|
|
361
|
+
result.success = true;
|
|
362
|
+
result.error = undefined;
|
|
363
|
+
await doFinalizeRoundToIdle(makeDeps(), record, result);
|
|
364
|
+
// one-shot record.result = 该 subagent 最终输出:空文本续轮沿用前值,不被 "(empty)" 覆盖
|
|
365
|
+
expect(record.result).toBe("first round output");
|
|
366
|
+
});
|
|
367
|
+
});
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// src/__tests__/finalized-marker.test.ts
|
|
2
|
+
//
|
|
3
|
+
// finalized-marker 专属测试。
|
|
4
|
+
// 覆盖:write→read 往返 / 缺 sidecar → false / best-effort IO 错静默 / .cancelled 互斥。
|
|
5
|
+
|
|
6
|
+
import * as fs from "node:fs";
|
|
7
|
+
import * as os from "node:os";
|
|
8
|
+
import * as path from "node:path";
|
|
9
|
+
|
|
10
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
11
|
+
|
|
12
|
+
import { readFinalized, readFinalizedReason, writeFinalized } from "../finalized-marker.ts";
|
|
13
|
+
|
|
14
|
+
describe("finalized-marker", () => {
|
|
15
|
+
let tmpDir: string;
|
|
16
|
+
let sessionFile: string;
|
|
17
|
+
|
|
18
|
+
beforeEach(() => {
|
|
19
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "fm-test-"));
|
|
20
|
+
sessionFile = path.join(tmpDir, "2026-01-01_uuid.jsonl");
|
|
21
|
+
});
|
|
22
|
+
afterEach(() => {
|
|
23
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
describe("write → read 往返", () => {
|
|
27
|
+
it("写入后 readFinalized 返回 true", () => {
|
|
28
|
+
writeFinalized(sessionFile);
|
|
29
|
+
expect(readFinalized(sessionFile)).toBe(true);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("sidecar 路径 = sessionFile + '.finalized'", () => {
|
|
33
|
+
writeFinalized(sessionFile);
|
|
34
|
+
expect(fs.existsSync(`${sessionFile}.finalized`)).toBe(true);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("sidecar 内容为空(无 reason 时保持旧格式兼容)", () => {
|
|
38
|
+
writeFinalized(sessionFile);
|
|
39
|
+
const content = fs.readFileSync(`${sessionFile}.finalized`, "utf-8");
|
|
40
|
+
expect(content).toBe("");
|
|
41
|
+
expect(readFinalizedReason(sessionFile)).toBe("");
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// [v8.5 A2] 携带真实 closedReason 写入 → 读取返回原值(trim 后)
|
|
45
|
+
it("带 reason 写入 → readFinalizedReason 返回原值", () => {
|
|
46
|
+
writeFinalized(sessionFile, "user-close");
|
|
47
|
+
expect(readFinalized(sessionFile)).toBe(true);
|
|
48
|
+
expect(readFinalizedReason(sessionFile)).toBe("user-close");
|
|
49
|
+
|
|
50
|
+
writeFinalized(sessionFile, "parent-shutdown");
|
|
51
|
+
expect(readFinalizedReason(sessionFile)).toBe("parent-shutdown");
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("带 reason 的内容含首尾空白时 trim 后返回", () => {
|
|
55
|
+
fs.writeFileSync(`${sessionFile}.finalized`, " gc \n", "utf-8");
|
|
56
|
+
expect(readFinalizedReason(sessionFile)).toBe("gc");
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
describe("readFinalizedReason 无 sidecar", () => {
|
|
61
|
+
it("不存在 → undefined(与「存在但空串」区分)", () => {
|
|
62
|
+
expect(readFinalizedReason(sessionFile)).toBeUndefined();
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
describe("readFinalized 无 sidecar", () => {
|
|
67
|
+
it("不存在 → false", () => {
|
|
68
|
+
expect(readFinalized(sessionFile)).toBe(false);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
describe("best-effort IO 错静默", () => {
|
|
73
|
+
it("writeFileSync 抛错时不抛出", () => {
|
|
74
|
+
// 目标路径不存在(不存在的父目录),writeFileSync 会抛
|
|
75
|
+
const badPath = path.join(tmpDir, "nonexistent-sub", "session.jsonl");
|
|
76
|
+
expect(() => writeFinalized(badPath)).not.toThrow();
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("写失败后 readFinalized 返回 false(sidecar 未写入)", () => {
|
|
80
|
+
const badPath = path.join(tmpDir, "nonexistent-sub", "session.jsonl");
|
|
81
|
+
writeFinalized(badPath); // 静默失败
|
|
82
|
+
expect(readFinalized(badPath)).toBe(false);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
describe("与 .cancelled 互斥(BC-4)", () => {
|
|
87
|
+
it("写 finalized 时删除已有的 .cancelled", () => {
|
|
88
|
+
// 先写一个 .cancelled sidecar
|
|
89
|
+
fs.writeFileSync(`${sessionFile}.cancelled`, `{"id":"bg-1","status":"cancelled","agent":"w","startedAt":1,"endedAt":2}\n`, "utf-8");
|
|
90
|
+
expect(fs.existsSync(`${sessionFile}.cancelled`)).toBe(true);
|
|
91
|
+
|
|
92
|
+
// 写 finalized → .cancelled 应被删除
|
|
93
|
+
writeFinalized(sessionFile);
|
|
94
|
+
expect(fs.existsSync(`${sessionFile}.cancelled`)).toBe(false);
|
|
95
|
+
expect(readFinalized(sessionFile)).toBe(true);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it("无 .cancelled 时写 finalized 正常(不报错)", () => {
|
|
99
|
+
expect(fs.existsSync(`${sessionFile}.cancelled`)).toBe(false);
|
|
100
|
+
expect(() => writeFinalized(sessionFile)).not.toThrow();
|
|
101
|
+
expect(readFinalized(sessionFile)).toBe(true);
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
});
|