@adhdev/daemon-core 0.9.82-rc.44 → 0.9.82-rc.440
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 +15 -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 +60 -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 +29 -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 +142 -0
- package/dist/commands/mesh-coordinator.d.ts +85 -1
- package/dist/commands/router.d.ts +276 -2
- package/dist/commands/upgrade-helper.d.ts +41 -1
- package/dist/config/chat-history.d.ts +9 -0
- package/dist/config/config.d.ts +5 -0
- package/dist/config/mesh-config.d.ts +120 -1
- package/dist/config/mesh-json-config.d.ts +199 -0
- package/dist/config/repo-settings.d.ts +77 -0
- package/dist/daemon/dev-server.d.ts +0 -2
- 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 +11 -1
- 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 +64 -14
- package/dist/index.js +50679 -20122
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +47546 -17153
- 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/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 +164 -0
- package/dist/mesh/coordinator-prompt.d.ts +89 -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 +5 -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 +69 -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 +77 -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 +289 -0
- package/dist/mesh/mesh-queue-assignment.d.ts +113 -0
- package/dist/mesh/mesh-reconcile-loop.d.ts +65 -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 +450 -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 +300 -5
- package/dist/mesh/preview-freshness.d.ts +18 -0
- package/dist/mesh/refine-config.d.ts +216 -0
- package/dist/mesh/worktree-bootstrap-config.d.ts +145 -0
- package/dist/providers/acp-provider-instance.d.ts +5 -0
- package/dist/providers/approval-utils.d.ts +20 -0
- package/dist/providers/chat-message-normalization.d.ts +31 -1
- package/dist/providers/cli-provider-instance.d.ts +252 -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 +63 -0
- package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -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 +27 -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 +23 -1
- package/dist/providers/provider-loader.d.ts +26 -4
- 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 +91 -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 +422 -0
- package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
- package/dist/providers/spec/fsm-loader.d.ts +14 -0
- package/dist/providers/spec/fsm-types.d.ts +174 -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 +509 -13
- package/dist/runtime-defaults.d.ts +2 -0
- package/dist/sessions/registry.d.ts +6 -0
- package/dist/shared-types-extra.d.ts +2 -4
- package/dist/shared-types.d.ts +59 -2
- 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 +7 -3
- package/src/agent-stream/poller.ts +2 -3
- package/src/agent-stream/provider-adapter.ts +1 -1
- package/src/boot/daemon-lifecycle.ts +63 -12
- 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/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
- package/src/commands/chat-commands-debug-bundle.ts +398 -0
- package/src/commands/chat-commands-read.ts +2327 -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 +572 -27
- package/src/commands/handler.ts +841 -2
- package/src/commands/high-family/index.ts +28 -0
- package/src/commands/high-family/mesh-coordinator-launch.ts +678 -0
- package/src/commands/high-family/mesh-events.ts +80 -0
- package/src/commands/high-family/mesh-status.ts +714 -0
- package/src/commands/high-family/types.ts +76 -0
- package/src/commands/low-family/coordinator-prompt.ts +72 -0
- package/src/commands/low-family/daemon-lifecycle.ts +107 -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 +238 -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 +1242 -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 +143 -0
- package/src/commands/mesh-coordinator.ts +334 -124
- package/src/commands/router.ts +2846 -3484
- 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 +12 -0
- package/src/config/mesh-config.ts +593 -22
- package/src/config/mesh-json-config.ts +376 -0
- package/src/config/recent-activity.ts +8 -2
- 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 +28 -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 +59 -15
- 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 +196 -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/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 +338 -0
- package/src/mesh/coordinator-prompt.ts +415 -34
- package/src/mesh/coordinator-registry.ts +121 -0
- package/src/mesh/mesh-active-work.ts +645 -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 +51 -0
- package/src/mesh/mesh-event-forwarding.ts +1897 -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 +656 -0
- package/src/mesh/mesh-events-stale.ts +389 -0
- package/src/mesh/mesh-events-utils.ts +443 -0
- package/src/mesh/mesh-events.ts +33 -1035
- package/src/mesh/mesh-fast-forward.ts +843 -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 +656 -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 +1887 -0
- package/src/mesh/mesh-queue-assignment.ts +1924 -0
- package/src/mesh/mesh-reconcile-loop.ts +1997 -0
- package/src/mesh/mesh-refine-batch.ts +205 -0
- package/src/mesh/mesh-refine-gates.ts +1673 -0
- package/src/mesh/mesh-refine-status.ts +231 -0
- package/src/mesh/mesh-review-inbox.ts +307 -0
- package/src/mesh/mesh-routing.ts +291 -0
- package/src/mesh/mesh-runtime-store.ts +1853 -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 +1254 -141
- package/src/mesh/preview-freshness.ts +118 -0
- package/src/mesh/refine-config.ts +423 -0
- package/src/mesh/worktree-bootstrap-config.ts +450 -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 +57 -5
- package/src/providers/chat-message-normalization.ts +92 -4
- package/src/providers/cli-provider-instance.ts +2001 -106
- 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 +85 -0
- package/src/providers/native-history/antigravity-cli-transcript.ts +643 -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 +345 -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 +19 -1
- package/src/providers/provider-loader.ts +668 -50
- 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 +250 -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 +235 -0
- package/src/providers/spec/cli-adapter.ts +1056 -0
- package/src/providers/spec/evaluator.ts +407 -0
- package/src/providers/spec/fsm-driver.ts +1410 -0
- package/src/providers/spec/fsm-evaluator.ts +272 -0
- package/src/providers/spec/fsm-loader.ts +120 -0
- package/src/providers/spec/fsm-types.ts +273 -0
- package/src/providers/spec/native-history-executor.ts +1143 -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 +748 -14
- package/src/runtime-defaults.ts +39 -0
- 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 +64 -1
- 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,1997 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// mesh-reconcile-loop — periodic queue → live coordinator reconciliation
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
// Single-model replacement for the old event-based "spontaneous forward" paths
|
|
5
|
+
// (remote P2P mesh_forward_event dispatch + live-CLI PTY fire-and-forget inject).
|
|
6
|
+
// Those pushed events at the moment a worker transitioned state, and silently
|
|
7
|
+
// dropped on the network (P2P) or when the coordinator was generating.
|
|
8
|
+
//
|
|
9
|
+
// The reliable backbone has always been the pending-events queue (SQLite +
|
|
10
|
+
// JSONL): every mesh coordinator event is persisted there before anything else
|
|
11
|
+
// (see injectMeshSystemMessage). What was missing was an *active* drainer that
|
|
12
|
+
// runs on a schedule rather than only when the coordinator (an LLM) happens to
|
|
13
|
+
// call a mesh tool.
|
|
14
|
+
//
|
|
15
|
+
// This loop is that drainer. On a fixed interval it:
|
|
16
|
+
// 1. Finds live CLI coordinator sessions on THIS daemon (meshCoordinatorFor
|
|
17
|
+
// stamp). For each mesh, drains the local queue scoped to this daemon and
|
|
18
|
+
// injects pending events into the coordinator. When a coordinator is idle it
|
|
19
|
+
// receives every queued event. When ONLY generating coordinators exist (the
|
|
20
|
+
// common case while the coordinator is blocked awaiting a worker result), the
|
|
21
|
+
// loop force-drains ONLY the force-inject events (completion / approval / stop /
|
|
22
|
+
// refine·bootstrap terminal) and force-writes them into the generating PTY —
|
|
23
|
+
// the same busy-bypass send-guard escape the live-CLI inject used to use.
|
|
24
|
+
// Non-force progress events stay queued for the next idle tick (injecting them
|
|
25
|
+
// mid-generation would be noise). This is what makes a coordinator parked in
|
|
26
|
+
// `generating` while awaiting a worker's completion actually receive it.
|
|
27
|
+
// 2. In cloud mode (dispatchMeshCommand present), pulls each remote worker
|
|
28
|
+
// node daemon's queue over P2P (get_pending_mesh_events) and re-injects via
|
|
29
|
+
// handleMeshForwardEvent — the same pull the MCP drainCoordinatorPendingEvents
|
|
30
|
+
// already does, now driven by the daemon timer instead of an LLM tool call.
|
|
31
|
+
//
|
|
32
|
+
// IMPORTANT — limits of this loop:
|
|
33
|
+
// - It only delivers to *live CLI coordinator instances* on this daemon. A
|
|
34
|
+
// pure stdio MCP coordinator (an LLM with no live CLI session to inject
|
|
35
|
+
// into) has no inject target here; that case stays pull-driven — the LLM
|
|
36
|
+
// drains the queue when it calls mesh_status / mesh_read_chat. We do NOT try
|
|
37
|
+
// to "wake" an LLM from the daemon; that is structurally impossible over a
|
|
38
|
+
// stdio request/response transport. See docs/refactoring/2026-06-15-mesh-event-to-queue-polling.md §4.7.
|
|
39
|
+
// - Queue persistence (queuePendingMeshCoordinatorEvent) and the SQLite
|
|
40
|
+
// drained=1 idempotency are the trust backbone and are untouched by this loop.
|
|
41
|
+
// ---------------------------------------------------------------------------
|
|
42
|
+
|
|
43
|
+
import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
|
|
44
|
+
import type { LocalMeshEntry } from '../repo-mesh-types.js';
|
|
45
|
+
import { loadConfig } from '../config/config.js';
|
|
46
|
+
import { listMeshes } from '../config/mesh-config.js';
|
|
47
|
+
import { LOG, getLogLevel } from '../logging/logger.js';
|
|
48
|
+
import { drainPendingMeshCoordinatorEvents, getPendingMeshCoordinatorEvents, buildPendingEventFingerprint, queuePendingMeshCoordinatorEvent } from './mesh-events-pending.js';
|
|
49
|
+
import type { PendingMeshCoordinatorEvent } from './mesh-events-pending.js';
|
|
50
|
+
import { appendLedgerEntry } from './mesh-ledger.js';
|
|
51
|
+
import { MeshRuntimeStore } from './mesh-runtime-store.js';
|
|
52
|
+
import { handleMeshForwardEvent, shouldForceInjectMeshEvent, triggerMeshQueue, resolveForwardEventMeshId } from './mesh-events-coordinator.js';
|
|
53
|
+
import {
|
|
54
|
+
peekUnresolvedDelegateForwards,
|
|
55
|
+
ackUnresolvedDelegateForward,
|
|
56
|
+
expireStaleUnresolvedDelegateForwards,
|
|
57
|
+
} from './mesh-unresolved-forward-outbox.js';
|
|
58
|
+
import { readNonEmptyString, readMeshCompletionSummary, buildMeshSystemMessage } from './mesh-events-utils.js';
|
|
59
|
+
import { traceMeshEventStage, traceMeshEventDrop } from './mesh-event-trace.js';
|
|
60
|
+
import { expandDaemonIdForms, daemonIdsEquivalent } from '@adhdev/mesh-shared';
|
|
61
|
+
import { getActiveDirectDispatches, getQueue, reclaimStrandedAssignedTask, updateTaskStatus } from './mesh-work-queue.js';
|
|
62
|
+
import { readLedgerEntries } from './mesh-ledger.js';
|
|
63
|
+
import { pruneStaleDirectDispatches } from './mesh-active-work.js';
|
|
64
|
+
import { findTerminalLedgerEvidenceForTask, reconcileDirectDispatchCompletionFromTranscript } from './mesh-events-stale.js';
|
|
65
|
+
import { extractFinalAssistantSummaryEvidence } from '../providers/chat-message-normalization.js';
|
|
66
|
+
import type { ChatMessage } from '../types.js';
|
|
67
|
+
|
|
68
|
+
// Default reconcile cadence. approval/completion notifications to a live CLI
|
|
69
|
+
// coordinator land within at most one interval. Overridable via env for tuning.
|
|
70
|
+
const DEFAULT_RECONCILE_INTERVAL_MS = 4_000;
|
|
71
|
+
|
|
72
|
+
// PHASE 5 (auto-prune) conservative age gate. A direct dispatch whose node/session is
|
|
73
|
+
// orphaned (no longer in the live mesh) is only auto-pruned once it is at least this old,
|
|
74
|
+
// measured from its dispatch time. This protects against a node/session that is only
|
|
75
|
+
// *transiently* invisible (a momentary probe failure, a daemon restart) being pruned the
|
|
76
|
+
// instant it disappears. The MANUAL prune (mesh_prune_stale_direct) has no age gate — an
|
|
77
|
+
// operator pruning explicitly wants the orphan gone now. Overridable via env for tuning.
|
|
78
|
+
const DEFAULT_AUTO_PRUNE_MIN_AGE_MS = 24 * 60 * 60_000; // 24h
|
|
79
|
+
|
|
80
|
+
function resolveAutoPruneMinAgeMs(): number {
|
|
81
|
+
const raw = readNonEmptyString(process.env.MESH_AUTO_PRUNE_MIN_AGE_MS);
|
|
82
|
+
if (raw) {
|
|
83
|
+
const parsed = Number.parseInt(raw, 10);
|
|
84
|
+
// Clamp to [1h, 30d] so a mis-set env can't make the gate pathologically aggressive
|
|
85
|
+
// (prune the moment something blinks) or effectively disable it forever.
|
|
86
|
+
if (Number.isFinite(parsed) && parsed >= 60 * 60_000 && parsed <= 30 * 24 * 60 * 60_000) return parsed;
|
|
87
|
+
}
|
|
88
|
+
return DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// PTY-OVERTRUST-DRAIN (Defect B, fix B). Age-based escape for the
|
|
92
|
+
// `generating_no_idle_coordinator` hold. Fix A makes the drain predicate read the RAW
|
|
93
|
+
// adapter (mask-stripped), so the common mask-driven false-busy is gone. But a hold can
|
|
94
|
+
// still arise from a genuine status-source desync that fix A does not reach (e.g. the
|
|
95
|
+
// adapter raw itself momentarily reads generating while the coordinator is actually at a
|
|
96
|
+
// turn end). This is a TIME-BASED BACKSTOP: when a mesh's pending terminal events have
|
|
97
|
+
// been held this long, re-confirm the coordinator's RAW adapter idle on the tick and, if
|
|
98
|
+
// it is genuinely idle, drain ONCE. It NEVER injects into a genuinely-generating PTY —
|
|
99
|
+
// the re-confirmation gates on raw adapter idle, so the intentional removal of
|
|
100
|
+
// force-inject-into-generating (data-loss) is preserved. Default 12s = 3 reconcile ticks
|
|
101
|
+
// at the 4s cadence: long enough that a normal mid-turn settle is not pre-empted, short
|
|
102
|
+
// enough that a desync-stranded completion is not held for minutes. Env-tunable.
|
|
103
|
+
const DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS = 12_000;
|
|
104
|
+
|
|
105
|
+
function resolvePendingHeldDrainEscalateMs(): number {
|
|
106
|
+
// Floor 4s (one tick) so a mis-set env cannot make the escape race a normal settle;
|
|
107
|
+
// ceiling 5min so it cannot be disabled into a permanent strand.
|
|
108
|
+
return resolveTunedReconcileMs('MESH_PENDING_HELD_DRAIN_ESCALATE_MS', DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS, 4_000, 5 * 60_000);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function resolveReconcileIntervalMs(): number {
|
|
112
|
+
const raw = readNonEmptyString(process.env.MESH_RECONCILE_INTERVAL_MS);
|
|
113
|
+
if (raw) {
|
|
114
|
+
const parsed = Number.parseInt(raw, 10);
|
|
115
|
+
if (Number.isFinite(parsed) && parsed >= 1_000 && parsed <= 60_000) return parsed;
|
|
116
|
+
}
|
|
117
|
+
return DEFAULT_RECONCILE_INTERVAL_MS;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// R4f (GENERATING-BOUNDARY, acked-hold redesign). PHASE 4 only synthesizes a missing completion
|
|
121
|
+
// when the worker session reads `idle`. But a worker that is GENUINELY generating (it emitted
|
|
122
|
+
// agent:generating_started — the dispatch row is 'acked' — and has not yet completed) can
|
|
123
|
+
// momentarily read `idle` mid-turn (a CLI PTY inter-tool-call settle, or the final assistant text
|
|
124
|
+
// already rendered while the turn's generating_completed lifecycle close still lags). A premature
|
|
125
|
+
// synth writes a terminal that then masks the worker's REAL completion when it lands seconds later
|
|
126
|
+
// (drop:duplicate_completion_terminal_ledger; the observed 71s task a250fb44 lost its [System]
|
|
127
|
+
// notification this way; the R4e 53s task synth fired 16s BEFORE the worker's real emit).
|
|
128
|
+
//
|
|
129
|
+
// R4 → R4e used FINITE timers (consecutive ticks / MIN_IDLE_SETTLE / ACKED_TURN_SETTLE) to delay the
|
|
130
|
+
// synth. That class of fix is fundamentally a RACE: the worker's real emit latency is variable and
|
|
131
|
+
// unbounded (win32 idle reads can flip before the emit arrives), so ANY finite timer eventually
|
|
132
|
+
// loses to a slow-enough turn — and the synth pre-empts the real completion. R4e live-FAILED for
|
|
133
|
+
// exactly this reason.
|
|
134
|
+
//
|
|
135
|
+
// R4f redesign (direction B). An `acked` task means the worker ECHOED generating_started (the
|
|
136
|
+
// taskId flip) — it is alive and mid-turn, so it WILL eventually emit a real terminal. We therefore
|
|
137
|
+
// HOLD the synth INDEFINITELY for an acked task. This is safe against the emit actually arriving:
|
|
138
|
+
// when the worker's real generating_completed lands, it writes a terminal ledger, and
|
|
139
|
+
// reconcileDirectDispatchCompletionFromTranscript's hasTerminalLedgerAfterDispatch check makes any
|
|
140
|
+
// later synth an idempotent no-op (alreadyTerminal). So the hold never costs a missed notification —
|
|
141
|
+
// the real emit always wins, no matter how late.
|
|
142
|
+
//
|
|
143
|
+
// The indefinite hold is released ONLY by a genuine-DEATH / emit-loss BACKSTOP — never a finite
|
|
144
|
+
// timer that races normal lag:
|
|
145
|
+
// (a) liveness failure — read_chat reports the session is gone, OR N consecutive read failures
|
|
146
|
+
// accumulate (a transport/session-gone signal, counted as death rather than swallowed via
|
|
147
|
+
// `continue`). A worker that died mid-turn will never emit, so the synth must eventually fire.
|
|
148
|
+
// (b) an absolute LONG death-deadline — time since the generating_started ack exceeds
|
|
149
|
+
// ACKED_DEATH_DEADLINE_MS, a backstop set FAR above any observed emit latency (default 8 min)
|
|
150
|
+
// so it does not race a normal slow turn; it only catches a worker that is genuinely wedged or
|
|
151
|
+
// whose emit was permanently lost. This is a notification-loss net, not a completion timer.
|
|
152
|
+
//
|
|
153
|
+
// A dispatch that was never acked (worker never started) is NOT held here: there is no in-flight
|
|
154
|
+
// generation to protect, so it keeps the existing first-idle-tick synth behavior (its lost-dispatch
|
|
155
|
+
// case is covered by the downstream grace + stale-summary guards). The map is pruned each PHASE-4
|
|
156
|
+
// pass to the set of currently active dispatches, so a completed/pruned task's state is dropped (no
|
|
157
|
+
// unbounded growth). Keyed by `${meshId}::${taskId}`.
|
|
158
|
+
|
|
159
|
+
// R4f backstop (a): how many CONSECUTIVE read_chat failures (transport error / success:false /
|
|
160
|
+
// no payload) for an acked task are treated as a death signal that releases the indefinite hold.
|
|
161
|
+
// A single failed read is a transient probe blip; a session that genuinely died reads-fail every
|
|
162
|
+
// tick, so a small streak distinguishes the two without racing a live-but-slow worker.
|
|
163
|
+
const ACKED_DEATH_CONSECUTIVE_READ_FAILURES = 3;
|
|
164
|
+
|
|
165
|
+
// R4f backstop (b): the absolute death-deadline. An acked task is held indefinitely until this much
|
|
166
|
+
// time has elapsed since its generating_started ack (dispatch.updatedAt); past it, a persistently
|
|
167
|
+
// idle session is synthesized as a notification-loss net. This is set FAR above any observed emit
|
|
168
|
+
// latency (R4e's worst case was ~16s) so it does NOT race a normal slow turn — it only catches a
|
|
169
|
+
// genuinely wedged worker or a permanently-lost emit. Read at call time so tests can tune it.
|
|
170
|
+
function resolveTunedReconcileMs(envName: string, def: number, min: number, max: number): number {
|
|
171
|
+
const raw = readNonEmptyString(process.env[envName]);
|
|
172
|
+
if (raw) {
|
|
173
|
+
const parsed = Number.parseInt(raw, 10);
|
|
174
|
+
if (Number.isFinite(parsed) && parsed >= min && parsed <= max) return parsed;
|
|
175
|
+
}
|
|
176
|
+
return def;
|
|
177
|
+
}
|
|
178
|
+
function resolveAckedDeathDeadlineMs(): number {
|
|
179
|
+
// Default 8 min — FAR above the variable emit latency the finite R4..R4e timers raced (R4e's
|
|
180
|
+
// worst case was ~16s); by the time this fires a live worker would long since have emitted its
|
|
181
|
+
// real terminal. The env-override floor is 0 so tests can force the deadline (production never
|
|
182
|
+
// sets it that low); the ceiling is 60min so a mis-set env cannot disable the loss-net forever.
|
|
183
|
+
return resolveTunedReconcileMs('MESH_INFLIGHT_ACKED_DEATH_DEADLINE_MS', 8 * 60_000, 0, 60 * 60_000);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ACKED-HOLD-IDLE-OVERTRUST (transcript-completion fast-track). The indefinite acked-hold above is
|
|
187
|
+
// safe but SLOW: when the worker's real generating_completed emit is dropped/lost, the only thing
|
|
188
|
+
// that promotes the missing completion is the 8-min death backstop — even though the answer has been
|
|
189
|
+
// FULLY rendered in the transcript for minutes (read_chat reports idle WITH a final visible assistant
|
|
190
|
+
// message every ~4s). Observed live: completions surfaced 144s / 492s late, both incompatible with the
|
|
191
|
+
// provider's own emit ceiling (COMPLETED_FINALIZATION_MAX_WAIT_MS 30s + NATIVE_HISTORY_MESH_IDLE_SETTLE
|
|
192
|
+
// 4s ≈ 34s). That gap = a worker that finished, whose PTY generating→idle edge / real emit was lost,
|
|
193
|
+
// held hostage to the 8-min net.
|
|
194
|
+
//
|
|
195
|
+
// Fast-track: when an acked task reads idle AND a final visible assistant message is present (the same
|
|
196
|
+
// transcript-completion evidence PHASE 4 already requires to synth), and that idle-with-final-assistant
|
|
197
|
+
// state has PERSISTED for a short continuous grace, promote the synth EARLY — ahead of the 8-min
|
|
198
|
+
// backstop. The grace is the correctness gate: a SINGLE idle read could be a mid-turn blip (PTY
|
|
199
|
+
// inter-tool-call settle, or final text rendered while the next tool call is about to start), so we
|
|
200
|
+
// require the idle-with-final-assistant signal to hold continuously for the grace window before
|
|
201
|
+
// trusting it as a genuine turn-end. Any non-idle read (generating / waiting_approval), a read
|
|
202
|
+
// failure, or the disappearance of the final assistant message RESETS the streak — so an actively
|
|
203
|
+
// streaming worker that momentarily reads idle never crosses the grace.
|
|
204
|
+
//
|
|
205
|
+
// Safety: this only changes WHEN an acked synth fires (earlier), never WHETHER it is correct —
|
|
206
|
+
// reconcileDirectDispatchCompletionFromTranscript's hasTerminalLedgerAfterDispatch makes a real
|
|
207
|
+
// emit that lands later an idempotent no-op, exactly as the death-backstop synth relies on. The
|
|
208
|
+
// death backstop (8 min) is PRESERVED unchanged as the final net; the fast-track is a faster path in
|
|
209
|
+
// front of it. The grace is set ABOVE the provider's own emit ceiling (~34s) so a worker still inside
|
|
210
|
+
// its normal finalization window is never pre-empted — we only fast-track once enough continuous idle
|
|
211
|
+
// has elapsed that a live emit would already have arrived.
|
|
212
|
+
function resolveAckedTranscriptFastTrackGraceMs(): number {
|
|
213
|
+
// Default 40s — above the provider emit ceiling (30s COMPLETED_FINALIZATION_MAX_WAIT_MS + 4s
|
|
214
|
+
// NATIVE_HISTORY_MESH_IDLE_SETTLE ≈ 34s): a genuinely-live worker would have emitted its real
|
|
215
|
+
// terminal within that window, so 40s of CONTINUOUS idle-with-final-assistant means the emit was
|
|
216
|
+
// lost, not late. Far below the 8-min death backstop, so the fast-track is the dominant path for a
|
|
217
|
+
// lost emit while the backstop remains the last-resort net. Floor 0 lets tests force an immediate
|
|
218
|
+
// fast-track; ceiling 5min keeps a mis-set env from collapsing it into the death backstop.
|
|
219
|
+
return resolveTunedReconcileMs('MESH_INFLIGHT_ACKED_TRANSCRIPT_FASTTRACK_GRACE_MS', 40_000, 0, 5 * 60_000);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Per-task in-flight hold state for an acked dispatch:
|
|
223
|
+
// - liveConfirmedSinceAck: we have seen at least one conclusive read (idle OR generating) since
|
|
224
|
+
// the ack — proves the session is reachable, so a later read FAILURE is a genuine liveness loss
|
|
225
|
+
// rather than a node that was never reachable.
|
|
226
|
+
// - consecutiveReadFailures: streak of inconclusive read_chat results (death backstop (a)).
|
|
227
|
+
// - transcriptIdleSinceMs: the timestamp of the FIRST tick in the current continuous run of
|
|
228
|
+
// idle-with-final-assistant reads (ACKED-HOLD-IDLE-OVERTRUST fast-track). Cleared to undefined
|
|
229
|
+
// whenever the signal breaks (non-idle read, read failure, or no final assistant message), so a
|
|
230
|
+
// mid-turn idle blip never accumulates grace. When `now - transcriptIdleSinceMs` exceeds the
|
|
231
|
+
// fast-track grace the synth is promoted ahead of the death backstop.
|
|
232
|
+
interface AckedHoldState {
|
|
233
|
+
liveConfirmedSinceAck: boolean;
|
|
234
|
+
consecutiveReadFailures: number;
|
|
235
|
+
transcriptIdleSinceMs?: number;
|
|
236
|
+
}
|
|
237
|
+
const inFlightAckedHoldState = new Map<string, AckedHoldState>();
|
|
238
|
+
|
|
239
|
+
function inFlightSynthKey(meshId: string, taskId: string): string {
|
|
240
|
+
return `${meshId}::${taskId}`;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Test hook: clear the in-flight acked-hold state between cases.
|
|
244
|
+
export function __resetReconcileInFlightSynthDebounceForTests(): void {
|
|
245
|
+
inFlightAckedHoldState.clear();
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
interface LiveCoordinator {
|
|
249
|
+
meshId: string;
|
|
250
|
+
instance: ReturnType<DaemonComponents['instanceManager']['getInstance']>;
|
|
251
|
+
// Runtime session id of this coordinator instance (getState().instanceId). PHASE 2
|
|
252
|
+
// strict-matches an event's targetCoordinatorSessionId against this so a completion
|
|
253
|
+
// routes back to the exact originating coordinator session, not a sibling on the same
|
|
254
|
+
// daemon (the multi-coordinator misroute).
|
|
255
|
+
sessionId: string;
|
|
256
|
+
// PTY-OVERTRUST-DRAIN (Defect B): drain-eligibility, decided on the RAW adapter
|
|
257
|
+
// turn-state (mask-stripped) — NOT on getState().status, which overlays the
|
|
258
|
+
// auto-approve "hold-idle" visual mask that paints a genuinely-idle coordinator
|
|
259
|
+
// `generating` and so used to strand its worker's completion. True only when the
|
|
260
|
+
// raw adapter is at a real turn end AND the session is not modal-parked. When the
|
|
261
|
+
// instance does not expose getDrainStatus() (non-CLI / older), this falls back to
|
|
262
|
+
// the masked `status === 'idle'` (the pre-fix behaviour) so nothing regresses.
|
|
263
|
+
idle: boolean;
|
|
264
|
+
// True when the coordinator session is parked on a harness modal awaiting a
|
|
265
|
+
// human answer — claude-cli AskUserQuestion (waiting_choice) or a tool-consent
|
|
266
|
+
// prompt (waiting_approval). A force-inject into such a session would write raw
|
|
267
|
+
// keystrokes the modal key handler consumes, silently selecting a choice the
|
|
268
|
+
// user never made (data corruption). PHASE 2 excludes these from force-inject
|
|
269
|
+
// and leaves the event queued for a later (modal-resolved) tick.
|
|
270
|
+
modalParked: boolean;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// The set of coordinator-daemon ids THIS daemon answers to when draining the
|
|
274
|
+
// pending-events queue. A unicast completion event is stamped with the worker's
|
|
275
|
+
// meshCoordinatorDaemonId, which can be either:
|
|
276
|
+
// - the daemon's canonical status id (`standalone_<machineId>` / `daemon_<machineId>`),
|
|
277
|
+
// stamped by the MCP layer via ctx.localDaemonId (= getStatus().status.instanceId), or
|
|
278
|
+
// - the bare machineId, stamped by the local queue-assignment path (loadConfig().machineId).
|
|
279
|
+
// - the config-form node daemonId (`daemon_<machineId>`), which the MCP layer's
|
|
280
|
+
// resolveCoordinatorDaemonId prefers and stamps onto direct-dispatch workers.
|
|
281
|
+
// Draining with only one of these silently misses events stamped with the other —
|
|
282
|
+
// the exact reason a generating coordinator never self-received local completions,
|
|
283
|
+
// and the base-node completion-surface bug (base completions land full-form
|
|
284
|
+
// `daemon_<machineId>` while a coordinator that only knows itself as bare
|
|
285
|
+
// `<machineId>` never matches them). We expand to EVERY equivalent form so the
|
|
286
|
+
// scope match (host gate, self-node detection, and the drain IN-filter downstream)
|
|
287
|
+
// succeeds regardless of which path stamped the event.
|
|
288
|
+
function resolveCoordinatorDaemonIds(components: DaemonComponents): string[] {
|
|
289
|
+
const statusInstanceId = readNonEmptyString((components as { statusInstanceId?: string }).statusInstanceId);
|
|
290
|
+
const machineId = readNonEmptyString(loadConfig().machineId);
|
|
291
|
+
return expandDaemonIdForms([statusInstanceId, machineId]);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// Whether THIS daemon is the coordinator/host for a mesh — i.e. the daemon that
|
|
295
|
+
// owns coordinator ownership and must collect every worker node's completion
|
|
296
|
+
// events into its local queue. This is true regardless of whether a *live CLI*
|
|
297
|
+
// coordinator session currently exists: the coordinator is frequently a pure
|
|
298
|
+
// stdio MCP LLM (no live CLI session to inject into), and that LLM only sees the
|
|
299
|
+
// queue when it next calls a mesh tool. For it to see remote worker completions
|
|
300
|
+
// at all, the daemon must have already pulled them into the local queue on the
|
|
301
|
+
// timer — which is exactly what this predicate gates.
|
|
302
|
+
//
|
|
303
|
+
// Rule: this daemon hosts the mesh when meshHost.role is 'host' (the default for
|
|
304
|
+
// standalone-compat meshes with no host metadata) AND, when a hostDaemonId is
|
|
305
|
+
// pinned, it resolves to one of this daemon's ids. Member-only daemons return
|
|
306
|
+
// false — their own queue is pulled BY the host, not the other way around.
|
|
307
|
+
//
|
|
308
|
+
// `daemonIds` here is the EXPANDED self-identity set (runtime drain ids ∪ this
|
|
309
|
+
// daemon's mesh-config node id forms) — see resolveCoordinatorSelfIds. The
|
|
310
|
+
// pinned hostDaemonId is itself a config-form id and frequently does NOT equal a
|
|
311
|
+
// runtime id (bare machineId / status id), so gating on the runtime ids alone
|
|
312
|
+
// would wrongly classify the real host as a non-host and skip the remote pull
|
|
313
|
+
// entirely.
|
|
314
|
+
function daemonHostsMesh(mesh: LocalMeshEntry, daemonIds: string[]): boolean {
|
|
315
|
+
const host = mesh.meshHost;
|
|
316
|
+
// No metadata → default host (standalone compatibility, see createDefaultMeshHostMetadata).
|
|
317
|
+
if (!host) return true;
|
|
318
|
+
if (host.role && host.role !== 'host') return false;
|
|
319
|
+
const hostDaemonId = readNonEmptyString(host.hostDaemonId);
|
|
320
|
+
// Host role but no pinned hostDaemonId → treat as host (single-daemon / legacy).
|
|
321
|
+
if (!hostDaemonId) return true;
|
|
322
|
+
return daemonIdListIncludes(daemonIds, hostDaemonId);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function daemonIdListIncludes(ids: readonly string[], id: string | undefined): boolean {
|
|
326
|
+
if (!id) return false;
|
|
327
|
+
return ids.some(candidate => candidate === id || daemonIdsEquivalent(candidate, id));
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// Resolve EVERY id-form this daemon answers to FOR A GIVEN MESH: the runtime drain
|
|
331
|
+
// ids (status id + bare machineId) unioned with this daemon's mesh-config identity
|
|
332
|
+
// forms — the self node's daemonId/machineId (the node whose daemonId/machineId
|
|
333
|
+
// matches a runtime id) and the pinned meshHost.hostDaemonId WHEN it is provably
|
|
334
|
+
// ours. This is the single source of truth for "is this id me?" across both the
|
|
335
|
+
// host gate and the remote pull filter; the worker's meshCoordinatorDaemonId stamp
|
|
336
|
+
// is guaranteed to be one of these forms (it comes from resolveCoordinatorDaemonId,
|
|
337
|
+
// which prefers the coordinator node's config-form daemonId over the runtime status id).
|
|
338
|
+
function resolveCoordinatorSelfIds(mesh: LocalMeshEntry, drainDaemonIds: string[]): string[] {
|
|
339
|
+
const ids = new Set<string>(drainDaemonIds);
|
|
340
|
+
// Expand with the config-form id(s) of the self node — the mesh node whose
|
|
341
|
+
// daemonId/machineId matches a runtime id. Its config-form daemonId is exactly
|
|
342
|
+
// what resolveCoordinatorNode()→resolveCoordinatorDaemonId() stamps onto a worker.
|
|
343
|
+
for (const node of mesh.nodes) {
|
|
344
|
+
const nodeDaemonId = readNonEmptyString(node.daemonId);
|
|
345
|
+
const nodeMachineId = readNonEmptyString(node.machineId);
|
|
346
|
+
const isSelf = (nodeDaemonId && daemonIdListIncludes(drainDaemonIds, nodeDaemonId))
|
|
347
|
+
|| (nodeMachineId && daemonIdListIncludes(drainDaemonIds, nodeMachineId));
|
|
348
|
+
if (!isSelf) continue;
|
|
349
|
+
if (nodeDaemonId) ids.add(nodeDaemonId);
|
|
350
|
+
if (nodeMachineId) ids.add(nodeMachineId);
|
|
351
|
+
}
|
|
352
|
+
// The pinned host id is included ONLY when it is provably one of THIS daemon's ids
|
|
353
|
+
// (it already matches a runtime id or a resolved self-node id). A hostDaemonId that
|
|
354
|
+
// names a DIFFERENT daemon must NOT be claimed — that would make a member-only
|
|
355
|
+
// daemon believe it is the host and pull queues it does not own. Having a node on
|
|
356
|
+
// this daemon does not make this daemon the host; daemonHostsMesh still honours a
|
|
357
|
+
// foreign hostDaemonId and rejects ownership.
|
|
358
|
+
const hostDaemonId = readNonEmptyString(mesh.meshHost?.hostDaemonId);
|
|
359
|
+
if (hostDaemonId && daemonIdListIncludes([...ids], hostDaemonId)) ids.add(hostDaemonId);
|
|
360
|
+
return [...ids];
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Observability: last-seen modal-park state per coordinator session, so we LOG.info
|
|
364
|
+
// only on a TRANSITION (clear → parked, parked → cleared) instead of every 4s tick.
|
|
365
|
+
// Per-process; a restart re-logs the first observation, which is desirable — it
|
|
366
|
+
// re-confirms a coordinator that is still parked after the restart (the exact
|
|
367
|
+
// "restart does not clear it" symptom the operator needs visibility into).
|
|
368
|
+
const coordinatorModalParkState = new Map<string, boolean>();
|
|
369
|
+
|
|
370
|
+
// Find live CLI coordinator instances on THIS daemon, keyed by mesh.
|
|
371
|
+
function findLiveCoordinators(components: DaemonComponents): LiveCoordinator[] {
|
|
372
|
+
const out: LiveCoordinator[] = [];
|
|
373
|
+
for (const inst of components.instanceManager.getByCategory('cli')) {
|
|
374
|
+
const state = inst.getState();
|
|
375
|
+
const settings = state.settings && typeof state.settings === 'object'
|
|
376
|
+
? state.settings as Record<string, unknown>
|
|
377
|
+
: {};
|
|
378
|
+
const meshId = readNonEmptyString(settings.meshCoordinatorFor);
|
|
379
|
+
if (!meshId) continue;
|
|
380
|
+
const status = readNonEmptyString(state.status).toLowerCase();
|
|
381
|
+
// getState() overlays the modal-park statuses: an active AskUserQuestion
|
|
382
|
+
// prompt surfaces as waiting_choice, a tool-consent prompt as waiting_approval.
|
|
383
|
+
// NOTIF-HELD-DRAIN (Fix 1): consult the instance's own isModalParked() rather than the
|
|
384
|
+
// raw status literal so the corrected classification flows here — a busy mesh
|
|
385
|
+
// coordinator's routine, in-flight tool-consent (auto-approve off) is NOT a human-await
|
|
386
|
+
// modal and must NOT wedge the mesh's pending completion events under `modal_parked`.
|
|
387
|
+
// resolveModalParkStatus() (which isModalParked wraps) already encodes that distinction
|
|
388
|
+
// and the waiting_choice/stalled-auto-approve genuine-modal cases. Fall back to the
|
|
389
|
+
// status literal for any instance that does not expose the method. Lowercase compare —
|
|
390
|
+
// the SessionStatus enum is forked across modules and waiting_choice is absent from some.
|
|
391
|
+
const modalParked = typeof (inst as any).isModalParked === 'function'
|
|
392
|
+
? (inst as any).isModalParked() === true
|
|
393
|
+
: (status === 'waiting_choice' || status === 'waiting_approval');
|
|
394
|
+
// PTY-OVERTRUST-DRAIN (Defect B, fix A): drain-eligible idle is decided on the
|
|
395
|
+
// RAW adapter turn-state, not getState().status. getState() overlays the
|
|
396
|
+
// auto-approve hold-idle mask that paints a genuinely-idle coordinator
|
|
397
|
+
// `generating` (a UI-flicker suppressant), and the reconcile loop used to trust
|
|
398
|
+
// that mask and HOLD the worker's completion (generating_no_idle_coordinator)
|
|
399
|
+
// even though the PTY was at a real turn end. getDrainStatus() strips the mask
|
|
400
|
+
// (raw adapter idle, modal-park preserved). Fall back to the masked literal for
|
|
401
|
+
// any instance that does not expose it (non-CLI / older) — regression-0.
|
|
402
|
+
const drainStatus: string | null = typeof (inst as any).getDrainStatus === 'function'
|
|
403
|
+
? (inst as any).getDrainStatus()
|
|
404
|
+
: null;
|
|
405
|
+
const idle = drainStatus !== null ? drainStatus === 'idle' : (status === 'idle');
|
|
406
|
+
const sessionId = readNonEmptyString(state.instanceId);
|
|
407
|
+
// ── NOTIF (B) desync diagnostic (read-only, no behavior change) ───────────
|
|
408
|
+
// The confirmed (B) defect: a coordinator whose FSM is idle (status above ===
|
|
409
|
+
// 'idle' for minutes) is nonetheless classified busy here, so the generating/
|
|
410
|
+
// modal-park hold never drains and a worker completion is stranded until the
|
|
411
|
+
// user's next turn edge. Static analysis found no code path where getState()
|
|
412
|
+
// returns generating while lastStatus and the adapter raw are both idle — so the
|
|
413
|
+
// divergence is a runtime desync between the three status sources. Capture all
|
|
414
|
+
// three (plus the auto-approve mask state that getState() overlays at :803) for
|
|
415
|
+
// EVERY mesh-coordinator candidate on this tick, so the source that diverges from
|
|
416
|
+
// the others can be read directly against the same-tick "skip → generating"/
|
|
417
|
+
// "skip → modal-parked" hold logs below (pair by sessionId + timestamp).
|
|
418
|
+
//
|
|
419
|
+
// CRITICAL: reuse the `state` already fetched above (line ~301) — do NOT call
|
|
420
|
+
// getState() again. getState() runs maybeAutoApproveStatus() as a side effect,
|
|
421
|
+
// which would mutate the very auto-approve mask we are trying to observe. The
|
|
422
|
+
// adapter raw read uses allowParse:false, which only reads engine.activeModal and
|
|
423
|
+
// is side-effect-free.
|
|
424
|
+
if (getLogLevel() === 'debug') {
|
|
425
|
+
let adapterRaw = '?';
|
|
426
|
+
try {
|
|
427
|
+
const a = (inst as any).adapter;
|
|
428
|
+
if (a && typeof a.getStatus === 'function') {
|
|
429
|
+
adapterRaw = readNonEmptyString(a.getStatus({ allowParse: false })?.status) || '?';
|
|
430
|
+
}
|
|
431
|
+
} catch (e: any) {
|
|
432
|
+
adapterRaw = `err:${e?.message || e}`;
|
|
433
|
+
}
|
|
434
|
+
const lastStatus = readNonEmptyString((inst as any).lastStatus) || '?';
|
|
435
|
+
const autoApproveBusy = (inst as any).autoApproveBusy;
|
|
436
|
+
const maskSince = (inst as any).autoApproveMaskSince;
|
|
437
|
+
// PTY-OVERTRUST-DRAIN: include the mask-stripped drainStatus next to the three
|
|
438
|
+
// legacy sources so the divergence (getState=generating while adapterRaw=idle =
|
|
439
|
+
// the mask) is directly readable, and confirm drain now follows adapterRaw.
|
|
440
|
+
LOG.debug('MeshReconcile', `coordDiag sess=${sessionId || '?'} mesh=${meshId} getState=${status || '?'} drainStatus=${drainStatus || 'n/a'} lastStatus=${lastStatus} adapterRaw=${adapterRaw} autoApproveBusy=${autoApproveBusy === true} maskSince=${maskSince || 0}`);
|
|
441
|
+
}
|
|
442
|
+
// Modal-park transition observability: a coordinator entering modal-park is what
|
|
443
|
+
// begins holding completion events under `modal_parked`; one leaving it is what
|
|
444
|
+
// drains them. Both transitions were previously SILENT (the operator had no log
|
|
445
|
+
// to diagnose a stuck/held completion), so emit a single line per edge.
|
|
446
|
+
const stateKey = `${meshId}::${sessionId || '?'}`;
|
|
447
|
+
const prevParked = coordinatorModalParkState.get(stateKey);
|
|
448
|
+
if (prevParked !== modalParked) {
|
|
449
|
+
coordinatorModalParkState.set(stateKey, modalParked);
|
|
450
|
+
if (modalParked) {
|
|
451
|
+
LOG.info('MeshReconcile', `Coordinator ${sessionId || '?'} (mesh ${meshId}) entered modal-park (status=${status}) — terminal events for it will be held until the modal is answered`);
|
|
452
|
+
} else if (prevParked === true) {
|
|
453
|
+
LOG.info('MeshReconcile', `Coordinator ${sessionId || '?'} (mesh ${meshId}) left modal-park (status=${status}) — held events will drain on this/next tick`);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
out.push({ meshId, instance: inst, sessionId, idle, modalParked });
|
|
457
|
+
}
|
|
458
|
+
return out;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* DRAIN-WITHOUT-INJECT guard. Classify, for a mesh on THIS daemon, whether a
|
|
463
|
+
* queue-drain caller (the MCP `get_pending_mesh_events` poll) may safely consume
|
|
464
|
+
* pending coordinator events — i.e. whether there is a surface that will actually
|
|
465
|
+
* deliver them.
|
|
466
|
+
*
|
|
467
|
+
* Root cause being guarded: `get_pending_mesh_events` marks rows drained=1
|
|
468
|
+
* atomically and unconditionally. When the live CLI coordinator for the mesh is
|
|
469
|
+
* GENERATING (or modal-parked), the reconcile loop correctly HOLDS its terminal
|
|
470
|
+
* events (drained=0) for the coordinator's next idle tick — but a concurrent MCP
|
|
471
|
+
* poll draining the SAME queue consumes those held rows into a tool result that
|
|
472
|
+
* the busy coordinator never surfaces as a turn, so the completion is lost
|
|
473
|
+
* forever (drained=1, never re-queued). The reconcile loop is the authoritative
|
|
474
|
+
* delivery path for a live CLI coordinator; the MCP poll must defer to it.
|
|
475
|
+
*
|
|
476
|
+
* Returns:
|
|
477
|
+
* - hasLiveCliCoordinator: a CLI session with meshCoordinatorFor === meshId
|
|
478
|
+
* exists on this daemon (the reconcile loop owns its delivery).
|
|
479
|
+
* - deliverableNow: there is an IDLE live CLI coordinator (reconcile would
|
|
480
|
+
* full-drain into it) — draining now is safe and equivalent.
|
|
481
|
+
* - holdForReconcile: a live CLI coordinator exists but is non-idle
|
|
482
|
+
* (generating / modal-parked). The MCP poll MUST NOT drain; the reconcile
|
|
483
|
+
* loop holds the events undrained and injects them on the next idle tick.
|
|
484
|
+
*
|
|
485
|
+
* A mesh with NO live CLI coordinator on this daemon is a pure stdio MCP / LLM
|
|
486
|
+
* coordinator: the MCP tool result IS the only surface, so the poll legitimately
|
|
487
|
+
* drains (holdForReconcile=false). No regression to that path.
|
|
488
|
+
*/
|
|
489
|
+
export function resolveCoordinatorDrainDeliverability(
|
|
490
|
+
components: Pick<DaemonComponents, 'instanceManager'>,
|
|
491
|
+
meshId: string,
|
|
492
|
+
): { hasLiveCliCoordinator: boolean; deliverableNow: boolean; holdForReconcile: boolean } {
|
|
493
|
+
const coordinators = findLiveCoordinators(components as DaemonComponents).filter(c => c.meshId === meshId);
|
|
494
|
+
if (coordinators.length === 0) {
|
|
495
|
+
return { hasLiveCliCoordinator: false, deliverableNow: false, holdForReconcile: false };
|
|
496
|
+
}
|
|
497
|
+
const hasIdle = coordinators.some(c => c.idle);
|
|
498
|
+
return {
|
|
499
|
+
hasLiveCliCoordinator: true,
|
|
500
|
+
deliverableNow: hasIdle,
|
|
501
|
+
// A live CLI coordinator exists but none is idle → the reconcile loop is
|
|
502
|
+
// holding the events; the poll must not steal them.
|
|
503
|
+
holdForReconcile: !hasIdle,
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* DRAIN-WITHOUT-INJECT guard for the `get_pending_mesh_events` daemon handler.
|
|
509
|
+
*
|
|
510
|
+
* Decides whether an incoming pending-events DRAIN must be held (return nothing,
|
|
511
|
+
* leave rows drained=0) because the only surface for those events is a LOCAL live
|
|
512
|
+
* CLI coordinator that is currently busy (generating / modal-parked) — in which
|
|
513
|
+
* case the reconcile loop owns delivery on the coordinator's next idle tick, and
|
|
514
|
+
* the poll draining them now would lose them.
|
|
515
|
+
*
|
|
516
|
+
* The hold applies ONLY when BOTH:
|
|
517
|
+
* 1) a live CLI coordinator for this mesh on THIS daemon is non-idle, AND
|
|
518
|
+
* 2) the drain is targeted at THIS daemon (the requested coordinatorDaemonId is
|
|
519
|
+
* empty/broadcast, or matches one of this daemon's id forms).
|
|
520
|
+
*
|
|
521
|
+
* A REMOTE coordinator pulling our worker's events passes its own (remote)
|
|
522
|
+
* coordinatorDaemonId — condition (2) is false — so the drain proceeds and the
|
|
523
|
+
* remote pull is never blocked by our local coordinator's busy state. A pure
|
|
524
|
+
* stdio MCP coordinator (no live CLI session) never satisfies (1), so its tool
|
|
525
|
+
* result remains the surface and the drain proceeds. No regression to either.
|
|
526
|
+
*/
|
|
527
|
+
export function shouldHoldPendingDrainForBusyLocalCoordinator(
|
|
528
|
+
components: Pick<DaemonComponents, 'instanceManager'> & { statusInstanceId?: string },
|
|
529
|
+
meshId: string,
|
|
530
|
+
requestedCoordinatorDaemonId?: string | null,
|
|
531
|
+
): boolean {
|
|
532
|
+
if (!meshId) return false;
|
|
533
|
+
const deliverability = resolveCoordinatorDrainDeliverability(components, meshId);
|
|
534
|
+
if (!deliverability.holdForReconcile) return false;
|
|
535
|
+
// The local CLI coordinator is busy. Hold only when the drain is for THIS daemon.
|
|
536
|
+
const requested = readNonEmptyString(requestedCoordinatorDaemonId);
|
|
537
|
+
if (!requested) return true; // broadcast drain → would consume the held local events
|
|
538
|
+
const localIds = expandDaemonIdForms([
|
|
539
|
+
readNonEmptyString((components as { statusInstanceId?: string }).statusInstanceId),
|
|
540
|
+
readNonEmptyString(loadConfig().machineId),
|
|
541
|
+
]);
|
|
542
|
+
return localIds.some(id => daemonIdsEquivalent(id, requested));
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// Inject a drained pending event into a live coordinator session. Force-inject
|
|
546
|
+
// events carry force:true so they bypass the busy send-guard and land in the PTY
|
|
547
|
+
// even while the coordinator is generating (see shouldForceInjectMeshEvent).
|
|
548
|
+
function injectPendingIntoCoordinator(
|
|
549
|
+
coordinator: LiveCoordinator['instance'],
|
|
550
|
+
pending: PendingMeshCoordinatorEvent,
|
|
551
|
+
): void {
|
|
552
|
+
if (!coordinator) return;
|
|
553
|
+
// NOTIF-DROP-SYNTH-NO-MESSAGE (defence-in-depth): a queued event with no coordinatorMessage
|
|
554
|
+
// used to be dropped here (drain-without-inject) — the row had already been consumed
|
|
555
|
+
// (drained=1) by the caller's drain, so silently returning lost it forever. The primary fix
|
|
556
|
+
// makes the transcript-reconcile synth always carry a coordinatorMessage, but as a backstop,
|
|
557
|
+
// lazily synthesize the [System] text for any force-inject (terminal: completion / approval /
|
|
558
|
+
// stop / refine·bootstrap) event that still arrives message-less, so it surfaces instead of
|
|
559
|
+
// vanishing. A NON-force lifecycle event (agent:ready / generating_started) legitimately
|
|
560
|
+
// carries no message and must NOT be injected (it is queued only to re-drive the claim state
|
|
561
|
+
// machine on pull) — for it we still return without injecting.
|
|
562
|
+
let coordinatorMessage = pending.coordinatorMessage;
|
|
563
|
+
if (!coordinatorMessage) {
|
|
564
|
+
if (!shouldForceInjectMeshEvent(pending.event)) return;
|
|
565
|
+
const metadataEvent = pending.metadataEvent && typeof pending.metadataEvent === 'object'
|
|
566
|
+
? pending.metadataEvent
|
|
567
|
+
: {};
|
|
568
|
+
coordinatorMessage = buildMeshSystemMessage({
|
|
569
|
+
event: pending.event,
|
|
570
|
+
nodeLabel: pending.nodeLabel,
|
|
571
|
+
metadataEvent,
|
|
572
|
+
});
|
|
573
|
+
if (!coordinatorMessage) return; // builder produced nothing — nothing to surface
|
|
574
|
+
LOG.warn('MeshReconcile', `Lazily synthesized missing coordinatorMessage for ${pending.event} (mesh ${pending.meshId}) at inject time — a queued terminal event arrived message-less`);
|
|
575
|
+
}
|
|
576
|
+
const force = shouldForceInjectMeshEvent(pending.event);
|
|
577
|
+
// EVTTRACE: event surfaced to the coordinator (injected into its live CLI session).
|
|
578
|
+
// This is the terminal happy-path stage. Observation only.
|
|
579
|
+
traceMeshEventStage('surfaced', {
|
|
580
|
+
taskId: pending.metadataEvent?.taskId,
|
|
581
|
+
sessionId: pending.metadataEvent?.targetSessionId ?? pending.targetCoordinatorSessionId,
|
|
582
|
+
nodeId: pending.nodeId,
|
|
583
|
+
meshId: pending.meshId,
|
|
584
|
+
event: pending.event,
|
|
585
|
+
}, force ? 'force-inject' : 'inject');
|
|
586
|
+
coordinator.onEvent('send_message', {
|
|
587
|
+
input: { text: coordinatorMessage, textFallback: coordinatorMessage },
|
|
588
|
+
...(force ? { force: true } : {}),
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// Held-event ledger dedup: fingerprints of held terminal events already written as an
|
|
593
|
+
// `event_held` ledger audit record in THIS process. Prevents the 4s reconcile tick from
|
|
594
|
+
// re-logging the same held event every interval while a coordinator stays modal-parked.
|
|
595
|
+
// Per-process only (not persisted) — if the daemon restarts while an event is still held
|
|
596
|
+
// it is re-logged once, which is desirable: it re-confirms the event is still undelivered.
|
|
597
|
+
const heldEventLedgerRecorded = new Set<string>();
|
|
598
|
+
|
|
599
|
+
// C1 (data safety): when a terminal completion/approval/bootstrap event cannot be
|
|
600
|
+
// delivered because the only coordinators are modal-parked, the event is held at
|
|
601
|
+
// drained=0 in the pending queue (SQLite + JSONL) for a later tick. That queue is
|
|
602
|
+
// disk-persisted but carries no operator-visible audit trail and can be silently
|
|
603
|
+
// dropped by the pending-file trim (100 KB / 50-entry cap). To guarantee a held
|
|
604
|
+
// completion's worker summary is never silently lost, mirror each held terminal event
|
|
605
|
+
// into the coordinator's mesh ledger as an `event_held` entry — auditable and
|
|
606
|
+
// recoverable (the finalSummary survives even if the pending copy is later trimmed or
|
|
607
|
+
// the coordinator session is force-resolved before re-drain). Idempotent per process
|
|
608
|
+
// via heldEventLedgerRecorded so a long modal park does not spam the ledger.
|
|
609
|
+
function recordHeldTerminalEventsToLedger(
|
|
610
|
+
meshId: string,
|
|
611
|
+
drainDaemonIds: string[],
|
|
612
|
+
reason: string,
|
|
613
|
+
heldForCoordinatorCount: number,
|
|
614
|
+
): void {
|
|
615
|
+
let pending: readonly PendingMeshCoordinatorEvent[];
|
|
616
|
+
try {
|
|
617
|
+
pending = getPendingMeshCoordinatorEvents(meshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
|
|
618
|
+
} catch {
|
|
619
|
+
return; // best-effort audit — never let a peek failure break the tick
|
|
620
|
+
}
|
|
621
|
+
for (const event of pending) {
|
|
622
|
+
// Only audit terminal/force-inject events (completion / approval / stop / refine·
|
|
623
|
+
// bootstrap). Silent lifecycle events (agent:ready / generating_started) carry no
|
|
624
|
+
// worker output to preserve and re-drain harmlessly, so they need no audit trail.
|
|
625
|
+
if (!shouldForceInjectMeshEvent(event.event)) continue;
|
|
626
|
+
const fingerprint = buildPendingEventFingerprint(event);
|
|
627
|
+
const key = `${meshId}::${fingerprint || `${event.event}::${event.nodeId || ''}::${event.queuedAt}`}`;
|
|
628
|
+
if (heldEventLedgerRecorded.has(key)) continue;
|
|
629
|
+
heldEventLedgerRecorded.add(key);
|
|
630
|
+
const finalSummary = readMeshCompletionSummary(event.metadataEvent);
|
|
631
|
+
try {
|
|
632
|
+
appendLedgerEntry(meshId, {
|
|
633
|
+
kind: 'event_held',
|
|
634
|
+
...(event.nodeId ? { nodeId: event.nodeId } : {}),
|
|
635
|
+
payload: {
|
|
636
|
+
event: event.event,
|
|
637
|
+
reason,
|
|
638
|
+
recoverable: true,
|
|
639
|
+
heldForCoordinators: heldForCoordinatorCount,
|
|
640
|
+
nodeLabel: event.nodeLabel,
|
|
641
|
+
...(event.workspace ? { workspace: event.workspace } : {}),
|
|
642
|
+
targetCoordinatorDaemonId: event.targetCoordinatorDaemonId ?? null,
|
|
643
|
+
queuedAt: event.queuedAt,
|
|
644
|
+
...(fingerprint ? { fingerprint } : {}),
|
|
645
|
+
...(finalSummary ? { finalSummary } : {}),
|
|
646
|
+
},
|
|
647
|
+
});
|
|
648
|
+
LOG.info('MeshReconcile', `Ledger-recorded held ${event.event} for mesh ${meshId} (reason ${reason}) — recoverable from ledger`);
|
|
649
|
+
} catch (e: any) {
|
|
650
|
+
// Failed to persist — drop the dedup marker so the next tick retries.
|
|
651
|
+
heldEventLedgerRecorded.delete(key);
|
|
652
|
+
LOG.warn('MeshReconcile', `Failed to ledger-record held ${event.event} for mesh ${meshId}: ${e?.message || e}`);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// PTY-OVERTRUST-DRAIN (Defect B, fix B). Age of the OLDEST queued terminal/force-inject
|
|
658
|
+
// event for a mesh, in ms — the signal the generating-hold age-escape gates on. Returns 0
|
|
659
|
+
// when there is no held terminal event (no escape needed). Best-effort: a peek failure
|
|
660
|
+
// returns 0 (no escape this tick), never throws into the tick.
|
|
661
|
+
function oldestHeldTerminalEventAgeMs(meshId: string, drainDaemonIds: string[]): number {
|
|
662
|
+
let pending: readonly PendingMeshCoordinatorEvent[];
|
|
663
|
+
try {
|
|
664
|
+
pending = getPendingMeshCoordinatorEvents(meshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
|
|
665
|
+
} catch {
|
|
666
|
+
return 0;
|
|
667
|
+
}
|
|
668
|
+
const now = Date.now();
|
|
669
|
+
let maxAge = 0;
|
|
670
|
+
for (const event of pending) {
|
|
671
|
+
if (!shouldForceInjectMeshEvent(event.event)) continue; // only terminal events matter
|
|
672
|
+
const queuedAt = typeof event.queuedAt === 'number' ? event.queuedAt : now;
|
|
673
|
+
const age = now - queuedAt;
|
|
674
|
+
if (age > maxAge) maxAge = age;
|
|
675
|
+
}
|
|
676
|
+
return maxAge;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
// PTY-OVERTRUST-DRAIN (Defect B, fix B). Re-confirm, on the RAW adapter (mask-stripped),
|
|
680
|
+
// which of the held-as-generating coordinators is GENUINELY idle right now. A coordinator
|
|
681
|
+
// whose getDrainStatus() reads 'idle' is a real drain target the time-based escape may
|
|
682
|
+
// deliver into. One that still reads 'generating'/'modal_parked'/'other' stays held — the
|
|
683
|
+
// escape NEVER injects into a genuinely-busy PTY (that is the data-loss force-inject path
|
|
684
|
+
// intentionally removed; re-confirmation is what keeps this safe). Falls back to the
|
|
685
|
+
// coordinator's already-computed `idle` flag when the instance does not expose
|
|
686
|
+
// getDrainStatus() (non-CLI / older) — that flag is itself raw-adapter-derived post-fix-A.
|
|
687
|
+
function reconfirmGenuinelyIdleCoordinators(generating: LiveCoordinator[]): LiveCoordinator[] {
|
|
688
|
+
const out: LiveCoordinator[] = [];
|
|
689
|
+
for (const c of generating) {
|
|
690
|
+
const inst = c.instance as any;
|
|
691
|
+
const drainStatus: string | null = typeof inst?.getDrainStatus === 'function'
|
|
692
|
+
? inst.getDrainStatus()
|
|
693
|
+
: null;
|
|
694
|
+
const genuinelyIdle = drainStatus !== null ? drainStatus === 'idle' : c.idle;
|
|
695
|
+
if (genuinelyIdle) out.push({ ...c, idle: true });
|
|
696
|
+
}
|
|
697
|
+
return out;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
// Full-drain the local pending queue for a mesh and inject every event into the given
|
|
701
|
+
// IDLE target coordinators, honouring strict session routing. Shared by the normal idle
|
|
702
|
+
// delivery path and the Defect-B age-escape so both deliver identically (one drain, one
|
|
703
|
+
// inject-per-event, strict-route hold for an unmatched session). Returns the number of
|
|
704
|
+
// events drained (0 when the queue was empty / drain failed). Callers must have already
|
|
705
|
+
// confirmed the targets are genuinely idle.
|
|
706
|
+
function drainAndInjectIntoTargets(
|
|
707
|
+
meshId: string,
|
|
708
|
+
drainDaemonIds: string[],
|
|
709
|
+
localDaemonId: string | undefined,
|
|
710
|
+
targetCoordinators: LiveCoordinator[],
|
|
711
|
+
logLabel: string,
|
|
712
|
+
): number {
|
|
713
|
+
let pendingEvents: PendingMeshCoordinatorEvent[] = [];
|
|
714
|
+
try {
|
|
715
|
+
pendingEvents = drainPendingMeshCoordinatorEvents(
|
|
716
|
+
meshId,
|
|
717
|
+
drainDaemonIds.length > 0 ? drainDaemonIds : localDaemonId,
|
|
718
|
+
);
|
|
719
|
+
} catch (e: any) {
|
|
720
|
+
LOG.warn('MeshReconcile', `Drain failed for mesh ${meshId}: ${e?.message || e}`);
|
|
721
|
+
return 0;
|
|
722
|
+
}
|
|
723
|
+
if (pendingEvents.length === 0) return 0;
|
|
724
|
+
|
|
725
|
+
LOG.info('MeshReconcile', `Reconcile inject → ${logLabel}: ${pendingEvents.length} pending event(s) → ${targetCoordinators.length} coordinator(s) for mesh ${meshId}`);
|
|
726
|
+
for (const pending of pendingEvents) {
|
|
727
|
+
// Strict session routing (multi-coordinator): when the event names an
|
|
728
|
+
// originating coordinator session, deliver ONLY to the live coordinator whose
|
|
729
|
+
// session id matches — a sibling coordinator on the same daemon must NOT receive
|
|
730
|
+
// another coordinator's completion. When the event carries no session id (legacy /
|
|
731
|
+
// version-skewed / single-coordinator), fall back to the daemon-level set
|
|
732
|
+
// (unchanged behaviour — regression-0 for the common case).
|
|
733
|
+
const wantSession = readNonEmptyString(pending.targetCoordinatorSessionId);
|
|
734
|
+
if (wantSession) {
|
|
735
|
+
// SESSION-ID IS SINGLE-FORM: a coordinator session id is one canonical
|
|
736
|
+
// UUID (crypto.randomUUID), carried verbatim end-to-end — no node/daemon-id
|
|
737
|
+
// style serialization variants. Exact `===` is the correct match; unlike
|
|
738
|
+
// the daemon-level set below it needs no equivalence helper.
|
|
739
|
+
const matched = targetCoordinators.filter(c => c.sessionId === wantSession);
|
|
740
|
+
if (matched.length === 0) {
|
|
741
|
+
// The originating coordinator session is not deliverable on this daemon
|
|
742
|
+
// right now (gone, or modal-parked and excluded from targets). Strict mode
|
|
743
|
+
// does NOT broadcast to siblings — hold the event for a later tick, and
|
|
744
|
+
// ledger-expire it past a TTL so it can never wedge forever.
|
|
745
|
+
holdOrExpireStrictUnmatchedEvent(pending, wantSession, meshId);
|
|
746
|
+
continue;
|
|
747
|
+
}
|
|
748
|
+
for (const c of matched) injectPendingIntoCoordinator(c.instance, pending);
|
|
749
|
+
continue;
|
|
750
|
+
}
|
|
751
|
+
for (const c of targetCoordinators) {
|
|
752
|
+
injectPendingIntoCoordinator(c.instance, pending);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
return pendingEvents.length;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// One reconcile tick. Two independent phases:
|
|
759
|
+
//
|
|
760
|
+
// PHASE 1 — Remote queue pull (the fix for remote worktree completions never
|
|
761
|
+
// reaching an MCP/LLM coordinator). For EVERY mesh this daemon hosts/
|
|
762
|
+
// coordinates, pull each remote worker node's pending-events queue over P2P
|
|
763
|
+
// into THIS daemon's local queue. This runs *regardless of whether a live CLI
|
|
764
|
+
// coordinator exists* — the coordinator is usually a pure stdio MCP LLM with
|
|
765
|
+
// no live CLI session, and it can only observe a remote worker's completion
|
|
766
|
+
// once that event has been pulled into the local queue (which it then drains
|
|
767
|
+
// on its next mesh tool call). Previously this pull was gated behind a live
|
|
768
|
+
// CLI coordinator and so never ran for MCP/LLM coordinators — remote
|
|
769
|
+
// completions sat on the remote node's queue until the LLM happened to call
|
|
770
|
+
// mesh_read_chat, which triggered the MCP-side pull. The daemon now does it
|
|
771
|
+
// autonomously on the timer. Standalone (no dispatchMeshCommand) skips this
|
|
772
|
+
// phase entirely — there are no remote nodes to pull from.
|
|
773
|
+
//
|
|
774
|
+
// PHASE 2 — Live CLI inject. For each mesh that has a live CLI coordinator on
|
|
775
|
+
// THIS daemon, drain the local queue and inject pending events into the PTY.
|
|
776
|
+
// Unchanged from before.
|
|
777
|
+
// Bug B: how long a row may sit 'assigned' with an unconfirmed dispatch before the
|
|
778
|
+
// watchdog reclaims it. Must be comfortably larger than the per-dispatch confirm
|
|
779
|
+
// timeout (DISPATCH_CONFIRM_TIMEOUT_MS in mesh-events-coordinator) so a slow-but-live
|
|
780
|
+
// dispatch still inside its normal confirm window is never reclaimed early — this is
|
|
781
|
+
// the durable backstop for the case the in-process confirm timer can't cover (a timer
|
|
782
|
+
// lost to a daemon restart between claim and confirm).
|
|
783
|
+
const ASSIGNED_STRANDED_DEADLINE_MS = 5 * 60_000;
|
|
784
|
+
|
|
785
|
+
// PHASE 2.5 — assigned-stranded dispatch watchdog (Bug B). claimNextTask atomically
|
|
786
|
+
// flips a row to 'assigned' BEFORE the fire-and-forget dispatch runs. If that dispatch
|
|
787
|
+
// neither rejects (→ no .catch requeue) nor is confirmed delivered — a relay that hangs
|
|
788
|
+
// without acking, or a confirm timer lost across a restart — the row stays 'assigned'
|
|
789
|
+
// forever: it contributes 0 pending, so PHASE 3 (gated on pendingQueueTaskCount>0) never
|
|
790
|
+
// re-examines it, and nothing but a manual requeue clears it. This is that missing net.
|
|
791
|
+
//
|
|
792
|
+
// Regression guard: a row whose delivery IS confirmed (delivered/acked/completed) is a
|
|
793
|
+
// genuinely in-flight (or completion-lost) task — left to PHASE 4's completion reconcile,
|
|
794
|
+
// never reclaimed here. And the deadline is generous so a slow-but-live dispatch still in
|
|
795
|
+
// its normal confirm window is never reclaimed early. Reclaimed rows return to 'pending'
|
|
796
|
+
// with ownership cleared, so the PHASE 3 trigger below re-dispatches them this same tick.
|
|
797
|
+
function recoverStrandedAssignedDispatches(meshId: string, store: MeshRuntimeStore): void {
|
|
798
|
+
const assigned = getQueue(meshId, { status: ['assigned'] });
|
|
799
|
+
if (!assigned.length) return;
|
|
800
|
+
const nowMs = Date.now();
|
|
801
|
+
for (const row of assigned) {
|
|
802
|
+
const dispatchedAtMs = Date.parse(row.dispatchTimestamp ?? '');
|
|
803
|
+
if (!Number.isFinite(dispatchedAtMs)) continue; // no dispatch ts → can't age it
|
|
804
|
+
if (nowMs - dispatchedAtMs < ASSIGNED_STRANDED_DEADLINE_MS) continue; // still in confirm window
|
|
805
|
+
const terminal = findTerminalLedgerEvidenceForTask({
|
|
806
|
+
meshId,
|
|
807
|
+
taskId: row.id,
|
|
808
|
+
});
|
|
809
|
+
if (terminal) {
|
|
810
|
+
const status = terminal.kind === 'task_completed' ? 'completed' : 'failed';
|
|
811
|
+
updateTaskStatus(meshId, row.id, status);
|
|
812
|
+
LOG.warn('MeshReconcile', `Skipped stranded reclaim redispatch for terminal task ${row.id} on mesh ${meshId}; ${terminal.kind} ledger evidence already exists`);
|
|
813
|
+
traceMeshEventDrop('assigned_stranded_terminal_ledger', {
|
|
814
|
+
taskId: row.id,
|
|
815
|
+
sessionId: row.assignedSessionId,
|
|
816
|
+
nodeId: row.assignedNodeId,
|
|
817
|
+
meshId,
|
|
818
|
+
event: 'agent:generating_completed',
|
|
819
|
+
}, terminal.kind);
|
|
820
|
+
continue;
|
|
821
|
+
}
|
|
822
|
+
if (store.taskHasConfirmedDelivery(meshId, row.id)) continue; // dispatched → PHASE 4's job
|
|
823
|
+
const reclaimed = reclaimStrandedAssignedTask(meshId, row.id, {
|
|
824
|
+
reason: 'assigned_stranded_dispatch_unconfirmed',
|
|
825
|
+
ageMs: nowMs - dispatchedAtMs,
|
|
826
|
+
});
|
|
827
|
+
if (reclaimed) {
|
|
828
|
+
LOG.warn('MeshReconcile', `Reclaimed stranded assigned task ${row.id} on mesh ${meshId} `
|
|
829
|
+
+ `(node=${row.assignedNodeId ?? '?'} session=${row.assignedSessionId ?? '?'}, dispatched `
|
|
830
|
+
+ `${Math.round((nowMs - dispatchedAtMs) / 1000)}s ago, never confirmed delivered → ${reclaimed.status})`);
|
|
831
|
+
// EVTTRACE: the dispatch for this task was stranded (assigned, never confirmed
|
|
832
|
+
// delivered) and reclaimed (CANON-B) — its expected completion event never
|
|
833
|
+
// arrived. Observation only; the reclaim decision above is unchanged.
|
|
834
|
+
traceMeshEventDrop('assigned_stranded_reclaim', {
|
|
835
|
+
taskId: row.id,
|
|
836
|
+
sessionId: row.assignedSessionId,
|
|
837
|
+
nodeId: row.assignedNodeId,
|
|
838
|
+
meshId,
|
|
839
|
+
event: 'agent:generating_completed',
|
|
840
|
+
}, `unconfirmed ${Math.round((nowMs - dispatchedAtMs) / 1000)}s → ${reclaimed.status}`);
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
export async function runMeshReconcileTick(components: DaemonComponents): Promise<void> {
|
|
846
|
+
const localDaemonId = readNonEmptyString(loadConfig().machineId) || undefined;
|
|
847
|
+
// The id-set used to scope the local queue drain (status id + machineId). See
|
|
848
|
+
// resolveCoordinatorDaemonIds — the status id is what the MCP layer stamps and
|
|
849
|
+
// is mandatory here for a generating CLI coordinator to self-receive completions.
|
|
850
|
+
const drainDaemonIds = resolveCoordinatorDaemonIds(components);
|
|
851
|
+
const dispatchMeshCommand = components.dispatchMeshCommand;
|
|
852
|
+
const store = (() => {
|
|
853
|
+
try { return MeshRuntimeStore.getInstance(); } catch { return undefined; }
|
|
854
|
+
})();
|
|
855
|
+
|
|
856
|
+
// ── PHASE 0: retry the worker-side unresolved-delegate forward outbox ──────
|
|
857
|
+
// Cloud-only (needs dispatchMeshCommand). A worker that is NOT a member of the
|
|
858
|
+
// coordinator's mesh cannot be reached by the coordinator's PHASE 1 pull (it is
|
|
859
|
+
// in no mesh.node), so its completion must be PUSHED to the coordinator. This
|
|
860
|
+
// drains the durable outbox enqueued by forwardUnresolvedDelegateEvent and retries
|
|
861
|
+
// any push that has not yet been acked. See mesh-unresolved-forward-outbox.ts.
|
|
862
|
+
if (dispatchMeshCommand) {
|
|
863
|
+
try {
|
|
864
|
+
await retryUnresolvedDelegateForwards(components);
|
|
865
|
+
} catch (e: any) {
|
|
866
|
+
LOG.warn('MeshReconcile', `Unresolved-delegate forward retry failed: ${e?.message || e}`);
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// ── PHASE 1: pull remote node queues for every mesh this daemon hosts ──────
|
|
871
|
+
// Cloud-only (dispatchMeshCommand present). Runs whether or not a live CLI
|
|
872
|
+
// coordinator exists — this is what lets an MCP/LLM coordinator ever see a
|
|
873
|
+
// remote worker's completion.
|
|
874
|
+
if (dispatchMeshCommand) {
|
|
875
|
+
for (const mesh of listMeshes()) {
|
|
876
|
+
// Expand to every id-form this daemon answers to for this mesh (runtime
|
|
877
|
+
// drain ids ∪ config-form node/host ids) and use it for BOTH the host gate
|
|
878
|
+
// and the remote pull filter, so a worker stamp in any form is recovered.
|
|
879
|
+
const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
|
|
880
|
+
if (!daemonHostsMesh(mesh, selfIds)) continue;
|
|
881
|
+
try {
|
|
882
|
+
await pullRemoteNodeQueues(components, mesh, localDaemonId, selfIds);
|
|
883
|
+
} catch (e: any) {
|
|
884
|
+
LOG.warn('MeshReconcile', `Remote node pull failed for mesh ${mesh.id}: ${e?.message || e}`);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
// ── PHASE 2.5: assigned-stranded dispatch watchdog (Bug B) ─────────────────
|
|
890
|
+
// Runs before PHASE 3 so any row it returns to 'pending' is re-dispatched by the
|
|
891
|
+
// PHASE 3 trigger in this same tick. See recoverStrandedAssignedDispatches.
|
|
892
|
+
if (store) {
|
|
893
|
+
for (const mesh of listMeshes()) {
|
|
894
|
+
const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
|
|
895
|
+
if (!daemonHostsMesh(mesh, selfIds)) continue;
|
|
896
|
+
try {
|
|
897
|
+
recoverStrandedAssignedDispatches(mesh.id, store);
|
|
898
|
+
} catch (e: any) {
|
|
899
|
+
LOG.warn('MeshReconcile', `Assigned-stranded watchdog failed for mesh ${mesh.id}: ${e?.message || e}`);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
// ── PHASE 3: recover pending queue claims for newly-idle sessions ──────────
|
|
905
|
+
// The event-driven claim paths (agent:ready / agent:generating_completed in
|
|
906
|
+
// mesh-events-coordinator) re-claim the queue the moment a session goes idle,
|
|
907
|
+
// but that depends on a single event being emitted AND (for a remote node)
|
|
908
|
+
// successfully forwarded to this coordinator. If that event is missed/dropped,
|
|
909
|
+
// a pending task targeting a now-idle session would sit unclaimed forever —
|
|
910
|
+
// there was no periodic safety net. This phase is that net: for every mesh this
|
|
911
|
+
// daemon hosts that has at least one pending task, run one triggerMeshQueue so a
|
|
912
|
+
// session that became idle without a delivered ready-event still gets its work.
|
|
913
|
+
//
|
|
914
|
+
// O(1) guard: skip the (relatively expensive) full idle-session + remote-idle
|
|
915
|
+
// scan entirely when the queue has no pending tasks — a COUNT(*) over the
|
|
916
|
+
// indexed status column, so an idle mesh costs one cheap query per tick.
|
|
917
|
+
// claimNextQueueTask is atomic, so racing the event-driven path can only have
|
|
918
|
+
// one winner; double-claiming is impossible.
|
|
919
|
+
for (const mesh of listMeshes()) {
|
|
920
|
+
const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
|
|
921
|
+
if (!daemonHostsMesh(mesh, selfIds)) continue;
|
|
922
|
+
if (store) {
|
|
923
|
+
try {
|
|
924
|
+
if (store.pendingQueueTaskCount(mesh.id) === 0) continue;
|
|
925
|
+
} catch { /* fall through and let triggerMeshQueue decide */ }
|
|
926
|
+
}
|
|
927
|
+
try {
|
|
928
|
+
await triggerMeshQueue(components, mesh.id);
|
|
929
|
+
} catch (e: any) {
|
|
930
|
+
LOG.warn('MeshReconcile', `Pending-claim recovery trigger failed for mesh ${mesh.id}: ${e?.message || e}`);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
// ── PHASE 4: synthesize lost completions for unterminated direct dispatches ─
|
|
935
|
+
// Symmetric to PHASE 3 (which recovers a *lost claim* for a newly-idle session)
|
|
936
|
+
// but for the opposite gap: a worker that ALREADY completed, went idle, and
|
|
937
|
+
// whose terminal completion event was never persisted (dropped before reaching
|
|
938
|
+
// the queue/outbox, or its forward was lost). PHASE 1/2/3 can only deliver an
|
|
939
|
+
// event that exists in a queue — they cannot recover a completion that was
|
|
940
|
+
// never recorded, so the coordinator keeps believing the worker is generating.
|
|
941
|
+
//
|
|
942
|
+
// reconcileDirectDispatchCompletionFromTranscript already synthesizes the
|
|
943
|
+
// missing terminal event from the worker's transcript, but until now it ran
|
|
944
|
+
// ONLY when an LLM coordinator polled mesh_status (mcp_mesh_status_transcript_
|
|
945
|
+
// reconciliation). This phase pulls that same correction onto the daemon timer
|
|
946
|
+
// so it no longer depends on the LLM polling. The reconcile is idempotent
|
|
947
|
+
// (hasTerminalLedgerAfterDispatch guards against re-synthesis), so attempting it
|
|
948
|
+
// every tick for the same dispatch is safe — once a terminal exists it no-ops.
|
|
949
|
+
for (const mesh of listMeshes()) {
|
|
950
|
+
const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
|
|
951
|
+
if (!daemonHostsMesh(mesh, selfIds)) continue;
|
|
952
|
+
try {
|
|
953
|
+
await reconcileUnterminatedDirectDispatches(components, mesh, selfIds, localDaemonId);
|
|
954
|
+
} catch (e: any) {
|
|
955
|
+
LOG.warn('MeshReconcile', `Completion reconcile failed for mesh ${mesh.id}: ${e?.message || e}`);
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
// ── PHASE 5: auto-prune orphaned direct dispatch records ───────────────────
|
|
960
|
+
// staleDirectWork (orphaned direct-dispatch rows whose node/session is no longer in the
|
|
961
|
+
// live mesh) otherwise accumulates indefinitely: a removed worktree node or a cleanly
|
|
962
|
+
// terminated session leaves its direct-dispatch row behind, stuck in a non-terminal status
|
|
963
|
+
// (e.g. generating) for days. This is NOT a false-idle bug — it is the separate problem of
|
|
964
|
+
// orphaned records that the only existing cleanup path (manual MCP mesh_prune_stale_direct)
|
|
965
|
+
// never reaches unless an operator runs it by hand.
|
|
966
|
+
//
|
|
967
|
+
// This phase runs the SAME prune core the manual tool calls (pruneStaleDirectDispatches),
|
|
968
|
+
// in execute mode, on the daemon timer. The only difference from the manual path is a
|
|
969
|
+
// conservative age gate (DEFAULT_AUTO_PRUNE_MIN_AGE_MS): a freshly-orphaned record is held
|
|
970
|
+
// back until it is provably stale, so a transient probe miss never auto-prunes live work.
|
|
971
|
+
// Every other safety rule is inherited unchanged from the core — active/pending/generating
|
|
972
|
+
// work and fresh unacknowledged dispatch failures are never pruned, ledger-only audit entries
|
|
973
|
+
// are preserved, and the prune itself is recorded with a direct_dispatch_pruned ledger entry.
|
|
974
|
+
// Idempotent: a pruned row is gone from getActiveDirectDispatches, so the next tick finds
|
|
975
|
+
// nothing to re-prune. Isolated in its own try/catch per mesh so it can never kill the tick.
|
|
976
|
+
{
|
|
977
|
+
const minAgeMs = resolveAutoPruneMinAgeMs();
|
|
978
|
+
for (const mesh of listMeshes()) {
|
|
979
|
+
const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
|
|
980
|
+
if (!daemonHostsMesh(mesh, selfIds)) continue;
|
|
981
|
+
try {
|
|
982
|
+
await autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs);
|
|
983
|
+
} catch (e: any) {
|
|
984
|
+
LOG.warn('MeshReconcile', `Auto-prune stale direct failed for mesh ${mesh.id}: ${e?.message || e}`);
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
// ── PHASE 2: inject into live CLI coordinators on this daemon ──────────────
|
|
990
|
+
const coordinators = findLiveCoordinators(components);
|
|
991
|
+
if (coordinators.length === 0) {
|
|
992
|
+
// No live CLI coordinator on this daemon — nothing to inject into.
|
|
993
|
+
// (MCP-only LLM coordinators drain the local queue via their own tool
|
|
994
|
+
// calls; PHASE 1 above has already populated it from remote nodes.)
|
|
995
|
+
return;
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
// Group coordinators by mesh; multiple coordinator instances for one mesh is
|
|
999
|
+
// unusual but supported (each gets the same drained events).
|
|
1000
|
+
const byMesh = new Map<string, LiveCoordinator[]>();
|
|
1001
|
+
for (const c of coordinators) {
|
|
1002
|
+
const list = byMesh.get(c.meshId);
|
|
1003
|
+
if (list) list.push(c);
|
|
1004
|
+
else byMesh.set(c.meshId, [c]);
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
for (const [meshId, meshCoordinators] of byMesh) {
|
|
1008
|
+
// Drain the local queue scoped to this coordinator daemon and inject.
|
|
1009
|
+
// - If an idle coordinator exists, FULL-drain and deliver every event to it
|
|
1010
|
+
// (the idle input box accepts the prompt as a real next turn). The drain
|
|
1011
|
+
// marks consumed rows drained=1 atomically, so the pull path can't re-deliver.
|
|
1012
|
+
// - If only GENERATING coordinators exist (no idle target), we HOLD: leave the
|
|
1013
|
+
// events queued (drained=0) for the coordinator's next idle/turn-end tick.
|
|
1014
|
+
//
|
|
1015
|
+
// NOTIF-SURFACE-LOCAL (false-idle hold): we used to force-inject terminal events
|
|
1016
|
+
// (completion/approval/stop/refine·bootstrap) straight into a *generating*
|
|
1017
|
+
// coordinator's PTY (forceSendMessage → atomic content+\r write), on the theory it
|
|
1018
|
+
// bypassed the busy send-guard and broke the await-result deadlock. But a raw PTY
|
|
1019
|
+
// write into a claude-cli that is mid-generation is NOT consumed as a new turn — the
|
|
1020
|
+
// bytes land in the terminal input buffer and the LLM never reads them on its next
|
|
1021
|
+
// turn. The `surfaced/force-inject` trace fired, the row was marked drained=1, and the
|
|
1022
|
+
// genuine completion was lost forever (the exact same-daemon local-worktree miss: the
|
|
1023
|
+
// coordinator's OWN session is generating at the moment its worker completes). The
|
|
1024
|
+
// deadlock the force path guarded against does not actually require force: a
|
|
1025
|
+
// coordinator that dispatched a task via mesh_send_task returns to idle when that
|
|
1026
|
+
// tool call resolves (dispatch is fire-and-forget; the worker runs for minutes while
|
|
1027
|
+
// the coordinator is idle/between turns), so the completion lands on the very next
|
|
1028
|
+
// idle tick (≤ one reconcile interval). Holding the event undrained for that idle
|
|
1029
|
+
// tick is therefore the single, reliable delivery — and it is the SAME skip-and-hold
|
|
1030
|
+
// the modal-park branch below already uses. This also makes double-injection
|
|
1031
|
+
// structurally impossible: there is exactly one delivery path (the idle full-drain),
|
|
1032
|
+
// so we never need a surface-time fingerprint to dedup a force-write against a re-drain.
|
|
1033
|
+
const idleCoordinators = meshCoordinators.filter(c => c.idle);
|
|
1034
|
+
// A coordinator parked on a harness modal (waiting_choice / waiting_approval) is
|
|
1035
|
+
// non-idle; it is held under the modal-park branch (a force-inject into a modal would
|
|
1036
|
+
// write raw keystrokes the modal key handler eats, silently selecting a choice the
|
|
1037
|
+
// user never made). A plainly-generating coordinator (non-idle, non-modal-parked) is
|
|
1038
|
+
// ALSO held now — for the false-idle reason above — but separately, so the C1 ledger
|
|
1039
|
+
// audit and the operator-facing skip log can name the right hold reason.
|
|
1040
|
+
const generatingCoordinators = meshCoordinators.filter(c => !c.idle && !c.modalParked);
|
|
1041
|
+
const modalParkedCoordinators = meshCoordinators.filter(c => !c.idle && c.modalParked);
|
|
1042
|
+
// Only an IDLE coordinator is a deliverable target. A generating coordinator's PTY
|
|
1043
|
+
// does not consume an injected prompt as a turn, so it is held (not a target).
|
|
1044
|
+
const targetCoordinators = idleCoordinators;
|
|
1045
|
+
|
|
1046
|
+
// ── no-idle-target short-circuit (MUST precede the drain) ─────────────────
|
|
1047
|
+
// When there is no IDLE coordinator for this mesh — only generating and/or
|
|
1048
|
+
// modal-parked ones — there is nowhere a queued event can land as a real turn.
|
|
1049
|
+
// We skip-and-hold: by NOT draining we leave the events at drained=0 in the queue,
|
|
1050
|
+
// so a later tick (once a coordinator returns to idle) delivers them. This
|
|
1051
|
+
// short-circuit MUST run BEFORE drainPendingMeshCoordinatorEvents — the drain marks
|
|
1052
|
+
// rows drained=1 atomically, which would lose the events for a coordinator that is
|
|
1053
|
+
// only transiently busy (the false-idle local-worktree miss). Both the generating
|
|
1054
|
+
// hold and the modal-park hold record a C1 ledger audit copy so a held completion's
|
|
1055
|
+
// worker summary is recoverable even if the coordinator never returns or the pending
|
|
1056
|
+
// file is later trimmed.
|
|
1057
|
+
if (targetCoordinators.length === 0) {
|
|
1058
|
+
if (modalParkedCoordinators.length > 0) {
|
|
1059
|
+
// ── orphan escape (MUST precede the blanket modal-park hold) ──────────
|
|
1060
|
+
// A modal-parked coordinator with no idle/generating sibling otherwise
|
|
1061
|
+
// wedges EVERY pending event under `modal_parked` until that modal resolves
|
|
1062
|
+
// — including a STRICT-routed completion whose originating coordinator
|
|
1063
|
+
// session is GONE (an orphan: the worktree/session that produced it was
|
|
1064
|
+
// removed, or that coordinator session died). Such an event will never be
|
|
1065
|
+
// deliverable to its target session no matter what the modal-parked sibling
|
|
1066
|
+
// does, so holding it under modal_parked is a permanent-held leak (the very
|
|
1067
|
+
// "data restart re-reproduces it" symptom — the gate is reconstructed live
|
|
1068
|
+
// from the still-parked modal, so a restart does not clear it). Route those
|
|
1069
|
+
// orphan events through the strict-route hold/expire path so the bounded
|
|
1070
|
+
// STRICT_SESSION_MATCH_TTL eventually expires them (recoverable, ledgered)
|
|
1071
|
+
// instead of leaving them held forever. A strict event whose target session
|
|
1072
|
+
// IS live but merely modal-parked is left to the blanket hold below (it is
|
|
1073
|
+
// genuinely transiently blocked, not orphaned).
|
|
1074
|
+
const liveSessionIds = new Set(
|
|
1075
|
+
meshCoordinators.map(c => readNonEmptyString(c.sessionId)).filter(Boolean),
|
|
1076
|
+
);
|
|
1077
|
+
let orphanEscaped = 0;
|
|
1078
|
+
const hasPendingForOrphanPeek = !store
|
|
1079
|
+
|| (() => { try { return store.pendingEventCount(meshId) > 0; } catch { return true; } })();
|
|
1080
|
+
if (hasPendingForOrphanPeek) {
|
|
1081
|
+
// Identify which pending event NAMES correspond to orphan-targeted events
|
|
1082
|
+
// (a strict targetCoordinatorSessionId that matches no live coordinator).
|
|
1083
|
+
let peeked: readonly PendingMeshCoordinatorEvent[] = [];
|
|
1084
|
+
try {
|
|
1085
|
+
peeked = getPendingMeshCoordinatorEvents(meshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
|
|
1086
|
+
} catch { peeked = []; }
|
|
1087
|
+
const isOrphan = (e: PendingMeshCoordinatorEvent): boolean => {
|
|
1088
|
+
const want = readNonEmptyString(e.targetCoordinatorSessionId);
|
|
1089
|
+
return !!want && !liveSessionIds.has(want);
|
|
1090
|
+
};
|
|
1091
|
+
const orphanEventNames = new Set(peeked.filter(isOrphan).map(e => e.event));
|
|
1092
|
+
if (orphanEventNames.size > 0) {
|
|
1093
|
+
// The drain filter is event-NAME scoped (not per-row), so draining by the
|
|
1094
|
+
// orphan event names also pulls any non-orphan event sharing that name. Drain
|
|
1095
|
+
// them all, then re-route: orphan-targeted events go through the strict-route
|
|
1096
|
+
// hold/expire path (bounded TTL → eventually ledger-expired, recoverable);
|
|
1097
|
+
// non-orphan events of the same name are re-queued unchanged (queuedAt
|
|
1098
|
+
// preserved) so they remain genuinely held for their still-live, modal-parked
|
|
1099
|
+
// target. This is the same per-event strict routing PHASE 2 does below — just
|
|
1100
|
+
// reached here because the blanket modal-park short-circuit would otherwise
|
|
1101
|
+
// wedge the orphans forever.
|
|
1102
|
+
let drained: PendingMeshCoordinatorEvent[] = [];
|
|
1103
|
+
try {
|
|
1104
|
+
drained = drainPendingMeshCoordinatorEvents(
|
|
1105
|
+
meshId,
|
|
1106
|
+
drainDaemonIds.length > 0 ? drainDaemonIds : localDaemonId,
|
|
1107
|
+
{ onlyEvents: orphanEventNames },
|
|
1108
|
+
);
|
|
1109
|
+
} catch (e: any) {
|
|
1110
|
+
LOG.warn('MeshReconcile', `Orphan-escape drain failed for mesh ${meshId}: ${e?.message || e}`);
|
|
1111
|
+
drained = [];
|
|
1112
|
+
}
|
|
1113
|
+
for (const pending of drained) {
|
|
1114
|
+
if (isOrphan(pending)) {
|
|
1115
|
+
holdOrExpireStrictUnmatchedEvent(pending, readNonEmptyString(pending.targetCoordinatorSessionId), meshId);
|
|
1116
|
+
orphanEscaped++;
|
|
1117
|
+
} else {
|
|
1118
|
+
// Still-live (modal-parked) target — re-queue unchanged so it is held
|
|
1119
|
+
// for the next modal-resolved tick, exactly like the blanket hold would.
|
|
1120
|
+
try { queuePendingMeshCoordinatorEvent(pending); } catch { /* best-effort re-queue */ }
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
LOG.info('MeshReconcile', `Reconcile skip → modal-parked: holding pending event(s) for mesh ${meshId} (${modalParkedCoordinators.length} coordinator(s) awaiting a modal answer; events left queued${orphanEscaped > 0 ? `; ${orphanEscaped} orphan-targeted event(s) routed to strict-route TTL` : ''})`);
|
|
1126
|
+
// NOTIF (B) diagnostic: name the session(s) classified modal-parked so the
|
|
1127
|
+
// same-tick coordDiag line (paired by sessionId) shows whether the modal-park
|
|
1128
|
+
// overlay is a real human-await or an unreleased mask (the getState_overlay origin).
|
|
1129
|
+
if (getLogLevel() === 'debug') {
|
|
1130
|
+
LOG.debug('MeshReconcile', `coordHoldModalParked mesh=${meshId} heldFor=[${modalParkedCoordinators.map(c => c.sessionId || '?').join(',')}] (these were classified modal-parked; cross-ref same-tick coordDiag by sessionId)`);
|
|
1131
|
+
}
|
|
1132
|
+
// C1: mirror held terminal events into the ledger so a held completion's
|
|
1133
|
+
// worker summary is auditable/recoverable even if the modal is never
|
|
1134
|
+
// resolved, the coordinator restarts, or the pending file is later trimmed.
|
|
1135
|
+
// The events stay queued (drained=0) for re-drain on a later tick; this only
|
|
1136
|
+
// adds the durable audit copy. Idempotent per process — only newly-held
|
|
1137
|
+
// events are logged. O(1)-gated: skip the peek when the queue is empty.
|
|
1138
|
+
let hasPending = true;
|
|
1139
|
+
if (store) {
|
|
1140
|
+
try { hasPending = store.pendingEventCount(meshId) > 0; } catch { /* peek below */ }
|
|
1141
|
+
}
|
|
1142
|
+
if (hasPending) {
|
|
1143
|
+
recordHeldTerminalEventsToLedger(
|
|
1144
|
+
meshId,
|
|
1145
|
+
drainDaemonIds.length > 0 ? drainDaemonIds : (localDaemonId ? [localDaemonId] : []),
|
|
1146
|
+
'modal_parked',
|
|
1147
|
+
modalParkedCoordinators.length,
|
|
1148
|
+
);
|
|
1149
|
+
}
|
|
1150
|
+
} else if (generatingCoordinators.length > 0) {
|
|
1151
|
+
// ── generating hold (NOTIF-SURFACE-LOCAL false-idle fix) ─────────────
|
|
1152
|
+
// The only coordinator(s) for this mesh are plainly generating (no idle, no
|
|
1153
|
+
// modal). A raw force-write into a generating claude-cli PTY is not consumed
|
|
1154
|
+
// as a turn, so we do NOT inject and do NOT drain — the events stay queued
|
|
1155
|
+
// (drained=0) and the next tick that finds the coordinator idle full-drains
|
|
1156
|
+
// them as real turns (the coordinator returns to idle when its current
|
|
1157
|
+
// tool-call/turn resolves; a dispatched worker runs for minutes while the
|
|
1158
|
+
// coordinator is idle, so this lands within one reconcile interval). C1: mirror
|
|
1159
|
+
// any held terminal events into the ledger so a completion's worker summary is
|
|
1160
|
+
// recoverable even before that idle tick. Idempotent per process; O(1)-gated.
|
|
1161
|
+
let hasPending = true;
|
|
1162
|
+
if (store) {
|
|
1163
|
+
try { hasPending = store.pendingEventCount(meshId) > 0; } catch { /* peek below */ }
|
|
1164
|
+
}
|
|
1165
|
+
if (hasPending) {
|
|
1166
|
+
// ── PTY-OVERTRUST-DRAIN (Defect B, fix B): age-based escape ───────────
|
|
1167
|
+
// Fix A already routes the common mask-driven false-busy to the idle path,
|
|
1168
|
+
// so reaching here means the coordinator's RAW adapter reads generating.
|
|
1169
|
+
// That is almost always genuine — but a status-source desync fix A does not
|
|
1170
|
+
// reach can momentarily make the raw adapter read generating while the PTY
|
|
1171
|
+
// is actually at a turn end, stranding the completion across many ticks. As a
|
|
1172
|
+
// TIME-BASED BACKSTOP, once the oldest held terminal event has aged past the
|
|
1173
|
+
// escalate threshold, RE-CONFIRM each held coordinator's raw adapter idle and,
|
|
1174
|
+
// if genuinely idle, drain ONCE into it. The re-confirmation gate is what makes
|
|
1175
|
+
// this safe: it NEVER injects into a genuinely-generating PTY (that is the
|
|
1176
|
+
// data-loss force-inject path intentionally removed). A coordinator still
|
|
1177
|
+
// genuinely generating stays held.
|
|
1178
|
+
const escalateMs = resolvePendingHeldDrainEscalateMs();
|
|
1179
|
+
const heldAgeMs = oldestHeldTerminalEventAgeMs(
|
|
1180
|
+
meshId,
|
|
1181
|
+
drainDaemonIds.length > 0 ? drainDaemonIds : (localDaemonId ? [localDaemonId] : []),
|
|
1182
|
+
);
|
|
1183
|
+
if (heldAgeMs >= escalateMs) {
|
|
1184
|
+
const escapeTargets = reconfirmGenuinelyIdleCoordinators(generatingCoordinators);
|
|
1185
|
+
if (escapeTargets.length > 0) {
|
|
1186
|
+
LOG.info('MeshReconcile', `Reconcile age-escape → generating-hold: held terminal event(s) for mesh ${meshId} aged ${Math.round(heldAgeMs / 1000)}s (≥ ${Math.round(escalateMs / 1000)}s) and ${escapeTargets.length} coordinator(s) re-confirmed genuinely idle on the raw adapter — draining once`);
|
|
1187
|
+
const drained = drainAndInjectIntoTargets(meshId, drainDaemonIds, localDaemonId, escapeTargets, 'age-escape');
|
|
1188
|
+
if (drained > 0) continue; // delivered → no hold this tick
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
LOG.info('MeshReconcile', `Reconcile skip → generating: holding pending event(s) for mesh ${meshId} (${generatingCoordinators.length} coordinator(s) busy; events left queued for the next idle tick)`);
|
|
1192
|
+
// NOTIF (B) diagnostic: this is the hold that strands the completion. Name
|
|
1193
|
+
// the sessionId(s) the loop just classified non-idle/non-modal so the
|
|
1194
|
+
// same-tick coordDiag line above (paired by sessionId) reveals which status
|
|
1195
|
+
// source diverged. If a coordDiag for one of these sessions shows getState
|
|
1196
|
+
// (or lastStatus/adapterRaw) === idle, that is the runtime desync origin.
|
|
1197
|
+
if (getLogLevel() === 'debug') {
|
|
1198
|
+
LOG.debug('MeshReconcile', `coordHoldGenerating mesh=${meshId} heldFor=[${generatingCoordinators.map(c => c.sessionId || '?').join(',')}] (these were classified busy; cross-ref same-tick coordDiag by sessionId)`);
|
|
1199
|
+
}
|
|
1200
|
+
recordHeldTerminalEventsToLedger(
|
|
1201
|
+
meshId,
|
|
1202
|
+
drainDaemonIds.length > 0 ? drainDaemonIds : (localDaemonId ? [localDaemonId] : []),
|
|
1203
|
+
'generating_no_idle_coordinator',
|
|
1204
|
+
generatingCoordinators.length,
|
|
1205
|
+
);
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
continue;
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
// O(1) guard: skip the drain entirely when the queue is empty.
|
|
1212
|
+
if (store) {
|
|
1213
|
+
try {
|
|
1214
|
+
if (store.pendingEventCount(meshId) === 0) continue;
|
|
1215
|
+
} catch { /* fall through to drain */ }
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
// An idle coordinator is present (targetCoordinators.length > 0): FULL-drain every
|
|
1219
|
+
// queued event and deliver it to the idle input box as a real turn. The no-idle case
|
|
1220
|
+
// (generating/modal-only) was already held above and never reaches here, so there is
|
|
1221
|
+
// no force-drain-into-generating path left — the single delivery is the idle drain.
|
|
1222
|
+
drainAndInjectIntoTargets(meshId, drainDaemonIds, localDaemonId, targetCoordinators, 'idle');
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
// Strict-routing TTL: how long a drained completion whose originating coordinator session
|
|
1227
|
+
// is not currently deliverable is held (re-queued for re-drain) before it is ledger-
|
|
1228
|
+
// expired. Bounded so a coordinator session that never returns cannot wedge the event
|
|
1229
|
+
// forever; broad enough to ride out a transient modal-park / brief restart.
|
|
1230
|
+
const STRICT_SESSION_MATCH_TTL_MS = 60_000;
|
|
1231
|
+
|
|
1232
|
+
// Re-queue (hold) a strict-routed event whose coordinator session is not live, or — once it
|
|
1233
|
+
// has aged past STRICT_SESSION_MATCH_TTL_MS — ledger-expire it (recoverable) and drop it.
|
|
1234
|
+
// We deliberately do NOT broadcast an aged-out event to sibling coordinators: that is the
|
|
1235
|
+
// very misroute strict routing exists to prevent. The drain already marked the row drained=1,
|
|
1236
|
+
// so re-queuing re-persists a fresh undrained copy (dedup keys on drained=0 only); queuedAt is
|
|
1237
|
+
// preserved so the TTL measures the event's true age across re-queues.
|
|
1238
|
+
function holdOrExpireStrictUnmatchedEvent(
|
|
1239
|
+
pending: PendingMeshCoordinatorEvent,
|
|
1240
|
+
wantSession: string,
|
|
1241
|
+
meshId: string,
|
|
1242
|
+
): void {
|
|
1243
|
+
const queuedAt = typeof pending.queuedAt === 'number' ? pending.queuedAt : Date.now();
|
|
1244
|
+
if (Date.now() - queuedAt <= STRICT_SESSION_MATCH_TTL_MS) {
|
|
1245
|
+
try {
|
|
1246
|
+
queuePendingMeshCoordinatorEvent(pending); // preserves queuedAt → true age retained
|
|
1247
|
+
LOG.info('MeshReconcile', `Strict route hold: coordinator session ${wantSession} not live on mesh ${meshId} — re-queued (${pending.event})`);
|
|
1248
|
+
// EVTTRACE: event held (re-queued) — its originating coordinator session is not
|
|
1249
|
+
// currently deliverable. Held, not dropped; surfaces later or expires past TTL.
|
|
1250
|
+
traceMeshEventDrop('strict_route_hold', {
|
|
1251
|
+
taskId: pending.metadataEvent?.taskId,
|
|
1252
|
+
sessionId: pending.metadataEvent?.targetSessionId ?? wantSession,
|
|
1253
|
+
nodeId: pending.nodeId,
|
|
1254
|
+
meshId,
|
|
1255
|
+
event: pending.event,
|
|
1256
|
+
}, `coordinatorSession=${wantSession} not live`);
|
|
1257
|
+
} catch (e: any) {
|
|
1258
|
+
LOG.warn('MeshReconcile', `Strict route re-queue failed for ${pending.event} on mesh ${meshId}: ${e?.message || e}`);
|
|
1259
|
+
}
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
const finalSummary = readMeshCompletionSummary(pending.metadataEvent || {});
|
|
1263
|
+
try {
|
|
1264
|
+
appendLedgerEntry(meshId, {
|
|
1265
|
+
kind: 'event_held',
|
|
1266
|
+
...(pending.nodeId ? { nodeId: pending.nodeId } : {}),
|
|
1267
|
+
payload: {
|
|
1268
|
+
event: pending.event,
|
|
1269
|
+
reason: 'strict_route_expired',
|
|
1270
|
+
recoverable: true,
|
|
1271
|
+
targetCoordinatorSessionId: wantSession,
|
|
1272
|
+
targetCoordinatorDaemonId: pending.targetCoordinatorDaemonId ?? null,
|
|
1273
|
+
nodeLabel: pending.nodeLabel,
|
|
1274
|
+
...(pending.workspace ? { workspace: pending.workspace } : {}),
|
|
1275
|
+
queuedAt,
|
|
1276
|
+
...(finalSummary ? { finalSummary } : {}),
|
|
1277
|
+
},
|
|
1278
|
+
});
|
|
1279
|
+
LOG.warn('MeshReconcile', `Strict route expire: coordinator session ${wantSession} never returned for mesh ${meshId} — recorded to ledger (recoverable), dropped (${pending.event})`);
|
|
1280
|
+
// EVTTRACE: event expired past the strict-route TTL — dropped (recoverable, ledgered).
|
|
1281
|
+
traceMeshEventDrop('strict_route_expired', {
|
|
1282
|
+
taskId: pending.metadataEvent?.taskId,
|
|
1283
|
+
sessionId: pending.metadataEvent?.targetSessionId ?? wantSession,
|
|
1284
|
+
nodeId: pending.nodeId,
|
|
1285
|
+
meshId,
|
|
1286
|
+
event: pending.event,
|
|
1287
|
+
}, `coordinatorSession=${wantSession} never returned`);
|
|
1288
|
+
} catch (e: any) {
|
|
1289
|
+
LOG.warn('MeshReconcile', `Failed to ledger-expire strict-unmatched ${pending.event} for mesh ${meshId}: ${e?.message || e}`);
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
// Cloud-only: retry the worker-side unresolved-delegate forward outbox. For each
|
|
1294
|
+
// durably-queued entry, push it to its coordinator daemon over P2P (mesh_forward_event)
|
|
1295
|
+
// and ack (mark drained) ONLY on a successful, non-rejected response. A failed or
|
|
1296
|
+
// rejected push leaves the entry queued for the next tick — at-least-once delivery.
|
|
1297
|
+
// Stale entries (coordinator unreachable past the max age) are expired first so the
|
|
1298
|
+
// outbox can't grow without bound. The coordinator dedups duplicate deliveries on its
|
|
1299
|
+
// own fingerprint, so a retry that races the original immediate push is harmless.
|
|
1300
|
+
// RECONCILE-MESHID-DROP: per-entry count of consecutive HARD rejections (the coordinator
|
|
1301
|
+
// returned success:false, e.g. "meshId required"). A rejection means the push was delivered
|
|
1302
|
+
// and deterministically refused — retrying the identical payload every 4s can never succeed,
|
|
1303
|
+
// so it would loop until the 30-minute age expiry, spamming the log the whole time. After
|
|
1304
|
+
// MAX_FORWARD_REJECTIONS such rejections we drop the entry (drain it) with ONE fail-loud
|
|
1305
|
+
// warning. Transient transport failures (the dispatch throws — coordinator momentarily
|
|
1306
|
+
// unreachable) do NOT count here; those legitimately retry until the age expiry. In-memory
|
|
1307
|
+
// (keyed by the durable outbox row id) is sufficient: a daemon restart re-arms the loop, and
|
|
1308
|
+
// the age expiry remains the durable backstop. Cleared whenever an entry is delivered/drained.
|
|
1309
|
+
const unresolvedForwardRejectionCounts = new Map<string, number>();
|
|
1310
|
+
const MAX_FORWARD_REJECTIONS = 5;
|
|
1311
|
+
|
|
1312
|
+
export function __resetUnresolvedForwardRejectionCountsForTests(): void {
|
|
1313
|
+
unresolvedForwardRejectionCounts.clear();
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
async function retryUnresolvedDelegateForwards(components: DaemonComponents): Promise<void> {
|
|
1317
|
+
const dispatchMeshCommand = components.dispatchMeshCommand;
|
|
1318
|
+
if (!dispatchMeshCommand) return;
|
|
1319
|
+
|
|
1320
|
+
// Drop entries that have exhausted their retry budget (fail-loud inside).
|
|
1321
|
+
expireStaleUnresolvedDelegateForwards();
|
|
1322
|
+
|
|
1323
|
+
const entries = peekUnresolvedDelegateForwards();
|
|
1324
|
+
if (entries.length === 0) {
|
|
1325
|
+
// Nothing queued — clear any stale per-entry rejection counters so the map can't grow.
|
|
1326
|
+
if (unresolvedForwardRejectionCounts.size > 0) unresolvedForwardRejectionCounts.clear();
|
|
1327
|
+
return;
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
// Every id-form THIS daemon answers to. A self-addressed outbox entry (coordinator
|
|
1331
|
+
// == this daemon) must never be cross-dialled — see the self-route branch below.
|
|
1332
|
+
const selfIds = resolveCoordinatorDaemonIds(components);
|
|
1333
|
+
const isSelfCoordinatorId = (id: string): boolean =>
|
|
1334
|
+
selfIds.some(self => daemonIdsEquivalent(self, id));
|
|
1335
|
+
|
|
1336
|
+
for (const entry of entries) {
|
|
1337
|
+
// EVTTRACE correlation context for this outbox entry's retry.
|
|
1338
|
+
const entryTraceCtx = {
|
|
1339
|
+
taskId: (entry.payload as Record<string, unknown>).taskId,
|
|
1340
|
+
sessionId: readNonEmptyString(entry.payload.targetSessionId) || readNonEmptyString(entry.payload.sessionId),
|
|
1341
|
+
nodeId: readNonEmptyString(entry.payload.nodeId),
|
|
1342
|
+
event: readNonEmptyString(entry.payload.event),
|
|
1343
|
+
};
|
|
1344
|
+
|
|
1345
|
+
// Self-addressed forward: the coordinator daemon this entry targets IS this
|
|
1346
|
+
// daemon (a self-coordinating / single-node mesh, or a delegate whose coordinator
|
|
1347
|
+
// anchor resolved to our own id). A cross-daemon mesh_forward_event to our own id
|
|
1348
|
+
// is REFUSED by the dispatch self-dial guard ("Refusing to send ... to this
|
|
1349
|
+
// daemon's own id; route via the local router instead") on every retry, so the
|
|
1350
|
+
// entry can never be acked and loops forever (~every tick), spamming the log and
|
|
1351
|
+
// pinning the outbox row permanently undrained. Honour the guard's own advice:
|
|
1352
|
+
// route the event straight through the local receiver (handleMeshForwardEvent —
|
|
1353
|
+
// the same path the coordinator runs on receiving a remote push), then ack it.
|
|
1354
|
+
// We drain regardless of the local result: a cross-daemon dispatch could not have
|
|
1355
|
+
// resolved it either (the guard rejects before the receiver ever runs), so leaving
|
|
1356
|
+
// it queued only re-spams. handleMeshForwardEvent has the BEST recovery chance —
|
|
1357
|
+
// this daemon hosts the mesh, so its workspace/nodeId → meshId recovery applies.
|
|
1358
|
+
if (isSelfCoordinatorId(entry.coordinatorDaemonId)) {
|
|
1359
|
+
let localResult: any;
|
|
1360
|
+
try {
|
|
1361
|
+
traceMeshEventStage('forward_send', entryTraceCtx, `self → local router (${entry.coordinatorDaemonId})`);
|
|
1362
|
+
localResult = handleMeshForwardEvent(components, entry.payload);
|
|
1363
|
+
} catch (e: any) {
|
|
1364
|
+
LOG.warn('MeshReconcile', `Local route of self-addressed forward to ${entry.coordinatorDaemonId} threw: ${e?.message || e} — draining anyway to break the retry loop`);
|
|
1365
|
+
}
|
|
1366
|
+
ackUnresolvedDelegateForward(entry.id);
|
|
1367
|
+
unresolvedForwardRejectionCounts.delete(entry.id);
|
|
1368
|
+
if (localResult && localResult.success === false) {
|
|
1369
|
+
LOG.warn('MeshReconcile', `Self-addressed unresolved-delegate ${readNonEmptyString(entry.payload.event)} rejected by local router (${readNonEmptyString(localResult.error) || 'no reason'}) — drained to break the self-forward retry loop`);
|
|
1370
|
+
traceMeshEventDrop('self_forward_local_rejected', entryTraceCtx, readNonEmptyString(localResult.error) || 'no reason');
|
|
1371
|
+
} else {
|
|
1372
|
+
LOG.info('MeshReconcile', `Self-addressed unresolved-delegate ${readNonEmptyString(entry.payload.event)} routed via local router (coordinator ${entry.coordinatorDaemonId} is self) — drained`);
|
|
1373
|
+
}
|
|
1374
|
+
continue;
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
// RECONCILE-MESHID-DROP: the stored forward payload was built when the worker
|
|
1378
|
+
// "couldn't resolve" its meshId, so the coordinator rejects it "meshId required"
|
|
1379
|
+
// when its own workspace/nodeId recovery misses. The worker can usually resolve it
|
|
1380
|
+
// now (member node membership / live-session meshNodeFor) — stamp it on so the
|
|
1381
|
+
// coordinator accepts. Covers entries persisted before this fix AND late-bound
|
|
1382
|
+
// sessions. No-op when the payload already carries a meshId or none is resolvable.
|
|
1383
|
+
let pushPayload = entry.payload;
|
|
1384
|
+
if (!readNonEmptyString(pushPayload.meshId)) {
|
|
1385
|
+
const recoveredMeshId = resolveForwardEventMeshId(components, pushPayload);
|
|
1386
|
+
if (recoveredMeshId) {
|
|
1387
|
+
pushPayload = { ...pushPayload, meshId: recoveredMeshId };
|
|
1388
|
+
traceMeshEventStage('forward_meshid_recovered', entryTraceCtx, `meshId=${recoveredMeshId}`);
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
let result: any;
|
|
1393
|
+
try {
|
|
1394
|
+
traceMeshEventStage('forward_send', entryTraceCtx, `retry → ${entry.coordinatorDaemonId}`);
|
|
1395
|
+
result = await dispatchMeshCommand(entry.coordinatorDaemonId, 'mesh_forward_event', pushPayload);
|
|
1396
|
+
} catch (e: any) {
|
|
1397
|
+
// Coordinator unreachable (transport threw) — keep the entry queued and try again
|
|
1398
|
+
// next tick. This is NOT a hard rejection, so it does not count toward the cap;
|
|
1399
|
+
// the age expiry bounds a permanently-offline coordinator.
|
|
1400
|
+
LOG.warn('MeshReconcile', `Retry forward to coordinator ${entry.coordinatorDaemonId} failed: ${e?.message || e} — left queued`);
|
|
1401
|
+
traceMeshEventDrop('retry_forward_failed', entryTraceCtx, e?.message || String(e));
|
|
1402
|
+
continue;
|
|
1403
|
+
}
|
|
1404
|
+
if (result && result.success === false) {
|
|
1405
|
+
// Hard rejection: the push was delivered and deterministically refused. Retrying
|
|
1406
|
+
// the identical payload can never succeed, so bound it — after MAX_FORWARD_REJECTIONS
|
|
1407
|
+
// drop (drain) the entry with one fail-loud warning instead of re-spamming every tick.
|
|
1408
|
+
const rejections = (unresolvedForwardRejectionCounts.get(entry.id) || 0) + 1;
|
|
1409
|
+
unresolvedForwardRejectionCounts.set(entry.id, rejections);
|
|
1410
|
+
const reason = readNonEmptyString(result.error) || 'no reason';
|
|
1411
|
+
if (rejections >= MAX_FORWARD_REJECTIONS) {
|
|
1412
|
+
ackUnresolvedDelegateForward(entry.id);
|
|
1413
|
+
unresolvedForwardRejectionCounts.delete(entry.id);
|
|
1414
|
+
LOG.warn('MeshReconcile', `Retry forward to coordinator ${entry.coordinatorDaemonId} rejected ${rejections}x (${reason}) — dropping unresolved-delegate ${readNonEmptyString(entry.payload.event)} (sess=${readNonEmptyString(entry.payload.targetSessionId) || readNonEmptyString(entry.payload.sessionId) || '-'}) to stop the retry loop`);
|
|
1415
|
+
traceMeshEventDrop('retry_forward_exhausted', entryTraceCtx, `${reason} (${rejections} rejections)`);
|
|
1416
|
+
} else {
|
|
1417
|
+
LOG.warn('MeshReconcile', `Retry forward to coordinator ${entry.coordinatorDaemonId} rejected (${reason}) — left queued (attempt ${rejections}/${MAX_FORWARD_REJECTIONS})`);
|
|
1418
|
+
traceMeshEventDrop('retry_forward_rejected', entryTraceCtx, reason);
|
|
1419
|
+
}
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
// Acked — mark the durable copy delivered.
|
|
1423
|
+
ackUnresolvedDelegateForward(entry.id);
|
|
1424
|
+
unresolvedForwardRejectionCounts.delete(entry.id);
|
|
1425
|
+
LOG.info('MeshReconcile', `Retried+delivered unresolved-delegate ${readNonEmptyString(entry.payload.event)} to coordinator ${entry.coordinatorDaemonId}`);
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
// Cloud-only: poll each remote worker node daemon for pending coordinator events
|
|
1430
|
+
// and re-inject them locally via handleMeshForwardEvent (which re-queues +
|
|
1431
|
+
// surfaces to the live coordinator on the next tick / immediately if idle).
|
|
1432
|
+
//
|
|
1433
|
+
// Scoping: the remote handler (get_pending_mesh_events) drains its queue filtered
|
|
1434
|
+
// by coordinatorDaemonId — returning events targeted at that id OR unscoped, and
|
|
1435
|
+
// leaving events targeted at a *different* coordinator. A remote worker stamps the
|
|
1436
|
+
// coordinator id in one of SEVERAL forms (the canonical status id `standalone_`/
|
|
1437
|
+
// `daemon_<machineId>` stamped by the MCP layer, the bare machineId stamped by the
|
|
1438
|
+
// local queue path, OR — most commonly for remote launches — the coordinator mesh
|
|
1439
|
+
// node's config-form `daemonId`, which resolveCoordinatorDaemonId prefers and which
|
|
1440
|
+
// is NOT canonicalised). `candidateDaemonIds` is the already-expanded self-identity
|
|
1441
|
+
// set (resolveCoordinatorSelfIds: runtime drain ids ∪ this daemon's mesh-config node/
|
|
1442
|
+
// host id forms), so we pull ONCE PER candidate id and a completion stamped with any
|
|
1443
|
+
// of them is recovered. The remote drain is atomic (drained=1), so issuing multiple
|
|
1444
|
+
// pulls cannot double-deliver — the first pull that matches consumes the event; the
|
|
1445
|
+
// rest see nothing. When no ids resolve we fall back to a single unscoped pull.
|
|
1446
|
+
async function pullRemoteNodeQueues(
|
|
1447
|
+
components: DaemonComponents,
|
|
1448
|
+
mesh: LocalMeshEntry,
|
|
1449
|
+
localDaemonId: string | undefined,
|
|
1450
|
+
candidateDaemonIds: string[],
|
|
1451
|
+
): Promise<void> {
|
|
1452
|
+
const dispatchMeshCommand = components.dispatchMeshCommand;
|
|
1453
|
+
if (!dispatchMeshCommand) return;
|
|
1454
|
+
const meshId = mesh.id;
|
|
1455
|
+
|
|
1456
|
+
// One args object per candidate coordinator-id form, or a single unscoped pull
|
|
1457
|
+
// when none resolve.
|
|
1458
|
+
const pulls: Array<Record<string, unknown>> = candidateDaemonIds.length > 0
|
|
1459
|
+
? candidateDaemonIds.map(id => ({ meshId, coordinatorDaemonId: id }))
|
|
1460
|
+
: [{ meshId }];
|
|
1461
|
+
|
|
1462
|
+
for (const node of mesh.nodes) {
|
|
1463
|
+
const nodeDaemonId = readNonEmptyString(node.daemonId);
|
|
1464
|
+
// Skip nodes without a daemon, and nodes on THIS daemon (their events are
|
|
1465
|
+
// already in the local queue drained in PHASE 2). "This daemon" is matched
|
|
1466
|
+
// against the full self-identity set (candidateDaemonIds), not just the bare
|
|
1467
|
+
// localDaemonId — a self node can be registered under the config-form daemonId
|
|
1468
|
+
// (`daemon_<machineId>`) which would NOT equal bare localDaemonId, and pulling
|
|
1469
|
+
// from ourselves over P2P is both wasteful and a self-dispatch hazard.
|
|
1470
|
+
if (!nodeDaemonId) continue;
|
|
1471
|
+
if (daemonIdsEquivalent(nodeDaemonId, localDaemonId)) continue;
|
|
1472
|
+
if (daemonIdListIncludes(candidateDaemonIds, nodeDaemonId)) continue;
|
|
1473
|
+
|
|
1474
|
+
for (const pendingEventArgs of pulls) {
|
|
1475
|
+
let events: unknown;
|
|
1476
|
+
try {
|
|
1477
|
+
events = await dispatchMeshCommand(nodeDaemonId, 'get_pending_mesh_events', pendingEventArgs);
|
|
1478
|
+
} catch {
|
|
1479
|
+
// Remote pull is best-effort; the node may be offline. Retry next tick.
|
|
1480
|
+
break; // node unreachable — don't bother with the other id form this tick.
|
|
1481
|
+
}
|
|
1482
|
+
const list = extractPendingEvents(events).filter(e => readNonEmptyString(e?.meshId) === meshId);
|
|
1483
|
+
for (const event of list) {
|
|
1484
|
+
const payload = buildForwardPayloadFromPending(event);
|
|
1485
|
+
if (!payload.event || !payload.meshId) continue;
|
|
1486
|
+
try {
|
|
1487
|
+
handleMeshForwardEvent(components, payload);
|
|
1488
|
+
} catch { /* best-effort re-inject */ }
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
// Pull the read_chat payload out of whatever envelope the transport returned.
|
|
1495
|
+
// A local commandHandler.handle() returns the CommandResult directly; a remote
|
|
1496
|
+
// dispatchMeshCommand returns it possibly wrapped in { payload } / { result }.
|
|
1497
|
+
function unwrapReadChatPayload(raw: unknown): Record<string, unknown> | null {
|
|
1498
|
+
let cursor: unknown = raw;
|
|
1499
|
+
for (let depth = 0; depth < 4 && cursor && typeof cursor === 'object'; depth++) {
|
|
1500
|
+
const record = cursor as Record<string, unknown>;
|
|
1501
|
+
if (Array.isArray(record.messages)) return record;
|
|
1502
|
+
if (record.payload && typeof record.payload === 'object') { cursor = record.payload; continue; }
|
|
1503
|
+
if (record.result && typeof record.result === 'object') { cursor = record.result; continue; }
|
|
1504
|
+
if (record.data && typeof record.data === 'object') { cursor = record.data; continue; }
|
|
1505
|
+
break;
|
|
1506
|
+
}
|
|
1507
|
+
return cursor && typeof cursor === 'object' ? cursor as Record<string, unknown> : null;
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
function readChatPayloadStatus(payload: Record<string, unknown> | null): string {
|
|
1511
|
+
return readNonEmptyString(payload?.status).toLowerCase();
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
// R4e fix (3): peek the pending-events queue for a REAL (worker-emitted) terminal completion
|
|
1515
|
+
// already queued for a task — used to yield the in-flight synth to the worker's own emit. Broad
|
|
1516
|
+
// peek (no daemon-id scoping) matched precisely by taskId, so a worker stamp in any daemon-id form
|
|
1517
|
+
// is still recognized. Best-effort: a peek failure returns false (proceed to synth — never block
|
|
1518
|
+
// delivery). A prior SYNTH's still-queued pending event also names this taskId, but a synth always
|
|
1519
|
+
// writes its terminal ledger atomically, so hasTerminalLedgerAfterDispatch downstream already
|
|
1520
|
+
// no-ops that case — this guard is specifically for an as-yet-unledgered worker emit in flight.
|
|
1521
|
+
function realTerminalEmitPendingForTask(meshId: string, taskId: string): boolean {
|
|
1522
|
+
let pending: readonly PendingMeshCoordinatorEvent[];
|
|
1523
|
+
try {
|
|
1524
|
+
pending = getPendingMeshCoordinatorEvents(meshId);
|
|
1525
|
+
} catch {
|
|
1526
|
+
return false;
|
|
1527
|
+
}
|
|
1528
|
+
return pending.some(e =>
|
|
1529
|
+
readNonEmptyString(e.metadataEvent?.taskId) === taskId
|
|
1530
|
+
&& (e.event === 'agent:generating_completed' || e.event === 'agent:stopped'));
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
// R4e fix (2): one fresh read_chat status read for the worker session, via the same local/remote
|
|
1534
|
+
// transport PHASE 4 uses. Returns the lowercased status, or null when the read is inconclusive
|
|
1535
|
+
// (transport error, success:false, no payload) — callers treat null as "no new evidence, proceed".
|
|
1536
|
+
async function reprobeWorkerStatus(
|
|
1537
|
+
components: DaemonComponents,
|
|
1538
|
+
args: { isLocalNode: boolean; nodeDaemonId: string; readArgs: Record<string, unknown> },
|
|
1539
|
+
): Promise<string | null> {
|
|
1540
|
+
try {
|
|
1541
|
+
if (args.isLocalNode) {
|
|
1542
|
+
const r = await components.commandHandler.handle('read_chat', args.readArgs);
|
|
1543
|
+
if (r && (r as { success?: boolean }).success === false) return null;
|
|
1544
|
+
return readChatPayloadStatus(unwrapReadChatPayload(r));
|
|
1545
|
+
}
|
|
1546
|
+
if (components.dispatchMeshCommand) {
|
|
1547
|
+
const r = await components.dispatchMeshCommand(args.nodeDaemonId, 'read_chat', args.readArgs);
|
|
1548
|
+
const p = unwrapReadChatPayload(r);
|
|
1549
|
+
if (p && (p as { success?: boolean }).success === false) return null;
|
|
1550
|
+
return readChatPayloadStatus(p);
|
|
1551
|
+
}
|
|
1552
|
+
} catch {
|
|
1553
|
+
return null;
|
|
1554
|
+
}
|
|
1555
|
+
return null;
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
// PHASE 4 helper. For every active (non-terminal) direct dispatch this daemon
|
|
1559
|
+
// hosts, confirm the worker session is idle via a read_chat and — if a final
|
|
1560
|
+
// assistant summary is present but no terminal ledger exists for that dispatch —
|
|
1561
|
+
// synthesize the missing completion through reconcileDirectDispatchCompletionFromTranscript.
|
|
1562
|
+
//
|
|
1563
|
+
// read_chat is resolved against the target node: a node on THIS daemon is read
|
|
1564
|
+
// through the local commandHandler; a remote node is read over P2P via
|
|
1565
|
+
// dispatchMeshCommand. Both yield the same { messages, status, providerSessionId }
|
|
1566
|
+
// shape. We only synthesize when the session reports idle AND a final assistant
|
|
1567
|
+
// message exists — the same evidence bar the MCP poll path uses — so an actively
|
|
1568
|
+
// generating worker is never falsely completed. The reconcile itself is idempotent.
|
|
1569
|
+
async function reconcileUnterminatedDirectDispatches(
|
|
1570
|
+
components: DaemonComponents,
|
|
1571
|
+
mesh: LocalMeshEntry,
|
|
1572
|
+
selfIds: string[],
|
|
1573
|
+
localDaemonId: string | undefined,
|
|
1574
|
+
): Promise<void> {
|
|
1575
|
+
const dispatches = getActiveDirectDispatches(mesh.id);
|
|
1576
|
+
if (dispatches.length === 0) return; // cheap exit — nothing dispatched, nothing to reconcile
|
|
1577
|
+
|
|
1578
|
+
// Prune the in-flight acked-hold map to the tasks still active in THIS mesh, so a
|
|
1579
|
+
// completed/pruned task's state is dropped (the map never grows without bound).
|
|
1580
|
+
const activeTaskKeys = new Set(
|
|
1581
|
+
dispatches
|
|
1582
|
+
.map(d => readNonEmptyString(d.taskId))
|
|
1583
|
+
.filter(Boolean)
|
|
1584
|
+
.map(taskId => inFlightSynthKey(mesh.id, taskId)),
|
|
1585
|
+
);
|
|
1586
|
+
for (const key of inFlightAckedHoldState.keys()) {
|
|
1587
|
+
if (key.startsWith(`${mesh.id}::`) && !activeTaskKeys.has(key)) {
|
|
1588
|
+
inFlightAckedHoldState.delete(key);
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
const dispatchMeshCommand = components.dispatchMeshCommand;
|
|
1593
|
+
const nodeById = new Map(mesh.nodes.map(n => [n.id, n] as const));
|
|
1594
|
+
|
|
1595
|
+
for (const dispatch of dispatches) {
|
|
1596
|
+
const sessionId = readNonEmptyString(dispatch.sessionId);
|
|
1597
|
+
const nodeId = readNonEmptyString(dispatch.nodeId);
|
|
1598
|
+
const taskId = readNonEmptyString(dispatch.taskId);
|
|
1599
|
+
if (!sessionId || !nodeId || !taskId) continue;
|
|
1600
|
+
|
|
1601
|
+
const node = nodeById.get(nodeId);
|
|
1602
|
+
const nodeDaemonId = readNonEmptyString(node?.daemonId);
|
|
1603
|
+
// A node is local when it has no daemonId, names this daemon, or actually
|
|
1604
|
+
// has a live instance here. Anything else is reached over P2P.
|
|
1605
|
+
const isLocalNode = !nodeDaemonId
|
|
1606
|
+
|| daemonIdListIncludes(selfIds, nodeDaemonId)
|
|
1607
|
+
|| daemonIdsEquivalent(nodeDaemonId, localDaemonId)
|
|
1608
|
+
|| !!components.instanceManager.getInstance(sessionId);
|
|
1609
|
+
|
|
1610
|
+
const providerType = readNonEmptyString(dispatch.providerType);
|
|
1611
|
+
const readArgs: Record<string, unknown> = {
|
|
1612
|
+
sessionId,
|
|
1613
|
+
targetSessionId: sessionId,
|
|
1614
|
+
tailLimit: 10,
|
|
1615
|
+
...(node?.workspace ? { workspace: node.workspace } : {}),
|
|
1616
|
+
...(providerType ? { agentType: providerType, providerType } : {}),
|
|
1617
|
+
};
|
|
1618
|
+
|
|
1619
|
+
const synthKey = inFlightSynthKey(mesh.id, taskId);
|
|
1620
|
+
const isAcked = dispatch.status === 'acked';
|
|
1621
|
+
|
|
1622
|
+
// R4f: read the worker session. A FAILED read (transport error / success:false / no payload)
|
|
1623
|
+
// is no longer silently swallowed for an acked task — it is the liveness side of the
|
|
1624
|
+
// death backstop (a). We classify the read result and route an acked failure into the
|
|
1625
|
+
// failure counter; a never-acked (or non-acked) failure keeps the old best-effort `continue`.
|
|
1626
|
+
let payload: Record<string, unknown> | null = null;
|
|
1627
|
+
let readFailed = false;
|
|
1628
|
+
try {
|
|
1629
|
+
if (isLocalNode) {
|
|
1630
|
+
const result = await components.commandHandler.handle('read_chat', readArgs);
|
|
1631
|
+
if (result && (result as { success?: boolean }).success === false) {
|
|
1632
|
+
readFailed = true;
|
|
1633
|
+
} else {
|
|
1634
|
+
payload = unwrapReadChatPayload(result);
|
|
1635
|
+
}
|
|
1636
|
+
} else if (dispatchMeshCommand) {
|
|
1637
|
+
const result = await dispatchMeshCommand(nodeDaemonId, 'read_chat', readArgs);
|
|
1638
|
+
payload = unwrapReadChatPayload(result);
|
|
1639
|
+
if (payload && (payload as { success?: boolean }).success === false) { payload = null; readFailed = true; }
|
|
1640
|
+
} else {
|
|
1641
|
+
continue; // remote node but no P2P transport — can't read; retry next tick (not a death signal)
|
|
1642
|
+
}
|
|
1643
|
+
} catch {
|
|
1644
|
+
readFailed = true; // session may be gone or node offline
|
|
1645
|
+
}
|
|
1646
|
+
if (!payload && !readFailed) continue; // null payload that wasn't a hard failure — retry next tick
|
|
1647
|
+
|
|
1648
|
+
if (readFailed || !payload) {
|
|
1649
|
+
// R4f backstop (a) — liveness failure. For a never-acked dispatch there is no in-flight
|
|
1650
|
+
// turn to protect, so a read failure is a transient probe blip → retry next tick (old
|
|
1651
|
+
// behavior). For an ACKED dispatch that we had previously confirmed live, a streak of
|
|
1652
|
+
// consecutive read failures means the worker session genuinely went away mid-turn and
|
|
1653
|
+
// will never emit its real completion — count it. The actual terminal cleanup of a
|
|
1654
|
+
// gone session is owned by PHASE 2.5 (stranded reclaim) / PHASE 5 (orphan prune); here
|
|
1655
|
+
// we only record the death observation and STOP holding so those nets can take over,
|
|
1656
|
+
// rather than pinning the row on an indefinite hold for a session that is already gone.
|
|
1657
|
+
if (isAcked) {
|
|
1658
|
+
const prior = inFlightAckedHoldState.get(synthKey);
|
|
1659
|
+
const failures = (prior?.consecutiveReadFailures ?? 0) + 1;
|
|
1660
|
+
const liveConfirmedSinceAck = prior?.liveConfirmedSinceAck ?? false;
|
|
1661
|
+
// A read failure breaks the idle-with-final-assistant run → reset the fast-track streak
|
|
1662
|
+
// (transcriptIdleSinceMs cleared by omission) so it must re-accumulate from scratch.
|
|
1663
|
+
inFlightAckedHoldState.set(synthKey, { liveConfirmedSinceAck, consecutiveReadFailures: failures });
|
|
1664
|
+
if (liveConfirmedSinceAck && failures >= ACKED_DEATH_CONSECUTIVE_READ_FAILURES) {
|
|
1665
|
+
LOG.warn('MeshReconcile', `Acked-hold death signal: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) read_chat failed ${failures}x consecutively after a live-confirmed ack — worker session presumed gone mid-turn; releasing the indefinite synth hold to the stranded-reclaim / orphan-prune nets`);
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
continue; // no readable transcript this tick → cannot synth here; retry / let backstops act
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
// Read succeeded (a conclusive idle/generating status) → the session is reachable: reset the
|
|
1672
|
+
// failure streak and mark it live-confirmed-since-ack, so a LATER read failure is recognized
|
|
1673
|
+
// as a genuine liveness loss (backstop a) rather than a node that was never reachable. The
|
|
1674
|
+
// fast-track idle streak (transcriptIdleSinceMs) is PRESERVED across this reset — it is
|
|
1675
|
+
// managed below where the idle + final-assistant signal is actually evaluated.
|
|
1676
|
+
const priorHoldState = inFlightAckedHoldState.get(synthKey);
|
|
1677
|
+
inFlightAckedHoldState.set(synthKey, {
|
|
1678
|
+
liveConfirmedSinceAck: true,
|
|
1679
|
+
consecutiveReadFailures: 0,
|
|
1680
|
+
...(priorHoldState?.transcriptIdleSinceMs !== undefined ? { transcriptIdleSinceMs: priorHoldState.transcriptIdleSinceMs } : {}),
|
|
1681
|
+
});
|
|
1682
|
+
|
|
1683
|
+
// Only act on a session that has actually settled to idle. A generating /
|
|
1684
|
+
// waiting_approval session is mid-turn — synthesizing a completion now would
|
|
1685
|
+
// be wrong. (idle is the only status the MCP poll path reconciles too.)
|
|
1686
|
+
const nowMs = Date.now();
|
|
1687
|
+
if (readChatPayloadStatus(payload) !== 'idle') {
|
|
1688
|
+
// Not idle → the worker is genuinely mid-turn (a clear live signal). Keep the
|
|
1689
|
+
// live-confirmed flag set (above) but RESET the fast-track idle streak: a turn that
|
|
1690
|
+
// resumed generating proves the prior idle was a mid-turn blip, not a settled turn-end.
|
|
1691
|
+
inFlightAckedHoldState.set(synthKey, { liveConfirmedSinceAck: true, consecutiveReadFailures: 0 });
|
|
1692
|
+
continue;
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
// R4f GENERATING-BOUNDARY (acked-hold): a dispatch whose worker was OBSERVED to start
|
|
1696
|
+
// generating (the agent:generating_started ack flipped the row to 'acked') is ALIVE and
|
|
1697
|
+
// mid-turn — it WILL eventually emit a real terminal. An `idle` read here is therefore
|
|
1698
|
+
// presumed a TRANSIENT mid-turn window (a PTY inter-tool-call settle, or final text already
|
|
1699
|
+
// rendered while the lifecycle close lags), NOT a settled completion. We HOLD the synth
|
|
1700
|
+
// INDEFINITELY rather than racing the worker's (variable, unbounded) emit latency with a
|
|
1701
|
+
// finite timer — the failure mode of R4..R4e. This is safe: when the worker's real emit
|
|
1702
|
+
// lands it writes a terminal ledger, and reconcileDirectDispatchCompletionFromTranscript's
|
|
1703
|
+
// hasTerminalLedgerAfterDispatch makes any later synth an idempotent no-op, so the real emit
|
|
1704
|
+
// always wins no matter how late. The hold is released ONLY by the death backstops:
|
|
1705
|
+
// (a) consecutive read failures after a live-confirmed ack (handled above), or
|
|
1706
|
+
// (b) the absolute ACKED_DEATH_DEADLINE_MS since the ack — a notification-loss net set FAR
|
|
1707
|
+
// above any observed emit latency, so it catches a genuinely-wedged worker / lost emit
|
|
1708
|
+
// without racing a normal slow turn.
|
|
1709
|
+
// A never-acked dispatch (worker never started) is exempt — no in-flight generation to
|
|
1710
|
+
// pre-empt; it keeps the first-idle-tick synth, with the downstream grace + stale-summary
|
|
1711
|
+
// guards as its backstops.
|
|
1712
|
+
//
|
|
1713
|
+
// ACKED-HOLD-IDLE-OVERTRUST: the read is idle. Extract the final-assistant evidence NOW (the
|
|
1714
|
+
// same signal the synth below requires) so the fast-track can gate on idle-WITH-final-assistant
|
|
1715
|
+
// rather than bare idle. Only when a final visible assistant message is present do we treat
|
|
1716
|
+
// this tick as a candidate turn-end and accumulate the fast-track grace streak; a bare idle
|
|
1717
|
+
// with no assistant result is the worker still warming up and resets the streak.
|
|
1718
|
+
const messages = Array.isArray(payload.messages) ? payload.messages as ChatMessage[] : [];
|
|
1719
|
+
const evidence = extractFinalAssistantSummaryEvidence(messages);
|
|
1720
|
+
|
|
1721
|
+
if (isAcked) {
|
|
1722
|
+
const ackedAtMs = Date.parse(readNonEmptyString(dispatch.updatedAt));
|
|
1723
|
+
const sinceAckMs = Number.isFinite(ackedAtMs) ? nowMs - ackedAtMs : Number.POSITIVE_INFINITY;
|
|
1724
|
+
const deathDeadlineMs = resolveAckedDeathDeadlineMs();
|
|
1725
|
+
|
|
1726
|
+
// ACKED-HOLD-IDLE-OVERTRUST fast-track. Maintain the continuous idle-with-final-assistant
|
|
1727
|
+
// streak. The streak starts (or continues) only while a final visible assistant message is
|
|
1728
|
+
// present; a tick with idle-but-no-assistant breaks it (the answer is not yet rendered).
|
|
1729
|
+
const holdState = inFlightAckedHoldState.get(synthKey);
|
|
1730
|
+
let fastTrackReady = false;
|
|
1731
|
+
if (evidence.finalSummary) {
|
|
1732
|
+
const idleSinceMs = holdState?.transcriptIdleSinceMs ?? nowMs;
|
|
1733
|
+
if (holdState && holdState.transcriptIdleSinceMs === undefined) {
|
|
1734
|
+
inFlightAckedHoldState.set(synthKey, { ...holdState, transcriptIdleSinceMs: idleSinceMs });
|
|
1735
|
+
}
|
|
1736
|
+
const fastTrackGraceMs = resolveAckedTranscriptFastTrackGraceMs();
|
|
1737
|
+
const idleHeldMs = nowMs - idleSinceMs;
|
|
1738
|
+
if (idleHeldMs >= fastTrackGraceMs) {
|
|
1739
|
+
fastTrackReady = true;
|
|
1740
|
+
LOG.info('MeshReconcile', `Acked-hold transcript fast-track: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) read idle WITH a final assistant message for ${Math.round(idleHeldMs / 1000)}s continuous (grace ${Math.round(fastTrackGraceMs / 1000)}s) — promoting the synth ahead of the ${Math.round(deathDeadlineMs / 1000)}s death backstop; the worker's real emit was lost/late and a later one no-ops idempotently.`);
|
|
1741
|
+
}
|
|
1742
|
+
} else if (holdState?.transcriptIdleSinceMs !== undefined) {
|
|
1743
|
+
// Idle but no final assistant yet → not a turn-end; reset the streak.
|
|
1744
|
+
inFlightAckedHoldState.set(synthKey, { ...holdState, transcriptIdleSinceMs: undefined });
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
// Hold indefinitely UNLESS the fast-track grace was met OR the absolute death deadline is
|
|
1748
|
+
// reached. The fast-track is the new fast path in front of the (preserved) 8-min backstop.
|
|
1749
|
+
if (!fastTrackReady && sinceAckMs < deathDeadlineMs) {
|
|
1750
|
+
LOG.info('MeshReconcile', `Acked-hold: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) read idle ${Number.isFinite(sinceAckMs) ? Math.round(sinceAckMs / 1000) + 's' : '∞'} since the generating_started ack — HOLDING synth (worker presumed alive; a later real emit is idempotent). Transcript fast-track promotes at ${Math.round(resolveAckedTranscriptFastTrackGraceMs() / 1000)}s continuous idle-with-final-assistant; death backstop at ${Math.round(deathDeadlineMs / 1000)}s or on consecutive read failures.`);
|
|
1751
|
+
continue;
|
|
1752
|
+
}
|
|
1753
|
+
if (!fastTrackReady) {
|
|
1754
|
+
LOG.warn('MeshReconcile', `Acked-hold death deadline reached: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) still idle ${Math.round(sinceAckMs / 1000)}s after the ack (deadline ${Math.round(deathDeadlineMs / 1000)}s) — synthesizing the missing completion as a notification-loss net (a real emit, if it ever lands, no-ops idempotently).`);
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
// R4f (auxiliary, was R4e fix 3) — worker-emit priority. Secondary check: if the worker's
|
|
1759
|
+
// REAL terminal emit for this task has already arrived in the pending-events queue (queued
|
|
1760
|
+
// for delivery to the coordinator) but not yet written a terminal ledger, YIELD — let the
|
|
1761
|
+
// genuine emit surface rather than racing it with a synth that would win the taskId-anchored
|
|
1762
|
+
// fingerprint dedup and mask it. Under the R4f acked-hold this is now an auxiliary belt-and-
|
|
1763
|
+
// suspenders check (the indefinite hold already defers an acked synth); it still guards the
|
|
1764
|
+
// never-acked path and the post-death-deadline acked synth from racing an emit caught in
|
|
1765
|
+
// flight at synth-commit time.
|
|
1766
|
+
if (realTerminalEmitPendingForTask(mesh.id, taskId)) {
|
|
1767
|
+
inFlightAckedHoldState.delete(synthKey);
|
|
1768
|
+
LOG.info('MeshReconcile', `Worker-emit priority: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) has a real terminal completion already queued — yielding synth to the worker's own emit`);
|
|
1769
|
+
continue;
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1772
|
+
if (!evidence.finalSummary) continue; // no assistant result yet — nothing to attribute
|
|
1773
|
+
|
|
1774
|
+
// STALE-SUMMARY guard (modal-parked / reused-session misattribution): a direct
|
|
1775
|
+
// dispatch frequently reuses a session that already ran a PRIOR task. read_chat
|
|
1776
|
+
// returns the tail of the WHOLE session, so extractFinalAssistantSummaryEvidence
|
|
1777
|
+
// picks the latest user-facing assistant message — which, for a task that has
|
|
1778
|
+
// barely started (the session momentarily reads idle between turns), is the prior
|
|
1779
|
+
// task's final summary. The downstream reconcile proves the summary is after the
|
|
1780
|
+
// LEDGER task_dispatched entry; here we additionally have the AUTHORITATIVE per-task
|
|
1781
|
+
// dispatchedAt (the dispatch-store row, immune to ledger-ordering quirks), so when
|
|
1782
|
+
// the selected transcript message is provably BEFORE this task's own dispatch we
|
|
1783
|
+
// refuse it outright — it is a prior task's summary, not this task's output (the
|
|
1784
|
+
// 2843ms-duration stale-summary bug where task 2e3f501e copy-pasted 4eca2d9d's
|
|
1785
|
+
// summary). When the message carries no usable timestamp we do NOT block here: the
|
|
1786
|
+
// downstream reconcile already rejects a non-JSON summary it cannot prove is
|
|
1787
|
+
// post-dispatch (transcript_not_proven_after_dispatch), and a structured
|
|
1788
|
+
// final_summary_json is self-attributing — so a timeless provider is not
|
|
1789
|
+
// over-blocked while the provable-stale case is still caught.
|
|
1790
|
+
const dispatchedAtMs = Date.parse(readNonEmptyString(dispatch.dispatchedAt));
|
|
1791
|
+
const transcriptAtMs = Date.parse(evidence.transcriptMessageAt ?? '');
|
|
1792
|
+
if (Number.isFinite(dispatchedAtMs) && Number.isFinite(transcriptAtMs) && transcriptAtMs < dispatchedAtMs) {
|
|
1793
|
+
LOG.info('MeshReconcile', `Stale-summary guard: skipping transcript reconcile for task ${taskId} on node ${nodeId} (mesh ${mesh.id}) — final assistant message (${evidence.transcriptMessageAt}) predates this task's dispatch (${dispatch.dispatchedAt}); it is a prior task's summary`);
|
|
1794
|
+
traceMeshEventDrop('reconcile_stale_summary_before_dispatch', {
|
|
1795
|
+
taskId, sessionId, nodeId, meshId: mesh.id, event: 'agent:generating_completed',
|
|
1796
|
+
}, `transcriptAt=${evidence.transcriptMessageAt} < dispatchedAt=${dispatch.dispatchedAt}`);
|
|
1797
|
+
continue;
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
// R4f (auxiliary, was R4e fix 2) — live re-probe immediately before committing the synth. A
|
|
1801
|
+
// fresh read right now catches a worker that resumed generating since this tick's first read
|
|
1802
|
+
// so it is never falsely completed off a stale snapshot. Best-effort: an inconclusive
|
|
1803
|
+
// re-probe (transport error/null) falls through to the synth — we already hold a valid idle
|
|
1804
|
+
// read from the top of THIS tick, so a re-probe failure must not re-introduce a
|
|
1805
|
+
// notification-miss. Under the R4f acked-hold this matters mainly for the never-acked path
|
|
1806
|
+
// and the post-death-deadline acked synth (the indefinite hold already deferred a live acked
|
|
1807
|
+
// turn); it stays as a final live-state guard at synth-commit time.
|
|
1808
|
+
const reprobeStatus = await reprobeWorkerStatus(components, { isLocalNode, nodeDaemonId, readArgs });
|
|
1809
|
+
if (reprobeStatus && reprobeStatus !== 'idle') {
|
|
1810
|
+
inFlightAckedHoldState.delete(synthKey);
|
|
1811
|
+
LOG.info('MeshReconcile', `Live re-probe defer: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) read '${reprobeStatus}' at synth-commit time — worker resumed generating; deferring synth to a later tick`);
|
|
1812
|
+
continue;
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
const providerSessionId = readNonEmptyString(payload.providerSessionId);
|
|
1816
|
+
const coordinatorDaemonId = selfIds.find(id => !!id);
|
|
1817
|
+
try {
|
|
1818
|
+
const result = reconcileDirectDispatchCompletionFromTranscript({
|
|
1819
|
+
meshId: mesh.id,
|
|
1820
|
+
nodeId,
|
|
1821
|
+
sessionId,
|
|
1822
|
+
providerType: providerType || undefined,
|
|
1823
|
+
providerSessionId: providerSessionId || undefined,
|
|
1824
|
+
taskId,
|
|
1825
|
+
finalSummary: evidence.finalSummary,
|
|
1826
|
+
...(evidence.transcriptMessageAt ? { transcriptMessageAt: evidence.transcriptMessageAt } : {}),
|
|
1827
|
+
...(coordinatorDaemonId ? { targetCoordinatorDaemonId: coordinatorDaemonId } : {}),
|
|
1828
|
+
source: 'daemon_reconcile_transcript_completion',
|
|
1829
|
+
});
|
|
1830
|
+
if (result.reconciled) {
|
|
1831
|
+
LOG.info('MeshReconcile', `Synthesized missing completion (${result.kind}) for task ${taskId} on node ${nodeId} (mesh ${mesh.id})`);
|
|
1832
|
+
}
|
|
1833
|
+
} catch (e: any) {
|
|
1834
|
+
LOG.warn('MeshReconcile', `Transcript completion reconcile threw for task ${taskId}: ${e?.message || e}`);
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
|
|
1839
|
+
// PHASE 5 helper. Build the live-node view (mesh.nodes decorated with each node's live
|
|
1840
|
+
// session list) and run the shared prune core in execute mode with the conservative age gate.
|
|
1841
|
+
//
|
|
1842
|
+
// Orphan detection needs the SAME live-session evidence the manual MCP prune uses: a node still
|
|
1843
|
+
// in mesh.nodes whose session list no longer contains the dispatched sessionId is "session not
|
|
1844
|
+
// present" (prunable); a node missing from mesh.nodes entirely is "node no longer in live mesh"
|
|
1845
|
+
// (prunable). We obtain live sessions per node via get_status_metadata — local nodes through the
|
|
1846
|
+
// local commandHandler, remote nodes over P2P (dispatchMeshCommand) — exactly the transports
|
|
1847
|
+
// PHASE 4 already uses. A node we cannot probe (offline) keeps an empty session list; combined
|
|
1848
|
+
// with the age gate that only matters once the orphan is genuinely old.
|
|
1849
|
+
//
|
|
1850
|
+
// O(1) fast exit: when there are no active direct dispatches at all there is nothing to prune,
|
|
1851
|
+
// so we skip the (per-node) status probes entirely — an idle mesh costs one indexed query.
|
|
1852
|
+
async function autoPruneStaleDirectDispatches(
|
|
1853
|
+
components: DaemonComponents,
|
|
1854
|
+
mesh: LocalMeshEntry,
|
|
1855
|
+
selfIds: string[],
|
|
1856
|
+
localDaemonId: string | undefined,
|
|
1857
|
+
minAgeMs: number,
|
|
1858
|
+
): Promise<void> {
|
|
1859
|
+
const directDispatches = getActiveDirectDispatches(mesh.id);
|
|
1860
|
+
if (directDispatches.length === 0) return; // nothing dispatched → nothing to prune
|
|
1861
|
+
|
|
1862
|
+
const liveNodes = await collectLiveNodesWithSessions(components, mesh, selfIds, localDaemonId);
|
|
1863
|
+
|
|
1864
|
+
const result = pruneStaleDirectDispatches({
|
|
1865
|
+
meshId: mesh.id,
|
|
1866
|
+
queue: getQueue(mesh.id),
|
|
1867
|
+
ledgerEntries: readLedgerEntries(mesh.id, { tail: 500 }),
|
|
1868
|
+
directDispatches,
|
|
1869
|
+
nodes: liveNodes,
|
|
1870
|
+
execute: true,
|
|
1871
|
+
minAgeMs,
|
|
1872
|
+
source: 'daemon_reconcile_auto_prune',
|
|
1873
|
+
});
|
|
1874
|
+
|
|
1875
|
+
// Log only when something was actually pruned — silence on the common no-op tick.
|
|
1876
|
+
if (result.prunedCount > 0) {
|
|
1877
|
+
LOG.info('MeshReconcile', `Auto-pruned ${result.prunedCount} orphaned direct dispatch record(s) for mesh ${mesh.id}`);
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1881
|
+
// Probe each node for its live session list (get_status_metadata) and return mesh.nodes
|
|
1882
|
+
// decorated with a `sessions` array — the shape buildMeshActiveWork / sessionStatusFromNodes
|
|
1883
|
+
// consume to decide whether a dispatched session is still present. Best-effort: an unreachable
|
|
1884
|
+
// node yields an empty session list rather than throwing.
|
|
1885
|
+
async function collectLiveNodesWithSessions(
|
|
1886
|
+
components: DaemonComponents,
|
|
1887
|
+
mesh: LocalMeshEntry,
|
|
1888
|
+
selfIds: string[],
|
|
1889
|
+
localDaemonId: string | undefined,
|
|
1890
|
+
): Promise<any[]> {
|
|
1891
|
+
const dispatchMeshCommand = components.dispatchMeshCommand;
|
|
1892
|
+
return Promise.all(mesh.nodes.map(async (node) => {
|
|
1893
|
+
const nodeDaemonId = readNonEmptyString(node.daemonId);
|
|
1894
|
+
const isLocalNode = !nodeDaemonId
|
|
1895
|
+
|| daemonIdListIncludes(selfIds, nodeDaemonId)
|
|
1896
|
+
|| daemonIdsEquivalent(nodeDaemonId, localDaemonId);
|
|
1897
|
+
let statusResult: unknown;
|
|
1898
|
+
try {
|
|
1899
|
+
if (isLocalNode) {
|
|
1900
|
+
statusResult = await components.commandHandler.handle('get_status_metadata', {});
|
|
1901
|
+
} else if (dispatchMeshCommand) {
|
|
1902
|
+
statusResult = await dispatchMeshCommand(nodeDaemonId, 'get_status_metadata', {});
|
|
1903
|
+
} else {
|
|
1904
|
+
return node; // remote node, no P2P transport — leave undecorated
|
|
1905
|
+
}
|
|
1906
|
+
} catch {
|
|
1907
|
+
return node; // unreachable — leave undecorated (empty session list)
|
|
1908
|
+
}
|
|
1909
|
+
const sessions = extractStatusMetadataSessions(statusResult);
|
|
1910
|
+
return sessions.length > 0 ? { ...node, sessions } : node;
|
|
1911
|
+
}));
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
// Pull the live session list out of a get_status_metadata result, tolerating the same
|
|
1915
|
+
// envelope shapes unwrapReadChatPayload handles (direct CommandResult or { payload }/{ result }).
|
|
1916
|
+
function extractStatusMetadataSessions(raw: unknown): any[] {
|
|
1917
|
+
let cursor: unknown = raw;
|
|
1918
|
+
for (let depth = 0; depth < 4 && cursor && typeof cursor === 'object'; depth++) {
|
|
1919
|
+
const record = cursor as Record<string, unknown>;
|
|
1920
|
+
const status = record.status && typeof record.status === 'object' ? record.status as Record<string, unknown> : undefined;
|
|
1921
|
+
if (status && Array.isArray(status.sessions)) return status.sessions;
|
|
1922
|
+
if (Array.isArray(record.sessions)) return record.sessions;
|
|
1923
|
+
if (record.payload && typeof record.payload === 'object') { cursor = record.payload; continue; }
|
|
1924
|
+
if (record.result && typeof record.result === 'object') { cursor = record.result; continue; }
|
|
1925
|
+
if (record.data && typeof record.data === 'object') { cursor = record.data; continue; }
|
|
1926
|
+
break;
|
|
1927
|
+
}
|
|
1928
|
+
return [];
|
|
1929
|
+
}
|
|
1930
|
+
|
|
1931
|
+
function extractPendingEvents(raw: unknown): any[] {
|
|
1932
|
+
if (Array.isArray(raw)) return raw;
|
|
1933
|
+
if (raw && typeof raw === 'object') {
|
|
1934
|
+
const events = (raw as Record<string, unknown>).events;
|
|
1935
|
+
if (Array.isArray(events)) return events;
|
|
1936
|
+
}
|
|
1937
|
+
return [];
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1940
|
+
// Flatten a queued PendingMeshCoordinatorEvent into the flat payload shape
|
|
1941
|
+
// handleMeshForwardEvent expects (mirrors the MCP buildMeshForwardPayloadFromPendingEvent).
|
|
1942
|
+
function buildForwardPayloadFromPending(event: any): Record<string, unknown> {
|
|
1943
|
+
const metadata = event?.metadataEvent && typeof event.metadataEvent === 'object'
|
|
1944
|
+
? event.metadataEvent as Record<string, unknown>
|
|
1945
|
+
: {};
|
|
1946
|
+
return {
|
|
1947
|
+
event: readNonEmptyString(event?.event),
|
|
1948
|
+
meshId: readNonEmptyString(event?.meshId),
|
|
1949
|
+
nodeId: readNonEmptyString(event?.nodeId) || readNonEmptyString(metadata.meshNodeId),
|
|
1950
|
+
workspace: readNonEmptyString(event?.workspace) || readNonEmptyString(metadata.workspace),
|
|
1951
|
+
// Preserve the originating coordinator session id across the relay. It is normally
|
|
1952
|
+
// carried inside metadataEvent.meshCoordinatorSessionId (spread below), but pass the
|
|
1953
|
+
// top-level field through explicitly too so the handleMeshForwardEvent whitelist
|
|
1954
|
+
// recovers it regardless of which carrier the producing daemon used.
|
|
1955
|
+
...(readNonEmptyString(event?.targetCoordinatorSessionId)
|
|
1956
|
+
? { targetCoordinatorSessionId: readNonEmptyString(event.targetCoordinatorSessionId) }
|
|
1957
|
+
: {}),
|
|
1958
|
+
...metadata,
|
|
1959
|
+
// NOTIF-MISS (FIX 3): surface the dispatch task id at the TOP LEVEL so the relay's
|
|
1960
|
+
// received-stage trace (and buildRelayMetadataEvent) recovers it regardless of which
|
|
1961
|
+
// carrier the producing daemon used. The metadata spread above may carry the id only as
|
|
1962
|
+
// `meshActiveTaskId` (a worker provider event), leaving top-level `taskId` unset and the
|
|
1963
|
+
// received stage rendering `task=-`. Resolve both carriers into an explicit `taskId` so
|
|
1964
|
+
// dedup stays task-scoped end-to-end. Only set when a non-empty id exists (no clobber to
|
|
1965
|
+
// undefined when neither is present).
|
|
1966
|
+
...((): Record<string, unknown> => {
|
|
1967
|
+
const tid = readNonEmptyString(metadata.taskId) || readNonEmptyString(metadata.meshActiveTaskId);
|
|
1968
|
+
return tid ? { taskId: tid } : {};
|
|
1969
|
+
})(),
|
|
1970
|
+
};
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
interface ReconcileLoopHandle {
|
|
1974
|
+
stop(): void;
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
// Start the periodic reconcile loop. Returns a handle with stop() for shutdown.
|
|
1978
|
+
export function setupMeshReconcileLoop(components: DaemonComponents): ReconcileLoopHandle {
|
|
1979
|
+
const intervalMs = resolveReconcileIntervalMs();
|
|
1980
|
+
let running = false;
|
|
1981
|
+
const timer = setInterval(() => {
|
|
1982
|
+
if (running) return; // never overlap ticks
|
|
1983
|
+
running = true;
|
|
1984
|
+
void runMeshReconcileTick(components)
|
|
1985
|
+
.catch((e: any) => LOG.warn('MeshReconcile', `Reconcile tick error: ${e?.message || e}`))
|
|
1986
|
+
.finally(() => { running = false; });
|
|
1987
|
+
}, intervalMs);
|
|
1988
|
+
// Don't keep the process alive solely for this timer.
|
|
1989
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
1990
|
+
LOG.info('MeshReconcile', `Mesh reconcile loop started (interval ${intervalMs}ms)`);
|
|
1991
|
+
return {
|
|
1992
|
+
stop() {
|
|
1993
|
+
clearInterval(timer);
|
|
1994
|
+
LOG.info('MeshReconcile', 'Mesh reconcile loop stopped');
|
|
1995
|
+
},
|
|
1996
|
+
};
|
|
1997
|
+
}
|