@adhdev/daemon-core 0.9.82-rc.21 → 0.9.82-rc.210

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 (269) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +1 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/chat/source-machine.d.ts +166 -0
  4. package/dist/chat/source-resolver.d.ts +104 -0
  5. package/dist/chat/subscription-updates.d.ts +1 -0
  6. package/dist/cli-adapter-types.d.ts +23 -2
  7. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  8. package/dist/cli-adapters/cli-state-engine.d.ts +178 -0
  9. package/dist/cli-adapters/provider-cli-adapter.d.ts +106 -63
  10. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  11. package/dist/cli-adapters/provider-cli-shared.d.ts +29 -0
  12. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  13. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +3 -3
  14. package/dist/cli-adapters/terminal-backends/types.d.ts +1 -2
  15. package/dist/cli-adapters/terminal-screen.d.ts +2 -11
  16. package/dist/commands/cli-manager.d.ts +2 -1
  17. package/dist/commands/handler.d.ts +110 -0
  18. package/dist/commands/mesh-coordinator.d.ts +85 -1
  19. package/dist/commands/router.d.ts +32 -1
  20. package/dist/config/chat-history.d.ts +9 -0
  21. package/dist/config/config.d.ts +5 -0
  22. package/dist/config/mesh-config.d.ts +72 -1
  23. package/dist/git/git-commands.d.ts +9 -1
  24. package/dist/git/git-diff.d.ts +6 -0
  25. package/dist/git/git-types.d.ts +2 -0
  26. package/dist/index.d.ts +46 -11
  27. package/dist/index.js +35171 -15756
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +34878 -15556
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/installer.d.ts +1 -4
  32. package/dist/ipc/local-ipc-server.d.ts +91 -0
  33. package/dist/launch.d.ts +1 -1
  34. package/dist/logging/async-batch-writer.d.ts +10 -0
  35. package/dist/mesh/contracts.d.ts +164 -0
  36. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  37. package/dist/mesh/coordinator-registry.d.ts +59 -0
  38. package/dist/mesh/mesh-active-work.d.ts +90 -0
  39. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  40. package/dist/mesh/mesh-events-coordinator.d.ts +151 -0
  41. package/dist/mesh/mesh-events-pending.d.ts +33 -0
  42. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  43. package/dist/mesh/mesh-events-utils.d.ts +14 -0
  44. package/dist/mesh/mesh-events.d.ts +5 -40
  45. package/dist/mesh/mesh-fast-forward.d.ts +41 -0
  46. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  47. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  48. package/dist/mesh/mesh-ledger.d.ts +77 -1
  49. package/dist/mesh/mesh-missions.d.ts +58 -0
  50. package/dist/mesh/mesh-refine-status.d.ts +26 -0
  51. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  52. package/dist/mesh/mesh-runtime-store.d.ts +324 -0
  53. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  54. package/dist/mesh/mesh-work-queue.d.ts +137 -6
  55. package/dist/mesh/preview-freshness.d.ts +18 -0
  56. package/dist/mesh/refine-config.d.ts +215 -0
  57. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  58. package/dist/providers/acp-provider-instance.d.ts +2 -0
  59. package/dist/providers/approval-utils.d.ts +13 -0
  60. package/dist/providers/cli-provider-instance.d.ts +39 -3
  61. package/dist/providers/contracts.d.ts +130 -6
  62. package/dist/providers/external-sources.d.ts +71 -0
  63. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  64. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  65. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  66. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  67. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  68. package/dist/providers/native-history/index.d.ts +13 -0
  69. package/dist/providers/provider-instance-manager.d.ts +12 -0
  70. package/dist/providers/provider-instance.d.ts +13 -1
  71. package/dist/providers/provider-loader.d.ts +26 -4
  72. package/dist/providers/provider-trust.d.ts +31 -0
  73. package/dist/providers/read-chat-contract.d.ts +29 -0
  74. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  75. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  76. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  77. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  78. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  79. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  80. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  81. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  82. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  83. package/dist/providers/sdk/v1/index.d.ts +30 -0
  84. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  85. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  86. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  87. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  88. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  89. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  90. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  91. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  92. package/dist/providers/spec/adapter.d.ts +52 -0
  93. package/dist/providers/spec/cli-adapter.d.ts +101 -0
  94. package/dist/providers/spec/driver.d.ts +225 -0
  95. package/dist/providers/spec/evaluator.d.ts +54 -0
  96. package/dist/providers/spec/loader.d.ts +15 -0
  97. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  98. package/dist/providers/spec/route.d.ts +4 -0
  99. package/dist/providers/spec/schema.gen.d.ts +2025 -0
  100. package/dist/providers/spec/types.d.ts +302 -0
  101. package/dist/providers/transcript-v2.d.ts +176 -0
  102. package/dist/providers/types/interactive-prompt.d.ts +48 -0
  103. package/dist/repo-mesh-types.d.ts +109 -1
  104. package/dist/sessions/registry.d.ts +3 -0
  105. package/dist/shared-types-extra.d.ts +2 -4
  106. package/dist/shared-types.d.ts +42 -1
  107. package/dist/status/normalize.d.ts +1 -1
  108. package/dist/status/normalize.js +1 -0
  109. package/dist/status/normalize.js.map +1 -1
  110. package/dist/status/normalize.mjs +1 -0
  111. package/dist/status/normalize.mjs.map +1 -1
  112. package/dist/status/reporter.d.ts +2 -0
  113. package/dist/status/snapshot.d.ts +1 -0
  114. package/dist/types.d.ts +5 -0
  115. package/package.json +6 -3
  116. package/src/agent-stream/poller.ts +2 -3
  117. package/src/boot/daemon-lifecycle.ts +22 -10
  118. package/src/boot/process-hardening.ts +89 -0
  119. package/src/chat/source-machine.ts +534 -0
  120. package/src/chat/source-resolver.ts +0 -0
  121. package/src/chat/subscription-updates.ts +20 -1
  122. package/src/cli-adapter-types.d.ts +1 -0
  123. package/src/cli-adapter-types.ts +22 -2
  124. package/src/cli-adapters/cli-script-runner.ts +421 -0
  125. package/src/cli-adapters/cli-state-engine.ts +1138 -0
  126. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  127. package/src/cli-adapters/provider-cli-adapter.ts +673 -1139
  128. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  129. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  130. package/src/cli-adapters/provider-cli-runtime.ts +3 -1
  131. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  132. package/src/cli-adapters/provider-cli-shared.ts +59 -11
  133. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  134. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +35 -29
  135. package/src/cli-adapters/terminal-backends/types.ts +1 -3
  136. package/src/cli-adapters/terminal-screen.ts +11 -81
  137. package/src/commands/chat-commands.ts +1787 -60
  138. package/src/commands/cli-manager.ts +283 -14
  139. package/src/commands/handler.ts +809 -2
  140. package/src/commands/mesh-coordinator.ts +332 -122
  141. package/src/commands/router.ts +4198 -557
  142. package/src/config/chat-history.ts +95 -24
  143. package/src/config/config.ts +12 -0
  144. package/src/config/mesh-config.ts +280 -2
  145. package/src/config/recent-activity.ts +8 -2
  146. package/src/daemon/dev-auto-implement.ts +3 -2
  147. package/src/daemon/dev-cli-debug.ts +10 -1
  148. package/src/detection/ide-detector.ts +26 -16
  149. package/src/git/git-commands.ts +42 -12
  150. package/src/git/git-diff.ts +53 -0
  151. package/src/git/git-status.ts +35 -6
  152. package/src/git/git-types.ts +2 -0
  153. package/src/git/git-worktree.ts +8 -1
  154. package/src/index.ts +126 -10
  155. package/src/installer.d.ts +1 -1
  156. package/src/installer.ts +8 -6
  157. package/src/ipc/local-ipc-server.ts +278 -0
  158. package/src/launch.d.ts +1 -1
  159. package/src/launch.ts +37 -28
  160. package/src/logging/async-batch-writer.ts +55 -0
  161. package/src/logging/logger.ts +2 -1
  162. package/src/mesh/contracts.ts +329 -0
  163. package/src/mesh/coordinator-prompt.ts +218 -31
  164. package/src/mesh/coordinator-registry.ts +121 -0
  165. package/src/mesh/mesh-active-work.ts +437 -0
  166. package/src/mesh/mesh-delivery-policy.ts +315 -0
  167. package/src/mesh/mesh-events-coordinator.ts +1404 -0
  168. package/src/mesh/mesh-events-pending.ts +371 -0
  169. package/src/mesh/mesh-events-stale.ts +283 -0
  170. package/src/mesh/mesh-events-utils.ts +161 -0
  171. package/src/mesh/mesh-events.ts +24 -908
  172. package/src/mesh/mesh-fast-forward.ts +438 -0
  173. package/src/mesh/mesh-host-ownership.ts +73 -0
  174. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  175. package/src/mesh/mesh-ledger.ts +587 -102
  176. package/src/mesh/mesh-missions.ts +151 -0
  177. package/src/mesh/mesh-refine-status.ts +144 -0
  178. package/src/mesh/mesh-review-inbox.ts +307 -0
  179. package/src/mesh/mesh-runtime-store.ts +1305 -0
  180. package/src/mesh/mesh-task-stats.ts +154 -0
  181. package/src/mesh/mesh-work-queue.ts +490 -166
  182. package/src/mesh/preview-freshness.ts +118 -0
  183. package/src/mesh/refine-config.ts +403 -0
  184. package/src/mesh/worktree-bootstrap-config.ts +326 -0
  185. package/src/providers/acp-provider-instance.ts +15 -1
  186. package/src/providers/approval-utils.d.ts +4 -0
  187. package/src/providers/approval-utils.ts +47 -5
  188. package/src/providers/chat-message-normalization.ts +4 -11
  189. package/src/providers/cli-provider-instance.ts +833 -64
  190. package/src/providers/contracts.d.ts +55 -0
  191. package/src/providers/contracts.ts +141 -6
  192. package/src/providers/external-sources.ts +218 -0
  193. package/src/providers/ide-provider-instance.ts +19 -5
  194. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  195. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  196. package/src/providers/native-history/codex-cli-transcript.ts +419 -0
  197. package/src/providers/native-history/dispatcher.ts +340 -0
  198. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  199. package/src/providers/native-history/index.ts +30 -0
  200. package/src/providers/provider-instance-manager.ts +30 -0
  201. package/src/providers/provider-instance.ts +10 -1
  202. package/src/providers/provider-loader.ts +582 -50
  203. package/src/providers/provider-schema.ts +87 -14
  204. package/src/providers/provider-trust.ts +114 -0
  205. package/src/providers/read-chat-contract.ts +76 -16
  206. package/src/providers/sdk/README.md +49 -0
  207. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  208. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  209. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  210. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  211. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  212. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  213. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  214. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  215. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  216. package/src/providers/sdk/v1/index.ts +152 -0
  217. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  218. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  219. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  220. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  221. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  222. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  223. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  224. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  225. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  226. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  227. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  228. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  229. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  230. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  231. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  232. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  233. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  234. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  235. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  236. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  237. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  238. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  239. package/src/providers/sdk/v1/validators/index.ts +19 -0
  240. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  241. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  242. package/src/providers/spec/adapter.ts +138 -0
  243. package/src/providers/spec/cli-adapter.ts +626 -0
  244. package/src/providers/spec/driver.ts +912 -0
  245. package/src/providers/spec/evaluator.ts +597 -0
  246. package/src/providers/spec/loader.ts +324 -0
  247. package/src/providers/spec/native-history-executor.ts +939 -0
  248. package/src/providers/spec/route.ts +51 -0
  249. package/src/providers/spec/schema.gen.ts +691 -0
  250. package/src/providers/spec/schema.json +341 -0
  251. package/src/providers/spec/types.ts +356 -0
  252. package/src/providers/transcript-v2.ts +567 -0
  253. package/src/providers/types/interactive-prompt.ts +425 -0
  254. package/src/providers/version-archive.ts +38 -20
  255. package/src/repo-mesh-types.ts +119 -1
  256. package/src/sessions/registry.ts +3 -0
  257. package/src/shared-types-extra.ts +2 -4
  258. package/src/shared-types.ts +45 -1
  259. package/src/status/builders.ts +24 -6
  260. package/src/status/normalize.ts +2 -0
  261. package/src/status/reporter.ts +15 -0
  262. package/src/status/snapshot.ts +84 -25
  263. package/src/system/host-memory.ts +29 -12
  264. package/src/types.ts +5 -0
  265. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  266. package/dist/mesh/mesh-sync.d.ts +0 -53
  267. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  268. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  269. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,939 @@
