@adhdev/daemon-core 0.9.82-rc.46 → 0.9.82-rc.461
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/dist/boot/daemon-lifecycle.d.ts +9 -0
- package/dist/boot/process-hardening.d.ts +50 -0
- package/dist/build-info.d.ts +37 -0
- package/dist/chat/source-machine.d.ts +166 -0
- package/dist/chat/source-resolver.d.ts +104 -0
- package/dist/chat/subscription-updates.d.ts +1 -0
- package/dist/cli-adapter-types.d.ts +68 -2
- package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
- package/dist/cli-adapters/cli-state-engine.d.ts +200 -0
- package/dist/cli-adapters/provider-cli-adapter.d.ts +126 -64
- package/dist/cli-adapters/provider-cli-parse.d.ts +5 -0
- package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
- package/dist/cli-adapters/provider-cli-shared.d.ts +74 -0
- package/dist/cli-adapters/pty-write-chunking.d.ts +34 -0
- package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
- package/dist/cli-adapters/resolve-executable.d.ts +69 -0
- package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
- package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
- package/dist/cli-adapters/terminal-screen.d.ts +4 -11
- package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
- package/dist/commands/chat-commands-read.d.ts +7 -0
- package/dist/commands/chat-commands-scope.d.ts +39 -0
- package/dist/commands/chat-commands-shared.d.ts +33 -0
- package/dist/commands/chat-commands-write.d.ts +14 -0
- package/dist/commands/chat-commands.d.ts +10 -23
- package/dist/commands/cli-manager.d.ts +25 -1
- package/dist/commands/handler.d.ts +125 -0
- package/dist/commands/high-family/index.d.ts +3 -0
- package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
- package/dist/commands/high-family/mesh-events.d.ts +2 -0
- package/dist/commands/high-family/mesh-status.d.ts +2 -0
- package/dist/commands/high-family/types.d.ts +64 -0
- package/dist/commands/low-family/coordinator-prompt.d.ts +9 -0
- package/dist/commands/low-family/daemon-lifecycle.d.ts +2 -0
- package/dist/commands/low-family/diagnostics.d.ts +2 -0
- package/dist/commands/low-family/index.d.ts +3 -0
- package/dist/commands/low-family/mesh-ledger.d.ts +10 -0
- package/dist/commands/low-family/mesh-node-logs.d.ts +2 -0
- package/dist/commands/low-family/notification.d.ts +2 -0
- package/dist/commands/low-family/refine-config.d.ts +2 -0
- package/dist/commands/low-family/session-host.d.ts +2 -0
- package/dist/commands/low-family/spec-providerdev.d.ts +11 -0
- package/dist/commands/low-family/status-meta.d.ts +2 -0
- package/dist/commands/low-family/types.d.ts +33 -0
- package/dist/commands/med-family/cli-agent.d.ts +2 -0
- package/dist/commands/med-family/fast-forward.d.ts +2 -0
- package/dist/commands/med-family/ide.d.ts +10 -0
- package/dist/commands/med-family/index.d.ts +3 -0
- package/dist/commands/med-family/mesh-crud.d.ts +48 -0
- package/dist/commands/med-family/mesh-host-pairing.d.ts +2 -0
- package/dist/commands/med-family/mesh-queue.d.ts +2 -0
- package/dist/commands/med-family/mesh-restart.d.ts +2 -0
- package/dist/commands/med-family/types.d.ts +152 -0
- package/dist/commands/mesh-coordinator.d.ts +85 -1
- package/dist/commands/router-refine.d.ts +137 -0
- package/dist/commands/router-worktree-cleanup.d.ts +133 -0
- package/dist/commands/router.d.ts +241 -12
- package/dist/commands/upgrade-helper.d.ts +41 -1
- package/dist/config/chat-history.d.ts +9 -0
- package/dist/config/config.d.ts +19 -0
- package/dist/config/mesh-config.d.ts +136 -1
- package/dist/config/mesh-json-config.d.ts +199 -0
- package/dist/config/registry-resolver.d.ts +54 -0
- package/dist/config/repo-settings.d.ts +77 -0
- package/dist/daemon/dev-server.d.ts +0 -2
- package/dist/detection/cli-detector.d.ts +17 -0
- package/dist/detection/ide-detector.d.ts +13 -0
- package/dist/detection/win32-ide-version.d.ts +37 -0
- package/dist/git/change-impact-config.d.ts +159 -0
- package/dist/git/git-commands.d.ts +26 -2
- package/dist/git/git-diff.d.ts +6 -0
- package/dist/git/git-executor.d.ts +11 -0
- package/dist/git/git-status.d.ts +57 -0
- package/dist/git/git-types.d.ts +2 -50
- package/dist/git/git-worktree.d.ts +71 -1
- package/dist/git/index.d.ts +3 -1
- package/dist/index.d.ts +67 -15
- package/dist/index.js +58583 -25541
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +58207 -25332
- package/dist/index.mjs.map +1 -1
- package/dist/installer.d.ts +1 -4
- package/dist/ipc/local-ipc-server.d.ts +91 -0
- package/dist/launch.d.ts +1 -1
- package/dist/logging/async-batch-writer.d.ts +10 -0
- package/dist/logging/debug-config.d.ts +16 -0
- package/dist/logging/log-redactor.d.ts +24 -0
- package/dist/logging/log-tail-reader.d.ts +81 -0
- package/dist/logging/logger.d.ts +1 -1
- package/dist/mesh/contracts.d.ts +230 -0
- package/dist/mesh/coordinator-prompt.d.ts +76 -0
- package/dist/mesh/coordinator-registry.d.ts +59 -0
- package/dist/mesh/mesh-active-work.d.ts +174 -0
- package/dist/mesh/mesh-clone-grace.d.ts +8 -0
- package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
- package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
- package/dist/mesh/mesh-event-classify.d.ts +7 -0
- package/dist/mesh/mesh-event-forwarding.d.ts +41 -0
- package/dist/mesh/mesh-event-trace.d.ts +21 -0
- package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
- package/dist/mesh/mesh-events-pending.d.ts +155 -0
- package/dist/mesh/mesh-events-stale.d.ts +61 -0
- package/dist/mesh/mesh-events-utils.d.ts +75 -0
- package/dist/mesh/mesh-events.d.ts +6 -49
- package/dist/mesh/mesh-fast-forward.d.ts +81 -0
- package/dist/mesh/mesh-host-ownership.d.ts +29 -0
- package/dist/mesh/mesh-init.d.ts +128 -0
- package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
- package/dist/mesh/mesh-ledger.d.ts +133 -1
- package/dist/mesh/mesh-magi-status.d.ts +63 -0
- package/dist/mesh/mesh-missions.d.ts +189 -0
- package/dist/mesh/mesh-node-identity.d.ts +310 -0
- package/dist/mesh/mesh-queue-assignment.d.ts +158 -0
- package/dist/mesh/mesh-reconcile-loop.d.ts +80 -0
- package/dist/mesh/mesh-refine-batch.d.ts +68 -0
- package/dist/mesh/mesh-refine-gates.d.ts +428 -0
- package/dist/mesh/mesh-refine-status.d.ts +62 -0
- package/dist/mesh/mesh-review-inbox.d.ts +90 -0
- package/dist/mesh/mesh-routing.d.ts +70 -0
- package/dist/mesh/mesh-runtime-store.d.ts +493 -0
- package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
- package/dist/mesh/mesh-task-inflight.d.ts +46 -0
- package/dist/mesh/mesh-task-stats.d.ts +49 -0
- package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
- package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
- package/dist/mesh/mesh-work-queue.d.ts +318 -5
- package/dist/mesh/preview-freshness.d.ts +28 -0
- package/dist/mesh/refine-config.d.ts +216 -0
- package/dist/mesh/worktree-bootstrap-config.d.ts +219 -0
- package/dist/providers/acp-provider-instance.d.ts +5 -0
- package/dist/providers/approval-utils.d.ts +45 -0
- package/dist/providers/chat-message-normalization.d.ts +58 -1
- package/dist/providers/cli-provider-instance.d.ts +290 -3
- package/dist/providers/contracts.d.ts +149 -6
- package/dist/providers/external-sources.d.ts +71 -0
- package/dist/providers/manual-attendance.d.ts +79 -0
- package/dist/providers/native-history/antigravity-claim-registry.d.ts +28 -0
- package/dist/providers/native-history/antigravity-cli-transcript.d.ts +137 -0
- package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
- package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
- package/dist/providers/native-history/constants.d.ts +12 -0
- package/dist/providers/native-history/dispatcher.d.ts +31 -0
- package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
- package/dist/providers/native-history/index.d.ts +13 -0
- package/dist/providers/provider-instance-manager.d.ts +29 -0
- package/dist/providers/provider-instance.d.ts +30 -1
- package/dist/providers/provider-loader.d.ts +42 -5
- package/dist/providers/provider-trust.d.ts +31 -0
- package/dist/providers/read-chat-contract.d.ts +29 -0
- package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
- package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
- package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
- package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
- package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
- package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
- package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
- package/dist/providers/sdk/v1/index.d.ts +30 -0
- package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
- package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
- package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
- package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
- package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
- package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
- package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
- package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
- package/dist/providers/spec/adapter.d.ts +98 -0
- package/dist/providers/spec/cli-adapter.d.ts +223 -0
- package/dist/providers/spec/evaluator.d.ts +45 -0
- package/dist/providers/spec/fsm-driver.d.ts +449 -0
- package/dist/providers/spec/fsm-evaluator.d.ts +93 -0
- package/dist/providers/spec/fsm-loader.d.ts +14 -0
- package/dist/providers/spec/fsm-types.d.ts +202 -0
- package/dist/providers/spec/native-history-executor.d.ts +41 -0
- package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
- package/dist/providers/spec/route.d.ts +4 -0
- package/dist/providers/spec/types.d.ts +222 -0
- package/dist/providers/status-monitor.d.ts +7 -7
- package/dist/providers/transcript-v2.d.ts +176 -0
- package/dist/providers/types/interactive-prompt.d.ts +84 -0
- package/dist/providers/working-dir.d.ts +17 -0
- package/dist/repo-mesh-types.d.ts +598 -12
- package/dist/runtime-defaults.d.ts +2 -0
- package/dist/session-host/managed-host.d.ts +64 -0
- package/dist/session-host/runtime-surface.d.ts +10 -16
- package/dist/sessions/registry.d.ts +6 -0
- package/dist/shared-types-extra.d.ts +2 -4
- package/dist/shared-types.d.ts +86 -55
- package/dist/status/normalize.d.ts +1 -1
- package/dist/status/normalize.js +1 -0
- package/dist/status/normalize.js.map +1 -1
- package/dist/status/normalize.mjs +1 -0
- package/dist/status/normalize.mjs.map +1 -1
- package/dist/status/reporter.d.ts +2 -0
- package/dist/status/snapshot.d.ts +26 -0
- package/dist/system/hash.d.ts +8 -0
- package/dist/system/load-better-sqlite3.d.ts +21 -0
- package/dist/types.d.ts +5 -0
- package/package.json +11 -4
- package/src/agent-stream/poller.ts +2 -3
- package/src/agent-stream/provider-adapter.ts +1 -1
- package/src/boot/daemon-lifecycle.ts +80 -14
- package/src/boot/process-hardening.ts +89 -0
- package/src/build-info.ts +73 -0
- package/src/chat/source-machine.ts +534 -0
- package/src/chat/source-resolver.ts +0 -0
- package/src/chat/subscription-updates.ts +20 -1
- package/src/cli-adapter-types.d.ts +3 -1
- package/src/cli-adapter-types.ts +68 -2
- package/src/cli-adapters/cli-script-runner.ts +421 -0
- package/src/cli-adapters/cli-state-engine.ts +1246 -0
- package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
- package/src/cli-adapters/provider-cli-adapter.ts +914 -1144
- package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
- package/src/cli-adapters/provider-cli-parse.ts +19 -0
- package/src/cli-adapters/provider-cli-runtime.ts +56 -7
- package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
- package/src/cli-adapters/provider-cli-shared.ts +121 -11
- package/src/cli-adapters/pty-transport.ts +2 -1
- package/src/cli-adapters/pty-write-chunking.ts +106 -0
- package/src/cli-adapters/raw-terminal-io.ts +252 -0
- package/src/cli-adapters/resolve-executable.ts +204 -0
- package/src/cli-adapters/session-host-transport.ts +2 -1
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
- package/src/cli-adapters/terminal-backends/types.ts +10 -3
- package/src/cli-adapters/terminal-screen.ts +16 -81
- package/src/commands/chat-commands-debug-bundle.ts +398 -0
- package/src/commands/chat-commands-read.ts +2488 -0
- package/src/commands/chat-commands-scope.ts +54 -0
- package/src/commands/chat-commands-shared.ts +114 -0
- package/src/commands/chat-commands-write.ts +891 -0
- package/src/commands/chat-commands.ts +19 -1841
- package/src/commands/cli-manager.ts +596 -27
- package/src/commands/handler.ts +845 -2
- package/src/commands/high-family/index.ts +28 -0
- package/src/commands/high-family/mesh-coordinator-launch.ts +680 -0
- package/src/commands/high-family/mesh-events.ts +89 -0
- package/src/commands/high-family/mesh-status.ts +832 -0
- package/src/commands/high-family/types.ts +80 -0
- package/src/commands/low-family/coordinator-prompt.ts +72 -0
- package/src/commands/low-family/daemon-lifecycle.ts +120 -0
- package/src/commands/low-family/diagnostics.ts +57 -0
- package/src/commands/low-family/index.ts +37 -0
- package/src/commands/low-family/mesh-ledger.ts +62 -0
- package/src/commands/low-family/mesh-node-logs.ts +87 -0
- package/src/commands/low-family/notification.ts +116 -0
- package/src/commands/low-family/refine-config.ts +106 -0
- package/src/commands/low-family/session-host.ts +274 -0
- package/src/commands/low-family/spec-providerdev.ts +217 -0
- package/src/commands/low-family/status-meta.ts +112 -0
- package/src/commands/low-family/types.ts +39 -0
- package/src/commands/med-family/cli-agent.ts +241 -0
- package/src/commands/med-family/fast-forward.ts +230 -0
- package/src/commands/med-family/ide.ts +163 -0
- package/src/commands/med-family/index.ts +37 -0
- package/src/commands/med-family/mesh-crud.ts +1287 -0
- package/src/commands/med-family/mesh-host-pairing.ts +234 -0
- package/src/commands/med-family/mesh-queue.ts +167 -0
- package/src/commands/med-family/mesh-restart.ts +92 -0
- package/src/commands/med-family/types.ts +153 -0
- package/src/commands/mesh-coordinator.ts +334 -124
- package/src/commands/router-refine.ts +1711 -0
- package/src/commands/router-worktree-cleanup.ts +870 -0
- package/src/commands/router.ts +1025 -4070
- package/src/commands/stream-commands.ts +8 -0
- package/src/commands/upgrade-helper.ts +310 -45
- package/src/config/chat-history.ts +493 -24
- package/src/config/config.ts +30 -0
- package/src/config/mesh-config.ts +632 -23
- package/src/config/mesh-json-config.ts +376 -0
- package/src/config/recent-activity.ts +8 -2
- package/src/config/registry-resolver.ts +100 -0
- package/src/config/repo-settings.ts +111 -0
- package/src/daemon/dev-auto-implement.ts +3 -2
- package/src/daemon/dev-cli-debug.ts +10 -1
- package/src/daemon/dev-server.ts +0 -541
- package/src/detection/cli-detector.ts +94 -9
- package/src/detection/ide-detector.ts +55 -16
- package/src/detection/win32-ide-version.ts +106 -0
- package/src/git/change-impact-config.ts +354 -0
- package/src/git/git-commands.ts +112 -16
- package/src/git/git-diff.ts +81 -11
- package/src/git/git-executor.ts +12 -0
- package/src/git/git-status.ts +767 -48
- package/src/git/git-types.ts +14 -62
- package/src/git/git-worktree.ts +261 -4
- package/src/git/index.ts +17 -0
- package/src/index.ts +200 -12
- package/src/installer.d.ts +1 -1
- package/src/installer.ts +8 -6
- package/src/ipc/local-ipc-server.ts +278 -0
- package/src/launch.d.ts +1 -1
- package/src/launch.ts +37 -28
- package/src/logging/async-batch-writer.ts +55 -0
- package/src/logging/command-log.ts +7 -5
- package/src/logging/debug-config.ts +25 -0
- package/src/logging/debug-trace.ts +7 -2
- package/src/logging/log-redactor.ts +100 -0
- package/src/logging/log-tail-reader.ts +341 -0
- package/src/logging/logger.ts +14 -7
- package/src/mesh/contracts.ts +469 -0
- package/src/mesh/coordinator-prompt.ts +554 -34
- package/src/mesh/coordinator-registry.ts +121 -0
- package/src/mesh/mesh-active-work.ts +656 -0
- package/src/mesh/mesh-clone-grace.ts +68 -0
- package/src/mesh/mesh-coordinator-config.ts +97 -0
- package/src/mesh/mesh-delivery-policy.ts +315 -0
- package/src/mesh/mesh-event-classify.ts +73 -0
- package/src/mesh/mesh-event-forwarding.ts +1950 -0
- package/src/mesh/mesh-event-trace.ts +67 -0
- package/src/mesh/mesh-events-coordinator.ts +32 -0
- package/src/mesh/mesh-events-pending.ts +1132 -0
- package/src/mesh/mesh-events-stale.ts +440 -0
- package/src/mesh/mesh-events-utils.ts +443 -0
- package/src/mesh/mesh-events.ts +35 -1035
- package/src/mesh/mesh-fast-forward.ts +856 -0
- package/src/mesh/mesh-host-ownership.ts +111 -0
- package/src/mesh/mesh-init.ts +350 -0
- package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
- package/src/mesh/mesh-ledger.ts +873 -102
- package/src/mesh/mesh-magi-status.ts +223 -0
- package/src/mesh/mesh-missions.ts +449 -0
- package/src/mesh/mesh-node-identity.ts +2065 -0
- package/src/mesh/mesh-queue-assignment.ts +2233 -0
- package/src/mesh/mesh-reconcile-loop.ts +2397 -0
- package/src/mesh/mesh-refine-batch.ts +205 -0
- package/src/mesh/mesh-refine-gates.ts +1686 -0
- package/src/mesh/mesh-refine-status.ts +231 -0
- package/src/mesh/mesh-review-inbox.ts +308 -0
- package/src/mesh/mesh-routing.ts +291 -0
- package/src/mesh/mesh-runtime-store.ts +2056 -0
- package/src/mesh/mesh-scheduling-runtime.ts +198 -0
- package/src/mesh/mesh-task-inflight.ts +70 -0
- package/src/mesh/mesh-task-stats.ts +161 -0
- package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
- package/src/mesh/mesh-warmup-deadline.ts +152 -0
- package/src/mesh/mesh-work-queue.ts +1281 -141
- package/src/mesh/preview-freshness.ts +163 -0
- package/src/mesh/refine-config.ts +423 -0
- package/src/mesh/worktree-bootstrap-config.ts +599 -0
- package/src/providers/acp-provider-instance.ts +43 -10
- package/src/providers/approval-utils.d.ts +5 -0
- package/src/providers/approval-utils.ts +99 -5
- package/src/providers/chat-message-normalization.ts +126 -4
- package/src/providers/cli-provider-instance.ts +2456 -107
- package/src/providers/contracts.d.ts +55 -0
- package/src/providers/contracts.ts +160 -6
- package/src/providers/extension-provider-instance.ts +12 -7
- package/src/providers/external-sources.ts +218 -0
- package/src/providers/ide-provider-instance.ts +35 -12
- package/src/providers/manual-attendance.ts +105 -0
- package/src/providers/native-history/antigravity-claim-registry.ts +131 -0
- package/src/providers/native-history/antigravity-cli-transcript.ts +1193 -0
- package/src/providers/native-history/claude-cli-transcript.ts +396 -0
- package/src/providers/native-history/codex-cli-transcript.ts +479 -0
- package/src/providers/native-history/constants.ts +19 -0
- package/src/providers/native-history/dispatcher.ts +503 -0
- package/src/providers/native-history/hermes-cli-transcript.ts +260 -0
- package/src/providers/native-history/index.ts +30 -0
- package/src/providers/provider-instance-manager.ts +71 -0
- package/src/providers/provider-instance.ts +24 -1
- package/src/providers/provider-loader.ts +700 -55
- package/src/providers/provider-schema.ts +87 -14
- package/src/providers/provider-trust.ts +114 -0
- package/src/providers/read-chat-contract.ts +76 -16
- package/src/providers/sdk/README.md +49 -0
- package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
- package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval.ts +261 -0
- package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
- package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
- package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
- package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
- package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
- package/src/providers/sdk/v1/index.ts +152 -0
- package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
- package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
- package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
- package/src/providers/sdk/v1/schemas/cli/provider.schema.json +509 -0
- package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
- package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
- package/src/providers/sdk/v1/types/cli/index.ts +365 -0
- package/src/providers/sdk/v1/types/common/index.ts +229 -0
- package/src/providers/sdk/v1/validators/index.ts +19 -0
- package/src/providers/sdk/v1/validators/manifest.ts +110 -0
- package/src/providers/sdk/v1/validators/taint.ts +309 -0
- package/src/providers/spec/adapter.ts +246 -0
- package/src/providers/spec/cli-adapter.ts +1064 -0
- package/src/providers/spec/evaluator.ts +407 -0
- package/src/providers/spec/fsm-driver.ts +1528 -0
- package/src/providers/spec/fsm-evaluator.ts +290 -0
- package/src/providers/spec/fsm-loader.ts +128 -0
- package/src/providers/spec/fsm-types.ts +301 -0
- package/src/providers/spec/native-history-executor.ts +1174 -0
- package/src/providers/spec/pre-launch-trust.ts +104 -0
- package/src/providers/spec/route.ts +51 -0
- package/src/providers/spec/types.ts +262 -0
- package/src/providers/status-monitor.d.ts +7 -7
- package/src/providers/status-monitor.ts +37 -22
- package/src/providers/transcript-v2.ts +567 -0
- package/src/providers/types/interactive-prompt.ts +536 -0
- package/src/providers/version-archive.ts +64 -24
- package/src/providers/working-dir.ts +23 -0
- package/src/repo-mesh-types.ts +836 -13
- package/src/runtime-defaults.ts +39 -0
- package/src/session-host/managed-host.ts +218 -0
- package/src/session-host/runtime-surface.ts +20 -80
- package/src/sessions/registry.ts +6 -0
- package/src/shared-types-extra.ts +2 -4
- package/src/shared-types.d.ts +8 -0
- package/src/shared-types.ts +124 -55
- package/src/status/builders.ts +26 -6
- package/src/status/normalize.ts +2 -0
- package/src/status/reporter.ts +19 -1
- package/src/status/snapshot.ts +95 -26
- package/src/system/hash.ts +23 -0
- package/src/system/host-memory.ts +29 -12
- package/src/system/load-better-sqlite3.ts +68 -0
- package/src/types.ts +5 -0
- package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
- package/dist/mesh/mesh-sync.d.ts +0 -53
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
- package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
- package/src/mesh/mesh-sync.ts +0 -111
|
@@ -0,0 +1,2233 @@
|
|
|
1
|
+
import { existsSync } from 'fs';
|
|
2
|
+
import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
|
|
3
|
+
import { MESH_CONNECT_TIMEOUT_MS } from '../runtime-defaults.js';
|
|
4
|
+
import { loadConfig } from '../config/config.js';
|
|
5
|
+
import { getMesh } from '../config/mesh-config.js';
|
|
6
|
+
import { detectCLI } from '../detection/cli-detector.js';
|
|
7
|
+
import { LOG } from '../logging/logger.js';
|
|
8
|
+
import { appendLedgerEntry } from './mesh-ledger.js';
|
|
9
|
+
import { buildMeshNodeCapabilityTags, nodeSatisfiesRequiredTags, claimNextTask, updateTaskStatus, getQueue, recordTaskAutoLaunch, getActiveDirectDispatches, isTaskReadonly, taskDependenciesSatisfied } from './mesh-work-queue.js';
|
|
10
|
+
import type { MeshWorkQueueEntry } from './mesh-work-queue.js';
|
|
11
|
+
import { fastForwardMeshNode } from './mesh-fast-forward.js';
|
|
12
|
+
import { createSessionDelivery, updateSessionDeliveryStatus } from './mesh-delivery-policy.js';
|
|
13
|
+
import { MeshRuntimeStore } from './mesh-runtime-store.js';
|
|
14
|
+
import { traceMeshEventDrop } from './mesh-event-trace.js';
|
|
15
|
+
import { awaitWithWarmupDeadline, resolveWarmupDeadlineOpts } from './mesh-warmup-deadline.js';
|
|
16
|
+
import { resolveDelegatedWorkerAutoApprove, resolveProviderMaxParallel, resolveNodeSchedulingPriority, normalizeMeshSchedulingStrategy, resolveMaxParallelTasks, resolveMaxReadonlyParallelTasks } from '../repo-mesh-types.js';
|
|
17
|
+
import type { RepoMeshSchedulingStrategy } from '../repo-mesh-types.js';
|
|
18
|
+
import { normalizeMeshNodeId, meshNodeIdMatches, daemonIdsEquivalent, canonicalDaemonId, normalizeMeshWorkspaceForCompare, meshWorkspacesEquivalent, sessionIdsEquivalent, type MeshNodeIdentified } from '@adhdev/mesh-shared';
|
|
19
|
+
import { findTerminalLedgerEvidenceForTask, hasUnterminalDirectDispatchLedgerEntry } from './mesh-events-stale.js';
|
|
20
|
+
import { readNonEmptyString } from './mesh-events-utils.js';
|
|
21
|
+
import { queuePendingMeshCoordinatorEvent, retractPendingDispatchBlockedEvent } from './mesh-events-pending.js';
|
|
22
|
+
import { isWorktreeBootstrapStaleRunning, shouldDeferDispatchForBootstrap } from './worktree-bootstrap-config.js';
|
|
23
|
+
import { isWithinCloneBootstrapGrace } from './mesh-clone-grace.js';
|
|
24
|
+
import { beginTaskDispatchInFlight, endTaskDispatchInFlight } from './mesh-task-inflight.js';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* CANON: the single canonical coordinator-daemon id this daemon stamps onto every
|
|
28
|
+
* worker dispatch (meshContext.coordinatorDaemonId / sourceCoordinatorDaemonId / the
|
|
29
|
+
* co-located meshCoordinatorDaemonId anchor). loadConfig().machineId is the bare
|
|
30
|
+
* `mach_X` form; canonicalizing to `daemon_mach_X` unifies it with the MCP-side
|
|
31
|
+
* resolveCoordinatorDaemonId producer so the two dispatch paths can never stamp a
|
|
32
|
+
* worker's coordinator anchor in two different forms — the CANON-IDENTITY
|
|
33
|
+
* double-dispatch root cause. Consumers of the anchor already compare under
|
|
34
|
+
* daemonIdsEquivalent / expandDaemonIdForms, so the exact form is form-agnostic on
|
|
35
|
+
* the read side; this only removes the producer-side skew.
|
|
36
|
+
*/
|
|
37
|
+
function localCoordinatorDaemonId(): string | undefined {
|
|
38
|
+
return canonicalDaemonId(readNonEmptyString(loadConfig().machineId));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ---------------------------------------------------------------------------
|
|
42
|
+
// Idle auto fast-forward throttle state
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
const IDLE_AUTO_FAST_FORWARD_THROTTLE_MS = 30 * 60 * 1000;
|
|
45
|
+
const idleAutoFastForwardLastAttempt = new Map<string, number>();
|
|
46
|
+
|
|
47
|
+
export function __resetIdleAutoFastForwardForTests(): void {
|
|
48
|
+
idleAutoFastForwardLastAttempt.clear();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function getMeshWithCache(components: DaemonComponents, meshId: string): any | undefined {
|
|
52
|
+
const localMesh = getMesh(meshId);
|
|
53
|
+
const cachedMesh = components.router?.getCachedInlineMesh(meshId);
|
|
54
|
+
if (!localMesh) return cachedMesh;
|
|
55
|
+
if (!cachedMesh) return localMesh;
|
|
56
|
+
return mergeInlineCacheOnlyNodes(localMesh, cachedMesh);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Claim-time membership view unification (CLAIMSTALL fix).
|
|
61
|
+
*
|
|
62
|
+
* The coordinator's claim path — triggerMeshQueue → autoLaunch candidate filter
|
|
63
|
+
* and the local/remote idle-session drain — reads mesh membership through
|
|
64
|
+
* getMeshWithCache, which historically returned the local-config mesh verbatim
|
|
65
|
+
* whenever one existed. A freshly cloned worktree node is registered ONLY into the
|
|
66
|
+
* router's inline mesh cache: clone_mesh_node's `meshRecord.inline` branch calls
|
|
67
|
+
* updateInlineMeshNode, NOT addNode, so the worktree node never reaches local
|
|
68
|
+
* config (meshes.json). The config-first view therefore omits the worktree node,
|
|
69
|
+
* while send_task — which resolves membership through getMeshForCommand(preferInline)
|
|
70
|
+
* over the same inline cache — sees it. That view asymmetry is the stall: a queue
|
|
71
|
+
* task pinned to the worktree node reports `target_node_id_unmatched` (autoLaunch
|
|
72
|
+
* candidate filter / targetPinUnmatched check) and the node's idle session is
|
|
73
|
+
* dropped from the drain pool (mesh.nodes.find miss), so claim never fires and the
|
|
74
|
+
* task is stranded pending — even though nodeId matching itself is correct.
|
|
75
|
+
*
|
|
76
|
+
* Fix: union the local-config nodes with any inline-cache-ONLY nodes, so the claim
|
|
77
|
+
* view matches the command (send_task) view. Base (non-worktree) nodes present in
|
|
78
|
+
* local config stay config-authoritative — their entry is taken verbatim from
|
|
79
|
+
* localMesh, so base node claim/matching is byte-for-byte unchanged. Only nodes
|
|
80
|
+
* that exist solely in the inline cache (the cloned worktree nodes) are appended.
|
|
81
|
+
* Identity comparison uses the shared 3-form normalizer (id / nodeId / node_id),
|
|
82
|
+
* identical to every other claim-path consumer — the matching logic is untouched,
|
|
83
|
+
* only which nodes are visible.
|
|
84
|
+
*/
|
|
85
|
+
function mergeInlineCacheOnlyNodes(localMesh: any, cachedMesh: any): any {
|
|
86
|
+
const localNodes = Array.isArray(localMesh?.nodes) ? localMesh.nodes : [];
|
|
87
|
+
const cachedNodes = Array.isArray(cachedMesh?.nodes) ? cachedMesh.nodes : [];
|
|
88
|
+
if (!cachedNodes.length) return localMesh;
|
|
89
|
+
const cacheOnly = cachedNodes.filter((cachedNode: any) => {
|
|
90
|
+
const cachedId = readMeshNodeId(cachedNode);
|
|
91
|
+
// Unidentifiable cache entries can never be a claim/route target — skip them
|
|
92
|
+
// rather than appending junk that no consumer can address.
|
|
93
|
+
if (!cachedId) return false;
|
|
94
|
+
return !localNodes.some((localNode: any) => meshNodeIdMatches(localNode, cachedId));
|
|
95
|
+
});
|
|
96
|
+
if (!cacheOnly.length) return localMesh;
|
|
97
|
+
return { ...localMesh, nodes: [...localNodes, ...cacheOnly] };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
// Queue assignment
|
|
102
|
+
// ---------------------------------------------------------------------------
|
|
103
|
+
|
|
104
|
+
// Per-dispatch confirmation timeout (Bug B). A dispatch promise that never settles —
|
|
105
|
+
// a saturated remote P2P relay that hangs, or a transport that resolves only after
|
|
106
|
+
// the worker acks — would otherwise leave the just-claimed queue row 'assigned' with
|
|
107
|
+
// its delivery stuck 'delivering' forever: the .catch that requeues never fires, and
|
|
108
|
+
// PHASE 3 reconcile skips the row (it counts 0 pending). Racing the dispatch against
|
|
109
|
+
// this timeout guarantees a hung dispatch deterministically returns the task to
|
|
110
|
+
// 'pending' for re-dispatch. Generous so a merely-slow-but-live dispatch (a cold
|
|
111
|
+
// remote relay) is never reclaimed early; the reconcile assigned-stranded watchdog is
|
|
112
|
+
// the durable cross-restart backstop for a timer lost to a daemon restart.
|
|
113
|
+
const DISPATCH_CONFIRM_TIMEOUT_MS = 120_000;
|
|
114
|
+
|
|
115
|
+
// Cold-open connect budget for the warmup-aware REMOTE task dispatch deadline. A
|
|
116
|
+
// remote `agent_command` to a peer whose mesh DataChannel is not open yet first has
|
|
117
|
+
// to drive the cross-machine (often TURN-relayed) handshake; charging that warmup
|
|
118
|
+
// against the response budget is the same cold-open false-timeout the git_status
|
|
119
|
+
// probe path already guards against. This budget bounds ONLY the "channel not open
|
|
120
|
+
// yet" phase; once the channel is warm the DISPATCH_CONFIRM_TIMEOUT_MS response
|
|
121
|
+
// budget governs (identical to the legacy flat guard for an already-open peer, so
|
|
122
|
+
// no latency is added to a normal dispatch). Matches the daemon-cloud
|
|
123
|
+
// DaemonMeshManager CONNECT_TIMEOUT_MS (45s) so the caller-side deadline tracks the
|
|
124
|
+
// transport's own cold-open window rather than guessing.
|
|
125
|
+
//
|
|
126
|
+
// Sourced from the unified, env-overridable MESH_CONNECT_TIMEOUT_MS (runtime-defaults)
|
|
127
|
+
// — the SAME budget the router's direct-peer git_status probe uses. Previously this
|
|
128
|
+
// was a hard-coded 45_000 while the probe path was env-overridable, so setting the
|
|
129
|
+
// env tuned the probe but silently left this dispatch path at 45s (a silent
|
|
130
|
+
// asymmetry). They now move together.
|
|
131
|
+
const DISPATCH_CONNECT_TIMEOUT_MS = MESH_CONNECT_TIMEOUT_MS;
|
|
132
|
+
|
|
133
|
+
// Fail-loud (throttled) trace for a remote dispatch that ran with NO live mesh
|
|
134
|
+
// connection getter wired — the same degraded-warmup misconfiguration the git probe
|
|
135
|
+
// path warns about. Warn once per peer; resolveWarmupDeadlineOpts then falls back to
|
|
136
|
+
// the conservative combined budget instead of silently assuming "always warm".
|
|
137
|
+
const dispatchWarmupGetterMissingWarned = new Set<string>();
|
|
138
|
+
function warnDispatchWarmupGetterMissingOnce(daemonId: string): void {
|
|
139
|
+
if (dispatchWarmupGetterMissingWarned.has(daemonId)) return;
|
|
140
|
+
dispatchWarmupGetterMissingWarned.add(daemonId);
|
|
141
|
+
LOG.warn('MeshQueue', `Mesh peer connection getter unavailable for ${String(daemonId).slice(0, 12)}; remote task-dispatch warmup deadline degraded to the combined connect+response window. Avoids a cold-open false-timeout but loses warm/cold precision — wire getMeshPeerConnectionStatus on this daemon.`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
interface DeliverTaskContext {
|
|
145
|
+
meshId: string;
|
|
146
|
+
nodeId: string;
|
|
147
|
+
sessionId: string;
|
|
148
|
+
providerType: string;
|
|
149
|
+
task: MeshWorkQueueEntry;
|
|
150
|
+
transport: 'remote' | 'local';
|
|
151
|
+
sourceCoordinatorSessionId?: string;
|
|
152
|
+
sourceCoordinatorDaemonId?: string;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Readiness barrier for the LOCAL auto-launch path. A just-spawned CLI session is
|
|
156
|
+
// not interactive until its PTY prints the input prompt (the adapter flips
|
|
157
|
+
// isReady() / settles to idle ~2-6s later). Poll the local adapter until it reports
|
|
158
|
+
// ready (or idle), bounded by a generous timeout so a slow/contended boot still
|
|
159
|
+
// lands, and a hard cap so a session that never becomes interactive doesn't block the
|
|
160
|
+
// reconcile loop forever (the adapter's queue-until-ready path is the backstop then).
|
|
161
|
+
const LOCAL_LAUNCH_READY_TIMEOUT_MS = 15_000;
|
|
162
|
+
const LOCAL_LAUNCH_READY_POLL_MS = 100;
|
|
163
|
+
|
|
164
|
+
async function waitForLocalSessionReady(components: DaemonComponents, sessionId: string): Promise<void> {
|
|
165
|
+
const adapter = components.cliManager?.adapters?.get(sessionId) as
|
|
166
|
+
| { isReady?: () => boolean; currentStatus?: string }
|
|
167
|
+
| undefined;
|
|
168
|
+
// No locally-resolvable adapter (e.g. a remote/forwarded session that somehow
|
|
169
|
+
// reached this branch) → nothing to wait on; let dispatch proceed.
|
|
170
|
+
if (!adapter || typeof adapter.isReady !== 'function') return;
|
|
171
|
+
const deadline = Date.now() + LOCAL_LAUNCH_READY_TIMEOUT_MS;
|
|
172
|
+
while (Date.now() < deadline) {
|
|
173
|
+
if (adapter.isReady() || adapter.currentStatus === 'idle') return;
|
|
174
|
+
await new Promise<void>(resolve => setTimeout(resolve, LOCAL_LAUNCH_READY_POLL_MS));
|
|
175
|
+
}
|
|
176
|
+
LOG.warn('MeshQueue', `Auto-launched session ${sessionId} not interactive after ${LOCAL_LAUNCH_READY_TIMEOUT_MS}ms; dispatching anyway (adapter queue-until-ready will buffer)`);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// CONS scope 3: the SINGLE source of truth for dispatching a claimed task to its
|
|
180
|
+
// session. The remote (P2P dispatchMeshCommand) and local (cliManager.handleCliCommand)
|
|
181
|
+
// branches differ ONLY in the transport call — the delivery record, the delivered/failed
|
|
182
|
+
// transitions, the pending-requeue-on-failure, the dispatch_failed ledger entry, AND the
|
|
183
|
+
// Bug B hang timeout are identical and live here once so a future change to the dispatch
|
|
184
|
+
// lifecycle cannot drift between the two paths. The caller passes a `dispatchThunk` that
|
|
185
|
+
// performs only the transport-specific send and returns its promise.
|
|
186
|
+
//
|
|
187
|
+
// Cold-open warmup (remote only): the REMOTE transport speaks over a P2P
|
|
188
|
+
// DataChannel that may still be opening when the first task is dispatched to a peer.
|
|
189
|
+
// When `warmup` is supplied the dispatch is awaited under the warmup-aware deadline
|
|
190
|
+
// (mesh-warmup-deadline) — the cold-open handshake is charged to the connect budget
|
|
191
|
+
// and only the warm round trip to the DISPATCH_CONFIRM_TIMEOUT_MS response budget —
|
|
192
|
+
// so the very first dispatch to a not-yet-open peer is no longer false-timed at the
|
|
193
|
+
// combined window. An already-open peer behaves identically to the legacy flat guard
|
|
194
|
+
// (response budget governs from t0), so a normal dispatch sees no added latency. The
|
|
195
|
+
// LOCAL transport (in-process cliManager) has no channel to warm up and keeps the
|
|
196
|
+
// flat Bug B hang guard.
|
|
197
|
+
function deliverTaskToSession(
|
|
198
|
+
dispatchThunk: () => Promise<unknown>,
|
|
199
|
+
ctx: DeliverTaskContext,
|
|
200
|
+
warmup?: { daemonId: string; getConnection?: (daemonId: string) => Record<string, unknown> | null },
|
|
201
|
+
): void {
|
|
202
|
+
const delivery = createSessionDelivery({
|
|
203
|
+
meshId: ctx.meshId,
|
|
204
|
+
nodeId: ctx.nodeId,
|
|
205
|
+
sessionId: ctx.sessionId,
|
|
206
|
+
providerType: ctx.providerType,
|
|
207
|
+
taskId: ctx.task.id,
|
|
208
|
+
kind: 'task',
|
|
209
|
+
message: ctx.task.message,
|
|
210
|
+
status: 'delivering',
|
|
211
|
+
...(ctx.sourceCoordinatorSessionId ? { sourceCoordinatorSessionId: ctx.sourceCoordinatorSessionId } : {}),
|
|
212
|
+
...(ctx.sourceCoordinatorDaemonId ? { sourceCoordinatorDaemonId: ctx.sourceCoordinatorDaemonId } : {}),
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
// Invoke the transport synchronously (preserves the prior fire-and-forget timing,
|
|
216
|
+
// and lets a synchronous throw fall into the same failure path as a rejection).
|
|
217
|
+
let dispatchPromise: Promise<unknown>;
|
|
218
|
+
try {
|
|
219
|
+
dispatchPromise = Promise.resolve(dispatchThunk());
|
|
220
|
+
} catch (e) {
|
|
221
|
+
dispatchPromise = Promise.reject(e);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
225
|
+
let guarded: Promise<unknown>;
|
|
226
|
+
if (warmup) {
|
|
227
|
+
// Remote P2P: cold-open-aware deadline. awaitWithWarmupDeadline owns its own
|
|
228
|
+
// timers (so `timer` stays undefined and the clearTimeout below is a no-op),
|
|
229
|
+
// and rejects with Error('timeout') when either budget lapses — the same
|
|
230
|
+
// retryable failure shape the catch below already handles (requeue + ledger).
|
|
231
|
+
guarded = awaitWithWarmupDeadline(dispatchPromise, resolveWarmupDeadlineOpts({
|
|
232
|
+
getConnection: warmup.getConnection,
|
|
233
|
+
daemonId: warmup.daemonId,
|
|
234
|
+
connectTimeoutMs: DISPATCH_CONNECT_TIMEOUT_MS,
|
|
235
|
+
responseTimeoutMs: DISPATCH_CONFIRM_TIMEOUT_MS,
|
|
236
|
+
onMissingGetter: warnDispatchWarmupGetterMissingOnce,
|
|
237
|
+
}));
|
|
238
|
+
} else {
|
|
239
|
+
guarded = Promise.race([
|
|
240
|
+
dispatchPromise,
|
|
241
|
+
new Promise<never>((_, reject) => {
|
|
242
|
+
timer = setTimeout(
|
|
243
|
+
() => reject(new Error(`dispatch_confirm_timeout after ${DISPATCH_CONFIRM_TIMEOUT_MS}ms`)),
|
|
244
|
+
DISPATCH_CONFIRM_TIMEOUT_MS,
|
|
245
|
+
);
|
|
246
|
+
// Never keep the process alive solely for this confirm-timeout timer.
|
|
247
|
+
if (typeof (timer as { unref?: () => void })?.unref === 'function') (timer as { unref: () => void }).unref();
|
|
248
|
+
}),
|
|
249
|
+
]);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
guarded.then(() => {
|
|
253
|
+
if (timer) clearTimeout(timer);
|
|
254
|
+
updateSessionDeliveryStatus(delivery.id, 'delivered');
|
|
255
|
+
}).catch((e: any) => {
|
|
256
|
+
if (timer) clearTimeout(timer);
|
|
257
|
+
// A dispatch failure (transport reject OR hang timeout) is most often transient —
|
|
258
|
+
// a busy/refusing adapter, or a relay that never acked — not a permanent task
|
|
259
|
+
// failure. Marking the task terminal here would permanently kill tasks a later
|
|
260
|
+
// tick delivers fine. Return it to 'pending' and record a retryable dispatch_failed
|
|
261
|
+
// ledger entry so the reconcile loop re-dispatches it. Identical for both transports.
|
|
262
|
+
LOG.error('MeshQueue', `Failed to dispatch task via ${ctx.transport} to node ${ctx.nodeId}: ${e?.message}`);
|
|
263
|
+
updateSessionDeliveryStatus(delivery.id, 'failed', { lastError: e?.message, incrementAttempt: true });
|
|
264
|
+
// The dispatch failed — the task is no longer in-flight (it returns to pending
|
|
265
|
+
// for a clean re-dispatch). Clear the single-flight mark so a legitimate
|
|
266
|
+
// requeue/re-claim is not blocked as if a worker were still generating.
|
|
267
|
+
endTaskDispatchInFlight(ctx.meshId, ctx.task.id);
|
|
268
|
+
updateTaskStatus(ctx.meshId, ctx.task.id, 'pending');
|
|
269
|
+
try {
|
|
270
|
+
appendLedgerEntry(ctx.meshId, {
|
|
271
|
+
kind: 'dispatch_failed' as any,
|
|
272
|
+
nodeId: ctx.nodeId,
|
|
273
|
+
sessionId: ctx.sessionId,
|
|
274
|
+
payload: { taskId: ctx.task.id, deliveryId: delivery.id, error: e?.message, retryable: true, transport: ctx.transport },
|
|
275
|
+
});
|
|
276
|
+
} catch { /* ledger write is best-effort */ }
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// WTCLAIM: workspace normalization for base-vs-worktree comparison now lives in
|
|
281
|
+
// @adhdev/mesh-shared (normalizeMeshWorkspaceForCompare) so the enqueue→claim path,
|
|
282
|
+
// the mesh_status per-node session filter, and the read_chat node scope guard all
|
|
283
|
+
// share one comparison rule instead of drifting module-private copies.
|
|
284
|
+
|
|
285
|
+
export function tryAssignQueueTask(
|
|
286
|
+
components: DaemonComponents,
|
|
287
|
+
meshId: string,
|
|
288
|
+
nodeId: string,
|
|
289
|
+
sessionId: string,
|
|
290
|
+
providerType: string
|
|
291
|
+
): boolean {
|
|
292
|
+
const mesh = getMeshWithCache(components, meshId);
|
|
293
|
+
// Match with the shared 3-form normalizer (id / nodeId / node_id), not raw
|
|
294
|
+
// `n.id` — a stamp-form nodeId vs the mesh node's config-form id must still
|
|
295
|
+
// resolve, mirroring the remote idle-session path below (:1341).
|
|
296
|
+
const node = mesh?.nodes.find((n: any) => meshNodeIdMatches(n, nodeId));
|
|
297
|
+
|
|
298
|
+
// WORKTREE-CLAIM-GATE-BYPASS: the SINGLE claim-time gate for the worktree-bootstrap defer.
|
|
299
|
+
// tryAssignQueueTask is the one funnel every claim path flows through — the event-driven
|
|
300
|
+
// agent:ready drain, the triggerMeshQueue idle-session drain (local + remote), the
|
|
301
|
+
// auto-launch claim, and the PHASE 3 reconcile re-drain all call it. The agent:ready handler
|
|
302
|
+
// (mesh-event-forwarding) deferred its OWN claim while a worktree node's bootstrap was still
|
|
303
|
+
// 'running', but it ALSO called setRemoteIdleSession first — registering the session as a
|
|
304
|
+
// claim candidate. A concurrent triggerMeshQueue drain then pulled that candidate and claimed
|
|
305
|
+
// through tryAssignQueueTask within ~0.16s, BYPASSING the event-handler-local defer: the task
|
|
306
|
+
// dispatched into a half-built worktree (native addons not yet installed → child daemon dies
|
|
307
|
+
// → empty session, totalMessages=0). The transport ack returns ok:true, so neither the
|
|
308
|
+
// assigned-stranded watchdog nor the pending-only PHASE 3 reconcile ever re-fires it → the
|
|
309
|
+
// session is stranded empty forever.
|
|
310
|
+
//
|
|
311
|
+
// Lowering the gate HERE makes the defer a property of the claim itself, not of one caller:
|
|
312
|
+
// a worktree node whose bootstrap is still 'running' can never be claimed from any path. The
|
|
313
|
+
// task stays pending (we return false WITHOUT touching its status — no fail/cancel), so the
|
|
314
|
+
// bootstrap_complete refire (triggerMeshQueue re-fired on worktree_bootstrap_complete) re-runs
|
|
315
|
+
// this claim and passes once status is no longer 'running'. The registered remote-idle session
|
|
316
|
+
// persists for REMOTE_IDLE_SESSION_TTL_MS (5min > observed ~2m8s bootstrap), so the refire
|
|
317
|
+
// still finds a live candidate to re-claim. Identity uses meshNodeIdMatches (the same shared
|
|
318
|
+
// 3-form normalizer the defer guard uses), never a raw === — canon-identity regression guard.
|
|
319
|
+
// Conservative: any non-'running' status (idle/complete/failed/absent/unknown) does NOT gate,
|
|
320
|
+
// so a base node and a fully-bootstrapped worktree keep prior behavior exactly.
|
|
321
|
+
// COMPLETION-PROPAGATION F7 (C2 SSOT): resolve the node's bootstrap status from the router's
|
|
322
|
+
// synchronous inline cache FIRST — the authoritative source markWorktreeBootstrapTerminalState
|
|
323
|
+
// stamps synchronously — falling back to the merged claim view only when the inline node carries
|
|
324
|
+
// no bootstrap status. getMeshWithCache takes a config-REGISTERED node verbatim from local
|
|
325
|
+
// config, whose bootstrap status lags the inline stamp (the detached async persist chain), so a
|
|
326
|
+
// config-registered worktree node could read a stale 'running' here and defer a claim whose
|
|
327
|
+
// bootstrap is already complete. Reading the inline node removes that stale-'running' defer,
|
|
328
|
+
// symmetric with the remote dispatch guard (cli-agent.ts F6). Conservative: only override with
|
|
329
|
+
// the inline node when it actually carries a status (an incomplete inline entry never masks a
|
|
330
|
+
// genuine config 'running').
|
|
331
|
+
const inlineBootstrapNode = (() => {
|
|
332
|
+
try {
|
|
333
|
+
const inlineMesh = components.router?.getCachedInlineMesh?.(meshId);
|
|
334
|
+
const inlineNode = Array.isArray(inlineMesh?.nodes)
|
|
335
|
+
? inlineMesh.nodes.find((n: any) => meshNodeIdMatches(n, nodeId))
|
|
336
|
+
: undefined;
|
|
337
|
+
return readNonEmptyString(inlineNode?.worktreeBootstrap?.status) ? inlineNode : undefined;
|
|
338
|
+
} catch { return undefined; }
|
|
339
|
+
})();
|
|
340
|
+
const bootstrapGateNode = inlineBootstrapNode ?? node;
|
|
341
|
+
if ((bootstrapGateNode as { worktreeBootstrap?: { status?: string } } | undefined)?.worktreeBootstrap?.status === 'running') {
|
|
342
|
+
// Fix (3) safety net + F7: shouldDeferDispatchForBootstrap returns false when the 'running'
|
|
343
|
+
// state is stale (older than the backstop AND git-clean) — treat that as silently complete
|
|
344
|
+
// and allow the claim; otherwise defer (leave the task pending) so the claim re-fires once
|
|
345
|
+
// bootstrap reaches a terminal state and never dispatches into a half-built worktree.
|
|
346
|
+
if (!shouldDeferDispatchForBootstrap(bootstrapGateNode as any)) {
|
|
347
|
+
LOG.warn('MeshQueue', `Worktree node ${nodeId} (${sessionId}) bootstrap stuck 'running' beyond the stale backstop and its worktree is git-clean — treating bootstrap as silently complete and allowing the claim (the terminal-state stamp likely never reached this daemon's mesh view)`);
|
|
348
|
+
} else {
|
|
349
|
+
LOG.info('MeshQueue', `Gating queue claim for worktree node ${nodeId} (${sessionId}): worktree bootstrap still running — task left pending; claim re-fires once bootstrap reaches a terminal state (guards against dispatching into a half-built worktree → empty session)`);
|
|
350
|
+
return false;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// WTCLAIM (fix-B extended to the enqueue→claim path): a base-targeted task must never be
|
|
355
|
+
// claimed by — and dispatched into — a co-located worktree-clone session, nor vice versa.
|
|
356
|
+
// The drain candidate's nodeId is derived from settings.meshNodeId || settings.nodeId
|
|
357
|
+
// (triggerMeshQueue), so a worktree session whose meshNodeId is empty/stale falls back to
|
|
358
|
+
// settings.nodeId = the BASE node id and impersonates the base node here. fix-B's worker-side
|
|
359
|
+
// workspace scope only ran for sessionless dispatch (meshScopeNodeId && !targetSessionId); the
|
|
360
|
+
// claim path ALWAYS carries a targetSessionId, so it never engaged. Apply the same scope here:
|
|
361
|
+
// for a LOCAL claiming session (adapter resolvable on this daemon), require its actual
|
|
362
|
+
// workingDir to match the target node's declared workspace. On a confirmed mismatch, refuse the
|
|
363
|
+
// claim so the task returns to pending for the correctly-scoped session/node to pull. Scoped to
|
|
364
|
+
// local sessions where the workspace is verifiable — a remote session lives on another daemon
|
|
365
|
+
// whose paths we cannot compare here (and remote candidates are already nodeId-matched from
|
|
366
|
+
// getRemoteIdleSessions). Conservative by design: when either workspace is unknown we do NOT
|
|
367
|
+
// skip, so a node with no declared workspace keeps its prior behavior and no legitimate claim
|
|
368
|
+
// is starved.
|
|
369
|
+
// WTDISPATCH (residual of WTCLAIM): the cross-node claim guard must reach EVERY claiming
|
|
370
|
+
// session this daemon can observe — not only those whose adapter happens to be in
|
|
371
|
+
// cliManager.adapters. An auto-launched worker session can carry its node binding on the
|
|
372
|
+
// CLI-instance settings while its session-host record shows no_node_binding, and the
|
|
373
|
+
// event-driven / remote-idle drain (agent:ready → setRemoteIdleSession → tryAssignQueueTask)
|
|
374
|
+
// can pass a nodeId that does NOT belong to the claiming session — a sibling worktree node
|
|
375
|
+
// on the SAME daemon. The adapter-only WTCLAIM check (rc.361/4c5b30b1) never engaged for a
|
|
376
|
+
// session observed solely via instanceManager, so session A could pull node B's task and
|
|
377
|
+
// node A's task was left with no session to claim it (no task_dispatched — it never dispatches).
|
|
378
|
+
//
|
|
379
|
+
// Resolve the claiming session's REAL identity from the adapter workingDir, then fall back to
|
|
380
|
+
// the live CLI instance's workspace + its stamped meshNodeId, and refuse a claim that
|
|
381
|
+
// contradicts EITHER (fail-closed). Reuses the shared meshWorkspacesEquivalent / meshNodeIdMatches
|
|
382
|
+
// comparators — no new comparison logic. Conservative: when neither the workspace NOR the stamp
|
|
383
|
+
// is resolvable we do NOT refuse, so a node with no declared workspace keeps prior behavior and
|
|
384
|
+
// a genuinely remote (cross-daemon) candidate stays nodeId-matched from getRemoteIdleSessions.
|
|
385
|
+
const localClaimAdapter = components.cliManager?.adapters?.get(sessionId) as { workingDir?: string } | undefined;
|
|
386
|
+
let claimInstanceWorkspace = '';
|
|
387
|
+
let claimStampedNodeId = '';
|
|
388
|
+
try {
|
|
389
|
+
const claimState = components.instanceManager?.getInstance?.(sessionId)?.getState?.();
|
|
390
|
+
claimInstanceWorkspace = readNonEmptyString(claimState?.workspace);
|
|
391
|
+
const claimSettings = (claimState?.settings as Record<string, unknown>) || {};
|
|
392
|
+
claimStampedNodeId = readNonEmptyString(claimSettings.meshNodeId);
|
|
393
|
+
} catch { /* best-effort — fall through to the conservative (no refuse) path */ }
|
|
394
|
+
|
|
395
|
+
const nodeWorkspaceRaw = readNonEmptyString(node?.workspace);
|
|
396
|
+
const sessionWorkspaceRaw = readNonEmptyString(localClaimAdapter?.workingDir) || claimInstanceWorkspace;
|
|
397
|
+
|
|
398
|
+
if (claimStampedNodeId && nodeId) {
|
|
399
|
+
// The session carries its OWN meshNodeId stamp — its authoritative node identity, set when
|
|
400
|
+
// the coordinator launched/dispatched it (mesh-routing trusts this stamp FIRST). When it
|
|
401
|
+
// matches the claim target the session genuinely belongs to this node, so the stamp settles
|
|
402
|
+
// it and the workspace heuristic is skipped (a base/worktree pair can legitimately share a
|
|
403
|
+
// workspace). When it does NOT match, the claim is a cross-node leak — refuse, fail-closed.
|
|
404
|
+
if (!meshNodeIdMatches({ id: claimStampedNodeId } as MeshNodeIdentified, nodeId)) {
|
|
405
|
+
LOG.info('MeshQueue', `WTDISPATCH: refusing claim for node ${nodeId} (${sessionId}) — session is bound to node "${claimStampedNodeId}" (cross-node claim blocked)`);
|
|
406
|
+
return false;
|
|
407
|
+
}
|
|
408
|
+
} else if (sessionWorkspaceRaw && nodeWorkspaceRaw && !meshWorkspacesEquivalent(sessionWorkspaceRaw, nodeWorkspaceRaw)) {
|
|
409
|
+
// No stamp (the no_node_binding worker) — fall back to the workspace to tell two co-located
|
|
410
|
+
// sibling worktree sessions apart. WTCLAIM, now reaching instanceManager-observable sessions
|
|
411
|
+
// too. Conservative: unknown workspace on either side → do NOT refuse (no legitimate claim
|
|
412
|
+
// starved; a genuinely remote cross-daemon candidate stays nodeId-matched as before).
|
|
413
|
+
LOG.info('MeshQueue', `WTCLAIM: refusing claim for node ${nodeId} (${sessionId}) — session workspace "${normalizeMeshWorkspaceForCompare(sessionWorkspaceRaw)}" ≠ node workspace "${normalizeMeshWorkspaceForCompare(nodeWorkspaceRaw)}" (cross-workspace dispatch blocked)`);
|
|
414
|
+
return false;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const capabilityTags = buildMeshNodeCapabilityTags(node, providerType);
|
|
418
|
+
// Per-(node, provider) maxParallel cap (RepoMeshNodePolicy.providerRoles) layers
|
|
419
|
+
// on top of the global/taskMode caps — stricter wins. Resolved here where the
|
|
420
|
+
// claiming session's providerType + node policy are both known, then enforced
|
|
421
|
+
// inside the atomic claim transaction so concurrent claims can't overshoot it.
|
|
422
|
+
const providerMaxParallel = resolveProviderMaxParallel(node?.policy, providerType);
|
|
423
|
+
// WTDISPATCH-FANOUT: tell the atomic claim whether the claiming node is a worktree
|
|
424
|
+
// clone so a `convergence` task (base-only: merge → push → cleanup) is refused for
|
|
425
|
+
// worktree sessions. Without it, every sibling worktree session on this daemon could
|
|
426
|
+
// claim the same convergence intent and race push/production-deploy (the 4-way fan-out).
|
|
427
|
+
const nodeIsWorktree = node?.isLocalWorktree === true;
|
|
428
|
+
const task = claimNextTask(meshId, nodeId, sessionId, capabilityTags, {
|
|
429
|
+
providerType,
|
|
430
|
+
...(providerMaxParallel !== undefined ? { providerMaxParallel } : {}),
|
|
431
|
+
nodeIsWorktree,
|
|
432
|
+
});
|
|
433
|
+
if (!task) {
|
|
434
|
+
return false;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
const terminal = findTerminalLedgerEvidenceForTask({
|
|
438
|
+
meshId,
|
|
439
|
+
taskId: task.id,
|
|
440
|
+
});
|
|
441
|
+
if (terminal) {
|
|
442
|
+
const status = terminal.kind === 'task_completed' ? 'completed' : 'failed';
|
|
443
|
+
updateTaskStatus(meshId, task.id, status);
|
|
444
|
+
LOG.info('MeshQueue', `Skipped dispatch for terminal task ${task.id} on mesh ${meshId}; ${terminal.kind} ledger evidence already exists`);
|
|
445
|
+
traceMeshEventDrop('dispatch_terminal_ledger', {
|
|
446
|
+
taskId: task.id,
|
|
447
|
+
sessionId,
|
|
448
|
+
nodeId,
|
|
449
|
+
meshId,
|
|
450
|
+
event: 'agent_command',
|
|
451
|
+
}, terminal.kind);
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
LOG.info('MeshQueue', `Node ${nodeId} (${sessionId}) pulled task ${task.id}`);
|
|
456
|
+
|
|
457
|
+
// FALSE-BLOCKER-CLONE-QUEUE (stale-event clear): the task just claimed and will dispatch,
|
|
458
|
+
// so any actionable blocker previously paged for it (e.g. a 'target_node_id_unmatched'
|
|
459
|
+
// emitted during the clone/bootstrap propagation window before the node became
|
|
460
|
+
// claimable) is now stale — re-arm the de-dup ledger and retract any undelivered
|
|
461
|
+
// dispatch_blocked event so the coordinator does not keep seeing a resolved blocker.
|
|
462
|
+
retractActionableSkipIfPreviouslyNotified(meshId, task.id);
|
|
463
|
+
|
|
464
|
+
// CANON-IDENTITY single-flight: mark the just-claimed task in-flight the moment it
|
|
465
|
+
// is handed to a transport. The atomic claim already prevents a concurrent claim,
|
|
466
|
+
// but this lets requeueTask distinguish a genuinely-generating task (refuse the
|
|
467
|
+
// operator requeue — it would open a second session) from a stale assigned row
|
|
468
|
+
// (still requeueable). Cleared when the task leaves `assigned` (terminal / dispatch
|
|
469
|
+
// failure / cancel / reclaim).
|
|
470
|
+
beginTaskDispatchInFlight(meshId, task.id);
|
|
471
|
+
|
|
472
|
+
if (node?.daemonId && components.dispatchMeshCommand) {
|
|
473
|
+
const isLocalNode = components.cliManager.adapters.has(sessionId);
|
|
474
|
+
if (!isLocalNode) {
|
|
475
|
+
const localDaemonIdForDispatch = localCoordinatorDaemonId();
|
|
476
|
+
// (3) Originating coordinator session that enqueued this task — route its
|
|
477
|
+
// completion back to that exact session (multi-coordinator). Carried over P2P
|
|
478
|
+
// to the remote worker, which echoes it on its completion event.
|
|
479
|
+
const sourceCoordinatorSessionId = readNonEmptyString(task.sourceCoordinatorSessionId) || undefined;
|
|
480
|
+
const dispatchMeshCommand = components.dispatchMeshCommand;
|
|
481
|
+
const remoteDaemonId = node.daemonId;
|
|
482
|
+
// CONS3: only the transport call differs — everything else (delivery record,
|
|
483
|
+
// status transitions, requeue-on-failure, ledger, Bug B hang timeout) is in
|
|
484
|
+
// the shared deliverTaskToSession helper.
|
|
485
|
+
deliverTaskToSession(
|
|
486
|
+
() => dispatchMeshCommand(remoteDaemonId, 'agent_command', {
|
|
487
|
+
targetSessionId: sessionId,
|
|
488
|
+
cliType: providerType,
|
|
489
|
+
action: 'send_chat',
|
|
490
|
+
message: task.message,
|
|
491
|
+
meshContext: {
|
|
492
|
+
meshId,
|
|
493
|
+
nodeId,
|
|
494
|
+
taskId: task.id,
|
|
495
|
+
...(localDaemonIdForDispatch ? { coordinatorDaemonId: localDaemonIdForDispatch } : {}),
|
|
496
|
+
...(sourceCoordinatorSessionId ? { coordinatorSessionId: sourceCoordinatorSessionId } : {}),
|
|
497
|
+
},
|
|
498
|
+
}),
|
|
499
|
+
{
|
|
500
|
+
meshId,
|
|
501
|
+
nodeId,
|
|
502
|
+
sessionId,
|
|
503
|
+
providerType,
|
|
504
|
+
task,
|
|
505
|
+
transport: 'remote',
|
|
506
|
+
...(sourceCoordinatorSessionId ? { sourceCoordinatorSessionId } : {}),
|
|
507
|
+
...(localDaemonIdForDispatch ? { sourceCoordinatorDaemonId: localDaemonIdForDispatch } : {}),
|
|
508
|
+
},
|
|
509
|
+
// Warmup-aware deadline: this dispatch can be the FIRST command to a
|
|
510
|
+
// peer whose mesh DataChannel is still opening — charge the cold-open
|
|
511
|
+
// handshake to the connect budget, not the response budget.
|
|
512
|
+
{ daemonId: remoteDaemonId, getConnection: components.getMeshPeerConnectionStatus },
|
|
513
|
+
);
|
|
514
|
+
return true;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// Stamp mesh context onto the session so completion events route correctly
|
|
519
|
+
// via setupMeshEventForwarding. Without this, manually-opened idle sessions
|
|
520
|
+
// (mesh_launch_session without auto-launch) lack meshNodeFor/meshNodeId and
|
|
521
|
+
// agent:generating_completed is silently dropped as isMeshDelegate=false.
|
|
522
|
+
try {
|
|
523
|
+
const inst = components.instanceManager.getInstance(sessionId);
|
|
524
|
+
if (inst && typeof inst.updateSettings === 'function') {
|
|
525
|
+
// Adopting a (possibly manually-opened) local session as a worker: apply the
|
|
526
|
+
// delegated-worker auto-approve policy here too, so a session that was launched
|
|
527
|
+
// without autoApprove still auto-approves once the coordinator dispatches a task
|
|
528
|
+
// to it (the "approval notification fires only for certain delegated sessions"
|
|
529
|
+
// case). updateSettings preserves runtime mesh keys; passing autoApprove keeps it.
|
|
530
|
+
//
|
|
531
|
+
// This local-dispatch branch also runs on the coordinator daemon for a co-located
|
|
532
|
+
// session, so the coordinator daemon id IS this daemon's id. Stamp it alongside
|
|
533
|
+
// the node identity so the session is fully relay-safe (meshCoordinatorDaemonId is
|
|
534
|
+
// the anchor the forwarder keys on), matching what mesh_launch_session stamps.
|
|
535
|
+
const localDaemonId = localCoordinatorDaemonId();
|
|
536
|
+
const localSourceCoordinatorSessionId = readNonEmptyString(task.sourceCoordinatorSessionId);
|
|
537
|
+
inst.updateSettings({
|
|
538
|
+
meshNodeFor: meshId,
|
|
539
|
+
meshNodeId: nodeId,
|
|
540
|
+
launchedByCoordinator: true,
|
|
541
|
+
autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
|
|
542
|
+
...(localDaemonId ? { meshCoordinatorDaemonId: localDaemonId } : {}),
|
|
543
|
+
// COMPLETION-PROPAGATION F5: (re)stamp the coordinator SESSION anchor from THIS
|
|
544
|
+
// task's sourceCoordinatorSessionId with PRIORITY — a manually-launched (or reused)
|
|
545
|
+
// session may already carry a stale anchor from mesh_launch_session or a prior task,
|
|
546
|
+
// and a stale session anchor makes the completion unicast to the wrong/absent
|
|
547
|
+
// coordinator session (targetCoordinatorSessionId), stranding it. When this task
|
|
548
|
+
// carries a source, overwrite; when it carries NONE, CLEAR the anchor to undefined
|
|
549
|
+
// (updateSettings merges, so an explicit undefined overrides) so the completion
|
|
550
|
+
// cannot be misrouted by a stale unicast anchor and instead BROADCASTS — the real
|
|
551
|
+
// coordinator (which drains its own pending queue) then picks it up. Daemon-level
|
|
552
|
+
// routing (meshCoordinatorDaemonId above) is unaffected.
|
|
553
|
+
meshCoordinatorSessionId: localSourceCoordinatorSessionId || undefined,
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
} catch { /* best-effort — dispatch still proceeds */ }
|
|
557
|
+
|
|
558
|
+
// CONS3: same shared dispatch lifecycle as the remote branch — only the transport
|
|
559
|
+
// (cliManager.handleCliCommand) differs.
|
|
560
|
+
// ARCH-REFACTOR R1: carry meshContext (incl. taskId) on the LOCAL dispatch too, so
|
|
561
|
+
// handleCliCommand's send_chat path binds this task to its turn (per-turn identity).
|
|
562
|
+
// Previously only the remote branch shipped meshContext.taskId; the local path relied
|
|
563
|
+
// on the last-write-wins session scalar, which races a follow-up task and made the
|
|
564
|
+
// completion echo the wrong taskId (the standalone NOTIF-MISDELIVER repro).
|
|
565
|
+
deliverTaskToSession(
|
|
566
|
+
() => components.cliManager.handleCliCommand('agent_command', {
|
|
567
|
+
targetSessionId: sessionId,
|
|
568
|
+
cliType: providerType,
|
|
569
|
+
action: 'send_chat',
|
|
570
|
+
message: task.message,
|
|
571
|
+
meshContext: {
|
|
572
|
+
meshId,
|
|
573
|
+
nodeId,
|
|
574
|
+
taskId: task.id,
|
|
575
|
+
...(localCoordinatorDaemonId() ? { coordinatorDaemonId: localCoordinatorDaemonId() } : {}),
|
|
576
|
+
...(readNonEmptyString(task.sourceCoordinatorSessionId) ? { coordinatorSessionId: readNonEmptyString(task.sourceCoordinatorSessionId) } : {}),
|
|
577
|
+
},
|
|
578
|
+
}),
|
|
579
|
+
{
|
|
580
|
+
meshId,
|
|
581
|
+
nodeId,
|
|
582
|
+
sessionId,
|
|
583
|
+
providerType,
|
|
584
|
+
task,
|
|
585
|
+
transport: 'local',
|
|
586
|
+
...(readNonEmptyString(task.sourceCoordinatorSessionId) ? { sourceCoordinatorSessionId: readNonEmptyString(task.sourceCoordinatorSessionId) } : {}),
|
|
587
|
+
...(localCoordinatorDaemonId() ? { sourceCoordinatorDaemonId: localCoordinatorDaemonId() } : {}),
|
|
588
|
+
},
|
|
589
|
+
);
|
|
590
|
+
|
|
591
|
+
return true;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
const autoLaunchInProgress = new Set<string>();
|
|
595
|
+
const autoLaunchCooldownUntil = new Map<string, number>();
|
|
596
|
+
const AUTO_LAUNCH_COOLDOWN_MS = 5_000;
|
|
597
|
+
// A remote auto-launch (launch_cli forward) is fire-and-async: the worker session
|
|
598
|
+
// spawns, reaches idle, emits agent:ready, that ready is queued on the worker, pulled
|
|
599
|
+
// by this coordinator (reconcile PHASE 1), and only THEN claims the task. That round
|
|
600
|
+
// trip routinely exceeds the 5s per-(mesh,node) cooldown, so cooldown alone lets the
|
|
601
|
+
// reconcile loop fire a SECOND launch for the same still-pending task before the first
|
|
602
|
+
// session's claim lands — every tick spawns yet another orphan session (observed live:
|
|
603
|
+
// 26 sessions for one task). This is a per-TASK await-claim window: once a task has a
|
|
604
|
+
// successfully-launched session whose claim we are still waiting on, do not launch it
|
|
605
|
+
// again until the window lapses. It is generous (a slow remote spawn can take tens of
|
|
606
|
+
// seconds) but bounded so a launch that silently never reaches idle is eventually retried.
|
|
607
|
+
const AUTO_LAUNCH_AWAIT_CLAIM_MS = 90_000;
|
|
608
|
+
|
|
609
|
+
// AUTOLAUNCH-CLAIM-CHURN. For a REMOTE node the launch→claim handshake is purely
|
|
610
|
+
// event-sourced: the worker's agent:ready must be pulled (reconcile PHASE 1) to run
|
|
611
|
+
// setRemoteIdleSession before the drain can claim. If that pull is lost, nothing recovers,
|
|
612
|
+
// and after AUTO_LAUNCH_AWAIT_CLAIM_MS the loop used to blindly RESPAWN a new session — whose
|
|
613
|
+
// respawn guards (nodeHasLiveSessionPendingClaim / liveSessionCountForNode) scan only the LOCAL
|
|
614
|
+
// instanceManager, so the remote pending-claim session is invisible and a fresh ghost accumulates
|
|
615
|
+
// every ~90s (observed live 2026-07-04: task 8b188c64, and 7 ghost sessions on this worktree's
|
|
616
|
+
// own task at 11:23-11:34). Instead of respawning on window expiry, we re-drive the claim for the
|
|
617
|
+
// EXISTING session; when its liveness cannot be positively determined we EXTEND the window with
|
|
618
|
+
// exponential backoff (90 → 180 → 360s) and, only after the cap, deliver the task directly into
|
|
619
|
+
// the launched session (the mesh_send_task-equivalent) rather than spawning another worker.
|
|
620
|
+
const AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES = 2;
|
|
621
|
+
// Local mirror of REMOTE_IDLE_SESSION_TTL_MS (mesh-event-forwarding) — kept here to avoid a
|
|
622
|
+
// cross-module import cycle. Used when (re)registering a launched remote session as an idle
|
|
623
|
+
// claim candidate during the await-claim re-drive.
|
|
624
|
+
const AUTO_LAUNCH_REMOTE_IDLE_TTL_MS = 5 * 60 * 1000;
|
|
625
|
+
|
|
626
|
+
// Per-task await-claim backoff state, keyed `${meshId}::${taskId}`. `cycles` counts how many
|
|
627
|
+
// times the window has been extended; `nextAttemptAtMs` rate-limits the re-drive to the backoff
|
|
628
|
+
// cadence so the 4s reconcile tick does not hammer it. Cleared once the task claims, the direct
|
|
629
|
+
// dispatch fires, or a respawn is authorized. In-memory (per process); a stale entry is harmless
|
|
630
|
+
// (it only defers a respawn) and self-clears on the next resolution.
|
|
631
|
+
interface AwaitClaimBackoffState { cycles: number; nextAttemptAtMs: number; }
|
|
632
|
+
const autoLaunchAwaitClaimBackoff = new Map<string, AwaitClaimBackoffState>();
|
|
633
|
+
|
|
634
|
+
// Test hooks: reset / seed the await-claim backoff state between cases.
|
|
635
|
+
export function __resetAutoLaunchAwaitClaimBackoffForTests(): void {
|
|
636
|
+
autoLaunchAwaitClaimBackoff.clear();
|
|
637
|
+
}
|
|
638
|
+
export function __seedAutoLaunchAwaitClaimBackoffForTests(meshId: string, taskId: string, state: AwaitClaimBackoffState): void {
|
|
639
|
+
autoLaunchAwaitClaimBackoff.set(`${meshId}::${taskId}`, { ...state });
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// Backoff window for a given cycle count: 90 → 180 → 360s (capped at the cap-cycle multiplier).
|
|
643
|
+
function awaitClaimWindowMs(cycles: number): number {
|
|
644
|
+
return AUTO_LAUNCH_AWAIT_CLAIM_MS * Math.pow(2, Math.min(cycles, AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES));
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// Does the coordinator's remote-session view (MeshRuntimeStore remote idle sessions, populated by
|
|
648
|
+
// mesh event forwarding) currently show this session as a live idle claim candidate? Positive
|
|
649
|
+
// evidence the launched remote session is reachable — used to re-drive its claim directly instead
|
|
650
|
+
// of respawning. Absence is NOT proof the session is gone (the agent:ready pull may simply have
|
|
651
|
+
// been lost), so callers treat a false here as UNKNOWN liveness, never a definitive terminal.
|
|
652
|
+
function remoteSessionAppearsLive(meshId: string, sessionId: string): boolean {
|
|
653
|
+
if (!sessionId) return false;
|
|
654
|
+
try {
|
|
655
|
+
return MeshRuntimeStore.getInstance().getRemoteIdleSessions(meshId)
|
|
656
|
+
.some(s => sessionIdsEquivalent(s.sessionId, sessionId));
|
|
657
|
+
} catch {
|
|
658
|
+
return false;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// (A) Respawn-guard remote-awareness. The session ids of pending tasks whose auto-launch record
|
|
663
|
+
// targets `nodeId` (status started/completed with a sessionId) and is still inside its await-claim
|
|
664
|
+
// window — the base 90s window OR an active backoff extension. Such a session is ALREADY on its way
|
|
665
|
+
// to claim even when it is REMOTE (invisible to this daemon's instanceManager), so counting it
|
|
666
|
+
// suppresses a duplicate launch that would otherwise spawn a ghost.
|
|
667
|
+
function inWindowAutoLaunchSessionIdsForNode(meshId: string, nodeId: string): string[] {
|
|
668
|
+
const nowMs = Date.now();
|
|
669
|
+
const out: string[] = [];
|
|
670
|
+
for (const task of getQueue(meshId, { status: ['pending'] as any })) {
|
|
671
|
+
const al = task.autoLaunch;
|
|
672
|
+
const sid = al ? readNonEmptyString(al.sessionId) : '';
|
|
673
|
+
if (!al || (al.status !== 'started' && al.status !== 'completed') || !sid) continue;
|
|
674
|
+
if (!daemonIdsEquivalent(al.nodeId, nodeId)) continue;
|
|
675
|
+
const launchedAtMs = Date.parse(al.updatedAt);
|
|
676
|
+
const inBaseWindow = Number.isFinite(launchedAtMs) && nowMs - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS;
|
|
677
|
+
const inBackoff = autoLaunchAwaitClaimBackoff.has(`${meshId}::${task.id}`);
|
|
678
|
+
if (inBaseWindow || inBackoff) out.push(sid);
|
|
679
|
+
}
|
|
680
|
+
return out;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// De-dup for repeated `skipped` ledger noise: the reconcile loop re-runs the queue
|
|
684
|
+
// trigger every 4s, so a task that can't be claimed (e.g. a remote node with no
|
|
685
|
+
// transport, or a node under cooldown) would otherwise append an identical
|
|
686
|
+
// session_auto_launch{phase:'skipped'} entry on every tick — flooding the ledger.
|
|
687
|
+
// We suppress a `skipped` ledger append when the immediately-prior recorded event
|
|
688
|
+
// for that task was the SAME (phase, reason). Any non-skip phase (started/failed/
|
|
689
|
+
// completed) or a changed reason resets the de-dup so real transitions still record.
|
|
690
|
+
const lastAutoLaunchLedgerKey = new Map<string, string>();
|
|
691
|
+
const AUTO_LAUNCH_LEDGER_DEDUP_MAX = 2000;
|
|
692
|
+
|
|
693
|
+
// Fix (1): actionable dispatch-skip notification.
|
|
694
|
+
//
|
|
695
|
+
// User-core gap: when a queued task cannot be dispatched the coordinator (Claude Code via
|
|
696
|
+
// MCP) had no proactive signal — the skip was only recorded to task.autoLaunch + the ledger,
|
|
697
|
+
// both of which the coordinator must poll to discover. For a skip that will NOT self-resolve
|
|
698
|
+
// (a routing miss, no capable node, a convergence task pinned to a worktree, an unusable
|
|
699
|
+
// provider, an unreachable remote, or a dirty workspace) the coordinator could sit waiting
|
|
700
|
+
// for a dispatch that can never happen. We now actively surface those — and ONLY those — as a
|
|
701
|
+
// pending coordinator event carrying a "why + how to act" message, routed to the originating
|
|
702
|
+
// coordinator (sourceCoordinator*). Transient/back-pressure skips (cooldown, in-progress,
|
|
703
|
+
// awaiting-claim, parallel/session caps, node not yet launch-ready, an active assignment) are
|
|
704
|
+
// deliberately excluded: they clear on their own and would only spam the coordinator every 4s.
|
|
705
|
+
const ACTIONABLE_SKIP_REASON_PREFIXES = [
|
|
706
|
+
'target_node_id_unmatched',
|
|
707
|
+
'no_node_satisfies_required_tags',
|
|
708
|
+
'mesh_convergence_target_is_worktree',
|
|
709
|
+
'remote_auto_launch_unsupported',
|
|
710
|
+
'remote_auto_launch_no_coordinator_daemon_id',
|
|
711
|
+
'missing_provider_priority',
|
|
712
|
+
'provider_loader_unavailable',
|
|
713
|
+
'provider_priority_unusable',
|
|
714
|
+
'provider_unusable',
|
|
715
|
+
'dirty_workspace',
|
|
716
|
+
];
|
|
717
|
+
|
|
718
|
+
// FALSE-BLOCKER-CLONE-QUEUE: the TRANSIENT counterpart of 'target_node_id_unmatched'. A
|
|
719
|
+
// queue task pinned to a freshly cloned worktree node can transiently find no matching node
|
|
720
|
+
// (its inline-cache entry has not propagated to this coordinator daemon yet, and/or its
|
|
721
|
+
// worktree bootstrap is still running). That unmatch SELF-RESOLVES — it is not the permanent
|
|
722
|
+
// routing miss the actionable blocker exists for — so it is deliberately NOT listed in
|
|
723
|
+
// ACTIONABLE_SKIP_REASON_PREFIXES: isActionableSkipReason() returns false for it, so no
|
|
724
|
+
// "actionable blocker — will NOT clear on its own" coordinator page is emitted. The skip is
|
|
725
|
+
// still recorded to task.autoLaunch + the ledger for diagnosability.
|
|
726
|
+
const TRANSIENT_TARGET_NODE_BOOTSTRAP_PENDING_REASON = 'target_node_bootstrap_pending';
|
|
727
|
+
|
|
728
|
+
// De-dup actionable-skip coordinator notifications: emit once per (mesh, task) until the
|
|
729
|
+
// reason CHANGES, so the 4s reconcile loop re-marking the same skip does not re-notify. A
|
|
730
|
+
// non-skip transition (or a genuine reason change) re-arms it. In-memory only — a daemon
|
|
731
|
+
// restart re-notifies once, which is the correct behaviour after a restart.
|
|
732
|
+
const lastActionableSkipNotified = new Map<string, string>();
|
|
733
|
+
|
|
734
|
+
function isActionableSkipReason(reason?: string): boolean {
|
|
735
|
+
if (!reason) return false;
|
|
736
|
+
return ACTIONABLE_SKIP_REASON_PREFIXES.some(prefix => reason === prefix || reason.startsWith(prefix));
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* FALSE-BLOCKER-CLONE-QUEUE: a target pin is TRANSIENTLY (not permanently) unresolved when
|
|
741
|
+
* the pinned node is a freshly cloned worktree that will auto-claim once its bootstrap
|
|
742
|
+
* completes / its inline-cache entry propagates — as opposed to a removed/dead node whose
|
|
743
|
+
* unmatch is a permanent, actionable routing miss. Two signals, either suffices:
|
|
744
|
+
* (a) the node IS visible in the (cache-merged) mesh view but its worktree bootstrap is
|
|
745
|
+
* still 'running' (and not stuck past the stale backstop), or
|
|
746
|
+
* (b) the node is NOT visible here yet, but a clone for its id was issued within the grace
|
|
747
|
+
* window (propagation/bootstrap latency) — see mesh-clone-grace.
|
|
748
|
+
* Conservative: a node neither bootstrap-running nor recently cloned → returns false, so a
|
|
749
|
+
* genuinely dead node keeps its permanent, actionable 'target_node_id_unmatched'.
|
|
750
|
+
*/
|
|
751
|
+
function isTargetNodeTransientlyUnresolved(mesh: any, task: MeshWorkQueueEntry): boolean {
|
|
752
|
+
const targetNodeId = readNonEmptyString(task.targetNodeId);
|
|
753
|
+
if (!targetNodeId) return false;
|
|
754
|
+
const node = Array.isArray(mesh?.nodes)
|
|
755
|
+
? mesh.nodes.find((n: any) => meshNodeIdMatches(n, targetNodeId))
|
|
756
|
+
: undefined;
|
|
757
|
+
if (node
|
|
758
|
+
&& (node as { worktreeBootstrap?: { status?: string } }).worktreeBootstrap?.status === 'running'
|
|
759
|
+
&& !isWorktreeBootstrapStaleRunning(node)) {
|
|
760
|
+
return true;
|
|
761
|
+
}
|
|
762
|
+
return isWithinCloneBootstrapGrace(targetNodeId);
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* FALSE-BLOCKER-CLONE-QUEUE (stale-event clear): once a task whose actionable blocker we
|
|
767
|
+
* previously paged either gets claimed or transitions to a self-resolving state, re-arm the
|
|
768
|
+
* de-dup ledger (so a later genuine blocker re-notifies) AND retract any still-undelivered
|
|
769
|
+
* dispatch_blocked pending event, so the coordinator's pending queue no longer carries the
|
|
770
|
+
* stale "will NOT clear on its own" warning. Cheap: only touches the pending store when this
|
|
771
|
+
* (mesh, task) actually had a prior actionable notification recorded.
|
|
772
|
+
*/
|
|
773
|
+
function retractActionableSkipIfPreviouslyNotified(meshId: string, taskId: string): void {
|
|
774
|
+
const dedupKey = `${meshId}:${taskId}`;
|
|
775
|
+
if (!lastActionableSkipNotified.delete(dedupKey)) return; // nothing was paged → nothing to retract
|
|
776
|
+
try {
|
|
777
|
+
const coordinatorDaemonId = readNonEmptyString(loadConfig().machineId) || undefined;
|
|
778
|
+
const removed = retractPendingDispatchBlockedEvent(meshId, taskId, coordinatorDaemonId);
|
|
779
|
+
if (removed > 0) {
|
|
780
|
+
LOG.info('MeshQueue', `Retracted ${removed} stale dispatch-blocked event(s) for task ${taskId} (mesh ${meshId}) — its blocker resolved`);
|
|
781
|
+
}
|
|
782
|
+
} catch (e: any) {
|
|
783
|
+
LOG.warn('MeshQueue', `Failed to retract stale dispatch-blocked event for task ${taskId} (mesh ${meshId}): ${e?.message || e}`);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
function actionableSkipGuidance(reason: string): { summary: string; nextAction: string } {
|
|
788
|
+
if (reason === 'target_node_id_unmatched') return {
|
|
789
|
+
summary: 'it is pinned to a target node id that matches no node in the mesh (the node may have been removed, or its id form does not resolve)',
|
|
790
|
+
nextAction: 'Verify the target node still exists with mesh_status, then re-enqueue without the node pin or with a valid node id (or re-clone the node).',
|
|
791
|
+
};
|
|
792
|
+
if (reason === 'no_node_satisfies_required_tags') return {
|
|
793
|
+
summary: "no node in the mesh can satisfy the task's required capability tags",
|
|
794
|
+
nextAction: "Relax the task's requiredTags, or add/launch a node whose provider produces the required capabilities.",
|
|
795
|
+
};
|
|
796
|
+
if (reason === 'mesh_convergence_target_is_worktree') return {
|
|
797
|
+
summary: 'it is a convergence task (base-only: merge → push → cleanup) but every candidate node is a worktree clone',
|
|
798
|
+
nextAction: 'Dispatch the convergence task to the base node, or run the deterministic fast-forward path (mesh_fast_forward_node / mesh_refine_node) instead.',
|
|
799
|
+
};
|
|
800
|
+
if (reason.startsWith('remote_auto_launch')) return {
|
|
801
|
+
summary: 'the target node is on a remote daemon this coordinator cannot auto-launch a session on (no dispatch transport, or no coordinator daemon id to stamp)',
|
|
802
|
+
nextAction: 'Launch a session on that node yourself with mesh_launch_session, or ensure the remote daemon is connected over P2P.',
|
|
803
|
+
};
|
|
804
|
+
if (reason.startsWith('provider') || reason === 'missing_provider_priority') return {
|
|
805
|
+
summary: 'the node has no usable provider for this task (provider priority missing/unusable, or the provider loader is unavailable)',
|
|
806
|
+
nextAction: "Check the node's providerPriority policy and that the required CLI/ACP provider is installed and enabled on that machine.",
|
|
807
|
+
};
|
|
808
|
+
if (reason === 'dirty_workspace') return {
|
|
809
|
+
summary: "the node's workspace is dirty, so auto-launch is blocked to avoid clobbering uncommitted changes",
|
|
810
|
+
nextAction: "Clean or commit the node's working tree (or fast-forward it); the task will then auto-assign.",
|
|
811
|
+
};
|
|
812
|
+
return {
|
|
813
|
+
summary: `it cannot be dispatched (${reason})`,
|
|
814
|
+
nextAction: 'Inspect the node/mesh state with mesh_status and resolve the blocker, or re-enqueue the task.',
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/** Surface a non-self-resolving dispatch skip to the originating coordinator as a pending
|
|
819
|
+
* event (so it is delivered actively, not only on poll). De-duped per (mesh, task, reason). */
|
|
820
|
+
function notifyCoordinatorOfActionableSkip(meshId: string, taskId: string, reason: string | undefined, nodeId?: string): void {
|
|
821
|
+
if (!isActionableSkipReason(reason)) return;
|
|
822
|
+
// FALSE-BLOCKER-CLONE-QUEUE chokepoint defense: a 'target_node_id_unmatched' skip whose
|
|
823
|
+
// node was cloned within the grace window is a TRANSIENT propagation/bootstrap gap that
|
|
824
|
+
// auto-clears, not a permanent routing miss — never page the coordinator for it (the
|
|
825
|
+
// reason classifier upstream already routes the common case to the transient reason; this
|
|
826
|
+
// is the single-funnel backstop for any path that still labels it as the permanent reason).
|
|
827
|
+
if (reason === 'target_node_id_unmatched' && isWithinCloneBootstrapGrace(readNonEmptyString(nodeId))) return;
|
|
828
|
+
const dedupKey = `${meshId}:${taskId}`;
|
|
829
|
+
if (lastActionableSkipNotified.get(dedupKey) === reason) return;
|
|
830
|
+
lastActionableSkipNotified.set(dedupKey, reason!);
|
|
831
|
+
if (lastActionableSkipNotified.size > AUTO_LAUNCH_LEDGER_DEDUP_MAX) {
|
|
832
|
+
const oldest = lastActionableSkipNotified.keys().next().value;
|
|
833
|
+
if (oldest !== undefined) lastActionableSkipNotified.delete(oldest);
|
|
834
|
+
}
|
|
835
|
+
let task: MeshWorkQueueEntry | undefined;
|
|
836
|
+
try { task = getQueue(meshId).find(t => t.id === taskId); } catch { /* best-effort */ }
|
|
837
|
+
// The queue is owned by this coordinator daemon, so scope the event to this daemon's id;
|
|
838
|
+
// the originating coordinator SESSION (if known) further narrows delivery on this daemon.
|
|
839
|
+
const targetCoordinatorDaemonId = readNonEmptyString(loadConfig().machineId);
|
|
840
|
+
const targetCoordinatorSessionId = readNonEmptyString(task?.sourceCoordinatorSessionId);
|
|
841
|
+
const nodeLabel = readNonEmptyString(nodeId) || readNonEmptyString(task?.targetNodeId);
|
|
842
|
+
const { summary, nextAction } = actionableSkipGuidance(reason!);
|
|
843
|
+
const coordinatorMessage = `[System] A queued mesh task${nodeLabel ? ` for node ${nodeLabel}` : ''} is not being dispatched because ${summary}. ${nextAction} This is an actionable blocker — it will NOT clear on its own; the task stays pending until you resolve it.`;
|
|
844
|
+
try {
|
|
845
|
+
queuePendingMeshCoordinatorEvent({
|
|
846
|
+
event: 'mesh:dispatch_blocked',
|
|
847
|
+
meshId,
|
|
848
|
+
nodeLabel: nodeLabel || meshId,
|
|
849
|
+
...(nodeLabel ? { nodeId: nodeLabel } : {}),
|
|
850
|
+
metadataEvent: {
|
|
851
|
+
source: 'mesh_queue_dispatch_skip',
|
|
852
|
+
taskId,
|
|
853
|
+
reason,
|
|
854
|
+
...(nodeLabel ? { nodeId: nodeLabel } : {}),
|
|
855
|
+
coordinatorMessage,
|
|
856
|
+
},
|
|
857
|
+
coordinatorMessage,
|
|
858
|
+
queuedAt: Date.now(),
|
|
859
|
+
...(targetCoordinatorDaemonId ? { targetCoordinatorDaemonId } : {}),
|
|
860
|
+
...(targetCoordinatorSessionId ? { targetCoordinatorSessionId } : {}),
|
|
861
|
+
});
|
|
862
|
+
} catch (e: any) {
|
|
863
|
+
LOG.warn('MeshQueue', `Failed to surface actionable dispatch-skip (${reason}) for task ${taskId}: ${e?.message || e}`);
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
function sweepExpiredCooldowns(): void {
|
|
868
|
+
const now = Date.now();
|
|
869
|
+
for (const [key, until] of autoLaunchCooldownUntil) {
|
|
870
|
+
if (now >= until) autoLaunchCooldownUntil.delete(key);
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
function normalizeProviderPriority(policy: unknown): string[] {
|
|
875
|
+
const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
|
|
876
|
+
? (policy as Record<string, unknown>).providerPriority
|
|
877
|
+
: undefined;
|
|
878
|
+
if (!Array.isArray(raw)) return [];
|
|
879
|
+
const seen = new Set<string>();
|
|
880
|
+
return raw
|
|
881
|
+
.map(type => typeof type === 'string' ? type.trim() : '')
|
|
882
|
+
.filter(Boolean)
|
|
883
|
+
.filter(type => {
|
|
884
|
+
if (seen.has(type)) return false;
|
|
885
|
+
seen.add(type);
|
|
886
|
+
return true;
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
function isTerminalSessionStatus(status: string): boolean {
|
|
891
|
+
return ['stopped', 'failed', 'terminated', 'exited', 'closed'].includes(status);
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
function isIdleSessionState(state: any): boolean {
|
|
895
|
+
const status = readNonEmptyString(state?.status).toLowerCase();
|
|
896
|
+
if (isTerminalSessionStatus(status)) return false;
|
|
897
|
+
return status === 'idle' || state?.activeChat?.status === 'waiting_input';
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
function isDirtyNode(node: any): boolean {
|
|
901
|
+
return node?.health === 'dirty' || node?.git?.dirty === true;
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
function resolveAutoFastForwardPolicy(mesh: any): { enabled: boolean; maxBehind?: number; requireCleanSubmodules: boolean } {
|
|
905
|
+
const record = mesh?.policy?.autoFastForward && typeof mesh.policy.autoFastForward === 'object' && !Array.isArray(mesh.policy.autoFastForward)
|
|
906
|
+
? mesh.policy.autoFastForward as Record<string, unknown>
|
|
907
|
+
: {};
|
|
908
|
+
const maxBehind = Number(record.maxBehind);
|
|
909
|
+
return {
|
|
910
|
+
enabled: record.enabled !== false,
|
|
911
|
+
...(Number.isFinite(maxBehind) && maxBehind >= 0 ? { maxBehind: Math.floor(maxBehind) } : {}),
|
|
912
|
+
requireCleanSubmodules: record.requireCleanSubmodules !== false,
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
function sessionStateLooksActive(state: any): boolean {
|
|
917
|
+
const status = readNonEmptyString(state?.status).toLowerCase();
|
|
918
|
+
const chatStatus = readNonEmptyString(state?.activeChat?.status).toLowerCase();
|
|
919
|
+
// 'long_generating' is retained as a legacy alias for the renamed 'no_progress' busy status.
|
|
920
|
+
const active = new Set(['generating', 'streaming', 'no_progress', 'long_generating', 'working', 'starting', 'waiting_approval']);
|
|
921
|
+
return active.has(status) || active.has(chatStatus);
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
function nodeHasActiveMeshWork(components: DaemonComponents, meshId: string, nodeId: string, currentSessionId?: string): boolean {
|
|
925
|
+
if (nodeHasActiveAssignment(meshId, nodeId)) return true;
|
|
926
|
+
return components.instanceManager.getByCategory('cli').some((inst: any) => {
|
|
927
|
+
const state = inst.getState();
|
|
928
|
+
const settings = state.settings as Record<string, unknown> || {};
|
|
929
|
+
if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
|
|
930
|
+
const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
|
|
931
|
+
// Match under canonical machine-core form, NOT a raw `!==`: a session's stamped
|
|
932
|
+
// meshNodeId and the candidate nodeId can carry interchangeable daemon-id forms
|
|
933
|
+
// (bare `mach_X` vs `daemon_mach_X`). A raw mismatch makes a BUSY node look idle,
|
|
934
|
+
// so the active-work gate passes and a SECOND session is launched/claimed for a
|
|
935
|
+
// task already running here — the CANON-IDENTITY duplicate dispatch.
|
|
936
|
+
if (!daemonIdsEquivalent(instNodeId, nodeId)) return false;
|
|
937
|
+
const sessionId = readNonEmptyString(state.instanceId);
|
|
938
|
+
if (currentSessionId && sessionIdsEquivalent(sessionId, currentSessionId) && isIdleSessionState(state)) return false;
|
|
939
|
+
return sessionStateLooksActive(state);
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
function isLaunchableNode(node: any): boolean {
|
|
944
|
+
if (!node || node.status === 'disabled' || node.status === 'removed') return false;
|
|
945
|
+
const health = readNonEmptyString(node.health).toLowerCase();
|
|
946
|
+
if (!health) return true;
|
|
947
|
+
return health === 'online' || health === 'unknown';
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/** Whether a mesh node's daemon/machine identity resolves to THIS coordinator daemon
|
|
951
|
+
* (i.e. the queue session can be spawned by a direct local `launch_cli`). */
|
|
952
|
+
function isLocalAutoLaunchNode(node: any): boolean {
|
|
953
|
+
const daemonId = readNonEmptyString(node?.daemonId);
|
|
954
|
+
const machineId = readNonEmptyString(node?.machineId);
|
|
955
|
+
const appConfig = loadConfig();
|
|
956
|
+
const localMachineId = readNonEmptyString(appConfig.machineId) || readNonEmptyString(appConfig.registeredMachineId);
|
|
957
|
+
|
|
958
|
+
// Route BOTH the daemonId and the machineId through the canonical machine-core
|
|
959
|
+
// equivalence helper so a node carrying any interchangeable id form (bare `mach_<hex>`
|
|
960
|
+
// or a `daemon_`/`standalone_` prefixed form) resolves to THIS coordinator instead of
|
|
961
|
+
// being misjudged as remote. machineId used to use a raw `===`, which — AND-combined
|
|
962
|
+
// with the daemonId match — would misjudge a local node as remote whenever a
|
|
963
|
+
// form-mismatched machineId arrived, dispatching a local task to a remote node (B-2).
|
|
964
|
+
const daemonMatchesLocal = !daemonId || daemonIdsEquivalent(daemonId, localMachineId);
|
|
965
|
+
const machineMatchesLocal = !machineId || daemonIdsEquivalent(machineId, localMachineId);
|
|
966
|
+
|
|
967
|
+
if (node?.isLocalWorktree === true) {
|
|
968
|
+
return daemonMatchesLocal && machineMatchesLocal;
|
|
969
|
+
}
|
|
970
|
+
if (daemonId || machineId) {
|
|
971
|
+
return daemonMatchesLocal && machineMatchesLocal;
|
|
972
|
+
}
|
|
973
|
+
return true;
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
/**
|
|
977
|
+
* Resolve how a pending queue task should be auto-launched onto a node.
|
|
978
|
+
*
|
|
979
|
+
* - `local`: spawn directly on this daemon via cliManager.handleCliCommand('launch_cli').
|
|
980
|
+
* - `remote`: forward `launch_cli` to the node's daemon via dispatchMeshCommand
|
|
981
|
+
* (mirrors what mesh_launch_session does). Requires dispatchMeshCommand AND a
|
|
982
|
+
* resolvable coordinator daemonId for relay-safe completion routing.
|
|
983
|
+
* - `skip`: not launchable from here — carries the reason (e.g. a remote node with
|
|
984
|
+
* no dispatch transport, or no coordinator daemonId to stamp).
|
|
985
|
+
*/
|
|
986
|
+
function resolveAutoLaunchTarget(components: DaemonComponents, node: any): {
|
|
987
|
+
mode: 'local' | 'remote' | 'skip';
|
|
988
|
+
reason?: string;
|
|
989
|
+
daemonId?: string;
|
|
990
|
+
coordinatorDaemonId?: string;
|
|
991
|
+
} {
|
|
992
|
+
if (isLocalAutoLaunchNode(node)) return { mode: 'local' };
|
|
993
|
+
|
|
994
|
+
// Remote node. Forwarding the launch is possible only with a dispatch transport
|
|
995
|
+
// (cloud mode) plus a coordinator daemonId to stamp into the worker so completion
|
|
996
|
+
// events route back here. Without either, fall back to a graceful skip.
|
|
997
|
+
const daemonId = readNonEmptyString(node?.daemonId);
|
|
998
|
+
if (!daemonId) return { mode: 'skip', reason: 'remote_auto_launch_unsupported' };
|
|
999
|
+
if (!components.dispatchMeshCommand) return { mode: 'skip', reason: 'remote_auto_launch_unsupported' };
|
|
1000
|
+
// CANON: stamp the canonical `daemon_mach_` coordinator anchor onto the remote
|
|
1001
|
+
// worker (meshCoordinatorDaemonId) so its completion forwards back under the same
|
|
1002
|
+
// form every other dispatch path uses — no producer-side coordinator-id skew.
|
|
1003
|
+
const coordinatorDaemonId = localCoordinatorDaemonId();
|
|
1004
|
+
if (!coordinatorDaemonId) return { mode: 'skip', reason: 'remote_auto_launch_no_coordinator_daemon_id' };
|
|
1005
|
+
return { mode: 'remote', daemonId, coordinatorDaemonId };
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
function activeAssignedCount(meshId: string): number {
|
|
1009
|
+
return getQueue(meshId, { status: ['assigned'] as any }).length;
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
/** Active assignments that hold the one-active-per-node / global-parallel invariant
|
|
1013
|
+
* (everything except read-only diagnoses, which run unbounded by the write cap). */
|
|
1014
|
+
export function activeWriteAssignedCount(meshId: string): number {
|
|
1015
|
+
return getQueue(meshId, { status: ['assigned'] as any })
|
|
1016
|
+
.filter(task => !isTaskReadonly(task)).length;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
/** Active read-only assignments, for the read-only safety cap. */
|
|
1020
|
+
export function activeReadonlyAssignedCount(meshId: string): number {
|
|
1021
|
+
return getQueue(meshId, { status: ['assigned'] as any })
|
|
1022
|
+
.filter(isTaskReadonly).length;
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
function nodeHasActiveAssignment(meshId: string, nodeId: string): boolean {
|
|
1026
|
+
// Canonical-form match, NOT a raw `===`: an assigned row stamped in one daemon-id
|
|
1027
|
+
// form (e.g. `daemon_mach_X`) must still register as this node's active work when
|
|
1028
|
+
// the candidate nodeId arrives bare (`mach_X`). A raw mismatch makes the node look
|
|
1029
|
+
// free, letting a second write task auto-launch onto an already-busy node and
|
|
1030
|
+
// breaking the one-write-per-node (worktree isolation) invariant.
|
|
1031
|
+
return getQueue(meshId, { status: ['assigned'] as any }).some(task => daemonIdsEquivalent(task.assignedNodeId, nodeId));
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
/** Active (status='assigned') task count for a node — the load metric for
|
|
1035
|
+
* least-loaded / round-robin ranking. Lower = preferred. */
|
|
1036
|
+
function nodeActiveLoad(meshId: string, nodeId: string): number {
|
|
1037
|
+
return MeshRuntimeStore.getInstance().nodeActiveAssignmentCount(meshId, nodeId);
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/**
|
|
1041
|
+
* The mesh-wide scheduling strategy, read from the MACHINE-LOCAL stored mesh
|
|
1042
|
+
* policy. Resolution order:
|
|
1043
|
+
* 1. the stored mesh policy schedulingStrategy raw 4-union, then
|
|
1044
|
+
* 2. 'first_eligible' (strict no-change default).
|
|
1045
|
+
* Policy is machine-local only — there is no repo-file (`.adhdev/mesh.json`)
|
|
1046
|
+
* overlay. Only governs the final tie-break; eligibility, capacity, and priority
|
|
1047
|
+
* gates apply identically to every strategy.
|
|
1048
|
+
*/
|
|
1049
|
+
function resolveSchedulingStrategy(mesh: any): RepoMeshSchedulingStrategy {
|
|
1050
|
+
return normalizeMeshSchedulingStrategy(mesh?.policy?.schedulingStrategy);
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
/**
|
|
1054
|
+
* Order eligible nodes for assignment per the mesh scheduling pipeline:
|
|
1055
|
+
* PRIORITY (schedulingPriority desc) → TIE-BREAK (strategy).
|
|
1056
|
+
*
|
|
1057
|
+
* The caller has already applied the TAG hard-filter and is responsible for the
|
|
1058
|
+
* MAX-ALLOC capacity gate (the per-node launch/claim checks). This function only
|
|
1059
|
+
* decides the *preference order* among nodes that are otherwise eligible.
|
|
1060
|
+
*
|
|
1061
|
+
* - 'first_eligible' (default): returns the input order verbatim and does NOT touch
|
|
1062
|
+
* the round-robin cursor — byte-for-byte the pre-feature behavior.
|
|
1063
|
+
* - 'priority_only': schedulingPriority desc, then input order (load ignored).
|
|
1064
|
+
* - 'least_loaded' (the user-facing 'spread' mode): schedulingPriority desc, then
|
|
1065
|
+
* active load asc, then — among nodes still tied at (priority, load) — the input
|
|
1066
|
+
* order is rotated by a per-mesh cursor that advances once per pass. The rotation
|
|
1067
|
+
* tie-break is ALWAYS on for least_loaded so a single 'spread' mode subsumes the
|
|
1068
|
+
* former separate 'round_robin' strategy (two equal-load nodes still alternate
|
|
1069
|
+
* fairly across passes instead of the lower index always winning).
|
|
1070
|
+
* - 'round_robin': retained as an escape-hatch alias; behaves identically to
|
|
1071
|
+
* 'least_loaded' now that least_loaded carries the rotation.
|
|
1072
|
+
*
|
|
1073
|
+
* `nodes` carries the original config/array index so the tie-break can fall back to
|
|
1074
|
+
* deterministic input order. `bumpCursor` advances the round-robin cursor exactly
|
|
1075
|
+
* once per scheduling pass (consulted for both 'least_loaded' and 'round_robin').
|
|
1076
|
+
*/
|
|
1077
|
+
interface RankableNode { nodeId: string; node: any; index: number }
|
|
1078
|
+
|
|
1079
|
+
/** Test-only: resolve a mesh's effective scheduling strategy through the full
|
|
1080
|
+
* LOCAL-WINS path (`.adhdev/mesh.json` distribution → strategy, else stored policy).
|
|
1081
|
+
* Exposed so the repo-file overlay wiring can be exercised by a direct call. */
|
|
1082
|
+
export function __resolveSchedulingStrategyForTests(mesh: any): RepoMeshSchedulingStrategy {
|
|
1083
|
+
return resolveSchedulingStrategy(mesh);
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
/** Test-only: the pure node-ordering stage (PRIORITY → TIE-BREAK). Exposed so the
|
|
1087
|
+
* scheduling pipeline can be unit-tested without standing up live CLI sessions. */
|
|
1088
|
+
export function __orderEligibleNodesForTests(
|
|
1089
|
+
meshId: string,
|
|
1090
|
+
strategy: RepoMeshSchedulingStrategy,
|
|
1091
|
+
nodes: RankableNode[],
|
|
1092
|
+
opts?: { bumpCursor?: boolean },
|
|
1093
|
+
): RankableNode[] {
|
|
1094
|
+
return orderEligibleNodes(meshId, strategy, nodes, opts);
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
/** One idle session eligible to claim a queued task, together with the resolved
|
|
1098
|
+
* mesh node record it belongs to. Local candidates come from live CLI instances,
|
|
1099
|
+
* remote candidates from the registered remote-idle-session store; the two arrive
|
|
1100
|
+
* with their `nodeId` under different serialization forms. */
|
|
1101
|
+
type IdleCandidate = { nodeId: string; sessionId: string; providerType: string; origin: 'local' | 'remote'; node: any };
|
|
1102
|
+
|
|
1103
|
+
/**
|
|
1104
|
+
* Merge local + remote idle candidates into the scheduling pool with a single,
|
|
1105
|
+
* form-canonical node identity.
|
|
1106
|
+
*
|
|
1107
|
+
* INVARIANT: every candidate in the returned pool carries its `nodeId` in
|
|
1108
|
+
* CANONICAL (normalized) form, and `uniqueNodes` has exactly one entry per
|
|
1109
|
+
* physical node. Local and remote candidates arrive with their `nodeId` under
|
|
1110
|
+
* mixed forms (config `id`, wire `nodeId`, DB `node_id`). Downstream scheduling
|
|
1111
|
+
* keys the pool by raw-string equality (Set dedup, baseIndex, rankIndex,
|
|
1112
|
+
* nodeActiveLoad), so two candidates for the SAME physical node under two
|
|
1113
|
+
* different forms would otherwise be treated as two distinct nodes — form-drift
|
|
1114
|
+
* that splits a node's load and double-ranks it. Canonicalizing here (via the
|
|
1115
|
+
* resolved node record, which meshNodeIdMatches already matched form-agnostically)
|
|
1116
|
+
* makes every later `=== nodeId` comparison operate on one agreed form. Falls back
|
|
1117
|
+
* to the raw candidate id when the node is unresolved (an unresolved candidate
|
|
1118
|
+
* cannot be normalized, but also has no sibling to collide with).
|
|
1119
|
+
*/
|
|
1120
|
+
function buildSchedulingPool(
|
|
1121
|
+
localCandidates: IdleCandidate[],
|
|
1122
|
+
remoteCandidates: IdleCandidate[],
|
|
1123
|
+
): { pool: IdleCandidate[]; uniqueNodes: RankableNode[] } {
|
|
1124
|
+
const pool = [...localCandidates, ...remoteCandidates].map(c => ({
|
|
1125
|
+
...c,
|
|
1126
|
+
nodeId: normalizeMeshNodeId(c.node) ?? c.nodeId,
|
|
1127
|
+
}));
|
|
1128
|
+
// Both sides are canonical now, so raw `===` in the Set dedup and the node
|
|
1129
|
+
// re-lookup is form-safe.
|
|
1130
|
+
const uniqueNodes: RankableNode[] = [...new Set(pool.map(c => c.nodeId))]
|
|
1131
|
+
.map((nodeId, index) => ({
|
|
1132
|
+
nodeId,
|
|
1133
|
+
node: pool.find(c => meshNodeIdMatches({ id: c.nodeId } as MeshNodeIdentified, nodeId))?.node,
|
|
1134
|
+
index,
|
|
1135
|
+
}));
|
|
1136
|
+
return { pool, uniqueNodes };
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
/** Test-only: the pool-canonicalization + unique-node collapse stage. Exposed so
|
|
1140
|
+
* the mixed-form dedup invariant can be unit-tested without a live daemon. */
|
|
1141
|
+
export function __buildSchedulingPoolForTests(
|
|
1142
|
+
localCandidates: IdleCandidate[],
|
|
1143
|
+
remoteCandidates: IdleCandidate[],
|
|
1144
|
+
): { pool: IdleCandidate[]; uniqueNodes: RankableNode[] } {
|
|
1145
|
+
return buildSchedulingPool(localCandidates, remoteCandidates);
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
function orderEligibleNodes(
|
|
1149
|
+
meshId: string,
|
|
1150
|
+
strategy: RepoMeshSchedulingStrategy,
|
|
1151
|
+
nodes: RankableNode[],
|
|
1152
|
+
opts?: { bumpCursor?: boolean },
|
|
1153
|
+
): RankableNode[] {
|
|
1154
|
+
if (strategy === 'first_eligible' || nodes.length <= 1) {
|
|
1155
|
+
return nodes;
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
const priorityOf = (n: { node: any }) => resolveNodeSchedulingPriority(n.node?.policy);
|
|
1159
|
+
|
|
1160
|
+
// Round-robin rotation offset: rotate the deterministic input order by a
|
|
1161
|
+
// per-mesh cursor so the tie-break winner among equal (priority, load) nodes
|
|
1162
|
+
// cycles across passes. The cursor advances once per scheduling pass. Applied
|
|
1163
|
+
// to both 'least_loaded' (the 'spread' mode — rotation absorbed as its
|
|
1164
|
+
// tie-break) and the legacy 'round_robin' alias.
|
|
1165
|
+
let rotation = 0;
|
|
1166
|
+
if (strategy === 'least_loaded' || strategy === 'round_robin') {
|
|
1167
|
+
const cursor = opts?.bumpCursor
|
|
1168
|
+
? MeshRuntimeStore.getInstance().bumpSchedulerCursor(meshId)
|
|
1169
|
+
: MeshRuntimeStore.getInstance().getSchedulerCursor(meshId);
|
|
1170
|
+
rotation = ((cursor % nodes.length) + nodes.length) % nodes.length;
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
// Rotation rank: position of each node after rotating input order by `rotation`.
|
|
1174
|
+
// For non-round-robin strategies rotation is 0, so this is just the input index.
|
|
1175
|
+
const rotationRank = (index: number) => (index - rotation + nodes.length) % nodes.length;
|
|
1176
|
+
|
|
1177
|
+
return [...nodes].sort((a, b) => {
|
|
1178
|
+
const prioDelta = priorityOf(b) - priorityOf(a); // higher priority first
|
|
1179
|
+
if (prioDelta !== 0) return prioDelta;
|
|
1180
|
+
if (strategy === 'least_loaded' || strategy === 'round_robin') {
|
|
1181
|
+
const loadDelta = nodeActiveLoad(meshId, a.nodeId) - nodeActiveLoad(meshId, b.nodeId);
|
|
1182
|
+
if (loadDelta !== 0) return loadDelta;
|
|
1183
|
+
}
|
|
1184
|
+
return rotationRank(a.index) - rotationRank(b.index);
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
/** Active assignments on a (node, provider) — pre-launch guard for the per-(node,
|
|
1189
|
+
* provider) maxParallel cap. The authoritative enforcement is in the claim
|
|
1190
|
+
* transaction; this only avoids spawning a session that would fail the claim. */
|
|
1191
|
+
function activeProviderAssignedCount(meshId: string, nodeId: string, providerType: string): number {
|
|
1192
|
+
return getQueue(meshId, { status: ['assigned'] as any })
|
|
1193
|
+
.filter(task => daemonIdsEquivalent(task.assignedNodeId, nodeId) && task.assignedProviderType === providerType).length;
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
export function sessionHasActiveAssignment(meshId: string, sessionId: string): boolean {
|
|
1197
|
+
if (getQueue(meshId, { status: ['assigned'] as any }).some(task => sessionIdsEquivalent(task.assignedSessionId, sessionId))) {
|
|
1198
|
+
return true;
|
|
1199
|
+
}
|
|
1200
|
+
// Direct dispatches (mesh_send_task) are tracked in mesh_direct_dispatches, not the
|
|
1201
|
+
// work queue. A session completing a still-active direct dispatch IS an active
|
|
1202
|
+
// assignment — without this, findRecentTerminalLedgerEvidence dedup wrongly suppresses
|
|
1203
|
+
// the canonical agent:generating_completed for direct-dispatch tasks (validation/general),
|
|
1204
|
+
// so the coordinator polling get_pending_mesh_events never observes task_completed and the
|
|
1205
|
+
// session goes silently idle. This check runs before markSessionTerminal marks the
|
|
1206
|
+
// dispatch terminal, so the in-flight dispatch is still observable here.
|
|
1207
|
+
try {
|
|
1208
|
+
if (getActiveDirectDispatches(meshId).some(d => sessionIdsEquivalent(d.sessionId, sessionId))) return true;
|
|
1209
|
+
if (hasUnterminalDirectDispatchLedgerEntry(meshId, sessionId)) return true;
|
|
1210
|
+
} catch { /* best-effort — fall through to false */ }
|
|
1211
|
+
return false;
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
/**
|
|
1215
|
+
* CANON-IDENTITY single-flight hardening (restart-safe, observation-based).
|
|
1216
|
+
*
|
|
1217
|
+
* The in-memory single-flight Set (mesh-task-inflight) is process-local and is LOST on a
|
|
1218
|
+
* daemon restart — after a restart, a task still being generated by a live local worker is
|
|
1219
|
+
* no longer marked in-flight, so requeueTask's Set check passes and would re-open the task
|
|
1220
|
+
* for a duplicate second dispatch. This recovers the "still generating" signal from
|
|
1221
|
+
* observable runtime state instead of the in-memory mark: a session is actively generating
|
|
1222
|
+
* when its live local CLI instance reports an active (generating/streaming/…) status — the
|
|
1223
|
+
* same predicate the dispatch active-work gate uses (sessionStateLooksActive).
|
|
1224
|
+
*
|
|
1225
|
+
* Local-only by design: it inspects THIS daemon's instanceManager. The primary cross-process
|
|
1226
|
+
* fix (IpcTransport requeue delegating to the mesh-host daemon) keeps begin (dispatch) and
|
|
1227
|
+
* check (requeue guard) co-located so the in-memory mark stays authoritative in the common
|
|
1228
|
+
* path; this is the restart-safety net for sessions hosted on this daemon. A genuinely
|
|
1229
|
+
* dead/stale session is not generating → returns false → the requeue proceeds as before.
|
|
1230
|
+
*/
|
|
1231
|
+
export function isSessionActivelyGenerating(components: DaemonComponents, sessionId: string): boolean {
|
|
1232
|
+
if (!sessionId) return false;
|
|
1233
|
+
const state = components.instanceManager?.getInstance?.(sessionId)?.getState?.();
|
|
1234
|
+
if (!state) return false;
|
|
1235
|
+
return sessionStateLooksActive(state);
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
/**
|
|
1239
|
+
* RECLAIM-FALSEPOS tri-state busy verdict for a session id.
|
|
1240
|
+
*
|
|
1241
|
+
* The binary isSessionActivelyGenerating() folds "absence of a positive generating
|
|
1242
|
+
* signal" into a definitive NEGATIVE (returns false when the instance is absent). But a
|
|
1243
|
+
* REMOTE session (never in THIS daemon's instanceManager) — or a locally-present session
|
|
1244
|
+
* looked up under a skewed id form — then looks "not generating" and can be reclaimed out
|
|
1245
|
+
* from under a worker that is genuinely mid-turn. This resolves an explicit three-way
|
|
1246
|
+
* verdict instead:
|
|
1247
|
+
* - GENERATING — a locally-present instance reports an active/streaming state.
|
|
1248
|
+
* - IDLE_CONFIRMED — a locally-present instance reports a non-active (idle/terminal)
|
|
1249
|
+
* state. Positive local evidence the worker is not working.
|
|
1250
|
+
* - UNKNOWN — no locally-present instance matches (remote / gone / id-skew) or
|
|
1251
|
+
* the observation failed. NEVER treated as IDLE_CONFIRMED.
|
|
1252
|
+
*
|
|
1253
|
+
* The lookup scans getByCategory('cli') with sessionIdsEquivalent (the same equivalence
|
|
1254
|
+
* matching nodeHasActiveMeshWork / liveSessionCountForNode use) rather than a raw
|
|
1255
|
+
* instanceManager.getInstance(id) Map.get, so an id-form-skewed but present session is
|
|
1256
|
+
* found (closing the same id-form-skew hole class e245c2f9's F1 fixed elsewhere).
|
|
1257
|
+
*/
|
|
1258
|
+
export type SessionBusyVerdict = 'GENERATING' | 'IDLE_CONFIRMED' | 'UNKNOWN';
|
|
1259
|
+
export function resolveSessionBusyVerdict(components: DaemonComponents, sessionId: string): SessionBusyVerdict {
|
|
1260
|
+
if (!sessionId) return 'UNKNOWN';
|
|
1261
|
+
try {
|
|
1262
|
+
const instances = components.instanceManager?.getByCategory?.('cli') || [];
|
|
1263
|
+
const inst = instances.find((i: any) => {
|
|
1264
|
+
const sid = readNonEmptyString(i?.getState?.().instanceId);
|
|
1265
|
+
return sid && sessionIdsEquivalent(sid, sessionId);
|
|
1266
|
+
});
|
|
1267
|
+
if (!inst) return 'UNKNOWN'; // remote / gone / id-form skew not present locally
|
|
1268
|
+
const state = inst.getState?.();
|
|
1269
|
+
if (!state) return 'UNKNOWN';
|
|
1270
|
+
return sessionStateLooksActive(state) ? 'GENERATING' : 'IDLE_CONFIRMED';
|
|
1271
|
+
} catch {
|
|
1272
|
+
return 'UNKNOWN'; // failed observation ⇒ unknown, never a definitive idle
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
function liveSessionCountForNode(components: DaemonComponents, meshId: string, nodeId: string): number {
|
|
1277
|
+
const localInstances = components.instanceManager.getByCategory('cli').filter((inst: any) => {
|
|
1278
|
+
const state = inst.getState();
|
|
1279
|
+
const settings = state.settings as Record<string, unknown> || {};
|
|
1280
|
+
if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
|
|
1281
|
+
const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
|
|
1282
|
+
// Canonical-form match (see nodeHasActiveMeshWork): a daemon-id form skew between
|
|
1283
|
+
// the session's stamped nodeId and the candidate nodeId must not undercount this
|
|
1284
|
+
// node's live sessions, which would defeat the maxConcurrentSessions cap.
|
|
1285
|
+
if (!daemonIdsEquivalent(instNodeId, nodeId)) return false;
|
|
1286
|
+
const status = readNonEmptyString(state.status).toLowerCase();
|
|
1287
|
+
return !isTerminalSessionStatus(status);
|
|
1288
|
+
});
|
|
1289
|
+
let count = localInstances.length;
|
|
1290
|
+
// (A) AUTOLAUNCH-CLAIM-CHURN: also count launched-but-not-yet-claimed sessions targeting this
|
|
1291
|
+
// node whose await-claim window is still open. A REMOTE such session is invisible to the local
|
|
1292
|
+
// instanceManager above, so without this the maxConcurrentSessions cap undercounts it and a
|
|
1293
|
+
// duplicate ghost launch slips through. Exclude any id already represented by a local instance
|
|
1294
|
+
// so a co-located launch is not double-counted.
|
|
1295
|
+
const localSessionIds = localInstances
|
|
1296
|
+
.map((inst: any) => readNonEmptyString(inst.getState().instanceId))
|
|
1297
|
+
.filter(Boolean);
|
|
1298
|
+
for (const sid of inWindowAutoLaunchSessionIdsForNode(meshId, nodeId)) {
|
|
1299
|
+
if (!localSessionIds.some(local => sessionIdsEquivalent(local, sid))) count += 1;
|
|
1300
|
+
}
|
|
1301
|
+
return count;
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
/**
|
|
1305
|
+
* DOUBLE-DISPATCH auto-launch gate: does this node already have a LIVE mesh session that
|
|
1306
|
+
* is NOT holding an assigned queue task — i.e. one that is idle, booting toward its first
|
|
1307
|
+
* claim, or in a momentary non-idle flip? Such a session WILL claim a still-pending task
|
|
1308
|
+
* on its own via the idle→claim / agent:ready drain, so spawning a NEW session here only
|
|
1309
|
+
* races it and yields a duplicate worker that double-stamps the same taskId (the
|
|
1310
|
+
* enqueue → drain-miss → auto-launch RCA: the drain skipped a momentarily-non-idle idle
|
|
1311
|
+
* session as a candidate, and the write-only nodeHasActiveAssignment gate — which only
|
|
1312
|
+
* inspects status='assigned' rows — could not see the about-to-claim session either).
|
|
1313
|
+
*
|
|
1314
|
+
* A session that already HOLDS an assigned queue task is genuine concurrent work, not a
|
|
1315
|
+
* free claimer, and is excluded — so a read-only auto-launch onto a busy-but-no-idle node
|
|
1316
|
+
* is still allowed. A node with NO live mesh session at all (dead, or never launched) does
|
|
1317
|
+
* not match, preserving the legitimate first-session spawn.
|
|
1318
|
+
*/
|
|
1319
|
+
function nodeHasLiveSessionPendingClaim(components: DaemonComponents, meshId: string, nodeId: string): boolean {
|
|
1320
|
+
// (A) AUTOLAUNCH-CLAIM-CHURN remote-awareness: a task whose auto-launch record targets this
|
|
1321
|
+
// node and is still inside its await-claim window (base or backoff) already has a session on
|
|
1322
|
+
// its way to claim — even when that session is REMOTE and thus invisible to the local
|
|
1323
|
+
// instanceManager scan below. Treat it as a live pending-claim session so a duplicate launch
|
|
1324
|
+
// is suppressed and no ghost accumulates every ~90s.
|
|
1325
|
+
if (inWindowAutoLaunchSessionIdsForNode(meshId, nodeId).length > 0) return true;
|
|
1326
|
+
// Session ids currently holding an assigned queue task on this node — those are busy,
|
|
1327
|
+
// not pending claimers, so they must NOT suppress a (read-only) launch.
|
|
1328
|
+
const busySessionIds = new Set(
|
|
1329
|
+
getQueue(meshId, { status: ['assigned'] as any })
|
|
1330
|
+
.filter(task => daemonIdsEquivalent(task.assignedNodeId, nodeId))
|
|
1331
|
+
.map(task => readNonEmptyString(task.assignedSessionId))
|
|
1332
|
+
.filter(Boolean),
|
|
1333
|
+
);
|
|
1334
|
+
return components.instanceManager.getByCategory('cli').some((inst: any) => {
|
|
1335
|
+
const state = inst.getState();
|
|
1336
|
+
const settings = state.settings as Record<string, unknown> || {};
|
|
1337
|
+
if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
|
|
1338
|
+
const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
|
|
1339
|
+
// Canonical-form match (see nodeHasActiveMeshWork / liveSessionCountForNode): a
|
|
1340
|
+
// daemon-id form skew must not make a present session look absent and reopen the
|
|
1341
|
+
// duplicate-launch hole.
|
|
1342
|
+
if (!daemonIdsEquivalent(instNodeId, nodeId)) return false;
|
|
1343
|
+
const status = readNonEmptyString(state.status).toLowerCase();
|
|
1344
|
+
if (isTerminalSessionStatus(status)) return false; // dead → no claimer here, allow launch
|
|
1345
|
+
const sessionId = readNonEmptyString(state.instanceId);
|
|
1346
|
+
if (sessionId && busySessionIds.has(sessionId)) return false; // busy with its own assigned task
|
|
1347
|
+
return true; // live + unassigned → will claim the pending task itself
|
|
1348
|
+
});
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
function recordAutoLaunchEvent(meshId: string, args: {
|
|
1352
|
+
phase: 'skipped' | 'started' | 'failed' | 'completed';
|
|
1353
|
+
taskId: string;
|
|
1354
|
+
nodeId?: string;
|
|
1355
|
+
providerType?: string;
|
|
1356
|
+
sessionId?: string;
|
|
1357
|
+
reason?: string;
|
|
1358
|
+
error?: string;
|
|
1359
|
+
}) {
|
|
1360
|
+
// Suppress consecutive identical `skipped` entries for the same task (4s reconcile
|
|
1361
|
+
// re-trigger noise). Non-skip phases and changed reasons always record and reset
|
|
1362
|
+
// the de-dup so genuine state transitions remain visible in the ledger.
|
|
1363
|
+
const dedupKey = `${meshId}:${args.taskId}`;
|
|
1364
|
+
const currentSig = `${args.phase}|${args.reason || ''}`;
|
|
1365
|
+
if (args.phase === 'skipped' && lastAutoLaunchLedgerKey.get(dedupKey) === currentSig) {
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
lastAutoLaunchLedgerKey.set(dedupKey, currentSig);
|
|
1369
|
+
if (lastAutoLaunchLedgerKey.size > AUTO_LAUNCH_LEDGER_DEDUP_MAX) {
|
|
1370
|
+
// Bound memory: drop the oldest insertion (Map preserves insertion order).
|
|
1371
|
+
const oldest = lastAutoLaunchLedgerKey.keys().next().value;
|
|
1372
|
+
if (oldest !== undefined) lastAutoLaunchLedgerKey.delete(oldest);
|
|
1373
|
+
}
|
|
1374
|
+
try {
|
|
1375
|
+
appendLedgerEntry(meshId, {
|
|
1376
|
+
kind: 'session_auto_launch',
|
|
1377
|
+
nodeId: args.nodeId,
|
|
1378
|
+
sessionId: args.sessionId,
|
|
1379
|
+
providerType: args.providerType,
|
|
1380
|
+
payload: {
|
|
1381
|
+
phase: args.phase,
|
|
1382
|
+
taskId: args.taskId,
|
|
1383
|
+
reason: args.reason,
|
|
1384
|
+
error: args.error,
|
|
1385
|
+
},
|
|
1386
|
+
});
|
|
1387
|
+
} catch (e: any) {
|
|
1388
|
+
LOG.warn('MeshQueue', `Failed to record auto-launch ledger event: ${e?.message || e}`);
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
function markAutoLaunch(meshId: string, taskId: string, args: {
|
|
1393
|
+
status: 'skipped' | 'started' | 'failed' | 'completed';
|
|
1394
|
+
reason?: string;
|
|
1395
|
+
nodeId?: string;
|
|
1396
|
+
providerType?: string;
|
|
1397
|
+
sessionId?: string;
|
|
1398
|
+
error?: string;
|
|
1399
|
+
}) {
|
|
1400
|
+
recordTaskAutoLaunch(meshId, taskId, {
|
|
1401
|
+
status: args.status,
|
|
1402
|
+
reason: args.reason || args.error,
|
|
1403
|
+
nodeId: args.nodeId,
|
|
1404
|
+
providerType: args.providerType,
|
|
1405
|
+
sessionId: args.sessionId,
|
|
1406
|
+
});
|
|
1407
|
+
recordAutoLaunchEvent(meshId, {
|
|
1408
|
+
phase: args.status,
|
|
1409
|
+
taskId,
|
|
1410
|
+
nodeId: args.nodeId,
|
|
1411
|
+
providerType: args.providerType,
|
|
1412
|
+
sessionId: args.sessionId,
|
|
1413
|
+
reason: args.reason,
|
|
1414
|
+
error: args.error,
|
|
1415
|
+
});
|
|
1416
|
+
// Fix (1): actively notify the coordinator of a non-self-resolving skip; re-arm the
|
|
1417
|
+
// notification on any non-skip transition (started/completed) so a later genuine skip
|
|
1418
|
+
// re-notifies.
|
|
1419
|
+
if (args.status === 'skipped') {
|
|
1420
|
+
if (isActionableSkipReason(args.reason)) {
|
|
1421
|
+
notifyCoordinatorOfActionableSkip(meshId, taskId, args.reason, args.nodeId);
|
|
1422
|
+
} else if (args.reason === TRANSIENT_TARGET_NODE_BOOTSTRAP_PENDING_REASON) {
|
|
1423
|
+
// FALSE-BLOCKER-CLONE-QUEUE (stale-event clear): the unmatch is now known to be a
|
|
1424
|
+
// self-resolving clone/bootstrap window — retract any earlier actionable blocker we
|
|
1425
|
+
// paged for this same task. Other transient/back-pressure reasons (cooldown, caps)
|
|
1426
|
+
// intentionally do NOT retract: they can mask a still-standing real blocker.
|
|
1427
|
+
retractActionableSkipIfPreviouslyNotified(meshId, taskId);
|
|
1428
|
+
}
|
|
1429
|
+
} else {
|
|
1430
|
+
// started/completed: the task is progressing — re-arm the de-dup ledger and retract
|
|
1431
|
+
// any still-undelivered stale blocker for it.
|
|
1432
|
+
retractActionableSkipIfPreviouslyNotified(meshId, taskId);
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
async function resolveUsableProvider(
|
|
1437
|
+
components: DaemonComponents,
|
|
1438
|
+
nodeId: string,
|
|
1439
|
+
node: any,
|
|
1440
|
+
requiredTags?: string[],
|
|
1441
|
+
): Promise<{ providerType?: string; reason?: string }> {
|
|
1442
|
+
const providerPriority = normalizeProviderPriority(node?.policy);
|
|
1443
|
+
if (!providerPriority.length) return { reason: 'missing_provider_priority' };
|
|
1444
|
+
const providerLoader = components.providerLoader;
|
|
1445
|
+
if (!providerLoader) return { reason: 'provider_loader_unavailable' };
|
|
1446
|
+
|
|
1447
|
+
const failed: string[] = [];
|
|
1448
|
+
for (const requestedType of providerPriority) {
|
|
1449
|
+
const normalizedType = typeof providerLoader.resolveAlias === 'function'
|
|
1450
|
+
? providerLoader.resolveAlias(requestedType)
|
|
1451
|
+
: requestedType;
|
|
1452
|
+
// Skip providers that can't satisfy the task's requiredTags (e.g. provider=hermes-cli
|
|
1453
|
+
// means only hermes-cli qualifies, not any other type in providerPriority).
|
|
1454
|
+
if (requiredTags?.length && !nodeSatisfiesRequiredTags(requiredTags, buildMeshNodeCapabilityTags(node, normalizedType))) {
|
|
1455
|
+
failed.push(`${requestedType}: required_tags_mismatch`);
|
|
1456
|
+
continue;
|
|
1457
|
+
}
|
|
1458
|
+
if (typeof providerLoader.isMachineProviderEnabled === 'function' && !providerLoader.isMachineProviderEnabled(normalizedType)) {
|
|
1459
|
+
failed.push(`${requestedType}: disabled`);
|
|
1460
|
+
continue;
|
|
1461
|
+
}
|
|
1462
|
+
let detected: any;
|
|
1463
|
+
try {
|
|
1464
|
+
detected = await detectCLI(normalizedType, providerLoader, { includeVersion: false });
|
|
1465
|
+
} catch (e: any) {
|
|
1466
|
+
failed.push(`${requestedType}: detect failed: ${e?.message || e}`);
|
|
1467
|
+
continue;
|
|
1468
|
+
}
|
|
1469
|
+
if (typeof providerLoader.setCliDetectionResults === 'function') {
|
|
1470
|
+
providerLoader.setCliDetectionResults([{
|
|
1471
|
+
id: normalizedType,
|
|
1472
|
+
installed: !!detected,
|
|
1473
|
+
path: detected?.path,
|
|
1474
|
+
}], false);
|
|
1475
|
+
}
|
|
1476
|
+
(components as any).onStatusChange?.();
|
|
1477
|
+
if (detected) return { providerType: normalizedType };
|
|
1478
|
+
failed.push(`${requestedType}: not detected`);
|
|
1479
|
+
}
|
|
1480
|
+
return { reason: `provider_priority_unusable: ${failed.join('; ') || nodeId}` };
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
// Canonical mesh node-id normalization. A node may arrive from the local config
|
|
1484
|
+
// form (`id`) or the inline-cache form (`nodeId`/`node_id`) — see
|
|
1485
|
+
// readInlineMeshNodeId in commands/router.ts. Comparing only `node.id` against a
|
|
1486
|
+
// task.targetNodeId silently drops inline-cached worktree nodes, leaving a
|
|
1487
|
+
// target-routed task permanently pending with a misleading
|
|
1488
|
+
// `no_node_satisfies_required_tags` skip.
|
|
1489
|
+
function readMeshNodeId(node: any): string {
|
|
1490
|
+
// Delegate to the shared 3-way (id / nodeId / node_id) normalizer so this
|
|
1491
|
+
// and every other mesh node-id read agree on identity. Coalesce to '' to
|
|
1492
|
+
// preserve the existing string return contract for callers that do
|
|
1493
|
+
// `=== task.targetNodeId` / `if (!nodeId)`.
|
|
1494
|
+
return normalizeMeshNodeId(node) ?? '';
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
// AUTOLAUNCH-CLAIM-CHURN. The await-claim window for a launched (remote) session has expired
|
|
1498
|
+
// without a claim. Instead of a blind respawn, re-drive the claim for the EXISTING session,
|
|
1499
|
+
// backing off when its liveness is unknown, and only respawning when it is provably unclaimable.
|
|
1500
|
+
// Returns a directive for the caller:
|
|
1501
|
+
// - 'claimed' — the re-drive claimed/dispatched the task into the existing session (progress).
|
|
1502
|
+
// - 'fallback' — the post-cap direct dispatch delivered the task into the existing session.
|
|
1503
|
+
// - 'backoff' — liveness unknown; the window was extended (or is still cooling down). No launch.
|
|
1504
|
+
// - 'respawn' — the session is provably gone/unclaimable; the caller may launch a fresh one.
|
|
1505
|
+
function driveExpiredAwaitClaim(
|
|
1506
|
+
components: DaemonComponents,
|
|
1507
|
+
meshId: string,
|
|
1508
|
+
task: MeshWorkQueueEntry,
|
|
1509
|
+
ctx: { sessionId: string; nodeId: string; providerType: string },
|
|
1510
|
+
): 'claimed' | 'fallback' | 'backoff' | 'respawn' {
|
|
1511
|
+
const { sessionId, nodeId, providerType } = ctx;
|
|
1512
|
+
const backoffKey = `${meshId}::${task.id}`;
|
|
1513
|
+
const nowMs = Date.now();
|
|
1514
|
+
const state = autoLaunchAwaitClaimBackoff.get(backoffKey) || { cycles: 0, nextAttemptAtMs: 0 };
|
|
1515
|
+
// Rate-limit re-drive attempts to the backoff cadence so the 4s reconcile tick does not hammer
|
|
1516
|
+
// a still-cooling-down window. The initial (no-state) expiry proceeds immediately.
|
|
1517
|
+
if (state.nextAttemptAtMs && nowMs < state.nextAttemptAtMs) return 'backoff';
|
|
1518
|
+
|
|
1519
|
+
const atCap = state.cycles >= AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES;
|
|
1520
|
+
const live = remoteSessionAppearsLive(meshId, sessionId);
|
|
1521
|
+
|
|
1522
|
+
// (B) Re-drive when the remote view shows the session live; (C) after the backoff cap, force the
|
|
1523
|
+
// same direct dispatch unconditionally. Both funnel through tryAssignQueueTask, which
|
|
1524
|
+
// idempotently (re)registers the session, delivers the task message (send_chat), and marks the
|
|
1525
|
+
// row assigned — the exact operation a coordinator performs manually via mesh_send_task. (D)
|
|
1526
|
+
// The setRemoteIdleSession re-register makes this robust to a dropped agent:ready.
|
|
1527
|
+
if ((live || atCap) && nodeId && providerType) {
|
|
1528
|
+
try {
|
|
1529
|
+
MeshRuntimeStore.getInstance().setRemoteIdleSession(meshId, nodeId, sessionId, providerType, nowMs + AUTO_LAUNCH_REMOTE_IDLE_TTL_MS);
|
|
1530
|
+
} catch { /* best-effort re-register */ }
|
|
1531
|
+
const assigned = tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType);
|
|
1532
|
+
if (assigned) {
|
|
1533
|
+
autoLaunchAwaitClaimBackoff.delete(backoffKey);
|
|
1534
|
+
const isFallback = atCap && !live;
|
|
1535
|
+
recordAutoLaunchEvent(meshId, {
|
|
1536
|
+
phase: 'completed',
|
|
1537
|
+
taskId: task.id,
|
|
1538
|
+
reason: isFallback ? 'await_claim_direct_dispatch_fallback' : 'await_claim_redriven',
|
|
1539
|
+
nodeId,
|
|
1540
|
+
sessionId,
|
|
1541
|
+
});
|
|
1542
|
+
// Content-free progress line (ids only).
|
|
1543
|
+
LOG.info('MeshQueue', `Auto-launch await-claim ${isFallback ? 'direct-dispatch fallback' : 're-drive'} claimed task ${task.id} into existing session ${sessionId} on node ${nodeId} (mesh ${meshId})`);
|
|
1544
|
+
return isFallback ? 'fallback' : 'claimed';
|
|
1545
|
+
}
|
|
1546
|
+
if (atCap) {
|
|
1547
|
+
// The forced dispatch could not claim — the session is genuinely gone/unclaimable.
|
|
1548
|
+
// Authorize a fresh respawn (ghosts were already prevented through the backoff window).
|
|
1549
|
+
autoLaunchAwaitClaimBackoff.delete(backoffKey);
|
|
1550
|
+
return 'respawn';
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
// Liveness unknown (or live-but-not-claimable) and not at cap → extend the window with backoff.
|
|
1554
|
+
const cycles = Math.min(state.cycles + 1, AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES);
|
|
1555
|
+
autoLaunchAwaitClaimBackoff.set(backoffKey, { cycles, nextAttemptAtMs: nowMs + awaitClaimWindowMs(cycles) });
|
|
1556
|
+
recordAutoLaunchEvent(meshId, { phase: 'skipped', taskId: task.id, reason: 'awaiting_launched_session_claim_backoff', nodeId, sessionId });
|
|
1557
|
+
return 'backoff';
|
|
1558
|
+
}
|
|
1559
|
+
|
|
1560
|
+
async function maybeAutoLaunchOneQueueSession(components: DaemonComponents, meshId: string, mesh: any): Promise<boolean> {
|
|
1561
|
+
const queue = getQueue(meshId);
|
|
1562
|
+
// DEPENDSON-GATE-SYMMETRY: status index over the FULL queue (incl. completed)
|
|
1563
|
+
// so the dependency gate below sees the terminal state of every referenced
|
|
1564
|
+
// dependency, not just the still-active rows.
|
|
1565
|
+
const statusById = new Map(queue.map(task => [task.id, task.status] as const));
|
|
1566
|
+
const pending = queue.filter(task => task.status === 'pending');
|
|
1567
|
+
// AUTOLAUNCH-CLAIM-CHURN: prune await-claim backoff state for tasks of this mesh that are no
|
|
1568
|
+
// longer pending (claimed/completed/cancelled) so the map cannot grow without bound.
|
|
1569
|
+
{
|
|
1570
|
+
const pendingIds = new Set(pending.map(t => t.id));
|
|
1571
|
+
const prefix = `${meshId}::`;
|
|
1572
|
+
for (const key of [...autoLaunchAwaitClaimBackoff.keys()]) {
|
|
1573
|
+
if (key.startsWith(prefix) && !pendingIds.has(key.slice(prefix.length))) autoLaunchAwaitClaimBackoff.delete(key);
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
if (!pending.length) return false;
|
|
1577
|
+
|
|
1578
|
+
// Write cap + read-only cap resolved through the shared helpers from the
|
|
1579
|
+
// MACHINE-LOCAL stored mesh policy (no repo-file overlay). These are the same
|
|
1580
|
+
// resolvers the observability projection uses, so the enforced and exposed
|
|
1581
|
+
// caps can never drift.
|
|
1582
|
+
const maxParallelTasks = resolveMaxParallelTasks(mesh?.policy?.maxParallelTasks);
|
|
1583
|
+
// Read-only diagnoses carry no isolation/merge cost, so they are exempt from the
|
|
1584
|
+
// write-task parallel cap. To prevent runaway auto-launch they get their own,
|
|
1585
|
+
// higher safety cap (default 2× the write cap).
|
|
1586
|
+
const maxReadonlyParallelTasks = resolveMaxReadonlyParallelTasks(maxParallelTasks);
|
|
1587
|
+
for (const task of pending) {
|
|
1588
|
+
// DEPENDSON-GATE-SYMMETRY: never spawn a session for a task whose
|
|
1589
|
+
// dependsOn set is not all-completed (or that carries a system block). The
|
|
1590
|
+
// launched session would idle→claim and be refused by the SAME predicate in
|
|
1591
|
+
// claimNextQueueTask, producing orphan-session / re-launch churn. Skip it so
|
|
1592
|
+
// a later tick — after the dependency completes — launches it. Tasks with no
|
|
1593
|
+
// dependsOn pass through unchanged (predicate is true).
|
|
1594
|
+
if (!taskDependenciesSatisfied(task, statusById)) {
|
|
1595
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'dependencies_unsatisfied' });
|
|
1596
|
+
continue;
|
|
1597
|
+
}
|
|
1598
|
+
const isReadonly = isTaskReadonly(task);
|
|
1599
|
+
if (isReadonly) {
|
|
1600
|
+
if (activeReadonlyAssignedCount(meshId) >= maxReadonlyParallelTasks) {
|
|
1601
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_readonly_parallel_tasks_reached' });
|
|
1602
|
+
continue;
|
|
1603
|
+
}
|
|
1604
|
+
} else if (activeWriteAssignedCount(meshId) >= maxParallelTasks) {
|
|
1605
|
+
// Write tasks are capped; skip this one but keep scanning so a later
|
|
1606
|
+
// read-only task in the queue can still launch under its own cap.
|
|
1607
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_parallel_tasks_reached' });
|
|
1608
|
+
continue;
|
|
1609
|
+
}
|
|
1610
|
+
if (task.targetSessionId) {
|
|
1611
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'target_session_constraint' });
|
|
1612
|
+
continue;
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
// Per-task await-claim guard. A prior auto-launch already spawned a session for
|
|
1616
|
+
// this task and we are waiting for that session's idle→claim to land (remote
|
|
1617
|
+
// claims arrive via the worker→coordinator agent:ready pull, which can lag well
|
|
1618
|
+
// past the per-node cooldown). Re-launching now would spawn a duplicate orphan
|
|
1619
|
+
// session that never gets work. The task leaves `pending` the instant the claim
|
|
1620
|
+
// succeeds, so this guard only suppresses the in-flight window; if the launched
|
|
1621
|
+
// session never reaches idle within the window, a later tick retries.
|
|
1622
|
+
if (task.autoLaunch?.status === 'completed' && task.autoLaunch.sessionId) {
|
|
1623
|
+
const launchedAtMs = Date.parse(task.autoLaunch.updatedAt);
|
|
1624
|
+
const alSessionId = readNonEmptyString(task.autoLaunch.sessionId);
|
|
1625
|
+
const alNodeId = readNonEmptyString(task.autoLaunch.nodeId);
|
|
1626
|
+
const alProvider = readNonEmptyString(task.autoLaunch.providerType);
|
|
1627
|
+
if (Number.isFinite(launchedAtMs) && Date.now() - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS) {
|
|
1628
|
+
// Record the skip in the ledger ONLY (dedup'd). Do NOT call markAutoLaunch
|
|
1629
|
+
// here: recordTaskAutoLaunch overwrites task.autoLaunch wholesale, which would
|
|
1630
|
+
// erase the very `completed` record (status + sessionId + updatedAt) this guard
|
|
1631
|
+
// reads on the next tick, reopening the duplicate-launch hole it closes.
|
|
1632
|
+
recordAutoLaunchEvent(meshId, { phase: 'skipped', taskId: task.id, reason: 'awaiting_launched_session_claim', nodeId: alNodeId, sessionId: alSessionId });
|
|
1633
|
+
continue;
|
|
1634
|
+
}
|
|
1635
|
+
// AUTOLAUNCH-CLAIM-CHURN: the initial await-claim window expired. Rather than a blind
|
|
1636
|
+
// respawn (which the local-only respawn guards can't dedup for a remote pending-claim
|
|
1637
|
+
// session → ghost accumulation), re-drive the claim for the EXISTING launched session,
|
|
1638
|
+
// backing off on unknown liveness and direct-dispatching after the cap. Only a
|
|
1639
|
+
// 'respawn' directive falls through to a fresh launch below.
|
|
1640
|
+
if (Number.isFinite(launchedAtMs) && alSessionId && alNodeId) {
|
|
1641
|
+
const outcome = driveExpiredAwaitClaim(components, meshId, task, { sessionId: alSessionId, nodeId: alNodeId, providerType: alProvider });
|
|
1642
|
+
if (outcome === 'claimed' || outcome === 'fallback') return true; // progress; suppress a duplicate launch
|
|
1643
|
+
if (outcome === 'backoff') continue; // window extended; no respawn
|
|
1644
|
+
// outcome === 'respawn' → session provably gone; proceed to a fresh launch below.
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
const candidateNodes = Array.isArray(mesh?.nodes)
|
|
1649
|
+
? mesh.nodes.filter((node: any) => {
|
|
1650
|
+
// Bug A: match the target pin with the shared 3-form (id / nodeId / node_id)
|
|
1651
|
+
// normalizer, mirroring the remote-idle drain (meshNodeIdMatches at the
|
|
1652
|
+
// getRemoteIdleSessions filter). A strict `readMeshNodeId(node) !== targetNodeId`
|
|
1653
|
+
// dropped a target node whose identity arrived under a different form (a freshly
|
|
1654
|
+
// mesh_clone_node'd worktree), emptying candidateNodes and mislabelling the skip.
|
|
1655
|
+
if (task.targetNodeId && !meshNodeIdMatches(node, task.targetNodeId)) return false;
|
|
1656
|
+
// WTDISPATCH-FANOUT: a convergence task is base-only (it merges/pushes onto
|
|
1657
|
+
// base). Never auto-launch a worktree-clone session for it — that is the very
|
|
1658
|
+
// fan-out the claim guard refuses, so spinning the session up would only waste
|
|
1659
|
+
// a launch that can never claim. Mirrors claimNextQueueTask's convergence gate.
|
|
1660
|
+
if (task.taskMode === 'convergence' && node?.isLocalWorktree === true) return false;
|
|
1661
|
+
// Skip nodes that can never satisfy requiredTags regardless of which provider
|
|
1662
|
+
// from providerPriority is selected. A node satisfies tags if at least one
|
|
1663
|
+
// provider in its priority list would produce matching capability tags.
|
|
1664
|
+
if (task.requiredTags?.length) {
|
|
1665
|
+
const priorities = normalizeProviderPriority(node?.policy);
|
|
1666
|
+
const providerCandidates = priorities.length ? priorities : [undefined as unknown as string];
|
|
1667
|
+
return providerCandidates.some(p =>
|
|
1668
|
+
nodeSatisfiesRequiredTags(task.requiredTags, buildMeshNodeCapabilityTags(node, p))
|
|
1669
|
+
);
|
|
1670
|
+
}
|
|
1671
|
+
return true;
|
|
1672
|
+
})
|
|
1673
|
+
: [];
|
|
1674
|
+
if (!candidateNodes.length) {
|
|
1675
|
+
// Bug A: distinguish the two ways the candidate set empties. A task pinned to a
|
|
1676
|
+
// targetNodeId whose node is absent from the mesh (or whose id arrived under a
|
|
1677
|
+
// different form) is a ROUTING miss — report it as `target_node_id_unmatched`, not
|
|
1678
|
+
// the hard-coded `no_node_satisfies_required_tags`, which mislabelled a 3-form
|
|
1679
|
+
// node-id mismatch as a capability failure and sent diagnosis down the wrong path.
|
|
1680
|
+
// Only fall back to the tag reason when no target pin is in play, or the pin DID
|
|
1681
|
+
// match a node but its tags excluded it (a genuine capability miss).
|
|
1682
|
+
const targetPinUnmatched = !!task.targetNodeId
|
|
1683
|
+
&& !(Array.isArray(mesh?.nodes) && mesh.nodes.some((n: any) => meshNodeIdMatches(n, task.targetNodeId)));
|
|
1684
|
+
// Fix (2): a `convergence` task is base-only — the candidate filter above
|
|
1685
|
+
// (`taskMode === 'convergence' && node.isLocalWorktree`) deliberately drops every
|
|
1686
|
+
// worktree-clone node, so candidateNodes can empty out NOT because the target is
|
|
1687
|
+
// missing or tag-incapable, but because every node the task could land on is a
|
|
1688
|
+
// worktree. Reporting that as `target_node_id_unmatched` / `no_node_satisfies_
|
|
1689
|
+
// required_tags` mislabels the cause and sends diagnosis down the wrong path.
|
|
1690
|
+
// Detect it explicitly and report the same reason mesh_send_task uses for a direct
|
|
1691
|
+
// convergence dispatch onto a worktree, so both surfaces agree.
|
|
1692
|
+
const convergenceOntoWorktree = task.taskMode === 'convergence'
|
|
1693
|
+
&& Array.isArray(mesh?.nodes)
|
|
1694
|
+
&& (() => {
|
|
1695
|
+
const matched = (mesh.nodes as any[]).filter((n: any) =>
|
|
1696
|
+
!task.targetNodeId || meshNodeIdMatches(n, task.targetNodeId));
|
|
1697
|
+
return matched.length > 0 && matched.every((n: any) => n?.isLocalWorktree === true);
|
|
1698
|
+
})();
|
|
1699
|
+
// FALSE-BLOCKER-CLONE-QUEUE: an unmatched target pin is only a PERMANENT routing
|
|
1700
|
+
// miss when the node is genuinely absent — a freshly cloned worktree whose
|
|
1701
|
+
// inline-cache entry has not propagated here yet (or whose bootstrap is still
|
|
1702
|
+
// running) is TRANSIENTLY unresolved and auto-claims shortly. Report that as the
|
|
1703
|
+
// transient (non-actionable) reason so the coordinator is not paged with a false
|
|
1704
|
+
// "actionable blocker — will NOT clear on its own". A genuinely dead node is neither
|
|
1705
|
+
// bootstrap-running nor inside the clone grace window → stays 'target_node_id_unmatched'.
|
|
1706
|
+
const targetTransientlyUnresolved = targetPinUnmatched
|
|
1707
|
+
&& isTargetNodeTransientlyUnresolved(mesh, task);
|
|
1708
|
+
markAutoLaunch(meshId, task.id, {
|
|
1709
|
+
status: 'skipped',
|
|
1710
|
+
reason: convergenceOntoWorktree
|
|
1711
|
+
? 'mesh_convergence_target_is_worktree'
|
|
1712
|
+
: targetTransientlyUnresolved
|
|
1713
|
+
? TRANSIENT_TARGET_NODE_BOOTSTRAP_PENDING_REASON
|
|
1714
|
+
: (targetPinUnmatched ? 'target_node_id_unmatched' : 'no_node_satisfies_required_tags'),
|
|
1715
|
+
nodeId: task.targetNodeId,
|
|
1716
|
+
});
|
|
1717
|
+
continue;
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
// PRIORITY → TIE-BREAK: order the eligible (TAG-filtered) candidate nodes by
|
|
1721
|
+
// the mesh scheduling strategy. 'first_eligible' (default) returns them in
|
|
1722
|
+
// config/array order unchanged, so distribution is strictly opt-in. The
|
|
1723
|
+
// per-node MAX-ALLOC capacity gate (nodeHasActiveAssignment, provider cap,
|
|
1724
|
+
// maxConcurrentSessions) is still applied inside the loop below; this only
|
|
1725
|
+
// chooses which eligible node is *tried first*.
|
|
1726
|
+
const strategy = resolveSchedulingStrategy(mesh);
|
|
1727
|
+
const orderedCandidateNodes = strategy === 'first_eligible'
|
|
1728
|
+
? candidateNodes
|
|
1729
|
+
: orderEligibleNodes(
|
|
1730
|
+
meshId,
|
|
1731
|
+
strategy,
|
|
1732
|
+
candidateNodes
|
|
1733
|
+
.map((node: any, index: number) => ({ nodeId: readMeshNodeId(node), node, index }))
|
|
1734
|
+
.filter((c: RankableNode) => c.nodeId),
|
|
1735
|
+
{ bumpCursor: true },
|
|
1736
|
+
).map((c: RankableNode) => c.node);
|
|
1737
|
+
|
|
1738
|
+
for (const node of orderedCandidateNodes) {
|
|
1739
|
+
const nodeId = readMeshNodeId(node);
|
|
1740
|
+
if (!nodeId) continue;
|
|
1741
|
+
const launchKey = `${meshId}:${nodeId}`;
|
|
1742
|
+
const now = Date.now();
|
|
1743
|
+
const cooldownUntil = autoLaunchCooldownUntil.get(launchKey) || 0;
|
|
1744
|
+
if (cooldownUntil > 0 && now >= cooldownUntil) autoLaunchCooldownUntil.delete(launchKey);
|
|
1745
|
+
if (autoLaunchInProgress.has(launchKey)) {
|
|
1746
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_in_progress', nodeId });
|
|
1747
|
+
continue;
|
|
1748
|
+
}
|
|
1749
|
+
if (now < cooldownUntil) {
|
|
1750
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_cooldown', nodeId });
|
|
1751
|
+
continue;
|
|
1752
|
+
}
|
|
1753
|
+
if (isDirtyNode(node)) {
|
|
1754
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'dirty_workspace', nodeId });
|
|
1755
|
+
continue;
|
|
1756
|
+
}
|
|
1757
|
+
if (!isLaunchableNode(node)) {
|
|
1758
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_not_launch_ready', nodeId });
|
|
1759
|
+
continue;
|
|
1760
|
+
}
|
|
1761
|
+
const launchTarget = resolveAutoLaunchTarget(components, node);
|
|
1762
|
+
if (launchTarget.mode === 'skip') {
|
|
1763
|
+
// Remote node we can't reach (no transport / no coordinator daemonId).
|
|
1764
|
+
// Set a cooldown so the 4s reconcile loop doesn't re-attempt this node
|
|
1765
|
+
// every tick; the de-dup'd skip ledger keeps it diagnosable without flood.
|
|
1766
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: launchTarget.reason || 'auto_launch_unavailable', nodeId });
|
|
1767
|
+
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
|
|
1768
|
+
continue;
|
|
1769
|
+
}
|
|
1770
|
+
// DOUBLE-DISPATCH auto-launch gate (see nodeHasLiveSessionPendingClaim): when this
|
|
1771
|
+
// node already has a live session on its way to claim (idle / booting / momentary
|
|
1772
|
+
// non-idle flip), do NOT spawn a second one — that session pulls the pending task
|
|
1773
|
+
// via the normal idle→claim / agent:ready drain. Launching here races it and yields
|
|
1774
|
+
// a duplicate worker that double-stamps the same taskId. Applies to read-only tasks
|
|
1775
|
+
// too: an idle session can claim either kind, while a genuinely BUSY session (holding
|
|
1776
|
+
// its own assigned task) is excluded by the helper, so a read-only launch onto a
|
|
1777
|
+
// busy-but-no-idle node is still allowed. Skip with a transient (non-actionable)
|
|
1778
|
+
// reason so the coordinator is not paged; the 4s reconcile retries, and once the
|
|
1779
|
+
// existing session goes terminal this gate clears and a legitimate launch proceeds.
|
|
1780
|
+
if (nodeHasLiveSessionPendingClaim(components, meshId, nodeId)) {
|
|
1781
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_has_live_session_pending_claim', nodeId });
|
|
1782
|
+
continue;
|
|
1783
|
+
}
|
|
1784
|
+
// Write tasks keep the one-active-per-node invariant (worktree isolation);
|
|
1785
|
+
// read-only diagnoses may auto-launch onto a node that already has an active
|
|
1786
|
+
// assignment. Classified by the shared isTaskReadonly predicate.
|
|
1787
|
+
if (!isTaskReadonly(task) && nodeHasActiveAssignment(meshId, nodeId)) {
|
|
1788
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_has_active_assignment', nodeId });
|
|
1789
|
+
continue;
|
|
1790
|
+
}
|
|
1791
|
+
const maxConcurrentSessions = Number(node?.policy?.maxConcurrentSessions);
|
|
1792
|
+
if (Number.isFinite(maxConcurrentSessions) && maxConcurrentSessions >= 0 && liveSessionCountForNode(components, meshId, nodeId) >= maxConcurrentSessions) {
|
|
1793
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_concurrent_sessions_reached', nodeId });
|
|
1794
|
+
continue;
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
autoLaunchInProgress.add(launchKey);
|
|
1798
|
+
try {
|
|
1799
|
+
const resolved = await resolveUsableProvider(components, nodeId, node, task.requiredTags);
|
|
1800
|
+
if (!resolved.providerType) {
|
|
1801
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: resolved.reason || 'provider_unusable', nodeId });
|
|
1802
|
+
continue;
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
// Don't spawn a session for a (node, provider) already at its declared
|
|
1806
|
+
// maxParallel cap — it would launch only to fail the claim. The claim
|
|
1807
|
+
// transaction enforces the cap regardless; this just avoids a doomed launch.
|
|
1808
|
+
const providerCap = resolveProviderMaxParallel(node?.policy, resolved.providerType);
|
|
1809
|
+
if (
|
|
1810
|
+
providerCap !== undefined
|
|
1811
|
+
&& activeProviderAssignedCount(meshId, nodeId, resolved.providerType) >= providerCap
|
|
1812
|
+
) {
|
|
1813
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_provider_parallel_reached', nodeId, providerType: resolved.providerType });
|
|
1814
|
+
continue;
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
// Shared worker-launch envelope. For a local node it spawns directly on this
|
|
1818
|
+
// daemon; for a remote node the identical command is forwarded to the node's
|
|
1819
|
+
// daemon (mirrors mesh_launch_session), with the coordinator daemonId stamped
|
|
1820
|
+
// so the worker's completion events route back to this coordinator.
|
|
1821
|
+
const launchSettings: Record<string, unknown> = {
|
|
1822
|
+
// Worker launch envelope: role + mesh context so worker can route completion events.
|
|
1823
|
+
role: 'worker',
|
|
1824
|
+
meshNodeFor: meshId,
|
|
1825
|
+
meshNodeId: nodeId,
|
|
1826
|
+
spawnedSessionVisibility: mesh?.policy?.spawnedSessionVisibility || 'hidden',
|
|
1827
|
+
// Coordinator-dispatched worker: auto-approve unless mesh/node policy
|
|
1828
|
+
// opts out (default true). Lands in settingsOverride and beats the
|
|
1829
|
+
// global per-provider-type autoApprove config (see shouldAutoApprove).
|
|
1830
|
+
autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
|
|
1831
|
+
launchedByCoordinator: true,
|
|
1832
|
+
autoLaunchedForQueueTaskId: task.id,
|
|
1833
|
+
};
|
|
1834
|
+
|
|
1835
|
+
if (launchTarget.mode === 'remote') {
|
|
1836
|
+
// Relay-safe completion routing: stamp the coordinator anchor the same way
|
|
1837
|
+
// mesh_launch_session does so the worker forwards events back to this daemon.
|
|
1838
|
+
const remoteSettings: Record<string, unknown> = {
|
|
1839
|
+
...launchSettings,
|
|
1840
|
+
meshCoordinatorDaemonId: launchTarget.coordinatorDaemonId,
|
|
1841
|
+
meshCoordinatorNodeId: nodeId,
|
|
1842
|
+
};
|
|
1843
|
+
markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
|
|
1844
|
+
let launchResult: any;
|
|
1845
|
+
try {
|
|
1846
|
+
launchResult = await components.dispatchMeshCommand!(launchTarget.daemonId!, 'launch_cli', {
|
|
1847
|
+
cliType: resolved.providerType,
|
|
1848
|
+
dir: node.workspace,
|
|
1849
|
+
settings: remoteSettings,
|
|
1850
|
+
// MAGI-KIND-PANEL model axis: forward the task's model override so the
|
|
1851
|
+
// remote worker session launches with it (initialModel). Best-effort.
|
|
1852
|
+
...(typeof task.model === 'string' && task.model.trim() ? { initialModel: task.model.trim() } : {}),
|
|
1853
|
+
});
|
|
1854
|
+
} catch (e: any) {
|
|
1855
|
+
markAutoLaunch(meshId, task.id, { status: 'failed', reason: `remote_launch_dispatch_failed: ${e?.message || String(e)}`, nodeId, providerType: resolved.providerType });
|
|
1856
|
+
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
|
|
1857
|
+
return false;
|
|
1858
|
+
}
|
|
1859
|
+
const payload = (launchResult && typeof launchResult === 'object' && 'payload' in launchResult && launchResult.payload && typeof launchResult.payload === 'object')
|
|
1860
|
+
? launchResult.payload
|
|
1861
|
+
: launchResult;
|
|
1862
|
+
if (!payload?.success) {
|
|
1863
|
+
const reason = readNonEmptyString(payload?.error) || 'remote_launch_cli_failed';
|
|
1864
|
+
markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
|
|
1865
|
+
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
|
|
1866
|
+
return false;
|
|
1867
|
+
}
|
|
1868
|
+
// Remote launch is async: the worker session will register and emit agent:ready,
|
|
1869
|
+
// which (forwarded back here) drives the claim via the normal event path / PHASE 1
|
|
1870
|
+
// reconcile. Set a cooldown so the 4s loop doesn't re-launch before that lands.
|
|
1871
|
+
const remoteSessionId = readNonEmptyString(payload.sessionId) || readNonEmptyString(payload.id) || readNonEmptyString(payload.runtimeSessionId);
|
|
1872
|
+
markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId: remoteSessionId || undefined });
|
|
1873
|
+
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
|
|
1874
|
+
return true;
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
|
|
1878
|
+
const launchResult: any = await components.cliManager.handleCliCommand('launch_cli', {
|
|
1879
|
+
cliType: resolved.providerType,
|
|
1880
|
+
dir: node.workspace,
|
|
1881
|
+
settings: launchSettings,
|
|
1882
|
+
// MAGI-KIND-PANEL model axis: local launch forwards the task's model
|
|
1883
|
+
// override as initialModel (CLI → modelLaunchArgs; ACP → setConfigOption).
|
|
1884
|
+
...(typeof task.model === 'string' && task.model.trim() ? { initialModel: task.model.trim() } : {}),
|
|
1885
|
+
});
|
|
1886
|
+
if (!launchResult?.success) {
|
|
1887
|
+
const reason = launchResult?.error || 'launch_cli_failed';
|
|
1888
|
+
markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
|
|
1889
|
+
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
|
|
1890
|
+
return false;
|
|
1891
|
+
}
|
|
1892
|
+
const sessionId = readNonEmptyString(launchResult.sessionId) || readNonEmptyString(launchResult.id) || readNonEmptyString(launchResult.runtimeSessionId);
|
|
1893
|
+
if (!sessionId) {
|
|
1894
|
+
markAutoLaunch(meshId, task.id, { status: 'failed', reason: 'launch_missing_session_id', nodeId, providerType: resolved.providerType });
|
|
1895
|
+
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
|
|
1896
|
+
return false;
|
|
1897
|
+
}
|
|
1898
|
+
markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId });
|
|
1899
|
+
// Readiness barrier: a freshly-spawned local CLI session is NOT yet
|
|
1900
|
+
// interactive — its PTY prints the input prompt (and the adapter flips
|
|
1901
|
+
// isReady()) only ~2-6s after launch. Dispatching the task immediately
|
|
1902
|
+
// pushes the first (often large) message into a not-yet-ready PTY, which
|
|
1903
|
+
// could throw "not ready" and bounce the task through requeue (on win32
|
|
1904
|
+
// this raced the auto-launch cooldown and stranded the worker idle).
|
|
1905
|
+
// Await interactive readiness before claiming/dispatching so the very
|
|
1906
|
+
// first message lands cleanly. The adapter's queue-until-ready path is the
|
|
1907
|
+
// backstop if readiness is reported late; this just avoids the churn.
|
|
1908
|
+
await waitForLocalSessionReady(components, sessionId);
|
|
1909
|
+
tryAssignQueueTask(components, meshId, nodeId, sessionId, resolved.providerType);
|
|
1910
|
+
return true;
|
|
1911
|
+
} catch (e: any) {
|
|
1912
|
+
markAutoLaunch(meshId, task.id, { status: 'failed', error: e?.message || String(e), nodeId });
|
|
1913
|
+
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS);
|
|
1914
|
+
return false;
|
|
1915
|
+
} finally {
|
|
1916
|
+
autoLaunchInProgress.delete(launchKey);
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
return false;
|
|
1921
|
+
}
|
|
1922
|
+
|
|
1923
|
+
export interface MeshQueueTriggerResult {
|
|
1924
|
+
success: true;
|
|
1925
|
+
meshId: string;
|
|
1926
|
+
pendingBefore: number;
|
|
1927
|
+
assignedBefore: number;
|
|
1928
|
+
pendingAfter: number;
|
|
1929
|
+
assignedAfter: number;
|
|
1930
|
+
claimed: boolean;
|
|
1931
|
+
newlyAssignedTasks: Array<{
|
|
1932
|
+
id: string;
|
|
1933
|
+
nodeId?: string;
|
|
1934
|
+
sessionId?: string;
|
|
1935
|
+
}>;
|
|
1936
|
+
localIdleSessionsChecked: number;
|
|
1937
|
+
remoteIdleSessionsChecked: number;
|
|
1938
|
+
skippedSessions: Array<{
|
|
1939
|
+
nodeId?: string;
|
|
1940
|
+
sessionId?: string;
|
|
1941
|
+
reason: string;
|
|
1942
|
+
status?: string;
|
|
1943
|
+
}>;
|
|
1944
|
+
autoLaunchStarted: boolean;
|
|
1945
|
+
/**
|
|
1946
|
+
* True when a worker session is already on its way to claim a still-pending task —
|
|
1947
|
+
* either launched this tick (autoLaunchStarted) or launched on a prior tick and still
|
|
1948
|
+
* booting/awaiting-claim. Callers MUST treat this as "wait, do not launch another
|
|
1949
|
+
* session": a second launch double-edits the worktree. Mutually informative with
|
|
1950
|
+
* `noIdleMeshSessionAvailable`, which is suppressed whenever this is true.
|
|
1951
|
+
*/
|
|
1952
|
+
autoLaunchPending?: boolean;
|
|
1953
|
+
noIdleMeshSessionAvailable?: boolean;
|
|
1954
|
+
}
|
|
1955
|
+
|
|
1956
|
+
function countQueueStatus(meshId: string, status: 'pending' | 'assigned'): number {
|
|
1957
|
+
return getQueue(meshId, { status: [status] as any }).length;
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
function getQueueStatusById(meshId: string): Map<string, string> {
|
|
1961
|
+
return new Map(getQueue(meshId).map(task => [task.id, task.status]));
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
export async function triggerMeshQueue(components: DaemonComponents, meshId: string): Promise<MeshQueueTriggerResult> {
|
|
1965
|
+
const mesh = getMeshWithCache(components, meshId);
|
|
1966
|
+
const pendingBefore = countQueueStatus(meshId, 'pending');
|
|
1967
|
+
const assignedBefore = countQueueStatus(meshId, 'assigned');
|
|
1968
|
+
const beforeStatus = getQueueStatusById(meshId);
|
|
1969
|
+
const skippedSessions: MeshQueueTriggerResult['skippedSessions'] = [];
|
|
1970
|
+
let localIdleSessionsChecked = 0;
|
|
1971
|
+
let remoteIdleSessionsChecked = 0;
|
|
1972
|
+
let autoLaunchStarted = false;
|
|
1973
|
+
if (!mesh) {
|
|
1974
|
+
return {
|
|
1975
|
+
success: true,
|
|
1976
|
+
meshId,
|
|
1977
|
+
pendingBefore,
|
|
1978
|
+
assignedBefore,
|
|
1979
|
+
pendingAfter: pendingBefore,
|
|
1980
|
+
assignedAfter: assignedBefore,
|
|
1981
|
+
claimed: false,
|
|
1982
|
+
newlyAssignedTasks: [],
|
|
1983
|
+
localIdleSessionsChecked,
|
|
1984
|
+
remoteIdleSessionsChecked,
|
|
1985
|
+
skippedSessions: [{ reason: 'mesh_not_found' }],
|
|
1986
|
+
autoLaunchStarted,
|
|
1987
|
+
noIdleMeshSessionAvailable: true,
|
|
1988
|
+
};
|
|
1989
|
+
}
|
|
1990
|
+
|
|
1991
|
+
// Collect every idle mesh session (local CLI instances + remote idle records)
|
|
1992
|
+
// as drain candidates. The drain ORDER depends on the scheduling strategy:
|
|
1993
|
+
// - 'first_eligible' (default): local-first, then remote, exactly as before.
|
|
1994
|
+
// - otherwise: local + remote merged into one pool and drained in scheduling
|
|
1995
|
+
// order (priority → load → tie-break). This local-first debias is required
|
|
1996
|
+
// because without it the coordinator's own local node is always visited
|
|
1997
|
+
// first and greedily absorbs all untargeted work before any remote idle
|
|
1998
|
+
// session is even considered — the comparator alone can't spread work if
|
|
1999
|
+
// local is always tried first.
|
|
2000
|
+
const strategy = resolveSchedulingStrategy(mesh);
|
|
2001
|
+
const localCandidates: IdleCandidate[] = [];
|
|
2002
|
+
|
|
2003
|
+
const cliInstances = components.instanceManager.getByCategory('cli');
|
|
2004
|
+
for (const inst of cliInstances) {
|
|
2005
|
+
const state = inst.getState();
|
|
2006
|
+
const settings = state.settings as Record<string, unknown> || {};
|
|
2007
|
+
|
|
2008
|
+
const instMeshId = readNonEmptyString(settings.meshNodeFor);
|
|
2009
|
+
if (instMeshId !== meshId) continue;
|
|
2010
|
+
|
|
2011
|
+
const nodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
|
|
2012
|
+
if (!nodeId) continue;
|
|
2013
|
+
|
|
2014
|
+
if (!isIdleSessionState(state)) {
|
|
2015
|
+
const status = readNonEmptyString(state.status).toLowerCase();
|
|
2016
|
+
skippedSessions.push({
|
|
2017
|
+
nodeId,
|
|
2018
|
+
sessionId: readNonEmptyString(state.instanceId),
|
|
2019
|
+
reason: isTerminalSessionStatus(status) ? 'terminal_session' : 'session_not_idle',
|
|
2020
|
+
status: status || undefined,
|
|
2021
|
+
});
|
|
2022
|
+
continue;
|
|
2023
|
+
}
|
|
2024
|
+
|
|
2025
|
+
const sessionId = state.instanceId;
|
|
2026
|
+
const providerType = state.type || readNonEmptyString(settings.providerType);
|
|
2027
|
+
|
|
2028
|
+
if (providerType) {
|
|
2029
|
+
localIdleSessionsChecked += 1;
|
|
2030
|
+
localCandidates.push({ nodeId, sessionId, providerType, origin: 'local', node: mesh.nodes.find((n: any) => meshNodeIdMatches(n, nodeId)) });
|
|
2031
|
+
} else {
|
|
2032
|
+
skippedSessions.push({
|
|
2033
|
+
nodeId,
|
|
2034
|
+
sessionId,
|
|
2035
|
+
reason: 'provider_type_missing',
|
|
2036
|
+
});
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
|
|
2040
|
+
let remoteSessions: Array<{ nodeId: string; sessionId: string; providerType: string }> = [];
|
|
2041
|
+
try {
|
|
2042
|
+
remoteSessions = MeshRuntimeStore.getInstance().getRemoteIdleSessions(meshId);
|
|
2043
|
+
} catch { /* best-effort */ }
|
|
2044
|
+
|
|
2045
|
+
const remoteCandidates: IdleCandidate[] = [];
|
|
2046
|
+
for (const idle of remoteSessions) {
|
|
2047
|
+
// Match with the shared 3-form normalizer (id / nodeId / node_id), not raw
|
|
2048
|
+
// `n.id`, so an inline-cached worktree node whose identity arrived under a
|
|
2049
|
+
// different form is not silently dropped — leaving a remote idle session
|
|
2050
|
+
// unable to claim its pending queue task.
|
|
2051
|
+
const node = mesh.nodes.find((n: any) => meshNodeIdMatches(n, idle.nodeId));
|
|
2052
|
+
if (node) {
|
|
2053
|
+
remoteIdleSessionsChecked += 1;
|
|
2054
|
+
remoteCandidates.push({ nodeId: idle.nodeId, sessionId: idle.sessionId, providerType: idle.providerType, origin: 'remote', node });
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
|
|
2058
|
+
const assignIdleCandidate = (candidate: IdleCandidate): void => {
|
|
2059
|
+
const assigned = tryAssignQueueTask(components, meshId, candidate.nodeId, candidate.sessionId, candidate.providerType);
|
|
2060
|
+
if (assigned && candidate.origin === 'remote') {
|
|
2061
|
+
try {
|
|
2062
|
+
MeshRuntimeStore.getInstance().deleteRemoteIdleSession(meshId, candidate.nodeId, candidate.sessionId);
|
|
2063
|
+
} catch { /* best-effort */ }
|
|
2064
|
+
}
|
|
2065
|
+
};
|
|
2066
|
+
|
|
2067
|
+
if (strategy === 'first_eligible') {
|
|
2068
|
+
// Strict no-change: drain local idle sessions first (original order), then
|
|
2069
|
+
// remote idle sessions. tryAssignQueueTask is a no-op when nothing matches.
|
|
2070
|
+
for (const candidate of localCandidates) assignIdleCandidate(candidate);
|
|
2071
|
+
for (const candidate of remoteCandidates) assignIdleCandidate(candidate);
|
|
2072
|
+
} else {
|
|
2073
|
+
// Merge local + remote into one pool and drain in scheduling order. Each
|
|
2074
|
+
// assignment mutates a node's active load, and the next pick re-reads it,
|
|
2075
|
+
// so re-ranking after every assignment keeps the spread fair as load shifts.
|
|
2076
|
+
// buildSchedulingPool canonicalizes every candidate's nodeId so the Set
|
|
2077
|
+
// dedup, baseIndex, rankIndex, and nodeActiveLoad keying below all agree on
|
|
2078
|
+
// one form (see the invariant on that helper).
|
|
2079
|
+
const { pool, uniqueNodes } = buildSchedulingPool(localCandidates, remoteCandidates);
|
|
2080
|
+
const baseIndex = new Map<string, number>();
|
|
2081
|
+
pool.forEach((c, i) => { if (!baseIndex.has(c.nodeId)) baseIndex.set(c.nodeId, i); });
|
|
2082
|
+
// Bump the round-robin cursor once for this whole drain pass.
|
|
2083
|
+
const ranked = orderEligibleNodes(meshId, strategy, uniqueNodes, { bumpCursor: true });
|
|
2084
|
+
const rankIndex = new Map<string, number>(ranked.map((r, i) => [r.nodeId, i]));
|
|
2085
|
+
const remaining = [...pool];
|
|
2086
|
+
while (remaining.length > 0) {
|
|
2087
|
+
// Re-rank each pass so a node that just took work defers its next session.
|
|
2088
|
+
remaining.sort((a, b) => {
|
|
2089
|
+
const aPrio = resolveNodeSchedulingPriority(a.node?.policy);
|
|
2090
|
+
const bPrio = resolveNodeSchedulingPriority(b.node?.policy);
|
|
2091
|
+
if (aPrio !== bPrio) return bPrio - aPrio;
|
|
2092
|
+
if (strategy === 'least_loaded' || strategy === 'round_robin') {
|
|
2093
|
+
const loadDelta = nodeActiveLoad(meshId, a.nodeId) - nodeActiveLoad(meshId, b.nodeId);
|
|
2094
|
+
if (loadDelta !== 0) return loadDelta;
|
|
2095
|
+
}
|
|
2096
|
+
return (rankIndex.get(a.nodeId) ?? 0) - (rankIndex.get(b.nodeId) ?? 0);
|
|
2097
|
+
});
|
|
2098
|
+
assignIdleCandidate(remaining.shift()!);
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
autoLaunchStarted = await maybeAutoLaunchOneQueueSession(components, meshId, mesh);
|
|
2103
|
+
const afterQueue = getQueue(meshId);
|
|
2104
|
+
const pendingAfter = afterQueue.filter(task => task.status === 'pending').length;
|
|
2105
|
+
const assignedAfter = afterQueue.filter(task => task.status === 'assigned').length;
|
|
2106
|
+
const newlyAssignedTasks = afterQueue
|
|
2107
|
+
.filter(task => task.status === 'assigned' && beforeStatus.get(task.id) !== 'assigned')
|
|
2108
|
+
.map(task => ({
|
|
2109
|
+
id: task.id,
|
|
2110
|
+
nodeId: task.assignedNodeId,
|
|
2111
|
+
sessionId: task.assignedSessionId,
|
|
2112
|
+
}));
|
|
2113
|
+
|
|
2114
|
+
// An auto-launch is "pending" when the coordinator has already spun a session up
|
|
2115
|
+
// for a still-pending task and is waiting on that session's idle→claim. This covers
|
|
2116
|
+
// two ticks:
|
|
2117
|
+
// - THIS tick fired the launch (autoLaunchStarted), or
|
|
2118
|
+
// - a PRIOR tick launched a session that is still booting/awaiting-claim — the
|
|
2119
|
+
// per-task await-claim guard (maybeAutoLaunchOneQueueSession) deliberately
|
|
2120
|
+
// declines to launch again, so autoLaunchStarted is false even though a session
|
|
2121
|
+
// is on its way to claim this task.
|
|
2122
|
+
// Without this signal, the second tick reports `noIdleMeshSessionAvailable` and the
|
|
2123
|
+
// MCP guidance tells the coordinator to launch ANOTHER worker — producing a duplicate
|
|
2124
|
+
// session that double-edits the worktree. The claim itself is fine; only the wording
|
|
2125
|
+
// was wrong, so we surface `autoLaunchPending` to suppress the bad "launch one more"
|
|
2126
|
+
// advice while the just-launched session converges.
|
|
2127
|
+
const autoLaunchPending = autoLaunchStarted || afterQueue.some(task => {
|
|
2128
|
+
if (task.status !== 'pending') return false;
|
|
2129
|
+
const al = task.autoLaunch;
|
|
2130
|
+
if (!al || (al.status !== 'started' && al.status !== 'completed')) return false;
|
|
2131
|
+
const launchedAtMs = Date.parse(al.updatedAt);
|
|
2132
|
+
return Number.isFinite(launchedAtMs) && Date.now() - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS;
|
|
2133
|
+
});
|
|
2134
|
+
|
|
2135
|
+
return {
|
|
2136
|
+
success: true,
|
|
2137
|
+
meshId,
|
|
2138
|
+
pendingBefore,
|
|
2139
|
+
assignedBefore,
|
|
2140
|
+
pendingAfter,
|
|
2141
|
+
assignedAfter,
|
|
2142
|
+
claimed: newlyAssignedTasks.length > 0,
|
|
2143
|
+
newlyAssignedTasks,
|
|
2144
|
+
localIdleSessionsChecked,
|
|
2145
|
+
remoteIdleSessionsChecked,
|
|
2146
|
+
skippedSessions,
|
|
2147
|
+
autoLaunchStarted,
|
|
2148
|
+
...(autoLaunchPending ? { autoLaunchPending: true } : {}),
|
|
2149
|
+
// Only report "no idle session, go launch one" when nothing is already on its way.
|
|
2150
|
+
// A pending auto-launch (this tick or a prior still-converging one) means a session
|
|
2151
|
+
// WILL claim shortly, so it is not a no-session-available situation.
|
|
2152
|
+
...(pendingAfter > 0 && newlyAssignedTasks.length === 0 && localIdleSessionsChecked === 0 && remoteIdleSessionsChecked === 0 && !autoLaunchPending
|
|
2153
|
+
? { noIdleMeshSessionAvailable: true }
|
|
2154
|
+
: {}),
|
|
2155
|
+
};
|
|
2156
|
+
}
|
|
2157
|
+
|
|
2158
|
+
export async function maybeAutoFastForwardIdleNode(components: DaemonComponents, args: {
|
|
2159
|
+
meshId: string;
|
|
2160
|
+
nodeId: string;
|
|
2161
|
+
sessionId?: string;
|
|
2162
|
+
providerType?: string;
|
|
2163
|
+
}): Promise<void> {
|
|
2164
|
+
const mesh = getMeshWithCache(components, args.meshId);
|
|
2165
|
+
const node = mesh?.nodes?.find((candidate: any) => meshNodeIdMatches(candidate, args.nodeId));
|
|
2166
|
+
const workspace = readNonEmptyString(node?.workspace);
|
|
2167
|
+
if (!workspace) return;
|
|
2168
|
+
if (!existsSync(workspace)) return;
|
|
2169
|
+
|
|
2170
|
+
const policy = resolveAutoFastForwardPolicy(mesh);
|
|
2171
|
+
if (!policy.enabled) return;
|
|
2172
|
+
if (nodeHasActiveMeshWork(components, args.meshId, args.nodeId, args.sessionId)) return;
|
|
2173
|
+
|
|
2174
|
+
const throttleKey = `${args.meshId}:${args.nodeId}`;
|
|
2175
|
+
const now = Date.now();
|
|
2176
|
+
const lastAttempt = idleAutoFastForwardLastAttempt.get(throttleKey) || 0;
|
|
2177
|
+
if (now - lastAttempt < IDLE_AUTO_FAST_FORWARD_THROTTLE_MS) return;
|
|
2178
|
+
idleAutoFastForwardLastAttempt.set(throttleKey, now);
|
|
2179
|
+
|
|
2180
|
+
const submoduleIgnorePaths = Array.isArray(node?.policy?.submoduleIgnorePaths)
|
|
2181
|
+
? node.policy.submoduleIgnorePaths.filter((value: unknown): value is string => typeof value === 'string')
|
|
2182
|
+
: undefined;
|
|
2183
|
+
try {
|
|
2184
|
+
const dryRun = await fastForwardMeshNode({
|
|
2185
|
+
meshId: args.meshId,
|
|
2186
|
+
nodeId: args.nodeId,
|
|
2187
|
+
workspace,
|
|
2188
|
+
execute: false,
|
|
2189
|
+
dryRun: true,
|
|
2190
|
+
updateSubmodules: false,
|
|
2191
|
+
submoduleIgnorePaths,
|
|
2192
|
+
trigger: 'idle_auto',
|
|
2193
|
+
});
|
|
2194
|
+
if (!dryRun || dryRun.code !== 'fast_forward_available' || dryRun.allowed !== true) return;
|
|
2195
|
+
const behind = Number(dryRun.current?.behind);
|
|
2196
|
+
if (policy.maxBehind !== undefined && Number.isFinite(behind) && behind > policy.maxBehind) return;
|
|
2197
|
+
if (policy.requireCleanSubmodules) {
|
|
2198
|
+
const submodules = Array.isArray(dryRun.current?.submodules) ? dryRun.current.submodules : [];
|
|
2199
|
+
if (submodules.some((submodule: any) => submodule?.dirty || submodule?.outOfSync || submodule?.error)) return;
|
|
2200
|
+
}
|
|
2201
|
+
await fastForwardMeshNode({
|
|
2202
|
+
meshId: args.meshId,
|
|
2203
|
+
nodeId: args.nodeId,
|
|
2204
|
+
workspace,
|
|
2205
|
+
execute: true,
|
|
2206
|
+
dryRun: false,
|
|
2207
|
+
updateSubmodules: false,
|
|
2208
|
+
submoduleIgnorePaths,
|
|
2209
|
+
trigger: 'idle_auto',
|
|
2210
|
+
});
|
|
2211
|
+
} catch (e: any) {
|
|
2212
|
+
LOG.warn('MeshFastForward', `Idle auto fast-forward check failed for ${args.nodeId}: ${e?.message || e}`);
|
|
2213
|
+
}
|
|
2214
|
+
}
|
|
2215
|
+
|
|
2216
|
+
export function runIdleMaintenanceThenAssignQueue(components: DaemonComponents, args: {
|
|
2217
|
+
meshId: string;
|
|
2218
|
+
nodeId: string;
|
|
2219
|
+
sessionId: string;
|
|
2220
|
+
providerType: string;
|
|
2221
|
+
}): void {
|
|
2222
|
+
setImmediate(() => {
|
|
2223
|
+
maybeAutoFastForwardIdleNode(components, args)
|
|
2224
|
+
.finally(() => {
|
|
2225
|
+
try {
|
|
2226
|
+
tryAssignQueueTask(components, args.meshId, args.nodeId, args.sessionId, args.providerType);
|
|
2227
|
+
} catch (e: any) {
|
|
2228
|
+
LOG.warn('MeshQueue', `Failed to assign idle queue task after maintenance for ${args.nodeId}: ${e?.message || e}`);
|
|
2229
|
+
}
|
|
2230
|
+
});
|
|
2231
|
+
});
|
|
2232
|
+
}
|
|
2233
|
+
|