@adhdev/daemon-core 0.9.82-rc.35 → 0.9.82-rc.351

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.
Files changed (318) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +8 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/build-info.d.ts +37 -0
  4. package/dist/chat/source-machine.d.ts +166 -0
  5. package/dist/chat/source-resolver.d.ts +104 -0
  6. package/dist/chat/subscription-updates.d.ts +1 -0
  7. package/dist/cli-adapter-types.d.ts +46 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +116 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +53 -0
  14. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  15. package/dist/cli-adapters/resolve-executable.d.ts +14 -0
  16. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  17. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  18. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  19. package/dist/commands/cli-manager.d.ts +2 -1
  20. package/dist/commands/handler.d.ts +110 -0
  21. package/dist/commands/mesh-coordinator.d.ts +85 -1
  22. package/dist/commands/router.d.ts +324 -1
  23. package/dist/commands/upgrade-helper.d.ts +12 -0
  24. package/dist/config/chat-history.d.ts +9 -0
  25. package/dist/config/config.d.ts +5 -0
  26. package/dist/config/mesh-config.d.ts +77 -1
  27. package/dist/detection/ide-detector.d.ts +13 -0
  28. package/dist/detection/win32-ide-version.d.ts +37 -0
  29. package/dist/git/change-impact-config.d.ts +159 -0
  30. package/dist/git/git-commands.d.ts +11 -1
  31. package/dist/git/git-diff.d.ts +6 -0
  32. package/dist/git/git-executor.d.ts +11 -0
  33. package/dist/git/git-status.d.ts +23 -0
  34. package/dist/git/git-types.d.ts +2 -50
  35. package/dist/git/index.d.ts +2 -0
  36. package/dist/index.d.ts +53 -13
  37. package/dist/index.js +39817 -14303
  38. package/dist/index.js.map +1 -1
  39. package/dist/index.mjs +41436 -16047
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/installer.d.ts +1 -4
  42. package/dist/ipc/local-ipc-server.d.ts +91 -0
  43. package/dist/launch.d.ts +1 -1
  44. package/dist/logging/async-batch-writer.d.ts +10 -0
  45. package/dist/logging/log-redactor.d.ts +24 -0
  46. package/dist/logging/log-tail-reader.d.ts +46 -0
  47. package/dist/mesh/contracts.d.ts +164 -0
  48. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  49. package/dist/mesh/coordinator-registry.d.ts +59 -0
  50. package/dist/mesh/mesh-active-work.d.ts +174 -0
  51. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  52. package/dist/mesh/mesh-events-coordinator.d.ts +169 -0
  53. package/dist/mesh/mesh-events-pending.d.ts +55 -0
  54. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  55. package/dist/mesh/mesh-events-utils.d.ts +62 -0
  56. package/dist/mesh/mesh-events.d.ts +6 -49
  57. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  58. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  59. package/dist/mesh/mesh-init.d.ts +86 -0
  60. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  61. package/dist/mesh/mesh-ledger.d.ts +77 -1
  62. package/dist/mesh/mesh-missions.d.ts +164 -0
  63. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  64. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  65. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  66. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  67. package/dist/mesh/mesh-routing.d.ts +70 -0
  68. package/dist/mesh/mesh-runtime-store.d.ts +420 -0
  69. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  70. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  71. package/dist/mesh/mesh-work-queue.d.ts +218 -5
  72. package/dist/mesh/preview-freshness.d.ts +18 -0
  73. package/dist/mesh/refine-config.d.ts +216 -0
  74. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  75. package/dist/providers/acp-provider-instance.d.ts +2 -0
  76. package/dist/providers/approval-utils.d.ts +13 -0
  77. package/dist/providers/chat-message-normalization.d.ts +12 -0
  78. package/dist/providers/cli-provider-instance.d.ts +77 -3
  79. package/dist/providers/contracts.d.ts +139 -6
  80. package/dist/providers/external-sources.d.ts +71 -0
  81. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  82. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  83. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  84. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  85. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  86. package/dist/providers/native-history/index.d.ts +13 -0
  87. package/dist/providers/provider-instance-manager.d.ts +14 -0
  88. package/dist/providers/provider-instance.d.ts +15 -1
  89. package/dist/providers/provider-loader.d.ts +26 -4
  90. package/dist/providers/provider-trust.d.ts +31 -0
  91. package/dist/providers/read-chat-contract.d.ts +29 -0
  92. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  93. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  94. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  95. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  96. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  97. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  98. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  99. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  100. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  101. package/dist/providers/sdk/v1/index.d.ts +30 -0
  102. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  103. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  104. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  105. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  106. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  107. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  108. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  109. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  110. package/dist/providers/spec/adapter.d.ts +69 -0
  111. package/dist/providers/spec/cli-adapter.d.ts +217 -0
  112. package/dist/providers/spec/evaluator.d.ts +23 -0
  113. package/dist/providers/spec/fsm-driver.d.ts +322 -0
  114. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  115. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  116. package/dist/providers/spec/fsm-types.d.ts +144 -0
  117. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  118. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  119. package/dist/providers/spec/route.d.ts +4 -0
  120. package/dist/providers/spec/types.d.ts +180 -0
  121. package/dist/providers/status-monitor.d.ts +7 -7
  122. package/dist/providers/transcript-v2.d.ts +176 -0
  123. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  124. package/dist/providers/working-dir.d.ts +17 -0
  125. package/dist/repo-mesh-types.d.ts +295 -13
  126. package/dist/sessions/registry.d.ts +6 -0
  127. package/dist/shared-types-extra.d.ts +2 -4
  128. package/dist/shared-types.d.ts +59 -2
  129. package/dist/status/normalize.d.ts +1 -1
  130. package/dist/status/normalize.js +1 -0
  131. package/dist/status/normalize.js.map +1 -1
  132. package/dist/status/normalize.mjs +1 -0
  133. package/dist/status/normalize.mjs.map +1 -1
  134. package/dist/status/reporter.d.ts +2 -0
  135. package/dist/status/snapshot.d.ts +26 -0
  136. package/dist/system/load-better-sqlite3.d.ts +21 -0
  137. package/dist/types.d.ts +5 -0
  138. package/package.json +7 -3
  139. package/src/agent-stream/poller.ts +2 -3
  140. package/src/agent-stream/provider-adapter.ts +1 -1
  141. package/src/boot/daemon-lifecycle.ts +55 -12
  142. package/src/boot/process-hardening.ts +89 -0
  143. package/src/build-info.ts +73 -0
  144. package/src/chat/source-machine.ts +534 -0
  145. package/src/chat/source-resolver.ts +0 -0
  146. package/src/chat/subscription-updates.ts +20 -1
  147. package/src/cli-adapter-types.d.ts +1 -0
  148. package/src/cli-adapter-types.ts +47 -2
  149. package/src/cli-adapters/cli-script-runner.ts +421 -0
  150. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  151. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  152. package/src/cli-adapters/provider-cli-adapter.ts +774 -1141
  153. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  154. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  155. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  156. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  157. package/src/cli-adapters/provider-cli-shared.ts +100 -11
  158. package/src/cli-adapters/pty-transport.ts +2 -1
  159. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  160. package/src/cli-adapters/resolve-executable.ts +90 -0
  161. package/src/cli-adapters/session-host-transport.ts +2 -1
  162. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  163. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  164. package/src/cli-adapters/terminal-screen.ts +16 -81
  165. package/src/commands/chat-commands.ts +1823 -62
  166. package/src/commands/cli-manager.ts +304 -14
  167. package/src/commands/handler.ts +809 -2
  168. package/src/commands/mesh-coordinator.ts +332 -122
  169. package/src/commands/router.ts +7505 -1311
  170. package/src/commands/stream-commands.ts +8 -0
  171. package/src/commands/upgrade-helper.ts +81 -30
  172. package/src/config/chat-history.ts +483 -24
  173. package/src/config/config.ts +12 -0
  174. package/src/config/mesh-config.ts +388 -6
  175. package/src/config/recent-activity.ts +8 -2
  176. package/src/daemon/dev-auto-implement.ts +3 -2
  177. package/src/daemon/dev-cli-debug.ts +10 -1
  178. package/src/detection/cli-detector.ts +28 -9
  179. package/src/detection/ide-detector.ts +55 -16
  180. package/src/detection/win32-ide-version.ts +106 -0
  181. package/src/git/change-impact-config.ts +354 -0
  182. package/src/git/git-commands.ts +55 -14
  183. package/src/git/git-diff.ts +53 -0
  184. package/src/git/git-executor.ts +12 -0
  185. package/src/git/git-status.ts +574 -43
  186. package/src/git/git-types.ts +14 -62
  187. package/src/git/git-worktree.ts +8 -1
  188. package/src/git/index.ts +16 -0
  189. package/src/index.ts +151 -12
  190. package/src/installer.d.ts +1 -1
  191. package/src/installer.ts +8 -6
  192. package/src/ipc/local-ipc-server.ts +278 -0
  193. package/src/launch.d.ts +1 -1
  194. package/src/launch.ts +37 -28
  195. package/src/logging/async-batch-writer.ts +55 -0
  196. package/src/logging/log-redactor.ts +100 -0
  197. package/src/logging/log-tail-reader.ts +220 -0
  198. package/src/logging/logger.ts +2 -1
  199. package/src/mesh/contracts.ts +329 -0
  200. package/src/mesh/coordinator-prompt.ts +234 -31
  201. package/src/mesh/coordinator-registry.ts +121 -0
  202. package/src/mesh/mesh-active-work.ts +667 -0
  203. package/src/mesh/mesh-delivery-policy.ts +315 -0
  204. package/src/mesh/mesh-events-coordinator.ts +2303 -0
  205. package/src/mesh/mesh-events-pending.ts +567 -0
  206. package/src/mesh/mesh-events-stale.ts +307 -0
  207. package/src/mesh/mesh-events-utils.ts +381 -0
  208. package/src/mesh/mesh-events.ts +30 -1035
  209. package/src/mesh/mesh-fast-forward.ts +839 -0
  210. package/src/mesh/mesh-host-ownership.ts +73 -0
  211. package/src/mesh/mesh-init.ts +260 -0
  212. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  213. package/src/mesh/mesh-ledger.ts +590 -102
  214. package/src/mesh/mesh-missions.ts +322 -0
  215. package/src/mesh/mesh-reconcile-loop.ts +989 -0
  216. package/src/mesh/mesh-refine-batch.ts +197 -0
  217. package/src/mesh/mesh-refine-status.ts +231 -0
  218. package/src/mesh/mesh-review-inbox.ts +307 -0
  219. package/src/mesh/mesh-routing.ts +291 -0
  220. package/src/mesh/mesh-runtime-store.ts +1664 -0
  221. package/src/mesh/mesh-task-stats.ts +161 -0
  222. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  223. package/src/mesh/mesh-work-queue.ts +901 -141
  224. package/src/mesh/preview-freshness.ts +118 -0
  225. package/src/mesh/refine-config.ts +423 -0
  226. package/src/mesh/worktree-bootstrap-config.ts +331 -0
  227. package/src/providers/acp-provider-instance.ts +25 -9
  228. package/src/providers/approval-utils.d.ts +4 -0
  229. package/src/providers/approval-utils.ts +47 -5
  230. package/src/providers/chat-message-normalization.ts +45 -5
  231. package/src/providers/cli-provider-instance.ts +1041 -99
  232. package/src/providers/contracts.d.ts +55 -0
  233. package/src/providers/contracts.ts +150 -6
  234. package/src/providers/extension-provider-instance.ts +12 -7
  235. package/src/providers/external-sources.ts +218 -0
  236. package/src/providers/ide-provider-instance.ts +35 -12
  237. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  238. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  239. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  240. package/src/providers/native-history/dispatcher.ts +340 -0
  241. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  242. package/src/providers/native-history/index.ts +30 -0
  243. package/src/providers/provider-instance-manager.ts +30 -0
  244. package/src/providers/provider-instance.ts +10 -1
  245. package/src/providers/provider-loader.ts +670 -50
  246. package/src/providers/provider-schema.ts +87 -14
  247. package/src/providers/provider-trust.ts +114 -0
  248. package/src/providers/read-chat-contract.ts +76 -16
  249. package/src/providers/sdk/README.md +49 -0
  250. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  251. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  252. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  253. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  254. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  255. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  256. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  257. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  258. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  259. package/src/providers/sdk/v1/index.ts +152 -0
  260. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  261. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  262. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  263. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  264. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  265. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  266. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  267. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  268. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  269. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  270. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  271. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  272. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  273. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  274. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  275. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  276. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  277. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  278. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  279. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  280. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  281. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  282. package/src/providers/sdk/v1/validators/index.ts +19 -0
  283. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  284. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  285. package/src/providers/spec/adapter.ts +168 -0
  286. package/src/providers/spec/cli-adapter.ts +986 -0
  287. package/src/providers/spec/evaluator.ts +345 -0
  288. package/src/providers/spec/fsm-driver.ts +1065 -0
  289. package/src/providers/spec/fsm-evaluator.ts +255 -0
  290. package/src/providers/spec/fsm-loader.ts +120 -0
  291. package/src/providers/spec/fsm-types.ts +238 -0
  292. package/src/providers/spec/native-history-executor.ts +1136 -0
  293. package/src/providers/spec/pre-launch-trust.ts +104 -0
  294. package/src/providers/spec/route.ts +51 -0
  295. package/src/providers/spec/types.ts +226 -0
  296. package/src/providers/status-monitor.d.ts +7 -7
  297. package/src/providers/status-monitor.ts +37 -22
  298. package/src/providers/transcript-v2.ts +567 -0
  299. package/src/providers/types/interactive-prompt.ts +536 -0
  300. package/src/providers/version-archive.ts +64 -24
  301. package/src/providers/working-dir.ts +23 -0
  302. package/src/repo-mesh-types.ts +378 -14
  303. package/src/sessions/registry.ts +6 -0
  304. package/src/shared-types-extra.ts +2 -4
  305. package/src/shared-types.d.ts +8 -0
  306. package/src/shared-types.ts +64 -1
  307. package/src/status/builders.ts +26 -6
  308. package/src/status/normalize.ts +2 -0
  309. package/src/status/reporter.ts +19 -1
  310. package/src/status/snapshot.ts +95 -26
  311. package/src/system/host-memory.ts +29 -12
  312. package/src/system/load-better-sqlite3.ts +68 -0
  313. package/src/types.ts +5 -0
  314. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  315. package/dist/mesh/mesh-sync.d.ts +0 -53
  316. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  317. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  318. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,667 @@
