@adhdev/daemon-core 0.9.82-rc.34 → 0.9.82-rc.340
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 +8 -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 +46 -2
- package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
- package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
- package/dist/cli-adapters/provider-cli-adapter.d.ts +116 -64
- package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
- package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
- package/dist/cli-adapters/provider-cli-shared.d.ts +53 -0
- package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
- package/dist/cli-adapters/resolve-executable.d.ts +14 -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/cli-manager.d.ts +2 -1
- package/dist/commands/handler.d.ts +110 -0
- package/dist/commands/mesh-coordinator.d.ts +85 -1
- package/dist/commands/router.d.ts +308 -1
- package/dist/commands/upgrade-helper.d.ts +12 -0
- package/dist/config/chat-history.d.ts +9 -0
- package/dist/config/config.d.ts +5 -0
- package/dist/config/mesh-config.d.ts +77 -1
- 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 +23 -0
- package/dist/git/git-types.d.ts +2 -50
- package/dist/git/index.d.ts +2 -0
- package/dist/index.d.ts +52 -13
- package/dist/index.js +39439 -14533
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +39000 -14215
- 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 +46 -0
- package/dist/mesh/contracts.d.ts +164 -0
- package/dist/mesh/coordinator-prompt.d.ts +36 -0
- package/dist/mesh/coordinator-registry.d.ts +59 -0
- package/dist/mesh/mesh-active-work.d.ts +174 -0
- package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
- package/dist/mesh/mesh-events-coordinator.d.ts +169 -0
- package/dist/mesh/mesh-events-pending.d.ts +45 -0
- package/dist/mesh/mesh-events-stale.d.ts +40 -0
- package/dist/mesh/mesh-events-utils.d.ts +66 -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 -3
- package/dist/mesh/mesh-ledger.d.ts +77 -1
- package/dist/mesh/mesh-missions.d.ts +116 -0
- package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
- package/dist/mesh/mesh-refine-batch.d.ts +68 -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 +418 -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-work-queue.d.ts +208 -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 +135 -0
- package/dist/providers/acp-provider-instance.d.ts +2 -0
- package/dist/providers/approval-utils.d.ts +13 -0
- package/dist/providers/chat-message-normalization.d.ts +12 -0
- package/dist/providers/cli-provider-instance.d.ts +76 -3
- package/dist/providers/contracts.d.ts +139 -6
- package/dist/providers/external-sources.d.ts +71 -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/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 +13 -0
- package/dist/providers/provider-instance.d.ts +13 -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 +85 -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 +69 -0
- package/dist/providers/spec/cli-adapter.d.ts +217 -0
- package/dist/providers/spec/evaluator.d.ts +23 -0
- package/dist/providers/spec/fsm-driver.d.ts +306 -0
- package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
- package/dist/providers/spec/fsm-loader.d.ts +14 -0
- package/dist/providers/spec/fsm-types.d.ts +144 -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 +180 -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 +295 -13
- 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/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 +55 -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 +1 -0
- package/src/cli-adapter-types.ts +47 -2
- package/src/cli-adapters/cli-script-runner.ts +421 -0
- package/src/cli-adapters/cli-state-engine.ts +1215 -0
- package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
- package/src/cli-adapters/provider-cli-adapter.ts +774 -1141
- package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
- package/src/cli-adapters/provider-cli-parse.ts +13 -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 +100 -11
- package/src/cli-adapters/pty-transport.ts +2 -1
- package/src/cli-adapters/raw-terminal-io.ts +252 -0
- package/src/cli-adapters/resolve-executable.ts +90 -0
- package/src/cli-adapters/session-host-transport.ts +2 -1
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -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.ts +1823 -62
- package/src/commands/cli-manager.ts +286 -14
- package/src/commands/handler.ts +809 -2
- package/src/commands/mesh-coordinator.ts +332 -122
- package/src/commands/router.ts +7433 -1317
- package/src/commands/stream-commands.ts +8 -0
- package/src/commands/upgrade-helper.ts +81 -30
- package/src/config/chat-history.ts +483 -24
- package/src/config/config.ts +12 -0
- package/src/config/mesh-config.ts +388 -6
- package/src/config/recent-activity.ts +8 -2
- package/src/daemon/dev-auto-implement.ts +3 -2
- package/src/daemon/dev-cli-debug.ts +10 -1
- 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 +55 -14
- package/src/git/git-diff.ts +53 -0
- package/src/git/git-executor.ts +12 -0
- package/src/git/git-status.ts +574 -43
- package/src/git/git-types.ts +14 -62
- package/src/git/git-worktree.ts +8 -1
- package/src/git/index.ts +16 -0
- package/src/index.ts +146 -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/log-redactor.ts +100 -0
- package/src/logging/log-tail-reader.ts +220 -0
- package/src/logging/logger.ts +2 -1
- package/src/mesh/contracts.ts +329 -0
- package/src/mesh/coordinator-prompt.ts +234 -31
- package/src/mesh/coordinator-registry.ts +121 -0
- package/src/mesh/mesh-active-work.ts +623 -0
- package/src/mesh/mesh-delivery-policy.ts +315 -0
- package/src/mesh/mesh-events-coordinator.ts +2144 -0
- package/src/mesh/mesh-events-pending.ts +508 -0
- package/src/mesh/mesh-events-stale.ts +290 -0
- package/src/mesh/mesh-events-utils.ts +300 -0
- package/src/mesh/mesh-events.ts +30 -1035
- package/src/mesh/mesh-fast-forward.ts +839 -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 -5
- package/src/mesh/mesh-ledger.ts +589 -102
- package/src/mesh/mesh-missions.ts +248 -0
- package/src/mesh/mesh-reconcile-loop.ts +822 -0
- package/src/mesh/mesh-refine-batch.ts +197 -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 +1626 -0
- package/src/mesh/mesh-task-stats.ts +154 -0
- package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
- package/src/mesh/mesh-work-queue.ts +888 -141
- package/src/mesh/preview-freshness.ts +118 -0
- package/src/mesh/refine-config.ts +423 -0
- package/src/mesh/worktree-bootstrap-config.ts +331 -0
- package/src/providers/acp-provider-instance.ts +25 -9
- package/src/providers/approval-utils.d.ts +4 -0
- package/src/providers/approval-utils.ts +47 -5
- package/src/providers/chat-message-normalization.ts +45 -5
- package/src/providers/cli-provider-instance.ts +1038 -99
- 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/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/dispatcher.ts +340 -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 +30 -0
- package/src/providers/provider-instance.ts +10 -1
- package/src/providers/provider-loader.ts +670 -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 +262 -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 +168 -0
- package/src/providers/spec/cli-adapter.ts +986 -0
- package/src/providers/spec/evaluator.ts +345 -0
- package/src/providers/spec/fsm-driver.ts +993 -0
- package/src/providers/spec/fsm-evaluator.ts +255 -0
- package/src/providers/spec/fsm-loader.ts +120 -0
- package/src/providers/spec/fsm-types.ts +238 -0
- package/src/providers/spec/native-history-executor.ts +1136 -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 +226 -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 +378 -14
- 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/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,21 @@ 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'
|
|
39
45
|
;
|
|
40
46
|
|
|
41
47
|
export interface MeshLedgerEntry {
|
|
@@ -61,6 +67,44 @@ export function isIntentionalCleanupStopEntry(entry: Pick<MeshLedgerEntry, 'kind
|
|
|
61
67
|
|| payload.source === 'mesh_remove_node');
|
|
62
68
|
}
|
|
63
69
|
|
|
70
|
+
export type MeshWorkerResultStatus = 'completed' | 'failed' | 'blocked' | 'partial' | 'unknown';
|
|
71
|
+
export type MeshProcessArtifactKind = 'process' | 'log' | 'port' | 'window' | 'session' | 'file' | 'url' | 'other';
|
|
72
|
+
|
|
73
|
+
export interface MeshValidationResultArtifact {
|
|
74
|
+
command?: string;
|
|
75
|
+
status: 'passed' | 'failed' | 'skipped' | 'unknown';
|
|
76
|
+
durationMs?: number;
|
|
77
|
+
outputPath?: string;
|
|
78
|
+
summary?: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface MeshProcessArtifact {
|
|
82
|
+
kind: MeshProcessArtifactKind;
|
|
83
|
+
id?: string;
|
|
84
|
+
label?: string;
|
|
85
|
+
locator?: string;
|
|
86
|
+
pid?: number;
|
|
87
|
+
port?: number;
|
|
88
|
+
url?: string;
|
|
89
|
+
path?: string;
|
|
90
|
+
sessionId?: string;
|
|
91
|
+
keepRunning?: boolean;
|
|
92
|
+
metadata?: Record<string, unknown>;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface MeshWorkerResultArtifact {
|
|
96
|
+
status: MeshWorkerResultStatus;
|
|
97
|
+
classification?: string;
|
|
98
|
+
changedFiles: string[];
|
|
99
|
+
validationResults: MeshValidationResultArtifact[];
|
|
100
|
+
gitStatus?: Record<string, unknown>;
|
|
101
|
+
processArtifacts: MeshProcessArtifact[];
|
|
102
|
+
errors: string[];
|
|
103
|
+
nextAction?: string;
|
|
104
|
+
requiresUserAction: boolean;
|
|
105
|
+
source: 'explicit_metadata' | 'final_summary_json' | 'default';
|
|
106
|
+
}
|
|
107
|
+
|
|
64
108
|
export interface MeshTaskCompletionEvidence {
|
|
65
109
|
source: 'agent_status_event';
|
|
66
110
|
event: 'agent:generating_completed' | 'agent:ready';
|
|
@@ -74,6 +118,7 @@ export interface MeshTaskCompletionEvidence {
|
|
|
74
118
|
providerSessionId?: string;
|
|
75
119
|
finalSummaryAvailable: boolean;
|
|
76
120
|
};
|
|
121
|
+
workerResult: MeshWorkerResultArtifact;
|
|
77
122
|
git: {
|
|
78
123
|
status: 'deferred';
|
|
79
124
|
reason: string;
|
|
@@ -96,6 +141,7 @@ export interface BuildTaskCompletionEvidenceOptions {
|
|
|
96
141
|
providerType?: string;
|
|
97
142
|
providerSessionId?: string;
|
|
98
143
|
finalSummary?: string;
|
|
144
|
+
workerResult?: Record<string, unknown>;
|
|
99
145
|
completedAt?: string;
|
|
100
146
|
}
|
|
101
147
|
|
|
@@ -160,8 +206,19 @@ export interface AppendRemoteLedgerResult {
|
|
|
160
206
|
// ─── Constants ──────────────────────────────────
|
|
161
207
|
|
|
162
208
|
const LEDGER_DIR_NAME = 'mesh-ledger';
|
|
163
|
-
const MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB
|
|
209
|
+
const MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB — full rotation threshold
|
|
210
|
+
const COMPACT_THRESHOLD_BYTES = 2 * 1024 * 1024; // 2 MB — compaction threshold
|
|
211
|
+
const ARCHIVE_TERMINAL_OLDER_THAN_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
|
164
212
|
const RECENT_FAILURE_WINDOW_MS = 30 * 60 * 1000; // 30 minutes
|
|
213
|
+
|
|
214
|
+
// Kinds that accumulate indefinitely and are safe to archive after ARCHIVE_TERMINAL_OLDER_THAN_MS.
|
|
215
|
+
// Non-terminal kinds (dispatched, sessions, nodes, checkpoints) are always kept in the active file.
|
|
216
|
+
const ARCHIVABLE_KINDS: ReadonlySet<MeshLedgerKind> = new Set([
|
|
217
|
+
'task_completed',
|
|
218
|
+
'task_failed',
|
|
219
|
+
'task_stalled',
|
|
220
|
+
'recovery_attempted',
|
|
221
|
+
] as MeshLedgerKind[]);
|
|
165
222
|
const DEFAULT_LEDGER_SLICE_LIMIT = 100;
|
|
166
223
|
export const MAX_LEDGER_SLICE_LIMIT = 500;
|
|
167
224
|
|
|
@@ -186,8 +243,258 @@ function getRotatedPath(meshId: string, index: number): string {
|
|
|
186
243
|
return join(getLedgerDir(), `${safe}.${index}.jsonl`);
|
|
187
244
|
}
|
|
188
245
|
|
|
246
|
+
function getArchivePath(meshId: string): string {
|
|
247
|
+
const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
248
|
+
return join(getLedgerDir(), `${safe}.archive.jsonl`);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function getRotatedArchivePath(meshId: string, index: number): string {
|
|
252
|
+
const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
253
|
+
return join(getLedgerDir(), `${safe}.archive.${index}.jsonl`);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function getArchivedCountsPath(meshId: string): string {
|
|
257
|
+
const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
258
|
+
return join(getLedgerDir(), `${safe}.archived-counts.json`);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function rotateArchiveFile(meshId: string, archivePath: string): void {
|
|
262
|
+
let index = 1;
|
|
263
|
+
while (existsSync(getRotatedArchivePath(meshId, index))) {
|
|
264
|
+
index++;
|
|
265
|
+
if (index > 5) break;
|
|
266
|
+
}
|
|
267
|
+
if (index > 5) index = 5;
|
|
268
|
+
try {
|
|
269
|
+
renameSync(archivePath, getRotatedArchivePath(meshId, index));
|
|
270
|
+
} catch (e: any) {
|
|
271
|
+
process.stderr.write(`[adhdev-mesh] Archive rotation failed for mesh ${meshId}: ${e?.message || e}\n`);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
interface LedgerArchivedCounts {
|
|
276
|
+
taskCompleted: number;
|
|
277
|
+
taskFailed: number;
|
|
278
|
+
taskStalled: number;
|
|
279
|
+
recoveryAttempted: number;
|
|
280
|
+
totalArchived: number;
|
|
281
|
+
lastArchivedAt: string;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function readArchivedCounts(meshId: string): LedgerArchivedCounts {
|
|
285
|
+
const path = getArchivedCountsPath(meshId);
|
|
286
|
+
if (!existsSync(path)) return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: '' };
|
|
287
|
+
try { return JSON.parse(readFileSync(path, 'utf-8')) as LedgerArchivedCounts; } catch { return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: '' }; }
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function updateArchivedCounts(meshId: string, archived: MeshLedgerEntry[]): void {
|
|
291
|
+
const counts = readArchivedCounts(meshId);
|
|
292
|
+
for (const e of archived) {
|
|
293
|
+
if (e.kind === 'task_completed') counts.taskCompleted++;
|
|
294
|
+
else if (e.kind === 'task_failed') counts.taskFailed++;
|
|
295
|
+
else if (e.kind === 'task_stalled') counts.taskStalled++;
|
|
296
|
+
else if (e.kind === 'recovery_attempted') counts.recoveryAttempted++;
|
|
297
|
+
}
|
|
298
|
+
counts.totalArchived += archived.length;
|
|
299
|
+
counts.lastArchivedAt = new Date().toISOString();
|
|
300
|
+
try { writeFileSync(getArchivedCountsPath(meshId), JSON.stringify(counts), { encoding: 'utf-8', mode: 0o600 }); } catch { /* best-effort */ }
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// ─── Worker Result Footer ───────────────────────
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Footer to append to worker task messages so workers output structured results
|
|
307
|
+
* that the daemon parses via extractJsonObjectFromSummary / normalizeMeshWorkerResult.
|
|
308
|
+
*
|
|
309
|
+
* Usage: append buildWorkerTaskFooter() to the task message in mesh_send_task /
|
|
310
|
+
* mesh_enqueue_task. The coordinator prompt rules instruct coordinators to do this.
|
|
311
|
+
*/
|
|
312
|
+
export function buildWorkerTaskFooter(): string {
|
|
313
|
+
return `
|
|
314
|
+
|
|
315
|
+
---
|
|
316
|
+
When your task is done, end your final response with a JSON code block in this exact format (omit fields that don't apply):
|
|
317
|
+
\`\`\`json
|
|
318
|
+
{
|
|
319
|
+
"status": "completed",
|
|
320
|
+
"changedFiles": ["src/foo.ts", "tests/foo.test.ts"],
|
|
321
|
+
"gitStatus": { "branch": "feat/your-branch", "committed": true, "pushed": false },
|
|
322
|
+
"validationResults": [{ "command": "npm test", "status": "passed" }],
|
|
323
|
+
"errors": [],
|
|
324
|
+
"nextAction": "optional guidance for the coordinator"
|
|
325
|
+
}
|
|
326
|
+
\`\`\`
|
|
327
|
+
Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// ─── Ledger Compaction ──────────────────────────
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Compact the active ledger file for a mesh by moving old terminal entries
|
|
334
|
+
* (task_completed, task_failed, task_stalled, recovery_attempted older than 7 days)
|
|
335
|
+
* to <meshId>.archive.jsonl, keeping the active file lean.
|
|
336
|
+
*
|
|
337
|
+
* Non-terminal entries (dispatch, sessions, node lifecycle) are always retained.
|
|
338
|
+
* Called automatically from appendLedgerEntry when the file exceeds COMPACT_THRESHOLD_BYTES.
|
|
339
|
+
*/
|
|
340
|
+
export function compactLedger(meshId: string): { archivedCount: number; retainedCount: number } {
|
|
341
|
+
const filePath = getLedgerPath(meshId);
|
|
342
|
+
if (!existsSync(filePath)) return { archivedCount: 0, retainedCount: 0 };
|
|
343
|
+
|
|
344
|
+
const cutoff = Date.now() - ARCHIVE_TERMINAL_OLDER_THAN_MS;
|
|
345
|
+
const entries = readLedgerEntries(meshId);
|
|
346
|
+
|
|
347
|
+
const keep: MeshLedgerEntry[] = [];
|
|
348
|
+
const archive: MeshLedgerEntry[] = [];
|
|
349
|
+
for (const entry of entries) {
|
|
350
|
+
if (ARCHIVABLE_KINDS.has(entry.kind) && new Date(entry.timestamp).getTime() < cutoff) {
|
|
351
|
+
archive.push(entry);
|
|
352
|
+
} else {
|
|
353
|
+
keep.push(entry);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
if (archive.length === 0) return { archivedCount: 0, retainedCount: keep.length };
|
|
358
|
+
|
|
359
|
+
// Append archived entries to the archive file, rotate if it exceeds 50MB
|
|
360
|
+
const archivePath = getArchivePath(meshId);
|
|
361
|
+
try {
|
|
362
|
+
if (existsSync(archivePath) && statSync(archivePath).size > 50 * 1024 * 1024) {
|
|
363
|
+
rotateArchiveFile(meshId, archivePath);
|
|
364
|
+
}
|
|
365
|
+
const archiveLines = archive.map(e => JSON.stringify(e)).join('\n') + '\n';
|
|
366
|
+
appendFileSync(archivePath, archiveLines, { encoding: 'utf-8', mode: 0o600 });
|
|
367
|
+
updateArchivedCounts(meshId, archive);
|
|
368
|
+
} catch (e: any) {
|
|
369
|
+
process.stderr.write(`[adhdev-mesh] Ledger archive write failed for mesh ${meshId}: ${e?.message || e}\n`);
|
|
370
|
+
return { archivedCount: 0, retainedCount: entries.length };
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// Rewrite active file with retained entries only
|
|
374
|
+
try {
|
|
375
|
+
const keepLines = keep.length ? keep.map(e => JSON.stringify(e)).join('\n') + '\n' : '';
|
|
376
|
+
writeFileSync(filePath, keepLines, { encoding: 'utf-8', mode: 0o600 });
|
|
377
|
+
invalidateLedgerCache(meshId);
|
|
378
|
+
} catch (e: any) {
|
|
379
|
+
process.stderr.write(`[adhdev-mesh] Ledger compaction rewrite failed for mesh ${meshId}: ${e?.message || e}\n`);
|
|
380
|
+
return { archivedCount: archive.length, retainedCount: keep.length };
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// G2: mirror the compaction in SQLite so the runtime store matches the active
|
|
384
|
+
// ledger set. Archived entries live on in the JSONL archive files (export/debug).
|
|
385
|
+
try {
|
|
386
|
+
MeshRuntimeStore.getInstance().deleteLedgerEntries(meshId, archive.map(e => e.id));
|
|
387
|
+
invalidateLedgerCache(meshId);
|
|
388
|
+
} catch { /* best-effort; summary counts absorb the difference via archived counts */ }
|
|
389
|
+
|
|
390
|
+
return { archivedCount: archive.length, retainedCount: keep.length };
|
|
391
|
+
}
|
|
392
|
+
|
|
189
393
|
// ─── Core API ───────────────────────────────────
|
|
190
394
|
|
|
395
|
+
function readNonEmptyString(value: unknown): string | undefined {
|
|
396
|
+
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function readStringArray(value: unknown): string[] {
|
|
400
|
+
if (!Array.isArray(value)) return [];
|
|
401
|
+
return value.map(item => readNonEmptyString(item)).filter(Boolean) as string[];
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function extractJsonObjectFromSummary(summary?: string): Record<string, unknown> | undefined {
|
|
405
|
+
const text = readNonEmptyString(summary);
|
|
406
|
+
if (!text) return undefined;
|
|
407
|
+
const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
408
|
+
const candidates = [fenced?.[1], text].filter(Boolean) as string[];
|
|
409
|
+
for (const candidate of candidates) {
|
|
410
|
+
const trimmed = candidate.trim();
|
|
411
|
+
if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) continue;
|
|
412
|
+
try {
|
|
413
|
+
const parsed = JSON.parse(trimmed);
|
|
414
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
415
|
+
// Require at least one mesh worker result field to avoid false positives
|
|
416
|
+
// (e.g. JSON from tool call outputs or log lines in the final summary).
|
|
417
|
+
const hasWorkerShape = 'status' in parsed && (
|
|
418
|
+
'changedFiles' in parsed || 'errors' in parsed
|
|
419
|
+
|| 'gitStatus' in parsed || 'nextAction' in parsed
|
|
420
|
+
|| 'validationResults' in parsed
|
|
421
|
+
);
|
|
422
|
+
if (hasWorkerShape) return parsed;
|
|
423
|
+
}
|
|
424
|
+
} catch { /* try next candidate */ }
|
|
425
|
+
}
|
|
426
|
+
return undefined;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function normalizeValidationResults(value: unknown): MeshValidationResultArtifact[] {
|
|
430
|
+
if (!Array.isArray(value)) return [];
|
|
431
|
+
return value
|
|
432
|
+
.filter(item => item && typeof item === 'object' && !Array.isArray(item))
|
|
433
|
+
.map((item: any) => {
|
|
434
|
+
const status = ['passed', 'failed', 'skipped', 'unknown'].includes(item.status) ? item.status : 'unknown';
|
|
435
|
+
return {
|
|
436
|
+
...(readNonEmptyString(item.command) ? { command: readNonEmptyString(item.command) } : {}),
|
|
437
|
+
status,
|
|
438
|
+
...(Number.isFinite(Number(item.durationMs)) ? { durationMs: Number(item.durationMs) } : {}),
|
|
439
|
+
...(readNonEmptyString(item.outputPath) ? { outputPath: readNonEmptyString(item.outputPath) } : {}),
|
|
440
|
+
...(readNonEmptyString(item.summary) ? { summary: readNonEmptyString(item.summary) } : {}),
|
|
441
|
+
};
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function normalizeProcessArtifacts(value: unknown): MeshProcessArtifact[] {
|
|
446
|
+
if (!Array.isArray(value)) return [];
|
|
447
|
+
const kinds = new Set(['process', 'log', 'port', 'window', 'session', 'file', 'url', 'other']);
|
|
448
|
+
return value
|
|
449
|
+
.filter(item => item && typeof item === 'object' && !Array.isArray(item))
|
|
450
|
+
.map((item: any) => ({
|
|
451
|
+
kind: kinds.has(item.kind) ? item.kind : 'other',
|
|
452
|
+
...(readNonEmptyString(item.id) ? { id: readNonEmptyString(item.id) } : {}),
|
|
453
|
+
...(readNonEmptyString(item.label) ? { label: readNonEmptyString(item.label) } : {}),
|
|
454
|
+
...(readNonEmptyString(item.locator) ? { locator: readNonEmptyString(item.locator) } : {}),
|
|
455
|
+
...(Number.isFinite(Number(item.pid)) ? { pid: Number(item.pid) } : {}),
|
|
456
|
+
...(Number.isFinite(Number(item.port)) ? { port: Number(item.port) } : {}),
|
|
457
|
+
...(readNonEmptyString(item.url) ? { url: readNonEmptyString(item.url) } : {}),
|
|
458
|
+
...(readNonEmptyString(item.path) ? { path: readNonEmptyString(item.path) } : {}),
|
|
459
|
+
...(readNonEmptyString(item.sessionId) ? { sessionId: readNonEmptyString(item.sessionId) } : {}),
|
|
460
|
+
...(typeof item.keepRunning === 'boolean' ? { keepRunning: item.keepRunning } : {}),
|
|
461
|
+
...(item.metadata && typeof item.metadata === 'object' && !Array.isArray(item.metadata) ? { metadata: item.metadata as Record<string, unknown> } : {}),
|
|
462
|
+
}));
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
export function normalizeMeshWorkerResult(input?: Record<string, unknown>, source: MeshWorkerResultArtifact['source'] = 'explicit_metadata'): MeshWorkerResultArtifact {
|
|
466
|
+
const raw = input && typeof input === 'object' ? input : {};
|
|
467
|
+
const status = ['completed', 'failed', 'blocked', 'partial', 'unknown'].includes(String(raw.status))
|
|
468
|
+
? raw.status as MeshWorkerResultStatus
|
|
469
|
+
: 'unknown';
|
|
470
|
+
const gitStatus = raw.gitStatus && typeof raw.gitStatus === 'object' && !Array.isArray(raw.gitStatus)
|
|
471
|
+
? raw.gitStatus as Record<string, unknown>
|
|
472
|
+
: undefined;
|
|
473
|
+
return {
|
|
474
|
+
status,
|
|
475
|
+
...(readNonEmptyString(raw.classification) ? { classification: readNonEmptyString(raw.classification) } : {}),
|
|
476
|
+
changedFiles: readStringArray(raw.changedFiles),
|
|
477
|
+
validationResults: normalizeValidationResults(raw.validationResults),
|
|
478
|
+
...(gitStatus ? { gitStatus } : {}),
|
|
479
|
+
processArtifacts: normalizeProcessArtifacts(raw.processArtifacts),
|
|
480
|
+
errors: readStringArray(raw.errors),
|
|
481
|
+
...(readNonEmptyString(raw.nextAction) ? { nextAction: readNonEmptyString(raw.nextAction) } : {}),
|
|
482
|
+
requiresUserAction: raw.requiresUserAction === true,
|
|
483
|
+
source,
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function resolveWorkerResult(opts: BuildTaskCompletionEvidenceOptions): MeshWorkerResultArtifact {
|
|
488
|
+
if (opts.workerResult && typeof opts.workerResult === 'object') {
|
|
489
|
+
return normalizeMeshWorkerResult(opts.workerResult, 'explicit_metadata');
|
|
490
|
+
}
|
|
491
|
+
const parsed = extractJsonObjectFromSummary(opts.finalSummary);
|
|
492
|
+
if (parsed) {
|
|
493
|
+
return normalizeMeshWorkerResult(parsed, 'final_summary_json');
|
|
494
|
+
}
|
|
495
|
+
return normalizeMeshWorkerResult(undefined, 'default');
|
|
496
|
+
}
|
|
497
|
+
|
|
191
498
|
export function buildTaskCompletionEvidence(opts: BuildTaskCompletionEvidenceOptions): MeshTaskCompletionEvidence {
|
|
192
499
|
const providerSessionId = opts.providerSessionId?.trim() || undefined;
|
|
193
500
|
const providerType = opts.providerType?.trim() || undefined;
|
|
@@ -204,6 +511,7 @@ export function buildTaskCompletionEvidence(opts: BuildTaskCompletionEvidenceOpt
|
|
|
204
511
|
providerSessionId,
|
|
205
512
|
finalSummaryAvailable: typeof opts.finalSummary === 'string' && opts.finalSummary.trim().length > 0,
|
|
206
513
|
},
|
|
514
|
+
workerResult: resolveWorkerResult(opts),
|
|
207
515
|
git: {
|
|
208
516
|
status: 'deferred',
|
|
209
517
|
reason: 'ordinary_completion_git_status_not_checked',
|
|
@@ -239,21 +547,44 @@ export function appendLedgerEntry(
|
|
|
239
547
|
|
|
240
548
|
const filePath = getLedgerPath(meshId);
|
|
241
549
|
|
|
242
|
-
//
|
|
550
|
+
// Compact or rotate based on file size
|
|
243
551
|
if (existsSync(filePath)) {
|
|
244
552
|
try {
|
|
245
553
|
const stat = statSync(filePath);
|
|
246
554
|
if (stat.size >= MAX_FILE_SIZE_BYTES) {
|
|
247
555
|
rotateLedgerFile(meshId, filePath);
|
|
556
|
+
} else if (stat.size >= COMPACT_THRESHOLD_BYTES) {
|
|
557
|
+
compactLedger(meshId);
|
|
248
558
|
}
|
|
249
559
|
} catch {
|
|
250
560
|
// stat failed — proceed with append anyway
|
|
251
561
|
}
|
|
252
562
|
}
|
|
253
563
|
|
|
564
|
+
// Write to SQLite (G2: primary runtime read/write path)
|
|
565
|
+
try {
|
|
566
|
+
MeshRuntimeStore.getInstance().appendLedgerEntry({
|
|
567
|
+
id: entry.id,
|
|
568
|
+
meshId: entry.meshId,
|
|
569
|
+
timestamp: entry.timestamp,
|
|
570
|
+
kind: entry.kind,
|
|
571
|
+
nodeId: entry.nodeId ?? null,
|
|
572
|
+
sessionId: entry.sessionId ?? null,
|
|
573
|
+
providerType: entry.providerType ?? null,
|
|
574
|
+
payload: entry.payload,
|
|
575
|
+
});
|
|
576
|
+
} catch {
|
|
577
|
+
// SQLite write failed but the JSONL append below still records the entry.
|
|
578
|
+
// Reset the one-time import flag so the next read re-imports from JSONL
|
|
579
|
+
// and the store self-heals instead of silently missing this entry.
|
|
580
|
+
ledgerImportDone.delete(meshId);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// Also write to JSONL (retained as export/import/debug/legacy artifact)
|
|
254
584
|
try {
|
|
255
585
|
const line = JSON.stringify(entry) + '\n';
|
|
256
586
|
appendFileSync(filePath, line, { encoding: 'utf-8', mode: 0o600 });
|
|
587
|
+
invalidateLedgerCache(meshId);
|
|
257
588
|
meshLedgerEvents.emit('append', meshId, entry);
|
|
258
589
|
return entry;
|
|
259
590
|
} catch (e: any) {
|
|
@@ -285,8 +616,9 @@ export function appendRemoteLedgerEntries(meshId: string, entries: MeshLedgerEnt
|
|
|
285
616
|
if (entries.length === 0) return { accepted: 0, skippedDuplicate: 0, rejectedInvalid: 0, entries: [] };
|
|
286
617
|
const ledgerPath = getLedgerPath(meshId);
|
|
287
618
|
|
|
288
|
-
//
|
|
289
|
-
|
|
619
|
+
// Dedup against recent entries only — P2P replication is incremental (cursor-based),
|
|
620
|
+
// so duplicates appear in the recent tail, not deep history.
|
|
621
|
+
const existing = new Set(readLedgerEntries(meshId, { tail: 1000 }).map(e => e.id));
|
|
290
622
|
const validEntries: MeshLedgerEntry[] = [];
|
|
291
623
|
let rejectedInvalid = 0;
|
|
292
624
|
let skippedDuplicate = 0;
|
|
@@ -307,9 +639,24 @@ export function appendRemoteLedgerEntries(meshId: string, entries: MeshLedgerEnt
|
|
|
307
639
|
return { accepted: 0, skippedDuplicate, rejectedInvalid, entries: [] };
|
|
308
640
|
}
|
|
309
641
|
|
|
642
|
+
// G2: write to SQLite (primary runtime store); INSERT OR IGNORE dedups by id.
|
|
643
|
+
try {
|
|
644
|
+
MeshRuntimeStore.getInstance().importLedgerEntries(validEntries.map(e => ({
|
|
645
|
+
id: e.id,
|
|
646
|
+
meshId: e.meshId,
|
|
647
|
+
timestamp: e.timestamp,
|
|
648
|
+
kind: e.kind,
|
|
649
|
+
nodeId: e.nodeId ?? null,
|
|
650
|
+
sessionId: e.sessionId ?? null,
|
|
651
|
+
providerType: e.providerType ?? null,
|
|
652
|
+
payload: e.payload ?? {},
|
|
653
|
+
})));
|
|
654
|
+
} catch { /* best-effort; JSONL append below still records the entries */ }
|
|
655
|
+
|
|
310
656
|
try {
|
|
311
657
|
const lines = validEntries.map(e => JSON.stringify(e)).join('\n') + '\n';
|
|
312
658
|
appendFileSync(ledgerPath, lines, { encoding: 'utf-8', mode: 0o600 });
|
|
659
|
+
invalidateLedgerCache(meshId);
|
|
313
660
|
for (const entry of validEntries) {
|
|
314
661
|
meshLedgerEvents.emit('append', meshId, entry);
|
|
315
662
|
}
|
|
@@ -319,103 +666,151 @@ export function appendRemoteLedgerEntries(meshId: string, entries: MeshLedgerEnt
|
|
|
319
666
|
}
|
|
320
667
|
}
|
|
321
668
|
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
669
|
+
// ─── Ledger Read Cache ─────────────────────────
|
|
670
|
+
// Absorbs repeated reads within a single event-processing burst (e.g. agent:stopped
|
|
671
|
+
// triggers shouldSuppressIntentionalCleanupStop, findRecentTerminalLedgerEvidence,
|
|
672
|
+
// hasDispatchAfterTerminal, and getSessionRecoveryContext — all reading the same store).
|
|
673
|
+
// TTL is 100ms: short enough to stay current, long enough to cover one event cycle.
|
|
674
|
+
// Cache is invalidated on every write (append, remote import, compaction).
|
|
675
|
+
|
|
676
|
+
const ledgerReadCache = new Map<string, { entries: MeshLedgerEntry[]; cachedAt: number }>();
|
|
677
|
+
const LEDGER_CACHE_TTL_MS = 100;
|
|
678
|
+
|
|
679
|
+
function readLedgerFile(meshId: string): MeshLedgerEntry[] {
|
|
326
680
|
const filePath = getLedgerPath(meshId);
|
|
327
681
|
if (!existsSync(filePath)) return [];
|
|
328
|
-
|
|
329
682
|
let content: string;
|
|
683
|
+
try { content = readFileSync(filePath, 'utf-8'); } catch { return []; }
|
|
684
|
+
const entries: MeshLedgerEntry[] = [];
|
|
685
|
+
for (const line of content.split('\n')) {
|
|
686
|
+
if (!line.trim()) continue;
|
|
687
|
+
try {
|
|
688
|
+
const entry = JSON.parse(line) as MeshLedgerEntry;
|
|
689
|
+
if (entry.id && entry.kind) entries.push(entry);
|
|
690
|
+
} catch { /* skip malformed lines */ }
|
|
691
|
+
}
|
|
692
|
+
return entries;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// ─── G2: One-Time JSONL → SQLite Import ─────────
|
|
696
|
+
// On the first SQLite read for a mesh (per store instance), import any legacy
|
|
697
|
+
// JSONL entries into mesh_event_ledger. INSERT OR IGNORE makes this idempotent:
|
|
698
|
+
// dual-written entries are skipped, only pre-cutover legacy entries are added.
|
|
699
|
+
// Keyed by the store instance so MeshRuntimeStore.resetForTests() (fresh DB)
|
|
700
|
+
// naturally re-imports.
|
|
701
|
+
|
|
702
|
+
let ledgerImportStoreRef: MeshRuntimeStore | undefined;
|
|
703
|
+
const ledgerImportDone = new Set<string>();
|
|
704
|
+
|
|
705
|
+
function ensureLedgerImported(store: MeshRuntimeStore, meshId: string): void {
|
|
706
|
+
if (ledgerImportStoreRef !== store) {
|
|
707
|
+
ledgerImportDone.clear();
|
|
708
|
+
ledgerImportStoreRef = store;
|
|
709
|
+
}
|
|
710
|
+
if (ledgerImportDone.has(meshId)) return;
|
|
711
|
+
ledgerImportDone.add(meshId);
|
|
712
|
+
const fileEntries = readLedgerFile(meshId);
|
|
713
|
+
if (fileEntries.length === 0) return;
|
|
330
714
|
try {
|
|
331
|
-
|
|
715
|
+
store.importLedgerEntries(fileEntries.map(e => ({
|
|
716
|
+
id: e.id,
|
|
717
|
+
meshId: e.meshId,
|
|
718
|
+
timestamp: e.timestamp,
|
|
719
|
+
kind: e.kind,
|
|
720
|
+
nodeId: e.nodeId ?? null,
|
|
721
|
+
sessionId: e.sessionId ?? null,
|
|
722
|
+
providerType: e.providerType ?? null,
|
|
723
|
+
payload: e.payload ?? {},
|
|
724
|
+
})));
|
|
725
|
+
} catch { /* import is best-effort; reads fall back to JSONL on store failure */ }
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
function readLedgerFromStore(meshId: string): MeshLedgerEntry[] {
|
|
729
|
+
const store = MeshRuntimeStore.getInstance();
|
|
730
|
+
ensureLedgerImported(store, meshId);
|
|
731
|
+
return store.readLedgerEntriesOrdered(meshId).map(r => ({
|
|
732
|
+
id: r.id,
|
|
733
|
+
meshId: r.meshId,
|
|
734
|
+
timestamp: r.timestamp,
|
|
735
|
+
kind: r.kind as MeshLedgerKind,
|
|
736
|
+
...(r.nodeId ? { nodeId: r.nodeId } : {}),
|
|
737
|
+
...(r.sessionId ? { sessionId: r.sessionId } : {}),
|
|
738
|
+
...(r.providerType ? { providerType: r.providerType } : {}),
|
|
739
|
+
payload: (r.payload && typeof r.payload === 'object' ? r.payload : {}) as Record<string, unknown>,
|
|
740
|
+
}));
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
function getCachedRawEntries(meshId: string): MeshLedgerEntry[] {
|
|
744
|
+
const now = Date.now();
|
|
745
|
+
const cached = ledgerReadCache.get(meshId);
|
|
746
|
+
if (cached && now - cached.cachedAt < LEDGER_CACHE_TTL_MS) return cached.entries;
|
|
747
|
+
let entries: MeshLedgerEntry[];
|
|
748
|
+
try {
|
|
749
|
+
// G2: SQLite mesh_event_ledger is the primary runtime read path.
|
|
750
|
+
entries = readLedgerFromStore(meshId);
|
|
332
751
|
} catch {
|
|
333
|
-
|
|
752
|
+
// Store unavailable — fall back to the JSONL export artifact.
|
|
753
|
+
entries = readLedgerFile(meshId);
|
|
334
754
|
}
|
|
755
|
+
ledgerReadCache.set(meshId, { entries, cachedAt: now });
|
|
756
|
+
return entries;
|
|
757
|
+
}
|
|
335
758
|
|
|
336
|
-
|
|
337
|
-
|
|
759
|
+
function invalidateLedgerCache(meshId: string): void {
|
|
760
|
+
ledgerReadCache.delete(meshId);
|
|
761
|
+
}
|
|
338
762
|
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
763
|
+
/**
|
|
764
|
+
* Test helper: clear all runtime ledger state for a mesh — SQLite rows, read
|
|
765
|
+
* cache, and the one-time import flag. JSONL files are the caller's concern.
|
|
766
|
+
*/
|
|
767
|
+
export function __clearMeshLedgerForTests(meshId: string): void {
|
|
768
|
+
try {
|
|
769
|
+
MeshRuntimeStore.getInstance().clearLedgerForMesh(meshId);
|
|
770
|
+
} catch { /* store unavailable — nothing to clear */ }
|
|
771
|
+
ledgerReadCache.delete(meshId);
|
|
772
|
+
ledgerImportDone.delete(meshId);
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* Read ledger entries with optional filtering.
|
|
777
|
+
* G2: SQLite (mesh_event_ledger) is the primary read path; legacy JSONL is
|
|
778
|
+
* imported once per store instance and otherwise retained as an
|
|
779
|
+
* export/import/debug artifact only.
|
|
780
|
+
*/
|
|
781
|
+
export function readLedgerEntries(meshId: string, opts?: ReadLedgerOptions): MeshLedgerEntry[] {
|
|
782
|
+
let entries = getCachedRawEntries(meshId);
|
|
348
783
|
|
|
349
|
-
// Apply filters
|
|
350
784
|
if (opts?.since) {
|
|
351
785
|
const sinceDate = new Date(opts.since).getTime();
|
|
352
|
-
if (!isNaN(sinceDate))
|
|
353
|
-
entries = entries.filter(e => new Date(e.timestamp).getTime() >= sinceDate);
|
|
354
|
-
}
|
|
786
|
+
if (!isNaN(sinceDate)) entries = entries.filter(e => new Date(e.timestamp).getTime() >= sinceDate);
|
|
355
787
|
}
|
|
356
|
-
|
|
357
788
|
if (opts?.kind?.length) {
|
|
358
789
|
const kindSet = new Set(opts.kind);
|
|
359
790
|
entries = entries.filter(e => kindSet.has(e.kind));
|
|
360
791
|
}
|
|
361
|
-
|
|
362
|
-
// Apply tail (return last N entries)
|
|
363
792
|
if (opts?.tail && opts.tail > 0 && entries.length > opts.tail) {
|
|
364
793
|
entries = entries.slice(-opts.tail);
|
|
365
794
|
}
|
|
366
|
-
|
|
367
795
|
return entries;
|
|
368
796
|
}
|
|
369
797
|
|
|
370
798
|
/**
|
|
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.
|
|
799
|
+
* Build a ledger summary from pre-loaded entries. Used by both getLedgerSummary
|
|
800
|
+
* and readLedgerSlice so they share a single getCachedRawEntries() call.
|
|
406
801
|
*/
|
|
407
|
-
|
|
408
|
-
const
|
|
802
|
+
function buildLedgerSummary(meshId: string, entries: MeshLedgerEntry[]): MeshLedgerSummary {
|
|
803
|
+
const archived = readArchivedCounts(meshId);
|
|
409
804
|
const now = Date.now();
|
|
410
805
|
const recentFailureCutoff = now - RECENT_FAILURE_WINDOW_MS;
|
|
411
806
|
|
|
412
807
|
const summary: MeshLedgerSummary = {
|
|
413
808
|
meshId,
|
|
414
|
-
totalEntries: entries.length,
|
|
809
|
+
totalEntries: entries.length + archived.totalArchived,
|
|
415
810
|
taskDispatched: 0,
|
|
416
|
-
taskCompleted:
|
|
417
|
-
taskFailed:
|
|
418
|
-
taskStalled:
|
|
811
|
+
taskCompleted: archived.taskCompleted,
|
|
812
|
+
taskFailed: archived.taskFailed,
|
|
813
|
+
taskStalled: archived.taskStalled,
|
|
419
814
|
sessionLaunched: 0,
|
|
420
815
|
checkpointCreated: 0,
|
|
421
816
|
lastActivityAt: null,
|
|
@@ -450,6 +845,79 @@ export function getLedgerSummary(meshId: string): MeshLedgerSummary {
|
|
|
450
845
|
return summary;
|
|
451
846
|
}
|
|
452
847
|
|
|
848
|
+
/**
|
|
849
|
+
* Read a bounded, cursor-addressable ledger slice for local-first/P2P replication.
|
|
850
|
+
* The result is intentionally small and self-describing so coordinators can query
|
|
851
|
+
* remote daemons on demand without Cloud/D1 becoming a ledger data-plane.
|
|
852
|
+
*/
|
|
853
|
+
export function readLedgerSlice(meshId: string, opts?: ReadLedgerSliceOptions): MeshLedgerSlice {
|
|
854
|
+
const limit = clampLedgerSliceLimit(opts?.limit);
|
|
855
|
+
// Load raw entries once and share between filtering, pagination, and summary.
|
|
856
|
+
const rawEntries = getCachedRawEntries(meshId);
|
|
857
|
+
|
|
858
|
+
let entries: MeshLedgerEntry[] = rawEntries;
|
|
859
|
+
if (opts?.since) {
|
|
860
|
+
const sinceDate = new Date(opts.since).getTime();
|
|
861
|
+
if (!isNaN(sinceDate)) entries = entries.filter(e => new Date(e.timestamp).getTime() >= sinceDate);
|
|
862
|
+
}
|
|
863
|
+
if (opts?.kind?.length) {
|
|
864
|
+
const kindSet = new Set(opts.kind);
|
|
865
|
+
entries = entries.filter(e => kindSet.has(e.kind));
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
const afterId = typeof opts?.afterId === 'string' && opts.afterId.trim() ? opts.afterId.trim() : null;
|
|
869
|
+
if (afterId) {
|
|
870
|
+
const index = entries.findIndex(entry => entry.id === afterId);
|
|
871
|
+
entries = index >= 0 ? entries.slice(index + 1) : entries;
|
|
872
|
+
}
|
|
873
|
+
const bounded = entries.slice(0, limit);
|
|
874
|
+
return {
|
|
875
|
+
protocol: 'adhdev.mesh.ledger.slice.v1',
|
|
876
|
+
meshId,
|
|
877
|
+
entries: bounded,
|
|
878
|
+
cursor: {
|
|
879
|
+
afterId,
|
|
880
|
+
nextAfterId: bounded.length ? bounded[bounded.length - 1].id : afterId,
|
|
881
|
+
limit,
|
|
882
|
+
hasMore: entries.length > bounded.length,
|
|
883
|
+
},
|
|
884
|
+
summary: buildLedgerSummary(meshId, rawEntries),
|
|
885
|
+
sourceOfTruth: {
|
|
886
|
+
kind: 'local_jsonl',
|
|
887
|
+
path: getLedgerPath(meshId),
|
|
888
|
+
bounded: true,
|
|
889
|
+
maxLimit: MAX_LEDGER_SLICE_LIMIT,
|
|
890
|
+
},
|
|
891
|
+
};
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
/**
|
|
895
|
+
* G4: Read a bounded ledger slice from the SQLite mesh_event_ledger table.
|
|
896
|
+
* This is the preferred P2P reconcile read path; JSONL files are retained as
|
|
897
|
+
* export/import/debug/legacy artifacts only.
|
|
898
|
+
*
|
|
899
|
+
* Returns a shape structurally compatible with MeshLedgerSlice (minus the
|
|
900
|
+
* JSONL-specific `summary` and `sourceOfTruth.path` fields) so callers can
|
|
901
|
+
* pass it to buildMeshLedgerReplicaEvidence without modification.
|
|
902
|
+
*/
|
|
903
|
+
export function readLedgerSliceFromStore(meshId: string, opts?: ReadLedgerSliceOptions): ReturnType<typeof MeshRuntimeStore.prototype.readLedgerSlice> {
|
|
904
|
+
return MeshRuntimeStore.getInstance().readLedgerSlice(meshId, {
|
|
905
|
+
afterId: opts?.afterId,
|
|
906
|
+
since: opts?.since,
|
|
907
|
+
// ReadLedgerSliceOptions allows kind as array; SQLite path takes a single kind string.
|
|
908
|
+
// Pass first kind value if provided; callers needing multi-kind filtering should use readLedgerSlice (JSONL).
|
|
909
|
+
kind: opts?.kind?.length ? opts.kind[0] : undefined,
|
|
910
|
+
limit: opts?.limit,
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
/**
|
|
915
|
+
* Get a summary of mesh activity from the ledger.
|
|
916
|
+
*/
|
|
917
|
+
export function getLedgerSummary(meshId: string): MeshLedgerSummary {
|
|
918
|
+
return buildLedgerSummary(meshId, getCachedRawEntries(meshId));
|
|
919
|
+
}
|
|
920
|
+
|
|
453
921
|
// ─── Recovery Context ───────────────────────────
|
|
454
922
|
|
|
455
923
|
export interface SessionRecoveryContext {
|
|
@@ -484,46 +952,64 @@ export function getSessionRecoveryContext(
|
|
|
484
952
|
},
|
|
485
953
|
): SessionRecoveryContext {
|
|
486
954
|
const maxRetries = opts.maxRetries ?? 1;
|
|
487
|
-
|
|
955
|
+
// tail:500 is sufficient — task_dispatched is never archived (only terminal kinds are),
|
|
956
|
+
// so dispatch history is always present. The 30-min failure window means we never need
|
|
957
|
+
// more than a few dozen recent entries for consecutiveNodeFailures. Bounding to 500
|
|
958
|
+
// avoids a full O(n) scan for meshes with many historical entries.
|
|
959
|
+
const entries = readLedgerEntries(meshId, { tail: 500 });
|
|
488
960
|
|
|
489
|
-
//
|
|
961
|
+
// Single backward pass: find last task_dispatched AND count consecutive recent failures.
|
|
962
|
+
const now = Date.now();
|
|
963
|
+
const recentWindow = now - RECENT_FAILURE_WINDOW_MS;
|
|
490
964
|
let lastDispatch: MeshLedgerEntry | null = null;
|
|
965
|
+
let consecutiveNodeFailures = 0;
|
|
966
|
+
let failureCountDone = false;
|
|
491
967
|
for (let i = entries.length - 1; i >= 0; i--) {
|
|
492
968
|
const e = entries[i];
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
969
|
+
const ts = new Date(e.timestamp).getTime();
|
|
970
|
+
|
|
971
|
+
// Failure counting: scan until we exit the recent window or hit a chain-breaker
|
|
972
|
+
if (!failureCountDone) {
|
|
973
|
+
if (ts < recentWindow) {
|
|
974
|
+
failureCountDone = true;
|
|
975
|
+
} else if (opts.nodeId && e.nodeId !== opts.nodeId) {
|
|
976
|
+
// Entry for a different node — skip for failure counting but continue scanning for dispatch
|
|
977
|
+
} else if (e.kind === 'task_failed') {
|
|
978
|
+
if (!isIntentionalCleanupStopEntry(e)) consecutiveNodeFailures++;
|
|
979
|
+
} else if (e.kind === 'task_completed' || e.kind === 'task_dispatched') {
|
|
980
|
+
// A completion or new dispatch breaks the consecutive failure chain
|
|
981
|
+
failureCountDone = true;
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
// Dispatch search: find the last dispatch matching this session or node
|
|
986
|
+
if (lastDispatch === null && e.kind === 'task_dispatched') {
|
|
987
|
+
if (opts.sessionId && e.sessionId === opts.sessionId) { lastDispatch = e; }
|
|
988
|
+
else if (!opts.sessionId && opts.nodeId && e.nodeId === opts.nodeId) { lastDispatch = e; }
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
// Stop once both tasks are done
|
|
992
|
+
if (lastDispatch !== null && failureCountDone) break;
|
|
496
993
|
}
|
|
497
994
|
|
|
498
995
|
const lastTaskMessage = typeof lastDispatch?.payload?.message === 'string'
|
|
499
996
|
? lastDispatch.payload.message
|
|
500
997
|
: null;
|
|
501
998
|
|
|
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)
|
|
999
|
+
// Count how many times the same task was attempted.
|
|
1000
|
+
// Prefer exact taskId match (payload.taskId) to avoid 200-char prefix collisions.
|
|
520
1001
|
let taskAttemptCount = 0;
|
|
521
|
-
if (
|
|
522
|
-
const
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
if (e.payload
|
|
526
|
-
|
|
1002
|
+
if (lastDispatch) {
|
|
1003
|
+
const taskId = typeof lastDispatch.payload?.taskId === 'string' ? lastDispatch.payload.taskId : null;
|
|
1004
|
+
if (taskId) {
|
|
1005
|
+
for (const e of entries) {
|
|
1006
|
+
if (e.kind === 'task_dispatched' && e.payload?.taskId === taskId) taskAttemptCount++;
|
|
1007
|
+
}
|
|
1008
|
+
} else if (lastTaskMessage) {
|
|
1009
|
+
const prefix = lastTaskMessage.slice(0, 200);
|
|
1010
|
+
for (const e of entries) {
|
|
1011
|
+
if (e.kind === 'task_dispatched' && typeof e.payload?.message === 'string') {
|
|
1012
|
+
if (e.payload.message.startsWith(prefix)) taskAttemptCount++;
|
|
527
1013
|
}
|
|
528
1014
|
}
|
|
529
1015
|
}
|
|
@@ -573,7 +1059,8 @@ function rotateLedgerFile(meshId: string, currentPath: string): void {
|
|
|
573
1059
|
|
|
574
1060
|
try {
|
|
575
1061
|
renameSync(currentPath, getRotatedPath(meshId, index));
|
|
576
|
-
} catch {
|
|
1062
|
+
} catch (e: any) {
|
|
577
1063
|
// Rotation failed — the next append will just grow the file
|
|
1064
|
+
process.stderr.write(`[adhdev-mesh] Ledger rotation failed for mesh ${meshId}: ${e?.message || e}. File will continue to grow.\n`);
|
|
578
1065
|
}
|
|
579
1066
|
}
|