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