@adhdev/daemon-core 0.9.82-rc.43 → 0.9.82-rc.430
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/boot/daemon-lifecycle.d.ts +9 -0
- package/dist/boot/process-hardening.d.ts +50 -0
- package/dist/build-info.d.ts +37 -0
- package/dist/chat/source-machine.d.ts +166 -0
- package/dist/chat/source-resolver.d.ts +104 -0
- package/dist/chat/subscription-updates.d.ts +1 -0
- package/dist/cli-adapter-types.d.ts +68 -2
- package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
- package/dist/cli-adapters/cli-state-engine.d.ts +200 -0
- package/dist/cli-adapters/provider-cli-adapter.d.ts +126 -64
- package/dist/cli-adapters/provider-cli-parse.d.ts +5 -0
- package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
- package/dist/cli-adapters/provider-cli-shared.d.ts +74 -0
- package/dist/cli-adapters/pty-write-chunking.d.ts +34 -0
- package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
- package/dist/cli-adapters/resolve-executable.d.ts +69 -0
- package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
- package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
- package/dist/cli-adapters/terminal-screen.d.ts +4 -11
- package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
- package/dist/commands/chat-commands-read.d.ts +7 -0
- package/dist/commands/chat-commands-scope.d.ts +39 -0
- package/dist/commands/chat-commands-shared.d.ts +33 -0
- package/dist/commands/chat-commands-write.d.ts +14 -0
- package/dist/commands/chat-commands.d.ts +10 -23
- package/dist/commands/cli-manager.d.ts +15 -1
- package/dist/commands/handler.d.ts +125 -0
- package/dist/commands/high-family/index.d.ts +3 -0
- package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
- package/dist/commands/high-family/mesh-events.d.ts +2 -0
- package/dist/commands/high-family/mesh-status.d.ts +2 -0
- package/dist/commands/high-family/types.d.ts +60 -0
- package/dist/commands/low-family/coordinator-prompt.d.ts +9 -0
- package/dist/commands/low-family/daemon-lifecycle.d.ts +2 -0
- package/dist/commands/low-family/diagnostics.d.ts +2 -0
- package/dist/commands/low-family/index.d.ts +3 -0
- package/dist/commands/low-family/mesh-ledger.d.ts +10 -0
- package/dist/commands/low-family/mesh-node-logs.d.ts +2 -0
- package/dist/commands/low-family/notification.d.ts +2 -0
- package/dist/commands/low-family/refine-config.d.ts +2 -0
- package/dist/commands/low-family/session-host.d.ts +2 -0
- package/dist/commands/low-family/spec-providerdev.d.ts +11 -0
- package/dist/commands/low-family/status-meta.d.ts +2 -0
- package/dist/commands/low-family/types.d.ts +33 -0
- package/dist/commands/med-family/cli-agent.d.ts +2 -0
- package/dist/commands/med-family/fast-forward.d.ts +2 -0
- package/dist/commands/med-family/ide.d.ts +10 -0
- package/dist/commands/med-family/index.d.ts +3 -0
- package/dist/commands/med-family/mesh-crud.d.ts +29 -0
- package/dist/commands/med-family/mesh-host-pairing.d.ts +2 -0
- package/dist/commands/med-family/mesh-queue.d.ts +2 -0
- package/dist/commands/med-family/mesh-restart.d.ts +2 -0
- package/dist/commands/med-family/types.d.ts +142 -0
- package/dist/commands/mesh-coordinator.d.ts +85 -1
- package/dist/commands/router.d.ts +276 -2
- package/dist/commands/upgrade-helper.d.ts +41 -1
- package/dist/config/chat-history.d.ts +9 -0
- package/dist/config/config.d.ts +5 -0
- package/dist/config/mesh-config.d.ts +100 -1
- package/dist/config/mesh-json-config.d.ts +199 -0
- package/dist/config/repo-settings.d.ts +77 -0
- package/dist/daemon/dev-server.d.ts +0 -2
- package/dist/detection/ide-detector.d.ts +13 -0
- package/dist/detection/win32-ide-version.d.ts +37 -0
- package/dist/git/change-impact-config.d.ts +159 -0
- package/dist/git/git-commands.d.ts +11 -1
- package/dist/git/git-diff.d.ts +6 -0
- package/dist/git/git-executor.d.ts +11 -0
- package/dist/git/git-status.d.ts +57 -0
- package/dist/git/git-types.d.ts +2 -50
- package/dist/git/git-worktree.d.ts +71 -1
- package/dist/git/index.d.ts +3 -1
- package/dist/index.d.ts +64 -14
- package/dist/index.js +49391 -19228
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +48574 -18570
- package/dist/index.mjs.map +1 -1
- package/dist/installer.d.ts +1 -4
- package/dist/ipc/local-ipc-server.d.ts +91 -0
- package/dist/launch.d.ts +1 -1
- package/dist/logging/async-batch-writer.d.ts +10 -0
- package/dist/logging/log-redactor.d.ts +24 -0
- package/dist/logging/log-tail-reader.d.ts +81 -0
- package/dist/logging/logger.d.ts +1 -1
- package/dist/mesh/contracts.d.ts +164 -0
- package/dist/mesh/coordinator-prompt.d.ts +89 -0
- package/dist/mesh/coordinator-registry.d.ts +59 -0
- package/dist/mesh/mesh-active-work.d.ts +174 -0
- package/dist/mesh/mesh-clone-grace.d.ts +8 -0
- package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
- package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
- package/dist/mesh/mesh-event-classify.d.ts +5 -0
- package/dist/mesh/mesh-event-forwarding.d.ts +41 -0
- package/dist/mesh/mesh-event-trace.d.ts +21 -0
- package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
- package/dist/mesh/mesh-events-pending.d.ts +69 -0
- package/dist/mesh/mesh-events-stale.d.ts +61 -0
- package/dist/mesh/mesh-events-utils.d.ts +75 -0
- package/dist/mesh/mesh-events.d.ts +6 -49
- package/dist/mesh/mesh-fast-forward.d.ts +81 -0
- package/dist/mesh/mesh-host-ownership.d.ts +9 -0
- package/dist/mesh/mesh-init.d.ts +86 -0
- package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
- package/dist/mesh/mesh-ledger.d.ts +77 -1
- package/dist/mesh/mesh-magi-status.d.ts +63 -0
- package/dist/mesh/mesh-missions.d.ts +189 -0
- package/dist/mesh/mesh-node-identity.d.ts +289 -0
- package/dist/mesh/mesh-queue-assignment.d.ts +113 -0
- package/dist/mesh/mesh-reconcile-loop.d.ts +65 -0
- package/dist/mesh/mesh-refine-batch.d.ts +68 -0
- package/dist/mesh/mesh-refine-gates.d.ts +428 -0
- package/dist/mesh/mesh-refine-status.d.ts +62 -0
- package/dist/mesh/mesh-review-inbox.d.ts +90 -0
- package/dist/mesh/mesh-routing.d.ts +70 -0
- package/dist/mesh/mesh-runtime-store.d.ts +450 -0
- package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
- package/dist/mesh/mesh-task-inflight.d.ts +46 -0
- package/dist/mesh/mesh-task-stats.d.ts +49 -0
- package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
- package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
- package/dist/mesh/mesh-work-queue.d.ts +290 -5
- package/dist/mesh/preview-freshness.d.ts +18 -0
- package/dist/mesh/refine-config.d.ts +216 -0
- package/dist/mesh/worktree-bootstrap-config.d.ts +145 -0
- package/dist/providers/acp-provider-instance.d.ts +5 -0
- package/dist/providers/approval-utils.d.ts +20 -0
- package/dist/providers/chat-message-normalization.d.ts +31 -1
- package/dist/providers/cli-provider-instance.d.ts +221 -3
- package/dist/providers/contracts.d.ts +139 -6
- package/dist/providers/external-sources.d.ts +71 -0
- package/dist/providers/manual-attendance.d.ts +63 -0
- package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
- package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
- package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
- package/dist/providers/native-history/constants.d.ts +12 -0
- package/dist/providers/native-history/dispatcher.d.ts +27 -0
- package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
- package/dist/providers/native-history/index.d.ts +13 -0
- package/dist/providers/provider-instance-manager.d.ts +29 -0
- package/dist/providers/provider-instance.d.ts +23 -1
- package/dist/providers/provider-loader.d.ts +26 -4
- package/dist/providers/provider-trust.d.ts +31 -0
- package/dist/providers/read-chat-contract.d.ts +29 -0
- package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
- package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
- package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
- package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
- package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
- package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
- package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
- package/dist/providers/sdk/v1/index.d.ts +30 -0
- package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
- package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
- package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
- package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
- package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
- package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
- package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
- package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
- package/dist/providers/spec/adapter.d.ts +91 -0
- package/dist/providers/spec/cli-adapter.d.ts +223 -0
- package/dist/providers/spec/evaluator.d.ts +45 -0
- package/dist/providers/spec/fsm-driver.d.ts +422 -0
- package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
- package/dist/providers/spec/fsm-loader.d.ts +14 -0
- package/dist/providers/spec/fsm-types.d.ts +174 -0
- package/dist/providers/spec/native-history-executor.d.ts +41 -0
- package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
- package/dist/providers/spec/route.d.ts +4 -0
- package/dist/providers/spec/types.d.ts +222 -0
- package/dist/providers/status-monitor.d.ts +7 -7
- package/dist/providers/transcript-v2.d.ts +176 -0
- package/dist/providers/types/interactive-prompt.d.ts +84 -0
- package/dist/providers/working-dir.d.ts +17 -0
- package/dist/repo-mesh-types.d.ts +501 -13
- package/dist/runtime-defaults.d.ts +2 -0
- package/dist/sessions/registry.d.ts +6 -0
- package/dist/shared-types-extra.d.ts +2 -4
- package/dist/shared-types.d.ts +59 -2
- package/dist/status/normalize.d.ts +1 -1
- package/dist/status/normalize.js +1 -0
- package/dist/status/normalize.js.map +1 -1
- package/dist/status/normalize.mjs +1 -0
- package/dist/status/normalize.mjs.map +1 -1
- package/dist/status/reporter.d.ts +2 -0
- package/dist/status/snapshot.d.ts +26 -0
- package/dist/system/hash.d.ts +8 -0
- package/dist/system/load-better-sqlite3.d.ts +21 -0
- package/dist/types.d.ts +5 -0
- package/package.json +7 -3
- package/src/agent-stream/poller.ts +2 -3
- package/src/agent-stream/provider-adapter.ts +1 -1
- package/src/boot/daemon-lifecycle.ts +63 -12
- package/src/boot/process-hardening.ts +89 -0
- package/src/build-info.ts +73 -0
- package/src/chat/source-machine.ts +534 -0
- package/src/chat/source-resolver.ts +0 -0
- package/src/chat/subscription-updates.ts +20 -1
- package/src/cli-adapter-types.d.ts +3 -1
- package/src/cli-adapter-types.ts +68 -2
- package/src/cli-adapters/cli-script-runner.ts +421 -0
- package/src/cli-adapters/cli-state-engine.ts +1246 -0
- package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
- package/src/cli-adapters/provider-cli-adapter.ts +914 -1144
- package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
- package/src/cli-adapters/provider-cli-parse.ts +19 -0
- package/src/cli-adapters/provider-cli-runtime.ts +56 -7
- package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
- package/src/cli-adapters/provider-cli-shared.ts +121 -11
- package/src/cli-adapters/pty-transport.ts +2 -1
- package/src/cli-adapters/pty-write-chunking.ts +106 -0
- package/src/cli-adapters/raw-terminal-io.ts +252 -0
- package/src/cli-adapters/resolve-executable.ts +204 -0
- package/src/cli-adapters/session-host-transport.ts +2 -1
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
- package/src/cli-adapters/terminal-backends/types.ts +10 -3
- package/src/cli-adapters/terminal-screen.ts +16 -81
- package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
- package/src/commands/chat-commands-debug-bundle.ts +398 -0
- package/src/commands/chat-commands-read.ts +2327 -0
- package/src/commands/chat-commands-scope.ts +54 -0
- package/src/commands/chat-commands-shared.ts +114 -0
- package/src/commands/chat-commands-write.ts +891 -0
- package/src/commands/chat-commands.ts +19 -1841
- package/src/commands/cli-manager.ts +544 -26
- package/src/commands/handler.ts +841 -2
- package/src/commands/high-family/index.ts +28 -0
- package/src/commands/high-family/mesh-coordinator-launch.ts +678 -0
- package/src/commands/high-family/mesh-events.ts +80 -0
- package/src/commands/high-family/mesh-status.ts +710 -0
- package/src/commands/high-family/types.ts +76 -0
- package/src/commands/low-family/coordinator-prompt.ts +72 -0
- package/src/commands/low-family/daemon-lifecycle.ts +107 -0
- package/src/commands/low-family/diagnostics.ts +57 -0
- package/src/commands/low-family/index.ts +37 -0
- package/src/commands/low-family/mesh-ledger.ts +62 -0
- package/src/commands/low-family/mesh-node-logs.ts +87 -0
- package/src/commands/low-family/notification.ts +116 -0
- package/src/commands/low-family/refine-config.ts +106 -0
- package/src/commands/low-family/session-host.ts +274 -0
- package/src/commands/low-family/spec-providerdev.ts +217 -0
- package/src/commands/low-family/status-meta.ts +112 -0
- package/src/commands/low-family/types.ts +39 -0
- package/src/commands/med-family/cli-agent.ts +238 -0
- package/src/commands/med-family/fast-forward.ts +230 -0
- package/src/commands/med-family/ide.ts +163 -0
- package/src/commands/med-family/index.ts +37 -0
- package/src/commands/med-family/mesh-crud.ts +1066 -0
- package/src/commands/med-family/mesh-host-pairing.ts +234 -0
- package/src/commands/med-family/mesh-queue.ts +167 -0
- package/src/commands/med-family/mesh-restart.ts +92 -0
- package/src/commands/med-family/types.ts +143 -0
- package/src/commands/mesh-coordinator.ts +334 -124
- package/src/commands/router.ts +2711 -3254
- package/src/commands/stream-commands.ts +8 -0
- package/src/commands/upgrade-helper.ts +310 -45
- package/src/config/chat-history.ts +483 -24
- package/src/config/config.ts +12 -0
- package/src/config/mesh-config.ts +495 -22
- package/src/config/mesh-json-config.ts +376 -0
- package/src/config/recent-activity.ts +8 -2
- package/src/config/repo-settings.ts +111 -0
- package/src/daemon/dev-auto-implement.ts +3 -2
- package/src/daemon/dev-cli-debug.ts +10 -1
- package/src/daemon/dev-server.ts +0 -541
- package/src/detection/cli-detector.ts +28 -9
- package/src/detection/ide-detector.ts +55 -16
- package/src/detection/win32-ide-version.ts +106 -0
- package/src/git/change-impact-config.ts +354 -0
- package/src/git/git-commands.ts +59 -15
- package/src/git/git-diff.ts +81 -11
- package/src/git/git-executor.ts +12 -0
- package/src/git/git-status.ts +767 -48
- package/src/git/git-types.ts +14 -62
- package/src/git/git-worktree.ts +261 -4
- package/src/git/index.ts +17 -0
- package/src/index.ts +194 -12
- package/src/installer.d.ts +1 -1
- package/src/installer.ts +8 -6
- package/src/ipc/local-ipc-server.ts +278 -0
- package/src/launch.d.ts +1 -1
- package/src/launch.ts +37 -28
- package/src/logging/async-batch-writer.ts +55 -0
- package/src/logging/command-log.ts +7 -5
- package/src/logging/log-redactor.ts +100 -0
- package/src/logging/log-tail-reader.ts +341 -0
- package/src/logging/logger.ts +14 -7
- package/src/mesh/contracts.ts +338 -0
- package/src/mesh/coordinator-prompt.ts +381 -33
- package/src/mesh/coordinator-registry.ts +121 -0
- package/src/mesh/mesh-active-work.ts +645 -0
- package/src/mesh/mesh-clone-grace.ts +68 -0
- package/src/mesh/mesh-coordinator-config.ts +97 -0
- package/src/mesh/mesh-delivery-policy.ts +315 -0
- package/src/mesh/mesh-event-classify.ts +51 -0
- package/src/mesh/mesh-event-forwarding.ts +1888 -0
- package/src/mesh/mesh-event-trace.ts +67 -0
- package/src/mesh/mesh-events-coordinator.ts +32 -0
- package/src/mesh/mesh-events-pending.ts +656 -0
- package/src/mesh/mesh-events-stale.ts +389 -0
- package/src/mesh/mesh-events-utils.ts +443 -0
- package/src/mesh/mesh-events.ts +33 -1035
- package/src/mesh/mesh-fast-forward.ts +843 -0
- package/src/mesh/mesh-host-ownership.ts +73 -0
- package/src/mesh/mesh-init.ts +260 -0
- package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
- package/src/mesh/mesh-ledger.ts +656 -102
- package/src/mesh/mesh-magi-status.ts +223 -0
- package/src/mesh/mesh-missions.ts +449 -0
- package/src/mesh/mesh-node-identity.ts +1887 -0
- package/src/mesh/mesh-queue-assignment.ts +1918 -0
- package/src/mesh/mesh-reconcile-loop.ts +1780 -0
- package/src/mesh/mesh-refine-batch.ts +205 -0
- package/src/mesh/mesh-refine-gates.ts +1673 -0
- package/src/mesh/mesh-refine-status.ts +231 -0
- package/src/mesh/mesh-review-inbox.ts +307 -0
- package/src/mesh/mesh-routing.ts +291 -0
- package/src/mesh/mesh-runtime-store.ts +1853 -0
- package/src/mesh/mesh-scheduling-runtime.ts +198 -0
- package/src/mesh/mesh-task-inflight.ts +70 -0
- package/src/mesh/mesh-task-stats.ts +161 -0
- package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
- package/src/mesh/mesh-warmup-deadline.ts +152 -0
- package/src/mesh/mesh-work-queue.ts +1243 -141
- package/src/mesh/preview-freshness.ts +118 -0
- package/src/mesh/refine-config.ts +423 -0
- package/src/mesh/worktree-bootstrap-config.ts +450 -0
- package/src/providers/acp-provider-instance.ts +43 -10
- package/src/providers/approval-utils.d.ts +5 -0
- package/src/providers/approval-utils.ts +57 -5
- package/src/providers/chat-message-normalization.ts +92 -4
- package/src/providers/cli-provider-instance.ts +1933 -104
- package/src/providers/contracts.d.ts +55 -0
- package/src/providers/contracts.ts +150 -6
- package/src/providers/extension-provider-instance.ts +12 -7
- package/src/providers/external-sources.ts +218 -0
- package/src/providers/ide-provider-instance.ts +35 -12
- package/src/providers/manual-attendance.ts +85 -0
- package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
- package/src/providers/native-history/claude-cli-transcript.ts +396 -0
- package/src/providers/native-history/codex-cli-transcript.ts +479 -0
- package/src/providers/native-history/constants.ts +19 -0
- package/src/providers/native-history/dispatcher.ts +339 -0
- package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
- package/src/providers/native-history/index.ts +30 -0
- package/src/providers/provider-instance-manager.ts +71 -0
- package/src/providers/provider-instance.ts +19 -1
- package/src/providers/provider-loader.ts +668 -50
- package/src/providers/provider-schema.ts +87 -14
- package/src/providers/provider-trust.ts +114 -0
- package/src/providers/read-chat-contract.ts +76 -16
- package/src/providers/sdk/README.md +49 -0
- package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
- package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
- package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
- package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
- package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
- package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
- package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
- package/src/providers/sdk/v1/index.ts +152 -0
- package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
- package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
- package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
- package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
- package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
- package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
- package/src/providers/sdk/v1/types/cli/index.ts +365 -0
- package/src/providers/sdk/v1/types/common/index.ts +229 -0
- package/src/providers/sdk/v1/validators/index.ts +19 -0
- package/src/providers/sdk/v1/validators/manifest.ts +110 -0
- package/src/providers/sdk/v1/validators/taint.ts +309 -0
- package/src/providers/spec/adapter.ts +235 -0
- package/src/providers/spec/cli-adapter.ts +1056 -0
- package/src/providers/spec/evaluator.ts +407 -0
- package/src/providers/spec/fsm-driver.ts +1410 -0
- package/src/providers/spec/fsm-evaluator.ts +272 -0
- package/src/providers/spec/fsm-loader.ts +120 -0
- package/src/providers/spec/fsm-types.ts +273 -0
- package/src/providers/spec/native-history-executor.ts +1128 -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 +740 -14
- package/src/runtime-defaults.ts +39 -0
- package/src/sessions/registry.ts +6 -0
- package/src/shared-types-extra.ts +2 -4
- package/src/shared-types.d.ts +8 -0
- package/src/shared-types.ts +64 -1
- package/src/status/builders.ts +26 -6
- package/src/status/normalize.ts +2 -0
- package/src/status/reporter.ts +19 -1
- package/src/status/snapshot.ts +95 -26
- package/src/system/hash.ts +23 -0
- package/src/system/host-memory.ts +29 -12
- package/src/system/load-better-sqlite3.ts +68 -0
- package/src/types.ts +5 -0
- package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
- package/dist/mesh/mesh-sync.d.ts +0 -53
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
- package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
- package/src/mesh/mesh-sync.ts +0 -111
package/src/mesh/mesh-ledger.ts
CHANGED
|
@@ -13,11 +13,12 @@
|
|
|
13
13
|
* Safety: mode 0o600, atomic append via appendFileSync
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
|
-
import { existsSync, mkdirSync, readFileSync,
|
|
16
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, renameSync, writeFileSync } from 'fs';
|
|
17
17
|
import { join } from 'path';
|
|
18
18
|
import { randomUUID } from 'crypto';
|
|
19
19
|
import { getConfigDir } from '../config/config.js';
|
|
20
20
|
import { EventEmitter } from 'events';
|
|
21
|
+
import { MeshRuntimeStore } from './mesh-runtime-store.js';
|
|
21
22
|
// ─── Types ──────────────────────────────────────
|
|
22
23
|
|
|
23
24
|
export type MeshLedgerKind =
|
|
@@ -26,16 +27,45 @@ export type MeshLedgerKind =
|
|
|
26
27
|
| 'task_failed'
|
|
27
28
|
| 'task_stalled'
|
|
28
29
|
| 'task_approval_needed'
|
|
30
|
+
| 'p2p_dispatch_failed'
|
|
29
31
|
| 'session_launched'
|
|
30
32
|
| 'session_auto_launch'
|
|
31
33
|
| 'session_stopped'
|
|
32
34
|
| 'checkpoint_created'
|
|
33
35
|
| 'node_cloned'
|
|
36
|
+
| 'node_joined'
|
|
34
37
|
| 'node_removed'
|
|
35
38
|
| 'coordinator_started'
|
|
36
39
|
| 'recovery_attempted'
|
|
37
40
|
| 'ledger_replicated'
|
|
38
41
|
| 'ledger_reconciled'
|
|
42
|
+
| 'direct_fast_forward'
|
|
43
|
+
| 'delivery_unroutable'
|
|
44
|
+
| 'direct_dispatch_pruned'
|
|
45
|
+
| 'event_held'
|
|
46
|
+
| 'task_reclaimed'
|
|
47
|
+
// Gap2-A: a coordinator-recorded operating note — a runtime-accumulated
|
|
48
|
+
// lesson (provider quirk, pattern to avoid, recovery lesson) persisted in
|
|
49
|
+
// the ledger so it survives coordinator restarts and is provider-neutral.
|
|
50
|
+
// payload: { text, category?, createdAt?, sourceCoordinator? }
|
|
51
|
+
| 'coordinator_operating_note'
|
|
52
|
+
// Mission audit trail: mission record mutations (mesh_mission_upsert) so the
|
|
53
|
+
// ledger captures mission lifecycle, not just task events. Without these a
|
|
54
|
+
// mission create / goal rewrite / status transition left no ledger trace,
|
|
55
|
+
// breaking audit continuity and post-restart recovery.
|
|
56
|
+
// mission_created payload: { missionId, title, goalSummary, goalLength, goalTruncated, status }
|
|
57
|
+
// mission_status_changed payload: { missionId, title, fromStatus, toStatus }
|
|
58
|
+
// mission_goal_updated payload: { missionId, title, prevGoalSummary, nextGoalSummary, prevGoalLength, nextGoalLength, goalTruncated }
|
|
59
|
+
| 'mission_created'
|
|
60
|
+
| 'mission_status_changed'
|
|
61
|
+
| 'mission_goal_updated'
|
|
62
|
+
// MAGI (Multi-Agent Ground-truth Insight) cross-verification activity. Persisted
|
|
63
|
+
// so a wait=false fan-out and its later synthesis survive coordinator restarts and
|
|
64
|
+
// are foldable into mesh_status (keyed by consensusGroupId).
|
|
65
|
+
// magi_dispatched payload: { source:'magi', consensusGroupId, missionId?, panel?, question?, replicaCount }
|
|
66
|
+
// magi_synthesis payload: { source:'magi', consensusGroupId, missionId?, panel?, question?, synthesis }
|
|
67
|
+
| 'magi_dispatched'
|
|
68
|
+
| 'magi_synthesis'
|
|
39
69
|
;
|
|
40
70
|
|
|
41
71
|
export interface MeshLedgerEntry {
|
|
@@ -61,6 +91,51 @@ export function isIntentionalCleanupStopEntry(entry: Pick<MeshLedgerEntry, 'kind
|
|
|
61
91
|
|| payload.source === 'mesh_remove_node');
|
|
62
92
|
}
|
|
63
93
|
|
|
94
|
+
export type MeshWorkerResultStatus = 'completed' | 'failed' | 'blocked' | 'partial' | 'unknown';
|
|
95
|
+
export type MeshProcessArtifactKind = 'process' | 'log' | 'port' | 'window' | 'session' | 'file' | 'url' | 'other';
|
|
96
|
+
|
|
97
|
+
export interface MeshValidationResultArtifact {
|
|
98
|
+
command?: string;
|
|
99
|
+
status: 'passed' | 'failed' | 'skipped' | 'unknown';
|
|
100
|
+
durationMs?: number;
|
|
101
|
+
outputPath?: string;
|
|
102
|
+
summary?: string;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface MeshProcessArtifact {
|
|
106
|
+
kind: MeshProcessArtifactKind;
|
|
107
|
+
id?: string;
|
|
108
|
+
label?: string;
|
|
109
|
+
locator?: string;
|
|
110
|
+
pid?: number;
|
|
111
|
+
port?: number;
|
|
112
|
+
url?: string;
|
|
113
|
+
path?: string;
|
|
114
|
+
sessionId?: string;
|
|
115
|
+
keepRunning?: boolean;
|
|
116
|
+
metadata?: Record<string, unknown>;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface MeshWorkerResultArtifact {
|
|
120
|
+
status: MeshWorkerResultStatus;
|
|
121
|
+
classification?: string;
|
|
122
|
+
changedFiles: string[];
|
|
123
|
+
validationResults: MeshValidationResultArtifact[];
|
|
124
|
+
gitStatus?: Record<string, unknown>;
|
|
125
|
+
processArtifacts: MeshProcessArtifact[];
|
|
126
|
+
errors: string[];
|
|
127
|
+
nextAction?: string;
|
|
128
|
+
requiresUserAction: boolean;
|
|
129
|
+
// NOTIF Defect-2b: `parseable_answer` = the final summary held a parseable JSON
|
|
130
|
+
// ANSWER (e.g. a MAGI claim_audit / rca envelope) that is NOT worker-result-shaped
|
|
131
|
+
// (no status + changedFiles/errors/…). It is still concrete evidence that the worker
|
|
132
|
+
// produced a real, parseable answer — so it must NOT be labelled evidenceLevel
|
|
133
|
+
// 'insufficient' — but it is NOT a self-attributing worker result, so it is deliberately
|
|
134
|
+
// distinct from 'final_summary_json' and stays subject to the direct-dispatch grace gate
|
|
135
|
+
// in mesh-events-stale.ts (which keys on `!== 'final_summary_json'`).
|
|
136
|
+
source: 'explicit_metadata' | 'final_summary_json' | 'parseable_answer' | 'default';
|
|
137
|
+
}
|
|
138
|
+
|
|
64
139
|
export interface MeshTaskCompletionEvidence {
|
|
65
140
|
source: 'agent_status_event';
|
|
66
141
|
event: 'agent:generating_completed' | 'agent:ready';
|
|
@@ -74,6 +149,7 @@ export interface MeshTaskCompletionEvidence {
|
|
|
74
149
|
providerSessionId?: string;
|
|
75
150
|
finalSummaryAvailable: boolean;
|
|
76
151
|
};
|
|
152
|
+
workerResult: MeshWorkerResultArtifact;
|
|
77
153
|
git: {
|
|
78
154
|
status: 'deferred';
|
|
79
155
|
reason: string;
|
|
@@ -96,6 +172,7 @@ export interface BuildTaskCompletionEvidenceOptions {
|
|
|
96
172
|
providerType?: string;
|
|
97
173
|
providerSessionId?: string;
|
|
98
174
|
finalSummary?: string;
|
|
175
|
+
workerResult?: Record<string, unknown>;
|
|
99
176
|
completedAt?: string;
|
|
100
177
|
}
|
|
101
178
|
|
|
@@ -160,8 +237,19 @@ export interface AppendRemoteLedgerResult {
|
|
|
160
237
|
// ─── Constants ──────────────────────────────────
|
|
161
238
|
|
|
162
239
|
const LEDGER_DIR_NAME = 'mesh-ledger';
|
|
163
|
-
const MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB
|
|
240
|
+
const MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB — full rotation threshold
|
|
241
|
+
const COMPACT_THRESHOLD_BYTES = 2 * 1024 * 1024; // 2 MB — compaction threshold
|
|
242
|
+
const ARCHIVE_TERMINAL_OLDER_THAN_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
|
164
243
|
const RECENT_FAILURE_WINDOW_MS = 30 * 60 * 1000; // 30 minutes
|
|
244
|
+
|
|
245
|
+
// Kinds that accumulate indefinitely and are safe to archive after ARCHIVE_TERMINAL_OLDER_THAN_MS.
|
|
246
|
+
// Non-terminal kinds (dispatched, sessions, nodes, checkpoints) are always kept in the active file.
|
|
247
|
+
const ARCHIVABLE_KINDS: ReadonlySet<MeshLedgerKind> = new Set([
|
|
248
|
+
'task_completed',
|
|
249
|
+
'task_failed',
|
|
250
|
+
'task_stalled',
|
|
251
|
+
'recovery_attempted',
|
|
252
|
+
] as MeshLedgerKind[]);
|
|
165
253
|
const DEFAULT_LEDGER_SLICE_LIMIT = 100;
|
|
166
254
|
export const MAX_LEDGER_SLICE_LIMIT = 500;
|
|
167
255
|
|
|
@@ -186,8 +274,294 @@ function getRotatedPath(meshId: string, index: number): string {
|
|
|
186
274
|
return join(getLedgerDir(), `${safe}.${index}.jsonl`);
|
|
187
275
|
}
|
|
188
276
|
|
|
277
|
+
function getArchivePath(meshId: string): string {
|
|
278
|
+
const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
279
|
+
return join(getLedgerDir(), `${safe}.archive.jsonl`);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function getRotatedArchivePath(meshId: string, index: number): string {
|
|
283
|
+
const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
284
|
+
return join(getLedgerDir(), `${safe}.archive.${index}.jsonl`);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function getArchivedCountsPath(meshId: string): string {
|
|
288
|
+
const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
289
|
+
return join(getLedgerDir(), `${safe}.archived-counts.json`);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function rotateArchiveFile(meshId: string, archivePath: string): void {
|
|
293
|
+
let index = 1;
|
|
294
|
+
while (existsSync(getRotatedArchivePath(meshId, index))) {
|
|
295
|
+
index++;
|
|
296
|
+
if (index > 5) break;
|
|
297
|
+
}
|
|
298
|
+
if (index > 5) index = 5;
|
|
299
|
+
try {
|
|
300
|
+
renameSync(archivePath, getRotatedArchivePath(meshId, index));
|
|
301
|
+
} catch (e: any) {
|
|
302
|
+
process.stderr.write(`[adhdev-mesh] Archive rotation failed for mesh ${meshId}: ${e?.message || e}\n`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
interface LedgerArchivedCounts {
|
|
307
|
+
taskCompleted: number;
|
|
308
|
+
taskFailed: number;
|
|
309
|
+
taskStalled: number;
|
|
310
|
+
recoveryAttempted: number;
|
|
311
|
+
totalArchived: number;
|
|
312
|
+
lastArchivedAt: string;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function readArchivedCounts(meshId: string): LedgerArchivedCounts {
|
|
316
|
+
const path = getArchivedCountsPath(meshId);
|
|
317
|
+
if (!existsSync(path)) return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: '' };
|
|
318
|
+
try { return JSON.parse(readFileSync(path, 'utf-8')) as LedgerArchivedCounts; } catch { return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: '' }; }
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function updateArchivedCounts(meshId: string, archived: MeshLedgerEntry[]): void {
|
|
322
|
+
const counts = readArchivedCounts(meshId);
|
|
323
|
+
for (const e of archived) {
|
|
324
|
+
if (e.kind === 'task_completed') counts.taskCompleted++;
|
|
325
|
+
else if (e.kind === 'task_failed') counts.taskFailed++;
|
|
326
|
+
else if (e.kind === 'task_stalled') counts.taskStalled++;
|
|
327
|
+
else if (e.kind === 'recovery_attempted') counts.recoveryAttempted++;
|
|
328
|
+
}
|
|
329
|
+
counts.totalArchived += archived.length;
|
|
330
|
+
counts.lastArchivedAt = new Date().toISOString();
|
|
331
|
+
try { writeFileSync(getArchivedCountsPath(meshId), JSON.stringify(counts), { encoding: 'utf-8', mode: 0o600 }); } catch { /* best-effort */ }
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// ─── Worker Result Footer ───────────────────────
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Footer to append to worker task messages so workers output structured results
|
|
338
|
+
* that the daemon parses via extractJsonObjectFromSummary / normalizeMeshWorkerResult.
|
|
339
|
+
*
|
|
340
|
+
* Usage: append buildWorkerTaskFooter() to the task message in mesh_send_task /
|
|
341
|
+
* mesh_enqueue_task. The coordinator prompt rules instruct coordinators to do this.
|
|
342
|
+
*/
|
|
343
|
+
export function buildWorkerTaskFooter(): string {
|
|
344
|
+
return `
|
|
345
|
+
|
|
346
|
+
---
|
|
347
|
+
When your task is done, end your final response with a JSON code block in this exact format (omit fields that don't apply):
|
|
348
|
+
\`\`\`json
|
|
349
|
+
{
|
|
350
|
+
"status": "completed",
|
|
351
|
+
"changedFiles": ["src/foo.ts", "tests/foo.test.ts"],
|
|
352
|
+
"gitStatus": { "branch": "feat/your-branch", "committed": true, "pushed": false },
|
|
353
|
+
"validationResults": [{ "command": "npm test", "status": "passed" }],
|
|
354
|
+
"errors": [],
|
|
355
|
+
"nextAction": "optional guidance for the coordinator"
|
|
356
|
+
}
|
|
357
|
+
\`\`\`
|
|
358
|
+
Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// ─── Ledger Compaction ──────────────────────────
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Compact the active ledger file for a mesh by moving old terminal entries
|
|
365
|
+
* (task_completed, task_failed, task_stalled, recovery_attempted older than 7 days)
|
|
366
|
+
* to <meshId>.archive.jsonl, keeping the active file lean.
|
|
367
|
+
*
|
|
368
|
+
* Non-terminal entries (dispatch, sessions, node lifecycle) are always retained.
|
|
369
|
+
* Called automatically from appendLedgerEntry when the file exceeds COMPACT_THRESHOLD_BYTES.
|
|
370
|
+
*/
|
|
371
|
+
export function compactLedger(meshId: string): { archivedCount: number; retainedCount: number } {
|
|
372
|
+
const filePath = getLedgerPath(meshId);
|
|
373
|
+
if (!existsSync(filePath)) return { archivedCount: 0, retainedCount: 0 };
|
|
374
|
+
|
|
375
|
+
const cutoff = Date.now() - ARCHIVE_TERMINAL_OLDER_THAN_MS;
|
|
376
|
+
const entries = readLedgerEntries(meshId);
|
|
377
|
+
|
|
378
|
+
const keep: MeshLedgerEntry[] = [];
|
|
379
|
+
const archive: MeshLedgerEntry[] = [];
|
|
380
|
+
for (const entry of entries) {
|
|
381
|
+
if (ARCHIVABLE_KINDS.has(entry.kind) && new Date(entry.timestamp).getTime() < cutoff) {
|
|
382
|
+
archive.push(entry);
|
|
383
|
+
} else {
|
|
384
|
+
keep.push(entry);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
if (archive.length === 0) return { archivedCount: 0, retainedCount: keep.length };
|
|
389
|
+
|
|
390
|
+
// Append archived entries to the archive file, rotate if it exceeds 50MB
|
|
391
|
+
const archivePath = getArchivePath(meshId);
|
|
392
|
+
try {
|
|
393
|
+
if (existsSync(archivePath) && statSync(archivePath).size > 50 * 1024 * 1024) {
|
|
394
|
+
rotateArchiveFile(meshId, archivePath);
|
|
395
|
+
}
|
|
396
|
+
const archiveLines = archive.map(e => JSON.stringify(e)).join('\n') + '\n';
|
|
397
|
+
appendFileSync(archivePath, archiveLines, { encoding: 'utf-8', mode: 0o600 });
|
|
398
|
+
updateArchivedCounts(meshId, archive);
|
|
399
|
+
} catch (e: any) {
|
|
400
|
+
process.stderr.write(`[adhdev-mesh] Ledger archive write failed for mesh ${meshId}: ${e?.message || e}\n`);
|
|
401
|
+
return { archivedCount: 0, retainedCount: entries.length };
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// Rewrite active file with retained entries only
|
|
405
|
+
try {
|
|
406
|
+
const keepLines = keep.length ? keep.map(e => JSON.stringify(e)).join('\n') + '\n' : '';
|
|
407
|
+
writeFileSync(filePath, keepLines, { encoding: 'utf-8', mode: 0o600 });
|
|
408
|
+
invalidateLedgerCache(meshId);
|
|
409
|
+
} catch (e: any) {
|
|
410
|
+
process.stderr.write(`[adhdev-mesh] Ledger compaction rewrite failed for mesh ${meshId}: ${e?.message || e}\n`);
|
|
411
|
+
return { archivedCount: archive.length, retainedCount: keep.length };
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// G2: mirror the compaction in SQLite so the runtime store matches the active
|
|
415
|
+
// ledger set. Archived entries live on in the JSONL archive files (export/debug).
|
|
416
|
+
try {
|
|
417
|
+
MeshRuntimeStore.getInstance().deleteLedgerEntries(meshId, archive.map(e => e.id));
|
|
418
|
+
invalidateLedgerCache(meshId);
|
|
419
|
+
} catch { /* best-effort; summary counts absorb the difference via archived counts */ }
|
|
420
|
+
|
|
421
|
+
return { archivedCount: archive.length, retainedCount: keep.length };
|
|
422
|
+
}
|
|
423
|
+
|
|
189
424
|
// ─── Core API ───────────────────────────────────
|
|
190
425
|
|
|
426
|
+
function readNonEmptyString(value: unknown): string | undefined {
|
|
427
|
+
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function readStringArray(value: unknown): string[] {
|
|
431
|
+
if (!Array.isArray(value)) return [];
|
|
432
|
+
return value.map(item => readNonEmptyString(item)).filter(Boolean) as string[];
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function extractJsonObjectFromSummary(summary?: string): Record<string, unknown> | undefined {
|
|
436
|
+
const text = readNonEmptyString(summary);
|
|
437
|
+
if (!text) return undefined;
|
|
438
|
+
const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
439
|
+
const candidates = [fenced?.[1], text].filter(Boolean) as string[];
|
|
440
|
+
for (const candidate of candidates) {
|
|
441
|
+
const trimmed = candidate.trim();
|
|
442
|
+
if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) continue;
|
|
443
|
+
try {
|
|
444
|
+
const parsed = JSON.parse(trimmed);
|
|
445
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
446
|
+
// Require at least one mesh worker result field to avoid false positives
|
|
447
|
+
// (e.g. JSON from tool call outputs or log lines in the final summary).
|
|
448
|
+
const hasWorkerShape = 'status' in parsed && (
|
|
449
|
+
'changedFiles' in parsed || 'errors' in parsed
|
|
450
|
+
|| 'gitStatus' in parsed || 'nextAction' in parsed
|
|
451
|
+
|| 'validationResults' in parsed
|
|
452
|
+
);
|
|
453
|
+
if (hasWorkerShape) return parsed;
|
|
454
|
+
}
|
|
455
|
+
} catch { /* try next candidate */ }
|
|
456
|
+
}
|
|
457
|
+
return undefined;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function normalizeValidationResults(value: unknown): MeshValidationResultArtifact[] {
|
|
461
|
+
if (!Array.isArray(value)) return [];
|
|
462
|
+
return value
|
|
463
|
+
.filter(item => item && typeof item === 'object' && !Array.isArray(item))
|
|
464
|
+
.map((item: any) => {
|
|
465
|
+
const status = ['passed', 'failed', 'skipped', 'unknown'].includes(item.status) ? item.status : 'unknown';
|
|
466
|
+
return {
|
|
467
|
+
...(readNonEmptyString(item.command) ? { command: readNonEmptyString(item.command) } : {}),
|
|
468
|
+
status,
|
|
469
|
+
...(Number.isFinite(Number(item.durationMs)) ? { durationMs: Number(item.durationMs) } : {}),
|
|
470
|
+
...(readNonEmptyString(item.outputPath) ? { outputPath: readNonEmptyString(item.outputPath) } : {}),
|
|
471
|
+
...(readNonEmptyString(item.summary) ? { summary: readNonEmptyString(item.summary) } : {}),
|
|
472
|
+
};
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function normalizeProcessArtifacts(value: unknown): MeshProcessArtifact[] {
|
|
477
|
+
if (!Array.isArray(value)) return [];
|
|
478
|
+
const kinds = new Set(['process', 'log', 'port', 'window', 'session', 'file', 'url', 'other']);
|
|
479
|
+
return value
|
|
480
|
+
.filter(item => item && typeof item === 'object' && !Array.isArray(item))
|
|
481
|
+
.map((item: any) => ({
|
|
482
|
+
kind: kinds.has(item.kind) ? item.kind : 'other',
|
|
483
|
+
...(readNonEmptyString(item.id) ? { id: readNonEmptyString(item.id) } : {}),
|
|
484
|
+
...(readNonEmptyString(item.label) ? { label: readNonEmptyString(item.label) } : {}),
|
|
485
|
+
...(readNonEmptyString(item.locator) ? { locator: readNonEmptyString(item.locator) } : {}),
|
|
486
|
+
...(Number.isFinite(Number(item.pid)) ? { pid: Number(item.pid) } : {}),
|
|
487
|
+
...(Number.isFinite(Number(item.port)) ? { port: Number(item.port) } : {}),
|
|
488
|
+
...(readNonEmptyString(item.url) ? { url: readNonEmptyString(item.url) } : {}),
|
|
489
|
+
...(readNonEmptyString(item.path) ? { path: readNonEmptyString(item.path) } : {}),
|
|
490
|
+
...(readNonEmptyString(item.sessionId) ? { sessionId: readNonEmptyString(item.sessionId) } : {}),
|
|
491
|
+
...(typeof item.keepRunning === 'boolean' ? { keepRunning: item.keepRunning } : {}),
|
|
492
|
+
...(item.metadata && typeof item.metadata === 'object' && !Array.isArray(item.metadata) ? { metadata: item.metadata as Record<string, unknown> } : {}),
|
|
493
|
+
}));
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
export function normalizeMeshWorkerResult(input?: Record<string, unknown>, source: MeshWorkerResultArtifact['source'] = 'explicit_metadata'): MeshWorkerResultArtifact {
|
|
497
|
+
const raw = input && typeof input === 'object' ? input : {};
|
|
498
|
+
const status = ['completed', 'failed', 'blocked', 'partial', 'unknown'].includes(String(raw.status))
|
|
499
|
+
? raw.status as MeshWorkerResultStatus
|
|
500
|
+
: 'unknown';
|
|
501
|
+
const gitStatus = raw.gitStatus && typeof raw.gitStatus === 'object' && !Array.isArray(raw.gitStatus)
|
|
502
|
+
? raw.gitStatus as Record<string, unknown>
|
|
503
|
+
: undefined;
|
|
504
|
+
return {
|
|
505
|
+
status,
|
|
506
|
+
...(readNonEmptyString(raw.classification) ? { classification: readNonEmptyString(raw.classification) } : {}),
|
|
507
|
+
changedFiles: readStringArray(raw.changedFiles),
|
|
508
|
+
validationResults: normalizeValidationResults(raw.validationResults),
|
|
509
|
+
...(gitStatus ? { gitStatus } : {}),
|
|
510
|
+
processArtifacts: normalizeProcessArtifacts(raw.processArtifacts),
|
|
511
|
+
errors: readStringArray(raw.errors),
|
|
512
|
+
...(readNonEmptyString(raw.nextAction) ? { nextAction: readNonEmptyString(raw.nextAction) } : {}),
|
|
513
|
+
requiresUserAction: raw.requiresUserAction === true,
|
|
514
|
+
source,
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* NOTIF Defect-2b: does the summary contain ANY parseable JSON object answer (not just a
|
|
520
|
+
* worker-result-shaped one)? Some providers (and every MAGI replica) emit a complete, valid
|
|
521
|
+
* answer as a JSON envelope that has no `status`/`changedFiles` worker-result fields, so
|
|
522
|
+
* extractJsonObjectFromSummary returns undefined and the completion is mislabelled
|
|
523
|
+
* source='default' → evidenceLevel='insufficient' even though a real answer was produced.
|
|
524
|
+
* This is a conservative existence check: it only returns true when a JSON object actually
|
|
525
|
+
* parses out of the summary (raw or fenced), so an empty / prose-only / unparseable summary
|
|
526
|
+
* still resolves to 'default'.
|
|
527
|
+
*/
|
|
528
|
+
function summaryHasParseableJsonAnswer(summary?: string): boolean {
|
|
529
|
+
const text = readNonEmptyString(summary);
|
|
530
|
+
if (!text) return false;
|
|
531
|
+
const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
532
|
+
const candidates = [fenced?.[1], text].filter(Boolean) as string[];
|
|
533
|
+
for (const candidate of candidates) {
|
|
534
|
+
const trimmed = candidate.trim();
|
|
535
|
+
if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) continue;
|
|
536
|
+
try {
|
|
537
|
+
const parsed = JSON.parse(trimmed);
|
|
538
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
539
|
+
&& Object.keys(parsed).length > 0) {
|
|
540
|
+
return true;
|
|
541
|
+
}
|
|
542
|
+
} catch { /* try next candidate */ }
|
|
543
|
+
}
|
|
544
|
+
return false;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function resolveWorkerResult(opts: BuildTaskCompletionEvidenceOptions): MeshWorkerResultArtifact {
|
|
548
|
+
if (opts.workerResult && typeof opts.workerResult === 'object') {
|
|
549
|
+
return normalizeMeshWorkerResult(opts.workerResult, 'explicit_metadata');
|
|
550
|
+
}
|
|
551
|
+
const parsed = extractJsonObjectFromSummary(opts.finalSummary);
|
|
552
|
+
if (parsed) {
|
|
553
|
+
return normalizeMeshWorkerResult(parsed, 'final_summary_json');
|
|
554
|
+
}
|
|
555
|
+
// NOTIF Defect-2b: no worker-result-shaped JSON, but a parseable JSON answer IS present
|
|
556
|
+
// (the common MAGI / answer-only case). Treat it as concrete evidence so the completion is
|
|
557
|
+
// not labelled 'insufficient', while keeping the worker-result fields empty (status stays
|
|
558
|
+
// 'unknown') — we only know an answer parsed, not its task outcome.
|
|
559
|
+
if (summaryHasParseableJsonAnswer(opts.finalSummary)) {
|
|
560
|
+
return normalizeMeshWorkerResult(undefined, 'parseable_answer');
|
|
561
|
+
}
|
|
562
|
+
return normalizeMeshWorkerResult(undefined, 'default');
|
|
563
|
+
}
|
|
564
|
+
|
|
191
565
|
export function buildTaskCompletionEvidence(opts: BuildTaskCompletionEvidenceOptions): MeshTaskCompletionEvidence {
|
|
192
566
|
const providerSessionId = opts.providerSessionId?.trim() || undefined;
|
|
193
567
|
const providerType = opts.providerType?.trim() || undefined;
|
|
@@ -204,6 +578,7 @@ export function buildTaskCompletionEvidence(opts: BuildTaskCompletionEvidenceOpt
|
|
|
204
578
|
providerSessionId,
|
|
205
579
|
finalSummaryAvailable: typeof opts.finalSummary === 'string' && opts.finalSummary.trim().length > 0,
|
|
206
580
|
},
|
|
581
|
+
workerResult: resolveWorkerResult(opts),
|
|
207
582
|
git: {
|
|
208
583
|
status: 'deferred',
|
|
209
584
|
reason: 'ordinary_completion_git_status_not_checked',
|
|
@@ -239,21 +614,44 @@ export function appendLedgerEntry(
|
|
|
239
614
|
|
|
240
615
|
const filePath = getLedgerPath(meshId);
|
|
241
616
|
|
|
242
|
-
//
|
|
617
|
+
// Compact or rotate based on file size
|
|
243
618
|
if (existsSync(filePath)) {
|
|
244
619
|
try {
|
|
245
620
|
const stat = statSync(filePath);
|
|
246
621
|
if (stat.size >= MAX_FILE_SIZE_BYTES) {
|
|
247
622
|
rotateLedgerFile(meshId, filePath);
|
|
623
|
+
} else if (stat.size >= COMPACT_THRESHOLD_BYTES) {
|
|
624
|
+
compactLedger(meshId);
|
|
248
625
|
}
|
|
249
626
|
} catch {
|
|
250
627
|
// stat failed — proceed with append anyway
|
|
251
628
|
}
|
|
252
629
|
}
|
|
253
630
|
|
|
631
|
+
// Write to SQLite (G2: primary runtime read/write path)
|
|
632
|
+
try {
|
|
633
|
+
MeshRuntimeStore.getInstance().appendLedgerEntry({
|
|
634
|
+
id: entry.id,
|
|
635
|
+
meshId: entry.meshId,
|
|
636
|
+
timestamp: entry.timestamp,
|
|
637
|
+
kind: entry.kind,
|
|
638
|
+
nodeId: entry.nodeId ?? null,
|
|
639
|
+
sessionId: entry.sessionId ?? null,
|
|
640
|
+
providerType: entry.providerType ?? null,
|
|
641
|
+
payload: entry.payload,
|
|
642
|
+
});
|
|
643
|
+
} catch {
|
|
644
|
+
// SQLite write failed but the JSONL append below still records the entry.
|
|
645
|
+
// Reset the one-time import flag so the next read re-imports from JSONL
|
|
646
|
+
// and the store self-heals instead of silently missing this entry.
|
|
647
|
+
ledgerImportDone.delete(meshId);
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// Also write to JSONL (retained as export/import/debug/legacy artifact)
|
|
254
651
|
try {
|
|
255
652
|
const line = JSON.stringify(entry) + '\n';
|
|
256
653
|
appendFileSync(filePath, line, { encoding: 'utf-8', mode: 0o600 });
|
|
654
|
+
invalidateLedgerCache(meshId);
|
|
257
655
|
meshLedgerEvents.emit('append', meshId, entry);
|
|
258
656
|
return entry;
|
|
259
657
|
} catch (e: any) {
|
|
@@ -285,8 +683,9 @@ export function appendRemoteLedgerEntries(meshId: string, entries: MeshLedgerEnt
|
|
|
285
683
|
if (entries.length === 0) return { accepted: 0, skippedDuplicate: 0, rejectedInvalid: 0, entries: [] };
|
|
286
684
|
const ledgerPath = getLedgerPath(meshId);
|
|
287
685
|
|
|
288
|
-
//
|
|
289
|
-
|
|
686
|
+
// Dedup against recent entries only — P2P replication is incremental (cursor-based),
|
|
687
|
+
// so duplicates appear in the recent tail, not deep history.
|
|
688
|
+
const existing = new Set(readLedgerEntries(meshId, { tail: 1000 }).map(e => e.id));
|
|
290
689
|
const validEntries: MeshLedgerEntry[] = [];
|
|
291
690
|
let rejectedInvalid = 0;
|
|
292
691
|
let skippedDuplicate = 0;
|
|
@@ -307,9 +706,24 @@ export function appendRemoteLedgerEntries(meshId: string, entries: MeshLedgerEnt
|
|
|
307
706
|
return { accepted: 0, skippedDuplicate, rejectedInvalid, entries: [] };
|
|
308
707
|
}
|
|
309
708
|
|
|
709
|
+
// G2: write to SQLite (primary runtime store); INSERT OR IGNORE dedups by id.
|
|
710
|
+
try {
|
|
711
|
+
MeshRuntimeStore.getInstance().importLedgerEntries(validEntries.map(e => ({
|
|
712
|
+
id: e.id,
|
|
713
|
+
meshId: e.meshId,
|
|
714
|
+
timestamp: e.timestamp,
|
|
715
|
+
kind: e.kind,
|
|
716
|
+
nodeId: e.nodeId ?? null,
|
|
717
|
+
sessionId: e.sessionId ?? null,
|
|
718
|
+
providerType: e.providerType ?? null,
|
|
719
|
+
payload: e.payload ?? {},
|
|
720
|
+
})));
|
|
721
|
+
} catch { /* best-effort; JSONL append below still records the entries */ }
|
|
722
|
+
|
|
310
723
|
try {
|
|
311
724
|
const lines = validEntries.map(e => JSON.stringify(e)).join('\n') + '\n';
|
|
312
725
|
appendFileSync(ledgerPath, lines, { encoding: 'utf-8', mode: 0o600 });
|
|
726
|
+
invalidateLedgerCache(meshId);
|
|
313
727
|
for (const entry of validEntries) {
|
|
314
728
|
meshLedgerEvents.emit('append', meshId, entry);
|
|
315
729
|
}
|
|
@@ -319,103 +733,151 @@ export function appendRemoteLedgerEntries(meshId: string, entries: MeshLedgerEnt
|
|
|
319
733
|
}
|
|
320
734
|
}
|
|
321
735
|
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
736
|
+
// ─── Ledger Read Cache ─────────────────────────
|
|
737
|
+
// Absorbs repeated reads within a single event-processing burst (e.g. agent:stopped
|
|
738
|
+
// triggers shouldSuppressIntentionalCleanupStop, findRecentTerminalLedgerEvidence,
|
|
739
|
+
// hasDispatchAfterTerminal, and getSessionRecoveryContext — all reading the same store).
|
|
740
|
+
// TTL is 100ms: short enough to stay current, long enough to cover one event cycle.
|
|
741
|
+
// Cache is invalidated on every write (append, remote import, compaction).
|
|
742
|
+
|
|
743
|
+
const ledgerReadCache = new Map<string, { entries: MeshLedgerEntry[]; cachedAt: number }>();
|
|
744
|
+
const LEDGER_CACHE_TTL_MS = 100;
|
|
745
|
+
|
|
746
|
+
function readLedgerFile(meshId: string): MeshLedgerEntry[] {
|
|
326
747
|
const filePath = getLedgerPath(meshId);
|
|
327
748
|
if (!existsSync(filePath)) return [];
|
|
328
|
-
|
|
329
749
|
let content: string;
|
|
750
|
+
try { content = readFileSync(filePath, 'utf-8'); } catch { return []; }
|
|
751
|
+
const entries: MeshLedgerEntry[] = [];
|
|
752
|
+
for (const line of content.split('\n')) {
|
|
753
|
+
if (!line.trim()) continue;
|
|
754
|
+
try {
|
|
755
|
+
const entry = JSON.parse(line) as MeshLedgerEntry;
|
|
756
|
+
if (entry.id && entry.kind) entries.push(entry);
|
|
757
|
+
} catch { /* skip malformed lines */ }
|
|
758
|
+
}
|
|
759
|
+
return entries;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
// ─── G2: One-Time JSONL → SQLite Import ─────────
|
|
763
|
+
// On the first SQLite read for a mesh (per store instance), import any legacy
|
|
764
|
+
// JSONL entries into mesh_event_ledger. INSERT OR IGNORE makes this idempotent:
|
|
765
|
+
// dual-written entries are skipped, only pre-cutover legacy entries are added.
|
|
766
|
+
// Keyed by the store instance so MeshRuntimeStore.resetForTests() (fresh DB)
|
|
767
|
+
// naturally re-imports.
|
|
768
|
+
|
|
769
|
+
let ledgerImportStoreRef: MeshRuntimeStore | undefined;
|
|
770
|
+
const ledgerImportDone = new Set<string>();
|
|
771
|
+
|
|
772
|
+
function ensureLedgerImported(store: MeshRuntimeStore, meshId: string): void {
|
|
773
|
+
if (ledgerImportStoreRef !== store) {
|
|
774
|
+
ledgerImportDone.clear();
|
|
775
|
+
ledgerImportStoreRef = store;
|
|
776
|
+
}
|
|
777
|
+
if (ledgerImportDone.has(meshId)) return;
|
|
778
|
+
ledgerImportDone.add(meshId);
|
|
779
|
+
const fileEntries = readLedgerFile(meshId);
|
|
780
|
+
if (fileEntries.length === 0) return;
|
|
781
|
+
try {
|
|
782
|
+
store.importLedgerEntries(fileEntries.map(e => ({
|
|
783
|
+
id: e.id,
|
|
784
|
+
meshId: e.meshId,
|
|
785
|
+
timestamp: e.timestamp,
|
|
786
|
+
kind: e.kind,
|
|
787
|
+
nodeId: e.nodeId ?? null,
|
|
788
|
+
sessionId: e.sessionId ?? null,
|
|
789
|
+
providerType: e.providerType ?? null,
|
|
790
|
+
payload: e.payload ?? {},
|
|
791
|
+
})));
|
|
792
|
+
} catch { /* import is best-effort; reads fall back to JSONL on store failure */ }
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
function readLedgerFromStore(meshId: string): MeshLedgerEntry[] {
|
|
796
|
+
const store = MeshRuntimeStore.getInstance();
|
|
797
|
+
ensureLedgerImported(store, meshId);
|
|
798
|
+
return store.readLedgerEntriesOrdered(meshId).map(r => ({
|
|
799
|
+
id: r.id,
|
|
800
|
+
meshId: r.meshId,
|
|
801
|
+
timestamp: r.timestamp,
|
|
802
|
+
kind: r.kind as MeshLedgerKind,
|
|
803
|
+
...(r.nodeId ? { nodeId: r.nodeId } : {}),
|
|
804
|
+
...(r.sessionId ? { sessionId: r.sessionId } : {}),
|
|
805
|
+
...(r.providerType ? { providerType: r.providerType } : {}),
|
|
806
|
+
payload: (r.payload && typeof r.payload === 'object' ? r.payload : {}) as Record<string, unknown>,
|
|
807
|
+
}));
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
function getCachedRawEntries(meshId: string): MeshLedgerEntry[] {
|
|
811
|
+
const now = Date.now();
|
|
812
|
+
const cached = ledgerReadCache.get(meshId);
|
|
813
|
+
if (cached && now - cached.cachedAt < LEDGER_CACHE_TTL_MS) return cached.entries;
|
|
814
|
+
let entries: MeshLedgerEntry[];
|
|
330
815
|
try {
|
|
331
|
-
|
|
816
|
+
// G2: SQLite mesh_event_ledger is the primary runtime read path.
|
|
817
|
+
entries = readLedgerFromStore(meshId);
|
|
332
818
|
} catch {
|
|
333
|
-
|
|
819
|
+
// Store unavailable — fall back to the JSONL export artifact.
|
|
820
|
+
entries = readLedgerFile(meshId);
|
|
334
821
|
}
|
|
822
|
+
ledgerReadCache.set(meshId, { entries, cachedAt: now });
|
|
823
|
+
return entries;
|
|
824
|
+
}
|
|
335
825
|
|
|
336
|
-
|
|
337
|
-
|
|
826
|
+
function invalidateLedgerCache(meshId: string): void {
|
|
827
|
+
ledgerReadCache.delete(meshId);
|
|
828
|
+
}
|
|
338
829
|
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
830
|
+
/**
|
|
831
|
+
* Test helper: clear all runtime ledger state for a mesh — SQLite rows, read
|
|
832
|
+
* cache, and the one-time import flag. JSONL files are the caller's concern.
|
|
833
|
+
*/
|
|
834
|
+
export function __clearMeshLedgerForTests(meshId: string): void {
|
|
835
|
+
try {
|
|
836
|
+
MeshRuntimeStore.getInstance().clearLedgerForMesh(meshId);
|
|
837
|
+
} catch { /* store unavailable — nothing to clear */ }
|
|
838
|
+
ledgerReadCache.delete(meshId);
|
|
839
|
+
ledgerImportDone.delete(meshId);
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/**
|
|
843
|
+
* Read ledger entries with optional filtering.
|
|
844
|
+
* G2: SQLite (mesh_event_ledger) is the primary read path; legacy JSONL is
|
|
845
|
+
* imported once per store instance and otherwise retained as an
|
|
846
|
+
* export/import/debug artifact only.
|
|
847
|
+
*/
|
|
848
|
+
export function readLedgerEntries(meshId: string, opts?: ReadLedgerOptions): MeshLedgerEntry[] {
|
|
849
|
+
let entries = getCachedRawEntries(meshId);
|
|
348
850
|
|
|
349
|
-
// Apply filters
|
|
350
851
|
if (opts?.since) {
|
|
351
852
|
const sinceDate = new Date(opts.since).getTime();
|
|
352
|
-
if (!isNaN(sinceDate))
|
|
353
|
-
entries = entries.filter(e => new Date(e.timestamp).getTime() >= sinceDate);
|
|
354
|
-
}
|
|
853
|
+
if (!isNaN(sinceDate)) entries = entries.filter(e => new Date(e.timestamp).getTime() >= sinceDate);
|
|
355
854
|
}
|
|
356
|
-
|
|
357
855
|
if (opts?.kind?.length) {
|
|
358
856
|
const kindSet = new Set(opts.kind);
|
|
359
857
|
entries = entries.filter(e => kindSet.has(e.kind));
|
|
360
858
|
}
|
|
361
|
-
|
|
362
|
-
// Apply tail (return last N entries)
|
|
363
859
|
if (opts?.tail && opts.tail > 0 && entries.length > opts.tail) {
|
|
364
860
|
entries = entries.slice(-opts.tail);
|
|
365
861
|
}
|
|
366
|
-
|
|
367
862
|
return entries;
|
|
368
863
|
}
|
|
369
864
|
|
|
370
865
|
/**
|
|
371
|
-
*
|
|
372
|
-
*
|
|
373
|
-
* remote daemons on demand without Cloud/D1 becoming a ledger data-plane.
|
|
374
|
-
*/
|
|
375
|
-
export function readLedgerSlice(meshId: string, opts?: ReadLedgerSliceOptions): MeshLedgerSlice {
|
|
376
|
-
const limit = clampLedgerSliceLimit(opts?.limit);
|
|
377
|
-
let entries = readLedgerEntries(meshId, { since: opts?.since, kind: opts?.kind });
|
|
378
|
-
const afterId = typeof opts?.afterId === 'string' && opts.afterId.trim() ? opts.afterId.trim() : null;
|
|
379
|
-
if (afterId) {
|
|
380
|
-
const index = entries.findIndex(entry => entry.id === afterId);
|
|
381
|
-
entries = index >= 0 ? entries.slice(index + 1) : entries;
|
|
382
|
-
}
|
|
383
|
-
const bounded = entries.slice(0, limit);
|
|
384
|
-
return {
|
|
385
|
-
protocol: 'adhdev.mesh.ledger.slice.v1',
|
|
386
|
-
meshId,
|
|
387
|
-
entries: bounded,
|
|
388
|
-
cursor: {
|
|
389
|
-
afterId,
|
|
390
|
-
nextAfterId: bounded.length ? bounded[bounded.length - 1].id : afterId,
|
|
391
|
-
limit,
|
|
392
|
-
hasMore: entries.length > bounded.length,
|
|
393
|
-
},
|
|
394
|
-
summary: getLedgerSummary(meshId),
|
|
395
|
-
sourceOfTruth: {
|
|
396
|
-
kind: 'local_jsonl',
|
|
397
|
-
path: getLedgerPath(meshId),
|
|
398
|
-
bounded: true,
|
|
399
|
-
maxLimit: MAX_LEDGER_SLICE_LIMIT,
|
|
400
|
-
},
|
|
401
|
-
};
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
/**
|
|
405
|
-
* Get a summary of mesh activity from the ledger.
|
|
866
|
+
* Build a ledger summary from pre-loaded entries. Used by both getLedgerSummary
|
|
867
|
+
* and readLedgerSlice so they share a single getCachedRawEntries() call.
|
|
406
868
|
*/
|
|
407
|
-
|
|
408
|
-
const
|
|
869
|
+
function buildLedgerSummary(meshId: string, entries: MeshLedgerEntry[]): MeshLedgerSummary {
|
|
870
|
+
const archived = readArchivedCounts(meshId);
|
|
409
871
|
const now = Date.now();
|
|
410
872
|
const recentFailureCutoff = now - RECENT_FAILURE_WINDOW_MS;
|
|
411
873
|
|
|
412
874
|
const summary: MeshLedgerSummary = {
|
|
413
875
|
meshId,
|
|
414
|
-
totalEntries: entries.length,
|
|
876
|
+
totalEntries: entries.length + archived.totalArchived,
|
|
415
877
|
taskDispatched: 0,
|
|
416
|
-
taskCompleted:
|
|
417
|
-
taskFailed:
|
|
418
|
-
taskStalled:
|
|
878
|
+
taskCompleted: archived.taskCompleted,
|
|
879
|
+
taskFailed: archived.taskFailed,
|
|
880
|
+
taskStalled: archived.taskStalled,
|
|
419
881
|
sessionLaunched: 0,
|
|
420
882
|
checkpointCreated: 0,
|
|
421
883
|
lastActivityAt: null,
|
|
@@ -450,6 +912,79 @@ export function getLedgerSummary(meshId: string): MeshLedgerSummary {
|
|
|
450
912
|
return summary;
|
|
451
913
|
}
|
|
452
914
|
|
|
915
|
+
/**
|
|
916
|
+
* Read a bounded, cursor-addressable ledger slice for local-first/P2P replication.
|
|
917
|
+
* The result is intentionally small and self-describing so coordinators can query
|
|
918
|
+
* remote daemons on demand without Cloud/D1 becoming a ledger data-plane.
|
|
919
|
+
*/
|
|
920
|
+
export function readLedgerSlice(meshId: string, opts?: ReadLedgerSliceOptions): MeshLedgerSlice {
|
|
921
|
+
const limit = clampLedgerSliceLimit(opts?.limit);
|
|
922
|
+
// Load raw entries once and share between filtering, pagination, and summary.
|
|
923
|
+
const rawEntries = getCachedRawEntries(meshId);
|
|
924
|
+
|
|
925
|
+
let entries: MeshLedgerEntry[] = rawEntries;
|
|
926
|
+
if (opts?.since) {
|
|
927
|
+
const sinceDate = new Date(opts.since).getTime();
|
|
928
|
+
if (!isNaN(sinceDate)) entries = entries.filter(e => new Date(e.timestamp).getTime() >= sinceDate);
|
|
929
|
+
}
|
|
930
|
+
if (opts?.kind?.length) {
|
|
931
|
+
const kindSet = new Set(opts.kind);
|
|
932
|
+
entries = entries.filter(e => kindSet.has(e.kind));
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
const afterId = typeof opts?.afterId === 'string' && opts.afterId.trim() ? opts.afterId.trim() : null;
|
|
936
|
+
if (afterId) {
|
|
937
|
+
const index = entries.findIndex(entry => entry.id === afterId);
|
|
938
|
+
entries = index >= 0 ? entries.slice(index + 1) : entries;
|
|
939
|
+
}
|
|
940
|
+
const bounded = entries.slice(0, limit);
|
|
941
|
+
return {
|
|
942
|
+
protocol: 'adhdev.mesh.ledger.slice.v1',
|
|
943
|
+
meshId,
|
|
944
|
+
entries: bounded,
|
|
945
|
+
cursor: {
|
|
946
|
+
afterId,
|
|
947
|
+
nextAfterId: bounded.length ? bounded[bounded.length - 1].id : afterId,
|
|
948
|
+
limit,
|
|
949
|
+
hasMore: entries.length > bounded.length,
|
|
950
|
+
},
|
|
951
|
+
summary: buildLedgerSummary(meshId, rawEntries),
|
|
952
|
+
sourceOfTruth: {
|
|
953
|
+
kind: 'local_jsonl',
|
|
954
|
+
path: getLedgerPath(meshId),
|
|
955
|
+
bounded: true,
|
|
956
|
+
maxLimit: MAX_LEDGER_SLICE_LIMIT,
|
|
957
|
+
},
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
/**
|
|
962
|
+
* G4: Read a bounded ledger slice from the SQLite mesh_event_ledger table.
|
|
963
|
+
* This is the preferred P2P reconcile read path; JSONL files are retained as
|
|
964
|
+
* export/import/debug/legacy artifacts only.
|
|
965
|
+
*
|
|
966
|
+
* Returns a shape structurally compatible with MeshLedgerSlice (minus the
|
|
967
|
+
* JSONL-specific `summary` and `sourceOfTruth.path` fields) so callers can
|
|
968
|
+
* pass it to buildMeshLedgerReplicaEvidence without modification.
|
|
969
|
+
*/
|
|
970
|
+
export function readLedgerSliceFromStore(meshId: string, opts?: ReadLedgerSliceOptions): ReturnType<typeof MeshRuntimeStore.prototype.readLedgerSlice> {
|
|
971
|
+
return MeshRuntimeStore.getInstance().readLedgerSlice(meshId, {
|
|
972
|
+
afterId: opts?.afterId,
|
|
973
|
+
since: opts?.since,
|
|
974
|
+
// ReadLedgerSliceOptions allows kind as array; SQLite path takes a single kind string.
|
|
975
|
+
// Pass first kind value if provided; callers needing multi-kind filtering should use readLedgerSlice (JSONL).
|
|
976
|
+
kind: opts?.kind?.length ? opts.kind[0] : undefined,
|
|
977
|
+
limit: opts?.limit,
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
/**
|
|
982
|
+
* Get a summary of mesh activity from the ledger.
|
|
983
|
+
*/
|
|
984
|
+
export function getLedgerSummary(meshId: string): MeshLedgerSummary {
|
|
985
|
+
return buildLedgerSummary(meshId, getCachedRawEntries(meshId));
|
|
986
|
+
}
|
|
987
|
+
|
|
453
988
|
// ─── Recovery Context ───────────────────────────
|
|
454
989
|
|
|
455
990
|
export interface SessionRecoveryContext {
|
|
@@ -484,46 +1019,64 @@ export function getSessionRecoveryContext(
|
|
|
484
1019
|
},
|
|
485
1020
|
): SessionRecoveryContext {
|
|
486
1021
|
const maxRetries = opts.maxRetries ?? 1;
|
|
487
|
-
|
|
1022
|
+
// tail:500 is sufficient — task_dispatched is never archived (only terminal kinds are),
|
|
1023
|
+
// so dispatch history is always present. The 30-min failure window means we never need
|
|
1024
|
+
// more than a few dozen recent entries for consecutiveNodeFailures. Bounding to 500
|
|
1025
|
+
// avoids a full O(n) scan for meshes with many historical entries.
|
|
1026
|
+
const entries = readLedgerEntries(meshId, { tail: 500 });
|
|
488
1027
|
|
|
489
|
-
//
|
|
1028
|
+
// Single backward pass: find last task_dispatched AND count consecutive recent failures.
|
|
1029
|
+
const now = Date.now();
|
|
1030
|
+
const recentWindow = now - RECENT_FAILURE_WINDOW_MS;
|
|
490
1031
|
let lastDispatch: MeshLedgerEntry | null = null;
|
|
1032
|
+
let consecutiveNodeFailures = 0;
|
|
1033
|
+
let failureCountDone = false;
|
|
491
1034
|
for (let i = entries.length - 1; i >= 0; i--) {
|
|
492
1035
|
const e = entries[i];
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
1036
|
+
const ts = new Date(e.timestamp).getTime();
|
|
1037
|
+
|
|
1038
|
+
// Failure counting: scan until we exit the recent window or hit a chain-breaker
|
|
1039
|
+
if (!failureCountDone) {
|
|
1040
|
+
if (ts < recentWindow) {
|
|
1041
|
+
failureCountDone = true;
|
|
1042
|
+
} else if (opts.nodeId && e.nodeId !== opts.nodeId) {
|
|
1043
|
+
// Entry for a different node — skip for failure counting but continue scanning for dispatch
|
|
1044
|
+
} else if (e.kind === 'task_failed') {
|
|
1045
|
+
if (!isIntentionalCleanupStopEntry(e)) consecutiveNodeFailures++;
|
|
1046
|
+
} else if (e.kind === 'task_completed' || e.kind === 'task_dispatched') {
|
|
1047
|
+
// A completion or new dispatch breaks the consecutive failure chain
|
|
1048
|
+
failureCountDone = true;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// Dispatch search: find the last dispatch matching this session or node
|
|
1053
|
+
if (lastDispatch === null && e.kind === 'task_dispatched') {
|
|
1054
|
+
if (opts.sessionId && e.sessionId === opts.sessionId) { lastDispatch = e; }
|
|
1055
|
+
else if (!opts.sessionId && opts.nodeId && e.nodeId === opts.nodeId) { lastDispatch = e; }
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
// Stop once both tasks are done
|
|
1059
|
+
if (lastDispatch !== null && failureCountDone) break;
|
|
496
1060
|
}
|
|
497
1061
|
|
|
498
1062
|
const lastTaskMessage = typeof lastDispatch?.payload?.message === 'string'
|
|
499
1063
|
? lastDispatch.payload.message
|
|
500
1064
|
: null;
|
|
501
1065
|
|
|
502
|
-
// Count
|
|
503
|
-
|
|
504
|
-
const recentWindow = now - RECENT_FAILURE_WINDOW_MS;
|
|
505
|
-
let consecutiveNodeFailures = 0;
|
|
506
|
-
for (let i = entries.length - 1; i >= 0; i--) {
|
|
507
|
-
const e = entries[i];
|
|
508
|
-
if (new Date(e.timestamp).getTime() < recentWindow) break;
|
|
509
|
-
if (opts.nodeId && e.nodeId !== opts.nodeId) continue;
|
|
510
|
-
if (e.kind === 'task_failed') {
|
|
511
|
-
if (isIntentionalCleanupStopEntry(e)) continue;
|
|
512
|
-
consecutiveNodeFailures++;
|
|
513
|
-
} else if (e.kind === 'task_completed' || e.kind === 'task_dispatched') {
|
|
514
|
-
// A completion or new dispatch breaks the consecutive failure chain
|
|
515
|
-
break;
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
// Count how many times the same task was attempted (match by message prefix)
|
|
1066
|
+
// Count how many times the same task was attempted.
|
|
1067
|
+
// Prefer exact taskId match (payload.taskId) to avoid 200-char prefix collisions.
|
|
520
1068
|
let taskAttemptCount = 0;
|
|
521
|
-
if (
|
|
522
|
-
const
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
if (e.payload
|
|
526
|
-
|
|
1069
|
+
if (lastDispatch) {
|
|
1070
|
+
const taskId = typeof lastDispatch.payload?.taskId === 'string' ? lastDispatch.payload.taskId : null;
|
|
1071
|
+
if (taskId) {
|
|
1072
|
+
for (const e of entries) {
|
|
1073
|
+
if (e.kind === 'task_dispatched' && e.payload?.taskId === taskId) taskAttemptCount++;
|
|
1074
|
+
}
|
|
1075
|
+
} else if (lastTaskMessage) {
|
|
1076
|
+
const prefix = lastTaskMessage.slice(0, 200);
|
|
1077
|
+
for (const e of entries) {
|
|
1078
|
+
if (e.kind === 'task_dispatched' && typeof e.payload?.message === 'string') {
|
|
1079
|
+
if (e.payload.message.startsWith(prefix)) taskAttemptCount++;
|
|
527
1080
|
}
|
|
528
1081
|
}
|
|
529
1082
|
}
|
|
@@ -573,7 +1126,8 @@ function rotateLedgerFile(meshId: string, currentPath: string): void {
|
|
|
573
1126
|
|
|
574
1127
|
try {
|
|
575
1128
|
renameSync(currentPath, getRotatedPath(meshId, index));
|
|
576
|
-
} catch {
|
|
1129
|
+
} catch (e: any) {
|
|
577
1130
|
// Rotation failed — the next append will just grow the file
|
|
1131
|
+
process.stderr.write(`[adhdev-mesh] Ledger rotation failed for mesh ${meshId}: ${e?.message || e}. File will continue to grow.\n`);
|
|
578
1132
|
}
|
|
579
1133
|
}
|