@adhdev/daemon-core 0.9.82-rc.46 → 0.9.82-rc.460
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/boot/daemon-lifecycle.d.ts +9 -0
- package/dist/boot/process-hardening.d.ts +50 -0
- package/dist/build-info.d.ts +37 -0
- package/dist/chat/source-machine.d.ts +166 -0
- package/dist/chat/source-resolver.d.ts +104 -0
- package/dist/chat/subscription-updates.d.ts +1 -0
- package/dist/cli-adapter-types.d.ts +68 -2
- package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
- package/dist/cli-adapters/cli-state-engine.d.ts +200 -0
- package/dist/cli-adapters/provider-cli-adapter.d.ts +126 -64
- package/dist/cli-adapters/provider-cli-parse.d.ts +5 -0
- package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
- package/dist/cli-adapters/provider-cli-shared.d.ts +74 -0
- package/dist/cli-adapters/pty-write-chunking.d.ts +34 -0
- package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
- package/dist/cli-adapters/resolve-executable.d.ts +69 -0
- package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
- package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
- package/dist/cli-adapters/terminal-screen.d.ts +4 -11
- package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
- package/dist/commands/chat-commands-read.d.ts +7 -0
- package/dist/commands/chat-commands-scope.d.ts +39 -0
- package/dist/commands/chat-commands-shared.d.ts +33 -0
- package/dist/commands/chat-commands-write.d.ts +14 -0
- package/dist/commands/chat-commands.d.ts +10 -23
- package/dist/commands/cli-manager.d.ts +25 -1
- package/dist/commands/handler.d.ts +125 -0
- package/dist/commands/high-family/index.d.ts +3 -0
- package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
- package/dist/commands/high-family/mesh-events.d.ts +2 -0
- package/dist/commands/high-family/mesh-status.d.ts +2 -0
- package/dist/commands/high-family/types.d.ts +64 -0
- package/dist/commands/low-family/coordinator-prompt.d.ts +9 -0
- package/dist/commands/low-family/daemon-lifecycle.d.ts +2 -0
- package/dist/commands/low-family/diagnostics.d.ts +2 -0
- package/dist/commands/low-family/index.d.ts +3 -0
- package/dist/commands/low-family/mesh-ledger.d.ts +10 -0
- package/dist/commands/low-family/mesh-node-logs.d.ts +2 -0
- package/dist/commands/low-family/notification.d.ts +2 -0
- package/dist/commands/low-family/refine-config.d.ts +2 -0
- package/dist/commands/low-family/session-host.d.ts +2 -0
- package/dist/commands/low-family/spec-providerdev.d.ts +11 -0
- package/dist/commands/low-family/status-meta.d.ts +2 -0
- package/dist/commands/low-family/types.d.ts +33 -0
- package/dist/commands/med-family/cli-agent.d.ts +2 -0
- package/dist/commands/med-family/fast-forward.d.ts +2 -0
- package/dist/commands/med-family/ide.d.ts +10 -0
- package/dist/commands/med-family/index.d.ts +3 -0
- package/dist/commands/med-family/mesh-crud.d.ts +48 -0
- package/dist/commands/med-family/mesh-host-pairing.d.ts +2 -0
- package/dist/commands/med-family/mesh-queue.d.ts +2 -0
- package/dist/commands/med-family/mesh-restart.d.ts +2 -0
- package/dist/commands/med-family/types.d.ts +152 -0
- package/dist/commands/mesh-coordinator.d.ts +85 -1
- package/dist/commands/router-refine.d.ts +137 -0
- package/dist/commands/router-worktree-cleanup.d.ts +133 -0
- package/dist/commands/router.d.ts +241 -12
- package/dist/commands/upgrade-helper.d.ts +41 -1
- package/dist/config/chat-history.d.ts +9 -0
- package/dist/config/config.d.ts +19 -0
- package/dist/config/mesh-config.d.ts +129 -1
- package/dist/config/mesh-json-config.d.ts +199 -0
- package/dist/config/registry-resolver.d.ts +54 -0
- package/dist/config/repo-settings.d.ts +77 -0
- package/dist/daemon/dev-server.d.ts +0 -2
- package/dist/detection/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 +12 -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 +67 -15
- package/dist/index.js +57943 -25340
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +57611 -25174
- package/dist/index.mjs.map +1 -1
- package/dist/installer.d.ts +1 -4
- package/dist/ipc/local-ipc-server.d.ts +91 -0
- package/dist/launch.d.ts +1 -1
- package/dist/logging/async-batch-writer.d.ts +10 -0
- package/dist/logging/debug-config.d.ts +16 -0
- package/dist/logging/log-redactor.d.ts +24 -0
- package/dist/logging/log-tail-reader.d.ts +81 -0
- package/dist/logging/logger.d.ts +1 -1
- package/dist/mesh/contracts.d.ts +230 -0
- package/dist/mesh/coordinator-prompt.d.ts +76 -0
- package/dist/mesh/coordinator-registry.d.ts +59 -0
- package/dist/mesh/mesh-active-work.d.ts +174 -0
- package/dist/mesh/mesh-clone-grace.d.ts +8 -0
- package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
- package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
- package/dist/mesh/mesh-event-classify.d.ts +7 -0
- package/dist/mesh/mesh-event-forwarding.d.ts +41 -0
- package/dist/mesh/mesh-event-trace.d.ts +21 -0
- package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
- package/dist/mesh/mesh-events-pending.d.ts +113 -0
- package/dist/mesh/mesh-events-stale.d.ts +61 -0
- package/dist/mesh/mesh-events-utils.d.ts +75 -0
- package/dist/mesh/mesh-events.d.ts +6 -49
- package/dist/mesh/mesh-fast-forward.d.ts +81 -0
- package/dist/mesh/mesh-host-ownership.d.ts +29 -0
- package/dist/mesh/mesh-init.d.ts +128 -0
- package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
- package/dist/mesh/mesh-ledger.d.ts +133 -1
- package/dist/mesh/mesh-magi-status.d.ts +63 -0
- package/dist/mesh/mesh-missions.d.ts +189 -0
- package/dist/mesh/mesh-node-identity.d.ts +306 -0
- package/dist/mesh/mesh-queue-assignment.d.ts +158 -0
- package/dist/mesh/mesh-reconcile-loop.d.ts +80 -0
- package/dist/mesh/mesh-refine-batch.d.ts +68 -0
- package/dist/mesh/mesh-refine-gates.d.ts +428 -0
- package/dist/mesh/mesh-refine-status.d.ts +62 -0
- package/dist/mesh/mesh-review-inbox.d.ts +90 -0
- package/dist/mesh/mesh-routing.d.ts +70 -0
- package/dist/mesh/mesh-runtime-store.d.ts +476 -0
- package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
- package/dist/mesh/mesh-task-inflight.d.ts +46 -0
- package/dist/mesh/mesh-task-stats.d.ts +49 -0
- package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
- package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
- package/dist/mesh/mesh-work-queue.d.ts +318 -5
- package/dist/mesh/preview-freshness.d.ts +28 -0
- package/dist/mesh/refine-config.d.ts +216 -0
- package/dist/mesh/worktree-bootstrap-config.d.ts +219 -0
- package/dist/providers/acp-provider-instance.d.ts +5 -0
- package/dist/providers/approval-utils.d.ts +45 -0
- package/dist/providers/chat-message-normalization.d.ts +58 -1
- package/dist/providers/cli-provider-instance.d.ts +290 -3
- package/dist/providers/contracts.d.ts +149 -6
- package/dist/providers/external-sources.d.ts +71 -0
- package/dist/providers/manual-attendance.d.ts +79 -0
- package/dist/providers/native-history/antigravity-claim-registry.d.ts +28 -0
- package/dist/providers/native-history/antigravity-cli-transcript.d.ts +137 -0
- package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
- package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
- package/dist/providers/native-history/constants.d.ts +12 -0
- package/dist/providers/native-history/dispatcher.d.ts +31 -0
- package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
- package/dist/providers/native-history/index.d.ts +13 -0
- package/dist/providers/provider-instance-manager.d.ts +29 -0
- package/dist/providers/provider-instance.d.ts +30 -1
- package/dist/providers/provider-loader.d.ts +42 -5
- package/dist/providers/provider-trust.d.ts +31 -0
- package/dist/providers/read-chat-contract.d.ts +29 -0
- package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
- package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
- package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
- package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
- package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
- package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
- package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
- package/dist/providers/sdk/v1/index.d.ts +30 -0
- package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
- package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
- package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
- package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
- package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
- package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
- package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
- package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
- package/dist/providers/spec/adapter.d.ts +98 -0
- package/dist/providers/spec/cli-adapter.d.ts +223 -0
- package/dist/providers/spec/evaluator.d.ts +45 -0
- package/dist/providers/spec/fsm-driver.d.ts +449 -0
- package/dist/providers/spec/fsm-evaluator.d.ts +93 -0
- package/dist/providers/spec/fsm-loader.d.ts +14 -0
- package/dist/providers/spec/fsm-types.d.ts +202 -0
- package/dist/providers/spec/native-history-executor.d.ts +41 -0
- package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
- package/dist/providers/spec/route.d.ts +4 -0
- package/dist/providers/spec/types.d.ts +222 -0
- package/dist/providers/status-monitor.d.ts +7 -7
- package/dist/providers/transcript-v2.d.ts +176 -0
- package/dist/providers/types/interactive-prompt.d.ts +84 -0
- package/dist/providers/working-dir.d.ts +17 -0
- package/dist/repo-mesh-types.d.ts +519 -13
- package/dist/runtime-defaults.d.ts +2 -0
- package/dist/session-host/managed-host.d.ts +64 -0
- package/dist/session-host/runtime-surface.d.ts +10 -16
- package/dist/sessions/registry.d.ts +6 -0
- package/dist/shared-types-extra.d.ts +2 -4
- package/dist/shared-types.d.ts +86 -55
- package/dist/status/normalize.d.ts +1 -1
- package/dist/status/normalize.js +1 -0
- package/dist/status/normalize.js.map +1 -1
- package/dist/status/normalize.mjs +1 -0
- package/dist/status/normalize.mjs.map +1 -1
- package/dist/status/reporter.d.ts +2 -0
- package/dist/status/snapshot.d.ts +26 -0
- package/dist/system/hash.d.ts +8 -0
- package/dist/system/load-better-sqlite3.d.ts +21 -0
- package/dist/types.d.ts +5 -0
- package/package.json +11 -4
- package/src/agent-stream/poller.ts +2 -3
- package/src/agent-stream/provider-adapter.ts +1 -1
- package/src/boot/daemon-lifecycle.ts +65 -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/chat-commands-debug-bundle.ts +398 -0
- package/src/commands/chat-commands-read.ts +2488 -0
- package/src/commands/chat-commands-scope.ts +54 -0
- package/src/commands/chat-commands-shared.ts +114 -0
- package/src/commands/chat-commands-write.ts +891 -0
- package/src/commands/chat-commands.ts +19 -1841
- package/src/commands/cli-manager.ts +596 -27
- package/src/commands/handler.ts +845 -2
- package/src/commands/high-family/index.ts +28 -0
- package/src/commands/high-family/mesh-coordinator-launch.ts +680 -0
- package/src/commands/high-family/mesh-events.ts +89 -0
- package/src/commands/high-family/mesh-status.ts +822 -0
- package/src/commands/high-family/types.ts +80 -0
- package/src/commands/low-family/coordinator-prompt.ts +72 -0
- package/src/commands/low-family/daemon-lifecycle.ts +120 -0
- package/src/commands/low-family/diagnostics.ts +57 -0
- package/src/commands/low-family/index.ts +37 -0
- package/src/commands/low-family/mesh-ledger.ts +62 -0
- package/src/commands/low-family/mesh-node-logs.ts +87 -0
- package/src/commands/low-family/notification.ts +116 -0
- package/src/commands/low-family/refine-config.ts +106 -0
- package/src/commands/low-family/session-host.ts +274 -0
- package/src/commands/low-family/spec-providerdev.ts +217 -0
- package/src/commands/low-family/status-meta.ts +112 -0
- package/src/commands/low-family/types.ts +39 -0
- package/src/commands/med-family/cli-agent.ts +241 -0
- package/src/commands/med-family/fast-forward.ts +230 -0
- package/src/commands/med-family/ide.ts +163 -0
- package/src/commands/med-family/index.ts +37 -0
- package/src/commands/med-family/mesh-crud.ts +1287 -0
- package/src/commands/med-family/mesh-host-pairing.ts +234 -0
- package/src/commands/med-family/mesh-queue.ts +167 -0
- package/src/commands/med-family/mesh-restart.ts +92 -0
- package/src/commands/med-family/types.ts +153 -0
- package/src/commands/mesh-coordinator.ts +334 -124
- package/src/commands/router-refine.ts +1711 -0
- package/src/commands/router-worktree-cleanup.ts +870 -0
- package/src/commands/router.ts +1025 -4070
- package/src/commands/stream-commands.ts +8 -0
- package/src/commands/upgrade-helper.ts +310 -45
- package/src/config/chat-history.ts +493 -24
- package/src/config/config.ts +30 -0
- package/src/config/mesh-config.ts +619 -23
- package/src/config/mesh-json-config.ts +376 -0
- package/src/config/recent-activity.ts +8 -2
- package/src/config/registry-resolver.ts +100 -0
- package/src/config/repo-settings.ts +111 -0
- package/src/daemon/dev-auto-implement.ts +3 -2
- package/src/daemon/dev-cli-debug.ts +10 -1
- package/src/daemon/dev-server.ts +0 -541
- package/src/detection/cli-detector.ts +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 +78 -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 +200 -12
- package/src/installer.d.ts +1 -1
- package/src/installer.ts +8 -6
- package/src/ipc/local-ipc-server.ts +278 -0
- package/src/launch.d.ts +1 -1
- package/src/launch.ts +37 -28
- package/src/logging/async-batch-writer.ts +55 -0
- package/src/logging/command-log.ts +7 -5
- package/src/logging/debug-config.ts +25 -0
- package/src/logging/debug-trace.ts +7 -2
- package/src/logging/log-redactor.ts +100 -0
- package/src/logging/log-tail-reader.ts +341 -0
- package/src/logging/logger.ts +14 -7
- package/src/mesh/contracts.ts +469 -0
- package/src/mesh/coordinator-prompt.ts +536 -34
- package/src/mesh/coordinator-registry.ts +121 -0
- package/src/mesh/mesh-active-work.ts +656 -0
- package/src/mesh/mesh-clone-grace.ts +68 -0
- package/src/mesh/mesh-coordinator-config.ts +97 -0
- package/src/mesh/mesh-delivery-policy.ts +315 -0
- package/src/mesh/mesh-event-classify.ts +73 -0
- package/src/mesh/mesh-event-forwarding.ts +1932 -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 +766 -0
- package/src/mesh/mesh-events-stale.ts +440 -0
- package/src/mesh/mesh-events-utils.ts +443 -0
- package/src/mesh/mesh-events.ts +33 -1035
- package/src/mesh/mesh-fast-forward.ts +856 -0
- package/src/mesh/mesh-host-ownership.ts +111 -0
- package/src/mesh/mesh-init.ts +350 -0
- package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
- package/src/mesh/mesh-ledger.ts +873 -102
- package/src/mesh/mesh-magi-status.ts +223 -0
- package/src/mesh/mesh-missions.ts +449 -0
- package/src/mesh/mesh-node-identity.ts +1994 -0
- package/src/mesh/mesh-queue-assignment.ts +2233 -0
- package/src/mesh/mesh-reconcile-loop.ts +2390 -0
- package/src/mesh/mesh-refine-batch.ts +205 -0
- package/src/mesh/mesh-refine-gates.ts +1686 -0
- package/src/mesh/mesh-refine-status.ts +231 -0
- package/src/mesh/mesh-review-inbox.ts +308 -0
- package/src/mesh/mesh-routing.ts +291 -0
- package/src/mesh/mesh-runtime-store.ts +2026 -0
- package/src/mesh/mesh-scheduling-runtime.ts +198 -0
- package/src/mesh/mesh-task-inflight.ts +70 -0
- package/src/mesh/mesh-task-stats.ts +161 -0
- package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
- package/src/mesh/mesh-warmup-deadline.ts +152 -0
- package/src/mesh/mesh-work-queue.ts +1281 -141
- package/src/mesh/preview-freshness.ts +163 -0
- package/src/mesh/refine-config.ts +423 -0
- package/src/mesh/worktree-bootstrap-config.ts +599 -0
- package/src/providers/acp-provider-instance.ts +43 -10
- package/src/providers/approval-utils.d.ts +5 -0
- package/src/providers/approval-utils.ts +99 -5
- package/src/providers/chat-message-normalization.ts +126 -4
- package/src/providers/cli-provider-instance.ts +2456 -107
- package/src/providers/contracts.d.ts +55 -0
- package/src/providers/contracts.ts +160 -6
- package/src/providers/extension-provider-instance.ts +12 -7
- package/src/providers/external-sources.ts +218 -0
- package/src/providers/ide-provider-instance.ts +35 -12
- package/src/providers/manual-attendance.ts +105 -0
- package/src/providers/native-history/antigravity-claim-registry.ts +131 -0
- package/src/providers/native-history/antigravity-cli-transcript.ts +1193 -0
- package/src/providers/native-history/claude-cli-transcript.ts +396 -0
- package/src/providers/native-history/codex-cli-transcript.ts +479 -0
- package/src/providers/native-history/constants.ts +19 -0
- package/src/providers/native-history/dispatcher.ts +503 -0
- package/src/providers/native-history/hermes-cli-transcript.ts +260 -0
- package/src/providers/native-history/index.ts +30 -0
- package/src/providers/provider-instance-manager.ts +71 -0
- package/src/providers/provider-instance.ts +24 -1
- package/src/providers/provider-loader.ts +700 -55
- package/src/providers/provider-schema.ts +87 -14
- package/src/providers/provider-trust.ts +114 -0
- package/src/providers/read-chat-contract.ts +76 -16
- package/src/providers/sdk/README.md +49 -0
- package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
- package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval.ts +261 -0
- package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
- package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
- package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
- package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
- package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
- package/src/providers/sdk/v1/index.ts +152 -0
- package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
- package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
- package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
- package/src/providers/sdk/v1/schemas/cli/provider.schema.json +509 -0
- package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
- package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
- package/src/providers/sdk/v1/types/cli/index.ts +365 -0
- package/src/providers/sdk/v1/types/common/index.ts +229 -0
- package/src/providers/sdk/v1/validators/index.ts +19 -0
- package/src/providers/sdk/v1/validators/manifest.ts +110 -0
- package/src/providers/sdk/v1/validators/taint.ts +309 -0
- package/src/providers/spec/adapter.ts +246 -0
- package/src/providers/spec/cli-adapter.ts +1064 -0
- package/src/providers/spec/evaluator.ts +407 -0
- package/src/providers/spec/fsm-driver.ts +1528 -0
- package/src/providers/spec/fsm-evaluator.ts +290 -0
- package/src/providers/spec/fsm-loader.ts +128 -0
- package/src/providers/spec/fsm-types.ts +301 -0
- package/src/providers/spec/native-history-executor.ts +1174 -0
- package/src/providers/spec/pre-launch-trust.ts +104 -0
- package/src/providers/spec/route.ts +51 -0
- package/src/providers/spec/types.ts +262 -0
- package/src/providers/status-monitor.d.ts +7 -7
- package/src/providers/status-monitor.ts +37 -22
- package/src/providers/transcript-v2.ts +567 -0
- package/src/providers/types/interactive-prompt.ts +536 -0
- package/src/providers/version-archive.ts +64 -24
- package/src/providers/working-dir.ts +23 -0
- package/src/repo-mesh-types.ts +758 -14
- package/src/runtime-defaults.ts +39 -0
- package/src/session-host/managed-host.ts +218 -0
- package/src/session-host/runtime-surface.ts +20 -80
- package/src/sessions/registry.ts +6 -0
- package/src/shared-types-extra.ts +2 -4
- package/src/shared-types.d.ts +8 -0
- package/src/shared-types.ts +124 -55
- package/src/status/builders.ts +26 -6
- package/src/status/normalize.ts +2 -0
- package/src/status/reporter.ts +19 -1
- package/src/status/snapshot.ts +95 -26
- package/src/system/hash.ts +23 -0
- package/src/system/host-memory.ts +29 -12
- package/src/system/load-better-sqlite3.ts +68 -0
- package/src/types.ts +5 -0
- package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
- package/dist/mesh/mesh-sync.d.ts +0 -53
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
- package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
- package/src/mesh/mesh-sync.ts +0 -111
|
@@ -0,0 +1,2026 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, statSync } from 'fs';
|
|
2
|
+
import { dirname, join } from 'path';
|
|
3
|
+
import { LOG } from '../logging/logger.js';
|
|
4
|
+
import { loadBetterSqlite3 } from '../system/load-better-sqlite3.js';
|
|
5
|
+
import { getLedgerDir } from './mesh-ledger.js';
|
|
6
|
+
import { nodeSatisfiesRequiredTags, isTaskReadonly, taskDependenciesSatisfied } from './mesh-work-queue.js';
|
|
7
|
+
import { meshNodeIdMatches, daemonIdsEquivalent, expandDaemonIdForms, sessionIdsEquivalent } from '@adhdev/mesh-shared';
|
|
8
|
+
import type { MeshTaskStatus, MeshWorkQueueEntry } from './mesh-work-queue.js';
|
|
9
|
+
import type BetterSqlite3 from 'better-sqlite3';
|
|
10
|
+
import type { Database as DatabaseHandle } from 'better-sqlite3';
|
|
11
|
+
|
|
12
|
+
let DatabaseCtor: typeof BetterSqlite3 | undefined;
|
|
13
|
+
|
|
14
|
+
function loadDatabaseCtor(): typeof BetterSqlite3 {
|
|
15
|
+
if (DatabaseCtor) return DatabaseCtor;
|
|
16
|
+
DatabaseCtor = loadBetterSqlite3() as typeof BetterSqlite3;
|
|
17
|
+
return DatabaseCtor;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function safeMeshId(meshId: string): string {
|
|
21
|
+
return meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// T2 (B2b): a persisted acked-hold record for one in-flight direct dispatch. The
|
|
25
|
+
// reconcile loop keeps a Map cache of these but this row is the SSOT so the hold
|
|
26
|
+
// survives a daemon restart. See the mesh_inflight_hold table comment.
|
|
27
|
+
export interface MeshInflightHoldRow {
|
|
28
|
+
taskId: string;
|
|
29
|
+
meshId: string | null;
|
|
30
|
+
holdReason: string | null;
|
|
31
|
+
heldAt: number | null;
|
|
32
|
+
firstIdleSinceAck: number | null;
|
|
33
|
+
readFailureCount: number | null;
|
|
34
|
+
updatedAt: number | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function legacyQueuePath(meshId: string): string {
|
|
38
|
+
return join(getLedgerDir(), `${safeMeshId(meshId)}.queue.json`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
let loggedMigrationFailure = false;
|
|
42
|
+
|
|
43
|
+
function meshRuntimeStorePath(): string {
|
|
44
|
+
const dir = getLedgerDir();
|
|
45
|
+
const nextPath = join(dir, 'mesh-runtime.db');
|
|
46
|
+
if (existsSync(nextPath)) return nextPath;
|
|
47
|
+
|
|
48
|
+
const legacyPath = join(dir, 'beads.db');
|
|
49
|
+
if (!existsSync(legacyPath)) return nextPath;
|
|
50
|
+
|
|
51
|
+
try {
|
|
52
|
+
renameSync(legacyPath, nextPath);
|
|
53
|
+
for (const suffix of ['-wal', '-shm']) {
|
|
54
|
+
const legacyCompanion = `${legacyPath}${suffix}`;
|
|
55
|
+
if (existsSync(legacyCompanion)) {
|
|
56
|
+
renameSync(legacyCompanion, `${nextPath}${suffix}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
} catch (err: any) {
|
|
60
|
+
// Migration failed — most commonly win32 EPERM when a handle to the
|
|
61
|
+
// legacy DB is still open. Do NOT fall through to opening `nextPath`:
|
|
62
|
+
// that would create a fresh EMPTY store while the existing data stays
|
|
63
|
+
// stranded in the legacy file (split-brain / silent data loss). Instead
|
|
64
|
+
// keep using whichever file actually holds the data in-place — the next
|
|
65
|
+
// boot retries the rename. If the main rename already landed (only a
|
|
66
|
+
// companion file failed), the data is at nextPath; otherwise it is still
|
|
67
|
+
// at legacyPath.
|
|
68
|
+
if (!loggedMigrationFailure) {
|
|
69
|
+
loggedMigrationFailure = true;
|
|
70
|
+
LOG.warn(
|
|
71
|
+
'MeshRuntimeStore',
|
|
72
|
+
`Legacy beads.db→mesh-runtime.db migration failed; using existing DB in-place to avoid data loss: ${err?.message || err}`,
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
return existsSync(nextPath) ? nextPath : legacyPath;
|
|
76
|
+
}
|
|
77
|
+
return nextPath;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export class MeshRuntimeStore {
|
|
81
|
+
private static instance: MeshRuntimeStore | undefined;
|
|
82
|
+
private readonly db: DatabaseHandle;
|
|
83
|
+
private readonly dbPath: string;
|
|
84
|
+
private readonly migratedMeshIds = new Set<string>();
|
|
85
|
+
private fingerprintSweepCounter = 0;
|
|
86
|
+
private walWriteCounter = 0;
|
|
87
|
+
// Independent cadence for the tool-call-log sweep. Must NOT share walWriteCounter:
|
|
88
|
+
// sharing makes each store's threshold drift by the other's write volume (WAL
|
|
89
|
+
// checkpoint at 500 vs tool-log sweep at 200 would interfere arbitrarily).
|
|
90
|
+
private toolCallLogCounter = 0;
|
|
91
|
+
private static readonly WAL_CHECK_INTERVAL = 500;
|
|
92
|
+
private static readonly WAL_MAX_BYTES = 50 * 1024 * 1024; // 50 MB
|
|
93
|
+
|
|
94
|
+
private constructor(dbPath: string) {
|
|
95
|
+
const dir = dirname(dbPath);
|
|
96
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
97
|
+
|
|
98
|
+
this.dbPath = dbPath;
|
|
99
|
+
this.db = new (loadDatabaseCtor())(dbPath);
|
|
100
|
+
this.db.pragma('journal_mode = WAL');
|
|
101
|
+
this.db.pragma('synchronous = NORMAL');
|
|
102
|
+
this.db.pragma('foreign_keys = ON');
|
|
103
|
+
this.db.pragma('busy_timeout = 5000');
|
|
104
|
+
this.migrate();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private static loggedGetInstanceFailure = false;
|
|
108
|
+
|
|
109
|
+
static getInstance(): MeshRuntimeStore {
|
|
110
|
+
if (!this.instance) {
|
|
111
|
+
try {
|
|
112
|
+
this.instance = new MeshRuntimeStore(meshRuntimeStorePath());
|
|
113
|
+
} catch (err: any) {
|
|
114
|
+
// SQLite store could not be opened (e.g. better-sqlite3 native
|
|
115
|
+
// load failure, locked/corrupt DB). Callers wrap getInstance in
|
|
116
|
+
// try/catch and silently degrade to JSONL-only — surface ONE warn
|
|
117
|
+
// so that degraded mode is diagnosable, then re-throw unchanged.
|
|
118
|
+
if (!MeshRuntimeStore.loggedGetInstanceFailure) {
|
|
119
|
+
MeshRuntimeStore.loggedGetInstanceFailure = true;
|
|
120
|
+
LOG.warn(
|
|
121
|
+
'MeshRuntimeStore',
|
|
122
|
+
`getInstance failed; callers will degrade to JSONL-only: ${err?.message || err}`,
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
throw err;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return this.instance;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
static resetForTests(): void {
|
|
132
|
+
this.instance?.close();
|
|
133
|
+
this.instance = undefined;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
close(): void {
|
|
137
|
+
this.db.close();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
transaction<T>(fn: () => T): T {
|
|
141
|
+
return this.db.transaction(fn).immediate();
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private migrate(): void {
|
|
145
|
+
this.db.exec(`
|
|
146
|
+
CREATE TABLE IF NOT EXISTS mesh_queue (
|
|
147
|
+
id TEXT PRIMARY KEY,
|
|
148
|
+
mesh_id TEXT NOT NULL,
|
|
149
|
+
status TEXT NOT NULL,
|
|
150
|
+
target_node_id TEXT,
|
|
151
|
+
target_session_id TEXT,
|
|
152
|
+
assigned_node_id TEXT,
|
|
153
|
+
assigned_session_id TEXT,
|
|
154
|
+
created_at TEXT NOT NULL,
|
|
155
|
+
updated_at TEXT NOT NULL,
|
|
156
|
+
payload TEXT NOT NULL
|
|
157
|
+
);
|
|
158
|
+
|
|
159
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_queue_mesh_status_created
|
|
160
|
+
ON mesh_queue(mesh_id, status, created_at);
|
|
161
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_queue_assignment
|
|
162
|
+
ON mesh_queue(mesh_id, assigned_node_id, assigned_session_id, status);
|
|
163
|
+
|
|
164
|
+
-- mesh_id is DB-level isolation (defense-in-depth). The fingerprint STRING
|
|
165
|
+
-- also carries meshId as its first '::'-joined segment (see
|
|
166
|
+
-- buildMeshCompletionFingerprint) — that string-prefix defense is kept; this
|
|
167
|
+
-- column makes cross-mesh suppression impossible even if the string format
|
|
168
|
+
-- drifts or two meshes ever collide on a fingerprint body.
|
|
169
|
+
CREATE TABLE IF NOT EXISTS mesh_completion_fingerprints (
|
|
170
|
+
fingerprint TEXT PRIMARY KEY,
|
|
171
|
+
expires_at INTEGER NOT NULL,
|
|
172
|
+
mesh_id TEXT NOT NULL DEFAULT ''
|
|
173
|
+
);
|
|
174
|
+
-- NOTE: the (mesh_id, fingerprint) index is created in migrateMeshIsolationColumns,
|
|
175
|
+
-- NOT here. A pre-isolation DB still has the legacy table (CREATE IF NOT EXISTS is a
|
|
176
|
+
-- no-op), so referencing mesh_id in an index before the ALTER ADD COLUMN runs would
|
|
177
|
+
-- fail with "no such column". The migration adds the column then the index.
|
|
178
|
+
|
|
179
|
+
CREATE TABLE IF NOT EXISTS mesh_direct_dispatches (
|
|
180
|
+
task_id TEXT PRIMARY KEY,
|
|
181
|
+
mesh_id TEXT NOT NULL,
|
|
182
|
+
node_id TEXT,
|
|
183
|
+
session_id TEXT,
|
|
184
|
+
provider_type TEXT,
|
|
185
|
+
message TEXT NOT NULL,
|
|
186
|
+
task_mode TEXT,
|
|
187
|
+
via TEXT NOT NULL,
|
|
188
|
+
status TEXT NOT NULL DEFAULT 'dispatched',
|
|
189
|
+
dispatched_to_idle_session INTEGER NOT NULL DEFAULT 0,
|
|
190
|
+
dispatched_at TEXT NOT NULL,
|
|
191
|
+
updated_at TEXT NOT NULL
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
CREATE INDEX IF NOT EXISTS idx_direct_dispatches_mesh_session
|
|
195
|
+
ON mesh_direct_dispatches(mesh_id, session_id, status);
|
|
196
|
+
|
|
197
|
+
-- MESH-ISOLATION-LEAK: mesh_id is part of the PK so a nodeId shared across two
|
|
198
|
+
-- meshes (same machine in multiple repos) keeps a separate idle-session row per
|
|
199
|
+
-- mesh, and getRemoteIdleSessions(meshId) can never surface another mesh's
|
|
200
|
+
-- session for a queue claim.
|
|
201
|
+
CREATE TABLE IF NOT EXISTS remote_idle_sessions (
|
|
202
|
+
mesh_id TEXT NOT NULL,
|
|
203
|
+
node_id TEXT NOT NULL,
|
|
204
|
+
session_id TEXT NOT NULL,
|
|
205
|
+
provider_type TEXT NOT NULL,
|
|
206
|
+
expires_at INTEGER NOT NULL,
|
|
207
|
+
metadata TEXT,
|
|
208
|
+
PRIMARY KEY (mesh_id, node_id, session_id)
|
|
209
|
+
);
|
|
210
|
+
|
|
211
|
+
CREATE TABLE IF NOT EXISTS mesh_session_delivery (
|
|
212
|
+
id TEXT PRIMARY KEY,
|
|
213
|
+
mesh_id TEXT NOT NULL,
|
|
214
|
+
node_id TEXT,
|
|
215
|
+
session_id TEXT,
|
|
216
|
+
provider_type TEXT,
|
|
217
|
+
task_id TEXT,
|
|
218
|
+
kind TEXT NOT NULL,
|
|
219
|
+
priority INTEGER NOT NULL DEFAULT 0,
|
|
220
|
+
message TEXT NOT NULL,
|
|
221
|
+
status TEXT NOT NULL DEFAULT 'queued',
|
|
222
|
+
deliver_after TEXT,
|
|
223
|
+
expires_at TEXT,
|
|
224
|
+
attempt_count INTEGER NOT NULL DEFAULT 0,
|
|
225
|
+
source_coordinator_session_id TEXT,
|
|
226
|
+
source_coordinator_daemon_id TEXT,
|
|
227
|
+
last_error TEXT,
|
|
228
|
+
created_at TEXT NOT NULL,
|
|
229
|
+
updated_at TEXT NOT NULL
|
|
230
|
+
);
|
|
231
|
+
|
|
232
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_session_delivery_mesh_status
|
|
233
|
+
ON mesh_session_delivery(mesh_id, status, created_at);
|
|
234
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_session_delivery_session
|
|
235
|
+
ON mesh_session_delivery(mesh_id, session_id, status);
|
|
236
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_session_delivery_task
|
|
237
|
+
ON mesh_session_delivery(mesh_id, task_id);
|
|
238
|
+
|
|
239
|
+
CREATE TABLE IF NOT EXISTS mesh_completion_conflicts (
|
|
240
|
+
id TEXT PRIMARY KEY,
|
|
241
|
+
mesh_id TEXT NOT NULL,
|
|
242
|
+
fingerprint TEXT NOT NULL,
|
|
243
|
+
conflicting_task_id TEXT,
|
|
244
|
+
conflicting_session_id TEXT,
|
|
245
|
+
original_task_id TEXT,
|
|
246
|
+
original_session_id TEXT,
|
|
247
|
+
event TEXT NOT NULL,
|
|
248
|
+
created_at TEXT NOT NULL
|
|
249
|
+
);
|
|
250
|
+
|
|
251
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_completion_conflicts_mesh
|
|
252
|
+
ON mesh_completion_conflicts(mesh_id, created_at);
|
|
253
|
+
|
|
254
|
+
CREATE TABLE IF NOT EXISTS mesh_tool_call_log (
|
|
255
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
256
|
+
mesh_id TEXT NOT NULL,
|
|
257
|
+
tool TEXT NOT NULL,
|
|
258
|
+
session_id TEXT,
|
|
259
|
+
called_at INTEGER NOT NULL
|
|
260
|
+
);
|
|
261
|
+
|
|
262
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_tool_call_log_mesh_tool_time
|
|
263
|
+
ON mesh_tool_call_log(mesh_id, tool, called_at);
|
|
264
|
+
|
|
265
|
+
-- G2: Event ledger — runtime source of truth for task/session lifecycle events.
|
|
266
|
+
-- JSONL files are retained as export/import/debug/legacy artifacts only.
|
|
267
|
+
CREATE TABLE IF NOT EXISTS mesh_event_ledger (
|
|
268
|
+
id TEXT PRIMARY KEY,
|
|
269
|
+
mesh_id TEXT NOT NULL,
|
|
270
|
+
timestamp TEXT NOT NULL,
|
|
271
|
+
kind TEXT NOT NULL,
|
|
272
|
+
node_id TEXT,
|
|
273
|
+
session_id TEXT,
|
|
274
|
+
provider_type TEXT,
|
|
275
|
+
payload TEXT NOT NULL DEFAULT '{}'
|
|
276
|
+
);
|
|
277
|
+
|
|
278
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_event_ledger_mesh_time
|
|
279
|
+
ON mesh_event_ledger(mesh_id, timestamp);
|
|
280
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_event_ledger_mesh_kind
|
|
281
|
+
ON mesh_event_ledger(mesh_id, kind, timestamp);
|
|
282
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_event_ledger_session
|
|
283
|
+
ON mesh_event_ledger(mesh_id, session_id, timestamp);
|
|
284
|
+
|
|
285
|
+
-- G3: Pending coordinator event inbox — replaces <meshId>.pending-events.jsonl.
|
|
286
|
+
-- Coordinator drains this table on get_pending_mesh_events, then deletes drained rows.
|
|
287
|
+
CREATE TABLE IF NOT EXISTS mesh_pending_events (
|
|
288
|
+
id TEXT PRIMARY KEY,
|
|
289
|
+
mesh_id TEXT NOT NULL,
|
|
290
|
+
coordinator_daemon_id TEXT,
|
|
291
|
+
event TEXT NOT NULL,
|
|
292
|
+
payload TEXT NOT NULL DEFAULT '{}',
|
|
293
|
+
fingerprint TEXT,
|
|
294
|
+
queued_at INTEGER NOT NULL,
|
|
295
|
+
drained INTEGER NOT NULL DEFAULT 0,
|
|
296
|
+
drained_at INTEGER,
|
|
297
|
+
-- v2 protocol envelope (B2a). All nullable so pre-v2 rows and events
|
|
298
|
+
-- emitted before a coordinator identity is known coexist as v1. The
|
|
299
|
+
-- authoritative copy of each also rides inside the payload column; these
|
|
300
|
+
-- columns exist for queryable idempotency (event_id) and scope-based drain
|
|
301
|
+
-- filtering without JSON-parsing every row. dispatched_by / intended_for
|
|
302
|
+
-- hold the JSON-serialized CoordinatorIdentity.
|
|
303
|
+
protocol_version TEXT,
|
|
304
|
+
event_id TEXT,
|
|
305
|
+
scope TEXT,
|
|
306
|
+
dispatched_by TEXT,
|
|
307
|
+
intended_for TEXT
|
|
308
|
+
);
|
|
309
|
+
|
|
310
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_pending_events_mesh_drained
|
|
311
|
+
ON mesh_pending_events(mesh_id, drained, queued_at);
|
|
312
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_mesh_pending_events_fingerprint
|
|
313
|
+
ON mesh_pending_events(mesh_id, fingerprint)
|
|
314
|
+
WHERE fingerprint IS NOT NULL;
|
|
315
|
+
|
|
316
|
+
-- M3: persistent mission records. Plans live in the system, not in the
|
|
317
|
+
-- coordinator LLM's context. Progress is derived from task statuses at
|
|
318
|
+
-- query time (mission_id on queue tasks) — never stored here.
|
|
319
|
+
CREATE TABLE IF NOT EXISTS mesh_missions (
|
|
320
|
+
id TEXT PRIMARY KEY,
|
|
321
|
+
mesh_id TEXT NOT NULL,
|
|
322
|
+
title TEXT NOT NULL,
|
|
323
|
+
goal TEXT NOT NULL DEFAULT '',
|
|
324
|
+
status TEXT NOT NULL DEFAULT 'active',
|
|
325
|
+
source TEXT,
|
|
326
|
+
created_at TEXT NOT NULL,
|
|
327
|
+
updated_at TEXT NOT NULL
|
|
328
|
+
);
|
|
329
|
+
|
|
330
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_missions_mesh_status
|
|
331
|
+
ON mesh_missions(mesh_id, status, updated_at);
|
|
332
|
+
|
|
333
|
+
-- Load-balancing scheduler: per-mesh round-robin rotation cursor. When
|
|
334
|
+
-- the schedulingStrategy is 'round_robin', several eligible nodes tied at
|
|
335
|
+
-- the least load are rotated by this cursor so the tie-break winner cycles
|
|
336
|
+
-- across scheduling passes instead of always favouring the same array-order
|
|
337
|
+
-- node. Persisted (not a module Map) so rotation survives daemon restarts
|
|
338
|
+
-- and stays a single source of truth across scheduling entry points.
|
|
339
|
+
CREATE TABLE IF NOT EXISTS mesh_scheduler_cursor (
|
|
340
|
+
mesh_id TEXT PRIMARY KEY,
|
|
341
|
+
cursor INTEGER NOT NULL DEFAULT 0
|
|
342
|
+
);
|
|
343
|
+
|
|
344
|
+
-- T2 (B2b): persistent acked-hold state for in-flight direct dispatches.
|
|
345
|
+
-- The reconcile loop's PHASE-4 acked-hold (death-consequence counter,
|
|
346
|
+
-- fast-track idle streak, live-confirmed flag) used to live only in a
|
|
347
|
+
-- process-local Map (mesh-reconcile-loop.ts inFlightAckedHoldState), so a
|
|
348
|
+
-- daemon restart lost it — re-opening the door to the duplicate-emit / drop
|
|
349
|
+
-- window that the PHASE-4 transcript synth backstop then had to correct after
|
|
350
|
+
-- the fact. Persisting it lets the state survive a restart: the loop
|
|
351
|
+
-- rehydrates the Map from this table on first touch and stays read-through /
|
|
352
|
+
-- write-through against it thereafter. Keyed by task_id (one hold per
|
|
353
|
+
-- in-flight dispatch); mesh_id is carried for per-mesh listing / prune.
|
|
354
|
+
-- hold_reason — 'live' once a conclusive read confirmed the session
|
|
355
|
+
-- reachable since the ack, else 'unconfirmed' (drives
|
|
356
|
+
-- the death-backstop's liveConfirmedSinceAck gate).
|
|
357
|
+
-- held_at — ms epoch the hold row was first created.
|
|
358
|
+
-- first_idle_since_ack — ms epoch of the FIRST tick in the current continuous
|
|
359
|
+
-- idle-with-final-assistant run (fast-track streak); NULL
|
|
360
|
+
-- when the streak is broken / not yet started.
|
|
361
|
+
-- read_failure_count — consecutive read_chat failures since the last
|
|
362
|
+
-- conclusive read (death backstop (a)).
|
|
363
|
+
CREATE TABLE IF NOT EXISTS mesh_inflight_hold (
|
|
364
|
+
task_id TEXT PRIMARY KEY,
|
|
365
|
+
mesh_id TEXT,
|
|
366
|
+
hold_reason TEXT,
|
|
367
|
+
held_at INTEGER,
|
|
368
|
+
first_idle_since_ack INTEGER,
|
|
369
|
+
read_failure_count INTEGER,
|
|
370
|
+
updated_at INTEGER
|
|
371
|
+
);
|
|
372
|
+
|
|
373
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_inflight_hold_mesh
|
|
374
|
+
ON mesh_inflight_hold(mesh_id);
|
|
375
|
+
`);
|
|
376
|
+
this.migrateMeshIsolationColumns();
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
private tableColumns(table: string): Set<string> {
|
|
380
|
+
const rows = this.db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;
|
|
381
|
+
return new Set(rows.map(r => r.name));
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* MESH-ISOLATION-LEAK migration. Two tables historically lacked a `mesh_id` column,
|
|
386
|
+
* letting one machine that belongs to multiple meshes (multiple repos) leak rows
|
|
387
|
+
* across meshes. Both migrations are idempotent and run on every boot — the column
|
|
388
|
+
* check short-circuits once the new schema is in place.
|
|
389
|
+
*/
|
|
390
|
+
private migrateMeshIsolationColumns(): void {
|
|
391
|
+
try {
|
|
392
|
+
// 1. mesh_completion_fingerprints: ADD COLUMN + backfill mesh_id from the
|
|
393
|
+
// fingerprint string's first '::'-joined segment (buildMeshCompletionFingerprint
|
|
394
|
+
// prefixes meshId). A row whose fingerprint has no '::' (legacy/foreign format)
|
|
395
|
+
// backfills to '' — still strictly tighter than the prior global query.
|
|
396
|
+
const fpCols = this.tableColumns('mesh_completion_fingerprints');
|
|
397
|
+
if (!fpCols.has('mesh_id')) {
|
|
398
|
+
this.db.exec(`ALTER TABLE mesh_completion_fingerprints ADD COLUMN mesh_id TEXT NOT NULL DEFAULT ''`);
|
|
399
|
+
this.db.exec(`
|
|
400
|
+
UPDATE mesh_completion_fingerprints
|
|
401
|
+
SET mesh_id = substr(fingerprint, 1, instr(fingerprint, '::') - 1)
|
|
402
|
+
WHERE instr(fingerprint, '::') > 0 AND mesh_id = ''
|
|
403
|
+
`);
|
|
404
|
+
}
|
|
405
|
+
// The mesh_id column is now guaranteed to exist (fresh DB had it from CREATE TABLE,
|
|
406
|
+
// legacy DB just got it via ALTER). Create the index unconditionally — IF NOT EXISTS
|
|
407
|
+
// makes it a no-op once present.
|
|
408
|
+
this.db.exec(`
|
|
409
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_completion_fingerprints_mesh
|
|
410
|
+
ON mesh_completion_fingerprints(mesh_id, fingerprint)
|
|
411
|
+
`);
|
|
412
|
+
|
|
413
|
+
// 2. remote_idle_sessions: the mesh_id is part of the PRIMARY KEY, which SQLite
|
|
414
|
+
// cannot add via ALTER. The rows are ephemeral — sessions re-register on the
|
|
415
|
+
// next agent:ready / agent:generating_completed — so a safe DROP+recreate is
|
|
416
|
+
// acceptable (per fix spec) rather than a full table rebuild + un-backfillable
|
|
417
|
+
// mesh_id. Only rebuild when the legacy (no mesh_id) schema is detected.
|
|
418
|
+
const idleCols = this.tableColumns('remote_idle_sessions');
|
|
419
|
+
if (!idleCols.has('mesh_id')) {
|
|
420
|
+
this.db.exec(`
|
|
421
|
+
DROP TABLE IF EXISTS remote_idle_sessions;
|
|
422
|
+
CREATE TABLE remote_idle_sessions (
|
|
423
|
+
mesh_id TEXT NOT NULL,
|
|
424
|
+
node_id TEXT NOT NULL,
|
|
425
|
+
session_id TEXT NOT NULL,
|
|
426
|
+
provider_type TEXT NOT NULL,
|
|
427
|
+
expires_at INTEGER NOT NULL,
|
|
428
|
+
metadata TEXT,
|
|
429
|
+
PRIMARY KEY (mesh_id, node_id, session_id)
|
|
430
|
+
);
|
|
431
|
+
`);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// 3. mesh_missions.source: nullable provenance tag ('magi' | 'coordinator').
|
|
435
|
+
// Pre-existing rows keep source NULL — listMeshMissionSummaries treats a
|
|
436
|
+
// NULL/absent source as a coordinator mission (never auto-hidden), so the
|
|
437
|
+
// completed-MAGI bounding only ever affects rows explicitly stamped 'magi'.
|
|
438
|
+
const missionCols = this.tableColumns('mesh_missions');
|
|
439
|
+
if (!missionCols.has('source')) {
|
|
440
|
+
this.db.exec(`ALTER TABLE mesh_missions ADD COLUMN source TEXT`);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// 4. mesh_pending_events v2 envelope columns (B2a). A pre-v2 DB has the
|
|
444
|
+
// table (CREATE IF NOT EXISTS is a no-op) without these columns, so add
|
|
445
|
+
// each missing one. All nullable — legacy rows read back as v1 events
|
|
446
|
+
// (protocol_version NULL) with no reader change. Idempotent: the column
|
|
447
|
+
// check short-circuits once present, and every ADD COLUMN is guarded.
|
|
448
|
+
const pendingCols = this.tableColumns('mesh_pending_events');
|
|
449
|
+
for (const col of ['protocol_version', 'event_id', 'scope', 'dispatched_by', 'intended_for'] as const) {
|
|
450
|
+
if (!pendingCols.has(col)) {
|
|
451
|
+
this.db.exec(`ALTER TABLE mesh_pending_events ADD COLUMN ${col} TEXT`);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
// Idempotency index on event_id (partial: only stamped v2 rows). Created
|
|
455
|
+
// unconditionally — IF NOT EXISTS makes it a no-op once present, and the
|
|
456
|
+
// event_id column is guaranteed to exist by the loop above.
|
|
457
|
+
this.db.exec(`
|
|
458
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_pending_events_event_id
|
|
459
|
+
ON mesh_pending_events(mesh_id, event_id)
|
|
460
|
+
WHERE event_id IS NOT NULL
|
|
461
|
+
`);
|
|
462
|
+
} catch (err: any) {
|
|
463
|
+
// Best-effort: a failed isolation migration must not brick the store. The
|
|
464
|
+
// CREATE-TABLE definitions above already carry the new schema for fresh DBs;
|
|
465
|
+
// an existing DB that fails here keeps the old (leaky-but-functional) schema
|
|
466
|
+
// until the next boot retries. Surface one warn for diagnosability.
|
|
467
|
+
if (!loggedMigrationFailure) {
|
|
468
|
+
loggedMigrationFailure = true;
|
|
469
|
+
LOG.warn('MeshRuntimeStore', `mesh-isolation column migration failed: ${err?.message || err}`);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
hasCompletionFingerprint(meshId: string, fingerprint: string): boolean {
|
|
475
|
+
const now = Date.now();
|
|
476
|
+
// Scope by mesh_id (defense-in-depth) AS WELL AS the fingerprint string, whose
|
|
477
|
+
// first '::' segment already encodes meshId. A fingerprint can only suppress a
|
|
478
|
+
// duplicate within its own mesh.
|
|
479
|
+
const row = this.db
|
|
480
|
+
.prepare('SELECT 1 FROM mesh_completion_fingerprints WHERE mesh_id = ? AND fingerprint = ? AND expires_at > ?')
|
|
481
|
+
.get(meshId, fingerprint, now) as { 1: number } | undefined;
|
|
482
|
+
// Sweep expired fingerprints every 100 reads so stale rows don't accumulate
|
|
483
|
+
// even during read-heavy (non-write) periods when recordFingerprintSeen is idle.
|
|
484
|
+
if (++this.fingerprintSweepCounter >= 100) {
|
|
485
|
+
this.fingerprintSweepCounter = 0;
|
|
486
|
+
this.sweepExpiredFingerprints();
|
|
487
|
+
}
|
|
488
|
+
return row !== undefined;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
recordCompletionFingerprint(meshId: string, fingerprint: string, ttlMs: number): void {
|
|
492
|
+
const expiresAt = Date.now() + ttlMs;
|
|
493
|
+
this.db.prepare('INSERT OR REPLACE INTO mesh_completion_fingerprints (fingerprint, expires_at, mesh_id) VALUES (?, ?, ?)')
|
|
494
|
+
.run(fingerprint, expiresAt, meshId);
|
|
495
|
+
this.maybeCheckpointWal();
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
sweepExpiredFingerprints(): void {
|
|
499
|
+
this.db.prepare('DELETE FROM mesh_completion_fingerprints WHERE expires_at <= ?').run(Date.now());
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
private maybeCheckpointWal(): void {
|
|
503
|
+
if (++this.walWriteCounter < MeshRuntimeStore.WAL_CHECK_INTERVAL) return;
|
|
504
|
+
this.walWriteCounter = 0;
|
|
505
|
+
try {
|
|
506
|
+
const walPath = `${this.dbPath}-wal`;
|
|
507
|
+
if (!existsSync(walPath)) return;
|
|
508
|
+
const size = statSync(walPath).size;
|
|
509
|
+
if (size < MeshRuntimeStore.WAL_MAX_BYTES) return;
|
|
510
|
+
process.stderr.write(
|
|
511
|
+
`[adhdev-mesh] WAL file ${Math.round(size / 1024 / 1024)}MB exceeds threshold; forcing checkpoint\n`,
|
|
512
|
+
);
|
|
513
|
+
this.db.pragma('wal_checkpoint(TRUNCATE)');
|
|
514
|
+
} catch { /* best-effort */ }
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
private ensureLegacyQueueMigrated(meshId: string): void {
|
|
518
|
+
if (this.migratedMeshIds.has(meshId)) return;
|
|
519
|
+
this.migratedMeshIds.add(meshId);
|
|
520
|
+
|
|
521
|
+
const count = this.db
|
|
522
|
+
.prepare('SELECT COUNT(*) AS count FROM mesh_queue WHERE mesh_id = ?')
|
|
523
|
+
.get(meshId) as { count: number };
|
|
524
|
+
if (count.count > 0) return;
|
|
525
|
+
|
|
526
|
+
const path = legacyQueuePath(meshId);
|
|
527
|
+
if (!existsSync(path)) return;
|
|
528
|
+
|
|
529
|
+
try {
|
|
530
|
+
const entries = JSON.parse(readFileSync(path, 'utf-8')) as MeshWorkQueueEntry[];
|
|
531
|
+
if (!Array.isArray(entries)) return;
|
|
532
|
+
const insert = this.db.prepare(`
|
|
533
|
+
INSERT OR REPLACE INTO mesh_queue (
|
|
534
|
+
id, mesh_id, status, target_node_id, target_session_id,
|
|
535
|
+
assigned_node_id, assigned_session_id, created_at, updated_at, payload
|
|
536
|
+
) VALUES (
|
|
537
|
+
@id, @meshId, @status, @targetNodeId, @targetSessionId,
|
|
538
|
+
@assignedNodeId, @assignedSessionId, @createdAt, @updatedAt, @payload
|
|
539
|
+
)
|
|
540
|
+
`);
|
|
541
|
+
for (const entry of entries) {
|
|
542
|
+
insert.run(this.toRow(entry));
|
|
543
|
+
}
|
|
544
|
+
} catch {
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
getQueueEntries(meshId: string, statuses?: MeshTaskStatus[]): MeshWorkQueueEntry[] {
|
|
550
|
+
this.ensureLegacyQueueMigrated(meshId);
|
|
551
|
+
if (statuses?.length) {
|
|
552
|
+
const placeholders = statuses.map(() => '?').join(', ');
|
|
553
|
+
const rows = this.db
|
|
554
|
+
.prepare(`SELECT payload FROM mesh_queue WHERE mesh_id = ? AND status IN (${placeholders}) ORDER BY created_at ASC`)
|
|
555
|
+
.all(meshId, ...statuses) as Array<{ payload: string }>;
|
|
556
|
+
return rows.map(row => JSON.parse(row.payload) as MeshWorkQueueEntry);
|
|
557
|
+
}
|
|
558
|
+
const rows = this.db
|
|
559
|
+
.prepare('SELECT payload FROM mesh_queue WHERE mesh_id = ? ORDER BY created_at ASC')
|
|
560
|
+
.all(meshId) as Array<{ payload: string }>;
|
|
561
|
+
return rows.map(row => JSON.parse(row.payload) as MeshWorkQueueEntry);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
getQueueRevision(meshId: string): string {
|
|
565
|
+
this.ensureLegacyQueueMigrated(meshId);
|
|
566
|
+
const rows = this.db
|
|
567
|
+
.prepare('SELECT id, status, updated_at FROM mesh_queue WHERE mesh_id = ? ORDER BY id ASC')
|
|
568
|
+
.all(meshId) as Array<{ id: string; status: string; updated_at: string }>;
|
|
569
|
+
// Tab as field delimiter (UUIDs and ISO timestamps never contain tabs).
|
|
570
|
+
return rows.map(row => `${row.id}\t${row.status}\t${row.updated_at}`).join('\n');
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
replaceQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
|
|
574
|
+
const deleteStmt = this.db.prepare('DELETE FROM mesh_queue WHERE mesh_id = ?');
|
|
575
|
+
const insert = this.db.prepare(`
|
|
576
|
+
INSERT INTO mesh_queue (
|
|
577
|
+
id, mesh_id, status, target_node_id, target_session_id,
|
|
578
|
+
assigned_node_id, assigned_session_id, created_at, updated_at, payload
|
|
579
|
+
) VALUES (
|
|
580
|
+
@id, @meshId, @status, @targetNodeId, @targetSessionId,
|
|
581
|
+
@assignedNodeId, @assignedSessionId, @createdAt, @updatedAt, @payload
|
|
582
|
+
)
|
|
583
|
+
`);
|
|
584
|
+
deleteStmt.run(meshId);
|
|
585
|
+
for (const entry of queue) insert.run(this.toRow(entry));
|
|
586
|
+
this.maybeCheckpointWal();
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
deleteQueue(meshId: string): void {
|
|
590
|
+
this.db.prepare('DELETE FROM mesh_queue WHERE mesh_id = ?').run(meshId);
|
|
591
|
+
this.migratedMeshIds.delete(meshId);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
insertQueueEntry(entry: MeshWorkQueueEntry): void {
|
|
595
|
+
this.db.prepare(`
|
|
596
|
+
INSERT INTO mesh_queue (
|
|
597
|
+
id, mesh_id, status, target_node_id, target_session_id,
|
|
598
|
+
assigned_node_id, assigned_session_id, created_at, updated_at, payload
|
|
599
|
+
) VALUES (
|
|
600
|
+
@id, @meshId, @status, @targetNodeId, @targetSessionId,
|
|
601
|
+
@assignedNodeId, @assignedSessionId, @createdAt, @updatedAt, @payload
|
|
602
|
+
)
|
|
603
|
+
`).run(this.toRow(entry));
|
|
604
|
+
this.maybeCheckpointWal();
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
updateQueueEntry(entry: MeshWorkQueueEntry): void {
|
|
608
|
+
const now = new Date().toISOString();
|
|
609
|
+
entry.updatedAt = now;
|
|
610
|
+
this.db.prepare(`
|
|
611
|
+
UPDATE mesh_queue SET
|
|
612
|
+
status = @status,
|
|
613
|
+
target_node_id = @targetNodeId,
|
|
614
|
+
target_session_id = @targetSessionId,
|
|
615
|
+
assigned_node_id = @assignedNodeId,
|
|
616
|
+
assigned_session_id = @assignedSessionId,
|
|
617
|
+
updated_at = @updatedAt,
|
|
618
|
+
payload = @payload
|
|
619
|
+
WHERE id = @id AND mesh_id = @meshId
|
|
620
|
+
`).run(this.toRow(entry));
|
|
621
|
+
this.maybeCheckpointWal();
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
findQueueEntryById(meshId: string, id: string): MeshWorkQueueEntry | null {
|
|
625
|
+
this.ensureLegacyQueueMigrated(meshId);
|
|
626
|
+
const row = this.db.prepare(
|
|
627
|
+
'SELECT payload FROM mesh_queue WHERE id = ? AND mesh_id = ?'
|
|
628
|
+
).get(id, meshId) as { payload: string } | undefined;
|
|
629
|
+
return row ? JSON.parse(row.payload) as MeshWorkQueueEntry : null;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
hasActiveAssignment(meshId: string, sessionId: string, nodeId: string): boolean {
|
|
633
|
+
this.ensureLegacyQueueMigrated(meshId);
|
|
634
|
+
const row = this.db.prepare(`
|
|
635
|
+
SELECT 1 FROM mesh_queue
|
|
636
|
+
WHERE mesh_id = ? AND status = 'assigned'
|
|
637
|
+
AND (assigned_session_id = ? OR assigned_node_id = ?)
|
|
638
|
+
LIMIT 1
|
|
639
|
+
`).get(meshId, sessionId, nodeId);
|
|
640
|
+
return row !== undefined;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** A session may only execute one task at a time, regardless of task mode. */
|
|
644
|
+
private hasActiveSessionAssignment(meshId: string, sessionId: string): boolean {
|
|
645
|
+
const row = this.db.prepare(`
|
|
646
|
+
SELECT 1 FROM mesh_queue
|
|
647
|
+
WHERE mesh_id = ? AND status = 'assigned' AND assigned_session_id = ?
|
|
648
|
+
LIMIT 1
|
|
649
|
+
`).get(meshId, sessionId);
|
|
650
|
+
return row !== undefined;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/** A node may only execute one write task at a time (worktree isolation). */
|
|
654
|
+
private hasActiveNodeAssignment(meshId: string, nodeId: string): boolean {
|
|
655
|
+
// The serialization gate (claimNextQueueTask's `!nodeBusy`) must see a node as
|
|
656
|
+
// busy when ANY active row's assigned_node_id matches in ANY equivalent
|
|
657
|
+
// daemon-id form (config-form `daemon_mach_X` vs stamp-form `mach_X`, or the
|
|
658
|
+
// standalone form). A raw `assigned_node_id = ?` on a single form silently
|
|
659
|
+
// misses a form-variant assigned row, making an already-assigned node look idle
|
|
660
|
+
// and letting a second write task claim it — duplicate claim / base leak. Mirror
|
|
661
|
+
// the node-pinned SELECT below (the `target_node_id IN (...)` query): expand to
|
|
662
|
+
// every equivalent form and bind an IN (...) set so the busy gate and the
|
|
663
|
+
// candidate SELECT use the SAME matching rule.
|
|
664
|
+
const nodeIdForms = expandDaemonIdForms(nodeId);
|
|
665
|
+
if (nodeIdForms.length === 0) return false;
|
|
666
|
+
const placeholders = nodeIdForms.map(() => '?').join(', ');
|
|
667
|
+
const row = this.db.prepare(`
|
|
668
|
+
SELECT 1 FROM mesh_queue
|
|
669
|
+
WHERE mesh_id = ? AND status = 'assigned' AND assigned_node_id IN (${placeholders})
|
|
670
|
+
LIMIT 1
|
|
671
|
+
`).get(meshId, ...nodeIdForms);
|
|
672
|
+
return row !== undefined;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/**
|
|
676
|
+
* Count active (status='assigned') tasks on a node, regardless of provider or
|
|
677
|
+
* task mode. This is the load metric for least-loaded / round-robin ranking:
|
|
678
|
+
* the scheduler prefers the node with the fewest active assignments so
|
|
679
|
+
* untargeted work spreads instead of piling onto whichever node asks first.
|
|
680
|
+
*/
|
|
681
|
+
nodeActiveAssignmentCount(meshId: string, nodeId: string): number {
|
|
682
|
+
const row = this.db.prepare(`
|
|
683
|
+
SELECT COUNT(*) as count FROM mesh_queue
|
|
684
|
+
WHERE mesh_id = ? AND status = 'assigned' AND assigned_node_id = ?
|
|
685
|
+
`).get(meshId, nodeId) as { count: number } | undefined;
|
|
686
|
+
return row?.count ?? 0;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* O(1) count of queue tasks in 'pending' status for a mesh. A COUNT(*) over the
|
|
691
|
+
* indexed status column, so it avoids JSON.parse-ing every queue row — used as a
|
|
692
|
+
* cheap guard before the reconcile loop runs a full triggerMeshQueue scan.
|
|
693
|
+
*/
|
|
694
|
+
pendingQueueTaskCount(meshId: string): number {
|
|
695
|
+
const row = this.db.prepare(`
|
|
696
|
+
SELECT COUNT(*) as count FROM mesh_queue
|
|
697
|
+
WHERE mesh_id = ? AND status = 'pending'
|
|
698
|
+
`).get(meshId) as { count: number } | undefined;
|
|
699
|
+
return row?.count ?? 0;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* Read the current per-mesh round-robin cursor (0 when unset). Used to rotate
|
|
704
|
+
* the tie-break winner among nodes tied at the least load.
|
|
705
|
+
*/
|
|
706
|
+
getSchedulerCursor(meshId: string): number {
|
|
707
|
+
const row = this.db.prepare(
|
|
708
|
+
'SELECT cursor FROM mesh_scheduler_cursor WHERE mesh_id = ?'
|
|
709
|
+
).get(meshId) as { cursor: number } | undefined;
|
|
710
|
+
return row?.cursor ?? 0;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* Atomically advance the per-mesh round-robin cursor by one and return the
|
|
715
|
+
* value that was current BEFORE the bump (the value the caller should rotate
|
|
716
|
+
* by for this pass). UPSERT keeps it lock-free across concurrent passes.
|
|
717
|
+
*/
|
|
718
|
+
bumpSchedulerCursor(meshId: string): number {
|
|
719
|
+
return this.transaction(() => {
|
|
720
|
+
const current = this.getSchedulerCursor(meshId);
|
|
721
|
+
this.db.prepare(`
|
|
722
|
+
INSERT INTO mesh_scheduler_cursor (mesh_id, cursor) VALUES (?, ?)
|
|
723
|
+
ON CONFLICT(mesh_id) DO UPDATE SET cursor = excluded.cursor
|
|
724
|
+
`).run(meshId, current + 1);
|
|
725
|
+
return current;
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// ── Acked-Hold State (T2 / B2b) ──────────────────────────────────────────
|
|
730
|
+
//
|
|
731
|
+
// Persistent mirror of the reconcile loop's inFlightAckedHoldState Map. Keyed
|
|
732
|
+
// by task_id (one in-flight dispatch = one hold). These are plain read/write/
|
|
733
|
+
// delete/list accessors; the read-through/write-through cache and the restart
|
|
734
|
+
// rehydrate live in mesh-reconcile-loop.ts.
|
|
735
|
+
|
|
736
|
+
private mapInflightHoldRow(r: Record<string, unknown> | undefined): MeshInflightHoldRow | null {
|
|
737
|
+
if (!r) return null;
|
|
738
|
+
return {
|
|
739
|
+
taskId: r.task_id as string,
|
|
740
|
+
meshId: (r.mesh_id as string | null) ?? null,
|
|
741
|
+
holdReason: (r.hold_reason as string | null) ?? null,
|
|
742
|
+
heldAt: (r.held_at as number | null) ?? null,
|
|
743
|
+
firstIdleSinceAck: (r.first_idle_since_ack as number | null) ?? null,
|
|
744
|
+
readFailureCount: (r.read_failure_count as number | null) ?? null,
|
|
745
|
+
updatedAt: (r.updated_at as number | null) ?? null,
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
upsertInflightHold(entry: {
|
|
750
|
+
taskId: string;
|
|
751
|
+
meshId?: string | null;
|
|
752
|
+
holdReason?: string | null;
|
|
753
|
+
heldAt?: number | null;
|
|
754
|
+
firstIdleSinceAck?: number | null;
|
|
755
|
+
readFailureCount?: number | null;
|
|
756
|
+
}): void {
|
|
757
|
+
const now = Date.now();
|
|
758
|
+
// Preserve held_at across an upsert (it marks when the hold was first created);
|
|
759
|
+
// only set it from the incoming value when the row is new. All other fields are
|
|
760
|
+
// overwritten with the latest state — the caller passes the full current state.
|
|
761
|
+
this.db.prepare(`
|
|
762
|
+
INSERT INTO mesh_inflight_hold
|
|
763
|
+
(task_id, mesh_id, hold_reason, held_at, first_idle_since_ack, read_failure_count, updated_at)
|
|
764
|
+
VALUES (@taskId, @meshId, @holdReason, @heldAt, @firstIdleSinceAck, @readFailureCount, @updatedAt)
|
|
765
|
+
ON CONFLICT(task_id) DO UPDATE SET
|
|
766
|
+
mesh_id = excluded.mesh_id,
|
|
767
|
+
hold_reason = excluded.hold_reason,
|
|
768
|
+
first_idle_since_ack = excluded.first_idle_since_ack,
|
|
769
|
+
read_failure_count = excluded.read_failure_count,
|
|
770
|
+
updated_at = excluded.updated_at
|
|
771
|
+
`).run({
|
|
772
|
+
taskId: entry.taskId,
|
|
773
|
+
meshId: entry.meshId ?? null,
|
|
774
|
+
holdReason: entry.holdReason ?? null,
|
|
775
|
+
heldAt: entry.heldAt ?? now,
|
|
776
|
+
firstIdleSinceAck: entry.firstIdleSinceAck ?? null,
|
|
777
|
+
readFailureCount: entry.readFailureCount ?? null,
|
|
778
|
+
updatedAt: now,
|
|
779
|
+
});
|
|
780
|
+
this.maybeCheckpointWal();
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
getInflightHold(taskId: string): MeshInflightHoldRow | null {
|
|
784
|
+
const row = this.db.prepare(
|
|
785
|
+
'SELECT * FROM mesh_inflight_hold WHERE task_id = ?'
|
|
786
|
+
).get(taskId) as Record<string, unknown> | undefined;
|
|
787
|
+
return this.mapInflightHoldRow(row);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
listInflightHoldsByMesh(meshId: string): MeshInflightHoldRow[] {
|
|
791
|
+
const rows = this.db.prepare(
|
|
792
|
+
'SELECT * FROM mesh_inflight_hold WHERE mesh_id = ?'
|
|
793
|
+
).all(meshId) as Array<Record<string, unknown>>;
|
|
794
|
+
return rows.map(r => this.mapInflightHoldRow(r)).filter((r): r is MeshInflightHoldRow => r !== null);
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
deleteInflightHold(taskId: string): void {
|
|
798
|
+
this.db.prepare('DELETE FROM mesh_inflight_hold WHERE task_id = ?').run(taskId);
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/**
|
|
802
|
+
* Count active (status='assigned') tasks on a (node, provider) combination,
|
|
803
|
+
* matched by the assignedProviderType stamped on the payload at claim time.
|
|
804
|
+
* Drives the per-(node, provider) maxParallel cap (RepoMeshNodePolicy
|
|
805
|
+
* providerRoles). The active-assignment set for a single node is tiny, so
|
|
806
|
+
* parsing payloads here is cheap and avoids a schema migration. Pre-cap legacy
|
|
807
|
+
* rows (no provider stamp) and other providers on the same node do not consume
|
|
808
|
+
* this provider's budget, so the cap is fully backward compatible.
|
|
809
|
+
*/
|
|
810
|
+
private activeProviderAssignmentCount(meshId: string, nodeId: string, providerType: string): number {
|
|
811
|
+
const rows = this.db.prepare(`
|
|
812
|
+
SELECT payload FROM mesh_queue
|
|
813
|
+
WHERE mesh_id = ? AND status = 'assigned' AND assigned_node_id = ?
|
|
814
|
+
`).all(meshId, nodeId) as Array<{ payload: string }>;
|
|
815
|
+
let count = 0;
|
|
816
|
+
for (const row of rows) {
|
|
817
|
+
try {
|
|
818
|
+
const entry = JSON.parse(row.payload) as MeshWorkQueueEntry;
|
|
819
|
+
if (entry.assignedProviderType === providerType) count += 1;
|
|
820
|
+
} catch { /* skip unparsable row */ }
|
|
821
|
+
}
|
|
822
|
+
return count;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// O(1) claim: transaction ensures only one session claims a pending task
|
|
826
|
+
claimNextQueueTask(
|
|
827
|
+
meshId: string,
|
|
828
|
+
nodeId: string,
|
|
829
|
+
sessionId: string,
|
|
830
|
+
capabilityTags: string[] = [],
|
|
831
|
+
opts?: { providerType?: string; providerMaxParallel?: number; nodeIsWorktree?: boolean },
|
|
832
|
+
): MeshWorkQueueEntry | null {
|
|
833
|
+
return this.transaction(() => {
|
|
834
|
+
this.ensureLegacyQueueMigrated(meshId);
|
|
835
|
+
// A session executes one task at a time regardless of mode — block early.
|
|
836
|
+
// The node-level conflict is evaluated per-candidate below so that
|
|
837
|
+
// read-only (live_debug_readonly) tasks can claim concurrently on a node
|
|
838
|
+
// that already has an active assignment, while write tasks keep the
|
|
839
|
+
// one-active-per-node invariant (worktree isolation).
|
|
840
|
+
if (this.hasActiveSessionAssignment(meshId, sessionId)) return null;
|
|
841
|
+
const nodeBusy = this.hasActiveNodeAssignment(meshId, nodeId);
|
|
842
|
+
|
|
843
|
+
// Per-(node, provider) maxParallel cap (RepoMeshNodePolicy providerRoles).
|
|
844
|
+
// Orthogonal to taskMode: this bounds the (node, provider) resource pool
|
|
845
|
+
// regardless of read-only vs write. When the cap is already met, this
|
|
846
|
+
// session cannot claim any candidate here — return null. This composes
|
|
847
|
+
// with the global/taskMode caps enforced in the coordinator (stricter
|
|
848
|
+
// wins); omitting providerMaxParallel preserves prior behavior exactly.
|
|
849
|
+
const providerType = typeof opts?.providerType === 'string' ? opts.providerType.trim() : '';
|
|
850
|
+
const providerMaxParallel = opts?.providerMaxParallel;
|
|
851
|
+
if (
|
|
852
|
+
providerType
|
|
853
|
+
&& typeof providerMaxParallel === 'number'
|
|
854
|
+
&& Number.isFinite(providerMaxParallel)
|
|
855
|
+
&& providerMaxParallel >= 0
|
|
856
|
+
&& this.activeProviderAssignmentCount(meshId, nodeId, providerType) >= providerMaxParallel
|
|
857
|
+
) {
|
|
858
|
+
return null;
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
// The node-pinned SELECT must match a row whose target_node_id was stamped
|
|
862
|
+
// in ANY equivalent daemon-id form (config-form `daemon_mach_X` vs the
|
|
863
|
+
// claiming session's stamp-form `mach_X`). A single `= ?` bind on the
|
|
864
|
+
// stamp-form silently fails to fetch a config-form row, leaving the task
|
|
865
|
+
// pending forever (the empty-session WORKTREE-CLAIM-GATE repro). Expand to
|
|
866
|
+
// every equivalent form and bind an IN (...) set; the per-candidate
|
|
867
|
+
// targetMatches() JS gate above re-validates each fetched row.
|
|
868
|
+
const nodeIdForms = expandDaemonIdForms(nodeId);
|
|
869
|
+
const nodePinnedPlaceholders = nodeIdForms.map(() => '?').join(', ');
|
|
870
|
+
// Priority: session-targeted > node-targeted (no session) > unconstrained
|
|
871
|
+
const rows = [
|
|
872
|
+
...(
|
|
873
|
+
this.db.prepare(`
|
|
874
|
+
SELECT payload FROM mesh_queue
|
|
875
|
+
WHERE mesh_id = ? AND status = 'pending' AND target_session_id = ?
|
|
876
|
+
ORDER BY created_at ASC
|
|
877
|
+
`).all(meshId, sessionId) as Array<{ payload: string }>
|
|
878
|
+
),
|
|
879
|
+
...(
|
|
880
|
+
this.db.prepare(`
|
|
881
|
+
SELECT payload FROM mesh_queue
|
|
882
|
+
WHERE mesh_id = ? AND status = 'pending' AND target_node_id IN (${nodePinnedPlaceholders}) AND target_session_id IS NULL
|
|
883
|
+
ORDER BY created_at ASC
|
|
884
|
+
`).all(meshId, ...nodeIdForms) as Array<{ payload: string }>
|
|
885
|
+
),
|
|
886
|
+
...(
|
|
887
|
+
this.db.prepare(`
|
|
888
|
+
SELECT payload FROM mesh_queue
|
|
889
|
+
WHERE mesh_id = ? AND status = 'pending' AND target_node_id IS NULL AND target_session_id IS NULL
|
|
890
|
+
ORDER BY created_at ASC
|
|
891
|
+
`).all(meshId) as Array<{ payload: string }>
|
|
892
|
+
),
|
|
893
|
+
];
|
|
894
|
+
const candidates = rows.map(row => JSON.parse(row.payload) as MeshWorkQueueEntry);
|
|
895
|
+
|
|
896
|
+
// M1: a task with unmet dependencies (or a system blockedReason) is not claimable.
|
|
897
|
+
// Resolve dependency statuses in one query over the union of referenced ids.
|
|
898
|
+
const depIds = [...new Set(candidates.flatMap(c => Array.isArray(c.dependsOn) ? c.dependsOn : []))];
|
|
899
|
+
const depStatus = new Map<string, string>();
|
|
900
|
+
if (depIds.length > 0) {
|
|
901
|
+
const placeholders = depIds.map(() => '?').join(', ');
|
|
902
|
+
const depRows = this.db.prepare(
|
|
903
|
+
`SELECT id, status FROM mesh_queue WHERE mesh_id = ? AND id IN (${placeholders})`
|
|
904
|
+
).all(meshId, ...depIds) as Array<{ id: string; status: string }>;
|
|
905
|
+
for (const r of depRows) depStatus.set(r.id, r.status);
|
|
906
|
+
}
|
|
907
|
+
// DEPENDSON-GATE-SYMMETRY: the claim gate shares the single
|
|
908
|
+
// taskDependenciesSatisfied predicate with the auto-launch filter and
|
|
909
|
+
// the cloud eager P2P push, so a task blocked here is blocked there too.
|
|
910
|
+
const dependenciesSatisfied = (candidate: MeshWorkQueueEntry): boolean =>
|
|
911
|
+
taskDependenciesSatisfied(candidate, depStatus);
|
|
912
|
+
|
|
913
|
+
// Per-candidate node-conflict gate: write tasks require an idle node; read-only
|
|
914
|
+
// tasks bypass the node-busy check so N read-only diagnoses can run on one node
|
|
915
|
+
// at once. Read-only classification is decided solely by isTaskReadonly (the
|
|
916
|
+
// single predicate shared with the cap counters / auto-launch / guardrail).
|
|
917
|
+
const nodeConflictAllows = (candidate: MeshWorkQueueEntry): boolean => {
|
|
918
|
+
if (isTaskReadonly(candidate)) return true;
|
|
919
|
+
return !nodeBusy;
|
|
920
|
+
};
|
|
921
|
+
|
|
922
|
+
// WTDISPATCH-FANOUT: a `convergence` task lands its work onto base (merge →
|
|
923
|
+
// push → cleanup against the real checkout). It must NEVER be claimed by a
|
|
924
|
+
// co-located worktree-clone session — N sibling worktree sessions on one daemon
|
|
925
|
+
// each claiming the same convergence intent is the 4-way push/deploy fan-out the
|
|
926
|
+
// live repro hit. Base-only, fail-closed: when the claiming node is a worktree
|
|
927
|
+
// (nodeIsWorktree), exclude every convergence candidate so it stays pending for
|
|
928
|
+
// the base node to pull.
|
|
929
|
+
const nodeIsWorktree = opts?.nodeIsWorktree === true;
|
|
930
|
+
const convergenceAllows = (candidate: MeshWorkQueueEntry): boolean =>
|
|
931
|
+
candidate.taskMode !== 'convergence' || !nodeIsWorktree;
|
|
932
|
+
|
|
933
|
+
// WTDISPATCH-FANOUT: defensive exact-target gate. The prioritized SQL above
|
|
934
|
+
// already segregates session/node-pinned rows, but a future query change (or a
|
|
935
|
+
// candidate row whose stored target drifted from its column) must never let a
|
|
936
|
+
// sibling worktree session on the same daemon absorb another node's/session's
|
|
937
|
+
// pinned task. When a task carries an explicit target, require an exact match
|
|
938
|
+
// here too — fail-closed.
|
|
939
|
+
// The target id may have been stamped in a different serialization /
|
|
940
|
+
// daemon-id form than the claiming session's nodeId (config-form
|
|
941
|
+
// `daemon_mach_X` vs stamp-form `mach_X`, or the 3-way id/nodeId/node_id
|
|
942
|
+
// node forms). A raw `!==` here permanently strands a node-pinned task as
|
|
943
|
+
// an empty session. Accept the candidate when the target resolves to the
|
|
944
|
+
// same node under ANY equivalent form; keep targetSessionId an exact match.
|
|
945
|
+
const targetMatches = (candidate: MeshWorkQueueEntry): boolean => {
|
|
946
|
+
// Session ids are single-form (unlike node/daemon ids with their 3
|
|
947
|
+
// serialization forms requiring expandDaemonIdForms) — see the
|
|
948
|
+
// sessionIdsEquivalent doc; it is the one canonical exact-match
|
|
949
|
+
// predicate for them.
|
|
950
|
+
if (candidate.targetSessionId && !sessionIdsEquivalent(candidate.targetSessionId, sessionId)) return false;
|
|
951
|
+
if (
|
|
952
|
+
candidate.targetNodeId
|
|
953
|
+
&& !daemonIdsEquivalent(candidate.targetNodeId, nodeId)
|
|
954
|
+
&& !meshNodeIdMatches({ id: candidate.targetNodeId }, nodeId)
|
|
955
|
+
) {
|
|
956
|
+
return false;
|
|
957
|
+
}
|
|
958
|
+
return true;
|
|
959
|
+
};
|
|
960
|
+
|
|
961
|
+
const entry = candidates.find(candidate =>
|
|
962
|
+
nodeSatisfiesRequiredTags(candidate.requiredTags, capabilityTags)
|
|
963
|
+
&& dependenciesSatisfied(candidate)
|
|
964
|
+
&& convergenceAllows(candidate)
|
|
965
|
+
&& targetMatches(candidate)
|
|
966
|
+
&& nodeConflictAllows(candidate));
|
|
967
|
+
if (!entry) return null;
|
|
968
|
+
|
|
969
|
+
const now = new Date().toISOString();
|
|
970
|
+
entry.status = 'assigned';
|
|
971
|
+
entry.assignedNodeId = nodeId;
|
|
972
|
+
entry.assignedSessionId = sessionId;
|
|
973
|
+
if (providerType) entry.assignedProviderType = providerType;
|
|
974
|
+
entry.dispatchTimestamp = now;
|
|
975
|
+
entry.updatedAt = now;
|
|
976
|
+
|
|
977
|
+
this.db.prepare(`
|
|
978
|
+
UPDATE mesh_queue SET
|
|
979
|
+
status = 'assigned', assigned_node_id = ?, assigned_session_id = ?,
|
|
980
|
+
updated_at = ?, payload = ?
|
|
981
|
+
WHERE id = ? AND mesh_id = ?
|
|
982
|
+
`).run(nodeId, sessionId, now, JSON.stringify(entry), entry.id, meshId);
|
|
983
|
+
|
|
984
|
+
this.maybeCheckpointWal();
|
|
985
|
+
return entry;
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
getQueueStatsByStatus(meshId: string): { status: string; count: number }[] {
|
|
990
|
+
this.ensureLegacyQueueMigrated(meshId);
|
|
991
|
+
return this.db.prepare(
|
|
992
|
+
`SELECT status, COUNT(*) as count FROM mesh_queue WHERE mesh_id = ? GROUP BY status`
|
|
993
|
+
).all(meshId) as { status: string; count: number }[];
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
getActiveAssignmentDetails(meshId: string): Array<{ id: string; nodeId?: string; sessionId?: string; message: string }> {
|
|
997
|
+
this.ensureLegacyQueueMigrated(meshId);
|
|
998
|
+
const rows = this.db.prepare(`
|
|
999
|
+
SELECT assigned_node_id, assigned_session_id, payload
|
|
1000
|
+
FROM mesh_queue WHERE mesh_id = ? AND status = 'assigned'
|
|
1001
|
+
`).all(meshId) as Array<{ assigned_node_id: string | null; assigned_session_id: string | null; payload: string }>;
|
|
1002
|
+
return rows.map(r => {
|
|
1003
|
+
let id = '', message = '';
|
|
1004
|
+
try { const e = JSON.parse(r.payload) as MeshWorkQueueEntry; id = e.id; message = e.message; } catch { /* ignore */ }
|
|
1005
|
+
return { id, nodeId: r.assigned_node_id ?? undefined, sessionId: r.assigned_session_id ?? undefined, message };
|
|
1006
|
+
});
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/**
|
|
1010
|
+
* Resolve the `assigned` queue row a completion event belongs to.
|
|
1011
|
+
*
|
|
1012
|
+
* Clock-skew safety (C2): a completion event's `occurredAtIso` carries the
|
|
1013
|
+
* REMOTE WORKER's clock, while `updated_at` carries the COORDINATOR's clock
|
|
1014
|
+
* (set at assignment and re-bumped on every mutation). For a remote node,
|
|
1015
|
+
* coordinator-clock > worker-clock skew used to make an `updated_at <= occurredAt`
|
|
1016
|
+
* filter return nothing, stranding the finished task as `assigned` forever.
|
|
1017
|
+
*
|
|
1018
|
+
* We therefore NEVER filter completion-matching on the mutable `updated_at`:
|
|
1019
|
+
* 1. If `taskId` is given, match the exact `assigned` row by id (no time filter).
|
|
1020
|
+
* 2. Otherwise a session holds at most one `assigned` task — match it without a
|
|
1021
|
+
* time filter. If several exist (shouldn't normally), disambiguate by the
|
|
1022
|
+
* IMMUTABLE `dispatchTimestamp`: latest `dispatchTimestamp <= occurredAt`,
|
|
1023
|
+
* and if skew makes ALL of them later than `occurredAt`, fall back to the
|
|
1024
|
+
* most-recent `dispatchTimestamp` rather than returning null.
|
|
1025
|
+
*/
|
|
1026
|
+
findAssignedBySession(
|
|
1027
|
+
meshId: string,
|
|
1028
|
+
sessionId: string,
|
|
1029
|
+
occurredAtIso?: string,
|
|
1030
|
+
taskId?: string,
|
|
1031
|
+
): MeshWorkQueueEntry | null {
|
|
1032
|
+
this.ensureLegacyQueueMigrated(meshId);
|
|
1033
|
+
|
|
1034
|
+
// WRITE/READ PREDICATE SYMMETRY (COMPLETION-PROPAGATION F1): the claim path writes
|
|
1035
|
+
// assigned_session_id RAW (claimNextTask), and the sibling gates that decide whether a
|
|
1036
|
+
// session already holds work (sessionHasActiveAssignment) and which pending row a
|
|
1037
|
+
// session may claim (targetMatches) compare it through sessionIdsEquivalent — the
|
|
1038
|
+
// canonical single-form predicate that TRIMS both sides. A raw SQL `assigned_session_id
|
|
1039
|
+
// = ?` here is asymmetric with that write/sibling predicate: a completion whose
|
|
1040
|
+
// resolveEventSessionId-reinterpreted sessionId is equivalent-but-not-byte-identical to
|
|
1041
|
+
// the stored column (e.g. a whitespace/serialization skew from a manually-launched
|
|
1042
|
+
// session) silently fetched zero rows and stranded the finished task as `assigned`
|
|
1043
|
+
// forever (the mesh-work-queue :1251 "N assigned row(s) exist" warning is that exact
|
|
1044
|
+
// signature). Fetch every `assigned` row for the mesh and filter session membership in
|
|
1045
|
+
// JS with sessionIdsEquivalent, mirroring the node-id IN(...)+JS-revalidate pattern the
|
|
1046
|
+
// claim SELECT uses (claimNextTask :720-736 / targetMatches :797-811).
|
|
1047
|
+
const allRows = this.db.prepare(
|
|
1048
|
+
`SELECT payload FROM mesh_queue WHERE mesh_id = ? AND status = 'assigned'`
|
|
1049
|
+
).all(meshId) as Array<{ payload: string }>;
|
|
1050
|
+
const sessionEntries = allRows
|
|
1051
|
+
.map(r => { try { return JSON.parse(r.payload) as MeshWorkQueueEntry; } catch { return null; } })
|
|
1052
|
+
.filter((e): e is MeshWorkQueueEntry => e !== null)
|
|
1053
|
+
.filter(e => sessionIdsEquivalent(e.assignedSessionId, sessionId));
|
|
1054
|
+
|
|
1055
|
+
// 1. Exact taskId match — robust against clock skew and stale rows. Scoped to the
|
|
1056
|
+
// session-equivalent set (as the raw `AND assigned_session_id = ? AND id = ?` was),
|
|
1057
|
+
// now via the trimming equivalence predicate.
|
|
1058
|
+
if (taskId) {
|
|
1059
|
+
const byId = sessionEntries.find(e => e.id === taskId);
|
|
1060
|
+
if (byId) return byId;
|
|
1061
|
+
// Fall through to session-based matching if the id didn't line up
|
|
1062
|
+
// (e.g. event carried a stale/foreign taskId).
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
// 2. Session-based match WITHOUT the mutable updated_at filter.
|
|
1066
|
+
const entries = sessionEntries;
|
|
1067
|
+
if (entries.length === 0) return null;
|
|
1068
|
+
if (entries.length === 1) return entries[0];
|
|
1069
|
+
|
|
1070
|
+
// Multiple assigned rows for one session: disambiguate by the immutable
|
|
1071
|
+
// dispatchTimestamp (falling back to updated_at only for legacy rows that
|
|
1072
|
+
// predate dispatchTimestamp). We use these to ORDER, never to FILTER —
|
|
1073
|
+
// so a skewed occurredAt can never drop the live row to null.
|
|
1074
|
+
const orderKey = (e: MeshWorkQueueEntry) => e.dispatchTimestamp ?? e.updatedAt ?? '';
|
|
1075
|
+
const byDispatchDesc = [...entries].sort((a, b) => orderKey(b).localeCompare(orderKey(a)));
|
|
1076
|
+
if (occurredAtIso) {
|
|
1077
|
+
const atOrBefore = byDispatchDesc.find(e => orderKey(e) <= occurredAtIso);
|
|
1078
|
+
if (atOrBefore) return atOrBefore;
|
|
1079
|
+
}
|
|
1080
|
+
// Skew made every dispatch later than occurredAt — fall back to the
|
|
1081
|
+
// most-recently dispatched row rather than stranding the completion.
|
|
1082
|
+
return byDispatchDesc[0];
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
private toRow(entry: MeshWorkQueueEntry): Record<string, unknown> {
|
|
1086
|
+
return {
|
|
1087
|
+
id: entry.id,
|
|
1088
|
+
meshId: entry.meshId,
|
|
1089
|
+
status: entry.status,
|
|
1090
|
+
targetNodeId: entry.targetNodeId ?? null,
|
|
1091
|
+
targetSessionId: entry.targetSessionId ?? null,
|
|
1092
|
+
assignedNodeId: entry.assignedNodeId ?? null,
|
|
1093
|
+
assignedSessionId: entry.assignedSessionId ?? null,
|
|
1094
|
+
createdAt: entry.createdAt,
|
|
1095
|
+
updatedAt: entry.updatedAt,
|
|
1096
|
+
payload: JSON.stringify(entry),
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
// ── Direct Dispatch Tracking ─────────────────────────────────────────────
|
|
1101
|
+
|
|
1102
|
+
insertDirectDispatch(entry: {
|
|
1103
|
+
taskId: string;
|
|
1104
|
+
meshId: string;
|
|
1105
|
+
nodeId?: string;
|
|
1106
|
+
sessionId?: string;
|
|
1107
|
+
providerType?: string;
|
|
1108
|
+
message: string;
|
|
1109
|
+
taskMode?: string;
|
|
1110
|
+
via: string;
|
|
1111
|
+
dispatchedToIdleSession?: boolean;
|
|
1112
|
+
dispatchedAt: string;
|
|
1113
|
+
}): void {
|
|
1114
|
+
const now = new Date().toISOString();
|
|
1115
|
+
this.db.prepare(`
|
|
1116
|
+
INSERT OR REPLACE INTO mesh_direct_dispatches
|
|
1117
|
+
(task_id, mesh_id, node_id, session_id, provider_type, message, task_mode, via,
|
|
1118
|
+
status, dispatched_to_idle_session, dispatched_at, updated_at)
|
|
1119
|
+
VALUES
|
|
1120
|
+
(@taskId, @meshId, @nodeId, @sessionId, @providerType, @message, @taskMode, @via,
|
|
1121
|
+
'dispatched', @dispatchedToIdle, @dispatchedAt, @updatedAt)
|
|
1122
|
+
`).run({
|
|
1123
|
+
taskId: entry.taskId,
|
|
1124
|
+
meshId: entry.meshId,
|
|
1125
|
+
nodeId: entry.nodeId ?? null,
|
|
1126
|
+
sessionId: entry.sessionId ?? null,
|
|
1127
|
+
providerType: entry.providerType ?? null,
|
|
1128
|
+
message: entry.message,
|
|
1129
|
+
taskMode: entry.taskMode ?? null,
|
|
1130
|
+
via: entry.via,
|
|
1131
|
+
dispatchedToIdle: entry.dispatchedToIdleSession ? 1 : 0,
|
|
1132
|
+
dispatchedAt: entry.dispatchedAt,
|
|
1133
|
+
updatedAt: now,
|
|
1134
|
+
});
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
getActiveDirectDispatches(meshId: string): Array<{
|
|
1138
|
+
taskId: string;
|
|
1139
|
+
meshId: string;
|
|
1140
|
+
nodeId: string | null;
|
|
1141
|
+
sessionId: string | null;
|
|
1142
|
+
providerType: string | null;
|
|
1143
|
+
message: string;
|
|
1144
|
+
taskMode: string | null;
|
|
1145
|
+
via: string;
|
|
1146
|
+
status: string;
|
|
1147
|
+
dispatchedToIdleSession: boolean;
|
|
1148
|
+
dispatchedAt: string;
|
|
1149
|
+
updatedAt: string;
|
|
1150
|
+
}> {
|
|
1151
|
+
const rows = this.db.prepare(`
|
|
1152
|
+
SELECT task_id, mesh_id, node_id, session_id, provider_type, message, task_mode, via,
|
|
1153
|
+
status, dispatched_to_idle_session, dispatched_at, updated_at
|
|
1154
|
+
FROM mesh_direct_dispatches
|
|
1155
|
+
WHERE mesh_id = ? AND status NOT IN ('completed', 'failed', 'stale')
|
|
1156
|
+
ORDER BY dispatched_at ASC
|
|
1157
|
+
`).all(meshId) as Array<Record<string, unknown>>;
|
|
1158
|
+
return rows.map(r => ({
|
|
1159
|
+
taskId: r.task_id as string,
|
|
1160
|
+
meshId: r.mesh_id as string,
|
|
1161
|
+
nodeId: r.node_id as string | null,
|
|
1162
|
+
sessionId: r.session_id as string | null,
|
|
1163
|
+
providerType: r.provider_type as string | null,
|
|
1164
|
+
message: r.message as string,
|
|
1165
|
+
taskMode: r.task_mode as string | null,
|
|
1166
|
+
via: r.via as string,
|
|
1167
|
+
status: r.status as string,
|
|
1168
|
+
dispatchedToIdleSession: (r.dispatched_to_idle_session as number) === 1,
|
|
1169
|
+
dispatchedAt: r.dispatched_at as string,
|
|
1170
|
+
updatedAt: r.updated_at as string,
|
|
1171
|
+
}));
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
// CANON-B (dispatch identity): mesh_direct_dispatches is keyed by task_id (PK), but a
|
|
1175
|
+
// single session can host several sequential direct dispatches (re-dispatch / nudge), so
|
|
1176
|
+
// matching a status flip by session_id alone hits EVERY non-terminal row for that session
|
|
1177
|
+
// — flipping a sibling task's row and stranding the one whose event actually fired (the
|
|
1178
|
+
// assigned-stranded watchdog then requeues a task that is really still generating). When
|
|
1179
|
+
// the firing event carries a taskId, target the single PK row; the session_id match is the
|
|
1180
|
+
// legacy fallback only for events that arrive without a taskId.
|
|
1181
|
+
updateDirectDispatchStatus(meshId: string, sessionId: string, status: 'acked' | 'completed' | 'failed' | 'stale', taskId?: string): void {
|
|
1182
|
+
const now = new Date().toISOString();
|
|
1183
|
+
if (taskId) {
|
|
1184
|
+
this.db.prepare(`
|
|
1185
|
+
UPDATE mesh_direct_dispatches
|
|
1186
|
+
SET status = @status, updated_at = @updatedAt
|
|
1187
|
+
WHERE mesh_id = @meshId AND task_id = @taskId
|
|
1188
|
+
AND status NOT IN ('completed', 'failed')
|
|
1189
|
+
`).run({ status, meshId, taskId, updatedAt: now });
|
|
1190
|
+
return;
|
|
1191
|
+
}
|
|
1192
|
+
if (!sessionId) return; // never update rows without a session binding
|
|
1193
|
+
this.db.prepare(`
|
|
1194
|
+
UPDATE mesh_direct_dispatches
|
|
1195
|
+
SET status = @status, updated_at = @updatedAt
|
|
1196
|
+
WHERE mesh_id = @meshId AND session_id = @sessionId
|
|
1197
|
+
AND session_id IS NOT NULL
|
|
1198
|
+
AND status NOT IN ('completed', 'failed')
|
|
1199
|
+
`).run({ status, meshId, sessionId, updatedAt: now });
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
/**
|
|
1203
|
+
* MESH-DISPATCH-MISROUTE (fix 3, consumer residual): resolve the task_id of the SINGLE
|
|
1204
|
+
* non-terminal direct dispatch a session owns. Returns the task_id only when the session
|
|
1205
|
+
* holds exactly ONE active ('dispatched'/'acked') row — the case where a taskId-less
|
|
1206
|
+
* lifecycle event (a legacy/relayed worker whose producer never stamped meshActiveTaskId)
|
|
1207
|
+
* unambiguously belongs to that one dispatch. With zero rows there is nothing to ack; with
|
|
1208
|
+
* two or more (a re-dispatch/nudge sibling) the firing event's owner is ambiguous, so we
|
|
1209
|
+
* return null and the caller MUST NOT fall back to the session_id sweep that would flip a
|
|
1210
|
+
* sibling row ("may flip a sibling dispatch row"). This narrows the legacy fallback to the
|
|
1211
|
+
* only safe case instead of removing the producer-side TASKIDLESS stamp's safety net.
|
|
1212
|
+
*/
|
|
1213
|
+
getSoleActiveDirectDispatchTaskId(meshId: string, sessionId: string): string | null {
|
|
1214
|
+
if (!sessionId) return null;
|
|
1215
|
+
const rows = this.db.prepare(`
|
|
1216
|
+
SELECT task_id FROM mesh_direct_dispatches
|
|
1217
|
+
WHERE mesh_id = ? AND session_id = ?
|
|
1218
|
+
AND status NOT IN ('completed', 'failed', 'stale')
|
|
1219
|
+
`).all(meshId, sessionId) as Array<{ task_id: string }>;
|
|
1220
|
+
if (rows.length !== 1) return null;
|
|
1221
|
+
const taskId = typeof rows[0]?.task_id === 'string' ? rows[0].task_id.trim() : '';
|
|
1222
|
+
return taskId || null;
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
cleanupTerminalDirectDispatches(olderThanMs: number): void {
|
|
1226
|
+
const cutoff = new Date(Date.now() - olderThanMs).toISOString();
|
|
1227
|
+
this.db.prepare(`
|
|
1228
|
+
DELETE FROM mesh_direct_dispatches
|
|
1229
|
+
WHERE status IN ('completed', 'failed', 'stale') AND updated_at < ?
|
|
1230
|
+
`).run(cutoff);
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
deleteDirectDispatches(meshId: string): void {
|
|
1234
|
+
this.db.prepare(`DELETE FROM mesh_direct_dispatches WHERE mesh_id = ?`).run(meshId);
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
/**
|
|
1238
|
+
* Delete specific direct dispatch rows by taskId for a mesh. Used by the staleDirect prune
|
|
1239
|
+
* path to remove orphaned/terminal dispatch records whose node/session is no longer in the
|
|
1240
|
+
* live mesh. Returns the number of rows actually deleted. No-op for an empty taskId list.
|
|
1241
|
+
*/
|
|
1242
|
+
deleteDirectDispatchesByTaskId(meshId: string, taskIds: string[]): number {
|
|
1243
|
+
const ids = (taskIds || []).map(id => typeof id === 'string' ? id.trim() : '').filter(Boolean);
|
|
1244
|
+
if (!ids.length) return 0;
|
|
1245
|
+
const stmt = this.db.prepare(`DELETE FROM mesh_direct_dispatches WHERE mesh_id = ? AND task_id = ?`);
|
|
1246
|
+
let deleted = 0;
|
|
1247
|
+
const run = this.db.transaction((rows: string[]) => {
|
|
1248
|
+
for (const taskId of rows) {
|
|
1249
|
+
deleted += stmt.run(meshId, taskId).changes;
|
|
1250
|
+
}
|
|
1251
|
+
});
|
|
1252
|
+
run(ids);
|
|
1253
|
+
return deleted;
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
markStaleDirectDispatches(meshId: string, olderThanMs: number): void {
|
|
1257
|
+
const cutoff = new Date(Date.now() - olderThanMs).toISOString();
|
|
1258
|
+
const now = new Date().toISOString();
|
|
1259
|
+
this.db.prepare(`
|
|
1260
|
+
UPDATE mesh_direct_dispatches
|
|
1261
|
+
SET status = 'stale', updated_at = ?
|
|
1262
|
+
WHERE mesh_id = ? AND status = 'dispatched' AND dispatched_at < ?
|
|
1263
|
+
`).run(now, meshId, cutoff);
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
// ── Remote Idle Sessions ─────────────────────────────────────────────────
|
|
1267
|
+
|
|
1268
|
+
setRemoteIdleSession(meshId: string, nodeId: string, sessionId: string, providerType: string, expiresAt: number, metadata?: any): void {
|
|
1269
|
+
this.db.prepare(`
|
|
1270
|
+
INSERT OR REPLACE INTO remote_idle_sessions (mesh_id, node_id, session_id, provider_type, expires_at, metadata)
|
|
1271
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
1272
|
+
`).run(meshId, nodeId, sessionId, providerType, expiresAt, metadata ? JSON.stringify(metadata) : null);
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
getRemoteIdleSessions(meshId: string): Array<{ nodeId: string; sessionId: string; providerType: string; expiresAt: number; metadata?: any }> {
|
|
1276
|
+
// MESH-ISOLATION-LEAK: always mesh-scoped. A bare (cross-mesh) read here is what
|
|
1277
|
+
// let mesh B claim mesh A's idle session when both share a nodeId.
|
|
1278
|
+
const rows = this.db.prepare('SELECT node_id, session_id, provider_type, expires_at, metadata FROM remote_idle_sessions WHERE mesh_id = ?').all(meshId) as Array<any>;
|
|
1279
|
+
return rows.map(r => ({
|
|
1280
|
+
nodeId: r.node_id,
|
|
1281
|
+
sessionId: r.session_id,
|
|
1282
|
+
providerType: r.provider_type,
|
|
1283
|
+
expiresAt: r.expires_at,
|
|
1284
|
+
metadata: r.metadata ? JSON.parse(r.metadata) : undefined,
|
|
1285
|
+
}));
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
deleteRemoteIdleSession(meshId: string, nodeId: string, sessionId: string): void {
|
|
1289
|
+
this.db.prepare('DELETE FROM remote_idle_sessions WHERE mesh_id = ? AND node_id = ? AND session_id = ?').run(meshId, nodeId, sessionId);
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
pruneExpiredRemoteIdleSessions(): void {
|
|
1293
|
+
this.db.prepare('DELETE FROM remote_idle_sessions WHERE expires_at <= ?').run(Date.now());
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
// ── Session Delivery Queue ───────────────────────────────────────────────
|
|
1297
|
+
|
|
1298
|
+
insertSessionDelivery(entry: {
|
|
1299
|
+
id: string;
|
|
1300
|
+
meshId: string;
|
|
1301
|
+
nodeId?: string;
|
|
1302
|
+
sessionId?: string;
|
|
1303
|
+
providerType?: string;
|
|
1304
|
+
taskId?: string;
|
|
1305
|
+
kind: string;
|
|
1306
|
+
priority?: number;
|
|
1307
|
+
message: string;
|
|
1308
|
+
status: string;
|
|
1309
|
+
deliverAfter?: string;
|
|
1310
|
+
expiresAt?: string;
|
|
1311
|
+
sourceCoordinatorSessionId?: string;
|
|
1312
|
+
sourceCoordinatorDaemonId?: string;
|
|
1313
|
+
createdAt: string;
|
|
1314
|
+
updatedAt: string;
|
|
1315
|
+
}): void {
|
|
1316
|
+
this.db.prepare(`
|
|
1317
|
+
INSERT OR REPLACE INTO mesh_session_delivery (
|
|
1318
|
+
id, mesh_id, node_id, session_id, provider_type, task_id, kind, priority,
|
|
1319
|
+
message, status, deliver_after, expires_at, attempt_count,
|
|
1320
|
+
source_coordinator_session_id, source_coordinator_daemon_id,
|
|
1321
|
+
last_error, created_at, updated_at
|
|
1322
|
+
) VALUES (
|
|
1323
|
+
@id, @meshId, @nodeId, @sessionId, @providerType, @taskId, @kind, @priority,
|
|
1324
|
+
@message, @status, @deliverAfter, @expiresAt, 0,
|
|
1325
|
+
@sourceCoordinatorSessionId, @sourceCoordinatorDaemonId,
|
|
1326
|
+
NULL, @createdAt, @updatedAt
|
|
1327
|
+
)
|
|
1328
|
+
`).run({
|
|
1329
|
+
id: entry.id,
|
|
1330
|
+
meshId: entry.meshId,
|
|
1331
|
+
nodeId: entry.nodeId ?? null,
|
|
1332
|
+
sessionId: entry.sessionId ?? null,
|
|
1333
|
+
providerType: entry.providerType ?? null,
|
|
1334
|
+
taskId: entry.taskId ?? null,
|
|
1335
|
+
kind: entry.kind,
|
|
1336
|
+
priority: entry.priority ?? 0,
|
|
1337
|
+
message: entry.message,
|
|
1338
|
+
status: entry.status,
|
|
1339
|
+
deliverAfter: entry.deliverAfter ?? null,
|
|
1340
|
+
expiresAt: entry.expiresAt ?? null,
|
|
1341
|
+
sourceCoordinatorSessionId: entry.sourceCoordinatorSessionId ?? null,
|
|
1342
|
+
sourceCoordinatorDaemonId: entry.sourceCoordinatorDaemonId ?? null,
|
|
1343
|
+
createdAt: entry.createdAt,
|
|
1344
|
+
updatedAt: entry.updatedAt,
|
|
1345
|
+
});
|
|
1346
|
+
this.maybeCheckpointWal();
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
updateSessionDeliveryStatus(id: string, status: string, opts?: { lastError?: string; incrementAttempt?: boolean }): void {
|
|
1350
|
+
const now = new Date().toISOString();
|
|
1351
|
+
if (opts?.incrementAttempt) {
|
|
1352
|
+
this.db.prepare(`
|
|
1353
|
+
UPDATE mesh_session_delivery
|
|
1354
|
+
SET status = @status, last_error = @lastError, attempt_count = attempt_count + 1, updated_at = @updatedAt
|
|
1355
|
+
WHERE id = @id
|
|
1356
|
+
`).run({ id, status, lastError: opts?.lastError ?? null, updatedAt: now });
|
|
1357
|
+
} else {
|
|
1358
|
+
this.db.prepare(`
|
|
1359
|
+
UPDATE mesh_session_delivery
|
|
1360
|
+
SET status = @status, last_error = @lastError, updated_at = @updatedAt
|
|
1361
|
+
WHERE id = @id
|
|
1362
|
+
`).run({ id, status, lastError: opts?.lastError ?? null, updatedAt: now });
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
getActiveSessionDeliveries(meshId: string, sessionId?: string): Array<{
|
|
1367
|
+
id: string; meshId: string; nodeId: string | null; sessionId: string | null;
|
|
1368
|
+
providerType: string | null; taskId: string | null; kind: string; priority: number;
|
|
1369
|
+
message: string; status: string; deliverAfter: string | null; expiresAt: string | null;
|
|
1370
|
+
attemptCount: number; sourceCoordinatorSessionId: string | null;
|
|
1371
|
+
sourceCoordinatorDaemonId: string | null; lastError: string | null;
|
|
1372
|
+
createdAt: string; updatedAt: string;
|
|
1373
|
+
}> {
|
|
1374
|
+
const now = new Date().toISOString();
|
|
1375
|
+
const sql = sessionId
|
|
1376
|
+
? `SELECT * FROM mesh_session_delivery WHERE mesh_id = ? AND session_id = ? AND status NOT IN ('delivered','completed','failed','expired','cancelled') AND (expires_at IS NULL OR expires_at > ?) ORDER BY priority DESC, created_at ASC`
|
|
1377
|
+
: `SELECT * FROM mesh_session_delivery WHERE mesh_id = ? AND status NOT IN ('delivered','completed','failed','expired','cancelled') AND (expires_at IS NULL OR expires_at > ?) ORDER BY priority DESC, created_at ASC`;
|
|
1378
|
+
const rows = sessionId
|
|
1379
|
+
? this.db.prepare(sql).all(meshId, sessionId, now) as Array<Record<string, unknown>>
|
|
1380
|
+
: this.db.prepare(sql).all(meshId, now) as Array<Record<string, unknown>>;
|
|
1381
|
+
return rows.map(r => ({
|
|
1382
|
+
id: r.id as string,
|
|
1383
|
+
meshId: r.mesh_id as string,
|
|
1384
|
+
nodeId: r.node_id as string | null,
|
|
1385
|
+
sessionId: r.session_id as string | null,
|
|
1386
|
+
providerType: r.provider_type as string | null,
|
|
1387
|
+
taskId: r.task_id as string | null,
|
|
1388
|
+
kind: r.kind as string,
|
|
1389
|
+
priority: r.priority as number,
|
|
1390
|
+
message: r.message as string,
|
|
1391
|
+
status: r.status as string,
|
|
1392
|
+
deliverAfter: r.deliver_after as string | null,
|
|
1393
|
+
expiresAt: r.expires_at as string | null,
|
|
1394
|
+
attemptCount: r.attempt_count as number,
|
|
1395
|
+
sourceCoordinatorSessionId: r.source_coordinator_session_id as string | null,
|
|
1396
|
+
sourceCoordinatorDaemonId: r.source_coordinator_daemon_id as string | null,
|
|
1397
|
+
lastError: r.last_error as string | null,
|
|
1398
|
+
createdAt: r.created_at as string,
|
|
1399
|
+
updatedAt: r.updated_at as string,
|
|
1400
|
+
}));
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
/**
|
|
1404
|
+
* Bug B watchdog support: true when at least one delivery record for the task has
|
|
1405
|
+
* reached a confirmed-handed-off status (delivered / acked / completed). The
|
|
1406
|
+
* assigned-stranded watchdog uses this to distinguish a dispatch that was never
|
|
1407
|
+
* confirmed (reclaimable) from one that WAS handed to the worker (a genuinely
|
|
1408
|
+
* in-flight or completion-lost task, which is PHASE 4's responsibility, not this
|
|
1409
|
+
* watchdog's). Indexed by (mesh_id, task_id).
|
|
1410
|
+
*/
|
|
1411
|
+
taskHasConfirmedDelivery(meshId: string, taskId: string): boolean {
|
|
1412
|
+
const row = this.db.prepare(`
|
|
1413
|
+
SELECT 1 FROM mesh_session_delivery
|
|
1414
|
+
WHERE mesh_id = ? AND task_id = ? AND status IN ('delivered','acked','completed')
|
|
1415
|
+
LIMIT 1
|
|
1416
|
+
`).get(meshId, taskId) as { 1: number } | undefined;
|
|
1417
|
+
return !!row;
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
expireStaleSessionDeliveries(meshId: string): void {
|
|
1421
|
+
const now = new Date().toISOString();
|
|
1422
|
+
this.db.prepare(`
|
|
1423
|
+
UPDATE mesh_session_delivery
|
|
1424
|
+
SET status = 'expired', updated_at = ?
|
|
1425
|
+
WHERE mesh_id = ? AND expires_at IS NOT NULL AND expires_at <= ?
|
|
1426
|
+
AND status NOT IN ('delivered','completed','failed','expired','cancelled')
|
|
1427
|
+
`).run(now, meshId, now);
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
deleteSessionDeliveries(meshId: string): void {
|
|
1431
|
+
this.db.prepare('DELETE FROM mesh_session_delivery WHERE mesh_id = ?').run(meshId);
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
// ── Completion Conflict Diagnostics ──────────────────────────────────────
|
|
1435
|
+
|
|
1436
|
+
recordCompletionConflict(entry: {
|
|
1437
|
+
id: string;
|
|
1438
|
+
meshId: string;
|
|
1439
|
+
fingerprint: string;
|
|
1440
|
+
conflictingTaskId?: string;
|
|
1441
|
+
conflictingSessionId?: string;
|
|
1442
|
+
originalTaskId?: string;
|
|
1443
|
+
originalSessionId?: string;
|
|
1444
|
+
event: string;
|
|
1445
|
+
createdAt: string;
|
|
1446
|
+
}): void {
|
|
1447
|
+
this.db.prepare(`
|
|
1448
|
+
INSERT OR IGNORE INTO mesh_completion_conflicts
|
|
1449
|
+
(id, mesh_id, fingerprint, conflicting_task_id, conflicting_session_id,
|
|
1450
|
+
original_task_id, original_session_id, event, created_at)
|
|
1451
|
+
VALUES (@id, @meshId, @fingerprint, @conflictingTaskId, @conflictingSessionId,
|
|
1452
|
+
@originalTaskId, @originalSessionId, @event, @createdAt)
|
|
1453
|
+
`).run({
|
|
1454
|
+
id: entry.id,
|
|
1455
|
+
meshId: entry.meshId,
|
|
1456
|
+
fingerprint: entry.fingerprint,
|
|
1457
|
+
conflictingTaskId: entry.conflictingTaskId ?? null,
|
|
1458
|
+
conflictingSessionId: entry.conflictingSessionId ?? null,
|
|
1459
|
+
originalTaskId: entry.originalTaskId ?? null,
|
|
1460
|
+
originalSessionId: entry.originalSessionId ?? null,
|
|
1461
|
+
event: entry.event,
|
|
1462
|
+
createdAt: entry.createdAt,
|
|
1463
|
+
});
|
|
1464
|
+
this.maybeCheckpointWal();
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
getRecentCompletionConflicts(meshId: string, limitMs: number = 60 * 60 * 1000): Array<{
|
|
1468
|
+
id: string; meshId: string; fingerprint: string; conflictingTaskId: string | null;
|
|
1469
|
+
conflictingSessionId: string | null; originalTaskId: string | null;
|
|
1470
|
+
originalSessionId: string | null; event: string; createdAt: string;
|
|
1471
|
+
}> {
|
|
1472
|
+
const cutoff = new Date(Date.now() - limitMs).toISOString();
|
|
1473
|
+
const rows = this.db.prepare(
|
|
1474
|
+
'SELECT * FROM mesh_completion_conflicts WHERE mesh_id = ? AND created_at >= ? ORDER BY created_at DESC LIMIT 50'
|
|
1475
|
+
).all(meshId, cutoff) as Array<Record<string, unknown>>;
|
|
1476
|
+
return rows.map(r => ({
|
|
1477
|
+
id: r.id as string,
|
|
1478
|
+
meshId: r.mesh_id as string,
|
|
1479
|
+
fingerprint: r.fingerprint as string,
|
|
1480
|
+
conflictingTaskId: r.conflicting_task_id as string | null,
|
|
1481
|
+
conflictingSessionId: r.conflicting_session_id as string | null,
|
|
1482
|
+
originalTaskId: r.original_task_id as string | null,
|
|
1483
|
+
originalSessionId: r.original_session_id as string | null,
|
|
1484
|
+
event: r.event as string,
|
|
1485
|
+
createdAt: r.created_at as string,
|
|
1486
|
+
}));
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
/**
|
|
1490
|
+
* Record a mesh tool call and check whether this mesh+tool combination is
|
|
1491
|
+
* being called too rapidly (sliding window rate guard).
|
|
1492
|
+
*
|
|
1493
|
+
* Returns a rate-limit advisory string when the call rate is too high, null otherwise.
|
|
1494
|
+
* windowMs: sliding window size in ms (default 10s)
|
|
1495
|
+
* maxCalls: max allowed calls within the window (default 5)
|
|
1496
|
+
*/
|
|
1497
|
+
recordMeshToolCall(opts: {
|
|
1498
|
+
meshId: string;
|
|
1499
|
+
tool: string;
|
|
1500
|
+
sessionId?: string | null;
|
|
1501
|
+
windowMs?: number;
|
|
1502
|
+
maxCalls?: number;
|
|
1503
|
+
}): { rateLimitExceeded: boolean; callsInWindow: number; advisory: string | null } {
|
|
1504
|
+
const { meshId, tool, sessionId = null } = opts;
|
|
1505
|
+
const windowMs = opts.windowMs ?? 10_000;
|
|
1506
|
+
const maxCalls = opts.maxCalls ?? 5;
|
|
1507
|
+
const now = Date.now();
|
|
1508
|
+
const windowStart = now - windowMs;
|
|
1509
|
+
|
|
1510
|
+
this.db.prepare(
|
|
1511
|
+
'INSERT INTO mesh_tool_call_log (mesh_id, tool, session_id, called_at) VALUES (?, ?, ?, ?)'
|
|
1512
|
+
).run(meshId, tool, sessionId, now);
|
|
1513
|
+
|
|
1514
|
+
const row = this.db.prepare(
|
|
1515
|
+
'SELECT COUNT(*) as cnt FROM mesh_tool_call_log WHERE mesh_id = ? AND tool = ? AND called_at >= ?'
|
|
1516
|
+
).get(meshId, tool, windowStart) as { cnt: number };
|
|
1517
|
+
const callsInWindow = row?.cnt ?? 0;
|
|
1518
|
+
|
|
1519
|
+
// Sweep old entries periodically to keep the table lean (every 200 calls across all tools).
|
|
1520
|
+
if (++this.toolCallLogCounter % 200 === 0) {
|
|
1521
|
+
this.db.prepare(
|
|
1522
|
+
'DELETE FROM mesh_tool_call_log WHERE called_at < ?'
|
|
1523
|
+
).run(now - Math.max(windowMs * 10, 60_000));
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
if (callsInWindow > maxCalls) {
|
|
1527
|
+
const advisory = `Rate limit: ${tool} called ${callsInWindow} times in the last ${windowMs / 1000}s for mesh ${meshId}. `
|
|
1528
|
+
+ `Wait for pendingCoordinatorEvents or an explicit user status request before calling again.`;
|
|
1529
|
+
return { rateLimitExceeded: true, callsInWindow, advisory };
|
|
1530
|
+
}
|
|
1531
|
+
return { rateLimitExceeded: false, callsInWindow, advisory: null };
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
/**
|
|
1535
|
+
* Prune tool call log entries older than the given age in ms.
|
|
1536
|
+
* Exposed for testing.
|
|
1537
|
+
*/
|
|
1538
|
+
pruneToolCallLog(olderThanMs: number): void {
|
|
1539
|
+
this.db.prepare('DELETE FROM mesh_tool_call_log WHERE called_at < ?').run(Date.now() - olderThanMs);
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
// ── G2: Event Ledger ────────────────────────────────────────────────────
|
|
1543
|
+
|
|
1544
|
+
appendLedgerEntry(entry: {
|
|
1545
|
+
id: string;
|
|
1546
|
+
meshId: string;
|
|
1547
|
+
timestamp: string;
|
|
1548
|
+
kind: string;
|
|
1549
|
+
nodeId?: string | null;
|
|
1550
|
+
sessionId?: string | null;
|
|
1551
|
+
providerType?: string | null;
|
|
1552
|
+
payload?: unknown;
|
|
1553
|
+
}): void {
|
|
1554
|
+
this.db.prepare(
|
|
1555
|
+
`INSERT OR IGNORE INTO mesh_event_ledger
|
|
1556
|
+
(id, mesh_id, timestamp, kind, node_id, session_id, provider_type, payload)
|
|
1557
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
|
1558
|
+
).run(
|
|
1559
|
+
entry.id,
|
|
1560
|
+
entry.meshId,
|
|
1561
|
+
entry.timestamp,
|
|
1562
|
+
entry.kind,
|
|
1563
|
+
entry.nodeId ?? null,
|
|
1564
|
+
entry.sessionId ?? null,
|
|
1565
|
+
entry.providerType ?? null,
|
|
1566
|
+
JSON.stringify(entry.payload ?? {}),
|
|
1567
|
+
);
|
|
1568
|
+
this.maybeCheckpointWal();
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
readLedgerEntries(meshId: string, opts?: {
|
|
1572
|
+
tail?: number;
|
|
1573
|
+
since?: string;
|
|
1574
|
+
kind?: string;
|
|
1575
|
+
limit?: number;
|
|
1576
|
+
}): Array<{ id: string; meshId: string; timestamp: string; kind: string; nodeId: string | null; sessionId: string | null; providerType: string | null; payload: unknown }> {
|
|
1577
|
+
const limit = opts?.tail ?? opts?.limit ?? 200;
|
|
1578
|
+
let query: string;
|
|
1579
|
+
const params: unknown[] = [meshId];
|
|
1580
|
+
if (opts?.kind && opts?.since) {
|
|
1581
|
+
query = `SELECT * FROM mesh_event_ledger WHERE mesh_id = ? AND kind = ? AND timestamp >= ? ORDER BY timestamp DESC LIMIT ?`;
|
|
1582
|
+
params.push(opts.kind, opts.since, limit);
|
|
1583
|
+
} else if (opts?.kind) {
|
|
1584
|
+
query = `SELECT * FROM mesh_event_ledger WHERE mesh_id = ? AND kind = ? ORDER BY timestamp DESC LIMIT ?`;
|
|
1585
|
+
params.push(opts.kind, limit);
|
|
1586
|
+
} else if (opts?.since) {
|
|
1587
|
+
query = `SELECT * FROM mesh_event_ledger WHERE mesh_id = ? AND timestamp >= ? ORDER BY timestamp DESC LIMIT ?`;
|
|
1588
|
+
params.push(opts.since, limit);
|
|
1589
|
+
} else {
|
|
1590
|
+
query = `SELECT * FROM mesh_event_ledger WHERE mesh_id = ? ORDER BY timestamp DESC LIMIT ?`;
|
|
1591
|
+
params.push(limit);
|
|
1592
|
+
}
|
|
1593
|
+
const rows = this.db.prepare(query).all(...params) as Array<Record<string, unknown>>;
|
|
1594
|
+
return rows.map(r => ({
|
|
1595
|
+
id: r.id as string,
|
|
1596
|
+
meshId: r.mesh_id as string,
|
|
1597
|
+
timestamp: r.timestamp as string,
|
|
1598
|
+
kind: r.kind as string,
|
|
1599
|
+
nodeId: r.node_id as string | null,
|
|
1600
|
+
sessionId: r.session_id as string | null,
|
|
1601
|
+
providerType: r.provider_type as string | null,
|
|
1602
|
+
payload: (() => { try { return JSON.parse(r.payload as string); } catch { return {}; } })(),
|
|
1603
|
+
}));
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
/**
|
|
1607
|
+
* G2 read cutover: read ledger entries in append order (oldest first),
|
|
1608
|
+
* matching legacy JSONL file-order semantics. Ties on the same timestamp
|
|
1609
|
+
* are broken by rowid (insertion order), preserving the positional
|
|
1610
|
+
* guarantee that mesh-events relies on for same-millisecond entries.
|
|
1611
|
+
*/
|
|
1612
|
+
readLedgerEntriesOrdered(meshId: string, opts?: {
|
|
1613
|
+
since?: string;
|
|
1614
|
+
kinds?: string[];
|
|
1615
|
+
tail?: number;
|
|
1616
|
+
}): Array<{ id: string; meshId: string; timestamp: string; kind: string; nodeId: string | null; sessionId: string | null; providerType: string | null; payload: unknown }> {
|
|
1617
|
+
const params: unknown[] = [meshId];
|
|
1618
|
+
let whereClause = 'mesh_id = ?';
|
|
1619
|
+
if (opts?.since) {
|
|
1620
|
+
whereClause += ' AND timestamp >= ?';
|
|
1621
|
+
params.push(opts.since);
|
|
1622
|
+
}
|
|
1623
|
+
const kinds = Array.isArray(opts?.kinds) ? opts.kinds.filter(k => typeof k === 'string' && k.trim()) : [];
|
|
1624
|
+
if (kinds.length > 0) {
|
|
1625
|
+
whereClause += ` AND kind IN (${kinds.map(() => '?').join(', ')})`;
|
|
1626
|
+
params.push(...kinds);
|
|
1627
|
+
}
|
|
1628
|
+
let query: string;
|
|
1629
|
+
if (opts?.tail && opts.tail > 0) {
|
|
1630
|
+
// Tail: newest N in append order — inner DESC limit, outer re-sort ASC.
|
|
1631
|
+
query = `SELECT * FROM (
|
|
1632
|
+
SELECT rowid AS rid, * FROM mesh_event_ledger WHERE ${whereClause}
|
|
1633
|
+
ORDER BY timestamp DESC, rowid DESC LIMIT ?
|
|
1634
|
+
) ORDER BY timestamp ASC, rid ASC`;
|
|
1635
|
+
params.push(Math.floor(opts.tail));
|
|
1636
|
+
} else {
|
|
1637
|
+
query = `SELECT rowid AS rid, * FROM mesh_event_ledger WHERE ${whereClause} ORDER BY timestamp ASC, rowid ASC`;
|
|
1638
|
+
}
|
|
1639
|
+
const rows = this.db.prepare(query).all(...params) as Array<Record<string, unknown>>;
|
|
1640
|
+
return rows.map(r => ({
|
|
1641
|
+
id: r.id as string,
|
|
1642
|
+
meshId: r.mesh_id as string,
|
|
1643
|
+
timestamp: r.timestamp as string,
|
|
1644
|
+
kind: r.kind as string,
|
|
1645
|
+
nodeId: r.node_id as string | null,
|
|
1646
|
+
sessionId: r.session_id as string | null,
|
|
1647
|
+
providerType: r.provider_type as string | null,
|
|
1648
|
+
payload: (() => { try { return JSON.parse(r.payload as string); } catch { return {}; } })(),
|
|
1649
|
+
}));
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
/** Remove all ledger entries for a mesh (mesh deletion / test cleanup). */
|
|
1653
|
+
clearLedgerForMesh(meshId: string): number {
|
|
1654
|
+
return this.db.prepare('DELETE FROM mesh_event_ledger WHERE mesh_id = ?').run(meshId).changes;
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
/** G2: remove entries moved to the JSONL archive so the SQLite runtime set mirrors the active ledger. */
|
|
1658
|
+
deleteLedgerEntries(meshId: string, ids: string[]): number {
|
|
1659
|
+
if (!ids.length) return 0;
|
|
1660
|
+
let deleted = 0;
|
|
1661
|
+
const stmt = this.db.prepare('DELETE FROM mesh_event_ledger WHERE mesh_id = ? AND id = ?');
|
|
1662
|
+
this.db.transaction(() => {
|
|
1663
|
+
for (const id of ids) {
|
|
1664
|
+
deleted += stmt.run(meshId, id).changes;
|
|
1665
|
+
}
|
|
1666
|
+
})();
|
|
1667
|
+
return deleted;
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
hasLedgerEntry(meshId: string, id: string): boolean {
|
|
1671
|
+
const row = this.db.prepare(
|
|
1672
|
+
'SELECT 1 FROM mesh_event_ledger WHERE mesh_id = ? AND id = ? LIMIT 1'
|
|
1673
|
+
).get(meshId, id);
|
|
1674
|
+
return row !== undefined;
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
ledgerEntryCount(meshId: string): number {
|
|
1678
|
+
const row = this.db.prepare(
|
|
1679
|
+
'SELECT COUNT(*) as cnt FROM mesh_event_ledger WHERE mesh_id = ?'
|
|
1680
|
+
).get(meshId) as { cnt: number } | undefined;
|
|
1681
|
+
return row?.cnt ?? 0;
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
importLedgerEntries(entries: Array<{
|
|
1685
|
+
id: string; meshId: string; timestamp: string; kind: string;
|
|
1686
|
+
nodeId?: string | null; sessionId?: string | null; providerType?: string | null; payload?: unknown;
|
|
1687
|
+
}>): number {
|
|
1688
|
+
let imported = 0;
|
|
1689
|
+
const stmt = this.db.prepare(
|
|
1690
|
+
`INSERT OR IGNORE INTO mesh_event_ledger
|
|
1691
|
+
(id, mesh_id, timestamp, kind, node_id, session_id, provider_type, payload)
|
|
1692
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
|
1693
|
+
);
|
|
1694
|
+
this.db.transaction(() => {
|
|
1695
|
+
for (const e of entries) {
|
|
1696
|
+
const result = stmt.run(
|
|
1697
|
+
e.id, e.meshId, e.timestamp, e.kind,
|
|
1698
|
+
e.nodeId ?? null, e.sessionId ?? null, e.providerType ?? null,
|
|
1699
|
+
JSON.stringify(e.payload ?? {}),
|
|
1700
|
+
);
|
|
1701
|
+
if (result.changes > 0) imported++;
|
|
1702
|
+
}
|
|
1703
|
+
})();
|
|
1704
|
+
return imported;
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
/**
|
|
1708
|
+
* G4: Read a bounded, cursor-addressable ledger slice directly from the SQLite
|
|
1709
|
+
* mesh_event_ledger table. This is the P2P reconcile read path; JSONL files are
|
|
1710
|
+
* retained as export/import/debug/legacy artifacts only.
|
|
1711
|
+
*
|
|
1712
|
+
* The return shape is structurally compatible with MeshLedgerSlice so callers
|
|
1713
|
+
* in mesh-tools.ts can pass it directly to buildMeshLedgerReplicaEvidence.
|
|
1714
|
+
*/
|
|
1715
|
+
readLedgerSlice(meshId: string, opts?: {
|
|
1716
|
+
afterId?: string;
|
|
1717
|
+
since?: string;
|
|
1718
|
+
kind?: string;
|
|
1719
|
+
limit?: number;
|
|
1720
|
+
}): {
|
|
1721
|
+
protocol: 'adhdev.mesh.ledger.slice.v1';
|
|
1722
|
+
meshId: string;
|
|
1723
|
+
entries: Array<{ id: string; meshId: string; timestamp: string; kind: string; nodeId: string | null; sessionId: string | null; providerType: string | null; payload: unknown }>;
|
|
1724
|
+
cursor: { afterId: string | null; nextAfterId: string | null; limit: number; hasMore: boolean };
|
|
1725
|
+
sourceOfTruth: { kind: 'local_sqlite'; table: 'mesh_event_ledger'; bounded: true; maxLimit: number };
|
|
1726
|
+
} {
|
|
1727
|
+
// Protocol maximum of 500, default 100 — mirrors mesh-ledger.ts constants.
|
|
1728
|
+
const MAX_LIMIT = 500;
|
|
1729
|
+
const DEFAULT_LIMIT = 100;
|
|
1730
|
+
const limit = (typeof opts?.limit === 'number' && Number.isFinite(opts.limit))
|
|
1731
|
+
? Math.max(1, Math.min(MAX_LIMIT, Math.floor(opts.limit)))
|
|
1732
|
+
: DEFAULT_LIMIT;
|
|
1733
|
+
|
|
1734
|
+
const afterId = typeof opts?.afterId === 'string' && opts.afterId.trim() ? opts.afterId.trim() : null;
|
|
1735
|
+
|
|
1736
|
+
// Build query: fetch limit+1 rows so we can detect hasMore without a COUNT(*).
|
|
1737
|
+
const params: unknown[] = [meshId];
|
|
1738
|
+
let whereClause = 'mesh_id = ?';
|
|
1739
|
+
|
|
1740
|
+
if (opts?.kind) {
|
|
1741
|
+
whereClause += ' AND kind = ?';
|
|
1742
|
+
params.push(opts.kind);
|
|
1743
|
+
}
|
|
1744
|
+
if (opts?.since) {
|
|
1745
|
+
whereClause += ' AND timestamp >= ?';
|
|
1746
|
+
params.push(opts.since);
|
|
1747
|
+
}
|
|
1748
|
+
if (afterId) {
|
|
1749
|
+
// afterId: return entries with timestamp strictly after the referenced entry's timestamp,
|
|
1750
|
+
// or with the same timestamp but id > afterId (stable pagination).
|
|
1751
|
+
whereClause += ` AND (timestamp > (SELECT timestamp FROM mesh_event_ledger WHERE id = ? AND mesh_id = ?) OR (timestamp = (SELECT timestamp FROM mesh_event_ledger WHERE id = ? AND mesh_id = ?) AND id > ?))`;
|
|
1752
|
+
params.push(afterId, meshId, afterId, meshId, afterId);
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1755
|
+
// Fetch limit+1 to detect hasMore
|
|
1756
|
+
const query = `SELECT * FROM mesh_event_ledger WHERE ${whereClause} ORDER BY timestamp ASC, id ASC LIMIT ?`;
|
|
1757
|
+
params.push(limit + 1);
|
|
1758
|
+
|
|
1759
|
+
const rows = this.db.prepare(query).all(...params) as Array<Record<string, unknown>>;
|
|
1760
|
+
const hasMore = rows.length > limit;
|
|
1761
|
+
const bounded = hasMore ? rows.slice(0, limit) : rows;
|
|
1762
|
+
|
|
1763
|
+
const entries = bounded.map(r => ({
|
|
1764
|
+
id: r.id as string,
|
|
1765
|
+
meshId: r.mesh_id as string,
|
|
1766
|
+
timestamp: r.timestamp as string,
|
|
1767
|
+
kind: r.kind as string,
|
|
1768
|
+
nodeId: r.node_id as string | null,
|
|
1769
|
+
sessionId: r.session_id as string | null,
|
|
1770
|
+
providerType: r.provider_type as string | null,
|
|
1771
|
+
payload: (() => { try { return JSON.parse(r.payload as string); } catch { return {}; } })(),
|
|
1772
|
+
}));
|
|
1773
|
+
|
|
1774
|
+
return {
|
|
1775
|
+
protocol: 'adhdev.mesh.ledger.slice.v1',
|
|
1776
|
+
meshId,
|
|
1777
|
+
entries,
|
|
1778
|
+
cursor: {
|
|
1779
|
+
afterId,
|
|
1780
|
+
nextAfterId: entries.length ? entries[entries.length - 1].id : afterId,
|
|
1781
|
+
limit,
|
|
1782
|
+
hasMore,
|
|
1783
|
+
},
|
|
1784
|
+
sourceOfTruth: {
|
|
1785
|
+
kind: 'local_sqlite',
|
|
1786
|
+
table: 'mesh_event_ledger',
|
|
1787
|
+
bounded: true,
|
|
1788
|
+
maxLimit: MAX_LIMIT,
|
|
1789
|
+
},
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
// ── G3: Pending Coordinator Events ──────────────────────────────────────
|
|
1794
|
+
|
|
1795
|
+
insertPendingEvent(event: {
|
|
1796
|
+
id: string;
|
|
1797
|
+
meshId: string;
|
|
1798
|
+
coordinatorDaemonId?: string | null;
|
|
1799
|
+
event: string;
|
|
1800
|
+
payload?: unknown;
|
|
1801
|
+
fingerprint?: string | null;
|
|
1802
|
+
queuedAt: number;
|
|
1803
|
+
// v2 envelope columns (B2a) — all optional so v1 callers/rows are unaffected.
|
|
1804
|
+
// dispatchedBy / intendedFor are pre-serialized CoordinatorIdentity JSON.
|
|
1805
|
+
protocolVersion?: string | null;
|
|
1806
|
+
eventId?: string | null;
|
|
1807
|
+
scope?: string | null;
|
|
1808
|
+
dispatchedBy?: string | null;
|
|
1809
|
+
intendedFor?: string | null;
|
|
1810
|
+
}): boolean {
|
|
1811
|
+
const result = this.db.prepare(
|
|
1812
|
+
`INSERT OR IGNORE INTO mesh_pending_events
|
|
1813
|
+
(id, mesh_id, coordinator_daemon_id, event, payload, fingerprint, queued_at,
|
|
1814
|
+
protocol_version, event_id, scope, dispatched_by, intended_for)
|
|
1815
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
1816
|
+
).run(
|
|
1817
|
+
event.id,
|
|
1818
|
+
event.meshId,
|
|
1819
|
+
event.coordinatorDaemonId ?? null,
|
|
1820
|
+
event.event,
|
|
1821
|
+
JSON.stringify(event.payload ?? {}),
|
|
1822
|
+
event.fingerprint ?? null,
|
|
1823
|
+
event.queuedAt,
|
|
1824
|
+
event.protocolVersion ?? null,
|
|
1825
|
+
event.eventId ?? null,
|
|
1826
|
+
event.scope ?? null,
|
|
1827
|
+
event.dispatchedBy ?? null,
|
|
1828
|
+
event.intendedFor ?? null,
|
|
1829
|
+
);
|
|
1830
|
+
this.maybeCheckpointWal();
|
|
1831
|
+
return result.changes > 0;
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
/**
|
|
1835
|
+
* Drain undrained pending events for a mesh, atomically marking them drained.
|
|
1836
|
+
* When `opts.onlyEvents` is supplied, ONLY rows whose `event` is in that set are
|
|
1837
|
+
* drained — the rest stay queued (drained=0) for a later drain. This is how the
|
|
1838
|
+
* reconcile loop force-drains terminal/force-inject events into a *generating*
|
|
1839
|
+
* coordinator while leaving non-force progress events for the coordinator's next
|
|
1840
|
+
* idle transition. Filtering happens inside the same transaction as the
|
|
1841
|
+
* drained=1 marking, so force-drain + a concurrent full drain can never both
|
|
1842
|
+
* consume the same row.
|
|
1843
|
+
*/
|
|
1844
|
+
drainPendingEvents(
|
|
1845
|
+
meshId: string,
|
|
1846
|
+
coordinatorDaemonId?: string | null | ReadonlyArray<string>,
|
|
1847
|
+
opts?: { onlyEvents?: ReadonlySet<string> },
|
|
1848
|
+
): Array<{ id: string; event: string; payload: unknown }> {
|
|
1849
|
+
return this.transaction(() => {
|
|
1850
|
+
const onlyEvents = opts?.onlyEvents;
|
|
1851
|
+
// An explicit-but-empty filter means "drain nothing" (no event name can match).
|
|
1852
|
+
if (onlyEvents && onlyEvents.size === 0) return [];
|
|
1853
|
+
const eventList = onlyEvents ? [...onlyEvents] : [];
|
|
1854
|
+
// A coordinator daemon can answer to more than one id form: its canonical
|
|
1855
|
+
// status id (e.g. `standalone_<machineId>` / `daemon_<machineId>`, which the
|
|
1856
|
+
// MCP layer stamps via ctx.localDaemonId) AND the bare machineId (stamped by
|
|
1857
|
+
// the local queue-assignment path). Accept ANY of them so a unicast event
|
|
1858
|
+
// stamped with either id is drained here. Unscoped (NULL) rows always match.
|
|
1859
|
+
const daemonIds = (Array.isArray(coordinatorDaemonId)
|
|
1860
|
+
? coordinatorDaemonId
|
|
1861
|
+
: coordinatorDaemonId ? [coordinatorDaemonId] : [])
|
|
1862
|
+
.filter((id): id is string => typeof id === 'string' && id.length > 0);
|
|
1863
|
+
// Filter by event name IN-SQL when onlyEvents is set so the LIMIT applies to
|
|
1864
|
+
// matching rows — a long run of non-force events ahead in the queue must not
|
|
1865
|
+
// crowd a force event out of the 100-row window.
|
|
1866
|
+
const clauses = ['mesh_id = ?', 'drained = 0'];
|
|
1867
|
+
const params: unknown[] = [meshId];
|
|
1868
|
+
if (daemonIds.length > 0) {
|
|
1869
|
+
clauses.push(`(coordinator_daemon_id IS NULL OR coordinator_daemon_id IN (${daemonIds.map(() => '?').join(',')}))`);
|
|
1870
|
+
params.push(...daemonIds);
|
|
1871
|
+
}
|
|
1872
|
+
if (eventList.length > 0) {
|
|
1873
|
+
clauses.push(`event IN (${eventList.map(() => '?').join(',')})`);
|
|
1874
|
+
params.push(...eventList);
|
|
1875
|
+
}
|
|
1876
|
+
const rows = this.db.prepare(
|
|
1877
|
+
`SELECT id, event, payload FROM mesh_pending_events WHERE ${clauses.join(' AND ')} ORDER BY queued_at ASC LIMIT 100`
|
|
1878
|
+
).all(...params) as Array<{ id: string; event: string; payload: string }>;
|
|
1879
|
+
if (rows.length === 0) return [];
|
|
1880
|
+
const ids = rows.map(r => r.id);
|
|
1881
|
+
const now = Date.now();
|
|
1882
|
+
this.db.prepare(
|
|
1883
|
+
`UPDATE mesh_pending_events SET drained = 1, drained_at = ? WHERE id IN (${ids.map(() => '?').join(',')})`
|
|
1884
|
+
).run(now, ...ids);
|
|
1885
|
+
return rows.map(r => ({
|
|
1886
|
+
id: r.id,
|
|
1887
|
+
event: r.event,
|
|
1888
|
+
payload: (() => { try { return JSON.parse(r.payload); } catch { return {}; } })(),
|
|
1889
|
+
}));
|
|
1890
|
+
});
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
/** Non-destructive peek — returns undrained events without marking them drained. */
|
|
1894
|
+
peekPendingEvents(meshId: string, coordinatorDaemonId?: string | null | ReadonlyArray<string>): Array<{ id: string; event: string; payload: unknown }> {
|
|
1895
|
+
const daemonIds = (Array.isArray(coordinatorDaemonId)
|
|
1896
|
+
? coordinatorDaemonId
|
|
1897
|
+
: coordinatorDaemonId ? [coordinatorDaemonId] : [])
|
|
1898
|
+
.filter((id): id is string => typeof id === 'string' && id.length > 0);
|
|
1899
|
+
const whereClause = daemonIds.length > 0
|
|
1900
|
+
? `WHERE mesh_id = ? AND drained = 0 AND (coordinator_daemon_id IS NULL OR coordinator_daemon_id IN (${daemonIds.map(() => '?').join(',')}))`
|
|
1901
|
+
: `WHERE mesh_id = ? AND drained = 0`;
|
|
1902
|
+
const params: unknown[] = daemonIds.length > 0 ? [meshId, ...daemonIds] : [meshId];
|
|
1903
|
+
const rows = this.db.prepare(
|
|
1904
|
+
`SELECT id, event, payload FROM mesh_pending_events ${whereClause} ORDER BY queued_at ASC LIMIT 100`
|
|
1905
|
+
).all(...params) as Array<{ id: string; event: string; payload: string }>;
|
|
1906
|
+
return rows.map(r => ({
|
|
1907
|
+
id: r.id,
|
|
1908
|
+
event: r.event,
|
|
1909
|
+
payload: (() => { try { return JSON.parse(r.payload); } catch { return {}; } })(),
|
|
1910
|
+
}));
|
|
1911
|
+
}
|
|
1912
|
+
|
|
1913
|
+
hasPendingEventFingerprint(meshId: string, fingerprint: string): boolean {
|
|
1914
|
+
const row = this.db.prepare(
|
|
1915
|
+
'SELECT 1 FROM mesh_pending_events WHERE mesh_id = ? AND fingerprint = ? AND drained = 0 LIMIT 1'
|
|
1916
|
+
).get(meshId, fingerprint);
|
|
1917
|
+
return row !== undefined;
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
// ── M3: Mission Records ─────────────────────────────────────────────────
|
|
1921
|
+
|
|
1922
|
+
upsertMission(mission: {
|
|
1923
|
+
id: string;
|
|
1924
|
+
meshId: string;
|
|
1925
|
+
title: string;
|
|
1926
|
+
goal?: string;
|
|
1927
|
+
status?: string;
|
|
1928
|
+
source?: string;
|
|
1929
|
+
}): void {
|
|
1930
|
+
const now = new Date().toISOString();
|
|
1931
|
+
// `source` is a write-once provenance tag: on conflict we only overwrite it
|
|
1932
|
+
// with a non-null incoming value (COALESCE(excluded, existing)), so a later
|
|
1933
|
+
// status/goal upsert that omits source never clears a previously-stamped
|
|
1934
|
+
// 'magi'/'coordinator' tag.
|
|
1935
|
+
this.db.prepare(
|
|
1936
|
+
`INSERT INTO mesh_missions (id, mesh_id, title, goal, status, source, created_at, updated_at)
|
|
1937
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1938
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
1939
|
+
title = excluded.title,
|
|
1940
|
+
goal = excluded.goal,
|
|
1941
|
+
status = excluded.status,
|
|
1942
|
+
source = COALESCE(excluded.source, mesh_missions.source),
|
|
1943
|
+
updated_at = excluded.updated_at`
|
|
1944
|
+
).run(
|
|
1945
|
+
mission.id,
|
|
1946
|
+
mission.meshId,
|
|
1947
|
+
mission.title,
|
|
1948
|
+
mission.goal ?? '',
|
|
1949
|
+
mission.status ?? 'active',
|
|
1950
|
+
mission.source ?? null,
|
|
1951
|
+
now,
|
|
1952
|
+
now,
|
|
1953
|
+
);
|
|
1954
|
+
this.maybeCheckpointWal();
|
|
1955
|
+
}
|
|
1956
|
+
|
|
1957
|
+
getMission(meshId: string, missionId: string): { id: string; meshId: string; title: string; goal: string; status: string; source?: string; createdAt: string; updatedAt: string } | null {
|
|
1958
|
+
const row = this.db.prepare(
|
|
1959
|
+
'SELECT * FROM mesh_missions WHERE mesh_id = ? AND id = ?'
|
|
1960
|
+
).get(meshId, missionId) as Record<string, string> | undefined;
|
|
1961
|
+
if (!row) return null;
|
|
1962
|
+
return { id: row.id, meshId: row.mesh_id, title: row.title, goal: row.goal, status: row.status, source: row.source ?? undefined, createdAt: row.created_at, updatedAt: row.updated_at };
|
|
1963
|
+
}
|
|
1964
|
+
|
|
1965
|
+
getMissions(meshId: string, statuses?: string[]): Array<{ id: string; meshId: string; title: string; goal: string; status: string; source?: string; createdAt: string; updatedAt: string }> {
|
|
1966
|
+
let rows: Array<Record<string, string>>;
|
|
1967
|
+
if (statuses?.length) {
|
|
1968
|
+
const placeholders = statuses.map(() => '?').join(', ');
|
|
1969
|
+
rows = this.db.prepare(
|
|
1970
|
+
`SELECT * FROM mesh_missions WHERE mesh_id = ? AND status IN (${placeholders}) ORDER BY updated_at DESC`
|
|
1971
|
+
).all(meshId, ...statuses) as Array<Record<string, string>>;
|
|
1972
|
+
} else {
|
|
1973
|
+
rows = this.db.prepare(
|
|
1974
|
+
'SELECT * FROM mesh_missions WHERE mesh_id = ? ORDER BY updated_at DESC'
|
|
1975
|
+
).all(meshId) as Array<Record<string, string>>;
|
|
1976
|
+
}
|
|
1977
|
+
return rows.map(row => ({ id: row.id, meshId: row.mesh_id, title: row.title, goal: row.goal, status: row.status, source: row.source ?? undefined, createdAt: row.created_at, updatedAt: row.updated_at }));
|
|
1978
|
+
}
|
|
1979
|
+
|
|
1980
|
+
/** Remove all missions for a mesh — mesh deletion / test cleanup. */
|
|
1981
|
+
clearMissionsForMesh(meshId: string): number {
|
|
1982
|
+
return this.db.prepare('DELETE FROM mesh_missions WHERE mesh_id = ?').run(meshId).changes;
|
|
1983
|
+
}
|
|
1984
|
+
|
|
1985
|
+
/** Remove all pending-event rows (drained included) for a mesh — mesh deletion / test cleanup. */
|
|
1986
|
+
clearPendingEventsForMesh(meshId: string): number {
|
|
1987
|
+
return this.db.prepare('DELETE FROM mesh_pending_events WHERE mesh_id = ?').run(meshId).changes;
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
pendingEventCount(meshId: string): number {
|
|
1991
|
+
const row = this.db.prepare(
|
|
1992
|
+
'SELECT COUNT(*) as cnt FROM mesh_pending_events WHERE mesh_id = ? AND drained = 0'
|
|
1993
|
+
).get(meshId) as { cnt: number } | undefined;
|
|
1994
|
+
return row?.cnt ?? 0;
|
|
1995
|
+
}
|
|
1996
|
+
|
|
1997
|
+
/**
|
|
1998
|
+
* Mark specific pending-event rows drained by id (ack). Used by the
|
|
1999
|
+
* unresolved-delegate durable-forward outbox: an event is peeked (not drained)
|
|
2000
|
+
* while its push to the coordinator is unconfirmed, then marked drained ONLY
|
|
2001
|
+
* after the push is acked. A failed push leaves the row undrained so the next
|
|
2002
|
+
* reconcile tick retries it. Returns the number of rows newly marked drained.
|
|
2003
|
+
*/
|
|
2004
|
+
markPendingEventsDrainedById(ids: ReadonlyArray<string>): number {
|
|
2005
|
+
const idList = ids.filter((id): id is string => typeof id === 'string' && id.length > 0);
|
|
2006
|
+
if (idList.length === 0) return 0;
|
|
2007
|
+
const now = Date.now();
|
|
2008
|
+
return this.db.prepare(
|
|
2009
|
+
`UPDATE mesh_pending_events SET drained = 1, drained_at = ? WHERE drained = 0 AND id IN (${idList.map(() => '?').join(',')})`
|
|
2010
|
+
).run(now, ...idList).changes;
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
/**
|
|
2014
|
+
* Hard-delete pending-event rows by id (including the dedup fingerprint history).
|
|
2015
|
+
* Used to expire an unresolved-delegate outbox entry that has exhausted its retry
|
|
2016
|
+
* budget — fully removing it frees the fingerprint so a genuinely new completion
|
|
2017
|
+
* for the same task could be re-queued later. Returns the number of rows deleted.
|
|
2018
|
+
*/
|
|
2019
|
+
deletePendingEventsById(ids: ReadonlyArray<string>): number {
|
|
2020
|
+
const idList = ids.filter((id): id is string => typeof id === 'string' && id.length > 0);
|
|
2021
|
+
if (idList.length === 0) return 0;
|
|
2022
|
+
return this.db.prepare(
|
|
2023
|
+
`DELETE FROM mesh_pending_events WHERE id IN (${idList.map(() => '?').join(',')})`
|
|
2024
|
+
).run(...idList).changes;
|
|
2025
|
+
}
|
|
2026
|
+
}
|