1
+ /**
2
+ * Declarative native-history executor.
3
+ *
4
+ * Reads a spec.json's `native_history.source` block and turns it into a
5
+ * NativeHistoryResult by talking directly to the on-disk store (jsonl
6
+ * file or sqlite db). No per-provider TypeScript reader required —
7
+ * adding a new provider is just authoring spec.json.
8
+ *
9
+ * Two source kinds:
10
+ * - jsonl — newest matching file inside a path (with variable expansion)
11
+ * + jsonpath-lite map for each record
12
+ * - sqlite — read-only better-sqlite3 handle, two queries (session pick
13
+ * + message fetch) + jsonpath-lite map for each row
14
+ *
15
+ * Exotic formats can still ship a provider-local reader via
16
+ * `native_history.override_path` — the dispatcher in provider-loader picks
17
+ * that path instead of calling this executor.
18
+ */
19
+ 'use strict';
20
+
21
+ import * as fs from 'node:fs';
22
+ import * as os from 'node:os';
23
+ import * as path from 'node:path';
24
+ import type {
25
+ NativeHistoryConfig,
26
+ NativeHistoryJsonlSource,
27
+ NativeHistoryMessageMap,
28
+ NativeHistorySqliteSource,
29
+ } from './types.js';
30
+
31
+ export interface NativeHistoryInput {
32
+ agentType?: string;
33
+ sessionId?: string;
34
+ providerSessionId?: string;
35
+ historySessionId?: string;
36
+ workspace?: string;
37
+ /** Daemon-side wall clock at the moment the session was registered.
38
+ * Native-history file lookups use this as the lower bound: any file
39
+ * whose mtime is before the current session started can't be from
40
+ * this session, so it's excluded from newest-recent matching. The
41
+ * caller (chat-history pipeline) populates this from the session
42
+ * registry; specs/executor never need to know how it's sourced. */
43
+ sessionStartedAtMs?: number;
44
+ /** Env overrides the daemon set on the spawned CLI. The mesh
45
+ * coordinator points hermes at a per-coordinator HERMES_HOME so
46
+ * the hermes process writes its state.db into a tmp directory
47
+ * instead of ~/.hermes. expandPath consults this map before
48
+ * process.env so the native-history reader follows the spawned
49
+ * child's view of HERMES_HOME / similar overrides; without it
50
+ * the reader would always look at ~/.hermes and miss every
51
+ * coordinator-session transcript. */
52
+ envOverrides?: Record<string, string>;
53
+ args?: Record<string, unknown>;
54
+ }
55
+
56
+ export interface NativeHistoryMessage {
57
+ role: 'user' | 'assistant' | 'system';
58
+ content: string;
59
+ receivedAt: number;
60
+ kind?: string;
61
+ workspace?: string;
62
+ }
63
+
64
+ export interface NativeHistoryResult {
65
+ messages: NativeHistoryMessage[];
66
+ providerSessionId?: string;
67
+ sourcePath: string;
68
+ sourceMtimeMs: number;
69
+ nativeHistoryCoverage?: 'full' | 'partial' | 'best-effort';
70
+ workspace?: string;
71
+ }
72
+
73
+ const UUID_RE = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;
74
+
75
+ export function executeNativeHistory(cfg: NativeHistoryConfig, input: NativeHistoryInput): NativeHistoryResult | null {
76
+ if (!cfg?.source) return null;
77
+ if (cfg.source.kind === 'jsonl') return executeJsonl(cfg.source, input);
78
+ if (cfg.source.kind === 'sqlite') return executeSqlite(cfg.source, input);
79
+ return null;
80
+ }
81
+
82
+ // ────────────────────────────────────────────────────────────────────────────
83
+ // JSONL
84
+ // ────────────────────────────────────────────────────────────────────────────
85
+
86
+ function executeJsonl(src: NativeHistoryJsonlSource, input: NativeHistoryInput): NativeHistoryResult | null {
87
+ const resolved = expandPath(src.path, input);
88
+ if (!resolved) return null;
89
+
90
+ const windowMs = typeof src.recent_window_ms === 'number' ? src.recent_window_ms : 5 * 60_000;
91
+ const filePat = src.file_pattern ? globToRegex(src.file_pattern) : /.*\.jsonl$/;
92
+ const requestedSessionId = readRequestedSessionId(input);
93
+
94
+ // path can be:
95
+ // - a concrete file → used as-is
96
+ // - a concrete dir → newest matching file inside recent_window_ms
97
+ // - a path with `*` or `**` segments → walk all dirs that match the
98
+ // glob, pick the newest matching file across all matches. Lets
99
+ // specs like ~/.gemini/antigravity-cli/brain/*/.system_generated/logs
100
+ // resolve transparently without a per-provider override.
101
+ // The session-start cutoff guarantees a fresh dashboard view can't
102
+ // pick up a transcript file from a session that ended before this
103
+ // one started. recent_window_ms only controls how far back we'd
104
+ // otherwise look for a matching file; the session-start floor wins
105
+ // when it's later.
106
+ const sessionFloor = typeof input.sessionStartedAtMs === 'number' ? input.sessionStartedAtMs : 0;
107
+ // When multiple concurrent CLI sessions in the same workspace each create
108
+ // their own rollout (e.g. two codex-cli sessions both writing into
109
+ // ~/.codex/sessions/{date}), `newestRecentFile` picks the same file for
110
+ // every reader and the daemon sessions cross-alias each other. Prefer
111
+ // session-meta-aware matching: the candidate whose meta.cwd matches the
112
+ // workspace AND whose meta.timestamp is closest to (or within
113
+ // spawnGraceMs of) the daemon's spawn time wins. Falls back to mtime
114
+ // ordering when no candidate exposes a usable session_meta.
115
+ const workspaceHint = typeof input.workspace === 'string' && input.workspace.trim() ? input.workspace.trim() : '';
116
+ let sourcePath: string | null = null;
117
+ if (resolved.includes('*')) {
118
+ sourcePath = pickExactSessionFileAcrossGlob(resolved, filePat, requestedSessionId)
119
+ || pickSessionBoundFileAcrossGlob(resolved, filePat, windowMs, sessionFloor, workspaceHint)
120
+ || newestRecentFileAcrossGlob(resolved, filePat, windowMs, sessionFloor);
121
+ } else {
122
+ let stat: fs.Stats | null = null;
123
+ try { stat = fs.statSync(resolved); } catch { /* fall through to date-walk fallback */ }
124
+ if (stat && stat.isFile()) {
125
+ sourcePath = resolved;
126
+ } else if (stat && stat.isDirectory()) {
127
+ sourcePath = pickExactSessionFile(resolved, filePat, requestedSessionId)
128
+ || (requestedSessionId ? null : pickSessionBoundFile(resolved, filePat, windowMs, sessionFloor, workspaceHint))
129
+ || (requestedSessionId ? null : newestRecentFile(resolved, filePat, windowMs, sessionFloor));
130
+ }
131
+ // Date-templated directories (e.g. ~/.codex/sessions/{yyyy}/{mm}/{dd})
132
+ // can drift from the provider's chosen calendar day because CLIs
133
+ // disagree on local-vs-UTC date buckets. Search nearby date dirs
134
+ // before falling back to non-exact matching.
135
+ if (!sourcePath && hasDateTemplateSegment(src.path)) {
136
+ sourcePath = pickExactSessionFileAcrossDateWindow(src.path, input, filePat, requestedSessionId)
137
+ || (requestedSessionId ? null : pickSessionBoundFileAcrossDateWindow(src.path, input, filePat, windowMs, sessionFloor, workspaceHint))
138
+ || (requestedSessionId ? null : newestRecentFileAcrossDateWindow(src.path, input, filePat, windowMs, sessionFloor));
139
+ }
140
+ }
141
+ if (!sourcePath) return null;
142
+
143
+ const mtime = safeMtimeMs(sourcePath);
144
+ const lines = readJsonlLines(sourcePath);
145
+ if (lines.length === 0) return null;
146
+ const transcriptWorkspace = readSessionMetaWorkspace(lines);
147
+
148
+ // session id: filename uuid or extracted from first record
149
+ let providerSessionId: string | undefined;
150
+ if (src.session_id_from === 'first_record' && src.session_id_path) {
151
+ const v = jsonPathGet(lines[0], src.session_id_path);
152
+ if (typeof v === 'string' && v) providerSessionId = v;
153
+ } else if (src.session_id_from === 'filename_uuid' || !src.session_id_from) {
154
+ const m = path.basename(sourcePath).match(UUID_RE);
155
+ if (m) providerSessionId = m[1];
156
+ }
157
+
158
+ const requested = requestedSessionId || '';
159
+ if (requested && providerSessionId && providerSessionId !== requested) return null;
160
+
161
+ const filter = src.message_filter ? compileWhere(src.message_filter.where) : null;
162
+ const messages: NativeHistoryMessage[] = [];
163
+ for (let i = 0; i < lines.length; i += 1) {
164
+ const rec = lines[i];
165
+ if (filter && !filter(rec)) continue;
166
+ const msg = projectMessage(rec, src.message_map, i, lines.length, mtime);
167
+ if (msg) {
168
+ if (transcriptWorkspace) msg.workspace = transcriptWorkspace;
169
+ messages.push(msg);
170
+ }
171
+ }
172
+ if (messages.length === 0) return null;
173
+
174
+ return {
175
+ messages,
176
+ providerSessionId,
177
+ sourcePath,
178
+ sourceMtimeMs: mtime,
179
+ nativeHistoryCoverage: 'full',
180
+ workspace: transcriptWorkspace,
181
+ };
182
+ }
183
+
184
+ function readSessionMetaWorkspace(lines: any[]): string | undefined {
185
+ for (const record of lines.slice(0, 5)) {
186
+ if (String(record?.type ?? '') !== 'session_meta') continue;
187
+ const cwd = typeof record?.payload?.cwd === 'string' ? record.payload.cwd.trim() : '';
188
+ if (cwd) return cwd;
189
+ }
190
+ return undefined;
191
+ }
192
+
193
+ function readJsonlLines(p: string): any[] {
194
+ let text: string;
195
+ try { text = fs.readFileSync(p, 'utf8'); } catch { return []; }
196
+ const out: any[] = [];
197
+ for (const line of text.split('\n')) {
198
+ const trimmed = line.trim();
199
+ if (!trimmed) continue;
200
+ try { out.push(JSON.parse(trimmed)); } catch { /* skip malformed line */ }
201
+ }
202
+ return out;
203
+ }
204
+
205
+ // ────────────────────────────────────────────────────────────────────────────
206
+ // SQLite
207
+ // ────────────────────────────────────────────────────────────────────────────
208
+
209
+ function executeSqlite(src: NativeHistorySqliteSource, input: NativeHistoryInput): NativeHistoryResult | null {
210
+ const resolved = expandPath(src.path, input);
211
+ if (!resolved || !fs.existsSync(resolved)) return null;
212
+
213
+ let Database: any;
214
+ try {
215
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
216
+ Database = require('better-sqlite3');
217
+ } catch { return null; }
218
+
219
+ let db: any;
220
+ try { db = new Database(resolved, { readonly: true, fileMustExist: true }); }
221
+ catch { return null; }
222
+
223
+ try {
224
+ let sessionRow: any;
225
+ try {
226
+ // session_query may reference `?` to receive the session's
227
+ // start-time floor in seconds (e.g. WHERE started_at >= ?).
228
+ // That gives spec authors a robust way to keep prior-session
229
+ // rows out of a fresh dashboard view without inventing their
230
+ // own time arithmetic in SQL. When the caller didn't pass a
231
+ // session floor (i.e. no live session is associated with the
232
+ // call), we use 0 so spec queries that bind `?` still produce
233
+ // a sane result rather than choking the whole executor.
234
+ const sessionFloorSeconds = typeof input.sessionStartedAtMs === 'number'
235
+ ? Math.floor(input.sessionStartedAtMs / 1000)
236
+ : 0;
237
+ const stmt = db.prepare(src.session_query);
238
+ try {
239
+ sessionRow = stmt.get(sessionFloorSeconds);
240
+ } catch {
241
+ sessionRow = stmt.get();
242
+ }
243
+ } catch { return null; }
244
+ if (!sessionRow) return null;
245
+ // First column of the first row is the session id.
246
+ const sessionIdRaw = Object.values(sessionRow)[0];
247
+ const sessionId = sessionIdRaw == null ? '' : String(sessionIdRaw);
248
+ if (!sessionId) return null;
249
+
250
+ const requested = input.providerSessionId || '';
251
+ if (requested && sessionId !== requested) return null;
252
+
253
+ const messageRows: any[] = db.prepare(src.message_query).all(sessionId);
254
+ if (!messageRows || messageRows.length === 0) return null;
255
+
256
+ const mtime = safeMtimeMs(resolved);
257
+ const messages: NativeHistoryMessage[] = [];
258
+ for (let i = 0; i < messageRows.length; i += 1) {
259
+ const msg = projectMessage(messageRows[i], src.message_map, i, messageRows.length, mtime);
260
+ if (msg) messages.push(msg);
261
+ }
262
+ if (messages.length === 0) return null;
263
+
264
+ return {
265
+ messages,
266
+ providerSessionId: sessionId,
267
+ sourcePath: resolved,
268
+ sourceMtimeMs: mtime,
269
+ nativeHistoryCoverage: 'full',
270
+ };
271
+ } finally {
272
+ try { db.close(); } catch { /* ignore */ }
273
+ }
274
+ }
275
+
276
+ // ────────────────────────────────────────────────────────────────────────────
277
+ // Path expansion + globbing
278
+ // ────────────────────────────────────────────────────────────────────────────
279
+
280
+ function expandPath(template: string, input: NativeHistoryInput): string | null {
281
+ if (!template) return null;
282
+ let out = template;
283
+ if (out.startsWith('~/') || out === '~') {
284
+ out = path.join(os.homedir(), out.slice(2));
285
+ }
286
+ // ${VAR} expands from envOverrides (the spawned child's view) first,
287
+ // then process.env. ${VAR:-fallback} keeps the bash-style default
288
+ // so spec authors can say e.g. ${HERMES_HOME:-~/.hermes}/state.db
289
+ // and have it work both for coordinator-launched sessions (where
290
+ // HERMES_HOME is set to a tmpdir) and normal sessions.
291
+ out = out.replace(/\$\{([A-Z_][A-Z0-9_]*)(?::-(.*?))?\}/g, (_m, name, fallback) => {
292
+ const v = input.envOverrides?.[name] ?? process.env[name];
293
+ return v != null && v !== '' ? v : (fallback ?? '');
294
+ });
295
+ // Re-expand ~ in case the fallback used it.
296
+ if (out.startsWith('~/')) out = path.join(os.homedir(), out.slice(2));
297
+ const now = new Date();
298
+ // claude (and a couple of other Anthropic-CLI–style providers) writes
299
+ // its per-cwd transcript under the *resolved* path
300
+ // (/private/tmp/foo, not /tmp/foo on macOS where /tmp -> /private/tmp).
301
+ // Without realpath, the spec template `~/.claude/projects/{cwd_dashed}/…`
302
+ // builds `-tmp-foo` and never finds the actual `-private-tmp-foo` dir.
303
+ const workspaceRaw = input.workspace ?? '';
304
+ let workspaceResolved = workspaceRaw;
305
+ if (workspaceRaw) {
306
+ try { workspaceResolved = fs.realpathSync(workspaceRaw); }
307
+ catch { /* path may not exist yet — keep the raw value */ }
308
+ }
309
+ const vars: Record<string, string> = {
310
+ cwd: workspaceResolved,
311
+ cwd_dashed: workspaceResolved.replace(/\//g, '-'),
312
+ session_id: input.providerSessionId || input.sessionId || input.historySessionId || '',
313
+ yyyy: String(now.getFullYear()),
314
+ mm: String(now.getMonth() + 1).padStart(2, '0'),
315
+ dd: String(now.getDate()).padStart(2, '0'),
316
+ };
317
+ // Replace {var}. If a referenced variable is empty (e.g. session_id
318
+ // before the agent has allocated one), return null so the caller
319
+ // doesn't accidentally fall through to an unrelated newest-file
320
+ // match. Wildcards (`*`) are explicitly allowed to pass — the dir
321
+ // glob walker handles them separately.
322
+ let missing = false;
323
+ out = out.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_m, name) => {
324
+ const v = vars[name] ?? '';
325
+ if (!v) missing = true;
326
+ return v;
327
+ });
328
+ if (missing) return null;
329
+ return out;
330
+ }
331
+
332
+ function globToRegex(pattern: string): RegExp {
333
+ // Minimal glob: `*` → `[^/]*`, `?` → `[^/]`, `.` → `\.`. Anchored.
334
+ const re = pattern
335
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
336
+ .replace(/\*/g, '[^/]*')
337
+ .replace(/\?/g, '[^/]');
338
+ return new RegExp(`^${re}$`);
339
+ }
340
+
341
+ /**
342
+ * Resolve a path with `*` segments to all concrete directories that match,
343
+ * then pick the newest file inside any of them. `*` matches one path
344
+ * component (no slashes); `**` matches zero or more components. Filenames
345
+ * are matched against `pattern`, not the glob — file_pattern is the right
346
+ * place for the leaf match.
347
+ */
348
+ function expandDirGlob(template: string): string[] {
349
+ const parts = template.split('/');
350
+ let dirs: string[] = parts[0] === '' ? ['/'] : [parts[0]];
351
+ for (let i = 1; i < parts.length; i += 1) {
352
+ const seg = parts[i];
353
+ if (!seg) continue;
354
+ const next: string[] = [];
355
+ if (seg === '**') {
356
+ for (const d of dirs) walkAllDirs(d, next);
357
+ dirs = next;
358
+ continue;
359
+ }
360
+ if (seg.includes('*') || seg.includes('?')) {
361
+ const re = globToRegex(seg);
362
+ for (const d of dirs) {
363
+ let entries: fs.Dirent[];
364
+ try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch { continue; }
365
+ for (const e of entries) {
366
+ if (e.isDirectory() && re.test(e.name)) next.push(path.join(d, e.name));
367
+ }
368
+ }
369
+ } else {
370
+ for (const d of dirs) {
371
+ const candidate = path.join(d, seg);
372
+ let stat: fs.Stats | null = null;
373
+ try { stat = fs.statSync(candidate); } catch { continue; }
374
+ if (stat.isDirectory()) next.push(candidate);
375
+ }
376
+ }
377
+ dirs = next;
378
+ }
379
+ return dirs;
380
+ }
381
+
382
+ function walkAllDirs(root: string, out: string[]): void {
383
+ let entries: fs.Dirent[];
384
+ try { entries = fs.readdirSync(root, { withFileTypes: true }); } catch { return; }
385
+ out.push(root);
386
+ for (const e of entries) {
387
+ if (e.isDirectory()) walkAllDirs(path.join(root, e.name), out);
388
+ }
389
+ }
390
+
391
+ function newestRecentFileAcrossGlob(template: string, pattern: RegExp, windowMs: number, sessionFloorMs = 0): string | null {
392
+ const dirs = expandDirGlob(template);
393
+ const cutoff = Math.max(Date.now() - windowMs, sessionFloorMs);
394
+ let best: { p: string; mtime: number } | null = null;
395
+ for (const d of dirs) {
396
+ let entries: fs.Dirent[];
397
+ try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch { continue; }
398
+ for (const e of entries) {
399
+ if (!e.isFile() || !pattern.test(e.name)) continue;
400
+ const p = path.join(d, e.name);
401
+ const mtime = safeMtimeMs(p);
402
+ if (mtime < cutoff) continue;
403
+ if (!best || mtime > best.mtime) best = { p, mtime };
404
+ }
405
+ }
406
+ return best ? best.p : null;
407
+ }
408
+
409
+ function hasDateTemplateSegment(template: string): boolean {
410
+ return /\{yyyy\}|\{mm\}|\{dd\}/.test(template);
411
+ }
412
+
413
+ /**
414
+ * Walk nearby local calendar days of a date-templated path (e.g.
415
+ * `~/.codex/sessions/{yyyy}/{mm}/{dd}`) and return the newest matching
416
+ * file across all of them. Providers differ on local-vs-UTC date buckets,
417
+ * so today's expanded dir alone can miss a live transcript.
418
+ */
419
+ function newestRecentFileAcrossDateWindow(
420
+ template: string,
421
+ input: NativeHistoryInput,
422
+ pattern: RegExp,
423
+ windowMs: number,
424
+ sessionFloorMs: number,
425
+ ): string | null {
426
+ const cutoff = Math.max(Date.now() - windowMs, sessionFloorMs);
427
+ let best: { p: string; mtime: number } | null = null;
428
+ for (const dayOffset of [0, -1, 1, -2, 2]) {
429
+ const dayMs = Date.now() + dayOffset * 24 * 60 * 60 * 1000;
430
+ const dayInput: NativeHistoryInput = { ...input, sessionStartedAtMs: sessionFloorMs };
431
+ const resolved = expandPathForDate(template, dayInput, new Date(dayMs));
432
+ if (!resolved) continue;
433
+ let entries: fs.Dirent[];
434
+ try { entries = fs.readdirSync(resolved, { withFileTypes: true }); } catch { continue; }
435
+ for (const e of entries) {
436
+ if (!e.isFile() || !pattern.test(e.name)) continue;
437
+ const p = path.join(resolved, e.name);
438
+ const mtime = safeMtimeMs(p);
439
+ if (mtime < cutoff) continue;
440
+ if (!best || mtime > best.mtime) best = { p, mtime };
441
+ }
442
+ }
443
+ return best ? best.p : null;
444
+ }
445
+
446
+ function expandPathForDate(template: string, input: NativeHistoryInput, day: Date): string | null {
447
+ // Reuse expandPath logic but stamp {yyyy}/{mm}/{dd} from the given day.
448
+ if (!template) return null;
449
+ let out = template;
450
+ if (out.startsWith('~/') || out === '~') {
451
+ out = path.join(os.homedir(), out.slice(2));
452
+ }
453
+ out = out.replace(/\$\{([A-Z_][A-Z0-9_]*)(?::-(.*?))?\}/g, (_m, name, fallback) => {
454
+ const v = input.envOverrides?.[name] ?? process.env[name];
455
+ return v != null && v !== '' ? v : (fallback ?? '');
456
+ });
457
+ if (out.startsWith('~/')) out = path.join(os.homedir(), out.slice(2));
458
+ const workspaceRaw = input.workspace ?? '';
459
+ let workspaceResolved = workspaceRaw;
460
+ if (workspaceRaw) {
461
+ try { workspaceResolved = fs.realpathSync(workspaceRaw); } catch { /* keep raw */ }
462
+ }
463
+ const vars: Record<string, string> = {
464
+ cwd: workspaceResolved,
465
+ cwd_dashed: workspaceResolved.replace(/\//g, '-'),
466
+ session_id: input.providerSessionId || input.sessionId || input.historySessionId || '',
467
+ yyyy: String(day.getFullYear()),
468
+ mm: String(day.getMonth() + 1).padStart(2, '0'),
469
+ dd: String(day.getDate()).padStart(2, '0'),
470
+ };
471
+ let missing = false;
472
+ out = out.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_m, name) => {
473
+ const v = vars[name] ?? '';
474
+ if (!v) missing = true;
475
+ return v;
476
+ });
477
+ if (missing) return null;
478
+ return out;
479
+ }
480
+
481
+ function newestRecentFile(dir: string, pattern: RegExp, windowMs: number, sessionFloorMs = 0): string | null {
482
+ let entries: fs.Dirent[];
483
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return null; }
484
+ const cutoff = Math.max(Date.now() - windowMs, sessionFloorMs);
485
+ let best: { p: string; mtime: number } | null = null;
486
+ for (const e of entries) {
487
+ if (!e.isFile() || !pattern.test(e.name)) continue;
488
+ const p = path.join(dir, e.name);
489
+ const mtime = safeMtimeMs(p);
490
+ if (mtime < cutoff) continue;
491
+ if (!best || mtime > best.mtime) best = { p, mtime };
492
+ }
493
+ return best ? best.p : null;
494
+ }
495
+
496
+ function safeMtimeMs(p: string): number {
497
+ try { return Math.floor(fs.statSync(p).mtimeMs); } catch { return 0; }
498
+ }
499
+
500
+ function readRequestedSessionId(input: NativeHistoryInput): string {
501
+ const raw = input.providerSessionId || input.sessionId || input.historySessionId || '';
502
+ const value = typeof raw === 'string' ? raw.trim() : '';
503
+ return UUID_RE.test(value) ? value : '';
504
+ }
505
+
506
+ function filenameUuid(filePath: string): string {
507
+ const match = path.basename(filePath).match(UUID_RE);
508
+ return match?.[1] || '';
509
+ }
510
+
511
+ function pickExactSessionFile(dir: string, pattern: RegExp, requestedSessionId: string): string | null {
512
+ if (!requestedSessionId) return null;
513
+ const files = listMatchingFiles(dir, pattern)
514
+ .filter(p => filenameUuid(p).toLowerCase() === requestedSessionId.toLowerCase())
515
+ .sort((a, b) => safeMtimeMs(b) - safeMtimeMs(a));
516
+ return files[0] || null;
517
+ }
518
+
519
+ function pickExactSessionFileAcrossGlob(template: string, pattern: RegExp, requestedSessionId: string): string | null {
520
+ if (!requestedSessionId) return null;
521
+ const dirs = expandDirGlob(template);
522
+ const matches: string[] = [];
523
+ for (const d of dirs) {
524
+ const found = pickExactSessionFile(d, pattern, requestedSessionId);
525
+ if (found) matches.push(found);
526
+ }
527
+ matches.sort((a, b) => safeMtimeMs(b) - safeMtimeMs(a));
528
+ return matches[0] || null;
529
+ }
530
+
531
+ function pickExactSessionFileAcrossDateWindow(
532
+ template: string,
533
+ input: NativeHistoryInput,
534
+ pattern: RegExp,
535
+ requestedSessionId: string,
536
+ ): string | null {
537
+ if (!requestedSessionId) return null;
538
+ const matches: string[] = [];
539
+ for (const dayOffset of [0, -1, 1, -2, 2]) {
540
+ const dayMs = Date.now() + dayOffset * 24 * 60 * 60 * 1000;
541
+ const resolved = expandPathForDate(template, input, new Date(dayMs));
542
+ if (!resolved) continue;
543
+ const found = pickExactSessionFile(resolved, pattern, requestedSessionId);
544
+ if (found) matches.push(found);
545
+ }
546
+ matches.sort((a, b) => safeMtimeMs(b) - safeMtimeMs(a));
547
+ return matches[0] || null;
548
+ }
549
+
550
+ // ────────────────────────────────────────────────────────────────────────────
551
+ // Per-session rollout binding
552
+ //
553
+ // Reads the first JSONL line of a candidate file and returns a `session_meta`
554
+ // payload if present. Codex-cli writes
555
+ // {"timestamp":"...","type":"session_meta","payload":{"id":...,"cwd":...,
556
+ // "timestamp":"..."}}
557
+ // as the first record. Other providers that don't follow this convention
558
+ // return null and fall back to the mtime-based picker.
559
+ // ────────────────────────────────────────────────────────────────────────────
560
+
561
+ interface CandidateMeta {
562
+ cwd?: string;
563
+ sessionTimestampMs?: number;
564
+ }
565
+
566
+ function readCandidateSessionMeta(filePath: string): CandidateMeta | null {
567
+ try {
568
+ // Read only the first line — meta is always the first JSONL record
569
+ // and full file reads here would scale O(files × file_size).
570
+ const fd = fs.openSync(filePath, 'r');
571
+ try {
572
+ const buf = Buffer.alloc(8192);
573
+ const bytes = fs.readSync(fd, buf, 0, buf.length, 0);
574
+ if (bytes <= 0) return null;
575
+ const text = buf.subarray(0, bytes).toString('utf8');
576
+ const nl = text.indexOf('\n');
577
+ const firstLine = (nl >= 0 ? text.slice(0, nl) : text).trim();
578
+ if (!firstLine) return null;
579
+ const parsed = JSON.parse(firstLine) as Record<string, unknown>;
580
+ if (String(parsed.type ?? '') !== 'session_meta') return null;
581
+ const payload = parsed.payload && typeof parsed.payload === 'object'
582
+ ? (parsed.payload as Record<string, unknown>)
583
+ : null;
584
+ if (!payload) return null;
585
+ const cwd = typeof payload.cwd === 'string' ? payload.cwd : undefined;
586
+ const tsRaw = payload.timestamp;
587
+ const tsMs = typeof tsRaw === 'string'
588
+ ? Date.parse(tsRaw)
589
+ : typeof tsRaw === 'number'
590
+ ? (tsRaw < 1e12 ? Math.floor(tsRaw * 1000) : Math.floor(tsRaw))
591
+ : NaN;
592
+ return {
593
+ cwd,
594
+ sessionTimestampMs: Number.isFinite(tsMs) ? tsMs : undefined,
595
+ };
596
+ } finally {
597
+ fs.closeSync(fd);
598
+ }
599
+ } catch {
600
+ return null;
601
+ }
602
+ }
603
+
604
+ /**
605
+ * Spawn-bind grace window: an on-disk rollout whose session_meta.timestamp
606
+ * lands within ±SPAWN_BIND_GRACE_MS of the daemon's spawnedAtMs is treated
607
+ * as belonging to that daemon session. 10s is long enough to absorb codex
608
+ * binary startup latency on cold caches and short enough that two
609
+ * back-to-back launches don't both fall inside the same window.
610
+ */
611
+ const SPAWN_BIND_GRACE_MS = 10_000;
612
+
613
+ function pickBoundFromEntries(
614
+ candidatePaths: string[],
615
+ sessionFloorMs: number,
616
+ workspaceHint: string,
617
+ ): string | null {
618
+ if (!sessionFloorMs || !workspaceHint || candidatePaths.length === 0) return null;
619
+ // Resolve workspaceHint to handle macOS /tmp → /private/tmp aliasing, the
620
+ // same way expandPath does for the template substitution. Without this
621
+ // the daemon's `/Users/foo/repo` and codex's `/private/Users/foo/repo`
622
+ // never compare equal and disambiguation silently fails.
623
+ let workspaceResolved = workspaceHint;
624
+ try { workspaceResolved = fs.realpathSync(workspaceHint); } catch { /* keep raw */ }
625
+ let best: { p: string; diff: number } | null = null;
626
+ for (const p of candidatePaths) {
627
+ const meta = readCandidateSessionMeta(p);
628
+ if (!meta || !meta.cwd || meta.sessionTimestampMs == null) continue;
629
+ let candidateCwd = meta.cwd;
630
+ try { candidateCwd = fs.realpathSync(meta.cwd); } catch { /* keep raw */ }
631
+ if (candidateCwd !== workspaceResolved && meta.cwd !== workspaceHint) continue;
632
+ const diff = Math.abs(meta.sessionTimestampMs - sessionFloorMs);
633
+ if (diff > SPAWN_BIND_GRACE_MS) continue;
634
+ if (!best || diff < best.diff) best = { p, diff };
635
+ }
636
+ return best ? best.p : null;
637
+ }
638
+
639
+ function listMatchingFiles(dir: string, pattern: RegExp): string[] {
640
+ let entries: fs.Dirent[];
641
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return []; }
642
+ const out: string[] = [];
643
+ for (const e of entries) {
644
+ if (!e.isFile() || !pattern.test(e.name)) continue;
645
+ out.push(path.join(dir, e.name));
646
+ }
647
+ return out;
648
+ }
649
+
650
+ function pickSessionBoundFile(
651
+ dir: string,
652
+ pattern: RegExp,
653
+ windowMs: number,
654
+ sessionFloorMs: number,
655
+ workspaceHint: string,
656
+ ): string | null {
657
+ if (!sessionFloorMs || !workspaceHint) return null;
658
+ const cutoff = Math.max(Date.now() - windowMs, sessionFloorMs - SPAWN_BIND_GRACE_MS);
659
+ const files = listMatchingFiles(dir, pattern).filter(p => safeMtimeMs(p) >= cutoff);
660
+ return pickBoundFromEntries(files, sessionFloorMs, workspaceHint);
661
+ }
662
+
663
+ function pickSessionBoundFileAcrossGlob(
664
+ template: string,
665
+ pattern: RegExp,
666
+ windowMs: number,
667
+ sessionFloorMs: number,
668
+ workspaceHint: string,
669
+ ): string | null {
670
+ if (!sessionFloorMs || !workspaceHint) return null;
671
+ const dirs = expandDirGlob(template);
672
+ const cutoff = Math.max(Date.now() - windowMs, sessionFloorMs - SPAWN_BIND_GRACE_MS);
673
+ const files: string[] = [];
674
+ for (const d of dirs) {
675
+ for (const p of listMatchingFiles(d, pattern)) {
676
+ if (safeMtimeMs(p) >= cutoff) files.push(p);
677
+ }
678
+ }
679
+ return pickBoundFromEntries(files, sessionFloorMs, workspaceHint);
680
+ }
681
+
682
+ function pickSessionBoundFileAcrossDateWindow(
683
+ template: string,
684
+ input: NativeHistoryInput,
685
+ pattern: RegExp,
686
+ windowMs: number,
687
+ sessionFloorMs: number,
688
+ workspaceHint: string,
689
+ ): string | null {
690
+ if (!sessionFloorMs || !workspaceHint) return null;
691
+ const cutoff = Math.max(Date.now() - windowMs, sessionFloorMs - SPAWN_BIND_GRACE_MS);
692
+ const files: string[] = [];
693
+ for (const dayOffset of [0, -1, 1, -2, 2]) {
694
+ const dayMs = sessionFloorMs + dayOffset * 24 * 60 * 60 * 1000;
695
+ const dayInput: NativeHistoryInput = { ...input, sessionStartedAtMs: sessionFloorMs };
696
+ const resolved = expandPathForDate(template, dayInput, new Date(dayMs));
697
+ if (!resolved) continue;
698
+ for (const p of listMatchingFiles(resolved, pattern)) {
699
+ if (safeMtimeMs(p) >= cutoff) files.push(p);
700
+ }
701
+ }
702
+ return pickBoundFromEntries(files, sessionFloorMs, workspaceHint);
703
+ }
704
+
705
+ // ────────────────────────────────────────────────────────────────────────────
706
+ // jsonpath-lite + projection
707
+ // ────────────────────────────────────────────────────────────────────────────
708
+
709
+ /**
710
+ * Resolve `$.a.b[0].c` against a record. Strings without leading `$` are
711
+ * literals. Supports `||` fallback between paths so a single message_map
712
+ * entry can pick the first non-empty value across alternative locations
713
+ * (e.g. agy's content vs. thinking).
714
+ */
715
+ function jsonPathGet(record: any, expr: string): unknown {
716
+ if (typeof expr !== 'string') return undefined;
717
+ if (expr.includes('||')) {
718
+ for (const alt of expr.split('||')) {
719
+ const v = jsonPathGet(record, alt.trim());
720
+ if (v != null && v !== '') return v;
721
+ }
722
+ return undefined;
723
+ }
724
+ if (!expr.startsWith('$')) return expr;
725
+ let cur: any = record;
726
+ let i = 1;
727
+ while (i < expr.length && cur != null) {
728
+ const ch = expr[i];
729
+ if (ch === '.') { i += 1; continue; }
730
+ if (ch === '[') {
731
+ const close = expr.indexOf(']', i);
732
+ if (close < 0) return undefined;
733
+ const idx = Number(expr.slice(i + 1, close));
734
+ if (!Number.isInteger(idx)) return undefined;
735
+ cur = cur[idx];
736
+ i = close + 1;
737
+ continue;
738
+ }
739
+ let end = i;
740
+ while (end < expr.length && expr[end] !== '.' && expr[end] !== '[') end += 1;
741
+ const key = expr.slice(i, end);
742
+ cur = cur[key];
743
+ i = end;
744
+ }
745
+ return cur;
746
+ }
747
+
748
+ function projectMessage(record: any, map: NativeHistoryMessageMap, index: number, total: number, sourceMtimeMs: number): NativeHistoryMessage | null {
749
+ const roleRaw = jsonPathGet(record, map.role);
750
+ const contentRaw = jsonPathGet(record, map.content);
751
+ const role = normalizeRole(roleRaw);
752
+ let content = stringifyContent(contentRaw);
753
+ if (content && map.content_strip) {
754
+ for (const tag of map.content_strip) {
755
+ const safeTag = tag.replace(/[.+^${}()|[\]\\]/g, '\\$&');
756
+ const re = new RegExp(`<${safeTag}\\b[^>]*>[\\s\\S]*?<\\/${safeTag}\\s*>`, 'gi');
757
+ content = content.replace(re, '');
758
+ }
759
+ }
760
+ if (content && map.content_unwrap) {
761
+ for (const tag of map.content_unwrap) {
762
+ const safeTag = tag.replace(/[.+^${}()|[\]\\]/g, '\\$&');
763
+ const open = new RegExp(`<${safeTag}\\b[^>]*>`, 'gi');
764
+ const close = new RegExp(`<\\/${safeTag}\\s*>`, 'gi');
765
+ content = content.replace(open, '').replace(close, '');
766
+ }
767
+ }
768
+ if (content) content = content.trim();
769
+ if (!content) return null;
770
+
771
+ // Records are passed in chronological order (oldest → newest), so the
772
+ // last record's receivedAt should be ~sourceMtimeMs (when the file was
773
+ // last touched) and earlier records should walk backwards. Earlier
774
+ // version had this inverted, which made the dashboard render bubbles
775
+ // in reverse order and produce the "chat jumping" effect.
776
+ let receivedAt = sourceMtimeMs - ((total - 1 - index) * 1000);
777
+ if (map.timestamp_ms) {
778
+ const tsRaw = jsonPathGet(record, map.timestamp_ms);
779
+ const parsed = parseTimestamp(tsRaw);
780
+ if (parsed != null) receivedAt = parsed;
781
+ }
782
+ const kindRaw = map.kind ? jsonPathGet(record, map.kind) : undefined;
783
+ const kind = typeof kindRaw === 'string' && kindRaw ? kindRaw : 'standard';
784
+ return { role, content, receivedAt, kind };
785
+ }
786
+
787
+ /**
788
+ * Coerce a timestamp value to epoch milliseconds. Accepts:
789
+ * - number (ms or seconds — heuristic: < 1e12 means seconds)
790
+ * - ISO 8601 string ("2026-06-05T01:25:28Z")
791
+ * - numeric string
792
+ *
793
+ * Returns null when the value can't be parsed; caller falls back to the
794
+ * monotonic-by-index estimate.
795
+ */
796
+ function parseTimestamp(v: unknown): number | null {
797
+ if (v == null) return null;
798
+ if (typeof v === 'number' && Number.isFinite(v) && v > 0) {
799
+ return v < 1e12 ? Math.floor(v * 1000) : Math.floor(v);
800
+ }
801
+ if (typeof v === 'string' && v) {
802
+ const trimmed = v.trim();
803
+ const asNum = Number(trimmed);
804
+ if (Number.isFinite(asNum) && asNum > 0) {
805
+ return asNum < 1e12 ? Math.floor(asNum * 1000) : Math.floor(asNum);
806
+ }
807
+ const parsed = Date.parse(trimmed);
808
+ if (Number.isFinite(parsed)) return parsed;
809
+ }
810
+ return null;
811
+ }
812
+
813
+ function normalizeRole(r: unknown): 'user' | 'assistant' | 'system' {
814
+ const s = String(r ?? '').toLowerCase();
815
+ if (s === 'user' || s === 'human' || s === 'user_explicit') return 'user';
816
+ if (s === 'assistant' || s === 'ai' || s === 'model') return 'assistant';
817
+ if (s === 'tool' || s === 'tool_result' || s === 'function') return 'assistant';
818
+ return 'system';
819
+ }
820
+
821
+ /**
822
+ * Coerce a content value to a plain string the dashboard can render.
823
+ *
824
+ * Many providers ship structured content (claude messages are arrays of
825
+ * typed blocks: text / tool_use / tool_result). We collapse those to
826
+ * their text-bearing parts so the dashboard doesn't show raw JSON
827
+ * fragments in the transcript. Tool calls/results are intentionally
828
+ * dropped — the daemon's chat schema is for user-visible turns.
829
+ *
830
+ * Order of attempts:
831
+ * 1. string → as-is
832
+ * 2. array of blocks → join the `text` field of each
833
+ * block that has one; if none have
834
+ * a text field, fall through
835
+ * 3. object with a top-level `text` → that string
836
+ * 4. last resort → JSON.stringify
837
+ */
838
+ function stringifyContent(v: unknown): string {
839
+ if (v == null) return '';
840
+ if (typeof v === 'string') return v;
841
+ if (Array.isArray(v)) {
842
+ const parts: string[] = [];
843
+ for (const block of v) {
844
+ if (block == null) continue;
845
+ if (typeof block === 'string') { parts.push(block); continue; }
846
+ if (typeof block === 'object') {
847
+ const t = (block as any).text;
848
+ if (typeof t === 'string' && t) { parts.push(t); continue; }
849
+ // tool_use / tool_result / image / etc — skip from the
850
+ // user-facing transcript. They re-surface via the
851
+ // adapter's tool-event channel if/when that's wired.
852
+ }
853
+ }
854
+ if (parts.length > 0) return parts.join('\n');
855
+ return '';
856
+ }
857
+ if (typeof v === 'object') {
858
+ const t = (v as any).text;
859
+ if (typeof t === 'string') return t;
860
+ }
861
+ try { return JSON.stringify(v); } catch { return String(v); }
862
+ }
863
+
864
+ // ────────────────────────────────────────────────────────────────────────────
865
+ // where-clause mini-language
866
+ //
867
+ // Grammar (intentionally tiny — keep spec readable):
868
+ // expr := term (('&&' | '||') term)*
869
+ // term := path op literal
870
+ // op := '==' | '!=' | '>' | '<' | '>=' | '<='
871
+ // path := jsonpath like '$.foo.bar[0].baz'
872
+ // literal := string ('"…"' or "'…'") | number | true | false | null
873
+ //
874
+ // No grouping, no negation. If you need more, write a real reader file
875
+ // behind `native_history.override_path`.
876
+ // ────────────────────────────────────────────────────────────────────────────
877
+
878
+ interface WhereTerm { path: string; op: string; lit: unknown; negate?: boolean }
879
+
880
+ function compileWhere(src: string): (record: any) => boolean {
881
+ const ors: WhereTerm[][] = [];
882
+ for (const orChunk of src.split('||')) {
883
+ const ands: WhereTerm[] = [];
884
+ for (const andChunk of orChunk.split('&&')) {
885
+ const term = parseTerm(andChunk.trim());
886
+ if (term) ands.push(term);
887
+ }
888
+ if (ands.length > 0) ors.push(ands);
889
+ }
890
+ return (record: any) => ors.some(ands => ands.every(t => evalTerm(t, record)));
891
+ }
892
+
893
+ function parseTerm(src: string): WhereTerm | null {
894
+ let s = src.trim();
895
+ let negate = false;
896
+ if (s.startsWith('!')) { negate = true; s = s.slice(1).trim(); }
897
+ // Function-call form: startsWith($.x, "y") / endsWith($.x, "y") / contains($.x, "y")
898
+ const fnMatch = s.match(/^(startsWith|endsWith|contains)\s*\(\s*(.+?)\s*,\s*(.+?)\s*\)$/);
899
+ if (fnMatch) {
900
+ const [, op, pathExpr, litExpr] = fnMatch;
901
+ return { path: pathExpr, op, lit: parseLiteral(litExpr), negate };
902
+ }
903
+ // Binary comparison: <path> <op> <literal>
904
+ const opMatch = s.match(/^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/);
905
+ if (!opMatch) return null;
906
+ const [, lhs, op, rhsRaw] = opMatch;
907
+ return { path: lhs.trim(), op, lit: parseLiteral(rhsRaw.trim()), negate };
908
+ }
909
+
910
+ function parseLiteral(src: string): unknown {
911
+ if (src === 'true') return true;
912
+ if (src === 'false') return false;
913
+ if (src === 'null') return null;
914
+ if ((src.startsWith('"') && src.endsWith('"')) || (src.startsWith("'") && src.endsWith("'"))) {
915
+ return src.slice(1, -1);
916
+ }
917
+ const n = Number(src);
918
+ if (!Number.isNaN(n)) return n;
919
+ return src; // bareword — treated as string
920
+ }
921
+
922
+ function evalTerm(t: WhereTerm, record: any): boolean {
923
+ const lhs = jsonPathGet(record, t.path);
924
+ const lit = t.lit;
925
+ let result: boolean;
926
+ switch (t.op) {
927
+ case '==': result = lhs === lit; break;
928
+ case '!=': result = lhs !== lit; break;
929
+ case '>': result = Number(lhs) > Number(lit); break;
930
+ case '<': result = Number(lhs) < Number(lit); break;
931
+ case '>=': result = Number(lhs) >= Number(lit); break;
932
+ case '<=': result = Number(lhs) <= Number(lit); break;
933
+ case 'startsWith': result = typeof lhs === 'string' && typeof lit === 'string' && lhs.startsWith(lit); break;
934
+ case 'endsWith': result = typeof lhs === 'string' && typeof lit === 'string' && lhs.endsWith(lit); break;
935
+ case 'contains': result = typeof lhs === 'string' && typeof lit === 'string' && lhs.includes(lit); break;
936
+ default: result = false;
937
+ }
938
+ return t.negate ? !result : result;
939
+ }