1
+ import type { MeshLedgerEntry } from './mesh-ledger.js';
2
+ import { appendLedgerEntry } from './mesh-ledger.js';
3
+ import type { MeshWorkQueueEntry, DirectDispatchRecord } from './mesh-work-queue.js';
4
+ import { deleteDirectDispatchesByTaskId } from './mesh-work-queue.js';
5
+ import { meshNodeIdMatches } from '@adhdev/mesh-shared';
6
+
7
+ export type MeshActiveWorkSource = 'queue' | 'direct';
8
+ export type MeshActiveWorkStatus = 'pending' | 'assigned' | 'generating' | 'idle' | 'failed' | 'awaiting_approval';
9
+
10
+ export interface MeshActiveWorkRecord {
11
+ taskId: string;
12
+ source: MeshActiveWorkSource;
13
+ status: MeshActiveWorkStatus;
14
+ nodeId?: string;
15
+ sessionId?: string;
16
+ providerType?: string;
17
+ taskTitle: string;
18
+ taskSummary: string;
19
+ message?: string;
20
+ taskMode?: string;
21
+ createdAt: string;
22
+ updatedAt: string;
23
+ dispatchedAt?: string;
24
+ elapsedMs: number;
25
+ terminal?: boolean;
26
+ terminalKind?: string;
27
+ terminalAt?: string;
28
+ staleReason?: string;
29
+ /**
30
+ * When true, the session targeted by this direct dispatch still exists in the live mesh
31
+ * but did not transition to generating — the dispatch was not acknowledged by the provider.
32
+ * Distinct from historical/orphaned stale entries where the node/session is gone.
33
+ */
34
+ staleDispatchUnacknowledged?: boolean;
35
+ }
36
+
37
+ export interface MeshActiveWorkSummary {
38
+ totalActiveCount: number;
39
+ queueActiveCount: number;
40
+ directActiveCount: number;
41
+ awaitingApprovalCount: number;
42
+ generatingCount: number;
43
+ failedCount: number;
44
+ idleCount: number;
45
+ sourceCounts: Record<MeshActiveWorkSource, number>;
46
+ statusCounts: Record<MeshActiveWorkStatus, number>;
47
+ staleDirectCount: number;
48
+ /**
49
+ * Count of stale direct entries where the target session still exists in the live mesh
50
+ * but never transitioned to generating — these are fresh dispatch failures, not historical orphans.
51
+ * Requires immediate recovery: launch a fresh session and retry the task.
52
+ */
53
+ staleDirectUnacknowledgedCount?: number;
54
+ /**
55
+ * When staleDirectCount > 0, this note clarifies what kind of stale records exist.
56
+ * Fresh unacknowledged dispatches carry an actionable recovery note; orphaned historical
57
+ * entries carry the "historical evidence only" note. Both may coexist.
58
+ */
59
+ staleDirectNote?: string;
60
+ }
61
+
62
+ export interface MeshStaleDirectWorkSummary {
63
+ count: number;
64
+ sampleLimit: number;
65
+ sample: Array<Pick<MeshActiveWorkRecord, 'taskId' | 'status' | 'nodeId' | 'sessionId' | 'taskTitle' | 'createdAt' | 'staleReason'>>;
66
+ reasonCounts: Record<string, number>;
67
+ detailHint: string;
68
+ note?: string;
69
+ }
70
+
71
+ export interface BuildMeshActiveWorkOptions {
72
+ meshId: string;
73
+ queue?: MeshWorkQueueEntry[];
74
+ ledgerEntries?: MeshLedgerEntry[];
75
+ /**
76
+ * Active direct dispatches from MeshRuntimeStore. When provided, these are used instead of
77
+ * scanning ledger entries for direct dispatches — eliminates the O(n_ledger) scan.
78
+ * Falls back to ledger scanning when not provided.
79
+ */
80
+ directDispatches?: DirectDispatchRecord[];
81
+ nodes?: any[];
82
+ now?: number;
83
+ /** Include terminal direct rows (idle/failed) for handoff/recent-work surfaces. Defaults false. */
84
+ includeTerminalDirect?: boolean;
85
+ }
86
+
87
+ const DIRECT_DISPATCH_VIA = new Set(['p2p_direct', 'local_direct', 'mesh_send_task']);
88
+ const TERMINAL_LEDGER_KINDS = new Set(['task_completed', 'task_failed', 'task_stalled']);
89
+
90
+ function readString(value: unknown): string | undefined {
91
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
92
+ }
93
+
94
+ function summarizeMessage(message: string): { title: string; summary: string } {
95
+ const oneLine = message.replace(/\s+/g, ' ').trim();
96
+ const title = oneLine.length > 96 ? `${oneLine.slice(0, 93)}...` : oneLine;
97
+ return { title: title || '(untitled task)', summary: oneLine };
98
+ }
99
+
100
+ function elapsedSince(value: string | undefined, now: number): number {
101
+ const started = value ? new Date(value).getTime() : Number.NaN;
102
+ return Number.isFinite(started) ? Math.max(0, now - started) : 0;
103
+ }
104
+
105
+ function sessionStatusFromNodes(nodes: any[] | undefined, nodeId?: string, sessionId?: string): { status?: MeshActiveWorkStatus; staleReason?: string } {
106
+ if (!Array.isArray(nodes)) return {};
107
+ if (!nodeId) return { staleReason: 'direct task has no node id' };
108
+ const node = nodes.find(item => meshNodeIdMatches(item, nodeId));
109
+ if (!node) return { staleReason: 'direct task node is no longer in the live mesh' };
110
+ if (!sessionId) return {};
111
+ const candidates: any[] = [];
112
+ for (const value of [
113
+ node.sessions,
114
+ node.activeSessions,
115
+ node.active_sessions,
116
+ node.activeSessionDetails,
117
+ node.active_session_details,
118
+ node.sessionDetails,
119
+ node.session_details,
120
+ node.lastProbe?.sessions,
121
+ node.last_probe?.sessions,
122
+ node.lastProbe?.status?.sessions,
123
+ node.last_probe?.status?.sessions,
124
+ ]) {
125
+ if (Array.isArray(value)) candidates.push(...value);
126
+ }
127
+ for (const value of [node.activeSession, node.active_session, node.currentSession, node.current_session, node.runtimeSession, node.runtime_session, node.session]) {
128
+ if (value && typeof value === 'object') candidates.push(value);
129
+ }
130
+ const session = candidates.find(item => {
131
+ if (typeof item === 'string') return item === sessionId;
132
+ const id = readString(item?.id) || readString(item?.sessionId) || readString(item?.session_id) || readString(item?.runtimeSessionId) || readString(item?.instanceId);
133
+ return id === sessionId;
134
+ });
135
+ if (!session) return { staleReason: 'direct task session is not present in live session records' };
136
+ if (typeof session === 'string') return {};
137
+ const raw = `${readString(session.status) || ''} ${readString(session.lifecycle) || ''} ${readString(session.state) || ''} ${readString(session.activeChat?.status) || ''}`.toLowerCase();
138
+ if (raw.includes('approval')) return { status: 'awaiting_approval' };
139
+ if (raw.includes('generating') || raw.includes('running') || raw.includes('busy')) return { status: 'generating' };
140
+ if (raw.includes('failed') || raw.includes('stopped') || raw.includes('terminated') || raw.includes('exited')) return { status: 'failed' };
141
+ if (raw.includes('idle') || raw.includes('waiting_input') || raw.includes('ready')) return { status: 'idle' };
142
+ return {};
143
+ }
144
+
145
+ function isDirectDispatch(entry: MeshLedgerEntry): boolean {
146
+ if (entry.kind !== 'task_dispatched') return false;
147
+ const payload = entry.payload || {};
148
+ if (payload.source === 'direct') return true;
149
+ const via = readString(payload.via);
150
+ return Boolean(via && DIRECT_DISPATCH_VIA.has(via) && payload.source !== 'queue');
151
+ }
152
+
153
+ function directDispatchTaskId(entry: MeshLedgerEntry): string {
154
+ return readString(entry.payload?.taskId) || entry.id;
155
+ }
156
+
157
+ function terminalMatchesDispatch(terminal: MeshLedgerEntry, dispatch: MeshLedgerEntry, taskId: string): boolean {
158
+ const terminalTaskId = readString(terminal.payload?.taskId);
159
+ if (terminalTaskId && terminalTaskId === taskId) return true;
160
+ if (terminalTaskId && terminalTaskId !== taskId) return false;
161
+ if (dispatch.sessionId && terminal.sessionId === dispatch.sessionId) return true;
162
+ return Boolean(dispatch.nodeId && terminal.nodeId === dispatch.nodeId && !dispatch.sessionId);
163
+ }
164
+
165
+ function statusFromTerminal(entry: MeshLedgerEntry): MeshActiveWorkStatus {
166
+ if (entry.kind === 'task_approval_needed') return 'awaiting_approval';
167
+ if (entry.kind === 'task_completed') return 'idle';
168
+ return 'failed';
169
+ }
170
+
171
+ const LEDGER_ONLY_STALE_REASON =
172
+ 'direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition';
173
+
174
+ /**
175
+ * Single source of truth for classifying whether a direct dispatch is ledger-only
176
+ * stale (dispatched but never acknowledged: no provider ack, no transcript append,
177
+ * no runtime transition) and whether that staleness is "fresh unacknowledged"
178
+ * (target session still live) vs. an orphaned historical record.
179
+ *
180
+ * Previously this predicate was inlined in all three dispatch-classification blocks
181
+ * (MeshRuntimeStore path, remote-ledger path, full-ledger path) and had drifted —
182
+ * e.g. one block gated `isIdleUnacknowledged` on `!isTerminal` and another did not.
183
+ * Extracting it keeps the three callers byte-for-byte consistent. Status derivation
184
+ * stays per-block: it genuinely differs by data source and is passed in via `status`.
185
+ */
186
+ function classifyDirectDispatch(params: {
187
+ /** Final classified status of the dispatch. */
188
+ status: MeshActiveWorkStatus;
189
+ /** True when a real terminal row applies (completed/failed/stale); excludes approval_needed. Gates the stale verdict. */
190
+ isTerminalRow: boolean;
191
+ /** True when any terminal-derived status exists (incl. approval_needed). Used to detect "no transition". */
192
+ hasTerminalStatus: boolean;
193
+ /** Live session status from the mesh nodes, if any. */
194
+ liveStatus?: string;
195
+ /** Live stale reason from the mesh nodes, if any. */
196
+ liveStaleReason?: string;
197
+ /** Whether the dispatch targeted an already-idle session. */
198
+ dispatchedToIdleSession: boolean;
199
+ }): { ledgerOnlyStaleReason: string | undefined; isFreshUnacknowledged: boolean } {
200
+ const { status, isTerminalRow, hasTerminalStatus, liveStatus, liveStaleReason, dispatchedToIdleSession } = params;
201
+ const isNoTransition = !hasTerminalStatus && !liveStatus;
202
+ const isIdleUnacknowledged = status === 'idle';
203
+ const ledgerOnlyStaleReason =
204
+ !isTerminalRow && (isIdleUnacknowledged || isNoTransition || (dispatchedToIdleSession && isIdleUnacknowledged))
205
+ ? LEDGER_ONLY_STALE_REASON
206
+ : undefined;
207
+ const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !liveStaleReason);
208
+ return { ledgerOnlyStaleReason, isFreshUnacknowledged };
209
+ }
210
+
211
+ export function buildMeshActiveWorkSummary(activeWork: MeshActiveWorkRecord[]): MeshActiveWorkSummary {
212
+ const statusCounts: Record<MeshActiveWorkStatus, number> = {
213
+ pending: 0,
214
+ assigned: 0,
215
+ generating: 0,
216
+ idle: 0,
217
+ failed: 0,
218
+ awaiting_approval: 0,
219
+ };
220
+ const sourceCounts: Record<MeshActiveWorkSource, number> = { queue: 0, direct: 0 };
221
+ for (const item of activeWork) {
222
+ sourceCounts[item.source] += 1;
223
+ statusCounts[item.status] += 1;
224
+ }
225
+ const staleDirectCount = activeWork.filter(item => item.source === 'direct' && item.staleReason).length;
226
+ const staleDirectUnacknowledgedCount = activeWork.filter(item => item.source === 'direct' && item.staleDispatchUnacknowledged).length;
227
+ return {
228
+ totalActiveCount: activeWork.length,
229
+ queueActiveCount: sourceCounts.queue,
230
+ directActiveCount: sourceCounts.direct,
231
+ awaitingApprovalCount: statusCounts.awaiting_approval,
232
+ generatingCount: statusCounts.generating,
233
+ failedCount: statusCounts.failed,
234
+ idleCount: statusCounts.idle,
235
+ sourceCounts,
236
+ statusCounts,
237
+ staleDirectCount,
238
+ ...(staleDirectUnacknowledgedCount > 0 ? { staleDirectUnacknowledgedCount } : {}),
239
+ ...(staleDirectCount > 0 ? { staleDirectNote: 'Stale direct records are orphaned ledger entries whose node/session no longer exists. They are historical recovery evidence only — not active or unresolved work. The queue (source: queue) is authoritative for pending/assigned tasks.' } : {}),
240
+ };
241
+ }
242
+
243
+
244
+ export function buildMeshActiveWork(opts: BuildMeshActiveWorkOptions): { activeWork: MeshActiveWorkRecord[]; staleDirectWork: MeshActiveWorkRecord[]; staleDirectWorkNote?: string; terminalDirectWork: MeshActiveWorkRecord[]; summary: MeshActiveWorkSummary } {
245
+ const now = opts.now ?? Date.now();
246
+ const records: MeshActiveWorkRecord[] = [];
247
+ const staleDirectWork: MeshActiveWorkRecord[] = [];
248
+ const terminalDirectWork: MeshActiveWorkRecord[] = [];
249
+
250
+ for (const task of opts.queue || []) {
251
+ if (task.status !== 'pending' && task.status !== 'assigned') continue;
252
+ const { title, summary } = summarizeMessage(task.message || '');
253
+ records.push({
254
+ taskId: task.id,
255
+ source: 'queue',
256
+ status: task.status,
257
+ nodeId: task.assignedNodeId || task.targetNodeId,
258
+ sessionId: task.assignedSessionId || task.targetSessionId,
259
+ taskTitle: title,
260
+ taskSummary: summary,
261
+ message: task.message,
262
+ taskMode: task.taskMode,
263
+ createdAt: task.createdAt,
264
+ updatedAt: task.updatedAt,
265
+ dispatchedAt: task.dispatchTimestamp,
266
+ elapsedMs: elapsedSince(task.dispatchTimestamp || task.createdAt, now),
267
+ });
268
+ }
269
+
270
+ // When MeshRuntimeStore direct dispatches are provided, use them for LOCAL dispatches (O(1) indexed).
271
+ // ALSO scan ledger for remote dispatches (P2P) whose taskIds are not in MeshRuntimeStore — these
272
+ // are never written to the local MeshRuntimeStore since they're dispatched from a remote daemon.
273
+ if (opts.directDispatches !== undefined) {
274
+ const dbTaskIds = new Set(opts.directDispatches.map(d => d.taskId));
275
+ for (const dispatch of opts.directDispatches) {
276
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId ?? undefined, dispatch.sessionId ?? undefined);
277
+ const dbStatus = dispatch.status; // 'dispatched' | 'acked' | 'completed' | 'failed' | 'stale'
278
+ const isTerminal = dbStatus === 'completed' || dbStatus === 'failed' || dbStatus === 'stale';
279
+ const status: MeshActiveWorkStatus = isTerminal
280
+ ? (dbStatus === 'completed' ? 'idle' : 'failed')
281
+ : live.status || (dbStatus === 'acked' ? 'generating' : 'assigned');
282
+ const { ledgerOnlyStaleReason, isFreshUnacknowledged } = classifyDirectDispatch({
283
+ status,
284
+ isTerminalRow: isTerminal,
285
+ hasTerminalStatus: isTerminal,
286
+ liveStatus: live.status,
287
+ liveStaleReason: live.staleReason,
288
+ dispatchedToIdleSession: dispatch.dispatchedToIdleSession === true,
289
+ });
290
+ const { title, summary } = summarizeMessage(dispatch.message || '');
291
+ const record: MeshActiveWorkRecord = {
292
+ taskId: dispatch.taskId,
293
+ source: 'direct',
294
+ status,
295
+ nodeId: dispatch.nodeId ?? undefined,
296
+ sessionId: dispatch.sessionId ?? undefined,
297
+ providerType: dispatch.providerType ?? undefined,
298
+ taskTitle: title,
299
+ taskSummary: summary,
300
+ message: dispatch.message,
301
+ taskMode: dispatch.taskMode ?? undefined,
302
+ createdAt: dispatch.dispatchedAt,
303
+ updatedAt: dispatch.updatedAt,
304
+ dispatchedAt: dispatch.dispatchedAt,
305
+ elapsedMs: elapsedSince(dispatch.dispatchedAt, now),
306
+ terminal: isTerminal,
307
+ terminalKind: isTerminal ? (dbStatus === 'completed' ? 'task_completed' : 'task_failed') : undefined,
308
+ terminalAt: isTerminal ? dispatch.updatedAt : undefined,
309
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
310
+ ...(isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}),
311
+ };
312
+ if (isTerminal) {
313
+ terminalDirectWork.push(record);
314
+ if (opts.includeTerminalDirect !== true) continue;
315
+ }
316
+ if ((live.staleReason || ledgerOnlyStaleReason) && !isTerminal) {
317
+ staleDirectWork.push(record);
318
+ continue;
319
+ }
320
+ records.push(record);
321
+ }
322
+ // Also scan ledger for remote dispatches (via p2p_direct) whose taskIds are NOT in MeshRuntimeStore.
323
+ // Remote daemons write their own local MeshRuntimeStore; this coordinator's MeshRuntimeStore only has local dispatches.
324
+ const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
325
+ const terminals = ledgerEntries.filter(entry => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === 'task_approval_needed');
326
+ for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
327
+ const taskId = directDispatchTaskId(dispatch);
328
+ if (dbTaskIds.has(taskId)) continue; // already covered by MeshRuntimeStore path above
329
+ const terminal = terminals
330
+ .filter(entry => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime())
331
+ .find(entry => terminalMatchesDispatch(entry, dispatch, taskId));
332
+ const terminalStatus = terminal ? statusFromTerminal(terminal) : undefined;
333
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
334
+ const status = terminalStatus || live.status || 'assigned';
335
+ const terminalRow = Boolean(terminal && terminal.kind !== 'task_approval_needed');
336
+ const { ledgerOnlyStaleReason, isFreshUnacknowledged } = classifyDirectDispatch({
337
+ status,
338
+ isTerminalRow: terminalRow,
339
+ hasTerminalStatus: Boolean(terminalStatus),
340
+ liveStatus: live.status,
341
+ liveStaleReason: live.staleReason,
342
+ dispatchedToIdleSession: dispatch.payload?.dispatchedToIdleSession === true,
343
+ });
344
+ const message = readString(dispatch.payload?.message) || readString(dispatch.payload?.summary) || '';
345
+ const { title, summary } = summarizeMessage(message);
346
+ const record: MeshActiveWorkRecord = {
347
+ taskId,
348
+ source: 'direct',
349
+ status,
350
+ nodeId: dispatch.nodeId,
351
+ sessionId: dispatch.sessionId,
352
+ providerType: dispatch.providerType || readString(dispatch.payload?.providerType),
353
+ taskTitle: readString(dispatch.payload?.taskTitle) || title,
354
+ taskSummary: readString(dispatch.payload?.taskSummary) || summary,
355
+ message,
356
+ taskMode: readString(dispatch.payload?.taskMode),
357
+ createdAt: dispatch.timestamp,
358
+ updatedAt: terminal?.timestamp || dispatch.timestamp,
359
+ dispatchedAt: dispatch.timestamp,
360
+ elapsedMs: elapsedSince(dispatch.timestamp, now),
361
+ terminal: terminalRow,
362
+ terminalKind: terminal?.kind,
363
+ terminalAt: terminal?.timestamp,
364
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
365
+ ...(isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}),
366
+ };
367
+ if (terminalRow) {
368
+ terminalDirectWork.push(record);
369
+ if (opts.includeTerminalDirect !== true) continue;
370
+ }
371
+ if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
372
+ staleDirectWork.push(record);
373
+ continue;
374
+ }
375
+ records.push(record);
376
+ }
377
+ } else {
378
+ // Full ledger scan: no MeshRuntimeStore direct dispatches available (standalone mode or empty).
379
+ const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
380
+ const terminals = ledgerEntries.filter(entry => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === 'task_approval_needed');
381
+ for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
382
+ const taskId = directDispatchTaskId(dispatch);
383
+ const terminal = terminals
384
+ .filter(entry => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime())
385
+ .find(entry => terminalMatchesDispatch(entry, dispatch, taskId));
386
+ const terminalStatus = terminal ? statusFromTerminal(terminal) : undefined;
387
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
388
+ const status = terminalStatus || live.status || 'assigned';
389
+ const terminalRow = Boolean(terminal && terminal.kind !== 'task_approval_needed');
390
+ const { ledgerOnlyStaleReason, isFreshUnacknowledged } = classifyDirectDispatch({
391
+ status,
392
+ isTerminalRow: terminalRow,
393
+ hasTerminalStatus: Boolean(terminalStatus),
394
+ liveStatus: live.status,
395
+ liveStaleReason: live.staleReason,
396
+ dispatchedToIdleSession: dispatch.payload?.dispatchedToIdleSession === true,
397
+ });
398
+ const message = readString(dispatch.payload?.message) || readString(dispatch.payload?.summary) || '';
399
+ const { title, summary } = summarizeMessage(message);
400
+ const record: MeshActiveWorkRecord = {
401
+ taskId,
402
+ source: 'direct',
403
+ status,
404
+ nodeId: dispatch.nodeId,
405
+ sessionId: dispatch.sessionId,
406
+ providerType: dispatch.providerType || readString(dispatch.payload?.providerType),
407
+ taskTitle: readString(dispatch.payload?.taskTitle) || title,
408
+ taskSummary: readString(dispatch.payload?.taskSummary) || summary,
409
+ message,
410
+ taskMode: readString(dispatch.payload?.taskMode),
411
+ createdAt: dispatch.timestamp,
412
+ updatedAt: terminal?.timestamp || dispatch.timestamp,
413
+ dispatchedAt: dispatch.timestamp,
414
+ elapsedMs: elapsedSince(dispatch.timestamp, now),
415
+ terminal: terminalRow,
416
+ terminalKind: terminal?.kind,
417
+ terminalAt: terminal?.timestamp,
418
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
419
+ ...(isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}),
420
+ };
421
+ if (terminalRow) {
422
+ terminalDirectWork.push(record);
423
+ if (opts.includeTerminalDirect !== true) continue;
424
+ }
425
+ if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
426
+ staleDirectWork.push(record);
427
+ continue;
428
+ }
429
+ records.push(record);
430
+ }
431
+ }
432
+
433
+ records.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
434
+ staleDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
435
+ terminalDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
436
+ const summary = buildMeshActiveWorkSummary(records);
437
+ summary.staleDirectCount = staleDirectWork.length;
438
+ const unacknowledgedCount = staleDirectWork.filter(r => r.staleDispatchUnacknowledged).length;
439
+ if (unacknowledgedCount > 0) {
440
+ summary.staleDirectUnacknowledgedCount = unacknowledgedCount;
441
+ }
442
+ // Build a note that accurately describes what's in the stale set.
443
+ // When there are fresh unacknowledged entries (node/session still live, session never started),
444
+ // use the actionable recovery note instead of the misleading "historical evidence only" note.
445
+ const staleDirectWorkNote = staleDirectWork.length > 0
446
+ ? unacknowledgedCount > 0 && unacknowledgedCount === staleDirectWork.length
447
+ ? `${unacknowledgedCount} direct dispatch(es) were not acknowledged by the target session — the session received the agent_command but never transitioned to generating. This is a fresh dispatch failure, not historical noise. Recovery: launch a fresh session on the same node and retry the task, or use mesh_enqueue_task for queue-based assignment.`
448
+ : unacknowledgedCount > 0
449
+ ? `${unacknowledgedCount} of ${staleDirectWork.length} stale direct record(s) are fresh unacknowledged dispatch failures (session still live but never transitioned to generating); the rest are orphaned historical entries whose node/session no longer exists. Fresh unacknowledged dispatches need recovery: launch a fresh session and retry. Orphaned entries are historical evidence only — not active or unresolved work.`
450
+ : 'These are orphaned ledger entries whose original node or session no longer exists in the live mesh. They are historical/recovery evidence only — not active or unresolved work. Do not treat staleDirectCount as a status mismatch; use the queue (source: queue) as authoritative for pending/assigned tasks.'
451
+ : undefined;
452
+ if (staleDirectWorkNote) {
453
+ summary.staleDirectNote = staleDirectWorkNote;
454
+ }
455
+ return { activeWork: records, staleDirectWork, staleDirectWorkNote, terminalDirectWork, summary };
456
+ }
457
+
458
+ /**
459
+ * staleReason strings (produced by sessionStatusFromNodes above) that indicate the original
460
+ * node/session is GONE from the live mesh — i.e. the staleDirect record is an orphaned ledger
461
+ * artifact, not active or recoverable work. These are the only reasons safe to prune from the
462
+ * active staleDirect surface. The "no provider acknowledgement" reason is deliberately excluded:
463
+ * those entries have a still-live node/session (staleDispatchUnacknowledged) and represent
464
+ * recoverable dispatch failures, never orphans.
465
+ */
466
+ export const PRUNABLE_ORPHAN_STALE_REASONS: ReadonlySet<string> = new Set([
467
+ 'direct task node is no longer in the live mesh',
468
+ 'direct task session is not present in live session records',
469
+ 'direct task has no node id',
470
+ ]);
471
+
472
+ export type StaleDirectPruneClassification = 'prunable_orphan' | 'prunable_terminal' | 'preserve_unacknowledged' | 'preserve_active';
473
+
474
+ /**
475
+ * Classify a direct-work record for the staleDirect prune path. Pure function — the prune tool
476
+ * uses this so the safety rules (never touch active work or recoverable unacknowledged dispatches)
477
+ * live next to the staleReason producers and are independently testable.
478
+ */
479
+ export function classifyStaleDirectForPrune(
480
+ record: Pick<MeshActiveWorkRecord, 'staleReason' | 'staleDispatchUnacknowledged' | 'terminal'>,
481
+ opts: { includeTerminal?: boolean } = {},
482
+ ): StaleDirectPruneClassification {
483
+ if (record.staleDispatchUnacknowledged === true) return 'preserve_unacknowledged';
484
+ if (record.terminal === true) return opts.includeTerminal ? 'prunable_terminal' : 'preserve_active';
485
+ if (record.staleReason && PRUNABLE_ORPHAN_STALE_REASONS.has(record.staleReason)) return 'prunable_orphan';
486
+ return 'preserve_active';
487
+ }
488
+
489
+ /**
490
+ * Outcome of one staleDirect prune pass. Pure data — callers (the MCP tool, the
491
+ * daemon reconcile loop) format/log this however they need. The MCP tool wraps it in
492
+ * its JSON response; the reconcile loop logs prunedCount when > 0.
493
+ */
494
+ export interface StaleDirectPruneResult {
495
+ mode: 'execute' | 'dry_run';
496
+ includeTerminal: boolean;
497
+ /** Total staleDirect (+terminal when included) candidates surfaced this pass. */
498
+ candidateCount: number;
499
+ /** Records classified prunable AND (when minAgeMs > 0) old enough to auto-prune. */
500
+ prunable: MeshActiveWorkRecord[];
501
+ prunedCount: number;
502
+ /** Prunable by classification but younger than the age gate — only populated when minAgeMs > 0. */
503
+ skippedTooYoung: MeshActiveWorkRecord[];
504
+ preservedUnacknowledged: MeshActiveWorkRecord[];
505
+ /** Prunable orphans/terminals with no store-backed row to delete (ledger-only audit). */
506
+ preservedLedgerOnly: MeshActiveWorkRecord[];
507
+ preservedNotOrphan: MeshActiveWorkRecord[];
508
+ }
509
+
510
+ export interface PruneStaleDirectDispatchesOptions {
511
+ meshId: string;
512
+ /** Active direct dispatches from MeshRuntimeStore (getActiveDirectDispatches). */
513
+ directDispatches: DirectDispatchRecord[];
514
+ /** Ledger tail used to attribute remote/terminal dispatches (readLedgerEntries). */
515
+ ledgerEntries?: MeshLedgerEntry[];
516
+ queue?: MeshWorkQueueEntry[];
517
+ /** Live mesh nodes (decorated with live session details) — drives orphan detection. */
518
+ nodes?: any[];
519
+ /** When true, actually delete + append the audit ledger entry. Default false (dry run). */
520
+ execute?: boolean;
521
+ /** Include terminal (idle/failed) direct rows as prune candidates. Default false. */
522
+ includeTerminal?: boolean;
523
+ /**
524
+ * Minimum age (ms, measured from createdAt/dispatchedAt) before a prunable orphan is
525
+ * eligible. 0 (default) prunes immediately regardless of age — the manual prune behavior.
526
+ * The daemon auto-prune passes a conservative threshold so a node/session that is only
527
+ * transiently invisible is never pruned on the spot.
528
+ */
529
+ minAgeMs?: number;
530
+ /** Audit source string written into the direct_dispatch_pruned ledger payload. */
531
+ source?: string;
532
+ now?: number;
533
+ }
534
+
535
+ /**
536
+ * Shared staleDirect prune core. Single source of truth for the prune decision + the
537
+ * mutation (store-row delete + audit-ledger append) used by BOTH the manual MCP tool
538
+ * (mesh_prune_stale_direct, minAgeMs=0) and the daemon reconcile loop's auto-prune
539
+ * PHASE (minAgeMs > 0). Pure decision logic via buildMeshActiveWork + classifyStaleDirectForPrune;
540
+ * the only side effects (on execute) are deleteDirectDispatchesByTaskId and a single
541
+ * direct_dispatch_pruned ledger entry — never touching the append-only audit history of the
542
+ * pruned dispatches themselves.
543
+ *
544
+ * Safety rules (identical for manual + auto):
545
+ * - Only records classified as staleDirectWork against the CURRENT live mesh are eligible.
546
+ * - Of those, only orphans (node/session gone) — and terminals when includeTerminal — are prunable.
547
+ * Fresh unacknowledged dispatch failures (node/session still live) are always preserved.
548
+ * - Only store-backed rows (taskId present in MeshRuntimeStore) are deleted; ledger-only remote
549
+ * entries are preserved.
550
+ * - When minAgeMs > 0, a prunable orphan younger than the gate is held back (skippedTooYoung).
551
+ * This applies ONLY to the auto path; the manual path passes minAgeMs=0 (immediate).
552
+ *
553
+ * Idempotent: a deleted row no longer appears in getActiveDirectDispatches, so a second pass
554
+ * over the same orphan finds nothing to prune.
555
+ */
556
+ export function pruneStaleDirectDispatches(opts: PruneStaleDirectDispatchesOptions): StaleDirectPruneResult {
557
+ const now = opts.now ?? Date.now();
558
+ const includeTerminal = opts.includeTerminal === true;
559
+ const execute = opts.execute === true;
560
+ const minAgeMs = Math.max(0, opts.minAgeMs ?? 0);
561
+
562
+ const activeWorkEvidence = buildMeshActiveWork({
563
+ meshId: opts.meshId,
564
+ queue: opts.queue,
565
+ ledgerEntries: opts.ledgerEntries,
566
+ directDispatches: opts.directDispatches,
567
+ nodes: opts.nodes,
568
+ now,
569
+ includeTerminalDirect: includeTerminal,
570
+ });
571
+
572
+ const candidates = [
573
+ ...activeWorkEvidence.staleDirectWork,
574
+ ...(includeTerminal ? activeWorkEvidence.terminalDirectWork : []),
575
+ ];
576
+ // Only prune store-backed dispatch rows (taskIds present in MeshRuntimeStore). Ledger-only
577
+ // remote entries have no store row to delete and are pure audit history — leave them alone.
578
+ const storeTaskIds = new Set(opts.directDispatches.map(d => d.taskId));
579
+
580
+ const prunable: MeshActiveWorkRecord[] = [];
581
+ const skippedTooYoung: MeshActiveWorkRecord[] = [];
582
+ const preservedUnacknowledged: MeshActiveWorkRecord[] = [];
583
+ const preservedLedgerOnly: MeshActiveWorkRecord[] = [];
584
+ const preservedNotOrphan: MeshActiveWorkRecord[] = [];
585
+ for (const record of candidates) {
586
+ const classification = classifyStaleDirectForPrune(record, { includeTerminal });
587
+ if (classification === 'preserve_unacknowledged') {
588
+ preservedUnacknowledged.push(record);
589
+ continue;
590
+ }
591
+ if (classification === 'preserve_active') {
592
+ preservedNotOrphan.push(record);
593
+ continue;
594
+ }
595
+ // prunable_orphan | prunable_terminal — only delete store-backed rows; ledger-only remote
596
+ // entries have no store row to delete and are pure audit history.
597
+ if (!storeTaskIds.has(record.taskId)) {
598
+ preservedLedgerOnly.push(record);
599
+ continue;
600
+ }
601
+ // Age gate (auto path only): hold back orphans that are too fresh — a node/session that is
602
+ // only transiently invisible must not be pruned the instant it disappears.
603
+ if (minAgeMs > 0) {
604
+ const ageRef = record.dispatchedAt || record.createdAt;
605
+ const ageMs = elapsedSince(ageRef, now);
606
+ if (ageMs < minAgeMs) {
607
+ skippedTooYoung.push(record);
608
+ continue;
609
+ }
610
+ }
611
+ prunable.push(record);
612
+ }
613
+
614
+ let prunedCount = 0;
615
+ if (execute && prunable.length) {
616
+ prunedCount = deleteDirectDispatchesByTaskId(opts.meshId, prunable.map(r => r.taskId));
617
+ appendLedgerEntry(opts.meshId, {
618
+ kind: 'direct_dispatch_pruned',
619
+ payload: {
620
+ source: opts.source || 'prune_stale_direct',
621
+ prunedCount,
622
+ taskIds: prunable.map(r => r.taskId),
623
+ reasons: Array.from(new Set(prunable.map(r => r.staleReason || (r.terminal ? 'terminal' : 'unknown')))),
624
+ },
625
+ });
626
+ }
627
+
628
+ return {
629
+ mode: execute ? 'execute' : 'dry_run',
630
+ includeTerminal,
631
+ candidateCount: candidates.length,
632
+ prunable,
633
+ prunedCount,
634
+ skippedTooYoung,
635
+ preservedUnacknowledged,
636
+ preservedLedgerOnly,
637
+ preservedNotOrphan,
638
+ };
639
+ }
640
+
641
+ export function buildCompactStaleDirectWorkSummary(
642
+ staleDirectWork: MeshActiveWorkRecord[],
643
+ opts: { sampleLimit?: number; detailHint?: string; note?: string } = {},
644
+ ): MeshStaleDirectWorkSummary {
645
+ const sampleLimit = Math.max(0, Math.min(10, Math.floor(opts.sampleLimit ?? 3)));
646
+ const reasonCounts: Record<string, number> = {};
647
+ for (const entry of staleDirectWork) {
648
+ const reason = entry.staleReason || 'unknown';
649
+ reasonCounts[reason] = (reasonCounts[reason] || 0) + 1;
650
+ }
651
+ return {
652
+ count: staleDirectWork.length,
653
+ sampleLimit,
654
+ sample: staleDirectWork.slice(0, sampleLimit).map(entry => ({
655
+ taskId: entry.taskId,
656
+ status: entry.status,
657
+ nodeId: entry.nodeId,
658
+ sessionId: entry.sessionId,
659
+ taskTitle: entry.taskTitle,
660
+ createdAt: entry.createdAt,
661
+ staleReason: entry.staleReason,
662
+ })),
663
+ reasonCounts,
664
+ detailHint: opts.detailHint || 'Stale direct records are historical recovery evidence only. Use mesh_task_history for full ledger details, or request includeStaleDirectWorkDetails when supported by the caller.',
665
+ ...(opts.note ? { note: opts.note } : {}),
666
+ };
667
+ }